GNU Linux-libre 5.15.137-gnu
[releases.git] / fs / ubifs / super.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * This file is part of UBIFS.
4  *
5  * Copyright (C) 2006-2008 Nokia Corporation.
6  *
7  * Authors: Artem Bityutskiy (Битюцкий Артём)
8  *          Adrian Hunter
9  */
10
11 /*
12  * This file implements UBIFS initialization and VFS superblock operations. Some
13  * initialization stuff which is rather large and complex is placed at
14  * corresponding subsystems, but most of it is here.
15  */
16
17 #include <linux/init.h>
18 #include <linux/slab.h>
19 #include <linux/module.h>
20 #include <linux/ctype.h>
21 #include <linux/kthread.h>
22 #include <linux/parser.h>
23 #include <linux/seq_file.h>
24 #include <linux/mount.h>
25 #include <linux/math64.h>
26 #include <linux/writeback.h>
27 #include "ubifs.h"
28
29 static int ubifs_default_version_set(const char *val, const struct kernel_param *kp)
30 {
31         int n = 0, ret;
32
33         ret = kstrtoint(val, 10, &n);
34         if (ret != 0 || n < 4 || n > UBIFS_FORMAT_VERSION)
35                 return -EINVAL;
36         return param_set_int(val, kp);
37 }
38
39 static const struct kernel_param_ops ubifs_default_version_ops = {
40         .set = ubifs_default_version_set,
41         .get = param_get_int,
42 };
43
44 int ubifs_default_version = UBIFS_FORMAT_VERSION;
45 module_param_cb(default_version, &ubifs_default_version_ops, &ubifs_default_version, 0600);
46
47 /*
48  * Maximum amount of memory we may 'kmalloc()' without worrying that we are
49  * allocating too much.
50  */
51 #define UBIFS_KMALLOC_OK (128*1024)
52
53 /* Slab cache for UBIFS inodes */
54 static struct kmem_cache *ubifs_inode_slab;
55
56 /* UBIFS TNC shrinker description */
57 static struct shrinker ubifs_shrinker_info = {
58         .scan_objects = ubifs_shrink_scan,
59         .count_objects = ubifs_shrink_count,
60         .seeks = DEFAULT_SEEKS,
61 };
62
63 /**
64  * validate_inode - validate inode.
65  * @c: UBIFS file-system description object
66  * @inode: the inode to validate
67  *
68  * This is a helper function for 'ubifs_iget()' which validates various fields
69  * of a newly built inode to make sure they contain sane values and prevent
70  * possible vulnerabilities. Returns zero if the inode is all right and
71  * a non-zero error code if not.
72  */
73 static int validate_inode(struct ubifs_info *c, const struct inode *inode)
74 {
75         int err;
76         const struct ubifs_inode *ui = ubifs_inode(inode);
77
78         if (inode->i_size > c->max_inode_sz) {
79                 ubifs_err(c, "inode is too large (%lld)",
80                           (long long)inode->i_size);
81                 return 1;
82         }
83
84         if (ui->compr_type >= UBIFS_COMPR_TYPES_CNT) {
85                 ubifs_err(c, "unknown compression type %d", ui->compr_type);
86                 return 2;
87         }
88
89         if (ui->xattr_names + ui->xattr_cnt > XATTR_LIST_MAX)
90                 return 3;
91
92         if (ui->data_len < 0 || ui->data_len > UBIFS_MAX_INO_DATA)
93                 return 4;
94
95         if (ui->xattr && !S_ISREG(inode->i_mode))
96                 return 5;
97
98         if (!ubifs_compr_present(c, ui->compr_type)) {
99                 ubifs_warn(c, "inode %lu uses '%s' compression, but it was not compiled in",
100                            inode->i_ino, ubifs_compr_name(c, ui->compr_type));
101         }
102
103         err = dbg_check_dir(c, inode);
104         return err;
105 }
106
107 struct inode *ubifs_iget(struct super_block *sb, unsigned long inum)
108 {
109         int err;
110         union ubifs_key key;
111         struct ubifs_ino_node *ino;
112         struct ubifs_info *c = sb->s_fs_info;
113         struct inode *inode;
114         struct ubifs_inode *ui;
115
116         dbg_gen("inode %lu", inum);
117
118         inode = iget_locked(sb, inum);
119         if (!inode)
120                 return ERR_PTR(-ENOMEM);
121         if (!(inode->i_state & I_NEW))
122                 return inode;
123         ui = ubifs_inode(inode);
124
125         ino = kmalloc(UBIFS_MAX_INO_NODE_SZ, GFP_NOFS);
126         if (!ino) {
127                 err = -ENOMEM;
128                 goto out;
129         }
130
131         ino_key_init(c, &key, inode->i_ino);
132
133         err = ubifs_tnc_lookup(c, &key, ino);
134         if (err)
135                 goto out_ino;
136
137         inode->i_flags |= S_NOCMTIME;
138
139         if (!IS_ENABLED(CONFIG_UBIFS_ATIME_SUPPORT))
140                 inode->i_flags |= S_NOATIME;
141
142         set_nlink(inode, le32_to_cpu(ino->nlink));
143         i_uid_write(inode, le32_to_cpu(ino->uid));
144         i_gid_write(inode, le32_to_cpu(ino->gid));
145         inode->i_atime.tv_sec  = (int64_t)le64_to_cpu(ino->atime_sec);
146         inode->i_atime.tv_nsec = le32_to_cpu(ino->atime_nsec);
147         inode->i_mtime.tv_sec  = (int64_t)le64_to_cpu(ino->mtime_sec);
148         inode->i_mtime.tv_nsec = le32_to_cpu(ino->mtime_nsec);
149         inode->i_ctime.tv_sec  = (int64_t)le64_to_cpu(ino->ctime_sec);
150         inode->i_ctime.tv_nsec = le32_to_cpu(ino->ctime_nsec);
151         inode->i_mode = le32_to_cpu(ino->mode);
152         inode->i_size = le64_to_cpu(ino->size);
153
154         ui->data_len    = le32_to_cpu(ino->data_len);
155         ui->flags       = le32_to_cpu(ino->flags);
156         ui->compr_type  = le16_to_cpu(ino->compr_type);
157         ui->creat_sqnum = le64_to_cpu(ino->creat_sqnum);
158         ui->xattr_cnt   = le32_to_cpu(ino->xattr_cnt);
159         ui->xattr_size  = le32_to_cpu(ino->xattr_size);
160         ui->xattr_names = le32_to_cpu(ino->xattr_names);
161         ui->synced_i_size = ui->ui_size = inode->i_size;
162
163         ui->xattr = (ui->flags & UBIFS_XATTR_FL) ? 1 : 0;
164
165         err = validate_inode(c, inode);
166         if (err)
167                 goto out_invalid;
168
169         switch (inode->i_mode & S_IFMT) {
170         case S_IFREG:
171                 inode->i_mapping->a_ops = &ubifs_file_address_operations;
172                 inode->i_op = &ubifs_file_inode_operations;
173                 inode->i_fop = &ubifs_file_operations;
174                 if (ui->xattr) {
175                         ui->data = kmalloc(ui->data_len + 1, GFP_NOFS);
176                         if (!ui->data) {
177                                 err = -ENOMEM;
178                                 goto out_ino;
179                         }
180                         memcpy(ui->data, ino->data, ui->data_len);
181                         ((char *)ui->data)[ui->data_len] = '\0';
182                 } else if (ui->data_len != 0) {
183                         err = 10;
184                         goto out_invalid;
185                 }
186                 break;
187         case S_IFDIR:
188                 inode->i_op  = &ubifs_dir_inode_operations;
189                 inode->i_fop = &ubifs_dir_operations;
190                 if (ui->data_len != 0) {
191                         err = 11;
192                         goto out_invalid;
193                 }
194                 break;
195         case S_IFLNK:
196                 inode->i_op = &ubifs_symlink_inode_operations;
197                 if (ui->data_len <= 0 || ui->data_len > UBIFS_MAX_INO_DATA) {
198                         err = 12;
199                         goto out_invalid;
200                 }
201                 ui->data = kmalloc(ui->data_len + 1, GFP_NOFS);
202                 if (!ui->data) {
203                         err = -ENOMEM;
204                         goto out_ino;
205                 }
206                 memcpy(ui->data, ino->data, ui->data_len);
207                 ((char *)ui->data)[ui->data_len] = '\0';
208                 break;
209         case S_IFBLK:
210         case S_IFCHR:
211         {
212                 dev_t rdev;
213                 union ubifs_dev_desc *dev;
214
215                 ui->data = kmalloc(sizeof(union ubifs_dev_desc), GFP_NOFS);
216                 if (!ui->data) {
217                         err = -ENOMEM;
218                         goto out_ino;
219                 }
220
221                 dev = (union ubifs_dev_desc *)ino->data;
222                 if (ui->data_len == sizeof(dev->new))
223                         rdev = new_decode_dev(le32_to_cpu(dev->new));
224                 else if (ui->data_len == sizeof(dev->huge))
225                         rdev = huge_decode_dev(le64_to_cpu(dev->huge));
226                 else {
227                         err = 13;
228                         goto out_invalid;
229                 }
230                 memcpy(ui->data, ino->data, ui->data_len);
231                 inode->i_op = &ubifs_file_inode_operations;
232                 init_special_inode(inode, inode->i_mode, rdev);
233                 break;
234         }
235         case S_IFSOCK:
236         case S_IFIFO:
237                 inode->i_op = &ubifs_file_inode_operations;
238                 init_special_inode(inode, inode->i_mode, 0);
239                 if (ui->data_len != 0) {
240                         err = 14;
241                         goto out_invalid;
242                 }
243                 break;
244         default:
245                 err = 15;
246                 goto out_invalid;
247         }
248
249         kfree(ino);
250         ubifs_set_inode_flags(inode);
251         unlock_new_inode(inode);
252         return inode;
253
254 out_invalid:
255         ubifs_err(c, "inode %lu validation failed, error %d", inode->i_ino, err);
256         ubifs_dump_node(c, ino, UBIFS_MAX_INO_NODE_SZ);
257         ubifs_dump_inode(c, inode);
258         err = -EINVAL;
259 out_ino:
260         kfree(ino);
261 out:
262         ubifs_err(c, "failed to read inode %lu, error %d", inode->i_ino, err);
263         iget_failed(inode);
264         return ERR_PTR(err);
265 }
266
267 static struct inode *ubifs_alloc_inode(struct super_block *sb)
268 {
269         struct ubifs_inode *ui;
270
271         ui = kmem_cache_alloc(ubifs_inode_slab, GFP_NOFS);
272         if (!ui)
273                 return NULL;
274
275         memset((void *)ui + sizeof(struct inode), 0,
276                sizeof(struct ubifs_inode) - sizeof(struct inode));
277         mutex_init(&ui->ui_mutex);
278         init_rwsem(&ui->xattr_sem);
279         spin_lock_init(&ui->ui_lock);
280         return &ui->vfs_inode;
281 };
282
283 static void ubifs_free_inode(struct inode *inode)
284 {
285         struct ubifs_inode *ui = ubifs_inode(inode);
286
287         kfree(ui->data);
288         fscrypt_free_inode(inode);
289
290         kmem_cache_free(ubifs_inode_slab, ui);
291 }
292
293 /*
294  * Note, Linux write-back code calls this without 'i_mutex'.
295  */
296 static int ubifs_write_inode(struct inode *inode, struct writeback_control *wbc)
297 {
298         int err = 0;
299         struct ubifs_info *c = inode->i_sb->s_fs_info;
300         struct ubifs_inode *ui = ubifs_inode(inode);
301
302         ubifs_assert(c, !ui->xattr);
303         if (is_bad_inode(inode))
304                 return 0;
305
306         mutex_lock(&ui->ui_mutex);
307         /*
308          * Due to races between write-back forced by budgeting
309          * (see 'sync_some_inodes()') and background write-back, the inode may
310          * have already been synchronized, do not do this again. This might
311          * also happen if it was synchronized in an VFS operation, e.g.
312          * 'ubifs_link()'.
313          */
314         if (!ui->dirty) {
315                 mutex_unlock(&ui->ui_mutex);
316                 return 0;
317         }
318
319         /*
320          * As an optimization, do not write orphan inodes to the media just
321          * because this is not needed.
322          */
323         dbg_gen("inode %lu, mode %#x, nlink %u",
324                 inode->i_ino, (int)inode->i_mode, inode->i_nlink);
325         if (inode->i_nlink) {
326                 err = ubifs_jnl_write_inode(c, inode);
327                 if (err)
328                         ubifs_err(c, "can't write inode %lu, error %d",
329                                   inode->i_ino, err);
330                 else
331                         err = dbg_check_inode_size(c, inode, ui->ui_size);
332         }
333
334         ui->dirty = 0;
335         mutex_unlock(&ui->ui_mutex);
336         ubifs_release_dirty_inode_budget(c, ui);
337         return err;
338 }
339
340 static int ubifs_drop_inode(struct inode *inode)
341 {
342         int drop = generic_drop_inode(inode);
343
344         if (!drop)
345                 drop = fscrypt_drop_inode(inode);
346
347         return drop;
348 }
349
350 static void ubifs_evict_inode(struct inode *inode)
351 {
352         int err;
353         struct ubifs_info *c = inode->i_sb->s_fs_info;
354         struct ubifs_inode *ui = ubifs_inode(inode);
355
356         if (ui->xattr)
357                 /*
358                  * Extended attribute inode deletions are fully handled in
359                  * 'ubifs_removexattr()'. These inodes are special and have
360                  * limited usage, so there is nothing to do here.
361                  */
362                 goto out;
363
364         dbg_gen("inode %lu, mode %#x", inode->i_ino, (int)inode->i_mode);
365         ubifs_assert(c, !atomic_read(&inode->i_count));
366
367         truncate_inode_pages_final(&inode->i_data);
368
369         if (inode->i_nlink)
370                 goto done;
371
372         if (is_bad_inode(inode))
373                 goto out;
374
375         ui->ui_size = inode->i_size = 0;
376         err = ubifs_jnl_delete_inode(c, inode);
377         if (err)
378                 /*
379                  * Worst case we have a lost orphan inode wasting space, so a
380                  * simple error message is OK here.
381                  */
382                 ubifs_err(c, "can't delete inode %lu, error %d",
383                           inode->i_ino, err);
384
385 out:
386         if (ui->dirty)
387                 ubifs_release_dirty_inode_budget(c, ui);
388         else {
389                 /* We've deleted something - clean the "no space" flags */
390                 c->bi.nospace = c->bi.nospace_rp = 0;
391                 smp_wmb();
392         }
393 done:
394         clear_inode(inode);
395         fscrypt_put_encryption_info(inode);
396 }
397
398 static void ubifs_dirty_inode(struct inode *inode, int flags)
399 {
400         struct ubifs_info *c = inode->i_sb->s_fs_info;
401         struct ubifs_inode *ui = ubifs_inode(inode);
402
403         ubifs_assert(c, mutex_is_locked(&ui->ui_mutex));
404         if (!ui->dirty) {
405                 ui->dirty = 1;
406                 dbg_gen("inode %lu",  inode->i_ino);
407         }
408 }
409
410 static int ubifs_statfs(struct dentry *dentry, struct kstatfs *buf)
411 {
412         struct ubifs_info *c = dentry->d_sb->s_fs_info;
413         unsigned long long free;
414         __le32 *uuid = (__le32 *)c->uuid;
415
416         free = ubifs_get_free_space(c);
417         dbg_gen("free space %lld bytes (%lld blocks)",
418                 free, free >> UBIFS_BLOCK_SHIFT);
419
420         buf->f_type = UBIFS_SUPER_MAGIC;
421         buf->f_bsize = UBIFS_BLOCK_SIZE;
422         buf->f_blocks = c->block_cnt;
423         buf->f_bfree = free >> UBIFS_BLOCK_SHIFT;
424         if (free > c->report_rp_size)
425                 buf->f_bavail = (free - c->report_rp_size) >> UBIFS_BLOCK_SHIFT;
426         else
427                 buf->f_bavail = 0;
428         buf->f_files = 0;
429         buf->f_ffree = 0;
430         buf->f_namelen = UBIFS_MAX_NLEN;
431         buf->f_fsid.val[0] = le32_to_cpu(uuid[0]) ^ le32_to_cpu(uuid[2]);
432         buf->f_fsid.val[1] = le32_to_cpu(uuid[1]) ^ le32_to_cpu(uuid[3]);
433         ubifs_assert(c, buf->f_bfree <= c->block_cnt);
434         return 0;
435 }
436
437 static int ubifs_show_options(struct seq_file *s, struct dentry *root)
438 {
439         struct ubifs_info *c = root->d_sb->s_fs_info;
440
441         if (c->mount_opts.unmount_mode == 2)
442                 seq_puts(s, ",fast_unmount");
443         else if (c->mount_opts.unmount_mode == 1)
444                 seq_puts(s, ",norm_unmount");
445
446         if (c->mount_opts.bulk_read == 2)
447                 seq_puts(s, ",bulk_read");
448         else if (c->mount_opts.bulk_read == 1)
449                 seq_puts(s, ",no_bulk_read");
450
451         if (c->mount_opts.chk_data_crc == 2)
452                 seq_puts(s, ",chk_data_crc");
453         else if (c->mount_opts.chk_data_crc == 1)
454                 seq_puts(s, ",no_chk_data_crc");
455
456         if (c->mount_opts.override_compr) {
457                 seq_printf(s, ",compr=%s",
458                            ubifs_compr_name(c, c->mount_opts.compr_type));
459         }
460
461         seq_printf(s, ",assert=%s", ubifs_assert_action_name(c));
462         seq_printf(s, ",ubi=%d,vol=%d", c->vi.ubi_num, c->vi.vol_id);
463
464         return 0;
465 }
466
467 static int ubifs_sync_fs(struct super_block *sb, int wait)
468 {
469         int i, err;
470         struct ubifs_info *c = sb->s_fs_info;
471
472         /*
473          * Zero @wait is just an advisory thing to help the file system shove
474          * lots of data into the queues, and there will be the second
475          * '->sync_fs()' call, with non-zero @wait.
476          */
477         if (!wait)
478                 return 0;
479
480         /*
481          * Synchronize write buffers, because 'ubifs_run_commit()' does not
482          * do this if it waits for an already running commit.
483          */
484         for (i = 0; i < c->jhead_cnt; i++) {
485                 err = ubifs_wbuf_sync(&c->jheads[i].wbuf);
486                 if (err)
487                         return err;
488         }
489
490         /*
491          * Strictly speaking, it is not necessary to commit the journal here,
492          * synchronizing write-buffers would be enough. But committing makes
493          * UBIFS free space predictions much more accurate, so we want to let
494          * the user be able to get more accurate results of 'statfs()' after
495          * they synchronize the file system.
496          */
497         err = ubifs_run_commit(c);
498         if (err)
499                 return err;
500
501         return ubi_sync(c->vi.ubi_num);
502 }
503
504 /**
505  * init_constants_early - initialize UBIFS constants.
506  * @c: UBIFS file-system description object
507  *
508  * This function initialize UBIFS constants which do not need the superblock to
509  * be read. It also checks that the UBI volume satisfies basic UBIFS
510  * requirements. Returns zero in case of success and a negative error code in
511  * case of failure.
512  */
513 static int init_constants_early(struct ubifs_info *c)
514 {
515         if (c->vi.corrupted) {
516                 ubifs_warn(c, "UBI volume is corrupted - read-only mode");
517                 c->ro_media = 1;
518         }
519
520         if (c->di.ro_mode) {
521                 ubifs_msg(c, "read-only UBI device");
522                 c->ro_media = 1;
523         }
524
525         if (c->vi.vol_type == UBI_STATIC_VOLUME) {
526                 ubifs_msg(c, "static UBI volume - read-only mode");
527                 c->ro_media = 1;
528         }
529
530         c->leb_cnt = c->vi.size;
531         c->leb_size = c->vi.usable_leb_size;
532         c->leb_start = c->di.leb_start;
533         c->half_leb_size = c->leb_size / 2;
534         c->min_io_size = c->di.min_io_size;
535         c->min_io_shift = fls(c->min_io_size) - 1;
536         c->max_write_size = c->di.max_write_size;
537         c->max_write_shift = fls(c->max_write_size) - 1;
538
539         if (c->leb_size < UBIFS_MIN_LEB_SZ) {
540                 ubifs_errc(c, "too small LEBs (%d bytes), min. is %d bytes",
541                            c->leb_size, UBIFS_MIN_LEB_SZ);
542                 return -EINVAL;
543         }
544
545         if (c->leb_cnt < UBIFS_MIN_LEB_CNT) {
546                 ubifs_errc(c, "too few LEBs (%d), min. is %d",
547                            c->leb_cnt, UBIFS_MIN_LEB_CNT);
548                 return -EINVAL;
549         }
550
551         if (!is_power_of_2(c->min_io_size)) {
552                 ubifs_errc(c, "bad min. I/O size %d", c->min_io_size);
553                 return -EINVAL;
554         }
555
556         /*
557          * Maximum write size has to be greater or equivalent to min. I/O
558          * size, and be multiple of min. I/O size.
559          */
560         if (c->max_write_size < c->min_io_size ||
561             c->max_write_size % c->min_io_size ||
562             !is_power_of_2(c->max_write_size)) {
563                 ubifs_errc(c, "bad write buffer size %d for %d min. I/O unit",
564                            c->max_write_size, c->min_io_size);
565                 return -EINVAL;
566         }
567
568         /*
569          * UBIFS aligns all node to 8-byte boundary, so to make function in
570          * io.c simpler, assume minimum I/O unit size to be 8 bytes if it is
571          * less than 8.
572          */
573         if (c->min_io_size < 8) {
574                 c->min_io_size = 8;
575                 c->min_io_shift = 3;
576                 if (c->max_write_size < c->min_io_size) {
577                         c->max_write_size = c->min_io_size;
578                         c->max_write_shift = c->min_io_shift;
579                 }
580         }
581
582         c->ref_node_alsz = ALIGN(UBIFS_REF_NODE_SZ, c->min_io_size);
583         c->mst_node_alsz = ALIGN(UBIFS_MST_NODE_SZ, c->min_io_size);
584
585         /*
586          * Initialize node length ranges which are mostly needed for node
587          * length validation.
588          */
589         c->ranges[UBIFS_PAD_NODE].len  = UBIFS_PAD_NODE_SZ;
590         c->ranges[UBIFS_SB_NODE].len   = UBIFS_SB_NODE_SZ;
591         c->ranges[UBIFS_MST_NODE].len  = UBIFS_MST_NODE_SZ;
592         c->ranges[UBIFS_REF_NODE].len  = UBIFS_REF_NODE_SZ;
593         c->ranges[UBIFS_TRUN_NODE].len = UBIFS_TRUN_NODE_SZ;
594         c->ranges[UBIFS_CS_NODE].len   = UBIFS_CS_NODE_SZ;
595         c->ranges[UBIFS_AUTH_NODE].min_len = UBIFS_AUTH_NODE_SZ;
596         c->ranges[UBIFS_AUTH_NODE].max_len = UBIFS_AUTH_NODE_SZ +
597                                 UBIFS_MAX_HMAC_LEN;
598         c->ranges[UBIFS_SIG_NODE].min_len = UBIFS_SIG_NODE_SZ;
599         c->ranges[UBIFS_SIG_NODE].max_len = c->leb_size - UBIFS_SB_NODE_SZ;
600
601         c->ranges[UBIFS_INO_NODE].min_len  = UBIFS_INO_NODE_SZ;
602         c->ranges[UBIFS_INO_NODE].max_len  = UBIFS_MAX_INO_NODE_SZ;
603         c->ranges[UBIFS_ORPH_NODE].min_len =
604                                 UBIFS_ORPH_NODE_SZ + sizeof(__le64);
605         c->ranges[UBIFS_ORPH_NODE].max_len = c->leb_size;
606         c->ranges[UBIFS_DENT_NODE].min_len = UBIFS_DENT_NODE_SZ;
607         c->ranges[UBIFS_DENT_NODE].max_len = UBIFS_MAX_DENT_NODE_SZ;
608         c->ranges[UBIFS_XENT_NODE].min_len = UBIFS_XENT_NODE_SZ;
609         c->ranges[UBIFS_XENT_NODE].max_len = UBIFS_MAX_XENT_NODE_SZ;
610         c->ranges[UBIFS_DATA_NODE].min_len = UBIFS_DATA_NODE_SZ;
611         c->ranges[UBIFS_DATA_NODE].max_len = UBIFS_MAX_DATA_NODE_SZ;
612         /*
613          * Minimum indexing node size is amended later when superblock is
614          * read and the key length is known.
615          */
616         c->ranges[UBIFS_IDX_NODE].min_len = UBIFS_IDX_NODE_SZ + UBIFS_BRANCH_SZ;
617         /*
618          * Maximum indexing node size is amended later when superblock is
619          * read and the fanout is known.
620          */
621         c->ranges[UBIFS_IDX_NODE].max_len = INT_MAX;
622
623         /*
624          * Initialize dead and dark LEB space watermarks. See gc.c for comments
625          * about these values.
626          */
627         c->dead_wm = ALIGN(MIN_WRITE_SZ, c->min_io_size);
628         c->dark_wm = ALIGN(UBIFS_MAX_NODE_SZ, c->min_io_size);
629
630         /*
631          * Calculate how many bytes would be wasted at the end of LEB if it was
632          * fully filled with data nodes of maximum size. This is used in
633          * calculations when reporting free space.
634          */
635         c->leb_overhead = c->leb_size % UBIFS_MAX_DATA_NODE_SZ;
636
637         /* Buffer size for bulk-reads */
638         c->max_bu_buf_len = UBIFS_MAX_BULK_READ * UBIFS_MAX_DATA_NODE_SZ;
639         if (c->max_bu_buf_len > c->leb_size)
640                 c->max_bu_buf_len = c->leb_size;
641
642         /* Log is ready, preserve one LEB for commits. */
643         c->min_log_bytes = c->leb_size;
644
645         return 0;
646 }
647
648 /**
649  * bud_wbuf_callback - bud LEB write-buffer synchronization call-back.
650  * @c: UBIFS file-system description object
651  * @lnum: LEB the write-buffer was synchronized to
652  * @free: how many free bytes left in this LEB
653  * @pad: how many bytes were padded
654  *
655  * This is a callback function which is called by the I/O unit when the
656  * write-buffer is synchronized. We need this to correctly maintain space
657  * accounting in bud logical eraseblocks. This function returns zero in case of
658  * success and a negative error code in case of failure.
659  *
660  * This function actually belongs to the journal, but we keep it here because
661  * we want to keep it static.
662  */
663 static int bud_wbuf_callback(struct ubifs_info *c, int lnum, int free, int pad)
664 {
665         return ubifs_update_one_lp(c, lnum, free, pad, 0, 0);
666 }
667
668 /*
669  * init_constants_sb - initialize UBIFS constants.
670  * @c: UBIFS file-system description object
671  *
672  * This is a helper function which initializes various UBIFS constants after
673  * the superblock has been read. It also checks various UBIFS parameters and
674  * makes sure they are all right. Returns zero in case of success and a
675  * negative error code in case of failure.
676  */
677 static int init_constants_sb(struct ubifs_info *c)
678 {
679         int tmp, err;
680         long long tmp64;
681
682         c->main_bytes = (long long)c->main_lebs * c->leb_size;
683         c->max_znode_sz = sizeof(struct ubifs_znode) +
684                                 c->fanout * sizeof(struct ubifs_zbranch);
685
686         tmp = ubifs_idx_node_sz(c, 1);
687         c->ranges[UBIFS_IDX_NODE].min_len = tmp;
688         c->min_idx_node_sz = ALIGN(tmp, 8);
689
690         tmp = ubifs_idx_node_sz(c, c->fanout);
691         c->ranges[UBIFS_IDX_NODE].max_len = tmp;
692         c->max_idx_node_sz = ALIGN(tmp, 8);
693
694         /* Make sure LEB size is large enough to fit full commit */
695         tmp = UBIFS_CS_NODE_SZ + UBIFS_REF_NODE_SZ * c->jhead_cnt;
696         tmp = ALIGN(tmp, c->min_io_size);
697         if (tmp > c->leb_size) {
698                 ubifs_err(c, "too small LEB size %d, at least %d needed",
699                           c->leb_size, tmp);
700                 return -EINVAL;
701         }
702
703         /*
704          * Make sure that the log is large enough to fit reference nodes for
705          * all buds plus one reserved LEB.
706          */
707         tmp64 = c->max_bud_bytes + c->leb_size - 1;
708         c->max_bud_cnt = div_u64(tmp64, c->leb_size);
709         tmp = (c->ref_node_alsz * c->max_bud_cnt + c->leb_size - 1);
710         tmp /= c->leb_size;
711         tmp += 1;
712         if (c->log_lebs < tmp) {
713                 ubifs_err(c, "too small log %d LEBs, required min. %d LEBs",
714                           c->log_lebs, tmp);
715                 return -EINVAL;
716         }
717
718         /*
719          * When budgeting we assume worst-case scenarios when the pages are not
720          * be compressed and direntries are of the maximum size.
721          *
722          * Note, data, which may be stored in inodes is budgeted separately, so
723          * it is not included into 'c->bi.inode_budget'.
724          */
725         c->bi.page_budget = UBIFS_MAX_DATA_NODE_SZ * UBIFS_BLOCKS_PER_PAGE;
726         c->bi.inode_budget = UBIFS_INO_NODE_SZ;
727         c->bi.dent_budget = UBIFS_MAX_DENT_NODE_SZ;
728
729         /*
730          * When the amount of flash space used by buds becomes
731          * 'c->max_bud_bytes', UBIFS just blocks all writers and starts commit.
732          * The writers are unblocked when the commit is finished. To avoid
733          * writers to be blocked UBIFS initiates background commit in advance,
734          * when number of bud bytes becomes above the limit defined below.
735          */
736         c->bg_bud_bytes = (c->max_bud_bytes * 13) >> 4;
737
738         /*
739          * Ensure minimum journal size. All the bytes in the journal heads are
740          * considered to be used, when calculating the current journal usage.
741          * Consequently, if the journal is too small, UBIFS will treat it as
742          * always full.
743          */
744         tmp64 = (long long)(c->jhead_cnt + 1) * c->leb_size + 1;
745         if (c->bg_bud_bytes < tmp64)
746                 c->bg_bud_bytes = tmp64;
747         if (c->max_bud_bytes < tmp64 + c->leb_size)
748                 c->max_bud_bytes = tmp64 + c->leb_size;
749
750         err = ubifs_calc_lpt_geom(c);
751         if (err)
752                 return err;
753
754         /* Initialize effective LEB size used in budgeting calculations */
755         c->idx_leb_size = c->leb_size - c->max_idx_node_sz;
756         return 0;
757 }
758
759 /*
760  * init_constants_master - initialize UBIFS constants.
761  * @c: UBIFS file-system description object
762  *
763  * This is a helper function which initializes various UBIFS constants after
764  * the master node has been read. It also checks various UBIFS parameters and
765  * makes sure they are all right.
766  */
767 static void init_constants_master(struct ubifs_info *c)
768 {
769         long long tmp64;
770
771         c->bi.min_idx_lebs = ubifs_calc_min_idx_lebs(c);
772         c->report_rp_size = ubifs_reported_space(c, c->rp_size);
773
774         /*
775          * Calculate total amount of FS blocks. This number is not used
776          * internally because it does not make much sense for UBIFS, but it is
777          * necessary to report something for the 'statfs()' call.
778          *
779          * Subtract the LEB reserved for GC, the LEB which is reserved for
780          * deletions, minimum LEBs for the index, and assume only one journal
781          * head is available.
782          */
783         tmp64 = c->main_lebs - 1 - 1 - MIN_INDEX_LEBS - c->jhead_cnt + 1;
784         tmp64 *= (long long)c->leb_size - c->leb_overhead;
785         tmp64 = ubifs_reported_space(c, tmp64);
786         c->block_cnt = tmp64 >> UBIFS_BLOCK_SHIFT;
787 }
788
789 /**
790  * take_gc_lnum - reserve GC LEB.
791  * @c: UBIFS file-system description object
792  *
793  * This function ensures that the LEB reserved for garbage collection is marked
794  * as "taken" in lprops. We also have to set free space to LEB size and dirty
795  * space to zero, because lprops may contain out-of-date information if the
796  * file-system was un-mounted before it has been committed. This function
797  * returns zero in case of success and a negative error code in case of
798  * failure.
799  */
800 static int take_gc_lnum(struct ubifs_info *c)
801 {
802         int err;
803
804         if (c->gc_lnum == -1) {
805                 ubifs_err(c, "no LEB for GC");
806                 return -EINVAL;
807         }
808
809         /* And we have to tell lprops that this LEB is taken */
810         err = ubifs_change_one_lp(c, c->gc_lnum, c->leb_size, 0,
811                                   LPROPS_TAKEN, 0, 0);
812         return err;
813 }
814
815 /**
816  * alloc_wbufs - allocate write-buffers.
817  * @c: UBIFS file-system description object
818  *
819  * This helper function allocates and initializes UBIFS write-buffers. Returns
820  * zero in case of success and %-ENOMEM in case of failure.
821  */
822 static int alloc_wbufs(struct ubifs_info *c)
823 {
824         int i, err;
825
826         c->jheads = kcalloc(c->jhead_cnt, sizeof(struct ubifs_jhead),
827                             GFP_KERNEL);
828         if (!c->jheads)
829                 return -ENOMEM;
830
831         /* Initialize journal heads */
832         for (i = 0; i < c->jhead_cnt; i++) {
833                 INIT_LIST_HEAD(&c->jheads[i].buds_list);
834                 err = ubifs_wbuf_init(c, &c->jheads[i].wbuf);
835                 if (err)
836                         goto out_wbuf;
837
838                 c->jheads[i].wbuf.sync_callback = &bud_wbuf_callback;
839                 c->jheads[i].wbuf.jhead = i;
840                 c->jheads[i].grouped = 1;
841                 c->jheads[i].log_hash = ubifs_hash_get_desc(c);
842                 if (IS_ERR(c->jheads[i].log_hash)) {
843                         err = PTR_ERR(c->jheads[i].log_hash);
844                         goto out_log_hash;
845                 }
846         }
847
848         /*
849          * Garbage Collector head does not need to be synchronized by timer.
850          * Also GC head nodes are not grouped.
851          */
852         c->jheads[GCHD].wbuf.no_timer = 1;
853         c->jheads[GCHD].grouped = 0;
854
855         return 0;
856
857 out_log_hash:
858         kfree(c->jheads[i].wbuf.buf);
859         kfree(c->jheads[i].wbuf.inodes);
860
861 out_wbuf:
862         while (i--) {
863                 kfree(c->jheads[i].wbuf.buf);
864                 kfree(c->jheads[i].wbuf.inodes);
865                 kfree(c->jheads[i].log_hash);
866         }
867         kfree(c->jheads);
868         c->jheads = NULL;
869
870         return err;
871 }
872
873 /**
874  * free_wbufs - free write-buffers.
875  * @c: UBIFS file-system description object
876  */
877 static void free_wbufs(struct ubifs_info *c)
878 {
879         int i;
880
881         if (c->jheads) {
882                 for (i = 0; i < c->jhead_cnt; i++) {
883                         kfree(c->jheads[i].wbuf.buf);
884                         kfree(c->jheads[i].wbuf.inodes);
885                         kfree(c->jheads[i].log_hash);
886                 }
887                 kfree(c->jheads);
888                 c->jheads = NULL;
889         }
890 }
891
892 /**
893  * free_orphans - free orphans.
894  * @c: UBIFS file-system description object
895  */
896 static void free_orphans(struct ubifs_info *c)
897 {
898         struct ubifs_orphan *orph;
899
900         while (c->orph_dnext) {
901                 orph = c->orph_dnext;
902                 c->orph_dnext = orph->dnext;
903                 list_del(&orph->list);
904                 kfree(orph);
905         }
906
907         while (!list_empty(&c->orph_list)) {
908                 orph = list_entry(c->orph_list.next, struct ubifs_orphan, list);
909                 list_del(&orph->list);
910                 kfree(orph);
911                 ubifs_err(c, "orphan list not empty at unmount");
912         }
913
914         vfree(c->orph_buf);
915         c->orph_buf = NULL;
916 }
917
918 /**
919  * free_buds - free per-bud objects.
920  * @c: UBIFS file-system description object
921  */
922 static void free_buds(struct ubifs_info *c)
923 {
924         struct ubifs_bud *bud, *n;
925
926         rbtree_postorder_for_each_entry_safe(bud, n, &c->buds, rb)
927                 kfree(bud);
928 }
929
930 /**
931  * check_volume_empty - check if the UBI volume is empty.
932  * @c: UBIFS file-system description object
933  *
934  * This function checks if the UBIFS volume is empty by looking if its LEBs are
935  * mapped or not. The result of checking is stored in the @c->empty variable.
936  * Returns zero in case of success and a negative error code in case of
937  * failure.
938  */
939 static int check_volume_empty(struct ubifs_info *c)
940 {
941         int lnum, err;
942
943         c->empty = 1;
944         for (lnum = 0; lnum < c->leb_cnt; lnum++) {
945                 err = ubifs_is_mapped(c, lnum);
946                 if (unlikely(err < 0))
947                         return err;
948                 if (err == 1) {
949                         c->empty = 0;
950                         break;
951                 }
952
953                 cond_resched();
954         }
955
956         return 0;
957 }
958
959 /*
960  * UBIFS mount options.
961  *
962  * Opt_fast_unmount: do not run a journal commit before un-mounting
963  * Opt_norm_unmount: run a journal commit before un-mounting
964  * Opt_bulk_read: enable bulk-reads
965  * Opt_no_bulk_read: disable bulk-reads
966  * Opt_chk_data_crc: check CRCs when reading data nodes
967  * Opt_no_chk_data_crc: do not check CRCs when reading data nodes
968  * Opt_override_compr: override default compressor
969  * Opt_assert: set ubifs_assert() action
970  * Opt_auth_key: The key name used for authentication
971  * Opt_auth_hash_name: The hash type used for authentication
972  * Opt_err: just end of array marker
973  */
974 enum {
975         Opt_fast_unmount,
976         Opt_norm_unmount,
977         Opt_bulk_read,
978         Opt_no_bulk_read,
979         Opt_chk_data_crc,
980         Opt_no_chk_data_crc,
981         Opt_override_compr,
982         Opt_assert,
983         Opt_auth_key,
984         Opt_auth_hash_name,
985         Opt_ignore,
986         Opt_err,
987 };
988
989 static const match_table_t tokens = {
990         {Opt_fast_unmount, "fast_unmount"},
991         {Opt_norm_unmount, "norm_unmount"},
992         {Opt_bulk_read, "bulk_read"},
993         {Opt_no_bulk_read, "no_bulk_read"},
994         {Opt_chk_data_crc, "chk_data_crc"},
995         {Opt_no_chk_data_crc, "no_chk_data_crc"},
996         {Opt_override_compr, "compr=%s"},
997         {Opt_auth_key, "auth_key=%s"},
998         {Opt_auth_hash_name, "auth_hash_name=%s"},
999         {Opt_ignore, "ubi=%s"},
1000         {Opt_ignore, "vol=%s"},
1001         {Opt_assert, "assert=%s"},
1002         {Opt_err, NULL},
1003 };
1004
1005 /**
1006  * parse_standard_option - parse a standard mount option.
1007  * @option: the option to parse
1008  *
1009  * Normally, standard mount options like "sync" are passed to file-systems as
1010  * flags. However, when a "rootflags=" kernel boot parameter is used, they may
1011  * be present in the options string. This function tries to deal with this
1012  * situation and parse standard options. Returns 0 if the option was not
1013  * recognized, and the corresponding integer flag if it was.
1014  *
1015  * UBIFS is only interested in the "sync" option, so do not check for anything
1016  * else.
1017  */
1018 static int parse_standard_option(const char *option)
1019 {
1020
1021         pr_notice("UBIFS: parse %s\n", option);
1022         if (!strcmp(option, "sync"))
1023                 return SB_SYNCHRONOUS;
1024         return 0;
1025 }
1026
1027 /**
1028  * ubifs_parse_options - parse mount parameters.
1029  * @c: UBIFS file-system description object
1030  * @options: parameters to parse
1031  * @is_remount: non-zero if this is FS re-mount
1032  *
1033  * This function parses UBIFS mount options and returns zero in case success
1034  * and a negative error code in case of failure.
1035  */
1036 static int ubifs_parse_options(struct ubifs_info *c, char *options,
1037                                int is_remount)
1038 {
1039         char *p;
1040         substring_t args[MAX_OPT_ARGS];
1041
1042         if (!options)
1043                 return 0;
1044
1045         while ((p = strsep(&options, ","))) {
1046                 int token;
1047
1048                 if (!*p)
1049                         continue;
1050
1051                 token = match_token(p, tokens, args);
1052                 switch (token) {
1053                 /*
1054                  * %Opt_fast_unmount and %Opt_norm_unmount options are ignored.
1055                  * We accept them in order to be backward-compatible. But this
1056                  * should be removed at some point.
1057                  */
1058                 case Opt_fast_unmount:
1059                         c->mount_opts.unmount_mode = 2;
1060                         break;
1061                 case Opt_norm_unmount:
1062                         c->mount_opts.unmount_mode = 1;
1063                         break;
1064                 case Opt_bulk_read:
1065                         c->mount_opts.bulk_read = 2;
1066                         c->bulk_read = 1;
1067                         break;
1068                 case Opt_no_bulk_read:
1069                         c->mount_opts.bulk_read = 1;
1070                         c->bulk_read = 0;
1071                         break;
1072                 case Opt_chk_data_crc:
1073                         c->mount_opts.chk_data_crc = 2;
1074                         c->no_chk_data_crc = 0;
1075                         break;
1076                 case Opt_no_chk_data_crc:
1077                         c->mount_opts.chk_data_crc = 1;
1078                         c->no_chk_data_crc = 1;
1079                         break;
1080                 case Opt_override_compr:
1081                 {
1082                         char *name = match_strdup(&args[0]);
1083
1084                         if (!name)
1085                                 return -ENOMEM;
1086                         if (!strcmp(name, "none"))
1087                                 c->mount_opts.compr_type = UBIFS_COMPR_NONE;
1088                         else if (!strcmp(name, "lzo"))
1089                                 c->mount_opts.compr_type = UBIFS_COMPR_LZO;
1090                         else if (!strcmp(name, "zlib"))
1091                                 c->mount_opts.compr_type = UBIFS_COMPR_ZLIB;
1092                         else if (!strcmp(name, "zstd"))
1093                                 c->mount_opts.compr_type = UBIFS_COMPR_ZSTD;
1094                         else {
1095                                 ubifs_err(c, "unknown compressor \"%s\"", name); //FIXME: is c ready?
1096                                 kfree(name);
1097                                 return -EINVAL;
1098                         }
1099                         kfree(name);
1100                         c->mount_opts.override_compr = 1;
1101                         c->default_compr = c->mount_opts.compr_type;
1102                         break;
1103                 }
1104                 case Opt_assert:
1105                 {
1106                         char *act = match_strdup(&args[0]);
1107
1108                         if (!act)
1109                                 return -ENOMEM;
1110                         if (!strcmp(act, "report"))
1111                                 c->assert_action = ASSACT_REPORT;
1112                         else if (!strcmp(act, "read-only"))
1113                                 c->assert_action = ASSACT_RO;
1114                         else if (!strcmp(act, "panic"))
1115                                 c->assert_action = ASSACT_PANIC;
1116                         else {
1117                                 ubifs_err(c, "unknown assert action \"%s\"", act);
1118                                 kfree(act);
1119                                 return -EINVAL;
1120                         }
1121                         kfree(act);
1122                         break;
1123                 }
1124                 case Opt_auth_key:
1125                         if (!is_remount) {
1126                                 c->auth_key_name = kstrdup(args[0].from,
1127                                                                 GFP_KERNEL);
1128                                 if (!c->auth_key_name)
1129                                         return -ENOMEM;
1130                         }
1131                         break;
1132                 case Opt_auth_hash_name:
1133                         if (!is_remount) {
1134                                 c->auth_hash_name = kstrdup(args[0].from,
1135                                                                 GFP_KERNEL);
1136                                 if (!c->auth_hash_name)
1137                                         return -ENOMEM;
1138                         }
1139                         break;
1140                 case Opt_ignore:
1141                         break;
1142                 default:
1143                 {
1144                         unsigned long flag;
1145                         struct super_block *sb = c->vfs_sb;
1146
1147                         flag = parse_standard_option(p);
1148                         if (!flag) {
1149                                 ubifs_err(c, "unrecognized mount option \"%s\" or missing value",
1150                                           p);
1151                                 return -EINVAL;
1152                         }
1153                         sb->s_flags |= flag;
1154                         break;
1155                 }
1156                 }
1157         }
1158
1159         return 0;
1160 }
1161
1162 /*
1163  * ubifs_release_options - release mount parameters which have been dumped.
1164  * @c: UBIFS file-system description object
1165  */
1166 static void ubifs_release_options(struct ubifs_info *c)
1167 {
1168         kfree(c->auth_key_name);
1169         c->auth_key_name = NULL;
1170         kfree(c->auth_hash_name);
1171         c->auth_hash_name = NULL;
1172 }
1173
1174 /**
1175  * destroy_journal - destroy journal data structures.
1176  * @c: UBIFS file-system description object
1177  *
1178  * This function destroys journal data structures including those that may have
1179  * been created by recovery functions.
1180  */
1181 static void destroy_journal(struct ubifs_info *c)
1182 {
1183         while (!list_empty(&c->unclean_leb_list)) {
1184                 struct ubifs_unclean_leb *ucleb;
1185
1186                 ucleb = list_entry(c->unclean_leb_list.next,
1187                                    struct ubifs_unclean_leb, list);
1188                 list_del(&ucleb->list);
1189                 kfree(ucleb);
1190         }
1191         while (!list_empty(&c->old_buds)) {
1192                 struct ubifs_bud *bud;
1193
1194                 bud = list_entry(c->old_buds.next, struct ubifs_bud, list);
1195                 list_del(&bud->list);
1196                 kfree(bud);
1197         }
1198         ubifs_destroy_idx_gc(c);
1199         ubifs_destroy_size_tree(c);
1200         ubifs_tnc_close(c);
1201         free_buds(c);
1202 }
1203
1204 /**
1205  * bu_init - initialize bulk-read information.
1206  * @c: UBIFS file-system description object
1207  */
1208 static void bu_init(struct ubifs_info *c)
1209 {
1210         ubifs_assert(c, c->bulk_read == 1);
1211
1212         if (c->bu.buf)
1213                 return; /* Already initialized */
1214
1215 again:
1216         c->bu.buf = kmalloc(c->max_bu_buf_len, GFP_KERNEL | __GFP_NOWARN);
1217         if (!c->bu.buf) {
1218                 if (c->max_bu_buf_len > UBIFS_KMALLOC_OK) {
1219                         c->max_bu_buf_len = UBIFS_KMALLOC_OK;
1220                         goto again;
1221                 }
1222
1223                 /* Just disable bulk-read */
1224                 ubifs_warn(c, "cannot allocate %d bytes of memory for bulk-read, disabling it",
1225                            c->max_bu_buf_len);
1226                 c->mount_opts.bulk_read = 1;
1227                 c->bulk_read = 0;
1228                 return;
1229         }
1230 }
1231
1232 /**
1233  * check_free_space - check if there is enough free space to mount.
1234  * @c: UBIFS file-system description object
1235  *
1236  * This function makes sure UBIFS has enough free space to be mounted in
1237  * read/write mode. UBIFS must always have some free space to allow deletions.
1238  */
1239 static int check_free_space(struct ubifs_info *c)
1240 {
1241         ubifs_assert(c, c->dark_wm > 0);
1242         if (c->lst.total_free + c->lst.total_dirty < c->dark_wm) {
1243                 ubifs_err(c, "insufficient free space to mount in R/W mode");
1244                 ubifs_dump_budg(c, &c->bi);
1245                 ubifs_dump_lprops(c);
1246                 return -ENOSPC;
1247         }
1248         return 0;
1249 }
1250
1251 /**
1252  * mount_ubifs - mount UBIFS file-system.
1253  * @c: UBIFS file-system description object
1254  *
1255  * This function mounts UBIFS file system. Returns zero in case of success and
1256  * a negative error code in case of failure.
1257  */
1258 static int mount_ubifs(struct ubifs_info *c)
1259 {
1260         int err;
1261         long long x, y;
1262         size_t sz;
1263
1264         c->ro_mount = !!sb_rdonly(c->vfs_sb);
1265         /* Suppress error messages while probing if SB_SILENT is set */
1266         c->probing = !!(c->vfs_sb->s_flags & SB_SILENT);
1267
1268         err = init_constants_early(c);
1269         if (err)
1270                 return err;
1271
1272         err = ubifs_debugging_init(c);
1273         if (err)
1274                 return err;
1275
1276         err = check_volume_empty(c);
1277         if (err)
1278                 goto out_free;
1279
1280         if (c->empty && (c->ro_mount || c->ro_media)) {
1281                 /*
1282                  * This UBI volume is empty, and read-only, or the file system
1283                  * is mounted read-only - we cannot format it.
1284                  */
1285                 ubifs_err(c, "can't format empty UBI volume: read-only %s",
1286                           c->ro_media ? "UBI volume" : "mount");
1287                 err = -EROFS;
1288                 goto out_free;
1289         }
1290
1291         if (c->ro_media && !c->ro_mount) {
1292                 ubifs_err(c, "cannot mount read-write - read-only media");
1293                 err = -EROFS;
1294                 goto out_free;
1295         }
1296
1297         /*
1298          * The requirement for the buffer is that it should fit indexing B-tree
1299          * height amount of integers. We assume the height if the TNC tree will
1300          * never exceed 64.
1301          */
1302         err = -ENOMEM;
1303         c->bottom_up_buf = kmalloc_array(BOTTOM_UP_HEIGHT, sizeof(int),
1304                                          GFP_KERNEL);
1305         if (!c->bottom_up_buf)
1306                 goto out_free;
1307
1308         c->sbuf = vmalloc(c->leb_size);
1309         if (!c->sbuf)
1310                 goto out_free;
1311
1312         if (!c->ro_mount) {
1313                 c->ileb_buf = vmalloc(c->leb_size);
1314                 if (!c->ileb_buf)
1315                         goto out_free;
1316         }
1317
1318         if (c->bulk_read == 1)
1319                 bu_init(c);
1320
1321         if (!c->ro_mount) {
1322                 c->write_reserve_buf = kmalloc(COMPRESSED_DATA_NODE_BUF_SZ + \
1323                                                UBIFS_CIPHER_BLOCK_SIZE,
1324                                                GFP_KERNEL);
1325                 if (!c->write_reserve_buf)
1326                         goto out_free;
1327         }
1328
1329         c->mounting = 1;
1330
1331         if (c->auth_key_name) {
1332                 if (IS_ENABLED(CONFIG_UBIFS_FS_AUTHENTICATION)) {
1333                         err = ubifs_init_authentication(c);
1334                         if (err)
1335                                 goto out_free;
1336                 } else {
1337                         ubifs_err(c, "auth_key_name, but UBIFS is built without"
1338                                   " authentication support");
1339                         err = -EINVAL;
1340                         goto out_free;
1341                 }
1342         }
1343
1344         err = ubifs_read_superblock(c);
1345         if (err)
1346                 goto out_auth;
1347
1348         c->probing = 0;
1349
1350         /*
1351          * Make sure the compressor which is set as default in the superblock
1352          * or overridden by mount options is actually compiled in.
1353          */
1354         if (!ubifs_compr_present(c, c->default_compr)) {
1355                 ubifs_err(c, "'compressor \"%s\" is not compiled in",
1356                           ubifs_compr_name(c, c->default_compr));
1357                 err = -ENOTSUPP;
1358                 goto out_auth;
1359         }
1360
1361         err = init_constants_sb(c);
1362         if (err)
1363                 goto out_auth;
1364
1365         sz = ALIGN(c->max_idx_node_sz, c->min_io_size) * 2;
1366         c->cbuf = kmalloc(sz, GFP_NOFS);
1367         if (!c->cbuf) {
1368                 err = -ENOMEM;
1369                 goto out_auth;
1370         }
1371
1372         err = alloc_wbufs(c);
1373         if (err)
1374                 goto out_cbuf;
1375
1376         sprintf(c->bgt_name, BGT_NAME_PATTERN, c->vi.ubi_num, c->vi.vol_id);
1377         if (!c->ro_mount) {
1378                 /* Create background thread */
1379                 c->bgt = kthread_create(ubifs_bg_thread, c, "%s", c->bgt_name);
1380                 if (IS_ERR(c->bgt)) {
1381                         err = PTR_ERR(c->bgt);
1382                         c->bgt = NULL;
1383                         ubifs_err(c, "cannot spawn \"%s\", error %d",
1384                                   c->bgt_name, err);
1385                         goto out_wbufs;
1386                 }
1387                 wake_up_process(c->bgt);
1388         }
1389
1390         err = ubifs_read_master(c);
1391         if (err)
1392                 goto out_master;
1393
1394         init_constants_master(c);
1395
1396         if ((c->mst_node->flags & cpu_to_le32(UBIFS_MST_DIRTY)) != 0) {
1397                 ubifs_msg(c, "recovery needed");
1398                 c->need_recovery = 1;
1399         }
1400
1401         if (c->need_recovery && !c->ro_mount) {
1402                 err = ubifs_recover_inl_heads(c, c->sbuf);
1403                 if (err)
1404                         goto out_master;
1405         }
1406
1407         err = ubifs_lpt_init(c, 1, !c->ro_mount);
1408         if (err)
1409                 goto out_master;
1410
1411         if (!c->ro_mount && c->space_fixup) {
1412                 err = ubifs_fixup_free_space(c);
1413                 if (err)
1414                         goto out_lpt;
1415         }
1416
1417         if (!c->ro_mount && !c->need_recovery) {
1418                 /*
1419                  * Set the "dirty" flag so that if we reboot uncleanly we
1420                  * will notice this immediately on the next mount.
1421                  */
1422                 c->mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY);
1423                 err = ubifs_write_master(c);
1424                 if (err)
1425                         goto out_lpt;
1426         }
1427
1428         /*
1429          * Handle offline signed images: Now that the master node is
1430          * written and its validation no longer depends on the hash
1431          * in the superblock, we can update the offline signed
1432          * superblock with a HMAC version,
1433          */
1434         if (ubifs_authenticated(c) && ubifs_hmac_zero(c, c->sup_node->hmac)) {
1435                 err = ubifs_hmac_wkm(c, c->sup_node->hmac_wkm);
1436                 if (err)
1437                         goto out_lpt;
1438                 c->superblock_need_write = 1;
1439         }
1440
1441         if (!c->ro_mount && c->superblock_need_write) {
1442                 err = ubifs_write_sb_node(c, c->sup_node);
1443                 if (err)
1444                         goto out_lpt;
1445                 c->superblock_need_write = 0;
1446         }
1447
1448         err = dbg_check_idx_size(c, c->bi.old_idx_sz);
1449         if (err)
1450                 goto out_lpt;
1451
1452         err = ubifs_replay_journal(c);
1453         if (err)
1454                 goto out_journal;
1455
1456         /* Calculate 'min_idx_lebs' after journal replay */
1457         c->bi.min_idx_lebs = ubifs_calc_min_idx_lebs(c);
1458
1459         err = ubifs_mount_orphans(c, c->need_recovery, c->ro_mount);
1460         if (err)
1461                 goto out_orphans;
1462
1463         if (!c->ro_mount) {
1464                 int lnum;
1465
1466                 err = check_free_space(c);
1467                 if (err)
1468                         goto out_orphans;
1469
1470                 /* Check for enough log space */
1471                 lnum = c->lhead_lnum + 1;
1472                 if (lnum >= UBIFS_LOG_LNUM + c->log_lebs)
1473                         lnum = UBIFS_LOG_LNUM;
1474                 if (lnum == c->ltail_lnum) {
1475                         err = ubifs_consolidate_log(c);
1476                         if (err)
1477                                 goto out_orphans;
1478                 }
1479
1480                 if (c->need_recovery) {
1481                         if (!ubifs_authenticated(c)) {
1482                                 err = ubifs_recover_size(c, true);
1483                                 if (err)
1484                                         goto out_orphans;
1485                         }
1486
1487                         err = ubifs_rcvry_gc_commit(c);
1488                         if (err)
1489                                 goto out_orphans;
1490
1491                         if (ubifs_authenticated(c)) {
1492                                 err = ubifs_recover_size(c, false);
1493                                 if (err)
1494                                         goto out_orphans;
1495                         }
1496                 } else {
1497                         err = take_gc_lnum(c);
1498                         if (err)
1499                                 goto out_orphans;
1500
1501                         /*
1502                          * GC LEB may contain garbage if there was an unclean
1503                          * reboot, and it should be un-mapped.
1504                          */
1505                         err = ubifs_leb_unmap(c, c->gc_lnum);
1506                         if (err)
1507                                 goto out_orphans;
1508                 }
1509
1510                 err = dbg_check_lprops(c);
1511                 if (err)
1512                         goto out_orphans;
1513         } else if (c->need_recovery) {
1514                 err = ubifs_recover_size(c, false);
1515                 if (err)
1516                         goto out_orphans;
1517         } else {
1518                 /*
1519                  * Even if we mount read-only, we have to set space in GC LEB
1520                  * to proper value because this affects UBIFS free space
1521                  * reporting. We do not want to have a situation when
1522                  * re-mounting from R/O to R/W changes amount of free space.
1523                  */
1524                 err = take_gc_lnum(c);
1525                 if (err)
1526                         goto out_orphans;
1527         }
1528
1529         spin_lock(&ubifs_infos_lock);
1530         list_add_tail(&c->infos_list, &ubifs_infos);
1531         spin_unlock(&ubifs_infos_lock);
1532
1533         if (c->need_recovery) {
1534                 if (c->ro_mount)
1535                         ubifs_msg(c, "recovery deferred");
1536                 else {
1537                         c->need_recovery = 0;
1538                         ubifs_msg(c, "recovery completed");
1539                         /*
1540                          * GC LEB has to be empty and taken at this point. But
1541                          * the journal head LEBs may also be accounted as
1542                          * "empty taken" if they are empty.
1543                          */
1544                         ubifs_assert(c, c->lst.taken_empty_lebs > 0);
1545                 }
1546         } else
1547                 ubifs_assert(c, c->lst.taken_empty_lebs > 0);
1548
1549         err = dbg_check_filesystem(c);
1550         if (err)
1551                 goto out_infos;
1552
1553         dbg_debugfs_init_fs(c);
1554
1555         c->mounting = 0;
1556
1557         ubifs_msg(c, "UBIFS: mounted UBI device %d, volume %d, name \"%s\"%s",
1558                   c->vi.ubi_num, c->vi.vol_id, c->vi.name,
1559                   c->ro_mount ? ", R/O mode" : "");
1560         x = (long long)c->main_lebs * c->leb_size;
1561         y = (long long)c->log_lebs * c->leb_size + c->max_bud_bytes;
1562         ubifs_msg(c, "LEB size: %d bytes (%d KiB), min./max. I/O unit sizes: %d bytes/%d bytes",
1563                   c->leb_size, c->leb_size >> 10, c->min_io_size,
1564                   c->max_write_size);
1565         ubifs_msg(c, "FS size: %lld bytes (%lld MiB, %d LEBs), max %d LEBs, journal size %lld bytes (%lld MiB, %d LEBs)",
1566                   x, x >> 20, c->main_lebs, c->max_leb_cnt,
1567                   y, y >> 20, c->log_lebs + c->max_bud_cnt);
1568         ubifs_msg(c, "reserved for root: %llu bytes (%llu KiB)",
1569                   c->report_rp_size, c->report_rp_size >> 10);
1570         ubifs_msg(c, "media format: w%d/r%d (latest is w%d/r%d), UUID %pUB%s",
1571                   c->fmt_version, c->ro_compat_version,
1572                   UBIFS_FORMAT_VERSION, UBIFS_RO_COMPAT_VERSION, c->uuid,
1573                   c->big_lpt ? ", big LPT model" : ", small LPT model");
1574
1575         dbg_gen("default compressor:  %s", ubifs_compr_name(c, c->default_compr));
1576         dbg_gen("data journal heads:  %d",
1577                 c->jhead_cnt - NONDATA_JHEADS_CNT);
1578         dbg_gen("log LEBs:            %d (%d - %d)",
1579                 c->log_lebs, UBIFS_LOG_LNUM, c->log_last);
1580         dbg_gen("LPT area LEBs:       %d (%d - %d)",
1581                 c->lpt_lebs, c->lpt_first, c->lpt_last);
1582         dbg_gen("orphan area LEBs:    %d (%d - %d)",
1583                 c->orph_lebs, c->orph_first, c->orph_last);
1584         dbg_gen("main area LEBs:      %d (%d - %d)",
1585                 c->main_lebs, c->main_first, c->leb_cnt - 1);
1586         dbg_gen("index LEBs:          %d", c->lst.idx_lebs);
1587         dbg_gen("total index bytes:   %llu (%llu KiB, %llu MiB)",
1588                 c->bi.old_idx_sz, c->bi.old_idx_sz >> 10,
1589                 c->bi.old_idx_sz >> 20);
1590         dbg_gen("key hash type:       %d", c->key_hash_type);
1591         dbg_gen("tree fanout:         %d", c->fanout);
1592         dbg_gen("reserved GC LEB:     %d", c->gc_lnum);
1593         dbg_gen("max. znode size      %d", c->max_znode_sz);
1594         dbg_gen("max. index node size %d", c->max_idx_node_sz);
1595         dbg_gen("node sizes:          data %zu, inode %zu, dentry %zu",
1596                 UBIFS_DATA_NODE_SZ, UBIFS_INO_NODE_SZ, UBIFS_DENT_NODE_SZ);
1597         dbg_gen("node sizes:          trun %zu, sb %zu, master %zu",
1598                 UBIFS_TRUN_NODE_SZ, UBIFS_SB_NODE_SZ, UBIFS_MST_NODE_SZ);
1599         dbg_gen("node sizes:          ref %zu, cmt. start %zu, orph %zu",
1600                 UBIFS_REF_NODE_SZ, UBIFS_CS_NODE_SZ, UBIFS_ORPH_NODE_SZ);
1601         dbg_gen("max. node sizes:     data %zu, inode %zu dentry %zu, idx %d",
1602                 UBIFS_MAX_DATA_NODE_SZ, UBIFS_MAX_INO_NODE_SZ,
1603                 UBIFS_MAX_DENT_NODE_SZ, ubifs_idx_node_sz(c, c->fanout));
1604         dbg_gen("dead watermark:      %d", c->dead_wm);
1605         dbg_gen("dark watermark:      %d", c->dark_wm);
1606         dbg_gen("LEB overhead:        %d", c->leb_overhead);
1607         x = (long long)c->main_lebs * c->dark_wm;
1608         dbg_gen("max. dark space:     %lld (%lld KiB, %lld MiB)",
1609                 x, x >> 10, x >> 20);
1610         dbg_gen("maximum bud bytes:   %lld (%lld KiB, %lld MiB)",
1611                 c->max_bud_bytes, c->max_bud_bytes >> 10,
1612                 c->max_bud_bytes >> 20);
1613         dbg_gen("BG commit bud bytes: %lld (%lld KiB, %lld MiB)",
1614                 c->bg_bud_bytes, c->bg_bud_bytes >> 10,
1615                 c->bg_bud_bytes >> 20);
1616         dbg_gen("current bud bytes    %lld (%lld KiB, %lld MiB)",
1617                 c->bud_bytes, c->bud_bytes >> 10, c->bud_bytes >> 20);
1618         dbg_gen("max. seq. number:    %llu", c->max_sqnum);
1619         dbg_gen("commit number:       %llu", c->cmt_no);
1620         dbg_gen("max. xattrs per inode: %d", ubifs_xattr_max_cnt(c));
1621         dbg_gen("max orphans:           %d", c->max_orphans);
1622
1623         return 0;
1624
1625 out_infos:
1626         spin_lock(&ubifs_infos_lock);
1627         list_del(&c->infos_list);
1628         spin_unlock(&ubifs_infos_lock);
1629 out_orphans:
1630         free_orphans(c);
1631 out_journal:
1632         destroy_journal(c);
1633 out_lpt:
1634         ubifs_lpt_free(c, 0);
1635 out_master:
1636         kfree(c->mst_node);
1637         kfree(c->rcvrd_mst_node);
1638         if (c->bgt)
1639                 kthread_stop(c->bgt);
1640 out_wbufs:
1641         free_wbufs(c);
1642 out_cbuf:
1643         kfree(c->cbuf);
1644 out_auth:
1645         ubifs_exit_authentication(c);
1646 out_free:
1647         kfree(c->write_reserve_buf);
1648         kfree(c->bu.buf);
1649         vfree(c->ileb_buf);
1650         vfree(c->sbuf);
1651         kfree(c->bottom_up_buf);
1652         kfree(c->sup_node);
1653         ubifs_debugging_exit(c);
1654         return err;
1655 }
1656
1657 /**
1658  * ubifs_umount - un-mount UBIFS file-system.
1659  * @c: UBIFS file-system description object
1660  *
1661  * Note, this function is called to free allocated resourced when un-mounting,
1662  * as well as free resources when an error occurred while we were half way
1663  * through mounting (error path cleanup function). So it has to make sure the
1664  * resource was actually allocated before freeing it.
1665  */
1666 static void ubifs_umount(struct ubifs_info *c)
1667 {
1668         dbg_gen("un-mounting UBI device %d, volume %d", c->vi.ubi_num,
1669                 c->vi.vol_id);
1670
1671         dbg_debugfs_exit_fs(c);
1672         spin_lock(&ubifs_infos_lock);
1673         list_del(&c->infos_list);
1674         spin_unlock(&ubifs_infos_lock);
1675
1676         if (c->bgt)
1677                 kthread_stop(c->bgt);
1678
1679         destroy_journal(c);
1680         free_wbufs(c);
1681         free_orphans(c);
1682         ubifs_lpt_free(c, 0);
1683         ubifs_exit_authentication(c);
1684
1685         ubifs_release_options(c);
1686         kfree(c->cbuf);
1687         kfree(c->rcvrd_mst_node);
1688         kfree(c->mst_node);
1689         kfree(c->write_reserve_buf);
1690         kfree(c->bu.buf);
1691         vfree(c->ileb_buf);
1692         vfree(c->sbuf);
1693         kfree(c->bottom_up_buf);
1694         kfree(c->sup_node);
1695         ubifs_debugging_exit(c);
1696 }
1697
1698 /**
1699  * ubifs_remount_rw - re-mount in read-write mode.
1700  * @c: UBIFS file-system description object
1701  *
1702  * UBIFS avoids allocating many unnecessary resources when mounted in read-only
1703  * mode. This function allocates the needed resources and re-mounts UBIFS in
1704  * read-write mode.
1705  */
1706 static int ubifs_remount_rw(struct ubifs_info *c)
1707 {
1708         int err, lnum;
1709
1710         if (c->rw_incompat) {
1711                 ubifs_err(c, "the file-system is not R/W-compatible");
1712                 ubifs_msg(c, "on-flash format version is w%d/r%d, but software only supports up to version w%d/r%d",
1713                           c->fmt_version, c->ro_compat_version,
1714                           UBIFS_FORMAT_VERSION, UBIFS_RO_COMPAT_VERSION);
1715                 return -EROFS;
1716         }
1717
1718         mutex_lock(&c->umount_mutex);
1719         dbg_save_space_info(c);
1720         c->remounting_rw = 1;
1721         c->ro_mount = 0;
1722
1723         if (c->space_fixup) {
1724                 err = ubifs_fixup_free_space(c);
1725                 if (err)
1726                         goto out;
1727         }
1728
1729         err = check_free_space(c);
1730         if (err)
1731                 goto out;
1732
1733         if (c->need_recovery) {
1734                 ubifs_msg(c, "completing deferred recovery");
1735                 err = ubifs_write_rcvrd_mst_node(c);
1736                 if (err)
1737                         goto out;
1738                 if (!ubifs_authenticated(c)) {
1739                         err = ubifs_recover_size(c, true);
1740                         if (err)
1741                                 goto out;
1742                 }
1743                 err = ubifs_clean_lebs(c, c->sbuf);
1744                 if (err)
1745                         goto out;
1746                 err = ubifs_recover_inl_heads(c, c->sbuf);
1747                 if (err)
1748                         goto out;
1749         } else {
1750                 /* A readonly mount is not allowed to have orphans */
1751                 ubifs_assert(c, c->tot_orphans == 0);
1752                 err = ubifs_clear_orphans(c);
1753                 if (err)
1754                         goto out;
1755         }
1756
1757         if (!(c->mst_node->flags & cpu_to_le32(UBIFS_MST_DIRTY))) {
1758                 c->mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY);
1759                 err = ubifs_write_master(c);
1760                 if (err)
1761                         goto out;
1762         }
1763
1764         if (c->superblock_need_write) {
1765                 struct ubifs_sb_node *sup = c->sup_node;
1766
1767                 err = ubifs_write_sb_node(c, sup);
1768                 if (err)
1769                         goto out;
1770
1771                 c->superblock_need_write = 0;
1772         }
1773
1774         c->ileb_buf = vmalloc(c->leb_size);
1775         if (!c->ileb_buf) {
1776                 err = -ENOMEM;
1777                 goto out;
1778         }
1779
1780         c->write_reserve_buf = kmalloc(COMPRESSED_DATA_NODE_BUF_SZ + \
1781                                        UBIFS_CIPHER_BLOCK_SIZE, GFP_KERNEL);
1782         if (!c->write_reserve_buf) {
1783                 err = -ENOMEM;
1784                 goto out;
1785         }
1786
1787         err = ubifs_lpt_init(c, 0, 1);
1788         if (err)
1789                 goto out;
1790
1791         /* Create background thread */
1792         c->bgt = kthread_create(ubifs_bg_thread, c, "%s", c->bgt_name);
1793         if (IS_ERR(c->bgt)) {
1794                 err = PTR_ERR(c->bgt);
1795                 c->bgt = NULL;
1796                 ubifs_err(c, "cannot spawn \"%s\", error %d",
1797                           c->bgt_name, err);
1798                 goto out;
1799         }
1800         wake_up_process(c->bgt);
1801
1802         c->orph_buf = vmalloc(c->leb_size);
1803         if (!c->orph_buf) {
1804                 err = -ENOMEM;
1805                 goto out;
1806         }
1807
1808         /* Check for enough log space */
1809         lnum = c->lhead_lnum + 1;
1810         if (lnum >= UBIFS_LOG_LNUM + c->log_lebs)
1811                 lnum = UBIFS_LOG_LNUM;
1812         if (lnum == c->ltail_lnum) {
1813                 err = ubifs_consolidate_log(c);
1814                 if (err)
1815                         goto out;
1816         }
1817
1818         if (c->need_recovery) {
1819                 err = ubifs_rcvry_gc_commit(c);
1820                 if (err)
1821                         goto out;
1822
1823                 if (ubifs_authenticated(c)) {
1824                         err = ubifs_recover_size(c, false);
1825                         if (err)
1826                                 goto out;
1827                 }
1828         } else {
1829                 err = ubifs_leb_unmap(c, c->gc_lnum);
1830         }
1831         if (err)
1832                 goto out;
1833
1834         dbg_gen("re-mounted read-write");
1835         c->remounting_rw = 0;
1836
1837         if (c->need_recovery) {
1838                 c->need_recovery = 0;
1839                 ubifs_msg(c, "deferred recovery completed");
1840         } else {
1841                 /*
1842                  * Do not run the debugging space check if the were doing
1843                  * recovery, because when we saved the information we had the
1844                  * file-system in a state where the TNC and lprops has been
1845                  * modified in memory, but all the I/O operations (including a
1846                  * commit) were deferred. So the file-system was in
1847                  * "non-committed" state. Now the file-system is in committed
1848                  * state, and of course the amount of free space will change
1849                  * because, for example, the old index size was imprecise.
1850                  */
1851                 err = dbg_check_space_info(c);
1852         }
1853
1854         mutex_unlock(&c->umount_mutex);
1855         return err;
1856
1857 out:
1858         c->ro_mount = 1;
1859         vfree(c->orph_buf);
1860         c->orph_buf = NULL;
1861         if (c->bgt) {
1862                 kthread_stop(c->bgt);
1863                 c->bgt = NULL;
1864         }
1865         kfree(c->write_reserve_buf);
1866         c->write_reserve_buf = NULL;
1867         vfree(c->ileb_buf);
1868         c->ileb_buf = NULL;
1869         ubifs_lpt_free(c, 1);
1870         c->remounting_rw = 0;
1871         mutex_unlock(&c->umount_mutex);
1872         return err;
1873 }
1874
1875 /**
1876  * ubifs_remount_ro - re-mount in read-only mode.
1877  * @c: UBIFS file-system description object
1878  *
1879  * We assume VFS has stopped writing. Possibly the background thread could be
1880  * running a commit, however kthread_stop will wait in that case.
1881  */
1882 static void ubifs_remount_ro(struct ubifs_info *c)
1883 {
1884         int i, err;
1885
1886         ubifs_assert(c, !c->need_recovery);
1887         ubifs_assert(c, !c->ro_mount);
1888
1889         mutex_lock(&c->umount_mutex);
1890         if (c->bgt) {
1891                 kthread_stop(c->bgt);
1892                 c->bgt = NULL;
1893         }
1894
1895         dbg_save_space_info(c);
1896
1897         for (i = 0; i < c->jhead_cnt; i++) {
1898                 err = ubifs_wbuf_sync(&c->jheads[i].wbuf);
1899                 if (err)
1900                         ubifs_ro_mode(c, err);
1901         }
1902
1903         c->mst_node->flags &= ~cpu_to_le32(UBIFS_MST_DIRTY);
1904         c->mst_node->flags |= cpu_to_le32(UBIFS_MST_NO_ORPHS);
1905         c->mst_node->gc_lnum = cpu_to_le32(c->gc_lnum);
1906         err = ubifs_write_master(c);
1907         if (err)
1908                 ubifs_ro_mode(c, err);
1909
1910         vfree(c->orph_buf);
1911         c->orph_buf = NULL;
1912         kfree(c->write_reserve_buf);
1913         c->write_reserve_buf = NULL;
1914         vfree(c->ileb_buf);
1915         c->ileb_buf = NULL;
1916         ubifs_lpt_free(c, 1);
1917         c->ro_mount = 1;
1918         err = dbg_check_space_info(c);
1919         if (err)
1920                 ubifs_ro_mode(c, err);
1921         mutex_unlock(&c->umount_mutex);
1922 }
1923
1924 static void ubifs_put_super(struct super_block *sb)
1925 {
1926         int i;
1927         struct ubifs_info *c = sb->s_fs_info;
1928
1929         ubifs_msg(c, "un-mount UBI device %d", c->vi.ubi_num);
1930
1931         /*
1932          * The following asserts are only valid if there has not been a failure
1933          * of the media. For example, there will be dirty inodes if we failed
1934          * to write them back because of I/O errors.
1935          */
1936         if (!c->ro_error) {
1937                 ubifs_assert(c, c->bi.idx_growth == 0);
1938                 ubifs_assert(c, c->bi.dd_growth == 0);
1939                 ubifs_assert(c, c->bi.data_growth == 0);
1940         }
1941
1942         /*
1943          * The 'c->umount_lock' prevents races between UBIFS memory shrinker
1944          * and file system un-mount. Namely, it prevents the shrinker from
1945          * picking this superblock for shrinking - it will be just skipped if
1946          * the mutex is locked.
1947          */
1948         mutex_lock(&c->umount_mutex);
1949         if (!c->ro_mount) {
1950                 /*
1951                  * First of all kill the background thread to make sure it does
1952                  * not interfere with un-mounting and freeing resources.
1953                  */
1954                 if (c->bgt) {
1955                         kthread_stop(c->bgt);
1956                         c->bgt = NULL;
1957                 }
1958
1959                 /*
1960                  * On fatal errors c->ro_error is set to 1, in which case we do
1961                  * not write the master node.
1962                  */
1963                 if (!c->ro_error) {
1964                         int err;
1965
1966                         /* Synchronize write-buffers */
1967                         for (i = 0; i < c->jhead_cnt; i++) {
1968                                 err = ubifs_wbuf_sync(&c->jheads[i].wbuf);
1969                                 if (err)
1970                                         ubifs_ro_mode(c, err);
1971                         }
1972
1973                         /*
1974                          * We are being cleanly unmounted which means the
1975                          * orphans were killed - indicate this in the master
1976                          * node. Also save the reserved GC LEB number.
1977                          */
1978                         c->mst_node->flags &= ~cpu_to_le32(UBIFS_MST_DIRTY);
1979                         c->mst_node->flags |= cpu_to_le32(UBIFS_MST_NO_ORPHS);
1980                         c->mst_node->gc_lnum = cpu_to_le32(c->gc_lnum);
1981                         err = ubifs_write_master(c);
1982                         if (err)
1983                                 /*
1984                                  * Recovery will attempt to fix the master area
1985                                  * next mount, so we just print a message and
1986                                  * continue to unmount normally.
1987                                  */
1988                                 ubifs_err(c, "failed to write master node, error %d",
1989                                           err);
1990                 } else {
1991                         for (i = 0; i < c->jhead_cnt; i++)
1992                                 /* Make sure write-buffer timers are canceled */
1993                                 hrtimer_cancel(&c->jheads[i].wbuf.timer);
1994                 }
1995         }
1996
1997         ubifs_umount(c);
1998         ubi_close_volume(c->ubi);
1999         mutex_unlock(&c->umount_mutex);
2000 }
2001
2002 static int ubifs_remount_fs(struct super_block *sb, int *flags, char *data)
2003 {
2004         int err;
2005         struct ubifs_info *c = sb->s_fs_info;
2006
2007         sync_filesystem(sb);
2008         dbg_gen("old flags %#lx, new flags %#x", sb->s_flags, *flags);
2009
2010         err = ubifs_parse_options(c, data, 1);
2011         if (err) {
2012                 ubifs_err(c, "invalid or unknown remount parameter");
2013                 return err;
2014         }
2015
2016         if (c->ro_mount && !(*flags & SB_RDONLY)) {
2017                 if (c->ro_error) {
2018                         ubifs_msg(c, "cannot re-mount R/W due to prior errors");
2019                         return -EROFS;
2020                 }
2021                 if (c->ro_media) {
2022                         ubifs_msg(c, "cannot re-mount R/W - UBI volume is R/O");
2023                         return -EROFS;
2024                 }
2025                 err = ubifs_remount_rw(c);
2026                 if (err)
2027                         return err;
2028         } else if (!c->ro_mount && (*flags & SB_RDONLY)) {
2029                 if (c->ro_error) {
2030                         ubifs_msg(c, "cannot re-mount R/O due to prior errors");
2031                         return -EROFS;
2032                 }
2033                 ubifs_remount_ro(c);
2034         }
2035
2036         if (c->bulk_read == 1)
2037                 bu_init(c);
2038         else {
2039                 dbg_gen("disable bulk-read");
2040                 mutex_lock(&c->bu_mutex);
2041                 kfree(c->bu.buf);
2042                 c->bu.buf = NULL;
2043                 mutex_unlock(&c->bu_mutex);
2044         }
2045
2046         if (!c->need_recovery)
2047                 ubifs_assert(c, c->lst.taken_empty_lebs > 0);
2048
2049         return 0;
2050 }
2051
2052 const struct super_operations ubifs_super_operations = {
2053         .alloc_inode   = ubifs_alloc_inode,
2054         .free_inode    = ubifs_free_inode,
2055         .put_super     = ubifs_put_super,
2056         .write_inode   = ubifs_write_inode,
2057         .drop_inode    = ubifs_drop_inode,
2058         .evict_inode   = ubifs_evict_inode,
2059         .statfs        = ubifs_statfs,
2060         .dirty_inode   = ubifs_dirty_inode,
2061         .remount_fs    = ubifs_remount_fs,
2062         .show_options  = ubifs_show_options,
2063         .sync_fs       = ubifs_sync_fs,
2064 };
2065
2066 /**
2067  * open_ubi - parse UBI device name string and open the UBI device.
2068  * @name: UBI volume name
2069  * @mode: UBI volume open mode
2070  *
2071  * The primary method of mounting UBIFS is by specifying the UBI volume
2072  * character device node path. However, UBIFS may also be mounted without any
2073  * character device node using one of the following methods:
2074  *
2075  * o ubiX_Y    - mount UBI device number X, volume Y;
2076  * o ubiY      - mount UBI device number 0, volume Y;
2077  * o ubiX:NAME - mount UBI device X, volume with name NAME;
2078  * o ubi:NAME  - mount UBI device 0, volume with name NAME.
2079  *
2080  * Alternative '!' separator may be used instead of ':' (because some shells
2081  * like busybox may interpret ':' as an NFS host name separator). This function
2082  * returns UBI volume description object in case of success and a negative
2083  * error code in case of failure.
2084  */
2085 static struct ubi_volume_desc *open_ubi(const char *name, int mode)
2086 {
2087         struct ubi_volume_desc *ubi;
2088         int dev, vol;
2089         char *endptr;
2090
2091         if (!name || !*name)
2092                 return ERR_PTR(-EINVAL);
2093
2094         /* First, try to open using the device node path method */
2095         ubi = ubi_open_volume_path(name, mode);
2096         if (!IS_ERR(ubi))
2097                 return ubi;
2098
2099         /* Try the "nodev" method */
2100         if (name[0] != 'u' || name[1] != 'b' || name[2] != 'i')
2101                 return ERR_PTR(-EINVAL);
2102
2103         /* ubi:NAME method */
2104         if ((name[3] == ':' || name[3] == '!') && name[4] != '\0')
2105                 return ubi_open_volume_nm(0, name + 4, mode);
2106
2107         if (!isdigit(name[3]))
2108                 return ERR_PTR(-EINVAL);
2109
2110         dev = simple_strtoul(name + 3, &endptr, 0);
2111
2112         /* ubiY method */
2113         if (*endptr == '\0')
2114                 return ubi_open_volume(0, dev, mode);
2115
2116         /* ubiX_Y method */
2117         if (*endptr == '_' && isdigit(endptr[1])) {
2118                 vol = simple_strtoul(endptr + 1, &endptr, 0);
2119                 if (*endptr != '\0')
2120                         return ERR_PTR(-EINVAL);
2121                 return ubi_open_volume(dev, vol, mode);
2122         }
2123
2124         /* ubiX:NAME method */
2125         if ((*endptr == ':' || *endptr == '!') && endptr[1] != '\0')
2126                 return ubi_open_volume_nm(dev, ++endptr, mode);
2127
2128         return ERR_PTR(-EINVAL);
2129 }
2130
2131 static struct ubifs_info *alloc_ubifs_info(struct ubi_volume_desc *ubi)
2132 {
2133         struct ubifs_info *c;
2134
2135         c = kzalloc(sizeof(struct ubifs_info), GFP_KERNEL);
2136         if (c) {
2137                 spin_lock_init(&c->cnt_lock);
2138                 spin_lock_init(&c->cs_lock);
2139                 spin_lock_init(&c->buds_lock);
2140                 spin_lock_init(&c->space_lock);
2141                 spin_lock_init(&c->orphan_lock);
2142                 init_rwsem(&c->commit_sem);
2143                 mutex_init(&c->lp_mutex);
2144                 mutex_init(&c->tnc_mutex);
2145                 mutex_init(&c->log_mutex);
2146                 mutex_init(&c->umount_mutex);
2147                 mutex_init(&c->bu_mutex);
2148                 mutex_init(&c->write_reserve_mutex);
2149                 init_waitqueue_head(&c->cmt_wq);
2150                 c->buds = RB_ROOT;
2151                 c->old_idx = RB_ROOT;
2152                 c->size_tree = RB_ROOT;
2153                 c->orph_tree = RB_ROOT;
2154                 INIT_LIST_HEAD(&c->infos_list);
2155                 INIT_LIST_HEAD(&c->idx_gc);
2156                 INIT_LIST_HEAD(&c->replay_list);
2157                 INIT_LIST_HEAD(&c->replay_buds);
2158                 INIT_LIST_HEAD(&c->uncat_list);
2159                 INIT_LIST_HEAD(&c->empty_list);
2160                 INIT_LIST_HEAD(&c->freeable_list);
2161                 INIT_LIST_HEAD(&c->frdi_idx_list);
2162                 INIT_LIST_HEAD(&c->unclean_leb_list);
2163                 INIT_LIST_HEAD(&c->old_buds);
2164                 INIT_LIST_HEAD(&c->orph_list);
2165                 INIT_LIST_HEAD(&c->orph_new);
2166                 c->no_chk_data_crc = 1;
2167                 c->assert_action = ASSACT_RO;
2168
2169                 c->highest_inum = UBIFS_FIRST_INO;
2170                 c->lhead_lnum = c->ltail_lnum = UBIFS_LOG_LNUM;
2171
2172                 ubi_get_volume_info(ubi, &c->vi);
2173                 ubi_get_device_info(c->vi.ubi_num, &c->di);
2174         }
2175         return c;
2176 }
2177
2178 static int ubifs_fill_super(struct super_block *sb, void *data, int silent)
2179 {
2180         struct ubifs_info *c = sb->s_fs_info;
2181         struct inode *root;
2182         int err;
2183
2184         c->vfs_sb = sb;
2185         /* Re-open the UBI device in read-write mode */
2186         c->ubi = ubi_open_volume(c->vi.ubi_num, c->vi.vol_id, UBI_READWRITE);
2187         if (IS_ERR(c->ubi)) {
2188                 err = PTR_ERR(c->ubi);
2189                 goto out;
2190         }
2191
2192         err = ubifs_parse_options(c, data, 0);
2193         if (err)
2194                 goto out_close;
2195
2196         /*
2197          * UBIFS provides 'backing_dev_info' in order to disable read-ahead. For
2198          * UBIFS, I/O is not deferred, it is done immediately in readpage,
2199          * which means the user would have to wait not just for their own I/O
2200          * but the read-ahead I/O as well i.e. completely pointless.
2201          *
2202          * Read-ahead will be disabled because @sb->s_bdi->ra_pages is 0. Also
2203          * @sb->s_bdi->capabilities are initialized to 0 so there won't be any
2204          * writeback happening.
2205          */
2206         err = super_setup_bdi_name(sb, "ubifs_%d_%d", c->vi.ubi_num,
2207                                    c->vi.vol_id);
2208         if (err)
2209                 goto out_close;
2210         sb->s_bdi->ra_pages = 0;
2211         sb->s_bdi->io_pages = 0;
2212
2213         sb->s_fs_info = c;
2214         sb->s_magic = UBIFS_SUPER_MAGIC;
2215         sb->s_blocksize = UBIFS_BLOCK_SIZE;
2216         sb->s_blocksize_bits = UBIFS_BLOCK_SHIFT;
2217         sb->s_maxbytes = c->max_inode_sz = key_max_inode_size(c);
2218         if (c->max_inode_sz > MAX_LFS_FILESIZE)
2219                 sb->s_maxbytes = c->max_inode_sz = MAX_LFS_FILESIZE;
2220         sb->s_op = &ubifs_super_operations;
2221         sb->s_xattr = ubifs_xattr_handlers;
2222         fscrypt_set_ops(sb, &ubifs_crypt_operations);
2223
2224         mutex_lock(&c->umount_mutex);
2225         err = mount_ubifs(c);
2226         if (err) {
2227                 ubifs_assert(c, err < 0);
2228                 goto out_unlock;
2229         }
2230
2231         /* Read the root inode */
2232         root = ubifs_iget(sb, UBIFS_ROOT_INO);
2233         if (IS_ERR(root)) {
2234                 err = PTR_ERR(root);
2235                 goto out_umount;
2236         }
2237
2238         sb->s_root = d_make_root(root);
2239         if (!sb->s_root) {
2240                 err = -ENOMEM;
2241                 goto out_umount;
2242         }
2243
2244         import_uuid(&sb->s_uuid, c->uuid);
2245
2246         mutex_unlock(&c->umount_mutex);
2247         return 0;
2248
2249 out_umount:
2250         ubifs_umount(c);
2251 out_unlock:
2252         mutex_unlock(&c->umount_mutex);
2253 out_close:
2254         ubifs_release_options(c);
2255         ubi_close_volume(c->ubi);
2256 out:
2257         return err;
2258 }
2259
2260 static int sb_test(struct super_block *sb, void *data)
2261 {
2262         struct ubifs_info *c1 = data;
2263         struct ubifs_info *c = sb->s_fs_info;
2264
2265         return c->vi.cdev == c1->vi.cdev;
2266 }
2267
2268 static int sb_set(struct super_block *sb, void *data)
2269 {
2270         sb->s_fs_info = data;
2271         return set_anon_super(sb, NULL);
2272 }
2273
2274 static struct dentry *ubifs_mount(struct file_system_type *fs_type, int flags,
2275                         const char *name, void *data)
2276 {
2277         struct ubi_volume_desc *ubi;
2278         struct ubifs_info *c;
2279         struct super_block *sb;
2280         int err;
2281
2282         dbg_gen("name %s, flags %#x", name, flags);
2283
2284         /*
2285          * Get UBI device number and volume ID. Mount it read-only so far
2286          * because this might be a new mount point, and UBI allows only one
2287          * read-write user at a time.
2288          */
2289         ubi = open_ubi(name, UBI_READONLY);
2290         if (IS_ERR(ubi)) {
2291                 if (!(flags & SB_SILENT))
2292                         pr_err("UBIFS error (pid: %d): cannot open \"%s\", error %d",
2293                                current->pid, name, (int)PTR_ERR(ubi));
2294                 return ERR_CAST(ubi);
2295         }
2296
2297         c = alloc_ubifs_info(ubi);
2298         if (!c) {
2299                 err = -ENOMEM;
2300                 goto out_close;
2301         }
2302
2303         dbg_gen("opened ubi%d_%d", c->vi.ubi_num, c->vi.vol_id);
2304
2305         sb = sget(fs_type, sb_test, sb_set, flags, c);
2306         if (IS_ERR(sb)) {
2307                 err = PTR_ERR(sb);
2308                 kfree(c);
2309                 goto out_close;
2310         }
2311
2312         if (sb->s_root) {
2313                 struct ubifs_info *c1 = sb->s_fs_info;
2314                 kfree(c);
2315                 /* A new mount point for already mounted UBIFS */
2316                 dbg_gen("this ubi volume is already mounted");
2317                 if (!!(flags & SB_RDONLY) != c1->ro_mount) {
2318                         err = -EBUSY;
2319                         goto out_deact;
2320                 }
2321         } else {
2322                 err = ubifs_fill_super(sb, data, flags & SB_SILENT ? 1 : 0);
2323                 if (err)
2324                         goto out_deact;
2325                 /* We do not support atime */
2326                 sb->s_flags |= SB_ACTIVE;
2327                 if (IS_ENABLED(CONFIG_UBIFS_ATIME_SUPPORT))
2328                         ubifs_msg(c, "full atime support is enabled.");
2329                 else
2330                         sb->s_flags |= SB_NOATIME;
2331         }
2332
2333         /* 'fill_super()' opens ubi again so we must close it here */
2334         ubi_close_volume(ubi);
2335
2336         return dget(sb->s_root);
2337
2338 out_deact:
2339         deactivate_locked_super(sb);
2340 out_close:
2341         ubi_close_volume(ubi);
2342         return ERR_PTR(err);
2343 }
2344
2345 static void kill_ubifs_super(struct super_block *s)
2346 {
2347         struct ubifs_info *c = s->s_fs_info;
2348         kill_anon_super(s);
2349         kfree(c);
2350 }
2351
2352 static struct file_system_type ubifs_fs_type = {
2353         .name    = "ubifs",
2354         .owner   = THIS_MODULE,
2355         .mount   = ubifs_mount,
2356         .kill_sb = kill_ubifs_super,
2357 };
2358 MODULE_ALIAS_FS("ubifs");
2359
2360 /*
2361  * Inode slab cache constructor.
2362  */
2363 static void inode_slab_ctor(void *obj)
2364 {
2365         struct ubifs_inode *ui = obj;
2366         inode_init_once(&ui->vfs_inode);
2367 }
2368
2369 static int __init ubifs_init(void)
2370 {
2371         int err;
2372
2373         BUILD_BUG_ON(sizeof(struct ubifs_ch) != 24);
2374
2375         /* Make sure node sizes are 8-byte aligned */
2376         BUILD_BUG_ON(UBIFS_CH_SZ        & 7);
2377         BUILD_BUG_ON(UBIFS_INO_NODE_SZ  & 7);
2378         BUILD_BUG_ON(UBIFS_DENT_NODE_SZ & 7);
2379         BUILD_BUG_ON(UBIFS_XENT_NODE_SZ & 7);
2380         BUILD_BUG_ON(UBIFS_DATA_NODE_SZ & 7);
2381         BUILD_BUG_ON(UBIFS_TRUN_NODE_SZ & 7);
2382         BUILD_BUG_ON(UBIFS_SB_NODE_SZ   & 7);
2383         BUILD_BUG_ON(UBIFS_MST_NODE_SZ  & 7);
2384         BUILD_BUG_ON(UBIFS_REF_NODE_SZ  & 7);
2385         BUILD_BUG_ON(UBIFS_CS_NODE_SZ   & 7);
2386         BUILD_BUG_ON(UBIFS_ORPH_NODE_SZ & 7);
2387
2388         BUILD_BUG_ON(UBIFS_MAX_DENT_NODE_SZ & 7);
2389         BUILD_BUG_ON(UBIFS_MAX_XENT_NODE_SZ & 7);
2390         BUILD_BUG_ON(UBIFS_MAX_DATA_NODE_SZ & 7);
2391         BUILD_BUG_ON(UBIFS_MAX_INO_NODE_SZ  & 7);
2392         BUILD_BUG_ON(UBIFS_MAX_NODE_SZ      & 7);
2393         BUILD_BUG_ON(MIN_WRITE_SZ           & 7);
2394
2395         /* Check min. node size */
2396         BUILD_BUG_ON(UBIFS_INO_NODE_SZ  < MIN_WRITE_SZ);
2397         BUILD_BUG_ON(UBIFS_DENT_NODE_SZ < MIN_WRITE_SZ);
2398         BUILD_BUG_ON(UBIFS_XENT_NODE_SZ < MIN_WRITE_SZ);
2399         BUILD_BUG_ON(UBIFS_TRUN_NODE_SZ < MIN_WRITE_SZ);
2400
2401         BUILD_BUG_ON(UBIFS_MAX_DENT_NODE_SZ > UBIFS_MAX_NODE_SZ);
2402         BUILD_BUG_ON(UBIFS_MAX_XENT_NODE_SZ > UBIFS_MAX_NODE_SZ);
2403         BUILD_BUG_ON(UBIFS_MAX_DATA_NODE_SZ > UBIFS_MAX_NODE_SZ);
2404         BUILD_BUG_ON(UBIFS_MAX_INO_NODE_SZ  > UBIFS_MAX_NODE_SZ);
2405
2406         /* Defined node sizes */
2407         BUILD_BUG_ON(UBIFS_SB_NODE_SZ  != 4096);
2408         BUILD_BUG_ON(UBIFS_MST_NODE_SZ != 512);
2409         BUILD_BUG_ON(UBIFS_INO_NODE_SZ != 160);
2410         BUILD_BUG_ON(UBIFS_REF_NODE_SZ != 64);
2411
2412         /*
2413          * We use 2 bit wide bit-fields to store compression type, which should
2414          * be amended if more compressors are added. The bit-fields are:
2415          * @compr_type in 'struct ubifs_inode', @default_compr in
2416          * 'struct ubifs_info' and @compr_type in 'struct ubifs_mount_opts'.
2417          */
2418         BUILD_BUG_ON(UBIFS_COMPR_TYPES_CNT > 4);
2419
2420         /*
2421          * We require that PAGE_SIZE is greater-than-or-equal-to
2422          * UBIFS_BLOCK_SIZE. It is assumed that both are powers of 2.
2423          */
2424         if (PAGE_SIZE < UBIFS_BLOCK_SIZE) {
2425                 pr_err("UBIFS error (pid %d): VFS page cache size is %u bytes, but UBIFS requires at least 4096 bytes",
2426                        current->pid, (unsigned int)PAGE_SIZE);
2427                 return -EINVAL;
2428         }
2429
2430         ubifs_inode_slab = kmem_cache_create("ubifs_inode_slab",
2431                                 sizeof(struct ubifs_inode), 0,
2432                                 SLAB_MEM_SPREAD | SLAB_RECLAIM_ACCOUNT |
2433                                 SLAB_ACCOUNT, &inode_slab_ctor);
2434         if (!ubifs_inode_slab)
2435                 return -ENOMEM;
2436
2437         err = register_shrinker(&ubifs_shrinker_info);
2438         if (err)
2439                 goto out_slab;
2440
2441         err = ubifs_compressors_init();
2442         if (err)
2443                 goto out_shrinker;
2444
2445         dbg_debugfs_init();
2446
2447         err = register_filesystem(&ubifs_fs_type);
2448         if (err) {
2449                 pr_err("UBIFS error (pid %d): cannot register file system, error %d",
2450                        current->pid, err);
2451                 goto out_dbg;
2452         }
2453         return 0;
2454
2455 out_dbg:
2456         dbg_debugfs_exit();
2457         ubifs_compressors_exit();
2458 out_shrinker:
2459         unregister_shrinker(&ubifs_shrinker_info);
2460 out_slab:
2461         kmem_cache_destroy(ubifs_inode_slab);
2462         return err;
2463 }
2464 /* late_initcall to let compressors initialize first */
2465 late_initcall(ubifs_init);
2466
2467 static void __exit ubifs_exit(void)
2468 {
2469         WARN_ON(!list_empty(&ubifs_infos));
2470         WARN_ON(atomic_long_read(&ubifs_clean_zn_cnt) != 0);
2471
2472         dbg_debugfs_exit();
2473         ubifs_compressors_exit();
2474         unregister_shrinker(&ubifs_shrinker_info);
2475
2476         /*
2477          * Make sure all delayed rcu free inodes are flushed before we
2478          * destroy cache.
2479          */
2480         rcu_barrier();
2481         kmem_cache_destroy(ubifs_inode_slab);
2482         unregister_filesystem(&ubifs_fs_type);
2483 }
2484 module_exit(ubifs_exit);
2485
2486 MODULE_LICENSE("GPL");
2487 MODULE_VERSION(__stringify(UBIFS_VERSION));
2488 MODULE_AUTHOR("Artem Bityutskiy, Adrian Hunter");
2489 MODULE_DESCRIPTION("UBIFS - UBI File System");