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