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