xref: /openbsd/sys/ufs/ffs/ffs_alloc.c (revision 81fb472f)
1 /*	$OpenBSD: ffs_alloc.c,v 1.115 2024/02/03 18:51:58 beck Exp $	*/
2 /*	$NetBSD: ffs_alloc.c,v 1.11 1996/05/11 18:27:09 mycroft Exp $	*/
3 
4 /*
5  * Copyright (c) 2002 Networks Associates Technology, Inc.
6  * All rights reserved.
7  *
8  * This software was developed for the FreeBSD Project by Marshall
9  * Kirk McKusick and Network Associates Laboratories, the Security
10  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
11  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
12  * research program.
13  *
14  * Copyright (c) 1982, 1986, 1989, 1993
15  *	The Regents of the University of California.  All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  * 3. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  *
41  *	@(#)ffs_alloc.c	8.11 (Berkeley) 10/27/94
42  */
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/buf.h>
47 #include <sys/vnode.h>
48 #include <sys/mount.h>
49 #include <sys/syslog.h>
50 #include <sys/stdint.h>
51 #include <sys/time.h>
52 
53 #include <ufs/ufs/quota.h>
54 #include <ufs/ufs/inode.h>
55 #include <ufs/ufs/ufsmount.h>
56 #include <ufs/ufs/ufs_extern.h>
57 
58 #include <ufs/ffs/fs.h>
59 #include <ufs/ffs/ffs_extern.h>
60 
61 #define ffs_fserr(fs, uid, cp) do {				\
62 	log(LOG_ERR, "uid %u on %s: %s\n", (uid),		\
63 	    (fs)->fs_fsmnt, (cp));				\
64 } while (0)
65 
66 daddr_t		ffs_alloccg(struct inode *, u_int, daddr_t, int);
67 struct buf *	ffs_cgread(struct fs *, struct inode *, u_int);
68 daddr_t		ffs_alloccgblk(struct inode *, struct buf *, daddr_t);
69 ufsino_t	ffs_dirpref(struct inode *);
70 daddr_t		ffs_fragextend(struct inode *, u_int, daddr_t, int, int);
71 daddr_t		ffs_hashalloc(struct inode *, u_int, daddr_t, int,
72 		    daddr_t (*)(struct inode *, u_int, daddr_t, int));
73 daddr_t		ffs_nodealloccg(struct inode *, u_int, daddr_t, int);
74 daddr_t		ffs_mapsearch(struct fs *, struct cg *, daddr_t, int);
75 
76 static const struct timeval	fserr_interval = { 2, 0 };
77 
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) quadratically rehash into other cylinder groups, until an
90  *      available block is located.
91  * If no block preference is given the following hierarchy 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) quadratically rehash into other cylinder groups, until an
96  *      available block is located.
97  */
98 int
ffs_alloc(struct inode * ip,daddr_t lbn,daddr_t bpref,int size,struct ucred * cred,daddr_t * bnp)99 ffs_alloc(struct inode *ip, daddr_t lbn, daddr_t bpref, int size,
100     struct ucred *cred, daddr_t *bnp)
101 {
102 	static struct timeval fsfull_last;
103 	struct fs *fs;
104 	daddr_t bno;
105 	u_int cg;
106 	int error;
107 
108 	*bnp = 0;
109 	fs = ip->i_fs;
110 #ifdef DIAGNOSTIC
111 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
112 		printf("dev = 0x%x, bsize = %d, size = %d, fs = %s\n",
113 		    ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
114 		panic("ffs_alloc: bad size");
115 	}
116 	if (cred == NOCRED)
117 		panic("ffs_alloc: missing credential");
118 #endif /* DIAGNOSTIC */
119 	if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
120 		goto nospace;
121 	if (cred->cr_uid != 0 && freespace(fs, fs->fs_minfree) <= 0)
122 		goto nospace;
123 
124 	if ((error = ufs_quota_alloc_blocks(ip, btodb(size), cred)) != 0)
125 		return (error);
126 
127 	/*
128 	 * Start allocation in the preferred block's cylinder group or
129 	 * the file's inode's cylinder group if no preferred block was
130 	 * specified.
131 	 */
132 	if (bpref >= fs->fs_size)
133 		bpref = 0;
134 	if (bpref == 0)
135 		cg = ino_to_cg(fs, ip->i_number);
136 	else
137 		cg = dtog(fs, bpref);
138 
139 	/* Try allocating a block. */
140 	bno = ffs_hashalloc(ip, cg, bpref, size, ffs_alloccg);
141 	if (bno > 0) {
142 		/* allocation successful, update inode data */
143 		DIP_ADD(ip, blocks, btodb(size));
144 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
145 		*bnp = bno;
146 		return (0);
147 	}
148 
149 	/* Restore user's disk quota because allocation failed. */
150 	(void) ufs_quota_free_blocks(ip, btodb(size), cred);
151 
152 nospace:
153 	if (ratecheck(&fsfull_last, &fserr_interval)) {
154 		ffs_fserr(fs, cred->cr_uid, "file system full");
155 		uprintf("\n%s: write failed, file system is full\n",
156 		    fs->fs_fsmnt);
157 	}
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
ffs_realloccg(struct inode * ip,daddr_t lbprev,daddr_t bpref,int osize,int nsize,struct ucred * cred,struct buf ** bpp,daddr_t * blknop)170 ffs_realloccg(struct inode *ip, daddr_t lbprev, daddr_t bpref, int osize,
171     int nsize, struct ucred *cred, struct buf **bpp, daddr_t *blknop)
172 {
173 	static struct timeval fsfull_last;
174 	struct fs *fs;
175 	struct buf *bp = NULL;
176 	daddr_t quota_updated = 0;
177 	int request, error;
178 	u_int cg;
179 	daddr_t bprev, bno;
180 
181 	if (bpp != NULL)
182 		*bpp = NULL;
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%x, bsize = %d, osize = %d, nsize = %d, fs = %s\n",
189 		    ip->i_dev, fs->fs_bsize, osize, nsize, fs->fs_fsmnt);
190 		panic("ffs_realloccg: bad size");
191 	}
192 	if (cred == NOCRED)
193 		panic("ffs_realloccg: missing credential");
194 #endif /* DIAGNOSTIC */
195 	if (cred->cr_uid != 0 && freespace(fs, fs->fs_minfree) <= 0)
196 		goto nospace;
197 
198 	bprev = DIP(ip, db[lbprev]);
199 
200 	if (bprev == 0) {
201 		printf("dev = 0x%x, bsize = %d, bprev = %lld, fs = %s\n",
202 		    ip->i_dev, fs->fs_bsize, (long long)bprev, fs->fs_fsmnt);
203 		panic("ffs_realloccg: bad bprev");
204 	}
205 
206 	/*
207 	 * Allocate the extra space in the buffer.
208 	 */
209 	if (bpp != NULL) {
210 		if ((error = bread(ITOV(ip), lbprev, fs->fs_bsize, &bp)) != 0)
211 			goto error;
212 		buf_adjcnt(bp, osize);
213 	}
214 
215 	if ((error = ufs_quota_alloc_blocks(ip, btodb(nsize - osize), cred))
216 	    != 0)
217 		goto error;
218 
219 	quota_updated = btodb(nsize - osize);
220 
221 	/*
222 	 * Check for extension in the existing location.
223 	 */
224 	cg = dtog(fs, bprev);
225 	if ((bno = ffs_fragextend(ip, cg, bprev, osize, nsize)) != 0) {
226 		DIP_ADD(ip, blocks, btodb(nsize - osize));
227 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
228 		if (bpp != NULL) {
229 			if (bp->b_blkno != fsbtodb(fs, bno))
230 				panic("ffs_realloccg: bad blockno");
231 #ifdef DIAGNOSTIC
232 			if (nsize > bp->b_bufsize)
233 				panic("ffs_realloccg: small buf");
234 #endif
235 			buf_adjcnt(bp, nsize);
236 			bp->b_flags |= B_DONE;
237 			memset(bp->b_data + osize, 0, nsize - osize);
238 			*bpp = bp;
239 		}
240 		if (blknop != NULL) {
241 			*blknop = bno;
242 		}
243 		return (0);
244 	}
245 	/*
246 	 * Allocate a new disk location.
247 	 */
248 	if (bpref >= fs->fs_size)
249 		bpref = 0;
250 	switch (fs->fs_optim) {
251 	case FS_OPTSPACE:
252 		/*
253 		 * Allocate an exact sized fragment. Although this makes
254 		 * best use of space, we will waste time relocating it if
255 		 * the file continues to grow. If the fragmentation is
256 		 * less than half of the minimum free reserve, we choose
257 		 * to begin optimizing for time.
258 		 */
259 		request = nsize;
260 		if (fs->fs_minfree < 5 ||
261 		    fs->fs_cstotal.cs_nffree >
262 		    fs->fs_dsize * fs->fs_minfree / (2 * 100))
263 			break;
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 		fs->fs_optim = FS_OPTSPACE;
282 		break;
283 	default:
284 		printf("dev = 0x%x, optim = %d, fs = %s\n",
285 		    ip->i_dev, fs->fs_optim, fs->fs_fsmnt);
286 		panic("ffs_realloccg: bad optim");
287 		/* NOTREACHED */
288 	}
289 	bno = ffs_hashalloc(ip, cg, bpref, request, ffs_alloccg);
290 	if (bno <= 0)
291 		goto nospace;
292 
293 	(void) uvm_vnp_uncache(ITOV(ip));
294 	ffs_blkfree(ip, bprev, (long)osize);
295 	if (nsize < request)
296 		ffs_blkfree(ip, bno + numfrags(fs, nsize),
297 		    (long)(request - nsize));
298 	DIP_ADD(ip, blocks, btodb(nsize - osize));
299 	ip->i_flag |= IN_CHANGE | IN_UPDATE;
300 	if (bpp != NULL) {
301 		bp->b_blkno = fsbtodb(fs, bno);
302 #ifdef DIAGNOSTIC
303 		if (nsize > bp->b_bufsize)
304 			panic("ffs_realloccg: small buf 2");
305 #endif
306 		buf_adjcnt(bp, nsize);
307 		bp->b_flags |= B_DONE;
308 		memset(bp->b_data + osize, 0, nsize - osize);
309 		*bpp = bp;
310 	}
311 	if (blknop != NULL) {
312 		*blknop = bno;
313 	}
314 	return (0);
315 
316 nospace:
317 	if (ratecheck(&fsfull_last, &fserr_interval)) {
318 		ffs_fserr(fs, cred->cr_uid, "file system full");
319 		uprintf("\n%s: write failed, file system is full\n",
320 		    fs->fs_fsmnt);
321 	}
322 	error = ENOSPC;
323 
324 error:
325 	if (bp != NULL) {
326 		brelse(bp);
327 		bp = NULL;
328 	}
329 
330  	/*
331 	 * Restore user's disk quota because allocation failed.
332 	 */
333 	if (quota_updated != 0)
334 		(void)ufs_quota_free_blocks(ip, quota_updated, cred);
335 
336 	return error;
337 }
338 
339 /*
340  * Allocate an inode in the file system.
341  *
342  * If allocating a directory, use ffs_dirpref to select the inode.
343  * If allocating in a directory, the following hierarchy is followed:
344  *   1) allocate the preferred inode.
345  *   2) allocate an inode in the same cylinder group.
346  *   3) quadratically rehash into other cylinder groups, until an
347  *      available inode is located.
348  * If no inode preference is given the following hierarchy is used
349  * to allocate an inode:
350  *   1) allocate an inode in cylinder group 0.
351  *   2) quadratically rehash into other cylinder groups, until an
352  *      available inode is located.
353  */
354 int
ffs_inode_alloc(struct inode * pip,mode_t mode,struct ucred * cred,struct vnode ** vpp)355 ffs_inode_alloc(struct inode *pip, mode_t mode, struct ucred *cred,
356     struct vnode **vpp)
357 {
358 	static struct timeval fsnoinodes_last;
359 	struct vnode *pvp = ITOV(pip);
360 	struct fs *fs;
361 	struct inode *ip;
362 	ufsino_t ino, ipref;
363 	u_int cg;
364 	int error;
365 
366 	*vpp = NULL;
367 	fs = pip->i_fs;
368 	if (fs->fs_cstotal.cs_nifree == 0)
369 		goto noinodes;
370 
371 	if ((mode & IFMT) == IFDIR)
372 		ipref = ffs_dirpref(pip);
373 	else
374 		ipref = pip->i_number;
375 	if (ipref >= fs->fs_ncg * fs->fs_ipg)
376 		ipref = 0;
377 	cg = ino_to_cg(fs, ipref);
378 
379 	/*
380 	 * Track number of dirs created one after another
381 	 * in a same cg without intervening by files.
382 	 */
383 	if ((mode & IFMT) == IFDIR) {
384 		if (fs->fs_contigdirs[cg] < 255)
385 			fs->fs_contigdirs[cg]++;
386 	} else {
387 		if (fs->fs_contigdirs[cg] > 0)
388 			fs->fs_contigdirs[cg]--;
389 	}
390 	ino = (ufsino_t)ffs_hashalloc(pip, cg, ipref, mode, ffs_nodealloccg);
391 	if (ino == 0)
392 		goto noinodes;
393 	error = VFS_VGET(pvp->v_mount, ino, vpp);
394 	if (error) {
395 		ffs_inode_free(pip, ino, mode);
396 		return (error);
397 	}
398 
399 	ip = VTOI(*vpp);
400 
401 	if (DIP(ip, mode)) {
402 		printf("mode = 0%o, inum = %u, fs = %s\n",
403 		    DIP(ip, mode), ip->i_number, fs->fs_fsmnt);
404 		panic("ffs_valloc: dup alloc");
405 	}
406 
407 	if (DIP(ip, blocks)) {
408 		printf("free inode %s/%d had %lld blocks\n",
409 		    fs->fs_fsmnt, ino, (long long)DIP(ip, blocks));
410 		DIP_ASSIGN(ip, blocks, 0);
411 	}
412 
413 	DIP_ASSIGN(ip, flags, 0);
414 
415 	/*
416 	 * Set up a new generation number for this inode.
417 	 * On wrap, we make sure to assign a number != 0 and != UINT_MAX
418 	 * (the original value).
419 	 */
420 	if (DIP(ip, gen) != 0)
421 		DIP_ADD(ip, gen, 1);
422 	while (DIP(ip, gen) == 0)
423 		DIP_ASSIGN(ip, gen, arc4random_uniform(UINT_MAX));
424 
425 	return (0);
426 
427 noinodes:
428 	if (ratecheck(&fsnoinodes_last, &fserr_interval)) {
429 		ffs_fserr(fs, cred->cr_uid, "out of inodes");
430 		uprintf("\n%s: create/symlink failed, no inodes free\n",
431 		    fs->fs_fsmnt);
432 	}
433 	return (ENOSPC);
434 }
435 
436 /*
437  * Find a cylinder group to place a directory.
438  *
439  * The policy implemented by this algorithm is to allocate a
440  * directory inode in the same cylinder group as its parent
441  * directory, but also to reserve space for its files inodes
442  * and data. Restrict the number of directories which may be
443  * allocated one after another in the same cylinder group
444  * without intervening allocation of files.
445  *
446  * If we allocate a first level directory then force allocation
447  * in another cylinder group.
448  */
449 ufsino_t
ffs_dirpref(struct inode * pip)450 ffs_dirpref(struct inode *pip)
451 {
452 	struct fs *fs;
453 	u_int	cg, prefcg;
454 	u_int	dirsize, cgsize;
455 	u_int	avgifree, avgbfree, avgndir, curdirsize;
456 	u_int	minifree, minbfree, maxndir;
457 	u_int	mincg, minndir;
458 	u_int	maxcontigdirs;
459 
460 	fs = pip->i_fs;
461 
462 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
463 	avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
464 	avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
465 
466 	/*
467 	 * Force allocation in another cg if creating a first level dir.
468 	 */
469 	if (ITOV(pip)->v_flag & VROOT) {
470 		prefcg = arc4random_uniform(fs->fs_ncg);
471 		mincg = prefcg;
472 		minndir = fs->fs_ipg;
473 		for (cg = prefcg; cg < fs->fs_ncg; cg++)
474 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
475 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
476 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
477 				mincg = cg;
478 				minndir = fs->fs_cs(fs, cg).cs_ndir;
479 			}
480 		for (cg = 0; cg < prefcg; cg++)
481 			if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
482 			    fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
483 			    fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
484 				mincg = cg;
485 				minndir = fs->fs_cs(fs, cg).cs_ndir;
486 			}
487 		cg = mincg;
488 		goto end;
489 	} else
490 		prefcg = ino_to_cg(fs, pip->i_number);
491 
492 	/*
493 	 * Count various limits which used for
494 	 * optimal allocation of a directory inode.
495 	 */
496 	maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
497 	minifree = avgifree - (avgifree / 4);
498 	if (minifree < 1)
499 		minifree = 1;
500 	minbfree = avgbfree - (avgbfree / 4);
501 	if (minbfree < 1)
502 		minbfree = 1;
503 
504 	cgsize = fs->fs_fsize * fs->fs_fpg;
505 	dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
506 	curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
507 	if (dirsize < curdirsize)
508 		dirsize = curdirsize;
509 	if (dirsize <= 0)
510 		maxcontigdirs = 0;		/* dirsize overflowed */
511 	else
512 		maxcontigdirs = min(avgbfree * fs->fs_bsize  / dirsize, 255);
513 	if (fs->fs_avgfpdir > 0)
514 		maxcontigdirs = min(maxcontigdirs,
515 				    fs->fs_ipg / fs->fs_avgfpdir);
516 	if (maxcontigdirs == 0)
517 		maxcontigdirs = 1;
518 
519 	/*
520 	 * Limit number of dirs in one cg and reserve space for
521 	 * regular files, but only if we have no deficit in
522 	 * inodes or space.
523 	 *
524 	 * We are trying to find a suitable cylinder group nearby
525 	 * our preferred cylinder group to place a new directory.
526 	 * We scan from our preferred cylinder group forward looking
527 	 * for a cylinder group that meets our criterion. If we get
528 	 * to the final cylinder group and do not find anything,
529 	 * we start scanning forwards from the beginning of the
530 	 * filesystem. While it might seem sensible to start scanning
531 	 * backwards or even to alternate looking forward and backward,
532 	 * this approach fails badly when the filesystem is nearly full.
533 	 * Specifically, we first search all the areas that have no space
534 	 * and finally try the one preceding that. We repeat this on
535 	 * every request and in the case of the final block end up
536 	 * searching the entire filesystem. By jumping to the front
537 	 * of the filesystem, our future forward searches always look
538 	 * in new cylinder groups so finds every possible block after
539 	 * one pass over the filesystem.
540 	 */
541 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
542 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
543 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
544 	    	    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
545 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
546 				goto end;
547 		}
548 	for (cg = 0; cg < prefcg; cg++)
549 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
550 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
551 	    	    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
552 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
553 				goto end;
554 		}
555 	/*
556 	 * This is a backstop when we have deficit in space.
557 	 */
558 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
559 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
560 			goto end;
561 	for (cg = 0; cg < prefcg; cg++)
562 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
563 			goto end;
564 end:
565 	return ((ufsino_t)(fs->fs_ipg * cg));
566 }
567 
568 /*
569  * Select the desired position for the next block in a file.  The file is
570  * logically divided into sections. The first section is composed of the
571  * direct blocks. Each additional section contains fs_maxbpg blocks.
572  *
573  * If no blocks have been allocated in the first section, the policy is to
574  * request a block in the same cylinder group as the inode that describes
575  * the file. The first indirect is allocated immediately following the last
576  * direct block and the data blocks for the first indirect immediately
577  * follow it.
578  *
579  * If no blocks have been allocated in any other section, the indirect
580  * block(s) are allocated in the same cylinder group as its inode in an
581  * area reserved immediately following the inode blocks. The policy for
582  * the data blocks is to place them in a cylinder group with a greater than
583  * average number of free blocks. An appropriate cylinder group is found
584  * by using a rotor that sweeps the cylinder groups. When a new group of
585  * blocks is needed, the sweep begins in the cylinder group following the
586  * cylinder group from which the previous allocation was made. The sweep
587  * continues until a cylinder group with greater than the average number
588  * of free blocks is found. If the allocation is for the first block in an
589  * indirect block, the information on the previous allocation is unavailable;
590  * here a best guess is made based upon the logical block number being
591  * allocated.
592  */
593 int32_t
ffs1_blkpref(struct inode * ip,daddr_t lbn,int indx,int32_t * bap)594 ffs1_blkpref(struct inode *ip, daddr_t lbn, int indx, int32_t *bap)
595 {
596 	struct fs *fs;
597 	u_int cg, inocg;
598 	u_int avgbfree, startcg;
599 	uint32_t pref;
600 
601 	KASSERT(indx <= 0 || bap != NULL);
602 	fs = ip->i_fs;
603 	/*
604 	 * Allocation of indirect blocks is indicated by passing negative
605 	 * values in indx: -1 for single indirect, -2 for double indirect,
606 	 * -3 for triple indirect. As noted below, we attempt to allocate
607 	 * the first indirect inline with the file data. For all later
608 	 * indirect blocks, the data is often allocated in other cylinder
609 	 * groups. However to speed random file access and to speed up
610 	 * fsck, the filesystem reserves the first fs_metaspace blocks
611 	 * (typically half of fs_minfree) of the data area of each cylinder
612 	 * group to hold these later indirect blocks.
613 	 */
614 	inocg = ino_to_cg(fs, ip->i_number);
615 	if (indx < 0) {
616 		/*
617 		 * Our preference for indirect blocks is the zone at the
618 		 * beginning of the inode's cylinder group data area that
619 		 * we try to reserve for indirect blocks.
620 		 */
621 		pref = cgmeta(fs, inocg);
622 		/*
623 		 * If we are allocating the first indirect block, try to
624 		 * place it immediately following the last direct block.
625 		 */
626 		if (indx == -1 && lbn < NDADDR + NINDIR(fs) &&
627 		    ip->i_din1->di_db[NDADDR - 1] != 0)
628 			pref = ip->i_din1->di_db[NDADDR - 1] + fs->fs_frag;
629 		return (pref);
630 	}
631 	/*
632 	 * If we are allocating the first data block in the first indirect
633 	 * block and the indirect has been allocated in the data block area,
634 	 * try to place it immediately following the indirect block.
635 	 */
636 	if (lbn == NDADDR) {
637 		pref = ip->i_din1->di_ib[0];
638 		if (pref != 0 && pref >= cgdata(fs, inocg) &&
639 		    pref < cgbase(fs, inocg + 1))
640 			return (pref + fs->fs_frag);
641 	}
642 	/*
643 	 * If we are the beginning of a file, or we have already allocated
644 	 * the maximum number of blocks per cylinder group, or we do not
645 	 * have a block allocated immediately preceding us, then we need
646 	 * to decide where to start allocating new blocks.
647 	 */
648 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
649 		/*
650 		 * If we are allocating a directory data block, we want
651 		 * to place it in the metadata area.
652 		 */
653 		if ((DIP(ip, mode) & IFMT) == IFDIR)
654 			return (cgmeta(fs, inocg));
655 		/*
656 		 * Until we fill all the direct and all the first indirect's
657 		 * blocks, we try to allocate in the data area of the inode's
658 		 * cylinder group.
659 		 */
660 		if (lbn < NDADDR + NINDIR(fs))
661 			return (cgdata(fs, inocg));
662 		/*
663 		 * Find a cylinder with greater than average number of
664 		 * unused data blocks.
665 		 */
666 		if (indx == 0 || bap[indx - 1] == 0)
667 			startcg = inocg + lbn / fs->fs_maxbpg;
668 		else
669 			startcg = dtog(fs, bap[indx - 1]) + 1;
670 		startcg %= fs->fs_ncg;
671 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
672 		for (cg = startcg; cg < fs->fs_ncg; cg++)
673 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
674 				fs->fs_cgrotor = cg;
675 				return (cgdata(fs, cg));
676 			}
677 		for (cg = 0; cg <= startcg; cg++)
678 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
679 				fs->fs_cgrotor = cg;
680 				return (cgdata(fs, cg));
681 			}
682 		return (0);
683 	}
684 	/*
685 	 * Otherwise, we just always try to lay things out contiguously.
686 	 */
687 	return (bap[indx - 1] + fs->fs_frag);
688 }
689 
690 /*
691  * Same as above, for UFS2.
692  */
693 #ifdef FFS2
694 int64_t
ffs2_blkpref(struct inode * ip,daddr_t lbn,int indx,int64_t * bap)695 ffs2_blkpref(struct inode *ip, daddr_t lbn, int indx, int64_t *bap)
696 {
697 	struct fs *fs;
698 	u_int cg, inocg;
699 	u_int avgbfree, startcg;
700 	uint64_t pref;
701 
702 	KASSERT(indx <= 0 || bap != NULL);
703 	fs = ip->i_fs;
704 	/*
705 	 * Allocation of indirect blocks is indicated by passing negative
706 	 * values in indx: -1 for single indirect, -2 for double indirect,
707 	 * -3 for triple indirect. As noted below, we attempt to allocate
708 	 * the first indirect inline with the file data. For all later
709 	 * indirect blocks, the data is often allocated in other cylinder
710 	 * groups. However to speed random file access and to speed up
711 	 * fsck, the filesystem reserves the first fs_metaspace blocks
712 	 * (typically half of fs_minfree) of the data area of each cylinder
713 	 * group to hold these later indirect blocks.
714 	 */
715 	inocg = ino_to_cg(fs, ip->i_number);
716 	if (indx < 0) {
717 		/*
718 		 * Our preference for indirect blocks is the zone at the
719 		 * beginning of the inode's cylinder group data area that
720 		 * we try to reserve for indirect blocks.
721 		 */
722 		pref = cgmeta(fs, inocg);
723 		/*
724 		 * If we are allocating the first indirect block, try to
725 		 * place it immediately following the last direct block.
726 		 */
727 		if (indx == -1 && lbn < NDADDR + NINDIR(fs) &&
728 		    ip->i_din2->di_db[NDADDR - 1] != 0)
729 			pref = ip->i_din2->di_db[NDADDR - 1] + fs->fs_frag;
730 		return (pref);
731 	}
732 	/*
733 	 * If we are allocating the first data block in the first indirect
734 	 * block and the indirect has been allocated in the data block area,
735 	 * try to place it immediately following the indirect block.
736 	 */
737 	if (lbn == NDADDR) {
738 		pref = ip->i_din2->di_ib[0];
739 		if (pref != 0 && pref >= cgdata(fs, inocg) &&
740 		    pref < cgbase(fs, inocg + 1))
741 			return (pref + fs->fs_frag);
742 	}
743 	/*
744 	 * If we are the beginning of a file, or we have already allocated
745 	 * the maximum number of blocks per cylinder group, or we do not
746 	 * have a block allocated immediately preceding us, then we need
747 	 * to decide where to start allocating new blocks.
748 	 */
749 
750 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
751 		/*
752 		 * If we are allocating a directory data block, we want
753 		 * to place it in the metadata area.
754 		 */
755 		if ((DIP(ip, mode) & IFMT) == IFDIR)
756 			return (cgmeta(fs, inocg));
757 		/*
758 		 * Until we fill all the direct and all the first indirect's
759 		 * blocks, we try to allocate in the data area of the inode's
760 		 * cylinder group.
761 		 */
762 		if (lbn < NDADDR + NINDIR(fs))
763 			return (cgdata(fs, inocg));
764 		/*
765 		 * Find a cylinder with greater than average number of
766 		 * unused data blocks.
767 		 */
768 		if (indx == 0 || bap[indx - 1] == 0)
769 			startcg = inocg + lbn / fs->fs_maxbpg;
770 		else
771 			startcg = dtog(fs, bap[indx - 1] + 1);
772 
773 		startcg %= fs->fs_ncg;
774 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
775 
776 		for (cg = startcg; cg < fs->fs_ncg; cg++)
777 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree)
778 				return (cgbase(fs, cg) + fs->fs_frag);
779 
780 		for (cg = 0; cg < startcg; cg++)
781 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree)
782 				return (cgbase(fs, cg) + fs->fs_frag);
783 
784 		return (0);
785 	}
786 
787 	/*
788 	 * Otherwise, we just always try to lay things out contiguously.
789 	 */
790 	return (bap[indx - 1] + fs->fs_frag);
791 }
792 #endif /* FFS2 */
793 
794 /*
795  * Implement the cylinder overflow algorithm.
796  *
797  * The policy implemented by this algorithm is:
798  *   1) allocate the block in its requested cylinder group.
799  *   2) quadratically rehash on the cylinder group number.
800  *   3) brute force search for a free block.
801  */
802 daddr_t
ffs_hashalloc(struct inode * ip,u_int cg,daddr_t pref,int size,daddr_t (* allocator)(struct inode *,u_int,daddr_t,int))803 ffs_hashalloc(struct inode *ip, u_int cg, daddr_t pref, int size,
804     daddr_t (*allocator)(struct inode *, u_int, daddr_t, int))
805 {
806 	struct fs *fs;
807 	daddr_t result;
808 	u_int i, icg = cg;
809 
810 	fs = ip->i_fs;
811 	/*
812 	 * 1: preferred cylinder group
813 	 */
814 	result = (*allocator)(ip, cg, pref, size);
815 	if (result)
816 		return (result);
817 	/*
818 	 * 2: quadratic rehash
819 	 */
820 	for (i = 1; i < fs->fs_ncg; i *= 2) {
821 		cg += i;
822 		if (cg >= fs->fs_ncg)
823 			cg -= fs->fs_ncg;
824 		result = (*allocator)(ip, cg, 0, size);
825 		if (result)
826 			return (result);
827 	}
828 	/*
829 	 * 3: brute force search
830 	 * Note that we start at i == 2, since 0 was checked initially,
831 	 * and 1 is always checked in the quadratic rehash.
832 	 */
833 	cg = (icg + 2) % fs->fs_ncg;
834 	for (i = 2; i < fs->fs_ncg; i++) {
835 		result = (*allocator)(ip, cg, 0, size);
836 		if (result)
837 			return (result);
838 		cg++;
839 		if (cg == fs->fs_ncg)
840 			cg = 0;
841 	}
842 	return (0);
843 }
844 
845 struct buf *
ffs_cgread(struct fs * fs,struct inode * ip,u_int cg)846 ffs_cgread(struct fs *fs, struct inode *ip, u_int cg)
847 {
848 	struct buf *bp;
849 
850 	if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
851 	    (int)fs->fs_cgsize, &bp)) {
852 		brelse(bp);
853 		return (NULL);
854 	}
855 
856 	if (!cg_chkmagic((struct cg *)bp->b_data)) {
857 		brelse(bp);
858 		return (NULL);
859 	}
860 
861 	return bp;
862 }
863 
864 /*
865  * Determine whether a fragment can be extended.
866  *
867  * Check to see if the necessary fragments are available, and
868  * if they are, allocate them.
869  */
870 daddr_t
ffs_fragextend(struct inode * ip,u_int cg,daddr_t bprev,int osize,int nsize)871 ffs_fragextend(struct inode *ip, u_int cg, daddr_t bprev, int osize, int nsize)
872 {
873 	struct fs *fs;
874 	struct cg *cgp;
875 	struct buf *bp;
876 	struct timespec now;
877 	daddr_t bno;
878 	int i, frags, bbase;
879 
880 	fs = ip->i_fs;
881 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
882 		return (0);
883 	frags = numfrags(fs, nsize);
884 	bbase = fragnum(fs, bprev);
885 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
886 		/* cannot extend across a block boundary */
887 		return (0);
888 	}
889 
890 	if (!(bp = ffs_cgread(fs, ip, cg)))
891 		return (0);
892 
893 	cgp = (struct cg *)bp->b_data;
894 	nanotime(&now);
895 	cgp->cg_ffs2_time = now.tv_sec;
896 	cgp->cg_time = now.tv_sec;
897 
898 	bno = dtogd(fs, bprev);
899 	for (i = numfrags(fs, osize); i < frags; i++)
900 		if (isclr(cg_blksfree(cgp), bno + i)) {
901 			brelse(bp);
902 			return (0);
903 		}
904 	/*
905 	 * the current fragment can be extended
906 	 * deduct the count on fragment being extended into
907 	 * increase the count on the remaining fragment (if any)
908 	 * allocate the extended piece
909 	 */
910 	for (i = frags; i < fs->fs_frag - bbase; i++)
911 		if (isclr(cg_blksfree(cgp), bno + i))
912 			break;
913 	cgp->cg_frsum[i - numfrags(fs, osize)]--;
914 	if (i != frags)
915 		cgp->cg_frsum[i - frags]++;
916 	for (i = numfrags(fs, osize); i < frags; i++) {
917 		clrbit(cg_blksfree(cgp), bno + i);
918 		cgp->cg_cs.cs_nffree--;
919 		fs->fs_cstotal.cs_nffree--;
920 		fs->fs_cs(fs, cg).cs_nffree--;
921 	}
922 	fs->fs_fmod = 1;
923 
924 	bdwrite(bp);
925 	return (bprev);
926 }
927 
928 /*
929  * Determine whether a block can be allocated.
930  *
931  * Check to see if a block of the appropriate size is available,
932  * and if it is, allocate it.
933  */
934 daddr_t
ffs_alloccg(struct inode * ip,u_int cg,daddr_t bpref,int size)935 ffs_alloccg(struct inode *ip, u_int cg, daddr_t bpref, int size)
936 {
937 	struct fs *fs;
938 	struct cg *cgp;
939 	struct buf *bp;
940 	struct timespec now;
941 	daddr_t bno, blkno;
942 	int i, frags, allocsiz;
943 
944 	fs = ip->i_fs;
945 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
946 		return (0);
947 
948 	if (!(bp = ffs_cgread(fs, ip, cg)))
949 		return (0);
950 
951 	cgp = (struct cg *)bp->b_data;
952 	if (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize) {
953 		brelse(bp);
954 		return (0);
955 	}
956 
957 	nanotime(&now);
958 	cgp->cg_ffs2_time = now.tv_sec;
959 	cgp->cg_time = now.tv_sec;
960 
961 	if (size == fs->fs_bsize) {
962 		/* allocate and return a complete data block */
963 		bno = ffs_alloccgblk(ip, bp, bpref);
964 		bdwrite(bp);
965 		return (bno);
966 	}
967 	/*
968 	 * check to see if any fragments are already available
969 	 * allocsiz is the size which will be allocated, hacking
970 	 * it down to a smaller size if necessary
971 	 */
972 	frags = numfrags(fs, size);
973 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
974 		if (cgp->cg_frsum[allocsiz] != 0)
975 			break;
976 	if (allocsiz == fs->fs_frag) {
977 		/*
978 		 * no fragments were available, so a block will be
979 		 * allocated, and hacked up
980 		 */
981 		if (cgp->cg_cs.cs_nbfree == 0) {
982 			brelse(bp);
983 			return (0);
984 		}
985 		bno = ffs_alloccgblk(ip, bp, bpref);
986 		bpref = dtogd(fs, bno);
987 		for (i = frags; i < fs->fs_frag; i++)
988 			setbit(cg_blksfree(cgp), bpref + i);
989 		i = fs->fs_frag - frags;
990 		cgp->cg_cs.cs_nffree += i;
991 		fs->fs_cstotal.cs_nffree += i;
992 		fs->fs_cs(fs, cg).cs_nffree += i;
993 		fs->fs_fmod = 1;
994 		cgp->cg_frsum[i]++;
995 		bdwrite(bp);
996 		return (bno);
997 	}
998 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
999 	if (bno < 0) {
1000 		brelse(bp);
1001 		return (0);
1002 	}
1003 
1004 	for (i = 0; i < frags; i++)
1005 		clrbit(cg_blksfree(cgp), bno + i);
1006 	cgp->cg_cs.cs_nffree -= frags;
1007 	fs->fs_cstotal.cs_nffree -= frags;
1008 	fs->fs_cs(fs, cg).cs_nffree -= frags;
1009 	fs->fs_fmod = 1;
1010 	cgp->cg_frsum[allocsiz]--;
1011 	if (frags != allocsiz)
1012 		cgp->cg_frsum[allocsiz - frags]++;
1013 
1014 	blkno = cgbase(fs, cg) + bno;
1015 	bdwrite(bp);
1016 	return (blkno);
1017 }
1018 
1019 /*
1020  * Allocate a block in a cylinder group.
1021  * Note that this routine only allocates fs_bsize blocks; these
1022  * blocks may be fragmented by the routine that allocates them.
1023  */
1024 daddr_t
ffs_alloccgblk(struct inode * ip,struct buf * bp,daddr_t bpref)1025 ffs_alloccgblk(struct inode *ip, struct buf *bp, daddr_t bpref)
1026 {
1027 	struct fs *fs;
1028 	struct cg *cgp;
1029 	daddr_t bno, blkno;
1030 	u_int8_t *blksfree;
1031 	int cylno, cgbpref;
1032 
1033 	fs = ip->i_fs;
1034 	cgp = (struct cg *) bp->b_data;
1035 	blksfree = cg_blksfree(cgp);
1036 
1037 	if (bpref == 0) {
1038 		bpref = cgp->cg_rotor;
1039 	} else if ((cgbpref = dtog(fs, bpref)) != cgp->cg_cgx) {
1040 		/* map bpref to correct zone in this cg */
1041 		if (bpref < cgdata(fs, cgbpref))
1042 			bpref = cgmeta(fs, cgp->cg_cgx);
1043 		else
1044 			bpref = cgdata(fs, cgp->cg_cgx);
1045 	}
1046 	/*
1047 	 * If the requested block is available, use it.
1048 	 */
1049 	bno = dtogd(fs, blknum(fs, bpref));
1050 	if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
1051 		goto gotit;
1052 	/*
1053 	 * Take the next available block in this cylinder group.
1054 	 */
1055 	bno = ffs_mapsearch(fs, cgp, bpref, (int) fs->fs_frag);
1056 	if (bno < 0)
1057 		return (0);
1058 
1059 	/* Update cg_rotor only if allocated from the data zone */
1060 	if (bno >= dtogd(fs, cgdata(fs, cgp->cg_cgx)))
1061 		cgp->cg_rotor = bno;
1062 
1063 gotit:
1064 	blkno = fragstoblks(fs, bno);
1065 	ffs_clrblock(fs, blksfree, blkno);
1066 	ffs_clusteracct(fs, cgp, blkno, -1);
1067 	cgp->cg_cs.cs_nbfree--;
1068 	fs->fs_cstotal.cs_nbfree--;
1069 	fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1070 
1071 	if (fs->fs_magic != FS_UFS2_MAGIC) {
1072 		cylno = cbtocylno(fs, bno);
1073 		cg_blks(fs, cgp, cylno)[cbtorpos(fs, bno)]--;
1074 		cg_blktot(cgp)[cylno]--;
1075 	}
1076 
1077 	fs->fs_fmod = 1;
1078 	blkno = cgbase(fs, cgp->cg_cgx) + bno;
1079 
1080 	return (blkno);
1081 }
1082 
1083 /* inode allocation routine */
1084 daddr_t
ffs_nodealloccg(struct inode * ip,u_int cg,daddr_t ipref,int mode)1085 ffs_nodealloccg(struct inode *ip, u_int cg, daddr_t ipref, int mode)
1086 {
1087 	struct fs *fs;
1088 	struct cg *cgp;
1089 	struct buf *bp;
1090 	struct timespec now;
1091 	int start, len, loc, map, i;
1092 #ifdef FFS2
1093 	struct buf *ibp = NULL;
1094 	struct ufs2_dinode *dp2;
1095 #endif
1096 
1097 	/*
1098 	 * For efficiency, before looking at the bitmaps for free inodes,
1099 	 * check the counters kept in the superblock cylinder group summaries,
1100 	 * and in the cylinder group itself.
1101 	 */
1102 	fs = ip->i_fs;
1103 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
1104 		return (0);
1105 
1106 	if (!(bp = ffs_cgread(fs, ip, cg)))
1107 		return (0);
1108 
1109 	cgp = (struct cg *)bp->b_data;
1110 	if (cgp->cg_cs.cs_nifree == 0) {
1111 		brelse(bp);
1112 		return (0);
1113 	}
1114 
1115 	/*
1116 	 * We are committed to the allocation from now on, so update the time
1117 	 * on the cylinder group.
1118 	 */
1119 	nanotime(&now);
1120 	cgp->cg_ffs2_time = now.tv_sec;
1121 	cgp->cg_time = now.tv_sec;
1122 
1123 	/*
1124 	 * If there was a preferred location for the new inode, try to find it.
1125 	 */
1126 	if (ipref) {
1127 		ipref %= fs->fs_ipg;
1128 		if (isclr(cg_inosused(cgp), ipref))
1129 			goto gotit; /* inode is free, grab it. */
1130 	}
1131 
1132 	/*
1133 	 * Otherwise, look for the next available inode, starting at cg_irotor
1134 	 * (the position in the bitmap of the last used inode).
1135 	 */
1136 	start = cgp->cg_irotor / NBBY;
1137 	len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
1138 	loc = skpc(0xff, len, &cg_inosused(cgp)[start]);
1139 	if (loc == 0) {
1140 		/*
1141 		 * If we didn't find a free inode in the upper part of the
1142 		 * bitmap (from cg_irotor to the end), then look at the bottom
1143 		 * part (from 0 to cg_irotor).
1144 		 */
1145 		len = start + 1;
1146 		start = 0;
1147 		loc = skpc(0xff, len, &cg_inosused(cgp)[0]);
1148 		if (loc == 0) {
1149 			/*
1150 			 * If we failed again, then either the bitmap or the
1151 			 * counters kept for the cylinder group are wrong.
1152 			 */
1153 			printf("cg = %d, irotor = %d, fs = %s\n",
1154 			    cg, cgp->cg_irotor, fs->fs_fsmnt);
1155 			panic("ffs_nodealloccg: map corrupted");
1156 			/* NOTREACHED */
1157 		}
1158 	}
1159 
1160 	/* skpc() returns the position relative to the end */
1161 	i = start + len - loc;
1162 
1163 	/*
1164 	 * Okay, so now in 'i' we have the location in the bitmap of a byte
1165 	 * holding a free inode. Find the corresponding bit and set it,
1166 	 * updating cg_irotor as well, accordingly.
1167 	 */
1168 	map = cg_inosused(cgp)[i];
1169 	ipref = i * NBBY;
1170 	for (i = 1; i < (1 << NBBY); i <<= 1, ipref++) {
1171 		if ((map & i) == 0) {
1172 			cgp->cg_irotor = ipref;
1173 			goto gotit;
1174 		}
1175 	}
1176 
1177 	printf("fs = %s\n", fs->fs_fsmnt);
1178 	panic("ffs_nodealloccg: block not in map");
1179 	/* NOTREACHED */
1180 
1181 gotit:
1182 
1183 #ifdef FFS2
1184 	/*
1185 	 * For FFS2, check if all inodes in this cylinder group have been used
1186 	 * at least once. If they haven't, and we are allocating an inode past
1187 	 * the last allocated block of inodes, read in a block and initialize
1188 	 * all inodes in it.
1189 	 */
1190 	if (fs->fs_magic == FS_UFS2_MAGIC &&
1191 	    /* Inode is beyond last initialized block of inodes? */
1192 	    ipref + INOPB(fs) > cgp->cg_initediblk &&
1193 	    /* Has any inode not been used at least once? */
1194 	    cgp->cg_initediblk < cgp->cg_ffs2_niblk) {
1195 
1196                 ibp = getblk(ip->i_devvp, fsbtodb(fs,
1197                     ino_to_fsba(fs, cg * fs->fs_ipg + cgp->cg_initediblk)),
1198                     (int)fs->fs_bsize, 0, INFSLP);
1199 
1200                 memset(ibp->b_data, 0, fs->fs_bsize);
1201                 dp2 = (struct ufs2_dinode *)(ibp->b_data);
1202 
1203 		/* Give each inode a generation number */
1204                 for (i = 0; i < INOPB(fs); i++) {
1205                         while (dp2->di_gen == 0)
1206 				dp2->di_gen = arc4random();
1207                         dp2++;
1208                 }
1209 
1210 		/* Update the counter of initialized inodes */
1211                 cgp->cg_initediblk += INOPB(fs);
1212         }
1213 #endif /* FFS2 */
1214 
1215 	setbit(cg_inosused(cgp), ipref);
1216 
1217 	/* Update the counters we keep on free inodes */
1218 	cgp->cg_cs.cs_nifree--;
1219 	fs->fs_cstotal.cs_nifree--;
1220 	fs->fs_cs(fs, cg).cs_nifree--;
1221 	fs->fs_fmod = 1; /* file system was modified */
1222 
1223 	/* Update the counters we keep on allocated directories */
1224 	if ((mode & IFMT) == IFDIR) {
1225 		cgp->cg_cs.cs_ndir++;
1226 		fs->fs_cstotal.cs_ndir++;
1227 		fs->fs_cs(fs, cg).cs_ndir++;
1228 	}
1229 
1230 	bdwrite(bp);
1231 
1232 #ifdef FFS2
1233 	if (ibp != NULL)
1234 		bawrite(ibp);
1235 #endif
1236 
1237 	/* Return the allocated inode number */
1238 	return (cg * fs->fs_ipg + ipref);
1239 }
1240 
1241 /*
1242  * Free a block or fragment.
1243  *
1244  * The specified block or fragment is placed back in the
1245  * free map. If a fragment is deallocated, a possible
1246  * block reassembly is checked.
1247  */
1248 void
ffs_blkfree(struct inode * ip,daddr_t bno,long size)1249 ffs_blkfree(struct inode *ip, daddr_t bno, long size)
1250 {
1251 	struct fs *fs;
1252 	struct cg *cgp;
1253 	struct buf *bp;
1254 	struct timespec now;
1255 	daddr_t blkno;
1256 	int i, cg, blk, frags, bbase;
1257 
1258 	fs = ip->i_fs;
1259 	if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
1260 	    fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
1261 		printf("dev = 0x%x, bsize = %d, size = %ld, fs = %s\n",
1262 		    ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
1263 		panic("ffs_blkfree: bad size");
1264 	}
1265 	cg = dtog(fs, bno);
1266 	if ((u_int)bno >= fs->fs_size) {
1267 		printf("bad block %lld, ino %u\n", (long long)bno,
1268 		    ip->i_number);
1269 		ffs_fserr(fs, DIP(ip, uid), "bad block");
1270 		return;
1271 	}
1272 	if (!(bp = ffs_cgread(fs, ip, cg)))
1273 		return;
1274 
1275 	cgp = (struct cg *)bp->b_data;
1276 	nanotime(&now);
1277 	cgp->cg_ffs2_time = now.tv_sec;
1278 	cgp->cg_time = now.tv_sec;
1279 
1280 	bno = dtogd(fs, bno);
1281 	if (size == fs->fs_bsize) {
1282 		blkno = fragstoblks(fs, bno);
1283 		if (!ffs_isfreeblock(fs, cg_blksfree(cgp), blkno)) {
1284 			printf("dev = 0x%x, block = %lld, fs = %s\n",
1285 			    ip->i_dev, (long long)bno, fs->fs_fsmnt);
1286 			panic("ffs_blkfree: freeing free block");
1287 		}
1288 		ffs_setblock(fs, cg_blksfree(cgp), blkno);
1289 		ffs_clusteracct(fs, cgp, blkno, 1);
1290 		cgp->cg_cs.cs_nbfree++;
1291 		fs->fs_cstotal.cs_nbfree++;
1292 		fs->fs_cs(fs, cg).cs_nbfree++;
1293 
1294 		if (fs->fs_magic != FS_UFS2_MAGIC) {
1295 			i = cbtocylno(fs, bno);
1296 			cg_blks(fs, cgp, i)[cbtorpos(fs, bno)]++;
1297 			cg_blktot(cgp)[i]++;
1298 		}
1299 
1300 	} else {
1301 		bbase = bno - fragnum(fs, bno);
1302 		/*
1303 		 * decrement the counts associated with the old frags
1304 		 */
1305 		blk = blkmap(fs, cg_blksfree(cgp), bbase);
1306 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
1307 		/*
1308 		 * deallocate the fragment
1309 		 */
1310 		frags = numfrags(fs, size);
1311 		for (i = 0; i < frags; i++) {
1312 			if (isset(cg_blksfree(cgp), bno + i)) {
1313 				printf("dev = 0x%x, block = %lld, fs = %s\n",
1314 				    ip->i_dev, (long long)(bno + i),
1315 				    fs->fs_fsmnt);
1316 				panic("ffs_blkfree: freeing free frag");
1317 			}
1318 			setbit(cg_blksfree(cgp), bno + i);
1319 		}
1320 		cgp->cg_cs.cs_nffree += i;
1321 		fs->fs_cstotal.cs_nffree += i;
1322 		fs->fs_cs(fs, cg).cs_nffree += i;
1323 		/*
1324 		 * add back in counts associated with the new frags
1325 		 */
1326 		blk = blkmap(fs, cg_blksfree(cgp), bbase);
1327 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
1328 		/*
1329 		 * if a complete block has been reassembled, account for it
1330 		 */
1331 		blkno = fragstoblks(fs, bbase);
1332 		if (ffs_isblock(fs, cg_blksfree(cgp), blkno)) {
1333 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
1334 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
1335 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
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 
1341 			if (fs->fs_magic != FS_UFS2_MAGIC) {
1342 				i = cbtocylno(fs, bbase);
1343 				cg_blks(fs, cgp, i)[cbtorpos(fs, bbase)]++;
1344 				cg_blktot(cgp)[i]++;
1345 			}
1346 		}
1347 	}
1348 	fs->fs_fmod = 1;
1349 	bdwrite(bp);
1350 }
1351 
1352 int
ffs_inode_free(struct inode * pip,ufsino_t ino,mode_t mode)1353 ffs_inode_free(struct inode *pip, ufsino_t ino, mode_t mode)
1354 {
1355 	return (ffs_freefile(pip, ino, mode));
1356 }
1357 
1358 /*
1359  * Do the actual free operation.
1360  * The specified inode is placed back in the free map.
1361  */
1362 int
ffs_freefile(struct inode * pip,ufsino_t ino,mode_t mode)1363 ffs_freefile(struct inode *pip, ufsino_t ino, mode_t mode)
1364 {
1365 	struct fs *fs;
1366 	struct cg *cgp;
1367 	struct buf *bp;
1368 	struct timespec now;
1369 	u_int cg;
1370 
1371 	fs = pip->i_fs;
1372 	if (ino >= fs->fs_ipg * fs->fs_ncg)
1373 		panic("ffs_freefile: range: dev = 0x%x, ino = %d, fs = %s",
1374 		    pip->i_dev, ino, fs->fs_fsmnt);
1375 
1376 	cg = ino_to_cg(fs, ino);
1377 	if (!(bp = ffs_cgread(fs, pip, cg)))
1378 		return (0);
1379 
1380 	cgp = (struct cg *)bp->b_data;
1381 	nanotime(&now);
1382 	cgp->cg_ffs2_time = now.tv_sec;
1383 	cgp->cg_time = now.tv_sec;
1384 
1385 	ino %= fs->fs_ipg;
1386 	if (isclr(cg_inosused(cgp), ino)) {
1387 		printf("dev = 0x%x, ino = %u, fs = %s\n",
1388 		    pip->i_dev, ino, fs->fs_fsmnt);
1389 		if (fs->fs_ronly == 0)
1390 			panic("ffs_freefile: freeing free inode");
1391 	}
1392 	clrbit(cg_inosused(cgp), ino);
1393 	if (ino < cgp->cg_irotor)
1394 		cgp->cg_irotor = ino;
1395 	cgp->cg_cs.cs_nifree++;
1396 	fs->fs_cstotal.cs_nifree++;
1397 	fs->fs_cs(fs, cg).cs_nifree++;
1398 	if ((mode & IFMT) == IFDIR) {
1399 		cgp->cg_cs.cs_ndir--;
1400 		fs->fs_cstotal.cs_ndir--;
1401 		fs->fs_cs(fs, cg).cs_ndir--;
1402 	}
1403 	fs->fs_fmod = 1;
1404 	bdwrite(bp);
1405 	return (0);
1406 }
1407 
1408 
1409 /*
1410  * Find a block of the specified size in the specified cylinder group.
1411  *
1412  * It is a panic if a request is made to find a block if none are
1413  * available.
1414  */
1415 daddr_t
ffs_mapsearch(struct fs * fs,struct cg * cgp,daddr_t bpref,int allocsiz)1416 ffs_mapsearch(struct fs *fs, struct cg *cgp, daddr_t bpref, int allocsiz)
1417 {
1418 	daddr_t bno;
1419 	int start, len, loc, i;
1420 	int blk, field, subfield, pos;
1421 
1422 	/*
1423 	 * find the fragment by searching through the free block
1424 	 * map for an appropriate bit pattern
1425 	 */
1426 	if (bpref)
1427 		start = dtogd(fs, bpref) / NBBY;
1428 	else
1429 		start = cgp->cg_frotor / NBBY;
1430 	len = howmany(fs->fs_fpg, NBBY) - start;
1431 	loc = scanc((u_int)len, (u_char *)&cg_blksfree(cgp)[start],
1432 		(u_char *)fragtbl[fs->fs_frag],
1433 		(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
1434 	if (loc == 0) {
1435 		len = start + 1;
1436 		start = 0;
1437 		loc = scanc((u_int)len, (u_char *)&cg_blksfree(cgp)[0],
1438 			(u_char *)fragtbl[fs->fs_frag],
1439 			(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
1440 		if (loc == 0) {
1441 			printf("start = %d, len = %d, fs = %s\n",
1442 			    start, len, fs->fs_fsmnt);
1443 			panic("ffs_alloccg: map corrupted");
1444 			/* NOTREACHED */
1445 		}
1446 	}
1447 	bno = (start + len - loc) * NBBY;
1448 	cgp->cg_frotor = bno;
1449 	/*
1450 	 * found the byte in the map
1451 	 * sift through the bits to find the selected frag
1452 	 */
1453 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
1454 		blk = blkmap(fs, cg_blksfree(cgp), bno);
1455 		blk <<= 1;
1456 		field = around[allocsiz];
1457 		subfield = inside[allocsiz];
1458 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
1459 			if ((blk & field) == subfield)
1460 				return (bno + pos);
1461 			field <<= 1;
1462 			subfield <<= 1;
1463 		}
1464 	}
1465 	printf("bno = %lld, fs = %s\n", (long long)bno, fs->fs_fsmnt);
1466 	panic("ffs_alloccg: block not in map");
1467 	return (-1);
1468 }
1469 
1470 /*
1471  * Update the cluster map because of an allocation or free.
1472  *
1473  * Cnt == 1 means free; cnt == -1 means allocating.
1474  */
1475 void
ffs_clusteracct(struct fs * fs,struct cg * cgp,daddr_t blkno,int cnt)1476 ffs_clusteracct(struct fs *fs, struct cg *cgp, daddr_t blkno, int cnt)
1477 {
1478 	int32_t *sump;
1479 	int32_t *lp;
1480 	u_char *freemapp, *mapp;
1481 	int i, start, end, forw, back, map, bit;
1482 
1483 	if (fs->fs_contigsumsize <= 0)
1484 		return;
1485 	freemapp = cg_clustersfree(cgp);
1486 	sump = cg_clustersum(cgp);
1487 	/*
1488 	 * Allocate or clear the actual block.
1489 	 */
1490 	if (cnt > 0)
1491 		setbit(freemapp, blkno);
1492 	else
1493 		clrbit(freemapp, blkno);
1494 	/*
1495 	 * Find the size of the cluster going forward.
1496 	 */
1497 	start = blkno + 1;
1498 	end = start + fs->fs_contigsumsize;
1499 	if (end >= cgp->cg_nclusterblks)
1500 		end = cgp->cg_nclusterblks;
1501 	mapp = &freemapp[start / NBBY];
1502 	map = *mapp++;
1503 	bit = 1 << (start % NBBY);
1504 	for (i = start; i < end; i++) {
1505 		if ((map & bit) == 0)
1506 			break;
1507 		if ((i & (NBBY - 1)) != (NBBY - 1)) {
1508 			bit <<= 1;
1509 		} else {
1510 			map = *mapp++;
1511 			bit = 1;
1512 		}
1513 	}
1514 	forw = i - start;
1515 	/*
1516 	 * Find the size of the cluster going backward.
1517 	 */
1518 	start = blkno - 1;
1519 	end = start - fs->fs_contigsumsize;
1520 	if (end < 0)
1521 		end = -1;
1522 	mapp = &freemapp[start / NBBY];
1523 	map = *mapp--;
1524 	bit = 1 << (start % NBBY);
1525 	for (i = start; i > end; i--) {
1526 		if ((map & bit) == 0)
1527 			break;
1528 		if ((i & (NBBY - 1)) != 0) {
1529 			bit >>= 1;
1530 		} else {
1531 			map = *mapp--;
1532 			bit = 1 << (NBBY - 1);
1533 		}
1534 	}
1535 	back = start - i;
1536 	/*
1537 	 * Account for old cluster and the possibly new forward and
1538 	 * back clusters.
1539 	 */
1540 	i = back + forw + 1;
1541 	if (i > fs->fs_contigsumsize)
1542 		i = fs->fs_contigsumsize;
1543 	sump[i] += cnt;
1544 	if (back > 0)
1545 		sump[back] -= cnt;
1546 	if (forw > 0)
1547 		sump[forw] -= cnt;
1548 	/*
1549 	 * Update cluster summary information.
1550 	 */
1551 	lp = &sump[fs->fs_contigsumsize];
1552 	for (i = fs->fs_contigsumsize; i > 0; i--)
1553 		if (*lp-- > 0)
1554 			break;
1555 	fs->fs_maxcluster[cgp->cg_cgx] = i;
1556 }
1557