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