-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroad_am.c
1992 lines (1646 loc) · 51.1 KB
/
road_am.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
/*-------------------------------------------------------------------------
*
* road_am.c
*
* Portions Copyright (c) 2024, PostgreSQL Global Development Group
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#ifdef USE_LZ4
#include <lz4.h>
#endif
#include "access/amapi.h"
#include "access/generic_xlog.h"
#include "access/heapam.h"
#include "access/hio.h"
#include "access/tableam.h"
#include "access/multixact.h"
#include "access/heaptoast.h"
#include "access/xlog_internal.h"
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/index.h"
#include "catalog/heap.h"
#include "catalog/pg_am.h"
#include "catalog/storage.h"
#include "commands/vacuum.h"
#include "common/pg_lzcompress.h"
#include "executor/executor.h"
#include "executor/tuptable.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
#include "utils/inval.h"
#include "storage/bufmgr.h"
#include "storage/ipc.h"
#include "storage/procarray.h"
#include "storage/lmgr.h"
#include "storage/smgr.h"
#include "tcop/utility.h"
#include "pgstat.h"
#include "road_am.h"
#include "skiplist_table.h"
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(road_am_handler);
#define FEATURE_NOT_SUPPORTED() \
ereport(ERROR, \
errcode(ERRCODE_FEATURE_NOT_SUPPORTED), \
errmsg("%s is not supported", __func__))
/*
* Struct for all information required by inserting tuples to a ROAD table.
* Since a ROAD table is created during either ALTER TABLE ... SET ACCESS
* METHOD or CREATE TABLE ... AS, both of which take an AccessExclusiveLock
* on the original table, and we don't allow these operations to be called
* in a transaction block, we insert tuples to one ROAD table in a transaction.
*/
typedef struct RoadInsertStateData
{
Oid relid;
Oid skip_relid;
/* The first rownumber in the current chunk page */
RowNumber first_rownum;
/* The current rownumber */
RowNumber cur_rownum;
/*
* Flags if ALTER TABLE ... SET ACCESS METHOD or CREATE TABLE ... AS is
* called. This is necessary to control whether we can allow insertion to
* the ROAD table.
*
* XXX: if we find a better way to distinguish how road_insert_tuple is
* called, we don't need both variables (as well as probably
* ProcessUtility hook).
*/
bool called_in_atsam;
bool called_in_ctas;
/*
* In ALTER TABLE ... SET ACCESS METHOD, road_tuple_insert() and
* road_relation_set_new_filelocator() don't know the original table's
* OID. If we create the skiplist table for the new (transient) relation,
* the skiplist able will be removed altogether. In our process utility
* hook, we set the original relation's OID to atsam_relid. So it's a
* valid OID only during ALTER TABLE ... SET ACCESS METHOD execution.
*/
Oid atsam_relid;
/* Work buffer to collect tuples */
char chunk_page[ROAD_CHUNK_PAGE_SIZE];
int compression_method;
} RoadInsertStateData;
static RoadInsertStateData RoadInsertState = {0};
/*
* SeqScan descriptor for a ROAD table.
*/
typedef struct RoadScanDescData
{
TableScanDescData base;
bool inited;
/*
* The current buffer, block, and position in a ROAD table page.
*/
Buffer curbuf;
BlockNumber curblk;
int64 curpos;
/* The current and max offset number within the chunk page */
OffsetNumber curoff;
OffsetNumber maxoff;
/* The current and max chunk number */
int64 curchunk;
int64 maxchunk;
HeapTupleData tuple;
int compression_method;
/* Working buffer for a chunk page */
char chunk_page[ROAD_CHUNK_PAGE_SIZE];
} RoadScanDescData;
typedef struct RoadScanDescData *RoadScanDesc;
/* A scan descriptor for index fetching */
typedef struct RoadIndexFetchData
{
IndexFetchTableData base;
bool inited;
int compression_method;
/* Working buffer for a chunk page */
char chunk_page[ROAD_CHUNK_PAGE_SIZE];
/*
* The rownumbers of the first and last tuples in
* the cached chunk_page.
*/
RowNumber first_rownum;
RowNumber last_rownum;
} RoadIndexFetchData;
typedef struct RoadIndexFetchData *RoadIndexFetch;
typedef enum
{
ROAD_PGLZ_COMPRESSION = 0,
ROAD_LZ4_COMPRESSION,
/* ROAD_ZSTD_COMPRESSION, */
} RoadCompressionMethod;
static const struct config_enum_entry compression_options[] =
{
{"pglz", ROAD_PGLZ_COMPRESSION, false},
#ifdef USE_LZ4
{"lz4", ROAD_LZ4_COMPRESSION, false},
#endif
/*
* XXX: not supported yet.
* #ifdef USE_ZSTD {"zstd", ROAD_ZSTD_COMPRESSION, false}, #endif
*/
{NULL, 0, false},
};
static int road_compression_method = ROAD_PGLZ_COMPRESSION;
static void RoadXactCallback(XactEvent event, void *arg);
static void RoadSubXactCallback(SubXactEvent event, SubTransactionId mySubid,
SubTransactionId parentSubid, void *arg);
static void road_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
bool readOnlyTree,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest, QueryCompletion *qc);
static void road_flush_insert_state(RoadInsertStateData * state);
static void road_insert_compressed_chunk_page(RoadInsertStateData * state,
char *c_buffer, int c_len);
/* chunk page functions */
static int32 chunk_page_compress(RoadInsertStateData * state, Page chunkpage,
ChunkHeader cdata);
static void chunk_page_init(Page page);
static ProcessUtility_hook_type prev_ProcessUtility = NULL;
void
_PG_init(void)
{
if (!process_shared_preload_libraries_in_progress)
ereport(ERROR,
(errmsg("cannot load \"%s\" after startup", "pgroad"),
errdetail("\"%s\" must be loaded with shared_preload_libraries.",
"pgroad")));
DefineCustomEnumVariable("pgroad.compression",
"compression method for ROAD table",
NULL,
&road_compression_method,
ROAD_PGLZ_COMPRESSION,
compression_options,
PGC_SUSET,
0,
NULL, NULL, NULL);
MarkGUCPrefixReserved("pgroad");
/* Register xact callbacks */
RegisterXactCallback(RoadXactCallback, NULL);
RegisterSubXactCallback(RoadSubXactCallback, NULL);
/* Install hooks */
prev_ProcessUtility = ProcessUtility_hook ?
ProcessUtility_hook : standard_ProcessUtility;
ProcessUtility_hook = road_ProcessUtility;
}
/* Reset all fields of RoadInsertStateData */
static void
road_insert_state_init(RoadInsertStateData * state)
{
MemSet(state, 0, sizeof(RoadInsertStateData));
chunk_page_init((Page) state->chunk_page);
}
static void
RoadXactCallback(XactEvent event, void *arg)
{
switch (event)
{
case XACT_EVENT_PRE_COMMIT:
case XACT_EVENT_COMMIT:
case XACT_EVENT_ABORT:
case XACT_EVENT_PARALLEL_ABORT:
case XACT_EVENT_PREPARE:
case XACT_EVENT_PARALLEL_COMMIT:
case XACT_EVENT_PARALLEL_PRE_COMMIT:
case XACT_EVENT_PRE_PREPARE:
{
road_insert_state_init(&RoadInsertState);
break;
}
}
}
static void
RoadSubXactCallback(SubXactEvent event, SubTransactionId mySubid,
SubTransactionId parentSubid, void *arg)
{
/* XXX */
}
/*
* Check if CTAS or ALTER TABLE ... SET ACCESS METHOD is called.
*/
static void
road_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
bool readOnlyTree,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest, QueryCompletion *qc)
{
NodeTag tag = nodeTag(pstmt->utilityStmt);
if (tag == T_CreateTableAsStmt)
{
RoadInsertState.called_in_ctas = true;
Assert(!RoadInsertState.called_in_atsam);
}
else if (tag == T_AlterTableStmt)
{
AlterTableStmt *atstmt = (AlterTableStmt *) pstmt->utilityStmt;
ListCell *cell;
foreach(cell, atstmt->cmds)
{
AlterTableCmd *cmd = (AlterTableCmd *) lfirst(cell);
if (cmd->subtype == AT_SetAccessMethod)
{
Relation rel = relation_openrv(atstmt->relation, ShareLock);
ROAD_DEBUG_LOG("ProcessUtility: rel %s am %s",
RelationGetRelationName(rel), cmd->name);
/*
* Are we about to change the access method of the relation to
* ROAD table AM?
*/
if (strcmp(cmd->name, "road") == 0)
{
/* Remember the original table's OID */
RoadInsertState.atsam_relid = RelationGetRelid(rel);
RoadInsertState.called_in_atsam = true;
}
RelationClose(rel);
break;
}
}
Assert(!RoadInsertState.called_in_ctas);
}
prev_ProcessUtility(pstmt, queryString, false, context,
params, queryEnv, dest, qc);
}
static inline ItemPointerData
rownumber_to_tid(uint64 rownumber)
{
ItemPointerData ret = {0};
ItemPointerSetBlockNumber(&ret, rownumber / MaxHeapTuplesPerPage);
/*
* We cannot use offset number more than MaxHeapTuplesPerPage, see
* tidbitmap.
*/
ItemPointerSetOffsetNumber(&ret, rownumber % MaxHeapTuplesPerPage +
FirstOffsetNumber);
return ret;
}
static inline uint64
tid_to_rownumber(ItemPointer tid)
{
return (uint64) (ItemPointerGetBlockNumber(tid) * MaxHeapTuplesPerPage +
ItemPointerGetOffsetNumber(tid) - FirstOffsetNumber);
}
static void
chunk_page_init(Page page)
{
Size pageSize = ROAD_CHUNK_PAGE_SIZE;
Size specialSize = 0;
PageHeader p = (PageHeader) page;
specialSize = MAXALIGN(specialSize);
Assert(pageSize > specialSize + SizeOfPageHeaderData);
/* Make sure all fields of page are zero, as well as unused space */
MemSet(p, 0, pageSize);
p->pd_flags = 0;
p->pd_lower = SizeOfPageHeaderData;
p->pd_upper = pageSize - specialSize;
p->pd_special = pageSize - specialSize;
PageSetPageSizeAndVersion(page, pageSize, PG_PAGE_LAYOUT_VERSION);
}
static Size
chunk_page_free_space(Page page)
{
return PageGetFreeSpace(page);
}
static uint16
chunk_page_get_max_offsetnumber(Page page)
{
return (uint16) PageGetMaxOffsetNumber(page);
}
static OffsetNumber
chunk_page_add_item(Page page, Item item, Size size, OffsetNumber offsetNumber)
{
PageHeader phdr = (PageHeader) page;
Size alignedSize;
int lower;
int upper;
ItemId itemId;
OffsetNumber limit;
bool needshuffle = false;
/*
* Be wary about corrupted page pointers
*/
if (phdr->pd_lower < SizeOfPageHeaderData ||
phdr->pd_lower > phdr->pd_upper ||
phdr->pd_upper > phdr->pd_special ||
phdr->pd_special > ROAD_CHUNK_PAGE_SIZE)
ereport(PANIC,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg("corrupted page pointers: lower = %u, upper = %u, special = %u",
phdr->pd_lower, phdr->pd_upper, phdr->pd_special)));
/*
* Select offsetNumber to place the new item at
*/
limit = OffsetNumberNext(PageGetMaxOffsetNumber(page));
/* was offsetNumber passed in? */
if (OffsetNumberIsValid(offsetNumber))
{
if (offsetNumber < limit)
needshuffle = true; /* need to move existing linp's */
}
else
{
/* offsetNumber was not passed in, so find a free slot */
/* if no free slot, we'll put it at limit (1st open slot) */
if (PageHasFreeLinePointers(page))
{
/*
* Scan line pointer array to locate a "recyclable" (unused)
* ItemId.
*
* Always use earlier items first. PageTruncateLinePointerArray
* can only truncate unused items when they appear as a contiguous
* group at the end of the line pointer array.
*/
for (offsetNumber = FirstOffsetNumber;
offsetNumber < limit; /* limit is maxoff+1 */
offsetNumber++)
{
itemId = PageGetItemId(page, offsetNumber);
/*
* We check for no storage as well, just to be paranoid;
* unused items should never have storage. Assert() that the
* invariant is respected too.
*/
Assert(ItemIdIsUsed(itemId) || !ItemIdHasStorage(itemId));
if (!ItemIdIsUsed(itemId) && !ItemIdHasStorage(itemId))
break;
}
if (offsetNumber >= limit)
{
/* the hint is wrong, so reset it */
PageClearHasFreeLinePointers(page);
}
}
else
{
/* don't bother searching if hint says there's no free slot */
offsetNumber = limit;
}
}
if (offsetNumber > limit)
{
elog(WARNING, "specified item offset is too large");
return InvalidOffsetNumber;
}
/* Reject placing items beyond heap boundary, if heap */
if (offsetNumber > MaxHeapTuplesPerChunkPage)
{
elog(WARNING, "can't put more than MaxHeapTuplesPerPage items in a heap page");
return InvalidOffsetNumber;
}
/*
* Compute new lower and upper pointers for page, see if it'll fit.
*
* Note: do arithmetic as signed ints, to avoid mistakes if, say,
* alignedSize > pd_upper.
*/
if (offsetNumber == limit || needshuffle)
lower = phdr->pd_lower + sizeof(ItemIdData);
else
lower = phdr->pd_lower;
alignedSize = MAXALIGN(size);
upper = (int) phdr->pd_upper - (int) alignedSize;
if (lower > upper)
return InvalidOffsetNumber;
/*
* OK to insert the item. First, shuffle the existing pointers if needed.
*/
itemId = PageGetItemId(page, offsetNumber);
if (needshuffle)
memmove(itemId + 1, itemId,
(limit - offsetNumber) * sizeof(ItemIdData));
/* set the line pointer */
ItemIdSetNormal(itemId, upper, size);
/*
* Items normally contain no uninitialized bytes. Core bufpage consumers
* conform, but this is not a necessary coding rule; a new index AM could
* opt to depart from it. However, data type input functions and other
* C-language functions that synthesize datums should initialize all
* bytes; datumIsEqual() relies on this. Testing here, along with the
* similar check in printtup(), helps to catch such mistakes.
*
* Values of the "name" type retrieved via index-only scans may contain
* uninitialized bytes; see comment in btrescan(). Valgrind will report
* this as an error, but it is safe to ignore.
*/
/* VALGRIND_CHECK_MEM_IS_DEFINED(item, size); */
/* copy the item's data onto the page */
memcpy((char *) page + upper, item, size);
/* adjust page header */
phdr->pd_lower = (LocationIndex) lower;
phdr->pd_upper = (LocationIndex) upper;
return offsetNumber;
}
static void
chunk_page_decompress(RoadCompressionMethod method, ChunkHeader chunk, char *src, char *dest)
{
char tmp[ROAD_CHUNK_PAGE_SIZE];
int len = 0;
if (method == ROAD_PGLZ_COMPRESSION)
{
len = pglz_decompress(src, chunk->c_len, tmp,
ROAD_CHUNK_PAGE_SIZE - chunk->c_hole_len, false);
}
#ifdef USE_LZ4
else if (method == ROAD_LZ4_COMPRESSION)
{
len = LZ4_decompress_safe(src, tmp, chunk->c_len, ROAD_CHUNK_PAGE_SIZE);
}
#endif
if (len < 0)
elog(ERROR, "could not decompress chunk page data");
if (chunk->c_hole_len == 0)
memcpy(dest, tmp, ROAD_CHUNK_PAGE_SIZE);
else
{
memcpy(dest, tmp, chunk->c_hole_off);
MemSet(dest + chunk->c_hole_off, 0, chunk->c_hole_len);
memcpy(dest + (chunk->c_hole_off + chunk->c_hole_len),
tmp + chunk->c_hole_off,
ROAD_CHUNK_PAGE_SIZE - (chunk->c_hole_off + chunk->c_hole_len));
}
ROAD_DEBUG_LOG("DECOMPRESS: c_len %u c_hole_off %u c_hole_len %u decompressed len %d method %d",
chunk->c_len, chunk->c_hole_off,
chunk->c_hole_len, len, method);
}
/*
* Compress the given chunkpage into cdata. Return the total length
* including the compressed chunkpage and chunk header size.
*/
static int32
chunk_page_compress(RoadInsertStateData * state, Page chunkpage, ChunkHeader cdata)
{
uint16 lower = ((PageHeader) chunkpage)->pd_lower;
uint16 upper = ((PageHeader) chunkpage)->pd_upper;
int orig_len,
dest_len = 0;
int hole_offset,
hole_len = 0;
char tmp[ROAD_CHUNK_PAGE_SIZE];
char *source,
*dest;
if (lower >= SizeOfPageHeaderData && upper > lower && upper <= ROAD_CHUNK_PAGE_SIZE)
{
hole_offset = lower;
hole_len = upper - lower;
}
if (hole_len > 0)
{
source = tmp;
memcpy(source, chunkpage, hole_offset);
memcpy(source + hole_offset,
chunkpage + (hole_offset + hole_len),
ROAD_CHUNK_PAGE_SIZE - (hole_len + hole_offset));
}
else
source = chunkpage;
orig_len = ROAD_CHUNK_PAGE_SIZE - hole_len;
dest = ((char *) cdata) + SizeOfChunkHeaderData;
if (state->compression_method == ROAD_PGLZ_COMPRESSION)
{
dest_len = pglz_compress(source, orig_len, dest, PGLZ_strategy_always);
}
#ifdef USE_LZ4
else if (state->compression_method == ROAD_LZ4_COMPRESSION)
{
dest_len = LZ4_compress_default(source, dest, orig_len, ROAD_CHUNK_PAGE_SIZE);
}
#endif
if (dest_len < 0)
elog(ERROR, "could not compress chunk page data");
cdata->c_len = dest_len;
cdata->c_hole_off = hole_offset;
cdata->c_hole_len = hole_len;
ROAD_DEBUG_LOG("COMPRESS: c_len %u c_hole_off %u c_hole_len %u total len %lu method %d",
cdata->c_len, cdata->c_hole_off,
cdata->c_hole_len, dest_len + SizeOfChunkHeaderData,
state->compression_method);
return dest_len + SizeOfChunkHeaderData;
}
static void
road_page_init(Page page)
{
Assert(PageIsNew(page));
PageInit(page, BLCKSZ, 0);
((PageHeader) page)->pd_lower = MAXALIGN(SizeOfPageHeaderData);
}
static int
road_page_get_freespace(Page page)
{
/*
* We don't use PageGetFreeSpace() for road pages since the road page
* doesn't use ItemId while the function subtract the space by one ItemId.
*/
return (int) ((PageHeader) page)->pd_upper -
(int) ((PageHeader) page)->pd_lower;
}
static Buffer
road_get_meta_page(Relation rel)
{
Buffer buffer;
buffer = ReadBuffer(rel, ROAD_META_BLOCKNO);
LockBuffer(buffer, BUFFER_LOCK_SHARE);
return buffer;
}
/*
* Compress and insert the chunk page to the table, and update the
* corresponding skiplist entry.
*
* c_buffer is the compressed chunk page including the header, and
* c_len is the total length of c_buffer.
*/
static void
road_flush_insert_state(RoadInsertStateData * state)
{
char tmp[ROAD_CHUNK_PAGE_SIZE] = {0};
int len;
ROAD_DEBUG_LOG("FLUSH: start oid %u chunk page ntuples %u freespace %zu first_rownum %lu cur_rownum %lu",
state->relid,
chunk_page_get_max_offsetnumber(state->chunk_page),
chunk_page_free_space(state->chunk_page),
state->first_rownum,
state->cur_rownum);
ROAD_DEBUG_LOG("FLUSH: step-1: start compress");
len = chunk_page_compress(state, state->chunk_page, (ChunkHeader) tmp);
ROAD_DEBUG_LOG("FLUSH: step-2: insert compressed page");
road_insert_compressed_chunk_page(state, tmp, len);
state->first_rownum = state->cur_rownum;
chunk_page_init((Page) state->chunk_page);
ROAD_DEBUG_LOG("FLUSH: step-3: finish, update the insert state next-first %lu next-cur %lu",
state->first_rownum,
state->cur_rownum);
}
static void
road_write_data(Relation rel, Buffer metabuffer, Buffer *buffers, int nbuffers,
char *src, int src_len)
{
int idx;
int written;
int nbuffers_remain = MAX_GENERIC_XLOG_PAGES;
Page page;
RoadMetaPage *metap;
GenericXLogState *state = GenericXLogStart(rel);
/* update the meta page */
page = GenericXLogRegisterBuffer(state, metabuffer,
GENERIC_XLOG_FULL_IMAGE);
nbuffers_remain--;
metap = (RoadMetaPage *) PageGetContents(page);
metap->nchunks += 1;
written = idx = 0;
while (written < src_len)
{
Buffer buffer = buffers[idx];
uint32 len;
Size freespace;
PageHeader phdr;
/*
* Generic XLOG infrastructure has the limit of the maximum number
* of buffers that can be registered, MAX_GENERIC_XLOG_PAGES, 4 as of
* now. So if the total number of buffers that we're writing the
* compressed chunk pages across to exceeds the limit, we have to
* split WAL records.
*/
if (nbuffers_remain == 0)
{
/* Write the previously collected data changes */
GenericXLogFinish(state);
/* Start a new WAL insertion */
state = GenericXLogStart(rel);
nbuffers_remain = MAX_GENERIC_XLOG_PAGES;
}
/* Register a new buffer and get the working page */
page = GenericXLogRegisterBuffer(state, buffer, GENERIC_XLOG_FULL_IMAGE);
nbuffers_remain--;
phdr = (PageHeader) page;
if (PageIsNew(page))
road_page_init(page);
freespace = road_page_get_freespace(page);
len = Min(freespace, src_len - written);
ROAD_DEBUG_LOG("FLUSH: [%d] blk %u pd_lower %u -> %u, c_buf pos %u (total %u), write %u",
idx, BufferGetBlockNumber(buffer),
phdr->pd_lower,
phdr->pd_lower + len,
written, src_len,
len);
Assert(phdr->pd_lower + len <= BLCKSZ);
memcpy((char *) page + phdr->pd_lower,
(char *) src + written,
len);
phdr->pd_lower += len;
written += len;
idx++;
}
GenericXLogFinish(state);
}
/*
* Insert the given compressed chunk page into the table. Also, insert the
* corresponding skiplist table entry.
*/
static void
road_insert_compressed_chunk_page(RoadInsertStateData * state, char *c_buffer,
int c_len)
{
Relation rel = table_open(state->relid, NoLock);
BlockNumber blkno;
Buffer *buffers;
Buffer metabuffer;
int num_buffers;
Buffer buffer;
Page page;
Size freespace;
uint64 skipent_offset;
Assert(CheckRelationLockedByMe(rel, AccessExclusiveLock, true));
metabuffer = ReadBuffer(rel, ROAD_META_BLOCKNO);
LockBuffer(metabuffer, BUFFER_LOCK_EXCLUSIVE);
/* road table has meta page at block 0 */
blkno = RelationGetNumberOfBlocks(rel) - 1;
if (blkno == ROAD_META_BLOCKNO)
blkno = P_NEW;
buffer = ReadBuffer(rel, blkno);
LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
page = (Page) BufferGetPage(buffer);
if (PageIsNew(page))
road_page_init(page);
freespace = road_page_get_freespace(page);
if (freespace >= c_len)
{
ROAD_DEBUG_LOG("FLUSH: tail page %u has enough space %lu for chunk size %u",
BufferGetBlockNumber(buffer), freespace, c_len);
/* easy case, no need to extend the table */
buffers = palloc(sizeof(Buffer));
buffers[0] = buffer;
num_buffers = 1;
skipent_offset = (BufferGetBlockNumber(buffers[0]) * BLCKSZ) +
(PageIsNew(page) ?
MAXALIGN(SizeOfPageHeaderData) :
((PageHeader) BufferGetPage(buffer))->pd_lower);
}
else if (freespace >= SizeOfChunkHeaderData)
{
uint32 extend_by;
uint32 extended_by;
/*
* The tail page doesn't have enough space to store the whole
* compressed page, but can have at least the chunk header. So we keep
* hold this buffer to use, and extend the cc-table for the remaining
* data.
*/
extend_by = ((c_len - freespace) / (BLCKSZ - sizeof(PageHeaderData))) + 1;
num_buffers = extend_by + 1;
buffers = palloc(sizeof(Buffer) * num_buffers);
buffers[0] = buffer;
ExtendBufferedRelBy(BMR_REL(rel), MAIN_FORKNUM,
NULL,
0,
extend_by,
&(buffers[1]),
&extended_by);
ROAD_DEBUG_LOG("FLUSH: tail page %u has space %lu only header %lu (c_len %u), extend by %u",
BufferGetBlockNumber(buffer),
freespace, SizeOfChunkHeaderData,
c_len,
extend_by);
for (int i = 1; i < num_buffers; i++)
LockBuffer(buffers[i], BUFFER_LOCK_EXCLUSIVE);
skipent_offset = (BufferGetBlockNumber(buffers[0]) * BLCKSZ) +
(PageIsNew(page) ?
MAXALIGN(SizeOfPageHeaderData) :
((PageHeader) BufferGetPage(buffer))->pd_lower);
}
else
{
uint32 extend_by;
uint32 extended_by;
ROAD_DEBUG_LOG("FLUSH: tail page %u doesn't have space %lu (cc %u), extend by %u",
BufferGetBlockNumber(buffer),
freespace,
c_len,
(uint32) ((c_len / (BLCKSZ - sizeof(PageHeaderData))) + 1));
/*
* The tail page doesn't have enough space even for the chunk header.
* We extend the cc-table and store the compressed page from the next
* page.
*/
UnlockReleaseBuffer(buffer);
extend_by = (c_len / (BLCKSZ - sizeof(PageHeaderData))) + 1;
num_buffers = extend_by;
buffers = palloc(sizeof(Buffer) * num_buffers);
ExtendBufferedRelBy(BMR_REL(rel), MAIN_FORKNUM,
NULL,
0,
extend_by,
buffers,
&extended_by);
for (int i = 0; i < num_buffers; i++)
LockBuffer(buffers[i], BUFFER_LOCK_EXCLUSIVE);
skipent_offset = (BufferGetBlockNumber(buffers[0]) * BLCKSZ) +
MAXALIGN(SizeOfPageHeaderData);
}
/*
* Insert a new entry to skiplist table.
*
* Inserting the compressed chunk is non-transactional since all tuples
* inside the chunk page don't have any visibility information and
* considered as visible anyway, whereas inserting the skiplist table
* entry is transactional since the skiplist table is a heap table.
* Therefore, we insert the skiplist table entry first and then insert the
* compressed chunk page. Note that we write a separate WAL for skiplist
* entry insertion from WAL for compressed page insertion.
*
* If the server crashes immediately after inserting a skiplist entry,
* nothing update will be visible thanks to a heap table (and CLOG).
*/
Assert(OidIsValid(RoadInsertState.skip_relid));
skiplist_insert_entry(RoadInsertState.skip_relid, state->first_rownum,
skipent_offset);
/* Write the compressed page to (multiple) blocks */
road_write_data(rel, metabuffer, buffers, num_buffers, c_buffer, c_len);
UnlockReleaseBuffer(metabuffer);
for (int i = 0; i < num_buffers; i++)
UnlockReleaseBuffer(buffers[i]);
table_close(rel, NoLock);
}
static void
chunk_page_put_tuple(RoadInsertStateData * state, HeapTuple tuple)
{
if (tuple->t_len > chunk_page_free_space(state->chunk_page))
{
road_flush_insert_state(state);
Assert(tuple->t_len <= chunk_page_free_space(state->chunk_page));
}
/* XXX: use HeapTuple for now */
chunk_page_add_item(state->chunk_page, (Item) tuple->t_data, tuple->t_len,
InvalidOffsetNumber);
}
static RoadInsertStateData *
road_get_insert_state(Relation rel)
{
if (!OidIsValid(RoadInsertState.relid))
{
Buffer metabuf;
RoadMetaPage *metap;
metabuf = road_get_meta_page(rel);
metap = (RoadMetaPage *) PageGetContents(BufferGetPage(metabuf));
RoadInsertState.compression_method = metap->compression_method;
UnlockReleaseBuffer(metabuf);
RoadInsertState.relid = RelationGetRelid(rel);
chunk_page_init((Page) RoadInsertState.chunk_page);
ROAD_DEBUG_LOG("INSERT: initialize insert state relid %u skip_relid %u comp_method %d",
RoadInsertState.relid, RoadInsertState.skip_relid,
RoadInsertState.compression_method);
}
return &(RoadInsertState);
}
void
d(const char *msg, char *data, int len)
{
StringInfoData buf;
initStringInfo(&buf);
for (int i = 0; i < len; i++)
appendStringInfo(&buf, "%02X ", (uint8) data[i]);
ROAD_DEBUG_LOG("%s:\n%s", msg, buf.data);
pfree(buf.data);
}
static const TupleTableSlotOps *
road_slot_callbacks(Relation relation)
{
/*
* Here you would most likely want to invent your own set of slot
* callbacks for your AM.
*/
return &TTSOpsVirtual;
}
static void
road_initscan(RoadScanDesc scan)
{
scan->inited = false;
scan->curbuf = InvalidBuffer;
MemSet(scan->chunk_page, 0, ROAD_CHUNK_PAGE_SIZE);
}
static TableScanDesc
road_scan_begin(Relation relation, Snapshot snapshot,
int nkeys, ScanKey key,
ParallelTableScanDesc parallel_scan,
uint32 flags)
{
RoadScanDesc scan;
scan = palloc0(sizeof(RoadScanDescData));
scan->base.rs_rd = relation;
scan->base.rs_snapshot = snapshot;
scan->base.rs_nkeys = nkeys;
scan->base.rs_flags = flags;
scan->base.rs_parallel = parallel_scan;