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