xref: /freebsd-14.2/sys/fs/unionfs/union_subr.c (revision 6d118b95)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1994 Jan-Simon Pendry
5  * Copyright (c) 1994
6  *	The Regents of the University of California.  All rights reserved.
7  * Copyright (c) 2005, 2006, 2012 Masanori Ozawa <[email protected]>, ONGS Inc.
8  * Copyright (c) 2006, 2012 Daichi Goto <[email protected]>
9  *
10  * This code is derived from software contributed to Berkeley by
11  * Jan-Simon Pendry.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)union_subr.c	8.20 (Berkeley) 5/20/95
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/ktr.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/malloc.h>
47 #include <sys/mount.h>
48 #include <sys/namei.h>
49 #include <sys/proc.h>
50 #include <sys/vnode.h>
51 #include <sys/dirent.h>
52 #include <sys/fcntl.h>
53 #include <sys/filedesc.h>
54 #include <sys/stat.h>
55 #include <sys/sysctl.h>
56 #include <sys/taskqueue.h>
57 #include <sys/resourcevar.h>
58 
59 #include <machine/atomic.h>
60 
61 #include <security/mac/mac_framework.h>
62 
63 #include <vm/uma.h>
64 
65 #include <fs/unionfs/union.h>
66 
67 #define NUNIONFSNODECACHE 16
68 #define UNIONFSHASHMASK (NUNIONFSNODECACHE - 1)
69 
70 static MALLOC_DEFINE(M_UNIONFSHASH, "UNIONFS hash", "UNIONFS hash table");
71 MALLOC_DEFINE(M_UNIONFSNODE, "UNIONFS node", "UNIONFS vnode private part");
72 MALLOC_DEFINE(M_UNIONFSPATH, "UNIONFS path", "UNIONFS path private part");
73 
74 static struct task unionfs_deferred_rele_task;
75 static struct mtx unionfs_deferred_rele_lock;
76 static STAILQ_HEAD(, unionfs_node) unionfs_deferred_rele_list =
77     STAILQ_HEAD_INITIALIZER(unionfs_deferred_rele_list);
78 static TASKQUEUE_DEFINE_THREAD(unionfs_rele);
79 
80 unsigned int unionfs_ndeferred = 0;
81 SYSCTL_UINT(_vfs, OID_AUTO, unionfs_ndeferred, CTLFLAG_RD,
82     &unionfs_ndeferred, 0, "unionfs deferred vnode release");
83 
84 static void unionfs_deferred_rele(void *, int);
85 
86 /*
87  * Initialize
88  */
89 int
unionfs_init(struct vfsconf * vfsp)90 unionfs_init(struct vfsconf *vfsp)
91 {
92 	UNIONFSDEBUG("unionfs_init\n");	/* printed during system boot */
93 	TASK_INIT(&unionfs_deferred_rele_task, 0, unionfs_deferred_rele, NULL);
94 	mtx_init(&unionfs_deferred_rele_lock, "uniondefr", NULL, MTX_DEF);
95 	return (0);
96 }
97 
98 /*
99  * Uninitialize
100  */
101 int
unionfs_uninit(struct vfsconf * vfsp)102 unionfs_uninit(struct vfsconf *vfsp)
103 {
104 	taskqueue_quiesce(taskqueue_unionfs_rele);
105 	taskqueue_free(taskqueue_unionfs_rele);
106 	mtx_destroy(&unionfs_deferred_rele_lock);
107 	return (0);
108 }
109 
110 static void
unionfs_deferred_rele(void * arg __unused,int pending __unused)111 unionfs_deferred_rele(void *arg __unused, int pending __unused)
112 {
113 	STAILQ_HEAD(, unionfs_node) local_rele_list;
114 	struct unionfs_node *unp, *tunp;
115 	unsigned int ndeferred;
116 
117 	ndeferred = 0;
118 	STAILQ_INIT(&local_rele_list);
119 	mtx_lock(&unionfs_deferred_rele_lock);
120 	STAILQ_CONCAT(&local_rele_list, &unionfs_deferred_rele_list);
121 	mtx_unlock(&unionfs_deferred_rele_lock);
122 	STAILQ_FOREACH_SAFE(unp, &local_rele_list, un_rele, tunp) {
123 		++ndeferred;
124 		MPASS(unp->un_dvp != NULL);
125 		vrele(unp->un_dvp);
126 		free(unp, M_UNIONFSNODE);
127 	}
128 
129 	/* We expect this function to be single-threaded, thus no atomic */
130 	unionfs_ndeferred += ndeferred;
131 }
132 
133 static struct unionfs_node_hashhead *
unionfs_get_hashhead(struct vnode * dvp,struct vnode * lookup)134 unionfs_get_hashhead(struct vnode *dvp, struct vnode *lookup)
135 {
136 	struct unionfs_node *unp;
137 
138 	unp = VTOUNIONFS(dvp);
139 
140 	return (&(unp->un_hashtbl[vfs_hash_index(lookup) & UNIONFSHASHMASK]));
141 }
142 
143 /*
144  * Attempt to lookup a cached unionfs vnode by upper/lower vp
145  * from dvp, with dvp's interlock held.
146  */
147 static struct vnode *
unionfs_get_cached_vnode_locked(struct vnode * lookup,struct vnode * dvp)148 unionfs_get_cached_vnode_locked(struct vnode *lookup, struct vnode *dvp)
149 {
150 	struct unionfs_node *unp;
151 	struct unionfs_node_hashhead *hd;
152 	struct vnode *vp;
153 
154 	hd = unionfs_get_hashhead(dvp, lookup);
155 
156 	LIST_FOREACH(unp, hd, un_hash) {
157 		if (unp->un_uppervp == lookup ||
158 		    unp->un_lowervp == lookup) {
159 			vp = UNIONFSTOV(unp);
160 			VI_LOCK_FLAGS(vp, MTX_DUPOK);
161 			vp->v_iflag &= ~VI_OWEINACT;
162 			if (VN_IS_DOOMED(vp) ||
163 			    ((vp->v_iflag & VI_DOINGINACT) != 0)) {
164 				VI_UNLOCK(vp);
165 				vp = NULLVP;
166 			} else {
167 				vrefl(vp);
168 				VI_UNLOCK(vp);
169 			}
170 			return (vp);
171 		}
172 	}
173 
174 	return (NULLVP);
175 }
176 
177 
178 /*
179  * Get the cached vnode.
180  */
181 static struct vnode *
unionfs_get_cached_vnode(struct vnode * uvp,struct vnode * lvp,struct vnode * dvp)182 unionfs_get_cached_vnode(struct vnode *uvp, struct vnode *lvp,
183     struct vnode *dvp)
184 {
185 	struct vnode *vp;
186 
187 	vp = NULLVP;
188 	VI_LOCK(dvp);
189 	if (uvp != NULLVP)
190 		vp = unionfs_get_cached_vnode_locked(uvp, dvp);
191 	else if (lvp != NULLVP)
192 		vp = unionfs_get_cached_vnode_locked(lvp, dvp);
193 	VI_UNLOCK(dvp);
194 
195 	return (vp);
196 }
197 
198 /*
199  * Add the new vnode into cache.
200  */
201 static struct vnode *
unionfs_ins_cached_vnode(struct unionfs_node * uncp,struct vnode * dvp)202 unionfs_ins_cached_vnode(struct unionfs_node *uncp,
203     struct vnode *dvp)
204 {
205 	struct unionfs_node_hashhead *hd;
206 	struct vnode *vp;
207 
208 	ASSERT_VOP_ELOCKED(uncp->un_uppervp, __func__);
209 	ASSERT_VOP_ELOCKED(uncp->un_lowervp, __func__);
210 	KASSERT(uncp->un_uppervp == NULLVP || uncp->un_uppervp->v_type == VDIR,
211 	    ("%s: v_type != VDIR", __func__));
212 	KASSERT(uncp->un_lowervp == NULLVP || uncp->un_lowervp->v_type == VDIR,
213 	    ("%s: v_type != VDIR", __func__));
214 
215 	vp = NULLVP;
216 	VI_LOCK(dvp);
217 	if (uncp->un_uppervp != NULL)
218 		vp = unionfs_get_cached_vnode_locked(uncp->un_uppervp, dvp);
219 	else if (uncp->un_lowervp != NULL)
220 		vp = unionfs_get_cached_vnode_locked(uncp->un_lowervp, dvp);
221 	if (vp == NULLVP) {
222 		hd = unionfs_get_hashhead(dvp, (uncp->un_uppervp != NULLVP ?
223 		    uncp->un_uppervp : uncp->un_lowervp));
224 		LIST_INSERT_HEAD(hd, uncp, un_hash);
225 	}
226 	VI_UNLOCK(dvp);
227 
228 	return (vp);
229 }
230 
231 /*
232  * Remove the vnode.
233  */
234 static void
unionfs_rem_cached_vnode(struct unionfs_node * unp,struct vnode * dvp)235 unionfs_rem_cached_vnode(struct unionfs_node *unp, struct vnode *dvp)
236 {
237 	KASSERT(unp != NULL, ("%s: null node", __func__));
238 	KASSERT(dvp != NULLVP,
239 	    ("%s: null parent vnode", __func__));
240 
241 	VI_LOCK(dvp);
242 	if (unp->un_hash.le_prev != NULL) {
243 		LIST_REMOVE(unp, un_hash);
244 		unp->un_hash.le_next = NULL;
245 		unp->un_hash.le_prev = NULL;
246 	}
247 	VI_UNLOCK(dvp);
248 }
249 
250 /*
251  * Common cleanup handling for unionfs_nodeget
252  * Upper, lower, and parent directory vnodes are expected to be referenced by
253  * the caller.  Upper and lower vnodes, if non-NULL, are also expected to be
254  * exclusively locked by the caller.
255  * This function will return with the caller's locks and references undone.
256  */
257 static void
unionfs_nodeget_cleanup(struct vnode * vp,struct unionfs_node * unp)258 unionfs_nodeget_cleanup(struct vnode *vp, struct unionfs_node *unp)
259 {
260 
261 	/*
262 	 * Lock and reset the default vnode lock; vgone() expects a locked
263 	 * vnode, and we're going to reset the vnode ops.
264 	 */
265 	lockmgr(&vp->v_lock, LK_EXCLUSIVE, NULL);
266 
267 	/*
268 	 * Clear out private data and reset the vnode ops to avoid use of
269 	 * unionfs vnode ops on a partially constructed vnode.
270 	 */
271 	VI_LOCK(vp);
272 	vp->v_data = NULL;
273 	vp->v_vnlock = &vp->v_lock;
274 	vp->v_op = &dead_vnodeops;
275 	VI_UNLOCK(vp);
276 	vgone(vp);
277 	vput(vp);
278 
279 	if (unp->un_dvp != NULLVP)
280 		vrele(unp->un_dvp);
281 	if (unp->un_uppervp != NULLVP)
282 		vput(unp->un_uppervp);
283 	if (unp->un_lowervp != NULLVP)
284 		vput(unp->un_lowervp);
285 	if (unp->un_hashtbl != NULL)
286 		hashdestroy(unp->un_hashtbl, M_UNIONFSHASH, UNIONFSHASHMASK);
287 	free(unp->un_path, M_UNIONFSPATH);
288 	free(unp, M_UNIONFSNODE);
289 }
290 
291 /*
292  * Make a new or get existing unionfs node.
293  *
294  * uppervp and lowervp should be unlocked. Because if new unionfs vnode is
295  * locked, uppervp or lowervp is locked too. In order to prevent dead lock,
296  * you should not lock plurality simultaneously.
297  */
298 int
unionfs_nodeget(struct mount * mp,struct vnode * uppervp,struct vnode * lowervp,struct vnode * dvp,struct vnode ** vpp,struct componentname * cnp)299 unionfs_nodeget(struct mount *mp, struct vnode *uppervp,
300     struct vnode *lowervp, struct vnode *dvp, struct vnode **vpp,
301     struct componentname *cnp)
302 {
303 	char	       *path;
304 	struct unionfs_mount *ump;
305 	struct unionfs_node *unp;
306 	struct vnode   *vp;
307 	u_long		hashmask;
308 	int		error;
309 	int		lkflags;
310 	__enum_uint8(vtype)	vt;
311 
312 	error = 0;
313 	ump = MOUNTTOUNIONFSMOUNT(mp);
314 	lkflags = (cnp ? cnp->cn_lkflags : 0);
315 	path = (cnp ? cnp->cn_nameptr : NULL);
316 	*vpp = NULLVP;
317 
318 	if (uppervp == NULLVP && lowervp == NULLVP)
319 		panic("%s: upper and lower is null", __func__);
320 
321 	vt = (uppervp != NULLVP ? uppervp->v_type : lowervp->v_type);
322 
323 	/* If it has no ISLASTCN flag, path check is skipped. */
324 	if (cnp && !(cnp->cn_flags & ISLASTCN))
325 		path = NULL;
326 
327 	/* check the cache */
328 	if (dvp != NULLVP && vt == VDIR) {
329 		vp = unionfs_get_cached_vnode(uppervp, lowervp, dvp);
330 		if (vp != NULLVP) {
331 			*vpp = vp;
332 			goto unionfs_nodeget_out;
333 		}
334 	}
335 
336 	unp = malloc(sizeof(struct unionfs_node),
337 	    M_UNIONFSNODE, M_WAITOK | M_ZERO);
338 
339 	error = getnewvnode("unionfs", mp, &unionfs_vnodeops, &vp);
340 	if (error != 0) {
341 		free(unp, M_UNIONFSNODE);
342 		return (error);
343 	}
344 	if (dvp != NULLVP)
345 		vref(dvp);
346 	if (uppervp != NULLVP)
347 		vref(uppervp);
348 	if (lowervp != NULLVP)
349 		vref(lowervp);
350 
351 	if (vt == VDIR) {
352 		unp->un_hashtbl = hashinit(NUNIONFSNODECACHE, M_UNIONFSHASH,
353 		    &hashmask);
354 		KASSERT(hashmask == UNIONFSHASHMASK,
355 		    ("unexpected unionfs hash mask 0x%lx", hashmask));
356 	}
357 
358 	unp->un_vnode = vp;
359 	unp->un_uppervp = uppervp;
360 	unp->un_lowervp = lowervp;
361 	unp->un_dvp = dvp;
362 	if (uppervp != NULLVP)
363 		vp->v_vnlock = uppervp->v_vnlock;
364 	else
365 		vp->v_vnlock = lowervp->v_vnlock;
366 
367 	if (path != NULL) {
368 		unp->un_path = malloc(cnp->cn_namelen + 1,
369 		    M_UNIONFSPATH, M_WAITOK | M_ZERO);
370 		bcopy(cnp->cn_nameptr, unp->un_path, cnp->cn_namelen);
371 		unp->un_path[cnp->cn_namelen] = '\0';
372 		unp->un_pathlen = cnp->cn_namelen;
373 	}
374 	vp->v_type = vt;
375 	vp->v_data = unp;
376 
377 	/*
378 	 * TODO: This is an imperfect check, as there's no guarantee that
379 	 * the underlying filesystems will always return vnode pointers
380 	 * for the root inodes that match our cached values.  To reduce
381 	 * the likelihood of failure, for example in the case where either
382 	 * vnode has been forcibly doomed, we check both pointers and set
383 	 * VV_ROOT if either matches.
384 	 */
385 	if (ump->um_uppervp == uppervp || ump->um_lowervp == lowervp)
386 		vp->v_vflag |= VV_ROOT;
387 	KASSERT(dvp != NULL || (vp->v_vflag & VV_ROOT) != 0,
388 	    ("%s: NULL dvp for non-root vp %p", __func__, vp));
389 
390 	vn_lock_pair(lowervp, false, LK_EXCLUSIVE, uppervp, false,
391 	    LK_EXCLUSIVE);
392 	error = insmntque1(vp, mp);
393 	if (error != 0) {
394 		unionfs_nodeget_cleanup(vp, unp);
395 		return (error);
396 	}
397 	if (lowervp != NULL && VN_IS_DOOMED(lowervp)) {
398 		vput(lowervp);
399 		unp->un_lowervp = lowervp = NULL;
400 	}
401 	if (uppervp != NULL && VN_IS_DOOMED(uppervp)) {
402 		vput(uppervp);
403 		unp->un_uppervp = uppervp = NULL;
404 		if (lowervp != NULLVP)
405 			vp->v_vnlock = lowervp->v_vnlock;
406 	}
407 	if (lowervp == NULL && uppervp == NULL) {
408 		unionfs_nodeget_cleanup(vp, unp);
409 		return (ENOENT);
410 	}
411 
412 	vn_set_state(vp, VSTATE_CONSTRUCTED);
413 
414 	if (dvp != NULLVP && vt == VDIR)
415 		*vpp = unionfs_ins_cached_vnode(unp, dvp);
416 	if (*vpp != NULLVP) {
417 		unionfs_nodeget_cleanup(vp, unp);
418 		vp = *vpp;
419 	} else {
420 		if (uppervp != NULL)
421 			VOP_UNLOCK(uppervp);
422 		if (lowervp != NULL)
423 			VOP_UNLOCK(lowervp);
424 		*vpp = vp;
425 	}
426 
427 unionfs_nodeget_out:
428 	if (lkflags & LK_TYPE_MASK)
429 		vn_lock(vp, lkflags | LK_RETRY);
430 
431 	return (0);
432 }
433 
434 /*
435  * Clean up the unionfs node.
436  */
437 void
unionfs_noderem(struct vnode * vp)438 unionfs_noderem(struct vnode *vp)
439 {
440 	struct unionfs_node *unp, *unp_t1, *unp_t2;
441 	struct unionfs_node_hashhead *hd;
442 	struct unionfs_node_status *unsp, *unsp_tmp;
443 	struct vnode   *lvp;
444 	struct vnode   *uvp;
445 	struct vnode   *dvp;
446 	int		count;
447 	int		writerefs;
448 
449 	/*
450 	 * The root vnode lock may be recursed during unmount, because
451 	 * it may share the same lock as the unionfs mount's covered vnode,
452 	 * which is locked across VFS_UNMOUNT().  This lock will then be
453 	 * recursively taken during the vflush() issued by unionfs_unmount().
454 	 * But we still only need to lock the unionfs lock once, because only
455 	 * one of those lock operations was taken against a unionfs vnode and
456 	 * will be undone against a unionfs vnode.
457 	 */
458 	KASSERT(vp->v_vnlock->lk_recurse == 0 || (vp->v_vflag & VV_ROOT) != 0,
459 	    ("%s: vnode %p locked recursively", __func__, vp));
460 	if (lockmgr(&vp->v_lock, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0)
461 		panic("%s: failed to acquire lock for vnode lock", __func__);
462 
463 	/*
464 	 * Use the interlock to protect the clearing of v_data to
465 	 * prevent faults in unionfs_lock().
466 	 */
467 	VI_LOCK(vp);
468 	unp = VTOUNIONFS(vp);
469 	lvp = unp->un_lowervp;
470 	uvp = unp->un_uppervp;
471 	dvp = unp->un_dvp;
472 	unp->un_lowervp = unp->un_uppervp = NULLVP;
473 	vp->v_vnlock = &(vp->v_lock);
474 	vp->v_data = NULL;
475 	vp->v_object = NULL;
476 	if (unp->un_hashtbl != NULL) {
477 		/*
478 		 * Clear out any cached child vnodes.  This should only
479 		 * be necessary during forced unmount, when the vnode may
480 		 * be reclaimed with a non-zero use count.  Otherwise the
481 		 * reference held by each child should prevent reclamation.
482 		 */
483 		for (count = 0; count <= UNIONFSHASHMASK; count++) {
484 			hd = unp->un_hashtbl + count;
485 			LIST_FOREACH_SAFE(unp_t1, hd, un_hash, unp_t2) {
486 				LIST_REMOVE(unp_t1, un_hash);
487 				unp_t1->un_hash.le_next = NULL;
488 				unp_t1->un_hash.le_prev = NULL;
489 			}
490 		}
491 	}
492 	VI_UNLOCK(vp);
493 
494 	writerefs = atomic_load_int(&vp->v_writecount);
495 	VNASSERT(writerefs >= 0, vp,
496 	    ("%s: write count %d, unexpected text ref", __func__, writerefs));
497 	/*
498 	 * If we were opened for write, we leased the write reference
499 	 * to the lower vnode.  If this is a reclamation due to the
500 	 * forced unmount, undo the reference now.
501 	 */
502 	if (writerefs > 0) {
503 		VNASSERT(uvp != NULL, vp,
504 		    ("%s: write reference without upper vnode", __func__));
505 		VOP_ADD_WRITECOUNT(uvp, -writerefs);
506 	}
507 	if (lvp != NULLVP)
508 		VOP_UNLOCK(lvp);
509 	if (uvp != NULLVP)
510 		VOP_UNLOCK(uvp);
511 
512 	if (dvp != NULLVP)
513 		unionfs_rem_cached_vnode(unp, dvp);
514 
515 	if (lvp != NULLVP)
516 		vrele(lvp);
517 	if (uvp != NULLVP)
518 		vrele(uvp);
519 	if (unp->un_path != NULL) {
520 		free(unp->un_path, M_UNIONFSPATH);
521 		unp->un_path = NULL;
522 		unp->un_pathlen = 0;
523 	}
524 
525 	if (unp->un_hashtbl != NULL) {
526 		hashdestroy(unp->un_hashtbl, M_UNIONFSHASH, UNIONFSHASHMASK);
527 	}
528 
529 	LIST_FOREACH_SAFE(unsp, &(unp->un_unshead), uns_list, unsp_tmp) {
530 		LIST_REMOVE(unsp, uns_list);
531 		free(unsp, M_TEMP);
532 	}
533 	if (dvp != NULLVP) {
534 		mtx_lock(&unionfs_deferred_rele_lock);
535 		STAILQ_INSERT_TAIL(&unionfs_deferred_rele_list, unp, un_rele);
536 		mtx_unlock(&unionfs_deferred_rele_lock);
537 		taskqueue_enqueue(taskqueue_unionfs_rele,
538 		    &unionfs_deferred_rele_task);
539 	} else
540 		free(unp, M_UNIONFSNODE);
541 }
542 
543 /*
544  * Get the unionfs node status object for the vnode corresponding to unp,
545  * for the process that owns td.  Allocate a new status object if one
546  * does not already exist.
547  */
548 void
unionfs_get_node_status(struct unionfs_node * unp,struct thread * td,struct unionfs_node_status ** unspp)549 unionfs_get_node_status(struct unionfs_node *unp, struct thread *td,
550     struct unionfs_node_status **unspp)
551 {
552 	struct unionfs_node_status *unsp;
553 	pid_t pid;
554 
555 	pid = td->td_proc->p_pid;
556 
557 	KASSERT(NULL != unspp, ("%s: NULL status", __func__));
558 	ASSERT_VOP_ELOCKED(UNIONFSTOV(unp), __func__);
559 
560 	LIST_FOREACH(unsp, &(unp->un_unshead), uns_list) {
561 		if (unsp->uns_pid == pid) {
562 			*unspp = unsp;
563 			return;
564 		}
565 	}
566 
567 	/* create a new unionfs node status */
568 	unsp = malloc(sizeof(struct unionfs_node_status),
569 	    M_TEMP, M_WAITOK | M_ZERO);
570 
571 	unsp->uns_pid = pid;
572 	LIST_INSERT_HEAD(&(unp->un_unshead), unsp, uns_list);
573 
574 	*unspp = unsp;
575 }
576 
577 /*
578  * Remove the unionfs node status, if you can.
579  * You need exclusive lock this vnode.
580  */
581 void
unionfs_tryrem_node_status(struct unionfs_node * unp,struct unionfs_node_status * unsp)582 unionfs_tryrem_node_status(struct unionfs_node *unp,
583     struct unionfs_node_status *unsp)
584 {
585 	KASSERT(NULL != unsp, ("%s: NULL status", __func__));
586 	ASSERT_VOP_ELOCKED(UNIONFSTOV(unp), __func__);
587 
588 	if (0 < unsp->uns_lower_opencnt || 0 < unsp->uns_upper_opencnt)
589 		return;
590 
591 	LIST_REMOVE(unsp, uns_list);
592 	free(unsp, M_TEMP);
593 }
594 
595 /*
596  * Create upper node attr.
597  */
598 void
unionfs_create_uppervattr_core(struct unionfs_mount * ump,struct vattr * lva,struct vattr * uva,struct thread * td)599 unionfs_create_uppervattr_core(struct unionfs_mount *ump, struct vattr *lva,
600     struct vattr *uva, struct thread *td)
601 {
602 	VATTR_NULL(uva);
603 	uva->va_type = lva->va_type;
604 	uva->va_atime = lva->va_atime;
605 	uva->va_mtime = lva->va_mtime;
606 	uva->va_ctime = lva->va_ctime;
607 
608 	switch (ump->um_copymode) {
609 	case UNIONFS_TRANSPARENT:
610 		uva->va_mode = lva->va_mode;
611 		uva->va_uid = lva->va_uid;
612 		uva->va_gid = lva->va_gid;
613 		break;
614 	case UNIONFS_MASQUERADE:
615 		if (ump->um_uid == lva->va_uid) {
616 			uva->va_mode = lva->va_mode & 077077;
617 			uva->va_mode |= (lva->va_type == VDIR ?
618 			    ump->um_udir : ump->um_ufile) & 0700;
619 			uva->va_uid = lva->va_uid;
620 			uva->va_gid = lva->va_gid;
621 		} else {
622 			uva->va_mode = (lva->va_type == VDIR ?
623 			    ump->um_udir : ump->um_ufile);
624 			uva->va_uid = ump->um_uid;
625 			uva->va_gid = ump->um_gid;
626 		}
627 		break;
628 	default:		/* UNIONFS_TRADITIONAL */
629 		uva->va_mode = 0777 & ~td->td_proc->p_pd->pd_cmask;
630 		uva->va_uid = ump->um_uid;
631 		uva->va_gid = ump->um_gid;
632 		break;
633 	}
634 }
635 
636 /*
637  * Create upper node attr.
638  */
639 int
unionfs_create_uppervattr(struct unionfs_mount * ump,struct vnode * lvp,struct vattr * uva,struct ucred * cred,struct thread * td)640 unionfs_create_uppervattr(struct unionfs_mount *ump, struct vnode *lvp,
641     struct vattr *uva, struct ucred *cred, struct thread *td)
642 {
643 	struct vattr	lva;
644 	int		error;
645 
646 	if ((error = VOP_GETATTR(lvp, &lva, cred)))
647 		return (error);
648 
649 	unionfs_create_uppervattr_core(ump, &lva, uva, td);
650 
651 	return (error);
652 }
653 
654 /*
655  * relookup
656  *
657  * dvp should be locked on entry and will be locked on return.
658  *
659  * If an error is returned, *vpp will be invalid, otherwise it will hold a
660  * locked, referenced vnode. If *vpp == dvp then remember that only one
661  * LK_EXCLUSIVE lock is held.
662  */
663 int
unionfs_relookup(struct vnode * dvp,struct vnode ** vpp,struct componentname * cnp,struct componentname * cn,struct thread * td,char * path,int pathlen,u_long nameiop)664 unionfs_relookup(struct vnode *dvp, struct vnode **vpp,
665     struct componentname *cnp, struct componentname *cn, struct thread *td,
666     char *path, int pathlen, u_long nameiop)
667 {
668 	int error;
669 	bool refstart;
670 
671 	cn->cn_namelen = pathlen;
672 	cn->cn_pnbuf = path;
673 	cn->cn_nameiop = nameiop;
674 	cn->cn_flags = (LOCKPARENT | LOCKLEAF | ISLASTCN);
675 	cn->cn_lkflags = LK_EXCLUSIVE;
676 	cn->cn_cred = cnp->cn_cred;
677 	cn->cn_nameptr = cn->cn_pnbuf;
678 
679 	refstart = false;
680 	if (nameiop == DELETE) {
681 		cn->cn_flags |= (cnp->cn_flags & DOWHITEOUT);
682 	} else if (nameiop == RENAME) {
683 		refstart = true;
684 	} else if (nameiop == CREATE) {
685 		cn->cn_flags |= NOCACHE;
686 	}
687 
688 	vref(dvp);
689 	VOP_UNLOCK(dvp);
690 
691 	if ((error = vfs_relookup(dvp, vpp, cn, refstart))) {
692 		vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
693 	} else
694 		vrele(dvp);
695 
696 	KASSERT(cn->cn_pnbuf == path, ("%s: cn_pnbuf changed", __func__));
697 
698 	return (error);
699 }
700 
701 /*
702  * relookup for CREATE namei operation.
703  *
704  * dvp is unionfs vnode. dvp should be locked.
705  *
706  * If it called 'unionfs_copyfile' function by unionfs_link etc,
707  * VOP_LOOKUP information is broken.
708  * So it need relookup in order to create link etc.
709  */
710 int
unionfs_relookup_for_create(struct vnode * dvp,struct componentname * cnp,struct thread * td)711 unionfs_relookup_for_create(struct vnode *dvp, struct componentname *cnp,
712     struct thread *td)
713 {
714 	struct vnode *udvp;
715 	struct vnode *vp;
716 	struct componentname cn;
717 	int error;
718 
719 	udvp = UNIONFSVPTOUPPERVP(dvp);
720 	vp = NULLVP;
721 
722 	error = unionfs_relookup(udvp, &vp, cnp, &cn, td, cnp->cn_nameptr,
723 	    cnp->cn_namelen, CREATE);
724 	if (error)
725 		return (error);
726 
727 	if (vp != NULLVP) {
728 		if (udvp == vp)
729 			vrele(vp);
730 		else
731 			vput(vp);
732 
733 		error = EEXIST;
734 	}
735 
736 	return (error);
737 }
738 
739 /*
740  * relookup for DELETE namei operation.
741  *
742  * dvp is unionfs vnode. dvp should be locked.
743  */
744 int
unionfs_relookup_for_delete(struct vnode * dvp,struct componentname * cnp,struct thread * td)745 unionfs_relookup_for_delete(struct vnode *dvp, struct componentname *cnp,
746     struct thread *td)
747 {
748 	struct vnode *udvp;
749 	struct vnode *vp;
750 	struct componentname cn;
751 	int error;
752 
753 	udvp = UNIONFSVPTOUPPERVP(dvp);
754 	vp = NULLVP;
755 
756 	error = unionfs_relookup(udvp, &vp, cnp, &cn, td, cnp->cn_nameptr,
757 	    cnp->cn_namelen, DELETE);
758 	if (error)
759 		return (error);
760 
761 	if (vp == NULLVP)
762 		error = ENOENT;
763 	else {
764 		if (udvp == vp)
765 			vrele(vp);
766 		else
767 			vput(vp);
768 	}
769 
770 	return (error);
771 }
772 
773 /*
774  * relookup for RENAME namei operation.
775  *
776  * dvp is unionfs vnode. dvp should be locked.
777  */
778 int
unionfs_relookup_for_rename(struct vnode * dvp,struct componentname * cnp,struct thread * td)779 unionfs_relookup_for_rename(struct vnode *dvp, struct componentname *cnp,
780     struct thread *td)
781 {
782 	struct vnode *udvp;
783 	struct vnode *vp;
784 	struct componentname cn;
785 	int error;
786 
787 	udvp = UNIONFSVPTOUPPERVP(dvp);
788 	vp = NULLVP;
789 
790 	error = unionfs_relookup(udvp, &vp, cnp, &cn, td, cnp->cn_nameptr,
791 	    cnp->cn_namelen, RENAME);
792 	if (error)
793 		return (error);
794 
795 	if (vp != NULLVP) {
796 		if (udvp == vp)
797 			vrele(vp);
798 		else
799 			vput(vp);
800 	}
801 
802 	return (error);
803 }
804 
805 /*
806  * Update the unionfs_node.
807  *
808  * uvp is new locked upper vnode. unionfs vnode's lock will be exchanged to the
809  * uvp's lock and lower's lock will be unlocked.
810  */
811 static void
unionfs_node_update(struct unionfs_node * unp,struct vnode * uvp,struct thread * td)812 unionfs_node_update(struct unionfs_node *unp, struct vnode *uvp,
813     struct thread *td)
814 {
815 	struct unionfs_node_hashhead *hd;
816 	struct vnode   *vp;
817 	struct vnode   *lvp;
818 	struct vnode   *dvp;
819 	unsigned	count, lockrec;
820 
821 	vp = UNIONFSTOV(unp);
822 	lvp = unp->un_lowervp;
823 	ASSERT_VOP_ELOCKED(lvp, __func__);
824 	ASSERT_VOP_ELOCKED(uvp, __func__);
825 	dvp = unp->un_dvp;
826 
827 	VNASSERT(vp->v_writecount == 0, vp,
828 	    ("%s: non-zero writecount", __func__));
829 	/*
830 	 * Update the upper vnode's lock state to match the lower vnode,
831 	 * and then switch the unionfs vnode's lock to the upper vnode.
832 	 */
833 	lockrec = lvp->v_vnlock->lk_recurse;
834 	for (count = 0; count < lockrec; count++)
835 		vn_lock(uvp, LK_EXCLUSIVE | LK_CANRECURSE | LK_RETRY);
836 	VI_LOCK(vp);
837 	unp->un_uppervp = uvp;
838 	vp->v_vnlock = uvp->v_vnlock;
839 	VI_UNLOCK(vp);
840 
841 	/*
842 	 * Re-cache the unionfs vnode against the upper vnode
843 	 */
844 	if (dvp != NULLVP && vp->v_type == VDIR) {
845 		VI_LOCK(dvp);
846 		if (unp->un_hash.le_prev != NULL) {
847 			LIST_REMOVE(unp, un_hash);
848 			hd = unionfs_get_hashhead(dvp, uvp);
849 			LIST_INSERT_HEAD(hd, unp, un_hash);
850 		}
851 		VI_UNLOCK(unp->un_dvp);
852 	}
853 }
854 
855 /*
856  * Create a new shadow dir.
857  *
858  * udvp should be locked on entry and will be locked on return.
859  *
860  * If no error returned, unp will be updated.
861  */
862 int
unionfs_mkshadowdir(struct unionfs_mount * ump,struct vnode * udvp,struct unionfs_node * unp,struct componentname * cnp,struct thread * td)863 unionfs_mkshadowdir(struct unionfs_mount *ump, struct vnode *udvp,
864     struct unionfs_node *unp, struct componentname *cnp, struct thread *td)
865 {
866 	struct vnode   *lvp;
867 	struct vnode   *uvp;
868 	struct vattr	va;
869 	struct vattr	lva;
870 	struct nameidata nd;
871 	struct mount   *mp;
872 	struct ucred   *cred;
873 	struct ucred   *credbk;
874 	struct uidinfo *rootinfo;
875 	int		error;
876 
877 	if (unp->un_uppervp != NULLVP)
878 		return (EEXIST);
879 
880 	lvp = unp->un_lowervp;
881 	uvp = NULLVP;
882 	credbk = cnp->cn_cred;
883 
884 	/* Authority change to root */
885 	rootinfo = uifind((uid_t)0);
886 	cred = crdup(cnp->cn_cred);
887 	/*
888 	 * The calls to chgproccnt() are needed to compensate for change_ruid()
889 	 * calling chgproccnt().
890 	 */
891 	chgproccnt(cred->cr_ruidinfo, 1, 0);
892 	change_euid(cred, rootinfo);
893 	change_ruid(cred, rootinfo);
894 	change_svuid(cred, (uid_t)0);
895 	uifree(rootinfo);
896 	cnp->cn_cred = cred;
897 
898 	memset(&nd.ni_cnd, 0, sizeof(struct componentname));
899 	NDPREINIT(&nd);
900 
901 	if ((error = VOP_GETATTR(lvp, &lva, cnp->cn_cred)))
902 		goto unionfs_mkshadowdir_abort;
903 
904 	if ((error = unionfs_relookup(udvp, &uvp, cnp, &nd.ni_cnd, td,
905 	    cnp->cn_nameptr, cnp->cn_namelen, CREATE)))
906 		goto unionfs_mkshadowdir_abort;
907 	if (uvp != NULLVP) {
908 		if (udvp == uvp)
909 			vrele(uvp);
910 		else
911 			vput(uvp);
912 
913 		error = EEXIST;
914 		goto unionfs_mkshadowdir_abort;
915 	}
916 
917 	if ((error = vn_start_write(udvp, &mp, V_WAIT | V_PCATCH)))
918 		goto unionfs_mkshadowdir_abort;
919 	unionfs_create_uppervattr_core(ump, &lva, &va, td);
920 
921 	/*
922 	 * Temporarily NUL-terminate the current pathname component.
923 	 * This function may be called during lookup operations in which
924 	 * the current pathname component is not the leaf, meaning that
925 	 * the NUL terminator is some distance beyond the end of the current
926 	 * component.  This *should* be fine, as cn_namelen will still
927 	 * correctly indicate the length of only the current component,
928 	 * but ZFS in particular does not respect cn_namelen in its VOP_MKDIR
929 	 * implementation
930 	 * Note that this assumes nd.ni_cnd.cn_pnbuf was allocated by
931 	 * something like a local namei() operation and the temporary
932 	 * NUL-termination will not have an effect on other threads.
933 	 */
934 	char *pathend = &nd.ni_cnd.cn_nameptr[nd.ni_cnd.cn_namelen];
935 	char pathterm = *pathend;
936 	*pathend = '\0';
937 	error = VOP_MKDIR(udvp, &uvp, &nd.ni_cnd, &va);
938 	*pathend = pathterm;
939 
940 	if (!error) {
941 		/*
942 		 * XXX The bug which cannot set uid/gid was corrected.
943 		 * Ignore errors.
944 		 */
945 		va.va_type = VNON;
946 		VOP_SETATTR(uvp, &va, nd.ni_cnd.cn_cred);
947 
948 		/*
949 		 * VOP_SETATTR() may transiently drop uvp's lock, so it's
950 		 * important to call it before unionfs_node_update() transfers
951 		 * the unionfs vnode's lock from lvp to uvp; otherwise the
952 		 * unionfs vnode itself would be transiently unlocked and
953 		 * potentially doomed.
954 		 */
955 		unionfs_node_update(unp, uvp, td);
956 	}
957 	vn_finished_write(mp);
958 
959 unionfs_mkshadowdir_abort:
960 	cnp->cn_cred = credbk;
961 	chgproccnt(cred->cr_ruidinfo, -1, 0);
962 	crfree(cred);
963 
964 	return (error);
965 }
966 
967 static inline void
unionfs_forward_vop_ref(struct vnode * basevp,int * lkflags)968 unionfs_forward_vop_ref(struct vnode *basevp, int *lkflags)
969 {
970 	ASSERT_VOP_LOCKED(basevp, __func__);
971 	*lkflags = VOP_ISLOCKED(basevp);
972 	vref(basevp);
973 }
974 
975 /*
976  * Prepare unionfs to issue a forwarded VOP to either the upper or lower
977  * FS.  This should be used for any VOP which may drop the vnode lock;
978  * it is not required otherwise.
979  * The unionfs vnode shares its lock with the base-layer vnode(s); if the
980  * base FS must transiently drop its vnode lock, the unionfs vnode may
981  * effectively become unlocked.  During that window, a concurrent forced
982  * unmount may doom the unionfs vnode, which leads to two significant
983  * issues:
984  * 1) Completion of, and return from, the unionfs VOP with the unionfs
985  *    vnode completely unlocked.  When the unionfs vnode becomes doomed
986  *    it stops sharing its lock with the base vnode, so even if the
987  *    forwarded VOP reacquires the base vnode lock the unionfs vnode
988  *    lock will no longer be held.  This can lead to violation of the
989  *    caller's sychronization requirements as well as various failed
990  *    locking assertions when DEBUG_VFS_LOCKS is enabled.
991  * 2) Loss of reference on the base vnode.  The caller is expected to
992  *    hold a v_usecount reference on the unionfs vnode, while the
993  *    unionfs vnode holds a reference on the base-layer vnode(s).  But
994  *    these references are released when the unionfs vnode becomes
995  *    doomed, violating the base layer's expectation that its caller
996  *    must hold a reference to prevent vnode recycling.
997  *
998  * basevp1 and basevp2 represent two base-layer vnodes which are
999  * expected to be locked when this function is called.  basevp2
1000  * may be NULL, but if not NULL basevp1 and basevp2 should represent
1001  * a parent directory and a filed linked to it, respectively.
1002  * lkflags1 and lkflags2 are output parameters that will store the
1003  * current lock status of basevp1 and basevp2, respectively.  They
1004  * are intended to be passed as the lkflags1 and lkflags2 parameters
1005  * in the subsequent call to unionfs_forward_vop_finish_pair().
1006  * lkflags2 may be NULL iff basevp2 is NULL.
1007  */
1008 void
unionfs_forward_vop_start_pair(struct vnode * basevp1,int * lkflags1,struct vnode * basevp2,int * lkflags2)1009 unionfs_forward_vop_start_pair(struct vnode *basevp1, int *lkflags1,
1010     struct vnode *basevp2, int *lkflags2)
1011 {
1012 	/*
1013 	 * Take an additional reference on the base-layer vnodes to
1014 	 * avoid loss of reference if the unionfs vnodes are doomed.
1015 	 */
1016 	unionfs_forward_vop_ref(basevp1, lkflags1);
1017 	if (basevp2 != NULL)
1018 		unionfs_forward_vop_ref(basevp2, lkflags2);
1019 }
1020 
1021 static inline bool
unionfs_forward_vop_rele(struct vnode * unionvp,struct vnode * basevp,int lkflags)1022 unionfs_forward_vop_rele(struct vnode *unionvp, struct vnode *basevp,
1023     int lkflags)
1024 {
1025 	bool unionvp_doomed;
1026 
1027 	if (__predict_false(VTOUNIONFS(unionvp) == NULL)) {
1028 		if ((lkflags & LK_EXCLUSIVE) != 0)
1029 			ASSERT_VOP_ELOCKED(basevp, __func__);
1030 		else
1031 			ASSERT_VOP_LOCKED(basevp, __func__);
1032 		unionvp_doomed = true;
1033 	} else {
1034 		vrele(basevp);
1035 		unionvp_doomed = false;
1036 	}
1037 
1038 	return (unionvp_doomed);
1039 }
1040 
1041 
1042 /*
1043  * Indicate completion of a forwarded VOP previously prepared by
1044  * unionfs_forward_vop_start_pair().
1045  * basevp1 and basevp2 must be the same values passed to the prior
1046  * call to unionfs_forward_vop_start_pair().  unionvp1 and unionvp2
1047  * must be the unionfs vnodes that were initially above basevp1 and
1048  * basevp2, respectively.
1049  * basevp1 and basevp2 (if not NULL) must be locked when this function
1050  * is called, while unionvp1 and/or unionvp2 may be unlocked if either
1051  * unionfs vnode has become doomed.
1052  * lkflags1 and lkflag2 represent the locking flags that should be
1053  * used to re-lock unionvp1 and unionvp2, respectively, if either
1054  * vnode has become doomed.
1055  *
1056  * Returns true if any unionfs vnode was found to be doomed, false
1057  * otherwise.
1058  */
1059 bool
unionfs_forward_vop_finish_pair(struct vnode * unionvp1,struct vnode * basevp1,int lkflags1,struct vnode * unionvp2,struct vnode * basevp2,int lkflags2)1060 unionfs_forward_vop_finish_pair(
1061     struct vnode *unionvp1, struct vnode *basevp1, int lkflags1,
1062     struct vnode *unionvp2, struct vnode *basevp2, int lkflags2)
1063 {
1064 	bool vp1_doomed, vp2_doomed;
1065 
1066 	/*
1067 	 * If either vnode is found to have been doomed, set
1068 	 * a flag indicating that it needs to be re-locked.
1069 	 * Otherwise, simply drop the base-vnode reference that
1070 	 * was taken in unionfs_forward_vop_start().
1071 	 */
1072 	vp1_doomed = unionfs_forward_vop_rele(unionvp1, basevp1, lkflags1);
1073 
1074 	if (unionvp2 != NULL)
1075 		vp2_doomed = unionfs_forward_vop_rele(unionvp2, basevp2, lkflags2);
1076 	else
1077 		vp2_doomed = false;
1078 
1079 	/*
1080 	 * If any of the unionfs vnodes need to be re-locked, that
1081 	 * means the unionfs vnode's lock is now de-coupled from the
1082 	 * corresponding base vnode.  We therefore need to drop the
1083 	 * base vnode lock (since nothing else will after this point),
1084 	 * and also release the reference taken in
1085 	 * unionfs_forward_vop_start_pair().
1086 	 */
1087 	if (__predict_false(vp1_doomed && vp2_doomed))
1088 		VOP_VPUT_PAIR(basevp1, &basevp2, true);
1089 	else if (__predict_false(vp1_doomed)) {
1090 		/*
1091 		 * If basevp1 needs to be unlocked, then we may not
1092 		 * be able to safely unlock it with basevp2 still locked,
1093 		 * for the same reason that an ordinary VFS call would
1094 		 * need to use VOP_VPUT_PAIR() here.  We might be able
1095 		 * to use VOP_VPUT_PAIR(..., false) here, but then we
1096 		 * would need to deal with the possibility of basevp2
1097 		 * changing out from under us, which could result in
1098 		 * either the unionfs vnode becoming doomed or its
1099 		 * upper/lower vp no longer matching basevp2.  Either
1100 		 * scenario would require at least re-locking the unionfs
1101 		 * vnode anyway.
1102 		 */
1103 		if (unionvp2 != NULL) {
1104 			VOP_UNLOCK(unionvp2);
1105 			vp2_doomed = true;
1106 		}
1107 		vput(basevp1);
1108 	} else if (__predict_false(vp2_doomed))
1109 		vput(basevp2);
1110 
1111 	if (__predict_false(vp1_doomed || vp2_doomed))
1112 		vn_lock_pair(unionvp1, !vp1_doomed, lkflags1,
1113 		    unionvp2, !vp2_doomed, lkflags2);
1114 
1115 	return (vp1_doomed || vp2_doomed);
1116 }
1117 
1118 /*
1119  * Create a new whiteout.
1120  *
1121  * udvp and dvp should be locked on entry and will be locked on return.
1122  */
1123 int
unionfs_mkwhiteout(struct vnode * dvp,struct vnode * udvp,struct componentname * cnp,struct thread * td,char * path,int pathlen)1124 unionfs_mkwhiteout(struct vnode *dvp, struct vnode *udvp,
1125     struct componentname *cnp, struct thread *td, char *path, int pathlen)
1126 {
1127 	struct vnode   *wvp;
1128 	struct nameidata nd;
1129 	struct mount   *mp;
1130 	int		error;
1131 	int		lkflags;
1132 
1133 	wvp = NULLVP;
1134 	NDPREINIT(&nd);
1135 	if ((error = unionfs_relookup(udvp, &wvp, cnp, &nd.ni_cnd, td, path,
1136 	    pathlen, CREATE))) {
1137 		return (error);
1138 	}
1139 	if (wvp != NULLVP) {
1140 		if (udvp == wvp)
1141 			vrele(wvp);
1142 		else
1143 			vput(wvp);
1144 
1145 		return (EEXIST);
1146 	}
1147 
1148 	if ((error = vn_start_write(udvp, &mp, V_WAIT | V_PCATCH)))
1149 		goto unionfs_mkwhiteout_free_out;
1150 	unionfs_forward_vop_start(udvp, &lkflags);
1151 	error = VOP_WHITEOUT(udvp, &nd.ni_cnd, CREATE);
1152 	unionfs_forward_vop_finish(dvp, udvp, lkflags);
1153 
1154 	vn_finished_write(mp);
1155 
1156 unionfs_mkwhiteout_free_out:
1157 	return (error);
1158 }
1159 
1160 /*
1161  * Create a new vnode for create a new shadow file.
1162  *
1163  * If an error is returned, *vpp will be invalid, otherwise it will hold a
1164  * locked, referenced and opened vnode.
1165  *
1166  * unp is never updated.
1167  */
1168 static int
unionfs_vn_create_on_upper(struct vnode ** vpp,struct vnode * udvp,struct unionfs_node * unp,struct vattr * uvap,struct thread * td)1169 unionfs_vn_create_on_upper(struct vnode **vpp, struct vnode *udvp,
1170     struct unionfs_node *unp, struct vattr *uvap, struct thread *td)
1171 {
1172 	struct unionfs_mount *ump;
1173 	struct vnode   *vp;
1174 	struct vnode   *lvp;
1175 	struct ucred   *cred;
1176 	struct vattr	lva;
1177 	struct nameidata nd;
1178 	int		fmode;
1179 	int		error;
1180 
1181 	ump = MOUNTTOUNIONFSMOUNT(UNIONFSTOV(unp)->v_mount);
1182 	vp = NULLVP;
1183 	lvp = unp->un_lowervp;
1184 	cred = td->td_ucred;
1185 	fmode = FFLAGS(O_WRONLY | O_CREAT | O_TRUNC | O_EXCL);
1186 	error = 0;
1187 
1188 	if ((error = VOP_GETATTR(lvp, &lva, cred)) != 0)
1189 		return (error);
1190 	unionfs_create_uppervattr_core(ump, &lva, uvap, td);
1191 
1192 	if (unp->un_path == NULL)
1193 		panic("%s: NULL un_path", __func__);
1194 
1195 	nd.ni_cnd.cn_namelen = unp->un_pathlen;
1196 	nd.ni_cnd.cn_pnbuf = unp->un_path;
1197 	nd.ni_cnd.cn_nameiop = CREATE;
1198 	nd.ni_cnd.cn_flags = LOCKPARENT | LOCKLEAF | ISLASTCN;
1199 	nd.ni_cnd.cn_lkflags = LK_EXCLUSIVE;
1200 	nd.ni_cnd.cn_cred = cred;
1201 	nd.ni_cnd.cn_nameptr = nd.ni_cnd.cn_pnbuf;
1202 	NDPREINIT(&nd);
1203 
1204 	vref(udvp);
1205 	if ((error = vfs_relookup(udvp, &vp, &nd.ni_cnd, false)) != 0)
1206 		goto unionfs_vn_create_on_upper_free_out2;
1207 	vrele(udvp);
1208 
1209 	if (vp != NULLVP) {
1210 		if (vp == udvp)
1211 			vrele(vp);
1212 		else
1213 			vput(vp);
1214 		error = EEXIST;
1215 		goto unionfs_vn_create_on_upper_free_out1;
1216 	}
1217 
1218 	if ((error = VOP_CREATE(udvp, &vp, &nd.ni_cnd, uvap)) != 0)
1219 		goto unionfs_vn_create_on_upper_free_out1;
1220 
1221 	if ((error = VOP_OPEN(vp, fmode, cred, td, NULL)) != 0) {
1222 		vput(vp);
1223 		goto unionfs_vn_create_on_upper_free_out1;
1224 	}
1225 	error = VOP_ADD_WRITECOUNT(vp, 1);
1226 	CTR3(KTR_VFS, "%s: vp %p v_writecount increased to %d",
1227 	    __func__, vp, vp->v_writecount);
1228 	if (error == 0) {
1229 		*vpp = vp;
1230 	} else {
1231 		VOP_CLOSE(vp, fmode, cred, td);
1232 	}
1233 
1234 unionfs_vn_create_on_upper_free_out1:
1235 	VOP_UNLOCK(udvp);
1236 
1237 unionfs_vn_create_on_upper_free_out2:
1238 	KASSERT(nd.ni_cnd.cn_pnbuf == unp->un_path,
1239 	    ("%s: cn_pnbuf changed", __func__));
1240 
1241 	return (error);
1242 }
1243 
1244 /*
1245  * Copy from lvp to uvp.
1246  *
1247  * lvp and uvp should be locked and opened on entry and will be locked and
1248  * opened on return.
1249  */
1250 static int
unionfs_copyfile_core(struct vnode * lvp,struct vnode * uvp,struct ucred * cred,struct thread * td)1251 unionfs_copyfile_core(struct vnode *lvp, struct vnode *uvp,
1252     struct ucred *cred, struct thread *td)
1253 {
1254 	char           *buf;
1255 	struct uio	uio;
1256 	struct iovec	iov;
1257 	off_t		offset;
1258 	int		count;
1259 	int		error;
1260 	int		bufoffset;
1261 
1262 	error = 0;
1263 	memset(&uio, 0, sizeof(uio));
1264 
1265 	uio.uio_td = td;
1266 	uio.uio_segflg = UIO_SYSSPACE;
1267 	uio.uio_offset = 0;
1268 
1269 	buf = malloc(MAXBSIZE, M_TEMP, M_WAITOK);
1270 
1271 	while (error == 0) {
1272 		offset = uio.uio_offset;
1273 
1274 		uio.uio_iov = &iov;
1275 		uio.uio_iovcnt = 1;
1276 		iov.iov_base = buf;
1277 		iov.iov_len = MAXBSIZE;
1278 		uio.uio_resid = iov.iov_len;
1279 		uio.uio_rw = UIO_READ;
1280 
1281 		if ((error = VOP_READ(lvp, &uio, 0, cred)) != 0)
1282 			break;
1283 		if ((count = MAXBSIZE - uio.uio_resid) == 0)
1284 			break;
1285 
1286 		bufoffset = 0;
1287 		while (bufoffset < count) {
1288 			uio.uio_iov = &iov;
1289 			uio.uio_iovcnt = 1;
1290 			iov.iov_base = buf + bufoffset;
1291 			iov.iov_len = count - bufoffset;
1292 			uio.uio_offset = offset + bufoffset;
1293 			uio.uio_resid = iov.iov_len;
1294 			uio.uio_rw = UIO_WRITE;
1295 
1296 			if ((error = VOP_WRITE(uvp, &uio, 0, cred)) != 0)
1297 				break;
1298 
1299 			bufoffset += (count - bufoffset) - uio.uio_resid;
1300 		}
1301 
1302 		uio.uio_offset = offset + bufoffset;
1303 	}
1304 
1305 	free(buf, M_TEMP);
1306 
1307 	return (error);
1308 }
1309 
1310 /*
1311  * Copy file from lower to upper.
1312  *
1313  * If you need copy of the contents, set 1 to docopy. Otherwise, set 0 to
1314  * docopy.
1315  *
1316  * If no error returned, unp will be updated.
1317  */
1318 int
unionfs_copyfile(struct unionfs_node * unp,int docopy,struct ucred * cred,struct thread * td)1319 unionfs_copyfile(struct unionfs_node *unp, int docopy, struct ucred *cred,
1320     struct thread *td)
1321 {
1322 	struct mount   *mp;
1323 	struct vnode   *udvp;
1324 	struct vnode   *lvp;
1325 	struct vnode   *uvp;
1326 	struct vattr	uva;
1327 	int		error;
1328 
1329 	lvp = unp->un_lowervp;
1330 	uvp = NULLVP;
1331 
1332 	if ((UNIONFSTOV(unp)->v_mount->mnt_flag & MNT_RDONLY))
1333 		return (EROFS);
1334 	if (unp->un_dvp == NULLVP)
1335 		return (EINVAL);
1336 	if (unp->un_uppervp != NULLVP)
1337 		return (EEXIST);
1338 	udvp = VTOUNIONFS(unp->un_dvp)->un_uppervp;
1339 	if (udvp == NULLVP)
1340 		return (EROFS);
1341 	if ((udvp->v_mount->mnt_flag & MNT_RDONLY))
1342 		return (EROFS);
1343 
1344 	error = VOP_ACCESS(lvp, VREAD, cred, td);
1345 	if (error != 0)
1346 		return (error);
1347 
1348 	if ((error = vn_start_write(udvp, &mp, V_WAIT | V_PCATCH)) != 0)
1349 		return (error);
1350 	error = unionfs_vn_create_on_upper(&uvp, udvp, unp, &uva, td);
1351 	if (error != 0) {
1352 		vn_finished_write(mp);
1353 		return (error);
1354 	}
1355 
1356 	if (docopy != 0) {
1357 		error = VOP_OPEN(lvp, FREAD, cred, td, NULL);
1358 		if (error == 0) {
1359 			error = unionfs_copyfile_core(lvp, uvp, cred, td);
1360 			VOP_CLOSE(lvp, FREAD, cred, td);
1361 		}
1362 	}
1363 	VOP_CLOSE(uvp, FWRITE, cred, td);
1364 	VOP_ADD_WRITECOUNT_CHECKED(uvp, -1);
1365 	CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d",
1366 	    __func__, uvp, uvp->v_writecount);
1367 
1368 	vn_finished_write(mp);
1369 
1370 	if (error == 0) {
1371 		/* Reset the attributes. Ignore errors. */
1372 		uva.va_type = VNON;
1373 		VOP_SETATTR(uvp, &uva, cred);
1374 	}
1375 
1376 	unionfs_node_update(unp, uvp, td);
1377 
1378 	return (error);
1379 }
1380 
1381 /*
1382  * It checks whether vp can rmdir. (check empty)
1383  *
1384  * vp is unionfs vnode.
1385  * vp should be locked.
1386  */
1387 int
unionfs_check_rmdir(struct vnode * vp,struct ucred * cred,struct thread * td)1388 unionfs_check_rmdir(struct vnode *vp, struct ucred *cred, struct thread *td)
1389 {
1390 	struct vnode   *uvp;
1391 	struct vnode   *lvp;
1392 	struct vnode   *tvp;
1393 	struct dirent  *dp;
1394 	struct dirent  *edp;
1395 	struct componentname cn;
1396 	struct iovec	iov;
1397 	struct uio	uio;
1398 	struct vattr	va;
1399 	int		error;
1400 	int		eofflag;
1401 	int		lookuperr;
1402 
1403 	/*
1404 	 * The size of buf needs to be larger than DIRBLKSIZ.
1405 	 */
1406 	char		buf[256 * 6];
1407 
1408 	ASSERT_VOP_ELOCKED(vp, __func__);
1409 
1410 	eofflag = 0;
1411 	uvp = UNIONFSVPTOUPPERVP(vp);
1412 	lvp = UNIONFSVPTOLOWERVP(vp);
1413 
1414 	/* check opaque */
1415 	if ((error = VOP_GETATTR(uvp, &va, cred)) != 0)
1416 		return (error);
1417 	if (va.va_flags & OPAQUE)
1418 		return (0);
1419 
1420 	/* open vnode */
1421 #ifdef MAC
1422 	if ((error = mac_vnode_check_open(cred, vp, VEXEC|VREAD)) != 0)
1423 		return (error);
1424 #endif
1425 	if ((error = VOP_ACCESS(vp, VEXEC|VREAD, cred, td)) != 0)
1426 		return (error);
1427 	if ((error = VOP_OPEN(vp, FREAD, cred, td, NULL)) != 0)
1428 		return (error);
1429 
1430 	uio.uio_rw = UIO_READ;
1431 	uio.uio_segflg = UIO_SYSSPACE;
1432 	uio.uio_td = td;
1433 	uio.uio_offset = 0;
1434 
1435 #ifdef MAC
1436 	error = mac_vnode_check_readdir(td->td_ucred, lvp);
1437 #endif
1438 	while (!error && !eofflag) {
1439 		iov.iov_base = buf;
1440 		iov.iov_len = sizeof(buf);
1441 		uio.uio_iov = &iov;
1442 		uio.uio_iovcnt = 1;
1443 		uio.uio_resid = iov.iov_len;
1444 
1445 		error = VOP_READDIR(lvp, &uio, cred, &eofflag, NULL, NULL);
1446 		if (error != 0)
1447 			break;
1448 		KASSERT(eofflag != 0 || uio.uio_resid < sizeof(buf),
1449 		    ("%s: empty read from lower FS", __func__));
1450 
1451 		edp = (struct dirent*)&buf[sizeof(buf) - uio.uio_resid];
1452 		for (dp = (struct dirent*)buf; !error && dp < edp;
1453 		     dp = (struct dirent*)((caddr_t)dp + dp->d_reclen)) {
1454 			if (dp->d_type == DT_WHT || dp->d_fileno == 0 ||
1455 			    (dp->d_namlen == 1 && dp->d_name[0] == '.') ||
1456 			    (dp->d_namlen == 2 && !bcmp(dp->d_name, "..", 2)))
1457 				continue;
1458 
1459 			cn.cn_namelen = dp->d_namlen;
1460 			cn.cn_pnbuf = NULL;
1461 			cn.cn_nameptr = dp->d_name;
1462 			cn.cn_nameiop = LOOKUP;
1463 			cn.cn_flags = LOCKPARENT | LOCKLEAF | RDONLY | ISLASTCN;
1464 			cn.cn_lkflags = LK_EXCLUSIVE;
1465 			cn.cn_cred = cred;
1466 
1467 			/*
1468 			 * check entry in lower.
1469 			 * Sometimes, readdir function returns
1470 			 * wrong entry.
1471 			 */
1472 			lookuperr = VOP_LOOKUP(lvp, &tvp, &cn);
1473 
1474 			if (!lookuperr)
1475 				vput(tvp);
1476 			else
1477 				continue; /* skip entry */
1478 
1479 			/*
1480 			 * check entry
1481 			 * If it has no exist/whiteout entry in upper,
1482 			 * directory is not empty.
1483 			 */
1484 			cn.cn_flags = LOCKPARENT | LOCKLEAF | RDONLY | ISLASTCN;
1485 			lookuperr = VOP_LOOKUP(uvp, &tvp, &cn);
1486 
1487 			if (!lookuperr)
1488 				vput(tvp);
1489 
1490 			/* ignore exist or whiteout entry */
1491 			if (!lookuperr ||
1492 			    (lookuperr == ENOENT && (cn.cn_flags & ISWHITEOUT)))
1493 				continue;
1494 
1495 			error = ENOTEMPTY;
1496 		}
1497 	}
1498 
1499 	/* close vnode */
1500 	VOP_CLOSE(vp, FREAD, cred, td);
1501 
1502 	return (error);
1503 }
1504 
1505