Home | History | Annotate | Line # | Download | only in ffs
ffs_alloc.c revision 1.4
      1 /*	$NetBSD: ffs_alloc.c,v 1.4 1994/10/20 04:20:55 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_int32_t (*)()));
     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_int32_t (*)())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_int32_t (*)())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 #ifdef DEBUG
    308 #include <sys/sysctl.h>
    309 int doasyncfree = 1;
    310 struct ctldebug debug14 = { "doasyncfree", &doasyncfree };
    311 #else
    312 #define doasyncfree 1
    313 #endif
    314 
    315 int
    316 ffs_reallocblks(ap)
    317 	struct vop_reallocblks_args /* {
    318 		struct vnode *a_vp;
    319 		struct cluster_save *a_buflist;
    320 	} */ *ap;
    321 {
    322 	struct fs *fs;
    323 	struct inode *ip;
    324 	struct vnode *vp;
    325 	struct buf *sbp, *ebp;
    326 	daddr_t *bap, *sbap, *ebap;
    327 	struct cluster_save *buflist;
    328 	daddr_t start_lbn, end_lbn, soff, eoff, newblk, blkno;
    329 	struct indir start_ap[NIADDR + 1], end_ap[NIADDR + 1], *idp;
    330 	int i, len, start_lvl, end_lvl, pref, ssize;
    331 
    332 	vp = ap->a_vp;
    333 	ip = VTOI(vp);
    334 	fs = ip->i_fs;
    335 	if (fs->fs_contigsumsize <= 0)
    336 		return (ENOSPC);
    337 	buflist = ap->a_buflist;
    338 	len = buflist->bs_nchildren;
    339 	start_lbn = buflist->bs_children[0]->b_lblkno;
    340 	end_lbn = start_lbn + len - 1;
    341 #ifdef DIAGNOSTIC
    342 	for (i = 1; i < len; i++)
    343 		if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
    344 			panic("ffs_reallocblks: non-cluster");
    345 #endif
    346 	/*
    347 	 * If the latest allocation is in a new cylinder group, assume that
    348 	 * the filesystem has decided to move and do not force it back to
    349 	 * the previous cylinder group.
    350 	 */
    351 	if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
    352 	    dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
    353 		return (ENOSPC);
    354 	if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
    355 	    ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
    356 		return (ENOSPC);
    357 	/*
    358 	 * Get the starting offset and block map for the first block.
    359 	 */
    360 	if (start_lvl == 0) {
    361 		sbap = &ip->i_db[0];
    362 		soff = start_lbn;
    363 	} else {
    364 		idp = &start_ap[start_lvl - 1];
    365 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
    366 			brelse(sbp);
    367 			return (ENOSPC);
    368 		}
    369 		sbap = (daddr_t *)sbp->b_data;
    370 		soff = idp->in_off;
    371 	}
    372 	/*
    373 	 * Find the preferred location for the cluster.
    374 	 */
    375 	pref = ffs_blkpref(ip, start_lbn, soff, sbap);
    376 	/*
    377 	 * If the block range spans two block maps, get the second map.
    378 	 */
    379 	if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
    380 		ssize = len;
    381 	} else {
    382 #ifdef DIAGNOSTIC
    383 		if (start_ap[start_lvl-1].in_lbn == idp->in_lbn)
    384 			panic("ffs_reallocblk: start == end");
    385 #endif
    386 		ssize = len - (idp->in_off + 1);
    387 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
    388 			goto fail;
    389 		ebap = (daddr_t *)ebp->b_data;
    390 	}
    391 	/*
    392 	 * Search the block map looking for an allocation of the desired size.
    393 	 */
    394 	if ((newblk = (daddr_t)ffs_hashalloc(ip, dtog(fs, pref), (long)pref,
    395 	    len, (u_int32_t (*)())ffs_clusteralloc)) == 0)
    396 		goto fail;
    397 	/*
    398 	 * We have found a new contiguous block.
    399 	 *
    400 	 * First we have to replace the old block pointers with the new
    401 	 * block pointers in the inode and indirect blocks associated
    402 	 * with the file.
    403 	 */
    404 	blkno = newblk;
    405 	for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
    406 		if (i == ssize)
    407 			bap = ebap;
    408 #ifdef DIAGNOSTIC
    409 		if (buflist->bs_children[i]->b_blkno != fsbtodb(fs, *bap))
    410 			panic("ffs_reallocblks: alloc mismatch");
    411 #endif
    412 		*bap++ = blkno;
    413 	}
    414 	/*
    415 	 * Next we must write out the modified inode and indirect blocks.
    416 	 * For strict correctness, the writes should be synchronous since
    417 	 * the old block values may have been written to disk. In practise
    418 	 * they are almost never written, but if we are concerned about
    419 	 * strict correctness, the `doasyncfree' flag should be set to zero.
    420 	 *
    421 	 * The test on `doasyncfree' should be changed to test a flag
    422 	 * that shows whether the associated buffers and inodes have
    423 	 * been written. The flag should be set when the cluster is
    424 	 * started and cleared whenever the buffer or inode is flushed.
    425 	 * We can then check below to see if it is set, and do the
    426 	 * synchronous write only when it has been cleared.
    427 	 */
    428 	if (sbap != &ip->i_db[0]) {
    429 		if (doasyncfree)
    430 			bdwrite(sbp);
    431 		else
    432 			bwrite(sbp);
    433 	} else {
    434 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
    435 		if (!doasyncfree)
    436 			VOP_UPDATE(vp, &time, &time, MNT_WAIT);
    437 	}
    438 	if (ssize < len)
    439 		if (doasyncfree)
    440 			bdwrite(ebp);
    441 		else
    442 			bwrite(ebp);
    443 	/*
    444 	 * Last, free the old blocks and assign the new blocks to the buffers.
    445 	 */
    446 	for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
    447 		ffs_blkfree(ip, dbtofsb(fs, buflist->bs_children[i]->b_blkno),
    448 		    fs->fs_bsize);
    449 		buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
    450 	}
    451 	return (0);
    452 
    453 fail:
    454 	if (ssize < len)
    455 		brelse(ebp);
    456 	if (sbap != &ip->i_db[0])
    457 		brelse(sbp);
    458 	return (ENOSPC);
    459 }
    460 
    461 /*
    462  * Allocate an inode in the file system.
    463  *
    464  * If allocating a directory, use ffs_dirpref to select the inode.
    465  * If allocating in a directory, the following hierarchy is followed:
    466  *   1) allocate the preferred inode.
    467  *   2) allocate an inode in the same cylinder group.
    468  *   3) quadradically rehash into other cylinder groups, until an
    469  *      available inode is located.
    470  * If no inode preference is given the following heirarchy is used
    471  * to allocate an inode:
    472  *   1) allocate an inode in cylinder group 0.
    473  *   2) quadradically rehash into other cylinder groups, until an
    474  *      available inode is located.
    475  */
    476 ffs_valloc(ap)
    477 	struct vop_valloc_args /* {
    478 		struct vnode *a_pvp;
    479 		int a_mode;
    480 		struct ucred *a_cred;
    481 		struct vnode **a_vpp;
    482 	} */ *ap;
    483 {
    484 	register struct vnode *pvp = ap->a_pvp;
    485 	register struct inode *pip;
    486 	register struct fs *fs;
    487 	register struct inode *ip;
    488 	mode_t mode = ap->a_mode;
    489 	ino_t ino, ipref;
    490 	int cg, error;
    491 
    492 	*ap->a_vpp = NULL;
    493 	pip = VTOI(pvp);
    494 	fs = pip->i_fs;
    495 	if (fs->fs_cstotal.cs_nifree == 0)
    496 		goto noinodes;
    497 
    498 	if ((mode & IFMT) == IFDIR)
    499 		ipref = ffs_dirpref(fs);
    500 	else
    501 		ipref = pip->i_number;
    502 	if (ipref >= fs->fs_ncg * fs->fs_ipg)
    503 		ipref = 0;
    504 	cg = ino_to_cg(fs, ipref);
    505 	ino = (ino_t)ffs_hashalloc(pip, cg, (long)ipref, mode, ffs_nodealloccg);
    506 	if (ino == 0)
    507 		goto noinodes;
    508 	error = VFS_VGET(pvp->v_mount, ino, ap->a_vpp);
    509 	if (error) {
    510 		VOP_VFREE(pvp, ino, mode);
    511 		return (error);
    512 	}
    513 	ip = VTOI(*ap->a_vpp);
    514 	if (ip->i_mode) {
    515 		printf("mode = 0%o, inum = %d, fs = %s\n",
    516 		    ip->i_mode, ip->i_number, fs->fs_fsmnt);
    517 		panic("ffs_valloc: dup alloc");
    518 	}
    519 	if (ip->i_blocks) {				/* XXX */
    520 		printf("free inode %s/%d had %d blocks\n",
    521 		    fs->fs_fsmnt, ino, ip->i_blocks);
    522 		ip->i_blocks = 0;
    523 	}
    524 	ip->i_flags = 0;
    525 	/*
    526 	 * Set up a new generation number for this inode.
    527 	 */
    528 	if (++nextgennumber < (u_long)time.tv_sec)
    529 		nextgennumber = time.tv_sec;
    530 	ip->i_gen = nextgennumber;
    531 	return (0);
    532 noinodes:
    533 	ffs_fserr(fs, ap->a_cred->cr_uid, "out of inodes");
    534 	uprintf("\n%s: create/symlink failed, no inodes free\n", fs->fs_fsmnt);
    535 	return (ENOSPC);
    536 }
    537 
    538 /*
    539  * Find a cylinder to place a directory.
    540  *
    541  * The policy implemented by this algorithm is to select from
    542  * among those cylinder groups with above the average number of
    543  * free inodes, the one with the smallest number of directories.
    544  */
    545 static ino_t
    546 ffs_dirpref(fs)
    547 	register struct fs *fs;
    548 {
    549 	int cg, minndir, mincg, avgifree;
    550 
    551 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
    552 	minndir = fs->fs_ipg;
    553 	mincg = 0;
    554 	for (cg = 0; cg < fs->fs_ncg; cg++)
    555 		if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
    556 		    fs->fs_cs(fs, cg).cs_nifree >= avgifree) {
    557 			mincg = cg;
    558 			minndir = fs->fs_cs(fs, cg).cs_ndir;
    559 		}
    560 	return ((ino_t)(fs->fs_ipg * mincg));
    561 }
    562 
    563 /*
    564  * Select the desired position for the next block in a file.  The file is
    565  * logically divided into sections. The first section is composed of the
    566  * direct blocks. Each additional section contains fs_maxbpg blocks.
    567  *
    568  * If no blocks have been allocated in the first section, the policy is to
    569  * request a block in the same cylinder group as the inode that describes
    570  * the file. If no blocks have been allocated in any other section, the
    571  * policy is to place the section in a cylinder group with a greater than
    572  * average number of free blocks.  An appropriate cylinder group is found
    573  * by using a rotor that sweeps the cylinder groups. When a new group of
    574  * blocks is needed, the sweep begins in the cylinder group following the
    575  * cylinder group from which the previous allocation was made. The sweep
    576  * continues until a cylinder group with greater than the average number
    577  * of free blocks is found. If the allocation is for the first block in an
    578  * indirect block, the information on the previous allocation is unavailable;
    579  * here a best guess is made based upon the logical block number being
    580  * allocated.
    581  *
    582  * If a section is already partially allocated, the policy is to
    583  * contiguously allocate fs_maxcontig blocks.  The end of one of these
    584  * contiguous blocks and the beginning of the next is physically separated
    585  * so that the disk head will be in transit between them for at least
    586  * fs_rotdelay milliseconds.  This is to allow time for the processor to
    587  * schedule another I/O transfer.
    588  */
    589 daddr_t
    590 ffs_blkpref(ip, lbn, indx, bap)
    591 	struct inode *ip;
    592 	daddr_t lbn;
    593 	int indx;
    594 	daddr_t *bap;
    595 {
    596 	register struct fs *fs;
    597 	register int cg;
    598 	int avgbfree, startcg;
    599 	daddr_t nextblk;
    600 
    601 	fs = ip->i_fs;
    602 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
    603 		if (lbn < NDADDR) {
    604 			cg = ino_to_cg(fs, ip->i_number);
    605 			return (fs->fs_fpg * cg + fs->fs_frag);
    606 		}
    607 		/*
    608 		 * Find a cylinder with greater than average number of
    609 		 * unused data blocks.
    610 		 */
    611 		if (indx == 0 || bap[indx - 1] == 0)
    612 			startcg =
    613 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
    614 		else
    615 			startcg = dtog(fs, bap[indx - 1]) + 1;
    616 		startcg %= fs->fs_ncg;
    617 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
    618 		for (cg = startcg; cg < fs->fs_ncg; cg++)
    619 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    620 				fs->fs_cgrotor = cg;
    621 				return (fs->fs_fpg * cg + fs->fs_frag);
    622 			}
    623 		for (cg = 0; cg <= startcg; cg++)
    624 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    625 				fs->fs_cgrotor = cg;
    626 				return (fs->fs_fpg * cg + fs->fs_frag);
    627 			}
    628 		return (NULL);
    629 	}
    630 	/*
    631 	 * One or more previous blocks have been laid out. If less
    632 	 * than fs_maxcontig previous blocks are contiguous, the
    633 	 * next block is requested contiguously, otherwise it is
    634 	 * requested rotationally delayed by fs_rotdelay milliseconds.
    635 	 */
    636 	nextblk = bap[indx - 1] + fs->fs_frag;
    637 	if (indx < fs->fs_maxcontig || bap[indx - fs->fs_maxcontig] +
    638 	    blkstofrags(fs, fs->fs_maxcontig) != nextblk)
    639 		return (nextblk);
    640 	if (fs->fs_rotdelay != 0)
    641 		/*
    642 		 * Here we convert ms of delay to frags as:
    643 		 * (frags) = (ms) * (rev/sec) * (sect/rev) /
    644 		 *	((sect/frag) * (ms/sec))
    645 		 * then round up to the next block.
    646 		 */
    647 		nextblk += roundup(fs->fs_rotdelay * fs->fs_rps * fs->fs_nsect /
    648 		    (NSPF(fs) * 1000), fs->fs_frag);
    649 	return (nextblk);
    650 }
    651 
    652 /*
    653  * Implement the cylinder overflow algorithm.
    654  *
    655  * The policy implemented by this algorithm is:
    656  *   1) allocate the block in its requested cylinder group.
    657  *   2) quadradically rehash on the cylinder group number.
    658  *   3) brute force search for a free block.
    659  */
    660 /*VARARGS5*/
    661 static u_long
    662 ffs_hashalloc(ip, cg, pref, size, allocator)
    663 	struct inode *ip;
    664 	int cg;
    665 	long pref;
    666 	int size;	/* size for data blocks, mode for inodes */
    667 	u_int32_t (*allocator)();
    668 {
    669 	register struct fs *fs;
    670 	long result;
    671 	int i, icg = cg;
    672 
    673 	fs = ip->i_fs;
    674 	/*
    675 	 * 1: preferred cylinder group
    676 	 */
    677 	result = (*allocator)(ip, cg, pref, size);
    678 	if (result)
    679 		return (result);
    680 	/*
    681 	 * 2: quadratic rehash
    682 	 */
    683 	for (i = 1; i < fs->fs_ncg; i *= 2) {
    684 		cg += i;
    685 		if (cg >= fs->fs_ncg)
    686 			cg -= fs->fs_ncg;
    687 		result = (*allocator)(ip, cg, 0, size);
    688 		if (result)
    689 			return (result);
    690 	}
    691 	/*
    692 	 * 3: brute force search
    693 	 * Note that we start at i == 2, since 0 was checked initially,
    694 	 * and 1 is always checked in the quadratic rehash.
    695 	 */
    696 	cg = (icg + 2) % fs->fs_ncg;
    697 	for (i = 2; i < fs->fs_ncg; i++) {
    698 		result = (*allocator)(ip, cg, 0, size);
    699 		if (result)
    700 			return (result);
    701 		cg++;
    702 		if (cg == fs->fs_ncg)
    703 			cg = 0;
    704 	}
    705 	return (NULL);
    706 }
    707 
    708 /*
    709  * Determine whether a fragment can be extended.
    710  *
    711  * Check to see if the necessary fragments are available, and
    712  * if they are, allocate them.
    713  */
    714 static daddr_t
    715 ffs_fragextend(ip, cg, bprev, osize, nsize)
    716 	struct inode *ip;
    717 	int cg;
    718 	long bprev;
    719 	int osize, nsize;
    720 {
    721 	register struct fs *fs;
    722 	register struct cg *cgp;
    723 	struct buf *bp;
    724 	long bno;
    725 	int frags, bbase;
    726 	int i, error;
    727 
    728 	fs = ip->i_fs;
    729 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
    730 		return (NULL);
    731 	frags = numfrags(fs, nsize);
    732 	bbase = fragnum(fs, bprev);
    733 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
    734 		/* cannot extend across a block boundary */
    735 		return (NULL);
    736 	}
    737 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
    738 		(int)fs->fs_cgsize, NOCRED, &bp);
    739 	if (error) {
    740 		brelse(bp);
    741 		return (NULL);
    742 	}
    743 	cgp = (struct cg *)bp->b_data;
    744 	if (!cg_chkmagic(cgp)) {
    745 		brelse(bp);
    746 		return (NULL);
    747 	}
    748 	cgp->cg_time = time.tv_sec;
    749 	bno = dtogd(fs, bprev);
    750 	for (i = numfrags(fs, osize); i < frags; i++)
    751 		if (isclr(cg_blksfree(cgp), bno + i)) {
    752 			brelse(bp);
    753 			return (NULL);
    754 		}
    755 	/*
    756 	 * the current fragment can be extended
    757 	 * deduct the count on fragment being extended into
    758 	 * increase the count on the remaining fragment (if any)
    759 	 * allocate the extended piece
    760 	 */
    761 	for (i = frags; i < fs->fs_frag - bbase; i++)
    762 		if (isclr(cg_blksfree(cgp), bno + i))
    763 			break;
    764 	cgp->cg_frsum[i - numfrags(fs, osize)]--;
    765 	if (i != frags)
    766 		cgp->cg_frsum[i - frags]++;
    767 	for (i = numfrags(fs, osize); i < frags; i++) {
    768 		clrbit(cg_blksfree(cgp), bno + i);
    769 		cgp->cg_cs.cs_nffree--;
    770 		fs->fs_cstotal.cs_nffree--;
    771 		fs->fs_cs(fs, cg).cs_nffree--;
    772 	}
    773 	fs->fs_fmod = 1;
    774 	bdwrite(bp);
    775 	return (bprev);
    776 }
    777 
    778 /*
    779  * Determine whether a block can be allocated.
    780  *
    781  * Check to see if a block of the appropriate size is available,
    782  * and if it is, allocate it.
    783  */
    784 static daddr_t
    785 ffs_alloccg(ip, cg, bpref, size)
    786 	struct inode *ip;
    787 	int cg;
    788 	daddr_t bpref;
    789 	int size;
    790 {
    791 	register struct fs *fs;
    792 	register struct cg *cgp;
    793 	struct buf *bp;
    794 	register int i;
    795 	int error, bno, frags, allocsiz;
    796 
    797 	fs = ip->i_fs;
    798 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
    799 		return (NULL);
    800 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
    801 		(int)fs->fs_cgsize, NOCRED, &bp);
    802 	if (error) {
    803 		brelse(bp);
    804 		return (NULL);
    805 	}
    806 	cgp = (struct cg *)bp->b_data;
    807 	if (!cg_chkmagic(cgp) ||
    808 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize)) {
    809 		brelse(bp);
    810 		return (NULL);
    811 	}
    812 	cgp->cg_time = time.tv_sec;
    813 	if (size == fs->fs_bsize) {
    814 		bno = ffs_alloccgblk(fs, cgp, bpref);
    815 		bdwrite(bp);
    816 		return (bno);
    817 	}
    818 	/*
    819 	 * check to see if any fragments are already available
    820 	 * allocsiz is the size which will be allocated, hacking
    821 	 * it down to a smaller size if necessary
    822 	 */
    823 	frags = numfrags(fs, size);
    824 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
    825 		if (cgp->cg_frsum[allocsiz] != 0)
    826 			break;
    827 	if (allocsiz == fs->fs_frag) {
    828 		/*
    829 		 * no fragments were available, so a block will be
    830 		 * allocated, and hacked up
    831 		 */
    832 		if (cgp->cg_cs.cs_nbfree == 0) {
    833 			brelse(bp);
    834 			return (NULL);
    835 		}
    836 		bno = ffs_alloccgblk(fs, cgp, bpref);
    837 		bpref = dtogd(fs, bno);
    838 		for (i = frags; i < fs->fs_frag; i++)
    839 			setbit(cg_blksfree(cgp), bpref + i);
    840 		i = fs->fs_frag - frags;
    841 		cgp->cg_cs.cs_nffree += i;
    842 		fs->fs_cstotal.cs_nffree += i;
    843 		fs->fs_cs(fs, cg).cs_nffree += i;
    844 		fs->fs_fmod = 1;
    845 		cgp->cg_frsum[i]++;
    846 		bdwrite(bp);
    847 		return (bno);
    848 	}
    849 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
    850 	if (bno < 0) {
    851 		brelse(bp);
    852 		return (NULL);
    853 	}
    854 	for (i = 0; i < frags; i++)
    855 		clrbit(cg_blksfree(cgp), bno + i);
    856 	cgp->cg_cs.cs_nffree -= frags;
    857 	fs->fs_cstotal.cs_nffree -= frags;
    858 	fs->fs_cs(fs, cg).cs_nffree -= frags;
    859 	fs->fs_fmod = 1;
    860 	cgp->cg_frsum[allocsiz]--;
    861 	if (frags != allocsiz)
    862 		cgp->cg_frsum[allocsiz - frags]++;
    863 	bdwrite(bp);
    864 	return (cg * fs->fs_fpg + bno);
    865 }
    866 
    867 /*
    868  * Allocate a block in a cylinder group.
    869  *
    870  * This algorithm implements the following policy:
    871  *   1) allocate the requested block.
    872  *   2) allocate a rotationally optimal block in the same cylinder.
    873  *   3) allocate the next available block on the block rotor for the
    874  *      specified cylinder group.
    875  * Note that this routine only allocates fs_bsize blocks; these
    876  * blocks may be fragmented by the routine that allocates them.
    877  */
    878 static daddr_t
    879 ffs_alloccgblk(fs, cgp, bpref)
    880 	register struct fs *fs;
    881 	register struct cg *cgp;
    882 	daddr_t bpref;
    883 {
    884 	daddr_t bno, blkno;
    885 	int cylno, pos, delta;
    886 	short *cylbp;
    887 	register int i;
    888 
    889 	if (bpref == 0 || dtog(fs, bpref) != cgp->cg_cgx) {
    890 		bpref = cgp->cg_rotor;
    891 		goto norot;
    892 	}
    893 	bpref = blknum(fs, bpref);
    894 	bpref = dtogd(fs, bpref);
    895 	/*
    896 	 * if the requested block is available, use it
    897 	 */
    898 	if (ffs_isblock(fs, cg_blksfree(cgp), fragstoblks(fs, bpref))) {
    899 		bno = bpref;
    900 		goto gotit;
    901 	}
    902 	/*
    903 	 * check for a block available on the same cylinder
    904 	 */
    905 	cylno = cbtocylno(fs, bpref);
    906 	if (cg_blktot(cgp)[cylno] == 0)
    907 		goto norot;
    908 	if (fs->fs_cpc == 0) {
    909 		/*
    910 		 * Block layout information is not available.
    911 		 * Leaving bpref unchanged means we take the
    912 		 * next available free block following the one
    913 		 * we just allocated. Hopefully this will at
    914 		 * least hit a track cache on drives of unknown
    915 		 * geometry (e.g. SCSI).
    916 		 */
    917 		goto norot;
    918 	}
    919 	/*
    920 	 * check the summary information to see if a block is
    921 	 * available in the requested cylinder starting at the
    922 	 * requested rotational position and proceeding around.
    923 	 */
    924 	cylbp = cg_blks(fs, cgp, cylno);
    925 	pos = cbtorpos(fs, bpref);
    926 	for (i = pos; i < fs->fs_nrpos; i++)
    927 		if (cylbp[i] > 0)
    928 			break;
    929 	if (i == fs->fs_nrpos)
    930 		for (i = 0; i < pos; i++)
    931 			if (cylbp[i] > 0)
    932 				break;
    933 	if (cylbp[i] > 0) {
    934 		/*
    935 		 * found a rotational position, now find the actual
    936 		 * block. A panic if none is actually there.
    937 		 */
    938 		pos = cylno % fs->fs_cpc;
    939 		bno = (cylno - pos) * fs->fs_spc / NSPB(fs);
    940 		if (fs_postbl(fs, pos)[i] == -1) {
    941 			printf("pos = %d, i = %d, fs = %s\n",
    942 			    pos, i, fs->fs_fsmnt);
    943 			panic("ffs_alloccgblk: cyl groups corrupted");
    944 		}
    945 		for (i = fs_postbl(fs, pos)[i];; ) {
    946 			if (ffs_isblock(fs, cg_blksfree(cgp), bno + i)) {
    947 				bno = blkstofrags(fs, (bno + i));
    948 				goto gotit;
    949 			}
    950 			delta = fs_rotbl(fs)[i];
    951 			if (delta <= 0 ||
    952 			    delta + i > fragstoblks(fs, fs->fs_fpg))
    953 				break;
    954 			i += delta;
    955 		}
    956 		printf("pos = %d, i = %d, fs = %s\n", pos, i, fs->fs_fsmnt);
    957 		panic("ffs_alloccgblk: can't find blk in cyl");
    958 	}
    959 norot:
    960 	/*
    961 	 * no blocks in the requested cylinder, so take next
    962 	 * available one in this cylinder group.
    963 	 */
    964 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
    965 	if (bno < 0)
    966 		return (NULL);
    967 	cgp->cg_rotor = bno;
    968 gotit:
    969 	blkno = fragstoblks(fs, bno);
    970 	ffs_clrblock(fs, cg_blksfree(cgp), (long)blkno);
    971 	ffs_clusteracct(fs, cgp, blkno, -1);
    972 	cgp->cg_cs.cs_nbfree--;
    973 	fs->fs_cstotal.cs_nbfree--;
    974 	fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
    975 	cylno = cbtocylno(fs, bno);
    976 	cg_blks(fs, cgp, cylno)[cbtorpos(fs, bno)]--;
    977 	cg_blktot(cgp)[cylno]--;
    978 	fs->fs_fmod = 1;
    979 	return (cgp->cg_cgx * fs->fs_fpg + bno);
    980 }
    981 
    982 /*
    983  * Determine whether a cluster can be allocated.
    984  *
    985  * We do not currently check for optimal rotational layout if there
    986  * are multiple choices in the same cylinder group. Instead we just
    987  * take the first one that we find following bpref.
    988  */
    989 static daddr_t
    990 ffs_clusteralloc(ip, cg, bpref, len)
    991 	struct inode *ip;
    992 	int cg;
    993 	daddr_t bpref;
    994 	int len;
    995 {
    996 	register struct fs *fs;
    997 	register struct cg *cgp;
    998 	struct buf *bp;
    999 	int i, run, bno, bit, map;
   1000 	u_char *mapp;
   1001 
   1002 	fs = ip->i_fs;
   1003 	if (fs->fs_cs(fs, cg).cs_nbfree < len)
   1004 		return (NULL);
   1005 	if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize,
   1006 	    NOCRED, &bp))
   1007 		goto fail;
   1008 	cgp = (struct cg *)bp->b_data;
   1009 	if (!cg_chkmagic(cgp))
   1010 		goto fail;
   1011 	/*
   1012 	 * Check to see if a cluster of the needed size (or bigger) is
   1013 	 * available in this cylinder group.
   1014 	 */
   1015 	for (i = len; i <= fs->fs_contigsumsize; i++)
   1016 		if (cg_clustersum(cgp)[i] > 0)
   1017 			break;
   1018 	if (i > fs->fs_contigsumsize)
   1019 		goto fail;
   1020 	/*
   1021 	 * Search the cluster map to find a big enough cluster.
   1022 	 * We take the first one that we find, even if it is larger
   1023 	 * than we need as we prefer to get one close to the previous
   1024 	 * block allocation. We do not search before the current
   1025 	 * preference point as we do not want to allocate a block
   1026 	 * that is allocated before the previous one (as we will
   1027 	 * then have to wait for another pass of the elevator
   1028 	 * algorithm before it will be read). We prefer to fail and
   1029 	 * be recalled to try an allocation in the next cylinder group.
   1030 	 */
   1031 	if (dtog(fs, bpref) != cg)
   1032 		bpref = 0;
   1033 	else
   1034 		bpref = fragstoblks(fs, dtogd(fs, blknum(fs, bpref)));
   1035 	mapp = &cg_clustersfree(cgp)[bpref / NBBY];
   1036 	map = *mapp++;
   1037 	bit = 1 << (bpref % NBBY);
   1038 	for (run = 0, i = bpref; i < cgp->cg_nclusterblks; i++) {
   1039 		if ((map & bit) == 0) {
   1040 			run = 0;
   1041 		} else {
   1042 			run++;
   1043 			if (run == len)
   1044 				break;
   1045 		}
   1046 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
   1047 			bit <<= 1;
   1048 		} else {
   1049 			map = *mapp++;
   1050 			bit = 1;
   1051 		}
   1052 	}
   1053 	if (i == cgp->cg_nclusterblks)
   1054 		goto fail;
   1055 	/*
   1056 	 * Allocate the cluster that we have found.
   1057 	 */
   1058 	bno = cg * fs->fs_fpg + blkstofrags(fs, i - run + 1);
   1059 	len = blkstofrags(fs, len);
   1060 	for (i = 0; i < len; i += fs->fs_frag)
   1061 		if (ffs_alloccgblk(fs, cgp, bno + i) != bno + i)
   1062 			panic("ffs_clusteralloc: lost block");
   1063 	brelse(bp);
   1064 	return (bno);
   1065 
   1066 fail:
   1067 	brelse(bp);
   1068 	return (0);
   1069 }
   1070 
   1071 /*
   1072  * Determine whether an inode can be allocated.
   1073  *
   1074  * Check to see if an inode is available, and if it is,
   1075  * allocate it using the following policy:
   1076  *   1) allocate the requested inode.
   1077  *   2) allocate the next available inode after the requested
   1078  *      inode in the specified cylinder group.
   1079  */
   1080 static ino_t
   1081 ffs_nodealloccg(ip, cg, ipref, mode)
   1082 	struct inode *ip;
   1083 	int cg;
   1084 	daddr_t ipref;
   1085 	int mode;
   1086 {
   1087 	register struct fs *fs;
   1088 	register struct cg *cgp;
   1089 	struct buf *bp;
   1090 	int error, start, len, loc, map, i;
   1091 
   1092 	fs = ip->i_fs;
   1093 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
   1094 		return (NULL);
   1095 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1096 		(int)fs->fs_cgsize, NOCRED, &bp);
   1097 	if (error) {
   1098 		brelse(bp);
   1099 		return (NULL);
   1100 	}
   1101 	cgp = (struct cg *)bp->b_data;
   1102 	if (!cg_chkmagic(cgp) || cgp->cg_cs.cs_nifree == 0) {
   1103 		brelse(bp);
   1104 		return (NULL);
   1105 	}
   1106 	cgp->cg_time = time.tv_sec;
   1107 	if (ipref) {
   1108 		ipref %= fs->fs_ipg;
   1109 		if (isclr(cg_inosused(cgp), ipref))
   1110 			goto gotit;
   1111 	}
   1112 	start = cgp->cg_irotor / NBBY;
   1113 	len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
   1114 	loc = skpc(0xff, len, &cg_inosused(cgp)[start]);
   1115 	if (loc == 0) {
   1116 		len = start + 1;
   1117 		start = 0;
   1118 		loc = skpc(0xff, len, &cg_inosused(cgp)[0]);
   1119 		if (loc == 0) {
   1120 			printf("cg = %d, irotor = %d, fs = %s\n",
   1121 			    cg, cgp->cg_irotor, fs->fs_fsmnt);
   1122 			panic("ffs_nodealloccg: map corrupted");
   1123 			/* NOTREACHED */
   1124 		}
   1125 	}
   1126 	i = start + len - loc;
   1127 	map = cg_inosused(cgp)[i];
   1128 	ipref = i * NBBY;
   1129 	for (i = 1; i < (1 << NBBY); i <<= 1, ipref++) {
   1130 		if ((map & i) == 0) {
   1131 			cgp->cg_irotor = ipref;
   1132 			goto gotit;
   1133 		}
   1134 	}
   1135 	printf("fs = %s\n", fs->fs_fsmnt);
   1136 	panic("ffs_nodealloccg: block not in map");
   1137 	/* NOTREACHED */
   1138 gotit:
   1139 	setbit(cg_inosused(cgp), ipref);
   1140 	cgp->cg_cs.cs_nifree--;
   1141 	fs->fs_cstotal.cs_nifree--;
   1142 	fs->fs_cs(fs, cg).cs_nifree--;
   1143 	fs->fs_fmod = 1;
   1144 	if ((mode & IFMT) == IFDIR) {
   1145 		cgp->cg_cs.cs_ndir++;
   1146 		fs->fs_cstotal.cs_ndir++;
   1147 		fs->fs_cs(fs, cg).cs_ndir++;
   1148 	}
   1149 	bdwrite(bp);
   1150 	return (cg * fs->fs_ipg + ipref);
   1151 }
   1152 
   1153 /*
   1154  * Free a block or fragment.
   1155  *
   1156  * The specified block or fragment is placed back in the
   1157  * free map. If a fragment is deallocated, a possible
   1158  * block reassembly is checked.
   1159  */
   1160 ffs_blkfree(ip, bno, size)
   1161 	register struct inode *ip;
   1162 	daddr_t bno;
   1163 	long size;
   1164 {
   1165 	register struct fs *fs;
   1166 	register struct cg *cgp;
   1167 	struct buf *bp;
   1168 	daddr_t blkno;
   1169 	int i, error, cg, blk, frags, bbase;
   1170 
   1171 	fs = ip->i_fs;
   1172 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
   1173 		printf("dev = 0x%x, bsize = %d, size = %d, fs = %s\n",
   1174 		    ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
   1175 		panic("blkfree: bad size");
   1176 	}
   1177 	cg = dtog(fs, bno);
   1178 	if ((u_int)bno >= fs->fs_size) {
   1179 		printf("bad block %d, ino %d\n", bno, ip->i_number);
   1180 		ffs_fserr(fs, ip->i_uid, "bad block");
   1181 		return;
   1182 	}
   1183 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1184 		(int)fs->fs_cgsize, NOCRED, &bp);
   1185 	if (error) {
   1186 		brelse(bp);
   1187 		return;
   1188 	}
   1189 	cgp = (struct cg *)bp->b_data;
   1190 	if (!cg_chkmagic(cgp)) {
   1191 		brelse(bp);
   1192 		return;
   1193 	}
   1194 	cgp->cg_time = time.tv_sec;
   1195 	bno = dtogd(fs, bno);
   1196 	if (size == fs->fs_bsize) {
   1197 		blkno = fragstoblks(fs, bno);
   1198 		if (ffs_isblock(fs, cg_blksfree(cgp), blkno)) {
   1199 			printf("dev = 0x%x, block = %d, fs = %s\n",
   1200 			    ip->i_dev, bno, fs->fs_fsmnt);
   1201 			panic("blkfree: freeing free block");
   1202 		}
   1203 		ffs_setblock(fs, cg_blksfree(cgp), blkno);
   1204 		ffs_clusteracct(fs, cgp, blkno, 1);
   1205 		cgp->cg_cs.cs_nbfree++;
   1206 		fs->fs_cstotal.cs_nbfree++;
   1207 		fs->fs_cs(fs, cg).cs_nbfree++;
   1208 		i = cbtocylno(fs, bno);
   1209 		cg_blks(fs, cgp, i)[cbtorpos(fs, bno)]++;
   1210 		cg_blktot(cgp)[i]++;
   1211 	} else {
   1212 		bbase = bno - fragnum(fs, bno);
   1213 		/*
   1214 		 * decrement the counts associated with the old frags
   1215 		 */
   1216 		blk = blkmap(fs, cg_blksfree(cgp), bbase);
   1217 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
   1218 		/*
   1219 		 * deallocate the fragment
   1220 		 */
   1221 		frags = numfrags(fs, size);
   1222 		for (i = 0; i < frags; i++) {
   1223 			if (isset(cg_blksfree(cgp), bno + i)) {
   1224 				printf("dev = 0x%x, block = %d, fs = %s\n",
   1225 				    ip->i_dev, bno + i, fs->fs_fsmnt);
   1226 				panic("blkfree: freeing free frag");
   1227 			}
   1228 			setbit(cg_blksfree(cgp), bno + i);
   1229 		}
   1230 		cgp->cg_cs.cs_nffree += i;
   1231 		fs->fs_cstotal.cs_nffree += i;
   1232 		fs->fs_cs(fs, cg).cs_nffree += i;
   1233 		/*
   1234 		 * add back in counts associated with the new frags
   1235 		 */
   1236 		blk = blkmap(fs, cg_blksfree(cgp), bbase);
   1237 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
   1238 		/*
   1239 		 * if a complete block has been reassembled, account for it
   1240 		 */
   1241 		blkno = fragstoblks(fs, bbase);
   1242 		if (ffs_isblock(fs, cg_blksfree(cgp), blkno)) {
   1243 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
   1244 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
   1245 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
   1246 			ffs_clusteracct(fs, cgp, blkno, 1);
   1247 			cgp->cg_cs.cs_nbfree++;
   1248 			fs->fs_cstotal.cs_nbfree++;
   1249 			fs->fs_cs(fs, cg).cs_nbfree++;
   1250 			i = cbtocylno(fs, bbase);
   1251 			cg_blks(fs, cgp, i)[cbtorpos(fs, bbase)]++;
   1252 			cg_blktot(cgp)[i]++;
   1253 		}
   1254 	}
   1255 	fs->fs_fmod = 1;
   1256 	bdwrite(bp);
   1257 }
   1258 
   1259 /*
   1260  * Free an inode.
   1261  *
   1262  * The specified inode is placed back in the free map.
   1263  */
   1264 int
   1265 ffs_vfree(ap)
   1266 	struct vop_vfree_args /* {
   1267 		struct vnode *a_pvp;
   1268 		ino_t a_ino;
   1269 		int a_mode;
   1270 	} */ *ap;
   1271 {
   1272 	register struct fs *fs;
   1273 	register struct cg *cgp;
   1274 	register struct inode *pip;
   1275 	ino_t ino = ap->a_ino;
   1276 	struct buf *bp;
   1277 	int error, cg;
   1278 
   1279 	pip = VTOI(ap->a_pvp);
   1280 	fs = pip->i_fs;
   1281 	if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
   1282 		panic("ifree: range: dev = 0x%x, ino = %d, fs = %s\n",
   1283 		    pip->i_dev, ino, fs->fs_fsmnt);
   1284 	cg = ino_to_cg(fs, ino);
   1285 	error = bread(pip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1286 		(int)fs->fs_cgsize, NOCRED, &bp);
   1287 	if (error) {
   1288 		brelse(bp);
   1289 		return (0);
   1290 	}
   1291 	cgp = (struct cg *)bp->b_data;
   1292 	if (!cg_chkmagic(cgp)) {
   1293 		brelse(bp);
   1294 		return (0);
   1295 	}
   1296 	cgp->cg_time = time.tv_sec;
   1297 	ino %= fs->fs_ipg;
   1298 	if (isclr(cg_inosused(cgp), ino)) {
   1299 		printf("dev = 0x%x, ino = %d, fs = %s\n",
   1300 		    pip->i_dev, ino, fs->fs_fsmnt);
   1301 		if (fs->fs_ronly == 0)
   1302 			panic("ifree: freeing free inode");
   1303 	}
   1304 	clrbit(cg_inosused(cgp), ino);
   1305 	if (ino < cgp->cg_irotor)
   1306 		cgp->cg_irotor = ino;
   1307 	cgp->cg_cs.cs_nifree++;
   1308 	fs->fs_cstotal.cs_nifree++;
   1309 	fs->fs_cs(fs, cg).cs_nifree++;
   1310 	if ((ap->a_mode & IFMT) == IFDIR) {
   1311 		cgp->cg_cs.cs_ndir--;
   1312 		fs->fs_cstotal.cs_ndir--;
   1313 		fs->fs_cs(fs, cg).cs_ndir--;
   1314 	}
   1315 	fs->fs_fmod = 1;
   1316 	bdwrite(bp);
   1317 	return (0);
   1318 }
   1319 
   1320 /*
   1321  * Find a block of the specified size in the specified cylinder group.
   1322  *
   1323  * It is a panic if a request is made to find a block if none are
   1324  * available.
   1325  */
   1326 static daddr_t
   1327 ffs_mapsearch(fs, cgp, bpref, allocsiz)
   1328 	register struct fs *fs;
   1329 	register struct cg *cgp;
   1330 	daddr_t bpref;
   1331 	int allocsiz;
   1332 {
   1333 	daddr_t bno;
   1334 	int start, len, loc, i;
   1335 	int blk, field, subfield, pos;
   1336 
   1337 	/*
   1338 	 * find the fragment by searching through the free block
   1339 	 * map for an appropriate bit pattern
   1340 	 */
   1341 	if (bpref)
   1342 		start = dtogd(fs, bpref) / NBBY;
   1343 	else
   1344 		start = cgp->cg_frotor / NBBY;
   1345 	len = howmany(fs->fs_fpg, NBBY) - start;
   1346 	loc = scanc((u_int)len, (u_char *)&cg_blksfree(cgp)[start],
   1347 		(u_char *)fragtbl[fs->fs_frag],
   1348 		(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
   1349 	if (loc == 0) {
   1350 		len = start + 1;
   1351 		start = 0;
   1352 		loc = scanc((u_int)len, (u_char *)&cg_blksfree(cgp)[0],
   1353 			(u_char *)fragtbl[fs->fs_frag],
   1354 			(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
   1355 		if (loc == 0) {
   1356 			printf("start = %d, len = %d, fs = %s\n",
   1357 			    start, len, fs->fs_fsmnt);
   1358 			panic("ffs_alloccg: map corrupted");
   1359 			/* NOTREACHED */
   1360 		}
   1361 	}
   1362 	bno = (start + len - loc) * NBBY;
   1363 	cgp->cg_frotor = bno;
   1364 	/*
   1365 	 * found the byte in the map
   1366 	 * sift through the bits to find the selected frag
   1367 	 */
   1368 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
   1369 		blk = blkmap(fs, cg_blksfree(cgp), bno);
   1370 		blk <<= 1;
   1371 		field = around[allocsiz];
   1372 		subfield = inside[allocsiz];
   1373 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
   1374 			if ((blk & field) == subfield)
   1375 				return (bno + pos);
   1376 			field <<= 1;
   1377 			subfield <<= 1;
   1378 		}
   1379 	}
   1380 	printf("bno = %d, fs = %s\n", bno, fs->fs_fsmnt);
   1381 	panic("ffs_alloccg: block not in map");
   1382 	return (-1);
   1383 }
   1384 
   1385 /*
   1386  * Update the cluster map because of an allocation or free.
   1387  *
   1388  * Cnt == 1 means free; cnt == -1 means allocating.
   1389  */
   1390 ffs_clusteracct(fs, cgp, blkno, cnt)
   1391 	struct fs *fs;
   1392 	struct cg *cgp;
   1393 	daddr_t blkno;
   1394 	int cnt;
   1395 {
   1396 	int32_t *sump;
   1397 	u_char *freemapp, *mapp;
   1398 	int i, start, end, forw, back, map, bit;
   1399 
   1400 	if (fs->fs_contigsumsize <= 0)
   1401 		return;
   1402 	freemapp = cg_clustersfree(cgp);
   1403 	sump = cg_clustersum(cgp);
   1404 	/*
   1405 	 * Allocate or clear the actual block.
   1406 	 */
   1407 	if (cnt > 0)
   1408 		setbit(freemapp, blkno);
   1409 	else
   1410 		clrbit(freemapp, blkno);
   1411 	/*
   1412 	 * Find the size of the cluster going forward.
   1413 	 */
   1414 	start = blkno + 1;
   1415 	end = start + fs->fs_contigsumsize;
   1416 	if (end >= cgp->cg_nclusterblks)
   1417 		end = cgp->cg_nclusterblks;
   1418 	mapp = &freemapp[start / NBBY];
   1419 	map = *mapp++;
   1420 	bit = 1 << (start % NBBY);
   1421 	for (i = start; i < end; i++) {
   1422 		if ((map & bit) == 0)
   1423 			break;
   1424 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
   1425 			bit <<= 1;
   1426 		} else {
   1427 			map = *mapp++;
   1428 			bit = 1;
   1429 		}
   1430 	}
   1431 	forw = i - start;
   1432 	/*
   1433 	 * Find the size of the cluster going backward.
   1434 	 */
   1435 	start = blkno - 1;
   1436 	end = start - fs->fs_contigsumsize;
   1437 	if (end < 0)
   1438 		end = -1;
   1439 	mapp = &freemapp[start / NBBY];
   1440 	map = *mapp--;
   1441 	bit = 1 << (start % NBBY);
   1442 	for (i = start; i > end; i--) {
   1443 		if ((map & bit) == 0)
   1444 			break;
   1445 		if ((i & (NBBY - 1)) != 0) {
   1446 			bit >>= 1;
   1447 		} else {
   1448 			map = *mapp--;
   1449 			bit = 1 << (NBBY - 1);
   1450 		}
   1451 	}
   1452 	back = start - i;
   1453 	/*
   1454 	 * Account for old cluster and the possibly new forward and
   1455 	 * back clusters.
   1456 	 */
   1457 	i = back + forw + 1;
   1458 	if (i > fs->fs_contigsumsize)
   1459 		i = fs->fs_contigsumsize;
   1460 	sump[i] += cnt;
   1461 	if (back > 0)
   1462 		sump[back] -= cnt;
   1463 	if (forw > 0)
   1464 		sump[forw] -= cnt;
   1465 }
   1466 
   1467 /*
   1468  * Fserr prints the name of a file system with an error diagnostic.
   1469  *
   1470  * The form of the error message is:
   1471  *	fs: error message
   1472  */
   1473 static void
   1474 ffs_fserr(fs, uid, cp)
   1475 	struct fs *fs;
   1476 	u_int uid;
   1477 	char *cp;
   1478 {
   1479 
   1480 	log(LOG_ERR, "uid %d on %s: %s\n", uid, fs->fs_fsmnt, cp);
   1481 }
   1482