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