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