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