]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/fs/nfsserver/nfs_nfsdport.c
MFC: r241561
[FreeBSD/stable/9.git] / sys / fs / nfsserver / nfs_nfsdport.c
1 /*-
2  * Copyright (c) 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Rick Macklem at The University of Guelph.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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 the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include <sys/capability.h>
38
39 /*
40  * Functions that perform the vfs operations required by the routines in
41  * nfsd_serv.c. It is hoped that this change will make the server more
42  * portable.
43  */
44
45 #include <fs/nfs/nfsport.h>
46 #include <sys/hash.h>
47 #include <sys/sysctl.h>
48 #include <nlm/nlm_prot.h>
49 #include <nlm/nlm.h>
50
51 FEATURE(nfsd, "NFSv4 server");
52
53 extern u_int32_t newnfs_true, newnfs_false, newnfs_xdrneg1;
54 extern int nfsrv_useacl;
55 extern int newnfs_numnfsd;
56 extern struct mount nfsv4root_mnt;
57 extern struct nfsrv_stablefirst nfsrv_stablefirst;
58 extern void (*nfsd_call_servertimer)(void);
59 extern SVCPOOL  *nfsrvd_pool;
60 extern struct nfsv4lock nfsd_suspend_lock;
61 struct vfsoptlist nfsv4root_opt, nfsv4root_newopt;
62 NFSDLOCKMUTEX;
63 struct mtx nfs_cache_mutex;
64 struct mtx nfs_v4root_mutex;
65 struct nfsrvfh nfs_rootfh, nfs_pubfh;
66 int nfs_pubfhset = 0, nfs_rootfhset = 0;
67 struct proc *nfsd_master_proc = NULL;
68 static pid_t nfsd_master_pid = (pid_t)-1;
69 static char nfsd_master_comm[MAXCOMLEN + 1];
70 static struct timeval nfsd_master_start;
71 static uint32_t nfsv4_sysid = 0;
72
73 static int nfssvc_srvcall(struct thread *, struct nfssvc_args *,
74     struct ucred *);
75
76 int nfsrv_enable_crossmntpt = 1;
77 static int nfs_commit_blks;
78 static int nfs_commit_miss;
79 extern int nfsrv_issuedelegs;
80 extern int nfsrv_dolocallocks;
81
82 SYSCTL_NODE(_vfs, OID_AUTO, nfsd, CTLFLAG_RW, 0, "New NFS server");
83 SYSCTL_INT(_vfs_nfsd, OID_AUTO, mirrormnt, CTLFLAG_RW,
84     &nfsrv_enable_crossmntpt, 0, "Enable nfsd to cross mount points");
85 SYSCTL_INT(_vfs_nfsd, OID_AUTO, commit_blks, CTLFLAG_RW, &nfs_commit_blks,
86     0, "");
87 SYSCTL_INT(_vfs_nfsd, OID_AUTO, commit_miss, CTLFLAG_RW, &nfs_commit_miss,
88     0, "");
89 SYSCTL_INT(_vfs_nfsd, OID_AUTO, issue_delegations, CTLFLAG_RW,
90     &nfsrv_issuedelegs, 0, "Enable nfsd to issue delegations");
91 SYSCTL_INT(_vfs_nfsd, OID_AUTO, enable_locallocks, CTLFLAG_RW,
92     &nfsrv_dolocallocks, 0, "Enable nfsd to acquire local locks on files");
93
94 #define MAX_REORDERED_RPC       16
95 #define NUM_HEURISTIC           1031
96 #define NHUSE_INIT              64
97 #define NHUSE_INC               16
98 #define NHUSE_MAX               2048
99
100 static struct nfsheur {
101         struct vnode *nh_vp;    /* vp to match (unreferenced pointer) */
102         off_t nh_nextoff;       /* next offset for sequential detection */
103         int nh_use;             /* use count for selection */
104         int nh_seqcount;        /* heuristic */
105 } nfsheur[NUM_HEURISTIC];
106
107
108 /*
109  * Heuristic to detect sequential operation.
110  */
111 static struct nfsheur *
112 nfsrv_sequential_heuristic(struct uio *uio, struct vnode *vp)
113 {
114         struct nfsheur *nh;
115         int hi, try;
116
117         /* Locate best candidate. */
118         try = 32;
119         hi = ((int)(vm_offset_t)vp / sizeof(struct vnode)) % NUM_HEURISTIC;
120         nh = &nfsheur[hi];
121         while (try--) {
122                 if (nfsheur[hi].nh_vp == vp) {
123                         nh = &nfsheur[hi];
124                         break;
125                 }
126                 if (nfsheur[hi].nh_use > 0)
127                         --nfsheur[hi].nh_use;
128                 hi = (hi + 1) % NUM_HEURISTIC;
129                 if (nfsheur[hi].nh_use < nh->nh_use)
130                         nh = &nfsheur[hi];
131         }
132
133         /* Initialize hint if this is a new file. */
134         if (nh->nh_vp != vp) {
135                 nh->nh_vp = vp;
136                 nh->nh_nextoff = uio->uio_offset;
137                 nh->nh_use = NHUSE_INIT;
138                 if (uio->uio_offset == 0)
139                         nh->nh_seqcount = 4;
140                 else
141                         nh->nh_seqcount = 1;
142         }
143
144         /* Calculate heuristic. */
145         if ((uio->uio_offset == 0 && nh->nh_seqcount > 0) ||
146             uio->uio_offset == nh->nh_nextoff) {
147                 /* See comments in vfs_vnops.c:sequential_heuristic(). */
148                 nh->nh_seqcount += howmany(uio->uio_resid, 16384);
149                 if (nh->nh_seqcount > IO_SEQMAX)
150                         nh->nh_seqcount = IO_SEQMAX;
151         } else if (qabs(uio->uio_offset - nh->nh_nextoff) <= MAX_REORDERED_RPC *
152             imax(vp->v_mount->mnt_stat.f_iosize, uio->uio_resid)) {
153                 /* Probably a reordered RPC, leave seqcount alone. */
154         } else if (nh->nh_seqcount > 1) {
155                 nh->nh_seqcount /= 2;
156         } else {
157                 nh->nh_seqcount = 0;
158         }
159         nh->nh_use += NHUSE_INC;
160         if (nh->nh_use > NHUSE_MAX)
161                 nh->nh_use = NHUSE_MAX;
162         return (nh);
163 }
164
165 /*
166  * Get attributes into nfsvattr structure.
167  */
168 int
169 nfsvno_getattr(struct vnode *vp, struct nfsvattr *nvap, struct ucred *cred,
170     struct thread *p, int vpislocked)
171 {
172         int error, lockedit = 0;
173
174         if (vpislocked == 0) {
175                 /*
176                  * When vpislocked == 0, the vnode is either exclusively
177                  * locked by this thread or not locked by this thread.
178                  * As such, shared lock it, if not exclusively locked.
179                  */
180                 if (NFSVOPISLOCKED(vp) != LK_EXCLUSIVE) {
181                         lockedit = 1;
182                         NFSVOPLOCK(vp, LK_SHARED | LK_RETRY);
183                 }
184         }
185         error = VOP_GETATTR(vp, &nvap->na_vattr, cred);
186         if (lockedit != 0)
187                 NFSVOPUNLOCK(vp, 0);
188
189         NFSEXITCODE(error);
190         return (error);
191 }
192
193 /*
194  * Get a file handle for a vnode.
195  */
196 int
197 nfsvno_getfh(struct vnode *vp, fhandle_t *fhp, struct thread *p)
198 {
199         int error;
200
201         NFSBZERO((caddr_t)fhp, sizeof(fhandle_t));
202         fhp->fh_fsid = vp->v_mount->mnt_stat.f_fsid;
203         error = VOP_VPTOFH(vp, &fhp->fh_fid);
204
205         NFSEXITCODE(error);
206         return (error);
207 }
208
209 /*
210  * Perform access checking for vnodes obtained from file handles that would
211  * refer to files already opened by a Unix client. You cannot just use
212  * vn_writechk() and VOP_ACCESSX() for two reasons.
213  * 1 - You must check for exported rdonly as well as MNT_RDONLY for the write
214  *     case.
215  * 2 - The owner is to be given access irrespective of mode bits for some
216  *     operations, so that processes that chmod after opening a file don't
217  *     break.
218  */
219 int
220 nfsvno_accchk(struct vnode *vp, accmode_t accmode, struct ucred *cred,
221     struct nfsexstuff *exp, struct thread *p, int override, int vpislocked,
222     u_int32_t *supportedtypep)
223 {
224         struct vattr vattr;
225         int error = 0, getret = 0;
226
227         if (vpislocked == 0) {
228                 if (NFSVOPLOCK(vp, LK_SHARED) != 0) {
229                         error = EPERM;
230                         goto out;
231                 }
232         }
233         if (accmode & VWRITE) {
234                 /* Just vn_writechk() changed to check rdonly */
235                 /*
236                  * Disallow write attempts on read-only file systems;
237                  * unless the file is a socket or a block or character
238                  * device resident on the file system.
239                  */
240                 if (NFSVNO_EXRDONLY(exp) ||
241                     (vp->v_mount->mnt_flag & MNT_RDONLY)) {
242                         switch (vp->v_type) {
243                         case VREG:
244                         case VDIR:
245                         case VLNK:
246                                 error = EROFS;
247                         default:
248                                 break;
249                         }
250                 }
251                 /*
252                  * If there's shared text associated with
253                  * the inode, try to free it up once.  If
254                  * we fail, we can't allow writing.
255                  */
256                 if ((vp->v_vflag & VV_TEXT) != 0 && error == 0)
257                         error = ETXTBSY;
258         }
259         if (error != 0) {
260                 if (vpislocked == 0)
261                         NFSVOPUNLOCK(vp, 0);
262                 goto out;
263         }
264
265         /*
266          * Should the override still be applied when ACLs are enabled?
267          */
268         error = VOP_ACCESSX(vp, accmode, cred, p);
269         if (error != 0 && (accmode & (VDELETE | VDELETE_CHILD))) {
270                 /*
271                  * Try again with VEXPLICIT_DENY, to see if the test for
272                  * deletion is supported.
273                  */
274                 error = VOP_ACCESSX(vp, accmode | VEXPLICIT_DENY, cred, p);
275                 if (error == 0) {
276                         if (vp->v_type == VDIR) {
277                                 accmode &= ~(VDELETE | VDELETE_CHILD);
278                                 accmode |= VWRITE;
279                                 error = VOP_ACCESSX(vp, accmode, cred, p);
280                         } else if (supportedtypep != NULL) {
281                                 *supportedtypep &= ~NFSACCESS_DELETE;
282                         }
283                 }
284         }
285
286         /*
287          * Allow certain operations for the owner (reads and writes
288          * on files that are already open).
289          */
290         if (override != NFSACCCHK_NOOVERRIDE &&
291             (error == EPERM || error == EACCES)) {
292                 if (cred->cr_uid == 0 && (override & NFSACCCHK_ALLOWROOT))
293                         error = 0;
294                 else if (override & NFSACCCHK_ALLOWOWNER) {
295                         getret = VOP_GETATTR(vp, &vattr, cred);
296                         if (getret == 0 && cred->cr_uid == vattr.va_uid)
297                                 error = 0;
298                 }
299         }
300         if (vpislocked == 0)
301                 NFSVOPUNLOCK(vp, 0);
302
303 out:
304         NFSEXITCODE(error);
305         return (error);
306 }
307
308 /*
309  * Set attribute(s) vnop.
310  */
311 int
312 nfsvno_setattr(struct vnode *vp, struct nfsvattr *nvap, struct ucred *cred,
313     struct thread *p, struct nfsexstuff *exp)
314 {
315         int error;
316
317         error = VOP_SETATTR(vp, &nvap->na_vattr, cred);
318         NFSEXITCODE(error);
319         return (error);
320 }
321
322 /*
323  * Set up nameidata for a lookup() call and do it.
324  */
325 int
326 nfsvno_namei(struct nfsrv_descript *nd, struct nameidata *ndp,
327     struct vnode *dp, int islocked, struct nfsexstuff *exp, struct thread *p,
328     struct vnode **retdirp)
329 {
330         struct componentname *cnp = &ndp->ni_cnd;
331         int i;
332         struct iovec aiov;
333         struct uio auio;
334         int lockleaf = (cnp->cn_flags & LOCKLEAF) != 0, linklen;
335         int error = 0, crossmnt;
336         char *cp;
337
338         *retdirp = NULL;
339         cnp->cn_nameptr = cnp->cn_pnbuf;
340         ndp->ni_strictrelative = 0;
341         /*
342          * Extract and set starting directory.
343          */
344         if (dp->v_type != VDIR) {
345                 if (islocked)
346                         vput(dp);
347                 else
348                         vrele(dp);
349                 nfsvno_relpathbuf(ndp);
350                 error = ENOTDIR;
351                 goto out1;
352         }
353         if (islocked)
354                 NFSVOPUNLOCK(dp, 0);
355         VREF(dp);
356         *retdirp = dp;
357         if (NFSVNO_EXRDONLY(exp))
358                 cnp->cn_flags |= RDONLY;
359         ndp->ni_segflg = UIO_SYSSPACE;
360         crossmnt = 1;
361
362         if (nd->nd_flag & ND_PUBLOOKUP) {
363                 ndp->ni_loopcnt = 0;
364                 if (cnp->cn_pnbuf[0] == '/') {
365                         vrele(dp);
366                         /*
367                          * Check for degenerate pathnames here, since lookup()
368                          * panics on them.
369                          */
370                         for (i = 1; i < ndp->ni_pathlen; i++)
371                                 if (cnp->cn_pnbuf[i] != '/')
372                                         break;
373                         if (i == ndp->ni_pathlen) {
374                                 error = NFSERR_ACCES;
375                                 goto out;
376                         }
377                         dp = rootvnode;
378                         VREF(dp);
379                 }
380         } else if ((nfsrv_enable_crossmntpt == 0 && NFSVNO_EXPORTED(exp)) ||
381             (nd->nd_flag & ND_NFSV4) == 0) {
382                 /*
383                  * Only cross mount points for NFSv4 when doing a
384                  * mount while traversing the file system above
385                  * the mount point, unless nfsrv_enable_crossmntpt is set.
386                  */
387                 cnp->cn_flags |= NOCROSSMOUNT;
388                 crossmnt = 0;
389         }
390
391         /*
392          * Initialize for scan, set ni_startdir and bump ref on dp again
393          * becuase lookup() will dereference ni_startdir.
394          */
395
396         cnp->cn_thread = p;
397         ndp->ni_startdir = dp;
398         ndp->ni_rootdir = rootvnode;
399         ndp->ni_topdir = NULL;
400
401         if (!lockleaf)
402                 cnp->cn_flags |= LOCKLEAF;
403         for (;;) {
404                 cnp->cn_nameptr = cnp->cn_pnbuf;
405                 /*
406                  * Call lookup() to do the real work.  If an error occurs,
407                  * ndp->ni_vp and ni_dvp are left uninitialized or NULL and
408                  * we do not have to dereference anything before returning.
409                  * In either case ni_startdir will be dereferenced and NULLed
410                  * out.
411                  */
412                 error = lookup(ndp);
413                 if (error)
414                         break;
415
416                 /*
417                  * Check for encountering a symbolic link.  Trivial
418                  * termination occurs if no symlink encountered.
419                  */
420                 if ((cnp->cn_flags & ISSYMLINK) == 0) {
421                         if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0)
422                                 nfsvno_relpathbuf(ndp);
423                         if (ndp->ni_vp && !lockleaf)
424                                 NFSVOPUNLOCK(ndp->ni_vp, 0);
425                         break;
426                 }
427
428                 /*
429                  * Validate symlink
430                  */
431                 if ((cnp->cn_flags & LOCKPARENT) && ndp->ni_pathlen == 1)
432                         NFSVOPUNLOCK(ndp->ni_dvp, 0);
433                 if (!(nd->nd_flag & ND_PUBLOOKUP)) {
434                         error = EINVAL;
435                         goto badlink2;
436                 }
437
438                 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
439                         error = ELOOP;
440                         goto badlink2;
441                 }
442                 if (ndp->ni_pathlen > 1)
443                         cp = uma_zalloc(namei_zone, M_WAITOK);
444                 else
445                         cp = cnp->cn_pnbuf;
446                 aiov.iov_base = cp;
447                 aiov.iov_len = MAXPATHLEN;
448                 auio.uio_iov = &aiov;
449                 auio.uio_iovcnt = 1;
450                 auio.uio_offset = 0;
451                 auio.uio_rw = UIO_READ;
452                 auio.uio_segflg = UIO_SYSSPACE;
453                 auio.uio_td = NULL;
454                 auio.uio_resid = MAXPATHLEN;
455                 error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
456                 if (error) {
457                 badlink1:
458                         if (ndp->ni_pathlen > 1)
459                                 uma_zfree(namei_zone, cp);
460                 badlink2:
461                         vrele(ndp->ni_dvp);
462                         vput(ndp->ni_vp);
463                         break;
464                 }
465                 linklen = MAXPATHLEN - auio.uio_resid;
466                 if (linklen == 0) {
467                         error = ENOENT;
468                         goto badlink1;
469                 }
470                 if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
471                         error = ENAMETOOLONG;
472                         goto badlink1;
473                 }
474
475                 /*
476                  * Adjust or replace path
477                  */
478                 if (ndp->ni_pathlen > 1) {
479                         NFSBCOPY(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
480                         uma_zfree(namei_zone, cnp->cn_pnbuf);
481                         cnp->cn_pnbuf = cp;
482                 } else
483                         cnp->cn_pnbuf[linklen] = '\0';
484                 ndp->ni_pathlen += linklen;
485
486                 /*
487                  * Cleanup refs for next loop and check if root directory
488                  * should replace current directory.  Normally ni_dvp
489                  * becomes the new base directory and is cleaned up when
490                  * we loop.  Explicitly null pointers after invalidation
491                  * to clarify operation.
492                  */
493                 vput(ndp->ni_vp);
494                 ndp->ni_vp = NULL;
495
496                 if (cnp->cn_pnbuf[0] == '/') {
497                         vrele(ndp->ni_dvp);
498                         ndp->ni_dvp = ndp->ni_rootdir;
499                         VREF(ndp->ni_dvp);
500                 }
501                 ndp->ni_startdir = ndp->ni_dvp;
502                 ndp->ni_dvp = NULL;
503         }
504         if (!lockleaf)
505                 cnp->cn_flags &= ~LOCKLEAF;
506
507 out:
508         if (error) {
509                 uma_zfree(namei_zone, cnp->cn_pnbuf);
510                 ndp->ni_vp = NULL;
511                 ndp->ni_dvp = NULL;
512                 ndp->ni_startdir = NULL;
513                 cnp->cn_flags &= ~HASBUF;
514         } else if ((ndp->ni_cnd.cn_flags & (WANTPARENT|LOCKPARENT)) == 0) {
515                 ndp->ni_dvp = NULL;
516         }
517
518 out1:
519         NFSEXITCODE2(error, nd);
520         return (error);
521 }
522
523 /*
524  * Set up a pathname buffer and return a pointer to it and, optionally
525  * set a hash pointer.
526  */
527 void
528 nfsvno_setpathbuf(struct nameidata *ndp, char **bufpp, u_long **hashpp)
529 {
530         struct componentname *cnp = &ndp->ni_cnd;
531
532         cnp->cn_flags |= (NOMACCHECK | HASBUF);
533         cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
534         if (hashpp != NULL)
535                 *hashpp = NULL;
536         *bufpp = cnp->cn_pnbuf;
537 }
538
539 /*
540  * Release the above path buffer, if not released by nfsvno_namei().
541  */
542 void
543 nfsvno_relpathbuf(struct nameidata *ndp)
544 {
545
546         if ((ndp->ni_cnd.cn_flags & HASBUF) == 0)
547                 panic("nfsrelpath");
548         uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
549         ndp->ni_cnd.cn_flags &= ~HASBUF;
550 }
551
552 /*
553  * Readlink vnode op into an mbuf list.
554  */
555 int
556 nfsvno_readlink(struct vnode *vp, struct ucred *cred, struct thread *p,
557     struct mbuf **mpp, struct mbuf **mpendp, int *lenp)
558 {
559         struct iovec iv[(NFS_MAXPATHLEN+MLEN-1)/MLEN];
560         struct iovec *ivp = iv;
561         struct uio io, *uiop = &io;
562         struct mbuf *mp, *mp2 = NULL, *mp3 = NULL;
563         int i, len, tlen, error = 0;
564
565         len = 0;
566         i = 0;
567         while (len < NFS_MAXPATHLEN) {
568                 NFSMGET(mp);
569                 MCLGET(mp, M_WAIT);
570                 mp->m_len = NFSMSIZ(mp);
571                 if (len == 0) {
572                         mp3 = mp2 = mp;
573                 } else {
574                         mp2->m_next = mp;
575                         mp2 = mp;
576                 }
577                 if ((len + mp->m_len) > NFS_MAXPATHLEN) {
578                         mp->m_len = NFS_MAXPATHLEN - len;
579                         len = NFS_MAXPATHLEN;
580                 } else {
581                         len += mp->m_len;
582                 }
583                 ivp->iov_base = mtod(mp, caddr_t);
584                 ivp->iov_len = mp->m_len;
585                 i++;
586                 ivp++;
587         }
588         uiop->uio_iov = iv;
589         uiop->uio_iovcnt = i;
590         uiop->uio_offset = 0;
591         uiop->uio_resid = len;
592         uiop->uio_rw = UIO_READ;
593         uiop->uio_segflg = UIO_SYSSPACE;
594         uiop->uio_td = NULL;
595         error = VOP_READLINK(vp, uiop, cred);
596         if (error) {
597                 m_freem(mp3);
598                 *lenp = 0;
599                 goto out;
600         }
601         if (uiop->uio_resid > 0) {
602                 len -= uiop->uio_resid;
603                 tlen = NFSM_RNDUP(len);
604                 nfsrv_adj(mp3, NFS_MAXPATHLEN - tlen, tlen - len);
605         }
606         *lenp = len;
607         *mpp = mp3;
608         *mpendp = mp;
609
610 out:
611         NFSEXITCODE(error);
612         return (error);
613 }
614
615 /*
616  * Read vnode op call into mbuf list.
617  */
618 int
619 nfsvno_read(struct vnode *vp, off_t off, int cnt, struct ucred *cred,
620     struct thread *p, struct mbuf **mpp, struct mbuf **mpendp)
621 {
622         struct mbuf *m;
623         int i;
624         struct iovec *iv;
625         struct iovec *iv2;
626         int error = 0, len, left, siz, tlen, ioflag = 0;
627         struct mbuf *m2 = NULL, *m3;
628         struct uio io, *uiop = &io;
629         struct nfsheur *nh;
630
631         len = left = NFSM_RNDUP(cnt);
632         m3 = NULL;
633         /*
634          * Generate the mbuf list with the uio_iov ref. to it.
635          */
636         i = 0;
637         while (left > 0) {
638                 NFSMGET(m);
639                 MCLGET(m, M_WAIT);
640                 m->m_len = 0;
641                 siz = min(M_TRAILINGSPACE(m), left);
642                 left -= siz;
643                 i++;
644                 if (m3)
645                         m2->m_next = m;
646                 else
647                         m3 = m;
648                 m2 = m;
649         }
650         MALLOC(iv, struct iovec *, i * sizeof (struct iovec),
651             M_TEMP, M_WAITOK);
652         uiop->uio_iov = iv2 = iv;
653         m = m3;
654         left = len;
655         i = 0;
656         while (left > 0) {
657                 if (m == NULL)
658                         panic("nfsvno_read iov");
659                 siz = min(M_TRAILINGSPACE(m), left);
660                 if (siz > 0) {
661                         iv->iov_base = mtod(m, caddr_t) + m->m_len;
662                         iv->iov_len = siz;
663                         m->m_len += siz;
664                         left -= siz;
665                         iv++;
666                         i++;
667                 }
668                 m = m->m_next;
669         }
670         uiop->uio_iovcnt = i;
671         uiop->uio_offset = off;
672         uiop->uio_resid = len;
673         uiop->uio_rw = UIO_READ;
674         uiop->uio_segflg = UIO_SYSSPACE;
675         nh = nfsrv_sequential_heuristic(uiop, vp);
676         ioflag |= nh->nh_seqcount << IO_SEQSHIFT;
677         error = VOP_READ(vp, uiop, IO_NODELOCKED | ioflag, cred);
678         FREE((caddr_t)iv2, M_TEMP);
679         if (error) {
680                 m_freem(m3);
681                 *mpp = NULL;
682                 goto out;
683         }
684         nh->nh_nextoff = uiop->uio_offset;
685         tlen = len - uiop->uio_resid;
686         cnt = cnt < tlen ? cnt : tlen;
687         tlen = NFSM_RNDUP(cnt);
688         if (tlen == 0) {
689                 m_freem(m3);
690                 m3 = NULL;
691         } else if (len != tlen || tlen != cnt)
692                 nfsrv_adj(m3, len - tlen, tlen - cnt);
693         *mpp = m3;
694         *mpendp = m2;
695
696 out:
697         NFSEXITCODE(error);
698         return (error);
699 }
700
701 /*
702  * Write vnode op from an mbuf list.
703  */
704 int
705 nfsvno_write(struct vnode *vp, off_t off, int retlen, int cnt, int stable,
706     struct mbuf *mp, char *cp, struct ucred *cred, struct thread *p)
707 {
708         struct iovec *ivp;
709         int i, len;
710         struct iovec *iv;
711         int ioflags, error;
712         struct uio io, *uiop = &io;
713         struct nfsheur *nh;
714
715         MALLOC(ivp, struct iovec *, cnt * sizeof (struct iovec), M_TEMP,
716             M_WAITOK);
717         uiop->uio_iov = iv = ivp;
718         uiop->uio_iovcnt = cnt;
719         i = mtod(mp, caddr_t) + mp->m_len - cp;
720         len = retlen;
721         while (len > 0) {
722                 if (mp == NULL)
723                         panic("nfsvno_write");
724                 if (i > 0) {
725                         i = min(i, len);
726                         ivp->iov_base = cp;
727                         ivp->iov_len = i;
728                         ivp++;
729                         len -= i;
730                 }
731                 mp = mp->m_next;
732                 if (mp) {
733                         i = mp->m_len;
734                         cp = mtod(mp, caddr_t);
735                 }
736         }
737
738         if (stable == NFSWRITE_UNSTABLE)
739                 ioflags = IO_NODELOCKED;
740         else
741                 ioflags = (IO_SYNC | IO_NODELOCKED);
742         uiop->uio_resid = retlen;
743         uiop->uio_rw = UIO_WRITE;
744         uiop->uio_segflg = UIO_SYSSPACE;
745         NFSUIOPROC(uiop, p);
746         uiop->uio_offset = off;
747         nh = nfsrv_sequential_heuristic(uiop, vp);
748         ioflags |= nh->nh_seqcount << IO_SEQSHIFT;
749         error = VOP_WRITE(vp, uiop, ioflags, cred);
750         if (error == 0)
751                 nh->nh_nextoff = uiop->uio_offset;
752         FREE((caddr_t)iv, M_TEMP);
753
754         NFSEXITCODE(error);
755         return (error);
756 }
757
758 /*
759  * Common code for creating a regular file (plus special files for V2).
760  */
761 int
762 nfsvno_createsub(struct nfsrv_descript *nd, struct nameidata *ndp,
763     struct vnode **vpp, struct nfsvattr *nvap, int *exclusive_flagp,
764     int32_t *cverf, NFSDEV_T rdev, struct thread *p, struct nfsexstuff *exp)
765 {
766         u_quad_t tempsize;
767         int error;
768
769         error = nd->nd_repstat;
770         if (!error && ndp->ni_vp == NULL) {
771                 if (nvap->na_type == VREG || nvap->na_type == VSOCK) {
772                         vrele(ndp->ni_startdir);
773                         error = VOP_CREATE(ndp->ni_dvp,
774                             &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
775                         vput(ndp->ni_dvp);
776                         nfsvno_relpathbuf(ndp);
777                         if (!error) {
778                                 if (*exclusive_flagp) {
779                                         *exclusive_flagp = 0;
780                                         NFSVNO_ATTRINIT(nvap);
781                                         nvap->na_atime.tv_sec = cverf[0];
782                                         nvap->na_atime.tv_nsec = cverf[1];
783                                         error = VOP_SETATTR(ndp->ni_vp,
784                                             &nvap->na_vattr, nd->nd_cred);
785                                 }
786                         }
787                 /*
788                  * NFS V2 Only. nfsrvd_mknod() does this for V3.
789                  * (This implies, just get out on an error.)
790                  */
791                 } else if (nvap->na_type == VCHR || nvap->na_type == VBLK ||
792                         nvap->na_type == VFIFO) {
793                         if (nvap->na_type == VCHR && rdev == 0xffffffff)
794                                 nvap->na_type = VFIFO;
795                         if (nvap->na_type != VFIFO &&
796                             (error = priv_check_cred(nd->nd_cred,
797                              PRIV_VFS_MKNOD_DEV, 0))) {
798                                 vrele(ndp->ni_startdir);
799                                 nfsvno_relpathbuf(ndp);
800                                 vput(ndp->ni_dvp);
801                                 goto out;
802                         }
803                         nvap->na_rdev = rdev;
804                         error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
805                             &ndp->ni_cnd, &nvap->na_vattr);
806                         vput(ndp->ni_dvp);
807                         nfsvno_relpathbuf(ndp);
808                         vrele(ndp->ni_startdir);
809                         if (error)
810                                 goto out;
811                 } else {
812                         vrele(ndp->ni_startdir);
813                         nfsvno_relpathbuf(ndp);
814                         vput(ndp->ni_dvp);
815                         error = ENXIO;
816                         goto out;
817                 }
818                 *vpp = ndp->ni_vp;
819         } else {
820                 /*
821                  * Handle cases where error is already set and/or
822                  * the file exists.
823                  * 1 - clean up the lookup
824                  * 2 - iff !error and na_size set, truncate it
825                  */
826                 vrele(ndp->ni_startdir);
827                 nfsvno_relpathbuf(ndp);
828                 *vpp = ndp->ni_vp;
829                 if (ndp->ni_dvp == *vpp)
830                         vrele(ndp->ni_dvp);
831                 else
832                         vput(ndp->ni_dvp);
833                 if (!error && nvap->na_size != VNOVAL) {
834                         error = nfsvno_accchk(*vpp, VWRITE,
835                             nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
836                             NFSACCCHK_VPISLOCKED, NULL);
837                         if (!error) {
838                                 tempsize = nvap->na_size;
839                                 NFSVNO_ATTRINIT(nvap);
840                                 nvap->na_size = tempsize;
841                                 error = VOP_SETATTR(*vpp,
842                                     &nvap->na_vattr, nd->nd_cred);
843                         }
844                 }
845                 if (error)
846                         vput(*vpp);
847         }
848
849 out:
850         NFSEXITCODE(error);
851         return (error);
852 }
853
854 /*
855  * Do a mknod vnode op.
856  */
857 int
858 nfsvno_mknod(struct nameidata *ndp, struct nfsvattr *nvap, struct ucred *cred,
859     struct thread *p)
860 {
861         int error = 0;
862         enum vtype vtyp;
863
864         vtyp = nvap->na_type;
865         /*
866          * Iff doesn't exist, create it.
867          */
868         if (ndp->ni_vp) {
869                 vrele(ndp->ni_startdir);
870                 nfsvno_relpathbuf(ndp);
871                 vput(ndp->ni_dvp);
872                 vrele(ndp->ni_vp);
873                 error = EEXIST;
874                 goto out;
875         }
876         if (vtyp != VCHR && vtyp != VBLK && vtyp != VSOCK && vtyp != VFIFO) {
877                 vrele(ndp->ni_startdir);
878                 nfsvno_relpathbuf(ndp);
879                 vput(ndp->ni_dvp);
880                 error = NFSERR_BADTYPE;
881                 goto out;
882         }
883         if (vtyp == VSOCK) {
884                 vrele(ndp->ni_startdir);
885                 error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
886                     &ndp->ni_cnd, &nvap->na_vattr);
887                 vput(ndp->ni_dvp);
888                 nfsvno_relpathbuf(ndp);
889         } else {
890                 if (nvap->na_type != VFIFO &&
891                     (error = priv_check_cred(cred, PRIV_VFS_MKNOD_DEV, 0))) {
892                         vrele(ndp->ni_startdir);
893                         nfsvno_relpathbuf(ndp);
894                         vput(ndp->ni_dvp);
895                         goto out;
896                 }
897                 error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
898                     &ndp->ni_cnd, &nvap->na_vattr);
899                 vput(ndp->ni_dvp);
900                 nfsvno_relpathbuf(ndp);
901                 vrele(ndp->ni_startdir);
902                 /*
903                  * Since VOP_MKNOD returns the ni_vp, I can't
904                  * see any reason to do the lookup.
905                  */
906         }
907
908 out:
909         NFSEXITCODE(error);
910         return (error);
911 }
912
913 /*
914  * Mkdir vnode op.
915  */
916 int
917 nfsvno_mkdir(struct nameidata *ndp, struct nfsvattr *nvap, uid_t saved_uid,
918     struct ucred *cred, struct thread *p, struct nfsexstuff *exp)
919 {
920         int error = 0;
921
922         if (ndp->ni_vp != NULL) {
923                 if (ndp->ni_dvp == ndp->ni_vp)
924                         vrele(ndp->ni_dvp);
925                 else
926                         vput(ndp->ni_dvp);
927                 vrele(ndp->ni_vp);
928                 nfsvno_relpathbuf(ndp);
929                 error = EEXIST;
930                 goto out;
931         }
932         error = VOP_MKDIR(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
933             &nvap->na_vattr);
934         vput(ndp->ni_dvp);
935         nfsvno_relpathbuf(ndp);
936
937 out:
938         NFSEXITCODE(error);
939         return (error);
940 }
941
942 /*
943  * symlink vnode op.
944  */
945 int
946 nfsvno_symlink(struct nameidata *ndp, struct nfsvattr *nvap, char *pathcp,
947     int pathlen, int not_v2, uid_t saved_uid, struct ucred *cred, struct thread *p,
948     struct nfsexstuff *exp)
949 {
950         int error = 0;
951
952         if (ndp->ni_vp) {
953                 vrele(ndp->ni_startdir);
954                 nfsvno_relpathbuf(ndp);
955                 if (ndp->ni_dvp == ndp->ni_vp)
956                         vrele(ndp->ni_dvp);
957                 else
958                         vput(ndp->ni_dvp);
959                 vrele(ndp->ni_vp);
960                 error = EEXIST;
961                 goto out;
962         }
963
964         error = VOP_SYMLINK(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
965             &nvap->na_vattr, pathcp);
966         vput(ndp->ni_dvp);
967         vrele(ndp->ni_startdir);
968         nfsvno_relpathbuf(ndp);
969         /*
970          * Although FreeBSD still had the lookup code in
971          * it for 7/current, there doesn't seem to be any
972          * point, since VOP_SYMLINK() returns the ni_vp.
973          * Just vput it for v2.
974          */
975         if (!not_v2 && !error)
976                 vput(ndp->ni_vp);
977
978 out:
979         NFSEXITCODE(error);
980         return (error);
981 }
982
983 /*
984  * Parse symbolic link arguments.
985  * This function has an ugly side effect. It will MALLOC() an area for
986  * the symlink and set iov_base to point to it, only if it succeeds.
987  * So, if it returns with uiop->uio_iov->iov_base != NULL, that must
988  * be FREE'd later.
989  */
990 int
991 nfsvno_getsymlink(struct nfsrv_descript *nd, struct nfsvattr *nvap,
992     struct thread *p, char **pathcpp, int *lenp)
993 {
994         u_int32_t *tl;
995         char *pathcp = NULL;
996         int error = 0, len;
997         struct nfsv2_sattr *sp;
998
999         *pathcpp = NULL;
1000         *lenp = 0;
1001         if ((nd->nd_flag & ND_NFSV3) &&
1002             (error = nfsrv_sattr(nd, nvap, NULL, NULL, p)))
1003                 goto nfsmout;
1004         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
1005         len = fxdr_unsigned(int, *tl);
1006         if (len > NFS_MAXPATHLEN || len <= 0) {
1007                 error = EBADRPC;
1008                 goto nfsmout;
1009         }
1010         MALLOC(pathcp, caddr_t, len + 1, M_TEMP, M_WAITOK);
1011         error = nfsrv_mtostr(nd, pathcp, len);
1012         if (error)
1013                 goto nfsmout;
1014         if (nd->nd_flag & ND_NFSV2) {
1015                 NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
1016                 nvap->na_mode = fxdr_unsigned(u_int16_t, sp->sa_mode);
1017         }
1018         *pathcpp = pathcp;
1019         *lenp = len;
1020         NFSEXITCODE2(0, nd);
1021         return (0);
1022 nfsmout:
1023         if (pathcp)
1024                 free(pathcp, M_TEMP);
1025         NFSEXITCODE2(error, nd);
1026         return (error);
1027 }
1028
1029 /*
1030  * Remove a non-directory object.
1031  */
1032 int
1033 nfsvno_removesub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1034     struct thread *p, struct nfsexstuff *exp)
1035 {
1036         struct vnode *vp;
1037         int error = 0;
1038
1039         vp = ndp->ni_vp;
1040         if (vp->v_type == VDIR)
1041                 error = NFSERR_ISDIR;
1042         else if (is_v4)
1043                 error = nfsrv_checkremove(vp, 1, p);
1044         if (!error)
1045                 error = VOP_REMOVE(ndp->ni_dvp, vp, &ndp->ni_cnd);
1046         if (ndp->ni_dvp == vp)
1047                 vrele(ndp->ni_dvp);
1048         else
1049                 vput(ndp->ni_dvp);
1050         vput(vp);
1051         if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1052                 nfsvno_relpathbuf(ndp);
1053         NFSEXITCODE(error);
1054         return (error);
1055 }
1056
1057 /*
1058  * Remove a directory.
1059  */
1060 int
1061 nfsvno_rmdirsub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1062     struct thread *p, struct nfsexstuff *exp)
1063 {
1064         struct vnode *vp;
1065         int error = 0;
1066
1067         vp = ndp->ni_vp;
1068         if (vp->v_type != VDIR) {
1069                 error = ENOTDIR;
1070                 goto out;
1071         }
1072         /*
1073          * No rmdir "." please.
1074          */
1075         if (ndp->ni_dvp == vp) {
1076                 error = EINVAL;
1077                 goto out;
1078         }
1079         /*
1080          * The root of a mounted filesystem cannot be deleted.
1081          */
1082         if (vp->v_vflag & VV_ROOT)
1083                 error = EBUSY;
1084 out:
1085         if (!error)
1086                 error = VOP_RMDIR(ndp->ni_dvp, vp, &ndp->ni_cnd);
1087         if (ndp->ni_dvp == vp)
1088                 vrele(ndp->ni_dvp);
1089         else
1090                 vput(ndp->ni_dvp);
1091         vput(vp);
1092         if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1093                 nfsvno_relpathbuf(ndp);
1094         NFSEXITCODE(error);
1095         return (error);
1096 }
1097
1098 /*
1099  * Rename vnode op.
1100  */
1101 int
1102 nfsvno_rename(struct nameidata *fromndp, struct nameidata *tondp,
1103     u_int32_t ndstat, u_int32_t ndflag, struct ucred *cred, struct thread *p)
1104 {
1105         struct vnode *fvp, *tvp, *tdvp;
1106         int error = 0;
1107
1108         fvp = fromndp->ni_vp;
1109         if (ndstat) {
1110                 vrele(fromndp->ni_dvp);
1111                 vrele(fvp);
1112                 error = ndstat;
1113                 goto out1;
1114         }
1115         tdvp = tondp->ni_dvp;
1116         tvp = tondp->ni_vp;
1117         if (tvp != NULL) {
1118                 if (fvp->v_type == VDIR && tvp->v_type != VDIR) {
1119                         error = (ndflag & ND_NFSV2) ? EISDIR : EEXIST;
1120                         goto out;
1121                 } else if (fvp->v_type != VDIR && tvp->v_type == VDIR) {
1122                         error = (ndflag & ND_NFSV2) ? ENOTDIR : EEXIST;
1123                         goto out;
1124                 }
1125                 if (tvp->v_type == VDIR && tvp->v_mountedhere) {
1126                         error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1127                         goto out;
1128                 }
1129
1130                 /*
1131                  * A rename to '.' or '..' results in a prematurely
1132                  * unlocked vnode on FreeBSD5, so I'm just going to fail that
1133                  * here.
1134                  */
1135                 if ((tondp->ni_cnd.cn_namelen == 1 &&
1136                      tondp->ni_cnd.cn_nameptr[0] == '.') ||
1137                     (tondp->ni_cnd.cn_namelen == 2 &&
1138                      tondp->ni_cnd.cn_nameptr[0] == '.' &&
1139                      tondp->ni_cnd.cn_nameptr[1] == '.')) {
1140                         error = EINVAL;
1141                         goto out;
1142                 }
1143         }
1144         if (fvp->v_type == VDIR && fvp->v_mountedhere) {
1145                 error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1146                 goto out;
1147         }
1148         if (fvp->v_mount != tdvp->v_mount) {
1149                 error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1150                 goto out;
1151         }
1152         if (fvp == tdvp) {
1153                 error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EINVAL;
1154                 goto out;
1155         }
1156         if (fvp == tvp) {
1157                 /*
1158                  * If source and destination are the same, there is nothing to
1159                  * do. Set error to -1 to indicate this.
1160                  */
1161                 error = -1;
1162                 goto out;
1163         }
1164         if (ndflag & ND_NFSV4) {
1165                 if (NFSVOPLOCK(fvp, LK_EXCLUSIVE) == 0) {
1166                         error = nfsrv_checkremove(fvp, 0, p);
1167                         NFSVOPUNLOCK(fvp, 0);
1168                 } else
1169                         error = EPERM;
1170                 if (tvp && !error)
1171                         error = nfsrv_checkremove(tvp, 1, p);
1172         } else {
1173                 /*
1174                  * For NFSv2 and NFSv3, try to get rid of the delegation, so
1175                  * that the NFSv4 client won't be confused by the rename.
1176                  * Since nfsd_recalldelegation() can only be called on an
1177                  * unlocked vnode at this point and fvp is the file that will
1178                  * still exist after the rename, just do fvp.
1179                  */
1180                 nfsd_recalldelegation(fvp, p);
1181         }
1182 out:
1183         if (!error) {
1184                 error = VOP_RENAME(fromndp->ni_dvp, fromndp->ni_vp,
1185                     &fromndp->ni_cnd, tondp->ni_dvp, tondp->ni_vp,
1186                     &tondp->ni_cnd);
1187         } else {
1188                 if (tdvp == tvp)
1189                         vrele(tdvp);
1190                 else
1191                         vput(tdvp);
1192                 if (tvp)
1193                         vput(tvp);
1194                 vrele(fromndp->ni_dvp);
1195                 vrele(fvp);
1196                 if (error == -1)
1197                         error = 0;
1198         }
1199         vrele(tondp->ni_startdir);
1200         nfsvno_relpathbuf(tondp);
1201 out1:
1202         vrele(fromndp->ni_startdir);
1203         nfsvno_relpathbuf(fromndp);
1204         NFSEXITCODE(error);
1205         return (error);
1206 }
1207
1208 /*
1209  * Link vnode op.
1210  */
1211 int
1212 nfsvno_link(struct nameidata *ndp, struct vnode *vp, struct ucred *cred,
1213     struct thread *p, struct nfsexstuff *exp)
1214 {
1215         struct vnode *xp;
1216         int error = 0;
1217
1218         xp = ndp->ni_vp;
1219         if (xp != NULL) {
1220                 error = EEXIST;
1221         } else {
1222                 xp = ndp->ni_dvp;
1223                 if (vp->v_mount != xp->v_mount)
1224                         error = EXDEV;
1225         }
1226         if (!error) {
1227                 NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
1228                 if ((vp->v_iflag & VI_DOOMED) == 0)
1229                         error = VOP_LINK(ndp->ni_dvp, vp, &ndp->ni_cnd);
1230                 else
1231                         error = EPERM;
1232                 if (ndp->ni_dvp == vp)
1233                         vrele(ndp->ni_dvp);
1234                 else
1235                         vput(ndp->ni_dvp);
1236                 NFSVOPUNLOCK(vp, 0);
1237         } else {
1238                 if (ndp->ni_dvp == ndp->ni_vp)
1239                         vrele(ndp->ni_dvp);
1240                 else
1241                         vput(ndp->ni_dvp);
1242                 if (ndp->ni_vp)
1243                         vrele(ndp->ni_vp);
1244         }
1245         nfsvno_relpathbuf(ndp);
1246         NFSEXITCODE(error);
1247         return (error);
1248 }
1249
1250 /*
1251  * Do the fsync() appropriate for the commit.
1252  */
1253 int
1254 nfsvno_fsync(struct vnode *vp, u_int64_t off, int cnt, struct ucred *cred,
1255     struct thread *td)
1256 {
1257         int error = 0;
1258
1259         /*
1260          * RFC 1813 3.3.21: if count is 0, a flush from offset to the end of
1261          * file is done.  At this time VOP_FSYNC does not accept offset and
1262          * byte count parameters so call VOP_FSYNC the whole file for now.
1263          * The same is true for NFSv4: RFC 3530 Sec. 14.2.3.
1264          */
1265         if (cnt == 0 || cnt > MAX_COMMIT_COUNT) {
1266                 /*
1267                  * Give up and do the whole thing
1268                  */
1269                 if (vp->v_object &&
1270                    (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
1271                         VM_OBJECT_LOCK(vp->v_object);
1272                         vm_object_page_clean(vp->v_object, 0, 0, OBJPC_SYNC);
1273                         VM_OBJECT_UNLOCK(vp->v_object);
1274                 }
1275                 error = VOP_FSYNC(vp, MNT_WAIT, td);
1276         } else {
1277                 /*
1278                  * Locate and synchronously write any buffers that fall
1279                  * into the requested range.  Note:  we are assuming that
1280                  * f_iosize is a power of 2.
1281                  */
1282                 int iosize = vp->v_mount->mnt_stat.f_iosize;
1283                 int iomask = iosize - 1;
1284                 struct bufobj *bo;
1285                 daddr_t lblkno;
1286
1287                 /*
1288                  * Align to iosize boundry, super-align to page boundry.
1289                  */
1290                 if (off & iomask) {
1291                         cnt += off & iomask;
1292                         off &= ~(u_quad_t)iomask;
1293                 }
1294                 if (off & PAGE_MASK) {
1295                         cnt += off & PAGE_MASK;
1296                         off &= ~(u_quad_t)PAGE_MASK;
1297                 }
1298                 lblkno = off / iosize;
1299
1300                 if (vp->v_object &&
1301                    (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
1302                         VM_OBJECT_LOCK(vp->v_object);
1303                         vm_object_page_clean(vp->v_object, off, off + cnt,
1304                             OBJPC_SYNC);
1305                         VM_OBJECT_UNLOCK(vp->v_object);
1306                 }
1307
1308                 bo = &vp->v_bufobj;
1309                 BO_LOCK(bo);
1310                 while (cnt > 0) {
1311                         struct buf *bp;
1312
1313                         /*
1314                          * If we have a buffer and it is marked B_DELWRI we
1315                          * have to lock and write it.  Otherwise the prior
1316                          * write is assumed to have already been committed.
1317                          *
1318                          * gbincore() can return invalid buffers now so we
1319                          * have to check that bit as well (though B_DELWRI
1320                          * should not be set if B_INVAL is set there could be
1321                          * a race here since we haven't locked the buffer).
1322                          */
1323                         if ((bp = gbincore(&vp->v_bufobj, lblkno)) != NULL) {
1324                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
1325                                     LK_INTERLOCK, BO_MTX(bo)) == ENOLCK) {
1326                                         BO_LOCK(bo);
1327                                         continue; /* retry */
1328                                 }
1329                                 if ((bp->b_flags & (B_DELWRI|B_INVAL)) ==
1330                                     B_DELWRI) {
1331                                         bremfree(bp);
1332                                         bp->b_flags &= ~B_ASYNC;
1333                                         bwrite(bp);
1334                                         ++nfs_commit_miss;
1335                                 } else
1336                                         BUF_UNLOCK(bp);
1337                                 BO_LOCK(bo);
1338                         }
1339                         ++nfs_commit_blks;
1340                         if (cnt < iosize)
1341                                 break;
1342                         cnt -= iosize;
1343                         ++lblkno;
1344                 }
1345                 BO_UNLOCK(bo);
1346         }
1347         NFSEXITCODE(error);
1348         return (error);
1349 }
1350
1351 /*
1352  * Statfs vnode op.
1353  */
1354 int
1355 nfsvno_statfs(struct vnode *vp, struct statfs *sf)
1356 {
1357         int error;
1358
1359         error = VFS_STATFS(vp->v_mount, sf);
1360         if (error == 0) {
1361                 /*
1362                  * Since NFS handles these values as unsigned on the
1363                  * wire, there is no way to represent negative values,
1364                  * so set them to 0. Without this, they will appear
1365                  * to be very large positive values for clients like
1366                  * Solaris10.
1367                  */
1368                 if (sf->f_bavail < 0)
1369                         sf->f_bavail = 0;
1370                 if (sf->f_ffree < 0)
1371                         sf->f_ffree = 0;
1372         }
1373         NFSEXITCODE(error);
1374         return (error);
1375 }
1376
1377 /*
1378  * Do the vnode op stuff for Open. Similar to nfsvno_createsub(), but
1379  * must handle nfsrv_opencheck() calls after any other access checks.
1380  */
1381 void
1382 nfsvno_open(struct nfsrv_descript *nd, struct nameidata *ndp,
1383     nfsquad_t clientid, nfsv4stateid_t *stateidp, struct nfsstate *stp,
1384     int *exclusive_flagp, struct nfsvattr *nvap, int32_t *cverf, int create,
1385     NFSACL_T *aclp, nfsattrbit_t *attrbitp, struct ucred *cred, struct thread *p,
1386     struct nfsexstuff *exp, struct vnode **vpp)
1387 {
1388         struct vnode *vp = NULL;
1389         u_quad_t tempsize;
1390         struct nfsexstuff nes;
1391
1392         if (ndp->ni_vp == NULL)
1393                 nd->nd_repstat = nfsrv_opencheck(clientid,
1394                     stateidp, stp, NULL, nd, p, nd->nd_repstat);
1395         if (!nd->nd_repstat) {
1396                 if (ndp->ni_vp == NULL) {
1397                         vrele(ndp->ni_startdir);
1398                         nd->nd_repstat = VOP_CREATE(ndp->ni_dvp,
1399                             &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
1400                         vput(ndp->ni_dvp);
1401                         nfsvno_relpathbuf(ndp);
1402                         if (!nd->nd_repstat) {
1403                                 if (*exclusive_flagp) {
1404                                         *exclusive_flagp = 0;
1405                                         NFSVNO_ATTRINIT(nvap);
1406                                         nvap->na_atime.tv_sec = cverf[0];
1407                                         nvap->na_atime.tv_nsec = cverf[1];
1408                                         nd->nd_repstat = VOP_SETATTR(ndp->ni_vp,
1409                                             &nvap->na_vattr, cred);
1410                                 } else {
1411                                         nfsrv_fixattr(nd, ndp->ni_vp, nvap,
1412                                             aclp, p, attrbitp, exp);
1413                                 }
1414                         }
1415                         vp = ndp->ni_vp;
1416                 } else {
1417                         if (ndp->ni_startdir)
1418                                 vrele(ndp->ni_startdir);
1419                         nfsvno_relpathbuf(ndp);
1420                         vp = ndp->ni_vp;
1421                         if (create == NFSV4OPEN_CREATE) {
1422                                 if (ndp->ni_dvp == vp)
1423                                         vrele(ndp->ni_dvp);
1424                                 else
1425                                         vput(ndp->ni_dvp);
1426                         }
1427                         if (NFSVNO_ISSETSIZE(nvap) && vp->v_type == VREG) {
1428                                 if (ndp->ni_cnd.cn_flags & RDONLY)
1429                                         NFSVNO_SETEXRDONLY(&nes);
1430                                 else
1431                                         NFSVNO_EXINIT(&nes);
1432                                 nd->nd_repstat = nfsvno_accchk(vp, 
1433                                     VWRITE, cred, &nes, p,
1434                                     NFSACCCHK_NOOVERRIDE,
1435                                     NFSACCCHK_VPISLOCKED, NULL);
1436                                 nd->nd_repstat = nfsrv_opencheck(clientid,
1437                                     stateidp, stp, vp, nd, p, nd->nd_repstat);
1438                                 if (!nd->nd_repstat) {
1439                                         tempsize = nvap->na_size;
1440                                         NFSVNO_ATTRINIT(nvap);
1441                                         nvap->na_size = tempsize;
1442                                         nd->nd_repstat = VOP_SETATTR(vp,
1443                                             &nvap->na_vattr, cred);
1444                                 }
1445                         } else if (vp->v_type == VREG) {
1446                                 nd->nd_repstat = nfsrv_opencheck(clientid,
1447                                     stateidp, stp, vp, nd, p, nd->nd_repstat);
1448                         }
1449                 }
1450         } else {
1451                 if (ndp->ni_cnd.cn_flags & HASBUF)
1452                         nfsvno_relpathbuf(ndp);
1453                 if (ndp->ni_startdir && create == NFSV4OPEN_CREATE) {
1454                         vrele(ndp->ni_startdir);
1455                         if (ndp->ni_dvp == ndp->ni_vp)
1456                                 vrele(ndp->ni_dvp);
1457                         else
1458                                 vput(ndp->ni_dvp);
1459                         if (ndp->ni_vp)
1460                                 vput(ndp->ni_vp);
1461                 }
1462         }
1463         *vpp = vp;
1464
1465         NFSEXITCODE2(0, nd);
1466 }
1467
1468 /*
1469  * Updates the file rev and sets the mtime and ctime
1470  * to the current clock time, returning the va_filerev and va_Xtime
1471  * values.
1472  */
1473 void
1474 nfsvno_updfilerev(struct vnode *vp, struct nfsvattr *nvap,
1475     struct ucred *cred, struct thread *p)
1476 {
1477         struct vattr va;
1478
1479         VATTR_NULL(&va);
1480         getnanotime(&va.va_mtime);
1481         (void) VOP_SETATTR(vp, &va, cred);
1482         (void) nfsvno_getattr(vp, nvap, cred, p, 1);
1483 }
1484
1485 /*
1486  * Glue routine to nfsv4_fillattr().
1487  */
1488 int
1489 nfsvno_fillattr(struct nfsrv_descript *nd, struct mount *mp, struct vnode *vp,
1490     struct nfsvattr *nvap, fhandle_t *fhp, int rderror, nfsattrbit_t *attrbitp,
1491     struct ucred *cred, struct thread *p, int isdgram, int reterr,
1492     int supports_nfsv4acls, int at_root, uint64_t mounted_on_fileno)
1493 {
1494         int error;
1495
1496         error = nfsv4_fillattr(nd, mp, vp, NULL, &nvap->na_vattr, fhp, rderror,
1497             attrbitp, cred, p, isdgram, reterr, supports_nfsv4acls, at_root,
1498             mounted_on_fileno);
1499         NFSEXITCODE2(0, nd);
1500         return (error);
1501 }
1502
1503 /* Since the Readdir vnode ops vary, put the entire functions in here. */
1504 /*
1505  * nfs readdir service
1506  * - mallocs what it thinks is enough to read
1507  *      count rounded up to a multiple of DIRBLKSIZ <= NFS_MAXREADDIR
1508  * - calls VOP_READDIR()
1509  * - loops around building the reply
1510  *      if the output generated exceeds count break out of loop
1511  *      The NFSM_CLGET macro is used here so that the reply will be packed
1512  *      tightly in mbuf clusters.
1513  * - it trims out records with d_fileno == 0
1514  *      this doesn't matter for Unix clients, but they might confuse clients
1515  *      for other os'.
1516  * - it trims out records with d_type == DT_WHT
1517  *      these cannot be seen through NFS (unless we extend the protocol)
1518  *     The alternate call nfsrvd_readdirplus() does lookups as well.
1519  * PS: The NFS protocol spec. does not clarify what the "count" byte
1520  *      argument is a count of.. just name strings and file id's or the
1521  *      entire reply rpc or ...
1522  *      I tried just file name and id sizes and it confused the Sun client,
1523  *      so I am using the full rpc size now. The "paranoia.." comment refers
1524  *      to including the status longwords that are not a part of the dir.
1525  *      "entry" structures, but are in the rpc.
1526  */
1527 int
1528 nfsrvd_readdir(struct nfsrv_descript *nd, int isdgram,
1529     struct vnode *vp, struct thread *p, struct nfsexstuff *exp)
1530 {
1531         struct dirent *dp;
1532         u_int32_t *tl;
1533         int dirlen;
1534         char *cpos, *cend, *rbuf;
1535         struct nfsvattr at;
1536         int nlen, error = 0, getret = 1;
1537         int siz, cnt, fullsiz, eofflag, ncookies;
1538         u_int64_t off, toff, verf;
1539         u_long *cookies = NULL, *cookiep;
1540         struct uio io;
1541         struct iovec iv;
1542         int not_zfs;
1543
1544         if (nd->nd_repstat) {
1545                 nfsrv_postopattr(nd, getret, &at);
1546                 goto out;
1547         }
1548         if (nd->nd_flag & ND_NFSV2) {
1549                 NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1550                 off = fxdr_unsigned(u_quad_t, *tl++);
1551         } else {
1552                 NFSM_DISSECT(tl, u_int32_t *, 5 * NFSX_UNSIGNED);
1553                 off = fxdr_hyper(tl);
1554                 tl += 2;
1555                 verf = fxdr_hyper(tl);
1556                 tl += 2;
1557         }
1558         toff = off;
1559         cnt = fxdr_unsigned(int, *tl);
1560         if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
1561                 cnt = NFS_SRVMAXDATA(nd);
1562         siz = ((cnt + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
1563         fullsiz = siz;
1564         if (nd->nd_flag & ND_NFSV3) {
1565                 nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd->nd_cred,
1566                     p, 1);
1567 #if 0
1568                 /*
1569                  * va_filerev is not sufficient as a cookie verifier,
1570                  * since it is not supposed to change when entries are
1571                  * removed/added unless that offset cookies returned to
1572                  * the client are no longer valid.
1573                  */
1574                 if (!nd->nd_repstat && toff && verf != at.na_filerev)
1575                         nd->nd_repstat = NFSERR_BAD_COOKIE;
1576 #endif
1577         }
1578         if (nd->nd_repstat == 0 && cnt == 0) {
1579                 if (nd->nd_flag & ND_NFSV2)
1580                         /* NFSv2 does not have NFSERR_TOOSMALL */
1581                         nd->nd_repstat = EPERM;
1582                 else
1583                         nd->nd_repstat = NFSERR_TOOSMALL;
1584         }
1585         if (!nd->nd_repstat)
1586                 nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
1587                     nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1588                     NFSACCCHK_VPISLOCKED, NULL);
1589         if (nd->nd_repstat) {
1590                 vput(vp);
1591                 if (nd->nd_flag & ND_NFSV3)
1592                         nfsrv_postopattr(nd, getret, &at);
1593                 goto out;
1594         }
1595         not_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs");
1596         MALLOC(rbuf, caddr_t, siz, M_TEMP, M_WAITOK);
1597 again:
1598         eofflag = 0;
1599         if (cookies) {
1600                 free((caddr_t)cookies, M_TEMP);
1601                 cookies = NULL;
1602         }
1603
1604         iv.iov_base = rbuf;
1605         iv.iov_len = siz;
1606         io.uio_iov = &iv;
1607         io.uio_iovcnt = 1;
1608         io.uio_offset = (off_t)off;
1609         io.uio_resid = siz;
1610         io.uio_segflg = UIO_SYSSPACE;
1611         io.uio_rw = UIO_READ;
1612         io.uio_td = NULL;
1613         nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
1614             &cookies);
1615         off = (u_int64_t)io.uio_offset;
1616         if (io.uio_resid)
1617                 siz -= io.uio_resid;
1618
1619         if (!cookies && !nd->nd_repstat)
1620                 nd->nd_repstat = NFSERR_PERM;
1621         if (nd->nd_flag & ND_NFSV3) {
1622                 getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1623                 if (!nd->nd_repstat)
1624                         nd->nd_repstat = getret;
1625         }
1626
1627         /*
1628          * Handles the failed cases. nd->nd_repstat == 0 past here.
1629          */
1630         if (nd->nd_repstat) {
1631                 vput(vp);
1632                 free((caddr_t)rbuf, M_TEMP);
1633                 if (cookies)
1634                         free((caddr_t)cookies, M_TEMP);
1635                 if (nd->nd_flag & ND_NFSV3)
1636                         nfsrv_postopattr(nd, getret, &at);
1637                 goto out;
1638         }
1639         /*
1640          * If nothing read, return eof
1641          * rpc reply
1642          */
1643         if (siz == 0) {
1644                 vput(vp);
1645                 if (nd->nd_flag & ND_NFSV2) {
1646                         NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1647                 } else {
1648                         nfsrv_postopattr(nd, getret, &at);
1649                         NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
1650                         txdr_hyper(at.na_filerev, tl);
1651                         tl += 2;
1652                 }
1653                 *tl++ = newnfs_false;
1654                 *tl = newnfs_true;
1655                 FREE((caddr_t)rbuf, M_TEMP);
1656                 FREE((caddr_t)cookies, M_TEMP);
1657                 goto out;
1658         }
1659
1660         /*
1661          * Check for degenerate cases of nothing useful read.
1662          * If so go try again
1663          */
1664         cpos = rbuf;
1665         cend = rbuf + siz;
1666         dp = (struct dirent *)cpos;
1667         cookiep = cookies;
1668
1669         /*
1670          * For some reason FreeBSD's ufs_readdir() chooses to back the
1671          * directory offset up to a block boundary, so it is necessary to
1672          * skip over the records that precede the requested offset. This
1673          * requires the assumption that file offset cookies monotonically
1674          * increase.
1675          * Since the offset cookies don't monotonically increase for ZFS,
1676          * this is not done when ZFS is the file system.
1677          */
1678         while (cpos < cend && ncookies > 0 &&
1679             (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
1680              (not_zfs != 0 && ((u_quad_t)(*cookiep)) <= toff))) {
1681                 cpos += dp->d_reclen;
1682                 dp = (struct dirent *)cpos;
1683                 cookiep++;
1684                 ncookies--;
1685         }
1686         if (cpos >= cend || ncookies == 0) {
1687                 siz = fullsiz;
1688                 toff = off;
1689                 goto again;
1690         }
1691         vput(vp);
1692
1693         /*
1694          * dirlen is the size of the reply, including all XDR and must
1695          * not exceed cnt. For NFSv2, RFC1094 didn't clearly indicate
1696          * if the XDR should be included in "count", but to be safe, we do.
1697          * (Include the two booleans at the end of the reply in dirlen now.)
1698          */
1699         if (nd->nd_flag & ND_NFSV3) {
1700                 nfsrv_postopattr(nd, getret, &at);
1701                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1702                 txdr_hyper(at.na_filerev, tl);
1703                 dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
1704         } else {
1705                 dirlen = 2 * NFSX_UNSIGNED;
1706         }
1707
1708         /* Loop through the records and build reply */
1709         while (cpos < cend && ncookies > 0) {
1710                 nlen = dp->d_namlen;
1711                 if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
1712                         nlen <= NFS_MAXNAMLEN) {
1713                         if (nd->nd_flag & ND_NFSV3)
1714                                 dirlen += (6*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
1715                         else
1716                                 dirlen += (4*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
1717                         if (dirlen > cnt) {
1718                                 eofflag = 0;
1719                                 break;
1720                         }
1721
1722                         /*
1723                          * Build the directory record xdr from
1724                          * the dirent entry.
1725                          */
1726                         if (nd->nd_flag & ND_NFSV3) {
1727                                 NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
1728                                 *tl++ = newnfs_true;
1729                                 *tl++ = 0;
1730                         } else {
1731                                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1732                                 *tl++ = newnfs_true;
1733                         }
1734                         *tl = txdr_unsigned(dp->d_fileno);
1735                         (void) nfsm_strtom(nd, dp->d_name, nlen);
1736                         if (nd->nd_flag & ND_NFSV3) {
1737                                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1738                                 *tl++ = 0;
1739                         } else
1740                                 NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
1741                         *tl = txdr_unsigned(*cookiep);
1742                 }
1743                 cpos += dp->d_reclen;
1744                 dp = (struct dirent *)cpos;
1745                 cookiep++;
1746                 ncookies--;
1747         }
1748         if (cpos < cend)
1749                 eofflag = 0;
1750         NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1751         *tl++ = newnfs_false;
1752         if (eofflag)
1753                 *tl = newnfs_true;
1754         else
1755                 *tl = newnfs_false;
1756         FREE((caddr_t)rbuf, M_TEMP);
1757         FREE((caddr_t)cookies, M_TEMP);
1758
1759 out:
1760         NFSEXITCODE2(0, nd);
1761         return (0);
1762 nfsmout:
1763         vput(vp);
1764         NFSEXITCODE2(error, nd);
1765         return (error);
1766 }
1767
1768 /*
1769  * Readdirplus for V3 and Readdir for V4.
1770  */
1771 int
1772 nfsrvd_readdirplus(struct nfsrv_descript *nd, int isdgram,
1773     struct vnode *vp, struct thread *p, struct nfsexstuff *exp)
1774 {
1775         struct dirent *dp;
1776         u_int32_t *tl;
1777         int dirlen;
1778         char *cpos, *cend, *rbuf;
1779         struct vnode *nvp;
1780         fhandle_t nfh;
1781         struct nfsvattr nva, at, *nvap = &nva;
1782         struct mbuf *mb0, *mb1;
1783         struct nfsreferral *refp;
1784         int nlen, r, error = 0, getret = 1, usevget = 1;
1785         int siz, cnt, fullsiz, eofflag, ncookies, entrycnt;
1786         caddr_t bpos0, bpos1;
1787         u_int64_t off, toff, verf;
1788         u_long *cookies = NULL, *cookiep;
1789         nfsattrbit_t attrbits, rderrbits, savbits;
1790         struct uio io;
1791         struct iovec iv;
1792         struct componentname cn;
1793         int at_root, needs_unbusy, not_zfs, supports_nfsv4acls;
1794         struct mount *mp, *new_mp;
1795         uint64_t mounted_on_fileno;
1796
1797         if (nd->nd_repstat) {
1798                 nfsrv_postopattr(nd, getret, &at);
1799                 goto out;
1800         }
1801         NFSM_DISSECT(tl, u_int32_t *, 6 * NFSX_UNSIGNED);
1802         off = fxdr_hyper(tl);
1803         toff = off;
1804         tl += 2;
1805         verf = fxdr_hyper(tl);
1806         tl += 2;
1807         siz = fxdr_unsigned(int, *tl++);
1808         cnt = fxdr_unsigned(int, *tl);
1809
1810         /*
1811          * Use the server's maximum data transfer size as the upper bound
1812          * on reply datalen.
1813          */
1814         if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
1815                 cnt = NFS_SRVMAXDATA(nd);
1816
1817         /*
1818          * siz is a "hint" of how much directory information (name, fileid,
1819          * cookie) should be in the reply. At least one client "hints" 0,
1820          * so I set it to cnt for that case. I also round it up to the
1821          * next multiple of DIRBLKSIZ.
1822          */
1823         if (siz <= 0)
1824                 siz = cnt;
1825         siz = ((siz + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
1826
1827         if (nd->nd_flag & ND_NFSV4) {
1828                 error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
1829                 if (error)
1830                         goto nfsmout;
1831                 NFSSET_ATTRBIT(&savbits, &attrbits);
1832                 NFSCLRNOTFILLABLE_ATTRBIT(&attrbits);
1833                 NFSZERO_ATTRBIT(&rderrbits);
1834                 NFSSETBIT_ATTRBIT(&rderrbits, NFSATTRBIT_RDATTRERROR);
1835         } else {
1836                 NFSZERO_ATTRBIT(&attrbits);
1837         }
1838         fullsiz = siz;
1839         nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1840         if (!nd->nd_repstat) {
1841             if (off && verf != at.na_filerev) {
1842                 /*
1843                  * va_filerev is not sufficient as a cookie verifier,
1844                  * since it is not supposed to change when entries are
1845                  * removed/added unless that offset cookies returned to
1846                  * the client are no longer valid.
1847                  */
1848 #if 0
1849                 if (nd->nd_flag & ND_NFSV4) {
1850                         nd->nd_repstat = NFSERR_NOTSAME;
1851                 } else {
1852                         nd->nd_repstat = NFSERR_BAD_COOKIE;
1853                 }
1854 #endif
1855             } else if ((nd->nd_flag & ND_NFSV4) && off == 0 && verf != 0) {
1856                 nd->nd_repstat = NFSERR_BAD_COOKIE;
1857             }
1858         }
1859         if (!nd->nd_repstat && vp->v_type != VDIR)
1860                 nd->nd_repstat = NFSERR_NOTDIR;
1861         if (!nd->nd_repstat && cnt == 0)
1862                 nd->nd_repstat = NFSERR_TOOSMALL;
1863         if (!nd->nd_repstat)
1864                 nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
1865                     nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1866                     NFSACCCHK_VPISLOCKED, NULL);
1867         if (nd->nd_repstat) {
1868                 vput(vp);
1869                 if (nd->nd_flag & ND_NFSV3)
1870                         nfsrv_postopattr(nd, getret, &at);
1871                 goto out;
1872         }
1873         not_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs");
1874
1875         MALLOC(rbuf, caddr_t, siz, M_TEMP, M_WAITOK);
1876 again:
1877         eofflag = 0;
1878         if (cookies) {
1879                 free((caddr_t)cookies, M_TEMP);
1880                 cookies = NULL;
1881         }
1882
1883         iv.iov_base = rbuf;
1884         iv.iov_len = siz;
1885         io.uio_iov = &iv;
1886         io.uio_iovcnt = 1;
1887         io.uio_offset = (off_t)off;
1888         io.uio_resid = siz;
1889         io.uio_segflg = UIO_SYSSPACE;
1890         io.uio_rw = UIO_READ;
1891         io.uio_td = NULL;
1892         nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
1893             &cookies);
1894         off = (u_int64_t)io.uio_offset;
1895         if (io.uio_resid)
1896                 siz -= io.uio_resid;
1897
1898         getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1899
1900         if (!cookies && !nd->nd_repstat)
1901                 nd->nd_repstat = NFSERR_PERM;
1902         if (!nd->nd_repstat)
1903                 nd->nd_repstat = getret;
1904         if (nd->nd_repstat) {
1905                 vput(vp);
1906                 if (cookies)
1907                         free((caddr_t)cookies, M_TEMP);
1908                 free((caddr_t)rbuf, M_TEMP);
1909                 if (nd->nd_flag & ND_NFSV3)
1910                         nfsrv_postopattr(nd, getret, &at);
1911                 goto out;
1912         }
1913         /*
1914          * If nothing read, return eof
1915          * rpc reply
1916          */
1917         if (siz == 0) {
1918                 vput(vp);
1919                 if (nd->nd_flag & ND_NFSV3)
1920                         nfsrv_postopattr(nd, getret, &at);
1921                 NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
1922                 txdr_hyper(at.na_filerev, tl);
1923                 tl += 2;
1924                 *tl++ = newnfs_false;
1925                 *tl = newnfs_true;
1926                 free((caddr_t)cookies, M_TEMP);
1927                 free((caddr_t)rbuf, M_TEMP);
1928                 goto out;
1929         }
1930
1931         /*
1932          * Check for degenerate cases of nothing useful read.
1933          * If so go try again
1934          */
1935         cpos = rbuf;
1936         cend = rbuf + siz;
1937         dp = (struct dirent *)cpos;
1938         cookiep = cookies;
1939
1940         /*
1941          * For some reason FreeBSD's ufs_readdir() chooses to back the
1942          * directory offset up to a block boundary, so it is necessary to
1943          * skip over the records that precede the requested offset. This
1944          * requires the assumption that file offset cookies monotonically
1945          * increase.
1946          * Since the offset cookies don't monotonically increase for ZFS,
1947          * this is not done when ZFS is the file system.
1948          */
1949         while (cpos < cend && ncookies > 0 &&
1950           (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
1951            (not_zfs != 0 && ((u_quad_t)(*cookiep)) <= toff) ||
1952            ((nd->nd_flag & ND_NFSV4) &&
1953             ((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
1954              (dp->d_namlen==2 && dp->d_name[0]=='.' && dp->d_name[1]=='.'))))) {
1955                 cpos += dp->d_reclen;
1956                 dp = (struct dirent *)cpos;
1957                 cookiep++;
1958                 ncookies--;
1959         }
1960         if (cpos >= cend || ncookies == 0) {
1961                 siz = fullsiz;
1962                 toff = off;
1963                 goto again;
1964         }
1965
1966         /*
1967          * Busy the file system so that the mount point won't go away
1968          * and, as such, VFS_VGET() can be used safely.
1969          */
1970         mp = vp->v_mount;
1971         vfs_ref(mp);
1972         NFSVOPUNLOCK(vp, 0);
1973         nd->nd_repstat = vfs_busy(mp, 0);
1974         vfs_rel(mp);
1975         if (nd->nd_repstat != 0) {
1976                 vrele(vp);
1977                 free(cookies, M_TEMP);
1978                 free(rbuf, M_TEMP);
1979                 if (nd->nd_flag & ND_NFSV3)
1980                         nfsrv_postopattr(nd, getret, &at);
1981                 goto out;
1982         }
1983
1984         /*
1985          * Save this position, in case there is an error before one entry
1986          * is created.
1987          */
1988         mb0 = nd->nd_mb;
1989         bpos0 = nd->nd_bpos;
1990
1991         /*
1992          * Fill in the first part of the reply.
1993          * dirlen is the reply length in bytes and cannot exceed cnt.
1994          * (Include the two booleans at the end of the reply in dirlen now,
1995          *  so we recognize when we have exceeded cnt.)
1996          */
1997         if (nd->nd_flag & ND_NFSV3) {
1998                 dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
1999                 nfsrv_postopattr(nd, getret, &at);
2000         } else {
2001                 dirlen = NFSX_VERF + 2 * NFSX_UNSIGNED;
2002         }
2003         NFSM_BUILD(tl, u_int32_t *, NFSX_VERF);
2004         txdr_hyper(at.na_filerev, tl);
2005
2006         /*
2007          * Save this position, in case there is an empty reply needed.
2008          */
2009         mb1 = nd->nd_mb;
2010         bpos1 = nd->nd_bpos;
2011
2012         /* Loop through the records and build reply */
2013         entrycnt = 0;
2014         while (cpos < cend && ncookies > 0 && dirlen < cnt) {
2015                 nlen = dp->d_namlen;
2016                 if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
2017                     nlen <= NFS_MAXNAMLEN &&
2018                     ((nd->nd_flag & ND_NFSV3) || nlen > 2 ||
2019                      (nlen==2 && (dp->d_name[0]!='.' || dp->d_name[1]!='.'))
2020                       || (nlen == 1 && dp->d_name[0] != '.'))) {
2021                         /*
2022                          * Save the current position in the reply, in case
2023                          * this entry exceeds cnt.
2024                          */
2025                         mb1 = nd->nd_mb;
2026                         bpos1 = nd->nd_bpos;
2027         
2028                         /*
2029                          * For readdir_and_lookup get the vnode using
2030                          * the file number.
2031                          */
2032                         nvp = NULL;
2033                         refp = NULL;
2034                         r = 0;
2035                         at_root = 0;
2036                         needs_unbusy = 0;
2037                         new_mp = mp;
2038                         mounted_on_fileno = (uint64_t)dp->d_fileno;
2039                         if ((nd->nd_flag & ND_NFSV3) ||
2040                             NFSNONZERO_ATTRBIT(&savbits)) {
2041                                 if (nd->nd_flag & ND_NFSV4)
2042                                         refp = nfsv4root_getreferral(NULL,
2043                                             vp, dp->d_fileno);
2044                                 if (refp == NULL) {
2045                                         if (usevget)
2046                                                 r = VFS_VGET(mp, dp->d_fileno,
2047                                                     LK_SHARED, &nvp);
2048                                         else
2049                                                 r = EOPNOTSUPP;
2050                                         if (r == EOPNOTSUPP) {
2051                                                 if (usevget) {
2052                                                         usevget = 0;
2053                                                         cn.cn_nameiop = LOOKUP;
2054                                                         cn.cn_lkflags =
2055                                                             LK_SHARED |
2056                                                             LK_RETRY;
2057                                                         cn.cn_cred =
2058                                                             nd->nd_cred;
2059                                                         cn.cn_thread = p;
2060                                                 }
2061                                                 cn.cn_nameptr = dp->d_name;
2062                                                 cn.cn_namelen = nlen;
2063                                                 cn.cn_flags = ISLASTCN |
2064                                                     NOFOLLOW | LOCKLEAF |
2065                                                     MPSAFE;
2066                                                 if (nlen == 2 &&
2067                                                     dp->d_name[0] == '.' &&
2068                                                     dp->d_name[1] == '.')
2069                                                         cn.cn_flags |=
2070                                                             ISDOTDOT;
2071                                                 if (NFSVOPLOCK(vp, LK_SHARED)
2072                                                     != 0) {
2073                                                         nd->nd_repstat = EPERM;
2074                                                         break;
2075                                                 }
2076                                                 if ((vp->v_vflag & VV_ROOT) != 0
2077                                                     && (cn.cn_flags & ISDOTDOT)
2078                                                     != 0) {
2079                                                         vref(vp);
2080                                                         nvp = vp;
2081                                                         r = 0;
2082                                                 } else {
2083                                                         r = VOP_LOOKUP(vp, &nvp,
2084                                                             &cn);
2085                                                         if (vp != nvp)
2086                                                                 NFSVOPUNLOCK(vp,
2087                                                                     0);
2088                                                 }
2089                                         }
2090
2091                                         /*
2092                                          * For NFSv4, check to see if nvp is
2093                                          * a mount point and get the mount
2094                                          * point vnode, as required.
2095                                          */
2096                                         if (r == 0 &&
2097                                             nfsrv_enable_crossmntpt != 0 &&
2098                                             (nd->nd_flag & ND_NFSV4) != 0 &&
2099                                             nvp->v_type == VDIR &&
2100                                             nvp->v_mountedhere != NULL) {
2101                                                 new_mp = nvp->v_mountedhere;
2102                                                 r = vfs_busy(new_mp, 0);
2103                                                 vput(nvp);
2104                                                 nvp = NULL;
2105                                                 if (r == 0) {
2106                                                         r = VFS_ROOT(new_mp,
2107                                                             LK_SHARED, &nvp);
2108                                                         needs_unbusy = 1;
2109                                                         if (r == 0)
2110                                                                 at_root = 1;
2111                                                 }
2112                                         }
2113                                 }
2114                                 if (!r) {
2115                                     if (refp == NULL &&
2116                                         ((nd->nd_flag & ND_NFSV3) ||
2117                                          NFSNONZERO_ATTRBIT(&attrbits))) {
2118                                         r = nfsvno_getfh(nvp, &nfh, p);
2119                                         if (!r)
2120                                             r = nfsvno_getattr(nvp, nvap,
2121                                                 nd->nd_cred, p, 1);
2122                                     }
2123                                 } else {
2124                                     nvp = NULL;
2125                                 }
2126                                 if (r) {
2127                                         if (!NFSISSET_ATTRBIT(&attrbits,
2128                                             NFSATTRBIT_RDATTRERROR)) {
2129                                                 if (nvp != NULL)
2130                                                         vput(nvp);
2131                                                 if (needs_unbusy != 0)
2132                                                         vfs_unbusy(new_mp);
2133                                                 nd->nd_repstat = r;
2134                                                 break;
2135                                         }
2136                                 }
2137                         }
2138
2139                         /*
2140                          * Build the directory record xdr
2141                          */
2142                         if (nd->nd_flag & ND_NFSV3) {
2143                                 NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2144                                 *tl++ = newnfs_true;
2145                                 *tl++ = 0;
2146                                 *tl = txdr_unsigned(dp->d_fileno);
2147                                 dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2148                                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2149                                 *tl++ = 0;
2150                                 *tl = txdr_unsigned(*cookiep);
2151                                 nfsrv_postopattr(nd, 0, nvap);
2152                                 dirlen += nfsm_fhtom(nd,(u_int8_t *)&nfh,0,1);
2153                                 dirlen += (5*NFSX_UNSIGNED+NFSX_V3POSTOPATTR);
2154                                 if (nvp != NULL)
2155                                         vput(nvp);
2156                         } else {
2157                                 NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2158                                 *tl++ = newnfs_true;
2159                                 *tl++ = 0;
2160                                 *tl = txdr_unsigned(*cookiep);
2161                                 dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2162                                 if (nvp != NULL) {
2163                                         supports_nfsv4acls =
2164                                             nfs_supportsnfsv4acls(nvp);
2165                                         NFSVOPUNLOCK(nvp, 0);
2166                                 } else
2167                                         supports_nfsv4acls = 0;
2168                                 if (refp != NULL) {
2169                                         dirlen += nfsrv_putreferralattr(nd,
2170                                             &savbits, refp, 0,
2171                                             &nd->nd_repstat);
2172                                         if (nd->nd_repstat) {
2173                                                 if (nvp != NULL)
2174                                                         vrele(nvp);
2175                                                 if (needs_unbusy != 0)
2176                                                         vfs_unbusy(new_mp);
2177                                                 break;
2178                                         }
2179                                 } else if (r) {
2180                                         dirlen += nfsvno_fillattr(nd, new_mp,
2181                                             nvp, nvap, &nfh, r, &rderrbits,
2182                                             nd->nd_cred, p, isdgram, 0,
2183                                             supports_nfsv4acls, at_root,
2184                                             mounted_on_fileno);
2185                                 } else {
2186                                         dirlen += nfsvno_fillattr(nd, new_mp,
2187                                             nvp, nvap, &nfh, r, &attrbits,
2188                                             nd->nd_cred, p, isdgram, 0,
2189                                             supports_nfsv4acls, at_root,
2190                                             mounted_on_fileno);
2191                                 }
2192                                 if (nvp != NULL)
2193                                         vrele(nvp);
2194                                 dirlen += (3 * NFSX_UNSIGNED);
2195                         }
2196                         if (needs_unbusy != 0)
2197                                 vfs_unbusy(new_mp);
2198                         if (dirlen <= cnt)
2199                                 entrycnt++;
2200                 }
2201                 cpos += dp->d_reclen;
2202                 dp = (struct dirent *)cpos;
2203                 cookiep++;
2204                 ncookies--;
2205         }
2206         vrele(vp);
2207         vfs_unbusy(mp);
2208
2209         /*
2210          * If dirlen > cnt, we must strip off the last entry. If that
2211          * results in an empty reply, report NFSERR_TOOSMALL.
2212          */
2213         if (dirlen > cnt || nd->nd_repstat) {
2214                 if (!nd->nd_repstat && entrycnt == 0)
2215                         nd->nd_repstat = NFSERR_TOOSMALL;
2216                 if (nd->nd_repstat)
2217                         newnfs_trimtrailing(nd, mb0, bpos0);
2218                 else
2219                         newnfs_trimtrailing(nd, mb1, bpos1);
2220                 eofflag = 0;
2221         } else if (cpos < cend)
2222                 eofflag = 0;
2223         if (!nd->nd_repstat) {
2224                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2225                 *tl++ = newnfs_false;
2226                 if (eofflag)
2227                         *tl = newnfs_true;
2228                 else
2229                         *tl = newnfs_false;
2230         }
2231         FREE((caddr_t)cookies, M_TEMP);
2232         FREE((caddr_t)rbuf, M_TEMP);
2233
2234 out:
2235         NFSEXITCODE2(0, nd);
2236         return (0);
2237 nfsmout:
2238         vput(vp);
2239         NFSEXITCODE2(error, nd);
2240         return (error);
2241 }
2242
2243 /*
2244  * Get the settable attributes out of the mbuf list.
2245  * (Return 0 or EBADRPC)
2246  */
2247 int
2248 nfsrv_sattr(struct nfsrv_descript *nd, struct nfsvattr *nvap,
2249     nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2250 {
2251         u_int32_t *tl;
2252         struct nfsv2_sattr *sp;
2253         struct timeval curtime;
2254         int error = 0, toclient = 0;
2255
2256         switch (nd->nd_flag & (ND_NFSV2 | ND_NFSV3 | ND_NFSV4)) {
2257         case ND_NFSV2:
2258                 NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
2259                 /*
2260                  * Some old clients didn't fill in the high order 16bits.
2261                  * --> check the low order 2 bytes for 0xffff
2262                  */
2263                 if ((fxdr_unsigned(int, sp->sa_mode) & 0xffff) != 0xffff)
2264                         nvap->na_mode = nfstov_mode(sp->sa_mode);
2265                 if (sp->sa_uid != newnfs_xdrneg1)
2266                         nvap->na_uid = fxdr_unsigned(uid_t, sp->sa_uid);
2267                 if (sp->sa_gid != newnfs_xdrneg1)
2268                         nvap->na_gid = fxdr_unsigned(gid_t, sp->sa_gid);
2269                 if (sp->sa_size != newnfs_xdrneg1)
2270                         nvap->na_size = fxdr_unsigned(u_quad_t, sp->sa_size);
2271                 if (sp->sa_atime.nfsv2_sec != newnfs_xdrneg1) {
2272 #ifdef notyet
2273                         fxdr_nfsv2time(&sp->sa_atime, &nvap->na_atime);
2274 #else
2275                         nvap->na_atime.tv_sec =
2276                                 fxdr_unsigned(u_int32_t,sp->sa_atime.nfsv2_sec);
2277                         nvap->na_atime.tv_nsec = 0;
2278 #endif
2279                 }
2280                 if (sp->sa_mtime.nfsv2_sec != newnfs_xdrneg1)
2281                         fxdr_nfsv2time(&sp->sa_mtime, &nvap->na_mtime);
2282                 break;
2283         case ND_NFSV3:
2284                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2285                 if (*tl == newnfs_true) {
2286                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2287                         nvap->na_mode = nfstov_mode(*tl);
2288                 }
2289                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2290                 if (*tl == newnfs_true) {
2291                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2292                         nvap->na_uid = fxdr_unsigned(uid_t, *tl);
2293                 }
2294                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2295                 if (*tl == newnfs_true) {
2296                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2297                         nvap->na_gid = fxdr_unsigned(gid_t, *tl);
2298                 }
2299                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2300                 if (*tl == newnfs_true) {
2301                         NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2302                         nvap->na_size = fxdr_hyper(tl);
2303                 }
2304                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2305                 switch (fxdr_unsigned(int, *tl)) {
2306                 case NFSV3SATTRTIME_TOCLIENT:
2307                         NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2308                         fxdr_nfsv3time(tl, &nvap->na_atime);
2309                         toclient = 1;
2310                         break;
2311                 case NFSV3SATTRTIME_TOSERVER:
2312                         NFSGETTIME(&curtime);
2313                         nvap->na_atime.tv_sec = curtime.tv_sec;
2314                         nvap->na_atime.tv_nsec = curtime.tv_usec * 1000;
2315                         nvap->na_vaflags |= VA_UTIMES_NULL;
2316                         break;
2317                 };
2318                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2319                 switch (fxdr_unsigned(int, *tl)) {
2320                 case NFSV3SATTRTIME_TOCLIENT:
2321                         NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2322                         fxdr_nfsv3time(tl, &nvap->na_mtime);
2323                         nvap->na_vaflags &= ~VA_UTIMES_NULL;
2324                         break;
2325                 case NFSV3SATTRTIME_TOSERVER:
2326                         NFSGETTIME(&curtime);
2327                         nvap->na_mtime.tv_sec = curtime.tv_sec;
2328                         nvap->na_mtime.tv_nsec = curtime.tv_usec * 1000;
2329                         if (!toclient)
2330                                 nvap->na_vaflags |= VA_UTIMES_NULL;
2331                         break;
2332                 };
2333                 break;
2334         case ND_NFSV4:
2335                 error = nfsv4_sattr(nd, nvap, attrbitp, aclp, p);
2336         };
2337 nfsmout:
2338         NFSEXITCODE2(error, nd);
2339         return (error);
2340 }
2341
2342 /*
2343  * Handle the setable attributes for V4.
2344  * Returns NFSERR_BADXDR if it can't be parsed, 0 otherwise.
2345  */
2346 int
2347 nfsv4_sattr(struct nfsrv_descript *nd, struct nfsvattr *nvap,
2348     nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2349 {
2350         u_int32_t *tl;
2351         int attrsum = 0;
2352         int i, j;
2353         int error, attrsize, bitpos, aclsize, aceerr, retnotsup = 0;
2354         int toclient = 0;
2355         u_char *cp, namestr[NFSV4_SMALLSTR + 1];
2356         uid_t uid;
2357         gid_t gid;
2358         struct timeval curtime;
2359
2360         error = nfsrv_getattrbits(nd, attrbitp, NULL, &retnotsup);
2361         if (error)
2362                 goto nfsmout;
2363         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2364         attrsize = fxdr_unsigned(int, *tl);
2365
2366         /*
2367          * Loop around getting the setable attributes. If an unsupported
2368          * one is found, set nd_repstat == NFSERR_ATTRNOTSUPP and return.
2369          */
2370         if (retnotsup) {
2371                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2372                 bitpos = NFSATTRBIT_MAX;
2373         } else {
2374                 bitpos = 0;
2375         }
2376         for (; bitpos < NFSATTRBIT_MAX; bitpos++) {
2377             if (attrsum > attrsize) {
2378                 error = NFSERR_BADXDR;
2379                 goto nfsmout;
2380             }
2381             if (NFSISSET_ATTRBIT(attrbitp, bitpos))
2382                 switch (bitpos) {
2383                 case NFSATTRBIT_SIZE:
2384                         NFSM_DISSECT(tl, u_int32_t *, NFSX_HYPER);
2385                         nvap->na_size = fxdr_hyper(tl);
2386                         attrsum += NFSX_HYPER;
2387                         break;
2388                 case NFSATTRBIT_ACL:
2389                         error = nfsrv_dissectacl(nd, aclp, &aceerr, &aclsize,
2390                             p);
2391                         if (error)
2392                                 goto nfsmout;
2393                         if (aceerr && !nd->nd_repstat)
2394                                 nd->nd_repstat = aceerr;
2395                         attrsum += aclsize;
2396                         break;
2397                 case NFSATTRBIT_ARCHIVE:
2398                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2399                         if (!nd->nd_repstat)
2400                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2401                         attrsum += NFSX_UNSIGNED;
2402                         break;
2403                 case NFSATTRBIT_HIDDEN:
2404                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2405                         if (!nd->nd_repstat)
2406                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2407                         attrsum += NFSX_UNSIGNED;
2408                         break;
2409                 case NFSATTRBIT_MIMETYPE:
2410                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2411                         i = fxdr_unsigned(int, *tl);
2412                         error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
2413                         if (error)
2414                                 goto nfsmout;
2415                         if (!nd->nd_repstat)
2416                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2417                         attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(i));
2418                         break;
2419                 case NFSATTRBIT_MODE:
2420                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2421                         nvap->na_mode = nfstov_mode(*tl);
2422                         attrsum += NFSX_UNSIGNED;
2423                         break;
2424                 case NFSATTRBIT_OWNER:
2425                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2426                         j = fxdr_unsigned(int, *tl);
2427                         if (j < 0) {
2428                                 error = NFSERR_BADXDR;
2429                                 goto nfsmout;
2430                         }
2431                         if (j > NFSV4_SMALLSTR)
2432                                 cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2433                         else
2434                                 cp = namestr;
2435                         error = nfsrv_mtostr(nd, cp, j);
2436                         if (error) {
2437                                 if (j > NFSV4_SMALLSTR)
2438                                         free(cp, M_NFSSTRING);
2439                                 goto nfsmout;
2440                         }
2441                         if (!nd->nd_repstat) {
2442                                 nd->nd_repstat = nfsv4_strtouid(nd, cp, j, &uid,
2443                                     p);
2444                                 if (!nd->nd_repstat)
2445                                         nvap->na_uid = uid;
2446                         }
2447                         if (j > NFSV4_SMALLSTR)
2448                                 free(cp, M_NFSSTRING);
2449                         attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2450                         break;
2451                 case NFSATTRBIT_OWNERGROUP:
2452                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2453                         j = fxdr_unsigned(int, *tl);
2454                         if (j < 0) {
2455                                 error = NFSERR_BADXDR;
2456                                 goto nfsmout;
2457                         }
2458                         if (j > NFSV4_SMALLSTR)
2459                                 cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2460                         else
2461                                 cp = namestr;
2462                         error = nfsrv_mtostr(nd, cp, j);
2463                         if (error) {
2464                                 if (j > NFSV4_SMALLSTR)
2465                                         free(cp, M_NFSSTRING);
2466                                 goto nfsmout;
2467                         }
2468                         if (!nd->nd_repstat) {
2469                                 nd->nd_repstat = nfsv4_strtogid(nd, cp, j, &gid,
2470                                     p);
2471                                 if (!nd->nd_repstat)
2472                                         nvap->na_gid = gid;
2473                         }
2474                         if (j > NFSV4_SMALLSTR)
2475                                 free(cp, M_NFSSTRING);
2476                         attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2477                         break;
2478                 case NFSATTRBIT_SYSTEM:
2479                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2480                         if (!nd->nd_repstat)
2481                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2482                         attrsum += NFSX_UNSIGNED;
2483                         break;
2484                 case NFSATTRBIT_TIMEACCESSSET:
2485                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2486                         attrsum += NFSX_UNSIGNED;
2487                         if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2488                             NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2489                             fxdr_nfsv4time(tl, &nvap->na_atime);
2490                             toclient = 1;
2491                             attrsum += NFSX_V4TIME;
2492                         } else {
2493                             NFSGETTIME(&curtime);
2494                             nvap->na_atime.tv_sec = curtime.tv_sec;
2495                             nvap->na_atime.tv_nsec = curtime.tv_usec * 1000;
2496                             nvap->na_vaflags |= VA_UTIMES_NULL;
2497                         }
2498                         break;
2499                 case NFSATTRBIT_TIMEBACKUP:
2500                         NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2501                         if (!nd->nd_repstat)
2502                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2503                         attrsum += NFSX_V4TIME;
2504                         break;
2505                 case NFSATTRBIT_TIMECREATE:
2506                         NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2507                         if (!nd->nd_repstat)
2508                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2509                         attrsum += NFSX_V4TIME;
2510                         break;
2511                 case NFSATTRBIT_TIMEMODIFYSET:
2512                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2513                         attrsum += NFSX_UNSIGNED;
2514                         if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2515                             NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2516                             fxdr_nfsv4time(tl, &nvap->na_mtime);
2517                             nvap->na_vaflags &= ~VA_UTIMES_NULL;
2518                             attrsum += NFSX_V4TIME;
2519                         } else {
2520                             NFSGETTIME(&curtime);
2521                             nvap->na_mtime.tv_sec = curtime.tv_sec;
2522                             nvap->na_mtime.tv_nsec = curtime.tv_usec * 1000;
2523                             if (!toclient)
2524                                 nvap->na_vaflags |= VA_UTIMES_NULL;
2525                         }
2526                         break;
2527                 default:
2528                         nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2529                         /*
2530                          * set bitpos so we drop out of the loop.
2531                          */
2532                         bitpos = NFSATTRBIT_MAX;
2533                         break;
2534                 };
2535         }
2536
2537         /*
2538          * some clients pad the attrlist, so we need to skip over the
2539          * padding.
2540          */
2541         if (attrsum > attrsize) {
2542                 error = NFSERR_BADXDR;
2543         } else {
2544                 attrsize = NFSM_RNDUP(attrsize);
2545                 if (attrsum < attrsize)
2546                         error = nfsm_advance(nd, attrsize - attrsum, -1);
2547         }
2548 nfsmout:
2549         NFSEXITCODE2(error, nd);
2550         return (error);
2551 }
2552
2553 /*
2554  * Check/setup export credentials.
2555  */
2556 int
2557 nfsd_excred(struct nfsrv_descript *nd, struct nfsexstuff *exp,
2558     struct ucred *credanon)
2559 {
2560         int error = 0;
2561
2562         /*
2563          * Check/setup credentials.
2564          */
2565         if (nd->nd_flag & ND_GSS)
2566                 exp->nes_exflag &= ~MNT_EXPORTANON;
2567
2568         /*
2569          * Check to see if the operation is allowed for this security flavor.
2570          * RFC2623 suggests that the NFSv3 Fsinfo RPC be allowed to
2571          * AUTH_NONE or AUTH_SYS for file systems requiring RPCSEC_GSS.
2572          * Also, allow Secinfo, so that it can acquire the correct flavor(s).
2573          */
2574         if (nfsvno_testexp(nd, exp) &&
2575             nd->nd_procnum != NFSV4OP_SECINFO &&
2576             nd->nd_procnum != NFSPROC_FSINFO) {
2577                 if (nd->nd_flag & ND_NFSV4)
2578                         error = NFSERR_WRONGSEC;
2579                 else
2580                         error = (NFSERR_AUTHERR | AUTH_TOOWEAK);
2581                 goto out;
2582         }
2583
2584         /*
2585          * Check to see if the file system is exported V4 only.
2586          */
2587         if (NFSVNO_EXV4ONLY(exp) && !(nd->nd_flag & ND_NFSV4)) {
2588                 error = NFSERR_PROGNOTV4;
2589                 goto out;
2590         }
2591
2592         /*
2593          * Now, map the user credentials.
2594          * (Note that ND_AUTHNONE will only be set for an NFSv3
2595          *  Fsinfo RPC. If set for anything else, this code might need
2596          *  to change.)
2597          */
2598         if (NFSVNO_EXPORTED(exp) &&
2599             ((!(nd->nd_flag & ND_GSS) && nd->nd_cred->cr_uid == 0) ||
2600              NFSVNO_EXPORTANON(exp) ||
2601              (nd->nd_flag & ND_AUTHNONE))) {
2602                 nd->nd_cred->cr_uid = credanon->cr_uid;
2603                 nd->nd_cred->cr_gid = credanon->cr_gid;
2604                 crsetgroups(nd->nd_cred, credanon->cr_ngroups,
2605                     credanon->cr_groups);
2606         }
2607
2608 out:
2609         NFSEXITCODE2(error, nd);
2610         return (error);
2611 }
2612
2613 /*
2614  * Check exports.
2615  */
2616 int
2617 nfsvno_checkexp(struct mount *mp, struct sockaddr *nam, struct nfsexstuff *exp,
2618     struct ucred **credp)
2619 {
2620         int i, error, *secflavors;
2621
2622         error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
2623             &exp->nes_numsecflavor, &secflavors);
2624         if (error) {
2625                 if (nfs_rootfhset) {
2626                         exp->nes_exflag = 0;
2627                         exp->nes_numsecflavor = 0;
2628                         error = 0;
2629                 }
2630         } else {
2631                 /* Copy the security flavors. */
2632                 for (i = 0; i < exp->nes_numsecflavor; i++)
2633                         exp->nes_secflavors[i] = secflavors[i];
2634         }
2635         NFSEXITCODE(error);
2636         return (error);
2637 }
2638
2639 /*
2640  * Get a vnode for a file handle and export stuff.
2641  */
2642 int
2643 nfsvno_fhtovp(struct mount *mp, fhandle_t *fhp, struct sockaddr *nam,
2644     int lktype, struct vnode **vpp, struct nfsexstuff *exp,
2645     struct ucred **credp)
2646 {
2647         int i, error, *secflavors;
2648
2649         *credp = NULL;
2650         exp->nes_numsecflavor = 0;
2651         if (VFS_NEEDSGIANT(mp))
2652                 error = ESTALE;
2653         else
2654                 error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, vpp);
2655         if (error != 0)
2656                 /* Make sure the server replies ESTALE to the client. */
2657                 error = ESTALE;
2658         if (nam && !error) {
2659                 error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
2660                     &exp->nes_numsecflavor, &secflavors);
2661                 if (error) {
2662                         if (nfs_rootfhset) {
2663                                 exp->nes_exflag = 0;
2664                                 exp->nes_numsecflavor = 0;
2665                                 error = 0;
2666                         } else {
2667                                 vput(*vpp);
2668                         }
2669                 } else {
2670                         /* Copy the security flavors. */
2671                         for (i = 0; i < exp->nes_numsecflavor; i++)
2672                                 exp->nes_secflavors[i] = secflavors[i];
2673                 }
2674         }
2675         if (error == 0 && lktype == LK_SHARED)
2676                 /*
2677                  * It would be much better to pass lktype to VFS_FHTOVP(),
2678                  * but this will have to do until VFS_FHTOVP() has a lock
2679                  * type argument like VFS_VGET().
2680                  */
2681                 NFSVOPLOCK(*vpp, LK_DOWNGRADE | LK_RETRY);
2682
2683         NFSEXITCODE(error);
2684         return (error);
2685 }
2686
2687 /*
2688  * nfsd_fhtovp() - convert a fh to a vnode ptr
2689  *      - look up fsid in mount list (if not found ret error)
2690  *      - get vp and export rights by calling nfsvno_fhtovp()
2691  *      - if cred->cr_uid == 0 or MNT_EXPORTANON set it to credanon
2692  *        for AUTH_SYS
2693  *      - if mpp != NULL, return the mount point so that it can
2694  *        be used for vn_finished_write() by the caller
2695  */
2696 void
2697 nfsd_fhtovp(struct nfsrv_descript *nd, struct nfsrvfh *nfp, int lktype,
2698     struct vnode **vpp, struct nfsexstuff *exp,
2699     struct mount **mpp, int startwrite, struct thread *p)
2700 {
2701         struct mount *mp;
2702         struct ucred *credanon;
2703         fhandle_t *fhp;
2704
2705         fhp = (fhandle_t *)nfp->nfsrvfh_data;
2706         /*
2707          * Check for the special case of the nfsv4root_fh.
2708          */
2709         mp = vfs_busyfs(&fhp->fh_fsid);
2710         if (mpp != NULL)
2711                 *mpp = mp;
2712         if (mp == NULL) {
2713                 *vpp = NULL;
2714                 nd->nd_repstat = ESTALE;
2715                 goto out;
2716         }
2717
2718         if (startwrite)
2719                 vn_start_write(NULL, mpp, V_WAIT);
2720
2721         nd->nd_repstat = nfsvno_fhtovp(mp, fhp, nd->nd_nam, lktype, vpp, exp,
2722             &credanon);
2723         vfs_unbusy(mp);
2724
2725         /*
2726          * For NFSv4 without a pseudo root fs, unexported file handles
2727          * can be returned, so that Lookup works everywhere.
2728          */
2729         if (!nd->nd_repstat && exp->nes_exflag == 0 &&
2730             !(nd->nd_flag & ND_NFSV4)) {
2731                 vput(*vpp);
2732                 nd->nd_repstat = EACCES;
2733         }
2734
2735         /*
2736          * Personally, I've never seen any point in requiring a
2737          * reserved port#, since only in the rare case where the
2738          * clients are all boxes with secure system priviledges,
2739          * does it provide any enhanced security, but... some people
2740          * believe it to be useful and keep putting this code back in.
2741          * (There is also some "security checker" out there that
2742          *  complains if the nfs server doesn't enforce this.)
2743          * However, note the following:
2744          * RFC3530 (NFSv4) specifies that a reserved port# not be
2745          *      required.
2746          * RFC2623 recommends that, if a reserved port# is checked for,
2747          *      that there be a way to turn that off--> ifdef'd.
2748          */
2749 #ifdef NFS_REQRSVPORT
2750         if (!nd->nd_repstat) {
2751                 struct sockaddr_in *saddr;
2752                 struct sockaddr_in6 *saddr6;
2753
2754                 saddr = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in *);
2755                 saddr6 = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in6 *);
2756                 if (!(nd->nd_flag & ND_NFSV4) &&
2757                     ((saddr->sin_family == AF_INET &&
2758                       ntohs(saddr->sin_port) >= IPPORT_RESERVED) ||
2759                      (saddr6->sin6_family == AF_INET6 &&
2760                       ntohs(saddr6->sin6_port) >= IPPORT_RESERVED))) {
2761                         vput(*vpp);
2762                         nd->nd_repstat = (NFSERR_AUTHERR | AUTH_TOOWEAK);
2763                 }
2764         }
2765 #endif  /* NFS_REQRSVPORT */
2766
2767         /*
2768          * Check/setup credentials.
2769          */
2770         if (!nd->nd_repstat) {
2771                 nd->nd_saveduid = nd->nd_cred->cr_uid;
2772                 nd->nd_repstat = nfsd_excred(nd, exp, credanon);
2773                 if (nd->nd_repstat)
2774                         vput(*vpp);
2775         }
2776         if (credanon != NULL)
2777                 crfree(credanon);
2778         if (nd->nd_repstat) {
2779                 if (startwrite)
2780                         vn_finished_write(mp);
2781                 *vpp = NULL;
2782                 if (mpp != NULL)
2783                         *mpp = NULL;
2784         }
2785
2786 out:
2787         NFSEXITCODE2(0, nd);
2788 }
2789
2790 /*
2791  * glue for fp.
2792  */
2793 int
2794 fp_getfvp(struct thread *p, int fd, struct file **fpp, struct vnode **vpp)
2795 {
2796         struct filedesc *fdp;
2797         struct file *fp;
2798         int error = 0;
2799
2800         fdp = p->td_proc->p_fd;
2801         if (fd >= fdp->fd_nfiles ||
2802             (fp = fdp->fd_ofiles[fd]) == NULL) {
2803                 error = EBADF;
2804                 goto out;
2805         }
2806         *fpp = fp;
2807
2808 out:
2809         NFSEXITCODE(error);
2810         return (error);
2811 }
2812
2813 /*
2814  * Called from nfssvc() to update the exports list. Just call
2815  * vfs_export(). This has to be done, since the v4 root fake fs isn't
2816  * in the mount list.
2817  */
2818 int
2819 nfsrv_v4rootexport(void *argp, struct ucred *cred, struct thread *p)
2820 {
2821         struct nfsex_args *nfsexargp = (struct nfsex_args *)argp;
2822         int error = 0;
2823         struct nameidata nd;
2824         fhandle_t fh;
2825
2826         error = vfs_export(&nfsv4root_mnt, &nfsexargp->export);
2827         if ((nfsexargp->export.ex_flags & MNT_DELEXPORT) != 0)
2828                 nfs_rootfhset = 0;
2829         else if (error == 0) {
2830                 if (nfsexargp->fspec == NULL) {
2831                         error = EPERM;
2832                         goto out;
2833                 }
2834                 /*
2835                  * If fspec != NULL, this is the v4root path.
2836                  */
2837                 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_USERSPACE,
2838                     nfsexargp->fspec, p);
2839                 if ((error = namei(&nd)) != 0)
2840                         goto out;
2841                 error = nfsvno_getfh(nd.ni_vp, &fh, p);
2842                 vrele(nd.ni_vp);
2843                 if (!error) {
2844                         nfs_rootfh.nfsrvfh_len = NFSX_MYFH;
2845                         NFSBCOPY((caddr_t)&fh,
2846                             nfs_rootfh.nfsrvfh_data,
2847                             sizeof (fhandle_t));
2848                         nfs_rootfhset = 1;
2849                 }
2850         }
2851
2852 out:
2853         NFSEXITCODE(error);
2854         return (error);
2855 }
2856
2857 /*
2858  * Get the tcp socket sequence numbers we need.
2859  * (Maybe this should be moved to the tcp sources?)
2860  */
2861 int
2862 nfsrv_getsocksndseq(struct socket *so, tcp_seq *maxp, tcp_seq *unap)
2863 {
2864         struct inpcb *inp;
2865         struct tcpcb *tp;
2866         int error = 0;
2867
2868         inp = sotoinpcb(so);
2869         KASSERT(inp != NULL, ("nfsrv_getsocksndseq: inp == NULL"));
2870         INP_RLOCK(inp);
2871         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
2872                 INP_RUNLOCK(inp);
2873                 error = EPIPE;
2874                 goto out;
2875         }
2876         tp = intotcpcb(inp);
2877         if (tp->t_state != TCPS_ESTABLISHED) {
2878                 INP_RUNLOCK(inp);
2879                 error = EPIPE;
2880                 goto out;
2881         }
2882         *maxp = tp->snd_max;
2883         *unap = tp->snd_una;
2884         INP_RUNLOCK(inp);
2885
2886 out:
2887         NFSEXITCODE(error);
2888         return (error);
2889 }
2890
2891 /*
2892  * This function needs to test to see if the system is near its limit
2893  * for memory allocation via malloc() or mget() and return True iff
2894  * either of these resources are near their limit.
2895  * XXX (For now, this is just a stub.)
2896  */
2897 int nfsrv_testmalloclimit = 0;
2898 int
2899 nfsrv_mallocmget_limit(void)
2900 {
2901         static int printmesg = 0;
2902         static int testval = 1;
2903
2904         if (nfsrv_testmalloclimit && (testval++ % 1000) == 0) {
2905                 if ((printmesg++ % 100) == 0)
2906                         printf("nfsd: malloc/mget near limit\n");
2907                 return (1);
2908         }
2909         return (0);
2910 }
2911
2912 /*
2913  * BSD specific initialization of a mount point.
2914  */
2915 void
2916 nfsd_mntinit(void)
2917 {
2918         static int inited = 0;
2919
2920         if (inited)
2921                 return;
2922         inited = 1;
2923         nfsv4root_mnt.mnt_flag = (MNT_RDONLY | MNT_EXPORTED);
2924         TAILQ_INIT(&nfsv4root_mnt.mnt_nvnodelist);
2925         TAILQ_INIT(&nfsv4root_mnt.mnt_activevnodelist);
2926         nfsv4root_mnt.mnt_export = NULL;
2927         TAILQ_INIT(&nfsv4root_opt);
2928         TAILQ_INIT(&nfsv4root_newopt);
2929         nfsv4root_mnt.mnt_opt = &nfsv4root_opt;
2930         nfsv4root_mnt.mnt_optnew = &nfsv4root_newopt;
2931         nfsv4root_mnt.mnt_nvnodelistsize = 0;
2932         nfsv4root_mnt.mnt_activevnodelistsize = 0;
2933 }
2934
2935 /*
2936  * Get a vnode for a file handle, without checking exports, etc.
2937  */
2938 struct vnode *
2939 nfsvno_getvp(fhandle_t *fhp)
2940 {
2941         struct mount *mp;
2942         struct vnode *vp;
2943         int error;
2944
2945         mp = vfs_busyfs(&fhp->fh_fsid);
2946         if (mp == NULL)
2947                 return (NULL);
2948         error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, &vp);
2949         vfs_unbusy(mp);
2950         if (error)
2951                 return (NULL);
2952         return (vp);
2953 }
2954
2955 /*
2956  * Do a local VOP_ADVLOCK().
2957  */
2958 int
2959 nfsvno_advlock(struct vnode *vp, int ftype, u_int64_t first,
2960     u_int64_t end, struct thread *td)
2961 {
2962         int error = 0;
2963         struct flock fl;
2964         u_int64_t tlen;
2965
2966         if (nfsrv_dolocallocks == 0)
2967                 goto out;
2968
2969         /* Check for VI_DOOMED here, so that VOP_ADVLOCK() isn't performed. */
2970         if ((vp->v_iflag & VI_DOOMED) != 0) {
2971                 error = EPERM;
2972                 goto out;
2973         }
2974
2975         fl.l_whence = SEEK_SET;
2976         fl.l_type = ftype;
2977         fl.l_start = (off_t)first;
2978         if (end == NFS64BITSSET) {
2979                 fl.l_len = 0;
2980         } else {
2981                 tlen = end - first;
2982                 fl.l_len = (off_t)tlen;
2983         }
2984         /*
2985          * For FreeBSD8, the l_pid and l_sysid must be set to the same
2986          * values for all calls, so that all locks will be held by the
2987          * nfsd server. (The nfsd server handles conflicts between the
2988          * various clients.)
2989          * Since an NFSv4 lockowner is a ClientID plus an array of up to 1024
2990          * bytes, so it can't be put in l_sysid.
2991          */
2992         if (nfsv4_sysid == 0)
2993                 nfsv4_sysid = nlm_acquire_next_sysid();
2994         fl.l_pid = (pid_t)0;
2995         fl.l_sysid = (int)nfsv4_sysid;
2996
2997         NFSVOPUNLOCK(vp, 0);
2998         if (ftype == F_UNLCK)
2999                 error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_UNLCK, &fl,
3000                     (F_POSIX | F_REMOTE));
3001         else
3002                 error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_SETLK, &fl,
3003                     (F_POSIX | F_REMOTE));
3004         NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
3005
3006 out:
3007         NFSEXITCODE(error);
3008         return (error);
3009 }
3010
3011 /*
3012  * Check the nfsv4 root exports.
3013  */
3014 int
3015 nfsvno_v4rootexport(struct nfsrv_descript *nd)
3016 {
3017         struct ucred *credanon;
3018         int exflags, error = 0, numsecflavor, *secflavors, i;
3019
3020         error = vfs_stdcheckexp(&nfsv4root_mnt, nd->nd_nam, &exflags,
3021             &credanon, &numsecflavor, &secflavors);
3022         if (error) {
3023                 error = NFSERR_PROGUNAVAIL;
3024                 goto out;
3025         }
3026         if (credanon != NULL)
3027                 crfree(credanon);
3028         for (i = 0; i < numsecflavor; i++) {
3029                 if (secflavors[i] == AUTH_SYS)
3030                         nd->nd_flag |= ND_EXAUTHSYS;
3031                 else if (secflavors[i] == RPCSEC_GSS_KRB5)
3032                         nd->nd_flag |= ND_EXGSS;
3033                 else if (secflavors[i] == RPCSEC_GSS_KRB5I)
3034                         nd->nd_flag |= ND_EXGSSINTEGRITY;
3035                 else if (secflavors[i] == RPCSEC_GSS_KRB5P)
3036                         nd->nd_flag |= ND_EXGSSPRIVACY;
3037         }
3038
3039 out:
3040         NFSEXITCODE(error);
3041         return (error);
3042 }
3043
3044 /*
3045  * Nfs server psuedo system call for the nfsd's
3046  */
3047 /*
3048  * MPSAFE
3049  */
3050 static int
3051 nfssvc_nfsd(struct thread *td, struct nfssvc_args *uap)
3052 {
3053         struct file *fp;
3054         struct nfsd_addsock_args sockarg;
3055         struct nfsd_nfsd_args nfsdarg;
3056         int error;
3057
3058         if (uap->flag & NFSSVC_NFSDADDSOCK) {
3059                 error = copyin(uap->argp, (caddr_t)&sockarg, sizeof (sockarg));
3060                 if (error)
3061                         goto out;
3062                 /*
3063                  * Since we don't know what rights might be required,
3064                  * pretend that we need them all. It is better to be too
3065                  * careful than too reckless.
3066                  */
3067                 if ((error = fget(td, sockarg.sock, CAP_SOCK_ALL, &fp)) != 0)
3068                         goto out;
3069                 if (fp->f_type != DTYPE_SOCKET) {
3070                         fdrop(fp, td);
3071                         error = EPERM;
3072                         goto out;
3073                 }
3074                 error = nfsrvd_addsock(fp);
3075                 fdrop(fp, td);
3076         } else if (uap->flag & NFSSVC_NFSDNFSD) {
3077                 if (uap->argp == NULL) {
3078                         error = EINVAL;
3079                         goto out;
3080                 }
3081                 error = copyin(uap->argp, (caddr_t)&nfsdarg,
3082                     sizeof (nfsdarg));
3083                 if (error)
3084                         goto out;
3085                 error = nfsrvd_nfsd(td, &nfsdarg);
3086         } else {
3087                 error = nfssvc_srvcall(td, uap, td->td_ucred);
3088         }
3089
3090 out:
3091         NFSEXITCODE(error);
3092         return (error);
3093 }
3094
3095 static int
3096 nfssvc_srvcall(struct thread *p, struct nfssvc_args *uap, struct ucred *cred)
3097 {
3098         struct nfsex_args export;
3099         struct file *fp = NULL;
3100         int stablefd, len;
3101         struct nfsd_clid adminrevoke;
3102         struct nfsd_dumplist dumplist;
3103         struct nfsd_dumpclients *dumpclients;
3104         struct nfsd_dumplocklist dumplocklist;
3105         struct nfsd_dumplocks *dumplocks;
3106         struct nameidata nd;
3107         vnode_t vp;
3108         int error = EINVAL, igotlock;
3109         struct proc *procp;
3110         static int suspend_nfsd = 0;
3111
3112         if (uap->flag & NFSSVC_PUBLICFH) {
3113                 NFSBZERO((caddr_t)&nfs_pubfh.nfsrvfh_data,
3114                     sizeof (fhandle_t));
3115                 error = copyin(uap->argp,
3116                     &nfs_pubfh.nfsrvfh_data, sizeof (fhandle_t));
3117                 if (!error)
3118                         nfs_pubfhset = 1;
3119         } else if (uap->flag & NFSSVC_V4ROOTEXPORT) {
3120                 error = copyin(uap->argp,(caddr_t)&export,
3121                     sizeof (struct nfsex_args));
3122                 if (!error)
3123                         error = nfsrv_v4rootexport(&export, cred, p);
3124         } else if (uap->flag & NFSSVC_NOPUBLICFH) {
3125                 nfs_pubfhset = 0;
3126                 error = 0;
3127         } else if (uap->flag & NFSSVC_STABLERESTART) {
3128                 error = copyin(uap->argp, (caddr_t)&stablefd,
3129                     sizeof (int));
3130                 if (!error)
3131                         error = fp_getfvp(p, stablefd, &fp, &vp);
3132                 if (!error && (NFSFPFLAG(fp) & (FREAD | FWRITE)) != (FREAD | FWRITE))
3133                         error = EBADF;
3134                 if (!error && newnfs_numnfsd != 0)
3135                         error = EPERM;
3136                 if (!error) {
3137                         nfsrv_stablefirst.nsf_fp = fp;
3138                         nfsrv_setupstable(p);
3139                 }
3140         } else if (uap->flag & NFSSVC_ADMINREVOKE) {
3141                 error = copyin(uap->argp, (caddr_t)&adminrevoke,
3142                     sizeof (struct nfsd_clid));
3143                 if (!error)
3144                         error = nfsrv_adminrevoke(&adminrevoke, p);
3145         } else if (uap->flag & NFSSVC_DUMPCLIENTS) {
3146                 error = copyin(uap->argp, (caddr_t)&dumplist,
3147                     sizeof (struct nfsd_dumplist));
3148                 if (!error && (dumplist.ndl_size < 1 ||
3149                         dumplist.ndl_size > NFSRV_MAXDUMPLIST))
3150                         error = EPERM;
3151                 if (!error) {
3152                     len = sizeof (struct nfsd_dumpclients) * dumplist.ndl_size;
3153                     dumpclients = (struct nfsd_dumpclients *)malloc(len,
3154                         M_TEMP, M_WAITOK);
3155                     nfsrv_dumpclients(dumpclients, dumplist.ndl_size);
3156                     error = copyout(dumpclients,
3157                         CAST_USER_ADDR_T(dumplist.ndl_list), len);
3158                     free((caddr_t)dumpclients, M_TEMP);
3159                 }
3160         } else if (uap->flag & NFSSVC_DUMPLOCKS) {
3161                 error = copyin(uap->argp, (caddr_t)&dumplocklist,
3162                     sizeof (struct nfsd_dumplocklist));
3163                 if (!error && (dumplocklist.ndllck_size < 1 ||
3164                         dumplocklist.ndllck_size > NFSRV_MAXDUMPLIST))
3165                         error = EPERM;
3166                 if (!error)
3167                         error = nfsrv_lookupfilename(&nd,
3168                                 dumplocklist.ndllck_fname, p);
3169                 if (!error) {
3170                         len = sizeof (struct nfsd_dumplocks) *
3171                                 dumplocklist.ndllck_size;
3172                         dumplocks = (struct nfsd_dumplocks *)malloc(len,
3173                                 M_TEMP, M_WAITOK);
3174                         nfsrv_dumplocks(nd.ni_vp, dumplocks,
3175                             dumplocklist.ndllck_size, p);
3176                         vput(nd.ni_vp);
3177                         error = copyout(dumplocks,
3178                             CAST_USER_ADDR_T(dumplocklist.ndllck_list), len);
3179                         free((caddr_t)dumplocks, M_TEMP);
3180                 }
3181         } else if (uap->flag & NFSSVC_BACKUPSTABLE) {
3182                 procp = p->td_proc;
3183                 PROC_LOCK(procp);
3184                 nfsd_master_pid = procp->p_pid;
3185                 bcopy(procp->p_comm, nfsd_master_comm, MAXCOMLEN + 1);
3186                 nfsd_master_start = procp->p_stats->p_start;
3187                 nfsd_master_proc = procp;
3188                 PROC_UNLOCK(procp);
3189         } else if ((uap->flag & NFSSVC_SUSPENDNFSD) != 0) {
3190                 NFSLOCKV4ROOTMUTEX();
3191                 if (suspend_nfsd == 0) {
3192                         /* Lock out all nfsd threads */
3193                         do {
3194                                 igotlock = nfsv4_lock(&nfsd_suspend_lock, 1,
3195                                     NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
3196                         } while (igotlock == 0 && suspend_nfsd == 0);
3197                         suspend_nfsd = 1;
3198                 }
3199                 NFSUNLOCKV4ROOTMUTEX();
3200                 error = 0;
3201         } else if ((uap->flag & NFSSVC_RESUMENFSD) != 0) {
3202                 NFSLOCKV4ROOTMUTEX();
3203                 if (suspend_nfsd != 0) {
3204                         nfsv4_unlock(&nfsd_suspend_lock, 0);
3205                         suspend_nfsd = 0;
3206                 }
3207                 NFSUNLOCKV4ROOTMUTEX();
3208                 error = 0;
3209         }
3210
3211         NFSEXITCODE(error);
3212         return (error);
3213 }
3214
3215 /*
3216  * Check exports.
3217  * Returns 0 if ok, 1 otherwise.
3218  */
3219 int
3220 nfsvno_testexp(struct nfsrv_descript *nd, struct nfsexstuff *exp)
3221 {
3222         int i;
3223
3224         /*
3225          * This seems odd, but allow the case where the security flavor
3226          * list is empty. This happens when NFSv4 is traversing non-exported
3227          * file systems. Exported file systems should always have a non-empty
3228          * security flavor list.
3229          */
3230         if (exp->nes_numsecflavor == 0)
3231                 return (0);
3232
3233         for (i = 0; i < exp->nes_numsecflavor; i++) {
3234                 /*
3235                  * The tests for privacy and integrity must be first,
3236                  * since ND_GSS is set for everything but AUTH_SYS.
3237                  */
3238                 if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5P &&
3239                     (nd->nd_flag & ND_GSSPRIVACY))
3240                         return (0);
3241                 if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5I &&
3242                     (nd->nd_flag & ND_GSSINTEGRITY))
3243                         return (0);
3244                 if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5 &&
3245                     (nd->nd_flag & ND_GSS))
3246                         return (0);
3247                 if (exp->nes_secflavors[i] == AUTH_SYS &&
3248                     (nd->nd_flag & ND_GSS) == 0)
3249                         return (0);
3250         }
3251         return (1);
3252 }
3253
3254 /*
3255  * Calculate a hash value for the fid in a file handle.
3256  */
3257 uint32_t
3258 nfsrv_hashfh(fhandle_t *fhp)
3259 {
3260         uint32_t hashval;
3261
3262         hashval = hash32_buf(&fhp->fh_fid, sizeof(struct fid), 0);
3263         return (hashval);
3264 }
3265
3266 /*
3267  * Signal the userland master nfsd to backup the stable restart file.
3268  */
3269 void
3270 nfsrv_backupstable(void)
3271 {
3272         struct proc *procp;
3273
3274         if (nfsd_master_proc != NULL) {
3275                 procp = pfind(nfsd_master_pid);
3276                 /* Try to make sure it is the correct process. */
3277                 if (procp == nfsd_master_proc &&
3278                     procp->p_stats->p_start.tv_sec ==
3279                     nfsd_master_start.tv_sec &&
3280                     procp->p_stats->p_start.tv_usec ==
3281                     nfsd_master_start.tv_usec &&
3282                     strcmp(procp->p_comm, nfsd_master_comm) == 0)
3283                         kern_psignal(procp, SIGUSR2);
3284                 else
3285                         nfsd_master_proc = NULL;
3286
3287                 if (procp != NULL)
3288                         PROC_UNLOCK(procp);
3289         }
3290 }
3291
3292 extern int (*nfsd_call_nfsd)(struct thread *, struct nfssvc_args *);
3293
3294 /*
3295  * Called once to initialize data structures...
3296  */
3297 static int
3298 nfsd_modevent(module_t mod, int type, void *data)
3299 {
3300         int error = 0;
3301         static int loaded = 0;
3302
3303         switch (type) {
3304         case MOD_LOAD:
3305                 if (loaded)
3306                         goto out;
3307                 newnfs_portinit();
3308                 mtx_init(&nfs_cache_mutex, "nfs_cache_mutex", NULL, MTX_DEF);
3309                 mtx_init(&nfs_v4root_mutex, "nfs_v4root_mutex", NULL, MTX_DEF);
3310                 mtx_init(&nfsv4root_mnt.mnt_mtx, "struct mount mtx", NULL,
3311                     MTX_DEF);
3312                 lockinit(&nfsv4root_mnt.mnt_explock, PVFS, "explock", 0, 0);
3313                 nfsrvd_initcache();
3314                 nfsd_init();
3315                 NFSD_LOCK();
3316                 nfsrvd_init(0);
3317                 NFSD_UNLOCK();
3318                 nfsd_mntinit();
3319 #ifdef VV_DISABLEDELEG
3320                 vn_deleg_ops.vndeleg_recall = nfsd_recalldelegation;
3321                 vn_deleg_ops.vndeleg_disable = nfsd_disabledelegation;
3322 #endif
3323                 nfsd_call_servertimer = nfsrv_servertimer;
3324                 nfsd_call_nfsd = nfssvc_nfsd;
3325                 loaded = 1;
3326                 break;
3327
3328         case MOD_UNLOAD:
3329                 if (newnfs_numnfsd != 0) {
3330                         error = EBUSY;
3331                         break;
3332                 }
3333
3334 #ifdef VV_DISABLEDELEG
3335                 vn_deleg_ops.vndeleg_recall = NULL;
3336                 vn_deleg_ops.vndeleg_disable = NULL;
3337 #endif
3338                 nfsd_call_servertimer = NULL;
3339                 nfsd_call_nfsd = NULL;
3340
3341                 /* Clean out all NFSv4 state. */
3342                 nfsrv_throwawayallstate(curthread);
3343
3344                 /* Clean the NFS server reply cache */
3345                 nfsrvd_cleancache();
3346
3347                 /* Free up the krpc server pool. */
3348                 if (nfsrvd_pool != NULL)
3349                         svcpool_destroy(nfsrvd_pool);
3350
3351                 /* and get rid of the locks */
3352                 mtx_destroy(&nfs_cache_mutex);
3353                 mtx_destroy(&nfs_v4root_mutex);
3354                 mtx_destroy(&nfsv4root_mnt.mnt_mtx);
3355                 lockdestroy(&nfsv4root_mnt.mnt_explock);
3356                 loaded = 0;
3357                 break;
3358         default:
3359                 error = EOPNOTSUPP;
3360                 break;
3361         }
3362
3363 out:
3364         NFSEXITCODE(error);
3365         return (error);
3366 }
3367 static moduledata_t nfsd_mod = {
3368         "nfsd",
3369         nfsd_modevent,
3370         NULL,
3371 };
3372 DECLARE_MODULE(nfsd, nfsd_mod, SI_SUB_VFS, SI_ORDER_ANY);
3373
3374 /* So that loader and kldload(2) can find us, wherever we are.. */
3375 MODULE_VERSION(nfsd, 1);
3376 MODULE_DEPEND(nfsd, nfscommon, 1, 1, 1);
3377 MODULE_DEPEND(nfsd, nfslock, 1, 1, 1);
3378 MODULE_DEPEND(nfsd, nfslockd, 1, 1, 1);
3379 MODULE_DEPEND(nfsd, krpc, 1, 1, 1);
3380 MODULE_DEPEND(nfsd, nfssvc, 1, 1, 1);
3381