psort.c 21.9 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*-------------------------------------------------------------------------
 *
 * psort.c--
 *    Polyphase merge sort.
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *    $Header: /cvsroot/pgsql/src/backend/utils/sort/Attic/psort.c,v 1.7 1997/08/06 04:45:39 momjian Exp $
11 12
 *
 * NOTES
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 *      Sorts the first relation into the second relation.
 *
 *      The old psort.c's routines formed a temporary relation from the merged
 * sort files. This version keeps the files around instead of generating the
 * relation from them, and provides interface functions to the file so that
 * you can grab tuples, mark a position in the file, restore a position in the
 * file. You must now explicitly call an interface function to end the sort,
 * psort_end, when you are done.
 *      Now most of the global variables are stuck in the Sort nodes, and
 * accessed from there (they are passed to all the psort routines) so that
 * each sort running has its own separate state. This is facilitated by having
 * the Sort nodes passed in to all the interface functions.
 *      The one global variable that all the sorts still share is SortMemory.
 *      You should now be allowed to run two or more psorts concurrently,
 * so long as the memory they eat up is not greater than SORTMEM, the initial
 * value of SortMemory.				        	-Rex 2.15.1995
29 30 31 32 33 34 35 36 37 38
 *
 *    Use the tape-splitting method (Knuth, Vol. III, pp281-86) in the future.
 *
 *	Arguments? Variables?
 *		MAXMERGE, MAXTAPES
 *-------------------------------------------------------------------------
 */
#include <stdio.h>
#include <math.h>

39
#include "postgres.h"
40 41 42 43 44 45 46 47 48 49 50

#include "executor/execdebug.h"
#include "access/heapam.h"
#include "access/htup.h"
#include "access/relscan.h"
#include "access/skey.h"
#include "utils/tqual.h"	/* for NowTimeQual */

#include "storage/buf.h"
#include "storage/bufmgr.h"	/* for BLCKSZ */
#include "utils/portal.h"	/* for {Start,End}PortalAllocMode */
51
#include "utils/elog.h"
52 53
#include "utils/rel.h"

54 55 56 57
#include "nodes/execnodes.h"
#include "nodes/plannodes.h"
#include "executor/executor.h"

58
#include "utils/lselect.h"
59
#include "utils/psort.h"
60 61 62 63 64

#include "storage/fd.h"

#define	TEMPDIR	"./"

65 66
extern 		int	SortMem;	/* defined as postgres option */
static  	long	shortzero = 0;	/* used to delimit runs */
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
/*
 * old psort global variables
 *
 * (These are the global variables from the old psort. They are still used,
 *  but are now accessed from Sort nodes using the PS macro. Note that while
 *  these variables will be accessed by PS(node)->whatever, they will still
 *  be called by their original names within the comments!      -Rex 2.10.1995)
 *
 * LeftistContextData   treeContext;
 *
 * static       int     TapeRange;		// number of tapes - 1 (T) //
 * static       int     Level;			// (l) //
 * static       int     TotalDummy;		// summation of tp_dummy //
 * static struct tape   *Tape;
 *
 * static  	int	BytesRead;		// to keep track of # of IO //
 * static  	int	BytesWritten;
 *
 * struct leftist       *Tuples;		// current tuples in memory //
 *
 * FILE		 	*psort_grab_file;       // this holds tuples grabbed
 *						   from merged sort runs //
 * long		 	psort_current;		// current file position //
 * long		 	psort_saved;		// file position saved for
 *						   mark and restore //
 */
94

95 96 97 98
/*
 * PS - Macro to access and cast psortstate from a Sort node
 */
#define PS(N) ((Psortstate *)N->psortstate)
99 100

/*
101 102 103 104 105 106 107 108
 *      psort_begin     - polyphase merge sort entry point. Sorts the subplan
 *			  into a temporary file psort_grab_file. After
 *			  this is called, calling the interface function
 *			  psort_grabtuple iteratively will get you the sorted
 *			  tuples. psort_end then finishes the sort off, after
 *			  all the tuples have been grabbed.
 *
 *		          Allocates and initializes sort node's psort state.
109
 */
110 111
bool
psort_begin(Sort *node, int nkeys, ScanKey key)
112
{
113 114 115 116 117 118
    bool empty;	 /* to answer: is child node empty? */

    node->psortstate = (struct Psortstate *)palloc(sizeof(struct Psortstate));
    if (node->psortstate == NULL)
	return false;

119 120 121 122
    AssertArg(nkeys >= 1);
    AssertArg(key[0].sk_attno != 0);
    AssertArg(key[0].sk_procedure != 0);
    
123 124 125 126 127 128 129
    PS(node)->BytesRead = 0;
    PS(node)->BytesWritten = 0;
    PS(node)->treeContext.tupDesc =
	ExecGetTupType(outerPlan((Plan *)node));
    PS(node)->treeContext.nKeys = nkeys;
    PS(node)->treeContext.scanKeys = key;
    PS(node)->treeContext.sortMem = SortMem;
130

131 132 133 134 135 136 137 138 139 140 141 142 143
    PS(node)->Tuples = NULL;
    PS(node)->tupcount = 0;
    
    PS(node)->using_tape_files = false;
    PS(node)->memtuples = NULL;

    initialrun(node, &empty);

    if (empty)
	return false;

    if (PS(node)->using_tape_files)
	PS(node)->psort_grab_file = mergeruns(node);
144

145 146 147 148 149
    PS(node)->psort_current = 0;
    PS(node)->psort_saved = 0;

    return true;
}
150 151

/*
152
 *	inittapes	- initializes the tapes
153 154 155 156 157
 *			- (polyphase merge Alg.D(D1)--Knuth, Vol.3, p.270)
 *	Returns:
 *		number of allocated tapes
 */
void
158
inittapes(Sort *node)
159 160 161 162
{
    register	int			i;
    register	struct	tape		*tp;
    
163 164 165
    Assert(node != (Sort *) NULL);
    Assert(PS(node) != (Psortstate *) NULL);

166 167
    /*
      ASSERT(ntapes >= 3 && ntapes <= MAXTAPES,
168
      "inittapes: Invalid number of tapes to initialize.\n");
169 170
      */
    
171
    tp = PS(node)->Tape;
172 173 174 175 176 177
    for (i = 0; i < MAXTAPES && (tp->tp_file = gettape()) != NULL; i++) {
	tp->tp_dummy = 1;
	tp->tp_fib = 1;
	tp->tp_prev = tp - 1;
	tp++;
    }
178
    PS(node)->TapeRange = --tp - PS(node)->Tape;
179 180
    tp->tp_dummy = 0;
    tp->tp_fib = 0;
181
    PS(node)->Tape[0].tp_prev = tp;
182
    
183 184 185
    if (PS(node)->TapeRange <= 1)
	elog(WARN, "inittapes: Could only allocate %d < 3 tapes\n",
	     PS(node)->TapeRange + 1);
186
    
187 188 189 190
    PS(node)->Level = 1;
    PS(node)->TotalDummy = PS(node)->TapeRange;

    PS(node)->using_tape_files = true;
191 192 193
}

/*
194
 *	resetpsort	- resets (pfrees) palloc'd memory for an aborted Xaction
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
 *
 *	Not implemented yet.
 */
void
resetpsort()
{
    ;
}

/*
 *	PUTTUP		- writes the next tuple
 *	ENDRUN		- mark end of run
 *	GETLEN		- reads the length of the next tuple
 *	ALLOCTUP	- returns space for the new tuple
 *	SETTUPLEN	- stores the length into the tuple
 *	GETTUP		- reads the tuple
 *
 *	Note:
 *		LEN field must be a short; FP is a stream
 */

216 217 218 219

#define	PUTTUP(NODE, TUP, FP) if (1) {\
    ((Psortstate *)NODE->psortstate)->BytesWritten += (TUP)->t_len; \
    fwrite((char *)TUP, (TUP)->t_len, 1, FP);} else
220 221
#define	ENDRUN(FP)	fwrite((char *)&shortzero, sizeof (shortzero), 1, FP)
#define	GETLEN(LEN, FP)	fread((char *)&(LEN), sizeof (shortzero), 1, FP)
222
#define	ALLOCTUP(LEN)	((HeapTuple)palloc((unsigned)LEN))
223
#define	GETTUP(NODE, TUP, LEN, FP) if (1) {\
224
    IncrProcessed(); \
225 226 227
    ((Psortstate *)NODE->psortstate)->BytesRead += (LEN) - sizeof (shortzero); \
    fread((char *)(TUP) + sizeof (shortzero), (LEN) - sizeof (shortzero), 1, FP);} \
				else
228 229 230 231 232 233 234 235
#define	SETTUPLEN(TUP, LEN)	(TUP)->t_len = LEN
    
    /*
     *	USEMEM		- record use of memory
     *	FREEMEM		- record freeing of memory
     *	FULLMEM		- 1 iff a tuple will fit
     */
    
236 237 238
#define	USEMEM(NODE,AMT)	PS(node)->treeContext.sortMem -= (AMT)
#define	FREEMEM(NODE,AMT)	PS(node)->treeContext.sortMem += (AMT)
#define	LACKMEM(NODE)		(PS(node)->treeContext.sortMem <= MAXBLCKSZ)	/* not accurate */
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
#define	TRACEMEM(FUNC)
#define	TRACEOUT(FUNC, TUP)

/*
 *	initialrun	- distributes tuples from the relation
 *			- (replacement selection(R2-R3)--Knuth, Vol.3, p.257)
 *			- (polyphase merge Alg.D(D2-D4)--Knuth, Vol.3, p.271)
 *
 *	Explaination:
 *		Tuples are distributed to the tapes as in Algorithm D.
 *		A "tuple" with t_size == 0 is used to mark the end of a run.
 *
 *	Note:
 *		The replacement selection algorithm has been modified
 *		to go from R1 directly to R3 skipping R2 the first time.
 *
 *		Maybe should use closer(rdesc) before return
 *		Perhaps should adjust the number of tapes if less than n.
 *		used--v. likely to have problems in mergeruns().
 *		Must know if should open/close files before each
 *		call to  psort()?   If should--messy??
 *
 *	Possible optimization:
 *		put the first xxx runs in quickly--problem here since
 *		I (perhaps prematurely) combined the 2 algorithms.
 *		Also, perhaps allocate tapes when needed. Split into 2 funcs.
 */
void
267
initialrun(Sort *node, bool *empty)
268 269 270 271
{
    /*	register struct	tuple	*tup; */
    register struct	tape	*tp;
    int		baseruns;		/* D:(a) */
272 273 274 275 276 277
    int		extrapasses;		/* EOF */

    Assert(node != (Sort *) NULL);
    Assert(PS(node) != (Psortstate *) NULL);

    tp = PS(node)->Tape;
278
    
279 280 281 282 283
    if ((bool)createrun(node, tp->tp_file, empty) != false) {
	if (! PS(node)->using_tape_files)
	    inittapes(node);
	extrapasses = 0;
    }
284
    else
285
	return;	/* if rows fit in memory, we never access tape stuff */
286 287 288
    
    for ( ; ; ) {
	tp->tp_dummy--;
289
	PS(node)->TotalDummy--;
290 291 292
	if (tp->tp_dummy < (tp + 1)->tp_dummy)
	    tp++;
	else if (tp->tp_dummy != 0)
293
	    tp = PS(node)->Tape;
294
	else {
295 296 297 298 299
	    PS(node)->Level++;
	    baseruns = PS(node)->Tape[0].tp_fib;
	    for (tp = PS(node)->Tape;
		 tp - PS(node)->Tape < PS(node)->TapeRange; tp++) {
		PS(node)->TotalDummy +=
300 301 302 303 304 305
		    (tp->tp_dummy = baseruns
		     + (tp + 1)->tp_fib
		     - tp->tp_fib);
		tp->tp_fib = baseruns
		    + (tp + 1)->tp_fib;
	    }
306
	    tp = PS(node)->Tape;		/* D4 */
307
	}					/* D3 */
308 309 310
	if (extrapasses)
	    if (--extrapasses) {
		dumptuples(node);
311 312 313 314
		ENDRUN(tp->tp_file);
		continue;
	    } else
		break;
315 316 317

	if ((bool)createrun(node, tp->tp_file, empty) == false)
	    extrapasses = 1 + (PS(node)->Tuples != NULL);
318 319
	/* D2 */
    }
320 321
    for (tp = PS(node)->Tape + PS(node)->TapeRange; tp >= PS(node)->Tape; tp--)
	rewind(tp->tp_file);			    /* D. */
322 323 324
}

/*
325 326
 *      createrun       - places the next run on file, grabbing the tuples by
 *			executing the subplan passed in
327 328 329 330 331 332 333 334 335
 *
 *	Uses:
 *		Tuples, which should contain any tuples for this run
 *
 *	Returns:
 *		FALSE iff process through end of relation
 *		Tuples contains the tuples for the following run upon exit
 */
bool
336
createrun(Sort *node, FILE *file, bool *empty)
337 338 339 340 341 342 343
{
    register HeapTuple	lasttuple;
    register HeapTuple	btup, tup;
    struct	leftist	*nextrun;
    Buffer	b;
    bool		foundeor;
    short		junk;
344 345 346 347 348 349 350

    int cr_tuples = 0; /* Count tuples grabbed from plannode */
    TupleTableSlot *cr_slot;

    Assert(node != (Sort *) NULL);
    Assert(PS(node) != (Psortstate *) NULL);

351 352 353 354
    lasttuple = NULL;
    nextrun = NULL;
    foundeor = false;
    for ( ; ; ) {
355
	while (LACKMEM(node) && PS(node)->Tuples != NULL) {
356
	    if (lasttuple != NULL) {
357
		FREEMEM(node,lasttuple->t_len);
358 359 360
		FREE(lasttuple);
		TRACEMEM(createrun);
	    }
361 362 363 364 365
	    lasttuple = tup = gettuple(&PS(node)->Tuples, &junk,
				       &PS(node)->treeContext);
	    if (! PS(node)->using_tape_files)
		inittapes(node);
	    PUTTUP(node, tup, PS(node)->Tape->tp_file);
366 367
	    TRACEOUT(createrun, tup);
	}
368
	if (LACKMEM(node))
369
	    break;
370 371 372 373 374 375 376 377 378

	/* About to call ExecProcNode, it can mess up the state if it
	 * eventually calls another Sort node. So must stow it away here for
	 * the meantime.					-Rex 2.2.1995
	 */

	cr_slot = ExecProcNode(outerPlan((Plan *)node), (Plan *)node);

	if (TupIsNull(cr_slot)) {
379 380 381
	    foundeor = true;
	    break;
	}
382 383 384 385 386 387 388
	else {
	    tup = tuplecopy(cr_slot->val);
	    ExecClearTuple(cr_slot);
	    PS(node)->tupcount++;
	    cr_tuples++;
	}

389
	IncrProcessed();
390
	USEMEM(node,tup->t_len);
391
	TRACEMEM(createrun);
392 393 394
	if (lasttuple != NULL && tuplecmp(tup, lasttuple,
					  &PS(node)->treeContext))
	    puttuple(&nextrun, tup, 0, &PS(node)->treeContext);
395
	else
396
	    puttuple(&PS(node)->Tuples, tup, 0, &PS(node)->treeContext);
397 398
    }
    if (lasttuple != NULL) {
399
	FREEMEM(node,lasttuple->t_len);
400 401 402
	FREE(lasttuple);
	TRACEMEM(createrun);
    }
403 404 405
    dumptuples(node);
    if (PS(node)->using_tape_files)
	ENDRUN(file);
406
    /* delimit the end of the run */
407 408 409 410 411
    PS(node)->Tuples = nextrun;

    /* if we did not see any tuples, mark empty */
    *empty = (cr_tuples > 0) ? false : true;

412 413 414 415 416 417 418
    return((bool)! foundeor); /* XXX - works iff bool is {0,1} */
}

/*
 *	tuplecopy	- see also tuple.c:palloctup()
 *
 *	This should eventually go there under that name?  And this will
419
 *	then use palloc directly (see version -r1.2).
420 421
 */
HeapTuple
422
tuplecopy(HeapTuple tup)
423 424 425 426 427 428
{
    HeapTuple	rettup;
    
    if (!HeapTupleIsValid(tup)) {
	return(NULL);		/* just in case */
    }
429
    rettup = (HeapTuple)palloc(tup->t_len);
430 431 432 433 434 435 436 437 438 439 440 441
    memmove((char *)rettup, (char *)tup, tup->t_len);	/* XXX */
    return(rettup);
}

/*
 *	mergeruns	- merges all runs from input tapes
 *			  (polyphase merge Alg.D(D6)--Knuth, Vol.3, p271)
 *
 *	Returns:
 *		file of tuples in order
 */
FILE *
442
mergeruns(Sort *node)
443
{
444 445 446 447 448 449 450 451
    register struct     tape    *tp;

    Assert(node != (Sort *) NULL);
    Assert(PS(node) != (Psortstate *) NULL);
    Assert(PS(node)->using_tape_files == true);

    tp = PS(node)->Tape + PS(node)->TapeRange;
    merge(node, tp);
452
    rewind(tp->tp_file);
453
    while (--PS(node)->Level != 0) {
454 455
	tp = tp->tp_prev;
	rewind(tp->tp_file);
456 457
	/*	      resettape(tp->tp_file);	 -not sufficient */
	merge(node, tp);
458 459 460 461 462 463 464 465 466 467
	rewind(tp->tp_file);
    }
    return(tp->tp_file);
}

/*
 *	merge		- handles a single merge of the tape
 *			  (polyphase merge Alg.D(D5)--Knuth, Vol.3, p271)
 */
void
468
merge(Sort *node, struct tape *dest)
469 470 471 472 473 474 475 476 477 478 479
{
    register HeapTuple	tup;
    register struct	tape	*lasttp;	/* (TAPE[P]) */
    register struct	tape	*tp;
    struct	leftist	*tuples;
    FILE		*destfile;
    int		times;		/* runs left to merge */
    int		outdummy;	/* complete dummy runs */
    short		fromtape;
    long		tuplen;
    
480 481 482 483
    Assert(node != (Sort *) NULL);
    Assert(PS(node) != (Psortstate *) NULL);
    Assert(PS(node)->using_tape_files == true);

484 485 486 487 488 489 490
    lasttp = dest->tp_prev;
    times = lasttp->tp_fib;
    for (tp = lasttp ; tp != dest; tp = tp->tp_prev)
	tp->tp_fib -= times;
    tp->tp_fib += times;
    /* Tape[].tp_fib (A[]) is set to proper exit values */
    
491
    if (PS(node)->TotalDummy < PS(node)->TapeRange)/* no complete dummy runs */
492 493
	outdummy = 0;
    else {
494
	outdummy = PS(node)->TotalDummy;	/* a large positive number */
495 496 497 498 499 500
	for (tp = lasttp; tp != dest; tp = tp->tp_prev)
	    if (outdummy > tp->tp_dummy)
		outdummy = tp->tp_dummy;
	for (tp = lasttp; tp != dest; tp = tp->tp_prev)
	    tp->tp_dummy -= outdummy;
	tp->tp_dummy += outdummy;
501
	PS(node)->TotalDummy -= outdummy * PS(node)->TapeRange;
502 503 504 505
	/* do not add the outdummy runs yet */
	times -= outdummy;
    }
    destfile = dest->tp_file;
506
    while (times-- != 0) {		      /* merge one run */
507
	tuples = NULL;
508
	if (PS(node)->TotalDummy == 0)
509 510 511
	    for (tp = dest->tp_prev; tp != dest; tp = tp->tp_prev) {
		GETLEN(tuplen, tp->tp_file);
		tup = ALLOCTUP(tuplen);
512
		USEMEM(node,tuplen);
513 514
		TRACEMEM(merge);
		SETTUPLEN(tup, tuplen);
515 516 517
		GETTUP(node, tup, tuplen, tp->tp_file);
		puttuple(&tuples, tup, tp - PS(node)->Tape,
			 &PS(node)->treeContext);
518 519 520 521 522
	    }
	else {
	    for (tp = dest->tp_prev; tp != dest; tp = tp->tp_prev) {
		if (tp->tp_dummy != 0) {
		    tp->tp_dummy--;
523
		    PS(node)->TotalDummy--;
524 525 526
		} else {
		    GETLEN(tuplen, tp->tp_file);
		    tup = ALLOCTUP(tuplen);
527
		    USEMEM(node,tuplen);
528 529
		    TRACEMEM(merge);
		    SETTUPLEN(tup, tuplen);
530 531 532
		    GETTUP(node, tup, tuplen, tp->tp_file);
		    puttuple(&tuples, tup, tp - PS(node)->Tape,
			     &PS(node)->treeContext);
533 534 535 536 537
		}
	    }
	}
	while (tuples != NULL) {
	    /* possible optimization by using count in tuples */
538 539 540
	    tup = gettuple(&tuples, &fromtape, &PS(node)->treeContext);
	    PUTTUP(node, tup, destfile);
	    FREEMEM(node,tup->t_len);
541 542
	    FREE(tup);
	    TRACEMEM(merge);
543
	    GETLEN(tuplen, PS(node)->Tape[fromtape].tp_file);
544 545 546 547
	    if (tuplen == 0)
		;
	    else {
		tup = ALLOCTUP(tuplen);
548
		USEMEM(node,tuplen);
549 550
		TRACEMEM(merge);
		SETTUPLEN(tup, tuplen);
551 552
		GETTUP(node, tup, tuplen, PS(node)->Tape[fromtape].tp_file);
		puttuple(&tuples, tup, fromtape, &PS(node)->treeContext);
553
	    }
554
	} 
555 556
	ENDRUN(destfile);
    }
557
    PS(node)->TotalDummy += outdummy;
558 559 560
}

/*
561
 * dumptuples	- stores all the tuples in tree into file
562 563
 */
void
564
dumptuples(Sort *node)
565
{
566 567 568 569 570 571 572
    register struct	leftist	*tp;
    register struct	leftist	*newp;
    struct leftist **treep = &PS(node)->Tuples;
    LeftistContext context = &PS(node)->treeContext;
    HeapTuple	tup;
    int memtupindex = 0;

573
    if (! PS(node)->using_tape_files && PS(node)->tupcount) {
574 575 576
	Assert(PS(node)->memtuples == NULL);
    	PS(node)->memtuples = palloc(PS(node)->tupcount * sizeof(HeapTuple));
    }
577
    
578 579 580 581 582 583 584 585 586 587 588 589
    tp = *treep;
    while (tp != NULL) {
	tup = tp->lt_tuple;
	if (tp->lt_dist == 1)			/* lt_right == NULL */
	    newp = tp->lt_left;
	else
	    newp = lmerge(tp->lt_left, tp->lt_right, context);
	FREEMEM(node,sizeof (struct leftist));
	FREE(tp);
	if (PS(node)->using_tape_files) {
	    PUTTUP(node, tup, PS(node)->Tape->tp_file);
	    FREEMEM(node,tup->t_len);
590 591
	    FREE(tup);
	}
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
	else
	    PS(node)->memtuples[memtupindex++] = tup;

	tp = newp;
    }
    *treep = NULL;
}

/*
 *      psort_grabtuple - gets a tuple from the sorted file and returns it.
 *			  If there are no tuples left, returns NULL.
 *			  Should not call psort_end unless this has returned
 *		          a NULL indicating the last tuple has been processed.
 */
HeapTuple
psort_grabtuple(Sort *node)
{
    register HeapTuple  tup;
    long		tuplen;

    Assert(node != (Sort *) NULL);
    Assert(PS(node) != (Psortstate *) NULL);

    if (PS(node)->using_tape_files == true) {
	if (!feof(PS(node)->psort_grab_file)) {
	    if (GETLEN(tuplen, PS(node)->psort_grab_file) && tuplen != 0) {
	    	tup = (HeapTuple)palloc((unsigned)tuplen);
		SETTUPLEN(tup, tuplen);
	    	GETTUP(node, tup, tuplen, PS(node)->psort_grab_file);

	    	/* Update current merged sort file position */
		PS(node)->psort_current += tuplen;

	    	return tup;
	    }
	    else
	    	return NULL;
    	}
    	else
	    return NULL;
    }
    else {
    	if (PS(node)->psort_current < PS(node)->tupcount)
	    return PS(node)->memtuples[PS(node)->psort_current++];
    	else
	    return NULL;
    }
}

/*
 *      psort_markpos   - saves current position in the merged sort file
 */
void
psort_markpos(Sort *node)
{
    Assert(node != (Sort *) NULL);
    Assert(PS(node) != (Psortstate *) NULL);

    PS(node)->psort_saved = PS(node)->psort_current;
}

/*
 *      psort_restorepos- restores current position in merged sort file to
 *			  last saved position
 */
void
psort_restorepos(Sort *node)
{
    Assert(node != (Sort *) NULL);
    Assert(PS(node) != (Psortstate *) NULL);

    if (PS(node)->using_tape_files == true)
	fseek(PS(node)->psort_grab_file, PS(node)->psort_saved, SEEK_SET);
    PS(node)->psort_current = PS(node)->psort_saved;
}

/*
 *      psort_end       - unlinks the tape files, and cleans up. Should not be
 *			  called unless psort_grabtuple has returned a NULL.
 */
void
psort_end(Sort *node)
{
    register struct     tape    *tp;

    if (!node->cleaned) {
	Assert(node != (Sort *) NULL);
/* 	Assert(PS(node) != (Psortstate *) NULL); */

	/*
	 * I'm changing this because if we are sorting a relation
	 * with no tuples, psortstate is NULL.
	 */
	if (PS(node) != (Psortstate *) NULL) {
	    if (PS(node)->using_tape_files == true)
		for (tp = PS(node)->Tape + PS(node)->TapeRange; tp >= PS(node)->Tape; tp--)
		    destroytape(tp->tp_file);
	    else if (PS(node)->memtuples)
		pfree(PS(node)->memtuples);
	    
	    NDirectFileRead +=
		(int)ceil((double)PS(node)->BytesRead / BLCKSZ);
	    NDirectFileWrite +=
		(int)ceil((double)PS(node)->BytesWritten / BLCKSZ);

	    pfree((void *)node->psortstate);

	    node->cleaned = TRUE;
	}
    }
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
}

/*
 *	gettape		- handles access temporary files in polyphase merging
 *
 *	Optimizations:
 *		If guarenteed that only one sort running/process,
 *		can simplify the file generation--and need not store the
 *		name for later unlink.
 */

struct tapelst {
    char		*tl_name;
    int		tl_fd;
    struct	tapelst	*tl_next;
};

static struct	tapelst	*Tapes = NULL;
static char	Tempfile[MAXPGPATH] = TEMPDIR;

/*
 *	gettape		- returns an open stream for writing/reading
 *
 *	Returns:
 *		Open stream for writing/reading.
 *		NULL if unable to open temporary file.
 */
FILE *
gettape()
{
732 733 734 735 736 737 738
    register 	struct		tapelst	*tp;
    FILE			*file;
    static	int		tapeinit = 0;
    char			*mktemp();
    static	unsigned int	uniqueFileId = 0;
    extern	int		errno;
    char			uniqueName[MAXPGPATH];
739
    
740
    tp = (struct tapelst *)palloc((unsigned)sizeof (struct tapelst));
741 742 743 744 745 746 747 748
    
    sprintf(uniqueName, "%spg_psort.%d.%d", TEMPDIR, getpid(), uniqueFileId);
    uniqueFileId++;
    
    tapeinit = 1;
    
    tp->tl_name = palloc((unsigned)sizeof(uniqueName));
    
749
    /*
750
     * now, copy template with final null into palloc'd space
751
     */
752 753 754
    
    memmove(tp->tl_name, uniqueName, strlen(uniqueName));
    
755 756 757 758
    
    AllocateFile();
    file = fopen(tp->tl_name, "w+");
    if (file == NULL) {
759
	elog(NOTICE, "psort: gettape: fopen returned error code %i", errno);
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
	/* XXX this should not happen */
	FreeFile();
	FREE(tp->tl_name);
	FREE(tp);
	return(NULL);
    }
    
    tp->tl_fd = fileno(file);
    tp->tl_next = Tapes;
    Tapes = tp;
    return(file);
}

/*
 *	resettape	- resets the tape to size 0
 */
void
resettape(FILE *file)
{
    register	struct	tapelst	*tp;
    register	int		fd;
    
    Assert(PointerIsValid(file));
    
    fd = fileno(file);
    for (tp = Tapes; tp != NULL && tp->tl_fd != fd; tp = tp->tl_next)
	;
    if (tp == NULL)
	elog(WARN, "resettape: tape not found");
    
    file = freopen(tp->tl_name, "w+", file);
    if (file == NULL) {
	elog(FATAL, "could not freopen temporary file");
    }
}

/*
 *	distroytape	- unlinks the tape
 *
 *	Efficiency note:
 *		More efficient to destroy more recently allocated tapes first.
 *
 *	Possible bugs:
 *		Exits instead of returning status, if given invalid tape.
 */
void
destroytape(FILE *file)
{
    register	struct	tapelst		*tp, *tq;
    register	int			fd;
    
    if ((tp = Tapes) == NULL)
	elog(FATAL, "destroytape: tape not found");
    
    if ((fd = fileno(file)) == tp->tl_fd) {
	Tapes = tp->tl_next;
	fclose(file);
	FreeFile();
	unlink(tp->tl_name);
	FREE(tp->tl_name);
	FREE(tp);
    } else
	for ( ; ; ) {
	    if (tp->tl_next == NULL)
		elog(FATAL, "destroytape: tape not found");
	    if (tp->tl_next->tl_fd == fd) {
		fclose(file);
		FreeFile();
		tq = tp->tl_next;
		tp->tl_next = tq->tl_next;
		unlink(tq->tl_name);
		FREE((tq->tl_name));
		FREE(tq);
		break;
	    }
	    tp = tp->tl_next;
	}
}