xref: /titanic_50/usr/src/uts/common/fs/ufs/ufs_alloc.c (revision e2ff4ac63d83b80a04de28e4d3d6068fe781fa12)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T	*/
28 /*	  All Rights Reserved  	*/
29 
30 /*
31  * University Copyright- Copyright (c) 1982, 1986, 1988
32  * The Regents of the University of California
33  * All Rights Reserved
34  *
35  * University Acknowledgment- Portions of this document are derived from
36  * software developed by the University of California, Berkeley, and its
37  * contributors.
38  */
39 
40 
41 #pragma ident	"%Z%%M%	%I%	%E% SMI"
42 
43 #include <sys/types.h>
44 #include <sys/t_lock.h>
45 #include <sys/debug.h>
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/signal.h>
49 #include <sys/cred.h>
50 #include <sys/proc.h>
51 #include <sys/disp.h>
52 #include <sys/user.h>
53 #include <sys/buf.h>
54 #include <sys/vfs.h>
55 #include <sys/vnode.h>
56 #include <sys/acl.h>
57 #include <sys/fs/ufs_fs.h>
58 #include <sys/fs/ufs_inode.h>
59 #include <sys/fs/ufs_acl.h>
60 #include <sys/fs/ufs_bio.h>
61 #include <sys/fs/ufs_quota.h>
62 #include <sys/kmem.h>
63 #include <sys/fs/ufs_trans.h>
64 #include <sys/fs/ufs_panic.h>
65 #include <sys/errno.h>
66 #include <sys/time.h>
67 #include <sys/sysmacros.h>
68 #include <sys/file.h>
69 #include <sys/fcntl.h>
70 #include <sys/flock.h>
71 #include <fs/fs_subr.h>
72 #include <sys/cmn_err.h>
73 #include <sys/policy.h>
74 
75 static ino_t	hashalloc();
76 static daddr_t	fragextend();
77 static daddr_t	alloccg();
78 static daddr_t	alloccgblk();
79 static ino_t	ialloccg();
80 static daddr_t	mapsearch();
81 
82 extern int	inside[], around[];
83 extern uchar_t	*fragtbl[];
84 void delay();
85 
86 /*
87  * Allocate a block in the file system.
88  *
89  * The size of the requested block is given, which must be some
90  * multiple of fs_fsize and <= fs_bsize.
91  * A preference may be optionally specified. If a preference is given
92  * the following hierarchy is used to allocate a block:
93  *   1) allocate the requested block.
94  *   2) allocate a rotationally optimal block in the same cylinder.
95  *   3) allocate a block in the same cylinder group.
96  *   4) quadratically rehash into other cylinder groups, until an
97  *	available block is located.
98  * If no block preference is given the following hierarchy is used
99  * to allocate a block:
100  *   1) allocate a block in the cylinder group that contains the
101  *	inode for the file.
102  *   2) quadratically rehash into other cylinder groups, until an
103  *	available block is located.
104  */
105 int
106 alloc(struct inode *ip, daddr_t bpref, int size, daddr_t *bnp, cred_t *cr)
107 {
108 	struct fs *fs;
109 	struct ufsvfs *ufsvfsp;
110 	daddr_t bno;
111 	int cg;
112 	int err;
113 	char *errmsg = NULL;
114 	size_t len;
115 
116 	ufsvfsp = ip->i_ufsvfs;
117 	fs = ufsvfsp->vfs_fs;
118 	if ((unsigned)size > fs->fs_bsize || fragoff(fs, size) != 0) {
119 		err = ufs_fault(ITOV(ip),
120 	    "alloc: bad size, dev = 0x%lx, bsize = %d, size = %d, fs = %s\n",
121 	    ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
122 		return (err);
123 	}
124 	if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
125 		goto nospace;
126 	if (freespace(fs, ufsvfsp) <= 0 &&
127 	    secpolicy_fs_minfree(cr, ufsvfsp->vfs_vfs) != 0)
128 		goto nospace;
129 	err = chkdq(ip, (long)btodb(size), 0, cr, &errmsg, &len);
130 	/* Note that may not have err, but may have errmsg */
131 	if (errmsg != NULL) {
132 		uprintf(errmsg);
133 		kmem_free(errmsg, len);
134 		errmsg = NULL;
135 	}
136 	if (err)
137 		return (err);
138 	if (bpref >= fs->fs_size)
139 		bpref = 0;
140 	if (bpref == 0)
141 		cg = (int)itog(fs, ip->i_number);
142 	else
143 		cg = dtog(fs, bpref);
144 
145 	bno = (daddr_t)hashalloc(ip, cg, (long)bpref, size,
146 	    (ulong_t (*)())alloccg);
147 	if (bno > 0) {
148 		*bnp = bno;
149 		return (0);
150 	}
151 
152 	/*
153 	 * hashalloc() failed because some other thread grabbed
154 	 * the last block so unwind the quota operation.  We can
155 	 * ignore the return because subtractions don't fail and
156 	 * size is guaranteed to be >= zero by our caller.
157 	 */
158 	(void) chkdq(ip, -(long)btodb(size), 0, cr, (char **)NULL,
159 		(size_t *)NULL);
160 
161 nospace:
162 	mutex_enter(&ufsvfsp->vfs_lock);
163 	if ((lbolt - ufsvfsp->vfs_lastwhinetime) > (hz << 2) &&
164 		(!(TRANS_ISTRANS(ufsvfsp)) || !(ip->i_flag & IQUIET))) {
165 		ufsvfsp->vfs_lastwhinetime = lbolt;
166 		cmn_err(CE_NOTE, "alloc: %s: file system full", fs->fs_fsmnt);
167 	}
168 	mutex_exit(&ufsvfsp->vfs_lock);
169 	return (ENOSPC);
170 }
171 
172 /*
173  * Reallocate a fragment to a bigger size
174  *
175  * The number and size of the old block is given, and a preference
176  * and new size is also specified.  The allocator attempts to extend
177  * the original block.  Failing that, the regular block allocator is
178  * invoked to get an appropriate block.
179  */
180 int
181 realloccg(struct inode *ip, daddr_t bprev, daddr_t bpref, int osize,
182     int nsize, daddr_t *bnp, cred_t *cr)
183 {
184 	daddr_t bno;
185 	struct fs *fs;
186 	struct ufsvfs *ufsvfsp;
187 	int cg, request;
188 	int err;
189 	char *errmsg = NULL;
190 	size_t len;
191 
192 	ufsvfsp = ip->i_ufsvfs;
193 	fs = ufsvfsp->vfs_fs;
194 	if ((unsigned)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
195 	    (unsigned)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
196 		err = ufs_fault(ITOV(ip),
197 	"realloccg: bad size, dev=0x%lx, bsize=%d, osize=%d, nsize=%d, fs=%s\n",
198 		    ip->i_dev, fs->fs_bsize, osize, nsize,
199 		    fs->fs_fsmnt);
200 		return (err);
201 	}
202 	if (freespace(fs, ufsvfsp) <= 0 &&
203 	    secpolicy_fs_minfree(cr, ufsvfsp->vfs_vfs) != 0)
204 		goto nospace;
205 	if (bprev == 0) {
206 		err = ufs_fault(ITOV(ip),
207 	"realloccg: bad bprev, dev = 0x%lx, bsize = %d, bprev = %ld, fs = %s\n",
208 		    ip->i_dev, fs->fs_bsize, bprev,
209 		    fs->fs_fsmnt);
210 		return (err);
211 	}
212 	err = chkdq(ip, (long)btodb(nsize - osize), 0, cr, &errmsg, &len);
213 	/* Note that may not have err, but may have errmsg */
214 	if (errmsg != NULL) {
215 		uprintf(errmsg);
216 		kmem_free(errmsg, len);
217 		errmsg = NULL;
218 	}
219 	if (err)
220 		return (err);
221 	cg = dtog(fs, bprev);
222 	bno = fragextend(ip, cg, (long)bprev, osize, nsize);
223 	if (bno != 0) {
224 		*bnp = bno;
225 		return (0);
226 	}
227 	if (bpref >= fs->fs_size)
228 		bpref = 0;
229 
230 	/*
231 	 * When optimizing for time we allocate a full block and
232 	 * then only use the upper portion for this request. When
233 	 * this file grows again it will grow into the unused portion
234 	 * of the block (See fragextend() above).  This saves time
235 	 * because an extra disk write would be needed if the frags
236 	 * following the current allocation were not free. The extra
237 	 * disk write is needed to move the data from its current
238 	 * location into the newly allocated position.
239 	 *
240 	 * When optimizing for space we allocate a run of frags
241 	 * that is just the right size for this request.
242 	 */
243 	request = (fs->fs_optim == FS_OPTTIME) ? fs->fs_bsize : nsize;
244 	bno = (daddr_t)hashalloc(ip, cg, (long)bpref, request,
245 		(ulong_t (*)())alloccg);
246 	if (bno > 0) {
247 		*bnp = bno;
248 		if (nsize < request)
249 			(void) free(ip, bno + numfrags(fs, nsize),
250 			    (off_t)(request - nsize), I_NOCANCEL);
251 		return (0);
252 	}
253 
254 	/*
255 	 * hashalloc() failed because some other thread grabbed
256 	 * the last block so unwind the quota operation.  We can
257 	 * ignore the return because subtractions don't fail, and
258 	 * our caller guarantees nsize >= osize.
259 	 */
260 	(void) chkdq(ip, -(long)btodb(nsize - osize), 0, cr, (char **)NULL,
261 		(size_t *)NULL);
262 
263 nospace:
264 	mutex_enter(&ufsvfsp->vfs_lock);
265 	if ((lbolt - ufsvfsp->vfs_lastwhinetime) > (hz << 2) &&
266 		(!(TRANS_ISTRANS(ufsvfsp)) || !(ip->i_flag & IQUIET))) {
267 		ufsvfsp->vfs_lastwhinetime = lbolt;
268 		cmn_err(CE_NOTE,
269 			"realloccg %s: file system full", fs->fs_fsmnt);
270 	}
271 	mutex_exit(&ufsvfsp->vfs_lock);
272 	return (ENOSPC);
273 }
274 
275 /*
276  * Allocate an inode in the file system.
277  *
278  * A preference may be optionally specified. If a preference is given
279  * the following hierarchy is used to allocate an inode:
280  *   1) allocate the requested inode.
281  *   2) allocate an inode in the same cylinder group.
282  *   3) quadratically rehash into other cylinder groups, until an
283  *	available inode is located.
284  * If no inode preference is given the following hierarchy is used
285  * to allocate an inode:
286  *   1) allocate an inode in cylinder group 0.
287  *   2) quadratically rehash into other cylinder groups, until an
288  *	available inode is located.
289  */
290 int
291 ufs_ialloc(struct inode *pip,
292     ino_t ipref, mode_t mode, struct inode **ipp, cred_t *cr)
293 {
294 	struct inode *ip;
295 	struct fs *fs;
296 	int cg;
297 	ino_t ino;
298 	int err;
299 	int nifree;
300 	struct ufsvfs *ufsvfsp = pip->i_ufsvfs;
301 	char *errmsg = NULL;
302 	size_t len;
303 
304 	ASSERT(RW_WRITE_HELD(&pip->i_rwlock));
305 	fs = pip->i_fs;
306 loop:
307 	nifree = fs->fs_cstotal.cs_nifree;
308 
309 	if (nifree == 0)
310 		goto noinodes;
311 	/*
312 	 * Shadow inodes don't count against a user's inode allocation.
313 	 * They are an implementation method and not a resource.
314 	 */
315 	if ((mode != IFSHAD) && (mode != IFATTRDIR)) {
316 		err = chkiq((struct ufsvfs *)ITOV(pip)->v_vfsp->vfs_data,
317 			/* change */ 1, (struct inode *)NULL, crgetuid(cr), 0,
318 			cr, &errmsg, &len);
319 		/*
320 		 * As we haven't acquired any locks yet, dump the message
321 		 * now.
322 		 */
323 		if (errmsg != NULL) {
324 			uprintf(errmsg);
325 			kmem_free(errmsg, len);
326 			errmsg = NULL;
327 		}
328 		if (err)
329 			return (err);
330 	}
331 
332 	if (ipref >= (ulong_t)(fs->fs_ncg * fs->fs_ipg))
333 		ipref = 0;
334 	cg = (int)itog(fs, ipref);
335 	ino = (ino_t)hashalloc(pip, cg, (long)ipref, (int)mode,
336 	    (ulong_t (*)())ialloccg);
337 	if (ino == 0) {
338 		if ((mode != IFSHAD) && (mode != IFATTRDIR)) {
339 			/*
340 			 * We can safely ignore the return from chkiq()
341 			 * because deallocations can only fail if we
342 			 * can't get the user's quota info record off
343 			 * the disk due to an I/O error.  In that case,
344 			 * the quota subsystem is already messed up.
345 			 */
346 			(void) chkiq(ufsvfsp, /* change */ -1,
347 				(struct inode *)NULL, crgetuid(cr), 0, cr,
348 				(char **)NULL, (size_t *)NULL);
349 		}
350 		goto noinodes;
351 	}
352 	err = ufs_iget(pip->i_vfs, ino, ipp, cr);
353 	if (err) {
354 		if ((mode != IFSHAD) && (mode != IFATTRDIR)) {
355 			/*
356 			 * See above comment about why it is safe to ignore an
357 			 * error return here.
358 			 */
359 			(void) chkiq(ufsvfsp, /* change */ -1,
360 				(struct inode *)NULL, crgetuid(cr), 0, cr,
361 				(char **)NULL, (size_t *)NULL);
362 		}
363 		ufs_ifree(pip, ino, 0);
364 		return (err);
365 	}
366 	ip = *ipp;
367 	ASSERT(!ip->i_ufs_acl);
368 	ASSERT(!ip->i_dquot);
369 	rw_enter(&ip->i_contents, RW_WRITER);
370 
371 	/*
372 	 * Check if we really got a free inode, if not then complain
373 	 * and mark the inode ISTALE so that it will be freed by the
374 	 * ufs idle thread eventually and will not be sent to ufs_delete().
375 	 */
376 	if (ip->i_mode || (ip->i_nlink > 0)) {
377 		ip->i_flag |= ISTALE;
378 		rw_exit(&ip->i_contents);
379 		VN_RELE(ITOV(ip));
380 		cmn_err(CE_WARN,
381 			"%s: unexpected allocated inode %d, run fsck(1M)%s",
382 			fs->fs_fsmnt, (int)ino,
383 			(TRANS_ISTRANS(ufsvfsp) ? " -o f" : ""));
384 		goto loop;
385 	}
386 
387 	/*
388 	 * Check the inode has no size or data blocks.
389 	 * This could have happened if the truncation failed when
390 	 * deleting the inode. It used to be possible for this to occur
391 	 * if a block allocation failed when iteratively truncating a
392 	 * large file using logging and with a full file system.
393 	 * This was fixed with bug fix 4348738. However, truncation may
394 	 * still fail on an IO error. So in all cases for safety and
395 	 * security we clear out the size; the blocks allocated; and
396 	 * pointers to the blocks. This will ultimately cause a fsck
397 	 * error of un-accounted for blocks, but its a fairly benign error,
398 	 * and possibly the correct thing to do anyway as accesssing those
399 	 * blocks agains may lead to more IO errors.
400 	 */
401 	if (ip->i_size || ip->i_blocks) {
402 		int i;
403 
404 		if (ip->i_size) {
405 			cmn_err(CE_WARN,
406 			"%s: free inode %d had size 0x%llx, run fsck(1M)%s",
407 			fs->fs_fsmnt, (int)ino, ip->i_size,
408 			(TRANS_ISTRANS(ufsvfsp) ? " -o f" : ""));
409 		}
410 		/*
411 		 * Clear any garbage left behind.
412 		 */
413 		ip->i_size = (u_offset_t)0;
414 		ip->i_blocks = 0;
415 		for (i = 0; i < NDADDR; i++)
416 			ip->i_db[i] = 0;
417 		for (i = 0; i < NIADDR; i++)
418 			ip->i_ib[i] = 0;
419 	}
420 
421 	/*
422 	 * Initialize the link count
423 	 */
424 	ip->i_nlink = 0;
425 
426 	/*
427 	 * Clear the old flags
428 	 */
429 	ip->i_flag &= IREF;
430 
431 	/*
432 	 * Access times are not really defined if the fs is mounted
433 	 * with 'noatime'. But it can cause nfs clients to fail
434 	 * open() if the atime is not a legal value. Set a legal value
435 	 * here when the inode is allocated.
436 	 */
437 	if (ufsvfsp->vfs_noatime) {
438 		mutex_enter(&ufs_iuniqtime_lock);
439 		ip->i_atime = iuniqtime;
440 		mutex_exit(&ufs_iuniqtime_lock);
441 	}
442 	rw_exit(&ip->i_contents);
443 	return (0);
444 noinodes:
445 	if (!(TRANS_ISTRANS(ufsvfsp)) || !(pip->i_flag & IQUIET))
446 		cmn_err(CE_NOTE, "%s: out of inodes\n", fs->fs_fsmnt);
447 	return (ENOSPC);
448 }
449 
450 /*
451  * Find a cylinder group to place a directory.
452  * Returns an inumber within the selected cylinder group.
453  * Note, the vfs_lock is not needed as we don't require exact cg summary info.
454  *
455  * If the switch ufs_close_dirs is set, then the policy is to use
456  * the current cg if it has more than 25% free inodes and more
457  * than 25% free blocks. Otherwise the cgs are searched from
458  * the beginning and the first cg with the same criteria is
459  * used. If that is also null then we revert to the old algorithm.
460  * This tends to cluster files at the beginning of the disk
461  * until the disk gets full.
462  *
463  * Otherwise if ufs_close_dirs is not set then the original policy is
464  * used which is to select from among those cylinder groups with
465  * above the average number of free inodes, the one with the smallest
466  * number of directories.
467  */
468 
469 int ufs_close_dirs = 1;	/* allocate directories close as possible */
470 
471 ino_t
472 dirpref(inode_t *dp)
473 {
474 	int cg, minndir, mincg, avgifree, mininode, minbpg, ifree;
475 	struct fs *fs = dp->i_fs;
476 
477 	cg = itog(fs, dp->i_number);
478 	mininode = fs->fs_ipg >> 2;
479 	minbpg = fs->fs_maxbpg >> 2;
480 	if (ufs_close_dirs &&
481 	    (fs->fs_cs(fs, cg).cs_nifree > mininode) &&
482 	    (fs->fs_cs(fs, cg).cs_nbfree > minbpg)) {
483 		return (dp->i_number);
484 	}
485 
486 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
487 	minndir = fs->fs_ipg;
488 	mincg = 0;
489 	for (cg = 0; cg < fs->fs_ncg; cg++) {
490 		ifree = fs->fs_cs(fs, cg).cs_nifree;
491 		if (ufs_close_dirs &&
492 		    (ifree > mininode) &&
493 		    (fs->fs_cs(fs, cg).cs_nbfree > minbpg)) {
494 			return ((ino_t)(fs->fs_ipg * cg));
495 		}
496 		if ((fs->fs_cs(fs, cg).cs_ndir < minndir) &&
497 		    (ifree >= avgifree)) {
498 			mincg = cg;
499 			minndir = fs->fs_cs(fs, cg).cs_ndir;
500 		}
501 	}
502 	return ((ino_t)(fs->fs_ipg * mincg));
503 }
504 
505 /*
506  * Select the desired position for the next block in a file.  The file is
507  * logically divided into sections. The first section is composed of the
508  * direct blocks. Each additional section contains fs_maxbpg blocks.
509  *
510  * If no blocks have been allocated in the first section, the policy is to
511  * request a block in the same cylinder group as the inode that describes
512  * the file. If no blocks have been allocated in any other section, the
513  * policy is to place the section in a cylinder group with a greater than
514  * average number of free blocks.  An appropriate cylinder group is found
515  * by using a rotor that sweeps the cylinder groups. When a new group of
516  * blocks is needed, the sweep begins in the cylinder group following the
517  * cylinder group from which the previous allocation was made. The sweep
518  * continues until a cylinder group with greater than the average number
519  * of free blocks is found. If the allocation is for the first block in an
520  * indirect block, the information on the previous allocation is unavailable;
521  * here a best guess is made based upon the logical block number being
522  * allocated.
523  *
524  * If a section is already partially allocated, the policy is to
525  * contiguously allocate fs_maxcontig blocks.  The end of one of these
526  * contiguous blocks and the beginning of the next is physically separated
527  * so that the disk head will be in transit between them for at least
528  * fs_rotdelay milliseconds.  This is to allow time for the processor to
529  * schedule another I/O transfer.
530  */
531 daddr_t
532 blkpref(struct inode *ip, daddr_t lbn, int indx, daddr32_t *bap)
533 {
534 	struct fs *fs;
535 	struct ufsvfs *ufsvfsp;
536 	int cg;
537 	int avgbfree, startcg;
538 	daddr_t nextblk;
539 
540 	ufsvfsp = ip->i_ufsvfs;
541 	fs = ip->i_fs;
542 	if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
543 		if (lbn < NDADDR) {
544 			cg = itog(fs, ip->i_number);
545 			return (fs->fs_fpg * cg + fs->fs_frag);
546 		}
547 		/*
548 		 * Find a cylinder with greater than average
549 		 * number of unused data blocks.
550 		 */
551 		if (indx == 0 || bap[indx - 1] == 0)
552 			startcg = itog(fs, ip->i_number) + lbn / fs->fs_maxbpg;
553 		else
554 			startcg = dtog(fs, bap[indx - 1]) + 1;
555 		startcg %= fs->fs_ncg;
556 
557 		mutex_enter(&ufsvfsp->vfs_lock);
558 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
559 		/*
560 		 * used for computing log space for writes/truncs
561 		 */
562 		ufsvfsp->vfs_avgbfree = avgbfree;
563 		for (cg = startcg; cg < fs->fs_ncg; cg++)
564 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
565 				fs->fs_cgrotor = cg;
566 				mutex_exit(&ufsvfsp->vfs_lock);
567 				return (fs->fs_fpg * cg + fs->fs_frag);
568 			}
569 		for (cg = 0; cg <= startcg; cg++)
570 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
571 				fs->fs_cgrotor = cg;
572 				mutex_exit(&ufsvfsp->vfs_lock);
573 				return (fs->fs_fpg * cg + fs->fs_frag);
574 			}
575 		mutex_exit(&ufsvfsp->vfs_lock);
576 		return (NULL);
577 	}
578 	/*
579 	 * One or more previous blocks have been laid out. If less
580 	 * than fs_maxcontig previous blocks are contiguous, the
581 	 * next block is requested contiguously, otherwise it is
582 	 * requested rotationally delayed by fs_rotdelay milliseconds.
583 	 */
584 	nextblk = bap[indx - 1] + fs->fs_frag;
585 	if (indx > fs->fs_maxcontig &&
586 	    bap[indx - fs->fs_maxcontig] + blkstofrags(fs, fs->fs_maxcontig)
587 	    != nextblk)
588 		return (nextblk);
589 	if (fs->fs_rotdelay != 0)
590 		/*
591 		 * Here we convert ms of delay to frags as:
592 		 * (frags) = (ms) * (rev/sec) * (sect/rev) /
593 		 *	((sect/frag) * (ms/sec))
594 		 * then round up to the next block.
595 		 */
596 		nextblk += roundup(fs->fs_rotdelay * fs->fs_rps * fs->fs_nsect /
597 		    (NSPF(fs) * 1000), fs->fs_frag);
598 	return (nextblk);
599 }
600 
601 /*
602  * Free a block or fragment.
603  *
604  * The specified block or fragment is placed back in the
605  * free map. If a fragment is deallocated, a possible
606  * block reassembly is checked.
607  */
608 void
609 free(struct inode *ip, daddr_t bno, off_t size, int flags)
610 {
611 	struct fs *fs = ip->i_fs;
612 	struct ufsvfs *ufsvfsp = ip->i_ufsvfs;
613 	struct ufs_q *delq = &ufsvfsp->vfs_delete;
614 	struct ufs_delq_info *delq_info = &ufsvfsp->vfs_delete_info;
615 	struct cg *cgp;
616 	struct buf *bp;
617 	int cg, bmap, bbase;
618 	int i;
619 	uchar_t *blksfree;
620 	int *blktot;
621 	short *blks;
622 	daddr_t blkno, cylno, rpos;
623 
624 	if ((unsigned long)size > fs->fs_bsize || fragoff(fs, size) != 0) {
625 		(void) ufs_fault(ITOV(ip),
626 		"free: bad size, dev = 0x%lx, bsize = %d, size = %d, fs = %s\n",
627 		    ip->i_dev, fs->fs_bsize, (int)size, fs->fs_fsmnt);
628 		return;
629 	}
630 	cg = dtog(fs, bno);
631 	ASSERT(!ufs_badblock(ip, bno));
632 	bp = UFS_BREAD(ufsvfsp, ip->i_dev, (daddr_t)fsbtodb(fs, cgtod(fs, cg)),
633 		    (int)fs->fs_cgsize);
634 
635 	cgp = bp->b_un.b_cg;
636 	if (bp->b_flags & B_ERROR || !cg_chkmagic(cgp)) {
637 		brelse(bp);
638 		return;
639 	}
640 
641 	if (!(flags & I_NOCANCEL))
642 		TRANS_CANCEL(ufsvfsp, ldbtob(fsbtodb(fs, bno)), size, flags);
643 	if (flags & (I_DIR|I_IBLK|I_SHAD|I_QUOTA)) {
644 		TRANS_MATA_FREE(ufsvfsp, ldbtob(fsbtodb(fs, bno)), size);
645 	}
646 	blksfree = cg_blksfree(cgp);
647 	blktot = cg_blktot(cgp);
648 	mutex_enter(&ufsvfsp->vfs_lock);
649 	cgp->cg_time = gethrestime_sec();
650 	bno = dtogd(fs, bno);
651 	if (size == fs->fs_bsize) {
652 		blkno = fragstoblks(fs, bno);
653 		cylno = cbtocylno(fs, bno);
654 		rpos = cbtorpos(ufsvfsp, bno);
655 		blks = cg_blks(ufsvfsp, cgp, cylno);
656 		if (!isclrblock(fs, blksfree, blkno)) {
657 			mutex_exit(&ufsvfsp->vfs_lock);
658 			brelse(bp);
659 			(void) ufs_fault(ITOV(ip), "free: freeing free block, "
660 			    "dev:0x%lx, block:%ld, ino:%lu, fs:%s",
661 			    ip->i_dev, bno, ip->i_number, fs->fs_fsmnt);
662 			return;
663 		}
664 		setblock(fs, blksfree, blkno);
665 		blks[rpos]++;
666 		blktot[cylno]++;
667 		cgp->cg_cs.cs_nbfree++;		/* Log below */
668 		fs->fs_cstotal.cs_nbfree++;
669 		fs->fs_cs(fs, cg).cs_nbfree++;
670 		if (TRANS_ISTRANS(ufsvfsp) && (flags & I_ACCT)) {
671 			mutex_enter(&delq->uq_mutex);
672 			delq_info->delq_unreclaimed_blocks -=
673 			    btodb(fs->fs_bsize);
674 			mutex_exit(&delq->uq_mutex);
675 		}
676 	} else {
677 		bbase = bno - fragnum(fs, bno);
678 		/*
679 		 * Decrement the counts associated with the old frags
680 		 */
681 		bmap = blkmap(fs, blksfree, bbase);
682 		fragacct(fs, bmap, cgp->cg_frsum, -1);
683 		/*
684 		 * Deallocate the fragment
685 		 */
686 		for (i = 0; i < numfrags(fs, size); i++) {
687 			if (isset(blksfree, bno + i)) {
688 				brelse(bp);
689 				mutex_exit(&ufsvfsp->vfs_lock);
690 				(void) ufs_fault(ITOV(ip),
691 				    "free: freeing free frag, "
692 				    "dev:0x%lx, blk:%ld, cg:%d, "
693 				    "ino:%lu, fs:%s",
694 				    ip->i_dev,
695 				    bno + i,
696 				    cgp->cg_cgx,
697 				    ip->i_number,
698 				    fs->fs_fsmnt);
699 				return;
700 			}
701 			setbit(blksfree, bno + i);
702 		}
703 		cgp->cg_cs.cs_nffree += i;
704 		fs->fs_cstotal.cs_nffree += i;
705 		fs->fs_cs(fs, cg).cs_nffree += i;
706 		if (TRANS_ISTRANS(ufsvfsp) && (flags & I_ACCT)) {
707 			mutex_enter(&delq->uq_mutex);
708 			delq_info->delq_unreclaimed_blocks -=
709 			    btodb(i * fs->fs_fsize);
710 			mutex_exit(&delq->uq_mutex);
711 		}
712 		/*
713 		 * Add back in counts associated with the new frags
714 		 */
715 		bmap = blkmap(fs, blksfree, bbase);
716 		fragacct(fs, bmap, cgp->cg_frsum, 1);
717 		/*
718 		 * If a complete block has been reassembled, account for it
719 		 */
720 		blkno = fragstoblks(fs, bbase);
721 		if (isblock(fs, blksfree, blkno)) {
722 			cylno = cbtocylno(fs, bbase);
723 			rpos = cbtorpos(ufsvfsp, bbase);
724 			blks = cg_blks(ufsvfsp, cgp, cylno);
725 			blks[rpos]++;
726 			blktot[cylno]++;
727 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
728 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
729 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
730 			cgp->cg_cs.cs_nbfree++;
731 			fs->fs_cstotal.cs_nbfree++;
732 			fs->fs_cs(fs, cg).cs_nbfree++;
733 		}
734 	}
735 	fs->fs_fmod = 1;
736 	ufs_notclean(ufsvfsp);
737 	TRANS_BUF(ufsvfsp, 0, fs->fs_cgsize, bp, DT_CG);
738 	TRANS_SI(ufsvfsp, fs, cg);
739 	bdrwrite(bp);
740 }
741 
742 /*
743  * Free an inode.
744  *
745  * The specified inode is placed back in the free map.
746  */
747 void
748 ufs_ifree(struct inode *ip, ino_t ino, mode_t mode)
749 {
750 	struct fs *fs = ip->i_fs;
751 	struct ufsvfs *ufsvfsp = ip->i_ufsvfs;
752 	struct cg *cgp;
753 	struct buf *bp;
754 	unsigned int inot;
755 	int cg;
756 	char *iused;
757 
758 	if (ip->i_number == ino && ip->i_mode != 0) {
759 		(void) ufs_fault(ITOV(ip),
760 		    "ufs_ifree: illegal mode: (imode) %o, (omode) %o, ino %d, "
761 		    "fs = %s\n",
762 		    ip->i_mode, mode, (int)ip->i_number, fs->fs_fsmnt);
763 		return;
764 	}
765 	if (ino >= fs->fs_ipg * fs->fs_ncg) {
766 		(void) ufs_fault(ITOV(ip),
767 		    "ifree: range, dev = 0x%x, ino = %d, fs = %s\n",
768 		    (int)ip->i_dev, (int)ino, fs->fs_fsmnt);
769 		return;
770 	}
771 	cg = (int)itog(fs, ino);
772 	bp = UFS_BREAD(ufsvfsp, ip->i_dev, (daddr_t)fsbtodb(fs, cgtod(fs, cg)),
773 		    (int)fs->fs_cgsize);
774 
775 	cgp = bp->b_un.b_cg;
776 	if (bp->b_flags & B_ERROR || !cg_chkmagic(cgp)) {
777 		brelse(bp);
778 		return;
779 	}
780 	mutex_enter(&ufsvfsp->vfs_lock);
781 	cgp->cg_time = gethrestime_sec();
782 	iused = cg_inosused(cgp);
783 	inot = (unsigned int)(ino % (ulong_t)fs->fs_ipg);
784 	if (isclr(iused, inot)) {
785 		mutex_exit(&ufsvfsp->vfs_lock);
786 		brelse(bp);
787 		(void) ufs_fault(ITOV(ip), "ufs_ifree: freeing free inode, "
788 				    "mode: (imode) %o, (omode) %o, ino:%d, "
789 				    "fs:%s",
790 				    ip->i_mode, mode, (int)ino, fs->fs_fsmnt);
791 		return;
792 	}
793 	clrbit(iused, inot);
794 
795 	if (inot < (ulong_t)cgp->cg_irotor)
796 		cgp->cg_irotor = inot;
797 	cgp->cg_cs.cs_nifree++;
798 	fs->fs_cstotal.cs_nifree++;
799 	fs->fs_cs(fs, cg).cs_nifree++;
800 	if (((mode & IFMT) == IFDIR) || ((mode & IFMT) == IFATTRDIR)) {
801 		cgp->cg_cs.cs_ndir--;
802 		fs->fs_cstotal.cs_ndir--;
803 		fs->fs_cs(fs, cg).cs_ndir--;
804 	}
805 	fs->fs_fmod = 1;
806 	ufs_notclean(ufsvfsp);
807 	TRANS_BUF(ufsvfsp, 0, fs->fs_cgsize, bp, DT_CG);
808 	TRANS_SI(ufsvfsp, fs, cg);
809 	bdrwrite(bp);
810 }
811 
812 /*
813  * Implement the cylinder overflow algorithm.
814  *
815  * The policy implemented by this algorithm is:
816  *   1) allocate the block in its requested cylinder group.
817  *   2) quadratically rehash on the cylinder group number.
818  *   3) brute force search for a free block.
819  * The size parameter means size for data blocks, mode for inodes.
820  */
821 static ino_t
822 hashalloc(struct inode *ip, int cg, long pref, int size, ulong_t (*allocator)())
823 {
824 	struct fs *fs;
825 	int i;
826 	long result;
827 	int icg = cg;
828 
829 	fs = ip->i_fs;
830 	/*
831 	 * 1: preferred cylinder group
832 	 */
833 	result = (*allocator)(ip, cg, pref, size);
834 	if (result)
835 		return (result);
836 	/*
837 	 * 2: quadratic rehash
838 	 */
839 	for (i = 1; i < fs->fs_ncg; i *= 2) {
840 		cg += i;
841 		if (cg >= fs->fs_ncg)
842 			cg -= fs->fs_ncg;
843 		result = (*allocator)(ip, cg, 0, size);
844 		if (result)
845 			return (result);
846 	}
847 	/*
848 	 * 3: brute force search
849 	 * Note that we start at i == 2, since 0 was checked initially,
850 	 * and 1 is always checked in the quadratic rehash.
851 	 */
852 	cg = (icg + 2) % fs->fs_ncg;
853 	for (i = 2; i < fs->fs_ncg; i++) {
854 		result = (*allocator)(ip, cg, 0, size);
855 		if (result)
856 			return (result);
857 		cg++;
858 		if (cg == fs->fs_ncg)
859 			cg = 0;
860 	}
861 	return (NULL);
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 static daddr_t
871 fragextend(struct inode *ip, int cg, long bprev, int osize, int nsize)
872 {
873 	struct ufsvfs *ufsvfsp = ip->i_ufsvfs;
874 	struct fs *fs = ip->i_fs;
875 	struct buf *bp;
876 	struct cg *cgp;
877 	uchar_t *blksfree;
878 	long bno;
879 	int frags, bbase;
880 	int i, j;
881 
882 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
883 		return (NULL);
884 	frags = numfrags(fs, nsize);
885 	bbase = (int)fragnum(fs, bprev);
886 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
887 		/* cannot extend across a block boundary */
888 		return (NULL);
889 	}
890 
891 	bp = UFS_BREAD(ufsvfsp, ip->i_dev, (daddr_t)fsbtodb(fs, cgtod(fs, cg)),
892 		    (int)fs->fs_cgsize);
893 	cgp = bp->b_un.b_cg;
894 	if (bp->b_flags & B_ERROR || !cg_chkmagic(cgp)) {
895 		brelse(bp);
896 		return (NULL);
897 	}
898 
899 	blksfree = cg_blksfree(cgp);
900 	mutex_enter(&ufsvfsp->vfs_lock);
901 	bno = dtogd(fs, bprev);
902 	for (i = numfrags(fs, osize); i < frags; i++) {
903 		if (isclr(blksfree, bno + i)) {
904 			mutex_exit(&ufsvfsp->vfs_lock);
905 			brelse(bp);
906 			return (NULL);
907 		}
908 		if ((TRANS_ISCANCEL(ufsvfsp, ldbtob(fsbtodb(fs, bprev + i)),
909 			fs->fs_fsize))) {
910 			mutex_exit(&ufsvfsp->vfs_lock);
911 			brelse(bp);
912 			return (NULL);
913 		}
914 	}
915 
916 	cgp->cg_time = gethrestime_sec();
917 	/*
918 	 * The current fragment can be extended,
919 	 * deduct the count on fragment being extended into
920 	 * increase the count on the remaining fragment (if any)
921 	 * allocate the extended piece.
922 	 */
923 	for (i = frags; i < fs->fs_frag - bbase; i++)
924 		if (isclr(blksfree, bno + i))
925 			break;
926 	j = i - numfrags(fs, osize);
927 	cgp->cg_frsum[j]--;
928 	ASSERT(cgp->cg_frsum[j] >= 0);
929 	if (i != frags)
930 		cgp->cg_frsum[i - frags]++;
931 	for (i = numfrags(fs, osize); i < frags; i++) {
932 		clrbit(blksfree, bno + i);
933 		cgp->cg_cs.cs_nffree--;
934 		fs->fs_cs(fs, cg).cs_nffree--;
935 		fs->fs_cstotal.cs_nffree--;
936 	}
937 	fs->fs_fmod = 1;
938 	ufs_notclean(ufsvfsp);
939 	TRANS_BUF(ufsvfsp, 0, fs->fs_cgsize, bp, DT_CG);
940 	TRANS_SI(ufsvfsp, fs, cg);
941 	bdrwrite(bp);
942 	return ((daddr_t)bprev);
943 }
944 
945 /*
946  * Determine whether a block can be allocated.
947  *
948  * Check to see if a block of the apprpriate size
949  * is available, and if it is, allocate it.
950  */
951 static daddr_t
952 alloccg(struct inode *ip, int cg, daddr_t bpref, int size)
953 {
954 	struct ufsvfs *ufsvfsp = ip->i_ufsvfs;
955 	struct fs *fs = ip->i_fs;
956 	struct buf *bp;
957 	struct cg *cgp;
958 	uchar_t *blksfree;
959 	int bno, frags;
960 	int allocsiz;
961 	int i;
962 
963 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
964 		return (0);
965 	bp = UFS_BREAD(ufsvfsp, ip->i_dev, (daddr_t)fsbtodb(fs, cgtod(fs, cg)),
966 		    (int)fs->fs_cgsize);
967 
968 	cgp = bp->b_un.b_cg;
969 	if (bp->b_flags & B_ERROR || !cg_chkmagic(cgp) ||
970 	    (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize)) {
971 		brelse(bp);
972 		return (0);
973 	}
974 	blksfree = cg_blksfree(cgp);
975 	mutex_enter(&ufsvfsp->vfs_lock);
976 	cgp->cg_time = gethrestime_sec();
977 	if (size == fs->fs_bsize) {
978 		if ((bno = alloccgblk(ufsvfsp, cgp, bpref, bp)) == 0)
979 			goto errout;
980 		fs->fs_fmod = 1;
981 		ufs_notclean(ufsvfsp);
982 		TRANS_SI(ufsvfsp, fs, cg);
983 		bdrwrite(bp);
984 		return (bno);
985 	}
986 	/*
987 	 * Check to see if any fragments are already available
988 	 * allocsiz is the size which will be allocated, hacking
989 	 * it down to a smaller size if necessary.
990 	 */
991 	frags = numfrags(fs, size);
992 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
993 		if (cgp->cg_frsum[allocsiz] != 0)
994 			break;
995 
996 	if (allocsiz != fs->fs_frag)
997 		bno = mapsearch(ufsvfsp, cgp, bpref, allocsiz);
998 
999 	if (allocsiz == fs->fs_frag || bno < 0) {
1000 		/*
1001 		 * No fragments were available, so a block
1002 		 * will be allocated and hacked up.
1003 		 */
1004 		if (cgp->cg_cs.cs_nbfree == 0)
1005 			goto errout;
1006 		if ((bno = alloccgblk(ufsvfsp, cgp, bpref, bp)) == 0)
1007 			goto errout;
1008 		bpref = dtogd(fs, bno);
1009 		for (i = frags; i < fs->fs_frag; i++)
1010 			setbit(blksfree, bpref + i);
1011 		i = fs->fs_frag - frags;
1012 		cgp->cg_cs.cs_nffree += i;
1013 		fs->fs_cstotal.cs_nffree += i;
1014 		fs->fs_cs(fs, cg).cs_nffree += i;
1015 		cgp->cg_frsum[i]++;
1016 		fs->fs_fmod = 1;
1017 		ufs_notclean(ufsvfsp);
1018 		TRANS_SI(ufsvfsp, fs, cg);
1019 		bdrwrite(bp);
1020 		return (bno);
1021 	}
1022 
1023 	for (i = 0; i < frags; i++)
1024 		clrbit(blksfree, bno + i);
1025 	cgp->cg_cs.cs_nffree -= frags;
1026 	fs->fs_cstotal.cs_nffree -= frags;
1027 	fs->fs_cs(fs, cg).cs_nffree -= frags;
1028 	cgp->cg_frsum[allocsiz]--;
1029 	ASSERT(cgp->cg_frsum[allocsiz] >= 0);
1030 	if (frags != allocsiz) {
1031 		cgp->cg_frsum[allocsiz - frags]++;
1032 	}
1033 	fs->fs_fmod = 1;
1034 	ufs_notclean(ufsvfsp);
1035 	TRANS_BUF(ufsvfsp, 0, fs->fs_cgsize, bp, DT_CG);
1036 	TRANS_SI(ufsvfsp, fs, cg);
1037 	bdrwrite(bp);
1038 	return (cg * fs->fs_fpg + bno);
1039 errout:
1040 	mutex_exit(&ufsvfsp->vfs_lock);
1041 	brelse(bp);
1042 	return (0);
1043 }
1044 
1045 /*
1046  * Allocate a block in a cylinder group.
1047  *
1048  * This algorithm implements the following policy:
1049  *   1) allocate the requested block.
1050  *   2) allocate a rotationally optimal block in the same cylinder.
1051  *   3) allocate the next available block on the block rotor for the
1052  *	specified cylinder group.
1053  * Note that this routine only allocates fs_bsize blocks; these
1054  * blocks may be fragmented by the routine that allocates them.
1055  */
1056 static daddr_t
1057 alloccgblk(
1058 	struct ufsvfs *ufsvfsp,
1059 	struct cg *cgp,
1060 	daddr_t bpref,
1061 	struct buf *bp)
1062 {
1063 	daddr_t bno;
1064 	int cylno, pos, delta, rotbl_size;
1065 	short *cylbp;
1066 	int i;
1067 	struct fs *fs;
1068 	uchar_t *blksfree;
1069 	daddr_t blkno, rpos, frag;
1070 	short *blks;
1071 	int32_t *blktot;
1072 
1073 	ASSERT(MUTEX_HELD(&ufsvfsp->vfs_lock));
1074 	fs = ufsvfsp->vfs_fs;
1075 	blksfree = cg_blksfree(cgp);
1076 	if (bpref == 0) {
1077 		bpref = cgp->cg_rotor;
1078 		goto norot;
1079 	}
1080 	bpref = blknum(fs, bpref);
1081 	bpref = dtogd(fs, bpref);
1082 	/*
1083 	 * If the requested block is available, use it.
1084 	 */
1085 	if (isblock(fs, blksfree, (daddr_t)fragstoblks(fs, bpref))) {
1086 		bno = bpref;
1087 		goto gotit;
1088 	}
1089 	/*
1090 	 * Check for a block available on the same cylinder.
1091 	 */
1092 	cylno = cbtocylno(fs, bpref);
1093 	if (cg_blktot(cgp)[cylno] == 0)
1094 		goto norot;
1095 	if (fs->fs_cpc == 0) {
1096 		/*
1097 		 * Block layout info is not available, so just
1098 		 * have to take any block in this cylinder.
1099 		 */
1100 		bpref = howmany(fs->fs_spc * cylno, NSPF(fs));
1101 		goto norot;
1102 	}
1103 	/*
1104 	 * Check the summary information to see if a block is
1105 	 * available in the requested cylinder starting at the
1106 	 * requested rotational position and proceeding around.
1107 	 */
1108 	cylbp = cg_blks(ufsvfsp, cgp, cylno);
1109 	pos = cbtorpos(ufsvfsp, bpref);
1110 	for (i = pos; i < ufsvfsp->vfs_nrpos; i++)
1111 		if (cylbp[i] > 0)
1112 			break;
1113 	if (i == ufsvfsp->vfs_nrpos)
1114 		for (i = 0; i < pos; i++)
1115 			if (cylbp[i] > 0)
1116 				break;
1117 	if (cylbp[i] > 0) {
1118 		/*
1119 		 * Found a rotational position, now find the actual
1120 		 * block.  A "panic" if none is actually there.
1121 		 */
1122 
1123 		/*
1124 		 * Up to this point, "pos" has referred to the rotational
1125 		 * position of the desired block.  From now on, it holds
1126 		 * the offset of the current cylinder within a cylinder
1127 		 * cycle.  (A cylinder cycle refers to a set of cylinders
1128 		 * which are described by a single rotational table; the
1129 		 * size of the cycle is fs_cpc.)
1130 		 *
1131 		 * bno is set to the block number of the first block within
1132 		 * the current cylinder cycle.
1133 		 */
1134 
1135 		pos = cylno % fs->fs_cpc;
1136 		bno = (cylno - pos) * fs->fs_spc / NSPB(fs);
1137 
1138 		/*
1139 		 * The blocks within a cylinder are grouped into equivalence
1140 		 * classes according to their "rotational position."  There
1141 		 * are two tables used to determine these classes.
1142 		 *
1143 		 * The positional offset table (fs_postbl) has an entry for
1144 		 * each rotational position of each cylinder in a cylinder
1145 		 * cycle.  This entry contains the relative block number
1146 		 * (counting from the start of the cylinder cycle) of the
1147 		 * first block in the equivalence class for that position
1148 		 * and that cylinder.  Positions for which no blocks exist
1149 		 * are indicated by a -1.
1150 		 *
1151 		 * The rotational delta table (fs_rotbl) has an entry for
1152 		 * each block in a cylinder cycle.  This entry contains
1153 		 * the offset from that block to the next block in the
1154 		 * same equivalence class.  The last block in the class
1155 		 * is indicated by a zero in the table.
1156 		 *
1157 		 * The following code, then, walks through all of the blocks
1158 		 * in the cylinder (cylno) which we're allocating within
1159 		 * which are in the equivalence class for the rotational
1160 		 * position (i) which we're allocating within.
1161 		 */
1162 
1163 		if (fs_postbl(ufsvfsp, pos)[i] == -1) {
1164 			(void) ufs_fault(ufsvfsp->vfs_root,
1165 	    "alloccgblk: cyl groups corrupted, pos = %d, i = %d, fs = %s\n",
1166 				    pos, i, fs->fs_fsmnt);
1167 			return (0);
1168 		}
1169 
1170 		/*
1171 		 * There is one entry in the rotational table for each block
1172 		 * in the cylinder cycle.  These are whole blocks, not frags.
1173 		 */
1174 
1175 		rotbl_size = (fs->fs_cpc * fs->fs_spc) >>
1176 		    (fs->fs_fragshift + fs->fs_fsbtodb);
1177 
1178 		/*
1179 		 * As we start, "i" is the rotational position within which
1180 		 * we're searching.  After the next line, it will be a block
1181 		 * number (relative to the start of the cylinder cycle)
1182 		 * within the equivalence class of that rotational position.
1183 		 */
1184 
1185 		i = fs_postbl(ufsvfsp, pos)[i];
1186 
1187 		for (;;) {
1188 			if (isblock(fs, blksfree, (daddr_t)(bno + i))) {
1189 				bno = blkstofrags(fs, (bno + i));
1190 				goto gotit;
1191 			}
1192 			delta = fs_rotbl(fs)[i];
1193 			if (delta <= 0 ||		/* End of chain, or */
1194 			    delta + i > rotbl_size)	/* end of table? */
1195 				break;			/* If so, panic. */
1196 			i += delta;
1197 		}
1198 		(void) ufs_fault(ufsvfsp->vfs_root,
1199 	"alloccgblk: can't find blk in cyl, pos:%d, i:%d, fs:%s bno: %x\n",
1200 		    pos, i, fs->fs_fsmnt, (int)bno);
1201 		return (0);
1202 	}
1203 norot:
1204 	/*
1205 	 * No blocks in the requested cylinder, so take
1206 	 * next available one in this cylinder group.
1207 	 */
1208 	bno = mapsearch(ufsvfsp, cgp, bpref, (int)fs->fs_frag);
1209 	if (bno < 0)
1210 		return (0);
1211 	cgp->cg_rotor = bno;
1212 gotit:
1213 	blkno = fragstoblks(fs, bno);
1214 	frag = (cgp->cg_cgx * fs->fs_fpg) + bno;
1215 	if (TRANS_ISCANCEL(ufsvfsp, ldbtob(fsbtodb(fs, frag)), fs->fs_bsize))
1216 		goto norot;
1217 	clrblock(fs, blksfree, (long)blkno);
1218 	/*
1219 	 * the other cg/sb/si fields are TRANS'ed by the caller
1220 	 */
1221 	cgp->cg_cs.cs_nbfree--;
1222 	fs->fs_cstotal.cs_nbfree--;
1223 	fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1224 	cylno = cbtocylno(fs, bno);
1225 	blks = cg_blks(ufsvfsp, cgp, cylno);
1226 	rpos = cbtorpos(ufsvfsp, bno);
1227 	blktot = cg_blktot(cgp);
1228 	blks[rpos]--;
1229 	blktot[cylno]--;
1230 	TRANS_BUF(ufsvfsp, 0, fs->fs_cgsize, bp, DT_CG);
1231 	fs->fs_fmod = 1;
1232 	return (frag);
1233 }
1234 
1235 /*
1236  * Determine whether an inode can be allocated.
1237  *
1238  * Check to see if an inode is available, and if it is,
1239  * allocate it using the following policy:
1240  *   1) allocate the requested inode.
1241  *   2) allocate the next available inode after the requested
1242  *	inode in the specified cylinder group.
1243  */
1244 static ino_t
1245 ialloccg(struct inode *ip, int cg, daddr_t ipref, int mode)
1246 {
1247 	struct ufsvfs *ufsvfsp = ip->i_ufsvfs;
1248 	struct fs *fs = ip->i_fs;
1249 	struct cg *cgp;
1250 	struct buf *bp;
1251 	int start, len, loc, map, i;
1252 	char *iused;
1253 
1254 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
1255 		return (0);
1256 	bp = UFS_BREAD(ufsvfsp, ip->i_dev, (daddr_t)fsbtodb(fs, cgtod(fs, cg)),
1257 		    (int)fs->fs_cgsize);
1258 
1259 	cgp = bp->b_un.b_cg;
1260 	if (bp->b_flags & B_ERROR || !cg_chkmagic(cgp) ||
1261 	    cgp->cg_cs.cs_nifree == 0) {
1262 		brelse(bp);
1263 		return (0);
1264 	}
1265 	iused = cg_inosused(cgp);
1266 	mutex_enter(&ufsvfsp->vfs_lock);
1267 	/*
1268 	 * While we are waiting for the mutex, someone may have taken
1269 	 * the last available inode.  Need to recheck.
1270 	 */
1271 	if (cgp->cg_cs.cs_nifree == 0) {
1272 		mutex_exit(&ufsvfsp->vfs_lock);
1273 		brelse(bp);
1274 		return (0);
1275 	}
1276 
1277 	cgp->cg_time = gethrestime_sec();
1278 	if (ipref) {
1279 		ipref %= fs->fs_ipg;
1280 		if (isclr(iused, ipref))
1281 			goto gotit;
1282 	}
1283 	start = cgp->cg_irotor / NBBY;
1284 	len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
1285 	loc = skpc(0xff, (uint_t)len, &iused[start]);
1286 	if (loc == 0) {
1287 		len = start + 1;
1288 		start = 0;
1289 		loc = skpc(0xff, (uint_t)len, &iused[0]);
1290 		if (loc == 0) {
1291 			mutex_exit(&ufsvfsp->vfs_lock);
1292 			(void) ufs_fault(ITOV(ip),
1293 		    "ialloccg: map corrupted, cg = %d, irotor = %d, fs = %s\n",
1294 				    cg, (int)cgp->cg_irotor, fs->fs_fsmnt);
1295 			return (0);
1296 		}
1297 	}
1298 	i = start + len - loc;
1299 	map = iused[i];
1300 	ipref = i * NBBY;
1301 	for (i = 1; i < (1 << NBBY); i <<= 1, ipref++) {
1302 		if ((map & i) == 0) {
1303 			cgp->cg_irotor = ipref;
1304 			goto gotit;
1305 		}
1306 	}
1307 
1308 	mutex_exit(&ufsvfsp->vfs_lock);
1309 	(void) ufs_fault(ITOV(ip), "ialloccg: block not in mapfs = %s",
1310 							    fs->fs_fsmnt);
1311 	return (0);
1312 gotit:
1313 	setbit(iused, ipref);
1314 	cgp->cg_cs.cs_nifree--;
1315 	fs->fs_cstotal.cs_nifree--;
1316 	fs->fs_cs(fs, cg).cs_nifree--;
1317 	if (((mode & IFMT) == IFDIR) || ((mode & IFMT) == IFATTRDIR)) {
1318 		cgp->cg_cs.cs_ndir++;
1319 		fs->fs_cstotal.cs_ndir++;
1320 		fs->fs_cs(fs, cg).cs_ndir++;
1321 	}
1322 	fs->fs_fmod = 1;
1323 	ufs_notclean(ufsvfsp);
1324 	TRANS_BUF(ufsvfsp, 0, fs->fs_cgsize, bp, DT_CG);
1325 	TRANS_SI(ufsvfsp, fs, cg);
1326 	bdrwrite(bp);
1327 	return (cg * fs->fs_ipg + ipref);
1328 }
1329 
1330 /*
1331  * Find a block of the specified size in the specified cylinder group.
1332  *
1333  * It is a panic if a request is made to find a block if none are
1334  * available.
1335  */
1336 static daddr_t
1337 mapsearch(struct ufsvfs *ufsvfsp, struct cg *cgp, daddr_t bpref,
1338 	int allocsiz)
1339 {
1340 	struct fs *fs	= ufsvfsp->vfs_fs;
1341 	daddr_t bno, cfrag;
1342 	int start, len, loc, i, last, first, secondtime;
1343 	int blk, field, subfield, pos;
1344 	int gotit;
1345 
1346 	/*
1347 	 * ufsvfs->vfs_lock is held when calling this.
1348 	 */
1349 	/*
1350 	 * Find the fragment by searching through the
1351 	 * free block map for an appropriate bit pattern.
1352 	 */
1353 	if (bpref)
1354 		start = dtogd(fs, bpref) / NBBY;
1355 	else
1356 		start = cgp->cg_frotor / NBBY;
1357 	/*
1358 	 * the following loop performs two scans -- the first scan
1359 	 * searches the bottom half of the array for a match and the
1360 	 * second scan searches the top half of the array.  The loops
1361 	 * have been merged just to make things difficult.
1362 	 */
1363 	first = start;
1364 	last = howmany(fs->fs_fpg, NBBY);
1365 	secondtime = 0;
1366 	cfrag = cgp->cg_cgx * fs->fs_fpg;
1367 	while (first < last) {
1368 		len = last - first;
1369 		/*
1370 		 * search the array for a match
1371 		 */
1372 		loc = scanc((unsigned)len, (uchar_t *)&cg_blksfree(cgp)[first],
1373 			(uchar_t *)fragtbl[fs->fs_frag],
1374 			(int)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
1375 		/*
1376 		 * match found
1377 		 */
1378 		if (loc) {
1379 			bno = (last - loc) * NBBY;
1380 
1381 			/*
1382 			 * Found the byte in the map, sift
1383 			 * through the bits to find the selected frag
1384 			 */
1385 			cgp->cg_frotor = bno;
1386 			gotit = 0;
1387 			for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
1388 				blk = blkmap(fs, cg_blksfree(cgp), bno);
1389 				blk <<= 1;
1390 				field = around[allocsiz];
1391 				subfield = inside[allocsiz];
1392 				for (pos = 0;
1393 				    pos <= fs->fs_frag - allocsiz;
1394 				    pos++) {
1395 					if ((blk & field) == subfield) {
1396 						gotit++;
1397 						break;
1398 					}
1399 					field <<= 1;
1400 					subfield <<= 1;
1401 				}
1402 				if (gotit)
1403 					break;
1404 			}
1405 			bno += pos;
1406 
1407 			/*
1408 			 * success if block is *not* being converted from
1409 			 * metadata into userdata (harpy).  If so, ignore.
1410 			 */
1411 			if (!TRANS_ISCANCEL(ufsvfsp,
1412 				ldbtob(fsbtodb(fs, (cfrag+bno))),
1413 				allocsiz * fs->fs_fsize))
1414 				return (bno);
1415 			/*
1416 			 * keep looking -- this block is being converted
1417 			 */
1418 			first = (last - loc) + 1;
1419 			loc = 0;
1420 			if (first < last)
1421 				continue;
1422 		}
1423 		/*
1424 		 * no usable matches in bottom half -- now search the top half
1425 		 */
1426 		if (secondtime)
1427 			/*
1428 			 * no usable matches in top half -- all done
1429 			 */
1430 			break;
1431 		secondtime = 1;
1432 		last = start + 1;
1433 		first = 0;
1434 	}
1435 	/*
1436 	 * no usable matches
1437 	 */
1438 	return ((daddr_t)-1);
1439 }
1440 
1441 #define	UFSNADDR (NDADDR + NIADDR)	/* NADDR applies to (obsolete) S5FS */
1442 #define	IB(i)	(NDADDR + (i))	/* index of i'th indirect block ptr */
1443 #define	SINGLE	0		/* single indirect block ptr */
1444 #define	DOUBLE	1		/* double indirect block ptr */
1445 #define	TRIPLE	2		/* triple indirect block ptr */
1446 
1447 /*
1448  * Free storage space associated with the specified inode.  The portion
1449  * to be freed is specified by lp->l_start and lp->l_len (already
1450  * normalized to a "whence" of 0).
1451  *
1452  * This is an experimental facility whose continued existence is not
1453  * guaranteed.  Currently, we only support the special case
1454  * of l_len == 0, meaning free to end of file.
1455  *
1456  * Blocks are freed in reverse order.  This FILO algorithm will tend to
1457  * maintain a contiguous free list much longer than FIFO.
1458  * See also ufs_itrunc() in ufs_inode.c.
1459  *
1460  * Bug: unused bytes in the last retained block are not cleared.
1461  * This may result in a "hole" in the file that does not read as zeroes.
1462  */
1463 /* ARGSUSED */
1464 int
1465 ufs_freesp(struct vnode *vp, struct flock64 *lp, int flag, cred_t *cr)
1466 {
1467 	int i;
1468 	struct inode *ip = VTOI(vp);
1469 	int error;
1470 
1471 	ASSERT(vp->v_type == VREG);
1472 	ASSERT(lp->l_start >= 0);	/* checked by convoff */
1473 
1474 	if (lp->l_len != 0)
1475 		return (EINVAL);
1476 
1477 	rw_enter(&ip->i_contents, RW_READER);
1478 	if (ip->i_size == (u_offset_t)lp->l_start) {
1479 		rw_exit(&ip->i_contents);
1480 		return (0);
1481 	}
1482 
1483 	/*
1484 	 * Check if there is any active mandatory lock on the
1485 	 * range that will be truncated/expanded.
1486 	 */
1487 	if (MANDLOCK(vp, ip->i_mode)) {
1488 		offset_t save_start;
1489 
1490 		save_start = lp->l_start;
1491 
1492 		if (ip->i_size < lp->l_start) {
1493 			/*
1494 			 * "Truncate up" case: need to make sure there
1495 			 * is no lock beyond current end-of-file. To
1496 			 * do so, we need to set l_start to the size
1497 			 * of the file temporarily.
1498 			 */
1499 			lp->l_start = ip->i_size;
1500 		}
1501 		lp->l_type = F_WRLCK;
1502 		lp->l_sysid = 0;
1503 		lp->l_pid = ttoproc(curthread)->p_pid;
1504 		i = (flag & (FNDELAY|FNONBLOCK)) ? 0 : SLPFLCK;
1505 		rw_exit(&ip->i_contents);
1506 		if ((i = reclock(vp, lp, i, 0, lp->l_start, NULL)) != 0 ||
1507 		    lp->l_type != F_UNLCK) {
1508 			return (i ? i : EAGAIN);
1509 		}
1510 		rw_enter(&ip->i_contents, RW_READER);
1511 
1512 		lp->l_start = save_start;
1513 	}
1514 
1515 	/*
1516 	 * Make sure a write isn't in progress (allocating blocks)
1517 	 * by acquiring i_rwlock (we promised ufs_bmap we wouldn't
1518 	 * truncate while it was allocating blocks).
1519 	 * Grab the locks in the right order.
1520 	 */
1521 	rw_exit(&ip->i_contents);
1522 	rw_enter(&ip->i_rwlock, RW_WRITER);
1523 	error = TRANS_ITRUNC(ip, (u_offset_t)lp->l_start, 0, cr);
1524 	rw_exit(&ip->i_rwlock);
1525 	return (error);
1526 }
1527 
1528 /*
1529  * Find a cg with as close to nb contiguous bytes as possible
1530  *	THIS MAY TAKE MANY DISK READS!
1531  *
1532  * Implemented in an attempt to allocate contiguous blocks for
1533  * writing the ufs log file to, minimizing future disk head seeking
1534  */
1535 daddr_t
1536 contigpref(ufsvfs_t *ufsvfsp, size_t nb)
1537 {
1538 	struct fs	*fs	= ufsvfsp->vfs_fs;
1539 	daddr_t		nblk	= lblkno(fs, blkroundup(fs, nb));
1540 	daddr_t		savebno, curbno, cgbno;
1541 	int		cg, cgblks, savecg, savenblk, curnblk;
1542 	uchar_t		*blksfree;
1543 	buf_t		*bp;
1544 	struct cg	*cgp;
1545 
1546 	savenblk = 0;
1547 	savecg = 0;
1548 	savebno = 0;
1549 	for (cg = 0; cg < fs->fs_ncg; ++cg) {
1550 
1551 		/* not enough free blks for a contig check */
1552 		if (fs->fs_cs(fs, cg).cs_nbfree < nblk)
1553 			continue;
1554 
1555 		/*
1556 		 * find the largest contiguous range in this cg
1557 		 */
1558 		bp = UFS_BREAD(ufsvfsp, ufsvfsp->vfs_dev,
1559 			(daddr_t)fsbtodb(fs, cgtod(fs, cg)),
1560 			(int)fs->fs_cgsize);
1561 		cgp = bp->b_un.b_cg;
1562 		if (bp->b_flags & B_ERROR || !cg_chkmagic(cgp)) {
1563 			brelse(bp);
1564 			continue;
1565 		}
1566 		blksfree = cg_blksfree(cgp);	    /* free array */
1567 		cgblks = fragstoblks(fs, fs->fs_fpg); /* blks in free array */
1568 		cgbno = 0;
1569 		while (cgbno < cgblks && savenblk < nblk) {
1570 			/* find a free block */
1571 			for (; cgbno < cgblks; ++cgbno)
1572 				if (isblock(fs, blksfree, cgbno))
1573 					break;
1574 			curbno = cgbno;
1575 			/* count the number of free blocks */
1576 			for (curnblk = 0; cgbno < cgblks; ++cgbno) {
1577 				if (!isblock(fs, blksfree, cgbno))
1578 					break;
1579 				if (++curnblk >= nblk)
1580 					break;
1581 			}
1582 			if (curnblk > savenblk) {
1583 				savecg = cg;
1584 				savenblk = curnblk;
1585 				savebno = curbno;
1586 			}
1587 		}
1588 		brelse(bp);
1589 		if (savenblk >= nblk)
1590 			break;
1591 	}
1592 
1593 	/* convert block offset in cg to frag offset in cg */
1594 	savebno = blkstofrags(fs, savebno);
1595 
1596 	/* convert frag offset in cg to frag offset in fs */
1597 	savebno += (savecg * fs->fs_fpg);
1598 
1599 	return (savebno);
1600 }
1601