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