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