mkfs_ext2.c 25 KB

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