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