-
Notifications
You must be signed in to change notification settings - Fork 34
/
oclengine.c
1573 lines (1322 loc) · 38 KB
/
oclengine.c
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* OCLExplorer bitcoin addresses brute-force tool
* Copyright (C) 2017 Stanislav V. Tretyakov <[email protected]>
*
*/
#include "oclexplorer.h"
static uint32_t * BTREE_HEAP;
static uint32_t BTREE_HEAP_SIZE;
/***********************************************************************
* OpenCL debugging and support
***********************************************************************/
const char *
ocl_strerror(cl_int ret){
#define OCL_STATUS(st) case st: return #st;
switch (ret) {
OCL_STATUS(CL_SUCCESS);
OCL_STATUS(CL_DEVICE_NOT_FOUND);
OCL_STATUS(CL_DEVICE_NOT_AVAILABLE);
OCL_STATUS(CL_COMPILER_NOT_AVAILABLE);
OCL_STATUS(CL_MEM_OBJECT_ALLOCATION_FAILURE);
OCL_STATUS(CL_OUT_OF_RESOURCES);
OCL_STATUS(CL_OUT_OF_HOST_MEMORY);
OCL_STATUS(CL_PROFILING_INFO_NOT_AVAILABLE);
OCL_STATUS(CL_MEM_COPY_OVERLAP);
OCL_STATUS(CL_IMAGE_FORMAT_MISMATCH);
OCL_STATUS(CL_IMAGE_FORMAT_NOT_SUPPORTED);
OCL_STATUS(CL_BUILD_PROGRAM_FAILURE);
OCL_STATUS(CL_MAP_FAILURE);
#if defined(CL_MISALIGNED_SUB_BUFFER_OFFSET)
OCL_STATUS(CL_MISALIGNED_SUB_BUFFER_OFFSET);
#endif /* defined(CL_MISALIGNED_SUB_BUFFER_OFFSET) */
#if defined(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST)
OCL_STATUS(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST);
#endif /* defined(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST) */
OCL_STATUS(CL_INVALID_VALUE);
OCL_STATUS(CL_INVALID_DEVICE_TYPE);
OCL_STATUS(CL_INVALID_PLATFORM);
OCL_STATUS(CL_INVALID_DEVICE);
OCL_STATUS(CL_INVALID_CONTEXT);
OCL_STATUS(CL_INVALID_QUEUE_PROPERTIES);
OCL_STATUS(CL_INVALID_COMMAND_QUEUE);
OCL_STATUS(CL_INVALID_HOST_PTR);
OCL_STATUS(CL_INVALID_MEM_OBJECT);
OCL_STATUS(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR);
OCL_STATUS(CL_INVALID_IMAGE_SIZE);
OCL_STATUS(CL_INVALID_SAMPLER);
OCL_STATUS(CL_INVALID_BINARY);
OCL_STATUS(CL_INVALID_BUILD_OPTIONS);
OCL_STATUS(CL_INVALID_PROGRAM);
OCL_STATUS(CL_INVALID_PROGRAM_EXECUTABLE);
OCL_STATUS(CL_INVALID_KERNEL_NAME);
OCL_STATUS(CL_INVALID_KERNEL_DEFINITION);
OCL_STATUS(CL_INVALID_KERNEL);
OCL_STATUS(CL_INVALID_ARG_INDEX);
OCL_STATUS(CL_INVALID_ARG_VALUE);
OCL_STATUS(CL_INVALID_ARG_SIZE);
OCL_STATUS(CL_INVALID_KERNEL_ARGS);
OCL_STATUS(CL_INVALID_WORK_DIMENSION);
OCL_STATUS(CL_INVALID_WORK_GROUP_SIZE);
OCL_STATUS(CL_INVALID_WORK_ITEM_SIZE);
OCL_STATUS(CL_INVALID_GLOBAL_OFFSET);
OCL_STATUS(CL_INVALID_EVENT_WAIT_LIST);
OCL_STATUS(CL_INVALID_EVENT);
OCL_STATUS(CL_INVALID_OPERATION);
OCL_STATUS(CL_INVALID_GL_OBJECT);
OCL_STATUS(CL_INVALID_BUFFER_SIZE);
OCL_STATUS(CL_INVALID_MIP_LEVEL);
OCL_STATUS(CL_INVALID_GLOBAL_WORK_SIZE);
#if defined(CL_INVALID_PROPERTY)
OCL_STATUS(CL_INVALID_PROPERTY);
#endif /* defined(CL_INVALID_PROPERTY) */
#undef OCL_STATUS
default: {
static char tmp[64];
snprintf(tmp, sizeof(tmp), "Unknown code %d", ret);
return tmp;
}
}
}
void
ocl_error(int code, const char *desc){
const char *err = ocl_strerror(code);
if (desc) {
fprintf(stderr, "%s: %s\n", desc, err);
} else {
fprintf(stderr, "%s\n", err);
}
}
/*Вывод информации о текущем устройстве и платформе*/
void
ocl_print_info(ocl_s *ocl){
cl_device_id did = ocl->device_id;
fprintf(stderr, "\n==[SELECTED DEVICE INFO]============================\n");
fprintf(stderr, "Device: %s\n", ocl_device_getstr(did, CL_DEVICE_NAME));
fprintf(stderr, "Vendor: %s (%04x)\n", ocl_device_getstr(did, CL_DEVICE_VENDOR), ocl_device_getuint(did, CL_DEVICE_VENDOR_ID));
fprintf(stderr, "Driver: %s\n", ocl_device_getstr(did, CL_DRIVER_VERSION));
fprintf(stderr, "Profile: %s\n", ocl_device_getstr(did, CL_DEVICE_PROFILE));
fprintf(stderr, "Version: %s\n", ocl_device_getstr(did, CL_DEVICE_VERSION));
fprintf(stderr, "Max compute units: %zd\n", ocl_device_getsizet(did, CL_DEVICE_MAX_COMPUTE_UNITS));
fprintf(stderr, "Max workgroup size: %zd\n", ocl_device_getsizet(did, CL_DEVICE_MAX_WORK_GROUP_SIZE));
fprintf(stderr, "Global memory: %ld\n", ocl_device_getulong(did, CL_DEVICE_GLOBAL_MEM_SIZE));
fprintf(stderr, "Max allocation: %ld\n\n", ocl_device_getulong(did, CL_DEVICE_MAX_MEM_ALLOC_SIZE));
}
/***********************************************************************
* OCL
***********************************************************************/
/*Инициализация устройства и компиляция программы*/
ocl_s *
ocl_init(int platform_id, int device_id, const char * program, uint32_t ncols, uint32_t nrows, uint32_t invsize){
ocl_s * ocl = (ocl_s *)calloc(1, sizeof(ocl_s));
/* получить доступные платформы */
if((ocl->platform_id = ocl_platform_get(platform_id)) == NULL) return NULL;
/* получить доступные устройства */
if((ocl->device_id = ocl_device_get(ocl->platform_id, device_id)) == NULL) return NULL;
cl_int ret;
/* создать контекст */
ocl->context = clCreateContext(NULL, 1, &(ocl->device_id), NULL, NULL, &ret);
if (!ocl->context){
ocl_error(ret, "clCreateContext");
return NULL;
}
/* создаем команду */
ocl->command = clCreateCommandQueue(ocl->context, ocl->device_id, 0, &ret);
if (!ocl->context){
ocl_error(ret, "clCreateCommandQueue");
return NULL;
}
/* получить опции компилятора */
char optbuf[256];
ocl->quirks = ocl_get_quirks(ocl->device_id, optbuf);
/*Загрузка и компиляция CL программы*/
if(!ocl_load_program(ocl, program, optbuf)) return NULL;
/*Вычисление настроек матрицы*/
/*Количество одновременно выполняемых потоков на GPU*/
size_t nthreads = ocl_device_getsizet(ocl->device_id, CL_DEVICE_MAX_WORK_GROUP_SIZE);
size_t full_threads = ocl_device_getsizet(ocl->device_id, CL_DEVICE_MAX_COMPUTE_UNITS);
full_threads *= nthreads;
cl_ulong memsize = ocl_device_getulong(ocl->device_id, CL_DEVICE_GLOBAL_MEM_SIZE);
cl_ulong allocsize = ocl_device_getulong(ocl->device_id, CL_DEVICE_MAX_MEM_ALLOC_SIZE);
memsize /= 2;
if(!ncols || !nrows){
ncols = full_threads;
nrows = 2;
while ((ncols > nrows) && !(ncols & 1)){
ncols /= 2;
nrows *= 2;
}
int worksize = 2048; //defult is 2048
int wsmult = 1;
while ((!worksize || ((wsmult * 2) <= worksize)) &&
((ncols * nrows * 2 * 128) < memsize) &&
((ncols * nrows * 2 * 64) < allocsize)) {
if (ncols > nrows)
nrows *= 2;
else
ncols *= 2;
wsmult *= 2;
}
}
uint32_t round = nrows * ncols;
if(!invsize){
invsize = 2;
while(!(round % (invsize << 1)) && ((round / invsize) > full_threads)) invsize <<= 1;
}
if ((round % invsize) || !is_pow2(invsize) || (invsize < 2)) {
fprintf(stderr, "Grid size: %dx%d\n", ncols, nrows);
fprintf(stderr, "Modular inverse thread size: %d\n", invsize);
if (round % invsize)
fprintf(stderr, "Modular inverse work size must evenly divide points\n");
else
fprintf(stderr, "Modular inverse work per task (%d) must be a power of 2\n", invsize);
return NULL;
}
ocl->ncols = ncols;
ocl->nrows = nrows;
ocl->round = round;
ocl->invsize = invsize;
printf("Grid size: %dx%d, total %d\n", ncols, nrows, round);
printf("Modular inverse: %d threads, %d ops each\n", round/invsize, invsize);
return ocl;
}/*END: ocl_init()*/
static void
ocl_free_kernel(ocl_s *ocl){
int i, arg;
for (arg = 0; arg < MAX_ARG; arg++) {
if (ocl->arguments[arg]) {
clReleaseMemObject(ocl->arguments[arg]);
ocl->arguments[arg] = NULL;
ocl->argument_size[arg] = 0;
}
}
for (i = 0; i < MAX_KERNEL; i++) {
if(ocl->kernel[i]){
clReleaseKernel(ocl->kernel[i]);
ocl->kernel[i] = NULL;
}
}
}
/*Удаление устройства*/
void
ocl_clear(ocl_s * ocl){
ocl_free_kernel(ocl);
if (ocl->program) {
clReleaseProgram(ocl->program);
}
if (ocl->command) {
clReleaseCommandQueue(ocl->command);
}
if (ocl->context) {
clReleaseContext(ocl->context);
}
memset(ocl, 0, sizeof(ocl_s));
}
/***********************************************************************
* PLATFORM
***********************************************************************/
/*Получение платформы*/
cl_platform_id
ocl_platform_get(int num){
int np;
cl_platform_id id, *ids;
np = ocl_platform_list(&ids);
if (np < 0) return NULL;
if (!np){
fprintf(stderr, "No OpenCL platforms available\n");
return NULL;
}
if (num < 0) {
if (np == 1)
num = 0;
else
num = np;
}
if (num < np) {
id = ids[num];
free(ids);
return id;
}
free(ids);
return NULL;
}
/*Получение списка доступных платформ*/
int
ocl_platform_list(cl_platform_id **list_out){
cl_uint np;
cl_int res;
cl_platform_id *ids;
res = clGetPlatformIDs(0, NULL, &np);
if (res != CL_SUCCESS) {
ocl_error(res, "clGetPlatformIDs(0)");
*list_out = NULL;
return -1;
}
if (np) {
ids = (cl_platform_id *) malloc(np * sizeof(*ids));
if (ids == NULL) {
fprintf(stderr,
"Could not allocate platform ID list\n");
*list_out = NULL;
return -1;
}
res = clGetPlatformIDs(np, ids, NULL);
if (res != CL_SUCCESS) {
ocl_error(res, "clGetPlatformIDs(n)");
free(ids);
*list_out = NULL;
return -1;
}
*list_out = ids;
}
return np;
}
/*Вывод информации о доступных платформах*/
void
ocl_platforms_info(cl_platform_id *ids, int np, int base){
int i;
char nbuf[128];
char vbuf[128];
size_t len;
cl_int res;
for (i = 0; i < np; i++) {
res = clGetPlatformInfo(ids[i], CL_PLATFORM_NAME, sizeof(nbuf), nbuf, &len);
if (res != CL_SUCCESS) {
ocl_error(res, "clGetPlatformInfo(NAME)");
continue;
}
if (len >= sizeof(nbuf))
len = sizeof(nbuf) - 1;
nbuf[len] = '\0';
res = clGetPlatformInfo(ids[i], CL_PLATFORM_VENDOR, sizeof(vbuf), vbuf, &len);
if (res != CL_SUCCESS) {
ocl_error(res, "clGetPlatformInfo(VENDOR)");
continue;
}
if (len >= sizeof(vbuf))
len = sizeof(vbuf) - 1;
vbuf[len] = '\0';
fprintf(stderr, "%d: [%s] %s\n", i + base, vbuf, nbuf);
}
}
const char *
ocl_platform_getstr(cl_platform_id pid, cl_platform_info param){
static char platform_str[1024];
cl_int ret;
size_t size_ret;
ret = clGetPlatformInfo(pid, param,
sizeof(platform_str), platform_str,
&size_ret);
if (ret != CL_SUCCESS) {
snprintf(platform_str, sizeof(platform_str),
"clGetPlatformInfo(%d): %s",
param, ocl_strerror(ret));
}
return platform_str;
}
/***********************************************************************
* DEVICE
***********************************************************************/
/*Получение заданного устройства в указанной платформе*/
cl_device_id
ocl_device_manual(int platformidx, int deviceidx){
cl_platform_id pid;
cl_device_id did = NULL;
pid = ocl_platform_get(platformidx);
if (pid) {
did = ocl_device_get(pid, deviceidx);
if (did)
return did;
}
return NULL;
}
/*Получение устройства*/
cl_device_id
ocl_device_get(cl_platform_id pid, int num){
int nd;
cl_device_id id, *ids;
nd = ocl_devices_list(pid, &ids);
if (nd < 0)
return NULL;
if (!nd) {
fprintf(stderr, "No OpenCL devices found\n");
return NULL;
}
if (num < 0) {
if (nd == 1)
num = 0;
else
num = nd;
}
if (num < nd) {
id = ids[num];
free(ids);
return id;
}
free(ids);
return NULL;
}
/*Список устройств платформы*/
int
ocl_devices_list(cl_platform_id pid, cl_device_id **list_out){
cl_uint nd;
cl_int res;
cl_device_id *ids;
res = clGetDeviceIDs(pid, CL_DEVICE_TYPE_GPU, 0, NULL, &nd);
if (res != CL_SUCCESS) {
ocl_error(res, "clGetDeviceIDs(0)");
*list_out = NULL;
return -1;
}
if (nd) {
ids = (cl_device_id *) malloc(nd * sizeof(*ids));
if (ids == NULL) {
fprintf(stderr, "Could not allocate device ID list\n");
*list_out = NULL;
return -1;
}
res = clGetDeviceIDs(pid, CL_DEVICE_TYPE_GPU, nd, ids, NULL);
if (res != CL_SUCCESS) {
ocl_error(res, "clGetDeviceIDs(n)");
free(ids);
*list_out = NULL;
return -1;
}
*list_out = ids;
}
return nd;
}
/*Информация об устройствах платформы*/
void
ocl_devices_info(cl_platform_id pid, cl_device_id *ids, int nd, int base){
int i;
char nbuf[128];
char vbuf[128];
size_t len;
cl_int res;
for (i = 0; i < nd; i++) {
res = clGetDeviceInfo(ids[i], CL_DEVICE_NAME, sizeof(nbuf), nbuf, &len);
if (res != CL_SUCCESS) continue;
if (len >= sizeof(nbuf))
len = sizeof(nbuf) - 1;
nbuf[len] = '\0';
res = clGetDeviceInfo(ids[i], CL_DEVICE_VENDOR, sizeof(vbuf), vbuf, &len);
if (res != CL_SUCCESS) continue;
if (len >= sizeof(vbuf))
len = sizeof(vbuf) - 1;
vbuf[len] = '\0';
fprintf(stderr, " %d: [%s] %s\n", i + base, vbuf, nbuf);
}
}
/*Возвращает платформу заданного устройства*/
cl_platform_id
ocl_device_getplatform(cl_device_id did){
cl_int ret;
cl_platform_id val;
size_t size_ret;
ret = clGetDeviceInfo(did, CL_DEVICE_PLATFORM,
sizeof(val), &val, &size_ret);
if (ret != CL_SUCCESS) {
fprintf(stderr, "clGetDeviceInfo(CL_DEVICE_PLATFORM): %s",
ocl_strerror(ret));
}
return val;
}
/*Возвращает тип устройства*/
cl_device_type
ocl_device_gettype(cl_device_id did){
cl_int ret;
cl_device_type val;
size_t size_ret;
ret = clGetDeviceInfo(did, CL_DEVICE_TYPE,
sizeof(val), &val, &size_ret);
if (ret != CL_SUCCESS) {
fprintf(stderr, "clGetDeviceInfo(CL_DEVICE_TYPE): %s",
ocl_strerror(ret));
}
return val;
}
/*Возвращает текстовый параметр устройства*/
const char *
ocl_device_getstr(cl_device_id did, cl_device_info param){
static char device_str[1024];
cl_int ret;
size_t size_ret;
ret = clGetDeviceInfo(did, param,
sizeof(device_str), device_str,
&size_ret);
if (ret != CL_SUCCESS) {
snprintf(device_str, sizeof(device_str),
"clGetDeviceInfo(%d): %s",
param, ocl_strerror(ret));
}
return device_str;
}
/*Возвращает size_t параметр устройства*/
size_t
ocl_device_getsizet(cl_device_id did, cl_device_info param){
cl_int ret;
size_t val;
size_t size_ret;
ret = clGetDeviceInfo(did, param, sizeof(val), &val, &size_ret);
if (ret != CL_SUCCESS) {
fprintf(stderr,
"clGetDeviceInfo(%d): %s", param, ocl_strerror(ret));
}
return val;
}
/*Возвращает cl_ulong параметр устройства*/
cl_ulong
ocl_device_getulong(cl_device_id did, cl_device_info param){
cl_int ret;
cl_ulong val;
size_t size_ret;
ret = clGetDeviceInfo(did, param, sizeof(val), &val, &size_ret);
if (ret != CL_SUCCESS) {
fprintf(stderr,
"clGetDeviceInfo(%d): %s", param, ocl_strerror(ret));
}
return val;
}
/*Возвращает cl_uint параметр устройства*/
cl_uint
ocl_device_getuint(cl_device_id did, cl_device_info param){
cl_int ret;
cl_uint val;
size_t size_ret;
ret = clGetDeviceInfo(did, param, sizeof(val), &val, &size_ret);
if (ret != CL_SUCCESS) {
fprintf(stderr,
"clGetDeviceInfo(%d): %s", param, ocl_strerror(ret));
}
return val;
}
enum {
VG_OCL_DEEP_PREPROC_UNROLL = (1 << 0),
VG_OCL_PRAGMA_UNROLL = (1 << 1),
VG_OCL_EXPENSIVE_BRANCHES = (1 << 2),
VG_OCL_DEEP_VLIW = (1 << 3),
VG_OCL_AMD_BFI_INT = (1 << 4),
VG_OCL_NV_VERBOSE = (1 << 5),
VG_OCL_BROKEN = (1 << 6),
VG_OCL_NO_BINARIES = (1 << 7),
VG_OCL_OPTIMIZATIONS = (VG_OCL_DEEP_PREPROC_UNROLL |
VG_OCL_PRAGMA_UNROLL |
VG_OCL_EXPENSIVE_BRANCHES |
VG_OCL_DEEP_VLIW |
VG_OCL_AMD_BFI_INT),
};
/*Вычисление исходя из устройства опций для компиляции*/
unsigned int
ocl_get_quirks(cl_device_id did, char * optbuf){
uint32_t vend;
const char *dvn;
unsigned int quirks = 0;
quirks |= VG_OCL_DEEP_PREPROC_UNROLL;
vend = ocl_device_getuint(did, CL_DEVICE_VENDOR_ID);
switch (vend) {
case 0x10de: /* NVIDIA */
/*
* NVIDIA's compiler seems to take a really really long
* time when using preprocessor unrolling, but works
* well with pragma unroll.
*/
quirks &= ~VG_OCL_DEEP_PREPROC_UNROLL;
quirks |= VG_OCL_PRAGMA_UNROLL;
quirks |= VG_OCL_NV_VERBOSE;
break;
case 0x1002: /* AMD/ATI */
/*
* AMD's compiler works best with preprocesor unrolling.
* Pragma unroll is unreliable with AMD's compiler and
* seems to crash based on whether the gods were smiling
* when Catalyst was last installed/upgraded.
*/
if (ocl_device_gettype(did) & CL_DEVICE_TYPE_GPU) {
quirks |= VG_OCL_EXPENSIVE_BRANCHES;
quirks |= VG_OCL_DEEP_VLIW;
dvn = ocl_device_getstr(did, CL_DEVICE_EXTENSIONS);
if (dvn && strstr(dvn, "cl_amd_media_ops"))
quirks |= VG_OCL_AMD_BFI_INT;
dvn = ocl_device_getstr(did, CL_DEVICE_NAME);
if (!strcmp(dvn, "ATI RV710")) {
quirks &= ~VG_OCL_OPTIMIZATIONS;
quirks |= VG_OCL_NO_BINARIES;
}
}
break;
default:
break;
}
if(optbuf) ocl_get_quirks_str(quirks, optbuf);
return quirks;
}
/*Получение строки опций для компиляции из вычесленного значения ocl_get_quirks()*/
void
ocl_get_quirks_str(unsigned int quirks, char * optbuf){
int end = 0;
if (quirks & VG_OCL_DEEP_PREPROC_UNROLL)
end += sprintf(optbuf + end, "-DDEEP_PREPROC_UNROLL ");
if (quirks & VG_OCL_PRAGMA_UNROLL)
end += sprintf(optbuf + end, "-DPRAGMA_UNROLL ");
if (quirks & VG_OCL_EXPENSIVE_BRANCHES)
end += sprintf(optbuf + end, "-DVERY_EXPENSIVE_BRANCHES ");
if (quirks & VG_OCL_DEEP_VLIW)
end += sprintf(optbuf + end, "-DDEEP_VLIW ");
if (quirks & VG_OCL_AMD_BFI_INT)
end += sprintf(optbuf + end, "-DAMD_BFI_INT ");
if (quirks & VG_OCL_NV_VERBOSE)
end += sprintf(optbuf + end, "-cl-nv-verbose ");
optbuf[end] = '\0';
}
/***********************************************************************
* PROGRAM
***********************************************************************/
int
ocl_load_program(ocl_s * ocl, const char *filename, const char *opts){
FILE *kfp;
char *buf, *tbuf;
int len, fromsource = 0, patched = 0;
size_t sz, szr;
cl_program prog;
cl_int ret, sts;
uint32_t prog_hash = 0;
char bin_name[64];
uint8_t * ptr;
sz = 128 * 1024;
buf = (char *) malloc(sz);
if (!buf) {
fprintf(stderr, "Could not allocate program buffer\n");
return 0;
}
fprintf(stderr, "Load program file: %s\n",filename);
kfp = fopen(filename, "r");
if (!kfp) {
fprintf(stderr, "Error loading kernel file '%s': %s\n",
filename, strerror(errno));
free(buf);
return 0;
}
len = fread(buf, 1, sz, kfp);
fclose(kfp);
kfp = NULL;
if (!len) {
fprintf(stderr, "Short read on CL kernel\n");
free(buf);
return 0;
}
prog_hash = ocl_hash_program(ocl, opts, buf, len);
ptr = (uint8_t *)&prog_hash;
sprintf(bin_name, "%02x%02x%02x%02x.oclbin", ptr[0], ptr[1], ptr[2], ptr[3]);
if (ocl->quirks & VG_OCL_NO_BINARIES) {
//
} else {
kfp = fopen(bin_name, "rb");
}
//Нет бинарника, компилируем из исходника
if (!kfp) {
fromsource = 1;
sz = len;
prog = clCreateProgramWithSource(ocl->context,
1, (const char **) &buf, &sz,
&ret);
} else {
szr = 0;
while (!feof(kfp)) {
len = fread(buf + szr, 1, sz - szr, kfp);
if (!len) {
fprintf(stderr,
"Short read on CL kernel binary\n");
fclose(kfp);
free(buf);
return 0;
}
szr += len;
if (szr == sz) {
tbuf = (char *) realloc(buf, sz*2);
if (!tbuf) {
fprintf(stderr,
"Could not expand CL kernel "
"binary buffer\n");
fclose(kfp);
free(buf);
return 0;
}
buf = tbuf;
sz *= 2;
}
}
fclose(kfp);
rebuild:
prog = clCreateProgramWithBinary(ocl->context,
1, &ocl->device_id,
&szr,
(const unsigned char **) &buf,
&sts,
&ret);
}
free(buf);
if (!prog) {
ocl_error(ret, "clCreateProgramWithSource");
return 0;
}
if (fromsource && !patched) {
fprintf(stderr,"Compiling CL, can take minutes...");
fflush(stderr);
}
ret = clBuildProgram(prog, 1, &ocl->device_id, opts, NULL, NULL);
if (ret != CL_SUCCESS) {
if (fromsource && !patched) fprintf(stderr, "failure.\n");
ocl_error(ret, "clBuildProgram");
ocl_buildlog(ocl, prog);
clReleaseProgram(prog);
return 0;
}
if (fromsource && !(ocl->quirks & VG_OCL_NO_BINARIES)) {
ret = clGetProgramInfo(prog,
CL_PROGRAM_BINARY_SIZES,
sizeof(szr), &szr,
&sz);
if (ret != CL_SUCCESS) {
ocl_error(ret,
"WARNING: clGetProgramInfo(BINARY_SIZES)");
goto out;
}
if (sz == 0) {
fprintf(stderr,
"WARNING: zero-length CL kernel binary\n");
goto out;
}
buf = (char *) malloc(szr);
if (!buf) {
fprintf(stderr,
"WARNING: Could not allocate %zd bytes "
"for CL binary\n",
szr);
goto out;
}
ret = clGetProgramInfo(prog,
CL_PROGRAM_BINARIES,
sizeof(buf), &buf,
&sz);
if (ret != CL_SUCCESS) {
ocl_error(ret,
"WARNING: clGetProgramInfo(BINARIES)");
free(buf);
goto out;
}
if ((ocl->quirks & VG_OCL_AMD_BFI_INT) && !patched) {
patched = ocl_amd_patch((unsigned char *) buf, szr);
if (patched > 0) {
clReleaseProgram(prog);
goto rebuild;
}
fprintf(stderr,
"WARNING: AMD BFI_INT patching failed\n");
if (patched < 0) {
/* Program was incompletely modified */
free(buf);
goto out;
}
}
kfp = fopen(bin_name, "wb");
if (!kfp) {
fprintf(stderr, "WARNING: "
"could not save CL kernel binary: %s\n",
strerror(errno));
} else {
sz = fwrite(buf, 1, szr, kfp);
fclose(kfp);
if (sz != szr) {
fprintf(stderr,
"WARNING: short write on CL kernel "
"binary file: expected "
"%zd, got %zd\n",
szr, sz);
unlink(bin_name);
}
}
free(buf);
}
out:
ocl->program = prog;
return 1;
}
/*Получение CRC32 хеша программы*/
uint32_t
ocl_hash_program(ocl_s * ocl, const char *opts, const char *program, size_t size){
const char *str;
uint32_t h = 0;
cl_platform_id pid = ocl_device_getplatform(ocl->device_id);
str = ocl_platform_getstr(pid, CL_PLATFORM_NAME);
h = hash_crc32(h, str, strlen(str));
str = ocl_platform_getstr(pid, CL_PLATFORM_VERSION);
h = hash_crc32(h, str, strlen(str));
str = ocl_device_getstr(ocl->device_id, CL_DEVICE_NAME);
h = hash_crc32(h, str, strlen(str));
if (opts) h = hash_crc32(h, opts, strlen(opts));
if (program && size) h = hash_crc32(h, program, size);
return h;
}
/*Построение лога процесса компиляции программы*/
void
ocl_buildlog(ocl_s * ocl, cl_program prog){
size_t logbufsize, logsize;
char *log;
int off = 0;
cl_int ret;
ret = clGetProgramBuildInfo(prog,
ocl->device_id,
CL_PROGRAM_BUILD_LOG,
0, NULL,
&logbufsize);
if (ret != CL_SUCCESS) {
ocl_error(ret, "clGetProgramBuildInfo");
return;
}
log = (char *) malloc(logbufsize);
if (!log) {
fprintf(stderr, "Could not allocate build log buffer\n");
return;
}
ret = clGetProgramBuildInfo(prog,
ocl->device_id,
CL_PROGRAM_BUILD_LOG,
logbufsize,
log,
&logsize);
if (ret != CL_SUCCESS) {
ocl_error(ret, "clGetProgramBuildInfo");
} else {
/* Remove leading newlines and trailing newlines/whitespace */
log[logbufsize-1] = '\0';
for (off = logsize - 1; off >= 0; off--) {
if ((log[off] != '\r') &&
(log[off] != '\n') &&
(log[off] != ' ') &&
(log[off] != '\t') &&
(log[off] != '\0'))
break;
log[off] = '\0';
}
for (off = 0; off < logbufsize; off++) {
if ((log[off] != '\r') &&
(log[off] != '\n'))
break;
}
fprintf(stderr, "Build log:\n%s\n", &log[off]);
}
free(log);
}
typedef struct {
unsigned char e_ident[16];
uint16_t e_type;
uint16_t e_machine;
uint32_t e_version;
uint32_t e_entry;
uint32_t e_phoff;
uint32_t e_shoff;
uint32_t e_flags;
uint16_t e_ehsize;
uint16_t e_phentsize;
uint16_t e_phnum;
uint16_t e_shentsize;
uint16_t e_shnum;
uint16_t e_shstrndx;
} vg_elf32_header_t;
typedef struct {
uint32_t sh_name;
uint32_t sh_type;
uint32_t sh_flags;
uint32_t sh_addr;
uint32_t sh_offset;
uint32_t sh_size;
uint32_t sh_link;
uint32_t sh_info;
uint32_t sh_addralign;
uint32_t sh_entsize;
} vg_elf32_shdr_t;
int
ocl_amd_patch_inner(unsigned char *binary, size_t size){
vg_elf32_header_t *ehp;
vg_elf32_shdr_t *shp, *nshp;
uint32_t *instr;
size_t off;
int i, n, txt2idx, patched;
ehp = (vg_elf32_header_t *) binary;
if ((size < sizeof(*ehp)) ||
memcmp(ehp->e_ident, "\x7f" "ELF\1\1\1\x64", 8) ||
!ehp->e_shoff)
return 0;
off = ehp->e_shoff + (ehp->e_shstrndx * ehp->e_shentsize);
nshp = (vg_elf32_shdr_t *) (binary + off);
if ((off + sizeof(*nshp)) > size)
return 0;
shp = (vg_elf32_shdr_t *) (binary + ehp->e_shoff);
n = 0;
txt2idx = 0;
for (i = 0; i < ehp->e_shnum; i++) {
off = nshp->sh_offset + shp[i].sh_name;
if (((off + 6) >= size) ||
memcmp(binary + off, ".text", 6))