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