forked from Dirbaio/gominer
-
Notifications
You must be signed in to change notification settings - Fork 80
/
cldevice.go
806 lines (684 loc) · 21.8 KB
/
cldevice.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// Copyright (c) 2016-2023 The Decred developers.
//go:build opencl && !cuda && !opencladl
// +build opencl,!cuda,!opencladl
package main
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"math"
"os"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/decred/gominer/cl"
"github.com/decred/gominer/util"
"github.com/decred/gominer/work"
)
// Return the GPU library in use.
func gpuLib() string {
return "OpenCL"
}
const (
outputBufferSize = cl.CL_size_t(64)
localWorksize = 64
uint32Size = cl.CL_size_t(unsafe.Sizeof(cl.CL_uint(0)))
)
var zeroSlice = []cl.CL_uint{cl.CL_uint(0)}
func appendBitfield(info, value cl.CL_bitfield, name string, str *string) {
if (info & value) != 0 {
*str += name
}
}
func amdgpuFanPercentToValue(percent uint32) uint32 {
value := AMDGPUFanFailSafe
calculatedValue := float64(AMDGPUFanMax) * float64(percent) / float64(100)
if calculatedValue > 0 {
value = uint32(calculatedValue)
} else {
minrLog.Errorf("amdgpuFanPercentToValue() failed; using failsafe "+
"value of %v", AMDGPUFanFailSafe)
}
return value
}
// validate that we can write to the AMDGPU sysfs fan path.
func amdgpuFanPermissionsValid(index int) error {
path := amdgpuGetSysfsPath(index, "fan")
file, err := os.OpenFile(path, os.O_WRONLY, 0666)
file.Close()
if err != nil {
if os.IsPermission(err) {
return fmt.Errorf("path %v is not writable", path)
} else {
return fmt.Errorf("path %v unusable %w", path, err)
}
}
return nil
}
func amdgpuGetSysfsPath(index int, field string) string {
cardPath := fmt.Sprintf("%s%d", "/sys/class/drm/card", index)
driverPath := "/sys/module/amdgpu"
if field == "card" {
return cardPath
}
if field == "driver" {
return driverPath
}
// find hwmon/hwmon<number>
hwmonBasePath := fmt.Sprintf("%s%d%s", "/sys/class/drm/card", index, "/device/hwmon/")
hwmonName := ""
// open hwmon base path and scan for the numbered entry
files, err := os.ReadDir(hwmonBasePath)
if err != nil {
minrLog.Errorf("unable to read AMDGPU sysfs dir %v: %v", hwmonBasePath,
err)
return "unknown"
}
for _, f := range files {
// we should only find one entry but the API may not be stable
if strings.Contains(f.Name(), "hwmon") {
hwmonName = f.Name()
}
}
if hwmonName == "" {
minrLog.Errorf("unable to find full hwmon path")
return "unknown"
}
hwmonFullPath := fmt.Sprintf("%s/%s/", hwmonBasePath, hwmonName)
switch field {
case "fan":
return hwmonFullPath + "pwm1"
case "temp":
return hwmonFullPath + "temp1_input"
}
return "unknown"
}
func fanControlSet(index int, fanCur uint32, tempTargetType string,
fanChangeLevel string) {
fanAdjustmentPercent := FanControlAdjustmentSmall
fanNewPercent := uint32(0)
fanNewValue := uint32(0)
if fanChangeLevel == ChangeLevelLarge {
fanAdjustmentPercent = FanControlAdjustmentLarge
}
minrLog.Tracef("DEV #%d fanControlSet fanCur %v tempTargetType %v "+
"fanChangeLevel %v", index, fanCur, tempTargetType, fanChangeLevel)
switch tempTargetType {
// Decrease the temperature by increasing the fan speed
case TargetLower:
fanNewPercent = fanCur + fanAdjustmentPercent
fanNewValue = amdgpuFanPercentToValue(fanNewPercent)
// Increase the temperature by decreasing the fan speed
case TargetHigher:
fanNewPercent = fanCur - fanAdjustmentPercent
fanNewValue = amdgpuFanPercentToValue(fanNewPercent)
}
fanPath := amdgpuGetSysfsPath(index, "fan")
minrLog.Tracef("DEV #%d need to %v temperature; adjusting fan from "+
"fanCur %v%% to fanNewPercent %v%% by writing fanNewValue %v to %v",
index, strings.ToLower(tempTargetType), fanCur, fanNewPercent,
fanNewValue, fanPath)
err := deviceStatsWriteSysfsEntry(fanPath, fanNewValue)
if err != nil {
minrLog.Errorf("DEV #%d unable to adjust fan: %v", index, err)
} else {
minrLog.Infof("DEV #%d successfully adjusted fan from %v%% to %v%% to "+
"%v temp", index, fanCur, fanNewPercent,
strings.ToLower(tempTargetType))
}
}
func loadProgramSource(filename string) ([][]byte, []cl.CL_size_t, error) {
var programBuffer [1][]byte
var programSize [1]cl.CL_size_t
// Read each program file and place content into buffer array.
programHandle, err := os.Open(filename)
if err != nil {
return nil, nil, err
}
defer programHandle.Close()
buf := bytes.NewBuffer(nil)
_, err = io.Copy(buf, programHandle)
if err != nil {
return nil, nil, err
}
str := buf.String()
programFinal := []byte(str)
programSize[0] = cl.CL_size_t(len(programFinal))
programBuffer[0] = make([]byte, programSize[0])
copy(programBuffer[0], programFinal)
return programBuffer[:], programSize[:], nil
}
func clError(status cl.CL_int, f string) error {
if -status < 0 || int(-status) > len(cl.ERROR_CODES_STRINGS) {
return fmt.Errorf("returned unknown error")
}
return fmt.Errorf("%s returned error %s (%d)", f,
cl.ERROR_CODES_STRINGS[-status], status)
}
type Device struct {
// The following variables must only be used atomically.
fanPercent uint32
temperature uint32
sync.Mutex
index int
// Items for OpenCL device
platformID cl.CL_platform_id
deviceID cl.CL_device_id
deviceName string
deviceType string
context cl.CL_context
queue cl.CL_command_queue
outputBuffer cl.CL_mem
program cl.CL_program
kernel cl.CL_kernel
fanControlActive bool
fanControlLastTemp uint32
fanControlLastFanPercent uint32
fanTempActive bool
kind string
tempTarget uint32
workSize uint32
// extraNonce is an additional nonce that is used to separate groups of
// devices into exclusive ranges to ensure multiple groups do not duplicate
// work.
//
// For solo mining, it is unique per device.
//
// For pool mining, it is assigned by the pool on a per-connection basis and
// therefore is only unique per client. Note that this means it will be the
// same for all devices with pool mining.
extraNonce uint32
// extraNonce2 is a per device additional nonce where the first byte is the
// device ID (offset by a per-process random value) and the last 3 bytes are
// dedicated to the search space. Note that this means up to 256 devices
// are supported without the possibility of duplicate work.
//
// Since the first byte is unique per device, it does not change during
// operation which implies this value will rollover to 0x??000000 from
// 0x??ffffff.
extraNonce2 uint32
midstate [8]uint32
lastBlock [16]uint32
work work.Work
newWork chan *work.Work
workDone chan []byte
hasWork bool
started uint32
allDiffOneShares uint64
validShares uint64
invalidShares uint64
}
// If the device order and OpenCL index are ever not the same then we can
// implement topology finding code:
// https://github.com/Oblomov/clinfo/blob/master/src/clinfo.c#L1061-L1126
func determineDeviceKind(index int, deviceType string) string {
deviceKind := DeviceKindUnknown
if deviceType == DeviceTypeCPU {
return deviceKind
}
switch runtime.GOOS {
case "linux":
// check if the AMDGPU driver is loaded
if _, err := os.Stat(amdgpuGetSysfsPath(index, "driver")); err == nil {
// make sure a sysfs entry exists for the index of this device
if _, err := os.Stat(amdgpuGetSysfsPath(index, "card")); err == nil {
deviceKind = DeviceKindAMDGPU
}
}
}
return deviceKind
}
func deviceStats(index int) (uint32, uint32) {
fanPercent := deviceStatsReadSysfsEntry(amdgpuGetSysfsPath(index, "fan"))
fanPercentFloat := float64(fanPercent) / float64(AMDGPUFanMax) * float64(100)
fanPercent = uint32(fanPercentFloat)
temperature := deviceStatsReadSysfsEntry(amdgpuGetSysfsPath(index, "temp")) / AMDTempDivisor
return fanPercent, temperature
}
func deviceStatsReadSysfsEntry(path string) uint32 {
res := uint32(0)
dataRaw := ""
f, err := os.Open(path)
if err != nil {
if err != nil {
minrLog.Errorf("unable to open %v", path)
return res
}
}
defer f.Close()
r := bufio.NewScanner(f)
for r.Scan() {
dataRaw = string(r.Bytes())
}
if err := r.Err(); err != nil {
return res
}
dataInt, err := strconv.Atoi(dataRaw)
if err != nil {
minrLog.Errorf("unable to convert to int %v", err)
return res
}
res = uint32(dataInt)
return res
}
func deviceStatsWriteSysfsEntry(path string, value uint32) error {
stringValue := strconv.Itoa(int(value)) + "\n"
err := os.WriteFile(path, []byte(stringValue), 0644)
if err != nil {
return fmt.Errorf("unable to write %v to %v: %w", value, path, err)
}
return nil
}
func getCLPlatforms() ([]cl.CL_platform_id, error) {
var numPlatforms cl.CL_uint
status := cl.CLGetPlatformIDs(0, nil, &numPlatforms)
if status != cl.CL_SUCCESS {
return nil, clError(status, "CLGetPlatformIDs")
}
platforms := make([]cl.CL_platform_id, numPlatforms)
status = cl.CLGetPlatformIDs(numPlatforms, platforms, nil)
if status != cl.CL_SUCCESS {
return nil, clError(status, "CLGetPlatformIDs")
}
return platforms, nil
}
// getCLDevices returns the list of devices for the given platform.
func getCLDevices(platform cl.CL_platform_id) ([]cl.CL_device_id, error) {
var numDevices cl.CL_uint
status := cl.CLGetDeviceIDs(platform, cl.CL_DEVICE_TYPE_ALL, 0, nil,
&numDevices)
if status != cl.CL_SUCCESS && status != cl.CL_DEVICE_NOT_FOUND {
return nil, clError(status, "CLGetDeviceIDs")
}
if numDevices == 0 {
return nil, nil
}
devices := make([]cl.CL_device_id, numDevices)
status = cl.CLGetDeviceIDs(platform, cl.CL_DEVICE_TYPE_ALL, numDevices,
devices, nil)
if status != cl.CL_SUCCESS {
return nil, clError(status, "CLGetDeviceIDs")
}
return devices, nil
}
// ListDevices prints a list of devices present.
func ListDevices() {
platformIDs, err := getCLPlatforms()
if err != nil {
fmt.Fprintf(os.Stderr, "Could not get CL platforms: %v\n", err)
os.Exit(1)
}
deviceListIndex := 0
for i := range platformIDs {
platformID := platformIDs[i]
deviceIDs, err := getCLDevices(platformID)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not get CL devices for platform: %v\n", err)
os.Exit(1)
}
for _, deviceID := range deviceIDs {
fmt.Printf("DEV #%d: %s\n", deviceListIndex, getDeviceInfo(deviceID, cl.CL_DEVICE_NAME, "CL_DEVICE_NAME"))
deviceListIndex++
}
}
}
func NewDevice(index int, order int, platformID cl.CL_platform_id, deviceID cl.CL_device_id,
workDone chan []byte) (*Device, error) {
d := &Device{
index: index,
platformID: platformID,
deviceID: deviceID,
deviceName: getDeviceInfo(deviceID, cl.CL_DEVICE_NAME, "CL_DEVICE_NAME"),
deviceType: getDeviceInfo(deviceID, cl.CL_DEVICE_TYPE, "CL_DEVICE_TYPE"),
newWork: make(chan *work.Work, 5),
workDone: workDone,
fanPercent: 0,
temperature: 0,
tempTarget: 0,
}
var status cl.CL_int
// Create the CL context.
d.context = cl.CLCreateContext(nil, 1, []cl.CL_device_id{deviceID},
nil, nil, &status)
if status != cl.CL_SUCCESS {
return nil, clError(status, "CLCreateContext")
}
// Create the command queue.
d.queue = cl.CLCreateCommandQueue(d.context, deviceID, 0, &status)
if status != cl.CL_SUCCESS {
return nil, clError(status, "CLCreateCommandQueue")
}
// Create the output buffer.
d.outputBuffer = cl.CLCreateBuffer(d.context, cl.CL_MEM_READ_WRITE,
uint32Size*outputBufferSize, nil, &status)
if status != cl.CL_SUCCESS {
return nil, clError(status, "CLCreateBuffer")
}
// Load kernel source.
progSrc, progSize, err := loadProgramSource(cfg.ClKernel)
if err != nil {
return nil, fmt.Errorf("could not load kernel source: %w", err)
}
// Create the program.
d.program = cl.CLCreateProgramWithSource(d.context, 1, progSrc,
progSize[:], &status)
if status != cl.CL_SUCCESS {
return nil, clError(status, "CLCreateProgramWithSource")
}
// Build the program for the device.
compilerOptions := ""
compilerOptions += fmt.Sprintf(" -D WORKSIZE=%d", localWorksize)
status = cl.CLBuildProgram(d.program, 1, []cl.CL_device_id{deviceID},
[]byte(compilerOptions), nil, nil)
if status != cl.CL_SUCCESS {
err = clError(status, "CLBuildProgram")
// Something went wrong! Print what it is.
var logSize cl.CL_size_t
status = cl.CLGetProgramBuildInfo(d.program, deviceID,
cl.CL_PROGRAM_BUILD_LOG, 0, nil, &logSize)
if status != cl.CL_SUCCESS {
minrLog.Errorf("Could not obtain compilation error log: %v",
clError(status, "CLGetProgramBuildInfo"))
}
var programLog interface{}
status = cl.CLGetProgramBuildInfo(d.program, deviceID,
cl.CL_PROGRAM_BUILD_LOG, logSize, &programLog, nil)
if status != cl.CL_SUCCESS {
minrLog.Errorf("Could not obtain compilation error log: %v",
clError(status, "CLGetProgramBuildInfo"))
}
minrLog.Errorf("%s\n", programLog)
return nil, err
}
// Create the kernel.
d.kernel = cl.CLCreateKernel(d.program, []byte("search"), &status)
if status != cl.CL_SUCCESS {
return nil, clError(status, "CLCreateKernel")
}
d.started = uint32(time.Now().Unix())
// Autocalibrate the desired work size for the kernel, or use one of the
// values passed explicitly by the use.
// The intensity or worksize must be set by the user.
userSetWorkSize := false
if len(cfg.IntensityInts) > 0 || len(cfg.WorkSizeInts) > 0 {
userSetWorkSize = true
}
var globalWorkSize uint32
if !userSetWorkSize {
// Apply the first setting as a global setting
calibrateTime := cfg.AutocalibrateInts[0]
// Override with the per-device setting if it exists
for i := range cfg.AutocalibrateInts {
if i == order {
calibrateTime = cfg.AutocalibrateInts[i]
}
}
idealWorkSize, err := d.calcWorkSizeForMilliseconds(calibrateTime)
if err != nil {
return nil, err
}
minrLog.Debugf("Autocalibration successful, work size for %v"+
"ms per kernel execution on device %v determined to be %v",
calibrateTime, d.index, idealWorkSize)
globalWorkSize = idealWorkSize
} else {
if len(cfg.IntensityInts) > 0 {
// Apply the first setting as a global setting
globalWorkSize = 1 << uint32(cfg.IntensityInts[0])
// Override with the per-device setting if it exists
for i := range cfg.IntensityInts {
if i == order {
globalWorkSize = 1 << uint32(cfg.IntensityInts[order])
}
}
}
if len(cfg.WorkSizeInts) > 0 {
// Apply the first setting as a global setting
globalWorkSize = cfg.WorkSizeInts[0]
// Override with the per-device setting if it exists
for i := range cfg.WorkSizeInts {
if i == order {
globalWorkSize = cfg.WorkSizeInts[order]
}
}
}
}
intensity := math.Log2(float64(globalWorkSize))
minrLog.Infof("DEV #%d: Work size set to %v ('intensity' %v)",
d.index, globalWorkSize, intensity)
d.workSize = globalWorkSize
// Determine the device/driver kind
d.kind = determineDeviceKind(d.index, d.deviceType)
switch d.kind {
case DeviceKindAMDGPU:
fanPercent, temperature := deviceStats(d.index)
// Newer cards will idle with the fan off so just check if we got
// a good temperature reading
if temperature != 0 {
atomic.StoreUint32(&d.fanPercent, fanPercent)
atomic.StoreUint32(&d.temperature, temperature)
d.fanTempActive = true
}
}
// Check if temperature target is specified
if len(cfg.TempTargetInts) > 0 {
// Apply the first setting as a global setting
d.tempTarget = cfg.TempTargetInts[0]
// Override with the per-device setting if it exists
for i := range cfg.TempTargetInts {
if i == order {
d.tempTarget = cfg.TempTargetInts[order]
}
}
d.fanControlActive = true
}
// validate that we can actually do fan control
fanControlNotWorking := false
if d.tempTarget > 0 {
// validate that fan control is supported
if !d.fanControlSupported(d.kind) {
return nil, fmt.Errorf("temperature target of %v for device #%v; "+
"fan control is not supported on device kind %v", d.tempTarget,
index, d.kind)
}
if !d.fanTempActive {
minrLog.Errorf("DEV #%d ignoring temperature target of %v; "+
"could not get initial %v read", index, d.tempTarget, d.kind)
fanControlNotWorking = true
}
if !fanControlNotWorking {
err := amdgpuFanPermissionsValid(index)
if err != nil {
minrLog.Errorf("DEV #%d ignoring temperature target of %v; "+
"%v", index, d.tempTarget, err)
fanControlNotWorking = true
}
}
if fanControlNotWorking {
d.tempTarget = 0
d.fanControlActive = false
}
}
return d, nil
}
func (d *Device) runDevice(ctx context.Context) error {
minrLog.Infof("Started DEV #%d: %s", d.index, d.deviceName)
outputData := make([]uint32, outputBufferSize)
// Initialize the nonces for the device such that each device in the same
// system is doing different work while also helping prevent collisions
// across multiple processes and systems working on the same template.
if err := d.initNonces(); err != nil {
return err
}
var status cl.CL_int
ctxDoneCh := ctx.Done()
for {
d.updateCurrentWork(ctx)
select {
case <-ctxDoneCh:
return nil
default:
}
// Increment second extra nonce while respecting the device id.
util.RolloverExtraNonce(&d.extraNonce2)
d.lastBlock[work.Nonce2Word] = d.extraNonce2
// Update the timestamp.
diffSeconds := uint32(time.Now().Unix()) - d.work.TimeReceived
ts := d.work.JobTime + diffSeconds
d.lastBlock[work.TimestampWord] = ts
// arg 0: pointer to the buffer
obuf := d.outputBuffer
status = cl.CLSetKernelArg(d.kernel, 0,
cl.CL_size_t(unsafe.Sizeof(obuf)),
unsafe.Pointer(&obuf))
if status != cl.CL_SUCCESS {
return clError(status, "CLSetKernelArg")
}
// args 1..8: midstate
for i := 0; i < 8; i++ {
ms := d.midstate[i]
status = cl.CLSetKernelArg(d.kernel, cl.CL_uint(i+1),
uint32Size, unsafe.Pointer(&ms))
if status != cl.CL_SUCCESS {
return clError(status, "CLSetKernelArg")
}
}
// args 9..20: lastBlock except nonce
i2 := 0
for i := 0; i < 12; i++ {
if i2 == work.Nonce0Word {
i2++
}
lb := d.lastBlock[i2]
status = cl.CLSetKernelArg(d.kernel, cl.CL_uint(i+9),
uint32Size, unsafe.Pointer(&lb))
if status != cl.CL_SUCCESS {
return clError(status, "CLSetKernelArg")
}
i2++
}
// Clear the found count from the buffer
status = cl.CLEnqueueWriteBuffer(d.queue, d.outputBuffer,
cl.CL_FALSE, 0, uint32Size, unsafe.Pointer(&zeroSlice[0]),
0, nil, nil)
if status != cl.CL_SUCCESS {
return clError(status, "CLEnqueueWriteBuffer")
}
// Execute the kernel and follow its execution time.
currentTime := time.Now()
var globalWorkSize [1]cl.CL_size_t
globalWorkSize[0] = cl.CL_size_t(d.workSize)
var localWorkSize [1]cl.CL_size_t
localWorkSize[0] = localWorksize
status = cl.CLEnqueueNDRangeKernel(d.queue, d.kernel, 1, nil,
globalWorkSize[:], localWorkSize[:], 0, nil, nil)
if status != cl.CL_SUCCESS {
return clError(status, "CLEnqueueNDRangeKernel")
}
// Read the output buffer.
cl.CLEnqueueReadBuffer(d.queue, d.outputBuffer, cl.CL_TRUE, 0,
uint32Size*outputBufferSize, unsafe.Pointer(&outputData[0]), 0,
nil, nil)
if status != cl.CL_SUCCESS {
return clError(status, "CLEnqueueReadBuffer")
}
for i := uint32(0); i < outputData[0]; i++ {
minrLog.Debugf("DEV #%d: Found candidate %v nonce %08x, "+
"extraNonce %08x, extraNonce2 %08x, timestamp %08x",
d.index, i+1, outputData[i+1], d.lastBlock[work.Nonce1Word],
d.lastBlock[work.Nonce2Word], d.lastBlock[work.TimestampWord])
// Assess the work. If it's below target, it'll be rejected
// here. The mining algorithm currently sends this function any
// difficulty 1 shares.
d.foundCandidate(d.lastBlock[work.TimestampWord], outputData[i+1],
d.lastBlock[work.Nonce1Word], d.lastBlock[work.Nonce2Word])
}
elapsedTime := time.Since(currentTime)
minrLog.Tracef("DEV #%d: Kernel execution to read time: %v", d.index,
elapsedTime)
}
}
func newMinerDevs(workDone chan []byte) ([]*Device, error) {
deviceListIndex := 0
deviceListEnabledCount := 0
platformIDs, err := getCLPlatforms()
if err != nil {
return nil, fmt.Errorf("could not get CL platforms: %w", err)
}
var devices []*Device
for p := range platformIDs {
platformID := platformIDs[p]
CLdeviceIDs, err := getCLDevices(platformID)
if err != nil {
return nil, fmt.Errorf("could not get CL devices for platform: %w", err)
}
for _, CLdeviceID := range CLdeviceIDs {
miningAllowed := false
// Enforce device restrictions if they exist
if len(cfg.DeviceIDs) > 0 {
for _, i := range cfg.DeviceIDs {
if deviceListIndex == i {
miningAllowed = true
}
}
} else {
miningAllowed = true
}
if miningAllowed {
newDevice, err := NewDevice(deviceListIndex, deviceListEnabledCount, platformID, CLdeviceID, workDone)
if err != nil {
return nil, err
}
devices = append(devices, newDevice)
deviceListEnabledCount++
}
deviceListIndex++
}
}
return devices, nil
}
func getDeviceInfo(id cl.CL_device_id,
name cl.CL_device_info,
str string) string {
var errNum cl.CL_int
var paramValueSize cl.CL_size_t
errNum = cl.CLGetDeviceInfo(id, name, 0, nil, ¶mValueSize)
if errNum != cl.CL_SUCCESS {
return fmt.Sprintf("Failed to find OpenCL device info %s.\n", str)
}
var info interface{}
errNum = cl.CLGetDeviceInfo(id, name, paramValueSize, &info, nil)
if errNum != cl.CL_SUCCESS {
return fmt.Sprintf("Failed to find OpenCL device info %s.\n", str)
}
switch name {
case cl.CL_DEVICE_TYPE:
var deviceTypeStr string
appendBitfield(cl.CL_bitfield(info.(cl.CL_device_type)),
cl.CL_bitfield(cl.CL_DEVICE_TYPE_CPU),
DeviceTypeCPU,
&deviceTypeStr)
appendBitfield(cl.CL_bitfield(info.(cl.CL_device_type)),
cl.CL_bitfield(cl.CL_DEVICE_TYPE_GPU),
DeviceTypeGPU,
&deviceTypeStr)
info = deviceTypeStr
}
strinfo := fmt.Sprintf("%v", info)
return strinfo
}
func (d *Device) Release() {
cl.CLReleaseKernel(d.kernel)
cl.CLReleaseProgram(d.program)
cl.CLReleaseCommandQueue(d.queue)
cl.CLReleaseMemObject(d.outputBuffer)
cl.CLReleaseContext(d.context)
// XXX need to check if/how the AMDGPU driver/device takes back
// automatic fan control like we do for ADL
}