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