summaryrefslogtreecommitdiff
path: root/sbin/newfs/mkfs.c
blob: 45a16a96a9c10c8c3327cf8d1d034f5fafcaa477 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
/*	$OpenBSD: mkfs.c,v 1.86 2014/06/30 19:19:17 otto Exp $	*/
/*	$NetBSD: mkfs.c,v 1.25 1995/06/18 21:35:38 cgd Exp $	*/

/*
 * Copyright (c) 2002 Networks Associates Technology, Inc.
 * All rights reserved.
 *
 * This software was developed for the FreeBSD Project by Marshall
 * Kirk McKusick and Network Associates Laboratories, the Security
 * Research Division of Network Associates, Inc. under DARPA/SPAWAR
 * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
 * research program.
 *
 * Copyright (c) 1980, 1989, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/param.h>
#include <sys/time.h>
#include <sys/disklabel.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/sysctl.h>

#include <ufs/ufs/dinode.h>
#include <ufs/ufs/dir.h>
#include <ufs/ffs/fs.h>

#include <err.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>

#ifndef STANDALONE
#include <a.out.h>
#include <stdio.h>
#include <errno.h>
#endif

/*
 * Default directory umask.
 */
#define UMASK		0755

#define POWEROF2(num)	(((num) & ((num) - 1)) == 0)

/*
 * 'Standard' bad FFS magic.
 */
#define FS_BAD_MAGIC	0x19960408

/*
 * The minimum number of cylinder groups that should be created.
 */
#define MINCYLGRPS	4

/*
 * variables set up by front end.
 */
extern int	mfs;		/* run as the memory based filesystem */
extern int	Nflag;		/* run mkfs without writing file system */
extern int	Oflag;		/* format as an 4.3BSD file system */
extern daddr_t fssize;		/* file system size in 512-byte blocks. */
extern long long	sectorsize;	/* bytes/sector */
extern int	fsize;		/* fragment size */
extern int	bsize;		/* block size */
extern int	maxfrgspercg;	/* maximum fragments per cylinder group */
extern int	minfree;	/* free space threshold */
extern int	opt;		/* optimization preference (space or time) */
extern int	density;	/* number of bytes per inode */
extern int	maxbpg;		/* maximum blocks per file in a cyl group */
extern int	avgfilesize;	/* expected average file size */
extern int	avgfilesperdir;	/* expected number of files per directory */
extern int	quiet;		/* quiet flag */
extern caddr_t	membase;	/* start address of memory based filesystem */

union fs_u {
	struct fs fs;
	char pad[SBSIZE];
} *fsun;
#define sblock	fsun->fs

struct	csum *fscs;

union cg_u {
	struct cg cg;
	char pad[MAXBSIZE];
} *cgun;
#define acg	cgun->cg

union dinode {
	struct ufs1_dinode dp1;
	struct ufs2_dinode dp2;
};

int	fsi, fso;

static caddr_t iobuf;
static long iobufsize;

daddr_t	alloc(int, int);
static int	charsperline(void);
static int	ilog2(int);
void		initcg(int, time_t);
void		wtfs(daddr_t, int, void *);
int		fsinit1(time_t, mode_t, uid_t, gid_t);
int		fsinit2(time_t);
int		makedir(struct direct *, int);
void		iput(union dinode *, ino_t);
void		setblock(struct fs *, unsigned char *, int);
void		clrblock(struct fs *, unsigned char *, int);
int		isblock(struct fs *, unsigned char *, int);
void		rdfs(daddr_t, int, void *);
void		mkfs(struct partition *, char *, int, int,
		    mode_t, uid_t, gid_t);
static		void checksz(void);

#ifndef STANDALONE
volatile sig_atomic_t cur_cylno;
volatile const char *cur_fsys;
void	siginfo(int sig);

void
siginfo(int sig)
{
	int save_errno = errno;
	char buf[128];

	snprintf(buf, sizeof(buf), "%s: initializing cg %ld/%d\n",
	    cur_fsys, (long)cur_cylno, sblock.fs_ncg);
	write(STDERR_FILENO, buf, strlen(buf));
	errno = save_errno;
}
#endif

void
mkfs(struct partition *pp, char *fsys, int fi, int fo, mode_t mfsmode,
    uid_t mfsuid, gid_t mfsgid)
{
	time_t utime;
	quad_t sizepb;
	int i, j, width, origdensity, fragsperinode, minfpg, optimalfpg;
	int lastminfpg, mincylgrps;
	long cylno, csfrags;
	char tmpbuf[100];	/* XXX this will break in about 2,500 years */

	if ((fsun = calloc(1, sizeof (union fs_u))) == NULL ||
	    (cgun = calloc(1, sizeof (union cg_u))) == NULL)
		err(1, "calloc");

#ifndef STANDALONE
	time(&utime);
#endif
	if (mfs) {
		quad_t sz = (quad_t)fssize * DEV_BSIZE;
		if (sz > SIZE_T_MAX) {
			errno = ENOMEM;
			err(12, "mmap");
		}
		membase = mmap(NULL, sz, PROT_READ|PROT_WRITE,
		    MAP_ANON|MAP_PRIVATE, -1, (off_t)0);
		if (membase == MAP_FAILED)
			err(12, "mmap");
		madvise(membase, sz, MADV_RANDOM);
	}
	fsi = fi;
	fso = fo;
	/*
	 * Validate the given file system size.
	 * Verify that its last block can actually be accessed.
	 */
	if (Oflag <= 1 && fssize > INT_MAX)
		errx(13, "preposterous size %lld, max is %d", (long long)fssize,
		    INT_MAX);
	if (Oflag == 2 && fssize > MAXDISKSIZE)
		errx(13, "preposterous size %lld, max is %lld",
		    (long long)fssize, MAXDISKSIZE);

	wtfs(fssize - (sectorsize / DEV_BSIZE), sectorsize, (char *)&sblock);

	sblock.fs_postblformat = FS_DYNAMICPOSTBLFMT;
	sblock.fs_avgfilesize = avgfilesize;
	sblock.fs_avgfpdir = avgfilesperdir;

	/*
	 * Collect and verify the block and fragment sizes.
	 */
	if (!POWEROF2(bsize)) {
		errx(16, "block size must be a power of 2, not %d", bsize);
	}
	if (!POWEROF2(fsize)) {
		errx(17, "fragment size must be a power of 2, not %d",
		     fsize);
	}
	if (fsize < sectorsize) {
		errx(18, "fragment size %d is too small, minimum is %lld",
		     fsize, sectorsize);
	}
	if (bsize < MINBSIZE) {
		errx(19, "block size %d is too small, minimum is %d",
		     bsize, MINBSIZE);
	}
	if (bsize > MAXBSIZE) {
		errx(19, "block size %d is too large, maximum is %d",
		     bsize, MAXBSIZE);
	}
	if (bsize < fsize) {
		errx(20, "block size (%d) cannot be smaller than fragment size (%d)",
		     bsize, fsize);
	}
	sblock.fs_bsize = bsize;
	sblock.fs_fsize = fsize;

	/*
	 * Calculate the superblock bitmasks and shifts.
	 */
	sblock.fs_bmask = ~(sblock.fs_bsize - 1);
	sblock.fs_fmask = ~(sblock.fs_fsize - 1);
	sblock.fs_qbmask = ~sblock.fs_bmask;
	sblock.fs_qfmask = ~sblock.fs_fmask;
	sblock.fs_bshift = ilog2(sblock.fs_bsize);
	sblock.fs_fshift = ilog2(sblock.fs_fsize);
	sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
	if (sblock.fs_frag > MAXFRAG) {
		errx(21, "fragment size %d is too small, minimum with block "
		    "size %d is %d", sblock.fs_fsize, sblock.fs_bsize,
		    sblock.fs_bsize / MAXFRAG);
	}
	sblock.fs_fragshift = ilog2(sblock.fs_frag);
	sblock.fs_fsbtodb = ilog2(sblock.fs_fsize / DEV_BSIZE);
	sblock.fs_size = dbtofsb(&sblock, fssize);
	sblock.fs_nspf = sblock.fs_fsize / DEV_BSIZE;
	sblock.fs_maxcontig = 1;
	sblock.fs_nrpos = 1;
	sblock.fs_cpg = 1;

	/*
	 * Before the file system is fully initialized, mark it as invalid.
	 */
	sblock.fs_magic = FS_BAD_MAGIC;

	/*
	 * Set the remaining superblock fields.  Note that for FFS1, media
	 * geometry fields are set to fake values.  This is for compatibility
	 * with really ancient kernels that might still inspect these values.
	 */
	if (Oflag <= 1) {
		sblock.fs_sblockloc = SBLOCK_UFS1;
		sblock.fs_nindir = sblock.fs_bsize / sizeof(int32_t);
		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
		if (Oflag == 0) {
			sblock.fs_maxsymlinklen = 0;
			sblock.fs_inodefmt = FS_42INODEFMT;
		} else {
			sblock.fs_maxsymlinklen = MAXSYMLINKLEN_UFS1;
			sblock.fs_inodefmt = FS_44INODEFMT;
		}
		sblock.fs_cgoffset = 0;
		sblock.fs_cgmask = 0xffffffff;
		sblock.fs_ffs1_size = sblock.fs_size;
		sblock.fs_rotdelay = 0;
		sblock.fs_rps = 60;
		sblock.fs_interleave = 1;
		sblock.fs_trackskew = 0;
		sblock.fs_cpc = 0;
	} else {
		sblock.fs_inodefmt = FS_44INODEFMT;
		sblock.fs_sblockloc = SBLOCK_UFS2;
		sblock.fs_nindir = sblock.fs_bsize / sizeof(int64_t);
		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs2_dinode);
		sblock.fs_maxsymlinklen = MAXSYMLINKLEN_UFS2;
	}
	sblock.fs_sblkno =
	    roundup(howmany(sblock.fs_sblockloc + SBLOCKSIZE, sblock.fs_fsize),
		sblock.fs_frag);
	sblock.fs_cblkno = (int32_t)(sblock.fs_sblkno +
	    roundup(howmany(SBSIZE, sblock.fs_fsize), sblock.fs_frag));
	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
	sblock.fs_maxfilesize = sblock.fs_bsize * NDADDR - 1;
	for (sizepb = sblock.fs_bsize, i = 0; i < NIADDR; i++) {
		sizepb *= NINDIR(&sblock);
		sblock.fs_maxfilesize += sizepb;
	}
#ifdef notyet
	/*
	 * It is impossible to create a snapshot in case fs_maxfilesize is
	 * smaller than fssize.
	 */
	if (sblock.fs_maxfilesize < (u_quad_t)fssize)
		warnx("WARNING: You will be unable to create snapshots on this "
		    "file system. Correct by using a larger blocksize.");
#endif
	/*
	 * Calculate the number of blocks to put into each cylinder group. The
	 * first goal is to have at least enough data blocks in each cylinder
	 * group to meet the density requirement. Once this goal is achieved
	 * we try to expand to have at least mincylgrps cylinder groups. Once
	 * this goal is achieved, we pack as many blocks into each cylinder
	 * group map as will fit.
	 *
	 * We start by calculating the smallest number of blocks that we can
	 * put into each cylinder group. If this is too big, we reduce the
	 * density until it fits.
	 */
	origdensity = density;
	for (;;) {
		fragsperinode = MAX(numfrags(&sblock, density), 1);

		minfpg = fragsperinode * INOPB(&sblock);
		if (minfpg > sblock.fs_size)
			minfpg = sblock.fs_size;

		sblock.fs_ipg = INOPB(&sblock);
		sblock.fs_fpg = roundup(sblock.fs_iblkno +
		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
		if (sblock.fs_fpg < minfpg)
			sblock.fs_fpg = minfpg;

		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
		    INOPB(&sblock));
		sblock.fs_fpg = roundup(sblock.fs_iblkno +
		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
		if (sblock.fs_fpg < minfpg)
			sblock.fs_fpg = minfpg;

		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
		    INOPB(&sblock));

		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
			break;

		density -= sblock.fs_fsize;
	}
	if (density != origdensity)
		warnx("density reduced from %d to %d bytes per inode",
		    origdensity, density);

	/*
	 * Use a lower value for mincylgrps if the user specified a large
	 * number of blocks per cylinder group.  This is needed for, e.g. the
	 * install media which needs to pack 2 files very tightly.
	 */
	mincylgrps = MINCYLGRPS;
	if (maxfrgspercg != INT_MAX) {
		i = sblock.fs_size / maxfrgspercg;
		if (i < MINCYLGRPS)
			mincylgrps = i <= 0 ? 1 : i;
	}

	/*
	 * Start packing more blocks into the cylinder group until it cannot
	 * grow any larger, the number of cylinder groups drops below
	 * mincylgrps, or we reach the requested size.
	 */
	for (;;) {
		sblock.fs_fpg += sblock.fs_frag;
		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
		    INOPB(&sblock));

		if (sblock.fs_fpg > maxfrgspercg ||
		    sblock.fs_size / sblock.fs_fpg < mincylgrps ||
		    CGSIZE(&sblock) > (unsigned long)sblock.fs_bsize)
			break;
	}
	sblock.fs_fpg -= sblock.fs_frag;
	sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
	    INOPB(&sblock));
	if (sblock.fs_fpg > maxfrgspercg)
		warnx("can't honour -c: minimum is %d", sblock.fs_fpg);

	/*
	 * Check to be sure that the last cylinder group has enough blocks to
	 * be viable. If it is too small, reduce the number of blocks per
	 * cylinder group which will have the effect of moving more blocks into
	 * the last cylinder group.
	 */
	optimalfpg = sblock.fs_fpg;
	for (;;) {
		sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
		lastminfpg = roundup(sblock.fs_iblkno +
		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
		if (sblock.fs_size < lastminfpg)
			errx(28, "file system size %jd < minimum size of %d "
			    "fragments", (intmax_t)sblock.fs_size, lastminfpg);

		if (sblock.fs_size % sblock.fs_fpg >= lastminfpg ||
		    sblock.fs_size % sblock.fs_fpg == 0)
			break;

		sblock.fs_fpg -= sblock.fs_frag;
		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
		    INOPB(&sblock));
	}

	if (optimalfpg != sblock.fs_fpg)
		warnx("reduced number of fragments per cylinder group from %d"
		    " to %d to enlarge last cylinder group", optimalfpg,
		    sblock.fs_fpg);

	/*
	 * Back to filling superblock fields.
	 */
	if (Oflag <= 1) {
		sblock.fs_spc = sblock.fs_fpg * sblock.fs_nspf;
		sblock.fs_nsect = sblock.fs_spc;
		sblock.fs_npsect = sblock.fs_spc;
		sblock.fs_ncyl = sblock.fs_ncg;
	}
	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
	sblock.fs_csaddr = cgdmin(&sblock, 0);
	sblock.fs_cssize =
	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));

	fscs = (struct csum *)calloc(1, sblock.fs_cssize);
	if (fscs == NULL)
		errx(31, "calloc failed");

	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
	if (sblock.fs_sbsize > SBLOCKSIZE)
		sblock.fs_sbsize = SBLOCKSIZE;

	sblock.fs_minfree = minfree;
	sblock.fs_maxbpg = maxbpg;
	sblock.fs_optim = opt;
	sblock.fs_cgrotor = 0;
	sblock.fs_pendingblocks = 0;
	sblock.fs_pendinginodes = 0;
	sblock.fs_fmod = 0;
	sblock.fs_ronly = 0;
	sblock.fs_state = 0;
	sblock.fs_clean = 1;
	sblock.fs_id[0] = (u_int32_t)utime;
	sblock.fs_id[1] = (u_int32_t)arc4random();
	sblock.fs_fsmnt[0] = '\0';

	csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
	sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
	    sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);

	sblock.fs_cstotal.cs_nbfree = fragstoblks(&sblock, sblock.fs_dsize) -
	    howmany(csfrags, sblock.fs_frag);
	sblock.fs_cstotal.cs_nffree = fragnum(&sblock, sblock.fs_size) +
	    (fragnum(&sblock, csfrags) > 0 ?
	    sblock.fs_frag - fragnum(&sblock, csfrags) : 0);
	sblock.fs_cstotal.cs_nifree = sblock.fs_ncg * sblock.fs_ipg - ROOTINO;
	sblock.fs_cstotal.cs_ndir = 0;

	sblock.fs_dsize -= csfrags;
	sblock.fs_time = utime;

	if (Oflag <= 1) {
		sblock.fs_ffs1_time = sblock.fs_time;
		sblock.fs_ffs1_dsize = sblock.fs_dsize;
		sblock.fs_ffs1_csaddr = sblock.fs_csaddr;
		sblock.fs_ffs1_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
		sblock.fs_ffs1_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
		sblock.fs_ffs1_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
		sblock.fs_ffs1_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
	}

	/*
	 * Dump out summary information about file system.
	 */
	if (!mfs) {
#define B2MBFACTOR (1 / (1024.0 * 1024.0))
		printf("%s: %.1fMB in %jd sectors of %lld bytes\n", fsys,
		    (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
		    (intmax_t)fsbtodb(&sblock, sblock.fs_size) /
		    (sectorsize / DEV_BSIZE), sectorsize);
		printf("%d cylinder groups of %.2fMB, %d blocks, %d"
		    " inodes each\n", sblock.fs_ncg,
		    (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
		    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
#undef B2MBFACTOR
		checksz();
	}

	/*
	 * Wipe out old FFS1 superblock if necessary.
	 */
	if (Oflag >= 2) {
		union fs_u *fsun1;
		struct fs *fs1;

		fsun1 = calloc(1, sizeof(union fs_u));
		if (fsun1 == NULL)
			err(39, "calloc");
		fs1 = &fsun1->fs;
		rdfs(SBLOCK_UFS1 / DEV_BSIZE, SBSIZE, (char *)fs1);
		if (fs1->fs_magic == FS_UFS1_MAGIC) {
			fs1->fs_magic = FS_BAD_MAGIC;
			wtfs(SBLOCK_UFS1 / DEV_BSIZE, SBSIZE, (char *)fs1);
		}
		free(fsun1);
	}

	wtfs((int)sblock.fs_sblockloc / DEV_BSIZE, SBSIZE, (char *)&sblock);
	sblock.fs_magic = (Oflag <= 1) ? FS_UFS1_MAGIC : FS_UFS2_MAGIC;

	/*
	 * Now build the cylinders group blocks and
	 * then print out indices of cylinder groups.
	 */
	if (!quiet)
		printf("super-block backups (for fsck -b #) at:\n");
#ifndef STANDALONE
	else if (!mfs && isatty(STDIN_FILENO)) {
		signal(SIGINFO, siginfo);
		cur_fsys = fsys;
	}
#endif
	i = 0;
	width = charsperline();
	/*
	* Allocate space for superblock, cylinder group map, and two sets of
	* inode blocks.
	*/
	if (sblock.fs_bsize < SBLOCKSIZE)
		iobufsize = SBLOCKSIZE + 3 * sblock.fs_bsize;
	else
		iobufsize = 4 * sblock.fs_bsize;
	if ((iobuf = malloc(iobufsize)) == 0)
		errx(38, "cannot allocate I/O buffer");
	bzero(iobuf, iobufsize);
	/*
	 * Make a copy of the superblock into the buffer that we will be
	 * writing out in each cylinder group.
	 */
	bcopy((char *)&sblock, iobuf, SBLOCKSIZE);
	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
		cur_cylno = (sig_atomic_t)cylno;
		initcg(cylno, utime);
		if (quiet)
			continue;
		j = snprintf(tmpbuf, sizeof tmpbuf, " %lld,",
		    (long long)fsbtodb(&sblock, cgsblock(&sblock, cylno)));
		if (j >= sizeof tmpbuf)
			j = sizeof tmpbuf - 1;
		if (j == -1 || i+j >= width) {
			printf("\n");
			i = 0;
		}
		i += j;
		printf("%s", tmpbuf);
		fflush(stdout);
	}
	if (!quiet)
		printf("\n");
	if (Nflag && !mfs)
		exit(0);
	/*
	 * Now construct the initial file system, then write out the superblock.
	 */
	if (Oflag <= 1) {
		if (fsinit1(utime, mfsmode, mfsuid, mfsgid))
			errx(32, "fsinit1 failed");
		sblock.fs_ffs1_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
		sblock.fs_ffs1_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
		sblock.fs_ffs1_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
		sblock.fs_ffs1_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
	} else {
		if (fsinit2(utime))
			errx(32, "fsinit2 failed");
	}

	wtfs((int)sblock.fs_sblockloc / DEV_BSIZE, SBSIZE, (char *)&sblock);

	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
		wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
		    sblock.fs_cssize - i < sblock.fs_bsize ?
		    sblock.fs_cssize - i : sblock.fs_bsize,
		    ((char *)fscs) + i);

	/*
	 * Update information about this partition in pack label, to that it may
	 * be updated on disk.
	 */
	pp->p_fstype = FS_BSDFFS;
	pp->p_fragblock =
	    DISKLABELV1_FFS_FRAGBLOCK(sblock.fs_fsize, sblock.fs_frag);
	pp->p_cpg = sblock.fs_cpg;
}

/*
 * Initialize a cylinder group.
 */
void
initcg(int cylno, time_t utime)
{
	int i, j, d, dlower, dupper, blkno, start;
	daddr_t cbase, dmax;
	struct ufs1_dinode *dp1;
	struct ufs2_dinode *dp2;
	struct csum *cs;

	/*
	 * Determine block bounds for cylinder group.  Allow space for
	 * super block summary information in first cylinder group.
	 */
	cbase = cgbase(&sblock, cylno);
	dmax = cbase + sblock.fs_fpg;
	if (dmax > sblock.fs_size)
		dmax = sblock.fs_size;
	if (fsbtodb(&sblock, cgsblock(&sblock, cylno)) + iobufsize / DEV_BSIZE 
	    > fssize)
		errx(40, "inode table does not fit in cylinder group");

	dlower = cgsblock(&sblock, cylno) - cbase;
	dupper = cgdmin(&sblock, cylno) - cbase;
	if (cylno == 0)
		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
	cs = &fscs[cylno];
	memset(&acg, 0, sblock.fs_cgsize);
	acg.cg_ffs2_time = utime;
	acg.cg_magic = CG_MAGIC;
	acg.cg_cgx = cylno;
	acg.cg_ffs2_niblk = sblock.fs_ipg;
	acg.cg_initediblk = MIN(sblock.fs_ipg, 2 * INOPB(&sblock));
	acg.cg_ndblk = dmax - cbase;

	start = sizeof(struct cg);
	if (Oflag <= 1) {
		/* Hack to maintain compatibility with old fsck. */
		if (cylno == sblock.fs_ncg - 1)
			acg.cg_ncyl = 0;
		else
			acg.cg_ncyl = sblock.fs_cpg;
		acg.cg_time = acg.cg_ffs2_time;
		acg.cg_ffs2_time = 0;
		acg.cg_niblk = acg.cg_ffs2_niblk;
		acg.cg_ffs2_niblk = 0;
		acg.cg_initediblk = 0;
		acg.cg_btotoff = start;
		acg.cg_boff = acg.cg_btotoff + sblock.fs_cpg * sizeof(int32_t);
		acg.cg_iusedoff = acg.cg_boff +
		    sblock.fs_cpg * sizeof(u_int16_t);
	} else {
		acg.cg_iusedoff = start;
	}

	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
	acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT);
	if (acg.cg_nextfreeoff > sblock.fs_cgsize)
		errx(37, "panic: cylinder group too big: %d > %d",
		    acg.cg_nextfreeoff, sblock.fs_cgsize);
	acg.cg_cs.cs_nifree += sblock.fs_ipg;
	if (cylno == 0) {
		for (i = 0; i < ROOTINO; i++) {
			setbit(cg_inosused(&acg), i);
			acg.cg_cs.cs_nifree--;
		}
	}
	if (cylno > 0) {
		/*
		 * In cylno 0, space is reserved for boot and super blocks.
		 */
		for (d = 0; d < dlower; d += sblock.fs_frag) {
			blkno = d / sblock.fs_frag;
			setblock(&sblock, cg_blksfree(&acg), blkno);
			acg.cg_cs.cs_nbfree++;
			if (Oflag <= 1) {
				cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
				cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
				    [cbtorpos(&sblock, d)]++;
			}
		}
	}
	if ((i = dupper % sblock.fs_frag)) {
		acg.cg_frsum[sblock.fs_frag - i]++;
		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
			setbit(cg_blksfree(&acg), dupper);
			acg.cg_cs.cs_nffree++;
		}
	}
	for (d = dupper;
	    d + sblock.fs_frag <= acg.cg_ndblk;
	    d += sblock.fs_frag) {
		blkno = d / sblock.fs_frag;
		setblock(&sblock, cg_blksfree(&acg), blkno);
		acg.cg_cs.cs_nbfree++;
		if (Oflag <= 1) {
			cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
			cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
			    [cbtorpos(&sblock, d)]++;
		}
	}
	if (d < acg.cg_ndblk) {
		acg.cg_frsum[acg.cg_ndblk - d]++;
		for (; d < acg.cg_ndblk; d++) {
			setbit(cg_blksfree(&acg), d);
			acg.cg_cs.cs_nffree++;
		}
	}
	*cs = acg.cg_cs;

	/*
	 * Write out the duplicate superblock, the cylinder group map
	 * and two blocks worth of inodes in a single write.
	 */
	start = sblock.fs_bsize > SBLOCKSIZE ? sblock.fs_bsize : SBLOCKSIZE;
	bcopy((char *)&acg, &iobuf[start], sblock.fs_cgsize);
	start += sblock.fs_bsize;
	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
	for (i = MIN(sblock.fs_ipg, 2 * INOPB(&sblock)); i != 0; i--) {
		if (sblock.fs_magic == FS_UFS1_MAGIC) {
			dp1->di_gen = (u_int32_t)arc4random();
			dp1++;
		} else {
			dp2->di_gen = (u_int32_t)arc4random();
			dp2++;
		}
	}
	wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)), iobufsize, iobuf);

	if (Oflag <= 1) {
		/* Initialize inodes for FFS1. */
		for (i = 2 * sblock.fs_frag;
		    i < sblock.fs_ipg / INOPF(&sblock);
		    i += sblock.fs_frag) {
			dp1 = (struct ufs1_dinode *)(&iobuf[start]);
			for (j = 0; j < INOPB(&sblock); j++) {
				dp1->di_gen = (u_int32_t)arc4random();
				dp1++;
			}
			wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
			    sblock.fs_bsize, &iobuf[start]);
		}
	}
}

#define PREDEFDIR 2

struct direct root_dir[] = {
	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
};
struct odirect {
	u_int32_t d_ino;
	u_int16_t d_reclen;
	u_int16_t d_namlen;
	u_char	d_name[MAXNAMLEN + 1];
} oroot_dir[] = {
	{ ROOTINO, sizeof(struct direct), 1, "." },
	{ ROOTINO, sizeof(struct direct), 2, ".." },
};

int
fsinit1(time_t utime, mode_t mfsmode, uid_t mfsuid, gid_t mfsgid)
{
	union dinode node;

	/*
	 * Initialize the node
	 */
	memset(&node, 0, sizeof(node));
	node.dp1.di_atime = utime;
	node.dp1.di_mtime = utime;
	node.dp1.di_ctime = utime;

	/*
	 * Create the root directory.
	 */
	if (mfs) {
		node.dp1.di_mode = IFDIR | mfsmode;
		node.dp1.di_uid = mfsuid;
		node.dp1.di_gid = mfsgid;
	} else {
		node.dp1.di_mode = IFDIR | UMASK;
		node.dp1.di_uid = geteuid();
		node.dp1.di_gid = getegid();
	}
	node.dp1.di_nlink = PREDEFDIR;
	if (Oflag == 0)
		node.dp1.di_size = makedir((struct direct *)oroot_dir,
		    PREDEFDIR);
	else
		node.dp1.di_size = makedir(root_dir, PREDEFDIR);
	node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
	if (node.dp1.di_db[0] == 0)
		return (1);

	node.dp1.di_blocks = btodb(fragroundup(&sblock, node.dp1.di_size));

	wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize, iobuf);
	iput(&node, ROOTINO);

#ifdef notyet
	/*
	* Create the .snap directory.
	*/
	node.dp1.di_mode |= 020;
	node.dp1.di_gid = gid;
	node.dp1.di_nlink = SNAPLINKCNT;
	node.dp1.di_size = makedir(snap_dir, SNAPLINKCNT);

	node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
	if (node.dp1.di_db[0] == 0)
		return (1);

	node.dp1.di_blocks = btodb(fragroundup(&sblock, node.dp1.di_size));

	wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize, iobuf);
	iput(&node, ROOTINO + 1);
#endif
	return (0);
}

int
fsinit2(time_t utime)
{
	union dinode node;

	/*
	 * Initialize the node.
	 */
	memset(&node, 0, sizeof(node));
	node.dp2.di_atime = utime;
	node.dp2.di_mtime = utime;
	node.dp2.di_ctime = utime;

	/*
	 * Create the root directory.
	 */
	node.dp2.di_mode = IFDIR | UMASK;
	node.dp2.di_uid = geteuid();
	node.dp2.di_gid = getegid();
	node.dp2.di_nlink = PREDEFDIR;
	node.dp2.di_size = makedir(root_dir, PREDEFDIR);

	node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
	if (node.dp2.di_db[0] == 0)
		return (1);

	node.dp2.di_blocks = btodb(fragroundup(&sblock, node.dp2.di_size));

	wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize, iobuf);
	iput(&node, ROOTINO);

#ifdef notyet
	/*
	 * Create the .snap directory.
	 */
	node.dp2.di_mode |= 020;
	node.dp2.di_gid = gid;
	node.dp2.di_nlink = SNAPLINKCNT;
	node.dp2.di_size = makedir(snap_dir, SNAPLINKCNT);

	node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
	if (node.dp2.di_db[0] == 0)
		return (1);

	node.dp2.di_blocks = btodb(fragroundup(&sblock, node.dp2.di_size));

	wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize, iobuf);
	iput(&node, ROOTINO + 1);
#endif
	return (0);
}

/*
 * construct a set of directory entries in "buf".
 * return size of directory.
 */
int
makedir(struct direct *protodir, int entries)
{
	char *cp;
	int i, spcleft;

	spcleft = DIRBLKSIZ;
	for (cp = iobuf, i = 0; i < entries - 1; i++) {
		protodir[i].d_reclen = DIRSIZ(0, &protodir[i]);
		memcpy(cp, &protodir[i], protodir[i].d_reclen);
		cp += protodir[i].d_reclen;
		spcleft -= protodir[i].d_reclen;
	}
	protodir[i].d_reclen = spcleft;
	memcpy(cp, &protodir[i], DIRSIZ(0, &protodir[i]));
	return (DIRBLKSIZ);
}

/*
 * allocate a block or frag
 */
daddr_t
alloc(int size, int mode)
{
	int i, frag;
	daddr_t d, blkno;

	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
	    (char *)&acg);
	if (acg.cg_magic != CG_MAGIC) {
		warnx("cg 0: bad magic number");
		return (0);
	}
	if (acg.cg_cs.cs_nbfree == 0) {
		warnx("first cylinder group ran out of space");
		return (0);
	}
	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
			goto goth;
	warnx("internal error: can't find block in cyl 0");
	return (0);
goth:
	blkno = fragstoblks(&sblock, d);
	clrblock(&sblock, cg_blksfree(&acg), blkno);
	acg.cg_cs.cs_nbfree--;
	sblock.fs_cstotal.cs_nbfree--;
	fscs[0].cs_nbfree--;
	if (mode & IFDIR) {
		acg.cg_cs.cs_ndir++;
		sblock.fs_cstotal.cs_ndir++;
		fscs[0].cs_ndir++;
	}
	if (Oflag <= 1) {
		cg_blktot(&acg)[cbtocylno(&sblock, d)]--;
		cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
		    [cbtorpos(&sblock, d)]--;
	}
	if (size != sblock.fs_bsize) {
		frag = howmany(size, sblock.fs_fsize);
		fscs[0].cs_nffree += sblock.fs_frag - frag;
		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
		acg.cg_frsum[sblock.fs_frag - frag]++;
		for (i = frag; i < sblock.fs_frag; i++)
			setbit(cg_blksfree(&acg), d + i);
	}
	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
	    (char *)&acg);
	return (d);
}

/*
 * Allocate an inode on the disk
 */
void
iput(union dinode *ip, ino_t ino)
{
	daddr_t d;

	if (Oflag <= 1)
		ip->dp1.di_gen = (u_int32_t)arc4random();
	else
		ip->dp2.di_gen = (u_int32_t)arc4random();

	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
	    (char *)&acg);
	if (acg.cg_magic != CG_MAGIC)
		errx(41, "cg 0: bad magic number");

	acg.cg_cs.cs_nifree--;
	setbit(cg_inosused(&acg), ino);

	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
	    (char *)&acg);

	sblock.fs_cstotal.cs_nifree--;
	fscs[0].cs_nifree--;
	if (ino >= sblock.fs_ipg * sblock.fs_ncg)
		errx(32, "fsinit: inode value %llu out of range",
		    (unsigned long long)ino);
	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
	rdfs(d, sblock.fs_bsize, iobuf);

	if (Oflag <= 1)
		((struct ufs1_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
		    ip->dp1;
	else
		((struct ufs2_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
		    ip->dp2;

	wtfs(d, sblock.fs_bsize, iobuf);
}

/*
 * read a block from the file system
 */
void
rdfs(daddr_t bno, int size, void *bf)
{
	int n;

	if (mfs) {
		memcpy(bf, membase + bno * DEV_BSIZE, size);
		return;
	}
	n = pread(fsi, bf, size, (off_t)bno * DEV_BSIZE);
	if (n != size) {
		err(34, "rdfs: read error on block %lld", (long long)bno);
	}
}

/*
 * write a block to the file system
 */
void
wtfs(daddr_t bno, int size, void *bf)
{
	int n;

	if (mfs) {
		memcpy(membase + bno * DEV_BSIZE, bf, size);
		return;
	}
	if (Nflag)
		return;
	n = pwrite(fso, bf, size, (off_t)bno * DEV_BSIZE);
	if (n != size) {
		err(36, "wtfs: write error on block %lld", (long long)bno);
	}
}

/*
 * check if a block is available
 */
int
isblock(struct fs *fs, unsigned char *cp, int h)
{
	unsigned char mask;

	switch (fs->fs_frag) {
	case 8:
		return (cp[h] == 0xff);
	case 4:
		mask = 0x0f << ((h & 0x1) << 2);
		return ((cp[h >> 1] & mask) == mask);
	case 2:
		mask = 0x03 << ((h & 0x3) << 1);
		return ((cp[h >> 2] & mask) == mask);
	case 1:
		mask = 0x01 << (h & 0x7);
		return ((cp[h >> 3] & mask) == mask);
	default:
#ifdef STANDALONE
		printf("isblock bad fs_frag %d\n", fs->fs_frag);
#else
		warnx("isblock bad fs_frag %d", fs->fs_frag);
#endif
		return (0);
	}
}

/*
 * take a block out of the map
 */
void
clrblock(struct fs *fs, unsigned char *cp, int h)
{
	switch ((fs)->fs_frag) {
	case 8:
		cp[h] = 0;
		return;
	case 4:
		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
		return;
	case 2:
		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
		return;
	case 1:
		cp[h >> 3] &= ~(0x01 << (h & 0x7));
		return;
	default:
#ifdef STANDALONE
		printf("clrblock bad fs_frag %d\n", fs->fs_frag);
#else
		warnx("clrblock bad fs_frag %d", fs->fs_frag);
#endif
		return;
	}
}

/*
 * put a block into the map
 */
void
setblock(struct fs *fs, unsigned char *cp, int h)
{
	switch (fs->fs_frag) {
	case 8:
		cp[h] = 0xff;
		return;
	case 4:
		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
		return;
	case 2:
		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
		return;
	case 1:
		cp[h >> 3] |= (0x01 << (h & 0x7));
		return;
	default:
#ifdef STANDALONE
		printf("setblock bad fs_frag %d\n", fs->fs_frag);
#else
		warnx("setblock bad fs_frag %d", fs->fs_frag);
#endif
		return;
	}
}

/*
 * Determine the number of characters in a
 * single line.
 */
static int
charsperline(void)
{
	int columns;
	char *cp;
	struct winsize ws;

	columns = 0;
	if (ioctl(0, TIOCGWINSZ, &ws) != -1)
		columns = ws.ws_col;
	if (columns == 0 && (cp = getenv("COLUMNS")))
		columns = atoi(cp);
	if (columns == 0)
		columns = 80;   /* last resort */
	return columns;
}

static int
ilog2(int val)
{
	int n;

	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
		if (1 << n == val)
			return (n);

	errx(1, "ilog2: %d is not a power of 2\n", val);
}

struct inoinfo {
        struct  inoinfo *i_nexthash;    /* next entry in hash chain */
        struct  inoinfo *i_child, *i_sibling, *i_parentp;
        size_t  i_isize;                /* size of inode */
        ino_t   i_number;               /* inode number of this entry */  
        ino_t   i_parent;               /* inode number of parent */
  
        ino_t   i_dotdot;               /* inode number of `..' */
        u_int   i_numblks;              /* size of block array in bytes */
        daddr_t i_blks[1];              /* actually longer */
};

static void
checksz(void)
{
	unsigned long long allocate, maxino, maxfsblock, ndir, bound;
	int mib[2];
	struct rlimit datasz;
	size_t len;

	mib[0] = CTL_HW;
	mib[1] = HW_PHYSMEM64;
	len = sizeof(bound);
	
	if (sysctl(mib, 2, &bound, &len, NULL, 0) != 0)
		err(1, "can't get physmem");
	if (getrlimit(RLIMIT_DATA, &datasz) != 0)
		err(1, "can't get rlimit");
	bound = MIN(datasz.rlim_max, bound);

	allocate = 0;
	maxino = sblock.fs_ncg * (unsigned long long)sblock.fs_ipg;
	maxfsblock = sblock.fs_size;
	ndir = maxino / avgfilesperdir;

	allocate += roundup(howmany(maxfsblock, NBBY), sizeof(int16_t));
	allocate += (maxino + 1) * 3;
	allocate += sblock.fs_ncg * sizeof(long);
	allocate += (MAX(ndir, 128) + 10) * sizeof(struct inoinfo);
	allocate += MAX(ndir, 128) * sizeof(struct inoinfo);

	if (allocate > bound)
		warnx("warning: fsck_ffs will need %lluMB; "
		    "min(ulimit -dH,physmem) is %lluMB",
		    allocate / (1024ULL * 1024ULL),
		    bound / (1024ULL * 1024ULL));
}