forked from heterodb/pg-strom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpu_cache.c
4606 lines (4214 loc) · 121 KB
/
gpu_cache.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_cache.c
*
* GPU data cache that syncronizes a PostgreSQL table
* ----
* 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"
//#define GPUCACHE_DEBUG_MESSAGE 1
/*
* GpuCacheControlCommand
*/
#define GCACHE_CONTROL_CMD__APPLY_REDO 'A'
#define GCACHE_CONTROL_CMD__COMPACTION 'C'
#define GCACHE_CONTROL_CMD__DROP_UNLOAD 'D'
#define GCACHE_CONTROL_CMD__ERRORBUF_SIZE 120
typedef struct
{
dlist_node chain;
GpuCacheIdent ident;
Latch *backend;
int command; /* one of GCACHE_CONTROL_CMD__* */
uint64_t end_pos; /* for APPLY_REDO */
int errcode;
char errbuf[GCACHE_CONTROL_CMD__ERRORBUF_SIZE];
} GpuCacheControlCommand;
/*
* GpuCacheSharedHead (shared structure; static)
*/
typedef struct
{
/* pg_strom.gpucache_auto_preload related */
int32 gcache_auto_preload_count;
NameData gcache_auto_preload_dbname;
/* Mutex for creation of GpuCacheSharedState shared-memory segment */
pthread_mutex_t gcache_sstate_mutex;
/* IPC to GpuService background workers */
pthread_mutex_t gcache_cmd_mutex;
dlist_head gcache_free_cmds;
GpuCacheControlCommand __gcache_control_cmds[100];
struct {
pthread_cond_t cond;
dlist_head queue;
} gpus[FLEXIBLE_ARRAY_MEMBER]; /* per GPU device */
} GpuCacheSharedHead;
/*
* GpuCacheOptions
*/
typedef struct
{
Oid tg_sync_row;
int cuda_dindex;
int32 gpu_sync_interval;
size_t gpu_sync_threshold;
int64 max_num_rows;
int64 rowid_hash_nslots;
size_t redo_buffer_size;
} GpuCacheOptions;
INLINE_FUNCTION(bool)
GpuCacheOptionsEqual(const GpuCacheOptions *a, const GpuCacheOptions *b)
{
return (a->tg_sync_row == b->tg_sync_row &&
a->cuda_dindex == b->cuda_dindex &&
a->gpu_sync_interval == b->gpu_sync_interval &&
a->gpu_sync_threshold == b->gpu_sync_threshold &&
a->max_num_rows == b->max_num_rows &&
a->rowid_hash_nslots == b->rowid_hash_nslots &&
a->redo_buffer_size == b->redo_buffer_size);
}
/*
* GpuCacheTableSignatureBuffer
*/
typedef struct
{
Oid reltablespace;
Oid relfilenode; /* if 0, cannot have gpucache */
int16 relnatts;
GpuCacheOptions gc_options;
struct {
Oid atttypid;
int32 atttypmod;
int16 attlen;
bool attbyval;
char attalign;
bool attnotnull;
bool attisdropped;
} attrs[FLEXIBLE_ARRAY_MEMBER];
} GpuCacheTableSignatureBuffer;
typedef struct
{
Oid table_oid;
uint64_t signature;
GpuCacheOptions gc_options;
} GpuCacheTableSignatureCache;
/*
* GpuCacheSharedState (shared structure; dynamic memory mapped)
*/
typedef struct
{
char magic[8]; /* = "GpuCache" */
GpuCacheIdent ident;
char table_name[NAMEDATALEN]; /* for debug */
uint64_t rowid_map_offset;
uint64_t redo_buffer_offset;
/* GpuCache configuration parameters */
GpuCacheOptions gc_options;
/* current status */
#define GCACHE_PHASE__NOT_BUILT 0 /* not built yet */
#define GCACHE_PHASE__IS_EMPTY 1 /* not initial loaded */
#define GCACHE_PHASE__IS_LOADING 2 /* now initial loading */
#define GCACHE_PHASE__IS_READY 3 /* now ready */
#define GCACHE_PHASE__IS_CORRUPTED 4 /* corrupted */
pg_atomic_uint32 phase;
/* device memory allocation (just for information) */
pg_atomic_uint64 gcache_main_size;
pg_atomic_uint64 gcache_main_nitems;
pg_atomic_uint64 gcache_extra_size;
pg_atomic_uint64 gcache_extra_usage; /* used in extra buffer (incl dead space) */
pg_atomic_uint64 gcache_extra_dead; /* dead space in extra buffer */
/* rowid-map propertoes */
pthread_mutex_t rowid_mutex;
uint32_t rowid_next_free;
uint32_t rowid_num_free;
/* redo buffer properties */
pthread_mutex_t redo_mutex;
uint64_t redo_write_timestamp;
uint64_t redo_write_nitems;
uint64_t redo_write_pos;
uint64_t redo_read_nitems;
uint64_t redo_read_pos;
uint64_t redo_sync_pos;
/* schema definitions (KDS_FORMAT_COLUMN) */
size_t kds_extra_sz;
kern_data_store kds_head;
} GpuCacheSharedState;
#define GpuCacheSharedStateName(nameBuf,nameLen,datOid,relOid,signature) \
snprintf((nameBuf), (nameLen), \
".gpucache_p%u_d%u_r%u.%09lx.buf", \
PostPortNumber, (datOid), (relOid), (signature))
/*
* GpuCacheRowIdItem
*/
typedef struct
{
uint32_t next;
ItemPointerData ctid;
uint16_t __padding__;
} GpuCacheRowIdItem;
INLINE_FUNCTION(char *)
gpuCacheRedoLogBuffer(GpuCacheSharedState *gc_sstate)
{
return (char *)gc_sstate + gc_sstate->redo_buffer_offset;
}
INLINE_FUNCTION(uint32_t *)
gpuCacheRowIdHashSlot(GpuCacheSharedState *gc_sstate)
{
return (uint32_t *)((char *)gc_sstate + gc_sstate->rowid_map_offset);
}
INLINE_FUNCTION(GpuCacheRowIdItem *)
gpuCacheRowIdItemArray(GpuCacheSharedState *gc_sstate)
{
return (GpuCacheRowIdItem *)
(gpuCacheRowIdHashSlot(gc_sstate) + gc_sstate->gc_options.rowid_hash_nslots);
}
/*
* GpuCacheLocalMapping
*/
typedef struct
{
dlist_node chain;
GpuCacheIdent ident;
int refcnt;
GpuCacheSharedState *gc_sstate;
size_t mmap_sz;
/* fields below are valid only GpuService context */
pthread_rwlock_t gcache_rwlock;
CUdeviceptr gcache_main_devptr;
CUdeviceptr gcache_extra_devptr;
ssize_t gcache_main_size;
ssize_t gcache_extra_size;
} GpuCacheLocalMapping;
/*
* GpuCacheDesc (GpuCache Descriptor per backend)
*/
struct GpuCacheDesc
{
GpuCacheIdent ident;
TransactionId xid;
GpuCacheOptions gc_options;
GpuCacheLocalMapping *gc_lmap;
bool drop_on_rollback;
bool drop_on_commit;
uint32_t nitems;
StringInfoData buf; /* array of PendingCtidItem */
};
typedef struct
{
uint32_t rowid;
char tag;
ItemPointerData ctid;
} PendingCtidItem;
/* --- static variables --- */
static char *pgstrom_gpucache_auto_preload; /* GUC */
static bool pgstrom_enable_gpucache; /* GUC */
static GpuCacheSharedHead *gcache_shared_head = NULL;
static HTAB *gcache_descriptors_htab = NULL;
static HTAB *gcache_signatures_htab = NULL;
static shmem_request_hook_type shmem_request_next = NULL;
static shmem_startup_hook_type shmem_startup_next = NULL;
static object_access_hook_type object_access_next = NULL;
/* --- function declarations --- */
static void __gpuCacheAppendLog(GpuCacheDesc *gc_desc,
GCacheTxLogCommon *tx_log);
static void gpuCacheInvokeDropUnload(const GpuCacheDesc *gc_desc,
bool is_async);
void gpuCacheStartupPreloader(Datum arg);
/*
* gpucache_sync_trigger_function_oid
*/
static Oid __gpucache_sync_trigger_function_oid = InvalidOid;
static Oid
gpucache_sync_trigger_function_oid(void)
{
if (!OidIsValid(__gpucache_sync_trigger_function_oid))
{
Oid namespace_oid;
oidvector argtypes;
namespace_oid = get_namespace_oid("pgstrom", true);
if (!OidIsValid(namespace_oid))
return InvalidOid;
memset(&argtypes, 0, sizeof(oidvector));
SET_VARSIZE(&argtypes, offsetof(oidvector, values[0]));
argtypes.ndim = 1;
argtypes.dataoffset = 0;
argtypes.elemtype = OIDOID;
argtypes.dim1 = 0;
argtypes.lbound1 = 0;
__gpucache_sync_trigger_function_oid
= GetSysCacheOid3(PROCNAMEARGSNSP,
Anum_pg_proc_oid,
CStringGetDatum("gpucache_sync_trigger"),
PointerGetDatum(&argtypes),
ObjectIdGetDatum(namespace_oid));
}
return __gpucache_sync_trigger_function_oid;
}
static inline bool
is_gpucache_sync_trigger(int16 trig_type,
char trig_enabled,
Oid trig_func_oid,
int16 trig_nargs)
{
if (trig_type == (TRIGGER_TYPE_ROW |
TRIGGER_TYPE_AFTER |
TRIGGER_TYPE_INSERT |
TRIGGER_TYPE_DELETE |
TRIGGER_TYPE_UPDATE) &&
(trig_enabled == TRIGGER_FIRES_ON_ORIGIN ||
trig_enabled == TRIGGER_FIRES_ALWAYS) &&
trig_func_oid == gpucache_sync_trigger_function_oid() &&
(trig_nargs == 0 || trig_nargs == 1))
{
return true;
}
return false;
}
/*
* parseSyncTriggerOptions
*/
static bool
__parseSyncTriggerOptions(int elevel,
Form_pg_class pg_class,
FormData_pg_attribute *pg_attrs,
Oid trigger_oid,
const char *trigger_name,
const char *trigger_config,
GpuCacheOptions *gc_options)
{
int cuda_dindex = 0; /* default: GPU0 */
int gpu_sync_interval = 5000000L; /* default: 5sec = 5000000us */
ssize_t gpu_sync_threshold = -1; /* default: auto */
int64 max_num_rows = (10UL << 20); /* default: 10M rows */
int64 rowid_hash_nslots = -1; /* default: auto */
ssize_t redo_buffer_size = (160UL << 20); /* default: 160MB */
char *config;
char *key, *value;
char *saved;
size_t main_sz = 0;
size_t extra_sz = 0;
int unitsz;
if (!trigger_config)
goto out;
config = alloca(strlen(trigger_config) + 1);
strcpy(config, trigger_config);
for (key = strtok_r(config, ",", &saved);
key != NULL;
key = strtok_r(NULL, ",", &saved))
{
value = strchr(key, '=');
if (!value)
{
elog(elevel, "gpucache: options syntax error [%s]", key);
return false;
}
*value++ = '\0';
key = __trim(key);
value = __trim(value);
if (strcmp(key, "gpu_device_id") == 0)
{
int gpu_device_id;
gpu_device_id = __strtol(value);
if (errno != 0)
{
elog(elevel, "gpucache: invalid option [%s]=[%s] : %m", key, value);
return false;
}
cuda_dindex = -1;
for (int i=0; i < numGpuDevAttrs; i++)
{
if (gpuDevAttrs[i].DEV_ID == gpu_device_id)
{
cuda_dindex = i;
break;
}
}
if (cuda_dindex < 0)
{
elog(elevel, "gpucache: gpu_device_id (%d) not found", gpu_device_id);
return false;
}
}
else if (strcmp(key, "max_num_rows") == 0)
{
max_num_rows = __strtol(value);
if (errno != 0)
{
elog(elevel, "gpucache: invalid option [%s]=[%s] : %m", key, value);
return false;
}
}
else if (strcmp(key, "gpu_sync_interval") == 0)
{
gpu_sync_interval = __strtol(value);
if (errno != 0)
{
elog(elevel, "gpucache: invalid option [%s]=[%s] : %m", key, value);
return false;
}
gpu_sync_interval *= 1000000L; /* [sec -> us] */
}
else if (strcmp(key, "gpu_sync_threshold") == 0)
{
gpu_sync_threshold = __strtosz(value);
if (errno != 0)
{
elog(elevel, "gpucache: invalid option [%s]=[%s]", key, value);
return false;
}
}
else if (strcmp(key, "redo_buffer_size") == 0)
{
redo_buffer_size = __strtosz(value);
if (errno != 0)
{
elog(elevel, "gpucache: invalid option [%s]=[%s]", key, value);
return false;
}
}
else
{
elog(elevel, "gpucache: unknown option [%s]=[%s]", key, value);
}
}
out:
/* default configuration (auto adjustment) */
if (gpu_sync_threshold < 0)
gpu_sync_threshold = redo_buffer_size / 4;
if (rowid_hash_nslots < 0)
rowid_hash_nslots = (max_num_rows + max_num_rows / 5);
/*
* validate configuration parameters
*/
if (redo_buffer_size < (16UL << 20))
{
elog(elevel, "gpucache: 'redo_buffer_size' is too small (%zu)",
redo_buffer_size);
return false;
}
if (gpu_sync_threshold < Max(redo_buffer_size / 20, (4UL << 20)))
{
elog(elevel, "gpucache: 'gpu_sync_threshold' is too small (must be larger than [%zu])", Max(redo_buffer_size/20, (4UL<<20)));
return false;
}
if (gpu_sync_threshold > redo_buffer_size / 2)
{
elog(elevel, "gpucache: 'gpu_sync_threshold' is too large (must be smaller than [%zu]", redo_buffer_size / 2);
return false;
}
if (max_num_rows >= UINT_MAX)
{
elog(elevel, "gpucache: max_num_rows too large (%lu)", max_num_rows);
return false;
}
/* check initial kds_column/kds_extra size */
for (int j=0; j < pg_class->relnatts; j++)
{
Form_pg_attribute attr = &pg_attrs[j];
if (!attr->attnotnull)
main_sz += MAXALIGN(BITMAPLEN(max_num_rows));
if (attr->attlen > 0)
{
unitsz = att_align_nominal(attr->attlen,
attr->attalign);
main_sz += MAXALIGN(unitsz * max_num_rows);
}
else if (attr->attlen == -1)
{
main_sz += MAXALIGN(sizeof(uint32_t) * max_num_rows);
unitsz = get_typavgwidth(attr->atttypid,
attr->atttypmod);
extra_sz += MAXALIGN(unitsz) * max_num_rows;
}
else
{
elog(elevel, "unexpected type length (%d) for type %s",
(int)attr->attlen,
format_type_be(attr->atttypid));
return false;
}
}
main_sz += (MAXALIGN(offsetof(kern_data_store, /* KDS Header */
colmeta[pg_class->relnatts+1])) +
MAXALIGN(sizeof(GpuCacheSysattr) * max_num_rows)); /* System Column */
if (extra_sz > 0)
{
/* 25% margin + header */
extra_sz += extra_sz / 4;
extra_sz += offsetof(kern_data_extra, data);
}
if (main_sz >= __KDS_LENGTH_LIMIT || extra_sz >= __KDS_LENGTH_LIMIT)
{
elog(elevel, "gpucache: max_num_rows = %ld consumes too much GPU device memory (main: %s, extra: %s), so we recommend to reduce 'max_num_rows' configuration",
max_num_rows,
format_bytesz(main_sz),
format_bytesz(extra_sz));
return false;
}
/*
* write back to the caller
*/
if (gc_options)
{
gc_options->tg_sync_row = trigger_oid;
gc_options->cuda_dindex = cuda_dindex;
gc_options->gpu_sync_interval = gpu_sync_interval;
gc_options->gpu_sync_threshold = gpu_sync_threshold;
gc_options->max_num_rows = max_num_rows;
gc_options->rowid_hash_nslots = rowid_hash_nslots;
gc_options->redo_buffer_size = redo_buffer_size;
}
return true;
}
/* ------------------------------------------------------------
*
* Routines to manage the table signature
*
* In some cases we have to rebuild GpuCache even if the cached-table is still
* valid. For example, add/remove columns by ALTER TABLE, enables/disables
* the trigger function to synchronize GpuCache and so on.
* The table signature is a simple and lightweight way to detect these cases.
* ------------------------------------------------------------
*/
static uint64_t
gpuCacheTableSignatureCommon(int elevel,
Form_pg_class pg_class,
FormData_pg_attribute *pg_attrs,
Oid trigger_oid,
const char *trigger_name,
const char *trigger_config,
GpuCacheOptions *gc_options) /* out */
{
GpuCacheTableSignatureBuffer *sig;
int nattrs = pg_class->relnatts;
size_t len;
len = offsetof(GpuCacheTableSignatureBuffer,
attrs[pg_class->relnatts]);
sig = alloca(len);
memset(sig, 0, len);
sig->reltablespace = pg_class->reltablespace;
sig->relfilenode = pg_class->relfilenode;
sig->relnatts = pg_class->relnatts;
for (int j=0; j < nattrs; j++)
{
Form_pg_attribute attr = &pg_attrs[j];
sig->attrs[j].atttypid = attr->atttypid;
sig->attrs[j].atttypmod = attr->atttypmod;
sig->attrs[j].attlen = attr->attlen;
sig->attrs[j].attbyval = attr->attbyval;
sig->attrs[j].attalign = attr->attalign;
sig->attrs[j].attnotnull = attr->attnotnull;
sig->attrs[j].attisdropped = attr->attisdropped;
}
if (!__parseSyncTriggerOptions(elevel,
pg_class,
pg_attrs,
trigger_oid,
trigger_name,
trigger_config,
&sig->gc_options))
return 0UL;
if (gc_options)
memcpy(gc_options, &sig->gc_options, sizeof(GpuCacheOptions));
return (uint64_t)hash_any((unsigned char *)sig, len) | 0x100000000UL;
}
static void
__gpuCacheTableSignature(Relation rel, GpuCacheTableSignatureCache *entry)
{
TupleDesc tupdesc = RelationGetDescr(rel);
Form_pg_class rel_form = RelationGetForm(rel);
TriggerDesc *trigdesc = rel->trigdesc;
Oid trigger_oid = InvalidOid;
const char *trigger_name = NULL;
const char *trigger_config = NULL;
if (rel_form->relkind != RELKIND_RELATION &&
rel_form->relkind != RELKIND_PARTITIONED_TABLE)
goto no_gpu_cache;
if (rel_form->relfilenode == 0)
goto no_gpu_cache;
if (trigdesc)
{
for (int i=0; i < trigdesc->numtriggers; i++)
{
Trigger *trig = &trigdesc->triggers[i];
if (is_gpucache_sync_trigger(trig->tgtype,
trig->tgenabled,
trig->tgfoid,
trig->tgnargs))
{
if (OidIsValid(trigger_oid))
goto no_gpu_cache;
if (trig->tgnargs == 1)
trigger_config = trig->tgargs[0];
else
Assert(trig->tgnargs == 0);
trigger_oid = trig->tgoid;
trigger_name = trig->tgname;
}
}
if (OidIsValid(trigger_oid))
{
entry->signature
= gpuCacheTableSignatureCommon(WARNING,
rel_form,
tupdesc->attrs,
trigger_oid,
trigger_name,
trigger_config,
&entry->gc_options);
if (entry->signature != 0UL)
return;
}
}
no_gpu_cache:
memset(&entry->gc_options, 0, sizeof(GpuCacheOptions));
entry->gc_options.cuda_dindex = -1;
entry->signature = 0;
}
static inline uint64_t
gpuCacheTableSignature(Relation rel, GpuCacheOptions *gc_options)
{
GpuCacheTableSignatureCache *entry;
Oid table_oid = RelationGetRelid(rel);
bool found;
entry = hash_search(gcache_signatures_htab,
&table_oid, HASH_ENTER, &found);
if (!found)
{
Assert(entry->table_oid == table_oid);
PG_TRY();
{
__gpuCacheTableSignature(rel, entry);
}
PG_CATCH();
{
hash_search(gcache_signatures_htab,
&table_oid, HASH_REMOVE, NULL);
PG_RE_THROW();
}
PG_END_TRY();
}
if (gc_options)
memcpy(gc_options, &entry->gc_options, sizeof(GpuCacheOptions));
return entry->signature;
}
static uint64_t
__gpuCacheTableSignatureSnapshot(Form_pg_class pg_class,
Snapshot snapshot,
GpuCacheOptions *gc_options)
{
FormData_pg_attribute *pg_attrs;
Oid table_oid = pg_class->oid;
Oid trigger_oid = InvalidOid;
const char *trigger_name = NULL;
const char *trigger_config = NULL;
Relation srel;
ScanKeyData skey[2];
SysScanDesc sscan;
HeapTuple tuple;
/* pg_class */
if (pg_class->relkind != RELKIND_RELATION &&
pg_class->relkind != RELKIND_PARTITIONED_TABLE)
return 0UL;
if (pg_class->relfilenode == 0)
return 0UL;
if (!pg_class->relhastriggers)
return 0UL;
/* pg_trigger */
srel = table_open(TriggerRelationId, AccessShareLock);
ScanKeyInit(&skey[0],
Anum_pg_trigger_tgrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(table_oid));
sscan = systable_beginscan(srel, TriggerRelidNameIndexId,
true, snapshot, 1, skey);
while ((tuple = systable_getnext(sscan)) != NULL)
{
Form_pg_trigger pg_trig = (Form_pg_trigger) GETSTRUCT(tuple);
if (is_gpucache_sync_trigger(pg_trig->tgtype,
pg_trig->tgenabled,
pg_trig->tgfoid,
pg_trig->tgnargs))
{
if (OidIsValid(trigger_oid)) /* duplicate triggers */
{
systable_endscan(sscan);
table_close(srel, AccessShareLock);
return 0UL;
}
if (pg_trig->tgnargs == 1)
{
Datum datum;
bool isnull;
datum = heap_getattr(tuple,
Anum_pg_trigger_tgargs,
RelationGetDescr(srel),
&isnull);
if (!isnull)
trigger_config = TextDatumGetCString(datum);
}
trigger_oid = pg_trig->oid;
trigger_name = pstrdup(NameStr(pg_trig->tgname));
}
}
systable_endscan(sscan);
table_close(srel, AccessShareLock);
if (!OidIsValid(trigger_oid))
return 0UL;
/* pg_attribute */
srel = table_open(AttributeRelationId, AccessShareLock);
ScanKeyInit(&skey[0],
Anum_pg_attribute_attrelid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(table_oid));
ScanKeyInit(&skey[1],
Anum_pg_attribute_attnum,
BTGreaterStrategyNumber, F_INT2GT,
Int16GetDatum(0));
sscan = systable_beginscan(srel, AttributeRelidNumIndexId,
true, snapshot, 2, skey);
pg_attrs = alloca(sizeof(FormData_pg_attribute) * pg_class->relnatts);
memset(pg_attrs, 0, sizeof(FormData_pg_attribute) * pg_class->relnatts);
while ((tuple = systable_getnext(sscan)) != NULL)
{
Form_pg_attribute attr = (Form_pg_attribute) GETSTRUCT(tuple);
Assert(attr->attnum > 0 && attr->attnum <= pg_class->relnatts);
memcpy(&pg_attrs[attr->attnum-1], attr,
sizeof(FormData_pg_attribute));
}
systable_endscan(sscan);
table_close(srel, AccessShareLock);
/* parse & validate options */
return gpuCacheTableSignatureCommon(WARNING,
pg_class,
pg_attrs,
trigger_oid,
trigger_name,
trigger_config,
gc_options);
}
static uint64_t
gpuCacheTableSignatureSnapshot(Oid table_oid,
Snapshot snapshot,
GpuCacheOptions *gc_options)
{
Relation srel;
ScanKeyData skey;
SysScanDesc sscan;
HeapTuple tuple;
uint64_t signature = 0UL;
/* pg_class */
srel = table_open(RelationRelationId, AccessShareLock);
ScanKeyInit(&skey,
Anum_pg_class_oid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(table_oid));
sscan = systable_beginscan(srel, ClassOidIndexId,
true, snapshot, 1, &skey);
tuple = systable_getnext(sscan);
if (HeapTupleIsValid(tuple))
{
Form_pg_class pg_class = (Form_pg_class)GETSTRUCT(tuple);
signature = __gpuCacheTableSignatureSnapshot(pg_class,
snapshot,
gc_options);
}
systable_endscan(sscan);
table_close(srel, AccessShareLock);
return signature;
}
/*
* gpuCacheTableSignatureInvalidation
*/
static void
gpuCacheTableSignatureInvalidation(Oid table_oid)
{
hash_search(gcache_signatures_htab,
&table_oid, HASH_REMOVE, NULL);
}
/* ------------------------------------------------------------
*
* Routines to manage GpuCacheSharedState
*
* ------------------------------------------------------------
*/
#define GCACHE_SHARED_MAPPING_NSLOTS 79
static pthread_mutex_t gcache_shared_mapping_lock;
static dlist_head gcache_shared_mapping_slot[GCACHE_SHARED_MAPPING_NSLOTS];
static inline dlist_head *
__gpuCacheSharedMappingHashSlot(Oid database_oid,
Oid table_oid,
uint64_t signature)
{
GpuCacheIdent hkey;
uint32_t hash;
hkey.database_oid = database_oid;
hkey.table_oid = table_oid;
hkey.signature = signature;
hash = hash_any((unsigned char *)&hkey, sizeof(hkey));
return &gcache_shared_mapping_slot[hash % GCACHE_SHARED_MAPPING_NSLOTS];
}
/*
* __setup_kern_data_store_column
*/
static void
__setup_kern_data_store_column(kern_data_store *kds_head,
size_t *p_extra_sz,
Relation rel,
uint32_t nrooms)
{
TupleDesc tupdesc = RelationGetDescr(rel);
kern_colmeta *cmeta;
size_t sz, off;
size_t unitsz;
size_t extra_sz = 0;
setup_kern_data_store(kds_head, tupdesc, 0, KDS_FORMAT_COLUMN);
kds_head->table_oid = RelationGetRelid(rel);
kds_head->column_nrooms = nrooms;
Assert(kds_head->nr_colmeta > tupdesc->natts);
off = KDS_HEAD_LENGTH(kds_head);
for (int j=0; j < tupdesc->natts; j++)
{
Form_pg_attribute attr = TupleDescAttr(tupdesc, j);
cmeta = &kds_head->colmeta[j];
if (!attr->attnotnull)
{
sz = MAXALIGN(BITMAPLEN(nrooms));
cmeta->nullmap_offset = __kds_packed(off);
cmeta->nullmap_length = __kds_packed(sz);
off += sz;
}
if (attr->attlen > 0)
{
unitsz = att_align_nominal(attr->attlen,
attr->attalign);
sz = MAXALIGN(unitsz * nrooms);
cmeta->values_offset = __kds_packed(off);
cmeta->values_length = __kds_packed(sz);
off += sz;
}
else if (attr->attlen == -1)
{
sz = MAXALIGN(sizeof(uint32) * nrooms);
cmeta->values_offset = __kds_packed(off);
cmeta->values_length = __kds_packed(sz);
off += sz;
unitsz = get_typavgwidth(attr->atttypid,
attr->atttypmod);
extra_sz += MAXALIGN(unitsz) * nrooms;
}
else
{
elog(ERROR, "unexpected type length (%d) at %s.%s",
attr->attlen,
RelationGetRelationName(rel),
NameStr(attr->attname));
}
}
/* system column */
cmeta = &kds_head->colmeta[kds_head->nr_colmeta - 1];
sz = MAXALIGN(cmeta->attlen * nrooms);
cmeta->values_offset = __kds_packed(off);
cmeta->values_length = __kds_packed(sz);
off += sz;
kds_head->length = off;
/* varlena buffer size */
if (extra_sz > 0)
{
/* 25% margin */
extra_sz += extra_sz / 4;
extra_sz += offsetof(kern_data_extra, data);
}
*p_extra_sz = extra_sz;
}
/*
* __openGpuCacheSharedState
*
* NOTE: caller must hold gcache_shared_mapping_lock
*/
static GpuCacheLocalMapping *
__openGpuCacheSharedState(Oid database_oid,
Oid table_oid,
uint64_t signature,
bool try_open_if_corrupted,
char *errbuf, size_t errbuf_sz)
{
int fdesc = -1;
struct stat stat_buf;
char namebuf[MAXPGPATH];
size_t off;
dlist_head *hslot;
GpuCacheSharedState *gc_sstate = MAP_FAILED;
GpuCacheLocalMapping *gc_lmap;
GpuCacheSharedStateName(namebuf, MAXPGPATH,
database_oid,
table_oid,
signature);
fdesc = shm_open(namebuf, O_RDWR, 0600);
if (fdesc < 0)
{
if (errno == ENOENT)
return MAP_FAILED;
snprintf(errbuf, errbuf_sz,
"failed on shm_open('%s'): %m", namebuf);
goto bailout;
}
if (fstat(fdesc, &stat_buf) != 0)
{
snprintf(errbuf, errbuf_sz,
"failed on fstat('%s'): %m", namebuf);
goto bailout;
}
if ((stat_buf.st_size & PAGE_MASK) != 0)
{
snprintf(errbuf, errbuf_sz,
"file-size of '%s' is not aligned: %zu",
namebuf, stat_buf.st_size);
goto bailout;
}
gc_sstate = mmap(NULL, stat_buf.st_size,
PROT_READ | PROT_WRITE,
MAP_SHARED,
fdesc, 0);
if (gc_sstate == MAP_FAILED)
{
snprintf(errbuf, errbuf_sz,
"failed on mmap('%s', %zu): %m",
namebuf, stat_buf.st_size);
goto bailout;
}
/*
* wait for completion of the initial setup
*/
for (;;)
{
uint32_t phase = pg_atomic_read_u32(&gc_sstate->phase);
if (phase == GCACHE_PHASE__IS_EMPTY ||
phase == GCACHE_PHASE__IS_LOADING ||
phase == GCACHE_PHASE__IS_READY)
{
break;
}
else if (phase == GCACHE_PHASE__IS_CORRUPTED)
{
if (try_open_if_corrupted)
break;
snprintf(errbuf, errbuf_sz,
"GpuCacheSharedState is already corrupted");
goto bailout;
}
else
{
snprintf(errbuf, errbuf_sz,
"GpuCacheSharedState has unknown phase (%u)", phase);
goto bailout;
}
usleep(1000L); /* 1ms */
}
/* simple validation checks */
if (memcmp(gc_sstate->magic, "GpuCache", 8) != 0)
{
snprintf(errbuf, errbuf_sz,
"GpuCacheSharedState validation error");
goto bailout;
}
off = PAGE_ALIGN(offsetof(GpuCacheSharedState, kds_head) +