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