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