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