forked from kaigai/pg_strom
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgpuscan.c
More file actions
2182 lines (1937 loc) · 57.1 KB
/
gpuscan.c
File metadata and controls
2182 lines (1937 loc) · 57.1 KB
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
/*
* gpuscan.c
*
* Sequential scan accelerated by GPU processors
* ----
* Copyright 2011-2014 (C) KaiGai Kohei <kaigai@kaigai.gr.jp>
* Copyright 2014 (C) The PG-Strom Development Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "postgres.h"
#include "access/sysattr.h"
#include "catalog/pg_type.h"
#include "catalog/pg_namespace.h"
#include "commands/explain.h"
#include "miscadmin.h"
#include "nodes/bitmapset.h"
#include "nodes/execnodes.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/plannodes.h"
#include "nodes/relation.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/var.h"
#include "parser/parsetree.h"
#include "storage/bufmgr.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/spccache.h"
#include "utils/syscache.h"
#include "utils/tqual.h"
#include "pg_strom.h"
#include "opencl_gpuscan.h"
static add_scan_path_hook_type add_scan_path_next;
static CustomPathMethods gpuscan_path_methods;
static CustomPlanMethods gpuscan_plan_methods;
static bool enable_gpuscan;
typedef struct {
CustomPath cpath;
List *dev_quals; /* RestrictInfo run on device */
List *host_quals; /* RestrictInfo run on host */
} GpuScanPath;
typedef struct {
CustomPlan cplan;
Index scanrelid; /* index of the range table */
const char *kern_source; /* source of opencl kernel */
int extra_flags; /* extra libraries to be included */
List *used_params; /* list of Const/Param in use */
List *used_vars; /* list of Var in use */
List *dev_clauses; /* clauses to be run on device */
} GpuScanPlan;
typedef struct {
CustomPlanState cps;
Relation scan_rel;
TupleTableSlot *scan_slot;
HeapTupleData scan_tuple;
BlockNumber curr_blknum;
BlockNumber last_blknum;
cl_uint tuple_width;
List *dev_quals;
pgstrom_queue *mqueue;
Datum dprog_key;
kern_parambuf *kparams;
pgstrom_gpuscan *curr_chunk;
uint32 curr_index;
int num_running;
dlist_head ready_chunks;
pgstrom_perfmon pfm; /* sum of performance counter */
} GpuScanState;
/* static functions */
static void clserv_process_gpuscan(pgstrom_message *msg);
/*
* cost_gpuscan
*
* cost estimation for GpuScan
*/
static void
cost_gpuscan(GpuScanPath *gpu_path, PlannerInfo *root,
RelOptInfo *baserel, ParamPathInfo *param_info,
List *dev_quals, List *host_quals, bool is_bulkload)
{
Path *path = &gpu_path->cpath.path;
Cost startup_cost = 0;
Cost run_cost = 0;
double spc_seq_page_cost;
QualCost dev_cost;
QualCost host_cost;
Cost gpu_per_tuple;
Cost cpu_per_tuple;
Selectivity dev_sel;
/* Should only be applied to base relations */
Assert(baserel->relid > 0);
Assert(baserel->rtekind == RTE_RELATION);
/* Mark the path with the correct row estimate */
if (param_info)
path->rows = param_info->ppi_rows;
else
path->rows = baserel->rows;
/* fetch estimated page cost for tablespace containing table */
get_tablespace_page_costs(baserel->reltablespace,
NULL,
&spc_seq_page_cost);
/* Disk costs */
run_cost += spc_seq_page_cost * baserel->pages;
/* GPU costs */
cost_qual_eval(&dev_cost, dev_quals, root);
dev_sel = clauselist_selectivity(root, dev_quals, 0, JOIN_INNER, NULL);
dev_cost.startup += pgstrom_gpu_setup_cost;
if (cpu_tuple_cost > 0.0)
dev_cost.per_tuple *= pgstrom_gpu_tuple_cost / cpu_tuple_cost;
else
dev_cost.per_tuple += disable_cost;
/* CPU costs */
cost_qual_eval(&host_cost, host_quals, root);
if (param_info)
{
QualCost param_cost;
/* Include costs of pushed-down clauses */
cost_qual_eval(¶m_cost, param_info->ppi_clauses, root);
host_cost.startup += param_cost.startup;
host_cost.per_tuple += param_cost.per_tuple;
}
/* total path cost */
startup_cost += dev_cost.startup + host_cost.startup;
if (!is_bulkload)
cpu_per_tuple = host_cost.per_tuple + cpu_tuple_cost;
else
cpu_per_tuple = host_cost.per_tuple;
gpu_per_tuple = dev_cost.per_tuple;
run_cost += (gpu_per_tuple * baserel->tuples +
cpu_per_tuple * dev_sel * baserel->tuples);
gpu_path->cpath.path.startup_cost = startup_cost;
gpu_path->cpath.path.total_cost = startup_cost + run_cost;
}
static void
gpuscan_add_scan_path(PlannerInfo *root,
RelOptInfo *baserel,
RangeTblEntry *rte)
{
GpuScanPath *pathnode;
List *dev_quals = NIL;
List *host_quals = NIL;
ListCell *cell;
codegen_context context;
/* call the secondary hook */
if (add_scan_path_next)
add_scan_path_next(root, baserel, rte);
/* nothing to do, if either PG-Strom or GpuScan is not enabled */
if (!pgstrom_enabled() || !enable_gpuscan)
return;
/* only base relation we can handle */
if (baserel->rtekind != RTE_RELATION || baserel->relid == 0)
return;
/* system catalog is not supported */
if (get_rel_namespace(rte->relid) == PG_CATALOG_NAMESPACE)
return;
/* check whether the qualifier can run on GPU device, or not */
pgstrom_init_codegen_context(&context);
foreach (cell, baserel->baserestrictinfo)
{
RestrictInfo *rinfo = lfirst(cell);
if (pgstrom_codegen_available_expression(rinfo->clause))
dev_quals = lappend(dev_quals, rinfo);
else
host_quals = lappend(host_quals, rinfo);
}
/*
* FIXME: needs to pay attention for projection cost.
*/
/*
* Construction of a custom-plan node.
*/
pathnode = palloc0(sizeof(GpuScanPath));
pathnode->cpath.path.type = T_CustomPath;
pathnode->cpath.path.pathtype = T_CustomPlan;
pathnode->cpath.path.parent = baserel;
pathnode->cpath.path.param_info
= get_baserel_parampathinfo(root, baserel, baserel->lateral_relids);
pathnode->cpath.path.pathkeys = NIL; /* gpuscan has unsorted result */
pathnode->cpath.methods = &gpuscan_path_methods;
cost_gpuscan(pathnode, root, baserel,
pathnode->cpath.path.param_info,
dev_quals, host_quals, false);
pathnode->dev_quals = dev_quals;
pathnode->host_quals = host_quals;
add_path(baserel, &pathnode->cpath.path);
}
/*
* gpuscan_try_replace_seqscan_path
*
* It tries to replace the supplied SeqScan path by GpuScan, if it is
* enough simple. Even though seq_path didn't involve any qualifiers,
* it makes sense if parent path is managed by PG-Strom because of bulk-
* loading functionality.
*/
Path *
gpuscan_try_replace_seqscan_path(PlannerInfo *root, Path *path,
List **p_upper_quals)
{
RelOptInfo *rel = path->parent;
GpuScanPath *gpath;
ListCell *lc;
int i;
/* enable_gpuscan has to be turned on */
if (!enable_gpuscan)
return path;
/* !!! See the logic in use_physical_tlist() !!! */
/* shortcut checks, if unavailable to replace */
if (rel->rtekind != RTE_RELATION)
return path;
if (rel->reloptkind != RELOPT_BASEREL)
return path;
/*
* System column reference involves projection, so unavailable
* to have bulk-loading.
*/
for (i = rel->min_attr; i <= 0; i++)
{
if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
return path;
}
/*
* Can't replace it if the rel is required to emit any placeholder
* expressions, either.
*/
foreach (lc, root->placeholder_list)
{
PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
if (bms_nonempty_difference(phinfo->ph_needed, rel->relids) &&
bms_is_subset(phinfo->ph_eval_at, rel->relids))
return path;
}
/* OK, check individual path-node */
if (path->pathtype == T_SeqScan)
{
List *dev_quals = NIL;
/* Simple SeqScan has only device executable qualifier */
foreach (lc, rel->baserestrictinfo)
{
RestrictInfo *rinfo = lfirst(lc);
if (!pgstrom_codegen_available_expression(rinfo->clause))
return path;
dev_quals = lappend(dev_quals, rinfo);
}
/* OK, probably GpuScan instead of SeqScan makes sense */
gpath = palloc0(sizeof(GpuScanPath));
gpath->cpath.path.type = T_CustomPath;
gpath->cpath.path.pathtype = T_CustomPlan;
gpath->cpath.path.parent = rel;
gpath->cpath.path.param_info
= get_baserel_parampathinfo(root, rel, rel->lateral_relids);
gpath->cpath.path.pathkeys = NIL; /* gpuscan has unsorted result */
gpath->cpath.methods = &gpuscan_path_methods;
gpath->dev_quals = copyObject(dev_quals);
gpath->host_quals = NIL;
}
else if (pgstrom_path_is_gpuscan(path))
{
GpuScanPath *gpath_orig = (GpuScanPath *) path;
/* we cannot pull up dev_quals from GpuScan with host_qual */
if (gpath_orig->host_quals != NIL)
return path;
/* it does not make sense to pull-up device qualifier */
if (gpath_orig->dev_quals == NIL)
return path;
gpath = palloc0(sizeof(GpuScanPath));
gpath->cpath.path.type = T_CustomPath;
gpath->cpath.path.pathtype = T_CustomPlan;
gpath->cpath.path.parent = rel;
gpath->cpath.path.param_info
= get_baserel_parampathinfo(root, rel, rel->lateral_relids);
gpath->cpath.path.pathkeys = NIL; /* gpuscan has unsorted result */
gpath->cpath.methods = &gpuscan_path_methods;
gpath->dev_quals = copyObject(gpath_orig->dev_quals);
gpath->host_quals = NIL;
}
else
return path; /* elsewhere, unavailable to replace */
/*
* If upper node allows to device executable qualifier, we hand
* over this evaluation on the upper node. Unlike usual query
* planning policy, qualifier pull-up enables to reduce interaction
* between backend and opencl server So, it makes sense probably.
*/
if (p_upper_quals && gpath->dev_quals)
{
RelOptInfo rel_fake;
/* move the device qualifier */
*p_upper_quals = gpath->dev_quals;
gpath->dev_quals = NIL;
Assert(gpath->host_quals == NIL);
/* adjust number of rows estimated */
memcpy(&rel_fake, rel, sizeof(RelOptInfo));
rel_fake.rows = rel_fake.tuples;
cost_gpuscan(gpath, root, &rel_fake,
gpath->cpath.path.param_info,
NIL, NIL, true);
}
else
{
cost_gpuscan(gpath, root, rel,
gpath->cpath.path.param_info,
gpath->dev_quals, NIL, true);
}
return (Path *) gpath;
}
/*
* gpuscan_try_replace_seqscan_plan
*
* It tries to replace the supplied SeqScan plan by GpuScan, if it is
* enough simple. Even though seq_path didn't involve any qualifiers,
* it makes sense if parent path is managed by PG-Strom because of bulk-
* loading functionality.
*/
Plan *
gpuscan_try_replace_seqscan_plan(PlannedStmt *pstmt,
Plan *plan,
Bitmapset *attr_refs,
List **p_upper_quals)
{
Index scanrelid;
RangeTblEntry *rte;
Relation relation;
GpuScanPlan *gscan;
ListCell *lc;
BlockNumber num_pages;
double num_tuples;
double allvisfrac;
double spc_seq_page_cost;
Oid tablespace_oid;
/* enable_gpuscan has to be turned on */
if (!enable_gpuscan)
return plan;
if (IsA(plan, SeqScan))
{
scanrelid = ((Scan *) plan)->scanrelid;
rte = rt_fetch(scanrelid, pstmt->rtable);
if (rte->rtekind != RTE_RELATION)
return plan; /* usually, shouldn't happen */
if (rte->relkind != RELKIND_RELATION &&
rte->relkind != RELKIND_TOASTVALUE &&
rte->relkind != RELKIND_MATVIEW)
return plan; /* usually, shouldn't happen */
/*
* check whether the device referenced target-entry can be
* constructed on the device side. no need to care about
* host-only fields.
*/
foreach (lc, plan->targetlist)
{
TargetEntry *tle = lfirst(lc);
int x = tle->resno - FirstLowInvalidHeapAttributeNumber;
if (!bms_is_member(x, attr_refs))
continue;
if (!pgstrom_codegen_available_expression(tle->expr))
return plan;
}
/*
* check whether the plan qualifiers can be executable on the
* device side. If host only expression is here, unavailable
* to replace it by GpuScan.
*/
if (!pgstrom_codegen_available_expression((Expr *)plan->qual))
return plan;
/*
* OK, SeqScan can be replaced by GpuScan
*/
gscan = palloc0(sizeof(GpuScanPlan));
gscan->cplan.plan.type = T_CustomPlan;
gscan->cplan.plan.plan_width = plan->plan_width;
gscan->cplan.plan.targetlist = plan->targetlist;
gscan->cplan.plan.qual = NIL;
gscan->cplan.plan.lefttree = NULL;
gscan->cplan.plan.righttree = NULL;
gscan->cplan.methods = &gpuscan_plan_methods;
gscan->scanrelid = scanrelid;
gscan->kern_source = NULL;
gscan->extra_flags = DEVKERNEL_NEEDS_GPUSCAN |
(!devprog_enable_optimize ? DEVKERNEL_DISABLE_OPTIMIZE : 0);
gscan->used_params = NIL;
gscan->used_vars = NIL;
gscan->dev_clauses = copyObject(plan->qual);
}
else if (pgstrom_plan_is_gpuscan(plan))
{
gscan = (GpuScanPlan *) plan;
scanrelid = gscan->scanrelid;
rte = rt_fetch(scanrelid, pstmt->rtable);
Assert(rte->rtekind == RTE_RELATION);
Assert(rte->relkind == RELKIND_RELATION ||
rte->relkind == RELKIND_TOASTVALUE ||
rte->relkind == RELKIND_MATVIEW);
/* unavailable to pull-up host only qualifiers */
if (gscan->cplan.plan.qual != NIL)
return plan;
/* it does not make sense to replace GpuScan again */
if (!gscan->dev_clauses)
return plan;
/* duplication to modify field below */
gscan = copyObject(plan);
}
else
return plan; /* elsewhere, unavailable to replace */
/*
* pull-up device executable qualifiers, if available
*/
if (p_upper_quals && gscan->dev_clauses)
{
*p_upper_quals = gscan->dev_clauses;
gscan->dev_clauses = NIL;
/* it also leads no kernel execution in GpuScan node */
gscan->kern_source = NULL;
gscan->extra_flags &= DEVKERNEL_DISABLE_OPTIMIZE;
gscan->used_params = NIL;
gscan->used_vars = NIL;
}
/* FIXME: we may have p_upper_quals != NULL on call */
Assert(gscan->dev_clauses == NIL);
/*
* update cost estimation for the GpuScan node
*
* TODO: integration with cost_gpuscan() for more consistency.
*/
relation = heap_open(rte->relid, NoLock);
estimate_rel_size(relation, NULL,
&num_pages,
&num_tuples,
&allvisfrac);
/* fetch estimated page cost for tablespace containing table */
tablespace_oid = RelationGetForm(relation)->reltablespace;
get_tablespace_page_costs(tablespace_oid, NULL, &spc_seq_page_cost);
/* only disk cost to be paid attention */
gscan->cplan.plan.plan_rows = num_tuples;
gscan->cplan.plan.startup_cost = 0.0;
gscan->cplan.plan.total_cost = spc_seq_page_cost * num_pages;
heap_close(relation, NoLock);
return (Plan *) gscan;
}
/*
* OpenCL code generation that can run on GPU/MIC device
*/
static char *
gpuscan_codegen_quals(PlannerInfo *root, List *dev_quals,
codegen_context *context)
{
StringInfoData str;
StringInfoData decl;
char *expr_code;
pgstrom_init_codegen_context(context);
if (dev_quals == NIL)
return NULL;
/* OK, let's walk on the device expression tree */
expr_code = pgstrom_codegen_expression((Node *)dev_quals, context);
Assert(expr_code != NULL);
initStringInfo(&decl);
initStringInfo(&str);
/*
* make declarations of var and param references
*/
appendStringInfo(&str, "%s\n", pgstrom_codegen_func_declarations(context));
appendStringInfo(&decl, "%s%s\n",
pgstrom_codegen_param_declarations(context,
context->param_refs),
pgstrom_codegen_var_declarations(context));
/* qualifier definition with row-store */
appendStringInfo(
&str,
"static pg_bool_t\n"
"gpuscan_qual_eval(__private cl_int *errcode,\n"
" __global kern_parambuf *kparams,\n"
" __global kern_data_store *kds,\n"
" __global kern_data_store *ktoast,\n"
" size_t kds_index)\n"
"{\n"
"%s"
" return %s;\n"
"}\n", decl.data, expr_code);
return str.data;
}
static CustomPlan *
gpuscan_create_plan(PlannerInfo *root, CustomPath *best_path)
{
RelOptInfo *rel = best_path->path.parent;
GpuScanPath *gpath = (GpuScanPath *)best_path;
GpuScanPlan *gscan;
List *tlist;
List *host_clauses;
List *dev_clauses;
char *kern_source;
codegen_context context;
/*
* See the comments in create_scan_plan(). We may be able to omit
* projection of the table tuples, if possible.
*/
if (use_physical_tlist(root, rel))
{
tlist = build_physical_tlist(root, rel);
if (tlist == NIL)
tlist = build_path_tlist(root, &best_path->path);
}
else
tlist = build_path_tlist(root, &best_path->path);
/* it should be a base relation */
Assert(rel->relid > 0);
Assert(rel->rtekind == RTE_RELATION);
/* Sort clauses into best execution order */
host_clauses = order_qual_clauses(root, gpath->host_quals);
dev_clauses = order_qual_clauses(root, gpath->dev_quals);
/* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
host_clauses = extract_actual_clauses(host_clauses, false);
dev_clauses = extract_actual_clauses(dev_clauses, false);
/* Replace any outer-relation variables with nestloop params */
if (best_path->path.param_info)
{
host_clauses = (List *)
replace_nestloop_params(root, (Node *) host_clauses);
dev_clauses = (List *)
replace_nestloop_params(root, (Node *) dev_clauses);
}
/*
* Construct OpenCL kernel code
*/
kern_source = gpuscan_codegen_quals(root, dev_clauses, &context);
/*
* Construction of GpuScanPlan node; on top of CustomPlan node
*/
gscan = palloc0(sizeof(GpuScanPlan));
gscan->cplan.plan.type = T_CustomPlan;
gscan->cplan.plan.targetlist = tlist;
gscan->cplan.plan.qual = host_clauses;
gscan->cplan.plan.lefttree = NULL;
gscan->cplan.plan.righttree = NULL;
gscan->cplan.methods = &gpuscan_plan_methods;
gscan->scanrelid = rel->relid;
gscan->kern_source = kern_source;
gscan->extra_flags = context.extra_flags |
DEVKERNEL_NEEDS_GPUSCAN |
(!devprog_enable_optimize ? DEVKERNEL_DISABLE_OPTIMIZE : 0);
gscan->used_params = context.used_params;
gscan->used_vars = context.used_vars;
gscan->dev_clauses = dev_clauses;
return &gscan->cplan;
}
static void
gpuscan_textout_path(StringInfo str, Node *node)
{
GpuScanPath *pathnode = (GpuScanPath *) node;
char *temp;
/* dev_quals */
temp = nodeToString(pathnode->dev_quals);
appendStringInfo(str, " :dev_quals %s", temp);
pfree(temp);
/* host_quals */
temp = nodeToString(pathnode->host_quals);
appendStringInfo(str, " :host_quals %s", temp);
pfree(temp);
}
static void
gpuscan_set_plan_ref(PlannerInfo *root,
CustomPlan *custom_plan,
int rtoffset)
{
GpuScanPlan *gscan = (GpuScanPlan *)custom_plan;
gscan->scanrelid += rtoffset;
gscan->cplan.plan.targetlist = (List *)
fix_scan_expr(root, (Node *)gscan->cplan.plan.targetlist, rtoffset);
gscan->cplan.plan.qual = (List *)
fix_scan_expr(root, (Node *)gscan->cplan.plan.qual, rtoffset);
gscan->used_vars = (List *)
fix_scan_expr(root, (Node *)gscan->used_vars, rtoffset);
gscan->dev_clauses = (List *)
fix_scan_expr(root, (Node *)gscan->dev_clauses, rtoffset);
}
static void
gpuscan_finalize_plan(PlannerInfo *root,
CustomPlan *custom_plan,
Bitmapset **paramids,
Bitmapset **valid_params,
Bitmapset **scan_params)
{
*paramids = bms_add_members(*paramids, *scan_params);
}
/*
* pgstrom_gpuscan_can_bulkload (obsolete!)
*
* It tells caller whether the supplied custom-plan-state is GpuScan and
* can support bulk-loading, or not.
*/
bool
pgstrom_gpuscan_can_bulkload(const CustomPlanState *cps)
{
if (cps->methods == &gpuscan_plan_methods &&
!cps->ps.ps_ProjInfo)
return true;
return false;
}
/*
* pgstrom_path_is_gpuscan
*
* It returns true, if supplied path node is gpuscan.
*/
bool
pgstrom_path_is_gpuscan(const Path *path)
{
if (IsA(path, CustomPath) &&
path->pathtype == T_CustomPlan &&
((CustomPath *) path)->methods == &gpuscan_path_methods)
return true;
return false;
}
/*
* pgstrom_plan_is_gpuscan
*
* It returns true, if supplied plan node is gpuscan.
*/
bool
pgstrom_plan_is_gpuscan(const Plan *plan)
{
CustomPlan *cplan = (CustomPlan *) plan;
if (IsA(cplan, CustomPlan) &&
cplan->methods == &gpuscan_plan_methods)
return true;
return false;
}
/*
* pgstrom_gpuscan_setup_bulkslot
*
* It setup tuple-slot for bulk-loading and projection-info to transform
* the tuple into expected form.
* (Once CustomPlan become CustomScan, no need to be a API)
*/
void
pgstrom_gpuscan_setup_bulkslot(PlanState *outer_ps,
ProjectionInfo **p_bulk_proj,
TupleTableSlot **p_bulk_slot)
{
GpuScanState *gss = (GpuScanState *) outer_ps;
if (!IsA(gss, CustomPlanState) ||
gss->cps.methods != &gpuscan_plan_methods)
elog(ERROR, "Bug? PlanState node is not GpuScan");
*p_bulk_proj = gss->cps.ps.ps_ProjInfo;
*p_bulk_slot = gss->scan_slot;
}
static CustomPlanState *
gpuscan_begin(CustomPlan *node, EState *estate, int eflags)
{
GpuScanPlan *gsplan = (GpuScanPlan *) node;
Index scanrelid = gsplan->scanrelid;
GpuScanState *gss;
TupleDesc tupdesc;
BlockNumber relpages;
double reltuples;
double allvisfrac;
/* gpuscan should not have inner/outer plan now */
Assert(outerPlan(node) == NULL);
Assert(innerPlan(node) == NULL);
/*
* create a state structure
*/
gss = palloc0(sizeof(GpuScanState));
gss->cps.ps.type = T_CustomPlanState;
gss->cps.ps.plan = (Plan *) node;
gss->cps.ps.state = estate;
gss->cps.methods = &gpuscan_plan_methods;
/*
* create expression context
*/
ExecAssignExprContext(estate, &gss->cps.ps);
/*
* initialize child expressions
*/
gss->cps.ps.targetlist = (List *)
ExecInitExpr((Expr *) node->plan.targetlist, &gss->cps.ps);
gss->cps.ps.qual = (List *)
ExecInitExpr((Expr *) node->plan.qual, &gss->cps.ps);
gss->dev_quals = (List *)
ExecInitExpr((Expr *) gsplan->dev_clauses, &gss->cps.ps);
/*
* tuple table initialization
*/
ExecInitResultTupleSlot(estate, &gss->cps.ps);
gss->scan_slot = ExecAllocTableSlot(&estate->es_tupleTable);
/*
* initialize scan relation
*/
gss->scan_rel = ExecOpenScanRelation(estate, scanrelid, eflags);
tupdesc = RelationGetDescr(gss->scan_rel);
ExecSetSlotDescriptor(gss->scan_slot, tupdesc);
gss->scan_tuple.t_tableOid = RelationGetRelid(gss->scan_rel);
/*
* Initialize result tuple type and projection info.
*/
ExecAssignResultTypeFromTL(&gss->cps.ps);
if (tlist_matches_tupdesc(&gss->cps.ps,
node->plan.targetlist,
scanrelid,
tupdesc))
gss->cps.ps.ps_ProjInfo = NULL;
else
ExecAssignProjectionInfo(&gss->cps.ps, tupdesc);
/*
* OK, let's initialize stuff for block scan
*/
gss->curr_blknum = 0;
gss->last_blknum = RelationGetNumberOfBlocks(gss->scan_rel);
estimate_rel_size(gss->scan_rel, NULL,
&relpages, &reltuples, &allvisfrac);
gss->tuple_width = (Size)((double)BLCKSZ * (double)relpages / reltuples);
/*
* Setting up kernel program, if needed
*/
if (gsplan->kern_source)
{
gss->dprog_key = pgstrom_get_devprog_key(gsplan->kern_source,
gsplan->extra_flags);
pgstrom_track_object((StromObject *)gss->dprog_key, 0);
/* also, message queue */
gss->mqueue = pgstrom_create_queue();
pgstrom_track_object(&gss->mqueue->sobj, 0);
}
gss->kparams = pgstrom_create_kern_parambuf(gsplan->used_params,
gss->cps.ps.ps_ExprContext);
/* rest of run-time parameters */
gss->curr_chunk = NULL;
gss->curr_index = 0;
gss->num_running = 0;
dlist_init(&gss->ready_chunks);
/* Is perfmon needed? */
gss->pfm.enabled = pgstrom_perfmon_enabled;
return &gss->cps;
}
/*
* pgstrom_release_gpuscan
*
* Callback handler when reference counter of pgstrom_gpuscan object
* reached to zero, due to pgstrom_put_message.
* It also unlinks associated device program and release row-store.
* Note that this callback shall never be invoked under the OpenCL
* server context, because some resources (like shared-buffer) are
* assumed to be released by the backend process.
*/
static void
pgstrom_release_gpuscan(pgstrom_message *msg)
{
pgstrom_gpuscan *gpuscan = (pgstrom_gpuscan *) msg;
/* unlink message queue, if any */
if (msg->respq)
pgstrom_put_queue(msg->respq);
/* unlink device program, if any */
if (gpuscan->dprog_key != 0)
pgstrom_put_devprog_key(gpuscan->dprog_key);
/* release data-store, if any */
if (gpuscan->pds)
pgstrom_put_data_store(gpuscan->pds);
pgstrom_shmem_free(gpuscan);
}
static pgstrom_gpuscan *
pgstrom_create_gpuscan(GpuScanState *gss, pgstrom_data_store *pds)
{
pgstrom_gpuscan *gpuscan;
kern_data_store *kds = pds->kds;
kern_resultbuf *kresults;
cl_uint nitems = kds->nitems;
Size length;
length = (STROMALIGN(offsetof(pgstrom_gpuscan, kern.kparams)) +
STROMALIGN(gss->kparams->length) +
STROMALIGN(offsetof(kern_resultbuf, results[nitems])));
gpuscan = pgstrom_shmem_alloc(length);
if (!gpuscan)
elog(ERROR, "out of shared memory");
/* fields of pgstrom_gpuscan */
pgstrom_init_message(&gpuscan->msg,
StromTag_GpuScan,
gss->dprog_key != 0 ? gss->mqueue : NULL,
clserv_process_gpuscan,
pgstrom_release_gpuscan,
gss->pfm.enabled);
if (gss->dprog_key != 0)
gpuscan->dprog_key = pgstrom_retain_devprog_key(gss->dprog_key);
else
gpuscan->dprog_key = 0;
gpuscan->pds = pds;
/* copy kern_parambuf */
Assert(gss->kparams->length == STROMALIGN(gss->kparams->length));
memcpy(KERN_GPUSCAN_PARAMBUF(&gpuscan->kern),
gss->kparams,
gss->kparams->length);
/* setting up resultbuf */
kresults = KERN_GPUSCAN_RESULTBUF(&gpuscan->kern);
memset(kresults, 0, sizeof(kern_resultbuf));
kresults->nrels = 1;
kresults->nrooms = nitems;
/* If GpuScan does not involve kernel execution, we treat this
* chunk as all-visible. */
if (gss->dprog_key == 0)
{
kresults->all_visible = true;
kresults->nitems = nitems;
}
return gpuscan;
}
static pgstrom_gpuscan *
pgstrom_load_gpuscan(GpuScanState *gss)
{
pgstrom_gpuscan *gpuscan = NULL;
Relation rel = gss->scan_rel;
TupleDesc tupdesc = RelationGetDescr(rel);
Snapshot snapshot = gss->cps.ps.state->es_snapshot;
Size length;
pgstrom_data_store *pds;
struct timeval tv1, tv2;
/* no more blocks to read */
if (gss->curr_blknum > gss->last_blknum)
return NULL;
if (gss->pfm.enabled)
gettimeofday(&tv1, NULL);
retry:
length = (pgstrom_chunk_size << 20);
pds = pgstrom_create_data_store_row(tupdesc, length, gss->tuple_width);
PG_TRY();
{
while (gss->curr_blknum < gss->last_blknum &&
pgstrom_data_store_insert_block(pds, rel,
gss->curr_blknum,
snapshot, true) >= 0)
gss->curr_blknum++;
if (pds->kds->nitems > 0)
gpuscan = pgstrom_create_gpuscan(gss, pds);
else
{
pgstrom_put_data_store(pds);
/* NOTE: In case when it scans on a large hole (that is
* continuous blocks contain invisible tuples only; may
* be created by DELETE with relaxed condition),
* pgstrom_data_store_insert_block() may return negative
* value without valid tuples, even though we don't reach
* either end of relation or chunk.
* So, we need to check whether we actually touched on
* the end-of-relation. If not, retry scanning.
*/
if (gss->curr_blknum < gss->last_blknum)
goto retry;
}
}
PG_CATCH();
{
pgstrom_put_data_store(pds);
PG_RE_THROW();
}
PG_END_TRY();
/* track local object */
if (gpuscan)
pgstrom_track_object(&gpuscan->msg.sobj, 0);
/* update perfmon statistics */
if (gss->pfm.enabled)
{
gettimeofday(&tv2, NULL);
gss->pfm.time_outer_load += timeval_diff(&tv1, &tv2);
}
return gpuscan;
}
static TupleTableSlot *
gpuscan_next_tuple(GpuScanState *gss)