-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathgpuhashjoin.c
5073 lines (4576 loc) · 137 KB
/
gpuhashjoin.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
/*
* gpuhashjoin.c
*
* Hash-Join acceleration by GPU processors
* ----
* Copyright 2011-2014 (C) KaiGai Kohei <[email protected]>
* 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 "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/relation.h"
#include "nodes/plannodes.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/subselect.h"
#include "optimizer/tlist.h"
#include "optimizer/var.h"
#include "parser/parsetree.h"
#include "parser/parse_coerce.h"
#include "storage/ipc.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/pg_crc.h"
#include "utils/selfuncs.h"
#include "pg_strom.h"
#include "opencl_hashjoin.h"
/* static variables */
static add_hashjoin_path_hook_type add_hashjoin_path_next;
static CustomPathMethods gpuhashjoin_path_methods;
static CustomPlanMethods gpuhashjoin_plan_methods;
static CustomPlanMethods multihash_plan_methods;
static bool enable_gpuhashjoin;
/*
* (depth=0)
* [GpuHashJoin] ---<outer>--- [relation scan to be joined]
* |
* <inner>
* | (depth=1)
* +-- [MultiHash] ---<outer>--- [relation scan to be hashed]
* |
* <inner>
* | (depth=2)
* +-- [MultiHash] ---<outer>--- [relation scan to be hashed]
*
* The diagram above shows structure of GpuHashJoin which can have a hash-
* table that contains multiple inner scans. GpuHashJoin always takes a
* MultiHash node as inner relation to join it with outer relation, then
* materialize them into a single pseudo relation view. A MultiHash node
* has an outer relation to be hashed, and can optionally have another
* MultiHash node to put multiple inner (small) relations on a hash-table.
* A smallest set of GpuHashJoin is consists of an outer relation and
* an inner MultiHash node. When third relation is added, it inject the
* third relation on the inner-tree of GpuHashJoin. So, it means the
* deepest MultiHash is the first relation to be joined with outer
* relation, then second deepest one shall be joined, in case when order
* of join needs to be paid attention.
*/
typedef struct
{
CustomPath cpath;
Path *outerpath; /* outer path (always one) */
int num_rels; /* number of inner relations */
Size hashtable_size; /* estimated hashtable size */
struct {
Path *scan_path;
JoinType jointype;
List *hash_clause;
List *qual_clause;
List *host_clause;
double threshold_ratio;
Size chunk_size; /* available size for each relation chunk */
cl_uint ntuples; /* estimated number of tuples per chunk */
cl_uint nloops; /* expected number of outer loops */
} inners[FLEXIBLE_ARRAY_MEMBER];
} GpuHashJoinPath;
/*
* source of pseudo tlist entries
*/
typedef struct
{
Index srcdepth; /* source relation depth */
AttrNumber srcresno; /* source resource number (>0) */
AttrNumber resno; /* resource number of pseudo relation */
char *resname; /* name of this resource, if any */
Oid vartype; /* type oid of the expression node */
int32 vartypmod; /* typmod value of the expression node */
Oid varcollid; /* collation oid of the expression node */
bool ref_host; /* true, if referenced in host expression */
bool ref_device; /* true, if referenced in device expression */
Expr *expr; /* source Var or PlaceHolderVar node */
} vartrans_info;
typedef struct
{
CustomPlan cplan;
/*
* outerPlan ... relation to be joined
* innerPlan ... MultiHash with multiple inner relations
*/
int num_rels; /* number of underlying MultiHash */
const char *kernel_source;
int extra_flags;
bool outer_bulkload; /* is outer can bulk loading? */
List *join_types; /* list of join types */
List *hash_clauses; /* list of hash_clause (List *) */
List *qual_clauses; /* list of qual_clause (List *) */
List *host_clauses; /* list of host_clause (List *) */
List *used_params; /* template for kparams */
Bitmapset *outer_attrefs; /* bitmap of referenced outer columns */
List *pscan_vartrans; /* list of vartrans_info */
} GpuHashJoin;
typedef struct
{
CustomPlan cplan;
/*
* outerPlan ... relation to be hashed
* innerPlan ... one another MultiHash, if any
*/
int depth; /* depth of this hash table */
cl_uint nslots; /* width of hash slots */
cl_uint nloops; /* expected number of outer loops */
double threshold_ratio;
Size hashtable_size; /* estimated total hashtable size */
List *hash_inner_keys;/* list of inner hash key expressions */
List *hash_outer_keys;/* list of outer hash key expressions */
/*
* NOTE: Any varno of the var-nodes in hash_inner_keys references
* OUTER_VAR, because this expression node is used to calculate
* hash-value of individual entries on construction of MultiHashNode
* during outer relation scan.
* On the other hands, any varno of the var-nodes in hash_outer_keys
* references INDEX_VAR with varattno on the pseudo tlist, because
* it is used for code generation.
*/
} MultiHash;
/*
* MultiHashNode - a data structure to be returned from MultiHash node;
* that contains a pgstrom_multihash_tables object on shared memory
* region and related tuplestore/tupleslot for each inner relations.
*/
typedef struct {
Node type; /* T_Invalid */
pgstrom_multihash_tables *mhtables;
int nrels;
} MultiHashNode;
typedef struct
{
CustomPlanState cps;
List *join_types;
List *hash_clauses;
List *qual_clauses;
List *host_clauses;
pgstrom_multihash_tables *mhtables;
int pscan_nattrs;
vartrans_info *pscan_vartrans;
TupleTableSlot *pscan_slot;
TupleTableSlot *pscan_wider_slot;
ProjectionInfo *pscan_projection;
ProjectionInfo *pscan_wider_projection;
/* average ratio to popurate result row */
double row_population_ratio;
/* average number of tuples per page */
double ntups_per_page;
/* state for outer scan */
bool outer_done;
bool outer_bulkload;
TupleTableSlot *outer_overflow;
pgstrom_queue *mqueue;
Datum dprog_key;
kern_parambuf *kparams;
pgstrom_gpuhashjoin *curr_ghjoin;
cl_uint curr_index;
bool curr_recheck;
cl_int num_running;
dlist_head ready_pscans;
pgstrom_perfmon pfm;
} GpuHashJoinState;
typedef struct {
CustomPlanState cps;
int depth;
cl_uint nslots;
double threshold_ratio;
Size chunk_size;
Size hashtable_size;
TupleTableSlot *outer_overflow;
bool outer_done;
kern_hashtable *curr_chunk;
List *hash_keys;
List *hash_keylen;
List *hash_keybyval;
} MultiHashState;
/* declaration of static functions */
static void clserv_process_gpuhashjoin(pgstrom_message *message);
/*
* path_is_gpuhashjoin - returns true, if supplied pathnode is gpuhashjoin
*/
static bool
path_is_gpuhashjoin(Path *pathnode)
{
CustomPath *cpath = (CustomPath *) pathnode;
if (!IsA(cpath, CustomPath))
return false;
if (cpath->methods != &gpuhashjoin_path_methods)
return false;
return true;
}
/*
* path_is_mergeable_gpuhashjoin - returns true, if supplied pathnode is
* gpuhashjoin that can be merged with one more inner scan.
*/
static bool
path_is_mergeable_gpuhashjoin(Path *pathnode)
{
RelOptInfo *rel = pathnode->parent;
GpuHashJoinPath *gpath;
List *host_clause;
ListCell *cell;
int last;
if (!path_is_gpuhashjoin(pathnode))
return false;
gpath = (GpuHashJoinPath *) pathnode;
last = gpath->num_rels - 1;
/*
* target-list must be simple var-nodes only
*/
foreach (cell, rel->reltargetlist)
{
Expr *expr = lfirst(cell);
if (!IsA(expr, Var))
return false;
}
/*
* Only INNER JOIN is supported right now
*/
if (gpath->inners[last].jointype != JOIN_INNER)
return false;
/*
* Host qual should not contain volatile function except for
* the last inner relation
*/
host_clause = gpath->inners[last].host_clause;
foreach (cell, host_clause)
{
RestrictInfo *rinfo = lfirst(cell);
Assert(IsA(rinfo, RestrictInfo));
if (contain_volatile_functions((Node *)rinfo->clause))
return false;
}
/*
* TODO: Is any other condition to be checked?
*/
return true;
}
/*
* pgstrom_plan_is_multihash - returns true, if supplied plan is multihash
*/
bool
pgstrom_plan_is_multihash(const Plan *plan)
{
CustomPlan *cplan = (CustomPlan *) plan;
if (IsA(cplan, CustomPlan) &&
cplan->methods == &multihash_plan_methods)
return true;
return false;
}
/*
* estimate_hashitem_size
*
* It estimates size of hashitem for GpuHashJoin
*/
static bool
estimate_hashtable_size(PlannerInfo *root,
GpuHashJoinPath *gpath,
Relids required_outer,
JoinCostWorkspace *workspace)
{
RelOptInfo *joinrel = gpath->cpath.path.parent;
Size hashtable_size;
Size threshold_size;
cl_int numbatches;
bool is_first = true;
do {
Size largest_size;
cl_int i_largest;
cl_int i, nrels = gpath->num_rels;
/* increment outer loop count to reduce size of hash table */
if (!is_first)
gpath->inners[i_largest].nloops++;
numbatches = 1;
largest_size = 0;
i_largest = -1;
hashtable_size = LONGALIGN(offsetof(kern_multihash,
htable_offset[nrels]));
for (i=0; i < nrels; i++)
{
Path *scan_path = gpath->inners[i].scan_path;
RelOptInfo *scan_rel = scan_path->parent;
cl_uint ncols = list_length(scan_rel->reltargetlist);
double ntuples;
Size entry_size;
Size chunk_size;
if (is_first)
gpath->inners[i].nloops = 1;
else
numbatches *= gpath->inners[i].nloops;
/* force a plausible relation size if no information.
* It expects 15% of margin to avoid unnecessary hash-
* table split
*/
ntuples = (Max(1.15 * scan_path->rows, 1000.0) /
(double) gpath->inners[i].nloops);
/* estimate length of each hash entry */
entry_size = (offsetof(kern_hashentry, htup) +
MAXALIGN(offsetof(HeapTupleHeaderData,
t_bits[BITMAPLEN(ncols)])) +
MAXALIGN(scan_rel->width));
/* estimate length of this chunk */
chunk_size = (LONGALIGN(offsetof(kern_hashtable,
colmeta[ncols])) +
LONGALIGN(sizeof(cl_uint) * (Size)ntuples) +
LONGALIGN(entry_size * (Size)ntuples));
chunk_size = STROMALIGN(chunk_size);
if (largest_size < chunk_size)
{
largest_size = chunk_size;
i_largest = i;
}
gpath->inners[i].chunk_size = chunk_size;
gpath->inners[i].ntuples = (cl_uint) ntuples;
/* expand estimated hashtable-size */
hashtable_size += chunk_size;
}
/* also compute threshold_ratio */
threshold_size = 0;
for (i = nrels - 1; i >= 0; i--)
{
threshold_size += gpath->inners[i].chunk_size;
gpath->inners[i].threshold_ratio
= (double) threshold_size / (double) hashtable_size;
}
Assert(i_largest >= 0 && i_largest < nrels);
is_first = false;
/*
* NOTE: In case when extreme number of rows are expected,
* it does not make sense to split hash-tables because
* increasion of numbatches also increases the total cost
* by iteration of outer scan. In this case, the best
* strategy is to give up this path, instead of incredible
* number of numbatches!
*/
if (!add_path_precheck(joinrel,
workspace->startup_cost,
workspace->startup_cost +
workspace->run_cost * numbatches,
NULL, required_outer))
return false;
} while (hashtable_size > pgstrom_shmem_maxalloc());
/*
* Update estimated hashtable_size, but ensure hashtable_size
* shall be allocated at least
*/
gpath->hashtable_size = Max(hashtable_size,
pgstrom_chunk_size << 20);
/*
* Update JoinCostWorkspace according to numbatches
*/
workspace->run_cost *= numbatches;
workspace->total_cost = workspace->startup_cost + workspace->run_cost;
return true; /* ok */
}
/*
* cost_gpuhashjoin
*
* cost estimation for GpuHashJoin
*/
static bool
cost_gpuhashjoin(PlannerInfo *root,
GpuHashJoinPath *gpath,
Relids required_outer,
JoinCostWorkspace *workspace)
{
Path *outer_path = gpath->outerpath;
Cost startup_cost;
Cost run_cost;
Cost row_cost;
double num_rows;
int num_hash_clauses = 0;
int i;
/* cost of source data */
startup_cost = outer_path->startup_cost;
run_cost = outer_path->total_cost - outer_path->startup_cost;
for (i=0; i < gpath->num_rels; i++)
startup_cost += gpath->inners[i].scan_path->total_cost;
/*
* Cost of computing hash function: it is done by CPU right now,
* so we follow the logic in initial_cost_hashjoin().
*/
for (i=0; i < gpath->num_rels; i++)
{
num_hash_clauses += list_length(gpath->inners[i].hash_clause);
num_rows = gpath->inners[i].scan_path->rows;
startup_cost += (cpu_operator_cost *
list_length(gpath->inners[i].hash_clause) +
cpu_tuple_cost) * num_rows;
}
/* in addition, it takes cost to set up OpenCL device/program */
startup_cost += pgstrom_gpu_setup_cost;
/* on the other hands, its cost to run outer scan for joinning
* is much less than usual GPU hash join.
*/
num_rows = gpath->outerpath->rows;
row_cost = pgstrom_gpu_operator_cost * num_hash_clauses;
run_cost += row_cost * num_rows;
/* setup join-cost-workspace */
workspace->startup_cost = startup_cost;
workspace->run_cost = run_cost;
workspace->total_cost = startup_cost + run_cost;
workspace->numbatches = 1;
/*
* Estimation of hash table size and number of outer loops
* according to the split of hash tables.
* In case of estimated plan cost is too large to win the
* existing paths, it breaks to find out this path.
*/
if (!estimate_hashtable_size(root, gpath, required_outer, workspace))
return false;
return true;
}
/*
* approx_tuple_count - copied from costsize.c but arguments are adjusted
* according to GpuHashJoinPath.
*/
static double
approx_tuple_count(PlannerInfo *root, GpuHashJoinPath *gpath)
{
Path *outer_path = gpath->outerpath;
Selectivity selec = 1.0;
double tuples = outer_path->rows;
int i;
for (i=0; i < gpath->num_rels; i++)
{
Path *inner_path = gpath->inners[i].scan_path;
List *hash_clause = gpath->inners[i].hash_clause;
List *qual_clause = gpath->inners[i].qual_clause;
double inner_tuples = inner_path->rows;
SpecialJoinInfo sjinfo;
ListCell *cell;
/* make up a SpecialJoinInfo for JOIN_INNER semantics. */
sjinfo.type = T_SpecialJoinInfo;
sjinfo.min_lefthand = outer_path->parent->relids;
sjinfo.min_righthand = inner_path->parent->relids;
sjinfo.syn_lefthand = outer_path->parent->relids;
sjinfo.syn_righthand = inner_path->parent->relids;
sjinfo.jointype = JOIN_INNER;
/* we don't bother trying to make the remaining fields valid */
sjinfo.lhs_strict = false;
sjinfo.delay_upper_joins = false;
sjinfo.join_quals = NIL;
/* Get the approximate selectivity */
foreach (cell, hash_clause)
{
Node *qual = (Node *) lfirst(cell);
/* Note that clause_selectivity can cache its result */
selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
}
foreach (cell, qual_clause)
{
Node *qual = (Node *) lfirst(cell);
/* Note that clause_selectivity can cache its result */
selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
}
/* Apply it to the input relation sizes */
tuples *= selec * inner_tuples;
}
return clamp_row_est(tuples);
}
static void
final_cost_gpuhashjoin(PlannerInfo *root, GpuHashJoinPath *gpath,
JoinCostWorkspace *workspace)
{
Path *path = &gpath->cpath.path;
Cost startup_cost = workspace->startup_cost;
Cost run_cost = workspace->run_cost;
QualCost hash_cost;
QualCost qual_cost;
QualCost host_cost;
double hashjointuples;
int i;
/* Mark the path with correct row estimation */
if (path->param_info)
path->rows = path->param_info->ppi_rows;
else
path->rows = path->parent->rows;
/* Compute cost of the hash, qual and host clauses */
for (i=0; i < gpath->num_rels; i++)
{
List *hash_clause = gpath->inners[i].hash_clause;
List *qual_clause = gpath->inners[i].qual_clause;
List *host_clause = gpath->inners[i].host_clause;
double outer_path_rows = gpath->outerpath->rows;
double inner_path_rows = gpath->inners[i].scan_path->rows;
Relids inner_relids = gpath->inners[i].scan_path->parent->relids;
Selectivity innerbucketsize = 1.0;
ListCell *cell;
/*
* Determine bucketsize fraction for inner relation.
* We use the smallest bucketsize estimated for any individual
* hashclause; this is undoubtedly conservative.
*/
foreach (cell, hash_clause)
{
RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(cell);
Selectivity thisbucketsize;
double virtualbuckets;
Node *op_expr;
Assert(IsA(restrictinfo, RestrictInfo));
/* Right now, GpuHashJoin assumes all the inner record can
* be loaded into a single "multihash_tables" structure,
* so hash table is never divided and outer relation is
* rescanned.
* This assumption may change in the future implementation
*/
if (inner_path_rows < 1000.0)
virtualbuckets = 1000.0;
else
virtualbuckets = inner_path_rows;
/*
* First we have to figure out which side of the hashjoin clause
* is the inner side.
*
* Since we tend to visit the same clauses over and over when
* planning a large query, we cache the bucketsize estimate in the
* RestrictInfo node to avoid repeated lookups of statistics.
*/
if (bms_is_subset(restrictinfo->right_relids, inner_relids))
op_expr = get_rightop(restrictinfo->clause);
else
op_expr = get_leftop(restrictinfo->clause);
thisbucketsize = estimate_hash_bucketsize(root, op_expr,
virtualbuckets);
if (innerbucketsize > thisbucketsize)
innerbucketsize = thisbucketsize;
}
/*
* Pulls function cost of individual clauses
*/
cost_qual_eval(&hash_cost, hash_clause, root);
cost_qual_eval(&qual_cost, qual_clause, root);
cost_qual_eval(&host_cost, host_clause, root);
/*
* Because cost_qual_eval returns cost value that assumes CPU
* execution, we need to adjust its ratio according to the score
* of GPU execution to CPU.
*/
hash_cost.per_tuple *= (pgstrom_gpu_operator_cost / cpu_operator_cost);
qual_cost.per_tuple *= (pgstrom_gpu_operator_cost / cpu_operator_cost);
/*
* The number of comparison according to hash_clauses and qual_clauses
* are the number of outer tuples, but right now PG-Strom does not
* support to divide hash table
*/
startup_cost += hash_cost.startup + qual_cost.startup;
run_cost += ((hash_cost.per_tuple + qual_cost.per_tuple)
* outer_path_rows
* clamp_row_est(inner_path_rows * innerbucketsize) * 0.5);
}
/*
* Get approx # tuples passing the hashquals. We use
* approx_tuple_count here because we need an estimate done with
* JOIN_INNER semantics.
*/
hashjointuples = approx_tuple_count(root, gpath);
/*
* Also add cost for qualifiers to be run on host
*/
startup_cost += host_cost.startup;
run_cost += (cpu_tuple_cost + host_cost.per_tuple) * hashjointuples;
gpath->cpath.path.startup_cost = startup_cost;
gpath->cpath.path.total_cost = startup_cost + run_cost;
}
/*
* gpuhashjoin_add_path
*
* callback function invoked to check up GpuHashJoinPath.
*/
static void
gpuhashjoin_add_path(PlannerInfo *root,
RelOptInfo *joinrel,
JoinType jointype,
JoinCostWorkspace *core_workspace,
SpecialJoinInfo *sjinfo,
SemiAntiJoinFactors *semifactors,
Path *outer_path,
Path *inner_path,
List *restrict_clauses,
Relids required_outer,
List *hashclauses)
{
GpuHashJoinPath *gpath_new;
ParamPathInfo *ppinfo;
List *hash_clause = NIL;
List *qual_clause = NIL;
List *host_clause = NIL;
List *outer_clause;
ListCell *cell;
JoinCostWorkspace gpu_workspace;
/* calls secondary module if exists */
if (add_hashjoin_path_next)
add_hashjoin_path_next(root,
joinrel,
jointype,
core_workspace,
sjinfo,
semifactors,
outer_path,
inner_path,
restrict_clauses,
required_outer,
hashclauses);
/* nothing to do, if either PG-Strom or GpuHashJoin is not enabled */
if (!pgstrom_enabled() || !enable_gpuhashjoin)
return;
/*
* right now, only inner join is supported!
*/
if (jointype != JOIN_INNER)
return;
/*
* make a ParamPathInfo of this GpuHashJoin, according to the standard
* manner.
* XXX - needs to ensure whether it is actually harmless in case when
* multiple inner relations are planned to be cached.
*/
ppinfo = get_joinrel_parampathinfo(root,
joinrel,
outer_path,
inner_path,
sjinfo,
bms_copy(required_outer),
&restrict_clauses);
/* reasonable portion of hash-clauses can be runnable on GPU */
foreach (cell, restrict_clauses)
{
RestrictInfo *rinfo = lfirst(cell);
if (pgstrom_codegen_available_expression(rinfo->clause))
{
if (list_member_ptr(hashclauses, rinfo))
hash_clause = lappend(hash_clause, rinfo);
else
qual_clause = lappend(qual_clause, rinfo);
}
else
host_clause = lappend(host_clause, rinfo);
}
if (hash_clause == NIL)
return; /* no need to run it on GPU */
/*
* creation of gpuhashjoin path, if no pull-up
*/
outer_clause = NIL;
gpath_new = palloc0(offsetof(GpuHashJoinPath, inners[1]));
gpath_new->cpath.path.type = T_CustomPath;
gpath_new->cpath.path.pathtype = T_CustomPlan;
gpath_new->cpath.path.parent = joinrel;
gpath_new->cpath.path.param_info = ppinfo;
gpath_new->cpath.path.pathkeys = NIL;
/* other cost fields of Path shall be set later */
gpath_new->cpath.methods = &gpuhashjoin_path_methods;
gpath_new->num_rels = 1;
gpath_new->outerpath = gpuscan_try_replace_seqscan_path(root, outer_path,
&outer_clause);
gpath_new->inners[0].scan_path = inner_path;
gpath_new->inners[0].jointype = jointype;
gpath_new->inners[0].hash_clause = hash_clause;
gpath_new->inners[0].qual_clause = list_concat(qual_clause, outer_clause);
gpath_new->inners[0].host_clause = host_clause;
/* cost estimation and check availability */
if (cost_gpuhashjoin(root, gpath_new,
required_outer,
&gpu_workspace))
{
if (add_path_precheck(joinrel,
gpu_workspace.startup_cost,
gpu_workspace.total_cost,
NULL, required_outer))
{
final_cost_gpuhashjoin(root, gpath_new, &gpu_workspace);
add_path(joinrel, &gpath_new->cpath.path);
}
}
/*
* creation of gpuhashjoin path using sub-inner pull-up, if available
*/
if (path_is_mergeable_gpuhashjoin(outer_path))
{
GpuHashJoinPath *gpath_sub = (GpuHashJoinPath *) outer_path;
int num_rels = gpath_sub->num_rels;
outer_clause = NIL;
gpath_new = palloc0(offsetof(GpuHashJoinPath, inners[num_rels + 1]));
gpath_new->cpath.path.type = T_CustomPath;
gpath_new->cpath.path.pathtype = T_CustomPlan;
gpath_new->cpath.path.parent = joinrel;
gpath_new->cpath.path.param_info = ppinfo;
gpath_new->cpath.path.pathkeys = NIL;
/* other cost fields of Path shall be set later */
gpath_new->cpath.methods = &gpuhashjoin_path_methods;
gpath_new->num_rels = gpath_sub->num_rels + 1;
gpath_new->outerpath =
gpuscan_try_replace_seqscan_path(root, gpath_sub->outerpath,
&outer_clause);
memcpy(gpath_new->inners,
gpath_sub->inners,
offsetof(GpuHashJoinPath, inners[num_rels]) -
offsetof(GpuHashJoinPath, inners[0]));
gpath_new->inners[num_rels].scan_path = inner_path;
gpath_new->inners[num_rels].jointype = jointype;
gpath_new->inners[num_rels].hash_clause = hash_clause;
gpath_new->inners[num_rels].qual_clause = list_concat(qual_clause,
outer_clause);
gpath_new->inners[num_rels].host_clause = host_clause;
/* cost estimation and check availability */
if (cost_gpuhashjoin(root, gpath_new,
required_outer,
&gpu_workspace))
{
if (add_path_precheck(joinrel,
gpu_workspace.startup_cost,
gpu_workspace.total_cost,
NULL, required_outer))
{
final_cost_gpuhashjoin(root, gpath_new, &gpu_workspace);
add_path(joinrel, &gpath_new->cpath.path);
}
}
}
}
/*
* XXX - a workaround. once CustomPlan became based on CustomScan,
* we can access Scan->scanrelid...
*/
typedef struct {
CustomPlan cplan;
Index scanrelid;
} GpuScanPlanDummy;
static bool
gpuhashjoin_use_bulkload(GpuHashJoin *ghjoin)
{
Plan *outer_plan = outerPlan(ghjoin);
Bitmapset *outer_attrefs = NULL;
Index outer_scanrelid;
ListCell *lc;
/*
* Only GpuScan support bulk-loading right now
*/
if (!pgstrom_plan_is_gpuscan(outer_plan))
return false;
outer_scanrelid = ((GpuScanPlanDummy *) outer_plan)->scanrelid;
pull_varattnos((Node *)ghjoin->cplan.plan.targetlist,
outer_scanrelid,
&outer_attrefs);
pull_varattnos((Node *)ghjoin->hash_clauses,
outer_scanrelid,
&outer_attrefs);
pull_varattnos((Node *)ghjoin->qual_clauses,
outer_scanrelid,
&outer_attrefs);
pull_varattnos((Node *)ghjoin->host_clauses,
outer_scanrelid,
&outer_attrefs);
foreach (lc, outer_plan->targetlist)
{
TargetEntry *tle = lfirst(lc);
int x = tle->resno - FirstLowInvalidHeapAttributeNumber;
if (!bms_is_member(x, outer_attrefs))
continue;
if (!IsA(tle->expr, Var) ||
((Var *) tle->expr)->varattno != tle->resno)
return false;
}
return true;
}
static CustomPlan *
gpuhashjoin_create_plan(PlannerInfo *root, CustomPath *best_path)
{
GpuHashJoinPath *gpath = (GpuHashJoinPath *)best_path;
GpuHashJoin *ghjoin;
Plan *prev_plan = NULL;
List *join_types = NIL;
List *hash_clauses = NIL;
List *qual_clauses = NIL;
List *host_clauses = NIL;
int i;
ghjoin = palloc0(sizeof(GpuHashJoin));
NodeSetTag(ghjoin, T_CustomPlan);
ghjoin->cplan.methods = &gpuhashjoin_plan_methods;
ghjoin->cplan.plan.targetlist
= build_path_tlist(root, &gpath->cpath.path);
ghjoin->cplan.plan.qual = NIL; /* to be set later */
outerPlan(ghjoin) = create_plan_recurse(root, gpath->outerpath);
for (i=0; i < gpath->num_rels; i++)
{
MultiHash *mhash;
List *hash_clause = gpath->inners[i].hash_clause;
List *qual_clause = gpath->inners[i].qual_clause;
List *host_clause = gpath->inners[i].host_clause;
Plan *scan_plan
= create_plan_recurse(root, gpath->inners[i].scan_path);
if (gpath->cpath.path.param_info)
{
hash_clause = (List *)
replace_nestloop_params(root, (Node *) hash_clause);
qual_clause = (List *)
replace_nestloop_params(root, (Node *) qual_clause);
host_clause = (List *)
replace_nestloop_params(root, (Node *) host_clause);
}
/*
* Sort clauses into best execution order, even though it's
* uncertain whether it makes sense in GPU execution...
*/
hash_clause = order_qual_clauses(root, hash_clause);
qual_clause = order_qual_clauses(root, qual_clause);
host_clause = order_qual_clauses(root, host_clause);
/* Get plan expression form */
hash_clause = extract_actual_clauses(hash_clause, false);
qual_clause = extract_actual_clauses(qual_clause, false);
host_clause = extract_actual_clauses(host_clause, false);
/* saved on the GpuHashJoin node */
join_types = lappend_int(join_types, (int)gpath->inners[i].jointype);
hash_clauses = lappend(hash_clauses, hash_clause);
qual_clauses = lappend(qual_clauses, qual_clause);
host_clauses = lappend(host_clauses, host_clause);
/* Make a MultiHash node */
mhash = palloc0(sizeof(MultiHash));
NodeSetTag(mhash, T_CustomPlan);
mhash->cplan.methods = &multihash_plan_methods;
mhash->cplan.plan.startup_cost = scan_plan->total_cost;
mhash->cplan.plan.total_cost = scan_plan->total_cost;
mhash->cplan.plan.plan_rows = scan_plan->plan_rows;
mhash->cplan.plan.plan_width = scan_plan->plan_width;
mhash->cplan.plan.targetlist = scan_plan->targetlist;
mhash->cplan.plan.qual = NIL;
mhash->depth = i + 1;
mhash->nslots = gpath->inners[i].ntuples;
mhash->nloops = gpath->inners[i].nloops;
mhash->threshold_ratio = gpath->inners[i].threshold_ratio;
mhash->hashtable_size = gpath->hashtable_size;
/* chain it under the GpuHashJoin */
outerPlan(mhash) = scan_plan;
if (prev_plan)
innerPlan(prev_plan) = (Plan *) mhash;
else
innerPlan(ghjoin) = (Plan *) mhash;
prev_plan = (Plan *) mhash;
}
ghjoin->num_rels = gpath->num_rels;
ghjoin->join_types = join_types;
ghjoin->hash_clauses = hash_clauses;
ghjoin->qual_clauses = qual_clauses;
ghjoin->host_clauses = host_clauses;
ghjoin->outer_bulkload = gpuhashjoin_use_bulkload(ghjoin);
return &ghjoin->cplan;
}
static void
gpuhashjoin_textout_path(StringInfo str, Node *node)
{
GpuHashJoinPath *gpath = (GpuHashJoinPath *) node;
char *temp;
int i;
/* outerpath */
temp = nodeToString(gpath->outerpath);
appendStringInfo(str, " :outerpath %s", temp);
/* num_rels */
appendStringInfo(str, " :num_rels %d", gpath->num_rels);
/* inners */
appendStringInfo(str, " :num_rels (");
for (i=0; i < gpath->num_rels; i++)
{
appendStringInfo(str, "{");
/* path */