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