1 /*-
2  * Copyright (c) 1990, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Margo Seltzer.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #define _DEFAULT_SOURCE
34 #include <sys/param.h>
35 #if defined(LIBC_SCCS) && !defined(lint)
36 static char sccsid[] = "@(#)hash_page.c	8.7 (Berkeley) 8/16/94";
37 #endif /* LIBC_SCCS and not lint */
38 #include <sys/cdefs.h>
39 
40 /*
41  * PACKAGE:  hashing
42  *
43  * DESCRIPTION:
44  *	Page manipulation for hashing package.
45  *
46  * ROUTINES:
47  *
48  * External
49  *	__get_page
50  *	__add_ovflpage
51  * Internal
52  *	overflow_page
53  *	open_temp
54  */
55 
56 #include <sys/types.h>
57 
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <signal.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <unistd.h>
65 #ifdef DEBUG
66 #include <assert.h>
67 #endif
68 
69 #include "db_local.h"
70 #include "hash.h"
71 #include "page.h"
72 #include "extern.h"
73 
74 static __uint32_t	*fetch_bitmap(HTAB *, int);
75 static __uint32_t	 first_free(__uint32_t);
76 static int	 open_temp(HTAB *);
77 static __uint16_t	 overflow_page(HTAB *);
78 static void	 putpair(char *, const DBT *, const DBT *);
79 static void	 squeeze_key(__uint16_t *, const DBT *, const DBT *);
80 static int	 ugly_split
81 (HTAB *, __uint32_t, BUFHEAD *, BUFHEAD *, int, int);
82 
83 #define	PAGE_INIT(P) { \
84 	((__uint16_t *)(P))[0] = 0; \
85 	((__uint16_t *)(P))[1] = hashp->BSIZE - 3 * sizeof(__uint16_t); \
86 	((__uint16_t *)(P))[2] = hashp->BSIZE; \
87 }
88 
89 /*
90  * This is called AFTER we have verified that there is room on the page for
91  * the pair (PAIRFITS has returned true) so we go right ahead and start moving
92  * stuff on.
93  */
94 static void
putpair(char * p,const DBT * key,const DBT * val)95 putpair(char *p, const DBT *key, const DBT *val)
96 {
97 	__uint16_t *bp, n, off;
98 
99 	bp = (__uint16_t *)p;
100 
101 	/* Enter the key first. */
102 	n = bp[0];
103 
104 	off = OFFSET(bp) - key->size;
105 	memmove(p + off, key->data, key->size);
106 	bp[++n] = off;
107 
108 	/* Now the data. */
109 	off -= val->size;
110 	memmove(p + off, val->data, val->size);
111 	bp[++n] = off;
112 
113 	/* Adjust page info. */
114 	bp[0] = n;
115 	bp[n + 1] = off - ((n + 3) * sizeof(__uint16_t));
116 	bp[n + 2] = off;
117 }
118 
119 /*
120  * Returns:
121  *	 0 OK
122  *	-1 error
123  */
124 extern int
__delpair(HTAB * hashp,BUFHEAD * bufp,int ndx)125 __delpair(HTAB *hashp,
126           BUFHEAD *bufp,
127           int ndx)
128 {
129 	__uint16_t *bp, newoff;
130 	int n;
131 	__uint16_t pairlen;
132 
133 	bp = (__uint16_t *)bufp->page;
134 	n = bp[0];
135 
136 	if (bp[ndx + 1] < REAL_KEY)
137 		return (__big_delete(hashp, bufp));
138 	if (ndx != 1)
139 		newoff = bp[ndx - 1];
140 	else
141 		newoff = hashp->BSIZE;
142 	pairlen = newoff - bp[ndx + 1];
143 
144 	if (ndx != (n - 1)) {
145 		/* Hard Case -- need to shuffle keys */
146 		int i;
147 		char *src = bufp->page + (int)OFFSET(bp);
148 		char *dst = src + (int)pairlen;
149 		memmove(dst, src, bp[ndx + 1] - OFFSET(bp));
150 
151 		/* Now adjust the pointers */
152 		for (i = ndx + 2; i <= n; i += 2) {
153 			if (bp[i + 1] == OVFLPAGE) {
154 				bp[i - 2] = bp[i];
155 				bp[i - 1] = bp[i + 1];
156 			} else {
157 				bp[i - 2] = bp[i] + pairlen;
158 				bp[i - 1] = bp[i + 1] + pairlen;
159 			}
160 		}
161 	}
162 	/* Finally adjust the page data */
163 	bp[n] = OFFSET(bp) + pairlen;
164 	bp[n - 1] = bp[n + 1] + pairlen + 2 * sizeof(__uint16_t);
165 	bp[0] = n - 2;
166 	hashp->NKEYS--;
167 
168 	bufp->flags |= BUF_MOD;
169 	return (0);
170 }
171 /*
172  * Returns:
173  *	 0 ==> OK
174  *	-1 ==> Error
175  */
176 extern int
__split_page(HTAB * hashp,__uint32_t obucket,__uint32_t nbucket)177 __split_page(HTAB *hashp,
178              __uint32_t obucket,
179              __uint32_t nbucket)
180 {
181 	BUFHEAD *new_bufp, *old_bufp;
182 	__uint16_t *ino;
183 	char *np;
184 	DBT key, val;
185 	int ndx, retval;
186 	__uint16_t n, copyto, diff, off, moved;
187 	char *op;
188 
189 	copyto = (__uint16_t)hashp->BSIZE;
190 	off = (__uint16_t)hashp->BSIZE;
191 	old_bufp = __get_buf(hashp, obucket, NULL, 0);
192 	if (old_bufp == NULL)
193 		return (-1);
194 	new_bufp = __get_buf(hashp, nbucket, NULL, 0);
195 	if (new_bufp == NULL)
196 		return (-1);
197 
198 	old_bufp->flags |= (BUF_MOD | BUF_PIN);
199 	new_bufp->flags |= (BUF_MOD | BUF_PIN);
200 
201 	ino = (__uint16_t *)(op = old_bufp->page);
202 	np = new_bufp->page;
203 
204 	moved = 0;
205 
206 	for (n = 1, ndx = 1; n < ino[0]; n += 2) {
207 		if (ino[n + 1] < REAL_KEY) {
208 			retval = ugly_split(hashp, obucket, old_bufp, new_bufp,
209 			    (int)copyto, (int)moved);
210 			old_bufp->flags &= ~BUF_PIN;
211 			new_bufp->flags &= ~BUF_PIN;
212 			return (retval);
213 
214 		}
215 		key.data = (u_char *)op + ino[n];
216 		key.size = off - ino[n];
217 
218 		if (__call_hash(hashp, key.data, key.size) == obucket) {
219 			/* Don't switch page */
220 			diff = copyto - off;
221 			if (diff) {
222 				copyto = ino[n + 1] + diff;
223 				memmove(op + copyto, op + ino[n + 1],
224 				    off - ino[n + 1]);
225 				ino[ndx] = copyto + ino[n] - ino[n + 1];
226 				ino[ndx + 1] = copyto;
227 			} else
228 				copyto = ino[n + 1];
229 			ndx += 2;
230 		} else {
231 			/* Switch page */
232 			val.data = (u_char *)op + ino[n + 1];
233 			val.size = ino[n] - ino[n + 1];
234 			putpair(np, &key, &val);
235 			moved += 2;
236 		}
237 
238 		off = ino[n + 1];
239 	}
240 
241 	/* Now clean up the page */
242 	ino[0] -= moved;
243 	FREESPACE(ino) = copyto - sizeof(__uint16_t) * (ino[0] + 3);
244 	OFFSET(ino) = copyto;
245 
246 #ifdef DEBUG3
247 	(void)fprintf(stderr, "split %d/%d\n",
248 	    ((__uint16_t *)np)[0] / 2,
249 	    ((__uint16_t *)op)[0] / 2);
250 #endif
251 	/* unpin both pages */
252 	old_bufp->flags &= ~BUF_PIN;
253 	new_bufp->flags &= ~BUF_PIN;
254 	return (0);
255 }
256 
257 /*
258  * Called when we encounter an overflow or big key/data page during split
259  * handling.  This is special cased since we have to begin checking whether
260  * the key/data pairs fit on their respective pages and because we may need
261  * overflow pages for both the old and new pages.
262  *
263  * The first page might be a page with regular key/data pairs in which case
264  * we have a regular overflow condition and just need to go on to the next
265  * page or it might be a big key/data pair in which case we need to fix the
266  * big key/data pair.
267  *
268  * Returns:
269  *	 0 ==> success
270  *	-1 ==> failure
271  */
272 static int
ugly_split(HTAB * hashp,__uint32_t obucket,BUFHEAD * old_bufp,BUFHEAD * new_bufp,int copyto,int moved)273 ugly_split(HTAB *hashp,
274            __uint32_t obucket,	/* Same as __split_page. */
275            BUFHEAD *old_bufp,
276            BUFHEAD *new_bufp,
277            int copyto,  	/* First byte on page which contains key/data values. */
278            int moved)		/* Number of pairs moved to new page. */
279 {
280 	BUFHEAD *bufp;		/* Buffer header for ino */
281 	__uint16_t *ino;		/* Page keys come off of */
282 	__uint16_t *np;		/* New page */
283 	__uint16_t *op;		/* Page keys go on to if they aren't moving */
284 
285 	BUFHEAD *last_bfp;	/* Last buf header OVFL needing to be freed */
286 	DBT key, val;
287 	SPLIT_RETURN ret;
288 	__uint16_t n, off, ov_addr, scopyto;
289 	char *cino;		/* Character value of ino */
290 
291 	bufp = old_bufp;
292 	ino = (__uint16_t *)old_bufp->page;
293 	np = (__uint16_t *)new_bufp->page;
294 	op = (__uint16_t *)old_bufp->page;
295 	last_bfp = NULL;
296 	scopyto = (__uint16_t)copyto;	/* ANSI */
297 
298 	n = ino[0] - 1;
299 	while (n < ino[0]) {
300 		if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) {
301 			if (__big_split(hashp, old_bufp,
302 			    new_bufp, bufp, bufp->addr, obucket, &ret))
303 				return (-1);
304 			old_bufp = ret.oldp;
305 			if (!old_bufp)
306 				return (-1);
307 			op = (__uint16_t *)old_bufp->page;
308 			new_bufp = ret.newp;
309 			if (!new_bufp)
310 				return (-1);
311 			np = (__uint16_t *)new_bufp->page;
312 			bufp = ret.nextp;
313 			if (!bufp)
314 				return (0);
315 			cino = (char *)bufp->page;
316 			ino = (__uint16_t *)cino;
317 			last_bfp = ret.nextp;
318 		} else if (ino[n + 1] == OVFLPAGE) {
319 			ov_addr = ino[n];
320 			/*
321 			 * Fix up the old page -- the extra 2 are the fields
322 			 * which contained the overflow information.
323 			 */
324 			ino[0] -= (moved + 2);
325 			FREESPACE(ino) =
326 			    scopyto - sizeof(__uint16_t) * (ino[0] + 3);
327 			OFFSET(ino) = scopyto;
328 
329 			bufp = __get_buf(hashp, ov_addr, bufp, 0);
330 			if (!bufp)
331 				return (-1);
332 
333 			ino = (__uint16_t *)bufp->page;
334 			n = 1;
335 			scopyto = hashp->BSIZE;
336 			moved = 0;
337 
338 			if (last_bfp)
339 				__free_ovflpage(hashp, last_bfp);
340 			last_bfp = bufp;
341 		}
342 		/* Move regular sized pairs of there are any */
343 		off = hashp->BSIZE;
344 		for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) {
345 			cino = (char *)ino;
346 			key.data = (u_char *)cino + ino[n];
347 			key.size = off - ino[n];
348 			val.data = (u_char *)cino + ino[n + 1];
349 			val.size = ino[n] - ino[n + 1];
350 			off = ino[n + 1];
351 
352 			if (__call_hash(hashp, key.data, key.size) == obucket) {
353 				/* Keep on old page */
354 				if (PAIRFITS(op, (&key), (&val)))
355 					putpair((char *)op, &key, &val);
356 				else {
357 					old_bufp =
358 					    __add_ovflpage(hashp, old_bufp);
359 					if (!old_bufp)
360 						return (-1);
361 					op = (__uint16_t *)old_bufp->page;
362 					putpair((char *)op, &key, &val);
363 				}
364 				old_bufp->flags |= BUF_MOD;
365 			} else {
366 				/* Move to new page */
367 				if (PAIRFITS(np, (&key), (&val)))
368 					putpair((char *)np, &key, &val);
369 				else {
370 					new_bufp =
371 					    __add_ovflpage(hashp, new_bufp);
372 					if (!new_bufp)
373 						return (-1);
374 					np = (__uint16_t *)new_bufp->page;
375 					putpair((char *)np, &key, &val);
376 				}
377 				new_bufp->flags |= BUF_MOD;
378 			}
379 		}
380 	}
381 	if (last_bfp)
382 		__free_ovflpage(hashp, last_bfp);
383 	return (0);
384 }
385 
386 /*
387  * Add the given pair to the page
388  *
389  * Returns:
390  *	0 ==> OK
391  *	1 ==> failure
392  */
393 extern int
__addel(HTAB * hashp,BUFHEAD * bufp,const DBT * key,const DBT * val)394 __addel(HTAB *hashp,
395 	BUFHEAD *bufp,
396 	const DBT *key,
397         const DBT *val)
398 {
399 	__uint16_t *bp, *sop;
400 	int do_expand;
401 
402 	bp = (__uint16_t *)bufp->page;
403 	do_expand = 0;
404 	while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY))
405 		/* Exception case */
406 		if (bp[2] == FULL_KEY_DATA && bp[0] == 2)
407 			/* This is the last page of a big key/data pair
408 			   and we need to add another page */
409 			break;
410 		else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) {
411 			bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
412 			if (!bufp)
413 				return (-1);
414 			bp = (__uint16_t *)bufp->page;
415 		} else
416 			/* Try to squeeze key on this page */
417 			if (FREESPACE(bp) > PAIRSIZE(key, val)) {
418 				squeeze_key(bp, key, val);
419 				return (0);
420 			} else {
421 				bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
422 				if (!bufp)
423 					return (-1);
424 				bp = (__uint16_t *)bufp->page;
425 			}
426 
427 	if (PAIRFITS(bp, key, val))
428 		putpair(bufp->page, key, val);
429 	else {
430 		do_expand = 1;
431 		bufp = __add_ovflpage(hashp, bufp);
432 		if (!bufp)
433 			return (-1);
434 		sop = (__uint16_t *)bufp->page;
435 
436 		if (PAIRFITS(sop, key, val))
437 			putpair((char *)sop, key, val);
438 		else
439 			if (__big_insert(hashp, bufp, key, val))
440 				return (-1);
441 	}
442 	bufp->flags |= BUF_MOD;
443 	/*
444 	 * If the average number of keys per bucket exceeds the fill factor,
445 	 * expand the table.
446 	 */
447 	hashp->NKEYS++;
448 	if (do_expand ||
449 	    (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR))
450 		return (__expand_table(hashp));
451 	return (0);
452 }
453 
454 /*
455  *
456  * Returns:
457  *	pointer on success
458  *	NULL on error
459  */
460 extern BUFHEAD *
__add_ovflpage(HTAB * hashp,BUFHEAD * bufp)461 __add_ovflpage(HTAB *hashp, BUFHEAD *bufp)
462 {
463 	__uint16_t *sp;
464 	__uint16_t ndx, ovfl_num;
465 #ifdef DEBUG1
466 	int tmp1, tmp2;
467 #endif
468 	sp = (__uint16_t *)bufp->page;
469 
470 	/* Check if we are dynamically determining the fill factor */
471 	if (hashp->FFACTOR == DEF_FFACTOR) {
472 		hashp->FFACTOR = sp[0] >> 1;
473 		if (hashp->FFACTOR < MIN_FFACTOR)
474 			hashp->FFACTOR = MIN_FFACTOR;
475 	}
476 	bufp->flags |= BUF_MOD;
477 	ovfl_num = overflow_page(hashp);
478 #ifdef DEBUG1
479 	tmp1 = bufp->addr;
480 	tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0;
481 #endif
482 	if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1)))
483 		return (NULL);
484 	bufp->ovfl->flags |= BUF_MOD;
485 #ifdef DEBUG1
486 	(void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n",
487 	    tmp1, tmp2, bufp->ovfl->addr);
488 #endif
489 	ndx = sp[0];
490 	/*
491 	 * Since a pair is allocated on a page only if there's room to add
492 	 * an overflow page, we know that the OVFL information will fit on
493 	 * the page.
494 	 */
495 	sp[ndx + 4] = OFFSET(sp);
496 	sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE;
497 	sp[ndx + 1] = ovfl_num;
498 	sp[ndx + 2] = OVFLPAGE;
499 	sp[0] = ndx + 2;
500 #ifdef HASH_STATISTICS
501 	hash_overflows++;
502 #endif
503 	return (bufp->ovfl);
504 }
505 
506 /*
507  * Returns:
508  *	 0 indicates SUCCESS
509  *	-1 indicates FAILURE
510  */
511 extern int
__get_page(HTAB * hashp,char * p,__uint32_t bucket,int is_bucket,int is_disk,int is_bitmap)512 __get_page(HTAB *hashp,
513            char *p,
514            __uint32_t bucket,
515            int is_bucket,
516            int is_disk,
517            int is_bitmap)
518 {
519 	int fd, page, size;
520 	int rsize;
521 	__uint16_t *bp;
522 
523 	fd = hashp->fp;
524 	size = hashp->BSIZE;
525 
526 	if ((fd == -1) || !is_disk) {
527 		PAGE_INIT(p);
528 		return (0);
529 	}
530 	if (is_bucket)
531 		page = BUCKET_TO_PAGE(bucket);
532 	else
533 		page = OADDR_TO_PAGE(bucket);
534 	if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
535 	    ((rsize = read(fd, p, size)) == -1))
536 		return (-1);
537 	bp = (__uint16_t *)p;
538 	if (!rsize)
539 		bp[0] = 0;	/* We hit the EOF, so initialize a new page */
540 	else
541 		if (rsize != size) {
542 			errno = EFTYPE;
543 			return (-1);
544 		}
545 	if (!is_bitmap && !bp[0]) {
546 		PAGE_INIT(p);
547 	} else
548                if (hashp->LORDER != DB_BYTE_ORDER) {
549 			int i, max;
550 
551 			if (is_bitmap) {
552 				max = hashp->BSIZE >> 2; /* divide by 4 */
553 				for (i = 0; i < max; i++)
554 					M_32_SWAP(((int *)p)[i]);
555 			} else {
556 				M_16_SWAP(bp[0]);
557 				max = bp[0] + 2;
558 				for (i = 1; i <= max; i++)
559 					M_16_SWAP(bp[i]);
560 			}
561 		}
562 	return (0);
563 }
564 
565 /*
566  * Write page p to disk
567  *
568  * Returns:
569  *	 0 ==> OK
570  *	-1 ==>failure
571  */
572 extern int
__put_page(HTAB * hashp,char * p,__uint32_t bucket,int is_bucket,int is_bitmap)573 __put_page(HTAB *hashp,
574            char *p,
575            __uint32_t bucket,
576            int is_bucket,
577            int is_bitmap)
578 {
579 	int fd, page, size;
580 	int wsize;
581 
582 	size = hashp->BSIZE;
583 	if ((hashp->fp == -1) && open_temp(hashp))
584 		return (-1);
585 	fd = hashp->fp;
586 
587        if (hashp->LORDER != DB_BYTE_ORDER) {
588 		int i;
589 		int max;
590 
591 		if (is_bitmap) {
592 			max = hashp->BSIZE >> 2;	/* divide by 4 */
593 			for (i = 0; i < max; i++)
594 				M_32_SWAP(((int *)p)[i]);
595 		} else {
596 			max = ((__uint16_t *)p)[0] + 2;
597 			for (i = 0; i <= max; i++)
598 				M_16_SWAP(((__uint16_t *)p)[i]);
599 		}
600 	}
601 	if (is_bucket)
602 		page = BUCKET_TO_PAGE(bucket);
603 	else
604 		page = OADDR_TO_PAGE(bucket);
605 	if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
606 	    ((wsize = write(fd, p, size)) == -1))
607 		/* Errno is set */
608 		return (-1);
609 	if (wsize != size) {
610 		errno = EFTYPE;
611 		return (-1);
612 	}
613 	return (0);
614 }
615 
616 #define BYTE_MASK	((1 << INT_BYTE_SHIFT) -1)
617 /*
618  * Initialize a new bitmap page.  Bitmap pages are left in memory
619  * once they are read in.
620  */
621 extern int
__ibitmap(HTAB * hashp,int pnum,int nbits,int ndx)622 __ibitmap(HTAB *hashp,
623           int pnum,
624           int nbits,
625           int ndx)
626 {
627 	__uint32_t *ip;
628 	int clearbytes, clearints;
629 
630 	if ((ip = (__uint32_t *)malloc(hashp->BSIZE)) == NULL)
631 		return (1);
632 	hashp->nmaps++;
633 	clearints = ((nbits - 1) >> INT_BYTE_SHIFT) + 1;
634 	clearbytes = clearints << INT_TO_BYTE;
635 	(void)memset((char *)ip, 0, clearbytes);
636 	(void)memset(((char *)ip) + clearbytes, 0xFF,
637 	    hashp->BSIZE - clearbytes);
638 	ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK);
639 	SETBIT(ip, 0);
640 	hashp->BITMAPS[ndx] = (__uint16_t)pnum;
641 	hashp->mapp[ndx] = ip;
642 	return (0);
643 }
644 
645 static __uint32_t
first_free(__uint32_t map)646 first_free(__uint32_t map)
647 {
648 	__uint32_t i, mask;
649 
650 	mask = 0x1;
651 	for (i = 0; i < BITS_PER_MAP; i++) {
652 		if (!(mask & map))
653 			return (i);
654 		mask = mask << 1;
655 	}
656 	return (i);
657 }
658 
659 static __uint16_t
overflow_page(HTAB * hashp)660 overflow_page(HTAB *hashp)
661 {
662 	__uint32_t *freep = NULL;
663 	int max_free, offset, splitnum;
664 	__uint16_t addr;
665 	int bit, first_page, free_bit, free_page, i, in_use_bits, j;
666 #ifdef DEBUG2
667 	int tmp1, tmp2;
668 #endif
669 	splitnum = hashp->OVFL_POINT;
670 	max_free = hashp->SPARES[splitnum];
671 
672 	free_page = (max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT);
673 	free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1);
674 
675 	/* Look through all the free maps to find the first free block */
676 	first_page = hashp->LAST_FREED >>(hashp->BSHIFT + BYTE_SHIFT);
677 	for ( i = first_page; i <= free_page; i++ ) {
678 		if (!(freep = (__uint32_t *)hashp->mapp[i]) &&
679 		    !(freep = fetch_bitmap(hashp, i)))
680 			return (0);
681 		if (i == free_page)
682 			in_use_bits = free_bit;
683 		else
684 			in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1;
685 
686 		if (i == first_page) {
687 			bit = hashp->LAST_FREED &
688 			    ((hashp->BSIZE << BYTE_SHIFT) - 1);
689 			j = bit / BITS_PER_MAP;
690 			bit = bit & ~(BITS_PER_MAP - 1);
691 		} else {
692 			bit = 0;
693 			j = 0;
694 		}
695 		for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP)
696 			if (freep[j] != ALL_SET)
697 				goto found;
698 	}
699 
700 	/* No Free Page Found */
701 	hashp->LAST_FREED = hashp->SPARES[splitnum];
702 	hashp->SPARES[splitnum]++;
703 	offset = hashp->SPARES[splitnum] -
704 	    (splitnum ? hashp->SPARES[splitnum - 1] : 0);
705 
706 #define	OVMSG	"HASH: Out of overflow pages.  Increase page size\n"
707 	if (offset > SPLITMASK) {
708 		if (++splitnum >= NCACHED) {
709 			(void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
710 			return (0);
711 		}
712 		hashp->OVFL_POINT = splitnum;
713 		hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
714 		hashp->SPARES[splitnum-1]--;
715 		offset = 1;
716 	}
717 
718 	/* Check if we need to allocate a new bitmap page */
719 	if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) {
720 		free_page++;
721 		if (free_page >= NCACHED) {
722 			(void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
723 			return (0);
724 		}
725 		/*
726 		 * This is tricky.  The 1 indicates that you want the new page
727 		 * allocated with 1 clear bit.  Actually, you are going to
728 		 * allocate 2 pages from this map.  The first is going to be
729 		 * the map page, the second is the overflow page we were
730 		 * looking for.  The init_bitmap routine automatically, sets
731 		 * the first bit of itself to indicate that the bitmap itself
732 		 * is in use.  We would explicitly set the second bit, but
733 		 * don't have to if we tell init_bitmap not to leave it clear
734 		 * in the first place.
735 		 */
736 		if (__ibitmap(hashp,
737 		    (int)OADDR_OF(splitnum, offset), 1, free_page))
738 			return (0);
739 		hashp->SPARES[splitnum]++;
740 #ifdef DEBUG2
741 		free_bit = 2;
742 #endif
743 		offset++;
744 		if (offset > SPLITMASK) {
745 			if (++splitnum >= NCACHED) {
746 				(void)write(STDERR_FILENO, OVMSG,
747 				    sizeof(OVMSG) - 1);
748 				return (0);
749 			}
750 			hashp->OVFL_POINT = splitnum;
751 			hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
752 			hashp->SPARES[splitnum-1]--;
753 			offset = 0;
754 		}
755 	} else {
756 		/*
757 		 * Free_bit addresses the last used bit.  Bump it to address
758 		 * the first available bit.
759 		 */
760 		free_bit++;
761 		SETBIT(freep, free_bit);
762 	}
763 
764 	/* Calculate address of the new overflow page */
765 	addr = OADDR_OF(splitnum, offset);
766 #ifdef DEBUG2
767 	(void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
768 	    addr, free_bit, free_page);
769 #endif
770 	return (addr);
771 
772 found:
773 	bit = bit + first_free(freep[j]);
774 	SETBIT(freep, bit);
775 #ifdef DEBUG2
776 	tmp1 = bit;
777 	tmp2 = i;
778 #endif
779 	/*
780 	 * Bits are addressed starting with 0, but overflow pages are addressed
781 	 * beginning at 1. Bit is a bit addressnumber, so we need to increment
782 	 * it to convert it to a page number.
783 	 */
784 	bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT));
785 	if (bit >= hashp->LAST_FREED)
786 		hashp->LAST_FREED = bit - 1;
787 
788 	/* Calculate the split number for this page */
789 	for (i = 0; (i < splitnum) && (bit > hashp->SPARES[i]); i++);
790 	offset = (i ? bit - hashp->SPARES[i - 1] : bit);
791 	if (offset >= SPLITMASK)
792 		return (0);	/* Out of overflow pages */
793 	addr = OADDR_OF(i, offset);
794 #ifdef DEBUG2
795 	(void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
796 	    addr, tmp1, tmp2);
797 #endif
798 
799 	/* Allocate and return the overflow page */
800 	return (addr);
801 }
802 
803 /*
804  * Mark this overflow page as free.
805  */
806 extern void
__free_ovflpage(HTAB * hashp,BUFHEAD * obufp)807 __free_ovflpage(HTAB *hashp, BUFHEAD *obufp)
808 {
809 	__uint16_t addr;
810 	__uint32_t *freep;
811 	int bit_address, free_page, free_bit;
812 	__uint16_t ndx;
813 
814 	addr = obufp->addr;
815 #ifdef DEBUG1
816 	(void)fprintf(stderr, "Freeing %d\n", addr);
817 #endif
818 	ndx = (((__uint16_t)addr) >> SPLITSHIFT);
819 	bit_address =
820 	    (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1;
821 	 if (bit_address < hashp->LAST_FREED)
822 		hashp->LAST_FREED = bit_address;
823 	free_page = (bit_address >> (hashp->BSHIFT + BYTE_SHIFT));
824 	free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1);
825 
826 	if (!(freep = hashp->mapp[free_page]))
827 		freep = fetch_bitmap(hashp, free_page);
828 #ifdef DEBUG
829 	/*
830 	 * This had better never happen.  It means we tried to read a bitmap
831 	 * that has already had overflow pages allocated off it, and we
832 	 * failed to read it from the file.
833 	 */
834 	if (!freep)
835 		assert(0);
836 #endif
837 	CLRBIT(freep, free_bit);
838 #ifdef DEBUG2
839 	(void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n",
840 	    obufp->addr, free_bit, free_page);
841 #endif
842 	__reclaim_buf(hashp, obufp);
843 }
844 
845 /*
846  * Returns:
847  *	 0 success
848  *	-1 failure
849  */
850 static int
open_temp(HTAB * hashp)851 open_temp(HTAB *hashp)
852 {
853 	sigset_t set, oset;
854 	static char namestr[] = "_hashXXXXXX";
855 
856 	/* Block signals; make sure file goes away at process exit. */
857 	(void)sigfillset(&set);
858 	(void)sigprocmask(SIG_BLOCK, &set, &oset);
859 	if ((hashp->fp = mkstemp(namestr)) != -1) {
860 		(void)unlink(namestr);
861 #ifdef _HAVE_FCNTL
862 		(void)fcntl(hashp->fp, F_SETFD, 1);
863 #endif
864 	}
865 	(void)sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
866 	return (hashp->fp != -1 ? 0 : -1);
867 }
868 
869 /*
870  * We have to know that the key will fit, but the last entry on the page is
871  * an overflow pair, so we need to shift things.
872  */
873 static void
squeeze_key(__uint16_t * sp,const DBT * key,const DBT * val)874 squeeze_key(__uint16_t *sp,
875             const DBT *key,
876             const DBT *val)
877 {
878 	char *p;
879 	__uint16_t free_space, n, off, pageno;
880 
881 	p = (char *)sp;
882 	n = sp[0];
883 	free_space = FREESPACE(sp);
884 	off = OFFSET(sp);
885 
886 	pageno = sp[n - 1];
887 	off -= key->size;
888 	sp[n - 1] = off;
889 	memmove(p + off, key->data, key->size);
890 	off -= val->size;
891 	sp[n] = off;
892 	memmove(p + off, val->data, val->size);
893 	sp[0] = n + 2;
894 	sp[n + 1] = pageno;
895 	sp[n + 2] = OVFLPAGE;
896 	FREESPACE(sp) = free_space - PAIRSIZE(key, val);
897 	OFFSET(sp) = off;
898 }
899 
900 static __uint32_t *
fetch_bitmap(HTAB * hashp,int ndx)901 fetch_bitmap(HTAB *hashp, int ndx)
902 {
903 	if (ndx >= hashp->nmaps)
904 		return (NULL);
905 	if ((hashp->mapp[ndx] = (__uint32_t *)malloc(hashp->BSIZE)) == NULL)
906 		return (NULL);
907 	if (__get_page(hashp,
908 	    (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) {
909 		free(hashp->mapp[ndx]);
910 		return (NULL);
911 	}
912 	return (hashp->mapp[ndx]);
913 }
914 
915 #ifdef DEBUG4
916 int
print_chain(addr)917 print_chain(addr)
918 	int addr;
919 {
920 	BUFHEAD *bufp;
921 	short *bp, oaddr;
922 
923 	(void)fprintf(stderr, "%d ", addr);
924 	bufp = __get_buf(hashp, addr, NULL, 0);
925 	bp = (short *)bufp->page;
926 	while (bp[0] && ((bp[bp[0]] == OVFLPAGE) ||
927 		((bp[0] > 2) && bp[2] < REAL_KEY))) {
928 		oaddr = bp[bp[0] - 1];
929 		(void)fprintf(stderr, "%d ", (int)oaddr);
930 		bufp = __get_buf(hashp, (int)oaddr, bufp, 0);
931 		bp = (short *)bufp->page;
932 	}
933 	(void)fprintf(stderr, "\n");
934 }
935 #endif
936