Introducing a new way to review your PRs.

Read the announcement

luke-jr / bfgminer

Modular ASIC/FPGA miner written in C, featuring overclocking, monitoring, fan speed control and remote interface capabilities.

View on GitHub

13 documents · Updated Nov 16, 2026

docs / device-model-lowlevel-io

Device Model and Low-Level I/O

Overview

This area is the bridge between miner drivers and physical devices. deviceapi.h exposes the high-level device-driver lifecycle: drivers register themselves with BFG_REGISTER_DRIVER, are initialized and sorted by bfg_devapi_init() in deviceapi.c, then consume common miner loops, work preparation, device-control handoff, processor grouping, and --set-device handling. The miner thread enters the selected driver's thread_init, optional minerloop, and shutdown hooks in deviceapi.c; drivers that do not provide their own loop fall back to minerloop_scanhash, while asynchronous and queue-oriented drivers use minerloop_async or minerloop_queue.

Discovery is split between legacy serial selection and the low-level scan layer. _serial_detect() in deviceapi.c walks the user-supplied scan_devices list, accepts driver:device or dname:device selectors, honors auto/noauto/all, and calls a driver's explicit detector or autoscan callback. Newer hardware paths use lowlevel_scan() in lowlevel.c, which calls each compiled low-level backend (lowl-usb.c, lowl-ftdi.c, lowl-hid.c, mcp2210.c, lowl-mswin.c, lowl-pci.c, and lowl-vcom.c) and returns struct lowlevel_device_info records containing manufacturer/product/serial/path/devid/VID/PID plus backend-specific data. lowlevel_scan() groups records with the same devid under same_devid_next, so a single physical USB device that appears as both raw USB and HID/VCOM can be probed once by higher-level logic.

Backend selection is compile-time gated and data-driven. lowlevel.c includes a backend only when its NEED_BFG_LOWL_*, HAVE_LIBUSB, USE_NANOFURY, USE_VFIO, or USE_UIO symbols are enabled, then detection helpers such as lowlevel_detect(), lowlevel_detect_serial(), and lowlevel_detect_id() filter the cached scan results by product text, serial, low-level driver, VID, and PID. When a driver successfully claims a device, it should call lowlevel_claim() or backend-specific wrappers such as bfg_claim_libusb() in lowl-usb.h, bfg_claim_serial() in lowl-vcom.c, or bfg_claim_any2() in lowlevel.c; the shared claim table prevents two drivers from opening the same devid.

The low-level backends provide both discovery and transport helpers:

  • lowl-usb.c enumerates libusb devices, fetches USB strings when possible, creates stable usb:bus:addr IDs with bfg_make_devid_usb(), and wraps bulk endpoints with usb_open_ep_pair(), usb_read(), and usb_write() so drivers can handle packet boundaries, read buffering, and timeout behavior consistently.
  • lowl-hid.c dynamically loads hidapi variants (libhidapi, libhidapi-hidraw, libhidapi-libusb, or platform equivalents), exposes the resolved hid_* functions through lowl-hid.h, and converts HID enumeration into low-level device records. When using the libusb HID backend, it maps hidapi's path format back to the shared USB devid to avoid duplicate physical probes.
  • lowl-ftdi.c builds FT232R/FT232H low-level records by matching libusb-discovered FTDI VID/PID pairs, then implements FTDI control transfers, MPSSE setup, buffered reads/writes, CBUS helpers, and MPSSE read/write transactions for hardware drivers that speak through FTDI chips.
  • mcp2210.c is another HID-derived low-level driver for Microchip MCP2210 USB-to-SPI bridges. It matches MCP2210 VID/PID through lowl_hid, opens the HID path, preserves current SPI/GPIO configuration blocks, and exposes SPI transfer plus GPIO helpers in mcp2210.h.
  • lowl-vcom.c handles serial/VCOM discovery and I/O. It collects candidate tty/COM paths from Linux sysfs, libudev, /dev/serial/by-id, macOS IOKit, Windows USB/DDK and FTDI APIs, user-specified scan paths, and platform fallback scanners. It opens serial ports with POSIX termios or Win32 CreateFile, configures 8N1, baud and timeouts from iospeeds.h/iospeeds_posix.h, supports CTS/DTR/RTS GPIO-style access, and passes manufacturer/product/serial metadata through detectone_meta_info while probing legacy serial drivers.
  • lowl-pci.c scans /sys/bus/pci/devices, emits pci:<domain:bus:slot.func> IDs, and opens BAR access through VFIO first and UIO second when compiled in. Its public API in lowl-pci.h lets drivers read/write BAR words or byte ranges; byte access is translated through word operations for mmap-backed paths.
  • lowl-mswin.c enumerates Windows SetupAPI interfaces for the Monarch KMDF GUID declared in lowl-mswin.h, records mswin:<DevicePath> devices, and lets drivers verify the GUID with lowl_mswin_match_guid().
  • lowl-spi.c is a direct SPI/GPIO helper rather than a struct lowlevel_driver. It can initialize Raspberry Pi-style GPIO mapping, open Linux spidev devices, perform full-duplex transfers, dump protocol bytes when opt_dev_protocol is enabled, and build Bitfury-style SPI command frames with spi_emit_*() helpers.

Firmware/blob loading is shared through open_bitstream() in deviceapi.c and the parsers in binloader.c. open_bitstream() searches opt_kernel_path, cgminer_path, the current directory, driver-specific subdirectories, and bitstreams/package share directories. open_xilinx_bitstream() validates Xilinx bitstream headers and exposes the payload length, while load_bitstream_bytes() prefers <prefix>.bin, falls back to Intel HEX via load_bitstream_intelhex(), and logs the standard missing-firmware message through _bitstream_not_found().

tm_i2c.c/tm_i2c.h provide a narrow Linux I2C helper for temperature/core-voltage boards on /dev/i2c-1, using I2C_RDWR to send three-byte command/data packets to slots derived from TM_ADDR. usbtest.py is a manual serial/VCOM diagnostic script that opens a pyserial port, sends hex/text or known Icarus test payloads, and prints the reply.

Coverage

Owned globs:

Coupling

  • If struct lowlevel_device_info or its ownership rules change in lowlevel.h, update every backend that allocates or copies it: lowl-usb.c, lowl-hid.c, lowl-ftdi.c, mcp2210.c, lowl-vcom.c, lowl-pci.c, and lowl-mswin.c. Some backends store referenced libusb devices in lowl_data and rely on backend devinfo_free hooks; others use lowlevel_devinfo_semicpy() to copy only public fields.
  • If the devid format changes in lowlevel.c, also update backend claim wrappers and duplicate suppression in lowl-usb.c, lowl-hid.c, lowl-vcom.c, lowl-pci.c, and lowl-mswin.c. The claim table in bfg_claim_any() keys solely on these strings, so inconsistent IDs allow multiple drivers to open the same physical device.
  • If USB/HID enumeration behavior changes, verify VCOM fallback behavior in lowl-vcom.c. Both vcom_lowl_probe_wrapper() and _serial_autodetect_found_cb() try to reattach a kernel driver for raw USB entries through lowl_usb_attach_kernel_driver() and set bfg_need_detect_rescan; removing that handoff can leave serial ports undiscovered after a raw USB probe.
  • If valid baud rates are added or removed in iospeeds.h or iospeeds_posix.h, verify serial_open(), valid_baud(), and generated iospeeds_local.h users in lowl-vcom.c. The termios conversion path uses the same macro list to decide both accepted values and B<baud> constants.
  • If miner-loop callbacks in deviceapi.h change (scanhash, async job callbacks, queue callbacks, poll, or disable/enable semantics), verify minerloop_scanhash(), minerloop_async(), and minerloop_queue() in deviceapi.c. Hardware drivers consume these common loops and may rely on notifier/timer state being updated in the order shown there.
  • If firmware search paths change in open_bitstream() in deviceapi.c, also verify all parsers in binloader.c; they report missing firmware using only the filename they pass into open_bitstream() and assume the search policy is centralized there.

Risks

  • lowlevel.c has a history of duplicate-device and claim-table fixes (lowlevel: Collapse multiple lowlevel drivers on the same devid, Bugfix: lowlevel: Free hash table data when done with it, Bugfix: bfg_claim_any: Use a mutex to avoid races around device claims). If lowlevel_scan_free(), the same_devid_next grouping, or bfg_claim_any() is changed, duplicate probes or use-after-free bugs can let two drivers race the same USB/HID/VCOM device.
  • deviceapi.c miner-loop state transitions have repeated bugfixes around async disable, queued work, and result processing. If minerloop_async(), job_start_abort(), do_get_results(), or minerloop_queue() are changed, devices can be disabled while work pointers still reference old jobs, leading to lost hashes or shutdown hangs.
  • lowl-vcom.c timeout handling has several historical fixes around termios/Win32 timeout units and invalid zero timeouts. If vcom_set_timeout_ms() or serial_open() changes timeout conversion, serial drivers may block forever (timeout_ms=0 means no timeout) or poll too aggressively.
  • lowl-pci.c BAR access is split across VFIO, UIO, mmap, and pread/pwrite fallbacks. If lowl_pci_get_data_from_words() or lowl_pci_set_data_in_words() changes offset/endianness math, byte-oriented hardware registers can be read or written at the wrong byte lane even though word access still appears to work.