xref: /openbmc/linux/fs/overlayfs/inode.c (revision a01822e9)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *
4  * Copyright (C) 2011 Novell Inc.
5  */
6 
7 #include <linux/fs.h>
8 #include <linux/slab.h>
9 #include <linux/cred.h>
10 #include <linux/xattr.h>
11 #include <linux/posix_acl.h>
12 #include <linux/ratelimit.h>
13 #include "overlayfs.h"
14 
15 
16 int ovl_setattr(struct dentry *dentry, struct iattr *attr)
17 {
18 	int err;
19 	bool full_copy_up = false;
20 	struct dentry *upperdentry;
21 	const struct cred *old_cred;
22 
23 	err = setattr_prepare(dentry, attr);
24 	if (err)
25 		return err;
26 
27 	err = ovl_want_write(dentry);
28 	if (err)
29 		goto out;
30 
31 	if (attr->ia_valid & ATTR_SIZE) {
32 		struct inode *realinode = d_inode(ovl_dentry_real(dentry));
33 
34 		err = -ETXTBSY;
35 		if (atomic_read(&realinode->i_writecount) < 0)
36 			goto out_drop_write;
37 
38 		/* Truncate should trigger data copy up as well */
39 		full_copy_up = true;
40 	}
41 
42 	if (!full_copy_up)
43 		err = ovl_copy_up(dentry);
44 	else
45 		err = ovl_copy_up_with_data(dentry);
46 	if (!err) {
47 		struct inode *winode = NULL;
48 
49 		upperdentry = ovl_dentry_upper(dentry);
50 
51 		if (attr->ia_valid & ATTR_SIZE) {
52 			winode = d_inode(upperdentry);
53 			err = get_write_access(winode);
54 			if (err)
55 				goto out_drop_write;
56 		}
57 
58 		if (attr->ia_valid & (ATTR_KILL_SUID|ATTR_KILL_SGID))
59 			attr->ia_valid &= ~ATTR_MODE;
60 
61 		/*
62 		 * We might have to translate ovl file into real file object
63 		 * once use cases emerge.  For now, simply don't let underlying
64 		 * filesystem rely on attr->ia_file
65 		 */
66 		attr->ia_valid &= ~ATTR_FILE;
67 
68 		/*
69 		 * If open(O_TRUNC) is done, VFS calls ->setattr with ATTR_OPEN
70 		 * set.  Overlayfs does not pass O_TRUNC flag to underlying
71 		 * filesystem during open -> do not pass ATTR_OPEN.  This
72 		 * disables optimization in fuse which assumes open(O_TRUNC)
73 		 * already set file size to 0.  But we never passed O_TRUNC to
74 		 * fuse.  So by clearing ATTR_OPEN, fuse will be forced to send
75 		 * setattr request to server.
76 		 */
77 		attr->ia_valid &= ~ATTR_OPEN;
78 
79 		inode_lock(upperdentry->d_inode);
80 		old_cred = ovl_override_creds(dentry->d_sb);
81 		err = notify_change(upperdentry, attr, NULL);
82 		revert_creds(old_cred);
83 		if (!err)
84 			ovl_copyattr(upperdentry->d_inode, dentry->d_inode);
85 		inode_unlock(upperdentry->d_inode);
86 
87 		if (winode)
88 			put_write_access(winode);
89 	}
90 out_drop_write:
91 	ovl_drop_write(dentry);
92 out:
93 	return err;
94 }
95 
96 static int ovl_map_dev_ino(struct dentry *dentry, struct kstat *stat, int fsid)
97 {
98 	bool samefs = ovl_same_fs(dentry->d_sb);
99 	unsigned int xinobits = ovl_xino_bits(dentry->d_sb);
100 	unsigned int xinoshift = 64 - xinobits;
101 
102 	if (samefs) {
103 		/*
104 		 * When all layers are on the same fs, all real inode
105 		 * number are unique, so we use the overlay st_dev,
106 		 * which is friendly to du -x.
107 		 */
108 		stat->dev = dentry->d_sb->s_dev;
109 		return 0;
110 	} else if (xinobits) {
111 		/*
112 		 * All inode numbers of underlying fs should not be using the
113 		 * high xinobits, so we use high xinobits to partition the
114 		 * overlay st_ino address space. The high bits holds the fsid
115 		 * (upper fsid is 0). The lowest xinobit is reserved for mapping
116 		 * the non-peresistent inode numbers range in case of overflow.
117 		 * This way all overlay inode numbers are unique and use the
118 		 * overlay st_dev.
119 		 */
120 		if (likely(!(stat->ino >> xinoshift))) {
121 			stat->ino |= ((u64)fsid) << (xinoshift + 1);
122 			stat->dev = dentry->d_sb->s_dev;
123 			return 0;
124 		} else if (ovl_xino_warn(dentry->d_sb)) {
125 			pr_warn_ratelimited("inode number too big (%pd2, ino=%llu, xinobits=%d)\n",
126 					    dentry, stat->ino, xinobits);
127 		}
128 	}
129 
130 	/* The inode could not be mapped to a unified st_ino address space */
131 	if (S_ISDIR(dentry->d_inode->i_mode)) {
132 		/*
133 		 * Always use the overlay st_dev for directories, so 'find
134 		 * -xdev' will scan the entire overlay mount and won't cross the
135 		 * overlay mount boundaries.
136 		 *
137 		 * If not all layers are on the same fs the pair {real st_ino;
138 		 * overlay st_dev} is not unique, so use the non persistent
139 		 * overlay st_ino for directories.
140 		 */
141 		stat->dev = dentry->d_sb->s_dev;
142 		stat->ino = dentry->d_inode->i_ino;
143 	} else {
144 		/*
145 		 * For non-samefs setup, if we cannot map all layers st_ino
146 		 * to a unified address space, we need to make sure that st_dev
147 		 * is unique per underlying fs, so we use the unique anonymous
148 		 * bdev assigned to the underlying fs.
149 		 */
150 		stat->dev = OVL_FS(dentry->d_sb)->fs[fsid].pseudo_dev;
151 	}
152 
153 	return 0;
154 }
155 
156 int ovl_getattr(const struct path *path, struct kstat *stat,
157 		u32 request_mask, unsigned int flags)
158 {
159 	struct dentry *dentry = path->dentry;
160 	enum ovl_path_type type;
161 	struct path realpath;
162 	const struct cred *old_cred;
163 	bool is_dir = S_ISDIR(dentry->d_inode->i_mode);
164 	int fsid = 0;
165 	int err;
166 	bool metacopy_blocks = false;
167 
168 	metacopy_blocks = ovl_is_metacopy_dentry(dentry);
169 
170 	type = ovl_path_real(dentry, &realpath);
171 	old_cred = ovl_override_creds(dentry->d_sb);
172 	err = vfs_getattr(&realpath, stat, request_mask, flags);
173 	if (err)
174 		goto out;
175 
176 	/*
177 	 * For non-dir or same fs, we use st_ino of the copy up origin.
178 	 * This guaranties constant st_dev/st_ino across copy up.
179 	 * With xino feature and non-samefs, we use st_ino of the copy up
180 	 * origin masked with high bits that represent the layer id.
181 	 *
182 	 * If lower filesystem supports NFS file handles, this also guaranties
183 	 * persistent st_ino across mount cycle.
184 	 */
185 	if (!is_dir || ovl_same_dev(dentry->d_sb)) {
186 		if (!OVL_TYPE_UPPER(type)) {
187 			fsid = ovl_layer_lower(dentry)->fsid;
188 		} else if (OVL_TYPE_ORIGIN(type)) {
189 			struct kstat lowerstat;
190 			u32 lowermask = STATX_INO | STATX_BLOCKS |
191 					(!is_dir ? STATX_NLINK : 0);
192 
193 			ovl_path_lower(dentry, &realpath);
194 			err = vfs_getattr(&realpath, &lowerstat,
195 					  lowermask, flags);
196 			if (err)
197 				goto out;
198 
199 			/*
200 			 * Lower hardlinks may be broken on copy up to different
201 			 * upper files, so we cannot use the lower origin st_ino
202 			 * for those different files, even for the same fs case.
203 			 *
204 			 * Similarly, several redirected dirs can point to the
205 			 * same dir on a lower layer. With the "verify_lower"
206 			 * feature, we do not use the lower origin st_ino, if
207 			 * we haven't verified that this redirect is unique.
208 			 *
209 			 * With inodes index enabled, it is safe to use st_ino
210 			 * of an indexed origin. The index validates that the
211 			 * upper hardlink is not broken and that a redirected
212 			 * dir is the only redirect to that origin.
213 			 */
214 			if (ovl_test_flag(OVL_INDEX, d_inode(dentry)) ||
215 			    (!ovl_verify_lower(dentry->d_sb) &&
216 			     (is_dir || lowerstat.nlink == 1))) {
217 				fsid = ovl_layer_lower(dentry)->fsid;
218 				stat->ino = lowerstat.ino;
219 			}
220 
221 			/*
222 			 * If we are querying a metacopy dentry and lower
223 			 * dentry is data dentry, then use the blocks we
224 			 * queried just now. We don't have to do additional
225 			 * vfs_getattr(). If lower itself is metacopy, then
226 			 * additional vfs_getattr() is unavoidable.
227 			 */
228 			if (metacopy_blocks &&
229 			    realpath.dentry == ovl_dentry_lowerdata(dentry)) {
230 				stat->blocks = lowerstat.blocks;
231 				metacopy_blocks = false;
232 			}
233 		}
234 
235 		if (metacopy_blocks) {
236 			/*
237 			 * If lower is not same as lowerdata or if there was
238 			 * no origin on upper, we can end up here.
239 			 */
240 			struct kstat lowerdatastat;
241 			u32 lowermask = STATX_BLOCKS;
242 
243 			ovl_path_lowerdata(dentry, &realpath);
244 			err = vfs_getattr(&realpath, &lowerdatastat,
245 					  lowermask, flags);
246 			if (err)
247 				goto out;
248 			stat->blocks = lowerdatastat.blocks;
249 		}
250 	}
251 
252 	err = ovl_map_dev_ino(dentry, stat, fsid);
253 	if (err)
254 		goto out;
255 
256 	/*
257 	 * It's probably not worth it to count subdirs to get the
258 	 * correct link count.  nlink=1 seems to pacify 'find' and
259 	 * other utilities.
260 	 */
261 	if (is_dir && OVL_TYPE_MERGE(type))
262 		stat->nlink = 1;
263 
264 	/*
265 	 * Return the overlay inode nlinks for indexed upper inodes.
266 	 * Overlay inode nlink counts the union of the upper hardlinks
267 	 * and non-covered lower hardlinks. It does not include the upper
268 	 * index hardlink.
269 	 */
270 	if (!is_dir && ovl_test_flag(OVL_INDEX, d_inode(dentry)))
271 		stat->nlink = dentry->d_inode->i_nlink;
272 
273 out:
274 	revert_creds(old_cred);
275 
276 	return err;
277 }
278 
279 int ovl_permission(struct inode *inode, int mask)
280 {
281 	struct inode *upperinode = ovl_inode_upper(inode);
282 	struct inode *realinode = upperinode ?: ovl_inode_lower(inode);
283 	const struct cred *old_cred;
284 	int err;
285 
286 	/* Careful in RCU walk mode */
287 	if (!realinode) {
288 		WARN_ON(!(mask & MAY_NOT_BLOCK));
289 		return -ECHILD;
290 	}
291 
292 	/*
293 	 * Check overlay inode with the creds of task and underlying inode
294 	 * with creds of mounter
295 	 */
296 	err = generic_permission(inode, mask);
297 	if (err)
298 		return err;
299 
300 	old_cred = ovl_override_creds(inode->i_sb);
301 	if (!upperinode &&
302 	    !special_file(realinode->i_mode) && mask & MAY_WRITE) {
303 		mask &= ~(MAY_WRITE | MAY_APPEND);
304 		/* Make sure mounter can read file for copy up later */
305 		mask |= MAY_READ;
306 	}
307 	err = inode_permission(realinode, mask);
308 	revert_creds(old_cred);
309 
310 	return err;
311 }
312 
313 static const char *ovl_get_link(struct dentry *dentry,
314 				struct inode *inode,
315 				struct delayed_call *done)
316 {
317 	const struct cred *old_cred;
318 	const char *p;
319 
320 	if (!dentry)
321 		return ERR_PTR(-ECHILD);
322 
323 	old_cred = ovl_override_creds(dentry->d_sb);
324 	p = vfs_get_link(ovl_dentry_real(dentry), done);
325 	revert_creds(old_cred);
326 	return p;
327 }
328 
329 bool ovl_is_private_xattr(const char *name)
330 {
331 	return strncmp(name, OVL_XATTR_PREFIX,
332 		       sizeof(OVL_XATTR_PREFIX) - 1) == 0;
333 }
334 
335 int ovl_xattr_set(struct dentry *dentry, struct inode *inode, const char *name,
336 		  const void *value, size_t size, int flags)
337 {
338 	int err;
339 	struct dentry *upperdentry = ovl_i_dentry_upper(inode);
340 	struct dentry *realdentry = upperdentry ?: ovl_dentry_lower(dentry);
341 	const struct cred *old_cred;
342 
343 	err = ovl_want_write(dentry);
344 	if (err)
345 		goto out;
346 
347 	if (!value && !upperdentry) {
348 		err = vfs_getxattr(realdentry, name, NULL, 0);
349 		if (err < 0)
350 			goto out_drop_write;
351 	}
352 
353 	if (!upperdentry) {
354 		err = ovl_copy_up(dentry);
355 		if (err)
356 			goto out_drop_write;
357 
358 		realdentry = ovl_dentry_upper(dentry);
359 	}
360 
361 	old_cred = ovl_override_creds(dentry->d_sb);
362 	if (value)
363 		err = vfs_setxattr(realdentry, name, value, size, flags);
364 	else {
365 		WARN_ON(flags != XATTR_REPLACE);
366 		err = vfs_removexattr(realdentry, name);
367 	}
368 	revert_creds(old_cred);
369 
370 	/* copy c/mtime */
371 	ovl_copyattr(d_inode(realdentry), inode);
372 
373 out_drop_write:
374 	ovl_drop_write(dentry);
375 out:
376 	return err;
377 }
378 
379 int ovl_xattr_get(struct dentry *dentry, struct inode *inode, const char *name,
380 		  void *value, size_t size)
381 {
382 	ssize_t res;
383 	const struct cred *old_cred;
384 	struct dentry *realdentry =
385 		ovl_i_dentry_upper(inode) ?: ovl_dentry_lower(dentry);
386 
387 	old_cred = ovl_override_creds(dentry->d_sb);
388 	res = vfs_getxattr(realdentry, name, value, size);
389 	revert_creds(old_cred);
390 	return res;
391 }
392 
393 static bool ovl_can_list(const char *s)
394 {
395 	/* List all non-trusted xatts */
396 	if (strncmp(s, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) != 0)
397 		return true;
398 
399 	/* Never list trusted.overlay, list other trusted for superuser only */
400 	return !ovl_is_private_xattr(s) &&
401 	       ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN);
402 }
403 
404 ssize_t ovl_listxattr(struct dentry *dentry, char *list, size_t size)
405 {
406 	struct dentry *realdentry = ovl_dentry_real(dentry);
407 	ssize_t res;
408 	size_t len;
409 	char *s;
410 	const struct cred *old_cred;
411 
412 	old_cred = ovl_override_creds(dentry->d_sb);
413 	res = vfs_listxattr(realdentry, list, size);
414 	revert_creds(old_cred);
415 	if (res <= 0 || size == 0)
416 		return res;
417 
418 	/* filter out private xattrs */
419 	for (s = list, len = res; len;) {
420 		size_t slen = strnlen(s, len) + 1;
421 
422 		/* underlying fs providing us with an broken xattr list? */
423 		if (WARN_ON(slen > len))
424 			return -EIO;
425 
426 		len -= slen;
427 		if (!ovl_can_list(s)) {
428 			res -= slen;
429 			memmove(s, s + slen, len);
430 		} else {
431 			s += slen;
432 		}
433 	}
434 
435 	return res;
436 }
437 
438 struct posix_acl *ovl_get_acl(struct inode *inode, int type)
439 {
440 	struct inode *realinode = ovl_inode_real(inode);
441 	const struct cred *old_cred;
442 	struct posix_acl *acl;
443 
444 	if (!IS_ENABLED(CONFIG_FS_POSIX_ACL) || !IS_POSIXACL(realinode))
445 		return NULL;
446 
447 	old_cred = ovl_override_creds(inode->i_sb);
448 	acl = get_acl(realinode, type);
449 	revert_creds(old_cred);
450 
451 	return acl;
452 }
453 
454 int ovl_update_time(struct inode *inode, struct timespec64 *ts, int flags)
455 {
456 	if (flags & S_ATIME) {
457 		struct ovl_fs *ofs = inode->i_sb->s_fs_info;
458 		struct path upperpath = {
459 			.mnt = ofs->upper_mnt,
460 			.dentry = ovl_upperdentry_dereference(OVL_I(inode)),
461 		};
462 
463 		if (upperpath.dentry) {
464 			touch_atime(&upperpath);
465 			inode->i_atime = d_inode(upperpath.dentry)->i_atime;
466 		}
467 	}
468 	return 0;
469 }
470 
471 static int ovl_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
472 		      u64 start, u64 len)
473 {
474 	int err;
475 	struct inode *realinode = ovl_inode_real(inode);
476 	const struct cred *old_cred;
477 
478 	if (!realinode->i_op->fiemap)
479 		return -EOPNOTSUPP;
480 
481 	old_cred = ovl_override_creds(inode->i_sb);
482 
483 	if (fieinfo->fi_flags & FIEMAP_FLAG_SYNC)
484 		filemap_write_and_wait(realinode->i_mapping);
485 
486 	err = realinode->i_op->fiemap(realinode, fieinfo, start, len);
487 	revert_creds(old_cred);
488 
489 	return err;
490 }
491 
492 static const struct inode_operations ovl_file_inode_operations = {
493 	.setattr	= ovl_setattr,
494 	.permission	= ovl_permission,
495 	.getattr	= ovl_getattr,
496 	.listxattr	= ovl_listxattr,
497 	.get_acl	= ovl_get_acl,
498 	.update_time	= ovl_update_time,
499 	.fiemap		= ovl_fiemap,
500 };
501 
502 static const struct inode_operations ovl_symlink_inode_operations = {
503 	.setattr	= ovl_setattr,
504 	.get_link	= ovl_get_link,
505 	.getattr	= ovl_getattr,
506 	.listxattr	= ovl_listxattr,
507 	.update_time	= ovl_update_time,
508 };
509 
510 static const struct inode_operations ovl_special_inode_operations = {
511 	.setattr	= ovl_setattr,
512 	.permission	= ovl_permission,
513 	.getattr	= ovl_getattr,
514 	.listxattr	= ovl_listxattr,
515 	.get_acl	= ovl_get_acl,
516 	.update_time	= ovl_update_time,
517 };
518 
519 static const struct address_space_operations ovl_aops = {
520 	/* For O_DIRECT dentry_open() checks f_mapping->a_ops->direct_IO */
521 	.direct_IO		= noop_direct_IO,
522 };
523 
524 /*
525  * It is possible to stack overlayfs instance on top of another
526  * overlayfs instance as lower layer. We need to annotate the
527  * stackable i_mutex locks according to stack level of the super
528  * block instance. An overlayfs instance can never be in stack
529  * depth 0 (there is always a real fs below it).  An overlayfs
530  * inode lock will use the lockdep annotaion ovl_i_mutex_key[depth].
531  *
532  * For example, here is a snip from /proc/lockdep_chains after
533  * dir_iterate of nested overlayfs:
534  *
535  * [...] &ovl_i_mutex_dir_key[depth]   (stack_depth=2)
536  * [...] &ovl_i_mutex_dir_key[depth]#2 (stack_depth=1)
537  * [...] &type->i_mutex_dir_key        (stack_depth=0)
538  *
539  * Locking order w.r.t ovl_want_write() is important for nested overlayfs.
540  *
541  * This chain is valid:
542  * - inode->i_rwsem			(inode_lock[2])
543  * - upper_mnt->mnt_sb->s_writers	(ovl_want_write[0])
544  * - OVL_I(inode)->lock			(ovl_inode_lock[2])
545  * - OVL_I(lowerinode)->lock		(ovl_inode_lock[1])
546  *
547  * And this chain is valid:
548  * - inode->i_rwsem			(inode_lock[2])
549  * - OVL_I(inode)->lock			(ovl_inode_lock[2])
550  * - lowerinode->i_rwsem		(inode_lock[1])
551  * - OVL_I(lowerinode)->lock		(ovl_inode_lock[1])
552  *
553  * But lowerinode->i_rwsem SHOULD NOT be acquired while ovl_want_write() is
554  * held, because it is in reverse order of the non-nested case using the same
555  * upper fs:
556  * - inode->i_rwsem			(inode_lock[1])
557  * - upper_mnt->mnt_sb->s_writers	(ovl_want_write[0])
558  * - OVL_I(inode)->lock			(ovl_inode_lock[1])
559  */
560 #define OVL_MAX_NESTING FILESYSTEM_MAX_STACK_DEPTH
561 
562 static inline void ovl_lockdep_annotate_inode_mutex_key(struct inode *inode)
563 {
564 #ifdef CONFIG_LOCKDEP
565 	static struct lock_class_key ovl_i_mutex_key[OVL_MAX_NESTING];
566 	static struct lock_class_key ovl_i_mutex_dir_key[OVL_MAX_NESTING];
567 	static struct lock_class_key ovl_i_lock_key[OVL_MAX_NESTING];
568 
569 	int depth = inode->i_sb->s_stack_depth - 1;
570 
571 	if (WARN_ON_ONCE(depth < 0 || depth >= OVL_MAX_NESTING))
572 		depth = 0;
573 
574 	if (S_ISDIR(inode->i_mode))
575 		lockdep_set_class(&inode->i_rwsem, &ovl_i_mutex_dir_key[depth]);
576 	else
577 		lockdep_set_class(&inode->i_rwsem, &ovl_i_mutex_key[depth]);
578 
579 	lockdep_set_class(&OVL_I(inode)->lock, &ovl_i_lock_key[depth]);
580 #endif
581 }
582 
583 static void ovl_next_ino(struct inode *inode)
584 {
585 	struct ovl_fs *ofs = inode->i_sb->s_fs_info;
586 
587 	inode->i_ino = atomic_long_inc_return(&ofs->last_ino);
588 	if (unlikely(!inode->i_ino))
589 		inode->i_ino = atomic_long_inc_return(&ofs->last_ino);
590 }
591 
592 static void ovl_map_ino(struct inode *inode, unsigned long ino, int fsid)
593 {
594 	int xinobits = ovl_xino_bits(inode->i_sb);
595 	unsigned int xinoshift = 64 - xinobits;
596 
597 	/*
598 	 * When d_ino is consistent with st_ino (samefs or i_ino has enough
599 	 * bits to encode layer), set the same value used for st_ino to i_ino,
600 	 * so inode number exposed via /proc/locks and a like will be
601 	 * consistent with d_ino and st_ino values. An i_ino value inconsistent
602 	 * with d_ino also causes nfsd readdirplus to fail.
603 	 */
604 	inode->i_ino = ino;
605 	if (ovl_same_fs(inode->i_sb)) {
606 		return;
607 	} else if (xinobits && likely(!(ino >> xinoshift))) {
608 		inode->i_ino |= (unsigned long)fsid << (xinoshift + 1);
609 		return;
610 	}
611 
612 	/*
613 	 * For directory inodes on non-samefs with xino disabled or xino
614 	 * overflow, we allocate a non-persistent inode number, to be used for
615 	 * resolving st_ino collisions in ovl_map_dev_ino().
616 	 *
617 	 * To avoid ino collision with legitimate xino values from upper
618 	 * layer (fsid 0), use the lowest xinobit to map the non
619 	 * persistent inode numbers to the unified st_ino address space.
620 	 */
621 	if (S_ISDIR(inode->i_mode)) {
622 		ovl_next_ino(inode);
623 		if (xinobits) {
624 			inode->i_ino &= ~0UL >> xinobits;
625 			inode->i_ino |= 1UL << xinoshift;
626 		}
627 	}
628 }
629 
630 void ovl_inode_init(struct inode *inode, struct ovl_inode_params *oip,
631 		    unsigned long ino, int fsid)
632 {
633 	struct inode *realinode;
634 
635 	if (oip->upperdentry)
636 		OVL_I(inode)->__upperdentry = oip->upperdentry;
637 	if (oip->lowerpath && oip->lowerpath->dentry)
638 		OVL_I(inode)->lower = igrab(d_inode(oip->lowerpath->dentry));
639 	if (oip->lowerdata)
640 		OVL_I(inode)->lowerdata = igrab(d_inode(oip->lowerdata));
641 
642 	realinode = ovl_inode_real(inode);
643 	ovl_copyattr(realinode, inode);
644 	ovl_copyflags(realinode, inode);
645 	ovl_map_ino(inode, ino, fsid);
646 }
647 
648 static void ovl_fill_inode(struct inode *inode, umode_t mode, dev_t rdev)
649 {
650 	inode->i_mode = mode;
651 	inode->i_flags |= S_NOCMTIME;
652 #ifdef CONFIG_FS_POSIX_ACL
653 	inode->i_acl = inode->i_default_acl = ACL_DONT_CACHE;
654 #endif
655 
656 	ovl_lockdep_annotate_inode_mutex_key(inode);
657 
658 	switch (mode & S_IFMT) {
659 	case S_IFREG:
660 		inode->i_op = &ovl_file_inode_operations;
661 		inode->i_fop = &ovl_file_operations;
662 		inode->i_mapping->a_ops = &ovl_aops;
663 		break;
664 
665 	case S_IFDIR:
666 		inode->i_op = &ovl_dir_inode_operations;
667 		inode->i_fop = &ovl_dir_operations;
668 		break;
669 
670 	case S_IFLNK:
671 		inode->i_op = &ovl_symlink_inode_operations;
672 		break;
673 
674 	default:
675 		inode->i_op = &ovl_special_inode_operations;
676 		init_special_inode(inode, mode, rdev);
677 		break;
678 	}
679 }
680 
681 /*
682  * With inodes index enabled, an overlay inode nlink counts the union of upper
683  * hardlinks and non-covered lower hardlinks. During the lifetime of a non-pure
684  * upper inode, the following nlink modifying operations can happen:
685  *
686  * 1. Lower hardlink copy up
687  * 2. Upper hardlink created, unlinked or renamed over
688  * 3. Lower hardlink whiteout or renamed over
689  *
690  * For the first, copy up case, the union nlink does not change, whether the
691  * operation succeeds or fails, but the upper inode nlink may change.
692  * Therefore, before copy up, we store the union nlink value relative to the
693  * lower inode nlink in the index inode xattr trusted.overlay.nlink.
694  *
695  * For the second, upper hardlink case, the union nlink should be incremented
696  * or decremented IFF the operation succeeds, aligned with nlink change of the
697  * upper inode. Therefore, before link/unlink/rename, we store the union nlink
698  * value relative to the upper inode nlink in the index inode.
699  *
700  * For the last, lower cover up case, we simplify things by preceding the
701  * whiteout or cover up with copy up. This makes sure that there is an index
702  * upper inode where the nlink xattr can be stored before the copied up upper
703  * entry is unlink.
704  */
705 #define OVL_NLINK_ADD_UPPER	(1 << 0)
706 
707 /*
708  * On-disk format for indexed nlink:
709  *
710  * nlink relative to the upper inode - "U[+-]NUM"
711  * nlink relative to the lower inode - "L[+-]NUM"
712  */
713 
714 static int ovl_set_nlink_common(struct dentry *dentry,
715 				struct dentry *realdentry, const char *format)
716 {
717 	struct inode *inode = d_inode(dentry);
718 	struct inode *realinode = d_inode(realdentry);
719 	char buf[13];
720 	int len;
721 
722 	len = snprintf(buf, sizeof(buf), format,
723 		       (int) (inode->i_nlink - realinode->i_nlink));
724 
725 	if (WARN_ON(len >= sizeof(buf)))
726 		return -EIO;
727 
728 	return ovl_do_setxattr(ovl_dentry_upper(dentry),
729 			       OVL_XATTR_NLINK, buf, len, 0);
730 }
731 
732 int ovl_set_nlink_upper(struct dentry *dentry)
733 {
734 	return ovl_set_nlink_common(dentry, ovl_dentry_upper(dentry), "U%+i");
735 }
736 
737 int ovl_set_nlink_lower(struct dentry *dentry)
738 {
739 	return ovl_set_nlink_common(dentry, ovl_dentry_lower(dentry), "L%+i");
740 }
741 
742 unsigned int ovl_get_nlink(struct dentry *lowerdentry,
743 			   struct dentry *upperdentry,
744 			   unsigned int fallback)
745 {
746 	int nlink_diff;
747 	int nlink;
748 	char buf[13];
749 	int err;
750 
751 	if (!lowerdentry || !upperdentry || d_inode(lowerdentry)->i_nlink == 1)
752 		return fallback;
753 
754 	err = vfs_getxattr(upperdentry, OVL_XATTR_NLINK, &buf, sizeof(buf) - 1);
755 	if (err < 0)
756 		goto fail;
757 
758 	buf[err] = '\0';
759 	if ((buf[0] != 'L' && buf[0] != 'U') ||
760 	    (buf[1] != '+' && buf[1] != '-'))
761 		goto fail;
762 
763 	err = kstrtoint(buf + 1, 10, &nlink_diff);
764 	if (err < 0)
765 		goto fail;
766 
767 	nlink = d_inode(buf[0] == 'L' ? lowerdentry : upperdentry)->i_nlink;
768 	nlink += nlink_diff;
769 
770 	if (nlink <= 0)
771 		goto fail;
772 
773 	return nlink;
774 
775 fail:
776 	pr_warn_ratelimited("failed to get index nlink (%pd2, err=%i)\n",
777 			    upperdentry, err);
778 	return fallback;
779 }
780 
781 struct inode *ovl_new_inode(struct super_block *sb, umode_t mode, dev_t rdev)
782 {
783 	struct inode *inode;
784 
785 	inode = new_inode(sb);
786 	if (inode)
787 		ovl_fill_inode(inode, mode, rdev);
788 
789 	return inode;
790 }
791 
792 static int ovl_inode_test(struct inode *inode, void *data)
793 {
794 	return inode->i_private == data;
795 }
796 
797 static int ovl_inode_set(struct inode *inode, void *data)
798 {
799 	inode->i_private = data;
800 	return 0;
801 }
802 
803 static bool ovl_verify_inode(struct inode *inode, struct dentry *lowerdentry,
804 			     struct dentry *upperdentry, bool strict)
805 {
806 	/*
807 	 * For directories, @strict verify from lookup path performs consistency
808 	 * checks, so NULL lower/upper in dentry must match NULL lower/upper in
809 	 * inode. Non @strict verify from NFS handle decode path passes NULL for
810 	 * 'unknown' lower/upper.
811 	 */
812 	if (S_ISDIR(inode->i_mode) && strict) {
813 		/* Real lower dir moved to upper layer under us? */
814 		if (!lowerdentry && ovl_inode_lower(inode))
815 			return false;
816 
817 		/* Lookup of an uncovered redirect origin? */
818 		if (!upperdentry && ovl_inode_upper(inode))
819 			return false;
820 	}
821 
822 	/*
823 	 * Allow non-NULL lower inode in ovl_inode even if lowerdentry is NULL.
824 	 * This happens when finding a copied up overlay inode for a renamed
825 	 * or hardlinked overlay dentry and lower dentry cannot be followed
826 	 * by origin because lower fs does not support file handles.
827 	 */
828 	if (lowerdentry && ovl_inode_lower(inode) != d_inode(lowerdentry))
829 		return false;
830 
831 	/*
832 	 * Allow non-NULL __upperdentry in inode even if upperdentry is NULL.
833 	 * This happens when finding a lower alias for a copied up hard link.
834 	 */
835 	if (upperdentry && ovl_inode_upper(inode) != d_inode(upperdentry))
836 		return false;
837 
838 	return true;
839 }
840 
841 struct inode *ovl_lookup_inode(struct super_block *sb, struct dentry *real,
842 			       bool is_upper)
843 {
844 	struct inode *inode, *key = d_inode(real);
845 
846 	inode = ilookup5(sb, (unsigned long) key, ovl_inode_test, key);
847 	if (!inode)
848 		return NULL;
849 
850 	if (!ovl_verify_inode(inode, is_upper ? NULL : real,
851 			      is_upper ? real : NULL, false)) {
852 		iput(inode);
853 		return ERR_PTR(-ESTALE);
854 	}
855 
856 	return inode;
857 }
858 
859 bool ovl_lookup_trap_inode(struct super_block *sb, struct dentry *dir)
860 {
861 	struct inode *key = d_inode(dir);
862 	struct inode *trap;
863 	bool res;
864 
865 	trap = ilookup5(sb, (unsigned long) key, ovl_inode_test, key);
866 	if (!trap)
867 		return false;
868 
869 	res = IS_DEADDIR(trap) && !ovl_inode_upper(trap) &&
870 				  !ovl_inode_lower(trap);
871 
872 	iput(trap);
873 	return res;
874 }
875 
876 /*
877  * Create an inode cache entry for layer root dir, that will intentionally
878  * fail ovl_verify_inode(), so any lookup that will find some layer root
879  * will fail.
880  */
881 struct inode *ovl_get_trap_inode(struct super_block *sb, struct dentry *dir)
882 {
883 	struct inode *key = d_inode(dir);
884 	struct inode *trap;
885 
886 	if (!d_is_dir(dir))
887 		return ERR_PTR(-ENOTDIR);
888 
889 	trap = iget5_locked(sb, (unsigned long) key, ovl_inode_test,
890 			    ovl_inode_set, key);
891 	if (!trap)
892 		return ERR_PTR(-ENOMEM);
893 
894 	if (!(trap->i_state & I_NEW)) {
895 		/* Conflicting layer roots? */
896 		iput(trap);
897 		return ERR_PTR(-ELOOP);
898 	}
899 
900 	trap->i_mode = S_IFDIR;
901 	trap->i_flags = S_DEAD;
902 	unlock_new_inode(trap);
903 
904 	return trap;
905 }
906 
907 /*
908  * Does overlay inode need to be hashed by lower inode?
909  */
910 static bool ovl_hash_bylower(struct super_block *sb, struct dentry *upper,
911 			     struct dentry *lower, struct dentry *index)
912 {
913 	struct ovl_fs *ofs = sb->s_fs_info;
914 
915 	/* No, if pure upper */
916 	if (!lower)
917 		return false;
918 
919 	/* Yes, if already indexed */
920 	if (index)
921 		return true;
922 
923 	/* Yes, if won't be copied up */
924 	if (!ofs->upper_mnt)
925 		return true;
926 
927 	/* No, if lower hardlink is or will be broken on copy up */
928 	if ((upper || !ovl_indexdir(sb)) &&
929 	    !d_is_dir(lower) && d_inode(lower)->i_nlink > 1)
930 		return false;
931 
932 	/* No, if non-indexed upper with NFS export */
933 	if (sb->s_export_op && upper)
934 		return false;
935 
936 	/* Otherwise, hash by lower inode for fsnotify */
937 	return true;
938 }
939 
940 static struct inode *ovl_iget5(struct super_block *sb, struct inode *newinode,
941 			       struct inode *key)
942 {
943 	return newinode ? inode_insert5(newinode, (unsigned long) key,
944 					 ovl_inode_test, ovl_inode_set, key) :
945 			  iget5_locked(sb, (unsigned long) key,
946 				       ovl_inode_test, ovl_inode_set, key);
947 }
948 
949 struct inode *ovl_get_inode(struct super_block *sb,
950 			    struct ovl_inode_params *oip)
951 {
952 	struct dentry *upperdentry = oip->upperdentry;
953 	struct ovl_path *lowerpath = oip->lowerpath;
954 	struct inode *realinode = upperdentry ? d_inode(upperdentry) : NULL;
955 	struct inode *inode;
956 	struct dentry *lowerdentry = lowerpath ? lowerpath->dentry : NULL;
957 	bool bylower = ovl_hash_bylower(sb, upperdentry, lowerdentry,
958 					oip->index);
959 	int fsid = bylower ? lowerpath->layer->fsid : 0;
960 	bool is_dir, metacopy = false;
961 	unsigned long ino = 0;
962 	int err = oip->newinode ? -EEXIST : -ENOMEM;
963 
964 	if (!realinode)
965 		realinode = d_inode(lowerdentry);
966 
967 	/*
968 	 * Copy up origin (lower) may exist for non-indexed upper, but we must
969 	 * not use lower as hash key if this is a broken hardlink.
970 	 */
971 	is_dir = S_ISDIR(realinode->i_mode);
972 	if (upperdentry || bylower) {
973 		struct inode *key = d_inode(bylower ? lowerdentry :
974 						      upperdentry);
975 		unsigned int nlink = is_dir ? 1 : realinode->i_nlink;
976 
977 		inode = ovl_iget5(sb, oip->newinode, key);
978 		if (!inode)
979 			goto out_err;
980 		if (!(inode->i_state & I_NEW)) {
981 			/*
982 			 * Verify that the underlying files stored in the inode
983 			 * match those in the dentry.
984 			 */
985 			if (!ovl_verify_inode(inode, lowerdentry, upperdentry,
986 					      true)) {
987 				iput(inode);
988 				err = -ESTALE;
989 				goto out_err;
990 			}
991 
992 			dput(upperdentry);
993 			kfree(oip->redirect);
994 			goto out;
995 		}
996 
997 		/* Recalculate nlink for non-dir due to indexing */
998 		if (!is_dir)
999 			nlink = ovl_get_nlink(lowerdentry, upperdentry, nlink);
1000 		set_nlink(inode, nlink);
1001 		ino = key->i_ino;
1002 	} else {
1003 		/* Lower hardlink that will be broken on copy up */
1004 		inode = new_inode(sb);
1005 		if (!inode) {
1006 			err = -ENOMEM;
1007 			goto out_err;
1008 		}
1009 		ino = realinode->i_ino;
1010 		fsid = lowerpath->layer->fsid;
1011 	}
1012 	ovl_fill_inode(inode, realinode->i_mode, realinode->i_rdev);
1013 	ovl_inode_init(inode, oip, ino, fsid);
1014 
1015 	if (upperdentry && ovl_is_impuredir(upperdentry))
1016 		ovl_set_flag(OVL_IMPURE, inode);
1017 
1018 	if (oip->index)
1019 		ovl_set_flag(OVL_INDEX, inode);
1020 
1021 	if (upperdentry) {
1022 		err = ovl_check_metacopy_xattr(upperdentry);
1023 		if (err < 0)
1024 			goto out_err;
1025 		metacopy = err;
1026 		if (!metacopy)
1027 			ovl_set_flag(OVL_UPPERDATA, inode);
1028 	}
1029 
1030 	OVL_I(inode)->redirect = oip->redirect;
1031 
1032 	if (bylower)
1033 		ovl_set_flag(OVL_CONST_INO, inode);
1034 
1035 	/* Check for non-merge dir that may have whiteouts */
1036 	if (is_dir) {
1037 		if (((upperdentry && lowerdentry) || oip->numlower > 1) ||
1038 		    ovl_check_origin_xattr(upperdentry ?: lowerdentry)) {
1039 			ovl_set_flag(OVL_WHITEOUTS, inode);
1040 		}
1041 	}
1042 
1043 	if (inode->i_state & I_NEW)
1044 		unlock_new_inode(inode);
1045 out:
1046 	return inode;
1047 
1048 out_err:
1049 	pr_warn_ratelimited("failed to get inode (%i)\n", err);
1050 	inode = ERR_PTR(err);
1051 	goto out;
1052 }
1053