xref: /freebsd/sys/ufs/ffs/ffs_alloc.c (revision 17ee9d00bc1ae1e598c38f25826f861e4bc6c3ce)
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)ffs_alloc.c	8.8 (Berkeley) 2/21/94
34  * $Id: ffs_alloc.c,v 1.6 1995/01/09 16:05:17 davidg Exp $
35  */
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/buf.h>
40 #include <sys/proc.h>
41 #include <sys/vnode.h>
42 #include <sys/mount.h>
43 #include <sys/kernel.h>
44 #include <sys/syslog.h>
45 
46 #include <vm/vm.h>
47 
48 #include <ufs/ufs/quota.h>
49 #include <ufs/ufs/inode.h>
50 #include <ufs/ufs/ufs_extern.h>		/* YF - needed for ufs_getlbns() */
51 
52 #include <ufs/ffs/fs.h>
53 #include <ufs/ffs/ffs_extern.h>
54 
55 extern u_long nextgennumber;
56 
57 static daddr_t	ffs_alloccg __P((struct inode *, int, daddr_t, int));
58 static daddr_t	ffs_alloccgblk __P((struct fs *, struct cg *, daddr_t));
59 static daddr_t	ffs_clusteralloc __P((struct inode *, int, daddr_t, int));
60 static ino_t	ffs_dirpref __P((struct fs *));
61 static daddr_t	ffs_fragextend __P((struct inode *, int, long, int, int));
62 static void	ffs_fserr __P((struct fs *, u_int, char *));
63 static u_long	ffs_hashalloc
64 		    __P((struct inode *, int, long, int, u_long (*)()));
65 static ino_t	ffs_nodealloccg __P((struct inode *, int, daddr_t, int));
66 static daddr_t	ffs_mapsearch __P((struct fs *, struct cg *, daddr_t, int));
67 
68 void		ffs_clusteracct	__P((struct fs *, struct cg *, daddr_t, int));
69 
70 /*
71  * Allocate a block in the file system.
72  *
73  * The size of the requested block is given, which must be some
74  * multiple of fs_fsize and <= fs_bsize.
75  * A preference may be optionally specified. If a preference is given
76  * the following hierarchy is used to allocate a block:
77  *   1) allocate the requested block.
78  *   2) allocate a rotationally optimal block in the same cylinder.
79  *   3) allocate a block in the same cylinder group.
80  *   4) quadradically rehash into other cylinder groups, until an
81  *      available block is located.
82  * If no block preference is given the following heirarchy is used
83  * to allocate a block:
84  *   1) allocate a block in the cylinder group that contains the
85  *      inode for the file.
86  *   2) quadradically rehash into other cylinder groups, until an
87  *      available block is located.
88  */
89 int
90 ffs_alloc(ip, lbn, bpref, size, cred, bnp)
91 	register struct inode *ip;
92 	daddr_t lbn, bpref;
93 	int size;
94 	struct ucred *cred;
95 	daddr_t *bnp;
96 {
97 	register struct fs *fs;
98 	daddr_t bno;
99 	int cg;
100 #ifdef QUOTA
101 	int error;
102 #endif
103 
104 
105 	*bnp = 0;
106 	fs = ip->i_fs;
107 #ifdef DIAGNOSTIC
108 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
109 		printf("dev = 0x%lx, bsize = %ld, size = %d, fs = %s\n",
110 		    (u_long)ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
111 		panic("ffs_alloc: bad size");
112 	}
113 	if (cred == NOCRED)
114 		panic("ffs_alloc: missing credential\n");
115 #endif /* DIAGNOSTIC */
116 	if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
117 		goto nospace;
118 	if (cred->cr_uid != 0 && freespace(fs, fs->fs_minfree) <= 0)
119 		goto nospace;
120 #ifdef QUOTA
121 	error = chkdq(ip, (long)btodb(size), cred, 0);
122 	if (error)
123 		return (error);
124 #endif
125 	if (bpref >= fs->fs_size)
126 		bpref = 0;
127 	if (bpref == 0)
128 		cg = ino_to_cg(fs, ip->i_number);
129 	else
130 		cg = dtog(fs, bpref);
131 	bno = (daddr_t)ffs_hashalloc(ip, cg, (long)bpref, size,
132 	    (u_long (*)())ffs_alloccg);
133 	if (bno > 0) {
134 		ip->i_blocks += btodb(size);
135 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
136 		*bnp = bno;
137 		return (0);
138 	}
139 #ifdef QUOTA
140 	/*
141 	 * Restore user's disk quota because allocation failed.
142 	 */
143 	(void) chkdq(ip, (long)-btodb(size), cred, FORCE);
144 #endif
145 nospace:
146 	ffs_fserr(fs, cred->cr_uid, "file system full");
147 	uprintf("\n%s: write failed, file system is full\n", fs->fs_fsmnt);
148 	return (ENOSPC);
149 }
150 
151 /*
152  * Reallocate a fragment to a bigger size
153  *
154  * The number and size of the old block is given, and a preference
155  * and new size is also specified. The allocator attempts to extend
156  * the original block. Failing that, the regular block allocator is
157  * invoked to get an appropriate block.
158  */
159 int
160 ffs_realloccg(ip, lbprev, bpref, osize, nsize, cred, bpp)
161 	register struct inode *ip;
162 	daddr_t lbprev;
163 	daddr_t bpref;
164 	int osize, nsize;
165 	struct ucred *cred;
166 	struct buf **bpp;
167 {
168 	register struct fs *fs;
169 	struct buf *bp;
170 	int cg, request, error;
171 	daddr_t bprev, bno;
172 
173 	*bpp = 0;
174 	fs = ip->i_fs;
175 #ifdef DIAGNOSTIC
176 	if ((u_int)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
177 	    (u_int)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
178 		printf(
179 		    "dev = 0x%lx, bsize = %d, osize = %d, nsize = %d, fs = %s\n",
180 		    (u_long)ip->i_dev, fs->fs_bsize, osize, nsize, fs->fs_fsmnt);
181 		panic("ffs_realloccg: bad size");
182 	}
183 	if (cred == NOCRED)
184 		panic("ffs_realloccg: missing credential\n");
185 #endif /* DIAGNOSTIC */
186 	if (cred->cr_uid != 0 && freespace(fs, fs->fs_minfree) <= 0)
187 		goto nospace;
188 	if ((bprev = ip->i_db[lbprev]) == 0) {
189 		printf("dev = 0x%lx, bsize = %ld, bprev = %ld, fs = %s\n",
190 		    (u_long) ip->i_dev, fs->fs_bsize, bprev, fs->fs_fsmnt);
191 		panic("ffs_realloccg: bad bprev");
192 	}
193 	/*
194 	 * Allocate the extra space in the buffer.
195 	 */
196 	error = bread(ITOV(ip), lbprev, osize, NOCRED, &bp);
197 	if (error) {
198 		brelse(bp);
199 		return (error);
200 	}
201 #ifdef QUOTA
202 	error = chkdq(ip, (long)btodb(nsize - osize), cred, 0);
203 	if (error) {
204 		brelse(bp);
205 		return (error);
206 	}
207 #endif
208 	/*
209 	 * Check for extension in the existing location.
210 	 */
211 	cg = dtog(fs, bprev);
212 	bno = ffs_fragextend(ip, cg, (long)bprev, osize, nsize);
213 	if (bno) {
214 		if (bp->b_blkno != fsbtodb(fs, bno))
215 			panic("bad blockno");
216 		ip->i_blocks += btodb(nsize - osize);
217 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
218 		allocbuf(bp, nsize, 0);
219 		bp->b_flags |= B_DONE;
220 		bzero((char *)bp->b_data + osize, (u_int)nsize - osize);
221 		*bpp = bp;
222 		return (0);
223 	}
224 	/*
225 	 * Allocate a new disk location.
226 	 */
227 	if (bpref >= fs->fs_size)
228 		bpref = 0;
229 	switch ((int)fs->fs_optim) {
230 	case FS_OPTSPACE:
231 		/*
232 		 * Allocate an exact sized fragment. Although this makes
233 		 * best use of space, we will waste time relocating it if
234 		 * the file continues to grow. If the fragmentation is
235 		 * less than half of the minimum free reserve, we choose
236 		 * to begin optimizing for time.
237 		 */
238 		request = nsize;
239 		if (fs->fs_minfree < 5 ||
240 		    fs->fs_cstotal.cs_nffree >
241 		    fs->fs_dsize * fs->fs_minfree / (2 * 100))
242 			break;
243 		log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
244 			fs->fs_fsmnt);
245 		fs->fs_optim = FS_OPTTIME;
246 		break;
247 	case FS_OPTTIME:
248 		/*
249 		 * At this point we have discovered a file that is trying to
250 		 * grow a small fragment to a larger fragment. To save time,
251 		 * we allocate a full sized block, then free the unused portion.
252 		 * If the file continues to grow, the `ffs_fragextend' call
253 		 * above will be able to grow it in place without further
254 		 * copying. If aberrant programs cause disk fragmentation to
255 		 * grow within 2% of the free reserve, we choose to begin
256 		 * optimizing for space.
257 		 */
258 		request = fs->fs_bsize;
259 		if (fs->fs_cstotal.cs_nffree <
260 		    fs->fs_dsize * (fs->fs_minfree - 2) / 100)
261 			break;
262 		log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
263 			fs->fs_fsmnt);
264 		fs->fs_optim = FS_OPTSPACE;
265 		break;
266 	default:
267 		printf("dev = 0x%lx, optim = %ld, fs = %s\n",
268 		    (u_long)ip->i_dev, fs->fs_optim, fs->fs_fsmnt);
269 		panic("ffs_realloccg: bad optim");
270 		/* NOTREACHED */
271 	}
272 	bno = (daddr_t)ffs_hashalloc(ip, cg, (long)bpref, request,
273 	    (u_long (*)())ffs_alloccg);
274 	if (bno > 0) {
275 		bp->b_blkno = fsbtodb(fs, bno);
276 		/* (void) vnode_pager_uncache(ITOV(ip)); */
277 		ffs_blkfree(ip, bprev, (long)osize);
278 		if (nsize < request)
279 			ffs_blkfree(ip, bno + numfrags(fs, nsize),
280 			    (long)(request - nsize));
281 		ip->i_blocks += btodb(nsize - osize);
282 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
283 		allocbuf(bp, nsize, 0);
284 		bp->b_flags |= B_DONE;
285 		bzero((char *)bp->b_data + osize, (u_int)nsize - osize);
286 		*bpp = bp;
287 		return (0);
288 	}
289 #ifdef QUOTA
290 	/*
291 	 * Restore user's disk quota because allocation failed.
292 	 */
293 	(void) chkdq(ip, (long)-btodb(nsize - osize), cred, FORCE);
294 #endif
295 	brelse(bp);
296 nospace:
297 	/*
298 	 * no space available
299 	 */
300 	ffs_fserr(fs, cred->cr_uid, "file system full");
301 	uprintf("\n%s: write failed, file system is full\n", fs->fs_fsmnt);
302 	return (ENOSPC);
303 }
304 
305 /*
306  * Reallocate a sequence of blocks into a contiguous sequence of blocks.
307  *
308  * The vnode and an array of buffer pointers for a range of sequential
309  * logical blocks to be made contiguous is given. The allocator attempts
310  * to find a range of sequential blocks starting as close as possible to
311  * an fs_rotdelay offset from the end of the allocation for the logical
312  * block immediately preceeding the current range. If successful, the
313  * physical block numbers in the buffer pointers and in the inode are
314  * changed to reflect the new allocation. If unsuccessful, the allocation
315  * is left unchanged. The success in doing the reallocation is returned.
316  * Note that the error return is not reflected back to the user. Rather
317  * the previous block allocation will be used.
318  */
319 #include <sys/sysctl.h>
320 int doasyncfree = 1;
321 #ifdef DEBUG
322 struct ctldebug debug14 = { "doasyncfree", &doasyncfree };
323 #endif
324 int
325 ffs_reallocblks(ap)
326 	struct vop_reallocblks_args /* {
327 		struct vnode *a_vp;
328 		struct cluster_save *a_buflist;
329 	} */ *ap;
330 {
331 	struct fs *fs;
332 	struct inode *ip;
333 	struct vnode *vp;
334 	struct buf *sbp, *ebp;
335 	daddr_t *bap, *sbap, *ebap = 0;
336 	struct cluster_save *buflist;
337 	daddr_t start_lbn, end_lbn, soff, newblk, blkno;
338 	struct indir start_ap[NIADDR + 1], end_ap[NIADDR + 1], *idp;
339 	int i, len, start_lvl, end_lvl, pref, ssize;
340 
341 	vp = ap->a_vp;
342 	ip = VTOI(vp);
343 	fs = ip->i_fs;
344 	if (fs->fs_contigsumsize <= 0)
345 		return (ENOSPC);
346 	buflist = ap->a_buflist;
347 	len = buflist->bs_nchildren;
348 	start_lbn = buflist->bs_children[0]->b_lblkno;
349 	end_lbn = start_lbn + len - 1;
350 #ifdef DIAGNOSTIC
351 	for (i = 1; i < len; i++)
352 		if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
353 			panic("ffs_reallocblks: non-cluster");
354 #endif
355 	/*
356 	 * If the latest allocation is in a new cylinder group, assume that
357 	 * the filesystem has decided to move and do not force it back to
358 	 * the previous cylinder group.
359 	 */
360 	if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
361 	    dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
362 		return (ENOSPC);
363 	if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
364 	    ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
365 		return (ENOSPC);
366 	/*
367 	 * Get the starting offset and block map for the first block.
368 	 */
369 	if (start_lvl == 0) {
370 		sbap = &ip->i_db[0];
371 		soff = start_lbn;
372 	} else {
373 		idp = &start_ap[start_lvl - 1];
374 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
375 			brelse(sbp);
376 			return (ENOSPC);
377 		}
378 		sbap = (daddr_t *)sbp->b_data;
379 		soff = idp->in_off;
380 	}
381 	/*
382 	 * Find the preferred location for the cluster.
383 	 */
384 	pref = ffs_blkpref(ip, start_lbn, soff, sbap);
385 	/*
386 	 * If the block range spans two block maps, get the second map.
387 	 */
388 	if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
389 		ssize = len;
390 	} else {
391 #ifdef DIAGNOSTIC
392 		if (start_ap[start_lvl-1].in_lbn == idp->in_lbn)
393 			panic("ffs_reallocblk: start == end");
394 #endif
395 		ssize = len - (idp->in_off + 1);
396 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
397 			goto fail;
398 		ebap = (daddr_t *)ebp->b_data;
399 	}
400 	/*
401 	 * Search the block map looking for an allocation of the desired size.
402 	 */
403 	if ((newblk = (daddr_t)ffs_hashalloc(ip, dtog(fs, pref), (long)pref,
404 	    len, (u_long (*)())ffs_clusteralloc)) == 0)
405 		goto fail;
406 	/*
407 	 * We have found a new contiguous block.
408 	 *
409 	 * First we have to replace the old block pointers with the new
410 	 * block pointers in the inode and indirect blocks associated
411 	 * with the file.
412 	 */
413 	blkno = newblk;
414 	for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
415 		if (i == ssize)
416 			bap = ebap;
417 #ifdef DIAGNOSTIC
418 		if (buflist->bs_children[i]->b_blkno != fsbtodb(fs, *bap))
419 			panic("ffs_reallocblks: alloc mismatch");
420 #endif
421 		*bap++ = blkno;
422 	}
423 	/*
424 	 * Next we must write out the modified inode and indirect blocks.
425 	 * For strict correctness, the writes should be synchronous since
426 	 * the old block values may have been written to disk. In practise
427 	 * they are almost never written, but if we are concerned about
428 	 * strict correctness, the `doasyncfree' flag should be set to zero.
429 	 *
430 	 * The test on `doasyncfree' should be changed to test a flag
431 	 * that shows whether the associated buffers and inodes have
432 	 * been written. The flag should be set when the cluster is
433 	 * started and cleared whenever the buffer or inode is flushed.
434 	 * We can then check below to see if it is set, and do the
435 	 * synchronous write only when it has been cleared.
436 	 */
437 	if (sbap != &ip->i_db[0]) {
438 		if (doasyncfree)
439 			bdwrite(sbp);
440 		else
441 			bwrite(sbp);
442 	} else {
443 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
444 		if (!doasyncfree)
445 			VOP_UPDATE(vp, &time, &time, 1);
446 	}
447 	if (ssize < len)
448 		if (doasyncfree)
449 			bdwrite(ebp);
450 		else
451 			bwrite(ebp);
452 	/*
453 	 * Last, free the old blocks and assign the new blocks to the buffers.
454 	 */
455 	for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
456 		ffs_blkfree(ip, dbtofsb(fs, buflist->bs_children[i]->b_blkno),
457 		    fs->fs_bsize);
458 		buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
459 	}
460 	return (0);
461 
462 fail:
463 	if (ssize < len)
464 		brelse(ebp);
465 	if (sbap != &ip->i_db[0])
466 		brelse(sbp);
467 	return (ENOSPC);
468 }
469 
470 /*
471  * Allocate an inode in the file system.
472  *
473  * If allocating a directory, use ffs_dirpref to select the inode.
474  * If allocating in a directory, the following hierarchy is followed:
475  *   1) allocate the preferred inode.
476  *   2) allocate an inode in the same cylinder group.
477  *   3) quadradically rehash into other cylinder groups, until an
478  *      available inode is located.
479  * If no inode preference is given the following heirarchy is used
480  * to allocate an inode:
481  *   1) allocate an inode in cylinder group 0.
482  *   2) quadradically rehash into other cylinder groups, until an
483  *      available inode is located.
484  */
485 int
486 ffs_valloc(ap)
487 	struct vop_valloc_args /* {
488 		struct vnode *a_pvp;
489 		int a_mode;
490 		struct ucred *a_cred;
491 		struct vnode **a_vpp;
492 	} */ *ap;
493 {
494 	register struct vnode *pvp = ap->a_pvp;
495 	register struct inode *pip;
496 	register struct fs *fs;
497 	register struct inode *ip;
498 	mode_t mode = ap->a_mode;
499 	ino_t ino, ipref;
500 	int cg, error;
501 
502 	*ap->a_vpp = NULL;
503 	pip = VTOI(pvp);
504 	fs = pip->i_fs;
505 	if (fs->fs_cstotal.cs_nifree == 0)
506 		goto noinodes;
507 
508 	if ((mode & IFMT) == IFDIR)
509 		ipref = ffs_dirpref(fs);
510 	else
511 		ipref = pip->i_number;
512 	if (ipref >= fs->fs_ncg * fs->fs_ipg)
513 		ipref = 0;
514 	cg = ino_to_cg(fs, ipref);
515 	ino = (ino_t)ffs_hashalloc(pip, cg, (long)ipref, mode, ffs_nodealloccg);
516 	if (ino == 0)
517 		goto noinodes;
518 	error = VFS_VGET(pvp->v_mount, ino, ap->a_vpp);
519 	if (error) {
520 		VOP_VFREE(pvp, ino, mode);
521 		return (error);
522 	}
523 	ip = VTOI(*ap->a_vpp);
524 	if (ip->i_mode) {
525 		printf("mode = 0%o, inum = %ld, fs = %s\n",
526 		    ip->i_mode, ip->i_number, fs->fs_fsmnt);
527 		panic("ffs_valloc: dup alloc");
528 	}
529 	if (ip->i_blocks) {				/* XXX */
530 		printf("free inode %s/%ld had %ld blocks\n",
531 		    fs->fs_fsmnt, ino, ip->i_blocks);
532 		ip->i_blocks = 0;
533 	}
534 	ip->i_flags = 0;
535 	/*
536 	 * Set up a new generation number for this inode.
537 	 */
538 	if (++nextgennumber < (u_long)time.tv_sec)
539 		nextgennumber = time.tv_sec;
540 	ip->i_gen = nextgennumber;
541 	return (0);
542 noinodes:
543 	ffs_fserr(fs, ap->a_cred->cr_uid, "out of inodes");
544 	uprintf("\n%s: create/symlink failed, no inodes free\n", fs->fs_fsmnt);
545 	return (ENOSPC);
546 }
547 
548 /*
549  * Find a cylinder to place a directory.
550  *
551  * The policy implemented by this algorithm is to select from
552  * among those cylinder groups with above the average number of
553  * free inodes, the one with the smallest number of directories.
554  */
555 static ino_t
556 ffs_dirpref(fs)
557 	register struct fs *fs;
558 {
559 	int cg, minndir, mincg, avgifree;
560 
561 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
562 	minndir = fs->fs_ipg;
563 	mincg = 0;
564 	for (cg = 0; cg < fs->fs_ncg; cg++)
565 		if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
566 		    fs->fs_cs(fs, cg).cs_nifree >= avgifree) {
567 			mincg = cg;
568 			minndir = fs->fs_cs(fs, cg).cs_ndir;
569 		}
570 	return ((ino_t)(fs->fs_ipg * mincg));
571 }
572 
573 /*
574  * Select the desired position for the next block in a file.  The file is
575  * logically divided into sections. The first section is composed of the
576  * direct blocks. Each additional section contains fs_maxbpg blocks.
577  *
578  * If no blocks have been allocated in the first section, the policy is to
579  * request a block in the same cylinder group as the inode that describes
580  * the file. If no blocks have been allocated in any other section, the
581  * policy is to place the section in a cylinder group with a greater than
582  * average number of free blocks.  An appropriate cylinder group is found
583  * by using a rotor that sweeps the cylinder groups. When a new group of
584  * blocks is needed, the sweep begins in the cylinder group following the
585  * cylinder group from which the previous allocation was made. The sweep
586  * continues until a cylinder group with greater than the average number
587  * of free blocks is found. If the allocation is for the first block in an
588  * indirect block, the information on the previous allocation is unavailable;
589  * here a best guess is made based upon the logical block number being
590  * allocated.
591  *
592  * If a section is already partially allocated, the policy is to
593  * contiguously allocate fs_maxcontig blocks.  The end of one of these
594  * contiguous blocks and the beginning of the next is physically separated
595  * so that the disk head will be in transit between them for at least
596  * fs_rotdelay milliseconds.  This is to allow time for the processor to
597  * schedule another I/O transfer.
598  */
599 daddr_t
600 ffs_blkpref(ip, lbn, indx, bap)
601 	struct inode *ip;
602 	daddr_t lbn;
603 	int indx;
604 	daddr_t *bap;
605 {
606 	register struct fs *fs;
607 	register int cg;
608 	int avgbfree, startcg;
609 	daddr_t nextblk;
610 
611 	fs = ip->i_fs;
612 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
613 		if (lbn < NDADDR) {
614 			cg = ino_to_cg(fs, ip->i_number);
615 			return (fs->fs_fpg * cg + fs->fs_frag);
616 		}
617 		/*
618 		 * Find a cylinder with greater than average number of
619 		 * unused data blocks.
620 		 */
621 		if (indx == 0 || bap[indx - 1] == 0)
622 			startcg =
623 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
624 		else
625 			startcg = dtog(fs, bap[indx - 1]) + 1;
626 		startcg %= fs->fs_ncg;
627 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
628 		for (cg = startcg; cg < fs->fs_ncg; cg++)
629 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
630 				fs->fs_cgrotor = cg;
631 				return (fs->fs_fpg * cg + fs->fs_frag);
632 			}
633 		for (cg = 0; cg <= startcg; cg++)
634 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
635 				fs->fs_cgrotor = cg;
636 				return (fs->fs_fpg * cg + fs->fs_frag);
637 			}
638 		return (NULL);
639 	}
640 	/*
641 	 * One or more previous blocks have been laid out. If less
642 	 * than fs_maxcontig previous blocks are contiguous, the
643 	 * next block is requested contiguously, otherwise it is
644 	 * requested rotationally delayed by fs_rotdelay milliseconds.
645 	 */
646 	nextblk = bap[indx - 1] + fs->fs_frag;
647 	if (indx < fs->fs_maxcontig || bap[indx - fs->fs_maxcontig] +
648 	    blkstofrags(fs, fs->fs_maxcontig) != nextblk)
649 		return (nextblk);
650 	if (fs->fs_rotdelay != 0)
651 		/*
652 		 * Here we convert ms of delay to frags as:
653 		 * (frags) = (ms) * (rev/sec) * (sect/rev) /
654 		 *	((sect/frag) * (ms/sec))
655 		 * then round up to the next block.
656 		 */
657 		nextblk += roundup(fs->fs_rotdelay * fs->fs_rps * fs->fs_nsect /
658 		    (NSPF(fs) * 1000), fs->fs_frag);
659 	return (nextblk);
660 }
661 
662 /*
663  * Implement the cylinder overflow algorithm.
664  *
665  * The policy implemented by this algorithm is:
666  *   1) allocate the block in its requested cylinder group.
667  *   2) quadradically rehash on the cylinder group number.
668  *   3) brute force search for a free block.
669  */
670 /*VARARGS5*/
671 static u_long
672 ffs_hashalloc(ip, cg, pref, size, allocator)
673 	struct inode *ip;
674 	int cg;
675 	long pref;
676 	int size;	/* size for data blocks, mode for inodes */
677 	u_long (*allocator)();
678 {
679 	register struct fs *fs;
680 	long result;
681 	int i, icg = cg;
682 
683 	fs = ip->i_fs;
684 	/*
685 	 * 1: preferred cylinder group
686 	 */
687 	result = (*allocator)(ip, cg, pref, size);
688 	if (result)
689 		return (result);
690 	/*
691 	 * 2: quadratic rehash
692 	 */
693 	for (i = 1; i < fs->fs_ncg; i *= 2) {
694 		cg += i;
695 		if (cg >= fs->fs_ncg)
696 			cg -= fs->fs_ncg;
697 		result = (*allocator)(ip, cg, 0, size);
698 		if (result)
699 			return (result);
700 	}
701 	/*
702 	 * 3: brute force search
703 	 * Note that we start at i == 2, since 0 was checked initially,
704 	 * and 1 is always checked in the quadratic rehash.
705 	 */
706 	cg = (icg + 2) % fs->fs_ncg;
707 	for (i = 2; i < fs->fs_ncg; i++) {
708 		result = (*allocator)(ip, cg, 0, size);
709 		if (result)
710 			return (result);
711 		cg++;
712 		if (cg == fs->fs_ncg)
713 			cg = 0;
714 	}
715 	return (NULL);
716 }
717 
718 /*
719  * Determine whether a fragment can be extended.
720  *
721  * Check to see if the necessary fragments are available, and
722  * if they are, allocate them.
723  */
724 static daddr_t
725 ffs_fragextend(ip, cg, bprev, osize, nsize)
726 	struct inode *ip;
727 	int cg;
728 	long bprev;
729 	int osize, nsize;
730 {
731 	register struct fs *fs;
732 	register struct cg *cgp;
733 	struct buf *bp;
734 	long bno;
735 	int frags, bbase;
736 	int i, error;
737 
738 	fs = ip->i_fs;
739 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
740 		return (NULL);
741 	frags = numfrags(fs, nsize);
742 	bbase = fragnum(fs, bprev);
743 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
744 		/* cannot extend across a block boundary */
745 		return (NULL);
746 	}
747 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
748 		(int)fs->fs_cgsize, NOCRED, &bp);
749 	if (error) {
750 		brelse(bp);
751 		return (NULL);
752 	}
753 	cgp = (struct cg *)bp->b_data;
754 	if (!cg_chkmagic(cgp)) {
755 		brelse(bp);
756 		return (NULL);
757 	}
758 	cgp->cg_time = time.tv_sec;
759 	bno = dtogd(fs, bprev);
760 	for (i = numfrags(fs, osize); i < frags; i++)
761 		if (isclr(cg_blksfree(cgp), bno + i)) {
762 			brelse(bp);
763 			return (NULL);
764 		}
765 	/*
766 	 * the current fragment can be extended
767 	 * deduct the count on fragment being extended into
768 	 * increase the count on the remaining fragment (if any)
769 	 * allocate the extended piece
770 	 */
771 	for (i = frags; i < fs->fs_frag - bbase; i++)
772 		if (isclr(cg_blksfree(cgp), bno + i))
773 			break;
774 	cgp->cg_frsum[i - numfrags(fs, osize)]--;
775 	if (i != frags)
776 		cgp->cg_frsum[i - frags]++;
777 	for (i = numfrags(fs, osize); i < frags; i++) {
778 		clrbit(cg_blksfree(cgp), bno + i);
779 		cgp->cg_cs.cs_nffree--;
780 		fs->fs_cstotal.cs_nffree--;
781 		fs->fs_cs(fs, cg).cs_nffree--;
782 	}
783 	fs->fs_fmod = 1;
784 	bdwrite(bp);
785 	return (bprev);
786 }
787 
788 /*
789  * Determine whether a block can be allocated.
790  *
791  * Check to see if a block of the appropriate size is available,
792  * and if it is, allocate it.
793  */
794 static daddr_t
795 ffs_alloccg(ip, cg, bpref, size)
796 	struct inode *ip;
797 	int cg;
798 	daddr_t bpref;
799 	int size;
800 {
801 	register struct fs *fs;
802 	register struct cg *cgp;
803 	struct buf *bp;
804 	register int i;
805 	int error, bno, frags, allocsiz;
806 
807 	fs = ip->i_fs;
808 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
809 		return (NULL);
810 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
811 		(int)fs->fs_cgsize, NOCRED, &bp);
812 	if (error) {
813 		brelse(bp);
814 		return (NULL);
815 	}
816 	cgp = (struct cg *)bp->b_data;
817 	if (!cg_chkmagic(cgp) ||
818 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize)) {
819 		brelse(bp);
820 		return (NULL);
821 	}
822 	cgp->cg_time = time.tv_sec;
823 	if (size == fs->fs_bsize) {
824 		bno = ffs_alloccgblk(fs, cgp, bpref);
825 		bdwrite(bp);
826 		return (bno);
827 	}
828 	/*
829 	 * check to see if any fragments are already available
830 	 * allocsiz is the size which will be allocated, hacking
831 	 * it down to a smaller size if necessary
832 	 */
833 	frags = numfrags(fs, size);
834 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
835 		if (cgp->cg_frsum[allocsiz] != 0)
836 			break;
837 	if (allocsiz == fs->fs_frag) {
838 		/*
839 		 * no fragments were available, so a block will be
840 		 * allocated, and hacked up
841 		 */
842 		if (cgp->cg_cs.cs_nbfree == 0) {
843 			brelse(bp);
844 			return (NULL);
845 		}
846 		bno = ffs_alloccgblk(fs, cgp, bpref);
847 		bpref = dtogd(fs, bno);
848 		for (i = frags; i < fs->fs_frag; i++)
849 			setbit(cg_blksfree(cgp), bpref + i);
850 		i = fs->fs_frag - frags;
851 		cgp->cg_cs.cs_nffree += i;
852 		fs->fs_cstotal.cs_nffree += i;
853 		fs->fs_cs(fs, cg).cs_nffree += i;
854 		fs->fs_fmod = 1;
855 		cgp->cg_frsum[i]++;
856 		bdwrite(bp);
857 		return (bno);
858 	}
859 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
860 	if (bno < 0) {
861 		brelse(bp);
862 		return (NULL);
863 	}
864 	for (i = 0; i < frags; i++)
865 		clrbit(cg_blksfree(cgp), bno + i);
866 	cgp->cg_cs.cs_nffree -= frags;
867 	fs->fs_cstotal.cs_nffree -= frags;
868 	fs->fs_cs(fs, cg).cs_nffree -= frags;
869 	fs->fs_fmod = 1;
870 	cgp->cg_frsum[allocsiz]--;
871 	if (frags != allocsiz)
872 		cgp->cg_frsum[allocsiz - frags]++;
873 	bdwrite(bp);
874 	return (cg * fs->fs_fpg + bno);
875 }
876 
877 /*
878  * Allocate a block in a cylinder group.
879  *
880  * This algorithm implements the following policy:
881  *   1) allocate the requested block.
882  *   2) allocate a rotationally optimal block in the same cylinder.
883  *   3) allocate the next available block on the block rotor for the
884  *      specified cylinder group.
885  * Note that this routine only allocates fs_bsize blocks; these
886  * blocks may be fragmented by the routine that allocates them.
887  */
888 static daddr_t
889 ffs_alloccgblk(fs, cgp, bpref)
890 	register struct fs *fs;
891 	register struct cg *cgp;
892 	daddr_t bpref;
893 {
894 	daddr_t bno, blkno;
895 	int cylno, pos, delta;
896 	short *cylbp;
897 	register int i;
898 
899 	if (bpref == 0 || dtog(fs, bpref) != cgp->cg_cgx) {
900 		bpref = cgp->cg_rotor;
901 		goto norot;
902 	}
903 	bpref = blknum(fs, bpref);
904 	bpref = dtogd(fs, bpref);
905 	/*
906 	 * if the requested block is available, use it
907 	 */
908 	if (ffs_isblock(fs, cg_blksfree(cgp), fragstoblks(fs, bpref))) {
909 		bno = bpref;
910 		goto gotit;
911 	}
912 	/*
913 	 * check for a block available on the same cylinder
914 	 */
915 	cylno = cbtocylno(fs, bpref);
916 	if (cg_blktot(cgp)[cylno] == 0)
917 		goto norot;
918 	if (fs->fs_cpc == 0) {
919 		/*
920 		 * Block layout information is not available.
921 		 * Leaving bpref unchanged means we take the
922 		 * next available free block following the one
923 		 * we just allocated. Hopefully this will at
924 		 * least hit a track cache on drives of unknown
925 		 * geometry (e.g. SCSI).
926 		 */
927 		goto norot;
928 	}
929 	/*
930 	 * check the summary information to see if a block is
931 	 * available in the requested cylinder starting at the
932 	 * requested rotational position and proceeding around.
933 	 */
934 	cylbp = cg_blks(fs, cgp, cylno);
935 	pos = cbtorpos(fs, bpref);
936 	for (i = pos; i < fs->fs_nrpos; i++)
937 		if (cylbp[i] > 0)
938 			break;
939 	if (i == fs->fs_nrpos)
940 		for (i = 0; i < pos; i++)
941 			if (cylbp[i] > 0)
942 				break;
943 	if (cylbp[i] > 0) {
944 		/*
945 		 * found a rotational position, now find the actual
946 		 * block. A panic if none is actually there.
947 		 */
948 		pos = cylno % fs->fs_cpc;
949 		bno = (cylno - pos) * fs->fs_spc / NSPB(fs);
950 		if (fs_postbl(fs, pos)[i] == -1) {
951 			printf("pos = %d, i = %d, fs = %s\n",
952 			    pos, i, fs->fs_fsmnt);
953 			panic("ffs_alloccgblk: cyl groups corrupted");
954 		}
955 		for (i = fs_postbl(fs, pos)[i];; ) {
956 			if (ffs_isblock(fs, cg_blksfree(cgp), bno + i)) {
957 				bno = blkstofrags(fs, (bno + i));
958 				goto gotit;
959 			}
960 			delta = fs_rotbl(fs)[i];
961 			if (delta <= 0 ||
962 			    delta + i > fragstoblks(fs, fs->fs_fpg))
963 				break;
964 			i += delta;
965 		}
966 		printf("pos = %d, i = %d, fs = %s\n", pos, i, fs->fs_fsmnt);
967 		panic("ffs_alloccgblk: can't find blk in cyl");
968 	}
969 norot:
970 	/*
971 	 * no blocks in the requested cylinder, so take next
972 	 * available one in this cylinder group.
973 	 */
974 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
975 	if (bno < 0)
976 		return (NULL);
977 	cgp->cg_rotor = bno;
978 gotit:
979 	blkno = fragstoblks(fs, bno);
980 	ffs_clrblock(fs, cg_blksfree(cgp), (long)blkno);
981 	ffs_clusteracct(fs, cgp, blkno, -1);
982 	cgp->cg_cs.cs_nbfree--;
983 	fs->fs_cstotal.cs_nbfree--;
984 	fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
985 	cylno = cbtocylno(fs, bno);
986 	cg_blks(fs, cgp, cylno)[cbtorpos(fs, bno)]--;
987 	cg_blktot(cgp)[cylno]--;
988 	fs->fs_fmod = 1;
989 	return (cgp->cg_cgx * fs->fs_fpg + bno);
990 }
991 
992 /*
993  * Determine whether a cluster can be allocated.
994  *
995  * We do not currently check for optimal rotational layout if there
996  * are multiple choices in the same cylinder group. Instead we just
997  * take the first one that we find following bpref.
998  */
999 static daddr_t
1000 ffs_clusteralloc(ip, cg, bpref, len)
1001 	struct inode *ip;
1002 	int cg;
1003 	daddr_t bpref;
1004 	int len;
1005 {
1006 	register struct fs *fs;
1007 	register struct cg *cgp;
1008 	struct buf *bp;
1009 	int i, run, bno, bit, map;
1010 	u_char *mapp;
1011 
1012 	fs = ip->i_fs;
1013 	if (fs->fs_cs(fs, cg).cs_nbfree < len)
1014 		return (NULL);
1015 	if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize,
1016 	    NOCRED, &bp))
1017 		goto fail;
1018 	cgp = (struct cg *)bp->b_data;
1019 	if (!cg_chkmagic(cgp))
1020 		goto fail;
1021 	/*
1022 	 * Check to see if a cluster of the needed size (or bigger) is
1023 	 * available in this cylinder group.
1024 	 */
1025 	for (i = len; i <= fs->fs_contigsumsize; i++)
1026 		if (cg_clustersum(cgp)[i] > 0)
1027 			break;
1028 	if (i > fs->fs_contigsumsize)
1029 		goto fail;
1030 	/*
1031 	 * Search the cluster map to find a big enough cluster.
1032 	 * We take the first one that we find, even if it is larger
1033 	 * than we need as we prefer to get one close to the previous
1034 	 * block allocation. We do not search before the current
1035 	 * preference point as we do not want to allocate a block
1036 	 * that is allocated before the previous one (as we will
1037 	 * then have to wait for another pass of the elevator
1038 	 * algorithm before it will be read). We prefer to fail and
1039 	 * be recalled to try an allocation in the next cylinder group.
1040 	 */
1041 	if (dtog(fs, bpref) != cg)
1042 		bpref = 0;
1043 	else
1044 		bpref = fragstoblks(fs, dtogd(fs, blknum(fs, bpref)));
1045 	mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1046 	map = *mapp++;
1047 	bit = 1 << (bpref % NBBY);
1048 	for (run = 0, i = bpref; i < cgp->cg_nclusterblks; i++) {
1049 		if ((map & bit) == 0) {
1050 			run = 0;
1051 		} else {
1052 			run++;
1053 			if (run == len)
1054 				break;
1055 		}
1056 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
1057 			bit <<= 1;
1058 		} else {
1059 			map = *mapp++;
1060 			bit = 1;
1061 		}
1062 	}
1063 	if (i == cgp->cg_nclusterblks)
1064 		goto fail;
1065 	/*
1066 	 * Allocate the cluster that we have found.
1067 	 */
1068 	bno = cg * fs->fs_fpg + blkstofrags(fs, i - run + 1);
1069 	len = blkstofrags(fs, len);
1070 	for (i = 0; i < len; i += fs->fs_frag)
1071 		if (ffs_alloccgblk(fs, cgp, bno + i) != bno + i)
1072 			panic("ffs_clusteralloc: lost block");
1073 	brelse(bp);
1074 	return (bno);
1075 
1076 fail:
1077 	brelse(bp);
1078 	return (0);
1079 }
1080 
1081 /*
1082  * Determine whether an inode can be allocated.
1083  *
1084  * Check to see if an inode is available, and if it is,
1085  * allocate it using the following policy:
1086  *   1) allocate the requested inode.
1087  *   2) allocate the next available inode after the requested
1088  *      inode in the specified cylinder group.
1089  */
1090 static ino_t
1091 ffs_nodealloccg(ip, cg, ipref, mode)
1092 	struct inode *ip;
1093 	int cg;
1094 	daddr_t ipref;
1095 	int mode;
1096 {
1097 	register struct fs *fs;
1098 	register struct cg *cgp;
1099 	struct buf *bp;
1100 	int error, start, len, loc, map, i;
1101 
1102 	fs = ip->i_fs;
1103 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
1104 		return (NULL);
1105 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1106 		(int)fs->fs_cgsize, NOCRED, &bp);
1107 	if (error) {
1108 		brelse(bp);
1109 		return (NULL);
1110 	}
1111 	cgp = (struct cg *)bp->b_data;
1112 	if (!cg_chkmagic(cgp) || cgp->cg_cs.cs_nifree == 0) {
1113 		brelse(bp);
1114 		return (NULL);
1115 	}
1116 	cgp->cg_time = time.tv_sec;
1117 	if (ipref) {
1118 		ipref %= fs->fs_ipg;
1119 		if (isclr(cg_inosused(cgp), ipref))
1120 			goto gotit;
1121 	}
1122 	start = cgp->cg_irotor / NBBY;
1123 	len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
1124 	loc = skpc(0xff, len, &cg_inosused(cgp)[start]);
1125 	if (loc == 0) {
1126 		len = start + 1;
1127 		start = 0;
1128 		loc = skpc(0xff, len, &cg_inosused(cgp)[0]);
1129 		if (loc == 0) {
1130 			printf("cg = %d, irotor = %ld, fs = %s\n",
1131 			    cg, cgp->cg_irotor, fs->fs_fsmnt);
1132 			panic("ffs_nodealloccg: map corrupted");
1133 			/* NOTREACHED */
1134 		}
1135 	}
1136 	i = start + len - loc;
1137 	map = cg_inosused(cgp)[i];
1138 	ipref = i * NBBY;
1139 	for (i = 1; i < (1 << NBBY); i <<= 1, ipref++) {
1140 		if ((map & i) == 0) {
1141 			cgp->cg_irotor = ipref;
1142 			goto gotit;
1143 		}
1144 	}
1145 	printf("fs = %s\n", fs->fs_fsmnt);
1146 	panic("ffs_nodealloccg: block not in map");
1147 	/* NOTREACHED */
1148 gotit:
1149 	setbit(cg_inosused(cgp), ipref);
1150 	cgp->cg_cs.cs_nifree--;
1151 	fs->fs_cstotal.cs_nifree--;
1152 	fs->fs_cs(fs, cg).cs_nifree--;
1153 	fs->fs_fmod = 1;
1154 	if ((mode & IFMT) == IFDIR) {
1155 		cgp->cg_cs.cs_ndir++;
1156 		fs->fs_cstotal.cs_ndir++;
1157 		fs->fs_cs(fs, cg).cs_ndir++;
1158 	}
1159 	bdwrite(bp);
1160 	return (cg * fs->fs_ipg + ipref);
1161 }
1162 
1163 /*
1164  * Free a block or fragment.
1165  *
1166  * The specified block or fragment is placed back in the
1167  * free map. If a fragment is deallocated, a possible
1168  * block reassembly is checked.
1169  */
1170 void
1171 ffs_blkfree(ip, bno, size)
1172 	register struct inode *ip;
1173 	daddr_t bno;
1174 	long size;
1175 {
1176 	register struct fs *fs;
1177 	register struct cg *cgp;
1178 	struct buf *bp;
1179 	daddr_t blkno;
1180 	int i, error, cg, blk, frags, bbase;
1181 
1182 	fs = ip->i_fs;
1183 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
1184 		printf("dev = 0x%lx, bsize = %ld, size = %ld, fs = %s\n",
1185 		    (u_long)ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
1186 		panic("blkfree: bad size");
1187 	}
1188 	cg = dtog(fs, bno);
1189 	if ((u_int)bno >= fs->fs_size) {
1190 		printf("bad block %ld, ino %ld\n", bno, ip->i_number);
1191 		ffs_fserr(fs, ip->i_uid, "bad block");
1192 		return;
1193 	}
1194 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1195 		(int)fs->fs_cgsize, NOCRED, &bp);
1196 	if (error) {
1197 		brelse(bp);
1198 		return;
1199 	}
1200 	cgp = (struct cg *)bp->b_data;
1201 	if (!cg_chkmagic(cgp)) {
1202 		brelse(bp);
1203 		return;
1204 	}
1205 	cgp->cg_time = time.tv_sec;
1206 	bno = dtogd(fs, bno);
1207 	if (size == fs->fs_bsize) {
1208 		blkno = fragstoblks(fs, bno);
1209 		if (ffs_isblock(fs, cg_blksfree(cgp), blkno)) {
1210 			printf("dev = 0x%lx, block = %ld, fs = %s\n",
1211 			    (u_long) ip->i_dev, bno, fs->fs_fsmnt);
1212 			panic("blkfree: freeing free block");
1213 		}
1214 		ffs_setblock(fs, cg_blksfree(cgp), blkno);
1215 		ffs_clusteracct(fs, cgp, blkno, 1);
1216 		cgp->cg_cs.cs_nbfree++;
1217 		fs->fs_cstotal.cs_nbfree++;
1218 		fs->fs_cs(fs, cg).cs_nbfree++;
1219 		i = cbtocylno(fs, bno);
1220 		cg_blks(fs, cgp, i)[cbtorpos(fs, bno)]++;
1221 		cg_blktot(cgp)[i]++;
1222 	} else {
1223 		bbase = bno - fragnum(fs, bno);
1224 		/*
1225 		 * decrement the counts associated with the old frags
1226 		 */
1227 		blk = blkmap(fs, cg_blksfree(cgp), bbase);
1228 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
1229 		/*
1230 		 * deallocate the fragment
1231 		 */
1232 		frags = numfrags(fs, size);
1233 		for (i = 0; i < frags; i++) {
1234 			if (isset(cg_blksfree(cgp), bno + i)) {
1235 				printf("dev = 0x%lx, block = %ld, fs = %s\n",
1236 				    (u_long) ip->i_dev, bno + i, fs->fs_fsmnt);
1237 				panic("blkfree: freeing free frag");
1238 			}
1239 			setbit(cg_blksfree(cgp), bno + i);
1240 		}
1241 		cgp->cg_cs.cs_nffree += i;
1242 		fs->fs_cstotal.cs_nffree += i;
1243 		fs->fs_cs(fs, cg).cs_nffree += i;
1244 		/*
1245 		 * add back in counts associated with the new frags
1246 		 */
1247 		blk = blkmap(fs, cg_blksfree(cgp), bbase);
1248 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
1249 		/*
1250 		 * if a complete block has been reassembled, account for it
1251 		 */
1252 		blkno = fragstoblks(fs, bbase);
1253 		if (ffs_isblock(fs, cg_blksfree(cgp), blkno)) {
1254 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
1255 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
1256 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
1257 			ffs_clusteracct(fs, cgp, blkno, 1);
1258 			cgp->cg_cs.cs_nbfree++;
1259 			fs->fs_cstotal.cs_nbfree++;
1260 			fs->fs_cs(fs, cg).cs_nbfree++;
1261 			i = cbtocylno(fs, bbase);
1262 			cg_blks(fs, cgp, i)[cbtorpos(fs, bbase)]++;
1263 			cg_blktot(cgp)[i]++;
1264 		}
1265 	}
1266 	fs->fs_fmod = 1;
1267 	bdwrite(bp);
1268 }
1269 
1270 /*
1271  * Free an inode.
1272  *
1273  * The specified inode is placed back in the free map.
1274  */
1275 int
1276 ffs_vfree(ap)
1277 	struct vop_vfree_args /* {
1278 		struct vnode *a_pvp;
1279 		ino_t a_ino;
1280 		int a_mode;
1281 	} */ *ap;
1282 {
1283 	register struct fs *fs;
1284 	register struct cg *cgp;
1285 	register struct inode *pip;
1286 	ino_t ino = ap->a_ino;
1287 	struct buf *bp;
1288 	int error, cg;
1289 
1290 	pip = VTOI(ap->a_pvp);
1291 	fs = pip->i_fs;
1292 	if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
1293 		panic("ifree: range: dev = 0x%x, ino = %d, fs = %s\n",
1294 		    pip->i_dev, ino, fs->fs_fsmnt);
1295 	cg = ino_to_cg(fs, ino);
1296 	error = bread(pip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1297 		(int)fs->fs_cgsize, NOCRED, &bp);
1298 	if (error) {
1299 		brelse(bp);
1300 		return (0);
1301 	}
1302 	cgp = (struct cg *)bp->b_data;
1303 	if (!cg_chkmagic(cgp)) {
1304 		brelse(bp);
1305 		return (0);
1306 	}
1307 	cgp->cg_time = time.tv_sec;
1308 	ino %= fs->fs_ipg;
1309 	if (isclr(cg_inosused(cgp), ino)) {
1310 		printf("dev = 0x%lx, ino = %ld, fs = %s\n",
1311 		    (u_long)pip->i_dev, ino, fs->fs_fsmnt);
1312 		if (fs->fs_ronly == 0)
1313 			panic("ifree: freeing free inode");
1314 	}
1315 	clrbit(cg_inosused(cgp), ino);
1316 	if (ino < cgp->cg_irotor)
1317 		cgp->cg_irotor = ino;
1318 	cgp->cg_cs.cs_nifree++;
1319 	fs->fs_cstotal.cs_nifree++;
1320 	fs->fs_cs(fs, cg).cs_nifree++;
1321 	if ((ap->a_mode & IFMT) == IFDIR) {
1322 		cgp->cg_cs.cs_ndir--;
1323 		fs->fs_cstotal.cs_ndir--;
1324 		fs->fs_cs(fs, cg).cs_ndir--;
1325 	}
1326 	fs->fs_fmod = 1;
1327 	bdwrite(bp);
1328 	return (0);
1329 }
1330 
1331 /*
1332  * Find a block of the specified size in the specified cylinder group.
1333  *
1334  * It is a panic if a request is made to find a block if none are
1335  * available.
1336  */
1337 static daddr_t
1338 ffs_mapsearch(fs, cgp, bpref, allocsiz)
1339 	register struct fs *fs;
1340 	register struct cg *cgp;
1341 	daddr_t bpref;
1342 	int allocsiz;
1343 {
1344 	daddr_t bno;
1345 	int start, len, loc, i;
1346 	int blk, field, subfield, pos;
1347 
1348 	/*
1349 	 * find the fragment by searching through the free block
1350 	 * map for an appropriate bit pattern
1351 	 */
1352 	if (bpref)
1353 		start = dtogd(fs, bpref) / NBBY;
1354 	else
1355 		start = cgp->cg_frotor / NBBY;
1356 	len = howmany(fs->fs_fpg, NBBY) - start;
1357 	loc = scanc((u_int)len, (u_char *)&cg_blksfree(cgp)[start],
1358 		(u_char *)fragtbl[fs->fs_frag],
1359 		(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
1360 	if (loc == 0) {
1361 		len = start + 1;
1362 		start = 0;
1363 		loc = scanc((u_int)len, (u_char *)&cg_blksfree(cgp)[0],
1364 			(u_char *)fragtbl[fs->fs_frag],
1365 			(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
1366 		if (loc == 0) {
1367 			printf("start = %d, len = %d, fs = %s\n",
1368 			    start, len, fs->fs_fsmnt);
1369 			panic("ffs_alloccg: map corrupted");
1370 			/* NOTREACHED */
1371 		}
1372 	}
1373 	bno = (start + len - loc) * NBBY;
1374 	cgp->cg_frotor = bno;
1375 	/*
1376 	 * found the byte in the map
1377 	 * sift through the bits to find the selected frag
1378 	 */
1379 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
1380 		blk = blkmap(fs, cg_blksfree(cgp), bno);
1381 		blk <<= 1;
1382 		field = around[allocsiz];
1383 		subfield = inside[allocsiz];
1384 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
1385 			if ((blk & field) == subfield)
1386 				return (bno + pos);
1387 			field <<= 1;
1388 			subfield <<= 1;
1389 		}
1390 	}
1391 	printf("bno = %lu, fs = %s\n", (u_long)bno, fs->fs_fsmnt);
1392 	panic("ffs_alloccg: block not in map");
1393 	return (-1);
1394 }
1395 
1396 /*
1397  * Update the cluster map because of an allocation or free.
1398  *
1399  * Cnt == 1 means free; cnt == -1 means allocating.
1400  */
1401 void
1402 ffs_clusteracct(fs, cgp, blkno, cnt)
1403 	struct fs *fs;
1404 	struct cg *cgp;
1405 	daddr_t blkno;
1406 	int cnt;
1407 {
1408 	long *sump;
1409 	u_char *freemapp, *mapp;
1410 	int i, start, end, forw, back, map, bit;
1411 
1412 	if (fs->fs_contigsumsize <= 0)
1413 		return;
1414 	freemapp = cg_clustersfree(cgp);
1415 	sump = cg_clustersum(cgp);
1416 	/*
1417 	 * Allocate or clear the actual block.
1418 	 */
1419 	if (cnt > 0)
1420 		setbit(freemapp, blkno);
1421 	else
1422 		clrbit(freemapp, blkno);
1423 	/*
1424 	 * Find the size of the cluster going forward.
1425 	 */
1426 	start = blkno + 1;
1427 	end = start + fs->fs_contigsumsize;
1428 	if (end >= cgp->cg_nclusterblks)
1429 		end = cgp->cg_nclusterblks;
1430 	mapp = &freemapp[start / NBBY];
1431 	map = *mapp++;
1432 	bit = 1 << (start % NBBY);
1433 	for (i = start; i < end; i++) {
1434 		if ((map & bit) == 0)
1435 			break;
1436 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
1437 			bit <<= 1;
1438 		} else {
1439 			map = *mapp++;
1440 			bit = 1;
1441 		}
1442 	}
1443 	forw = i - start;
1444 	/*
1445 	 * Find the size of the cluster going backward.
1446 	 */
1447 	start = blkno - 1;
1448 	end = start - fs->fs_contigsumsize;
1449 	if (end < 0)
1450 		end = -1;
1451 	mapp = &freemapp[start / NBBY];
1452 	map = *mapp--;
1453 	bit = 1 << (start % NBBY);
1454 	for (i = start; i > end; i--) {
1455 		if ((map & bit) == 0)
1456 			break;
1457 		if ((i & (NBBY - 1)) != 0) {
1458 			bit >>= 1;
1459 		} else {
1460 			map = *mapp--;
1461 			bit = 1 << (NBBY - 1);
1462 		}
1463 	}
1464 	back = start - i;
1465 	/*
1466 	 * Account for old cluster and the possibly new forward and
1467 	 * back clusters.
1468 	 */
1469 	i = back + forw + 1;
1470 	if (i > fs->fs_contigsumsize)
1471 		i = fs->fs_contigsumsize;
1472 	sump[i] += cnt;
1473 	if (back > 0)
1474 		sump[back] -= cnt;
1475 	if (forw > 0)
1476 		sump[forw] -= cnt;
1477 }
1478 
1479 /*
1480  * Fserr prints the name of a file system with an error diagnostic.
1481  *
1482  * The form of the error message is:
1483  *	fs: error message
1484  */
1485 static void
1486 ffs_fserr(fs, uid, cp)
1487 	struct fs *fs;
1488 	u_int uid;
1489 	char *cp;
1490 {
1491 
1492 	log(LOG_ERR, "uid %d on %s: %s\n", uid, fs->fs_fsmnt, cp);
1493 }
1494