Home | History | Annotate | Line # | Download | only in ffs
ffs_alloc.c revision 1.130
      1 /*	$NetBSD: ffs_alloc.c,v 1.130 2011/11/28 08:05:07 tls 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.130 2011/11/28 08:05:07 tls 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 || 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 				 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 || 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 || fragoff(fs, osize) != 0 ||
    351 	    (u_int)nsize > fs->fs_bsize || 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 		brelse(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 != 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, 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, fsbtodb(fs, bprev),
    485 			    osize);
    486 		} else {
    487 			ffs_blkfree(fs, ip->i_devvp, bprev, (long)osize,
    488 			    ip->i_number);
    489 		}
    490 		if (nsize < request) {
    491 			if ((ip->i_ump->um_mountp->mnt_wapbl) &&
    492 			    (ITOV(ip)->v_type != VREG)) {
    493 				UFS_WAPBL_REGISTER_DEALLOCATION(
    494 				    ip->i_ump->um_mountp,
    495 				    fsbtodb(fs, (bno + numfrags(fs, nsize))),
    496 				    request - nsize);
    497 			} else
    498 				ffs_blkfree(fs, ip->i_devvp,
    499 				    bno + numfrags(fs, nsize),
    500 				    (long)(request - nsize), ip->i_number);
    501 		}
    502 		DIP_ADD(ip, blocks, btodb(nsize - osize));
    503 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
    504 		if (bpp != NULL) {
    505 			bp->b_blkno = fsbtodb(fs, bno);
    506 			allocbuf(bp, nsize, 1);
    507 			memset((char *)bp->b_data + osize, 0, (u_int)nsize - osize);
    508 			mutex_enter(bp->b_objlock);
    509 			KASSERT(!cv_has_waiters(&bp->b_done));
    510 			bp->b_oflags |= BO_DONE;
    511 			mutex_exit(bp->b_objlock);
    512 			*bpp = bp;
    513 		}
    514 		if (blknop != NULL) {
    515 			*blknop = bno;
    516 		}
    517 		return (0);
    518 	}
    519 	mutex_exit(&ump->um_lock);
    520 
    521 #if defined(QUOTA) || defined(QUOTA2)
    522 	/*
    523 	 * Restore user's disk quota because allocation failed.
    524 	 */
    525 	(void) chkdq(ip, -btodb(nsize - osize), cred, FORCE);
    526 #endif
    527 	if (bpp != NULL) {
    528 		brelse(bp, 0);
    529 	}
    530 
    531 nospace:
    532 	/*
    533 	 * no space available
    534 	 */
    535 	ffs_fserr(fs, kauth_cred_geteuid(cred), "file system full");
    536 	uprintf("\n%s: write failed, file system is full\n", fs->fs_fsmnt);
    537 	return (ENOSPC);
    538 }
    539 
    540 /*
    541  * Allocate an inode in the file system.
    542  *
    543  * If allocating a directory, use ffs_dirpref to select the inode.
    544  * If allocating in a directory, the following hierarchy is followed:
    545  *   1) allocate the preferred inode.
    546  *   2) allocate an inode in the same cylinder group.
    547  *   3) quadradically rehash into other cylinder groups, until an
    548  *      available inode is located.
    549  * If no inode preference is given the following hierarchy is used
    550  * to allocate an inode:
    551  *   1) allocate an inode in cylinder group 0.
    552  *   2) quadradically rehash into other cylinder groups, until an
    553  *      available inode is located.
    554  *
    555  * => um_lock not held upon entry or return
    556  */
    557 int
    558 ffs_valloc(struct vnode *pvp, int mode, kauth_cred_t cred,
    559     struct vnode **vpp)
    560 {
    561 	struct ufsmount *ump;
    562 	struct inode *pip;
    563 	struct fs *fs;
    564 	struct inode *ip;
    565 	struct timespec ts;
    566 	ino_t ino, ipref;
    567 	int cg, error;
    568 
    569 	UFS_WAPBL_JUNLOCK_ASSERT(pvp->v_mount);
    570 
    571 	*vpp = NULL;
    572 	pip = VTOI(pvp);
    573 	fs = pip->i_fs;
    574 	ump = pip->i_ump;
    575 
    576 	error = UFS_WAPBL_BEGIN(pvp->v_mount);
    577 	if (error) {
    578 		return error;
    579 	}
    580 	mutex_enter(&ump->um_lock);
    581 	if (fs->fs_cstotal.cs_nifree == 0)
    582 		goto noinodes;
    583 
    584 	if ((mode & IFMT) == IFDIR)
    585 		ipref = ffs_dirpref(pip);
    586 	else
    587 		ipref = pip->i_number;
    588 	if (ipref >= fs->fs_ncg * fs->fs_ipg)
    589 		ipref = 0;
    590 	cg = ino_to_cg(fs, ipref);
    591 	/*
    592 	 * Track number of dirs created one after another
    593 	 * in a same cg without intervening by files.
    594 	 */
    595 	if ((mode & IFMT) == IFDIR) {
    596 		if (fs->fs_contigdirs[cg] < 255)
    597 			fs->fs_contigdirs[cg]++;
    598 	} else {
    599 		if (fs->fs_contigdirs[cg] > 0)
    600 			fs->fs_contigdirs[cg]--;
    601 	}
    602 	ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode, 0, ffs_nodealloccg);
    603 	if (ino == 0)
    604 		goto noinodes;
    605 	UFS_WAPBL_END(pvp->v_mount);
    606 	error = VFS_VGET(pvp->v_mount, ino, vpp);
    607 	if (error) {
    608 		int err;
    609 		err = UFS_WAPBL_BEGIN(pvp->v_mount);
    610 		if (err == 0)
    611 			ffs_vfree(pvp, ino, mode);
    612 		if (err == 0)
    613 			UFS_WAPBL_END(pvp->v_mount);
    614 		return (error);
    615 	}
    616 	KASSERT((*vpp)->v_type == VNON);
    617 	ip = VTOI(*vpp);
    618 	if (ip->i_mode) {
    619 #if 0
    620 		printf("mode = 0%o, inum = %d, fs = %s\n",
    621 		    ip->i_mode, ip->i_number, fs->fs_fsmnt);
    622 #else
    623 		printf("dmode %x mode %x dgen %x gen %x\n",
    624 		    DIP(ip, mode), ip->i_mode,
    625 		    DIP(ip, gen), ip->i_gen);
    626 		printf("size %llx blocks %llx\n",
    627 		    (long long)DIP(ip, size), (long long)DIP(ip, blocks));
    628 		printf("ino %llu ipref %llu\n", (unsigned long long)ino,
    629 		    (unsigned long long)ipref);
    630 #if 0
    631 		error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ino)),
    632 		    (int)fs->fs_bsize, NOCRED, 0, &bp);
    633 #endif
    634 
    635 #endif
    636 		panic("ffs_valloc: dup alloc");
    637 	}
    638 	if (DIP(ip, blocks)) {				/* XXX */
    639 		printf("free inode %s/%llu had %" PRId64 " blocks\n",
    640 		    fs->fs_fsmnt, (unsigned long long)ino, DIP(ip, blocks));
    641 		DIP_ASSIGN(ip, blocks, 0);
    642 	}
    643 	ip->i_flag &= ~IN_SPACECOUNTED;
    644 	ip->i_flags = 0;
    645 	DIP_ASSIGN(ip, flags, 0);
    646 	/*
    647 	 * Set up a new generation number for this inode.
    648 	 */
    649 	ip->i_gen++;
    650 	DIP_ASSIGN(ip, gen, ip->i_gen);
    651 	if (fs->fs_magic == FS_UFS2_MAGIC) {
    652 		vfs_timestamp(&ts);
    653 		ip->i_ffs2_birthtime = ts.tv_sec;
    654 		ip->i_ffs2_birthnsec = ts.tv_nsec;
    655 	}
    656 	return (0);
    657 noinodes:
    658 	mutex_exit(&ump->um_lock);
    659 	UFS_WAPBL_END(pvp->v_mount);
    660 	ffs_fserr(fs, kauth_cred_geteuid(cred), "out of inodes");
    661 	uprintf("\n%s: create/symlink failed, no inodes free\n", fs->fs_fsmnt);
    662 	return (ENOSPC);
    663 }
    664 
    665 /*
    666  * Find a cylinder group in which to place a directory.
    667  *
    668  * The policy implemented by this algorithm is to allocate a
    669  * directory inode in the same cylinder group as its parent
    670  * directory, but also to reserve space for its files inodes
    671  * and data. Restrict the number of directories which may be
    672  * allocated one after another in the same cylinder group
    673  * without intervening allocation of files.
    674  *
    675  * If we allocate a first level directory then force allocation
    676  * in another cylinder group.
    677  */
    678 static ino_t
    679 ffs_dirpref(struct inode *pip)
    680 {
    681 	register struct fs *fs;
    682 	int cg, prefcg;
    683 	int64_t dirsize, cgsize, curdsz;
    684 	int avgifree, avgbfree, avgndir;
    685 	int minifree, minbfree, maxndir;
    686 	int mincg, minndir;
    687 	int maxcontigdirs;
    688 
    689 	KASSERT(mutex_owned(&pip->i_ump->um_lock));
    690 
    691 	fs = pip->i_fs;
    692 
    693 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
    694 	avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
    695 	avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
    696 
    697 	/*
    698 	 * Force allocation in another cg if creating a first level dir.
    699 	 */
    700 	if (ITOV(pip)->v_vflag & VV_ROOT) {
    701 		prefcg = random() % fs->fs_ncg;
    702 		mincg = prefcg;
    703 		minndir = fs->fs_ipg;
    704 		for (cg = prefcg; cg < fs->fs_ncg; cg++)
    705 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
    706 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
    707 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    708 				mincg = cg;
    709 				minndir = fs->fs_cs(fs, cg).cs_ndir;
    710 			}
    711 		for (cg = 0; cg < prefcg; cg++)
    712 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
    713 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
    714 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    715 				mincg = cg;
    716 				minndir = fs->fs_cs(fs, cg).cs_ndir;
    717 			}
    718 		return ((ino_t)(fs->fs_ipg * mincg));
    719 	}
    720 
    721 	/*
    722 	 * Count various limits which used for
    723 	 * optimal allocation of a directory inode.
    724 	 */
    725 	maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
    726 	minifree = avgifree - fs->fs_ipg / 4;
    727 	if (minifree < 0)
    728 		minifree = 0;
    729 	minbfree = avgbfree - fragstoblks(fs, fs->fs_fpg) / 4;
    730 	if (minbfree < 0)
    731 		minbfree = 0;
    732 	cgsize = (int64_t)fs->fs_fsize * fs->fs_fpg;
    733 	dirsize = (int64_t)fs->fs_avgfilesize * fs->fs_avgfpdir;
    734 	if (avgndir != 0) {
    735 		curdsz = (cgsize - (int64_t)avgbfree * fs->fs_bsize) / avgndir;
    736 		if (dirsize < curdsz)
    737 			dirsize = curdsz;
    738 	}
    739 	if (cgsize < dirsize * 255)
    740 		maxcontigdirs = cgsize / dirsize;
    741 	else
    742 		maxcontigdirs = 255;
    743 	if (fs->fs_avgfpdir > 0)
    744 		maxcontigdirs = min(maxcontigdirs,
    745 				    fs->fs_ipg / fs->fs_avgfpdir);
    746 	if (maxcontigdirs == 0)
    747 		maxcontigdirs = 1;
    748 
    749 	/*
    750 	 * Limit number of dirs in one cg and reserve space for
    751 	 * regular files, but only if we have no deficit in
    752 	 * inodes or space.
    753 	 */
    754 	prefcg = ino_to_cg(fs, pip->i_number);
    755 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
    756 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
    757 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
    758 	    	    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
    759 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
    760 				return ((ino_t)(fs->fs_ipg * cg));
    761 		}
    762 	for (cg = 0; cg < prefcg; cg++)
    763 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
    764 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
    765 	    	    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
    766 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
    767 				return ((ino_t)(fs->fs_ipg * cg));
    768 		}
    769 	/*
    770 	 * This is a backstop when we are deficient in space.
    771 	 */
    772 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
    773 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
    774 			return ((ino_t)(fs->fs_ipg * cg));
    775 	for (cg = 0; cg < prefcg; cg++)
    776 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
    777 			break;
    778 	return ((ino_t)(fs->fs_ipg * cg));
    779 }
    780 
    781 /*
    782  * Select the desired position for the next block in a file.  The file is
    783  * logically divided into sections. The first section is composed of the
    784  * direct blocks. Each additional section contains fs_maxbpg blocks.
    785  *
    786  * If no blocks have been allocated in the first section, the policy is to
    787  * request a block in the same cylinder group as the inode that describes
    788  * the file. If no blocks have been allocated in any other section, the
    789  * policy is to place the section in a cylinder group with a greater than
    790  * average number of free blocks.  An appropriate cylinder group is found
    791  * by using a rotor that sweeps the cylinder groups. When a new group of
    792  * blocks is needed, the sweep begins in the cylinder group following the
    793  * cylinder group from which the previous allocation was made. The sweep
    794  * continues until a cylinder group with greater than the average number
    795  * of free blocks is found. If the allocation is for the first block in an
    796  * indirect block, the information on the previous allocation is unavailable;
    797  * here a best guess is made based upon the logical block number being
    798  * allocated.
    799  *
    800  * If a section is already partially allocated, the policy is to
    801  * contiguously allocate fs_maxcontig blocks.  The end of one of these
    802  * contiguous blocks and the beginning of the next is laid out
    803  * contigously if possible.
    804  *
    805  * => um_lock held on entry and exit
    806  */
    807 daddr_t
    808 ffs_blkpref_ufs1(struct inode *ip, daddr_t lbn, int indx, int flags,
    809     int32_t *bap /* XXX ondisk32 */)
    810 {
    811 	struct fs *fs;
    812 	int cg;
    813 	int avgbfree, startcg;
    814 
    815 	KASSERT(mutex_owned(&ip->i_ump->um_lock));
    816 
    817 	fs = ip->i_fs;
    818 
    819 	/*
    820 	 * If allocating a contiguous file with B_CONTIG, use the hints
    821 	 * in the inode extentions to return the desired block.
    822 	 *
    823 	 * For metadata (indirect blocks) return the address of where
    824 	 * the first indirect block resides - we'll scan for the next
    825 	 * available slot if we need to allocate more than one indirect
    826 	 * block.  For data, return the address of the actual block
    827 	 * relative to the address of the first data block.
    828 	 */
    829 	if (flags & B_CONTIG) {
    830 		KASSERT(ip->i_ffs_first_data_blk != 0);
    831 		KASSERT(ip->i_ffs_first_indir_blk != 0);
    832 		if (flags & B_METAONLY)
    833 			return ip->i_ffs_first_indir_blk;
    834 		else
    835 			return ip->i_ffs_first_data_blk + blkstofrags(fs, lbn);
    836 	}
    837 
    838 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
    839 		if (lbn < NDADDR + NINDIR(fs)) {
    840 			cg = ino_to_cg(fs, ip->i_number);
    841 			return (cgbase(fs, cg) + fs->fs_frag);
    842 		}
    843 		/*
    844 		 * Find a cylinder with greater than average number of
    845 		 * unused data blocks.
    846 		 */
    847 		if (indx == 0 || bap[indx - 1] == 0)
    848 			startcg =
    849 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
    850 		else
    851 			startcg = dtog(fs,
    852 				ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + 1);
    853 		startcg %= fs->fs_ncg;
    854 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
    855 		for (cg = startcg; cg < fs->fs_ncg; cg++)
    856 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    857 				return (cgbase(fs, cg) + fs->fs_frag);
    858 			}
    859 		for (cg = 0; cg < startcg; cg++)
    860 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    861 				return (cgbase(fs, cg) + fs->fs_frag);
    862 			}
    863 		return (0);
    864 	}
    865 	/*
    866 	 * We just always try to lay things out contiguously.
    867 	 */
    868 	return ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + fs->fs_frag;
    869 }
    870 
    871 daddr_t
    872 ffs_blkpref_ufs2(struct inode *ip, daddr_t lbn, int indx, int flags,
    873     int64_t *bap)
    874 {
    875 	struct fs *fs;
    876 	int cg;
    877 	int avgbfree, startcg;
    878 
    879 	KASSERT(mutex_owned(&ip->i_ump->um_lock));
    880 
    881 	fs = ip->i_fs;
    882 
    883 	/*
    884 	 * If allocating a contiguous file with B_CONTIG, use the hints
    885 	 * in the inode extentions to return the desired block.
    886 	 *
    887 	 * For metadata (indirect blocks) return the address of where
    888 	 * the first indirect block resides - we'll scan for the next
    889 	 * available slot if we need to allocate more than one indirect
    890 	 * block.  For data, return the address of the actual block
    891 	 * relative to the address of the first data block.
    892 	 */
    893 	if (flags & B_CONTIG) {
    894 		KASSERT(ip->i_ffs_first_data_blk != 0);
    895 		KASSERT(ip->i_ffs_first_indir_blk != 0);
    896 		if (flags & B_METAONLY)
    897 			return ip->i_ffs_first_indir_blk;
    898 		else
    899 			return ip->i_ffs_first_data_blk + blkstofrags(fs, lbn);
    900 	}
    901 
    902 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
    903 		if (lbn < NDADDR + NINDIR(fs)) {
    904 			cg = ino_to_cg(fs, ip->i_number);
    905 			return (cgbase(fs, cg) + fs->fs_frag);
    906 		}
    907 		/*
    908 		 * Find a cylinder with greater than average number of
    909 		 * unused data blocks.
    910 		 */
    911 		if (indx == 0 || bap[indx - 1] == 0)
    912 			startcg =
    913 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
    914 		else
    915 			startcg = dtog(fs,
    916 				ufs_rw64(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + 1);
    917 		startcg %= fs->fs_ncg;
    918 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
    919 		for (cg = startcg; cg < fs->fs_ncg; cg++)
    920 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    921 				return (cgbase(fs, cg) + fs->fs_frag);
    922 			}
    923 		for (cg = 0; cg < startcg; cg++)
    924 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    925 				return (cgbase(fs, cg) + fs->fs_frag);
    926 			}
    927 		return (0);
    928 	}
    929 	/*
    930 	 * We just always try to lay things out contiguously.
    931 	 */
    932 	return ufs_rw64(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + fs->fs_frag;
    933 }
    934 
    935 
    936 /*
    937  * Implement the cylinder overflow algorithm.
    938  *
    939  * The policy implemented by this algorithm is:
    940  *   1) allocate the block in its requested cylinder group.
    941  *   2) quadradically rehash on the cylinder group number.
    942  *   3) brute force search for a free block.
    943  *
    944  * => called with um_lock held
    945  * => returns with um_lock released on success, held on failure
    946  *    (*allocator releases lock on success, retains lock on failure)
    947  */
    948 /*VARARGS5*/
    949 static daddr_t
    950 ffs_hashalloc(struct inode *ip, int cg, daddr_t pref,
    951     int size /* size for data blocks, mode for inodes */,
    952     int flags, daddr_t (*allocator)(struct inode *, int, daddr_t, int, int))
    953 {
    954 	struct fs *fs;
    955 	daddr_t result;
    956 	int i, icg = cg;
    957 
    958 	fs = ip->i_fs;
    959 	/*
    960 	 * 1: preferred cylinder group
    961 	 */
    962 	result = (*allocator)(ip, cg, pref, size, flags);
    963 	if (result)
    964 		return (result);
    965 
    966 	if (flags & B_CONTIG)
    967 		return (result);
    968 	/*
    969 	 * 2: quadratic rehash
    970 	 */
    971 	for (i = 1; i < fs->fs_ncg; i *= 2) {
    972 		cg += i;
    973 		if (cg >= fs->fs_ncg)
    974 			cg -= fs->fs_ncg;
    975 		result = (*allocator)(ip, cg, 0, size, flags);
    976 		if (result)
    977 			return (result);
    978 	}
    979 	/*
    980 	 * 3: brute force search
    981 	 * Note that we start at i == 2, since 0 was checked initially,
    982 	 * and 1 is always checked in the quadratic rehash.
    983 	 */
    984 	cg = (icg + 2) % fs->fs_ncg;
    985 	for (i = 2; i < fs->fs_ncg; i++) {
    986 		result = (*allocator)(ip, cg, 0, size, flags);
    987 		if (result)
    988 			return (result);
    989 		cg++;
    990 		if (cg == fs->fs_ncg)
    991 			cg = 0;
    992 	}
    993 	return (0);
    994 }
    995 
    996 /*
    997  * Determine whether a fragment can be extended.
    998  *
    999  * Check to see if the necessary fragments are available, and
   1000  * if they are, allocate them.
   1001  *
   1002  * => called with um_lock held
   1003  * => returns with um_lock released on success, held on failure
   1004  */
   1005 static daddr_t
   1006 ffs_fragextend(struct inode *ip, int cg, daddr_t bprev, int osize, int nsize)
   1007 {
   1008 	struct ufsmount *ump;
   1009 	struct fs *fs;
   1010 	struct cg *cgp;
   1011 	struct buf *bp;
   1012 	daddr_t bno;
   1013 	int frags, bbase;
   1014 	int i, error;
   1015 	u_int8_t *blksfree;
   1016 
   1017 	fs = ip->i_fs;
   1018 	ump = ip->i_ump;
   1019 
   1020 	KASSERT(mutex_owned(&ump->um_lock));
   1021 
   1022 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
   1023 		return (0);
   1024 	frags = numfrags(fs, nsize);
   1025 	bbase = fragnum(fs, bprev);
   1026 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
   1027 		/* cannot extend across a block boundary */
   1028 		return (0);
   1029 	}
   1030 	mutex_exit(&ump->um_lock);
   1031 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1032 		(int)fs->fs_cgsize, NOCRED, B_MODIFY, &bp);
   1033 	if (error)
   1034 		goto fail;
   1035 	cgp = (struct cg *)bp->b_data;
   1036 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs)))
   1037 		goto fail;
   1038 	cgp->cg_old_time = ufs_rw32(time_second, UFS_FSNEEDSWAP(fs));
   1039 	if ((fs->fs_magic != FS_UFS1_MAGIC) ||
   1040 	    (fs->fs_old_flags & FS_FLAGS_UPDATED))
   1041 		cgp->cg_time = ufs_rw64(time_second, UFS_FSNEEDSWAP(fs));
   1042 	bno = dtogd(fs, bprev);
   1043 	blksfree = cg_blksfree(cgp, UFS_FSNEEDSWAP(fs));
   1044 	for (i = numfrags(fs, osize); i < frags; i++)
   1045 		if (isclr(blksfree, bno + i))
   1046 			goto fail;
   1047 	/*
   1048 	 * the current fragment can be extended
   1049 	 * deduct the count on fragment being extended into
   1050 	 * increase the count on the remaining fragment (if any)
   1051 	 * allocate the extended piece
   1052 	 */
   1053 	for (i = frags; i < fs->fs_frag - bbase; i++)
   1054 		if (isclr(blksfree, bno + i))
   1055 			break;
   1056 	ufs_add32(cgp->cg_frsum[i - numfrags(fs, osize)], -1, UFS_FSNEEDSWAP(fs));
   1057 	if (i != frags)
   1058 		ufs_add32(cgp->cg_frsum[i - frags], 1, UFS_FSNEEDSWAP(fs));
   1059 	mutex_enter(&ump->um_lock);
   1060 	for (i = numfrags(fs, osize); i < frags; i++) {
   1061 		clrbit(blksfree, bno + i);
   1062 		ufs_add32(cgp->cg_cs.cs_nffree, -1, UFS_FSNEEDSWAP(fs));
   1063 		fs->fs_cstotal.cs_nffree--;
   1064 		fs->fs_cs(fs, cg).cs_nffree--;
   1065 	}
   1066 	fs->fs_fmod = 1;
   1067 	ACTIVECG_CLR(fs, cg);
   1068 	mutex_exit(&ump->um_lock);
   1069 	bdwrite(bp);
   1070 	return (bprev);
   1071 
   1072  fail:
   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, 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  	brelse(bp, 0);
   1186  	mutex_enter(&ump->um_lock);
   1187  	return (0);
   1188 }
   1189 
   1190 /*
   1191  * Allocate a block in a cylinder group.
   1192  *
   1193  * This algorithm implements the following policy:
   1194  *   1) allocate the requested block.
   1195  *   2) allocate a rotationally optimal block in the same cylinder.
   1196  *   3) allocate the next available block on the block rotor for the
   1197  *      specified cylinder group.
   1198  * Note that this routine only allocates fs_bsize blocks; these
   1199  * blocks may be fragmented by the routine that allocates them.
   1200  */
   1201 static daddr_t
   1202 ffs_alloccgblk(struct inode *ip, struct buf *bp, daddr_t bpref, int flags)
   1203 {
   1204 	struct ufsmount *ump;
   1205 	struct fs *fs = ip->i_fs;
   1206 	struct cg *cgp;
   1207 	int cg;
   1208 	daddr_t blkno;
   1209 	int32_t bno;
   1210 	u_int8_t *blksfree;
   1211 #ifdef FFS_EI
   1212 	const int needswap = UFS_FSNEEDSWAP(fs);
   1213 #endif
   1214 
   1215 	ump = ip->i_ump;
   1216 
   1217 	KASSERT(mutex_owned(&ump->um_lock));
   1218 
   1219 	cgp = (struct cg *)bp->b_data;
   1220 	blksfree = cg_blksfree(cgp, needswap);
   1221 	if (bpref == 0 || dtog(fs, bpref) != ufs_rw32(cgp->cg_cgx, needswap)) {
   1222 		bpref = ufs_rw32(cgp->cg_rotor, needswap);
   1223 	} else {
   1224 		bpref = blknum(fs, bpref);
   1225 		bno = dtogd(fs, bpref);
   1226 		/*
   1227 		 * if the requested block is available, use it
   1228 		 */
   1229 		if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
   1230 			goto gotit;
   1231 		/*
   1232 		 * if the requested data block isn't available and we are
   1233 		 * trying to allocate a contiguous file, return an error.
   1234 		 */
   1235 		if ((flags & (B_CONTIG | B_METAONLY)) == B_CONTIG)
   1236 			return (0);
   1237 	}
   1238 
   1239 	/*
   1240 	 * Take the next available block in this cylinder group.
   1241 	 */
   1242 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
   1243 	if (bno < 0)
   1244 		return (0);
   1245 	cgp->cg_rotor = ufs_rw32(bno, needswap);
   1246 gotit:
   1247 	blkno = fragstoblks(fs, bno);
   1248 	ffs_clrblock(fs, blksfree, blkno);
   1249 	ffs_clusteracct(fs, cgp, blkno, -1);
   1250 	ufs_add32(cgp->cg_cs.cs_nbfree, -1, needswap);
   1251 	fs->fs_cstotal.cs_nbfree--;
   1252 	fs->fs_cs(fs, ufs_rw32(cgp->cg_cgx, needswap)).cs_nbfree--;
   1253 	if ((fs->fs_magic == FS_UFS1_MAGIC) &&
   1254 	    ((fs->fs_old_flags & FS_FLAGS_UPDATED) == 0)) {
   1255 		int cylno;
   1256 		cylno = old_cbtocylno(fs, bno);
   1257 		KASSERT(cylno >= 0);
   1258 		KASSERT(cylno < fs->fs_old_ncyl);
   1259 		KASSERT(old_cbtorpos(fs, bno) >= 0);
   1260 		KASSERT(fs->fs_old_nrpos == 0 || old_cbtorpos(fs, bno) < fs->fs_old_nrpos);
   1261 		ufs_add16(old_cg_blks(fs, cgp, cylno, needswap)[old_cbtorpos(fs, bno)], -1,
   1262 		    needswap);
   1263 		ufs_add32(old_cg_blktot(cgp, needswap)[cylno], -1, needswap);
   1264 	}
   1265 	fs->fs_fmod = 1;
   1266 	cg = ufs_rw32(cgp->cg_cgx, needswap);
   1267 	blkno = cgbase(fs, cg) + bno;
   1268 	return (blkno);
   1269 }
   1270 
   1271 /*
   1272  * Determine whether an inode can be allocated.
   1273  *
   1274  * Check to see if an inode is available, and if it is,
   1275  * allocate it using the following policy:
   1276  *   1) allocate the requested inode.
   1277  *   2) allocate the next available inode after the requested
   1278  *      inode in the specified cylinder group.
   1279  */
   1280 static daddr_t
   1281 ffs_nodealloccg(struct inode *ip, int cg, daddr_t ipref, int mode, int flags)
   1282 {
   1283 	struct ufsmount *ump = ip->i_ump;
   1284 	struct fs *fs = ip->i_fs;
   1285 	struct cg *cgp;
   1286 	struct buf *bp, *ibp;
   1287 	u_int8_t *inosused;
   1288 	int error, start, len, loc, map, i;
   1289 	int32_t initediblk;
   1290 	daddr_t nalloc;
   1291 	struct ufs2_dinode *dp2;
   1292 #ifdef FFS_EI
   1293 	const int needswap = UFS_FSNEEDSWAP(fs);
   1294 #endif
   1295 
   1296 	KASSERT(mutex_owned(&ump->um_lock));
   1297 	UFS_WAPBL_JLOCK_ASSERT(ip->i_ump->um_mountp);
   1298 
   1299 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
   1300 		return (0);
   1301 	mutex_exit(&ump->um_lock);
   1302 	ibp = NULL;
   1303 	initediblk = -1;
   1304 retry:
   1305 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1306 		(int)fs->fs_cgsize, NOCRED, B_MODIFY, &bp);
   1307 	if (error)
   1308 		goto fail;
   1309 	cgp = (struct cg *)bp->b_data;
   1310 	if (!cg_chkmagic(cgp, needswap) || cgp->cg_cs.cs_nifree == 0)
   1311 		goto fail;
   1312 
   1313 	if (ibp != NULL &&
   1314 	    initediblk != ufs_rw32(cgp->cg_initediblk, needswap)) {
   1315 		/* Another thread allocated more inodes so we retry the test. */
   1316 		brelse(ibp, 0);
   1317 		ibp = NULL;
   1318 	}
   1319 	/*
   1320 	 * Check to see if we need to initialize more inodes.
   1321 	 */
   1322 	if (fs->fs_magic == FS_UFS2_MAGIC && ibp == NULL) {
   1323 		initediblk = ufs_rw32(cgp->cg_initediblk, needswap);
   1324 		nalloc = fs->fs_ipg - ufs_rw32(cgp->cg_cs.cs_nifree, needswap);
   1325 		if (nalloc + INOPB(fs) > initediblk &&
   1326 		    initediblk < ufs_rw32(cgp->cg_niblk, needswap)) {
   1327 			/*
   1328 			 * We have to release the cg buffer here to prevent
   1329 			 * a deadlock when reading the inode block will
   1330 			 * run a copy-on-write that might use this cg.
   1331 			 */
   1332 			brelse(bp, 0);
   1333 			bp = NULL;
   1334 			error = ffs_getblk(ip->i_devvp, fsbtodb(fs,
   1335 			    ino_to_fsba(fs, cg * fs->fs_ipg + initediblk)),
   1336 			    FFS_NOBLK, fs->fs_bsize, false, &ibp);
   1337 			if (error)
   1338 				goto fail;
   1339 			goto retry;
   1340 		}
   1341 	}
   1342 
   1343 	cgp->cg_old_time = ufs_rw32(time_second, needswap);
   1344 	if ((fs->fs_magic != FS_UFS1_MAGIC) ||
   1345 	    (fs->fs_old_flags & FS_FLAGS_UPDATED))
   1346 		cgp->cg_time = ufs_rw64(time_second, needswap);
   1347 	inosused = cg_inosused(cgp, needswap);
   1348 	if (ipref) {
   1349 		ipref %= fs->fs_ipg;
   1350 		if (isclr(inosused, ipref))
   1351 			goto gotit;
   1352 	}
   1353 	start = ufs_rw32(cgp->cg_irotor, needswap) / NBBY;
   1354 	len = howmany(fs->fs_ipg - ufs_rw32(cgp->cg_irotor, needswap),
   1355 		NBBY);
   1356 	loc = skpc(0xff, len, &inosused[start]);
   1357 	if (loc == 0) {
   1358 		len = start + 1;
   1359 		start = 0;
   1360 		loc = skpc(0xff, len, &inosused[0]);
   1361 		if (loc == 0) {
   1362 			printf("cg = %d, irotor = %d, fs = %s\n",
   1363 			    cg, ufs_rw32(cgp->cg_irotor, needswap),
   1364 				fs->fs_fsmnt);
   1365 			panic("ffs_nodealloccg: map corrupted");
   1366 			/* NOTREACHED */
   1367 		}
   1368 	}
   1369 	i = start + len - loc;
   1370 	map = inosused[i] ^ 0xff;
   1371 	if (map == 0) {
   1372 		printf("fs = %s\n", fs->fs_fsmnt);
   1373 		panic("ffs_nodealloccg: block not in map");
   1374 	}
   1375 	ipref = i * NBBY + ffs(map) - 1;
   1376 	cgp->cg_irotor = ufs_rw32(ipref, needswap);
   1377 gotit:
   1378 	UFS_WAPBL_REGISTER_INODE(ip->i_ump->um_mountp, cg * fs->fs_ipg + ipref,
   1379 	    mode);
   1380 	/*
   1381 	 * Check to see if we need to initialize more inodes.
   1382 	 */
   1383 	if (ibp != NULL) {
   1384 		KASSERT(initediblk == ufs_rw32(cgp->cg_initediblk, needswap));
   1385 		memset(ibp->b_data, 0, fs->fs_bsize);
   1386 		dp2 = (struct ufs2_dinode *)(ibp->b_data);
   1387 		for (i = 0; i < INOPB(fs); i++) {
   1388 			/*
   1389 			 * Don't bother to swap, it's supposed to be
   1390 			 * random, after all.
   1391 			 */
   1392 			dp2->di_gen = (cprng_fast32() & INT32_MAX) / 2 + 1;
   1393 			dp2++;
   1394 		}
   1395 		initediblk += INOPB(fs);
   1396 		cgp->cg_initediblk = ufs_rw32(initediblk, needswap);
   1397 	}
   1398 
   1399 	mutex_enter(&ump->um_lock);
   1400 	ACTIVECG_CLR(fs, cg);
   1401 	setbit(inosused, ipref);
   1402 	ufs_add32(cgp->cg_cs.cs_nifree, -1, needswap);
   1403 	fs->fs_cstotal.cs_nifree--;
   1404 	fs->fs_cs(fs, cg).cs_nifree--;
   1405 	fs->fs_fmod = 1;
   1406 	if ((mode & IFMT) == IFDIR) {
   1407 		ufs_add32(cgp->cg_cs.cs_ndir, 1, needswap);
   1408 		fs->fs_cstotal.cs_ndir++;
   1409 		fs->fs_cs(fs, cg).cs_ndir++;
   1410 	}
   1411 	mutex_exit(&ump->um_lock);
   1412 	if (ibp != NULL) {
   1413 		bwrite(bp);
   1414 		bawrite(ibp);
   1415 	} else
   1416 		bdwrite(bp);
   1417 	return (cg * fs->fs_ipg + ipref);
   1418  fail:
   1419 	if (bp != NULL)
   1420 		brelse(bp, 0);
   1421 	if (ibp != NULL)
   1422 		brelse(ibp, 0);
   1423 	mutex_enter(&ump->um_lock);
   1424 	return (0);
   1425 }
   1426 
   1427 /*
   1428  * Allocate a block or fragment.
   1429  *
   1430  * The specified block or fragment is removed from the
   1431  * free map, possibly fragmenting a block in the process.
   1432  *
   1433  * This implementation should mirror fs_blkfree
   1434  *
   1435  * => um_lock not held on entry or exit
   1436  */
   1437 int
   1438 ffs_blkalloc(struct inode *ip, daddr_t bno, long size)
   1439 {
   1440 	int error;
   1441 
   1442 	error = ffs_check_bad_allocation(__func__, ip->i_fs, bno, size,
   1443 	    ip->i_dev, ip->i_uid);
   1444 	if (error)
   1445 		return error;
   1446 
   1447 	return ffs_blkalloc_ump(ip->i_ump, bno, size);
   1448 }
   1449 
   1450 int
   1451 ffs_blkalloc_ump(struct ufsmount *ump, daddr_t bno, long size)
   1452 {
   1453 	struct fs *fs = ump->um_fs;
   1454 	struct cg *cgp;
   1455 	struct buf *bp;
   1456 	int32_t fragno, cgbno;
   1457 	int i, error, cg, blk, frags, bbase;
   1458 	u_int8_t *blksfree;
   1459 	const int needswap = UFS_FSNEEDSWAP(fs);
   1460 
   1461 	KASSERT((u_int)size <= fs->fs_bsize && fragoff(fs, size) == 0 &&
   1462 	    fragnum(fs, bno) + numfrags(fs, size) <= fs->fs_frag);
   1463 	KASSERT(bno < fs->fs_size);
   1464 
   1465 	cg = dtog(fs, bno);
   1466 	error = bread(ump->um_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1467 		(int)fs->fs_cgsize, NOCRED, B_MODIFY, &bp);
   1468 	if (error) {
   1469 		brelse(bp, 0);
   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 void
   1556 ffs_blkfree(struct fs *fs, struct vnode *devvp, daddr_t bno, long size,
   1557     ino_t inum)
   1558 {
   1559 	struct cg *cgp;
   1560 	struct buf *bp;
   1561 	struct ufsmount *ump;
   1562 	daddr_t cgblkno;
   1563 	int error, cg;
   1564 	dev_t dev;
   1565 	const bool devvp_is_snapshot = (devvp->v_type != VBLK);
   1566 #ifdef FFS_EI
   1567 	const int needswap = UFS_FSNEEDSWAP(fs);
   1568 #endif
   1569 
   1570 	KASSERT(!devvp_is_snapshot);
   1571 
   1572 	cg = dtog(fs, bno);
   1573 	dev = devvp->v_rdev;
   1574 	ump = VFSTOUFS(devvp->v_specmountpoint);
   1575 	KASSERT(fs == ump->um_fs);
   1576 	cgblkno = fsbtodb(fs, cgtod(fs, cg));
   1577 	if (ffs_snapblkfree(fs, devvp, bno, size, inum))
   1578 		return;
   1579 
   1580 	error = ffs_check_bad_allocation(__func__, fs, bno, size, dev, inum);
   1581 	if (error)
   1582 		return;
   1583 
   1584 	error = bread(devvp, cgblkno, (int)fs->fs_cgsize,
   1585 	    NOCRED, B_MODIFY, &bp);
   1586 	if (error) {
   1587 		brelse(bp, 0);
   1588 		return;
   1589 	}
   1590 	cgp = (struct cg *)bp->b_data;
   1591 	if (!cg_chkmagic(cgp, needswap)) {
   1592 		brelse(bp, 0);
   1593 		return;
   1594 	}
   1595 
   1596 	ffs_blkfree_common(ump, fs, dev, bp, bno, size, devvp_is_snapshot);
   1597 
   1598 	bdwrite(bp);
   1599 }
   1600 
   1601 /*
   1602  * Free a block or fragment from a snapshot cg copy.
   1603  *
   1604  * The specified block or fragment is placed back in the
   1605  * free map. If a fragment is deallocated, a possible
   1606  * block reassembly is checked.
   1607  *
   1608  * => um_lock not held on entry or exit
   1609  */
   1610 void
   1611 ffs_blkfree_snap(struct fs *fs, struct vnode *devvp, daddr_t bno, long size,
   1612     ino_t inum)
   1613 {
   1614 	struct cg *cgp;
   1615 	struct buf *bp;
   1616 	struct ufsmount *ump;
   1617 	daddr_t cgblkno;
   1618 	int error, cg;
   1619 	dev_t dev;
   1620 	const bool devvp_is_snapshot = (devvp->v_type != VBLK);
   1621 #ifdef FFS_EI
   1622 	const int needswap = UFS_FSNEEDSWAP(fs);
   1623 #endif
   1624 
   1625 	KASSERT(devvp_is_snapshot);
   1626 
   1627 	cg = dtog(fs, bno);
   1628 	dev = VTOI(devvp)->i_devvp->v_rdev;
   1629 	ump = VFSTOUFS(devvp->v_mount);
   1630 	cgblkno = fragstoblks(fs, cgtod(fs, cg));
   1631 
   1632 	error = ffs_check_bad_allocation(__func__, fs, bno, size, dev, inum);
   1633 	if (error)
   1634 		return;
   1635 
   1636 	error = bread(devvp, cgblkno, (int)fs->fs_cgsize,
   1637 	    NOCRED, B_MODIFY, &bp);
   1638 	if (error) {
   1639 		brelse(bp, 0);
   1640 		return;
   1641 	}
   1642 	cgp = (struct cg *)bp->b_data;
   1643 	if (!cg_chkmagic(cgp, needswap)) {
   1644 		brelse(bp, 0);
   1645 		return;
   1646 	}
   1647 
   1648 	ffs_blkfree_common(ump, fs, dev, bp, bno, size, devvp_is_snapshot);
   1649 
   1650 	bdwrite(bp);
   1651 }
   1652 
   1653 static void
   1654 ffs_blkfree_common(struct ufsmount *ump, struct fs *fs, dev_t dev,
   1655     struct buf *bp, daddr_t bno, long size, bool devvp_is_snapshot)
   1656 {
   1657 	struct cg *cgp;
   1658 	int32_t fragno, cgbno;
   1659 	int i, cg, blk, frags, bbase;
   1660 	u_int8_t *blksfree;
   1661 	const int needswap = UFS_FSNEEDSWAP(fs);
   1662 
   1663 	cg = dtog(fs, bno);
   1664 	cgp = (struct cg *)bp->b_data;
   1665 	cgp->cg_old_time = ufs_rw32(time_second, needswap);
   1666 	if ((fs->fs_magic != FS_UFS1_MAGIC) ||
   1667 	    (fs->fs_old_flags & FS_FLAGS_UPDATED))
   1668 		cgp->cg_time = ufs_rw64(time_second, needswap);
   1669 	cgbno = dtogd(fs, bno);
   1670 	blksfree = cg_blksfree(cgp, needswap);
   1671 	mutex_enter(&ump->um_lock);
   1672 	if (size == fs->fs_bsize) {
   1673 		fragno = fragstoblks(fs, cgbno);
   1674 		if (!ffs_isfreeblock(fs, blksfree, fragno)) {
   1675 			if (devvp_is_snapshot) {
   1676 				mutex_exit(&ump->um_lock);
   1677 				return;
   1678 			}
   1679 			printf("dev = 0x%llx, block = %" PRId64 ", fs = %s\n",
   1680 			    (unsigned long long)dev, bno, fs->fs_fsmnt);
   1681 			panic("blkfree: freeing free block");
   1682 		}
   1683 		ffs_setblock(fs, blksfree, fragno);
   1684 		ffs_clusteracct(fs, cgp, fragno, 1);
   1685 		ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
   1686 		fs->fs_cstotal.cs_nbfree++;
   1687 		fs->fs_cs(fs, cg).cs_nbfree++;
   1688 		if ((fs->fs_magic == FS_UFS1_MAGIC) &&
   1689 		    ((fs->fs_old_flags & FS_FLAGS_UPDATED) == 0)) {
   1690 			i = old_cbtocylno(fs, cgbno);
   1691 			KASSERT(i >= 0);
   1692 			KASSERT(i < fs->fs_old_ncyl);
   1693 			KASSERT(old_cbtorpos(fs, cgbno) >= 0);
   1694 			KASSERT(fs->fs_old_nrpos == 0 || old_cbtorpos(fs, cgbno) < fs->fs_old_nrpos);
   1695 			ufs_add16(old_cg_blks(fs, cgp, i, needswap)[old_cbtorpos(fs, cgbno)], 1,
   1696 			    needswap);
   1697 			ufs_add32(old_cg_blktot(cgp, needswap)[i], 1, needswap);
   1698 		}
   1699 	} else {
   1700 		bbase = cgbno - fragnum(fs, cgbno);
   1701 		/*
   1702 		 * decrement the counts associated with the old frags
   1703 		 */
   1704 		blk = blkmap(fs, blksfree, bbase);
   1705 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1, needswap);
   1706 		/*
   1707 		 * deallocate the fragment
   1708 		 */
   1709 		frags = numfrags(fs, size);
   1710 		for (i = 0; i < frags; i++) {
   1711 			if (isset(blksfree, cgbno + i)) {
   1712 				printf("dev = 0x%llx, block = %" PRId64
   1713 				       ", fs = %s\n",
   1714 				    (unsigned long long)dev, bno + i,
   1715 				    fs->fs_fsmnt);
   1716 				panic("blkfree: freeing free frag");
   1717 			}
   1718 			setbit(blksfree, cgbno + i);
   1719 		}
   1720 		ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
   1721 		fs->fs_cstotal.cs_nffree += i;
   1722 		fs->fs_cs(fs, cg).cs_nffree += i;
   1723 		/*
   1724 		 * add back in counts associated with the new frags
   1725 		 */
   1726 		blk = blkmap(fs, blksfree, bbase);
   1727 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1, needswap);
   1728 		/*
   1729 		 * if a complete block has been reassembled, account for it
   1730 		 */
   1731 		fragno = fragstoblks(fs, bbase);
   1732 		if (ffs_isblock(fs, blksfree, fragno)) {
   1733 			ufs_add32(cgp->cg_cs.cs_nffree, -fs->fs_frag, needswap);
   1734 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
   1735 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
   1736 			ffs_clusteracct(fs, cgp, fragno, 1);
   1737 			ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
   1738 			fs->fs_cstotal.cs_nbfree++;
   1739 			fs->fs_cs(fs, cg).cs_nbfree++;
   1740 			if ((fs->fs_magic == FS_UFS1_MAGIC) &&
   1741 			    ((fs->fs_old_flags & FS_FLAGS_UPDATED) == 0)) {
   1742 				i = old_cbtocylno(fs, bbase);
   1743 				KASSERT(i >= 0);
   1744 				KASSERT(i < fs->fs_old_ncyl);
   1745 				KASSERT(old_cbtorpos(fs, bbase) >= 0);
   1746 				KASSERT(fs->fs_old_nrpos == 0 || old_cbtorpos(fs, bbase) < fs->fs_old_nrpos);
   1747 				ufs_add16(old_cg_blks(fs, cgp, i, needswap)[old_cbtorpos(fs,
   1748 				    bbase)], 1, needswap);
   1749 				ufs_add32(old_cg_blktot(cgp, needswap)[i], 1, needswap);
   1750 			}
   1751 		}
   1752 	}
   1753 	fs->fs_fmod = 1;
   1754 	ACTIVECG_CLR(fs, cg);
   1755 	mutex_exit(&ump->um_lock);
   1756 }
   1757 
   1758 /*
   1759  * Free an inode.
   1760  */
   1761 int
   1762 ffs_vfree(struct vnode *vp, ino_t ino, int mode)
   1763 {
   1764 
   1765 	return ffs_freefile(vp->v_mount, ino, mode);
   1766 }
   1767 
   1768 /*
   1769  * Do the actual free operation.
   1770  * The specified inode is placed back in the free map.
   1771  *
   1772  * => um_lock not held on entry or exit
   1773  */
   1774 int
   1775 ffs_freefile(struct mount *mp, ino_t ino, int mode)
   1776 {
   1777 	struct ufsmount *ump = VFSTOUFS(mp);
   1778 	struct fs *fs = ump->um_fs;
   1779 	struct vnode *devvp;
   1780 	struct cg *cgp;
   1781 	struct buf *bp;
   1782 	int error, cg;
   1783 	daddr_t cgbno;
   1784 	dev_t dev;
   1785 #ifdef FFS_EI
   1786 	const int needswap = UFS_FSNEEDSWAP(fs);
   1787 #endif
   1788 
   1789 	cg = ino_to_cg(fs, ino);
   1790 	devvp = ump->um_devvp;
   1791 	dev = devvp->v_rdev;
   1792 	cgbno = fsbtodb(fs, cgtod(fs, cg));
   1793 
   1794 	if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
   1795 		panic("ifree: range: dev = 0x%llx, ino = %llu, fs = %s",
   1796 		    (long long)dev, (unsigned long long)ino, fs->fs_fsmnt);
   1797 	error = bread(devvp, cgbno, (int)fs->fs_cgsize,
   1798 	    NOCRED, B_MODIFY, &bp);
   1799 	if (error) {
   1800 		brelse(bp, 0);
   1801 		return (error);
   1802 	}
   1803 	cgp = (struct cg *)bp->b_data;
   1804 	if (!cg_chkmagic(cgp, needswap)) {
   1805 		brelse(bp, 0);
   1806 		return (0);
   1807 	}
   1808 
   1809 	ffs_freefile_common(ump, fs, dev, bp, ino, mode, false);
   1810 
   1811 	bdwrite(bp);
   1812 
   1813 	return 0;
   1814 }
   1815 
   1816 int
   1817 ffs_freefile_snap(struct fs *fs, struct vnode *devvp, ino_t ino, int mode)
   1818 {
   1819 	struct ufsmount *ump;
   1820 	struct cg *cgp;
   1821 	struct buf *bp;
   1822 	int error, cg;
   1823 	daddr_t cgbno;
   1824 	dev_t dev;
   1825 #ifdef FFS_EI
   1826 	const int needswap = UFS_FSNEEDSWAP(fs);
   1827 #endif
   1828 
   1829 	KASSERT(devvp->v_type != VBLK);
   1830 
   1831 	cg = ino_to_cg(fs, ino);
   1832 	dev = VTOI(devvp)->i_devvp->v_rdev;
   1833 	ump = VFSTOUFS(devvp->v_mount);
   1834 	cgbno = fragstoblks(fs, cgtod(fs, cg));
   1835 	if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
   1836 		panic("ifree: range: dev = 0x%llx, ino = %llu, fs = %s",
   1837 		    (unsigned long long)dev, (unsigned long long)ino,
   1838 		    fs->fs_fsmnt);
   1839 	error = bread(devvp, cgbno, (int)fs->fs_cgsize,
   1840 	    NOCRED, B_MODIFY, &bp);
   1841 	if (error) {
   1842 		brelse(bp, 0);
   1843 		return (error);
   1844 	}
   1845 	cgp = (struct cg *)bp->b_data;
   1846 	if (!cg_chkmagic(cgp, needswap)) {
   1847 		brelse(bp, 0);
   1848 		return (0);
   1849 	}
   1850 	ffs_freefile_common(ump, fs, dev, bp, ino, mode, true);
   1851 
   1852 	bdwrite(bp);
   1853 
   1854 	return 0;
   1855 }
   1856 
   1857 static void
   1858 ffs_freefile_common(struct ufsmount *ump, struct fs *fs, dev_t dev,
   1859     struct buf *bp, ino_t ino, int mode, bool devvp_is_snapshot)
   1860 {
   1861 	int cg;
   1862 	struct cg *cgp;
   1863 	u_int8_t *inosused;
   1864 #ifdef FFS_EI
   1865 	const int needswap = UFS_FSNEEDSWAP(fs);
   1866 #endif
   1867 
   1868 	cg = ino_to_cg(fs, ino);
   1869 	cgp = (struct cg *)bp->b_data;
   1870 	cgp->cg_old_time = ufs_rw32(time_second, needswap);
   1871 	if ((fs->fs_magic != FS_UFS1_MAGIC) ||
   1872 	    (fs->fs_old_flags & FS_FLAGS_UPDATED))
   1873 		cgp->cg_time = ufs_rw64(time_second, needswap);
   1874 	inosused = cg_inosused(cgp, needswap);
   1875 	ino %= fs->fs_ipg;
   1876 	if (isclr(inosused, ino)) {
   1877 		printf("ifree: dev = 0x%llx, ino = %llu, fs = %s\n",
   1878 		    (unsigned long long)dev, (unsigned long long)ino +
   1879 		    cg * fs->fs_ipg, fs->fs_fsmnt);
   1880 		if (fs->fs_ronly == 0)
   1881 			panic("ifree: freeing free inode");
   1882 	}
   1883 	clrbit(inosused, ino);
   1884 	if (!devvp_is_snapshot)
   1885 		UFS_WAPBL_UNREGISTER_INODE(ump->um_mountp,
   1886 		    ino + cg * fs->fs_ipg, mode);
   1887 	if (ino < ufs_rw32(cgp->cg_irotor, needswap))
   1888 		cgp->cg_irotor = ufs_rw32(ino, needswap);
   1889 	ufs_add32(cgp->cg_cs.cs_nifree, 1, needswap);
   1890 	mutex_enter(&ump->um_lock);
   1891 	fs->fs_cstotal.cs_nifree++;
   1892 	fs->fs_cs(fs, cg).cs_nifree++;
   1893 	if ((mode & IFMT) == IFDIR) {
   1894 		ufs_add32(cgp->cg_cs.cs_ndir, -1, needswap);
   1895 		fs->fs_cstotal.cs_ndir--;
   1896 		fs->fs_cs(fs, cg).cs_ndir--;
   1897 	}
   1898 	fs->fs_fmod = 1;
   1899 	ACTIVECG_CLR(fs, cg);
   1900 	mutex_exit(&ump->um_lock);
   1901 }
   1902 
   1903 /*
   1904  * Check to see if a file is free.
   1905  */
   1906 int
   1907 ffs_checkfreefile(struct fs *fs, struct vnode *devvp, ino_t ino)
   1908 {
   1909 	struct cg *cgp;
   1910 	struct buf *bp;
   1911 	daddr_t cgbno;
   1912 	int ret, cg;
   1913 	u_int8_t *inosused;
   1914 	const bool devvp_is_snapshot = (devvp->v_type != VBLK);
   1915 
   1916 	KASSERT(devvp_is_snapshot);
   1917 
   1918 	cg = ino_to_cg(fs, ino);
   1919 	if (devvp_is_snapshot)
   1920 		cgbno = fragstoblks(fs, cgtod(fs, cg));
   1921 	else
   1922 		cgbno = fsbtodb(fs, cgtod(fs, cg));
   1923 	if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
   1924 		return 1;
   1925 	if (bread(devvp, cgbno, (int)fs->fs_cgsize, NOCRED, 0, &bp)) {
   1926 		brelse(bp, 0);
   1927 		return 1;
   1928 	}
   1929 	cgp = (struct cg *)bp->b_data;
   1930 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs))) {
   1931 		brelse(bp, 0);
   1932 		return 1;
   1933 	}
   1934 	inosused = cg_inosused(cgp, UFS_FSNEEDSWAP(fs));
   1935 	ino %= fs->fs_ipg;
   1936 	ret = isclr(inosused, ino);
   1937 	brelse(bp, 0);
   1938 	return ret;
   1939 }
   1940 
   1941 /*
   1942  * Find a block of the specified size in the specified cylinder group.
   1943  *
   1944  * It is a panic if a request is made to find a block if none are
   1945  * available.
   1946  */
   1947 static int32_t
   1948 ffs_mapsearch(struct fs *fs, struct cg *cgp, daddr_t bpref, int allocsiz)
   1949 {
   1950 	int32_t bno;
   1951 	int start, len, loc, i;
   1952 	int blk, field, subfield, pos;
   1953 	int ostart, olen;
   1954 	u_int8_t *blksfree;
   1955 #ifdef FFS_EI
   1956 	const int needswap = UFS_FSNEEDSWAP(fs);
   1957 #endif
   1958 
   1959 	/* KASSERT(mutex_owned(&ump->um_lock)); */
   1960 
   1961 	/*
   1962 	 * find the fragment by searching through the free block
   1963 	 * map for an appropriate bit pattern
   1964 	 */
   1965 	if (bpref)
   1966 		start = dtogd(fs, bpref) / NBBY;
   1967 	else
   1968 		start = ufs_rw32(cgp->cg_frotor, needswap) / NBBY;
   1969 	blksfree = cg_blksfree(cgp, needswap);
   1970 	len = howmany(fs->fs_fpg, NBBY) - start;
   1971 	ostart = start;
   1972 	olen = len;
   1973 	loc = scanc((u_int)len,
   1974 		(const u_char *)&blksfree[start],
   1975 		(const u_char *)fragtbl[fs->fs_frag],
   1976 		(1 << (allocsiz - 1 + (fs->fs_frag & (NBBY - 1)))));
   1977 	if (loc == 0) {
   1978 		len = start + 1;
   1979 		start = 0;
   1980 		loc = scanc((u_int)len,
   1981 			(const u_char *)&blksfree[0],
   1982 			(const u_char *)fragtbl[fs->fs_frag],
   1983 			(1 << (allocsiz - 1 + (fs->fs_frag & (NBBY - 1)))));
   1984 		if (loc == 0) {
   1985 			printf("start = %d, len = %d, fs = %s\n",
   1986 			    ostart, olen, fs->fs_fsmnt);
   1987 			printf("offset=%d %ld\n",
   1988 				ufs_rw32(cgp->cg_freeoff, needswap),
   1989 				(long)blksfree - (long)cgp);
   1990 			printf("cg %d\n", cgp->cg_cgx);
   1991 			panic("ffs_alloccg: map corrupted");
   1992 			/* NOTREACHED */
   1993 		}
   1994 	}
   1995 	bno = (start + len - loc) * NBBY;
   1996 	cgp->cg_frotor = ufs_rw32(bno, needswap);
   1997 	/*
   1998 	 * found the byte in the map
   1999 	 * sift through the bits to find the selected frag
   2000 	 */
   2001 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
   2002 		blk = blkmap(fs, blksfree, bno);
   2003 		blk <<= 1;
   2004 		field = around[allocsiz];
   2005 		subfield = inside[allocsiz];
   2006 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
   2007 			if ((blk & field) == subfield)
   2008 				return (bno + pos);
   2009 			field <<= 1;
   2010 			subfield <<= 1;
   2011 		}
   2012 	}
   2013 	printf("bno = %d, fs = %s\n", bno, fs->fs_fsmnt);
   2014 	panic("ffs_alloccg: block not in map");
   2015 	/* return (-1); */
   2016 }
   2017 
   2018 /*
   2019  * Fserr prints the name of a file system with an error diagnostic.
   2020  *
   2021  * The form of the error message is:
   2022  *	fs: error message
   2023  */
   2024 static void
   2025 ffs_fserr(struct fs *fs, u_int uid, const char *cp)
   2026 {
   2027 
   2028 	log(LOG_ERR, "uid %d, pid %d, command %s, on %s: %s\n",
   2029 	    uid, curproc->p_pid, curproc->p_comm, fs->fs_fsmnt, cp);
   2030 }
   2031