1 /*$Id$*/
2 /*-
3  * Copyright (c) 1990, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Margo Seltzer.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *	This product includes software developed by the University of
20  *	California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 
38 #if defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid[] = "@(#)hash.c	8.1 (Berkeley) 6/6/93";
40 #endif /* LIBC_SCCS and not lint */
41 
42 #include <sys/types.h>
43 #include <sys/param.h>
44 #include <sys/stat.h>
45 
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #ifndef IPSC
52 #include <unistd.h>
53 #endif
54 #ifdef DEBUG
55 #include <assert.h>
56 #endif
57 
58 #include <db.h>
59 #include "hash.h"
60 #include "page.h"
61 #include "extern.h"
62 
63 #if defined(NX)
64 extern int ipsc_open(const char *, int, int);
65 extern int ipsc_read(int, char *, int);
66 extern int ipsc_write(int, const char *, int);
67 extern int ipsc_lseek(int, off_t, int);
68 
69 #define open(a,b,c) ipsc_open(a,b,c)
70 #define read(a,b,c) ipsc_read(a,b,c)
71 #define write(a,b,c) ipsc_write(a,b,c)
72 #define lseek(a,b,c) ipsc_lseek(a,b,c)
73 #endif
74 
75 static int   alloc_segs __P((HTAB *, int));
76 static int   flush_meta __P((HTAB *));
77 static int   hash_access __P((HTAB *, ACTION, DBT *, DBT *));
78 static int   hash_close __P((DB *));
79 static int   hash_delete __P((const DB *, const DBT *, u_int));
80 static int   hash_fd __P((const DB *));
81 static int   hash_get __P((const DB *, const DBT *, DBT *, u_int));
82 static int   hash_put __P((const DB *, DBT *, const DBT *, u_int));
83 static void *hash_realloc __P((SEGMENT **, int, int));
84 static int   hash_seq __P((const DB *, DBT *, DBT *, u_int));
85 static int   hash_sync __P((const DB *, u_int));
86 static int   hdestroy __P((HTAB *));
87 static HTAB *init_hash __P((HTAB *, const char *, HASHINFO *));
88 static int   init_htab __P((HTAB *, int));
89 #if BYTE_ORDER == LITTLE_ENDIAN
90 static void  swap_header __P((HTAB *));
91 static void  swap_header_copy __P((HASHHDR *, HASHHDR *));
92 #endif
93 
94 /* Fast arithmetic, relying on powers of 2, */
95 #define MOD(x, y)		((x) & ((y) - 1))
96 
97 #define RETURN_ERROR(ERR, LOC)	{ save_errno = ERR; goto LOC; }
98 
99 /* Return values */
100 #define	SUCCESS	 (0)
101 #define	ERROR	(-1)
102 #define	ABNORMAL (1)
103 
104 #ifdef HASH_STATISTICS
105 long hash_accesses, hash_collisions, hash_expansions, hash_overflows;
106 #endif
107 
108 /************************** INTERFACE ROUTINES ***************************/
109 /* OPEN/CLOSE */
110 
111 extern DB *
112 __hash_open(file, flags, mode, info)
113 	const char *file;
114 	int flags, mode;
115 	const HASHINFO *info;	/* Special directives for create */
116 {
117 	HTAB *hashp;
118 	struct stat statbuf;
119 	DB *dbp;
120 	int bpages, new_table, nsegs, save_errno;
121 	long hdrsize;
122 
123 	if ((flags & O_ACCMODE) == O_WRONLY) {
124 		errno = EINVAL;
125 		return (NULL);
126 	}
127 
128 	if (!(hashp = (HTAB *) calloc(1, sizeof(HTAB))))
129 		return (NULL);
130 	hashp->fp = -1;
131 	/*
132 	 * Select flags relevant to us. Even if user wants write only, we need
133 	 * to be able to read the actual file, so we need to open it read/write.
134 	 * But, the field in the hashp structure needs to be accurate so that
135 	 * we can check accesses.
136 	 */
137 	hashp->flags = flags = flags & __USE_OPEN_FLAGS;
138 
139 	new_table = 0;
140 	if (!file || (flags & O_TRUNC) ||
141 	    (stat(file, &statbuf) && (errno == ENOENT))) {
142 		if (errno == ENOENT)
143 			errno = 0; /* Just in case someone looks at errno */
144 		new_table = 1;
145 	}
146 	if (file) {
147 		if ((hashp->fp = open(file, flags, mode)) == -1)
148 			RETURN_ERROR(errno, error0);
149 		(void)fcntl(hashp->fp, F_SETFD, 1);
150 	}
151 	if (new_table) {
152 		if (!(hashp = init_hash(hashp, file, (HASHINFO *)info)))
153 			RETURN_ERROR(errno, error1);
154 	} else {
155 		/* Table already exists */
156 		if (info && info->hash)
157 			hashp->hash = info->hash;
158 		else
159 			hashp->hash = __default_hash;
160 
161 		hdrsize = read(hashp->fp, (char *) &hashp->hdr, sizeof(HASHHDR));
162 #if BYTE_ORDER == LITTLE_ENDIAN
163 		swap_header(hashp);
164 #endif
165 		if (hdrsize == -1)
166 			RETURN_ERROR(errno, error1);
167 		if (hdrsize != sizeof(HASHHDR))
168 			RETURN_ERROR(EFTYPE, error1);
169 		/* Verify file type, versions and hash function */
170 		if (hashp->MAGIC != HASHMAGIC)
171 			RETURN_ERROR(EFTYPE, error1);
172 		if (hashp->VERSION != HASHVERSION)
173 			RETURN_ERROR(EFTYPE, error1);
174 		if (hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
175 			RETURN_ERROR(EFTYPE, error1);
176 		/*
177 		 * Figure out how many segments we need.  Max_Bucket is the
178 		 * maximum bucket number, so the number of buckets is
179 		 * max_bucket + 1.
180 		 */
181 		nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
182 			 hashp->SGSIZE;
183 		hashp->nsegs = 0;
184 		if (alloc_segs(hashp, nsegs))
185 			/*
186 			 * If alloc_segs fails, table will have been destroyed
187 			 * and errno will have been set.
188 			 */
189 			return (NULL);
190 		/* Read in bitmaps */
191 		bpages = (hashp->SPARES[hashp->OVFL_POINT] +
192 		    (hashp->HBSIZE << BYTE_SHIFT) - 1) >>
193 		    (hashp->HBSHIFT + BYTE_SHIFT);
194 
195 		hashp->nmaps = bpages;
196 		(void)memset(&hashp->mapp[0], 0, bpages * sizeof(u_long *));
197 	}
198 
199 	/* Initialize Buffer Manager */
200 	if (info && info->cachesize)
201 		__buf_init(hashp, info->cachesize);
202 	else
203 		__buf_init(hashp, DEF_BUFSIZE);
204 
205 	hashp->new_file = new_table;
206 	hashp->save_file = file && (hashp->flags & O_RDWR);
207 	hashp->cbucket = -1;
208 	if (!(dbp = (DB *) calloc(sizeof(DB), 1U))) {
209 		save_errno = errno;
210 		hdestroy(hashp);
211 		errno = save_errno;
212 		return (NULL);
213 	}
214 	dbp->internal = hashp;
215 	dbp->close = hash_close;
216 	dbp->del = hash_delete;
217 	dbp->fd = hash_fd;
218 	dbp->get = hash_get;
219 	dbp->put = hash_put;
220 	dbp->seq = hash_seq;
221 	dbp->sync = hash_sync;
222 	dbp->type = DB_HASH;
223 
224 #ifdef DEBUG
225 	(void)fprintf(stderr,
226 "%s\n%s%x\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%x\n%s%x\n%s%d\n%s%d\n",
227 	    "init_htab:",
228 	    "TABLE POINTER   ", hashp,
229 	    "BUCKET SIZE     ", hashp->HBSIZE,
230 	    "BUCKET SHIFT    ", hashp->HBSHIFT,
231 	    "DIRECTORY SIZE  ", hashp->DSIZE,
232 	    "SEGMENT SIZE    ", hashp->SGSIZE,
233 	    "SEGMENT SHIFT   ", hashp->SSHIFT,
234 	    "FILL FACTOR     ", hashp->FFACTOR,
235 	    "MAX BUCKET      ", hashp->MAX_BUCKET,
236 	    "OVFL POINT	     ", hashp->OVFL_POINT,
237 	    "LAST FREED      ", hashp->LAST_FREED,
238 	    "HIGH MASK       ", hashp->HIGH_MASK,
239 	    "LOW  MASK       ", hashp->LOW_MASK,
240 	    "NSEGS           ", hashp->nsegs,
241 	    "NKEYS           ", hashp->NKEYS);
242 #endif
243 #ifdef HASH_STATISTICS
244 	hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
245 #endif
246 	return (dbp);
247 
248 error1:
249 	if (hashp != NULL)
250 		(void)close(hashp->fp);
251 
252 error0:
253 	free(hashp);
254 	errno = save_errno;
255 	return (NULL);
256 }
257 
258 static int
hash_close(dbp)259 hash_close(dbp)
260 	DB *dbp;
261 {
262 	HTAB *hashp;
263 	int retval;
264 
265 	if (!dbp)
266 		return (ERROR);
267 
268 	hashp = (HTAB *)dbp->internal;
269 	retval = hdestroy(hashp);
270 	free(dbp);
271 	return (retval);
272 }
273 
274 static int
hash_fd(dbp)275 hash_fd(dbp)
276 	const DB *dbp;
277 {
278 	HTAB *hashp;
279 
280 	if (!dbp)
281 		return (ERROR);
282 
283 	hashp = (HTAB *)dbp->internal;
284 	if (hashp->fp == -1) {
285 		errno = ENOENT;
286 		return (-1);
287 	}
288 	return (hashp->fp);
289 }
290 
291 /************************** LOCAL CREATION ROUTINES **********************/
292 static HTAB *
init_hash(hashp,file,info)293 init_hash(hashp, file, info)
294 	HTAB *hashp;
295 	const char *file;
296 	HASHINFO *info;
297 {
298 	struct stat statbuf;
299 	int nelem;
300 
301 	nelem = 1;
302 	hashp->NKEYS = 0;
303 	hashp->LORDER = BYTE_ORDER;
304 	hashp->HBSIZE = DEF_BUCKET_SIZE;
305 	hashp->HBSHIFT = DEF_BUCKET_SHIFT;
306 	hashp->SGSIZE = DEF_SEGSIZE;
307 	hashp->SSHIFT = DEF_SEGSIZE_SHIFT;
308 	hashp->DSIZE = DEF_DIRSIZE;
309 	hashp->FFACTOR = DEF_FFACTOR;
310 	hashp->hash = __default_hash;
311 	memset(hashp->SPARES, 0, sizeof(hashp->SPARES));
312 	memset(hashp->BITMAPS, 0, sizeof (hashp->BITMAPS));
313 
314 	/* Fix bucket size to be optimal for file system */
315 	if (file != NULL) {
316 		if (stat(file, &statbuf))
317 			return (NULL);
318 #ifdef IPSC
319 		hashp->HBSIZE = 1024;
320 #else
321 		hashp->HBSIZE = (int) statbuf.st_blksize;
322 #endif
323 		hashp->HBSHIFT = __log2(hashp->HBSIZE);
324 	}
325 
326 	if (info) {
327 		if (info->bsize) {
328 			/* Round pagesize up to power of 2 */
329 			hashp->HBSHIFT = __log2(info->bsize);
330 			hashp->HBSIZE = 1 << hashp->HBSHIFT;
331 			if (hashp->HBSIZE > MAX_BSIZE) {
332 				errno = EINVAL;
333 				return (NULL);
334 			}
335 		}
336 		if (info->ffactor)
337 			hashp->FFACTOR = info->ffactor;
338 		if (info->hash)
339 			hashp->hash = info->hash;
340 		if (info->nelem)
341 			nelem = info->nelem;
342 		if (info->lorder) {
343 			if (info->lorder != BIG_ENDIAN &&
344 			    info->lorder != LITTLE_ENDIAN) {
345 				errno = EINVAL;
346 				return (NULL);
347 			}
348 			hashp->LORDER = info->lorder;
349 		}
350 	}
351 	/* init_htab should destroy the table and set errno if it fails */
352 	if (init_htab(hashp, nelem))
353 		return (NULL);
354 	else
355 		return (hashp);
356 }
357 /*
358  * This calls alloc_segs which may run out of memory.  Alloc_segs will destroy
359  * the table and set errno, so we just pass the error information along.
360  *
361  * Returns 0 on No Error
362  */
363 static int
init_htab(hashp,nelem)364 init_htab(hashp, nelem)
365 	HTAB *hashp;
366 	int nelem;
367 {
368 	register int nbuckets, nsegs;
369 	int l2;
370 
371 	/*
372 	 * Divide number of elements by the fill factor and determine a
373 	 * desired number of buckets.  Allocate space for the next greater
374 	 * power of two number of buckets.
375 	 */
376 	nelem = (nelem - 1) / hashp->FFACTOR + 1;
377 
378 	l2 = __log2(MAX(nelem, 2));
379 	nbuckets = 1 << l2;
380 
381 	hashp->SPARES[l2] = l2 + 1;
382 	hashp->SPARES[l2 + 1] = l2 + 1;
383 	hashp->OVFL_POINT = l2;
384 	hashp->LAST_FREED = 2;
385 
386 	/* First bitmap page is at: splitpoint l2 page offset 1 */
387 	if (__init_bitmap(hashp, OADDR_OF(l2, 1), l2 + 1, 0))
388 		return (-1);
389 
390 	hashp->MAX_BUCKET = hashp->LOW_MASK = nbuckets - 1;
391 	hashp->HIGH_MASK = (nbuckets << 1) - 1;
392 	hashp->HDRPAGES = (int) (((MAX(sizeof(HASHHDR), MINHDRSIZE) - 1) >>
393 	    hashp->HBSHIFT) + 1);
394 
395 	nsegs = (nbuckets - 1) / hashp->SGSIZE + 1;
396 	nsegs = 1 << __log2(nsegs);
397 
398 	if (nsegs > hashp->DSIZE)
399 		hashp->DSIZE = nsegs;
400 	return (alloc_segs(hashp, nsegs));
401 }
402 
403 /********************** DESTROY/CLOSE ROUTINES ************************/
404 
405 /*
406  * Flushes any changes to the file if necessary and destroys the hashp
407  * structure, freeing all allocated space.
408  */
409 static int
hdestroy(hashp)410 hdestroy(hashp)
411 	HTAB *hashp;
412 {
413 	int i, save_errno;
414 
415 	save_errno = 0;
416 
417 #ifdef HASH_STATISTICS
418 	(void)fprintf(stderr, "hdestroy: accesses %ld collisions %ld\n",
419 	    hash_accesses, hash_collisions);
420 	(void)fprintf(stderr, "hdestroy: expansions %ld\n",
421 	    hash_expansions);
422 	(void)fprintf(stderr, "hdestroy: overflows %ld\n",
423 	    hash_overflows);
424 	(void)fprintf(stderr, "keys %ld maxp %d segmentcount %d\n",
425 	    hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs);
426 
427 	for (i = 0; i < NCACHED; i++)
428 		(void)fprintf(stderr,
429 		    "spares[%d] = %d\n", i, hashp->SPARES[i]);
430 #endif
431 	/*
432 	 * Call on buffer manager to free buffers, and if required,
433 	 * write them to disk.
434 	 */
435 	if (__buf_free(hashp, 1, hashp->save_file))
436 		save_errno = errno;
437 	if (hashp->dir) {
438 		free(*hashp->dir);	/* Free initial segments */
439 		/* Free extra segments */
440 		while (hashp->exsegs--)
441 			free(hashp->dir[--hashp->nsegs]);
442 		free(hashp->dir);
443 	}
444 	if (flush_meta(hashp) && !save_errno)
445 		save_errno = errno;
446 	/* Free Bigmaps */
447 	for (i = 0; i < hashp->nmaps; i++)
448 		if (hashp->mapp[i])
449 			free(hashp->mapp[i]);
450 
451 	if (hashp->fp != -1)
452 		(void)close(hashp->fp);
453 
454 	if (save_errno) {
455 		errno = save_errno;
456 		return (ERROR);
457 	}
458 	return (SUCCESS);
459 }
460 /*
461  * Write modified pages to disk
462  *
463  * Returns:
464  *	 0 == OK
465  *	-1 ERROR
466  */
467 static int
hash_sync(dbp,flags)468 hash_sync(dbp, flags)
469 	const DB *dbp;
470 	u_int flags;
471 {
472 	HTAB *hashp;
473 
474 	if (flags != 0) {
475 		errno = EINVAL;
476 		return (ERROR);
477 	}
478 
479 	if (!dbp)
480 		return (ERROR);
481 
482 	hashp = (HTAB *)dbp->internal;
483 	if (!hashp->save_file)
484 		return (0);
485 	if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
486 		return (ERROR);
487 	hashp->new_file = 0;
488 	return (0);
489 }
490 
491 /*
492  * Returns:
493  *	 0 == OK
494  *	-1 indicates that errno should be set
495  */
496 static int
flush_meta(hashp)497 flush_meta(hashp)
498 	HTAB *hashp;
499 {
500 	HASHHDR *whdrp;
501 #if BYTE_ORDER == LITTLE_ENDIAN
502 	HASHHDR whdr;
503 #endif
504 	int fp, i;
505 	long wsize;
506 
507 	if (!hashp->save_file)
508 		return (0);
509 	hashp->MAGIC = HASHMAGIC;
510 	hashp->VERSION = HASHVERSION;
511 	hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY));
512 
513 	fp = hashp->fp;
514 	whdrp = &hashp->hdr;
515 #if BYTE_ORDER == LITTLE_ENDIAN
516 	whdrp = &whdr;
517 	swap_header_copy(&hashp->hdr, whdrp);
518 #endif
519 	if ((lseek(fp, (off_t)0, SEEK_SET) == -1) ||
520 	    ((wsize = write(fp, (char *) whdrp, sizeof(HASHHDR))) == -1))
521 		return (-1);
522 	else
523 		if (wsize != sizeof(HASHHDR)) {
524 			errno = EFTYPE;
525 			hashp->errnumb = errno;
526 			return (-1);
527 		}
528 	for (i = 0; i < NCACHED; i++)
529 		if (hashp->mapp[i])
530 			if (__put_page(hashp, (char *)hashp->mapp[i],
531 				hashp->BITMAPS[i], 0, 1))
532 				return (-1);
533 	return (0);
534 }
535 
536 /*******************************SEARCH ROUTINES *****************************/
537 /*
538  * All the access routines return
539  *
540  * Returns:
541  *	 0 on SUCCESS
542  *	 1 to indicate an external ERROR (i.e. key not found, etc)
543  *	-1 to indicate an internal ERROR (i.e. out of memory, etc)
544  */
545 static int
hash_get(dbp,key,data,flag)546 hash_get(dbp, key, data, flag)
547 	const DB *dbp;
548 	const DBT *key;
549 	DBT *data;
550 	u_int flag;
551 {
552 	HTAB *hashp;
553 
554 	hashp = (HTAB *)dbp->internal;
555 	if (flag) {
556 		hashp->errnumb = errno = EINVAL;
557 		return (ERROR);
558 	}
559 	return (hash_access(hashp, HASH_GET, (DBT *)key, data));
560 }
561 
562 static int
hash_put(dbp,key,data,flag)563 hash_put(dbp, key, data, flag)
564 	const DB *dbp;
565 	DBT *key;
566 	const DBT *data;
567 	u_int flag;
568 {
569 	HTAB *hashp;
570 
571 	hashp = (HTAB *)dbp->internal;
572 	if (flag && flag != R_NOOVERWRITE) {
573 		hashp->errnumb = errno = EINVAL;
574 		return (ERROR);
575 	}
576 	if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
577 		hashp->errnumb = errno = EPERM;
578 		return (ERROR);
579 	}
580 	return (hash_access(hashp, flag == R_NOOVERWRITE ?
581 	    HASH_PUTNEW : HASH_PUT, (DBT *)key, (DBT *)data));
582 }
583 
584 static int
hash_delete(dbp,key,flag)585 hash_delete(dbp, key, flag)
586 	const DB *dbp;
587 	const DBT *key;
588 	u_int flag;		/* Ignored */
589 {
590 	HTAB *hashp;
591 
592 	hashp = (HTAB *)dbp->internal;
593 	if (flag && flag != R_CURSOR) {
594 		hashp->errnumb = errno = EINVAL;
595 		return (ERROR);
596 	}
597 	if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
598 		hashp->errnumb = errno = EPERM;
599 		return (ERROR);
600 	}
601 	return (hash_access(hashp, HASH_DELETE, (DBT *)key, NULL));
602 }
603 
604 /*
605  * Assume that hashp has been set in wrapper routine.
606  */
607 static int
hash_access(hashp,action,key,val)608 hash_access(hashp, action, key, val)
609 	HTAB *hashp;
610 	ACTION action;
611 	DBT *key, *val;
612 {
613 	register BUFHEAD *rbufp;
614 	BUFHEAD *bufp, *save_bufp;
615 	register u_short *bp;
616 	register int n, ndx, off, size;
617 	register char *kp;
618 	u_short pageno;
619 
620 #ifdef HASH_STATISTICS
621 	hash_accesses++;
622 #endif
623 
624 	off = hashp->HBSIZE;
625 	size = (int) key->size;
626 	kp = (char *)key->data;
627 	rbufp = __get_buf(hashp, __call_hash(hashp, kp, size), NULL, 0);
628 	if (!rbufp) {
629 		return (ERROR);
630 	      }
631 	save_bufp = rbufp;
632 
633 	/* Pin the bucket chain */
634 	rbufp->flags |= BUF_PIN;
635 	for (bp = (u_short *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
636 		if (bp[1] >= REAL_KEY) {
637 			/* Real key/data pair */
638 			if (size == off - *bp &&
639 			    memcmp(kp, rbufp->page + *bp, size) == 0)
640 				goto found;
641 			off = bp[1];
642 #ifdef HASH_STATISTICS
643 			hash_collisions++;
644 #endif
645 			bp += 2;
646 			ndx += 2;
647 		} else if (bp[1] == OVFLPAGE) {
648 			rbufp = __get_buf(hashp, *bp, rbufp, 0);
649 			if (!rbufp) {
650 				save_bufp->flags &= ~BUF_PIN;
651 				return (ERROR);
652 			}
653 			/* FOR LOOP INIT */
654 			bp = (u_short *)rbufp->page;
655 			n = *bp++;
656 			ndx = 1;
657 			off = hashp->HBSIZE;
658 		} else if (bp[1] < REAL_KEY) {
659 			if ((ndx =
660 			    __find_bigpair(hashp, rbufp, ndx, kp, size)) > 0)
661 				goto found;
662 			if (ndx == -2) {
663 				bufp = rbufp;
664 				if (!(pageno =
665 				    __find_last_page(hashp, &bufp))) {
666 					ndx = 0;
667 					rbufp = bufp;
668 					break;	/* FOR */
669 				}
670 				rbufp = __get_buf(hashp, pageno, bufp, 0);
671 				if (!rbufp) {
672 					save_bufp->flags &= ~BUF_PIN;
673 					return (ERROR);
674 				}
675 				/* FOR LOOP INIT */
676 				bp = (u_short *)rbufp->page;
677 				n = *bp++;
678 				ndx = 1;
679 				off = hashp->HBSIZE;
680 			} else {
681 				save_bufp->flags &= ~BUF_PIN;
682 				return (ERROR);
683 			}
684 		}
685 
686 	/* Not found */
687 	switch (action) {
688 	case HASH_PUT:
689 	case HASH_PUTNEW:
690 		if (__addel(hashp, rbufp, key, val)) {
691 			save_bufp->flags &= ~BUF_PIN;
692 			return (ERROR);
693 		} else {
694 			save_bufp->flags &= ~BUF_PIN;
695 			return (SUCCESS);
696 		}
697 	case HASH_GET:
698 	case HASH_DELETE:
699 	default:
700 		save_bufp->flags &= ~BUF_PIN;
701 		return (ABNORMAL);
702 	}
703 
704 found:
705 	switch (action) {
706 	case HASH_PUTNEW:
707 		save_bufp->flags &= ~BUF_PIN;
708 		return (ABNORMAL);
709 	case HASH_GET:
710 		bp = (u_short *)rbufp->page;
711 		if (bp[ndx + 1] < REAL_KEY) {
712 			if (__big_return(hashp, rbufp, ndx, val, 0))
713 				return (ERROR);
714 		} else {
715 			val->data = (u_char *)rbufp->page + (int)bp[ndx + 1];
716 			val->size = bp[ndx] - bp[ndx + 1];
717 		}
718 		break;
719 	case HASH_PUT:
720 		if ((__delpair(hashp, rbufp, ndx)) ||
721 		    (__addel(hashp, rbufp, key, val))) {
722 			save_bufp->flags &= ~BUF_PIN;
723 			return (ERROR);
724 		}
725 		break;
726 	case HASH_DELETE:
727 		if (__delpair(hashp, rbufp, ndx))
728 			return (ERROR);
729 		break;
730 	default:
731 		abort();
732 	}
733 	save_bufp->flags &= ~BUF_PIN;
734 	return (SUCCESS);
735 }
736 
737 static int
hash_seq(dbp,key,data,flag)738 hash_seq(dbp, key, data, flag)
739 	const DB *dbp;
740 	DBT *key, *data;
741 	u_int flag;
742 {
743 	register u_int bucket;
744 	register BUFHEAD *bufp;
745 	HTAB *hashp;
746 	u_short *bp, ndx;
747 
748 	hashp = (HTAB *)dbp->internal;
749 	if (flag && flag != R_FIRST && flag != R_NEXT) {
750 		hashp->errnumb = errno = EINVAL;
751 		return (ERROR);
752 	}
753 #ifdef HASH_STATISTICS
754 	hash_accesses++;
755 #endif
756 	if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
757 		hashp->cbucket = 0;
758 		hashp->cndx = 1;
759 		hashp->cpage = NULL;
760 	}
761 
762 	for (bp = NULL; !bp || !bp[0]; ) {
763 		if (!(bufp = hashp->cpage)) {
764 			for (bucket = hashp->cbucket;
765 			    bucket <= hashp->MAX_BUCKET;
766 			    bucket++, hashp->cndx = 1) {
767 				bufp = __get_buf(hashp, bucket, NULL, 0);
768 				if (!bufp)
769 					return (ERROR);
770 				hashp->cpage = bufp;
771 				bp = (u_short *)bufp->page;
772 				if (bp[0]) {
773 					break;
774 				}
775 			}
776 			hashp->cbucket = bucket;
777 			if (hashp->cbucket > hashp->MAX_BUCKET) {
778 				hashp->cbucket = -1;
779 				return (ABNORMAL);
780 			}
781 		} else
782 			bp = (u_short *)hashp->cpage->page;
783 
784 #ifdef DEBUG
785 		assert(bp);
786 		assert(bufp);
787 #endif
788 		while (bp[hashp->cndx + 1] == OVFLPAGE) {
789 			bufp = hashp->cpage =
790 			    __get_buf(hashp, bp[hashp->cndx], bufp, 0);
791 			if (!bufp)
792 				return (ERROR);
793 			bp = (u_short *)(bufp->page);
794 			hashp->cndx = 1;
795 		}
796 		if (!bp[0]) {
797 			hashp->cpage = NULL;
798 			++hashp->cbucket;
799 		}
800 	}
801 	ndx = hashp->cndx;
802 	if (bp[ndx + 1] < REAL_KEY) {
803 		if (__big_keydata(hashp, bufp, key, data, 1))
804 			return (ERROR);
805 	} else {
806 		key->data = (u_char *)hashp->cpage->page + bp[ndx];
807 		key->size = (ndx > 1 ? bp[ndx - 1] : hashp->HBSIZE) - bp[ndx];
808 		data->data = (u_char *)hashp->cpage->page + bp[ndx + 1];
809 		data->size = bp[ndx] - bp[ndx + 1];
810 		ndx += 2;
811 		if (ndx > bp[0]) {
812 			hashp->cpage = NULL;
813 			hashp->cbucket++;
814 			hashp->cndx = 1;
815 		} else
816 			hashp->cndx = ndx;
817 	}
818 	return (SUCCESS);
819 }
820 
821 /********************************* UTILITIES ************************/
822 
823 /*
824  * Returns:
825  *	 0 ==> OK
826  *	-1 ==> Error
827  */
828 extern int
829 __expand_table(hashp)
830 	HTAB *hashp;
831 {
832 	u_int old_bucket, new_bucket;
833 	int dirsize, new_segnum, spare_ndx;
834 
835 #ifdef HASH_STATISTICS
836 	hash_expansions++;
837 #endif
838 	new_bucket = ++hashp->MAX_BUCKET;
839 	old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
840 
841 	new_segnum = new_bucket >> hashp->SSHIFT;
842 
843 	/* Check if we need a new segment */
844 	if (new_segnum >= hashp->nsegs) {
845 		/* Check if we need to expand directory */
846 		if (new_segnum >= hashp->DSIZE) {
847 			/* Reallocate directory */
848 			dirsize = (int) (hashp->DSIZE * sizeof(SEGMENT *));
849 			if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
850 				return (-1);
851 			hashp->DSIZE = dirsize << 1;
852 		}
853 		if (!(hashp->dir[new_segnum] =
854 			(SEGMENT) calloc(hashp->SGSIZE, sizeof(SEGMENT))))
855 			return (-1);
856 		hashp->exsegs++;
857 		hashp->nsegs++;
858 	}
859 	/*
860 	 * If the split point is increasing (MAX_BUCKET's log base 2
861 	 * * increases), we need to copy the current contents of the spare
862 	 * split bucket to the next bucket.
863 	 */
864 	spare_ndx = __log2(hashp->MAX_BUCKET + 1);
865 	if (spare_ndx > hashp->OVFL_POINT) {
866 		hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
867 		hashp->OVFL_POINT = spare_ndx;
868 	}
869 
870 	if (new_bucket > hashp->HIGH_MASK) {
871 		/* Starting a new doubling */
872 		hashp->LOW_MASK = hashp->HIGH_MASK;
873 		hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
874 	}
875 	/* Relocate records to the new bucket */
876 	return (__split_page(hashp, old_bucket, new_bucket));
877 }
878 
879 /*
880  * If realloc guarantees that the pointer is not destroyed if the realloc
881  * fails, then this routine can go away.
882  */
883 static void *
hash_realloc(p_ptr,oldsize,newsize)884 hash_realloc(p_ptr, oldsize, newsize)
885 	SEGMENT **p_ptr;
886 	int oldsize, newsize;
887 {
888 	register void *p;
889 
890 	if (p = calloc(newsize, 1U)) {
891 		memmove(p, *p_ptr, oldsize);
892 		memset((char *)p + oldsize, 0, newsize - oldsize);
893 		free(*p_ptr);
894 		*p_ptr = p;
895 	}
896 	return (p);
897 }
898 
899 extern u_int
900 __call_hash(hashp, k, len)
901 	HTAB *hashp;
902 	char *k;
903 	int len;
904 {
905 	int n, bucket;
906 
907 	n = hashp->hash((const u_char *) k, len);
908 	bucket = n & hashp->HIGH_MASK;
909 	if (bucket > hashp->MAX_BUCKET)
910 		bucket = bucket & hashp->LOW_MASK;
911 	return (bucket);
912 }
913 
914 /*
915  * Allocate segment table.  On error, destroy the table and set errno.
916  *
917  * Returns 0 on success
918  */
919 static int
alloc_segs(hashp,nsegs)920 alloc_segs(hashp, nsegs)
921 	HTAB *hashp;
922 	int nsegs;
923 {
924 	register int i;
925 	register SEGMENT store;
926 
927 	int save_errno;
928 
929 	if (!(hashp->dir = (SEGMENT *) calloc(hashp->DSIZE, sizeof(SEGMENT)))) {
930 		save_errno = errno;
931 		(void)hdestroy(hashp);
932 		errno = save_errno;
933 		return (-1);
934 	}
935 	/* Allocate segments */
936 	store = (SEGMENT) calloc(nsegs << hashp->SSHIFT, sizeof(SEGMENT));
937 	if (!store) {
938 		save_errno = errno;
939 		(void)hdestroy(hashp);
940 		errno = save_errno;
941 		return (-1);
942 	}
943 	for (i = 0; i < nsegs; i++, hashp->nsegs++)
944 		hashp->dir[i] = &store[i << hashp->SSHIFT];
945 	return (0);
946 }
947 
948 #if BYTE_ORDER == LITTLE_ENDIAN
949 /*
950  * Hashp->hdr needs to be byteswapped.
951  */
952 static void
swap_header_copy(srcp,destp)953 swap_header_copy(srcp, destp)
954 	HASHHDR *srcp, *destp;
955 {
956 	int i;
957 
958 	BLSWAP_COPY(srcp->magic, destp->magic);
959 	BLSWAP_COPY(srcp->version, destp->version);
960 	BLSWAP_COPY(srcp->lorder, destp->lorder);
961 	BLSWAP_COPY(srcp->bsize, destp->bsize);
962 	BLSWAP_COPY(srcp->bshift, destp->bshift);
963 	BLSWAP_COPY(srcp->dsize, destp->dsize);
964 	BLSWAP_COPY(srcp->ssize, destp->ssize);
965 	BLSWAP_COPY(srcp->sshift, destp->sshift);
966 	BLSWAP_COPY(srcp->ovfl_point, destp->ovfl_point);
967 	BLSWAP_COPY(srcp->last_freed, destp->last_freed);
968 	BLSWAP_COPY(srcp->max_bucket, destp->max_bucket);
969 	BLSWAP_COPY(srcp->high_mask, destp->high_mask);
970 	BLSWAP_COPY(srcp->low_mask, destp->low_mask);
971 	BLSWAP_COPY(srcp->ffactor, destp->ffactor);
972 	BLSWAP_COPY(srcp->nkeys, destp->nkeys);
973 	BLSWAP_COPY(srcp->hdrpages, destp->hdrpages);
974 	BLSWAP_COPY(srcp->h_charkey, destp->h_charkey);
975 	for (i = 0; i < NCACHED; i++) {
976 		BLSWAP_COPY(srcp->spares[i], destp->spares[i]);
977 		BSSWAP_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
978 	}
979 }
980 
981 static void
swap_header(hashp)982 swap_header(hashp)
983 	HTAB *hashp;
984 {
985 	HASHHDR *hdrp;
986 	int i;
987 
988 	hdrp = &hashp->hdr;
989 
990 	BLSWAP(hdrp->magic);
991 	BLSWAP(hdrp->version);
992 	BLSWAP(hdrp->lorder);
993 	BLSWAP(hdrp->bsize);
994 	BLSWAP(hdrp->bshift);
995 	BLSWAP(hdrp->dsize);
996 	BLSWAP(hdrp->ssize);
997 	BLSWAP(hdrp->sshift);
998 	BLSWAP(hdrp->ovfl_point);
999 	BLSWAP(hdrp->last_freed);
1000 	BLSWAP(hdrp->max_bucket);
1001 	BLSWAP(hdrp->high_mask);
1002 	BLSWAP(hdrp->low_mask);
1003 	BLSWAP(hdrp->ffactor);
1004 	BLSWAP(hdrp->nkeys);
1005 	BLSWAP(hdrp->hdrpages);
1006 	BLSWAP(hdrp->h_charkey);
1007 	for (i = 0; i < NCACHED; i++) {
1008 		BLSWAP(hdrp->spares[i]);
1009 		BSSWAP(hdrp->bitmaps[i]);
1010 	}
1011 }
1012 #endif
1013