aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

mkfs.ext4.c (14476B)


      1 /*
      2  * Copyright (c) 2015 Grzegorz Kostka (kostka.grzegorz@gmail.com)
      3  * All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  *
      9  * - Redistributions of source code must retain the above copyright
     10  *   notice, this list of conditions and the following disclaimer.
     11  * - Redistributions in binary form must reproduce the above copyright
     12  *   notice, this list of conditions and the following disclaimer in the
     13  *   documentation and/or other materials provided with the distribution.
     14  * - The name of the author may not be used to endorse or promote products
     15  *   derived from this software without specific prior written permission.
     16  *
     17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 /* Adapted from lwext4 src/ext4_mkfs.c, b2d8fe025940cf4091fc40334aedd64d56034cdc.
     30  * On-disk fields below use byte offsets from the ext4 and JBD2 specifications. */
     31 #include "diskutil.h"
     32 #include "util.h"
     33 
     34 #include <errno.h>
     35 #include <fcntl.h>
     36 #include <stdint.h>
     37 #include <stdlib.h>
     38 #include <sys/stat.h>
     39 #include <time.h>
     40 #include <unistd.h>
     41 
     42 enum {
     43   BLOCK        = MKFS_EXT4_BLOCK_SIZE,
     44   INODE        = 256,
     45   DESC         = 32,
     46   JOURNAL      = 1024,
     47   GROUP_BLOCKS = BLOCK * 8,
     48   ROOT         = 2,
     49   LOG_INO      = 8,
     50   LOST         = 11
     51 };
     52 
     53 struct Volume {
     54   const char *path;
     55   int         fd;
     56   uint32_t    blocks, groups, gdt_blocks, inodes_per_group;
     57   uint32_t    table_blocks, now;
     58 };
     59 
     60 static void
     61 usage(void)
     62 {
     63   eprintf("usage: %s [-L label] [-U uuid] device|image\n", argv0);
     64 }
     65 
     66 static void
     67 le16(unsigned char *p, uint16_t v)
     68 {
     69   p[0] = v;
     70   p[1] = v >> 8;
     71 }
     72 
     73 static void
     74 le32(unsigned char *p, uint32_t v)
     75 {
     76   le16(p, v);
     77   le16(p + 2, v >> 16);
     78 }
     79 
     80 static void
     81 be32(unsigned char *p, uint32_t v)
     82 {
     83   p[0] = v >> 24;
     84   p[1] = v >> 16;
     85   p[2] = v >> 8;
     86   p[3] = v;
     87 }
     88 
     89 static void
     90 volume_uuid(unsigned char uuid[16], const char *s)
     91 {
     92   int     fd, hi, lo;
     93   size_t  i = 0;
     94   ssize_t n;
     95 
     96   if (s) {
     97     if (strlen(s) != 36)
     98       usage();
     99     for (; i < 16; i++) {
    100       if ((i == 4 || i == 6 || i == 8 || i == 10) && *s++ != '-')
    101         usage();
    102       hi = hexval(*s++);
    103       lo = hexval(*s++);
    104       if (hi < 0 || lo < 0)
    105         usage();
    106       uuid[i] = (hi << 4) | lo;
    107     }
    108     if (!memcmp(uuid, (unsigned char[16]){0}, 16))
    109       eprintf("UUID must be nonzero\n");
    110     return;
    111   }
    112   if ((fd = open(ARUU_PATH_DEVURANDOM, O_RDONLY)) < 0)
    113     eprintf("%s:", ARUU_PATH_DEVURANDOM);
    114   while (i < 16) {
    115     n = read(fd, uuid + i, 16 - i);
    116     if (n < 0 && errno == EINTR)
    117       continue;
    118     if (n <= 0) {
    119       if (!n)
    120         errno = EIO;
    121       eprintf("%s:", ARUU_PATH_DEVURANDOM);
    122     }
    123     i += n;
    124   }
    125   if (close(fd) < 0)
    126     eprintf("%s:", ARUU_PATH_DEVURANDOM);
    127   uuid[6] = (uuid[6] & 15) | 0x40;
    128   uuid[8] = (uuid[8] & 63) | 0x80;
    129 }
    130 
    131 /* With sparse_super, groups 0, 1 and powers of 3, 5 and 7 have backups. */
    132 static int
    133 has_super(uint32_t group)
    134 {
    135   const unsigned bases[] = {3, 5, 7};
    136   size_t         i;
    137 
    138   if (group <= 1)
    139     return 1;
    140   for (i = 0; i < LEN(bases); i++) {
    141     uint32_t n = group;
    142 
    143     while (n % bases[i] == 0)
    144       n /= bases[i];
    145     if (n == 1)
    146       return 1;
    147   }
    148   return 0;
    149 }
    150 
    151 static void
    152 open_volume(struct Volume *v)
    153 {
    154   struct stat  st;
    155   struct flock lock  = {.l_type = F_WRLCK, .l_whence = SEEK_SET};
    156   int          flags = O_RDWR | O_NONBLOCK | O_NOCTTY;
    157   uint64_t     bytes;
    158   time_t       now;
    159 
    160 #if defined(__linux__) && !defined(ARUU_FORCE_POSIX)
    161   flags |= O_EXCL; /* kernel claim on a block device */
    162 #endif
    163   if ((v->fd = open(v->path, flags)) < 0 || fstat(v->fd, &st) < 0)
    164     eprintf("%s:", v->path);
    165   if (S_ISREG(st.st_mode)) {
    166     if (fcntl(v->fd, F_SETLK, &lock) < 0 || fstat(v->fd, &st) < 0)
    167       eprintf("%s:", v->path);
    168 #if defined(__linux__) && !defined(ARUU_FORCE_POSIX)
    169     blockdev_check_loop(&st, v->path);
    170 #endif
    171     bytes = st.st_size;
    172 #if defined(__linux__) && !defined(ARUU_FORCE_POSIX)
    173   } else if (S_ISBLK(st.st_mode)) {
    174     struct BlockDev dev = {.fd = v->fd};
    175 
    176     blockdev_sys_size(&dev);
    177     if (!dev.sec_size || BLOCK % dev.sec_size)
    178       eprintf("%s: incompatible sector size\n", v->path);
    179     if (dev.size % dev.sec_size)
    180       eprintf("%s: incomplete device sector\n", v->path);
    181     /* A partition can end between filesystem blocks. Leave its tail alone. */
    182     bytes = dev.size - dev.size % BLOCK;
    183 #endif
    184   } else {
    185     eprintf("%s: unsupported target type\n", v->path);
    186   }
    187   if (bytes % BLOCK || !mkfs_ext4_size_ok(bytes) || (off_t)bytes <= 0
    188       || (uint64_t)(off_t)bytes != bytes)
    189     eprintf("%s: expected a 4 KiB aligned size from 8 MiB to below 16 TiB\n", v->path);
    190 
    191   v->blocks           = bytes / BLOCK;
    192   v->groups           = 1 + (v->blocks - 1) / GROUP_BLOCKS;
    193   v->gdt_blocks       = 1 + (v->groups - 1) / (BLOCK / DESC);
    194   v->inodes_per_group = (v->blocks / 4 + v->groups - 1) / v->groups;
    195   v->table_blocks     = (v->inodes_per_group + BLOCK / INODE - 1) / (BLOCK / INODE);
    196   v->inodes_per_group = v->table_blocks * (BLOCK / INODE);
    197   /* As in lwext4, omit a partial last group too small for its own metadata. */
    198   if (v->groups > 1 && v->blocks % GROUP_BLOCKS
    199       && v->blocks % GROUP_BLOCKS
    200              < 2 + v->table_blocks + (has_super(v->groups - 1) ? 1 + v->gdt_blocks : 0)) {
    201     v->blocks -= v->blocks % GROUP_BLOCKS;
    202     v->groups--;
    203     v->gdt_blocks = 1 + (v->groups - 1) / (BLOCK / DESC);
    204   }
    205   now = time(NULL);
    206   if (now == (time_t)-1 || (uintmax_t)now > UINT32_MAX)
    207     eprintf("filesystem timestamp out of range\n");
    208   v->now = (uint32_t)now;
    209 }
    210 
    211 static void
    212 write_blocks(const struct Volume *v, uint32_t block, const unsigned char *buf, unsigned count)
    213 {
    214   off_t   off  = (off_t)((uint64_t)block * BLOCK);
    215   size_t  done = 0, len = (size_t)count * BLOCK;
    216   ssize_t n;
    217 
    218   if (block >= v->blocks || count > v->blocks - block)
    219     eprintf("%s: block outside volume\n", v->path);
    220   while (done < len) {
    221     n = pwrite(v->fd, buf + done, len - done, off + (off_t)done);
    222     if (n < 0 && errno == EINTR)
    223       continue;
    224     if (n <= 0) {
    225       if (!n)
    226         errno = EIO;
    227       eprintf("%s: writing block %u:", v->path, (unsigned)block);
    228     }
    229     done += n;
    230   }
    231 }
    232 
    233 static void
    234 write_block(const struct Volume *v, uint32_t block, const unsigned char *buf)
    235 {
    236   write_blocks(v, block, buf, 1);
    237 }
    238 
    239 static void
    240 sync_volume(const struct Volume *v)
    241 {
    242   while (fsync(v->fd) < 0)
    243     if (errno != EINTR)
    244       eprintf("%s: fsync:", v->path);
    245 }
    246 
    247 /* A used prefix, a free interval, then padding through the end of the bitmap. */
    248 static void
    249 bitmap(const struct Volume *v, uint32_t block, uint32_t used, uint32_t count)
    250 {
    251   unsigned char map[BLOCK];
    252 
    253   memset(map, 0xff, sizeof map);
    254   for (; used < count; used++)
    255     map[used / 8] &= ~(1U << (used % 8));
    256   write_block(v, block, map);
    257 }
    258 
    259 static void
    260 inode(
    261     unsigned char *p, uint32_t now, unsigned mode, unsigned links, uint32_t bytes, uint32_t blocks
    262 )
    263 {
    264   le16(p, mode);
    265   le32(p + 4, bytes);
    266   le32(p + 8, now); /* atime, ctime, mtime */
    267   le32(p + 12, now);
    268   le32(p + 16, now);
    269   le16(p + 26, links);
    270   le32(p + 28, blocks * (BLOCK / 512));
    271   le16(p + 128, 32); /* i_extra_isize */
    272   le32(p + 132, now >> 31);
    273   le32(p + 136, now >> 31);
    274   le32(p + 140, now >> 31);
    275   le32(p + 144, now); /* crtime */
    276   le32(p + 148, now >> 31);
    277 }
    278 
    279 static void
    280 dirent(unsigned char *p, uint32_t ino, unsigned len, const char *name)
    281 {
    282   le32(p, ino);
    283   le16(p + 4, len);
    284   p[6] = strlen(name);
    285   p[7] = 2; /* EXT4_FT_DIR */
    286   memcpy(p + 8, name, p[6]);
    287 }
    288 
    289 /* The first table block holds all reserved inodes and lost+found. The two
    290  * directory blocks, journal indirect block and journal data follow the table. */
    291 static void
    292 write_files(const struct Volume *v, uint32_t root, unsigned char *sb)
    293 {
    294   unsigned char  table[BLOCK] = {0}, buf[BLOCK] = {0};
    295   unsigned char *log   = table + (LOG_INO - 1) * INODE;
    296   uint32_t       first = root + 3, i;
    297 
    298   inode(table + (ROOT - 1) * INODE, v->now, 0040755, 3, BLOCK, 1);
    299   le32(table + (ROOT - 1) * INODE + 40, root);
    300   inode(table + (LOST - 1) * INODE, v->now, 0040700, 2, BLOCK, 1);
    301   le32(table + (LOST - 1) * INODE + 40, root + 1);
    302   inode(log, v->now, 0100600, 1, JOURNAL * BLOCK, JOURNAL + 1);
    303   for (i = 0; i < 12; i++)
    304     le32(log + 40 + 4 * i, first + i);
    305   le32(log + 40 + 12 * 4, root + 2);
    306   memcpy(sb + 268, log + 40, 60); /* journal i_block backup */
    307   le32(sb + 332, JOURNAL * BLOCK);
    308   write_block(v, root - v->table_blocks, table);
    309 
    310   dirent(buf, ROOT, 12, ".");
    311   dirent(buf + 12, ROOT, 12, "..");
    312   dirent(buf + 24, LOST, BLOCK - 24, "lost+found");
    313   write_block(v, root, buf);
    314   memset(buf, 0, BLOCK);
    315   dirent(buf, LOST, 12, ".");
    316   dirent(buf + 12, ROOT, BLOCK - 12, "..");
    317   write_block(v, root + 1, buf);
    318 
    319   memset(buf, 0, BLOCK);
    320   for (i = 12; i < JOURNAL; i++)
    321     le32(buf + (i - 12) * 4, first + i);
    322   write_block(v, root + 2, buf);
    323 
    324   /* lwext4 create_journal_inode: JBD2 superblock v2, empty log. */
    325   memset(buf, 0, BLOCK);
    326   be32(buf, 0xc03b3998);
    327   be32(buf + 4, 4);
    328   be32(buf + 12, BLOCK);
    329   be32(buf + 16, JOURNAL);
    330   be32(buf + 20, 1); /* first log block */
    331   be32(buf + 24, 1); /* next sequence */
    332   be32(buf + 40, 1); /* revoke */
    333   memcpy(buf + 48, sb + 104, 16);
    334   be32(buf + 64, 1); /* internal journal, one user */
    335   write_block(v, first, buf);
    336   memset(buf, 0, BLOCK);
    337   for (i = 1; i < JOURNAL; i++)
    338     write_block(v, first + i, buf);
    339 }
    340 
    341 static void
    342 format(const struct Volume *v, const char *label, const unsigned char uuid[16])
    343 {
    344   static const unsigned char zero[64 * 1024];
    345   unsigned char              sb[1024] = {0}, first[BLOCK], buf[BLOCK] = {0};
    346   unsigned char             *gdt = ecalloc(v->gdt_blocks, BLOCK);
    347   uint32_t                   g, i, free_blocks = 0;
    348   size_t                     done = 0;
    349   ssize_t                    n;
    350 
    351   /* Read the whole block for devices with 4 KiB logical sectors. Only the
    352    * superblock at offset 1024 is invalidated and later published. */
    353   while (done < sizeof first) {
    354     n = pread(v->fd, first + done, sizeof first - done, done);
    355     if (n < 0 && errno == EINTR)
    356       continue;
    357     if (n < 0)
    358       eprintf("%s: reading boot area:", v->path);
    359     if (!n)
    360       eprintf("%s: short read of boot area\n", v->path);
    361     done += n;
    362   }
    363   memset(first + 1024, 0, sizeof sb);
    364   write_block(v, 0, first);
    365   sync_volume(v);
    366   for (g = 0; g < v->groups; g++) {
    367     uint32_t       start        = g * GROUP_BLOCKS;
    368     uint32_t       count        = MIN(v->blocks - start, GROUP_BLOCKS);
    369     uint32_t       bitmap_block = start + (has_super(g) ? 1 + v->gdt_blocks : 0);
    370     uint32_t       table        = bitmap_block + 2;
    371     uint32_t       used         = table - start + v->table_blocks + (g == 0 ? JOURNAL + 3 : 0);
    372     uint32_t       inodes       = g == 0 ? LOST : 0;
    373     unsigned char *d            = gdt + g * DESC;
    374 
    375     le32(d, bitmap_block);
    376     le32(d + 4, bitmap_block + 1);
    377     le32(d + 8, table);
    378     le16(d + 12, count - used);
    379     le16(d + 14, v->inodes_per_group - inodes);
    380     le16(d + 16, g == 0 ? 2 : 0);
    381     free_blocks += count - used;
    382     bitmap(v, bitmap_block, used, count);
    383     bitmap(v, bitmap_block + 1, inodes, v->inodes_per_group);
    384     for (i = (g == 0); i < v->table_blocks;) {
    385       unsigned chunk = MIN(v->table_blocks - i, sizeof zero / BLOCK);
    386       write_blocks(v, table + i, zero, chunk);
    387       i += chunk;
    388     }
    389   }
    390 
    391   /* lwext4 fill_sb: dynamic revision, Linux inode layout, remount-ro on error. */
    392   le32(sb, v->inodes_per_group * v->groups);
    393   le32(sb + 4, v->blocks);
    394   le32(sb + 12, free_blocks);
    395   le32(sb + 16, v->inodes_per_group * v->groups - LOST);
    396   le32(sb + 24, 2); /* block and cluster size, log2(bytes / 1024) */
    397   le32(sb + 28, 2);
    398   le32(sb + 32, GROUP_BLOCKS);
    399   le32(sb + 36, GROUP_BLOCKS);
    400   le32(sb + 40, v->inodes_per_group);
    401   le32(sb + 48, v->now); /* last write */
    402   le16(sb + 54, 0xffff); /* no mount-count limit */
    403   le16(sb + 56, 0xef53);
    404   le16(sb + 58, 1); /* clean */
    405   le16(sb + 60, 2);
    406   le32(sb + 64, v->now); /* last check */
    407   le32(sb + 76, 1);
    408   le32(sb + 84, LOST); /* first non-reserved inode */
    409   le16(sb + 88, INODE);
    410   le32(sb + 92, 4);     /* has_journal */
    411   le32(sb + 96, 2);     /* filetype */
    412   le32(sb + 100, 0x43); /* sparse_super | large_file | extra_isize */
    413   memcpy(sb + 104, uuid, 16);
    414   memcpy(sb + 120, label, strlen(label));
    415   le32(sb + 224, LOG_INO);
    416   sb[253] = 1;            /* journal backup type */
    417   le32(sb + 264, v->now); /* creation time */
    418   le16(sb + 348, 32);     /* required and desired extra inode fields */
    419   le16(sb + 350, 32);
    420   write_files(v, 3 + v->gdt_blocks + v->table_blocks, sb);
    421 
    422   for (g = 0; g < v->groups; g++) {
    423     if (!has_super(g))
    424       continue;
    425     write_blocks(v, g * GROUP_BLOCKS + 1, gdt, v->gdt_blocks);
    426     if (g) {
    427       le16(sb + 90, g);
    428       memcpy(buf, sb, sizeof sb);
    429       write_block(v, g * GROUP_BLOCKS, buf);
    430     }
    431   }
    432   sync_volume(v);
    433   le16(sb + 90, 0);
    434   memcpy(first + 1024, sb, sizeof sb);
    435   write_block(v, 0, first);
    436   sync_volume(v);
    437   free(gdt);
    438 }
    439 
    440 // ?man mkfs.ext4: create a MICE journaled filesystem for the Linux ext4 driver
    441 // ?man arguments: [-L label] [-U uuid] device|image
    442 // ?man Formats an existing image or Linux block device, 8 MiB to below 16 TiB with 4 KiB blocks.
    443 int
    444 main(int argc, char **argv)
    445 {
    446   struct Volume v     = {0};
    447   const char   *label = "", *id = NULL;
    448   unsigned char uuid[16];
    449 
    450   ARGBEGIN
    451   {
    452     case 'L':
    453       label = EARGF(usage());
    454       break;
    455     case 'U':
    456       id = EARGF(usage());
    457       break;
    458     default:
    459       usage();
    460   }
    461   ARGEND
    462   if (argc != 1)
    463     usage();
    464   if (strlen(label) > 16)
    465     eprintf("volume label exceeds 16 bytes\n");
    466   volume_uuid(uuid, id);
    467   v.path = argv[0];
    468   open_volume(&v);
    469   format(&v, label, uuid);
    470   if (close(v.fd) < 0)
    471     eprintf("%s:", v.path);
    472   return 0;
    473 }