forked from heterodb/pg-strom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpu_service.c
3789 lines (3469 loc) · 97 KB
/
gpu_service.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
/*
* gpu_service.c
*
* A background worker process that handles any interactions with GPU
* ----
* Copyright 2011-2023 (C) KaiGai Kohei <[email protected]>
* Copyright 2014-2023 (C) PG-Strom Developers Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the PostgreSQL License.
*/
#include "pg_strom.h"
#include "cuda_common.h"
#include <cudaProfiler.h>
/*
* gpuContext / gpuMemory
*/
typedef struct
{
pthread_mutex_t lock;
bool is_managed; /* true, if managed memory pool */
size_t total_sz; /* total pool size */
size_t hard_limit;
size_t keep_limit;
dlist_head segment_list;
} gpuMemoryPool;
struct gpuContext
{
dlist_node chain;
int serv_fd; /* for accept(2) */
int cuda_dindex;
CUdevice cuda_device;
CUcontext cuda_context;
CUmodule cuda_module;
HTAB *cuda_type_htab;
HTAB *cuda_func_htab;
xpu_encode_info *cuda_encode_catalog;
gpuMemoryPool pool_raw;
gpuMemoryPool pool_managed;
bool cuda_profiler_started;
volatile uint32_t cuda_stack_limit; /* current configuration */
pthread_mutex_t cuda_setlimit_lock;
int gpumain_shmem_sz_dynamic;
/* GPU client */
pthread_mutex_t client_lock;
dlist_head client_list;
/* GPU workers */
pthread_mutex_t worker_lock;
dlist_head worker_list;
/* XPU commands */
pthread_cond_t cond;
pthread_mutex_t lock;
dlist_head command_list;
};
struct gpuClient
{
struct gpuContext *gcontext;/* per-device status */
dlist_node chain; /* gcontext->client_list */
kern_session_info *session; /* per session info (on cuda managed memory) */
struct gpuQueryBuffer *gq_buf; /* per query join/preagg device buffer */
pg_atomic_uint32 refcnt; /* odd number, if error status */
pthread_mutex_t mutex; /* mutex to write the socket */
int sockfd; /* connection to PG backend */
pthread_t worker; /* receiver thread */
};
#define GPUSERV_WORKER_KIND__GPUTASK 't'
#define GPUSERV_WORKER_KIND__GPUCACHE 'c'
typedef struct
{
dlist_node chain;
gpuContext *gcontext;
pthread_t worker;
char kind; /* one of GPUSERV_WORKER_KIND__* */
volatile bool termination;
} gpuWorker;
/*
* GPU service shared GPU variable
*/
//#define __SIGWAKEUP (__SIGRTMIN + 3)
#define __SIGWAKEUP SIGUSR2
typedef struct
{
volatile pid_t gpuserv_pid;
volatile bool gpuserv_ready_accept;
pg_atomic_uint32 max_async_tasks_updated;
pg_atomic_uint32 max_async_tasks;
pg_atomic_uint32 gpuserv_debug_output;
} gpuServSharedState;
/*
* variables
*/
static __thread int MY_DINDEX_PER_THREAD = -1;
static __thread CUdevice MY_DEVICE_PER_THREAD = -1;
static __thread CUcontext MY_CONTEXT_PER_THREAD = NULL;
static __thread CUstream MY_STREAM_PER_THREAD = NULL;
static __thread CUevent MY_EVENT_PER_THREAD = NULL;
static __thread gpuContext *GpuWorkerCurrentContext = NULL;
static volatile int gpuserv_bgworker_got_signal = 0;
static dlist_head gpuserv_gpucontext_list;
static int gpuserv_epoll_fdesc = -1;
static int gpuserv_logger_pipefd[2];
static FILE *gpuserv_logger_filp;
static StringInfoData gpuserv_logger_buffer;
static shmem_request_hook_type shmem_request_next = NULL;
static shmem_startup_hook_type shmem_startup_next = NULL;
static gpuServSharedState *gpuserv_shared_state = NULL;
static int __pgstrom_max_async_tasks_dummy;
static int __pgstrom_cuda_stack_limit_kb;
static bool __gpuserv_debug_output_dummy;
static char *pgstrom_cuda_toolkit_basedir = CUDA_TOOLKIT_BASEDIR; /* GUC */
static const char *pgstrom_fatbin_image_filename = "/dev/null";
static void
gpuservLoggerReport(const char *fmt, ...) pg_attribute_printf(1, 2);
#define __gsLog(fmt, ...) \
gpuservLoggerReport("GPU%d|LOG|%s|%d|%s|" fmt "\n", \
MY_DINDEX_PER_THREAD, \
__basename(__FILE__), \
__LINE__, __FUNCTION__, \
##__VA_ARGS__)
#define __gsDebug(fmt, ...) \
do { \
if (gpuserv_shared_state && \
pg_atomic_read_u32(&gpuserv_shared_state->gpuserv_debug_output) != 0) \
__gsLog(fmt, ##__VA_ARGS__); \
} while(0)
#define __gsDebugExtra(fmt, ...) \
do { \
if (gpuserv_shared_state && \
pg_atomic_read_u32(&gpuserv_shared_state->gpuserv_debug_output) != 0) \
{ \
const char *filename; \
uint32_t lineno; \
int errcode; \
char buffer[2048]; \
\
errcode = heterodbExtraGetError(&filename, \
&lineno, \
NULL, \
buffer, \
sizeof(buffer)); \
if (errcode == 0) \
__gsLog("heterodb-extra: " fmt, ##__VA_ARGS__); \
else \
__gsLog("heterodb-extra: " fmt " [%s] (code=%d, %s:%d)", \
##__VA_ARGS__, buffer, errcode, \
__basename(filename), lineno); \
} \
} while(0)
static void
gpuserv_debug_output_assign(bool newval, void *extra)
{
uint32_t ival = (newval ? 1 : 0);
if (gpuserv_shared_state)
pg_atomic_write_u32(&gpuserv_shared_state->gpuserv_debug_output, ival);
else
__gpuserv_debug_output_dummy = ival;
}
static const char *
gpuserv_debug_output_show(void)
{
if (gpuserv_shared_state)
{
if (pg_atomic_read_u32(&gpuserv_shared_state->gpuserv_debug_output) != 0)
return "on";
else
return "off";
}
return (__gpuserv_debug_output_dummy ? "on" : "off");
}
static void
pgstrom_max_async_tasks_assign(int newval, void *extra)
{
if (gpuserv_shared_state)
{
pid_t gpuserv_pid = gpuserv_shared_state->gpuserv_pid;
pg_atomic_write_u32(&gpuserv_shared_state->max_async_tasks, newval);
pg_atomic_write_u32(&gpuserv_shared_state->max_async_tasks_updated, 1);
if (gpuserv_pid != 0)
kill(gpuserv_pid, SIGUSR2);
}
else
__pgstrom_max_async_tasks_dummy = newval;
}
int
pgstrom_max_async_tasks(void)
{
return (gpuserv_shared_state
? pg_atomic_read_u32(&gpuserv_shared_state->max_async_tasks)
: __pgstrom_max_async_tasks_dummy);
}
static const char *
pgstrom_max_async_tasks_show(void)
{
return psprintf("%u", pgstrom_max_async_tasks());
}
/*
* gpuserv_ready_accept
*/
bool
gpuserv_ready_accept(void)
{
return (gpuserv_shared_state &&
gpuserv_shared_state->gpuserv_ready_accept);
}
/*
* gpuservLoggerOpen
*/
static void
gpuservLoggerOpen(void)
{
struct epoll_event ev;
if (pipe(gpuserv_logger_pipefd) != 0)
elog(ERROR, "failed on pipe(2): %m");
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.ptr = NULL;
if (epoll_ctl(gpuserv_epoll_fdesc,
EPOLL_CTL_ADD,
gpuserv_logger_pipefd[0], &ev) != 0)
elog(ERROR, "failed on epoll_ctl(2): %m");
gpuserv_logger_filp = fdopen(gpuserv_logger_pipefd[1], "ab");
initStringInfo(&gpuserv_logger_buffer);
}
/*
* gpuservLoggerDispatch
*/
static void
gpuservLoggerDispatch(void)
{
char *line, *tail;
Assert(!GpuWorkerCurrentContext);
/* read from pipe */
for (;;)
{
size_t unitsz = 2048;
ssize_t nbytes;
enlargeStringInfo(&gpuserv_logger_buffer, unitsz);
nbytes = read(gpuserv_logger_pipefd[0],
gpuserv_logger_buffer.data + gpuserv_logger_buffer.len,
unitsz);
if (nbytes < 0)
{
if (errno != EINTR)
elog(ERROR, "failed on read(gpuserv_logger_pipefd): %m");
}
else
{
gpuserv_logger_buffer.len += nbytes;
if (nbytes < unitsz)
break;
}
}
gpuserv_logger_buffer.data[gpuserv_logger_buffer.len] = '\0';
for (line = gpuserv_logger_buffer.data;
(tail = strchr(line, '\n')) != NULL;
line = tail + 1)
{
char *tok, *saveptr;
char *domain = "GPU?";
char *filename = "unknown file";
int lineno = -1;
char *funcname = "unknown function";
char *message = "unknown message";
int elevel = LOG;
*tail = '\0';
tok = strtok_r(line, "|", &saveptr);
if (tok)
domain = __trim(tok);
tok = strtok_r(NULL, "|", &saveptr);
if (tok)
{
char *elabel = __trim(tok);
if (strcmp(elabel, "DEBUG") == 0)
elevel = DEBUG1;
else if (strcmp(elabel, "NOTICE") == 0)
elevel = NOTICE;
else if (strcmp(elabel, "WARNING") == 0)
elevel = WARNING;
else
elevel = LOG;
}
tok = strtok_r(NULL, "|", &saveptr);
if (tok)
filename = __trim(tok);
tok = strtok_r(NULL, "|", &saveptr);
if (tok)
lineno = atoi(__trim(tok));
tok = strtok_r(NULL, "|", &saveptr);
if (tok)
{
funcname = __trim(tok);
message = saveptr;
}
if (errstart(elevel, domain))
{
errmsg("%s: %s", domain, message);
errfinish(filename, lineno, funcname);
}
}
if (*line != '\0' && line != gpuserv_logger_buffer.data)
{
size_t remained = strlen(line);
memmove(gpuserv_logger_buffer.data, line, remained+1);
gpuserv_logger_buffer.len = remained;
}
}
/*
* gpuservLoggerReport
*/
static void
gpuservLoggerReport(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(gpuserv_logger_filp, fmt, ap);
va_end(ap);
fflush(gpuserv_logger_filp);
}
/*
* cuStrError
*/
const char *
cuStrError(CUresult rc)
{
static __thread char buffer[300];
const char *err_name;
/* is it cufile error? */
if ((int)rc > CUFILEOP_BASE_ERR)
return cufileop_status_error((CUfileOpError)rc);
if (cuGetErrorName(rc, &err_name) == CUDA_SUCCESS)
return err_name;
snprintf(buffer, sizeof(buffer), "Unknown CUDA Error (%d)", (int)rc);
return buffer;
}
/* ----------------------------------------------------------------
*
* GPU Fatbin Builder
*
* ----------------------------------------------------------------
*/
/*
* __gpu_archtecture_label
*/
static const char *
__gpu_archtecture_label(int major_cc, int minor_cc)
{
int cuda_arch = major_cc * 100 + minor_cc;
switch (cuda_arch)
{
case 600: /* Tesla P100 */
return "sm_60";
case 601: /* Tesla P40 */
return "sm_61";
case 700: /* Tesla V100 */
return "sm_70";
case 705: /* Tesla T4 */
return "sm_75";
case 800: /* NVIDIA A100 */
return "sm_80";
case 806: /* NVIDIA A40 */
return "sm_86";
case 809: /* NVIDIA L40 */
return "sm_89";
case 900: /* NVIDIA H100 */
return "sm_90";
default:
elog(ERROR, "unsupported compute capability (%d.%d)",
major_cc, minor_cc);
}
return NULL;
}
/*
* __setup_gpu_fatbin_filename
*/
#define PGSTROM_FATBIN_DIR ".pgstrom_fatbin"
static void
__appendTextFromFile(StringInfo buf, const char *filename, const char *suffix)
{
char path[MAXPGPATH];
int fdesc;
snprintf(path, MAXPGPATH,
PGSHAREDIR "/pg_strom/%s%s", filename, suffix ? suffix : "");
fdesc = open(path, O_RDONLY);
if (fdesc < 0)
elog(ERROR, "could not open '%s': %m", path);
PG_TRY();
{
struct stat st_buf;
off_t remained;
ssize_t nbytes;
if (fstat(fdesc, &st_buf) != 0)
elog(ERROR, "failed on fstat('%s'): %m", path);
remained = st_buf.st_size;
enlargeStringInfo(buf, remained);
while (remained > 0)
{
nbytes = read(fdesc, buf->data + buf->len, remained);
if (nbytes < 0)
{
if (errno != EINTR)
elog(ERROR, "failed on read('%s'): %m", path);
}
else if (nbytes == 0)
{
elog(ERROR, "unable to read '%s' by the EOF", path);
}
else
{
Assert(nbytes <= remained);
buf->len += nbytes;
remained -= nbytes;
}
}
}
PG_CATCH();
{
close(fdesc);
PG_RE_THROW();
}
PG_END_TRY();
close(fdesc);
}
static char *
__setup_gpu_fatbin_filename(void)
{
int cuda_version = -1;
char hexsum[33]; /* 128bit hash */
char *namebuf;
char *tok, *pos;
const char *errstr;
ResourceOwner resowner_saved;
ResourceOwner resowner_dummy;
StringInfoData buf;
for (int i=0; i < numGpuDevAttrs; i++)
{
if (i == 0)
cuda_version = gpuDevAttrs[i].CUDA_DRIVER_VERSION;
else if (cuda_version != gpuDevAttrs[i].CUDA_DRIVER_VERSION)
elog(ERROR, "Bug? CUDA Driver version mismatch between devices");
}
namebuf = alloca(Max(sizeof(CUDA_CORE_HEADERS),
sizeof(CUDA_CORE_FILES)) + 1);
initStringInfo(&buf);
/* CUDA_CORE_HEADERS */
strcpy(namebuf, CUDA_CORE_HEADERS);
for (tok = strtok_r(namebuf, " ", &pos);
tok != NULL;
tok = strtok_r(NULL, " ", &pos))
{
__appendTextFromFile(&buf, tok, NULL);
}
/* CUDA_CORE_SRCS */
strcpy(namebuf, CUDA_CORE_FILES);
for (tok = strtok_r(namebuf, " ", &pos);
tok != NULL;
tok = strtok_r(NULL, " ", &pos))
{
__appendTextFromFile(&buf, tok, ".cu");
}
/*
* Calculation of MD5SUM. Note that pg_md5_hash internally use
* ResourceOwner to track openSSL memory, however, we may not
* have the CurrentResourceOwner during startup.
*/
resowner_saved = CurrentResourceOwner;
resowner_dummy = ResourceOwnerCreate(NULL, "MD5SUM Dummy");
PG_TRY();
{
CurrentResourceOwner = resowner_dummy;
if (!pg_md5_hash(buf.data, buf.len, hexsum, &errstr))
elog(ERROR, "could not compute MD5 hash: %s", errstr);
}
PG_CATCH();
{
CurrentResourceOwner = resowner_saved;
ResourceOwnerRelease(resowner_dummy,
RESOURCE_RELEASE_BEFORE_LOCKS,
false,
false);
ResourceOwnerDelete(resowner_dummy);
PG_RE_THROW();
}
PG_END_TRY();
CurrentResourceOwner = resowner_saved;
ResourceOwnerRelease(resowner_dummy,
RESOURCE_RELEASE_BEFORE_LOCKS,
true,
false);
ResourceOwnerDelete(resowner_dummy);
return psprintf("pgstrom-gpucode-V%06d-%s.fatbin",
cuda_version, hexsum);
}
/*
* __validate_gpu_fatbin_file
*/
static bool
__validate_gpu_fatbin_file(const char *fatbin_dir, const char *fatbin_file)
{
StringInfoData cmd;
StringInfoData buf;
FILE *filp;
char *temp;
bool retval = false;
initStringInfo(&cmd);
initStringInfo(&buf);
appendStringInfo(&buf, "%s/%s", fatbin_dir, fatbin_file);
if (access(buf.data, R_OK) != 0)
return false;
/* Pick up supported SM from the fatbin file */
appendStringInfo(&cmd,
"%s/bin/cuobjdump '%s/%s'"
" | grep '^arch '"
" | awk '{print $3}'",
pgstrom_cuda_toolkit_basedir,
fatbin_dir, fatbin_file);
filp = OpenPipeStream(cmd.data, "r");
if (!filp)
{
elog(LOG, "unable to run [%s]: %m", cmd.data);
goto out;
}
resetStringInfo(&buf);
for (;;)
{
ssize_t nbytes;
enlargeStringInfo(&buf, 512);
nbytes = fread(buf.data + buf.len, 1, 512, filp);
if (nbytes < 0)
{
if (errno != EINTR)
{
elog(LOG, "unable to read from pipe:[%s]: %m", cmd.data);
goto out;
}
}
else if (nbytes == 0)
{
if (feof(filp))
break;
elog(LOG, "unable to read from pipe:[%s]: %m", cmd.data);
goto out;
}
else
{
buf.len += nbytes;
}
}
ClosePipeStream(filp);
temp = alloca(buf.len + 1);
for (int i=0; i < numGpuDevAttrs; i++)
{
char *tok, *pos;
const char *label;
label = __gpu_archtecture_label(gpuDevAttrs[i].COMPUTE_CAPABILITY_MAJOR,
gpuDevAttrs[i].COMPUTE_CAPABILITY_MINOR);
memcpy(temp, buf.data, buf.len+1);
for (tok = strtok_r(temp, " \n\r", &pos);
tok != NULL;
tok = strtok_r(NULL, " \n\r", &pos))
{
if (strcmp(label, tok) == 0)
break; /* ok, supported */
}
if (!tok)
{
elog(LOG, "GPU%d '%s' CC%d.%d is not supported at '%s'",
i, gpuDevAttrs[i].DEV_NAME,
gpuDevAttrs[i].COMPUTE_CAPABILITY_MAJOR,
gpuDevAttrs[i].COMPUTE_CAPABILITY_MINOR,
fatbin_file);
goto out;
}
}
/* ok, this fatbin is validated */
retval = true;
out:
pfree(cmd.data);
pfree(buf.data);
return retval;
}
/*
* __rebuild_gpu_fatbin_file
*/
static void
__rebuild_gpu_fatbin_file(const char *fatbin_dir,
const char *fatbin_file)
{
StringInfoData cmd;
char workdir[200];
char *namebuf;
char *tok, *pos;
int count;
int status;
strcpy(workdir, "/tmp/.pgstrom_fatbin_build_XXXXXX");
if (!mkdtemp(workdir))
elog(ERROR, "unable to create work directory for fatbin rebuild");
elog(LOG, "PG-Strom fatbin image is not valid now, so rebuild in progress...");
namebuf = alloca(sizeof(CUDA_CORE_FILES) + 1);
strcpy(namebuf, CUDA_CORE_FILES);
initStringInfo(&cmd);
appendStringInfo(&cmd, "cd '%s' && (", workdir);
for (tok = strtok_r(namebuf, " ", &pos), count=0;
tok != NULL;
tok = strtok_r(NULL, " ", &pos), count++)
{
if (count > 0)
appendStringInfo(&cmd, " & ");
appendStringInfo(&cmd,
" /bin/sh -x -c '%s/bin/nvcc"
" --maxrregcount=%d"
" --source-in-ptx -lineinfo"
" -I. -I%s "
" -DHAVE_FLOAT2 "
" -arch=native --threads 4"
" --device-c"
" -o %s.o"
" %s/pg_strom/%s.cu' > %s.log 2>&1",
pgstrom_cuda_toolkit_basedir,
CUDA_MAXREGCOUNT,
PGINCLUDEDIR,
tok,
PGSHAREDIR, tok, tok);
}
appendStringInfo(&cmd,
") && wait;"
" /bin/sh -x -c '%s/bin/nvcc"
" -Xnvlink --suppress-stack-size-warning"
" -arch=native --threads 4"
" --device-link --fatbin"
" -o '%s'",
pgstrom_cuda_toolkit_basedir,
fatbin_file);
strcpy(namebuf, CUDA_CORE_FILES);
for (tok = strtok_r(namebuf, " ", &pos);
tok != NULL;
tok = strtok_r(NULL, " ", &pos))
{
appendStringInfo(&cmd, " %s.o", tok);
}
appendStringInfo(&cmd, "' > %s.log 2>&1", fatbin_file);
elog(LOG, "rebuild fatbin command: %s", cmd.data);
status = system(cmd.data);
if (status != 0)
elog(ERROR, "failed on the build process at [%s]", workdir);
/* validation of the fatbin file */
if (!__validate_gpu_fatbin_file(workdir, fatbin_file))
elog(ERROR, "failed on validation of the rebuilt fatbin at [%s]", workdir);
/* installation of the rebuilt fatbin */
resetStringInfo(&cmd);
appendStringInfo(&cmd,
"mkdir -p '%s'; "
"install -m 0644 %s/%s '%s'",
fatbin_dir,
workdir, fatbin_file, fatbin_dir);
strcpy(namebuf, CUDA_CORE_FILES);
for (tok = strtok_r(namebuf, " ", &pos);
tok != NULL;
tok = strtok_r(NULL, " ", &pos))
{
appendStringInfo(&cmd, "; cat %s/%s.log >> %s/%s.log",
workdir, tok,
PGSTROM_FATBIN_DIR, fatbin_file);
}
appendStringInfo(&cmd, "; cat %s/%s.log >> %s/%s.log",
workdir, fatbin_file,
PGSTROM_FATBIN_DIR, fatbin_file);
status = system(cmd.data);
if (status != 0)
elog(ERROR, "failed on shell command: %s", cmd.data);
}
static void
gpuservSetupFatbin(void)
{
const char *fatbin_file = __setup_gpu_fatbin_filename();
const char *fatbin_dir = PGSHAREDIR "/pg_strom";
char *path;
if (!__validate_gpu_fatbin_file(fatbin_dir,
fatbin_file))
{
fatbin_dir = PGSTROM_FATBIN_DIR;
if (!__validate_gpu_fatbin_file(fatbin_dir,
fatbin_file))
{
__rebuild_gpu_fatbin_file(fatbin_dir,
fatbin_file);
}
}
path = alloca(strlen(fatbin_dir) +
strlen(fatbin_file) + 100);
sprintf(path, "%s/%s", fatbin_dir, fatbin_file);
pgstrom_fatbin_image_filename = strdup(path);
if (!pgstrom_fatbin_image_filename)
elog(ERROR, "out of memory");
elog(LOG, "PG-Strom fatbin image is ready: %s", fatbin_file);
}
/* ----------------------------------------------------------------
*
* GPU Memory Allocator
*
* ----------------------------------------------------------------
*/
static int pgstrom_gpu_mempool_segment_sz_kb; /* GUC */
static double pgstrom_gpu_mempool_max_ratio; /* GUC */
static double pgstrom_gpu_mempool_min_ratio; /* GUC */
static int pgstrom_gpu_mempool_release_delay; /* GUC */
typedef struct
{
dlist_node chain;
gpuMemoryPool *pool; /* memory pool that owns this segment */
size_t segment_sz;
size_t active_sz; /* == 0 can be released */
CUdeviceptr devptr;
unsigned long iomap_handle; /* for legacy nvme_strom */
dlist_head free_chunks; /* list of free chunks */
dlist_head addr_chunks; /* list of ordered chunks */
struct timeval tval;
} gpuMemorySegment;
typedef struct
{
dlist_node free_chain;
dlist_node addr_chain;
gpuMemorySegment *mseg;
CUdeviceptr __base; /* base pointer of the segment */
size_t __offset; /* offset from the base */
size_t __length; /* length of the chunk */
CUdeviceptr m_devptr; /* __base + __offset */
} gpuMemChunk;
static gpuMemChunk *
__gpuMemAllocFromSegment(gpuMemoryPool *pool,
gpuMemorySegment *mseg,
size_t bytesize)
{
gpuMemChunk *chunk;
gpuMemChunk *buddy;
dlist_iter iter;
dlist_foreach(iter, &mseg->free_chunks)
{
chunk = dlist_container(gpuMemChunk, free_chain, iter.cur);
if (bytesize <= chunk->__length)
{
size_t surplus = chunk->__length - bytesize;
/* try to split, if free chunk is enough large (>4MB) */
if (surplus > (4UL << 20))
{
buddy = calloc(1, sizeof(gpuMemChunk));
if (!buddy)
{
__gsDebug("out of memory");
return NULL; /* out of memory */
}
chunk->__length -= surplus;
buddy->mseg = mseg;
buddy->__base = mseg->devptr;
buddy->__offset = chunk->__offset + chunk->__length;
buddy->__length = surplus;
buddy->m_devptr = (buddy->__base + buddy->__offset);
dlist_insert_after(&chunk->free_chain, &buddy->free_chain);
dlist_insert_after(&chunk->addr_chain, &buddy->addr_chain);
}
/* mark it as an active chunk */
dlist_delete(&chunk->free_chain);
memset(&chunk->free_chain, 0, sizeof(dlist_node));
mseg->active_sz += chunk->__length;
/* update the LRU ordered segment list and timestamp */
gettimeofday(&mseg->tval, NULL);
dlist_move_head(&pool->segment_list, &mseg->chain);
return chunk;
}
}
return NULL;
}
static gpuMemorySegment *
__gpuMemAllocNewSegment(gpuMemoryPool *pool, size_t segment_sz)
{
gpuMemorySegment *mseg = calloc(1, sizeof(gpuMemorySegment));
gpuMemChunk *chunk = calloc(1, sizeof(gpuMemChunk));
CUresult rc;
if (!mseg || !chunk)
goto error;
mseg->pool = pool;
mseg->segment_sz = segment_sz;
mseg->active_sz = 0;
dlist_init(&mseg->free_chunks);
dlist_init(&mseg->addr_chunks);
if (pool->is_managed)
{
rc = cuMemAllocManaged(&mseg->devptr, mseg->segment_sz,
CU_MEM_ATTACH_GLOBAL);
if (rc != CUDA_SUCCESS)
{
__gsDebug("failed on cuMemAllocManaged(sz=%lu): %s",
mseg->segment_sz, cuStrError(rc));
goto error;
}
memset((void *)mseg->devptr, 0, mseg->segment_sz);
}
else
{
rc = cuMemAlloc(&mseg->devptr, mseg->segment_sz);
if (rc != CUDA_SUCCESS)
{
__gsDebug("failed on cuMemAlloc(sz=%lu): %s",
mseg->segment_sz, cuStrError(rc));
goto error;
}
if (!gpuDirectMapGpuMemory(mseg->devptr,
mseg->segment_sz,
&mseg->iomap_handle))
{
__gsDebugExtra("failed on gpuDirectMapGpuMemory");
goto error;
}
}
chunk->mseg = mseg;
chunk->__base = mseg->devptr;
chunk->__offset = 0;
chunk->__length = segment_sz;
chunk->m_devptr = (chunk->__base + chunk->__offset);
dlist_push_head(&mseg->free_chunks, &chunk->free_chain);
dlist_push_head(&mseg->addr_chunks, &chunk->addr_chain);
dlist_push_head(&pool->segment_list, &mseg->chain);
pool->total_sz += segment_sz;
return mseg;
error:
if (mseg->devptr)
cuMemFree(mseg->devptr);
if (mseg)
free(mseg);
if (chunk)
free(chunk);
return NULL;
}
static gpuMemChunk *
__gpuMemAllocCommon(gpuMemoryPool *pool, size_t bytesize)
{
dlist_iter iter;
size_t segment_sz;
gpuMemChunk *chunk = NULL;
bytesize = PAGE_ALIGN(bytesize);
pthreadMutexLock(&pool->lock);
dlist_foreach(iter, &pool->segment_list)
{
gpuMemorySegment *mseg = dlist_container(gpuMemorySegment,
chain, iter.cur);
if (mseg->active_sz + bytesize <= mseg->segment_sz)
{
chunk = __gpuMemAllocFromSegment(pool, mseg, bytesize);
if (chunk)
goto out_unlock;
}
}
segment_sz = ((size_t)pgstrom_gpu_mempool_segment_sz_kb << 10);
if (segment_sz < bytesize)
segment_sz = bytesize;
/*
* total consumption of mapped GPU memory must be less than
* the hard-limit of the memory pool.
*/
if (pool->is_managed ||
pool->total_sz + segment_sz <= pool->hard_limit)
{
gpuMemorySegment *mseg = __gpuMemAllocNewSegment(pool, segment_sz);
if (mseg)
chunk = __gpuMemAllocFromSegment(pool, mseg, bytesize);
}
out_unlock:
pthreadMutexUnlock(&pool->lock);
return (chunk ? chunk : NULL);
}
static gpuMemChunk *
gpuMemAlloc(size_t bytesize)
{
return __gpuMemAllocCommon(&GpuWorkerCurrentContext->pool_raw, bytesize);
}
static gpuMemChunk *
gpuMemAllocManaged(size_t bytesize)
{
return __gpuMemAllocCommon(&GpuWorkerCurrentContext->pool_managed, bytesize);
}
static void
gpuMemFree(gpuMemChunk *chunk)
{
gpuMemoryPool *pool;
gpuMemorySegment *mseg;
gpuMemChunk *buddy;
dlist_node *dnode;
Assert(!chunk->free_chain.prev && !chunk->free_chain.next);
mseg = chunk->mseg;
pool = mseg->pool;
pthreadMutexLock(&pool->lock);
/* revert this chunk state to 'free' */
mseg->active_sz -= chunk->__length;
dlist_push_head(&mseg->free_chunks,
&chunk->free_chain);
/* try merge if next chunk is also free */
if (dlist_has_next(&mseg->addr_chunks,
&chunk->addr_chain))
{
dnode = dlist_next_node(&mseg->addr_chunks,
&chunk->addr_chain);
buddy = dlist_container(gpuMemChunk,
addr_chain, dnode);
if (buddy->free_chain.prev && buddy->addr_chain.next)
{
Assert(chunk->__offset +
chunk->__length == buddy->__offset);
dlist_delete(&buddy->free_chain);
dlist_delete(&buddy->addr_chain);
chunk->__length += buddy->__length;