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