kernel - Implement shared namecache locks
[dragonfly.git] / sys / kern / vfs_nlookup.c
1 /*
2  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 /*
35  * nlookup() is the 'new' namei interface.  Rather then return directory and
36  * leaf vnodes (in various lock states) the new interface instead deals in
37  * namecache records.  Namecache records may represent both a positive or
38  * a negative hit.  The namespace is locked via the namecache record instead
39  * of via the vnode, and only the leaf namecache record (representing the
40  * filename) needs to be locked.
41  *
42  * This greatly improves filesystem parallelism and is a huge simplification
43  * of the API verses the old vnode locking / namei scheme.
44  *
45  * Filesystems must actively control the caching aspects of the namecache,
46  * and since namecache pointers are used as handles they are non-optional
47  * even for filesystems which do not generally wish to cache things.  It is
48  * intended that a separate cache coherency API will be constructed to handle
49  * these issues.
50  */
51
52 #include "opt_ktrace.h"
53
54 #include <sys/param.h>
55 #include <sys/systm.h>
56 #include <sys/kernel.h>
57 #include <sys/vnode.h>
58 #include <sys/mount.h>
59 #include <sys/filedesc.h>
60 #include <sys/proc.h>
61 #include <sys/namei.h>
62 #include <sys/nlookup.h>
63 #include <sys/malloc.h>
64 #include <sys/stat.h>
65 #include <sys/objcache.h>
66 #include <sys/file.h>
67
68 #ifdef KTRACE
69 #include <sys/ktrace.h>
70 #endif
71
72 static int naccess(struct nchandle *nch, int vmode, struct ucred *cred,
73                 int *stickyp);
74
75 /*
76  * Initialize a nlookup() structure, early error return for copyin faults
77  * or a degenerate empty string (which is not allowed).
78  *
79  * The first process proc0's credentials are used if the calling thread
80  * is not associated with a process context.
81  *
82  * MPSAFE
83  */
84 int
85 nlookup_init(struct nlookupdata *nd, 
86              const char *path, enum uio_seg seg, int flags)
87 {
88     size_t pathlen;
89     struct proc *p;
90     thread_t td;
91     int error;
92
93     td = curthread;
94     p = td->td_proc;
95
96     /*
97      * note: the pathlen set by copy*str() includes the terminating \0.
98      */
99     bzero(nd, sizeof(struct nlookupdata));
100     nd->nl_path = objcache_get(namei_oc, M_WAITOK);
101     nd->nl_flags |= NLC_HASBUF;
102     if (seg == UIO_SYSSPACE) 
103         error = copystr(path, nd->nl_path, MAXPATHLEN, &pathlen);
104     else
105         error = copyinstr(path, nd->nl_path, MAXPATHLEN, &pathlen);
106
107     /*
108      * Don't allow empty pathnames.
109      * POSIX.1 requirement: "" is not a vaild file name.
110      */
111     if (error == 0 && pathlen <= 1)
112         error = ENOENT;
113
114     if (error == 0) {
115         if (p && p->p_fd) {
116             cache_copy(&p->p_fd->fd_ncdir, &nd->nl_nch);
117             cache_copy(&p->p_fd->fd_nrdir, &nd->nl_rootnch);
118             if (p->p_fd->fd_njdir.ncp)
119                 cache_copy(&p->p_fd->fd_njdir, &nd->nl_jailnch);
120             nd->nl_cred = crhold(p->p_ucred);
121         } else {
122             cache_copy(&rootnch, &nd->nl_nch);
123             cache_copy(&nd->nl_nch, &nd->nl_rootnch);
124             cache_copy(&nd->nl_nch, &nd->nl_jailnch);
125             nd->nl_cred = crhold(proc0.p_ucred);
126         }
127         nd->nl_td = td;
128         nd->nl_flags |= flags;
129     } else {
130         nlookup_done(nd);
131     }
132     return(error);
133 }
134
135
136 /*
137  * nlookup_init() for "at" family of syscalls.
138  *
139  * Works similarly to nlookup_init() but if path is relative and fd is not
140  * AT_FDCWD, path is interpreted relative to the directory pointed to by fd.
141  * In this case, the file entry pointed to by fd is ref'ed and returned in
142  * *fpp. 
143  *
144  * If the call succeeds, nlookup_done_at() must be called to clean-up the nd
145  * and release the ref to the file entry.
146  */
147 int
148 nlookup_init_at(struct nlookupdata *nd, struct file **fpp, int fd, 
149                 const char *path, enum uio_seg seg, int flags)
150 {
151         struct thread *td = curthread;
152         struct proc *p = td->td_proc;
153         struct file* fp;
154         struct vnode *vp;
155         int error;
156
157         *fpp = NULL;
158
159         if  ((error = nlookup_init(nd, path, seg, flags)) != 0) {
160                 return (error);
161         }
162
163         if (nd->nl_path[0] != '/' && fd != AT_FDCWD) {
164                 if ((error = holdvnode(p->p_fd, fd, &fp)) != 0)
165                         goto done;
166                 vp = (struct vnode*)fp->f_data;
167                 if (vp->v_type != VDIR || fp->f_nchandle.ncp == NULL) {
168                         fdrop(fp);
169                         fp = NULL;
170                         error = ENOTDIR;
171                         goto done;
172                 }
173                 cache_drop(&nd->nl_nch);
174                 cache_copy(&fp->f_nchandle, &nd->nl_nch);
175                 *fpp = fp;
176         }
177
178
179 done:
180         if (error)
181                 nlookup_done(nd);
182         return (error);
183
184 }
185
186 /*
187  * This works similarly to nlookup_init() but does not assume a process
188  * context.  rootnch is always chosen for the root directory and the cred
189  * and starting directory are supplied in arguments.
190  */
191 int
192 nlookup_init_raw(struct nlookupdata *nd, 
193              const char *path, enum uio_seg seg, int flags,
194              struct ucred *cred, struct nchandle *ncstart)
195 {
196     size_t pathlen;
197     thread_t td;
198     int error;
199
200     td = curthread;
201
202     bzero(nd, sizeof(struct nlookupdata));
203     nd->nl_path = objcache_get(namei_oc, M_WAITOK);
204     nd->nl_flags |= NLC_HASBUF;
205     if (seg == UIO_SYSSPACE) 
206         error = copystr(path, nd->nl_path, MAXPATHLEN, &pathlen);
207     else
208         error = copyinstr(path, nd->nl_path, MAXPATHLEN, &pathlen);
209
210     /*
211      * Don't allow empty pathnames.
212      * POSIX.1 requirement: "" is not a vaild file name.
213      */
214     if (error == 0 && pathlen <= 1)
215         error = ENOENT;
216
217     if (error == 0) {
218         cache_copy(ncstart, &nd->nl_nch);
219         cache_copy(&rootnch, &nd->nl_rootnch);
220         cache_copy(&rootnch, &nd->nl_jailnch);
221         nd->nl_cred = crhold(cred);
222         nd->nl_td = td;
223         nd->nl_flags |= flags;
224     } else {
225         nlookup_done(nd);
226     }
227     return(error);
228 }
229
230 /*
231  * This works similarly to nlookup_init_raw() but does not rely
232  * on rootnch being initialized yet.
233  */
234 int
235 nlookup_init_root(struct nlookupdata *nd, 
236              const char *path, enum uio_seg seg, int flags,
237              struct ucred *cred, struct nchandle *ncstart,
238              struct nchandle *ncroot)
239 {
240     size_t pathlen;
241     thread_t td;
242     int error;
243
244     td = curthread;
245
246     bzero(nd, sizeof(struct nlookupdata));
247     nd->nl_path = objcache_get(namei_oc, M_WAITOK);
248     nd->nl_flags |= NLC_HASBUF;
249     if (seg == UIO_SYSSPACE) 
250         error = copystr(path, nd->nl_path, MAXPATHLEN, &pathlen);
251     else
252         error = copyinstr(path, nd->nl_path, MAXPATHLEN, &pathlen);
253
254     /*
255      * Don't allow empty pathnames.
256      * POSIX.1 requirement: "" is not a vaild file name.
257      */
258     if (error == 0 && pathlen <= 1)
259         error = ENOENT;
260
261     if (error == 0) {
262         cache_copy(ncstart, &nd->nl_nch);
263         cache_copy(ncroot, &nd->nl_rootnch);
264         cache_copy(ncroot, &nd->nl_jailnch);
265         nd->nl_cred = crhold(cred);
266         nd->nl_td = td;
267         nd->nl_flags |= flags;
268     } else {
269         nlookup_done(nd);
270     }
271     return(error);
272 }
273
274 /*
275  * Set a different credential; this credential will be used by future
276  * operations performed on nd.nl_open_vp and nlookupdata structure.
277  */
278 void
279 nlookup_set_cred(struct nlookupdata *nd, struct ucred *cred)
280 {
281         KKASSERT(nd->nl_cred != NULL);
282
283         if (nd->nl_cred != cred) {
284                 cred = crhold(cred);
285                 crfree(nd->nl_cred);
286                 nd->nl_cred = cred;
287         }
288 }
289
290 /*
291  * Cleanup a nlookupdata structure after we are through with it.  This may
292  * be called on any nlookupdata structure initialized with nlookup_init().
293  * Calling nlookup_done() is mandatory in all cases except where nlookup_init()
294  * returns an error, even if as a consumer you believe you have taken all
295  * dynamic elements out of the nlookupdata structure.
296  */
297 void
298 nlookup_done(struct nlookupdata *nd)
299 {
300     if (nd->nl_nch.ncp) {
301         if (nd->nl_flags & NLC_NCPISLOCKED) {
302             nd->nl_flags &= ~NLC_NCPISLOCKED;
303             cache_unlock(&nd->nl_nch);
304         }
305         cache_drop(&nd->nl_nch);        /* NULL's out the nch */
306     }
307     if (nd->nl_rootnch.ncp)
308         cache_drop(&nd->nl_rootnch);
309     if (nd->nl_jailnch.ncp)
310         cache_drop(&nd->nl_jailnch);
311     if ((nd->nl_flags & NLC_HASBUF) && nd->nl_path) {
312         objcache_put(namei_oc, nd->nl_path);
313         nd->nl_path = NULL;
314     }
315     if (nd->nl_cred) {
316         crfree(nd->nl_cred);
317         nd->nl_cred = NULL;
318     }
319     if (nd->nl_open_vp) {
320         if (nd->nl_flags & NLC_LOCKVP) {
321                 vn_unlock(nd->nl_open_vp);
322                 nd->nl_flags &= ~NLC_LOCKVP;
323         }
324         vn_close(nd->nl_open_vp, nd->nl_vp_fmode);
325         nd->nl_open_vp = NULL;
326     }
327     if (nd->nl_dvp) {
328         vrele(nd->nl_dvp);
329         nd->nl_dvp = NULL;
330     }
331     nd->nl_flags = 0;   /* clear remaining flags (just clear everything) */
332 }
333
334 /*
335  * Works similarly to nlookup_done() when nd initialized with
336  * nlookup_init_at().
337  */
338 void
339 nlookup_done_at(struct nlookupdata *nd, struct file *fp)
340 {
341         nlookup_done(nd);
342         if (fp != NULL)
343                 fdrop(fp);
344 }
345
346 void
347 nlookup_zero(struct nlookupdata *nd)
348 {
349         bzero(nd, sizeof(struct nlookupdata));
350 }
351
352 /*
353  * Simple all-in-one nlookup.  Returns a locked namecache structure or NULL
354  * if an error occured. 
355  *
356  * Note that the returned ncp is not checked for permissions, though VEXEC
357  * is checked on the directory path leading up to the result.  The caller
358  * must call naccess() to check the permissions of the returned leaf.
359  */
360 struct nchandle
361 nlookup_simple(const char *str, enum uio_seg seg,
362                int niflags, int *error)
363 {
364     struct nlookupdata nd;
365     struct nchandle nch;
366
367     *error = nlookup_init(&nd, str, seg, niflags);
368     if (*error == 0) {
369             if ((*error = nlookup(&nd)) == 0) {
370                     nch = nd.nl_nch;    /* keep hold ref from structure */
371                     cache_zero(&nd.nl_nch); /* and NULL out */
372             } else {
373                     cache_zero(&nch);
374             }
375             nlookup_done(&nd);
376     } else {
377             cache_zero(&nch);
378     }
379     return(nch);
380 }
381
382 /*
383  * Do a generic nlookup.  Note that the passed nd is not nlookup_done()'d
384  * on return, even if an error occurs.  If no error occurs the returned
385  * nl_nch is always referenced and locked, otherwise it may or may not be.
386  *
387  * Intermediate directory elements, including the current directory, require
388  * execute (search) permission.  nlookup does not examine the access 
389  * permissions on the returned element.
390  *
391  * If NLC_CREATE is set the last directory must allow node creation,
392  * and an error code of 0 will be returned for a non-existant
393  * target (not ENOENT).
394  *
395  * If NLC_RENAME_DST is set the last directory mut allow node deletion,
396  * plus the sticky check is made, and an error code of 0 will be returned
397  * for a non-existant target (not ENOENT).
398  *
399  * If NLC_DELETE is set the last directory mut allow node deletion,
400  * plus the sticky check is made.
401  *
402  * If NLC_REFDVP is set nd->nl_dvp will be set to the directory vnode
403  * of the returned entry.  The vnode will be referenced, but not locked,
404  * and will be released by nlookup_done() along with everything else.
405  *
406  * NOTE: As an optimization we attempt to obtain a shared namecache lock
407  *       on any intermediate elements.  On success, the returned element
408  *       is ALWAYS locked exclusively.
409  */
410 static
411 int
412 islastelement(const char *ptr)
413 {
414         while (*ptr == '/')
415                 ++ptr;
416         return (*ptr == 0);
417 }
418
419 int
420 nlookup(struct nlookupdata *nd)
421 {
422     globaldata_t gd = mycpu;
423     struct nlcomponent nlc;
424     struct nchandle nch;
425     struct nchandle par;
426     struct nchandle nctmp;
427     struct mount *mp;
428     struct vnode *hvp;          /* hold to prevent recyclement */
429     int wasdotordotdot;
430     char *ptr;
431     int error;
432     int len;
433     int dflags;
434     int hit = 1;
435
436 #ifdef KTRACE
437     if (KTRPOINT(nd->nl_td, KTR_NAMEI))
438         ktrnamei(nd->nl_td->td_lwp, nd->nl_path);
439 #endif
440     bzero(&nlc, sizeof(nlc));
441
442     /*
443      * Setup for the loop.  The current working namecache element is
444      * always at least referenced.  We lock it as required, but always
445      * return a locked, resolved namecache entry.
446      */
447     nd->nl_loopcnt = 0;
448     if (nd->nl_dvp) {
449         vrele(nd->nl_dvp);
450         nd->nl_dvp = NULL;
451     }
452     ptr = nd->nl_path;
453
454     /*
455      * Loop on the path components.  At the top of the loop nd->nl_nch
456      * is ref'd and unlocked and represents our current position.
457      */
458     for (;;) {
459         /*
460          * Make sure nl_nch is locked so we can access the vnode, resolution
461          * state, etc.
462          */
463         if ((nd->nl_flags & NLC_NCPISLOCKED) == 0) {
464                 nd->nl_flags |= NLC_NCPISLOCKED;
465                 cache_lock_maybe_shared(&nd->nl_nch, islastelement(ptr));
466         }
467
468         /*
469          * Check if the root directory should replace the current
470          * directory.  This is done at the start of a translation
471          * or after a symbolic link has been found.  In other cases
472          * ptr will never be pointing at a '/'.
473          */
474         if (*ptr == '/') {
475             do {
476                 ++ptr;
477             } while (*ptr == '/');
478             cache_unlock(&nd->nl_nch);
479             cache_get_maybe_shared(&nd->nl_rootnch, &nch,
480                                    islastelement(ptr));
481             cache_drop(&nd->nl_nch);
482             nd->nl_nch = nch;           /* remains locked */
483
484             /*
485              * Fast-track termination.  There is no parent directory of
486              * the root in the same mount from the point of view of
487              * the caller so return EACCES if NLC_REFDVP is specified,
488              * and EEXIST if NLC_CREATE is also specified.
489              * e.g. 'rmdir /' or 'mkdir /' are not allowed.
490              */
491             if (*ptr == 0) {
492                 if (nd->nl_flags & NLC_REFDVP)
493                         error = (nd->nl_flags & NLC_CREATE) ? EEXIST : EACCES;
494                 else
495                         error = 0;
496                 break;
497             }
498             continue;
499         }
500
501         /*
502          * Check directory search permissions (nd->nl_nch is locked & refd)
503          */
504         dflags = 0;
505         error = naccess(&nd->nl_nch, NLC_EXEC, nd->nl_cred, &dflags);
506         if (error)
507             break;
508
509         /*
510          * Extract the path component.  Path components are limited to
511          * 255 characters.
512          */
513         nlc.nlc_nameptr = ptr;
514         while (*ptr && *ptr != '/')
515             ++ptr;
516         nlc.nlc_namelen = ptr - nlc.nlc_nameptr;
517         if (nlc.nlc_namelen >= 256) {
518             error = ENAMETOOLONG;
519             break;
520         }
521
522         /*
523          * Lookup the path component in the cache, creating an unresolved
524          * entry if necessary.  We have to handle "." and ".." as special
525          * cases.
526          *
527          * When handling ".." we have to detect a traversal back through a
528          * mount point.   If we are at the root, ".." just returns the root.
529          *
530          * When handling "." or ".." we also have to recalculate dflags
531          * since our dflags will be for some sub-directory instead of the
532          * parent dir.
533          *
534          * This subsection returns a locked, refd 'nch' unless it errors out,
535          * and an unlocked but still ref'd nd->nl_nch.
536          *
537          * The namecache topology is not allowed to be disconnected, so 
538          * encountering a NULL parent will generate EINVAL.  This typically
539          * occurs when a directory is removed out from under a process.
540          *
541          * WARNING! The unlocking of nd->nl_nch is sensitive code.
542          */
543         KKASSERT(nd->nl_flags & NLC_NCPISLOCKED);
544
545         if (nlc.nlc_namelen == 1 && nlc.nlc_nameptr[0] == '.') {
546             cache_unlock(&nd->nl_nch);
547             nd->nl_flags &= ~NLC_NCPISLOCKED;
548             cache_get_maybe_shared(&nd->nl_nch, &nch, islastelement(ptr));
549             wasdotordotdot = 1;
550         } else if (nlc.nlc_namelen == 2 && 
551                    nlc.nlc_nameptr[0] == '.' && nlc.nlc_nameptr[1] == '.') {
552             if (nd->nl_nch.mount == nd->nl_rootnch.mount &&
553                 nd->nl_nch.ncp == nd->nl_rootnch.ncp
554             ) {
555                 /*
556                  * ".." at the root returns the root
557                  */
558                 cache_unlock(&nd->nl_nch);
559                 nd->nl_flags &= ~NLC_NCPISLOCKED;
560                 cache_get_maybe_shared(&nd->nl_nch, &nch, islastelement(ptr));
561             } else {
562                 /*
563                  * Locate the parent ncp.  If we are at the root of a
564                  * filesystem mount we have to skip to the mounted-on
565                  * point in the underlying filesystem.
566                  *
567                  * Expect the parent to always be good since the
568                  * mountpoint doesn't go away.  XXX hack.  cache_get()
569                  * requires the ncp to already have a ref as a safety.
570                  */
571                 nctmp = nd->nl_nch;
572                 while (nctmp.ncp == nctmp.mount->mnt_ncmountpt.ncp)
573                         nctmp = nctmp.mount->mnt_ncmounton;
574                 nctmp.ncp = nctmp.ncp->nc_parent;
575                 KKASSERT(nctmp.ncp != NULL);
576                 cache_hold(&nctmp);
577                 cache_unlock(&nd->nl_nch);
578                 nd->nl_flags &= ~NLC_NCPISLOCKED;
579                 cache_get_maybe_shared(&nctmp, &nch, islastelement(ptr));
580                 cache_drop(&nctmp);             /* NOTE: zero's nctmp */
581             }
582             wasdotordotdot = 2;
583         } else {
584             /*
585              * Must unlock nl_nch when traversing down the path.  However,
586              * the child ncp has not yet been found/created and the parent's
587              * child list might be empty.  Thus releasing the lock can
588              * allow a race whereby the parent ncp's vnode is recycled.
589              * This case can occur especially when maxvnodes is set very low.
590              *
591              * We need the parent's ncp to remain resolved for all normal
592              * filesystem activities, so we vhold() the vp during the lookup
593              * to prevent recyclement due to vnlru / maxvnodes.
594              *
595              * If we race an unlink or rename the ncp might be marked
596              * DESTROYED after resolution, requiring a retry.
597              */
598             if ((hvp = nd->nl_nch.ncp->nc_vp) != NULL)
599                 vhold(hvp);
600             cache_unlock(&nd->nl_nch);
601             nd->nl_flags &= ~NLC_NCPISLOCKED;
602             error = cache_nlookup_maybe_shared(&nd->nl_nch, &nlc,
603                                                islastelement(ptr), &nch);
604             if (error == EWOULDBLOCK) {
605                     nch = cache_nlookup(&nd->nl_nch, &nlc);
606                     if (nch.ncp->nc_flag & NCF_UNRESOLVED)
607                         hit = 0;
608                     for (;;) {
609                         error = cache_resolve(&nch, nd->nl_cred);
610                         if (error != EAGAIN &&
611                             (nch.ncp->nc_flag & NCF_DESTROYED) == 0) {
612                                 break;
613                         }
614                         kprintf("[diagnostic] nlookup: relookup %*.*s\n",
615                                 nch.ncp->nc_nlen, nch.ncp->nc_nlen,
616                                 nch.ncp->nc_name);
617                         cache_put(&nch);
618                         nch = cache_nlookup(&nd->nl_nch, &nlc);
619                     }
620             }
621             if (hvp)
622                 vdrop(hvp);
623             wasdotordotdot = 0;
624         }
625
626         /*
627          * If the last component was "." or ".." our dflags no longer
628          * represents the parent directory and we have to explicitly
629          * look it up.
630          *
631          * Expect the parent to be good since nch is locked.
632          */
633         if (wasdotordotdot && error == 0) {
634             dflags = 0;
635             if ((par.ncp = nch.ncp->nc_parent) != NULL) {
636                 par.mount = nch.mount;
637                 cache_hold(&par);
638                 cache_lock_maybe_shared(&par, islastelement(ptr));
639                 error = naccess(&par, 0, nd->nl_cred, &dflags);
640                 cache_put(&par);
641             }
642         }
643
644         /*
645          * [end of subsection]
646          *
647          * nch is locked and referenced.
648          * nd->nl_nch is unlocked and referenced.
649          *
650          * nl_nch must be unlocked or we could chain lock to the root
651          * if a resolve gets stuck (e.g. in NFS).
652          */
653         KKASSERT((nd->nl_flags & NLC_NCPISLOCKED) == 0);
654
655         /*
656          * Resolve the namespace if necessary.  The ncp returned by
657          * cache_nlookup() is referenced and locked.
658          *
659          * XXX neither '.' nor '..' should return EAGAIN since they were
660          * previously resolved and thus cannot be newly created ncp's.
661          */
662         if (nch.ncp->nc_flag & NCF_UNRESOLVED) {
663             hit = 0;
664             error = cache_resolve(&nch, nd->nl_cred);
665             KKASSERT(error != EAGAIN);
666         } else {
667             error = nch.ncp->nc_error;
668         }
669
670         /*
671          * Early completion.  ENOENT is not an error if this is the last
672          * component and NLC_CREATE or NLC_RENAME (rename target) was
673          * requested.  Note that ncp->nc_error is left as ENOENT in that
674          * case, which we check later on.
675          *
676          * Also handle invalid '.' or '..' components terminating a path
677          * for a create/rename/delete.  The standard requires this and pax
678          * pretty stupidly depends on it.
679          */
680         if (islastelement(ptr)) {
681             if (error == ENOENT &&
682                 (nd->nl_flags & (NLC_CREATE | NLC_RENAME_DST))
683             ) {
684                 if (nd->nl_flags & NLC_NFS_RDONLY) {
685                         error = EROFS;
686                 } else {
687                         error = naccess(&nch, nd->nl_flags | dflags,
688                                         nd->nl_cred, NULL);
689                 }
690             }
691             if (error == 0 && wasdotordotdot &&
692                 (nd->nl_flags & (NLC_CREATE | NLC_DELETE |
693                                  NLC_RENAME_SRC | NLC_RENAME_DST))) {
694                 /*
695                  * POSIX junk
696                  */
697                 if (nd->nl_flags & NLC_CREATE)
698                         error = EEXIST;
699                 else if (nd->nl_flags & NLC_DELETE)
700                         error = (wasdotordotdot == 1) ? EINVAL : ENOTEMPTY;
701                 else
702                         error = EINVAL;
703             }
704         }
705
706         /*
707          * Early completion on error.
708          */
709         if (error) {
710             cache_put(&nch);
711             break;
712         }
713
714         /*
715          * If the element is a symlink and it is either not the last
716          * element or it is the last element and we are allowed to
717          * follow symlinks, resolve the symlink.
718          */
719         if ((nch.ncp->nc_flag & NCF_ISSYMLINK) &&
720             (*ptr || (nd->nl_flags & NLC_FOLLOW))
721         ) {
722             if (nd->nl_loopcnt++ >= MAXSYMLINKS) {
723                 error = ELOOP;
724                 cache_put(&nch);
725                 break;
726             }
727             error = nreadsymlink(nd, &nch, &nlc);
728             cache_put(&nch);
729             if (error)
730                 break;
731
732             /*
733              * Concatenate trailing path elements onto the returned symlink.
734              * Note that if the path component (ptr) is not exhausted, it
735              * will being with a '/', so we do not have to add another one.
736              *
737              * The symlink may not be empty.
738              */
739             len = strlen(ptr);
740             if (nlc.nlc_namelen == 0 || nlc.nlc_namelen + len >= MAXPATHLEN) {
741                 error = nlc.nlc_namelen ? ENAMETOOLONG : ENOENT;
742                 objcache_put(namei_oc, nlc.nlc_nameptr);
743                 break;
744             }
745             bcopy(ptr, nlc.nlc_nameptr + nlc.nlc_namelen, len + 1);
746             if (nd->nl_flags & NLC_HASBUF)
747                 objcache_put(namei_oc, nd->nl_path);
748             nd->nl_path = nlc.nlc_nameptr;
749             nd->nl_flags |= NLC_HASBUF;
750             ptr = nd->nl_path;
751
752             /*
753              * Go back up to the top to resolve any initial '/'s in the
754              * symlink.
755              */
756             continue;
757         }
758
759         /*
760          * If the element is a directory and we are crossing a mount point,
761          * Locate the mount.
762          */
763         while ((nch.ncp->nc_flag & NCF_ISMOUNTPT) && 
764             (nd->nl_flags & NLC_NOCROSSMOUNT) == 0 &&
765             (mp = cache_findmount(&nch)) != NULL
766         ) {
767             struct vnode *tdp;
768             int vfs_do_busy = 0;
769
770             /*
771              * VFS must be busied before the namecache entry is locked,
772              * but we don't want to waste time calling vfs_busy() if the
773              * mount point is already resolved.
774              */
775 again:
776             cache_put(&nch);
777             if (vfs_do_busy) {
778                 while (vfs_busy(mp, 0)) {
779                     if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
780                         kprintf("nlookup: warning umount race avoided\n");
781                         cache_dropmount(mp);
782                         error = EBUSY;
783                         vfs_do_busy = 0;
784                         goto double_break;
785                     }
786                 }
787             }
788             cache_get_maybe_shared(&mp->mnt_ncmountpt, &nch,
789                                    islastelement(ptr));
790
791             if (nch.ncp->nc_flag & NCF_UNRESOLVED) {
792                 if (vfs_do_busy == 0) {
793                     vfs_do_busy = 1;
794                     goto again;
795                 }
796                 error = VFS_ROOT(mp, &tdp);
797                 vfs_unbusy(mp);
798                 vfs_do_busy = 0;
799                 if (error) {
800                     cache_dropmount(mp);
801                     break;
802                 }
803                 cache_setvp(&nch, tdp);
804                 vput(tdp);
805             }
806             if (vfs_do_busy)
807                 vfs_unbusy(mp);
808             cache_dropmount(mp);
809         }
810
811         if (error) {
812             cache_put(&nch);
813 double_break:
814             break;
815         }
816             
817         /*
818          * Skip any slashes to get to the next element.  If there 
819          * are any slashes at all the current element must be a
820          * directory or, in the create case, intended to become a directory.
821          * If it isn't we break without incrementing ptr and fall through
822          * to the failure case below.
823          */
824         while (*ptr == '/') {
825             if ((nch.ncp->nc_flag & NCF_ISDIR) == 0 && 
826                 !(nd->nl_flags & NLC_WILLBEDIR)
827             ) {
828                 break;
829             }
830             ++ptr;
831         }
832
833         /*
834          * Continuation case: additional elements and the current
835          * element is a directory.
836          */
837         if (*ptr && (nch.ncp->nc_flag & NCF_ISDIR)) {
838             cache_drop(&nd->nl_nch);
839             cache_unlock(&nch);
840             KKASSERT((nd->nl_flags & NLC_NCPISLOCKED) == 0);
841             nd->nl_nch = nch;
842             continue;
843         }
844
845         /*
846          * Failure case: additional elements and the current element
847          * is not a directory
848          */
849         if (*ptr) {
850             cache_put(&nch);
851             error = ENOTDIR;
852             break;
853         }
854
855         /*
856          * Successful lookup of last element.
857          *
858          * Check permissions if the target exists.  If the target does not
859          * exist directory permissions were already tested in the early
860          * completion code above.
861          *
862          * nd->nl_flags will be adjusted on return with NLC_APPENDONLY
863          * if the file is marked append-only, and NLC_STICKY if the directory
864          * containing the file is sticky.
865          */
866         if (nch.ncp->nc_vp && (nd->nl_flags & NLC_ALLCHKS)) {
867             error = naccess(&nch, nd->nl_flags | dflags,
868                             nd->nl_cred, NULL);
869             if (error) {
870                 cache_put(&nch);
871                 break;
872             }
873         }
874
875         /*
876          * Termination: no more elements.
877          *
878          * If NLC_REFDVP is set acquire a referenced parent dvp.
879          */
880         if (nd->nl_flags & NLC_REFDVP) {
881                 cache_lock(&nd->nl_nch);
882                 error = cache_vref(&nd->nl_nch, nd->nl_cred, &nd->nl_dvp);
883                 cache_unlock(&nd->nl_nch);
884                 if (error) {
885                         kprintf("NLC_REFDVP: Cannot ref dvp of %p\n", nch.ncp);
886                         cache_put(&nch);
887                         break;
888                 }
889         }
890         cache_drop(&nd->nl_nch);
891         nd->nl_nch = nch;
892         nd->nl_flags |= NLC_NCPISLOCKED;
893         error = 0;
894         break;
895     }
896
897     if (hit)
898         ++gd->gd_nchstats->ncs_longhits;
899     else
900         ++gd->gd_nchstats->ncs_longmiss;
901
902     if (nd->nl_flags & NLC_NCPISLOCKED)
903         KKASSERT(cache_lockstatus(&nd->nl_nch) == LK_EXCLUSIVE);
904
905     /*
906      * NOTE: If NLC_CREATE was set the ncp may represent a negative hit
907      * (ncp->nc_error will be ENOENT), but we will still return an error
908      * code of 0.
909      */
910     return(error);
911 }
912
913 /*
914  * Resolve a mount point's glue ncp.  This ncp connects creates the illusion
915  * of continuity in the namecache tree by connecting the ncp related to the
916  * vnode under the mount to the ncp related to the mount's root vnode.
917  *
918  * If no error occured a locked, ref'd ncp is stored in *ncpp.
919  */
920 int
921 nlookup_mp(struct mount *mp, struct nchandle *nch)
922 {
923     struct vnode *vp;
924     int error;
925
926     error = 0;
927     cache_get(&mp->mnt_ncmountpt, nch);
928     if (nch->ncp->nc_flag & NCF_UNRESOLVED) {
929         while (vfs_busy(mp, 0))
930             ;
931         error = VFS_ROOT(mp, &vp);
932         vfs_unbusy(mp);
933         if (error) {
934             cache_put(nch);
935         } else {
936             cache_setvp(nch, vp);
937             vput(vp);
938         }
939     }
940     return(error);
941 }
942
943 /*
944  * Read the contents of a symlink, allocate a path buffer out of the
945  * namei_oc and initialize the supplied nlcomponent with the result.
946  *
947  * If an error occurs no buffer will be allocated or returned in the nlc.
948  */
949 int
950 nreadsymlink(struct nlookupdata *nd, struct nchandle *nch, 
951                 struct nlcomponent *nlc)
952 {
953     struct vnode *vp;
954     struct iovec aiov;
955     struct uio auio;
956     int linklen;
957     int error;
958     char *cp;
959
960     nlc->nlc_nameptr = NULL;
961     nlc->nlc_namelen = 0;
962     if (nch->ncp->nc_vp == NULL)
963         return(ENOENT);
964     if ((error = cache_vget(nch, nd->nl_cred, LK_SHARED, &vp)) != 0)
965         return(error);
966     cp = objcache_get(namei_oc, M_WAITOK);
967     aiov.iov_base = cp;
968     aiov.iov_len = MAXPATHLEN;
969     auio.uio_iov = &aiov;
970     auio.uio_iovcnt = 1;
971     auio.uio_offset = 0;
972     auio.uio_rw = UIO_READ;
973     auio.uio_segflg = UIO_SYSSPACE;
974     auio.uio_td = nd->nl_td;
975     auio.uio_resid = MAXPATHLEN - 1;
976     error = VOP_READLINK(vp, &auio, nd->nl_cred);
977     if (error)
978         goto fail;
979     linklen = MAXPATHLEN - 1 - auio.uio_resid;
980     if (varsym_enable) {
981         linklen = varsymreplace(cp, linklen, MAXPATHLEN - 1);
982         if (linklen < 0) {
983             error = ENAMETOOLONG;
984             goto fail;
985         }
986     }
987     cp[linklen] = 0;
988     nlc->nlc_nameptr = cp;
989     nlc->nlc_namelen = linklen;
990     vput(vp);
991     return(0);
992 fail:
993     objcache_put(namei_oc, cp);
994     vput(vp);
995     return(error);
996 }
997
998 /*
999  * Check access [XXX cache vattr!] [XXX quota]
1000  *
1001  * Generally check the NLC_* access bits.   All specified bits must pass
1002  * for this function to return 0.
1003  *
1004  * The file does not have to exist when checking NLC_CREATE or NLC_RENAME_DST
1005  * access, otherwise it must exist.  No error is returned in this case.
1006  *
1007  * The file must not exist if NLC_EXCL is specified.
1008  *
1009  * Directory permissions in general are tested for NLC_CREATE if the file
1010  * does not exist, NLC_DELETE if the file does exist, and NLC_RENAME_DST
1011  * whether the file exists or not.
1012  *
1013  * The directory sticky bit is tested for NLC_DELETE and NLC_RENAME_DST,
1014  * the latter is only tested if the target exists.
1015  *
1016  * The passed ncp must be referenced and locked.  If it is already resolved
1017  * it may be locked shared but otherwise should be locked exclusively.
1018  */
1019 static int
1020 naccess(struct nchandle *nch, int nflags, struct ucred *cred, int *nflagsp)
1021 {
1022     struct vnode *vp;
1023     struct vattr va;
1024     struct namecache *ncp;
1025     int error;
1026     int cflags;
1027
1028     KKASSERT(cache_lockstatus(nch) > 0);
1029
1030     ncp = nch->ncp;
1031     if (ncp->nc_flag & NCF_UNRESOLVED) {
1032         cache_resolve(nch, cred);
1033         ncp = nch->ncp;
1034     }
1035     error = ncp->nc_error;
1036
1037     /*
1038      * Directory permissions checks.  Silently ignore ENOENT if these
1039      * tests pass.  It isn't an error.
1040      *
1041      * We can safely resolve ncp->nc_parent because ncp is currently
1042      * locked.
1043      */
1044     if (nflags & (NLC_CREATE | NLC_DELETE | NLC_RENAME_SRC | NLC_RENAME_DST)) {
1045         if (((nflags & NLC_CREATE) && ncp->nc_vp == NULL) ||
1046             ((nflags & NLC_DELETE) && ncp->nc_vp != NULL) ||
1047             ((nflags & NLC_RENAME_SRC) && ncp->nc_vp != NULL) ||
1048             (nflags & NLC_RENAME_DST)
1049         ) {
1050             struct nchandle par;
1051
1052             if ((par.ncp = ncp->nc_parent) == NULL) {
1053                 if (error != EAGAIN)
1054                         error = EINVAL;
1055             } else if (error == 0 || error == ENOENT) {
1056                 par.mount = nch->mount;
1057                 cache_hold(&par);
1058                 cache_lock_maybe_shared(&par, 0);
1059                 error = naccess(&par, NLC_WRITE, cred, NULL);
1060                 cache_put(&par);
1061             }
1062         }
1063     }
1064
1065     /*
1066      * NLC_EXCL check.  Target file must not exist.
1067      */
1068     if (error == 0 && (nflags & NLC_EXCL) && ncp->nc_vp != NULL)
1069         error = EEXIST;
1070
1071     /*
1072      * Get the vnode attributes so we can do the rest of our checks.
1073      *
1074      * NOTE: We only call naccess_va() if the target exists.
1075      */
1076     if (error == 0) {
1077         error = cache_vget(nch, cred, LK_SHARED, &vp);
1078         if (error == ENOENT) {
1079             /*
1080              * Silently zero-out ENOENT if creating or renaming
1081              * (rename target).  It isn't an error.
1082              */
1083             if (nflags & (NLC_CREATE | NLC_RENAME_DST))
1084                 error = 0;
1085         } else if (error == 0) {
1086             /*
1087              * Get the vnode attributes and check for illegal O_TRUNC
1088              * requests and read-only mounts.
1089              *
1090              * NOTE: You can still open devices on read-only mounts for
1091              *       writing.
1092              *
1093              * NOTE: creates/deletes/renames are handled by the NLC_WRITE
1094              *       check on the parent directory above.
1095              *
1096              * XXX cache the va in the namecache or in the vnode
1097              */
1098             error = VOP_GETATTR(vp, &va);
1099             if (error == 0 && (nflags & NLC_TRUNCATE)) {
1100                 switch(va.va_type) {
1101                 case VREG:
1102                 case VDATABASE:
1103                 case VCHR:
1104                 case VBLK:
1105                 case VFIFO:
1106                     break;
1107                 case VDIR:
1108                     error = EISDIR;
1109                     break;
1110                 default:
1111                     error = EINVAL;
1112                     break;
1113                 }
1114             }
1115             if (error == 0 && (nflags & NLC_WRITE) && vp->v_mount &&
1116                 (vp->v_mount->mnt_flag & MNT_RDONLY)
1117             ) {
1118                 switch(va.va_type) {
1119                 case VDIR:
1120                 case VLNK:
1121                 case VREG:
1122                 case VDATABASE:
1123                     error = EROFS;
1124                     break;
1125                 default:
1126                     break;
1127                 }
1128             }
1129             vput(vp);
1130
1131             /*
1132              * Check permissions based on file attributes.  The passed
1133              * flags (*nflagsp) are modified with feedback based on
1134              * special attributes and requirements.
1135              */
1136             if (error == 0) {
1137                 /*
1138                  * Adjust the returned (*nflagsp) if non-NULL.
1139                  */
1140                 if (nflagsp) {
1141                     if ((va.va_mode & VSVTX) && va.va_uid != cred->cr_uid)
1142                         *nflagsp |= NLC_STICKY;
1143                     if (va.va_flags & APPEND)
1144                         *nflagsp |= NLC_APPENDONLY;
1145                     if (va.va_flags & IMMUTABLE)
1146                         *nflagsp |= NLC_IMMUTABLE;
1147                 }
1148
1149                 /*
1150                  * Track swapcache management flags in the namecache.
1151                  *
1152                  * Calculate the flags based on the current vattr info
1153                  * and recalculate the inherited flags from the parent
1154                  * (the original cache linkage may have occurred without
1155                  * getattrs and thus have stale flags).
1156                  */
1157                 cflags = 0;
1158                 if (va.va_flags & SF_NOCACHE)
1159                         cflags |= NCF_SF_NOCACHE;
1160                 if (va.va_flags & UF_CACHE)
1161                         cflags |= NCF_UF_CACHE;
1162                 if (ncp->nc_parent) {
1163                         if (ncp->nc_parent->nc_flag &
1164                             (NCF_SF_NOCACHE | NCF_SF_PNOCACHE)) {
1165                                 cflags |= NCF_SF_PNOCACHE;
1166                         }
1167                         if (ncp->nc_parent->nc_flag &
1168                             (NCF_UF_CACHE | NCF_UF_PCACHE)) {
1169                                 cflags |= NCF_UF_PCACHE;
1170                         }
1171                 }
1172
1173                 /*
1174                  * XXX we're not supposed to update nc_flag when holding
1175                  *     a shared lock.
1176                  */
1177                 atomic_clear_short(&ncp->nc_flag,
1178                                    (NCF_SF_NOCACHE | NCF_UF_CACHE |
1179                                    NCF_SF_PNOCACHE | NCF_UF_PCACHE) & ~cflags);
1180                 atomic_set_short(&ncp->nc_flag, cflags);
1181
1182                 /*
1183                  * Process general access.
1184                  */
1185                 error = naccess_va(&va, nflags, cred);
1186             }
1187         }
1188     }
1189     return(error);
1190 }
1191
1192 /*
1193  * Check the requested access against the given vattr using cred.
1194  */
1195 int
1196 naccess_va(struct vattr *va, int nflags, struct ucred *cred)
1197 {
1198     int i;
1199     int vmode;
1200
1201     /*
1202      * Test the immutable bit.  Creations, deletions, renames (source
1203      * or destination) are not allowed.  chown/chmod/other is also not
1204      * allowed but is handled by SETATTR.  Hardlinks to the immutable
1205      * file are allowed.
1206      *
1207      * If the directory is set to immutable then creations, deletions,
1208      * renames (source or dest) and hardlinks to files within the directory
1209      * are not allowed, and regular files opened through the directory may
1210      * not be written to or truncated (unless a special device).
1211      *
1212      * NOTE!  New hardlinks to immutable files work but new hardlinks to
1213      * files, immutable or not, sitting inside an immutable directory are
1214      * not allowed.  As always if the file is hardlinked via some other
1215      * path additional hardlinks may be possible even if the file is marked
1216      * immutable.  The sysop needs to create a closure by checking the hard
1217      * link count.  Once closure is achieved you are good, and security
1218      * scripts should check link counts anyway.
1219      *
1220      * Writes and truncations are only allowed on special devices.
1221      */
1222     if ((va->va_flags & IMMUTABLE) || (nflags & NLC_IMMUTABLE)) {
1223         if ((nflags & NLC_IMMUTABLE) && (nflags & NLC_HLINK))
1224             return (EPERM);
1225         if (nflags & (NLC_CREATE | NLC_DELETE |
1226                       NLC_RENAME_SRC | NLC_RENAME_DST)) {
1227             return (EPERM);
1228         }
1229         if (nflags & (NLC_WRITE | NLC_TRUNCATE)) {
1230             switch(va->va_type) {
1231             case VDIR:
1232                 return (EISDIR);
1233             case VLNK:
1234             case VREG:
1235             case VDATABASE:
1236                 return (EPERM);
1237             default:
1238                 break;
1239             }
1240         }
1241     }
1242
1243     /*
1244      * Test the no-unlink and append-only bits for opens, rename targets,
1245      * and deletions.  These bits are not tested for creations or
1246      * rename sources.
1247      *
1248      * Unlike FreeBSD we allow a file with APPEND set to be renamed.
1249      * If you do not wish this you must also set NOUNLINK.
1250      *
1251      * If the governing directory is marked APPEND-only it implies
1252      * NOUNLINK for all entries in the directory.
1253      */
1254     if (((va->va_flags & NOUNLINK) || (nflags & NLC_APPENDONLY)) &&
1255         (nflags & (NLC_DELETE | NLC_RENAME_SRC | NLC_RENAME_DST))
1256     ) {
1257         return (EPERM);
1258     }
1259
1260     /*
1261      * A file marked append-only may not be deleted but can be renamed.
1262      */
1263     if ((va->va_flags & APPEND) &&
1264         (nflags & (NLC_DELETE | NLC_RENAME_DST))
1265     ) {
1266         return (EPERM);
1267     }
1268
1269     /*
1270      * A file marked append-only which is opened for writing must also
1271      * be opened O_APPEND.
1272      */
1273     if ((va->va_flags & APPEND) && (nflags & (NLC_OPEN | NLC_TRUNCATE))) {
1274         if (nflags & NLC_TRUNCATE)
1275             return (EPERM);
1276         if ((nflags & (NLC_OPEN | NLC_WRITE)) == (NLC_OPEN | NLC_WRITE)) {
1277             if ((nflags & NLC_APPEND) == 0)
1278                 return (EPERM);
1279         }
1280     }
1281
1282     /*
1283      * root gets universal access
1284      */
1285     if (cred->cr_uid == 0)
1286         return(0);
1287
1288     /*
1289      * Check owner perms.
1290      *
1291      * If NLC_OWN is set the owner of the file is allowed no matter when
1292      * the owner-mode bits say (utimes).
1293      */
1294     vmode = 0;
1295     if (nflags & NLC_READ)
1296         vmode |= S_IRUSR;
1297     if (nflags & NLC_WRITE)
1298         vmode |= S_IWUSR;
1299     if (nflags & NLC_EXEC)
1300         vmode |= S_IXUSR;
1301
1302     if (cred->cr_uid == va->va_uid) {
1303         if ((nflags & NLC_OWN) == 0) {
1304             if ((vmode & va->va_mode) != vmode)
1305                 return(EACCES);
1306         }
1307         return(0);
1308     }
1309
1310     /*
1311      * If NLC_STICKY is set only the owner may delete or rename a file.
1312      * This bit is typically set on /tmp.
1313      *
1314      * Note that the NLC_READ/WRITE/EXEC bits are not typically set in
1315      * the specific delete or rename case.  For deletions and renames we
1316      * usually just care about directory permissions, not file permissions.
1317      */
1318     if ((nflags & NLC_STICKY) &&
1319         (nflags & (NLC_RENAME_SRC | NLC_RENAME_DST | NLC_DELETE))) {
1320         return(EACCES);
1321     }
1322
1323     /*
1324      * Check group perms
1325      */
1326     vmode >>= 3;
1327     for (i = 0; i < cred->cr_ngroups; ++i) {
1328         if (va->va_gid == cred->cr_groups[i]) {
1329             if ((vmode & va->va_mode) != vmode)
1330                 return(EACCES);
1331             return(0);
1332         }
1333     }
1334
1335     /*
1336      * Check world perms
1337      */
1338     vmode >>= 3;
1339     if ((vmode & va->va_mode) != vmode)
1340         return(EACCES);
1341     return(0);
1342 }
1343