xref: /freebsd/sys/fs/unionfs/union_subr.c (revision 6af83ee0d2941d18880b6aaa2b4facd1d30c6106)
1 /*-
2  * Copyright (c) 1994 Jan-Simon Pendry
3  * Copyright (c) 1994
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Jan-Simon Pendry.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)union_subr.c	8.20 (Berkeley) 5/20/95
34  * $FreeBSD$
35  */
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/fcntl.h>
40 #include <sys/file.h>
41 #include <sys/filedesc.h>
42 #include <sys/kernel.h>
43 #include <sys/lock.h>
44 #include <sys/malloc.h>
45 #include <sys/module.h>
46 #include <sys/mount.h>
47 #include <sys/mutex.h>
48 #include <sys/namei.h>
49 #include <sys/stat.h>
50 #include <sys/vnode.h>
51 
52 #include <vm/vm.h>
53 #include <vm/vm_extern.h>	/* for vnode_pager_setsize */
54 #include <vm/vm_object.h>	/* for vm cache coherency */
55 #include <vm/uma.h>
56 
57 #include <fs/unionfs/union.h>
58 
59 #include <sys/proc.h>
60 
61 extern int	union_init(void);
62 
63 /* must be power of two, otherwise change UNION_HASH() */
64 #define NHASH 32
65 
66 /* unsigned int ... */
67 #define UNION_HASH(u, l) \
68 	(((((uintptr_t) (u)) + ((uintptr_t) l)) >> 8) & (NHASH-1))
69 
70 static MALLOC_DEFINE(M_UNPATH, "unpath", "UNION path component");
71 static MALLOC_DEFINE(M_UNDCACHE, "undcac", "UNION directory cache");
72 
73 static LIST_HEAD(unhead, union_node) unhead[NHASH];
74 static int unvplock[NHASH];
75 
76 static void	union_dircache_r(struct vnode *vp, struct vnode ***vppp,
77 				      int *cntp);
78 static int	union_list_lock(int ix);
79 static void	union_list_unlock(int ix);
80 static int	union_relookup(struct union_mount *um, struct vnode *dvp,
81 				    struct vnode **vpp,
82 				    struct componentname *cnp,
83 				    struct componentname *cn, char *path,
84 				    int pathlen);
85 static void	union_updatevp(struct union_node *un,
86 				    struct vnode *uppervp,
87 				    struct vnode *lowervp);
88 static void union_newlower(struct union_node *, struct vnode *);
89 static void union_newupper(struct union_node *, struct vnode *);
90 static int union_copyfile(struct vnode *, struct vnode *,
91 					struct ucred *, struct thread *);
92 static int union_vn_create(struct vnode **, struct union_node *,
93 				struct thread *);
94 static int union_vn_close(struct vnode *, int, struct ucred *,
95 				struct thread *);
96 
97 int
98 union_init()
99 {
100 	int i;
101 
102 	for (i = 0; i < NHASH; i++)
103 		LIST_INIT(&unhead[i]);
104 	bzero((caddr_t)unvplock, sizeof(unvplock));
105 	return (0);
106 }
107 
108 static int
109 union_list_lock(ix)
110 	int ix;
111 {
112 	if (unvplock[ix] & UNVP_LOCKED) {
113 		unvplock[ix] |= UNVP_WANT;
114 		(void) tsleep( &unvplock[ix], PINOD, "unllck", 0);
115 		return (1);
116 	}
117 	unvplock[ix] |= UNVP_LOCKED;
118 	return (0);
119 }
120 
121 static void
122 union_list_unlock(ix)
123 	int ix;
124 {
125 	unvplock[ix] &= ~UNVP_LOCKED;
126 
127 	if (unvplock[ix] & UNVP_WANT) {
128 		unvplock[ix] &= ~UNVP_WANT;
129 		wakeup( &unvplock[ix]);
130 	}
131 }
132 
133 /*
134  *	union_updatevp:
135  *
136  *	The uppervp, if not NULL, must be referenced and not locked by us
137  *	The lowervp, if not NULL, must be referenced.
138  *
139  *	If uppervp and lowervp match pointers already installed, then
140  *	nothing happens. The passed vp's (when matching) are not adjusted.
141  *
142  *	This routine may only be called by union_newupper() and
143  *	union_newlower().
144  */
145 
146 static void
147 union_updatevp(un, uppervp, lowervp)
148 	struct union_node *un;
149 	struct vnode *uppervp;
150 	struct vnode *lowervp;
151 {
152 	int ohash = UNION_HASH(un->un_uppervp, un->un_lowervp);
153 	int nhash = UNION_HASH(uppervp, lowervp);
154 	int docache = (lowervp != NULLVP || uppervp != NULLVP);
155 	int lhash, uhash;
156 
157 	/*
158 	 * Ensure locking is ordered from lower to higher
159 	 * to avoid deadlocks.
160 	 */
161 	if (nhash < ohash) {
162 		lhash = nhash;
163 		uhash = ohash;
164 	} else {
165 		lhash = ohash;
166 		uhash = nhash;
167 	}
168 
169 	if (lhash != uhash) {
170 		while (union_list_lock(lhash))
171 			continue;
172 	}
173 
174 	while (union_list_lock(uhash))
175 		continue;
176 
177 	if (ohash != nhash || !docache) {
178 		if (un->un_flags & UN_CACHED) {
179 			un->un_flags &= ~UN_CACHED;
180 			LIST_REMOVE(un, un_cache);
181 		}
182 	}
183 
184 	if (ohash != nhash)
185 		union_list_unlock(ohash);
186 
187 	if (un->un_lowervp != lowervp) {
188 		if (un->un_lowervp) {
189 			vrele(un->un_lowervp);
190 			if (un->un_path) {
191 				free(un->un_path, M_UNPATH);
192 				un->un_path = 0;
193 			}
194 		}
195 		un->un_lowervp = lowervp;
196 		un->un_lowersz = VNOVAL;
197 	}
198 
199 	if (un->un_uppervp != uppervp) {
200 		if (un->un_uppervp)
201 			vrele(un->un_uppervp);
202 		un->un_uppervp = uppervp;
203 		un->un_uppersz = VNOVAL;
204 	}
205 
206 	if (docache && (ohash != nhash)) {
207 		LIST_INSERT_HEAD(&unhead[nhash], un, un_cache);
208 		un->un_flags |= UN_CACHED;
209 	}
210 
211 	union_list_unlock(nhash);
212 }
213 
214 /*
215  * Set a new lowervp.  The passed lowervp must be referenced and will be
216  * stored in the vp in a referenced state.
217  */
218 
219 static void
220 union_newlower(un, lowervp)
221 	struct union_node *un;
222 	struct vnode *lowervp;
223 {
224 	union_updatevp(un, un->un_uppervp, lowervp);
225 }
226 
227 /*
228  * Set a new uppervp.  The passed uppervp must be locked and will be
229  * stored in the vp in a locked state.  The caller should not unlock
230  * uppervp.
231  */
232 
233 static void
234 union_newupper(un, uppervp)
235 	struct union_node *un;
236 	struct vnode *uppervp;
237 {
238 	union_updatevp(un, uppervp, un->un_lowervp);
239 }
240 
241 /*
242  * Keep track of size changes in the underlying vnodes.
243  * If the size changes, then callback to the vm layer
244  * giving priority to the upper layer size.
245  */
246 void
247 union_newsize(vp, uppersz, lowersz)
248 	struct vnode *vp;
249 	off_t uppersz, lowersz;
250 {
251 	struct union_node *un;
252 	off_t sz;
253 
254 	/* only interested in regular files */
255 	if (vp->v_type != VREG)
256 		return;
257 
258 	un = VTOUNION(vp);
259 	sz = VNOVAL;
260 
261 	if ((uppersz != VNOVAL) && (un->un_uppersz != uppersz)) {
262 		un->un_uppersz = uppersz;
263 		if (sz == VNOVAL)
264 			sz = un->un_uppersz;
265 	}
266 
267 	if ((lowersz != VNOVAL) && (un->un_lowersz != lowersz)) {
268 		un->un_lowersz = lowersz;
269 		if (sz == VNOVAL)
270 			sz = un->un_lowersz;
271 	}
272 
273 	if (sz != VNOVAL) {
274 		UDEBUG(("union: %s size now %ld\n",
275 			(uppersz != VNOVAL ? "upper" : "lower"), (long)sz));
276 		/*
277 		 * There is no need to change size of non-existent object.
278 		 */
279 		/* vnode_pager_setsize(vp, sz); */
280 	}
281 }
282 
283 /*
284  *	union_allocvp:	allocate a union_node and associate it with a
285  *			parent union_node and one or two vnodes.
286  *
287  *	vpp	Holds the returned vnode locked and referenced if no
288  *		error occurs.
289  *
290  *	mp	Holds the mount point.  mp may or may not be busied.
291  *		allocvp() makes no changes to mp.
292  *
293  *	dvp	Holds the parent union_node to the one we wish to create.
294  *		XXX may only be used to traverse an uncopied lowervp-based
295  *		tree?  XXX
296  *
297  *		dvp may or may not be locked.  allocvp() makes no changes
298  *		to dvp.
299  *
300  *	upperdvp Holds the parent vnode to uppervp, generally used along
301  *		with path component information to create a shadow of
302  *		lowervp when uppervp does not exist.
303  *
304  *		upperdvp is referenced but unlocked on entry, and will be
305  *		dereferenced on return.
306  *
307  *	uppervp	Holds the new uppervp vnode to be stored in the
308  *		union_node we are allocating.  uppervp is referenced but
309  *		not locked, and will be dereferenced on return.
310  *
311  *	lowervp	Holds the new lowervp vnode to be stored in the
312  *		union_node we are allocating.  lowervp is referenced but
313  *		not locked, and will be dereferenced on return.
314  *
315  *	cnp	Holds path component information to be coupled with
316  *		lowervp and upperdvp to allow unionfs to create an uppervp
317  *		later on.  Only used if lowervp is valid.  The contents
318  *		of cnp is only valid for the duration of the call.
319  *
320  *	docache	Determine whether this node should be entered in the
321  *		cache or whether it should be destroyed as soon as possible.
322  *
323  * All union_nodes are maintained on a singly-linked
324  * list.  New nodes are only allocated when they cannot
325  * be found on this list.  Entries on the list are
326  * removed when the vfs reclaim entry is called.
327  *
328  * A single lock is kept for the entire list.  This is
329  * needed because the getnewvnode() function can block
330  * waiting for a vnode to become free, in which case there
331  * may be more than one process trying to get the same
332  * vnode.  This lock is only taken if we are going to
333  * call getnewvnode(), since the kernel itself is single-threaded.
334  *
335  * If an entry is found on the list, then call vget() to
336  * take a reference.  This is done because there may be
337  * zero references to it and so it needs to removed from
338  * the vnode free list.
339  */
340 
341 int
342 union_allocvp(vpp, mp, dvp, upperdvp, cnp, uppervp, lowervp, docache)
343 	struct vnode **vpp;
344 	struct mount *mp;
345 	struct vnode *dvp;		/* parent union vnode */
346 	struct vnode *upperdvp;		/* parent vnode of uppervp */
347 	struct componentname *cnp;	/* may be null */
348 	struct vnode *uppervp;		/* may be null */
349 	struct vnode *lowervp;		/* may be null */
350 	int docache;
351 {
352 	int error;
353 	struct union_node *un = 0;
354 	struct union_mount *um = MOUNTTOUNIONMOUNT(mp);
355 	struct thread *td = (cnp) ? cnp->cn_thread : curthread;
356 	int hash = 0;
357 	int vflag;
358 	int try;
359 
360 	if (uppervp == NULLVP && lowervp == NULLVP)
361 		panic("union: unidentifiable allocation");
362 
363 	if (uppervp && lowervp && (uppervp->v_type != lowervp->v_type)) {
364 		vrele(lowervp);
365 		lowervp = NULLVP;
366 	}
367 
368 	/* detect the root vnode (and aliases) */
369 	vflag = 0;
370 	if ((uppervp == um->um_uppervp) &&
371 	    ((lowervp == NULLVP) || lowervp == um->um_lowervp)) {
372 		if (lowervp == NULLVP) {
373 			lowervp = um->um_lowervp;
374 			if (lowervp != NULLVP)
375 				VREF(lowervp);
376 		}
377 		vflag = VV_ROOT;
378 	}
379 
380 loop:
381 	if (!docache) {
382 		un = 0;
383 	} else for (try = 0; try < 3; try++) {
384 		switch (try) {
385 		case 0:
386 			if (lowervp == NULLVP)
387 				continue;
388 			hash = UNION_HASH(uppervp, lowervp);
389 			break;
390 
391 		case 1:
392 			if (uppervp == NULLVP)
393 				continue;
394 			hash = UNION_HASH(uppervp, NULLVP);
395 			break;
396 
397 		case 2:
398 			if (lowervp == NULLVP)
399 				continue;
400 			hash = UNION_HASH(NULLVP, lowervp);
401 			break;
402 		}
403 
404 		while (union_list_lock(hash))
405 			continue;
406 
407 		LIST_FOREACH(un, &unhead[hash], un_cache) {
408 			if ((un->un_lowervp == lowervp ||
409 			     un->un_lowervp == NULLVP) &&
410 			    (un->un_uppervp == uppervp ||
411 			     un->un_uppervp == NULLVP) &&
412 			    (UNIONTOV(un)->v_mount == mp)) {
413 				if (vget(UNIONTOV(un), 0,
414 				    cnp ? cnp->cn_thread : NULL)) {
415 					union_list_unlock(hash);
416 					goto loop;
417 				}
418 				break;
419 			}
420 		}
421 
422 		union_list_unlock(hash);
423 
424 		if (un)
425 			break;
426 	}
427 
428 	if (un) {
429 		/*
430 		 * Obtain a lock on the union_node.  Everything is unlocked
431 		 * except for dvp, so check that case.  If they match, our
432 		 * new un is already locked.  Otherwise we have to lock our
433 		 * new un.
434 		 *
435 		 * A potential deadlock situation occurs when we are holding
436 		 * one lock while trying to get another.  We must follow
437 		 * strict ordering rules to avoid it.  We try to locate dvp
438 		 * by scanning up from un_vnode, since the most likely
439 		 * scenario is un being under dvp.
440 		 */
441 
442 		if (dvp && un->un_vnode != dvp) {
443 			struct vnode *scan = un->un_vnode;
444 
445 			do {
446 				scan = VTOUNION(scan)->un_pvp;
447 			} while (scan && scan->v_op == &union_vnodeops &&
448 				 scan != dvp);
449 			if (scan != dvp) {
450 				/*
451 				 * our new un is above dvp (we never saw dvp
452 				 * while moving up the tree).
453 				 */
454 				VREF(dvp);
455 				VOP_UNLOCK(dvp, 0, td);
456 				error = vn_lock(un->un_vnode, LK_EXCLUSIVE, td);
457 				vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY, td);
458 				vrele(dvp);
459 			} else {
460 				/*
461 				 * our new un is under dvp
462 				 */
463 				error = vn_lock(un->un_vnode, LK_EXCLUSIVE, td);
464 			}
465 		} else if (dvp == NULLVP) {
466 			/*
467 			 * dvp is NULL, we need to lock un.
468 			 */
469 			error = vn_lock(un->un_vnode, LK_EXCLUSIVE, td);
470 		} else {
471 			/*
472 			 * dvp == un->un_vnode, we are already locked.
473 			 */
474 			error = 0;
475 		}
476 
477 		if (error)
478 			goto loop;
479 
480 		/*
481 		 * At this point, the union_node is locked and referenced.
482 		 *
483 		 * uppervp is locked and referenced or NULL, lowervp is
484 		 * referenced or NULL.
485 		 */
486 		UDEBUG(("Modify existing un %p vn %p upper %p(refs %d) -> %p(refs %d)\n",
487 			un, un->un_vnode, un->un_uppervp,
488 			(un->un_uppervp ? vrefcnt(un->un_uppervp) : -99),
489 			uppervp,
490 			(uppervp ? vrefcnt(uppervp) : -99)
491 		));
492 
493 		if (uppervp != un->un_uppervp) {
494 			KASSERT(uppervp == NULL || vrefcnt(uppervp) > 0, ("union_allocvp: too few refs %d (at least 1 required) on uppervp", vrefcnt(uppervp)));
495 			union_newupper(un, uppervp);
496 		} else if (uppervp) {
497 			KASSERT(vrefcnt(uppervp) > 1, ("union_allocvp: too few refs %d (at least 2 required) on uppervp", vrefcnt(uppervp)));
498 			vrele(uppervp);
499 		}
500 
501 		/*
502 		 * Save information about the lower layer.
503 		 * This needs to keep track of pathname
504 		 * and directory information which union_vn_create()
505 		 * might need.
506 		 */
507 		if (lowervp != un->un_lowervp) {
508 			union_newlower(un, lowervp);
509 			if (cnp && (lowervp != NULLVP)) {
510 				un->un_path = malloc(cnp->cn_namelen+1,
511 						M_UNPATH, M_WAITOK);
512 				bcopy(cnp->cn_nameptr, un->un_path,
513 						cnp->cn_namelen);
514 				un->un_path[cnp->cn_namelen] = '\0';
515 			}
516 		} else if (lowervp) {
517 			vrele(lowervp);
518 		}
519 
520 		/*
521 		 * and upperdvp
522 		 */
523 		if (upperdvp != un->un_dirvp) {
524 			if (un->un_dirvp)
525 				vrele(un->un_dirvp);
526 			un->un_dirvp = upperdvp;
527 		} else if (upperdvp) {
528 			vrele(upperdvp);
529 		}
530 
531 		*vpp = UNIONTOV(un);
532 		return (0);
533 	}
534 
535 	if (docache) {
536 		/*
537 		 * Otherwise lock the vp list while we call getnewvnode()
538 		 * since that can block.
539 		 */
540 		hash = UNION_HASH(uppervp, lowervp);
541 
542 		if (union_list_lock(hash))
543 			goto loop;
544 	}
545 
546 	/*
547 	 * Create new node rather than replace old node.
548 	 */
549 
550 	error = getnewvnode("union", mp, &union_vnodeops, vpp);
551 	if (error) {
552 		/*
553 		 * If an error occurs, clear out vnodes.
554 		 */
555 		if (lowervp)
556 			vrele(lowervp);
557 		if (uppervp)
558 			vrele(uppervp);
559 		if (upperdvp)
560 			vrele(upperdvp);
561 		*vpp = NULL;
562 		goto out;
563 	}
564 
565 	MALLOC((*vpp)->v_data, void *, sizeof(struct union_node),
566 		M_TEMP, M_WAITOK);
567 
568 	ASSERT_VOP_LOCKED(*vpp, "union_allocvp");
569 	(*vpp)->v_vflag |= vflag;
570 	if (uppervp)
571 		(*vpp)->v_type = uppervp->v_type;
572 	else
573 		(*vpp)->v_type = lowervp->v_type;
574 
575 	un = VTOUNION(*vpp);
576 	bzero(un, sizeof(*un));
577 
578 	vn_lock(*vpp, LK_EXCLUSIVE | LK_RETRY, td);
579 
580 	un->un_vnode = *vpp;
581 	un->un_uppervp = uppervp;
582 	un->un_uppersz = VNOVAL;
583 	un->un_lowervp = lowervp;
584 	un->un_lowersz = VNOVAL;
585 	un->un_dirvp = upperdvp;
586 	un->un_pvp = dvp;		/* only parent dir in new allocation */
587 	if (dvp != NULLVP)
588 		VREF(dvp);
589 	un->un_dircache = NULL;
590 	un->un_openl = 0;
591 
592 	if (cnp && (lowervp != NULLVP)) {
593 		un->un_path = malloc(cnp->cn_namelen+1, M_UNPATH, M_WAITOK);
594 		bcopy(cnp->cn_nameptr, un->un_path, cnp->cn_namelen);
595 		un->un_path[cnp->cn_namelen] = '\0';
596 	} else {
597 		un->un_path = NULL;
598 		un->un_dirvp = NULL;
599 	}
600 
601 	if (docache) {
602 		LIST_INSERT_HEAD(&unhead[hash], un, un_cache);
603 		un->un_flags |= UN_CACHED;
604 	}
605 
606 out:
607 	if (docache)
608 		union_list_unlock(hash);
609 
610 	return (error);
611 }
612 
613 int
614 union_freevp(vp)
615 	struct vnode *vp;
616 {
617 	struct union_node *un = VTOUNION(vp);
618 
619 	if (un->un_flags & UN_CACHED) {
620 		un->un_flags &= ~UN_CACHED;
621 		LIST_REMOVE(un, un_cache);
622 	}
623 
624 	if (un->un_pvp != NULLVP) {
625 		vrele(un->un_pvp);
626 		un->un_pvp = NULL;
627 	}
628 	if (un->un_uppervp != NULLVP) {
629 		vrele(un->un_uppervp);
630 		un->un_uppervp = NULL;
631 	}
632 	if (un->un_lowervp != NULLVP) {
633 		vrele(un->un_lowervp);
634 		un->un_lowervp = NULL;
635 	}
636 	if (un->un_dirvp != NULLVP) {
637 		vrele(un->un_dirvp);
638 		un->un_dirvp = NULL;
639 	}
640 	if (un->un_path) {
641 		free(un->un_path, M_UNPATH);
642 		un->un_path = NULL;
643 	}
644 
645 	FREE(vp->v_data, M_TEMP);
646 	vp->v_data = 0;
647 	vp->v_object = NULL;
648 
649 	return (0);
650 }
651 
652 /*
653  * copyfile.  Copy the vnode (fvp) to the vnode (tvp)
654  * using a sequence of reads and writes.  Both (fvp)
655  * and (tvp) are locked on entry and exit.
656  *
657  * fvp and tvp are both exclusive locked on call, but their refcount's
658  * haven't been bumped at all.
659  */
660 static int
661 union_copyfile(fvp, tvp, cred, td)
662 	struct vnode *fvp;
663 	struct vnode *tvp;
664 	struct ucred *cred;
665 	struct thread *td;
666 {
667 	char *buf;
668 	struct uio uio;
669 	struct iovec iov;
670 	int error = 0;
671 
672 	/*
673 	 * strategy:
674 	 * Allocate a buffer of size MAXBSIZE.
675 	 * Loop doing reads and writes, keeping track
676 	 * of the current uio offset.
677 	 * Give up at the first sign of trouble.
678 	 */
679 
680 	bzero(&uio, sizeof(uio));
681 
682 	uio.uio_td = td;
683 	uio.uio_segflg = UIO_SYSSPACE;
684 	uio.uio_offset = 0;
685 
686 	VOP_LEASE(fvp, td, cred, LEASE_READ);
687 	VOP_LEASE(tvp, td, cred, LEASE_WRITE);
688 
689 	buf = malloc(MAXBSIZE, M_TEMP, M_WAITOK);
690 
691 	/* ugly loop follows... */
692 	do {
693 		off_t offset = uio.uio_offset;
694 		int count;
695 		int bufoffset;
696 
697 		/*
698 		 * Setup for big read.
699 		 */
700 		uio.uio_iov = &iov;
701 		uio.uio_iovcnt = 1;
702 		iov.iov_base = buf;
703 		iov.iov_len = MAXBSIZE;
704 		uio.uio_resid = iov.iov_len;
705 		uio.uio_rw = UIO_READ;
706 
707 		if ((error = VOP_READ(fvp, &uio, 0, cred)) != 0)
708 			break;
709 
710 		/*
711 		 * Get bytes read, handle read eof case and setup for
712 		 * write loop.
713 		 */
714 		if ((count = MAXBSIZE - uio.uio_resid) == 0)
715 			break;
716 		bufoffset = 0;
717 
718 		/*
719 		 * Write until an error occurs or our buffer has been
720 		 * exhausted, then update the offset for the next read.
721 		 */
722 		while (bufoffset < count) {
723 			uio.uio_iov = &iov;
724 			uio.uio_iovcnt = 1;
725 			iov.iov_base = buf + bufoffset;
726 			iov.iov_len = count - bufoffset;
727 			uio.uio_offset = offset + bufoffset;
728 			uio.uio_rw = UIO_WRITE;
729 			uio.uio_resid = iov.iov_len;
730 
731 			if ((error = VOP_WRITE(tvp, &uio, 0, cred)) != 0)
732 				break;
733 			bufoffset += (count - bufoffset) - uio.uio_resid;
734 		}
735 		uio.uio_offset = offset + bufoffset;
736 	} while (error == 0);
737 
738 	free(buf, M_TEMP);
739 	return (error);
740 }
741 
742 /*
743  *
744  * un's vnode is assumed to be locked on entry and remains locked on exit.
745  */
746 
747 int
748 union_copyup(un, docopy, cred, td)
749 	struct union_node *un;
750 	int docopy;
751 	struct ucred *cred;
752 	struct thread *td;
753 {
754 	int error;
755 	struct mount *mp;
756 	struct vnode *lvp, *uvp;
757 
758 	/*
759 	 * If the user does not have read permission, the vnode should not
760 	 * be copied to upper layer.
761 	 */
762 	vn_lock(un->un_lowervp, LK_EXCLUSIVE | LK_RETRY, td);
763 	error = VOP_ACCESS(un->un_lowervp, VREAD, cred, td);
764 	VOP_UNLOCK(un->un_lowervp, 0, td);
765 	if (error)
766 		return (error);
767 
768 	if ((error = vn_start_write(un->un_dirvp, &mp, V_WAIT | PCATCH)) != 0)
769 		return (error);
770 	if ((error = union_vn_create(&uvp, un, td)) != 0) {
771 		vn_finished_write(mp);
772 		return (error);
773 	}
774 
775 	lvp = un->un_lowervp;
776 
777 	KASSERT(vrefcnt(uvp) > 0, ("copy: uvp refcount 0: %d", vrefcnt(uvp)));
778 	if (docopy) {
779 		/*
780 		 * XX - should not ignore errors
781 		 * from VOP_CLOSE()
782 		 */
783 		vn_lock(lvp, LK_EXCLUSIVE | LK_RETRY, td);
784 		error = VOP_OPEN(lvp, FREAD, cred, td, -1);
785 		if (error == 0) {
786 			error = union_copyfile(lvp, uvp, cred, td);
787 			VOP_UNLOCK(lvp, 0, td);
788 			(void) VOP_CLOSE(lvp, FREAD, cred, td);
789 		}
790 		if (error == 0)
791 			UDEBUG(("union: copied up %s\n", un->un_path));
792 
793 	}
794 	VOP_UNLOCK(uvp, 0, td);
795 	vn_finished_write(mp);
796 	union_newupper(un, uvp);
797 	KASSERT(vrefcnt(uvp) > 0, ("copy: uvp refcount 0: %d", vrefcnt(uvp)));
798 	union_vn_close(uvp, FWRITE, cred, td);
799 	KASSERT(vrefcnt(uvp) > 0, ("copy: uvp refcount 0: %d", vrefcnt(uvp)));
800 	/*
801 	 * Subsequent IOs will go to the top layer, so
802 	 * call close on the lower vnode and open on the
803 	 * upper vnode to ensure that the filesystem keeps
804 	 * its references counts right.  This doesn't do
805 	 * the right thing with (cred) and (FREAD) though.
806 	 * Ignoring error returns is not right, either.
807 	 */
808 	if (error == 0) {
809 		int i;
810 
811 		for (i = 0; i < un->un_openl; i++) {
812 			(void) VOP_CLOSE(lvp, FREAD, cred, td);
813 			(void) VOP_OPEN(uvp, FREAD, cred, td, -1);
814 		}
815 		un->un_openl = 0;
816 	}
817 
818 	return (error);
819 
820 }
821 
822 /*
823  *	union_relookup:
824  *
825  *	dvp should be locked on entry and will be locked on return.  No
826  *	net change in the ref count will occur.
827  *
828  *	If an error is returned, *vpp will be invalid, otherwise it
829  *	will hold a locked, referenced vnode.  If *vpp == dvp then
830  *	remember that only one exclusive lock is held.
831  */
832 
833 static int
834 union_relookup(um, dvp, vpp, cnp, cn, path, pathlen)
835 	struct union_mount *um;
836 	struct vnode *dvp;
837 	struct vnode **vpp;
838 	struct componentname *cnp;
839 	struct componentname *cn;
840 	char *path;
841 	int pathlen;
842 {
843 	int error;
844 
845 	/*
846 	 * A new componentname structure must be faked up because
847 	 * there is no way to know where the upper level cnp came
848 	 * from or what it is being used for.  This must duplicate
849 	 * some of the work done by NDINIT(), some of the work done
850 	 * by namei(), some of the work done by lookup() and some of
851 	 * the work done by VOP_LOOKUP() when given a CREATE flag.
852 	 * Conclusion: Horrible.
853 	 */
854 	cn->cn_namelen = pathlen;
855 	cn->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
856 	bcopy(path, cn->cn_pnbuf, cn->cn_namelen);
857 	cn->cn_pnbuf[cn->cn_namelen] = '\0';
858 
859 	cn->cn_nameiop = CREATE;
860 	cn->cn_flags = (LOCKPARENT|LOCKLEAF|HASBUF|SAVENAME|ISLASTCN);
861 	cn->cn_thread = cnp->cn_thread;
862 	if (um->um_op == UNMNT_ABOVE)
863 		cn->cn_cred = cnp->cn_cred;
864 	else
865 		cn->cn_cred = um->um_cred;
866 	cn->cn_nameptr = cn->cn_pnbuf;
867 	cn->cn_consume = cnp->cn_consume;
868 
869 	VREF(dvp);
870 	VOP_UNLOCK(dvp, 0, cnp->cn_thread);
871 
872 	/*
873 	 * Pass dvp unlocked and referenced on call to relookup().
874 	 *
875 	 * If an error occurs, dvp will be returned unlocked and dereferenced.
876 	 */
877 
878 	if ((error = relookup(dvp, vpp, cn)) != 0) {
879 		vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY, cnp->cn_thread);
880 		return(error);
881 	}
882 
883 	/*
884 	 * If no error occurs, dvp will be returned locked with the reference
885 	 * left as before, and vpp will be returned referenced and locked.
886 	 *
887 	 * We want to return with dvp as it was passed to us, so we get
888 	 * rid of our reference.
889 	 */
890 	vrele(dvp);
891 	return (0);
892 }
893 
894 /*
895  * Create a shadow directory in the upper layer.
896  * The new vnode is returned locked.
897  *
898  * (um) points to the union mount structure for access to the
899  * the mounting process's credentials.
900  * (dvp) is the directory in which to create the shadow directory,
901  * It is locked (but not ref'd) on entry and return.
902  * (cnp) is the component name to be created.
903  * (vpp) is the returned newly created shadow directory, which
904  * is returned locked and ref'd
905  */
906 int
907 union_mkshadow(um, dvp, cnp, vpp)
908 	struct union_mount *um;
909 	struct vnode *dvp;
910 	struct componentname *cnp;
911 	struct vnode **vpp;
912 {
913 	int error;
914 	struct vattr va;
915 	struct thread *td = cnp->cn_thread;
916 	struct componentname cn;
917 	struct mount *mp;
918 
919 	if ((error = vn_start_write(dvp, &mp, V_WAIT | PCATCH)) != 0)
920 		return (error);
921 	if ((error = union_relookup(um, dvp, vpp, cnp, &cn,
922 			cnp->cn_nameptr, cnp->cn_namelen)) != 0) {
923 		vn_finished_write(mp);
924 		return (error);
925 	}
926 
927 	if (*vpp) {
928 		if (cn.cn_flags & HASBUF) {
929 			uma_zfree(namei_zone, cn.cn_pnbuf);
930 			cn.cn_flags &= ~HASBUF;
931 		}
932 		if (dvp == *vpp)
933 			vrele(*vpp);
934 		else
935 			vput(*vpp);
936 		vn_finished_write(mp);
937 		*vpp = NULLVP;
938 		return (EEXIST);
939 	}
940 
941 	/*
942 	 * Policy: when creating the shadow directory in the
943 	 * upper layer, create it owned by the user who did
944 	 * the mount, group from parent directory, and mode
945 	 * 777 modified by umask (ie mostly identical to the
946 	 * mkdir syscall).  (jsp, kb)
947 	 */
948 
949 	VATTR_NULL(&va);
950 	va.va_type = VDIR;
951 	va.va_mode = um->um_cmode;
952 
953 	/* VOP_LEASE: dvp is locked */
954 	VOP_LEASE(dvp, td, cn.cn_cred, LEASE_WRITE);
955 
956 	error = VOP_MKDIR(dvp, vpp, &cn, &va);
957 	if (cn.cn_flags & HASBUF) {
958 		uma_zfree(namei_zone, cn.cn_pnbuf);
959 		cn.cn_flags &= ~HASBUF;
960 	}
961 	/*vput(dvp);*/
962 	vn_finished_write(mp);
963 	return (error);
964 }
965 
966 /*
967  * Create a whiteout entry in the upper layer.
968  *
969  * (um) points to the union mount structure for access to the
970  * the mounting process's credentials.
971  * (dvp) is the directory in which to create the whiteout.
972  * It is locked on entry and return.
973  * (cnp) is the component name to be created.
974  */
975 int
976 union_mkwhiteout(um, dvp, cnp, path)
977 	struct union_mount *um;
978 	struct vnode *dvp;
979 	struct componentname *cnp;
980 	char *path;
981 {
982 	int error;
983 	struct thread *td = cnp->cn_thread;
984 	struct vnode *wvp;
985 	struct componentname cn;
986 	struct mount *mp;
987 
988 	if ((error = vn_start_write(dvp, &mp, V_WAIT | PCATCH)) != 0)
989 		return (error);
990 	error = union_relookup(um, dvp, &wvp, cnp, &cn, path, strlen(path));
991 	if (error) {
992 		vn_finished_write(mp);
993 		return (error);
994 	}
995 
996 	if (wvp) {
997 		if (cn.cn_flags & HASBUF) {
998 			uma_zfree(namei_zone, cn.cn_pnbuf);
999 			cn.cn_flags &= ~HASBUF;
1000 		}
1001 		if (wvp == dvp)
1002 			vrele(wvp);
1003 		else
1004 			vput(wvp);
1005 		vn_finished_write(mp);
1006 		return (EEXIST);
1007 	}
1008 
1009 	/* VOP_LEASE: dvp is locked */
1010 	VOP_LEASE(dvp, td, td->td_ucred, LEASE_WRITE);
1011 
1012 	error = VOP_WHITEOUT(dvp, &cn, CREATE);
1013 	if (cn.cn_flags & HASBUF) {
1014 		uma_zfree(namei_zone, cn.cn_pnbuf);
1015 		cn.cn_flags &= ~HASBUF;
1016 	}
1017 	vn_finished_write(mp);
1018 	return (error);
1019 }
1020 
1021 /*
1022  * union_vn_create: creates and opens a new shadow file
1023  * on the upper union layer.  This function is similar
1024  * in spirit to calling vn_open() but it avoids calling namei().
1025  * The problem with calling namei() is that a) it locks too many
1026  * things, and b) it doesn't start at the "right" directory,
1027  * whereas relookup() is told where to start.
1028  *
1029  * On entry, the vnode associated with un is locked.  It remains locked
1030  * on return.
1031  *
1032  * If no error occurs, *vpp contains a locked referenced vnode for your
1033  * use.  If an error occurs *vpp iis undefined.
1034  */
1035 static int
1036 union_vn_create(vpp, un, td)
1037 	struct vnode **vpp;
1038 	struct union_node *un;
1039 	struct thread *td;
1040 {
1041 	struct vnode *vp;
1042 	struct ucred *cred = td->td_ucred;
1043 	struct vattr vat;
1044 	struct vattr *vap = &vat;
1045 	int fmode = FFLAGS(O_WRONLY|O_CREAT|O_TRUNC|O_EXCL);
1046 	int error;
1047 	int cmode;
1048 	struct componentname cn;
1049 
1050 	*vpp = NULLVP;
1051 	FILEDESC_LOCK_FAST(td->td_proc->p_fd);
1052 	cmode = UN_FILEMODE & ~td->td_proc->p_fd->fd_cmask;
1053 	FILEDESC_UNLOCK_FAST(td->td_proc->p_fd);
1054 
1055 	/*
1056 	 * Build a new componentname structure (for the same
1057 	 * reasons outlines in union_mkshadow()).
1058 	 * The difference here is that the file is owned by
1059 	 * the current user, rather than by the person who
1060 	 * did the mount, since the current user needs to be
1061 	 * able to write the file (that's why it is being
1062 	 * copied in the first place).
1063 	 */
1064 	cn.cn_namelen = strlen(un->un_path);
1065 	cn.cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
1066 	bcopy(un->un_path, cn.cn_pnbuf, cn.cn_namelen+1);
1067 	cn.cn_nameiop = CREATE;
1068 	cn.cn_flags = (LOCKPARENT|LOCKLEAF|HASBUF|SAVENAME|ISLASTCN);
1069 	cn.cn_thread = td;
1070 	cn.cn_cred = td->td_ucred;
1071 	cn.cn_nameptr = cn.cn_pnbuf;
1072 	cn.cn_consume = 0;
1073 
1074 	/*
1075 	 * Pass dvp unlocked and referenced on call to relookup().
1076 	 *
1077 	 * If an error occurs, dvp will be returned unlocked and dereferenced.
1078 	 */
1079 	VREF(un->un_dirvp);
1080 	error = relookup(un->un_dirvp, &vp, &cn);
1081 	if (error)
1082 		return (error);
1083 
1084 	/*
1085 	 * If no error occurs, dvp will be returned locked with the reference
1086 	 * left as before, and vpp will be returned referenced and locked.
1087 	 */
1088 	if (vp) {
1089 		vput(un->un_dirvp);
1090 		if (cn.cn_flags & HASBUF) {
1091 			uma_zfree(namei_zone, cn.cn_pnbuf);
1092 			cn.cn_flags &= ~HASBUF;
1093 		}
1094 		if (vp == un->un_dirvp)
1095 			vrele(vp);
1096 		else
1097 			vput(vp);
1098 		return (EEXIST);
1099 	}
1100 
1101 	/*
1102 	 * Good - there was no race to create the file
1103 	 * so go ahead and create it.  The permissions
1104 	 * on the file will be 0666 modified by the
1105 	 * current user's umask.  Access to the file, while
1106 	 * it is unioned, will require access to the top *and*
1107 	 * bottom files.  Access when not unioned will simply
1108 	 * require access to the top-level file.
1109 	 * TODO: confirm choice of access permissions.
1110 	 */
1111 	VATTR_NULL(vap);
1112 	vap->va_type = VREG;
1113 	vap->va_mode = cmode;
1114 	VOP_LEASE(un->un_dirvp, td, cred, LEASE_WRITE);
1115 	error = VOP_CREATE(un->un_dirvp, &vp, &cn, vap);
1116 	if (cn.cn_flags & HASBUF) {
1117 		uma_zfree(namei_zone, cn.cn_pnbuf);
1118 		cn.cn_flags &= ~HASBUF;
1119 	}
1120 	vput(un->un_dirvp);
1121 	if (error)
1122 		return (error);
1123 
1124 	error = VOP_OPEN(vp, fmode, cred, td, -1);
1125 	if (error) {
1126 		vput(vp);
1127 		return (error);
1128 	}
1129 	vp->v_writecount++;
1130 	*vpp = vp;
1131 	return (0);
1132 }
1133 
1134 static int
1135 union_vn_close(vp, fmode, cred, td)
1136 	struct vnode *vp;
1137 	int fmode;
1138 	struct ucred *cred;
1139 	struct thread *td;
1140 {
1141 
1142 	if (fmode & FWRITE)
1143 		--vp->v_writecount;
1144 	return (VOP_CLOSE(vp, fmode, cred, td));
1145 }
1146 
1147 /*
1148  *	union_removed_upper:
1149  *
1150  *	An upper-only file/directory has been removed; un-cache it so
1151  *	that unionfs vnode gets reclaimed and the last uppervp reference
1152  *	disappears.
1153  *
1154  *	Called with union_node unlocked.
1155  */
1156 
1157 void
1158 union_removed_upper(un)
1159 	struct union_node *un;
1160 {
1161 	if (un->un_flags & UN_CACHED) {
1162 		int hash = UNION_HASH(un->un_uppervp, un->un_lowervp);
1163 
1164 		while (union_list_lock(hash))
1165 			continue;
1166 		un->un_flags &= ~UN_CACHED;
1167 		LIST_REMOVE(un, un_cache);
1168 		union_list_unlock(hash);
1169 	}
1170 }
1171 
1172 /*
1173  * Determine whether a whiteout is needed
1174  * during a remove/rmdir operation.
1175  */
1176 int
1177 union_dowhiteout(un, cred, td)
1178 	struct union_node *un;
1179 	struct ucred *cred;
1180 	struct thread *td;
1181 {
1182 	struct vattr va;
1183 
1184 	if (un->un_lowervp != NULLVP)
1185 		return (1);
1186 
1187 	if (VOP_GETATTR(un->un_uppervp, &va, cred, td) == 0 &&
1188 	    (va.va_flags & OPAQUE))
1189 		return (1);
1190 
1191 	return (0);
1192 }
1193 
1194 static void
1195 union_dircache_r(vp, vppp, cntp)
1196 	struct vnode *vp;
1197 	struct vnode ***vppp;
1198 	int *cntp;
1199 {
1200 	struct union_node *un;
1201 
1202 	if (vp->v_op != &union_vnodeops) {
1203 		if (vppp) {
1204 			VREF(vp);
1205 			*(*vppp)++ = vp;
1206 			if (--(*cntp) == 0)
1207 				panic("union: dircache table too small");
1208 		} else {
1209 			(*cntp)++;
1210 		}
1211 	} else {
1212 		un = VTOUNION(vp);
1213 		if (un->un_uppervp != NULLVP)
1214 			union_dircache_r(un->un_uppervp, vppp, cntp);
1215 		if (un->un_lowervp != NULLVP)
1216 			union_dircache_r(un->un_lowervp, vppp, cntp);
1217 	}
1218 }
1219 
1220 struct vnode *
1221 union_dircache_get(vp, td)
1222 	struct vnode *vp;
1223 	struct thread *td;
1224 {
1225 	int cnt;
1226 	struct vnode *nvp;
1227 	struct vnode **vpp;
1228 	struct vnode **dircache, **newdircache;
1229 	struct union_node *un;
1230 	int error;
1231 
1232 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1233 	un = VTOUNION(vp);
1234 	dircache = un->un_dircache;
1235 	newdircache = NULL;
1236 
1237 	nvp = NULLVP;
1238 
1239 	if (dircache == NULL) {
1240 		cnt = 0;
1241 		union_dircache_r(vp, 0, &cnt);
1242 		cnt++;
1243 		newdircache = dircache = malloc(cnt * sizeof(struct vnode *),
1244 						M_UNDCACHE, M_WAITOK);
1245 		vpp = dircache;
1246 		union_dircache_r(vp, &vpp, &cnt);
1247 		*vpp = NULLVP;
1248 		vpp = dircache + 1;
1249 	} else {
1250 		vpp = dircache;
1251 		do {
1252 			if (*vpp++ == un->un_uppervp)
1253 				break;
1254 		} while (*vpp != NULLVP);
1255 	}
1256 
1257 	if (*vpp == NULLVP)
1258 		goto out;
1259 
1260 	/*vn_lock(*vpp, LK_EXCLUSIVE | LK_RETRY, td);*/
1261 	UDEBUG(("ALLOCVP-3 %p ref %d\n", *vpp, (*vpp ? vrefcnt(*vpp) : -99)));
1262 	VREF(*vpp);
1263 	error = union_allocvp(&nvp, vp->v_mount, NULLVP, NULLVP, NULL, *vpp, NULLVP, 0);
1264 	UDEBUG(("ALLOCVP-3B %p ref %d\n", nvp, (*vpp ? vrefcnt(*vpp) : -99)));
1265 	if (error)
1266 		goto out;
1267 
1268 	un->un_dircache = NULL;
1269 	VTOUNION(nvp)->un_dircache = dircache;
1270 	newdircache = NULL;
1271 
1272 out:
1273 	/*
1274 	 * If we allocated a new dircache and couldn't attach
1275 	 * it to a new vp, free the resources we allocated.
1276 	 */
1277 	if (newdircache) {
1278 		for (vpp = newdircache; *vpp != NULLVP; vpp++)
1279 			vrele(*vpp);
1280 		free(newdircache, M_UNDCACHE);
1281 	}
1282 
1283 	VOP_UNLOCK(vp, 0, td);
1284 	return (nvp);
1285 }
1286 
1287 void
1288 union_dircache_free(struct union_node *un)
1289 {
1290 	struct vnode **vpp;
1291 
1292 	for (vpp = un->un_dircache; *vpp != NULLVP; vpp++)
1293 		vrele(*vpp);
1294 	free(un->un_dircache, M_UNDCACHE);
1295 	un->un_dircache = NULL;
1296 }
1297 
1298 /*
1299  * Module glue to remove #ifdef UNION from vfs_syscalls.c
1300  */
1301 static int
1302 union_dircheck(struct thread *td, struct vnode **vp, struct file *fp)
1303 {
1304 	int error = 0;
1305 
1306 	if ((*vp)->v_op == &union_vnodeops) {
1307 		struct vnode *lvp;
1308 
1309 		lvp = union_dircache_get(*vp, td);
1310 		if (lvp != NULLVP) {
1311 			struct vattr va;
1312 
1313 			/*
1314 			 * If the directory is opaque,
1315 			 * then don't show lower entries
1316 			 */
1317 			error = VOP_GETATTR(*vp, &va, fp->f_cred, td);
1318 			if (va.va_flags & OPAQUE) {
1319 				vput(lvp);
1320 				lvp = NULLVP;
1321 			}
1322 		}
1323 
1324 		if (lvp != NULLVP) {
1325 			error = VOP_OPEN(lvp, FREAD, fp->f_cred, td, -1);
1326 			if (error) {
1327 				vput(lvp);
1328 				return (error);
1329 			}
1330 			VOP_UNLOCK(lvp, 0, td);
1331 			FILE_LOCK(fp);
1332 			fp->f_vnode = lvp;
1333 			fp->f_data = lvp;
1334 			fp->f_offset = 0;
1335 			FILE_UNLOCK(fp);
1336 			error = vn_close(*vp, FREAD, fp->f_cred, td);
1337 			if (error)
1338 				return (error);
1339 			*vp = lvp;
1340 			return -1;	/* goto unionread */
1341 		}
1342 	}
1343 	return error;
1344 }
1345 
1346 static int
1347 union_modevent(module_t mod, int type, void *data)
1348 {
1349 	switch (type) {
1350 	case MOD_LOAD:
1351 		union_dircheckp = union_dircheck;
1352 		break;
1353 	case MOD_UNLOAD:
1354 		union_dircheckp = NULL;
1355 		break;
1356 	default:
1357 		return EOPNOTSUPP;
1358 		break;
1359 	}
1360 	return 0;
1361 }
1362 
1363 static moduledata_t union_mod = {
1364 	"union_dircheck",
1365 	union_modevent,
1366 	NULL
1367 };
1368 
1369 DECLARE_MODULE(union_dircheck, union_mod, SI_SUB_VFS, SI_ORDER_ANY);
1370