mkfs_ext2.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * mkfs_ext2: utility to create EXT2 filesystem
  4. * inspired by genext2fs
  5. *
  6. * Busybox'ed (2009) by Vladimir Dronnikov <dronnikov@gmail.com>
  7. *
  8. * Licensed under GPLv2, see file LICENSE in this tarball for details.
  9. */
  10. #include "libbb.h"
  11. #include <linux/fs.h>
  12. #include <linux/ext2_fs.h>
  13. #include "volume_id/volume_id_internal.h"
  14. #define ENABLE_FEATURE_MKFS_EXT2_RESERVED_GDT 0
  15. #define ENABLE_FEATURE_MKFS_EXT2_DIR_INDEX 1
  16. // from e2fsprogs
  17. #define s_reserved_gdt_blocks s_padding1
  18. #define s_mkfs_time s_reserved[0]
  19. #define s_flags s_reserved[22]
  20. #define EXT2_HASH_HALF_MD4 1
  21. #define EXT2_FLAGS_SIGNED_HASH 0x0001
  22. #define EXT2_FLAGS_UNSIGNED_HASH 0x0002
  23. // storage helpers
  24. char BUG_wrong_field_size(void);
  25. #define STORE_LE(field, value) \
  26. do { \
  27. if (sizeof(field) == 4) \
  28. field = cpu_to_le32(value); \
  29. else if (sizeof(field) == 2) \
  30. field = cpu_to_le16(value); \
  31. else if (sizeof(field) == 1) \
  32. field = (value); \
  33. else \
  34. BUG_wrong_field_size(); \
  35. } while (0)
  36. #define FETCH_LE32(field) \
  37. (sizeof(field) == 4 ? cpu_to_le32(field) : BUG_wrong_field_size())
  38. // All fields are little-endian
  39. struct ext2_dir {
  40. uint32_t inode1;
  41. uint16_t rec_len1;
  42. uint8_t name_len1;
  43. uint8_t file_type1;
  44. char name1[4];
  45. uint32_t inode2;
  46. uint16_t rec_len2;
  47. uint8_t name_len2;
  48. uint8_t file_type2;
  49. char name2[4];
  50. uint32_t inode3;
  51. uint16_t rec_len3;
  52. uint8_t name_len3;
  53. uint8_t file_type3;
  54. char name3[12];
  55. };
  56. static unsigned int_log2(unsigned arg)
  57. {
  58. unsigned r = 0;
  59. while ((arg >>= 1) != 0)
  60. r++;
  61. return r;
  62. }
  63. // taken from mkfs_minix.c. libbb candidate?
  64. // "uint32_t size", since we never use it for anything >32 bits
  65. static uint32_t div_roundup(uint32_t size, uint32_t n)
  66. {
  67. // Overflow-resistant
  68. uint32_t res = size / n;
  69. if (res * n != size)
  70. res++;
  71. return res;
  72. }
  73. static void allocate(uint8_t *bitmap, uint32_t blocksize, uint32_t start, uint32_t end)
  74. {
  75. uint32_t i;
  76. //bb_info_msg("ALLOC: [%u][%u][%u]: [%u-%u]:=[%x],[%x]", blocksize, start, end, start/8, blocksize - end/8 - 1, (1 << (start & 7)) - 1, (uint8_t)(0xFF00 >> (end & 7)));
  77. memset(bitmap, 0, blocksize);
  78. i = start / 8;
  79. memset(bitmap, 0xFF, i);
  80. bitmap[i] = (1 << (start & 7)) - 1; //0..7 => 00000000..01111111
  81. i = end / 8;
  82. bitmap[blocksize - i - 1] |= 0x7F00 >> (end & 7); //0..7 => 00000000..11111110
  83. memset(bitmap + blocksize - i, 0xFF, i); // N.B. no overflow here!
  84. }
  85. static uint32_t has_super(uint32_t x)
  86. {
  87. // 0, 1 and powers of 3, 5, 7 up to 2^32 limit
  88. static const uint32_t supers[] = {
  89. 0, 1, 3, 5, 7, 9, 25, 27, 49, 81, 125, 243, 343, 625, 729,
  90. 2187, 2401, 3125, 6561, 15625, 16807, 19683, 59049, 78125,
  91. 117649, 177147, 390625, 531441, 823543, 1594323, 1953125,
  92. 4782969, 5764801, 9765625, 14348907, 40353607, 43046721,
  93. 48828125, 129140163, 244140625, 282475249, 387420489,
  94. 1162261467, 1220703125, 1977326743, 3486784401/* >2^31 */,
  95. };
  96. const uint32_t *sp = supers + ARRAY_SIZE(supers);
  97. while (1) {
  98. sp--;
  99. if (x == *sp)
  100. return 1;
  101. if (x > *sp)
  102. return 0;
  103. }
  104. }
  105. #define fd 3 /* predefined output descriptor */
  106. static void PUT(uint64_t off, void *buf, uint32_t size)
  107. {
  108. // bb_info_msg("PUT[%llu]:[%u]", off, size);
  109. xlseek(fd, off, SEEK_SET);
  110. xwrite(fd, buf, size);
  111. }
  112. // 128 and 256-byte inodes:
  113. // 128-byte inode is described by struct ext2_inode.
  114. // 256-byte one just has these fields appended:
  115. // __u16 i_extra_isize;
  116. // __u16 i_pad1;
  117. // __u32 i_ctime_extra; /* extra Change time (nsec << 2 | epoch) */
  118. // __u32 i_mtime_extra; /* extra Modification time (nsec << 2 | epoch) */
  119. // __u32 i_atime_extra; /* extra Access time (nsec << 2 | epoch) */
  120. // __u32 i_crtime; /* File creation time */
  121. // __u32 i_crtime_extra; /* extra File creation time (nsec << 2 | epoch)*/
  122. // __u32 i_version_hi; /* high 32 bits for 64-bit version */
  123. // the rest is padding.
  124. //
  125. // linux/ext2_fs.h has "#define i_size_high i_dir_acl" which suggests that even
  126. // 128-byte inode is capable of describing large files (i_dir_acl is meaningful
  127. // only for directories, which never need i_size_high).
  128. //
  129. // Standard mke2fs creates a filesystem with 256-byte inodes if it is
  130. // bigger than 0.5GB. So far, we do not do this.
  131. // Standard mke2fs 1.41.9:
  132. // Usage: mke2fs [-c|-l filename] [-b block-size] [-f fragment-size]
  133. // [-i bytes-per-inode] [-I inode-size] [-J journal-options]
  134. // [-G meta group size] [-N number-of-inodes]
  135. // [-m reserved-blocks-percentage] [-o creator-os]
  136. // [-g blocks-per-group] [-L volume-label] [-M last-mounted-directory]
  137. // [-O feature[,...]] [-r fs-revision] [-E extended-option[,...]]
  138. // [-T fs-type] [-U UUID] [-jnqvFSV] device [blocks-count]
  139. //
  140. // Options not commented below are taken but silently ignored:
  141. enum {
  142. OPT_c = 1 << 0,
  143. OPT_l = 1 << 1,
  144. OPT_b = 1 << 2, // block size, in bytes
  145. OPT_f = 1 << 3,
  146. OPT_i = 1 << 4, // bytes per inode
  147. OPT_I = 1 << 5, // custom inode size, in bytes
  148. OPT_J = 1 << 6,
  149. OPT_G = 1 << 7,
  150. OPT_N = 1 << 8,
  151. OPT_m = 1 << 9, // percentage of blocks reserved for superuser
  152. OPT_o = 1 << 10,
  153. OPT_g = 1 << 11,
  154. OPT_L = 1 << 12, // label
  155. OPT_M = 1 << 13,
  156. OPT_O = 1 << 14,
  157. OPT_r = 1 << 15,
  158. OPT_E = 1 << 16,
  159. OPT_T = 1 << 17,
  160. OPT_U = 1 << 18,
  161. OPT_j = 1 << 19,
  162. OPT_n = 1 << 20, // dry run: do not write anything
  163. OPT_q = 1 << 21,
  164. OPT_v = 1 << 22,
  165. OPT_F = 1 << 23,
  166. OPT_S = 1 << 24,
  167. //OPT_V = 1 << 25, // -V version. bbox applets don't support that
  168. };
  169. int mkfs_ext2_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  170. int mkfs_ext2_main(int argc UNUSED_PARAM, char **argv)
  171. {
  172. unsigned i, pos, n;
  173. unsigned bs, bpi;
  174. unsigned blocksize, blocksize_log2;
  175. unsigned inodesize, user_inodesize;
  176. unsigned reserved_percent = 5;
  177. unsigned long long kilobytes;
  178. uint32_t nblocks, nblocks_full;
  179. uint32_t nreserved;
  180. uint32_t ngroups;
  181. uint32_t bytes_per_inode;
  182. uint32_t first_block;
  183. uint32_t inodes_per_group;
  184. uint32_t group_desc_blocks;
  185. uint32_t inode_table_blocks;
  186. uint32_t lost_and_found_blocks;
  187. time_t timestamp;
  188. const char *label = "";
  189. struct stat st;
  190. struct ext2_super_block *sb; // superblock
  191. struct ext2_group_desc *gd; // group descriptors
  192. struct ext2_inode *inode;
  193. struct ext2_dir *dir;
  194. uint8_t *buf;
  195. // using global "option_mask32" instead of local "opts":
  196. // we are register starved here
  197. opt_complementary = "-1:b+:m+:i+";
  198. /*opts =*/ getopt32(argv, "cl:b:f:i:I:J:G:N:m:o:g:L:M:O:r:E:T:U:jnqvFS",
  199. NULL, &bs, NULL, &bpi, &user_inodesize, NULL, NULL, NULL,
  200. &reserved_percent, NULL, NULL, &label, NULL, NULL, NULL, NULL, NULL, NULL);
  201. argv += optind; // argv[0] -- device
  202. // check the device is a block device
  203. xmove_fd(xopen(argv[0], O_WRONLY), fd);
  204. fstat(fd, &st);
  205. if (!S_ISBLK(st.st_mode) && !(option_mask32 & OPT_F))
  206. bb_error_msg_and_die("not a block device");
  207. // check if it is mounted
  208. // N.B. what if we format a file? find_mount_point will return false negative since
  209. // it is loop block device which mounted!
  210. if (find_mount_point(argv[0], 0))
  211. bb_error_msg_and_die("can't format mounted filesystem");
  212. // open the device, get size in kbytes
  213. if (argv[1]) {
  214. kilobytes = xatoull(argv[1]);
  215. // seek past end fails on block devices but works on files
  216. if (lseek(fd, kilobytes * 1024 - 1, SEEK_SET) != (off_t)-1) {
  217. if (!(option_mask32 & OPT_n))
  218. xwrite(fd, "", 1); // file grows if needed
  219. }
  220. //else {
  221. // bb_error_msg("warning, block device is smaller");
  222. //}
  223. } else {
  224. kilobytes = (uoff_t)xlseek(fd, 0, SEEK_END) / 1024;
  225. }
  226. bytes_per_inode = 16384;
  227. if (kilobytes < 512*1024)
  228. bytes_per_inode = 4096;
  229. if (kilobytes < 3*1024)
  230. bytes_per_inode = 8192;
  231. if (option_mask32 & OPT_i)
  232. bytes_per_inode = bpi;
  233. // Determine block size and inode size
  234. // block size is a multiple of 1024
  235. // inode size is a multiple of 128
  236. blocksize = 1024;
  237. inodesize = sizeof(struct ext2_inode); // 128
  238. if (kilobytes >= 512*1024) { // mke2fs 1.41.9 compat
  239. blocksize = 4096;
  240. inodesize = 256;
  241. }
  242. if (EXT2_MAX_BLOCK_SIZE > 4096) {
  243. // kilobytes >> 22 == size in 4gigabyte chunks.
  244. // if size >= 16k gigs, blocksize must be increased.
  245. // Try "mke2fs -F image $((16 * 1024*1024*1024))"
  246. while ((kilobytes >> 22) >= blocksize)
  247. blocksize *= 2;
  248. }
  249. if (option_mask32 & OPT_b)
  250. blocksize = bs;
  251. if (blocksize < EXT2_MIN_BLOCK_SIZE
  252. || blocksize > EXT2_MAX_BLOCK_SIZE
  253. || (blocksize & (blocksize - 1)) // not power of 2
  254. ) {
  255. bb_error_msg_and_die("blocksize %u is bad", blocksize);
  256. }
  257. // Do we have custom inode size?
  258. if (option_mask32 & OPT_I) {
  259. if (user_inodesize < sizeof(*inode)
  260. || user_inodesize > blocksize
  261. || (user_inodesize & (user_inodesize - 1)) // not power of 2
  262. ) {
  263. bb_error_msg("-%c is bad", 'I');
  264. } else {
  265. inodesize = user_inodesize;
  266. }
  267. }
  268. if ((int32_t)bytes_per_inode < blocksize)
  269. bb_error_msg_and_die("-%c is bad", 'i');
  270. // number of bits in one block, i.e. 8*blocksize
  271. #define blocks_per_group (8 * blocksize)
  272. first_block = (EXT2_MIN_BLOCK_SIZE == blocksize);
  273. blocksize_log2 = int_log2(blocksize);
  274. // Determine number of blocks
  275. kilobytes >>= (blocksize_log2 - EXT2_MIN_BLOCK_LOG_SIZE);
  276. nblocks = kilobytes;
  277. if (nblocks != kilobytes)
  278. bb_error_msg_and_die("block count doesn't fit in 32 bits");
  279. #define kilobytes kilobytes_unused_after_this
  280. // Experimentally, standard mke2fs won't work on images smaller than 60k
  281. if (nblocks < 60)
  282. bb_error_msg_and_die("need >= 60 blocks");
  283. // How many reserved blocks?
  284. if (reserved_percent > 50)
  285. bb_error_msg_and_die("-%c is bad", 'm');
  286. nreserved = (uint64_t)nblocks * reserved_percent / 100;
  287. // N.B. killing e2fsprogs feature! Unused blocks don't account in calculations
  288. nblocks_full = nblocks;
  289. // If last block group is too small, nblocks may be decreased in order
  290. // to discard it, and control returns here to recalculate some
  291. // parameters.
  292. // Note: blocksize and bytes_per_inode are never recalculated.
  293. retry:
  294. // N.B. a block group can have no more than blocks_per_group blocks
  295. ngroups = div_roundup(nblocks - first_block, blocks_per_group);
  296. group_desc_blocks = div_roundup(ngroups, blocksize / sizeof(*gd));
  297. // TODO: reserved blocks must be marked as such in the bitmaps,
  298. // or resulting filesystem is corrupt
  299. if (ENABLE_FEATURE_MKFS_EXT2_RESERVED_GDT) {
  300. /*
  301. * From e2fsprogs: Calculate the number of GDT blocks to reserve for online
  302. * filesystem growth.
  303. * The absolute maximum number of GDT blocks we can reserve is determined by
  304. * the number of block pointers that can fit into a single block.
  305. * We set it at 1024x the current filesystem size, or
  306. * the upper block count limit (2^32), whichever is lower.
  307. */
  308. uint32_t reserved_group_desc_blocks = 0xFFFFFFFF; // maximum block number
  309. if (nblocks < reserved_group_desc_blocks / 1024)
  310. reserved_group_desc_blocks = nblocks * 1024;
  311. reserved_group_desc_blocks = div_roundup(reserved_group_desc_blocks - first_block, blocks_per_group);
  312. reserved_group_desc_blocks = div_roundup(reserved_group_desc_blocks, blocksize / sizeof(*gd)) - group_desc_blocks;
  313. if (reserved_group_desc_blocks > blocksize / sizeof(uint32_t))
  314. reserved_group_desc_blocks = blocksize / sizeof(uint32_t);
  315. //TODO: STORE_LE(sb->s_reserved_gdt_blocks, reserved_group_desc_blocks);
  316. group_desc_blocks += reserved_group_desc_blocks;
  317. }
  318. {
  319. // N.B. e2fsprogs does as follows!
  320. uint32_t overhead, remainder;
  321. // ninodes is the max number of inodes in this filesystem
  322. uint32_t ninodes = ((uint64_t) nblocks_full * blocksize) / bytes_per_inode;
  323. if (ninodes < EXT2_GOOD_OLD_FIRST_INO+1)
  324. ninodes = EXT2_GOOD_OLD_FIRST_INO+1;
  325. inodes_per_group = div_roundup(ninodes, ngroups);
  326. // minimum number because the first EXT2_GOOD_OLD_FIRST_INO-1 are reserved
  327. if (inodes_per_group < 16)
  328. inodes_per_group = 16;
  329. // a block group can't have more inodes than blocks
  330. if (inodes_per_group > blocks_per_group)
  331. inodes_per_group = blocks_per_group;
  332. // adjust inodes per group so they completely fill the inode table blocks in the descriptor
  333. inodes_per_group = (div_roundup(inodes_per_group * inodesize, blocksize) * blocksize) / inodesize;
  334. // make sure the number of inodes per group is a multiple of 8
  335. inodes_per_group &= ~7;
  336. inode_table_blocks = div_roundup(inodes_per_group * inodesize, blocksize);
  337. // to be useful, lost+found should occupy at least 2 blocks (but not exceeding 16*1024 bytes),
  338. // and at most EXT2_NDIR_BLOCKS. So reserve these blocks right now
  339. /* Or e2fsprogs comment verbatim (what does it mean?):
  340. * Ensure that lost+found is at least 2 blocks, so we always
  341. * test large empty blocks for big-block filesystems. */
  342. lost_and_found_blocks = MIN(EXT2_NDIR_BLOCKS, 16 >> (blocksize_log2 - EXT2_MIN_BLOCK_LOG_SIZE));
  343. // the last group needs more attention: isn't it too small for possible overhead?
  344. overhead = (has_super(ngroups - 1) ? (1/*sb*/ + group_desc_blocks) : 0) + 1/*bbmp*/ + 1/*ibmp*/ + inode_table_blocks;
  345. remainder = (nblocks - first_block) % blocks_per_group;
  346. ////can't happen, nblocks >= 60 guarantees this
  347. ////if ((1 == ngroups)
  348. //// && remainder
  349. //// && (remainder < overhead + 1/* "/" */ + lost_and_found_blocks)
  350. ////) {
  351. //// bb_error_msg_and_die("way small device");
  352. ////}
  353. // Standard mke2fs uses 50. Looks like a bug in our calculation
  354. // of "remainder" or "overhead" - we don't match standard mke2fs
  355. // when we transition from one group to two groups
  356. // (a bit after 8M image size), but it works for two->three groups
  357. // transition (at 16M).
  358. if (remainder && (remainder < overhead + 50)) {
  359. //bb_info_msg("CHOP[%u]", remainder);
  360. nblocks -= remainder;
  361. goto retry;
  362. }
  363. }
  364. if (nblocks_full - nblocks)
  365. printf("warning: %u blocks unused\n\n", nblocks_full - nblocks);
  366. printf(
  367. "Filesystem label=%s\n"
  368. "OS type: Linux\n"
  369. "Block size=%u (log=%u)\n"
  370. "Fragment size=%u (log=%u)\n"
  371. "%u inodes, %u blocks\n"
  372. "%u blocks (%u%%) reserved for the super user\n"
  373. "First data block=%u\n"
  374. "Maximum filesystem blocks=%u\n"
  375. "%u block groups\n"
  376. "%u blocks per group, %u fragments per group\n"
  377. "%u inodes per group"
  378. , label
  379. , blocksize, blocksize_log2 - EXT2_MIN_BLOCK_LOG_SIZE
  380. , blocksize, blocksize_log2 - EXT2_MIN_BLOCK_LOG_SIZE
  381. , inodes_per_group * ngroups, nblocks
  382. , nreserved, reserved_percent
  383. , first_block
  384. , group_desc_blocks * (blocksize / (unsigned)sizeof(*gd)) * blocks_per_group
  385. , ngroups
  386. , blocks_per_group, blocks_per_group
  387. , inodes_per_group
  388. );
  389. {
  390. const char *fmt = "\nSuperblock backups stored on blocks:\n"
  391. "\t%u";
  392. pos = first_block;
  393. for (i = 1; i < ngroups; i++) {
  394. pos += blocks_per_group;
  395. if (has_super(i)) {
  396. printf(fmt, (unsigned)pos);
  397. fmt = ", %u";
  398. }
  399. }
  400. }
  401. bb_putchar('\n');
  402. if (option_mask32 & OPT_n) {
  403. if (ENABLE_FEATURE_CLEAN_UP)
  404. close(fd);
  405. return EXIT_SUCCESS;
  406. }
  407. // TODO: 3/5 refuse if mounted
  408. // TODO: 4/5 compat options
  409. // TODO: 1/5 sanity checks
  410. // TODO: 0/5 more verbose error messages
  411. // TODO: 4/5 bigendianness: recheck, wait for ARM reporters
  412. // TODO: 2/5 reserved GDT: how to mark but not allocate?
  413. // TODO: 3/5 dir_index?
  414. // fill the superblock
  415. sb = xzalloc(1024);
  416. STORE_LE(sb->s_rev_level, EXT2_DYNAMIC_REV); // revision 1 filesystem
  417. STORE_LE(sb->s_magic, EXT2_SUPER_MAGIC);
  418. STORE_LE(sb->s_inode_size, inodesize);
  419. // set "Required extra isize" and "Desired extra isize" fields to 28
  420. if (inodesize != sizeof(*inode))
  421. STORE_LE(sb->s_reserved[21], 0x001C001C);
  422. STORE_LE(sb->s_first_ino, EXT2_GOOD_OLD_FIRST_INO);
  423. STORE_LE(sb->s_log_block_size, blocksize_log2 - EXT2_MIN_BLOCK_LOG_SIZE);
  424. STORE_LE(sb->s_log_frag_size, blocksize_log2 - EXT2_MIN_BLOCK_LOG_SIZE);
  425. // first 1024 bytes of the device are for boot record. If block size is 1024 bytes, then
  426. // the first block is 1, otherwise 0
  427. STORE_LE(sb->s_first_data_block, first_block);
  428. // block and inode bitmaps occupy no more than one block, so maximum number of blocks is
  429. STORE_LE(sb->s_blocks_per_group, blocks_per_group);
  430. STORE_LE(sb->s_frags_per_group, blocks_per_group);
  431. // blocks
  432. STORE_LE(sb->s_blocks_count, nblocks);
  433. // reserve blocks for superuser
  434. STORE_LE(sb->s_r_blocks_count, nreserved);
  435. // ninodes
  436. STORE_LE(sb->s_inodes_per_group, inodes_per_group);
  437. STORE_LE(sb->s_inodes_count, inodes_per_group * ngroups);
  438. STORE_LE(sb->s_free_inodes_count, inodes_per_group * ngroups - EXT2_GOOD_OLD_FIRST_INO);
  439. // timestamps
  440. timestamp = time(NULL);
  441. STORE_LE(sb->s_mkfs_time, timestamp);
  442. STORE_LE(sb->s_wtime, timestamp);
  443. STORE_LE(sb->s_lastcheck, timestamp);
  444. // misc. Values are chosen to match mke2fs 1.41.9
  445. STORE_LE(sb->s_state, 1); // TODO: what's 1?
  446. STORE_LE(sb->s_creator_os, EXT2_OS_LINUX);
  447. STORE_LE(sb->s_checkinterval, 24*60*60 * 180); // 180 days
  448. STORE_LE(sb->s_errors, EXT2_ERRORS_DEFAULT);
  449. // mke2fs 1.41.9 also sets EXT3_FEATURE_COMPAT_RESIZE_INODE
  450. // and if >= 0.5GB, EXT3_FEATURE_RO_COMPAT_LARGE_FILE.
  451. // we use values which match "mke2fs -O ^resize_inode":
  452. // in this case 1.41.9 never sets EXT3_FEATURE_RO_COMPAT_LARGE_FILE.
  453. STORE_LE(sb->s_feature_compat, EXT2_FEATURE_COMPAT_SUPP
  454. | (EXT2_FEATURE_COMPAT_RESIZE_INO * ENABLE_FEATURE_MKFS_EXT2_RESERVED_GDT)
  455. | (EXT2_FEATURE_COMPAT_DIR_INDEX * ENABLE_FEATURE_MKFS_EXT2_DIR_INDEX)
  456. );
  457. STORE_LE(sb->s_feature_incompat, EXT2_FEATURE_INCOMPAT_FILETYPE);
  458. STORE_LE(sb->s_feature_ro_compat, EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER);
  459. STORE_LE(sb->s_flags, EXT2_FLAGS_UNSIGNED_HASH * ENABLE_FEATURE_MKFS_EXT2_DIR_INDEX);
  460. generate_uuid(sb->s_uuid);
  461. if (ENABLE_FEATURE_MKFS_EXT2_DIR_INDEX) {
  462. STORE_LE(sb->s_def_hash_version, EXT2_HASH_HALF_MD4);
  463. generate_uuid((uint8_t *)sb->s_hash_seed);
  464. }
  465. /*
  466. * From e2fsprogs: add "jitter" to the superblock's check interval so that we
  467. * don't check all the filesystems at the same time. We use a
  468. * kludgy hack of using the UUID to derive a random jitter value.
  469. */
  470. STORE_LE(sb->s_max_mnt_count,
  471. EXT2_DFL_MAX_MNT_COUNT
  472. + (sb->s_uuid[ARRAY_SIZE(sb->s_uuid)-1] % EXT2_DFL_MAX_MNT_COUNT));
  473. // write the label
  474. safe_strncpy((char *)sb->s_volume_name, label, sizeof(sb->s_volume_name));
  475. // calculate filesystem skeleton structures
  476. gd = xzalloc(group_desc_blocks * blocksize);
  477. buf = xmalloc(blocksize);
  478. sb->s_free_blocks_count = 0;
  479. for (i = 0, pos = first_block, n = nblocks - first_block;
  480. i < ngroups;
  481. i++, pos += blocks_per_group, n -= blocks_per_group
  482. ) {
  483. uint32_t overhead = pos + (has_super(i) ? (1/*sb*/ + group_desc_blocks) : 0);
  484. uint32_t free_blocks;
  485. // fill group descriptors
  486. STORE_LE(gd[i].bg_block_bitmap, overhead + 0);
  487. STORE_LE(gd[i].bg_inode_bitmap, overhead + 1);
  488. STORE_LE(gd[i].bg_inode_table, overhead + 2);
  489. overhead = overhead - pos + 1/*bbmp*/ + 1/*ibmp*/ + inode_table_blocks;
  490. gd[i].bg_free_inodes_count = inodes_per_group;
  491. //STORE_LE(gd[i].bg_used_dirs_count, 0);
  492. // N.B. both "/" and "/lost+found" are within the first block group
  493. // "/" occupies 1 block, "/lost+found" occupies lost_and_found_blocks...
  494. if (0 == i) {
  495. // ... thus increased overhead for the first block group ...
  496. overhead += 1 + lost_and_found_blocks;
  497. // ... and 2 used directories
  498. STORE_LE(gd[i].bg_used_dirs_count, 2);
  499. // well known reserved inodes belong to the first block too
  500. gd[i].bg_free_inodes_count -= EXT2_GOOD_OLD_FIRST_INO;
  501. }
  502. // cache free block count of the group
  503. free_blocks = (n < blocks_per_group ? n : blocks_per_group) - overhead;
  504. // mark preallocated blocks as allocated
  505. //bb_info_msg("ALLOC: [%u][%u][%u]", blocksize, overhead, blocks_per_group - (free_blocks + overhead));
  506. allocate(buf, blocksize,
  507. // reserve "overhead" blocks
  508. overhead,
  509. // mark unused trailing blocks
  510. blocks_per_group - (free_blocks + overhead)
  511. );
  512. // dump block bitmap
  513. PUT((uint64_t)(FETCH_LE32(gd[i].bg_block_bitmap)) * blocksize, buf, blocksize);
  514. STORE_LE(gd[i].bg_free_blocks_count, free_blocks);
  515. // mark preallocated inodes as allocated
  516. allocate(buf, blocksize,
  517. // mark reserved inodes
  518. inodes_per_group - gd[i].bg_free_inodes_count,
  519. // mark unused trailing inodes
  520. blocks_per_group - inodes_per_group
  521. );
  522. // dump inode bitmap
  523. //PUT((uint64_t)(FETCH_LE32(gd[i].bg_block_bitmap)) * blocksize, buf, blocksize);
  524. //but it's right after block bitmap, so we can just:
  525. xwrite(fd, buf, blocksize);
  526. STORE_LE(gd[i].bg_free_inodes_count, gd[i].bg_free_inodes_count);
  527. // count overall free blocks
  528. sb->s_free_blocks_count += free_blocks;
  529. }
  530. STORE_LE(sb->s_free_blocks_count, sb->s_free_blocks_count);
  531. // dump filesystem skeleton structures
  532. // printf("Writing superblocks and filesystem accounting information: ");
  533. for (i = 0, pos = first_block; i < ngroups; i++, pos += blocks_per_group) {
  534. // dump superblock and group descriptors and their backups
  535. if (has_super(i)) {
  536. // N.B. 1024 byte blocks are special
  537. PUT(((uint64_t)pos * blocksize) + ((0 == i && 1024 != blocksize) ? 1024 : 0),
  538. sb, 1024);
  539. PUT(((uint64_t)pos * blocksize) + blocksize,
  540. gd, group_desc_blocks * blocksize);
  541. }
  542. }
  543. // zero boot sectors
  544. memset(buf, 0, blocksize);
  545. PUT(0, buf, 1024); // N.B. 1024 <= blocksize, so buf[0..1023] contains zeros
  546. // zero inode tables
  547. for (i = 0; i < ngroups; ++i)
  548. for (n = 0; n < inode_table_blocks; ++n)
  549. PUT((uint64_t)(FETCH_LE32(gd[i].bg_inode_table) + n) * blocksize,
  550. buf, blocksize);
  551. // prepare directory inode
  552. inode = (struct ext2_inode *)buf;
  553. STORE_LE(inode->i_mode, S_IFDIR | S_IRWXU | S_IRGRP | S_IROTH | S_IXGRP | S_IXOTH);
  554. STORE_LE(inode->i_mtime, timestamp);
  555. STORE_LE(inode->i_atime, timestamp);
  556. STORE_LE(inode->i_ctime, timestamp);
  557. STORE_LE(inode->i_size, blocksize);
  558. // inode->i_blocks stores the number of 512 byte data blocks
  559. // (512, because it goes directly to struct stat without scaling)
  560. STORE_LE(inode->i_blocks, blocksize / 512);
  561. // dump root dir inode
  562. STORE_LE(inode->i_links_count, 3); // "/.", "/..", "/lost+found/.." point to this inode
  563. STORE_LE(inode->i_block[0], FETCH_LE32(gd[0].bg_inode_table) + inode_table_blocks);
  564. PUT(((uint64_t)FETCH_LE32(gd[0].bg_inode_table) * blocksize) + (EXT2_ROOT_INO-1) * inodesize,
  565. buf, inodesize);
  566. // dump lost+found dir inode
  567. STORE_LE(inode->i_links_count, 2); // both "/lost+found" and "/lost+found/." point to this inode
  568. STORE_LE(inode->i_size, lost_and_found_blocks * blocksize);
  569. STORE_LE(inode->i_blocks, (lost_and_found_blocks * blocksize) / 512);
  570. n = FETCH_LE32(inode->i_block[0]) + 1;
  571. for (i = 0; i < lost_and_found_blocks; ++i)
  572. STORE_LE(inode->i_block[i], i + n); // use next block
  573. //bb_info_msg("LAST BLOCK USED[%u]", i + n);
  574. PUT(((uint64_t)FETCH_LE32(gd[0].bg_inode_table) * blocksize) + (EXT2_GOOD_OLD_FIRST_INO-1) * inodesize,
  575. buf, inodesize);
  576. // dump directories
  577. memset(buf, 0, blocksize);
  578. dir = (struct ext2_dir *)buf;
  579. // dump 2nd+ blocks of "/lost+found"
  580. STORE_LE(dir->rec_len1, blocksize); // e2fsck 1.41.4 compat (1.41.9 does not need this)
  581. for (i = 1; i < lost_and_found_blocks; ++i)
  582. PUT((uint64_t)(FETCH_LE32(gd[0].bg_inode_table) + inode_table_blocks + 1+i) * blocksize,
  583. buf, blocksize);
  584. // dump 1st block of "/lost+found"
  585. STORE_LE(dir->inode1, EXT2_GOOD_OLD_FIRST_INO);
  586. STORE_LE(dir->rec_len1, 12);
  587. STORE_LE(dir->name_len1, 1);
  588. STORE_LE(dir->file_type1, EXT2_FT_DIR);
  589. dir->name1[0] = '.';
  590. STORE_LE(dir->inode2, EXT2_ROOT_INO);
  591. STORE_LE(dir->rec_len2, blocksize - 12);
  592. STORE_LE(dir->name_len2, 2);
  593. STORE_LE(dir->file_type2, EXT2_FT_DIR);
  594. dir->name2[0] = '.'; dir->name2[1] = '.';
  595. PUT((uint64_t)(FETCH_LE32(gd[0].bg_inode_table) + inode_table_blocks + 1) * blocksize, buf, blocksize);
  596. // dump root dir block
  597. STORE_LE(dir->inode1, EXT2_ROOT_INO);
  598. STORE_LE(dir->rec_len2, 12);
  599. STORE_LE(dir->inode3, EXT2_GOOD_OLD_FIRST_INO);
  600. STORE_LE(dir->rec_len3, blocksize - 12 - 12);
  601. STORE_LE(dir->name_len3, 10);
  602. STORE_LE(dir->file_type3, EXT2_FT_DIR);
  603. strcpy(dir->name3, "lost+found");
  604. PUT((uint64_t)(FETCH_LE32(gd[0].bg_inode_table) + inode_table_blocks + 0) * blocksize, buf, blocksize);
  605. // cleanup
  606. if (ENABLE_FEATURE_CLEAN_UP) {
  607. free(buf);
  608. free(gd);
  609. free(sb);
  610. }
  611. xclose(fd);
  612. return EXIT_SUCCESS;
  613. }