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