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