Home | History | Annotate | Line # | Download | only in ffs
ffs_alloc.c revision 1.64
      1 /*	$NetBSD: ffs_alloc.c,v 1.64 2003/05/04 01:52:18 gmcgarry Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2002 Networks Associates Technology, Inc.
      5  * All rights reserved.
      6  *
      7  * This software was developed for the FreeBSD Project by Marshall
      8  * Kirk McKusick and Network Associates Laboratories, the Security
      9  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
     10  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
     11  * research program
     12  *
     13  * Copyright (c) 1982, 1986, 1989, 1993
     14  *	The Regents of the University of California.  All rights reserved.
     15  *
     16  * Redistribution and use in source and binary forms, with or without
     17  * modification, are permitted provided that the following conditions
     18  * are met:
     19  * 1. Redistributions of source code must retain the above copyright
     20  *    notice, this list of conditions and the following disclaimer.
     21  * 2. Redistributions in binary form must reproduce the above copyright
     22  *    notice, this list of conditions and the following disclaimer in the
     23  *    documentation and/or other materials provided with the distribution.
     24  * 3. All advertising materials mentioning features or use of this software
     25  *    must display the following acknowledgement:
     26  *	This product includes software developed by the University of
     27  *	California, Berkeley and its contributors.
     28  * 4. Neither the name of the University nor the names of its contributors
     29  *    may be used to endorse or promote products derived from this software
     30  *    without specific prior written permission.
     31  *
     32  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     33  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     35  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     36  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     37  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     38  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     40  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     41  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     42  * SUCH DAMAGE.
     43  *
     44  *	@(#)ffs_alloc.c	8.19 (Berkeley) 7/13/95
     45  */
     46 
     47 #include <sys/cdefs.h>
     48 __KERNEL_RCSID(0, "$NetBSD: ffs_alloc.c,v 1.64 2003/05/04 01:52:18 gmcgarry Exp $");
     49 
     50 #if defined(_KERNEL_OPT)
     51 #include "opt_ffs.h"
     52 #include "opt_quota.h"
     53 #endif
     54 
     55 #include <sys/param.h>
     56 #include <sys/systm.h>
     57 #include <sys/buf.h>
     58 #include <sys/proc.h>
     59 #include <sys/vnode.h>
     60 #include <sys/mount.h>
     61 #include <sys/kernel.h>
     62 #include <sys/syslog.h>
     63 
     64 #include <ufs/ufs/quota.h>
     65 #include <ufs/ufs/ufsmount.h>
     66 #include <ufs/ufs/inode.h>
     67 #include <ufs/ufs/ufs_extern.h>
     68 #include <ufs/ufs/ufs_bswap.h>
     69 
     70 #include <ufs/ffs/fs.h>
     71 #include <ufs/ffs/ffs_extern.h>
     72 
     73 static daddr_t ffs_alloccg __P((struct inode *, int, daddr_t, int));
     74 static daddr_t ffs_alloccgblk __P((struct inode *, struct buf *, daddr_t));
     75 #ifdef XXXUBC
     76 static daddr_t ffs_clusteralloc __P((struct inode *, int, daddr_t, int));
     77 #endif
     78 static ino_t ffs_dirpref __P((struct inode *));
     79 static daddr_t ffs_fragextend __P((struct inode *, int, daddr_t, int, int));
     80 static void ffs_fserr __P((struct fs *, u_int, char *));
     81 static daddr_t ffs_hashalloc __P((struct inode *, int, daddr_t, int,
     82     daddr_t (*)(struct inode *, int, daddr_t, int)));
     83 static daddr_t ffs_nodealloccg __P((struct inode *, int, daddr_t, int));
     84 static int32_t ffs_mapsearch __P((struct fs *, struct cg *,
     85 				      daddr_t, int));
     86 #if defined(DIAGNOSTIC) || defined(DEBUG)
     87 #ifdef XXXUBC
     88 static int ffs_checkblk __P((struct inode *, daddr_t, long size));
     89 #endif
     90 #endif
     91 
     92 /* if 1, changes in optimalization strategy are logged */
     93 int ffs_log_changeopt = 0;
     94 
     95 /* in ffs_tables.c */
     96 extern const int inside[], around[];
     97 extern const u_char * const fragtbl[];
     98 
     99 /*
    100  * Allocate a block in the file system.
    101  *
    102  * The size of the requested block is given, which must be some
    103  * multiple of fs_fsize and <= fs_bsize.
    104  * A preference may be optionally specified. If a preference is given
    105  * the following hierarchy is used to allocate a block:
    106  *   1) allocate the requested block.
    107  *   2) allocate a rotationally optimal block in the same cylinder.
    108  *   3) allocate a block in the same cylinder group.
    109  *   4) quadradically rehash into other cylinder groups, until an
    110  *      available block is located.
    111  * If no block preference is given the following hierarchy is used
    112  * to allocate a block:
    113  *   1) allocate a block in the cylinder group that contains the
    114  *      inode for the file.
    115  *   2) quadradically rehash into other cylinder groups, until an
    116  *      available block is located.
    117  */
    118 int
    119 ffs_alloc(ip, lbn, bpref, size, cred, bnp)
    120 	struct inode *ip;
    121 	daddr_t lbn, bpref;
    122 	int size;
    123 	struct ucred *cred;
    124 	daddr_t *bnp;
    125 {
    126 	struct fs *fs;
    127 	daddr_t bno;
    128 	int cg;
    129 #ifdef QUOTA
    130 	int error;
    131 #endif
    132 
    133 	fs = ip->i_fs;
    134 
    135 #ifdef UVM_PAGE_TRKOWN
    136 	if (ITOV(ip)->v_type == VREG &&
    137 	    lblktosize(fs, (voff_t)lbn) < round_page(ITOV(ip)->v_size)) {
    138 		struct vm_page *pg;
    139 		struct uvm_object *uobj = &ITOV(ip)->v_uobj;
    140 		voff_t off = trunc_page(lblktosize(fs, lbn));
    141 		voff_t endoff = round_page(lblktosize(fs, lbn) + size);
    142 
    143 		simple_lock(&uobj->vmobjlock);
    144 		while (off < endoff) {
    145 			pg = uvm_pagelookup(uobj, off);
    146 			KASSERT(pg != NULL);
    147 			KASSERT(pg->owner == curproc->p_pid);
    148 			KASSERT((pg->flags & PG_CLEAN) == 0);
    149 			off += PAGE_SIZE;
    150 		}
    151 		simple_unlock(&uobj->vmobjlock);
    152 	}
    153 #endif
    154 
    155 	*bnp = 0;
    156 #ifdef DIAGNOSTIC
    157 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
    158 		printf("dev = 0x%x, bsize = %d, size = %d, fs = %s\n",
    159 		    ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
    160 		panic("ffs_alloc: bad size");
    161 	}
    162 	if (cred == NOCRED)
    163 		panic("ffs_alloc: missing credential");
    164 #endif /* DIAGNOSTIC */
    165 	if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
    166 		goto nospace;
    167 	if (cred->cr_uid != 0 && freespace(fs, fs->fs_minfree) <= 0)
    168 		goto nospace;
    169 #ifdef QUOTA
    170 	if ((error = chkdq(ip, btodb(size), cred, 0)) != 0)
    171 		return (error);
    172 #endif
    173 	if (bpref >= fs->fs_size)
    174 		bpref = 0;
    175 	if (bpref == 0)
    176 		cg = ino_to_cg(fs, ip->i_number);
    177 	else
    178 		cg = dtog(fs, bpref);
    179 	bno = ffs_hashalloc(ip, cg, (long)bpref, size,
    180 	    			     ffs_alloccg);
    181 	if (bno > 0) {
    182 		DIP(ip, blocks) += btodb(size);
    183 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
    184 		*bnp = bno;
    185 		return (0);
    186 	}
    187 #ifdef QUOTA
    188 	/*
    189 	 * Restore user's disk quota because allocation failed.
    190 	 */
    191 	(void) chkdq(ip, -btodb(size), cred, FORCE);
    192 #endif
    193 nospace:
    194 	ffs_fserr(fs, cred->cr_uid, "file system full");
    195 	uprintf("\n%s: write failed, file system is full\n", fs->fs_fsmnt);
    196 	return (ENOSPC);
    197 }
    198 
    199 /*
    200  * Reallocate a fragment to a bigger size
    201  *
    202  * The number and size of the old block is given, and a preference
    203  * and new size is also specified. The allocator attempts to extend
    204  * the original block. Failing that, the regular block allocator is
    205  * invoked to get an appropriate block.
    206  */
    207 int
    208 ffs_realloccg(ip, lbprev, bpref, osize, nsize, cred, bpp, blknop)
    209 	struct inode *ip;
    210 	daddr_t lbprev;
    211 	daddr_t bpref;
    212 	int osize, nsize;
    213 	struct ucred *cred;
    214 	struct buf **bpp;
    215 	daddr_t *blknop;
    216 {
    217 	struct fs *fs;
    218 	struct buf *bp;
    219 	int cg, request, error;
    220 	daddr_t bprev, bno;
    221 
    222 	fs = ip->i_fs;
    223 #ifdef UVM_PAGE_TRKOWN
    224 	if (ITOV(ip)->v_type == VREG) {
    225 		struct vm_page *pg;
    226 		struct uvm_object *uobj = &ITOV(ip)->v_uobj;
    227 		voff_t off = trunc_page(lblktosize(fs, lbprev));
    228 		voff_t endoff = round_page(lblktosize(fs, lbprev) + osize);
    229 
    230 		simple_lock(&uobj->vmobjlock);
    231 		while (off < endoff) {
    232 			pg = uvm_pagelookup(uobj, off);
    233 			KASSERT(pg != NULL);
    234 			KASSERT(pg->owner == curproc->p_pid);
    235 			KASSERT((pg->flags & PG_CLEAN) == 0);
    236 			off += PAGE_SIZE;
    237 		}
    238 		simple_unlock(&uobj->vmobjlock);
    239 	}
    240 #endif
    241 
    242 #ifdef DIAGNOSTIC
    243 	if ((u_int)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
    244 	    (u_int)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
    245 		printf(
    246 		    "dev = 0x%x, bsize = %d, osize = %d, nsize = %d, fs = %s\n",
    247 		    ip->i_dev, fs->fs_bsize, osize, nsize, fs->fs_fsmnt);
    248 		panic("ffs_realloccg: bad size");
    249 	}
    250 	if (cred == NOCRED)
    251 		panic("ffs_realloccg: missing credential");
    252 #endif /* DIAGNOSTIC */
    253 	if (cred->cr_uid != 0 && freespace(fs, fs->fs_minfree) <= 0)
    254 		goto nospace;
    255 	if (fs->fs_magic == FS_UFS2_MAGIC)
    256 		bprev = ufs_rw64(ip->i_ffs2_db[lbprev], UFS_FSNEEDSWAP(fs));
    257 	else
    258 		bprev = ufs_rw32(ip->i_ffs1_db[lbprev], UFS_FSNEEDSWAP(fs));
    259 
    260 	if (bprev == 0) {
    261 		printf("dev = 0x%x, bsize = %d, bprev = %" PRId64 ", fs = %s\n",
    262 		    ip->i_dev, fs->fs_bsize, bprev, fs->fs_fsmnt);
    263 		panic("ffs_realloccg: bad bprev");
    264 	}
    265 	/*
    266 	 * Allocate the extra space in the buffer.
    267 	 */
    268 	if (bpp != NULL &&
    269 	    (error = bread(ITOV(ip), lbprev, osize, NOCRED, &bp)) != 0) {
    270 		brelse(bp);
    271 		return (error);
    272 	}
    273 #ifdef QUOTA
    274 	if ((error = chkdq(ip, btodb(nsize - osize), cred, 0)) != 0) {
    275 		if (bpp != NULL) {
    276 			brelse(bp);
    277 		}
    278 		return (error);
    279 	}
    280 #endif
    281 	/*
    282 	 * Check for extension in the existing location.
    283 	 */
    284 	cg = dtog(fs, bprev);
    285 	if ((bno = ffs_fragextend(ip, cg, bprev, osize, nsize)) != 0) {
    286 		DIP(ip, blocks) += btodb(nsize - osize);
    287 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
    288 
    289 		if (bpp != NULL) {
    290 			if (bp->b_blkno != fsbtodb(fs, bno))
    291 				panic("bad blockno");
    292 			allocbuf(bp, nsize);
    293 			bp->b_flags |= B_DONE;
    294 			memset(bp->b_data + osize, 0, nsize - osize);
    295 			*bpp = bp;
    296 		}
    297 		if (blknop != NULL) {
    298 			*blknop = bno;
    299 		}
    300 		return (0);
    301 	}
    302 	/*
    303 	 * Allocate a new disk location.
    304 	 */
    305 	if (bpref >= fs->fs_size)
    306 		bpref = 0;
    307 	switch ((int)fs->fs_optim) {
    308 	case FS_OPTSPACE:
    309 		/*
    310 		 * Allocate an exact sized fragment. Although this makes
    311 		 * best use of space, we will waste time relocating it if
    312 		 * the file continues to grow. If the fragmentation is
    313 		 * less than half of the minimum free reserve, we choose
    314 		 * to begin optimizing for time.
    315 		 */
    316 		request = nsize;
    317 		if (fs->fs_minfree < 5 ||
    318 		    fs->fs_cstotal.cs_nffree >
    319 		    fs->fs_dsize * fs->fs_minfree / (2 * 100))
    320 			break;
    321 
    322 		if (ffs_log_changeopt) {
    323 			log(LOG_NOTICE,
    324 				"%s: optimization changed from SPACE to TIME\n",
    325 				fs->fs_fsmnt);
    326 		}
    327 
    328 		fs->fs_optim = FS_OPTTIME;
    329 		break;
    330 	case FS_OPTTIME:
    331 		/*
    332 		 * At this point we have discovered a file that is trying to
    333 		 * grow a small fragment to a larger fragment. To save time,
    334 		 * we allocate a full sized block, then free the unused portion.
    335 		 * If the file continues to grow, the `ffs_fragextend' call
    336 		 * above will be able to grow it in place without further
    337 		 * copying. If aberrant programs cause disk fragmentation to
    338 		 * grow within 2% of the free reserve, we choose to begin
    339 		 * optimizing for space.
    340 		 */
    341 		request = fs->fs_bsize;
    342 		if (fs->fs_cstotal.cs_nffree <
    343 		    fs->fs_dsize * (fs->fs_minfree - 2) / 100)
    344 			break;
    345 
    346 		if (ffs_log_changeopt) {
    347 			log(LOG_NOTICE,
    348 				"%s: optimization changed from TIME to SPACE\n",
    349 				fs->fs_fsmnt);
    350 		}
    351 
    352 		fs->fs_optim = FS_OPTSPACE;
    353 		break;
    354 	default:
    355 		printf("dev = 0x%x, optim = %d, fs = %s\n",
    356 		    ip->i_dev, fs->fs_optim, fs->fs_fsmnt);
    357 		panic("ffs_realloccg: bad optim");
    358 		/* NOTREACHED */
    359 	}
    360 	bno = ffs_hashalloc(ip, cg, bpref, request, ffs_alloccg);
    361 	if (bno > 0) {
    362 		if (!DOINGSOFTDEP(ITOV(ip)))
    363 			ffs_blkfree(ip, bprev, (long)osize);
    364 		if (nsize < request)
    365 			ffs_blkfree(ip, bno + numfrags(fs, nsize),
    366 			    (long)(request - nsize));
    367 		DIP(ip, blocks) += btodb(nsize - osize);
    368 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
    369 		if (bpp != NULL) {
    370 			bp->b_blkno = fsbtodb(fs, bno);
    371 			allocbuf(bp, nsize);
    372 			bp->b_flags |= B_DONE;
    373 			memset(bp->b_data + osize, 0, (u_int)nsize - osize);
    374 			*bpp = bp;
    375 		}
    376 		if (blknop != NULL) {
    377 			*blknop = bno;
    378 		}
    379 		return (0);
    380 	}
    381 #ifdef QUOTA
    382 	/*
    383 	 * Restore user's disk quota because allocation failed.
    384 	 */
    385 	(void) chkdq(ip, -btodb(nsize - osize), cred, FORCE);
    386 #endif
    387 	if (bpp != NULL) {
    388 		brelse(bp);
    389 	}
    390 
    391 nospace:
    392 	/*
    393 	 * no space available
    394 	 */
    395 	ffs_fserr(fs, cred->cr_uid, "file system full");
    396 	uprintf("\n%s: write failed, file system is full\n", fs->fs_fsmnt);
    397 	return (ENOSPC);
    398 }
    399 
    400 /*
    401  * Reallocate a sequence of blocks into a contiguous sequence of blocks.
    402  *
    403  * The vnode and an array of buffer pointers for a range of sequential
    404  * logical blocks to be made contiguous is given. The allocator attempts
    405  * to find a range of sequential blocks starting as close as possible
    406  * from the end of the allocation for the logical block immediately
    407  * preceding the current range. If successful, the physical block numbers
    408  * in the buffer pointers and in the inode are changed to reflect the new
    409  * allocation. If unsuccessful, the allocation is left unchanged. The
    410  * success in doing the reallocation is returned. Note that the error
    411  * return is not reflected back to the user. Rather the previous block
    412  * allocation will be used.
    413 
    414  */
    415 #ifdef XXXUBC
    416 #ifdef DEBUG
    417 #include <sys/sysctl.h>
    418 int prtrealloc = 0;
    419 struct ctldebug debug15 = { "prtrealloc", &prtrealloc };
    420 #endif
    421 #endif
    422 
    423 /*
    424  * NOTE: when re-enabling this, it must be updated for UFS2.
    425  */
    426 
    427 int doasyncfree = 1;
    428 
    429 int
    430 ffs_reallocblks(v)
    431 	void *v;
    432 {
    433 #ifdef XXXUBC
    434 	struct vop_reallocblks_args /* {
    435 		struct vnode *a_vp;
    436 		struct cluster_save *a_buflist;
    437 	} */ *ap = v;
    438 	struct fs *fs;
    439 	struct inode *ip;
    440 	struct vnode *vp;
    441 	struct buf *sbp, *ebp;
    442 	int32_t *bap, *ebap = NULL, *sbap;	/* XXX ondisk32 */
    443 	struct cluster_save *buflist;
    444 	daddr_t start_lbn, end_lbn, soff, newblk, blkno;
    445 	struct indir start_ap[NIADDR + 1], end_ap[NIADDR + 1], *idp;
    446 	int i, len, start_lvl, end_lvl, pref, ssize;
    447 #endif /* XXXUBC */
    448 
    449 	/* XXXUBC don't reallocblks for now */
    450 	return ENOSPC;
    451 
    452 #ifdef XXXUBC
    453 	vp = ap->a_vp;
    454 	ip = VTOI(vp);
    455 	fs = ip->i_fs;
    456 	if (fs->fs_contigsumsize <= 0)
    457 		return (ENOSPC);
    458 	buflist = ap->a_buflist;
    459 	len = buflist->bs_nchildren;
    460 	start_lbn = buflist->bs_children[0]->b_lblkno;
    461 	end_lbn = start_lbn + len - 1;
    462 #ifdef DIAGNOSTIC
    463 	for (i = 0; i < len; i++)
    464 		if (!ffs_checkblk(ip,
    465 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
    466 			panic("ffs_reallocblks: unallocated block 1");
    467 	for (i = 1; i < len; i++)
    468 		if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
    469 			panic("ffs_reallocblks: non-logical cluster");
    470 	blkno = buflist->bs_children[0]->b_blkno;
    471 	ssize = fsbtodb(fs, fs->fs_frag);
    472 	for (i = 1; i < len - 1; i++)
    473 		if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
    474 			panic("ffs_reallocblks: non-physical cluster %d", i);
    475 #endif
    476 	/*
    477 	 * If the latest allocation is in a new cylinder group, assume that
    478 	 * the filesystem has decided to move and do not force it back to
    479 	 * the previous cylinder group.
    480 	 */
    481 	if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
    482 	    dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
    483 		return (ENOSPC);
    484 	if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
    485 	    ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
    486 		return (ENOSPC);
    487 	/*
    488 	 * Get the starting offset and block map for the first block.
    489 	 */
    490 	if (start_lvl == 0) {
    491 		sbap = &ip->i_ffs1_db[0];
    492 		soff = start_lbn;
    493 	} else {
    494 		idp = &start_ap[start_lvl - 1];
    495 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
    496 			brelse(sbp);
    497 			return (ENOSPC);
    498 		}
    499 		sbap = (int32_t *)sbp->b_data;
    500 		soff = idp->in_off;
    501 	}
    502 	/*
    503 	 * Find the preferred location for the cluster.
    504 	 */
    505 	pref = ffs_blkpref(ip, start_lbn, soff, sbap);
    506 	/*
    507 	 * If the block range spans two block maps, get the second map.
    508 	 */
    509 	if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
    510 		ssize = len;
    511 	} else {
    512 #ifdef DIAGNOSTIC
    513 		if (start_ap[start_lvl-1].in_lbn == idp->in_lbn)
    514 			panic("ffs_reallocblk: start == end");
    515 #endif
    516 		ssize = len - (idp->in_off + 1);
    517 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
    518 			goto fail;
    519 		ebap = (int32_t *)ebp->b_data;	/* XXX ondisk32 */
    520 	}
    521 	/*
    522 	 * Search the block map looking for an allocation of the desired size.
    523 	 */
    524 	if ((newblk = (daddr_t)ffs_hashalloc(ip, dtog(fs, pref), (long)pref,
    525 	    len, ffs_clusteralloc)) == 0)
    526 		goto fail;
    527 	/*
    528 	 * We have found a new contiguous block.
    529 	 *
    530 	 * First we have to replace the old block pointers with the new
    531 	 * block pointers in the inode and indirect blocks associated
    532 	 * with the file.
    533 	 */
    534 #ifdef DEBUG
    535 	if (prtrealloc)
    536 		printf("realloc: ino %d, lbns %d-%d\n\told:", ip->i_number,
    537 		    start_lbn, end_lbn);
    538 #endif
    539 	blkno = newblk;
    540 	for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
    541 		daddr_t ba;
    542 
    543 		if (i == ssize) {
    544 			bap = ebap;
    545 			soff = -i;
    546 		}
    547 		/* XXX ondisk32 */
    548 		ba = ufs_rw32(*bap, UFS_FSNEEDSWAP(fs));
    549 #ifdef DIAGNOSTIC
    550 		if (!ffs_checkblk(ip,
    551 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
    552 			panic("ffs_reallocblks: unallocated block 2");
    553 		if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != ba)
    554 			panic("ffs_reallocblks: alloc mismatch");
    555 #endif
    556 #ifdef DEBUG
    557 		if (prtrealloc)
    558 			printf(" %d,", ba);
    559 #endif
    560  		if (DOINGSOFTDEP(vp)) {
    561  			if (sbap == &ip->i_ffs1_db[0] && i < ssize)
    562  				softdep_setup_allocdirect(ip, start_lbn + i,
    563  				    blkno, ba, fs->fs_bsize, fs->fs_bsize,
    564  				    buflist->bs_children[i]);
    565  			else
    566  				softdep_setup_allocindir_page(ip, start_lbn + i,
    567  				    i < ssize ? sbp : ebp, soff + i, blkno,
    568  				    ba, buflist->bs_children[i]);
    569  		}
    570 		/* XXX ondisk32 */
    571 		*bap++ = ufs_rw32((int32_t)blkno, UFS_FSNEEDSWAP(fs));
    572 	}
    573 	/*
    574 	 * Next we must write out the modified inode and indirect blocks.
    575 	 * For strict correctness, the writes should be synchronous since
    576 	 * the old block values may have been written to disk. In practise
    577 	 * they are almost never written, but if we are concerned about
    578 	 * strict correctness, the `doasyncfree' flag should be set to zero.
    579 	 *
    580 	 * The test on `doasyncfree' should be changed to test a flag
    581 	 * that shows whether the associated buffers and inodes have
    582 	 * been written. The flag should be set when the cluster is
    583 	 * started and cleared whenever the buffer or inode is flushed.
    584 	 * We can then check below to see if it is set, and do the
    585 	 * synchronous write only when it has been cleared.
    586 	 */
    587 	if (sbap != &ip->i_ffs1_db[0]) {
    588 		if (doasyncfree)
    589 			bdwrite(sbp);
    590 		else
    591 			bwrite(sbp);
    592 	} else {
    593 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
    594 		if (!doasyncfree)
    595 			VOP_UPDATE(vp, NULL, NULL, 1);
    596 	}
    597 	if (ssize < len) {
    598 		if (doasyncfree)
    599 			bdwrite(ebp);
    600 		else
    601 			bwrite(ebp);
    602 	}
    603 	/*
    604 	 * Last, free the old blocks and assign the new blocks to the buffers.
    605 	 */
    606 #ifdef DEBUG
    607 	if (prtrealloc)
    608 		printf("\n\tnew:");
    609 #endif
    610 	for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
    611 		if (!DOINGSOFTDEP(vp))
    612 			ffs_blkfree(ip,
    613 			    dbtofsb(fs, buflist->bs_children[i]->b_blkno),
    614 			    fs->fs_bsize);
    615 		buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
    616 #ifdef DEBUG
    617 		if (!ffs_checkblk(ip,
    618 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
    619 			panic("ffs_reallocblks: unallocated block 3");
    620 		if (prtrealloc)
    621 			printf(" %d,", blkno);
    622 #endif
    623 	}
    624 #ifdef DEBUG
    625 	if (prtrealloc) {
    626 		prtrealloc--;
    627 		printf("\n");
    628 	}
    629 #endif
    630 	return (0);
    631 
    632 fail:
    633 	if (ssize < len)
    634 		brelse(ebp);
    635 	if (sbap != &ip->i_ffs1_db[0])
    636 		brelse(sbp);
    637 	return (ENOSPC);
    638 #endif /* XXXUBC */
    639 }
    640 
    641 /*
    642  * Allocate an inode in the file system.
    643  *
    644  * If allocating a directory, use ffs_dirpref to select the inode.
    645  * If allocating in a directory, the following hierarchy is followed:
    646  *   1) allocate the preferred inode.
    647  *   2) allocate an inode in the same cylinder group.
    648  *   3) quadradically rehash into other cylinder groups, until an
    649  *      available inode is located.
    650  * If no inode preference is given the following hierarchy is used
    651  * to allocate an inode:
    652  *   1) allocate an inode in cylinder group 0.
    653  *   2) quadradically rehash into other cylinder groups, until an
    654  *      available inode is located.
    655  */
    656 int
    657 ffs_valloc(v)
    658 	void *v;
    659 {
    660 	struct vop_valloc_args /* {
    661 		struct vnode *a_pvp;
    662 		int a_mode;
    663 		struct ucred *a_cred;
    664 		struct vnode **a_vpp;
    665 	} */ *ap = v;
    666 	struct vnode *pvp = ap->a_pvp;
    667 	struct inode *pip;
    668 	struct fs *fs;
    669 	struct inode *ip;
    670 	struct timespec ts;
    671 	mode_t mode = ap->a_mode;
    672 	ino_t ino, ipref;
    673 	int cg, error;
    674 
    675 	*ap->a_vpp = NULL;
    676 	pip = VTOI(pvp);
    677 	fs = pip->i_fs;
    678 	if (fs->fs_cstotal.cs_nifree == 0)
    679 		goto noinodes;
    680 
    681 	if ((mode & IFMT) == IFDIR)
    682 		ipref = ffs_dirpref(pip);
    683 	else
    684 		ipref = pip->i_number;
    685 	if (ipref >= fs->fs_ncg * fs->fs_ipg)
    686 		ipref = 0;
    687 	cg = ino_to_cg(fs, ipref);
    688 	/*
    689 	 * Track number of dirs created one after another
    690 	 * in a same cg without intervening by files.
    691 	 */
    692 	if ((mode & IFMT) == IFDIR) {
    693 		if (fs->fs_contigdirs[cg] < 255)
    694 			fs->fs_contigdirs[cg]++;
    695 	} else {
    696 		if (fs->fs_contigdirs[cg] > 0)
    697 			fs->fs_contigdirs[cg]--;
    698 	}
    699 	ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode, ffs_nodealloccg);
    700 	if (ino == 0)
    701 		goto noinodes;
    702 	error = VFS_VGET(pvp->v_mount, ino, ap->a_vpp);
    703 	if (error) {
    704 		VOP_VFREE(pvp, ino, mode);
    705 		return (error);
    706 	}
    707 	ip = VTOI(*ap->a_vpp);
    708 	if (ip->i_mode) {
    709 #if 0
    710 		printf("mode = 0%o, inum = %d, fs = %s\n",
    711 		    ip->i_mode, ip->i_number, fs->fs_fsmnt);
    712 #else
    713 		printf("dmode %x mode %x dgen %x gen %x\n",
    714 		    DIP(ip, mode), ip->i_mode,
    715 		    DIP(ip, gen), ip->i_gen);
    716 		printf("size %llx blocks %llx\n",
    717 		    (long long)DIP(ip, size), (long long)DIP(ip, blocks));
    718 		printf("ino %u ipref %u\n", ino, ipref);
    719 #if 0
    720 		error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ino)),
    721 		    (int)fs->fs_bsize, NOCRED, &bp);
    722 #endif
    723 
    724 #endif
    725 		panic("ffs_valloc: dup alloc");
    726 	}
    727 	if (DIP(ip, blocks)) {				/* XXX */
    728 		printf("free inode %s/%d had %" PRId64 " blocks\n",
    729 		    fs->fs_fsmnt, ino, DIP(ip, blocks));
    730 		DIP(ip, blocks) = 0;
    731 	}
    732 	ip->i_flag &= ~IN_SPACECOUNTED;
    733 	ip->i_flags = 0;
    734 	DIP(ip, flags) = 0;
    735 	/*
    736 	 * Set up a new generation number for this inode.
    737 	 */
    738 	ip->i_gen++;
    739 	DIP(ip, gen) = ip->i_gen;
    740 	if (fs->fs_magic == FS_UFS2_MAGIC) {
    741 		TIMEVAL_TO_TIMESPEC(&time, &ts);
    742 		ip->i_ffs2_birthtime = ts.tv_sec;
    743 		ip->i_ffs2_birthnsec = ts.tv_nsec;
    744 	}
    745 	return (0);
    746 noinodes:
    747 	ffs_fserr(fs, ap->a_cred->cr_uid, "out of inodes");
    748 	uprintf("\n%s: create/symlink failed, no inodes free\n", fs->fs_fsmnt);
    749 	return (ENOSPC);
    750 }
    751 
    752 /*
    753  * Find a cylinder group in which to place a directory.
    754  *
    755  * The policy implemented by this algorithm is to allocate a
    756  * directory inode in the same cylinder group as its parent
    757  * directory, but also to reserve space for its files inodes
    758  * and data. Restrict the number of directories which may be
    759  * allocated one after another in the same cylinder group
    760  * without intervening allocation of files.
    761  *
    762  * If we allocate a first level directory then force allocation
    763  * in another cylinder group.
    764  */
    765 static ino_t
    766 ffs_dirpref(pip)
    767 	struct inode *pip;
    768 {
    769 	register struct fs *fs;
    770 	int cg, prefcg, dirsize, cgsize;
    771 	int avgifree, avgbfree, avgndir, curdirsize;
    772 	int minifree, minbfree, maxndir;
    773 	int mincg, minndir;
    774 	int maxcontigdirs;
    775 
    776 	fs = pip->i_fs;
    777 
    778 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
    779 	avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
    780 	avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
    781 
    782 	/*
    783 	 * Force allocation in another cg if creating a first level dir.
    784 	 */
    785 	if (ITOV(pip)->v_flag & VROOT) {
    786 		prefcg = random() % fs->fs_ncg;
    787 		mincg = prefcg;
    788 		minndir = fs->fs_ipg;
    789 		for (cg = prefcg; cg < fs->fs_ncg; cg++)
    790 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
    791 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
    792 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    793 				mincg = cg;
    794 				minndir = fs->fs_cs(fs, cg).cs_ndir;
    795 			}
    796 		for (cg = 0; cg < prefcg; cg++)
    797 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
    798 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
    799 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    800 				mincg = cg;
    801 				minndir = fs->fs_cs(fs, cg).cs_ndir;
    802 			}
    803 		return ((ino_t)(fs->fs_ipg * mincg));
    804 	}
    805 
    806 	/*
    807 	 * Count various limits which used for
    808 	 * optimal allocation of a directory inode.
    809 	 */
    810 	maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
    811 	minifree = avgifree - fs->fs_ipg / 4;
    812 	if (minifree < 0)
    813 		minifree = 0;
    814 	minbfree = avgbfree - fragstoblks(fs, fs->fs_fpg) / 4;
    815 	if (minbfree < 0)
    816 		minbfree = 0;
    817 	cgsize = fs->fs_fsize * fs->fs_fpg;
    818 	dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
    819 	curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
    820 	if (dirsize < curdirsize)
    821 		dirsize = curdirsize;
    822 	maxcontigdirs = min(cgsize / dirsize, 255);
    823 	if (fs->fs_avgfpdir > 0)
    824 		maxcontigdirs = min(maxcontigdirs,
    825 				    fs->fs_ipg / fs->fs_avgfpdir);
    826 	if (maxcontigdirs == 0)
    827 		maxcontigdirs = 1;
    828 
    829 	/*
    830 	 * Limit number of dirs in one cg and reserve space for
    831 	 * regular files, but only if we have no deficit in
    832 	 * inodes or space.
    833 	 */
    834 	prefcg = ino_to_cg(fs, pip->i_number);
    835 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
    836 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
    837 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
    838 	    	    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
    839 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
    840 				return ((ino_t)(fs->fs_ipg * cg));
    841 		}
    842 	for (cg = 0; cg < prefcg; cg++)
    843 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
    844 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
    845 	    	    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
    846 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
    847 				return ((ino_t)(fs->fs_ipg * cg));
    848 		}
    849 	/*
    850 	 * This is a backstop when we are deficient in space.
    851 	 */
    852 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
    853 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
    854 			return ((ino_t)(fs->fs_ipg * cg));
    855 	for (cg = 0; cg < prefcg; cg++)
    856 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
    857 			break;
    858 	return ((ino_t)(fs->fs_ipg * cg));
    859 }
    860 
    861 /*
    862  * Select the desired position for the next block in a file.  The file is
    863  * logically divided into sections. The first section is composed of the
    864  * direct blocks. Each additional section contains fs_maxbpg blocks.
    865  *
    866  * If no blocks have been allocated in the first section, the policy is to
    867  * request a block in the same cylinder group as the inode that describes
    868  * the file. If no blocks have been allocated in any other section, the
    869  * policy is to place the section in a cylinder group with a greater than
    870  * average number of free blocks.  An appropriate cylinder group is found
    871  * by using a rotor that sweeps the cylinder groups. When a new group of
    872  * blocks is needed, the sweep begins in the cylinder group following the
    873  * cylinder group from which the previous allocation was made. The sweep
    874  * continues until a cylinder group with greater than the average number
    875  * of free blocks is found. If the allocation is for the first block in an
    876  * indirect block, the information on the previous allocation is unavailable;
    877  * here a best guess is made based upon the logical block number being
    878  * allocated.
    879  *
    880  * If a section is already partially allocated, the policy is to
    881  * contiguously allocate fs_maxcontig blocks.  The end of one of these
    882  * contiguous blocks and the beginning of the next is laid out
    883  * contigously if possible.
    884  */
    885 daddr_t
    886 ffs_blkpref_ufs1(ip, lbn, indx, bap)
    887 	struct inode *ip;
    888 	daddr_t lbn;
    889 	int indx;
    890 	int32_t *bap;	/* XXX ondisk32 */
    891 {
    892 	struct fs *fs;
    893 	int cg;
    894 	int avgbfree, startcg;
    895 
    896 	fs = ip->i_fs;
    897 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
    898 		if (lbn < NDADDR + NINDIR(fs)) {
    899 			cg = ino_to_cg(fs, ip->i_number);
    900 			return (fs->fs_fpg * cg + fs->fs_frag);
    901 		}
    902 		/*
    903 		 * Find a cylinder with greater than average number of
    904 		 * unused data blocks.
    905 		 */
    906 		if (indx == 0 || bap[indx - 1] == 0)
    907 			startcg =
    908 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
    909 		else
    910 			startcg = dtog(fs,
    911 				ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + 1);
    912 		startcg %= fs->fs_ncg;
    913 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
    914 		for (cg = startcg; cg < fs->fs_ncg; cg++)
    915 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    916 				return (fs->fs_fpg * cg + fs->fs_frag);
    917 			}
    918 		for (cg = 0; cg < startcg; cg++)
    919 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    920 				return (fs->fs_fpg * cg + fs->fs_frag);
    921 			}
    922 		return (0);
    923 	}
    924 	/*
    925 	 * We just always try to lay things out contiguously.
    926 	 */
    927 	return ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + fs->fs_frag;
    928 }
    929 
    930 daddr_t
    931 ffs_blkpref_ufs2(ip, lbn, indx, bap)
    932 	struct inode *ip;
    933 	daddr_t lbn;
    934 	int indx;
    935 	int64_t *bap;
    936 {
    937 	struct fs *fs;
    938 	int cg;
    939 	int avgbfree, startcg;
    940 
    941 	fs = ip->i_fs;
    942 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
    943 		if (lbn < NDADDR + NINDIR(fs)) {
    944 			cg = ino_to_cg(fs, ip->i_number);
    945 			return (fs->fs_fpg * cg + fs->fs_frag);
    946 		}
    947 		/*
    948 		 * Find a cylinder with greater than average number of
    949 		 * unused data blocks.
    950 		 */
    951 		if (indx == 0 || bap[indx - 1] == 0)
    952 			startcg =
    953 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
    954 		else
    955 			startcg = dtog(fs,
    956 				ufs_rw64(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + 1);
    957 		startcg %= fs->fs_ncg;
    958 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
    959 		for (cg = startcg; cg < fs->fs_ncg; cg++)
    960 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    961 				return (fs->fs_fpg * cg + fs->fs_frag);
    962 			}
    963 		for (cg = 0; cg < startcg; cg++)
    964 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    965 				return (fs->fs_fpg * cg + fs->fs_frag);
    966 			}
    967 		return (0);
    968 	}
    969 	/*
    970 	 * We just always try to lay things out contiguously.
    971 	 */
    972 	return ufs_rw64(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + fs->fs_frag;
    973 }
    974 
    975 
    976 /*
    977  * Implement the cylinder overflow algorithm.
    978  *
    979  * The policy implemented by this algorithm is:
    980  *   1) allocate the block in its requested cylinder group.
    981  *   2) quadradically rehash on the cylinder group number.
    982  *   3) brute force search for a free block.
    983  */
    984 /*VARARGS5*/
    985 static daddr_t
    986 ffs_hashalloc(ip, cg, pref, size, allocator)
    987 	struct inode *ip;
    988 	int cg;
    989 	daddr_t pref;
    990 	int size;	/* size for data blocks, mode for inodes */
    991 	daddr_t (*allocator) __P((struct inode *, int, daddr_t, int));
    992 {
    993 	struct fs *fs;
    994 	daddr_t result;
    995 	int i, icg = cg;
    996 
    997 	fs = ip->i_fs;
    998 	/*
    999 	 * 1: preferred cylinder group
   1000 	 */
   1001 	result = (*allocator)(ip, cg, pref, size);
   1002 	if (result)
   1003 		return (result);
   1004 	/*
   1005 	 * 2: quadratic rehash
   1006 	 */
   1007 	for (i = 1; i < fs->fs_ncg; i *= 2) {
   1008 		cg += i;
   1009 		if (cg >= fs->fs_ncg)
   1010 			cg -= fs->fs_ncg;
   1011 		result = (*allocator)(ip, cg, 0, size);
   1012 		if (result)
   1013 			return (result);
   1014 	}
   1015 	/*
   1016 	 * 3: brute force search
   1017 	 * Note that we start at i == 2, since 0 was checked initially,
   1018 	 * and 1 is always checked in the quadratic rehash.
   1019 	 */
   1020 	cg = (icg + 2) % fs->fs_ncg;
   1021 	for (i = 2; i < fs->fs_ncg; i++) {
   1022 		result = (*allocator)(ip, cg, 0, size);
   1023 		if (result)
   1024 			return (result);
   1025 		cg++;
   1026 		if (cg == fs->fs_ncg)
   1027 			cg = 0;
   1028 	}
   1029 	return (0);
   1030 }
   1031 
   1032 /*
   1033  * Determine whether a fragment can be extended.
   1034  *
   1035  * Check to see if the necessary fragments are available, and
   1036  * if they are, allocate them.
   1037  */
   1038 static daddr_t
   1039 ffs_fragextend(ip, cg, bprev, osize, nsize)
   1040 	struct inode *ip;
   1041 	int cg;
   1042 	daddr_t bprev;
   1043 	int osize, nsize;
   1044 {
   1045 	struct fs *fs;
   1046 	struct cg *cgp;
   1047 	struct buf *bp;
   1048 	daddr_t bno;
   1049 	int frags, bbase;
   1050 	int i, error;
   1051 	u_int8_t *blksfree;
   1052 
   1053 	fs = ip->i_fs;
   1054 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
   1055 		return (0);
   1056 	frags = numfrags(fs, nsize);
   1057 	bbase = fragnum(fs, bprev);
   1058 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
   1059 		/* cannot extend across a block boundary */
   1060 		return (0);
   1061 	}
   1062 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1063 		(int)fs->fs_cgsize, NOCRED, &bp);
   1064 	if (error) {
   1065 		brelse(bp);
   1066 		return (0);
   1067 	}
   1068 	cgp = (struct cg *)bp->b_data;
   1069 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs))) {
   1070 		brelse(bp);
   1071 		return (0);
   1072 	}
   1073 	cgp->cg_old_time = ufs_rw32(time.tv_sec, UFS_FSNEEDSWAP(fs));
   1074 	cgp->cg_time = ufs_rw64(time.tv_sec, UFS_FSNEEDSWAP(fs));
   1075 	bno = dtogd(fs, bprev);
   1076 	blksfree = cg_blksfree(cgp, UFS_FSNEEDSWAP(fs));
   1077 	for (i = numfrags(fs, osize); i < frags; i++)
   1078 		if (isclr(blksfree, bno + i)) {
   1079 			brelse(bp);
   1080 			return (0);
   1081 		}
   1082 	/*
   1083 	 * the current fragment can be extended
   1084 	 * deduct the count on fragment being extended into
   1085 	 * increase the count on the remaining fragment (if any)
   1086 	 * allocate the extended piece
   1087 	 */
   1088 	for (i = frags; i < fs->fs_frag - bbase; i++)
   1089 		if (isclr(blksfree, bno + i))
   1090 			break;
   1091 	ufs_add32(cgp->cg_frsum[i - numfrags(fs, osize)], -1, UFS_FSNEEDSWAP(fs));
   1092 	if (i != frags)
   1093 		ufs_add32(cgp->cg_frsum[i - frags], 1, UFS_FSNEEDSWAP(fs));
   1094 	for (i = numfrags(fs, osize); i < frags; i++) {
   1095 		clrbit(blksfree, bno + i);
   1096 		ufs_add32(cgp->cg_cs.cs_nffree, -1, UFS_FSNEEDSWAP(fs));
   1097 		fs->fs_cstotal.cs_nffree--;
   1098 		fs->fs_cs(fs, cg).cs_nffree--;
   1099 	}
   1100 	fs->fs_fmod = 1;
   1101 	if (DOINGSOFTDEP(ITOV(ip)))
   1102 		softdep_setup_blkmapdep(bp, fs, bprev);
   1103 	bdwrite(bp);
   1104 	return (bprev);
   1105 }
   1106 
   1107 /*
   1108  * Determine whether a block can be allocated.
   1109  *
   1110  * Check to see if a block of the appropriate size is available,
   1111  * and if it is, allocate it.
   1112  */
   1113 static daddr_t
   1114 ffs_alloccg(ip, cg, bpref, size)
   1115 	struct inode *ip;
   1116 	int cg;
   1117 	daddr_t bpref;
   1118 	int size;
   1119 {
   1120 	struct fs *fs = ip->i_fs;
   1121 	struct cg *cgp;
   1122 	struct buf *bp;
   1123 	int32_t bno;
   1124 	daddr_t blkno;
   1125 	int error, frags, allocsiz, i;
   1126 	u_int8_t *blksfree;
   1127 #ifdef FFS_EI
   1128 	const int needswap = UFS_FSNEEDSWAP(fs);
   1129 #endif
   1130 
   1131 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
   1132 		return (0);
   1133 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1134 		(int)fs->fs_cgsize, NOCRED, &bp);
   1135 	if (error) {
   1136 		brelse(bp);
   1137 		return (0);
   1138 	}
   1139 	cgp = (struct cg *)bp->b_data;
   1140 	if (!cg_chkmagic(cgp, needswap) ||
   1141 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize)) {
   1142 		brelse(bp);
   1143 		return (0);
   1144 	}
   1145 	cgp->cg_old_time = ufs_rw32(time.tv_sec, needswap);
   1146 	cgp->cg_time = ufs_rw64(time.tv_sec, needswap);
   1147 	if (size == fs->fs_bsize) {
   1148 		blkno = ffs_alloccgblk(ip, bp, bpref);
   1149 		bdwrite(bp);
   1150 		return (blkno);
   1151 	}
   1152 	/*
   1153 	 * check to see if any fragments are already available
   1154 	 * allocsiz is the size which will be allocated, hacking
   1155 	 * it down to a smaller size if necessary
   1156 	 */
   1157 	blksfree = cg_blksfree(cgp, needswap);
   1158 	frags = numfrags(fs, size);
   1159 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
   1160 		if (cgp->cg_frsum[allocsiz] != 0)
   1161 			break;
   1162 	if (allocsiz == fs->fs_frag) {
   1163 		/*
   1164 		 * no fragments were available, so a block will be
   1165 		 * allocated, and hacked up
   1166 		 */
   1167 		if (cgp->cg_cs.cs_nbfree == 0) {
   1168 			brelse(bp);
   1169 			return (0);
   1170 		}
   1171 		blkno = ffs_alloccgblk(ip, bp, bpref);
   1172 		bno = dtogd(fs, blkno);
   1173 		for (i = frags; i < fs->fs_frag; i++)
   1174 			setbit(blksfree, bno + i);
   1175 		i = fs->fs_frag - frags;
   1176 		ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
   1177 		fs->fs_cstotal.cs_nffree += i;
   1178 		fs->fs_cs(fs, cg).cs_nffree += i;
   1179 		fs->fs_fmod = 1;
   1180 		ufs_add32(cgp->cg_frsum[i], 1, needswap);
   1181 		bdwrite(bp);
   1182 		return (blkno);
   1183 	}
   1184 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
   1185 #if 0
   1186 	/*
   1187 	 * XXX fvdl mapsearch will panic, and never return -1
   1188 	 *          also: returning NULL as daddr_t ?
   1189 	 */
   1190 	if (bno < 0) {
   1191 		brelse(bp);
   1192 		return (0);
   1193 	}
   1194 #endif
   1195 	for (i = 0; i < frags; i++)
   1196 		clrbit(blksfree, bno + i);
   1197 	ufs_add32(cgp->cg_cs.cs_nffree, -frags, needswap);
   1198 	fs->fs_cstotal.cs_nffree -= frags;
   1199 	fs->fs_cs(fs, cg).cs_nffree -= frags;
   1200 	fs->fs_fmod = 1;
   1201 	ufs_add32(cgp->cg_frsum[allocsiz], -1, needswap);
   1202 	if (frags != allocsiz)
   1203 		ufs_add32(cgp->cg_frsum[allocsiz - frags], 1, needswap);
   1204 	blkno = cg * fs->fs_fpg + bno;
   1205 	if (DOINGSOFTDEP(ITOV(ip)))
   1206 		softdep_setup_blkmapdep(bp, fs, blkno);
   1207 	bdwrite(bp);
   1208 	return blkno;
   1209 }
   1210 
   1211 /*
   1212  * Allocate a block in a cylinder group.
   1213  *
   1214  * This algorithm implements the following policy:
   1215  *   1) allocate the requested block.
   1216  *   2) allocate a rotationally optimal block in the same cylinder.
   1217  *   3) allocate the next available block on the block rotor for the
   1218  *      specified cylinder group.
   1219  * Note that this routine only allocates fs_bsize blocks; these
   1220  * blocks may be fragmented by the routine that allocates them.
   1221  */
   1222 static daddr_t
   1223 ffs_alloccgblk(ip, bp, bpref)
   1224 	struct inode *ip;
   1225 	struct buf *bp;
   1226 	daddr_t bpref;
   1227 {
   1228 	struct fs *fs = ip->i_fs;
   1229 	struct cg *cgp;
   1230 	daddr_t blkno;
   1231 	int32_t bno;
   1232 	u_int8_t *blksfree;
   1233 #ifdef FFS_EI
   1234 	const int needswap = UFS_FSNEEDSWAP(fs);
   1235 #endif
   1236 
   1237 	cgp = (struct cg *)bp->b_data;
   1238 	blksfree = cg_blksfree(cgp, needswap);
   1239 	if (bpref == 0 || dtog(fs, bpref) != ufs_rw32(cgp->cg_cgx, needswap)) {
   1240 		bpref = ufs_rw32(cgp->cg_rotor, needswap);
   1241 	} else {
   1242 		bpref = blknum(fs, bpref);
   1243 		bno = dtogd(fs, bpref);
   1244 		/*
   1245 		 * if the requested block is available, use it
   1246 		 */
   1247 		if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
   1248 			goto gotit;
   1249 	}
   1250 	/*
   1251 	 * Take the next available block in this cylinder group.
   1252 	 */
   1253 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
   1254 	if (bno < 0)
   1255 		return (0);
   1256 	cgp->cg_rotor = ufs_rw32(bno, needswap);
   1257 gotit:
   1258 	blkno = fragstoblks(fs, bno);
   1259 	ffs_clrblock(fs, blksfree, blkno);
   1260 	ffs_clusteracct(fs, cgp, blkno, -1);
   1261 	ufs_add32(cgp->cg_cs.cs_nbfree, -1, needswap);
   1262 	fs->fs_cstotal.cs_nbfree--;
   1263 	fs->fs_cs(fs, ufs_rw32(cgp->cg_cgx, needswap)).cs_nbfree--;
   1264 	fs->fs_fmod = 1;
   1265 	blkno = ufs_rw32(cgp->cg_cgx, needswap) * fs->fs_fpg + bno;
   1266 	if (DOINGSOFTDEP(ITOV(ip)))
   1267 		softdep_setup_blkmapdep(bp, fs, blkno);
   1268 	return (blkno);
   1269 }
   1270 
   1271 #ifdef XXXUBC
   1272 /*
   1273  * Determine whether a cluster can be allocated.
   1274  *
   1275  * We do not currently check for optimal rotational layout if there
   1276  * are multiple choices in the same cylinder group. Instead we just
   1277  * take the first one that we find following bpref.
   1278  */
   1279 
   1280 /*
   1281  * This function must be fixed for UFS2 if re-enabled.
   1282  */
   1283 static daddr_t
   1284 ffs_clusteralloc(ip, cg, bpref, len)
   1285 	struct inode *ip;
   1286 	int cg;
   1287 	daddr_t bpref;
   1288 	int len;
   1289 {
   1290 	struct fs *fs;
   1291 	struct cg *cgp;
   1292 	struct buf *bp;
   1293 	int i, got, run, bno, bit, map;
   1294 	u_char *mapp;
   1295 	int32_t *lp;
   1296 
   1297 	fs = ip->i_fs;
   1298 	if (fs->fs_maxcluster[cg] < len)
   1299 		return (0);
   1300 	if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize,
   1301 	    NOCRED, &bp))
   1302 		goto fail;
   1303 	cgp = (struct cg *)bp->b_data;
   1304 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs)))
   1305 		goto fail;
   1306 	/*
   1307 	 * Check to see if a cluster of the needed size (or bigger) is
   1308 	 * available in this cylinder group.
   1309 	 */
   1310 	lp = &cg_clustersum(cgp, UFS_FSNEEDSWAP(fs))[len];
   1311 	for (i = len; i <= fs->fs_contigsumsize; i++)
   1312 		if (ufs_rw32(*lp++, UFS_FSNEEDSWAP(fs)) > 0)
   1313 			break;
   1314 	if (i > fs->fs_contigsumsize) {
   1315 		/*
   1316 		 * This is the first time looking for a cluster in this
   1317 		 * cylinder group. Update the cluster summary information
   1318 		 * to reflect the true maximum sized cluster so that
   1319 		 * future cluster allocation requests can avoid reading
   1320 		 * the cylinder group map only to find no clusters.
   1321 		 */
   1322 		lp = &cg_clustersum(cgp, UFS_FSNEEDSWAP(fs))[len - 1];
   1323 		for (i = len - 1; i > 0; i--)
   1324 			if (ufs_rw32(*lp--, UFS_FSNEEDSWAP(fs)) > 0)
   1325 				break;
   1326 		fs->fs_maxcluster[cg] = i;
   1327 		goto fail;
   1328 	}
   1329 	/*
   1330 	 * Search the cluster map to find a big enough cluster.
   1331 	 * We take the first one that we find, even if it is larger
   1332 	 * than we need as we prefer to get one close to the previous
   1333 	 * block allocation. We do not search before the current
   1334 	 * preference point as we do not want to allocate a block
   1335 	 * that is allocated before the previous one (as we will
   1336 	 * then have to wait for another pass of the elevator
   1337 	 * algorithm before it will be read). We prefer to fail and
   1338 	 * be recalled to try an allocation in the next cylinder group.
   1339 	 */
   1340 	if (dtog(fs, bpref) != cg)
   1341 		bpref = 0;
   1342 	else
   1343 		bpref = fragstoblks(fs, dtogd(fs, blknum(fs, bpref)));
   1344 	mapp = &cg_clustersfree(cgp, UFS_FSNEEDSWAP(fs))[bpref / NBBY];
   1345 	map = *mapp++;
   1346 	bit = 1 << (bpref % NBBY);
   1347 	for (run = 0, got = bpref;
   1348 		got < ufs_rw32(cgp->cg_nclusterblks, UFS_FSNEEDSWAP(fs)); got++) {
   1349 		if ((map & bit) == 0) {
   1350 			run = 0;
   1351 		} else {
   1352 			run++;
   1353 			if (run == len)
   1354 				break;
   1355 		}
   1356 		if ((got & (NBBY - 1)) != (NBBY - 1)) {
   1357 			bit <<= 1;
   1358 		} else {
   1359 			map = *mapp++;
   1360 			bit = 1;
   1361 		}
   1362 	}
   1363 	if (got == ufs_rw32(cgp->cg_nclusterblks, UFS_FSNEEDSWAP(fs)))
   1364 		goto fail;
   1365 	/*
   1366 	 * Allocate the cluster that we have found.
   1367 	 */
   1368 #ifdef DIAGNOSTIC
   1369 	for (i = 1; i <= len; i++)
   1370 		if (!ffs_isblock(fs, cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)),
   1371 		    got - run + i))
   1372 			panic("ffs_clusteralloc: map mismatch");
   1373 #endif
   1374 	bno = cg * fs->fs_fpg + blkstofrags(fs, got - run + 1);
   1375 	if (dtog(fs, bno) != cg)
   1376 		panic("ffs_clusteralloc: allocated out of group");
   1377 	len = blkstofrags(fs, len);
   1378 	for (i = 0; i < len; i += fs->fs_frag)
   1379 		if ((got = ffs_alloccgblk(ip, bp, bno + i)) != bno + i)
   1380 			panic("ffs_clusteralloc: lost block");
   1381 	bdwrite(bp);
   1382 	return (bno);
   1383 
   1384 fail:
   1385 	brelse(bp);
   1386 	return (0);
   1387 }
   1388 #endif /* XXXUBC */
   1389 
   1390 /*
   1391  * Determine whether an inode can be allocated.
   1392  *
   1393  * Check to see if an inode is available, and if it is,
   1394  * allocate it using the following policy:
   1395  *   1) allocate the requested inode.
   1396  *   2) allocate the next available inode after the requested
   1397  *      inode in the specified cylinder group.
   1398  */
   1399 static daddr_t
   1400 ffs_nodealloccg(ip, cg, ipref, mode)
   1401 	struct inode *ip;
   1402 	int cg;
   1403 	daddr_t ipref;
   1404 	int mode;
   1405 {
   1406 	struct fs *fs = ip->i_fs;
   1407 	struct cg *cgp;
   1408 	struct buf *bp, *ibp;
   1409 	u_int8_t *inosused;
   1410 	int error, start, len, loc, map, i;
   1411 	int32_t initediblk;
   1412 	struct ufs2_dinode *dp2;
   1413 #ifdef FFS_EI
   1414 	const int needswap = UFS_FSNEEDSWAP(fs);
   1415 #endif
   1416 
   1417 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
   1418 		return (0);
   1419 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1420 		(int)fs->fs_cgsize, NOCRED, &bp);
   1421 	if (error) {
   1422 		brelse(bp);
   1423 		return (0);
   1424 	}
   1425 	cgp = (struct cg *)bp->b_data;
   1426 	if (!cg_chkmagic(cgp, needswap) || cgp->cg_cs.cs_nifree == 0) {
   1427 		brelse(bp);
   1428 		return (0);
   1429 	}
   1430 	cgp->cg_old_time = ufs_rw32(time.tv_sec, needswap);
   1431 	cgp->cg_time = ufs_rw64(time.tv_sec, needswap);
   1432 	inosused = cg_inosused(cgp, needswap);
   1433 	if (ipref) {
   1434 		ipref %= fs->fs_ipg;
   1435 		if (isclr(inosused, ipref))
   1436 			goto gotit;
   1437 	}
   1438 	start = ufs_rw32(cgp->cg_irotor, needswap) / NBBY;
   1439 	len = howmany(fs->fs_ipg - ufs_rw32(cgp->cg_irotor, needswap),
   1440 		NBBY);
   1441 	loc = skpc(0xff, len, &inosused[start]);
   1442 	if (loc == 0) {
   1443 		len = start + 1;
   1444 		start = 0;
   1445 		loc = skpc(0xff, len, &inosused[0]);
   1446 		if (loc == 0) {
   1447 			printf("cg = %d, irotor = %d, fs = %s\n",
   1448 			    cg, ufs_rw32(cgp->cg_irotor, needswap),
   1449 				fs->fs_fsmnt);
   1450 			panic("ffs_nodealloccg: map corrupted");
   1451 			/* NOTREACHED */
   1452 		}
   1453 	}
   1454 	i = start + len - loc;
   1455 	map = inosused[i];
   1456 	ipref = i * NBBY;
   1457 	for (i = 1; i < (1 << NBBY); i <<= 1, ipref++) {
   1458 		if ((map & i) == 0) {
   1459 			cgp->cg_irotor = ufs_rw32(ipref, needswap);
   1460 			goto gotit;
   1461 		}
   1462 	}
   1463 	printf("fs = %s\n", fs->fs_fsmnt);
   1464 	panic("ffs_nodealloccg: block not in map");
   1465 	/* NOTREACHED */
   1466 gotit:
   1467 	if (DOINGSOFTDEP(ITOV(ip)))
   1468 		softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref);
   1469 	setbit(inosused, ipref);
   1470 	ufs_add32(cgp->cg_cs.cs_nifree, -1, needswap);
   1471 	fs->fs_cstotal.cs_nifree--;
   1472 	fs->fs_cs(fs, cg).cs_nifree--;
   1473 	fs->fs_fmod = 1;
   1474 	if ((mode & IFMT) == IFDIR) {
   1475 		ufs_add32(cgp->cg_cs.cs_ndir, 1, needswap);
   1476 		fs->fs_cstotal.cs_ndir++;
   1477 		fs->fs_cs(fs, cg).cs_ndir++;
   1478 	}
   1479 	/*
   1480 	 * Check to see if we need to initialize more inodes.
   1481 	 */
   1482 	initediblk = ufs_rw32(cgp->cg_initediblk, needswap);
   1483 	if (fs->fs_magic == FS_UFS2_MAGIC &&
   1484 	    ipref + INOPB(fs) > initediblk &&
   1485 	    initediblk < ufs_rw32(cgp->cg_niblk, needswap)) {
   1486 		ibp = getblk(ip->i_devvp, fsbtodb(fs,
   1487 		    ino_to_fsba(fs, cg * fs->fs_ipg + initediblk)),
   1488 		    (int)fs->fs_bsize, 0, 0);
   1489 		    memset(ibp->b_data, 0, fs->fs_bsize);
   1490 		    dp2 = (struct ufs2_dinode *)(ibp->b_data);
   1491 		    for (i = 0; i < INOPB(fs); i++) {
   1492 			/*
   1493 			 * Don't bother to swap, it's supposed to be
   1494 			 * random, after all.
   1495 			 */
   1496 			dp2->di_gen = random() / 2 + 1;
   1497 			dp2++;
   1498 		}
   1499 		bawrite(ibp);
   1500 		initediblk += INOPB(fs);
   1501 		cgp->cg_initediblk = ufs_rw32(initediblk, needswap);
   1502 	}
   1503 
   1504 	bdwrite(bp);
   1505 	return (cg * fs->fs_ipg + ipref);
   1506 }
   1507 
   1508 /*
   1509  * Free a block or fragment.
   1510  *
   1511  * The specified block or fragment is placed back in the
   1512  * free map. If a fragment is deallocated, a possible
   1513  * block reassembly is checked.
   1514  */
   1515 void
   1516 ffs_blkfree(ip, bno, size)
   1517 	struct inode *ip;
   1518 	daddr_t bno;
   1519 	long size;
   1520 {
   1521 	struct fs *fs = ip->i_fs;
   1522 	struct cg *cgp;
   1523 	struct buf *bp;
   1524 	int32_t fragno, cgbno;
   1525 	int i, error, cg, blk, frags, bbase;
   1526 	u_int8_t *blksfree;
   1527 	const int needswap = UFS_FSNEEDSWAP(fs);
   1528 
   1529 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
   1530 	    fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
   1531 		printf("dev = 0x%x, bno = %" PRId64 " bsize = %d, "
   1532 		       "size = %ld, fs = %s\n",
   1533 		    ip->i_dev, bno, fs->fs_bsize, size, fs->fs_fsmnt);
   1534 		panic("blkfree: bad size");
   1535 	}
   1536 	cg = dtog(fs, bno);
   1537 	if (bno >= fs->fs_size) {
   1538 		printf("bad block %" PRId64 ", ino %d\n", bno, ip->i_number);
   1539 		ffs_fserr(fs, ip->i_uid, "bad block");
   1540 		return;
   1541 	}
   1542 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1543 		(int)fs->fs_cgsize, NOCRED, &bp);
   1544 	if (error) {
   1545 		brelse(bp);
   1546 		return;
   1547 	}
   1548 	cgp = (struct cg *)bp->b_data;
   1549 	if (!cg_chkmagic(cgp, needswap)) {
   1550 		brelse(bp);
   1551 		return;
   1552 	}
   1553 	cgp->cg_old_time = ufs_rw32(time.tv_sec, needswap);
   1554 	cgp->cg_time = ufs_rw64(time.tv_sec, needswap);
   1555 	cgbno = dtogd(fs, bno);
   1556 	blksfree = cg_blksfree(cgp, needswap);
   1557 	if (size == fs->fs_bsize) {
   1558 		fragno = fragstoblks(fs, cgbno);
   1559 		if (!ffs_isfreeblock(fs, blksfree, fragno)) {
   1560 			printf("dev = 0x%x, block = %" PRId64 ", fs = %s\n",
   1561 			    ip->i_dev, bno, fs->fs_fsmnt);
   1562 			panic("blkfree: freeing free block");
   1563 		}
   1564 		ffs_setblock(fs, blksfree, fragno);
   1565 		ffs_clusteracct(fs, cgp, fragno, 1);
   1566 		ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
   1567 		fs->fs_cstotal.cs_nbfree++;
   1568 		fs->fs_cs(fs, cg).cs_nbfree++;
   1569 	} else {
   1570 		bbase = cgbno - fragnum(fs, cgbno);
   1571 		/*
   1572 		 * decrement the counts associated with the old frags
   1573 		 */
   1574 		blk = blkmap(fs, blksfree, bbase);
   1575 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1, needswap);
   1576 		/*
   1577 		 * deallocate the fragment
   1578 		 */
   1579 		frags = numfrags(fs, size);
   1580 		for (i = 0; i < frags; i++) {
   1581 			if (isset(blksfree, cgbno + i)) {
   1582 				printf("dev = 0x%x, block = %" PRId64
   1583 				       ", fs = %s\n",
   1584 				    ip->i_dev, bno + i, fs->fs_fsmnt);
   1585 				panic("blkfree: freeing free frag");
   1586 			}
   1587 			setbit(blksfree, cgbno + i);
   1588 		}
   1589 		ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
   1590 		fs->fs_cstotal.cs_nffree += i;
   1591 		fs->fs_cs(fs, cg).cs_nffree += i;
   1592 		/*
   1593 		 * add back in counts associated with the new frags
   1594 		 */
   1595 		blk = blkmap(fs, blksfree, bbase);
   1596 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1, needswap);
   1597 		/*
   1598 		 * if a complete block has been reassembled, account for it
   1599 		 */
   1600 		fragno = fragstoblks(fs, bbase);
   1601 		if (ffs_isblock(fs, blksfree, fragno)) {
   1602 			ufs_add32(cgp->cg_cs.cs_nffree, -fs->fs_frag, needswap);
   1603 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
   1604 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
   1605 			ffs_clusteracct(fs, cgp, fragno, 1);
   1606 			ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
   1607 			fs->fs_cstotal.cs_nbfree++;
   1608 			fs->fs_cs(fs, cg).cs_nbfree++;
   1609 		}
   1610 	}
   1611 	fs->fs_fmod = 1;
   1612 	bdwrite(bp);
   1613 }
   1614 
   1615 #if defined(DIAGNOSTIC) || defined(DEBUG)
   1616 #ifdef XXXUBC
   1617 /*
   1618  * Verify allocation of a block or fragment. Returns true if block or
   1619  * fragment is allocated, false if it is free.
   1620  */
   1621 static int
   1622 ffs_checkblk(ip, bno, size)
   1623 	struct inode *ip;
   1624 	daddr_t bno;
   1625 	long size;
   1626 {
   1627 	struct fs *fs;
   1628 	struct cg *cgp;
   1629 	struct buf *bp;
   1630 	int i, error, frags, free;
   1631 
   1632 	fs = ip->i_fs;
   1633 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
   1634 		printf("bsize = %d, size = %ld, fs = %s\n",
   1635 		    fs->fs_bsize, size, fs->fs_fsmnt);
   1636 		panic("checkblk: bad size");
   1637 	}
   1638 	if (bno >= fs->fs_size)
   1639 		panic("checkblk: bad block %d", bno);
   1640 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, dtog(fs, bno))),
   1641 		(int)fs->fs_cgsize, NOCRED, &bp);
   1642 	if (error) {
   1643 		brelse(bp);
   1644 		return 0;
   1645 	}
   1646 	cgp = (struct cg *)bp->b_data;
   1647 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs))) {
   1648 		brelse(bp);
   1649 		return 0;
   1650 	}
   1651 	bno = dtogd(fs, bno);
   1652 	if (size == fs->fs_bsize) {
   1653 		free = ffs_isblock(fs, cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)),
   1654 			fragstoblks(fs, bno));
   1655 	} else {
   1656 		frags = numfrags(fs, size);
   1657 		for (free = 0, i = 0; i < frags; i++)
   1658 			if (isset(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i))
   1659 				free++;
   1660 		if (free != 0 && free != frags)
   1661 			panic("checkblk: partially free fragment");
   1662 	}
   1663 	brelse(bp);
   1664 	return (!free);
   1665 }
   1666 #endif /* XXXUBC */
   1667 #endif /* DIAGNOSTIC */
   1668 
   1669 /*
   1670  * Free an inode.
   1671  */
   1672 int
   1673 ffs_vfree(v)
   1674 	void *v;
   1675 {
   1676 	struct vop_vfree_args /* {
   1677 		struct vnode *a_pvp;
   1678 		ino_t a_ino;
   1679 		int a_mode;
   1680 	} */ *ap = v;
   1681 
   1682 	if (DOINGSOFTDEP(ap->a_pvp)) {
   1683 		softdep_freefile(ap);
   1684 		return (0);
   1685 	}
   1686 	return (ffs_freefile(ap));
   1687 }
   1688 
   1689 /*
   1690  * Do the actual free operation.
   1691  * The specified inode is placed back in the free map.
   1692  */
   1693 int
   1694 ffs_freefile(v)
   1695 	void *v;
   1696 {
   1697 	struct vop_vfree_args /* {
   1698 		struct vnode *a_pvp;
   1699 		ino_t a_ino;
   1700 		int a_mode;
   1701 	} */ *ap = v;
   1702 	struct cg *cgp;
   1703 	struct inode *pip = VTOI(ap->a_pvp);
   1704 	struct fs *fs = pip->i_fs;
   1705 	ino_t ino = ap->a_ino;
   1706 	struct buf *bp;
   1707 	int error, cg;
   1708 	u_int8_t *inosused;
   1709 #ifdef FFS_EI
   1710 	const int needswap = UFS_FSNEEDSWAP(fs);
   1711 #endif
   1712 
   1713 	if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
   1714 		panic("ifree: range: dev = 0x%x, ino = %d, fs = %s",
   1715 		    pip->i_dev, ino, fs->fs_fsmnt);
   1716 	cg = ino_to_cg(fs, ino);
   1717 	error = bread(pip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1718 		(int)fs->fs_cgsize, NOCRED, &bp);
   1719 	if (error) {
   1720 		brelse(bp);
   1721 		return (error);
   1722 	}
   1723 	cgp = (struct cg *)bp->b_data;
   1724 	if (!cg_chkmagic(cgp, needswap)) {
   1725 		brelse(bp);
   1726 		return (0);
   1727 	}
   1728 	cgp->cg_old_time = ufs_rw32(time.tv_sec, needswap);
   1729 	cgp->cg_time = ufs_rw64(time.tv_sec, needswap);
   1730 	inosused = cg_inosused(cgp, needswap);
   1731 	ino %= fs->fs_ipg;
   1732 	if (isclr(inosused, ino)) {
   1733 		printf("dev = 0x%x, ino = %d, fs = %s\n",
   1734 		    pip->i_dev, ino, fs->fs_fsmnt);
   1735 		if (fs->fs_ronly == 0)
   1736 			panic("ifree: freeing free inode");
   1737 	}
   1738 	clrbit(inosused, ino);
   1739 	if (ino < ufs_rw32(cgp->cg_irotor, needswap))
   1740 		cgp->cg_irotor = ufs_rw32(ino, needswap);
   1741 	ufs_add32(cgp->cg_cs.cs_nifree, 1, needswap);
   1742 	fs->fs_cstotal.cs_nifree++;
   1743 	fs->fs_cs(fs, cg).cs_nifree++;
   1744 	if ((ap->a_mode & IFMT) == IFDIR) {
   1745 		ufs_add32(cgp->cg_cs.cs_ndir, -1, needswap);
   1746 		fs->fs_cstotal.cs_ndir--;
   1747 		fs->fs_cs(fs, cg).cs_ndir--;
   1748 	}
   1749 	fs->fs_fmod = 1;
   1750 	bdwrite(bp);
   1751 	return (0);
   1752 }
   1753 
   1754 /*
   1755  * Find a block of the specified size in the specified cylinder group.
   1756  *
   1757  * It is a panic if a request is made to find a block if none are
   1758  * available.
   1759  */
   1760 static int32_t
   1761 ffs_mapsearch(fs, cgp, bpref, allocsiz)
   1762 	struct fs *fs;
   1763 	struct cg *cgp;
   1764 	daddr_t bpref;
   1765 	int allocsiz;
   1766 {
   1767 	int32_t bno;
   1768 	int start, len, loc, i;
   1769 	int blk, field, subfield, pos;
   1770 	int ostart, olen;
   1771 	u_int8_t *blksfree;
   1772 #ifdef FFS_EI
   1773 	const int needswap = UFS_FSNEEDSWAP(fs);
   1774 #endif
   1775 
   1776 	/*
   1777 	 * find the fragment by searching through the free block
   1778 	 * map for an appropriate bit pattern
   1779 	 */
   1780 	if (bpref)
   1781 		start = dtogd(fs, bpref) / NBBY;
   1782 	else
   1783 		start = ufs_rw32(cgp->cg_frotor, needswap) / NBBY;
   1784 	blksfree = cg_blksfree(cgp, needswap);
   1785 	len = howmany(fs->fs_fpg, NBBY) - start;
   1786 	ostart = start;
   1787 	olen = len;
   1788 	loc = scanc((u_int)len,
   1789 		(const u_char *)&blksfree[start],
   1790 		(const u_char *)fragtbl[fs->fs_frag],
   1791 		(1 << (allocsiz - 1 + (fs->fs_frag & (NBBY - 1)))));
   1792 	if (loc == 0) {
   1793 		len = start + 1;
   1794 		start = 0;
   1795 		loc = scanc((u_int)len,
   1796 			(const u_char *)&blksfree[0],
   1797 			(const u_char *)fragtbl[fs->fs_frag],
   1798 			(1 << (allocsiz - 1 + (fs->fs_frag & (NBBY - 1)))));
   1799 		if (loc == 0) {
   1800 			printf("start = %d, len = %d, fs = %s\n",
   1801 			    ostart, olen, fs->fs_fsmnt);
   1802 			printf("offset=%d %ld\n",
   1803 				ufs_rw32(cgp->cg_freeoff, needswap),
   1804 				(long)blksfree - (long)cgp);
   1805 			printf("cg %d\n", cgp->cg_cgx);
   1806 			panic("ffs_alloccg: map corrupted");
   1807 			/* NOTREACHED */
   1808 		}
   1809 	}
   1810 	bno = (start + len - loc) * NBBY;
   1811 	cgp->cg_frotor = ufs_rw32(bno, needswap);
   1812 	/*
   1813 	 * found the byte in the map
   1814 	 * sift through the bits to find the selected frag
   1815 	 */
   1816 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
   1817 		blk = blkmap(fs, blksfree, bno);
   1818 		blk <<= 1;
   1819 		field = around[allocsiz];
   1820 		subfield = inside[allocsiz];
   1821 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
   1822 			if ((blk & field) == subfield)
   1823 				return (bno + pos);
   1824 			field <<= 1;
   1825 			subfield <<= 1;
   1826 		}
   1827 	}
   1828 	printf("bno = %d, fs = %s\n", bno, fs->fs_fsmnt);
   1829 	panic("ffs_alloccg: block not in map");
   1830 	/* return (-1); */
   1831 }
   1832 
   1833 /*
   1834  * Update the cluster map because of an allocation or free.
   1835  *
   1836  * Cnt == 1 means free; cnt == -1 means allocating.
   1837  */
   1838 void
   1839 ffs_clusteracct(fs, cgp, blkno, cnt)
   1840 	struct fs *fs;
   1841 	struct cg *cgp;
   1842 	int32_t blkno;
   1843 	int cnt;
   1844 {
   1845 	int32_t *sump;
   1846 	int32_t *lp;
   1847 	u_char *freemapp, *mapp;
   1848 	int i, start, end, forw, back, map, bit;
   1849 #ifdef FFS_EI
   1850 	const int needswap = UFS_FSNEEDSWAP(fs);
   1851 #endif
   1852 
   1853 	if (fs->fs_contigsumsize <= 0)
   1854 		return;
   1855 	freemapp = cg_clustersfree(cgp, needswap);
   1856 	sump = cg_clustersum(cgp, needswap);
   1857 	/*
   1858 	 * Allocate or clear the actual block.
   1859 	 */
   1860 	if (cnt > 0)
   1861 		setbit(freemapp, blkno);
   1862 	else
   1863 		clrbit(freemapp, blkno);
   1864 	/*
   1865 	 * Find the size of the cluster going forward.
   1866 	 */
   1867 	start = blkno + 1;
   1868 	end = start + fs->fs_contigsumsize;
   1869 	if (end >= ufs_rw32(cgp->cg_nclusterblks, needswap))
   1870 		end = ufs_rw32(cgp->cg_nclusterblks, needswap);
   1871 	mapp = &freemapp[start / NBBY];
   1872 	map = *mapp++;
   1873 	bit = 1 << (start % NBBY);
   1874 	for (i = start; i < end; i++) {
   1875 		if ((map & bit) == 0)
   1876 			break;
   1877 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
   1878 			bit <<= 1;
   1879 		} else {
   1880 			map = *mapp++;
   1881 			bit = 1;
   1882 		}
   1883 	}
   1884 	forw = i - start;
   1885 	/*
   1886 	 * Find the size of the cluster going backward.
   1887 	 */
   1888 	start = blkno - 1;
   1889 	end = start - fs->fs_contigsumsize;
   1890 	if (end < 0)
   1891 		end = -1;
   1892 	mapp = &freemapp[start / NBBY];
   1893 	map = *mapp--;
   1894 	bit = 1 << (start % NBBY);
   1895 	for (i = start; i > end; i--) {
   1896 		if ((map & bit) == 0)
   1897 			break;
   1898 		if ((i & (NBBY - 1)) != 0) {
   1899 			bit >>= 1;
   1900 		} else {
   1901 			map = *mapp--;
   1902 			bit = 1 << (NBBY - 1);
   1903 		}
   1904 	}
   1905 	back = start - i;
   1906 	/*
   1907 	 * Account for old cluster and the possibly new forward and
   1908 	 * back clusters.
   1909 	 */
   1910 	i = back + forw + 1;
   1911 	if (i > fs->fs_contigsumsize)
   1912 		i = fs->fs_contigsumsize;
   1913 	ufs_add32(sump[i], cnt, needswap);
   1914 	if (back > 0)
   1915 		ufs_add32(sump[back], -cnt, needswap);
   1916 	if (forw > 0)
   1917 		ufs_add32(sump[forw], -cnt, needswap);
   1918 
   1919 	/*
   1920 	 * Update cluster summary information.
   1921 	 */
   1922 	lp = &sump[fs->fs_contigsumsize];
   1923 	for (i = fs->fs_contigsumsize; i > 0; i--)
   1924 		if (ufs_rw32(*lp--, needswap) > 0)
   1925 			break;
   1926 	fs->fs_maxcluster[ufs_rw32(cgp->cg_cgx, needswap)] = i;
   1927 }
   1928 
   1929 /*
   1930  * Fserr prints the name of a file system with an error diagnostic.
   1931  *
   1932  * The form of the error message is:
   1933  *	fs: error message
   1934  */
   1935 static void
   1936 ffs_fserr(fs, uid, cp)
   1937 	struct fs *fs;
   1938 	u_int uid;
   1939 	char *cp;
   1940 {
   1941 
   1942 	log(LOG_ERR, "uid %d, pid %d, command %s, on %s: %s\n",
   1943 	    uid, curproc->p_pid, curproc->p_comm, fs->fs_fsmnt, cp);
   1944 }
   1945