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