xref: /minix/sbin/newfs_ext2fs/mke2fs.c (revision dda632a2)
1 /*	$NetBSD: mke2fs.c,v 1.14 2010/09/10 15:51:20 tsutsui Exp $	*/
2 
3 /*-
4  * Copyright (c) 2007 Izumi Tsutsui.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 /*
28  * Copyright (c) 1980, 1989, 1993
29  *	The Regents of the University of California.  All rights reserved.
30  *
31  * Redistribution and use in source and binary forms, with or without
32  * modification, are permitted provided that the following conditions
33  * are met:
34  * 1. Redistributions of source code must retain the above copyright
35  *    notice, this list of conditions and the following disclaimer.
36  * 2. Redistributions in binary form must reproduce the above copyright
37  *    notice, this list of conditions and the following disclaimer in the
38  *    documentation and/or other materials provided with the distribution.
39  * 3. Neither the name of the University nor the names of its contributors
40  *    may be used to endorse or promote products derived from this software
41  *    without specific prior written permission.
42  *
43  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
44  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
47  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53  * SUCH DAMAGE.
54  */
55 
56 /*
57  * Copyright (c) 1997 Manuel Bouyer.
58  *
59  * Redistribution and use in source and binary forms, with or without
60  * modification, are permitted provided that the following conditions
61  * are met:
62  * 1. Redistributions of source code must retain the above copyright
63  *	notice, this list of conditions and the following disclaimer.
64  * 2. Redistributions in binary form must reproduce the above copyright
65  *	notice, this list of conditions and the following disclaimer in the
66  *	documentation and/or other materials provided with the distribution.
67  *
68  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
69  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
70  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
71  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
72  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
73  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
74  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
75  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
76  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
77  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
78  */
79 
80 /*
81  * mke2fs.c: "re-invent (dumb but non-GPLed) wheel as a fun project"
82  *
83  *	In spite of this name, there is no piece of code
84  *	derived from GPLed e2fsprogs written for Linux.
85  *	I referred them only to see how each structure
86  *	member should be initialized.
87  *
88  * Reference:
89  *	- All NetBSD sources under src/sys/ufs/ext2fs and src/sbin/fsck_ext2fs
90  *	- Ext2fs Home Page
91  *		http://e2fsprogs.sourceforge.net/ext2.html
92  *	- Design and Implementation of the Second Extended Filesystem
93  *		http://e2fsprogs.sourceforge.net/ext2intro.html
94  *	- Linux Documentation "The Second Extended Filesystem"
95  *		http://www.kernel.org/doc/Documentation/filesystems/ext2.txt
96  */
97 
98 #include <sys/cdefs.h>
99 #ifndef lint
100 #if 0
101 static char sccsid[] = "@(#)mkfs.c	8.11 (Berkeley) 5/3/95";
102 #else
103 __RCSID("$NetBSD: mke2fs.c,v 1.14 2010/09/10 15:51:20 tsutsui Exp $");
104 #endif
105 #endif /* not lint */
106 
107 #include <sys/param.h>
108 #include <sys/mman.h>
109 #include <sys/time.h>
110 #include <ufs/ext2fs/ext2fs_dinode.h>
111 #include <ufs/ext2fs/ext2fs_dir.h>
112 #include <ufs/ext2fs/ext2fs.h>
113 #include <sys/ioctl.h>
114 
115 #include <err.h>
116 #include <errno.h>
117 #include <lib.h>
118 #include <string.h>
119 #include <unistd.h>
120 #include <stdlib.h>
121 #include <stddef.h>
122 #include <stdio.h>
123 #include <uuid.h>
124 #include <assert.h>
125 #include <sys/termios.h>
126 
127 #include "extern.h"
128 
129 static void initcg(uint);
130 static void zap_old_sblock(daddr_t);
131 static uint cgoverhead(uint);
132 static int fsinit(const struct timeval *);
133 static int makedir(struct ext2fs_direct *, int);
134 static void copy_dir(struct ext2fs_direct *, struct ext2fs_direct *);
135 static void init_resizeino(const struct timeval *);
136 static uint32_t alloc(uint32_t, uint16_t);
137 static void iput(struct ext2fs_dinode *, ino_t);
138 static void rdfs(daddr_t, int, void *);
139 static void wtfs(daddr_t, int, void *);
140 static int ilog2(uint);
141 static int skpc(int, size_t, uint8_t *);
142 
143 /* XXX: some of these macro should be into <ufs/ext2fs/ext2fs.h>? */
144 #define EXT2_DEF_MAX_MNT_COUNT	20
145 #define EXT2_DEF_FSCKINTV	(180 * 24 * 60 * 60)	/* 180 days */
146 #define EXT2_RESERVED_INODES	(EXT2_FIRSTINO - 1)
147 #define EXT2_UMASK		0755
148 
149 #define EXT2_INO_INDEX(ino)	((ino) - 1)		/* no inode zero */
150 
151 #define EXT2_LOSTFOUNDSIZE	16384
152 #define EXT2_LOSTFOUNDINO	EXT2_FIRSTINO		/* XXX: not quite */
153 #define EXT2_LOSTFOUNDUMASK	0700
154 
155 #define EXT2_RESIZEINOUMASK	0600
156 
157 #define NBLOCK_SUPERBLOCK	1
158 #define NBLOCK_BLOCK_BITMAP	1
159 #define NBLOCK_INODE_BITMAP	1
160 
161 #define cgbase(fs, c)	\
162 	((fs)->e2fs.e2fs_first_dblock + (fs)->e2fs.e2fs_bpg * (c))
163 
164 
165 /*
166  * ext2fs super block and group descriptor structures
167  *
168  *   We don't have to use or setup whole in-memory m_ext2fs structure,
169  *   but prepare it to use several macro defined in kernel headers.
170  */
171 union {
172 	struct m_ext2fs m_ext2fs;
173 	char pad[SBSIZE];
174 } ext2fsun;
175 #define sblock	ext2fsun.m_ext2fs
176 #define gd	ext2fsun.m_ext2fs.e2fs_gd
177 
178 static uint8_t *iobuf;		/* for superblock and group descriptors */
179 static int iobufsize;
180 
181 static uint8_t buf[MAXBSIZE];	/* for initcg() and makedir() ops */
182 
183 static int fsi = -1, fso = -1;
184 
185 void
186 mke2fs(const char *fsys, int fi, int fo)
187 {
188 	struct timeval tv;
189 	int64_t minfssize;
190 	uint bcount, fbcount, ficount;
191 	uint blocks_gd, blocks_per_cg, inodes_per_cg, iblocks_per_cg;
192 	uint minblocks_per_cg, blocks_lastcg;
193 	uint ncg, cylno, sboff;
194 	uuid_t uuid;
195 	uint32_t uustat;
196 	int i, len, col, delta, fld_width, max_cols;
197 	struct winsize winsize;
198 
199 	gettimeofday(&tv, NULL);
200 	fsi = fi;
201 	fso = fo;
202 
203 	/*
204 	 * collect and verify the block and fragment sizes
205 	 */
206 	if (!powerof2(bsize)) {
207 		errx(EXIT_FAILURE,
208 		    "block size must be a power of 2, not %u\n",
209 		    bsize);
210 	}
211 	if (!powerof2(fsize)) {
212 		errx(EXIT_FAILURE,
213 		    "fragment size must be a power of 2, not %u\n",
214 		    fsize);
215 	}
216 	if (fsize < sectorsize) {
217 		errx(EXIT_FAILURE,
218 		    "fragment size %u is too small, minimum is %u\n",
219 		    fsize, sectorsize);
220 	}
221 	if (bsize < MINBSIZE) {
222 		errx(EXIT_FAILURE,
223 		    "block size %u is too small, minimum is %u\n",
224 		    bsize, MINBSIZE);
225 	}
226 	if (bsize > EXT2_MAXBSIZE) {
227 		errx(EXIT_FAILURE,
228 		    "block size %u is too large, maximum is %u\n",
229 		    bsize, MAXBSIZE);
230 	}
231 	if (bsize != fsize) {
232 		/*
233 		 * There is no fragment support on current ext2fs (yet?),
234 		 * but some kernel code refers fsize or fpg as bsize or bpg
235 		 * and Linux seems to set the same values to them.
236 		 */
237 		errx(EXIT_FAILURE,
238 		    "block size (%u) can't be different from "
239 		    "fragment size (%u)\n",
240 		    bsize, fsize);
241 	}
242 
243 	/* variable inodesize is REV1 feature */
244 	if (Oflag == 0 && inodesize != EXT2_REV0_DINODE_SIZE) {
245 		errx(EXIT_FAILURE, "GOOD_OLD_REV file system format"
246 		    " doesn't support %d byte inode\n", inodesize);
247 	}
248 
249 	sblock.e2fs.e2fs_log_bsize = ilog2(bsize) - LOG_MINBSIZE;
250 	/* Umm, why not e2fs_log_fsize? */
251 	sblock.e2fs.e2fs_fsize = ilog2(fsize) - LOG_MINBSIZE;
252 
253 	sblock.e2fs_bsize = bsize;
254 	sblock.e2fs_bshift = sblock.e2fs.e2fs_log_bsize + LOG_MINBSIZE;
255 	sblock.e2fs_qbmask = sblock.e2fs_bsize - 1;
256 	sblock.e2fs_bmask = ~sblock.e2fs_qbmask;
257 	sblock.e2fs_fsbtodb = ilog2(sblock.e2fs_bsize) - ilog2(sectorsize);
258 	sblock.e2fs_ipb = sblock.e2fs_bsize / inodesize;
259 
260 	/*
261 	 * Ext2fs preserves BBSIZE (1024 bytes) space at the top for
262 	 * bootloader (though it is not enough at all for our bootloader).
263 	 * If bsize == BBSIZE we have to preserve one block.
264 	 * If bsize > BBSIZE, the first block already contains BBSIZE space
265 	 * before superblock because superblock is allocated at SBOFF and
266 	 * bsize is a power of two (i.e. 2048 bytes or more).
267 	 */
268 	sblock.e2fs.e2fs_first_dblock = (sblock.e2fs_bsize > BBSIZE) ? 0 : 1;
269 	minfssize = fsbtodb(&sblock,
270 	    sblock.e2fs.e2fs_first_dblock +
271 	    NBLOCK_SUPERBLOCK +
272 	    1 /* at least one group descriptor */ +
273 	    NBLOCK_BLOCK_BITMAP	+
274 	    NBLOCK_INODE_BITMAP +
275 	    1 /* at least one inode table block */ +
276 	    1 /* at least one data block for rootdir */ +
277 	    1 /* at least one data block for data */
278 	    );			/* XXX and more? */
279 
280 	if (fssize < minfssize)
281 		errx(EXIT_FAILURE, "Filesystem size %" PRId64
282 		    " < minimum size of %" PRId64 "\n", fssize, minfssize);
283 
284 	bcount = dbtofsb(&sblock, fssize);
285 
286 	/*
287 	 * While many people claim that ext2fs is a (bad) clone of ufs/ffs,
288 	 * it isn't actual ffs so maybe we should call it "block group"
289 	 * as their native name rather than ffs derived "cylinder group."
290 	 * But we'll use the latter here since other kernel sources use it.
291 	 * (I also agree "cylinder" based allocation is obsolete though)
292 	 */
293 
294 	/* maybe "simple is the best" */
295 	blocks_per_cg = sblock.e2fs_bsize * NBBY;
296 
297 	ncg = howmany(bcount - sblock.e2fs.e2fs_first_dblock, blocks_per_cg);
298 	blocks_gd = howmany(sizeof(struct ext2_gd) * ncg, bsize);
299 
300 	/* check range of inode number */
301 	if (num_inodes < EXT2_FIRSTINO)
302 		num_inodes = EXT2_FIRSTINO;	/* needs reserved inodes + 1 */
303 	if (num_inodes > UINT16_MAX * ncg)
304 		num_inodes = UINT16_MAX * ncg;	/* ext2bgd_nifree is uint16_t */
305 
306 	inodes_per_cg = num_inodes / ncg;
307 	iblocks_per_cg = howmany(inodesize * inodes_per_cg, bsize);
308 
309 	/* Check that the last cylinder group has enough space for inodes */
310 	minblocks_per_cg =
311 	    NBLOCK_BLOCK_BITMAP +
312 	    NBLOCK_INODE_BITMAP +
313 	    iblocks_per_cg +
314 	    1;	/* at least one data block */
315 	if (Oflag == 0 || cg_has_sb(ncg - 1) != 0)
316 		minblocks_per_cg += NBLOCK_SUPERBLOCK + blocks_gd;
317 
318 	blocks_lastcg = bcount - sblock.e2fs.e2fs_first_dblock -
319 	    blocks_per_cg * (ncg - 1);
320 	if (blocks_lastcg < minblocks_per_cg) {
321 		/*
322 		 * Since we make all the cylinder groups the same size, the
323 		 * last will only be small if there are more than one
324 		 * cylinder groups. If the last one is too small to store
325 		 * filesystem data, just kill it.
326 		 *
327 		 * XXX: Does fsck_ext2fs(8) properly handle this case?
328 		 */
329 		bcount -= blocks_lastcg;
330 		ncg--;
331 		blocks_lastcg = blocks_per_cg;
332 		blocks_gd = howmany(sizeof(struct ext2_gd) * ncg, bsize);
333 		inodes_per_cg = num_inodes / ncg;
334 	}
335 	/* roundup inodes_per_cg to make it use whole inode table blocks */
336 	inodes_per_cg = roundup(inodes_per_cg, sblock.e2fs_ipb);
337 	num_inodes = inodes_per_cg * ncg;
338 	iblocks_per_cg = inodes_per_cg / sblock.e2fs_ipb;
339 
340 	/* XXX: probably we should check these adjusted values again */
341 
342 	sblock.e2fs.e2fs_bcount = bcount;
343 	sblock.e2fs.e2fs_icount = num_inodes;
344 
345 	sblock.e2fs_ncg = ncg;
346 	sblock.e2fs_ngdb = blocks_gd;
347 	sblock.e2fs_itpg = iblocks_per_cg;
348 
349 	sblock.e2fs.e2fs_rbcount = sblock.e2fs.e2fs_bcount * minfree / 100;
350 	/* e2fs_fbcount will be accounted later */
351 	/* e2fs_ficount will be accounted later */
352 
353 	sblock.e2fs.e2fs_bpg = blocks_per_cg;
354 	sblock.e2fs.e2fs_fpg = blocks_per_cg;
355 
356 	sblock.e2fs.e2fs_ipg = inodes_per_cg;
357 
358 	sblock.e2fs.e2fs_mtime = 0;
359 	sblock.e2fs.e2fs_wtime = tv.tv_sec;
360 	sblock.e2fs.e2fs_mnt_count = 0;
361 	/* XXX: should add some entropy to avoid checking all fs at once? */
362 	sblock.e2fs.e2fs_max_mnt_count = EXT2_DEF_MAX_MNT_COUNT;
363 
364 	sblock.e2fs.e2fs_magic = E2FS_MAGIC;
365 	sblock.e2fs.e2fs_state = E2FS_ISCLEAN;
366 	sblock.e2fs.e2fs_beh = E2FS_BEH_DEFAULT;
367 	sblock.e2fs.e2fs_minrev = 0;
368 	sblock.e2fs.e2fs_lastfsck = tv.tv_sec;
369 	sblock.e2fs.e2fs_fsckintv = EXT2_DEF_FSCKINTV;
370 
371 	/*
372 	 * Maybe we can use E2FS_OS_FREEBSD here and it would be more proper,
373 	 * but the purpose of this newfs_ext2fs(8) command is to provide
374 	 * a filesystem which can be recognized by firmware on some
375 	 * Linux based appliances that can load bootstrap files only from
376 	 * (their native) ext2fs, and anyway we will (and should) try to
377 	 * act like them as much as possible.
378 	 *
379 	 * Anyway, I hope that all newer such boxes will keep their support
380 	 * for the "GOOD_OLD_REV" ext2fs.
381 	 */
382 	sblock.e2fs.e2fs_creator = E2FS_OS_LINUX;
383 
384 	if (Oflag == 0) {
385 		sblock.e2fs.e2fs_rev = E2FS_REV0;
386 		sblock.e2fs.e2fs_features_compat   = 0;
387 		sblock.e2fs.e2fs_features_incompat = 0;
388 		sblock.e2fs.e2fs_features_rocompat = 0;
389 	} else {
390 		sblock.e2fs.e2fs_rev = E2FS_REV1;
391 		/*
392 		 * e2fsprogs say "REV1" is "dynamic" so
393 		 * it isn't quite a version and maybe it means
394 		 * "extended from REV0 so check compat features."
395 		 *
396 		 * XXX: We don't have any native tool to activate
397 		 *      the EXT2F_COMPAT_RESIZE feature and
398 		 *      fsck_ext2fs(8) might not fix structures for it.
399 		 */
400 		sblock.e2fs.e2fs_features_compat   = EXT2F_COMPAT_RESIZE;
401 		sblock.e2fs.e2fs_features_incompat = EXT2F_INCOMPAT_FTYPE;
402 		sblock.e2fs.e2fs_features_rocompat =
403 		    EXT2F_ROCOMPAT_SPARSESUPER | EXT2F_ROCOMPAT_LARGEFILE;
404 	}
405 
406 	sblock.e2fs.e2fs_ruid = geteuid();
407 	sblock.e2fs.e2fs_rgid = getegid();
408 
409 	sblock.e2fs.e2fs_first_ino = EXT2_FIRSTINO;
410 	sblock.e2fs.e2fs_inode_size = inodesize;
411 
412 	/* e2fs_block_group_nr is set on writing superblock to each group */
413 
414 	uuid_create(&uuid, &uustat);
415 	if (uustat != uuid_s_ok)
416 		errx(EXIT_FAILURE, "Failed to generate uuid\n");
417 	uuid_enc_le(sblock.e2fs.e2fs_uuid, &uuid);
418 	if (volname != NULL) {
419 		if (strlen(volname) > sizeof(sblock.e2fs.e2fs_vname))
420 			errx(EXIT_FAILURE, "Volume name is too long");
421 		strlcpy(sblock.e2fs.e2fs_vname, volname,
422 		    sizeof(sblock.e2fs.e2fs_vname));
423 	}
424 
425 	sblock.e2fs.e2fs_fsmnt[0] = '\0';
426 	sblock.e2fs_fsmnt[0] = '\0';
427 
428 	sblock.e2fs.e2fs_algo = 0;		/* XXX unsupported? */
429 	sblock.e2fs.e2fs_prealloc = 0;		/* XXX unsupported? */
430 	sblock.e2fs.e2fs_dir_prealloc = 0;	/* XXX unsupported? */
431 
432 	/* calculate blocks for reserved group descriptors for resize */
433 	sblock.e2fs.e2fs_reserved_ngdb = 0;
434 	if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
435 	    (sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_RESIZE) != 0) {
436 		uint64_t target_blocks;
437 		uint target_ncg, target_ngdb, reserved_ngdb;
438 
439 		/* reserve descriptors for size as 1024 times as current */
440 		target_blocks =
441 		    (sblock.e2fs.e2fs_bcount - sblock.e2fs.e2fs_first_dblock)
442 		    * 1024ULL;
443 		/* number of blocks must be in uint32_t */
444 		if (target_blocks > UINT32_MAX)
445 			target_blocks = UINT32_MAX;
446 		target_ncg = howmany(target_blocks, sblock.e2fs.e2fs_bpg);
447 		target_ngdb = howmany(sizeof(struct ext2_gd) * target_ncg,
448 		    sblock.e2fs_bsize);
449 		/*
450 		 * Reserved group descriptor blocks are preserved as
451 		 * the second level double indirect reference blocks in
452 		 * the EXT2_RESIZEINO inode, so the maximum number of
453 		 * the blocks is NINDIR(fs).
454 		 * (see also descriptions in init_resizeino() function)
455 		 *
456 		 * We check a number including current e2fs_ngdb here
457 		 * because they will be moved into reserved gdb on
458 		 * possible future size shrink, though e2fsprogs don't
459 		 * seem to care about it.
460 		 */
461 		if (target_ngdb > NINDIR(&sblock))
462 			target_ngdb = NINDIR(&sblock);
463 
464 		reserved_ngdb = target_ngdb - sblock.e2fs_ngdb;
465 
466 		/* make sure reserved_ngdb fits in the last cg */
467 		if (reserved_ngdb >= blocks_lastcg - cgoverhead(ncg - 1))
468 			reserved_ngdb = blocks_lastcg - cgoverhead(ncg - 1);
469 		if (reserved_ngdb == 0) {
470 			/* if no space for reserved gdb, disable the feature */
471 			sblock.e2fs.e2fs_features_compat &=
472 			    ~EXT2F_COMPAT_RESIZE;
473 		}
474 		sblock.e2fs.e2fs_reserved_ngdb = reserved_ngdb;
475 	}
476 
477 	/*
478 	 * Initialize group descriptors
479 	 */
480 	gd = malloc(sblock.e2fs_ngdb * bsize);
481 	if (gd == NULL)
482 		errx(EXIT_FAILURE, "Can't allocate descriptors buffer");
483 	memset(gd, 0, sblock.e2fs_ngdb * bsize);
484 
485 	fbcount = 0;
486 	ficount = 0;
487 	for (cylno = 0; cylno < ncg; cylno++) {
488 		uint boffset;
489 
490 		boffset = cgbase(&sblock, cylno);
491 		if (sblock.e2fs.e2fs_rev == E2FS_REV0 ||
492 		    (sblock.e2fs.e2fs_features_rocompat &
493 		     EXT2F_ROCOMPAT_SPARSESUPER) == 0 ||
494 		    cg_has_sb(cylno)) {
495 			boffset += NBLOCK_SUPERBLOCK + sblock.e2fs_ngdb;
496 			if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
497 			    (sblock.e2fs.e2fs_features_compat &
498 			     EXT2F_COMPAT_RESIZE) != 0)
499 				boffset += sblock.e2fs.e2fs_reserved_ngdb;
500 		}
501 		gd[cylno].ext2bgd_b_bitmap = boffset;
502 		boffset += NBLOCK_BLOCK_BITMAP;
503 		gd[cylno].ext2bgd_i_bitmap = boffset;
504 		boffset += NBLOCK_INODE_BITMAP;
505 		gd[cylno].ext2bgd_i_tables = boffset;
506 		if (cylno == (ncg - 1))
507 			gd[cylno].ext2bgd_nbfree =
508 			    blocks_lastcg - cgoverhead(cylno);
509 		else
510 			gd[cylno].ext2bgd_nbfree =
511 			    sblock.e2fs.e2fs_bpg - cgoverhead(cylno);
512 		fbcount += gd[cylno].ext2bgd_nbfree;
513 		gd[cylno].ext2bgd_nifree = sblock.e2fs.e2fs_ipg;
514 		if (cylno == 0) {
515 			/* take reserved inodes off nifree */
516 			gd[cylno].ext2bgd_nifree -= EXT2_RESERVED_INODES;
517 		}
518 		ficount += gd[cylno].ext2bgd_nifree;
519 		gd[cylno].ext2bgd_ndirs = 0;
520 	}
521 	sblock.e2fs.e2fs_fbcount = fbcount;
522 	sblock.e2fs.e2fs_ficount = ficount;
523 
524 	/*
525 	 * Dump out summary information about file system.
526 	 */
527 	if (verbosity > 0) {
528 		printf("%s: %u.%1uMB (%" PRId64 " sectors) "
529 		    "block size %u, fragment size %u\n",
530 		    fsys,
531 		    (uint)(((uint64_t)bcount * bsize) / (1024 * 1024)),
532 		    (uint)((uint64_t)bcount * bsize -
533 		    rounddown((uint64_t)bcount * bsize, 1024 * 1024))
534 		    / 1024 / 100,
535 		    fssize, bsize, fsize);
536 		printf("\tusing %u block groups of %u.0MB, %u blks, "
537 		    "%u inodes.\n",
538 		    ncg, bsize * sblock.e2fs.e2fs_bpg / (1024 * 1024),
539 		    sblock.e2fs.e2fs_bpg, sblock.e2fs.e2fs_ipg);
540 	}
541 
542 	/*
543 	 * allocate space for superblock and group descriptors
544 	 */
545 	iobufsize = (NBLOCK_SUPERBLOCK + sblock.e2fs_ngdb) * sblock.e2fs_bsize;
546 	iobuf = mmap(0, iobufsize, PROT_READ|PROT_WRITE,
547 	    MAP_ANON|MAP_PRIVATE, -1, 0);
548 	if (iobuf == NULL)
549 		errx(EXIT_FAILURE, "Cannot allocate I/O buffer\n");
550 	memset(iobuf, 0, iobufsize);
551 
552 	/*
553 	 * We now start writing to the filesystem
554 	 */
555 
556 	if (!Nflag) {
557 		static const uint pbsize[] = { 1024, 2048, 4096, 0 };
558 		uint pblock, epblock;
559 		/*
560 		 * Validate the given file system size.
561 		 * Verify that its last block can actually be accessed.
562 		 * Convert to file system fragment sized units.
563 		 */
564 		if (fssize <= 0)
565 			errx(EXIT_FAILURE, "Preposterous size %" PRId64 "\n",
566 			    fssize);
567 		wtfs(fssize - 1, sectorsize, iobuf);
568 
569 		/*
570 		 * Ensure there is nothing that looks like a filesystem
571 		 * superblock anywhere other than where ours will be.
572 		 * If fsck_ext2fs finds the wrong one all hell breaks loose!
573 		 *
574 		 * XXX: needs to check how fsck_ext2fs programs even
575 		 *      on other OSes determine alternate superblocks
576 		 */
577 		for (i = 0; pbsize[i] != 0; i++) {
578 			epblock = (uint64_t)bcount * bsize / pbsize[i];
579 			for (pblock = ((pbsize[i] == SBSIZE) ? 1 : 0);
580 			    pblock < epblock;
581 			    pblock += pbsize[i] * NBBY /* bpg */)
582 				zap_old_sblock((daddr_t)pblock *
583 				    pbsize[i] / sectorsize);
584 		}
585 	}
586 
587 	if (verbosity >= 3)
588 		printf("super-block backups (for fsck_ext2fs -b #) at:\n");
589 	/* If we are printing more than one line of numbers, line up columns */
590 	fld_width = verbosity < 4 ? 1 : snprintf(NULL, 0, "%" PRIu64,
591 	    (uint64_t)cgbase(&sblock, ncg - 1));
592 	/* Get terminal width */
593 	if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) == 0)
594 		max_cols = winsize.ws_col;
595 	else
596 		max_cols = 80;
597 	if (Nflag && verbosity == 3)
598 		/* Leave space to add " ..." after one row of numbers */
599 		max_cols -= 4;
600 #define BASE 0x10000	/* For some fixed-point maths */
601 	col = 0;
602 	delta = verbosity > 2 ? 0 : max_cols * BASE / ncg;
603 	for (cylno = 0; cylno < ncg; cylno++) {
604 		fflush(stdout);
605 		initcg(cylno);
606 		if (verbosity < 2)
607 			continue;
608 		/* the first one is a master, not backup */
609 		if (cylno == 0)
610 			continue;
611 		/* skip if this cylinder doesn't have a backup */
612 		if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
613 		    (sblock.e2fs.e2fs_features_rocompat &
614 		     EXT2F_ROCOMPAT_SPARSESUPER) != 0 &&
615 		    cg_has_sb(cylno) == 0)
616 			continue;
617 
618 		if (delta > 0) {
619 			if (Nflag)
620 				/* No point doing dots for -N */
621 				break;
622 			/* Print dots scaled to end near RH margin */
623 			for (col += delta; col > BASE; col -= BASE)
624 				printf(".");
625 			continue;
626 		}
627 		/* Print superblock numbers */
628 		len = printf(" %*" PRIu64 "," + !col, fld_width,
629 		    (uint64_t)cgbase(&sblock, cylno));
630 		col += len;
631 		if (col + len < max_cols)
632 			/* Next number fits */
633 			continue;
634 		/* Next number won't fit, need a newline */
635 		if (verbosity <= 3) {
636 			/* Print dots for subsequent cylinder groups */
637 			delta = sblock.e2fs_ncg - cylno - 1;
638 			if (delta != 0) {
639 				if (Nflag) {
640 					printf(" ...");
641 					break;
642 				}
643 				delta = max_cols * BASE / delta;
644 			}
645 		}
646 		col = 0;
647 		printf("\n");
648 	}
649 #undef BASE
650 	if (col > 0)
651 		printf("\n");
652 	if (Nflag)
653 		return;
654 
655 	/*
656 	 * Now construct the initial file system,
657 	 */
658 	if (fsinit(&tv) == 0)
659 		errx(EXIT_FAILURE, "Error making filesystem");
660 	/*
661 	 * Write out the superblock and group descriptors
662 	 */
663 	sblock.e2fs.e2fs_block_group_nr = 0;
664 	sboff = 0;
665 	if (cgbase(&sblock, 0) == 0) {
666 		/*
667 		 * If the first block contains the boot block sectors,
668 		 * (i.e. in case of sblock.e2fs.e2fs_bsize > BBSIZE)
669 		 * we have to preserve data in it.
670 		 */
671 		sboff = SBOFF;
672 	}
673 	e2fs_sbsave(&sblock.e2fs, (struct ext2fs *)(iobuf + sboff));
674 	e2fs_cgsave(gd, (struct ext2_gd *)(iobuf + sblock.e2fs_bsize),
675 	   sizeof(struct ext2_gd) * sblock.e2fs_ncg);
676 	wtfs(fsbtodb(&sblock, cgbase(&sblock, 0)) + sboff / sectorsize,
677 	    iobufsize - sboff, iobuf + sboff);
678 
679 	munmap(iobuf, iobufsize);
680 }
681 
682 /*
683  * Initialize a cylinder (block) group.
684  */
685 void
686 initcg(uint cylno)
687 {
688 	uint nblcg, i, j, sboff;
689 	struct ext2fs_dinode *dp;
690 
691 	/*
692 	 * Make a copy of the superblock and group descriptors.
693 	 */
694 	if (sblock.e2fs.e2fs_rev == E2FS_REV0 ||
695 	    (sblock.e2fs.e2fs_features_rocompat &
696 	     EXT2F_ROCOMPAT_SPARSESUPER) == 0 ||
697 	    cg_has_sb(cylno)) {
698 		sblock.e2fs.e2fs_block_group_nr = cylno;
699 		sboff = 0;
700 		if (cgbase(&sblock, cylno) == 0) {
701 			/* preserve data in bootblock in cg0 */
702 			sboff = SBOFF;
703 		}
704 		e2fs_sbsave(&sblock.e2fs, (struct ext2fs *)(iobuf + sboff));
705 		e2fs_cgsave(gd, (struct ext2_gd *)(iobuf +
706 		    sblock.e2fs_bsize * NBLOCK_SUPERBLOCK),
707 		    sizeof(struct ext2_gd) * sblock.e2fs_ncg);
708 		/* write superblock and group descriptor backups */
709 		wtfs(fsbtodb(&sblock, cgbase(&sblock, cylno)) +
710 		    sboff / sectorsize, iobufsize - sboff, iobuf + sboff);
711 	}
712 
713 	/*
714 	 * Initialize block bitmap.
715 	 */
716 	memset(buf, 0, sblock.e2fs_bsize);
717 	if (cylno == (sblock.e2fs_ncg - 1)) {
718 		/* The last group could have less blocks than e2fs_bpg. */
719 		nblcg = sblock.e2fs.e2fs_bcount -
720 		    cgbase(&sblock, sblock.e2fs_ncg - 1);
721 		for (i = nblcg; i < roundup(nblcg, NBBY); i++)
722 			setbit(buf, i);
723 		memset(&buf[i / NBBY], ~0U, sblock.e2fs.e2fs_bpg - i);
724 	}
725 	/* set overhead (superblock, group descriptor etc.) blocks used */
726 	for (i = 0; i < cgoverhead(cylno) / NBBY; i++)
727 		buf[i] = ~0;
728 	i = i * NBBY;
729 	for (; i < cgoverhead(cylno); i++)
730 		setbit(buf, i);
731 	wtfs(fsbtodb(&sblock, gd[cylno].ext2bgd_b_bitmap), sblock.e2fs_bsize,
732 	    buf);
733 
734 	/*
735 	 * Initialize inode bitmap.
736 	 *
737 	 *  Assume e2fs_ipg is a multiple of NBBY since
738 	 *  it's a multiple of e2fs_ipb (as we did above).
739 	 *  Note even (possibly smaller) the last group has the same e2fs_ipg.
740 	 */
741 	assert(!(sblock.e2fs.e2fs_ipg % NBBY));
742 	i = sblock.e2fs.e2fs_ipg / NBBY;
743 	memset(buf, 0, i);
744 	assert(sblock.e2fs_bsize >= i);
745 	memset(buf + i, ~0U, sblock.e2fs_bsize - i);
746 	if (cylno == 0) {
747 		/* mark reserved inodes */
748 		for (i = 1; i < EXT2_FIRSTINO; i++)
749 			setbit(buf, EXT2_INO_INDEX(i));
750 	}
751 	wtfs(fsbtodb(&sblock, gd[cylno].ext2bgd_i_bitmap), sblock.e2fs_bsize,
752 	    buf);
753 
754 	/*
755 	 * Initialize inode tables.
756 	 *
757 	 *  Just initialize generation numbers for NFS security.
758 	 *  XXX: sys/ufs/ext2fs/ext2fs_alloc.c:ext2fs_valloc() seems
759 	 *       to override these generated numbers.
760 	 */
761 	memset(buf, 0, sblock.e2fs_bsize);
762 	for (i = 0; i < sblock.e2fs_itpg; i++) {
763 		for (j = 0; j < sblock.e2fs_ipb; j++) {
764 			dp = (struct ext2fs_dinode *)(buf + inodesize * j);
765 			/* h2fs32() just for consistency */
766 			dp->e2di_gen = h2fs32(arc4random());
767 		}
768 		wtfs(fsbtodb(&sblock, gd[cylno].ext2bgd_i_tables + i),
769 		    sblock.e2fs_bsize, buf);
770 	}
771 }
772 
773 /*
774  * Zap possible lingering old superblock data
775  */
776 static void
777 zap_old_sblock(daddr_t sec)
778 {
779 	static daddr_t cg0_data;
780 	uint32_t oldfs[SBSIZE / sizeof(uint32_t)];
781 	static const struct fsm {
782 		uint32_t offset;
783 		uint32_t magic;
784 		uint32_t mask;
785 	} fs_magics[] = {
786 		{offsetof(struct ext2fs, e2fs_magic) / 4, E2FS_MAGIC, 0xffff},
787 		{offsetof(struct ext2fs, e2fs_magic) / 4,
788 		    E2FS_MAGIC << 16, 0xffff0000},
789 		{14, 0xef530000, 0xffff0000},	/* EXT2FS (big) */
790 		{0x55c / 4, 0x00011954, ~0U},	/* FS_UFS1_MAGIC */
791 		{0x55c / 4, 0x19540119, ~0U},	/* FS_UFS2_MAGIC */
792 		{0, 0x70162, ~0U},		/* LFS_MAGIC */
793 		{.offset = ~0U},
794 	};
795 	const struct fsm *fsm;
796 
797 	if (Nflag)
798 		return;
799 
800 	/* don't override data before superblock */
801 	if (sec < SBOFF / sectorsize)
802 		return;
803 
804 	if (cg0_data == 0) {
805 		cg0_data =
806 		    ((daddr_t)sblock.e2fs.e2fs_first_dblock + cgoverhead(0)) *
807 		    sblock.e2fs_bsize / sectorsize;
808 	}
809 
810 	/* Ignore anything that is beyond our filesystem */
811 	if (sec >= fssize)
812 		return;
813 	/* Zero anything inside our filesystem... */
814 	if (sec >= sblock.e2fs.e2fs_first_dblock * bsize / sectorsize) {
815 		/* ...unless we will write that area anyway */
816 		if (sec >= cg0_data)
817 			/* assume iobuf is zero'ed here */
818 			wtfs(sec, roundup(SBSIZE, sectorsize), iobuf);
819 		return;
820 	}
821 
822 	/*
823 	 * The sector might contain boot code, so we must validate it
824 	 *
825 	 * XXX: ext2fs won't preserve data after SBOFF,
826 	 *      but first_dblock could have a different value.
827 	 */
828 	rdfs(sec, sizeof(oldfs), &oldfs);
829 	for (fsm = fs_magics;; fsm++) {
830 		uint32_t v;
831 		if (fsm->mask == 0)
832 			return;
833 		v = oldfs[fsm->offset];
834 		if ((v & fsm->mask) == fsm->magic ||
835 		    (bswap32(v) & fsm->mask) == fsm->magic)
836 			break;
837 	}
838 
839 	/* Just zap the magic number */
840 	oldfs[fsm->offset] = 0;
841 	wtfs(sec, sizeof(oldfs), &oldfs);
842 }
843 
844 /*
845  * uint cgoverhead(uint c)
846  *
847  * 	Return a number of reserved blocks on the specified group.
848  * 	XXX: should be shared with src/sbin/fsck_ext2fs/setup.c
849  */
850 uint
851 cgoverhead(uint c)
852 {
853 	uint overh;
854 
855 	overh = NBLOCK_BLOCK_BITMAP + NBLOCK_INODE_BITMAP + sblock.e2fs_itpg;
856 
857 	if (sblock.e2fs.e2fs_rev == E2FS_REV0 ||
858 	    (sblock.e2fs.e2fs_features_rocompat &
859 	     EXT2F_ROCOMPAT_SPARSESUPER) == 0 ||
860 	    cg_has_sb(c) != 0) {
861 		overh += NBLOCK_SUPERBLOCK + sblock.e2fs_ngdb;
862 
863 		if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
864 		    (sblock.e2fs.e2fs_features_compat &
865 		     EXT2F_COMPAT_RESIZE) != 0)
866 			overh += sblock.e2fs.e2fs_reserved_ngdb;
867 	}
868 
869 	return overh;
870 }
871 
872 /*
873  * Initialize the file system
874  */
875 
876 #define LOSTDIR		/* e2fsck complains if there is no lost+found */
877 
878 #define	PREDEFDIR	2
879 
880 #ifdef LOSTDIR
881 #define	PREDEFROOTDIR	(PREDEFDIR + 1)
882 #else
883 #define	PREDEFROOTDIR	PREDEFDIR
884 #endif
885 
886 struct ext2fs_direct root_dir[] = {
887 	{ EXT2_ROOTINO, 0, 1, 0, "." },
888 	{ EXT2_ROOTINO, 0, 2, 0, ".." },
889 #ifdef LOSTDIR
890 	{ EXT2_LOSTFOUNDINO, 0, 10, 0, "lost+found" },
891 #endif
892 };
893 
894 #ifdef LOSTDIR
895 struct ext2fs_direct lost_found_dir[] = {
896 	{ EXT2_LOSTFOUNDINO, 0, 1, 0, "." },
897 	{ EXT2_ROOTINO, 0, 2, 0, ".." },
898 };
899 struct ext2fs_direct pad_dir = { 0, sizeof(struct ext2fs_direct), 0, 0, "" };
900 #endif
901 
902 int
903 fsinit(const struct timeval *tv)
904 {
905 	struct ext2fs_dinode node;
906 #ifdef LOSTDIR
907 	uint i, nblks_lostfound, blk;
908 #endif
909 
910 	/*
911 	 * Initialize the inode for the resizefs feature
912 	 */
913 	if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
914 	    (sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_RESIZE) != 0)
915 		init_resizeino(tv);
916 
917 	/*
918 	 * Initialize the node
919 	 */
920 
921 #ifdef LOSTDIR
922 	/*
923 	 * Create the lost+found directory
924 	 */
925 	if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
926 	    sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) {
927 		lost_found_dir[0].e2d_type = EXT2_FT_DIR;
928 		lost_found_dir[1].e2d_type = EXT2_FT_DIR;
929 	}
930 	(void)makedir(lost_found_dir, __arraycount(lost_found_dir));
931 
932 	/* prepare a bit large directory for preserved files */
933 	nblks_lostfound = EXT2_LOSTFOUNDSIZE / sblock.e2fs_bsize;
934 	/* ...but only with direct blocks */
935 	if (nblks_lostfound > NDADDR)
936 		nblks_lostfound = NDADDR;
937 
938 	memset(&node, 0, sizeof(node));
939 	node.e2di_mode = EXT2_IFDIR | EXT2_LOSTFOUNDUMASK;
940 	node.e2di_uid = geteuid();
941 	node.e2di_size = sblock.e2fs_bsize * nblks_lostfound;
942 	node.e2di_atime = tv->tv_sec;
943 	node.e2di_ctime = tv->tv_sec;
944 	node.e2di_mtime = tv->tv_sec;
945 	node.e2di_gid = getegid();
946 	node.e2di_nlink = PREDEFDIR;
947 	/* e2di_nblock is a number of disk blocks, not ext2fs blocks */
948 	node.e2di_nblock = fsbtodb(&sblock, nblks_lostfound);
949 	node.e2di_blocks[0] = alloc(sblock.e2fs_bsize, node.e2di_mode);
950 	if (node.e2di_blocks[0] == 0) {
951 		printf("%s: can't allocate block for lost+found\n", __func__);
952 		return 0;
953 	}
954 	for (i = 1; i < nblks_lostfound; i++) {
955 		blk = alloc(sblock.e2fs_bsize, 0);
956 		if (blk == 0) {
957 			printf("%s: can't allocate blocks for lost+found\n",
958 			    __func__);
959 			return 0;
960 		}
961 		node.e2di_blocks[i] = blk;
962 	}
963 	wtfs(fsbtodb(&sblock, node.e2di_blocks[0]), sblock.e2fs_bsize, buf);
964 	pad_dir.e2d_reclen = sblock.e2fs_bsize;
965 	for (i = 1; i < nblks_lostfound; i++) {
966 		memset(buf, 0, sblock.e2fs_bsize);
967 		copy_dir(&pad_dir, (struct ext2fs_direct *)buf);
968 		wtfs(fsbtodb(&sblock, node.e2di_blocks[i]), sblock.e2fs_bsize,
969 		    buf);
970 	}
971 	iput(&node, EXT2_LOSTFOUNDINO);
972 #endif
973 	/*
974 	 * create the root directory
975 	 */
976 	memset(&node, 0, sizeof(node));
977 	if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
978 	    sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) {
979 		root_dir[0].e2d_type = EXT2_FT_DIR;
980 		root_dir[1].e2d_type = EXT2_FT_DIR;
981 #ifdef LOSTDIR
982 		root_dir[2].e2d_type = EXT2_FT_DIR;
983 #endif
984 	}
985 	node.e2di_mode = EXT2_IFDIR | EXT2_UMASK;
986 	node.e2di_uid = geteuid();
987 	node.e2di_size = makedir(root_dir, __arraycount(root_dir));
988 	node.e2di_atime = tv->tv_sec;
989 	node.e2di_ctime = tv->tv_sec;
990 	node.e2di_mtime = tv->tv_sec;
991 	node.e2di_gid = getegid();
992 	node.e2di_nlink = PREDEFROOTDIR;
993 	/* e2di_nblock is a number of disk block, not ext2fs block */
994 	node.e2di_nblock = fsbtodb(&sblock, 1);
995 	node.e2di_blocks[0] = alloc(node.e2di_size, node.e2di_mode);
996 	if (node.e2di_blocks[0] == 0) {
997 		printf("%s: can't allocate block for root dir\n", __func__);
998 		return 0;
999 	}
1000 	wtfs(fsbtodb(&sblock, node.e2di_blocks[0]), sblock.e2fs_bsize, buf);
1001 	iput(&node, EXT2_ROOTINO);
1002 	return 1;
1003 }
1004 
1005 /*
1006  * Construct a set of directory entries in "buf".
1007  * return size of directory.
1008  */
1009 int
1010 makedir(struct ext2fs_direct *protodir, int entries)
1011 {
1012 	uint8_t *cp;
1013 	uint i, spcleft;
1014 	uint dirblksiz;
1015 
1016 	dirblksiz = sblock.e2fs_bsize;
1017 	memset(buf, 0, dirblksiz);
1018 	spcleft = dirblksiz;
1019 	for (cp = buf, i = 0; i < entries - 1; i++) {
1020 		protodir[i].e2d_reclen = EXT2FS_DIRSIZ(protodir[i].e2d_namlen);
1021 		copy_dir(&protodir[i], (struct ext2fs_direct *)cp);
1022 		cp += protodir[i].e2d_reclen;
1023 		spcleft -= protodir[i].e2d_reclen;
1024 	}
1025 	protodir[i].e2d_reclen = spcleft;
1026 	copy_dir(&protodir[i], (struct ext2fs_direct *)cp);
1027 	return dirblksiz;
1028 }
1029 
1030 /*
1031  * Copy a direntry to a buffer, in fs byte order
1032  */
1033 static void
1034 copy_dir(struct ext2fs_direct *dir, struct ext2fs_direct *dbuf)
1035 {
1036 
1037 	memcpy(dbuf, dir, EXT2FS_DIRSIZ(dir->e2d_namlen));
1038 	dbuf->e2d_ino = h2fs32(dir->e2d_ino);
1039 	dbuf->e2d_reclen = h2fs16(dir->e2d_reclen);
1040 }
1041 
1042 /*
1043  * void init_resizeino(const struct timeval *tv);
1044  *
1045  *	Initialize the EXT2_RESEIZE_INO inode to preserve
1046  *	reserved group descriptor blocks for future growth of this ext2fs.
1047  */
1048 void
1049 init_resizeino(const struct timeval *tv)
1050 {
1051 	struct ext2fs_dinode node;
1052 	uint64_t isize;
1053 	uint32_t *dindir_block, *reserved_gdb;
1054 	uint nblock, i, cylno, n;
1055 
1056 	memset(&node, 0, sizeof(node));
1057 
1058 	/*
1059 	 * Note this function only prepares required structures for
1060 	 * future resize. It's a quite different work to implement
1061 	 * a utility like resize_ext2fs(8) which handles actual
1062 	 * resize ops even on offline.
1063 	 *
1064 	 * Anyway, I'm not sure if there is any documentation about
1065 	 * this resize ext2fs feature and related data structures,
1066 	 * and I've written this function based on things what I see
1067 	 * on some existing implementation and real file system data
1068 	 * created by existing tools. To be honest, they are not
1069 	 * so easy to read, so I will try to implement it here without
1070 	 * any dumb optimization for people who would eventually
1071 	 * work on "yet another wheel" like resize_ext2fs(8).
1072 	 */
1073 
1074 	/*
1075 	 * I'm not sure what type is appropriate for this inode.
1076 	 * The release notes of e2fsprogs says they changed e2fsck to allow
1077 	 * IFREG for RESIZEINO since a certain resize tool used it. Hmm.
1078 	 */
1079 	node.e2di_mode = EXT2_IFREG | EXT2_RESIZEINOUMASK;
1080 	node.e2di_uid = geteuid();
1081 	node.e2di_atime = tv->tv_sec;
1082 	node.e2di_ctime = tv->tv_sec;
1083 	node.e2di_mtime = tv->tv_sec;
1084 	node.e2di_gid = getegid();
1085 	node.e2di_nlink = 1;
1086 
1087 	/*
1088 	 * To preserve the reserved group descriptor blocks,
1089 	 * EXT2_RESIZEINO uses only double indirect reference
1090 	 * blocks in its inode entries.
1091 	 *
1092 	 * All entries for direct, single indirect and triple
1093 	 * indirect references are left zero'ed. Maybe it's safe
1094 	 * because no write operation will happen with this inode.
1095 	 *
1096 	 * We have to allocate a block for the first level double
1097 	 * indirect reference block. Indexes of inode entries in
1098 	 * this first level dindirect block are corresponding to
1099 	 * indexes of group descriptors including both used (e2fs_ngdb)
1100 	 * and reserved (e2fs_reserved_ngdb) group descriptor blocks.
1101 	 *
1102 	 * Inode entries of indexes for used (e2fs_ngdb) descriptors are
1103 	 * left zero'ed. Entries for reserved (e2fs_reserved_ngdb) ones
1104 	 * have block numbers of actual reserved group descriptors
1105 	 * allocated at block group zero. This means e2fs_reserved_ngdb
1106 	 * blocks are reserved as the second level dindirect reference
1107 	 * blocks, and they actually contain block numbers of indirect
1108 	 * references. It may be safe since they don't have to keep any
1109 	 * data yet.
1110 	 *
1111 	 * Each these second dindirect blocks (i.e. reserved group
1112 	 * descriptor blocks in the first block group) should have
1113 	 * block numbers of its backups in all other block groups.
1114 	 * I.e. reserved_ngdb[0] block in block group 0 contains block
1115 	 * numbers of resreved_ngdb[0] from group 1 through (e2fs_ncg - 1).
1116 	 * The number of backups can be determined by the
1117 	 * EXT2_ROCOMPAT_SPARSESUPER feature and cg_has_sb() macro
1118 	 * as done in the above initcg() function.
1119 	 */
1120 
1121 	/* set e2di_size which occupies whole blocks through DINDIR blocks */
1122 	isize = (uint64_t)sblock.e2fs_bsize * NDADDR +
1123 	    (uint64_t)sblock.e2fs_bsize * NINDIR(&sblock) +
1124 	    (uint64_t)sblock.e2fs_bsize * NINDIR(&sblock) * NINDIR(&sblock);
1125 	if (isize > UINT32_MAX &&
1126 	    (sblock.e2fs.e2fs_features_rocompat &
1127 	     EXT2F_ROCOMPAT_LARGEFILE) == 0) {
1128 		/* XXX should enable it here and update all backups? */
1129 		errx(EXIT_FAILURE, "%s: large_file rocompat feature is "
1130 		    "required to enable resize feature for this filesystem\n",
1131 		    __func__);
1132 	}
1133 	/* upper 32bit is stored into e2di_dacl on REV1 feature */
1134 	node.e2di_size = isize & UINT32_MAX;
1135 	node.e2di_dacl = isize >> 32;
1136 
1137 #define SINGLE	0	/* index of single indirect block */
1138 #define DOUBLE	1	/* index of double indirect block */
1139 #define TRIPLE	2	/* index of triple indirect block */
1140 
1141 	/* zero out entries for direct references */
1142 	for (i = 0; i < NDADDR; i++)
1143 		node.e2di_blocks[i] = 0;
1144 	/* also zero out entries for single and triple indirect references */
1145 	node.e2di_blocks[NDADDR + SINGLE] = 0;
1146 	node.e2di_blocks[NDADDR + TRIPLE] = 0;
1147 
1148 	/* allocate a block for the first level double indirect reference */
1149 	node.e2di_blocks[NDADDR + DOUBLE] =
1150 	    alloc(sblock.e2fs_bsize, node.e2di_mode);
1151 	if (node.e2di_blocks[NDADDR + DOUBLE] == 0)
1152 		errx(EXIT_FAILURE, "%s: Can't allocate a dindirect block",
1153 		    __func__);
1154 
1155 	/* account this first block */
1156 	nblock = fsbtodb(&sblock, 1);
1157 
1158 	/* allocate buffer to set data in the dindirect block */
1159 	dindir_block = malloc(sblock.e2fs_bsize);
1160 	if (dindir_block == NULL)
1161 		errx(EXIT_FAILURE,
1162 		    "%s: Can't allocate buffer for a dindirect block",
1163 		    __func__);
1164 
1165 	/* allocate buffer to set data in the group descriptor blocks */
1166 	reserved_gdb = malloc(sblock.e2fs_bsize);
1167 	if (reserved_gdb == NULL)
1168 		errx(EXIT_FAILURE,
1169 		    "%s: Can't allocate buffer for group descriptor blocks",
1170 		    __func__);
1171 
1172 	/*
1173 	 * Setup block entries in the first level dindirect blocks
1174 	 */
1175 	for (i = 0; i < sblock.e2fs_ngdb; i++) {
1176 		/* no need to handle used group descriptor blocks */
1177 		dindir_block[i] = 0;
1178 	}
1179 	for (; i < sblock.e2fs_ngdb + sblock.e2fs.e2fs_reserved_ngdb; i++) {
1180 		/*
1181 		 * point reserved group descriptor block in the first
1182 		 * (i.e. master) block group
1183 		 *
1184 		 * XXX: e2fsprogs seem to use "(i % NINDIR(&sblock))" here
1185 		 *      to store maximum NINDIR(&sblock) reserved gdbs.
1186 		 *      I'm not sure what will be done on future filesystem
1187 		 *      shrink in that case on their way.
1188 		 */
1189 		if (i >= NINDIR(&sblock))
1190 			errx(EXIT_FAILURE, "%s: too many reserved "
1191 			    "group descriptors (%u) for resize inode",
1192 			    __func__, sblock.e2fs.e2fs_reserved_ngdb);
1193 		dindir_block[i] =
1194 		    h2fs32(cgbase(&sblock, 0) + NBLOCK_SUPERBLOCK + i);
1195 
1196 		/*
1197 		 * Setup block entries in the second dindirect blocks
1198 		 * (which are primary reserved group descriptor blocks)
1199 		 * to point their backups.
1200 		 */
1201 		for (n = 0, cylno = 1; cylno < sblock.e2fs_ncg; cylno++) {
1202 			/* skip block groups without backup */
1203 			if ((sblock.e2fs.e2fs_features_rocompat &
1204 			     EXT2F_ROCOMPAT_SPARSESUPER) != 0 &&
1205 			    cg_has_sb(cylno) == 0)
1206 				continue;
1207 
1208 			if (n >= NINDIR(&sblock))
1209 				errx(EXIT_FAILURE, "%s: too many block groups "
1210 				    "for the resize feature", __func__);
1211 			/*
1212 			 * These blocks are already reserved in
1213 			 * initcg() so no need to use alloc() here.
1214 			 */
1215 			reserved_gdb[n++] = h2fs32(cgbase(&sblock, cylno) +
1216 			    NBLOCK_SUPERBLOCK + i);
1217 			nblock += fsbtodb(&sblock, 1);
1218 		}
1219 		for (; n < NINDIR(&sblock); n++)
1220 			reserved_gdb[n] = 0;
1221 
1222 		/* write group descriptor block as the second dindirect refs */
1223 		wtfs(fsbtodb(&sblock, fs2h32(dindir_block[i])),
1224 		    sblock.e2fs_bsize, reserved_gdb);
1225 		nblock += fsbtodb(&sblock, 1);
1226 	}
1227 	for (; i < NINDIR(&sblock); i++) {
1228 		/* leave trailing entries unallocated */
1229 		dindir_block[i] = 0;
1230 	}
1231 	free(reserved_gdb);
1232 
1233 	/* finally write the first level dindirect block */
1234 	wtfs(fsbtodb(&sblock, node.e2di_blocks[NDADDR + DOUBLE]),
1235 	    sblock.e2fs_bsize, dindir_block);
1236 	free(dindir_block);
1237 
1238 	node.e2di_nblock = nblock;
1239 	iput(&node, EXT2_RESIZEINO);
1240 }
1241 
1242 /*
1243  * uint32_t alloc(uint32_t size, uint16_t mode)
1244  *
1245  *	Allocate a block (from cylinder group 0)
1246  *	Reference: src/sys/ufs/ext2fs/ext2fs_alloc.c:ext2fs_alloccg()
1247  */
1248 uint32_t
1249 alloc(uint32_t size, uint16_t mode)
1250 {
1251 	uint32_t loc, bno;
1252 	uint8_t *bbp;
1253 	uint len, map, i;
1254 
1255 	if (gd[0].ext2bgd_nbfree == 0)
1256 		return 0;
1257 
1258 	if (size > sblock.e2fs_bsize)
1259 		return 0;
1260 
1261 	bbp = malloc(sblock.e2fs_bsize);
1262 	if (bbp == NULL)
1263 		return 0;
1264 	rdfs(fsbtodb(&sblock, gd[0].ext2bgd_b_bitmap), sblock.e2fs_bsize, bbp);
1265 
1266 	/* XXX: kernel uses e2fs_fpg here */
1267 	len = sblock.e2fs.e2fs_bpg / NBBY;
1268 
1269 #if 0	/* no need block allocation for root or lost+found dir */
1270 	for (loc = 0; loc < len; loc++) {
1271 		if (bbp[loc] == 0) {
1272 			bno = loc * NBBY;
1273 			goto gotit;
1274 		}
1275 	}
1276 #endif
1277 
1278 	loc = skpc(~0U, len, bbp);
1279 	if (loc == 0)
1280 		return 0;
1281 	loc = len - loc;
1282 	map = bbp[loc];
1283 	bno = loc * NBBY;
1284 	for (i = 0; i < NBBY; i++, bno++) {
1285 		if ((map & (1 << i)) == 0)
1286 			goto gotit;
1287 	}
1288 	return 0;
1289 
1290  gotit:
1291 	if (isset(bbp, bno))
1292 		errx(EXIT_FAILURE, "%s: inconsistent bitmap\n", __func__);
1293 
1294 	setbit(bbp, bno);
1295 	wtfs(fsbtodb(&sblock, gd[0].ext2bgd_b_bitmap), sblock.e2fs_bsize, bbp);
1296 	free(bbp);
1297 	/* XXX: modified group descriptors won't be written into backups */
1298 	gd[0].ext2bgd_nbfree--;
1299 	if ((mode & EXT2_IFDIR) != 0)
1300 		gd[0].ext2bgd_ndirs++;
1301 	sblock.e2fs.e2fs_fbcount--;
1302 
1303 	return sblock.e2fs.e2fs_first_dblock + bno;
1304 }
1305 
1306 /*
1307  * void iput(struct ext2fs_dinode *ip, ino_t ino)
1308  *
1309  *	Put an inode entry into the corresponding table.
1310  */
1311 static void
1312 iput(struct ext2fs_dinode *ip, ino_t ino)
1313 {
1314 	daddr_t d;
1315 	uint c, i;
1316 	struct ext2fs_dinode *dp;
1317 	uint8_t *bp;
1318 
1319 	bp = malloc(sblock.e2fs_bsize);
1320 	if (bp == NULL)
1321 		errx(EXIT_FAILURE, "%s: can't allocate buffer for inode\n",
1322 		    __func__);
1323 
1324 	/*
1325 	 * Reserved inodes are allocated and accounted in initcg()
1326 	 * so skip checks of the bitmap and allocation for them.
1327 	 */
1328 	if (ino >= EXT2_FIRSTINO) {
1329 		c = ino_to_cg(&sblock, ino);
1330 
1331 		/* sanity check */
1332 		if (gd[c].ext2bgd_nifree == 0)
1333 			errx(EXIT_FAILURE,
1334 			    "%s: no free inode %" PRIu64 " in block group %u\n",
1335 			    __func__, (uint64_t)ino, c);
1336 
1337 		/* update inode bitmap */
1338 		rdfs(fsbtodb(&sblock, gd[0].ext2bgd_i_bitmap),
1339 		    sblock.e2fs_bsize, bp);
1340 
1341 		/* more sanity */
1342 		if (isset(bp, EXT2_INO_INDEX(ino)))
1343 			errx(EXIT_FAILURE, "%s: inode %" PRIu64
1344 			    " already in use\n", __func__, (uint64_t)ino);
1345 		setbit(bp, EXT2_INO_INDEX(ino));
1346 		wtfs(fsbtodb(&sblock, gd[0].ext2bgd_i_bitmap),
1347 		    sblock.e2fs_bsize, bp);
1348 		gd[c].ext2bgd_nifree--;
1349 		sblock.e2fs.e2fs_ficount--;
1350 	}
1351 
1352 	if (ino >= sblock.e2fs.e2fs_ipg * sblock.e2fs_ncg)
1353 		errx(EXIT_FAILURE, "%s: inode value out of range (%" PRIu64
1354 		    ").\n", __func__, (uint64_t)ino);
1355 
1356 	/* update an inode entry in the table */
1357 	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
1358 	rdfs(d, sblock.e2fs_bsize, bp);
1359 
1360 	dp = (struct ext2fs_dinode *)(bp +
1361 	    inodesize * ino_to_fsbo(&sblock, ino));
1362 	e2fs_isave(ip, dp);
1363 	/* e2fs_i_bswap() doesn't swap e2di_blocks addrs */
1364 	if ((ip->e2di_mode & EXT2_IFMT) != EXT2_IFLNK) {
1365 		for (i = 0; i < NDADDR + NIADDR; i++)
1366 			dp->e2di_blocks[i] = h2fs32(ip->e2di_blocks[i]);
1367 	}
1368 	/* h2fs32() just for consistency */
1369 	dp->e2di_gen = h2fs32(arc4random());
1370 
1371 	wtfs(d, sblock.e2fs_bsize, bp);
1372 	free(bp);
1373 }
1374 
1375 /*
1376  * Read a block from the file system
1377  */
1378 void
1379 rdfs(daddr_t bno, int size, void *bf)
1380 {
1381 	int n;
1382 	off_t offset;
1383 
1384 	offset = bno;
1385 	n = pread(fsi, bf, size, offset * sectorsize);
1386 	if (n != size)
1387 		err(EXIT_FAILURE, "%s: read error for sector %" PRId64,
1388 		    __func__, (int64_t)bno);
1389 }
1390 
1391 /*
1392  * Write a block to the file system
1393  */
1394 void
1395 wtfs(daddr_t bno, int size, void *bf)
1396 {
1397 	int n;
1398 	off_t offset;
1399 
1400 	if (Nflag)
1401 		return;
1402 	offset = bno;
1403 	errno = 0;
1404 	n = pwrite(fso, bf, size, offset * sectorsize);
1405 	if (n != size)
1406 		err(EXIT_FAILURE, "%s: write error for sector %" PRId64,
1407 		    __func__, (int64_t)bno);
1408 }
1409 
1410 int
1411 ilog2(uint val)
1412 {
1413 
1414 	if (val == 0 || !powerof2(val))
1415 		errx(EXIT_FAILURE, "%s: %u is not a power of 2\n",
1416 		    __func__, val);
1417 
1418 	return ffs(val) - 1;
1419 }
1420 
1421 /*
1422  * int skpc(int mask, size_t size, uint8_t *cp)
1423  *
1424  *	Locate an unsigned character of value mask inside cp[].
1425  * 	(from src/sys/lib/libkern/skpc.c)
1426  */
1427 int
1428 skpc(int mask, size_t size, uint8_t *cp)
1429 {
1430 	uint8_t *end;
1431 
1432 	end = &cp[size];
1433 	while (cp < end && *cp == (uint8_t)mask)
1434 		cp++;
1435 
1436 	return end - cp;
1437 }
1438