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