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