]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/fs/nfsserver/nfs_nfsdport.c
MFV: tcpdump 4.3.0.
[FreeBSD/FreeBSD.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 (VOP_IS_TEXT(vp) && 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  */
324 int
325 nfsvno_namei(struct nfsrv_descript *nd, struct nameidata *ndp,
326     struct vnode *dp, int islocked, struct nfsexstuff *exp, struct thread *p,
327     struct vnode **retdirp)
328 {
329         struct componentname *cnp = &ndp->ni_cnd;
330         int i;
331         struct iovec aiov;
332         struct uio auio;
333         int lockleaf = (cnp->cn_flags & LOCKLEAF) != 0, linklen;
334         int error = 0, crossmnt;
335         char *cp;
336
337         *retdirp = NULL;
338         cnp->cn_nameptr = cnp->cn_pnbuf;
339         ndp->ni_strictrelative = 0;
340         /*
341          * Extract and set starting directory.
342          */
343         if (dp->v_type != VDIR) {
344                 if (islocked)
345                         vput(dp);
346                 else
347                         vrele(dp);
348                 nfsvno_relpathbuf(ndp);
349                 error = ENOTDIR;
350                 goto out1;
351         }
352         if (islocked)
353                 NFSVOPUNLOCK(dp, 0);
354         VREF(dp);
355         *retdirp = dp;
356         if (NFSVNO_EXRDONLY(exp))
357                 cnp->cn_flags |= RDONLY;
358         ndp->ni_segflg = UIO_SYSSPACE;
359         crossmnt = 1;
360
361         if (nd->nd_flag & ND_PUBLOOKUP) {
362                 ndp->ni_loopcnt = 0;
363                 if (cnp->cn_pnbuf[0] == '/') {
364                         vrele(dp);
365                         /*
366                          * Check for degenerate pathnames here, since lookup()
367                          * panics on them.
368                          */
369                         for (i = 1; i < ndp->ni_pathlen; i++)
370                                 if (cnp->cn_pnbuf[i] != '/')
371                                         break;
372                         if (i == ndp->ni_pathlen) {
373                                 error = NFSERR_ACCES;
374                                 goto out;
375                         }
376                         dp = rootvnode;
377                         VREF(dp);
378                 }
379         } else if ((nfsrv_enable_crossmntpt == 0 && NFSVNO_EXPORTED(exp)) ||
380             (nd->nd_flag & ND_NFSV4) == 0) {
381                 /*
382                  * Only cross mount points for NFSv4 when doing a
383                  * mount while traversing the file system above
384                  * the mount point, unless nfsrv_enable_crossmntpt is set.
385                  */
386                 cnp->cn_flags |= NOCROSSMOUNT;
387                 crossmnt = 0;
388         }
389
390         /*
391          * Initialize for scan, set ni_startdir and bump ref on dp again
392          * becuase lookup() will dereference ni_startdir.
393          */
394
395         cnp->cn_thread = p;
396         ndp->ni_startdir = dp;
397         ndp->ni_rootdir = rootvnode;
398         ndp->ni_topdir = NULL;
399
400         if (!lockleaf)
401                 cnp->cn_flags |= LOCKLEAF;
402         for (;;) {
403                 cnp->cn_nameptr = cnp->cn_pnbuf;
404                 /*
405                  * Call lookup() to do the real work.  If an error occurs,
406                  * ndp->ni_vp and ni_dvp are left uninitialized or NULL and
407                  * we do not have to dereference anything before returning.
408                  * In either case ni_startdir will be dereferenced and NULLed
409                  * out.
410                  */
411                 error = lookup(ndp);
412                 if (error)
413                         break;
414
415                 /*
416                  * Check for encountering a symbolic link.  Trivial
417                  * termination occurs if no symlink encountered.
418                  */
419                 if ((cnp->cn_flags & ISSYMLINK) == 0) {
420                         if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0)
421                                 nfsvno_relpathbuf(ndp);
422                         if (ndp->ni_vp && !lockleaf)
423                                 NFSVOPUNLOCK(ndp->ni_vp, 0);
424                         break;
425                 }
426
427                 /*
428                  * Validate symlink
429                  */
430                 if ((cnp->cn_flags & LOCKPARENT) && ndp->ni_pathlen == 1)
431                         NFSVOPUNLOCK(ndp->ni_dvp, 0);
432                 if (!(nd->nd_flag & ND_PUBLOOKUP)) {
433                         error = EINVAL;
434                         goto badlink2;
435                 }
436
437                 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
438                         error = ELOOP;
439                         goto badlink2;
440                 }
441                 if (ndp->ni_pathlen > 1)
442                         cp = uma_zalloc(namei_zone, M_WAITOK);
443                 else
444                         cp = cnp->cn_pnbuf;
445                 aiov.iov_base = cp;
446                 aiov.iov_len = MAXPATHLEN;
447                 auio.uio_iov = &aiov;
448                 auio.uio_iovcnt = 1;
449                 auio.uio_offset = 0;
450                 auio.uio_rw = UIO_READ;
451                 auio.uio_segflg = UIO_SYSSPACE;
452                 auio.uio_td = NULL;
453                 auio.uio_resid = MAXPATHLEN;
454                 error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
455                 if (error) {
456                 badlink1:
457                         if (ndp->ni_pathlen > 1)
458                                 uma_zfree(namei_zone, cp);
459                 badlink2:
460                         vrele(ndp->ni_dvp);
461                         vput(ndp->ni_vp);
462                         break;
463                 }
464                 linklen = MAXPATHLEN - auio.uio_resid;
465                 if (linklen == 0) {
466                         error = ENOENT;
467                         goto badlink1;
468                 }
469                 if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
470                         error = ENAMETOOLONG;
471                         goto badlink1;
472                 }
473
474                 /*
475                  * Adjust or replace path
476                  */
477                 if (ndp->ni_pathlen > 1) {
478                         NFSBCOPY(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
479                         uma_zfree(namei_zone, cnp->cn_pnbuf);
480                         cnp->cn_pnbuf = cp;
481                 } else
482                         cnp->cn_pnbuf[linklen] = '\0';
483                 ndp->ni_pathlen += linklen;
484
485                 /*
486                  * Cleanup refs for next loop and check if root directory
487                  * should replace current directory.  Normally ni_dvp
488                  * becomes the new base directory and is cleaned up when
489                  * we loop.  Explicitly null pointers after invalidation
490                  * to clarify operation.
491                  */
492                 vput(ndp->ni_vp);
493                 ndp->ni_vp = NULL;
494
495                 if (cnp->cn_pnbuf[0] == '/') {
496                         vrele(ndp->ni_dvp);
497                         ndp->ni_dvp = ndp->ni_rootdir;
498                         VREF(ndp->ni_dvp);
499                 }
500                 ndp->ni_startdir = ndp->ni_dvp;
501                 ndp->ni_dvp = NULL;
502         }
503         if (!lockleaf)
504                 cnp->cn_flags &= ~LOCKLEAF;
505
506 out:
507         if (error) {
508                 nfsvno_relpathbuf(ndp);
509                 ndp->ni_vp = NULL;
510                 ndp->ni_dvp = NULL;
511                 ndp->ni_startdir = NULL;
512         } else if ((ndp->ni_cnd.cn_flags & (WANTPARENT|LOCKPARENT)) == 0) {
513                 ndp->ni_dvp = NULL;
514         }
515
516 out1:
517         NFSEXITCODE2(error, nd);
518         return (error);
519 }
520
521 /*
522  * Set up a pathname buffer and return a pointer to it and, optionally
523  * set a hash pointer.
524  */
525 void
526 nfsvno_setpathbuf(struct nameidata *ndp, char **bufpp, u_long **hashpp)
527 {
528         struct componentname *cnp = &ndp->ni_cnd;
529
530         cnp->cn_flags |= (NOMACCHECK | HASBUF);
531         cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
532         if (hashpp != NULL)
533                 *hashpp = NULL;
534         *bufpp = cnp->cn_pnbuf;
535 }
536
537 /*
538  * Release the above path buffer, if not released by nfsvno_namei().
539  */
540 void
541 nfsvno_relpathbuf(struct nameidata *ndp)
542 {
543
544         if ((ndp->ni_cnd.cn_flags & HASBUF) == 0)
545                 panic("nfsrelpath");
546         uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
547         ndp->ni_cnd.cn_flags &= ~HASBUF;
548 }
549
550 /*
551  * Readlink vnode op into an mbuf list.
552  */
553 int
554 nfsvno_readlink(struct vnode *vp, struct ucred *cred, struct thread *p,
555     struct mbuf **mpp, struct mbuf **mpendp, int *lenp)
556 {
557         struct iovec iv[(NFS_MAXPATHLEN+MLEN-1)/MLEN];
558         struct iovec *ivp = iv;
559         struct uio io, *uiop = &io;
560         struct mbuf *mp, *mp2 = NULL, *mp3 = NULL;
561         int i, len, tlen, error = 0;
562
563         len = 0;
564         i = 0;
565         while (len < NFS_MAXPATHLEN) {
566                 NFSMGET(mp);
567                 MCLGET(mp, M_WAIT);
568                 mp->m_len = NFSMSIZ(mp);
569                 if (len == 0) {
570                         mp3 = mp2 = mp;
571                 } else {
572                         mp2->m_next = mp;
573                         mp2 = mp;
574                 }
575                 if ((len + mp->m_len) > NFS_MAXPATHLEN) {
576                         mp->m_len = NFS_MAXPATHLEN - len;
577                         len = NFS_MAXPATHLEN;
578                 } else {
579                         len += mp->m_len;
580                 }
581                 ivp->iov_base = mtod(mp, caddr_t);
582                 ivp->iov_len = mp->m_len;
583                 i++;
584                 ivp++;
585         }
586         uiop->uio_iov = iv;
587         uiop->uio_iovcnt = i;
588         uiop->uio_offset = 0;
589         uiop->uio_resid = len;
590         uiop->uio_rw = UIO_READ;
591         uiop->uio_segflg = UIO_SYSSPACE;
592         uiop->uio_td = NULL;
593         error = VOP_READLINK(vp, uiop, cred);
594         if (error) {
595                 m_freem(mp3);
596                 *lenp = 0;
597                 goto out;
598         }
599         if (uiop->uio_resid > 0) {
600                 len -= uiop->uio_resid;
601                 tlen = NFSM_RNDUP(len);
602                 nfsrv_adj(mp3, NFS_MAXPATHLEN - tlen, tlen - len);
603         }
604         *lenp = len;
605         *mpp = mp3;
606         *mpendp = mp;
607
608 out:
609         NFSEXITCODE(error);
610         return (error);
611 }
612
613 /*
614  * Read vnode op call into mbuf list.
615  */
616 int
617 nfsvno_read(struct vnode *vp, off_t off, int cnt, struct ucred *cred,
618     struct thread *p, struct mbuf **mpp, struct mbuf **mpendp)
619 {
620         struct mbuf *m;
621         int i;
622         struct iovec *iv;
623         struct iovec *iv2;
624         int error = 0, len, left, siz, tlen, ioflag = 0;
625         struct mbuf *m2 = NULL, *m3;
626         struct uio io, *uiop = &io;
627         struct nfsheur *nh;
628
629         len = left = NFSM_RNDUP(cnt);
630         m3 = NULL;
631         /*
632          * Generate the mbuf list with the uio_iov ref. to it.
633          */
634         i = 0;
635         while (left > 0) {
636                 NFSMGET(m);
637                 MCLGET(m, M_WAIT);
638                 m->m_len = 0;
639                 siz = min(M_TRAILINGSPACE(m), left);
640                 left -= siz;
641                 i++;
642                 if (m3)
643                         m2->m_next = m;
644                 else
645                         m3 = m;
646                 m2 = m;
647         }
648         MALLOC(iv, struct iovec *, i * sizeof (struct iovec),
649             M_TEMP, M_WAITOK);
650         uiop->uio_iov = iv2 = iv;
651         m = m3;
652         left = len;
653         i = 0;
654         while (left > 0) {
655                 if (m == NULL)
656                         panic("nfsvno_read iov");
657                 siz = min(M_TRAILINGSPACE(m), left);
658                 if (siz > 0) {
659                         iv->iov_base = mtod(m, caddr_t) + m->m_len;
660                         iv->iov_len = siz;
661                         m->m_len += siz;
662                         left -= siz;
663                         iv++;
664                         i++;
665                 }
666                 m = m->m_next;
667         }
668         uiop->uio_iovcnt = i;
669         uiop->uio_offset = off;
670         uiop->uio_resid = len;
671         uiop->uio_rw = UIO_READ;
672         uiop->uio_segflg = UIO_SYSSPACE;
673         nh = nfsrv_sequential_heuristic(uiop, vp);
674         ioflag |= nh->nh_seqcount << IO_SEQSHIFT;
675         error = VOP_READ(vp, uiop, IO_NODELOCKED | ioflag, cred);
676         FREE((caddr_t)iv2, M_TEMP);
677         if (error) {
678                 m_freem(m3);
679                 *mpp = NULL;
680                 goto out;
681         }
682         nh->nh_nextoff = uiop->uio_offset;
683         tlen = len - uiop->uio_resid;
684         cnt = cnt < tlen ? cnt : tlen;
685         tlen = NFSM_RNDUP(cnt);
686         if (tlen == 0) {
687                 m_freem(m3);
688                 m3 = NULL;
689         } else if (len != tlen || tlen != cnt)
690                 nfsrv_adj(m3, len - tlen, tlen - cnt);
691         *mpp = m3;
692         *mpendp = m2;
693
694 out:
695         NFSEXITCODE(error);
696         return (error);
697 }
698
699 /*
700  * Write vnode op from an mbuf list.
701  */
702 int
703 nfsvno_write(struct vnode *vp, off_t off, int retlen, int cnt, int stable,
704     struct mbuf *mp, char *cp, struct ucred *cred, struct thread *p)
705 {
706         struct iovec *ivp;
707         int i, len;
708         struct iovec *iv;
709         int ioflags, error;
710         struct uio io, *uiop = &io;
711         struct nfsheur *nh;
712
713         MALLOC(ivp, struct iovec *, cnt * sizeof (struct iovec), M_TEMP,
714             M_WAITOK);
715         uiop->uio_iov = iv = ivp;
716         uiop->uio_iovcnt = cnt;
717         i = mtod(mp, caddr_t) + mp->m_len - cp;
718         len = retlen;
719         while (len > 0) {
720                 if (mp == NULL)
721                         panic("nfsvno_write");
722                 if (i > 0) {
723                         i = min(i, len);
724                         ivp->iov_base = cp;
725                         ivp->iov_len = i;
726                         ivp++;
727                         len -= i;
728                 }
729                 mp = mp->m_next;
730                 if (mp) {
731                         i = mp->m_len;
732                         cp = mtod(mp, caddr_t);
733                 }
734         }
735
736         if (stable == NFSWRITE_UNSTABLE)
737                 ioflags = IO_NODELOCKED;
738         else
739                 ioflags = (IO_SYNC | IO_NODELOCKED);
740         uiop->uio_resid = retlen;
741         uiop->uio_rw = UIO_WRITE;
742         uiop->uio_segflg = UIO_SYSSPACE;
743         NFSUIOPROC(uiop, p);
744         uiop->uio_offset = off;
745         nh = nfsrv_sequential_heuristic(uiop, vp);
746         ioflags |= nh->nh_seqcount << IO_SEQSHIFT;
747         error = VOP_WRITE(vp, uiop, ioflags, cred);
748         if (error == 0)
749                 nh->nh_nextoff = uiop->uio_offset;
750         FREE((caddr_t)iv, M_TEMP);
751
752         NFSEXITCODE(error);
753         return (error);
754 }
755
756 /*
757  * Common code for creating a regular file (plus special files for V2).
758  */
759 int
760 nfsvno_createsub(struct nfsrv_descript *nd, struct nameidata *ndp,
761     struct vnode **vpp, struct nfsvattr *nvap, int *exclusive_flagp,
762     int32_t *cverf, NFSDEV_T rdev, struct thread *p, struct nfsexstuff *exp)
763 {
764         u_quad_t tempsize;
765         int error;
766
767         error = nd->nd_repstat;
768         if (!error && ndp->ni_vp == NULL) {
769                 if (nvap->na_type == VREG || nvap->na_type == VSOCK) {
770                         vrele(ndp->ni_startdir);
771                         error = VOP_CREATE(ndp->ni_dvp,
772                             &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
773                         vput(ndp->ni_dvp);
774                         nfsvno_relpathbuf(ndp);
775                         if (!error) {
776                                 if (*exclusive_flagp) {
777                                         *exclusive_flagp = 0;
778                                         NFSVNO_ATTRINIT(nvap);
779                                         nvap->na_atime.tv_sec = cverf[0];
780                                         nvap->na_atime.tv_nsec = cverf[1];
781                                         error = VOP_SETATTR(ndp->ni_vp,
782                                             &nvap->na_vattr, nd->nd_cred);
783                                 }
784                         }
785                 /*
786                  * NFS V2 Only. nfsrvd_mknod() does this for V3.
787                  * (This implies, just get out on an error.)
788                  */
789                 } else if (nvap->na_type == VCHR || nvap->na_type == VBLK ||
790                         nvap->na_type == VFIFO) {
791                         if (nvap->na_type == VCHR && rdev == 0xffffffff)
792                                 nvap->na_type = VFIFO;
793                         if (nvap->na_type != VFIFO &&
794                             (error = priv_check_cred(nd->nd_cred,
795                              PRIV_VFS_MKNOD_DEV, 0))) {
796                                 vrele(ndp->ni_startdir);
797                                 nfsvno_relpathbuf(ndp);
798                                 vput(ndp->ni_dvp);
799                                 goto out;
800                         }
801                         nvap->na_rdev = rdev;
802                         error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
803                             &ndp->ni_cnd, &nvap->na_vattr);
804                         vput(ndp->ni_dvp);
805                         nfsvno_relpathbuf(ndp);
806                         vrele(ndp->ni_startdir);
807                         if (error)
808                                 goto out;
809                 } else {
810                         vrele(ndp->ni_startdir);
811                         nfsvno_relpathbuf(ndp);
812                         vput(ndp->ni_dvp);
813                         error = ENXIO;
814                         goto out;
815                 }
816                 *vpp = ndp->ni_vp;
817         } else {
818                 /*
819                  * Handle cases where error is already set and/or
820                  * the file exists.
821                  * 1 - clean up the lookup
822                  * 2 - iff !error and na_size set, truncate it
823                  */
824                 vrele(ndp->ni_startdir);
825                 nfsvno_relpathbuf(ndp);
826                 *vpp = ndp->ni_vp;
827                 if (ndp->ni_dvp == *vpp)
828                         vrele(ndp->ni_dvp);
829                 else
830                         vput(ndp->ni_dvp);
831                 if (!error && nvap->na_size != VNOVAL) {
832                         error = nfsvno_accchk(*vpp, VWRITE,
833                             nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
834                             NFSACCCHK_VPISLOCKED, NULL);
835                         if (!error) {
836                                 tempsize = nvap->na_size;
837                                 NFSVNO_ATTRINIT(nvap);
838                                 nvap->na_size = tempsize;
839                                 error = VOP_SETATTR(*vpp,
840                                     &nvap->na_vattr, nd->nd_cred);
841                         }
842                 }
843                 if (error)
844                         vput(*vpp);
845         }
846
847 out:
848         NFSEXITCODE(error);
849         return (error);
850 }
851
852 /*
853  * Do a mknod vnode op.
854  */
855 int
856 nfsvno_mknod(struct nameidata *ndp, struct nfsvattr *nvap, struct ucred *cred,
857     struct thread *p)
858 {
859         int error = 0;
860         enum vtype vtyp;
861
862         vtyp = nvap->na_type;
863         /*
864          * Iff doesn't exist, create it.
865          */
866         if (ndp->ni_vp) {
867                 vrele(ndp->ni_startdir);
868                 nfsvno_relpathbuf(ndp);
869                 vput(ndp->ni_dvp);
870                 vrele(ndp->ni_vp);
871                 error = EEXIST;
872                 goto out;
873         }
874         if (vtyp != VCHR && vtyp != VBLK && vtyp != VSOCK && vtyp != VFIFO) {
875                 vrele(ndp->ni_startdir);
876                 nfsvno_relpathbuf(ndp);
877                 vput(ndp->ni_dvp);
878                 error = NFSERR_BADTYPE;
879                 goto out;
880         }
881         if (vtyp == VSOCK) {
882                 vrele(ndp->ni_startdir);
883                 error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
884                     &ndp->ni_cnd, &nvap->na_vattr);
885                 vput(ndp->ni_dvp);
886                 nfsvno_relpathbuf(ndp);
887         } else {
888                 if (nvap->na_type != VFIFO &&
889                     (error = priv_check_cred(cred, PRIV_VFS_MKNOD_DEV, 0))) {
890                         vrele(ndp->ni_startdir);
891                         nfsvno_relpathbuf(ndp);
892                         vput(ndp->ni_dvp);
893                         goto out;
894                 }
895                 error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
896                     &ndp->ni_cnd, &nvap->na_vattr);
897                 vput(ndp->ni_dvp);
898                 nfsvno_relpathbuf(ndp);
899                 vrele(ndp->ni_startdir);
900                 /*
901                  * Since VOP_MKNOD returns the ni_vp, I can't
902                  * see any reason to do the lookup.
903                  */
904         }
905
906 out:
907         NFSEXITCODE(error);
908         return (error);
909 }
910
911 /*
912  * Mkdir vnode op.
913  */
914 int
915 nfsvno_mkdir(struct nameidata *ndp, struct nfsvattr *nvap, uid_t saved_uid,
916     struct ucred *cred, struct thread *p, struct nfsexstuff *exp)
917 {
918         int error = 0;
919
920         if (ndp->ni_vp != NULL) {
921                 if (ndp->ni_dvp == ndp->ni_vp)
922                         vrele(ndp->ni_dvp);
923                 else
924                         vput(ndp->ni_dvp);
925                 vrele(ndp->ni_vp);
926                 nfsvno_relpathbuf(ndp);
927                 error = EEXIST;
928                 goto out;
929         }
930         error = VOP_MKDIR(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
931             &nvap->na_vattr);
932         vput(ndp->ni_dvp);
933         nfsvno_relpathbuf(ndp);
934
935 out:
936         NFSEXITCODE(error);
937         return (error);
938 }
939
940 /*
941  * symlink vnode op.
942  */
943 int
944 nfsvno_symlink(struct nameidata *ndp, struct nfsvattr *nvap, char *pathcp,
945     int pathlen, int not_v2, uid_t saved_uid, struct ucred *cred, struct thread *p,
946     struct nfsexstuff *exp)
947 {
948         int error = 0;
949
950         if (ndp->ni_vp) {
951                 vrele(ndp->ni_startdir);
952                 nfsvno_relpathbuf(ndp);
953                 if (ndp->ni_dvp == ndp->ni_vp)
954                         vrele(ndp->ni_dvp);
955                 else
956                         vput(ndp->ni_dvp);
957                 vrele(ndp->ni_vp);
958                 error = EEXIST;
959                 goto out;
960         }
961
962         error = VOP_SYMLINK(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
963             &nvap->na_vattr, pathcp);
964         vput(ndp->ni_dvp);
965         vrele(ndp->ni_startdir);
966         nfsvno_relpathbuf(ndp);
967         /*
968          * Although FreeBSD still had the lookup code in
969          * it for 7/current, there doesn't seem to be any
970          * point, since VOP_SYMLINK() returns the ni_vp.
971          * Just vput it for v2.
972          */
973         if (!not_v2 && !error)
974                 vput(ndp->ni_vp);
975
976 out:
977         NFSEXITCODE(error);
978         return (error);
979 }
980
981 /*
982  * Parse symbolic link arguments.
983  * This function has an ugly side effect. It will MALLOC() an area for
984  * the symlink and set iov_base to point to it, only if it succeeds.
985  * So, if it returns with uiop->uio_iov->iov_base != NULL, that must
986  * be FREE'd later.
987  */
988 int
989 nfsvno_getsymlink(struct nfsrv_descript *nd, struct nfsvattr *nvap,
990     struct thread *p, char **pathcpp, int *lenp)
991 {
992         u_int32_t *tl;
993         char *pathcp = NULL;
994         int error = 0, len;
995         struct nfsv2_sattr *sp;
996
997         *pathcpp = NULL;
998         *lenp = 0;
999         if ((nd->nd_flag & ND_NFSV3) &&
1000             (error = nfsrv_sattr(nd, nvap, NULL, NULL, p)))
1001                 goto nfsmout;
1002         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
1003         len = fxdr_unsigned(int, *tl);
1004         if (len > NFS_MAXPATHLEN || len <= 0) {
1005                 error = EBADRPC;
1006                 goto nfsmout;
1007         }
1008         MALLOC(pathcp, caddr_t, len + 1, M_TEMP, M_WAITOK);
1009         error = nfsrv_mtostr(nd, pathcp, len);
1010         if (error)
1011                 goto nfsmout;
1012         if (nd->nd_flag & ND_NFSV2) {
1013                 NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
1014                 nvap->na_mode = fxdr_unsigned(u_int16_t, sp->sa_mode);
1015         }
1016         *pathcpp = pathcp;
1017         *lenp = len;
1018         NFSEXITCODE2(0, nd);
1019         return (0);
1020 nfsmout:
1021         if (pathcp)
1022                 free(pathcp, M_TEMP);
1023         NFSEXITCODE2(error, nd);
1024         return (error);
1025 }
1026
1027 /*
1028  * Remove a non-directory object.
1029  */
1030 int
1031 nfsvno_removesub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1032     struct thread *p, struct nfsexstuff *exp)
1033 {
1034         struct vnode *vp;
1035         int error = 0;
1036
1037         vp = ndp->ni_vp;
1038         if (vp->v_type == VDIR)
1039                 error = NFSERR_ISDIR;
1040         else if (is_v4)
1041                 error = nfsrv_checkremove(vp, 1, p);
1042         if (!error)
1043                 error = VOP_REMOVE(ndp->ni_dvp, vp, &ndp->ni_cnd);
1044         if (ndp->ni_dvp == vp)
1045                 vrele(ndp->ni_dvp);
1046         else
1047                 vput(ndp->ni_dvp);
1048         vput(vp);
1049         if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1050                 nfsvno_relpathbuf(ndp);
1051         NFSEXITCODE(error);
1052         return (error);
1053 }
1054
1055 /*
1056  * Remove a directory.
1057  */
1058 int
1059 nfsvno_rmdirsub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1060     struct thread *p, struct nfsexstuff *exp)
1061 {
1062         struct vnode *vp;
1063         int error = 0;
1064
1065         vp = ndp->ni_vp;
1066         if (vp->v_type != VDIR) {
1067                 error = ENOTDIR;
1068                 goto out;
1069         }
1070         /*
1071          * No rmdir "." please.
1072          */
1073         if (ndp->ni_dvp == vp) {
1074                 error = EINVAL;
1075                 goto out;
1076         }
1077         /*
1078          * The root of a mounted filesystem cannot be deleted.
1079          */
1080         if (vp->v_vflag & VV_ROOT)
1081                 error = EBUSY;
1082 out:
1083         if (!error)
1084                 error = VOP_RMDIR(ndp->ni_dvp, vp, &ndp->ni_cnd);
1085         if (ndp->ni_dvp == vp)
1086                 vrele(ndp->ni_dvp);
1087         else
1088                 vput(ndp->ni_dvp);
1089         vput(vp);
1090         if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1091                 nfsvno_relpathbuf(ndp);
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         /*
1258          * RFC 1813 3.3.21: if count is 0, a flush from offset to the end of
1259          * file is done.  At this time VOP_FSYNC does not accept offset and
1260          * byte count parameters so call VOP_FSYNC the whole file for now.
1261          * The same is true for NFSv4: RFC 3530 Sec. 14.2.3.
1262          */
1263         if (cnt == 0 || cnt > MAX_COMMIT_COUNT) {
1264                 /*
1265                  * Give up and do the whole thing
1266                  */
1267                 if (vp->v_object &&
1268                    (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
1269                         VM_OBJECT_LOCK(vp->v_object);
1270                         vm_object_page_clean(vp->v_object, 0, 0, OBJPC_SYNC);
1271                         VM_OBJECT_UNLOCK(vp->v_object);
1272                 }
1273                 error = VOP_FSYNC(vp, MNT_WAIT, td);
1274         } else {
1275                 /*
1276                  * Locate and synchronously write any buffers that fall
1277                  * into the requested range.  Note:  we are assuming that
1278                  * f_iosize is a power of 2.
1279                  */
1280                 int iosize = vp->v_mount->mnt_stat.f_iosize;
1281                 int iomask = iosize - 1;
1282                 struct bufobj *bo;
1283                 daddr_t lblkno;
1284
1285                 /*
1286                  * Align to iosize boundry, super-align to page boundry.
1287                  */
1288                 if (off & iomask) {
1289                         cnt += off & iomask;
1290                         off &= ~(u_quad_t)iomask;
1291                 }
1292                 if (off & PAGE_MASK) {
1293                         cnt += off & PAGE_MASK;
1294                         off &= ~(u_quad_t)PAGE_MASK;
1295                 }
1296                 lblkno = off / iosize;
1297
1298                 if (vp->v_object &&
1299                    (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
1300                         VM_OBJECT_LOCK(vp->v_object);
1301                         vm_object_page_clean(vp->v_object, off, off + cnt,
1302                             OBJPC_SYNC);
1303                         VM_OBJECT_UNLOCK(vp->v_object);
1304                 }
1305
1306                 bo = &vp->v_bufobj;
1307                 BO_LOCK(bo);
1308                 while (cnt > 0) {
1309                         struct buf *bp;
1310
1311                         /*
1312                          * If we have a buffer and it is marked B_DELWRI we
1313                          * have to lock and write it.  Otherwise the prior
1314                          * write is assumed to have already been committed.
1315                          *
1316                          * gbincore() can return invalid buffers now so we
1317                          * have to check that bit as well (though B_DELWRI
1318                          * should not be set if B_INVAL is set there could be
1319                          * a race here since we haven't locked the buffer).
1320                          */
1321                         if ((bp = gbincore(&vp->v_bufobj, lblkno)) != NULL) {
1322                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
1323                                     LK_INTERLOCK, BO_MTX(bo)) == ENOLCK) {
1324                                         BO_LOCK(bo);
1325                                         continue; /* retry */
1326                                 }
1327                                 if ((bp->b_flags & (B_DELWRI|B_INVAL)) ==
1328                                     B_DELWRI) {
1329                                         bremfree(bp);
1330                                         bp->b_flags &= ~B_ASYNC;
1331                                         bwrite(bp);
1332                                         ++nfs_commit_miss;
1333                                 } else
1334                                         BUF_UNLOCK(bp);
1335                                 BO_LOCK(bo);
1336                         }
1337                         ++nfs_commit_blks;
1338                         if (cnt < iosize)
1339                                 break;
1340                         cnt -= iosize;
1341                         ++lblkno;
1342                 }
1343                 BO_UNLOCK(bo);
1344         }
1345         NFSEXITCODE(error);
1346         return (error);
1347 }
1348
1349 /*
1350  * Statfs vnode op.
1351  */
1352 int
1353 nfsvno_statfs(struct vnode *vp, struct statfs *sf)
1354 {
1355         int error;
1356
1357         error = VFS_STATFS(vp->v_mount, sf);
1358         if (error == 0) {
1359                 /*
1360                  * Since NFS handles these values as unsigned on the
1361                  * wire, there is no way to represent negative values,
1362                  * so set them to 0. Without this, they will appear
1363                  * to be very large positive values for clients like
1364                  * Solaris10.
1365                  */
1366                 if (sf->f_bavail < 0)
1367                         sf->f_bavail = 0;
1368                 if (sf->f_ffree < 0)
1369                         sf->f_ffree = 0;
1370         }
1371         NFSEXITCODE(error);
1372         return (error);
1373 }
1374
1375 /*
1376  * Do the vnode op stuff for Open. Similar to nfsvno_createsub(), but
1377  * must handle nfsrv_opencheck() calls after any other access checks.
1378  */
1379 void
1380 nfsvno_open(struct nfsrv_descript *nd, struct nameidata *ndp,
1381     nfsquad_t clientid, nfsv4stateid_t *stateidp, struct nfsstate *stp,
1382     int *exclusive_flagp, struct nfsvattr *nvap, int32_t *cverf, int create,
1383     NFSACL_T *aclp, nfsattrbit_t *attrbitp, struct ucred *cred, struct thread *p,
1384     struct nfsexstuff *exp, struct vnode **vpp)
1385 {
1386         struct vnode *vp = NULL;
1387         u_quad_t tempsize;
1388         struct nfsexstuff nes;
1389
1390         if (ndp->ni_vp == NULL)
1391                 nd->nd_repstat = nfsrv_opencheck(clientid,
1392                     stateidp, stp, NULL, nd, p, nd->nd_repstat);
1393         if (!nd->nd_repstat) {
1394                 if (ndp->ni_vp == NULL) {
1395                         vrele(ndp->ni_startdir);
1396                         nd->nd_repstat = VOP_CREATE(ndp->ni_dvp,
1397                             &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
1398                         vput(ndp->ni_dvp);
1399                         nfsvno_relpathbuf(ndp);
1400                         if (!nd->nd_repstat) {
1401                                 if (*exclusive_flagp) {
1402                                         *exclusive_flagp = 0;
1403                                         NFSVNO_ATTRINIT(nvap);
1404                                         nvap->na_atime.tv_sec = cverf[0];
1405                                         nvap->na_atime.tv_nsec = cverf[1];
1406                                         nd->nd_repstat = VOP_SETATTR(ndp->ni_vp,
1407                                             &nvap->na_vattr, cred);
1408                                 } else {
1409                                         nfsrv_fixattr(nd, ndp->ni_vp, nvap,
1410                                             aclp, p, attrbitp, exp);
1411                                 }
1412                         }
1413                         vp = ndp->ni_vp;
1414                 } else {
1415                         if (ndp->ni_startdir)
1416                                 vrele(ndp->ni_startdir);
1417                         nfsvno_relpathbuf(ndp);
1418                         vp = ndp->ni_vp;
1419                         if (create == NFSV4OPEN_CREATE) {
1420                                 if (ndp->ni_dvp == vp)
1421                                         vrele(ndp->ni_dvp);
1422                                 else
1423                                         vput(ndp->ni_dvp);
1424                         }
1425                         if (NFSVNO_ISSETSIZE(nvap) && vp->v_type == VREG) {
1426                                 if (ndp->ni_cnd.cn_flags & RDONLY)
1427                                         NFSVNO_SETEXRDONLY(&nes);
1428                                 else
1429                                         NFSVNO_EXINIT(&nes);
1430                                 nd->nd_repstat = nfsvno_accchk(vp, 
1431                                     VWRITE, cred, &nes, p,
1432                                     NFSACCCHK_NOOVERRIDE,
1433                                     NFSACCCHK_VPISLOCKED, NULL);
1434                                 nd->nd_repstat = nfsrv_opencheck(clientid,
1435                                     stateidp, stp, vp, nd, p, nd->nd_repstat);
1436                                 if (!nd->nd_repstat) {
1437                                         tempsize = nvap->na_size;
1438                                         NFSVNO_ATTRINIT(nvap);
1439                                         nvap->na_size = tempsize;
1440                                         nd->nd_repstat = VOP_SETATTR(vp,
1441                                             &nvap->na_vattr, cred);
1442                                 }
1443                         } else if (vp->v_type == VREG) {
1444                                 nd->nd_repstat = nfsrv_opencheck(clientid,
1445                                     stateidp, stp, vp, nd, p, nd->nd_repstat);
1446                         }
1447                 }
1448         } else {
1449                 if (ndp->ni_cnd.cn_flags & HASBUF)
1450                         nfsvno_relpathbuf(ndp);
1451                 if (ndp->ni_startdir && create == NFSV4OPEN_CREATE) {
1452                         vrele(ndp->ni_startdir);
1453                         if (ndp->ni_dvp == ndp->ni_vp)
1454                                 vrele(ndp->ni_dvp);
1455                         else
1456                                 vput(ndp->ni_dvp);
1457                         if (ndp->ni_vp)
1458                                 vput(ndp->ni_vp);
1459                 }
1460         }
1461         *vpp = vp;
1462
1463         NFSEXITCODE2(0, nd);
1464 }
1465
1466 /*
1467  * Updates the file rev and sets the mtime and ctime
1468  * to the current clock time, returning the va_filerev and va_Xtime
1469  * values.
1470  */
1471 void
1472 nfsvno_updfilerev(struct vnode *vp, struct nfsvattr *nvap,
1473     struct ucred *cred, struct thread *p)
1474 {
1475         struct vattr va;
1476
1477         VATTR_NULL(&va);
1478         getnanotime(&va.va_mtime);
1479         (void) VOP_SETATTR(vp, &va, cred);
1480         (void) nfsvno_getattr(vp, nvap, cred, p, 1);
1481 }
1482
1483 /*
1484  * Glue routine to nfsv4_fillattr().
1485  */
1486 int
1487 nfsvno_fillattr(struct nfsrv_descript *nd, struct mount *mp, struct vnode *vp,
1488     struct nfsvattr *nvap, fhandle_t *fhp, int rderror, nfsattrbit_t *attrbitp,
1489     struct ucred *cred, struct thread *p, int isdgram, int reterr,
1490     int supports_nfsv4acls, int at_root, uint64_t mounted_on_fileno)
1491 {
1492         int error;
1493
1494         error = nfsv4_fillattr(nd, mp, vp, NULL, &nvap->na_vattr, fhp, rderror,
1495             attrbitp, cred, p, isdgram, reterr, supports_nfsv4acls, at_root,
1496             mounted_on_fileno);
1497         NFSEXITCODE2(0, nd);
1498         return (error);
1499 }
1500
1501 /* Since the Readdir vnode ops vary, put the entire functions in here. */
1502 /*
1503  * nfs readdir service
1504  * - mallocs what it thinks is enough to read
1505  *      count rounded up to a multiple of DIRBLKSIZ <= NFS_MAXREADDIR
1506  * - calls VOP_READDIR()
1507  * - loops around building the reply
1508  *      if the output generated exceeds count break out of loop
1509  *      The NFSM_CLGET macro is used here so that the reply will be packed
1510  *      tightly in mbuf clusters.
1511  * - it trims out records with d_fileno == 0
1512  *      this doesn't matter for Unix clients, but they might confuse clients
1513  *      for other os'.
1514  * - it trims out records with d_type == DT_WHT
1515  *      these cannot be seen through NFS (unless we extend the protocol)
1516  *     The alternate call nfsrvd_readdirplus() does lookups as well.
1517  * PS: The NFS protocol spec. does not clarify what the "count" byte
1518  *      argument is a count of.. just name strings and file id's or the
1519  *      entire reply rpc or ...
1520  *      I tried just file name and id sizes and it confused the Sun client,
1521  *      so I am using the full rpc size now. The "paranoia.." comment refers
1522  *      to including the status longwords that are not a part of the dir.
1523  *      "entry" structures, but are in the rpc.
1524  */
1525 int
1526 nfsrvd_readdir(struct nfsrv_descript *nd, int isdgram,
1527     struct vnode *vp, struct thread *p, struct nfsexstuff *exp)
1528 {
1529         struct dirent *dp;
1530         u_int32_t *tl;
1531         int dirlen;
1532         char *cpos, *cend, *rbuf;
1533         struct nfsvattr at;
1534         int nlen, error = 0, getret = 1;
1535         int siz, cnt, fullsiz, eofflag, ncookies;
1536         u_int64_t off, toff, verf;
1537         u_long *cookies = NULL, *cookiep;
1538         struct uio io;
1539         struct iovec iv;
1540         int not_zfs;
1541
1542         if (nd->nd_repstat) {
1543                 nfsrv_postopattr(nd, getret, &at);
1544                 goto out;
1545         }
1546         if (nd->nd_flag & ND_NFSV2) {
1547                 NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1548                 off = fxdr_unsigned(u_quad_t, *tl++);
1549         } else {
1550                 NFSM_DISSECT(tl, u_int32_t *, 5 * NFSX_UNSIGNED);
1551                 off = fxdr_hyper(tl);
1552                 tl += 2;
1553                 verf = fxdr_hyper(tl);
1554                 tl += 2;
1555         }
1556         toff = off;
1557         cnt = fxdr_unsigned(int, *tl);
1558         if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
1559                 cnt = NFS_SRVMAXDATA(nd);
1560         siz = ((cnt + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
1561         fullsiz = siz;
1562         if (nd->nd_flag & ND_NFSV3) {
1563                 nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd->nd_cred,
1564                     p, 1);
1565 #if 0
1566                 /*
1567                  * va_filerev is not sufficient as a cookie verifier,
1568                  * since it is not supposed to change when entries are
1569                  * removed/added unless that offset cookies returned to
1570                  * the client are no longer valid.
1571                  */
1572                 if (!nd->nd_repstat && toff && verf != at.na_filerev)
1573                         nd->nd_repstat = NFSERR_BAD_COOKIE;
1574 #endif
1575         }
1576         if (nd->nd_repstat == 0 && cnt == 0) {
1577                 if (nd->nd_flag & ND_NFSV2)
1578                         /* NFSv2 does not have NFSERR_TOOSMALL */
1579                         nd->nd_repstat = EPERM;
1580                 else
1581                         nd->nd_repstat = NFSERR_TOOSMALL;
1582         }
1583         if (!nd->nd_repstat)
1584                 nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
1585                     nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1586                     NFSACCCHK_VPISLOCKED, NULL);
1587         if (nd->nd_repstat) {
1588                 vput(vp);
1589                 if (nd->nd_flag & ND_NFSV3)
1590                         nfsrv_postopattr(nd, getret, &at);
1591                 goto out;
1592         }
1593         not_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs");
1594         MALLOC(rbuf, caddr_t, siz, M_TEMP, M_WAITOK);
1595 again:
1596         eofflag = 0;
1597         if (cookies) {
1598                 free((caddr_t)cookies, M_TEMP);
1599                 cookies = NULL;
1600         }
1601
1602         iv.iov_base = rbuf;
1603         iv.iov_len = siz;
1604         io.uio_iov = &iv;
1605         io.uio_iovcnt = 1;
1606         io.uio_offset = (off_t)off;
1607         io.uio_resid = siz;
1608         io.uio_segflg = UIO_SYSSPACE;
1609         io.uio_rw = UIO_READ;
1610         io.uio_td = NULL;
1611         nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
1612             &cookies);
1613         off = (u_int64_t)io.uio_offset;
1614         if (io.uio_resid)
1615                 siz -= io.uio_resid;
1616
1617         if (!cookies && !nd->nd_repstat)
1618                 nd->nd_repstat = NFSERR_PERM;
1619         if (nd->nd_flag & ND_NFSV3) {
1620                 getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1621                 if (!nd->nd_repstat)
1622                         nd->nd_repstat = getret;
1623         }
1624
1625         /*
1626          * Handles the failed cases. nd->nd_repstat == 0 past here.
1627          */
1628         if (nd->nd_repstat) {
1629                 vput(vp);
1630                 free((caddr_t)rbuf, M_TEMP);
1631                 if (cookies)
1632                         free((caddr_t)cookies, M_TEMP);
1633                 if (nd->nd_flag & ND_NFSV3)
1634                         nfsrv_postopattr(nd, getret, &at);
1635                 goto out;
1636         }
1637         /*
1638          * If nothing read, return eof
1639          * rpc reply
1640          */
1641         if (siz == 0) {
1642                 vput(vp);
1643                 if (nd->nd_flag & ND_NFSV2) {
1644                         NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1645                 } else {
1646                         nfsrv_postopattr(nd, getret, &at);
1647                         NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
1648                         txdr_hyper(at.na_filerev, tl);
1649                         tl += 2;
1650                 }
1651                 *tl++ = newnfs_false;
1652                 *tl = newnfs_true;
1653                 FREE((caddr_t)rbuf, M_TEMP);
1654                 FREE((caddr_t)cookies, M_TEMP);
1655                 goto out;
1656         }
1657
1658         /*
1659          * Check for degenerate cases of nothing useful read.
1660          * If so go try again
1661          */
1662         cpos = rbuf;
1663         cend = rbuf + siz;
1664         dp = (struct dirent *)cpos;
1665         cookiep = cookies;
1666
1667         /*
1668          * For some reason FreeBSD's ufs_readdir() chooses to back the
1669          * directory offset up to a block boundary, so it is necessary to
1670          * skip over the records that precede the requested offset. This
1671          * requires the assumption that file offset cookies monotonically
1672          * increase.
1673          * Since the offset cookies don't monotonically increase for ZFS,
1674          * this is not done when ZFS is the file system.
1675          */
1676         while (cpos < cend && ncookies > 0 &&
1677             (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
1678              (not_zfs != 0 && ((u_quad_t)(*cookiep)) <= toff))) {
1679                 cpos += dp->d_reclen;
1680                 dp = (struct dirent *)cpos;
1681                 cookiep++;
1682                 ncookies--;
1683         }
1684         if (cpos >= cend || ncookies == 0) {
1685                 siz = fullsiz;
1686                 toff = off;
1687                 goto again;
1688         }
1689         vput(vp);
1690
1691         /*
1692          * dirlen is the size of the reply, including all XDR and must
1693          * not exceed cnt. For NFSv2, RFC1094 didn't clearly indicate
1694          * if the XDR should be included in "count", but to be safe, we do.
1695          * (Include the two booleans at the end of the reply in dirlen now.)
1696          */
1697         if (nd->nd_flag & ND_NFSV3) {
1698                 nfsrv_postopattr(nd, getret, &at);
1699                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1700                 txdr_hyper(at.na_filerev, tl);
1701                 dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
1702         } else {
1703                 dirlen = 2 * NFSX_UNSIGNED;
1704         }
1705
1706         /* Loop through the records and build reply */
1707         while (cpos < cend && ncookies > 0) {
1708                 nlen = dp->d_namlen;
1709                 if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
1710                         nlen <= NFS_MAXNAMLEN) {
1711                         if (nd->nd_flag & ND_NFSV3)
1712                                 dirlen += (6*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
1713                         else
1714                                 dirlen += (4*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
1715                         if (dirlen > cnt) {
1716                                 eofflag = 0;
1717                                 break;
1718                         }
1719
1720                         /*
1721                          * Build the directory record xdr from
1722                          * the dirent entry.
1723                          */
1724                         if (nd->nd_flag & ND_NFSV3) {
1725                                 NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
1726                                 *tl++ = newnfs_true;
1727                                 *tl++ = 0;
1728                         } else {
1729                                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1730                                 *tl++ = newnfs_true;
1731                         }
1732                         *tl = txdr_unsigned(dp->d_fileno);
1733                         (void) nfsm_strtom(nd, dp->d_name, nlen);
1734                         if (nd->nd_flag & ND_NFSV3) {
1735                                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1736                                 *tl++ = 0;
1737                         } else
1738                                 NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
1739                         *tl = txdr_unsigned(*cookiep);
1740                 }
1741                 cpos += dp->d_reclen;
1742                 dp = (struct dirent *)cpos;
1743                 cookiep++;
1744                 ncookies--;
1745         }
1746         if (cpos < cend)
1747                 eofflag = 0;
1748         NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1749         *tl++ = newnfs_false;
1750         if (eofflag)
1751                 *tl = newnfs_true;
1752         else
1753                 *tl = newnfs_false;
1754         FREE((caddr_t)rbuf, M_TEMP);
1755         FREE((caddr_t)cookies, M_TEMP);
1756
1757 out:
1758         NFSEXITCODE2(0, nd);
1759         return (0);
1760 nfsmout:
1761         vput(vp);
1762         NFSEXITCODE2(error, nd);
1763         return (error);
1764 }
1765
1766 /*
1767  * Readdirplus for V3 and Readdir for V4.
1768  */
1769 int
1770 nfsrvd_readdirplus(struct nfsrv_descript *nd, int isdgram,
1771     struct vnode *vp, struct thread *p, struct nfsexstuff *exp)
1772 {
1773         struct dirent *dp;
1774         u_int32_t *tl;
1775         int dirlen;
1776         char *cpos, *cend, *rbuf;
1777         struct vnode *nvp;
1778         fhandle_t nfh;
1779         struct nfsvattr nva, at, *nvap = &nva;
1780         struct mbuf *mb0, *mb1;
1781         struct nfsreferral *refp;
1782         int nlen, r, error = 0, getret = 1, usevget = 1;
1783         int siz, cnt, fullsiz, eofflag, ncookies, entrycnt;
1784         caddr_t bpos0, bpos1;
1785         u_int64_t off, toff, verf;
1786         u_long *cookies = NULL, *cookiep;
1787         nfsattrbit_t attrbits, rderrbits, savbits;
1788         struct uio io;
1789         struct iovec iv;
1790         struct componentname cn;
1791         int at_root, needs_unbusy, not_zfs, supports_nfsv4acls;
1792         struct mount *mp, *new_mp;
1793         uint64_t mounted_on_fileno;
1794
1795         if (nd->nd_repstat) {
1796                 nfsrv_postopattr(nd, getret, &at);
1797                 goto out;
1798         }
1799         NFSM_DISSECT(tl, u_int32_t *, 6 * NFSX_UNSIGNED);
1800         off = fxdr_hyper(tl);
1801         toff = off;
1802         tl += 2;
1803         verf = fxdr_hyper(tl);
1804         tl += 2;
1805         siz = fxdr_unsigned(int, *tl++);
1806         cnt = fxdr_unsigned(int, *tl);
1807
1808         /*
1809          * Use the server's maximum data transfer size as the upper bound
1810          * on reply datalen.
1811          */
1812         if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
1813                 cnt = NFS_SRVMAXDATA(nd);
1814
1815         /*
1816          * siz is a "hint" of how much directory information (name, fileid,
1817          * cookie) should be in the reply. At least one client "hints" 0,
1818          * so I set it to cnt for that case. I also round it up to the
1819          * next multiple of DIRBLKSIZ.
1820          */
1821         if (siz <= 0)
1822                 siz = cnt;
1823         siz = ((siz + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
1824
1825         if (nd->nd_flag & ND_NFSV4) {
1826                 error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
1827                 if (error)
1828                         goto nfsmout;
1829                 NFSSET_ATTRBIT(&savbits, &attrbits);
1830                 NFSCLRNOTFILLABLE_ATTRBIT(&attrbits);
1831                 NFSZERO_ATTRBIT(&rderrbits);
1832                 NFSSETBIT_ATTRBIT(&rderrbits, NFSATTRBIT_RDATTRERROR);
1833         } else {
1834                 NFSZERO_ATTRBIT(&attrbits);
1835         }
1836         fullsiz = siz;
1837         nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1838         if (!nd->nd_repstat) {
1839             if (off && verf != at.na_filerev) {
1840                 /*
1841                  * va_filerev is not sufficient as a cookie verifier,
1842                  * since it is not supposed to change when entries are
1843                  * removed/added unless that offset cookies returned to
1844                  * the client are no longer valid.
1845                  */
1846 #if 0
1847                 if (nd->nd_flag & ND_NFSV4) {
1848                         nd->nd_repstat = NFSERR_NOTSAME;
1849                 } else {
1850                         nd->nd_repstat = NFSERR_BAD_COOKIE;
1851                 }
1852 #endif
1853             } else if ((nd->nd_flag & ND_NFSV4) && off == 0 && verf != 0) {
1854                 nd->nd_repstat = NFSERR_BAD_COOKIE;
1855             }
1856         }
1857         if (!nd->nd_repstat && vp->v_type != VDIR)
1858                 nd->nd_repstat = NFSERR_NOTDIR;
1859         if (!nd->nd_repstat && cnt == 0)
1860                 nd->nd_repstat = NFSERR_TOOSMALL;
1861         if (!nd->nd_repstat)
1862                 nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
1863                     nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1864                     NFSACCCHK_VPISLOCKED, NULL);
1865         if (nd->nd_repstat) {
1866                 vput(vp);
1867                 if (nd->nd_flag & ND_NFSV3)
1868                         nfsrv_postopattr(nd, getret, &at);
1869                 goto out;
1870         }
1871         not_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs");
1872
1873         MALLOC(rbuf, caddr_t, siz, M_TEMP, M_WAITOK);
1874 again:
1875         eofflag = 0;
1876         if (cookies) {
1877                 free((caddr_t)cookies, M_TEMP);
1878                 cookies = NULL;
1879         }
1880
1881         iv.iov_base = rbuf;
1882         iv.iov_len = siz;
1883         io.uio_iov = &iv;
1884         io.uio_iovcnt = 1;
1885         io.uio_offset = (off_t)off;
1886         io.uio_resid = siz;
1887         io.uio_segflg = UIO_SYSSPACE;
1888         io.uio_rw = UIO_READ;
1889         io.uio_td = NULL;
1890         nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
1891             &cookies);
1892         off = (u_int64_t)io.uio_offset;
1893         if (io.uio_resid)
1894                 siz -= io.uio_resid;
1895
1896         getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1897
1898         if (!cookies && !nd->nd_repstat)
1899                 nd->nd_repstat = NFSERR_PERM;
1900         if (!nd->nd_repstat)
1901                 nd->nd_repstat = getret;
1902         if (nd->nd_repstat) {
1903                 vput(vp);
1904                 if (cookies)
1905                         free((caddr_t)cookies, M_TEMP);
1906                 free((caddr_t)rbuf, M_TEMP);
1907                 if (nd->nd_flag & ND_NFSV3)
1908                         nfsrv_postopattr(nd, getret, &at);
1909                 goto out;
1910         }
1911         /*
1912          * If nothing read, return eof
1913          * rpc reply
1914          */
1915         if (siz == 0) {
1916                 vput(vp);
1917                 if (nd->nd_flag & ND_NFSV3)
1918                         nfsrv_postopattr(nd, getret, &at);
1919                 NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
1920                 txdr_hyper(at.na_filerev, tl);
1921                 tl += 2;
1922                 *tl++ = newnfs_false;
1923                 *tl = newnfs_true;
1924                 free((caddr_t)cookies, M_TEMP);
1925                 free((caddr_t)rbuf, M_TEMP);
1926                 goto out;
1927         }
1928
1929         /*
1930          * Check for degenerate cases of nothing useful read.
1931          * If so go try again
1932          */
1933         cpos = rbuf;
1934         cend = rbuf + siz;
1935         dp = (struct dirent *)cpos;
1936         cookiep = cookies;
1937
1938         /*
1939          * For some reason FreeBSD's ufs_readdir() chooses to back the
1940          * directory offset up to a block boundary, so it is necessary to
1941          * skip over the records that precede the requested offset. This
1942          * requires the assumption that file offset cookies monotonically
1943          * increase.
1944          * Since the offset cookies don't monotonically increase for ZFS,
1945          * this is not done when ZFS is the file system.
1946          */
1947         while (cpos < cend && ncookies > 0 &&
1948           (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
1949            (not_zfs != 0 && ((u_quad_t)(*cookiep)) <= toff) ||
1950            ((nd->nd_flag & ND_NFSV4) &&
1951             ((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
1952              (dp->d_namlen==2 && dp->d_name[0]=='.' && dp->d_name[1]=='.'))))) {
1953                 cpos += dp->d_reclen;
1954                 dp = (struct dirent *)cpos;
1955                 cookiep++;
1956                 ncookies--;
1957         }
1958         if (cpos >= cend || ncookies == 0) {
1959                 siz = fullsiz;
1960                 toff = off;
1961                 goto again;
1962         }
1963
1964         /*
1965          * Busy the file system so that the mount point won't go away
1966          * and, as such, VFS_VGET() can be used safely.
1967          */
1968         mp = vp->v_mount;
1969         vfs_ref(mp);
1970         NFSVOPUNLOCK(vp, 0);
1971         nd->nd_repstat = vfs_busy(mp, 0);
1972         vfs_rel(mp);
1973         if (nd->nd_repstat != 0) {
1974                 vrele(vp);
1975                 free(cookies, M_TEMP);
1976                 free(rbuf, M_TEMP);
1977                 if (nd->nd_flag & ND_NFSV3)
1978                         nfsrv_postopattr(nd, getret, &at);
1979                 goto out;
1980         }
1981
1982         /*
1983          * Save this position, in case there is an error before one entry
1984          * is created.
1985          */
1986         mb0 = nd->nd_mb;
1987         bpos0 = nd->nd_bpos;
1988
1989         /*
1990          * Fill in the first part of the reply.
1991          * dirlen is the reply length in bytes and cannot exceed cnt.
1992          * (Include the two booleans at the end of the reply in dirlen now,
1993          *  so we recognize when we have exceeded cnt.)
1994          */
1995         if (nd->nd_flag & ND_NFSV3) {
1996                 dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
1997                 nfsrv_postopattr(nd, getret, &at);
1998         } else {
1999                 dirlen = NFSX_VERF + 2 * NFSX_UNSIGNED;
2000         }
2001         NFSM_BUILD(tl, u_int32_t *, NFSX_VERF);
2002         txdr_hyper(at.na_filerev, tl);
2003
2004         /*
2005          * Save this position, in case there is an empty reply needed.
2006          */
2007         mb1 = nd->nd_mb;
2008         bpos1 = nd->nd_bpos;
2009
2010         /* Loop through the records and build reply */
2011         entrycnt = 0;
2012         while (cpos < cend && ncookies > 0 && dirlen < cnt) {
2013                 nlen = dp->d_namlen;
2014                 if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
2015                     nlen <= NFS_MAXNAMLEN &&
2016                     ((nd->nd_flag & ND_NFSV3) || nlen > 2 ||
2017                      (nlen==2 && (dp->d_name[0]!='.' || dp->d_name[1]!='.'))
2018                       || (nlen == 1 && dp->d_name[0] != '.'))) {
2019                         /*
2020                          * Save the current position in the reply, in case
2021                          * this entry exceeds cnt.
2022                          */
2023                         mb1 = nd->nd_mb;
2024                         bpos1 = nd->nd_bpos;
2025         
2026                         /*
2027                          * For readdir_and_lookup get the vnode using
2028                          * the file number.
2029                          */
2030                         nvp = NULL;
2031                         refp = NULL;
2032                         r = 0;
2033                         at_root = 0;
2034                         needs_unbusy = 0;
2035                         new_mp = mp;
2036                         mounted_on_fileno = (uint64_t)dp->d_fileno;
2037                         if ((nd->nd_flag & ND_NFSV3) ||
2038                             NFSNONZERO_ATTRBIT(&savbits)) {
2039                                 if (nd->nd_flag & ND_NFSV4)
2040                                         refp = nfsv4root_getreferral(NULL,
2041                                             vp, dp->d_fileno);
2042                                 if (refp == NULL) {
2043                                         if (usevget)
2044                                                 r = VFS_VGET(mp, dp->d_fileno,
2045                                                     LK_SHARED, &nvp);
2046                                         else
2047                                                 r = EOPNOTSUPP;
2048                                         if (r == EOPNOTSUPP) {
2049                                                 if (usevget) {
2050                                                         usevget = 0;
2051                                                         cn.cn_nameiop = LOOKUP;
2052                                                         cn.cn_lkflags =
2053                                                             LK_SHARED |
2054                                                             LK_RETRY;
2055                                                         cn.cn_cred =
2056                                                             nd->nd_cred;
2057                                                         cn.cn_thread = p;
2058                                                 }
2059                                                 cn.cn_nameptr = dp->d_name;
2060                                                 cn.cn_namelen = nlen;
2061                                                 cn.cn_flags = ISLASTCN |
2062                                                     NOFOLLOW | LOCKLEAF |
2063                                                     MPSAFE;
2064                                                 if (nlen == 2 &&
2065                                                     dp->d_name[0] == '.' &&
2066                                                     dp->d_name[1] == '.')
2067                                                         cn.cn_flags |=
2068                                                             ISDOTDOT;
2069                                                 if (NFSVOPLOCK(vp, LK_SHARED)
2070                                                     != 0) {
2071                                                         nd->nd_repstat = EPERM;
2072                                                         break;
2073                                                 }
2074                                                 if ((vp->v_vflag & VV_ROOT) != 0
2075                                                     && (cn.cn_flags & ISDOTDOT)
2076                                                     != 0) {
2077                                                         vref(vp);
2078                                                         nvp = vp;
2079                                                         r = 0;
2080                                                 } else {
2081                                                         r = VOP_LOOKUP(vp, &nvp,
2082                                                             &cn);
2083                                                         if (vp != nvp)
2084                                                                 NFSVOPUNLOCK(vp,
2085                                                                     0);
2086                                                 }
2087                                         }
2088
2089                                         /*
2090                                          * For NFSv4, check to see if nvp is
2091                                          * a mount point and get the mount
2092                                          * point vnode, as required.
2093                                          */
2094                                         if (r == 0 &&
2095                                             nfsrv_enable_crossmntpt != 0 &&
2096                                             (nd->nd_flag & ND_NFSV4) != 0 &&
2097                                             nvp->v_type == VDIR &&
2098                                             nvp->v_mountedhere != NULL) {
2099                                                 new_mp = nvp->v_mountedhere;
2100                                                 r = vfs_busy(new_mp, 0);
2101                                                 vput(nvp);
2102                                                 nvp = NULL;
2103                                                 if (r == 0) {
2104                                                         r = VFS_ROOT(new_mp,
2105                                                             LK_SHARED, &nvp);
2106                                                         needs_unbusy = 1;
2107                                                         if (r == 0)
2108                                                                 at_root = 1;
2109                                                 }
2110                                         }
2111                                 }
2112                                 if (!r) {
2113                                     if (refp == NULL &&
2114                                         ((nd->nd_flag & ND_NFSV3) ||
2115                                          NFSNONZERO_ATTRBIT(&attrbits))) {
2116                                         r = nfsvno_getfh(nvp, &nfh, p);
2117                                         if (!r)
2118                                             r = nfsvno_getattr(nvp, nvap,
2119                                                 nd->nd_cred, p, 1);
2120                                     }
2121                                 } else {
2122                                     nvp = NULL;
2123                                 }
2124                                 if (r) {
2125                                         if (!NFSISSET_ATTRBIT(&attrbits,
2126                                             NFSATTRBIT_RDATTRERROR)) {
2127                                                 if (nvp != NULL)
2128                                                         vput(nvp);
2129                                                 if (needs_unbusy != 0)
2130                                                         vfs_unbusy(new_mp);
2131                                                 nd->nd_repstat = r;
2132                                                 break;
2133                                         }
2134                                 }
2135                         }
2136
2137                         /*
2138                          * Build the directory record xdr
2139                          */
2140                         if (nd->nd_flag & ND_NFSV3) {
2141                                 NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2142                                 *tl++ = newnfs_true;
2143                                 *tl++ = 0;
2144                                 *tl = txdr_unsigned(dp->d_fileno);
2145                                 dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2146                                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2147                                 *tl++ = 0;
2148                                 *tl = txdr_unsigned(*cookiep);
2149                                 nfsrv_postopattr(nd, 0, nvap);
2150                                 dirlen += nfsm_fhtom(nd,(u_int8_t *)&nfh,0,1);
2151                                 dirlen += (5*NFSX_UNSIGNED+NFSX_V3POSTOPATTR);
2152                                 if (nvp != NULL)
2153                                         vput(nvp);
2154                         } else {
2155                                 NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2156                                 *tl++ = newnfs_true;
2157                                 *tl++ = 0;
2158                                 *tl = txdr_unsigned(*cookiep);
2159                                 dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2160                                 if (nvp != NULL) {
2161                                         supports_nfsv4acls =
2162                                             nfs_supportsnfsv4acls(nvp);
2163                                         NFSVOPUNLOCK(nvp, 0);
2164                                 } else
2165                                         supports_nfsv4acls = 0;
2166                                 if (refp != NULL) {
2167                                         dirlen += nfsrv_putreferralattr(nd,
2168                                             &savbits, refp, 0,
2169                                             &nd->nd_repstat);
2170                                         if (nd->nd_repstat) {
2171                                                 if (nvp != NULL)
2172                                                         vrele(nvp);
2173                                                 if (needs_unbusy != 0)
2174                                                         vfs_unbusy(new_mp);
2175                                                 break;
2176                                         }
2177                                 } else if (r) {
2178                                         dirlen += nfsvno_fillattr(nd, new_mp,
2179                                             nvp, nvap, &nfh, r, &rderrbits,
2180                                             nd->nd_cred, p, isdgram, 0,
2181                                             supports_nfsv4acls, at_root,
2182                                             mounted_on_fileno);
2183                                 } else {
2184                                         dirlen += nfsvno_fillattr(nd, new_mp,
2185                                             nvp, nvap, &nfh, r, &attrbits,
2186                                             nd->nd_cred, p, isdgram, 0,
2187                                             supports_nfsv4acls, at_root,
2188                                             mounted_on_fileno);
2189                                 }
2190                                 if (nvp != NULL)
2191                                         vrele(nvp);
2192                                 dirlen += (3 * NFSX_UNSIGNED);
2193                         }
2194                         if (needs_unbusy != 0)
2195                                 vfs_unbusy(new_mp);
2196                         if (dirlen <= cnt)
2197                                 entrycnt++;
2198                 }
2199                 cpos += dp->d_reclen;
2200                 dp = (struct dirent *)cpos;
2201                 cookiep++;
2202                 ncookies--;
2203         }
2204         vrele(vp);
2205         vfs_unbusy(mp);
2206
2207         /*
2208          * If dirlen > cnt, we must strip off the last entry. If that
2209          * results in an empty reply, report NFSERR_TOOSMALL.
2210          */
2211         if (dirlen > cnt || nd->nd_repstat) {
2212                 if (!nd->nd_repstat && entrycnt == 0)
2213                         nd->nd_repstat = NFSERR_TOOSMALL;
2214                 if (nd->nd_repstat)
2215                         newnfs_trimtrailing(nd, mb0, bpos0);
2216                 else
2217                         newnfs_trimtrailing(nd, mb1, bpos1);
2218                 eofflag = 0;
2219         } else if (cpos < cend)
2220                 eofflag = 0;
2221         if (!nd->nd_repstat) {
2222                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2223                 *tl++ = newnfs_false;
2224                 if (eofflag)
2225                         *tl = newnfs_true;
2226                 else
2227                         *tl = newnfs_false;
2228         }
2229         FREE((caddr_t)cookies, M_TEMP);
2230         FREE((caddr_t)rbuf, M_TEMP);
2231
2232 out:
2233         NFSEXITCODE2(0, nd);
2234         return (0);
2235 nfsmout:
2236         vput(vp);
2237         NFSEXITCODE2(error, nd);
2238         return (error);
2239 }
2240
2241 /*
2242  * Get the settable attributes out of the mbuf list.
2243  * (Return 0 or EBADRPC)
2244  */
2245 int
2246 nfsrv_sattr(struct nfsrv_descript *nd, struct nfsvattr *nvap,
2247     nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2248 {
2249         u_int32_t *tl;
2250         struct nfsv2_sattr *sp;
2251         struct timeval curtime;
2252         int error = 0, toclient = 0;
2253
2254         switch (nd->nd_flag & (ND_NFSV2 | ND_NFSV3 | ND_NFSV4)) {
2255         case ND_NFSV2:
2256                 NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
2257                 /*
2258                  * Some old clients didn't fill in the high order 16bits.
2259                  * --> check the low order 2 bytes for 0xffff
2260                  */
2261                 if ((fxdr_unsigned(int, sp->sa_mode) & 0xffff) != 0xffff)
2262                         nvap->na_mode = nfstov_mode(sp->sa_mode);
2263                 if (sp->sa_uid != newnfs_xdrneg1)
2264                         nvap->na_uid = fxdr_unsigned(uid_t, sp->sa_uid);
2265                 if (sp->sa_gid != newnfs_xdrneg1)
2266                         nvap->na_gid = fxdr_unsigned(gid_t, sp->sa_gid);
2267                 if (sp->sa_size != newnfs_xdrneg1)
2268                         nvap->na_size = fxdr_unsigned(u_quad_t, sp->sa_size);
2269                 if (sp->sa_atime.nfsv2_sec != newnfs_xdrneg1) {
2270 #ifdef notyet
2271                         fxdr_nfsv2time(&sp->sa_atime, &nvap->na_atime);
2272 #else
2273                         nvap->na_atime.tv_sec =
2274                                 fxdr_unsigned(u_int32_t,sp->sa_atime.nfsv2_sec);
2275                         nvap->na_atime.tv_nsec = 0;
2276 #endif
2277                 }
2278                 if (sp->sa_mtime.nfsv2_sec != newnfs_xdrneg1)
2279                         fxdr_nfsv2time(&sp->sa_mtime, &nvap->na_mtime);
2280                 break;
2281         case ND_NFSV3:
2282                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2283                 if (*tl == newnfs_true) {
2284                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2285                         nvap->na_mode = nfstov_mode(*tl);
2286                 }
2287                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2288                 if (*tl == newnfs_true) {
2289                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2290                         nvap->na_uid = fxdr_unsigned(uid_t, *tl);
2291                 }
2292                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2293                 if (*tl == newnfs_true) {
2294                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2295                         nvap->na_gid = fxdr_unsigned(gid_t, *tl);
2296                 }
2297                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2298                 if (*tl == newnfs_true) {
2299                         NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2300                         nvap->na_size = fxdr_hyper(tl);
2301                 }
2302                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2303                 switch (fxdr_unsigned(int, *tl)) {
2304                 case NFSV3SATTRTIME_TOCLIENT:
2305                         NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2306                         fxdr_nfsv3time(tl, &nvap->na_atime);
2307                         toclient = 1;
2308                         break;
2309                 case NFSV3SATTRTIME_TOSERVER:
2310                         NFSGETTIME(&curtime);
2311                         nvap->na_atime.tv_sec = curtime.tv_sec;
2312                         nvap->na_atime.tv_nsec = curtime.tv_usec * 1000;
2313                         nvap->na_vaflags |= VA_UTIMES_NULL;
2314                         break;
2315                 };
2316                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2317                 switch (fxdr_unsigned(int, *tl)) {
2318                 case NFSV3SATTRTIME_TOCLIENT:
2319                         NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2320                         fxdr_nfsv3time(tl, &nvap->na_mtime);
2321                         nvap->na_vaflags &= ~VA_UTIMES_NULL;
2322                         break;
2323                 case NFSV3SATTRTIME_TOSERVER:
2324                         NFSGETTIME(&curtime);
2325                         nvap->na_mtime.tv_sec = curtime.tv_sec;
2326                         nvap->na_mtime.tv_nsec = curtime.tv_usec * 1000;
2327                         if (!toclient)
2328                                 nvap->na_vaflags |= VA_UTIMES_NULL;
2329                         break;
2330                 };
2331                 break;
2332         case ND_NFSV4:
2333                 error = nfsv4_sattr(nd, nvap, attrbitp, aclp, p);
2334         };
2335 nfsmout:
2336         NFSEXITCODE2(error, nd);
2337         return (error);
2338 }
2339
2340 /*
2341  * Handle the setable attributes for V4.
2342  * Returns NFSERR_BADXDR if it can't be parsed, 0 otherwise.
2343  */
2344 int
2345 nfsv4_sattr(struct nfsrv_descript *nd, struct nfsvattr *nvap,
2346     nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2347 {
2348         u_int32_t *tl;
2349         int attrsum = 0;
2350         int i, j;
2351         int error, attrsize, bitpos, aclsize, aceerr, retnotsup = 0;
2352         int toclient = 0;
2353         u_char *cp, namestr[NFSV4_SMALLSTR + 1];
2354         uid_t uid;
2355         gid_t gid;
2356         struct timeval curtime;
2357
2358         error = nfsrv_getattrbits(nd, attrbitp, NULL, &retnotsup);
2359         if (error)
2360                 goto nfsmout;
2361         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2362         attrsize = fxdr_unsigned(int, *tl);
2363
2364         /*
2365          * Loop around getting the setable attributes. If an unsupported
2366          * one is found, set nd_repstat == NFSERR_ATTRNOTSUPP and return.
2367          */
2368         if (retnotsup) {
2369                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2370                 bitpos = NFSATTRBIT_MAX;
2371         } else {
2372                 bitpos = 0;
2373         }
2374         for (; bitpos < NFSATTRBIT_MAX; bitpos++) {
2375             if (attrsum > attrsize) {
2376                 error = NFSERR_BADXDR;
2377                 goto nfsmout;
2378             }
2379             if (NFSISSET_ATTRBIT(attrbitp, bitpos))
2380                 switch (bitpos) {
2381                 case NFSATTRBIT_SIZE:
2382                         NFSM_DISSECT(tl, u_int32_t *, NFSX_HYPER);
2383                         nvap->na_size = fxdr_hyper(tl);
2384                         attrsum += NFSX_HYPER;
2385                         break;
2386                 case NFSATTRBIT_ACL:
2387                         error = nfsrv_dissectacl(nd, aclp, &aceerr, &aclsize,
2388                             p);
2389                         if (error)
2390                                 goto nfsmout;
2391                         if (aceerr && !nd->nd_repstat)
2392                                 nd->nd_repstat = aceerr;
2393                         attrsum += aclsize;
2394                         break;
2395                 case NFSATTRBIT_ARCHIVE:
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_HIDDEN:
2402                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2403                         if (!nd->nd_repstat)
2404                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2405                         attrsum += NFSX_UNSIGNED;
2406                         break;
2407                 case NFSATTRBIT_MIMETYPE:
2408                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2409                         i = fxdr_unsigned(int, *tl);
2410                         error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
2411                         if (error)
2412                                 goto nfsmout;
2413                         if (!nd->nd_repstat)
2414                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2415                         attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(i));
2416                         break;
2417                 case NFSATTRBIT_MODE:
2418                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2419                         nvap->na_mode = nfstov_mode(*tl);
2420                         attrsum += NFSX_UNSIGNED;
2421                         break;
2422                 case NFSATTRBIT_OWNER:
2423                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2424                         j = fxdr_unsigned(int, *tl);
2425                         if (j < 0) {
2426                                 error = NFSERR_BADXDR;
2427                                 goto nfsmout;
2428                         }
2429                         if (j > NFSV4_SMALLSTR)
2430                                 cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2431                         else
2432                                 cp = namestr;
2433                         error = nfsrv_mtostr(nd, cp, j);
2434                         if (error) {
2435                                 if (j > NFSV4_SMALLSTR)
2436                                         free(cp, M_NFSSTRING);
2437                                 goto nfsmout;
2438                         }
2439                         if (!nd->nd_repstat) {
2440                                 nd->nd_repstat = nfsv4_strtouid(nd, cp, j, &uid,
2441                                     p);
2442                                 if (!nd->nd_repstat)
2443                                         nvap->na_uid = uid;
2444                         }
2445                         if (j > NFSV4_SMALLSTR)
2446                                 free(cp, M_NFSSTRING);
2447                         attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2448                         break;
2449                 case NFSATTRBIT_OWNERGROUP:
2450                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2451                         j = fxdr_unsigned(int, *tl);
2452                         if (j < 0) {
2453                                 error = NFSERR_BADXDR;
2454                                 goto nfsmout;
2455                         }
2456                         if (j > NFSV4_SMALLSTR)
2457                                 cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2458                         else
2459                                 cp = namestr;
2460                         error = nfsrv_mtostr(nd, cp, j);
2461                         if (error) {
2462                                 if (j > NFSV4_SMALLSTR)
2463                                         free(cp, M_NFSSTRING);
2464                                 goto nfsmout;
2465                         }
2466                         if (!nd->nd_repstat) {
2467                                 nd->nd_repstat = nfsv4_strtogid(nd, cp, j, &gid,
2468                                     p);
2469                                 if (!nd->nd_repstat)
2470                                         nvap->na_gid = gid;
2471                         }
2472                         if (j > NFSV4_SMALLSTR)
2473                                 free(cp, M_NFSSTRING);
2474                         attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2475                         break;
2476                 case NFSATTRBIT_SYSTEM:
2477                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2478                         if (!nd->nd_repstat)
2479                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2480                         attrsum += NFSX_UNSIGNED;
2481                         break;
2482                 case NFSATTRBIT_TIMEACCESSSET:
2483                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2484                         attrsum += NFSX_UNSIGNED;
2485                         if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2486                             NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2487                             fxdr_nfsv4time(tl, &nvap->na_atime);
2488                             toclient = 1;
2489                             attrsum += NFSX_V4TIME;
2490                         } else {
2491                             NFSGETTIME(&curtime);
2492                             nvap->na_atime.tv_sec = curtime.tv_sec;
2493                             nvap->na_atime.tv_nsec = curtime.tv_usec * 1000;
2494                             nvap->na_vaflags |= VA_UTIMES_NULL;
2495                         }
2496                         break;
2497                 case NFSATTRBIT_TIMEBACKUP:
2498                         NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2499                         if (!nd->nd_repstat)
2500                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2501                         attrsum += NFSX_V4TIME;
2502                         break;
2503                 case NFSATTRBIT_TIMECREATE:
2504                         NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2505                         if (!nd->nd_repstat)
2506                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2507                         attrsum += NFSX_V4TIME;
2508                         break;
2509                 case NFSATTRBIT_TIMEMODIFYSET:
2510                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2511                         attrsum += NFSX_UNSIGNED;
2512                         if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2513                             NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2514                             fxdr_nfsv4time(tl, &nvap->na_mtime);
2515                             nvap->na_vaflags &= ~VA_UTIMES_NULL;
2516                             attrsum += NFSX_V4TIME;
2517                         } else {
2518                             NFSGETTIME(&curtime);
2519                             nvap->na_mtime.tv_sec = curtime.tv_sec;
2520                             nvap->na_mtime.tv_nsec = curtime.tv_usec * 1000;
2521                             if (!toclient)
2522                                 nvap->na_vaflags |= VA_UTIMES_NULL;
2523                         }
2524                         break;
2525                 default:
2526                         nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2527                         /*
2528                          * set bitpos so we drop out of the loop.
2529                          */
2530                         bitpos = NFSATTRBIT_MAX;
2531                         break;
2532                 };
2533         }
2534
2535         /*
2536          * some clients pad the attrlist, so we need to skip over the
2537          * padding.
2538          */
2539         if (attrsum > attrsize) {
2540                 error = NFSERR_BADXDR;
2541         } else {
2542                 attrsize = NFSM_RNDUP(attrsize);
2543                 if (attrsum < attrsize)
2544                         error = nfsm_advance(nd, attrsize - attrsum, -1);
2545         }
2546 nfsmout:
2547         NFSEXITCODE2(error, nd);
2548         return (error);
2549 }
2550
2551 /*
2552  * Check/setup export credentials.
2553  */
2554 int
2555 nfsd_excred(struct nfsrv_descript *nd, struct nfsexstuff *exp,
2556     struct ucred *credanon)
2557 {
2558         int error = 0;
2559
2560         /*
2561          * Check/setup credentials.
2562          */
2563         if (nd->nd_flag & ND_GSS)
2564                 exp->nes_exflag &= ~MNT_EXPORTANON;
2565
2566         /*
2567          * Check to see if the operation is allowed for this security flavor.
2568          * RFC2623 suggests that the NFSv3 Fsinfo RPC be allowed to
2569          * AUTH_NONE or AUTH_SYS for file systems requiring RPCSEC_GSS.
2570          * Also, allow Secinfo, so that it can acquire the correct flavor(s).
2571          */
2572         if (nfsvno_testexp(nd, exp) &&
2573             nd->nd_procnum != NFSV4OP_SECINFO &&
2574             nd->nd_procnum != NFSPROC_FSINFO) {
2575                 if (nd->nd_flag & ND_NFSV4)
2576                         error = NFSERR_WRONGSEC;
2577                 else
2578                         error = (NFSERR_AUTHERR | AUTH_TOOWEAK);
2579                 goto out;
2580         }
2581
2582         /*
2583          * Check to see if the file system is exported V4 only.
2584          */
2585         if (NFSVNO_EXV4ONLY(exp) && !(nd->nd_flag & ND_NFSV4)) {
2586                 error = NFSERR_PROGNOTV4;
2587                 goto out;
2588         }
2589
2590         /*
2591          * Now, map the user credentials.
2592          * (Note that ND_AUTHNONE will only be set for an NFSv3
2593          *  Fsinfo RPC. If set for anything else, this code might need
2594          *  to change.)
2595          */
2596         if (NFSVNO_EXPORTED(exp) &&
2597             ((!(nd->nd_flag & ND_GSS) && nd->nd_cred->cr_uid == 0) ||
2598              NFSVNO_EXPORTANON(exp) ||
2599              (nd->nd_flag & ND_AUTHNONE))) {
2600                 nd->nd_cred->cr_uid = credanon->cr_uid;
2601                 nd->nd_cred->cr_gid = credanon->cr_gid;
2602                 crsetgroups(nd->nd_cred, credanon->cr_ngroups,
2603                     credanon->cr_groups);
2604         }
2605
2606 out:
2607         NFSEXITCODE2(error, nd);
2608         return (error);
2609 }
2610
2611 /*
2612  * Check exports.
2613  */
2614 int
2615 nfsvno_checkexp(struct mount *mp, struct sockaddr *nam, struct nfsexstuff *exp,
2616     struct ucred **credp)
2617 {
2618         int i, error, *secflavors;
2619
2620         error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
2621             &exp->nes_numsecflavor, &secflavors);
2622         if (error) {
2623                 if (nfs_rootfhset) {
2624                         exp->nes_exflag = 0;
2625                         exp->nes_numsecflavor = 0;
2626                         error = 0;
2627                 }
2628         } else {
2629                 /* Copy the security flavors. */
2630                 for (i = 0; i < exp->nes_numsecflavor; i++)
2631                         exp->nes_secflavors[i] = secflavors[i];
2632         }
2633         NFSEXITCODE(error);
2634         return (error);
2635 }
2636
2637 /*
2638  * Get a vnode for a file handle and export stuff.
2639  */
2640 int
2641 nfsvno_fhtovp(struct mount *mp, fhandle_t *fhp, struct sockaddr *nam,
2642     int lktype, struct vnode **vpp, struct nfsexstuff *exp,
2643     struct ucred **credp)
2644 {
2645         int i, error, *secflavors;
2646
2647         *credp = NULL;
2648         exp->nes_numsecflavor = 0;
2649         if (VFS_NEEDSGIANT(mp))
2650                 error = ESTALE;
2651         else
2652                 error = VFS_FHTOVP(mp, &fhp->fh_fid, lktype, vpp);
2653         if (error != 0)
2654                 /* Make sure the server replies ESTALE to the client. */
2655                 error = ESTALE;
2656         if (nam && !error) {
2657                 error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
2658                     &exp->nes_numsecflavor, &secflavors);
2659                 if (error) {
2660                         if (nfs_rootfhset) {
2661                                 exp->nes_exflag = 0;
2662                                 exp->nes_numsecflavor = 0;
2663                                 error = 0;
2664                         } else {
2665                                 vput(*vpp);
2666                         }
2667                 } else {
2668                         /* Copy the security flavors. */
2669                         for (i = 0; i < exp->nes_numsecflavor; i++)
2670                                 exp->nes_secflavors[i] = secflavors[i];
2671                 }
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         TAILQ_INIT(&nfsv4root_mnt.mnt_activevnodelist);
2916         nfsv4root_mnt.mnt_export = NULL;
2917         TAILQ_INIT(&nfsv4root_opt);
2918         TAILQ_INIT(&nfsv4root_newopt);
2919         nfsv4root_mnt.mnt_opt = &nfsv4root_opt;
2920         nfsv4root_mnt.mnt_optnew = &nfsv4root_newopt;
2921         nfsv4root_mnt.mnt_nvnodelistsize = 0;
2922         nfsv4root_mnt.mnt_activevnodelistsize = 0;
2923 }
2924
2925 /*
2926  * Get a vnode for a file handle, without checking exports, etc.
2927  */
2928 struct vnode *
2929 nfsvno_getvp(fhandle_t *fhp)
2930 {
2931         struct mount *mp;
2932         struct vnode *vp;
2933         int error;
2934
2935         mp = vfs_busyfs(&fhp->fh_fsid);
2936         if (mp == NULL)
2937                 return (NULL);
2938         error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, &vp);
2939         vfs_unbusy(mp);
2940         if (error)
2941                 return (NULL);
2942         return (vp);
2943 }
2944
2945 /*
2946  * Do a local VOP_ADVLOCK().
2947  */
2948 int
2949 nfsvno_advlock(struct vnode *vp, int ftype, u_int64_t first,
2950     u_int64_t end, struct thread *td)
2951 {
2952         int error = 0;
2953         struct flock fl;
2954         u_int64_t tlen;
2955
2956         if (nfsrv_dolocallocks == 0)
2957                 goto out;
2958
2959         /* Check for VI_DOOMED here, so that VOP_ADVLOCK() isn't performed. */
2960         if ((vp->v_iflag & VI_DOOMED) != 0) {
2961                 error = EPERM;
2962                 goto out;
2963         }
2964
2965         fl.l_whence = SEEK_SET;
2966         fl.l_type = ftype;
2967         fl.l_start = (off_t)first;
2968         if (end == NFS64BITSSET) {
2969                 fl.l_len = 0;
2970         } else {
2971                 tlen = end - first;
2972                 fl.l_len = (off_t)tlen;
2973         }
2974         /*
2975          * For FreeBSD8, the l_pid and l_sysid must be set to the same
2976          * values for all calls, so that all locks will be held by the
2977          * nfsd server. (The nfsd server handles conflicts between the
2978          * various clients.)
2979          * Since an NFSv4 lockowner is a ClientID plus an array of up to 1024
2980          * bytes, so it can't be put in l_sysid.
2981          */
2982         if (nfsv4_sysid == 0)
2983                 nfsv4_sysid = nlm_acquire_next_sysid();
2984         fl.l_pid = (pid_t)0;
2985         fl.l_sysid = (int)nfsv4_sysid;
2986
2987         NFSVOPUNLOCK(vp, 0);
2988         if (ftype == F_UNLCK)
2989                 error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_UNLCK, &fl,
2990                     (F_POSIX | F_REMOTE));
2991         else
2992                 error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_SETLK, &fl,
2993                     (F_POSIX | F_REMOTE));
2994         NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
2995
2996 out:
2997         NFSEXITCODE(error);
2998         return (error);
2999 }
3000
3001 /*
3002  * Check the nfsv4 root exports.
3003  */
3004 int
3005 nfsvno_v4rootexport(struct nfsrv_descript *nd)
3006 {
3007         struct ucred *credanon;
3008         int exflags, error = 0, numsecflavor, *secflavors, i;
3009
3010         error = vfs_stdcheckexp(&nfsv4root_mnt, nd->nd_nam, &exflags,
3011             &credanon, &numsecflavor, &secflavors);
3012         if (error) {
3013                 error = NFSERR_PROGUNAVAIL;
3014                 goto out;
3015         }
3016         if (credanon != NULL)
3017                 crfree(credanon);
3018         for (i = 0; i < numsecflavor; i++) {
3019                 if (secflavors[i] == AUTH_SYS)
3020                         nd->nd_flag |= ND_EXAUTHSYS;
3021                 else if (secflavors[i] == RPCSEC_GSS_KRB5)
3022                         nd->nd_flag |= ND_EXGSS;
3023                 else if (secflavors[i] == RPCSEC_GSS_KRB5I)
3024                         nd->nd_flag |= ND_EXGSSINTEGRITY;
3025                 else if (secflavors[i] == RPCSEC_GSS_KRB5P)
3026                         nd->nd_flag |= ND_EXGSSPRIVACY;
3027         }
3028
3029 out:
3030         NFSEXITCODE(error);
3031         return (error);
3032 }
3033
3034 /*
3035  * Nfs server psuedo system call for the nfsd's
3036  */
3037 /*
3038  * MPSAFE
3039  */
3040 static int
3041 nfssvc_nfsd(struct thread *td, struct nfssvc_args *uap)
3042 {
3043         struct file *fp;
3044         struct nfsd_addsock_args sockarg;
3045         struct nfsd_nfsd_args nfsdarg;
3046         int error;
3047
3048         if (uap->flag & NFSSVC_NFSDADDSOCK) {
3049                 error = copyin(uap->argp, (caddr_t)&sockarg, sizeof (sockarg));
3050                 if (error)
3051                         goto out;
3052                 /*
3053                  * Since we don't know what rights might be required,
3054                  * pretend that we need them all. It is better to be too
3055                  * careful than too reckless.
3056                  */
3057                 if ((error = fget(td, sockarg.sock, CAP_SOCK_ALL, &fp)) != 0)
3058                         goto out;
3059                 if (fp->f_type != DTYPE_SOCKET) {
3060                         fdrop(fp, td);
3061                         error = EPERM;
3062                         goto out;
3063                 }
3064                 error = nfsrvd_addsock(fp);
3065                 fdrop(fp, td);
3066         } else if (uap->flag & NFSSVC_NFSDNFSD) {
3067                 if (uap->argp == NULL) {
3068                         error = EINVAL;
3069                         goto out;
3070                 }
3071                 error = copyin(uap->argp, (caddr_t)&nfsdarg,
3072                     sizeof (nfsdarg));
3073                 if (error)
3074                         goto out;
3075                 error = nfsrvd_nfsd(td, &nfsdarg);
3076         } else {
3077                 error = nfssvc_srvcall(td, uap, td->td_ucred);
3078         }
3079
3080 out:
3081         NFSEXITCODE(error);
3082         return (error);
3083 }
3084
3085 static int
3086 nfssvc_srvcall(struct thread *p, struct nfssvc_args *uap, struct ucred *cred)
3087 {
3088         struct nfsex_args export;
3089         struct file *fp = NULL;
3090         int stablefd, len;
3091         struct nfsd_clid adminrevoke;
3092         struct nfsd_dumplist dumplist;
3093         struct nfsd_dumpclients *dumpclients;
3094         struct nfsd_dumplocklist dumplocklist;
3095         struct nfsd_dumplocks *dumplocks;
3096         struct nameidata nd;
3097         vnode_t vp;
3098         int error = EINVAL;
3099         struct proc *procp;
3100
3101         if (uap->flag & NFSSVC_PUBLICFH) {
3102                 NFSBZERO((caddr_t)&nfs_pubfh.nfsrvfh_data,
3103                     sizeof (fhandle_t));
3104                 error = copyin(uap->argp,
3105                     &nfs_pubfh.nfsrvfh_data, sizeof (fhandle_t));
3106                 if (!error)
3107                         nfs_pubfhset = 1;
3108         } else if (uap->flag & NFSSVC_V4ROOTEXPORT) {
3109                 error = copyin(uap->argp,(caddr_t)&export,
3110                     sizeof (struct nfsex_args));
3111                 if (!error)
3112                         error = nfsrv_v4rootexport(&export, cred, p);
3113         } else if (uap->flag & NFSSVC_NOPUBLICFH) {
3114                 nfs_pubfhset = 0;
3115                 error = 0;
3116         } else if (uap->flag & NFSSVC_STABLERESTART) {
3117                 error = copyin(uap->argp, (caddr_t)&stablefd,
3118                     sizeof (int));
3119                 if (!error)
3120                         error = fp_getfvp(p, stablefd, &fp, &vp);
3121                 if (!error && (NFSFPFLAG(fp) & (FREAD | FWRITE)) != (FREAD | FWRITE))
3122                         error = EBADF;
3123                 if (!error && newnfs_numnfsd != 0)
3124                         error = EPERM;
3125                 if (!error) {
3126                         nfsrv_stablefirst.nsf_fp = fp;
3127                         nfsrv_setupstable(p);
3128                 }
3129         } else if (uap->flag & NFSSVC_ADMINREVOKE) {
3130                 error = copyin(uap->argp, (caddr_t)&adminrevoke,
3131                     sizeof (struct nfsd_clid));
3132                 if (!error)
3133                         error = nfsrv_adminrevoke(&adminrevoke, p);
3134         } else if (uap->flag & NFSSVC_DUMPCLIENTS) {
3135                 error = copyin(uap->argp, (caddr_t)&dumplist,
3136                     sizeof (struct nfsd_dumplist));
3137                 if (!error && (dumplist.ndl_size < 1 ||
3138                         dumplist.ndl_size > NFSRV_MAXDUMPLIST))
3139                         error = EPERM;
3140                 if (!error) {
3141                     len = sizeof (struct nfsd_dumpclients) * dumplist.ndl_size;
3142                     dumpclients = (struct nfsd_dumpclients *)malloc(len,
3143                         M_TEMP, M_WAITOK);
3144                     nfsrv_dumpclients(dumpclients, dumplist.ndl_size);
3145                     error = copyout(dumpclients,
3146                         CAST_USER_ADDR_T(dumplist.ndl_list), len);
3147                     free((caddr_t)dumpclients, M_TEMP);
3148                 }
3149         } else if (uap->flag & NFSSVC_DUMPLOCKS) {
3150                 error = copyin(uap->argp, (caddr_t)&dumplocklist,
3151                     sizeof (struct nfsd_dumplocklist));
3152                 if (!error && (dumplocklist.ndllck_size < 1 ||
3153                         dumplocklist.ndllck_size > NFSRV_MAXDUMPLIST))
3154                         error = EPERM;
3155                 if (!error)
3156                         error = nfsrv_lookupfilename(&nd,
3157                                 dumplocklist.ndllck_fname, p);
3158                 if (!error) {
3159                         len = sizeof (struct nfsd_dumplocks) *
3160                                 dumplocklist.ndllck_size;
3161                         dumplocks = (struct nfsd_dumplocks *)malloc(len,
3162                                 M_TEMP, M_WAITOK);
3163                         nfsrv_dumplocks(nd.ni_vp, dumplocks,
3164                             dumplocklist.ndllck_size, p);
3165                         vput(nd.ni_vp);
3166                         error = copyout(dumplocks,
3167                             CAST_USER_ADDR_T(dumplocklist.ndllck_list), len);
3168                         free((caddr_t)dumplocks, M_TEMP);
3169                 }
3170         } else if (uap->flag & NFSSVC_BACKUPSTABLE) {
3171                 procp = p->td_proc;
3172                 PROC_LOCK(procp);
3173                 nfsd_master_pid = procp->p_pid;
3174                 bcopy(procp->p_comm, nfsd_master_comm, MAXCOMLEN + 1);
3175                 nfsd_master_start = procp->p_stats->p_start;
3176                 nfsd_master_proc = procp;
3177                 PROC_UNLOCK(procp);
3178         }
3179
3180         NFSEXITCODE(error);
3181         return (error);
3182 }
3183
3184 /*
3185  * Check exports.
3186  * Returns 0 if ok, 1 otherwise.
3187  */
3188 int
3189 nfsvno_testexp(struct nfsrv_descript *nd, struct nfsexstuff *exp)
3190 {
3191         int i;
3192
3193         /*
3194          * This seems odd, but allow the case where the security flavor
3195          * list is empty. This happens when NFSv4 is traversing non-exported
3196          * file systems. Exported file systems should always have a non-empty
3197          * security flavor list.
3198          */
3199         if (exp->nes_numsecflavor == 0)
3200                 return (0);
3201
3202         for (i = 0; i < exp->nes_numsecflavor; i++) {
3203                 /*
3204                  * The tests for privacy and integrity must be first,
3205                  * since ND_GSS is set for everything but AUTH_SYS.
3206                  */
3207                 if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5P &&
3208                     (nd->nd_flag & ND_GSSPRIVACY))
3209                         return (0);
3210                 if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5I &&
3211                     (nd->nd_flag & ND_GSSINTEGRITY))
3212                         return (0);
3213                 if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5 &&
3214                     (nd->nd_flag & ND_GSS))
3215                         return (0);
3216                 if (exp->nes_secflavors[i] == AUTH_SYS &&
3217                     (nd->nd_flag & ND_GSS) == 0)
3218                         return (0);
3219         }
3220         return (1);
3221 }
3222
3223 /*
3224  * Calculate a hash value for the fid in a file handle.
3225  */
3226 uint32_t
3227 nfsrv_hashfh(fhandle_t *fhp)
3228 {
3229         uint32_t hashval;
3230
3231         hashval = hash32_buf(&fhp->fh_fid, sizeof(struct fid), 0);
3232         return (hashval);
3233 }
3234
3235 /*
3236  * Signal the userland master nfsd to backup the stable restart file.
3237  */
3238 void
3239 nfsrv_backupstable(void)
3240 {
3241         struct proc *procp;
3242
3243         if (nfsd_master_proc != NULL) {
3244                 procp = pfind(nfsd_master_pid);
3245                 /* Try to make sure it is the correct process. */
3246                 if (procp == nfsd_master_proc &&
3247                     procp->p_stats->p_start.tv_sec ==
3248                     nfsd_master_start.tv_sec &&
3249                     procp->p_stats->p_start.tv_usec ==
3250                     nfsd_master_start.tv_usec &&
3251                     strcmp(procp->p_comm, nfsd_master_comm) == 0)
3252                         kern_psignal(procp, SIGUSR2);
3253                 else
3254                         nfsd_master_proc = NULL;
3255
3256                 if (procp != NULL)
3257                         PROC_UNLOCK(procp);
3258         }
3259 }
3260
3261 extern int (*nfsd_call_nfsd)(struct thread *, struct nfssvc_args *);
3262
3263 /*
3264  * Called once to initialize data structures...
3265  */
3266 static int
3267 nfsd_modevent(module_t mod, int type, void *data)
3268 {
3269         int error = 0;
3270         static int loaded = 0;
3271
3272         switch (type) {
3273         case MOD_LOAD:
3274                 if (loaded)
3275                         goto out;
3276                 newnfs_portinit();
3277                 mtx_init(&nfs_cache_mutex, "nfs_cache_mutex", NULL, MTX_DEF);
3278                 mtx_init(&nfs_v4root_mutex, "nfs_v4root_mutex", NULL, MTX_DEF);
3279                 mtx_init(&nfsv4root_mnt.mnt_mtx, "struct mount mtx", NULL,
3280                     MTX_DEF);
3281                 lockinit(&nfsv4root_mnt.mnt_explock, PVFS, "explock", 0, 0);
3282                 nfsrvd_initcache();
3283                 nfsd_init();
3284                 NFSD_LOCK();
3285                 nfsrvd_init(0);
3286                 NFSD_UNLOCK();
3287                 nfsd_mntinit();
3288 #ifdef VV_DISABLEDELEG
3289                 vn_deleg_ops.vndeleg_recall = nfsd_recalldelegation;
3290                 vn_deleg_ops.vndeleg_disable = nfsd_disabledelegation;
3291 #endif
3292                 nfsd_call_servertimer = nfsrv_servertimer;
3293                 nfsd_call_nfsd = nfssvc_nfsd;
3294                 loaded = 1;
3295                 break;
3296
3297         case MOD_UNLOAD:
3298                 if (newnfs_numnfsd != 0) {
3299                         error = EBUSY;
3300                         break;
3301                 }
3302
3303 #ifdef VV_DISABLEDELEG
3304                 vn_deleg_ops.vndeleg_recall = NULL;
3305                 vn_deleg_ops.vndeleg_disable = NULL;
3306 #endif
3307                 nfsd_call_servertimer = NULL;
3308                 nfsd_call_nfsd = NULL;
3309
3310                 /* Clean out all NFSv4 state. */
3311                 nfsrv_throwawayallstate(curthread);
3312
3313                 /* Clean the NFS server reply cache */
3314                 nfsrvd_cleancache();
3315
3316                 /* Free up the krpc server pool. */
3317                 if (nfsrvd_pool != NULL)
3318                         svcpool_destroy(nfsrvd_pool);
3319
3320                 /* and get rid of the locks */
3321                 mtx_destroy(&nfs_cache_mutex);
3322                 mtx_destroy(&nfs_v4root_mutex);
3323                 mtx_destroy(&nfsv4root_mnt.mnt_mtx);
3324                 lockdestroy(&nfsv4root_mnt.mnt_explock);
3325                 loaded = 0;
3326                 break;
3327         default:
3328                 error = EOPNOTSUPP;
3329                 break;
3330         }
3331
3332 out:
3333         NFSEXITCODE(error);
3334         return (error);
3335 }
3336 static moduledata_t nfsd_mod = {
3337         "nfsd",
3338         nfsd_modevent,
3339         NULL,
3340 };
3341 DECLARE_MODULE(nfsd, nfsd_mod, SI_SUB_VFS, SI_ORDER_ANY);
3342
3343 /* So that loader and kldload(2) can find us, wherever we are.. */
3344 MODULE_VERSION(nfsd, 1);
3345 MODULE_DEPEND(nfsd, nfscommon, 1, 1, 1);
3346 MODULE_DEPEND(nfsd, nfslock, 1, 1, 1);
3347 MODULE_DEPEND(nfsd, nfslockd, 1, 1, 1);
3348 MODULE_DEPEND(nfsd, krpc, 1, 1, 1);
3349 MODULE_DEPEND(nfsd, nfssvc, 1, 1, 1);
3350