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