xref: /openbsd/sbin/newfs_ext2fs/mke2fs.c (revision 91f110e0)
1 /* $OpenBSD: mke2fs.c,v 1.6 2013/12/27 19:17:28 deraadt 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 	/* Umm, why not e2fs_log_fsize? */
242 	sblock.e2fs.e2fs_fsize = ilog2(fsize) - LOG_MINBSIZE;
243 
244 	sblock.e2fs_bsize = bsize;
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 = malloc(sblock.e2fs_ngdb * bsize);
469 	if (gd == NULL)
470 		errx(EXIT_FAILURE, "Can't allocate descriptors buffer");
471 	memset(gd, 0, sblock.e2fs_ngdb * bsize);
472 
473 	fbcount = 0;
474 	ficount = 0;
475 	for (cylno = 0; cylno < ncg; cylno++) {
476 		uint boffset;
477 
478 		boffset = cgbase(&sblock, cylno);
479 		if (sblock.e2fs.e2fs_rev == E2FS_REV0 ||
480 		    (sblock.e2fs.e2fs_features_rocompat &
481 		     EXT2F_ROCOMPAT_SPARSESUPER) == 0 ||
482 		    cg_has_sb(cylno)) {
483 			boffset += NBLOCK_SUPERBLOCK + sblock.e2fs_ngdb;
484 			if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
485 			    (sblock.e2fs.e2fs_features_compat &
486 			     EXT2F_COMPAT_RESIZE) != 0)
487 				boffset += sblock.e2fs.e2fs_reserved_ngdb;
488 		}
489 		gd[cylno].ext2bgd_b_bitmap = boffset;
490 		boffset += NBLOCK_BLOCK_BITMAP;
491 		gd[cylno].ext2bgd_i_bitmap = boffset;
492 		boffset += NBLOCK_INODE_BITMAP;
493 		gd[cylno].ext2bgd_i_tables = boffset;
494 		if (cylno == (ncg - 1))
495 			gd[cylno].ext2bgd_nbfree =
496 			    blocks_lastcg - cgoverhead(cylno);
497 		else
498 			gd[cylno].ext2bgd_nbfree =
499 			    sblock.e2fs.e2fs_bpg - cgoverhead(cylno);
500 		fbcount += gd[cylno].ext2bgd_nbfree;
501 		gd[cylno].ext2bgd_nifree = sblock.e2fs.e2fs_ipg;
502 		if (cylno == 0) {
503 			/* take reserved inodes off nifree */
504 			gd[cylno].ext2bgd_nifree -= EXT2_RESERVED_INODES;
505 		}
506 		ficount += gd[cylno].ext2bgd_nifree;
507 		gd[cylno].ext2bgd_ndirs = 0;
508 	}
509 	sblock.e2fs.e2fs_fbcount = fbcount;
510 	sblock.e2fs.e2fs_ficount = ficount;
511 
512 	/*
513 	 * Dump out summary information about file system.
514 	 */
515 	if (verbosity > 0) {
516 		printf("%s: %u.%1uMB (%" PRId64 " sectors) "
517 		    "block size %u, fragment size %u\n",
518 		    fsys,
519 		    (uint)(((uint64_t)bcount * bsize) / (1024 * 1024)),
520 		    (uint)((uint64_t)bcount * bsize -
521 		    rounddown((uint64_t)bcount * bsize, 1024 * 1024))
522 		    / 1024 / 100,
523 		    fssize, bsize, fsize);
524 		printf("\tusing %u block groups of %u.0MB, %u blks, "
525 		    "%u inodes.\n",
526 		    ncg, bsize * sblock.e2fs.e2fs_bpg / (1024 * 1024),
527 		    sblock.e2fs.e2fs_bpg, sblock.e2fs.e2fs_ipg);
528 	}
529 
530 	/*
531 	 * allocate space for superblock and group descriptors
532 	 */
533 	iobufsize = (NBLOCK_SUPERBLOCK + sblock.e2fs_ngdb) * sblock.e2fs_bsize;
534 	iobuf = mmap(0, iobufsize, PROT_READ|PROT_WRITE,
535 	    MAP_ANON|MAP_PRIVATE, -1, 0);
536 	if (iobuf == NULL)
537 		errx(EXIT_FAILURE, "Cannot allocate I/O buffer\n");
538 	memset(iobuf, 0, iobufsize);
539 
540 	/*
541 	 * We now start writing to the filesystem
542 	 */
543 
544 	if (!Nflag) {
545 		static const uint pbsize[] = { 1024, 2048, 4096, 0 };
546 		uint pblock, epblock;
547 		/*
548 		 * Validate the given file system size.
549 		 * Verify that its last block can actually be accessed.
550 		 * Convert to file system fragment sized units.
551 		 */
552 		if (fssize <= 0)
553 			errx(EXIT_FAILURE, "Preposterous size %" PRId64 "\n",
554 			    fssize);
555 		wtfs(fssize - 1, sectorsize, iobuf);
556 
557 		/*
558 		 * Ensure there is nothing that looks like a filesystem
559 		 * superblock anywhere other than where ours will be.
560 		 * If fsck_ext2fs finds the wrong one all hell breaks loose!
561 		 *
562 		 * XXX: needs to check how fsck_ext2fs programs even
563 		 *      on other OSes determine alternate superblocks
564 		 */
565 		for (i = 0; pbsize[i] != 0; i++) {
566 			epblock = (uint64_t)bcount * bsize / pbsize[i];
567 			for (pblock = ((pbsize[i] == SBSIZE) ? 1 : 0);
568 			    pblock < epblock;
569 			    pblock += pbsize[i] * NBBY /* bpg */)
570 				zap_old_sblock((daddr32_t)pblock *
571 				    pbsize[i] / sectorsize);
572 		}
573 	}
574 
575 	if (verbosity >= 3)
576 		printf("super-block backups (for fsck_ext2fs -b #) at:\n");
577 	/* If we are printing more than one line of numbers, line up columns */
578 	fld_width = verbosity < 4 ? 1 : snprintf(NULL, 0, "%" PRIu64,
579 	    (uint64_t)cgbase(&sblock, ncg - 1));
580 	/* Get terminal width */
581 	if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) == 0)
582 		max_cols = winsize.ws_col;
583 	else
584 		max_cols = 80;
585 	if (Nflag && verbosity == 3)
586 		/* Leave space to add " ..." after one row of numbers */
587 		max_cols -= 4;
588 #define BASE 0x10000	/* For some fixed-point maths */
589 	col = 0;
590 	delta = verbosity > 2 ? 0 : max_cols * BASE / ncg;
591 	for (cylno = 0; cylno < ncg; cylno++) {
592 		fflush(stdout);
593 		initcg(cylno);
594 		if (verbosity < 2)
595 			continue;
596 		/* the first one is a master, not backup */
597 		if (cylno == 0)
598 			continue;
599 		/* skip if this cylinder doesn't have a backup */
600 		if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
601 		    (sblock.e2fs.e2fs_features_rocompat &
602 		     EXT2F_ROCOMPAT_SPARSESUPER) != 0 &&
603 		    cg_has_sb(cylno) == 0)
604 			continue;
605 
606 		if (delta > 0) {
607 			if (Nflag)
608 				/* No point doing dots for -N */
609 				break;
610 			/* Print dots scaled to end near RH margin */
611 			for (col += delta; col > BASE; col -= BASE)
612 				printf(".");
613 			continue;
614 		}
615 		/* Print superblock numbers */
616 		len = printf(" %*" PRIu64 "," + !col, fld_width,
617 		    (uint64_t)cgbase(&sblock, cylno));
618 		col += len;
619 		if (col + len < max_cols)
620 			/* Next number fits */
621 			continue;
622 		/* Next number won't fit, need a newline */
623 		if (verbosity <= 3) {
624 			/* Print dots for subsequent cylinder groups */
625 			delta = sblock.e2fs_ncg - cylno - 1;
626 			if (delta != 0) {
627 				if (Nflag) {
628 					printf(" ...");
629 					break;
630 				}
631 				delta = max_cols * BASE / delta;
632 			}
633 		}
634 		col = 0;
635 		printf("\n");
636 	}
637 #undef BASE
638 	if (col > 0)
639 		printf("\n");
640 	if (Nflag)
641 		return;
642 
643 	/*
644 	 * Now construct the initial file system,
645 	 */
646 	if (fsinit(&tv) == 0)
647 		errx(EXIT_FAILURE, "Error making filesystem");
648 	/*
649 	 * Write out the superblock and group descriptors
650 	 */
651 	sblock.e2fs.e2fs_block_group_nr = 0;
652 	sboff = 0;
653 	if (cgbase(&sblock, 0) == 0) {
654 		/*
655 		 * If the first block contains the boot block sectors,
656 		 * (i.e. in case of sblock.e2fs.e2fs_bsize > BBSIZE)
657 		 * we have to preserve data in it.
658 		 */
659 		sboff = SBOFF;
660 	}
661 	e2fs_sbsave(&sblock.e2fs, (struct ext2fs *)(iobuf + sboff));
662 	e2fs_cgsave(gd, (struct ext2_gd *)(iobuf + sblock.e2fs_bsize),
663 	   sizeof(struct ext2_gd) * sblock.e2fs_ncg);
664 	wtfs(fsbtodb(&sblock, cgbase(&sblock, 0)) + sboff / sectorsize,
665 	    iobufsize - sboff, iobuf + sboff);
666 
667 	munmap(iobuf, iobufsize);
668 }
669 
670 /*
671  * Initialize a cylinder (block) group.
672  */
673 void
674 initcg(uint cylno)
675 {
676 	uint nblcg, i, j, sboff;
677 	struct ext2fs_dinode *dp;
678 
679 	/*
680 	 * Make a copy of the superblock and group descriptors.
681 	 */
682 	if (sblock.e2fs.e2fs_rev == E2FS_REV0 ||
683 	    (sblock.e2fs.e2fs_features_rocompat &
684 	     EXT2F_ROCOMPAT_SPARSESUPER) == 0 ||
685 	    cg_has_sb(cylno)) {
686 		sblock.e2fs.e2fs_block_group_nr = cylno;
687 		sboff = 0;
688 		if (cgbase(&sblock, cylno) == 0) {
689 			/* preserve data in bootblock in cg0 */
690 			sboff = SBOFF;
691 		}
692 		e2fs_sbsave(&sblock.e2fs, (struct ext2fs *)(iobuf + sboff));
693 		e2fs_cgsave(gd, (struct ext2_gd *)(iobuf +
694 		    sblock.e2fs_bsize * NBLOCK_SUPERBLOCK),
695 		    sizeof(struct ext2_gd) * sblock.e2fs_ncg);
696 		/* write superblock and group descriptor backups */
697 		wtfs(fsbtodb(&sblock, cgbase(&sblock, cylno)) +
698 		    sboff / sectorsize, iobufsize - sboff, iobuf + sboff);
699 	}
700 
701 	/*
702 	 * Initialize block bitmap.
703 	 */
704 	memset(buf, 0, sblock.e2fs_bsize);
705 	if (cylno == (sblock.e2fs_ncg - 1)) {
706 		/* The last group could have less blocks than e2fs_bpg. */
707 		nblcg = sblock.e2fs.e2fs_bcount -
708 		    cgbase(&sblock, sblock.e2fs_ncg - 1);
709 		for (i = nblcg; i < roundup(nblcg, NBBY); i++)
710 			setbit(buf, i);
711 		memset(&buf[i / NBBY], ~0U, sblock.e2fs.e2fs_bpg - i);
712 	}
713 	/* set overhead (superblock, group descriptor etc.) blocks used */
714 	for (i = 0; i < cgoverhead(cylno) / NBBY; i++)
715 		buf[i] = ~0;
716 	i = i * NBBY;
717 	for (; i < cgoverhead(cylno); i++)
718 		setbit(buf, i);
719 	wtfs(fsbtodb(&sblock, gd[cylno].ext2bgd_b_bitmap), sblock.e2fs_bsize,
720 	    buf);
721 
722 	/*
723 	 * Initialize inode bitmap.
724 	 *
725 	 *  Assume e2fs_ipg is a multiple of NBBY since
726 	 *  it's a multiple of e2fs_ipb (as we did above).
727 	 *  Note even (possibly smaller) the last group has the same e2fs_ipg.
728 	 */
729 	i = sblock.e2fs.e2fs_ipg / NBBY;
730 	memset(buf, 0, i);
731 	memset(buf + i, ~0U, sblock.e2fs_bsize - i);
732 	if (cylno == 0) {
733 		/* mark reserved inodes */
734 		for (i = 1; i < EXT2_FIRSTINO; i++)
735 			setbit(buf, EXT2_INO_INDEX(i));
736 	}
737 	wtfs(fsbtodb(&sblock, gd[cylno].ext2bgd_i_bitmap), sblock.e2fs_bsize,
738 	    buf);
739 
740 	/*
741 	 * Initialize inode tables.
742 	 *
743 	 *  Just initialize generation numbers for NFS security.
744 	 *  XXX: sys/ufs/ext2fs/ext2fs_alloc.c:ext2fs_valloc() seems
745 	 *       to override these generated numbers.
746 	 */
747 	memset(buf, 0, sblock.e2fs_bsize);
748 	for (i = 0; i < sblock.e2fs_itpg; i++) {
749 		for (j = 0; j < sblock.e2fs_ipb; j++) {
750 			dp = (struct ext2fs_dinode *)(buf + inodesize * j);
751 			/* h2fs32() just for consistency */
752 			dp->e2di_gen = h2fs32(arc4random());
753 		}
754 		wtfs(fsbtodb(&sblock, gd[cylno].ext2bgd_i_tables + i),
755 		    sblock.e2fs_bsize, buf);
756 	}
757 }
758 
759 /*
760  * Zap possible lingering old superblock data
761  */
762 static void
763 zap_old_sblock(daddr32_t sec)
764 {
765 	static daddr32_t cg0_data;
766 	uint32_t oldfs[SBSIZE / sizeof(uint32_t)];
767 	static const struct fsm {
768 		uint32_t offset;
769 		uint32_t magic;
770 		uint32_t mask;
771 	} fs_magics[] = {
772 		{offsetof(struct ext2fs, e2fs_magic) / 4, E2FS_MAGIC, 0xffff},
773 		{offsetof(struct ext2fs, e2fs_magic) / 4,
774 		    E2FS_MAGIC << 16, 0xffff0000},
775 		{14, 0xef530000, 0xffff0000},	/* EXT2FS (big) */
776 		{0x55c / 4, 0x00011954, ~0U},	/* FS_UFS1_MAGIC */
777 		{0x55c / 4, 0x19540119, ~0U},	/* FS_UFS2_MAGIC */
778 		{0, 0x70162, ~0U},		/* LFS_MAGIC */
779 		{.offset = ~0U},
780 	};
781 	const struct fsm *fsm;
782 
783 	if (Nflag)
784 		return;
785 
786 	/* don't override data before superblock */
787 	if (sec < SBOFF / sectorsize)
788 		return;
789 
790 	if (cg0_data == 0) {
791 		cg0_data =
792 		    ((daddr32_t)sblock.e2fs.e2fs_first_dblock + cgoverhead(0)) *
793 		    sblock.e2fs_bsize / sectorsize;
794 	}
795 
796 	/* Ignore anything that is beyond our filesystem */
797 	if (sec >= fssize)
798 		return;
799 	/* Zero anything inside our filesystem... */
800 	if (sec >= sblock.e2fs.e2fs_first_dblock * bsize / sectorsize) {
801 		/* ...unless we will write that area anyway */
802 		if (sec >= cg0_data)
803 			/* assume iobuf is zero'ed here */
804 			wtfs(sec, roundup(SBSIZE, sectorsize), iobuf);
805 		return;
806 	}
807 
808 	/*
809 	 * The sector might contain boot code, so we must validate it
810 	 *
811 	 * XXX: ext2fs won't preserve data after SBOFF,
812 	 *      but first_dblock could have a different value.
813 	 */
814 	rdfs(sec, sizeof(oldfs), &oldfs);
815 	for (fsm = fs_magics;; fsm++) {
816 		uint32_t v;
817 		if (fsm->mask == 0)
818 			return;
819 		v = oldfs[fsm->offset];
820 		if ((v & fsm->mask) == fsm->magic ||
821 		    (swap32(v) & fsm->mask) == fsm->magic)
822 			break;
823 	}
824 
825 	/* Just zap the magic number */
826 	oldfs[fsm->offset] = 0;
827 	wtfs(sec, sizeof(oldfs), &oldfs);
828 }
829 
830 /*
831  * uint cgoverhead(uint c)
832  *
833  * 	Return a number of reserved blocks on the specified group.
834  * 	XXX: should be shared with src/sbin/fsck_ext2fs/setup.c
835  */
836 uint
837 cgoverhead(uint c)
838 {
839 	uint overh;
840 
841 	overh = NBLOCK_BLOCK_BITMAP + NBLOCK_INODE_BITMAP + sblock.e2fs_itpg;
842 
843 	if (sblock.e2fs.e2fs_rev == E2FS_REV0 ||
844 	    (sblock.e2fs.e2fs_features_rocompat &
845 	     EXT2F_ROCOMPAT_SPARSESUPER) == 0 ||
846 	    cg_has_sb(c) != 0) {
847 		overh += NBLOCK_SUPERBLOCK + sblock.e2fs_ngdb;
848 
849 		if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
850 		    (sblock.e2fs.e2fs_features_compat &
851 		     EXT2F_COMPAT_RESIZE) != 0)
852 			overh += sblock.e2fs.e2fs_reserved_ngdb;
853 	}
854 
855 	return overh;
856 }
857 
858 /*
859  * Initialize the file system
860  */
861 
862 #define LOSTDIR		/* e2fsck complains if there is no lost+found */
863 
864 #define	PREDEFDIR	2
865 
866 #ifdef LOSTDIR
867 #define	PREDEFROOTDIR	(PREDEFDIR + 1)
868 #else
869 #define	PREDEFROOTDIR	PREDEFDIR
870 #endif
871 
872 struct ext2fs_direct root_dir[] = {
873 	{ EXT2_ROOTINO, 0, 1, 0, "." },
874 	{ EXT2_ROOTINO, 0, 2, 0, ".." },
875 #ifdef LOSTDIR
876 	{ EXT2_LOSTFOUNDINO, 0, 10, 0, "lost+found" },
877 #endif
878 };
879 
880 #ifdef LOSTDIR
881 struct ext2fs_direct lost_found_dir[] = {
882 	{ EXT2_LOSTFOUNDINO, 0, 1, 0, "." },
883 	{ EXT2_ROOTINO, 0, 2, 0, ".." },
884 };
885 struct ext2fs_direct pad_dir = { 0, sizeof(struct ext2fs_direct), 0, 0, "" };
886 #endif
887 
888 int
889 fsinit(const struct timeval *tv)
890 {
891 	struct ext2fs_dinode node;
892 #ifdef LOSTDIR
893 	uint i, nblks_lostfound, blk;
894 #endif
895 
896 	/*
897 	 * Initialize the inode for the resizefs feature
898 	 */
899 	if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
900 	    (sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_RESIZE) != 0)
901 		init_resizeino(tv);
902 
903 	/*
904 	 * Initialize the node
905 	 */
906 
907 #ifdef LOSTDIR
908 	/*
909 	 * Create the lost+found directory
910 	 */
911 	if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
912 	    sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) {
913 		lost_found_dir[0].e2d_type = EXT2_FT_DIR;
914 		lost_found_dir[1].e2d_type = EXT2_FT_DIR;
915 	}
916 	(void)makedir(lost_found_dir, nitems(lost_found_dir));
917 
918 	/* prepare a bit large directory for preserved files */
919 	nblks_lostfound = EXT2_LOSTFOUNDSIZE / sblock.e2fs_bsize;
920 	/* ...but only with direct blocks */
921 	if (nblks_lostfound > NDADDR)
922 		nblks_lostfound = NDADDR;
923 
924 	memset(&node, 0, sizeof(node));
925 	node.e2di_mode = EXT2_IFDIR | EXT2_LOSTFOUNDUMASK;
926 	node.e2di_uid_low = geteuid();
927 	node.e2di_size = sblock.e2fs_bsize * nblks_lostfound;
928 	node.e2di_atime = (u_int32_t)tv->tv_sec;
929 	node.e2di_ctime = (u_int32_t)tv->tv_sec;
930 	node.e2di_mtime = (u_int32_t)tv->tv_sec;
931 	node.e2di_gid_low = getegid();
932 	node.e2di_nlink = PREDEFDIR;
933 	/* e2di_nblock is a number of disk blocks, not ext2fs blocks */
934 	node.e2di_nblock = fsbtodb(&sblock, nblks_lostfound);
935 	node.e2di_blocks[0] = alloc(sblock.e2fs_bsize, node.e2di_mode);
936 	if (node.e2di_blocks[0] == 0) {
937 		printf("%s: can't allocate block for lost+found\n", __func__);
938 		return 0;
939 	}
940 	for (i = 1; i < nblks_lostfound; i++) {
941 		blk = alloc(sblock.e2fs_bsize, 0);
942 		if (blk == 0) {
943 			printf("%s: can't allocate blocks for lost+found\n",
944 			    __func__);
945 			return 0;
946 		}
947 		node.e2di_blocks[i] = blk;
948 	}
949 	wtfs(fsbtodb(&sblock, node.e2di_blocks[0]), sblock.e2fs_bsize, buf);
950 	pad_dir.e2d_reclen = sblock.e2fs_bsize;
951 	for (i = 1; i < nblks_lostfound; i++) {
952 		memset(buf, 0, sblock.e2fs_bsize);
953 		copy_dir(&pad_dir, (struct ext2fs_direct *)buf);
954 		wtfs(fsbtodb(&sblock, node.e2di_blocks[i]), sblock.e2fs_bsize,
955 		    buf);
956 	}
957 	iput(&node, EXT2_LOSTFOUNDINO);
958 #endif
959 	/*
960 	 * create the root directory
961 	 */
962 	memset(&node, 0, sizeof(node));
963 	if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
964 	    sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) {
965 		root_dir[0].e2d_type = EXT2_FT_DIR;
966 		root_dir[1].e2d_type = EXT2_FT_DIR;
967 #ifdef LOSTDIR
968 		root_dir[2].e2d_type = EXT2_FT_DIR;
969 #endif
970 	}
971 	node.e2di_mode = EXT2_IFDIR | EXT2_UMASK;
972 	node.e2di_uid_low = geteuid();
973 	node.e2di_size = makedir(root_dir, nitems(root_dir));
974 	node.e2di_atime = (u_int32_t)tv->tv_sec;
975 	node.e2di_ctime = (u_int32_t)tv->tv_sec;
976 	node.e2di_mtime = (u_int32_t)tv->tv_sec;
977 	node.e2di_gid_low = getegid();
978 	node.e2di_nlink = PREDEFROOTDIR;
979 	/* e2di_nblock is a number of disk block, not ext2fs block */
980 	node.e2di_nblock = fsbtodb(&sblock, 1);
981 	node.e2di_blocks[0] = alloc(node.e2di_size, node.e2di_mode);
982 	if (node.e2di_blocks[0] == 0) {
983 		printf("%s: can't allocate block for root dir\n", __func__);
984 		return 0;
985 	}
986 	wtfs(fsbtodb(&sblock, node.e2di_blocks[0]), sblock.e2fs_bsize, buf);
987 	iput(&node, EXT2_ROOTINO);
988 	return 1;
989 }
990 
991 /*
992  * Construct a set of directory entries in "buf".
993  * return size of directory.
994  */
995 int
996 makedir(struct ext2fs_direct *protodir, int entries)
997 {
998 	uint8_t *cp;
999 	uint i, spcleft;
1000 	uint dirblksiz;
1001 
1002 	dirblksiz = sblock.e2fs_bsize;
1003 	memset(buf, 0, dirblksiz);
1004 	spcleft = dirblksiz;
1005 	for (cp = buf, i = 0; i < entries - 1; i++) {
1006 		protodir[i].e2d_reclen = EXT2FS_DIRSIZ(protodir[i].e2d_namlen);
1007 		copy_dir(&protodir[i], (struct ext2fs_direct *)cp);
1008 		cp += protodir[i].e2d_reclen;
1009 		spcleft -= protodir[i].e2d_reclen;
1010 	}
1011 	protodir[i].e2d_reclen = spcleft;
1012 	copy_dir(&protodir[i], (struct ext2fs_direct *)cp);
1013 	return dirblksiz;
1014 }
1015 
1016 /*
1017  * Copy a direntry to a buffer, in fs byte order
1018  */
1019 static void
1020 copy_dir(struct ext2fs_direct *dir, struct ext2fs_direct *dbuf)
1021 {
1022 
1023 	memcpy(dbuf, dir, EXT2FS_DIRSIZ(dir->e2d_namlen));
1024 	dbuf->e2d_ino = h2fs32(dir->e2d_ino);
1025 	dbuf->e2d_reclen = h2fs16(dir->e2d_reclen);
1026 }
1027 
1028 /*
1029  * void init_resizeino(const struct timeval *tv);
1030  *
1031  *	Initialize the EXT2_RESEIZE_INO inode to preserve
1032  *	reserved group descriptor blocks for future growth of this ext2fs.
1033  */
1034 void
1035 init_resizeino(const struct timeval *tv)
1036 {
1037 	struct ext2fs_dinode node;
1038 	uint64_t isize;
1039 	uint32_t *dindir_block, *reserved_gdb;
1040 	uint nblock, i, cylno, n;
1041 
1042 	memset(&node, 0, sizeof(node));
1043 
1044 	/*
1045 	 * Note this function only prepares required structures for
1046 	 * future resize. It's a quite different work to implement
1047 	 * a utility like resize_ext2fs(8) which handles actual
1048 	 * resize ops even on offline.
1049 	 *
1050 	 * Anyway, I'm not sure if there is any documentation about
1051 	 * this resize ext2fs feature and related data structures,
1052 	 * and I've written this function based on things what I see
1053 	 * on some existing implementation and real file system data
1054 	 * created by existing tools. To be honest, they are not
1055 	 * so easy to read, so I will try to implement it here without
1056 	 * any dumb optimization for people who would eventually
1057 	 * work on "yet another wheel" like resize_ext2fs(8).
1058 	 */
1059 
1060 	/*
1061 	 * I'm not sure what type is appropriate for this inode.
1062 	 * The release notes of e2fsprogs says they changed e2fsck to allow
1063 	 * IFREG for RESIZEINO since a certain resize tool used it. Hmm.
1064 	 */
1065 	node.e2di_mode = EXT2_IFREG | EXT2_RESIZEINOUMASK;
1066 	node.e2di_uid_low = geteuid();
1067 	node.e2di_atime = (u_int32_t)tv->tv_sec;
1068 	node.e2di_ctime = (u_int32_t)tv->tv_sec;
1069 	node.e2di_mtime = (u_int32_t)tv->tv_sec;
1070 	node.e2di_gid_low = getegid();
1071 	node.e2di_nlink = 1;
1072 
1073 	/*
1074 	 * To preserve the reserved group descriptor blocks,
1075 	 * EXT2_RESIZEINO uses only double indirect reference
1076 	 * blocks in its inode entries.
1077 	 *
1078 	 * All entries for direct, single indirect and triple
1079 	 * indirect references are left zero'ed. Maybe it's safe
1080 	 * because no write operation will happen with this inode.
1081 	 *
1082 	 * We have to allocate a block for the first level double
1083 	 * indirect reference block. Indexes of inode entries in
1084 	 * this first level dindirect block are corresponding to
1085 	 * indexes of group descriptors including both used (e2fs_ngdb)
1086 	 * and reserved (e2fs_reserved_ngdb) group descriptor blocks.
1087 	 *
1088 	 * Inode entries of indexes for used (e2fs_ngdb) descriptors are
1089 	 * left zero'ed. Entries for reserved (e2fs_reserved_ngdb) ones
1090 	 * have block numbers of actual reserved group descriptors
1091 	 * allocated at block group zero. This means e2fs_reserved_ngdb
1092 	 * blocks are reserved as the second level dindirect reference
1093 	 * blocks, and they actually contain block numbers of indirect
1094 	 * references. It may be safe since they don't have to keep any
1095 	 * data yet.
1096 	 *
1097 	 * Each these second dindirect blocks (i.e. reserved group
1098 	 * descriptor blocks in the first block group) should have
1099 	 * block numbers of its backups in all other block groups.
1100 	 * I.e. reserved_ngdb[0] block in block group 0 contains block
1101 	 * numbers of resreved_ngdb[0] from group 1 through (e2fs_ncg - 1).
1102 	 * The number of backups can be determined by the
1103 	 * EXT2_ROCOMPAT_SPARSESUPER feature and cg_has_sb() macro
1104 	 * as done in the above initcg() function.
1105 	 */
1106 
1107 	/* set e2di_size which occupies whole blocks through DINDIR blocks */
1108 	isize = (uint64_t)sblock.e2fs_bsize * NDADDR +
1109 	    (uint64_t)sblock.e2fs_bsize * NINDIR(&sblock) +
1110 	    (uint64_t)sblock.e2fs_bsize * NINDIR(&sblock) * NINDIR(&sblock);
1111 	if (isize > UINT32_MAX &&
1112 	    (sblock.e2fs.e2fs_features_rocompat &
1113 	     EXT2F_ROCOMPAT_LARGEFILE) == 0) {
1114 		/* XXX should enable it here and update all backups? */
1115 		errx(EXIT_FAILURE, "%s: large_file rocompat feature is "
1116 		    "required to enable resize feature for this filesystem\n",
1117 		    __func__);
1118 	}
1119 	/* upper 32bit is stored into e2di_dacl on REV1 feature */
1120 	node.e2di_size = isize & UINT32_MAX;
1121 	node.e2di_dacl = isize >> 32;
1122 
1123 #define SINGLE	0	/* index of single indirect block */
1124 #define DOUBLE	1	/* index of double indirect block */
1125 #define TRIPLE	2	/* index of triple indirect block */
1126 
1127 	/* zero out entries for direct references */
1128 	for (i = 0; i < NDADDR; i++)
1129 		node.e2di_blocks[i] = 0;
1130 	/* also zero out entries for single and triple indirect references */
1131 	node.e2di_blocks[NDADDR + SINGLE] = 0;
1132 	node.e2di_blocks[NDADDR + TRIPLE] = 0;
1133 
1134 	/* allocate a block for the first level double indirect reference */
1135 	node.e2di_blocks[NDADDR + DOUBLE] =
1136 	    alloc(sblock.e2fs_bsize, node.e2di_mode);
1137 	if (node.e2di_blocks[NDADDR + DOUBLE] == 0)
1138 		errx(EXIT_FAILURE, "%s: Can't allocate a dindirect block",
1139 		    __func__);
1140 
1141 	/* account this first block */
1142 	nblock = fsbtodb(&sblock, 1);
1143 
1144 	/* allocate buffer to set data in the dindirect block */
1145 	dindir_block = malloc(sblock.e2fs_bsize);
1146 	if (dindir_block == NULL)
1147 		errx(EXIT_FAILURE,
1148 		    "%s: Can't allocate buffer for a dindirect block",
1149 		    __func__);
1150 
1151 	/* allocate buffer to set data in the group descriptor blocks */
1152 	reserved_gdb = malloc(sblock.e2fs_bsize);
1153 	if (reserved_gdb == NULL)
1154 		errx(EXIT_FAILURE,
1155 		    "%s: Can't allocate buffer for group descriptor blocks",
1156 		    __func__);
1157 
1158 	/*
1159 	 * Setup block entries in the first level dindirect blocks
1160 	 */
1161 	for (i = 0; i < sblock.e2fs_ngdb; i++) {
1162 		/* no need to handle used group descriptor blocks */
1163 		dindir_block[i] = 0;
1164 	}
1165 	for (; i < sblock.e2fs_ngdb + sblock.e2fs.e2fs_reserved_ngdb; i++) {
1166 		/*
1167 		 * point reserved group descriptor block in the first
1168 		 * (i.e. master) block group
1169 		 *
1170 		 * XXX: e2fsprogs seem to use "(i % NINDIR(&sblock))" here
1171 		 *      to store maximum NINDIR(&sblock) reserved gdbs.
1172 		 *      I'm not sure what will be done on future filesystem
1173 		 *      shrink in that case on their way.
1174 		 */
1175 		if (i >= NINDIR(&sblock))
1176 			errx(EXIT_FAILURE, "%s: too many reserved "
1177 			    "group descriptors (%u) for resize inode",
1178 			    __func__, sblock.e2fs.e2fs_reserved_ngdb);
1179 		dindir_block[i] =
1180 		    h2fs32(cgbase(&sblock, 0) + NBLOCK_SUPERBLOCK + i);
1181 
1182 		/*
1183 		 * Setup block entries in the second dindirect blocks
1184 		 * (which are primary reserved group descriptor blocks)
1185 		 * to point their backups.
1186 		 */
1187 		for (n = 0, cylno = 1; cylno < sblock.e2fs_ncg; cylno++) {
1188 			/* skip block groups without backup */
1189 			if ((sblock.e2fs.e2fs_features_rocompat &
1190 			     EXT2F_ROCOMPAT_SPARSESUPER) != 0 &&
1191 			    cg_has_sb(cylno) == 0)
1192 				continue;
1193 
1194 			if (n >= NINDIR(&sblock))
1195 				errx(EXIT_FAILURE, "%s: too many block groups "
1196 				    "for the resize feature", __func__);
1197 			/*
1198 			 * These blocks are already reserved in
1199 			 * initcg() so no need to use alloc() here.
1200 			 */
1201 			reserved_gdb[n++] = h2fs32(cgbase(&sblock, cylno) +
1202 			    NBLOCK_SUPERBLOCK + i);
1203 			nblock += fsbtodb(&sblock, 1);
1204 		}
1205 		for (; n < NINDIR(&sblock); n++)
1206 			reserved_gdb[n] = 0;
1207 
1208 		/* write group descriptor block as the second dindirect refs */
1209 		wtfs(fsbtodb(&sblock, fs2h32(dindir_block[i])),
1210 		    sblock.e2fs_bsize, reserved_gdb);
1211 		nblock += fsbtodb(&sblock, 1);
1212 	}
1213 	for (; i < NINDIR(&sblock); i++) {
1214 		/* leave trailing entries unallocated */
1215 		dindir_block[i] = 0;
1216 	}
1217 	free(reserved_gdb);
1218 
1219 	/* finally write the first level dindirect block */
1220 	wtfs(fsbtodb(&sblock, node.e2di_blocks[NDADDR + DOUBLE]),
1221 	    sblock.e2fs_bsize, dindir_block);
1222 	free(dindir_block);
1223 
1224 	node.e2di_nblock = nblock;
1225 	iput(&node, EXT2_RESIZEINO);
1226 }
1227 
1228 /*
1229  * uint32_t alloc(uint32_t size, uint16_t mode)
1230  *
1231  *	Allocate a block (from cylinder group 0)
1232  *	Reference: src/sys/ufs/ext2fs/ext2fs_alloc.c:ext2fs_alloccg()
1233  */
1234 uint32_t
1235 alloc(uint32_t size, uint16_t mode)
1236 {
1237 	uint32_t loc, bno;
1238 	uint8_t *bbp;
1239 	uint len, map, i;
1240 
1241 	if (gd[0].ext2bgd_nbfree == 0)
1242 		return 0;
1243 
1244 	if (size > sblock.e2fs_bsize)
1245 		return 0;
1246 
1247 	bbp = malloc(sblock.e2fs_bsize);
1248 	if (bbp == NULL)
1249 		return 0;
1250 	rdfs(fsbtodb(&sblock, gd[0].ext2bgd_b_bitmap), sblock.e2fs_bsize, bbp);
1251 
1252 	/* XXX: kernel uses e2fs_fpg here */
1253 	len = sblock.e2fs.e2fs_bpg / NBBY;
1254 
1255 #if 0	/* no need block allocation for root or lost+found dir */
1256 	for (loc = 0; loc < len; loc++) {
1257 		if (bbp[loc] == 0) {
1258 			bno = loc * NBBY;
1259 			goto gotit;
1260 		}
1261 	}
1262 #endif
1263 
1264 	loc = skpc(~0U, len, bbp);
1265 	if (loc == 0) {
1266 		free(bbp);
1267 		return 0;
1268 	}
1269 	loc = len - loc;
1270 	map = bbp[loc];
1271 	bno = loc * NBBY;
1272 	for (i = 0; i < NBBY; i++, bno++) {
1273 		if ((map & (1 << i)) == 0)
1274 			goto gotit;
1275 	}
1276 	free(bbp);
1277 	return 0;
1278 
1279  gotit:
1280 	if (isset(bbp, bno))
1281 		errx(EXIT_FAILURE, "%s: inconsistent bitmap\n", __func__);
1282 
1283 	setbit(bbp, bno);
1284 	wtfs(fsbtodb(&sblock, gd[0].ext2bgd_b_bitmap), sblock.e2fs_bsize, bbp);
1285 	free(bbp);
1286 	/* XXX: modified group descriptors won't be written into backups */
1287 	gd[0].ext2bgd_nbfree--;
1288 	if ((mode & EXT2_IFDIR) != 0)
1289 		gd[0].ext2bgd_ndirs++;
1290 	sblock.e2fs.e2fs_fbcount--;
1291 
1292 	return sblock.e2fs.e2fs_first_dblock + bno;
1293 }
1294 
1295 /*
1296  * void iput(struct ext2fs_dinode *ip, ino_t ino)
1297  *
1298  *	Put an inode entry into the corresponding table.
1299  */
1300 static void
1301 iput(struct ext2fs_dinode *ip, ino_t ino)
1302 {
1303 	daddr32_t d;
1304 	uint c, i;
1305 	struct ext2fs_dinode *dp;
1306 	uint8_t *bp;
1307 
1308 	bp = malloc(sblock.e2fs_bsize);
1309 	if (bp == NULL)
1310 		errx(EXIT_FAILURE, "%s: can't allocate buffer for inode\n",
1311 		    __func__);
1312 
1313 	/*
1314 	 * Reserved inodes are allocated and accounted in initcg()
1315 	 * so skip checks of the bitmap and allocation for them.
1316 	 */
1317 	if (ino >= EXT2_FIRSTINO) {
1318 		c = ino_to_cg(&sblock, ino);
1319 
1320 		/* sanity check */
1321 		if (gd[c].ext2bgd_nifree == 0)
1322 			errx(EXIT_FAILURE,
1323 			    "%s: no free inode %" PRIu64 " in block group %u\n",
1324 			    __func__, (uint64_t)ino, c);
1325 
1326 		/* update inode bitmap */
1327 		rdfs(fsbtodb(&sblock, gd[0].ext2bgd_i_bitmap),
1328 		    sblock.e2fs_bsize, bp);
1329 
1330 		/* more sanity */
1331 		if (isset(bp, EXT2_INO_INDEX(ino)))
1332 			errx(EXIT_FAILURE, "%s: inode %" PRIu64
1333 			    " already in use\n", __func__, (uint64_t)ino);
1334 		setbit(bp, EXT2_INO_INDEX(ino));
1335 		wtfs(fsbtodb(&sblock, gd[0].ext2bgd_i_bitmap),
1336 		    sblock.e2fs_bsize, bp);
1337 		gd[c].ext2bgd_nifree--;
1338 		sblock.e2fs.e2fs_ficount--;
1339 	}
1340 
1341 	if (ino >= sblock.e2fs.e2fs_ipg * sblock.e2fs_ncg)
1342 		errx(EXIT_FAILURE, "%s: inode value out of range (%" PRIu64
1343 		    ").\n", __func__, (uint64_t)ino);
1344 
1345 	/* update an inode entry in the table */
1346 	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
1347 	rdfs(d, sblock.e2fs_bsize, bp);
1348 
1349 	dp = (struct ext2fs_dinode *)(bp +
1350 	    inodesize * ino_to_fsbo(&sblock, ino));
1351 	e2fs_isave(ip, dp);
1352 	/* e2fs_i_bswap() doesn't swap e2di_blocks addrs */
1353 	if ((ip->e2di_mode & EXT2_IFMT) != EXT2_IFLNK) {
1354 		for (i = 0; i < NDADDR + NIADDR; i++)
1355 			dp->e2di_blocks[i] = h2fs32(ip->e2di_blocks[i]);
1356 	}
1357 	/* h2fs32() just for consistency */
1358 	dp->e2di_gen = h2fs32(arc4random());
1359 
1360 	wtfs(d, sblock.e2fs_bsize, bp);
1361 	free(bp);
1362 }
1363 
1364 /*
1365  * Read a block from the file system
1366  */
1367 void
1368 rdfs(daddr32_t bno, int size, void *bf)
1369 {
1370 	int n;
1371 	off_t offset;
1372 
1373 	offset = bno;
1374 	n = pread(fsi, bf, size, offset * sectorsize);
1375 	if (n != size)
1376 		err(EXIT_FAILURE, "%s: read error for sector %" PRId64,
1377 		    __func__, (int64_t)bno);
1378 }
1379 
1380 /*
1381  * Write a block to the file system
1382  */
1383 void
1384 wtfs(daddr32_t bno, int size, void *bf)
1385 {
1386 	int n;
1387 	off_t offset;
1388 
1389 	if (Nflag)
1390 		return;
1391 	offset = bno;
1392 	n = pwrite(fso, bf, size, offset * sectorsize);
1393 	if (n != size)
1394 		err(EXIT_FAILURE, "%s: write error for sector %" PRId64,
1395 		    __func__, (int64_t)bno);
1396 }
1397 
1398 int
1399 ilog2(uint val)
1400 {
1401 
1402 	if (val == 0 || !powerof2(val))
1403 		errx(EXIT_FAILURE, "%s: %u is not a power of 2\n",
1404 		    __func__, val);
1405 
1406 	return ffs(val) - 1;
1407 }
1408 
1409 /*
1410  * int skpc(int mask, size_t size, uint8_t *cp)
1411  *
1412  *	Locate an unsigned character of value mask inside cp[].
1413  * 	(from src/sys/lib/libkern/skpc.c)
1414  */
1415 int
1416 skpc(int mask, size_t size, uint8_t *cp)
1417 {
1418 	uint8_t *end;
1419 
1420 	end = &cp[size];
1421 	while (cp < end && *cp == (uint8_t)mask)
1422 		cp++;
1423 
1424 	return end - cp;
1425 }
1426 
1427 static void
1428 uuid_get(struct m_ext2fs *sb)
1429 {
1430 	unsigned char buf[sizeof(sb->e2fs.e2fs_uuid)];
1431 
1432 	arc4random_buf(buf, sizeof(buf));
1433 	/* UUID version 4: random */
1434 	buf[6] &= 0x0f;
1435 	buf[6] |= 0x40;
1436 	/* RFC4122 variant */
1437 	buf[8] &= 0x3f;
1438 	buf[8] |= 0x80;
1439 	memcpy(sb->e2fs.e2fs_uuid, buf, sizeof(sb->e2fs.e2fs_uuid));
1440 }
1441