GNU Linux-libre 5.4.257-gnu1
[releases.git] / fs / ubifs / dir.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* * This file is part of UBIFS.
3  *
4  * Copyright (C) 2006-2008 Nokia Corporation.
5  * Copyright (C) 2006, 2007 University of Szeged, Hungary
6  *
7  * Authors: Artem Bityutskiy (Битюцкий Артём)
8  *          Adrian Hunter
9  *          Zoltan Sogor
10  */
11
12 /*
13  * This file implements directory operations.
14  *
15  * All FS operations in this file allocate budget before writing anything to the
16  * media. If they fail to allocate it, the error is returned. The only
17  * exceptions are 'ubifs_unlink()' and 'ubifs_rmdir()' which keep working even
18  * if they unable to allocate the budget, because deletion %-ENOSPC failure is
19  * not what users are usually ready to get. UBIFS budgeting subsystem has some
20  * space reserved for these purposes.
21  *
22  * All operations in this file write all inodes which they change straight
23  * away, instead of marking them dirty. For example, 'ubifs_link()' changes
24  * @i_size of the parent inode and writes the parent inode together with the
25  * target inode. This was done to simplify file-system recovery which would
26  * otherwise be very difficult to do. The only exception is rename which marks
27  * the re-named inode dirty (because its @i_ctime is updated) but does not
28  * write it, but just marks it as dirty.
29  */
30
31 #include "ubifs.h"
32
33 /**
34  * inherit_flags - inherit flags of the parent inode.
35  * @dir: parent inode
36  * @mode: new inode mode flags
37  *
38  * This is a helper function for 'ubifs_new_inode()' which inherits flag of the
39  * parent directory inode @dir. UBIFS inodes inherit the following flags:
40  * o %UBIFS_COMPR_FL, which is useful to switch compression on/of on
41  *   sub-directory basis;
42  * o %UBIFS_SYNC_FL - useful for the same reasons;
43  * o %UBIFS_DIRSYNC_FL - similar, but relevant only to directories.
44  *
45  * This function returns the inherited flags.
46  */
47 static int inherit_flags(const struct inode *dir, umode_t mode)
48 {
49         int flags;
50         const struct ubifs_inode *ui = ubifs_inode(dir);
51
52         if (!S_ISDIR(dir->i_mode))
53                 /*
54                  * The parent is not a directory, which means that an extended
55                  * attribute inode is being created. No flags.
56                  */
57                 return 0;
58
59         flags = ui->flags & (UBIFS_COMPR_FL | UBIFS_SYNC_FL | UBIFS_DIRSYNC_FL);
60         if (!S_ISDIR(mode))
61                 /* The "DIRSYNC" flag only applies to directories */
62                 flags &= ~UBIFS_DIRSYNC_FL;
63         return flags;
64 }
65
66 /**
67  * ubifs_new_inode - allocate new UBIFS inode object.
68  * @c: UBIFS file-system description object
69  * @dir: parent directory inode
70  * @mode: inode mode flags
71  *
72  * This function finds an unused inode number, allocates new inode and
73  * initializes it. Returns new inode in case of success and an error code in
74  * case of failure.
75  */
76 struct inode *ubifs_new_inode(struct ubifs_info *c, struct inode *dir,
77                               umode_t mode)
78 {
79         int err;
80         struct inode *inode;
81         struct ubifs_inode *ui;
82         bool encrypted = false;
83
84         if (ubifs_crypt_is_encrypted(dir)) {
85                 err = fscrypt_get_encryption_info(dir);
86                 if (err) {
87                         ubifs_err(c, "fscrypt_get_encryption_info failed: %i", err);
88                         return ERR_PTR(err);
89                 }
90
91                 if (!fscrypt_has_encryption_key(dir))
92                         return ERR_PTR(-EPERM);
93
94                 encrypted = true;
95         }
96
97         inode = new_inode(c->vfs_sb);
98         ui = ubifs_inode(inode);
99         if (!inode)
100                 return ERR_PTR(-ENOMEM);
101
102         /*
103          * Set 'S_NOCMTIME' to prevent VFS form updating [mc]time of inodes and
104          * marking them dirty in file write path (see 'file_update_time()').
105          * UBIFS has to fully control "clean <-> dirty" transitions of inodes
106          * to make budgeting work.
107          */
108         inode->i_flags |= S_NOCMTIME;
109
110         inode_init_owner(inode, dir, mode);
111         inode->i_mtime = inode->i_atime = inode->i_ctime =
112                          current_time(inode);
113         inode->i_mapping->nrpages = 0;
114
115         switch (mode & S_IFMT) {
116         case S_IFREG:
117                 inode->i_mapping->a_ops = &ubifs_file_address_operations;
118                 inode->i_op = &ubifs_file_inode_operations;
119                 inode->i_fop = &ubifs_file_operations;
120                 break;
121         case S_IFDIR:
122                 inode->i_op  = &ubifs_dir_inode_operations;
123                 inode->i_fop = &ubifs_dir_operations;
124                 inode->i_size = ui->ui_size = UBIFS_INO_NODE_SZ;
125                 break;
126         case S_IFLNK:
127                 inode->i_op = &ubifs_symlink_inode_operations;
128                 break;
129         case S_IFSOCK:
130         case S_IFIFO:
131         case S_IFBLK:
132         case S_IFCHR:
133                 inode->i_op  = &ubifs_file_inode_operations;
134                 encrypted = false;
135                 break;
136         default:
137                 BUG();
138         }
139
140         ui->flags = inherit_flags(dir, mode);
141         ubifs_set_inode_flags(inode);
142         if (S_ISREG(mode))
143                 ui->compr_type = c->default_compr;
144         else
145                 ui->compr_type = UBIFS_COMPR_NONE;
146         ui->synced_i_size = 0;
147
148         spin_lock(&c->cnt_lock);
149         /* Inode number overflow is currently not supported */
150         if (c->highest_inum >= INUM_WARN_WATERMARK) {
151                 if (c->highest_inum >= INUM_WATERMARK) {
152                         spin_unlock(&c->cnt_lock);
153                         ubifs_err(c, "out of inode numbers");
154                         make_bad_inode(inode);
155                         iput(inode);
156                         return ERR_PTR(-EINVAL);
157                 }
158                 ubifs_warn(c, "running out of inode numbers (current %lu, max %u)",
159                            (unsigned long)c->highest_inum, INUM_WATERMARK);
160         }
161
162         inode->i_ino = ++c->highest_inum;
163         /*
164          * The creation sequence number remains with this inode for its
165          * lifetime. All nodes for this inode have a greater sequence number,
166          * and so it is possible to distinguish obsolete nodes belonging to a
167          * previous incarnation of the same inode number - for example, for the
168          * purpose of rebuilding the index.
169          */
170         ui->creat_sqnum = ++c->max_sqnum;
171         spin_unlock(&c->cnt_lock);
172
173         if (encrypted) {
174                 err = fscrypt_inherit_context(dir, inode, &encrypted, true);
175                 if (err) {
176                         ubifs_err(c, "fscrypt_inherit_context failed: %i", err);
177                         make_bad_inode(inode);
178                         iput(inode);
179                         return ERR_PTR(err);
180                 }
181         }
182
183         return inode;
184 }
185
186 static int dbg_check_name(const struct ubifs_info *c,
187                           const struct ubifs_dent_node *dent,
188                           const struct fscrypt_name *nm)
189 {
190         if (!dbg_is_chk_gen(c))
191                 return 0;
192         if (le16_to_cpu(dent->nlen) != fname_len(nm))
193                 return -EINVAL;
194         if (memcmp(dent->name, fname_name(nm), fname_len(nm)))
195                 return -EINVAL;
196         return 0;
197 }
198
199 static struct dentry *ubifs_lookup(struct inode *dir, struct dentry *dentry,
200                                    unsigned int flags)
201 {
202         int err;
203         union ubifs_key key;
204         struct inode *inode = NULL;
205         struct ubifs_dent_node *dent = NULL;
206         struct ubifs_info *c = dir->i_sb->s_fs_info;
207         struct fscrypt_name nm;
208
209         dbg_gen("'%pd' in dir ino %lu", dentry, dir->i_ino);
210
211         err = fscrypt_prepare_lookup(dir, dentry, &nm);
212         if (err == -ENOENT)
213                 return d_splice_alias(NULL, dentry);
214         if (err)
215                 return ERR_PTR(err);
216
217         if (fname_len(&nm) > UBIFS_MAX_NLEN) {
218                 inode = ERR_PTR(-ENAMETOOLONG);
219                 goto done;
220         }
221
222         dent = kmalloc(UBIFS_MAX_DENT_NODE_SZ, GFP_NOFS);
223         if (!dent) {
224                 inode = ERR_PTR(-ENOMEM);
225                 goto done;
226         }
227
228         if (nm.hash) {
229                 ubifs_assert(c, fname_len(&nm) == 0);
230                 ubifs_assert(c, fname_name(&nm) == NULL);
231                 if (nm.hash & ~UBIFS_S_KEY_HASH_MASK)
232                         goto done; /* ENOENT */
233                 dent_key_init_hash(c, &key, dir->i_ino, nm.hash);
234                 err = ubifs_tnc_lookup_dh(c, &key, dent, nm.minor_hash);
235         } else {
236                 dent_key_init(c, &key, dir->i_ino, &nm);
237                 err = ubifs_tnc_lookup_nm(c, &key, dent, &nm);
238         }
239
240         if (err) {
241                 if (err == -ENOENT)
242                         dbg_gen("not found");
243                 else
244                         inode = ERR_PTR(err);
245                 goto done;
246         }
247
248         if (dbg_check_name(c, dent, &nm)) {
249                 inode = ERR_PTR(-EINVAL);
250                 goto done;
251         }
252
253         inode = ubifs_iget(dir->i_sb, le64_to_cpu(dent->inum));
254         if (IS_ERR(inode)) {
255                 /*
256                  * This should not happen. Probably the file-system needs
257                  * checking.
258                  */
259                 err = PTR_ERR(inode);
260                 ubifs_err(c, "dead directory entry '%pd', error %d",
261                           dentry, err);
262                 ubifs_ro_mode(c, err);
263                 goto done;
264         }
265
266         if (ubifs_crypt_is_encrypted(dir) &&
267             (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) &&
268             !fscrypt_has_permitted_context(dir, inode)) {
269                 ubifs_warn(c, "Inconsistent encryption contexts: %lu/%lu",
270                            dir->i_ino, inode->i_ino);
271                 iput(inode);
272                 inode = ERR_PTR(-EPERM);
273         }
274
275 done:
276         kfree(dent);
277         fscrypt_free_filename(&nm);
278         return d_splice_alias(inode, dentry);
279 }
280
281 static int ubifs_prepare_create(struct inode *dir, struct dentry *dentry,
282                                 struct fscrypt_name *nm)
283 {
284         if (fscrypt_is_nokey_name(dentry))
285                 return -ENOKEY;
286
287         return fscrypt_setup_filename(dir, &dentry->d_name, 0, nm);
288 }
289
290 static int ubifs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
291                         bool excl)
292 {
293         struct inode *inode;
294         struct ubifs_info *c = dir->i_sb->s_fs_info;
295         struct ubifs_budget_req req = { .new_ino = 1, .new_dent = 1,
296                                         .dirtied_ino = 1 };
297         struct ubifs_inode *dir_ui = ubifs_inode(dir);
298         struct fscrypt_name nm;
299         int err, sz_change;
300
301         /*
302          * Budget request settings: new inode, new direntry, changing the
303          * parent directory inode.
304          */
305
306         dbg_gen("dent '%pd', mode %#hx in dir ino %lu",
307                 dentry, mode, dir->i_ino);
308
309         err = ubifs_budget_space(c, &req);
310         if (err)
311                 return err;
312
313         err = ubifs_prepare_create(dir, dentry, &nm);
314         if (err)
315                 goto out_budg;
316
317         sz_change = CALC_DENT_SIZE(fname_len(&nm));
318
319         inode = ubifs_new_inode(c, dir, mode);
320         if (IS_ERR(inode)) {
321                 err = PTR_ERR(inode);
322                 goto out_fname;
323         }
324
325         err = ubifs_init_security(dir, inode, &dentry->d_name);
326         if (err)
327                 goto out_inode;
328
329         mutex_lock(&dir_ui->ui_mutex);
330         dir->i_size += sz_change;
331         dir_ui->ui_size = dir->i_size;
332         dir->i_mtime = dir->i_ctime = inode->i_ctime;
333         err = ubifs_jnl_update(c, dir, &nm, inode, 0, 0);
334         if (err)
335                 goto out_cancel;
336         mutex_unlock(&dir_ui->ui_mutex);
337
338         ubifs_release_budget(c, &req);
339         fscrypt_free_filename(&nm);
340         insert_inode_hash(inode);
341         d_instantiate(dentry, inode);
342         return 0;
343
344 out_cancel:
345         dir->i_size -= sz_change;
346         dir_ui->ui_size = dir->i_size;
347         mutex_unlock(&dir_ui->ui_mutex);
348 out_inode:
349         make_bad_inode(inode);
350         iput(inode);
351 out_fname:
352         fscrypt_free_filename(&nm);
353 out_budg:
354         ubifs_release_budget(c, &req);
355         ubifs_err(c, "cannot create regular file, error %d", err);
356         return err;
357 }
358
359 static int do_tmpfile(struct inode *dir, struct dentry *dentry,
360                       umode_t mode, struct inode **whiteout)
361 {
362         struct inode *inode;
363         struct ubifs_info *c = dir->i_sb->s_fs_info;
364         struct ubifs_budget_req req = { .new_ino = 1, .new_dent = 1,
365                                         .dirtied_ino = 1};
366         struct ubifs_budget_req ino_req = { .dirtied_ino = 1 };
367         struct ubifs_inode *ui, *dir_ui = ubifs_inode(dir);
368         int err, instantiated = 0;
369         struct fscrypt_name nm;
370
371         /*
372          * Budget request settings: new inode, new direntry, changing the
373          * parent directory inode.
374          * Allocate budget separately for new dirtied inode, the budget will
375          * be released via writeback.
376          */
377
378         dbg_gen("dent '%pd', mode %#hx in dir ino %lu",
379                 dentry, mode, dir->i_ino);
380
381         err = fscrypt_setup_filename(dir, &dentry->d_name, 0, &nm);
382         if (err)
383                 return err;
384
385         err = ubifs_budget_space(c, &req);
386         if (err) {
387                 fscrypt_free_filename(&nm);
388                 return err;
389         }
390
391         err = ubifs_budget_space(c, &ino_req);
392         if (err) {
393                 ubifs_release_budget(c, &req);
394                 fscrypt_free_filename(&nm);
395                 return err;
396         }
397
398         inode = ubifs_new_inode(c, dir, mode);
399         if (IS_ERR(inode)) {
400                 err = PTR_ERR(inode);
401                 goto out_budg;
402         }
403         ui = ubifs_inode(inode);
404
405         if (whiteout) {
406                 init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
407                 ubifs_assert(c, inode->i_op == &ubifs_file_inode_operations);
408         }
409
410         err = ubifs_init_security(dir, inode, &dentry->d_name);
411         if (err)
412                 goto out_inode;
413
414         mutex_lock(&ui->ui_mutex);
415         insert_inode_hash(inode);
416
417         if (whiteout) {
418                 mark_inode_dirty(inode);
419                 drop_nlink(inode);
420                 *whiteout = inode;
421         } else {
422                 d_tmpfile(dentry, inode);
423         }
424         ubifs_assert(c, ui->dirty);
425
426         instantiated = 1;
427         mutex_unlock(&ui->ui_mutex);
428
429         mutex_lock(&dir_ui->ui_mutex);
430         err = ubifs_jnl_update(c, dir, &nm, inode, 1, 0);
431         if (err)
432                 goto out_cancel;
433         mutex_unlock(&dir_ui->ui_mutex);
434
435         ubifs_release_budget(c, &req);
436         fscrypt_free_filename(&nm);
437
438         return 0;
439
440 out_cancel:
441         mutex_unlock(&dir_ui->ui_mutex);
442 out_inode:
443         make_bad_inode(inode);
444         if (!instantiated)
445                 iput(inode);
446         else if (whiteout)
447                 iput(*whiteout);
448 out_budg:
449         ubifs_release_budget(c, &req);
450         if (!instantiated)
451                 ubifs_release_budget(c, &ino_req);
452         fscrypt_free_filename(&nm);
453         ubifs_err(c, "cannot create temporary file, error %d", err);
454         return err;
455 }
456
457 static int ubifs_tmpfile(struct inode *dir, struct dentry *dentry,
458                          umode_t mode)
459 {
460         return do_tmpfile(dir, dentry, mode, NULL);
461 }
462
463 /**
464  * vfs_dent_type - get VFS directory entry type.
465  * @type: UBIFS directory entry type
466  *
467  * This function converts UBIFS directory entry type into VFS directory entry
468  * type.
469  */
470 static unsigned int vfs_dent_type(uint8_t type)
471 {
472         switch (type) {
473         case UBIFS_ITYPE_REG:
474                 return DT_REG;
475         case UBIFS_ITYPE_DIR:
476                 return DT_DIR;
477         case UBIFS_ITYPE_LNK:
478                 return DT_LNK;
479         case UBIFS_ITYPE_BLK:
480                 return DT_BLK;
481         case UBIFS_ITYPE_CHR:
482                 return DT_CHR;
483         case UBIFS_ITYPE_FIFO:
484                 return DT_FIFO;
485         case UBIFS_ITYPE_SOCK:
486                 return DT_SOCK;
487         default:
488                 BUG();
489         }
490         return 0;
491 }
492
493 /*
494  * The classical Unix view for directory is that it is a linear array of
495  * (name, inode number) entries. Linux/VFS assumes this model as well.
496  * Particularly, 'readdir()' call wants us to return a directory entry offset
497  * which later may be used to continue 'readdir()'ing the directory or to
498  * 'seek()' to that specific direntry. Obviously UBIFS does not really fit this
499  * model because directory entries are identified by keys, which may collide.
500  *
501  * UBIFS uses directory entry hash value for directory offsets, so
502  * 'seekdir()'/'telldir()' may not always work because of possible key
503  * collisions. But UBIFS guarantees that consecutive 'readdir()' calls work
504  * properly by means of saving full directory entry name in the private field
505  * of the file description object.
506  *
507  * This means that UBIFS cannot support NFS which requires full
508  * 'seekdir()'/'telldir()' support.
509  */
510 static int ubifs_readdir(struct file *file, struct dir_context *ctx)
511 {
512         int fstr_real_len = 0, err = 0;
513         struct fscrypt_name nm;
514         struct fscrypt_str fstr = {0};
515         union ubifs_key key;
516         struct ubifs_dent_node *dent;
517         struct inode *dir = file_inode(file);
518         struct ubifs_info *c = dir->i_sb->s_fs_info;
519         bool encrypted = ubifs_crypt_is_encrypted(dir);
520
521         dbg_gen("dir ino %lu, f_pos %#llx", dir->i_ino, ctx->pos);
522
523         if (ctx->pos > UBIFS_S_KEY_HASH_MASK || ctx->pos == 2)
524                 /*
525                  * The directory was seek'ed to a senseless position or there
526                  * are no more entries.
527                  */
528                 return 0;
529
530         if (encrypted) {
531                 err = fscrypt_get_encryption_info(dir);
532                 if (err && err != -ENOKEY)
533                         return err;
534
535                 err = fscrypt_fname_alloc_buffer(dir, UBIFS_MAX_NLEN, &fstr);
536                 if (err)
537                         return err;
538
539                 fstr_real_len = fstr.len;
540         }
541
542         if (file->f_version == 0) {
543                 /*
544                  * The file was seek'ed, which means that @file->private_data
545                  * is now invalid. This may also be just the first
546                  * 'ubifs_readdir()' invocation, in which case
547                  * @file->private_data is NULL, and the below code is
548                  * basically a no-op.
549                  */
550                 kfree(file->private_data);
551                 file->private_data = NULL;
552         }
553
554         /*
555          * 'generic_file_llseek()' unconditionally sets @file->f_version to
556          * zero, and we use this for detecting whether the file was seek'ed.
557          */
558         file->f_version = 1;
559
560         /* File positions 0 and 1 correspond to "." and ".." */
561         if (ctx->pos < 2) {
562                 ubifs_assert(c, !file->private_data);
563                 if (!dir_emit_dots(file, ctx)) {
564                         if (encrypted)
565                                 fscrypt_fname_free_buffer(&fstr);
566                         return 0;
567                 }
568
569                 /* Find the first entry in TNC and save it */
570                 lowest_dent_key(c, &key, dir->i_ino);
571                 fname_len(&nm) = 0;
572                 dent = ubifs_tnc_next_ent(c, &key, &nm);
573                 if (IS_ERR(dent)) {
574                         err = PTR_ERR(dent);
575                         goto out;
576                 }
577
578                 ctx->pos = key_hash_flash(c, &dent->key);
579                 file->private_data = dent;
580         }
581
582         dent = file->private_data;
583         if (!dent) {
584                 /*
585                  * The directory was seek'ed to and is now readdir'ed.
586                  * Find the entry corresponding to @ctx->pos or the closest one.
587                  */
588                 dent_key_init_hash(c, &key, dir->i_ino, ctx->pos);
589                 fname_len(&nm) = 0;
590                 dent = ubifs_tnc_next_ent(c, &key, &nm);
591                 if (IS_ERR(dent)) {
592                         err = PTR_ERR(dent);
593                         goto out;
594                 }
595                 ctx->pos = key_hash_flash(c, &dent->key);
596                 file->private_data = dent;
597         }
598
599         while (1) {
600                 dbg_gen("ino %llu, new f_pos %#x",
601                         (unsigned long long)le64_to_cpu(dent->inum),
602                         key_hash_flash(c, &dent->key));
603                 ubifs_assert(c, le64_to_cpu(dent->ch.sqnum) >
604                              ubifs_inode(dir)->creat_sqnum);
605
606                 fname_len(&nm) = le16_to_cpu(dent->nlen);
607                 fname_name(&nm) = dent->name;
608
609                 if (encrypted) {
610                         fstr.len = fstr_real_len;
611
612                         err = fscrypt_fname_disk_to_usr(dir, key_hash_flash(c,
613                                                         &dent->key),
614                                                         le32_to_cpu(dent->cookie),
615                                                         &nm.disk_name, &fstr);
616                         if (err)
617                                 goto out;
618                 } else {
619                         fstr.len = fname_len(&nm);
620                         fstr.name = fname_name(&nm);
621                 }
622
623                 if (!dir_emit(ctx, fstr.name, fstr.len,
624                                le64_to_cpu(dent->inum),
625                                vfs_dent_type(dent->type))) {
626                         if (encrypted)
627                                 fscrypt_fname_free_buffer(&fstr);
628                         return 0;
629                 }
630
631                 /* Switch to the next entry */
632                 key_read(c, &dent->key, &key);
633                 dent = ubifs_tnc_next_ent(c, &key, &nm);
634                 if (IS_ERR(dent)) {
635                         err = PTR_ERR(dent);
636                         goto out;
637                 }
638
639                 kfree(file->private_data);
640                 ctx->pos = key_hash_flash(c, &dent->key);
641                 file->private_data = dent;
642                 cond_resched();
643         }
644
645 out:
646         kfree(file->private_data);
647         file->private_data = NULL;
648
649         if (encrypted)
650                 fscrypt_fname_free_buffer(&fstr);
651
652         if (err != -ENOENT)
653                 ubifs_err(c, "cannot find next direntry, error %d", err);
654         else
655                 /*
656                  * -ENOENT is a non-fatal error in this context, the TNC uses
657                  * it to indicate that the cursor moved past the current directory
658                  * and readdir() has to stop.
659                  */
660                 err = 0;
661
662
663         /* 2 is a special value indicating that there are no more direntries */
664         ctx->pos = 2;
665         return err;
666 }
667
668 /* Free saved readdir() state when the directory is closed */
669 static int ubifs_dir_release(struct inode *dir, struct file *file)
670 {
671         kfree(file->private_data);
672         file->private_data = NULL;
673         return 0;
674 }
675
676 /**
677  * lock_2_inodes - a wrapper for locking two UBIFS inodes.
678  * @inode1: first inode
679  * @inode2: second inode
680  *
681  * We do not implement any tricks to guarantee strict lock ordering, because
682  * VFS has already done it for us on the @i_mutex. So this is just a simple
683  * wrapper function.
684  */
685 static void lock_2_inodes(struct inode *inode1, struct inode *inode2)
686 {
687         mutex_lock_nested(&ubifs_inode(inode1)->ui_mutex, WB_MUTEX_1);
688         mutex_lock_nested(&ubifs_inode(inode2)->ui_mutex, WB_MUTEX_2);
689 }
690
691 /**
692  * unlock_2_inodes - a wrapper for unlocking two UBIFS inodes.
693  * @inode1: first inode
694  * @inode2: second inode
695  */
696 static void unlock_2_inodes(struct inode *inode1, struct inode *inode2)
697 {
698         mutex_unlock(&ubifs_inode(inode2)->ui_mutex);
699         mutex_unlock(&ubifs_inode(inode1)->ui_mutex);
700 }
701
702 static int ubifs_link(struct dentry *old_dentry, struct inode *dir,
703                       struct dentry *dentry)
704 {
705         struct ubifs_info *c = dir->i_sb->s_fs_info;
706         struct inode *inode = d_inode(old_dentry);
707         struct ubifs_inode *ui = ubifs_inode(inode);
708         struct ubifs_inode *dir_ui = ubifs_inode(dir);
709         int err, sz_change = CALC_DENT_SIZE(dentry->d_name.len);
710         struct ubifs_budget_req req = { .new_dent = 1, .dirtied_ino = 2,
711                                 .dirtied_ino_d = ALIGN(ui->data_len, 8) };
712         struct fscrypt_name nm;
713
714         /*
715          * Budget request settings: new direntry, changing the target inode,
716          * changing the parent inode.
717          */
718
719         dbg_gen("dent '%pd' to ino %lu (nlink %d) in dir ino %lu",
720                 dentry, inode->i_ino,
721                 inode->i_nlink, dir->i_ino);
722         ubifs_assert(c, inode_is_locked(dir));
723         ubifs_assert(c, inode_is_locked(inode));
724
725         err = fscrypt_prepare_link(old_dentry, dir, dentry);
726         if (err)
727                 return err;
728
729         err = fscrypt_setup_filename(dir, &dentry->d_name, 0, &nm);
730         if (err)
731                 return err;
732
733         err = dbg_check_synced_i_size(c, inode);
734         if (err)
735                 goto out_fname;
736
737         err = ubifs_budget_space(c, &req);
738         if (err)
739                 goto out_fname;
740
741         lock_2_inodes(dir, inode);
742
743         /* Handle O_TMPFILE corner case, it is allowed to link a O_TMPFILE. */
744         if (inode->i_nlink == 0)
745                 ubifs_delete_orphan(c, inode->i_ino);
746
747         inc_nlink(inode);
748         ihold(inode);
749         inode->i_ctime = current_time(inode);
750         dir->i_size += sz_change;
751         dir_ui->ui_size = dir->i_size;
752         dir->i_mtime = dir->i_ctime = inode->i_ctime;
753         err = ubifs_jnl_update(c, dir, &nm, inode, 0, 0);
754         if (err)
755                 goto out_cancel;
756         unlock_2_inodes(dir, inode);
757
758         ubifs_release_budget(c, &req);
759         d_instantiate(dentry, inode);
760         fscrypt_free_filename(&nm);
761         return 0;
762
763 out_cancel:
764         dir->i_size -= sz_change;
765         dir_ui->ui_size = dir->i_size;
766         drop_nlink(inode);
767         if (inode->i_nlink == 0)
768                 ubifs_add_orphan(c, inode->i_ino);
769         unlock_2_inodes(dir, inode);
770         ubifs_release_budget(c, &req);
771         iput(inode);
772 out_fname:
773         fscrypt_free_filename(&nm);
774         return err;
775 }
776
777 static int ubifs_unlink(struct inode *dir, struct dentry *dentry)
778 {
779         struct ubifs_info *c = dir->i_sb->s_fs_info;
780         struct inode *inode = d_inode(dentry);
781         struct ubifs_inode *dir_ui = ubifs_inode(dir);
782         int err, sz_change, budgeted = 1;
783         struct ubifs_budget_req req = { .mod_dent = 1, .dirtied_ino = 2 };
784         unsigned int saved_nlink = inode->i_nlink;
785         struct fscrypt_name nm;
786
787         /*
788          * Budget request settings: deletion direntry, deletion inode (+1 for
789          * @dirtied_ino), changing the parent directory inode. If budgeting
790          * fails, go ahead anyway because we have extra space reserved for
791          * deletions.
792          */
793
794         dbg_gen("dent '%pd' from ino %lu (nlink %d) in dir ino %lu",
795                 dentry, inode->i_ino,
796                 inode->i_nlink, dir->i_ino);
797
798         err = fscrypt_setup_filename(dir, &dentry->d_name, 1, &nm);
799         if (err)
800                 return err;
801
802         err = ubifs_purge_xattrs(inode);
803         if (err)
804                 return err;
805
806         sz_change = CALC_DENT_SIZE(fname_len(&nm));
807
808         ubifs_assert(c, inode_is_locked(dir));
809         ubifs_assert(c, inode_is_locked(inode));
810         err = dbg_check_synced_i_size(c, inode);
811         if (err)
812                 goto out_fname;
813
814         err = ubifs_budget_space(c, &req);
815         if (err) {
816                 if (err != -ENOSPC)
817                         goto out_fname;
818                 budgeted = 0;
819         }
820
821         lock_2_inodes(dir, inode);
822         inode->i_ctime = current_time(dir);
823         drop_nlink(inode);
824         dir->i_size -= sz_change;
825         dir_ui->ui_size = dir->i_size;
826         dir->i_mtime = dir->i_ctime = inode->i_ctime;
827         err = ubifs_jnl_update(c, dir, &nm, inode, 1, 0);
828         if (err)
829                 goto out_cancel;
830         unlock_2_inodes(dir, inode);
831
832         if (budgeted)
833                 ubifs_release_budget(c, &req);
834         else {
835                 /* We've deleted something - clean the "no space" flags */
836                 c->bi.nospace = c->bi.nospace_rp = 0;
837                 smp_wmb();
838         }
839         fscrypt_free_filename(&nm);
840         return 0;
841
842 out_cancel:
843         dir->i_size += sz_change;
844         dir_ui->ui_size = dir->i_size;
845         set_nlink(inode, saved_nlink);
846         unlock_2_inodes(dir, inode);
847         if (budgeted)
848                 ubifs_release_budget(c, &req);
849 out_fname:
850         fscrypt_free_filename(&nm);
851         return err;
852 }
853
854 /**
855  * check_dir_empty - check if a directory is empty or not.
856  * @dir: VFS inode object of the directory to check
857  *
858  * This function checks if directory @dir is empty. Returns zero if the
859  * directory is empty, %-ENOTEMPTY if it is not, and other negative error codes
860  * in case of of errors.
861  */
862 int ubifs_check_dir_empty(struct inode *dir)
863 {
864         struct ubifs_info *c = dir->i_sb->s_fs_info;
865         struct fscrypt_name nm = { 0 };
866         struct ubifs_dent_node *dent;
867         union ubifs_key key;
868         int err;
869
870         lowest_dent_key(c, &key, dir->i_ino);
871         dent = ubifs_tnc_next_ent(c, &key, &nm);
872         if (IS_ERR(dent)) {
873                 err = PTR_ERR(dent);
874                 if (err == -ENOENT)
875                         err = 0;
876         } else {
877                 kfree(dent);
878                 err = -ENOTEMPTY;
879         }
880         return err;
881 }
882
883 static int ubifs_rmdir(struct inode *dir, struct dentry *dentry)
884 {
885         struct ubifs_info *c = dir->i_sb->s_fs_info;
886         struct inode *inode = d_inode(dentry);
887         int err, sz_change, budgeted = 1;
888         struct ubifs_inode *dir_ui = ubifs_inode(dir);
889         struct ubifs_budget_req req = { .mod_dent = 1, .dirtied_ino = 2 };
890         struct fscrypt_name nm;
891
892         /*
893          * Budget request settings: deletion direntry, deletion inode and
894          * changing the parent inode. If budgeting fails, go ahead anyway
895          * because we have extra space reserved for deletions.
896          */
897
898         dbg_gen("directory '%pd', ino %lu in dir ino %lu", dentry,
899                 inode->i_ino, dir->i_ino);
900         ubifs_assert(c, inode_is_locked(dir));
901         ubifs_assert(c, inode_is_locked(inode));
902         err = ubifs_check_dir_empty(d_inode(dentry));
903         if (err)
904                 return err;
905
906         err = fscrypt_setup_filename(dir, &dentry->d_name, 1, &nm);
907         if (err)
908                 return err;
909
910         err = ubifs_purge_xattrs(inode);
911         if (err)
912                 return err;
913
914         sz_change = CALC_DENT_SIZE(fname_len(&nm));
915
916         err = ubifs_budget_space(c, &req);
917         if (err) {
918                 if (err != -ENOSPC)
919                         goto out_fname;
920                 budgeted = 0;
921         }
922
923         lock_2_inodes(dir, inode);
924         inode->i_ctime = current_time(dir);
925         clear_nlink(inode);
926         drop_nlink(dir);
927         dir->i_size -= sz_change;
928         dir_ui->ui_size = dir->i_size;
929         dir->i_mtime = dir->i_ctime = inode->i_ctime;
930         err = ubifs_jnl_update(c, dir, &nm, inode, 1, 0);
931         if (err)
932                 goto out_cancel;
933         unlock_2_inodes(dir, inode);
934
935         if (budgeted)
936                 ubifs_release_budget(c, &req);
937         else {
938                 /* We've deleted something - clean the "no space" flags */
939                 c->bi.nospace = c->bi.nospace_rp = 0;
940                 smp_wmb();
941         }
942         fscrypt_free_filename(&nm);
943         return 0;
944
945 out_cancel:
946         dir->i_size += sz_change;
947         dir_ui->ui_size = dir->i_size;
948         inc_nlink(dir);
949         set_nlink(inode, 2);
950         unlock_2_inodes(dir, inode);
951         if (budgeted)
952                 ubifs_release_budget(c, &req);
953 out_fname:
954         fscrypt_free_filename(&nm);
955         return err;
956 }
957
958 static int ubifs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
959 {
960         struct inode *inode;
961         struct ubifs_inode *dir_ui = ubifs_inode(dir);
962         struct ubifs_info *c = dir->i_sb->s_fs_info;
963         int err, sz_change;
964         struct ubifs_budget_req req = { .new_ino = 1, .new_dent = 1,
965                                         .dirtied_ino = 1};
966         struct fscrypt_name nm;
967
968         /*
969          * Budget request settings: new inode, new direntry and changing parent
970          * directory inode.
971          */
972
973         dbg_gen("dent '%pd', mode %#hx in dir ino %lu",
974                 dentry, mode, dir->i_ino);
975
976         err = ubifs_budget_space(c, &req);
977         if (err)
978                 return err;
979
980         err = ubifs_prepare_create(dir, dentry, &nm);
981         if (err)
982                 goto out_budg;
983
984         sz_change = CALC_DENT_SIZE(fname_len(&nm));
985
986         inode = ubifs_new_inode(c, dir, S_IFDIR | mode);
987         if (IS_ERR(inode)) {
988                 err = PTR_ERR(inode);
989                 goto out_fname;
990         }
991
992         err = ubifs_init_security(dir, inode, &dentry->d_name);
993         if (err)
994                 goto out_inode;
995
996         mutex_lock(&dir_ui->ui_mutex);
997         insert_inode_hash(inode);
998         inc_nlink(inode);
999         inc_nlink(dir);
1000         dir->i_size += sz_change;
1001         dir_ui->ui_size = dir->i_size;
1002         dir->i_mtime = dir->i_ctime = inode->i_ctime;
1003         err = ubifs_jnl_update(c, dir, &nm, inode, 0, 0);
1004         if (err) {
1005                 ubifs_err(c, "cannot create directory, error %d", err);
1006                 goto out_cancel;
1007         }
1008         mutex_unlock(&dir_ui->ui_mutex);
1009
1010         ubifs_release_budget(c, &req);
1011         d_instantiate(dentry, inode);
1012         fscrypt_free_filename(&nm);
1013         return 0;
1014
1015 out_cancel:
1016         dir->i_size -= sz_change;
1017         dir_ui->ui_size = dir->i_size;
1018         drop_nlink(dir);
1019         mutex_unlock(&dir_ui->ui_mutex);
1020 out_inode:
1021         make_bad_inode(inode);
1022         iput(inode);
1023 out_fname:
1024         fscrypt_free_filename(&nm);
1025 out_budg:
1026         ubifs_release_budget(c, &req);
1027         return err;
1028 }
1029
1030 static int ubifs_mknod(struct inode *dir, struct dentry *dentry,
1031                        umode_t mode, dev_t rdev)
1032 {
1033         struct inode *inode;
1034         struct ubifs_inode *ui;
1035         struct ubifs_inode *dir_ui = ubifs_inode(dir);
1036         struct ubifs_info *c = dir->i_sb->s_fs_info;
1037         union ubifs_dev_desc *dev = NULL;
1038         int sz_change;
1039         int err, devlen = 0;
1040         struct ubifs_budget_req req = { .new_ino = 1, .new_dent = 1,
1041                                         .dirtied_ino = 1 };
1042         struct fscrypt_name nm;
1043
1044         /*
1045          * Budget request settings: new inode, new direntry and changing parent
1046          * directory inode.
1047          */
1048
1049         dbg_gen("dent '%pd' in dir ino %lu", dentry, dir->i_ino);
1050
1051         if (S_ISBLK(mode) || S_ISCHR(mode)) {
1052                 dev = kmalloc(sizeof(union ubifs_dev_desc), GFP_NOFS);
1053                 if (!dev)
1054                         return -ENOMEM;
1055                 devlen = ubifs_encode_dev(dev, rdev);
1056         }
1057
1058         req.new_ino_d = ALIGN(devlen, 8);
1059         err = ubifs_budget_space(c, &req);
1060         if (err) {
1061                 kfree(dev);
1062                 return err;
1063         }
1064
1065         err = ubifs_prepare_create(dir, dentry, &nm);
1066         if (err) {
1067                 kfree(dev);
1068                 goto out_budg;
1069         }
1070
1071         sz_change = CALC_DENT_SIZE(fname_len(&nm));
1072
1073         inode = ubifs_new_inode(c, dir, mode);
1074         if (IS_ERR(inode)) {
1075                 kfree(dev);
1076                 err = PTR_ERR(inode);
1077                 goto out_fname;
1078         }
1079
1080         init_special_inode(inode, inode->i_mode, rdev);
1081         inode->i_size = ubifs_inode(inode)->ui_size = devlen;
1082         ui = ubifs_inode(inode);
1083         ui->data = dev;
1084         ui->data_len = devlen;
1085
1086         err = ubifs_init_security(dir, inode, &dentry->d_name);
1087         if (err)
1088                 goto out_inode;
1089
1090         mutex_lock(&dir_ui->ui_mutex);
1091         dir->i_size += sz_change;
1092         dir_ui->ui_size = dir->i_size;
1093         dir->i_mtime = dir->i_ctime = inode->i_ctime;
1094         err = ubifs_jnl_update(c, dir, &nm, inode, 0, 0);
1095         if (err)
1096                 goto out_cancel;
1097         mutex_unlock(&dir_ui->ui_mutex);
1098
1099         ubifs_release_budget(c, &req);
1100         insert_inode_hash(inode);
1101         d_instantiate(dentry, inode);
1102         fscrypt_free_filename(&nm);
1103         return 0;
1104
1105 out_cancel:
1106         dir->i_size -= sz_change;
1107         dir_ui->ui_size = dir->i_size;
1108         mutex_unlock(&dir_ui->ui_mutex);
1109 out_inode:
1110         make_bad_inode(inode);
1111         iput(inode);
1112 out_fname:
1113         fscrypt_free_filename(&nm);
1114 out_budg:
1115         ubifs_release_budget(c, &req);
1116         return err;
1117 }
1118
1119 static int ubifs_symlink(struct inode *dir, struct dentry *dentry,
1120                          const char *symname)
1121 {
1122         struct inode *inode;
1123         struct ubifs_inode *ui;
1124         struct ubifs_inode *dir_ui = ubifs_inode(dir);
1125         struct ubifs_info *c = dir->i_sb->s_fs_info;
1126         int err, sz_change, len = strlen(symname);
1127         struct fscrypt_str disk_link;
1128         struct ubifs_budget_req req = { .new_ino = 1, .new_dent = 1,
1129                                         .dirtied_ino = 1 };
1130         struct fscrypt_name nm;
1131
1132         dbg_gen("dent '%pd', target '%s' in dir ino %lu", dentry,
1133                 symname, dir->i_ino);
1134
1135         err = fscrypt_prepare_symlink(dir, symname, len, UBIFS_MAX_INO_DATA,
1136                                       &disk_link);
1137         if (err)
1138                 return err;
1139
1140         /*
1141          * Budget request settings: new inode, new direntry and changing parent
1142          * directory inode.
1143          */
1144         req.new_ino_d = ALIGN(disk_link.len - 1, 8);
1145         err = ubifs_budget_space(c, &req);
1146         if (err)
1147                 return err;
1148
1149         err = ubifs_prepare_create(dir, dentry, &nm);
1150         if (err)
1151                 goto out_budg;
1152
1153         sz_change = CALC_DENT_SIZE(fname_len(&nm));
1154
1155         inode = ubifs_new_inode(c, dir, S_IFLNK | S_IRWXUGO);
1156         if (IS_ERR(inode)) {
1157                 err = PTR_ERR(inode);
1158                 goto out_fname;
1159         }
1160
1161         ui = ubifs_inode(inode);
1162         ui->data = kmalloc(disk_link.len, GFP_NOFS);
1163         if (!ui->data) {
1164                 err = -ENOMEM;
1165                 goto out_inode;
1166         }
1167
1168         if (IS_ENCRYPTED(inode)) {
1169                 disk_link.name = ui->data; /* encrypt directly into ui->data */
1170                 err = fscrypt_encrypt_symlink(inode, symname, len, &disk_link);
1171                 if (err)
1172                         goto out_inode;
1173         } else {
1174                 memcpy(ui->data, disk_link.name, disk_link.len);
1175                 inode->i_link = ui->data;
1176         }
1177
1178         /*
1179          * The terminating zero byte is not written to the flash media and it
1180          * is put just to make later in-memory string processing simpler. Thus,
1181          * data length is @disk_link.len - 1, not @disk_link.len.
1182          */
1183         ui->data_len = disk_link.len - 1;
1184         inode->i_size = ubifs_inode(inode)->ui_size = disk_link.len - 1;
1185
1186         err = ubifs_init_security(dir, inode, &dentry->d_name);
1187         if (err)
1188                 goto out_inode;
1189
1190         mutex_lock(&dir_ui->ui_mutex);
1191         dir->i_size += sz_change;
1192         dir_ui->ui_size = dir->i_size;
1193         dir->i_mtime = dir->i_ctime = inode->i_ctime;
1194         err = ubifs_jnl_update(c, dir, &nm, inode, 0, 0);
1195         if (err)
1196                 goto out_cancel;
1197         mutex_unlock(&dir_ui->ui_mutex);
1198
1199         insert_inode_hash(inode);
1200         d_instantiate(dentry, inode);
1201         err = 0;
1202         goto out_fname;
1203
1204 out_cancel:
1205         dir->i_size -= sz_change;
1206         dir_ui->ui_size = dir->i_size;
1207         mutex_unlock(&dir_ui->ui_mutex);
1208 out_inode:
1209         make_bad_inode(inode);
1210         iput(inode);
1211 out_fname:
1212         fscrypt_free_filename(&nm);
1213 out_budg:
1214         ubifs_release_budget(c, &req);
1215         return err;
1216 }
1217
1218 /**
1219  * lock_4_inodes - a wrapper for locking three UBIFS inodes.
1220  * @inode1: first inode
1221  * @inode2: second inode
1222  * @inode3: third inode
1223  * @inode4: fouth inode
1224  *
1225  * This function is used for 'ubifs_rename()' and @inode1 may be the same as
1226  * @inode2 whereas @inode3 and @inode4 may be %NULL.
1227  *
1228  * We do not implement any tricks to guarantee strict lock ordering, because
1229  * VFS has already done it for us on the @i_mutex. So this is just a simple
1230  * wrapper function.
1231  */
1232 static void lock_4_inodes(struct inode *inode1, struct inode *inode2,
1233                           struct inode *inode3, struct inode *inode4)
1234 {
1235         mutex_lock_nested(&ubifs_inode(inode1)->ui_mutex, WB_MUTEX_1);
1236         if (inode2 != inode1)
1237                 mutex_lock_nested(&ubifs_inode(inode2)->ui_mutex, WB_MUTEX_2);
1238         if (inode3)
1239                 mutex_lock_nested(&ubifs_inode(inode3)->ui_mutex, WB_MUTEX_3);
1240         if (inode4)
1241                 mutex_lock_nested(&ubifs_inode(inode4)->ui_mutex, WB_MUTEX_4);
1242 }
1243
1244 /**
1245  * unlock_4_inodes - a wrapper for unlocking three UBIFS inodes for rename.
1246  * @inode1: first inode
1247  * @inode2: second inode
1248  * @inode3: third inode
1249  * @inode4: fouth inode
1250  */
1251 static void unlock_4_inodes(struct inode *inode1, struct inode *inode2,
1252                             struct inode *inode3, struct inode *inode4)
1253 {
1254         if (inode4)
1255                 mutex_unlock(&ubifs_inode(inode4)->ui_mutex);
1256         if (inode3)
1257                 mutex_unlock(&ubifs_inode(inode3)->ui_mutex);
1258         if (inode1 != inode2)
1259                 mutex_unlock(&ubifs_inode(inode2)->ui_mutex);
1260         mutex_unlock(&ubifs_inode(inode1)->ui_mutex);
1261 }
1262
1263 static int do_rename(struct inode *old_dir, struct dentry *old_dentry,
1264                      struct inode *new_dir, struct dentry *new_dentry,
1265                      unsigned int flags)
1266 {
1267         struct ubifs_info *c = old_dir->i_sb->s_fs_info;
1268         struct inode *old_inode = d_inode(old_dentry);
1269         struct inode *new_inode = d_inode(new_dentry);
1270         struct inode *whiteout = NULL;
1271         struct ubifs_inode *old_inode_ui = ubifs_inode(old_inode);
1272         struct ubifs_inode *whiteout_ui = NULL;
1273         int err, release, sync = 0, move = (new_dir != old_dir);
1274         int is_dir = S_ISDIR(old_inode->i_mode);
1275         int unlink = !!new_inode, new_sz, old_sz;
1276         struct ubifs_budget_req req = { .new_dent = 1, .mod_dent = 1,
1277                                         .dirtied_ino = 3 };
1278         struct ubifs_budget_req ino_req = { .dirtied_ino = 1,
1279                         .dirtied_ino_d = ALIGN(old_inode_ui->data_len, 8) };
1280         struct timespec64 time;
1281         unsigned int saved_nlink;
1282         struct fscrypt_name old_nm, new_nm;
1283
1284         /*
1285          * Budget request settings: deletion direntry, new direntry, removing
1286          * the old inode, and changing old and new parent directory inodes.
1287          *
1288          * However, this operation also marks the target inode as dirty and
1289          * does not write it, so we allocate budget for the target inode
1290          * separately.
1291          */
1292
1293         dbg_gen("dent '%pd' ino %lu in dir ino %lu to dent '%pd' in dir ino %lu flags 0x%x",
1294                 old_dentry, old_inode->i_ino, old_dir->i_ino,
1295                 new_dentry, new_dir->i_ino, flags);
1296
1297         if (unlink) {
1298                 ubifs_assert(c, inode_is_locked(new_inode));
1299
1300                 /* Budget for old inode's data when its nlink > 1. */
1301                 req.dirtied_ino_d = ALIGN(ubifs_inode(new_inode)->data_len, 8);
1302                 err = ubifs_purge_xattrs(new_inode);
1303                 if (err)
1304                         return err;
1305         }
1306
1307         if (unlink && is_dir) {
1308                 err = ubifs_check_dir_empty(new_inode);
1309                 if (err)
1310                         return err;
1311         }
1312
1313         err = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_nm);
1314         if (err)
1315                 return err;
1316
1317         err = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_nm);
1318         if (err) {
1319                 fscrypt_free_filename(&old_nm);
1320                 return err;
1321         }
1322
1323         new_sz = CALC_DENT_SIZE(fname_len(&new_nm));
1324         old_sz = CALC_DENT_SIZE(fname_len(&old_nm));
1325
1326         err = ubifs_budget_space(c, &req);
1327         if (err) {
1328                 fscrypt_free_filename(&old_nm);
1329                 fscrypt_free_filename(&new_nm);
1330                 return err;
1331         }
1332         err = ubifs_budget_space(c, &ino_req);
1333         if (err) {
1334                 fscrypt_free_filename(&old_nm);
1335                 fscrypt_free_filename(&new_nm);
1336                 ubifs_release_budget(c, &req);
1337                 return err;
1338         }
1339
1340         if (flags & RENAME_WHITEOUT) {
1341                 union ubifs_dev_desc *dev = NULL;
1342                 struct ubifs_budget_req wht_req;
1343
1344                 dev = kmalloc(sizeof(union ubifs_dev_desc), GFP_NOFS);
1345                 if (!dev) {
1346                         err = -ENOMEM;
1347                         goto out_release;
1348                 }
1349
1350                 err = do_tmpfile(old_dir, old_dentry, S_IFCHR | WHITEOUT_MODE, &whiteout);
1351                 if (err) {
1352                         kfree(dev);
1353                         goto out_release;
1354                 }
1355
1356                 spin_lock(&whiteout->i_lock);
1357                 whiteout->i_state |= I_LINKABLE;
1358                 spin_unlock(&whiteout->i_lock);
1359
1360                 whiteout_ui = ubifs_inode(whiteout);
1361                 whiteout_ui->data = dev;
1362                 whiteout_ui->data_len = ubifs_encode_dev(dev, MKDEV(0, 0));
1363                 ubifs_assert(c, !whiteout_ui->dirty);
1364
1365                 memset(&wht_req, 0, sizeof(struct ubifs_budget_req));
1366                 wht_req.dirtied_ino = 1;
1367                 wht_req.dirtied_ino_d = ALIGN(whiteout_ui->data_len, 8);
1368                 /*
1369                  * To avoid deadlock between space budget (holds ui_mutex and
1370                  * waits wb work) and writeback work(waits ui_mutex), do space
1371                  * budget before ubifs inodes locked.
1372                  */
1373                 err = ubifs_budget_space(c, &wht_req);
1374                 if (err) {
1375                         iput(whiteout);
1376                         goto out_release;
1377                 }
1378
1379                 /* Add the old_dentry size to the old_dir size. */
1380                 old_sz -= CALC_DENT_SIZE(fname_len(&old_nm));
1381         }
1382
1383         lock_4_inodes(old_dir, new_dir, new_inode, whiteout);
1384
1385         /*
1386          * Like most other Unix systems, set the @i_ctime for inodes on a
1387          * rename.
1388          */
1389         time = current_time(old_dir);
1390         old_inode->i_ctime = time;
1391
1392         /* We must adjust parent link count when renaming directories */
1393         if (is_dir) {
1394                 if (move) {
1395                         /*
1396                          * @old_dir loses a link because we are moving
1397                          * @old_inode to a different directory.
1398                          */
1399                         drop_nlink(old_dir);
1400                         /*
1401                          * @new_dir only gains a link if we are not also
1402                          * overwriting an existing directory.
1403                          */
1404                         if (!unlink)
1405                                 inc_nlink(new_dir);
1406                 } else {
1407                         /*
1408                          * @old_inode is not moving to a different directory,
1409                          * but @old_dir still loses a link if we are
1410                          * overwriting an existing directory.
1411                          */
1412                         if (unlink)
1413                                 drop_nlink(old_dir);
1414                 }
1415         }
1416
1417         old_dir->i_size -= old_sz;
1418         ubifs_inode(old_dir)->ui_size = old_dir->i_size;
1419         old_dir->i_mtime = old_dir->i_ctime = time;
1420         new_dir->i_mtime = new_dir->i_ctime = time;
1421
1422         /*
1423          * And finally, if we unlinked a direntry which happened to have the
1424          * same name as the moved direntry, we have to decrement @i_nlink of
1425          * the unlinked inode and change its ctime.
1426          */
1427         if (unlink) {
1428                 /*
1429                  * Directories cannot have hard-links, so if this is a
1430                  * directory, just clear @i_nlink.
1431                  */
1432                 saved_nlink = new_inode->i_nlink;
1433                 if (is_dir)
1434                         clear_nlink(new_inode);
1435                 else
1436                         drop_nlink(new_inode);
1437                 new_inode->i_ctime = time;
1438         } else {
1439                 new_dir->i_size += new_sz;
1440                 ubifs_inode(new_dir)->ui_size = new_dir->i_size;
1441         }
1442
1443         /*
1444          * Do not ask 'ubifs_jnl_rename()' to flush write-buffer if @old_inode
1445          * is dirty, because this will be done later on at the end of
1446          * 'ubifs_rename()'.
1447          */
1448         if (IS_SYNC(old_inode)) {
1449                 sync = IS_DIRSYNC(old_dir) || IS_DIRSYNC(new_dir);
1450                 if (unlink && IS_SYNC(new_inode))
1451                         sync = 1;
1452         }
1453
1454         if (whiteout) {
1455                 inc_nlink(whiteout);
1456                 mark_inode_dirty(whiteout);
1457
1458                 spin_lock(&whiteout->i_lock);
1459                 whiteout->i_state &= ~I_LINKABLE;
1460                 spin_unlock(&whiteout->i_lock);
1461
1462                 iput(whiteout);
1463         }
1464
1465         err = ubifs_jnl_rename(c, old_dir, old_inode, &old_nm, new_dir,
1466                                new_inode, &new_nm, whiteout, sync);
1467         if (err)
1468                 goto out_cancel;
1469
1470         unlock_4_inodes(old_dir, new_dir, new_inode, whiteout);
1471         ubifs_release_budget(c, &req);
1472
1473         mutex_lock(&old_inode_ui->ui_mutex);
1474         release = old_inode_ui->dirty;
1475         mark_inode_dirty_sync(old_inode);
1476         mutex_unlock(&old_inode_ui->ui_mutex);
1477
1478         if (release)
1479                 ubifs_release_budget(c, &ino_req);
1480         if (IS_SYNC(old_inode))
1481                 err = old_inode->i_sb->s_op->write_inode(old_inode, NULL);
1482
1483         fscrypt_free_filename(&old_nm);
1484         fscrypt_free_filename(&new_nm);
1485         return err;
1486
1487 out_cancel:
1488         if (unlink) {
1489                 set_nlink(new_inode, saved_nlink);
1490         } else {
1491                 new_dir->i_size -= new_sz;
1492                 ubifs_inode(new_dir)->ui_size = new_dir->i_size;
1493         }
1494         old_dir->i_size += old_sz;
1495         ubifs_inode(old_dir)->ui_size = old_dir->i_size;
1496         if (is_dir) {
1497                 if (move) {
1498                         inc_nlink(old_dir);
1499                         if (!unlink)
1500                                 drop_nlink(new_dir);
1501                 } else {
1502                         if (unlink)
1503                                 inc_nlink(old_dir);
1504                 }
1505         }
1506         if (whiteout) {
1507                 drop_nlink(whiteout);
1508                 iput(whiteout);
1509         }
1510         unlock_4_inodes(old_dir, new_dir, new_inode, whiteout);
1511 out_release:
1512         ubifs_release_budget(c, &ino_req);
1513         ubifs_release_budget(c, &req);
1514         fscrypt_free_filename(&old_nm);
1515         fscrypt_free_filename(&new_nm);
1516         return err;
1517 }
1518
1519 static int ubifs_xrename(struct inode *old_dir, struct dentry *old_dentry,
1520                         struct inode *new_dir, struct dentry *new_dentry)
1521 {
1522         struct ubifs_info *c = old_dir->i_sb->s_fs_info;
1523         struct ubifs_budget_req req = { .new_dent = 1, .mod_dent = 1,
1524                                 .dirtied_ino = 2 };
1525         int sync = IS_DIRSYNC(old_dir) || IS_DIRSYNC(new_dir);
1526         struct inode *fst_inode = d_inode(old_dentry);
1527         struct inode *snd_inode = d_inode(new_dentry);
1528         struct timespec64 time;
1529         int err;
1530         struct fscrypt_name fst_nm, snd_nm;
1531
1532         ubifs_assert(c, fst_inode && snd_inode);
1533
1534         err = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &fst_nm);
1535         if (err)
1536                 return err;
1537
1538         err = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &snd_nm);
1539         if (err) {
1540                 fscrypt_free_filename(&fst_nm);
1541                 return err;
1542         }
1543
1544         err = ubifs_budget_space(c, &req);
1545         if (err)
1546                 goto out;
1547
1548         lock_4_inodes(old_dir, new_dir, NULL, NULL);
1549
1550         time = current_time(old_dir);
1551         fst_inode->i_ctime = time;
1552         snd_inode->i_ctime = time;
1553         old_dir->i_mtime = old_dir->i_ctime = time;
1554         new_dir->i_mtime = new_dir->i_ctime = time;
1555
1556         if (old_dir != new_dir) {
1557                 if (S_ISDIR(fst_inode->i_mode) && !S_ISDIR(snd_inode->i_mode)) {
1558                         inc_nlink(new_dir);
1559                         drop_nlink(old_dir);
1560                 }
1561                 else if (!S_ISDIR(fst_inode->i_mode) && S_ISDIR(snd_inode->i_mode)) {
1562                         drop_nlink(new_dir);
1563                         inc_nlink(old_dir);
1564                 }
1565         }
1566
1567         err = ubifs_jnl_xrename(c, old_dir, fst_inode, &fst_nm, new_dir,
1568                                 snd_inode, &snd_nm, sync);
1569
1570         unlock_4_inodes(old_dir, new_dir, NULL, NULL);
1571         ubifs_release_budget(c, &req);
1572
1573 out:
1574         fscrypt_free_filename(&fst_nm);
1575         fscrypt_free_filename(&snd_nm);
1576         return err;
1577 }
1578
1579 static int ubifs_rename(struct inode *old_dir, struct dentry *old_dentry,
1580                         struct inode *new_dir, struct dentry *new_dentry,
1581                         unsigned int flags)
1582 {
1583         int err;
1584         struct ubifs_info *c = old_dir->i_sb->s_fs_info;
1585
1586         if (flags & ~(RENAME_NOREPLACE | RENAME_WHITEOUT | RENAME_EXCHANGE))
1587                 return -EINVAL;
1588
1589         ubifs_assert(c, inode_is_locked(old_dir));
1590         ubifs_assert(c, inode_is_locked(new_dir));
1591
1592         err = fscrypt_prepare_rename(old_dir, old_dentry, new_dir, new_dentry,
1593                                      flags);
1594         if (err)
1595                 return err;
1596
1597         if (flags & RENAME_EXCHANGE)
1598                 return ubifs_xrename(old_dir, old_dentry, new_dir, new_dentry);
1599
1600         return do_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
1601 }
1602
1603 int ubifs_getattr(const struct path *path, struct kstat *stat,
1604                   u32 request_mask, unsigned int flags)
1605 {
1606         loff_t size;
1607         struct inode *inode = d_inode(path->dentry);
1608         struct ubifs_inode *ui = ubifs_inode(inode);
1609
1610         mutex_lock(&ui->ui_mutex);
1611
1612         if (ui->flags & UBIFS_APPEND_FL)
1613                 stat->attributes |= STATX_ATTR_APPEND;
1614         if (ui->flags & UBIFS_COMPR_FL)
1615                 stat->attributes |= STATX_ATTR_COMPRESSED;
1616         if (ui->flags & UBIFS_CRYPT_FL)
1617                 stat->attributes |= STATX_ATTR_ENCRYPTED;
1618         if (ui->flags & UBIFS_IMMUTABLE_FL)
1619                 stat->attributes |= STATX_ATTR_IMMUTABLE;
1620
1621         stat->attributes_mask |= (STATX_ATTR_APPEND |
1622                                 STATX_ATTR_COMPRESSED |
1623                                 STATX_ATTR_ENCRYPTED |
1624                                 STATX_ATTR_IMMUTABLE);
1625
1626         generic_fillattr(inode, stat);
1627         stat->blksize = UBIFS_BLOCK_SIZE;
1628         stat->size = ui->ui_size;
1629
1630         /*
1631          * Unfortunately, the 'stat()' system call was designed for block
1632          * device based file systems, and it is not appropriate for UBIFS,
1633          * because UBIFS does not have notion of "block". For example, it is
1634          * difficult to tell how many block a directory takes - it actually
1635          * takes less than 300 bytes, but we have to round it to block size,
1636          * which introduces large mistake. This makes utilities like 'du' to
1637          * report completely senseless numbers. This is the reason why UBIFS
1638          * goes the same way as JFFS2 - it reports zero blocks for everything
1639          * but regular files, which makes more sense than reporting completely
1640          * wrong sizes.
1641          */
1642         if (S_ISREG(inode->i_mode)) {
1643                 size = ui->xattr_size;
1644                 size += stat->size;
1645                 size = ALIGN(size, UBIFS_BLOCK_SIZE);
1646                 /*
1647                  * Note, user-space expects 512-byte blocks count irrespectively
1648                  * of what was reported in @stat->size.
1649                  */
1650                 stat->blocks = size >> 9;
1651         } else
1652                 stat->blocks = 0;
1653         mutex_unlock(&ui->ui_mutex);
1654         return 0;
1655 }
1656
1657 static int ubifs_dir_open(struct inode *dir, struct file *file)
1658 {
1659         if (ubifs_crypt_is_encrypted(dir))
1660                 return fscrypt_get_encryption_info(dir) ? -EACCES : 0;
1661
1662         return 0;
1663 }
1664
1665 const struct inode_operations ubifs_dir_inode_operations = {
1666         .lookup      = ubifs_lookup,
1667         .create      = ubifs_create,
1668         .link        = ubifs_link,
1669         .symlink     = ubifs_symlink,
1670         .unlink      = ubifs_unlink,
1671         .mkdir       = ubifs_mkdir,
1672         .rmdir       = ubifs_rmdir,
1673         .mknod       = ubifs_mknod,
1674         .rename      = ubifs_rename,
1675         .setattr     = ubifs_setattr,
1676         .getattr     = ubifs_getattr,
1677 #ifdef CONFIG_UBIFS_FS_XATTR
1678         .listxattr   = ubifs_listxattr,
1679 #endif
1680         .update_time = ubifs_update_time,
1681         .tmpfile     = ubifs_tmpfile,
1682 };
1683
1684 const struct file_operations ubifs_dir_operations = {
1685         .llseek         = generic_file_llseek,
1686         .release        = ubifs_dir_release,
1687         .read           = generic_read_dir,
1688         .iterate_shared = ubifs_readdir,
1689         .fsync          = ubifs_fsync,
1690         .unlocked_ioctl = ubifs_ioctl,
1691         .open           = ubifs_dir_open,
1692 #ifdef CONFIG_COMPAT
1693         .compat_ioctl   = ubifs_compat_ioctl,
1694 #endif
1695 };