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