xref: /freebsd/lib/libc/db/hash/hash_buf.c (revision 8a7df6c58d549bd2eaa5cad30b2ef93c3eca3c18)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1990, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Margo Seltzer.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * PACKAGE: hash
37  *
38  * DESCRIPTION:
39  *	Contains buffer management
40  *
41  * ROUTINES:
42  * External
43  *	__buf_init
44  *	__get_buf
45  *	__buf_free
46  *	__reclaim_buf
47  * Internal
48  *	newbuf
49  */
50 
51 #include <sys/param.h>
52 
53 #include <stddef.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 
58 #ifdef DEBUG
59 #include <assert.h>
60 #endif
61 
62 #include <db.h>
63 #include "hash.h"
64 #include "page.h"
65 #include "extern.h"
66 
67 static BUFHEAD *newbuf(HTAB *, u_int32_t, BUFHEAD *);
68 
69 /* Unlink B from its place in the lru */
70 #define BUF_REMOVE(B) { \
71 	(B)->prev->next = (B)->next; \
72 	(B)->next->prev = (B)->prev; \
73 }
74 
75 /* Insert B after P */
76 #define BUF_INSERT(B, P) { \
77 	(B)->next = (P)->next; \
78 	(B)->prev = (P); \
79 	(P)->next = (B); \
80 	(B)->next->prev = (B); \
81 }
82 
83 #define	MRU	hashp->bufhead.next
84 #define	LRU	hashp->bufhead.prev
85 
86 #define MRU_INSERT(B)	BUF_INSERT((B), &hashp->bufhead)
87 #define LRU_INSERT(B)	BUF_INSERT((B), LRU)
88 
89 /*
90  * We are looking for a buffer with address "addr".  If prev_bp is NULL, then
91  * address is a bucket index.  If prev_bp is not NULL, then it points to the
92  * page previous to an overflow page that we are trying to find.
93  *
94  * CAVEAT:  The buffer header accessed via prev_bp's ovfl field may no longer
95  * be valid.  Therefore, you must always verify that its address matches the
96  * address you are seeking.
97  */
98 BUFHEAD *
99 __get_buf(HTAB *hashp, u_int32_t addr,
100     BUFHEAD *prev_bp,	/* If prev_bp set, indicates a new overflow page. */
101     int newpage)
102 {
103 	int is_disk, segment_ndx, dir_ndx;
104 	u_int32_t is_disk_mask;
105 	SEGMENT segp;
106 	BUFHEAD *bp;
107 
108 	is_disk = 0;
109 	is_disk_mask = 0;
110 	if (prev_bp) {
111 		bp = prev_bp->ovfl;
112 		if (!bp || (bp->addr != addr))
113 			bp = NULL;
114 		if (!newpage)
115 			is_disk = BUF_DISK;
116 	} else {
117 		/* Grab buffer out of directory */
118 		segment_ndx = addr & (hashp->SGSIZE - 1);
119 		dir_ndx = addr >> hashp->SSHIFT;
120 		if (dir_ndx >= hashp->nsegs) {
121 			/*
122 			 * A bucket address could theoretically have been
123 			 * generated using maliciously crafted header values
124 			 * aimed at __call_hash.
125 			 */
126 			return (NULL);
127 		}
128 		/* valid segment ensured by __call_hash() */
129 		segp = hashp->dir[dir_ndx];
130 #ifdef DEBUG
131 		assert(segp != NULL);
132 #endif
133 		bp = PTROF(segp[segment_ndx]);
134 		is_disk_mask = ISDISK(segp[segment_ndx]);
135 		is_disk = is_disk_mask || !hashp->new_file;
136 	}
137 
138 	if (!bp) {
139 		bp = newbuf(hashp, addr, prev_bp);
140 		if (!bp ||
141 		    __get_page(hashp, bp->page, addr, !prev_bp, is_disk, 0))
142 			return (NULL);
143 		if (!prev_bp)
144 			segp[segment_ndx] =
145 			    (BUFHEAD *)((intptr_t)bp | is_disk_mask);
146 	} else {
147 		BUF_REMOVE(bp);
148 		MRU_INSERT(bp);
149 	}
150 	return (bp);
151 }
152 
153 /*
154  * We need a buffer for this page. Either allocate one, or evict a resident
155  * one (if we have as many buffers as we're allowed) and put this one in.
156  *
157  * If newbuf finds an error (returning NULL), it also sets errno.
158  */
159 static BUFHEAD *
160 newbuf(HTAB *hashp, u_int32_t addr, BUFHEAD *prev_bp)
161 {
162 	BUFHEAD *bp;		/* The buffer we're going to use */
163 	BUFHEAD *xbp;		/* Temp pointer */
164 	BUFHEAD *next_xbp;
165 	SEGMENT segp;
166 	int segment_ndx;
167 	u_int16_t oaddr, *shortp;
168 
169 	oaddr = 0;
170 	bp = LRU;
171 
172         /* It is bad to overwrite the page under the cursor. */
173         if (bp == hashp->cpage) {
174                 BUF_REMOVE(bp);
175                 MRU_INSERT(bp);
176                 bp = LRU;
177         }
178 
179 	/* If prev_bp is part of bp overflow, create a new buffer. */
180 	if (hashp->nbufs == 0 && prev_bp && bp->ovfl) {
181 		BUFHEAD *ovfl;
182 
183 		for (ovfl = bp->ovfl; ovfl ; ovfl = ovfl->ovfl) {
184 			if (ovfl == prev_bp) {
185 				hashp->nbufs++;
186 				break;
187 			}
188 		}
189 	}
190 
191 	/*
192 	 * If LRU buffer is pinned, the buffer pool is too small. We need to
193 	 * allocate more buffers.
194 	 */
195 	if (hashp->nbufs || (bp->flags & BUF_PIN) || bp == hashp->cpage) {
196 		/* Allocate a new one */
197 		if ((bp = (BUFHEAD *)calloc(1, sizeof(BUFHEAD))) == NULL)
198 			return (NULL);
199 		if ((bp->page = (char *)calloc(1, hashp->BSIZE)) == NULL) {
200 			free(bp);
201 			return (NULL);
202 		}
203 		if (hashp->nbufs)
204 			hashp->nbufs--;
205 	} else {
206 		/* Kick someone out */
207 		BUF_REMOVE(bp);
208 		/*
209 		 * If this is an overflow page with addr 0, it's already been
210 		 * flushed back in an overflow chain and initialized.
211 		 */
212 		if ((bp->addr != 0) || (bp->flags & BUF_BUCKET)) {
213 			/*
214 			 * Set oaddr before __put_page so that you get it
215 			 * before bytes are swapped.
216 			 */
217 			shortp = (u_int16_t *)bp->page;
218 			if (shortp[0])
219 				oaddr = shortp[shortp[0] - 1];
220 			if ((bp->flags & BUF_MOD) && __put_page(hashp, bp->page,
221 			    bp->addr, (int)IS_BUCKET(bp->flags), 0))
222 				return (NULL);
223 			/*
224 			 * Update the pointer to this page (i.e. invalidate it).
225 			 *
226 			 * If this is a new file (i.e. we created it at open
227 			 * time), make sure that we mark pages which have been
228 			 * written to disk so we retrieve them from disk later,
229 			 * rather than allocating new pages.
230 			 */
231 			if (IS_BUCKET(bp->flags)) {
232 				segment_ndx = bp->addr & (hashp->SGSIZE - 1);
233 				segp = hashp->dir[bp->addr >> hashp->SSHIFT];
234 #ifdef DEBUG
235 				assert(segp != NULL);
236 #endif
237 
238 				if (hashp->new_file &&
239 				    ((bp->flags & BUF_MOD) ||
240 				    ISDISK(segp[segment_ndx])))
241 					segp[segment_ndx] = (BUFHEAD *)BUF_DISK;
242 				else
243 					segp[segment_ndx] = NULL;
244 			}
245 			/*
246 			 * Since overflow pages can only be access by means of
247 			 * their bucket, free overflow pages associated with
248 			 * this bucket.
249 			 */
250 			for (xbp = bp; xbp->ovfl;) {
251 				next_xbp = xbp->ovfl;
252 				xbp->ovfl = NULL;
253 				xbp = next_xbp;
254 
255 				/* Check that ovfl pointer is up date. */
256 				if (IS_BUCKET(xbp->flags) ||
257 				    (oaddr != xbp->addr))
258 					break;
259 
260 				shortp = (u_int16_t *)xbp->page;
261 				if (shortp[0])
262 					/* set before __put_page */
263 					oaddr = shortp[shortp[0] - 1];
264 				if ((xbp->flags & BUF_MOD) && __put_page(hashp,
265 				    xbp->page, xbp->addr, 0, 0))
266 					return (NULL);
267 				xbp->addr = 0;
268 				xbp->flags = 0;
269 				BUF_REMOVE(xbp);
270 				LRU_INSERT(xbp);
271 			}
272 		}
273 	}
274 
275 	/* Now assign this buffer */
276 	bp->addr = addr;
277 #ifdef DEBUG1
278 	(void)fprintf(stderr, "NEWBUF1: %d->ovfl was %d is now %d\n",
279 	    bp->addr, (bp->ovfl ? bp->ovfl->addr : 0), 0);
280 #endif
281 	bp->ovfl = NULL;
282 	if (prev_bp) {
283 		/*
284 		 * If prev_bp is set, this is an overflow page, hook it in to
285 		 * the buffer overflow links.
286 		 */
287 #ifdef DEBUG1
288 		(void)fprintf(stderr, "NEWBUF2: %d->ovfl was %d is now %d\n",
289 		    prev_bp->addr, (prev_bp->ovfl ? prev_bp->ovfl->addr : 0),
290 		    (bp ? bp->addr : 0));
291 #endif
292 		prev_bp->ovfl = bp;
293 		bp->flags = 0;
294 	} else
295 		bp->flags = BUF_BUCKET;
296 	MRU_INSERT(bp);
297 	return (bp);
298 }
299 
300 void
301 __buf_init(HTAB *hashp, int nbytes)
302 {
303 	BUFHEAD *bfp;
304 	int npages;
305 
306 	bfp = &(hashp->bufhead);
307 	npages = (nbytes + hashp->BSIZE - 1) >> hashp->BSHIFT;
308 	npages = MAX(npages, MIN_BUFFERS);
309 
310 	hashp->nbufs = npages;
311 	bfp->next = bfp;
312 	bfp->prev = bfp;
313 	/*
314 	 * This space is calloc'd so these are already null.
315 	 *
316 	 * bfp->ovfl = NULL;
317 	 * bfp->flags = 0;
318 	 * bfp->page = NULL;
319 	 * bfp->addr = 0;
320 	 */
321 }
322 
323 int
324 __buf_free(HTAB *hashp, int do_free, int to_disk)
325 {
326 	BUFHEAD *bp;
327 
328 	/* Need to make sure that buffer manager has been initialized */
329 	if (!LRU)
330 		return (0);
331 	for (bp = LRU; bp != &hashp->bufhead;) {
332 		/* Check that the buffer is valid */
333 		if (bp->addr || IS_BUCKET(bp->flags)) {
334 			if (to_disk && (bp->flags & BUF_MOD) &&
335 			    __put_page(hashp, bp->page,
336 			    bp->addr, IS_BUCKET(bp->flags), 0))
337 				return (-1);
338 		}
339 		/* Check if we are freeing stuff */
340 		if (do_free) {
341 			if (bp->page) {
342 				(void)memset(bp->page, 0, hashp->BSIZE);
343 				free(bp->page);
344 			}
345 			BUF_REMOVE(bp);
346 			free(bp);
347 			bp = LRU;
348 		} else
349 			bp = bp->prev;
350 	}
351 	return (0);
352 }
353 
354 void
355 __reclaim_buf(HTAB *hashp, BUFHEAD *bp)
356 {
357 	bp->ovfl = NULL;
358 	bp->addr = 0;
359 	bp->flags = 0;
360 	BUF_REMOVE(bp);
361 	LRU_INSERT(bp);
362 }
363