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