forked from kaigai/pg_strom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cuda_serv.c
1743 lines (1590 loc) · 54.9 KB
/
cuda_serv.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
/*
* cuda_serv.c
*
* The background computing engine stick on the CUDA infrastructure.
* In addition, it also provide catalog of supported type and functions.
*
* --
* Copyright 2011-2012 (c) KaiGai Kohei <kaigai@kaigai.gr.jp>
*
* This software is an extension of PostgreSQL; You can use, copy,
* modify or distribute it under the terms of 'LICENSE' included
* within this package.
*/
#include "postgres.h"
#include "access/hash.h"
#include "access/htup_details.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#include "pg_strom.h"
#include "cuda_cmds.h"
#include <cuda.h>
#include <unistd.h>
/*
* Local type definitions
*/
typedef struct {
CUdevice device;
CUcontext context;
CUmodule module;
CUfunction kernel_qual;
char dev_name[256];
int dev_major;
int dev_minor;
int dev_proc_nums;
int dev_proc_warp_sz;
int dev_proc_clock;
size_t dev_global_mem_sz;
int dev_global_mem_width;
int dev_global_mem_clock;
int dev_shared_mem_size;
int dev_const_mem_size;
int dev_l2_cache_size;
int dev_max_block_dim_x;
int dev_max_block_dim_y;
int dev_max_block_dim_z;
int dev_max_grid_dim_x;
int dev_max_grid_dim_y;
int dev_max_grid_dim_z;
int dev_max_threads_per_proc;
int dev_max_regs_per_block;
int dev_integrated;
int dev_unified_addr;
int dev_can_map_hostmem;
int dev_concurrent_kernel;
int dev_concurrent_memcpy;
int dev_pci_busid;
int dev_pci_deviceid;
} GpuDevState;
typedef struct {
ShmsegList chain;
ChunkBuffer *chunk;
CUcontext context; /* reference to GpuDevState */
CUfunction kernel_qual; /* reference to GpuDevState */
CUstream stream;
CUdeviceptr devmem;
CUevent events[4];
} GpuExecState;
/*
* Local variables
*/
#define MAX_NUM_LOAD_SERVS 32
#define MAX_NUM_POLL_SERVS 4
static const char *pgstrom_gpu_error_string(CUresult errcode);
static int gpu_device_nums;
static GpuDevState *gpu_device_state;
static int gpu_num_load_servs;
static int gpu_num_poll_servs;
static pthread_t gpu_load_servs[MAX_NUM_LOAD_SERVS];
static pthread_t gpu_poll_servs[MAX_NUM_POLL_SERVS];
static ShmsegQueue *gpu_load_cmdq;
static ShmsegQueue gpu_poll_cmdq;
static List *gpu_type_info_slot[128];
static List *gpu_func_info_slot[512];
static void *
pgstrom_gpu_poll_serv(void *argv)
{
GpuExecState *gexec;
ChunkBuffer *chunk;
ShmsegList *item;
CUcontext dummy;
int index;
float elapsed;
CUresult ret;
while ((item = pgstrom_shmqueue_dequeue(&gpu_poll_cmdq)) != NULL)
{
gexec = container_of(item, GpuExecState, chain);
chunk = gexec->chunk;
ret = cuCtxPushCurrent(gexec->context);
Assert(ret == CUDA_SUCCESS);
/*
* XXX: We have no interface to synchronize at least one stream
* that complete all the tasks inside of the stream, so we try
* to synchronize the earliest stream being enqueued.
* Heuristically, it almost matches with order of completion.
* It is an idea to increase number of threads for chunk-poller.
*/
if (chunk->pf_enabled)
ret = cuEventSynchronize(gexec->events[3]);
else
ret = cuStreamSynchronize(gexec->stream);
if (ret != CUDA_SUCCESS)
{
chunk->status = CHUNKBUF_STATUS_ERROR;
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed on stream synchronization (%s)",
pgstrom_gpu_error_string(ret));
}
else
{
chunk->status = CHUNKBUF_STATUS_READY;
if (chunk->pf_enabled)
{
ret = cuEventElapsedTime(&elapsed,
gexec->events[0],
gexec->events[1]);
chunk->pf_async_memcpy = (uint64)(elapsed * 1000.0);
ret = cuEventElapsedTime(&elapsed,
gexec->events[1],
gexec->events[2]);
chunk->pf_async_kernel = (uint64)(elapsed * 1000.0);
ret = cuEventElapsedTime(&elapsed,
gexec->events[2],
gexec->events[3]);
chunk->pf_async_memcpy += (uint64)(elapsed * 1000.0);
}
}
ret = cuMemFree(gexec->devmem);
Assert(ret == CUDA_SUCCESS);
if (chunk->pf_enabled)
{
for (index=0; index < lengthof(gexec->events); index++)
{
ret = cuEventDestroy(gexec->events[index]);
Assert(ret == CUDA_SUCCESS);
}
}
ret = cuStreamDestroy(gexec->stream);
Assert(ret == CUDA_SUCCESS);
cuCtxPopCurrent(&dummy);
/*
* Back the chunk-buffer to its originator
*/
pgstrom_shmqueue_enqueue(chunk->recv_cmdq, &chunk->chain);
free(gexec);
}
elog(FATAL, "%s should not exit", __FUNCTION__);
return NULL;
}
static int
pgstrom_gpu_schedule(ChunkBuffer *chunk)
{
static int next_gpu_scheduled = 0;
/*
* TODO: more wise scheduling policy, rather than round-robin.
* IDEA: based on length of pending queue, computing capabilities, ...
*/
return __sync_fetch_and_add(&next_gpu_scheduled, 1) % gpu_device_nums;
}
static bool
pgstrom_gpu_exec_kernel(ChunkBuffer *chunk)
{
GpuExecState *gexec;
CUcontext dummy;
CUdeviceptr kernel_data[5];
void *kernel_args[5];
CUresult ret;
int index;
int n_blocks;
int n_threads;
gexec = malloc(sizeof(GpuExecState));
if (!gexec)
{
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"PG-Strom: failed on GpuExecState allocation");
goto error_0;
}
memset(gexec, 0, sizeof(GpuExecState));
gexec->chunk = chunk;
index = pgstrom_gpu_schedule(chunk);
gexec->context = gpu_device_state[index].context;
gexec->kernel_qual = gpu_device_state[index].kernel_qual;
ret = cuCtxPushCurrent(gexec->context);
if (ret != CUDA_SUCCESS)
{
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed on switch context (%s)",
pgstrom_gpu_error_string(ret));
goto error_1;
}
ret = cuStreamCreate(&gexec->stream, 0);
if (ret != CUDA_SUCCESS)
{
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed on create stream (%s)",
pgstrom_gpu_error_string(ret));
goto error_2;
}
if (chunk->pf_enabled)
{
for (index=0; index < lengthof(gexec->events); index++)
{
/*
* XXX - Now we're under investigation why CU_EVENT_DEFAULT
* lock out synchronization mechanism. Thus, it is unavailable
* to obtain elapsed time between asyncronous operations.
*/
ret = cuEventCreate(&gexec->events[index],
CU_EVENT_DISABLE_TIMING);
if (ret != CUDA_SUCCESS)
{
while (--index >= 0)
cuEventDestroy(gexec->events[index]);
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed on create event object (%s)",
pgstrom_gpu_error_string(ret));
goto error_3;
}
}
}
/*
* Allocation of the device memory
*/
ret = cuMemAlloc(&gexec->devmem, chunk->dma_length);
if (ret != CUDA_SUCCESS)
{
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed on allocate device memory (%s)",
pgstrom_gpu_error_string(ret));
goto error_4;
}
/*
* Asynchronous copy of chunk buffer from host to device
*/
if (chunk->pf_enabled)
{
ret = cuEventRecord(gexec->events[0], gexec->stream);
if (ret != CUDA_SUCCESS)
{
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed on enqueue prep HtoD copy event (%s)",
pgstrom_gpu_error_string(ret));
goto error_5;
}
}
ret = cuMemcpyHtoDAsync(gexec->devmem,
chunk->dma_buffer,
chunk->dma_length,
gexec->stream);
if (ret != CUDA_SUCCESS)
{
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed on enqueue cuMemcpyHtoDAsync (%s)",
pgstrom_gpu_error_string(ret));
goto error_5;
}
if (chunk->pf_enabled)
{
ret = cuEventRecord(gexec->events[1], gexec->stream);
if (ret != CUDA_SUCCESS)
{
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed on enqueue post HtoD copy event (%s)",
pgstrom_gpu_error_string(ret));
goto error_5;
}
}
/*
* Asynchronous kernel execution on this chunk buffer
*/
ret = cuFuncGetAttribute(&n_threads,
CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
gexec->kernel_qual);
if (ret != CUDA_SUCCESS)
{
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed to obtain max threads / block ratio (%s)",
pgstrom_gpu_error_string(ret));
goto error_6;
}
kernel_data[0] = chunk->nitems; /* int nitems */
kernel_args[0] = &kernel_data[0];
kernel_data[1] = gexec->devmem + ((char *)chunk->gpu_cmds -
(char *)chunk->dma_buffer);
kernel_args[1] = &kernel_data[1]; /* int commands[] */
kernel_data[2] = gexec->devmem + ((char *)chunk->cs_isnull -
(char *)chunk->dma_buffer);
kernel_args[2] = &kernel_data[2]; /* int cs_isnull[] */
kernel_data[3] = gexec->devmem + ((char *)chunk->cs_values -
(char *)chunk->dma_buffer);
kernel_args[3] = &kernel_data[3]; /* int cs_values[] */
kernel_data[4] = gexec->devmem + ((char *)chunk->cs_rowmap -
(char *)chunk->dma_buffer);
kernel_args[4] = &kernel_data[4]; /* uchar cs_rowmap[] */
n_blocks = ((chunk->nitems + n_threads * BITS_PER_BYTE - 1) /
(n_threads * BITS_PER_BYTE));
ret = cuLaunchKernel(gexec->kernel_qual,
n_blocks, 1, 1,
n_threads, 1, 1,
0,
gexec->stream,
kernel_args,
NULL);
if (ret != CUDA_SUCCESS)
{
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed on enqueue an execution of kernel "
"(n_block=%u, b_threads=%u) : %s", n_blocks, n_threads,
pgstrom_gpu_error_string(ret));
goto error_6;
}
/*
* Write back of the result
*/
if (chunk->pf_enabled)
{
ret = cuEventRecord(gexec->events[2], gexec->stream);
if (ret != CUDA_SUCCESS)
{
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed on enqueue prep DtoH copy event (%s)",
pgstrom_gpu_error_string(ret));
goto error_5;
}
}
ret = cuMemcpyDtoHAsync(chunk->cs_rowmap,
gexec->devmem + (uintptr_t)(chunk->cs_rowmap -
chunk->dma_buffer),
chunk->nitems / BITS_PER_BYTE,
gexec->stream);
if (ret != CUDA_SUCCESS)
{
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed on enqueue cuMemcpyDtoHAsync (%s)",
pgstrom_gpu_error_string(ret));
goto error_6;
}
if (chunk->pf_enabled)
{
ret = cuEventRecord(gexec->events[3], gexec->stream);
if (ret != CUDA_SUCCESS)
{
snprintf(chunk->error_msg, sizeof(chunk->error_msg),
"cuda: failed on enqueue post DtoH copy event (%s)",
pgstrom_gpu_error_string(ret));
goto error_5;
}
}
/*
* A series of sequence were successfully enqueued, so we'll wait
* for completion of the commands by chunk-poller server.
*/
pgstrom_shmqueue_enqueue(&gpu_poll_cmdq, &gexec->chain);
cuCtxPopCurrent(&dummy);
return true;
error_6:
cuStreamSynchronize(gexec->stream);
error_5:
cuMemFree(gexec->devmem);
error_4:
if (chunk->pf_enabled)
{
for (index=0; index < lengthof(gexec->events); index++)
cuEventDestroy(gexec->events[index]);
}
error_3:
cuStreamDestroy(gexec->stream);
error_2:
cuCtxPopCurrent(&dummy);
error_1:
free(gexec);
error_0:
return false;
}
static void *
pgstrom_gpu_load_serv(void *argv)
{
ChunkBuffer *chunk;
ShmsegList *item;
struct timeval tv;
while ((item = pgstrom_shmqueue_dequeue(gpu_load_cmdq)) != NULL)
{
chunk = container_of(item, ChunkBuffer, chain);
Assert(chunk->status == CHUNKBUF_STATUS_EXEC);
Assert(chunk->gpu_cmds != NULL);
Assert(chunk->cs_isnull != NULL);
Assert(chunk->cs_values != NULL);
Assert(chunk->cs_rowmap != NULL);
Assert(((char *)chunk->gpu_cmds - (char *)chunk->dma_buffer) >= 0);
Assert(((char *)chunk->gpu_cmds -
(char *)chunk->dma_buffer) < chunk->dma_length);
Assert(((char *)chunk->cs_isnull - (char *)chunk->dma_buffer) >= 0);
Assert(((char *)chunk->cs_isnull -
(char *)chunk->dma_buffer) < chunk->dma_length);
Assert(((char *)chunk->cs_values - (char *)chunk->dma_buffer) >= 0);
Assert(((char *)chunk->cs_values -
(char *)chunk->dma_buffer) < chunk->dma_length);
Assert(((char *)chunk->cs_rowmap - (char *)chunk->dma_buffer) >= 0);
Assert(((char *)chunk->cs_rowmap -
(char *)chunk->dma_buffer) < chunk->dma_length);
if (chunk->pf_enabled)
{
gettimeofday(&tv, NULL);
chunk->pf_queue_wait += TIMEVAL_ELAPSED(&chunk->pf_timeval, &tv);
}
if (!pgstrom_gpu_exec_kernel(chunk))
{
chunk->status = CHUNKBUF_STATUS_ERROR;
pgstrom_shmqueue_enqueue(chunk->recv_cmdq, &chunk->chain);
}
}
elog(FATAL, "%s should not exit", __FUNCTION__);
return NULL;
}
void pgstrom_gpu_enqueue_chunk(ChunkBuffer *chunk)
{
pgstrom_shmqueue_enqueue(gpu_load_cmdq, &chunk->chain);
}
int
pgstrom_gpu_num_devices(void)
{
return gpu_device_nums;
}
/*
* pgstrom_gpu_startup
*
* A callback routine just after shared memory segment was attached.
*
*/
void
pgstrom_gpu_startup(void *shmptr, Size shmsize)
{
CUresult ret;
char *shmbase;
char namebuf[MAXPGPATH];
char *kernel_path;
bytea *kernel_bytea;
char *kernel_image;
int i;
/*
* register shared memory segment as page-locked memory
*/
shmbase = (void *)(((uintptr_t) shmptr) & ~(getpagesize() - 1));
shmsize = ((((uintptr_t) shmptr & (getpagesize() - 1))
+ shmsize + getpagesize() - 1)
& ~(getpagesize() - 1));
ret = cuMemHostRegister(shmbase, shmsize,
CU_MEMHOSTREGISTER_PORTABLE);
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed lock shared memory segment (%s)",
pgstrom_gpu_error_string(ret));
elog(LOG, "cuda: 0x%p - 0x%p were locked for DMA buffer",
shmbase, ((char *)shmbase) + shmsize);
/*
* Create a command queue from backend to chunk-loader
*/
gpu_load_cmdq = pgstrom_shmseg_alloc(sizeof(ShmsegQueue));
if (!gpu_load_cmdq)
elog(ERROR, "PG-Strom: out of shared memory");
if (!pgstrom_shmqueue_init(gpu_load_cmdq))
elog(ERROR, "PG-Strom: failed to init shmqueue of chunk-loader");
/*
* Create a command queue from chunk-loader to chunk-poller
* (this command queue is in local memory)
*/
if (!pgstrom_shmqueue_init(&gpu_poll_cmdq))
elog(ERROR, "PG-Strom: failed to init shmqueue of chunk-poller");
/*
* Load the module for each devices
*/
get_share_path(my_exec_path, namebuf);
kernel_path = alloca(strlen(namebuf) + 40);
sprintf(kernel_path, "%s/extension/cuda_kernel.ptx", namebuf);
kernel_bytea = read_binary_file(kernel_path, 0, -1);
kernel_image = text_to_cstring(kernel_bytea);
for (i=0; i < gpu_device_nums; i++)
{
CUcontext dummy;
CUmodule module;
CUfunction kernel_qual;
int fn_max_threads;
int fn_num_regs;
int fn_ptx_version;
int fn_bin_version;
ret = cuCtxPushCurrent(gpu_device_state[i].context);
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to switch context (%s)",
pgstrom_gpu_error_string(ret));
// TODO: JIT options using cuModuleLoadDataEx
ret = cuModuleLoadData(&module, kernel_image);
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to load module (%s)",
pgstrom_gpu_error_string(ret));
ret = cuModuleGetFunction(&kernel_qual, module, "kernel_qual");
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to resolve \"kernel_qual\" (%s)",
pgstrom_gpu_error_string(ret));
ret = cuFuncSetCacheConfig(kernel_qual, CU_FUNC_CACHE_PREFER_L1);
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to switch L1 cache preference (%s)",
pgstrom_gpu_error_string(ret));
if ((ret = cuFuncGetAttribute(&fn_max_threads,
CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
kernel_qual)) != CUDA_SUCCESS ||
(ret = cuFuncGetAttribute(&fn_num_regs,
CU_FUNC_ATTRIBUTE_NUM_REGS,
kernel_qual)) != CUDA_SUCCESS ||
(ret = cuFuncGetAttribute(&fn_ptx_version,
CU_FUNC_ATTRIBUTE_PTX_VERSION,
kernel_qual)) != CUDA_SUCCESS ||
(ret = cuFuncGetAttribute(&fn_bin_version,
CU_FUNC_ATTRIBUTE_BINARY_VERSION,
kernel_qual)) != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to get attribute of the kernel (%s)",
pgstrom_gpu_error_string(ret));
gpu_device_state[i].module = module;
gpu_device_state[i].kernel_qual = kernel_qual;
elog(LOG, "function \"kernel_qual\" on device[%d] %s; "
"threads/block ratio = %d, regs/thread ratio = %d, "
"ptx version = %d, binary version = %d",
i, gpu_device_state[i].dev_name,
fn_max_threads, fn_num_regs, fn_ptx_version, fn_bin_version);
ret = cuCtxPopCurrent(&dummy);
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to switch context (%s)",
pgstrom_gpu_error_string(ret));
}
pfree(kernel_image);
pfree(kernel_bytea);
/*
* Launch the chunk-loader servers
*/
for (i=0; i < gpu_num_load_servs; i++)
{
if (pthread_create(&gpu_load_servs[i], NULL,
pgstrom_gpu_load_serv, NULL) != 0)
elog(ERROR, "PG-Strom: failed to launch chunk-loader server");
}
/*
* Launch the chunk-poller servers
*/
for (i=0; i < gpu_num_poll_servs; i++)
{
if (pthread_create(&gpu_poll_servs[i], NULL,
pgstrom_gpu_poll_serv, NULL) != 0)
elog(ERROR, "PG-Strom: failed to launch chunk-poller server");
}
}
/*
* pgstrom_gpu_init
*
* init routine of cuda calculation server
*/
void pgstrom_gpu_init(void)
{
CUresult ret;
int i, j;
memset(gpu_type_info_slot, 0, sizeof(gpu_type_info_slot));
memset(gpu_func_info_slot, 0, sizeof(gpu_func_info_slot));
/*
* GUC Parameters
*/
DefineCustomIntVariable("pg_strom.num_load_servs",
"number of servers to load chunks to devices",
NULL,
&gpu_num_load_servs,
2,
1,
MAX_NUM_LOAD_SERVS,
PGC_POSTMASTER,
0,
NULL, NULL, NULL);
DefineCustomIntVariable("pg_strom.num_poll_servs",
"number of servers to poll chunks to be ready",
NULL,
&gpu_num_poll_servs,
1,
1,
MAX_NUM_POLL_SERVS,
PGC_POSTMASTER,
0,
NULL, NULL, NULL);
/*
* Initialize CUDA API
*/
ret = cuInit(0);
if (ret != CUDA_SUCCESS)
elog(ERROR, "CUDA: failed to initialize driver API (%s)",
pgstrom_gpu_error_string(ret));
/*
* Collect device properties
*/
ret = cuDeviceGetCount(&gpu_device_nums);
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to get number of devices (%s)",
pgstrom_gpu_error_string(ret));
gpu_device_state = malloc(sizeof(GpuDevState) * gpu_device_nums);
if (!gpu_device_state)
elog(ERROR, "out of memory");
for (i=0; i < gpu_device_nums; i++)
{
GpuDevState *devstate = &gpu_device_state[i];
static struct {
size_t offset;
CUdevice_attribute attribute;
} device_attrs[] = {
{ offsetof(GpuDevState, dev_proc_nums),
CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT },
{ offsetof(GpuDevState, dev_proc_warp_sz),
CU_DEVICE_ATTRIBUTE_WARP_SIZE },
{ offsetof(GpuDevState, dev_proc_clock),
CU_DEVICE_ATTRIBUTE_CLOCK_RATE },
{ offsetof(GpuDevState, dev_global_mem_clock),
CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE },
{ offsetof(GpuDevState, dev_shared_mem_size),
CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK },
{ offsetof(GpuDevState, dev_const_mem_size),
CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY },
{ offsetof(GpuDevState, dev_l2_cache_size),
CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE },
{ offsetof(GpuDevState, dev_max_block_dim_x),
CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X },
{ offsetof(GpuDevState, dev_max_block_dim_y),
CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y },
{ offsetof(GpuDevState, dev_max_block_dim_z),
CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z },
{ offsetof(GpuDevState, dev_max_grid_dim_x),
CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X },
{ offsetof(GpuDevState, dev_max_grid_dim_y),
CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y },
{ offsetof(GpuDevState, dev_max_grid_dim_z),
CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z },
{ offsetof(GpuDevState, dev_max_regs_per_block),
CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK },
{ offsetof(GpuDevState, dev_max_threads_per_proc),
CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR },
{ offsetof(GpuDevState, dev_integrated ),
CU_DEVICE_ATTRIBUTE_INTEGRATED },
{ offsetof(GpuDevState, dev_unified_addr),
CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING },
{ offsetof(GpuDevState, dev_can_map_hostmem),
CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY },
{ offsetof(GpuDevState, dev_concurrent_kernel),
CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS},
{ offsetof(GpuDevState, dev_concurrent_memcpy),
CU_DEVICE_ATTRIBUTE_GPU_OVERLAP },
{ offsetof(GpuDevState, dev_pci_busid),
CU_DEVICE_ATTRIBUTE_PCI_BUS_ID },
{ offsetof(GpuDevState, dev_pci_deviceid),
CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID },
};
ret = cuDeviceGet(&devstate->device, i);
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to get device handler (%s)",
pgstrom_gpu_error_string(ret));
ret = cuCtxCreate(&devstate->context, 0, devstate->device);
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to create device context (%s)",
pgstrom_gpu_error_string(ret));
ret = cuDeviceGetName(devstate->dev_name,
sizeof(devstate->dev_name),
devstate->device);
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to get device name (%s)",
pgstrom_gpu_error_string(ret));
ret = cuDeviceComputeCapability(&devstate->dev_major,
&devstate->dev_minor,
devstate->device);
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to get computing capability (%s)",
pgstrom_gpu_error_string(ret));
ret = cuDeviceTotalMem(&devstate->dev_global_mem_sz, devstate->device);
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to get size of global memory (%s)",
pgstrom_gpu_error_string(ret));
for (j=0; j < lengthof(device_attrs); j++)
{
ret = cuDeviceGetAttribute((int *)((uintptr_t) devstate +
device_attrs[j].offset),
device_attrs[j].attribute,
devstate->device);
if (ret != CUDA_SUCCESS)
elog(ERROR, "cuda: failed to get attribute of device (%s)",
pgstrom_gpu_error_string(ret));
}
/*
* Logs of the device properties
*/
elog(LOG, "PG-Strom: GPU device[%d] %s; capability v%d.%d, "
"%d of streaming processor units (%d wraps per unit, %dMHz)",
i, devstate->dev_name, devstate->dev_major, devstate->dev_minor,
devstate->dev_proc_nums, devstate->dev_proc_warp_sz,
devstate->dev_proc_clock / 1000);
}
}
/*
* pgstrom_gpu_info(int dindex)
*
* This function shows properties of installed GPU devices.
* If dev_index is null, it shows properties of all the devices.
*/
Datum
pgstrom_gpu_info(PG_FUNCTION_ARGS)
{
FuncCallContext *fncxt;
GpuDevState *dev;
StringInfoData str;
uint32 devindex;
uint32 property;
HeapTuple tuple;
Datum values[3];
bool isnull[3];
if (SRF_IS_FIRSTCALL())
{
TupleDesc tupdesc;
MemoryContext oldcxt;
fncxt = SRF_FIRSTCALL_INIT();
oldcxt = MemoryContextSwitchTo(fncxt->multi_call_memory_ctx);
tupdesc = CreateTemplateTupleDesc(3, false);
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "device_id",
INT4OID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 2, "attribute",
TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 3, "value",
TEXTOID, -1, 0);
fncxt->tuple_desc = BlessTupleDesc(tupdesc);
fncxt->user_fctx = NULL;
MemoryContextSwitchTo(oldcxt);
}
fncxt = SRF_PERCALL_SETUP();
if (PG_GETARG_INT32(0) < 0)
{
devindex = fncxt->call_cntr / 22;
property = fncxt->call_cntr % 22;
if (devindex >= gpu_device_nums)
SRF_RETURN_DONE(fncxt);
}
else
{
devindex = PG_GETARG_INT32(0);
if (devindex >= gpu_device_nums)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("GPU device %d does not exist", devindex)));
if (fncxt->call_cntr >= 22)
SRF_RETURN_DONE(fncxt);
property = fncxt->call_cntr;
}
dev = &gpu_device_state[devindex];
initStringInfo(&str);
memset(isnull, false, sizeof(isnull));
values[0] = Int32GetDatum(devindex);
switch (property)
{
case 0:
values[1] = CStringGetTextDatum("name");
appendStringInfo(&str, "%s", dev->dev_name);
break;
case 1:
values[1] = CStringGetTextDatum("capability");
appendStringInfo(&str, "%d.%d", dev->dev_major, dev->dev_minor);
break;
case 2:
values[1] = CStringGetTextDatum("num of procs");
appendStringInfo(&str, "%d", dev->dev_proc_nums);
break;
case 3:
values[1] = CStringGetTextDatum("wrap per proc");
appendStringInfo(&str, "%d", dev->dev_proc_warp_sz);
break;
case 4:
values[1] = CStringGetTextDatum("clock of proc");
appendStringInfo(&str, "%d MHz", dev->dev_proc_clock / 1000);
break;
case 5:
values[1] = CStringGetTextDatum("global mem size");
appendStringInfo(&str, "%lu MB", (dev->dev_global_mem_sz >> 20));
break;
case 6:
values[1] = CStringGetTextDatum("global mem width");
appendStringInfo(&str, "%d bits", dev->dev_global_mem_width);
break;
case 7:
values[1] = CStringGetTextDatum("global mem clock");
appendStringInfo(&str, "%d MHz", dev->dev_global_mem_clock / 1000);
break;
case 8:
values[1] = CStringGetTextDatum("shared mem size");
appendStringInfo(&str, "%d KB", dev->dev_shared_mem_size / 1024);
break;
case 9:
values[1] = CStringGetTextDatum("const mem size");
appendStringInfo(&str, "%d KB", dev->dev_const_mem_size / 1024);
break;
case 10:
values[1] = CStringGetTextDatum("L2 cache size");
appendStringInfo(&str, "%d KB", dev->dev_l2_cache_size / 1024);
break;
case 11:
values[1] = CStringGetTextDatum("max block size");
appendStringInfo(&str, "{%d, %d, %d}",
dev->dev_max_block_dim_x,
dev->dev_max_block_dim_y,
dev->dev_max_block_dim_z);
break;
case 12:
values[1] = CStringGetTextDatum("max grid size");
appendStringInfo(&str, "{%d, %d, %d}",
dev->dev_max_grid_dim_x,
dev->dev_max_grid_dim_y,
dev->dev_max_grid_dim_z);
break;
case 13:
values[1] = CStringGetTextDatum("max threads per proc");
appendStringInfo(&str, "%d", dev->dev_max_threads_per_proc);
break;
case 14:
values[1] = CStringGetTextDatum("max registers per block");
appendStringInfo(&str, "%d", dev->dev_max_regs_per_block);
break;
case 15:
values[1] = CStringGetTextDatum("integrated memory");
appendStringInfo(&str, "%s",
(dev->dev_integrated ? "yes" : "no"));
break;
case 16:
values[1] = CStringGetTextDatum("unified address");
appendStringInfo(&str, "%s",
(dev->dev_unified_addr ? "yes" : "no"));
break;
case 17:
values[1] = CStringGetTextDatum("map host memory");
appendStringInfo(&str, "%s",
(dev->dev_can_map_hostmem ? "yes" : "no"));
break;
case 18:
values[1] = CStringGetTextDatum("concurrent kernel");
appendStringInfo(&str, "%s",
(dev->dev_concurrent_kernel ? "yes" : "no"));
break;
case 19:
values[1] = CStringGetTextDatum("concurrent memcpy");
appendStringInfo(&str, "%s",
(dev->dev_concurrent_memcpy ? "yes" : "no"));
break;
case 20:
values[1] = CStringGetTextDatum("pci bus-id");
appendStringInfo(&str, "%d", dev->dev_pci_busid);
break;
case 21:
values[1] = CStringGetTextDatum("pci device-id");
appendStringInfo(&str, "%d", dev->dev_pci_deviceid);
break;
default:
elog(ERROR, "unexpected property : %d", property);
break;
}
values[2] = CStringGetTextDatum(str.data);
tuple = heap_form_tuple(fncxt->tuple_desc, values, isnull);
pfree(str.data);
SRF_RETURN_NEXT(fncxt, HeapTupleGetDatum(tuple));
}
PG_FUNCTION_INFO_V1(pgstrom_gpu_info);
/*
* pgstrom_gpu_error_string
*
* returns a text representation of the supplied cuda error.
*/
static const char *
pgstrom_gpu_error_string(CUresult errcode)
{
static char strbuf[256];
switch (errcode)
{
case CUDA_SUCCESS:
return "success";
case CUDA_ERROR_INVALID_VALUE:
return "invalid value";
case CUDA_ERROR_OUT_OF_MEMORY:
return "out of memory";
case CUDA_ERROR_NOT_INITIALIZED:
return "not initialized";
case CUDA_ERROR_DEINITIALIZED:
return "deinitialized";
case CUDA_ERROR_PROFILER_DISABLED:
return "profiler disabled";
case CUDA_ERROR_PROFILER_NOT_INITIALIZED:
return "profiler not initialized";
case CUDA_ERROR_PROFILER_ALREADY_STARTED:
return "profiler already started";
case CUDA_ERROR_PROFILER_ALREADY_STOPPED:
return "profiler already stopped";