xref: /netbsd-src/sys/fs/union/union_subr.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: union_subr.c,v 1.57 2013/10/17 21:03:50 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Jan-Simon Pendry.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)union_subr.c	8.20 (Berkeley) 5/20/95
35  */
36 
37 /*
38  * Copyright (c) 1994 Jan-Simon Pendry
39  *
40  * This code is derived from software contributed to Berkeley by
41  * Jan-Simon Pendry.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. All advertising materials mentioning features or use of this software
52  *    must display the following acknowledgement:
53  *	This product includes software developed by the University of
54  *	California, Berkeley and its contributors.
55  * 4. Neither the name of the University nor the names of its contributors
56  *    may be used to endorse or promote products derived from this software
57  *    without specific prior written permission.
58  *
59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69  * SUCH DAMAGE.
70  *
71  *	@(#)union_subr.c	8.20 (Berkeley) 5/20/95
72  */
73 
74 #include <sys/cdefs.h>
75 __KERNEL_RCSID(0, "$NetBSD: union_subr.c,v 1.57 2013/10/17 21:03:50 christos Exp $");
76 
77 #include <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/proc.h>
80 #include <sys/time.h>
81 #include <sys/kernel.h>
82 #include <sys/vnode.h>
83 #include <sys/namei.h>
84 #include <sys/malloc.h>
85 #include <sys/dirent.h>
86 #include <sys/file.h>
87 #include <sys/filedesc.h>
88 #include <sys/queue.h>
89 #include <sys/mount.h>
90 #include <sys/stat.h>
91 #include <sys/kauth.h>
92 
93 #include <uvm/uvm_extern.h>
94 
95 #include <fs/union/union.h>
96 #include <miscfs/genfs/genfs.h>
97 #include <miscfs/specfs/specdev.h>
98 
99 static LIST_HEAD(uhashhead, union_node) *uhashtbl;
100 static u_long uhash_mask;		/* size of hash table - 1 */
101 #define UNION_HASH(u, l) \
102 	((((u_long) (u) + (u_long) (l)) >> 8) & uhash_mask)
103 #define NOHASH	((u_long)-1)
104 
105 static kmutex_t uhash_lock;
106 
107 void union_updatevp(struct union_node *, struct vnode *, struct vnode *);
108 static int union_do_lookup(struct vnode *, struct componentname *, kauth_cred_t,    const char *);
109 int union_vn_close(struct vnode *, int, kauth_cred_t, struct lwp *);
110 static void union_dircache_r(struct vnode *, struct vnode ***, int *);
111 struct vnode *union_dircache(struct vnode *, struct lwp *);
112 
113 void
114 union_init(void)
115 {
116 
117 	mutex_init(&uhash_lock, MUTEX_DEFAULT, IPL_NONE);
118 	uhashtbl = hashinit(desiredvnodes, HASH_LIST, true, &uhash_mask);
119 }
120 
121 void
122 union_reinit(void)
123 {
124 	struct union_node *un;
125 	struct uhashhead *oldhash, *hash;
126 	u_long oldmask, mask, val;
127 	int i;
128 
129 	hash = hashinit(desiredvnodes, HASH_LIST, true, &mask);
130 	mutex_enter(&uhash_lock);
131 	oldhash = uhashtbl;
132 	oldmask = uhash_mask;
133 	uhashtbl = hash;
134 	uhash_mask = mask;
135 	for (i = 0; i <= oldmask; i++) {
136 		while ((un = LIST_FIRST(&oldhash[i])) != NULL) {
137 			LIST_REMOVE(un, un_cache);
138 			val = UNION_HASH(un->un_uppervp, un->un_lowervp);
139 			LIST_INSERT_HEAD(&hash[val], un, un_cache);
140 		}
141 	}
142 	mutex_exit(&uhash_lock);
143 	hashdone(oldhash, HASH_LIST, oldmask);
144 }
145 
146 /*
147  * Free global unionfs resources.
148  */
149 void
150 union_done(void)
151 {
152 
153 	hashdone(uhashtbl, HASH_LIST, uhash_mask);
154 	mutex_destroy(&uhash_lock);
155 
156 	/* Make sure to unset the readdir hook. */
157 	vn_union_readdir_hook = NULL;
158 }
159 
160 void
161 union_updatevp(struct union_node *un, struct vnode *uppervp,
162 	struct vnode *lowervp)
163 {
164 	int ohash = UNION_HASH(un->un_uppervp, un->un_lowervp);
165 	int nhash = UNION_HASH(uppervp, lowervp);
166 	int docache = (lowervp != NULLVP || uppervp != NULLVP);
167 	bool un_unlock;
168 
169 	KASSERT(VOP_ISLOCKED(UNIONTOV(un)) == LK_EXCLUSIVE);
170 
171 	mutex_enter(&uhash_lock);
172 
173 	if (!docache || ohash != nhash) {
174 		if (un->un_cflags & UN_CACHED) {
175 			un->un_cflags &= ~UN_CACHED;
176 			LIST_REMOVE(un, un_cache);
177 		}
178 	}
179 
180 	if (un->un_lowervp != lowervp) {
181 		if (un->un_lowervp) {
182 			vrele(un->un_lowervp);
183 			if (un->un_path) {
184 				free(un->un_path, M_TEMP);
185 				un->un_path = 0;
186 			}
187 			if (un->un_dirvp) {
188 				vrele(un->un_dirvp);
189 				un->un_dirvp = NULLVP;
190 			}
191 		}
192 		un->un_lowervp = lowervp;
193 		mutex_enter(&un->un_lock);
194 		un->un_lowersz = VNOVAL;
195 		mutex_exit(&un->un_lock);
196 	}
197 
198 	if (un->un_uppervp != uppervp) {
199 		if (un->un_uppervp) {
200 			un_unlock = false;
201 			vrele(un->un_uppervp);
202 		} else
203 			un_unlock = true;
204 
205 		mutex_enter(&un->un_lock);
206 		un->un_uppervp = uppervp;
207 		mutex_exit(&un->un_lock);
208 		if (un_unlock) {
209 			struct vop_unlock_args ap;
210 
211 			ap.a_vp = UNIONTOV(un);
212 			genfs_unlock(&ap);
213 		}
214 		mutex_enter(&un->un_lock);
215 		un->un_uppersz = VNOVAL;
216 		mutex_exit(&un->un_lock);
217 		/* Update union vnode interlock. */
218 		if (uppervp != NULL) {
219 			mutex_obj_hold(uppervp->v_interlock);
220 			uvm_obj_setlock(&UNIONTOV(un)->v_uobj,
221 			    uppervp->v_interlock);
222 		}
223 	}
224 
225 	if (docache && (ohash != nhash)) {
226 		LIST_INSERT_HEAD(&uhashtbl[nhash], un, un_cache);
227 		un->un_cflags |= UN_CACHED;
228 	}
229 
230 	mutex_exit(&uhash_lock);
231 }
232 
233 void
234 union_newlower(struct union_node *un, struct vnode *lowervp)
235 {
236 
237 	union_updatevp(un, un->un_uppervp, lowervp);
238 }
239 
240 void
241 union_newupper(struct union_node *un, struct vnode *uppervp)
242 {
243 
244 	union_updatevp(un, uppervp, un->un_lowervp);
245 }
246 
247 /*
248  * Keep track of size changes in the underlying vnodes.
249  * If the size changes, then callback to the vm layer
250  * giving priority to the upper layer size.
251  *
252  * Mutex un_lock hold on entry and released on return.
253  */
254 void
255 union_newsize(struct vnode *vp, off_t uppersz, off_t lowersz)
256 {
257 	struct union_node *un = VTOUNION(vp);
258 	off_t sz;
259 
260 	KASSERT(mutex_owned(&un->un_lock));
261 	/* only interested in regular files */
262 	if (vp->v_type != VREG) {
263 		mutex_exit(&un->un_lock);
264 		uvm_vnp_setsize(vp, 0);
265 		return;
266 	}
267 
268 	sz = VNOVAL;
269 
270 	if ((uppersz != VNOVAL) && (un->un_uppersz != uppersz)) {
271 		un->un_uppersz = uppersz;
272 		if (sz == VNOVAL)
273 			sz = un->un_uppersz;
274 	}
275 
276 	if ((lowersz != VNOVAL) && (un->un_lowersz != lowersz)) {
277 		un->un_lowersz = lowersz;
278 		if (sz == VNOVAL)
279 			sz = un->un_lowersz;
280 	}
281 	mutex_exit(&un->un_lock);
282 
283 	if (sz != VNOVAL) {
284 #ifdef UNION_DIAGNOSTIC
285 		printf("union: %s size now %qd\n",
286 		    uppersz != VNOVAL ? "upper" : "lower", sz);
287 #endif
288 		uvm_vnp_setsize(vp, sz);
289 	}
290 }
291 
292 /*
293  * allocate a union_node/vnode pair.  the vnode is
294  * referenced and locked.  the new vnode is returned
295  * via (vpp).  (mp) is the mountpoint of the union filesystem,
296  * (dvp) is the parent directory where the upper layer object
297  * should exist (but doesn't) and (cnp) is the componentname
298  * information which is partially copied to allow the upper
299  * layer object to be created at a later time.  (uppervp)
300  * and (lowervp) reference the upper and lower layer objects
301  * being mapped.  either, but not both, can be nil.
302  * if supplied, (uppervp) is locked.
303  * the reference is either maintained in the new union_node
304  * object which is allocated, or they are vrele'd.
305  *
306  * all union_nodes are maintained on a singly-linked
307  * list.  new nodes are only allocated when they cannot
308  * be found on this list.  entries on the list are
309  * removed when the vfs reclaim entry is called.
310  *
311  * a single lock is kept for the entire list.  this is
312  * needed because the getnewvnode() function can block
313  * waiting for a vnode to become free, in which case there
314  * may be more than one process trying to get the same
315  * vnode.  this lock is only taken if we are going to
316  * call getnewvnode, since the kernel itself is single-threaded.
317  *
318  * if an entry is found on the list, then call vget() to
319  * take a reference.  this is done because there may be
320  * zero references to it and so it needs to removed from
321  * the vnode free list.
322  */
323 int
324 union_allocvp(
325 	struct vnode **vpp,
326 	struct mount *mp,
327 	struct vnode *undvp,		/* parent union vnode */
328 	struct vnode *dvp,		/* may be null */
329 	struct componentname *cnp,	/* may be null */
330 	struct vnode *uppervp,		/* may be null */
331 	struct vnode *lowervp,		/* may be null */
332 	int docache)
333 {
334 	int error;
335 	struct vattr va;
336 	struct union_node *un = NULL, *un1;
337 	struct vnode *vp, *xlowervp = NULLVP;
338 	struct union_mount *um = MOUNTTOUNIONMOUNT(mp);
339 	voff_t uppersz, lowersz;
340 	dev_t rdev;
341 	u_long hash[3];
342 	int vflag, iflag, lflag;
343 	int try;
344 
345 	if (uppervp)
346 		KASSERT(VOP_ISLOCKED(uppervp) == LK_EXCLUSIVE);
347 
348 	if (uppervp == NULLVP && lowervp == NULLVP)
349 		panic("union: unidentifiable allocation");
350 
351 	if (uppervp && lowervp && (uppervp->v_type != lowervp->v_type)) {
352 		xlowervp = lowervp;
353 		lowervp = NULLVP;
354 	}
355 
356 	/* detect the root vnode (and aliases) */
357 	iflag = VI_LAYER;
358 	vflag = 0;
359 	if ((uppervp == um->um_uppervp) &&
360 	    ((lowervp == NULLVP) || lowervp == um->um_lowervp)) {
361 		if (lowervp == NULLVP) {
362 			lowervp = um->um_lowervp;
363 			if (lowervp != NULLVP)
364 				vref(lowervp);
365 		}
366 		iflag = 0;
367 		vflag = VV_ROOT;
368 	}
369 
370 	if (!docache) {
371 		un = NULL;
372 		goto found;
373 	}
374 
375 	/*
376 	 * If both uppervp and lowervp are not NULL we have to
377 	 * search union nodes with one vnode as NULL too.
378 	 */
379 	hash[0] = UNION_HASH(uppervp, lowervp);
380 	if (uppervp == NULL || lowervp == NULL) {
381 		hash[1] = hash[2] = NOHASH;
382 	} else {
383 		hash[1] = UNION_HASH(uppervp, NULLVP);
384 		hash[2] = UNION_HASH(NULLVP, lowervp);
385 	}
386 
387 loop:
388 	mutex_enter(&uhash_lock);
389 
390 	for (try = 0; try < 3; try++) {
391 		if (hash[try] == NOHASH)
392 			continue;
393 		LIST_FOREACH(un, &uhashtbl[hash[try]], un_cache) {
394 			if ((un->un_lowervp && un->un_lowervp != lowervp) ||
395 			    (un->un_uppervp && un->un_uppervp != uppervp) ||
396 			    UNIONTOV(un)->v_mount != mp)
397 				continue;
398 
399 			if (uppervp != NULL &&
400 			    (uppervp == dvp || uppervp == un->un_uppervp))
401 				/* "." or already locked. */
402 				lflag = 0;
403 			else
404 				lflag = LK_EXCLUSIVE;
405 			vp = UNIONTOV(un);
406 			mutex_enter(vp->v_interlock);
407 			/*
408 			 * If this node being cleaned out and our caller
409 			 * holds a lock, then ignore it and continue.  To
410 			 * allow the cleaning to succeed the current thread
411 			 * must make progress.  For a brief time the cache
412 			 * may contain more than one vnode referring to
413 			 * a lower node.
414 			 */
415 			if ((vp->v_iflag & VI_XLOCK) != 0 && lflag == 0) {
416 				mutex_exit(vp->v_interlock);
417 				continue;
418 			}
419 			mutex_exit(&uhash_lock);
420 			if (vget(vp, lflag))
421 				goto loop;
422 			goto found;
423 		}
424 	}
425 
426 	mutex_exit(&uhash_lock);
427 
428 found:
429 	if (un) {
430 		KASSERT(VOP_ISLOCKED(UNIONTOV(un)) == LK_EXCLUSIVE);
431 		KASSERT(uppervp == NULL ||
432 		    VOP_ISLOCKED(uppervp) == LK_EXCLUSIVE);
433 		/*
434 		 * Save information about the upper layer.
435 		 */
436 		if (uppervp != un->un_uppervp) {
437 			union_newupper(un, uppervp);
438 		} else if (uppervp) {
439 			vrele(uppervp);
440 		}
441 
442 		if (un->un_uppervp)
443 			un->un_flags &= ~UN_KLOCK;
444 
445 		/*
446 		 * Save information about the lower layer.
447 		 * This needs to keep track of pathname
448 		 * and directory information which union_vn_create
449 		 * might need.
450 		 */
451 		if (lowervp != un->un_lowervp) {
452 			union_newlower(un, lowervp);
453 			if (cnp && (lowervp != NULLVP)) {
454 				un->un_path = malloc(cnp->cn_namelen+1,
455 						M_TEMP, M_WAITOK);
456 				memcpy(un->un_path, cnp->cn_nameptr,
457 						cnp->cn_namelen);
458 				un->un_path[cnp->cn_namelen] = '\0';
459 				vref(dvp);
460 				un->un_dirvp = dvp;
461 			}
462 		} else if (lowervp) {
463 			vrele(lowervp);
464 		}
465 		*vpp = UNIONTOV(un);
466 		return (0);
467 	}
468 
469 	uppersz = lowersz = VNOVAL;
470 	if (uppervp != NULLVP)
471 		if (VOP_GETATTR(uppervp, &va, FSCRED) == 0)
472 			uppersz = va.va_size;
473 	if (lowervp != NULLVP) {
474 		vn_lock(lowervp, LK_SHARED | LK_RETRY);
475 		error = VOP_GETATTR(lowervp, &va, FSCRED);
476 		VOP_UNLOCK(lowervp);
477 		if (error == 0)
478 			lowersz = va.va_size;
479 	}
480 
481 	/*
482 	 * Get a new vnode and share the lock with upper layer vnode,
483 	 * unless layers are inverted.
484 	 */
485 	vnode_t *svp = (uppervp != NULLVP) ? uppervp : lowervp;
486 	error = getnewvnode(VT_UNION, mp, union_vnodeop_p,
487 	    svp->v_interlock, vpp);
488 	if (error) {
489 		if (uppervp) {
490 			if (dvp == uppervp)
491 				vrele(uppervp);
492 			else
493 				vput(uppervp);
494 		}
495 		if (lowervp)
496 			vrele(lowervp);
497 
498 		return error;
499 	}
500 
501 	if (docache) {
502 		mutex_enter(&uhash_lock);
503 		LIST_FOREACH(un1, &uhashtbl[hash[0]], un_cache) {
504 			if (un1->un_lowervp == lowervp &&
505 			    un1->un_uppervp == uppervp &&
506 			    UNIONTOV(un1)->v_mount == mp) {
507 				vp = UNIONTOV(un1);
508 				mutex_enter(vp->v_interlock);
509 				/*
510 				 * Ignore nodes being cleaned out.
511 				 * See the cache lookup above.
512 				 */
513 				if ((vp->v_iflag & VI_XLOCK) != 0) {
514 					mutex_exit(vp->v_interlock);
515 					continue;
516 				}
517 				mutex_exit(vp->v_interlock);
518 				/*
519 				 * Another thread beat us, push back freshly
520 				 * allocated vnode and retry.
521 				 */
522 				mutex_exit(&uhash_lock);
523 				ungetnewvnode(*vpp);
524 				goto loop;
525 			}
526 		}
527 	}
528 
529 	(*vpp)->v_data = malloc(sizeof(struct union_node), M_TEMP, M_WAITOK);
530 
531 	(*vpp)->v_vflag |= vflag;
532 	(*vpp)->v_iflag |= iflag;
533 	rdev = NODEV;
534 	if (uppervp) {
535 		(*vpp)->v_type = uppervp->v_type;
536 		if (uppervp->v_type == VCHR || uppervp->v_type == VBLK)
537 			rdev = uppervp->v_rdev;
538 	} else {
539 		(*vpp)->v_type = lowervp->v_type;
540 		if (lowervp->v_type == VCHR || lowervp->v_type == VBLK)
541 			rdev = lowervp->v_rdev;
542 	}
543 	if (rdev != NODEV)
544 		spec_node_init(*vpp, rdev);
545 
546 	un = VTOUNION(*vpp);
547 	mutex_init(&un->un_lock, MUTEX_DEFAULT, IPL_NONE);
548 	un->un_vnode = *vpp;
549 	un->un_uppervp = uppervp;
550 	un->un_lowervp = lowervp;
551 	un->un_pvp = undvp;
552 	if (undvp != NULLVP)
553 		vref(undvp);
554 	un->un_dircache = 0;
555 	un->un_openl = 0;
556 	un->un_flags = 0;
557 	un->un_cflags = 0;
558 
559 	if (uppervp == NULL) {
560 		struct vop_lock_args ap;
561 
562 		ap.a_vp = UNIONTOV(un);
563 		ap.a_flags = LK_EXCLUSIVE;
564 		error = genfs_lock(&ap);
565 		KASSERT(error == 0);
566 	}
567 
568 	mutex_enter(&un->un_lock);
569 	un->un_uppersz = VNOVAL;
570 	un->un_lowersz = VNOVAL;
571 	union_newsize(*vpp, uppersz, lowersz);
572 
573 	if (dvp && cnp && (lowervp != NULLVP)) {
574 		un->un_path = malloc(cnp->cn_namelen+1, M_TEMP, M_WAITOK);
575 		memcpy(un->un_path, cnp->cn_nameptr, cnp->cn_namelen);
576 		un->un_path[cnp->cn_namelen] = '\0';
577 		vref(dvp);
578 		un->un_dirvp = dvp;
579 	} else {
580 		un->un_path = 0;
581 		un->un_dirvp = 0;
582 	}
583 
584 	if (docache) {
585 		LIST_INSERT_HEAD(&uhashtbl[hash[0]], un, un_cache);
586 		un->un_cflags |= UN_CACHED;
587 	}
588 
589 	if (xlowervp)
590 		vrele(xlowervp);
591 
592 	if (docache)
593 		mutex_exit(&uhash_lock);
594 
595 	return (error);
596 }
597 
598 int
599 union_freevp(struct vnode *vp)
600 {
601 	struct union_node *un = VTOUNION(vp);
602 
603 	mutex_enter(&uhash_lock);
604 	if (un->un_cflags & UN_CACHED) {
605 		un->un_cflags &= ~UN_CACHED;
606 		LIST_REMOVE(un, un_cache);
607 	}
608 	mutex_exit(&uhash_lock);
609 
610 	if (un->un_pvp != NULLVP)
611 		vrele(un->un_pvp);
612 	if (un->un_uppervp != NULLVP)
613 		vrele(un->un_uppervp);
614 	if (un->un_lowervp != NULLVP)
615 		vrele(un->un_lowervp);
616 	if (un->un_dirvp != NULLVP)
617 		vrele(un->un_dirvp);
618 	if (un->un_path)
619 		free(un->un_path, M_TEMP);
620 	mutex_destroy(&un->un_lock);
621 
622 	free(vp->v_data, M_TEMP);
623 	vp->v_data = NULL;
624 
625 	return (0);
626 }
627 
628 /*
629  * copyfile.  copy the vnode (fvp) to the vnode (tvp)
630  * using a sequence of reads and writes.  both (fvp)
631  * and (tvp) are locked on entry and exit.
632  */
633 int
634 union_copyfile(struct vnode *fvp, struct vnode *tvp, kauth_cred_t cred,
635 	struct lwp *l)
636 {
637 	char *tbuf;
638 	struct uio uio;
639 	struct iovec iov;
640 	int error = 0;
641 
642 	/*
643 	 * strategy:
644 	 * allocate a buffer of size MAXBSIZE.
645 	 * loop doing reads and writes, keeping track
646 	 * of the current uio offset.
647 	 * give up at the first sign of trouble.
648 	 */
649 
650 	uio.uio_offset = 0;
651 	UIO_SETUP_SYSSPACE(&uio);
652 
653 	tbuf = malloc(MAXBSIZE, M_TEMP, M_WAITOK);
654 
655 	/* ugly loop follows... */
656 	do {
657 		off_t offset = uio.uio_offset;
658 
659 		uio.uio_iov = &iov;
660 		uio.uio_iovcnt = 1;
661 		iov.iov_base = tbuf;
662 		iov.iov_len = MAXBSIZE;
663 		uio.uio_resid = iov.iov_len;
664 		uio.uio_rw = UIO_READ;
665 		error = VOP_READ(fvp, &uio, 0, cred);
666 
667 		if (error == 0) {
668 			uio.uio_iov = &iov;
669 			uio.uio_iovcnt = 1;
670 			iov.iov_base = tbuf;
671 			iov.iov_len = MAXBSIZE - uio.uio_resid;
672 			uio.uio_offset = offset;
673 			uio.uio_rw = UIO_WRITE;
674 			uio.uio_resid = iov.iov_len;
675 
676 			if (uio.uio_resid == 0)
677 				break;
678 
679 			do {
680 				error = VOP_WRITE(tvp, &uio, 0, cred);
681 			} while ((uio.uio_resid > 0) && (error == 0));
682 		}
683 
684 	} while (error == 0);
685 
686 	free(tbuf, M_TEMP);
687 	return (error);
688 }
689 
690 /*
691  * (un) is assumed to be locked on entry and remains
692  * locked on exit.
693  */
694 int
695 union_copyup(struct union_node *un, int docopy, kauth_cred_t cred,
696 	struct lwp *l)
697 {
698 	int error;
699 	struct vnode *lvp, *uvp;
700 	struct vattr lvattr, uvattr;
701 
702 	error = union_vn_create(&uvp, un, l);
703 	if (error)
704 		return (error);
705 
706 	KASSERT(VOP_ISLOCKED(uvp) == LK_EXCLUSIVE);
707 	union_newupper(un, uvp);
708 
709 	lvp = un->un_lowervp;
710 
711 	if (docopy) {
712 		/*
713 		 * XX - should not ignore errors
714 		 * from VOP_CLOSE
715 		 */
716 		vn_lock(lvp, LK_EXCLUSIVE | LK_RETRY);
717 
718         	error = VOP_GETATTR(lvp, &lvattr, cred);
719 		if (error == 0)
720 			error = VOP_OPEN(lvp, FREAD, cred);
721 		if (error == 0) {
722 			error = union_copyfile(lvp, uvp, cred, l);
723 			(void) VOP_CLOSE(lvp, FREAD, cred);
724 		}
725 		if (error == 0) {
726 			/* Copy permissions up too */
727 			vattr_null(&uvattr);
728 			uvattr.va_mode = lvattr.va_mode;
729 			uvattr.va_flags = lvattr.va_flags;
730         		error = VOP_SETATTR(uvp, &uvattr, cred);
731 		}
732 		VOP_UNLOCK(lvp);
733 #ifdef UNION_DIAGNOSTIC
734 		if (error == 0)
735 			uprintf("union: copied up %s\n", un->un_path);
736 #endif
737 
738 	}
739 	union_vn_close(uvp, FWRITE, cred, l);
740 
741 	/*
742 	 * Subsequent IOs will go to the top layer, so
743 	 * call close on the lower vnode and open on the
744 	 * upper vnode to ensure that the filesystem keeps
745 	 * its references counts right.  This doesn't do
746 	 * the right thing with (cred) and (FREAD) though.
747 	 * Ignoring error returns is not right, either.
748 	 */
749 	if (error == 0) {
750 		int i;
751 
752 		vn_lock(lvp, LK_EXCLUSIVE | LK_RETRY);
753 		for (i = 0; i < un->un_openl; i++) {
754 			(void) VOP_CLOSE(lvp, FREAD, cred);
755 			(void) VOP_OPEN(uvp, FREAD, cred);
756 		}
757 		un->un_openl = 0;
758 		VOP_UNLOCK(lvp);
759 	}
760 
761 	return (error);
762 
763 }
764 
765 /*
766  * Prepare the creation of a new node in the upper layer.
767  *
768  * (dvp) is the directory in which to create the new node.
769  * it is locked on entry and exit.
770  * (cnp) is the componentname to be created.
771  * (cred, path, hash) are credentials, path and its hash to fill (cnp).
772  */
773 static int
774 union_do_lookup(struct vnode *dvp, struct componentname *cnp, kauth_cred_t cred,
775     const char *path)
776 {
777 	int error;
778 	struct vnode *vp;
779 
780 	cnp->cn_nameiop = CREATE;
781 	cnp->cn_flags = LOCKPARENT | ISLASTCN;
782 	cnp->cn_cred = cred;
783 	cnp->cn_nameptr = path;
784 	cnp->cn_namelen = strlen(path);
785 
786 	error = VOP_LOOKUP(dvp, &vp, cnp);
787 
788 	if (error == 0) {
789 		KASSERT(vp != NULL);
790 		VOP_ABORTOP(dvp, cnp);
791 		if (dvp != vp)
792 			vput(vp);
793 		else
794 			vrele(vp);
795 		error = EEXIST;
796 	} else if (error == EJUSTRETURN) {
797 		error = 0;
798 	}
799 
800 	return error;
801 }
802 
803 /*
804  * Create a shadow directory in the upper layer.
805  * The new vnode is returned locked.
806  *
807  * (um) points to the union mount structure for access to the
808  * the mounting process's credentials.
809  * (dvp) is the directory in which to create the shadow directory.
810  * it is unlocked on entry and exit.
811  * (cnp) is the componentname to be created.
812  * (vpp) is the returned newly created shadow directory, which
813  * is returned locked.
814  *
815  * N.B. We still attempt to create shadow directories even if the union
816  * is mounted read-only, which is a little nonintuitive.
817  */
818 int
819 union_mkshadow(struct union_mount *um, struct vnode *dvp,
820 	struct componentname *cnp, struct vnode **vpp)
821 {
822 	int error;
823 	struct vattr va;
824 	struct componentname cn;
825 	char *pnbuf;
826 
827 	if (cnp->cn_namelen + 1 > MAXPATHLEN)
828 		return ENAMETOOLONG;
829 	pnbuf = PNBUF_GET();
830 	memcpy(pnbuf, cnp->cn_nameptr, cnp->cn_namelen);
831 	pnbuf[cnp->cn_namelen] = '\0';
832 
833 	vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
834 
835 	error = union_do_lookup(dvp, &cn,
836 	    (um->um_op == UNMNT_ABOVE ? cnp->cn_cred : um->um_cred), pnbuf);
837 	if (error) {
838 		VOP_UNLOCK(dvp);
839 		PNBUF_PUT(pnbuf);
840 		return error;
841 	}
842 
843 	/*
844 	 * policy: when creating the shadow directory in the
845 	 * upper layer, create it owned by the user who did
846 	 * the mount, group from parent directory, and mode
847 	 * 777 modified by umask (ie mostly identical to the
848 	 * mkdir syscall).  (jsp, kb)
849 	 */
850 
851 	vattr_null(&va);
852 	va.va_type = VDIR;
853 	va.va_mode = um->um_cmode;
854 
855 	vref(dvp);
856 	error = VOP_MKDIR(dvp, vpp, &cn, &va);
857 	PNBUF_PUT(pnbuf);
858 	return error;
859 }
860 
861 /*
862  * Create a whiteout entry in the upper layer.
863  *
864  * (um) points to the union mount structure for access to the
865  * the mounting process's credentials.
866  * (dvp) is the directory in which to create the whiteout.
867  * it is locked on entry and exit.
868  * (cnp) is the componentname to be created.
869  * (un) holds the path and its hash to be created.
870  */
871 int
872 union_mkwhiteout(struct union_mount *um, struct vnode *dvp,
873 	struct componentname *cnp, struct union_node *un)
874 {
875 	int error;
876 	struct componentname cn;
877 
878 	error = union_do_lookup(dvp, &cn,
879 	    (um->um_op == UNMNT_ABOVE ? cnp->cn_cred : um->um_cred),
880 	    un->un_path);
881 	if (error)
882 		return error;
883 
884 	error = VOP_WHITEOUT(dvp, &cn, CREATE);
885 	return error;
886 }
887 
888 /*
889  * union_vn_create: creates and opens a new shadow file
890  * on the upper union layer.  this function is similar
891  * in spirit to calling vn_open but it avoids calling namei().
892  * the problem with calling namei is that a) it locks too many
893  * things, and b) it doesn't start at the "right" directory,
894  * whereas union_do_lookup is told where to start.
895  */
896 int
897 union_vn_create(struct vnode **vpp, struct union_node *un, struct lwp *l)
898 {
899 	struct vnode *vp;
900 	kauth_cred_t cred = l->l_cred;
901 	struct vattr vat;
902 	struct vattr *vap = &vat;
903 	int fmode = FFLAGS(O_WRONLY|O_CREAT|O_TRUNC|O_EXCL);
904 	int error;
905 	int cmode = UN_FILEMODE & ~l->l_proc->p_cwdi->cwdi_cmask;
906 	struct componentname cn;
907 
908 	*vpp = NULLVP;
909 
910 	vn_lock(un->un_dirvp, LK_EXCLUSIVE | LK_RETRY);
911 
912 	error = union_do_lookup(un->un_dirvp, &cn, l->l_cred,
913 	    un->un_path);
914 	if (error) {
915 		VOP_UNLOCK(un->un_dirvp);
916 		return error;
917 	}
918 
919 	/*
920 	 * Good - there was no race to create the file
921 	 * so go ahead and create it.  The permissions
922 	 * on the file will be 0666 modified by the
923 	 * current user's umask.  Access to the file, while
924 	 * it is unioned, will require access to the top *and*
925 	 * bottom files.  Access when not unioned will simply
926 	 * require access to the top-level file.
927 	 * TODO: confirm choice of access permissions.
928 	 */
929 	vattr_null(vap);
930 	vap->va_type = VREG;
931 	vap->va_mode = cmode;
932 	vref(un->un_dirvp);
933 	error = VOP_CREATE(un->un_dirvp, &vp, &cn, vap);
934 	if (error)
935 		return error;
936 
937 	error = VOP_OPEN(vp, fmode, cred);
938 	if (error) {
939 		vput(vp);
940 		return error;
941 	}
942 
943 	vp->v_writecount++;
944 	*vpp = vp;
945 	return 0;
946 }
947 
948 int
949 union_vn_close(struct vnode *vp, int fmode, kauth_cred_t cred, struct lwp *l)
950 {
951 
952 	if (fmode & FWRITE)
953 		--vp->v_writecount;
954 	return (VOP_CLOSE(vp, fmode, cred));
955 }
956 
957 void
958 union_removed_upper(struct union_node *un)
959 {
960 	struct vnode *vp = UNIONTOV(un);
961 
962 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
963 #if 1
964 	/*
965 	 * We do not set the uppervp to NULLVP here, because lowervp
966 	 * may also be NULLVP, so this routine would end up creating
967 	 * a bogus union node with no upper or lower VP (that causes
968 	 * pain in many places that assume at least one VP exists).
969 	 * Since we've removed this node from the cache hash chains,
970 	 * it won't be found again.  When all current holders
971 	 * release it, union_inactive() will vgone() it.
972 	 */
973 	union_diruncache(un);
974 #else
975 	union_newupper(un, NULLVP);
976 #endif
977 
978 	VOP_UNLOCK(vp);
979 
980 	mutex_enter(&uhash_lock);
981 	if (un->un_cflags & UN_CACHED) {
982 		un->un_cflags &= ~UN_CACHED;
983 		LIST_REMOVE(un, un_cache);
984 	}
985 	mutex_exit(&uhash_lock);
986 }
987 
988 #if 0
989 struct vnode *
990 union_lowervp(struct vnode *vp)
991 {
992 	struct union_node *un = VTOUNION(vp);
993 
994 	if ((un->un_lowervp != NULLVP) &&
995 	    (vp->v_type == un->un_lowervp->v_type)) {
996 		if (vget(un->un_lowervp, 0) == 0)
997 			return (un->un_lowervp);
998 	}
999 
1000 	return (NULLVP);
1001 }
1002 #endif
1003 
1004 /*
1005  * determine whether a whiteout is needed
1006  * during a remove/rmdir operation.
1007  */
1008 int
1009 union_dowhiteout(struct union_node *un, kauth_cred_t cred)
1010 {
1011 	struct vattr va;
1012 
1013 	if (un->un_lowervp != NULLVP)
1014 		return (1);
1015 
1016 	if (VOP_GETATTR(un->un_uppervp, &va, cred) == 0 &&
1017 	    (va.va_flags & OPAQUE))
1018 		return (1);
1019 
1020 	return (0);
1021 }
1022 
1023 static void
1024 union_dircache_r(struct vnode *vp, struct vnode ***vppp, int *cntp)
1025 {
1026 	struct union_node *un;
1027 
1028 	if (vp->v_op != union_vnodeop_p) {
1029 		if (vppp) {
1030 			vref(vp);
1031 			*(*vppp)++ = vp;
1032 			if (--(*cntp) == 0)
1033 				panic("union: dircache table too small");
1034 		} else {
1035 			(*cntp)++;
1036 		}
1037 
1038 		return;
1039 	}
1040 
1041 	un = VTOUNION(vp);
1042 	if (un->un_uppervp != NULLVP)
1043 		union_dircache_r(un->un_uppervp, vppp, cntp);
1044 	if (un->un_lowervp != NULLVP)
1045 		union_dircache_r(un->un_lowervp, vppp, cntp);
1046 }
1047 
1048 struct vnode *
1049 union_dircache(struct vnode *vp, struct lwp *l)
1050 {
1051 	int cnt;
1052 	struct vnode *nvp = NULLVP;
1053 	struct vnode **vpp;
1054 	struct vnode **dircache;
1055 	int error;
1056 
1057 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1058 	dircache = VTOUNION(vp)->un_dircache;
1059 
1060 	nvp = NULLVP;
1061 
1062 	if (dircache == 0) {
1063 		cnt = 0;
1064 		union_dircache_r(vp, 0, &cnt);
1065 		cnt++;
1066 		dircache = (struct vnode **)
1067 				malloc(cnt * sizeof(struct vnode *),
1068 					M_TEMP, M_WAITOK);
1069 		vpp = dircache;
1070 		union_dircache_r(vp, &vpp, &cnt);
1071 		VTOUNION(vp)->un_dircache = dircache;
1072 		*vpp = NULLVP;
1073 		vpp = dircache + 1;
1074 	} else {
1075 		vpp = dircache;
1076 		do {
1077 			if (*vpp++ == VTOUNION(vp)->un_uppervp)
1078 				break;
1079 		} while (*vpp != NULLVP);
1080 	}
1081 
1082 	if (*vpp == NULLVP)
1083 		goto out;
1084 
1085 	vn_lock(*vpp, LK_EXCLUSIVE | LK_RETRY);
1086 	vref(*vpp);
1087 	error = union_allocvp(&nvp, vp->v_mount, NULLVP, NULLVP, 0, *vpp, NULLVP, 0);
1088 	if (!error) {
1089 		VTOUNION(vp)->un_dircache = 0;
1090 		VTOUNION(nvp)->un_dircache = dircache;
1091 	}
1092 
1093 out:
1094 	VOP_UNLOCK(vp);
1095 	return (nvp);
1096 }
1097 
1098 void
1099 union_diruncache(struct union_node *un)
1100 {
1101 	struct vnode **vpp;
1102 
1103 	KASSERT(VOP_ISLOCKED(UNIONTOV(un)) == LK_EXCLUSIVE);
1104 	if (un->un_dircache != 0) {
1105 		for (vpp = un->un_dircache; *vpp != NULLVP; vpp++)
1106 			vrele(*vpp);
1107 		free(un->un_dircache, M_TEMP);
1108 		un->un_dircache = 0;
1109 	}
1110 }
1111 
1112 /*
1113  * Check whether node can rmdir (check empty).
1114  */
1115 int
1116 union_check_rmdir(struct union_node *un, kauth_cred_t cred)
1117 {
1118 	int dirlen, eofflag, error;
1119 	char *dirbuf;
1120 	struct vattr va;
1121 	struct vnode *tvp;
1122 	struct dirent *dp, *edp;
1123 	struct componentname cn;
1124 	struct iovec aiov;
1125 	struct uio auio;
1126 
1127 	KASSERT(un->un_uppervp != NULL);
1128 
1129 	/* Check upper for being opaque. */
1130 	KASSERT(VOP_ISLOCKED(un->un_uppervp));
1131 	error = VOP_GETATTR(un->un_uppervp, &va, cred);
1132 	if (error || (va.va_flags & OPAQUE))
1133 		return error;
1134 
1135 	if (un->un_lowervp == NULL)
1136 		return 0;
1137 
1138 	/* Check lower for being empty. */
1139 	vn_lock(un->un_lowervp, LK_SHARED | LK_RETRY);
1140 	error = VOP_GETATTR(un->un_lowervp, &va, cred);
1141 	if (error) {
1142 		VOP_UNLOCK(un->un_lowervp);
1143 		return error;
1144 	}
1145 	dirlen = va.va_blocksize;
1146 	dirbuf = kmem_alloc(dirlen, KM_SLEEP);
1147 	if (dirbuf == NULL) {
1148 		VOP_UNLOCK(un->un_lowervp);
1149 		return ENOMEM;
1150 	}
1151 	/* error = 0; */
1152 	eofflag = 0;
1153 	auio.uio_offset = 0;
1154 	do {
1155 		aiov.iov_len = dirlen;
1156 		aiov.iov_base = dirbuf;
1157 		auio.uio_iov = &aiov;
1158 		auio.uio_iovcnt = 1;
1159 		auio.uio_resid = aiov.iov_len;
1160 		auio.uio_rw = UIO_READ;
1161 		UIO_SETUP_SYSSPACE(&auio);
1162 		error = VOP_READDIR(un->un_lowervp, &auio, cred, &eofflag,
1163 		    NULL, NULL);
1164 		if (error)
1165 			break;
1166 		edp = (struct dirent *)&dirbuf[dirlen - auio.uio_resid];
1167 		for (dp = (struct dirent *)dirbuf;
1168 		    error == 0 && dp < edp;
1169 		    dp = (struct dirent *)((char *)dp + dp->d_reclen)) {
1170 			if (dp->d_reclen == 0) {
1171 				error = ENOTEMPTY;
1172 				break;
1173 			}
1174 			if (dp->d_type == DT_WHT ||
1175 			    (dp->d_namlen == 1 && dp->d_name[0] == '.') ||
1176 			    (dp->d_namlen == 2 && !memcmp(dp->d_name, "..", 2)))
1177 				continue;
1178 			/* Check for presence in the upper layer. */
1179 			cn.cn_nameiop = LOOKUP;
1180 			cn.cn_flags = ISLASTCN | RDONLY;
1181 			cn.cn_cred = cred;
1182 			cn.cn_nameptr = dp->d_name;
1183 			cn.cn_namelen = dp->d_namlen;
1184 			error = VOP_LOOKUP(un->un_uppervp, &tvp, &cn);
1185 			if (error == ENOENT && (cn.cn_flags & ISWHITEOUT)) {
1186 				error = 0;
1187 				continue;
1188 			}
1189 			if (error == 0)
1190 				vput(tvp);
1191 			error = ENOTEMPTY;
1192 		}
1193 	} while (error == 0 && !eofflag);
1194 	kmem_free(dirbuf, dirlen);
1195 	VOP_UNLOCK(un->un_lowervp);
1196 
1197 	return error;
1198 }
1199 
1200 /*
1201  * This hook is called from vn_readdir() to switch to lower directory
1202  * entry after the upper directory is read.
1203  */
1204 int
1205 union_readdirhook(struct vnode **vpp, struct file *fp, struct lwp *l)
1206 {
1207 	struct vnode *vp = *vpp, *lvp;
1208 	struct vattr va;
1209 	int error;
1210 
1211 	if (vp->v_op != union_vnodeop_p)
1212 		return (0);
1213 
1214 	/*
1215 	 * If the directory is opaque,
1216 	 * then don't show lower entries
1217 	 */
1218 	vn_lock(vp, LK_SHARED | LK_RETRY);
1219 	error = VOP_GETATTR(vp, &va, fp->f_cred);
1220 	VOP_UNLOCK(vp);
1221 	if (error || (va.va_flags & OPAQUE))
1222 		return error;
1223 
1224 	if ((lvp = union_dircache(vp, l)) == NULLVP)
1225 		return (0);
1226 
1227 	error = VOP_OPEN(lvp, FREAD, fp->f_cred);
1228 	if (error) {
1229 		vput(lvp);
1230 		return (error);
1231 	}
1232 	VOP_UNLOCK(lvp);
1233 	fp->f_data = lvp;
1234 	fp->f_offset = 0;
1235 	error = vn_close(vp, FREAD, fp->f_cred);
1236 	if (error)
1237 		return (error);
1238 	*vpp = lvp;
1239 	return (0);
1240 }
1241