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