xref: /csrg-svn/sys/ufs/ffs/ffs_alloc.c (revision 53583)
1 /*
2  * Copyright (c) 1982, 1986, 1989 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  *
7  *	@(#)ffs_alloc.c	7.36 (Berkeley) 05/15/92
8  */
9 
10 #include <sys/param.h>
11 #include <sys/systm.h>
12 #include <sys/buf.h>
13 #include <sys/proc.h>
14 #include <sys/vnode.h>
15 #include <sys/kernel.h>
16 #include <sys/syslog.h>
17 
18 #include <vm/vm.h>
19 
20 #include <ufs/ufs/quota.h>
21 #include <ufs/ufs/inode.h>
22 
23 #include <ufs/ffs/fs.h>
24 #include <ufs/ffs/ffs_extern.h>
25 
26 extern u_long nextgennumber;
27 
28 static daddr_t	ffs_alloccg __P((struct inode *, int, daddr_t, int));
29 static daddr_t	ffs_alloccgblk __P((struct fs *, struct cg *, daddr_t));
30 static ino_t	ffs_dirpref __P((struct fs *));
31 static daddr_t	ffs_fragextend __P((struct inode *, int, long, int, int));
32 static void	ffs_fserr __P((struct fs *, u_int, char *));
33 static u_long	ffs_hashalloc
34 		    __P((struct inode *, int, long, int, u_long (*)()));
35 static ino_t	ffs_ialloccg __P((struct inode *, int, daddr_t, int));
36 static daddr_t	ffs_mapsearch __P((struct fs *, struct cg *, daddr_t, int));
37 
38 /*
39  * Allocate a block in the file system.
40  *
41  * The size of the requested block is given, which must be some
42  * multiple of fs_fsize and <= fs_bsize.
43  * A preference may be optionally specified. If a preference is given
44  * the following hierarchy is used to allocate a block:
45  *   1) allocate the requested block.
46  *   2) allocate a rotationally optimal block in the same cylinder.
47  *   3) allocate a block in the same cylinder group.
48  *   4) quadradically rehash into other cylinder groups, until an
49  *      available block is located.
50  * If no block preference is given the following heirarchy is used
51  * to allocate a block:
52  *   1) allocate a block in the cylinder group that contains the
53  *      inode for the file.
54  *   2) quadradically rehash into other cylinder groups, until an
55  *      available block is located.
56  */
57 ffs_alloc(ip, lbn, bpref, size, cred, bnp)
58 	register struct inode *ip;
59 	daddr_t lbn, bpref;
60 	int size;
61 	struct ucred *cred;
62 	daddr_t *bnp;
63 {
64 	daddr_t bno;
65 	register struct fs *fs;
66 	register struct buf *bp;
67 	int cg, error;
68 
69 	*bnp = 0;
70 	fs = ip->i_fs;
71 #ifdef DIAGNOSTIC
72 	if ((unsigned)size > fs->fs_bsize || fragoff(fs, size) != 0) {
73 		printf("dev = 0x%x, bsize = %d, size = %d, fs = %s\n",
74 		    ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
75 		panic("ffs_alloc: bad size");
76 	}
77 	if (cred == NOCRED)
78 		panic("ffs_alloc: missing credential\n");
79 #endif /* DIAGNOSTIC */
80 	if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
81 		goto nospace;
82 	if (cred->cr_uid != 0 && freespace(fs, fs->fs_minfree) <= 0)
83 		goto nospace;
84 #ifdef QUOTA
85 	if (error = chkdq(ip, (long)btodb(size), cred, 0))
86 		return (error);
87 #endif
88 	if (bpref >= fs->fs_size)
89 		bpref = 0;
90 	if (bpref == 0)
91 		cg = itog(fs, ip->i_number);
92 	else
93 		cg = dtog(fs, bpref);
94 	bno = (daddr_t)ffs_hashalloc(ip, cg, (long)bpref, size,
95 	    (u_long (*)())ffs_alloccg);
96 	if (bno > 0) {
97 		ip->i_blocks += btodb(size);
98 		ip->i_flag |= IUPD|ICHG;
99 		*bnp = bno;
100 		return (0);
101 	}
102 #ifdef QUOTA
103 	/*
104 	 * Restore user's disk quota because allocation failed.
105 	 */
106 	(void) chkdq(ip, (long)-btodb(size), cred, FORCE);
107 #endif
108 nospace:
109 	ffs_fserr(fs, cred->cr_uid, "file system full");
110 	uprintf("\n%s: write failed, file system is full\n", fs->fs_fsmnt);
111 	return (ENOSPC);
112 }
113 
114 /*
115  * Reallocate a fragment to a bigger size
116  *
117  * The number and size of the old block is given, and a preference
118  * and new size is also specified. The allocator attempts to extend
119  * the original block. Failing that, the regular block allocator is
120  * invoked to get an appropriate block.
121  */
122 ffs_realloccg(ip, lbprev, bpref, osize, nsize, cred, bpp)
123 	register struct inode *ip;
124 	daddr_t lbprev;
125 	daddr_t bpref;
126 	int osize, nsize;
127 	struct ucred *cred;
128 	struct buf **bpp;
129 {
130 	register struct fs *fs;
131 	struct buf *bp, *obp;
132 	int cg, request, error;
133 	daddr_t bprev, bno;
134 
135 	*bpp = 0;
136 	fs = ip->i_fs;
137 #ifdef DIAGNOSTIC
138 	if ((unsigned)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
139 	    (unsigned)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
140 		printf(
141 		    "dev = 0x%x, bsize = %d, osize = %d, nsize = %d, fs = %s\n",
142 		    ip->i_dev, fs->fs_bsize, osize, nsize, fs->fs_fsmnt);
143 		panic("ffs_realloccg: bad size");
144 	}
145 	if (cred == NOCRED)
146 		panic("ffs_realloccg: missing credential\n");
147 #endif /* DIAGNOSTIC */
148 	if (cred->cr_uid != 0 && freespace(fs, fs->fs_minfree) <= 0)
149 		goto nospace;
150 	if ((bprev = ip->i_db[lbprev]) == 0) {
151 		printf("dev = 0x%x, bsize = %d, bprev = %d, fs = %s\n",
152 		    ip->i_dev, fs->fs_bsize, bprev, fs->fs_fsmnt);
153 		panic("ffs_realloccg: bad bprev");
154 	}
155 	/*
156 	 * Allocate the extra space in the buffer.
157 	 */
158 	if (error = bread(ITOV(ip), lbprev, osize, NOCRED, &bp)) {
159 		brelse(bp);
160 		return (error);
161 	}
162 #ifdef QUOTA
163 	if (error = chkdq(ip, (long)btodb(nsize - osize), cred, 0)) {
164 		brelse(bp);
165 		return (error);
166 	}
167 #endif
168 	/*
169 	 * Check for extension in the existing location.
170 	 */
171 	cg = dtog(fs, bprev);
172 	if (bno = ffs_fragextend(ip, cg, (long)bprev, osize, nsize)) {
173 		if (bp->b_blkno != fsbtodb(fs, bno))
174 			panic("bad blockno");
175 		ip->i_blocks += btodb(nsize - osize);
176 		ip->i_flag |= IUPD|ICHG;
177 		allocbuf(bp, nsize);
178 		bp->b_flags |= B_DONE;
179 		bzero(bp->b_un.b_addr + osize, (unsigned)nsize - osize);
180 		*bpp = bp;
181 		return (0);
182 	}
183 	/*
184 	 * Allocate a new disk location.
185 	 */
186 	if (bpref >= fs->fs_size)
187 		bpref = 0;
188 	switch ((int)fs->fs_optim) {
189 	case FS_OPTSPACE:
190 		/*
191 		 * Allocate an exact sized fragment. Although this makes
192 		 * best use of space, we will waste time relocating it if
193 		 * the file continues to grow. If the fragmentation is
194 		 * less than half of the minimum free reserve, we choose
195 		 * to begin optimizing for time.
196 		 */
197 		request = nsize;
198 		if (fs->fs_minfree < 5 ||
199 		    fs->fs_cstotal.cs_nffree >
200 		    fs->fs_dsize * fs->fs_minfree / (2 * 100))
201 			break;
202 		log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
203 			fs->fs_fsmnt);
204 		fs->fs_optim = FS_OPTTIME;
205 		break;
206 	case FS_OPTTIME:
207 		/*
208 		 * At this point we have discovered a file that is trying to
209 		 * grow a small fragment to a larger fragment. To save time,
210 		 * we allocate a full sized block, then free the unused portion.
211 		 * If the file continues to grow, the `ffs_fragextend' call
212 		 * above will be able to grow it in place without further
213 		 * copying. If aberrant programs cause disk fragmentation to
214 		 * grow within 2% of the free reserve, we choose to begin
215 		 * optimizing for space.
216 		 */
217 		request = fs->fs_bsize;
218 		if (fs->fs_cstotal.cs_nffree <
219 		    fs->fs_dsize * (fs->fs_minfree - 2) / 100)
220 			break;
221 		log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
222 			fs->fs_fsmnt);
223 		fs->fs_optim = FS_OPTSPACE;
224 		break;
225 	default:
226 		printf("dev = 0x%x, optim = %d, fs = %s\n",
227 		    ip->i_dev, fs->fs_optim, fs->fs_fsmnt);
228 		panic("ffs_realloccg: bad optim");
229 		/* NOTREACHED */
230 	}
231 	bno = (daddr_t)ffs_hashalloc(ip, cg, (long)bpref, request,
232 	    (u_long (*)())ffs_alloccg);
233 	if (bno > 0) {
234 		bp->b_blkno = fsbtodb(fs, bno);
235 		(void) vnode_pager_uncache(ITOV(ip));
236 		ffs_blkfree(ip, bprev, (long)osize);
237 		if (nsize < request)
238 			ffs_blkfree(ip, bno + numfrags(fs, nsize),
239 			    (long)(request - nsize));
240 		ip->i_blocks += btodb(nsize - osize);
241 		ip->i_flag |= IUPD|ICHG;
242 		allocbuf(bp, nsize);
243 		bp->b_flags |= B_DONE;
244 		bzero(bp->b_un.b_addr + osize, (unsigned)nsize - osize);
245 		*bpp = bp;
246 		return (0);
247 	}
248 #ifdef QUOTA
249 	/*
250 	 * Restore user's disk quota because allocation failed.
251 	 */
252 	(void) chkdq(ip, (long)-btodb(nsize - osize), cred, FORCE);
253 #endif
254 	brelse(bp);
255 nospace:
256 	/*
257 	 * no space available
258 	 */
259 	ffs_fserr(fs, cred->cr_uid, "file system full");
260 	uprintf("\n%s: write failed, file system is full\n", fs->fs_fsmnt);
261 	return (ENOSPC);
262 }
263 
264 /*
265  * Allocate an inode in the file system.
266  *
267  * If allocating a directory, use ffs_dirpref to select the inode.
268  * If allocating in a directory, the following hierarchy is followed:
269  *   1) allocate the preferred inode.
270  *   2) allocate an inode in the same cylinder group.
271  *   3) quadradically rehash into other cylinder groups, until an
272  *      available inode is located.
273  * If no inode preference is given the following heirarchy is used
274  * to allocate an inode:
275  *   1) allocate an inode in cylinder group 0.
276  *   2) quadradically rehash into other cylinder groups, until an
277  *      available inode is located.
278  */
279 ffs_valloc (ap)
280 	struct vop_valloc_args *ap;
281 {
282 	USES_VOP_VFREE;
283 	USES_VOP_VGET;
284 	register struct inode *pip;
285 	register struct fs *fs;
286 	register struct inode *ip;
287 	ino_t ino, ipref;
288 	int cg, error;
289 
290 	*ap->a_vpp = NULL;
291 	pip = VTOI(ap->a_pvp);
292 	fs = pip->i_fs;
293 	if (fs->fs_cstotal.cs_nifree == 0)
294 		goto noinodes;
295 
296 	if ((ap->a_mode & IFMT) == IFDIR)
297 		ipref = ffs_dirpref(fs);
298 	else
299 		ipref = pip->i_number;
300 	if (ipref >= fs->fs_ncg * fs->fs_ipg)
301 		ipref = 0;
302 	cg = itog(fs, ipref);
303 	ino = (ino_t)ffs_hashalloc(pip, cg, (long)ipref, ap->a_mode, ffs_ialloccg);
304 	if (ino == 0)
305 		goto noinodes;
306 	error = FFS_VGET(ap->a_pvp->v_mount, ino, ap->a_vpp);
307 	if (error) {
308 		VOP_VFREE(ap->a_pvp, ino, ap->a_mode);
309 		return (error);
310 	}
311 	ip = VTOI(*ap->a_vpp);
312 	if (ip->i_mode) {
313 		printf("ap->a_mode = 0%o, inum = %d, fs = %s\n",
314 		    ip->i_mode, ip->i_number, fs->fs_fsmnt);
315 		panic("ffs_valloc: dup alloc");
316 	}
317 	if (ip->i_blocks) {				/* XXX */
318 		printf("free inode %s/%d had %d blocks\n",
319 		    fs->fs_fsmnt, ino, ip->i_blocks);
320 		ip->i_blocks = 0;
321 	}
322 	ip->i_flags = 0;
323 	/*
324 	 * Set up a new generation number for this inode.
325 	 */
326 	if (++nextgennumber < (u_long)time.tv_sec)
327 		nextgennumber = time.tv_sec;
328 	ip->i_gen = nextgennumber;
329 	return (0);
330 noinodes:
331 	ffs_fserr(fs, ap->a_cred->cr_uid, "out of inodes");
332 	uprintf("\n%s: create/symlink failed, no inodes free\n", fs->fs_fsmnt);
333 	return (ENOSPC);
334 }
335 
336 /*
337  * Find a cylinder to place a directory.
338  *
339  * The policy implemented by this algorithm is to select from
340  * among those cylinder groups with above the average number of
341  * free inodes, the one with the smallest number of directories.
342  */
343 static ino_t
344 ffs_dirpref(fs)
345 	register struct fs *fs;
346 {
347 	int cg, minndir, mincg, avgifree;
348 
349 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
350 	minndir = fs->fs_ipg;
351 	mincg = 0;
352 	for (cg = 0; cg < fs->fs_ncg; cg++)
353 		if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
354 		    fs->fs_cs(fs, cg).cs_nifree >= avgifree) {
355 			mincg = cg;
356 			minndir = fs->fs_cs(fs, cg).cs_ndir;
357 		}
358 	return ((ino_t)(fs->fs_ipg * mincg));
359 }
360 
361 /*
362  * Select the desired position for the next block in a file.  The file is
363  * logically divided into sections. The first section is composed of the
364  * direct blocks. Each additional section contains fs_maxbpg blocks.
365  *
366  * If no blocks have been allocated in the first section, the policy is to
367  * request a block in the same cylinder group as the inode that describes
368  * the file. If no blocks have been allocated in any other section, the
369  * policy is to place the section in a cylinder group with a greater than
370  * average number of free blocks.  An appropriate cylinder group is found
371  * by using a rotor that sweeps the cylinder groups. When a new group of
372  * blocks is needed, the sweep begins in the cylinder group following the
373  * cylinder group from which the previous allocation was made. The sweep
374  * continues until a cylinder group with greater than the average number
375  * of free blocks is found. If the allocation is for the first block in an
376  * indirect block, the information on the previous allocation is unavailable;
377  * here a best guess is made based upon the logical block number being
378  * allocated.
379  *
380  * If a section is already partially allocated, the policy is to
381  * contiguously allocate fs_maxcontig blocks.  The end of one of these
382  * contiguous blocks and the beginning of the next is physically separated
383  * so that the disk head will be in transit between them for at least
384  * fs_rotdelay milliseconds.  This is to allow time for the processor to
385  * schedule another I/O transfer.
386  */
387 daddr_t
388 ffs_blkpref(ip, lbn, indx, bap)
389 	struct inode *ip;
390 	daddr_t lbn;
391 	int indx;
392 	daddr_t *bap;
393 {
394 	register struct fs *fs;
395 	register int cg;
396 	int avgbfree, startcg;
397 	daddr_t nextblk;
398 
399 	fs = ip->i_fs;
400 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
401 		if (lbn < NDADDR) {
402 			cg = itog(fs, ip->i_number);
403 			return (fs->fs_fpg * cg + fs->fs_frag);
404 		}
405 		/*
406 		 * Find a cylinder with greater than average number of
407 		 * unused data blocks.
408 		 */
409 		if (indx == 0 || bap[indx - 1] == 0)
410 			startcg = itog(fs, ip->i_number) + lbn / fs->fs_maxbpg;
411 		else
412 			startcg = dtog(fs, bap[indx - 1]) + 1;
413 		startcg %= fs->fs_ncg;
414 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
415 		for (cg = startcg; cg < fs->fs_ncg; cg++)
416 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
417 				fs->fs_cgrotor = cg;
418 				return (fs->fs_fpg * cg + fs->fs_frag);
419 			}
420 		for (cg = 0; cg <= startcg; cg++)
421 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
422 				fs->fs_cgrotor = cg;
423 				return (fs->fs_fpg * cg + fs->fs_frag);
424 			}
425 		return (NULL);
426 	}
427 	/*
428 	 * One or more previous blocks have been laid out. If less
429 	 * than fs_maxcontig previous blocks are contiguous, the
430 	 * next block is requested contiguously, otherwise it is
431 	 * requested rotationally delayed by fs_rotdelay milliseconds.
432 	 */
433 	nextblk = bap[indx - 1] + fs->fs_frag;
434 	if (indx > fs->fs_maxcontig &&
435 	    bap[indx - fs->fs_maxcontig] + blkstofrags(fs, fs->fs_maxcontig)
436 	    != nextblk)
437 		return (nextblk);
438 	if (fs->fs_rotdelay != 0)
439 		/*
440 		 * Here we convert ms of delay to frags as:
441 		 * (frags) = (ms) * (rev/sec) * (sect/rev) /
442 		 *	((sect/frag) * (ms/sec))
443 		 * then round up to the next block.
444 		 */
445 		nextblk += roundup(fs->fs_rotdelay * fs->fs_rps * fs->fs_nsect /
446 		    (NSPF(fs) * 1000), fs->fs_frag);
447 	return (nextblk);
448 }
449 
450 /*
451  * Implement the cylinder overflow algorithm.
452  *
453  * The policy implemented by this algorithm is:
454  *   1) allocate the block in its requested cylinder group.
455  *   2) quadradically rehash on the cylinder group number.
456  *   3) brute force search for a free block.
457  */
458 /*VARARGS5*/
459 static u_long
460 ffs_hashalloc(ip, cg, pref, size, allocator)
461 	struct inode *ip;
462 	int cg;
463 	long pref;
464 	int size;	/* size for data blocks, mode for inodes */
465 	u_long (*allocator)();
466 {
467 	register struct fs *fs;
468 	long result;
469 	int i, icg = cg;
470 
471 	fs = ip->i_fs;
472 	/*
473 	 * 1: preferred cylinder group
474 	 */
475 	result = (*allocator)(ip, cg, pref, size);
476 	if (result)
477 		return (result);
478 	/*
479 	 * 2: quadratic rehash
480 	 */
481 	for (i = 1; i < fs->fs_ncg; i *= 2) {
482 		cg += i;
483 		if (cg >= fs->fs_ncg)
484 			cg -= fs->fs_ncg;
485 		result = (*allocator)(ip, cg, 0, size);
486 		if (result)
487 			return (result);
488 	}
489 	/*
490 	 * 3: brute force search
491 	 * Note that we start at i == 2, since 0 was checked initially,
492 	 * and 1 is always checked in the quadratic rehash.
493 	 */
494 	cg = (icg + 2) % fs->fs_ncg;
495 	for (i = 2; i < fs->fs_ncg; i++) {
496 		result = (*allocator)(ip, cg, 0, size);
497 		if (result)
498 			return (result);
499 		cg++;
500 		if (cg == fs->fs_ncg)
501 			cg = 0;
502 	}
503 	return (NULL);
504 }
505 
506 /*
507  * Determine whether a fragment can be extended.
508  *
509  * Check to see if the necessary fragments are available, and
510  * if they are, allocate them.
511  */
512 static daddr_t
513 ffs_fragextend(ip, cg, bprev, osize, nsize)
514 	struct inode *ip;
515 	int cg;
516 	long bprev;
517 	int osize, nsize;
518 {
519 	register struct fs *fs;
520 	register struct cg *cgp;
521 	struct buf *bp;
522 	long bno;
523 	int frags, bbase;
524 	int i, error;
525 
526 	fs = ip->i_fs;
527 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
528 		return (NULL);
529 	frags = numfrags(fs, nsize);
530 	bbase = fragnum(fs, bprev);
531 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
532 		/* cannot extend across a block boundary */
533 		return (NULL);
534 	}
535 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
536 		(int)fs->fs_cgsize, NOCRED, &bp);
537 	if (error) {
538 		brelse(bp);
539 		return (NULL);
540 	}
541 	cgp = bp->b_un.b_cg;
542 	if (!cg_chkmagic(cgp)) {
543 		brelse(bp);
544 		return (NULL);
545 	}
546 	cgp->cg_time = time.tv_sec;
547 	bno = dtogd(fs, bprev);
548 	for (i = numfrags(fs, osize); i < frags; i++)
549 		if (isclr(cg_blksfree(cgp), bno + i)) {
550 			brelse(bp);
551 			return (NULL);
552 		}
553 	/*
554 	 * the current fragment can be extended
555 	 * deduct the count on fragment being extended into
556 	 * increase the count on the remaining fragment (if any)
557 	 * allocate the extended piece
558 	 */
559 	for (i = frags; i < fs->fs_frag - bbase; i++)
560 		if (isclr(cg_blksfree(cgp), bno + i))
561 			break;
562 	cgp->cg_frsum[i - numfrags(fs, osize)]--;
563 	if (i != frags)
564 		cgp->cg_frsum[i - frags]++;
565 	for (i = numfrags(fs, osize); i < frags; i++) {
566 		clrbit(cg_blksfree(cgp), bno + i);
567 		cgp->cg_cs.cs_nffree--;
568 		fs->fs_cstotal.cs_nffree--;
569 		fs->fs_cs(fs, cg).cs_nffree--;
570 	}
571 	fs->fs_fmod = 1;
572 	bdwrite(bp);
573 	return (bprev);
574 }
575 
576 /*
577  * Determine whether a block can be allocated.
578  *
579  * Check to see if a block of the apprpriate size is available,
580  * and if it is, allocate it.
581  */
582 static daddr_t
583 ffs_alloccg(ip, cg, bpref, size)
584 	struct inode *ip;
585 	int cg;
586 	daddr_t bpref;
587 	int size;
588 {
589 	register struct fs *fs;
590 	register struct cg *cgp;
591 	struct buf *bp;
592 	register int i;
593 	int error, bno, frags, allocsiz;
594 
595 	fs = ip->i_fs;
596 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
597 		return (NULL);
598 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
599 		(int)fs->fs_cgsize, NOCRED, &bp);
600 	if (error) {
601 		brelse(bp);
602 		return (NULL);
603 	}
604 	cgp = bp->b_un.b_cg;
605 	if (!cg_chkmagic(cgp) ||
606 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize)) {
607 		brelse(bp);
608 		return (NULL);
609 	}
610 	cgp->cg_time = time.tv_sec;
611 	if (size == fs->fs_bsize) {
612 		bno = ffs_alloccgblk(fs, cgp, bpref);
613 		bdwrite(bp);
614 		return (bno);
615 	}
616 	/*
617 	 * check to see if any fragments are already available
618 	 * allocsiz is the size which will be allocated, hacking
619 	 * it down to a smaller size if necessary
620 	 */
621 	frags = numfrags(fs, size);
622 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
623 		if (cgp->cg_frsum[allocsiz] != 0)
624 			break;
625 	if (allocsiz == fs->fs_frag) {
626 		/*
627 		 * no fragments were available, so a block will be
628 		 * allocated, and hacked up
629 		 */
630 		if (cgp->cg_cs.cs_nbfree == 0) {
631 			brelse(bp);
632 			return (NULL);
633 		}
634 		bno = ffs_alloccgblk(fs, cgp, bpref);
635 		bpref = dtogd(fs, bno);
636 		for (i = frags; i < fs->fs_frag; i++)
637 			setbit(cg_blksfree(cgp), bpref + i);
638 		i = fs->fs_frag - frags;
639 		cgp->cg_cs.cs_nffree += i;
640 		fs->fs_cstotal.cs_nffree += i;
641 		fs->fs_cs(fs, cg).cs_nffree += i;
642 		fs->fs_fmod = 1;
643 		cgp->cg_frsum[i]++;
644 		bdwrite(bp);
645 		return (bno);
646 	}
647 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
648 	if (bno < 0) {
649 		brelse(bp);
650 		return (NULL);
651 	}
652 	for (i = 0; i < frags; i++)
653 		clrbit(cg_blksfree(cgp), bno + i);
654 	cgp->cg_cs.cs_nffree -= frags;
655 	fs->fs_cstotal.cs_nffree -= frags;
656 	fs->fs_cs(fs, cg).cs_nffree -= frags;
657 	fs->fs_fmod = 1;
658 	cgp->cg_frsum[allocsiz]--;
659 	if (frags != allocsiz)
660 		cgp->cg_frsum[allocsiz - frags]++;
661 	bdwrite(bp);
662 	return (cg * fs->fs_fpg + bno);
663 }
664 
665 /*
666  * Allocate a block in a cylinder group.
667  *
668  * This algorithm implements the following policy:
669  *   1) allocate the requested block.
670  *   2) allocate a rotationally optimal block in the same cylinder.
671  *   3) allocate the next available block on the block rotor for the
672  *      specified cylinder group.
673  * Note that this routine only allocates fs_bsize blocks; these
674  * blocks may be fragmented by the routine that allocates them.
675  */
676 static daddr_t
677 ffs_alloccgblk(fs, cgp, bpref)
678 	register struct fs *fs;
679 	register struct cg *cgp;
680 	daddr_t bpref;
681 {
682 	daddr_t bno;
683 	int cylno, pos, delta;
684 	short *cylbp;
685 	register int i;
686 
687 	if (bpref == 0) {
688 		bpref = cgp->cg_rotor;
689 		goto norot;
690 	}
691 	bpref = blknum(fs, bpref);
692 	bpref = dtogd(fs, bpref);
693 	/*
694 	 * if the requested block is available, use it
695 	 */
696 	if (ffs_isblock(fs, cg_blksfree(cgp), fragstoblks(fs, bpref))) {
697 		bno = bpref;
698 		goto gotit;
699 	}
700 	/*
701 	 * check for a block available on the same cylinder
702 	 */
703 	cylno = cbtocylno(fs, bpref);
704 	if (cg_blktot(cgp)[cylno] == 0)
705 		goto norot;
706 	if (fs->fs_cpc == 0) {
707 		/*
708 		 * block layout info is not available, so just have
709 		 * to take any block in this cylinder.
710 		 */
711 		bpref = howmany(fs->fs_spc * cylno, NSPF(fs));
712 		goto norot;
713 	}
714 	/*
715 	 * check the summary information to see if a block is
716 	 * available in the requested cylinder starting at the
717 	 * requested rotational position and proceeding around.
718 	 */
719 	cylbp = cg_blks(fs, cgp, cylno);
720 	pos = cbtorpos(fs, bpref);
721 	for (i = pos; i < fs->fs_nrpos; i++)
722 		if (cylbp[i] > 0)
723 			break;
724 	if (i == fs->fs_nrpos)
725 		for (i = 0; i < pos; i++)
726 			if (cylbp[i] > 0)
727 				break;
728 	if (cylbp[i] > 0) {
729 		/*
730 		 * found a rotational position, now find the actual
731 		 * block. A panic if none is actually there.
732 		 */
733 		pos = cylno % fs->fs_cpc;
734 		bno = (cylno - pos) * fs->fs_spc / NSPB(fs);
735 		if (fs_postbl(fs, pos)[i] == -1) {
736 			printf("pos = %d, i = %d, fs = %s\n",
737 			    pos, i, fs->fs_fsmnt);
738 			panic("ffs_alloccgblk: cyl groups corrupted");
739 		}
740 		for (i = fs_postbl(fs, pos)[i];; ) {
741 			if (ffs_isblock(fs, cg_blksfree(cgp), bno + i)) {
742 				bno = blkstofrags(fs, (bno + i));
743 				goto gotit;
744 			}
745 			delta = fs_rotbl(fs)[i];
746 			if (delta <= 0 ||
747 			    delta + i > fragstoblks(fs, fs->fs_fpg))
748 				break;
749 			i += delta;
750 		}
751 		printf("pos = %d, i = %d, fs = %s\n", pos, i, fs->fs_fsmnt);
752 		panic("ffs_alloccgblk: can't find blk in cyl");
753 	}
754 norot:
755 	/*
756 	 * no blocks in the requested cylinder, so take next
757 	 * available one in this cylinder group.
758 	 */
759 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
760 	if (bno < 0)
761 		return (NULL);
762 	cgp->cg_rotor = bno;
763 gotit:
764 	ffs_clrblock(fs, cg_blksfree(cgp), (long)fragstoblks(fs, bno));
765 	cgp->cg_cs.cs_nbfree--;
766 	fs->fs_cstotal.cs_nbfree--;
767 	fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
768 	cylno = cbtocylno(fs, bno);
769 	cg_blks(fs, cgp, cylno)[cbtorpos(fs, bno)]--;
770 	cg_blktot(cgp)[cylno]--;
771 	fs->fs_fmod = 1;
772 	return (cgp->cg_cgx * fs->fs_fpg + bno);
773 }
774 
775 /*
776  * Determine whether an inode can be allocated.
777  *
778  * Check to see if an inode is available, and if it is,
779  * allocate it using the following policy:
780  *   1) allocate the requested inode.
781  *   2) allocate the next available inode after the requested
782  *      inode in the specified cylinder group.
783  */
784 static ino_t
785 ffs_ialloccg(ip, cg, ipref, mode)
786 	struct inode *ip;
787 	int cg;
788 	daddr_t ipref;
789 	int mode;
790 {
791 	register struct fs *fs;
792 	register struct cg *cgp;
793 	struct buf *bp;
794 	int error, start, len, loc, map, i;
795 
796 	fs = ip->i_fs;
797 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
798 		return (NULL);
799 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
800 		(int)fs->fs_cgsize, NOCRED, &bp);
801 	if (error) {
802 		brelse(bp);
803 		return (NULL);
804 	}
805 	cgp = bp->b_un.b_cg;
806 	if (!cg_chkmagic(cgp) || cgp->cg_cs.cs_nifree == 0) {
807 		brelse(bp);
808 		return (NULL);
809 	}
810 	cgp->cg_time = time.tv_sec;
811 	if (ipref) {
812 		ipref %= fs->fs_ipg;
813 		if (isclr(cg_inosused(cgp), ipref))
814 			goto gotit;
815 	}
816 	start = cgp->cg_irotor / NBBY;
817 	len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
818 	loc = skpc(0xff, len, &cg_inosused(cgp)[start]);
819 	if (loc == 0) {
820 		len = start + 1;
821 		start = 0;
822 		loc = skpc(0xff, len, &cg_inosused(cgp)[0]);
823 		if (loc == 0) {
824 			printf("cg = %s, irotor = %d, fs = %s\n",
825 			    cg, cgp->cg_irotor, fs->fs_fsmnt);
826 			panic("ffs_ialloccg: map corrupted");
827 			/* NOTREACHED */
828 		}
829 	}
830 	i = start + len - loc;
831 	map = cg_inosused(cgp)[i];
832 	ipref = i * NBBY;
833 	for (i = 1; i < (1 << NBBY); i <<= 1, ipref++) {
834 		if ((map & i) == 0) {
835 			cgp->cg_irotor = ipref;
836 			goto gotit;
837 		}
838 	}
839 	printf("fs = %s\n", fs->fs_fsmnt);
840 	panic("ffs_ialloccg: block not in map");
841 	/* NOTREACHED */
842 gotit:
843 	setbit(cg_inosused(cgp), ipref);
844 	cgp->cg_cs.cs_nifree--;
845 	fs->fs_cstotal.cs_nifree--;
846 	fs->fs_cs(fs, cg).cs_nifree--;
847 	fs->fs_fmod = 1;
848 	if ((mode & IFMT) == IFDIR) {
849 		cgp->cg_cs.cs_ndir++;
850 		fs->fs_cstotal.cs_ndir++;
851 		fs->fs_cs(fs, cg).cs_ndir++;
852 	}
853 	bdwrite(bp);
854 	return (cg * fs->fs_ipg + ipref);
855 }
856 
857 /*
858  * Free a block or fragment.
859  *
860  * The specified block or fragment is placed back in the
861  * free map. If a fragment is deallocated, a possible
862  * block reassembly is checked.
863  */
864 ffs_blkfree(ip, bno, size)
865 	register struct inode *ip;
866 	daddr_t bno;
867 	long size;
868 {
869 	register struct fs *fs;
870 	register struct cg *cgp;
871 	struct buf *bp;
872 	int error, cg, blk, frags, bbase;
873 	register int i;
874 
875 	fs = ip->i_fs;
876 	if ((unsigned)size > fs->fs_bsize || fragoff(fs, size) != 0) {
877 		printf("dev = 0x%x, bsize = %d, size = %d, fs = %s\n",
878 		    ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
879 		panic("blkfree: bad size");
880 	}
881 	cg = dtog(fs, bno);
882 	if ((unsigned)bno >= fs->fs_size) {
883 		printf("bad block %d, ino %d\n", bno, ip->i_number);
884 		ffs_fserr(fs, ip->i_uid, "bad block");
885 		return;
886 	}
887 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
888 		(int)fs->fs_cgsize, NOCRED, &bp);
889 	if (error) {
890 		brelse(bp);
891 		return;
892 	}
893 	cgp = bp->b_un.b_cg;
894 	if (!cg_chkmagic(cgp)) {
895 		brelse(bp);
896 		return;
897 	}
898 	cgp->cg_time = time.tv_sec;
899 	bno = dtogd(fs, bno);
900 	if (size == fs->fs_bsize) {
901 		if (ffs_isblock(fs, cg_blksfree(cgp), fragstoblks(fs, bno))) {
902 			printf("dev = 0x%x, block = %d, fs = %s\n",
903 			    ip->i_dev, bno, fs->fs_fsmnt);
904 			panic("blkfree: freeing free block");
905 		}
906 		ffs_setblock(fs, cg_blksfree(cgp), fragstoblks(fs, bno));
907 		cgp->cg_cs.cs_nbfree++;
908 		fs->fs_cstotal.cs_nbfree++;
909 		fs->fs_cs(fs, cg).cs_nbfree++;
910 		i = cbtocylno(fs, bno);
911 		cg_blks(fs, cgp, i)[cbtorpos(fs, bno)]++;
912 		cg_blktot(cgp)[i]++;
913 	} else {
914 		bbase = bno - fragnum(fs, bno);
915 		/*
916 		 * decrement the counts associated with the old frags
917 		 */
918 		blk = blkmap(fs, cg_blksfree(cgp), bbase);
919 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
920 		/*
921 		 * deallocate the fragment
922 		 */
923 		frags = numfrags(fs, size);
924 		for (i = 0; i < frags; i++) {
925 			if (isset(cg_blksfree(cgp), bno + i)) {
926 				printf("dev = 0x%x, block = %d, fs = %s\n",
927 				    ip->i_dev, bno + i, fs->fs_fsmnt);
928 				panic("blkfree: freeing free frag");
929 			}
930 			setbit(cg_blksfree(cgp), bno + i);
931 		}
932 		cgp->cg_cs.cs_nffree += i;
933 		fs->fs_cstotal.cs_nffree += i;
934 		fs->fs_cs(fs, cg).cs_nffree += i;
935 		/*
936 		 * add back in counts associated with the new frags
937 		 */
938 		blk = blkmap(fs, cg_blksfree(cgp), bbase);
939 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
940 		/*
941 		 * if a complete block has been reassembled, account for it
942 		 */
943 		if (ffs_isblock(fs, cg_blksfree(cgp),
944 		    (daddr_t)fragstoblks(fs, bbase))) {
945 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
946 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
947 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
948 			cgp->cg_cs.cs_nbfree++;
949 			fs->fs_cstotal.cs_nbfree++;
950 			fs->fs_cs(fs, cg).cs_nbfree++;
951 			i = cbtocylno(fs, bbase);
952 			cg_blks(fs, cgp, i)[cbtorpos(fs, bbase)]++;
953 			cg_blktot(cgp)[i]++;
954 		}
955 	}
956 	fs->fs_fmod = 1;
957 	bdwrite(bp);
958 }
959 
960 /*
961  * Free an inode.
962  *
963  * The specified inode is placed back in the free map.
964  */
965 int
966 ffs_vfree (ap)
967 	struct vop_vfree_args *ap;
968 {
969 	register struct fs *fs;
970 	register struct cg *cgp;
971 	register struct inode *pip;
972 	struct buf *bp;
973 	int error, cg;
974 
975 	pip = VTOI(ap->a_pvp);
976 	fs = pip->i_fs;
977 	if ((u_int)ap->a_ino >= fs->fs_ipg * fs->fs_ncg)
978 		panic("ifree: range: dev = 0x%x, ap->a_ino = %d, fs = %s\n",
979 		    pip->i_dev, ap->a_ino, fs->fs_fsmnt);
980 	cg = itog(fs, ap->a_ino);
981 	error = bread(pip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
982 		(int)fs->fs_cgsize, NOCRED, &bp);
983 	if (error) {
984 		brelse(bp);
985 		return (0);
986 	}
987 	cgp = bp->b_un.b_cg;
988 	if (!cg_chkmagic(cgp)) {
989 		brelse(bp);
990 		return (0);
991 	}
992 	cgp->cg_time = time.tv_sec;
993 	ap->a_ino %= fs->fs_ipg;
994 	if (isclr(cg_inosused(cgp), ap->a_ino)) {
995 		printf("dev = 0x%x, ap->a_ino = %d, fs = %s\n",
996 		    pip->i_dev, ap->a_ino, fs->fs_fsmnt);
997 		if (fs->fs_ronly == 0)
998 			panic("ifree: freeing free inode");
999 	}
1000 	clrbit(cg_inosused(cgp), ap->a_ino);
1001 	if (ap->a_ino < cgp->cg_irotor)
1002 		cgp->cg_irotor = ap->a_ino;
1003 	cgp->cg_cs.cs_nifree++;
1004 	fs->fs_cstotal.cs_nifree++;
1005 	fs->fs_cs(fs, cg).cs_nifree++;
1006 	if ((ap->a_mode & IFMT) == IFDIR) {
1007 		cgp->cg_cs.cs_ndir--;
1008 		fs->fs_cstotal.cs_ndir--;
1009 		fs->fs_cs(fs, cg).cs_ndir--;
1010 	}
1011 	fs->fs_fmod = 1;
1012 	bdwrite(bp);
1013 	return (0);
1014 }
1015 
1016 /*
1017  * Find a block of the specified size in the specified cylinder group.
1018  *
1019  * It is a panic if a request is made to find a block if none are
1020  * available.
1021  */
1022 static daddr_t
1023 ffs_mapsearch(fs, cgp, bpref, allocsiz)
1024 	register struct fs *fs;
1025 	register struct cg *cgp;
1026 	daddr_t bpref;
1027 	int allocsiz;
1028 {
1029 	daddr_t bno;
1030 	int start, len, loc, i;
1031 	int blk, field, subfield, pos;
1032 
1033 	/*
1034 	 * find the fragment by searching through the free block
1035 	 * map for an appropriate bit pattern
1036 	 */
1037 	if (bpref)
1038 		start = dtogd(fs, bpref) / NBBY;
1039 	else
1040 		start = cgp->cg_frotor / NBBY;
1041 	len = howmany(fs->fs_fpg, NBBY) - start;
1042 	loc = scanc((unsigned)len, (u_char *)&cg_blksfree(cgp)[start],
1043 		(u_char *)fragtbl[fs->fs_frag],
1044 		(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
1045 	if (loc == 0) {
1046 		len = start + 1;
1047 		start = 0;
1048 		loc = scanc((unsigned)len, (u_char *)&cg_blksfree(cgp)[0],
1049 			(u_char *)fragtbl[fs->fs_frag],
1050 			(u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
1051 		if (loc == 0) {
1052 			printf("start = %d, len = %d, fs = %s\n",
1053 			    start, len, fs->fs_fsmnt);
1054 			panic("ffs_alloccg: map corrupted");
1055 			/* NOTREACHED */
1056 		}
1057 	}
1058 	bno = (start + len - loc) * NBBY;
1059 	cgp->cg_frotor = bno;
1060 	/*
1061 	 * found the byte in the map
1062 	 * sift through the bits to find the selected frag
1063 	 */
1064 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
1065 		blk = blkmap(fs, cg_blksfree(cgp), bno);
1066 		blk <<= 1;
1067 		field = around[allocsiz];
1068 		subfield = inside[allocsiz];
1069 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
1070 			if ((blk & field) == subfield)
1071 				return (bno + pos);
1072 			field <<= 1;
1073 			subfield <<= 1;
1074 		}
1075 	}
1076 	printf("bno = %d, fs = %s\n", bno, fs->fs_fsmnt);
1077 	panic("ffs_alloccg: block not in map");
1078 	return (-1);
1079 }
1080 
1081 /*
1082  * Fserr prints the name of a file system with an error diagnostic.
1083  *
1084  * The form of the error message is:
1085  *	fs: error message
1086  */
1087 static void
1088 ffs_fserr(fs, uid, cp)
1089 	struct fs *fs;
1090 	u_int uid;
1091 	char *cp;
1092 {
1093 
1094 	log(LOG_ERR, "uid %d on %s: %s\n", uid, fs->fs_fsmnt, cp);
1095 }
1096