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