summaryrefslogtreecommitdiff
path: root/src/backend/executor/nodeHash.c
blob: 5578c7218399415a4f9a7af32322c860b5aeaa9c (plain)
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
/*-------------------------------------------------------------------------
 *
 * nodeHash.c
 *	  Routines to hash relations for hashjoin
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 *  $Id: nodeHash.c,v 1.31 1999/02/13 23:15:22 momjian Exp $
 *
 *-------------------------------------------------------------------------
 */
/*
 * INTERFACE ROUTINES
 *		ExecHash		- generate an in-memory hash table of the relation
 *		ExecInitHash	- initialize node and subnodes..
 *		ExecEndHash		- shutdown node and subnodes
 *
 */

#include <sys/types.h>
#include <stdio.h>		
#include <math.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <unistd.h>

#include "postgres.h"
#include "miscadmin.h"
#include "executor/execdebug.h"
#include "executor/executor.h"
#include "executor/nodeHash.h"
#include "executor/nodeHashjoin.h"
#include "storage/ipc.h"
#include "utils/hsearch.h"

extern int	NBuffers;
static int	HashTBSize;

static void mk_hj_temp(char *tempname);
static int	hashFunc(char *key, int len);
static int	ExecHashPartition(Hash *node);
static RelativeAddr hashTableAlloc(int size, HashJoinTable hashtable);
static void ExecHashOverflowInsert(HashJoinTable hashtable,
					   HashBucket bucket,
					   HeapTuple heapTuple);

/* ----------------------------------------------------------------
 *		ExecHash
 *
 *		build hash table for hashjoin, all do partitioning if more
 *		than one batches are required.
 * ----------------------------------------------------------------
 */
TupleTableSlot *
ExecHash(Hash *node)
{
	EState	   *estate;
	HashState  *hashstate;
	Plan	   *outerNode;
	Var		   *hashkey;
	HashJoinTable hashtable;
	TupleTableSlot *slot;
	ExprContext *econtext;

	int			nbatch;
	File	   *batches = NULL;
	RelativeAddr *batchPos;
	int		   *batchSizes;
	int			i;
	RelativeAddr *innerbatchNames;

	/* ----------------
	 *	get state info from node
	 * ----------------
	 */

	hashstate = node->hashstate;
	estate = node->plan.state;
	outerNode = outerPlan(node);

	hashtable = node->hashtable;
	if (hashtable == NULL)
		elog(ERROR, "ExecHash: hash table is NULL.");

	nbatch = hashtable->nbatch;

	if (nbatch > 0)
	{							/* if needs hash partition */
		innerbatchNames = (RelativeAddr *) ABSADDR(hashtable->innerbatchNames);

		/* --------------
		 *	allocate space for the file descriptors of batch files
		 *	then open the batch files in the current processes.
		 * --------------
		 */
		batches = (File *) palloc(nbatch * sizeof(File));
		for (i = 0; i < nbatch; i++)
		{
#ifndef __CYGWIN32__
			batches[i] = FileNameOpenFile(ABSADDR(innerbatchNames[i]),
										  O_CREAT | O_RDWR, 0600);
#else
			batches[i] = FileNameOpenFile(ABSADDR(innerbatchNames[i]),
										  O_CREAT | O_RDWR | O_BINARY, 0600);
#endif
		}
		hashstate->hashBatches = batches;
		batchPos = (RelativeAddr *) ABSADDR(hashtable->innerbatchPos);
		batchSizes = (int *) ABSADDR(hashtable->innerbatchSizes);
	}

	/* ----------------
	 *	set expression context
	 * ----------------
	 */
	hashkey = node->hashkey;
	econtext = hashstate->cstate.cs_ExprContext;

	/* ----------------
	 *	get tuple and insert into the hash table
	 * ----------------
	 */
	for (;;)
	{
		slot = ExecProcNode(outerNode, (Plan *) node);
		if (TupIsNull(slot))
			break;

		econtext->ecxt_innertuple = slot;
		ExecHashTableInsert(hashtable, econtext, hashkey,
							hashstate->hashBatches);

		ExecClearTuple(slot);
	}

	/*
	 * end of build phase, flush all the last pages of the batches.
	 */
	for (i = 0; i < nbatch; i++)
	{
		if (FileSeek(batches[i], 0L, SEEK_END) < 0)
			perror("FileSeek");
		if (FileWrite(batches[i], ABSADDR(hashtable->batch) + i * BLCKSZ, BLCKSZ) < 0)
			perror("FileWrite");
		NDirectFileWrite++;
	}

	/* ---------------------
	 *	Return the slot so that we have the tuple descriptor
	 *	when we need to save/restore them.	-Jeff 11 July 1991
	 * ---------------------
	 */
	return slot;
}

/* ----------------------------------------------------------------
 *		ExecInitHash
 *
 *		Init routine for Hash node
 * ----------------------------------------------------------------
 */
bool
ExecInitHash(Hash *node, EState *estate, Plan *parent)
{
	HashState  *hashstate;
	Plan	   *outerPlan;

	SO1_printf("ExecInitHash: %s\n",
			   "initializing hash node");

	/* ----------------
	 *	assign the node's execution state
	 * ----------------
	 */
	node->plan.state = estate;

	/* ----------------
	 * create state structure
	 * ----------------
	 */
	hashstate = makeNode(HashState);
	node->hashstate = hashstate;
	hashstate->hashBatches = NULL;

	/* ----------------
	 *	Miscellanious initialization
	 *
	 *		 +	assign node's base_id
	 *		 +	assign debugging hooks and
	 *		 +	create expression context for node
	 * ----------------
	 */
	ExecAssignNodeBaseInfo(estate, &hashstate->cstate, parent);
	ExecAssignExprContext(estate, &hashstate->cstate);

#define HASH_NSLOTS 1
	/* ----------------
	 * initialize our result slot
	 * ----------------
	 */
	ExecInitResultTupleSlot(estate, &hashstate->cstate);

	/* ----------------
	 * initializes child nodes
	 * ----------------
	 */
	outerPlan = outerPlan(node);
	ExecInitNode(outerPlan, estate, (Plan *) node);

	/* ----------------
	 *	initialize tuple type. no need to initialize projection
	 *	info because this node doesn't do projections
	 * ----------------
	 */
	ExecAssignResultTypeFromOuterPlan((Plan *) node, &hashstate->cstate);
	hashstate->cstate.cs_ProjInfo = NULL;

	return TRUE;
}

int
ExecCountSlotsHash(Hash *node)
{
	return ExecCountSlotsNode(outerPlan(node)) +
	ExecCountSlotsNode(innerPlan(node)) +
	HASH_NSLOTS;
}

/* ---------------------------------------------------------------
 *		ExecEndHash
 *
 *		clean up routine for Hash node
 * ----------------------------------------------------------------
 */
void
ExecEndHash(Hash *node)
{
	HashState  *hashstate;
	Plan	   *outerPlan;
	File	   *batches;

	/* ----------------
	 *	get info from the hash state
	 * ----------------
	 */
	hashstate = node->hashstate;
	batches = hashstate->hashBatches;
	if (batches != NULL)
		pfree(batches);

	/* ----------------
	 *	free projection info.  no need to free result type info
	 *	because that came from the outer plan...
	 * ----------------
	 */
	ExecFreeProjectionInfo(&hashstate->cstate);

	/* ----------------
	 *	shut down the subplan
	 * ----------------
	 */
	outerPlan = outerPlan(node);
	ExecEndNode(outerPlan, (Plan *) node);
}

static RelativeAddr
hashTableAlloc(int size, HashJoinTable hashtable)
{
	RelativeAddr p;

	p = hashtable->top;
	hashtable->top += size;
	return p;
}

/* ----------------------------------------------------------------
 *		ExecHashTableCreate
 *
 *		create a hashtable in shared memory for hashjoin.
 * ----------------------------------------------------------------
 */
#define NTUP_PER_BUCKET			10
#define FUDGE_FAC				1.5

HashJoinTable
ExecHashTableCreate(Hash *node)
{
	Plan	   *outerNode;
	int			nbatch;
	int			ntuples;
	int			tupsize;
	IpcMemoryId shmid;
	HashJoinTable hashtable;
	HashBucket	bucket;
	int			nbuckets;
	int			totalbuckets;
	int			bucketsize;
	int			i;
	RelativeAddr *outerbatchNames;
	RelativeAddr *outerbatchPos;
	RelativeAddr *innerbatchNames;
	RelativeAddr *innerbatchPos;
	int		   *innerbatchSizes;
	RelativeAddr tempname;

	nbatch = -1;
	HashTBSize = NBuffers / 2;
	while (nbatch < 0)
	{

		/*
		 * determine number of batches for the hashjoin
		 */
		HashTBSize *= 2;
		nbatch = ExecHashPartition(node);
	}
	/* ----------------
	 *	get information about the size of the relation
	 * ----------------
	 */
	outerNode = outerPlan(node);
	ntuples = outerNode->plan_size;
	if (ntuples <= 0)
		ntuples = 1000;			/* XXX just a hack */
	tupsize = outerNode->plan_width + sizeof(HeapTupleData);

	/*
	 * totalbuckets is the total number of hash buckets needed for the
	 * entire relation
	 */
	totalbuckets = ceil((double) ntuples / NTUP_PER_BUCKET);
	bucketsize = LONGALIGN(NTUP_PER_BUCKET * tupsize + sizeof(*bucket));

	/*
	 * nbuckets is the number of hash buckets for the first pass of hybrid
	 * hashjoin
	 */
	nbuckets = (HashTBSize - nbatch) * BLCKSZ / (bucketsize * FUDGE_FAC);
	if (totalbuckets < nbuckets)
		totalbuckets = nbuckets;
	if (nbatch == 0)
		nbuckets = totalbuckets;
#ifdef HJDEBUG
	printf("nbatch = %d, totalbuckets = %d, nbuckets = %d\n", 
			nbatch, totalbuckets, nbuckets);
#endif

	/* ----------------
	 *	in non-parallel machines, we don't need to put the hash table
	 *	in the shared memory.  We just palloc it.
	 * ----------------
	 */
	hashtable = (HashJoinTable) palloc((HashTBSize + 1) * BLCKSZ);
	shmid = 0;

	if (hashtable == NULL)
		elog(ERROR, "not enough memory for hashjoin.");
	/* ----------------
	 *	initialize the hash table header
	 * ----------------
	 */
	hashtable->nbuckets = nbuckets;
	hashtable->totalbuckets = totalbuckets;
	hashtable->bucketsize = bucketsize;
	hashtable->shmid = shmid;
	hashtable->top = sizeof(HashTableData);
	hashtable->bottom = HashTBSize * BLCKSZ;

	/*
	 * hashtable->readbuf has to be long aligned!!!
	 */
	hashtable->readbuf = hashtable->bottom;
	hashtable->nbatch = nbatch;
	hashtable->curbatch = 0;
	hashtable->pcount = hashtable->nprocess = 0;
	if (nbatch > 0)
	{
		/* ---------------
		 *	allocate and initialize the outer batches
		 * ---------------
		 */
		outerbatchNames = (RelativeAddr *) ABSADDR(
			   hashTableAlloc(nbatch * sizeof(RelativeAddr), hashtable));
		outerbatchPos = (RelativeAddr *) ABSADDR(
			   hashTableAlloc(nbatch * sizeof(RelativeAddr), hashtable));
		for (i = 0; i < nbatch; i++)
		{
			tempname = hashTableAlloc(12, hashtable);
			mk_hj_temp(ABSADDR(tempname));
			outerbatchNames[i] = tempname;
			outerbatchPos[i] = -1;
		}
		hashtable->outerbatchNames = RELADDR(outerbatchNames);
		hashtable->outerbatchPos = RELADDR(outerbatchPos);
		/* ---------------
		 *	allocate and initialize the inner batches
		 * ---------------
		 */
		innerbatchNames = (RelativeAddr *) ABSADDR(
			   hashTableAlloc(nbatch * sizeof(RelativeAddr), hashtable));
		innerbatchPos = (RelativeAddr *) ABSADDR(
			   hashTableAlloc(nbatch * sizeof(RelativeAddr), hashtable));
		innerbatchSizes = (int *) ABSADDR(
						hashTableAlloc(nbatch * sizeof(int), hashtable));
		for (i = 0; i < nbatch; i++)
		{
			tempname = hashTableAlloc(12, hashtable);
			mk_hj_temp(ABSADDR(tempname));
			innerbatchNames[i] = tempname;
			innerbatchPos[i] = -1;
			innerbatchSizes[i] = 0;
		}
		hashtable->innerbatchNames = RELADDR(innerbatchNames);
		hashtable->innerbatchPos = RELADDR(innerbatchPos);
		hashtable->innerbatchSizes = RELADDR(innerbatchSizes);
	}
	else
	{
		hashtable->outerbatchNames = (RelativeAddr) NULL;
		hashtable->outerbatchPos = (RelativeAddr) NULL;
		hashtable->innerbatchNames = (RelativeAddr) NULL;
		hashtable->innerbatchPos = (RelativeAddr) NULL;
		hashtable->innerbatchSizes = (RelativeAddr) NULL;
	}

	hashtable->batch = (RelativeAddr) LONGALIGN(hashtable->top +
												bucketsize * nbuckets);
	hashtable->overflownext = hashtable->batch + nbatch * BLCKSZ;
	/* ----------------
	 *	initialize each hash bucket
	 * ----------------
	 */
	bucket = (HashBucket) ABSADDR(hashtable->top);
	for (i = 0; i < nbuckets; i++)
	{
		bucket->top = RELADDR((char *) bucket + sizeof(*bucket));
		bucket->bottom = bucket->top;
		bucket->firstotuple = bucket->lastotuple = -1;
		bucket = (HashBucket) LONGALIGN(((char *) bucket + bucketsize));
	}
	return hashtable;
}

/* ----------------------------------------------------------------
 *		ExecHashTableInsert
 *
 *		insert a tuple into the hash table depending on the hash value
 *		it may just go to a tmp file for other batches
 * ----------------------------------------------------------------
 */
void
ExecHashTableInsert(HashJoinTable hashtable,
					ExprContext *econtext,
					Var *hashkey,
					File *batches)
{
	TupleTableSlot *slot;
	HeapTuple	heapTuple;
	HashBucket	bucket;
	int			bucketno;
	int			nbatch;
	int			batchno;
	char	   *buffer;
	RelativeAddr *batchPos;
	int		   *batchSizes;
	char	   *pos;

	nbatch = hashtable->nbatch;
	batchPos = (RelativeAddr *) ABSADDR(hashtable->innerbatchPos);
	batchSizes = (int *) ABSADDR(hashtable->innerbatchSizes);

	slot = econtext->ecxt_innertuple;
	heapTuple = slot->val;

#ifdef HJDEBUG
	printf("Inserting ");
#endif

	bucketno = ExecHashGetBucket(hashtable, econtext, hashkey);

	/* ----------------
	 *	decide whether to put the tuple in the hash table or a tmp file
	 * ----------------
	 */
	if (bucketno < hashtable->nbuckets)
	{
		/* ---------------
		 *	put the tuple in hash table
		 * ---------------
		 */
		bucket = (HashBucket)
			(ABSADDR(hashtable->top) + bucketno * hashtable->bucketsize);
		if ((char *) LONGALIGN(ABSADDR(bucket->bottom)) - (char *) bucket 
				+ heapTuple->t_len + HEAPTUPLESIZE > hashtable->bucketsize)
			ExecHashOverflowInsert(hashtable, bucket, heapTuple);
		else
		{
			memmove((char *) LONGALIGN(ABSADDR(bucket->bottom)),
					heapTuple,
					HEAPTUPLESIZE);
			memmove((char *) LONGALIGN(ABSADDR(bucket->bottom)) + HEAPTUPLESIZE,
					heapTuple->t_data,
					heapTuple->t_len);
			bucket->bottom = ((RelativeAddr) LONGALIGN(bucket->bottom) + 
					heapTuple->t_len + HEAPTUPLESIZE);
		}
	}
	else
	{
		/* -----------------
		 * put the tuple into a tmp file for other batches
		 * -----------------
		 */
		batchno = (float) (bucketno - hashtable->nbuckets) /
			(float) (hashtable->totalbuckets - hashtable->nbuckets)
			* nbatch;
		buffer = ABSADDR(hashtable->batch) + batchno * BLCKSZ;
		batchSizes[batchno]++;
		pos = (char *)
			ExecHashJoinSaveTuple(heapTuple,
								  buffer,
								  batches[batchno],
								  (char *) ABSADDR(batchPos[batchno]));
		batchPos[batchno] = RELADDR(pos);
	}
}

/* ----------------------------------------------------------------
 *		ExecHashTableDestroy
 *
 *		destroy a hash table
 * ----------------------------------------------------------------
 */
void
ExecHashTableDestroy(HashJoinTable hashtable)
{
	pfree(hashtable);
}

/* ----------------------------------------------------------------
 *		ExecHashGetBucket
 *
 *		Get the hash value for a tuple
 * ----------------------------------------------------------------
 */
int
ExecHashGetBucket(HashJoinTable hashtable,
				  ExprContext *econtext,
				  Var *hashkey)
{
	int			bucketno;
	Datum		keyval;
	bool		isNull;


	/* ----------------
	 *	Get the join attribute value of the tuple
	 * ----------------
	 * ...It's quick hack - use ExecEvalExpr instead of ExecEvalVar:
	 * hashkey may be T_ArrayRef, not just T_Var.		- vadim 04/22/97
	 */
	keyval = ExecEvalExpr((Node *) hashkey, econtext, &isNull, NULL);

	/*
	 * keyval could be null, so we better point it to something valid
	 * before trying to run hashFunc on it. --djm 8/17/96
	 */
	if (isNull)
	{
		execConstByVal = 0;
		execConstLen = 0;
		keyval = (Datum) "";
	}

	/* ------------------
	 *	compute the hash function
	 * ------------------
	 */
	if (execConstByVal)
		bucketno = hashFunc((char *) &keyval, execConstLen) % hashtable->totalbuckets;
	else
		bucketno = hashFunc((char *) keyval, execConstLen) % hashtable->totalbuckets;
#ifdef HJDEBUG
	if (bucketno >= hashtable->nbuckets)
		printf("hash(%d) = %d SAVED\n", keyval, bucketno);
	else
		printf("hash(%d) = %d\n", keyval, bucketno);
#endif

	return bucketno;
}

/* ----------------------------------------------------------------
 *		ExecHashOverflowInsert
 *
 *		insert into the overflow area of a hash bucket
 * ----------------------------------------------------------------
 */
static void
ExecHashOverflowInsert(HashJoinTable hashtable,
					   HashBucket bucket,
					   HeapTuple heapTuple)
{
	OverflowTuple otuple;
	RelativeAddr newend;
	OverflowTuple firstotuple;
	OverflowTuple lastotuple;

	firstotuple = (OverflowTuple) ABSADDR(bucket->firstotuple);
	lastotuple = (OverflowTuple) ABSADDR(bucket->lastotuple);
	/* ----------------
	 *	see if we run out of overflow space
	 * ----------------
	 */
	newend = (RelativeAddr) LONGALIGN(hashtable->overflownext + sizeof(*otuple)
									  + heapTuple->t_len + HEAPTUPLESIZE);
	if (newend > hashtable->bottom)
	{
		/* ------------------
		 * XXX the temporary hack above doesn't work because things
		 * above us don't know that we've moved the hash table!
		 *	- Chris Dunlop, <chris@onthe.net.au>
		 * ------------------
		 */
		elog(ERROR, 
				"hash table out of memory. Use -B parameter to increase buffers.");
	}

	/* ----------------
	 *	establish the overflow chain
	 * ----------------
	 */
	otuple = (OverflowTuple) ABSADDR(hashtable->overflownext);
	hashtable->overflownext = newend;
	if (firstotuple == NULL)
		bucket->firstotuple = bucket->lastotuple = RELADDR(otuple);
	else
	{
		lastotuple->next = RELADDR(otuple);
		bucket->lastotuple = RELADDR(otuple);
	}

	/* ----------------
	 *	copy the tuple into the overflow area
	 * ----------------
	 */
	otuple->next = -1;
	otuple->tuple = RELADDR(LONGALIGN(((char *) otuple + sizeof(*otuple))));
	memmove(ABSADDR(otuple->tuple),
			heapTuple,
			HEAPTUPLESIZE);
	memmove(ABSADDR(otuple->tuple) + HEAPTUPLESIZE,
			heapTuple->t_data,
			heapTuple->t_len);
}

/* ----------------------------------------------------------------
 *		ExecScanHashBucket
 *
 *		scan a hash bucket of matches
 * ----------------------------------------------------------------
 */
HeapTuple
ExecScanHashBucket(HashJoinState *hjstate,
				   HashBucket bucket,
				   HeapTuple curtuple,
				   List *hjclauses,
				   ExprContext *econtext)
{
	HeapTuple	heapTuple;
	bool		qualResult;
	OverflowTuple otuple = NULL;
	OverflowTuple curotuple;
	TupleTableSlot *inntuple;
	OverflowTuple firstotuple;
	OverflowTuple lastotuple;
	HashJoinTable hashtable;

	hashtable = hjstate->hj_HashTable;
	firstotuple = (OverflowTuple) ABSADDR(bucket->firstotuple);
	lastotuple = (OverflowTuple) ABSADDR(bucket->lastotuple);

	/* ----------------
	 *	search the hash bucket
	 * ----------------
	 */
	if (curtuple == NULL || curtuple < (HeapTuple) ABSADDR(bucket->bottom))
	{
		if (curtuple == NULL)
			heapTuple = (HeapTuple)
				LONGALIGN(ABSADDR(bucket->top));
		else
			heapTuple = (HeapTuple)
				LONGALIGN(((char *) curtuple + curtuple->t_len + HEAPTUPLESIZE));

		while (heapTuple < (HeapTuple) ABSADDR(bucket->bottom))
		{

			heapTuple->t_data = (HeapTupleHeader) 
								((char *) heapTuple + HEAPTUPLESIZE);

			inntuple = ExecStoreTuple(heapTuple,		/* tuple to store */
									  hjstate->hj_HashTupleSlot,		/* slot */
									  InvalidBuffer,	/* tuple has no buffer */
									  false);	/* do not pfree this tuple */

			econtext->ecxt_innertuple = inntuple;
			qualResult = ExecQual((List *) hjclauses, econtext);

			if (qualResult)
				return heapTuple;

			heapTuple = (HeapTuple)
				LONGALIGN(((char *) heapTuple + heapTuple->t_len + HEAPTUPLESIZE));
		}

		if (firstotuple == NULL)
			return NULL;
		otuple = firstotuple;
	}

	/* ----------------
	 *	search the overflow area of the hash bucket
	 * ----------------
	 */
	if (otuple == NULL)
	{
		curotuple = hjstate->hj_CurOTuple;
		otuple = (OverflowTuple) ABSADDR(curotuple->next);
	}

	while (otuple != NULL)
	{
		heapTuple = (HeapTuple) ABSADDR(otuple->tuple);
		heapTuple->t_data = (HeapTupleHeader) 
							((char *) heapTuple + HEAPTUPLESIZE);

		inntuple = ExecStoreTuple(heapTuple,	/* tuple to store */
								  hjstate->hj_HashTupleSlot,	/* slot */
								  InvalidBuffer,		/* SP?? this tuple has
														 * no buffer */
								  false);		/* do not pfree this tuple */

		econtext->ecxt_innertuple = inntuple;
		qualResult = ExecQual((List *) hjclauses, econtext);

		if (qualResult)
		{
			hjstate->hj_CurOTuple = otuple;
			return heapTuple;
		}

		otuple = (OverflowTuple) ABSADDR(otuple->next);
	}

	/* ----------------
	 *	no match
	 * ----------------
	 */
	return NULL;
}

/* ----------------------------------------------------------------
 *		hashFunc
 *
 *		the hash function, copied from Margo
 * ----------------------------------------------------------------
 */
static int
hashFunc(char *key, int len)
{
	unsigned int h;
	int			l;
	unsigned char *k;

	/*
	 * If this is a variable length type, then 'k' points to a "struct
	 * varlena" and len == -1. NOTE: VARSIZE returns the "real" data
	 * length plus the sizeof the "vl_len" attribute of varlena (the
	 * length information). 'k' points to the beginning of the varlena
	 * struct, so we have to use "VARDATA" to find the beginning of the
	 * "real" data.
	 */
	if (len == -1)
	{
		l = VARSIZE(key) - VARHDRSZ;
		k = (unsigned char *) VARDATA(key);
	}
	else
	{
		l = len;
		k = (unsigned char *) key;
	}

	h = 0;

	/*
	 * Convert string to integer
	 */
	while (l--)
		h = h * PRIME1 ^ (*k++);
	h %= PRIME2;

	return h;
}

/* ----------------------------------------------------------------
 *		ExecHashPartition
 *
 *		determine the number of batches needed for a hashjoin
 * ----------------------------------------------------------------
 */
static int
ExecHashPartition(Hash *node)
{
	Plan	   *outerNode;
	int			b;
	int			pages;
	int			ntuples;
	int			tupsize;

	/*
	 * get size information for plan node
	 */
	outerNode = outerPlan(node);
	ntuples = outerNode->plan_size;
	if (ntuples == 0)
		ntuples = 1000;
	tupsize = outerNode->plan_width + sizeof(HeapTupleData);
	pages = ceil((double) ntuples * tupsize * FUDGE_FAC / BLCKSZ);

	/*
	 * if amount of buffer space below hashjoin threshold, return negative
	 */
	if (ceil(sqrt((double) pages)) > HashTBSize)
		return -1;
	if (pages <= HashTBSize)
		b = 0;					/* fit in memory, no partitioning */
	else
		b = ceil((double) (pages - HashTBSize) / (double) (HashTBSize - 1));

	return b;
}

/* ----------------------------------------------------------------
 *		ExecHashTableReset
 *
 *		reset hash table header for new batch
 * ----------------------------------------------------------------
 */
void
ExecHashTableReset(HashJoinTable hashtable, int ntuples)
{
	int			i;
	HashBucket	bucket;

	hashtable->nbuckets = hashtable->totalbuckets
		= ceil((double) ntuples / NTUP_PER_BUCKET);

	hashtable->overflownext = hashtable->top + hashtable->bucketsize *
		hashtable->nbuckets;

	bucket = (HashBucket) ABSADDR(hashtable->top);
	for (i = 0; i < hashtable->nbuckets; i++)
	{
		bucket->top = RELADDR((char *) bucket + sizeof(*bucket));
		bucket->bottom = bucket->top;
		bucket->firstotuple = bucket->lastotuple = -1;
		bucket = (HashBucket) ((char *) bucket + hashtable->bucketsize);
	}
	hashtable->pcount = hashtable->nprocess;
}

static int	hjtmpcnt = 0;

static void
mk_hj_temp(char *tempname)
{
	snprintf(tempname, strlen(tempname), "HJ%d.%d", (int) MyProcPid, hjtmpcnt);
	hjtmpcnt = (hjtmpcnt + 1) % 1000;
}

void
ExecReScanHash(Hash *node, ExprContext *exprCtxt, Plan *parent)
{
	HashState  *hashstate = node->hashstate;

	if (hashstate->hashBatches != NULL)
	{
		pfree(hashstate->hashBatches);
		hashstate->hashBatches = NULL;
	}

	/*
	 * if chgParam of subnode is not null then plan will be re-scanned by
	 * first ExecProcNode.
	 */
	if (((Plan *) node)->lefttree->chgParam == NULL)
		ExecReScan(((Plan *) node)->lefttree, exprCtxt, (Plan *) node);

}