Home | History | Annotate | Line # | Download | only in ffs
ffs_alloc.c revision 1.46
      1 /*	$NetBSD: ffs_alloc.c,v 1.46 2001/08/20 12:00:54 wiz 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 fs *, ino_t));
     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 heirarchy 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, (voff_t)lbn));
    124 		voff_t endoff = round_page(lblktosize(fs, (voff_t)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 heirarchy 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 	ipref = pip->i_number;
    646 	if ((mode & IFMT) == IFDIR)
    647 		ipref = ffs_dirpref(fs, ipref);
    648 	if (ipref >= fs->fs_ncg * fs->fs_ipg)
    649 		ipref = 0;
    650 	cg = ino_to_cg(fs, ipref);
    651 	ino = (ino_t)ffs_hashalloc(pip, cg, (long)ipref, mode, ffs_nodealloccg);
    652 	if (ino == 0)
    653 		goto noinodes;
    654 	error = VFS_VGET(pvp->v_mount, ino, ap->a_vpp);
    655 	if (error) {
    656 		VOP_VFREE(pvp, ino, mode);
    657 		return (error);
    658 	}
    659 	ip = VTOI(*ap->a_vpp);
    660 	if (ip->i_ffs_mode) {
    661 		printf("mode = 0%o, inum = %d, fs = %s\n",
    662 		    ip->i_ffs_mode, ip->i_number, fs->fs_fsmnt);
    663 		panic("ffs_valloc: dup alloc");
    664 	}
    665 	if (ip->i_ffs_blocks) {				/* XXX */
    666 		printf("free inode %s/%d had %d blocks\n",
    667 		    fs->fs_fsmnt, ino, ip->i_ffs_blocks);
    668 		ip->i_ffs_blocks = 0;
    669 	}
    670 	ip->i_ffs_flags = 0;
    671 	/*
    672 	 * Set up a new generation number for this inode.
    673 	 */
    674 	ip->i_ffs_gen++;
    675 	return (0);
    676 noinodes:
    677 	ffs_fserr(fs, ap->a_cred->cr_uid, "out of inodes");
    678 	uprintf("\n%s: create/symlink failed, no inodes free\n", fs->fs_fsmnt);
    679 	return (ENOSPC);
    680 }
    681 
    682 /*
    683  * Find a cylinder in which to place a directory.
    684  *
    685  * The policy implemented by this algorithm is to select from among
    686  * those cylinder groups with above the average number of free inodes
    687  * and a "reasonable" number of free blocks, the one with the smallest
    688  * number of directories.  If there are no cylinder groups with a
    689  * reasonable number of free blocks, we select a CG with *any* free
    690  * blocks or free frags.
    691  *
    692  * "Reasonable" here is arbitrarily defined as "at least 25% of the
    693  * average amount of free space."
    694  *
    695  * This complex policy is intended to avoid pathological (linear
    696  * search) allocation performance when a filesystem contains many
    697  * small cylinder groups with few directory inodes and no free blocks;
    698  * this was observed in practice with the old allocation policy (which
    699  * ignored the distribution of free blocks).  Under the old policy,
    700  * when a new filesystem is populated with a number of files somewhat
    701  * larger than the CG size, and then a second tree containing a large
    702  * number of files and directories is created, mkdir() performance
    703  * would degrade catastrophically, taking many seconds and involving
    704  * thousands of disk reads to complete.
    705  *
    706  * XXX TODO: we currently ignore our "ipref" argument; we may want to
    707  * add a heuristic to determine whether to place a directory in the
    708  * same CG as its parent to reduce the amount of seeking required in
    709  * the course of tree-walks.
    710  */
    711 static ino_t
    712 ffs_dirpref(fs, ipref)
    713 	struct fs *fs;
    714 	ino_t ipref;
    715 {
    716 	int cg, minndir, mincg, avgifree, bfreethresh;
    717 	int minndirf, mincgf;
    718 	struct csum *cs;
    719 
    720 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
    721 	bfreethresh = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
    722 	bfreethresh >>= 2;
    723 	minndir = fs->fs_ipg;
    724 	minndirf = fs->fs_ipg;
    725 	mincg = 0;
    726 	mincgf = 0;
    727 	for (cg = 0; cg < fs->fs_ncg; cg++) {
    728 		cs = &fs->fs_cs(fs, cg);
    729 		if (cs->cs_nifree >= avgifree) {
    730 			if ((cs->cs_ndir < minndir) &&
    731 			    (cs->cs_nbfree > bfreethresh)) {
    732 				mincg = cg;
    733 				minndir = cs->cs_ndir;
    734 			}
    735 			if ((cs->cs_ndir < minndirf) &&
    736 			    ((cs->cs_nffree + cs->cs_nbfree) > 0)) {
    737 				mincgf = cg;
    738 				minndirf = cs->cs_ndir;
    739 			}
    740 		}
    741 	}
    742 	if (minndir == fs->fs_ipg)
    743 		mincg = mincgf;
    744 	return ((ino_t)(fs->fs_ipg * mincg));
    745 }
    746 
    747 /*
    748  * Select the desired position for the next block in a file.  The file is
    749  * logically divided into sections. The first section is composed of the
    750  * direct blocks. Each additional section contains fs_maxbpg blocks.
    751  *
    752  * If no blocks have been allocated in the first section, the policy is to
    753  * request a block in the same cylinder group as the inode that describes
    754  * the file. If no blocks have been allocated in any other section, the
    755  * policy is to place the section in a cylinder group with a greater than
    756  * average number of free blocks.  An appropriate cylinder group is found
    757  * by using a rotor that sweeps the cylinder groups. When a new group of
    758  * blocks is needed, the sweep begins in the cylinder group following the
    759  * cylinder group from which the previous allocation was made. The sweep
    760  * continues until a cylinder group with greater than the average number
    761  * of free blocks is found. If the allocation is for the first block in an
    762  * indirect block, the information on the previous allocation is unavailable;
    763  * here a best guess is made based upon the logical block number being
    764  * allocated.
    765  *
    766  * If a section is already partially allocated, the policy is to
    767  * contiguously allocate fs_maxcontig blocks.  The end of one of these
    768  * contiguous blocks and the beginning of the next is physically separated
    769  * so that the disk head will be in transit between them for at least
    770  * fs_rotdelay milliseconds.  This is to allow time for the processor to
    771  * schedule another I/O transfer.
    772  */
    773 ufs_daddr_t
    774 ffs_blkpref(ip, lbn, indx, bap)
    775 	struct inode *ip;
    776 	ufs_daddr_t lbn;
    777 	int indx;
    778 	ufs_daddr_t *bap;
    779 {
    780 	struct fs *fs;
    781 	int cg;
    782 	int avgbfree, startcg;
    783 	ufs_daddr_t nextblk;
    784 
    785 	fs = ip->i_fs;
    786 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
    787 		if (lbn < NDADDR + NINDIR(fs)) {
    788 			cg = ino_to_cg(fs, ip->i_number);
    789 			return (fs->fs_fpg * cg + fs->fs_frag);
    790 		}
    791 		/*
    792 		 * Find a cylinder with greater than average number of
    793 		 * unused data blocks.
    794 		 */
    795 		if (indx == 0 || bap[indx - 1] == 0)
    796 			startcg =
    797 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
    798 		else
    799 			startcg = dtog(fs,
    800 				ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + 1);
    801 		startcg %= fs->fs_ncg;
    802 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
    803 		for (cg = startcg; cg < fs->fs_ncg; cg++)
    804 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    805 				fs->fs_cgrotor = cg;
    806 				return (fs->fs_fpg * cg + fs->fs_frag);
    807 			}
    808 		for (cg = 0; cg <= startcg; cg++)
    809 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
    810 				fs->fs_cgrotor = cg;
    811 				return (fs->fs_fpg * cg + fs->fs_frag);
    812 			}
    813 		return (0);
    814 	}
    815 	/*
    816 	 * One or more previous blocks have been laid out. If less
    817 	 * than fs_maxcontig previous blocks are contiguous, the
    818 	 * next block is requested contiguously, otherwise it is
    819 	 * requested rotationally delayed by fs_rotdelay milliseconds.
    820 	 */
    821 	nextblk = ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + fs->fs_frag;
    822 	if (indx < fs->fs_maxcontig ||
    823 		ufs_rw32(bap[indx - fs->fs_maxcontig], UFS_FSNEEDSWAP(fs)) +
    824 	    blkstofrags(fs, fs->fs_maxcontig) != nextblk)
    825 		return (nextblk);
    826 	if (fs->fs_rotdelay != 0)
    827 		/*
    828 		 * Here we convert ms of delay to frags as:
    829 		 * (frags) = (ms) * (rev/sec) * (sect/rev) /
    830 		 *	((sect/frag) * (ms/sec))
    831 		 * then round up to the next block.
    832 		 */
    833 		nextblk += roundup(fs->fs_rotdelay * fs->fs_rps * fs->fs_nsect /
    834 		    (NSPF(fs) * 1000), fs->fs_frag);
    835 	return (nextblk);
    836 }
    837 
    838 /*
    839  * Implement the cylinder overflow algorithm.
    840  *
    841  * The policy implemented by this algorithm is:
    842  *   1) allocate the block in its requested cylinder group.
    843  *   2) quadradically rehash on the cylinder group number.
    844  *   3) brute force search for a free block.
    845  */
    846 /*VARARGS5*/
    847 static u_long
    848 ffs_hashalloc(ip, cg, pref, size, allocator)
    849 	struct inode *ip;
    850 	int cg;
    851 	long pref;
    852 	int size;	/* size for data blocks, mode for inodes */
    853 	ufs_daddr_t (*allocator) __P((struct inode *, int, ufs_daddr_t, int));
    854 {
    855 	struct fs *fs;
    856 	long result;
    857 	int i, icg = cg;
    858 
    859 	fs = ip->i_fs;
    860 	/*
    861 	 * 1: preferred cylinder group
    862 	 */
    863 	result = (*allocator)(ip, cg, pref, size);
    864 	if (result)
    865 		return (result);
    866 	/*
    867 	 * 2: quadratic rehash
    868 	 */
    869 	for (i = 1; i < fs->fs_ncg; i *= 2) {
    870 		cg += i;
    871 		if (cg >= fs->fs_ncg)
    872 			cg -= fs->fs_ncg;
    873 		result = (*allocator)(ip, cg, 0, size);
    874 		if (result)
    875 			return (result);
    876 	}
    877 	/*
    878 	 * 3: brute force search
    879 	 * Note that we start at i == 2, since 0 was checked initially,
    880 	 * and 1 is always checked in the quadratic rehash.
    881 	 */
    882 	cg = (icg + 2) % fs->fs_ncg;
    883 	for (i = 2; i < fs->fs_ncg; i++) {
    884 		result = (*allocator)(ip, cg, 0, size);
    885 		if (result)
    886 			return (result);
    887 		cg++;
    888 		if (cg == fs->fs_ncg)
    889 			cg = 0;
    890 	}
    891 	return (0);
    892 }
    893 
    894 /*
    895  * Determine whether a fragment can be extended.
    896  *
    897  * Check to see if the necessary fragments are available, and
    898  * if they are, allocate them.
    899  */
    900 static ufs_daddr_t
    901 ffs_fragextend(ip, cg, bprev, osize, nsize)
    902 	struct inode *ip;
    903 	int cg;
    904 	long bprev;
    905 	int osize, nsize;
    906 {
    907 	struct fs *fs;
    908 	struct cg *cgp;
    909 	struct buf *bp;
    910 	long bno;
    911 	int frags, bbase;
    912 	int i, error;
    913 
    914 	fs = ip->i_fs;
    915 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
    916 		return (0);
    917 	frags = numfrags(fs, nsize);
    918 	bbase = fragnum(fs, bprev);
    919 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
    920 		/* cannot extend across a block boundary */
    921 		return (0);
    922 	}
    923 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
    924 		(int)fs->fs_cgsize, NOCRED, &bp);
    925 	if (error) {
    926 		brelse(bp);
    927 		return (0);
    928 	}
    929 	cgp = (struct cg *)bp->b_data;
    930 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs))) {
    931 		brelse(bp);
    932 		return (0);
    933 	}
    934 	cgp->cg_time = ufs_rw32(time.tv_sec, UFS_FSNEEDSWAP(fs));
    935 	bno = dtogd(fs, bprev);
    936 	for (i = numfrags(fs, osize); i < frags; i++)
    937 		if (isclr(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i)) {
    938 			brelse(bp);
    939 			return (0);
    940 		}
    941 	/*
    942 	 * the current fragment can be extended
    943 	 * deduct the count on fragment being extended into
    944 	 * increase the count on the remaining fragment (if any)
    945 	 * allocate the extended piece
    946 	 */
    947 	for (i = frags; i < fs->fs_frag - bbase; i++)
    948 		if (isclr(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i))
    949 			break;
    950 	ufs_add32(cgp->cg_frsum[i - numfrags(fs, osize)], -1, UFS_FSNEEDSWAP(fs));
    951 	if (i != frags)
    952 		ufs_add32(cgp->cg_frsum[i - frags], 1, UFS_FSNEEDSWAP(fs));
    953 	for (i = numfrags(fs, osize); i < frags; i++) {
    954 		clrbit(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i);
    955 		ufs_add32(cgp->cg_cs.cs_nffree, -1, UFS_FSNEEDSWAP(fs));
    956 		fs->fs_cstotal.cs_nffree--;
    957 		fs->fs_cs(fs, cg).cs_nffree--;
    958 	}
    959 	fs->fs_fmod = 1;
    960 	if (DOINGSOFTDEP(ITOV(ip)))
    961 		softdep_setup_blkmapdep(bp, fs, bprev);
    962 	bdwrite(bp);
    963 	return (bprev);
    964 }
    965 
    966 /*
    967  * Determine whether a block can be allocated.
    968  *
    969  * Check to see if a block of the appropriate size is available,
    970  * and if it is, allocate it.
    971  */
    972 static ufs_daddr_t
    973 ffs_alloccg(ip, cg, bpref, size)
    974 	struct inode *ip;
    975 	int cg;
    976 	ufs_daddr_t bpref;
    977 	int size;
    978 {
    979 	struct cg *cgp;
    980 	struct buf *bp;
    981 	ufs_daddr_t bno, blkno;
    982 	int error, frags, allocsiz, i;
    983 	struct fs *fs = ip->i_fs;
    984 #ifdef FFS_EI
    985 	const int needswap = UFS_FSNEEDSWAP(fs);
    986 #endif
    987 
    988 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
    989 		return (0);
    990 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
    991 		(int)fs->fs_cgsize, NOCRED, &bp);
    992 	if (error) {
    993 		brelse(bp);
    994 		return (0);
    995 	}
    996 	cgp = (struct cg *)bp->b_data;
    997 	if (!cg_chkmagic(cgp, needswap) ||
    998 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize)) {
    999 		brelse(bp);
   1000 		return (0);
   1001 	}
   1002 	cgp->cg_time = ufs_rw32(time.tv_sec, needswap);
   1003 	if (size == fs->fs_bsize) {
   1004 		bno = ffs_alloccgblk(ip, bp, bpref);
   1005 		bdwrite(bp);
   1006 		return (bno);
   1007 	}
   1008 	/*
   1009 	 * check to see if any fragments are already available
   1010 	 * allocsiz is the size which will be allocated, hacking
   1011 	 * it down to a smaller size if necessary
   1012 	 */
   1013 	frags = numfrags(fs, size);
   1014 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
   1015 		if (cgp->cg_frsum[allocsiz] != 0)
   1016 			break;
   1017 	if (allocsiz == fs->fs_frag) {
   1018 		/*
   1019 		 * no fragments were available, so a block will be
   1020 		 * allocated, and hacked up
   1021 		 */
   1022 		if (cgp->cg_cs.cs_nbfree == 0) {
   1023 			brelse(bp);
   1024 			return (0);
   1025 		}
   1026 		bno = ffs_alloccgblk(ip, bp, bpref);
   1027 		bpref = dtogd(fs, bno);
   1028 		for (i = frags; i < fs->fs_frag; i++)
   1029 			setbit(cg_blksfree(cgp, needswap), bpref + i);
   1030 		i = fs->fs_frag - frags;
   1031 		ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
   1032 		fs->fs_cstotal.cs_nffree += i;
   1033 		fs->fs_cs(fs, cg).cs_nffree += i;
   1034 		fs->fs_fmod = 1;
   1035 		ufs_add32(cgp->cg_frsum[i], 1, needswap);
   1036 		bdwrite(bp);
   1037 		return (bno);
   1038 	}
   1039 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
   1040 #if 0
   1041 	/*
   1042 	 * XXX fvdl mapsearch will panic, and never return -1
   1043 	 *          also: returning NULL as ufs_daddr_t ?
   1044 	 */
   1045 	if (bno < 0) {
   1046 		brelse(bp);
   1047 		return (0);
   1048 	}
   1049 #endif
   1050 	for (i = 0; i < frags; i++)
   1051 		clrbit(cg_blksfree(cgp, needswap), bno + i);
   1052 	ufs_add32(cgp->cg_cs.cs_nffree, -frags, needswap);
   1053 	fs->fs_cstotal.cs_nffree -= frags;
   1054 	fs->fs_cs(fs, cg).cs_nffree -= frags;
   1055 	fs->fs_fmod = 1;
   1056 	ufs_add32(cgp->cg_frsum[allocsiz], -1, needswap);
   1057 	if (frags != allocsiz)
   1058 		ufs_add32(cgp->cg_frsum[allocsiz - frags], 1, needswap);
   1059 	blkno = cg * fs->fs_fpg + bno;
   1060 	if (DOINGSOFTDEP(ITOV(ip)))
   1061 		softdep_setup_blkmapdep(bp, fs, blkno);
   1062 	bdwrite(bp);
   1063 	return blkno;
   1064 }
   1065 
   1066 /*
   1067  * Allocate a block in a cylinder group.
   1068  *
   1069  * This algorithm implements the following policy:
   1070  *   1) allocate the requested block.
   1071  *   2) allocate a rotationally optimal block in the same cylinder.
   1072  *   3) allocate the next available block on the block rotor for the
   1073  *      specified cylinder group.
   1074  * Note that this routine only allocates fs_bsize blocks; these
   1075  * blocks may be fragmented by the routine that allocates them.
   1076  */
   1077 static ufs_daddr_t
   1078 ffs_alloccgblk(ip, bp, bpref)
   1079 	struct inode *ip;
   1080 	struct buf *bp;
   1081 	ufs_daddr_t bpref;
   1082 {
   1083 	struct cg *cgp;
   1084 	ufs_daddr_t bno, blkno;
   1085 	int cylno, pos, delta;
   1086 	short *cylbp;
   1087 	int i;
   1088 	struct fs *fs = ip->i_fs;
   1089 #ifdef FFS_EI
   1090 	const int needswap = UFS_FSNEEDSWAP(fs);
   1091 #endif
   1092 
   1093 	cgp = (struct cg *)bp->b_data;
   1094 	if (bpref == 0 || dtog(fs, bpref) != ufs_rw32(cgp->cg_cgx, needswap)) {
   1095 		bpref = ufs_rw32(cgp->cg_rotor, needswap);
   1096 		goto norot;
   1097 	}
   1098 	bpref = blknum(fs, bpref);
   1099 	bpref = dtogd(fs, bpref);
   1100 	/*
   1101 	 * if the requested block is available, use it
   1102 	 */
   1103 	if (ffs_isblock(fs, cg_blksfree(cgp, needswap),
   1104 		fragstoblks(fs, bpref))) {
   1105 		bno = bpref;
   1106 		goto gotit;
   1107 	}
   1108 	if (fs->fs_nrpos <= 1 || fs->fs_cpc == 0) {
   1109 		/*
   1110 		 * Block layout information is not available.
   1111 		 * Leaving bpref unchanged means we take the
   1112 		 * next available free block following the one
   1113 		 * we just allocated. Hopefully this will at
   1114 		 * least hit a track cache on drives of unknown
   1115 		 * geometry (e.g. SCSI).
   1116 		 */
   1117 		goto norot;
   1118 	}
   1119 	/*
   1120 	 * check for a block available on the same cylinder
   1121 	 */
   1122 	cylno = cbtocylno(fs, bpref);
   1123 	if (cg_blktot(cgp, needswap)[cylno] == 0)
   1124 		goto norot;
   1125 	/*
   1126 	 * check the summary information to see if a block is
   1127 	 * available in the requested cylinder starting at the
   1128 	 * requested rotational position and proceeding around.
   1129 	 */
   1130 	cylbp = cg_blks(fs, cgp, cylno, needswap);
   1131 	pos = cbtorpos(fs, bpref);
   1132 	for (i = pos; i < fs->fs_nrpos; i++)
   1133 		if (ufs_rw16(cylbp[i], needswap) > 0)
   1134 			break;
   1135 	if (i == fs->fs_nrpos)
   1136 		for (i = 0; i < pos; i++)
   1137 			if (ufs_rw16(cylbp[i], needswap) > 0)
   1138 				break;
   1139 	if (ufs_rw16(cylbp[i], needswap) > 0) {
   1140 		/*
   1141 		 * found a rotational position, now find the actual
   1142 		 * block. A panic if none is actually there.
   1143 		 */
   1144 		pos = cylno % fs->fs_cpc;
   1145 		bno = (cylno - pos) * fs->fs_spc / NSPB(fs);
   1146 		if (fs_postbl(fs, pos)[i] == -1) {
   1147 			printf("pos = %d, i = %d, fs = %s\n",
   1148 			    pos, i, fs->fs_fsmnt);
   1149 			panic("ffs_alloccgblk: cyl groups corrupted");
   1150 		}
   1151 		for (i = fs_postbl(fs, pos)[i];; ) {
   1152 			if (ffs_isblock(fs, cg_blksfree(cgp, needswap), bno + i)) {
   1153 				bno = blkstofrags(fs, (bno + i));
   1154 				goto gotit;
   1155 			}
   1156 			delta = fs_rotbl(fs)[i];
   1157 			if (delta <= 0 ||
   1158 			    delta + i > fragstoblks(fs, fs->fs_fpg))
   1159 				break;
   1160 			i += delta;
   1161 		}
   1162 		printf("pos = %d, i = %d, fs = %s\n", pos, i, fs->fs_fsmnt);
   1163 		panic("ffs_alloccgblk: can't find blk in cyl");
   1164 	}
   1165 norot:
   1166 	/*
   1167 	 * no blocks in the requested cylinder, so take next
   1168 	 * available one in this cylinder group.
   1169 	 */
   1170 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
   1171 	if (bno < 0)
   1172 		return (0);
   1173 	cgp->cg_rotor = ufs_rw32(bno, needswap);
   1174 gotit:
   1175 	blkno = fragstoblks(fs, bno);
   1176 	ffs_clrblock(fs, cg_blksfree(cgp, needswap), (long)blkno);
   1177 	ffs_clusteracct(fs, cgp, blkno, -1);
   1178 	ufs_add32(cgp->cg_cs.cs_nbfree, -1, needswap);
   1179 	fs->fs_cstotal.cs_nbfree--;
   1180 	fs->fs_cs(fs, ufs_rw32(cgp->cg_cgx, needswap)).cs_nbfree--;
   1181 	cylno = cbtocylno(fs, bno);
   1182 	ufs_add16(cg_blks(fs, cgp, cylno, needswap)[cbtorpos(fs, bno)], -1,
   1183 	    needswap);
   1184 	ufs_add32(cg_blktot(cgp, needswap)[cylno], -1, needswap);
   1185 	fs->fs_fmod = 1;
   1186 	blkno = ufs_rw32(cgp->cg_cgx, needswap) * fs->fs_fpg + bno;
   1187 	if (DOINGSOFTDEP(ITOV(ip)))
   1188 		softdep_setup_blkmapdep(bp, fs, blkno);
   1189 	return (blkno);
   1190 }
   1191 
   1192 /*
   1193  * Determine whether a cluster can be allocated.
   1194  *
   1195  * We do not currently check for optimal rotational layout if there
   1196  * are multiple choices in the same cylinder group. Instead we just
   1197  * take the first one that we find following bpref.
   1198  */
   1199 static ufs_daddr_t
   1200 ffs_clusteralloc(ip, cg, bpref, len)
   1201 	struct inode *ip;
   1202 	int cg;
   1203 	ufs_daddr_t bpref;
   1204 	int len;
   1205 {
   1206 	struct fs *fs;
   1207 	struct cg *cgp;
   1208 	struct buf *bp;
   1209 	int i, got, run, bno, bit, map;
   1210 	u_char *mapp;
   1211 	int32_t *lp;
   1212 
   1213 	fs = ip->i_fs;
   1214 	if (fs->fs_maxcluster[cg] < len)
   1215 		return (0);
   1216 	if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize,
   1217 	    NOCRED, &bp))
   1218 		goto fail;
   1219 	cgp = (struct cg *)bp->b_data;
   1220 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs)))
   1221 		goto fail;
   1222 	/*
   1223 	 * Check to see if a cluster of the needed size (or bigger) is
   1224 	 * available in this cylinder group.
   1225 	 */
   1226 	lp = &cg_clustersum(cgp, UFS_FSNEEDSWAP(fs))[len];
   1227 	for (i = len; i <= fs->fs_contigsumsize; i++)
   1228 		if (ufs_rw32(*lp++, UFS_FSNEEDSWAP(fs)) > 0)
   1229 			break;
   1230 	if (i > fs->fs_contigsumsize) {
   1231 		/*
   1232 		 * This is the first time looking for a cluster in this
   1233 		 * cylinder group. Update the cluster summary information
   1234 		 * to reflect the true maximum sized cluster so that
   1235 		 * future cluster allocation requests can avoid reading
   1236 		 * the cylinder group map only to find no clusters.
   1237 		 */
   1238 		lp = &cg_clustersum(cgp, UFS_FSNEEDSWAP(fs))[len - 1];
   1239 		for (i = len - 1; i > 0; i--)
   1240 			if (ufs_rw32(*lp--, UFS_FSNEEDSWAP(fs)) > 0)
   1241 				break;
   1242 		fs->fs_maxcluster[cg] = i;
   1243 		goto fail;
   1244 	}
   1245 	/*
   1246 	 * Search the cluster map to find a big enough cluster.
   1247 	 * We take the first one that we find, even if it is larger
   1248 	 * than we need as we prefer to get one close to the previous
   1249 	 * block allocation. We do not search before the current
   1250 	 * preference point as we do not want to allocate a block
   1251 	 * that is allocated before the previous one (as we will
   1252 	 * then have to wait for another pass of the elevator
   1253 	 * algorithm before it will be read). We prefer to fail and
   1254 	 * be recalled to try an allocation in the next cylinder group.
   1255 	 */
   1256 	if (dtog(fs, bpref) != cg)
   1257 		bpref = 0;
   1258 	else
   1259 		bpref = fragstoblks(fs, dtogd(fs, blknum(fs, bpref)));
   1260 	mapp = &cg_clustersfree(cgp, UFS_FSNEEDSWAP(fs))[bpref / NBBY];
   1261 	map = *mapp++;
   1262 	bit = 1 << (bpref % NBBY);
   1263 	for (run = 0, got = bpref;
   1264 		got < ufs_rw32(cgp->cg_nclusterblks, UFS_FSNEEDSWAP(fs)); got++) {
   1265 		if ((map & bit) == 0) {
   1266 			run = 0;
   1267 		} else {
   1268 			run++;
   1269 			if (run == len)
   1270 				break;
   1271 		}
   1272 		if ((got & (NBBY - 1)) != (NBBY - 1)) {
   1273 			bit <<= 1;
   1274 		} else {
   1275 			map = *mapp++;
   1276 			bit = 1;
   1277 		}
   1278 	}
   1279 	if (got == ufs_rw32(cgp->cg_nclusterblks, UFS_FSNEEDSWAP(fs)))
   1280 		goto fail;
   1281 	/*
   1282 	 * Allocate the cluster that we have found.
   1283 	 */
   1284 #ifdef DIAGNOSTIC
   1285 	for (i = 1; i <= len; i++)
   1286 		if (!ffs_isblock(fs, cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)),
   1287 		    got - run + i))
   1288 			panic("ffs_clusteralloc: map mismatch");
   1289 #endif
   1290 	bno = cg * fs->fs_fpg + blkstofrags(fs, got - run + 1);
   1291 	if (dtog(fs, bno) != cg)
   1292 		panic("ffs_clusteralloc: allocated out of group");
   1293 	len = blkstofrags(fs, len);
   1294 	for (i = 0; i < len; i += fs->fs_frag)
   1295 		if ((got = ffs_alloccgblk(ip, bp, bno + i)) != bno + i)
   1296 			panic("ffs_clusteralloc: lost block");
   1297 	bdwrite(bp);
   1298 	return (bno);
   1299 
   1300 fail:
   1301 	brelse(bp);
   1302 	return (0);
   1303 }
   1304 
   1305 /*
   1306  * Determine whether an inode can be allocated.
   1307  *
   1308  * Check to see if an inode is available, and if it is,
   1309  * allocate it using the following policy:
   1310  *   1) allocate the requested inode.
   1311  *   2) allocate the next available inode after the requested
   1312  *      inode in the specified cylinder group.
   1313  */
   1314 static ufs_daddr_t
   1315 ffs_nodealloccg(ip, cg, ipref, mode)
   1316 	struct inode *ip;
   1317 	int cg;
   1318 	ufs_daddr_t ipref;
   1319 	int mode;
   1320 {
   1321 	struct cg *cgp;
   1322 	struct buf *bp;
   1323 	int error, start, len, loc, map, i;
   1324 	struct fs *fs = ip->i_fs;
   1325 #ifdef FFS_EI
   1326 	const int needswap = UFS_FSNEEDSWAP(fs);
   1327 #endif
   1328 
   1329 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
   1330 		return (0);
   1331 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1332 		(int)fs->fs_cgsize, NOCRED, &bp);
   1333 	if (error) {
   1334 		brelse(bp);
   1335 		return (0);
   1336 	}
   1337 	cgp = (struct cg *)bp->b_data;
   1338 	if (!cg_chkmagic(cgp, needswap) || cgp->cg_cs.cs_nifree == 0) {
   1339 		brelse(bp);
   1340 		return (0);
   1341 	}
   1342 	cgp->cg_time = ufs_rw32(time.tv_sec, needswap);
   1343 	if (ipref) {
   1344 		ipref %= fs->fs_ipg;
   1345 		if (isclr(cg_inosused(cgp, needswap), ipref))
   1346 			goto gotit;
   1347 	}
   1348 	start = ufs_rw32(cgp->cg_irotor, needswap) / NBBY;
   1349 	len = howmany(fs->fs_ipg - ufs_rw32(cgp->cg_irotor, needswap),
   1350 		NBBY);
   1351 	loc = skpc(0xff, len, &cg_inosused(cgp, needswap)[start]);
   1352 	if (loc == 0) {
   1353 		len = start + 1;
   1354 		start = 0;
   1355 		loc = skpc(0xff, len, &cg_inosused(cgp, needswap)[0]);
   1356 		if (loc == 0) {
   1357 			printf("cg = %d, irotor = %d, fs = %s\n",
   1358 			    cg, ufs_rw32(cgp->cg_irotor, needswap),
   1359 				fs->fs_fsmnt);
   1360 			panic("ffs_nodealloccg: map corrupted");
   1361 			/* NOTREACHED */
   1362 		}
   1363 	}
   1364 	i = start + len - loc;
   1365 	map = cg_inosused(cgp, needswap)[i];
   1366 	ipref = i * NBBY;
   1367 	for (i = 1; i < (1 << NBBY); i <<= 1, ipref++) {
   1368 		if ((map & i) == 0) {
   1369 			cgp->cg_irotor = ufs_rw32(ipref, needswap);
   1370 			goto gotit;
   1371 		}
   1372 	}
   1373 	printf("fs = %s\n", fs->fs_fsmnt);
   1374 	panic("ffs_nodealloccg: block not in map");
   1375 	/* NOTREACHED */
   1376 gotit:
   1377 	if (DOINGSOFTDEP(ITOV(ip)))
   1378 		softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref);
   1379 	setbit(cg_inosused(cgp, needswap), ipref);
   1380 	ufs_add32(cgp->cg_cs.cs_nifree, -1, needswap);
   1381 	fs->fs_cstotal.cs_nifree--;
   1382 	fs->fs_cs(fs, cg).cs_nifree--;
   1383 	fs->fs_fmod = 1;
   1384 	if ((mode & IFMT) == IFDIR) {
   1385 		ufs_add32(cgp->cg_cs.cs_ndir, 1, needswap);
   1386 		fs->fs_cstotal.cs_ndir++;
   1387 		fs->fs_cs(fs, cg).cs_ndir++;
   1388 	}
   1389 	bdwrite(bp);
   1390 	return (cg * fs->fs_ipg + ipref);
   1391 }
   1392 
   1393 /*
   1394  * Free a block or fragment.
   1395  *
   1396  * The specified block or fragment is placed back in the
   1397  * free map. If a fragment is deallocated, a possible
   1398  * block reassembly is checked.
   1399  */
   1400 void
   1401 ffs_blkfree(ip, bno, size)
   1402 	struct inode *ip;
   1403 	ufs_daddr_t bno;
   1404 	long size;
   1405 {
   1406 	struct cg *cgp;
   1407 	struct buf *bp;
   1408 	ufs_daddr_t blkno;
   1409 	int i, error, cg, blk, frags, bbase;
   1410 	struct fs *fs = ip->i_fs;
   1411 	const int needswap = UFS_FSNEEDSWAP(fs);
   1412 
   1413 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
   1414 	    fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
   1415 		printf("dev = 0x%x, bno = %u bsize = %d, size = %ld, fs = %s\n",
   1416 		    ip->i_dev, bno, fs->fs_bsize, size, fs->fs_fsmnt);
   1417 		panic("blkfree: bad size");
   1418 	}
   1419 	cg = dtog(fs, bno);
   1420 	if ((u_int)bno >= fs->fs_size) {
   1421 		printf("bad block %d, ino %d\n", bno, ip->i_number);
   1422 		ffs_fserr(fs, ip->i_ffs_uid, "bad block");
   1423 		return;
   1424 	}
   1425 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1426 		(int)fs->fs_cgsize, NOCRED, &bp);
   1427 	if (error) {
   1428 		brelse(bp);
   1429 		return;
   1430 	}
   1431 	cgp = (struct cg *)bp->b_data;
   1432 	if (!cg_chkmagic(cgp, needswap)) {
   1433 		brelse(bp);
   1434 		return;
   1435 	}
   1436 	cgp->cg_time = ufs_rw32(time.tv_sec, needswap);
   1437 	bno = dtogd(fs, bno);
   1438 	if (size == fs->fs_bsize) {
   1439 		blkno = fragstoblks(fs, bno);
   1440 		if (!ffs_isfreeblock(fs, cg_blksfree(cgp, needswap), blkno)) {
   1441 			printf("dev = 0x%x, block = %d, fs = %s\n",
   1442 			    ip->i_dev, bno, fs->fs_fsmnt);
   1443 			panic("blkfree: freeing free block");
   1444 		}
   1445 		ffs_setblock(fs, cg_blksfree(cgp, needswap), blkno);
   1446 		ffs_clusteracct(fs, cgp, blkno, 1);
   1447 		ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
   1448 		fs->fs_cstotal.cs_nbfree++;
   1449 		fs->fs_cs(fs, cg).cs_nbfree++;
   1450 		i = cbtocylno(fs, bno);
   1451 		ufs_add16(cg_blks(fs, cgp, i, needswap)[cbtorpos(fs, bno)], 1,
   1452 		    needswap);
   1453 		ufs_add32(cg_blktot(cgp, needswap)[i], 1, needswap);
   1454 	} else {
   1455 		bbase = bno - fragnum(fs, bno);
   1456 		/*
   1457 		 * decrement the counts associated with the old frags
   1458 		 */
   1459 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bbase);
   1460 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1, needswap);
   1461 		/*
   1462 		 * deallocate the fragment
   1463 		 */
   1464 		frags = numfrags(fs, size);
   1465 		for (i = 0; i < frags; i++) {
   1466 			if (isset(cg_blksfree(cgp, needswap), bno + i)) {
   1467 				printf("dev = 0x%x, block = %d, fs = %s\n",
   1468 				    ip->i_dev, bno + i, fs->fs_fsmnt);
   1469 				panic("blkfree: freeing free frag");
   1470 			}
   1471 			setbit(cg_blksfree(cgp, needswap), bno + i);
   1472 		}
   1473 		ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
   1474 		fs->fs_cstotal.cs_nffree += i;
   1475 		fs->fs_cs(fs, cg).cs_nffree += i;
   1476 		/*
   1477 		 * add back in counts associated with the new frags
   1478 		 */
   1479 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bbase);
   1480 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1, needswap);
   1481 		/*
   1482 		 * if a complete block has been reassembled, account for it
   1483 		 */
   1484 		blkno = fragstoblks(fs, bbase);
   1485 		if (ffs_isblock(fs, cg_blksfree(cgp, needswap), blkno)) {
   1486 			ufs_add32(cgp->cg_cs.cs_nffree, -fs->fs_frag, needswap);
   1487 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
   1488 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
   1489 			ffs_clusteracct(fs, cgp, blkno, 1);
   1490 			ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
   1491 			fs->fs_cstotal.cs_nbfree++;
   1492 			fs->fs_cs(fs, cg).cs_nbfree++;
   1493 			i = cbtocylno(fs, bbase);
   1494 			ufs_add16(cg_blks(fs, cgp, i, needswap)[cbtorpos(fs,
   1495 								bbase)], 1,
   1496 			    needswap);
   1497 			ufs_add32(cg_blktot(cgp, needswap)[i], 1, needswap);
   1498 		}
   1499 	}
   1500 	fs->fs_fmod = 1;
   1501 	bdwrite(bp);
   1502 }
   1503 
   1504 #if defined(DIAGNOSTIC) || defined(DEBUG)
   1505 /*
   1506  * Verify allocation of a block or fragment. Returns true if block or
   1507  * fragment is allocated, false if it is free.
   1508  */
   1509 static int
   1510 ffs_checkblk(ip, bno, size)
   1511 	struct inode *ip;
   1512 	ufs_daddr_t bno;
   1513 	long size;
   1514 {
   1515 	struct fs *fs;
   1516 	struct cg *cgp;
   1517 	struct buf *bp;
   1518 	int i, error, frags, free;
   1519 
   1520 	fs = ip->i_fs;
   1521 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
   1522 		printf("bsize = %d, size = %ld, fs = %s\n",
   1523 		    fs->fs_bsize, size, fs->fs_fsmnt);
   1524 		panic("checkblk: bad size");
   1525 	}
   1526 	if ((u_int)bno >= fs->fs_size)
   1527 		panic("checkblk: bad block %d", bno);
   1528 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, dtog(fs, bno))),
   1529 		(int)fs->fs_cgsize, NOCRED, &bp);
   1530 	if (error) {
   1531 		brelse(bp);
   1532 		return 0;
   1533 	}
   1534 	cgp = (struct cg *)bp->b_data;
   1535 	if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs))) {
   1536 		brelse(bp);
   1537 		return 0;
   1538 	}
   1539 	bno = dtogd(fs, bno);
   1540 	if (size == fs->fs_bsize) {
   1541 		free = ffs_isblock(fs, cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)),
   1542 			fragstoblks(fs, bno));
   1543 	} else {
   1544 		frags = numfrags(fs, size);
   1545 		for (free = 0, i = 0; i < frags; i++)
   1546 			if (isset(cg_blksfree(cgp, UFS_FSNEEDSWAP(fs)), bno + i))
   1547 				free++;
   1548 		if (free != 0 && free != frags)
   1549 			panic("checkblk: partially free fragment");
   1550 	}
   1551 	brelse(bp);
   1552 	return (!free);
   1553 }
   1554 #endif /* DIAGNOSTIC */
   1555 
   1556 /*
   1557  * Free an inode.
   1558  */
   1559 int
   1560 ffs_vfree(v)
   1561 	void *v;
   1562 {
   1563 	struct vop_vfree_args /* {
   1564 		struct vnode *a_pvp;
   1565 		ino_t a_ino;
   1566 		int a_mode;
   1567 	} */ *ap = v;
   1568 
   1569 	if (DOINGSOFTDEP(ap->a_pvp)) {
   1570 		softdep_freefile(ap);
   1571 		return (0);
   1572 	}
   1573 	return (ffs_freefile(ap));
   1574 }
   1575 
   1576 /*
   1577  * Do the actual free operation.
   1578  * The specified inode is placed back in the free map.
   1579  */
   1580 int
   1581 ffs_freefile(v)
   1582 	void *v;
   1583 {
   1584 	struct vop_vfree_args /* {
   1585 		struct vnode *a_pvp;
   1586 		ino_t a_ino;
   1587 		int a_mode;
   1588 	} */ *ap = v;
   1589 	struct cg *cgp;
   1590 	struct inode *pip = VTOI(ap->a_pvp);
   1591 	struct fs *fs = pip->i_fs;
   1592 	ino_t ino = ap->a_ino;
   1593 	struct buf *bp;
   1594 	int error, cg;
   1595 #ifdef FFS_EI
   1596 	const int needswap = UFS_FSNEEDSWAP(fs);
   1597 #endif
   1598 
   1599 	if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
   1600 		panic("ifree: range: dev = 0x%x, ino = %d, fs = %s\n",
   1601 		    pip->i_dev, ino, fs->fs_fsmnt);
   1602 	cg = ino_to_cg(fs, ino);
   1603 	error = bread(pip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
   1604 		(int)fs->fs_cgsize, NOCRED, &bp);
   1605 	if (error) {
   1606 		brelse(bp);
   1607 		return (error);
   1608 	}
   1609 	cgp = (struct cg *)bp->b_data;
   1610 	if (!cg_chkmagic(cgp, needswap)) {
   1611 		brelse(bp);
   1612 		return (0);
   1613 	}
   1614 	cgp->cg_time = ufs_rw32(time.tv_sec, needswap);
   1615 	ino %= fs->fs_ipg;
   1616 	if (isclr(cg_inosused(cgp, needswap), ino)) {
   1617 		printf("dev = 0x%x, ino = %d, fs = %s\n",
   1618 		    pip->i_dev, ino, fs->fs_fsmnt);
   1619 		if (fs->fs_ronly == 0)
   1620 			panic("ifree: freeing free inode");
   1621 	}
   1622 	clrbit(cg_inosused(cgp, needswap), ino);
   1623 	if (ino < ufs_rw32(cgp->cg_irotor, needswap))
   1624 		cgp->cg_irotor = ufs_rw32(ino, needswap);
   1625 	ufs_add32(cgp->cg_cs.cs_nifree, 1, needswap);
   1626 	fs->fs_cstotal.cs_nifree++;
   1627 	fs->fs_cs(fs, cg).cs_nifree++;
   1628 	if ((ap->a_mode & IFMT) == IFDIR) {
   1629 		ufs_add32(cgp->cg_cs.cs_ndir, -1, needswap);
   1630 		fs->fs_cstotal.cs_ndir--;
   1631 		fs->fs_cs(fs, cg).cs_ndir--;
   1632 	}
   1633 	fs->fs_fmod = 1;
   1634 	bdwrite(bp);
   1635 	return (0);
   1636 }
   1637 
   1638 /*
   1639  * Find a block of the specified size in the specified cylinder group.
   1640  *
   1641  * It is a panic if a request is made to find a block if none are
   1642  * available.
   1643  */
   1644 static ufs_daddr_t
   1645 ffs_mapsearch(fs, cgp, bpref, allocsiz)
   1646 	struct fs *fs;
   1647 	struct cg *cgp;
   1648 	ufs_daddr_t bpref;
   1649 	int allocsiz;
   1650 {
   1651 	ufs_daddr_t bno;
   1652 	int start, len, loc, i;
   1653 	int blk, field, subfield, pos;
   1654 	int ostart, olen;
   1655 #ifdef FFS_EI
   1656 	const int needswap = UFS_FSNEEDSWAP(fs);
   1657 #endif
   1658 
   1659 	/*
   1660 	 * find the fragment by searching through the free block
   1661 	 * map for an appropriate bit pattern
   1662 	 */
   1663 	if (bpref)
   1664 		start = dtogd(fs, bpref) / NBBY;
   1665 	else
   1666 		start = ufs_rw32(cgp->cg_frotor, needswap) / NBBY;
   1667 	len = howmany(fs->fs_fpg, NBBY) - start;
   1668 	ostart = start;
   1669 	olen = len;
   1670 	loc = scanc((u_int)len,
   1671 		(const u_char *)&cg_blksfree(cgp, needswap)[start],
   1672 		(const u_char *)fragtbl[fs->fs_frag],
   1673 		(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
   1674 	if (loc == 0) {
   1675 		len = start + 1;
   1676 		start = 0;
   1677 		loc = scanc((u_int)len,
   1678 			(const u_char *)&cg_blksfree(cgp, needswap)[0],
   1679 			(const u_char *)fragtbl[fs->fs_frag],
   1680 			(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
   1681 		if (loc == 0) {
   1682 			printf("start = %d, len = %d, fs = %s\n",
   1683 			    ostart, olen, fs->fs_fsmnt);
   1684 			printf("offset=%d %ld\n",
   1685 				ufs_rw32(cgp->cg_freeoff, needswap),
   1686 				(long)cg_blksfree(cgp, needswap) - (long)cgp);
   1687 			panic("ffs_alloccg: map corrupted");
   1688 			/* NOTREACHED */
   1689 		}
   1690 	}
   1691 	bno = (start + len - loc) * NBBY;
   1692 	cgp->cg_frotor = ufs_rw32(bno, needswap);
   1693 	/*
   1694 	 * found the byte in the map
   1695 	 * sift through the bits to find the selected frag
   1696 	 */
   1697 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
   1698 		blk = blkmap(fs, cg_blksfree(cgp, needswap), bno);
   1699 		blk <<= 1;
   1700 		field = around[allocsiz];
   1701 		subfield = inside[allocsiz];
   1702 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
   1703 			if ((blk & field) == subfield)
   1704 				return (bno + pos);
   1705 			field <<= 1;
   1706 			subfield <<= 1;
   1707 		}
   1708 	}
   1709 	printf("bno = %d, fs = %s\n", bno, fs->fs_fsmnt);
   1710 	panic("ffs_alloccg: block not in map");
   1711 	return (-1);
   1712 }
   1713 
   1714 /*
   1715  * Update the cluster map because of an allocation or free.
   1716  *
   1717  * Cnt == 1 means free; cnt == -1 means allocating.
   1718  */
   1719 void
   1720 ffs_clusteracct(fs, cgp, blkno, cnt)
   1721 	struct fs *fs;
   1722 	struct cg *cgp;
   1723 	ufs_daddr_t blkno;
   1724 	int cnt;
   1725 {
   1726 	int32_t *sump;
   1727 	int32_t *lp;
   1728 	u_char *freemapp, *mapp;
   1729 	int i, start, end, forw, back, map, bit;
   1730 #ifdef FFS_EI
   1731 	const int needswap = UFS_FSNEEDSWAP(fs);
   1732 #endif
   1733 
   1734 	if (fs->fs_contigsumsize <= 0)
   1735 		return;
   1736 	freemapp = cg_clustersfree(cgp, needswap);
   1737 	sump = cg_clustersum(cgp, needswap);
   1738 	/*
   1739 	 * Allocate or clear the actual block.
   1740 	 */
   1741 	if (cnt > 0)
   1742 		setbit(freemapp, blkno);
   1743 	else
   1744 		clrbit(freemapp, blkno);
   1745 	/*
   1746 	 * Find the size of the cluster going forward.
   1747 	 */
   1748 	start = blkno + 1;
   1749 	end = start + fs->fs_contigsumsize;
   1750 	if (end >= ufs_rw32(cgp->cg_nclusterblks, needswap))
   1751 		end = ufs_rw32(cgp->cg_nclusterblks, needswap);
   1752 	mapp = &freemapp[start / NBBY];
   1753 	map = *mapp++;
   1754 	bit = 1 << (start % NBBY);
   1755 	for (i = start; i < end; i++) {
   1756 		if ((map & bit) == 0)
   1757 			break;
   1758 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
   1759 			bit <<= 1;
   1760 		} else {
   1761 			map = *mapp++;
   1762 			bit = 1;
   1763 		}
   1764 	}
   1765 	forw = i - start;
   1766 	/*
   1767 	 * Find the size of the cluster going backward.
   1768 	 */
   1769 	start = blkno - 1;
   1770 	end = start - fs->fs_contigsumsize;
   1771 	if (end < 0)
   1772 		end = -1;
   1773 	mapp = &freemapp[start / NBBY];
   1774 	map = *mapp--;
   1775 	bit = 1 << (start % NBBY);
   1776 	for (i = start; i > end; i--) {
   1777 		if ((map & bit) == 0)
   1778 			break;
   1779 		if ((i & (NBBY - 1)) != 0) {
   1780 			bit >>= 1;
   1781 		} else {
   1782 			map = *mapp--;
   1783 			bit = 1 << (NBBY - 1);
   1784 		}
   1785 	}
   1786 	back = start - i;
   1787 	/*
   1788 	 * Account for old cluster and the possibly new forward and
   1789 	 * back clusters.
   1790 	 */
   1791 	i = back + forw + 1;
   1792 	if (i > fs->fs_contigsumsize)
   1793 		i = fs->fs_contigsumsize;
   1794 	ufs_add32(sump[i], cnt, needswap);
   1795 	if (back > 0)
   1796 		ufs_add32(sump[back], -cnt, needswap);
   1797 	if (forw > 0)
   1798 		ufs_add32(sump[forw], -cnt, needswap);
   1799 
   1800 	/*
   1801 	 * Update cluster summary information.
   1802 	 */
   1803 	lp = &sump[fs->fs_contigsumsize];
   1804 	for (i = fs->fs_contigsumsize; i > 0; i--)
   1805 		if (ufs_rw32(*lp--, needswap) > 0)
   1806 			break;
   1807 	fs->fs_maxcluster[ufs_rw32(cgp->cg_cgx, needswap)] = i;
   1808 }
   1809 
   1810 /*
   1811  * Fserr prints the name of a file system with an error diagnostic.
   1812  *
   1813  * The form of the error message is:
   1814  *	fs: error message
   1815  */
   1816 static void
   1817 ffs_fserr(fs, uid, cp)
   1818 	struct fs *fs;
   1819 	u_int uid;
   1820 	char *cp;
   1821 {
   1822 
   1823 	log(LOG_ERR, "uid %d comm %s on %s: %s\n",
   1824 	    uid, curproc->p_comm, fs->fs_fsmnt, cp);
   1825 }
   1826