xref: /openbmc/linux/fs/overlayfs/util.c (revision 7df45f35313c1ae083dac72c066b3aebfc7fc0cd)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2011 Novell Inc.
4  * Copyright (C) 2016 Red Hat, Inc.
5  */
6 
7 #include <linux/fs.h>
8 #include <linux/mount.h>
9 #include <linux/slab.h>
10 #include <linux/cred.h>
11 #include <linux/xattr.h>
12 #include <linux/exportfs.h>
13 #include <linux/file.h>
14 #include <linux/fileattr.h>
15 #include <linux/uuid.h>
16 #include <linux/namei.h>
17 #include <linux/ratelimit.h>
18 #include "overlayfs.h"
19 
ovl_want_write(struct dentry * dentry)20 int ovl_want_write(struct dentry *dentry)
21 {
22 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
23 	return mnt_want_write(ovl_upper_mnt(ofs));
24 }
25 
ovl_drop_write(struct dentry * dentry)26 void ovl_drop_write(struct dentry *dentry)
27 {
28 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
29 	mnt_drop_write(ovl_upper_mnt(ofs));
30 }
31 
ovl_workdir(struct dentry * dentry)32 struct dentry *ovl_workdir(struct dentry *dentry)
33 {
34 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
35 	return ofs->workdir;
36 }
37 
ovl_override_creds(struct super_block * sb)38 const struct cred *ovl_override_creds(struct super_block *sb)
39 {
40 	struct ovl_fs *ofs = OVL_FS(sb);
41 
42 	return override_creds(ofs->creator_cred);
43 }
44 
45 /*
46  * Check if underlying fs supports file handles and try to determine encoding
47  * type, in order to deduce maximum inode number used by fs.
48  *
49  * Return 0 if file handles are not supported.
50  * Return 1 (FILEID_INO32_GEN) if fs uses the default 32bit inode encoding.
51  * Return -1 if fs uses a non default encoding with unknown inode size.
52  */
ovl_can_decode_fh(struct super_block * sb)53 int ovl_can_decode_fh(struct super_block *sb)
54 {
55 	if (!capable(CAP_DAC_READ_SEARCH))
56 		return 0;
57 
58 	if (!sb->s_export_op || !sb->s_export_op->fh_to_dentry)
59 		return 0;
60 
61 	return sb->s_export_op->encode_fh ? -1 : FILEID_INO32_GEN;
62 }
63 
ovl_indexdir(struct super_block * sb)64 struct dentry *ovl_indexdir(struct super_block *sb)
65 {
66 	struct ovl_fs *ofs = OVL_FS(sb);
67 
68 	return ofs->indexdir;
69 }
70 
71 /* Index all files on copy up. For now only enabled for NFS export */
ovl_index_all(struct super_block * sb)72 bool ovl_index_all(struct super_block *sb)
73 {
74 	struct ovl_fs *ofs = OVL_FS(sb);
75 
76 	return ofs->config.nfs_export && ofs->config.index;
77 }
78 
79 /* Verify lower origin on lookup. For now only enabled for NFS export */
ovl_verify_lower(struct super_block * sb)80 bool ovl_verify_lower(struct super_block *sb)
81 {
82 	struct ovl_fs *ofs = OVL_FS(sb);
83 
84 	return ofs->config.nfs_export && ofs->config.index;
85 }
86 
ovl_stack_alloc(unsigned int n)87 struct ovl_path *ovl_stack_alloc(unsigned int n)
88 {
89 	return kcalloc(n, sizeof(struct ovl_path), GFP_KERNEL);
90 }
91 
ovl_stack_cpy(struct ovl_path * dst,struct ovl_path * src,unsigned int n)92 void ovl_stack_cpy(struct ovl_path *dst, struct ovl_path *src, unsigned int n)
93 {
94 	unsigned int i;
95 
96 	memcpy(dst, src, sizeof(struct ovl_path) * n);
97 	for (i = 0; i < n; i++)
98 		dget(src[i].dentry);
99 }
100 
ovl_stack_put(struct ovl_path * stack,unsigned int n)101 void ovl_stack_put(struct ovl_path *stack, unsigned int n)
102 {
103 	unsigned int i;
104 
105 	for (i = 0; stack && i < n; i++)
106 		dput(stack[i].dentry);
107 }
108 
ovl_stack_free(struct ovl_path * stack,unsigned int n)109 void ovl_stack_free(struct ovl_path *stack, unsigned int n)
110 {
111 	ovl_stack_put(stack, n);
112 	kfree(stack);
113 }
114 
ovl_alloc_entry(unsigned int numlower)115 struct ovl_entry *ovl_alloc_entry(unsigned int numlower)
116 {
117 	size_t size = offsetof(struct ovl_entry, __lowerstack[numlower]);
118 	struct ovl_entry *oe = kzalloc(size, GFP_KERNEL);
119 
120 	if (oe)
121 		oe->__numlower = numlower;
122 
123 	return oe;
124 }
125 
ovl_free_entry(struct ovl_entry * oe)126 void ovl_free_entry(struct ovl_entry *oe)
127 {
128 	ovl_stack_put(ovl_lowerstack(oe), ovl_numlower(oe));
129 	kfree(oe);
130 }
131 
132 #define OVL_D_REVALIDATE (DCACHE_OP_REVALIDATE | DCACHE_OP_WEAK_REVALIDATE)
133 
ovl_dentry_remote(struct dentry * dentry)134 bool ovl_dentry_remote(struct dentry *dentry)
135 {
136 	return dentry->d_flags & OVL_D_REVALIDATE;
137 }
138 
ovl_dentry_update_reval(struct dentry * dentry,struct dentry * realdentry)139 void ovl_dentry_update_reval(struct dentry *dentry, struct dentry *realdentry)
140 {
141 	if (!ovl_dentry_remote(realdentry))
142 		return;
143 
144 	spin_lock(&dentry->d_lock);
145 	dentry->d_flags |= realdentry->d_flags & OVL_D_REVALIDATE;
146 	spin_unlock(&dentry->d_lock);
147 }
148 
ovl_dentry_init_reval(struct dentry * dentry,struct dentry * upperdentry,struct ovl_entry * oe)149 void ovl_dentry_init_reval(struct dentry *dentry, struct dentry *upperdentry,
150 			   struct ovl_entry *oe)
151 {
152 	return ovl_dentry_init_flags(dentry, upperdentry, oe, OVL_D_REVALIDATE);
153 }
154 
ovl_dentry_init_flags(struct dentry * dentry,struct dentry * upperdentry,struct ovl_entry * oe,unsigned int mask)155 void ovl_dentry_init_flags(struct dentry *dentry, struct dentry *upperdentry,
156 			   struct ovl_entry *oe, unsigned int mask)
157 {
158 	struct ovl_path *lowerstack = ovl_lowerstack(oe);
159 	unsigned int i, flags = 0;
160 
161 	if (upperdentry)
162 		flags |= upperdentry->d_flags;
163 	for (i = 0; i < ovl_numlower(oe) && lowerstack[i].dentry; i++)
164 		flags |= lowerstack[i].dentry->d_flags;
165 
166 	spin_lock(&dentry->d_lock);
167 	dentry->d_flags &= ~mask;
168 	dentry->d_flags |= flags & mask;
169 	spin_unlock(&dentry->d_lock);
170 }
171 
ovl_dentry_weird(struct dentry * dentry)172 bool ovl_dentry_weird(struct dentry *dentry)
173 {
174 	if (!d_can_lookup(dentry) && !d_is_file(dentry) && !d_is_symlink(dentry))
175 		return true;
176 
177 	return dentry->d_flags & (DCACHE_NEED_AUTOMOUNT |
178 				  DCACHE_MANAGE_TRANSIT |
179 				  DCACHE_OP_HASH |
180 				  DCACHE_OP_COMPARE);
181 }
182 
ovl_path_type(struct dentry * dentry)183 enum ovl_path_type ovl_path_type(struct dentry *dentry)
184 {
185 	struct ovl_entry *oe = OVL_E(dentry);
186 	enum ovl_path_type type = 0;
187 
188 	if (ovl_dentry_upper(dentry)) {
189 		type = __OVL_PATH_UPPER;
190 
191 		/*
192 		 * Non-dir dentry can hold lower dentry of its copy up origin.
193 		 */
194 		if (ovl_numlower(oe)) {
195 			if (ovl_test_flag(OVL_CONST_INO, d_inode(dentry)))
196 				type |= __OVL_PATH_ORIGIN;
197 			if (d_is_dir(dentry) ||
198 			    !ovl_has_upperdata(d_inode(dentry)))
199 				type |= __OVL_PATH_MERGE;
200 		}
201 	} else {
202 		if (ovl_numlower(oe) > 1)
203 			type |= __OVL_PATH_MERGE;
204 	}
205 	return type;
206 }
207 
ovl_path_upper(struct dentry * dentry,struct path * path)208 void ovl_path_upper(struct dentry *dentry, struct path *path)
209 {
210 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
211 
212 	path->mnt = ovl_upper_mnt(ofs);
213 	path->dentry = ovl_dentry_upper(dentry);
214 }
215 
ovl_path_lower(struct dentry * dentry,struct path * path)216 void ovl_path_lower(struct dentry *dentry, struct path *path)
217 {
218 	struct ovl_entry *oe = OVL_E(dentry);
219 	struct ovl_path *lowerpath = ovl_lowerstack(oe);
220 
221 	if (ovl_numlower(oe)) {
222 		path->mnt = lowerpath->layer->mnt;
223 		path->dentry = lowerpath->dentry;
224 	} else {
225 		*path = (struct path) { };
226 	}
227 }
228 
ovl_path_lowerdata(struct dentry * dentry,struct path * path)229 void ovl_path_lowerdata(struct dentry *dentry, struct path *path)
230 {
231 	struct ovl_entry *oe = OVL_E(dentry);
232 	struct ovl_path *lowerdata = ovl_lowerdata(oe);
233 	struct dentry *lowerdata_dentry = ovl_lowerdata_dentry(oe);
234 
235 	if (lowerdata_dentry) {
236 		path->dentry = lowerdata_dentry;
237 		/*
238 		 * Pairs with smp_wmb() in ovl_dentry_set_lowerdata().
239 		 * Make sure that if lowerdata->dentry is visible, then
240 		 * datapath->layer is visible as well.
241 		 */
242 		smp_rmb();
243 		path->mnt = READ_ONCE(lowerdata->layer)->mnt;
244 	} else {
245 		*path = (struct path) { };
246 	}
247 }
248 
ovl_path_real(struct dentry * dentry,struct path * path)249 enum ovl_path_type ovl_path_real(struct dentry *dentry, struct path *path)
250 {
251 	enum ovl_path_type type = ovl_path_type(dentry);
252 
253 	if (!OVL_TYPE_UPPER(type))
254 		ovl_path_lower(dentry, path);
255 	else
256 		ovl_path_upper(dentry, path);
257 
258 	return type;
259 }
260 
ovl_path_realdata(struct dentry * dentry,struct path * path)261 enum ovl_path_type ovl_path_realdata(struct dentry *dentry, struct path *path)
262 {
263 	enum ovl_path_type type = ovl_path_type(dentry);
264 
265 	WARN_ON_ONCE(d_is_dir(dentry));
266 
267 	if (!OVL_TYPE_UPPER(type) || OVL_TYPE_MERGE(type))
268 		ovl_path_lowerdata(dentry, path);
269 	else
270 		ovl_path_upper(dentry, path);
271 
272 	return type;
273 }
274 
ovl_dentry_upper(struct dentry * dentry)275 struct dentry *ovl_dentry_upper(struct dentry *dentry)
276 {
277 	struct inode *inode = d_inode(dentry);
278 
279 	return inode ? ovl_upperdentry_dereference(OVL_I(inode)) : NULL;
280 }
281 
ovl_dentry_lower(struct dentry * dentry)282 struct dentry *ovl_dentry_lower(struct dentry *dentry)
283 {
284 	struct ovl_entry *oe = OVL_E(dentry);
285 
286 	return ovl_numlower(oe) ? ovl_lowerstack(oe)->dentry : NULL;
287 }
288 
ovl_layer_lower(struct dentry * dentry)289 const struct ovl_layer *ovl_layer_lower(struct dentry *dentry)
290 {
291 	struct ovl_entry *oe = OVL_E(dentry);
292 
293 	return ovl_numlower(oe) ? ovl_lowerstack(oe)->layer : NULL;
294 }
295 
296 /*
297  * ovl_dentry_lower() could return either a data dentry or metacopy dentry
298  * depending on what is stored in lowerstack[0]. At times we need to find
299  * lower dentry which has data (and not metacopy dentry). This helper
300  * returns the lower data dentry.
301  */
ovl_dentry_lowerdata(struct dentry * dentry)302 struct dentry *ovl_dentry_lowerdata(struct dentry *dentry)
303 {
304 	return ovl_lowerdata_dentry(OVL_E(dentry));
305 }
306 
ovl_dentry_set_lowerdata(struct dentry * dentry,struct ovl_path * datapath)307 int ovl_dentry_set_lowerdata(struct dentry *dentry, struct ovl_path *datapath)
308 {
309 	struct ovl_entry *oe = OVL_E(dentry);
310 	struct ovl_path *lowerdata = ovl_lowerdata(oe);
311 	struct dentry *datadentry = datapath->dentry;
312 
313 	if (WARN_ON_ONCE(ovl_numlower(oe) <= 1))
314 		return -EIO;
315 
316 	WRITE_ONCE(lowerdata->layer, datapath->layer);
317 	/*
318 	 * Pairs with smp_rmb() in ovl_path_lowerdata().
319 	 * Make sure that if lowerdata->dentry is visible, then
320 	 * lowerdata->layer is visible as well.
321 	 */
322 	smp_wmb();
323 	WRITE_ONCE(lowerdata->dentry, dget(datadentry));
324 
325 	ovl_dentry_update_reval(dentry, datadentry);
326 
327 	return 0;
328 }
329 
ovl_dentry_real(struct dentry * dentry)330 struct dentry *ovl_dentry_real(struct dentry *dentry)
331 {
332 	return ovl_dentry_upper(dentry) ?: ovl_dentry_lower(dentry);
333 }
334 
ovl_i_dentry_upper(struct inode * inode)335 struct dentry *ovl_i_dentry_upper(struct inode *inode)
336 {
337 	return ovl_upperdentry_dereference(OVL_I(inode));
338 }
339 
ovl_i_path_real(struct inode * inode,struct path * path)340 struct inode *ovl_i_path_real(struct inode *inode, struct path *path)
341 {
342 	struct ovl_path *lowerpath = ovl_lowerpath(OVL_I_E(inode));
343 
344 	path->dentry = ovl_i_dentry_upper(inode);
345 	if (!path->dentry) {
346 		path->dentry = lowerpath->dentry;
347 		path->mnt = lowerpath->layer->mnt;
348 	} else {
349 		path->mnt = ovl_upper_mnt(OVL_FS(inode->i_sb));
350 	}
351 
352 	return path->dentry ? d_inode_rcu(path->dentry) : NULL;
353 }
354 
ovl_inode_upper(struct inode * inode)355 struct inode *ovl_inode_upper(struct inode *inode)
356 {
357 	struct dentry *upperdentry = ovl_i_dentry_upper(inode);
358 
359 	return upperdentry ? d_inode(upperdentry) : NULL;
360 }
361 
ovl_inode_lower(struct inode * inode)362 struct inode *ovl_inode_lower(struct inode *inode)
363 {
364 	struct ovl_path *lowerpath = ovl_lowerpath(OVL_I_E(inode));
365 
366 	return lowerpath ? d_inode(lowerpath->dentry) : NULL;
367 }
368 
ovl_inode_real(struct inode * inode)369 struct inode *ovl_inode_real(struct inode *inode)
370 {
371 	return ovl_inode_upper(inode) ?: ovl_inode_lower(inode);
372 }
373 
374 /* Return inode which contains lower data. Do not return metacopy */
ovl_inode_lowerdata(struct inode * inode)375 struct inode *ovl_inode_lowerdata(struct inode *inode)
376 {
377 	struct dentry *lowerdata = ovl_lowerdata_dentry(OVL_I_E(inode));
378 
379 	if (WARN_ON(!S_ISREG(inode->i_mode)))
380 		return NULL;
381 
382 	return lowerdata ? d_inode(lowerdata) : NULL;
383 }
384 
385 /* Return real inode which contains data. Does not return metacopy inode */
ovl_inode_realdata(struct inode * inode)386 struct inode *ovl_inode_realdata(struct inode *inode)
387 {
388 	struct inode *upperinode;
389 
390 	upperinode = ovl_inode_upper(inode);
391 	if (upperinode && ovl_has_upperdata(inode))
392 		return upperinode;
393 
394 	return ovl_inode_lowerdata(inode);
395 }
396 
ovl_lowerdata_redirect(struct inode * inode)397 const char *ovl_lowerdata_redirect(struct inode *inode)
398 {
399 	return inode && S_ISREG(inode->i_mode) ?
400 		OVL_I(inode)->lowerdata_redirect : NULL;
401 }
402 
ovl_dir_cache(struct inode * inode)403 struct ovl_dir_cache *ovl_dir_cache(struct inode *inode)
404 {
405 	return inode && S_ISDIR(inode->i_mode) ? OVL_I(inode)->cache : NULL;
406 }
407 
ovl_set_dir_cache(struct inode * inode,struct ovl_dir_cache * cache)408 void ovl_set_dir_cache(struct inode *inode, struct ovl_dir_cache *cache)
409 {
410 	OVL_I(inode)->cache = cache;
411 }
412 
ovl_dentry_set_flag(unsigned long flag,struct dentry * dentry)413 void ovl_dentry_set_flag(unsigned long flag, struct dentry *dentry)
414 {
415 	set_bit(flag, OVL_E_FLAGS(dentry));
416 }
417 
ovl_dentry_clear_flag(unsigned long flag,struct dentry * dentry)418 void ovl_dentry_clear_flag(unsigned long flag, struct dentry *dentry)
419 {
420 	clear_bit(flag, OVL_E_FLAGS(dentry));
421 }
422 
ovl_dentry_test_flag(unsigned long flag,struct dentry * dentry)423 bool ovl_dentry_test_flag(unsigned long flag, struct dentry *dentry)
424 {
425 	return test_bit(flag, OVL_E_FLAGS(dentry));
426 }
427 
ovl_dentry_is_opaque(struct dentry * dentry)428 bool ovl_dentry_is_opaque(struct dentry *dentry)
429 {
430 	return ovl_dentry_test_flag(OVL_E_OPAQUE, dentry);
431 }
432 
ovl_dentry_is_whiteout(struct dentry * dentry)433 bool ovl_dentry_is_whiteout(struct dentry *dentry)
434 {
435 	return !dentry->d_inode && ovl_dentry_is_opaque(dentry);
436 }
437 
ovl_dentry_set_opaque(struct dentry * dentry)438 void ovl_dentry_set_opaque(struct dentry *dentry)
439 {
440 	ovl_dentry_set_flag(OVL_E_OPAQUE, dentry);
441 }
442 
443 /*
444  * For hard links and decoded file handles, it's possible for ovl_dentry_upper()
445  * to return positive, while there's no actual upper alias for the inode.
446  * Copy up code needs to know about the existence of the upper alias, so it
447  * can't use ovl_dentry_upper().
448  */
ovl_dentry_has_upper_alias(struct dentry * dentry)449 bool ovl_dentry_has_upper_alias(struct dentry *dentry)
450 {
451 	return ovl_dentry_test_flag(OVL_E_UPPER_ALIAS, dentry);
452 }
453 
ovl_dentry_set_upper_alias(struct dentry * dentry)454 void ovl_dentry_set_upper_alias(struct dentry *dentry)
455 {
456 	ovl_dentry_set_flag(OVL_E_UPPER_ALIAS, dentry);
457 }
458 
ovl_should_check_upperdata(struct inode * inode)459 static bool ovl_should_check_upperdata(struct inode *inode)
460 {
461 	if (!S_ISREG(inode->i_mode))
462 		return false;
463 
464 	if (!ovl_inode_lower(inode))
465 		return false;
466 
467 	return true;
468 }
469 
ovl_has_upperdata(struct inode * inode)470 bool ovl_has_upperdata(struct inode *inode)
471 {
472 	if (!ovl_should_check_upperdata(inode))
473 		return true;
474 
475 	if (!ovl_test_flag(OVL_UPPERDATA, inode))
476 		return false;
477 	/*
478 	 * Pairs with smp_wmb() in ovl_set_upperdata(). Main user of
479 	 * ovl_has_upperdata() is ovl_copy_up_meta_inode_data(). Make sure
480 	 * if setting of OVL_UPPERDATA is visible, then effects of writes
481 	 * before that are visible too.
482 	 */
483 	smp_rmb();
484 	return true;
485 }
486 
ovl_set_upperdata(struct inode * inode)487 void ovl_set_upperdata(struct inode *inode)
488 {
489 	/*
490 	 * Pairs with smp_rmb() in ovl_has_upperdata(). Make sure
491 	 * if OVL_UPPERDATA flag is visible, then effects of write operations
492 	 * before it are visible as well.
493 	 */
494 	smp_wmb();
495 	ovl_set_flag(OVL_UPPERDATA, inode);
496 }
497 
498 /* Caller should hold ovl_inode->lock */
ovl_dentry_needs_data_copy_up_locked(struct dentry * dentry,int flags)499 bool ovl_dentry_needs_data_copy_up_locked(struct dentry *dentry, int flags)
500 {
501 	if (!ovl_open_flags_need_copy_up(flags))
502 		return false;
503 
504 	return !ovl_test_flag(OVL_UPPERDATA, d_inode(dentry));
505 }
506 
ovl_dentry_needs_data_copy_up(struct dentry * dentry,int flags)507 bool ovl_dentry_needs_data_copy_up(struct dentry *dentry, int flags)
508 {
509 	if (!ovl_open_flags_need_copy_up(flags))
510 		return false;
511 
512 	return !ovl_has_upperdata(d_inode(dentry));
513 }
514 
ovl_dentry_get_redirect(struct dentry * dentry)515 const char *ovl_dentry_get_redirect(struct dentry *dentry)
516 {
517 	return OVL_I(d_inode(dentry))->redirect;
518 }
519 
ovl_dentry_set_redirect(struct dentry * dentry,const char * redirect)520 void ovl_dentry_set_redirect(struct dentry *dentry, const char *redirect)
521 {
522 	struct ovl_inode *oi = OVL_I(d_inode(dentry));
523 
524 	kfree(oi->redirect);
525 	oi->redirect = redirect;
526 }
527 
ovl_inode_update(struct inode * inode,struct dentry * upperdentry)528 void ovl_inode_update(struct inode *inode, struct dentry *upperdentry)
529 {
530 	struct inode *upperinode = d_inode(upperdentry);
531 
532 	WARN_ON(OVL_I(inode)->__upperdentry);
533 
534 	/*
535 	 * Make sure upperdentry is consistent before making it visible
536 	 */
537 	smp_wmb();
538 	OVL_I(inode)->__upperdentry = upperdentry;
539 	if (inode_unhashed(inode)) {
540 		inode->i_private = upperinode;
541 		__insert_inode_hash(inode, (unsigned long) upperinode);
542 	}
543 }
544 
ovl_dir_version_inc(struct dentry * dentry,bool impurity)545 static void ovl_dir_version_inc(struct dentry *dentry, bool impurity)
546 {
547 	struct inode *inode = d_inode(dentry);
548 
549 	WARN_ON(!inode_is_locked(inode));
550 	WARN_ON(!d_is_dir(dentry));
551 	/*
552 	 * Version is used by readdir code to keep cache consistent.
553 	 * For merge dirs (or dirs with origin) all changes need to be noted.
554 	 * For non-merge dirs, cache contains only impure entries (i.e. ones
555 	 * which have been copied up and have origins), so only need to note
556 	 * changes to impure entries.
557 	 */
558 	if (!ovl_dir_is_real(inode) || impurity)
559 		OVL_I(inode)->version++;
560 }
561 
ovl_dir_modified(struct dentry * dentry,bool impurity)562 void ovl_dir_modified(struct dentry *dentry, bool impurity)
563 {
564 	/* Copy mtime/ctime */
565 	ovl_copyattr(d_inode(dentry));
566 
567 	ovl_dir_version_inc(dentry, impurity);
568 }
569 
ovl_inode_version_get(struct inode * inode)570 u64 ovl_inode_version_get(struct inode *inode)
571 {
572 	WARN_ON(!inode_is_locked(inode));
573 	return OVL_I(inode)->version;
574 }
575 
ovl_is_whiteout(struct dentry * dentry)576 bool ovl_is_whiteout(struct dentry *dentry)
577 {
578 	struct inode *inode = dentry->d_inode;
579 
580 	return inode && IS_WHITEOUT(inode);
581 }
582 
ovl_path_open(const struct path * path,int flags)583 struct file *ovl_path_open(const struct path *path, int flags)
584 {
585 	struct inode *inode = d_inode(path->dentry);
586 	struct mnt_idmap *real_idmap = mnt_idmap(path->mnt);
587 	int err, acc_mode;
588 
589 	if (flags & ~(O_ACCMODE | O_LARGEFILE))
590 		BUG();
591 
592 	switch (flags & O_ACCMODE) {
593 	case O_RDONLY:
594 		acc_mode = MAY_READ;
595 		break;
596 	case O_WRONLY:
597 		acc_mode = MAY_WRITE;
598 		break;
599 	default:
600 		BUG();
601 	}
602 
603 	err = inode_permission(real_idmap, inode, acc_mode | MAY_OPEN);
604 	if (err)
605 		return ERR_PTR(err);
606 
607 	/* O_NOATIME is an optimization, don't fail if not permitted */
608 	if (inode_owner_or_capable(real_idmap, inode))
609 		flags |= O_NOATIME;
610 
611 	return dentry_open(path, flags, current_cred());
612 }
613 
614 /* Caller should hold ovl_inode->lock */
ovl_already_copied_up_locked(struct dentry * dentry,int flags)615 static bool ovl_already_copied_up_locked(struct dentry *dentry, int flags)
616 {
617 	bool disconnected = dentry->d_flags & DCACHE_DISCONNECTED;
618 
619 	if (ovl_dentry_upper(dentry) &&
620 	    (ovl_dentry_has_upper_alias(dentry) || disconnected) &&
621 	    !ovl_dentry_needs_data_copy_up_locked(dentry, flags))
622 		return true;
623 
624 	return false;
625 }
626 
ovl_already_copied_up(struct dentry * dentry,int flags)627 bool ovl_already_copied_up(struct dentry *dentry, int flags)
628 {
629 	bool disconnected = dentry->d_flags & DCACHE_DISCONNECTED;
630 
631 	/*
632 	 * Check if copy-up has happened as well as for upper alias (in
633 	 * case of hard links) is there.
634 	 *
635 	 * Both checks are lockless:
636 	 *  - false negatives: will recheck under oi->lock
637 	 *  - false positives:
638 	 *    + ovl_dentry_upper() uses memory barriers to ensure the
639 	 *      upper dentry is up-to-date
640 	 *    + ovl_dentry_has_upper_alias() relies on locking of
641 	 *      upper parent i_rwsem to prevent reordering copy-up
642 	 *      with rename.
643 	 */
644 	if (ovl_dentry_upper(dentry) &&
645 	    (ovl_dentry_has_upper_alias(dentry) || disconnected) &&
646 	    !ovl_dentry_needs_data_copy_up(dentry, flags))
647 		return true;
648 
649 	return false;
650 }
651 
ovl_copy_up_start(struct dentry * dentry,int flags)652 int ovl_copy_up_start(struct dentry *dentry, int flags)
653 {
654 	struct inode *inode = d_inode(dentry);
655 	int err;
656 
657 	err = ovl_inode_lock_interruptible(inode);
658 	if (!err && ovl_already_copied_up_locked(dentry, flags)) {
659 		err = 1; /* Already copied up */
660 		ovl_inode_unlock(inode);
661 	}
662 
663 	return err;
664 }
665 
ovl_copy_up_end(struct dentry * dentry)666 void ovl_copy_up_end(struct dentry *dentry)
667 {
668 	ovl_inode_unlock(d_inode(dentry));
669 }
670 
ovl_path_check_origin_xattr(struct ovl_fs * ofs,const struct path * path)671 bool ovl_path_check_origin_xattr(struct ovl_fs *ofs, const struct path *path)
672 {
673 	int res;
674 
675 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_ORIGIN, NULL, 0);
676 
677 	/* Zero size value means "copied up but origin unknown" */
678 	if (res >= 0)
679 		return true;
680 
681 	return false;
682 }
683 
684 /*
685  * Load persistent uuid from xattr into s_uuid if found, or store a new
686  * random generated value in s_uuid and in xattr.
687  */
ovl_init_uuid_xattr(struct super_block * sb,struct ovl_fs * ofs,const struct path * upperpath)688 bool ovl_init_uuid_xattr(struct super_block *sb, struct ovl_fs *ofs,
689 			 const struct path *upperpath)
690 {
691 	bool set = false;
692 	int res;
693 
694 	/* Try to load existing persistent uuid */
695 	res = ovl_path_getxattr(ofs, upperpath, OVL_XATTR_UUID, sb->s_uuid.b,
696 				UUID_SIZE);
697 	if (res == UUID_SIZE)
698 		return true;
699 
700 	if (res != -ENODATA)
701 		goto fail;
702 
703 	/*
704 	 * With uuid=auto, if uuid xattr is found, it will be used.
705 	 * If uuid xattrs is not found, generate a persistent uuid only on mount
706 	 * of new overlays where upper root dir is not yet marked as impure.
707 	 * An upper dir is marked as impure on copy up or lookup of its subdirs.
708 	 */
709 	if (ofs->config.uuid == OVL_UUID_AUTO) {
710 		res = ovl_path_getxattr(ofs, upperpath, OVL_XATTR_IMPURE, NULL,
711 					0);
712 		if (res > 0) {
713 			/* Any mount of old overlay - downgrade to uuid=null */
714 			ofs->config.uuid = OVL_UUID_NULL;
715 			return true;
716 		} else if (res == -ENODATA) {
717 			/* First mount of new overlay - upgrade to uuid=on */
718 			ofs->config.uuid = OVL_UUID_ON;
719 		} else if (res < 0) {
720 			goto fail;
721 		}
722 
723 	}
724 
725 	/* Generate overlay instance uuid */
726 	uuid_gen(&sb->s_uuid);
727 
728 	/* Try to store persistent uuid */
729 	set = true;
730 	res = ovl_setxattr(ofs, upperpath->dentry, OVL_XATTR_UUID, sb->s_uuid.b,
731 			   UUID_SIZE);
732 	if (res == 0)
733 		return true;
734 
735 fail:
736 	memset(sb->s_uuid.b, 0, UUID_SIZE);
737 	ofs->config.uuid = OVL_UUID_NULL;
738 	pr_warn("failed to %s uuid (%pd2, err=%i); falling back to uuid=null.\n",
739 		set ? "set" : "get", upperpath->dentry, res);
740 	return false;
741 }
742 
ovl_path_check_dir_xattr(struct ovl_fs * ofs,const struct path * path,enum ovl_xattr ox)743 bool ovl_path_check_dir_xattr(struct ovl_fs *ofs, const struct path *path,
744 			       enum ovl_xattr ox)
745 {
746 	int res;
747 	char val;
748 
749 	if (!d_is_dir(path->dentry))
750 		return false;
751 
752 	res = ovl_path_getxattr(ofs, path, ox, &val, 1);
753 	if (res == 1 && val == 'y')
754 		return true;
755 
756 	return false;
757 }
758 
759 #define OVL_XATTR_OPAQUE_POSTFIX	"opaque"
760 #define OVL_XATTR_REDIRECT_POSTFIX	"redirect"
761 #define OVL_XATTR_ORIGIN_POSTFIX	"origin"
762 #define OVL_XATTR_IMPURE_POSTFIX	"impure"
763 #define OVL_XATTR_NLINK_POSTFIX		"nlink"
764 #define OVL_XATTR_UPPER_POSTFIX		"upper"
765 #define OVL_XATTR_UUID_POSTFIX		"uuid"
766 #define OVL_XATTR_METACOPY_POSTFIX	"metacopy"
767 #define OVL_XATTR_PROTATTR_POSTFIX	"protattr"
768 
769 #define OVL_XATTR_TAB_ENTRY(x) \
770 	[x] = { [false] = OVL_XATTR_TRUSTED_PREFIX x ## _POSTFIX, \
771 		[true] = OVL_XATTR_USER_PREFIX x ## _POSTFIX }
772 
773 const char *const ovl_xattr_table[][2] = {
774 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_OPAQUE),
775 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_REDIRECT),
776 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_ORIGIN),
777 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_IMPURE),
778 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_NLINK),
779 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_UPPER),
780 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_UUID),
781 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_METACOPY),
782 	OVL_XATTR_TAB_ENTRY(OVL_XATTR_PROTATTR),
783 };
784 
ovl_check_setxattr(struct ovl_fs * ofs,struct dentry * upperdentry,enum ovl_xattr ox,const void * value,size_t size,int xerr)785 int ovl_check_setxattr(struct ovl_fs *ofs, struct dentry *upperdentry,
786 		       enum ovl_xattr ox, const void *value, size_t size,
787 		       int xerr)
788 {
789 	int err;
790 
791 	if (ofs->noxattr)
792 		return xerr;
793 
794 	err = ovl_setxattr(ofs, upperdentry, ox, value, size);
795 
796 	if (err == -EOPNOTSUPP) {
797 		pr_warn("cannot set %s xattr on upper\n", ovl_xattr(ofs, ox));
798 		ofs->noxattr = true;
799 		return xerr;
800 	}
801 
802 	return err;
803 }
804 
ovl_set_impure(struct dentry * dentry,struct dentry * upperdentry)805 int ovl_set_impure(struct dentry *dentry, struct dentry *upperdentry)
806 {
807 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
808 	int err;
809 
810 	if (ovl_test_flag(OVL_IMPURE, d_inode(dentry)))
811 		return 0;
812 
813 	/*
814 	 * Do not fail when upper doesn't support xattrs.
815 	 * Upper inodes won't have origin nor redirect xattr anyway.
816 	 */
817 	err = ovl_check_setxattr(ofs, upperdentry, OVL_XATTR_IMPURE, "y", 1, 0);
818 	if (!err)
819 		ovl_set_flag(OVL_IMPURE, d_inode(dentry));
820 
821 	return err;
822 }
823 
824 
825 #define OVL_PROTATTR_MAX 32 /* Reserved for future flags */
826 
ovl_check_protattr(struct inode * inode,struct dentry * upper)827 void ovl_check_protattr(struct inode *inode, struct dentry *upper)
828 {
829 	struct ovl_fs *ofs = OVL_FS(inode->i_sb);
830 	u32 iflags = inode->i_flags & OVL_PROT_I_FLAGS_MASK;
831 	char buf[OVL_PROTATTR_MAX+1];
832 	int res, n;
833 
834 	res = ovl_getxattr_upper(ofs, upper, OVL_XATTR_PROTATTR, buf,
835 				 OVL_PROTATTR_MAX);
836 	if (res < 0)
837 		return;
838 
839 	/*
840 	 * Initialize inode flags from overlay.protattr xattr and upper inode
841 	 * flags.  If upper inode has those fileattr flags set (i.e. from old
842 	 * kernel), we do not clear them on ovl_get_inode(), but we will clear
843 	 * them on next fileattr_set().
844 	 */
845 	for (n = 0; n < res; n++) {
846 		if (buf[n] == 'a')
847 			iflags |= S_APPEND;
848 		else if (buf[n] == 'i')
849 			iflags |= S_IMMUTABLE;
850 		else
851 			break;
852 	}
853 
854 	if (!res || n < res) {
855 		pr_warn_ratelimited("incompatible overlay.protattr format (%pd2, len=%d)\n",
856 				    upper, res);
857 	} else {
858 		inode_set_flags(inode, iflags, OVL_PROT_I_FLAGS_MASK);
859 	}
860 }
861 
ovl_set_protattr(struct inode * inode,struct dentry * upper,struct fileattr * fa)862 int ovl_set_protattr(struct inode *inode, struct dentry *upper,
863 		      struct fileattr *fa)
864 {
865 	struct ovl_fs *ofs = OVL_FS(inode->i_sb);
866 	char buf[OVL_PROTATTR_MAX];
867 	int len = 0, err = 0;
868 	u32 iflags = 0;
869 
870 	BUILD_BUG_ON(HWEIGHT32(OVL_PROT_FS_FLAGS_MASK) > OVL_PROTATTR_MAX);
871 
872 	if (fa->flags & FS_APPEND_FL) {
873 		buf[len++] = 'a';
874 		iflags |= S_APPEND;
875 	}
876 	if (fa->flags & FS_IMMUTABLE_FL) {
877 		buf[len++] = 'i';
878 		iflags |= S_IMMUTABLE;
879 	}
880 
881 	/*
882 	 * Do not allow to set protection flags when upper doesn't support
883 	 * xattrs, because we do not set those fileattr flags on upper inode.
884 	 * Remove xattr if it exist and all protection flags are cleared.
885 	 */
886 	if (len) {
887 		err = ovl_check_setxattr(ofs, upper, OVL_XATTR_PROTATTR,
888 					 buf, len, -EPERM);
889 	} else if (inode->i_flags & OVL_PROT_I_FLAGS_MASK) {
890 		err = ovl_removexattr(ofs, upper, OVL_XATTR_PROTATTR);
891 		if (err == -EOPNOTSUPP || err == -ENODATA)
892 			err = 0;
893 	}
894 	if (err)
895 		return err;
896 
897 	inode_set_flags(inode, iflags, OVL_PROT_I_FLAGS_MASK);
898 
899 	/* Mask out the fileattr flags that should not be set in upper inode */
900 	fa->flags &= ~OVL_PROT_FS_FLAGS_MASK;
901 	fa->fsx_xflags &= ~OVL_PROT_FSX_FLAGS_MASK;
902 
903 	return 0;
904 }
905 
906 /**
907  * Caller must hold a reference to inode to prevent it from being freed while
908  * it is marked inuse.
909  */
ovl_inuse_trylock(struct dentry * dentry)910 bool ovl_inuse_trylock(struct dentry *dentry)
911 {
912 	struct inode *inode = d_inode(dentry);
913 	bool locked = false;
914 
915 	spin_lock(&inode->i_lock);
916 	if (!(inode->i_state & I_OVL_INUSE)) {
917 		inode->i_state |= I_OVL_INUSE;
918 		locked = true;
919 	}
920 	spin_unlock(&inode->i_lock);
921 
922 	return locked;
923 }
924 
ovl_inuse_unlock(struct dentry * dentry)925 void ovl_inuse_unlock(struct dentry *dentry)
926 {
927 	if (dentry) {
928 		struct inode *inode = d_inode(dentry);
929 
930 		spin_lock(&inode->i_lock);
931 		WARN_ON(!(inode->i_state & I_OVL_INUSE));
932 		inode->i_state &= ~I_OVL_INUSE;
933 		spin_unlock(&inode->i_lock);
934 	}
935 }
936 
ovl_is_inuse(struct dentry * dentry)937 bool ovl_is_inuse(struct dentry *dentry)
938 {
939 	struct inode *inode = d_inode(dentry);
940 	bool inuse;
941 
942 	spin_lock(&inode->i_lock);
943 	inuse = (inode->i_state & I_OVL_INUSE);
944 	spin_unlock(&inode->i_lock);
945 
946 	return inuse;
947 }
948 
949 /*
950  * Does this overlay dentry need to be indexed on copy up?
951  */
ovl_need_index(struct dentry * dentry)952 bool ovl_need_index(struct dentry *dentry)
953 {
954 	struct dentry *lower = ovl_dentry_lower(dentry);
955 
956 	if (!lower || !ovl_indexdir(dentry->d_sb))
957 		return false;
958 
959 	/* Index all files for NFS export and consistency verification */
960 	if (ovl_index_all(dentry->d_sb))
961 		return true;
962 
963 	/* Index only lower hardlinks on copy up */
964 	if (!d_is_dir(lower) && d_inode(lower)->i_nlink > 1)
965 		return true;
966 
967 	return false;
968 }
969 
970 /* Caller must hold OVL_I(inode)->lock */
ovl_cleanup_index(struct dentry * dentry)971 static void ovl_cleanup_index(struct dentry *dentry)
972 {
973 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
974 	struct dentry *indexdir = ovl_indexdir(dentry->d_sb);
975 	struct inode *dir = indexdir->d_inode;
976 	struct dentry *lowerdentry = ovl_dentry_lower(dentry);
977 	struct dentry *upperdentry = ovl_dentry_upper(dentry);
978 	struct dentry *index = NULL;
979 	struct inode *inode;
980 	struct qstr name = { };
981 	int err;
982 
983 	err = ovl_get_index_name(ofs, lowerdentry, &name);
984 	if (err)
985 		goto fail;
986 
987 	inode = d_inode(upperdentry);
988 	if (!S_ISDIR(inode->i_mode) && inode->i_nlink != 1) {
989 		pr_warn_ratelimited("cleanup linked index (%pd2, ino=%lu, nlink=%u)\n",
990 				    upperdentry, inode->i_ino, inode->i_nlink);
991 		/*
992 		 * We either have a bug with persistent union nlink or a lower
993 		 * hardlink was added while overlay is mounted. Adding a lower
994 		 * hardlink and then unlinking all overlay hardlinks would drop
995 		 * overlay nlink to zero before all upper inodes are unlinked.
996 		 * As a safety measure, when that situation is detected, set
997 		 * the overlay nlink to the index inode nlink minus one for the
998 		 * index entry itself.
999 		 */
1000 		set_nlink(d_inode(dentry), inode->i_nlink - 1);
1001 		ovl_set_nlink_upper(dentry);
1002 		goto out;
1003 	}
1004 
1005 	inode_lock_nested(dir, I_MUTEX_PARENT);
1006 	index = ovl_lookup_upper(ofs, name.name, indexdir, name.len);
1007 	err = PTR_ERR(index);
1008 	if (IS_ERR(index)) {
1009 		index = NULL;
1010 	} else if (ovl_index_all(dentry->d_sb)) {
1011 		/* Whiteout orphan index to block future open by handle */
1012 		err = ovl_cleanup_and_whiteout(OVL_FS(dentry->d_sb),
1013 					       dir, index);
1014 	} else {
1015 		/* Cleanup orphan index entries */
1016 		err = ovl_cleanup(ofs, dir, index);
1017 	}
1018 
1019 	inode_unlock(dir);
1020 	if (err)
1021 		goto fail;
1022 
1023 out:
1024 	kfree(name.name);
1025 	dput(index);
1026 	return;
1027 
1028 fail:
1029 	pr_err("cleanup index of '%pd2' failed (%i)\n", dentry, err);
1030 	goto out;
1031 }
1032 
1033 /*
1034  * Operations that change overlay inode and upper inode nlink need to be
1035  * synchronized with copy up for persistent nlink accounting.
1036  */
ovl_nlink_start(struct dentry * dentry)1037 int ovl_nlink_start(struct dentry *dentry)
1038 {
1039 	struct inode *inode = d_inode(dentry);
1040 	const struct cred *old_cred;
1041 	int err;
1042 
1043 	if (WARN_ON(!inode))
1044 		return -ENOENT;
1045 
1046 	/*
1047 	 * With inodes index is enabled, we store the union overlay nlink
1048 	 * in an xattr on the index inode. When whiting out an indexed lower,
1049 	 * we need to decrement the overlay persistent nlink, but before the
1050 	 * first copy up, we have no upper index inode to store the xattr.
1051 	 *
1052 	 * As a workaround, before whiteout/rename over an indexed lower,
1053 	 * copy up to create the upper index. Creating the upper index will
1054 	 * initialize the overlay nlink, so it could be dropped if unlink
1055 	 * or rename succeeds.
1056 	 *
1057 	 * TODO: implement metadata only index copy up when called with
1058 	 *       ovl_copy_up_flags(dentry, O_PATH).
1059 	 */
1060 	if (ovl_need_index(dentry) && !ovl_dentry_has_upper_alias(dentry)) {
1061 		err = ovl_copy_up(dentry);
1062 		if (err)
1063 			return err;
1064 	}
1065 
1066 	err = ovl_inode_lock_interruptible(inode);
1067 	if (err)
1068 		return err;
1069 
1070 	if (d_is_dir(dentry) || !ovl_test_flag(OVL_INDEX, inode))
1071 		goto out;
1072 
1073 	old_cred = ovl_override_creds(dentry->d_sb);
1074 	/*
1075 	 * The overlay inode nlink should be incremented/decremented IFF the
1076 	 * upper operation succeeds, along with nlink change of upper inode.
1077 	 * Therefore, before link/unlink/rename, we store the union nlink
1078 	 * value relative to the upper inode nlink in an upper inode xattr.
1079 	 */
1080 	err = ovl_set_nlink_upper(dentry);
1081 	revert_creds(old_cred);
1082 
1083 out:
1084 	if (err)
1085 		ovl_inode_unlock(inode);
1086 
1087 	return err;
1088 }
1089 
ovl_nlink_end(struct dentry * dentry)1090 void ovl_nlink_end(struct dentry *dentry)
1091 {
1092 	struct inode *inode = d_inode(dentry);
1093 
1094 	if (ovl_test_flag(OVL_INDEX, inode) && inode->i_nlink == 0) {
1095 		const struct cred *old_cred;
1096 
1097 		old_cred = ovl_override_creds(dentry->d_sb);
1098 		ovl_cleanup_index(dentry);
1099 		revert_creds(old_cred);
1100 	}
1101 
1102 	ovl_inode_unlock(inode);
1103 }
1104 
ovl_lock_rename_workdir(struct dentry * workdir,struct dentry * upperdir)1105 int ovl_lock_rename_workdir(struct dentry *workdir, struct dentry *upperdir)
1106 {
1107 	/* Workdir should not be the same as upperdir */
1108 	if (workdir == upperdir)
1109 		goto err;
1110 
1111 	/* Workdir should not be subdir of upperdir and vice versa */
1112 	if (lock_rename(workdir, upperdir) != NULL)
1113 		goto err_unlock;
1114 
1115 	return 0;
1116 
1117 err_unlock:
1118 	unlock_rename(workdir, upperdir);
1119 err:
1120 	pr_err("failed to lock workdir+upperdir\n");
1121 	return -EIO;
1122 }
1123 
1124 /*
1125  * err < 0, 0 if no metacopy xattr, metacopy data size if xattr found.
1126  * an empty xattr returns OVL_METACOPY_MIN_SIZE to distinguish from no xattr value.
1127  */
ovl_check_metacopy_xattr(struct ovl_fs * ofs,const struct path * path,struct ovl_metacopy * data)1128 int ovl_check_metacopy_xattr(struct ovl_fs *ofs, const struct path *path,
1129 			     struct ovl_metacopy *data)
1130 {
1131 	int res;
1132 
1133 	/* Only regular files can have metacopy xattr */
1134 	if (!S_ISREG(d_inode(path->dentry)->i_mode))
1135 		return 0;
1136 
1137 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_METACOPY,
1138 				data, data ? OVL_METACOPY_MAX_SIZE : 0);
1139 	if (res < 0) {
1140 		if (res == -ENODATA || res == -EOPNOTSUPP)
1141 			return 0;
1142 		/*
1143 		 * getxattr on user.* may fail with EACCES in case there's no
1144 		 * read permission on the inode.  Not much we can do, other than
1145 		 * tell the caller that this is not a metacopy inode.
1146 		 */
1147 		if (ofs->config.userxattr && res == -EACCES)
1148 			return 0;
1149 		goto out;
1150 	}
1151 
1152 	if (res == 0) {
1153 		/* Emulate empty data for zero size metacopy xattr */
1154 		res = OVL_METACOPY_MIN_SIZE;
1155 		if (data) {
1156 			memset(data, 0, res);
1157 			data->len = res;
1158 		}
1159 	} else if (res < OVL_METACOPY_MIN_SIZE) {
1160 		pr_warn_ratelimited("metacopy file '%pd' has too small xattr\n",
1161 				    path->dentry);
1162 		return -EIO;
1163 	} else if (data) {
1164 		if (data->version != 0) {
1165 			pr_warn_ratelimited("metacopy file '%pd' has unsupported version\n",
1166 					    path->dentry);
1167 			return -EIO;
1168 		}
1169 		if (res != data->len) {
1170 			pr_warn_ratelimited("metacopy file '%pd' has invalid xattr size\n",
1171 					    path->dentry);
1172 			return -EIO;
1173 		}
1174 	}
1175 
1176 	return res;
1177 out:
1178 	pr_warn_ratelimited("failed to get metacopy (%i)\n", res);
1179 	return res;
1180 }
1181 
ovl_set_metacopy_xattr(struct ovl_fs * ofs,struct dentry * d,struct ovl_metacopy * metacopy)1182 int ovl_set_metacopy_xattr(struct ovl_fs *ofs, struct dentry *d, struct ovl_metacopy *metacopy)
1183 {
1184 	size_t len = metacopy->len;
1185 
1186 	/* If no flags or digest fall back to empty metacopy file */
1187 	if (metacopy->version == 0 && metacopy->flags == 0 && metacopy->digest_algo == 0)
1188 		len = 0;
1189 
1190 	return ovl_check_setxattr(ofs, d, OVL_XATTR_METACOPY,
1191 				  metacopy, len, -EOPNOTSUPP);
1192 }
1193 
ovl_is_metacopy_dentry(struct dentry * dentry)1194 bool ovl_is_metacopy_dentry(struct dentry *dentry)
1195 {
1196 	struct ovl_entry *oe = OVL_E(dentry);
1197 
1198 	if (!d_is_reg(dentry))
1199 		return false;
1200 
1201 	if (ovl_dentry_upper(dentry)) {
1202 		if (!ovl_has_upperdata(d_inode(dentry)))
1203 			return true;
1204 		return false;
1205 	}
1206 
1207 	return (ovl_numlower(oe) > 1);
1208 }
1209 
ovl_get_redirect_xattr(struct ovl_fs * ofs,const struct path * path,int padding)1210 char *ovl_get_redirect_xattr(struct ovl_fs *ofs, const struct path *path, int padding)
1211 {
1212 	int res;
1213 	char *s, *next, *buf = NULL;
1214 
1215 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_REDIRECT, NULL, 0);
1216 	if (res == -ENODATA || res == -EOPNOTSUPP)
1217 		return NULL;
1218 	if (res < 0)
1219 		goto fail;
1220 	if (res == 0)
1221 		goto invalid;
1222 
1223 	buf = kzalloc(res + padding + 1, GFP_KERNEL);
1224 	if (!buf)
1225 		return ERR_PTR(-ENOMEM);
1226 
1227 	res = ovl_path_getxattr(ofs, path, OVL_XATTR_REDIRECT, buf, res);
1228 	if (res < 0)
1229 		goto fail;
1230 	if (res == 0)
1231 		goto invalid;
1232 
1233 	if (buf[0] == '/') {
1234 		for (s = buf; *s++ == '/'; s = next) {
1235 			next = strchrnul(s, '/');
1236 			if (s == next)
1237 				goto invalid;
1238 		}
1239 	} else {
1240 		if (strchr(buf, '/') != NULL)
1241 			goto invalid;
1242 	}
1243 
1244 	return buf;
1245 invalid:
1246 	pr_warn_ratelimited("invalid redirect (%s)\n", buf);
1247 	res = -EINVAL;
1248 	goto err_free;
1249 fail:
1250 	pr_warn_ratelimited("failed to get redirect (%i)\n", res);
1251 err_free:
1252 	kfree(buf);
1253 	return ERR_PTR(res);
1254 }
1255 
1256 /* Call with mounter creds as it may open the file */
ovl_ensure_verity_loaded(struct path * datapath)1257 int ovl_ensure_verity_loaded(struct path *datapath)
1258 {
1259 	struct inode *inode = d_inode(datapath->dentry);
1260 	struct file *filp;
1261 
1262 	if (!fsverity_active(inode) && IS_VERITY(inode)) {
1263 		/*
1264 		 * If this inode was not yet opened, the verity info hasn't been
1265 		 * loaded yet, so we need to do that here to force it into memory.
1266 		 */
1267 		filp = kernel_file_open(datapath, O_RDONLY, inode, current_cred());
1268 		if (IS_ERR(filp))
1269 			return PTR_ERR(filp);
1270 		fput(filp);
1271 	}
1272 
1273 	return 0;
1274 }
1275 
ovl_validate_verity(struct ovl_fs * ofs,struct path * metapath,struct path * datapath)1276 int ovl_validate_verity(struct ovl_fs *ofs,
1277 			struct path *metapath,
1278 			struct path *datapath)
1279 {
1280 	struct ovl_metacopy metacopy_data;
1281 	u8 actual_digest[FS_VERITY_MAX_DIGEST_SIZE];
1282 	int xattr_digest_size, digest_size;
1283 	int xattr_size, err;
1284 	u8 verity_algo;
1285 
1286 	if (!ofs->config.verity_mode ||
1287 	    /* Verity only works on regular files */
1288 	    !S_ISREG(d_inode(metapath->dentry)->i_mode))
1289 		return 0;
1290 
1291 	xattr_size = ovl_check_metacopy_xattr(ofs, metapath, &metacopy_data);
1292 	if (xattr_size < 0)
1293 		return xattr_size;
1294 
1295 	if (!xattr_size || !metacopy_data.digest_algo) {
1296 		if (ofs->config.verity_mode == OVL_VERITY_REQUIRE) {
1297 			pr_warn_ratelimited("metacopy file '%pd' has no digest specified\n",
1298 					    metapath->dentry);
1299 			return -EIO;
1300 		}
1301 		return 0;
1302 	}
1303 
1304 	xattr_digest_size = ovl_metadata_digest_size(&metacopy_data);
1305 
1306 	err = ovl_ensure_verity_loaded(datapath);
1307 	if (err < 0) {
1308 		pr_warn_ratelimited("lower file '%pd' failed to load fs-verity info\n",
1309 				    datapath->dentry);
1310 		return -EIO;
1311 	}
1312 
1313 	digest_size = fsverity_get_digest(d_inode(datapath->dentry), actual_digest,
1314 					  &verity_algo, NULL);
1315 	if (digest_size == 0) {
1316 		pr_warn_ratelimited("lower file '%pd' has no fs-verity digest\n", datapath->dentry);
1317 		return -EIO;
1318 	}
1319 
1320 	if (xattr_digest_size != digest_size ||
1321 	    metacopy_data.digest_algo != verity_algo ||
1322 	    memcmp(metacopy_data.digest, actual_digest, xattr_digest_size) != 0) {
1323 		pr_warn_ratelimited("lower file '%pd' has the wrong fs-verity digest\n",
1324 				    datapath->dentry);
1325 		return -EIO;
1326 	}
1327 
1328 	return 0;
1329 }
1330 
ovl_get_verity_digest(struct ovl_fs * ofs,struct path * src,struct ovl_metacopy * metacopy)1331 int ovl_get_verity_digest(struct ovl_fs *ofs, struct path *src,
1332 			  struct ovl_metacopy *metacopy)
1333 {
1334 	int err, digest_size;
1335 
1336 	if (!ofs->config.verity_mode || !S_ISREG(d_inode(src->dentry)->i_mode))
1337 		return 0;
1338 
1339 	err = ovl_ensure_verity_loaded(src);
1340 	if (err < 0) {
1341 		pr_warn_ratelimited("lower file '%pd' failed to load fs-verity info\n",
1342 				    src->dentry);
1343 		return -EIO;
1344 	}
1345 
1346 	digest_size = fsverity_get_digest(d_inode(src->dentry),
1347 					  metacopy->digest, &metacopy->digest_algo, NULL);
1348 	if (digest_size == 0 ||
1349 	    WARN_ON_ONCE(digest_size > FS_VERITY_MAX_DIGEST_SIZE)) {
1350 		if (ofs->config.verity_mode == OVL_VERITY_REQUIRE) {
1351 			pr_warn_ratelimited("lower file '%pd' has no fs-verity digest\n",
1352 					    src->dentry);
1353 			return -EIO;
1354 		}
1355 		return 0;
1356 	}
1357 
1358 	metacopy->len += digest_size;
1359 	return 0;
1360 }
1361 
1362 /*
1363  * ovl_sync_status() - Check fs sync status for volatile mounts
1364  *
1365  * Returns 1 if this is not a volatile mount and a real sync is required.
1366  *
1367  * Returns 0 if syncing can be skipped because mount is volatile, and no errors
1368  * have occurred on the upperdir since the mount.
1369  *
1370  * Returns -errno if it is a volatile mount, and the error that occurred since
1371  * the last mount. If the error code changes, it'll return the latest error
1372  * code.
1373  */
1374 
ovl_sync_status(struct ovl_fs * ofs)1375 int ovl_sync_status(struct ovl_fs *ofs)
1376 {
1377 	struct vfsmount *mnt;
1378 
1379 	if (ovl_should_sync(ofs))
1380 		return 1;
1381 
1382 	mnt = ovl_upper_mnt(ofs);
1383 	if (!mnt)
1384 		return 0;
1385 
1386 	return errseq_check(&mnt->mnt_sb->s_wb_err, ofs->errseq);
1387 }
1388 
1389 /*
1390  * ovl_copyattr() - copy inode attributes from layer to ovl inode
1391  *
1392  * When overlay copies inode information from an upper or lower layer to the
1393  * relevant overlay inode it will apply the idmapping of the upper or lower
1394  * layer when doing so ensuring that the ovl inode ownership will correctly
1395  * reflect the ownership of the idmapped upper or lower layer. For example, an
1396  * idmapped upper or lower layer mapping id 1001 to id 1000 will take care to
1397  * map any lower or upper inode owned by id 1001 to id 1000. These mapping
1398  * helpers are nops when the relevant layer isn't idmapped.
1399  */
ovl_copyattr(struct inode * inode)1400 void ovl_copyattr(struct inode *inode)
1401 {
1402 	struct path realpath;
1403 	struct inode *realinode;
1404 	struct mnt_idmap *real_idmap;
1405 	vfsuid_t vfsuid;
1406 	vfsgid_t vfsgid;
1407 
1408 	realinode = ovl_i_path_real(inode, &realpath);
1409 	real_idmap = mnt_idmap(realpath.mnt);
1410 
1411 	vfsuid = i_uid_into_vfsuid(real_idmap, realinode);
1412 	vfsgid = i_gid_into_vfsgid(real_idmap, realinode);
1413 
1414 	inode->i_uid = vfsuid_into_kuid(vfsuid);
1415 	inode->i_gid = vfsgid_into_kgid(vfsgid);
1416 	inode->i_mode = realinode->i_mode;
1417 	inode->i_atime = realinode->i_atime;
1418 	inode->i_mtime = realinode->i_mtime;
1419 	inode_set_ctime_to_ts(inode, inode_get_ctime(realinode));
1420 	i_size_write(inode, i_size_read(realinode));
1421 }
1422