xref: /csrg-svn/sys/ufs/ffs/ffs_alloc.c (revision 67871)
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  *
7  *	@(#)ffs_alloc.c	8.11 (Berkeley) 10/27/94
8  */
9 
10 #include <sys/param.h>
11 #include <sys/systm.h>
12 #include <sys/buf.h>
13 #include <sys/proc.h>
14 #include <sys/vnode.h>
15 #include <sys/mount.h>
16 #include <sys/kernel.h>
17 #include <sys/syslog.h>
18 
19 #include <vm/vm.h>
20 
21 #include <ufs/ufs/quota.h>
22 #include <ufs/ufs/inode.h>
23 
24 #include <ufs/ffs/fs.h>
25 #include <ufs/ffs/ffs_extern.h>
26 
27 extern u_long nextgennumber;
28 
29 static daddr_t	ffs_alloccg __P((struct inode *, int, daddr_t, int));
30 static daddr_t	ffs_alloccgblk __P((struct fs *, struct cg *, daddr_t));
31 static daddr_t	ffs_clusteralloc __P((struct inode *, int, daddr_t, int));
32 static ino_t	ffs_dirpref __P((struct fs *));
33 static daddr_t	ffs_fragextend __P((struct inode *, int, long, int, int));
34 static void	ffs_fserr __P((struct fs *, u_int, char *));
35 static u_long	ffs_hashalloc
36 		    __P((struct inode *, int, long, int, u_long (*)()));
37 static u_long	ffs_nodealloccg __P((struct inode *, int, daddr_t, int));
38 static daddr_t	ffs_mapsearch __P((struct fs *, struct cg *, daddr_t, int));
39 
40 /*
41  * Allocate a block in the file system.
42  *
43  * The size of the requested block is given, which must be some
44  * multiple of fs_fsize and <= fs_bsize.
45  * A preference may be optionally specified. If a preference is given
46  * the following hierarchy is used to allocate a block:
47  *   1) allocate the requested block.
48  *   2) allocate a rotationally optimal block in the same cylinder.
49  *   3) allocate a block in the same cylinder group.
50  *   4) quadradically rehash into other cylinder groups, until an
51  *      available block is located.
52  * If no block preference is given the following heirarchy is used
53  * to allocate a block:
54  *   1) allocate a block in the cylinder group that contains the
55  *      inode for the file.
56  *   2) quadradically rehash into other cylinder groups, until an
57  *      available block is located.
58  */
59 ffs_alloc(ip, lbn, bpref, size, cred, bnp)
60 	register struct inode *ip;
61 	daddr_t lbn, bpref;
62 	int size;
63 	struct ucred *cred;
64 	daddr_t *bnp;
65 {
66 	register struct fs *fs;
67 	daddr_t bno;
68 	int cg, error;
69 
70 	*bnp = 0;
71 	fs = ip->i_fs;
72 #ifdef DIAGNOSTIC
73 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
74 		printf("dev = 0x%x, bsize = %d, size = %d, fs = %s\n",
75 		    ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
76 		panic("ffs_alloc: bad size");
77 	}
78 	if (cred == NOCRED)
79 		panic("ffs_alloc: missing credential\n");
80 #endif /* DIAGNOSTIC */
81 	if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
82 		goto nospace;
83 	if (cred->cr_uid != 0 && freespace(fs, fs->fs_minfree) <= 0)
84 		goto nospace;
85 #ifdef QUOTA
86 	if (error = chkdq(ip, (long)btodb(size), cred, 0))
87 		return (error);
88 #endif
89 	if (bpref >= fs->fs_size)
90 		bpref = 0;
91 	if (bpref == 0)
92 		cg = ino_to_cg(fs, ip->i_number);
93 	else
94 		cg = dtog(fs, bpref);
95 	bno = (daddr_t)ffs_hashalloc(ip, cg, (long)bpref, size,
96 	    (u_long (*)())ffs_alloccg);
97 	if (bno > 0) {
98 		ip->i_blocks += btodb(size);
99 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
100 		*bnp = bno;
101 		return (0);
102 	}
103 #ifdef QUOTA
104 	/*
105 	 * Restore user's disk quota because allocation failed.
106 	 */
107 	(void) chkdq(ip, (long)-btodb(size), cred, FORCE);
108 #endif
109 nospace:
110 	ffs_fserr(fs, cred->cr_uid, "file system full");
111 	uprintf("\n%s: write failed, file system is full\n", fs->fs_fsmnt);
112 	return (ENOSPC);
113 }
114 
115 /*
116  * Reallocate a fragment to a bigger size
117  *
118  * The number and size of the old block is given, and a preference
119  * and new size is also specified. The allocator attempts to extend
120  * the original block. Failing that, the regular block allocator is
121  * invoked to get an appropriate block.
122  */
123 ffs_realloccg(ip, lbprev, bpref, osize, nsize, cred, bpp)
124 	register struct inode *ip;
125 	daddr_t lbprev;
126 	daddr_t bpref;
127 	int osize, nsize;
128 	struct ucred *cred;
129 	struct buf **bpp;
130 {
131 	register struct fs *fs;
132 	struct buf *bp;
133 	int cg, request, error;
134 	daddr_t bprev, bno;
135 
136 	*bpp = 0;
137 	fs = ip->i_fs;
138 #ifdef DIAGNOSTIC
139 	if ((u_int)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
140 	    (u_int)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
141 		printf(
142 		    "dev = 0x%x, bsize = %d, osize = %d, nsize = %d, fs = %s\n",
143 		    ip->i_dev, fs->fs_bsize, osize, nsize, fs->fs_fsmnt);
144 		panic("ffs_realloccg: bad size");
145 	}
146 	if (cred == NOCRED)
147 		panic("ffs_realloccg: missing credential\n");
148 #endif /* DIAGNOSTIC */
149 	if (cred->cr_uid != 0 && freespace(fs, fs->fs_minfree) <= 0)
150 		goto nospace;
151 	if ((bprev = ip->i_db[lbprev]) == 0) {
152 		printf("dev = 0x%x, bsize = %d, bprev = %d, fs = %s\n",
153 		    ip->i_dev, fs->fs_bsize, bprev, fs->fs_fsmnt);
154 		panic("ffs_realloccg: bad bprev");
155 	}
156 	/*
157 	 * Allocate the extra space in the buffer.
158 	 */
159 	if (error = bread(ITOV(ip), lbprev, osize, NOCRED, &bp)) {
160 		brelse(bp);
161 		return (error);
162 	}
163 #ifdef QUOTA
164 	if (error = chkdq(ip, (long)btodb(nsize - osize), cred, 0)) {
165 		brelse(bp);
166 		return (error);
167 	}
168 #endif
169 	/*
170 	 * Check for extension in the existing location.
171 	 */
172 	cg = dtog(fs, bprev);
173 	if (bno = ffs_fragextend(ip, cg, (long)bprev, osize, nsize)) {
174 		if (bp->b_blkno != fsbtodb(fs, bno))
175 			panic("bad blockno");
176 		ip->i_blocks += btodb(nsize - osize);
177 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
178 		allocbuf(bp, nsize);
179 		bp->b_flags |= B_DONE;
180 		bzero((char *)bp->b_data + osize, (u_int)nsize - osize);
181 		*bpp = bp;
182 		return (0);
183 	}
184 	/*
185 	 * Allocate a new disk location.
186 	 */
187 	if (bpref >= fs->fs_size)
188 		bpref = 0;
189 	switch ((int)fs->fs_optim) {
190 	case FS_OPTSPACE:
191 		/*
192 		 * Allocate an exact sized fragment. Although this makes
193 		 * best use of space, we will waste time relocating it if
194 		 * the file continues to grow. If the fragmentation is
195 		 * less than half of the minimum free reserve, we choose
196 		 * to begin optimizing for time.
197 		 */
198 		request = nsize;
199 		if (fs->fs_minfree < 5 ||
200 		    fs->fs_cstotal.cs_nffree >
201 		    fs->fs_dsize * fs->fs_minfree / (2 * 100))
202 			break;
203 		log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
204 			fs->fs_fsmnt);
205 		fs->fs_optim = FS_OPTTIME;
206 		break;
207 	case FS_OPTTIME:
208 		/*
209 		 * At this point we have discovered a file that is trying to
210 		 * grow a small fragment to a larger fragment. To save time,
211 		 * we allocate a full sized block, then free the unused portion.
212 		 * If the file continues to grow, the `ffs_fragextend' call
213 		 * above will be able to grow it in place without further
214 		 * copying. If aberrant programs cause disk fragmentation to
215 		 * grow within 2% of the free reserve, we choose to begin
216 		 * optimizing for space.
217 		 */
218 		request = fs->fs_bsize;
219 		if (fs->fs_cstotal.cs_nffree <
220 		    fs->fs_dsize * (fs->fs_minfree - 2) / 100)
221 			break;
222 		log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
223 			fs->fs_fsmnt);
224 		fs->fs_optim = FS_OPTSPACE;
225 		break;
226 	default:
227 		printf("dev = 0x%x, optim = %d, fs = %s\n",
228 		    ip->i_dev, fs->fs_optim, fs->fs_fsmnt);
229 		panic("ffs_realloccg: bad optim");
230 		/* NOTREACHED */
231 	}
232 	bno = (daddr_t)ffs_hashalloc(ip, cg, (long)bpref, request,
233 	    (u_long (*)())ffs_alloccg);
234 	if (bno > 0) {
235 		bp->b_blkno = fsbtodb(fs, bno);
236 		(void) vnode_pager_uncache(ITOV(ip));
237 		ffs_blkfree(ip, bprev, (long)osize);
238 		if (nsize < request)
239 			ffs_blkfree(ip, bno + numfrags(fs, nsize),
240 			    (long)(request - nsize));
241 		ip->i_blocks += btodb(nsize - osize);
242 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
243 		allocbuf(bp, nsize);
244 		bp->b_flags |= B_DONE;
245 		bzero((char *)bp->b_data + osize, (u_int)nsize - osize);
246 		*bpp = bp;
247 		return (0);
248 	}
249 #ifdef QUOTA
250 	/*
251 	 * Restore user's disk quota because allocation failed.
252 	 */
253 	(void) chkdq(ip, (long)-btodb(nsize - osize), cred, FORCE);
254 #endif
255 	brelse(bp);
256 nospace:
257 	/*
258 	 * no space available
259 	 */
260 	ffs_fserr(fs, cred->cr_uid, "file system full");
261 	uprintf("\n%s: write failed, file system is full\n", fs->fs_fsmnt);
262 	return (ENOSPC);
263 }
264 
265 /*
266  * Reallocate a sequence of blocks into a contiguous sequence of blocks.
267  *
268  * The vnode and an array of buffer pointers for a range of sequential
269  * logical blocks to be made contiguous is given. The allocator attempts
270  * to find a range of sequential blocks starting as close as possible to
271  * an fs_rotdelay offset from the end of the allocation for the logical
272  * block immediately preceeding the current range. If successful, the
273  * physical block numbers in the buffer pointers and in the inode are
274  * changed to reflect the new allocation. If unsuccessful, the allocation
275  * is left unchanged. The success in doing the reallocation is returned.
276  * Note that the error return is not reflected back to the user. Rather
277  * the previous block allocation will be used.
278  */
279 #include <sys/sysctl.h>
280 int doasyncfree = 1;
281 #ifdef DEBUG
282 struct ctldebug debug14 = { "doasyncfree", &doasyncfree };
283 int prtrealloc = 0;
284 struct ctldebug debug15 = { "prtrealloc", &prtrealloc };
285 #endif
286 
287 int
288 ffs_reallocblks(ap)
289 	struct vop_reallocblks_args /* {
290 		struct vnode *a_vp;
291 		struct cluster_save *a_buflist;
292 	} */ *ap;
293 {
294 	struct fs *fs;
295 	struct inode *ip;
296 	struct vnode *vp;
297 	struct buf *sbp, *ebp;
298 	daddr_t *bap, *sbap, *ebap;
299 	struct cluster_save *buflist;
300 	daddr_t start_lbn, end_lbn, soff, eoff, newblk, blkno;
301 	struct indir start_ap[NIADDR + 1], end_ap[NIADDR + 1], *idp;
302 	int i, len, start_lvl, end_lvl, pref, ssize;
303 
304 	vp = ap->a_vp;
305 	ip = VTOI(vp);
306 	fs = ip->i_fs;
307 	if (fs->fs_contigsumsize <= 0)
308 		return (ENOSPC);
309 	buflist = ap->a_buflist;
310 	len = buflist->bs_nchildren;
311 	start_lbn = buflist->bs_children[0]->b_lblkno;
312 	end_lbn = start_lbn + len - 1;
313 #ifdef DIAGNOSTIC
314 	for (i = 1; i < len; i++)
315 		if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
316 			panic("ffs_reallocblks: non-cluster");
317 #endif
318 	/*
319 	 * If the latest allocation is in a new cylinder group, assume that
320 	 * the filesystem has decided to move and do not force it back to
321 	 * the previous cylinder group.
322 	 */
323 	if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
324 	    dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
325 		return (ENOSPC);
326 	if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
327 	    ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
328 		return (ENOSPC);
329 	/*
330 	 * Get the starting offset and block map for the first block.
331 	 */
332 	if (start_lvl == 0) {
333 		sbap = &ip->i_db[0];
334 		soff = start_lbn;
335 	} else {
336 		idp = &start_ap[start_lvl - 1];
337 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
338 			brelse(sbp);
339 			return (ENOSPC);
340 		}
341 		sbap = (daddr_t *)sbp->b_data;
342 		soff = idp->in_off;
343 	}
344 	/*
345 	 * Find the preferred location for the cluster.
346 	 */
347 	pref = ffs_blkpref(ip, start_lbn, soff, sbap);
348 	/*
349 	 * If the block range spans two block maps, get the second map.
350 	 */
351 	if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
352 		ssize = len;
353 	} else {
354 #ifdef DIAGNOSTIC
355 		if (start_ap[start_lvl-1].in_lbn == idp->in_lbn)
356 			panic("ffs_reallocblk: start == end");
357 #endif
358 		ssize = len - (idp->in_off + 1);
359 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
360 			goto fail;
361 		ebap = (daddr_t *)ebp->b_data;
362 	}
363 	/*
364 	 * Search the block map looking for an allocation of the desired size.
365 	 */
366 	if ((newblk = (daddr_t)ffs_hashalloc(ip, dtog(fs, pref), (long)pref,
367 	    len, (u_long (*)())ffs_clusteralloc)) == 0)
368 		goto fail;
369 	/*
370 	 * We have found a new contiguous block.
371 	 *
372 	 * First we have to replace the old block pointers with the new
373 	 * block pointers in the inode and indirect blocks associated
374 	 * with the file.
375 	 */
376 #ifdef DEBUG
377 	if (prtrealloc)
378 		printf("realloc: ino %d, lbns %d-%d\n\told:", ip->i_number,
379 			start_lbn, end_lbn);
380 #endif DEBUG
381 	blkno = newblk;
382 	for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
383 		if (i == ssize)
384 			bap = ebap;
385 #ifdef DIAGNOSTIC
386 		if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
387 			panic("ffs_reallocblks: alloc mismatch");
388 #endif
389 #ifdef DEBUG
390 		if (prtrealloc)
391 			printf(" %d,", *bap);
392 #endif
393 		*bap++ = blkno;
394 	}
395 	/*
396 	 * Next we must write out the modified inode and indirect blocks.
397 	 * For strict correctness, the writes should be synchronous since
398 	 * the old block values may have been written to disk. In practise
399 	 * they are almost never written, but if we are concerned about
400 	 * strict correctness, the `doasyncfree' flag should be set to zero.
401 	 *
402 	 * The test on `doasyncfree' should be changed to test a flag
403 	 * that shows whether the associated buffers and inodes have
404 	 * been written. The flag should be set when the cluster is
405 	 * started and cleared whenever the buffer or inode is flushed.
406 	 * We can then check below to see if it is set, and do the
407 	 * synchronous write only when it has been cleared.
408 	 */
409 	if (sbap != &ip->i_db[0]) {
410 		if (doasyncfree)
411 			bdwrite(sbp);
412 		else
413 			bwrite(sbp);
414 	} else {
415 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
416 		if (!doasyncfree)
417 			VOP_UPDATE(vp, &time, &time, MNT_WAIT);
418 	}
419 	if (ssize < len)
420 		if (doasyncfree)
421 			bdwrite(ebp);
422 		else
423 			bwrite(ebp);
424 	/*
425 	 * Last, free the old blocks and assign the new blocks to the buffers.
426 	 */
427 #ifdef DEBUG
428 	if (prtrealloc)
429 		printf("\n\tnew:");
430 #endif
431 	for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
432 		ffs_blkfree(ip, dbtofsb(fs, buflist->bs_children[i]->b_blkno),
433 		    fs->fs_bsize);
434 		buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
435 #ifdef DEBUG
436 		if (prtrealloc)
437 			printf(" %d,", blkno);
438 #endif
439 	}
440 #ifdef DEBUG
441 	if (prtrealloc) {
442 		prtrealloc--;
443 		printf("\n");
444 	}
445 #endif
446 	return (0);
447 
448 fail:
449 	if (ssize < len)
450 		brelse(ebp);
451 	if (sbap != &ip->i_db[0])
452 		brelse(sbp);
453 	return (ENOSPC);
454 }
455 
456 /*
457  * Allocate an inode in the file system.
458  *
459  * If allocating a directory, use ffs_dirpref to select the inode.
460  * If allocating in a directory, the following hierarchy is followed:
461  *   1) allocate the preferred inode.
462  *   2) allocate an inode in the same cylinder group.
463  *   3) quadradically rehash into other cylinder groups, until an
464  *      available inode is located.
465  * If no inode preference is given the following heirarchy is used
466  * to allocate an inode:
467  *   1) allocate an inode in cylinder group 0.
468  *   2) quadradically rehash into other cylinder groups, until an
469  *      available inode is located.
470  */
471 ffs_valloc(ap)
472 	struct vop_valloc_args /* {
473 		struct vnode *a_pvp;
474 		int a_mode;
475 		struct ucred *a_cred;
476 		struct vnode **a_vpp;
477 	} */ *ap;
478 {
479 	register struct vnode *pvp = ap->a_pvp;
480 	register struct inode *pip;
481 	register struct fs *fs;
482 	register struct inode *ip;
483 	mode_t mode = ap->a_mode;
484 	ino_t ino, ipref;
485 	int cg, error;
486 
487 	*ap->a_vpp = NULL;
488 	pip = VTOI(pvp);
489 	fs = pip->i_fs;
490 	if (fs->fs_cstotal.cs_nifree == 0)
491 		goto noinodes;
492 
493 	if ((mode & IFMT) == IFDIR)
494 		ipref = ffs_dirpref(fs);
495 	else
496 		ipref = pip->i_number;
497 	if (ipref >= fs->fs_ncg * fs->fs_ipg)
498 		ipref = 0;
499 	cg = ino_to_cg(fs, ipref);
500 	ino = (ino_t)ffs_hashalloc(pip, cg, (long)ipref, mode, ffs_nodealloccg);
501 	if (ino == 0)
502 		goto noinodes;
503 	error = VFS_VGET(pvp->v_mount, ino, ap->a_vpp);
504 	if (error) {
505 		VOP_VFREE(pvp, ino, mode);
506 		return (error);
507 	}
508 	ip = VTOI(*ap->a_vpp);
509 	if (ip->i_mode) {
510 		printf("mode = 0%o, inum = %d, fs = %s\n",
511 		    ip->i_mode, ip->i_number, fs->fs_fsmnt);
512 		panic("ffs_valloc: dup alloc");
513 	}
514 	if (ip->i_blocks) {				/* XXX */
515 		printf("free inode %s/%d had %d blocks\n",
516 		    fs->fs_fsmnt, ino, ip->i_blocks);
517 		ip->i_blocks = 0;
518 	}
519 	ip->i_flags = 0;
520 	/*
521 	 * Set up a new generation number for this inode.
522 	 */
523 	if (++nextgennumber < (u_long)time.tv_sec)
524 		nextgennumber = time.tv_sec;
525 	ip->i_gen = nextgennumber;
526 	return (0);
527 noinodes:
528 	ffs_fserr(fs, ap->a_cred->cr_uid, "out of inodes");
529 	uprintf("\n%s: create/symlink failed, no inodes free\n", fs->fs_fsmnt);
530 	return (ENOSPC);
531 }
532 
533 /*
534  * Find a cylinder to place a directory.
535  *
536  * The policy implemented by this algorithm is to select from
537  * among those cylinder groups with above the average number of
538  * free inodes, the one with the smallest number of directories.
539  */
540 static ino_t
541 ffs_dirpref(fs)
542 	register struct fs *fs;
543 {
544 	int cg, minndir, mincg, avgifree;
545 
546 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
547 	minndir = fs->fs_ipg;
548 	mincg = 0;
549 	for (cg = 0; cg < fs->fs_ncg; cg++)
550 		if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
551 		    fs->fs_cs(fs, cg).cs_nifree >= avgifree) {
552 			mincg = cg;
553 			minndir = fs->fs_cs(fs, cg).cs_ndir;
554 		}
555 	return ((ino_t)(fs->fs_ipg * mincg));
556 }
557 
558 /*
559  * Select the desired position for the next block in a file.  The file is
560  * logically divided into sections. The first section is composed of the
561  * direct blocks. Each additional section contains fs_maxbpg blocks.
562  *
563  * If no blocks have been allocated in the first section, the policy is to
564  * request a block in the same cylinder group as the inode that describes
565  * the file. If no blocks have been allocated in any other section, the
566  * policy is to place the section in a cylinder group with a greater than
567  * average number of free blocks.  An appropriate cylinder group is found
568  * by using a rotor that sweeps the cylinder groups. When a new group of
569  * blocks is needed, the sweep begins in the cylinder group following the
570  * cylinder group from which the previous allocation was made. The sweep
571  * continues until a cylinder group with greater than the average number
572  * of free blocks is found. If the allocation is for the first block in an
573  * indirect block, the information on the previous allocation is unavailable;
574  * here a best guess is made based upon the logical block number being
575  * allocated.
576  *
577  * If a section is already partially allocated, the policy is to
578  * contiguously allocate fs_maxcontig blocks.  The end of one of these
579  * contiguous blocks and the beginning of the next is physically separated
580  * so that the disk head will be in transit between them for at least
581  * fs_rotdelay milliseconds.  This is to allow time for the processor to
582  * schedule another I/O transfer.
583  */
584 daddr_t
585 ffs_blkpref(ip, lbn, indx, bap)
586 	struct inode *ip;
587 	daddr_t lbn;
588 	int indx;
589 	daddr_t *bap;
590 {
591 	register struct fs *fs;
592 	register int cg;
593 	int avgbfree, startcg;
594 	daddr_t nextblk;
595 
596 	fs = ip->i_fs;
597 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
598 		if (lbn < NDADDR) {
599 			cg = ino_to_cg(fs, ip->i_number);
600 			return (fs->fs_fpg * cg + fs->fs_frag);
601 		}
602 		/*
603 		 * Find a cylinder with greater than average number of
604 		 * unused data blocks.
605 		 */
606 		if (indx == 0 || bap[indx - 1] == 0)
607 			startcg =
608 			    ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
609 		else
610 			startcg = dtog(fs, bap[indx - 1]) + 1;
611 		startcg %= fs->fs_ncg;
612 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
613 		for (cg = startcg; cg < fs->fs_ncg; cg++)
614 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
615 				fs->fs_cgrotor = cg;
616 				return (fs->fs_fpg * cg + fs->fs_frag);
617 			}
618 		for (cg = 0; cg <= startcg; cg++)
619 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
620 				fs->fs_cgrotor = cg;
621 				return (fs->fs_fpg * cg + fs->fs_frag);
622 			}
623 		return (NULL);
624 	}
625 	/*
626 	 * One or more previous blocks have been laid out. If less
627 	 * than fs_maxcontig previous blocks are contiguous, the
628 	 * next block is requested contiguously, otherwise it is
629 	 * requested rotationally delayed by fs_rotdelay milliseconds.
630 	 */
631 	nextblk = bap[indx - 1] + fs->fs_frag;
632 	if (indx < fs->fs_maxcontig || bap[indx - fs->fs_maxcontig] +
633 	    blkstofrags(fs, fs->fs_maxcontig) != nextblk)
634 		return (nextblk);
635 	if (fs->fs_rotdelay != 0)
636 		/*
637 		 * Here we convert ms of delay to frags as:
638 		 * (frags) = (ms) * (rev/sec) * (sect/rev) /
639 		 *	((sect/frag) * (ms/sec))
640 		 * then round up to the next block.
641 		 */
642 		nextblk += roundup(fs->fs_rotdelay * fs->fs_rps * fs->fs_nsect /
643 		    (NSPF(fs) * 1000), fs->fs_frag);
644 	return (nextblk);
645 }
646 
647 /*
648  * Implement the cylinder overflow algorithm.
649  *
650  * The policy implemented by this algorithm is:
651  *   1) allocate the block in its requested cylinder group.
652  *   2) quadradically rehash on the cylinder group number.
653  *   3) brute force search for a free block.
654  */
655 /*VARARGS5*/
656 static u_long
657 ffs_hashalloc(ip, cg, pref, size, allocator)
658 	struct inode *ip;
659 	int cg;
660 	long pref;
661 	int size;	/* size for data blocks, mode for inodes */
662 	u_long (*allocator)();
663 {
664 	register struct fs *fs;
665 	long result;
666 	int i, icg = cg;
667 
668 	fs = ip->i_fs;
669 	/*
670 	 * 1: preferred cylinder group
671 	 */
672 	result = (*allocator)(ip, cg, pref, size);
673 	if (result)
674 		return (result);
675 	/*
676 	 * 2: quadratic rehash
677 	 */
678 	for (i = 1; i < fs->fs_ncg; i *= 2) {
679 		cg += i;
680 		if (cg >= fs->fs_ncg)
681 			cg -= fs->fs_ncg;
682 		result = (*allocator)(ip, cg, 0, size);
683 		if (result)
684 			return (result);
685 	}
686 	/*
687 	 * 3: brute force search
688 	 * Note that we start at i == 2, since 0 was checked initially,
689 	 * and 1 is always checked in the quadratic rehash.
690 	 */
691 	cg = (icg + 2) % fs->fs_ncg;
692 	for (i = 2; i < fs->fs_ncg; i++) {
693 		result = (*allocator)(ip, cg, 0, size);
694 		if (result)
695 			return (result);
696 		cg++;
697 		if (cg == fs->fs_ncg)
698 			cg = 0;
699 	}
700 	return (NULL);
701 }
702 
703 /*
704  * Determine whether a fragment can be extended.
705  *
706  * Check to see if the necessary fragments are available, and
707  * if they are, allocate them.
708  */
709 static daddr_t
710 ffs_fragextend(ip, cg, bprev, osize, nsize)
711 	struct inode *ip;
712 	int cg;
713 	long bprev;
714 	int osize, nsize;
715 {
716 	register struct fs *fs;
717 	register struct cg *cgp;
718 	struct buf *bp;
719 	long bno;
720 	int frags, bbase;
721 	int i, error;
722 
723 	fs = ip->i_fs;
724 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
725 		return (NULL);
726 	frags = numfrags(fs, nsize);
727 	bbase = fragnum(fs, bprev);
728 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
729 		/* cannot extend across a block boundary */
730 		return (NULL);
731 	}
732 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
733 		(int)fs->fs_cgsize, NOCRED, &bp);
734 	if (error) {
735 		brelse(bp);
736 		return (NULL);
737 	}
738 	cgp = (struct cg *)bp->b_data;
739 	if (!cg_chkmagic(cgp)) {
740 		brelse(bp);
741 		return (NULL);
742 	}
743 	cgp->cg_time = time.tv_sec;
744 	bno = dtogd(fs, bprev);
745 	for (i = numfrags(fs, osize); i < frags; i++)
746 		if (isclr(cg_blksfree(cgp), bno + i)) {
747 			brelse(bp);
748 			return (NULL);
749 		}
750 	/*
751 	 * the current fragment can be extended
752 	 * deduct the count on fragment being extended into
753 	 * increase the count on the remaining fragment (if any)
754 	 * allocate the extended piece
755 	 */
756 	for (i = frags; i < fs->fs_frag - bbase; i++)
757 		if (isclr(cg_blksfree(cgp), bno + i))
758 			break;
759 	cgp->cg_frsum[i - numfrags(fs, osize)]--;
760 	if (i != frags)
761 		cgp->cg_frsum[i - frags]++;
762 	for (i = numfrags(fs, osize); i < frags; i++) {
763 		clrbit(cg_blksfree(cgp), bno + i);
764 		cgp->cg_cs.cs_nffree--;
765 		fs->fs_cstotal.cs_nffree--;
766 		fs->fs_cs(fs, cg).cs_nffree--;
767 	}
768 	fs->fs_fmod = 1;
769 	bdwrite(bp);
770 	return (bprev);
771 }
772 
773 /*
774  * Determine whether a block can be allocated.
775  *
776  * Check to see if a block of the appropriate size is available,
777  * and if it is, allocate it.
778  */
779 static daddr_t
780 ffs_alloccg(ip, cg, bpref, size)
781 	struct inode *ip;
782 	int cg;
783 	daddr_t bpref;
784 	int size;
785 {
786 	register struct fs *fs;
787 	register struct cg *cgp;
788 	struct buf *bp;
789 	register int i;
790 	int error, bno, frags, allocsiz;
791 
792 	fs = ip->i_fs;
793 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
794 		return (NULL);
795 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
796 		(int)fs->fs_cgsize, NOCRED, &bp);
797 	if (error) {
798 		brelse(bp);
799 		return (NULL);
800 	}
801 	cgp = (struct cg *)bp->b_data;
802 	if (!cg_chkmagic(cgp) ||
803 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize)) {
804 		brelse(bp);
805 		return (NULL);
806 	}
807 	cgp->cg_time = time.tv_sec;
808 	if (size == fs->fs_bsize) {
809 		bno = ffs_alloccgblk(fs, cgp, bpref);
810 		bdwrite(bp);
811 		return (bno);
812 	}
813 	/*
814 	 * check to see if any fragments are already available
815 	 * allocsiz is the size which will be allocated, hacking
816 	 * it down to a smaller size if necessary
817 	 */
818 	frags = numfrags(fs, size);
819 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
820 		if (cgp->cg_frsum[allocsiz] != 0)
821 			break;
822 	if (allocsiz == fs->fs_frag) {
823 		/*
824 		 * no fragments were available, so a block will be
825 		 * allocated, and hacked up
826 		 */
827 		if (cgp->cg_cs.cs_nbfree == 0) {
828 			brelse(bp);
829 			return (NULL);
830 		}
831 		bno = ffs_alloccgblk(fs, cgp, bpref);
832 		bpref = dtogd(fs, bno);
833 		for (i = frags; i < fs->fs_frag; i++)
834 			setbit(cg_blksfree(cgp), bpref + i);
835 		i = fs->fs_frag - frags;
836 		cgp->cg_cs.cs_nffree += i;
837 		fs->fs_cstotal.cs_nffree += i;
838 		fs->fs_cs(fs, cg).cs_nffree += i;
839 		fs->fs_fmod = 1;
840 		cgp->cg_frsum[i]++;
841 		bdwrite(bp);
842 		return (bno);
843 	}
844 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
845 	if (bno < 0) {
846 		brelse(bp);
847 		return (NULL);
848 	}
849 	for (i = 0; i < frags; i++)
850 		clrbit(cg_blksfree(cgp), bno + i);
851 	cgp->cg_cs.cs_nffree -= frags;
852 	fs->fs_cstotal.cs_nffree -= frags;
853 	fs->fs_cs(fs, cg).cs_nffree -= frags;
854 	fs->fs_fmod = 1;
855 	cgp->cg_frsum[allocsiz]--;
856 	if (frags != allocsiz)
857 		cgp->cg_frsum[allocsiz - frags]++;
858 	bdwrite(bp);
859 	return (cg * fs->fs_fpg + bno);
860 }
861 
862 /*
863  * Allocate a block in a cylinder group.
864  *
865  * This algorithm implements the following policy:
866  *   1) allocate the requested block.
867  *   2) allocate a rotationally optimal block in the same cylinder.
868  *   3) allocate the next available block on the block rotor for the
869  *      specified cylinder group.
870  * Note that this routine only allocates fs_bsize blocks; these
871  * blocks may be fragmented by the routine that allocates them.
872  */
873 static daddr_t
874 ffs_alloccgblk(fs, cgp, bpref)
875 	register struct fs *fs;
876 	register struct cg *cgp;
877 	daddr_t bpref;
878 {
879 	daddr_t bno, blkno;
880 	int cylno, pos, delta;
881 	short *cylbp;
882 	register int i;
883 
884 	if (bpref == 0 || dtog(fs, bpref) != cgp->cg_cgx) {
885 		bpref = cgp->cg_rotor;
886 		goto norot;
887 	}
888 	bpref = blknum(fs, bpref);
889 	bpref = dtogd(fs, bpref);
890 	/*
891 	 * if the requested block is available, use it
892 	 */
893 	if (ffs_isblock(fs, cg_blksfree(cgp), fragstoblks(fs, bpref))) {
894 		bno = bpref;
895 		goto gotit;
896 	}
897 	/*
898 	 * check for a block available on the same cylinder
899 	 */
900 	cylno = cbtocylno(fs, bpref);
901 	if (cg_blktot(cgp)[cylno] == 0)
902 		goto norot;
903 	if (fs->fs_cpc == 0) {
904 		/*
905 		 * Block layout information is not available.
906 		 * Leaving bpref unchanged means we take the
907 		 * next available free block following the one
908 		 * we just allocated. Hopefully this will at
909 		 * least hit a track cache on drives of unknown
910 		 * geometry (e.g. SCSI).
911 		 */
912 		goto norot;
913 	}
914 	/*
915 	 * check the summary information to see if a block is
916 	 * available in the requested cylinder starting at the
917 	 * requested rotational position and proceeding around.
918 	 */
919 	cylbp = cg_blks(fs, cgp, cylno);
920 	pos = cbtorpos(fs, bpref);
921 	for (i = pos; i < fs->fs_nrpos; i++)
922 		if (cylbp[i] > 0)
923 			break;
924 	if (i == fs->fs_nrpos)
925 		for (i = 0; i < pos; i++)
926 			if (cylbp[i] > 0)
927 				break;
928 	if (cylbp[i] > 0) {
929 		/*
930 		 * found a rotational position, now find the actual
931 		 * block. A panic if none is actually there.
932 		 */
933 		pos = cylno % fs->fs_cpc;
934 		bno = (cylno - pos) * fs->fs_spc / NSPB(fs);
935 		if (fs_postbl(fs, pos)[i] == -1) {
936 			printf("pos = %d, i = %d, fs = %s\n",
937 			    pos, i, fs->fs_fsmnt);
938 			panic("ffs_alloccgblk: cyl groups corrupted");
939 		}
940 		for (i = fs_postbl(fs, pos)[i];; ) {
941 			if (ffs_isblock(fs, cg_blksfree(cgp), bno + i)) {
942 				bno = blkstofrags(fs, (bno + i));
943 				goto gotit;
944 			}
945 			delta = fs_rotbl(fs)[i];
946 			if (delta <= 0 ||
947 			    delta + i > fragstoblks(fs, fs->fs_fpg))
948 				break;
949 			i += delta;
950 		}
951 		printf("pos = %d, i = %d, fs = %s\n", pos, i, fs->fs_fsmnt);
952 		panic("ffs_alloccgblk: can't find blk in cyl");
953 	}
954 norot:
955 	/*
956 	 * no blocks in the requested cylinder, so take next
957 	 * available one in this cylinder group.
958 	 */
959 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
960 	if (bno < 0)
961 		return (NULL);
962 	cgp->cg_rotor = bno;
963 gotit:
964 	blkno = fragstoblks(fs, bno);
965 	ffs_clrblock(fs, cg_blksfree(cgp), (long)blkno);
966 	ffs_clusteracct(fs, cgp, blkno, -1);
967 	cgp->cg_cs.cs_nbfree--;
968 	fs->fs_cstotal.cs_nbfree--;
969 	fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
970 	cylno = cbtocylno(fs, bno);
971 	cg_blks(fs, cgp, cylno)[cbtorpos(fs, bno)]--;
972 	cg_blktot(cgp)[cylno]--;
973 	fs->fs_fmod = 1;
974 	return (cgp->cg_cgx * fs->fs_fpg + bno);
975 }
976 
977 /*
978  * Determine whether a cluster can be allocated.
979  *
980  * We do not currently check for optimal rotational layout if there
981  * are multiple choices in the same cylinder group. Instead we just
982  * take the first one that we find following bpref.
983  */
984 static daddr_t
985 ffs_clusteralloc(ip, cg, bpref, len)
986 	struct inode *ip;
987 	int cg;
988 	daddr_t bpref;
989 	int len;
990 {
991 	register struct fs *fs;
992 	register struct cg *cgp;
993 	struct buf *bp;
994 	int i, run, bno, bit, map;
995 	u_char *mapp;
996 	int32_t *lp;
997 
998 	fs = ip->i_fs;
999 	if (fs->fs_maxcluster[cg] < len)
1000 		return (NULL);
1001 	if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize,
1002 	    NOCRED, &bp))
1003 		goto fail;
1004 	cgp = (struct cg *)bp->b_data;
1005 	if (!cg_chkmagic(cgp))
1006 		goto fail;
1007 	/*
1008 	 * Check to see if a cluster of the needed size (or bigger) is
1009 	 * available in this cylinder group.
1010 	 */
1011 	lp = &cg_clustersum(cgp)[len];
1012 	for (i = len; i <= fs->fs_contigsumsize; i++)
1013 		if (*lp++ > 0)
1014 			break;
1015 	if (i > fs->fs_contigsumsize) {
1016 		/*
1017 		 * This is the first time looking for a cluster in this
1018 		 * cylinder group. Update the cluster summary information
1019 		 * to reflect the true maximum sized cluster so that
1020 		 * future cluster allocation requests can avoid reading
1021 		 * the cylinder group map only to find no clusters.
1022 		 */
1023 		lp = &cg_clustersum(cgp)[len - 1];
1024 		for (i = len - 1; i > 0; i--)
1025 			if (*lp-- > 0)
1026 				break;
1027 		fs->fs_maxcluster[cg] = i;
1028 		goto fail;
1029 	}
1030 	/*
1031 	 * Search the cluster map to find a big enough cluster.
1032 	 * We take the first one that we find, even if it is larger
1033 	 * than we need as we prefer to get one close to the previous
1034 	 * block allocation. We do not search before the current
1035 	 * preference point as we do not want to allocate a block
1036 	 * that is allocated before the previous one (as we will
1037 	 * then have to wait for another pass of the elevator
1038 	 * algorithm before it will be read). We prefer to fail and
1039 	 * be recalled to try an allocation in the next cylinder group.
1040 	 */
1041 	if (dtog(fs, bpref) != cg)
1042 		bpref = 0;
1043 	else
1044 		bpref = fragstoblks(fs, dtogd(fs, blknum(fs, bpref)));
1045 	mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1046 	map = *mapp++;
1047 	bit = 1 << (bpref % NBBY);
1048 	for (run = 0, i = bpref; i < cgp->cg_nclusterblks; i++) {
1049 		if ((map & bit) == 0) {
1050 			run = 0;
1051 		} else {
1052 			run++;
1053 			if (run == len)
1054 				break;
1055 		}
1056 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
1057 			bit <<= 1;
1058 		} else {
1059 			map = *mapp++;
1060 			bit = 1;
1061 		}
1062 	}
1063 	if (i == cgp->cg_nclusterblks)
1064 		goto fail;
1065 	/*
1066 	 * Allocate the cluster that we have found.
1067 	 */
1068 	bno = cg * fs->fs_fpg + blkstofrags(fs, i - run + 1);
1069 	len = blkstofrags(fs, len);
1070 	for (i = 0; i < len; i += fs->fs_frag)
1071 		if (ffs_alloccgblk(fs, cgp, bno + i) != bno + i)
1072 			panic("ffs_clusteralloc: lost block");
1073 	brelse(bp);
1074 	return (bno);
1075 
1076 fail:
1077 	brelse(bp);
1078 	return (0);
1079 }
1080 
1081 /*
1082  * Determine whether an inode can be allocated.
1083  *
1084  * Check to see if an inode is available, and if it is,
1085  * allocate it using the following policy:
1086  *   1) allocate the requested inode.
1087  *   2) allocate the next available inode after the requested
1088  *      inode in the specified cylinder group.
1089  */
1090 static u_long
1091 ffs_nodealloccg(ip, cg, ipref, mode)
1092 	struct inode *ip;
1093 	int cg;
1094 	daddr_t ipref;
1095 	int mode;
1096 {
1097 	register struct fs *fs;
1098 	register struct cg *cgp;
1099 	struct buf *bp;
1100 	int error, start, len, loc, map, i;
1101 
1102 	fs = ip->i_fs;
1103 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
1104 		return (NULL);
1105 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1106 		(int)fs->fs_cgsize, NOCRED, &bp);
1107 	if (error) {
1108 		brelse(bp);
1109 		return (NULL);
1110 	}
1111 	cgp = (struct cg *)bp->b_data;
1112 	if (!cg_chkmagic(cgp) || cgp->cg_cs.cs_nifree == 0) {
1113 		brelse(bp);
1114 		return (NULL);
1115 	}
1116 	cgp->cg_time = time.tv_sec;
1117 	if (ipref) {
1118 		ipref %= fs->fs_ipg;
1119 		if (isclr(cg_inosused(cgp), ipref))
1120 			goto gotit;
1121 	}
1122 	start = cgp->cg_irotor / NBBY;
1123 	len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
1124 	loc = skpc(0xff, len, &cg_inosused(cgp)[start]);
1125 	if (loc == 0) {
1126 		len = start + 1;
1127 		start = 0;
1128 		loc = skpc(0xff, len, &cg_inosused(cgp)[0]);
1129 		if (loc == 0) {
1130 			printf("cg = %d, irotor = %d, fs = %s\n",
1131 			    cg, cgp->cg_irotor, fs->fs_fsmnt);
1132 			panic("ffs_nodealloccg: map corrupted");
1133 			/* NOTREACHED */
1134 		}
1135 	}
1136 	i = start + len - loc;
1137 	map = cg_inosused(cgp)[i];
1138 	ipref = i * NBBY;
1139 	for (i = 1; i < (1 << NBBY); i <<= 1, ipref++) {
1140 		if ((map & i) == 0) {
1141 			cgp->cg_irotor = ipref;
1142 			goto gotit;
1143 		}
1144 	}
1145 	printf("fs = %s\n", fs->fs_fsmnt);
1146 	panic("ffs_nodealloccg: block not in map");
1147 	/* NOTREACHED */
1148 gotit:
1149 	setbit(cg_inosused(cgp), ipref);
1150 	cgp->cg_cs.cs_nifree--;
1151 	fs->fs_cstotal.cs_nifree--;
1152 	fs->fs_cs(fs, cg).cs_nifree--;
1153 	fs->fs_fmod = 1;
1154 	if ((mode & IFMT) == IFDIR) {
1155 		cgp->cg_cs.cs_ndir++;
1156 		fs->fs_cstotal.cs_ndir++;
1157 		fs->fs_cs(fs, cg).cs_ndir++;
1158 	}
1159 	bdwrite(bp);
1160 	return (cg * fs->fs_ipg + ipref);
1161 }
1162 
1163 /*
1164  * Free a block or fragment.
1165  *
1166  * The specified block or fragment is placed back in the
1167  * free map. If a fragment is deallocated, a possible
1168  * block reassembly is checked.
1169  */
1170 ffs_blkfree(ip, bno, size)
1171 	register struct inode *ip;
1172 	daddr_t bno;
1173 	long size;
1174 {
1175 	register struct fs *fs;
1176 	register struct cg *cgp;
1177 	struct buf *bp;
1178 	daddr_t blkno;
1179 	int i, error, cg, blk, frags, bbase;
1180 
1181 	fs = ip->i_fs;
1182 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
1183 		printf("dev = 0x%x, bsize = %d, size = %d, fs = %s\n",
1184 		    ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
1185 		panic("blkfree: bad size");
1186 	}
1187 	cg = dtog(fs, bno);
1188 	if ((u_int)bno >= fs->fs_size) {
1189 		printf("bad block %d, ino %d\n", bno, ip->i_number);
1190 		ffs_fserr(fs, ip->i_uid, "bad block");
1191 		return;
1192 	}
1193 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1194 		(int)fs->fs_cgsize, NOCRED, &bp);
1195 	if (error) {
1196 		brelse(bp);
1197 		return;
1198 	}
1199 	cgp = (struct cg *)bp->b_data;
1200 	if (!cg_chkmagic(cgp)) {
1201 		brelse(bp);
1202 		return;
1203 	}
1204 	cgp->cg_time = time.tv_sec;
1205 	bno = dtogd(fs, bno);
1206 	if (size == fs->fs_bsize) {
1207 		blkno = fragstoblks(fs, bno);
1208 		if (ffs_isblock(fs, cg_blksfree(cgp), blkno)) {
1209 			printf("dev = 0x%x, block = %d, fs = %s\n",
1210 			    ip->i_dev, bno, fs->fs_fsmnt);
1211 			panic("blkfree: freeing free block");
1212 		}
1213 		ffs_setblock(fs, cg_blksfree(cgp), blkno);
1214 		ffs_clusteracct(fs, cgp, blkno, 1);
1215 		cgp->cg_cs.cs_nbfree++;
1216 		fs->fs_cstotal.cs_nbfree++;
1217 		fs->fs_cs(fs, cg).cs_nbfree++;
1218 		i = cbtocylno(fs, bno);
1219 		cg_blks(fs, cgp, i)[cbtorpos(fs, bno)]++;
1220 		cg_blktot(cgp)[i]++;
1221 	} else {
1222 		bbase = bno - fragnum(fs, bno);
1223 		/*
1224 		 * decrement the counts associated with the old frags
1225 		 */
1226 		blk = blkmap(fs, cg_blksfree(cgp), bbase);
1227 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
1228 		/*
1229 		 * deallocate the fragment
1230 		 */
1231 		frags = numfrags(fs, size);
1232 		for (i = 0; i < frags; i++) {
1233 			if (isset(cg_blksfree(cgp), bno + i)) {
1234 				printf("dev = 0x%x, block = %d, fs = %s\n",
1235 				    ip->i_dev, bno + i, fs->fs_fsmnt);
1236 				panic("blkfree: freeing free frag");
1237 			}
1238 			setbit(cg_blksfree(cgp), bno + i);
1239 		}
1240 		cgp->cg_cs.cs_nffree += i;
1241 		fs->fs_cstotal.cs_nffree += i;
1242 		fs->fs_cs(fs, cg).cs_nffree += i;
1243 		/*
1244 		 * add back in counts associated with the new frags
1245 		 */
1246 		blk = blkmap(fs, cg_blksfree(cgp), bbase);
1247 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
1248 		/*
1249 		 * if a complete block has been reassembled, account for it
1250 		 */
1251 		blkno = fragstoblks(fs, bbase);
1252 		if (ffs_isblock(fs, cg_blksfree(cgp), blkno)) {
1253 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
1254 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
1255 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
1256 			ffs_clusteracct(fs, cgp, blkno, 1);
1257 			cgp->cg_cs.cs_nbfree++;
1258 			fs->fs_cstotal.cs_nbfree++;
1259 			fs->fs_cs(fs, cg).cs_nbfree++;
1260 			i = cbtocylno(fs, bbase);
1261 			cg_blks(fs, cgp, i)[cbtorpos(fs, bbase)]++;
1262 			cg_blktot(cgp)[i]++;
1263 		}
1264 	}
1265 	fs->fs_fmod = 1;
1266 	bdwrite(bp);
1267 }
1268 
1269 /*
1270  * Free an inode.
1271  *
1272  * The specified inode is placed back in the free map.
1273  */
1274 int
1275 ffs_vfree(ap)
1276 	struct vop_vfree_args /* {
1277 		struct vnode *a_pvp;
1278 		ino_t a_ino;
1279 		int a_mode;
1280 	} */ *ap;
1281 {
1282 	register struct fs *fs;
1283 	register struct cg *cgp;
1284 	register struct inode *pip;
1285 	ino_t ino = ap->a_ino;
1286 	struct buf *bp;
1287 	int error, cg;
1288 
1289 	pip = VTOI(ap->a_pvp);
1290 	fs = pip->i_fs;
1291 	if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
1292 		panic("ifree: range: dev = 0x%x, ino = %d, fs = %s\n",
1293 		    pip->i_dev, ino, fs->fs_fsmnt);
1294 	cg = ino_to_cg(fs, ino);
1295 	error = bread(pip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1296 		(int)fs->fs_cgsize, NOCRED, &bp);
1297 	if (error) {
1298 		brelse(bp);
1299 		return (0);
1300 	}
1301 	cgp = (struct cg *)bp->b_data;
1302 	if (!cg_chkmagic(cgp)) {
1303 		brelse(bp);
1304 		return (0);
1305 	}
1306 	cgp->cg_time = time.tv_sec;
1307 	ino %= fs->fs_ipg;
1308 	if (isclr(cg_inosused(cgp), ino)) {
1309 		printf("dev = 0x%x, ino = %d, fs = %s\n",
1310 		    pip->i_dev, ino, fs->fs_fsmnt);
1311 		if (fs->fs_ronly == 0)
1312 			panic("ifree: freeing free inode");
1313 	}
1314 	clrbit(cg_inosused(cgp), ino);
1315 	if (ino < cgp->cg_irotor)
1316 		cgp->cg_irotor = ino;
1317 	cgp->cg_cs.cs_nifree++;
1318 	fs->fs_cstotal.cs_nifree++;
1319 	fs->fs_cs(fs, cg).cs_nifree++;
1320 	if ((ap->a_mode & IFMT) == IFDIR) {
1321 		cgp->cg_cs.cs_ndir--;
1322 		fs->fs_cstotal.cs_ndir--;
1323 		fs->fs_cs(fs, cg).cs_ndir--;
1324 	}
1325 	fs->fs_fmod = 1;
1326 	bdwrite(bp);
1327 	return (0);
1328 }
1329 
1330 /*
1331  * Find a block of the specified size in the specified cylinder group.
1332  *
1333  * It is a panic if a request is made to find a block if none are
1334  * available.
1335  */
1336 static daddr_t
1337 ffs_mapsearch(fs, cgp, bpref, allocsiz)
1338 	register struct fs *fs;
1339 	register struct cg *cgp;
1340 	daddr_t bpref;
1341 	int allocsiz;
1342 {
1343 	daddr_t bno;
1344 	int start, len, loc, i;
1345 	int blk, field, subfield, pos;
1346 
1347 	/*
1348 	 * find the fragment by searching through the free block
1349 	 * map for an appropriate bit pattern
1350 	 */
1351 	if (bpref)
1352 		start = dtogd(fs, bpref) / NBBY;
1353 	else
1354 		start = cgp->cg_frotor / NBBY;
1355 	len = howmany(fs->fs_fpg, NBBY) - start;
1356 	loc = scanc((u_int)len, (u_char *)&cg_blksfree(cgp)[start],
1357 		(u_char *)fragtbl[fs->fs_frag],
1358 		(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
1359 	if (loc == 0) {
1360 		len = start + 1;
1361 		start = 0;
1362 		loc = scanc((u_int)len, (u_char *)&cg_blksfree(cgp)[0],
1363 			(u_char *)fragtbl[fs->fs_frag],
1364 			(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
1365 		if (loc == 0) {
1366 			printf("start = %d, len = %d, fs = %s\n",
1367 			    start, len, fs->fs_fsmnt);
1368 			panic("ffs_alloccg: map corrupted");
1369 			/* NOTREACHED */
1370 		}
1371 	}
1372 	bno = (start + len - loc) * NBBY;
1373 	cgp->cg_frotor = bno;
1374 	/*
1375 	 * found the byte in the map
1376 	 * sift through the bits to find the selected frag
1377 	 */
1378 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
1379 		blk = blkmap(fs, cg_blksfree(cgp), bno);
1380 		blk <<= 1;
1381 		field = around[allocsiz];
1382 		subfield = inside[allocsiz];
1383 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
1384 			if ((blk & field) == subfield)
1385 				return (bno + pos);
1386 			field <<= 1;
1387 			subfield <<= 1;
1388 		}
1389 	}
1390 	printf("bno = %d, fs = %s\n", bno, fs->fs_fsmnt);
1391 	panic("ffs_alloccg: block not in map");
1392 	return (-1);
1393 }
1394 
1395 /*
1396  * Update the cluster map because of an allocation or free.
1397  *
1398  * Cnt == 1 means free; cnt == -1 means allocating.
1399  */
1400 ffs_clusteracct(fs, cgp, blkno, cnt)
1401 	struct fs *fs;
1402 	struct cg *cgp;
1403 	daddr_t blkno;
1404 	int cnt;
1405 {
1406 	long *sump;
1407 	int32_t *lp;
1408 	u_char *freemapp, *mapp;
1409 	int i, start, end, forw, back, map, bit;
1410 
1411 	if (fs->fs_contigsumsize <= 0)
1412 		return;
1413 	freemapp = cg_clustersfree(cgp);
1414 	sump = cg_clustersum(cgp);
1415 	/*
1416 	 * Allocate or clear the actual block.
1417 	 */
1418 	if (cnt > 0)
1419 		setbit(freemapp, blkno);
1420 	else
1421 		clrbit(freemapp, blkno);
1422 	/*
1423 	 * Find the size of the cluster going forward.
1424 	 */
1425 	start = blkno + 1;
1426 	end = start + fs->fs_contigsumsize;
1427 	if (end >= cgp->cg_nclusterblks)
1428 		end = cgp->cg_nclusterblks;
1429 	mapp = &freemapp[start / NBBY];
1430 	map = *mapp++;
1431 	bit = 1 << (start % NBBY);
1432 	for (i = start; i < end; i++) {
1433 		if ((map & bit) == 0)
1434 			break;
1435 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
1436 			bit <<= 1;
1437 		} else {
1438 			map = *mapp++;
1439 			bit = 1;
1440 		}
1441 	}
1442 	forw = i - start;
1443 	/*
1444 	 * Find the size of the cluster going backward.
1445 	 */
1446 	start = blkno - 1;
1447 	end = start - fs->fs_contigsumsize;
1448 	if (end < 0)
1449 		end = -1;
1450 	mapp = &freemapp[start / NBBY];
1451 	map = *mapp--;
1452 	bit = 1 << (start % NBBY);
1453 	for (i = start; i > end; i--) {
1454 		if ((map & bit) == 0)
1455 			break;
1456 		if ((i & (NBBY - 1)) != 0) {
1457 			bit >>= 1;
1458 		} else {
1459 			map = *mapp--;
1460 			bit = 1 << (NBBY - 1);
1461 		}
1462 	}
1463 	back = start - i;
1464 	/*
1465 	 * Account for old cluster and the possibly new forward and
1466 	 * back clusters.
1467 	 */
1468 	i = back + forw + 1;
1469 	if (i > fs->fs_contigsumsize)
1470 		i = fs->fs_contigsumsize;
1471 	sump[i] += cnt;
1472 	if (back > 0)
1473 		sump[back] -= cnt;
1474 	if (forw > 0)
1475 		sump[forw] -= cnt;
1476 	/*
1477 	 * Update cluster summary information.
1478 	 */
1479 	lp = &sump[fs->fs_contigsumsize];
1480 	for (i = fs->fs_contigsumsize; i > 0; i--)
1481 		if (*lp-- > 0)
1482 			break;
1483 	fs->fs_maxcluster[cgp->cg_cgx] = i;
1484 }
1485 
1486 /*
1487  * Fserr prints the name of a file system with an error diagnostic.
1488  *
1489  * The form of the error message is:
1490  *	fs: error message
1491  */
1492 static void
1493 ffs_fserr(fs, uid, cp)
1494 	struct fs *fs;
1495 	u_int uid;
1496 	char *cp;
1497 {
1498 
1499 	log(LOG_ERR, "uid %d on %s: %s\n", uid, fs->fs_fsmnt, cp);
1500 }
1501