Home | History | Annotate | Line # | Download | only in ffs
ffs_alloc.c revision 1.60
      1 /*	$NetBSD: ffs_alloc.c,v 1.60 2003/04/02 10:39:36 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.60 2003/04/02 10:39:36 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 	DIP(ip, flags) = 0;
    731 	/*
    732 	 * Set up a new generation number for this inode.
    733 	 */
    734 	ip->i_gen++;
    735 	DIP(ip, gen) = ip->i_gen;
    736 	if (fs->fs_magic == FS_UFS2_MAGIC) {
    737 		TIMEVAL_TO_TIMESPEC(&time, &ts);
    738 		ip->i_ffs2_birthtime = ts.tv_sec;
    739 		ip->i_ffs2_birthnsec = ts.tv_nsec;
    740 	}
    741 	return (0);
    742 noinodes:
    743 	ffs_fserr(fs, ap->a_cred->cr_uid, "out of inodes");
    744 	uprintf("\n%s: create/symlink failed, no inodes free\n", fs->fs_fsmnt);
    745 	return (ENOSPC);
    746 }
    747 
    748 /*
    749  * Find a cylinder group in which to place a directory.
    750  *
    751  * The policy implemented by this algorithm is to allocate a
    752  * directory inode in the same cylinder group as its parent
    753  * directory, but also to reserve space for its files inodes
    754  * and data. Restrict the number of directories which may be
    755  * allocated one after another in the same cylinder group
    756  * without intervening allocation of files.
    757  *
    758  * If we allocate a first level directory then force allocation
    759  * in another cylinder group.
    760  */
    761 static ino_t
    762 ffs_dirpref(pip)
    763 	struct inode *pip;
    764 {
    765 	register struct fs *fs;
    766 	int cg, prefcg, dirsize, cgsize;
    767 	int avgifree, avgbfree, avgndir, curdirsize;
    768 	int minifree, minbfree, maxndir;
    769 	int mincg, minndir;
    770 	int maxcontigdirs;
    771 
    772 	fs = pip->i_fs;
    773 
    774 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
    775 	avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
    776 	avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
    777 
    778 	/*
    779 	 * Force allocation in another cg if creating a first level dir.
    780 	 */
    781 	if (ITOV(pip)->v_flag & VROOT) {
    782 		prefcg = random() % fs->fs_ncg;
    783 		mincg = prefcg;
    784 		minndir = fs->fs_ipg;
    785 		for (cg = prefcg; cg < fs->fs_ncg; cg++)
    786 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
    787 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
    788 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    789 				mincg = cg;
    790 				minndir = fs->fs_cs(fs, cg).cs_ndir;
    791 			}
    792 		for (cg = 0; cg < prefcg; cg++)
    793 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
    794 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
    795 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    796 				mincg = cg;
    797 				minndir = fs->fs_cs(fs, cg).cs_ndir;
    798 			}
    799 		return ((ino_t)(fs->fs_ipg * mincg));
    800 	}
    801 
    802 	/*
    803 	 * Count various limits which used for
    804 	 * optimal allocation of a directory inode.
    805 	 */
    806 	maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
    807 	minifree = avgifree - fs->fs_ipg / 4;
    808 	if (minifree < 0)
    809 		minifree = 0;
    810 	minbfree = avgbfree - fragstoblks(fs, fs->fs_fpg) / 4;
    811 	if (minbfree < 0)
    812 		minbfree = 0;
    813 	cgsize = fs->fs_fsize * fs->fs_fpg;
    814 	dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
    815 	curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
    816 	if (dirsize < curdirsize)
    817 		dirsize = curdirsize;
    818 	maxcontigdirs = min(cgsize / dirsize, 255);
    819 	if (fs->fs_avgfpdir > 0)
    820 		maxcontigdirs = min(maxcontigdirs,
    821 				    fs->fs_ipg / fs->fs_avgfpdir);
    822 	if (maxcontigdirs == 0)
    823 		maxcontigdirs = 1;
    824 
    825 	/*
    826 	 * Limit number of dirs in one cg and reserve space for
    827 	 * regular files, but only if we have no deficit in
    828 	 * inodes or space.
    829 	 */
    830 	prefcg = ino_to_cg(fs, pip->i_number);
    831 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
    832 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
    833 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
    834 	    	    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
    835 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
    836 				return ((ino_t)(fs->fs_ipg * cg));
    837 		}
    838 	for (cg = 0; cg < prefcg; cg++)
    839 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
    840 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
    841 	    	    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
    842 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
    843 				return ((ino_t)(fs->fs_ipg * cg));
    844 		}
    845 	/*
    846 	 * This is a backstop when we are deficient in space.
    847 	 */
    848 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
    849 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
    850 			return ((ino_t)(fs->fs_ipg * cg));
    851 	for (cg = 0; cg < prefcg; cg++)
    852 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
    853 			break;
    854 	return ((ino_t)(fs->fs_ipg * cg));
    855 }
    856 
    857 /*
    858  * Select the desired position for the next block in a file.  The file is
    859  * logically divided into sections. The first section is composed of the
    860  * direct blocks. Each additional section contains fs_maxbpg blocks.
    861  *
    862  * If no blocks have been allocated in the first section, the policy is to
    863  * request a block in the same cylinder group as the inode that describes
    864  * the file. If no blocks have been allocated in any other section, the
    865  * policy is to place the section in a cylinder group with a greater than
    866  * average number of free blocks.  An appropriate cylinder group is found
    867  * by using a rotor that sweeps the cylinder groups. When a new group of
    868  * blocks is needed, the sweep begins in the cylinder group following the
    869  * cylinder group from which the previous allocation was made. The sweep
    870  * continues until a cylinder group with greater than the average number
    871  * of free blocks is found. If the allocation is for the first block in an
    872  * indirect block, the information on the previous allocation is unavailable;
    873  * here a best guess is made based upon the logical block number being
    874  * allocated.
    875  *
    876  * If a section is already partially allocated, the policy is to
    877  * contiguously allocate fs_maxcontig blocks.  The end of one of these
    878  * contiguous blocks and the beginning of the next is laid out
    879  * contigously if possible.
    880  */
    881 daddr_t
    882 ffs_blkpref_ufs1(ip, lbn, indx, bap)
    883 	struct inode *ip;
    884 	daddr_t lbn;
    885 	int indx;
    886 	int32_t *bap;	/* XXX ondisk32 */
    887 {
    888 	struct fs *fs;
    889 	int cg;
    890 	int avgbfree, startcg;
    891 
    892 	fs = ip->i_fs;
    893 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
    894 		if (lbn < NDADDR + NINDIR(fs)) {
    895 			cg = ino_to_cg(fs, ip->i_number);
    896 			return (fs->fs_fpg * cg + fs->fs_frag);
    897 		}
    898 		/*
    899 		 * Find a cylinder with greater than average number of
    900 		 * unused data blocks.
    901 		 */
    902 		if (indx == 0 || bap[indx - 1] == 0)
    903 			startcg =
    904 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
    905 		else
    906 			startcg = dtog(fs,
    907 				ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + 1);
    908 		startcg %= fs->fs_ncg;
    909 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
    910 		for (cg = startcg; cg < fs->fs_ncg; cg++)
    911 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    912 				return (fs->fs_fpg * cg + fs->fs_frag);
    913 			}
    914 		for (cg = 0; cg < startcg; cg++)
    915 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    916 				return (fs->fs_fpg * cg + fs->fs_frag);
    917 			}
    918 		return (0);
    919 	}
    920 	/*
    921 	 * We just always try to lay things out contiguously.
    922 	 */
    923 	return ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + fs->fs_frag;
    924 }
    925 
    926 daddr_t
    927 ffs_blkpref_ufs2(ip, lbn, indx, bap)
    928 	struct inode *ip;
    929 	daddr_t lbn;
    930 	int indx;
    931 	int64_t *bap;
    932 {
    933 	struct fs *fs;
    934 	int cg;
    935 	int avgbfree, startcg;
    936 
    937 	fs = ip->i_fs;
    938 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
    939 		if (lbn < NDADDR + NINDIR(fs)) {
    940 			cg = ino_to_cg(fs, ip->i_number);
    941 			return (fs->fs_fpg * cg + fs->fs_frag);
    942 		}
    943 		/*
    944 		 * Find a cylinder with greater than average number of
    945 		 * unused data blocks.
    946 		 */
    947 		if (indx == 0 || bap[indx - 1] == 0)
    948 			startcg =
    949 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
    950 		else
    951 			startcg = dtog(fs,
    952 				ufs_rw64(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + 1);
    953 		startcg %= fs->fs_ncg;
    954 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
    955 		for (cg = startcg; cg < fs->fs_ncg; cg++)
    956 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    957 				return (fs->fs_fpg * cg + fs->fs_frag);
    958 			}
    959 		for (cg = 0; cg < startcg; cg++)
    960 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    961 				return (fs->fs_fpg * cg + fs->fs_frag);
    962 			}
    963 		return (0);
    964 	}
    965 	/*
    966 	 * We just always try to lay things out contiguously.
    967 	 */
    968 	return ufs_rw64(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + fs->fs_frag;
    969 }
    970 
    971 
    972 /*
    973  * Implement the cylinder overflow algorithm.
    974  *
    975  * The policy implemented by this algorithm is:
    976  *   1) allocate the block in its requested cylinder group.
    977  *   2) quadradically rehash on the cylinder group number.
    978  *   3) brute force search for a free block.
    979  */
    980 /*VARARGS5*/
    981 static daddr_t
    982 ffs_hashalloc(ip, cg, pref, size, allocator)
    983 	struct inode *ip;
    984 	int cg;
    985 	daddr_t pref;
    986 	int size;	/* size for data blocks, mode for inodes */
    987 	daddr_t (*allocator) __P((struct inode *, int, daddr_t, int));
    988 {
    989 	struct fs *fs;
    990 	daddr_t result;
    991 	int i, icg = cg;
    992 
    993 	fs = ip->i_fs;
    994 	/*
    995 	 * 1: preferred cylinder group
    996 	 */
    997 	result = (*allocator)(ip, cg, pref, size);
    998 	if (result)
    999 		return (result);
   1000 	/*
   1001 	 * 2: quadratic rehash
   1002 	 */
   1003 	for (i = 1; i < fs->fs_ncg; i *= 2) {
   1004 		cg += i;
   1005 		if (cg >= fs->fs_ncg)
   1006 			cg -= fs->fs_ncg;
   1007 		result = (*allocator)(ip, cg, 0, size);
   1008 		if (result)
   1009 			return (result);
   1010 	}
   1011 	/*
   1012 	 * 3: brute force search
   1013 	 * Note that we start at i == 2, since 0 was checked initially,
   1014 	 * and 1 is always checked in the quadratic rehash.
   1015 	 */
   1016 	cg = (icg + 2) % fs->fs_ncg;
   1017 	for (i = 2; i < fs->fs_ncg; i++) {
   1018 		result = (*allocator)(ip, cg, 0, size);
   1019 		if (result)
   1020 			return (result);
   1021 		cg++;
   1022 		if (cg == fs->fs_ncg)
   1023 			cg = 0;
   1024 	}
   1025 	return (0);
   1026 }
   1027 
   1028 /*
   1029  * Determine whether a fragment can be extended.
   1030  *
   1031  * Check to see if the necessary fragments are available, and
   1032  * if they are, allocate them.
   1033  */
   1034 static daddr_t
   1035 ffs_fragextend(ip, cg, bprev, osize, nsize)
   1036 	struct inode *ip;
   1037 	int cg;
   1038 	daddr_t bprev;
   1039 	int osize, nsize;
   1040 {
   1041 	struct fs *fs;
   1042 	struct cg *cgp;
   1043 	struct buf *bp;
   1044 	daddr_t bno;
   1045 	int frags, bbase;
   1046 	int i, error;
   1047 
   1048 	fs = ip->i_fs;
   1049 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
   1050 		return (0);
   1051 	frags = numfrags(fs, nsize);
   1052 	bbase = fragnum(fs, bprev);
   1053 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
   1054 		/* cannot extend across a block boundary */
   1055 		return (0);
   1056 	}
   1057 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1058 		(int)fs->fs_cgsize, NOCRED, &bp);
   1059 	if (error) {
   1060 		brelse(bp);
   1061 		return (0);
   1062 	}
   1063 	cgp = (struct cg *)bp->b_data;
   1064 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs))) {
   1065 		brelse(bp);
   1066 		return (0);
   1067 	}
   1068 	cgp->cg_old_time = cgp->cg_time =
   1069 	    ufs_rw32(time.tv_sec, UFS_FSNEEDSWAP(fs));
   1070 	bno = dtogd(fs, bprev);
   1071 	for (i = numfrags(fs, osize); i < frags; i++)
   1072 		if (isclr(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i)) {
   1073 			brelse(bp);
   1074 			return (0);
   1075 		}
   1076 	/*
   1077 	 * the current fragment can be extended
   1078 	 * deduct the count on fragment being extended into
   1079 	 * increase the count on the remaining fragment (if any)
   1080 	 * allocate the extended piece
   1081 	 */
   1082 	for (i = frags; i < fs->fs_frag - bbase; i++)
   1083 		if (isclr(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i))
   1084 			break;
   1085 	ufs_add32(cgp->cg_frsum[i - numfrags(fs, osize)], -1, UFS_FSNEEDSWAP(fs));
   1086 	if (i != frags)
   1087 		ufs_add32(cgp->cg_frsum[i - frags], 1, UFS_FSNEEDSWAP(fs));
   1088 	for (i = numfrags(fs, osize); i < frags; i++) {
   1089 		clrbit(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i);
   1090 		ufs_add32(cgp->cg_cs.cs_nffree, -1, UFS_FSNEEDSWAP(fs));
   1091 		fs->fs_cstotal.cs_nffree--;
   1092 		fs->fs_cs(fs, cg).cs_nffree--;
   1093 	}
   1094 	fs->fs_fmod = 1;
   1095 	if (DOINGSOFTDEP(ITOV(ip)))
   1096 		softdep_setup_blkmapdep(bp, fs, bprev);
   1097 	bdwrite(bp);
   1098 	return (bprev);
   1099 }
   1100 
   1101 /*
   1102  * Determine whether a block can be allocated.
   1103  *
   1104  * Check to see if a block of the appropriate size is available,
   1105  * and if it is, allocate it.
   1106  */
   1107 static daddr_t
   1108 ffs_alloccg(ip, cg, bpref, size)
   1109 	struct inode *ip;
   1110 	int cg;
   1111 	daddr_t bpref;
   1112 	int size;
   1113 {
   1114 	struct cg *cgp;
   1115 	struct buf *bp;
   1116 	int32_t bno;
   1117 	daddr_t blkno;
   1118 	int error, frags, allocsiz, i;
   1119 	struct fs *fs = ip->i_fs;
   1120 #ifdef FFS_EI
   1121 	const int needswap = UFS_FSNEEDSWAP(fs);
   1122 #endif
   1123 
   1124 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
   1125 		return (0);
   1126 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1127 		(int)fs->fs_cgsize, NOCRED, &bp);
   1128 	if (error) {
   1129 		brelse(bp);
   1130 		return (0);
   1131 	}
   1132 	cgp = (struct cg *)bp->b_data;
   1133 	if (!cg_chkmagic(cgp, needswap) ||
   1134 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize)) {
   1135 		brelse(bp);
   1136 		return (0);
   1137 	}
   1138 	cgp->cg_old_time = cgp->cg_time = ufs_rw32(time.tv_sec, needswap);
   1139 	if (size == fs->fs_bsize) {
   1140 		blkno = ffs_alloccgblk(ip, bp, bpref);
   1141 		bdwrite(bp);
   1142 		return (blkno);
   1143 	}
   1144 	/*
   1145 	 * check to see if any fragments are already available
   1146 	 * allocsiz is the size which will be allocated, hacking
   1147 	 * it down to a smaller size if necessary
   1148 	 */
   1149 	frags = numfrags(fs, size);
   1150 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
   1151 		if (cgp->cg_frsum[allocsiz] != 0)
   1152 			break;
   1153 	if (allocsiz == fs->fs_frag) {
   1154 		/*
   1155 		 * no fragments were available, so a block will be
   1156 		 * allocated, and hacked up
   1157 		 */
   1158 		if (cgp->cg_cs.cs_nbfree == 0) {
   1159 			brelse(bp);
   1160 			return (0);
   1161 		}
   1162 		blkno = ffs_alloccgblk(ip, bp, bpref);
   1163 		bno = dtogd(fs, blkno);
   1164 		for (i = frags; i < fs->fs_frag; i++)
   1165 			setbit(cg_blksfree(cgp, needswap), bno + i);
   1166 		i = fs->fs_frag - frags;
   1167 		ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
   1168 		fs->fs_cstotal.cs_nffree += i;
   1169 		fs->fs_cs(fs, cg).cs_nffree += i;
   1170 		fs->fs_fmod = 1;
   1171 		ufs_add32(cgp->cg_frsum[i], 1, needswap);
   1172 		bdwrite(bp);
   1173 		return (blkno);
   1174 	}
   1175 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
   1176 #if 0
   1177 	/*
   1178 	 * XXX fvdl mapsearch will panic, and never return -1
   1179 	 *          also: returning NULL as daddr_t ?
   1180 	 */
   1181 	if (bno < 0) {
   1182 		brelse(bp);
   1183 		return (0);
   1184 	}
   1185 #endif
   1186 	for (i = 0; i < frags; i++)
   1187 		clrbit(cg_blksfree(cgp, needswap), bno + i);
   1188 	ufs_add32(cgp->cg_cs.cs_nffree, -frags, needswap);
   1189 	fs->fs_cstotal.cs_nffree -= frags;
   1190 	fs->fs_cs(fs, cg).cs_nffree -= frags;
   1191 	fs->fs_fmod = 1;
   1192 	ufs_add32(cgp->cg_frsum[allocsiz], -1, needswap);
   1193 	if (frags != allocsiz)
   1194 		ufs_add32(cgp->cg_frsum[allocsiz - frags], 1, needswap);
   1195 	blkno = cg * fs->fs_fpg + bno;
   1196 	if (DOINGSOFTDEP(ITOV(ip)))
   1197 		softdep_setup_blkmapdep(bp, fs, blkno);
   1198 	bdwrite(bp);
   1199 	return blkno;
   1200 }
   1201 
   1202 /*
   1203  * Allocate a block in a cylinder group.
   1204  *
   1205  * This algorithm implements the following policy:
   1206  *   1) allocate the requested block.
   1207  *   2) allocate a rotationally optimal block in the same cylinder.
   1208  *   3) allocate the next available block on the block rotor for the
   1209  *      specified cylinder group.
   1210  * Note that this routine only allocates fs_bsize blocks; these
   1211  * blocks may be fragmented by the routine that allocates them.
   1212  */
   1213 static daddr_t
   1214 ffs_alloccgblk(ip, bp, bpref)
   1215 	struct inode *ip;
   1216 	struct buf *bp;
   1217 	daddr_t bpref;
   1218 {
   1219 	struct cg *cgp;
   1220 	daddr_t blkno;
   1221 	int32_t bno;
   1222 	struct fs *fs = ip->i_fs;
   1223 	u_int8_t *blksfree;
   1224 #ifdef FFS_EI
   1225 	const int needswap = UFS_FSNEEDSWAP(fs);
   1226 #endif
   1227 
   1228 	cgp = (struct cg *)bp->b_data;
   1229 	blksfree = cg_blksfree(cgp, needswap);
   1230 	if (bpref == 0 || dtog(fs, bpref) != ufs_rw32(cgp->cg_cgx, needswap)) {
   1231 		bpref = ufs_rw32(cgp->cg_rotor, needswap);
   1232 	} else {
   1233 		bpref = blknum(fs, bpref);
   1234 		bno = dtogd(fs, bpref);
   1235 		/*
   1236 		 * if the requested block is available, use it
   1237 		 */
   1238 		if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
   1239 			goto gotit;
   1240 	}
   1241 	/*
   1242 	 * Take the next available block in this cylinder group.
   1243 	 */
   1244 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
   1245 	if (bno < 0)
   1246 		return (0);
   1247 	cgp->cg_rotor = ufs_rw32(bno, needswap);
   1248 gotit:
   1249 	blkno = fragstoblks(fs, bno);
   1250 	ffs_clrblock(fs, blksfree, blkno);
   1251 	ffs_clusteracct(fs, cgp, blkno, -1);
   1252 	ufs_add32(cgp->cg_cs.cs_nbfree, -1, needswap);
   1253 	fs->fs_cstotal.cs_nbfree--;
   1254 	fs->fs_cs(fs, ufs_rw32(cgp->cg_cgx, needswap)).cs_nbfree--;
   1255 	fs->fs_fmod = 1;
   1256 	blkno = ufs_rw32(cgp->cg_cgx, needswap) * fs->fs_fpg + bno;
   1257 	if (DOINGSOFTDEP(ITOV(ip)))
   1258 		softdep_setup_blkmapdep(bp, fs, blkno);
   1259 	return (blkno);
   1260 }
   1261 
   1262 #ifdef XXXUBC
   1263 /*
   1264  * Determine whether a cluster can be allocated.
   1265  *
   1266  * We do not currently check for optimal rotational layout if there
   1267  * are multiple choices in the same cylinder group. Instead we just
   1268  * take the first one that we find following bpref.
   1269  */
   1270 
   1271 /*
   1272  * This function must be fixed for UFS2 if re-enabled.
   1273  */
   1274 static daddr_t
   1275 ffs_clusteralloc(ip, cg, bpref, len)
   1276 	struct inode *ip;
   1277 	int cg;
   1278 	daddr_t bpref;
   1279 	int len;
   1280 {
   1281 	struct fs *fs;
   1282 	struct cg *cgp;
   1283 	struct buf *bp;
   1284 	int i, got, run, bno, bit, map;
   1285 	u_char *mapp;
   1286 	int32_t *lp;
   1287 
   1288 	fs = ip->i_fs;
   1289 	if (fs->fs_maxcluster[cg] < len)
   1290 		return (0);
   1291 	if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize,
   1292 	    NOCRED, &bp))
   1293 		goto fail;
   1294 	cgp = (struct cg *)bp->b_data;
   1295 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs)))
   1296 		goto fail;
   1297 	/*
   1298 	 * Check to see if a cluster of the needed size (or bigger) is
   1299 	 * available in this cylinder group.
   1300 	 */
   1301 	lp = &cg_clustersum(cgp, UFS_FSNEEDSWAP(fs))[len];
   1302 	for (i = len; i <= fs->fs_contigsumsize; i++)
   1303 		if (ufs_rw32(*lp++, UFS_FSNEEDSWAP(fs)) > 0)
   1304 			break;
   1305 	if (i > fs->fs_contigsumsize) {
   1306 		/*
   1307 		 * This is the first time looking for a cluster in this
   1308 		 * cylinder group. Update the cluster summary information
   1309 		 * to reflect the true maximum sized cluster so that
   1310 		 * future cluster allocation requests can avoid reading
   1311 		 * the cylinder group map only to find no clusters.
   1312 		 */
   1313 		lp = &cg_clustersum(cgp, UFS_FSNEEDSWAP(fs))[len - 1];
   1314 		for (i = len - 1; i > 0; i--)
   1315 			if (ufs_rw32(*lp--, UFS_FSNEEDSWAP(fs)) > 0)
   1316 				break;
   1317 		fs->fs_maxcluster[cg] = i;
   1318 		goto fail;
   1319 	}
   1320 	/*
   1321 	 * Search the cluster map to find a big enough cluster.
   1322 	 * We take the first one that we find, even if it is larger
   1323 	 * than we need as we prefer to get one close to the previous
   1324 	 * block allocation. We do not search before the current
   1325 	 * preference point as we do not want to allocate a block
   1326 	 * that is allocated before the previous one (as we will
   1327 	 * then have to wait for another pass of the elevator
   1328 	 * algorithm before it will be read). We prefer to fail and
   1329 	 * be recalled to try an allocation in the next cylinder group.
   1330 	 */
   1331 	if (dtog(fs, bpref) != cg)
   1332 		bpref = 0;
   1333 	else
   1334 		bpref = fragstoblks(fs, dtogd(fs, blknum(fs, bpref)));
   1335 	mapp = &cg_clustersfree(cgp, UFS_FSNEEDSWAP(fs))[bpref / NBBY];
   1336 	map = *mapp++;
   1337 	bit = 1 << (bpref % NBBY);
   1338 	for (run = 0, got = bpref;
   1339 		got < ufs_rw32(cgp->cg_nclusterblks, UFS_FSNEEDSWAP(fs)); got++) {
   1340 		if ((map & bit) == 0) {
   1341 			run = 0;
   1342 		} else {
   1343 			run++;
   1344 			if (run == len)
   1345 				break;
   1346 		}
   1347 		if ((got & (NBBY - 1)) != (NBBY - 1)) {
   1348 			bit <<= 1;
   1349 		} else {
   1350 			map = *mapp++;
   1351 			bit = 1;
   1352 		}
   1353 	}
   1354 	if (got == ufs_rw32(cgp->cg_nclusterblks, UFS_FSNEEDSWAP(fs)))
   1355 		goto fail;
   1356 	/*
   1357 	 * Allocate the cluster that we have found.
   1358 	 */
   1359 #ifdef DIAGNOSTIC
   1360 	for (i = 1; i <= len; i++)
   1361 		if (!ffs_isblock(fs, cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)),
   1362 		    got - run + i))
   1363 			panic("ffs_clusteralloc: map mismatch");
   1364 #endif
   1365 	bno = cg * fs->fs_fpg + blkstofrags(fs, got - run + 1);
   1366 	if (dtog(fs, bno) != cg)
   1367 		panic("ffs_clusteralloc: allocated out of group");
   1368 	len = blkstofrags(fs, len);
   1369 	for (i = 0; i < len; i += fs->fs_frag)
   1370 		if ((got = ffs_alloccgblk(ip, bp, bno + i)) != bno + i)
   1371 			panic("ffs_clusteralloc: lost block");
   1372 	bdwrite(bp);
   1373 	return (bno);
   1374 
   1375 fail:
   1376 	brelse(bp);
   1377 	return (0);
   1378 }
   1379 #endif /* XXXUBC */
   1380 
   1381 /*
   1382  * Determine whether an inode can be allocated.
   1383  *
   1384  * Check to see if an inode is available, and if it is,
   1385  * allocate it using the following policy:
   1386  *   1) allocate the requested inode.
   1387  *   2) allocate the next available inode after the requested
   1388  *      inode in the specified cylinder group.
   1389  */
   1390 static daddr_t
   1391 ffs_nodealloccg(ip, cg, ipref, mode)
   1392 	struct inode *ip;
   1393 	int cg;
   1394 	daddr_t ipref;
   1395 	int mode;
   1396 {
   1397 	struct cg *cgp;
   1398 	struct buf *bp, *ibp;
   1399 	u_int8_t *inosused;
   1400 	int error, start, len, loc, map, i;
   1401 	struct fs *fs = ip->i_fs;
   1402 	int32_t initediblk;
   1403 	struct ufs2_dinode *dp2;
   1404 #ifdef FFS_EI
   1405 	const int needswap = UFS_FSNEEDSWAP(fs);
   1406 #endif
   1407 
   1408 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
   1409 		return (0);
   1410 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1411 		(int)fs->fs_cgsize, NOCRED, &bp);
   1412 	if (error) {
   1413 		brelse(bp);
   1414 		return (0);
   1415 	}
   1416 	cgp = (struct cg *)bp->b_data;
   1417 	if (!cg_chkmagic(cgp, needswap) || cgp->cg_cs.cs_nifree == 0) {
   1418 		brelse(bp);
   1419 		return (0);
   1420 	}
   1421 	cgp->cg_old_time = cgp->cg_time = ufs_rw32(time.tv_sec, needswap);
   1422 	inosused = cg_inosused(cgp, needswap);
   1423 	if (ipref) {
   1424 		ipref %= fs->fs_ipg;
   1425 		if (isclr(inosused, ipref))
   1426 			goto gotit;
   1427 	}
   1428 	start = ufs_rw32(cgp->cg_irotor, needswap) / NBBY;
   1429 	len = howmany(fs->fs_ipg - ufs_rw32(cgp->cg_irotor, needswap),
   1430 		NBBY);
   1431 	loc = skpc(0xff, len, &inosused[start]);
   1432 	if (loc == 0) {
   1433 		len = start + 1;
   1434 		start = 0;
   1435 		loc = skpc(0xff, len, &inosused[0]);
   1436 		if (loc == 0) {
   1437 			printf("cg = %d, irotor = %d, fs = %s\n",
   1438 			    cg, ufs_rw32(cgp->cg_irotor, needswap),
   1439 				fs->fs_fsmnt);
   1440 			panic("ffs_nodealloccg: map corrupted");
   1441 			/* NOTREACHED */
   1442 		}
   1443 	}
   1444 	i = start + len - loc;
   1445 	map = inosused[i];
   1446 	ipref = i * NBBY;
   1447 	for (i = 1; i < (1 << NBBY); i <<= 1, ipref++) {
   1448 		if ((map & i) == 0) {
   1449 			cgp->cg_irotor = ufs_rw32(ipref, needswap);
   1450 			goto gotit;
   1451 		}
   1452 	}
   1453 	printf("fs = %s\n", fs->fs_fsmnt);
   1454 	panic("ffs_nodealloccg: block not in map");
   1455 	/* NOTREACHED */
   1456 gotit:
   1457 	if (DOINGSOFTDEP(ITOV(ip)))
   1458 		softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref);
   1459 	setbit(inosused, ipref);
   1460 	ufs_add32(cgp->cg_cs.cs_nifree, -1, needswap);
   1461 	fs->fs_cstotal.cs_nifree--;
   1462 	fs->fs_cs(fs, cg).cs_nifree--;
   1463 	fs->fs_fmod = 1;
   1464 	if ((mode & IFMT) == IFDIR) {
   1465 		ufs_add32(cgp->cg_cs.cs_ndir, 1, needswap);
   1466 		fs->fs_cstotal.cs_ndir++;
   1467 		fs->fs_cs(fs, cg).cs_ndir++;
   1468 	}
   1469 	/*
   1470 	 * Check to see if we need to initialize more inodes.
   1471 	 */
   1472 	initediblk = ufs_rw32(cgp->cg_initediblk, needswap);
   1473 	if (fs->fs_magic == FS_UFS2_MAGIC &&
   1474 	    ipref + INOPB(fs) > initediblk &&
   1475 	    initediblk < ufs_rw32(cgp->cg_niblk, needswap)) {
   1476 		ibp = getblk(ip->i_devvp, fsbtodb(fs,
   1477 		    ino_to_fsba(fs, cg * fs->fs_ipg + initediblk)),
   1478 		    (int)fs->fs_bsize, 0, 0);
   1479 		    memset(ibp->b_data, 0, fs->fs_bsize);
   1480 		    dp2 = (struct ufs2_dinode *)(ibp->b_data);
   1481 		    for (i = 0; i < INOPB(fs); i++) {
   1482 			/*
   1483 			 * Don't bother to swap, it's supposed to be
   1484 			 * random, after all.
   1485 			 */
   1486 			dp2->di_gen = random() / 2 + 1;
   1487 			dp2++;
   1488 		}
   1489 		bawrite(ibp);
   1490 		initediblk += INOPB(fs);
   1491 		cgp->cg_initediblk = ufs_rw32(initediblk, needswap);
   1492 	}
   1493 
   1494 	bdwrite(bp);
   1495 	return (cg * fs->fs_ipg + ipref);
   1496 }
   1497 
   1498 /*
   1499  * Free a block or fragment.
   1500  *
   1501  * The specified block or fragment is placed back in the
   1502  * free map. If a fragment is deallocated, a possible
   1503  * block reassembly is checked.
   1504  */
   1505 void
   1506 ffs_blkfree(ip, bno, size)
   1507 	struct inode *ip;
   1508 	daddr_t bno;
   1509 	long size;
   1510 {
   1511 	struct cg *cgp;
   1512 	struct buf *bp;
   1513 	int32_t fragno, cgbno;
   1514 	int i, error, cg, blk, frags, bbase;
   1515 	struct fs *fs = ip->i_fs;
   1516 	const int needswap = UFS_FSNEEDSWAP(fs);
   1517 
   1518 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
   1519 	    fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
   1520 		printf("dev = 0x%x, bno = %" PRId64 " bsize = %d, "
   1521 		       "size = %ld, fs = %s\n",
   1522 		    ip->i_dev, bno, fs->fs_bsize, size, fs->fs_fsmnt);
   1523 		panic("blkfree: bad size");
   1524 	}
   1525 	cg = dtog(fs, bno);
   1526 	if (bno >= fs->fs_size) {
   1527 		printf("bad block %" PRId64 ", ino %d\n", bno, ip->i_number);
   1528 		ffs_fserr(fs, ip->i_uid, "bad block");
   1529 		return;
   1530 	}
   1531 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1532 		(int)fs->fs_cgsize, NOCRED, &bp);
   1533 	if (error) {
   1534 		brelse(bp);
   1535 		return;
   1536 	}
   1537 	cgp = (struct cg *)bp->b_data;
   1538 	if (!cg_chkmagic(cgp, needswap)) {
   1539 		brelse(bp);
   1540 		return;
   1541 	}
   1542 	cgp->cg_old_time = cgp->cg_time = ufs_rw32(time.tv_sec, needswap);
   1543 	cgbno = dtogd(fs, bno);
   1544 	if (size == fs->fs_bsize) {
   1545 		fragno = fragstoblks(fs, cgbno);
   1546 		if (!ffs_isfreeblock(fs, cg_blksfree(cgp, needswap), fragno)) {
   1547 			printf("dev = 0x%x, block = %" PRId64 ", fs = %s\n",
   1548 			    ip->i_dev, bno, fs->fs_fsmnt);
   1549 			panic("blkfree: freeing free block");
   1550 		}
   1551 		ffs_setblock(fs, cg_blksfree(cgp, needswap), fragno);
   1552 		ffs_clusteracct(fs, cgp, fragno, 1);
   1553 		ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
   1554 		fs->fs_cstotal.cs_nbfree++;
   1555 		fs->fs_cs(fs, cg).cs_nbfree++;
   1556 	} else {
   1557 		bbase = cgbno - fragnum(fs, cgbno);
   1558 		/*
   1559 		 * decrement the counts associated with the old frags
   1560 		 */
   1561 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bbase);
   1562 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1, needswap);
   1563 		/*
   1564 		 * deallocate the fragment
   1565 		 */
   1566 		frags = numfrags(fs, size);
   1567 		for (i = 0; i < frags; i++) {
   1568 			if (isset(cg_blksfree(cgp, needswap), cgbno + i)) {
   1569 				printf("dev = 0x%x, block = %" PRId64
   1570 				       ", fs = %s\n",
   1571 				    ip->i_dev, bno + i, fs->fs_fsmnt);
   1572 				panic("blkfree: freeing free frag");
   1573 			}
   1574 			setbit(cg_blksfree(cgp, needswap), cgbno + i);
   1575 		}
   1576 		ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
   1577 		fs->fs_cstotal.cs_nffree += i;
   1578 		fs->fs_cs(fs, cg).cs_nffree += i;
   1579 		/*
   1580 		 * add back in counts associated with the new frags
   1581 		 */
   1582 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bbase);
   1583 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1, needswap);
   1584 		/*
   1585 		 * if a complete block has been reassembled, account for it
   1586 		 */
   1587 		fragno = fragstoblks(fs, bbase);
   1588 		if (ffs_isblock(fs, cg_blksfree(cgp, needswap), fragno)) {
   1589 			ufs_add32(cgp->cg_cs.cs_nffree, -fs->fs_frag, needswap);
   1590 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
   1591 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
   1592 			ffs_clusteracct(fs, cgp, fragno, 1);
   1593 			ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
   1594 			fs->fs_cstotal.cs_nbfree++;
   1595 			fs->fs_cs(fs, cg).cs_nbfree++;
   1596 		}
   1597 	}
   1598 	fs->fs_fmod = 1;
   1599 	bdwrite(bp);
   1600 }
   1601 
   1602 #if defined(DIAGNOSTIC) || defined(DEBUG)
   1603 #ifdef XXXUBC
   1604 /*
   1605  * Verify allocation of a block or fragment. Returns true if block or
   1606  * fragment is allocated, false if it is free.
   1607  */
   1608 static int
   1609 ffs_checkblk(ip, bno, size)
   1610 	struct inode *ip;
   1611 	daddr_t bno;
   1612 	long size;
   1613 {
   1614 	struct fs *fs;
   1615 	struct cg *cgp;
   1616 	struct buf *bp;
   1617 	int i, error, frags, free;
   1618 
   1619 	fs = ip->i_fs;
   1620 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
   1621 		printf("bsize = %d, size = %ld, fs = %s\n",
   1622 		    fs->fs_bsize, size, fs->fs_fsmnt);
   1623 		panic("checkblk: bad size");
   1624 	}
   1625 	if (bno >= fs->fs_size)
   1626 		panic("checkblk: bad block %d", bno);
   1627 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, dtog(fs, bno))),
   1628 		(int)fs->fs_cgsize, NOCRED, &bp);
   1629 	if (error) {
   1630 		brelse(bp);
   1631 		return 0;
   1632 	}
   1633 	cgp = (struct cg *)bp->b_data;
   1634 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs))) {
   1635 		brelse(bp);
   1636 		return 0;
   1637 	}
   1638 	bno = dtogd(fs, bno);
   1639 	if (size == fs->fs_bsize) {
   1640 		free = ffs_isblock(fs, cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)),
   1641 			fragstoblks(fs, bno));
   1642 	} else {
   1643 		frags = numfrags(fs, size);
   1644 		for (free = 0, i = 0; i < frags; i++)
   1645 			if (isset(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i))
   1646 				free++;
   1647 		if (free != 0 && free != frags)
   1648 			panic("checkblk: partially free fragment");
   1649 	}
   1650 	brelse(bp);
   1651 	return (!free);
   1652 }
   1653 #endif /* XXXUBC */
   1654 #endif /* DIAGNOSTIC */
   1655 
   1656 /*
   1657  * Free an inode.
   1658  */
   1659 int
   1660 ffs_vfree(v)
   1661 	void *v;
   1662 {
   1663 	struct vop_vfree_args /* {
   1664 		struct vnode *a_pvp;
   1665 		ino_t a_ino;
   1666 		int a_mode;
   1667 	} */ *ap = v;
   1668 
   1669 	if (DOINGSOFTDEP(ap->a_pvp)) {
   1670 		softdep_freefile(ap);
   1671 		return (0);
   1672 	}
   1673 	return (ffs_freefile(ap));
   1674 }
   1675 
   1676 /*
   1677  * Do the actual free operation.
   1678  * The specified inode is placed back in the free map.
   1679  */
   1680 int
   1681 ffs_freefile(v)
   1682 	void *v;
   1683 {
   1684 	struct vop_vfree_args /* {
   1685 		struct vnode *a_pvp;
   1686 		ino_t a_ino;
   1687 		int a_mode;
   1688 	} */ *ap = v;
   1689 	struct cg *cgp;
   1690 	struct inode *pip = VTOI(ap->a_pvp);
   1691 	struct fs *fs = pip->i_fs;
   1692 	ino_t ino = ap->a_ino;
   1693 	struct buf *bp;
   1694 	int error, cg;
   1695 #ifdef FFS_EI
   1696 	const int needswap = UFS_FSNEEDSWAP(fs);
   1697 #endif
   1698 
   1699 	if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
   1700 		panic("ifree: range: dev = 0x%x, ino = %d, fs = %s",
   1701 		    pip->i_dev, ino, fs->fs_fsmnt);
   1702 	cg = ino_to_cg(fs, ino);
   1703 	error = bread(pip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1704 		(int)fs->fs_cgsize, NOCRED, &bp);
   1705 	if (error) {
   1706 		brelse(bp);
   1707 		return (error);
   1708 	}
   1709 	cgp = (struct cg *)bp->b_data;
   1710 	if (!cg_chkmagic(cgp, needswap)) {
   1711 		brelse(bp);
   1712 		return (0);
   1713 	}
   1714 	cgp->cg_old_time = cgp->cg_time = ufs_rw32(time.tv_sec, needswap);
   1715 	ino %= fs->fs_ipg;
   1716 	if (isclr(cg_inosused(cgp, needswap), ino)) {
   1717 		printf("dev = 0x%x, ino = %d, fs = %s\n",
   1718 		    pip->i_dev, ino, fs->fs_fsmnt);
   1719 		if (fs->fs_ronly == 0)
   1720 			panic("ifree: freeing free inode");
   1721 	}
   1722 	clrbit(cg_inosused(cgp, needswap), ino);
   1723 	if (ino < ufs_rw32(cgp->cg_irotor, needswap))
   1724 		cgp->cg_irotor = ufs_rw32(ino, needswap);
   1725 	ufs_add32(cgp->cg_cs.cs_nifree, 1, needswap);
   1726 	fs->fs_cstotal.cs_nifree++;
   1727 	fs->fs_cs(fs, cg).cs_nifree++;
   1728 	if ((ap->a_mode & IFMT) == IFDIR) {
   1729 		ufs_add32(cgp->cg_cs.cs_ndir, -1, needswap);
   1730 		fs->fs_cstotal.cs_ndir--;
   1731 		fs->fs_cs(fs, cg).cs_ndir--;
   1732 	}
   1733 	fs->fs_fmod = 1;
   1734 	bdwrite(bp);
   1735 	return (0);
   1736 }
   1737 
   1738 /*
   1739  * Find a block of the specified size in the specified cylinder group.
   1740  *
   1741  * It is a panic if a request is made to find a block if none are
   1742  * available.
   1743  */
   1744 static int32_t
   1745 ffs_mapsearch(fs, cgp, bpref, allocsiz)
   1746 	struct fs *fs;
   1747 	struct cg *cgp;
   1748 	daddr_t bpref;
   1749 	int allocsiz;
   1750 {
   1751 	int32_t bno;
   1752 	int start, len, loc, i;
   1753 	int blk, field, subfield, pos;
   1754 	int ostart, olen;
   1755 #ifdef FFS_EI
   1756 	const int needswap = UFS_FSNEEDSWAP(fs);
   1757 #endif
   1758 
   1759 	/*
   1760 	 * find the fragment by searching through the free block
   1761 	 * map for an appropriate bit pattern
   1762 	 */
   1763 	if (bpref)
   1764 		start = dtogd(fs, bpref) / NBBY;
   1765 	else
   1766 		start = ufs_rw32(cgp->cg_frotor, needswap) / NBBY;
   1767 	len = howmany(fs->fs_fpg, NBBY) - start;
   1768 	ostart = start;
   1769 	olen = len;
   1770 	loc = scanc((u_int)len,
   1771 		(const u_char *)&cg_blksfree(cgp, needswap)[start],
   1772 		(const u_char *)fragtbl[fs->fs_frag],
   1773 		(1 << (allocsiz - 1 + (fs->fs_frag & (NBBY - 1)))));
   1774 	if (loc == 0) {
   1775 		len = start + 1;
   1776 		start = 0;
   1777 		loc = scanc((u_int)len,
   1778 			(const u_char *)&cg_blksfree(cgp, needswap)[0],
   1779 			(const u_char *)fragtbl[fs->fs_frag],
   1780 			(1 << (allocsiz - 1 + (fs->fs_frag & (NBBY - 1)))));
   1781 		if (loc == 0) {
   1782 			printf("start = %d, len = %d, fs = %s\n",
   1783 			    ostart, olen, fs->fs_fsmnt);
   1784 			printf("offset=%d %ld\n",
   1785 				ufs_rw32(cgp->cg_freeoff, needswap),
   1786 				(long)cg_blksfree(cgp, needswap) - (long)cgp);
   1787 			panic("ffs_alloccg: map corrupted");
   1788 			/* NOTREACHED */
   1789 		}
   1790 	}
   1791 	bno = (start + len - loc) * NBBY;
   1792 	cgp->cg_frotor = ufs_rw32(bno, needswap);
   1793 	/*
   1794 	 * found the byte in the map
   1795 	 * sift through the bits to find the selected frag
   1796 	 */
   1797 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
   1798 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bno);
   1799 		blk <<= 1;
   1800 		field = around[allocsiz];
   1801 		subfield = inside[allocsiz];
   1802 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
   1803 			if ((blk & field) == subfield)
   1804 				return (bno + pos);
   1805 			field <<= 1;
   1806 			subfield <<= 1;
   1807 		}
   1808 	}
   1809 	printf("bno = %d, fs = %s\n", bno, fs->fs_fsmnt);
   1810 	panic("ffs_alloccg: block not in map");
   1811 	/* return (-1); */
   1812 }
   1813 
   1814 /*
   1815  * Update the cluster map because of an allocation or free.
   1816  *
   1817  * Cnt == 1 means free; cnt == -1 means allocating.
   1818  */
   1819 void
   1820 ffs_clusteracct(fs, cgp, blkno, cnt)
   1821 	struct fs *fs;
   1822 	struct cg *cgp;
   1823 	int32_t blkno;
   1824 	int cnt;
   1825 {
   1826 	int32_t *sump;
   1827 	int32_t *lp;
   1828 	u_char *freemapp, *mapp;
   1829 	int i, start, end, forw, back, map, bit;
   1830 #ifdef FFS_EI
   1831 	const int needswap = UFS_FSNEEDSWAP(fs);
   1832 #endif
   1833 
   1834 	if (fs->fs_contigsumsize <= 0)
   1835 		return;
   1836 	freemapp = cg_clustersfree(cgp, needswap);
   1837 	sump = cg_clustersum(cgp, needswap);
   1838 	/*
   1839 	 * Allocate or clear the actual block.
   1840 	 */
   1841 	if (cnt > 0)
   1842 		setbit(freemapp, blkno);
   1843 	else
   1844 		clrbit(freemapp, blkno);
   1845 	/*
   1846 	 * Find the size of the cluster going forward.
   1847 	 */
   1848 	start = blkno + 1;
   1849 	end = start + fs->fs_contigsumsize;
   1850 	if (end >= ufs_rw32(cgp->cg_nclusterblks, needswap))
   1851 		end = ufs_rw32(cgp->cg_nclusterblks, needswap);
   1852 	mapp = &freemapp[start / NBBY];
   1853 	map = *mapp++;
   1854 	bit = 1 << (start % NBBY);
   1855 	for (i = start; i < end; i++) {
   1856 		if ((map & bit) == 0)
   1857 			break;
   1858 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
   1859 			bit <<= 1;
   1860 		} else {
   1861 			map = *mapp++;
   1862 			bit = 1;
   1863 		}
   1864 	}
   1865 	forw = i - start;
   1866 	/*
   1867 	 * Find the size of the cluster going backward.
   1868 	 */
   1869 	start = blkno - 1;
   1870 	end = start - fs->fs_contigsumsize;
   1871 	if (end < 0)
   1872 		end = -1;
   1873 	mapp = &freemapp[start / NBBY];
   1874 	map = *mapp--;
   1875 	bit = 1 << (start % NBBY);
   1876 	for (i = start; i > end; i--) {
   1877 		if ((map & bit) == 0)
   1878 			break;
   1879 		if ((i & (NBBY - 1)) != 0) {
   1880 			bit >>= 1;
   1881 		} else {
   1882 			map = *mapp--;
   1883 			bit = 1 << (NBBY - 1);
   1884 		}
   1885 	}
   1886 	back = start - i;
   1887 	/*
   1888 	 * Account for old cluster and the possibly new forward and
   1889 	 * back clusters.
   1890 	 */
   1891 	i = back + forw + 1;
   1892 	if (i > fs->fs_contigsumsize)
   1893 		i = fs->fs_contigsumsize;
   1894 	ufs_add32(sump[i], cnt, needswap);
   1895 	if (back > 0)
   1896 		ufs_add32(sump[back], -cnt, needswap);
   1897 	if (forw > 0)
   1898 		ufs_add32(sump[forw], -cnt, needswap);
   1899 
   1900 	/*
   1901 	 * Update cluster summary information.
   1902 	 */
   1903 	lp = &sump[fs->fs_contigsumsize];
   1904 	for (i = fs->fs_contigsumsize; i > 0; i--)
   1905 		if (ufs_rw32(*lp--, needswap) > 0)
   1906 			break;
   1907 	fs->fs_maxcluster[ufs_rw32(cgp->cg_cgx, needswap)] = i;
   1908 }
   1909 
   1910 /*
   1911  * Fserr prints the name of a file system with an error diagnostic.
   1912  *
   1913  * The form of the error message is:
   1914  *	fs: error message
   1915  */
   1916 static void
   1917 ffs_fserr(fs, uid, cp)
   1918 	struct fs *fs;
   1919 	u_int uid;
   1920 	char *cp;
   1921 {
   1922 
   1923 	log(LOG_ERR, "uid %d comm %s on %s: %s\n",
   1924 	    uid, curproc->p_comm, fs->fs_fsmnt, cp);
   1925 }
   1926