xref: /openbsd-src/sbin/newfs/mkfs.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: mkfs.c,v 1.72 2008/08/08 23:49:53 krw Exp $	*/
2 /*	$NetBSD: mkfs.c,v 1.25 1995/06/18 21:35:38 cgd Exp $	*/
3 
4 /*
5  * Copyright (c) 2002 Networks Associates Technology, Inc.
6  * All rights reserved.
7  *
8  * This software was developed for the FreeBSD Project by Marshall
9  * Kirk McKusick and Network Associates Laboratories, the Security
10  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
11  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
12  * research program.
13  *
14  * Copyright (c) 1980, 1989, 1993
15  *	The Regents of the University of California.  All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  * 3. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  */
41 
42 #include <sys/param.h>
43 #include <sys/time.h>
44 #include <sys/disklabel.h>
45 #include <sys/ioctl.h>
46 #include <sys/mman.h>
47 
48 #include <ufs/ufs/dinode.h>
49 #include <ufs/ufs/dir.h>
50 #include <ufs/ffs/fs.h>
51 
52 #include <err.h>
53 #include <string.h>
54 #include <stdlib.h>
55 #include <stdint.h>
56 #include <unistd.h>
57 
58 #ifndef STANDALONE
59 #include <a.out.h>
60 #include <stdio.h>
61 #include <errno.h>
62 #endif
63 
64 /*
65  * Default directory umask.
66  */
67 #define UMASK		0755
68 
69 #define POWEROF2(num)	(((num) & ((num) - 1)) == 0)
70 
71 /*
72  * 'Standard' bad FFS magic.
73  */
74 #define FS_BAD_MAGIC	0x19960408
75 
76 /*
77  * The minimum number of cylinder groups that should be created.
78  */
79 #define MINCYLGRPS	4
80 
81 /*
82  * variables set up by front end.
83  */
84 extern int	mfs;		/* run as the memory based filesystem */
85 extern int	Nflag;		/* run mkfs without writing file system */
86 extern int	Oflag;		/* format as an 4.3BSD file system */
87 extern daddr64_t fssize;	/* file system size */
88 extern int	sectorsize;	/* bytes/sector */
89 extern int	fsize;		/* fragment size */
90 extern int	bsize;		/* block size */
91 extern int	maxfrgspercg;	/* maximum fragments per cylinder group */
92 extern int	minfree;	/* free space threshold */
93 extern int	opt;		/* optimization preference (space or time) */
94 extern int	density;	/* number of bytes per inode */
95 extern int	maxbpg;		/* maximum blocks per file in a cyl group */
96 extern int	avgfilesize;	/* expected average file size */
97 extern int	avgfilesperdir;	/* expected number of files per directory */
98 extern int	quiet;		/* quiet flag */
99 extern caddr_t	membase;	/* start address of memory based filesystem */
100 
101 union fs_u {
102 	struct fs fs;
103 	char pad[SBSIZE];
104 } *fsun;
105 #define sblock	fsun->fs
106 
107 struct	csum *fscs;
108 
109 union cg_u {
110 	struct cg cg;
111 	char pad[MAXBSIZE];
112 } *cgun;
113 #define acg	cgun->cg
114 
115 union dinode {
116 	struct ufs1_dinode dp1;
117 	struct ufs2_dinode dp2;
118 };
119 
120 int	fsi, fso;
121 
122 static caddr_t iobuf;
123 static long iobufsize;
124 
125 daddr64_t	alloc(int, int);
126 static int	charsperline(void);
127 static int	ilog2(int);
128 void		initcg(int, time_t);
129 void		wtfs(daddr64_t, int, void *);
130 int		fsinit1(time_t, mode_t, uid_t, gid_t);
131 int		fsinit2(time_t);
132 int		makedir(struct direct *, int);
133 void		iput(union dinode *, ino_t);
134 void		setblock(struct fs *, unsigned char *, int);
135 void		clrblock(struct fs *, unsigned char *, int);
136 int		isblock(struct fs *, unsigned char *, int);
137 void		rdfs(daddr64_t, int, void *);
138 void		mkfs(struct partition *, char *, int, int,
139 		    mode_t, uid_t, gid_t);
140 
141 #ifndef STANDALONE
142 volatile sig_atomic_t cur_cylno;
143 volatile const char *cur_fsys;
144 
145 void
146 siginfo(int sig)
147 {
148 	int save_errno = errno;
149 	char buf[128];
150 
151 	snprintf(buf, sizeof(buf), "%s: initializing cg %ld/%d\n",
152 	    cur_fsys, (long)cur_cylno, sblock.fs_ncg);
153 	write(STDERR_FILENO, buf, strlen(buf));
154 	errno = save_errno;
155 }
156 #endif
157 
158 void
159 mkfs(struct partition *pp, char *fsys, int fi, int fo, mode_t mfsmode,
160     uid_t mfsuid, gid_t mfsgid)
161 {
162 	time_t utime;
163 	quad_t sizepb;
164 	int i, j, width, origdensity, fragsperinode, minfpg, optimalfpg;
165 	int lastminfpg, mincylgrps;
166 	long cylno, csfrags;
167 	char tmpbuf[100];	/* XXX this will break in about 2,500 years */
168 
169 	if ((fsun = calloc(1, sizeof (union fs_u))) == NULL ||
170 	    (cgun = calloc(1, sizeof (union cg_u))) == NULL)
171 		err(1, "calloc");
172 
173 #ifndef STANDALONE
174 	time(&utime);
175 #endif
176 	if (mfs) {
177 		quad_t sz = (quad_t)fssize * DEV_BSIZE;
178 		if (sz > SIZE_T_MAX) {
179 			errno = ENOMEM;
180 			err(12, "mmap");
181 		}
182 		membase = mmap(NULL, sz, PROT_READ|PROT_WRITE,
183 		    MAP_ANON|MAP_PRIVATE, -1, (off_t)0);
184 		if (membase == MAP_FAILED)
185 			err(12, "mmap");
186 		madvise(membase, sz, MADV_RANDOM);
187 	}
188 	fsi = fi;
189 	fso = fo;
190 	/*
191 	 * Validate the given file system size.
192 	 * Verify that its last block can actually be accessed.
193 	 */
194 	if (Oflag <= 1 && fssize > INT_MAX)
195 		errx(13, "preposterous size %lld, max is %d", fssize, INT_MAX);
196 	if (Oflag == 2 && fssize > MAXDISKSIZE)
197 		errx(13, "preposterous size %lld, max is %lld", fssize,
198 		    MAXDISKSIZE);
199 
200 	wtfs(fssize - (sectorsize / DEV_BSIZE), sectorsize, (char *)&sblock);
201 
202 	sblock.fs_postblformat = FS_DYNAMICPOSTBLFMT;
203 	sblock.fs_avgfilesize = avgfilesize;
204 	sblock.fs_avgfpdir = avgfilesperdir;
205 
206 	/*
207 	 * Collect and verify the block and fragment sizes.
208 	 */
209 	if (!POWEROF2(bsize)) {
210 		errx(16, "block size must be a power of 2, not %d", bsize);
211 	}
212 	if (!POWEROF2(fsize)) {
213 		errx(17, "fragment size must be a power of 2, not %d",
214 		     fsize);
215 	}
216 	if (fsize < sectorsize) {
217 		errx(18, "fragment size %d is too small, minimum is %d",
218 		     fsize, sectorsize);
219 	}
220 	if (bsize < MINBSIZE) {
221 		errx(19, "block size %d is too small, minimum is %d",
222 		     bsize, MINBSIZE);
223 	}
224 	if (bsize > MAXBSIZE) {
225 		errx(19, "block size %d is too large, maximum is %d",
226 		     bsize, MAXBSIZE);
227 	}
228 	if (bsize < fsize) {
229 		errx(20, "block size (%d) cannot be smaller than fragment size (%d)",
230 		     bsize, fsize);
231 	}
232 	sblock.fs_bsize = bsize;
233 	sblock.fs_fsize = fsize;
234 
235 	/*
236 	 * Calculate the superblock bitmasks and shifts.
237 	 */
238 	sblock.fs_bmask = ~(sblock.fs_bsize - 1);
239 	sblock.fs_fmask = ~(sblock.fs_fsize - 1);
240 	sblock.fs_qbmask = ~sblock.fs_bmask;
241 	sblock.fs_qfmask = ~sblock.fs_fmask;
242 	sblock.fs_bshift = ilog2(sblock.fs_bsize);
243 	sblock.fs_fshift = ilog2(sblock.fs_fsize);
244 	sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
245 	if (sblock.fs_frag > MAXFRAG) {
246 		errx(21, "fragment size %d is too small, minimum with block "
247 		    "size %d is %d", sblock.fs_fsize, sblock.fs_bsize,
248 		    sblock.fs_bsize / MAXFRAG);
249 	}
250 	sblock.fs_fragshift = ilog2(sblock.fs_frag);
251 	sblock.fs_fsbtodb = ilog2(sblock.fs_fsize / DEV_BSIZE);
252 	sblock.fs_size = dbtofsb(&sblock, fssize);
253 	sblock.fs_nspf = sblock.fs_fsize / DEV_BSIZE;
254 	sblock.fs_maxcontig = 1;
255 	sblock.fs_nrpos = 1;
256 	sblock.fs_cpg = 1;
257 
258 	/*
259 	 * Before the file system is fully initialized, mark it as invalid.
260 	 */
261 	sblock.fs_magic = FS_BAD_MAGIC;
262 
263 	/*
264 	 * Set the remaining superblock fields.  Note that for FFS1, media
265 	 * geometry fields are set to fake values.  This is for compatibility
266 	 * with really ancient kernels that might still inspect these values.
267 	 */
268 	if (Oflag <= 1) {
269 		sblock.fs_sblockloc = SBLOCK_UFS1;
270 		sblock.fs_nindir = sblock.fs_bsize / sizeof(int32_t);
271 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
272 		if (Oflag == 0) {
273 			sblock.fs_maxsymlinklen = 0;
274 			sblock.fs_inodefmt = FS_42INODEFMT;
275 		} else {
276 			sblock.fs_maxsymlinklen = MAXSYMLINKLEN_UFS1;
277 			sblock.fs_inodefmt = FS_44INODEFMT;
278 		}
279 		sblock.fs_cgoffset = 0;
280 		sblock.fs_cgmask = 0xffffffff;
281 		sblock.fs_ffs1_size = sblock.fs_size;
282 		sblock.fs_rotdelay = 0;
283 		sblock.fs_rps = 60;
284 		sblock.fs_interleave = 1;
285 		sblock.fs_trackskew = 0;
286 		sblock.fs_cpc = 0;
287 	} else {
288 		sblock.fs_inodefmt = FS_44INODEFMT;
289 		sblock.fs_sblockloc = SBLOCK_UFS2;
290 		sblock.fs_nindir = sblock.fs_bsize / sizeof(int64_t);
291 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs2_dinode);
292 		sblock.fs_maxsymlinklen = MAXSYMLINKLEN_UFS2;
293 	}
294 	sblock.fs_sblkno =
295 	    roundup(howmany(sblock.fs_sblockloc + SBLOCKSIZE, sblock.fs_fsize),
296 		sblock.fs_frag);
297 	sblock.fs_cblkno = (int32_t)(sblock.fs_sblkno +
298 	    roundup(howmany(SBSIZE, sblock.fs_fsize), sblock.fs_frag));
299 	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
300 	sblock.fs_maxfilesize = sblock.fs_bsize * NDADDR - 1;
301 	for (sizepb = sblock.fs_bsize, i = 0; i < NIADDR; i++) {
302 		sizepb *= NINDIR(&sblock);
303 		sblock.fs_maxfilesize += sizepb;
304 	}
305 #ifdef notyet
306 	/*
307 	 * It is impossible to create a snapshot in case fs_maxfilesize is
308 	 * smaller than fssize.
309 	 */
310 	if (sblock.fs_maxfilesize < (u_quad_t)fssize)
311 		warnx("WARNING: You will be unable to create snapshots on this "
312 		    "file system. Correct by using a larger blocksize.");
313 #endif
314 	/*
315 	 * Calculate the number of blocks to put into each cylinder group. The
316 	 * first goal is to have at least enough data blocks in each cylinder
317 	 * group to meet the density requirement. Once this goal is achieved
318 	 * we try to expand to have at least mincylgrps cylinder groups. Once
319 	 * this goal is achieved, we pack as many blocks into each cylinder
320 	 * group map as will fit.
321 	 *
322 	 * We start by calculating the smallest number of blocks that we can
323 	 * put into each cylinder group. If this is too big, we reduce the
324 	 * density until it fits.
325 	 */
326 	origdensity = density;
327 	for (;;) {
328 		fragsperinode = MAX(numfrags(&sblock, density), 1);
329 
330 		minfpg = fragsperinode * INOPB(&sblock);
331 		if (minfpg > sblock.fs_size)
332 			minfpg = sblock.fs_size;
333 
334 		sblock.fs_ipg = INOPB(&sblock);
335 		sblock.fs_fpg = roundup(sblock.fs_iblkno +
336 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
337 		if (sblock.fs_fpg < minfpg)
338 			sblock.fs_fpg = minfpg;
339 
340 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
341 		    INOPB(&sblock));
342 		sblock.fs_fpg = roundup(sblock.fs_iblkno +
343 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
344 		if (sblock.fs_fpg < minfpg)
345 			sblock.fs_fpg = minfpg;
346 
347 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
348 		    INOPB(&sblock));
349 
350 		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
351 			break;
352 
353 		density -= sblock.fs_fsize;
354 	}
355 	if (density != origdensity)
356 		warnx("density reduced from %d to %d bytes per inode",
357 		    origdensity, density);
358 
359 	/*
360 	 * Use a lower value for mincylgrps if the user specified a large
361 	 * number of blocks per cylinder group.  This is needed for, e.g. the
362 	 * install media which needs to pack 2 files very tightly.
363 	 */
364 	mincylgrps = MINCYLGRPS;
365 	if (maxfrgspercg != INT_MAX) {
366 		i = sblock.fs_size / maxfrgspercg;
367 		if (i < MINCYLGRPS)
368 			mincylgrps = i <= 0 ? 1 : i;
369 	}
370 
371 	/*
372 	 * Start packing more blocks into the cylinder group until it cannot
373 	 * grow any larger, the number of cylinder groups drops below
374 	 * mincylgrps, or we reach the requested size.
375 	 */
376 	for (;;) {
377 		sblock.fs_fpg += sblock.fs_frag;
378 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
379 		    INOPB(&sblock));
380 
381 		if (sblock.fs_fpg > maxfrgspercg ||
382 		    sblock.fs_size / sblock.fs_fpg < mincylgrps ||
383 		    CGSIZE(&sblock) > (unsigned long)sblock.fs_bsize)
384 			break;
385 	}
386 	sblock.fs_fpg -= sblock.fs_frag;
387 	sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
388 	    INOPB(&sblock));
389 	if (sblock.fs_fpg > maxfrgspercg)
390 		warnx("can't honour -c: minimum is %d", sblock.fs_fpg);
391 
392 	/*
393 	 * Check to be sure that the last cylinder group has enough blocks to
394 	 * be viable. If it is too small, reduce the number of blocks per
395 	 * cylinder group which will have the effect of moving more blocks into
396 	 * the last cylinder group.
397 	 */
398 	optimalfpg = sblock.fs_fpg;
399 	for (;;) {
400 		sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
401 		lastminfpg = roundup(sblock.fs_iblkno +
402 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
403 		if (sblock.fs_size < lastminfpg)
404 			errx(28, "file system size %jd < minimum size of %d",
405 			    (intmax_t)sblock.fs_size, lastminfpg);
406 
407 		if (sblock.fs_size % sblock.fs_fpg >= lastminfpg ||
408 		    sblock.fs_size % sblock.fs_fpg == 0)
409 			break;
410 
411 		sblock.fs_fpg -= sblock.fs_frag;
412 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
413 		    INOPB(&sblock));
414 	}
415 
416 	if (optimalfpg != sblock.fs_fpg)
417 		warnx("reduced number of fragments per cylinder group from %d"
418 		    " to %d to enlarge last cylinder group", optimalfpg,
419 		    sblock.fs_fpg);
420 
421 	/*
422 	 * Back to filling superblock fields.
423 	 */
424 	if (Oflag <= 1) {
425 		sblock.fs_spc = sblock.fs_fpg * sblock.fs_nspf;
426 		sblock.fs_nsect = sblock.fs_spc;
427 		sblock.fs_npsect = sblock.fs_spc;
428 		sblock.fs_ncyl = sblock.fs_ncg;
429 	}
430 	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
431 	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
432 	sblock.fs_csaddr = cgdmin(&sblock, 0);
433 	sblock.fs_cssize =
434 	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
435 
436 	fscs = (struct csum *)calloc(1, sblock.fs_cssize);
437 	if (fscs == NULL)
438 		errx(31, "calloc failed");
439 
440 	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
441 	if (sblock.fs_sbsize > SBLOCKSIZE)
442 		sblock.fs_sbsize = SBLOCKSIZE;
443 
444 	sblock.fs_minfree = minfree;
445 	sblock.fs_maxbpg = maxbpg;
446 	sblock.fs_optim = opt;
447 	sblock.fs_cgrotor = 0;
448 	sblock.fs_pendingblocks = 0;
449 	sblock.fs_pendinginodes = 0;
450 	sblock.fs_fmod = 0;
451 	sblock.fs_ronly = 0;
452 	sblock.fs_state = 0;
453 	sblock.fs_clean = 1;
454 	sblock.fs_id[0] = (u_int32_t)utime;
455 	sblock.fs_id[1] = (u_int32_t)arc4random();
456 	sblock.fs_fsmnt[0] = '\0';
457 
458 	csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
459 	sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
460 	    sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);
461 
462 	sblock.fs_cstotal.cs_nbfree = fragstoblks(&sblock, sblock.fs_dsize) -
463 	    howmany(csfrags, sblock.fs_frag);
464 	sblock.fs_cstotal.cs_nffree = fragnum(&sblock, sblock.fs_size) +
465 	    (fragnum(&sblock, csfrags) > 0 ?
466 	    sblock.fs_frag - fragnum(&sblock, csfrags) : 0);
467 	sblock.fs_cstotal.cs_nifree = sblock.fs_ncg * sblock.fs_ipg - ROOTINO;
468 	sblock.fs_cstotal.cs_ndir = 0;
469 
470 	sblock.fs_dsize -= csfrags;
471 	sblock.fs_time = utime;
472 
473 	if (Oflag <= 1) {
474 		sblock.fs_ffs1_time = sblock.fs_time;
475 		sblock.fs_ffs1_dsize = sblock.fs_dsize;
476 		sblock.fs_ffs1_csaddr = sblock.fs_csaddr;
477 		sblock.fs_ffs1_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
478 		sblock.fs_ffs1_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
479 		sblock.fs_ffs1_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
480 		sblock.fs_ffs1_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
481 	}
482 
483 	/*
484 	 * Dump out summary information about file system.
485 	 */
486 	if (!mfs) {
487 #define B2MBFACTOR (1 / (1024.0 * 1024.0))
488 		printf("%s: %.1fMB in %jd sectors of %d bytes\n", fsys,
489 		    (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
490 		    (intmax_t)fsbtodb(&sblock, sblock.fs_size), sectorsize);
491 		printf("%d cylinder groups of %.2fMB, %d blocks, %d"
492 		    " inodes each\n", sblock.fs_ncg,
493 		    (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
494 		    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
495 #undef B2MBFACTOR
496 	}
497 
498 	/*
499 	 * Wipe out old FFS1 superblock if necessary.
500 	 */
501 	if (Oflag >= 2) {
502 		union fs_u *fsun1;
503 		struct fs *fs1;
504 
505 		fsun1 = calloc(1, sizeof(union fs_u));
506 		if (fsun1 == NULL)
507 			err(39, "calloc");
508 		fs1 = &fsun1->fs;
509 		rdfs(SBLOCK_UFS1 / DEV_BSIZE, SBSIZE, (char *)fs1);
510 		if (fs1->fs_magic == FS_UFS1_MAGIC) {
511 			fs1->fs_magic = FS_BAD_MAGIC;
512 			wtfs(SBLOCK_UFS1 / DEV_BSIZE, SBSIZE, (char *)fs1);
513 		}
514 		free(fsun1);
515 	}
516 
517 	wtfs((int)sblock.fs_sblockloc / DEV_BSIZE, SBSIZE, (char *)&sblock);
518 	sblock.fs_magic = (Oflag <= 1) ? FS_UFS1_MAGIC : FS_UFS2_MAGIC;
519 
520 	/*
521 	 * Now build the cylinders group blocks and
522 	 * then print out indices of cylinder groups.
523 	 */
524 	if (!quiet)
525 		printf("super-block backups (for fsck -b #) at:\n");
526 #ifndef STANDALONE
527 	else if (!mfs && isatty(STDIN_FILENO)) {
528 		signal(SIGINFO, siginfo);
529 		cur_fsys = fsys;
530 	}
531 #endif
532 	i = 0;
533 	width = charsperline();
534 	/*
535 	* Allocate space for superblock, cylinder group map, and two sets of
536 	* inode blocks.
537 	*/
538 	if (sblock.fs_bsize < SBLOCKSIZE)
539 		iobufsize = SBLOCKSIZE + 3 * sblock.fs_bsize;
540 	else
541 		iobufsize = 4 * sblock.fs_bsize;
542 	if ((iobuf = malloc(iobufsize)) == 0)
543 		errx(38, "cannot allocate I/O buffer");
544 	bzero(iobuf, iobufsize);
545 	/*
546 	 * Make a copy of the superblock into the buffer that we will be
547 	 * writing out in each cylinder group.
548 	 */
549 	bcopy((char *)&sblock, iobuf, SBLOCKSIZE);
550 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
551 		cur_cylno = (sig_atomic_t)cylno;
552 		initcg(cylno, utime);
553 		if (quiet)
554 			continue;
555 		j = snprintf(tmpbuf, sizeof tmpbuf, " %lld,",
556 		    fsbtodb(&sblock, cgsblock(&sblock, cylno)));
557 		if (j >= sizeof tmpbuf)
558 			j = sizeof tmpbuf - 1;
559 		if (j == -1 || i+j >= width) {
560 			printf("\n");
561 			i = 0;
562 		}
563 		i += j;
564 		printf("%s", tmpbuf);
565 		fflush(stdout);
566 	}
567 	if (!quiet)
568 		printf("\n");
569 	if (Nflag && !mfs)
570 		exit(0);
571 	/*
572 	 * Now construct the initial file system, then write out the superblock.
573 	 */
574 	if (Oflag <= 1) {
575 		if (fsinit1(utime, mfsmode, mfsuid, mfsgid))
576 			errx(32, "fsinit1 failed");
577 		sblock.fs_ffs1_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
578 		sblock.fs_ffs1_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
579 		sblock.fs_ffs1_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
580 		sblock.fs_ffs1_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
581 	} else {
582 		if (fsinit2(utime))
583 			errx(32, "fsinit2 failed");
584 	}
585 
586 	wtfs((int)sblock.fs_sblockloc / DEV_BSIZE, SBSIZE, (char *)&sblock);
587 
588 	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
589 		wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
590 		    sblock.fs_cssize - i < sblock.fs_bsize ?
591 		    sblock.fs_cssize - i : sblock.fs_bsize,
592 		    ((char *)fscs) + i);
593 
594 	/*
595 	 * Update information about this partion in pack label, to that it may
596 	 * be updated on disk.
597 	 */
598 	pp->p_fstype = FS_BSDFFS;
599 	pp->p_fragblock =
600 	    DISKLABELV1_FFS_FRAGBLOCK(sblock.fs_fsize, sblock.fs_frag);
601 	pp->p_cpg = sblock.fs_cpg;
602 }
603 
604 /*
605  * Initialize a cylinder group.
606  */
607 void
608 initcg(int cylno, time_t utime)
609 {
610 	int i, j, d, dlower, dupper, blkno, start;
611 	daddr64_t cbase, dmax;
612 	struct ufs1_dinode *dp1;
613 	struct ufs2_dinode *dp2;
614 	struct csum *cs;
615 
616 	/*
617 	 * Determine block bounds for cylinder group.  Allow space for
618 	 * super block summary information in first cylinder group.
619 	 */
620 	cbase = cgbase(&sblock, cylno);
621 	dmax = cbase + sblock.fs_fpg;
622 	if (dmax > sblock.fs_size)
623 		dmax = sblock.fs_size;
624 	if (fsbtodb(&sblock, cgsblock(&sblock, cylno)) + iobufsize / sectorsize
625 	    > fssize)
626 		errx(40, "inode table does not fit in cylinder group");
627 
628 	dlower = cgsblock(&sblock, cylno) - cbase;
629 	dupper = cgdmin(&sblock, cylno) - cbase;
630 	if (cylno == 0)
631 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
632 	cs = &fscs[cylno];
633 	memset(&acg, 0, sblock.fs_cgsize);
634 	acg.cg_ffs2_time = utime;
635 	acg.cg_magic = CG_MAGIC;
636 	acg.cg_cgx = cylno;
637 	acg.cg_ffs2_niblk = sblock.fs_ipg;
638 	acg.cg_initediblk = MIN(sblock.fs_ipg, 2 * INOPB(&sblock));
639 	acg.cg_ndblk = dmax - cbase;
640 
641 	start = sizeof(struct cg);
642 	if (Oflag <= 1) {
643 		/* Hack to maintain compatibility with old fsck. */
644 		if (cylno == sblock.fs_ncg - 1)
645 			acg.cg_ncyl = 0;
646 		else
647 			acg.cg_ncyl = sblock.fs_cpg;
648 		acg.cg_time = acg.cg_ffs2_time;
649 		acg.cg_ffs2_time = 0;
650 		acg.cg_niblk = acg.cg_ffs2_niblk;
651 		acg.cg_ffs2_niblk = 0;
652 		acg.cg_initediblk = 0;
653 		acg.cg_btotoff = start;
654 		acg.cg_boff = acg.cg_btotoff + sblock.fs_cpg * sizeof(int32_t);
655 		acg.cg_iusedoff = acg.cg_boff +
656 		    sblock.fs_cpg * sizeof(u_int16_t);
657 	} else {
658 		acg.cg_iusedoff = start;
659 	}
660 
661 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
662 	acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT);
663 	if (acg.cg_nextfreeoff > sblock.fs_cgsize)
664 		errx(37, "panic: cylinder group too big: %d > %d",
665 		    acg.cg_nextfreeoff, sblock.fs_cgsize);
666 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
667 	if (cylno == 0) {
668 		for (i = 0; i < ROOTINO; i++) {
669 			setbit(cg_inosused(&acg), i);
670 			acg.cg_cs.cs_nifree--;
671 		}
672 	}
673 	if (cylno > 0) {
674 		/*
675 		 * In cylno 0, space is reserved for boot and super blocks.
676 		 */
677 		for (d = 0; d < dlower; d += sblock.fs_frag) {
678 			blkno = d / sblock.fs_frag;
679 			setblock(&sblock, cg_blksfree(&acg), blkno);
680 			acg.cg_cs.cs_nbfree++;
681 			if (Oflag <= 1) {
682 				cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
683 				cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
684 				    [cbtorpos(&sblock, d)]++;
685 			}
686 		}
687 	}
688 	if ((i = dupper % sblock.fs_frag)) {
689 		acg.cg_frsum[sblock.fs_frag - i]++;
690 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
691 			setbit(cg_blksfree(&acg), dupper);
692 			acg.cg_cs.cs_nffree++;
693 		}
694 	}
695 	for (d = dupper;
696 	    d + sblock.fs_frag <= acg.cg_ndblk;
697 	    d += sblock.fs_frag) {
698 		blkno = d / sblock.fs_frag;
699 		setblock(&sblock, cg_blksfree(&acg), blkno);
700 		acg.cg_cs.cs_nbfree++;
701 		if (Oflag <= 1) {
702 			cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
703 			cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
704 			    [cbtorpos(&sblock, d)]++;
705 		}
706 	}
707 	if (d < acg.cg_ndblk) {
708 		acg.cg_frsum[acg.cg_ndblk - d]++;
709 		for (; d < acg.cg_ndblk; d++) {
710 			setbit(cg_blksfree(&acg), d);
711 			acg.cg_cs.cs_nffree++;
712 		}
713 	}
714 	*cs = acg.cg_cs;
715 
716 	/*
717 	 * Write out the duplicate superblock, the cylinder group map
718 	 * and two blocks worth of inodes in a single write.
719 	 */
720 	start = sblock.fs_bsize > SBLOCKSIZE ? sblock.fs_bsize : SBLOCKSIZE;
721 	bcopy((char *)&acg, &iobuf[start], sblock.fs_cgsize);
722 	start += sblock.fs_bsize;
723 	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
724 	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
725 	for (i = MIN(sblock.fs_ipg, 2 * INOPB(&sblock)); i != 0; i--) {
726 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
727 			dp1->di_gen = (u_int32_t)arc4random();
728 			dp1++;
729 		} else {
730 			dp2->di_gen = (u_int32_t)arc4random();
731 			dp2++;
732 		}
733 	}
734 	wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)), iobufsize, iobuf);
735 
736 	if (Oflag <= 1) {
737 		/* Initialize inodes for FFS1. */
738 		for (i = 2 * sblock.fs_frag;
739 		    i < sblock.fs_ipg / INOPF(&sblock);
740 		    i += sblock.fs_frag) {
741 			dp1 = (struct ufs1_dinode *)(&iobuf[start]);
742 			for (j = 0; j < INOPB(&sblock); j++) {
743 				dp1->di_gen = (u_int32_t)arc4random();
744 				dp1++;
745 			}
746 			wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
747 			    sblock.fs_bsize, &iobuf[start]);
748 		}
749 	}
750 }
751 
752 #define PREDEFDIR 2
753 
754 struct direct root_dir[] = {
755 	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
756 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
757 };
758 struct odirect {
759 	u_int32_t d_ino;
760 	u_int16_t d_reclen;
761 	u_int16_t d_namlen;
762 	u_char	d_name[MAXNAMLEN + 1];
763 } oroot_dir[] = {
764 	{ ROOTINO, sizeof(struct direct), 1, "." },
765 	{ ROOTINO, sizeof(struct direct), 2, ".." },
766 };
767 
768 int
769 fsinit1(time_t utime, mode_t mfsmode, uid_t mfsuid, gid_t mfsgid)
770 {
771 	union dinode node;
772 
773 	/*
774 	 * Initialize the node
775 	 */
776 	memset(&node, 0, sizeof(node));
777 	node.dp1.di_atime = utime;
778 	node.dp1.di_mtime = utime;
779 	node.dp1.di_ctime = utime;
780 
781 	/*
782 	 * Create the root directory.
783 	 */
784 	if (mfs) {
785 		node.dp1.di_mode = IFDIR | mfsmode;
786 		node.dp1.di_uid = mfsuid;
787 		node.dp1.di_gid = mfsgid;
788 	} else {
789 		node.dp1.di_mode = IFDIR | UMASK;
790 		node.dp1.di_uid = geteuid();
791 		node.dp1.di_gid = getegid();
792 	}
793 	node.dp1.di_nlink = PREDEFDIR;
794 	if (Oflag == 0)
795 		node.dp1.di_size = makedir((struct direct *)oroot_dir,
796 		    PREDEFDIR);
797 	else
798 		node.dp1.di_size = makedir(root_dir, PREDEFDIR);
799 	node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
800 	if (node.dp1.di_db[0] == 0)
801 		return (1);
802 
803 	node.dp1.di_blocks = btodb(fragroundup(&sblock, node.dp1.di_size));
804 
805 	wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize, iobuf);
806 	iput(&node, ROOTINO);
807 
808 #ifdef notyet
809 	/*
810 	* Create the .snap directory.
811 	*/
812 	node.dp1.di_mode |= 020;
813 	node.dp1.di_gid = gid;
814 	node.dp1.di_nlink = SNAPLINKCNT;
815 	node.dp1.di_size = makedir(snap_dir, SNAPLINKCNT);
816 
817 	node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
818 	if (node.dp1.di_db[0] == 0)
819 		return (1);
820 
821 	node.dp1.di_blocks = btodb(fragroundup(&sblock, node.dp1.di_size));
822 
823 	wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize, iobuf);
824 	iput(&node, ROOTINO + 1);
825 #endif
826 	return (0);
827 }
828 
829 int
830 fsinit2(time_t utime)
831 {
832 	union dinode node;
833 
834 	/*
835 	 * Initialize the node.
836 	 */
837 	memset(&node, 0, sizeof(node));
838 	node.dp2.di_atime = utime;
839 	node.dp2.di_mtime = utime;
840 	node.dp2.di_ctime = utime;
841 
842 	/*
843 	 * Create the root directory.
844 	 */
845 	node.dp2.di_mode = IFDIR | UMASK;
846 	node.dp2.di_uid = geteuid();
847 	node.dp2.di_gid = getegid();
848 	node.dp2.di_nlink = PREDEFDIR;
849 	node.dp2.di_size = makedir(root_dir, PREDEFDIR);
850 
851 	node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
852 	if (node.dp2.di_db[0] == 0)
853 		return (1);
854 
855 	node.dp2.di_blocks = btodb(fragroundup(&sblock, node.dp2.di_size));
856 
857 	wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize, iobuf);
858 	iput(&node, ROOTINO);
859 
860 #ifdef notyet
861 	/*
862 	 * Create the .snap directory.
863 	 */
864 	node.dp2.di_mode |= 020;
865 	node.dp2.di_gid = gid;
866 	node.dp2.di_nlink = SNAPLINKCNT;
867 	node.dp2.di_size = makedir(snap_dir, SNAPLINKCNT);
868 
869 	node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
870 	if (node.dp2.di_db[0] == 0)
871 		return (1);
872 
873 	node.dp2.di_blocks = btodb(fragroundup(&sblock, node.dp2.di_size));
874 
875 	wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize, iobuf);
876 	iput(&node, ROOTINO + 1);
877 #endif
878 	return (0);
879 }
880 
881 /*
882  * construct a set of directory entries in "buf".
883  * return size of directory.
884  */
885 int
886 makedir(struct direct *protodir, int entries)
887 {
888 	char *cp;
889 	int i, spcleft;
890 
891 	spcleft = DIRBLKSIZ;
892 	for (cp = iobuf, i = 0; i < entries - 1; i++) {
893 		protodir[i].d_reclen = DIRSIZ(0, &protodir[i]);
894 		memcpy(cp, &protodir[i], protodir[i].d_reclen);
895 		cp += protodir[i].d_reclen;
896 		spcleft -= protodir[i].d_reclen;
897 	}
898 	protodir[i].d_reclen = spcleft;
899 	memcpy(cp, &protodir[i], DIRSIZ(0, &protodir[i]));
900 	return (DIRBLKSIZ);
901 }
902 
903 /*
904  * allocate a block or frag
905  */
906 daddr64_t
907 alloc(int size, int mode)
908 {
909 	int i, frag;
910 	daddr64_t d, blkno;
911 
912 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
913 	    (char *)&acg);
914 	if (acg.cg_magic != CG_MAGIC) {
915 		warnx("cg 0: bad magic number");
916 		return (0);
917 	}
918 	if (acg.cg_cs.cs_nbfree == 0) {
919 		warnx("first cylinder group ran out of space");
920 		return (0);
921 	}
922 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
923 		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
924 			goto goth;
925 	warnx("internal error: can't find block in cyl 0");
926 	return (0);
927 goth:
928 	blkno = fragstoblks(&sblock, d);
929 	clrblock(&sblock, cg_blksfree(&acg), blkno);
930 	acg.cg_cs.cs_nbfree--;
931 	sblock.fs_cstotal.cs_nbfree--;
932 	fscs[0].cs_nbfree--;
933 	if (mode & IFDIR) {
934 		acg.cg_cs.cs_ndir++;
935 		sblock.fs_cstotal.cs_ndir++;
936 		fscs[0].cs_ndir++;
937 	}
938 	if (Oflag <= 1) {
939 		cg_blktot(&acg)[cbtocylno(&sblock, d)]--;
940 		cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
941 		    [cbtorpos(&sblock, d)]--;
942 	}
943 	if (size != sblock.fs_bsize) {
944 		frag = howmany(size, sblock.fs_fsize);
945 		fscs[0].cs_nffree += sblock.fs_frag - frag;
946 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
947 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
948 		acg.cg_frsum[sblock.fs_frag - frag]++;
949 		for (i = frag; i < sblock.fs_frag; i++)
950 			setbit(cg_blksfree(&acg), d + i);
951 	}
952 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
953 	    (char *)&acg);
954 	return (d);
955 }
956 
957 /*
958  * Allocate an inode on the disk
959  */
960 void
961 iput(union dinode *ip, ino_t ino)
962 {
963 	daddr64_t d;
964 
965 	if (Oflag <= 1)
966 		ip->dp1.di_gen = (u_int32_t)arc4random();
967 	else
968 		ip->dp2.di_gen = (u_int32_t)arc4random();
969 
970 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
971 	    (char *)&acg);
972 	if (acg.cg_magic != CG_MAGIC)
973 		errx(41, "cg 0: bad magic number");
974 
975 	acg.cg_cs.cs_nifree--;
976 	setbit(cg_inosused(&acg), ino);
977 
978 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
979 	    (char *)&acg);
980 
981 	sblock.fs_cstotal.cs_nifree--;
982 	fscs[0].cs_nifree--;
983 	if (ino >= sblock.fs_ipg * sblock.fs_ncg)
984 		errx(32, "fsinit: inode value %d out of range", ino);
985 	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
986 	rdfs(d, sblock.fs_bsize, iobuf);
987 
988 	if (Oflag <= 1)
989 		((struct ufs1_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
990 		    ip->dp1;
991 	else
992 		((struct ufs2_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
993 		    ip->dp2;
994 
995 	wtfs(d, sblock.fs_bsize, iobuf);
996 }
997 
998 /*
999  * read a block from the file system
1000  */
1001 void
1002 rdfs(daddr64_t bno, int size, void *bf)
1003 {
1004 	int n;
1005 
1006 	if (mfs) {
1007 		memcpy(bf, membase + bno * DEV_BSIZE, size);
1008 		return;
1009 	}
1010 	n = pread(fsi, bf, size, (off_t)bno * DEV_BSIZE);
1011 	if (n != size) {
1012 		err(34, "rdfs: read error on block %lld", bno);
1013 	}
1014 }
1015 
1016 /*
1017  * write a block to the file system
1018  */
1019 void
1020 wtfs(daddr64_t bno, int size, void *bf)
1021 {
1022 	int n;
1023 
1024 	if (mfs) {
1025 		memcpy(membase + bno * DEV_BSIZE, bf, size);
1026 		return;
1027 	}
1028 	if (Nflag)
1029 		return;
1030 	n = pwrite(fso, bf, size, (off_t)bno * DEV_BSIZE);
1031 	if (n != size) {
1032 		err(36, "wtfs: write error on block %lld", bno);
1033 	}
1034 }
1035 
1036 /*
1037  * check if a block is available
1038  */
1039 int
1040 isblock(struct fs *fs, unsigned char *cp, int h)
1041 {
1042 	unsigned char mask;
1043 
1044 	switch (fs->fs_frag) {
1045 	case 8:
1046 		return (cp[h] == 0xff);
1047 	case 4:
1048 		mask = 0x0f << ((h & 0x1) << 2);
1049 		return ((cp[h >> 1] & mask) == mask);
1050 	case 2:
1051 		mask = 0x03 << ((h & 0x3) << 1);
1052 		return ((cp[h >> 2] & mask) == mask);
1053 	case 1:
1054 		mask = 0x01 << (h & 0x7);
1055 		return ((cp[h >> 3] & mask) == mask);
1056 	default:
1057 #ifdef STANDALONE
1058 		printf("isblock bad fs_frag %d\n", fs->fs_frag);
1059 #else
1060 		warnx("isblock bad fs_frag %d", fs->fs_frag);
1061 #endif
1062 		return (0);
1063 	}
1064 }
1065 
1066 /*
1067  * take a block out of the map
1068  */
1069 void
1070 clrblock(struct fs *fs, unsigned char *cp, int h)
1071 {
1072 	switch ((fs)->fs_frag) {
1073 	case 8:
1074 		cp[h] = 0;
1075 		return;
1076 	case 4:
1077 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1078 		return;
1079 	case 2:
1080 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1081 		return;
1082 	case 1:
1083 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
1084 		return;
1085 	default:
1086 #ifdef STANDALONE
1087 		printf("clrblock bad fs_frag %d\n", fs->fs_frag);
1088 #else
1089 		warnx("clrblock bad fs_frag %d", fs->fs_frag);
1090 #endif
1091 		return;
1092 	}
1093 }
1094 
1095 /*
1096  * put a block into the map
1097  */
1098 void
1099 setblock(struct fs *fs, unsigned char *cp, int h)
1100 {
1101 	switch (fs->fs_frag) {
1102 	case 8:
1103 		cp[h] = 0xff;
1104 		return;
1105 	case 4:
1106 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1107 		return;
1108 	case 2:
1109 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1110 		return;
1111 	case 1:
1112 		cp[h >> 3] |= (0x01 << (h & 0x7));
1113 		return;
1114 	default:
1115 #ifdef STANDALONE
1116 		printf("setblock bad fs_frag %d\n", fs->fs_frag);
1117 #else
1118 		warnx("setblock bad fs_frag %d", fs->fs_frag);
1119 #endif
1120 		return;
1121 	}
1122 }
1123 
1124 /*
1125  * Determine the number of characters in a
1126  * single line.
1127  */
1128 static int
1129 charsperline(void)
1130 {
1131 	int columns;
1132 	char *cp;
1133 	struct winsize ws;
1134 
1135 	columns = 0;
1136 	if (ioctl(0, TIOCGWINSZ, &ws) != -1)
1137 		columns = ws.ws_col;
1138 	if (columns == 0 && (cp = getenv("COLUMNS")))
1139 		columns = atoi(cp);
1140 	if (columns == 0)
1141 		columns = 80;   /* last resort */
1142 	return columns;
1143 }
1144 
1145 static int
1146 ilog2(int val)
1147 {
1148 	int n;
1149 
1150 	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
1151 		if (1 << n == val)
1152 			return (n);
1153 
1154 	errx(1, "ilog2: %d is not a power of 2\n", val);
1155 }
1156