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