3
0

mkfs_ext2.c 26 KB

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