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