-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoblivpg_fdw.c
1388 lines (1088 loc) · 34.4 KB
/
oblivpg_fdw.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
/*-------------------------------------------------------------------------
*
* file_fdw.c
* foreign-data wrapper for server-side zero leakage indexes and heap.
*
* Copyright (c) 2018-2019, HASLab
*
* IDENTIFICATION
* contrib/oblivpg_fdw/oblivpg_fdw.c
*
*-------------------------------------------------------------------------
*/
#include <string.h>
#include "include/obliv_status.h"
#include "include/obliv_utils.h"
#include "include/oblivpg_fdw.h"
#include "include/obliv_ocalls.h"
#include "access/htup.h"
#include "access/htup_details.h"
#include "access/tuptoaster.h"
#include "access/nbtree.h"
#include "catalog/catalog.h"
#include "postgres.h"
#include "access/xact.h"
#include "catalog/pg_namespace_d.h"
#include "commands/explain.h"
#include "foreign/fdwapi.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/hsearch.h"
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "executor/tuptable.h"
#include "nodes/nodes.h"
#include "nodes/primnodes.h"
#include "storage/shmem.h"
#include "storage/smgr.h"
#include "optimizer/clauses.h"
#include "optimizer/restrictinfo.h"
#include <collectc/queue.h>
#define DYNAMIC 0
#define FOREST 1
/**
* SGX includes
*/
/* Needed to create enclave and do ecall. */
#ifndef UNSAFE
#include "sgx_urts.h"
#include "Enclave_u.h"
#else
#include "Enclave_dt.h"
#endif
#include "ops.h"
/**
*
* The current postgres version does not support table indexes on foreign tables.
* To overcome this limitation without modifying the server core source code, this extension assumes that the
* database has a standard postgres table which mirrors the foreign table. Furthermore, this mirror table has at most
* an index on a single column. This mirror table and its index will enable this extension to know what type of index and
* which column should be indexed. Furthermore, the mirror table and mirror indexcan be used for functional testing purposes and benchmarking.
*
* The last part for this hack to work is the table OBLIV_MAPPING_TABLE_NAME that must be created by the user and
* which will map foreign table Oids to its mirror tables Oids. From this information, the extension can visit the
* catalog tables to learn the necessary information about the indexes.
*indexes
* To read, write or modify the physical files of a table or an index the extension leverages the internal postgres
* API. To open a descriptor of the files it is necessary the to have an associated Relation for either the index or the heap file.
* This relation can be created with the method heap_create on the src/backend/catalog/heap.c file.
* The relation itself requires a varying number of parameters, most of which can be obtained from the foreign table relation.
* However, to create an index transparently for the foreign table, it is necessary to have a relation Oid (relid) which can be obtained
* by the function GetNewRelFileNode. To have an idea on how to create the index transparently it is helpful to follow the
* standard postgres flow to create a normal table index.
*
* It can be considered that the index creation flow of a postgres table starts in the IndexCmds source file in the function DefineIndex.
* The next relevant function is on the src/backend/catalog/index.c file, index_create function.
* From these functions, most of the necessary logic can be used and it just might be possible to build on top of it.
*
*
*/
/***
*
* The logic of a default insert operation starts on the executor node nodeMofifyTable function ExecInsert.
* Read this code to understand how insertions are done.
*/
/**
* Postgres macro to ensure that the compiled object file is not loaded to
* an incompatible server.
*/
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
PG_FUNCTION_INFO_V1(oblivpg_fdw_handler);
PG_FUNCTION_INFO_V1(oblivpg_fdw_validator);
/* Function declarations for extension loading and unloading */
extern void _PG_init(void);
extern void _PG_fini(void);
PG_FUNCTION_INFO_V1(init_soe);
PG_FUNCTION_INFO_V1(open_enclave);
PG_FUNCTION_INFO_V1(close_enclave);
PG_FUNCTION_INFO_V1(load_blocks);
PG_FUNCTION_INFO_V1(attach_shmem);
PG_FUNCTION_INFO_V1(set_nextterm);
/* Default CPU cost to start up a foreign query. */
#define DEFAULT_FDW_STARTUP_COST 100.0
/* Default CPU cost to start up a foreign query. */
#define DEFAULT_OBLIV_FDW_TOTAL_COST 100.0
/* Predefined max tuple size for sgx to copy the real tuple to*/
#define MAX_TUPLE_SIZE 8070
#define ENCLAVE_LIB "/usr/local/lib/soe/libsoe.signed.so"
int opmode;
int type_op;
int queueOid;
//Inter process memory shared hash
static STerm *term_state= NULL;
#ifndef UNSAFE
sgx_enclave_id_t enclave_id = 0;
#endif
/**
* Postgres initialization function which is called immediately after the an
* extension is loaded. This function can latter be used to initialize SGX
* enclaves and set-up Remote attestation.
*
* This function is only called when an extension is first created. It is not
* used for every database initialization.
*/
void
_PG_init()
{
}
/**
* Postgres cleaning function which is called just before an extension is
* unloaded from a server. This function can latter be used to close SGX
* enclaves and clean the final context.
*/
void
_PG_fini()
{
}
typedef struct BTQueueData
{
unsigned int level;
BlockNumber bts_parent_blkno;
OffsetNumber bts_offnum;
BlockNumber bts_bn_entry;
} BTQueueData;
typedef BTQueueData *BTQData;
typedef struct TreeConfig
{
unsigned int levels;
int *fanouts;
} TreeConfig;
typedef TreeConfig *TConfig;
/* Assuming a default tree hight to allocate to fanouts. This is reallocated for trees with more levels. */
#define DTHeight 3
/*
* FDW callback routines
*/
/* Functions for scanning oblivious index and table */
static void obliviousGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static void obliviousGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid);
static ForeignScan *obliviousGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan);
static void obliviousExplainForeignScan(ForeignScanState *scanState, ExplainState *explainState);
static void obliviousBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *obliviousIterateForeignScan(ForeignScanState *node);
static void obliviousReScanForeignScan(ForeignScanState *node);
static void obliviousEndForeignScan(ForeignScanState *node);
static bool obliviousAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *func,
BlockNumber *totalpages);
static bool obliviousIsForeignScanParallelSafe(PlannerInfo *root,
RelOptInfo *rel,
RangeTblEntry *rte);
/* Helper function */
static int getindexColumn(Oid oTable);
static TConfig transverse_tree(Oid indexOID, bool load);
static void load_blocks_heap(Oid heapOid);
static bool init_termstate(void);
static char* get_nextterm(void);
static void set_nterm(char* term);
static void foreignInsert(HeapTuple tuple, Relation rel);
static void load_tuples_heap(Oid toid);
Datum
init_soe(PG_FUNCTION_ARGS)
{
Oid mappingOid;
Oid ftw_oid;
Oid realIndexOid;
sgx_status_t status;
Relation oblivMappingRel;
Relation mirrorHeapTable;
Relation mirrorIndexTable;
FdwOblivTableStatus oStatus;
char *mirrorTableRelationName;
char *mirrorIndexRelationName;
Oid hashFunctionOID;
Oid indexHandlerOID;
FormData_pg_attribute attrDesc;
TupleDesc indexTupleDesc;
unsigned int attrDescLength;
TConfig config;
char* initialTerm;
#ifdef DUMMYS
initialTerm = palloc(sizeof(char*)*6);
memcpy(initialTerm, "DUMMY",5);
initialTerm[10]= '\0';
init_termstate();
set_nterm(initialTerm);
pfree(initialTerm);
#endif
type_op = PG_GETARG_UINT32(0);
ftw_oid = PG_GETARG_OID(1);
opmode = PG_GETARG_UINT32(2);
/* Test run or deployment */
realIndexOid = PG_GETARG_OID(3);
status = SGX_SUCCESS;
mappingOid = get_relname_relid(OBLIV_MAPPING_TABLE_NAME, PG_PUBLIC_NAMESPACE);
if (mappingOid != InvalidOid)
{
oblivMappingRel = heap_open(mappingOid, RowShareLock);
oStatus = getOblivTableStatus(ftw_oid, oblivMappingRel);
mirrorHeapTable = heap_open(oStatus.relTableMirrorId, NoLock);
mirrorTableRelationName = RelationGetRelationName(mirrorHeapTable);
mirrorIndexTable = index_open(oStatus.relIndexMirrorId, NoLock);
mirrorIndexRelationName = RelationGetRelationName(mirrorIndexTable);
/*
* Fetch the oid of the functions that manipulate the indexed columns
* data types. In the current prototype this is the function used to
* hash a given value. The system's default functions for the database
* datatypes are defined in fmgroids.h. This values are also in the
* catalog table pg_proc.
*/
indexTupleDesc = RelationGetDescr(mirrorIndexTable);
attrDesc = indexTupleDesc->attrs[0];
attrDescLength = sizeof(FormData_pg_attribute);
indexHandlerOID = mirrorIndexTable->rd_amhandler;
setupOblivStatus(oStatus, mirrorTableRelationName, mirrorIndexRelationName, indexHandlerOID);
elog(DEBUG1, "Initializing SOE");
config = transverse_tree(realIndexOid, false);
if (type_op == DYNAMIC)
{
hashFunctionOID = mirrorIndexTable->rd_support[0];
#ifndef UNSAFE
status = initSOE(enclave_id,
mirrorTableRelationName,
mirrorIndexRelationName,
oStatus.tableNBlocks,
config->fanouts,
config->levels*sizeof(int),
config->levels,
oStatus.indexNBlocks,
oStatus.relTableMirrorId,
oStatus.relIndexMirrorId,
(unsigned int) hashFunctionOID,
(unsigned int) indexHandlerOID,
(char *) &attrDesc,
attrDescLength);
#else
initSOE(mirrorTableRelationName,
mirrorIndexRelationName,
oStatus.tableNBlocks,
config->fanouts,
config->levels*sizeof(int),
config->levels,
oStatus.indexNBlocks,
oStatus.relTableMirrorId,
oStatus.relIndexMirrorId,
(unsigned int) hashFunctionOID,
(unsigned int) indexHandlerOID,
(char *) &attrDesc,
attrDescLength);
#endif
}
else if (type_op == FOREST)
{
elog(DEBUG1, "Initializing FSOE for table with %d bocks", oStatus.tableNBlocks);
#ifndef UNSAFE
status = initFSOE(enclave_id,
mirrorTableRelationName,
mirrorIndexRelationName,
oStatus.tableNBlocks,
config->fanouts,
config->levels*sizeof(int),
config->levels,
oStatus.relTableMirrorId,
oStatus.relIndexMirrorId,
(char *) &attrDesc,
attrDescLength);
#else
initFSOE(mirrorTableRelationName,
mirrorIndexRelationName,
oStatus.tableNBlocks,
config->fanouts,
config->levels*sizeof(int),
config->levels,
oStatus.relTableMirrorId,
oStatus.relIndexMirrorId,
(char *) &attrDesc,
attrDescLength);
#endif
pfree(config);
}
else
{
elog(ERROR, "Unsupported initialization type %d", type_op);
}
if (status != SGX_SUCCESS)
{
elog(ERROR, "SOE initialization failed %d ", status);
}
heap_close(mirrorHeapTable, NoLock);
index_close(mirrorIndexTable, NoLock);
heap_close(oblivMappingRel, RowShareLock);
}
PG_RETURN_INT32(0);
}
Datum
open_enclave(PG_FUNCTION_ARGS)
{
#ifndef UNSAFE
sgx_status_t status;
int token_update;
sgx_launch_token_t token;
token_update = 0;
memset(&token, 0, sizeof(sgx_launch_token_t));
status = sgx_create_enclave(ENCLAVE_LIB,
SGX_DEBUG_FLAG,
&token,
&token_update,
&enclave_id, NULL);
if (SGX_SUCCESS != status)
{
elog(ERROR, "Enclave was not created. Return error %#x", status);
sgx_destroy_enclave(enclave_id);
PG_RETURN_INT32(status);
}
elog(DEBUG1, "Enclave successfully created");
PG_RETURN_INT32(status);
#else
PG_RETURN_INT32(0);
#endif
}
TConfig
transverse_tree(Oid indexOID, bool load)
{
Relation irel;
BTQData queue_data = NULL;
void *qblock;
Buffer bufp;
int queue_stat;
Queue *queue;
bool isroot = true;
unsigned int max_height = 0;
unsigned int cb_height = 0;
unsigned int nblocks_level = 0;
unsigned int level_offset = 0;
unsigned int nblocks_level_next = 0;
TConfig result;
result = (TConfig) palloc(sizeof(struct TreeConfig));
result->fanouts = (int *) palloc(sizeof(int) * DTHeight);
irel = index_open(indexOID, ExclusiveLock);
elog(DEBUG1, "The number of blocks of index is %d",RelationGetNumberOfBlocks(irel));
queue_stat = queue_new(&queue);
if (queue_stat != CC_OK)
{
/* TODO: Log error and abort. */
elog(ERROR, " queue initialization failed");
}
/* Get the root page to start with */
bufp = _bt_getroot(irel, BT_READ);
/* The three has not been created and does not have a root */
/* if(!BufferIsValid(*bufp)) */
/**/
//elog(DEBUG1, "Root is block number %d",BufferGetBlockNumber(bufp));
queue_data = (BTQData) palloc(sizeof(BTQueueData));
queue_data->bts_parent_blkno = InvalidBlockNumber;
/* IS ROOT */
/* the root is not the offset of any other block. */
queue_data->bts_offnum = InvalidOffsetNumber;
queue_data->bts_bn_entry = 0;
/* We consider root to be on the first block. */
queue_data->level = 0;
queue_enqueue(queue, queue_data);
/* Breadth first tree transversal */
while (queue_poll(queue, &qblock) != CC_ERR_OUT_OF_RANGE)
{
Page page;
/* current queue (cq) data */
BTQData cq_data = NULL;
BTPageOpaque opaque;
OffsetNumber offnum;
ItemId itemid;
IndexTuple itup;
BlockNumber blkno;
BlockNumber par_blkno;
OffsetNumber low,
high;
BTQData cblock;
/* target block */
BlockNumber tblock = 0;
if (load)
{
tblock = nblocks_level_next;
}
cblock = (BTQData) qblock;
blkno = cblock->bts_bn_entry;
/* ITS NOT A ROOT BLOCK */
if (!isroot)
{
bufp = ReadBuffer(irel, cblock->bts_bn_entry);
}
// elog(DEBUG1, "WTF?");
page = BufferGetPage(bufp);
opaque = (BTPageOpaque) PageGetSpecialPointer(page);
elog(DEBUG1, "page opaque has size %lu\n", sizeof(BTPageOpaqueData));
//opaque->lsize=0;
opaque->location[0] = 0;
opaque->location[1] = 0;
//elog(DEBUG1, "page has size %d and location %d %d", opaque->location[0], opaque->location[1]);
blkno = BufferGetBlockNumber(bufp);
low = P_FIRSTDATAKEY(opaque);
high = PageGetMaxOffsetNumber(page);
if (load)
{
/* Set tree page prev pointer */
if (opaque->btpo_prev != P_NONE)
{
opaque->btpo_prev = level_offset - 1;
}
/* Set tree page next pointer */
if (opaque->btpo_next != P_NONE)
{
opaque->btpo_next = level_offset + 1;
}
}
par_blkno = BufferGetBlockNumber(bufp);
offnum = low;
if (!P_ISLEAF(opaque))
{
while (offnum <= high)
{
/*
* push elements to the stack to be transversed on the next
* loop iteration.
*/
/* Get page offset on disk. */
itemid = PageGetItemId(page, offnum);
itup = (IndexTuple) PageGetItem(page, itemid);
blkno = BTreeInnerTupleGetDownLink(itup);
cq_data = (BTQData) palloc(sizeof(BTQueueData));
cq_data->bts_offnum = offnum;
cq_data->bts_bn_entry = blkno;
cq_data->bts_parent_blkno = par_blkno;
queue_enqueue(queue, cq_data);
offnum = OffsetNumberNext(offnum);
if (load)
{
/* update children block numbers */
BTreeInnerTupleSetDownLink(itup, tblock);
tblock += 1;
}
}
}
if (load)
{
//elog(DEBUG1, "Loading block %d at level %d", level_offset, max_height);
/* Invoke SOE function to store tree block */
#ifdef UNSAFE
addIndexBlock(page, BLCKSZ, level_offset, max_height);
#else
addIndexBlock(enclave_id, page, BLCKSZ, level_offset, max_height);
#endif
}
if (P_ISROOT(opaque))
{
nblocks_level = high - low + 1;
level_offset = 0;
cb_height += 1;
isroot = false;
max_height = Max(max_height, cb_height);
if (!load)
{
elog(DEBUG1, "Fanout of height %d is %d\n", 0, nblocks_level);
result->fanouts[0] = nblocks_level;
}
}
else
{
if (level_offset == nblocks_level - 1)
{
if (!P_ISLEAF(opaque))
{
nblocks_level_next += (high - low + 1);
if (!load)
{
if (cb_height > DTHeight)
{
result->fanouts = (int *) realloc(result->fanouts, sizeof(int) * cb_height);
}
elog(DEBUG1, "Fanout of height %d is %d\n", cb_height, nblocks_level_next);
result->fanouts[cb_height] = nblocks_level_next;
}
}
nblocks_level = nblocks_level_next;
nblocks_level_next = 0;
cb_height += 1;
max_height = Max(max_height, cb_height);
level_offset = 0;
}
else
{
level_offset++;
if (!P_ISLEAF(opaque))
{
nblocks_level_next += (high - low + 1);
}
}
}
pfree(qblock);
ReleaseBuffer(bufp);
}
queue_destroy(queue);
index_close(irel, ExclusiveLock);
if (!load)
{
elog(DEBUG1, "Tree height is %d\n", max_height-1);
result->levels = max_height - 1;
}
return result;
}
Datum
load_blocks(PG_FUNCTION_ARGS)
{
Oid ioid = PG_GETARG_OID(0);
Oid toid = PG_GETARG_OID(1);
elog(DEBUG1,"Initializing oblivious tree construction");
transverse_tree(ioid, true);
elog(DEBUG1, "Initializing oblivious heap table");
load_blocks_heap(toid);
PG_RETURN_INT32(0);
}
Datum
attach_shmem(PG_FUNCTION_ARGS)
{
bool found;
found = init_termstate();
PG_RETURN_BOOL(found);
}
Datum set_nextterm(PG_FUNCTION_ARGS)
{
char* term = PG_GETARG_CSTRING(0);
set_nterm(term);
PG_RETURN_VOID();
}
void set_nterm(char* term)
{
//LWLockAcquire(&term_state->lock, LW_EXCLUSIVE);
memcpy(term_state->term, term, strlen(term)+1);
term_state->term_size = strlen(term) + 1;
//LWLockRelease(&term_state->lock);
}
char* get_nextterm(){
char* term;
//LWLockAcquire(&term_state->lock, LW_EXCLUSIVE);
term = palloc(sizeof(char*)*term_state->term_size);
memcpy(term, term_state->term, term_state->term_size);
memcpy(term_state->term, "DUMMY", sizeof(char)*6);
term_state->term[5] = '\0';
term_state->term_size=6;
//LWLockRelease(&term_state->lock);
return term;
}
void
load_blocks_heap(Oid toid)
{
Relation rel;
BlockNumber npages;
BlockNumber blkno;
Buffer buffer;
Page page;
int* r_blkno;
rel = heap_open(toid, NoLock);
npages = RelationGetNumberOfBlocks(rel);
elog(DEBUG1, "The Number of blocks of table is %d", npages);
for (blkno = 0; blkno < npages; blkno++)
{
if(blkno%500 == 0){
elog(DEBUG1, "Loading Heap Block %d", blkno);
}
buffer = ReadBuffer(rel, blkno);
if (BufferIsValid(buffer))
{
page = BufferGetPage(buffer);
/**
* Assumes that heap blocks of the original table are
* initiated with a special area for an integer.
*/
if(page == PageGetSpecialPointer(page)){
elog(ERROR, "Page has no allocated space for special area");
}
r_blkno = (int*) PageGetSpecialPointer(page);
*r_blkno = blkno;
#ifdef UNSAFE
addHeapBlock(page, BLCKSZ, blkno);
#else
addHeapBlock(enclave_id, page, BLCKSZ, blkno);
#endif
}
else
{
elog(ERROR, "Buffer is invalid %d", blkno);
}
ReleaseBuffer(buffer);
}
heap_close(rel, NoLock);
}
void
load_tuples_heap(Oid toid){
Snapshot snapshot;
HeapScanDesc scan;
Relation rel;
HeapTuple tuple;
rel = heap_open(toid, ExclusiveLock);
elog(DEBUG1, "The Number of blocks of table is %d", RelationGetNumberOfBlocks(rel));
snapshot = RegisterSnapshot(GetLatestSnapshot());
scan = heap_beginscan(rel, snapshot, 0, NULL);
while((tuple = heap_getnext(scan, ForwardScanDirection))!= NULL){
foreignInsert(tuple, rel);
}
heap_endscan(scan);
UnregisterSnapshot(snapshot);
heap_close(rel, ExclusiveLock);
}
Datum
close_enclave(PG_FUNCTION_ARGS)
{
int result;
#ifndef UNSAFE
sgx_status_t status;
status = sgx_destroy_enclave(enclave_id);
if (SGX_SUCCESS != status)
{
elog(ERROR, "Enclave was not destroyed. Return error %d", status);
PG_RETURN_INT32(status);
}
PG_RETURN_INT32(status);
#else
closeSoe();
PG_RETURN_INT32(0);
#endif
//closeOblivStatus();
//elog(DEBUG1, "Enclave destroyed");
}
bool init_termstate(){
bool found;
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
term_state = ShmemInitStruct("opterms", sizeof(STerm), &found);
if(!found){
//First time creating STerms
LWLockInitialize(&term_state->lock, LWLockNewTrancheId());
term_state->term_size = 0;
memset(term_state->term,0, MAX_TERM_SIZE);
}
LWLockRelease(AddinShmemInitLock);
LWLockRegisterTranche(term_state->lock.tranche, "oblivpg_sterms");
return found;
}
/* Functions for updating foreign tables */
/**
* Function used by postgres before issuing a table update. This function is
* used to initialize the necessary resources to have an oblivious heap
* and oblivious table
*/
static void obliviousBeginForeignModify(ModifyTableState *mtstate,
ResultRelInfo *rinfo, List *fdw_private,
int subplan_index, int eflags);
static TupleTableSlot *obliviousExecForeignInsert(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
/*
* Foreign-data wrapper handler function: return a structure with pointers
* to callback routines.
*/
Datum
oblivpg_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwroutine = makeNode(FdwRoutine);
/* Oblivious table scan functions */
fdwroutine->GetForeignRelSize = obliviousGetForeignRelSize;
fdwroutine->GetForeignPaths = obliviousGetForeignPaths;
fdwroutine->GetForeignPlan = obliviousGetForeignPlan;
fdwroutine->ExplainForeignScan = obliviousExplainForeignScan;
fdwroutine->BeginForeignScan = obliviousBeginForeignScan;
fdwroutine->IterateForeignScan = obliviousIterateForeignScan;
fdwroutine->ReScanForeignScan = obliviousReScanForeignScan;
fdwroutine->EndForeignScan = obliviousEndForeignScan;
fdwroutine->AnalyzeForeignTable = obliviousAnalyzeForeignTable;
fdwroutine->IsForeignScanParallelSafe = obliviousIsForeignScanParallelSafe;
/* Oblivious insertion, update, deletion table functions */
fdwroutine->BeginForeignModify = obliviousBeginForeignModify;
fdwroutine->ExecForeignInsert = obliviousExecForeignInsert;
PG_RETURN_POINTER(fdwroutine);
}
/*
* Validate the generic options given to a FOREIGN DATA WRAPPER, SERVER,
* USER MAPPING or FOREIGN TABLE that uses file_fdw.
*
* Raise an ERROR if the option or its value is considered invalid.
*
* This function has to be completed, follow the example on file_fdw.c.
*/
Datum
oblivpg_fdw_validator(PG_FUNCTION_ARGS)
{
/* To Complete */
PG_RETURN_VOID();
}
static void
obliviousGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
/* To complete */
}
static void
obliviousGetForeignPaths(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid)
{
Path *path = NULL;
Cost startup_cost = DEFAULT_FDW_STARTUP_COST;
Cost total_cost = DEFAULT_OBLIV_FDW_TOTAL_COST;
path = (Path *) create_foreignscan_path(root, baserel,
NULL, /* default pathtarget */
baserel->rows,
startup_cost,
total_cost,
NIL, /* no pathkeys */
NULL, /* no outer rel either */
NULL, /* no extra plan */
NIL); /* no fdw_private list */
add_path(baserel, path);
}
static ForeignScan *
obliviousGetForeignPlan(PlannerInfo *root,
RelOptInfo *baserel,
Oid foreigntableid,
ForeignPath *best_path,
List *tlist,
List *scan_clauses,
Plan *outer_plan)
{
ForeignScan *foreignScan = NULL;
/*
* TODO: A future implementation might iterate over the scan_clauses list
* and filter any clause that is not going to be processed by the fdw. The
* current prototype assumes simple queries with a single clause with the
* following syntax: ... where colname op value
*/
scan_clauses = extract_actual_clauses(scan_clauses,
false); /* extract regular clauses */
foreignScan = make_foreignscan(tlist, scan_clauses, baserel->relid, NIL, NIL, NIL, NIL, NULL);
return foreignScan;
}
static void
obliviousBeginForeignScan(ForeignScanState *node, int eflags)
{
/**On the stream execution, this function should check if the necessary resources are initiated
*
* enclave
* constant rate thread
*
*
* For now, this code follows a similar logic as the sequential scan on the postgres code
* (nodeSeqscan.c -> ExecInitSeqScan).
*/
OblivScanState *fsstate;
Relation oblivFDWTable;
/* Ostatus obliv_status; */
FdwOblivTableStatus oStatus;
Relation oblivMappingRel;
Oid mappingOid;
List *scan_clauses;