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