xref: /netbsd-src/usr.sbin/makefs/ffs/ffs_alloc.c (revision 1ca5c1b28139779176bd5c13ad7c5f25c0bcd5f8)
1 /*	$NetBSD: ffs_alloc.c,v 1.7 2002/01/08 06:00:14 lukem Exp $	*/
2 /* From: NetBSD: ffs_alloc.c,v 1.50 2001/09/06 02:16:01 lukem Exp */
3 
4 /*
5  * Copyright (c) 1982, 1986, 1989, 1993
6  *	The Regents of the University of California.  All rights reserved.
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. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)ffs_alloc.c	8.19 (Berkeley) 7/13/95
37  */
38 
39 #include <sys/cdefs.h>
40 #ifndef __lint
41 __RCSID("$NetBSD: ffs_alloc.c,v 1.7 2002/01/08 06:00:14 lukem Exp $");
42 #endif	/* !__lint */
43 
44 #include <sys/param.h>
45 #include <sys/time.h>
46 
47 #include <err.h>
48 #include <errno.h>
49 
50 #include "makefs.h"
51 
52 #include <ufs/ufs/dinode.h>
53 #include <ufs/ufs/ufs_bswap.h>
54 #include <ufs/ffs/fs.h>
55 
56 #include "ffs/buf.h"
57 #include "ffs/ufs_inode.h"
58 #include "ffs/ffs_extern.h"
59 
60 
61 static int scanc(u_int, const u_char *, const u_char *, int);
62 
63 static ufs_daddr_t ffs_alloccg(struct inode *, int, ufs_daddr_t, int);
64 static ufs_daddr_t ffs_alloccgblk(struct inode *, struct buf *, ufs_daddr_t);
65 static u_long ffs_hashalloc(struct inode *, int, long, int,
66 		     ufs_daddr_t (*)(struct inode *, int, ufs_daddr_t, int));
67 static ufs_daddr_t ffs_mapsearch(struct fs *, struct cg *, ufs_daddr_t, int);
68 
69 /* in ffs_tables.c */
70 extern const int inside[], around[];
71 extern const u_char * const fragtbl[];
72 
73 /*
74  * Allocate a block in the file system.
75  *
76  * The size of the requested block is given, which must be some
77  * multiple of fs_fsize and <= fs_bsize.
78  * A preference may be optionally specified. If a preference is given
79  * the following hierarchy is used to allocate a block:
80  *   1) allocate the requested block.
81  *   2) allocate a rotationally optimal block in the same cylinder.
82  *   3) allocate a block in the same cylinder group.
83  *   4) quadradically rehash into other cylinder groups, until an
84  *      available block is located.
85  * If no block preference is given the following hierarchy is used
86  * to allocate a block:
87  *   1) allocate a block in the cylinder group that contains the
88  *      inode for the file.
89  *   2) quadradically rehash into other cylinder groups, until an
90  *      available block is located.
91  */
92 int
93 ffs_alloc(struct inode *ip, ufs_daddr_t lbn, ufs_daddr_t bpref, int size,
94     ufs_daddr_t *bnp)
95 {
96 	struct fs *fs = ip->i_fs;
97 	ufs_daddr_t bno;
98 	int cg;
99 
100 	*bnp = 0;
101 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
102 		errx(1, "ffs_alloc: bad size: bsize %d size %d",
103 		    fs->fs_bsize, size);
104 	}
105 	if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
106 		goto nospace;
107 	if (bpref >= fs->fs_size)
108 		bpref = 0;
109 	if (bpref == 0)
110 		cg = ino_to_cg(fs, ip->i_number);
111 	else
112 		cg = dtog(fs, bpref);
113 	bno = (ufs_daddr_t)ffs_hashalloc(ip, cg, (long)bpref, size,
114 	    			     ffs_alloccg);
115 	if (bno > 0) {
116 		ip->i_ffs_blocks += btodb(size);
117 		*bnp = bno;
118 		return (0);
119 	}
120 nospace:
121 	return (ENOSPC);
122 }
123 
124 /*
125  * Select the desired position for the next block in a file.  The file is
126  * logically divided into sections. The first section is composed of the
127  * direct blocks. Each additional section contains fs_maxbpg blocks.
128  *
129  * If no blocks have been allocated in the first section, the policy is to
130  * request a block in the same cylinder group as the inode that describes
131  * the file. If no blocks have been allocated in any other section, the
132  * policy is to place the section in a cylinder group with a greater than
133  * average number of free blocks.  An appropriate cylinder group is found
134  * by using a rotor that sweeps the cylinder groups. When a new group of
135  * blocks is needed, the sweep begins in the cylinder group following the
136  * cylinder group from which the previous allocation was made. The sweep
137  * continues until a cylinder group with greater than the average number
138  * of free blocks is found. If the allocation is for the first block in an
139  * indirect block, the information on the previous allocation is unavailable;
140  * here a best guess is made based upon the logical block number being
141  * allocated.
142  *
143  * If a section is already partially allocated, the policy is to
144  * contiguously allocate fs_maxcontig blocks.  The end of one of these
145  * contiguous blocks and the beginning of the next is physically separated
146  * so that the disk head will be in transit between them for at least
147  * fs_rotdelay milliseconds.  This is to allow time for the processor to
148  * schedule another I/O transfer.
149  */
150 ufs_daddr_t
151 ffs_blkpref(struct inode *ip, ufs_daddr_t lbn, int indx, ufs_daddr_t *bap)
152 {
153 	struct fs *fs;
154 	int cg;
155 	int avgbfree, startcg;
156 	ufs_daddr_t nextblk;
157 
158 	fs = ip->i_fs;
159 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
160 		if (lbn < NDADDR + NINDIR(fs)) {
161 			cg = ino_to_cg(fs, ip->i_number);
162 			return (fs->fs_fpg * cg + fs->fs_frag);
163 		}
164 		/*
165 		 * Find a cylinder with greater than average number of
166 		 * unused data blocks.
167 		 */
168 		if (indx == 0 || bap[indx - 1] == 0)
169 			startcg =
170 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
171 		else
172 			startcg = dtog(fs,
173 				ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + 1);
174 		startcg %= fs->fs_ncg;
175 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
176 		for (cg = startcg; cg < fs->fs_ncg; cg++)
177 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
178 				fs->fs_cgrotor = cg;
179 				return (fs->fs_fpg * cg + fs->fs_frag);
180 			}
181 		for (cg = 0; cg <= startcg; cg++)
182 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
183 				fs->fs_cgrotor = cg;
184 				return (fs->fs_fpg * cg + fs->fs_frag);
185 			}
186 		return (0);
187 	}
188 	/*
189 	 * One or more previous blocks have been laid out. If less
190 	 * than fs_maxcontig previous blocks are contiguous, the
191 	 * next block is requested contiguously, otherwise it is
192 	 * requested rotationally delayed by fs_rotdelay milliseconds.
193 	 */
194 	nextblk = ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + fs->fs_frag;
195 	if (indx < fs->fs_maxcontig ||
196 		ufs_rw32(bap[indx - fs->fs_maxcontig], UFS_FSNEEDSWAP(fs)) +
197 	    blkstofrags(fs, fs->fs_maxcontig) != nextblk)
198 		return (nextblk);
199 	if (fs->fs_rotdelay != 0)
200 		/*
201 		 * Here we convert ms of delay to frags as:
202 		 * (frags) = (ms) * (rev/sec) * (sect/rev) /
203 		 *	((sect/frag) * (ms/sec))
204 		 * then round up to the next block.
205 		 */
206 		nextblk += roundup(fs->fs_rotdelay * fs->fs_rps * fs->fs_nsect /
207 		    (NSPF(fs) * 1000), fs->fs_frag);
208 	return (nextblk);
209 }
210 
211 /*
212  * Implement the cylinder overflow algorithm.
213  *
214  * The policy implemented by this algorithm is:
215  *   1) allocate the block in its requested cylinder group.
216  *   2) quadradically rehash on the cylinder group number.
217  *   3) brute force search for a free block.
218  *
219  * `size':	size for data blocks, mode for inodes
220  */
221 /*VARARGS5*/
222 static u_long
223 ffs_hashalloc(struct inode *ip, int cg, long pref, int size,
224     ufs_daddr_t (*allocator)(struct inode *, int, ufs_daddr_t, int))
225 {
226 	struct fs *fs;
227 	long result;
228 	int i, icg = cg;
229 
230 	fs = ip->i_fs;
231 	/*
232 	 * 1: preferred cylinder group
233 	 */
234 	result = (*allocator)(ip, cg, pref, size);
235 	if (result)
236 		return (result);
237 	/*
238 	 * 2: quadratic rehash
239 	 */
240 	for (i = 1; i < fs->fs_ncg; i *= 2) {
241 		cg += i;
242 		if (cg >= fs->fs_ncg)
243 			cg -= fs->fs_ncg;
244 		result = (*allocator)(ip, cg, 0, size);
245 		if (result)
246 			return (result);
247 	}
248 	/*
249 	 * 3: brute force search
250 	 * Note that we start at i == 2, since 0 was checked initially,
251 	 * and 1 is always checked in the quadratic rehash.
252 	 */
253 	cg = (icg + 2) % fs->fs_ncg;
254 	for (i = 2; i < fs->fs_ncg; i++) {
255 		result = (*allocator)(ip, cg, 0, size);
256 		if (result)
257 			return (result);
258 		cg++;
259 		if (cg == fs->fs_ncg)
260 			cg = 0;
261 	}
262 	return (0);
263 }
264 
265 /*
266  * Determine whether a block can be allocated.
267  *
268  * Check to see if a block of the appropriate size is available,
269  * and if it is, allocate it.
270  */
271 static ufs_daddr_t
272 ffs_alloccg(struct inode *ip, int cg, ufs_daddr_t bpref, int size)
273 {
274 	struct cg *cgp;
275 	struct buf *bp;
276 	ufs_daddr_t bno, blkno;
277 	int error, frags, allocsiz, i;
278 	struct fs *fs = ip->i_fs;
279 	const int needswap = UFS_FSNEEDSWAP(fs);
280 
281 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
282 		return (0);
283 	error = bread(ip->i_fd, ip->i_fs, fsbtodb(fs, cgtod(fs, cg)),
284 		(int)fs->fs_cgsize, &bp);
285 	if (error) {
286 		brelse(bp);
287 		return (0);
288 	}
289 	cgp = (struct cg *)bp->b_data;
290 	if (!cg_chkmagic(cgp, needswap) ||
291 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize)) {
292 		brelse(bp);
293 		return (0);
294 	}
295 	if (size == fs->fs_bsize) {
296 		bno = ffs_alloccgblk(ip, bp, bpref);
297 		bdwrite(bp);
298 		return (bno);
299 	}
300 	/*
301 	 * check to see if any fragments are already available
302 	 * allocsiz is the size which will be allocated, hacking
303 	 * it down to a smaller size if necessary
304 	 */
305 	frags = numfrags(fs, size);
306 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
307 		if (cgp->cg_frsum[allocsiz] != 0)
308 			break;
309 	if (allocsiz == fs->fs_frag) {
310 		/*
311 		 * no fragments were available, so a block will be
312 		 * allocated, and hacked up
313 		 */
314 		if (cgp->cg_cs.cs_nbfree == 0) {
315 			brelse(bp);
316 			return (0);
317 		}
318 		bno = ffs_alloccgblk(ip, bp, bpref);
319 		bpref = dtogd(fs, bno);
320 		for (i = frags; i < fs->fs_frag; i++)
321 			setbit(cg_blksfree(cgp, needswap), bpref + i);
322 		i = fs->fs_frag - frags;
323 		ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
324 		fs->fs_cstotal.cs_nffree += i;
325 		fs->fs_cs(fs, cg).cs_nffree += i;
326 		fs->fs_fmod = 1;
327 		ufs_add32(cgp->cg_frsum[i], 1, needswap);
328 		bdwrite(bp);
329 		return (bno);
330 	}
331 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
332 	for (i = 0; i < frags; i++)
333 		clrbit(cg_blksfree(cgp, needswap), bno + i);
334 	ufs_add32(cgp->cg_cs.cs_nffree, -frags, needswap);
335 	fs->fs_cstotal.cs_nffree -= frags;
336 	fs->fs_cs(fs, cg).cs_nffree -= frags;
337 	fs->fs_fmod = 1;
338 	ufs_add32(cgp->cg_frsum[allocsiz], -1, needswap);
339 	if (frags != allocsiz)
340 		ufs_add32(cgp->cg_frsum[allocsiz - frags], 1, needswap);
341 	blkno = cg * fs->fs_fpg + bno;
342 	bdwrite(bp);
343 	return blkno;
344 }
345 
346 /*
347  * Allocate a block in a cylinder group.
348  *
349  * This algorithm implements the following policy:
350  *   1) allocate the requested block.
351  *   2) allocate a rotationally optimal block in the same cylinder.
352  *   3) allocate the next available block on the block rotor for the
353  *      specified cylinder group.
354  * Note that this routine only allocates fs_bsize blocks; these
355  * blocks may be fragmented by the routine that allocates them.
356  */
357 static ufs_daddr_t
358 ffs_alloccgblk(struct inode *ip, struct buf *bp, ufs_daddr_t bpref)
359 {
360 	struct cg *cgp;
361 	ufs_daddr_t bno, blkno;
362 	int cylno, pos, delta;
363 	short *cylbp;
364 	int i;
365 	struct fs *fs = ip->i_fs;
366 	const int needswap = UFS_FSNEEDSWAP(fs);
367 
368 	cgp = (struct cg *)bp->b_data;
369 	if (bpref == 0 || dtog(fs, bpref) != ufs_rw32(cgp->cg_cgx, needswap)) {
370 		bpref = ufs_rw32(cgp->cg_rotor, needswap);
371 		goto norot;
372 	}
373 	bpref = blknum(fs, bpref);
374 	bpref = dtogd(fs, bpref);
375 	/*
376 	 * if the requested block is available, use it
377 	 */
378 	if (ffs_isblock(fs, cg_blksfree(cgp, needswap),
379 		fragstoblks(fs, bpref))) {
380 		bno = bpref;
381 		goto gotit;
382 	}
383 	if (fs->fs_nrpos <= 1 || fs->fs_cpc == 0) {
384 		/*
385 		 * Block layout information is not available.
386 		 * Leaving bpref unchanged means we take the
387 		 * next available free block following the one
388 		 * we just allocated. Hopefully this will at
389 		 * least hit a track cache on drives of unknown
390 		 * geometry (e.g. SCSI).
391 		 */
392 		goto norot;
393 	}
394 	/*
395 	 * check for a block available on the same cylinder
396 	 */
397 	cylno = cbtocylno(fs, bpref);
398 	if (cg_blktot(cgp, needswap)[cylno] == 0)
399 		goto norot;
400 	/*
401 	 * check the summary information to see if a block is
402 	 * available in the requested cylinder starting at the
403 	 * requested rotational position and proceeding around.
404 	 */
405 	cylbp = cg_blks(fs, cgp, cylno, needswap);
406 	pos = cbtorpos(fs, bpref);
407 	for (i = pos; i < fs->fs_nrpos; i++)
408 		if (ufs_rw16(cylbp[i], needswap) > 0)
409 			break;
410 	if (i == fs->fs_nrpos)
411 		for (i = 0; i < pos; i++)
412 			if (ufs_rw16(cylbp[i], needswap) > 0)
413 				break;
414 	if (ufs_rw16(cylbp[i], needswap) > 0) {
415 		/*
416 		 * found a rotational position, now find the actual
417 		 * block. A panic if none is actually there.
418 		 */
419 		pos = cylno % fs->fs_cpc;
420 		bno = (cylno - pos) * fs->fs_spc / NSPB(fs);
421 		if (fs_postbl(fs, pos)[i] == -1) {
422 			errx(1,
423 			    "ffs_alloccgblk: cyl groups corrupted: pos %d i %d",
424 			    pos, i);
425 		}
426 		for (i = fs_postbl(fs, pos)[i];; ) {
427 			if (ffs_isblock(fs, cg_blksfree(cgp, needswap), bno + i)) {
428 				bno = blkstofrags(fs, (bno + i));
429 				goto gotit;
430 			}
431 			delta = fs_rotbl(fs)[i];
432 			if (delta <= 0 ||
433 			    delta + i > fragstoblks(fs, fs->fs_fpg))
434 				break;
435 			i += delta;
436 		}
437 		errx(1, "ffs_alloccgblk: can't find blk in cyl: pos %d i %d",
438 		    pos, i);
439 	}
440 norot:
441 	/*
442 	 * no blocks in the requested cylinder, so take next
443 	 * available one in this cylinder group.
444 	 */
445 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
446 	if (bno < 0)
447 		return (0);
448 	cgp->cg_rotor = ufs_rw32(bno, needswap);
449 gotit:
450 	blkno = fragstoblks(fs, bno);
451 	ffs_clrblock(fs, cg_blksfree(cgp, needswap), (long)blkno);
452 	ffs_clusteracct(fs, cgp, blkno, -1);
453 	ufs_add32(cgp->cg_cs.cs_nbfree, -1, needswap);
454 	fs->fs_cstotal.cs_nbfree--;
455 	fs->fs_cs(fs, ufs_rw32(cgp->cg_cgx, needswap)).cs_nbfree--;
456 	cylno = cbtocylno(fs, bno);
457 	ufs_add16(cg_blks(fs, cgp, cylno, needswap)[cbtorpos(fs, bno)], -1,
458 	    needswap);
459 	ufs_add32(cg_blktot(cgp, needswap)[cylno], -1, needswap);
460 	fs->fs_fmod = 1;
461 	blkno = ufs_rw32(cgp->cg_cgx, needswap) * fs->fs_fpg + bno;
462 	return (blkno);
463 }
464 
465 /*
466  * Free a block or fragment.
467  *
468  * The specified block or fragment is placed back in the
469  * free map. If a fragment is deallocated, a possible
470  * block reassembly is checked.
471  */
472 void
473 ffs_blkfree(struct inode *ip, ufs_daddr_t bno, long size)
474 {
475 	struct cg *cgp;
476 	struct buf *bp;
477 	ufs_daddr_t blkno;
478 	int i, error, cg, blk, frags, bbase;
479 	struct fs *fs = ip->i_fs;
480 	const int needswap = UFS_FSNEEDSWAP(fs);
481 
482 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
483 	    fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
484 		errx(1, "blkfree: bad size: bno %u bsize %d size %ld",
485 		    bno, fs->fs_bsize, size);
486 	}
487 	cg = dtog(fs, bno);
488 	if ((u_int)bno >= fs->fs_size) {
489 		warnx("bad block %d, ino %d\n", bno, ip->i_number);
490 		return;
491 	}
492 	error = bread(ip->i_fd, ip->i_fs, fsbtodb(fs, cgtod(fs, cg)),
493 		(int)fs->fs_cgsize, &bp);
494 	if (error) {
495 		brelse(bp);
496 		return;
497 	}
498 	cgp = (struct cg *)bp->b_data;
499 	if (!cg_chkmagic(cgp, needswap)) {
500 		brelse(bp);
501 		return;
502 	}
503 	bno = dtogd(fs, bno);
504 	if (size == fs->fs_bsize) {
505 		blkno = fragstoblks(fs, bno);
506 		if (!ffs_isfreeblock(fs, cg_blksfree(cgp, needswap), blkno)) {
507 			errx(1, "blkfree: freeing free block %d", bno);
508 		}
509 		ffs_setblock(fs, cg_blksfree(cgp, needswap), blkno);
510 		ffs_clusteracct(fs, cgp, blkno, 1);
511 		ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
512 		fs->fs_cstotal.cs_nbfree++;
513 		fs->fs_cs(fs, cg).cs_nbfree++;
514 		i = cbtocylno(fs, bno);
515 		ufs_add16(cg_blks(fs, cgp, i, needswap)[cbtorpos(fs, bno)], 1,
516 		    needswap);
517 		ufs_add32(cg_blktot(cgp, needswap)[i], 1, needswap);
518 	} else {
519 		bbase = bno - fragnum(fs, bno);
520 		/*
521 		 * decrement the counts associated with the old frags
522 		 */
523 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bbase);
524 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1, needswap);
525 		/*
526 		 * deallocate the fragment
527 		 */
528 		frags = numfrags(fs, size);
529 		for (i = 0; i < frags; i++) {
530 			if (isset(cg_blksfree(cgp, needswap), bno + i)) {
531 				errx(1, "blkfree: freeing free frag: block %d",
532 				    bno + i);
533 			}
534 			setbit(cg_blksfree(cgp, needswap), bno + i);
535 		}
536 		ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
537 		fs->fs_cstotal.cs_nffree += i;
538 		fs->fs_cs(fs, cg).cs_nffree += i;
539 		/*
540 		 * add back in counts associated with the new frags
541 		 */
542 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bbase);
543 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1, needswap);
544 		/*
545 		 * if a complete block has been reassembled, account for it
546 		 */
547 		blkno = fragstoblks(fs, bbase);
548 		if (ffs_isblock(fs, cg_blksfree(cgp, needswap), blkno)) {
549 			ufs_add32(cgp->cg_cs.cs_nffree, -fs->fs_frag, needswap);
550 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
551 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
552 			ffs_clusteracct(fs, cgp, blkno, 1);
553 			ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
554 			fs->fs_cstotal.cs_nbfree++;
555 			fs->fs_cs(fs, cg).cs_nbfree++;
556 			i = cbtocylno(fs, bbase);
557 			ufs_add16(cg_blks(fs, cgp, i, needswap)[cbtorpos(fs,
558 								bbase)], 1,
559 			    needswap);
560 			ufs_add32(cg_blktot(cgp, needswap)[i], 1, needswap);
561 		}
562 	}
563 	fs->fs_fmod = 1;
564 	bdwrite(bp);
565 }
566 
567 
568 static int
569 scanc(u_int size, const u_char *cp, const u_char table[], int mask)
570 {
571 	const u_char *end = &cp[size];
572 
573 	while (cp < end && (table[*cp] & mask) == 0)
574 		cp++;
575 	return (end - cp);
576 }
577 
578 /*
579  * Find a block of the specified size in the specified cylinder group.
580  *
581  * It is a panic if a request is made to find a block if none are
582  * available.
583  */
584 static ufs_daddr_t
585 ffs_mapsearch(struct fs *fs, struct cg *cgp, ufs_daddr_t bpref, int allocsiz)
586 {
587 	ufs_daddr_t bno;
588 	int start, len, loc, i;
589 	int blk, field, subfield, pos;
590 	int ostart, olen;
591 	const int needswap = UFS_FSNEEDSWAP(fs);
592 
593 	/*
594 	 * find the fragment by searching through the free block
595 	 * map for an appropriate bit pattern
596 	 */
597 	if (bpref)
598 		start = dtogd(fs, bpref) / NBBY;
599 	else
600 		start = ufs_rw32(cgp->cg_frotor, needswap) / NBBY;
601 	len = howmany(fs->fs_fpg, NBBY) - start;
602 	ostart = start;
603 	olen = len;
604 	loc = scanc((u_int)len,
605 		(const u_char *)&cg_blksfree(cgp, needswap)[start],
606 		(const u_char *)fragtbl[fs->fs_frag],
607 		(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
608 	if (loc == 0) {
609 		len = start + 1;
610 		start = 0;
611 		loc = scanc((u_int)len,
612 			(const u_char *)&cg_blksfree(cgp, needswap)[0],
613 			(const u_char *)fragtbl[fs->fs_frag],
614 			(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
615 		if (loc == 0) {
616 			errx(1,
617     "ffs_alloccg: map corrupted: start %d len %d offset %d %ld",
618 				ostart, olen,
619 				ufs_rw32(cgp->cg_freeoff, needswap),
620 				(long)cg_blksfree(cgp, needswap) - (long)cgp);
621 			/* NOTREACHED */
622 		}
623 	}
624 	bno = (start + len - loc) * NBBY;
625 	cgp->cg_frotor = ufs_rw32(bno, needswap);
626 	/*
627 	 * found the byte in the map
628 	 * sift through the bits to find the selected frag
629 	 */
630 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
631 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bno);
632 		blk <<= 1;
633 		field = around[allocsiz];
634 		subfield = inside[allocsiz];
635 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
636 			if ((blk & field) == subfield)
637 				return (bno + pos);
638 			field <<= 1;
639 			subfield <<= 1;
640 		}
641 	}
642 	errx(1, "ffs_alloccg: block not in map: bno %d", bno);
643 	return (-1);
644 }
645 
646 /*
647  * Update the cluster map because of an allocation or free.
648  *
649  * Cnt == 1 means free; cnt == -1 means allocating.
650  */
651 void
652 ffs_clusteracct(struct fs *fs, struct cg *cgp, ufs_daddr_t blkno, int cnt)
653 {
654 	int32_t *sump;
655 	int32_t *lp;
656 	u_char *freemapp, *mapp;
657 	int i, start, end, forw, back, map, bit;
658 	const int needswap = UFS_FSNEEDSWAP(fs);
659 
660 	if (fs->fs_contigsumsize <= 0)
661 		return;
662 	freemapp = cg_clustersfree(cgp, needswap);
663 	sump = cg_clustersum(cgp, needswap);
664 	/*
665 	 * Allocate or clear the actual block.
666 	 */
667 	if (cnt > 0)
668 		setbit(freemapp, blkno);
669 	else
670 		clrbit(freemapp, blkno);
671 	/*
672 	 * Find the size of the cluster going forward.
673 	 */
674 	start = blkno + 1;
675 	end = start + fs->fs_contigsumsize;
676 	if (end >= ufs_rw32(cgp->cg_nclusterblks, needswap))
677 		end = ufs_rw32(cgp->cg_nclusterblks, needswap);
678 	mapp = &freemapp[start / NBBY];
679 	map = *mapp++;
680 	bit = 1 << (start % NBBY);
681 	for (i = start; i < end; i++) {
682 		if ((map & bit) == 0)
683 			break;
684 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
685 			bit <<= 1;
686 		} else {
687 			map = *mapp++;
688 			bit = 1;
689 		}
690 	}
691 	forw = i - start;
692 	/*
693 	 * Find the size of the cluster going backward.
694 	 */
695 	start = blkno - 1;
696 	end = start - fs->fs_contigsumsize;
697 	if (end < 0)
698 		end = -1;
699 	mapp = &freemapp[start / NBBY];
700 	map = *mapp--;
701 	bit = 1 << (start % NBBY);
702 	for (i = start; i > end; i--) {
703 		if ((map & bit) == 0)
704 			break;
705 		if ((i & (NBBY - 1)) != 0) {
706 			bit >>= 1;
707 		} else {
708 			map = *mapp--;
709 			bit = 1 << (NBBY - 1);
710 		}
711 	}
712 	back = start - i;
713 	/*
714 	 * Account for old cluster and the possibly new forward and
715 	 * back clusters.
716 	 */
717 	i = back + forw + 1;
718 	if (i > fs->fs_contigsumsize)
719 		i = fs->fs_contigsumsize;
720 	ufs_add32(sump[i], cnt, needswap);
721 	if (back > 0)
722 		ufs_add32(sump[back], -cnt, needswap);
723 	if (forw > 0)
724 		ufs_add32(sump[forw], -cnt, needswap);
725 
726 	/*
727 	 * Update cluster summary information.
728 	 */
729 	lp = &sump[fs->fs_contigsumsize];
730 	for (i = fs->fs_contigsumsize; i > 0; i--)
731 		if (ufs_rw32(*lp--, needswap) > 0)
732 			break;
733 	fs->fs_maxcluster[ufs_rw32(cgp->cg_cgx, needswap)] = i;
734 }
735