/
opencl.c
2059 lines (1758 loc) · 71 KB
/
opencl.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
/*
This file is part of darktable,
copyright (c) 2009--2012 johannes hanika.
copyright (c) 2011--2013 Ulrich Pegelow.
darktable is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
darktable is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with darktable. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_OPENCL
#include "common/darktable.h"
#include "common/opencl.h"
#include "common/bilateralcl.h"
#include "common/gaussian.h"
#include "common/interpolation.h"
#include "common/dlopencl.h"
#include "common/nvidia_gpus.h"
#include "develop/pixelpipe.h"
#include "control/conf.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <locale.h>
#include <sys/stat.h>
#include <errno.h>
#include <libgen.h>
#include <ctype.h>
static const char *dt_opencl_get_vendor_by_id(unsigned int id);
static char *_ascii_str_canonical(const char *in, char *out, int maxlen);
/** parse a single token of priority string and store priorities in priority_list */
static void dt_opencl_priority_parse(dt_opencl_t *cl, char *configstr, int *priority_list);
/** parse a complete priority string */
static void dt_opencl_priorities_parse(dt_opencl_t *cl, const char *configstr);
void dt_opencl_init(dt_opencl_t *cl, const gboolean exclude_opencl)
{
char *str;
dt_pthread_mutex_init(&cl->lock, NULL);
cl->inited = 0;
cl->enabled = 0;
cl->stopped = 0;
cl->error_count = 0;
// work-around to fix a bug in some AMD OpenCL compilers, which would fail parsing certain numerical
// constants if locale is different from "C".
// we save the current locale, set locale to "C", and restore the previous setting after OpenCL is
// initialized
char *locale = strdup(setlocale(LC_ALL, NULL));
setlocale(LC_ALL, "C");
int handles = dt_conf_get_int("opencl_number_event_handles");
handles = (handles < 0 ? 0x7fffffff : handles);
cl->number_event_handles = handles;
cl->use_events = (handles != 0);
cl->avoid_atomics = dt_conf_get_bool("opencl_avoid_atomics");
cl->async_pixelpipe = dt_conf_get_bool("opencl_async_pixelpipe");
cl->synch_cache = dt_conf_get_bool("opencl_synch_cache");
cl->micro_nap = dt_conf_get_int("opencl_micro_nap");
cl->dlocl = NULL;
cl->dev_priority_image = NULL;
cl->dev_priority_preview = NULL;
cl->dev_priority_export = NULL;
cl->dev_priority_thumbnail = NULL;
// user selectable parameter defines minimum requirement on GPU memory
// default is 768MB
// values below 200 will be (re)set to 200
const int opencl_memory_requirement = MAX(200, dt_conf_get_int("opencl_memory_requirement"));
dt_conf_set_int("opencl_memory_requirement", opencl_memory_requirement);
if(exclude_opencl)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] do not try to find and use an opencl runtime library due to "
"explicit user request\n");
goto finally;
}
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl related configuration options:\n");
dt_print(DT_DEBUG_OPENCL, "[opencl_init] \n");
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl: %d\n", dt_conf_get_bool("opencl"));
str = dt_conf_get_string("opencl_library");
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_library: '%s'\n", str);
g_free(str);
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_memory_requirement: %d\n",
dt_conf_get_int("opencl_memory_requirement"));
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_memory_headroom: %d\n",
dt_conf_get_int("opencl_memory_headroom"));
str = dt_conf_get_string("opencl_device_priority");
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_device_priority: '%s'\n", str);
g_free(str);
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_size_roundup: %d\n",
dt_conf_get_int("opencl_size_roundup"));
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_async_pixelpipe: %d\n",
dt_conf_get_bool("opencl_async_pixelpipe"));
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_synch_cache: %d\n", dt_conf_get_bool("opencl_synch_cache"));
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_number_event_handles: %d\n",
dt_conf_get_int("opencl_number_event_handles"));
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_micro_nap: %d\n", dt_conf_get_int("opencl_micro_nap"));
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_use_pinned_memory: %d\n",
dt_conf_get_bool("opencl_use_pinned_memory"));
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_use_cpu_devices: %d\n",
dt_conf_get_bool("opencl_use_cpu_devices"));
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_avoid_atomics: %d\n",
dt_conf_get_bool("opencl_avoid_atomics"));
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl_omit_whitebalance: %d\n",
dt_conf_get_bool("opencl_omit_whitebalance"));
dt_print(DT_DEBUG_OPENCL, "[opencl_init] \n");
// look for explicit definition of opencl_runtime library in preferences
char *library = dt_conf_get_string("opencl_library");
// dynamically load opencl runtime
if(!dt_dlopencl_init(library, &cl->dlocl))
{
dt_print(DT_DEBUG_OPENCL,
"[opencl_init] no working opencl library found. Continue with opencl disabled\n");
g_free(library);
goto finally;
}
else
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] opencl library '%s' found on your system and loaded\n",
cl->dlocl->library);
}
g_free(library);
cl_int err;
cl_platform_id all_platforms[DT_OPENCL_MAX_PLATFORMS];
cl_uint all_num_devices[DT_OPENCL_MAX_PLATFORMS];
cl_uint num_platforms = DT_OPENCL_MAX_PLATFORMS;
err = (cl->dlocl->symbols->dt_clGetPlatformIDs)(DT_OPENCL_MAX_PLATFORMS, all_platforms, &num_platforms);
if(err != CL_SUCCESS)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] could not get platforms: %d\n", err);
goto finally;
}
if(num_platforms == 0)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] no opencl platform available\n");
goto finally;
}
dt_print(DT_DEBUG_OPENCL, "[opencl_init] found %d platform%s\n", num_platforms,
num_platforms > 1 ? "s" : "");
for(int n = 0; n < num_platforms; n++)
{
cl_platform_id platform = all_platforms[n];
// get the number of GPU devices available to the platforms
// the other common option is CL_DEVICE_TYPE_GPU/CPU (but the latter doesn't work with the nvidia drivers)
err = (cl->dlocl->symbols->dt_clGetDeviceIDs)(platform, CL_DEVICE_TYPE_ALL, 0, NULL,
&(all_num_devices[n]));
if(err != CL_SUCCESS)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] could not get device id size: %d\n", err);
}
}
cl_uint num_devices = 0;
for(int n = 0; n < num_platforms; n++) num_devices += all_num_devices[n];
// create the device list
cl->dev = (dt_opencl_device_t *)malloc(sizeof(dt_opencl_device_t) * num_devices);
cl_device_id *devices = (cl_device_id *)malloc(sizeof(cl_device_id) * num_devices);
cl_device_id *devs = devices;
for(int n = 0; n < num_platforms; n++)
{
cl_platform_id platform = all_platforms[n];
err = (cl->dlocl->symbols->dt_clGetDeviceIDs)(platform, CL_DEVICE_TYPE_ALL, all_num_devices[n], devs,
NULL);
if(err != CL_SUCCESS)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] could not get devices list: %d\n", err);
}
devs += all_num_devices[n];
}
dt_print(DT_DEBUG_OPENCL, "[opencl_init] found %d device%s\n", num_devices, num_devices > 1 ? "s" : "");
if(num_devices == 0) goto finally;
int dev = 0;
for(int k = 0; k < num_devices; k++)
{
memset(cl->dev[dev].program, 0x0, sizeof(cl_program) * DT_OPENCL_MAX_PROGRAMS);
memset(cl->dev[dev].program_used, 0x0, sizeof(int) * DT_OPENCL_MAX_PROGRAMS);
memset(cl->dev[dev].kernel, 0x0, sizeof(cl_kernel) * DT_OPENCL_MAX_KERNELS);
memset(cl->dev[dev].kernel_used, 0x0, sizeof(int) * DT_OPENCL_MAX_KERNELS);
cl->dev[dev].eventlist = NULL;
cl->dev[dev].eventtags = NULL;
cl->dev[dev].numevents = 0;
cl->dev[dev].eventsconsolidated = 0;
cl->dev[dev].maxevents = 0;
cl->dev[dev].lostevents = 0;
cl->dev[dev].totalevents = 0;
cl->dev[dev].totalsuccess = 0;
cl->dev[dev].totallost = 0;
cl->dev[dev].summary = CL_COMPLETE;
cl->dev[dev].used_global_mem = 0;
cl->dev[dev].nvidia_sm_20 = 0;
cl->dev[dev].vendor = "";
cl->dev[dev].name = "";
cl->dev[dev].cname = "";
cl_device_id devid = cl->dev[dev].devid = devices[k];
char infostr[1024];
char vendor[256];
char driverversion[256];
char deviceversion[256];
size_t infoint;
size_t infointtab[1024];
cl_device_type type;
cl_bool image_support = 0;
cl_bool device_available = 0;
cl_uint vendor_id = 0;
// test GPU availability, vendor, memory, image support etc:
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_AVAILABLE, sizeof(cl_bool), &device_available,
NULL);
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_VENDOR, sizeof(vendor), &vendor, NULL);
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_VENDOR_ID, sizeof(cl_uint), &vendor_id, NULL);
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_NAME, sizeof(infostr), &infostr, NULL);
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DRIVER_VERSION, sizeof(driverversion), &driverversion,
NULL);
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_VERSION, sizeof(deviceversion), &deviceversion,
NULL);
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_TYPE, sizeof(cl_device_type), &type, NULL);
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_IMAGE_SUPPORT, sizeof(cl_bool), &image_support,
NULL);
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_IMAGE2D_MAX_HEIGHT, sizeof(size_t),
&(cl->dev[dev].max_image_height), NULL);
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_IMAGE2D_MAX_WIDTH, sizeof(size_t),
&(cl->dev[dev].max_image_width), NULL);
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(cl_ulong),
&(cl->dev[dev].max_mem_alloc), NULL);
if(!strncasecmp(vendor, "NVIDIA", 6))
{
// very lame attempt to detect support for atomic float add in global memory.
// we need compute model sm_20, but let's try for all nvidia devices :(
cl->dev[dev].nvidia_sm_20 = dt_nvidia_gpu_supports_sm_20(infostr);
dt_print(DT_DEBUG_OPENCL, "[opencl_init] device %d `%s' %s sm_20 support.\n", k, infostr,
cl->dev[dev].nvidia_sm_20 ? "has" : "doesn't have");
}
if((type == CL_DEVICE_TYPE_CPU) && !dt_conf_get_bool("opencl_use_cpu_devices"))
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] discarding CPU device %d `%s'.\n", k, infostr);
continue;
}
if(!device_available)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] discarding device %d `%s' as it is not available.\n", k,
infostr);
continue;
}
if(!image_support)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] discarding device %d `%s' due to missing image support.\n", k,
infostr);
continue;
}
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(cl_ulong),
&(cl->dev[dev].max_global_mem), NULL);
if(cl->dev[dev].max_global_mem < opencl_memory_requirement * 1024 * 1024)
{
dt_print(DT_DEBUG_OPENCL,
"[opencl_init] discarding device %d `%s' due to insufficient global memory (%luMB).\n", k,
infostr, cl->dev[dev].max_global_mem / 1024 / 1024);
continue;
}
cl->dev[dev].vendor = dt_opencl_get_vendor_by_id(vendor_id);
cl->dev[dev].name = strdup(infostr);
cl->dev[dev].cname = _ascii_str_canonical(infostr, NULL, 0);
dt_print(DT_DEBUG_OPENCL, "[opencl_init] device %d `%s' supports image sizes of %zd x %zd\n", k, infostr,
cl->dev[dev].max_image_width, cl->dev[dev].max_image_height);
dt_print(DT_DEBUG_OPENCL, "[opencl_init] device %d `%s' allows GPU memory allocations of up to %luMB\n",
k, infostr, cl->dev[dev].max_mem_alloc / 1024 / 1024);
if(darktable.unmuted & DT_DEBUG_OPENCL)
{
printf("[opencl_init] device %d: %s \n", k, infostr);
printf(" GLOBAL_MEM_SIZE: %.0fMB\n", (double)cl->dev[dev].max_global_mem / 1024.0 / 1024.0);
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(infoint),
&infoint, NULL);
printf(" MAX_WORK_GROUP_SIZE: %zd\n", infoint);
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(infoint),
&infoint, NULL);
printf(" MAX_WORK_ITEM_DIMENSIONS: %zd\n", infoint);
printf(" MAX_WORK_ITEM_SIZES: [ ");
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(infointtab),
infointtab, NULL);
for(size_t i = 0; i < infoint; i++) printf("%zd ", infointtab[i]);
printf("]\n");
printf(" DRIVER_VERSION: %s\n", driverversion);
printf(" DEVICE_VERSION: %s\n", deviceversion);
}
dt_pthread_mutex_init(&cl->dev[dev].lock, NULL);
cl->dev[dev].context = (cl->dlocl->symbols->dt_clCreateContext)(0, 1, &devid, NULL, NULL, &err);
if(err != CL_SUCCESS)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] could not create context for device %d: %d\n", k, err);
goto finally;
}
// create a command queue for first device the context reported
cl->dev[dev].cmd_queue = (cl->dlocl->symbols->dt_clCreateCommandQueue)(
cl->dev[dev].context, devid, (darktable.unmuted & DT_DEBUG_PERF) ? CL_QUEUE_PROFILING_ENABLE : 0,
&err);
if(err != CL_SUCCESS)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] could not create command queue for device %d: %d\n", k, err);
goto finally;
}
char dtcache[PATH_MAX] = { 0 };
char cachedir[PATH_MAX] = { 0 };
char devname[1024];
double tstart, tend, tdiff;
dt_loc_get_user_cache_dir(dtcache, sizeof(dtcache));
int len = strlen(infostr);
int j = 0;
// remove non-alphanumeric chars from device name
for(int i = 0; i < len; i++)
if(isalnum(infostr[i])) devname[j++] = infostr[i];
devname[j] = 0;
snprintf(cachedir, sizeof(cachedir), "%s/cached_kernels_for_%s", dtcache, devname);
if(g_mkdir_with_parents(cachedir, 0700) == -1)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] failed to create directory `%s'!\n", cachedir);
goto finally;
}
char dtpath[PATH_MAX] = { 0 };
char filename[PATH_MAX] = { 0 };
char confentry[PATH_MAX] = { 0 };
char binname[PATH_MAX] = { 0 };
dt_loc_get_datadir(dtpath, sizeof(dtpath));
snprintf(filename, sizeof(filename), "%s/kernels/programs.conf", dtpath);
char kerneldir[PATH_MAX] = { 0 };
snprintf(kerneldir, sizeof(kerneldir), "%s/kernels", dtpath);
// now load all darktable cl kernels.
// TODO: compile as a job?
tstart = dt_get_wtime();
FILE *f = fopen(filename, "rb");
if(f)
{
while(!feof(f))
{
int prog = -1;
gchar *confline_pattern = g_strdup_printf("%%%zu[^\n]\n", sizeof(confentry) - 1);
int rd = fscanf(f, confline_pattern, confentry);
g_free(confline_pattern);
if(rd != 1) continue;
// remove comments:
size_t end = strlen(confentry);
for(size_t pos = 0; pos < end; pos++)
if(confentry[pos] == '#')
{
confentry[pos] = '\0';
for(int l = pos - 1; l >= 0; l--)
{
if(confentry[l] == ' ')
confentry[l] = '\0';
else
break;
}
break;
}
if(confentry[0] == '\0') continue;
const char *programname = NULL, *programnumber = NULL;
gchar **tokens = g_strsplit_set(confentry, " \t", 2);
if(tokens)
{
programname = tokens[0];
if(tokens[0])
programnumber
= tokens[1]; // if the 0st wasn't NULL then we have at least the terminating NULL in [1]
}
prog = programnumber ? strtol(programnumber, NULL, 10) : -1;
if(!programname || programname[0] == '\0' || prog < 0)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] malformed entry in programs.conf `%s'; ignoring it!\n",
confentry);
continue;
}
snprintf(filename, sizeof(filename), "%s/kernels/%s", dtpath, programname);
snprintf(binname, sizeof(binname), "%s/%s.bin", cachedir, programname);
dt_print(DT_DEBUG_OPENCL, "[opencl_init] compiling program `%s' ..\n", programname);
int loaded_cached;
char md5sum[33];
if(dt_opencl_load_program(dev, prog, filename, binname, cachedir, md5sum, &loaded_cached)
&& dt_opencl_build_program(dev, prog, binname, cachedir, md5sum, loaded_cached, kerneldir)
!= CL_SUCCESS)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] failed to compile program `%s'!\n", programname);
fclose(f);
g_strfreev(tokens);
goto finally;
}
g_strfreev(tokens);
}
fclose(f);
tend = dt_get_wtime();
tdiff = tend - tstart;
dt_print(DT_DEBUG_OPENCL, "[opencl_init] kernel loading time: %2.4lf \n", tdiff);
}
else
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] could not open `%s'!\n", filename);
goto finally;
}
++dev;
}
free(devices);
if(dev > 0)
{
cl->num_devs = dev;
cl->inited = 1;
cl->enabled = dt_conf_get_bool("opencl");
cl->dev_priority_image = (int *)malloc(sizeof(int) * (dev + 1));
cl->dev_priority_preview = (int *)malloc(sizeof(int) * (dev + 1));
cl->dev_priority_export = (int *)malloc(sizeof(int) * (dev + 1));
cl->dev_priority_thumbnail = (int *)malloc(sizeof(int) * (dev + 1));
// only check successful malloc in debug mode; darktable will crash anyhow sooner or later if mallocs that
// small would fail
assert(cl->dev_priority_image != NULL && cl->dev_priority_preview != NULL
&& cl->dev_priority_export != NULL && cl->dev_priority_thumbnail != NULL);
// apply config settings for device priority
char *str = dt_conf_get_string("opencl_device_priority");
dt_opencl_priorities_parse(cl, str);
g_free(str);
dt_print(DT_DEBUG_OPENCL, "[opencl_init] OpenCL successfully initialized.\n");
dt_print(
DT_DEBUG_OPENCL,
"[opencl_init] here are the internal numbers and names of OpenCL devices available to darktable:\n");
for(int i = 0; i < dev; i++) dt_print(DT_DEBUG_OPENCL, "[opencl_init]\t\t%d\t'%s'\n", i, cl->dev[i].name);
dt_print(DT_DEBUG_OPENCL, "[opencl_init] these are your device priorities:\n");
dt_print(DT_DEBUG_OPENCL, "[opencl_init] \t\timage\tpreview\texport\tthumbnail\n");
for(int i = 0; i < dev; i++)
dt_print(DT_DEBUG_OPENCL, "[opencl_init]\t\t%d\t%d\t%d\t%d\n", cl->dev_priority_image[i],
cl->dev_priority_preview[i], cl->dev_priority_export[i], cl->dev_priority_thumbnail[i]);
}
else
{
dt_print(DT_DEBUG_OPENCL, "[opencl_init] no suitable devices found.\n");
}
finally:
dt_print(DT_DEBUG_OPENCL, "[opencl_init] FINALLY: opencl is %sAVAILABLE on this system.\n",
cl->inited ? "" : "NOT ");
dt_print(DT_DEBUG_OPENCL, "[opencl_init] initial status of opencl enabled flag is %s.\n",
cl->enabled ? "ON" : "OFF");
if(cl->inited)
{
dt_capabilities_add("opencl");
cl->bilateral = dt_bilateral_init_cl_global();
cl->gaussian = dt_gaussian_init_cl_global();
cl->interpolation = dt_interpolation_init_cl_global();
}
if(locale)
{
setlocale(LC_ALL, locale);
free(locale);
}
return;
}
void dt_opencl_cleanup(dt_opencl_t *cl)
{
if(cl->inited)
{
dt_bilateral_free_cl_global(cl->bilateral);
dt_gaussian_free_cl_global(cl->gaussian);
dt_interpolation_free_cl_global(cl->interpolation);
for(int i = 0; i < cl->num_devs; i++)
{
dt_pthread_mutex_destroy(&cl->dev[i].lock);
for(int k = 0; k < DT_OPENCL_MAX_KERNELS; k++)
if(cl->dev[i].kernel_used[k]) (cl->dlocl->symbols->dt_clReleaseKernel)(cl->dev[i].kernel[k]);
for(int k = 0; k < DT_OPENCL_MAX_PROGRAMS; k++)
if(cl->dev[i].program_used[k]) (cl->dlocl->symbols->dt_clReleaseProgram)(cl->dev[i].program[k]);
(cl->dlocl->symbols->dt_clReleaseCommandQueue)(cl->dev[i].cmd_queue);
(cl->dlocl->symbols->dt_clReleaseContext)(cl->dev[i].context);
if(cl->use_events)
{
if(cl->dev[i].totalevents)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_summary_statistics] device '%s': %d out of %d events were "
"successful and %d events lost\n",
cl->dev[i].name, cl->dev[i].totalsuccess, cl->dev[i].totalevents, cl->dev[i].totallost);
}
else
{
dt_print(DT_DEBUG_OPENCL, "[opencl_summary_statistics] device '%s': NOT utilized\n",
cl->dev[i].name);
}
dt_opencl_events_reset(i);
free(cl->dev[i].eventlist);
free(cl->dev[i].eventtags);
}
}
free(cl->dev_priority_image);
free(cl->dev_priority_preview);
free(cl->dev_priority_export);
free(cl->dev_priority_thumbnail);
}
if(cl->dlocl)
{
free(cl->dlocl->symbols);
g_free(cl->dlocl->library);
free(cl->dlocl);
}
free(cl->dev);
dt_pthread_mutex_destroy(&cl->lock);
}
static const char *dt_opencl_get_vendor_by_id(unsigned int id)
{
const char *vendor;
switch(id)
{
case 4098:
vendor = "AMD";
break;
case 4318:
vendor = "NVIDIA";
break;
case 0x8086u:
vendor = "INTEL";
break;
default:
vendor = "UNKNOWN";
}
return vendor;
}
int dt_opencl_finish(const int devid)
{
dt_opencl_t *cl = darktable.opencl;
if(!cl->inited || devid < 0) return -1;
cl_int err = (cl->dlocl->symbols->dt_clFinish)(cl->dev[devid].cmd_queue);
// take the opportunity to release some event handles, but without printing
// summary statistics
cl_int success = dt_opencl_events_flush(devid, 0);
return (err == CL_SUCCESS && success == CL_COMPLETE);
}
int dt_opencl_enqueue_barrier(const int devid)
{
dt_opencl_t *cl = darktable.opencl;
if(!cl->inited || devid < 0) return -1;
return (cl->dlocl->symbols->dt_clEnqueueBarrier)(cl->dev[devid].cmd_queue);
}
static int _take_from_list(int *list, int value)
{
int result = -1;
while(*list != -1 && *list != value) list++;
result = *list;
while(*list != -1)
{
*list = *(list + 1);
list++;
}
return result;
}
static int _device_by_cname(const char *name)
{
dt_opencl_t *cl = darktable.opencl;
int devs = cl->num_devs;
char tmp[2048] = { 0 };
int result = -1;
_ascii_str_canonical(name, tmp, sizeof(tmp));
for(int i = 0; i < devs; i++)
{
if(!strcmp(tmp, cl->dev[i].cname))
{
result = i;
break;
}
}
return result;
}
static char *_ascii_str_canonical(const char *in, char *out, int maxlen)
{
if(out == NULL)
{
maxlen = strlen(in) + 1;
out = malloc(maxlen);
if(out == NULL) return NULL;
}
int len = 0;
while(*in != '\0' && len < maxlen - 1)
{
int n = strcspn(in, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
in += n;
if(n != 0) continue;
out[len] = tolower(*in);
len++;
in++;
}
out[len] = '\0';
return out;
}
static char *_strsep(char **stringp, const char *delim)
{
char *begin, *end;
begin = *stringp;
if(begin == NULL) return NULL;
if(delim[0] == '\0' || delim[1] == '\0')
{
char ch = delim[0];
if(ch == '\0')
end = NULL;
else
{
if(*begin == ch)
end = begin;
else if(*begin == '\0')
end = NULL;
else
end = strchr(begin + 1, ch);
}
}
else
end = strpbrk(begin, delim);
if(end)
{
*end++ = '\0';
*stringp = end;
}
else
*stringp = NULL;
return begin;
}
// parse a single token of priority string and store priorities in priority_list
static void dt_opencl_priority_parse(dt_opencl_t *cl, char *configstr, int *priority_list)
{
int devs = cl->num_devs;
int count = 0;
int full[devs + 1];
// NULL or empty configstring?
if(configstr == NULL || *configstr == '\0')
{
priority_list[0] = -1;
return;
}
// first start with a full list of devices to take from
for(int i = 0; i < devs; i++) full[i] = i;
full[devs] = -1;
gchar **tokens = g_strsplit(configstr, ",", 0);
gchar **tokens_ptr = tokens;
while(tokens != NULL && *tokens_ptr != NULL && count < devs + 1 && full[0] != -1)
{
gchar *str = *tokens_ptr;
int not = 0;
int all = 0;
switch(*str)
{
case '*':
all = 1;
break;
case '!':
not = 1;
while(*str == '!') str++;
break;
}
if(all)
{
// copy all remaining device numbers from full to priority list
for(int i = 0; i < devs && full[i] != -1; i++)
{
priority_list[count] = full[i];
count++;
}
full[0] = -1; // mark full list as empty
}
else if(*str != '\0')
{
char *endptr = NULL;
// first check if str corresponds to an existing canonical device name
long number = _device_by_cname(str);
// if not try to convert string into decimal device number
if(number < 0) number = strtol(str, &endptr, 10);
// still not found or negative number given? set number to -1
if(number < 0 || (number == 0 && endptr == str)) number = -1;
// try to take number out of remaining device list
int dev_number = _take_from_list(full, number);
if(!not&&dev_number != -1)
{
priority_list[count] = dev_number;
count++;
}
}
tokens_ptr++;
}
g_strfreev(tokens);
// terminate priority list with -1
while(count < devs + 1) priority_list[count++] = -1;
}
// parse a complete priority string
static void dt_opencl_priorities_parse(dt_opencl_t *cl, const char *configstr)
{
char tmp[2048];
int len = 0;
// first get rid of all invalid characters
while(*configstr != '\0' && len < sizeof(tmp) - 1)
{
int n = strcspn(configstr, "/!,*0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
configstr += n;
if(n != 0) continue;
tmp[len] = *configstr;
len++;
configstr++;
}
tmp[len] = '\0';
char *str = tmp;
// now split config string into tokens, separated by '/' and parse them one after the other
char *prio = _strsep(&str, "/");
dt_opencl_priority_parse(cl, prio, cl->dev_priority_image);
prio = _strsep(&str, "/");
dt_opencl_priority_parse(cl, prio, cl->dev_priority_preview);
prio = _strsep(&str, "/");
dt_opencl_priority_parse(cl, prio, cl->dev_priority_export);
prio = _strsep(&str, "/");
dt_opencl_priority_parse(cl, prio, cl->dev_priority_thumbnail);
}
int dt_opencl_lock_device(const int pipetype)
{
dt_opencl_t *cl = darktable.opencl;
if(!cl->inited) return -1;
const int *priority;
switch(pipetype)
{
case DT_DEV_PIXELPIPE_FULL:
priority = cl->dev_priority_image;
break;
case DT_DEV_PIXELPIPE_PREVIEW:
priority = cl->dev_priority_preview;
break;
case DT_DEV_PIXELPIPE_EXPORT:
priority = cl->dev_priority_export;
break;
case DT_DEV_PIXELPIPE_THUMBNAIL:
priority = cl->dev_priority_thumbnail;
break;
default:
priority = NULL;
}
if(priority)
{
while(*priority != -1)
{
if(!dt_pthread_mutex_trylock(&cl->dev[*priority].lock)) return *priority;
priority++;
}
}
else
{
// only a fallback if a new pipe type would be added and we forget to take care of it in opencl.c
for(int try_dev = 0; try_dev < cl->num_devs; try_dev++)
{
// get first currently unused processor
if(!dt_pthread_mutex_trylock(&cl->dev[try_dev].lock)) return try_dev;
}
}
// no free GPU :(
// use CPU processing, if no free device:
return -1;
}
void dt_opencl_unlock_device(const int dev)
{
dt_opencl_t *cl = darktable.opencl;
if(!cl->inited) return;
if(dev < 0 || dev >= cl->num_devs) return;
dt_pthread_mutex_unlock(&cl->dev[dev].lock);
}
static FILE *fopen_stat(const char *filename, struct stat *st)
{
FILE *f = fopen(filename, "rb");
if(!f)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_fopen_stat] could not open file `%s'!\n", filename);
return NULL;
}
int fd = fileno(f);
if(fstat(fd, st) < 0)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_fopen_stat] could not stat file `%s'!\n", filename);
return NULL;
}
return f;
}
int dt_opencl_load_program(const int dev, const int prog, const char *filename, const char *binname,
const char *cachedir, char *md5sum, int *loaded_cached)
{
cl_int err;
dt_opencl_t *cl = darktable.opencl;
struct stat filestat, cachedstat;
*loaded_cached = 0;
if(prog < 0 || prog >= DT_OPENCL_MAX_PROGRAMS)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_load_source] invalid program number `%d' of file `%s'!\n", prog,
filename);
return 0;
}
if(cl->dev[dev].program_used[prog])
{
dt_print(DT_DEBUG_OPENCL,
"[opencl_load_source] program number `%d' already in use when loading file `%s'!\n", prog,
filename);
return 0;
}
FILE *f = fopen_stat(filename, &filestat);
if(!f) return 0;
size_t filesize = filestat.st_size;
char *file = (char *)malloc(filesize + 1024);
size_t rd = fread(file, sizeof(char), filesize, f);
fclose(f);
if(rd != filesize)
{
free(file);
dt_print(DT_DEBUG_OPENCL, "[opencl_load_source] could not read all of file `%s'!\n", filename);
return 0;
}
char *start = file + filesize;
char *end = start + 1024;
size_t len;
cl_device_id devid = cl->dev[dev].devid;
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DRIVER_VERSION, end - start, start, &len);
start += len;
cl_platform_id platform;
(cl->dlocl->symbols->dt_clGetDeviceInfo)(devid, CL_DEVICE_PLATFORM, sizeof(cl_platform_id), &platform, NULL);
(cl->dlocl->symbols->dt_clGetPlatformInfo)(platform, CL_PLATFORM_VERSION, end - start, start, &len);
start += len;
char *source_md5 = g_compute_checksum_for_data(G_CHECKSUM_MD5, (guchar *)file, start - file);
strncpy(md5sum, source_md5, 33);
g_free(source_md5);
file[filesize] = '\0';
char linkedfile[PATH_MAX] = { 0 };
ssize_t linkedfile_len = 0;
FILE *cached = fopen_stat(binname, &cachedstat);
if(cached)
{
if((linkedfile_len = readlink(binname, linkedfile, sizeof(linkedfile) - 1)) > 0)
{
linkedfile[linkedfile_len] = '\0';
if(strncmp(linkedfile, md5sum, 33) == 0)
{
// md5sum matches, load cached binary
size_t cached_filesize = cachedstat.st_size;
unsigned char *cached_content = (unsigned char *)malloc(cached_filesize + 1);
size_t rd = fread(cached_content, sizeof(char), cached_filesize, cached);
if(rd != cached_filesize)
{
dt_print(DT_DEBUG_OPENCL, "[opencl_load_program] could not read all of file `%s'!\n", binname);
}
else
{
cl->dev[dev].program[prog] = (cl->dlocl->symbols->dt_clCreateProgramWithBinary)(
cl->dev[dev].context, 1, &(cl->dev[dev].devid), &cached_filesize,
(const unsigned char **)&cached_content, NULL, &err);
if(err != CL_SUCCESS)
{
dt_print(DT_DEBUG_OPENCL,
"[opencl_load_program] could not load cached binary program from file `%s'! (%d)\n",
binname, err);
}
else
{
cl->dev[dev].program_used[prog] = 1;
*loaded_cached = 1;
}
}
free(cached_content);
}
}
fclose(cached);
}
if(*loaded_cached == 0)
{
// if loading cached was unsuccessful for whatever reason,