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