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