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