Home | History | Annotate | Line # | Download | only in ffs
ffs_alloc.c revision 1.51
      1 /*	$NetBSD: ffs_alloc.c,v 1.51 2001/09/15 20:36:41 chs 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 				fs->fs_cgrotor = cg;
    861 				return (fs->fs_fpg * cg + fs->fs_frag);
    862 			}
    863 		for (cg = 0; cg <= startcg; cg++)
    864 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    865 				fs->fs_cgrotor = cg;
    866 				return (fs->fs_fpg * cg + fs->fs_frag);
    867 			}
    868 		return (0);
    869 	}
    870 	/*
    871 	 * One or more previous blocks have been laid out. If less
    872 	 * than fs_maxcontig previous blocks are contiguous, the
    873 	 * next block is requested contiguously, otherwise it is
    874 	 * requested rotationally delayed by fs_rotdelay milliseconds.
    875 	 */
    876 	nextblk = ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + fs->fs_frag;
    877 	if (indx < fs->fs_maxcontig ||
    878 		ufs_rw32(bap[indx - fs->fs_maxcontig], UFS_FSNEEDSWAP(fs)) +
    879 	    blkstofrags(fs, fs->fs_maxcontig) != nextblk)
    880 		return (nextblk);
    881 	if (fs->fs_rotdelay != 0)
    882 		/*
    883 		 * Here we convert ms of delay to frags as:
    884 		 * (frags) = (ms) * (rev/sec) * (sect/rev) /
    885 		 *	((sect/frag) * (ms/sec))
    886 		 * then round up to the next block.
    887 		 */
    888 		nextblk += roundup(fs->fs_rotdelay * fs->fs_rps * fs->fs_nsect /
    889 		    (NSPF(fs) * 1000), fs->fs_frag);
    890 	return (nextblk);
    891 }
    892 
    893 /*
    894  * Implement the cylinder overflow algorithm.
    895  *
    896  * The policy implemented by this algorithm is:
    897  *   1) allocate the block in its requested cylinder group.
    898  *   2) quadradically rehash on the cylinder group number.
    899  *   3) brute force search for a free block.
    900  */
    901 /*VARARGS5*/
    902 static u_long
    903 ffs_hashalloc(ip, cg, pref, size, allocator)
    904 	struct inode *ip;
    905 	int cg;
    906 	long pref;
    907 	int size;	/* size for data blocks, mode for inodes */
    908 	ufs_daddr_t (*allocator) __P((struct inode *, int, ufs_daddr_t, int));
    909 {
    910 	struct fs *fs;
    911 	long result;
    912 	int i, icg = cg;
    913 
    914 	fs = ip->i_fs;
    915 	/*
    916 	 * 1: preferred cylinder group
    917 	 */
    918 	result = (*allocator)(ip, cg, pref, size);
    919 	if (result)
    920 		return (result);
    921 	/*
    922 	 * 2: quadratic rehash
    923 	 */
    924 	for (i = 1; i < fs->fs_ncg; i *= 2) {
    925 		cg += i;
    926 		if (cg >= fs->fs_ncg)
    927 			cg -= fs->fs_ncg;
    928 		result = (*allocator)(ip, cg, 0, size);
    929 		if (result)
    930 			return (result);
    931 	}
    932 	/*
    933 	 * 3: brute force search
    934 	 * Note that we start at i == 2, since 0 was checked initially,
    935 	 * and 1 is always checked in the quadratic rehash.
    936 	 */
    937 	cg = (icg + 2) % fs->fs_ncg;
    938 	for (i = 2; i < fs->fs_ncg; i++) {
    939 		result = (*allocator)(ip, cg, 0, size);
    940 		if (result)
    941 			return (result);
    942 		cg++;
    943 		if (cg == fs->fs_ncg)
    944 			cg = 0;
    945 	}
    946 	return (0);
    947 }
    948 
    949 /*
    950  * Determine whether a fragment can be extended.
    951  *
    952  * Check to see if the necessary fragments are available, and
    953  * if they are, allocate them.
    954  */
    955 static ufs_daddr_t
    956 ffs_fragextend(ip, cg, bprev, osize, nsize)
    957 	struct inode *ip;
    958 	int cg;
    959 	long bprev;
    960 	int osize, nsize;
    961 {
    962 	struct fs *fs;
    963 	struct cg *cgp;
    964 	struct buf *bp;
    965 	long bno;
    966 	int frags, bbase;
    967 	int i, error;
    968 
    969 	fs = ip->i_fs;
    970 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
    971 		return (0);
    972 	frags = numfrags(fs, nsize);
    973 	bbase = fragnum(fs, bprev);
    974 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
    975 		/* cannot extend across a block boundary */
    976 		return (0);
    977 	}
    978 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
    979 		(int)fs->fs_cgsize, NOCRED, &bp);
    980 	if (error) {
    981 		brelse(bp);
    982 		return (0);
    983 	}
    984 	cgp = (struct cg *)bp->b_data;
    985 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs))) {
    986 		brelse(bp);
    987 		return (0);
    988 	}
    989 	cgp->cg_time = ufs_rw32(time.tv_sec, UFS_FSNEEDSWAP(fs));
    990 	bno = dtogd(fs, bprev);
    991 	for (i = numfrags(fs, osize); i < frags; i++)
    992 		if (isclr(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i)) {
    993 			brelse(bp);
    994 			return (0);
    995 		}
    996 	/*
    997 	 * the current fragment can be extended
    998 	 * deduct the count on fragment being extended into
    999 	 * increase the count on the remaining fragment (if any)
   1000 	 * allocate the extended piece
   1001 	 */
   1002 	for (i = frags; i < fs->fs_frag - bbase; i++)
   1003 		if (isclr(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i))
   1004 			break;
   1005 	ufs_add32(cgp->cg_frsum[i - numfrags(fs, osize)], -1, UFS_FSNEEDSWAP(fs));
   1006 	if (i != frags)
   1007 		ufs_add32(cgp->cg_frsum[i - frags], 1, UFS_FSNEEDSWAP(fs));
   1008 	for (i = numfrags(fs, osize); i < frags; i++) {
   1009 		clrbit(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i);
   1010 		ufs_add32(cgp->cg_cs.cs_nffree, -1, UFS_FSNEEDSWAP(fs));
   1011 		fs->fs_cstotal.cs_nffree--;
   1012 		fs->fs_cs(fs, cg).cs_nffree--;
   1013 	}
   1014 	fs->fs_fmod = 1;
   1015 	if (DOINGSOFTDEP(ITOV(ip)))
   1016 		softdep_setup_blkmapdep(bp, fs, bprev);
   1017 	bdwrite(bp);
   1018 	return (bprev);
   1019 }
   1020 
   1021 /*
   1022  * Determine whether a block can be allocated.
   1023  *
   1024  * Check to see if a block of the appropriate size is available,
   1025  * and if it is, allocate it.
   1026  */
   1027 static ufs_daddr_t
   1028 ffs_alloccg(ip, cg, bpref, size)
   1029 	struct inode *ip;
   1030 	int cg;
   1031 	ufs_daddr_t bpref;
   1032 	int size;
   1033 {
   1034 	struct cg *cgp;
   1035 	struct buf *bp;
   1036 	ufs_daddr_t bno, blkno;
   1037 	int error, frags, allocsiz, i;
   1038 	struct fs *fs = ip->i_fs;
   1039 #ifdef FFS_EI
   1040 	const int needswap = UFS_FSNEEDSWAP(fs);
   1041 #endif
   1042 
   1043 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
   1044 		return (0);
   1045 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1046 		(int)fs->fs_cgsize, NOCRED, &bp);
   1047 	if (error) {
   1048 		brelse(bp);
   1049 		return (0);
   1050 	}
   1051 	cgp = (struct cg *)bp->b_data;
   1052 	if (!cg_chkmagic(cgp, needswap) ||
   1053 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize)) {
   1054 		brelse(bp);
   1055 		return (0);
   1056 	}
   1057 	cgp->cg_time = ufs_rw32(time.tv_sec, needswap);
   1058 	if (size == fs->fs_bsize) {
   1059 		bno = ffs_alloccgblk(ip, bp, bpref);
   1060 		bdwrite(bp);
   1061 		return (bno);
   1062 	}
   1063 	/*
   1064 	 * check to see if any fragments are already available
   1065 	 * allocsiz is the size which will be allocated, hacking
   1066 	 * it down to a smaller size if necessary
   1067 	 */
   1068 	frags = numfrags(fs, size);
   1069 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
   1070 		if (cgp->cg_frsum[allocsiz] != 0)
   1071 			break;
   1072 	if (allocsiz == fs->fs_frag) {
   1073 		/*
   1074 		 * no fragments were available, so a block will be
   1075 		 * allocated, and hacked up
   1076 		 */
   1077 		if (cgp->cg_cs.cs_nbfree == 0) {
   1078 			brelse(bp);
   1079 			return (0);
   1080 		}
   1081 		bno = ffs_alloccgblk(ip, bp, bpref);
   1082 		bpref = dtogd(fs, bno);
   1083 		for (i = frags; i < fs->fs_frag; i++)
   1084 			setbit(cg_blksfree(cgp, needswap), bpref + i);
   1085 		i = fs->fs_frag - frags;
   1086 		ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
   1087 		fs->fs_cstotal.cs_nffree += i;
   1088 		fs->fs_cs(fs, cg).cs_nffree += i;
   1089 		fs->fs_fmod = 1;
   1090 		ufs_add32(cgp->cg_frsum[i], 1, needswap);
   1091 		bdwrite(bp);
   1092 		return (bno);
   1093 	}
   1094 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
   1095 #if 0
   1096 	/*
   1097 	 * XXX fvdl mapsearch will panic, and never return -1
   1098 	 *          also: returning NULL as ufs_daddr_t ?
   1099 	 */
   1100 	if (bno < 0) {
   1101 		brelse(bp);
   1102 		return (0);
   1103 	}
   1104 #endif
   1105 	for (i = 0; i < frags; i++)
   1106 		clrbit(cg_blksfree(cgp, needswap), bno + i);
   1107 	ufs_add32(cgp->cg_cs.cs_nffree, -frags, needswap);
   1108 	fs->fs_cstotal.cs_nffree -= frags;
   1109 	fs->fs_cs(fs, cg).cs_nffree -= frags;
   1110 	fs->fs_fmod = 1;
   1111 	ufs_add32(cgp->cg_frsum[allocsiz], -1, needswap);
   1112 	if (frags != allocsiz)
   1113 		ufs_add32(cgp->cg_frsum[allocsiz - frags], 1, needswap);
   1114 	blkno = cg * fs->fs_fpg + bno;
   1115 	if (DOINGSOFTDEP(ITOV(ip)))
   1116 		softdep_setup_blkmapdep(bp, fs, blkno);
   1117 	bdwrite(bp);
   1118 	return blkno;
   1119 }
   1120 
   1121 /*
   1122  * Allocate a block in a cylinder group.
   1123  *
   1124  * This algorithm implements the following policy:
   1125  *   1) allocate the requested block.
   1126  *   2) allocate a rotationally optimal block in the same cylinder.
   1127  *   3) allocate the next available block on the block rotor for the
   1128  *      specified cylinder group.
   1129  * Note that this routine only allocates fs_bsize blocks; these
   1130  * blocks may be fragmented by the routine that allocates them.
   1131  */
   1132 static ufs_daddr_t
   1133 ffs_alloccgblk(ip, bp, bpref)
   1134 	struct inode *ip;
   1135 	struct buf *bp;
   1136 	ufs_daddr_t bpref;
   1137 {
   1138 	struct cg *cgp;
   1139 	ufs_daddr_t bno, blkno;
   1140 	int cylno, pos, delta;
   1141 	short *cylbp;
   1142 	int i;
   1143 	struct fs *fs = ip->i_fs;
   1144 #ifdef FFS_EI
   1145 	const int needswap = UFS_FSNEEDSWAP(fs);
   1146 #endif
   1147 
   1148 	cgp = (struct cg *)bp->b_data;
   1149 	if (bpref == 0 || dtog(fs, bpref) != ufs_rw32(cgp->cg_cgx, needswap)) {
   1150 		bpref = ufs_rw32(cgp->cg_rotor, needswap);
   1151 		goto norot;
   1152 	}
   1153 	bpref = blknum(fs, bpref);
   1154 	bpref = dtogd(fs, bpref);
   1155 	/*
   1156 	 * if the requested block is available, use it
   1157 	 */
   1158 	if (ffs_isblock(fs, cg_blksfree(cgp, needswap),
   1159 		fragstoblks(fs, bpref))) {
   1160 		bno = bpref;
   1161 		goto gotit;
   1162 	}
   1163 	if (fs->fs_nrpos <= 1 || fs->fs_cpc == 0) {
   1164 		/*
   1165 		 * Block layout information is not available.
   1166 		 * Leaving bpref unchanged means we take the
   1167 		 * next available free block following the one
   1168 		 * we just allocated. Hopefully this will at
   1169 		 * least hit a track cache on drives of unknown
   1170 		 * geometry (e.g. SCSI).
   1171 		 */
   1172 		goto norot;
   1173 	}
   1174 	/*
   1175 	 * check for a block available on the same cylinder
   1176 	 */
   1177 	cylno = cbtocylno(fs, bpref);
   1178 	if (cg_blktot(cgp, needswap)[cylno] == 0)
   1179 		goto norot;
   1180 	/*
   1181 	 * check the summary information to see if a block is
   1182 	 * available in the requested cylinder starting at the
   1183 	 * requested rotational position and proceeding around.
   1184 	 */
   1185 	cylbp = cg_blks(fs, cgp, cylno, needswap);
   1186 	pos = cbtorpos(fs, bpref);
   1187 	for (i = pos; i < fs->fs_nrpos; i++)
   1188 		if (ufs_rw16(cylbp[i], needswap) > 0)
   1189 			break;
   1190 	if (i == fs->fs_nrpos)
   1191 		for (i = 0; i < pos; i++)
   1192 			if (ufs_rw16(cylbp[i], needswap) > 0)
   1193 				break;
   1194 	if (ufs_rw16(cylbp[i], needswap) > 0) {
   1195 		/*
   1196 		 * found a rotational position, now find the actual
   1197 		 * block. A panic if none is actually there.
   1198 		 */
   1199 		pos = cylno % fs->fs_cpc;
   1200 		bno = (cylno - pos) * fs->fs_spc / NSPB(fs);
   1201 		if (fs_postbl(fs, pos)[i] == -1) {
   1202 			printf("pos = %d, i = %d, fs = %s\n",
   1203 			    pos, i, fs->fs_fsmnt);
   1204 			panic("ffs_alloccgblk: cyl groups corrupted");
   1205 		}
   1206 		for (i = fs_postbl(fs, pos)[i];; ) {
   1207 			if (ffs_isblock(fs, cg_blksfree(cgp, needswap), bno + i)) {
   1208 				bno = blkstofrags(fs, (bno + i));
   1209 				goto gotit;
   1210 			}
   1211 			delta = fs_rotbl(fs)[i];
   1212 			if (delta <= 0 ||
   1213 			    delta + i > fragstoblks(fs, fs->fs_fpg))
   1214 				break;
   1215 			i += delta;
   1216 		}
   1217 		printf("pos = %d, i = %d, fs = %s\n", pos, i, fs->fs_fsmnt);
   1218 		panic("ffs_alloccgblk: can't find blk in cyl");
   1219 	}
   1220 norot:
   1221 	/*
   1222 	 * no blocks in the requested cylinder, so take next
   1223 	 * available one in this cylinder group.
   1224 	 */
   1225 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
   1226 	if (bno < 0)
   1227 		return (0);
   1228 	cgp->cg_rotor = ufs_rw32(bno, needswap);
   1229 gotit:
   1230 	blkno = fragstoblks(fs, bno);
   1231 	ffs_clrblock(fs, cg_blksfree(cgp, needswap), (long)blkno);
   1232 	ffs_clusteracct(fs, cgp, blkno, -1);
   1233 	ufs_add32(cgp->cg_cs.cs_nbfree, -1, needswap);
   1234 	fs->fs_cstotal.cs_nbfree--;
   1235 	fs->fs_cs(fs, ufs_rw32(cgp->cg_cgx, needswap)).cs_nbfree--;
   1236 	cylno = cbtocylno(fs, bno);
   1237 	ufs_add16(cg_blks(fs, cgp, cylno, needswap)[cbtorpos(fs, bno)], -1,
   1238 	    needswap);
   1239 	ufs_add32(cg_blktot(cgp, needswap)[cylno], -1, needswap);
   1240 	fs->fs_fmod = 1;
   1241 	blkno = ufs_rw32(cgp->cg_cgx, needswap) * fs->fs_fpg + bno;
   1242 	if (DOINGSOFTDEP(ITOV(ip)))
   1243 		softdep_setup_blkmapdep(bp, fs, blkno);
   1244 	return (blkno);
   1245 }
   1246 
   1247 /*
   1248  * Determine whether a cluster can be allocated.
   1249  *
   1250  * We do not currently check for optimal rotational layout if there
   1251  * are multiple choices in the same cylinder group. Instead we just
   1252  * take the first one that we find following bpref.
   1253  */
   1254 static ufs_daddr_t
   1255 ffs_clusteralloc(ip, cg, bpref, len)
   1256 	struct inode *ip;
   1257 	int cg;
   1258 	ufs_daddr_t bpref;
   1259 	int len;
   1260 {
   1261 	struct fs *fs;
   1262 	struct cg *cgp;
   1263 	struct buf *bp;
   1264 	int i, got, run, bno, bit, map;
   1265 	u_char *mapp;
   1266 	int32_t *lp;
   1267 
   1268 	fs = ip->i_fs;
   1269 	if (fs->fs_maxcluster[cg] < len)
   1270 		return (0);
   1271 	if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize,
   1272 	    NOCRED, &bp))
   1273 		goto fail;
   1274 	cgp = (struct cg *)bp->b_data;
   1275 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs)))
   1276 		goto fail;
   1277 	/*
   1278 	 * Check to see if a cluster of the needed size (or bigger) is
   1279 	 * available in this cylinder group.
   1280 	 */
   1281 	lp = &cg_clustersum(cgp, UFS_FSNEEDSWAP(fs))[len];
   1282 	for (i = len; i <= fs->fs_contigsumsize; i++)
   1283 		if (ufs_rw32(*lp++, UFS_FSNEEDSWAP(fs)) > 0)
   1284 			break;
   1285 	if (i > fs->fs_contigsumsize) {
   1286 		/*
   1287 		 * This is the first time looking for a cluster in this
   1288 		 * cylinder group. Update the cluster summary information
   1289 		 * to reflect the true maximum sized cluster so that
   1290 		 * future cluster allocation requests can avoid reading
   1291 		 * the cylinder group map only to find no clusters.
   1292 		 */
   1293 		lp = &cg_clustersum(cgp, UFS_FSNEEDSWAP(fs))[len - 1];
   1294 		for (i = len - 1; i > 0; i--)
   1295 			if (ufs_rw32(*lp--, UFS_FSNEEDSWAP(fs)) > 0)
   1296 				break;
   1297 		fs->fs_maxcluster[cg] = i;
   1298 		goto fail;
   1299 	}
   1300 	/*
   1301 	 * Search the cluster map to find a big enough cluster.
   1302 	 * We take the first one that we find, even if it is larger
   1303 	 * than we need as we prefer to get one close to the previous
   1304 	 * block allocation. We do not search before the current
   1305 	 * preference point as we do not want to allocate a block
   1306 	 * that is allocated before the previous one (as we will
   1307 	 * then have to wait for another pass of the elevator
   1308 	 * algorithm before it will be read). We prefer to fail and
   1309 	 * be recalled to try an allocation in the next cylinder group.
   1310 	 */
   1311 	if (dtog(fs, bpref) != cg)
   1312 		bpref = 0;
   1313 	else
   1314 		bpref = fragstoblks(fs, dtogd(fs, blknum(fs, bpref)));
   1315 	mapp = &cg_clustersfree(cgp, UFS_FSNEEDSWAP(fs))[bpref / NBBY];
   1316 	map = *mapp++;
   1317 	bit = 1 << (bpref % NBBY);
   1318 	for (run = 0, got = bpref;
   1319 		got < ufs_rw32(cgp->cg_nclusterblks, UFS_FSNEEDSWAP(fs)); got++) {
   1320 		if ((map & bit) == 0) {
   1321 			run = 0;
   1322 		} else {
   1323 			run++;
   1324 			if (run == len)
   1325 				break;
   1326 		}
   1327 		if ((got & (NBBY - 1)) != (NBBY - 1)) {
   1328 			bit <<= 1;
   1329 		} else {
   1330 			map = *mapp++;
   1331 			bit = 1;
   1332 		}
   1333 	}
   1334 	if (got == ufs_rw32(cgp->cg_nclusterblks, UFS_FSNEEDSWAP(fs)))
   1335 		goto fail;
   1336 	/*
   1337 	 * Allocate the cluster that we have found.
   1338 	 */
   1339 #ifdef DIAGNOSTIC
   1340 	for (i = 1; i <= len; i++)
   1341 		if (!ffs_isblock(fs, cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)),
   1342 		    got - run + i))
   1343 			panic("ffs_clusteralloc: map mismatch");
   1344 #endif
   1345 	bno = cg * fs->fs_fpg + blkstofrags(fs, got - run + 1);
   1346 	if (dtog(fs, bno) != cg)
   1347 		panic("ffs_clusteralloc: allocated out of group");
   1348 	len = blkstofrags(fs, len);
   1349 	for (i = 0; i < len; i += fs->fs_frag)
   1350 		if ((got = ffs_alloccgblk(ip, bp, bno + i)) != bno + i)
   1351 			panic("ffs_clusteralloc: lost block");
   1352 	bdwrite(bp);
   1353 	return (bno);
   1354 
   1355 fail:
   1356 	brelse(bp);
   1357 	return (0);
   1358 }
   1359 
   1360 /*
   1361  * Determine whether an inode can be allocated.
   1362  *
   1363  * Check to see if an inode is available, and if it is,
   1364  * allocate it using the following policy:
   1365  *   1) allocate the requested inode.
   1366  *   2) allocate the next available inode after the requested
   1367  *      inode in the specified cylinder group.
   1368  */
   1369 static ufs_daddr_t
   1370 ffs_nodealloccg(ip, cg, ipref, mode)
   1371 	struct inode *ip;
   1372 	int cg;
   1373 	ufs_daddr_t ipref;
   1374 	int mode;
   1375 {
   1376 	struct cg *cgp;
   1377 	struct buf *bp;
   1378 	int error, start, len, loc, map, i;
   1379 	struct fs *fs = ip->i_fs;
   1380 #ifdef FFS_EI
   1381 	const int needswap = UFS_FSNEEDSWAP(fs);
   1382 #endif
   1383 
   1384 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
   1385 		return (0);
   1386 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1387 		(int)fs->fs_cgsize, NOCRED, &bp);
   1388 	if (error) {
   1389 		brelse(bp);
   1390 		return (0);
   1391 	}
   1392 	cgp = (struct cg *)bp->b_data;
   1393 	if (!cg_chkmagic(cgp, needswap) || cgp->cg_cs.cs_nifree == 0) {
   1394 		brelse(bp);
   1395 		return (0);
   1396 	}
   1397 	cgp->cg_time = ufs_rw32(time.tv_sec, needswap);
   1398 	if (ipref) {
   1399 		ipref %= fs->fs_ipg;
   1400 		if (isclr(cg_inosused(cgp, needswap), ipref))
   1401 			goto gotit;
   1402 	}
   1403 	start = ufs_rw32(cgp->cg_irotor, needswap) / NBBY;
   1404 	len = howmany(fs->fs_ipg - ufs_rw32(cgp->cg_irotor, needswap),
   1405 		NBBY);
   1406 	loc = skpc(0xff, len, &cg_inosused(cgp, needswap)[start]);
   1407 	if (loc == 0) {
   1408 		len = start + 1;
   1409 		start = 0;
   1410 		loc = skpc(0xff, len, &cg_inosused(cgp, needswap)[0]);
   1411 		if (loc == 0) {
   1412 			printf("cg = %d, irotor = %d, fs = %s\n",
   1413 			    cg, ufs_rw32(cgp->cg_irotor, needswap),
   1414 				fs->fs_fsmnt);
   1415 			panic("ffs_nodealloccg: map corrupted");
   1416 			/* NOTREACHED */
   1417 		}
   1418 	}
   1419 	i = start + len - loc;
   1420 	map = cg_inosused(cgp, needswap)[i];
   1421 	ipref = i * NBBY;
   1422 	for (i = 1; i < (1 << NBBY); i <<= 1, ipref++) {
   1423 		if ((map & i) == 0) {
   1424 			cgp->cg_irotor = ufs_rw32(ipref, needswap);
   1425 			goto gotit;
   1426 		}
   1427 	}
   1428 	printf("fs = %s\n", fs->fs_fsmnt);
   1429 	panic("ffs_nodealloccg: block not in map");
   1430 	/* NOTREACHED */
   1431 gotit:
   1432 	if (DOINGSOFTDEP(ITOV(ip)))
   1433 		softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref);
   1434 	setbit(cg_inosused(cgp, needswap), ipref);
   1435 	ufs_add32(cgp->cg_cs.cs_nifree, -1, needswap);
   1436 	fs->fs_cstotal.cs_nifree--;
   1437 	fs->fs_cs(fs, cg).cs_nifree--;
   1438 	fs->fs_fmod = 1;
   1439 	if ((mode & IFMT) == IFDIR) {
   1440 		ufs_add32(cgp->cg_cs.cs_ndir, 1, needswap);
   1441 		fs->fs_cstotal.cs_ndir++;
   1442 		fs->fs_cs(fs, cg).cs_ndir++;
   1443 	}
   1444 	bdwrite(bp);
   1445 	return (cg * fs->fs_ipg + ipref);
   1446 }
   1447 
   1448 /*
   1449  * Free a block or fragment.
   1450  *
   1451  * The specified block or fragment is placed back in the
   1452  * free map. If a fragment is deallocated, a possible
   1453  * block reassembly is checked.
   1454  */
   1455 void
   1456 ffs_blkfree(ip, bno, size)
   1457 	struct inode *ip;
   1458 	ufs_daddr_t bno;
   1459 	long size;
   1460 {
   1461 	struct cg *cgp;
   1462 	struct buf *bp;
   1463 	ufs_daddr_t blkno;
   1464 	int i, error, cg, blk, frags, bbase;
   1465 	struct fs *fs = ip->i_fs;
   1466 	const int needswap = UFS_FSNEEDSWAP(fs);
   1467 
   1468 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
   1469 	    fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
   1470 		printf("dev = 0x%x, bno = %u bsize = %d, size = %ld, fs = %s\n",
   1471 		    ip->i_dev, bno, fs->fs_bsize, size, fs->fs_fsmnt);
   1472 		panic("blkfree: bad size");
   1473 	}
   1474 	cg = dtog(fs, bno);
   1475 	if ((u_int)bno >= fs->fs_size) {
   1476 		printf("bad block %d, ino %d\n", bno, ip->i_number);
   1477 		ffs_fserr(fs, ip->i_ffs_uid, "bad block");
   1478 		return;
   1479 	}
   1480 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1481 		(int)fs->fs_cgsize, NOCRED, &bp);
   1482 	if (error) {
   1483 		brelse(bp);
   1484 		return;
   1485 	}
   1486 	cgp = (struct cg *)bp->b_data;
   1487 	if (!cg_chkmagic(cgp, needswap)) {
   1488 		brelse(bp);
   1489 		return;
   1490 	}
   1491 	cgp->cg_time = ufs_rw32(time.tv_sec, needswap);
   1492 	bno = dtogd(fs, bno);
   1493 	if (size == fs->fs_bsize) {
   1494 		blkno = fragstoblks(fs, bno);
   1495 		if (!ffs_isfreeblock(fs, cg_blksfree(cgp, needswap), blkno)) {
   1496 			printf("dev = 0x%x, block = %d, fs = %s\n",
   1497 			    ip->i_dev, bno, fs->fs_fsmnt);
   1498 			panic("blkfree: freeing free block");
   1499 		}
   1500 		ffs_setblock(fs, cg_blksfree(cgp, needswap), blkno);
   1501 		ffs_clusteracct(fs, cgp, blkno, 1);
   1502 		ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
   1503 		fs->fs_cstotal.cs_nbfree++;
   1504 		fs->fs_cs(fs, cg).cs_nbfree++;
   1505 		i = cbtocylno(fs, bno);
   1506 		ufs_add16(cg_blks(fs, cgp, i, needswap)[cbtorpos(fs, bno)], 1,
   1507 		    needswap);
   1508 		ufs_add32(cg_blktot(cgp, needswap)[i], 1, needswap);
   1509 	} else {
   1510 		bbase = bno - fragnum(fs, bno);
   1511 		/*
   1512 		 * decrement the counts associated with the old frags
   1513 		 */
   1514 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bbase);
   1515 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1, needswap);
   1516 		/*
   1517 		 * deallocate the fragment
   1518 		 */
   1519 		frags = numfrags(fs, size);
   1520 		for (i = 0; i < frags; i++) {
   1521 			if (isset(cg_blksfree(cgp, needswap), bno + i)) {
   1522 				printf("dev = 0x%x, block = %d, fs = %s\n",
   1523 				    ip->i_dev, bno + i, fs->fs_fsmnt);
   1524 				panic("blkfree: freeing free frag");
   1525 			}
   1526 			setbit(cg_blksfree(cgp, needswap), bno + i);
   1527 		}
   1528 		ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
   1529 		fs->fs_cstotal.cs_nffree += i;
   1530 		fs->fs_cs(fs, cg).cs_nffree += i;
   1531 		/*
   1532 		 * add back in counts associated with the new frags
   1533 		 */
   1534 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bbase);
   1535 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1, needswap);
   1536 		/*
   1537 		 * if a complete block has been reassembled, account for it
   1538 		 */
   1539 		blkno = fragstoblks(fs, bbase);
   1540 		if (ffs_isblock(fs, cg_blksfree(cgp, needswap), blkno)) {
   1541 			ufs_add32(cgp->cg_cs.cs_nffree, -fs->fs_frag, needswap);
   1542 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
   1543 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
   1544 			ffs_clusteracct(fs, cgp, blkno, 1);
   1545 			ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
   1546 			fs->fs_cstotal.cs_nbfree++;
   1547 			fs->fs_cs(fs, cg).cs_nbfree++;
   1548 			i = cbtocylno(fs, bbase);
   1549 			ufs_add16(cg_blks(fs, cgp, i, needswap)[cbtorpos(fs,
   1550 								bbase)], 1,
   1551 			    needswap);
   1552 			ufs_add32(cg_blktot(cgp, needswap)[i], 1, needswap);
   1553 		}
   1554 	}
   1555 	fs->fs_fmod = 1;
   1556 	bdwrite(bp);
   1557 }
   1558 
   1559 #if defined(DIAGNOSTIC) || defined(DEBUG)
   1560 /*
   1561  * Verify allocation of a block or fragment. Returns true if block or
   1562  * fragment is allocated, false if it is free.
   1563  */
   1564 static int
   1565 ffs_checkblk(ip, bno, size)
   1566 	struct inode *ip;
   1567 	ufs_daddr_t bno;
   1568 	long size;
   1569 {
   1570 	struct fs *fs;
   1571 	struct cg *cgp;
   1572 	struct buf *bp;
   1573 	int i, error, frags, free;
   1574 
   1575 	fs = ip->i_fs;
   1576 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
   1577 		printf("bsize = %d, size = %ld, fs = %s\n",
   1578 		    fs->fs_bsize, size, fs->fs_fsmnt);
   1579 		panic("checkblk: bad size");
   1580 	}
   1581 	if ((u_int)bno >= fs->fs_size)
   1582 		panic("checkblk: bad block %d", bno);
   1583 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, dtog(fs, bno))),
   1584 		(int)fs->fs_cgsize, NOCRED, &bp);
   1585 	if (error) {
   1586 		brelse(bp);
   1587 		return 0;
   1588 	}
   1589 	cgp = (struct cg *)bp->b_data;
   1590 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs))) {
   1591 		brelse(bp);
   1592 		return 0;
   1593 	}
   1594 	bno = dtogd(fs, bno);
   1595 	if (size == fs->fs_bsize) {
   1596 		free = ffs_isblock(fs, cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)),
   1597 			fragstoblks(fs, bno));
   1598 	} else {
   1599 		frags = numfrags(fs, size);
   1600 		for (free = 0, i = 0; i < frags; i++)
   1601 			if (isset(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i))
   1602 				free++;
   1603 		if (free != 0 && free != frags)
   1604 			panic("checkblk: partially free fragment");
   1605 	}
   1606 	brelse(bp);
   1607 	return (!free);
   1608 }
   1609 #endif /* DIAGNOSTIC */
   1610 
   1611 /*
   1612  * Free an inode.
   1613  */
   1614 int
   1615 ffs_vfree(v)
   1616 	void *v;
   1617 {
   1618 	struct vop_vfree_args /* {
   1619 		struct vnode *a_pvp;
   1620 		ino_t a_ino;
   1621 		int a_mode;
   1622 	} */ *ap = v;
   1623 
   1624 	if (DOINGSOFTDEP(ap->a_pvp)) {
   1625 		softdep_freefile(ap);
   1626 		return (0);
   1627 	}
   1628 	return (ffs_freefile(ap));
   1629 }
   1630 
   1631 /*
   1632  * Do the actual free operation.
   1633  * The specified inode is placed back in the free map.
   1634  */
   1635 int
   1636 ffs_freefile(v)
   1637 	void *v;
   1638 {
   1639 	struct vop_vfree_args /* {
   1640 		struct vnode *a_pvp;
   1641 		ino_t a_ino;
   1642 		int a_mode;
   1643 	} */ *ap = v;
   1644 	struct cg *cgp;
   1645 	struct inode *pip = VTOI(ap->a_pvp);
   1646 	struct fs *fs = pip->i_fs;
   1647 	ino_t ino = ap->a_ino;
   1648 	struct buf *bp;
   1649 	int error, cg;
   1650 #ifdef FFS_EI
   1651 	const int needswap = UFS_FSNEEDSWAP(fs);
   1652 #endif
   1653 
   1654 	if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
   1655 		panic("ifree: range: dev = 0x%x, ino = %d, fs = %s\n",
   1656 		    pip->i_dev, ino, fs->fs_fsmnt);
   1657 	cg = ino_to_cg(fs, ino);
   1658 	error = bread(pip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1659 		(int)fs->fs_cgsize, NOCRED, &bp);
   1660 	if (error) {
   1661 		brelse(bp);
   1662 		return (error);
   1663 	}
   1664 	cgp = (struct cg *)bp->b_data;
   1665 	if (!cg_chkmagic(cgp, needswap)) {
   1666 		brelse(bp);
   1667 		return (0);
   1668 	}
   1669 	cgp->cg_time = ufs_rw32(time.tv_sec, needswap);
   1670 	ino %= fs->fs_ipg;
   1671 	if (isclr(cg_inosused(cgp, needswap), ino)) {
   1672 		printf("dev = 0x%x, ino = %d, fs = %s\n",
   1673 		    pip->i_dev, ino, fs->fs_fsmnt);
   1674 		if (fs->fs_ronly == 0)
   1675 			panic("ifree: freeing free inode");
   1676 	}
   1677 	clrbit(cg_inosused(cgp, needswap), ino);
   1678 	if (ino < ufs_rw32(cgp->cg_irotor, needswap))
   1679 		cgp->cg_irotor = ufs_rw32(ino, needswap);
   1680 	ufs_add32(cgp->cg_cs.cs_nifree, 1, needswap);
   1681 	fs->fs_cstotal.cs_nifree++;
   1682 	fs->fs_cs(fs, cg).cs_nifree++;
   1683 	if ((ap->a_mode & IFMT) == IFDIR) {
   1684 		ufs_add32(cgp->cg_cs.cs_ndir, -1, needswap);
   1685 		fs->fs_cstotal.cs_ndir--;
   1686 		fs->fs_cs(fs, cg).cs_ndir--;
   1687 	}
   1688 	fs->fs_fmod = 1;
   1689 	bdwrite(bp);
   1690 	return (0);
   1691 }
   1692 
   1693 /*
   1694  * Find a block of the specified size in the specified cylinder group.
   1695  *
   1696  * It is a panic if a request is made to find a block if none are
   1697  * available.
   1698  */
   1699 static ufs_daddr_t
   1700 ffs_mapsearch(fs, cgp, bpref, allocsiz)
   1701 	struct fs *fs;
   1702 	struct cg *cgp;
   1703 	ufs_daddr_t bpref;
   1704 	int allocsiz;
   1705 {
   1706 	ufs_daddr_t bno;
   1707 	int start, len, loc, i;
   1708 	int blk, field, subfield, pos;
   1709 	int ostart, olen;
   1710 #ifdef FFS_EI
   1711 	const int needswap = UFS_FSNEEDSWAP(fs);
   1712 #endif
   1713 
   1714 	/*
   1715 	 * find the fragment by searching through the free block
   1716 	 * map for an appropriate bit pattern
   1717 	 */
   1718 	if (bpref)
   1719 		start = dtogd(fs, bpref) / NBBY;
   1720 	else
   1721 		start = ufs_rw32(cgp->cg_frotor, needswap) / NBBY;
   1722 	len = howmany(fs->fs_fpg, NBBY) - start;
   1723 	ostart = start;
   1724 	olen = len;
   1725 	loc = scanc((u_int)len,
   1726 		(const u_char *)&cg_blksfree(cgp, needswap)[start],
   1727 		(const u_char *)fragtbl[fs->fs_frag],
   1728 		(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
   1729 	if (loc == 0) {
   1730 		len = start + 1;
   1731 		start = 0;
   1732 		loc = scanc((u_int)len,
   1733 			(const u_char *)&cg_blksfree(cgp, needswap)[0],
   1734 			(const u_char *)fragtbl[fs->fs_frag],
   1735 			(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
   1736 		if (loc == 0) {
   1737 			printf("start = %d, len = %d, fs = %s\n",
   1738 			    ostart, olen, fs->fs_fsmnt);
   1739 			printf("offset=%d %ld\n",
   1740 				ufs_rw32(cgp->cg_freeoff, needswap),
   1741 				(long)cg_blksfree(cgp, needswap) - (long)cgp);
   1742 			panic("ffs_alloccg: map corrupted");
   1743 			/* NOTREACHED */
   1744 		}
   1745 	}
   1746 	bno = (start + len - loc) * NBBY;
   1747 	cgp->cg_frotor = ufs_rw32(bno, needswap);
   1748 	/*
   1749 	 * found the byte in the map
   1750 	 * sift through the bits to find the selected frag
   1751 	 */
   1752 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
   1753 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bno);
   1754 		blk <<= 1;
   1755 		field = around[allocsiz];
   1756 		subfield = inside[allocsiz];
   1757 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
   1758 			if ((blk & field) == subfield)
   1759 				return (bno + pos);
   1760 			field <<= 1;
   1761 			subfield <<= 1;
   1762 		}
   1763 	}
   1764 	printf("bno = %d, fs = %s\n", bno, fs->fs_fsmnt);
   1765 	panic("ffs_alloccg: block not in map");
   1766 	return (-1);
   1767 }
   1768 
   1769 /*
   1770  * Update the cluster map because of an allocation or free.
   1771  *
   1772  * Cnt == 1 means free; cnt == -1 means allocating.
   1773  */
   1774 void
   1775 ffs_clusteracct(fs, cgp, blkno, cnt)
   1776 	struct fs *fs;
   1777 	struct cg *cgp;
   1778 	ufs_daddr_t blkno;
   1779 	int cnt;
   1780 {
   1781 	int32_t *sump;
   1782 	int32_t *lp;
   1783 	u_char *freemapp, *mapp;
   1784 	int i, start, end, forw, back, map, bit;
   1785 #ifdef FFS_EI
   1786 	const int needswap = UFS_FSNEEDSWAP(fs);
   1787 #endif
   1788 
   1789 	if (fs->fs_contigsumsize <= 0)
   1790 		return;
   1791 	freemapp = cg_clustersfree(cgp, needswap);
   1792 	sump = cg_clustersum(cgp, needswap);
   1793 	/*
   1794 	 * Allocate or clear the actual block.
   1795 	 */
   1796 	if (cnt > 0)
   1797 		setbit(freemapp, blkno);
   1798 	else
   1799 		clrbit(freemapp, blkno);
   1800 	/*
   1801 	 * Find the size of the cluster going forward.
   1802 	 */
   1803 	start = blkno + 1;
   1804 	end = start + fs->fs_contigsumsize;
   1805 	if (end >= ufs_rw32(cgp->cg_nclusterblks, needswap))
   1806 		end = ufs_rw32(cgp->cg_nclusterblks, needswap);
   1807 	mapp = &freemapp[start / NBBY];
   1808 	map = *mapp++;
   1809 	bit = 1 << (start % NBBY);
   1810 	for (i = start; i < end; i++) {
   1811 		if ((map & bit) == 0)
   1812 			break;
   1813 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
   1814 			bit <<= 1;
   1815 		} else {
   1816 			map = *mapp++;
   1817 			bit = 1;
   1818 		}
   1819 	}
   1820 	forw = i - start;
   1821 	/*
   1822 	 * Find the size of the cluster going backward.
   1823 	 */
   1824 	start = blkno - 1;
   1825 	end = start - fs->fs_contigsumsize;
   1826 	if (end < 0)
   1827 		end = -1;
   1828 	mapp = &freemapp[start / NBBY];
   1829 	map = *mapp--;
   1830 	bit = 1 << (start % NBBY);
   1831 	for (i = start; i > end; i--) {
   1832 		if ((map & bit) == 0)
   1833 			break;
   1834 		if ((i & (NBBY - 1)) != 0) {
   1835 			bit >>= 1;
   1836 		} else {
   1837 			map = *mapp--;
   1838 			bit = 1 << (NBBY - 1);
   1839 		}
   1840 	}
   1841 	back = start - i;
   1842 	/*
   1843 	 * Account for old cluster and the possibly new forward and
   1844 	 * back clusters.
   1845 	 */
   1846 	i = back + forw + 1;
   1847 	if (i > fs->fs_contigsumsize)
   1848 		i = fs->fs_contigsumsize;
   1849 	ufs_add32(sump[i], cnt, needswap);
   1850 	if (back > 0)
   1851 		ufs_add32(sump[back], -cnt, needswap);
   1852 	if (forw > 0)
   1853 		ufs_add32(sump[forw], -cnt, needswap);
   1854 
   1855 	/*
   1856 	 * Update cluster summary information.
   1857 	 */
   1858 	lp = &sump[fs->fs_contigsumsize];
   1859 	for (i = fs->fs_contigsumsize; i > 0; i--)
   1860 		if (ufs_rw32(*lp--, needswap) > 0)
   1861 			break;
   1862 	fs->fs_maxcluster[ufs_rw32(cgp->cg_cgx, needswap)] = i;
   1863 }
   1864 
   1865 /*
   1866  * Fserr prints the name of a file system with an error diagnostic.
   1867  *
   1868  * The form of the error message is:
   1869  *	fs: error message
   1870  */
   1871 static void
   1872 ffs_fserr(fs, uid, cp)
   1873 	struct fs *fs;
   1874 	u_int uid;
   1875 	char *cp;
   1876 {
   1877 
   1878 	log(LOG_ERR, "uid %d comm %s on %s: %s\n",
   1879 	    uid, curproc->p_comm, fs->fs_fsmnt, cp);
   1880 }
   1881