xref: /titanic_50/usr/src/cmd/fs.d/ufs/mkfs/mkfs.c (revision e38a713ad4e0a9c42f8cccd9350412b2c6ccccdb)
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 (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
27 /*	  All Rights Reserved  	*/
28 
29 /*
30  * University Copyright- Copyright (c) 1982, 1986, 1988
31  * The Regents of the University of California
32  * All Rights Reserved
33  *
34  * University Acknowledgment- Portions of this document are derived from
35  * software developed by the University of California, Berkeley, and its
36  * contributors.
37  */
38 
39 #pragma ident	"%Z%%M%	%I%	%E% SMI"
40 
41 
42 /*
43  * The maximum supported file system size (in sectors) is the
44  * number of frags that can be represented in an int32_t field
45  * (INT_MAX) times the maximum number of sectors per frag.  Since
46  * the maximum frag size is MAXBSIZE, the maximum number of sectors
47  * per frag is MAXBSIZE/DEV_BSIZE.
48  */
49 #define	FS_MAX	(((diskaddr_t)INT_MAX) * (MAXBSIZE/DEV_BSIZE))
50 
51 /*
52  * make file system for cylinder-group style file systems
53  *
54  * usage:
55  *
56  *    mkfs [-F FSType] [-V] [-G [-P]] [-M dirname] [-m] [options]
57  *	[-o specific_options]  special size
58  *	[nsect ntrack bsize fsize cpg	minfree	rps nbpi opt apc rotdelay
59  *	  2     3      4     5     6	7	8   9	 10  11  12
60  *	nrpos maxcontig mtb]
61  *	13    14	15
62  *
63  *  where specific_options are:
64  *	N - no create
65  *	nsect - The number of sectors per track
66  *	ntrack - The number of tracks per cylinder
67  *	bsize - block size
68  *	fragsize - fragment size
69  *	cgsize - The number of disk cylinders per cylinder group.
70  * 	free - minimum free space
71  *	rps - rotational speed (rev/sec).
72  *	nbpi - number of data bytes per allocated inode
73  *	opt - optimization (space, time)
74  *	apc - number of alternates
75  *	gap - gap size
76  *	nrpos - number of rotational positions
77  *	maxcontig - maximum number of logical blocks that will be
78  *		allocated contiguously before inserting rotational delay
79  *	mtb - if "y", set up file system for eventual growth to over a
80  *		a terabyte
81  * -P Do not grow the file system, but print on stdout the maximal
82  *    size in sectors to which the file system can be increased. The calculated
83  *    size is limited by the value provided by the operand size.
84  *
85  * Note that -P is a project-private interface and together with -G intended
86  * to be used only by the growfs script. It is therefore purposely not
87  * documented in the man page.
88  * The -P option is covered by PSARC case 2003/422.
89  */
90 
91 /*
92  * The following constants set the defaults used for the number
93  * of sectors/track (fs_nsect), and number of tracks/cyl (fs_ntrak).
94  *
95  *			NSECT		NTRAK
96  *	72MB CDC	18		9
97  *	30MB CDC	18		5
98  *	720KB Diskette	9		2
99  *
100  * However the defaults will be different for disks larger than CHSLIMIT.
101  */
102 
103 #define	DFLNSECT	32
104 #define	DFLNTRAK	16
105 
106 /*
107  * The following default sectors and tracks values are used for
108  * non-efi disks that are larger than the CHS addressing limit. The
109  * existing default cpg of 16 (DESCPG) holds good for larger disks too.
110  */
111 #define	DEF_SECTORS_EFI	128
112 #define	DEF_TRACKS_EFI	48
113 
114 /*
115  * The maximum number of cylinders in a group depends upon how much
116  * information can be stored on a single cylinder. The default is to
117  * use 16 cylinders per group.  This is effectively tradition - it was
118  * the largest value acceptable under SunOs 4.1
119  */
120 #define	DESCPG		16	/* desired fs_cpg */
121 
122 /*
123  * The following two constants set the default block and fragment sizes.
124  * Both constants must be a power of 2 and meet the following constraints:
125  *	MINBSIZE <= DESBLKSIZE <= MAXBSIZE
126  *	DEV_BSIZE <= DESFRAGSIZE <= DESBLKSIZE
127  *	DESBLKSIZE / DESFRAGSIZE <= 8
128  */
129 #define	DESBLKSIZE	8192
130 #define	DESFRAGSIZE	1024
131 
132 /*
133  * MINFREE gives the minimum acceptable percentage of file system
134  * blocks which may be free. If the freelist drops below this level
135  * only the superuser may continue to allocate blocks. This may
136  * be set to 0 if no reserve of free blocks is deemed necessary,
137  * however throughput drops by fifty percent if the file system
138  * is run at between 90% and 100% full; thus the default value of
139  * fs_minfree is 10%. With 10% free space, fragmentation is not a
140  * problem, so we choose to optimize for time.
141  */
142 #define	MINFREE		10
143 #define	DEFAULTOPT	FS_OPTTIME
144 
145 /*
146  * ROTDELAY gives the minimum number of milliseconds to initiate
147  * another disk transfer on the same cylinder. It is no longer used
148  * and will always default to 0.
149  */
150 #define	ROTDELAY	0
151 
152 /*
153  * MAXBLKPG determines the maximum number of data blocks which are
154  * placed in a single cylinder group. The default is one indirect
155  * block worth of data blocks.
156  */
157 #define	MAXBLKPG(bsize)	((bsize) / sizeof (daddr32_t))
158 
159 /*
160  * Each file system has a number of inodes statically allocated.
161  * We allocate one inode slot per NBPI bytes, expecting this
162  * to be far more than we will ever need.
163  */
164 #define	NBPI		2048	/* Number Bytes Per Inode */
165 #define	MTB_NBPI	(MB)	/* Number Bytes Per Inode for multi-terabyte */
166 
167 /*
168  * Disks are assumed to rotate at 60HZ, unless otherwise specified.
169  */
170 #define	DEFHZ		60
171 
172 /*
173  * Cylinder group related limits.
174  *
175  * For each cylinder we keep track of the availability of blocks at different
176  * rotational positions, so that we can lay out the data to be picked
177  * up with minimum rotational latency.  NRPOS is the number of rotational
178  * positions which we distinguish.  With NRPOS 8 the resolution of our
179  * summary information is 2ms for a typical 3600 rpm drive.
180  */
181 #define	NRPOS		8	/* number distinct rotational positions */
182 
183 #ifdef DEBUG
184 #define	dprintf(x)	printf x
185 #else
186 #define	dprintf(x)
187 #endif
188 
189 /*
190  * For the -N option, when calculating the backup superblocks, do not print
191  * them if we are not really sure. We may have to try an alternate method of
192  * arriving at the superblocks. So defer printing till a handful of superblocks
193  * look good.
194  */
195 #define	tprintf(x)	if (Nflag && retry) \
196 				(void) strncat(tmpbuf, x, strlen(x)); \
197 			else \
198 				(void) fprintf(stderr, x);
199 
200 #define	ALTSB		32	/* Location of first backup superblock */
201 
202 /*
203  * range_check "user_supplied" flag values.
204  */
205 #define	RC_DEFAULT	0
206 #define	RC_KEYWORD	1
207 #define	RC_POSITIONAL	2
208 
209 /*
210  * ufs hole
211  */
212 #define	UFS_HOLE	-1
213 
214 #ifndef	STANDALONE
215 #include	<stdio.h>
216 #include	<sys/mnttab.h>
217 #endif
218 
219 #include	<stdlib.h>
220 #include	<unistd.h>
221 #include	<malloc.h>
222 #include	<string.h>
223 #include	<strings.h>
224 #include	<ctype.h>
225 #include	<errno.h>
226 #include	<sys/param.h>
227 #include	<time.h>
228 #include	<sys/types.h>
229 #include	<sys/sysmacros.h>
230 #include	<sys/vnode.h>
231 #include	<sys/fs/ufs_fsdir.h>
232 #include	<sys/fs/ufs_inode.h>
233 #include	<sys/fs/ufs_fs.h>
234 #include	<sys/fs/ufs_log.h>
235 #include	<sys/mntent.h>
236 #include	<sys/filio.h>
237 #include	<limits.h>
238 #include	<sys/int_const.h>
239 #include	<signal.h>
240 #include	<sys/efi_partition.h>
241 #include	"roll_log.h"
242 
243 #define	bcopy(f, t, n)    (void) memcpy(t, f, n)
244 #define	bzero(s, n)	(void) memset(s, 0, n)
245 #define	bcmp(s, d, n)	memcmp(s, d, n)
246 
247 #define	index(s, r)	strchr(s, r)
248 #define	rindex(s, r)	strrchr(s, r)
249 
250 #include	<sys/stat.h>
251 #include	<sys/statvfs.h>
252 #include	<locale.h>
253 #include	<fcntl.h>
254 #include 	<sys/isa_defs.h>	/* for ENDIAN defines */
255 #include	<sys/vtoc.h>
256 
257 #include	<sys/dkio.h>
258 #include	<sys/asynch.h>
259 
260 extern offset_t	llseek();
261 extern char	*getfullblkname();
262 extern long	lrand48();
263 
264 extern int	optind;
265 extern char	*optarg;
266 
267 
268 /*
269  * The size of a cylinder group is calculated by CGSIZE. The maximum size
270  * is limited by the fact that cylinder groups are at most one block.
271  * Its size is derived from the size of the maps maintained in the
272  * cylinder group and the (struct cg) size.
273  */
274 #define	CGSIZE(fs) \
275 	/* base cg		*/ (sizeof (struct cg) + \
276 	/* blktot size	*/ (fs)->fs_cpg * sizeof (long) + \
277 	/* blks size	*/ (fs)->fs_cpg * (fs)->fs_nrpos * sizeof (short) + \
278 	/* inode map	*/ howmany((fs)->fs_ipg, NBBY) + \
279 	/* block map */ howmany((fs)->fs_cpg * (fs)->fs_spc / NSPF(fs), NBBY))
280 
281 /*
282  * We limit the size of the inode map to be no more than a
283  * third of the cylinder group space, since we must leave at
284  * least an equal amount of space for the block map.
285  *
286  * N.B.: MAXIpG must be a multiple of INOPB(fs).
287  */
288 #define	MAXIpG(fs)	roundup((fs)->fs_bsize * NBBY / 3, INOPB(fs))
289 
290 /*
291  * Same as MAXIpG, but parameterized by the block size (b) and the
292  * cylinder group divisor (d), which is the reciprocal of the fraction of the
293  * cylinder group overhead block that is used for the inode map.  So for
294  * example, if d = 5, the macro's computation assumes that 1/5 of the
295  * cylinder group overhead block can be dedicated to the inode map.
296  */
297 #define	MAXIpG_B(b, d)	roundup((b) * NBBY / (d), (b) / sizeof (struct dinode))
298 
299 #define	UMASK		0755
300 #define	MAXINOPB	(MAXBSIZE / sizeof (struct dinode))
301 #define	POWEROF2(num)	(((num) & ((num) - 1)) == 0)
302 #define	MB		(1024*1024)
303 #define	BETWEEN(x, l, h)	((x) >= (l) && (x) <= (h))
304 
305 /*
306  * Used to set the inode generation number. Since both inodes and dinodes
307  * are dealt with, we really need a pointer to an icommon here.
308  */
309 #define	IRANDOMIZE(icp)	(icp)->ic_gen = lrand48();
310 
311 /*
312  * Flags for number()
313  */
314 #define	ALLOW_PERCENT	0x01	/* allow trailing `%' on number */
315 #define	ALLOW_MS1	0x02	/* allow trailing `ms', state 1 */
316 #define	ALLOW_MS2	0x04	/* allow trailing `ms', state 2 */
317 #define	ALLOW_END_ONLY	0x08	/* must be at end of number & suffixes */
318 
319 #define	MAXAIO	1000	/* maximum number of outstanding I/O's we'll manage */
320 #define	BLOCK	1	/* block in aiowait */
321 #define	NOBLOCK	0	/* don't block in aiowait */
322 
323 #define	RELEASE 1	/* free an aio buffer after use */
324 #define	SAVE	0	/* don't free the buffer */
325 
326 typedef struct aio_trans {
327 	aio_result_t resultbuf;
328 	diskaddr_t bno;
329 	char *buffer;
330 	int size;
331 	int release;
332 	struct aio_trans *next;
333 } aio_trans;
334 
335 typedef struct aio_results {
336 	int max;
337 	int outstanding;
338 	int maxpend;
339 	aio_trans *trans;
340 } aio_results;
341 
342 int aio_inited = 0;
343 aio_results results;
344 
345 /*
346  * Allow up to MAXBUF aio requests that each have a unique buffer.
347  * More aio's might be done, but not using memory through the getbuf()
348  * interface.  This can be raised, but you run into the potential of
349  * using more memory than is physically available on the machine,
350  * and if you start swapping, you can forget about performance.
351  * To prevent this, we also limit the total memory used for a given
352  * type of buffer to MAXBUFMEM.
353  *
354  * Tests indicate a cylinder group's worth of inodes takes:
355  *
356  *	NBPI	Size of Inode Buffer
357  *	 2k	1688k
358  *	 8k	 424k
359  *
360  * initcg() stores all the inodes for a cylinder group in one buffer,
361  * so allowing 20 buffers could take 32 MB if not limited by MAXBUFMEM.
362  */
363 #define	MAXBUF		20
364 #define	MAXBUFMEM	(8 * 1024 * 1024)
365 
366 /*
367  * header information for buffers managed by getbuf() and freebuf()
368  */
369 typedef struct bufhdr {
370 	struct bufhdr *head;
371 	struct bufhdr *next;
372 } bufhdr;
373 
374 int bufhdrsize;
375 
376 bufhdr inodebuf = { NULL, NULL };
377 bufhdr cgsumbuf = { NULL, NULL };
378 
379 #define	SECTORS_PER_TERABYTE	(1LL << 31)
380 /*
381  * The following constant specifies an upper limit for file system size
382  * that is actually a lot bigger than we expect to support with UFS. (Since
383  * it's specified in sectors, the file system size would be 2**44 * 512,
384  * which is 2**53, which is 8192 Terabytes.)  However, it's useful
385  * for checking the basic sanity of a size value that is input on the
386  * command line.
387  */
388 #define	FS_SIZE_UPPER_LIMIT	0x100000000000LL
389 
390 /*
391  * Forward declarations
392  */
393 static char *getbuf(bufhdr *bufhead, int size);
394 static void freebuf(char *buf);
395 static void freetrans(aio_trans *transp);
396 static aio_trans *get_aiop();
397 static aio_trans *wait_for_write(int block);
398 static void initcg(int cylno);
399 static void fsinit();
400 static int makedir(struct direct *protodir, int entries);
401 static void iput(struct inode *ip);
402 static void rdfs(diskaddr_t bno, int size, char *bf);
403 static void wtfs(diskaddr_t bno, int size, char *bf);
404 static void awtfs(diskaddr_t bno, int size, char *bf, int release);
405 static void wtfs_breakup(diskaddr_t bno, int size, char *bf);
406 static int isblock(struct fs *fs, unsigned char *cp, int h);
407 static void clrblock(struct fs *fs, unsigned char *cp, int h);
408 static void setblock(struct fs *fs, unsigned char *cp, int h);
409 static void usage();
410 static void dump_fscmd(char *fsys, int fsi);
411 static uint64_t number(uint64_t d_value, char *param, int flags);
412 static int match(char *s);
413 static char checkopt(char *optim);
414 static char checkmtb(char *mtbarg);
415 static void range_check(long *varp, char *name, long minimum,
416     long maximum, long def_val, int user_supplied);
417 static void range_check_64(uint64_t *varp, char *name, uint64_t minimum,
418     uint64_t maximum, uint64_t def_val, int user_supplied);
419 static daddr32_t alloc(int size, int mode);
420 static diskaddr_t get_max_size(int fd);
421 static long get_max_track_size(int fd);
422 static void block_sigint(sigset_t *old_mask);
423 static void unblock_sigint(sigset_t *old_mask);
424 static void recover_from_sigint(int signum);
425 static int confirm_abort(void);
426 static int getline(FILE *fp, char *loc, int maxlen);
427 static void flush_writes(void);
428 static long compute_maxcpg(long, long, long, long, long);
429 static int in_64bit_mode(void);
430 static int validate_size(int fd, diskaddr_t size);
431 static void dump_sblock(void);
432 
433 /*
434  * Workaround for mkfs to function properly on disks attached to XMIT 2.X
435  * controller. If the address is not aligned at 8 byte boundary, mkfs on
436  * disks attached to XMIT 2.X controller exhibts un-predictable behaviour.
437  */
438 #define	XMIT_2_X_ALIGN	8
439 #pragma	align XMIT_2_X_ALIGN(fsun, altfsun, cgun)
440 
441 union {
442 	struct fs fs;
443 	char pad[SBSIZE];
444 } fsun, altfsun;
445 #define	sblock	fsun.fs
446 #define	altsblock	altfsun.fs
447 
448 struct	csum *fscs;
449 
450 union cgun {
451 	struct cg cg;
452 	char pad[MAXBSIZE];
453 } cgun;
454 
455 #define	acg	cgun.cg
456 /*
457  * Size of screen in cols in which to fit output
458  */
459 #define	WIDTH	80
460 
461 struct dinode zino[MAXBSIZE / sizeof (struct dinode)];
462 
463 /*
464  * file descriptors used for rdfs(fsi) and wtfs(fso).
465  * Initialized to an illegal file descriptor number.
466  */
467 int	fsi = -1;
468 int	fso = -1;
469 
470 /*
471  * The BIG parameter is machine dependent.  It should be a longlong integer
472  * constant that can be used by the number parser to check the validity
473  * of numeric parameters.
474  */
475 
476 #define	BIG		0x7fffffffffffffffLL
477 
478 /* Used to indicate to number() that a bogus value should cause us to exit */
479 #define	NO_DEFAULT	LONG_MIN
480 
481 /*
482  * INVALIDSBLIMIT is the number of bad backup superblocks that will be
483  * tolerated before we decide to try arriving at a different set of them
484  * using a different logic. This is applicable for non-EFI disks only.
485  */
486 #define	INVALIDSBLIMIT	10
487 
488 /*
489  * The *_flag variables are used to indicate that the user specified
490  * the values, rather than that we made them up ourselves.  We can
491  * complain about the user giving us bogus values.
492  */
493 
494 /* semi-constants */
495 long	sectorsize = DEV_BSIZE;		/* bytes/sector from param.h */
496 long	bbsize = BBSIZE;		/* boot block size */
497 long	sbsize = SBSIZE;		/* superblock size */
498 
499 /* parameters */
500 diskaddr_t	fssize_db;		/* file system size in disk blocks */
501 diskaddr_t	fssize_frag;		/* file system size in frags */
502 long	cpg;				/* cylinders/cylinder group */
503 int	cpg_flag = RC_DEFAULT;
504 long	rotdelay = -1;			/* rotational delay between blocks */
505 int	rotdelay_flag = RC_DEFAULT;
506 long	maxcontig;			/* max contiguous blocks to allocate */
507 int	maxcontig_flag = RC_DEFAULT;
508 long	nsect = DFLNSECT;		/* sectors per track */
509 int	nsect_flag = RC_DEFAULT;
510 long	ntrack = DFLNTRAK;		/* tracks per cylinder group */
511 int	ntrack_flag = RC_DEFAULT;
512 long	bsize = DESBLKSIZE;		/* filesystem block size */
513 int	bsize_flag = RC_DEFAULT;
514 long	fragsize = DESFRAGSIZE; 	/* filesystem fragment size */
515 int	fragsize_flag = RC_DEFAULT;
516 long	minfree = MINFREE; 		/* fs_minfree */
517 int	minfree_flag = RC_DEFAULT;
518 long	rps = DEFHZ;			/* revolutions/second of drive */
519 int	rps_flag = RC_DEFAULT;
520 long	nbpi = NBPI;			/* number of bytes per inode */
521 int	nbpi_flag = RC_DEFAULT;
522 long	nrpos = NRPOS;			/* number of rotational positions */
523 int	nrpos_flag = RC_DEFAULT;
524 long	apc = 0;			/* alternate sectors per cylinder */
525 int	apc_flag = RC_DEFAULT;
526 char	opt = 't';			/* optimization style, `t' or `s' */
527 char	mtb = 'n';			/* multi-terabyte format, 'y' or 'n' */
528 #define	DEFAULT_SECT_TRAK_CPG	(nsect_flag == RC_DEFAULT && \
529 				ntrack_flag == RC_DEFAULT && \
530 				cpg_flag == RC_DEFAULT)
531 
532 long	debug = 0;			/* enable debugging output */
533 
534 int	spc_flag = 0;			/* alternate sectors specified or */
535 					/* found */
536 
537 /* global state */
538 int	Nflag;		/* do not write to disk */
539 int	mflag;		/* return the command line used to create this FS */
540 int	rflag;		/* report the superblock in an easily-parsed form */
541 int	Rflag;		/* dump the superblock in binary */
542 char	*fsys;
543 time_t	mkfstime;
544 char	*string;
545 int	label_type;
546 
547 /*
548  * logging support
549  */
550 int	ismdd;			/* true if device is a SVM device */
551 int	islog;			/* true if ufs or SVM logging is enabled */
552 int	islogok;		/* true if ufs/SVM log state is good */
553 
554 static int	isufslog;	/* true if ufs logging is enabled */
555 static int	waslog;		/* true when ufs logging disabled during grow */
556 
557 /*
558  * growfs defines, globals, and forward references
559  */
560 #define	NOTENOUGHSPACE 33
561 int		grow;
562 #define	GROW_WITH_DEFAULT_TRAK	(grow && ntrack_flag == RC_DEFAULT)
563 
564 static int	Pflag;		/* probe to which size the fs can be grown */
565 int		ismounted;
566 char		*directory;
567 diskaddr_t	grow_fssize;
568 long		grow_fs_size;
569 long		grow_fs_ncg;
570 diskaddr_t		grow_fs_csaddr;
571 long		grow_fs_cssize;
572 int		grow_fs_clean;
573 struct csum	*grow_fscs;
574 diskaddr_t		grow_sifrag;
575 int		test;
576 int		testforce;
577 diskaddr_t		testfrags;
578 int		inlockexit;
579 int		isbad;
580 
581 void		lockexit(int);
582 void		randomgeneration(void);
583 void		checksummarysize(void);
584 int		checksblock(struct fs, int);
585 void		growinit(char *);
586 void		checkdev(char *, char  *);
587 void		checkmount(struct mnttab *, char *);
588 struct dinode	*gdinode(ino_t);
589 int		csfraginrange(daddr32_t);
590 struct csfrag	*findcsfrag(daddr32_t, struct csfrag **);
591 void		checkindirect(ino_t, daddr32_t *, daddr32_t, int);
592 void		addcsfrag(ino_t, daddr32_t, struct csfrag **);
593 void		delcsfrag(daddr32_t, struct csfrag **);
594 void		checkdirect(ino_t, daddr32_t *, daddr32_t *, int);
595 void		findcsfragino(void);
596 void		fixindirect(daddr32_t, int);
597 void		fixdirect(caddr_t, daddr32_t, daddr32_t *, int);
598 void		fixcsfragino(void);
599 void		extendsummaryinfo(void);
600 int		notenoughspace(void);
601 void		unalloccsfragino(void);
602 void		unalloccsfragfree(void);
603 void		findcsfragfree(void);
604 void		copycsfragino(void);
605 void		rdcg(long);
606 void		wtcg(void);
607 void		flcg(void);
608 void		allocfrags(long, daddr32_t *, long *);
609 void		alloccsfragino(void);
610 void		alloccsfragfree(void);
611 void		freefrags(daddr32_t, long, long);
612 int		findfreerange(long *, long *);
613 void		resetallocinfo(void);
614 void		extendcg(long);
615 void		ulockfs(void);
616 void		wlockfs(void);
617 void		clockfs(void);
618 void		wtsb(void);
619 static int64_t	checkfragallocated(daddr32_t);
620 static struct csum 	*read_summaryinfo(struct fs *);
621 static diskaddr_t 	probe_summaryinfo();
622 
623 int
624 main(int argc, char *argv[])
625 {
626 	long i, mincpc, mincpg, ibpcl;
627 	long cylno, rpos, blk, j, warn = 0;
628 	long mincpgcnt, maxcpg;
629 	uint64_t used, bpcg, inospercg;
630 	long mapcramped, inodecramped;
631 	long postblsize, rotblsize, totalsbsize;
632 	FILE *mnttab;
633 	struct mnttab mntp;
634 	char *special;
635 	struct statvfs64 fs;
636 	struct dk_geom dkg;
637 	struct dk_cinfo dkcinfo;
638 	char pbuf[sizeof (uint64_t) * 3 + 1];
639 	char *tmpbuf;
640 	int width, plen;
641 	uint64_t num;
642 	int c, saverr;
643 	diskaddr_t max_fssize;
644 	long tmpmaxcontig = -1;
645 	struct sigaction sigact;
646 	uint64_t nbytes64;
647 	int remaining_cg;
648 	int do_dot = 0;
649 	int use_efi_dflts = 0, retry = 0, isremovable = 0;
650 	int invalid_sb_cnt, ret, skip_this_sb, cg_too_small;
651 	int geom_nsect, geom_ntrack, geom_cpg;
652 
653 	(void) setlocale(LC_ALL, "");
654 
655 #if !defined(TEXT_DOMAIN)
656 #define	TEXT_DOMAIN "SYS_TEST"
657 #endif
658 	(void) textdomain(TEXT_DOMAIN);
659 
660 	while ((c = getopt(argc, argv, "F:bmo:VPGM:T:t:")) != EOF) {
661 		switch (c) {
662 
663 		case 'F':
664 			string = optarg;
665 			if (strcmp(string, "ufs") != 0)
666 				usage();
667 			break;
668 
669 		case 'm':	/* return command line used to create this FS */
670 			mflag++;
671 			break;
672 
673 		case 'o':
674 			/*
675 			 * ufs specific options.
676 			 */
677 			string = optarg;
678 			while (*string != '\0') {
679 				if (match("nsect=")) {
680 					nsect = number(DFLNSECT, "nsect", 0);
681 					nsect_flag = RC_KEYWORD;
682 				} else if (match("ntrack=")) {
683 					ntrack = number(DFLNTRAK, "ntrack", 0);
684 					ntrack_flag = RC_KEYWORD;
685 				} else if (match("bsize=")) {
686 					bsize = number(DESBLKSIZE, "bsize", 0);
687 					bsize_flag = RC_KEYWORD;
688 				} else if (match("fragsize=")) {
689 					fragsize = number(DESFRAGSIZE,
690 					    "fragsize", 0);
691 					fragsize_flag = RC_KEYWORD;
692 				} else if (match("cgsize=")) {
693 					cpg = number(DESCPG, "cgsize", 0);
694 					cpg_flag = RC_KEYWORD;
695 				} else if (match("free=")) {
696 					minfree = number(MINFREE, "free",
697 					    ALLOW_PERCENT);
698 					minfree_flag = RC_KEYWORD;
699 				} else if (match("maxcontig=")) {
700 					tmpmaxcontig =
701 					    number(-1, "maxcontig", 0);
702 					maxcontig_flag = RC_KEYWORD;
703 				} else if (match("nrpos=")) {
704 					nrpos = number(NRPOS, "nrpos", 0);
705 					nrpos_flag = RC_KEYWORD;
706 				} else if (match("rps=")) {
707 					rps = number(DEFHZ, "rps", 0);
708 					rps_flag = RC_KEYWORD;
709 				} else if (match("nbpi=")) {
710 					nbpi = number(NBPI, "nbpi", 0);
711 					nbpi_flag = RC_KEYWORD;
712 				} else if (match("opt=")) {
713 					opt = checkopt(string);
714 				} else if (match("mtb=")) {
715 					mtb = checkmtb(string);
716 				} else if (match("apc=")) {
717 					apc = number(0, "apc", 0);
718 					apc_flag = RC_KEYWORD;
719 				} else if (match("gap=")) {
720 					(void) number(0, "gap", ALLOW_MS1);
721 					rotdelay = ROTDELAY;
722 					rotdelay_flag = RC_DEFAULT;
723 				} else if (match("debug=")) {
724 					debug = number(0, "debug", 0);
725 				} else if (match("N")) {
726 					Nflag++;
727 				} else if (match("calcsb")) {
728 					rflag++;
729 					Nflag++;
730 				} else if (match("calcbinsb")) {
731 					rflag++;
732 					Rflag++;
733 					Nflag++;
734 				} else if (*string == '\0') {
735 					break;
736 				} else {
737 					(void) fprintf(stderr, gettext(
738 					    "illegal option: %s\n"), string);
739 					usage();
740 				}
741 
742 				if (*string == ',') string++;
743 				if (*string == ' ') string++;
744 			}
745 			break;
746 
747 		case 'V':
748 			{
749 				char	*opt_text;
750 				int	opt_count;
751 
752 				(void) fprintf(stdout, gettext("mkfs -F ufs "));
753 				for (opt_count = 1; opt_count < argc;
754 				    opt_count++) {
755 					opt_text = argv[opt_count];
756 					if (opt_text)
757 						(void) fprintf(stdout, " %s ",
758 						    opt_text);
759 				}
760 				(void) fprintf(stdout, "\n");
761 			}
762 			break;
763 
764 		case 'b':	/* do nothing for this */
765 			break;
766 
767 		case 'M':	/* grow the mounted file system */
768 			directory = optarg;
769 
770 			/* FALLTHROUGH */
771 		case 'G':	/* grow the file system */
772 			grow = 1;
773 			break;
774 		case 'P':	/* probe the file system growing size 	*/
775 			Pflag = 1;
776 			grow = 1; /* probe mode implies fs growing	*/
777 			break;
778 		case 'T':	/* For testing */
779 			testforce = 1;
780 
781 			/* FALLTHROUGH */
782 		case 't':
783 			test = 1;
784 			string = optarg;
785 			testfrags = number(NO_DEFAULT, "testfrags", 0);
786 			break;
787 
788 		case '?':
789 			usage();
790 			break;
791 		}
792 	}
793 #ifdef MKFS_DEBUG
794 	/*
795 	 * Turning on MKFS_DEBUG causes mkfs to produce a filesystem
796 	 * that can be reproduced by setting the time to 0 and seeding
797 	 * the random number generator to a constant.
798 	 */
799 	mkfstime = 0;	/* reproducible results */
800 #else
801 	(void) time(&mkfstime);
802 #endif
803 
804 	if (optind >= (argc - 1)) {
805 		if (optind > (argc - 1)) {
806 			(void) fprintf(stderr,
807 			    gettext("special not specified\n"));
808 			usage();
809 		} else if (mflag == 0) {
810 			(void) fprintf(stderr,
811 			    gettext("size not specified\n"));
812 			usage();
813 		}
814 	}
815 	argc -= optind;
816 	argv = &argv[optind];
817 
818 	fsys = argv[0];
819 	fsi = open64(fsys, O_RDONLY);
820 	if (fsi < 0) {
821 		(void) fprintf(stderr, gettext("%s: cannot open\n"), fsys);
822 		lockexit(32);
823 	}
824 
825 	if (mflag) {
826 		dump_fscmd(fsys, fsi);
827 		lockexit(0);
828 	}
829 
830 	/*
831 	 * The task of setting all of the configuration parameters for a
832 	 * UFS file system is basically a matter of solving n equations
833 	 * in m variables.  Typically, m is greater than n, so there is
834 	 * usually more than one valid solution.  Since this is usually
835 	 * an under-constrained problem, it's not always obvious what the
836 	 * "best" configuration is.
837 	 *
838 	 * In general, the approach is to
839 	 * 1. Determine the values for the file system parameters
840 	 *    that are externally contrained and therefore not adjustable
841 	 *    by mkfs (such as the device's size and maxtransfer size).
842 	 * 2. Acquire the user's requested setting for all configuration
843 	 *    values that can be set on the command line.
844 	 * 3. Determine the final value of all configuration values, by
845 	 *    the following approach:
846 	 *	- set the file system block size (fs_bsize).  Although
847 	 *	  this could be regarded as an adjustable parameter, in
848 	 *	  fact, it's pretty much a constant.  At this time, it's
849 	 *	  generally set to 8k (with older hardware, it can
850 	 *	  sometimes make sense to set it to 4k, but those
851 	 *	  situations are pretty rare now).
852 	 *	- re-adjust the maximum file system size based on the
853 	 *	  value of the file system block size.  Since the
854 	 *	  frag size can't be any larger than a file system
855 	 *	  block, and the number of frags in the file system
856 	 *	  has to fit into 31 bits, the file system block size
857 	 *	  affects the maximum file system size.
858 	 *	- now that the real maximum file system is known, set the
859 	 *	  actual size of the file system to be created to
860 	 *	  MIN(requested size, maximum file system size).
861 	 *	- now validate, and if necessary, adjust the following
862 	 *	  values:
863 	 *		rotdelay
864 	 *		nsect
865 	 *		maxcontig
866 	 *		apc
867 	 *		frag_size
868 	 *		rps
869 	 *		minfree
870 	 *		nrpos
871 	 *		nrack
872 	 *		nbpi
873 	 *	- calculate maxcpg (the maximum value of the cylinders-per-
874 	 *	  cylinder-group configuration parameters).  There are two
875 	 *	  algorithms for calculating maxcpg:  an old one, which is
876 	 *	  used for file systems of less than 1 terabyte, and a
877 	 *	  new one, implemented in the function compute_maxcpg(),
878 	 *	  which is used for file systems of greater than 1 TB.
879 	 *	  The difference between them is that compute_maxcpg()
880 	 *	  really tries to maximize the cpg value.  The old
881 	 *	  algorithm fails to take advantage of smaller frags and
882 	 *	  lower inode density when determining the maximum cpg,
883 	 *	  and thus comes up with much lower numbers in some
884 	 *	  configurations.  At some point, we might use the
885 	 *	  new algorithm for determining maxcpg for all file
886 	 *	  systems, but at this time, the changes implemented for
887 	 *	  multi-terabyte UFS are NOT being automatically applied
888 	 *	  to UFS file systems of less than a terabyte (in the
889 	 *	  interest of not changing existing UFS policy too much
890 	 *	  until the ramifications of the changes are well-understood
891 	 *	  and have been evaluated for their effects on performance.)
892 	 *	- check the current values of the configuration parameters
893 	 *	  against the various constraints imposed by UFS.  These
894 	 *	  include:
895 	 *		* There must be at least one inode in each
896 	 *		  cylinder group.
897 	 *		* The cylinder group overhead block, which
898 	 *		  contains the inode and frag bigmaps, must fit
899 	 *		  within one file system block.
900 	 *		* The space required for inode maps should
901 	 *		  occupy no more than a third of the cylinder
902 	 *		  group overhead block.
903 	 *		* The rotational position tables have to fit
904 	 *		  within the available space in the super block.
905 	 *	  Adjust the configuration values that can be adjusted
906 	 *	  so that these constraints are satisfied.  The
907 	 *	  configuration values that are adjustable are:
908 	 *		* frag size
909 	 *		* cylinders per group
910 	 *		* inode density (can be increased)
911 	 *		* number of rotational positions (the rotational
912 	 *		  position tables are eliminated altogether if
913 	 *		  there isn't enough room for them.)
914 	 * 4. Set the values for all the dependent configuration
915 	 *    values (those that aren't settable on the command
916 	 *    line and which are completely dependent on the
917 	 *    adjustable parameters).  This include cpc (cycles
918 	 *    per cylinder, spc (sectors-per-cylinder), and many others.
919 	 */
920 
921 	/*
922 	 * Figure out the partition size and initialize the label_type.
923 	 */
924 	max_fssize = get_max_size(fsi);
925 
926 	/*
927 	 * Get and check positional arguments, if any.
928 	 */
929 	switch (argc - 1) {
930 	default:
931 		usage();
932 		/*NOTREACHED*/
933 	case 15:
934 		mtb = checkmtb(argv[15]);
935 		/* FALLTHROUGH */
936 	case 14:
937 		string = argv[14];
938 		tmpmaxcontig = number(-1, "maxcontig", 0);
939 		maxcontig_flag = RC_POSITIONAL;
940 		/* FALLTHROUGH */
941 	case 13:
942 		string = argv[13];
943 		nrpos = number(NRPOS, "nrpos", 0);
944 		nrpos_flag = RC_POSITIONAL;
945 		/* FALLTHROUGH */
946 	case 12:
947 		string = argv[12];
948 		rotdelay = ROTDELAY;
949 		rotdelay_flag = RC_DEFAULT;
950 		/* FALLTHROUGH */
951 	case 11:
952 		string = argv[11];
953 		apc = number(0, "apc", 0);
954 		apc_flag = RC_POSITIONAL;
955 		/* FALLTHROUGH */
956 	case 10:
957 		opt = checkopt(argv[10]);
958 		/* FALLTHROUGH */
959 	case 9:
960 		string = argv[9];
961 		nbpi = number(NBPI, "nbpi", 0);
962 		nbpi_flag = RC_POSITIONAL;
963 		/* FALLTHROUGH */
964 	case 8:
965 		string = argv[8];
966 		rps = number(DEFHZ, "rps", 0);
967 		rps_flag = RC_POSITIONAL;
968 		/* FALLTHROUGH */
969 	case 7:
970 		string = argv[7];
971 		minfree = number(MINFREE, "free", ALLOW_PERCENT);
972 		minfree_flag = RC_POSITIONAL;
973 		/* FALLTHROUGH */
974 	case 6:
975 		string = argv[6];
976 		cpg = number(DESCPG, "cgsize", 0);
977 		cpg_flag = RC_POSITIONAL;
978 		/* FALLTHROUGH */
979 	case 5:
980 		string = argv[5];
981 		fragsize = number(DESFRAGSIZE, "fragsize", 0);
982 		fragsize_flag = RC_POSITIONAL;
983 		/* FALLTHROUGH */
984 	case 4:
985 		string = argv[4];
986 		bsize = number(DESBLKSIZE, "bsize", 0);
987 		bsize_flag = RC_POSITIONAL;
988 		/* FALLTHROUGH */
989 	case 3:
990 		string = argv[3];
991 		ntrack = number(DFLNTRAK, "ntrack", 0);
992 		ntrack_flag = RC_POSITIONAL;
993 		/* FALLTHROUGH */
994 	case 2:
995 		string = argv[2];
996 		nsect = number(DFLNSECT, "nsect", 0);
997 		nsect_flag = RC_POSITIONAL;
998 		/* FALLTHROUGH */
999 	case 1:
1000 		string = argv[1];
1001 		fssize_db = number(max_fssize, "size", 0);
1002 	}
1003 
1004 	/*
1005 	 * Initialize the parameters in the same way as newfs so that
1006 	 * newfs and mkfs would result in the same file system layout
1007 	 * for EFI labelled disks. Do this only in the absence of user
1008 	 * specified values for these parameters.
1009 	 */
1010 	if (label_type == LABEL_TYPE_EFI) {
1011 		if (apc_flag == RC_DEFAULT) apc = 0;
1012 		if (nrpos_flag == RC_DEFAULT) nrpos = 1;
1013 		if (ntrack_flag == RC_DEFAULT) ntrack = DEF_TRACKS_EFI;
1014 		if (rps_flag == RC_DEFAULT) rps = DEFHZ;
1015 		if (nsect_flag == RC_DEFAULT) nsect = DEF_SECTORS_EFI;
1016 	}
1017 
1018 	if ((maxcontig_flag == RC_DEFAULT) || (tmpmaxcontig == -1) ||
1019 	    (maxcontig == -1)) {
1020 		long maxtrax = get_max_track_size(fsi);
1021 		maxcontig = maxtrax / bsize;
1022 
1023 	} else {
1024 		maxcontig = tmpmaxcontig;
1025 	}
1026 	dprintf(("DeBuG maxcontig : %ld\n", maxcontig));
1027 
1028 	if (rotdelay == -1) {	/* default by newfs and mkfs */
1029 		rotdelay = ROTDELAY;
1030 	}
1031 
1032 	if (cpg_flag == RC_DEFAULT) { /* If not explicity set, use default */
1033 		cpg = DESCPG;
1034 	}
1035 	dprintf(("DeBuG cpg : %ld\n", cpg));
1036 
1037 	/*
1038 	 * Now that we have the semi-sane args, either positional, via -o,
1039 	 * or by defaulting, handle inter-dependencies and range checks.
1040 	 */
1041 
1042 	/*
1043 	 * Settle the file system block size first, since it's a fixed
1044 	 * parameter once set and so many other parameters, including
1045 	 * max_fssize, depend on it.
1046 	 */
1047 	range_check(&bsize, "bsize", MINBSIZE, MAXBSIZE, DESBLKSIZE,
1048 	    bsize_flag);
1049 
1050 	if (!POWEROF2(bsize)) {
1051 		(void) fprintf(stderr,
1052 		    gettext("block size must be a power of 2, not %ld\n"),
1053 		    bsize);
1054 		bsize = DESBLKSIZE;
1055 		(void) fprintf(stderr,
1056 		    gettext("mkfs: bsize reset to default %ld\n"),
1057 		    bsize);
1058 	}
1059 
1060 	if (fssize_db > max_fssize && validate_size(fsi, fssize_db)) {
1061 		(void) fprintf(stderr, gettext(
1062 		    "Warning: the requested size of this file system\n"
1063 		    "(%lld sectors) is greater than the size of the\n"
1064 		    "device reported by the driver (%lld sectors).\n"
1065 		    "However, a read of the device at the requested size\n"
1066 		    "does succeed, so the requested size will be used.\n"),
1067 		    fssize_db, max_fssize);
1068 		max_fssize = fssize_db;
1069 	}
1070 	/*
1071 	 * Since the maximum allocatable unit (the frag) must be less than
1072 	 * or equal to bsize, and the number of frags must be less than or
1073 	 * equal to INT_MAX, the total size of the file system (in
1074 	 * bytes) must be less than or equal to bsize * INT_MAX.
1075 	 */
1076 
1077 	if (max_fssize > ((diskaddr_t)bsize/DEV_BSIZE) * INT_MAX)
1078 		max_fssize = ((diskaddr_t)bsize/DEV_BSIZE) * INT_MAX;
1079 
1080 	range_check_64(&fssize_db, "size", 1024LL, max_fssize, max_fssize, 1);
1081 
1082 	if (fssize_db >= SECTORS_PER_TERABYTE) {
1083 		mtb = 'y';
1084 		if (!in_64bit_mode()) {
1085 			(void) fprintf(stderr, gettext(
1086 "mkfs:  Warning: Creating a file system greater than 1 terabyte on a\n"
1087 "       system running a 32-bit kernel.  This file system will not be\n"
1088 "       accessible until the system is rebooted with a 64-bit kernel.\n"));
1089 		}
1090 	}
1091 	dprintf(("DeBuG mtb : %c\n", mtb));
1092 
1093 	/*
1094 	 * With newer and much larger disks, the newfs(1M) and mkfs_ufs(1M)
1095 	 * commands had problems in correctly handling the "native" geometries
1096 	 * for various storage devices.
1097 	 *
1098 	 * To handle the new age disks, mkfs_ufs(1M) will use the EFI style
1099 	 * for non-EFI disks that are larger than the CHS addressing limit
1100 	 * ( > 8GB approx ) and ignore the disk geometry information for
1101 	 * these drives. This is what is currently done for multi-terrabyte
1102 	 * filesystems on EFI disks.
1103 	 *
1104 	 * However if the user asked for a specific layout by supplying values
1105 	 * for even one of the three parameters (nsect, ntrack, cpg), honour
1106 	 * the user supplied parameters.
1107 	 *
1108 	 * Choosing EFI style or native geometry style can make a lot of
1109 	 * difference, because the size of a cylinder group is dependent on
1110 	 * this choice. This in turn means that the position of alternate
1111 	 * superblocks varies depending on the style chosen. It is not
1112 	 * necessary that all disks of size > CHSLIMIT have EFI style layout.
1113 	 * There can be disks which are > CHSLIMIT size, but have native
1114 	 * geometry style layout, thereby warranting the need for alternate
1115 	 * logic in superblock detection.
1116 	 */
1117 	if (mtb != 'y' && (ntrack == -1 || GROW_WITH_DEFAULT_TRAK ||
1118 	    DEFAULT_SECT_TRAK_CPG)) {
1119 		/*
1120 		 * "-1" indicates that we were called from newfs and ntracks
1121 		 * was not specified in newfs command line. Calculate nsect
1122 		 * and ntrack in the same manner as newfs.
1123 		 *
1124 		 * This is required because, the defaults for nsect and ntrack
1125 		 * is hardcoded in mkfs, whereas to generate the alternate
1126 		 * superblock locations for the -N option, there is a need for
1127 		 * the geometry based values that newfs would have arrived at.
1128 		 * Newfs would have arrived at these values as below.
1129 		 */
1130 		if (label_type == LABEL_TYPE_EFI ||
1131 		    label_type == LABEL_TYPE_OTHER) {
1132 			use_efi_dflts = 1;
1133 			retry = 1;
1134 		} else if (ioctl(fsi, DKIOCGGEOM, &dkg)) {
1135 			dprintf(("%s: Unable to read Disk geometry", fsys));
1136 			perror(gettext("Unable to read Disk geometry"));
1137 			lockexit(32);
1138 		} else {
1139 			nsect = dkg.dkg_nsect;
1140 			ntrack = dkg.dkg_nhead;
1141 #ifdef i386	/* Bug 1170182 */
1142 			if (ntrack > 32 && (ntrack % 16) != 0) {
1143 				ntrack -= (ntrack % 16);
1144 			}
1145 #endif
1146 			if (ioctl(fsi, DKIOCREMOVABLE, &isremovable)) {
1147 				dprintf(("DeBuG Unable to determine if %s is"
1148 				    " Removable Media. Proceeding with system"
1149 				    " determined parameters.\n", fsys));
1150 				isremovable = 0;
1151 			}
1152 			if (((dkg.dkg_ncyl * dkg.dkg_nhead * dkg.dkg_nsect)
1153 			    > CHSLIMIT) || isremovable) {
1154 				use_efi_dflts = 1;
1155 				retry = 1;
1156 			}
1157 		}
1158 	}
1159 	dprintf(("DeBuG CHSLIMIT = %d geom = %ld\n", CHSLIMIT,
1160 	    dkg.dkg_ncyl * dkg.dkg_nhead * dkg.dkg_nsect));
1161 	dprintf(("DeBuG label_type = %d isremovable = %d use_efi_dflts = %d\n",
1162 	    label_type, isremovable, use_efi_dflts));
1163 
1164 	/*
1165 	 * For the newfs -N case, even if the disksize is > CHSLIMIT, do not
1166 	 * blindly follow EFI style. If the fs_version indicates a geometry
1167 	 * based layout, try that one first. If it fails we can always try the
1168 	 * other logic.
1169 	 *
1170 	 * If we were called from growfs, we will have a problem if we mix
1171 	 * and match the filesystem creation and growth styles. For example,
1172 	 * if we create using EFI style, we have to also grow using EFI
1173 	 * style. So follow the style indicated by the fs_version.
1174 	 *
1175 	 * Read and verify the primary superblock. If it looks sane, use the
1176 	 * fs_version from the superblock. If the primary superblock does
1177 	 * not look good, read and verify the first alternate superblock at
1178 	 * ALTSB. Use the fs_version to decide whether to use the
1179 	 * EFI style logic or the old geometry based logic to calculate
1180 	 * the alternate superblock locations.
1181 	 */
1182 	if ((Nflag && use_efi_dflts) || (grow)) {
1183 		if (grow && ntrack_flag != RC_DEFAULT)
1184 			goto start_fs_creation;
1185 		rdfs((diskaddr_t)(SBOFF / sectorsize), (int)sbsize,
1186 		    (char *)&altsblock);
1187 		ret = checksblock(altsblock, 1);
1188 
1189 		if (!ret) {
1190 			if (altsblock.fs_magic == MTB_UFS_MAGIC) {
1191 				mtb = 'y';
1192 				goto start_fs_creation;
1193 			}
1194 			use_efi_dflts = (altsblock.fs_version ==
1195 			    UFS_EFISTYLE4NONEFI_VERSION_2) ? 1 : 0;
1196 		} else {
1197 			/*
1198 			 * The primary superblock didn't help in determining
1199 			 * the fs_version. Try the first alternate superblock.
1200 			 */
1201 			dprintf(("DeBuG checksblock() failed - error : %d"
1202 			    " for sb : %d\n", ret, SBOFF/sectorsize));
1203 			rdfs((diskaddr_t)ALTSB, (int)sbsize,
1204 			    (char *)&altsblock);
1205 			ret = checksblock(altsblock, 1);
1206 
1207 			if (!ret) {
1208 				if (altsblock.fs_magic == MTB_UFS_MAGIC) {
1209 					mtb = 'y';
1210 					goto start_fs_creation;
1211 				}
1212 				use_efi_dflts = (altsblock.fs_version ==
1213 				    UFS_EFISTYLE4NONEFI_VERSION_2) ? 1 : 0;
1214 			}
1215 			dprintf(("DeBuG checksblock() returned : %d"
1216 			    " for sb : %d\n", ret, ALTSB));
1217 		}
1218 	}
1219 
1220 	geom_nsect = nsect;
1221 	geom_ntrack = ntrack;
1222 	geom_cpg = cpg;
1223 	dprintf(("DeBuG geom_nsect=%d, geom_ntrack=%d, geom_cpg=%d\n",
1224 	    geom_nsect, geom_ntrack, geom_cpg));
1225 
1226 start_fs_creation:
1227 retry_alternate_logic:
1228 	invalid_sb_cnt = 0;
1229 	cg_too_small = 0;
1230 	if (use_efi_dflts) {
1231 		nsect = DEF_SECTORS_EFI;
1232 		ntrack = DEF_TRACKS_EFI;
1233 		cpg = DESCPG;
1234 		dprintf(("\nDeBuG Using EFI defaults\n"));
1235 	} else {
1236 		nsect = geom_nsect;
1237 		ntrack = geom_ntrack;
1238 		cpg = geom_cpg;
1239 		dprintf(("\nDeBuG Using Geometry\n"));
1240 		/*
1241 		 * 32K based on max block size of 64K, and rotational layout
1242 		 * test of nsect <= (256 * sectors/block).  Current block size
1243 		 * limit is not 64K, but it's growing soon.
1244 		 */
1245 		range_check(&nsect, "nsect", 1, 32768, DFLNSECT, nsect_flag);
1246 		/*
1247 		 * ntrack is the number of tracks per cylinder.
1248 		 * The ntrack value must be between 1 and the total number of
1249 		 * sectors in the file system.
1250 		 */
1251 		range_check(&ntrack, "ntrack", 1,
1252 		    fssize_db > INT_MAX ? INT_MAX : (uint32_t)fssize_db,
1253 		    DFLNTRAK, ntrack_flag);
1254 	}
1255 
1256 	range_check(&apc, "apc", 0, nsect - 1, 0, apc_flag);
1257 
1258 	if (mtb == 'y')
1259 		fragsize = bsize;
1260 
1261 	range_check(&fragsize, "fragsize", sectorsize, bsize,
1262 	    MAX(bsize / MAXFRAG, MIN(DESFRAGSIZE, bsize)), fragsize_flag);
1263 
1264 	if ((bsize / MAXFRAG) > fragsize) {
1265 		(void) fprintf(stderr, gettext(
1266 "fragment size %ld is too small, minimum with block size %ld is %ld\n"),
1267 		    fragsize, bsize, bsize / MAXFRAG);
1268 		(void) fprintf(stderr,
1269 		    gettext("mkfs: fragsize reset to minimum %ld\n"),
1270 		    bsize / MAXFRAG);
1271 		fragsize = bsize / MAXFRAG;
1272 	}
1273 
1274 	if (!POWEROF2(fragsize)) {
1275 		(void) fprintf(stderr,
1276 		    gettext("fragment size must be a power of 2, not %ld\n"),
1277 		    fragsize);
1278 		fragsize = MAX(bsize / MAXFRAG, MIN(DESFRAGSIZE, bsize));
1279 		(void) fprintf(stderr,
1280 		    gettext("mkfs: fragsize reset to %ld\n"),
1281 		    fragsize);
1282 	}
1283 
1284 	/* At this point, bsize must be >= fragsize, so no need to check it */
1285 
1286 	if (bsize < PAGESIZE) {
1287 		(void) fprintf(stderr, gettext(
1288 		    "WARNING: filesystem block size (%ld) is smaller than "
1289 		    "memory page size (%ld).\nResulting filesystem can not be "
1290 		    "mounted on this system.\n\n"),
1291 		    bsize, (long)PAGESIZE);
1292 	}
1293 
1294 	range_check(&rps, "rps", 1, 1000, DEFHZ, rps_flag);
1295 	range_check(&minfree, "free", 0, 99, MINFREE, minfree_flag);
1296 	range_check(&nrpos, "nrpos", 1, nsect, MIN(nsect, NRPOS), nrpos_flag);
1297 
1298 	/*
1299 	 * nbpi is variable, but 2MB seems a reasonable upper limit,
1300 	 * as 4MB tends to cause problems (using otherwise-default
1301 	 * parameters).  The true limit is where we end up with one
1302 	 * inode per cylinder group.  If this file system is being
1303 	 * configured for multi-terabyte access, nbpi must be at least 1MB.
1304 	 */
1305 	if (mtb == 'y' && nbpi < MTB_NBPI) {
1306 		if (nbpi_flag != RC_DEFAULT)
1307 			(void) fprintf(stderr, gettext("mkfs: bad value for "
1308 			    "nbpi: must be at least 1048576 for multi-terabyte,"
1309 			    " nbpi reset to default 1048576\n"));
1310 		nbpi = MTB_NBPI;
1311 	}
1312 
1313 	if (mtb == 'y')
1314 		range_check(&nbpi, "nbpi", MTB_NBPI, 2 * MB, MTB_NBPI,
1315 		    nbpi_flag);
1316 	else
1317 		range_check(&nbpi, "nbpi", DEV_BSIZE, 2 * MB, NBPI, nbpi_flag);
1318 
1319 	/*
1320 	 * maxcpg is another variably-limited parameter.  Calculate
1321 	 * the limit based on what we've got for its dependent
1322 	 * variables.  Effectively, it's how much space is left in the
1323 	 * superblock after all the other bits are accounted for.  We
1324 	 * only fill in sblock fields so we can use MAXIpG.
1325 	 *
1326 	 * If the calculation of maxcpg below (for the mtb == 'n'
1327 	 * case) is changed, update newfs as well.
1328 	 *
1329 	 * For old-style, non-MTB format file systems, use the old
1330 	 * algorithm for calculating the maximum cylinder group size,
1331 	 * even though it limits the cylinder group more than necessary.
1332 	 * Since layout can affect performance, we don't want to change
1333 	 * the default layout for non-MTB file systems at this time.
1334 	 * However, for MTB file systems, use the new maxcpg calculation,
1335 	 * which really maxes out the cylinder group size.
1336 	 */
1337 
1338 	sblock.fs_bsize = bsize;
1339 	sblock.fs_inopb = sblock.fs_bsize / sizeof (struct dinode);
1340 
1341 	if (mtb == 'n') {
1342 		maxcpg = (bsize - sizeof (struct cg) -
1343 		    howmany(MAXIpG(&sblock), NBBY)) /
1344 		    (sizeof (long) + nrpos * sizeof (short) +
1345 		    nsect / (MAXFRAG * NBBY));
1346 	} else {
1347 		maxcpg = compute_maxcpg(bsize, fragsize, nbpi, nrpos,
1348 		    nsect * ntrack);
1349 	}
1350 
1351 	dprintf(("DeBuG cpg : %ld\n", cpg));
1352 	/*
1353 	 * Increase the cpg to maxcpg if either newfs was invoked
1354 	 * with -T option or if mkfs wants to create a mtb file system
1355 	 * and if the user has not specified the cpg.
1356 	 */
1357 	if (cpg == -1 || (mtb == 'y' && cpg_flag == RC_DEFAULT))
1358 		cpg = maxcpg;
1359 	dprintf(("DeBuG cpg : %ld\n", cpg));
1360 
1361 	/*
1362 	 * mincpg is variable in complex ways, so we really can't
1363 	 * do a sane lower-end limit check at this point.
1364 	 */
1365 	range_check(&cpg, "cgsize", 1, maxcpg, MIN(maxcpg, DESCPG), cpg_flag);
1366 
1367 	/*
1368 	 * get the controller info
1369 	 */
1370 	ismdd = 0;
1371 	islog = 0;
1372 	islogok = 0;
1373 	waslog = 0;
1374 
1375 	if (ioctl(fsi, DKIOCINFO, &dkcinfo) == 0)
1376 		/*
1377 		 * if it is an MDD (disksuite) device
1378 		 */
1379 		if (dkcinfo.dki_ctype == DKC_MD) {
1380 			ismdd++;
1381 			/*
1382 			 * check the logging device
1383 			 */
1384 			if (ioctl(fsi, _FIOISLOG, NULL) == 0) {
1385 				islog++;
1386 				if (ioctl(fsi, _FIOISLOGOK, NULL) == 0)
1387 					islogok++;
1388 			}
1389 		}
1390 
1391 	/*
1392 	 * Do not grow the file system, but print on stdout the maximum
1393 	 * size in sectors to which the file system can be increased.
1394 	 * The calculated size is limited by fssize_db.
1395 	 * Note that we don't lock the filesystem and therefore under rare
1396 	 * conditions (the filesystem is mounted, the free block count is
1397 	 * almost zero, and the superuser is still changing it) the calculated
1398 	 * size can be imprecise.
1399 	 */
1400 	if (Pflag) {
1401 		(void) printf("%llu\n", probe_summaryinfo());
1402 		exit(0);
1403 	}
1404 
1405 	/*
1406 	 * If we're growing an existing filesystem, then we're about
1407 	 * to start doing things that can require recovery efforts if
1408 	 * we get interrupted, so make sure we get a chance to do so.
1409 	 */
1410 	if (grow) {
1411 		sigact.sa_handler = recover_from_sigint;
1412 		sigemptyset(&sigact.sa_mask);
1413 		sigact.sa_flags = SA_RESTART;
1414 
1415 		if (sigaction(SIGINT, &sigact, (struct sigaction *)NULL) < 0) {
1416 			perror(gettext("Could not register SIGINT handler"));
1417 			lockexit(3);
1418 		}
1419 	}
1420 
1421 	if (!Nflag) {
1422 		/*
1423 		 * Check if MNTTAB is trustable
1424 		 */
1425 		if (statvfs64(MNTTAB, &fs) < 0) {
1426 			(void) fprintf(stderr, gettext("can't statvfs %s\n"),
1427 			    MNTTAB);
1428 			exit(32);
1429 		}
1430 
1431 		if (strcmp(MNTTYPE_MNTFS, fs.f_basetype) != 0) {
1432 			(void) fprintf(stderr, gettext(
1433 			    "%s file system type is not %s, can't mkfs\n"),
1434 			    MNTTAB, MNTTYPE_MNTFS);
1435 			exit(32);
1436 		}
1437 
1438 		special = getfullblkname(fsys);
1439 		checkdev(fsys, special);
1440 
1441 		/*
1442 		 * If we found the block device name,
1443 		 * then check the mount table.
1444 		 * if mounted, and growing write lock the file system
1445 		 *
1446 		 */
1447 		if ((special != NULL) && (*special != '\0')) {
1448 			if ((mnttab = fopen(MNTTAB, "r")) == NULL) {
1449 				(void) fprintf(stderr, gettext(
1450 				    "can't open %s\n"), MNTTAB);
1451 				exit(32);
1452 			}
1453 			while ((getmntent(mnttab, &mntp)) == NULL) {
1454 				if (grow) {
1455 					checkmount(&mntp, special);
1456 					continue;
1457 				}
1458 				if (strcmp(special, mntp.mnt_special) == 0) {
1459 					(void) fprintf(stderr, gettext(
1460 					    "%s is mounted, can't mkfs\n"),
1461 					    special);
1462 					exit(32);
1463 				}
1464 			}
1465 			(void) fclose(mnttab);
1466 		}
1467 
1468 		if (directory && (ismounted == 0)) {
1469 			(void) fprintf(stderr, gettext("%s is not mounted\n"),
1470 			    special);
1471 			lockexit(32);
1472 		}
1473 
1474 		fso = (grow) ? open64(fsys, O_WRONLY) : creat64(fsys, 0666);
1475 		if (fso < 0) {
1476 			saverr = errno;
1477 			(void) fprintf(stderr,
1478 			    gettext("%s: cannot create: %s\n"),
1479 			    fsys, strerror(saverr));
1480 			lockexit(32);
1481 		}
1482 
1483 	} else {
1484 
1485 		/*
1486 		 * For the -N case, a file descriptor is needed for the llseek()
1487 		 * in wtfs(). See the comment in wtfs() for more information.
1488 		 *
1489 		 * Get a file descriptor that's read-only so that this code
1490 		 * doesn't accidentally write to the file.
1491 		 */
1492 		fso = open64(fsys, O_RDONLY);
1493 		if (fso < 0) {
1494 			saverr = errno;
1495 			(void) fprintf(stderr, gettext("%s: cannot open: %s\n"),
1496 			    fsys, strerror(saverr));
1497 			lockexit(32);
1498 		}
1499 	}
1500 
1501 	/*
1502 	 * seed random # generator (for ic_generation)
1503 	 */
1504 #ifdef MKFS_DEBUG
1505 	srand48(12962);	/* reproducible results */
1506 #else
1507 	srand48((long)(time((time_t *)NULL) + getpid()));
1508 #endif
1509 
1510 	if (grow) {
1511 		growinit(fsys);
1512 		goto grow00;
1513 	}
1514 
1515 	/*
1516 	 * Validate the given file system size.
1517 	 * Verify that its last block can actually be accessed.
1518 	 *
1519 	 * Note: it's ok to use sblock as a buffer because it is immediately
1520 	 * overwritten by the rdfs() of the superblock in the next line.
1521 	 *
1522 	 * ToDo: Because the size checking is done in rdfs()/wtfs(), the
1523 	 * error message for specifying an illegal size is very unfriendly.
1524 	 * In the future, one could replace the rdfs()/wtfs() calls
1525 	 * below with in-line calls to read() or write(). This allows better
1526 	 * error messages to be put in place.
1527 	 */
1528 	rdfs(fssize_db - 1, (int)sectorsize, (char *)&sblock);
1529 
1530 	/*
1531 	 * make the fs unmountable
1532 	 */
1533 	rdfs((diskaddr_t)(SBOFF / sectorsize), (int)sbsize, (char *)&sblock);
1534 	sblock.fs_magic = -1;
1535 	sblock.fs_clean = FSBAD;
1536 	sblock.fs_state = FSOKAY - sblock.fs_time;
1537 	wtfs((diskaddr_t)(SBOFF / sectorsize), (int)sbsize, (char *)&sblock);
1538 	bzero(&sblock, (size_t)sbsize);
1539 
1540 	sblock.fs_nsect = nsect;
1541 	sblock.fs_ntrak = ntrack;
1542 
1543 	/*
1544 	 * Validate specified/determined spc
1545 	 * and calculate minimum cylinders per group.
1546 	 */
1547 
1548 	/*
1549 	 * sectors/cyl = tracks/cyl * sectors/track
1550 	 */
1551 	sblock.fs_spc = sblock.fs_ntrak * sblock.fs_nsect;
1552 
1553 grow00:
1554 	if (apc_flag) {
1555 		sblock.fs_spc -= apc;
1556 	}
1557 	/*
1558 	 * Have to test for this separately from apc_flag, due to
1559 	 * the growfs case....
1560 	 */
1561 	if (sblock.fs_spc != sblock.fs_ntrak * sblock.fs_nsect) {
1562 		spc_flag = 1;
1563 	}
1564 	if (grow)
1565 		goto grow10;
1566 
1567 	sblock.fs_nrpos = nrpos;
1568 	sblock.fs_bsize = bsize;
1569 	sblock.fs_fsize = fragsize;
1570 	sblock.fs_minfree = minfree;
1571 
1572 grow10:
1573 	if (nbpi < sblock.fs_fsize) {
1574 		(void) fprintf(stderr, gettext(
1575 		"warning: wasteful data byte allocation / inode (nbpi):\n"));
1576 		(void) fprintf(stderr, gettext(
1577 		    "%ld smaller than allocatable fragment size of %d\n"),
1578 		    nbpi, sblock.fs_fsize);
1579 	}
1580 	if (grow)
1581 		goto grow20;
1582 
1583 	if (opt == 's')
1584 		sblock.fs_optim = FS_OPTSPACE;
1585 	else
1586 		sblock.fs_optim = FS_OPTTIME;
1587 
1588 	sblock.fs_bmask = ~(sblock.fs_bsize - 1);
1589 	sblock.fs_fmask = ~(sblock.fs_fsize - 1);
1590 	/*
1591 	 * Planning now for future expansion.
1592 	 */
1593 #if defined(_BIG_ENDIAN)
1594 		sblock.fs_qbmask.val[0] = 0;
1595 		sblock.fs_qbmask.val[1] = ~sblock.fs_bmask;
1596 		sblock.fs_qfmask.val[0] = 0;
1597 		sblock.fs_qfmask.val[1] = ~sblock.fs_fmask;
1598 #endif
1599 #if defined(_LITTLE_ENDIAN)
1600 		sblock.fs_qbmask.val[0] = ~sblock.fs_bmask;
1601 		sblock.fs_qbmask.val[1] = 0;
1602 		sblock.fs_qfmask.val[0] = ~sblock.fs_fmask;
1603 		sblock.fs_qfmask.val[1] = 0;
1604 #endif
1605 	for (sblock.fs_bshift = 0, i = sblock.fs_bsize; i > 1; i >>= 1)
1606 		sblock.fs_bshift++;
1607 	for (sblock.fs_fshift = 0, i = sblock.fs_fsize; i > 1; i >>= 1)
1608 		sblock.fs_fshift++;
1609 	sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
1610 	for (sblock.fs_fragshift = 0, i = sblock.fs_frag; i > 1; i >>= 1)
1611 		sblock.fs_fragshift++;
1612 	if (sblock.fs_frag > MAXFRAG) {
1613 		(void) fprintf(stderr, gettext(
1614 	"fragment size %d is too small, minimum with block size %d is %d\n"),
1615 		    sblock.fs_fsize, sblock.fs_bsize,
1616 		    sblock.fs_bsize / MAXFRAG);
1617 		lockexit(32);
1618 	}
1619 	sblock.fs_nindir = sblock.fs_bsize / sizeof (daddr32_t);
1620 	sblock.fs_inopb = sblock.fs_bsize / sizeof (struct dinode);
1621 	sblock.fs_nspf = sblock.fs_fsize / sectorsize;
1622 	for (sblock.fs_fsbtodb = 0, i = NSPF(&sblock); i > 1; i >>= 1)
1623 		sblock.fs_fsbtodb++;
1624 
1625 	/*
1626 	 * Compute the super-block, cylinder group, and inode blocks.
1627 	 * Note that these "blkno" are really fragment addresses.
1628 	 * For example, on an 8K/1K (block/fragment) system, fs_sblkno is 16,
1629 	 * fs_cblkno is 24, and fs_iblkno is 32. This is why CGSIZE is so
1630 	 * important: only 1 FS block is allocated for the cg struct (fragment
1631 	 * numbers 24 through 31).
1632 	 */
1633 	sblock.fs_sblkno =
1634 	    roundup(howmany(bbsize + sbsize, sblock.fs_fsize), sblock.fs_frag);
1635 	sblock.fs_cblkno = (daddr32_t)(sblock.fs_sblkno +
1636 	    roundup(howmany(sbsize, sblock.fs_fsize), sblock.fs_frag));
1637 	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
1638 
1639 	sblock.fs_cgoffset = roundup(
1640 	    howmany(sblock.fs_nsect, NSPF(&sblock)), sblock.fs_frag);
1641 	for (sblock.fs_cgmask = -1, i = sblock.fs_ntrak; i > 1; i >>= 1)
1642 		sblock.fs_cgmask <<= 1;
1643 	if (!POWEROF2(sblock.fs_ntrak))
1644 		sblock.fs_cgmask <<= 1;
1645 	/*
1646 	 * Validate specified/determined spc
1647 	 * and calculate minimum cylinders per group.
1648 	 */
1649 
1650 	for (sblock.fs_cpc = NSPB(&sblock), i = sblock.fs_spc;
1651 	    sblock.fs_cpc > 1 && (i & 1) == 0;
1652 	    sblock.fs_cpc >>= 1, i >>= 1)
1653 		/* void */;
1654 	mincpc = sblock.fs_cpc;
1655 
1656 	/* if these calculations are changed, check dump_fscmd also */
1657 	bpcg = (uint64_t)sblock.fs_spc * sectorsize;
1658 	inospercg = (uint64_t)roundup(bpcg / sizeof (struct dinode),
1659 	    INOPB(&sblock));
1660 	if (inospercg > MAXIpG(&sblock))
1661 		inospercg = MAXIpG(&sblock);
1662 	used = (uint64_t)(sblock.fs_iblkno + inospercg /
1663 	    INOPF(&sblock)) * NSPF(&sblock);
1664 	mincpgcnt = (long)howmany((uint64_t)sblock.fs_cgoffset *
1665 	    (~sblock.fs_cgmask) + used, sblock.fs_spc);
1666 	mincpg = roundup(mincpgcnt, mincpc);
1667 	/*
1668 	 * Insure that cylinder group with mincpg has enough space
1669 	 * for block maps
1670 	 */
1671 	sblock.fs_cpg = mincpg;
1672 	sblock.fs_ipg = (int32_t)inospercg;
1673 	mapcramped = 0;
1674 
1675 	/*
1676 	 * Make sure the cg struct fits within the file system block.
1677 	 * Use larger block sizes until it fits
1678 	 */
1679 	while (CGSIZE(&sblock) > sblock.fs_bsize) {
1680 		mapcramped = 1;
1681 		if (sblock.fs_bsize < MAXBSIZE) {
1682 			sblock.fs_bsize <<= 1;
1683 			if ((i & 1) == 0) {
1684 				i >>= 1;
1685 			} else {
1686 				sblock.fs_cpc <<= 1;
1687 				mincpc <<= 1;
1688 				mincpg = roundup(mincpgcnt, mincpc);
1689 				sblock.fs_cpg = mincpg;
1690 			}
1691 			sblock.fs_frag <<= 1;
1692 			sblock.fs_fragshift += 1;
1693 			if (sblock.fs_frag <= MAXFRAG)
1694 				continue;
1695 		}
1696 
1697 		/*
1698 		 * Looped far enough. The fragment is now as large as the
1699 		 * filesystem block!
1700 		 */
1701 		if (sblock.fs_fsize == sblock.fs_bsize) {
1702 			(void) fprintf(stderr, gettext(
1703 		    "There is no block size that can support this disk\n"));
1704 			lockexit(32);
1705 		}
1706 
1707 		/*
1708 		 * Try a larger fragment. Double the fragment size.
1709 		 */
1710 		sblock.fs_frag >>= 1;
1711 		sblock.fs_fragshift -= 1;
1712 		sblock.fs_fsize <<= 1;
1713 		sblock.fs_nspf <<= 1;
1714 	}
1715 	/*
1716 	 * Insure that cylinder group with mincpg has enough space for inodes
1717 	 */
1718 	inodecramped = 0;
1719 	used *= sectorsize;
1720 	nbytes64 = (uint64_t)mincpg * bpcg - used;
1721 	inospercg = (uint64_t)roundup((nbytes64 / nbpi), INOPB(&sblock));
1722 	sblock.fs_ipg = (int32_t)inospercg;
1723 	while (inospercg > MAXIpG(&sblock)) {
1724 		inodecramped = 1;
1725 		if (mincpc == 1 || sblock.fs_frag == 1 ||
1726 		    sblock.fs_bsize == MINBSIZE)
1727 			break;
1728 		nbytes64 = (uint64_t)mincpg * bpcg - used;
1729 		(void) fprintf(stderr,
1730 		    gettext("With a block size of %d %s %lu\n"),
1731 		    sblock.fs_bsize, gettext("minimum bytes per inode is"),
1732 		    (uint32_t)(nbytes64 / MAXIpG(&sblock) + 1));
1733 		sblock.fs_bsize >>= 1;
1734 		sblock.fs_frag >>= 1;
1735 		sblock.fs_fragshift -= 1;
1736 		mincpc >>= 1;
1737 		sblock.fs_cpg = roundup(mincpgcnt, mincpc);
1738 		if (CGSIZE(&sblock) > sblock.fs_bsize) {
1739 			sblock.fs_bsize <<= 1;
1740 			break;
1741 		}
1742 		mincpg = sblock.fs_cpg;
1743 		nbytes64 = (uint64_t)mincpg * bpcg - used;
1744 		inospercg = (uint64_t)roundup((nbytes64 / nbpi),
1745 		    INOPB(&sblock));
1746 		sblock.fs_ipg = (int32_t)inospercg;
1747 	}
1748 	if (inodecramped) {
1749 		if (inospercg > MAXIpG(&sblock)) {
1750 			nbytes64 = (uint64_t)mincpg * bpcg - used;
1751 			(void) fprintf(stderr, gettext(
1752 			    "Minimum bytes per inode is %d\n"),
1753 			    (uint32_t)(nbytes64 / MAXIpG(&sblock) + 1));
1754 		} else if (!mapcramped) {
1755 			(void) fprintf(stderr, gettext(
1756 	    "With %ld bytes per inode, minimum cylinders per group is %ld\n"),
1757 			    nbpi, mincpg);
1758 		}
1759 	}
1760 	if (mapcramped) {
1761 		(void) fprintf(stderr, gettext(
1762 		    "With %d sectors per cylinder, minimum cylinders "
1763 		    "per group is %ld\n"),
1764 		    sblock.fs_spc, mincpg);
1765 	}
1766 	if (inodecramped || mapcramped) {
1767 		/*
1768 		 * To make this at least somewhat comprehensible in
1769 		 * the world of i18n, figure out what we're going to
1770 		 * say and then say it all at one time.  The days of
1771 		 * needing to scrimp on string space are behind us....
1772 		 */
1773 		if ((sblock.fs_bsize != bsize) &&
1774 		    (sblock.fs_fsize != fragsize)) {
1775 			(void) fprintf(stderr, gettext(
1776 	    "This requires the block size to be changed from %ld to %d\n"
1777 	    "and the fragment size to be changed from %ld to %d\n"),
1778 			    bsize, sblock.fs_bsize,
1779 			    fragsize, sblock.fs_fsize);
1780 		} else if (sblock.fs_bsize != bsize) {
1781 			(void) fprintf(stderr, gettext(
1782 	    "This requires the block size to be changed from %ld to %d\n"),
1783 			    bsize, sblock.fs_bsize);
1784 		} else if (sblock.fs_fsize != fragsize) {
1785 			(void) fprintf(stderr, gettext(
1786 	    "This requires the fragment size to be changed from %ld to %d\n"),
1787 			    fragsize, sblock.fs_fsize);
1788 		} else {
1789 			(void) fprintf(stderr, gettext(
1790 	    "Unable to make filesystem fit with the given constraints\n"));
1791 		}
1792 		(void) fprintf(stderr, gettext(
1793 		    "Please re-run mkfs with corrected parameters\n"));
1794 		lockexit(32);
1795 	}
1796 	/*
1797 	 * Calculate the number of cylinders per group
1798 	 */
1799 	sblock.fs_cpg = cpg;
1800 	if (sblock.fs_cpg % mincpc != 0) {
1801 		(void) fprintf(stderr, gettext(
1802 		    "Warning: cylinder groups must have a multiple "
1803 		    "of %ld cylinders with the given\n         parameters\n"),
1804 		    mincpc);
1805 		sblock.fs_cpg = roundup(sblock.fs_cpg, mincpc);
1806 		(void) fprintf(stderr, gettext("Rounded cgsize up to %d\n"),
1807 		    sblock.fs_cpg);
1808 	}
1809 	/*
1810 	 * Must insure there is enough space for inodes
1811 	 */
1812 	/* if these calculations are changed, check dump_fscmd also */
1813 	nbytes64 = (uint64_t)sblock.fs_cpg * bpcg - used;
1814 	sblock.fs_ipg = roundup((uint32_t)(nbytes64 / nbpi), INOPB(&sblock));
1815 
1816 	/*
1817 	 * Slim down cylinders per group, until the inodes can fit.
1818 	 */
1819 	while (sblock.fs_ipg > MAXIpG(&sblock)) {
1820 		inodecramped = 1;
1821 		sblock.fs_cpg -= mincpc;
1822 		nbytes64 = (uint64_t)sblock.fs_cpg * bpcg - used;
1823 		sblock.fs_ipg = roundup((uint32_t)(nbytes64 / nbpi),
1824 		    INOPB(&sblock));
1825 	}
1826 	/*
1827 	 * Must insure there is enough space to hold block map.
1828 	 * Cut down on cylinders per group, until the cg struct fits in a
1829 	 * filesystem block.
1830 	 */
1831 	while (CGSIZE(&sblock) > sblock.fs_bsize) {
1832 		mapcramped = 1;
1833 		sblock.fs_cpg -= mincpc;
1834 		nbytes64 = (uint64_t)sblock.fs_cpg * bpcg - used;
1835 		sblock.fs_ipg = roundup((uint32_t)(nbytes64 / nbpi),
1836 		    INOPB(&sblock));
1837 	}
1838 	sblock.fs_fpg = (sblock.fs_cpg * sblock.fs_spc) / NSPF(&sblock);
1839 	if ((sblock.fs_cpg * sblock.fs_spc) % NSPB(&sblock) != 0) {
1840 		(void) fprintf(stderr,
1841 		gettext("newfs: panic (fs_cpg * fs_spc) %% NSPF != 0\n"));
1842 		lockexit(32);
1843 	}
1844 	if (sblock.fs_cpg < mincpg) {
1845 		(void) fprintf(stderr, gettext(
1846 "With the given parameters, cgsize must be at least %ld; please re-run mkfs\n"),
1847 		    mincpg);
1848 		lockexit(32);
1849 	}
1850 	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
1851 grow20:
1852 	/*
1853 	 * Now have size for file system and nsect and ntrak.
1854 	 * Determine number of cylinders and blocks in the file system.
1855 	 */
1856 	fssize_frag = (int64_t)dbtofsb(&sblock, fssize_db);
1857 	if (fssize_frag > INT_MAX) {
1858 		(void) fprintf(stderr, gettext(
1859 "There are too many fragments in the system, increase fragment size\n"),
1860 		    mincpg);
1861 		lockexit(32);
1862 	}
1863 	sblock.fs_size = (int32_t)fssize_frag;
1864 	sblock.fs_ncyl = (int32_t)(fssize_frag * NSPF(&sblock) / sblock.fs_spc);
1865 	if (fssize_frag * NSPF(&sblock) >
1866 	    (uint64_t)sblock.fs_ncyl * sblock.fs_spc) {
1867 		sblock.fs_ncyl++;
1868 		warn = 1;
1869 	}
1870 	if (sblock.fs_ncyl < 1) {
1871 		(void) fprintf(stderr, gettext(
1872 		    "file systems must have at least one cylinder\n"));
1873 		lockexit(32);
1874 	}
1875 	if (grow)
1876 		goto grow30;
1877 	/*
1878 	 * Determine feasability/values of rotational layout tables.
1879 	 *
1880 	 * The size of the rotational layout tables is limited by the size
1881 	 * of the file system block, fs_bsize.  The amount of space
1882 	 * available for tables is calculated as (fs_bsize - sizeof (struct
1883 	 * fs)).  The size of these tables is inversely proportional to the
1884 	 * block size of the file system. The size increases if sectors per
1885 	 * track are not powers of two, because more cylinders must be
1886 	 * described by the tables before the rotational pattern repeats
1887 	 * (fs_cpc).
1888 	 */
1889 	sblock.fs_postblformat = FS_DYNAMICPOSTBLFMT;
1890 	sblock.fs_sbsize = fragroundup(&sblock, sizeof (struct fs));
1891 	sblock.fs_npsect = sblock.fs_nsect;
1892 	if (sblock.fs_ntrak == 1) {
1893 		sblock.fs_cpc = 0;
1894 		goto next;
1895 	}
1896 	postblsize = sblock.fs_nrpos * sblock.fs_cpc * sizeof (short);
1897 	rotblsize = sblock.fs_cpc * sblock.fs_spc / NSPB(&sblock);
1898 	totalsbsize = sizeof (struct fs) + rotblsize;
1899 
1900 	/* do static allocation if nrpos == 8 and fs_cpc == 16  */
1901 	if (sblock.fs_nrpos == 8 && sblock.fs_cpc <= 16) {
1902 		/* use old static table space */
1903 		sblock.fs_postbloff = (char *)(&sblock.fs_opostbl[0][0]) -
1904 		    (char *)(&sblock.fs_link);
1905 		sblock.fs_rotbloff = &sblock.fs_space[0] -
1906 		    (uchar_t *)(&sblock.fs_link);
1907 	} else {
1908 		/* use 4.3 dynamic table space */
1909 		sblock.fs_postbloff = &sblock.fs_space[0] -
1910 		    (uchar_t *)(&sblock.fs_link);
1911 		sblock.fs_rotbloff = sblock.fs_postbloff + postblsize;
1912 		totalsbsize += postblsize;
1913 	}
1914 	if (totalsbsize > sblock.fs_bsize ||
1915 	    sblock.fs_nsect > (1 << NBBY) * NSPB(&sblock)) {
1916 		(void) fprintf(stderr, gettext(
1917 		    "Warning: insufficient space in super block for\n"
1918 		    "rotational layout tables with nsect %d, ntrack %d, "
1919 		    "and nrpos %d.\nOmitting tables - file system "
1920 		    "performance may be impaired.\n"),
1921 		    sblock.fs_nsect, sblock.fs_ntrak, sblock.fs_nrpos);
1922 
1923 		/*
1924 		 * Setting fs_cpc to 0 tells alloccgblk() in ufs_alloc.c to
1925 		 * ignore the positional layout table and rotational
1926 		 * position table.
1927 		 */
1928 		sblock.fs_cpc = 0;
1929 		goto next;
1930 	}
1931 	sblock.fs_sbsize = fragroundup(&sblock, totalsbsize);
1932 
1933 
1934 	/*
1935 	 * calculate the available blocks for each rotational position
1936 	 */
1937 	for (cylno = 0; cylno < sblock.fs_cpc; cylno++)
1938 		for (rpos = 0; rpos < sblock.fs_nrpos; rpos++)
1939 			fs_postbl(&sblock, cylno)[rpos] = -1;
1940 	for (i = (rotblsize - 1) * sblock.fs_frag;
1941 	    i >= 0; i -= sblock.fs_frag) {
1942 		cylno = cbtocylno(&sblock, i);
1943 		rpos = cbtorpos(&sblock, i);
1944 		blk = fragstoblks(&sblock, i);
1945 		if (fs_postbl(&sblock, cylno)[rpos] == -1)
1946 			fs_rotbl(&sblock)[blk] = 0;
1947 		else
1948 			fs_rotbl(&sblock)[blk] =
1949 			    fs_postbl(&sblock, cylno)[rpos] - blk;
1950 		fs_postbl(&sblock, cylno)[rpos] = blk;
1951 	}
1952 next:
1953 grow30:
1954 	/*
1955 	 * Compute/validate number of cylinder groups.
1956 	 * Note that if an excessively large filesystem is specified
1957 	 * (e.g., more than 16384 cylinders for an 8K filesystem block), it
1958 	 * does not get detected until checksummarysize()
1959 	 */
1960 	sblock.fs_ncg = sblock.fs_ncyl / sblock.fs_cpg;
1961 	if (sblock.fs_ncyl % sblock.fs_cpg)
1962 		sblock.fs_ncg++;
1963 	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
1964 	i = MIN(~sblock.fs_cgmask, sblock.fs_ncg - 1);
1965 	ibpcl = cgdmin(&sblock, i) - cgbase(&sblock, i);
1966 	if (ibpcl >= sblock.fs_fpg) {
1967 		(void) fprintf(stderr, gettext(
1968 		    "inode blocks/cyl group (%d) >= data blocks (%d)\n"),
1969 		    cgdmin(&sblock, i) - cgbase(&sblock, i) / sblock.fs_frag,
1970 		    sblock.fs_fpg / sblock.fs_frag);
1971 		if ((ibpcl < 0) || (sblock.fs_fpg < 0)) {
1972 			(void) fprintf(stderr, gettext(
1973 	    "number of cylinders per cylinder group (%d) must be decreased.\n"),
1974 			    sblock.fs_cpg);
1975 		} else {
1976 			(void) fprintf(stderr, gettext(
1977 	    "number of cylinders per cylinder group (%d) must be increased.\n"),
1978 			    sblock.fs_cpg);
1979 		}
1980 		(void) fprintf(stderr, gettext(
1981 "Note that cgsize may have been adjusted to allow struct cg to fit.\n"));
1982 		lockexit(32);
1983 	}
1984 	j = sblock.fs_ncg - 1;
1985 	if ((i = fssize_frag - j * sblock.fs_fpg) < sblock.fs_fpg &&
1986 	    cgdmin(&sblock, j) - cgbase(&sblock, j) > i) {
1987 		(void) fprintf(stderr, gettext(
1988 		    "Warning: inode blocks/cyl group (%d) >= data "
1989 		    "blocks (%ld) in last\n    cylinder group. This "
1990 		    "implies %ld sector(s) cannot be allocated.\n"),
1991 		    (cgdmin(&sblock, j) - cgbase(&sblock, j)) / sblock.fs_frag,
1992 		    i / sblock.fs_frag, i * NSPF(&sblock));
1993 		/*
1994 		 * If there is only one cylinder group and that is not even
1995 		 * big enough to hold the inodes, exit.
1996 		 */
1997 		if (sblock.fs_ncg == 1)
1998 			cg_too_small = 1;
1999 		sblock.fs_ncg--;
2000 		sblock.fs_ncyl -= sblock.fs_ncyl % sblock.fs_cpg;
2001 		sblock.fs_size = fssize_frag =
2002 		    (int64_t)sblock.fs_ncyl * (int64_t)sblock.fs_spc /
2003 		    (int64_t)NSPF(&sblock);
2004 		warn = 0;
2005 	}
2006 	if (warn && !spc_flag) {
2007 		(void) fprintf(stderr, gettext(
2008 		    "Warning: %d sector(s) in last cylinder unallocated\n"),
2009 		    sblock.fs_spc - (uint32_t)(fssize_frag * NSPF(&sblock) -
2010 		    (uint64_t)(sblock.fs_ncyl - 1) * sblock.fs_spc));
2011 	}
2012 	/*
2013 	 * fill in remaining fields of the super block
2014 	 */
2015 
2016 	/*
2017 	 * The csum records are stored in cylinder group 0, starting at
2018 	 * cgdmin, the first data block.
2019 	 */
2020 	sblock.fs_csaddr = cgdmin(&sblock, 0);
2021 	sblock.fs_cssize =
2022 	    fragroundup(&sblock, sblock.fs_ncg * sizeof (struct csum));
2023 	i = sblock.fs_bsize / sizeof (struct csum);
2024 	sblock.fs_csmask = ~(i - 1);
2025 	for (sblock.fs_csshift = 0; i > 1; i >>= 1)
2026 		sblock.fs_csshift++;
2027 	fscs = (struct csum *)calloc(1, sblock.fs_cssize);
2028 
2029 	checksummarysize();
2030 	if (mtb == 'y') {
2031 		sblock.fs_magic = MTB_UFS_MAGIC;
2032 		sblock.fs_version = MTB_UFS_VERSION_1;
2033 	} else {
2034 		sblock.fs_magic = FS_MAGIC;
2035 		if (use_efi_dflts)
2036 			sblock.fs_version = UFS_EFISTYLE4NONEFI_VERSION_2;
2037 		else
2038 			sblock.fs_version = UFS_VERSION_MIN;
2039 	}
2040 
2041 	if (grow) {
2042 		bcopy((caddr_t)grow_fscs, (caddr_t)fscs, (int)grow_fs_cssize);
2043 		extendsummaryinfo();
2044 		goto grow40;
2045 	}
2046 	sblock.fs_rotdelay = rotdelay;
2047 	sblock.fs_maxcontig = maxcontig;
2048 	sblock.fs_maxbpg = MAXBLKPG(sblock.fs_bsize);
2049 
2050 	sblock.fs_rps = rps;
2051 	sblock.fs_cgrotor = 0;
2052 	sblock.fs_cstotal.cs_ndir = 0;
2053 	sblock.fs_cstotal.cs_nbfree = 0;
2054 	sblock.fs_cstotal.cs_nifree = 0;
2055 	sblock.fs_cstotal.cs_nffree = 0;
2056 	sblock.fs_fmod = 0;
2057 	sblock.fs_ronly = 0;
2058 	sblock.fs_time = mkfstime;
2059 	sblock.fs_state = FSOKAY - sblock.fs_time;
2060 	sblock.fs_clean = FSCLEAN;
2061 grow40:
2062 
2063 	/*
2064 	 * If all that's needed is a dump of the superblock we
2065 	 * would use by default, we've got it now.  So, splat it
2066 	 * out and leave.
2067 	 */
2068 	if (rflag) {
2069 		dump_sblock();
2070 		lockexit(0);
2071 	}
2072 	/*
2073 	 * Dump out summary information about file system.
2074 	 */
2075 	(void) fprintf(stderr, gettext(
2076 	    "%s:\t%lld sectors in %d cylinders of %d tracks, %d sectors\n"),
2077 	    fsys, (uint64_t)sblock.fs_size * NSPF(&sblock), sblock.fs_ncyl,
2078 	    sblock.fs_ntrak, sblock.fs_nsect);
2079 	(void) fprintf(stderr, gettext(
2080 	    "\t%.1fMB in %d cyl groups (%d c/g, %.2fMB/g, %d i/g)\n"),
2081 	    (float)sblock.fs_size * sblock.fs_fsize / MB, sblock.fs_ncg,
2082 	    sblock.fs_cpg, (float)sblock.fs_fpg * sblock.fs_fsize / MB,
2083 	    sblock.fs_ipg);
2084 
2085 	tmpbuf = calloc(sblock.fs_ncg / 50 + 500, 1);
2086 	if (tmpbuf == NULL) {
2087 		perror("calloc");
2088 		lockexit(32);
2089 	}
2090 	if (cg_too_small) {
2091 		(void) fprintf(stderr, gettext("File system creation failed. "
2092 		    "There is only one cylinder group and\nthat is "
2093 		    "not even big enough to hold the inodes.\n"));
2094 		lockexit(32);
2095 	}
2096 	/*
2097 	 * Now build the cylinders group blocks and
2098 	 * then print out indices of cylinder groups.
2099 	 */
2100 	tprintf(gettext(
2101 	    "super-block backups (for fsck -F ufs -o b=#) at:\n"));
2102 	for (width = cylno = 0; cylno < sblock.fs_ncg && cylno < 10; cylno++) {
2103 		if ((grow == 0) || (cylno >= grow_fs_ncg))
2104 			initcg(cylno);
2105 		num = fsbtodb(&sblock, (uint64_t)cgsblock(&sblock, cylno));
2106 		/*
2107 		 * If Nflag and if the disk is larger than the CHSLIMIT,
2108 		 * then sanity test the superblocks before reporting. If there
2109 		 * are too many superblocks which look insane, we have
2110 		 * to retry with alternate logic. If both methods have
2111 		 * failed, then our efforts to arrive at alternate
2112 		 * superblocks failed, so complain and exit.
2113 		 */
2114 		if (Nflag && retry) {
2115 			skip_this_sb = 0;
2116 			rdfs((diskaddr_t)num, sbsize, (char *)&altsblock);
2117 			ret = checksblock(altsblock, 1);
2118 			if (ret) {
2119 				skip_this_sb = 1;
2120 				invalid_sb_cnt++;
2121 				dprintf(("DeBuG checksblock() failed - error :"
2122 				    " %d for sb : %llu invalid_sb_cnt : %d\n",
2123 				    ret, num, invalid_sb_cnt));
2124 			} else {
2125 				/*
2126 				 * Though the superblock looks sane, verify if
2127 				 * the fs_version in the superblock and the
2128 				 * logic that we are using to arrive at the
2129 				 * superblocks match.
2130 				 */
2131 				if (use_efi_dflts && altsblock.fs_version
2132 				    != UFS_EFISTYLE4NONEFI_VERSION_2) {
2133 					skip_this_sb = 1;
2134 					invalid_sb_cnt++;
2135 				}
2136 			}
2137 			if (invalid_sb_cnt >= INVALIDSBLIMIT) {
2138 				if (retry > 1) {
2139 					(void) fprintf(stderr, gettext(
2140 					    "Error determining alternate "
2141 					    "superblock locations\n"));
2142 					free(tmpbuf);
2143 					lockexit(32);
2144 				}
2145 				retry++;
2146 				use_efi_dflts = !use_efi_dflts;
2147 				free(tmpbuf);
2148 				goto retry_alternate_logic;
2149 			}
2150 			if (skip_this_sb)
2151 				continue;
2152 		}
2153 		(void) sprintf(pbuf, " %llu,", num);
2154 		plen = strlen(pbuf);
2155 		if ((width + plen) > (WIDTH - 1)) {
2156 			width = plen;
2157 			tprintf("\n");
2158 		} else {
2159 			width += plen;
2160 		}
2161 		if (Nflag && retry)
2162 			(void) strncat(tmpbuf, pbuf, strlen(pbuf));
2163 		else
2164 			(void) fprintf(stderr, "%s", pbuf);
2165 	}
2166 	tprintf("\n");
2167 
2168 	remaining_cg = sblock.fs_ncg - cylno;
2169 
2170 	/*
2171 	 * If there are more than 300 cylinder groups still to be
2172 	 * initialized, print a "." for every 50 cylinder groups.
2173 	 */
2174 	if (remaining_cg > 300) {
2175 		tprintf(gettext("Initializing cylinder groups:\n"));
2176 		do_dot = 1;
2177 	}
2178 
2179 	/*
2180 	 * Now initialize all cylinder groups between the first ten
2181 	 * and the last ten.
2182 	 *
2183 	 * If the number of cylinder groups was less than 10, all of the
2184 	 * cylinder group offsets would have printed in the last loop
2185 	 * and cylno will already be equal to sblock.fs_ncg and so this
2186 	 * loop will not be entered.  If there are less than 20 cylinder
2187 	 * groups, cylno is already less than fs_ncg - 10, so this loop
2188 	 * won't be entered in that case either.
2189 	 */
2190 
2191 	i = 0;
2192 	for (; cylno < sblock.fs_ncg - 10; cylno++) {
2193 		if ((grow == 0) || (cylno >= grow_fs_ncg))
2194 			initcg(cylno);
2195 		if (do_dot && cylno % 50 == 0) {
2196 			tprintf(".");
2197 			i++;
2198 			if (i == WIDTH - 1) {
2199 				tprintf("\n");
2200 				i = 0;
2201 			}
2202 		}
2203 	}
2204 
2205 	/*
2206 	 * Now print the cylinder group offsets for the last 10
2207 	 * cylinder groups, if any are left.
2208 	 */
2209 
2210 	if (do_dot) {
2211 		tprintf(gettext(
2212 	    "\nsuper-block backups for last 10 cylinder groups at:\n"));
2213 	}
2214 	for (width = 0; cylno < sblock.fs_ncg; cylno++) {
2215 		if ((grow == 0) || (cylno >= grow_fs_ncg))
2216 			initcg(cylno);
2217 		num = fsbtodb(&sblock, (uint64_t)cgsblock(&sblock, cylno));
2218 		if (Nflag && retry) {
2219 			skip_this_sb = 0;
2220 			rdfs((diskaddr_t)num, sbsize, (char *)&altsblock);
2221 			ret = checksblock(altsblock, 1);
2222 			if (ret) {
2223 				skip_this_sb = 1;
2224 				invalid_sb_cnt++;
2225 				dprintf(("DeBuG checksblock() failed - error :"
2226 				    " %d for sb : %llu invalid_sb_cnt : %d\n",
2227 				    ret, num, invalid_sb_cnt));
2228 			} else {
2229 				/*
2230 				 * Though the superblock looks sane, verify if
2231 				 * the fs_version in the superblock and the
2232 				 * logic that we are using to arrive at the
2233 				 * superblocks match.
2234 				 */
2235 				if (use_efi_dflts && altsblock.fs_version
2236 				    != UFS_EFISTYLE4NONEFI_VERSION_2) {
2237 					skip_this_sb = 1;
2238 					invalid_sb_cnt++;
2239 				}
2240 			}
2241 			if (invalid_sb_cnt >= INVALIDSBLIMIT) {
2242 				if (retry > 1) {
2243 					(void) fprintf(stderr, gettext(
2244 					    "Error determining alternate "
2245 					    "superblock locations\n"));
2246 					free(tmpbuf);
2247 					lockexit(32);
2248 				}
2249 				retry++;
2250 				use_efi_dflts = !use_efi_dflts;
2251 				free(tmpbuf);
2252 				goto retry_alternate_logic;
2253 			}
2254 			if (skip_this_sb)
2255 				continue;
2256 		}
2257 		/* Don't print ',' for the last superblock */
2258 		if (cylno == sblock.fs_ncg-1)
2259 			(void) sprintf(pbuf, " %llu", num);
2260 		else
2261 			(void) sprintf(pbuf, " %llu,", num);
2262 		plen = strlen(pbuf);
2263 		if ((width + plen) > (WIDTH - 1)) {
2264 			width = plen;
2265 			tprintf("\n");
2266 		} else {
2267 			width += plen;
2268 		}
2269 		if (Nflag && retry)
2270 			(void) strncat(tmpbuf, pbuf, strlen(pbuf));
2271 		else
2272 			(void) fprintf(stderr, "%s", pbuf);
2273 	}
2274 	tprintf("\n");
2275 	if (Nflag) {
2276 		if (retry)
2277 			(void) fprintf(stderr, "%s", tmpbuf);
2278 		free(tmpbuf);
2279 		lockexit(0);
2280 	}
2281 
2282 	free(tmpbuf);
2283 	if (grow)
2284 		goto grow50;
2285 
2286 	/*
2287 	 * Now construct the initial file system,
2288 	 * then write out the super-block.
2289 	 */
2290 	fsinit();
2291 grow50:
2292 	/*
2293 	 * write the superblock and csum information
2294 	 */
2295 	wtsb();
2296 
2297 	/*
2298 	 * extend the last cylinder group in the original file system
2299 	 */
2300 	if (grow) {
2301 		extendcg(grow_fs_ncg-1);
2302 		wtsb();
2303 	}
2304 
2305 	/*
2306 	 * Write out the duplicate super blocks to the first 10
2307 	 * cylinder groups (or fewer, if there are fewer than 10
2308 	 * cylinder groups).
2309 	 */
2310 	for (cylno = 0; cylno < sblock.fs_ncg && cylno < 10; cylno++)
2311 		awtfs(fsbtodb(&sblock, (uint64_t)cgsblock(&sblock, cylno)),
2312 		    (int)sbsize, (char *)&sblock, SAVE);
2313 
2314 	/*
2315 	 * Now write out duplicate super blocks to the remaining
2316 	 * cylinder groups.  In the case of multi-terabyte file
2317 	 * systems, just write out the super block to the last ten
2318 	 * cylinder groups (or however many are left).
2319 	 */
2320 	if (mtb == 'y') {
2321 		if (sblock.fs_ncg <= 10)
2322 			cylno = sblock.fs_ncg;
2323 		else if (sblock.fs_ncg <= 20)
2324 			cylno = 10;
2325 		else
2326 			cylno = sblock.fs_ncg - 10;
2327 	}
2328 
2329 	for (; cylno < sblock.fs_ncg; cylno++)
2330 		awtfs(fsbtodb(&sblock, (uint64_t)cgsblock(&sblock, cylno)),
2331 		    (int)sbsize, (char *)&sblock, SAVE);
2332 
2333 	/*
2334 	 * Flush out all the AIO writes we've done.  It's not
2335 	 * necessary to do this explicitly, but it's the only
2336 	 * way to report any errors from those writes.
2337 	 */
2338 	flush_writes();
2339 
2340 	/*
2341 	 * set clean flag
2342 	 */
2343 	if (grow)
2344 		sblock.fs_clean = grow_fs_clean;
2345 	else
2346 		sblock.fs_clean = FSCLEAN;
2347 	sblock.fs_time = mkfstime;
2348 	sblock.fs_state = FSOKAY - sblock.fs_time;
2349 	wtfs((diskaddr_t)(SBOFF / sectorsize), sbsize, (char *)&sblock);
2350 	isbad = 0;
2351 
2352 	if (fsync(fso) == -1) {
2353 		saverr = errno;
2354 		(void) fprintf(stderr,
2355 		    gettext("mkfs: fsync failed on write disk: %s\n"),
2356 		    strerror(saverr));
2357 		/* we're just cleaning up, so keep going */
2358 	}
2359 	if (close(fsi) == -1) {
2360 		saverr = errno;
2361 		(void) fprintf(stderr,
2362 		    gettext("mkfs: close failed on read disk: %s\n"),
2363 		    strerror(saverr));
2364 		/* we're just cleaning up, so keep going */
2365 	}
2366 	if (close(fso) == -1) {
2367 		saverr = errno;
2368 		(void) fprintf(stderr,
2369 		    gettext("mkfs: close failed on write disk: %s\n"),
2370 		    strerror(saverr));
2371 		/* we're just cleaning up, so keep going */
2372 	}
2373 	fsi = fso = -1;
2374 
2375 #ifndef STANDALONE
2376 	lockexit(0);
2377 #endif
2378 
2379 	return (0);
2380 }
2381 
2382 /*
2383  * Figure out how big the partition we're dealing with is.
2384  * The value returned is in disk blocks (sectors);
2385  */
2386 static diskaddr_t
2387 get_max_size(int fd)
2388 {
2389 	struct vtoc vtoc;
2390 	dk_gpt_t *efi_vtoc;
2391 	diskaddr_t	slicesize;
2392 
2393 	int index = read_vtoc(fd, &vtoc);
2394 
2395 	if (index >= 0) {
2396 		label_type = LABEL_TYPE_VTOC;
2397 	} else {
2398 		if (index == VT_ENOTSUP || index == VT_ERROR) {
2399 			/* it might be an EFI label */
2400 			index = efi_alloc_and_read(fd, &efi_vtoc);
2401 			label_type = LABEL_TYPE_EFI;
2402 		}
2403 	}
2404 
2405 	if (index < 0) {
2406 		switch (index) {
2407 		case VT_ERROR:
2408 			break;
2409 		case VT_EIO:
2410 			errno = EIO;
2411 			break;
2412 		case VT_EINVAL:
2413 			errno = EINVAL;
2414 		}
2415 		perror(gettext("Can not determine partition size"));
2416 		lockexit(32);
2417 	}
2418 
2419 	if (label_type == LABEL_TYPE_EFI) {
2420 		slicesize = efi_vtoc->efi_parts[index].p_size;
2421 		efi_free(efi_vtoc);
2422 	} else {
2423 		/*
2424 		 * In the vtoc struct, p_size is a 32-bit signed quantity.
2425 		 * In the dk_gpt struct (efi's version of the vtoc), p_size
2426 		 * is an unsigned 64-bit quantity.  By casting the vtoc's
2427 		 * psize to an unsigned 32-bit quantity, it will be copied
2428 		 * to 'slicesize' (an unsigned 64-bit diskaddr_t) without
2429 		 * sign extension.
2430 		 */
2431 
2432 		slicesize = (uint32_t)vtoc.v_part[index].p_size;
2433 	}
2434 
2435 	dprintf(("DeBuG get_max_size index = %d, p_size = %lld, dolimit = %d\n",
2436 	    index, slicesize, (slicesize > FS_MAX)));
2437 
2438 	/*
2439 	 * The next line limits a UFS file system to the maximum
2440 	 * supported size.
2441 	 */
2442 
2443 	if (slicesize > FS_MAX)
2444 		return (FS_MAX);
2445 	return (slicesize);
2446 }
2447 
2448 static long
2449 get_max_track_size(int fd)
2450 {
2451 	struct dk_cinfo ci;
2452 	long track_size = -1;
2453 
2454 	if (ioctl(fd, DKIOCINFO, &ci) == 0) {
2455 		track_size = ci.dki_maxtransfer * DEV_BSIZE;
2456 	}
2457 
2458 	if ((track_size < 0)) {
2459 		int	error = 0;
2460 		int	maxphys;
2461 		int	gotit = 0;
2462 
2463 		gotit = fsgetmaxphys(&maxphys, &error);
2464 		if (gotit) {
2465 			track_size = MIN(MB, maxphys);
2466 		} else {
2467 			(void) fprintf(stderr, gettext(
2468 "Warning: Could not get system value for maxphys. The value for\n"
2469 "maxcontig will default to 1MB.\n"));
2470 			track_size = MB;
2471 		}
2472 	}
2473 	return (track_size);
2474 }
2475 
2476 /*
2477  * Initialize a cylinder group.
2478  */
2479 static void
2480 initcg(int cylno)
2481 {
2482 	diskaddr_t cbase, d;
2483 	diskaddr_t dlower;	/* last data block before cg metadata */
2484 	diskaddr_t dupper;	/* first data block after cg metadata */
2485 	diskaddr_t dmax;
2486 	int64_t i;
2487 	struct csum *cs;
2488 	struct dinode *inode_buffer;
2489 	int size;
2490 
2491 	/*
2492 	 * Variables used to store intermediate results as a part of
2493 	 * the internal implementation of the cbtocylno() macros.
2494 	 */
2495 	diskaddr_t bno;		/* UFS block number (not sector number) */
2496 	int	cbcylno;	/* current cylinder number */
2497 	int	cbcylno_sect;	/* sector offset within cylinder */
2498 	int	cbsect_incr;	/* amount to increment sector offset */
2499 
2500 	/*
2501 	 * Variables used to store intermediate results as a part of
2502 	 * the internal implementation of the cbtorpos() macros.
2503 	 */
2504 	short	*cgblks;	/* pointer to array of free blocks in cg */
2505 	int	trackrpos;	/* tmp variable for rotation position */
2506 	int	trackoff;	/* offset within a track */
2507 	int	trackoff_incr;	/* amount to increment trackoff */
2508 	int	rpos;		/* rotation position of current block */
2509 	int	rpos_incr;	/* amount to increment rpos per block */
2510 
2511 	union cgun *icgun;	/* local pointer to a cg summary block */
2512 #define	icg	(icgun->cg)
2513 
2514 	icgun = (union cgun *)getbuf(&cgsumbuf, sizeof (union cgun));
2515 
2516 	/*
2517 	 * Determine block bounds for cylinder group.
2518 	 * Allow space for super block summary information in first
2519 	 * cylinder group.
2520 	 */
2521 	cbase = cgbase(&sblock, cylno);
2522 	dmax = cbase + sblock.fs_fpg;
2523 	if (dmax > sblock.fs_size)	/* last cg may be smaller than normal */
2524 		dmax = sblock.fs_size;
2525 	dlower = cgsblock(&sblock, cylno) - cbase;
2526 	dupper = cgdmin(&sblock, cylno) - cbase;
2527 	if (cylno == 0)
2528 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
2529 	cs = fscs + cylno;
2530 	icg.cg_time = mkfstime;
2531 	icg.cg_magic = CG_MAGIC;
2532 	icg.cg_cgx = cylno;
2533 	/* last one gets whatever's left */
2534 	if (cylno == sblock.fs_ncg - 1)
2535 		icg.cg_ncyl = sblock.fs_ncyl - (sblock.fs_cpg * cylno);
2536 	else
2537 		icg.cg_ncyl = sblock.fs_cpg;
2538 	icg.cg_niblk = sblock.fs_ipg;
2539 	icg.cg_ndblk = dmax - cbase;
2540 	icg.cg_cs.cs_ndir = 0;
2541 	icg.cg_cs.cs_nffree = 0;
2542 	icg.cg_cs.cs_nbfree = 0;
2543 	icg.cg_cs.cs_nifree = 0;
2544 	icg.cg_rotor = 0;
2545 	icg.cg_frotor = 0;
2546 	icg.cg_irotor = 0;
2547 	icg.cg_btotoff = &icg.cg_space[0] - (uchar_t *)(&icg.cg_link);
2548 	icg.cg_boff = icg.cg_btotoff + sblock.fs_cpg * sizeof (long);
2549 	icg.cg_iusedoff = icg.cg_boff +
2550 	    sblock.fs_cpg * sblock.fs_nrpos * sizeof (short);
2551 	icg.cg_freeoff = icg.cg_iusedoff + howmany(sblock.fs_ipg, NBBY);
2552 	icg.cg_nextfreeoff = icg.cg_freeoff +
2553 	    howmany(sblock.fs_cpg * sblock.fs_spc / NSPF(&sblock), NBBY);
2554 	for (i = 0; i < sblock.fs_frag; i++) {
2555 		icg.cg_frsum[i] = 0;
2556 	}
2557 	bzero((caddr_t)cg_inosused(&icg), icg.cg_freeoff - icg.cg_iusedoff);
2558 	icg.cg_cs.cs_nifree += sblock.fs_ipg;
2559 	if (cylno == 0)
2560 		for (i = 0; i < UFSROOTINO; i++) {
2561 			setbit(cg_inosused(&icg), i);
2562 			icg.cg_cs.cs_nifree--;
2563 		}
2564 
2565 	/*
2566 	 * Initialize all the inodes in the cylinder group using
2567 	 * random numbers.
2568 	 */
2569 	size = sblock.fs_ipg * sizeof (struct dinode);
2570 	inode_buffer = (struct dinode *)getbuf(&inodebuf, size);
2571 
2572 	for (i = 0; i < sblock.fs_ipg; i++) {
2573 		IRANDOMIZE(&(inode_buffer[i].di_ic));
2574 	}
2575 
2576 	/*
2577 	 * Write all inodes in a single write for performance.
2578 	 */
2579 	awtfs(fsbtodb(&sblock, (uint64_t)cgimin(&sblock, cylno)), (int)size,
2580 	    (char *)inode_buffer, RELEASE);
2581 
2582 	bzero((caddr_t)cg_blktot(&icg), icg.cg_boff - icg.cg_btotoff);
2583 	bzero((caddr_t)cg_blks(&sblock, &icg, 0),
2584 	    icg.cg_iusedoff - icg.cg_boff);
2585 	bzero((caddr_t)cg_blksfree(&icg), icg.cg_nextfreeoff - icg.cg_freeoff);
2586 
2587 	if (cylno > 0) {
2588 		for (d = 0; d < dlower; d += sblock.fs_frag) {
2589 			setblock(&sblock, cg_blksfree(&icg), d/sblock.fs_frag);
2590 			icg.cg_cs.cs_nbfree++;
2591 			cg_blktot(&icg)[cbtocylno(&sblock, d)]++;
2592 			cg_blks(&sblock, &icg, cbtocylno(&sblock, d))
2593 			    [cbtorpos(&sblock, d)]++;
2594 		}
2595 		sblock.fs_dsize += dlower;
2596 	}
2597 	sblock.fs_dsize += icg.cg_ndblk - dupper;
2598 	if ((i = dupper % sblock.fs_frag) != 0) {
2599 		icg.cg_frsum[sblock.fs_frag - i]++;
2600 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
2601 			setbit(cg_blksfree(&icg), dupper);
2602 			icg.cg_cs.cs_nffree++;
2603 		}
2604 	}
2605 
2606 	/*
2607 	 * WARNING: The following code is somewhat confusing, but
2608 	 * results in a substantial performance improvement in mkfs.
2609 	 *
2610 	 * Instead of using cbtocylno() and cbtorpos() macros, we
2611 	 * keep track of all the intermediate state of those macros
2612 	 * in some variables.  This allows simple addition to be
2613 	 * done to calculate the results as we step through the
2614 	 * blocks in an orderly fashion instead of the slower
2615 	 * multiplication and division the macros are forced to
2616 	 * used so they can support random input.  (Multiplication,
2617 	 * division, and remainder operations typically take about
2618 	 * 10x as many processor cycles as other operations.)
2619 	 *
2620 	 * The basic idea is to take code:
2621 	 *
2622 	 *	for (x = starting_x; x < max; x++)
2623 	 *		y = (x * c) / z
2624 	 *
2625 	 * and rewrite it to take advantage of the fact that
2626 	 * the variable x is incrementing in an orderly way:
2627 	 *
2628 	 *	intermediate = starting_x * c
2629 	 *	yval = intermediate / z
2630 	 *	for (x = starting_x; x < max; x++) {
2631 	 *		y = yval;
2632 	 *		intermediate += c
2633 	 *		if (intermediate > z) {
2634 	 *			yval++;
2635 	 *			intermediate -= z
2636 	 *		}
2637 	 *	}
2638 	 *
2639 	 * Performance has improved as much as 4X using this code.
2640 	 */
2641 
2642 	/*
2643 	 * Initialize the starting points for all the cbtocylno()
2644 	 * macro variables and figure out the increments needed each
2645 	 * time through the loop.
2646 	 */
2647 	cbcylno_sect = dupper * NSPF(&sblock);
2648 	cbsect_incr = sblock.fs_frag * NSPF(&sblock);
2649 	cbcylno = cbcylno_sect / sblock.fs_spc;
2650 	cbcylno_sect %= sblock.fs_spc;
2651 	cgblks = cg_blks(&sblock, &icg, cbcylno);
2652 	bno = dupper / sblock.fs_frag;
2653 
2654 	/*
2655 	 * Initialize the starting points for all the cbtorpos()
2656 	 * macro variables and figure out the increments needed each
2657 	 * time through the loop.
2658 	 *
2659 	 * It's harder to simplify the cbtorpos() macro if there were
2660 	 * alternate sectors specified (or if they previously existed
2661 	 * in the growfs case).  Since this is rare, we just revert to
2662 	 * using the macros in this case and skip the variable setup.
2663 	 */
2664 	if (!spc_flag) {
2665 		trackrpos = (cbcylno_sect % sblock.fs_nsect) * sblock.fs_nrpos;
2666 		rpos = trackrpos / sblock.fs_nsect;
2667 		trackoff = trackrpos % sblock.fs_nsect;
2668 		trackoff_incr = cbsect_incr * sblock.fs_nrpos;
2669 		rpos_incr = (trackoff_incr / sblock.fs_nsect) % sblock.fs_nrpos;
2670 		trackoff_incr = trackoff_incr % sblock.fs_nsect;
2671 	}
2672 
2673 	/*
2674 	 * Loop through all the blocks, marking them free and
2675 	 * updating totals kept in the superblock and cg summary.
2676 	 */
2677 	for (d = dupper; d + sblock.fs_frag <= dmax - cbase; ) {
2678 		setblock(&sblock, cg_blksfree(&icg),  bno);
2679 		icg.cg_cs.cs_nbfree++;
2680 
2681 		cg_blktot(&icg)[cbcylno]++;
2682 
2683 		if (!spc_flag)
2684 			cgblks[rpos]++;
2685 		else
2686 			cg_blks(&sblock, &icg, cbtocylno(&sblock, d))
2687 			    [cbtorpos(&sblock, d)]++;
2688 
2689 		d += sblock.fs_frag;
2690 		bno++;
2691 
2692 		/*
2693 		 * Increment the sector offset within the cylinder
2694 		 * for the cbtocylno() macro reimplementation.  If
2695 		 * we're beyond the end of the cylinder, update the
2696 		 * cylinder number, calculate the offset in the
2697 		 * new cylinder, and update the cgblks pointer
2698 		 * to the next rotational position.
2699 		 */
2700 		cbcylno_sect += cbsect_incr;
2701 		if (cbcylno_sect >= sblock.fs_spc) {
2702 			cbcylno++;
2703 			cbcylno_sect -= sblock.fs_spc;
2704 			cgblks += sblock.fs_nrpos;
2705 		}
2706 
2707 		/*
2708 		 * If there aren't alternate sectors, increment the
2709 		 * rotational position variables for the cbtorpos()
2710 		 * reimplementation.  Note that we potentially
2711 		 * increment rpos twice.  Once by rpos_incr, and one
2712 		 * more time when we wrap to a new track because
2713 		 * trackoff >= fs_nsect.
2714 		 */
2715 		if (!spc_flag) {
2716 			trackoff += trackoff_incr;
2717 			rpos += rpos_incr;
2718 			if (trackoff >= sblock.fs_nsect) {
2719 				trackoff -= sblock.fs_nsect;
2720 				rpos++;
2721 			}
2722 			if (rpos >= sblock.fs_nrpos)
2723 				rpos -= sblock.fs_nrpos;
2724 		}
2725 	}
2726 
2727 	if (d < dmax - cbase) {
2728 		icg.cg_frsum[dmax - cbase - d]++;
2729 		for (; d < dmax - cbase; d++) {
2730 			setbit(cg_blksfree(&icg), d);
2731 			icg.cg_cs.cs_nffree++;
2732 		}
2733 	}
2734 	sblock.fs_cstotal.cs_ndir += icg.cg_cs.cs_ndir;
2735 	sblock.fs_cstotal.cs_nffree += icg.cg_cs.cs_nffree;
2736 	sblock.fs_cstotal.cs_nbfree += icg.cg_cs.cs_nbfree;
2737 	sblock.fs_cstotal.cs_nifree += icg.cg_cs.cs_nifree;
2738 	*cs = icg.cg_cs;
2739 	awtfs(fsbtodb(&sblock, (uint64_t)cgtod(&sblock, cylno)),
2740 	    sblock.fs_bsize, (char *)&icg, RELEASE);
2741 }
2742 
2743 /*
2744  * initialize the file system
2745  */
2746 struct inode node;
2747 
2748 #define	LOSTDIR
2749 #ifdef LOSTDIR
2750 #define	PREDEFDIR 3
2751 #else
2752 #define	PREDEFDIR 2
2753 #endif
2754 
2755 struct direct root_dir[] = {
2756 	{ UFSROOTINO, sizeof (struct direct), 1, "." },
2757 	{ UFSROOTINO, sizeof (struct direct), 2, ".." },
2758 #ifdef LOSTDIR
2759 	{ LOSTFOUNDINO, sizeof (struct direct), 10, "lost+found" },
2760 #endif
2761 };
2762 #ifdef LOSTDIR
2763 struct direct lost_found_dir[] = {
2764 	{ LOSTFOUNDINO, sizeof (struct direct), 1, "." },
2765 	{ UFSROOTINO, sizeof (struct direct), 2, ".." },
2766 	{ 0, DIRBLKSIZ, 0, 0 },
2767 };
2768 #endif
2769 char buf[MAXBSIZE];
2770 
2771 static void
2772 fsinit()
2773 {
2774 	int i;
2775 
2776 
2777 	/*
2778 	 * initialize the node
2779 	 */
2780 	node.i_atime = mkfstime;
2781 	node.i_mtime = mkfstime;
2782 	node.i_ctime = mkfstime;
2783 #ifdef LOSTDIR
2784 	/*
2785 	 * create the lost+found directory
2786 	 */
2787 	(void) makedir(lost_found_dir, 2);
2788 	for (i = DIRBLKSIZ; i < sblock.fs_bsize; i += DIRBLKSIZ) {
2789 		bcopy(&lost_found_dir[2], &buf[i], DIRSIZ(&lost_found_dir[2]));
2790 	}
2791 	node.i_number = LOSTFOUNDINO;
2792 	node.i_smode = node.i_mode = IFDIR | 0700;
2793 	node.i_nlink = 2;
2794 	node.i_size = sblock.fs_bsize;
2795 	node.i_db[0] = alloc((int)node.i_size, node.i_mode);
2796 	node.i_blocks = btodb(fragroundup(&sblock, (int)node.i_size));
2797 	IRANDOMIZE(&node.i_ic);
2798 	wtfs(fsbtodb(&sblock, (uint64_t)node.i_db[0]), (int)node.i_size, buf);
2799 	iput(&node);
2800 #endif
2801 	/*
2802 	 * create the root directory
2803 	 */
2804 	node.i_number = UFSROOTINO;
2805 	node.i_mode = node.i_smode = IFDIR | UMASK;
2806 	node.i_nlink = PREDEFDIR;
2807 	node.i_size = makedir(root_dir, PREDEFDIR);
2808 	node.i_db[0] = alloc(sblock.fs_fsize, node.i_mode);
2809 	/* i_size < 2GB because we are initializing the file system */
2810 	node.i_blocks = btodb(fragroundup(&sblock, (int)node.i_size));
2811 	IRANDOMIZE(&node.i_ic);
2812 	wtfs(fsbtodb(&sblock, (uint64_t)node.i_db[0]), sblock.fs_fsize, buf);
2813 	iput(&node);
2814 }
2815 
2816 /*
2817  * construct a set of directory entries in "buf".
2818  * return size of directory.
2819  */
2820 static int
2821 makedir(struct direct *protodir, int entries)
2822 {
2823 	char *cp;
2824 	int i;
2825 	ushort_t spcleft;
2826 
2827 	spcleft = DIRBLKSIZ;
2828 	for (cp = buf, i = 0; i < entries - 1; i++) {
2829 		protodir[i].d_reclen = DIRSIZ(&protodir[i]);
2830 		bcopy(&protodir[i], cp, protodir[i].d_reclen);
2831 		cp += protodir[i].d_reclen;
2832 		spcleft -= protodir[i].d_reclen;
2833 	}
2834 	protodir[i].d_reclen = spcleft;
2835 	bcopy(&protodir[i], cp, DIRSIZ(&protodir[i]));
2836 	return (DIRBLKSIZ);
2837 }
2838 
2839 /*
2840  * allocate a block or frag
2841  */
2842 static daddr32_t
2843 alloc(int size, int mode)
2844 {
2845 	int i, frag;
2846 	daddr32_t d;
2847 
2848 	rdfs(fsbtodb(&sblock, (uint64_t)cgtod(&sblock, 0)), sblock.fs_cgsize,
2849 	    (char *)&acg);
2850 	if (acg.cg_magic != CG_MAGIC) {
2851 		(void) fprintf(stderr, gettext("cg 0: bad magic number\n"));
2852 		lockexit(32);
2853 	}
2854 	if (acg.cg_cs.cs_nbfree == 0) {
2855 		(void) fprintf(stderr,
2856 		    gettext("first cylinder group ran out of space\n"));
2857 		lockexit(32);
2858 	}
2859 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
2860 		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
2861 			goto goth;
2862 	(void) fprintf(stderr,
2863 	    gettext("internal error: can't find block in cyl 0\n"));
2864 	lockexit(32);
2865 goth:
2866 	clrblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag);
2867 	acg.cg_cs.cs_nbfree--;
2868 	sblock.fs_cstotal.cs_nbfree--;
2869 	fscs[0].cs_nbfree--;
2870 	if (mode & IFDIR) {
2871 		acg.cg_cs.cs_ndir++;
2872 		sblock.fs_cstotal.cs_ndir++;
2873 		fscs[0].cs_ndir++;
2874 	}
2875 	cg_blktot(&acg)[cbtocylno(&sblock, d)]--;
2876 	cg_blks(&sblock, &acg, cbtocylno(&sblock, d))[cbtorpos(&sblock, d)]--;
2877 	if (size != sblock.fs_bsize) {
2878 		frag = howmany(size, sblock.fs_fsize);
2879 		fscs[0].cs_nffree += sblock.fs_frag - frag;
2880 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
2881 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
2882 		acg.cg_frsum[sblock.fs_frag - frag]++;
2883 		for (i = frag; i < sblock.fs_frag; i++)
2884 			setbit(cg_blksfree(&acg), d + i);
2885 	}
2886 	wtfs(fsbtodb(&sblock, (uint64_t)cgtod(&sblock, 0)), sblock.fs_cgsize,
2887 	    (char *)&acg);
2888 	return (d);
2889 }
2890 
2891 /*
2892  * Allocate an inode on the disk
2893  */
2894 static void
2895 iput(struct inode *ip)
2896 {
2897 	struct dinode buf[MAXINOPB];
2898 	diskaddr_t d;
2899 
2900 	rdfs(fsbtodb(&sblock, (uint64_t)cgtod(&sblock, 0)), sblock.fs_cgsize,
2901 	    (char *)&acg);
2902 	if (acg.cg_magic != CG_MAGIC) {
2903 		(void) fprintf(stderr, gettext("cg 0: bad magic number\n"));
2904 		lockexit(32);
2905 	}
2906 	acg.cg_cs.cs_nifree--;
2907 	setbit(cg_inosused(&acg), ip->i_number);
2908 	wtfs(fsbtodb(&sblock, (uint64_t)cgtod(&sblock, 0)), sblock.fs_cgsize,
2909 	    (char *)&acg);
2910 	sblock.fs_cstotal.cs_nifree--;
2911 	fscs[0].cs_nifree--;
2912 	if ((int)ip->i_number >= sblock.fs_ipg * sblock.fs_ncg) {
2913 		(void) fprintf(stderr,
2914 		    gettext("fsinit: inode value out of range (%d).\n"),
2915 		    ip->i_number);
2916 		lockexit(32);
2917 	}
2918 	d = fsbtodb(&sblock, (uint64_t)itod(&sblock, (int)ip->i_number));
2919 	rdfs(d, sblock.fs_bsize, (char *)buf);
2920 	buf[itoo(&sblock, (int)ip->i_number)].di_ic = ip->i_ic;
2921 	wtfs(d, sblock.fs_bsize, (char *)buf);
2922 }
2923 
2924 /*
2925  * getbuf()	-- Get a buffer for use in an AIO operation.  Buffer
2926  *		is zero'd the first time returned, left with whatever
2927  *		was in memory after that.  This function actually gets
2928  *		enough memory the first time it's called to support
2929  *		MAXBUF buffers like a slab allocator.  When all the
2930  *		buffers are in use, it waits for an aio to complete
2931  *		and make a buffer available.
2932  *
2933  *		Never returns an error.  Either succeeds or exits.
2934  */
2935 static char *
2936 getbuf(bufhdr *bufhead, int size)
2937 {
2938 	bufhdr *pbuf;
2939 	bufhdr *prev;
2940 	int i;
2941 	int buf_size, max_bufs;
2942 
2943 	/*
2944 	 * Initialize all the buffers
2945 	 */
2946 	if (bufhead->head == NULL) {
2947 		/*
2948 		 * round up the size of our buffer header to a
2949 		 * 16 byte boundary so the address we return to
2950 		 * the caller is "suitably aligned".
2951 		 */
2952 		bufhdrsize = (sizeof (bufhdr) + 15) & ~15;
2953 
2954 		/*
2955 		 * Add in our header to the buffer and round it all up to
2956 		 * a 16 byte boundry so each member of the slab is aligned.
2957 		 */
2958 		buf_size = (size + bufhdrsize + 15) & ~15;
2959 
2960 		/*
2961 		 * Limit number of buffers to lesser of MAXBUFMEM's worth
2962 		 * or MAXBUF, whichever is less.
2963 		 */
2964 		max_bufs = MAXBUFMEM / buf_size;
2965 		if (max_bufs > MAXBUF)
2966 			max_bufs = MAXBUF;
2967 
2968 		pbuf = (bufhdr *)calloc(max_bufs, buf_size);
2969 		if (pbuf == NULL) {
2970 			perror("calloc");
2971 			lockexit(32);
2972 		}
2973 
2974 		bufhead->head = bufhead;
2975 		prev = bufhead;
2976 		for (i = 0; i < max_bufs; i++) {
2977 			pbuf->head = bufhead;
2978 			prev->next = pbuf;
2979 			prev = pbuf;
2980 			pbuf = (bufhdr *)((char *)pbuf + buf_size);
2981 		}
2982 	}
2983 
2984 	/*
2985 	 * Get an available buffer, waiting for I/O if necessary
2986 	 */
2987 	wait_for_write(NOBLOCK);
2988 	while (bufhead->next == NULL)
2989 		wait_for_write(BLOCK);
2990 
2991 	/*
2992 	 * Take the buffer off the list
2993 	 */
2994 	pbuf = bufhead->next;
2995 	bufhead->next = pbuf->next;
2996 	pbuf->next = NULL;
2997 
2998 	/*
2999 	 * return the empty buffer space just past the header
3000 	 */
3001 	return ((char *)pbuf + bufhdrsize);
3002 }
3003 
3004 /*
3005  * freebuf()	-- Free a buffer gotten previously through getbuf.
3006  *		Puts the buffer back on the appropriate list for
3007  *		later use.  Never calls free().
3008  *
3009  * Assumes that SIGINT is blocked.
3010  */
3011 static void
3012 freebuf(char *buf)
3013 {
3014 	bufhdr *pbuf;
3015 	bufhdr *bufhead;
3016 
3017 	/*
3018 	 * get the header for this buffer
3019 	 */
3020 	pbuf = (bufhdr *)(buf - bufhdrsize);
3021 
3022 	/*
3023 	 * Put it back on the list of available buffers
3024 	 */
3025 	bufhead = pbuf->head;
3026 	pbuf->next = bufhead->next;
3027 	bufhead->next = pbuf;
3028 }
3029 
3030 /*
3031  * freetrans()	-- Free a transaction gotten previously through getaiop.
3032  *		Puts the transaction struct back on the appropriate list for
3033  *		later use.  Never calls free().
3034  *
3035  * Assumes that SIGINT is blocked.
3036  */
3037 static void
3038 freetrans(aio_trans *transp)
3039 {
3040 	/*
3041 	 * free the buffer associated with this AIO if needed
3042 	 */
3043 	if (transp->release == RELEASE)
3044 		freebuf(transp->buffer);
3045 
3046 	/*
3047 	 * Put transaction on the free list
3048 	 */
3049 	transp->next = results.trans;
3050 	results.trans = transp;
3051 }
3052 
3053 /*
3054  * wait_for_write()	-- Wait for an aio write to complete.  Return
3055  *			the transaction structure for that write.
3056  *
3057  * Blocks SIGINT if necessary.
3058  */
3059 aio_trans *
3060 wait_for_write(int block)
3061 {
3062 	aio_trans	*transp;
3063 	aio_result_t	*resultp;
3064 	static struct timeval  zero_wait = { 0, 0 };
3065 	sigset_t	old_mask;
3066 
3067 	/*
3068 	 * If we know there aren't any outstanding transactions, just return
3069 	 */
3070 	if (results.outstanding == 0)
3071 		return ((aio_trans *) 0);
3072 
3073 	block_sigint(&old_mask);
3074 
3075 	resultp = aiowait(block ? NULL : &zero_wait);
3076 	if (resultp == NULL ||
3077 	    (resultp == (aio_result_t *)-1 && errno == EINVAL)) {
3078 		unblock_sigint(&old_mask);
3079 		return ((aio_trans *) 0);
3080 	}
3081 
3082 	results.outstanding--;
3083 	transp = (aio_trans *)resultp;
3084 
3085 	if (resultp->aio_return != transp->size) {
3086 		if (resultp->aio_return == -1) {
3087 			/*
3088 			 * The aiowrite() may have failed because the
3089 			 * kernel didn't have enough memory to do the job.
3090 			 * Flush all pending writes and try a normal
3091 			 * write().  wtfs_breakup() will call exit if it
3092 			 * fails, so we don't worry about errors here.
3093 			 */
3094 			flush_writes();
3095 			wtfs_breakup(transp->bno, transp->size, transp->buffer);
3096 		} else {
3097 			(void) fprintf(stderr, gettext(
3098 			    "short write (%d of %d bytes) on sector %lld\n"),
3099 			    resultp->aio_return, transp->size,
3100 			    transp->bno);
3101 			/*
3102 			 * Don't unblock SIGINT, to avoid potential
3103 			 * looping due to queued interrupts and
3104 			 * error handling.
3105 			 */
3106 			lockexit(32);
3107 		}
3108 	}
3109 
3110 	resultp->aio_return = 0;
3111 	freetrans(transp);
3112 	unblock_sigint(&old_mask);
3113 	return (transp);
3114 }
3115 
3116 /*
3117  * flush_writes()	-- flush all the outstanding aio writes.
3118  */
3119 static void
3120 flush_writes(void)
3121 {
3122 	while (wait_for_write(BLOCK))
3123 		;
3124 }
3125 
3126 /*
3127  * get_aiop()	-- find and return an aio_trans structure on which a new
3128  *		aio can be done.  Blocks on aiowait() if needed.  Reaps
3129  *		all outstanding completed aio's.
3130  *
3131  * Assumes that SIGINT is blocked.
3132  */
3133 aio_trans *
3134 get_aiop()
3135 {
3136 	int i;
3137 	aio_trans *transp;
3138 	aio_trans *prev;
3139 
3140 	/*
3141 	 * initialize aio stuff
3142 	 */
3143 	if (!aio_inited) {
3144 		aio_inited = 1;
3145 
3146 		results.maxpend = 0;
3147 		results.outstanding = 0;
3148 		results.max = MAXAIO;
3149 
3150 		results.trans = (aio_trans *)calloc(results.max,
3151 		    sizeof (aio_trans));
3152 		if (results.trans == NULL) {
3153 			perror("calloc");
3154 			lockexit(32);
3155 		}
3156 
3157 		/*
3158 		 * Initialize the linked list of aio transaction
3159 		 * structures.  Note that the final "next" pointer
3160 		 * will be NULL since we got the buffer from calloc().
3161 		 */
3162 		prev = results.trans;
3163 		for (i = 1; i < results.max; i++) {
3164 			prev->next = &(results.trans[i]);
3165 			prev = prev->next;
3166 		}
3167 	}
3168 
3169 	wait_for_write(NOBLOCK);
3170 	while (results.trans == NULL)
3171 		wait_for_write(BLOCK);
3172 	transp = results.trans;
3173 	results.trans = results.trans->next;
3174 
3175 	transp->next = 0;
3176 	transp->resultbuf.aio_return = AIO_INPROGRESS;
3177 	return (transp);
3178 }
3179 
3180 /*
3181  * read a block from the file system
3182  */
3183 static void
3184 rdfs(diskaddr_t bno, int size, char *bf)
3185 {
3186 	int n, saverr;
3187 
3188 	/*
3189 	 * In case we need any data that's pending in an aiowrite(),
3190 	 * we wait for them all to complete before doing a read.
3191 	 */
3192 	flush_writes();
3193 
3194 	/*
3195 	 * Note: the llseek() can succeed, even if the offset is out of range.
3196 	 * It's not until the file i/o operation (the read()) that one knows
3197 	 * for sure if the raw device can handle the offset.
3198 	 */
3199 	if (llseek(fsi, (offset_t)bno * sectorsize, 0) < 0) {
3200 		saverr = errno;
3201 		(void) fprintf(stderr,
3202 		    gettext("seek error on sector %lld: %s\n"),
3203 		    bno, strerror(saverr));
3204 		lockexit(32);
3205 	}
3206 	n = read(fsi, bf, size);
3207 	if (n != size) {
3208 		saverr = errno;
3209 		if (n == -1)
3210 			(void) fprintf(stderr,
3211 			    gettext("read error on sector %lld: %s\n"),
3212 			    bno, strerror(saverr));
3213 		else
3214 			(void) fprintf(stderr, gettext(
3215 			    "short read (%d of %d bytes) on sector %lld\n"),
3216 			    n, size, bno);
3217 		lockexit(32);
3218 	}
3219 }
3220 
3221 /*
3222  * write a block to the file system
3223  */
3224 static void
3225 wtfs(diskaddr_t bno, int size, char *bf)
3226 {
3227 	int n, saverr;
3228 
3229 	if (fso == -1)
3230 		return;
3231 
3232 	/*
3233 	 * Note: the llseek() can succeed, even if the offset is out of range.
3234 	 * It's not until the file i/o operation (the write()) that one knows
3235 	 * for sure if the raw device can handle the offset.
3236 	 */
3237 	if (llseek(fso, (offset_t)bno * sectorsize, 0) < 0) {
3238 		saverr = errno;
3239 		(void) fprintf(stderr,
3240 		    gettext("seek error on sector %lld: %s\n"),
3241 		    bno, strerror(saverr));
3242 		lockexit(32);
3243 	}
3244 	if (Nflag)
3245 		return;
3246 	n = write(fso, bf, size);
3247 	if (n != size) {
3248 		saverr = errno;
3249 		if (n == -1)
3250 			(void) fprintf(stderr,
3251 			    gettext("write error on sector %lld: %s\n"),
3252 			    bno, strerror(saverr));
3253 		else
3254 			(void) fprintf(stderr, gettext(
3255 			    "short write (%d of %d bytes) on sector %lld\n"),
3256 			    n, size, bno);
3257 		lockexit(32);
3258 	}
3259 }
3260 
3261 /*
3262  * write a block to the file system -- buffered with aio
3263  */
3264 static void
3265 awtfs(diskaddr_t bno, int size, char *bf, int release)
3266 {
3267 	int n;
3268 	aio_trans 	*transp;
3269 	sigset_t 	old_mask;
3270 
3271 	if (fso == -1)
3272 		return;
3273 
3274 	/*
3275 	 * We need to keep things consistent if we get interrupted,
3276 	 * so defer any expected interrupts for the time being.
3277 	 */
3278 	block_sigint(&old_mask);
3279 
3280 	if (Nflag) {
3281 		if (release == RELEASE)
3282 			freebuf(bf);
3283 	} else {
3284 		transp = get_aiop();
3285 		transp->bno = bno;
3286 		transp->buffer = bf;
3287 		transp->size = size;
3288 		transp->release = release;
3289 
3290 		n = aiowrite(fso, bf, size, (off_t)bno * sectorsize,
3291 		    SEEK_SET, &transp->resultbuf);
3292 
3293 		if (n < 0) {
3294 			/*
3295 			 * The aiowrite() may have failed because the
3296 			 * kernel didn't have enough memory to do the job.
3297 			 * Flush all pending writes and try a normal
3298 			 * write().  wtfs_breakup() will call exit if it
3299 			 * fails, so we don't worry about errors here.
3300 			 */
3301 			flush_writes();
3302 			wtfs_breakup(transp->bno, transp->size, transp->buffer);
3303 			freetrans(transp);
3304 		} else {
3305 			/*
3306 			 * Keep track of our pending writes.
3307 			 */
3308 			results.outstanding++;
3309 			if (results.outstanding > results.maxpend)
3310 				results.maxpend = results.outstanding;
3311 		}
3312 	}
3313 
3314 	unblock_sigint(&old_mask);
3315 }
3316 
3317 
3318 /*
3319  * write a block to the file system, but break it up into sbsize
3320  * chunks to avoid forcing a large amount of memory to be locked down.
3321  * Only used as a fallback when an aio write has failed.
3322  */
3323 static void
3324 wtfs_breakup(diskaddr_t bno, int size, char *bf)
3325 {
3326 	int n, saverr;
3327 	int wsize;
3328 	int block_incr = sbsize / sectorsize;
3329 
3330 	if (size < sbsize)
3331 		wsize = size;
3332 	else
3333 		wsize = sbsize;
3334 
3335 	n = 0;
3336 	while (size) {
3337 		/*
3338 		 * Note: the llseek() can succeed, even if the offset is
3339 		 * out of range.  It's not until the file i/o operation
3340 		 * (the write()) that one knows for sure if the raw device
3341 		 * can handle the offset.
3342 		 */
3343 		if (llseek(fso, (offset_t)bno * sectorsize, 0) < 0) {
3344 			saverr = errno;
3345 			(void) fprintf(stderr,
3346 			    gettext("seek error on sector %lld: %s\n"),
3347 			    bno, strerror(saverr));
3348 			lockexit(32);
3349 		}
3350 
3351 		n = write(fso, bf, wsize);
3352 		if (n == -1) {
3353 			saverr = errno;
3354 			(void) fprintf(stderr,
3355 			    gettext("write error on sector %lld: %s\n"),
3356 			    bno, strerror(saverr));
3357 			lockexit(32);
3358 		}
3359 		if (n != wsize) {
3360 			saverr = errno;
3361 			(void) fprintf(stderr, gettext(
3362 			    "short write (%d of %d bytes) on sector %lld\n"),
3363 			    n, size, bno);
3364 			lockexit(32);
3365 		}
3366 
3367 		bno += block_incr;
3368 		bf += wsize;
3369 		size -= wsize;
3370 		if (size < wsize)
3371 			wsize = size;
3372 	}
3373 }
3374 
3375 
3376 /*
3377  * check if a block is available
3378  */
3379 static int
3380 isblock(struct fs *fs, unsigned char *cp, int h)
3381 {
3382 	unsigned char mask;
3383 
3384 	switch (fs->fs_frag) {
3385 	case 8:
3386 		return (cp[h] == 0xff);
3387 	case 4:
3388 		mask = 0x0f << ((h & 0x1) << 2);
3389 		return ((cp[h >> 1] & mask) == mask);
3390 	case 2:
3391 		mask = 0x03 << ((h & 0x3) << 1);
3392 		return ((cp[h >> 2] & mask) == mask);
3393 	case 1:
3394 		mask = 0x01 << (h & 0x7);
3395 		return ((cp[h >> 3] & mask) == mask);
3396 	default:
3397 		(void) fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
3398 		return (0);
3399 	}
3400 }
3401 
3402 /*
3403  * take a block out of the map
3404  */
3405 static void
3406 clrblock(struct fs *fs, unsigned char *cp, int h)
3407 {
3408 	switch ((fs)->fs_frag) {
3409 	case 8:
3410 		cp[h] = 0;
3411 		return;
3412 	case 4:
3413 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
3414 		return;
3415 	case 2:
3416 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
3417 		return;
3418 	case 1:
3419 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
3420 		return;
3421 	default:
3422 		(void) fprintf(stderr,
3423 		    gettext("clrblock: bad fs_frag value %d\n"), fs->fs_frag);
3424 		return;
3425 	}
3426 }
3427 
3428 /*
3429  * put a block into the map
3430  */
3431 static void
3432 setblock(struct fs *fs, unsigned char *cp, int h)
3433 {
3434 	switch (fs->fs_frag) {
3435 	case 8:
3436 		cp[h] = 0xff;
3437 		return;
3438 	case 4:
3439 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
3440 		return;
3441 	case 2:
3442 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
3443 		return;
3444 	case 1:
3445 		cp[h >> 3] |= (0x01 << (h & 0x7));
3446 		return;
3447 	default:
3448 		(void) fprintf(stderr,
3449 		    gettext("setblock: bad fs_frag value %d\n"), fs->fs_frag);
3450 		return;
3451 	}
3452 }
3453 
3454 static void
3455 usage()
3456 {
3457 	(void) fprintf(stderr,
3458 	    gettext("ufs usage: mkfs [-F FSType] [-V] [-m] [-o options] "
3459 	    "special "				/* param 0 */
3460 	    "size(sectors) \\ \n"));		/* param 1 */
3461 	(void) fprintf(stderr,
3462 	    "[nsect "				/* param 2 */
3463 	    "ntrack "				/* param 3 */
3464 	    "bsize "				/* param 4 */
3465 	    "fragsize "				/* param 5 */
3466 	    "cpg "				/* param 6 */
3467 	    "free "				/* param 7 */
3468 	    "rps "				/* param 8 */
3469 	    "nbpi "				/* param 9 */
3470 	    "opt "				/* param 10 */
3471 	    "apc "				/* param 11 */
3472 	    "gap "				/* param 12 */
3473 	    "nrpos "				/* param 13 */
3474 	    "maxcontig "			/* param 14 */
3475 	    "mtb]\n");				/* param 15 */
3476 	(void) fprintf(stderr,
3477 	    gettext(" -m : dump fs cmd line used to make this partition\n"
3478 	    " -V :print this command line and return\n"
3479 	    " -o :ufs options: :nsect=%d,ntrack=%d,bsize=%d,fragsize=%d\n"
3480 	    " -o :ufs options: :cgsize=%d,free=%d,rps=%d,nbpi=%d,opt=%c\n"
3481 	    " -o :ufs options: :apc=%d,gap=%d,nrpos=%d,maxcontig=%d\n"
3482 	    " -o :ufs options: :mtb=%c,calcsb,calcbinsb\n"
3483 "NOTE that all -o suboptions: must be separated only by commas so as to\n"
3484 "be parsed as a single argument\n"),
3485 	    nsect, ntrack, bsize, fragsize, cpg, sblock.fs_minfree, rps,
3486 	    nbpi, opt, apc, (rotdelay == -1) ? 0 : rotdelay,
3487 	    sblock.fs_nrpos, maxcontig, mtb);
3488 	lockexit(32);
3489 }
3490 
3491 /*ARGSUSED*/
3492 static void
3493 dump_fscmd(char *fsys, int fsi)
3494 {
3495 	int64_t used, bpcg, inospercg;
3496 	int64_t nbpi;
3497 	uint64_t nbytes64;
3498 
3499 	bzero((char *)&sblock, sizeof (sblock));
3500 	rdfs((diskaddr_t)SBLOCK, SBSIZE, (char *)&sblock);
3501 
3502 	/*
3503 	 * ensure a valid file system and if not, exit with error or else
3504 	 * we will end up computing block numbers etc and dividing by zero
3505 	 * which will cause floating point errors in this routine.
3506 	 */
3507 
3508 	if ((sblock.fs_magic != FS_MAGIC) &&
3509 	    (sblock.fs_magic != MTB_UFS_MAGIC)) {
3510 		(void) fprintf(stderr, gettext(
3511 		    "[not currently a valid file system - bad superblock]\n"));
3512 		lockexit(32);
3513 	}
3514 
3515 	if (sblock.fs_magic == FS_MAGIC &&
3516 	    (sblock.fs_version != UFS_EFISTYLE4NONEFI_VERSION_2 &&
3517 	    sblock.fs_version != UFS_VERSION_MIN)) {
3518 		(void) fprintf(stderr, gettext(
3519 		    "Unknown version of UFS format: %d\n"), sblock.fs_version);
3520 		lockexit(32);
3521 	}
3522 
3523 	if (sblock.fs_magic == MTB_UFS_MAGIC &&
3524 	    (sblock.fs_version > MTB_UFS_VERSION_1 ||
3525 	    sblock.fs_version < MTB_UFS_VERSION_MIN)) {
3526 		(void) fprintf(stderr, gettext(
3527 		    "Unknown version of UFS format: %d\n"), sblock.fs_version);
3528 		lockexit(32);
3529 	}
3530 
3531 	/*
3532 	 * Compute a reasonable nbpi value.
3533 	 * The algorithm for "used" is copied from code
3534 	 * in main() verbatim.
3535 	 * The nbpi equation is taken from main where the
3536 	 * fs_ipg value is set for the last time.  The INOPB(...) - 1
3537 	 * is used to account for the roundup.
3538 	 * The problem is that a range of nbpi values map to
3539 	 * the same file system layout.  So it is not possible
3540 	 * to calculate the exact value specified when the file
3541 	 * system was created.  So instead we determine the top
3542 	 * end of the range of values.
3543 	 */
3544 	bpcg = sblock.fs_spc * sectorsize;
3545 	inospercg = (int64_t)roundup(bpcg / sizeof (struct dinode),
3546 	    INOPB(&sblock));
3547 	if (inospercg > MAXIpG(&sblock))
3548 		inospercg = MAXIpG(&sblock);
3549 	used = (int64_t)
3550 	    (sblock.fs_iblkno + inospercg / INOPF(&sblock)) * NSPF(&sblock);
3551 	used *= sectorsize;
3552 	nbytes64 = (uint64_t)sblock.fs_cpg * bpcg - used;
3553 
3554 	/*
3555 	 * The top end of the range of values for nbpi may not be
3556 	 * a valid command line value for mkfs. Report the bottom
3557 	 * end instead.
3558 	 */
3559 	nbpi = (int64_t)(nbytes64 / (sblock.fs_ipg));
3560 
3561 	(void) fprintf(stdout, gettext("mkfs -F ufs -o "), fsys);
3562 	(void) fprintf(stdout, "nsect=%d,ntrack=%d,",
3563 	    sblock.fs_nsect, sblock.fs_ntrak);
3564 	(void) fprintf(stdout, "bsize=%d,fragsize=%d,cgsize=%d,free=%d,",
3565 	    sblock.fs_bsize, sblock.fs_fsize, sblock.fs_cpg, sblock.fs_minfree);
3566 	(void) fprintf(stdout, "rps=%d,nbpi=%lld,opt=%c,apc=%d,gap=%d,",
3567 	    sblock.fs_rps, nbpi, (sblock.fs_optim == FS_OPTSPACE) ? 's' : 't',
3568 	    (sblock.fs_ntrak * sblock.fs_nsect) - sblock.fs_spc,
3569 	    sblock.fs_rotdelay);
3570 	(void) fprintf(stdout, "nrpos=%d,maxcontig=%d,mtb=%c ",
3571 	    sblock.fs_nrpos, sblock.fs_maxcontig,
3572 	    ((sblock.fs_magic == MTB_UFS_MAGIC) ? 'y' : 'n'));
3573 	(void) fprintf(stdout, "%s %lld\n", fsys,
3574 	    fsbtodb(&sblock, sblock.fs_size));
3575 
3576 	bzero((char *)&sblock, sizeof (sblock));
3577 }
3578 
3579 /* number ************************************************************* */
3580 /*									*/
3581 /* Convert a numeric string arg to binary				*/
3582 /*									*/
3583 /* Args:	d_value - default value, if have parse error		*/
3584 /*		param - the name of the argument, for error messages	*/
3585 /*		flags - parser state and what's allowed in the arg	*/
3586 /* Global arg:  string - pointer to command arg				*/
3587 /*									*/
3588 /* Valid forms: 123 | 123k | 123*123 | 123x123				*/
3589 /*									*/
3590 /* Return:	converted number					*/
3591 /*									*/
3592 /* ******************************************************************** */
3593 
3594 static uint64_t
3595 number(uint64_t d_value, char *param, int flags)
3596 {
3597 	char *cs;
3598 	uint64_t n, t;
3599 	uint64_t cut = BIG / 10;    /* limit to avoid overflow */
3600 	int minus = 0;
3601 
3602 	cs = string;
3603 	if (*cs == '-') {
3604 		minus = 1;
3605 		cs += 1;
3606 	}
3607 	if ((*cs < '0') || (*cs > '9')) {
3608 		goto bail_out;
3609 	}
3610 	n = 0;
3611 	while ((*cs >= '0') && (*cs <= '9') && (n <= cut)) {
3612 		n = n*10 + *cs++ - '0';
3613 	}
3614 	if (minus)
3615 		n = -n;
3616 	for (;;) {
3617 		switch (*cs++) {
3618 		case 'k':
3619 			if (flags & ALLOW_END_ONLY)
3620 				goto bail_out;
3621 			if (n > (BIG / 1024))
3622 				goto overflow;
3623 			n *= 1024;
3624 			continue;
3625 
3626 		case '*':
3627 		case 'x':
3628 			if (flags & ALLOW_END_ONLY)
3629 				goto bail_out;
3630 			string = cs;
3631 			t = number(d_value, param, flags);
3632 			if (n > (BIG / t))
3633 				goto overflow;
3634 			n *= t;
3635 			cs = string + 1; /* adjust for -- below */
3636 
3637 			/* recursion has read rest of expression */
3638 			/* FALLTHROUGH */
3639 
3640 		case ',':
3641 		case '\0':
3642 			cs--;
3643 			string = cs;
3644 			return (n);
3645 
3646 		case '%':
3647 			if (flags & ALLOW_END_ONLY)
3648 				goto bail_out;
3649 			if (flags & ALLOW_PERCENT) {
3650 				flags &= ~ALLOW_PERCENT;
3651 				flags |= ALLOW_END_ONLY;
3652 				continue;
3653 			}
3654 			goto bail_out;
3655 
3656 		case 'm':
3657 			if (flags & ALLOW_END_ONLY)
3658 				goto bail_out;
3659 			if (flags & ALLOW_MS1) {
3660 				flags &= ~ALLOW_MS1;
3661 				flags |= ALLOW_MS2;
3662 				continue;
3663 			}
3664 			goto bail_out;
3665 
3666 		case 's':
3667 			if (flags & ALLOW_END_ONLY)
3668 				goto bail_out;
3669 			if (flags & ALLOW_MS2) {
3670 				flags &= ~ALLOW_MS2;
3671 				flags |= ALLOW_END_ONLY;
3672 				continue;
3673 			}
3674 			goto bail_out;
3675 
3676 		case '0': case '1': case '2': case '3': case '4':
3677 		case '5': case '6': case '7': case '8': case '9':
3678 overflow:
3679 			(void) fprintf(stderr,
3680 			    gettext("mkfs: value for %s overflowed\n"),
3681 			    param);
3682 			while ((*cs != '\0') && (*cs != ','))
3683 				cs++;
3684 			string = cs;
3685 			return (BIG);
3686 
3687 		default:
3688 bail_out:
3689 			(void) fprintf(stderr, gettext(
3690 			    "mkfs: bad numeric arg for %s: \"%s\"\n"),
3691 			    param, string);
3692 			while ((*cs != '\0') && (*cs != ','))
3693 				cs++;
3694 			string = cs;
3695 			if (d_value != NO_DEFAULT) {
3696 				(void) fprintf(stderr,
3697 				    gettext("mkfs: %s reset to default %lld\n"),
3698 				    param, d_value);
3699 				return (d_value);
3700 			}
3701 			lockexit(2);
3702 
3703 		}
3704 	} /* never gets here */
3705 }
3706 
3707 /* match ************************************************************** */
3708 /*									*/
3709 /* Compare two text strings for equality				*/
3710 /*									*/
3711 /* Arg:	 s - pointer to string to match with a command arg		*/
3712 /* Global arg:  string - pointer to command arg				*/
3713 /*									*/
3714 /* Return:	1 if match, 0 if no match				*/
3715 /*		If match, also reset `string' to point to the text	*/
3716 /*		that follows the matching text.				*/
3717 /*									*/
3718 /* ******************************************************************** */
3719 
3720 static int
3721 match(char *s)
3722 {
3723 	char *cs;
3724 
3725 	cs = string;
3726 	while (*cs++ == *s) {
3727 		if (*s++ == '\0') {
3728 			goto true;
3729 		}
3730 	}
3731 	if (*s != '\0') {
3732 		return (0);
3733 	}
3734 
3735 true:
3736 	cs--;
3737 	string = cs;
3738 	return (1);
3739 }
3740 
3741 /*
3742  * GROWFS ROUTINES
3743  */
3744 
3745 /* ARGSUSED */
3746 void
3747 lockexit(int exitstatus)
3748 {
3749 	if (Pflag) {
3750 		/* the probe mode neither changes nor locks the filesystem */
3751 		exit(exitstatus);
3752 	}
3753 
3754 	/*
3755 	 * flush the dirty cylinder group
3756 	 */
3757 	if (inlockexit == 0) {
3758 		inlockexit = 1;
3759 		flcg();
3760 	}
3761 
3762 	if (aio_inited) {
3763 		flush_writes();
3764 	}
3765 
3766 	/*
3767 	 * make sure the file system is unlocked before exiting
3768 	 */
3769 	if ((inlockexit == 1) && (!isbad)) {
3770 		inlockexit = 2;
3771 		ulockfs();
3772 		/*
3773 		 * if logging was enabled, then re-enable it
3774 		 */
3775 		if (waslog) {
3776 			if (rl_log_control(fsys, _FIOLOGENABLE) != RL_SUCCESS) {
3777 				(void) fprintf(stderr, gettext(
3778 				    "failed to re-enable logging\n"));
3779 			}
3780 		}
3781 	} else if (grow) {
3782 		if (isbad) {
3783 			(void) fprintf(stderr, gettext(
3784 			    "Filesystem is currently inconsistent.  It "
3785 			    "must be repaired with fsck(1M)\nbefore being "
3786 			    "used.  Use the following command to "
3787 			    "do this:\n\n\tfsck %s\n\n"), fsys);
3788 
3789 			if (ismounted) {
3790 				(void) fprintf(stderr, gettext(
3791 				    "You will be told that the filesystem "
3792 				    "is already mounted, and asked if you\n"
3793 				    "wish to continue.  Answer `yes' to "
3794 				    "this question.\n\n"));
3795 			}
3796 
3797 			(void) fprintf(stderr, gettext(
3798 			    "One problem should be reported, that the summary "
3799 			    "information is bad.\nYou will then be asked if it "
3800 			    "should be salvaged.  Answer `yes' to\nthis "
3801 			    "question.\n\n"));
3802 		}
3803 
3804 		if (ismounted) {
3805 			/*
3806 			 * In theory, there's no way to get here without
3807 			 * isbad also being set, but be robust in the
3808 			 * face of future code changes.
3809 			 */
3810 			(void) fprintf(stderr, gettext(
3811 			    "The filesystem is currently mounted "
3812 			    "read-only and write-locked.  "));
3813 			if (isbad) {
3814 				(void) fprintf(stderr, gettext(
3815 				    "After\nrunning fsck, unlock the "
3816 				    "filesystem and "));
3817 			} else {
3818 				(void) fprintf(stderr, gettext(
3819 				    "Unlock the filesystem\nand "));
3820 			}
3821 
3822 			(void) fprintf(stderr, gettext(
3823 			    "re-enable writing with\nthe following "
3824 			    "command:\n\n\tlockfs -u %s\n\n"), directory);
3825 		}
3826 	}
3827 
3828 	exit(exitstatus);
3829 }
3830 
3831 void
3832 randomgeneration()
3833 {
3834 	int		 i;
3835 	struct dinode	*dp;
3836 
3837 	/*
3838 	 * always perform fsirand(1) function... newfs will notice that
3839 	 * the inodes have been randomized and will not call fsirand itself
3840 	 */
3841 	for (i = 0, dp = zino; i < sblock.fs_inopb; ++i, ++dp)
3842 		IRANDOMIZE(&dp->di_ic);
3843 }
3844 
3845 /*
3846  * Check the size of the summary information.
3847  * Fields in sblock are not changed in this function.
3848  *
3849  * For an 8K filesystem block, the maximum number of cylinder groups is 16384.
3850  *     MAXCSBUFS {32}  *   8K  {FS block size}
3851  *                         divided by (sizeof csum) {16}
3852  *
3853  * Note that MAXCSBUFS is not used in the kernel; as of Solaris 2.6 build 32,
3854  * this is the only place where it's referenced.
3855  */
3856 void
3857 checksummarysize()
3858 {
3859 	diskaddr_t	dmax;
3860 	diskaddr_t	dmin;
3861 	int64_t	cg0frags;
3862 	int64_t	cg0blocks;
3863 	int64_t	maxncg;
3864 	int64_t	maxfrags;
3865 	uint64_t	fs_size;
3866 	uint64_t maxfs_blocks; /* filesystem blocks for max filesystem size */
3867 
3868 	/*
3869 	 * compute the maximum summary info size
3870 	 */
3871 	dmin = cgdmin(&sblock, 0);
3872 	dmax = cgbase(&sblock, 0) + sblock.fs_fpg;
3873 	fs_size = (grow) ? grow_fs_size : sblock.fs_size;
3874 	if (dmax > fs_size)
3875 		dmax = fs_size;
3876 	cg0frags  = dmax - dmin;
3877 	cg0blocks = cg0frags / sblock.fs_frag;
3878 	cg0frags = cg0blocks * sblock.fs_frag;
3879 	maxncg   = (longlong_t)cg0blocks *
3880 	    (longlong_t)(sblock.fs_bsize / sizeof (struct csum));
3881 
3882 	maxfs_blocks = FS_MAX;
3883 
3884 	if (maxncg > ((longlong_t)maxfs_blocks / (longlong_t)sblock.fs_fpg) + 1)
3885 		maxncg = ((longlong_t)maxfs_blocks /
3886 		    (longlong_t)sblock.fs_fpg) + 1;
3887 
3888 	maxfrags = maxncg * (longlong_t)sblock.fs_fpg;
3889 
3890 	if (maxfrags > maxfs_blocks)
3891 		maxfrags = maxfs_blocks;
3892 
3893 
3894 	/*
3895 	 * remember for later processing in extendsummaryinfo()
3896 	 */
3897 	if (test)
3898 		grow_sifrag = dmin + (cg0blocks * sblock.fs_frag);
3899 	if (testfrags == 0)
3900 		testfrags = cg0frags;
3901 	if (testforce)
3902 		if (testfrags > cg0frags) {
3903 			(void) fprintf(stderr,
3904 			    gettext("Too many test frags (%lld); "
3905 			    "try %lld\n"), testfrags, cg0frags);
3906 			lockexit(32);
3907 		}
3908 
3909 	/*
3910 	 * if summary info is too large (too many cg's) tell the user and exit
3911 	 */
3912 	if ((longlong_t)sblock.fs_size > maxfrags) {
3913 		(void) fprintf(stderr, gettext(
3914 		    "Too many cylinder groups with %llu sectors;\n    try "
3915 		    "increasing cgsize, or decreasing fssize to %llu\n"),
3916 		    fsbtodb(&sblock, (uint64_t)sblock.fs_size),
3917 		    fsbtodb(&sblock, (uint64_t)maxfrags));
3918 		lockexit(32);
3919 	}
3920 }
3921 
3922 /*
3923  * checksblock() has two uses:
3924  *	- One is to sanity test the superblock and is used when newfs(1M)
3925  *	  is invoked with the "-N" option. If any discrepancy was found,
3926  *	  just return whatever error was found and do not exit.
3927  *	- the other use of it is in places where you expect the superblock
3928  *	  to be sane, and if it isn't, then we exit.
3929  * Which of the above two actions to take is indicated with the second argument.
3930  */
3931 
3932 int
3933 checksblock(struct fs sb, int proceed)
3934 {
3935 	int err = 0;
3936 	char *errmsg;
3937 
3938 	if ((sb.fs_magic != FS_MAGIC) && (sb.fs_magic != MTB_UFS_MAGIC)) {
3939 		err = 1;
3940 		errmsg = gettext("Bad superblock; magic number wrong\n");
3941 	} else if ((sb.fs_magic == FS_MAGIC &&
3942 	    (sb.fs_version != UFS_EFISTYLE4NONEFI_VERSION_2 &&
3943 	    sb.fs_version != UFS_VERSION_MIN)) ||
3944 	    (sb.fs_magic == MTB_UFS_MAGIC &&
3945 	    (sb.fs_version > MTB_UFS_VERSION_1 ||
3946 	    sb.fs_version < MTB_UFS_VERSION_MIN))) {
3947 		err = 2;
3948 		errmsg = gettext("Unrecognized version of UFS\n");
3949 	} else if (sb.fs_ncg < 1) {
3950 		err = 3;
3951 		errmsg = gettext("Bad superblock; ncg out of range\n");
3952 	} else if (sb.fs_cpg < 1) {
3953 		err = 4;
3954 		errmsg = gettext("Bad superblock; cpg out of range\n");
3955 	} else if (sb.fs_ncg * sb.fs_cpg < sb.fs_ncyl ||
3956 	    (sb.fs_ncg - 1) * sb.fs_cpg >= sb.fs_ncyl) {
3957 		err = 5;
3958 		errmsg = gettext("Bad superblock; ncyl out of range\n");
3959 	} else if (sb.fs_sbsize <= 0 || sb.fs_sbsize > sb.fs_bsize) {
3960 		err = 6;
3961 		errmsg = gettext("Bad superblock; superblock size out of "
3962 		    "range\n");
3963 	}
3964 
3965 	if (proceed) {
3966 		if (err) dprintf(("%s", errmsg));
3967 		return (err);
3968 	}
3969 
3970 	if (err) {
3971 		fprintf(stderr, "%s", errmsg);
3972 		lockexit(32);
3973 	}
3974 	return (32);
3975 }
3976 
3977 /*
3978  * Roll the embedded log, if any, and set up the global variables
3979  * islog, islogok and isufslog.
3980  */
3981 static void
3982 logsetup(char *devstr)
3983 {
3984 	void		*buf, *ud_buf;
3985 	extent_block_t	*ebp;
3986 	ml_unit_t	*ul;
3987 	ml_odunit_t	*ud;
3988 
3989 	/*
3990 	 * Does the superblock indicate that we are supposed to have a log ?
3991 	 */
3992 	if (sblock.fs_logbno == 0) {
3993 		/*
3994 		 * No log present, nothing to do.
3995 		 */
3996 		islogok = 0;
3997 		islog = 0;
3998 		isufslog = 0;
3999 		return;
4000 	} else {
4001 		/*
4002 		 * There's a log in a yet unknown state, attempt to roll it.
4003 		 */
4004 		islog = 1;
4005 		islogok = 0;
4006 		isufslog = 0;
4007 
4008 		/*
4009 		 * We failed to roll the log, bail out.
4010 		 */
4011 		if (rl_roll_log(devstr) != RL_SUCCESS)
4012 			return;
4013 
4014 		isufslog = 1;
4015 
4016 		/* log is not okay; check the fs */
4017 		if ((FSOKAY != (sblock.fs_state + sblock.fs_time)) ||
4018 		    (sblock.fs_clean != FSLOG))
4019 			return;
4020 
4021 		/* get the log allocation block */
4022 		buf = (void *)malloc(DEV_BSIZE);
4023 		if (buf == (void *) NULL)
4024 			return;
4025 
4026 		ud_buf = (void *)malloc(DEV_BSIZE);
4027 		if (ud_buf == (void *) NULL) {
4028 			free(buf);
4029 			return;
4030 		}
4031 
4032 		rdfs((diskaddr_t)logbtodb(&sblock, sblock.fs_logbno),
4033 		    DEV_BSIZE, buf);
4034 		ebp = (extent_block_t *)buf;
4035 
4036 		/* log allocation block is not okay; check the fs */
4037 		if (ebp->type != LUFS_EXTENTS) {
4038 			free(buf);
4039 			free(ud_buf);
4040 			return;
4041 		}
4042 
4043 		/* get the log state block(s) */
4044 		rdfs((diskaddr_t)logbtodb(&sblock, ebp->extents[0].pbno),
4045 		    DEV_BSIZE, ud_buf);
4046 		ud = (ml_odunit_t *)ud_buf;
4047 		ul = (ml_unit_t *)malloc(sizeof (*ul));
4048 		ul->un_ondisk = *ud;
4049 
4050 		/* log state is okay */
4051 		if ((ul->un_chksum == ul->un_head_ident + ul->un_tail_ident) &&
4052 		    (ul->un_version == LUFS_VERSION_LATEST) &&
4053 		    (ul->un_badlog == 0))
4054 			islogok = 1;
4055 		free(ud_buf);
4056 		free(buf);
4057 		free(ul);
4058 	}
4059 }
4060 
4061 void
4062 growinit(char *devstr)
4063 {
4064 	int	i;
4065 	char	buf[DEV_BSIZE];
4066 
4067 	/*
4068 	 * Read and verify the superblock
4069 	 */
4070 	rdfs((diskaddr_t)(SBOFF / sectorsize), (int)sbsize, (char *)&sblock);
4071 	(void) checksblock(sblock, 0);
4072 	if (sblock.fs_postblformat != FS_DYNAMICPOSTBLFMT) {
4073 		(void) fprintf(stderr,
4074 		    gettext("old file system format; can't growfs\n"));
4075 		lockexit(32);
4076 	}
4077 
4078 	/*
4079 	 * can't shrink a file system
4080 	 */
4081 	grow_fssize = fsbtodb(&sblock, (uint64_t)sblock.fs_size);
4082 	if (fssize_db < grow_fssize) {
4083 		(void) fprintf(stderr,
4084 		    gettext("%lld sectors < current size of %lld sectors\n"),
4085 		    fssize_db, grow_fssize);
4086 		lockexit(32);
4087 	}
4088 
4089 	/*
4090 	 * can't grow a system to over a terabyte unless it was set up
4091 	 * as an MTB UFS file system.
4092 	 */
4093 	if (mtb == 'y' && sblock.fs_magic != MTB_UFS_MAGIC) {
4094 		if (fssize_db >= SECTORS_PER_TERABYTE) {
4095 			(void) fprintf(stderr, gettext(
4096 "File system was not set up with the multi-terabyte format.\n"));
4097 			(void) fprintf(stderr, gettext(
4098 "Its size cannot be increased to a terabyte or more.\n"));
4099 		} else {
4100 			(void) fprintf(stderr, gettext(
4101 "Cannot convert file system to multi-terabyte format.\n"));
4102 		}
4103 		lockexit(32);
4104 	}
4105 
4106 	logsetup(devstr);
4107 
4108 	/*
4109 	 * can't growfs when logging device has errors
4110 	 */
4111 	if ((islog && !islogok) ||
4112 	    ((FSOKAY == (sblock.fs_state + sblock.fs_time)) &&
4113 	    (sblock.fs_clean == FSLOG && !islog))) {
4114 		(void) fprintf(stderr,
4115 		    gettext("logging device has errors; can't growfs\n"));
4116 		lockexit(32);
4117 	}
4118 
4119 	/*
4120 	 * disable ufs logging for growing
4121 	 */
4122 	if (isufslog) {
4123 		if (rl_log_control(devstr, _FIOLOGDISABLE) != RL_SUCCESS) {
4124 			(void) fprintf(stderr, gettext(
4125 			    "failed to disable logging\n"));
4126 			lockexit(32);
4127 		}
4128 		islog = 0;
4129 		waslog = 1;
4130 	}
4131 
4132 	/*
4133 	 * if mounted write lock the file system to be grown
4134 	 */
4135 	if (ismounted)
4136 		wlockfs();
4137 
4138 	/*
4139 	 * refresh dynamic superblock state - disabling logging will have
4140 	 * changed the amount of free space available in the file system
4141 	 */
4142 	rdfs((diskaddr_t)(SBOFF / sectorsize), sbsize, (char *)&sblock);
4143 
4144 	/*
4145 	 * make sure device is big enough
4146 	 */
4147 	rdfs((diskaddr_t)fssize_db - 1, DEV_BSIZE, buf);
4148 	wtfs((diskaddr_t)fssize_db - 1, DEV_BSIZE, buf);
4149 
4150 	/*
4151 	 * read current summary information
4152 	 */
4153 	grow_fscs = read_summaryinfo(&sblock);
4154 
4155 	/*
4156 	 * save some current size related fields from the superblock
4157 	 * These are used in extendsummaryinfo()
4158 	 */
4159 	grow_fs_size	= sblock.fs_size;
4160 	grow_fs_ncg	= sblock.fs_ncg;
4161 	grow_fs_csaddr	= (diskaddr_t)sblock.fs_csaddr;
4162 	grow_fs_cssize	= sblock.fs_cssize;
4163 
4164 	/*
4165 	 * save and reset the clean flag
4166 	 */
4167 	if (FSOKAY == (sblock.fs_state + sblock.fs_time))
4168 		grow_fs_clean = sblock.fs_clean;
4169 	else
4170 		grow_fs_clean = FSBAD;
4171 	sblock.fs_clean = FSBAD;
4172 	sblock.fs_state = FSOKAY - sblock.fs_time;
4173 	isbad = 1;
4174 	wtfs((diskaddr_t)(SBOFF / sectorsize), sbsize, (char *)&sblock);
4175 }
4176 
4177 void
4178 checkdev(char *rdev, char *bdev)
4179 {
4180 	struct stat64	statarea;
4181 
4182 	if (stat64(bdev, &statarea) < 0) {
4183 		(void) fprintf(stderr, gettext("can't check mount point; "));
4184 		(void) fprintf(stderr, gettext("can't stat %s\n"), bdev);
4185 		lockexit(32);
4186 	}
4187 	if ((statarea.st_mode & S_IFMT) != S_IFBLK) {
4188 		(void) fprintf(stderr, gettext(
4189 		    "can't check mount point; %s is not a block device\n"),
4190 		    bdev);
4191 		lockexit(32);
4192 	}
4193 	if (stat64(rdev, &statarea) < 0) {
4194 		(void) fprintf(stderr, gettext("can't stat %s\n"), rdev);
4195 		lockexit(32);
4196 	}
4197 	if ((statarea.st_mode & S_IFMT) != S_IFCHR) {
4198 		(void) fprintf(stderr,
4199 		    gettext("%s is not a character device\n"), rdev);
4200 		lockexit(32);
4201 	}
4202 }
4203 
4204 void
4205 checkmount(struct mnttab *mntp, char *bdevname)
4206 {
4207 	struct stat64	statdir;
4208 	struct stat64	statdev;
4209 
4210 	if (strcmp(bdevname, mntp->mnt_special) == 0) {
4211 		if (stat64(mntp->mnt_mountp, &statdir) == -1) {
4212 			(void) fprintf(stderr, gettext("can't stat %s\n"),
4213 			    mntp->mnt_mountp);
4214 			lockexit(32);
4215 		}
4216 		if (stat64(mntp->mnt_special, &statdev) == -1) {
4217 			(void) fprintf(stderr, gettext("can't stat %s\n"),
4218 			    mntp->mnt_special);
4219 			lockexit(32);
4220 		}
4221 		if (statdir.st_dev != statdev.st_rdev) {
4222 			(void) fprintf(stderr, gettext(
4223 			    "%s is not mounted on %s; mnttab(4) wrong\n"),
4224 			    mntp->mnt_special, mntp->mnt_mountp);
4225 			lockexit(32);
4226 		}
4227 		ismounted = 1;
4228 		if (directory) {
4229 			if (strcmp(mntp->mnt_mountp, directory) != 0) {
4230 				(void) fprintf(stderr,
4231 				    gettext("%s is mounted on %s, not %s\n"),
4232 				    bdevname, mntp->mnt_mountp, directory);
4233 				lockexit(32);
4234 			}
4235 		} else {
4236 			if (grow)
4237 				(void) fprintf(stderr, gettext(
4238 				    "%s is mounted on %s; can't growfs\n"),
4239 				    bdevname, mntp->mnt_mountp);
4240 			else
4241 				(void) fprintf(stderr,
4242 				    gettext("%s is mounted, can't mkfs\n"),
4243 				    bdevname);
4244 			lockexit(32);
4245 		}
4246 	}
4247 }
4248 
4249 struct dinode	*dibuf	= 0;
4250 diskaddr_t	difrag	= 0;
4251 
4252 struct dinode *
4253 gdinode(ino_t ino)
4254 {
4255 	/*
4256 	 * read the block of inodes containing inode number ino
4257 	 */
4258 	if (dibuf == 0)
4259 		dibuf = (struct dinode *)malloc((unsigned)sblock.fs_bsize);
4260 	if (itod(&sblock, ino) != difrag) {
4261 		difrag = itod(&sblock, ino);
4262 		rdfs(fsbtodb(&sblock, (uint64_t)difrag), (int)sblock.fs_bsize,
4263 		    (char *)dibuf);
4264 	}
4265 	return (dibuf + (ino % INOPB(&sblock)));
4266 }
4267 
4268 /*
4269  * structure that manages the frags we need for extended summary info
4270  *	These frags can be:
4271  *		free
4272  *		data  block
4273  *		alloc block
4274  */
4275 struct csfrag {
4276 	struct csfrag	*next;		/* next entry */
4277 	daddr32_t	 ofrag;		/* old frag */
4278 	daddr32_t	 nfrag;		/* new frag */
4279 	long		 cylno;		/* cylno of nfrag */
4280 	long		 frags;		/* number of frags */
4281 	long		 size;		/* size in bytes */
4282 	ino_t		 ino;		/* inode number */
4283 	long		 fixed;		/* Boolean - Already fixed? */
4284 };
4285 struct csfrag	*csfrag;		/* state unknown */
4286 struct csfrag	*csfragino;		/* frags belonging to an inode */
4287 struct csfrag	*csfragfree;		/* frags that are free */
4288 
4289 daddr32_t maxcsfrag	= 0;		/* maximum in range */
4290 daddr32_t mincsfrag	= 0x7fffffff;	/* minimum in range */
4291 
4292 int
4293 csfraginrange(daddr32_t frag)
4294 {
4295 	return ((frag >= mincsfrag) && (frag <= maxcsfrag));
4296 }
4297 
4298 struct csfrag *
4299 findcsfrag(daddr32_t frag, struct csfrag **cfap)
4300 {
4301 	struct csfrag	*cfp;
4302 
4303 	if (!csfraginrange(frag))
4304 		return (NULL);
4305 
4306 	for (cfp = *cfap; cfp; cfp = cfp->next)
4307 		if (cfp->ofrag == frag)
4308 			return (cfp);
4309 	return (NULL);
4310 }
4311 
4312 void
4313 checkindirect(ino_t ino, daddr32_t *fragsp, daddr32_t frag, int level)
4314 {
4315 	int			i;
4316 	int			ne	= sblock.fs_bsize / sizeof (daddr32_t);
4317 	daddr32_t			fsb[MAXBSIZE / sizeof (daddr32_t)];
4318 
4319 	if (frag == 0)
4320 		return;
4321 
4322 	rdfs(fsbtodb(&sblock, frag), (int)sblock.fs_bsize,
4323 	    (char *)fsb);
4324 
4325 	checkdirect(ino, fragsp, fsb, sblock.fs_bsize / sizeof (daddr32_t));
4326 
4327 	if (level)
4328 		for (i = 0; i < ne && *fragsp; ++i)
4329 			checkindirect(ino, fragsp, fsb[i], level-1);
4330 }
4331 
4332 void
4333 addcsfrag(ino_t ino, daddr32_t frag, struct csfrag **cfap)
4334 {
4335 	struct csfrag	*cfp, *curr, *prev;
4336 
4337 	/*
4338 	 * establish a range for faster checking in csfraginrange()
4339 	 */
4340 	if (frag > maxcsfrag)
4341 		maxcsfrag = frag;
4342 	if (frag < mincsfrag)
4343 		mincsfrag = frag;
4344 
4345 	/*
4346 	 * if this frag belongs to an inode and is not the start of a block
4347 	 *	then see if it is part of a frag range for this inode
4348 	 */
4349 	if (ino && (frag % sblock.fs_frag))
4350 		for (cfp = *cfap; cfp; cfp = cfp->next) {
4351 			if (ino != cfp->ino)
4352 				continue;
4353 			if (frag != cfp->ofrag + cfp->frags)
4354 				continue;
4355 			cfp->frags++;
4356 			cfp->size += sblock.fs_fsize;
4357 			return;
4358 		}
4359 	/*
4360 	 * allocate a csfrag entry and insert it in an increasing order into the
4361 	 * specified list
4362 	 */
4363 	cfp = (struct csfrag *)calloc(1, sizeof (struct csfrag));
4364 	cfp->ino	= ino;
4365 	cfp->ofrag	= frag;
4366 	cfp->frags	= 1;
4367 	cfp->size	= sblock.fs_fsize;
4368 	for (prev = NULL, curr = *cfap; curr != NULL;
4369 	    prev = curr, curr = curr->next) {
4370 		if (frag < curr->ofrag) {
4371 			cfp->next = curr;
4372 			if (prev)
4373 				prev->next = cfp;	/* middle element */
4374 			else
4375 				*cfap = cfp;		/* first element */
4376 			break;
4377 		}
4378 		if (curr->next == NULL) {
4379 			curr->next = cfp;		/* last element	*/
4380 			break;
4381 		}
4382 	}
4383 	if (*cfap == NULL)	/* will happen only once */
4384 		*cfap = cfp;
4385 }
4386 
4387 void
4388 delcsfrag(daddr32_t frag, struct csfrag **cfap)
4389 {
4390 	struct csfrag	*cfp;
4391 	struct csfrag	**cfpp;
4392 
4393 	/*
4394 	 * free up entry whose beginning frag matches
4395 	 */
4396 	for (cfpp = cfap; *cfpp; cfpp = &(*cfpp)->next) {
4397 		if (frag == (*cfpp)->ofrag) {
4398 			cfp = *cfpp;
4399 			*cfpp = (*cfpp)->next;
4400 			free((char *)cfp);
4401 			return;
4402 		}
4403 	}
4404 }
4405 
4406 /*
4407  * See whether any of the direct blocks in the array pointed by "db" and of
4408  * length "ne" are within the range of frags needed to extend the cylinder
4409  * summary. If so, remove those frags from the "as-yet-unclassified" list
4410  * (csfrag) and add them to the "owned-by-inode" list (csfragino).
4411  * For each such frag found, decrement the frag count pointed to by fragsp.
4412  * "ino" is the inode that contains (either directly or indirectly) the frags
4413  * being checked.
4414  */
4415 void
4416 checkdirect(ino_t ino, daddr32_t *fragsp, daddr32_t *db, int ne)
4417 {
4418 	int	 i;
4419 	int	 j;
4420 	int	 found;
4421 	diskaddr_t	 frag;
4422 
4423 	/*
4424 	 * scan for allocation within the new summary info range
4425 	 */
4426 	for (i = 0; i < ne && *fragsp; ++i) {
4427 		if ((frag = *db++) != 0) {
4428 			found = 0;
4429 			for (j = 0; j < sblock.fs_frag && *fragsp; ++j) {
4430 				if (found || (found = csfraginrange(frag))) {
4431 					addcsfrag(ino, frag, &csfragino);
4432 					delcsfrag(frag, &csfrag);
4433 				}
4434 				++frag;
4435 				--(*fragsp);
4436 			}
4437 		}
4438 	}
4439 }
4440 
4441 void
4442 findcsfragino()
4443 {
4444 	int		 i;
4445 	int		 j;
4446 	daddr32_t		 frags;
4447 	struct dinode	*dp;
4448 
4449 	/*
4450 	 * scan all old inodes looking for allocations in the new
4451 	 * summary info range.  Move the affected frag from the
4452 	 * generic csfrag list onto the `owned-by-inode' list csfragino.
4453 	 */
4454 	for (i = UFSROOTINO; i < grow_fs_ncg*sblock.fs_ipg && csfrag; ++i) {
4455 		dp = gdinode((ino_t)i);
4456 		switch (dp->di_mode & IFMT) {
4457 			case IFSHAD	:
4458 			case IFLNK 	:
4459 			case IFDIR 	:
4460 			case IFREG 	: break;
4461 			default		: continue;
4462 		}
4463 
4464 		frags   = dbtofsb(&sblock, dp->di_blocks);
4465 
4466 		checkdirect((ino_t)i, &frags, &dp->di_db[0], NDADDR+NIADDR);
4467 		for (j = 0; j < NIADDR && frags; ++j) {
4468 			/* Negate the block if its an fallocate'd block */
4469 			if (dp->di_ib[j] < 0 && dp->di_ib[j] != UFS_HOLE)
4470 				checkindirect((ino_t)i, &frags,
4471 				    -(dp->di_ib[j]), j);
4472 			else
4473 				checkindirect((ino_t)i, &frags,
4474 				    dp->di_ib[j], j);
4475 		}
4476 	}
4477 }
4478 
4479 void
4480 fixindirect(daddr32_t frag, int level)
4481 {
4482 	int			 i;
4483 	int			 ne	= sblock.fs_bsize / sizeof (daddr32_t);
4484 	daddr32_t			fsb[MAXBSIZE / sizeof (daddr32_t)];
4485 
4486 	if (frag == 0)
4487 		return;
4488 
4489 	rdfs(fsbtodb(&sblock, (uint64_t)frag), (int)sblock.fs_bsize,
4490 	    (char *)fsb);
4491 
4492 	fixdirect((caddr_t)fsb, frag, fsb, ne);
4493 
4494 	if (level)
4495 		for (i = 0; i < ne; ++i)
4496 			fixindirect(fsb[i], level-1);
4497 }
4498 
4499 void
4500 fixdirect(caddr_t bp, daddr32_t frag, daddr32_t *db, int ne)
4501 {
4502 	int	 i;
4503 	struct csfrag	*cfp;
4504 
4505 	for (i = 0; i < ne; ++i, ++db) {
4506 		if (*db == 0)
4507 			continue;
4508 		if ((cfp = findcsfrag(*db, &csfragino)) == NULL)
4509 			continue;
4510 		*db = cfp->nfrag;
4511 		cfp->fixed = 1;
4512 		wtfs(fsbtodb(&sblock, (uint64_t)frag), (int)sblock.fs_bsize,
4513 		    bp);
4514 	}
4515 }
4516 
4517 void
4518 fixcsfragino()
4519 {
4520 	int		 i;
4521 	struct dinode	*dp;
4522 	struct csfrag	*cfp;
4523 
4524 	for (cfp = csfragino; cfp; cfp = cfp->next) {
4525 		if (cfp->fixed)
4526 			continue;
4527 		dp = gdinode((ino_t)cfp->ino);
4528 		fixdirect((caddr_t)dibuf, difrag, dp->di_db, NDADDR+NIADDR);
4529 		for (i = 0; i < NIADDR; ++i)
4530 			fixindirect(dp->di_ib[i], i);
4531 	}
4532 }
4533 
4534 /*
4535  * Read the cylinders summary information specified by settings in the
4536  * passed 'fs' structure into a new allocated array of csum structures.
4537  * The caller is responsible for freeing the returned array.
4538  * Return a pointer to an array of csum structures.
4539  */
4540 static struct csum *
4541 read_summaryinfo(struct	fs *fsp)
4542 {
4543 	struct csum 	*csp;
4544 	int		i;
4545 
4546 	if ((csp = malloc((size_t)fsp->fs_cssize)) == NULL) {
4547 		(void) fprintf(stderr, gettext("cannot create csum list,"
4548 		    " not enough memory\n"));
4549 		exit(32);
4550 	}
4551 
4552 	for (i = 0; i < fsp->fs_cssize; i += fsp->fs_bsize) {
4553 		rdfs(fsbtodb(fsp,
4554 		    (uint64_t)(fsp->fs_csaddr + numfrags(fsp, i))),
4555 		    (int)(fsp->fs_cssize - i < fsp->fs_bsize ?
4556 		    fsp->fs_cssize - i : fsp->fs_bsize), ((caddr_t)csp) + i);
4557 	}
4558 
4559 	return (csp);
4560 }
4561 
4562 /*
4563  * Check the allocation of fragments that are to be made part of a csum block.
4564  * A fragment is allocated if it is either in the csfragfree list or, it is
4565  * in the csfragino list and has new frags associated with it.
4566  * Return the number of allocated fragments.
4567  */
4568 int64_t
4569 checkfragallocated(daddr32_t frag)
4570 {
4571 	struct 	csfrag	*cfp;
4572 	/*
4573 	 * Since the lists are sorted we can break the search if the asked
4574 	 * frag is smaller then the one in the list.
4575 	 */
4576 	for (cfp = csfragfree; cfp != NULL && frag >= cfp->ofrag;
4577 	    cfp = cfp->next) {
4578 		if (frag == cfp->ofrag)
4579 			return (1);
4580 	}
4581 	for (cfp = csfragino; cfp != NULL && frag >= cfp->ofrag;
4582 	    cfp = cfp->next) {
4583 		if (frag == cfp->ofrag && cfp->nfrag != 0)
4584 			return (cfp->frags);
4585 	}
4586 
4587 	return (0);
4588 }
4589 
4590 /*
4591  * Figure out how much the filesystem can be grown. The limiting factor is
4592  * the available free space needed to extend the cg summary info block.
4593  * The free space is determined in three steps:
4594  * - Try to extend the cg summary block to the required size.
4595  * - Find free blocks in last cg.
4596  * - Find free space in the last already allocated fragment of the summary info
4597  *   block, and use it for additional csum structures.
4598  * Return the maximum size of the new filesystem or 0 if it can't be grown.
4599  * Please note that this function leaves the global list pointers csfrag,
4600  * csfragfree, and csfragino initialized, and the caller is responsible for
4601  * freeing the lists.
4602  */
4603 diskaddr_t
4604 probe_summaryinfo()
4605 {
4606 	/* fragments by which the csum block can be extended. */
4607 	int64_t 	growth_csum_frags = 0;
4608 	/* fragments by which the filesystem can be extended. */
4609 	int64_t		growth_fs_frags = 0;
4610 	int64_t		new_fs_cssize;	/* size of csum blk in the new FS */
4611 	int64_t		new_fs_ncg;	/* number of cg in the new FS */
4612 	int64_t 	spare_csum;
4613 	daddr32_t	oldfrag_daddr;
4614 	daddr32_t	newfrag_daddr;
4615 	daddr32_t	daddr;
4616 	int		i;
4617 
4618 	/*
4619 	 * read and verify the superblock
4620 	 */
4621 	rdfs((diskaddr_t)(SBOFF / sectorsize), (int)sbsize, (char *)&sblock);
4622 	(void) checksblock(sblock, 0);
4623 
4624 	/*
4625 	 * check how much we can extend the cg summary info block
4626 	 */
4627 
4628 	/*
4629 	 * read current summary information
4630 	 */
4631 	fscs = read_summaryinfo(&sblock);
4632 
4633 	/*
4634 	 * build list of frags needed for cg summary info block extension
4635 	 */
4636 	oldfrag_daddr = howmany(sblock.fs_cssize, sblock.fs_fsize) +
4637 	    sblock.fs_csaddr;
4638 	new_fs_ncg = howmany(dbtofsb(&sblock, fssize_db), sblock.fs_fpg);
4639 	new_fs_cssize = fragroundup(&sblock, new_fs_ncg * sizeof (struct csum));
4640 	newfrag_daddr = howmany(new_fs_cssize, sblock.fs_fsize) +
4641 	    sblock.fs_csaddr;
4642 	/*
4643 	 * add all of the frags that are required to grow the cyl summary to the
4644 	 * csfrag list, which is the generic/unknown list, since at this point
4645 	 * we don't yet know the state of those frags.
4646 	 */
4647 	for (daddr = oldfrag_daddr; daddr < newfrag_daddr; daddr++)
4648 		addcsfrag((ino_t)0, daddr, &csfrag);
4649 
4650 	/*
4651 	 * filter free fragments and allocate them. Note that the free frags
4652 	 * must be allocated first otherwise they could be grabbed by
4653 	 * alloccsfragino() for data frags.
4654 	 */
4655 	findcsfragfree();
4656 	alloccsfragfree();
4657 
4658 	/*
4659 	 * filter fragments owned by inodes and allocate them
4660 	 */
4661 	grow_fs_ncg = sblock.fs_ncg; /* findcsfragino() needs this glob. var. */
4662 	findcsfragino();
4663 	alloccsfragino();
4664 
4665 	if (notenoughspace()) {
4666 		/*
4667 		 * check how many consecutive fragments could be allocated
4668 		 * in both lists.
4669 		 */
4670 		int64_t tmp_frags;
4671 		for (daddr = oldfrag_daddr; daddr < newfrag_daddr;
4672 		    daddr += tmp_frags) {
4673 			if ((tmp_frags = checkfragallocated(daddr)) > 0)
4674 				growth_csum_frags += tmp_frags;
4675 			else
4676 				break;
4677 		}
4678 	} else {
4679 		/*
4680 		 * We have all we need for the new desired size,
4681 		 * so clean up and report back.
4682 		 */
4683 		return (fssize_db);
4684 	}
4685 
4686 	/*
4687 	 * given the number of fragments by which the csum block can be grown
4688 	 * compute by how many new fragments the FS can be increased.
4689 	 * It is the number of csum instances per fragment multiplied by
4690 	 * `growth_csum_frags' and the number of fragments per cylinder group.
4691 	 */
4692 	growth_fs_frags = howmany(sblock.fs_fsize, sizeof (struct csum)) *
4693 	    growth_csum_frags * sblock.fs_fpg;
4694 
4695 	/*
4696 	 * compute free fragments in the last cylinder group
4697 	 */
4698 	rdcg(sblock.fs_ncg - 1);
4699 	growth_fs_frags += sblock.fs_fpg - acg.cg_ndblk;
4700 
4701 	/*
4702 	 * compute how many csum instances are unused in the old csum block.
4703 	 * For each unused csum instance the FS can be grown by one cylinder
4704 	 * group without extending the csum block.
4705 	 */
4706 	spare_csum = howmany(sblock.fs_cssize, sizeof (struct csum)) -
4707 	    sblock.fs_ncg;
4708 	if (spare_csum > 0)
4709 		growth_fs_frags += spare_csum * sblock.fs_fpg;
4710 
4711 	/*
4712 	 * recalculate the new filesystem size in sectors, shorten it by
4713 	 * the requested size `fssize_db' if necessary.
4714 	 */
4715 	if (growth_fs_frags > 0) {
4716 		diskaddr_t sect;
4717 		sect = (sblock.fs_size + growth_fs_frags) * sblock.fs_nspf;
4718 		return ((sect > fssize_db) ? fssize_db : sect);
4719 	}
4720 
4721 	return (0);
4722 }
4723 
4724 void
4725 extendsummaryinfo()
4726 {
4727 	int64_t		i;
4728 	int		localtest	= test;
4729 	int64_t		frags;
4730 	daddr32_t		oldfrag;
4731 	daddr32_t		newfrag;
4732 
4733 	/*
4734 	 * if no-write (-N), don't bother
4735 	 */
4736 	if (Nflag)
4737 		return;
4738 
4739 again:
4740 	flcg();
4741 	/*
4742 	 * summary info did not change size -- do nothing unless in test mode
4743 	 */
4744 	if (grow_fs_cssize == sblock.fs_cssize)
4745 		if (!localtest)
4746 			return;
4747 
4748 	/*
4749 	 * build list of frags needed for additional summary information
4750 	 */
4751 	oldfrag = howmany(grow_fs_cssize, sblock.fs_fsize) + grow_fs_csaddr;
4752 	newfrag = howmany(sblock.fs_cssize, sblock.fs_fsize) + grow_fs_csaddr;
4753 	/*
4754 	 * add all of the frags that are required to grow the cyl summary to the
4755 	 * csfrag list, which is the generic/unknown list, since at this point
4756 	 * we don't yet know the state of those frags.
4757 	 */
4758 	for (i = oldfrag, frags = 0; i < newfrag; ++i, ++frags)
4759 		addcsfrag((ino_t)0, (diskaddr_t)i, &csfrag);
4760 	/*
4761 	 * reduce the number of data blocks in the file system (fs_dsize) by
4762 	 * the number of frags that need to be added to the cyl summary
4763 	 */
4764 	sblock.fs_dsize -= (newfrag - oldfrag);
4765 
4766 	/*
4767 	 * In test mode, we move more data than necessary from
4768 	 * cylinder group 0.  The lookup/allocate/move code can be
4769 	 * better stressed without having to create HUGE file systems.
4770 	 */
4771 	if (localtest)
4772 		for (i = newfrag; i < grow_sifrag; ++i) {
4773 			if (frags >= testfrags)
4774 				break;
4775 			frags++;
4776 			addcsfrag((ino_t)0, (diskaddr_t)i, &csfrag);
4777 		}
4778 
4779 	/*
4780 	 * move frags to free or inode lists, depending on owner
4781 	 */
4782 	findcsfragfree();
4783 	findcsfragino();
4784 
4785 	/*
4786 	 * if not all frags can be located, file system must be inconsistent
4787 	 */
4788 	if (csfrag) {
4789 		isbad = 1;	/* should already be set, but make sure */
4790 		lockexit(32);
4791 	}
4792 
4793 	/*
4794 	 * allocate the free frags. Note that the free frags must be allocated
4795 	 * first otherwise they could be grabbed by alloccsfragino() for data
4796 	 * frags.
4797 	 */
4798 	alloccsfragfree();
4799 	/*
4800 	 * allocate extra space for inode frags
4801 	 */
4802 	alloccsfragino();
4803 
4804 	/*
4805 	 * not enough space
4806 	 */
4807 	if (notenoughspace()) {
4808 		unalloccsfragfree();
4809 		unalloccsfragino();
4810 		if (localtest && !testforce) {
4811 			localtest = 0;
4812 			goto again;
4813 		}
4814 		(void) fprintf(stderr, gettext("Not enough free space\n"));
4815 		lockexit(NOTENOUGHSPACE);
4816 	}
4817 
4818 	/*
4819 	 * copy the data from old frags to new frags
4820 	 */
4821 	copycsfragino();
4822 
4823 	/*
4824 	 * fix the inodes to point to the new frags
4825 	 */
4826 	fixcsfragino();
4827 
4828 	/*
4829 	 * We may have moved more frags than we needed.  Free them.
4830 	 */
4831 	rdcg((long)0);
4832 	for (i = newfrag; i <= maxcsfrag; ++i)
4833 		setbit(cg_blksfree(&acg), i-cgbase(&sblock, 0));
4834 	wtcg();
4835 
4836 	flcg();
4837 }
4838 
4839 /*
4840  * Check if all fragments in the `csfragino' list were reallocated.
4841  */
4842 int
4843 notenoughspace()
4844 {
4845 	struct csfrag	*cfp;
4846 
4847 	/*
4848 	 * If any element in the csfragino array has a "new frag location"
4849 	 * of 0, the allocfrags() function was unsuccessful in allocating
4850 	 * space for moving the frag represented by this array element.
4851 	 */
4852 	for (cfp = csfragino; cfp; cfp = cfp->next)
4853 		if (cfp->nfrag == 0)
4854 			return (1);
4855 	return (0);
4856 }
4857 
4858 void
4859 unalloccsfragino()
4860 {
4861 	struct csfrag	*cfp;
4862 
4863 	while ((cfp = csfragino) != NULL) {
4864 		if (cfp->nfrag)
4865 			freefrags(cfp->nfrag, cfp->frags, cfp->cylno);
4866 		delcsfrag(cfp->ofrag, &csfragino);
4867 	}
4868 }
4869 
4870 void
4871 unalloccsfragfree()
4872 {
4873 	struct csfrag	*cfp;
4874 
4875 	while ((cfp = csfragfree) != NULL) {
4876 		freefrags(cfp->ofrag, cfp->frags, cfp->cylno);
4877 		delcsfrag(cfp->ofrag, &csfragfree);
4878 	}
4879 }
4880 
4881 /*
4882  * For each frag in the "as-yet-unclassified" list (csfrag), see if
4883  * it's free (i.e., its bit is set in the free frag bit map).  If so,
4884  * move it from the "as-yet-unclassified" list to the csfragfree list.
4885  */
4886 void
4887 findcsfragfree()
4888 {
4889 	struct csfrag	*cfp;
4890 	struct csfrag	*cfpnext;
4891 
4892 	/*
4893 	 * move free frags onto the free-frag list
4894 	 */
4895 	rdcg((long)0);
4896 	for (cfp = csfrag; cfp; cfp = cfpnext) {
4897 		cfpnext = cfp->next;
4898 		if (isset(cg_blksfree(&acg), cfp->ofrag - cgbase(&sblock, 0))) {
4899 			addcsfrag(cfp->ino, cfp->ofrag, &csfragfree);
4900 			delcsfrag(cfp->ofrag, &csfrag);
4901 		}
4902 	}
4903 }
4904 
4905 void
4906 copycsfragino()
4907 {
4908 	struct csfrag	*cfp;
4909 	char		buf[MAXBSIZE];
4910 
4911 	/*
4912 	 * copy data from old frags to newly allocated frags
4913 	 */
4914 	for (cfp = csfragino; cfp; cfp = cfp->next) {
4915 		rdfs(fsbtodb(&sblock, (uint64_t)cfp->ofrag), (int)cfp->size,
4916 		    buf);
4917 		wtfs(fsbtodb(&sblock, (uint64_t)cfp->nfrag), (int)cfp->size,
4918 		    buf);
4919 	}
4920 }
4921 
4922 long	curcylno	= -1;
4923 int	cylnodirty	= 0;
4924 
4925 void
4926 rdcg(long cylno)
4927 {
4928 	if (cylno != curcylno) {
4929 		flcg();
4930 		curcylno = cylno;
4931 		rdfs(fsbtodb(&sblock, (uint64_t)cgtod(&sblock, curcylno)),
4932 		    (int)sblock.fs_cgsize, (char *)&acg);
4933 	}
4934 }
4935 
4936 void
4937 flcg()
4938 {
4939 	if (cylnodirty) {
4940 		if (debug && Pflag) {
4941 			(void) fprintf(stderr,
4942 			    "Assert: cylnodirty set in probe mode\n");
4943 			return;
4944 		}
4945 		resetallocinfo();
4946 		wtfs(fsbtodb(&sblock, (uint64_t)cgtod(&sblock, curcylno)),
4947 		    (int)sblock.fs_cgsize, (char *)&acg);
4948 		cylnodirty = 0;
4949 	}
4950 	curcylno = -1;
4951 }
4952 
4953 void
4954 wtcg()
4955 {
4956 	if (!Pflag) {
4957 		/* probe mode should never write to disk */
4958 		cylnodirty = 1;
4959 	}
4960 }
4961 
4962 void
4963 allocfrags(long frags, daddr32_t *fragp, long *cylnop)
4964 {
4965 	int	 i;
4966 	int	 j;
4967 	long	 bits;
4968 	long	 bit;
4969 
4970 	/*
4971 	 * Allocate a free-frag range in an old cylinder group
4972 	 */
4973 	for (i = 0, *fragp = 0; i < grow_fs_ncg; ++i) {
4974 		if (((fscs+i)->cs_nffree < frags) && ((fscs+i)->cs_nbfree == 0))
4975 			continue;
4976 		rdcg((long)i);
4977 		bit = bits = 0;
4978 		while (findfreerange(&bit, &bits)) {
4979 			if (frags <= bits)  {
4980 				for (j = 0; j < frags; ++j)
4981 					clrbit(cg_blksfree(&acg), bit+j);
4982 				wtcg();
4983 				*cylnop = i;
4984 				*fragp  = bit + cgbase(&sblock, i);
4985 				return;
4986 			}
4987 			bit += bits;
4988 		}
4989 	}
4990 }
4991 
4992 /*
4993  * Allocate space for frags that need to be moved in order to free up space for
4994  * expanding the cylinder summary info.
4995  * For each frag that needs to be moved (each frag or range of frags in
4996  * the csfragino list), allocate a new location and store the frag number
4997  * of that new location in the nfrag field of the csfrag struct.
4998  * If a new frag can't be allocated for any element in the csfragino list,
4999  * set the new frag number for that element to 0 and return immediately.
5000  * The notenoughspace() function will detect this condition.
5001  */
5002 void
5003 alloccsfragino()
5004 {
5005 	struct csfrag	*cfp;
5006 
5007 	/*
5008 	 * allocate space for inode frag ranges
5009 	 */
5010 	for (cfp = csfragino; cfp; cfp = cfp->next) {
5011 		allocfrags(cfp->frags, &cfp->nfrag, &cfp->cylno);
5012 		if (cfp->nfrag == 0)
5013 			break;
5014 	}
5015 }
5016 
5017 void
5018 alloccsfragfree()
5019 {
5020 	struct csfrag	*cfp;
5021 
5022 	/*
5023 	 * allocate the free frags needed for extended summary info
5024 	 */
5025 	rdcg((long)0);
5026 
5027 	for (cfp = csfragfree; cfp; cfp = cfp->next)
5028 		clrbit(cg_blksfree(&acg), cfp->ofrag - cgbase(&sblock, 0));
5029 
5030 	wtcg();
5031 }
5032 
5033 void
5034 freefrags(daddr32_t frag, long frags, long cylno)
5035 {
5036 	int	i;
5037 
5038 	/*
5039 	 * free frags
5040 	 */
5041 	rdcg(cylno);
5042 	for (i = 0; i < frags; ++i) {
5043 		setbit(cg_blksfree(&acg), (frag+i) - cgbase(&sblock, cylno));
5044 	}
5045 	wtcg();
5046 }
5047 
5048 int
5049 findfreerange(long *bitp, long *bitsp)
5050 {
5051 	long	 bit;
5052 
5053 	/*
5054 	 * find a range of free bits in a cylinder group bit map
5055 	 */
5056 	for (bit = *bitp, *bitsp = 0; bit < acg.cg_ndblk; ++bit)
5057 		if (isset(cg_blksfree(&acg), bit))
5058 			break;
5059 
5060 	if (bit >= acg.cg_ndblk)
5061 		return (0);
5062 
5063 	*bitp  = bit;
5064 	*bitsp = 1;
5065 	for (++bit; bit < acg.cg_ndblk; ++bit, ++(*bitsp)) {
5066 		if ((bit % sblock.fs_frag) == 0)
5067 			break;
5068 		if (isclr(cg_blksfree(&acg), bit))
5069 			break;
5070 	}
5071 	return (1);
5072 }
5073 
5074 void
5075 resetallocinfo()
5076 {
5077 	long	cno;
5078 	long	bit;
5079 	long	bits;
5080 
5081 	/*
5082 	 * Compute the free blocks/frags info and update the appropriate
5083 	 * inmemory superblock, summary info, and cylinder group fields
5084 	 */
5085 	sblock.fs_cstotal.cs_nffree -= acg.cg_cs.cs_nffree;
5086 	sblock.fs_cstotal.cs_nbfree -= acg.cg_cs.cs_nbfree;
5087 
5088 	acg.cg_cs.cs_nffree = 0;
5089 	acg.cg_cs.cs_nbfree = 0;
5090 
5091 	bzero((caddr_t)acg.cg_frsum, sizeof (acg.cg_frsum));
5092 	bzero((caddr_t)cg_blktot(&acg), (int)(acg.cg_iusedoff-acg.cg_btotoff));
5093 
5094 	bit = bits = 0;
5095 	while (findfreerange(&bit, &bits)) {
5096 		if (bits == sblock.fs_frag) {
5097 			acg.cg_cs.cs_nbfree++;
5098 			cno = cbtocylno(&sblock, bit);
5099 			cg_blktot(&acg)[cno]++;
5100 			cg_blks(&sblock, &acg, cno)[cbtorpos(&sblock, bit)]++;
5101 		} else {
5102 			acg.cg_cs.cs_nffree += bits;
5103 			acg.cg_frsum[bits]++;
5104 		}
5105 		bit += bits;
5106 	}
5107 
5108 	*(fscs + acg.cg_cgx) = acg.cg_cs;
5109 
5110 	sblock.fs_cstotal.cs_nffree += acg.cg_cs.cs_nffree;
5111 	sblock.fs_cstotal.cs_nbfree += acg.cg_cs.cs_nbfree;
5112 }
5113 
5114 void
5115 extendcg(long cylno)
5116 {
5117 	int	i;
5118 	diskaddr_t	dupper;
5119 	diskaddr_t	cbase;
5120 	diskaddr_t	dmax;
5121 
5122 	/*
5123 	 * extend the cylinder group at the end of the old file system
5124 	 * if it was partially allocated becase of lack of space
5125 	 */
5126 	flcg();
5127 	rdcg(cylno);
5128 
5129 	dupper = acg.cg_ndblk;
5130 	if (cylno == sblock.fs_ncg - 1)
5131 		acg.cg_ncyl = sblock.fs_ncyl - (sblock.fs_cpg * cylno);
5132 	else
5133 		acg.cg_ncyl = sblock.fs_cpg;
5134 	cbase = cgbase(&sblock, cylno);
5135 	dmax = cbase + sblock.fs_fpg;
5136 	if (dmax > sblock.fs_size)
5137 		dmax = sblock.fs_size;
5138 	acg.cg_ndblk = dmax - cbase;
5139 
5140 	for (i = dupper; i < acg.cg_ndblk; ++i)
5141 		setbit(cg_blksfree(&acg), i);
5142 
5143 	sblock.fs_dsize += (acg.cg_ndblk - dupper);
5144 
5145 	wtcg();
5146 	flcg();
5147 }
5148 
5149 struct lockfs	lockfs;
5150 int		lockfd;
5151 int		islocked;
5152 int		lockfskey;
5153 char		lockfscomment[128];
5154 
5155 void
5156 ulockfs()
5157 {
5158 	/*
5159 	 * if the file system was locked, unlock it before exiting
5160 	 */
5161 	if (islocked == 0)
5162 		return;
5163 
5164 	/*
5165 	 * first, check if the lock held
5166 	 */
5167 	lockfs.lf_flags = LOCKFS_MOD;
5168 	if (ioctl(lockfd, _FIOLFSS, &lockfs) == -1) {
5169 		perror(directory);
5170 		lockexit(32);
5171 	}
5172 
5173 	if (LOCKFS_IS_MOD(&lockfs)) {
5174 		(void) fprintf(stderr,
5175 		    gettext("FILE SYSTEM CHANGED DURING GROWFS!\n"));
5176 		(void) fprintf(stderr,
5177 		    gettext("   See lockfs(1), umount(1), and fsck(1)\n"));
5178 		lockexit(32);
5179 	}
5180 	/*
5181 	 * unlock the file system
5182 	 */
5183 	lockfs.lf_lock  = LOCKFS_ULOCK;
5184 	lockfs.lf_flags = 0;
5185 	lockfs.lf_key   = lockfskey;
5186 	clockfs();
5187 	if (ioctl(lockfd, _FIOLFS, &lockfs) == -1) {
5188 		perror(directory);
5189 		lockexit(32);
5190 	}
5191 }
5192 
5193 void
5194 wlockfs()
5195 {
5196 
5197 	/*
5198 	 * if no-write (-N), don't bother
5199 	 */
5200 	if (Nflag)
5201 		return;
5202 	/*
5203 	 * open the mountpoint, and write lock the file system
5204 	 */
5205 	if ((lockfd = open64(directory, O_RDONLY)) == -1) {
5206 		perror(directory);
5207 		lockexit(32);
5208 	}
5209 
5210 	/*
5211 	 * check if it is already locked
5212 	 */
5213 	if (ioctl(lockfd, _FIOLFSS, &lockfs) == -1) {
5214 		perror(directory);
5215 		lockexit(32);
5216 	}
5217 
5218 	if (lockfs.lf_lock != LOCKFS_WLOCK) {
5219 		lockfs.lf_lock  = LOCKFS_WLOCK;
5220 		lockfs.lf_flags = 0;
5221 		lockfs.lf_key   = 0;
5222 		clockfs();
5223 		if (ioctl(lockfd, _FIOLFS, &lockfs) == -1) {
5224 			perror(directory);
5225 			lockexit(32);
5226 		}
5227 	}
5228 	islocked = 1;
5229 	lockfskey = lockfs.lf_key;
5230 }
5231 
5232 void
5233 clockfs()
5234 {
5235 	time_t	t;
5236 	char	*ct;
5237 
5238 	(void) time(&t);
5239 	ct = ctime(&t);
5240 	ct[strlen(ct)-1] = '\0';
5241 
5242 	(void) sprintf(lockfscomment, "%s -- mkfs pid %d", ct, getpid());
5243 	lockfs.lf_comlen  = strlen(lockfscomment)+1;
5244 	lockfs.lf_comment = lockfscomment;
5245 }
5246 
5247 /*
5248  * Write the csum records and the superblock
5249  */
5250 void
5251 wtsb()
5252 {
5253 	long	i;
5254 
5255 	/*
5256 	 * write summary information
5257 	 */
5258 	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
5259 		wtfs(fsbtodb(&sblock, (uint64_t)(sblock.fs_csaddr +
5260 		    numfrags(&sblock, i))),
5261 		    (int)(sblock.fs_cssize - i < sblock.fs_bsize ?
5262 		    sblock.fs_cssize - i : sblock.fs_bsize),
5263 		    ((char *)fscs) + i);
5264 
5265 	/*
5266 	 * write superblock
5267 	 */
5268 	sblock.fs_time = mkfstime;
5269 	wtfs((diskaddr_t)(SBOFF / sectorsize), sbsize, (char *)&sblock);
5270 }
5271 
5272 /*
5273  * Verify that the optimization selection is reasonable, and advance
5274  * the global "string" appropriately.
5275  */
5276 static char
5277 checkopt(char *optim)
5278 {
5279 	char	opt;
5280 	int	limit = strcspn(optim, ",");
5281 
5282 	switch (limit) {
5283 	case 0:	/* missing indicator (have comma or nul) */
5284 		(void) fprintf(stderr, gettext(
5285 		    "mkfs: missing optimization flag reset to `t' (time)\n"));
5286 		opt = 't';
5287 		break;
5288 
5289 	case 1: /* single-character indicator */
5290 		opt = *optim;
5291 		if ((opt != 's') && (opt != 't')) {
5292 			(void) fprintf(stderr, gettext(
5293 		    "mkfs: bad optimization value `%c' reset to `t' (time)\n"),
5294 			    opt);
5295 			opt = 't';
5296 		}
5297 		break;
5298 
5299 	default: /* multi-character indicator */
5300 		(void) fprintf(stderr, gettext(
5301 	    "mkfs: bad optimization value `%*.*s' reset to `t' (time)\n"),
5302 		    limit, limit, optim);
5303 		opt = 't';
5304 		break;
5305 	}
5306 
5307 	string += limit;
5308 
5309 	return (opt);
5310 }
5311 
5312 /*
5313  * Verify that the mtb selection is reasonable, and advance
5314  * the global "string" appropriately.
5315  */
5316 static char
5317 checkmtb(char *mtbarg)
5318 {
5319 	char	mtbc;
5320 	int	limit = strcspn(mtbarg, ",");
5321 
5322 	switch (limit) {
5323 	case 0:	/* missing indicator (have comma or nul) */
5324 		(void) fprintf(stderr, gettext(
5325 		    "mkfs: missing mtb flag reset to `n' (no mtb support)\n"));
5326 		mtbc = 'n';
5327 		break;
5328 
5329 	case 1: /* single-character indicator */
5330 		mtbc = tolower(*mtbarg);
5331 		if ((mtbc != 'y') && (mtbc != 'n')) {
5332 			(void) fprintf(stderr, gettext(
5333 		    "mkfs: bad mtb value `%c' reset to `n' (no mtb support)\n"),
5334 			    mtbc);
5335 			mtbc = 'n';
5336 		}
5337 		break;
5338 
5339 	default: /* multi-character indicator */
5340 		(void) fprintf(stderr, gettext(
5341 	    "mkfs: bad mtb value `%*.*s' reset to `n' (no mtb support)\n"),
5342 		    limit, limit, mtbarg);
5343 		opt = 'n';
5344 		break;
5345 	}
5346 
5347 	string += limit;
5348 
5349 	return (mtbc);
5350 }
5351 
5352 /*
5353  * Verify that a value is in a range.  If it is not, resets it to
5354  * its default value if one is supplied, exits otherwise.
5355  *
5356  * When testing, can compare user_supplied to RC_KEYWORD or RC_POSITIONAL.
5357  */
5358 static void
5359 range_check(long *varp, char *name, long minimum, long maximum,
5360     long def_val, int user_supplied)
5361 {
5362 	dprintf(("DeBuG %s : %ld (%ld %ld %ld)\n",
5363 	    name, *varp, minimum, maximum, def_val));
5364 
5365 	if ((*varp < minimum) || (*varp > maximum)) {
5366 		if (user_supplied != RC_DEFAULT) {
5367 			(void) fprintf(stderr, gettext(
5368 	    "mkfs: bad value for %s: %ld must be between %ld and %ld\n"),
5369 			    name, *varp, minimum, maximum);
5370 		}
5371 		if (def_val != NO_DEFAULT) {
5372 			if (user_supplied) {
5373 				(void) fprintf(stderr,
5374 				    gettext("mkfs: %s reset to default %ld\n"),
5375 				    name, def_val);
5376 			}
5377 			*varp = def_val;
5378 			dprintf(("DeBuG %s : %ld\n", name, *varp));
5379 			return;
5380 		}
5381 		lockexit(2);
5382 		/*NOTREACHED*/
5383 	}
5384 }
5385 
5386 /*
5387  * Verify that a value is in a range.  If it is not, resets it to
5388  * its default value if one is supplied, exits otherwise.
5389  *
5390  * When testing, can compare user_supplied to RC_KEYWORD or RC_POSITIONAL.
5391  */
5392 static void
5393 range_check_64(uint64_t *varp, char *name, uint64_t minimum, uint64_t maximum,
5394     uint64_t def_val, int user_supplied)
5395 {
5396 	if ((*varp < minimum) || (*varp > maximum)) {
5397 		if (user_supplied != RC_DEFAULT) {
5398 			(void) fprintf(stderr, gettext(
5399 	    "mkfs: bad value for %s: %lld must be between %lld and %lld\n"),
5400 			    name, *varp, minimum, maximum);
5401 		}
5402 		if (def_val != NO_DEFAULT) {
5403 			if (user_supplied) {
5404 				(void) fprintf(stderr,
5405 				    gettext("mkfs: %s reset to default %lld\n"),
5406 				    name, def_val);
5407 			}
5408 			*varp = def_val;
5409 			return;
5410 		}
5411 		lockexit(2);
5412 		/*NOTREACHED*/
5413 	}
5414 }
5415 
5416 /*
5417  * Blocks SIGINT from delivery.  Returns the previous mask in the
5418  * buffer provided, so that mask may be later restored.
5419  */
5420 static void
5421 block_sigint(sigset_t *old_mask)
5422 {
5423 	sigset_t block_mask;
5424 
5425 	if (sigemptyset(&block_mask) < 0) {
5426 		fprintf(stderr, gettext("Could not clear signal mask\n"));
5427 		lockexit(3);
5428 	}
5429 	if (sigaddset(&block_mask, SIGINT) < 0) {
5430 		fprintf(stderr, gettext("Could not set signal mask\n"));
5431 		lockexit(3);
5432 	}
5433 	if (sigprocmask(SIG_BLOCK, &block_mask, old_mask) < 0) {
5434 		fprintf(stderr, gettext("Could not block SIGINT\n"));
5435 		lockexit(3);
5436 	}
5437 }
5438 
5439 /*
5440  * Restores the signal mask that was in force before a call
5441  * to block_sigint().  This may actually still have SIGINT blocked,
5442  * if we've been recursively invoked.
5443  */
5444 static void
5445 unblock_sigint(sigset_t *old_mask)
5446 {
5447 	if (sigprocmask(SIG_UNBLOCK, old_mask, (sigset_t *)NULL) < 0) {
5448 		fprintf(stderr, gettext("Could not restore signal mask\n"));
5449 		lockexit(3);
5450 	}
5451 }
5452 
5453 /*
5454  * Attempt to be somewhat graceful about being interrupted, rather than
5455  * just silently leaving the filesystem in an unusable state.
5456  *
5457  * The kernel has blocked SIGINT upon entry, so we don't have to worry
5458  * about recursion if the user starts pounding on the keyboard.
5459  */
5460 static void
5461 recover_from_sigint(int signum)
5462 {
5463 	if (fso > -1) {
5464 		if ((Nflag != 0) || confirm_abort()) {
5465 			lockexit(4);
5466 		}
5467 	}
5468 }
5469 
5470 static int
5471 confirm_abort(void)
5472 {
5473 	char line[80];
5474 
5475 	printf(gettext("\n\nAborting at this point will leave the filesystem "
5476 	    "in an inconsistent\nstate.  If you do choose to stop, "
5477 	    "you will be given instructions on how to\nrecover "
5478 	    "the filesystem.  Do you wish to cancel the filesystem "
5479 	    "grow\noperation (y/n)?"));
5480 	if (getline(stdin, line, sizeof (line)) == EOF)
5481 		line[0] = 'y';
5482 
5483 	printf("\n");
5484 	if (line[0] == 'y' || line[0] == 'Y')
5485 		return (1);
5486 	else {
5487 		return (0);
5488 	}
5489 }
5490 
5491 static int
5492 getline(FILE *fp, char *loc, int maxlen)
5493 {
5494 	int n;
5495 	char *p, *lastloc;
5496 
5497 	p = loc;
5498 	lastloc = &p[maxlen-1];
5499 	while ((n = getc(fp)) != '\n') {
5500 		if (n == EOF)
5501 			return (EOF);
5502 		if (!isspace(n) && p < lastloc)
5503 			*p++ = n;
5504 	}
5505 	*p = 0;
5506 	return (p - loc);
5507 }
5508 
5509 /*
5510  * Calculate the maximum value of cylinders-per-group for a file
5511  * system with the characteristics:
5512  *
5513  *	bsize - file system block size
5514  *	fragsize - frag size
5515  *	nbpi - number of bytes of disk space per inode
5516  *	nrpos - number of rotational positions
5517  *	spc - sectors per cylinder
5518  *
5519  * These five characteristic are not adjustable (by this function).
5520  * The only attribute of the file system which IS adjusted by this
5521  * function in order to maximize cylinders-per-group is the proportion
5522  * of the cylinder group overhead block used for the inode map.  The
5523  * inode map cannot occupy more than one-third of the cylinder group
5524  * overhead block, but it's OK for it to occupy less than one-third
5525  * of the overhead block.
5526  *
5527  * The setting of nbpi determines one possible value for the maximum
5528  * size of a cylinder group.  It does so because it determines the total
5529  * number of inodes in the file system (file system size is fixed, and
5530  * nbpi is fixed, so the total number of inodes is fixed too).  The
5531  * cylinder group has to be small enough so that the number of inodes
5532  * in the cylinder group is less than or equal to the number of bits
5533  * in one-third (or whatever proportion is assumed) of a file system
5534  * block.  The details of the calculation are:
5535  *
5536  *     The macro MAXIpG_B(bsize, inode_divisor) determines the maximum
5537  *     number of inodes that can be in a cylinder group, given the
5538  *     proportion of the cylinder group overhead block used for the
5539  *     inode bitmaps (an inode_divisor of 3 means that 1/3 of the
5540  *     block is used for inode bitmaps; an inode_divisor of 12 means
5541  *     that 1/12 of the block is used for inode bitmaps.)
5542  *
5543  *     Once the number of inodes per cylinder group is known, the
5544  *     maximum value of cylinders-per-group (determined by nbpi)
5545  *     is calculated by the formula
5546  *
5547  *     maxcpg_given_nbpi = (size of a cylinder group)/(size of a cylinder)
5548  *
5549  *			 = (inodes-per-cg * nbpi)/(spc * DEV_BSIZE)
5550  *
5551  *     (Interestingly, the size of the file system never enters
5552  *     into this calculation.)
5553  *
5554  * Another possible value for the maximum cylinder group size is determined
5555  * by frag_size and nrpos.  The frags in the cylinder group must be
5556  * representable in the frag bitmaps in the cylinder overhead block and the
5557  * rotational positions for each cylinder must be represented in the
5558  * rotational position tables.  The calculation of the maximum cpg
5559  * value, given the frag and nrpos vales, is:
5560  *
5561  *     maxcpg_given_fragsize =
5562  *	  (available space in the overhead block) / (size of per-cylinder data)
5563  *
5564  *     The available space in the overhead block =
5565  *	  bsize - sizeof (struct cg) - space_used_for_inode_bitmaps
5566  *
5567  *     The size of the per-cylinder data is:
5568  *	    sizeof(long)            # for the "blocks avail per cylinder" field
5569  *	    + nrpos * sizeof(short)   # for the rotational position table entry
5570  *	    + frags-per-cylinder/NBBY # number of bytes to represent this
5571  *				      # cylinder in the frag bitmap
5572  *
5573  * The two calculated maximum values of cylinder-per-group will typically
5574  * turn out to be different, since they are derived from two different
5575  * constraints.  Usually, maxcpg_given_nbpi is much bigger than
5576  * maxcpg_given_fragsize.  But they can be brought together by
5577  * adjusting the proportion of the overhead block dedicated to
5578  * the inode bitmaps.  Decreasing the proportion of the cylinder
5579  * group overhead block used for inode maps will decrease
5580  * maxcpg_given_nbpi and increase maxcpg_given_fragsize.
5581  *
5582  * This function calculates the initial values of maxcpg_given_nbpi
5583  * and maxcpg_given_fragsize assuming that 1/3 of the cg overhead
5584  * block is used for inode bitmaps.  Then it decreases the proportion
5585  * of the cg overhead block used for inode bitmaps (by increasing
5586  * the value of inode_divisor) until maxcpg_given_nbpi and
5587  * maxcpg_given_fragsize are the same, or stop changing, or
5588  * maxcpg_given_nbpi is less than maxcpg_given_fragsize.
5589  *
5590  * The loop terminates when any of the following occur:
5591  *	* maxcpg_given_fragsize is greater than or equal to
5592  *	  maxcpg_given_nbpi
5593  *	* neither maxcpg_given_fragsize nor maxcpg_given_nbpi
5594  *	  change in the expected direction
5595  *
5596  * The loop is guaranteed to terminate because it only continues
5597  * while maxcpg_given_fragsize and maxcpg_given_nbpi are approaching
5598  * each other.  As soon they cross each other, or neither one changes
5599  * in the direction of the other, or one of them moves in the wrong
5600  * direction, the loop completes.
5601  */
5602 
5603 static long
5604 compute_maxcpg(long bsize, long fragsize, long nbpi, long nrpos, long spc)
5605 {
5606 	int	maxcpg_given_nbpi;	/* in cylinders */
5607 	int	maxcpg_given_fragsize;	/* in cylinders */
5608 	int	spf;			/* sectors per frag */
5609 	int	inode_divisor;
5610 	int	old_max_given_frag = 0;
5611 	int	old_max_given_nbpi = INT_MAX;
5612 
5613 	spf = fragsize / DEV_BSIZE;
5614 	inode_divisor = 3;
5615 
5616 	while (1) {
5617 		maxcpg_given_nbpi =
5618 		    (((int64_t)(MAXIpG_B(bsize, inode_divisor))) * nbpi) /
5619 		    (DEV_BSIZE * ((int64_t)spc));
5620 		maxcpg_given_fragsize =
5621 		    (bsize - (sizeof (struct cg)) - (bsize / inode_divisor)) /
5622 		    (sizeof (long) + nrpos * sizeof (short) +
5623 		    (spc / spf) / NBBY);
5624 
5625 		if (maxcpg_given_fragsize >= maxcpg_given_nbpi)
5626 			return (maxcpg_given_nbpi);
5627 
5628 		/*
5629 		 * If neither value moves toward the other, return the
5630 		 * least of the old values (we use the old instead of the
5631 		 * new because: if the old is the same as the new, it
5632 		 * doesn't matter which ones we use.  If one of the
5633 		 * values changed, but in the wrong direction, the
5634 		 * new values are suspect.  Better use the old.  This
5635 		 * shouldn't happen, but it's best to check.
5636 		 */
5637 
5638 		if (!(maxcpg_given_nbpi < old_max_given_nbpi) &&
5639 		    !(maxcpg_given_fragsize > old_max_given_frag))
5640 			return (MIN(old_max_given_nbpi, old_max_given_frag));
5641 
5642 		/*
5643 		 * This is probably impossible, but if one of the maxcpg
5644 		 * values moved in the "right" direction and one moved
5645 		 * in the "wrong" direction (that is, the two values moved
5646 		 * in the same direction), the previous conditional won't
5647 		 * recognize that the values aren't converging (since at
5648 		 * least one value moved in the "right" direction, the
5649 		 * last conditional says "keep going").
5650 		 *
5651 		 * Just to make absolutely certain that the loop terminates,
5652 		 * check for one of the values moving in the "wrong" direction
5653 		 * and terminate the loop if it happens.
5654 		 */
5655 
5656 		if (maxcpg_given_nbpi > old_max_given_nbpi ||
5657 		    maxcpg_given_fragsize < old_max_given_frag)
5658 			return (MIN(old_max_given_nbpi, old_max_given_frag));
5659 
5660 		old_max_given_nbpi = maxcpg_given_nbpi;
5661 		old_max_given_frag = maxcpg_given_fragsize;
5662 
5663 		inode_divisor++;
5664 	}
5665 }
5666 
5667 static int
5668 in_64bit_mode(void)
5669 {
5670 	/*  cmd must be an absolute path, for security */
5671 	char *cmd = "/usr/bin/isainfo -b";
5672 	char buf[BUFSIZ];
5673 	FILE *ptr;
5674 	int retval = 0;
5675 
5676 	putenv("IFS= \t");
5677 	if ((ptr = popen(cmd, "r")) != NULL) {
5678 		if (fgets(buf, BUFSIZ, ptr) != NULL &&
5679 		    strncmp(buf, "64", 2) == 0)
5680 			retval = 1;
5681 		(void) pclose(ptr);
5682 	}
5683 	return (retval);
5684 }
5685 
5686 /*
5687  * validate_size
5688  *
5689  * Return 1 if the device appears to be at least "size" sectors long.
5690  * Return 0 if it's shorter or we can't read it.
5691  */
5692 
5693 static int
5694 validate_size(int fd, diskaddr_t size)
5695 {
5696 	char 		buf[DEV_BSIZE];
5697 	int rc;
5698 
5699 	if ((llseek(fd, (offset_t)((size - 1) * DEV_BSIZE), SEEK_SET) == -1) ||
5700 	    (read(fd, buf, DEV_BSIZE)) != DEV_BSIZE)
5701 		rc = 0;
5702 	else
5703 		rc = 1;
5704 	return (rc);
5705 }
5706 
5707 /*
5708  * Print every field of the calculated superblock, along with
5709  * its value.  To make parsing easier on the caller, the value
5710  * is printed first, then the name.  Additionally, there's only
5711  * one name/value pair per line.  All values are reported in
5712  * hexadecimal (with the traditional 0x prefix), as that's slightly
5713  * easier for humans to read.  Not that they're expected to, but
5714  * debugging happens.
5715  */
5716 static void
5717 dump_sblock(void)
5718 {
5719 	int row, column, pending, written;
5720 	caddr_t source;
5721 
5722 	if (Rflag) {
5723 		pending = sizeof (sblock);
5724 		source = (caddr_t)&sblock;
5725 		do {
5726 			written = write(fileno(stdout), source, pending);
5727 			pending -= written;
5728 			source += written;
5729 		} while ((pending > 0) && (written > 0));
5730 
5731 		if (written < 0) {
5732 			perror(gettext("Binary dump of superblock failed"));
5733 			lockexit(1);
5734 		}
5735 		return;
5736 	} else {
5737 		printf("0x%x sblock.fs_link\n", sblock.fs_link);
5738 		printf("0x%x sblock.fs_rolled\n", sblock.fs_rolled);
5739 		printf("0x%x sblock.fs_sblkno\n", sblock.fs_sblkno);
5740 		printf("0x%x sblock.fs_cblkno\n", sblock.fs_cblkno);
5741 		printf("0x%x sblock.fs_iblkno\n", sblock.fs_iblkno);
5742 		printf("0x%x sblock.fs_dblkno\n", sblock.fs_dblkno);
5743 		printf("0x%x sblock.fs_cgoffset\n", sblock.fs_cgoffset);
5744 		printf("0x%x sblock.fs_cgmask\n", sblock.fs_cgmask);
5745 		printf("0x%x sblock.fs_time\n", sblock.fs_time);
5746 		printf("0x%x sblock.fs_size\n", sblock.fs_size);
5747 		printf("0x%x sblock.fs_dsize\n", sblock.fs_dsize);
5748 		printf("0x%x sblock.fs_ncg\n", sblock.fs_ncg);
5749 		printf("0x%x sblock.fs_bsize\n", sblock.fs_bsize);
5750 		printf("0x%x sblock.fs_fsize\n", sblock.fs_fsize);
5751 		printf("0x%x sblock.fs_frag\n", sblock.fs_frag);
5752 		printf("0x%x sblock.fs_minfree\n", sblock.fs_minfree);
5753 		printf("0x%x sblock.fs_rotdelay\n", sblock.fs_rotdelay);
5754 		printf("0x%x sblock.fs_rps\n", sblock.fs_rps);
5755 		printf("0x%x sblock.fs_bmask\n", sblock.fs_bmask);
5756 		printf("0x%x sblock.fs_fmask\n", sblock.fs_fmask);
5757 		printf("0x%x sblock.fs_bshift\n", sblock.fs_bshift);
5758 		printf("0x%x sblock.fs_fshift\n", sblock.fs_fshift);
5759 		printf("0x%x sblock.fs_maxcontig\n", sblock.fs_maxcontig);
5760 		printf("0x%x sblock.fs_maxbpg\n", sblock.fs_maxbpg);
5761 		printf("0x%x sblock.fs_fragshift\n", sblock.fs_fragshift);
5762 		printf("0x%x sblock.fs_fsbtodb\n", sblock.fs_fsbtodb);
5763 		printf("0x%x sblock.fs_sbsize\n", sblock.fs_sbsize);
5764 		printf("0x%x sblock.fs_csmask\n", sblock.fs_csmask);
5765 		printf("0x%x sblock.fs_csshift\n", sblock.fs_csshift);
5766 		printf("0x%x sblock.fs_nindir\n", sblock.fs_nindir);
5767 		printf("0x%x sblock.fs_inopb\n", sblock.fs_inopb);
5768 		printf("0x%x sblock.fs_nspf\n", sblock.fs_nspf);
5769 		printf("0x%x sblock.fs_optim\n", sblock.fs_optim);
5770 #ifdef _LITTLE_ENDIAN
5771 		printf("0x%x sblock.fs_state\n", sblock.fs_state);
5772 #else
5773 		printf("0x%x sblock.fs_npsect\n", sblock.fs_npsect);
5774 #endif
5775 		printf("0x%x sblock.fs_si\n", sblock.fs_si);
5776 		printf("0x%x sblock.fs_trackskew\n", sblock.fs_trackskew);
5777 		printf("0x%x sblock.fs_id[0]\n", sblock.fs_id[0]);
5778 		printf("0x%x sblock.fs_id[1]\n", sblock.fs_id[1]);
5779 		printf("0x%x sblock.fs_csaddr\n", sblock.fs_csaddr);
5780 		printf("0x%x sblock.fs_cssize\n", sblock.fs_cssize);
5781 		printf("0x%x sblock.fs_cgsize\n", sblock.fs_cgsize);
5782 		printf("0x%x sblock.fs_ntrak\n", sblock.fs_ntrak);
5783 		printf("0x%x sblock.fs_nsect\n", sblock.fs_nsect);
5784 		printf("0x%x sblock.fs_spc\n", sblock.fs_spc);
5785 		printf("0x%x sblock.fs_ncyl\n", sblock.fs_ncyl);
5786 		printf("0x%x sblock.fs_cpg\n", sblock.fs_cpg);
5787 		printf("0x%x sblock.fs_ipg\n", sblock.fs_ipg);
5788 		printf("0x%x sblock.fs_fpg\n", sblock.fs_fpg);
5789 		printf("0x%x sblock.fs_cstotal\n", sblock.fs_cstotal);
5790 		printf("0x%x sblock.fs_fmod\n", sblock.fs_fmod);
5791 		printf("0x%x sblock.fs_clean\n", sblock.fs_clean);
5792 		printf("0x%x sblock.fs_ronly\n", sblock.fs_ronly);
5793 		printf("0x%x sblock.fs_flags\n", sblock.fs_flags);
5794 		printf("0x%x sblock.fs_fsmnt\n", sblock.fs_fsmnt);
5795 		printf("0x%x sblock.fs_cgrotor\n", sblock.fs_cgrotor);
5796 		printf("0x%x sblock.fs_u.fs_csp\n", sblock.fs_u.fs_csp);
5797 		printf("0x%x sblock.fs_cpc\n", sblock.fs_cpc);
5798 
5799 		/*
5800 		 * No macros are defined for the dimensions of the
5801 		 * opostbl array.
5802 		 */
5803 		for (row = 0; row < 16; row++) {
5804 			for (column = 0; column < 8; column++) {
5805 				printf("0x%x sblock.fs_opostbl[%d][%d]\n",
5806 				    sblock.fs_opostbl[row][column],
5807 				    row, column);
5808 			}
5809 		}
5810 
5811 		/*
5812 		 * Ditto the size of sparecon.
5813 		 */
5814 		for (row = 0; row < 51; row++) {
5815 			printf("0x%x sblock.fs_sparecon[%d]\n",
5816 			    sblock.fs_sparecon[row], row);
5817 		}
5818 
5819 		printf("0x%x sblock.fs_version\n", sblock.fs_version);
5820 		printf("0x%x sblock.fs_logbno\n", sblock.fs_logbno);
5821 		printf("0x%x sblock.fs_reclaim\n", sblock.fs_reclaim);
5822 		printf("0x%x sblock.fs_sparecon2\n", sblock.fs_sparecon2);
5823 #ifdef _LITTLE_ENDIAN
5824 		printf("0x%x sblock.fs_npsect\n", sblock.fs_npsect);
5825 #else
5826 		printf("0x%x sblock.fs_state\n", sblock.fs_state);
5827 #endif
5828 		printf("0x%llx sblock.fs_qbmask\n", sblock.fs_qbmask);
5829 		printf("0x%llx sblock.fs_qfmask\n", sblock.fs_qfmask);
5830 		printf("0x%x sblock.fs_postblformat\n", sblock.fs_postblformat);
5831 		printf("0x%x sblock.fs_nrpos\n", sblock.fs_nrpos);
5832 		printf("0x%x sblock.fs_postbloff\n", sblock.fs_postbloff);
5833 		printf("0x%x sblock.fs_rotbloff\n", sblock.fs_rotbloff);
5834 		printf("0x%x sblock.fs_magic\n", sblock.fs_magic);
5835 
5836 		/*
5837 		 * fs_space isn't of much use in this context, so we'll
5838 		 * just ignore it for now.
5839 		 */
5840 	}
5841 }
5842