xref: /netbsd-src/usr.sbin/makefs/ffs/ffs_alloc.c (revision b8c616269f5ebf18ab2e35cb8099d683130a177c)
1 /*	$NetBSD: ffs_alloc.c,v 1.11 2003/01/24 21:55:32 fvdl 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 #if defined(__RCSID) && !defined(__lint)
41 __RCSID("$NetBSD: ffs_alloc.c,v 1.11 2003/01/24 21:55:32 fvdl Exp $");
42 #endif	/* !__lint */
43 
44 #include <sys/param.h>
45 #include <sys/time.h>
46 
47 #include <errno.h>
48 
49 #include "makefs.h"
50 
51 #include <ufs/ufs/dinode.h>
52 #include <ufs/ufs/ufs_bswap.h>
53 #include <ufs/ffs/fs.h>
54 
55 #include "ffs/buf.h"
56 #include "ffs/ufs_inode.h"
57 #include "ffs/ffs_extern.h"
58 
59 
60 static int scanc(u_int, const u_char *, const u_char *, int);
61 
62 static daddr_t ffs_alloccg(struct inode *, int, daddr_t, int);
63 static daddr_t ffs_alloccgblk(struct inode *, struct buf *, daddr_t);
64 static daddr_t ffs_hashalloc(struct inode *, int, daddr_t, int,
65 		     daddr_t (*)(struct inode *, int, daddr_t, int));
66 static daddr_t ffs_mapsearch(struct fs *, struct cg *, daddr_t, int);
67 
68 /* in ffs_tables.c */
69 extern const int inside[], around[];
70 extern const u_char * const fragtbl[];
71 
72 /*
73  * Allocate a block in the file system.
74  *
75  * The size of the requested block is given, which must be some
76  * multiple of fs_fsize and <= fs_bsize.
77  * A preference may be optionally specified. If a preference is given
78  * the following hierarchy is used to allocate a block:
79  *   1) allocate the requested block.
80  *   2) allocate a rotationally optimal block in the same cylinder.
81  *   3) allocate a block in the same cylinder group.
82  *   4) quadradically rehash into other cylinder groups, until an
83  *      available block is located.
84  * If no block preference is given the following hierarchy is used
85  * to allocate a block:
86  *   1) allocate a block in the cylinder group that contains the
87  *      inode for the file.
88  *   2) quadradically rehash into other cylinder groups, until an
89  *      available block is located.
90  */
91 int
92 ffs_alloc(struct inode *ip, daddr_t lbn, daddr_t bpref, int size,
93     daddr_t *bnp)
94 {
95 	struct fs *fs = ip->i_fs;
96 	daddr_t bno;
97 	int cg;
98 
99 	*bnp = 0;
100 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
101 		errx(1, "ffs_alloc: bad size: bsize %d size %d",
102 		    fs->fs_bsize, size);
103 	}
104 	if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
105 		goto nospace;
106 	if (bpref >= fs->fs_size)
107 		bpref = 0;
108 	if (bpref == 0)
109 		cg = ino_to_cg(fs, ip->i_number);
110 	else
111 		cg = dtog(fs, bpref);
112 	bno = ffs_hashalloc(ip, cg, bpref, size, ffs_alloccg);
113 	if (bno > 0) {
114 		ip->i_ffs_blocks += size / DEV_BSIZE;
115 		*bnp = bno;
116 		return (0);
117 	}
118 nospace:
119 	return (ENOSPC);
120 }
121 
122 /*
123  * Select the desired position for the next block in a file.  The file is
124  * logically divided into sections. The first section is composed of the
125  * direct blocks. Each additional section contains fs_maxbpg blocks.
126  *
127  * If no blocks have been allocated in the first section, the policy is to
128  * request a block in the same cylinder group as the inode that describes
129  * the file. If no blocks have been allocated in any other section, the
130  * policy is to place the section in a cylinder group with a greater than
131  * average number of free blocks.  An appropriate cylinder group is found
132  * by using a rotor that sweeps the cylinder groups. When a new group of
133  * blocks is needed, the sweep begins in the cylinder group following the
134  * cylinder group from which the previous allocation was made. The sweep
135  * continues until a cylinder group with greater than the average number
136  * of free blocks is found. If the allocation is for the first block in an
137  * indirect block, the information on the previous allocation is unavailable;
138  * here a best guess is made based upon the logical block number being
139  * allocated.
140  *
141  * If a section is already partially allocated, the policy is to
142  * contiguously allocate fs_maxcontig blocks.  The end of one of these
143  * contiguous blocks and the beginning of the next is physically separated
144  * so that the disk head will be in transit between them for at least
145  * fs_rotdelay milliseconds.  This is to allow time for the processor to
146  * schedule another I/O transfer.
147  */
148 /* XXX ondisk32 */
149 daddr_t
150 ffs_blkpref(struct inode *ip, daddr_t lbn, int indx, int32_t *bap)
151 {
152 	struct fs *fs;
153 	int cg;
154 	int avgbfree, startcg;
155 	daddr_t nextblk;
156 
157 	fs = ip->i_fs;
158 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
159 		if (lbn < NDADDR + NINDIR(fs)) {
160 			cg = ino_to_cg(fs, ip->i_number);
161 			return (fs->fs_fpg * cg + fs->fs_frag);
162 		}
163 		/*
164 		 * Find a cylinder with greater than average number of
165 		 * unused data blocks.
166 		 */
167 		if (indx == 0 || bap[indx - 1] == 0)
168 			startcg =
169 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
170 		else
171 			startcg = dtog(fs,
172 				ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + 1);
173 		startcg %= fs->fs_ncg;
174 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
175 		for (cg = startcg; cg < fs->fs_ncg; cg++)
176 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
177 				fs->fs_cgrotor = cg;
178 				return (fs->fs_fpg * cg + fs->fs_frag);
179 			}
180 		for (cg = 0; cg <= startcg; cg++)
181 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
182 				fs->fs_cgrotor = cg;
183 				return (fs->fs_fpg * cg + fs->fs_frag);
184 			}
185 		return (0);
186 	}
187 	/*
188 	 * One or more previous blocks have been laid out. If less
189 	 * than fs_maxcontig previous blocks are contiguous, the
190 	 * next block is requested contiguously, otherwise it is
191 	 * requested rotationally delayed by fs_rotdelay milliseconds.
192 	 */
193 	/* XXX ondisk32 */
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 daddr_t
223 ffs_hashalloc(struct inode *ip, int cg, daddr_t pref, int size,
224     daddr_t (*allocator)(struct inode *, int, daddr_t, int))
225 {
226 	struct fs *fs;
227 	daddr_t 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 daddr_t
272 ffs_alloccg(struct inode *ip, int cg, daddr_t bpref, int size)
273 {
274 	struct cg *cgp;
275 	struct buf *bp;
276 	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 daddr_t
358 ffs_alloccgblk(struct inode *ip, struct buf *bp, daddr_t bpref)
359 {
360 	struct cg *cgp;
361 	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 	/* XXX ondisk32 */
370 	if (bpref == 0 || dtog(fs, bpref) != ufs_rw32(cgp->cg_cgx, needswap)) {
371 		bpref = ufs_rw32(cgp->cg_rotor, needswap);
372 		goto norot;
373 	}
374 	bpref = blknum(fs, bpref);
375 	bpref = dtogd(fs, bpref);
376 	/*
377 	 * if the requested block is available, use it
378 	 */
379 	if (ffs_isblock(fs, cg_blksfree(cgp, needswap),
380 		fragstoblks(fs, bpref))) {
381 		bno = bpref;
382 		goto gotit;
383 	}
384 	if (fs->fs_nrpos <= 1 || fs->fs_cpc == 0) {
385 		/*
386 		 * Block layout information is not available.
387 		 * Leaving bpref unchanged means we take the
388 		 * next available free block following the one
389 		 * we just allocated. Hopefully this will at
390 		 * least hit a track cache on drives of unknown
391 		 * geometry (e.g. SCSI).
392 		 */
393 		goto norot;
394 	}
395 	/*
396 	 * check for a block available on the same cylinder
397 	 */
398 	cylno = cbtocylno(fs, bpref);
399 	if (cg_blktot(cgp, needswap)[cylno] == 0)
400 		goto norot;
401 	/*
402 	 * check the summary information to see if a block is
403 	 * available in the requested cylinder starting at the
404 	 * requested rotational position and proceeding around.
405 	 */
406 	cylbp = cg_blks(fs, cgp, cylno, needswap);
407 	pos = cbtorpos(fs, bpref);
408 	for (i = pos; i < fs->fs_nrpos; i++)
409 		if (ufs_rw16(cylbp[i], needswap) > 0)
410 			break;
411 	if (i == fs->fs_nrpos)
412 		for (i = 0; i < pos; i++)
413 			if (ufs_rw16(cylbp[i], needswap) > 0)
414 				break;
415 	if (ufs_rw16(cylbp[i], needswap) > 0) {
416 		/*
417 		 * found a rotational position, now find the actual
418 		 * block. A panic if none is actually there.
419 		 */
420 		pos = cylno % fs->fs_cpc;
421 		bno = (cylno - pos) * fs->fs_spc / NSPB(fs);
422 		if (fs_postbl(fs, pos)[i] == -1) {
423 			errx(1,
424 			    "ffs_alloccgblk: cyl groups corrupted: pos %d i %d",
425 			    pos, i);
426 		}
427 		for (i = fs_postbl(fs, pos)[i];; ) {
428 			if (ffs_isblock(fs, cg_blksfree(cgp, needswap), bno + i)) {
429 				bno = blkstofrags(fs, (bno + i));
430 				goto gotit;
431 			}
432 			delta = fs_rotbl(fs)[i];
433 			if (delta <= 0 ||
434 			    delta + i > fragstoblks(fs, fs->fs_fpg))
435 				break;
436 			i += delta;
437 		}
438 		errx(1, "ffs_alloccgblk: can't find blk in cyl: pos %d i %d",
439 		    pos, i);
440 	}
441 norot:
442 	/*
443 	 * no blocks in the requested cylinder, so take next
444 	 * available one in this cylinder group.
445 	 */
446 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
447 	if (bno < 0)
448 		return (0);
449 	/* XXX ondisk32 */
450 	cgp->cg_rotor = ufs_rw64(bno, needswap);
451 gotit:
452 	blkno = fragstoblks(fs, bno);
453 	ffs_clrblock(fs, cg_blksfree(cgp, needswap), (long)blkno);
454 	ffs_clusteracct(fs, cgp, blkno, -1);
455 	ufs_add32(cgp->cg_cs.cs_nbfree, -1, needswap);
456 	fs->fs_cstotal.cs_nbfree--;
457 	fs->fs_cs(fs, ufs_rw32(cgp->cg_cgx, needswap)).cs_nbfree--;
458 	cylno = cbtocylno(fs, bno);
459 	ufs_add16(cg_blks(fs, cgp, cylno, needswap)[cbtorpos(fs, bno)], -1,
460 	    needswap);
461 	ufs_add32(cg_blktot(cgp, needswap)[cylno], -1, needswap);
462 	fs->fs_fmod = 1;
463 	/* XXX ondisk32 */
464 	blkno = ufs_rw32(cgp->cg_cgx, needswap) * fs->fs_fpg + bno;
465 	return (blkno);
466 }
467 
468 /*
469  * Free a block or fragment.
470  *
471  * The specified block or fragment is placed back in the
472  * free map. If a fragment is deallocated, a possible
473  * block reassembly is checked.
474  */
475 void
476 ffs_blkfree(struct inode *ip, daddr_t bno, long size)
477 {
478 	struct cg *cgp;
479 	struct buf *bp;
480 	daddr_t blkno;
481 	int i, error, cg, blk, frags, bbase;
482 	struct fs *fs = ip->i_fs;
483 	const int needswap = UFS_FSNEEDSWAP(fs);
484 
485 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
486 	    fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
487 		errx(1, "blkfree: bad size: bno %lld bsize %d size %ld",
488 		    (long long)bno, fs->fs_bsize, size);
489 	}
490 	cg = dtog(fs, bno);
491 	if ((u_int)bno >= fs->fs_size) {
492 		warnx("bad block %lld, ino %d", (long long)bno, ip->i_number);
493 		return;
494 	}
495 	error = bread(ip->i_fd, ip->i_fs, fsbtodb(fs, cgtod(fs, cg)),
496 		(int)fs->fs_cgsize, &bp);
497 	if (error) {
498 		brelse(bp);
499 		return;
500 	}
501 	cgp = (struct cg *)bp->b_data;
502 	if (!cg_chkmagic(cgp, needswap)) {
503 		brelse(bp);
504 		return;
505 	}
506 	bno = dtogd(fs, bno);
507 	if (size == fs->fs_bsize) {
508 		blkno = fragstoblks(fs, bno);
509 		if (!ffs_isfreeblock(fs, cg_blksfree(cgp, needswap), blkno)) {
510 			errx(1, "blkfree: freeing free block %lld",
511 			    (long long)bno);
512 		}
513 		ffs_setblock(fs, cg_blksfree(cgp, needswap), blkno);
514 		ffs_clusteracct(fs, cgp, blkno, 1);
515 		ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
516 		fs->fs_cstotal.cs_nbfree++;
517 		fs->fs_cs(fs, cg).cs_nbfree++;
518 		i = cbtocylno(fs, bno);
519 		ufs_add16(cg_blks(fs, cgp, i, needswap)[cbtorpos(fs, bno)], 1,
520 		    needswap);
521 		ufs_add32(cg_blktot(cgp, needswap)[i], 1, needswap);
522 	} else {
523 		bbase = bno - fragnum(fs, bno);
524 		/*
525 		 * decrement the counts associated with the old frags
526 		 */
527 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bbase);
528 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1, needswap);
529 		/*
530 		 * deallocate the fragment
531 		 */
532 		frags = numfrags(fs, size);
533 		for (i = 0; i < frags; i++) {
534 			if (isset(cg_blksfree(cgp, needswap), bno + i)) {
535 				errx(1, "blkfree: freeing free frag: block %lld",
536 				    (long long)(bno + i));
537 			}
538 			setbit(cg_blksfree(cgp, needswap), bno + i);
539 		}
540 		ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
541 		fs->fs_cstotal.cs_nffree += i;
542 		fs->fs_cs(fs, cg).cs_nffree += i;
543 		/*
544 		 * add back in counts associated with the new frags
545 		 */
546 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bbase);
547 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1, needswap);
548 		/*
549 		 * if a complete block has been reassembled, account for it
550 		 */
551 		blkno = fragstoblks(fs, bbase);
552 		if (ffs_isblock(fs, cg_blksfree(cgp, needswap), blkno)) {
553 			ufs_add32(cgp->cg_cs.cs_nffree, -fs->fs_frag, needswap);
554 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
555 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
556 			ffs_clusteracct(fs, cgp, blkno, 1);
557 			ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
558 			fs->fs_cstotal.cs_nbfree++;
559 			fs->fs_cs(fs, cg).cs_nbfree++;
560 			i = cbtocylno(fs, bbase);
561 			ufs_add16(cg_blks(fs, cgp, i, needswap)[cbtorpos(fs,
562 								bbase)], 1,
563 			    needswap);
564 			ufs_add32(cg_blktot(cgp, needswap)[i], 1, needswap);
565 		}
566 	}
567 	fs->fs_fmod = 1;
568 	bdwrite(bp);
569 }
570 
571 
572 static int
573 scanc(u_int size, const u_char *cp, const u_char table[], int mask)
574 {
575 	const u_char *end = &cp[size];
576 
577 	while (cp < end && (table[*cp] & mask) == 0)
578 		cp++;
579 	return (end - cp);
580 }
581 
582 /*
583  * Find a block of the specified size in the specified cylinder group.
584  *
585  * It is a panic if a request is made to find a block if none are
586  * available.
587  */
588 static daddr_t
589 ffs_mapsearch(struct fs *fs, struct cg *cgp, daddr_t bpref, int allocsiz)
590 {
591 	daddr_t bno;
592 	int start, len, loc, i;
593 	int blk, field, subfield, pos;
594 	int ostart, olen;
595 	const int needswap = UFS_FSNEEDSWAP(fs);
596 
597 	/*
598 	 * find the fragment by searching through the free block
599 	 * map for an appropriate bit pattern
600 	 */
601 	if (bpref)
602 		start = dtogd(fs, bpref) / NBBY;
603 	else
604 		start = ufs_rw32(cgp->cg_frotor, needswap) / NBBY;
605 	len = howmany(fs->fs_fpg, NBBY) - start;
606 	ostart = start;
607 	olen = len;
608 	loc = scanc((u_int)len,
609 		(const u_char *)&cg_blksfree(cgp, needswap)[start],
610 		(const u_char *)fragtbl[fs->fs_frag],
611 		(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
612 	if (loc == 0) {
613 		len = start + 1;
614 		start = 0;
615 		loc = scanc((u_int)len,
616 			(const u_char *)&cg_blksfree(cgp, needswap)[0],
617 			(const u_char *)fragtbl[fs->fs_frag],
618 			(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
619 		if (loc == 0) {
620 			errx(1,
621     "ffs_alloccg: map corrupted: start %d len %d offset %d %ld",
622 				ostart, olen,
623 				ufs_rw32(cgp->cg_freeoff, needswap),
624 				(long)cg_blksfree(cgp, needswap) - (long)cgp);
625 			/* NOTREACHED */
626 		}
627 	}
628 	bno = (start + len - loc) * NBBY;
629 	cgp->cg_frotor = ufs_rw32(bno, needswap);
630 	/*
631 	 * found the byte in the map
632 	 * sift through the bits to find the selected frag
633 	 */
634 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
635 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bno);
636 		blk <<= 1;
637 		field = around[allocsiz];
638 		subfield = inside[allocsiz];
639 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
640 			if ((blk & field) == subfield)
641 				return (bno + pos);
642 			field <<= 1;
643 			subfield <<= 1;
644 		}
645 	}
646 	errx(1, "ffs_alloccg: block not in map: bno %lld", (long long)bno);
647 	return (-1);
648 }
649 
650 /*
651  * Update the cluster map because of an allocation or free.
652  *
653  * Cnt == 1 means free; cnt == -1 means allocating.
654  */
655 void
656 ffs_clusteracct(struct fs *fs, struct cg *cgp, daddr_t blkno, int cnt)
657 {
658 	int32_t *sump;
659 	int32_t *lp;
660 	u_char *freemapp, *mapp;
661 	int i, start, end, forw, back, map, bit;
662 	const int needswap = UFS_FSNEEDSWAP(fs);
663 
664 	if (fs->fs_contigsumsize <= 0)
665 		return;
666 	freemapp = cg_clustersfree(cgp, needswap);
667 	sump = cg_clustersum(cgp, needswap);
668 	/*
669 	 * Allocate or clear the actual block.
670 	 */
671 	if (cnt > 0)
672 		setbit(freemapp, blkno);
673 	else
674 		clrbit(freemapp, blkno);
675 	/*
676 	 * Find the size of the cluster going forward.
677 	 */
678 	start = blkno + 1;
679 	end = start + fs->fs_contigsumsize;
680 	if (end >= ufs_rw32(cgp->cg_nclusterblks, needswap))
681 		end = ufs_rw32(cgp->cg_nclusterblks, needswap);
682 	mapp = &freemapp[start / NBBY];
683 	map = *mapp++;
684 	bit = 1 << (start % NBBY);
685 	for (i = start; i < end; i++) {
686 		if ((map & bit) == 0)
687 			break;
688 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
689 			bit <<= 1;
690 		} else {
691 			map = *mapp++;
692 			bit = 1;
693 		}
694 	}
695 	forw = i - start;
696 	/*
697 	 * Find the size of the cluster going backward.
698 	 */
699 	start = blkno - 1;
700 	end = start - fs->fs_contigsumsize;
701 	if (end < 0)
702 		end = -1;
703 	mapp = &freemapp[start / NBBY];
704 	map = *mapp--;
705 	bit = 1 << (start % NBBY);
706 	for (i = start; i > end; i--) {
707 		if ((map & bit) == 0)
708 			break;
709 		if ((i & (NBBY - 1)) != 0) {
710 			bit >>= 1;
711 		} else {
712 			map = *mapp--;
713 			bit = 1 << (NBBY - 1);
714 		}
715 	}
716 	back = start - i;
717 	/*
718 	 * Account for old cluster and the possibly new forward and
719 	 * back clusters.
720 	 */
721 	i = back + forw + 1;
722 	if (i > fs->fs_contigsumsize)
723 		i = fs->fs_contigsumsize;
724 	ufs_add32(sump[i], cnt, needswap);
725 	if (back > 0)
726 		ufs_add32(sump[back], -cnt, needswap);
727 	if (forw > 0)
728 		ufs_add32(sump[forw], -cnt, needswap);
729 
730 	/*
731 	 * Update cluster summary information.
732 	 */
733 	lp = &sump[fs->fs_contigsumsize];
734 	for (i = fs->fs_contigsumsize; i > 0; i--)
735 		if (ufs_rw32(*lp--, needswap) > 0)
736 			break;
737 	fs->fs_maxcluster[ufs_rw32(cgp->cg_cgx, needswap)] = i;
738 }
739