mkfs_ext2.c 25 KB

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