kernel - Performance tuning
[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                                 vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
432                                 vrele(dvp);
433                         } else {
434                                 /*
435                                  * our new un is under dvp
436                                  */
437                                 error = vn_lock(un->un_vnode, LK_EXCLUSIVE);
438                         }
439                 } else if (dvp == NULLVP) {
440                         /*
441                          * dvp is NULL, we need to lock un.
442                          */
443                         error = vn_lock(un->un_vnode, LK_EXCLUSIVE);
444                 } else {
445                         /*
446                          * dvp == un->un_vnode, we are already locked.
447                          */
448                         error = 0;
449                 }
450
451                 if (error)
452                         goto loop;
453
454                 /*
455                  * At this point, the union_node is locked and referenced.
456                  *
457                  * uppervp is locked and referenced or NULL, lowervp is
458                  * referenced or NULL.
459                  */
460                 UDEBUG(("Modify existing un %p vn %p upper %p(refs %d) -> %p(refs %d)\n",
461                         un, un->un_vnode, un->un_uppervp, 
462                         (un->un_uppervp ? VREFCNT(un->un_uppervp) : -99),
463                         uppervp,
464                         (uppervp ? VREFCNT(uppervp) : -99)
465                 ));
466
467                 if (uppervp != un->un_uppervp) {
468                         KASSERT(uppervp == NULL || VREFCNT(uppervp) > 0,
469                                 ("union_allocvp: too few refs %d (at least 1 "
470                                  "required) on uppervp",
471                                 VREFCNT(uppervp)));
472                         union_newupper(un, uppervp);
473                 } else if (uppervp) {
474                         KASSERT(VREFCNT(uppervp) > 1,
475                                 ("union_allocvp: too few refs %d (at least "
476                                  "2 required) on uppervp",
477                                  VREFCNT(uppervp)));
478                         vrele(uppervp);
479                 }
480
481                 /*
482                  * Save information about the lower layer.
483                  * This needs to keep track of pathname
484                  * and directory information which union_vn_create
485                  * might need.
486                  */
487                 if (lowervp != un->un_lowervp) {
488                         union_newlower(un, lowervp);
489                         if (cnp && (lowervp != NULLVP)) {
490                                 un->un_path = malloc(cnp->cn_namelen+1,
491                                                 M_TEMP, M_WAITOK);
492                                 bcopy(cnp->cn_nameptr, un->un_path,
493                                                 cnp->cn_namelen);
494                                 un->un_path[cnp->cn_namelen] = '\0';
495                         }
496                 } else if (lowervp) {
497                         vrele(lowervp);
498                 }
499
500                 /*
501                  * and upperdvp
502                  */
503                 if (upperdvp != un->un_dirvp) {
504                         if (un->un_dirvp)
505                                 vrele(un->un_dirvp);
506                         un->un_dirvp = upperdvp;
507                 } else if (upperdvp) {
508                         vrele(upperdvp);
509                 }
510
511                 *vpp = UNIONTOV(un);
512                 return (0);
513         }
514
515         if (docache) {
516                 /*
517                  * otherwise lock the vp list while we call getnewvnode
518                  * since that can block.
519                  */ 
520                 hash = UNION_HASH(uppervp, lowervp);
521
522                 if (union_list_lock(hash))
523                         goto loop;
524         }
525
526         /*
527          * Create new node rather then replace old node
528          */
529
530         error = getnewvnode(VT_UNION, mp, vpp, 0, 0);
531         if (error) {
532                 /*
533                  * If an error occurs clear out vnodes.
534                  */
535                 if (lowervp)
536                         vrele(lowervp);
537                 if (uppervp) 
538                         vrele(uppervp);
539                 if (upperdvp)
540                         vrele(upperdvp);
541                 *vpp = NULL;
542                 goto out;
543         }
544
545         (*vpp)->v_data = kmalloc(sizeof(struct union_node), M_TEMP, M_WAITOK);
546
547         vsetflags(*vpp, vflag);
548         if (uppervp)
549                 (*vpp)->v_type = uppervp->v_type;
550         else
551                 (*vpp)->v_type = lowervp->v_type;
552
553         un = VTOUNION(*vpp);
554         bzero(un, sizeof(*un));
555
556         un->un_vnode = *vpp;
557         un->un_uppervp = uppervp;
558         un->un_uppersz = VNOVAL;
559         un->un_lowervp = lowervp;
560         un->un_lowersz = VNOVAL;
561         un->un_dirvp = upperdvp;
562         un->un_pvp = dvp;               /* only parent dir in new allocation */
563         if (dvp != NULLVP)
564                 vref(dvp);
565         un->un_dircache = 0;
566         un->un_openl = 0;
567
568         if (cnp && (lowervp != NULLVP)) {
569                 un->un_path = kmalloc(cnp->cn_namelen+1, M_TEMP, M_WAITOK);
570                 bcopy(cnp->cn_nameptr, un->un_path, cnp->cn_namelen);
571                 un->un_path[cnp->cn_namelen] = '\0';
572         } else {
573                 un->un_path = 0;
574                 un->un_dirvp = NULL;
575         }
576
577         if (docache) {
578                 LIST_INSERT_HEAD(&unhead[hash], un, un_cache);
579                 un->un_flags |= UN_CACHED;
580         }
581
582         /* 
583          * locked refd vpp is returned
584          */
585
586 out:
587         if (docache)
588                 union_list_unlock(hash);
589
590         return (error);
591 }
592
593 int
594 union_freevp(struct vnode *vp)
595 {
596         struct union_node *un = VTOUNION(vp);
597
598         vp->v_data = NULL;
599         if (un->un_flags & UN_CACHED) {
600                 un->un_flags &= ~UN_CACHED;
601                 LIST_REMOVE(un, un_cache);
602         }
603         if (un->un_pvp != NULLVP) {
604                 vrele(un->un_pvp);
605                 un->un_pvp = NULL;
606         }
607         if (un->un_uppervp != NULLVP) {
608                 vrele(un->un_uppervp);
609                 un->un_uppervp = NULL;
610         }
611         if (un->un_lowervp != NULLVP) {
612                 vrele(un->un_lowervp);
613                 un->un_lowervp = NULL;
614         }
615         if (un->un_dirvp != NULLVP) {
616                 vrele(un->un_dirvp);
617                 un->un_dirvp = NULL;
618         }
619         if (un->un_path) {
620                 kfree(un->un_path, M_TEMP);
621                 un->un_path = NULL;
622         }
623         kfree(un, M_TEMP);
624         return (0);
625 }
626
627 /*
628  * copyfile.  copy the vnode (fvp) to the vnode (tvp)
629  * using a sequence of reads and writes.  both (fvp)
630  * and (tvp) are locked on entry and exit.
631  *
632  * fvp and tvp are both exclusive locked on call, but their refcount's
633  * haven't been bumped at all.
634  */
635 static int
636 union_copyfile(struct vnode *fvp, struct vnode *tvp, struct ucred *cred,
637                struct thread *td)
638 {
639         char *buf;
640         struct uio uio;
641         struct iovec iov;
642         int error = 0;
643
644         /*
645          * strategy:
646          * allocate a buffer of size MAXBSIZE.
647          * loop doing reads and writes, keeping track
648          * of the current uio offset.
649          * give up at the first sign of trouble.
650          */
651
652         bzero(&uio, sizeof(uio));
653
654         uio.uio_td = td;
655         uio.uio_segflg = UIO_SYSSPACE;
656         uio.uio_offset = 0;
657
658         buf = kmalloc(MAXBSIZE, M_TEMP, M_WAITOK);
659
660         /* ugly loop follows... */
661         do {
662                 off_t offset = uio.uio_offset;
663                 int count;
664                 int bufoffset;
665
666                 /*
667                  * Setup for big read
668                  */
669                 uio.uio_iov = &iov;
670                 uio.uio_iovcnt = 1;
671                 iov.iov_base = buf;
672                 iov.iov_len = MAXBSIZE;
673                 uio.uio_resid = iov.iov_len;
674                 uio.uio_rw = UIO_READ;
675
676                 if ((error = VOP_READ(fvp, &uio, 0, cred)) != 0)
677                         break;
678
679                 /*
680                  * Get bytes read, handle read eof case and setup for
681                  * write loop
682                  */
683                 if ((count = MAXBSIZE - uio.uio_resid) == 0)
684                         break;
685                 bufoffset = 0;
686
687                 /*
688                  * Write until an error occurs or our buffer has been
689                  * exhausted, then update the offset for the next read.
690                  */
691                 while (bufoffset < count) {
692                         uio.uio_iov = &iov;
693                         uio.uio_iovcnt = 1;
694                         iov.iov_base = buf + bufoffset;
695                         iov.iov_len = count - bufoffset;
696                         uio.uio_offset = offset + bufoffset;
697                         uio.uio_rw = UIO_WRITE;
698                         uio.uio_resid = iov.iov_len;
699
700                         if ((error = VOP_WRITE(tvp, &uio, 0, cred)) != 0)
701                                 break;
702                         bufoffset += (count - bufoffset) - uio.uio_resid;
703                 }
704                 uio.uio_offset = offset + bufoffset;
705         } while (error == 0);
706
707         kfree(buf, M_TEMP);
708         return (error);
709 }
710
711 /*
712  *
713  * un's vnode is assumed to be locked on entry and remains locked on exit.
714  */
715
716 int
717 union_copyup(struct union_node *un, int docopy, struct ucred *cred,
718              struct thread *td)
719 {
720         int error;
721         struct vnode *lvp, *uvp;
722
723         /*
724          * If the user does not have read permission, the vnode should not
725          * be copied to upper layer.
726          */
727         vn_lock(un->un_lowervp, LK_EXCLUSIVE | LK_RETRY);
728         error = VOP_EACCESS(un->un_lowervp, VREAD, cred);
729         vn_unlock(un->un_lowervp);
730         if (error)
731                 return (error);
732
733         error = union_vn_create(&uvp, un, td);
734         if (error)
735                 return (error);
736
737         lvp = un->un_lowervp;
738
739         KASSERT(VREFCNT(uvp) > 0,
740                 ("copy: uvp refcount 0: %d", VREFCNT(uvp)));
741         if (docopy) {
742                 /*
743                  * XX - should not ignore errors
744                  * from VOP_CLOSE
745                  */
746                 vn_lock(lvp, LK_EXCLUSIVE | LK_RETRY);
747                 error = VOP_OPEN(lvp, FREAD, cred, NULL);
748                 if (error == 0) {
749                         error = union_copyfile(lvp, uvp, cred, td);
750                         (void) VOP_CLOSE(lvp, FREAD);
751                         vn_unlock(lvp);
752                 }
753                 if (error == 0)
754                         UDEBUG(("union: copied up %s\n", un->un_path));
755
756         }
757         vn_unlock(uvp);
758         union_newupper(un, uvp);
759         KASSERT(VREFCNT(uvp) > 0, ("copy: uvp refcount 0: %d", VREFCNT(uvp)));
760         union_vn_close(uvp, FWRITE, cred);
761         KASSERT(VREFCNT(uvp) > 0, ("copy: uvp refcount 0: %d", VREFCNT(uvp)));
762         /*
763          * Subsequent IOs will go to the top layer, so
764          * call close on the lower vnode and open on the
765          * upper vnode to ensure that the filesystem keeps
766          * its references counts right.  This doesn't do
767          * the right thing with (cred) and (FREAD) though.
768          * Ignoring error returns is not right, either.
769          */
770         if (error == 0) {
771                 int i;
772
773                 for (i = 0; i < un->un_openl; i++) {
774                         vn_lock(lvp, LK_EXCLUSIVE | LK_RETRY);
775                         VOP_CLOSE(lvp, FREAD);
776                         vn_unlock(lvp);
777                         vn_lock(uvp, LK_EXCLUSIVE | LK_RETRY);
778                         VOP_OPEN(uvp, FREAD, cred, NULL);
779                         vn_unlock(uvp);
780                 }
781                 un->un_openl = 0;
782         }
783
784         return (error);
785
786 }
787
788 /*
789  *      union_relookup:
790  *
791  *      dvp should be locked on entry and will be locked on return.  No
792  *      net change in the ref count will occur.
793  *
794  *      If an error is returned, *vpp will be invalid, otherwise it
795  *      will hold a locked, referenced vnode.  If *vpp == dvp then
796  *      remember that only one exclusive lock is held.
797  */
798
799 static int
800 union_relookup(struct union_mount *um, struct vnode *dvp, struct vnode **vpp,
801                struct componentname *cnp, struct componentname *cn, char *path,
802                int pathlen)
803 {
804         int error;
805
806         /*
807          * A new componentname structure must be faked up because
808          * there is no way to know where the upper level cnp came
809          * from or what it is being used for.  This must duplicate
810          * some of the work done by NDINIT, some of the work done
811          * by namei, some of the work done by lookup and some of
812          * the work done by VOP_LOOKUP when given a CREATE flag.
813          * Conclusion: Horrible.
814          */
815         cn->cn_namelen = pathlen;
816         cn->cn_nameptr = objcache_get(namei_oc, M_WAITOK);
817         bcopy(path, cn->cn_nameptr, cn->cn_namelen);
818         cn->cn_nameptr[cn->cn_namelen] = '\0';
819
820         cn->cn_nameiop = NAMEI_CREATE;
821         cn->cn_flags = CNP_LOCKPARENT;
822         cn->cn_td = cnp->cn_td;
823         if (um->um_op == UNMNT_ABOVE)
824                 cn->cn_cred = cnp->cn_cred;
825         else
826                 cn->cn_cred = um->um_cred;
827         cn->cn_consume = cnp->cn_consume;
828
829         vref(dvp);
830         vn_unlock(dvp);
831
832         /*
833          * Pass dvp unlocked and referenced on call to relookup().
834          *
835          * If an error occurs, dvp will be returned unlocked and dereferenced.
836          */
837
838         if ((error = relookup(dvp, vpp, cn)) != 0) {
839                 objcache_put(namei_oc, cn->cn_nameptr);
840                 vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
841                 return(error);
842         }
843         objcache_put(namei_oc, cn->cn_nameptr);
844
845         /*
846          * If no error occurs, dvp will be returned locked with the reference
847          * left as before, and vpp will be returned referenced and locked.
848          *
849          * We want to return with dvp as it was passed to us, so we get
850          * rid of our reference.
851          */
852         vrele(dvp);
853         return (0);
854 }
855
856 /*
857  * Create a shadow directory in the upper layer.
858  * The new vnode is returned locked.
859  *
860  * (um) points to the union mount structure for access to the
861  * the mounting process's credentials.
862  * (dvp) is the directory in which to create the shadow directory,
863  * it is locked (but not ref'd) on entry and return.
864  * (cnp) is the componentname to be created.
865  * (vpp) is the returned newly created shadow directory, which
866  * is returned locked and ref'd
867  */
868 int
869 union_mkshadow(struct union_mount *um, struct vnode *dvp,
870                struct componentname *cnp, struct vnode **vpp)
871 {
872         int error;
873         struct vattr va;
874         struct thread *td = cnp->cn_td;
875         struct componentname cn;
876
877         error = union_relookup(um, dvp, vpp, cnp, &cn,
878                         cnp->cn_nameptr, cnp->cn_namelen);
879         if (error)
880                 return (error);
881
882         if (*vpp) {
883                 if (dvp == *vpp)
884                         vrele(*vpp);
885                 else
886                         vput(*vpp);
887                 *vpp = NULLVP;
888                 return (EEXIST);
889         }
890
891         /*
892          * policy: when creating the shadow directory in the
893          * upper layer, create it owned by the user who did
894          * the mount, group from parent directory, and mode
895          * 777 modified by umask (ie mostly identical to the
896          * mkdir syscall).  (jsp, kb)
897          */
898
899         VATTR_NULL(&va);
900         va.va_type = VDIR;
901         va.va_mode = um->um_cmode;
902
903         error = VOP_MKDIR(dvp, vpp, &cn, &va);
904         /*vput(dvp);*/
905         return (error);
906 }
907
908 /*
909  * Create a whiteout entry in the upper layer.
910  *
911  * (um) points to the union mount structure for access to the
912  * the mounting process's credentials.
913  * (dvp) is the directory in which to create the whiteout.
914  * it is locked on entry and return.
915  * (cnp) is the componentname to be created.
916  */
917 int
918 union_mkwhiteout(struct union_mount *um, struct vnode *dvp,
919                  struct componentname *cnp, char *path)
920 {
921         int error;
922         struct thread *td = cnp->cn_td;
923         struct vnode *wvp;
924         struct componentname cn;
925
926         KKASSERT(td->td_proc);
927
928         error = union_relookup(um, dvp, &wvp, cnp, &cn, path, strlen(path));
929         if (error)
930                 return (error);
931
932         if (wvp) {
933                 if (wvp == dvp)
934                         vrele(wvp);
935                 else
936                         vput(wvp);
937                 return (EEXIST);
938         }
939
940         error = VOP_WHITEOUT(dvp, &cn, NAMEI_CREATE);
941         return (error);
942 }
943
944 /*
945  * union_vn_create: creates and opens a new shadow file
946  * on the upper union layer.  this function is similar
947  * in spirit to calling vn_open but it avoids calling namei().
948  * the problem with calling namei is that a) it locks too many
949  * things, and b) it doesn't start at the "right" directory,
950  * whereas relookup is told where to start.
951  *
952  * On entry, the vnode associated with un is locked.  It remains locked
953  * on return.
954  *
955  * If no error occurs, *vpp contains a locked referenced vnode for your
956  * use.  If an error occurs *vpp iis undefined.
957  */
958 static int
959 union_vn_create(struct vnode **vpp, struct union_node *un, struct thread *td)
960 {
961         struct vnode *vp;
962         struct ucred *cred;
963         struct vattr vat;
964         struct vattr *vap = &vat;
965         int fmode = FFLAGS(O_WRONLY|O_CREAT|O_TRUNC|O_EXCL);
966         int error;
967         int cmode;
968         struct componentname cn;
969
970         KKASSERT(td->td_proc);
971         cred = td->td_proc->p_ucred;
972         cmode = UN_FILEMODE & ~td->td_proc->p_fd->fd_cmask;
973
974         *vpp = NULLVP;
975
976         /*
977          * Build a new componentname structure (for the same
978          * reasons outlines in union_mkshadow).
979          * The difference here is that the file is owned by
980          * the current user, rather than by the person who
981          * did the mount, since the current user needs to be
982          * able to write the file (that's why it is being
983          * copied in the first place).
984          */
985         cn.cn_namelen = strlen(un->un_path);
986         cn.cn_nameptr = objcache_get(namei_oc, M_WAITOK);
987         bcopy(un->un_path, cn.cn_nameptr, cn.cn_namelen+1);
988         cn.cn_nameiop = NAMEI_CREATE;
989         cn.cn_flags = CNP_LOCKPARENT;
990         cn.cn_td = td;
991         cn.cn_cred = cred;
992         cn.cn_consume = 0;
993
994         /*
995          * Pass dvp unlocked and referenced on call to relookup().
996          *
997          * If an error occurs, dvp will be returned unlocked and dereferenced.
998          */
999         vref(un->un_dirvp);
1000         error = relookup(un->un_dirvp, &vp, &cn);
1001         objcache_put(namei_oc, cn.cn_nameptr);
1002         if (error)
1003                 return (error);
1004
1005         /*
1006          * If no error occurs, dvp will be returned locked with the reference
1007          * left as before, and vpp will be returned referenced and locked.
1008          */
1009         if (vp) {
1010                 vput(un->un_dirvp);
1011                 if (vp == un->un_dirvp)
1012                         vrele(vp);
1013                 else
1014                         vput(vp);
1015                 return (EEXIST);
1016         }
1017
1018         /*
1019          * Good - there was no race to create the file
1020          * so go ahead and create it.  The permissions
1021          * on the file will be 0666 modified by the
1022          * current user's umask.  Access to the file, while
1023          * it is unioned, will require access to the top *and*
1024          * bottom files.  Access when not unioned will simply
1025          * require access to the top-level file.
1026          * TODO: confirm choice of access permissions.
1027          */
1028         VATTR_NULL(vap);
1029         vap->va_type = VREG;
1030         vap->va_mode = cmode;
1031         error = VOP_CREATE(un->un_dirvp, &vp, &cn, vap);
1032         vput(un->un_dirvp);
1033         if (error)
1034                 return (error);
1035
1036         error = VOP_OPEN(vp, fmode, cred, NULL);
1037         if (error) {
1038                 vput(vp);
1039                 return (error);
1040         }
1041         *vpp = vp;
1042         return (0);
1043 }
1044
1045 static int
1046 union_vn_close(struct vnode *vp, int fmode, struct ucred *cred)
1047 {
1048         return (VOP_CLOSE(vp, fmode));
1049 }
1050
1051 #if 0
1052
1053 /*
1054  *      union_removed_upper:
1055  *
1056  *      called with union_node unlocked. XXX
1057  */
1058
1059 void
1060 union_removed_upper(struct union_node *un)
1061 {
1062         struct thread *td = curthread;  /* XXX */
1063         struct vnode **vpp;
1064
1065         /*
1066          * Do not set the uppervp to NULLVP.  If lowervp is NULLVP,
1067          * union node will have neither uppervp nor lowervp.  We remove
1068          * the union node from cache, so that it will not be referrenced.
1069          */
1070         union_newupper(un, NULLVP);
1071         if (un->un_dircache != 0) {
1072                 for (vpp = un->un_dircache; *vpp != NULLVP; vpp++)
1073                         vrele(*vpp);
1074                 kfree(un->un_dircache, M_TEMP);
1075                 un->un_dircache = 0;
1076         }
1077
1078         if (un->un_flags & UN_CACHED) {
1079                 un->un_flags &= ~UN_CACHED;
1080                 LIST_REMOVE(un, un_cache);
1081         }
1082 }
1083
1084 #endif
1085
1086 /*
1087  * determine whether a whiteout is needed
1088  * during a remove/rmdir operation.
1089  */
1090 int
1091 union_dowhiteout(struct union_node *un, struct ucred *cred, struct thread *td)
1092 {
1093         struct vattr va;
1094
1095         if (un->un_lowervp != NULLVP)
1096                 return (1);
1097
1098         if (VOP_GETATTR(un->un_uppervp, &va) == 0 &&
1099             (va.va_flags & OPAQUE))
1100                 return (1);
1101
1102         return (0);
1103 }
1104
1105 static void
1106 union_dircache_r(struct vnode *vp, struct vnode ***vppp, int *cntp)
1107 {
1108         struct union_node *un;
1109
1110         if (vp->v_tag != VT_UNION) {
1111                 if (vppp) {
1112                         vref(vp);
1113                         *(*vppp)++ = vp;
1114                         if (--(*cntp) == 0)
1115                                 panic("union: dircache table too small");
1116                 } else {
1117                         (*cntp)++;
1118                 }
1119
1120                 return;
1121         }
1122
1123         un = VTOUNION(vp);
1124         if (un->un_uppervp != NULLVP)
1125                 union_dircache_r(un->un_uppervp, vppp, cntp);
1126         if (un->un_lowervp != NULLVP)
1127                 union_dircache_r(un->un_lowervp, vppp, cntp);
1128 }
1129
1130 struct vnode *
1131 union_dircache(struct vnode *vp, struct thread *td)
1132 {
1133         int cnt;
1134         struct vnode *nvp;
1135         struct vnode **vpp;
1136         struct vnode **dircache;
1137         struct union_node *un;
1138         int error;
1139
1140         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1141         dircache = VTOUNION(vp)->un_dircache;
1142
1143         nvp = NULLVP;
1144
1145         if (dircache == NULL) {
1146                 cnt = 0;
1147                 union_dircache_r(vp, 0, &cnt);
1148                 cnt++;
1149                 dircache = malloc(cnt * sizeof(struct vnode *),
1150                                 M_TEMP, M_WAITOK);
1151                 vpp = dircache;
1152                 union_dircache_r(vp, &vpp, &cnt);
1153                 *vpp = NULLVP;
1154                 vpp = dircache + 1;
1155         } else {
1156                 vpp = dircache;
1157                 do {
1158                         if (*vpp++ == VTOUNION(vp)->un_uppervp)
1159                                 break;
1160                 } while (*vpp != NULLVP);
1161         }
1162
1163         if (*vpp == NULLVP)
1164                 goto out;
1165
1166         /*vn_lock(*vpp, LK_EXCLUSIVE | LK_RETRY);*/
1167         UDEBUG(("ALLOCVP-3 %p ref %08x\n",
1168                 *vpp, (*vpp ? (*vpp)->v_refcnt : -99)));
1169         vref(*vpp);
1170         error = union_allocvp(&nvp, vp->v_mount, NULLVP, NULLVP, NULL, *vpp, NULLVP, 0);
1171         UDEBUG(("ALLOCVP-3B %p ref %08x\n",
1172                 nvp, (*vpp ? (*vpp)->v_refcnt : -99)));
1173         if (error)
1174                 goto out;
1175
1176         VTOUNION(vp)->un_dircache = 0;
1177         un = VTOUNION(nvp);
1178         un->un_dircache = dircache;
1179
1180 out:
1181         vn_unlock(vp);
1182         return (nvp);
1183 }
1184
1185 /*
1186  * Guarentee coherency with the VM cache by invalidating any clean VM pages
1187  * associated with this write and updating any dirty VM pages.  Since our
1188  * vnode is locked, other processes will not be able to read the pages in
1189  * again until after our write completes.
1190  *
1191  * We also have to be coherent with reads, by flushing any pending dirty
1192  * pages prior to issuing the read.
1193  *
1194  * XXX this is somewhat of a hack at the moment.  To support this properly
1195  * we would have to be able to run VOP_READ and VOP_WRITE through the VM
1196  * cache.  Then we wouldn't need to worry about coherency.
1197  */
1198
1199 void 
1200 union_vm_coherency(struct vnode *vp, struct uio *uio, int cleanfls)
1201 {
1202         vm_object_t object;
1203         vm_pindex_t pstart;
1204         vm_pindex_t pend;
1205         int pgoff;
1206
1207         if ((object = vp->v_object) == NULL)
1208             return;
1209
1210         pgoff = uio->uio_offset & PAGE_MASK;
1211         pstart = uio->uio_offset / PAGE_SIZE;
1212         pend = pstart + (uio->uio_resid + pgoff + PAGE_MASK) / PAGE_SIZE;
1213
1214         vm_object_page_clean(object, pstart, pend, OBJPC_SYNC);
1215         if (cleanfls)
1216                 vm_object_page_remove(object, pstart, pend, TRUE);
1217 }
1218
1219 /*
1220  * Module glue to remove #ifdef UNION from vfs_syscalls.c
1221  */
1222 static int
1223 union_dircheck(struct thread *td, struct vnode **vp, struct file *fp)
1224 {
1225         int error = 0;
1226
1227         if ((*vp)->v_tag == VT_UNION) {
1228                 struct vnode *lvp;
1229
1230                 lvp = union_dircache(*vp, td);
1231                 if (lvp != NULLVP) {
1232                         struct vattr va;
1233
1234                         /*
1235                          * If the directory is opaque,
1236                          * then don't show lower entries
1237                          */
1238                         error = VOP_GETATTR(*vp, &va);
1239                         if (va.va_flags & OPAQUE) {
1240                                 vput(lvp);
1241                                 lvp = NULL;
1242                         }
1243                 }
1244
1245                 if (lvp != NULLVP) {
1246                         error = VOP_OPEN(lvp, FREAD, fp->f_cred, NULL);
1247                         if (error) {
1248                                 vput(lvp);
1249                                 return (error);
1250                         }
1251                         vn_unlock(lvp);
1252                         fp->f_data = lvp;
1253                         fp->f_offset = 0;
1254                         error = vn_close(*vp, FREAD);
1255                         if (error)
1256                                 return (error);
1257                         *vp = lvp;
1258                         return -1;      /* goto unionread */
1259                 }
1260         }
1261         return error;
1262 }
1263
1264 static int
1265 union_modevent(module_t mod, int type, void *data)
1266 {
1267         switch (type) {
1268         case MOD_LOAD:
1269                 union_dircheckp = union_dircheck;
1270                 break;
1271         case MOD_UNLOAD:
1272                 union_dircheckp = NULL;
1273                 break;
1274         default:
1275                 break;
1276         }
1277         return 0;
1278 }
1279
1280 static moduledata_t union_mod = {
1281         "union_dircheck",
1282         union_modevent,
1283         NULL
1284 };
1285
1286 DECLARE_MODULE(union_dircheck, union_mod, SI_SUB_VFS, SI_ORDER_ANY);