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 / opencl-gpu-support

OpenCL GPU Support

Overview

OpenCL mining is implemented as a BFGMiner device driver in driver-opencl.c with per-device state defined in driver-opencl.h, lower-level OpenCL setup/build helpers in ocl.c/ocl.h, kernel source assets in opencl/, and AMD ADL monitoring/control in adl.c/adl.h. The bundled CL/ and ADL/ headers provide the OpenCL and AMD Display Library types used by those host integrations.

GPU support is intentionally opt-in for SHA256d and scrypt ASIC-era mining. README.GPU documents enabling OpenCL with -S opencl:auto, platform selection with --gpu-platform, and per-device settings via --set-device OCL...; README.scrypt documents scrypt-only tuning such as thread-concurrency, lookup-gap, and GPU_MAX_ALLOC_PERCENT. At startup, opencl_early_init() in driver-opencl.c pre-populates the global gpus[MAX_GPUDEVICES] array with struct opencl_device_data, defaulting dynamic intensity on and scrypt lookup gap to 2.

Device discovery begins in opencl_api.drv_detect, which calls opencl_detect() and then opencl_autodetect() in driver-opencl.c. opencl_autodetect() loads OpenCL dynamically (libOpenCL.so, Apple OpenCL framework, or OpenCL.dll) and resolves only the symbols this driver uses. It then calls clDevicesNum() in ocl.c, which enumerates OpenCL platforms, logs vendor/name/version and GPU device names, honors opt_platform_id, chooses the platform with the most devices when none is specified, and returns the maximum GPU count. For each discovered GPU, opencl_autodetect() binds gpus[i] to opencl_api, sets device_id, assigns virtual_gpu, installs probe-time set-device handlers, applies defaults, and registers the device with the core device layer. If ADL is enabled and not suppressed by opt_noadl, it calls init_adl(nDevs) after OpenCL registration.

Thread preparation creates the actual OpenCL runtime state. opencl_thread_prepare() in driver-opencl.c calls opencl_create_clState() in ocl.c using the per-device virtual_gpu. opencl_create_clState() re-enumerates the selected platform, validates the chosen GPU index, creates a GPU context and command queue, records device capabilities (cl_amd_media_ops, preferred vector width, max workgroup size, compute units, max allocation size), clamps vector width for known AMD behavior, detects Mesa-specific binary/bitalign limitations, resolves any deferred intensity string, and creates the shared outputBuffer. Per-thread host result buffers are allocated and the device output buffer is cleared in opencl_thread_init().

Kernel selection is split between metadata in the .cl files and host-side parameter queues. opencl_kernel_source() in ocl.c reads kernel-interface: comments from kernel sources, maps the interface name through select_kernel() in driver-opencl.c, and can map an algorithm alias such as SHA256d or scrypt. driver-opencl.c defines one host queue function per supported kernel ABI: queue_poclbm_kernel, queue_phatk_kernel, queue_diakgcn_kernel, queue_diablo_kernel, queue_fullheader_kernel, and queue_scrypt_kernel, then registers them in kernel_interfaces[]. The bundled kernels include SHA256d variants such as opencl/diablo.cl, opencl/phatk.cl, opencl/poclbm.cl, opencl/diakgcn.cl, opencl/keccak.cl, and opencl/scrypt.cl/opencl/zuikkis.cl/opencl/psw.cl for scrypt-style workloads. Each kernel must expose a search kernel because opencl_load_kernel() creates that kernel object by name.

Kernel build and cache management happen in opencl_load_kernel() in ocl.c, called lazily by opencl_scanhash_get_kernel() in driver-opencl.c the first time a work item for a mining algorithm reaches a GPU. If no explicit kernelinfo->file was set through --set-device OCL:kernel=..., the mining algorithm supplies a default kernel filename. opencl_load_kernel() reads <kernel>.cl, hashes the source into the binary cache filename, evaluates GOFFSET support by inspecting source markers and optionally running opencl_test_goffset(), chooses work size from device settings, scrypt defaults, Tahiti special-casing, or max workgroup size, and for scrypt computes thread_concurrency from max_alloc unless the user supplied it. It builds compiler options from work size, vector width, scrypt lookup-gap/thread-concurrency, BITALIGN, BFI_INT, and GOFFSET; it can load/save compiled .bin files depending on opt_opencl_binaries. Older AMD devices may require binary opcode patching for BFI_INT: opencl_should_patch_bfi_int(), opencl_get_kernel_binary(), opencl_patch_kernel_binary(), and opencl_replace_binary_kernel() implement that path.

The GPU work loop connects directly to the core work/algorithm path through the opencl_api device driver table in driver-opencl.c. For SHA256d builds, opencl_prepare_work() precomputes midstate-derived fields into struct opencl_work_data attached to work->device_data; the specific SHA256d queue function then pushes those fields as OpenCL kernel arguments. For scrypt, queue_scrypt_kernel() writes the 80-byte block header to CLbuffer0, passes the midstate words, target, output buffer, and scrypt scratch buffer (padbuffer8). opencl_scanhash() chooses the correct kernel for work_mining_algorithm(work), converts static or dynamic intensity into oclthreads, queues kernel parameters, enqueues the NDRange with either a global work offset or an explicit base nonce argument, reads the output buffer, advances work->blk.nonce by the device's maximum observed hashes to avoid repeats during dynamic intensity changes, and calls postcalc_hash_async() when the kernel reports candidate nonces.

ADL support is compiled under HAVE_ADL and isolated in adl.c. prepare_adl() dynamically loads AMD's ADL library (libatiadlxx.so, atiadlxx.dll, or atiadlxy.dll), resolves the Overdrive5 functions declared in adl_functions.h, creates ADL control, and refreshes adapter state. init_adl() enumerates ADL adapters, deduplicates logical entries by adapter ID, compares ADL and OpenCL device counts, applies manual OpenCL-to-ADL mapping from set_gpu_map()/adl_mapping, optionally reorders by bus number when opt_reorder is set, then attaches ADL state to each struct opencl_device_data. It records adapter indices, bus numbers, default performance levels, fan defaults, OD ranges, current clocks/voltage, power tune, and twin-GPU fan relationships.

Runtime monitoring and controls bridge ADL back into the OpenCL driver. gpu_stats(), gpu_temp(), gpu_fanspeed(), gpu_fanpercent(), gpu_activity(), gpu_engineclock(), gpu_memclock(), gpu_vddc(), and gpu_powertune() in adl.c are used by opencl_get_stats(), curses status rendering, API extra device status, and debug watchdog logging in driver-opencl.c. Set-device handlers in driver-opencl.c parse clock, fan, memclock, memdiff, powertune, voltage, and temp_overheat, while runtime setters call set_engineclock(), set_fanspeed(), set_memoryclock(), and set_vddc() in adl.c. gpu_autotune() implements --auto-fan and --auto-gpu: it compares ADL temperature and fan percent against target/overheat/cutoff thresholds, changes fan percent first when possible, then adjusts engine clock within recorded min/max bounds. clear_adl() restores managed performance levels and fan defaults on shutdown.

Coverage

Coupling

  • If a kernel in opencl/*.cl changes its kernel-interface: tag, algorithm alias, kernel function name, GOFFSET convention, or argument order, also update the matching queue function and kernel_interfaces[] in driver-opencl.c; opencl_load_kernel() only discovers the interface string and always creates a kernel named search, while argument binding is positional host code.
  • If mining algorithm metadata changes its OpenCL intensity conversions, min/max thread counts, min nonce diff, or default kernel selection, verify opencl_calc_intensity_range(), opencl_set_intensity_from_str(), opencl_scanhash_get_kernel(), and opencl_scanhash() in driver-opencl.c; these functions rely on algorithm callbacks to convert user intensity into nonces per kernel launch.
  • If scrypt memory sizing or kernel compile definitions change in opencl/scrypt.cl, opencl/zuikkis.cl, or opencl/psw.cl, verify queue_scrypt_kernel() in driver-opencl.c and the KL_SCRYPT branch of opencl_load_kernel() in ocl.c; the host allocates padbuffer8, chooses thread_concurrency, and passes LOOKUP_GAP, CONCURRENT_THREADS, and WORKSIZE as compile-time defines.
  • If OpenCL binary cache naming or compiler options change in ocl.c, make sure cache keys still include every option that changes generated code; opencl_load_kernel() reuses .bin files based on source hash, device name, goffset, vectors or scrypt lookup/thread-concurrency, work size, sizeof(long), and platform version.
  • If OpenCL/ADL device ordering or mapping behavior changes in driver-opencl.c or adl.c, update README.GPU examples for --gpu-map; ADL cannot identify the matching OpenCL device directly, so monitoring/control correctness depends on the assumed or manually configured mapping.
  • If ADL Overdrive calls or struct definitions change in ADL/** or adl_functions.h, verify every resolved symbol in prepare_adl() and the lock-protected getters/setters in adl.c; missing one required function disables ADL entirely.

Risks

  • ocl.c writes OpenCL binary cache files directly in opencl_save_kernel_binary() and notes that a failed write can leave a bad file. If the process or filesystem fails while saving a .bin, later runs may load a corrupt binary through opencl_load_kernel_binary() and fail or mine incorrectly until the cache is deleted.
  • adl.c maps ADL devices to OpenCL devices mostly by enumeration order, with manual overrides from set_gpu_map() in driver-opencl.c. If OpenCL and ADL enumerate differently, ADL monitoring/control can be applied to the wrong physical GPU, causing misleading temperatures or unsafe clock/fan changes.
  • opencl_patch_kernel_binary() in ocl.c patches AMD binary opcodes by scanning ELF/text markers and fixed offsets for older BFI_INT-capable devices. If AMD binary layout changes but still passes the coarse version/device checks in opencl_should_patch_bfi_int(), patched kernels may be invalid or silently lose the intended optimization.
  • reinit_gpu() in driver-opencl.c intentionally leaks/abandons queues and CL state around hung GPU recovery because the dying thread may still dereference them. If GPU recovery paths are changed to eagerly free those objects, a hard-hung driver can turn a single-device failure into process-wide memory corruption or crashes.