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