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