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:addrIDs withbfg_make_devid_usb(), and wraps bulk endpoints withusb_open_ep_pair(),usb_read(), andusb_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 resolvedhid_*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 USBdevidto 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 Win32CreateFile, configures 8N1, baud and timeouts from iospeeds.h/iospeeds_posix.h, supports CTS/DTR/RTS GPIO-style access, and passes manufacturer/product/serial metadata throughdetectone_meta_infowhile probing legacy serial drivers. - lowl-pci.c scans
/sys/bus/pci/devices, emitspci:<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 withlowl_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 whenopt_dev_protocolis enabled, and build Bitfury-style SPI command frames withspi_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:
- deviceapi.c
- deviceapi.h
- lowlevel.c
- lowlevel.h
- lowl-*.c
- lowl-*.h
- binloader.c
- binloader.h
- iospeeds.h
- iospeeds_posix.h
- mcp2210.c
- mcp2210.h
- tm_i2c.c
- tm_i2c.h
- usbtest.py
Coupling
- If
struct lowlevel_device_infoor 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 inlowl_dataand rely on backenddevinfo_freehooks; others uselowlevel_devinfo_semicpy()to copy only public fields. - If the
devidformat 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 inbfg_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 throughlowl_usb_attach_kernel_driver()and setbfg_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 andB<baud>constants. - If miner-loop callbacks in deviceapi.h change (
scanhash, async job callbacks, queue callbacks,poll, or disable/enable semantics), verifyminerloop_scanhash(),minerloop_async(), andminerloop_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 intoopen_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). Iflowlevel_scan_free(), thesame_devid_nextgrouping, orbfg_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(), orminerloop_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()orserial_open()changes timeout conversion, serial drivers may block forever (timeout_ms=0means 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()orlowl_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.