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