LCOV - code coverage report
Current view: top level - mkfs.ubifs - mkfs.ubifs.c (source / functions) Hit Total Coverage
Test: a simple test Lines: 935 1305 71.6 %
Date: 2024-06-05 20:10:43 Functions: 45 46 97.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :  * Copyright (C) 2008 Nokia Corporation.
       3             :  * Copyright (C) 2008 University of Szeged, Hungary
       4             :  *
       5             :  * This program is free software; you can redistribute it and/or modify it
       6             :  * under the terms of the GNU General Public License version 2 as published by
       7             :  * the Free Software Foundation.
       8             :  *
       9             :  * This program is distributed in the hope that it will be useful, but WITHOUT
      10             :  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
      11             :  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
      12             :  * more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License along with
      15             :  * this program; if not, write to the Free Software Foundation, Inc., 51
      16             :  * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
      17             :  *
      18             :  * Authors: Adrian Hunter
      19             :  *          Artem Bityutskiy
      20             :  *          Zoltan Sogor
      21             :  */
      22             : 
      23             : #define _XOPEN_SOURCE 500 /* For realpath() */
      24             : 
      25             : #include <stdio.h>
      26             : #include <stdlib.h>
      27             : #include <libgen.h>
      28             : #include <getopt.h>
      29             : #include <dirent.h>
      30             : #include <crc32.h>
      31             : #include <uuid.h>
      32             : #include <linux/fs.h>
      33             : #include <sys/types.h>
      34             : #include <sys/stat.h>
      35             : #include <sys/ioctl.h>
      36             : #ifdef WITH_XATTR
      37             : #include <sys/xattr.h>
      38             : #endif
      39             : 
      40             : #ifdef WITH_SELINUX
      41             : #include <selinux/selinux.h>
      42             : #include <selinux/label.h>
      43             : #endif
      44             : 
      45             : #ifdef WITH_ZSTD
      46             : #include <zstd.h>
      47             : #endif
      48             : 
      49             : #include "bitops.h"
      50             : #include "crypto.h"
      51             : #include "fscrypt.h"
      52             : #include "ubifs.h"
      53             : #include "defs.h"
      54             : #include "debug.h"
      55             : #include "key.h"
      56             : #include "compr.h"
      57             : #include "misc.h"
      58             : #include "devtable.h"
      59             : 
      60             : /* Size (prime number) of hash table for link counting */
      61             : #define HASH_TABLE_SIZE 10099
      62             : 
      63             : /* The node buffer must allow for worst case compression */
      64             : #define NODE_BUFFER_SIZE (UBIFS_DATA_NODE_SZ + \
      65             :                           UBIFS_BLOCK_SIZE * WORST_COMPR_FACTOR)
      66             : 
      67             : /* Default time granularity in nanoseconds */
      68             : #define DEFAULT_TIME_GRAN 1000000000
      69             : 
      70             : 
      71             : #ifdef WITH_SELINUX
      72             : #define XATTR_NAME_SELINUX "security.selinux"
      73             : static struct selabel_handle *sehnd;
      74             : #endif
      75             : 
      76             : /**
      77             :  * struct idx_entry - index entry.
      78             :  * @next: next index entry (NULL at end of list)
      79             :  * @prev: previous index entry (NULL at beginning of list)
      80             :  * @key: key
      81             :  * @name: directory entry name used for sorting colliding keys by name
      82             :  * @lnum: LEB number
      83             :  * @offs: offset
      84             :  * @len: length
      85             :  * @hash: hash of the node
      86             :  *
      87             :  * The index is recorded as a linked list which is sorted and used to create
      88             :  * the bottom level of the on-flash index tree. The remaining levels of the
      89             :  * index tree are each built from the level below.
      90             :  */
      91             : struct idx_entry {
      92             :         struct idx_entry *next;
      93             :         struct idx_entry *prev;
      94             :         union ubifs_key key;
      95             :         char *name;
      96             :         int name_len;
      97             :         int lnum;
      98             :         int offs;
      99             :         int len;
     100             :         uint8_t hash[UBIFS_MAX_HASH_LEN];
     101             : };
     102             : 
     103             : /**
     104             :  * struct inum_mapping - inode number mapping for link counting.
     105             :  * @next: next inum_mapping (NULL at end of list)
     106             :  * @prev: previous inum_mapping (NULL at beginning of list)
     107             :  * @dev: source device on which the source inode number resides
     108             :  * @inum: source inode number of the file
     109             :  * @use_inum: target inode number of the file
     110             :  * @use_nlink: number of links
     111             :  * @path_name: a path name of the file
     112             :  * @st: struct stat object containing inode attributes which have to be used
     113             :  *      when the inode is being created (actually only UID, GID, access
     114             :  *      mode, major and minor device numbers)
     115             :  *
     116             :  * If a file has more than one hard link, then the number of hard links that
     117             :  * exist in the source directory hierarchy must be counted to exclude the
     118             :  * possibility that the file is linked from outside the source directory
     119             :  * hierarchy.
     120             :  *
     121             :  * The inum_mappings are stored in a hash_table of linked lists.
     122             :  */
     123             : struct inum_mapping {
     124             :         struct inum_mapping *next;
     125             :         struct inum_mapping *prev;
     126             :         dev_t dev;
     127             :         ino_t inum;
     128             :         ino_t use_inum;
     129             :         unsigned int use_nlink;
     130             :         char *path_name;
     131             :         struct stat st;
     132             : };
     133             : 
     134             : /*
     135             :  * Because we copy functions from the kernel, we use a subset of the UBIFS
     136             :  * file-system description object struct ubifs_info.
     137             :  */
     138             : struct ubifs_info info_;
     139             : static struct ubifs_info *c = &info_;
     140             : 
     141             : int verbose;
     142             : int yes;
     143             : 
     144             : static char *root;
     145             : static int root_len;
     146             : static struct fscrypt_context *root_fctx;
     147             : static struct stat root_st;
     148             : static int squash_owner;
     149             : static int do_create_inum_attr;
     150             : static char *context;
     151             : static int context_len;
     152             : static struct stat context_st;
     153             : 
     154             : /* The 'head' (position) which nodes are written */
     155             : static int head_lnum;
     156             : static int head_offs;
     157             : static int head_flags;
     158             : 
     159             : /* The index list */
     160             : static struct idx_entry *idx_list_first;
     161             : static struct idx_entry *idx_list_last;
     162             : static size_t idx_cnt;
     163             : 
     164             : /* Global buffers */
     165             : static void *leb_buf;
     166             : static void *node_buf;
     167             : static void *block_buf;
     168             : 
     169             : /* Hash table for inode link counting */
     170             : static struct inum_mapping **hash_table;
     171             : 
     172             : /* Inode creation sequence number */
     173             : static unsigned long long creat_sqnum;
     174             : 
     175             : static const char *optstring = "d:r:m:o:D:yh?vVe:c:g:f:Fp:k:x:X:j:R:l:j:UQqaK:b:P:C:";
     176             : 
     177             : enum {
     178             :         HASH_ALGO_OPTION = CHAR_MAX + 1,
     179             :         AUTH_KEY_OPTION,
     180             :         AUTH_CERT_OPTION,
     181             : };
     182             : 
     183             : static const struct option longopts[] = {
     184             :         {"root",               1, NULL, 'r'},
     185             :         {"min-io-size",        1, NULL, 'm'},
     186             :         {"leb-size",           1, NULL, 'e'},
     187             :         {"max-leb-cnt",        1, NULL, 'c'},
     188             :         {"output",             1, NULL, 'o'},
     189             :         {"devtable",           1, NULL, 'D'},
     190             :         {"yes",                0, NULL, 'y'},
     191             :         {"help",               0, NULL, 'h'},
     192             :         {"verbose",            0, NULL, 'v'},
     193             :         {"version",            0, NULL, 'V'},
     194             :         {"debug-level",        1, NULL, 'g'},
     195             :         {"jrn-size",           1, NULL, 'j'},
     196             :         {"reserved",           1, NULL, 'R'},
     197             :         {"compr",              1, NULL, 'x'},
     198             :         {"favor-percent",      1, NULL, 'X'},
     199             :         {"fanout",             1, NULL, 'f'},
     200             :         {"space-fixup",        0, NULL, 'F'},
     201             :         {"keyhash",            1, NULL, 'k'},
     202             :         {"log-lebs",           1, NULL, 'l'},
     203             :         {"orph-lebs",          1, NULL, 'p'},
     204             :         {"squash-uids" ,       0, NULL, 'U'},
     205             :         {"set-inode-attr",     0, NULL, 'a'},
     206             :         {"selinux",            1, NULL, 's'},
     207             :         {"key",                1, NULL, 'K'},
     208             :         {"key-descriptor",     1, NULL, 'b'},
     209             :         {"padding",            1, NULL, 'P'},
     210             :         {"cipher",             1, NULL, 'C'},
     211             :         {"hash-algo",          1, NULL, HASH_ALGO_OPTION},
     212             :         {"auth-key",           1, NULL, AUTH_KEY_OPTION},
     213             :         {"auth-cert",          1, NULL, AUTH_CERT_OPTION},
     214             :         {NULL, 0, NULL, 0}
     215             : };
     216             : 
     217             : static const char *helptext =
     218             : "Usage: mkfs.ubifs [OPTIONS] target\n"
     219             : "Make a UBIFS file system image from an existing directory tree\n\n"
     220             : "Examples:\n"
     221             : "Build file system from directory /opt/img, writing the result in the ubifs.img file\n"
     222             : "\tmkfs.ubifs -m 512 -e 128KiB -c 100 -r /opt/img ubifs.img\n"
     223             : "The same, but writing directly to an UBI volume\n"
     224             : "\tmkfs.ubifs -r /opt/img /dev/ubi0_0\n"
     225             : "Creating an empty UBIFS filesystem on an UBI volume\n"
     226             : "\tmkfs.ubifs /dev/ubi0_0\n\n"
     227             : "Options:\n"
     228             : "-r, -d, --root=DIR       build file system from directory DIR\n"
     229             : "-m, --min-io-size=SIZE   minimum I/O unit size\n"
     230             : "-e, --leb-size=SIZE      logical erase block size\n"
     231             : "-c, --max-leb-cnt=COUNT  maximum logical erase block count\n"
     232             : "-o, --output=FILE        output to FILE\n"
     233             : "-j, --jrn-size=SIZE      journal size\n"
     234             : "-R, --reserved=SIZE      how much space should be reserved for the super-user\n"
     235             : "-x, --compr=TYPE         compression type - \"lzo\", \"favor_lzo\", \"zlib\"\n"
     236             : "                         \"zstd\" or \"none\" (default: \"lzo\")\n"
     237             : "-X, --favor-percent      may only be used with favor LZO compression and defines\n"
     238             : "                         how many percent better zlib should compress to make\n"
     239             : "                         mkfs.ubifs use zlib instead of LZO (default 20%)\n"
     240             : "-f, --fanout=NUM         fanout NUM (default: 8)\n"
     241             : "-F, --space-fixup        file-system free space has to be fixed up on first mount\n"
     242             : "                         (requires kernel version 3.0 or greater)\n"
     243             : "-k, --keyhash=TYPE       key hash type - \"r5\" or \"test\" (default: \"r5\")\n"
     244             : "-p, --orph-lebs=COUNT    count of erase blocks for orphans (default: 1)\n"
     245             : "-D, --devtable=FILE      use device table FILE\n"
     246             : "-U, --squash-uids        squash owners making all files owned by root\n"
     247             : "-l, --log-lebs=COUNT     count of erase blocks for the log (used only for\n"
     248             : "                         debugging)\n"
     249             : "-y, --yes                assume the answer is \"yes\" for all questions\n"
     250             : "-v, --verbose            verbose operation\n"
     251             : "-V, --version            display version information\n"
     252             : "-g, --debug=LEVEL        display printing information (0 - none, 1 - error message, \n"
     253             : "                         2 - warning message[default], 3 - notice message, 4 - debug message)\n"
     254             : "-a, --set-inum-attr      create user.image-inode-number extended attribute on files\n"
     255             : "                         added to the image. The attribute will contain the inode\n"
     256             : "                         number the file has in the generated image.\n"
     257             : "-s, --selinux=FILE       Selinux context file\n"
     258             : "-K, --key=FILE           load an encryption key from a specified file.\n"
     259             : "-b, --key-descriptor=HEX specify the key descriptor as a hex string.\n"
     260             : "-P, --padding=NUM        specify padding policy for encrypting filenames\n"
     261             : "                         (default = 4).\n"
     262             : "-C, --cipher=NAME        Specify cipher to use for file level encryption\n"
     263             : "                         (default is \"AES-256-XTS\").\n"
     264             : "    --hash-algo=NAME     hash algorithm to use for signed images\n"
     265             : "                         (Valid options include sha1, sha256, sha512)\n"
     266             : "    --auth-key=FILE      filename or PKCS #11 uri containing the authentication key\n"
     267             : "                         for signing\n"
     268             : "    --auth-cert=FILE     Authentication certificate filename for signing. Unused\n"
     269             : "                         when certificate is provided via PKCS #11\n"
     270             : "-h, --help               display this help text\n\n"
     271             : "Note, SIZE is specified in bytes, but it may also be specified in Kilobytes,\n"
     272             : "Megabytes, and Gigabytes if a KiB, MiB, or GiB suffix is used.\n\n"
     273             : "If you specify \"lzo\" or \"zlib\" compressors, mkfs.ubifs will use this compressor\n"
     274             : "for all data. The \"none\" disables any data compression. The \"favor_lzo\" is not\n"
     275             : "really a separate compressor. It is just a method of combining \"lzo\" and \"zlib\"\n"
     276             : "compressors. Namely, mkfs.ubifs tries to compress data with both \"lzo\" and \"zlib\"\n"
     277             : "compressors, then it compares which compressor is better. If \"zlib\" compresses 20\n"
     278             : "or more percent better than \"lzo\", mkfs.ubifs chooses \"zlib\", otherwise it chooses\n"
     279             : "\"lzo\". The \"--favor-percent\" may specify arbitrary threshold instead of the\n"
     280             : "default 20%.\n\n"
     281             : "The -F parameter is used to set the \"fix up free space\" flag in the superblock,\n"
     282             : "which forces UBIFS to \"fixup\" all the free space which it is going to use. This\n"
     283             : "option is useful to work-around the problem of double free space programming: if the\n"
     284             : "flasher program which flashes the UBI image is unable to skip NAND pages containing\n"
     285             : "only 0xFF bytes, the effect is that some NAND pages are written to twice - first time\n"
     286             : "when flashing the image and the second time when UBIFS is mounted and writes useful\n"
     287             : "data there. A proper UBI-aware flasher should skip such NAND pages, though. Note, this\n"
     288             : "flag may make the first mount very slow, because the \"free space fixup\" procedure\n"
     289             : "takes time. This feature is supported by the Linux kernel starting from version 3.0.\n"
     290             : "\n"
     291             : "mkfs.ubifs supports building signed images. For this the \"--hash-algo\",\n"
     292             : "\"--auth-key\" and \"--auth-cert\" options have to be specified.\n";
     293             : 
     294             : /**
     295             :  * make_path - make a path name from a directory and a name.
     296             :  * @dir: directory path name
     297             :  * @name: name
     298             :  */
     299       92160 : static char *make_path(const char *dir, const char *name)
     300             : {
     301             :         char *s;
     302             : 
     303       92160 :         xasprintf(&s, "%s%s%s",
     304       92160 :                   dir, dir[strlen(dir) - 1] == '/' ? "" : "/", name);
     305             : 
     306       92160 :         return s;
     307             : }
     308             : 
     309             : /**
     310             :  * is_contained - determine if a file is beneath a directory.
     311             :  * @file: file path name
     312             :  * @dir: directory path name
     313             :  *
     314             :  * This function returns %1 if @file is accessible from the @dir directory and
     315             :  * %0 otherwise. In case of error, returns %-1.
     316             :  */
     317         640 : static int is_contained(const char *file, const char *dir)
     318             : {
     319         640 :         char *real_file = NULL;
     320         640 :         char *real_dir = NULL;
     321             :         char *file_base, *copy;
     322         640 :         int ret = -1;
     323             : 
     324             :         /* Make a copy of the file path because 'dirname()' can modify it */
     325         640 :         copy = strdup(file);
     326         640 :         if (!copy)
     327             :                 return -1;
     328         640 :         file_base = dirname(copy);
     329             : 
     330             :         /* Turn the paths into the canonical form */
     331         640 :         real_file = xmalloc(PATH_MAX);
     332         640 :         real_dir = xmalloc(PATH_MAX);
     333             : 
     334         640 :         if (!realpath(file_base, real_file)) {
     335           0 :                 perror("Could not canonicalize file path");
     336           0 :                 goto out_free;
     337             :         }
     338         640 :         if (!realpath(dir, real_dir)) {
     339           0 :                 perror("Could not canonicalize directory");
     340           0 :                 goto out_free;
     341             :         }
     342             : 
     343         640 :         ret = !!strstr(real_file, real_dir);
     344             : 
     345         640 : out_free:
     346         640 :         free(copy);
     347         640 :         free(real_file);
     348         640 :         free(real_dir);
     349         640 :         return ret;
     350             : }
     351             : 
     352             : /**
     353             :  * calc_min_log_lebs - calculate the minimum number of log LEBs needed.
     354             :  * @max_bud_bytes: journal size (buds only)
     355             :  */
     356        1280 : static int calc_min_log_lebs(unsigned long long max_bud_bytes)
     357             : {
     358             :         int buds, log_lebs;
     359             :         unsigned long long log_size;
     360             : 
     361        1280 :         buds = (max_bud_bytes + c->leb_size - 1) / c->leb_size;
     362        1280 :         log_size = ALIGN(UBIFS_REF_NODE_SZ, c->min_io_size);
     363        1280 :         log_size *= buds;
     364        1280 :         log_size += ALIGN(UBIFS_CS_NODE_SZ +
     365             :                           UBIFS_REF_NODE_SZ * (c->jhead_cnt + 2),
     366             :                           c->min_io_size);
     367        1280 :         log_lebs = (log_size + c->leb_size - 1) / c->leb_size;
     368        1280 :         log_lebs += 1;
     369        1280 :         return log_lebs;
     370             : }
     371             : 
     372             : /**
     373             :  * add_space_overhead - add UBIFS overhead.
     374             :  * @size: flash space which should be visible to the user
     375             :  *
     376             :  * UBIFS has overhead, and if we need to reserve @size bytes for the user data,
     377             :  * we have to reserve more flash space, to compensate the overhead. This
     378             :  * function calculates and returns the amount of physical flash space which
     379             :  * should be reserved to provide @size bytes for the user.
     380             :  */
     381             : static long long add_space_overhead(long long size)
     382             : {
     383             :         int divisor, factor, f, max_idx_node_sz;
     384             : 
     385             :         /*
     386             :          * Do the opposite to what the 'ubifs_reported_space()' kernel UBIFS
     387             :          * function does.
     388             :          */
     389        1280 :         max_idx_node_sz =  ubifs_idx_node_sz(c, c->fanout);
     390         640 :         f = c->fanout > 3 ? c->fanout >> 1 : 2;
     391         640 :         divisor = UBIFS_BLOCK_SIZE;
     392         640 :         factor = UBIFS_MAX_DATA_NODE_SZ;
     393         640 :         factor += (max_idx_node_sz * 3) / (f - 1);
     394         640 :         size *= factor;
     395         640 :         return size / divisor;
     396             : }
     397             : 
     398         640 : static int validate_options(void)
     399             : {
     400             :         int tmp;
     401             : 
     402         640 :         if (!c->dev_name)
     403           0 :                 return errmsg("no output file or UBI volume specified");
     404         640 :         if (root) {
     405         640 :                 tmp = is_contained(c->dev_name, root);
     406         640 :                 if (tmp < 0)
     407           0 :                         return errmsg("failed to perform output file root check");
     408         640 :                 else if (tmp)
     409           0 :                         return errmsg("output file cannot be in the UBIFS root "
     410             :                                        "directory");
     411             :         }
     412        1280 :         if (!is_power_of_2(c->min_io_size))
     413           0 :                 return errmsg("min. I/O unit size should be power of 2");
     414         640 :         if (c->leb_size < c->min_io_size)
     415           0 :                 return errmsg("min. I/O unit cannot be larger than LEB size");
     416         640 :         if (c->leb_size < UBIFS_MIN_LEB_SZ)
     417           0 :                 return errmsg("too small LEB size %d, minimum is %d",
     418             :                                c->leb_size, UBIFS_MIN_LEB_SZ);
     419         640 :         if (c->leb_size % c->min_io_size)
     420           0 :                 return errmsg("LEB should be multiple of min. I/O units");
     421         640 :         if (c->leb_size % 8)
     422           0 :                 return errmsg("LEB size has to be multiple of 8");
     423         640 :         if (c->leb_size > UBIFS_MAX_LEB_SZ)
     424           0 :                 return errmsg("too large LEB size %d, maximum is %d",
     425             :                                 c->leb_size, UBIFS_MAX_LEB_SZ);
     426         640 :         if (c->max_leb_cnt < UBIFS_MIN_LEB_CNT)
     427           0 :                 return errmsg("too low max. count of LEBs, minimum is %d",
     428             :                                UBIFS_MIN_LEB_CNT);
     429         640 :         if (c->fanout < UBIFS_MIN_FANOUT)
     430           0 :                 return errmsg("too low fanout, minimum is %d",
     431             :                                UBIFS_MIN_FANOUT);
     432         640 :         tmp = c->leb_size - UBIFS_IDX_NODE_SZ;
     433         640 :         tmp /= UBIFS_BRANCH_SZ + UBIFS_MAX_KEY_LEN;
     434         640 :         if (c->fanout > tmp)
     435           0 :                 return errmsg("too high fanout, maximum is %d", tmp);
     436         640 :         if (c->log_lebs < UBIFS_MIN_LOG_LEBS)
     437           0 :                 return errmsg("too few log LEBs, minimum is %d",
     438             :                                UBIFS_MIN_LOG_LEBS);
     439         640 :         if (c->log_lebs >= c->max_leb_cnt - UBIFS_MIN_LEB_CNT)
     440           0 :                 return errmsg("too many log LEBs, maximum is %d",
     441             :                                c->max_leb_cnt - UBIFS_MIN_LEB_CNT);
     442         640 :         if (c->orph_lebs < UBIFS_MIN_ORPH_LEBS)
     443           0 :                 return errmsg("too few orphan LEBs, minimum is %d",
     444             :                                UBIFS_MIN_ORPH_LEBS);
     445         640 :         if (c->orph_lebs >= c->max_leb_cnt - UBIFS_MIN_LEB_CNT)
     446           0 :                 return errmsg("too many orphan LEBs, maximum is %d",
     447             :                                c->max_leb_cnt - UBIFS_MIN_LEB_CNT);
     448         640 :         tmp = UBIFS_SB_LEBS + UBIFS_MST_LEBS + c->log_lebs + c->lpt_lebs;
     449         640 :         tmp += c->orph_lebs + 4;
     450         640 :         if (tmp > c->max_leb_cnt)
     451           0 :                 return errmsg("too low max. count of LEBs, expected at "
     452             :                                "least %d", tmp);
     453         640 :         tmp = calc_min_log_lebs(c->max_bud_bytes);
     454         640 :         if (c->log_lebs < calc_min_log_lebs(c->max_bud_bytes))
     455           0 :                 return errmsg("too few log LEBs, expected at least %d", tmp);
     456         640 :         if (c->rp_size >= ((long long)c->leb_size * c->max_leb_cnt) / 2)
     457           0 :                 return errmsg("too much reserved space %lld", c->rp_size);
     458             :         return 0;
     459             : }
     460             : 
     461             : /**
     462             :  * get_multiplier - convert size specifier to an integer multiplier.
     463             :  * @str: the size specifier string
     464             :  *
     465             :  * This function parses the @str size specifier, which may be one of
     466             :  * 'KiB', 'MiB', or 'GiB' into an integer multiplier. Returns positive
     467             :  * size multiplier in case of success and %-1 in case of failure.
     468             :  */
     469           0 : static int get_multiplier(const char *str)
     470             : {
     471           0 :         if (!str)
     472             :                 return 1;
     473             : 
     474             :         /* Remove spaces before the specifier */
     475           0 :         while (*str == ' ' || *str == '\t')
     476           0 :                 str += 1;
     477             : 
     478           0 :         if (!strcmp(str, "KiB"))
     479             :                 return 1024;
     480           0 :         if (!strcmp(str, "MiB"))
     481             :                 return 1024 * 1024;
     482           0 :         if (!strcmp(str, "GiB"))
     483             :                 return 1024 * 1024 * 1024;
     484             : 
     485           0 :         return -1;
     486             : }
     487             : 
     488             : /**
     489             :  * get_bytes - convert a string containing amount of bytes into an
     490             :  *             integer.
     491             :  * @str: string to convert
     492             :  *
     493             :  * This function parses @str which may have one of 'KiB', 'MiB', or 'GiB' size
     494             :  * specifiers. Returns positive amount of bytes in case of success and %-1 in
     495             :  * case of failure.
     496             :  */
     497        1920 : static long long get_bytes(const char *str)
     498             : {
     499             :         char *endp;
     500        1920 :         long long bytes = strtoull(str, &endp, 0);
     501             : 
     502        1920 :         if (endp == str || bytes < 0)
     503           0 :                 return errmsg("incorrect amount of bytes: \"%s\"", str);
     504             : 
     505        1920 :         if (*endp != '\0') {
     506           0 :                 int mult = get_multiplier(endp);
     507             : 
     508           0 :                 if (mult == -1)
     509           0 :                         return errmsg("bad size specifier: \"%s\" - "
     510             :                                        "should be 'KiB', 'MiB' or 'GiB'", endp);
     511           0 :                 bytes *= mult;
     512             :         }
     513             : 
     514             :         return bytes;
     515             : }
     516             : 
     517             : static void select_default_compr(void)
     518             : {
     519         640 :         if (c->encrypted) {
     520         320 :                 c->default_compr = UBIFS_COMPR_NONE;
     521             :                 return;
     522             :         }
     523             : 
     524             : #ifdef WITH_LZO
     525         320 :         c->default_compr = UBIFS_COMPR_LZO;
     526             : #elif defined(WITH_ZLIB)
     527             :         c->default_compr = UBIFS_COMPR_ZLIB;
     528             : #else
     529             :         c->default_compr = UBIFS_COMPR_NONE;
     530             : #endif
     531             : }
     532             : 
     533         640 : static int get_options(int argc, char**argv)
     534             : {
     535         640 :         int opt, i, fscrypt_flags = FS_POLICY_FLAGS_PAD_4;
     536         640 :         const char *key_file = NULL, *key_desc = NULL;
     537         640 :         const char *tbl_file = NULL;
     538             :         struct stat st;
     539             :         char *endp;
     540             : #ifdef WITH_CRYPTO
     541         640 :         const char *cipher_name = NULL;
     542             : #endif
     543             : 
     544         640 :         c->fanout = 8;
     545         640 :         c->orph_lebs = 1;
     546         640 :         c->key_hash = key_r5_hash;
     547         640 :         c->key_len = UBIFS_SK_LEN;
     548         640 :         c->favor_percent = 20;
     549         640 :         c->lsave_cnt = 256;
     550         640 :         c->leb_size = -1;
     551         640 :         c->min_io_size = -1;
     552         640 :         c->max_leb_cnt = -1;
     553         640 :         c->max_bud_bytes = -1;
     554         640 :         c->log_lebs = -1;
     555         640 :         c->double_hash = 0;
     556         640 :         c->encrypted = 0;
     557         640 :         c->default_compr = -1;
     558             : 
     559             :         while (1) {
     560        5184 :                 opt = getopt_long(argc, argv, optstring, longopts, &i);
     561        5184 :                 if (opt == -1)
     562             :                         break;
     563        4544 :                 switch (opt) {
     564         640 :                 case 'r':
     565             :                 case 'd':
     566         640 :                         free(root);
     567         640 :                         root_len = strlen(optarg);
     568         640 :                         root = xmalloc(root_len + 2);
     569             : 
     570             :                         /*
     571             :                          * The further code expects '/' at the end of the root
     572             :                          * UBIFS directory on the host.
     573             :                          */
     574         640 :                         memcpy(root, optarg, root_len);
     575         640 :                         if (root[root_len - 1] != '/')
     576         640 :                                 root[root_len++] = '/';
     577         640 :                         root[root_len] = 0;
     578             : 
     579             :                         /* Make sure the root directory exists */
     580        1280 :                         if (stat(root, &st))
     581           0 :                                 return sys_errmsg("bad root directory '%s'",
     582             :                                                    root);
     583             :                         break;
     584         640 :                 case 'm':
     585         640 :                         c->min_io_size = get_bytes(optarg);
     586         640 :                         if (c->min_io_size <= 0)
     587           0 :                                 return errmsg("bad min. I/O size");
     588             :                         break;
     589         640 :                 case 'e':
     590         640 :                         c->leb_size = get_bytes(optarg);
     591         640 :                         if (c->leb_size <= 0)
     592           0 :                                 return errmsg("bad LEB size");
     593             :                         break;
     594         640 :                 case 'c':
     595         640 :                         c->max_leb_cnt = get_bytes(optarg);
     596         640 :                         if (c->max_leb_cnt <= 0)
     597           0 :                                 return errmsg("bad maximum LEB count");
     598             :                         break;
     599         256 :                 case 'o':
     600         256 :                         c->dev_name = xstrdup(optarg);
     601         256 :                         break;
     602           0 :                 case 'D':
     603           0 :                         tbl_file = optarg;
     604           0 :                         if (stat(tbl_file, &st) < 0)
     605           0 :                                 return sys_errmsg("bad device table file '%s'",
     606             :                                                    tbl_file);
     607             :                         break;
     608         128 :                 case 'y':
     609         128 :                         yes = 1;
     610         128 :                         break;
     611           0 :                 case 'h':
     612           0 :                         printf("%s", helptext);
     613           0 :                         exit(EXIT_SUCCESS);
     614           0 :                 case '?':
     615           0 :                         printf("%s", helptext);
     616             : #ifdef WITH_CRYPTO
     617           0 :                         printf("\n\nSupported ciphers:\n");
     618           0 :                         list_ciphers(stdout);
     619             : #endif
     620           0 :                         exit(-1);
     621           0 :                 case 'v':
     622           0 :                         verbose = 1;
     623           0 :                         break;
     624           0 :                 case 'V':
     625           0 :                         common_print_version();
     626           0 :                         exit(EXIT_SUCCESS);
     627           0 :                 case 'g':
     628           0 :                         c->debug_level = strtol(optarg, &endp, 0);
     629           0 :                         if (*endp != '\0' || endp == optarg ||
     630           0 :                             c->debug_level < 0 || c->debug_level > DEBUG_LEVEL)
     631           0 :                                 return errmsg("bad debugging level '%s'",
     632             :                                                optarg);
     633             :                         break;
     634         640 :                 case 'f':
     635         640 :                         c->fanout = strtol(optarg, &endp, 0);
     636         640 :                         if (*endp != '\0' || endp == optarg || c->fanout <= 0)
     637           0 :                                 return errmsg("bad fanout %s", optarg);
     638             :                         break;
     639         320 :                 case 'F':
     640         320 :                         c->space_fixup = 1;
     641         320 :                         break;
     642           0 :                 case 'l':
     643           0 :                         c->log_lebs = strtol(optarg, &endp, 0);
     644           0 :                         if (*endp != '\0' || endp == optarg || c->log_lebs <= 0)
     645           0 :                                 return errmsg("bad count of log LEBs '%s'",
     646             :                                                optarg);
     647             :                         break;
     648           0 :                 case 'p':
     649           0 :                         c->orph_lebs = strtol(optarg, &endp, 0);
     650           0 :                         if (*endp != '\0' || endp == optarg ||
     651             :                             c->orph_lebs <= 0)
     652           0 :                                 return errmsg("bad orphan LEB count '%s'",
     653             :                                                optarg);
     654             :                         break;
     655             :                 case 'k':
     656           0 :                         if (strcmp(optarg, "r5") == 0) {
     657           0 :                                 c->key_hash = key_r5_hash;
     658           0 :                                 c->key_hash_type = UBIFS_KEY_HASH_R5;
     659           0 :                         } else if (strcmp(optarg, "test") == 0) {
     660           0 :                                 c->key_hash = key_test_hash;
     661           0 :                                 c->key_hash_type = UBIFS_KEY_HASH_TEST;
     662             :                         } else
     663           0 :                                 return errmsg("bad key hash");
     664             :                         break;
     665             :                 case 'x':
     666           0 :                         if (strcmp(optarg, "none") == 0)
     667           0 :                                 c->default_compr = UBIFS_COMPR_NONE;
     668             : #ifdef WITH_ZLIB
     669           0 :                         else if (strcmp(optarg, "zlib") == 0)
     670           0 :                                 c->default_compr = UBIFS_COMPR_ZLIB;
     671             : #endif
     672             : #ifdef WITH_ZSTD
     673           0 :                         else if (strcmp(optarg, "zstd") == 0)
     674           0 :                                 c->default_compr = UBIFS_COMPR_ZSTD;
     675             : #endif
     676             : #ifdef WITH_LZO
     677           0 :                         else if (strcmp(optarg, "lzo") == 0)
     678           0 :                                 c->default_compr = UBIFS_COMPR_LZO;
     679             : #endif
     680             : #if defined(WITH_LZO) && defined(WITH_ZLIB)
     681           0 :                         else if (strcmp(optarg, "favor_lzo") == 0) {
     682           0 :                                 c->default_compr = UBIFS_COMPR_LZO;
     683           0 :                                 c->favor_lzo = 1;
     684             :                         }
     685             : #endif
     686             :                         else
     687           0 :                                 return errmsg("bad compressor name");
     688             :                         break;
     689           0 :                 case 'X':
     690             : #if !defined(WITH_LZO) && !defined(WITH_ZLIB)
     691             :                         return errmsg("built without LZO or ZLIB support");
     692             : #else
     693           0 :                         c->favor_percent = strtol(optarg, &endp, 0);
     694           0 :                         if (*endp != '\0' || endp == optarg ||
     695           0 :                             c->favor_percent <= 0 || c->favor_percent >= 100)
     696           0 :                                 return errmsg("bad favor LZO percent '%s'",
     697             :                                                optarg);
     698             : #endif
     699             :                         break;
     700           0 :                 case 'j':
     701           0 :                         c->max_bud_bytes = get_bytes(optarg);
     702           0 :                         if (c->max_bud_bytes <= 0)
     703           0 :                                 return errmsg("bad maximum amount of buds");
     704             :                         break;
     705           0 :                 case 'R':
     706           0 :                         c->rp_size = get_bytes(optarg);
     707           0 :                         if (c->rp_size < 0)
     708           0 :                                 return errmsg("bad reserved bytes count");
     709             :                         break;
     710           0 :                 case 'U':
     711           0 :                         squash_owner = 1;
     712           0 :                         break;
     713           0 :                 case 'a':
     714           0 :                         do_create_inum_attr = 1;
     715           0 :                         break;
     716           0 :                 case 's':
     717           0 :                         free(context);
     718           0 :                         context_len = strlen(optarg);
     719           0 :                         context = (char *) xmalloc(context_len + 1);
     720           0 :                         if (!context)
     721           0 :                                 return errmsg("xmalloc failed\n");
     722           0 :                         memcpy(context, optarg, context_len);
     723           0 :                         context[context_len] = '\0';
     724             : 
     725             :                         /* Make sure root directory exists */
     726           0 :                         if (stat(context, &context_st))
     727           0 :                                 return sys_errmsg("bad file context %s\n",
     728             :                                                                    context);
     729             :                         break;
     730         320 :                 case 'K':
     731         320 :                         if (key_file) {
     732           0 :                                 return errmsg("key file specified more than once");
     733             :                         }
     734         320 :                         key_file = optarg;
     735         320 :                         break;
     736           0 :                 case 'b':
     737           0 :                         if (key_desc) {
     738           0 :                                 return errmsg("key descriptor specified more than once");
     739             :                         }
     740           0 :                         key_desc = optarg;
     741           0 :                         break;
     742           0 :                 case 'P': {
     743           0 :                         int error = 0;
     744             :                         unsigned long num;
     745             : 
     746           0 :                         num = simple_strtoul(optarg, &error);
     747           0 :                         if (error)
     748             :                                 num = -1;
     749             : 
     750           0 :                         fscrypt_flags &= ~FS_POLICY_FLAGS_PAD_MASK;
     751             : 
     752           0 :                         switch (num) {
     753             :                         case 4:
     754             :                                 fscrypt_flags |= FS_POLICY_FLAGS_PAD_4;
     755             :                                 break;
     756           0 :                         case 8:
     757           0 :                                 fscrypt_flags |= FS_POLICY_FLAGS_PAD_8;
     758           0 :                                 break;
     759           0 :                         case 16:
     760           0 :                                 fscrypt_flags |= FS_POLICY_FLAGS_PAD_16;
     761           0 :                                 break;
     762           0 :                         case 32:
     763           0 :                                 fscrypt_flags |= FS_POLICY_FLAGS_PAD_32;
     764           0 :                                 break;
     765           0 :                         default:
     766           0 :                                 return errmsg("invalid padding policy '%s'",
     767             :                                                 optarg);
     768             :                         }
     769           0 :                         break;
     770             :                 }
     771             : #ifdef WITH_CRYPTO
     772         320 :                 case 'C':
     773         320 :                         cipher_name = optarg;
     774         320 :                         break;
     775           0 :                 case HASH_ALGO_OPTION:
     776           0 :                         c->hash_algo_name = xstrdup(optarg);
     777           0 :                         break;
     778           0 :                 case AUTH_KEY_OPTION:
     779           0 :                         c->auth_key_filename = xstrdup(optarg);
     780           0 :                         break;
     781           0 :                 case AUTH_CERT_OPTION:
     782           0 :                         c->auth_cert_filename = xstrdup(optarg);
     783           0 :                         break;
     784             : #else
     785             :                 case 'C':
     786             :                 case HASH_ALGO_OPTION:
     787             :                 case AUTH_KEY_OPTION:
     788             :                 case AUTH_CERT_OPTION:
     789             :                         return errmsg("mkfs.ubifs was built without crypto support.");
     790             : #endif
     791             :                 }
     792             :         }
     793             : 
     794         640 :         if (optind != argc && !c->dev_name)
     795         384 :                 c->dev_name = xstrdup(argv[optind]);
     796             : 
     797         640 :         if (!c->dev_name)
     798           0 :                 return errmsg("not output device or file specified");
     799             : 
     800         640 :         open_ubi(c, c->dev_name);
     801             : 
     802         640 :         if (c->libubi) {
     803         384 :                 c->min_io_size = c->di.min_io_size;
     804         384 :                 c->leb_size = c->vi.leb_size;
     805         384 :                 if (c->max_leb_cnt == -1)
     806           0 :                         c->max_leb_cnt = c->vi.rsvd_lebs;
     807             :         }
     808         640 :         if (key_file || key_desc) {
     809             : #ifdef WITH_CRYPTO
     810         320 :                 if (!key_file)
     811           0 :                         return errmsg("no key file specified");
     812             : 
     813         320 :                 c->double_hash = 1;
     814         320 :                 c->encrypted = 1;
     815             : 
     816         320 :                 if (cipher_name == NULL)
     817           0 :                         cipher_name = "AES-256-XTS";
     818             : 
     819         320 :                 root_fctx = init_fscrypt_context(cipher_name, fscrypt_flags,
     820             :                                                 key_file, key_desc);
     821         320 :                 if (!root_fctx)
     822             :                         return -1;
     823             : #else
     824             :                 return errmsg("mkfs.ubifs was built without crypto support.");
     825             : #endif
     826             :         }
     827             : 
     828         640 :         if (c->default_compr == -1)
     829             :                 select_default_compr();
     830             : 
     831         640 :         if (c->min_io_size == -1)
     832           0 :                 return errmsg("min. I/O unit was not specified "
     833             :                                "(use -h for help)");
     834             : 
     835         640 :         if (c->leb_size == -1)
     836           0 :                 return errmsg("LEB size was not specified (use -h for help)");
     837             : 
     838         640 :         if (c->max_leb_cnt == -1)
     839           0 :                 return errmsg("Maximum count of LEBs was not specified "
     840             :                                "(use -h for help)");
     841             : 
     842         640 :         if (c->max_bud_bytes == -1) {
     843             :                 int lebs;
     844             : 
     845         640 :                 lebs = c->max_leb_cnt - UBIFS_SB_LEBS - UBIFS_MST_LEBS;
     846         640 :                 lebs -= c->orph_lebs;
     847         640 :                 if (c->log_lebs != -1)
     848           0 :                         lebs -= c->log_lebs;
     849             :                 else
     850         640 :                         lebs -= UBIFS_MIN_LOG_LEBS;
     851             :                 /*
     852             :                  * We do not know lprops geometry so far, so assume minimum
     853             :                  * count of lprops LEBs.
     854             :                  */
     855         640 :                 lebs -= UBIFS_MIN_LPT_LEBS;
     856             :                 /* Make the journal about 12.5% of main area lebs */
     857         640 :                 c->max_bud_bytes = (lebs / 8) * (long long)c->leb_size;
     858             :                 /* Make the max journal size 8MiB */
     859         640 :                 if (c->max_bud_bytes > 8 * 1024 * 1024)
     860         480 :                         c->max_bud_bytes = 8 * 1024 * 1024;
     861         640 :                 if (c->max_bud_bytes < 4 * c->leb_size)
     862           0 :                         c->max_bud_bytes = 4 * c->leb_size;
     863             :         }
     864             : 
     865         640 :         if (c->log_lebs == -1) {
     866         640 :                 c->log_lebs = calc_min_log_lebs(c->max_bud_bytes);
     867         640 :                 c->log_lebs += 2;
     868             :         }
     869             : 
     870         640 :         if (c->min_io_size < 8)
     871         192 :                 c->min_io_size = 8;
     872        1280 :         c->rp_size = add_space_overhead(c->rp_size);
     873             : 
     874         640 :         if (verbose) {
     875           0 :                 printf("mkfs.ubifs\n");
     876           0 :                 printf("\troot:         %s\n", root);
     877           0 :                 printf("\tmin_io_size:  %d\n", c->min_io_size);
     878           0 :                 printf("\tleb_size:     %d\n", c->leb_size);
     879           0 :                 printf("\tmax_leb_cnt:  %d\n", c->max_leb_cnt);
     880           0 :                 printf("\toutput:       %s\n", c->dev_name);
     881           0 :                 printf("\tjrn_size:     %llu\n", c->max_bud_bytes);
     882           0 :                 printf("\treserved:     %llu\n", c->rp_size);
     883           0 :                 switch (c->default_compr) {
     884           0 :                 case UBIFS_COMPR_LZO:
     885           0 :                         printf("\tcompr:        lzo\n");
     886           0 :                         break;
     887           0 :                 case UBIFS_COMPR_ZLIB:
     888           0 :                         printf("\tcompr:        zlib\n");
     889           0 :                         break;
     890           0 :                 case UBIFS_COMPR_NONE:
     891           0 :                         printf("\tcompr:        none\n");
     892           0 :                         break;
     893             :                 }
     894           0 :                 printf("\tkeyhash:      %s\n", (c->key_hash == key_r5_hash) ?
     895             :                                                 "r5" : "test");
     896           0 :                 printf("\tfanout:       %d\n", c->fanout);
     897           0 :                 printf("\torph_lebs:    %d\n", c->orph_lebs);
     898           0 :                 printf("\tspace_fixup:  %d\n", c->space_fixup);
     899           0 :                 printf("\tselinux file: %s\n", context);
     900             :         }
     901             : 
     902         640 :         if (validate_options())
     903             :                 return -1;
     904             : 
     905         640 :         if (tbl_file && parse_devtable(tbl_file))
     906           0 :                 return errmsg("cannot parse device table file '%s'", tbl_file);
     907             : 
     908             :         return 0;
     909             : }
     910             : 
     911             : /**
     912             :  * write_empty_leb - copy the image of an empty LEB to the output target.
     913             :  * @lnum: LEB number
     914             :  */
     915        4240 : static int write_empty_leb(int lnum)
     916             : {
     917        4240 :         memset(leb_buf, 0xff, c->leb_size);
     918        4240 :         return ubifs_leb_change(c, lnum, leb_buf, c->leb_size);
     919             : }
     920             : 
     921             : /**
     922             :  * write_node - write a node to a LEB.
     923             :  * @node: node
     924             :  * @len: node length
     925             :  * @lnum: LEB number
     926             :  */
     927        1920 : static int write_node(void *node, int len, int lnum)
     928             : {
     929        1920 :         int alen = ALIGN(len, 8), wlen = ALIGN(len, c->min_io_size);
     930             : 
     931        1920 :         ubifs_prepare_node(c, node, len, 0);
     932        1920 :         memcpy(leb_buf, node, len);
     933        1920 :         memset(leb_buf + len, 0xff, alen - len);
     934        1920 :         ubifs_pad(c, leb_buf + alen, wlen - alen);
     935             : 
     936        1920 :         memset(leb_buf + wlen, 0xff, c->leb_size - wlen);
     937             : 
     938        1920 :         return ubifs_leb_change(c, lnum, leb_buf, c->leb_size);
     939             : }
     940             : 
     941             : /**
     942             :  * calc_dark - calculate LEB dark space size.
     943             :  * @c: the UBIFS file-system description object
     944             :  * @spc: amount of free and dirty space in the LEB
     945             :  *
     946             :  * This function calculates amount of dark space in an LEB which has @spc bytes
     947             :  * of free and dirty space. Returns the calculations result.
     948             :  *
     949             :  * Dark space is the space which is not always usable - it depends on which
     950             :  * nodes are written in which order. E.g., if an LEB has only 512 free bytes,
     951             :  * it is dark space, because it cannot fit a large data node. So UBIFS cannot
     952             :  * count on this LEB and treat these 512 bytes as usable because it is not true
     953             :  * if, for example, only big chunks of uncompressible data will be written to
     954             :  * the FS.
     955             :  */
     956             : static int calc_dark(struct ubifs_info *c, int spc)
     957             : {
     958       16920 :         if (spc < c->dark_wm)
     959             :                 return spc;
     960             : 
     961             :         /*
     962             :          * If we have slightly more space then the dark space watermark, we can
     963             :          * anyway safely assume it we'll be able to write a node of the
     964             :          * smallest size there.
     965             :          */
     966        1280 :         if (spc - c->dark_wm < (int)MIN_WRITE_SZ)
     967           0 :                 return spc - MIN_WRITE_SZ;
     968             : 
     969             :         return c->dark_wm;
     970             : }
     971             : 
     972             : /**
     973             :  * set_lprops - set the LEB property values for a LEB.
     974             :  * @lnum: LEB number
     975             :  * @offs: end offset of data in the LEB
     976             :  * @flags: LEB property flags
     977             :  */
     978       19760 : static void set_lprops(int lnum, int offs, int flags)
     979             : {
     980       19760 :         int i = lnum - c->main_first, free, dirty;
     981       19760 :         int a = max_t(int, c->min_io_size, 8);
     982             : 
     983       19760 :         free = c->leb_size - ALIGN(offs, a);
     984       19760 :         dirty = c->leb_size - free - ALIGN(offs, 8);
     985       19760 :         pr_debug("LEB %d free %d dirty %d flags %d\n", lnum, free, dirty, flags);
     986       19760 :         if (i < c->main_lebs) {
     987       19760 :                 c->lpt[i].free = free;
     988       19760 :                 c->lpt[i].dirty = dirty;
     989       19760 :                 c->lpt[i].flags = flags;
     990             :         }
     991       19760 :         c->lst.total_free += free;
     992       19760 :         c->lst.total_dirty += dirty;
     993       19760 :         if (flags & LPROPS_INDEX)
     994         800 :                 c->lst.idx_lebs += 1;
     995             :         else {
     996             :                 int spc;
     997             : 
     998       18960 :                 spc = free + dirty;
     999       18960 :                 if (spc < c->dead_wm)
    1000        2040 :                         c->lst.total_dead += spc;
    1001             :                 else
    1002       33840 :                         c->lst.total_dark += calc_dark(c, spc);
    1003       18960 :                 c->lst.total_used += c->leb_size - spc;
    1004             :         }
    1005       19760 : }
    1006             : 
    1007             : /**
    1008             :  * add_to_index - add a node key and position to the index.
    1009             :  * @key: node key
    1010             :  * @lnum: node LEB number
    1011             :  * @offs: node offset
    1012             :  * @len: node length
    1013             :  * @hash: hash of the node
    1014             :  */
    1015     1429120 : static int add_to_index(union ubifs_key *key, char *name, int name_len,
    1016             :                         int lnum, int offs, int len, const uint8_t *hash)
    1017             : {
    1018             :         struct idx_entry *e;
    1019             : 
    1020     1429120 :         pr_debug("LEB %d offs %d len %d\n", lnum, offs, len);
    1021     1429120 :         e = xmalloc(sizeof(struct idx_entry));
    1022     1429120 :         e->next = NULL;
    1023     1429120 :         e->prev = idx_list_last;
    1024     1429120 :         e->key = *key;
    1025     1429120 :         e->name = name;
    1026     1429120 :         e->name_len = name_len;
    1027     1429120 :         e->lnum = lnum;
    1028     1429120 :         e->offs = offs;
    1029     1429120 :         e->len = len;
    1030     1429120 :         memcpy(e->hash, hash, c->hash_len);
    1031             : 
    1032     1429120 :         if (!idx_list_first)
    1033         640 :                 idx_list_first = e;
    1034     1429120 :         if (idx_list_last)
    1035     1428480 :                 idx_list_last->next = e;
    1036     1429120 :         idx_list_last = e;
    1037     1429120 :         idx_cnt += 1;
    1038     1429120 :         return 0;
    1039             : }
    1040             : 
    1041             : /**
    1042             :  * flush_nodes - write the current head and move the head to the next LEB.
    1043             :  */
    1044       19120 : static int flush_nodes(void)
    1045             : {
    1046             :         int len, err;
    1047             : 
    1048       19120 :         if (!head_offs)
    1049             :                 return 0;
    1050       19120 :         len = ALIGN(head_offs, c->min_io_size);
    1051       19120 :         ubifs_pad(c, leb_buf + head_offs, len - head_offs);
    1052       19120 :         memset(leb_buf + len, 0xff, c->leb_size - len);
    1053       19120 :         err = ubifs_leb_change(c, head_lnum, leb_buf, c->leb_size);
    1054       19120 :         if (err)
    1055             :                 return err;
    1056       19120 :         set_lprops(head_lnum, head_offs, head_flags);
    1057       19120 :         head_lnum += 1;
    1058       19120 :         head_offs = 0;
    1059       19120 :         return 0;
    1060             : }
    1061             : 
    1062             : /**
    1063             :  * reserve_space - reserve space for a node on the head.
    1064             :  * @len: node length
    1065             :  * @lnum: LEB number is returned here
    1066             :  * @offs: offset is returned here
    1067             :  */
    1068     1906880 : static int reserve_space(int len, int *lnum, int *offs)
    1069             : {
    1070             :         int err;
    1071             : 
    1072     1906880 :         if (len > c->leb_size - head_offs) {
    1073       17840 :                 err = flush_nodes();
    1074       17840 :                 if (err)
    1075             :                         return err;
    1076             :         }
    1077     1906880 :         *lnum = head_lnum;
    1078     1906880 :         *offs = head_offs;
    1079     1906880 :         head_offs += ALIGN(len, 8);
    1080     1906880 :         return 0;
    1081             : }
    1082             : 
    1083             : /**
    1084             :  * add_node - write a node to the head.
    1085             :  * @key: node key
    1086             :  * @node: node
    1087             :  * @len: node length
    1088             :  */
    1089     1429120 : static int add_node(union ubifs_key *key, char *name, int name_len, void *node, int len)
    1090             : {
    1091     2858240 :         int err, lnum, offs, type = key_type(c, key);
    1092             :         uint8_t hash[UBIFS_MAX_HASH_LEN];
    1093             : 
    1094     1429120 :         if (type == UBIFS_DENT_KEY || type == UBIFS_XENT_KEY) {
    1095      125120 :                 if (!name)
    1096           0 :                         return errmsg("Directory entry or xattr "
    1097             :                                         "without name!");
    1098             :         } else {
    1099     1304000 :                 if (name)
    1100           0 :                         return errmsg("Name given for non dir/xattr node!");
    1101             :         }
    1102             : 
    1103     1429120 :         ubifs_prepare_node(c, node, len, 0);
    1104             : 
    1105     1429120 :         err = reserve_space(len, &lnum, &offs);
    1106     1429120 :         if (err)
    1107             :                 return err;
    1108             : 
    1109     1429120 :         memcpy(leb_buf + offs, node, len);
    1110     1429120 :         memset(leb_buf + offs + len, 0xff, ALIGN(len, 8) - len);
    1111             : 
    1112     2858240 :         ubifs_node_calc_hash(c, node, hash);
    1113             : 
    1114     1429120 :         add_to_index(key, name, name_len, lnum, offs, len, hash);
    1115             : 
    1116     1429120 :         return 0;
    1117             : }
    1118             : 
    1119       32960 : static int add_xattr(struct ubifs_ino_node *host_ino, struct stat *st,
    1120             :                      ino_t inum, char *name, const void *data,
    1121             :                      unsigned int data_len)
    1122             : {
    1123             :         struct ubifs_ino_node *ino;
    1124             :         struct ubifs_dent_node *xent;
    1125             :         struct fscrypt_name nm;
    1126             :         char *tmp_name;
    1127             :         union ubifs_key xkey, nkey;
    1128             :         int len, ret;
    1129             : 
    1130       32960 :         fname_len(&nm) = strlen(name);
    1131       32960 :         tmp_name = xmalloc(fname_len(&nm) + 1);
    1132       32960 :         memcpy(tmp_name, name, fname_len(&nm) + 1);
    1133       32960 :         fname_name(&nm) = tmp_name;
    1134             : 
    1135       32960 :         host_ino->xattr_cnt++;
    1136       32960 :         host_ino->xattr_size += CALC_DENT_SIZE(fname_len(&nm));
    1137       32960 :         host_ino->xattr_size += CALC_XATTR_BYTES(data_len);
    1138       32960 :         host_ino->xattr_names += fname_len(&nm);
    1139             : 
    1140       65920 :         xent = xzalloc(sizeof(*xent) + fname_len(&nm) + 1);
    1141       65920 :         ino = xzalloc(sizeof(*ino) + data_len);
    1142             : 
    1143       32960 :         xent_key_init(c, &xkey, inum, &nm);
    1144       32960 :         xent->ch.node_type = UBIFS_XENT_NODE;
    1145       65920 :         key_write(c, &xkey, &xent->key);
    1146             : 
    1147       32960 :         len = UBIFS_XENT_NODE_SZ + fname_len(&nm) + 1;
    1148             : 
    1149       32960 :         xent->ch.len = len;
    1150       32960 :         xent->padding1 = 0;
    1151       32960 :         xent->type = UBIFS_ITYPE_REG;
    1152       32960 :         xent->nlen = cpu_to_le16(fname_len(&nm));
    1153             : 
    1154       32960 :         memcpy(xent->name, fname_name(&nm), fname_len(&nm) + 1);
    1155             : 
    1156       32960 :         inum = ++c->highest_inum;
    1157       32960 :         creat_sqnum = ++c->max_sqnum;
    1158             : 
    1159       32960 :         xent->inum = cpu_to_le64(inum);
    1160             : 
    1161       32960 :         ret = add_node(&xkey, tmp_name, fname_len(&nm), xent, len);
    1162       32960 :         if (ret)
    1163             :                 goto out;
    1164             : 
    1165       32960 :         ino->creat_sqnum = cpu_to_le64(creat_sqnum);
    1166       32960 :         ino->nlink      = cpu_to_le32(1);
    1167             :         /*
    1168             :          * The time fields are updated assuming the default time granularity
    1169             :          * of 1 second. To support finer granularities, utime() would be needed.
    1170             :          */
    1171       32960 :         ino->atime_sec  = cpu_to_le64(st->st_atime);
    1172       32960 :         ino->ctime_sec  = cpu_to_le64(st->st_ctime);
    1173       32960 :         ino->mtime_sec  = cpu_to_le64(st->st_mtime);
    1174       32960 :         ino->atime_nsec = 0;
    1175       32960 :         ino->ctime_nsec = 0;
    1176       32960 :         ino->mtime_nsec = 0;
    1177       32960 :         ino->uid        = cpu_to_le32(st->st_uid);
    1178       32960 :         ino->gid        = cpu_to_le32(st->st_gid);
    1179       32960 :         ino->compr_type = cpu_to_le16(c->default_compr);
    1180       32960 :         ino->ch.node_type = UBIFS_INO_NODE;
    1181             : 
    1182       65920 :         ino_key_init(c, &nkey, inum);
    1183       65920 :         key_write(c, &nkey, &ino->key);
    1184             : 
    1185       32960 :         ino->size       = cpu_to_le64(data_len);
    1186       32960 :         ino->mode       = cpu_to_le32(S_IFREG);
    1187       32960 :         ino->data_len   = cpu_to_le32(data_len);
    1188       32960 :         ino->flags      = cpu_to_le32(UBIFS_XATTR_FL);
    1189             : 
    1190       32960 :         if (data_len)
    1191       32960 :                 memcpy(&ino->data, data, data_len);
    1192             : 
    1193       32960 :         ret = add_node(&nkey, NULL, 0, ino, UBIFS_INO_NODE_SZ + data_len);
    1194             : 
    1195       32960 : out:
    1196       32960 :         free(xent);
    1197       32960 :         free(ino);
    1198             : 
    1199       32960 :         return ret;
    1200             : }
    1201             : 
    1202             : #ifndef WITH_XATTR
    1203             : static inline int create_inum_attr(ino_t inum, const char *name)
    1204             : {
    1205             :         (void)inum;
    1206             :         (void)name;
    1207             : 
    1208             :         return 0;
    1209             : }
    1210             : 
    1211             : static inline int inode_add_xattr(struct ubifs_ino_node *host_ino,
    1212             :                                   const char *path_name,
    1213             :                                   struct stat *st, ino_t inum)
    1214             : {
    1215             :         (void)host_ino;
    1216             :         (void)path_name;
    1217             :         (void)st;
    1218             :         (void)inum;
    1219             : 
    1220             :         return 0;
    1221             : }
    1222             : #else
    1223       92800 : static int create_inum_attr(ino_t inum, const char *name)
    1224             : {
    1225             :         char *str;
    1226             :         int ret;
    1227             : 
    1228       92800 :         if (!do_create_inum_attr)
    1229             :                 return 0;
    1230             : 
    1231           0 :         ret = asprintf(&str, "%llu", (unsigned long long)inum);
    1232           0 :         if (ret < 0)
    1233             :                 return ret;
    1234             : 
    1235           0 :         ret = lsetxattr(name, "user.image-inode-number", str, ret, 0);
    1236             : 
    1237           0 :         free(str);
    1238             : 
    1239           0 :         return ret;
    1240             : }
    1241             : 
    1242       85760 : static int inode_add_xattr(struct ubifs_ino_node *host_ino,
    1243             :                            const char *path_name, struct stat *st, ino_t inum)
    1244             : {
    1245             :         int ret;
    1246       85760 :         void *buf = NULL;
    1247             :         ssize_t len;
    1248       85760 :         ssize_t pos = 0;
    1249             : 
    1250       85760 :         len = llistxattr(path_name, NULL, 0);
    1251       85760 :         if (len < 0) {
    1252           0 :                 if (errno == ENOENT || errno == EOPNOTSUPP)
    1253             :                         return 0;
    1254             : 
    1255           0 :                 sys_errmsg("llistxattr failed on %s", path_name);
    1256             : 
    1257           0 :                 return len;
    1258             :         }
    1259             : 
    1260       85760 :         if (len == 0)
    1261             :                 goto noxattr;
    1262             : 
    1263       10240 :         buf = xmalloc(len);
    1264             : 
    1265       10240 :         len = llistxattr(path_name, buf, len);
    1266       10240 :         if (len < 0) {
    1267           0 :                 sys_errmsg("llistxattr failed on %s", path_name);
    1268           0 :                 goto out_free;
    1269             :         }
    1270             : 
    1271       21120 :         while (pos < len) {
    1272       10880 :                 char attrbuf[1024] = { };
    1273             :                 char *name;
    1274             :                 ssize_t attrsize;
    1275             : 
    1276       10880 :                 name = buf + pos;
    1277       10880 :                 pos += strlen(name) + 1;
    1278             : 
    1279       10880 :                 attrsize = lgetxattr(path_name, name, attrbuf, sizeof(attrbuf) - 1);
    1280       10880 :                 if (attrsize < 0) {
    1281           0 :                         sys_errmsg("lgetxattr failed on %s", path_name);
    1282           0 :                         goto out_free;
    1283             :                 }
    1284             : 
    1285       10880 :                 if (!strcmp(name, "user.image-inode-number")) {
    1286             :                         ino_t inum_from_xattr;
    1287             : 
    1288           0 :                         inum_from_xattr = strtoull(attrbuf, NULL, 10);
    1289           0 :                         if (inum != inum_from_xattr) {
    1290           0 :                                 errno = EINVAL;
    1291           0 :                                 sys_errmsg("calculated inum (%llu) doesn't match inum from xattr (%llu) size (%zd) on %s",
    1292             :                                             (unsigned long long)inum,
    1293             :                                             (unsigned long long)inum_from_xattr,
    1294             :                                             attrsize,
    1295             :                                             path_name);
    1296           0 :                                 goto out_free;
    1297             :                         }
    1298             : 
    1299           0 :                         continue;
    1300             :                 }
    1301             : 
    1302             : #ifdef WITH_SELINUX
    1303             :                 /*
    1304             :                   Ignore selinux attributes if we have a label file, they are
    1305             :                   instead provided by inode_add_selinux_xattr.
    1306             :                  */
    1307       10880 :                 if (!strcmp(name, XATTR_NAME_SELINUX) && context && sehnd)
    1308           0 :                         continue;
    1309             : #endif
    1310             : 
    1311       10880 :                 ret = add_xattr(host_ino, st, inum, name, attrbuf, attrsize);
    1312       10880 :                 if (ret < 0)
    1313             :                         goto out_free;
    1314             :         }
    1315             : 
    1316       85760 : noxattr:
    1317       85760 :         free(buf);
    1318       85760 :         return 0;
    1319             : 
    1320           0 : out_free:
    1321           0 :         free(buf);
    1322             : 
    1323           0 :         return -1;
    1324             : }
    1325             : #endif
    1326             : 
    1327             : #ifdef WITH_SELINUX
    1328       85760 : static int inode_add_selinux_xattr(struct ubifs_ino_node *host_ino,
    1329             :                            const char *path_name, struct stat *st, ino_t inum)
    1330             : {
    1331             :         int ret;
    1332       85760 :         char *sepath = NULL;
    1333             :         char *name;
    1334             :         unsigned int con_size;
    1335             :         char *secontext;
    1336             : 
    1337       85760 :         if (!context || !sehnd)
    1338             :                 return 0;
    1339             : 
    1340           0 :         if (path_name[strlen(root)] == '/')
    1341           0 :                 sepath = strdup(&path_name[strlen(root)]);
    1342             : 
    1343           0 :         else if (asprintf(&sepath, "/%s", &path_name[strlen(root)]) < 0)
    1344           0 :                 sepath = NULL;
    1345             : 
    1346           0 :         if (!sepath)
    1347           0 :                 return sys_errmsg("could not get sepath\n");
    1348             : 
    1349           0 :         if (selabel_lookup(sehnd, &secontext, sepath, st->st_mode) < 0) {
    1350             :                 /* Failed to lookup context, assume unlabeled */
    1351           0 :                 secontext = strdup("system_u:object_r:unlabeled_t:s0");
    1352           0 :                 pr_debug("missing context: %s\t%s\t%d\n", secontext, sepath,
    1353             :                          st->st_mode);
    1354             :         }
    1355             : 
    1356           0 :         pr_debug("appling selinux context on sepath=%s, secontext=%s\n",
    1357             :                  sepath, secontext);
    1358           0 :         free(sepath);
    1359           0 :         con_size = strlen(secontext) + 1;
    1360           0 :         name = strdup(XATTR_NAME_SELINUX);
    1361             : 
    1362           0 :         ret = add_xattr(host_ino, st, inum, name, secontext, con_size);
    1363           0 :         if (ret < 0)
    1364           0 :                 pr_debug("add_xattr failed %d\n", ret);
    1365             :         return ret;
    1366             : }
    1367             : 
    1368             : #else
    1369             : static inline int inode_add_selinux_xattr(struct ubifs_ino_node *host_ino,
    1370             :                            const char *path_name, struct stat *st, ino_t inum)
    1371             : {
    1372             :         (void)host_ino;
    1373             :         (void)path_name;
    1374             :         (void)st;
    1375             :         (void)inum;
    1376             : 
    1377             :         return 0;
    1378             : }
    1379             : #endif
    1380             : 
    1381             : #ifdef WITH_CRYPTO
    1382       22080 : static int set_fscrypt_context(struct ubifs_ino_node *host_ino, ino_t inum,
    1383             :                                struct stat *host_st,
    1384             :                                struct fscrypt_context *fctx)
    1385             : {
    1386       22080 :         return add_xattr(host_ino, host_st, inum,
    1387             :                          xstrdup(UBIFS_XATTR_NAME_ENCRYPTION_CONTEXT),
    1388             :                          fctx, sizeof(*fctx));
    1389             : }
    1390             : 
    1391        3840 : static int encrypt_symlink(void *dst, void *data, unsigned int data_len,
    1392             :                            struct fscrypt_context *fctx)
    1393             : {
    1394             :         struct fscrypt_symlink_data *sd;
    1395             :         void *outbuf;
    1396             :         unsigned int link_disk_len;
    1397             :         unsigned int cryptlen;
    1398             :         int ret;
    1399             : 
    1400        3840 :         link_disk_len = sizeof(struct fscrypt_symlink_data);
    1401        3840 :         link_disk_len += fscrypt_fname_encrypted_size(fctx, data_len);
    1402             : 
    1403        3840 :         ret = encrypt_path(&outbuf, data, data_len, UBIFS_MAX_INO_DATA, fctx);
    1404        3840 :         if (ret < 0)
    1405             :                 return ret;
    1406        3840 :         cryptlen = ret;
    1407             : 
    1408        7680 :         sd = xzalloc(link_disk_len);
    1409        3840 :         memcpy(sd->encrypted_path, outbuf, cryptlen);
    1410        3840 :         sd->len = cpu_to_le16(cryptlen);
    1411        3840 :         memcpy(dst, sd, link_disk_len);
    1412        3840 :         ((char *)dst)[link_disk_len - 1] = '\0';
    1413             : 
    1414        3840 :         free(outbuf);
    1415        3840 :         free(sd);
    1416        3840 :         return link_disk_len;
    1417             : }
    1418             : #else
    1419             : static int set_fscrypt_context(struct ubifs_ino_node *host_ino, ino_t inum,
    1420             :                                struct stat *host_st,
    1421             :                                struct fscrypt_context *fctx)
    1422             : {
    1423             :         (void)host_ino;
    1424             :         (void)inum;
    1425             :         (void)host_st;
    1426             :         (void)fctx;
    1427             : 
    1428             :         assert(0);
    1429             :         return -1;
    1430             : }
    1431             : static int encrypt_symlink(void *dst, void *data, unsigned int data_len,
    1432             :                            struct fscrypt_context *fctx)
    1433             : {
    1434             :         (void)dst;
    1435             :         (void)data;
    1436             :         (void)data_len;
    1437             :         (void)fctx;
    1438             : 
    1439             :         assert(0);
    1440             :         return -1;
    1441             : }
    1442             : #endif
    1443             : 
    1444             : /**
    1445             :  * add_inode - write an inode.
    1446             :  * @st: stat information of source inode
    1447             :  * @inum: target inode number
    1448             :  * @data: inode data (for special inodes e.g. symlink path etc)
    1449             :  * @data_len: inode data length
    1450             :  * @flags: source inode flags
    1451             :  */
    1452       85760 : static int add_inode(struct stat *st, ino_t inum, void *data,
    1453             :                      unsigned int data_len, int flags, const char *xattr_path,
    1454             :                      struct fscrypt_context *fctx)
    1455             : {
    1456       85760 :         struct ubifs_ino_node *ino = node_buf;
    1457             :         union ubifs_key key;
    1458       85760 :         int len, use_flags = 0, ret;
    1459             : 
    1460       85760 :         if (c->default_compr != UBIFS_COMPR_NONE)
    1461       42880 :                 use_flags |= UBIFS_COMPR_FL;
    1462       85760 :         if (flags & FS_COMPR_FL)
    1463           0 :                 use_flags |= UBIFS_COMPR_FL;
    1464       85760 :         if (flags & FS_SYNC_FL)
    1465           0 :                 use_flags |= UBIFS_SYNC_FL;
    1466       85760 :         if (flags & FS_IMMUTABLE_FL)
    1467           0 :                 use_flags |= UBIFS_IMMUTABLE_FL;
    1468       85760 :         if (flags & FS_APPEND_FL)
    1469           0 :                 use_flags |= UBIFS_APPEND_FL;
    1470       85760 :         if (flags & FS_DIRSYNC_FL && S_ISDIR(st->st_mode))
    1471           0 :                 use_flags |= UBIFS_DIRSYNC_FL;
    1472       85760 :         if (fctx)
    1473       22080 :                 use_flags |= UBIFS_CRYPT_FL;
    1474       85760 :         memset(ino, 0, UBIFS_INO_NODE_SZ);
    1475             : 
    1476      171520 :         ino_key_init(c, &key, inum);
    1477       85760 :         ino->ch.node_type = UBIFS_INO_NODE;
    1478      171520 :         key_write(c, &key, &ino->key);
    1479       85760 :         ino->creat_sqnum = cpu_to_le64(creat_sqnum);
    1480       85760 :         ino->size       = cpu_to_le64(st->st_size);
    1481       85760 :         ino->nlink      = cpu_to_le32(st->st_nlink);
    1482             :         /*
    1483             :          * The time fields are updated assuming the default time granularity
    1484             :          * of 1 second. To support finer granularities, utime() would be needed.
    1485             :          */
    1486       85760 :         ino->atime_sec  = cpu_to_le64(st->st_atime);
    1487       85760 :         ino->ctime_sec  = cpu_to_le64(st->st_ctime);
    1488       85760 :         ino->mtime_sec  = cpu_to_le64(st->st_mtime);
    1489       85760 :         ino->atime_nsec = 0;
    1490       85760 :         ino->ctime_nsec = 0;
    1491       85760 :         ino->mtime_nsec = 0;
    1492       85760 :         ino->uid        = cpu_to_le32(st->st_uid);
    1493       85760 :         ino->gid        = cpu_to_le32(st->st_gid);
    1494       85760 :         ino->mode       = cpu_to_le32(st->st_mode);
    1495       85760 :         ino->flags      = cpu_to_le32(use_flags);
    1496       85760 :         ino->compr_type = cpu_to_le16(c->default_compr);
    1497       85760 :         if (data_len) {
    1498       46080 :                 if (!fctx) {
    1499       42240 :                         memcpy(&ino->data, data, data_len);
    1500             :                 } else {
    1501             :                         /* TODO: what about device files? */
    1502        3840 :                         if (!S_ISLNK(st->st_mode))
    1503           0 :                                 return errmsg("Expected symlink");
    1504             : 
    1505        3840 :                         ret = encrypt_symlink(&ino->data, data, data_len, fctx);
    1506        3840 :                         if (ret < 0)
    1507             :                                 return ret;
    1508        3840 :                         data_len = ret;
    1509             :                 }
    1510             :         }
    1511       85760 :         ino->data_len   = cpu_to_le32(data_len);
    1512       85760 :         len = UBIFS_INO_NODE_SZ + data_len;
    1513             : 
    1514       85760 :         if (xattr_path) {
    1515       85760 :                 ret = inode_add_selinux_xattr(ino, xattr_path, st, inum);
    1516       85760 :                 if (ret < 0)
    1517             :                         return ret;
    1518             : 
    1519       85760 :                 ret = inode_add_xattr(ino, xattr_path, st, inum);
    1520       85760 :                 if (ret < 0)
    1521             :                         return ret;
    1522             :         }
    1523             : 
    1524       85760 :         if (fctx) {
    1525       22080 :                 ret = set_fscrypt_context(ino, inum, st, fctx);
    1526       22080 :                 if (ret < 0)
    1527             :                         return ret;
    1528             :         }
    1529             : 
    1530       85760 :         return add_node(&key, NULL, 0, ino, len);
    1531             : }
    1532             : 
    1533             : /**
    1534             :  * add_dir_inode - write an inode for a directory.
    1535             :  * @dir: source directory
    1536             :  * @inum: target inode number
    1537             :  * @size: target directory size
    1538             :  * @nlink: target directory link count
    1539             :  * @st: struct stat object describing attributes (except size and nlink) of the
    1540             :  *      target inode to create
    1541             :  *
    1542             :  * Note, this function may be called with %NULL @dir, when the directory which
    1543             :  * is being created does not exist at the host file system, but is defined by
    1544             :  * the device table.
    1545             :  */
    1546       16640 : static int add_dir_inode(const char *path_name, DIR *dir, ino_t inum, loff_t size,
    1547             :                          unsigned int nlink, struct stat *st,
    1548             :                          struct fscrypt_context *fctx)
    1549             : {
    1550       16640 :         int fd, flags = 0;
    1551             : 
    1552       16640 :         st->st_size = size;
    1553       16640 :         st->st_nlink = nlink;
    1554             : 
    1555       16640 :         if (dir) {
    1556       16640 :                 fd = dirfd(dir);
    1557       16640 :                 if (fd == -1)
    1558           0 :                         return sys_errmsg("dirfd failed");
    1559       16640 :                 if (ioctl(fd, FS_IOC_GETFLAGS, &flags) == -1)
    1560           0 :                         flags = 0;
    1561             :         }
    1562             : 
    1563       16640 :         return add_inode(st, inum, NULL, 0, flags, path_name, fctx);
    1564             : }
    1565             : 
    1566             : /**
    1567             :  * add_dev_inode - write an inode for a character or block device.
    1568             :  * @st: stat information of source inode
    1569             :  * @inum: target inode number
    1570             :  * @flags: source inode flags
    1571             :  */
    1572       37120 : static int add_dev_inode(const char *path_name, struct stat *st, ino_t inum, int flags)
    1573             : {
    1574             :         union ubifs_dev_desc dev;
    1575             : 
    1576      148480 :         dev.huge = cpu_to_le64(makedev(major(st->st_rdev), minor(st->st_rdev)));
    1577       37120 :         return add_inode(st, inum, &dev, 8, flags, path_name, NULL);
    1578             : }
    1579             : 
    1580             : /**
    1581             :  * add_symlink_inode - write an inode for a symbolic link.
    1582             :  * @path_name: path name of symbolic link inode itself (not the link target)
    1583             :  * @st: stat information of source inode
    1584             :  * @inum: target inode number
    1585             :  * @flags: source inode flags
    1586             :  */
    1587        8960 : static int add_symlink_inode(const char *path_name, struct stat *st, ino_t inum,
    1588             :                              int flags, struct fscrypt_context *fctx)
    1589             : {
    1590             :         char buf[UBIFS_MAX_INO_DATA + 2];
    1591             :         ssize_t len;
    1592             : 
    1593             :         /* Take the symlink as is */
    1594        8960 :         len = readlink(path_name, buf, UBIFS_MAX_INO_DATA + 1);
    1595        8960 :         if (len <= 0)
    1596           0 :                 return sys_errmsg("readlink failed for %s", path_name);
    1597        8960 :         if (len > UBIFS_MAX_INO_DATA)
    1598           0 :                 return errmsg("symlink too long for %s", path_name);
    1599             : 
    1600        8960 :         return add_inode(st, inum, buf, len, flags, path_name, fctx);
    1601             : }
    1602             : 
    1603             : static void set_dent_cookie(struct ubifs_dent_node *dent)
    1604             : {
    1605             : #ifdef WITH_CRYPTO
    1606       92160 :         if (c->double_hash)
    1607       46080 :                 RAND_bytes((void *)&dent->cookie, sizeof(dent->cookie));
    1608             :         else
    1609             : #endif
    1610       46080 :                 dent->cookie = 0;
    1611             : }
    1612             : 
    1613             : /**
    1614             :  * add_dent_node - write a directory entry node.
    1615             :  * @dir_inum: target inode number of directory
    1616             :  * @name: directory entry name
    1617             :  * @inum: target inode number of the directory entry
    1618             :  * @type: type of the target inode
    1619             :  * @kname_len: the length of name stored in the directory entry node is
    1620             :  *             returned here
    1621             :  */
    1622       92160 : static int add_dent_node(ino_t dir_inum, const char *name, ino_t inum,
    1623             :                          unsigned char type, struct fscrypt_context *fctx,
    1624             :                          int *kname_len)
    1625             : {
    1626       92160 :         struct ubifs_dent_node *dent = node_buf;
    1627             :         union ubifs_key key;
    1628             :         struct qstr dname;
    1629             :         struct fscrypt_name nm;
    1630             :         char *kname;
    1631             :         int len;
    1632             : 
    1633       92160 :         pr_debug("%s ino %lu type %u dir ino %lu\n", name, (unsigned long)inum,
    1634             :                  (unsigned int)type, (unsigned long)dir_inum);
    1635       92160 :         memset(dent, 0, UBIFS_DENT_NODE_SZ);
    1636             : 
    1637       92160 :         dname.name = (void *)name;
    1638       92160 :         dname.len = strlen(name);
    1639             : 
    1640       92160 :         dent->ch.node_type = UBIFS_DENT_NODE;
    1641             : 
    1642       92160 :         dent->inum = cpu_to_le64(inum);
    1643       92160 :         dent->padding1 = 0;
    1644       92160 :         dent->type = type;
    1645       92160 :         set_dent_cookie(dent);
    1646             : 
    1647       92160 :         if (!fctx) {
    1648       46080 :                 *kname_len = dname.len;
    1649       46080 :                 kname = strdup(name);
    1650       46080 :                 if (!kname)
    1651           0 :                         return errmsg("cannot allocate memory");
    1652             :         } else {
    1653       46080 :                 unsigned int max_namelen = UBIFS_MAX_NLEN;
    1654             :                 int ret;
    1655             : 
    1656       46080 :                 if (type == UBIFS_ITYPE_LNK)
    1657        5440 :                         max_namelen = UBIFS_MAX_INO_DATA;
    1658             : 
    1659       46080 :                 ret = encrypt_path((void **)&kname, dname.name, dname.len,
    1660             :                                    max_namelen, fctx);
    1661       46080 :                 if (ret < 0)
    1662             :                         return ret;
    1663             : 
    1664       46080 :                 *kname_len = ret;
    1665             :         }
    1666             : 
    1667       92160 :         fname_name(&nm) = kname;
    1668       92160 :         fname_len(&nm) = *kname_len;
    1669       92160 :         dent_key_init(c, &key, dir_inum, &nm);
    1670       92160 :         dent->nlen = cpu_to_le16(*kname_len);
    1671       92160 :         memcpy(dent->name, kname, *kname_len);
    1672       92160 :         dent->name[*kname_len] = '\0';
    1673       92160 :         len = UBIFS_DENT_NODE_SZ + *kname_len + 1;
    1674             : 
    1675      184320 :         key_write(c, &key, dent->key);
    1676             : 
    1677       92160 :         return add_node(&key, kname, *kname_len, dent, len);
    1678             : }
    1679             : 
    1680             : /**
    1681             :  * lookup_inum_mapping - add an inode mapping for link counting.
    1682             :  * @dev: source device on which source inode number resides
    1683             :  * @inum: source inode number
    1684             :  */
    1685       13440 : static struct inum_mapping *lookup_inum_mapping(dev_t dev, ino_t inum)
    1686             : {
    1687             :         struct inum_mapping *im;
    1688             :         unsigned int k;
    1689             : 
    1690       13440 :         k = inum % HASH_TABLE_SIZE;
    1691       13440 :         im = hash_table[k];
    1692       26880 :         while (im) {
    1693        7040 :                 if (im->dev == dev && im->inum == inum)
    1694             :                         return im;
    1695           0 :                 im = im->next;
    1696             :         }
    1697        6400 :         im = xmalloc(sizeof(struct inum_mapping));
    1698        6400 :         im->next = hash_table[k];
    1699        6400 :         im->prev = NULL;
    1700        6400 :         im->dev = dev;
    1701        6400 :         im->inum = inum;
    1702        6400 :         im->use_inum = 0;
    1703        6400 :         im->use_nlink = 0;
    1704        6400 :         if (hash_table[k])
    1705           0 :                 hash_table[k]->prev = im;
    1706        6400 :         hash_table[k] = im;
    1707        6400 :         return im;
    1708             : }
    1709             : 
    1710             : /**
    1711             :  * all_zero - does a buffer contain only zero bytes.
    1712             :  * @buf: buffer
    1713             :  * @len: buffer length
    1714             :  */
    1715             : static int all_zero(void *buf, int len)
    1716             : {
    1717    13729920 :         unsigned char *p = buf;
    1718             : 
    1719 51470032640 :         while (len--)
    1720 51457488000 :                 if (*p++ != 0)
    1721             :                         return 0;
    1722             :         return 1;
    1723             : }
    1724             : 
    1725             : /**
    1726             :  * add_file - write the data of a file and its inode to the output file.
    1727             :  * @path_name: source path name
    1728             :  * @st: source inode stat information
    1729             :  * @inum: target inode number
    1730             :  * @flags: source inode flags
    1731             :  */
    1732       23040 : static int add_file(const char *path_name, struct stat *st, ino_t inum,
    1733             :                     int flags, struct fscrypt_context *fctx)
    1734             : {
    1735       23040 :         struct ubifs_data_node *dn = node_buf;
    1736       23040 :         void *buf = block_buf;
    1737       23040 :         loff_t file_size = 0;
    1738             :         ssize_t ret, bytes_read;
    1739             :         union ubifs_key key;
    1740             :         int fd, dn_len, err, compr_type, use_compr;
    1741       23040 :         unsigned int block_no = 0;
    1742             :         size_t out_len;
    1743             : 
    1744       23040 :         fd = open(path_name, O_RDONLY | O_LARGEFILE);
    1745       23040 :         if (fd == -1)
    1746           0 :                 return sys_errmsg("failed to open file '%s'", path_name);
    1747             :         do {
    1748             :                 /* Read next block */
    1749    13739520 :                 bytes_read = 0;
    1750             :                 do {
    1751    13756160 :                         ret = read(fd, buf + bytes_read,
    1752    13756160 :                                    UBIFS_BLOCK_SIZE - bytes_read);
    1753    13756160 :                         if (ret == -1) {
    1754           0 :                                 sys_errmsg("failed to read file '%s'",
    1755             :                                             path_name);
    1756           0 :                                 close(fd);
    1757           0 :                                 return 1;
    1758             :                         }
    1759    13756160 :                         bytes_read += ret;
    1760    13756160 :                 } while (ret != 0 && bytes_read != UBIFS_BLOCK_SIZE);
    1761    13739520 :                 if (bytes_read == 0)
    1762             :                         break;
    1763    13729920 :                 file_size += bytes_read;
    1764             :                 /* Skip holes */
    1765    27459840 :                 if (all_zero(buf, bytes_read)) {
    1766    12544640 :                         block_no += 1;
    1767    12544640 :                         continue;
    1768             :                 }
    1769             :                 /* Make data node */
    1770     1185280 :                 memset(dn, 0, UBIFS_DATA_NODE_SZ);
    1771     2370560 :                 data_key_init(c, &key, inum, block_no);
    1772     1185280 :                 dn->ch.node_type = UBIFS_DATA_NODE;
    1773     2370560 :                 key_write(c, &key, &dn->key);
    1774     1185280 :                 out_len = NODE_BUFFER_SIZE - UBIFS_DATA_NODE_SZ;
    1775     1777920 :                 if (c->default_compr == UBIFS_COMPR_NONE &&
    1776      592640 :                     !c->encrypted && (flags & FS_COMPR_FL))
    1777             : #ifdef WITH_LZO
    1778             :                         use_compr = UBIFS_COMPR_LZO;
    1779             : #elif defined(WITH_ZLIB)
    1780             :                         use_compr = UBIFS_COMPR_ZLIB;
    1781             : #else
    1782             :                         use_compr = UBIFS_COMPR_NONE;
    1783             : #endif
    1784             :                 else
    1785     1185280 :                         use_compr = c->default_compr;
    1786     1185280 :                 compr_type = compress_data(buf, bytes_read, &dn->data,
    1787             :                                            &out_len, use_compr);
    1788     1185280 :                 dn->compr_type = cpu_to_le16(compr_type);
    1789     1185280 :                 dn->size = cpu_to_le32(bytes_read);
    1790             : 
    1791     1185280 :                 if (!fctx) {
    1792      883840 :                         dn->compr_size = 0;
    1793             :                 } else {
    1794      301440 :                         ret = encrypt_data_node(fctx, block_no, dn, out_len);
    1795      301440 :                         if (ret < 0) {
    1796           0 :                                 close(fd);
    1797           0 :                                 return ret;
    1798             :                         }
    1799      301440 :                         out_len = ret;
    1800             :                 }
    1801             : 
    1802     1185280 :                 dn_len = UBIFS_DATA_NODE_SZ + out_len;
    1803             :                 /* Add data node to file system */
    1804     1185280 :                 err = add_node(&key, NULL, 0, dn, dn_len);
    1805     1185280 :                 if (err) {
    1806           0 :                         close(fd);
    1807           0 :                         return err;
    1808             :                 }
    1809             : 
    1810     1185280 :                 block_no++;
    1811    13729920 :         } while (ret != 0);
    1812             : 
    1813       23040 :         if (close(fd) == -1)
    1814           0 :                 return sys_errmsg("failed to close file '%s'", path_name);
    1815       23040 :         if (file_size != st->st_size)
    1816           0 :                 return errmsg("file size changed during writing file '%s'",
    1817             :                                path_name);
    1818             : 
    1819       23040 :         return add_inode(st, inum, NULL, 0, flags, path_name, fctx);
    1820             : }
    1821             : 
    1822             : /**
    1823             :  * add_non_dir - write a non-directory to the output file.
    1824             :  * @path_name: source path name
    1825             :  * @inum: target inode number is passed and returned here (due to link counting)
    1826             :  * @nlink: number of links if known otherwise zero
    1827             :  * @type: UBIFS inode type is returned here
    1828             :  * @st: struct stat object containing inode attributes which should be use when
    1829             :  *      creating the UBIFS inode
    1830             :  */
    1831       82560 : static int add_non_dir(const char *path_name, ino_t *inum, unsigned int nlink,
    1832             :                        unsigned char *type, struct stat *st,
    1833             :                        struct fscrypt_context *fctx)
    1834             : {
    1835       82560 :         int fd, flags = 0;
    1836             : 
    1837       82560 :         pr_debug("%s\n", path_name);
    1838             : 
    1839       82560 :         if (S_ISREG(st->st_mode)) {
    1840       29440 :                 fd = open(path_name, O_RDONLY);
    1841       29440 :                 if (fd == -1)
    1842           0 :                         return sys_errmsg("failed to open file '%s'",
    1843             :                                            path_name);
    1844       29440 :                 if (ioctl(fd, FS_IOC_GETFLAGS, &flags) == -1)
    1845           0 :                         flags = 0;
    1846       29440 :                 if (close(fd) == -1)
    1847           0 :                         return sys_errmsg("failed to close file '%s'",
    1848             :                                            path_name);
    1849       29440 :                 *type = UBIFS_ITYPE_REG;
    1850       53120 :         } else if (S_ISCHR(st->st_mode))
    1851       40960 :                 *type = UBIFS_ITYPE_CHR;
    1852       12160 :         else if (S_ISBLK(st->st_mode))
    1853           0 :                 *type = UBIFS_ITYPE_BLK;
    1854       12160 :         else if (S_ISLNK(st->st_mode))
    1855       12160 :                 *type = UBIFS_ITYPE_LNK;
    1856           0 :         else if (S_ISSOCK(st->st_mode))
    1857           0 :                 *type = UBIFS_ITYPE_SOCK;
    1858           0 :         else if (S_ISFIFO(st->st_mode))
    1859           0 :                 *type = UBIFS_ITYPE_FIFO;
    1860             :         else
    1861           0 :                 return errmsg("file '%s' has unknown inode type", path_name);
    1862             : 
    1863       82560 :         if (nlink)
    1864        6400 :                 st->st_nlink = nlink;
    1865       76160 :         else if (st->st_nlink > 1) {
    1866             :                 /*
    1867             :                  * If the number of links is greater than 1, then add this file
    1868             :                  * later when we know the number of links that we actually have.
    1869             :                  * For now, we just put the inode mapping in the hash table.
    1870             :                  */
    1871             :                 struct inum_mapping *im;
    1872             : 
    1873       13440 :                 im = lookup_inum_mapping(st->st_dev, st->st_ino);
    1874       13440 :                 if (!im)
    1875           0 :                         return errmsg("out of memory");
    1876       13440 :                 if (im->use_nlink == 0) {
    1877             :                         /* New entry */
    1878        6400 :                         im->use_inum = *inum;
    1879        6400 :                         im->use_nlink = 1;
    1880        6400 :                         im->path_name = xmalloc(strlen(path_name) + 1);
    1881        6400 :                         strcpy(im->path_name, path_name);
    1882             :                 } else {
    1883             :                         /* Existing entry */
    1884        7040 :                         *inum = im->use_inum;
    1885        7040 :                         im->use_nlink += 1;
    1886             :                         /* Return unused inode number */
    1887        7040 :                         c->highest_inum -= 1;
    1888             :                 }
    1889             : 
    1890       13440 :                 memcpy(&im->st, st, sizeof(struct stat));
    1891       13440 :                 return 0;
    1892             :         } else
    1893       62720 :                 st->st_nlink = 1;
    1894             : 
    1895       69120 :         creat_sqnum = ++c->max_sqnum;
    1896             : 
    1897       69120 :         if (S_ISREG(st->st_mode))
    1898       23040 :                 return add_file(path_name, st, *inum, flags, fctx);
    1899       46080 :         if (S_ISCHR(st->st_mode))
    1900       37120 :                 return add_dev_inode(path_name, st, *inum, flags);
    1901        8960 :         if (S_ISBLK(st->st_mode))
    1902           0 :                 return add_dev_inode(path_name, st, *inum, flags);
    1903        8960 :         if (S_ISLNK(st->st_mode))
    1904        8960 :                 return add_symlink_inode(path_name, st, *inum, flags, fctx);
    1905           0 :         if (S_ISSOCK(st->st_mode))
    1906           0 :                 return add_inode(st, *inum, NULL, 0, flags, NULL, NULL);
    1907           0 :         if (S_ISFIFO(st->st_mode))
    1908           0 :                 return add_inode(st, *inum, NULL, 0, flags, NULL, NULL);
    1909             : 
    1910           0 :         return errmsg("file '%s' has unknown inode type", path_name);
    1911             : }
    1912             : 
    1913             : /**
    1914             :  * add_directory - write a directory tree to the output file.
    1915             :  * @dir_name: directory path name
    1916             :  * @dir_inum: UBIFS inode number of directory
    1917             :  * @st: directory inode statistics
    1918             :  * @existing: zero if this function is called for a directory which
    1919             :  *            does not exist on the host file-system and it is being
    1920             :  *            created because it is defined in the device table file.
    1921             :  */
    1922       16640 : static int add_directory(const char *dir_name, ino_t dir_inum, struct stat *st,
    1923             :                          int existing, struct fscrypt_context *fctx)
    1924             : {
    1925             :         struct dirent *entry;
    1926       16640 :         DIR *dir = NULL;
    1927       16640 :         int kname_len, err = 0;
    1928       16640 :         loff_t size = UBIFS_INO_NODE_SZ;
    1929       16640 :         char *name = NULL;
    1930       16640 :         unsigned int nlink = 2;
    1931             :         struct path_htbl_element *ph_elt;
    1932       16640 :         struct name_htbl_element *nh_elt = NULL;
    1933       16640 :         struct hashtable_itr *itr = NULL;
    1934             :         ino_t inum;
    1935             :         unsigned char type;
    1936       16640 :         unsigned long long dir_creat_sqnum = ++c->max_sqnum;
    1937             : 
    1938       16640 :         pr_debug("%s\n", dir_name);
    1939       16640 :         if (existing) {
    1940       16640 :                 dir = opendir(dir_name);
    1941       16640 :                 if (dir == NULL)
    1942           0 :                         return sys_errmsg("cannot open directory '%s'",
    1943             :                                            dir_name);
    1944             :         }
    1945             : 
    1946             :         /*
    1947             :          * Check whether this directory contains files which should be
    1948             :          * added/changed because they were specified in the device table.
    1949             :          * @ph_elt will be non-zero if yes.
    1950             :          */
    1951       16640 :         ph_elt = devtbl_find_path(dir_name + root_len - 1);
    1952             : 
    1953             :         /*
    1954             :          * Before adding the directory itself, we have to iterate over all the
    1955             :          * entries the device table adds to this directory and create them.
    1956             :          */
    1957      158720 :         for (; existing;) {
    1958             :                 struct stat dent_st;
    1959      142080 :                 struct fscrypt_context *new_fctx = NULL;
    1960             : 
    1961      142080 :                 errno = 0;
    1962      142080 :                 entry = readdir(dir);
    1963      142080 :                 if (!entry) {
    1964       16640 :                         if (errno == 0)
    1965             :                                 break;
    1966           0 :                         sys_errmsg("error reading directory '%s'", dir_name);
    1967           0 :                         goto out_free;
    1968             :                 }
    1969             : 
    1970      125440 :                 if (strcmp(".", entry->d_name) == 0)
    1971       49920 :                         continue;
    1972      108800 :                 if (strcmp("..", entry->d_name) == 0)
    1973       16640 :                         continue;
    1974             : 
    1975       92160 :                 if (ph_elt)
    1976             :                         /*
    1977             :                          * This directory was referred to at the device table
    1978             :                          * file. Check if this directory entry is referred at
    1979             :                          * too.
    1980             :                          */
    1981           0 :                         nh_elt = devtbl_find_name(ph_elt, entry->d_name);
    1982             : 
    1983             :                 /*
    1984             :                  * We are going to create the file corresponding to this
    1985             :                  * directory entry (@entry->d_name). We use 'struct stat'
    1986             :                  * object to pass information about file attributes (actually
    1987             :                  * only about UID, GID, mode, major, and minor). Get attributes
    1988             :                  * for this file from the UBIFS rootfs on the host.
    1989             :                  */
    1990       92160 :                 free(name);
    1991       92160 :                 name = make_path(dir_name, entry->d_name);
    1992       92160 :                 if (lstat(name, &dent_st) == -1) {
    1993           0 :                         sys_errmsg("lstat failed for file '%s'", name);
    1994           0 :                         goto out_free;
    1995             :                 }
    1996             : 
    1997       92160 :                 if (squash_owner)
    1998             :                         /*
    1999             :                          * Squash UID/GID. But the device table may override
    2000             :                          * this.
    2001             :                          */
    2002           0 :                         dent_st.st_uid = dent_st.st_gid = 0;
    2003             : 
    2004             :                 /*
    2005             :                  * And if the device table describes the same file, override
    2006             :                  * the attributes. However, this is not allowed for device node
    2007             :                  * files.
    2008             :                  */
    2009       92160 :                 if (nh_elt && override_attributes(&dent_st, ph_elt, nh_elt))
    2010             :                         goto out_free;
    2011             : 
    2012       92160 :                 inum = ++c->highest_inum;
    2013             : 
    2014       92160 :                 if (fctx)
    2015       46080 :                         new_fctx = inherit_fscrypt_context(fctx);
    2016             : 
    2017       92160 :                 if (S_ISDIR(dent_st.st_mode)) {
    2018       16000 :                         err = add_directory(name, inum, &dent_st, 1, new_fctx);
    2019       16000 :                         if (err) {
    2020           0 :                                 free_fscrypt_context(new_fctx);
    2021           0 :                                 goto out_free;
    2022             :                         }
    2023       16000 :                         nlink += 1;
    2024       16000 :                         type = UBIFS_ITYPE_DIR;
    2025             :                 } else {
    2026       76160 :                         err = add_non_dir(name, &inum, 0, &type,
    2027             :                                           &dent_st, new_fctx);
    2028       76160 :                         if (err) {
    2029           0 :                                 free_fscrypt_context(new_fctx);
    2030           0 :                                 goto out_free;
    2031             :                         }
    2032             :                 }
    2033             : 
    2034       92160 :                 err = create_inum_attr(inum, name);
    2035       92160 :                 if (err) {
    2036           0 :                         free_fscrypt_context(new_fctx);
    2037           0 :                         goto out_free;
    2038             :                 }
    2039             : 
    2040       92160 :                 err = add_dent_node(dir_inum, entry->d_name, inum, type, fctx,
    2041             :                                     &kname_len);
    2042       92160 :                 if (err) {
    2043           0 :                         free_fscrypt_context(new_fctx);
    2044           0 :                         goto out_free;
    2045             :                 }
    2046       92160 :                 size += ALIGN(UBIFS_DENT_NODE_SZ + kname_len + 1, 8);
    2047             : 
    2048       92160 :                 if (new_fctx)
    2049       46080 :                         free_fscrypt_context(new_fctx);
    2050             :         }
    2051             : 
    2052             :         /*
    2053             :          * OK, we have created all files in this directory (recursively), let's
    2054             :          * also create all files described in the device table. All t
    2055             :          */
    2056       16640 :         nh_elt = first_name_htbl_element(ph_elt, &itr);
    2057       16640 :         while (nh_elt) {
    2058             :                 struct stat fake_st;
    2059           0 :                 struct fscrypt_context *new_fctx = NULL;
    2060             : 
    2061             :                 /*
    2062             :                  * We prohibit creating regular files using the device table,
    2063             :                  * the device table may only re-define attributes of regular
    2064             :                  * files.
    2065             :                  */
    2066           0 :                 if (S_ISREG(nh_elt->mode)) {
    2067           0 :                         errmsg("Bad device table entry %s/%s - it is "
    2068             :                                 "prohibited to create regular files "
    2069             :                                 "via device table",
    2070             :                                 strcmp(ph_elt->path, "/") ? ph_elt->path : "",
    2071             :                                 nh_elt->name);
    2072           0 :                         goto out_free;
    2073             :                 }
    2074             : 
    2075           0 :                 memcpy(&fake_st, &root_st, sizeof(struct stat));
    2076           0 :                 fake_st.st_uid  = nh_elt->uid;
    2077           0 :                 fake_st.st_gid  = nh_elt->gid;
    2078           0 :                 fake_st.st_mode = nh_elt->mode;
    2079           0 :                 fake_st.st_rdev = nh_elt->dev;
    2080           0 :                 fake_st.st_nlink = 1;
    2081             : 
    2082           0 :                 free(name);
    2083           0 :                 name = make_path(dir_name, nh_elt->name);
    2084           0 :                 inum = ++c->highest_inum;
    2085             : 
    2086           0 :                 new_fctx = inherit_fscrypt_context(fctx);
    2087             : 
    2088           0 :                 if (S_ISDIR(nh_elt->mode)) {
    2089           0 :                         err = add_directory(name, inum, &fake_st, 0, new_fctx);
    2090           0 :                         if (err) {
    2091           0 :                                 free_fscrypt_context(new_fctx);
    2092           0 :                                 goto out_free;
    2093             :                         }
    2094           0 :                         nlink += 1;
    2095           0 :                         type = UBIFS_ITYPE_DIR;
    2096             :                 } else {
    2097           0 :                         err = add_non_dir(name, &inum, 0, &type,
    2098             :                                           &fake_st, new_fctx);
    2099           0 :                         if (err) {
    2100           0 :                                 free_fscrypt_context(new_fctx);
    2101           0 :                                 goto out_free;
    2102             :                         }
    2103             :                 }
    2104             : 
    2105           0 :                 err = create_inum_attr(inum, name);
    2106           0 :                 if (err) {
    2107           0 :                         free_fscrypt_context(new_fctx);
    2108           0 :                         goto out_free;
    2109             :                 }
    2110             : 
    2111           0 :                 err = add_dent_node(dir_inum, nh_elt->name, inum, type, fctx,
    2112             :                                     &kname_len);
    2113           0 :                 if (err) {
    2114           0 :                         free_fscrypt_context(new_fctx);
    2115           0 :                         goto out_free;
    2116             :                 }
    2117             : 
    2118           0 :                 size += ALIGN(UBIFS_DENT_NODE_SZ + kname_len + 1, 8);
    2119             : 
    2120           0 :                 nh_elt = next_name_htbl_element(ph_elt, &itr);
    2121           0 :                 if (new_fctx)
    2122           0 :                         free_fscrypt_context(new_fctx);
    2123             :         }
    2124             : 
    2125       16640 :         creat_sqnum = dir_creat_sqnum;
    2126             : 
    2127       16640 :         err = add_dir_inode(dir ? dir_name : NULL, dir, dir_inum, size,
    2128             :                             nlink, st, fctx);
    2129       16640 :         if (err)
    2130             :                 goto out_free;
    2131             : 
    2132       16640 :         free(name);
    2133       16640 :         if (existing && closedir(dir) == -1)
    2134           0 :                 return sys_errmsg("error closing directory '%s'", dir_name);
    2135             : 
    2136             :         return 0;
    2137             : 
    2138           0 : out_free:
    2139           0 :         free(itr);
    2140           0 :         free(name);
    2141           0 :         if (existing)
    2142           0 :                 closedir(dir);
    2143             :         return -1;
    2144             : }
    2145             : 
    2146             : /**
    2147             :  * add_multi_linked_files - write all the files for which we counted links.
    2148             :  */
    2149         640 : static int add_multi_linked_files(void)
    2150             : {
    2151             :         int i, err;
    2152             : 
    2153     6464000 :         for (i = 0; i < HASH_TABLE_SIZE; i++) {
    2154             :                 struct inum_mapping *im;
    2155     6463360 :                 unsigned char type = 0;
    2156             : 
    2157     6469760 :                 for (im = hash_table[i]; im; im = im->next) {
    2158        6400 :                         pr_debug("%s\n", im->path_name);
    2159        6400 :                         err = add_non_dir(im->path_name, &im->use_inum,
    2160             :                                           im->use_nlink, &type, &im->st, NULL);
    2161        6400 :                         if (err)
    2162           0 :                                 return err;
    2163             :                 }
    2164             :         }
    2165             :         return 0;
    2166             : }
    2167             : 
    2168             : /**
    2169             :  * write_data - write the files and directories.
    2170             :  */
    2171         640 : static int write_data(void)
    2172             : {
    2173             :         int err;
    2174         640 :         mode_t mode = S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
    2175             :         struct path_htbl_element *ph_elt;
    2176             :         struct name_htbl_element *nh_elt;
    2177             : 
    2178         640 :         if (root) {
    2179        1280 :                 err = stat(root, &root_st);
    2180         640 :                 if (err)
    2181           0 :                         return sys_errmsg("bad root file-system directory '%s'",
    2182             :                                            root);
    2183         640 :                 if (squash_owner)
    2184           0 :                         root_st.st_uid = root_st.st_gid = 0;
    2185             :         } else {
    2186           0 :                 root_st.st_mtime = time(NULL);
    2187           0 :                 root_st.st_atime = root_st.st_ctime = root_st.st_mtime;
    2188           0 :                 root_st.st_mode = mode;
    2189             :         }
    2190             : 
    2191             :         /*
    2192             :          * Check for root entry and update permissions if it exists. This will
    2193             :          * also remove the entry from the device table list.
    2194             :          */
    2195         640 :         ph_elt = devtbl_find_path("/");
    2196         640 :         if (ph_elt) {
    2197           0 :                 nh_elt = devtbl_find_name(ph_elt, "");
    2198           0 :                 if (nh_elt && override_attributes(&root_st, ph_elt, nh_elt))
    2199             :                         return -1;
    2200             :         }
    2201             : 
    2202         640 :         head_flags = 0;
    2203             : 
    2204         640 :         err = create_inum_attr(UBIFS_ROOT_INO, root);
    2205         640 :         if (err)
    2206             :                 return err;
    2207             : 
    2208         640 :         err = add_directory(root, UBIFS_ROOT_INO, &root_st, !!root, root_fctx);
    2209         640 :         if (err)
    2210             :                 return err;
    2211         640 :         err = add_multi_linked_files();
    2212         640 :         if (err)
    2213             :                 return err;
    2214         640 :         return flush_nodes();
    2215             : }
    2216             : 
    2217             : static int namecmp(const struct idx_entry *e1, const struct idx_entry *e2)
    2218             : {
    2219           0 :         size_t len1 = e1->name_len, len2 = e2->name_len;
    2220           0 :         size_t clen = (len1 < len2) ? len1 : len2;
    2221             :         int cmp;
    2222             : 
    2223           0 :         cmp = memcmp(e1->name, e2->name, clen);
    2224           0 :         if (cmp)
    2225             :                 return cmp;
    2226           0 :         return (len1 < len2) ? -1 : 1;
    2227             : }
    2228             : 
    2229     9761436 : static int cmp_idx(const void *a, const void *b)
    2230             : {
    2231     9761436 :         const struct idx_entry *e1 = *(const struct idx_entry **)a;
    2232     9761436 :         const struct idx_entry *e2 = *(const struct idx_entry **)b;
    2233             :         int cmp;
    2234             : 
    2235     9761436 :         cmp = keys_cmp(c, &e1->key, &e2->key);
    2236             :         if (cmp)
    2237             :                 return cmp;
    2238           0 :         return namecmp(e1, e2);
    2239             : }
    2240             : 
    2241             : /**
    2242             :  * add_idx_node - write an index node to the head.
    2243             :  * @node: index node
    2244             :  * @child_cnt: number of children of this index node
    2245             :  */
    2246      477760 : static int add_idx_node(void *node, int child_cnt)
    2247             : {
    2248             :         int err, lnum, offs, len;
    2249             : 
    2250      955520 :         len = ubifs_idx_node_sz(c, child_cnt);
    2251             : 
    2252      477760 :         ubifs_prepare_node(c, node, len, 0);
    2253             : 
    2254      477760 :         err = reserve_space(len, &lnum, &offs);
    2255      477760 :         if (err)
    2256             :                 return err;
    2257             : 
    2258      477760 :         memcpy(leb_buf + offs, node, len);
    2259      477760 :         memset(leb_buf + offs + len, 0xff, ALIGN(len, 8) - len);
    2260             : 
    2261      477760 :         c->bi.old_idx_sz += ALIGN(len, 8);
    2262             : 
    2263      477760 :         pr_debug("at %d:%d len %d index size %llu\n", lnum, offs, len,
    2264             :                  c->bi.old_idx_sz);
    2265             : 
    2266             :         /* The last index node written will be the root */
    2267      477760 :         c->zroot.lnum = lnum;
    2268      477760 :         c->zroot.offs = offs;
    2269      477760 :         c->zroot.len = len;
    2270             : 
    2271      477760 :         return 0;
    2272             : }
    2273             : 
    2274             : /**
    2275             :  * write_index - write out the index.
    2276             :  */
    2277         640 : static int write_index(void)
    2278             : {
    2279             :         size_t sz, i, cnt, idx_sz, pstep, bcnt;
    2280             :         struct idx_entry **idx_ptr, **p;
    2281             :         struct ubifs_idx_node *idx;
    2282             :         struct ubifs_branch *br;
    2283         640 :         int child_cnt = 0, j, level, blnum, boffs, blen, blast_len, err;
    2284             :         uint8_t *hashes;
    2285             : 
    2286         640 :         pr_debug("leaf node count: %zd\n", idx_cnt);
    2287             : 
    2288             :         /* Reset the head for the index */
    2289         640 :         head_flags = LPROPS_INDEX;
    2290             :         /* Allocate index node */
    2291        1280 :         idx_sz = ubifs_idx_node_sz(c, c->fanout);
    2292         640 :         idx = xmalloc(idx_sz);
    2293             :         /* Make an array of pointers to sort the index list */
    2294         640 :         sz = idx_cnt * sizeof(struct idx_entry *);
    2295         640 :         if (sz / sizeof(struct idx_entry *) != idx_cnt) {
    2296           0 :                 free(idx);
    2297           0 :                 return errmsg("index is too big (%zu entries)", idx_cnt);
    2298             :         }
    2299         640 :         idx_ptr = xmalloc(sz);
    2300         640 :         idx_ptr[0] = idx_list_first;
    2301     1429120 :         for (i = 1; i < idx_cnt; i++)
    2302     1428480 :                 idx_ptr[i] = idx_ptr[i - 1]->next;
    2303         640 :         qsort(idx_ptr, idx_cnt, sizeof(struct idx_entry *), cmp_idx);
    2304             :         /* Write level 0 index nodes */
    2305         640 :         cnt = idx_cnt / c->fanout;
    2306         640 :         if (idx_cnt % c->fanout)
    2307         320 :                 cnt += 1;
    2308             : 
    2309         640 :         hashes = xmalloc(c->hash_len * cnt);
    2310             : 
    2311         640 :         p = idx_ptr;
    2312         640 :         blnum = head_lnum;
    2313         640 :         boffs = head_offs;
    2314      358080 :         for (i = 0; i < cnt; i++) {
    2315             :                 /*
    2316             :                  * Calculate the child count. All index nodes are created full
    2317             :                  * except for the last index node on each row.
    2318             :                  */
    2319      357440 :                 if (i == cnt - 1) {
    2320         640 :                         child_cnt = idx_cnt % c->fanout;
    2321         640 :                         if (child_cnt == 0)
    2322         320 :                                 child_cnt = c->fanout;
    2323             :                 } else
    2324      356800 :                         child_cnt = c->fanout;
    2325      357440 :                 memset(idx, 0, idx_sz);
    2326      357440 :                 idx->ch.node_type = UBIFS_IDX_NODE;
    2327      357440 :                 idx->child_cnt = cpu_to_le16(child_cnt);
    2328      357440 :                 idx->level = cpu_to_le16(0);
    2329     1786560 :                 for (j = 0; j < child_cnt; j++, p++) {
    2330     2858240 :                         br = ubifs_idx_branch(c, idx, j);
    2331     2858240 :                         key_write_idx(c, &(*p)->key, &br->key);
    2332     1429120 :                         br->lnum = cpu_to_le32((*p)->lnum);
    2333     1429120 :                         br->offs = cpu_to_le32((*p)->offs);
    2334     1429120 :                         br->len = cpu_to_le32((*p)->len);
    2335     2858240 :                         memcpy(ubifs_branch_hash(c, br), (*p)->hash, c->hash_len);
    2336             :                 }
    2337      357440 :                 add_idx_node(idx, child_cnt);
    2338             : 
    2339      714880 :                 ubifs_node_calc_hash(c, idx, hashes + i * c->hash_len);
    2340             :         }
    2341             :         /* Write level 1 index nodes and above */
    2342             :         level = 0;
    2343             :         pstep = 1;
    2344        3840 :         while (cnt > 1) {
    2345             :                 /*
    2346             :                  * 'blast_len' is the length of the last index node in the level
    2347             :                  * below.
    2348             :                  */
    2349        6400 :                 blast_len = ubifs_idx_node_sz(c, child_cnt);
    2350             :                 /* 'bcnt' is the number of index nodes in the level below */
    2351        3200 :                 bcnt = cnt;
    2352             :                 /* 'cnt' is the number of index nodes in this level */
    2353        3200 :                 cnt = (cnt + c->fanout - 1) / c->fanout;
    2354        3200 :                 if (cnt == 0)
    2355           0 :                         cnt = 1;
    2356        3200 :                 level += 1;
    2357             :                 /*
    2358             :                  * The key of an index node is the same as the key of its first
    2359             :                  * child. Thus we can get the key by stepping along the bottom
    2360             :                  * level 'p' with an increasing large step 'pstep'.
    2361             :                  */
    2362        3200 :                 p = idx_ptr;
    2363        3200 :                 pstep *= c->fanout;
    2364      123520 :                 for (i = 0; i < cnt; i++) {
    2365             :                         /*
    2366             :                          * Calculate the child count. All index nodes are
    2367             :                          * created full except for the last index node on each
    2368             :                          * row.
    2369             :                          */
    2370      120320 :                         if (i == cnt - 1) {
    2371        3200 :                                 child_cnt = bcnt % c->fanout;
    2372        3200 :                                 if (child_cnt == 0)
    2373        1280 :                                         child_cnt = c->fanout;
    2374             :                         } else
    2375      117120 :                                 child_cnt = c->fanout;
    2376      120320 :                         memset(idx, 0, idx_sz);
    2377      120320 :                         idx->ch.node_type = UBIFS_IDX_NODE;
    2378      120320 :                         idx->child_cnt = cpu_to_le16(child_cnt);
    2379      120320 :                         idx->level = cpu_to_le16(level);
    2380      597440 :                         for (j = 0; j < child_cnt; j++) {
    2381      477120 :                                 size_t bn = i * c->fanout + j;
    2382             : 
    2383             :                                 /*
    2384             :                                  * The length of the index node in the level
    2385             :                                  * below is 'idx_sz' except when it is the last
    2386             :                                  * node on the row. i.e. all the others on the
    2387             :                                  * row are full.
    2388             :                                  */
    2389      477120 :                                 if (bn == bcnt - 1)
    2390        3200 :                                         blen = blast_len;
    2391             :                                 else
    2392             :                                         blen = idx_sz;
    2393             :                                 /*
    2394             :                                  * 'blnum' and 'boffs' hold the position of the
    2395             :                                  * index node on the level below.
    2396             :                                  */
    2397      477120 :                                 if (boffs + blen > c->leb_size) {
    2398         160 :                                         blnum += 1;
    2399         160 :                                         boffs = 0;
    2400             :                                 }
    2401             :                                 /*
    2402             :                                  * Fill in the branch with the key and position
    2403             :                                  * of the index node from the level below.
    2404             :                                  */
    2405      954240 :                                 br = ubifs_idx_branch(c, idx, j);
    2406      954240 :                                 key_write_idx(c, &(*p)->key, &br->key);
    2407      477120 :                                 br->lnum = cpu_to_le32(blnum);
    2408      477120 :                                 br->offs = cpu_to_le32(boffs);
    2409      477120 :                                 br->len = cpu_to_le32(blen);
    2410             :                                 /*
    2411             :                                  * Step to the next index node on the level
    2412             :                                  * below.
    2413             :                                  */
    2414      477120 :                                 boffs += ALIGN(blen, 8);
    2415      477120 :                                 p += pstep;
    2416             : 
    2417     1431360 :                                 memcpy(ubifs_branch_hash(c, br),
    2418      477120 :                                        hashes + bn * c->hash_len,
    2419      477120 :                                        c->hash_len);
    2420             :                         }
    2421      120320 :                         add_idx_node(idx, child_cnt);
    2422      240640 :                         ubifs_node_calc_hash(c, idx, hashes + i * c->hash_len);
    2423             :                 }
    2424             :         }
    2425             : 
    2426         640 :         memcpy(c->root_idx_hash, hashes, c->hash_len);
    2427             : 
    2428             :         /* Free stuff */
    2429     1429760 :         for (i = 0; i < idx_cnt; i++) {
    2430     1429120 :                 free(idx_ptr[i]->name);
    2431     1429120 :                 free(idx_ptr[i]);
    2432             :         }
    2433         640 :         free(idx_ptr);
    2434         640 :         free(idx);
    2435             : 
    2436         640 :         pr_debug("zroot is at %d:%d len %d\n", c->zroot.lnum, c->zroot.offs,
    2437             :                  c->zroot.len);
    2438             : 
    2439             :         /* Set the index head */
    2440         640 :         c->ihead_lnum = head_lnum;
    2441         640 :         c->ihead_offs = ALIGN(head_offs, c->min_io_size);
    2442         640 :         pr_debug("ihead is at %d:%d\n", c->ihead_lnum, c->ihead_offs);
    2443             : 
    2444             :         /* Flush the last index LEB */
    2445         640 :         err = flush_nodes();
    2446         640 :         if (err)
    2447             :                 return err;
    2448             : 
    2449         640 :         return 0;
    2450             : }
    2451             : 
    2452             : /**
    2453             :  * set_gc_lnum - set the LEB number reserved for the garbage collector.
    2454             :  */
    2455         640 : static int set_gc_lnum(void)
    2456             : {
    2457             :         int err;
    2458             : 
    2459         640 :         c->gc_lnum = head_lnum++;
    2460         640 :         err = write_empty_leb(c->gc_lnum);
    2461         640 :         if (err)
    2462             :                 return err;
    2463         640 :         set_lprops(c->gc_lnum, 0, 0);
    2464         640 :         c->lst.empty_lebs += 1;
    2465         640 :         return 0;
    2466             : }
    2467             : 
    2468             : /**
    2469             :  * finalize_leb_cnt - now that we know how many LEBs we used.
    2470             :  */
    2471         640 : static int finalize_leb_cnt(void)
    2472             : {
    2473         640 :         c->leb_cnt = head_lnum;
    2474         640 :         if (c->leb_cnt > c->max_leb_cnt)
    2475           0 :                 return errmsg("max_leb_cnt too low (%d needed)", c->leb_cnt);
    2476         640 :         c->main_lebs = c->leb_cnt - c->main_first;
    2477         640 :         if (verbose) {
    2478           0 :                 printf("\tsuper lebs:   %d\n", UBIFS_SB_LEBS);
    2479           0 :                 printf("\tmaster lebs:  %d\n", UBIFS_MST_LEBS);
    2480           0 :                 printf("\tlog_lebs:     %d\n", c->log_lebs);
    2481           0 :                 printf("\tlpt_lebs:     %d\n", c->lpt_lebs);
    2482           0 :                 printf("\torph_lebs:    %d\n", c->orph_lebs);
    2483           0 :                 printf("\tmain_lebs:    %d\n", c->main_lebs);
    2484           0 :                 printf("\tgc lebs:      %d\n", 1);
    2485           0 :                 printf("\tindex lebs:   %d\n", c->lst.idx_lebs);
    2486           0 :                 printf("\tleb_cnt:      %d\n", c->leb_cnt);
    2487             :         }
    2488         640 :         pr_debug("total_free:  %llu\n", c->lst.total_free);
    2489         640 :         pr_debug("total_dirty: %llu\n", c->lst.total_dirty);
    2490         640 :         pr_debug("total_used:  %llu\n", c->lst.total_used);
    2491         640 :         pr_debug("total_dead:  %llu\n", c->lst.total_dead);
    2492         640 :         pr_debug("total_dark:  %llu\n", c->lst.total_dark);
    2493         640 :         pr_debug("index size:  %llu\n", c->bi.old_idx_sz);
    2494         640 :         pr_debug("empty_lebs:  %d\n", c->lst.empty_lebs);
    2495             :         return 0;
    2496             : }
    2497             : 
    2498             : static int ubifs_format_version(void)
    2499             : {
    2500         640 :         if (c->double_hash || c->encrypted)
    2501             :                 return 5;
    2502             : 
    2503             :         /* Default */
    2504             :         return 4;
    2505             : }
    2506             : 
    2507             : /**
    2508             :  * write_super - write the super block.
    2509             :  */
    2510         640 : static int write_super(void)
    2511             : {
    2512             :         void *buf;
    2513             :         struct ubifs_sb_node *sup;
    2514             :         struct ubifs_sig_node *sig;
    2515             :         int err, len;
    2516             : 
    2517        1280 :         buf = xzalloc(c->leb_size);
    2518             : 
    2519         640 :         sup = buf;
    2520             : 
    2521         640 :         sup->ch.node_type  = UBIFS_SB_NODE;
    2522         640 :         sup->key_hash      = c->key_hash_type;
    2523         640 :         sup->min_io_size   = cpu_to_le32(c->min_io_size);
    2524         640 :         sup->leb_size      = cpu_to_le32(c->leb_size);
    2525         640 :         sup->leb_cnt       = cpu_to_le32(c->leb_cnt);
    2526         640 :         sup->max_leb_cnt   = cpu_to_le32(c->max_leb_cnt);
    2527         640 :         sup->max_bud_bytes = cpu_to_le64(c->max_bud_bytes);
    2528         640 :         sup->log_lebs      = cpu_to_le32(c->log_lebs);
    2529         640 :         sup->lpt_lebs      = cpu_to_le32(c->lpt_lebs);
    2530         640 :         sup->orph_lebs     = cpu_to_le32(c->orph_lebs);
    2531         640 :         sup->jhead_cnt     = cpu_to_le32(c->jhead_cnt);
    2532         640 :         sup->fanout        = cpu_to_le32(c->fanout);
    2533         640 :         sup->lsave_cnt     = cpu_to_le32(c->lsave_cnt);
    2534         640 :         sup->fmt_version   = cpu_to_le32(ubifs_format_version());
    2535         640 :         sup->default_compr = cpu_to_le16(c->default_compr);
    2536         640 :         sup->rp_size       = cpu_to_le64(c->rp_size);
    2537         640 :         sup->time_gran     = cpu_to_le32(DEFAULT_TIME_GRAN);
    2538         640 :         sup->hash_algo     = cpu_to_le16(c->hash_algo);
    2539         640 :         uuid_generate_random(sup->uuid);
    2540             : 
    2541         640 :         if (verbose) {
    2542             :                 char s[40];
    2543             : 
    2544           0 :                 uuid_unparse_upper(sup->uuid, s);
    2545           0 :                 printf("\tUUID:         %s\n", s);
    2546             :         }
    2547         640 :         if (c->big_lpt)
    2548           0 :                 sup->flags |= cpu_to_le32(UBIFS_FLG_BIGLPT);
    2549         640 :         if (c->space_fixup)
    2550         320 :                 sup->flags |= cpu_to_le32(UBIFS_FLG_SPACE_FIXUP);
    2551         640 :         if (c->double_hash)
    2552         320 :                 sup->flags |= cpu_to_le32(UBIFS_FLG_DOUBLE_HASH);
    2553         640 :         if (c->encrypted)
    2554         320 :                 sup->flags |= cpu_to_le32(UBIFS_FLG_ENCRYPTION);
    2555        1280 :         if (ubifs_authenticated(c)) {
    2556           0 :                 sup->flags |= cpu_to_le32(UBIFS_FLG_AUTHENTICATION);
    2557           0 :                 memcpy(sup->hash_mst, c->mst_hash, c->hash_len);
    2558             :         }
    2559             : 
    2560         640 :         ubifs_prepare_node(c, sup, UBIFS_SB_NODE_SZ, 0);
    2561             : 
    2562         640 :         err = ubifs_sign_superblock_node(c, sup);
    2563         640 :         if (err)
    2564             :                 goto out;
    2565             : 
    2566         640 :         sig = (void *)(sup + 1);
    2567         640 :         ubifs_prepare_node(c, sig, UBIFS_SIG_NODE_SZ + le32_to_cpu(sig->len), 1);
    2568             : 
    2569         640 :         len = ALIGN(ALIGN(UBIFS_SIG_NODE_SZ + le32_to_cpu(sig->len), 8), c->min_io_size);
    2570         640 :         memset(buf + UBIFS_SB_NODE_SZ + len, 0xff, c->leb_size - (UBIFS_SB_NODE_SZ + len));
    2571             : 
    2572         640 :         err = ubifs_leb_change(c, UBIFS_SB_LNUM, buf, c->leb_size);
    2573             :         if (err)
    2574             :                 goto out;
    2575             : 
    2576         640 : out:
    2577         640 :         free(buf);
    2578             : 
    2579         640 :         return err;
    2580             : }
    2581             : 
    2582             : /**
    2583             :  * write_master - write the master node.
    2584             :  */
    2585         640 : static int write_master(void)
    2586             : {
    2587             :         struct ubifs_mst_node mst;
    2588             :         int err;
    2589             : 
    2590         640 :         memset(&mst, 0, UBIFS_MST_NODE_SZ);
    2591             : 
    2592         640 :         mst.ch.node_type = UBIFS_MST_NODE;
    2593         640 :         mst.log_lnum     = cpu_to_le32(UBIFS_LOG_LNUM);
    2594         640 :         mst.highest_inum = cpu_to_le64(c->highest_inum);
    2595         640 :         mst.cmt_no       = cpu_to_le64(0);
    2596         640 :         mst.flags        = cpu_to_le32(UBIFS_MST_NO_ORPHS);
    2597         640 :         mst.root_lnum    = cpu_to_le32(c->zroot.lnum);
    2598         640 :         mst.root_offs    = cpu_to_le32(c->zroot.offs);
    2599         640 :         mst.root_len     = cpu_to_le32(c->zroot.len);
    2600         640 :         mst.gc_lnum      = cpu_to_le32(c->gc_lnum);
    2601         640 :         mst.ihead_lnum   = cpu_to_le32(c->ihead_lnum);
    2602         640 :         mst.ihead_offs   = cpu_to_le32(c->ihead_offs);
    2603         640 :         mst.index_size   = cpu_to_le64(c->bi.old_idx_sz);
    2604         640 :         mst.lpt_lnum     = cpu_to_le32(c->lpt_lnum);
    2605         640 :         mst.lpt_offs     = cpu_to_le32(c->lpt_offs);
    2606         640 :         mst.nhead_lnum   = cpu_to_le32(c->nhead_lnum);
    2607         640 :         mst.nhead_offs   = cpu_to_le32(c->nhead_offs);
    2608         640 :         mst.ltab_lnum    = cpu_to_le32(c->ltab_lnum);
    2609         640 :         mst.ltab_offs    = cpu_to_le32(c->ltab_offs);
    2610         640 :         mst.lsave_lnum   = cpu_to_le32(c->lsave_lnum);
    2611         640 :         mst.lsave_offs   = cpu_to_le32(c->lsave_offs);
    2612         640 :         mst.lscan_lnum   = cpu_to_le32(c->lscan_lnum);
    2613         640 :         mst.empty_lebs   = cpu_to_le32(c->lst.empty_lebs);
    2614         640 :         mst.idx_lebs     = cpu_to_le32(c->lst.idx_lebs);
    2615         640 :         mst.total_free   = cpu_to_le64(c->lst.total_free);
    2616         640 :         mst.total_dirty  = cpu_to_le64(c->lst.total_dirty);
    2617         640 :         mst.total_used   = cpu_to_le64(c->lst.total_used);
    2618         640 :         mst.total_dead   = cpu_to_le64(c->lst.total_dead);
    2619         640 :         mst.total_dark   = cpu_to_le64(c->lst.total_dark);
    2620         640 :         mst.leb_cnt      = cpu_to_le32(c->leb_cnt);
    2621             : 
    2622        1280 :         if (ubifs_authenticated(c)) {
    2623           0 :                 memcpy(mst.hash_root_idx, c->root_idx_hash, c->hash_len);
    2624           0 :                 memcpy(mst.hash_lpt, c->lpt_hash, c->hash_len);
    2625             :         }
    2626             : 
    2627         640 :         err = write_node(&mst, UBIFS_MST_NODE_SZ, UBIFS_MST_LNUM);
    2628         640 :         if (err)
    2629             :                 return err;
    2630             : 
    2631         640 :         err = write_node(&mst, UBIFS_MST_NODE_SZ, UBIFS_MST_LNUM + 1);
    2632         640 :         if (err)
    2633             :                 return err;
    2634             : 
    2635         640 :         err = ubifs_master_node_calc_hash(c, &mst, c->mst_hash);
    2636         640 :         if (err)
    2637             :                 return err;
    2638             : 
    2639         640 :         return 0;
    2640             : }
    2641             : 
    2642             : /**
    2643             :  * write_log - write an empty log.
    2644             :  */
    2645         640 : static int write_log(void)
    2646             : {
    2647             :         struct ubifs_cs_node cs;
    2648             :         int err, i, lnum;
    2649             : 
    2650         640 :         lnum = UBIFS_LOG_LNUM;
    2651             : 
    2652         640 :         cs.ch.node_type = UBIFS_CS_NODE;
    2653         640 :         cs.cmt_no = cpu_to_le64(0);
    2654             : 
    2655         640 :         err = write_node(&cs, UBIFS_CS_NODE_SZ, lnum);
    2656         640 :         if (err)
    2657             :                 return err;
    2658             : 
    2659             :         lnum += 1;
    2660             : 
    2661        2320 :         for (i = 1; i < c->log_lebs; i++, lnum++) {
    2662        2320 :                 err = write_empty_leb(lnum);
    2663        2320 :                 if (err)
    2664             :                         return err;
    2665             :         }
    2666             : 
    2667             :         return 0;
    2668             : }
    2669             : 
    2670             : /**
    2671             :  * write_lpt - write the LEB properties tree.
    2672             :  */
    2673         640 : static int write_lpt(void)
    2674             : {
    2675             :         int err, lnum;
    2676             : 
    2677         640 :         c->lscan_lnum = c->main_first;
    2678         640 :         err = ubifs_create_lpt(c, c->lpt, c->main_lebs, c->lpt_hash, true);
    2679         640 :         if (err)
    2680             :                 return err;
    2681             : 
    2682         640 :         lnum = c->nhead_lnum + 1;
    2683        1920 :         while (lnum <= c->lpt_last) {
    2684         640 :                 err = write_empty_leb(lnum++);
    2685         640 :                 if (err)
    2686             :                         return err;
    2687             :         }
    2688             : 
    2689             :         return 0;
    2690             : }
    2691             : 
    2692             : /**
    2693             :  * write_orphan_area - write an empty orphan area.
    2694             :  */
    2695         640 : static int write_orphan_area(void)
    2696             : {
    2697             :         int err, i, lnum;
    2698             : 
    2699         640 :         lnum = UBIFS_LOG_LNUM + c->log_lebs + c->lpt_lebs;
    2700        1280 :         for (i = 0; i < c->orph_lebs; i++, lnum++) {
    2701         640 :                 err = write_empty_leb(lnum);
    2702         640 :                 if (err)
    2703             :                         return err;
    2704             :         }
    2705             :         return 0;
    2706             : }
    2707             : 
    2708             : /**
    2709             :  * init - initialize things.
    2710             :  */
    2711         640 : static int init(void)
    2712             : {
    2713         640 :         int err, main_lebs, big_lpt = 0, sz;
    2714             : 
    2715         640 :         c->highest_inum = UBIFS_FIRST_INO;
    2716             : 
    2717         640 :         c->jhead_cnt = 1;
    2718             : 
    2719         640 :         main_lebs = c->max_leb_cnt - UBIFS_SB_LEBS - UBIFS_MST_LEBS;
    2720         640 :         main_lebs -= c->log_lebs + c->orph_lebs;
    2721             : 
    2722         640 :         err = ubifs_calc_dflt_lpt_geom(c, &main_lebs, &big_lpt);
    2723         640 :         if (err)
    2724             :                 return err;
    2725             : 
    2726        1280 :         c->main_first = UBIFS_LOG_LNUM + c->log_lebs + c->lpt_lebs +
    2727         640 :                         c->orph_lebs;
    2728         640 :         head_lnum = c->main_first;
    2729         640 :         head_offs = 0;
    2730             : 
    2731         640 :         c->lpt_first = UBIFS_LOG_LNUM + c->log_lebs;
    2732         640 :         c->lpt_last = c->lpt_first + c->lpt_lebs - 1;
    2733             : 
    2734         640 :         c->lpt = xmalloc(c->main_lebs * sizeof(struct ubifs_lprops));
    2735             : 
    2736         640 :         c->dead_wm = ALIGN(MIN_WRITE_SZ, c->min_io_size);
    2737         640 :         c->dark_wm = ALIGN(UBIFS_MAX_NODE_SZ, c->min_io_size);
    2738         640 :         pr_debug("dead_wm %d  dark_wm %d\n", c->dead_wm, c->dark_wm);
    2739             : 
    2740         640 :         leb_buf = xmalloc(c->leb_size);
    2741         640 :         node_buf = xmalloc(NODE_BUFFER_SIZE);
    2742         640 :         block_buf = xmalloc(UBIFS_BLOCK_SIZE);
    2743             : 
    2744         640 :         sz = sizeof(struct inum_mapping *) * HASH_TABLE_SIZE;
    2745        1280 :         hash_table = xzalloc(sz);
    2746             : 
    2747         640 :         err = init_compression();
    2748         640 :         if (err)
    2749             :                 return err;
    2750             : 
    2751             : #ifdef WITH_SELINUX
    2752         640 :         if (context) {
    2753           0 :                 struct selinux_opt seopts[] = {
    2754             :                         { SELABEL_OPT_PATH, context }
    2755             :                 };
    2756             : 
    2757           0 :                 sehnd = selabel_open(SELABEL_CTX_FILE, seopts, 1);
    2758           0 :                 if (!sehnd)
    2759           0 :                         return errmsg("could not open selinux context\n");
    2760             :         }
    2761             : #endif
    2762             : 
    2763             :         return 0;
    2764             : }
    2765             : 
    2766         640 : static void destroy_hash_table(void)
    2767             : {
    2768             :         int i;
    2769             : 
    2770     6464000 :         for (i = 0; i < HASH_TABLE_SIZE; i++) {
    2771             :                 struct inum_mapping *im, *q;
    2772             : 
    2773    12933120 :                 for (im = hash_table[i]; im; ) {
    2774        6400 :                         q = im;
    2775        6400 :                         im = im->next;
    2776        6400 :                         free(q->path_name);
    2777        6400 :                         free(q);
    2778             :                 }
    2779             :         }
    2780         640 : }
    2781             : 
    2782             : /**
    2783             :  * deinit - deinitialize things.
    2784             :  */
    2785         640 : static void deinit(void)
    2786             : {
    2787             : 
    2788             : #ifdef WITH_SELINUX
    2789         640 :         if (sehnd)
    2790           0 :                 selabel_close(sehnd);
    2791             : #endif
    2792             : 
    2793         640 :         free(c->lpt);
    2794         640 :         free(leb_buf);
    2795         640 :         free(node_buf);
    2796         640 :         free(block_buf);
    2797         640 :         destroy_hash_table();
    2798         640 :         free(hash_table);
    2799         640 :         destroy_compression();
    2800         640 :         free_devtable_info();
    2801        1280 :         ubifs_exit_authentication(c);
    2802         640 : }
    2803             : 
    2804             : /**
    2805             :  * mkfs - make the file system.
    2806             :  *
    2807             :  * Each on-flash area has a corresponding function to create it. The order of
    2808             :  * the functions reflects what information must be known to complete each stage.
    2809             :  * As a consequence the output file is not written sequentially. No effort has
    2810             :  * been made to make efficient use of memory or to allow for the possibility of
    2811             :  * incremental updates to the output file.
    2812             :  */
    2813         640 : static int mkfs(void)
    2814             : {
    2815         640 :         int err = 0;
    2816             : 
    2817         640 :         err = init();
    2818         640 :         if (err)
    2819             :                 goto out;
    2820             : 
    2821         640 :         err = ubifs_init_authentication(c);
    2822         640 :         if (err)
    2823             :                 goto out;
    2824             : 
    2825         640 :         err = write_data();
    2826         640 :         if (err)
    2827             :                 goto out;
    2828             : 
    2829         640 :         err = set_gc_lnum();
    2830         640 :         if (err)
    2831             :                 goto out;
    2832             : 
    2833         640 :         err = write_index();
    2834         640 :         if (err)
    2835             :                 goto out;
    2836             : 
    2837         640 :         err = finalize_leb_cnt();
    2838         640 :         if (err)
    2839             :                 goto out;
    2840             : 
    2841         640 :         err = write_lpt();
    2842         640 :         if (err)
    2843             :                 goto out;
    2844             : 
    2845         640 :         err = write_master();
    2846         640 :         if (err)
    2847             :                 goto out;
    2848             : 
    2849         640 :         err = write_super();
    2850         640 :         if (err)
    2851             :                 goto out;
    2852             : 
    2853         640 :         err = write_log();
    2854         640 :         if (err)
    2855             :                 goto out;
    2856             : 
    2857         640 :         err = write_orphan_area();
    2858             : 
    2859         640 : out:
    2860         640 :         deinit();
    2861         640 :         return err;
    2862             : }
    2863             : 
    2864         640 : int main(int argc, char *argv[])
    2865             : {
    2866             :         int err;
    2867             : 
    2868         640 :         init_ubifs_info(c, MKFS_PROGRAM_TYPE);
    2869             : 
    2870         640 :         if (crypto_init())
    2871             :                 return -1;
    2872             : 
    2873         640 :         err = get_options(argc, argv);
    2874         640 :         if (err)
    2875             :                 goto out;
    2876             : 
    2877         640 :         err = open_target(c);
    2878         640 :         if (err)
    2879             :                 goto out;
    2880             : 
    2881         640 :         if (!yes && check_volume_empty(c)) {
    2882           0 :                 if (!prompt("UBI volume is not empty.  Format anyways?", false)) {
    2883           0 :                         close_target(c);
    2884           0 :                         err = errmsg("UBI volume is not empty");
    2885           0 :                         goto out;
    2886             :                 }
    2887             :         }
    2888             : 
    2889         640 :         err = mkfs();
    2890         640 :         if (err) {
    2891           0 :                 close_target(c);
    2892           0 :                 goto out;
    2893             :         }
    2894             : 
    2895         640 :         err = close_target(c);
    2896             : 
    2897         640 :         if (verbose && !err)
    2898           0 :                 printf("Success!\n");
    2899             : 
    2900        1280 : out:
    2901         640 :         free(c->dev_name);
    2902         640 :         close_ubi(c);
    2903         640 :         crypto_cleanup();
    2904         640 :         return err;
    2905             : }

Generated by: LCOV version 1.13