]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/fs/nfsserver/nfs_nfsdport.c
Add support for ext_pgs mbufs to nfsrv_adj().
[FreeBSD/FreeBSD.git] / sys / fs / nfsserver / nfs_nfsdport.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Rick Macklem at The University of Guelph.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  */
35
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38
39 #include <sys/capsicum.h>
40 #include <sys/extattr.h>
41
42 /*
43  * Functions that perform the vfs operations required by the routines in
44  * nfsd_serv.c. It is hoped that this change will make the server more
45  * portable.
46  */
47
48 #include <fs/nfs/nfsport.h>
49 #include <security/mac/mac_framework.h>
50 #include <sys/filio.h>
51 #include <sys/hash.h>
52 #include <sys/sysctl.h>
53 #include <nlm/nlm_prot.h>
54 #include <nlm/nlm.h>
55
56 FEATURE(nfsd, "NFSv4 server");
57
58 extern u_int32_t newnfs_true, newnfs_false, newnfs_xdrneg1;
59 extern int nfsrv_useacl;
60 extern int newnfs_numnfsd;
61 extern struct mount nfsv4root_mnt;
62 extern struct nfsrv_stablefirst nfsrv_stablefirst;
63 extern void (*nfsd_call_servertimer)(void);
64 extern SVCPOOL  *nfsrvd_pool;
65 extern struct nfsv4lock nfsd_suspend_lock;
66 extern struct nfsclienthashhead *nfsclienthash;
67 extern struct nfslockhashhead *nfslockhash;
68 extern struct nfssessionhash *nfssessionhash;
69 extern int nfsrv_sessionhashsize;
70 extern struct nfsstatsv1 nfsstatsv1;
71 extern struct nfslayouthash *nfslayouthash;
72 extern int nfsrv_layouthashsize;
73 extern struct mtx nfsrv_dslock_mtx;
74 extern int nfs_pnfsiothreads;
75 extern struct nfsdontlisthead nfsrv_dontlisthead;
76 extern volatile int nfsrv_dontlistlen;
77 extern volatile int nfsrv_devidcnt;
78 extern int nfsrv_maxpnfsmirror;
79 struct vfsoptlist nfsv4root_opt, nfsv4root_newopt;
80 NFSDLOCKMUTEX;
81 NFSSTATESPINLOCK;
82 struct nfsrchash_bucket nfsrchash_table[NFSRVCACHE_HASHSIZE];
83 struct nfsrchash_bucket nfsrcahash_table[NFSRVCACHE_HASHSIZE];
84 struct mtx nfsrc_udpmtx;
85 struct mtx nfs_v4root_mutex;
86 struct mtx nfsrv_dontlistlock_mtx;
87 struct mtx nfsrv_recalllock_mtx;
88 struct nfsrvfh nfs_rootfh, nfs_pubfh;
89 int nfs_pubfhset = 0, nfs_rootfhset = 0;
90 struct proc *nfsd_master_proc = NULL;
91 int nfsd_debuglevel = 0;
92 static pid_t nfsd_master_pid = (pid_t)-1;
93 static char nfsd_master_comm[MAXCOMLEN + 1];
94 static struct timeval nfsd_master_start;
95 static uint32_t nfsv4_sysid = 0;
96 static fhandle_t zerofh;
97
98 static int nfssvc_srvcall(struct thread *, struct nfssvc_args *,
99     struct ucred *);
100
101 int nfsrv_enable_crossmntpt = 1;
102 static int nfs_commit_blks;
103 static int nfs_commit_miss;
104 extern int nfsrv_issuedelegs;
105 extern int nfsrv_dolocallocks;
106 extern int nfsd_enable_stringtouid;
107 extern struct nfsdevicehead nfsrv_devidhead;
108
109 static int nfsrv_createiovec(int, struct mbuf **, struct mbuf **,
110     struct iovec **);
111 static int nfsrv_createiovecw(int, struct mbuf *, char *, struct iovec **,
112     int *);
113 static void nfsrv_pnfscreate(struct vnode *, struct vattr *, struct ucred *,
114     NFSPROC_T *);
115 static void nfsrv_pnfsremovesetup(struct vnode *, NFSPROC_T *, struct vnode **,
116     int *, char *, fhandle_t *);
117 static void nfsrv_pnfsremove(struct vnode **, int, char *, fhandle_t *,
118     NFSPROC_T *);
119 static int nfsrv_proxyds(struct vnode *, off_t, int, struct ucred *,
120     struct thread *, int, struct mbuf **, char *, struct mbuf **,
121     struct nfsvattr *, struct acl *, off_t *, int, bool *);
122 static int nfsrv_setextattr(struct vnode *, struct nfsvattr *, NFSPROC_T *);
123 static int nfsrv_readdsrpc(fhandle_t *, off_t, int, struct ucred *,
124     NFSPROC_T *, struct nfsmount *, struct mbuf **, struct mbuf **);
125 static int nfsrv_writedsrpc(fhandle_t *, off_t, int, struct ucred *,
126     NFSPROC_T *, struct vnode *, struct nfsmount **, int, struct mbuf **,
127     char *, int *);
128 static int nfsrv_allocatedsrpc(fhandle_t *, off_t, off_t, struct ucred *,
129     NFSPROC_T *, struct vnode *, struct nfsmount **, int, int *);
130 static int nfsrv_setacldsrpc(fhandle_t *, struct ucred *, NFSPROC_T *,
131     struct vnode *, struct nfsmount **, int, struct acl *, int *);
132 static int nfsrv_setattrdsrpc(fhandle_t *, struct ucred *, NFSPROC_T *,
133     struct vnode *, struct nfsmount **, int, struct nfsvattr *, int *);
134 static int nfsrv_getattrdsrpc(fhandle_t *, struct ucred *, NFSPROC_T *,
135     struct vnode *, struct nfsmount *, struct nfsvattr *);
136 static int nfsrv_seekdsrpc(fhandle_t *, off_t *, int, bool *, struct ucred *,
137     NFSPROC_T *, struct nfsmount *);
138 static int nfsrv_putfhname(fhandle_t *, char *);
139 static int nfsrv_pnfslookupds(struct vnode *, struct vnode *,
140     struct pnfsdsfile *, struct vnode **, NFSPROC_T *);
141 static void nfsrv_pnfssetfh(struct vnode *, struct pnfsdsfile *, char *, char *,
142     struct vnode *, NFSPROC_T *);
143 static int nfsrv_dsremove(struct vnode *, char *, struct ucred *, NFSPROC_T *);
144 static int nfsrv_dssetacl(struct vnode *, struct acl *, struct ucred *,
145     NFSPROC_T *);
146 static int nfsrv_pnfsstatfs(struct statfs *, struct mount *);
147
148 int nfs_pnfsio(task_fn_t *, void *);
149
150 SYSCTL_NODE(_vfs, OID_AUTO, nfsd, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
151     "NFS server");
152 SYSCTL_INT(_vfs_nfsd, OID_AUTO, mirrormnt, CTLFLAG_RW,
153     &nfsrv_enable_crossmntpt, 0, "Enable nfsd to cross mount points");
154 SYSCTL_INT(_vfs_nfsd, OID_AUTO, commit_blks, CTLFLAG_RW, &nfs_commit_blks,
155     0, "");
156 SYSCTL_INT(_vfs_nfsd, OID_AUTO, commit_miss, CTLFLAG_RW, &nfs_commit_miss,
157     0, "");
158 SYSCTL_INT(_vfs_nfsd, OID_AUTO, issue_delegations, CTLFLAG_RW,
159     &nfsrv_issuedelegs, 0, "Enable nfsd to issue delegations");
160 SYSCTL_INT(_vfs_nfsd, OID_AUTO, enable_locallocks, CTLFLAG_RW,
161     &nfsrv_dolocallocks, 0, "Enable nfsd to acquire local locks on files");
162 SYSCTL_INT(_vfs_nfsd, OID_AUTO, debuglevel, CTLFLAG_RW, &nfsd_debuglevel,
163     0, "Debug level for NFS server");
164 SYSCTL_INT(_vfs_nfsd, OID_AUTO, enable_stringtouid, CTLFLAG_RW,
165     &nfsd_enable_stringtouid, 0, "Enable nfsd to accept numeric owner_names");
166 static int nfsrv_pnfsgetdsattr = 1;
167 SYSCTL_INT(_vfs_nfsd, OID_AUTO, pnfsgetdsattr, CTLFLAG_RW,
168     &nfsrv_pnfsgetdsattr, 0, "When set getattr gets DS attributes via RPC");
169
170 /*
171  * nfsrv_dsdirsize can only be increased and only when the nfsd threads are
172  * not running.
173  * The dsN subdirectories for the increased values must have been created
174  * on all DS servers before this increase is done.
175  */
176 u_int   nfsrv_dsdirsize = 20;
177 static int
178 sysctl_dsdirsize(SYSCTL_HANDLER_ARGS)
179 {
180         int error, newdsdirsize;
181
182         newdsdirsize = nfsrv_dsdirsize;
183         error = sysctl_handle_int(oidp, &newdsdirsize, 0, req);
184         if (error != 0 || req->newptr == NULL)
185                 return (error);
186         if (newdsdirsize <= nfsrv_dsdirsize || newdsdirsize > 10000 ||
187             newnfs_numnfsd != 0)
188                 return (EINVAL);
189         nfsrv_dsdirsize = newdsdirsize;
190         return (0);
191 }
192 SYSCTL_PROC(_vfs_nfsd, OID_AUTO, dsdirsize,
193     CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(nfsrv_dsdirsize),
194     sysctl_dsdirsize, "IU", "Number of dsN subdirs on the DS servers");
195
196 #define MAX_REORDERED_RPC       16
197 #define NUM_HEURISTIC           1031
198 #define NHUSE_INIT              64
199 #define NHUSE_INC               16
200 #define NHUSE_MAX               2048
201
202 static struct nfsheur {
203         struct vnode *nh_vp;    /* vp to match (unreferenced pointer) */
204         off_t nh_nextoff;       /* next offset for sequential detection */
205         int nh_use;             /* use count for selection */
206         int nh_seqcount;        /* heuristic */
207 } nfsheur[NUM_HEURISTIC];
208
209
210 /*
211  * Heuristic to detect sequential operation.
212  */
213 static struct nfsheur *
214 nfsrv_sequential_heuristic(struct uio *uio, struct vnode *vp)
215 {
216         struct nfsheur *nh;
217         int hi, try;
218
219         /* Locate best candidate. */
220         try = 32;
221         hi = ((int)(vm_offset_t)vp / sizeof(struct vnode)) % NUM_HEURISTIC;
222         nh = &nfsheur[hi];
223         while (try--) {
224                 if (nfsheur[hi].nh_vp == vp) {
225                         nh = &nfsheur[hi];
226                         break;
227                 }
228                 if (nfsheur[hi].nh_use > 0)
229                         --nfsheur[hi].nh_use;
230                 hi = (hi + 1) % NUM_HEURISTIC;
231                 if (nfsheur[hi].nh_use < nh->nh_use)
232                         nh = &nfsheur[hi];
233         }
234
235         /* Initialize hint if this is a new file. */
236         if (nh->nh_vp != vp) {
237                 nh->nh_vp = vp;
238                 nh->nh_nextoff = uio->uio_offset;
239                 nh->nh_use = NHUSE_INIT;
240                 if (uio->uio_offset == 0)
241                         nh->nh_seqcount = 4;
242                 else
243                         nh->nh_seqcount = 1;
244         }
245
246         /* Calculate heuristic. */
247         if ((uio->uio_offset == 0 && nh->nh_seqcount > 0) ||
248             uio->uio_offset == nh->nh_nextoff) {
249                 /* See comments in vfs_vnops.c:sequential_heuristic(). */
250                 nh->nh_seqcount += howmany(uio->uio_resid, 16384);
251                 if (nh->nh_seqcount > IO_SEQMAX)
252                         nh->nh_seqcount = IO_SEQMAX;
253         } else if (qabs(uio->uio_offset - nh->nh_nextoff) <= MAX_REORDERED_RPC *
254             imax(vp->v_mount->mnt_stat.f_iosize, uio->uio_resid)) {
255                 /* Probably a reordered RPC, leave seqcount alone. */
256         } else if (nh->nh_seqcount > 1) {
257                 nh->nh_seqcount /= 2;
258         } else {
259                 nh->nh_seqcount = 0;
260         }
261         nh->nh_use += NHUSE_INC;
262         if (nh->nh_use > NHUSE_MAX)
263                 nh->nh_use = NHUSE_MAX;
264         return (nh);
265 }
266
267 /*
268  * Get attributes into nfsvattr structure.
269  */
270 int
271 nfsvno_getattr(struct vnode *vp, struct nfsvattr *nvap,
272     struct nfsrv_descript *nd, struct thread *p, int vpislocked,
273     nfsattrbit_t *attrbitp)
274 {
275         int error, gotattr, lockedit = 0;
276         struct nfsvattr na;
277
278         if (vpislocked == 0) {
279                 /*
280                  * When vpislocked == 0, the vnode is either exclusively
281                  * locked by this thread or not locked by this thread.
282                  * As such, shared lock it, if not exclusively locked.
283                  */
284                 if (NFSVOPISLOCKED(vp) != LK_EXCLUSIVE) {
285                         lockedit = 1;
286                         NFSVOPLOCK(vp, LK_SHARED | LK_RETRY);
287                 }
288         }
289
290         /*
291          * Acquire the Change, Size, TimeAccess, TimeModify and SpaceUsed
292          * attributes, as required.
293          * This needs to be done for regular files if:
294          * - non-NFSv4 RPCs or
295          * - when attrbitp == NULL or
296          * - an NFSv4 RPC with any of the above attributes in attrbitp.
297          * A return of 0 for nfsrv_proxyds() indicates that it has acquired
298          * these attributes.  nfsrv_proxyds() will return an error if the
299          * server is not a pNFS one.
300          */
301         gotattr = 0;
302         if (vp->v_type == VREG && nfsrv_devidcnt > 0 && (attrbitp == NULL ||
303             (nd->nd_flag & ND_NFSV4) == 0 ||
304             NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_CHANGE) ||
305             NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SIZE) ||
306             NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_TIMEACCESS) ||
307             NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_TIMEMODIFY) ||
308             NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SPACEUSED))) {
309                 error = nfsrv_proxyds(vp, 0, 0, nd->nd_cred, p,
310                     NFSPROC_GETATTR, NULL, NULL, NULL, &na, NULL, NULL, 0,
311                     NULL);
312                 if (error == 0)
313                         gotattr = 1;
314         }
315
316         error = VOP_GETATTR(vp, &nvap->na_vattr, nd->nd_cred);
317         if (lockedit != 0)
318                 NFSVOPUNLOCK(vp);
319
320         /*
321          * If we got the Change, Size and Modify Time from the DS,
322          * replace them.
323          */
324         if (gotattr != 0) {
325                 nvap->na_atime = na.na_atime;
326                 nvap->na_mtime = na.na_mtime;
327                 nvap->na_filerev = na.na_filerev;
328                 nvap->na_size = na.na_size;
329                 nvap->na_bytes = na.na_bytes;
330         }
331         NFSD_DEBUG(4, "nfsvno_getattr: gotattr=%d err=%d chg=%ju\n", gotattr,
332             error, (uintmax_t)na.na_filerev);
333
334         NFSEXITCODE(error);
335         return (error);
336 }
337
338 /*
339  * Get a file handle for a vnode.
340  */
341 int
342 nfsvno_getfh(struct vnode *vp, fhandle_t *fhp, struct thread *p)
343 {
344         int error;
345
346         NFSBZERO((caddr_t)fhp, sizeof(fhandle_t));
347         fhp->fh_fsid = vp->v_mount->mnt_stat.f_fsid;
348         error = VOP_VPTOFH(vp, &fhp->fh_fid);
349
350         NFSEXITCODE(error);
351         return (error);
352 }
353
354 /*
355  * Perform access checking for vnodes obtained from file handles that would
356  * refer to files already opened by a Unix client. You cannot just use
357  * vn_writechk() and VOP_ACCESSX() for two reasons.
358  * 1 - You must check for exported rdonly as well as MNT_RDONLY for the write
359  *     case.
360  * 2 - The owner is to be given access irrespective of mode bits for some
361  *     operations, so that processes that chmod after opening a file don't
362  *     break.
363  */
364 int
365 nfsvno_accchk(struct vnode *vp, accmode_t accmode, struct ucred *cred,
366     struct nfsexstuff *exp, struct thread *p, int override, int vpislocked,
367     u_int32_t *supportedtypep)
368 {
369         struct vattr vattr;
370         int error = 0, getret = 0;
371
372         if (vpislocked == 0) {
373                 if (NFSVOPLOCK(vp, LK_SHARED) != 0) {
374                         error = EPERM;
375                         goto out;
376                 }
377         }
378         if (accmode & VWRITE) {
379                 /* Just vn_writechk() changed to check rdonly */
380                 /*
381                  * Disallow write attempts on read-only file systems;
382                  * unless the file is a socket or a block or character
383                  * device resident on the file system.
384                  */
385                 if (NFSVNO_EXRDONLY(exp) ||
386                     (vp->v_mount->mnt_flag & MNT_RDONLY)) {
387                         switch (vp->v_type) {
388                         case VREG:
389                         case VDIR:
390                         case VLNK:
391                                 error = EROFS;
392                         default:
393                                 break;
394                         }
395                 }
396                 /*
397                  * If there's shared text associated with
398                  * the inode, try to free it up once.  If
399                  * we fail, we can't allow writing.
400                  */
401                 if (VOP_IS_TEXT(vp) && error == 0)
402                         error = ETXTBSY;
403         }
404         if (error != 0) {
405                 if (vpislocked == 0)
406                         NFSVOPUNLOCK(vp);
407                 goto out;
408         }
409
410         /*
411          * Should the override still be applied when ACLs are enabled?
412          */
413         error = VOP_ACCESSX(vp, accmode, cred, p);
414         if (error != 0 && (accmode & (VDELETE | VDELETE_CHILD))) {
415                 /*
416                  * Try again with VEXPLICIT_DENY, to see if the test for
417                  * deletion is supported.
418                  */
419                 error = VOP_ACCESSX(vp, accmode | VEXPLICIT_DENY, cred, p);
420                 if (error == 0) {
421                         if (vp->v_type == VDIR) {
422                                 accmode &= ~(VDELETE | VDELETE_CHILD);
423                                 accmode |= VWRITE;
424                                 error = VOP_ACCESSX(vp, accmode, cred, p);
425                         } else if (supportedtypep != NULL) {
426                                 *supportedtypep &= ~NFSACCESS_DELETE;
427                         }
428                 }
429         }
430
431         /*
432          * Allow certain operations for the owner (reads and writes
433          * on files that are already open).
434          */
435         if (override != NFSACCCHK_NOOVERRIDE &&
436             (error == EPERM || error == EACCES)) {
437                 if (cred->cr_uid == 0 && (override & NFSACCCHK_ALLOWROOT))
438                         error = 0;
439                 else if (override & NFSACCCHK_ALLOWOWNER) {
440                         getret = VOP_GETATTR(vp, &vattr, cred);
441                         if (getret == 0 && cred->cr_uid == vattr.va_uid)
442                                 error = 0;
443                 }
444         }
445         if (vpislocked == 0)
446                 NFSVOPUNLOCK(vp);
447
448 out:
449         NFSEXITCODE(error);
450         return (error);
451 }
452
453 /*
454  * Set attribute(s) vnop.
455  */
456 int
457 nfsvno_setattr(struct vnode *vp, struct nfsvattr *nvap, struct ucred *cred,
458     struct thread *p, struct nfsexstuff *exp)
459 {
460         u_quad_t savsize = 0;
461         int error, savedit;
462
463         /*
464          * If this is an exported file system and a pNFS service is running,
465          * don't VOP_SETATTR() of size for the MDS file system.
466          */
467         savedit = 0;
468         error = 0;
469         if (vp->v_type == VREG && (vp->v_mount->mnt_flag & MNT_EXPORTED) != 0 &&
470             nfsrv_devidcnt != 0 && nvap->na_vattr.va_size != VNOVAL &&
471             nvap->na_vattr.va_size > 0) {
472                 savsize = nvap->na_vattr.va_size;
473                 nvap->na_vattr.va_size = VNOVAL;
474                 if (nvap->na_vattr.va_uid != (uid_t)VNOVAL ||
475                     nvap->na_vattr.va_gid != (gid_t)VNOVAL ||
476                     nvap->na_vattr.va_mode != (mode_t)VNOVAL ||
477                     nvap->na_vattr.va_atime.tv_sec != VNOVAL ||
478                     nvap->na_vattr.va_mtime.tv_sec != VNOVAL)
479                         savedit = 1;
480                 else
481                         savedit = 2;
482         }
483         if (savedit != 2)
484                 error = VOP_SETATTR(vp, &nvap->na_vattr, cred);
485         if (savedit != 0)
486                 nvap->na_vattr.va_size = savsize;
487         if (error == 0 && (nvap->na_vattr.va_uid != (uid_t)VNOVAL ||
488             nvap->na_vattr.va_gid != (gid_t)VNOVAL ||
489             nvap->na_vattr.va_size != VNOVAL ||
490             nvap->na_vattr.va_mode != (mode_t)VNOVAL ||
491             nvap->na_vattr.va_atime.tv_sec != VNOVAL ||
492             nvap->na_vattr.va_mtime.tv_sec != VNOVAL)) {
493                 /* For a pNFS server, set the attributes on the DS file. */
494                 error = nfsrv_proxyds(vp, 0, 0, cred, p, NFSPROC_SETATTR,
495                     NULL, NULL, NULL, nvap, NULL, NULL, 0, NULL);
496                 if (error == ENOENT)
497                         error = 0;
498         }
499         NFSEXITCODE(error);
500         return (error);
501 }
502
503 /*
504  * Set up nameidata for a lookup() call and do it.
505  */
506 int
507 nfsvno_namei(struct nfsrv_descript *nd, struct nameidata *ndp,
508     struct vnode *dp, int islocked, struct nfsexstuff *exp, struct thread *p,
509     struct vnode **retdirp)
510 {
511         struct componentname *cnp = &ndp->ni_cnd;
512         int i;
513         struct iovec aiov;
514         struct uio auio;
515         int lockleaf = (cnp->cn_flags & LOCKLEAF) != 0, linklen;
516         int error = 0;
517         char *cp;
518
519         *retdirp = NULL;
520         cnp->cn_nameptr = cnp->cn_pnbuf;
521         ndp->ni_lcf = 0;
522         /*
523          * Extract and set starting directory.
524          */
525         if (dp->v_type != VDIR) {
526                 if (islocked)
527                         vput(dp);
528                 else
529                         vrele(dp);
530                 nfsvno_relpathbuf(ndp);
531                 error = ENOTDIR;
532                 goto out1;
533         }
534         if (islocked)
535                 NFSVOPUNLOCK(dp);
536         VREF(dp);
537         *retdirp = dp;
538         if (NFSVNO_EXRDONLY(exp))
539                 cnp->cn_flags |= RDONLY;
540         ndp->ni_segflg = UIO_SYSSPACE;
541
542         if (nd->nd_flag & ND_PUBLOOKUP) {
543                 ndp->ni_loopcnt = 0;
544                 if (cnp->cn_pnbuf[0] == '/') {
545                         vrele(dp);
546                         /*
547                          * Check for degenerate pathnames here, since lookup()
548                          * panics on them.
549                          */
550                         for (i = 1; i < ndp->ni_pathlen; i++)
551                                 if (cnp->cn_pnbuf[i] != '/')
552                                         break;
553                         if (i == ndp->ni_pathlen) {
554                                 error = NFSERR_ACCES;
555                                 goto out;
556                         }
557                         dp = rootvnode;
558                         VREF(dp);
559                 }
560         } else if ((nfsrv_enable_crossmntpt == 0 && NFSVNO_EXPORTED(exp)) ||
561             (nd->nd_flag & ND_NFSV4) == 0) {
562                 /*
563                  * Only cross mount points for NFSv4 when doing a
564                  * mount while traversing the file system above
565                  * the mount point, unless nfsrv_enable_crossmntpt is set.
566                  */
567                 cnp->cn_flags |= NOCROSSMOUNT;
568         }
569
570         /*
571          * Initialize for scan, set ni_startdir and bump ref on dp again
572          * because lookup() will dereference ni_startdir.
573          */
574
575         cnp->cn_thread = p;
576         ndp->ni_startdir = dp;
577         ndp->ni_rootdir = rootvnode;
578         ndp->ni_topdir = NULL;
579
580         if (!lockleaf)
581                 cnp->cn_flags |= LOCKLEAF;
582         for (;;) {
583                 cnp->cn_nameptr = cnp->cn_pnbuf;
584                 /*
585                  * Call lookup() to do the real work.  If an error occurs,
586                  * ndp->ni_vp and ni_dvp are left uninitialized or NULL and
587                  * we do not have to dereference anything before returning.
588                  * In either case ni_startdir will be dereferenced and NULLed
589                  * out.
590                  */
591                 error = lookup(ndp);
592                 if (error)
593                         break;
594
595                 /*
596                  * Check for encountering a symbolic link.  Trivial
597                  * termination occurs if no symlink encountered.
598                  */
599                 if ((cnp->cn_flags & ISSYMLINK) == 0) {
600                         if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0)
601                                 nfsvno_relpathbuf(ndp);
602                         if (ndp->ni_vp && !lockleaf)
603                                 NFSVOPUNLOCK(ndp->ni_vp);
604                         break;
605                 }
606
607                 /*
608                  * Validate symlink
609                  */
610                 if ((cnp->cn_flags & LOCKPARENT) && ndp->ni_pathlen == 1)
611                         NFSVOPUNLOCK(ndp->ni_dvp);
612                 if (!(nd->nd_flag & ND_PUBLOOKUP)) {
613                         error = EINVAL;
614                         goto badlink2;
615                 }
616
617                 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
618                         error = ELOOP;
619                         goto badlink2;
620                 }
621                 if (ndp->ni_pathlen > 1)
622                         cp = uma_zalloc(namei_zone, M_WAITOK);
623                 else
624                         cp = cnp->cn_pnbuf;
625                 aiov.iov_base = cp;
626                 aiov.iov_len = MAXPATHLEN;
627                 auio.uio_iov = &aiov;
628                 auio.uio_iovcnt = 1;
629                 auio.uio_offset = 0;
630                 auio.uio_rw = UIO_READ;
631                 auio.uio_segflg = UIO_SYSSPACE;
632                 auio.uio_td = NULL;
633                 auio.uio_resid = MAXPATHLEN;
634                 error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
635                 if (error) {
636                 badlink1:
637                         if (ndp->ni_pathlen > 1)
638                                 uma_zfree(namei_zone, cp);
639                 badlink2:
640                         vrele(ndp->ni_dvp);
641                         vput(ndp->ni_vp);
642                         break;
643                 }
644                 linklen = MAXPATHLEN - auio.uio_resid;
645                 if (linklen == 0) {
646                         error = ENOENT;
647                         goto badlink1;
648                 }
649                 if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
650                         error = ENAMETOOLONG;
651                         goto badlink1;
652                 }
653
654                 /*
655                  * Adjust or replace path
656                  */
657                 if (ndp->ni_pathlen > 1) {
658                         NFSBCOPY(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
659                         uma_zfree(namei_zone, cnp->cn_pnbuf);
660                         cnp->cn_pnbuf = cp;
661                 } else
662                         cnp->cn_pnbuf[linklen] = '\0';
663                 ndp->ni_pathlen += linklen;
664
665                 /*
666                  * Cleanup refs for next loop and check if root directory
667                  * should replace current directory.  Normally ni_dvp
668                  * becomes the new base directory and is cleaned up when
669                  * we loop.  Explicitly null pointers after invalidation
670                  * to clarify operation.
671                  */
672                 vput(ndp->ni_vp);
673                 ndp->ni_vp = NULL;
674
675                 if (cnp->cn_pnbuf[0] == '/') {
676                         vrele(ndp->ni_dvp);
677                         ndp->ni_dvp = ndp->ni_rootdir;
678                         VREF(ndp->ni_dvp);
679                 }
680                 ndp->ni_startdir = ndp->ni_dvp;
681                 ndp->ni_dvp = NULL;
682         }
683         if (!lockleaf)
684                 cnp->cn_flags &= ~LOCKLEAF;
685
686 out:
687         if (error) {
688                 nfsvno_relpathbuf(ndp);
689                 ndp->ni_vp = NULL;
690                 ndp->ni_dvp = NULL;
691                 ndp->ni_startdir = NULL;
692         } else if ((ndp->ni_cnd.cn_flags & (WANTPARENT|LOCKPARENT)) == 0) {
693                 ndp->ni_dvp = NULL;
694         }
695
696 out1:
697         NFSEXITCODE2(error, nd);
698         return (error);
699 }
700
701 /*
702  * Set up a pathname buffer and return a pointer to it and, optionally
703  * set a hash pointer.
704  */
705 void
706 nfsvno_setpathbuf(struct nameidata *ndp, char **bufpp, u_long **hashpp)
707 {
708         struct componentname *cnp = &ndp->ni_cnd;
709
710         cnp->cn_flags |= (NOMACCHECK | HASBUF);
711         cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
712         if (hashpp != NULL)
713                 *hashpp = NULL;
714         *bufpp = cnp->cn_pnbuf;
715 }
716
717 /*
718  * Release the above path buffer, if not released by nfsvno_namei().
719  */
720 void
721 nfsvno_relpathbuf(struct nameidata *ndp)
722 {
723
724         if ((ndp->ni_cnd.cn_flags & HASBUF) == 0)
725                 panic("nfsrelpath");
726         uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
727         ndp->ni_cnd.cn_flags &= ~HASBUF;
728 }
729
730 /*
731  * Readlink vnode op into an mbuf list.
732  */
733 int
734 nfsvno_readlink(struct vnode *vp, struct ucred *cred, struct thread *p,
735     struct mbuf **mpp, struct mbuf **mpendp, int *lenp)
736 {
737         struct iovec *iv;
738         struct uio io, *uiop = &io;
739         struct mbuf *mp, *mp3;
740         int len, tlen, error = 0;
741
742         len = NFS_MAXPATHLEN;
743         uiop->uio_iovcnt = nfsrv_createiovec(len, &mp3, &mp, &iv);
744         uiop->uio_iov = iv;
745         uiop->uio_offset = 0;
746         uiop->uio_resid = len;
747         uiop->uio_rw = UIO_READ;
748         uiop->uio_segflg = UIO_SYSSPACE;
749         uiop->uio_td = NULL;
750         error = VOP_READLINK(vp, uiop, cred);
751         free(iv, M_TEMP);
752         if (error) {
753                 m_freem(mp3);
754                 *lenp = 0;
755                 goto out;
756         }
757         if (uiop->uio_resid > 0) {
758                 len -= uiop->uio_resid;
759                 tlen = NFSM_RNDUP(len);
760                 if (tlen == 0) {
761                         m_freem(mp3);
762                         mp3 = mp = NULL;
763                 } else if (tlen != NFS_MAXPATHLEN || tlen != len)
764                         mp = nfsrv_adj(mp3, NFS_MAXPATHLEN - tlen,
765                             tlen - len);
766         }
767         *lenp = len;
768         *mpp = mp3;
769         *mpendp = mp;
770
771 out:
772         NFSEXITCODE(error);
773         return (error);
774 }
775
776 /*
777  * Create an mbuf chain and an associated iovec that can be used to Read
778  * or Getextattr of data.
779  * Upon success, return pointers to the first and last mbufs in the chain
780  * plus the malloc'd iovec and its iovlen.
781  */
782 static int
783 nfsrv_createiovec(int len, struct mbuf **mpp, struct mbuf **mpendp,
784     struct iovec **ivp)
785 {
786         struct mbuf *m, *m2 = NULL, *m3;
787         struct iovec *iv;
788         int i, left, siz;
789
790         left = len;
791         m3 = NULL;
792         /*
793          * Generate the mbuf list with the uio_iov ref. to it.
794          */
795         i = 0;
796         while (left > 0) {
797                 NFSMGET(m);
798                 MCLGET(m, M_WAITOK);
799                 m->m_len = 0;
800                 siz = min(M_TRAILINGSPACE(m), left);
801                 left -= siz;
802                 i++;
803                 if (m3)
804                         m2->m_next = m;
805                 else
806                         m3 = m;
807                 m2 = m;
808         }
809         *ivp = iv = malloc(i * sizeof (struct iovec), M_TEMP, M_WAITOK);
810         m = m3;
811         left = len;
812         i = 0;
813         while (left > 0) {
814                 if (m == NULL)
815                         panic("nfsvno_read iov");
816                 siz = min(M_TRAILINGSPACE(m), left);
817                 if (siz > 0) {
818                         iv->iov_base = mtod(m, caddr_t) + m->m_len;
819                         iv->iov_len = siz;
820                         m->m_len += siz;
821                         left -= siz;
822                         iv++;
823                         i++;
824                 }
825                 m = m->m_next;
826         }
827         *mpp = m3;
828         *mpendp = m2;
829         return (i);
830 }
831
832 /*
833  * Read vnode op call into mbuf list.
834  */
835 int
836 nfsvno_read(struct vnode *vp, off_t off, int cnt, struct ucred *cred,
837     struct thread *p, struct mbuf **mpp, struct mbuf **mpendp)
838 {
839         struct mbuf *m;
840         struct iovec *iv;
841         int error = 0, len, tlen, ioflag = 0;
842         struct mbuf *m3;
843         struct uio io, *uiop = &io;
844         struct nfsheur *nh;
845
846         /*
847          * Attempt to read from a DS file. A return of ENOENT implies
848          * there is no DS file to read.
849          */
850         error = nfsrv_proxyds(vp, off, cnt, cred, p, NFSPROC_READDS, mpp,
851             NULL, mpendp, NULL, NULL, NULL, 0, NULL);
852         if (error != ENOENT)
853                 return (error);
854
855         len = NFSM_RNDUP(cnt);
856         uiop->uio_iovcnt = nfsrv_createiovec(len, &m3, &m, &iv);
857         uiop->uio_iov = iv;
858         uiop->uio_offset = off;
859         uiop->uio_resid = len;
860         uiop->uio_rw = UIO_READ;
861         uiop->uio_segflg = UIO_SYSSPACE;
862         uiop->uio_td = NULL;
863         nh = nfsrv_sequential_heuristic(uiop, vp);
864         ioflag |= nh->nh_seqcount << IO_SEQSHIFT;
865         /* XXX KDM make this more systematic? */
866         nfsstatsv1.srvbytes[NFSV4OP_READ] += uiop->uio_resid;
867         error = VOP_READ(vp, uiop, IO_NODELOCKED | ioflag, cred);
868         free(iv, M_TEMP);
869         if (error) {
870                 m_freem(m3);
871                 *mpp = NULL;
872                 goto out;
873         }
874         nh->nh_nextoff = uiop->uio_offset;
875         tlen = len - uiop->uio_resid;
876         cnt = cnt < tlen ? cnt : tlen;
877         tlen = NFSM_RNDUP(cnt);
878         if (tlen == 0) {
879                 m_freem(m3);
880                 m3 = m = NULL;
881         } else if (len != tlen || tlen != cnt)
882                 m = nfsrv_adj(m3, len - tlen, tlen - cnt);
883         *mpp = m3;
884         *mpendp = m;
885
886 out:
887         NFSEXITCODE(error);
888         return (error);
889 }
890
891 /*
892  * Create the iovec for the mbuf chain passed in as an argument.
893  * The "cp" argument is where the data starts within the first mbuf in
894  * the chain. It returns the iovec and the iovcnt.
895  */
896 static int
897 nfsrv_createiovecw(int retlen, struct mbuf *m, char *cp, struct iovec **ivpp,
898     int *iovcntp)
899 {
900         struct mbuf *mp;
901         struct iovec *ivp;
902         int cnt, i, len;
903
904         /*
905          * Loop through the mbuf chain, counting how many mbufs are a
906          * part of this write operation, so the iovec size is known.
907          */
908         cnt = 0;
909         len = retlen;
910         mp = m;
911         i = mtod(mp, caddr_t) + mp->m_len - cp;
912         while (len > 0) {
913                 if (i > 0) {
914                         len -= i;
915                         cnt++;
916                 }
917                 mp = mp->m_next;
918                 if (!mp) {
919                         if (len > 0)
920                                 return (EBADRPC);
921                 } else
922                         i = mp->m_len;
923         }
924
925         /* Now, create the iovec. */
926         mp = m;
927         *ivpp = ivp = malloc(cnt * sizeof (struct iovec), M_TEMP,
928             M_WAITOK);
929         *iovcntp = cnt;
930         i = mtod(mp, caddr_t) + mp->m_len - cp;
931         len = retlen;
932         while (len > 0) {
933                 if (mp == NULL)
934                         panic("nfsvno_write");
935                 if (i > 0) {
936                         i = min(i, len);
937                         ivp->iov_base = cp;
938                         ivp->iov_len = i;
939                         ivp++;
940                         len -= i;
941                 }
942                 mp = mp->m_next;
943                 if (mp) {
944                         i = mp->m_len;
945                         cp = mtod(mp, caddr_t);
946                 }
947         }
948         return (0);
949 }
950
951 /*
952  * Write vnode op from an mbuf list.
953  */
954 int
955 nfsvno_write(struct vnode *vp, off_t off, int retlen, int *stable,
956     struct mbuf *mp, char *cp, struct ucred *cred, struct thread *p)
957 {
958         struct iovec *iv;
959         int cnt, ioflags, error;
960         struct uio io, *uiop = &io;
961         struct nfsheur *nh;
962
963         /*
964          * Attempt to write to a DS file. A return of ENOENT implies
965          * there is no DS file to write.
966          */
967         error = nfsrv_proxyds(vp, off, retlen, cred, p, NFSPROC_WRITEDS,
968             &mp, cp, NULL, NULL, NULL, NULL, 0, NULL);
969         if (error != ENOENT) {
970                 *stable = NFSWRITE_FILESYNC;
971                 return (error);
972         }
973
974
975         if (*stable == NFSWRITE_UNSTABLE)
976                 ioflags = IO_NODELOCKED;
977         else
978                 ioflags = (IO_SYNC | IO_NODELOCKED);
979         error = nfsrv_createiovecw(retlen, mp, cp, &iv, &cnt);
980         if (error != 0)
981                 return (error);
982         uiop->uio_iov = iv;
983         uiop->uio_iovcnt = cnt;
984         uiop->uio_resid = retlen;
985         uiop->uio_rw = UIO_WRITE;
986         uiop->uio_segflg = UIO_SYSSPACE;
987         NFSUIOPROC(uiop, p);
988         uiop->uio_offset = off;
989         nh = nfsrv_sequential_heuristic(uiop, vp);
990         ioflags |= nh->nh_seqcount << IO_SEQSHIFT;
991         /* XXX KDM make this more systematic? */
992         nfsstatsv1.srvbytes[NFSV4OP_WRITE] += uiop->uio_resid;
993         error = VOP_WRITE(vp, uiop, ioflags, cred);
994         if (error == 0)
995                 nh->nh_nextoff = uiop->uio_offset;
996         free(iv, M_TEMP);
997
998         NFSEXITCODE(error);
999         return (error);
1000 }
1001
1002 /*
1003  * Common code for creating a regular file (plus special files for V2).
1004  */
1005 int
1006 nfsvno_createsub(struct nfsrv_descript *nd, struct nameidata *ndp,
1007     struct vnode **vpp, struct nfsvattr *nvap, int *exclusive_flagp,
1008     int32_t *cverf, NFSDEV_T rdev, struct nfsexstuff *exp)
1009 {
1010         u_quad_t tempsize;
1011         int error;
1012         struct thread *p = curthread;
1013
1014         error = nd->nd_repstat;
1015         if (!error && ndp->ni_vp == NULL) {
1016                 if (nvap->na_type == VREG || nvap->na_type == VSOCK) {
1017                         vrele(ndp->ni_startdir);
1018                         error = VOP_CREATE(ndp->ni_dvp,
1019                             &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
1020                         /* For a pNFS server, create the data file on a DS. */
1021                         if (error == 0 && nvap->na_type == VREG) {
1022                                 /*
1023                                  * Create a data file on a DS for a pNFS server.
1024                                  * This function just returns if not
1025                                  * running a pNFS DS or the creation fails.
1026                                  */
1027                                 nfsrv_pnfscreate(ndp->ni_vp, &nvap->na_vattr,
1028                                     nd->nd_cred, p);
1029                         }
1030                         vput(ndp->ni_dvp);
1031                         nfsvno_relpathbuf(ndp);
1032                         if (!error) {
1033                                 if (*exclusive_flagp) {
1034                                         *exclusive_flagp = 0;
1035                                         NFSVNO_ATTRINIT(nvap);
1036                                         nvap->na_atime.tv_sec = cverf[0];
1037                                         nvap->na_atime.tv_nsec = cverf[1];
1038                                         error = VOP_SETATTR(ndp->ni_vp,
1039                                             &nvap->na_vattr, nd->nd_cred);
1040                                         if (error != 0) {
1041                                                 vput(ndp->ni_vp);
1042                                                 ndp->ni_vp = NULL;
1043                                                 error = NFSERR_NOTSUPP;
1044                                         }
1045                                 }
1046                         }
1047                 /*
1048                  * NFS V2 Only. nfsrvd_mknod() does this for V3.
1049                  * (This implies, just get out on an error.)
1050                  */
1051                 } else if (nvap->na_type == VCHR || nvap->na_type == VBLK ||
1052                         nvap->na_type == VFIFO) {
1053                         if (nvap->na_type == VCHR && rdev == 0xffffffff)
1054                                 nvap->na_type = VFIFO;
1055                         if (nvap->na_type != VFIFO &&
1056                             (error = priv_check_cred(nd->nd_cred, PRIV_VFS_MKNOD_DEV))) {
1057                                 vrele(ndp->ni_startdir);
1058                                 nfsvno_relpathbuf(ndp);
1059                                 vput(ndp->ni_dvp);
1060                                 goto out;
1061                         }
1062                         nvap->na_rdev = rdev;
1063                         error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
1064                             &ndp->ni_cnd, &nvap->na_vattr);
1065                         vput(ndp->ni_dvp);
1066                         nfsvno_relpathbuf(ndp);
1067                         vrele(ndp->ni_startdir);
1068                         if (error)
1069                                 goto out;
1070                 } else {
1071                         vrele(ndp->ni_startdir);
1072                         nfsvno_relpathbuf(ndp);
1073                         vput(ndp->ni_dvp);
1074                         error = ENXIO;
1075                         goto out;
1076                 }
1077                 *vpp = ndp->ni_vp;
1078         } else {
1079                 /*
1080                  * Handle cases where error is already set and/or
1081                  * the file exists.
1082                  * 1 - clean up the lookup
1083                  * 2 - iff !error and na_size set, truncate it
1084                  */
1085                 vrele(ndp->ni_startdir);
1086                 nfsvno_relpathbuf(ndp);
1087                 *vpp = ndp->ni_vp;
1088                 if (ndp->ni_dvp == *vpp)
1089                         vrele(ndp->ni_dvp);
1090                 else
1091                         vput(ndp->ni_dvp);
1092                 if (!error && nvap->na_size != VNOVAL) {
1093                         error = nfsvno_accchk(*vpp, VWRITE,
1094                             nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1095                             NFSACCCHK_VPISLOCKED, NULL);
1096                         if (!error) {
1097                                 tempsize = nvap->na_size;
1098                                 NFSVNO_ATTRINIT(nvap);
1099                                 nvap->na_size = tempsize;
1100                                 error = VOP_SETATTR(*vpp,
1101                                     &nvap->na_vattr, nd->nd_cred);
1102                         }
1103                 }
1104                 if (error)
1105                         vput(*vpp);
1106         }
1107
1108 out:
1109         NFSEXITCODE(error);
1110         return (error);
1111 }
1112
1113 /*
1114  * Do a mknod vnode op.
1115  */
1116 int
1117 nfsvno_mknod(struct nameidata *ndp, struct nfsvattr *nvap, struct ucred *cred,
1118     struct thread *p)
1119 {
1120         int error = 0;
1121         enum vtype vtyp;
1122
1123         vtyp = nvap->na_type;
1124         /*
1125          * Iff doesn't exist, create it.
1126          */
1127         if (ndp->ni_vp) {
1128                 vrele(ndp->ni_startdir);
1129                 nfsvno_relpathbuf(ndp);
1130                 vput(ndp->ni_dvp);
1131                 vrele(ndp->ni_vp);
1132                 error = EEXIST;
1133                 goto out;
1134         }
1135         if (vtyp != VCHR && vtyp != VBLK && vtyp != VSOCK && vtyp != VFIFO) {
1136                 vrele(ndp->ni_startdir);
1137                 nfsvno_relpathbuf(ndp);
1138                 vput(ndp->ni_dvp);
1139                 error = NFSERR_BADTYPE;
1140                 goto out;
1141         }
1142         if (vtyp == VSOCK) {
1143                 vrele(ndp->ni_startdir);
1144                 error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
1145                     &ndp->ni_cnd, &nvap->na_vattr);
1146                 vput(ndp->ni_dvp);
1147                 nfsvno_relpathbuf(ndp);
1148         } else {
1149                 if (nvap->na_type != VFIFO &&
1150                     (error = priv_check_cred(cred, PRIV_VFS_MKNOD_DEV))) {
1151                         vrele(ndp->ni_startdir);
1152                         nfsvno_relpathbuf(ndp);
1153                         vput(ndp->ni_dvp);
1154                         goto out;
1155                 }
1156                 error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
1157                     &ndp->ni_cnd, &nvap->na_vattr);
1158                 vput(ndp->ni_dvp);
1159                 nfsvno_relpathbuf(ndp);
1160                 vrele(ndp->ni_startdir);
1161                 /*
1162                  * Since VOP_MKNOD returns the ni_vp, I can't
1163                  * see any reason to do the lookup.
1164                  */
1165         }
1166
1167 out:
1168         NFSEXITCODE(error);
1169         return (error);
1170 }
1171
1172 /*
1173  * Mkdir vnode op.
1174  */
1175 int
1176 nfsvno_mkdir(struct nameidata *ndp, struct nfsvattr *nvap, uid_t saved_uid,
1177     struct ucred *cred, struct thread *p, struct nfsexstuff *exp)
1178 {
1179         int error = 0;
1180
1181         if (ndp->ni_vp != NULL) {
1182                 if (ndp->ni_dvp == ndp->ni_vp)
1183                         vrele(ndp->ni_dvp);
1184                 else
1185                         vput(ndp->ni_dvp);
1186                 vrele(ndp->ni_vp);
1187                 nfsvno_relpathbuf(ndp);
1188                 error = EEXIST;
1189                 goto out;
1190         }
1191         error = VOP_MKDIR(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
1192             &nvap->na_vattr);
1193         vput(ndp->ni_dvp);
1194         nfsvno_relpathbuf(ndp);
1195
1196 out:
1197         NFSEXITCODE(error);
1198         return (error);
1199 }
1200
1201 /*
1202  * symlink vnode op.
1203  */
1204 int
1205 nfsvno_symlink(struct nameidata *ndp, struct nfsvattr *nvap, char *pathcp,
1206     int pathlen, int not_v2, uid_t saved_uid, struct ucred *cred, struct thread *p,
1207     struct nfsexstuff *exp)
1208 {
1209         int error = 0;
1210
1211         if (ndp->ni_vp) {
1212                 vrele(ndp->ni_startdir);
1213                 nfsvno_relpathbuf(ndp);
1214                 if (ndp->ni_dvp == ndp->ni_vp)
1215                         vrele(ndp->ni_dvp);
1216                 else
1217                         vput(ndp->ni_dvp);
1218                 vrele(ndp->ni_vp);
1219                 error = EEXIST;
1220                 goto out;
1221         }
1222
1223         error = VOP_SYMLINK(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
1224             &nvap->na_vattr, pathcp);
1225         vput(ndp->ni_dvp);
1226         vrele(ndp->ni_startdir);
1227         nfsvno_relpathbuf(ndp);
1228         /*
1229          * Although FreeBSD still had the lookup code in
1230          * it for 7/current, there doesn't seem to be any
1231          * point, since VOP_SYMLINK() returns the ni_vp.
1232          * Just vput it for v2.
1233          */
1234         if (!not_v2 && !error)
1235                 vput(ndp->ni_vp);
1236
1237 out:
1238         NFSEXITCODE(error);
1239         return (error);
1240 }
1241
1242 /*
1243  * Parse symbolic link arguments.
1244  * This function has an ugly side effect. It will malloc() an area for
1245  * the symlink and set iov_base to point to it, only if it succeeds.
1246  * So, if it returns with uiop->uio_iov->iov_base != NULL, that must
1247  * be FREE'd later.
1248  */
1249 int
1250 nfsvno_getsymlink(struct nfsrv_descript *nd, struct nfsvattr *nvap,
1251     struct thread *p, char **pathcpp, int *lenp)
1252 {
1253         u_int32_t *tl;
1254         char *pathcp = NULL;
1255         int error = 0, len;
1256         struct nfsv2_sattr *sp;
1257
1258         *pathcpp = NULL;
1259         *lenp = 0;
1260         if ((nd->nd_flag & ND_NFSV3) &&
1261             (error = nfsrv_sattr(nd, NULL, nvap, NULL, NULL, p)))
1262                 goto nfsmout;
1263         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
1264         len = fxdr_unsigned(int, *tl);
1265         if (len > NFS_MAXPATHLEN || len <= 0) {
1266                 error = EBADRPC;
1267                 goto nfsmout;
1268         }
1269         pathcp = malloc(len + 1, M_TEMP, M_WAITOK);
1270         error = nfsrv_mtostr(nd, pathcp, len);
1271         if (error)
1272                 goto nfsmout;
1273         if (nd->nd_flag & ND_NFSV2) {
1274                 NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
1275                 nvap->na_mode = fxdr_unsigned(u_int16_t, sp->sa_mode);
1276         }
1277         *pathcpp = pathcp;
1278         *lenp = len;
1279         NFSEXITCODE2(0, nd);
1280         return (0);
1281 nfsmout:
1282         if (pathcp)
1283                 free(pathcp, M_TEMP);
1284         NFSEXITCODE2(error, nd);
1285         return (error);
1286 }
1287
1288 /*
1289  * Remove a non-directory object.
1290  */
1291 int
1292 nfsvno_removesub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1293     struct thread *p, struct nfsexstuff *exp)
1294 {
1295         struct vnode *vp, *dsdvp[NFSDEV_MAXMIRRORS];
1296         int error = 0, mirrorcnt;
1297         char fname[PNFS_FILENAME_LEN + 1];
1298         fhandle_t fh;
1299
1300         vp = ndp->ni_vp;
1301         dsdvp[0] = NULL;
1302         if (vp->v_type == VDIR)
1303                 error = NFSERR_ISDIR;
1304         else if (is_v4)
1305                 error = nfsrv_checkremove(vp, 1, NULL, (nfsquad_t)((u_quad_t)0),
1306                     p);
1307         if (error == 0)
1308                 nfsrv_pnfsremovesetup(vp, p, dsdvp, &mirrorcnt, fname, &fh);
1309         if (!error)
1310                 error = VOP_REMOVE(ndp->ni_dvp, vp, &ndp->ni_cnd);
1311         if (error == 0 && dsdvp[0] != NULL)
1312                 nfsrv_pnfsremove(dsdvp, mirrorcnt, fname, &fh, p);
1313         if (ndp->ni_dvp == vp)
1314                 vrele(ndp->ni_dvp);
1315         else
1316                 vput(ndp->ni_dvp);
1317         vput(vp);
1318         if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1319                 nfsvno_relpathbuf(ndp);
1320         NFSEXITCODE(error);
1321         return (error);
1322 }
1323
1324 /*
1325  * Remove a directory.
1326  */
1327 int
1328 nfsvno_rmdirsub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1329     struct thread *p, struct nfsexstuff *exp)
1330 {
1331         struct vnode *vp;
1332         int error = 0;
1333
1334         vp = ndp->ni_vp;
1335         if (vp->v_type != VDIR) {
1336                 error = ENOTDIR;
1337                 goto out;
1338         }
1339         /*
1340          * No rmdir "." please.
1341          */
1342         if (ndp->ni_dvp == vp) {
1343                 error = EINVAL;
1344                 goto out;
1345         }
1346         /*
1347          * The root of a mounted filesystem cannot be deleted.
1348          */
1349         if (vp->v_vflag & VV_ROOT)
1350                 error = EBUSY;
1351 out:
1352         if (!error)
1353                 error = VOP_RMDIR(ndp->ni_dvp, vp, &ndp->ni_cnd);
1354         if (ndp->ni_dvp == vp)
1355                 vrele(ndp->ni_dvp);
1356         else
1357                 vput(ndp->ni_dvp);
1358         vput(vp);
1359         if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1360                 nfsvno_relpathbuf(ndp);
1361         NFSEXITCODE(error);
1362         return (error);
1363 }
1364
1365 /*
1366  * Rename vnode op.
1367  */
1368 int
1369 nfsvno_rename(struct nameidata *fromndp, struct nameidata *tondp,
1370     u_int32_t ndstat, u_int32_t ndflag, struct ucred *cred, struct thread *p)
1371 {
1372         struct vnode *fvp, *tvp, *tdvp, *dsdvp[NFSDEV_MAXMIRRORS];
1373         int error = 0, mirrorcnt;
1374         char fname[PNFS_FILENAME_LEN + 1];
1375         fhandle_t fh;
1376
1377         dsdvp[0] = NULL;
1378         fvp = fromndp->ni_vp;
1379         if (ndstat) {
1380                 vrele(fromndp->ni_dvp);
1381                 vrele(fvp);
1382                 error = ndstat;
1383                 goto out1;
1384         }
1385         tdvp = tondp->ni_dvp;
1386         tvp = tondp->ni_vp;
1387         if (tvp != NULL) {
1388                 if (fvp->v_type == VDIR && tvp->v_type != VDIR) {
1389                         error = (ndflag & ND_NFSV2) ? EISDIR : EEXIST;
1390                         goto out;
1391                 } else if (fvp->v_type != VDIR && tvp->v_type == VDIR) {
1392                         error = (ndflag & ND_NFSV2) ? ENOTDIR : EEXIST;
1393                         goto out;
1394                 }
1395                 if (tvp->v_type == VDIR && tvp->v_mountedhere) {
1396                         error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1397                         goto out;
1398                 }
1399
1400                 /*
1401                  * A rename to '.' or '..' results in a prematurely
1402                  * unlocked vnode on FreeBSD5, so I'm just going to fail that
1403                  * here.
1404                  */
1405                 if ((tondp->ni_cnd.cn_namelen == 1 &&
1406                      tondp->ni_cnd.cn_nameptr[0] == '.') ||
1407                     (tondp->ni_cnd.cn_namelen == 2 &&
1408                      tondp->ni_cnd.cn_nameptr[0] == '.' &&
1409                      tondp->ni_cnd.cn_nameptr[1] == '.')) {
1410                         error = EINVAL;
1411                         goto out;
1412                 }
1413         }
1414         if (fvp->v_type == VDIR && fvp->v_mountedhere) {
1415                 error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1416                 goto out;
1417         }
1418         if (fvp->v_mount != tdvp->v_mount) {
1419                 error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1420                 goto out;
1421         }
1422         if (fvp == tdvp) {
1423                 error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EINVAL;
1424                 goto out;
1425         }
1426         if (fvp == tvp) {
1427                 /*
1428                  * If source and destination are the same, there is nothing to
1429                  * do. Set error to -1 to indicate this.
1430                  */
1431                 error = -1;
1432                 goto out;
1433         }
1434         if (ndflag & ND_NFSV4) {
1435                 if (NFSVOPLOCK(fvp, LK_EXCLUSIVE) == 0) {
1436                         error = nfsrv_checkremove(fvp, 0, NULL,
1437                             (nfsquad_t)((u_quad_t)0), p);
1438                         NFSVOPUNLOCK(fvp);
1439                 } else
1440                         error = EPERM;
1441                 if (tvp && !error)
1442                         error = nfsrv_checkremove(tvp, 1, NULL,
1443                             (nfsquad_t)((u_quad_t)0), p);
1444         } else {
1445                 /*
1446                  * For NFSv2 and NFSv3, try to get rid of the delegation, so
1447                  * that the NFSv4 client won't be confused by the rename.
1448                  * Since nfsd_recalldelegation() can only be called on an
1449                  * unlocked vnode at this point and fvp is the file that will
1450                  * still exist after the rename, just do fvp.
1451                  */
1452                 nfsd_recalldelegation(fvp, p);
1453         }
1454         if (error == 0 && tvp != NULL) {
1455                 nfsrv_pnfsremovesetup(tvp, p, dsdvp, &mirrorcnt, fname, &fh);
1456                 NFSD_DEBUG(4, "nfsvno_rename: pnfsremovesetup"
1457                     " dsdvp=%p\n", dsdvp[0]);
1458         }
1459 out:
1460         if (!error) {
1461                 error = VOP_RENAME(fromndp->ni_dvp, fromndp->ni_vp,
1462                     &fromndp->ni_cnd, tondp->ni_dvp, tondp->ni_vp,
1463                     &tondp->ni_cnd);
1464         } else {
1465                 if (tdvp == tvp)
1466                         vrele(tdvp);
1467                 else
1468                         vput(tdvp);
1469                 if (tvp)
1470                         vput(tvp);
1471                 vrele(fromndp->ni_dvp);
1472                 vrele(fvp);
1473                 if (error == -1)
1474                         error = 0;
1475         }
1476
1477         /*
1478          * If dsdvp[0] != NULL, it was set up by nfsrv_pnfsremovesetup() and
1479          * if the rename succeeded, the DS file for the tvp needs to be
1480          * removed.
1481          */
1482         if (error == 0 && dsdvp[0] != NULL) {
1483                 nfsrv_pnfsremove(dsdvp, mirrorcnt, fname, &fh, p);
1484                 NFSD_DEBUG(4, "nfsvno_rename: pnfsremove\n");
1485         }
1486
1487         vrele(tondp->ni_startdir);
1488         nfsvno_relpathbuf(tondp);
1489 out1:
1490         vrele(fromndp->ni_startdir);
1491         nfsvno_relpathbuf(fromndp);
1492         NFSEXITCODE(error);
1493         return (error);
1494 }
1495
1496 /*
1497  * Link vnode op.
1498  */
1499 int
1500 nfsvno_link(struct nameidata *ndp, struct vnode *vp, struct ucred *cred,
1501     struct thread *p, struct nfsexstuff *exp)
1502 {
1503         struct vnode *xp;
1504         int error = 0;
1505
1506         xp = ndp->ni_vp;
1507         if (xp != NULL) {
1508                 error = EEXIST;
1509         } else {
1510                 xp = ndp->ni_dvp;
1511                 if (vp->v_mount != xp->v_mount)
1512                         error = EXDEV;
1513         }
1514         if (!error) {
1515                 NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
1516                 if (!VN_IS_DOOMED(vp))
1517                         error = VOP_LINK(ndp->ni_dvp, vp, &ndp->ni_cnd);
1518                 else
1519                         error = EPERM;
1520                 if (ndp->ni_dvp == vp)
1521                         vrele(ndp->ni_dvp);
1522                 else
1523                         vput(ndp->ni_dvp);
1524                 NFSVOPUNLOCK(vp);
1525         } else {
1526                 if (ndp->ni_dvp == ndp->ni_vp)
1527                         vrele(ndp->ni_dvp);
1528                 else
1529                         vput(ndp->ni_dvp);
1530                 if (ndp->ni_vp)
1531                         vrele(ndp->ni_vp);
1532         }
1533         nfsvno_relpathbuf(ndp);
1534         NFSEXITCODE(error);
1535         return (error);
1536 }
1537
1538 /*
1539  * Do the fsync() appropriate for the commit.
1540  */
1541 int
1542 nfsvno_fsync(struct vnode *vp, u_int64_t off, int cnt, struct ucred *cred,
1543     struct thread *td)
1544 {
1545         int error = 0;
1546
1547         /*
1548          * RFC 1813 3.3.21: if count is 0, a flush from offset to the end of
1549          * file is done.  At this time VOP_FSYNC does not accept offset and
1550          * byte count parameters so call VOP_FSYNC the whole file for now.
1551          * The same is true for NFSv4: RFC 3530 Sec. 14.2.3.
1552          * File systems that do not use the buffer cache (as indicated
1553          * by MNTK_USES_BCACHE not being set) must use VOP_FSYNC().
1554          */
1555         if (cnt == 0 || cnt > MAX_COMMIT_COUNT ||
1556             (vp->v_mount->mnt_kern_flag & MNTK_USES_BCACHE) == 0) {
1557                 /*
1558                  * Give up and do the whole thing
1559                  */
1560                 if (vp->v_object && vm_object_mightbedirty(vp->v_object)) {
1561                         VM_OBJECT_WLOCK(vp->v_object);
1562                         vm_object_page_clean(vp->v_object, 0, 0, OBJPC_SYNC);
1563                         VM_OBJECT_WUNLOCK(vp->v_object);
1564                 }
1565                 error = VOP_FSYNC(vp, MNT_WAIT, td);
1566         } else {
1567                 /*
1568                  * Locate and synchronously write any buffers that fall
1569                  * into the requested range.  Note:  we are assuming that
1570                  * f_iosize is a power of 2.
1571                  */
1572                 int iosize = vp->v_mount->mnt_stat.f_iosize;
1573                 int iomask = iosize - 1;
1574                 struct bufobj *bo;
1575                 daddr_t lblkno;
1576
1577                 /*
1578                  * Align to iosize boundary, super-align to page boundary.
1579                  */
1580                 if (off & iomask) {
1581                         cnt += off & iomask;
1582                         off &= ~(u_quad_t)iomask;
1583                 }
1584                 if (off & PAGE_MASK) {
1585                         cnt += off & PAGE_MASK;
1586                         off &= ~(u_quad_t)PAGE_MASK;
1587                 }
1588                 lblkno = off / iosize;
1589
1590                 if (vp->v_object && vm_object_mightbedirty(vp->v_object)) {
1591                         VM_OBJECT_WLOCK(vp->v_object);
1592                         vm_object_page_clean(vp->v_object, off, off + cnt,
1593                             OBJPC_SYNC);
1594                         VM_OBJECT_WUNLOCK(vp->v_object);
1595                 }
1596
1597                 bo = &vp->v_bufobj;
1598                 BO_LOCK(bo);
1599                 while (cnt > 0) {
1600                         struct buf *bp;
1601
1602                         /*
1603                          * If we have a buffer and it is marked B_DELWRI we
1604                          * have to lock and write it.  Otherwise the prior
1605                          * write is assumed to have already been committed.
1606                          *
1607                          * gbincore() can return invalid buffers now so we
1608                          * have to check that bit as well (though B_DELWRI
1609                          * should not be set if B_INVAL is set there could be
1610                          * a race here since we haven't locked the buffer).
1611                          */
1612                         if ((bp = gbincore(&vp->v_bufobj, lblkno)) != NULL) {
1613                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
1614                                     LK_INTERLOCK, BO_LOCKPTR(bo)) == ENOLCK) {
1615                                         BO_LOCK(bo);
1616                                         continue; /* retry */
1617                                 }
1618                                 if ((bp->b_flags & (B_DELWRI|B_INVAL)) ==
1619                                     B_DELWRI) {
1620                                         bremfree(bp);
1621                                         bp->b_flags &= ~B_ASYNC;
1622                                         bwrite(bp);
1623                                         ++nfs_commit_miss;
1624                                 } else
1625                                         BUF_UNLOCK(bp);
1626                                 BO_LOCK(bo);
1627                         }
1628                         ++nfs_commit_blks;
1629                         if (cnt < iosize)
1630                                 break;
1631                         cnt -= iosize;
1632                         ++lblkno;
1633                 }
1634                 BO_UNLOCK(bo);
1635         }
1636         NFSEXITCODE(error);
1637         return (error);
1638 }
1639
1640 /*
1641  * Statfs vnode op.
1642  */
1643 int
1644 nfsvno_statfs(struct vnode *vp, struct statfs *sf)
1645 {
1646         struct statfs *tsf;
1647         int error;
1648
1649         tsf = NULL;
1650         if (nfsrv_devidcnt > 0) {
1651                 /* For a pNFS service, get the DS numbers. */
1652                 tsf = malloc(sizeof(*tsf), M_TEMP, M_WAITOK | M_ZERO);
1653                 error = nfsrv_pnfsstatfs(tsf, vp->v_mount);
1654                 if (error != 0) {
1655                         free(tsf, M_TEMP);
1656                         tsf = NULL;
1657                 }
1658         }
1659         error = VFS_STATFS(vp->v_mount, sf);
1660         if (error == 0) {
1661                 if (tsf != NULL) {
1662                         sf->f_blocks = tsf->f_blocks;
1663                         sf->f_bavail = tsf->f_bavail;
1664                         sf->f_bfree = tsf->f_bfree;
1665                         sf->f_bsize = tsf->f_bsize;
1666                 }
1667                 /*
1668                  * Since NFS handles these values as unsigned on the
1669                  * wire, there is no way to represent negative values,
1670                  * so set them to 0. Without this, they will appear
1671                  * to be very large positive values for clients like
1672                  * Solaris10.
1673                  */
1674                 if (sf->f_bavail < 0)
1675                         sf->f_bavail = 0;
1676                 if (sf->f_ffree < 0)
1677                         sf->f_ffree = 0;
1678         }
1679         free(tsf, M_TEMP);
1680         NFSEXITCODE(error);
1681         return (error);
1682 }
1683
1684 /*
1685  * Do the vnode op stuff for Open. Similar to nfsvno_createsub(), but
1686  * must handle nfsrv_opencheck() calls after any other access checks.
1687  */
1688 void
1689 nfsvno_open(struct nfsrv_descript *nd, struct nameidata *ndp,
1690     nfsquad_t clientid, nfsv4stateid_t *stateidp, struct nfsstate *stp,
1691     int *exclusive_flagp, struct nfsvattr *nvap, int32_t *cverf, int create,
1692     NFSACL_T *aclp, nfsattrbit_t *attrbitp, struct ucred *cred,
1693     struct nfsexstuff *exp, struct vnode **vpp)
1694 {
1695         struct vnode *vp = NULL;
1696         u_quad_t tempsize;
1697         struct nfsexstuff nes;
1698         struct thread *p = curthread;
1699
1700         if (ndp->ni_vp == NULL)
1701                 nd->nd_repstat = nfsrv_opencheck(clientid,
1702                     stateidp, stp, NULL, nd, p, nd->nd_repstat);
1703         if (!nd->nd_repstat) {
1704                 if (ndp->ni_vp == NULL) {
1705                         vrele(ndp->ni_startdir);
1706                         nd->nd_repstat = VOP_CREATE(ndp->ni_dvp,
1707                             &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
1708                         /* For a pNFS server, create the data file on a DS. */
1709                         if (nd->nd_repstat == 0) {
1710                                 /*
1711                                  * Create a data file on a DS for a pNFS server.
1712                                  * This function just returns if not
1713                                  * running a pNFS DS or the creation fails.
1714                                  */
1715                                 nfsrv_pnfscreate(ndp->ni_vp, &nvap->na_vattr,
1716                                     cred, p);
1717                         }
1718                         vput(ndp->ni_dvp);
1719                         nfsvno_relpathbuf(ndp);
1720                         if (!nd->nd_repstat) {
1721                                 if (*exclusive_flagp) {
1722                                         *exclusive_flagp = 0;
1723                                         NFSVNO_ATTRINIT(nvap);
1724                                         nvap->na_atime.tv_sec = cverf[0];
1725                                         nvap->na_atime.tv_nsec = cverf[1];
1726                                         nd->nd_repstat = VOP_SETATTR(ndp->ni_vp,
1727                                             &nvap->na_vattr, cred);
1728                                         if (nd->nd_repstat != 0) {
1729                                                 vput(ndp->ni_vp);
1730                                                 ndp->ni_vp = NULL;
1731                                                 nd->nd_repstat = NFSERR_NOTSUPP;
1732                                         } else
1733                                                 NFSSETBIT_ATTRBIT(attrbitp,
1734                                                     NFSATTRBIT_TIMEACCESS);
1735                                 } else {
1736                                         nfsrv_fixattr(nd, ndp->ni_vp, nvap,
1737                                             aclp, p, attrbitp, exp);
1738                                 }
1739                         }
1740                         vp = ndp->ni_vp;
1741                 } else {
1742                         if (ndp->ni_startdir)
1743                                 vrele(ndp->ni_startdir);
1744                         nfsvno_relpathbuf(ndp);
1745                         vp = ndp->ni_vp;
1746                         if (create == NFSV4OPEN_CREATE) {
1747                                 if (ndp->ni_dvp == vp)
1748                                         vrele(ndp->ni_dvp);
1749                                 else
1750                                         vput(ndp->ni_dvp);
1751                         }
1752                         if (NFSVNO_ISSETSIZE(nvap) && vp->v_type == VREG) {
1753                                 if (ndp->ni_cnd.cn_flags & RDONLY)
1754                                         NFSVNO_SETEXRDONLY(&nes);
1755                                 else
1756                                         NFSVNO_EXINIT(&nes);
1757                                 nd->nd_repstat = nfsvno_accchk(vp, 
1758                                     VWRITE, cred, &nes, p,
1759                                     NFSACCCHK_NOOVERRIDE,
1760                                     NFSACCCHK_VPISLOCKED, NULL);
1761                                 nd->nd_repstat = nfsrv_opencheck(clientid,
1762                                     stateidp, stp, vp, nd, p, nd->nd_repstat);
1763                                 if (!nd->nd_repstat) {
1764                                         tempsize = nvap->na_size;
1765                                         NFSVNO_ATTRINIT(nvap);
1766                                         nvap->na_size = tempsize;
1767                                         nd->nd_repstat = VOP_SETATTR(vp,
1768                                             &nvap->na_vattr, cred);
1769                                 }
1770                         } else if (vp->v_type == VREG) {
1771                                 nd->nd_repstat = nfsrv_opencheck(clientid,
1772                                     stateidp, stp, vp, nd, p, nd->nd_repstat);
1773                         }
1774                 }
1775         } else {
1776                 if (ndp->ni_cnd.cn_flags & HASBUF)
1777                         nfsvno_relpathbuf(ndp);
1778                 if (ndp->ni_startdir && create == NFSV4OPEN_CREATE) {
1779                         vrele(ndp->ni_startdir);
1780                         if (ndp->ni_dvp == ndp->ni_vp)
1781                                 vrele(ndp->ni_dvp);
1782                         else
1783                                 vput(ndp->ni_dvp);
1784                         if (ndp->ni_vp)
1785                                 vput(ndp->ni_vp);
1786                 }
1787         }
1788         *vpp = vp;
1789
1790         NFSEXITCODE2(0, nd);
1791 }
1792
1793 /*
1794  * Updates the file rev and sets the mtime and ctime
1795  * to the current clock time, returning the va_filerev and va_Xtime
1796  * values.
1797  * Return ESTALE to indicate the vnode is VIRF_DOOMED.
1798  */
1799 int
1800 nfsvno_updfilerev(struct vnode *vp, struct nfsvattr *nvap,
1801     struct nfsrv_descript *nd, struct thread *p)
1802 {
1803         struct vattr va;
1804
1805         VATTR_NULL(&va);
1806         vfs_timestamp(&va.va_mtime);
1807         if (NFSVOPISLOCKED(vp) != LK_EXCLUSIVE) {
1808                 NFSVOPLOCK(vp, LK_UPGRADE | LK_RETRY);
1809                 if (VN_IS_DOOMED(vp))
1810                         return (ESTALE);
1811         }
1812         (void) VOP_SETATTR(vp, &va, nd->nd_cred);
1813         (void) nfsvno_getattr(vp, nvap, nd, p, 1, NULL);
1814         return (0);
1815 }
1816
1817 /*
1818  * Glue routine to nfsv4_fillattr().
1819  */
1820 int
1821 nfsvno_fillattr(struct nfsrv_descript *nd, struct mount *mp, struct vnode *vp,
1822     struct nfsvattr *nvap, fhandle_t *fhp, int rderror, nfsattrbit_t *attrbitp,
1823     struct ucred *cred, struct thread *p, int isdgram, int reterr,
1824     int supports_nfsv4acls, int at_root, uint64_t mounted_on_fileno)
1825 {
1826         struct statfs *sf;
1827         int error;
1828
1829         sf = NULL;
1830         if (nfsrv_devidcnt > 0 &&
1831             (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SPACEAVAIL) ||
1832              NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SPACEFREE) ||
1833              NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SPACETOTAL))) {
1834                 sf = malloc(sizeof(*sf), M_TEMP, M_WAITOK | M_ZERO);
1835                 error = nfsrv_pnfsstatfs(sf, mp);
1836                 if (error != 0) {
1837                         free(sf, M_TEMP);
1838                         sf = NULL;
1839                 }
1840         }
1841         error = nfsv4_fillattr(nd, mp, vp, NULL, &nvap->na_vattr, fhp, rderror,
1842             attrbitp, cred, p, isdgram, reterr, supports_nfsv4acls, at_root,
1843             mounted_on_fileno, sf);
1844         free(sf, M_TEMP);
1845         NFSEXITCODE2(0, nd);
1846         return (error);
1847 }
1848
1849 /* Since the Readdir vnode ops vary, put the entire functions in here. */
1850 /*
1851  * nfs readdir service
1852  * - mallocs what it thinks is enough to read
1853  *      count rounded up to a multiple of DIRBLKSIZ <= NFS_MAXREADDIR
1854  * - calls VOP_READDIR()
1855  * - loops around building the reply
1856  *      if the output generated exceeds count break out of loop
1857  *      The NFSM_CLGET macro is used here so that the reply will be packed
1858  *      tightly in mbuf clusters.
1859  * - it trims out records with d_fileno == 0
1860  *      this doesn't matter for Unix clients, but they might confuse clients
1861  *      for other os'.
1862  * - it trims out records with d_type == DT_WHT
1863  *      these cannot be seen through NFS (unless we extend the protocol)
1864  *     The alternate call nfsrvd_readdirplus() does lookups as well.
1865  * PS: The NFS protocol spec. does not clarify what the "count" byte
1866  *      argument is a count of.. just name strings and file id's or the
1867  *      entire reply rpc or ...
1868  *      I tried just file name and id sizes and it confused the Sun client,
1869  *      so I am using the full rpc size now. The "paranoia.." comment refers
1870  *      to including the status longwords that are not a part of the dir.
1871  *      "entry" structures, but are in the rpc.
1872  */
1873 int
1874 nfsrvd_readdir(struct nfsrv_descript *nd, int isdgram,
1875     struct vnode *vp, struct nfsexstuff *exp)
1876 {
1877         struct dirent *dp;
1878         u_int32_t *tl;
1879         int dirlen;
1880         char *cpos, *cend, *rbuf;
1881         struct nfsvattr at;
1882         int nlen, error = 0, getret = 1;
1883         int siz, cnt, fullsiz, eofflag, ncookies;
1884         u_int64_t off, toff, verf __unused;
1885         u_long *cookies = NULL, *cookiep;
1886         struct uio io;
1887         struct iovec iv;
1888         int is_ufs;
1889         struct thread *p = curthread;
1890
1891         if (nd->nd_repstat) {
1892                 nfsrv_postopattr(nd, getret, &at);
1893                 goto out;
1894         }
1895         if (nd->nd_flag & ND_NFSV2) {
1896                 NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1897                 off = fxdr_unsigned(u_quad_t, *tl++);
1898         } else {
1899                 NFSM_DISSECT(tl, u_int32_t *, 5 * NFSX_UNSIGNED);
1900                 off = fxdr_hyper(tl);
1901                 tl += 2;
1902                 verf = fxdr_hyper(tl);
1903                 tl += 2;
1904         }
1905         toff = off;
1906         cnt = fxdr_unsigned(int, *tl);
1907         if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
1908                 cnt = NFS_SRVMAXDATA(nd);
1909         siz = ((cnt + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
1910         fullsiz = siz;
1911         if (nd->nd_flag & ND_NFSV3) {
1912                 nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd, p, 1,
1913                     NULL);
1914 #if 0
1915                 /*
1916                  * va_filerev is not sufficient as a cookie verifier,
1917                  * since it is not supposed to change when entries are
1918                  * removed/added unless that offset cookies returned to
1919                  * the client are no longer valid.
1920                  */
1921                 if (!nd->nd_repstat && toff && verf != at.na_filerev)
1922                         nd->nd_repstat = NFSERR_BAD_COOKIE;
1923 #endif
1924         }
1925         if (!nd->nd_repstat && vp->v_type != VDIR)
1926                 nd->nd_repstat = NFSERR_NOTDIR;
1927         if (nd->nd_repstat == 0 && cnt == 0) {
1928                 if (nd->nd_flag & ND_NFSV2)
1929                         /* NFSv2 does not have NFSERR_TOOSMALL */
1930                         nd->nd_repstat = EPERM;
1931                 else
1932                         nd->nd_repstat = NFSERR_TOOSMALL;
1933         }
1934         if (!nd->nd_repstat)
1935                 nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
1936                     nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1937                     NFSACCCHK_VPISLOCKED, NULL);
1938         if (nd->nd_repstat) {
1939                 vput(vp);
1940                 if (nd->nd_flag & ND_NFSV3)
1941                         nfsrv_postopattr(nd, getret, &at);
1942                 goto out;
1943         }
1944         is_ufs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "ufs") == 0;
1945         rbuf = malloc(siz, M_TEMP, M_WAITOK);
1946 again:
1947         eofflag = 0;
1948         if (cookies) {
1949                 free(cookies, M_TEMP);
1950                 cookies = NULL;
1951         }
1952
1953         iv.iov_base = rbuf;
1954         iv.iov_len = siz;
1955         io.uio_iov = &iv;
1956         io.uio_iovcnt = 1;
1957         io.uio_offset = (off_t)off;
1958         io.uio_resid = siz;
1959         io.uio_segflg = UIO_SYSSPACE;
1960         io.uio_rw = UIO_READ;
1961         io.uio_td = NULL;
1962         nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
1963             &cookies);
1964         off = (u_int64_t)io.uio_offset;
1965         if (io.uio_resid)
1966                 siz -= io.uio_resid;
1967
1968         if (!cookies && !nd->nd_repstat)
1969                 nd->nd_repstat = NFSERR_PERM;
1970         if (nd->nd_flag & ND_NFSV3) {
1971                 getret = nfsvno_getattr(vp, &at, nd, p, 1, NULL);
1972                 if (!nd->nd_repstat)
1973                         nd->nd_repstat = getret;
1974         }
1975
1976         /*
1977          * Handles the failed cases. nd->nd_repstat == 0 past here.
1978          */
1979         if (nd->nd_repstat) {
1980                 vput(vp);
1981                 free(rbuf, M_TEMP);
1982                 if (cookies)
1983                         free(cookies, M_TEMP);
1984                 if (nd->nd_flag & ND_NFSV3)
1985                         nfsrv_postopattr(nd, getret, &at);
1986                 goto out;
1987         }
1988         /*
1989          * If nothing read, return eof
1990          * rpc reply
1991          */
1992         if (siz == 0) {
1993                 vput(vp);
1994                 if (nd->nd_flag & ND_NFSV2) {
1995                         NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1996                 } else {
1997                         nfsrv_postopattr(nd, getret, &at);
1998                         NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
1999                         txdr_hyper(at.na_filerev, tl);
2000                         tl += 2;
2001                 }
2002                 *tl++ = newnfs_false;
2003                 *tl = newnfs_true;
2004                 free(rbuf, M_TEMP);
2005                 free(cookies, M_TEMP);
2006                 goto out;
2007         }
2008
2009         /*
2010          * Check for degenerate cases of nothing useful read.
2011          * If so go try again
2012          */
2013         cpos = rbuf;
2014         cend = rbuf + siz;
2015         dp = (struct dirent *)cpos;
2016         cookiep = cookies;
2017
2018         /*
2019          * For some reason FreeBSD's ufs_readdir() chooses to back the
2020          * directory offset up to a block boundary, so it is necessary to
2021          * skip over the records that precede the requested offset. This
2022          * requires the assumption that file offset cookies monotonically
2023          * increase.
2024          */
2025         while (cpos < cend && ncookies > 0 &&
2026             (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
2027              (is_ufs == 1 && ((u_quad_t)(*cookiep)) <= toff))) {
2028                 cpos += dp->d_reclen;
2029                 dp = (struct dirent *)cpos;
2030                 cookiep++;
2031                 ncookies--;
2032         }
2033         if (cpos >= cend || ncookies == 0) {
2034                 siz = fullsiz;
2035                 toff = off;
2036                 goto again;
2037         }
2038         vput(vp);
2039
2040         /*
2041          * dirlen is the size of the reply, including all XDR and must
2042          * not exceed cnt. For NFSv2, RFC1094 didn't clearly indicate
2043          * if the XDR should be included in "count", but to be safe, we do.
2044          * (Include the two booleans at the end of the reply in dirlen now.)
2045          */
2046         if (nd->nd_flag & ND_NFSV3) {
2047                 nfsrv_postopattr(nd, getret, &at);
2048                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2049                 txdr_hyper(at.na_filerev, tl);
2050                 dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
2051         } else {
2052                 dirlen = 2 * NFSX_UNSIGNED;
2053         }
2054
2055         /* Loop through the records and build reply */
2056         while (cpos < cend && ncookies > 0) {
2057                 nlen = dp->d_namlen;
2058                 if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
2059                         nlen <= NFS_MAXNAMLEN) {
2060                         if (nd->nd_flag & ND_NFSV3)
2061                                 dirlen += (6*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
2062                         else
2063                                 dirlen += (4*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
2064                         if (dirlen > cnt) {
2065                                 eofflag = 0;
2066                                 break;
2067                         }
2068
2069                         /*
2070                          * Build the directory record xdr from
2071                          * the dirent entry.
2072                          */
2073                         if (nd->nd_flag & ND_NFSV3) {
2074                                 NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2075                                 *tl++ = newnfs_true;
2076                                 *tl++ = 0;
2077                         } else {
2078                                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2079                                 *tl++ = newnfs_true;
2080                         }
2081                         *tl = txdr_unsigned(dp->d_fileno);
2082                         (void) nfsm_strtom(nd, dp->d_name, nlen);
2083                         if (nd->nd_flag & ND_NFSV3) {
2084                                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2085                                 *tl++ = 0;
2086                         } else
2087                                 NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
2088                         *tl = txdr_unsigned(*cookiep);
2089                 }
2090                 cpos += dp->d_reclen;
2091                 dp = (struct dirent *)cpos;
2092                 cookiep++;
2093                 ncookies--;
2094         }
2095         if (cpos < cend)
2096                 eofflag = 0;
2097         NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2098         *tl++ = newnfs_false;
2099         if (eofflag)
2100                 *tl = newnfs_true;
2101         else
2102                 *tl = newnfs_false;
2103         free(rbuf, M_TEMP);
2104         free(cookies, M_TEMP);
2105
2106 out:
2107         NFSEXITCODE2(0, nd);
2108         return (0);
2109 nfsmout:
2110         vput(vp);
2111         NFSEXITCODE2(error, nd);
2112         return (error);
2113 }
2114
2115 /*
2116  * Readdirplus for V3 and Readdir for V4.
2117  */
2118 int
2119 nfsrvd_readdirplus(struct nfsrv_descript *nd, int isdgram,
2120     struct vnode *vp, struct nfsexstuff *exp)
2121 {
2122         struct dirent *dp;
2123         u_int32_t *tl;
2124         int dirlen;
2125         char *cpos, *cend, *rbuf;
2126         struct vnode *nvp;
2127         fhandle_t nfh;
2128         struct nfsvattr nva, at, *nvap = &nva;
2129         struct mbuf *mb0, *mb1;
2130         struct nfsreferral *refp;
2131         int nlen, r, error = 0, getret = 1, usevget = 1;
2132         int siz, cnt, fullsiz, eofflag, ncookies, entrycnt;
2133         caddr_t bpos0, bpos1;
2134         u_int64_t off, toff, verf;
2135         u_long *cookies = NULL, *cookiep;
2136         nfsattrbit_t attrbits, rderrbits, savbits;
2137         struct uio io;
2138         struct iovec iv;
2139         struct componentname cn;
2140         int at_root, is_ufs, is_zfs, needs_unbusy, supports_nfsv4acls;
2141         struct mount *mp, *new_mp;
2142         uint64_t mounted_on_fileno;
2143         struct thread *p = curthread;
2144
2145         if (nd->nd_repstat) {
2146                 nfsrv_postopattr(nd, getret, &at);
2147                 goto out;
2148         }
2149         NFSM_DISSECT(tl, u_int32_t *, 6 * NFSX_UNSIGNED);
2150         off = fxdr_hyper(tl);
2151         toff = off;
2152         tl += 2;
2153         verf = fxdr_hyper(tl);
2154         tl += 2;
2155         siz = fxdr_unsigned(int, *tl++);
2156         cnt = fxdr_unsigned(int, *tl);
2157
2158         /*
2159          * Use the server's maximum data transfer size as the upper bound
2160          * on reply datalen.
2161          */
2162         if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
2163                 cnt = NFS_SRVMAXDATA(nd);
2164
2165         /*
2166          * siz is a "hint" of how much directory information (name, fileid,
2167          * cookie) should be in the reply. At least one client "hints" 0,
2168          * so I set it to cnt for that case. I also round it up to the
2169          * next multiple of DIRBLKSIZ.
2170          * Since the size of a Readdirplus directory entry reply will always
2171          * be greater than a directory entry returned by VOP_READDIR(), it
2172          * does not make sense to read more than NFS_SRVMAXDATA() via
2173          * VOP_READDIR().
2174          */
2175         if (siz <= 0)
2176                 siz = cnt;
2177         else if (siz > NFS_SRVMAXDATA(nd))
2178                 siz = NFS_SRVMAXDATA(nd);
2179         siz = ((siz + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
2180
2181         if (nd->nd_flag & ND_NFSV4) {
2182                 error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
2183                 if (error)
2184                         goto nfsmout;
2185                 NFSSET_ATTRBIT(&savbits, &attrbits);
2186                 NFSCLRNOTFILLABLE_ATTRBIT(&attrbits, nd);
2187                 NFSZERO_ATTRBIT(&rderrbits);
2188                 NFSSETBIT_ATTRBIT(&rderrbits, NFSATTRBIT_RDATTRERROR);
2189         } else {
2190                 NFSZERO_ATTRBIT(&attrbits);
2191         }
2192         fullsiz = siz;
2193         nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd, p, 1, NULL);
2194 #if 0
2195         if (!nd->nd_repstat) {
2196             if (off && verf != at.na_filerev) {
2197                 /*
2198                  * va_filerev is not sufficient as a cookie verifier,
2199                  * since it is not supposed to change when entries are
2200                  * removed/added unless that offset cookies returned to
2201                  * the client are no longer valid.
2202                  */
2203                 if (nd->nd_flag & ND_NFSV4) {
2204                         nd->nd_repstat = NFSERR_NOTSAME;
2205                 } else {
2206                         nd->nd_repstat = NFSERR_BAD_COOKIE;
2207                 }
2208             }
2209         }
2210 #endif
2211         if (!nd->nd_repstat && vp->v_type != VDIR)
2212                 nd->nd_repstat = NFSERR_NOTDIR;
2213         if (!nd->nd_repstat && cnt == 0)
2214                 nd->nd_repstat = NFSERR_TOOSMALL;
2215         if (!nd->nd_repstat)
2216                 nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
2217                     nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
2218                     NFSACCCHK_VPISLOCKED, NULL);
2219         if (nd->nd_repstat) {
2220                 vput(vp);
2221                 if (nd->nd_flag & ND_NFSV3)
2222                         nfsrv_postopattr(nd, getret, &at);
2223                 goto out;
2224         }
2225         is_ufs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "ufs") == 0;
2226         is_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs") == 0;
2227
2228         rbuf = malloc(siz, M_TEMP, M_WAITOK);
2229 again:
2230         eofflag = 0;
2231         if (cookies) {
2232                 free(cookies, M_TEMP);
2233                 cookies = NULL;
2234         }
2235
2236         iv.iov_base = rbuf;
2237         iv.iov_len = siz;
2238         io.uio_iov = &iv;
2239         io.uio_iovcnt = 1;
2240         io.uio_offset = (off_t)off;
2241         io.uio_resid = siz;
2242         io.uio_segflg = UIO_SYSSPACE;
2243         io.uio_rw = UIO_READ;
2244         io.uio_td = NULL;
2245         nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
2246             &cookies);
2247         off = (u_int64_t)io.uio_offset;
2248         if (io.uio_resid)
2249                 siz -= io.uio_resid;
2250
2251         getret = nfsvno_getattr(vp, &at, nd, p, 1, NULL);
2252
2253         if (!cookies && !nd->nd_repstat)
2254                 nd->nd_repstat = NFSERR_PERM;
2255         if (!nd->nd_repstat)
2256                 nd->nd_repstat = getret;
2257         if (nd->nd_repstat) {
2258                 vput(vp);
2259                 if (cookies)
2260                         free(cookies, M_TEMP);
2261                 free(rbuf, M_TEMP);
2262                 if (nd->nd_flag & ND_NFSV3)
2263                         nfsrv_postopattr(nd, getret, &at);
2264                 goto out;
2265         }
2266         /*
2267          * If nothing read, return eof
2268          * rpc reply
2269          */
2270         if (siz == 0) {
2271                 vput(vp);
2272                 if (nd->nd_flag & ND_NFSV3)
2273                         nfsrv_postopattr(nd, getret, &at);
2274                 NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
2275                 txdr_hyper(at.na_filerev, tl);
2276                 tl += 2;
2277                 *tl++ = newnfs_false;
2278                 *tl = newnfs_true;
2279                 free(cookies, M_TEMP);
2280                 free(rbuf, M_TEMP);
2281                 goto out;
2282         }
2283
2284         /*
2285          * Check for degenerate cases of nothing useful read.
2286          * If so go try again
2287          */
2288         cpos = rbuf;
2289         cend = rbuf + siz;
2290         dp = (struct dirent *)cpos;
2291         cookiep = cookies;
2292
2293         /*
2294          * For some reason FreeBSD's ufs_readdir() chooses to back the
2295          * directory offset up to a block boundary, so it is necessary to
2296          * skip over the records that precede the requested offset. This
2297          * requires the assumption that file offset cookies monotonically
2298          * increase.
2299          */
2300         while (cpos < cend && ncookies > 0 &&
2301           (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
2302            (is_ufs == 1 && ((u_quad_t)(*cookiep)) <= toff) ||
2303            ((nd->nd_flag & ND_NFSV4) &&
2304             ((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
2305              (dp->d_namlen==2 && dp->d_name[0]=='.' && dp->d_name[1]=='.'))))) {
2306                 cpos += dp->d_reclen;
2307                 dp = (struct dirent *)cpos;
2308                 cookiep++;
2309                 ncookies--;
2310         }
2311         if (cpos >= cend || ncookies == 0) {
2312                 siz = fullsiz;
2313                 toff = off;
2314                 goto again;
2315         }
2316
2317         /*
2318          * Busy the file system so that the mount point won't go away
2319          * and, as such, VFS_VGET() can be used safely.
2320          */
2321         mp = vp->v_mount;
2322         vfs_ref(mp);
2323         NFSVOPUNLOCK(vp);
2324         nd->nd_repstat = vfs_busy(mp, 0);
2325         vfs_rel(mp);
2326         if (nd->nd_repstat != 0) {
2327                 vrele(vp);
2328                 free(cookies, M_TEMP);
2329                 free(rbuf, M_TEMP);
2330                 if (nd->nd_flag & ND_NFSV3)
2331                         nfsrv_postopattr(nd, getret, &at);
2332                 goto out;
2333         }
2334
2335         /*
2336          * Check to see if entries in this directory can be safely acquired
2337          * via VFS_VGET() or if a switch to VOP_LOOKUP() is required.
2338          * ZFS snapshot directories need VOP_LOOKUP(), so that any
2339          * automount of the snapshot directory that is required will
2340          * be done.
2341          * This needs to be done here for NFSv4, since NFSv4 never does
2342          * a VFS_VGET() for "." or "..".
2343          */
2344         if (is_zfs == 1) {
2345                 r = VFS_VGET(mp, at.na_fileid, LK_SHARED, &nvp);
2346                 if (r == EOPNOTSUPP) {
2347                         usevget = 0;
2348                         cn.cn_nameiop = LOOKUP;
2349                         cn.cn_lkflags = LK_SHARED | LK_RETRY;
2350                         cn.cn_cred = nd->nd_cred;
2351                         cn.cn_thread = p;
2352                 } else if (r == 0)
2353                         vput(nvp);
2354         }
2355
2356         /*
2357          * Save this position, in case there is an error before one entry
2358          * is created.
2359          */
2360         mb0 = nd->nd_mb;
2361         bpos0 = nd->nd_bpos;
2362
2363         /*
2364          * Fill in the first part of the reply.
2365          * dirlen is the reply length in bytes and cannot exceed cnt.
2366          * (Include the two booleans at the end of the reply in dirlen now,
2367          *  so we recognize when we have exceeded cnt.)
2368          */
2369         if (nd->nd_flag & ND_NFSV3) {
2370                 dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
2371                 nfsrv_postopattr(nd, getret, &at);
2372         } else {
2373                 dirlen = NFSX_VERF + 2 * NFSX_UNSIGNED;
2374         }
2375         NFSM_BUILD(tl, u_int32_t *, NFSX_VERF);
2376         txdr_hyper(at.na_filerev, tl);
2377
2378         /*
2379          * Save this position, in case there is an empty reply needed.
2380          */
2381         mb1 = nd->nd_mb;
2382         bpos1 = nd->nd_bpos;
2383
2384         /* Loop through the records and build reply */
2385         entrycnt = 0;
2386         while (cpos < cend && ncookies > 0 && dirlen < cnt) {
2387                 nlen = dp->d_namlen;
2388                 if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
2389                     nlen <= NFS_MAXNAMLEN &&
2390                     ((nd->nd_flag & ND_NFSV3) || nlen > 2 ||
2391                      (nlen==2 && (dp->d_name[0]!='.' || dp->d_name[1]!='.'))
2392                       || (nlen == 1 && dp->d_name[0] != '.'))) {
2393                         /*
2394                          * Save the current position in the reply, in case
2395                          * this entry exceeds cnt.
2396                          */
2397                         mb1 = nd->nd_mb;
2398                         bpos1 = nd->nd_bpos;
2399         
2400                         /*
2401                          * For readdir_and_lookup get the vnode using
2402                          * the file number.
2403                          */
2404                         nvp = NULL;
2405                         refp = NULL;
2406                         r = 0;
2407                         at_root = 0;
2408                         needs_unbusy = 0;
2409                         new_mp = mp;
2410                         mounted_on_fileno = (uint64_t)dp->d_fileno;
2411                         if ((nd->nd_flag & ND_NFSV3) ||
2412                             NFSNONZERO_ATTRBIT(&savbits)) {
2413                                 if (nd->nd_flag & ND_NFSV4)
2414                                         refp = nfsv4root_getreferral(NULL,
2415                                             vp, dp->d_fileno);
2416                                 if (refp == NULL) {
2417                                         if (usevget)
2418                                                 r = VFS_VGET(mp, dp->d_fileno,
2419                                                     LK_SHARED, &nvp);
2420                                         else
2421                                                 r = EOPNOTSUPP;
2422                                         if (r == EOPNOTSUPP) {
2423                                                 if (usevget) {
2424                                                         usevget = 0;
2425                                                         cn.cn_nameiop = LOOKUP;
2426                                                         cn.cn_lkflags =
2427                                                             LK_SHARED |
2428                                                             LK_RETRY;
2429                                                         cn.cn_cred =
2430                                                             nd->nd_cred;
2431                                                         cn.cn_thread = p;
2432                                                 }
2433                                                 cn.cn_nameptr = dp->d_name;
2434                                                 cn.cn_namelen = nlen;
2435                                                 cn.cn_flags = ISLASTCN |
2436                                                     NOFOLLOW | LOCKLEAF;
2437                                                 if (nlen == 2 &&
2438                                                     dp->d_name[0] == '.' &&
2439                                                     dp->d_name[1] == '.')
2440                                                         cn.cn_flags |=
2441                                                             ISDOTDOT;
2442                                                 if (NFSVOPLOCK(vp, LK_SHARED)
2443                                                     != 0) {
2444                                                         nd->nd_repstat = EPERM;
2445                                                         break;
2446                                                 }
2447                                                 if ((vp->v_vflag & VV_ROOT) != 0
2448                                                     && (cn.cn_flags & ISDOTDOT)
2449                                                     != 0) {
2450                                                         vref(vp);
2451                                                         nvp = vp;
2452                                                         r = 0;
2453                                                 } else {
2454                                                         r = VOP_LOOKUP(vp, &nvp,
2455                                                             &cn);
2456                                                         if (vp != nvp)
2457                                                                 NFSVOPUNLOCK(vp);
2458                                                 }
2459                                         }
2460
2461                                         /*
2462                                          * For NFSv4, check to see if nvp is
2463                                          * a mount point and get the mount
2464                                          * point vnode, as required.
2465                                          */
2466                                         if (r == 0 &&
2467                                             nfsrv_enable_crossmntpt != 0 &&
2468                                             (nd->nd_flag & ND_NFSV4) != 0 &&
2469                                             nvp->v_type == VDIR &&
2470                                             nvp->v_mountedhere != NULL) {
2471                                                 new_mp = nvp->v_mountedhere;
2472                                                 r = vfs_busy(new_mp, 0);
2473                                                 vput(nvp);
2474                                                 nvp = NULL;
2475                                                 if (r == 0) {
2476                                                         r = VFS_ROOT(new_mp,
2477                                                             LK_SHARED, &nvp);
2478                                                         needs_unbusy = 1;
2479                                                         if (r == 0)
2480                                                                 at_root = 1;
2481                                                 }
2482                                         }
2483                                 }
2484
2485                                 /*
2486                                  * If we failed to look up the entry, then it
2487                                  * has become invalid, most likely removed.
2488                                  */
2489                                 if (r != 0) {
2490                                         if (needs_unbusy)
2491                                                 vfs_unbusy(new_mp);
2492                                         goto invalid;
2493                                 }
2494                                 KASSERT(refp != NULL || nvp != NULL,
2495                                     ("%s: undetected lookup error", __func__));
2496
2497                                 if (refp == NULL &&
2498                                     ((nd->nd_flag & ND_NFSV3) ||
2499                                      NFSNONZERO_ATTRBIT(&attrbits))) {
2500                                         r = nfsvno_getfh(nvp, &nfh, p);
2501                                         if (!r)
2502                                             r = nfsvno_getattr(nvp, nvap, nd, p,
2503                                                 1, &attrbits);
2504                                         if (r == 0 && is_zfs == 1 &&
2505                                             nfsrv_enable_crossmntpt != 0 &&
2506                                             (nd->nd_flag & ND_NFSV4) != 0 &&
2507                                             nvp->v_type == VDIR &&
2508                                             vp->v_mount != nvp->v_mount) {
2509                                             /*
2510                                              * For a ZFS snapshot, there is a
2511                                              * pseudo mount that does not set
2512                                              * v_mountedhere, so it needs to
2513                                              * be detected via a different
2514                                              * mount structure.
2515                                              */
2516                                             at_root = 1;
2517                                             if (new_mp == mp)
2518                                                 new_mp = nvp->v_mount;
2519                                         }
2520                                 }
2521
2522                                 /*
2523                                  * If we failed to get attributes of the entry,
2524                                  * then just skip it for NFSv3 (the traditional
2525                                  * behavior in the old NFS server).
2526                                  * For NFSv4 the behavior is controlled by
2527                                  * RDATTRERROR: we either ignore the error or
2528                                  * fail the request.
2529                                  * Note that RDATTRERROR is never set for NFSv3.
2530                                  */
2531                                 if (r != 0) {
2532                                         if (!NFSISSET_ATTRBIT(&attrbits,
2533                                             NFSATTRBIT_RDATTRERROR)) {
2534                                                 vput(nvp);
2535                                                 if (needs_unbusy != 0)
2536                                                         vfs_unbusy(new_mp);
2537                                                 if ((nd->nd_flag & ND_NFSV3))
2538                                                         goto invalid;
2539                                                 nd->nd_repstat = r;
2540                                                 break;
2541                                         }
2542                                 }
2543                         }
2544
2545                         /*
2546                          * Build the directory record xdr
2547                          */
2548                         if (nd->nd_flag & ND_NFSV3) {
2549                                 NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2550                                 *tl++ = newnfs_true;
2551                                 *tl++ = 0;
2552                                 *tl = txdr_unsigned(dp->d_fileno);
2553                                 dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2554                                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2555                                 *tl++ = 0;
2556                                 *tl = txdr_unsigned(*cookiep);
2557                                 nfsrv_postopattr(nd, 0, nvap);
2558                                 dirlen += nfsm_fhtom(nd,(u_int8_t *)&nfh,0,1);
2559                                 dirlen += (5*NFSX_UNSIGNED+NFSX_V3POSTOPATTR);
2560                                 if (nvp != NULL)
2561                                         vput(nvp);
2562                         } else {
2563                                 NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2564                                 *tl++ = newnfs_true;
2565                                 *tl++ = 0;
2566                                 *tl = txdr_unsigned(*cookiep);
2567                                 dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2568                                 if (nvp != NULL) {
2569                                         supports_nfsv4acls =
2570                                             nfs_supportsnfsv4acls(nvp);
2571                                         NFSVOPUNLOCK(nvp);
2572                                 } else
2573                                         supports_nfsv4acls = 0;
2574                                 if (refp != NULL) {
2575                                         dirlen += nfsrv_putreferralattr(nd,
2576                                             &savbits, refp, 0,
2577                                             &nd->nd_repstat);
2578                                         if (nd->nd_repstat) {
2579                                                 if (nvp != NULL)
2580                                                         vrele(nvp);
2581                                                 if (needs_unbusy != 0)
2582                                                         vfs_unbusy(new_mp);
2583                                                 break;
2584                                         }
2585                                 } else if (r) {
2586                                         dirlen += nfsvno_fillattr(nd, new_mp,
2587                                             nvp, nvap, &nfh, r, &rderrbits,
2588                                             nd->nd_cred, p, isdgram, 0,
2589                                             supports_nfsv4acls, at_root,
2590                                             mounted_on_fileno);
2591                                 } else {
2592                                         dirlen += nfsvno_fillattr(nd, new_mp,
2593                                             nvp, nvap, &nfh, r, &attrbits,
2594                                             nd->nd_cred, p, isdgram, 0,
2595                                             supports_nfsv4acls, at_root,
2596                                             mounted_on_fileno);
2597                                 }
2598                                 if (nvp != NULL)
2599                                         vrele(nvp);
2600                                 dirlen += (3 * NFSX_UNSIGNED);
2601                         }
2602                         if (needs_unbusy != 0)
2603                                 vfs_unbusy(new_mp);
2604                         if (dirlen <= cnt)
2605                                 entrycnt++;
2606                 }
2607 invalid:
2608                 cpos += dp->d_reclen;
2609                 dp = (struct dirent *)cpos;
2610                 cookiep++;
2611                 ncookies--;
2612         }
2613         vrele(vp);
2614         vfs_unbusy(mp);
2615
2616         /*
2617          * If dirlen > cnt, we must strip off the last entry. If that
2618          * results in an empty reply, report NFSERR_TOOSMALL.
2619          */
2620         if (dirlen > cnt || nd->nd_repstat) {
2621                 if (!nd->nd_repstat && entrycnt == 0)
2622                         nd->nd_repstat = NFSERR_TOOSMALL;
2623                 if (nd->nd_repstat) {
2624                         newnfs_trimtrailing(nd, mb0, bpos0);
2625                         if (nd->nd_flag & ND_NFSV3)
2626                                 nfsrv_postopattr(nd, getret, &at);
2627                 } else
2628                         newnfs_trimtrailing(nd, mb1, bpos1);
2629                 eofflag = 0;
2630         } else if (cpos < cend)
2631                 eofflag = 0;
2632         if (!nd->nd_repstat) {
2633                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2634                 *tl++ = newnfs_false;
2635                 if (eofflag)
2636                         *tl = newnfs_true;
2637                 else
2638                         *tl = newnfs_false;
2639         }
2640         free(cookies, M_TEMP);
2641         free(rbuf, M_TEMP);
2642
2643 out:
2644         NFSEXITCODE2(0, nd);
2645         return (0);
2646 nfsmout:
2647         vput(vp);
2648         NFSEXITCODE2(error, nd);
2649         return (error);
2650 }
2651
2652 /*
2653  * Get the settable attributes out of the mbuf list.
2654  * (Return 0 or EBADRPC)
2655  */
2656 int
2657 nfsrv_sattr(struct nfsrv_descript *nd, vnode_t vp, struct nfsvattr *nvap,
2658     nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2659 {
2660         u_int32_t *tl;
2661         struct nfsv2_sattr *sp;
2662         int error = 0, toclient = 0;
2663
2664         switch (nd->nd_flag & (ND_NFSV2 | ND_NFSV3 | ND_NFSV4)) {
2665         case ND_NFSV2:
2666                 NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
2667                 /*
2668                  * Some old clients didn't fill in the high order 16bits.
2669                  * --> check the low order 2 bytes for 0xffff
2670                  */
2671                 if ((fxdr_unsigned(int, sp->sa_mode) & 0xffff) != 0xffff)
2672                         nvap->na_mode = nfstov_mode(sp->sa_mode);
2673                 if (sp->sa_uid != newnfs_xdrneg1)
2674                         nvap->na_uid = fxdr_unsigned(uid_t, sp->sa_uid);
2675                 if (sp->sa_gid != newnfs_xdrneg1)
2676                         nvap->na_gid = fxdr_unsigned(gid_t, sp->sa_gid);
2677                 if (sp->sa_size != newnfs_xdrneg1)
2678                         nvap->na_size = fxdr_unsigned(u_quad_t, sp->sa_size);
2679                 if (sp->sa_atime.nfsv2_sec != newnfs_xdrneg1) {
2680 #ifdef notyet
2681                         fxdr_nfsv2time(&sp->sa_atime, &nvap->na_atime);
2682 #else
2683                         nvap->na_atime.tv_sec =
2684                                 fxdr_unsigned(u_int32_t,sp->sa_atime.nfsv2_sec);
2685                         nvap->na_atime.tv_nsec = 0;
2686 #endif
2687                 }
2688                 if (sp->sa_mtime.nfsv2_sec != newnfs_xdrneg1)
2689                         fxdr_nfsv2time(&sp->sa_mtime, &nvap->na_mtime);
2690                 break;
2691         case ND_NFSV3:
2692                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2693                 if (*tl == newnfs_true) {
2694                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2695                         nvap->na_mode = nfstov_mode(*tl);
2696                 }
2697                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2698                 if (*tl == newnfs_true) {
2699                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2700                         nvap->na_uid = fxdr_unsigned(uid_t, *tl);
2701                 }
2702                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2703                 if (*tl == newnfs_true) {
2704                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2705                         nvap->na_gid = fxdr_unsigned(gid_t, *tl);
2706                 }
2707                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2708                 if (*tl == newnfs_true) {
2709                         NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2710                         nvap->na_size = fxdr_hyper(tl);
2711                 }
2712                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2713                 switch (fxdr_unsigned(int, *tl)) {
2714                 case NFSV3SATTRTIME_TOCLIENT:
2715                         NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2716                         fxdr_nfsv3time(tl, &nvap->na_atime);
2717                         toclient = 1;
2718                         break;
2719                 case NFSV3SATTRTIME_TOSERVER:
2720                         vfs_timestamp(&nvap->na_atime);
2721                         nvap->na_vaflags |= VA_UTIMES_NULL;
2722                         break;
2723                 }
2724                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2725                 switch (fxdr_unsigned(int, *tl)) {
2726                 case NFSV3SATTRTIME_TOCLIENT:
2727                         NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2728                         fxdr_nfsv3time(tl, &nvap->na_mtime);
2729                         nvap->na_vaflags &= ~VA_UTIMES_NULL;
2730                         break;
2731                 case NFSV3SATTRTIME_TOSERVER:
2732                         vfs_timestamp(&nvap->na_mtime);
2733                         if (!toclient)
2734                                 nvap->na_vaflags |= VA_UTIMES_NULL;
2735                         break;
2736                 }
2737                 break;
2738         case ND_NFSV4:
2739                 error = nfsv4_sattr(nd, vp, nvap, attrbitp, aclp, p);
2740         }
2741 nfsmout:
2742         NFSEXITCODE2(error, nd);
2743         return (error);
2744 }
2745
2746 /*
2747  * Handle the setable attributes for V4.
2748  * Returns NFSERR_BADXDR if it can't be parsed, 0 otherwise.
2749  */
2750 int
2751 nfsv4_sattr(struct nfsrv_descript *nd, vnode_t vp, struct nfsvattr *nvap,
2752     nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2753 {
2754         u_int32_t *tl;
2755         int attrsum = 0;
2756         int i, j;
2757         int error, attrsize, bitpos, aclsize, aceerr, retnotsup = 0;
2758         int moderet, toclient = 0;
2759         u_char *cp, namestr[NFSV4_SMALLSTR + 1];
2760         uid_t uid;
2761         gid_t gid;
2762         u_short mode, mask;             /* Same type as va_mode. */
2763         struct vattr va;
2764
2765         error = nfsrv_getattrbits(nd, attrbitp, NULL, &retnotsup);
2766         if (error)
2767                 goto nfsmout;
2768         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2769         attrsize = fxdr_unsigned(int, *tl);
2770
2771         /*
2772          * Loop around getting the setable attributes. If an unsupported
2773          * one is found, set nd_repstat == NFSERR_ATTRNOTSUPP and return.
2774          */
2775         if (retnotsup) {
2776                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2777                 bitpos = NFSATTRBIT_MAX;
2778         } else {
2779                 bitpos = 0;
2780         }
2781         moderet = 0;
2782         for (; bitpos < NFSATTRBIT_MAX; bitpos++) {
2783             if (attrsum > attrsize) {
2784                 error = NFSERR_BADXDR;
2785                 goto nfsmout;
2786             }
2787             if (NFSISSET_ATTRBIT(attrbitp, bitpos))
2788                 switch (bitpos) {
2789                 case NFSATTRBIT_SIZE:
2790                         NFSM_DISSECT(tl, u_int32_t *, NFSX_HYPER);
2791                      if (vp != NULL && vp->v_type != VREG) {
2792                             error = (vp->v_type == VDIR) ? NFSERR_ISDIR :
2793                                 NFSERR_INVAL;
2794                             goto nfsmout;
2795                         }
2796                         nvap->na_size = fxdr_hyper(tl);
2797                         attrsum += NFSX_HYPER;
2798                         break;
2799                 case NFSATTRBIT_ACL:
2800                         error = nfsrv_dissectacl(nd, aclp, &aceerr, &aclsize,
2801                             p);
2802                         if (error)
2803                                 goto nfsmout;
2804                         if (aceerr && !nd->nd_repstat)
2805                                 nd->nd_repstat = aceerr;
2806                         attrsum += aclsize;
2807                         break;
2808                 case NFSATTRBIT_ARCHIVE:
2809                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2810                         if (!nd->nd_repstat)
2811                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2812                         attrsum += NFSX_UNSIGNED;
2813                         break;
2814                 case NFSATTRBIT_HIDDEN:
2815                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2816                         if (!nd->nd_repstat)
2817                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2818                         attrsum += NFSX_UNSIGNED;
2819                         break;
2820                 case NFSATTRBIT_MIMETYPE:
2821                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2822                         i = fxdr_unsigned(int, *tl);
2823                         error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
2824                         if (error)
2825                                 goto nfsmout;
2826                         if (!nd->nd_repstat)
2827                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2828                         attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(i));
2829                         break;
2830                 case NFSATTRBIT_MODE:
2831                         moderet = NFSERR_INVAL; /* Can't do MODESETMASKED. */
2832                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2833                         nvap->na_mode = nfstov_mode(*tl);
2834                         attrsum += NFSX_UNSIGNED;
2835                         break;
2836                 case NFSATTRBIT_OWNER:
2837                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2838                         j = fxdr_unsigned(int, *tl);
2839                         if (j < 0) {
2840                                 error = NFSERR_BADXDR;
2841                                 goto nfsmout;
2842                         }
2843                         if (j > NFSV4_SMALLSTR)
2844                                 cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2845                         else
2846                                 cp = namestr;
2847                         error = nfsrv_mtostr(nd, cp, j);
2848                         if (error) {
2849                                 if (j > NFSV4_SMALLSTR)
2850                                         free(cp, M_NFSSTRING);
2851                                 goto nfsmout;
2852                         }
2853                         if (!nd->nd_repstat) {
2854                                 nd->nd_repstat = nfsv4_strtouid(nd, cp, j,
2855                                     &uid);
2856                                 if (!nd->nd_repstat)
2857                                         nvap->na_uid = uid;
2858                         }
2859                         if (j > NFSV4_SMALLSTR)
2860                                 free(cp, M_NFSSTRING);
2861                         attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2862                         break;
2863                 case NFSATTRBIT_OWNERGROUP:
2864                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2865                         j = fxdr_unsigned(int, *tl);
2866                         if (j < 0) {
2867                                 error = NFSERR_BADXDR;
2868                                 goto nfsmout;
2869                         }
2870                         if (j > NFSV4_SMALLSTR)
2871                                 cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2872                         else
2873                                 cp = namestr;
2874                         error = nfsrv_mtostr(nd, cp, j);
2875                         if (error) {
2876                                 if (j > NFSV4_SMALLSTR)
2877                                         free(cp, M_NFSSTRING);
2878                                 goto nfsmout;
2879                         }
2880                         if (!nd->nd_repstat) {
2881                                 nd->nd_repstat = nfsv4_strtogid(nd, cp, j,
2882                                     &gid);
2883                                 if (!nd->nd_repstat)
2884                                         nvap->na_gid = gid;
2885                         }
2886                         if (j > NFSV4_SMALLSTR)
2887                                 free(cp, M_NFSSTRING);
2888                         attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2889                         break;
2890                 case NFSATTRBIT_SYSTEM:
2891                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2892                         if (!nd->nd_repstat)
2893                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2894                         attrsum += NFSX_UNSIGNED;
2895                         break;
2896                 case NFSATTRBIT_TIMEACCESSSET:
2897                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2898                         attrsum += NFSX_UNSIGNED;
2899                         if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2900                             NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2901                             fxdr_nfsv4time(tl, &nvap->na_atime);
2902                             toclient = 1;
2903                             attrsum += NFSX_V4TIME;
2904                         } else {
2905                             vfs_timestamp(&nvap->na_atime);
2906                             nvap->na_vaflags |= VA_UTIMES_NULL;
2907                         }
2908                         break;
2909                 case NFSATTRBIT_TIMEBACKUP:
2910                         NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2911                         if (!nd->nd_repstat)
2912                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2913                         attrsum += NFSX_V4TIME;
2914                         break;
2915                 case NFSATTRBIT_TIMECREATE:
2916                         NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2917                         if (!nd->nd_repstat)
2918                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2919                         attrsum += NFSX_V4TIME;
2920                         break;
2921                 case NFSATTRBIT_TIMEMODIFYSET:
2922                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2923                         attrsum += NFSX_UNSIGNED;
2924                         if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2925                             NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2926                             fxdr_nfsv4time(tl, &nvap->na_mtime);
2927                             nvap->na_vaflags &= ~VA_UTIMES_NULL;
2928                             attrsum += NFSX_V4TIME;
2929                         } else {
2930                             vfs_timestamp(&nvap->na_mtime);
2931                             if (!toclient)
2932                                 nvap->na_vaflags |= VA_UTIMES_NULL;
2933                         }
2934                         break;
2935                 case NFSATTRBIT_MODESETMASKED:
2936                         NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
2937                         mode = fxdr_unsigned(u_short, *tl++);
2938                         mask = fxdr_unsigned(u_short, *tl);
2939                         /*
2940                          * vp == NULL implies an Open/Create operation.
2941                          * This attribute can only be used for Setattr and
2942                          * only for NFSv4.1 or higher.
2943                          * If moderet != 0, a mode attribute has also been
2944                          * specified and this attribute cannot be done in the
2945                          * same Setattr operation.
2946                          */
2947                         if ((nd->nd_flag & ND_NFSV41) == 0)
2948                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2949                         else if ((mode & ~07777) != 0 || (mask & ~07777) != 0 ||
2950                             vp == NULL)
2951                                 nd->nd_repstat = NFSERR_INVAL;
2952                         else if (moderet == 0)
2953                                 moderet = VOP_GETATTR(vp, &va, nd->nd_cred);
2954                         if (moderet == 0)
2955                                 nvap->na_mode = (mode & mask) |
2956                                     (va.va_mode & ~mask);
2957                         else
2958                                 nd->nd_repstat = moderet;
2959                         attrsum += 2 * NFSX_UNSIGNED;
2960                         break;
2961                 default:
2962                         nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2963                         /*
2964                          * set bitpos so we drop out of the loop.
2965                          */
2966                         bitpos = NFSATTRBIT_MAX;
2967                         break;
2968                 }
2969         }
2970
2971         /*
2972          * some clients pad the attrlist, so we need to skip over the
2973          * padding.
2974          */
2975         if (attrsum > attrsize) {
2976                 error = NFSERR_BADXDR;
2977         } else {
2978                 attrsize = NFSM_RNDUP(attrsize);
2979                 if (attrsum < attrsize)
2980                         error = nfsm_advance(nd, attrsize - attrsum, -1);
2981         }
2982 nfsmout:
2983         NFSEXITCODE2(error, nd);
2984         return (error);
2985 }
2986
2987 /*
2988  * Check/setup export credentials.
2989  */
2990 int
2991 nfsd_excred(struct nfsrv_descript *nd, struct nfsexstuff *exp,
2992     struct ucred *credanon)
2993 {
2994         int error = 0;
2995
2996         /*
2997          * Check/setup credentials.
2998          */
2999         if (nd->nd_flag & ND_GSS)
3000                 exp->nes_exflag &= ~MNT_EXPORTANON;
3001
3002         /*
3003          * Check to see if the operation is allowed for this security flavor.
3004          * RFC2623 suggests that the NFSv3 Fsinfo RPC be allowed to
3005          * AUTH_NONE or AUTH_SYS for file systems requiring RPCSEC_GSS.
3006          * Also, allow Secinfo, so that it can acquire the correct flavor(s).
3007          */
3008         if (nfsvno_testexp(nd, exp) &&
3009             nd->nd_procnum != NFSV4OP_SECINFO &&
3010             nd->nd_procnum != NFSPROC_FSINFO) {
3011                 if (nd->nd_flag & ND_NFSV4)
3012                         error = NFSERR_WRONGSEC;
3013                 else
3014                         error = (NFSERR_AUTHERR | AUTH_TOOWEAK);
3015                 goto out;
3016         }
3017
3018         /*
3019          * Check to see if the file system is exported V4 only.
3020          */
3021         if (NFSVNO_EXV4ONLY(exp) && !(nd->nd_flag & ND_NFSV4)) {
3022                 error = NFSERR_PROGNOTV4;
3023                 goto out;
3024         }
3025
3026         /*
3027          * Now, map the user credentials.
3028          * (Note that ND_AUTHNONE will only be set for an NFSv3
3029          *  Fsinfo RPC. If set for anything else, this code might need
3030          *  to change.)
3031          */
3032         if (NFSVNO_EXPORTED(exp)) {
3033                 if (((nd->nd_flag & ND_GSS) == 0 && nd->nd_cred->cr_uid == 0) ||
3034                      NFSVNO_EXPORTANON(exp) ||
3035                      (nd->nd_flag & ND_AUTHNONE) != 0) {
3036                         nd->nd_cred->cr_uid = credanon->cr_uid;
3037                         nd->nd_cred->cr_gid = credanon->cr_gid;
3038                         crsetgroups(nd->nd_cred, credanon->cr_ngroups,
3039                             credanon->cr_groups);
3040                 } else if ((nd->nd_flag & ND_GSS) == 0) {
3041                         /*
3042                          * If using AUTH_SYS, call nfsrv_getgrpscred() to see
3043                          * if there is a replacement credential with a group
3044                          * list set up by "nfsuserd -manage-gids".
3045                          * If there is no replacement, nfsrv_getgrpscred()
3046                          * simply returns its argument.
3047                          */
3048                         nd->nd_cred = nfsrv_getgrpscred(nd->nd_cred);
3049                 }
3050         }
3051
3052 out:
3053         NFSEXITCODE2(error, nd);
3054         return (error);
3055 }
3056
3057 /*
3058  * Check exports.
3059  */
3060 int
3061 nfsvno_checkexp(struct mount *mp, struct sockaddr *nam, struct nfsexstuff *exp,
3062     struct ucred **credp)
3063 {
3064         int error;
3065
3066         error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
3067             &exp->nes_numsecflavor, exp->nes_secflavors);
3068         if (error) {
3069                 if (nfs_rootfhset) {
3070                         exp->nes_exflag = 0;
3071                         exp->nes_numsecflavor = 0;
3072                         error = 0;
3073                 }
3074         } else if (exp->nes_numsecflavor < 1 || exp->nes_numsecflavor >
3075             MAXSECFLAVORS) {
3076                 printf("nfsvno_checkexp: numsecflavors out of range\n");
3077                 exp->nes_numsecflavor = 0;
3078                 error = EACCES;
3079         }
3080         NFSEXITCODE(error);
3081         return (error);
3082 }
3083
3084 /*
3085  * Get a vnode for a file handle and export stuff.
3086  */
3087 int
3088 nfsvno_fhtovp(struct mount *mp, fhandle_t *fhp, struct sockaddr *nam,
3089     int lktype, struct vnode **vpp, struct nfsexstuff *exp,
3090     struct ucred **credp)
3091 {
3092         int error;
3093
3094         *credp = NULL;
3095         exp->nes_numsecflavor = 0;
3096         error = VFS_FHTOVP(mp, &fhp->fh_fid, lktype, vpp);
3097         if (error != 0)
3098                 /* Make sure the server replies ESTALE to the client. */
3099                 error = ESTALE;
3100         if (nam && !error) {
3101                 error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
3102                     &exp->nes_numsecflavor, exp->nes_secflavors);
3103                 if (error) {
3104                         if (nfs_rootfhset) {
3105                                 exp->nes_exflag = 0;
3106                                 exp->nes_numsecflavor = 0;
3107                                 error = 0;
3108                         } else {
3109                                 vput(*vpp);
3110                         }
3111                 } else if (exp->nes_numsecflavor < 1 || exp->nes_numsecflavor >
3112                     MAXSECFLAVORS) {
3113                         printf("nfsvno_fhtovp: numsecflavors out of range\n");
3114                         exp->nes_numsecflavor = 0;
3115                         error = EACCES;
3116                         vput(*vpp);
3117                 }
3118         }
3119         NFSEXITCODE(error);
3120         return (error);
3121 }
3122
3123 /*
3124  * nfsd_fhtovp() - convert a fh to a vnode ptr
3125  *      - look up fsid in mount list (if not found ret error)
3126  *      - get vp and export rights by calling nfsvno_fhtovp()
3127  *      - if cred->cr_uid == 0 or MNT_EXPORTANON set it to credanon
3128  *        for AUTH_SYS
3129  *      - if mpp != NULL, return the mount point so that it can
3130  *        be used for vn_finished_write() by the caller
3131  */
3132 void
3133 nfsd_fhtovp(struct nfsrv_descript *nd, struct nfsrvfh *nfp, int lktype,
3134     struct vnode **vpp, struct nfsexstuff *exp,
3135     struct mount **mpp, int startwrite)
3136 {
3137         struct mount *mp;
3138         struct ucred *credanon;
3139         fhandle_t *fhp;
3140
3141         fhp = (fhandle_t *)nfp->nfsrvfh_data;
3142         /*
3143          * Check for the special case of the nfsv4root_fh.
3144          */
3145         mp = vfs_busyfs(&fhp->fh_fsid);
3146         if (mpp != NULL)
3147                 *mpp = mp;
3148         if (mp == NULL) {
3149                 *vpp = NULL;
3150                 nd->nd_repstat = ESTALE;
3151                 goto out;
3152         }
3153
3154         if (startwrite) {
3155                 vn_start_write(NULL, mpp, V_WAIT);
3156                 if (lktype == LK_SHARED && !(MNT_SHARED_WRITES(mp)))
3157                         lktype = LK_EXCLUSIVE;
3158         }
3159         nd->nd_repstat = nfsvno_fhtovp(mp, fhp, nd->nd_nam, lktype, vpp, exp,
3160             &credanon);
3161         vfs_unbusy(mp);
3162
3163         /*
3164          * For NFSv4 without a pseudo root fs, unexported file handles
3165          * can be returned, so that Lookup works everywhere.
3166          */
3167         if (!nd->nd_repstat && exp->nes_exflag == 0 &&
3168             !(nd->nd_flag & ND_NFSV4)) {
3169                 vput(*vpp);
3170                 nd->nd_repstat = EACCES;
3171         }
3172
3173         /*
3174          * Personally, I've never seen any point in requiring a
3175          * reserved port#, since only in the rare case where the
3176          * clients are all boxes with secure system privileges,
3177          * does it provide any enhanced security, but... some people
3178          * believe it to be useful and keep putting this code back in.
3179          * (There is also some "security checker" out there that
3180          *  complains if the nfs server doesn't enforce this.)
3181          * However, note the following:
3182          * RFC3530 (NFSv4) specifies that a reserved port# not be
3183          *      required.
3184          * RFC2623 recommends that, if a reserved port# is checked for,
3185          *      that there be a way to turn that off--> ifdef'd.
3186          */
3187 #ifdef NFS_REQRSVPORT
3188         if (!nd->nd_repstat) {
3189                 struct sockaddr_in *saddr;
3190                 struct sockaddr_in6 *saddr6;
3191
3192                 saddr = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in *);
3193                 saddr6 = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in6 *);
3194                 if (!(nd->nd_flag & ND_NFSV4) &&
3195                     ((saddr->sin_family == AF_INET &&
3196                       ntohs(saddr->sin_port) >= IPPORT_RESERVED) ||
3197                      (saddr6->sin6_family == AF_INET6 &&
3198                       ntohs(saddr6->sin6_port) >= IPPORT_RESERVED))) {
3199                         vput(*vpp);
3200                         nd->nd_repstat = (NFSERR_AUTHERR | AUTH_TOOWEAK);
3201                 }
3202         }
3203 #endif  /* NFS_REQRSVPORT */
3204
3205         /*
3206          * Check/setup credentials.
3207          */
3208         if (!nd->nd_repstat) {
3209                 nd->nd_saveduid = nd->nd_cred->cr_uid;
3210                 nd->nd_repstat = nfsd_excred(nd, exp, credanon);
3211                 if (nd->nd_repstat)
3212                         vput(*vpp);
3213         }
3214         if (credanon != NULL)
3215                 crfree(credanon);
3216         if (nd->nd_repstat) {
3217                 if (startwrite)
3218                         vn_finished_write(mp);
3219                 *vpp = NULL;
3220                 if (mpp != NULL)
3221                         *mpp = NULL;
3222         }
3223
3224 out:
3225         NFSEXITCODE2(0, nd);
3226 }
3227
3228 /*
3229  * glue for fp.
3230  */
3231 static int
3232 fp_getfvp(struct thread *p, int fd, struct file **fpp, struct vnode **vpp)
3233 {
3234         struct filedesc *fdp;
3235         struct file *fp;
3236         int error = 0;
3237
3238         fdp = p->td_proc->p_fd;
3239         if (fd < 0 || fd >= fdp->fd_nfiles ||
3240             (fp = fdp->fd_ofiles[fd].fde_file) == NULL) {
3241                 error = EBADF;
3242                 goto out;
3243         }
3244         *fpp = fp;
3245
3246 out:
3247         NFSEXITCODE(error);
3248         return (error);
3249 }
3250
3251 /*
3252  * Called from nfssvc() to update the exports list. Just call
3253  * vfs_export(). This has to be done, since the v4 root fake fs isn't
3254  * in the mount list.
3255  */
3256 int
3257 nfsrv_v4rootexport(void *argp, struct ucred *cred, struct thread *p)
3258 {
3259         struct nfsex_args *nfsexargp = (struct nfsex_args *)argp;
3260         int error = 0;
3261         struct nameidata nd;
3262         fhandle_t fh;
3263
3264         error = vfs_export(&nfsv4root_mnt, &nfsexargp->export);
3265         if ((nfsexargp->export.ex_flags & MNT_DELEXPORT) != 0)
3266                 nfs_rootfhset = 0;
3267         else if (error == 0) {
3268                 if (nfsexargp->fspec == NULL) {
3269                         error = EPERM;
3270                         goto out;
3271                 }
3272                 /*
3273                  * If fspec != NULL, this is the v4root path.
3274                  */
3275                 NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE,
3276                     nfsexargp->fspec, p);
3277                 if ((error = namei(&nd)) != 0)
3278                         goto out;
3279                 error = nfsvno_getfh(nd.ni_vp, &fh, p);
3280                 vrele(nd.ni_vp);
3281                 if (!error) {
3282                         nfs_rootfh.nfsrvfh_len = NFSX_MYFH;
3283                         NFSBCOPY((caddr_t)&fh,
3284                             nfs_rootfh.nfsrvfh_data,
3285                             sizeof (fhandle_t));
3286                         nfs_rootfhset = 1;
3287                 }
3288         }
3289
3290 out:
3291         NFSEXITCODE(error);
3292         return (error);
3293 }
3294
3295 /*
3296  * This function needs to test to see if the system is near its limit
3297  * for memory allocation via malloc() or mget() and return True iff
3298  * either of these resources are near their limit.
3299  * XXX (For now, this is just a stub.)
3300  */
3301 int nfsrv_testmalloclimit = 0;
3302 int
3303 nfsrv_mallocmget_limit(void)
3304 {
3305         static int printmesg = 0;
3306         static int testval = 1;
3307
3308         if (nfsrv_testmalloclimit && (testval++ % 1000) == 0) {
3309                 if ((printmesg++ % 100) == 0)
3310                         printf("nfsd: malloc/mget near limit\n");
3311                 return (1);
3312         }
3313         return (0);
3314 }
3315
3316 /*
3317  * BSD specific initialization of a mount point.
3318  */
3319 void
3320 nfsd_mntinit(void)
3321 {
3322         static int inited = 0;
3323
3324         if (inited)
3325                 return;
3326         inited = 1;
3327         nfsv4root_mnt.mnt_flag = (MNT_RDONLY | MNT_EXPORTED);
3328         TAILQ_INIT(&nfsv4root_mnt.mnt_nvnodelist);
3329         TAILQ_INIT(&nfsv4root_mnt.mnt_lazyvnodelist);
3330         nfsv4root_mnt.mnt_export = NULL;
3331         TAILQ_INIT(&nfsv4root_opt);
3332         TAILQ_INIT(&nfsv4root_newopt);
3333         nfsv4root_mnt.mnt_opt = &nfsv4root_opt;
3334         nfsv4root_mnt.mnt_optnew = &nfsv4root_newopt;
3335         nfsv4root_mnt.mnt_nvnodelistsize = 0;
3336         nfsv4root_mnt.mnt_lazyvnodelistsize = 0;
3337 }
3338
3339 /*
3340  * Get a vnode for a file handle, without checking exports, etc.
3341  */
3342 struct vnode *
3343 nfsvno_getvp(fhandle_t *fhp)
3344 {
3345         struct mount *mp;
3346         struct vnode *vp;
3347         int error;
3348
3349         mp = vfs_busyfs(&fhp->fh_fsid);
3350         if (mp == NULL)
3351                 return (NULL);
3352         error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, &vp);
3353         vfs_unbusy(mp);
3354         if (error)
3355                 return (NULL);
3356         return (vp);
3357 }
3358
3359 /*
3360  * Do a local VOP_ADVLOCK().
3361  */
3362 int
3363 nfsvno_advlock(struct vnode *vp, int ftype, u_int64_t first,
3364     u_int64_t end, struct thread *td)
3365 {
3366         int error = 0;
3367         struct flock fl;
3368         u_int64_t tlen;
3369
3370         if (nfsrv_dolocallocks == 0)
3371                 goto out;
3372         ASSERT_VOP_UNLOCKED(vp, "nfsvno_advlock: vp locked");
3373
3374         fl.l_whence = SEEK_SET;
3375         fl.l_type = ftype;
3376         fl.l_start = (off_t)first;
3377         if (end == NFS64BITSSET) {
3378                 fl.l_len = 0;
3379         } else {
3380                 tlen = end - first;
3381                 fl.l_len = (off_t)tlen;
3382         }
3383         /*
3384          * For FreeBSD8, the l_pid and l_sysid must be set to the same
3385          * values for all calls, so that all locks will be held by the
3386          * nfsd server. (The nfsd server handles conflicts between the
3387          * various clients.)
3388          * Since an NFSv4 lockowner is a ClientID plus an array of up to 1024
3389          * bytes, so it can't be put in l_sysid.
3390          */
3391         if (nfsv4_sysid == 0)
3392                 nfsv4_sysid = nlm_acquire_next_sysid();
3393         fl.l_pid = (pid_t)0;
3394         fl.l_sysid = (int)nfsv4_sysid;
3395
3396         if (ftype == F_UNLCK)
3397                 error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_UNLCK, &fl,
3398                     (F_POSIX | F_REMOTE));
3399         else
3400                 error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_SETLK, &fl,
3401                     (F_POSIX | F_REMOTE));
3402
3403 out:
3404         NFSEXITCODE(error);
3405         return (error);
3406 }
3407
3408 /*
3409  * Check the nfsv4 root exports.
3410  */
3411 int
3412 nfsvno_v4rootexport(struct nfsrv_descript *nd)
3413 {
3414         struct ucred *credanon;
3415         int error = 0, numsecflavor, secflavors[MAXSECFLAVORS], i;
3416         uint64_t exflags;
3417
3418         error = vfs_stdcheckexp(&nfsv4root_mnt, nd->nd_nam, &exflags,
3419             &credanon, &numsecflavor, secflavors);
3420         if (error) {
3421                 error = NFSERR_PROGUNAVAIL;
3422                 goto out;
3423         }
3424         if (credanon != NULL)
3425                 crfree(credanon);
3426         for (i = 0; i < numsecflavor; i++) {
3427                 if (secflavors[i] == AUTH_SYS)
3428                         nd->nd_flag |= ND_EXAUTHSYS;
3429                 else if (secflavors[i] == RPCSEC_GSS_KRB5)
3430                         nd->nd_flag |= ND_EXGSS;
3431                 else if (secflavors[i] == RPCSEC_GSS_KRB5I)
3432                         nd->nd_flag |= ND_EXGSSINTEGRITY;
3433                 else if (secflavors[i] == RPCSEC_GSS_KRB5P)
3434                         nd->nd_flag |= ND_EXGSSPRIVACY;
3435         }
3436
3437 out:
3438         NFSEXITCODE(error);
3439         return (error);
3440 }
3441
3442 /*
3443  * Nfs server pseudo system call for the nfsd's
3444  */
3445 /*
3446  * MPSAFE
3447  */
3448 static int
3449 nfssvc_nfsd(struct thread *td, struct nfssvc_args *uap)
3450 {
3451         struct file *fp;
3452         struct nfsd_addsock_args sockarg;
3453         struct nfsd_nfsd_args nfsdarg;
3454         struct nfsd_nfsd_oargs onfsdarg;
3455         struct nfsd_pnfsd_args pnfsdarg;
3456         struct vnode *vp, *nvp, *curdvp;
3457         struct pnfsdsfile *pf;
3458         struct nfsdevice *ds, *fds;
3459         cap_rights_t rights;
3460         int buflen, error, ret;
3461         char *buf, *cp, *cp2, *cp3;
3462         char fname[PNFS_FILENAME_LEN + 1];
3463
3464         if (uap->flag & NFSSVC_NFSDADDSOCK) {
3465                 error = copyin(uap->argp, (caddr_t)&sockarg, sizeof (sockarg));
3466                 if (error)
3467                         goto out;
3468                 /*
3469                  * Since we don't know what rights might be required,
3470                  * pretend that we need them all. It is better to be too
3471                  * careful than too reckless.
3472                  */
3473                 error = fget(td, sockarg.sock,
3474                     cap_rights_init(&rights, CAP_SOCK_SERVER), &fp);
3475                 if (error != 0)
3476                         goto out;
3477                 if (fp->f_type != DTYPE_SOCKET) {
3478                         fdrop(fp, td);
3479                         error = EPERM;
3480                         goto out;
3481                 }
3482                 error = nfsrvd_addsock(fp);
3483                 fdrop(fp, td);
3484         } else if (uap->flag & NFSSVC_NFSDNFSD) {
3485                 if (uap->argp == NULL) {
3486                         error = EINVAL;
3487                         goto out;
3488                 }
3489                 if ((uap->flag & NFSSVC_NEWSTRUCT) == 0) {
3490                         error = copyin(uap->argp, &onfsdarg, sizeof(onfsdarg));
3491                         if (error == 0) {
3492                                 nfsdarg.principal = onfsdarg.principal;
3493                                 nfsdarg.minthreads = onfsdarg.minthreads;
3494                                 nfsdarg.maxthreads = onfsdarg.maxthreads;
3495                                 nfsdarg.version = 1;
3496                                 nfsdarg.addr = NULL;
3497                                 nfsdarg.addrlen = 0;
3498                                 nfsdarg.dnshost = NULL;
3499                                 nfsdarg.dnshostlen = 0;
3500                                 nfsdarg.dspath = NULL;
3501                                 nfsdarg.dspathlen = 0;
3502                                 nfsdarg.mdspath = NULL;
3503                                 nfsdarg.mdspathlen = 0;
3504                                 nfsdarg.mirrorcnt = 1;
3505                         }
3506                 } else
3507                         error = copyin(uap->argp, &nfsdarg, sizeof(nfsdarg));
3508                 if (error)
3509                         goto out;
3510                 if (nfsdarg.addrlen > 0 && nfsdarg.addrlen < 10000 &&
3511                     nfsdarg.dnshostlen > 0 && nfsdarg.dnshostlen < 10000 &&
3512                     nfsdarg.dspathlen > 0 && nfsdarg.dspathlen < 10000 &&
3513                     nfsdarg.mdspathlen > 0 && nfsdarg.mdspathlen < 10000 &&
3514                     nfsdarg.mirrorcnt >= 1 &&
3515                     nfsdarg.mirrorcnt <= NFSDEV_MAXMIRRORS &&
3516                     nfsdarg.addr != NULL && nfsdarg.dnshost != NULL &&
3517                     nfsdarg.dspath != NULL && nfsdarg.mdspath != NULL) {
3518                         NFSD_DEBUG(1, "addrlen=%d dspathlen=%d dnslen=%d"
3519                             " mdspathlen=%d mirrorcnt=%d\n", nfsdarg.addrlen,
3520                             nfsdarg.dspathlen, nfsdarg.dnshostlen,
3521                             nfsdarg.mdspathlen, nfsdarg.mirrorcnt);
3522                         cp = malloc(nfsdarg.addrlen + 1, M_TEMP, M_WAITOK);
3523                         error = copyin(nfsdarg.addr, cp, nfsdarg.addrlen);
3524                         if (error != 0) {
3525                                 free(cp, M_TEMP);
3526                                 goto out;
3527                         }
3528                         cp[nfsdarg.addrlen] = '\0';     /* Ensure nul term. */
3529                         nfsdarg.addr = cp;
3530                         cp = malloc(nfsdarg.dnshostlen + 1, M_TEMP, M_WAITOK);
3531                         error = copyin(nfsdarg.dnshost, cp, nfsdarg.dnshostlen);
3532                         if (error != 0) {
3533                                 free(nfsdarg.addr, M_TEMP);
3534                                 free(cp, M_TEMP);
3535                                 goto out;
3536                         }
3537                         cp[nfsdarg.dnshostlen] = '\0';  /* Ensure nul term. */
3538                         nfsdarg.dnshost = cp;
3539                         cp = malloc(nfsdarg.dspathlen + 1, M_TEMP, M_WAITOK);
3540                         error = copyin(nfsdarg.dspath, cp, nfsdarg.dspathlen);
3541                         if (error != 0) {
3542                                 free(nfsdarg.addr, M_TEMP);
3543                                 free(nfsdarg.dnshost, M_TEMP);
3544                                 free(cp, M_TEMP);
3545                                 goto out;
3546                         }
3547                         cp[nfsdarg.dspathlen] = '\0';   /* Ensure nul term. */
3548                         nfsdarg.dspath = cp;
3549                         cp = malloc(nfsdarg.mdspathlen + 1, M_TEMP, M_WAITOK);
3550                         error = copyin(nfsdarg.mdspath, cp, nfsdarg.mdspathlen);
3551                         if (error != 0) {
3552                                 free(nfsdarg.addr, M_TEMP);
3553                                 free(nfsdarg.dnshost, M_TEMP);
3554                                 free(nfsdarg.dspath, M_TEMP);
3555                                 free(cp, M_TEMP);
3556                                 goto out;
3557                         }
3558                         cp[nfsdarg.mdspathlen] = '\0';  /* Ensure nul term. */
3559                         nfsdarg.mdspath = cp;
3560                 } else {
3561                         nfsdarg.addr = NULL;
3562                         nfsdarg.addrlen = 0;
3563                         nfsdarg.dnshost = NULL;
3564                         nfsdarg.dnshostlen = 0;
3565                         nfsdarg.dspath = NULL;
3566                         nfsdarg.dspathlen = 0;
3567                         nfsdarg.mdspath = NULL;
3568                         nfsdarg.mdspathlen = 0;
3569                         nfsdarg.mirrorcnt = 1;
3570                 }
3571                 error = nfsrvd_nfsd(td, &nfsdarg);
3572                 free(nfsdarg.addr, M_TEMP);
3573                 free(nfsdarg.dnshost, M_TEMP);
3574                 free(nfsdarg.dspath, M_TEMP);
3575                 free(nfsdarg.mdspath, M_TEMP);
3576         } else if (uap->flag & NFSSVC_PNFSDS) {
3577                 error = copyin(uap->argp, &pnfsdarg, sizeof(pnfsdarg));
3578                 if (error == 0 && (pnfsdarg.op == PNFSDOP_DELDSSERVER ||
3579                     pnfsdarg.op == PNFSDOP_FORCEDELDS)) {
3580                         cp = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3581                         error = copyinstr(pnfsdarg.dspath, cp, PATH_MAX + 1,
3582                             NULL);
3583                         if (error == 0)
3584                                 error = nfsrv_deldsserver(pnfsdarg.op, cp, td);
3585                         free(cp, M_TEMP);
3586                 } else if (error == 0 && pnfsdarg.op == PNFSDOP_COPYMR) {
3587                         cp = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3588                         buflen = sizeof(*pf) * NFSDEV_MAXMIRRORS;
3589                         buf = malloc(buflen, M_TEMP, M_WAITOK);
3590                         error = copyinstr(pnfsdarg.mdspath, cp, PATH_MAX + 1,
3591                             NULL);
3592                         NFSD_DEBUG(4, "pnfsdcopymr cp mdspath=%d\n", error);
3593                         if (error == 0 && pnfsdarg.dspath != NULL) {
3594                                 cp2 = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3595                                 error = copyinstr(pnfsdarg.dspath, cp2,
3596                                     PATH_MAX + 1, NULL);
3597                                 NFSD_DEBUG(4, "pnfsdcopymr cp dspath=%d\n",
3598                                     error);
3599                         } else
3600                                 cp2 = NULL;
3601                         if (error == 0 && pnfsdarg.curdspath != NULL) {
3602                                 cp3 = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3603                                 error = copyinstr(pnfsdarg.curdspath, cp3,
3604                                     PATH_MAX + 1, NULL);
3605                                 NFSD_DEBUG(4, "pnfsdcopymr cp curdspath=%d\n",
3606                                     error);
3607                         } else
3608                                 cp3 = NULL;
3609                         curdvp = NULL;
3610                         fds = NULL;
3611                         if (error == 0)
3612                                 error = nfsrv_mdscopymr(cp, cp2, cp3, buf,
3613                                     &buflen, fname, td, &vp, &nvp, &pf, &ds,
3614                                     &fds);
3615                         NFSD_DEBUG(4, "nfsrv_mdscopymr=%d\n", error);
3616                         if (error == 0) {
3617                                 if (pf->dsf_dir >= nfsrv_dsdirsize) {
3618                                         printf("copymr: dsdir out of range\n");
3619                                         pf->dsf_dir = 0;
3620                                 }
3621                                 NFSD_DEBUG(4, "copymr: buflen=%d\n", buflen);
3622                                 error = nfsrv_copymr(vp, nvp,
3623                                     ds->nfsdev_dsdir[pf->dsf_dir], ds, pf,
3624                                     (struct pnfsdsfile *)buf,
3625                                     buflen / sizeof(*pf), td->td_ucred, td);
3626                                 vput(vp);
3627                                 vput(nvp);
3628                                 if (fds != NULL && error == 0) {
3629                                         curdvp = fds->nfsdev_dsdir[pf->dsf_dir];
3630                                         ret = vn_lock(curdvp, LK_EXCLUSIVE);
3631                                         if (ret == 0) {
3632                                                 nfsrv_dsremove(curdvp, fname,
3633                                                     td->td_ucred, td);
3634                                                 NFSVOPUNLOCK(curdvp);
3635                                         }
3636                                 }
3637                                 NFSD_DEBUG(4, "nfsrv_copymr=%d\n", error);
3638                         }
3639                         free(cp, M_TEMP);
3640                         free(cp2, M_TEMP);
3641                         free(cp3, M_TEMP);
3642                         free(buf, M_TEMP);
3643                 }
3644         } else {
3645                 error = nfssvc_srvcall(td, uap, td->td_ucred);
3646         }
3647
3648 out:
3649         NFSEXITCODE(error);
3650         return (error);
3651 }
3652
3653 static int
3654 nfssvc_srvcall(struct thread *p, struct nfssvc_args *uap, struct ucred *cred)
3655 {
3656         struct nfsex_args export;
3657         struct nfsex_oldargs oexp;
3658         struct file *fp = NULL;
3659         int stablefd, i, len;
3660         struct nfsd_clid adminrevoke;
3661         struct nfsd_dumplist dumplist;
3662         struct nfsd_dumpclients *dumpclients;
3663         struct nfsd_dumplocklist dumplocklist;
3664         struct nfsd_dumplocks *dumplocks;
3665         struct nameidata nd;
3666         vnode_t vp;
3667         int error = EINVAL, igotlock;
3668         struct proc *procp;
3669         gid_t *grps;
3670         static int suspend_nfsd = 0;
3671
3672         if (uap->flag & NFSSVC_PUBLICFH) {
3673                 NFSBZERO((caddr_t)&nfs_pubfh.nfsrvfh_data,
3674                     sizeof (fhandle_t));
3675                 error = copyin(uap->argp,
3676                     &nfs_pubfh.nfsrvfh_data, sizeof (fhandle_t));
3677                 if (!error)
3678                         nfs_pubfhset = 1;
3679         } else if ((uap->flag & (NFSSVC_V4ROOTEXPORT | NFSSVC_NEWSTRUCT)) ==
3680             (NFSSVC_V4ROOTEXPORT | NFSSVC_NEWSTRUCT)) {
3681                 error = copyin(uap->argp,(caddr_t)&export,
3682                     sizeof (struct nfsex_args));
3683                 if (!error) {
3684                         grps = NULL;
3685                         if (export.export.ex_ngroups > NGROUPS_MAX ||
3686                             export.export.ex_ngroups < 0)
3687                                 error = EINVAL;
3688                         else if (export.export.ex_ngroups > 0) {
3689                                 grps = malloc(export.export.ex_ngroups *
3690                                     sizeof(gid_t), M_TEMP, M_WAITOK);
3691                                 error = copyin(export.export.ex_groups, grps,
3692                                     export.export.ex_ngroups * sizeof(gid_t));
3693                                 export.export.ex_groups = grps;
3694                         } else
3695                                 export.export.ex_groups = NULL;
3696                         if (!error)
3697                                 error = nfsrv_v4rootexport(&export, cred, p);
3698                         free(grps, M_TEMP);
3699                 }
3700         } else if ((uap->flag & (NFSSVC_V4ROOTEXPORT | NFSSVC_NEWSTRUCT)) ==
3701             NFSSVC_V4ROOTEXPORT) {
3702                 error = copyin(uap->argp,(caddr_t)&oexp,
3703                     sizeof (struct nfsex_oldargs));
3704                 if (!error) {
3705                         memset(&export.export, 0, sizeof(export.export));
3706                         export.export.ex_flags = (uint64_t)oexp.export.ex_flags;
3707                         export.export.ex_root = oexp.export.ex_root;
3708                         export.export.ex_uid = oexp.export.ex_anon.cr_uid;
3709                         export.export.ex_ngroups =
3710                             oexp.export.ex_anon.cr_ngroups;
3711                         export.export.ex_groups = NULL;
3712                         if (export.export.ex_ngroups > XU_NGROUPS ||
3713                             export.export.ex_ngroups < 0)
3714                                 error = EINVAL;
3715                         else if (export.export.ex_ngroups > 0) {
3716                                 export.export.ex_groups = malloc(
3717                                     export.export.ex_ngroups * sizeof(gid_t),
3718                                     M_TEMP, M_WAITOK);
3719                                 for (i = 0; i < export.export.ex_ngroups; i++)
3720                                         export.export.ex_groups[i] =
3721                                             oexp.export.ex_anon.cr_groups[i];
3722                         }
3723                         export.export.ex_addr = oexp.export.ex_addr;
3724                         export.export.ex_addrlen = oexp.export.ex_addrlen;
3725                         export.export.ex_mask = oexp.export.ex_mask;
3726                         export.export.ex_masklen = oexp.export.ex_masklen;
3727                         export.export.ex_indexfile = oexp.export.ex_indexfile;
3728                         export.export.ex_numsecflavors =
3729                             oexp.export.ex_numsecflavors;
3730                         if (export.export.ex_numsecflavors >= MAXSECFLAVORS ||
3731                             export.export.ex_numsecflavors < 0)
3732                                 error = EINVAL;
3733                         else {
3734                                 for (i = 0; i < export.export.ex_numsecflavors;
3735                                     i++)
3736                                         export.export.ex_secflavors[i] =
3737                                             oexp.export.ex_secflavors[i];
3738                         }
3739                         export.fspec = oexp.fspec;
3740                         if (error == 0)
3741                                 error = nfsrv_v4rootexport(&export, cred, p);
3742                         free(export.export.ex_groups, M_TEMP);
3743                 }
3744         } else if (uap->flag & NFSSVC_NOPUBLICFH) {
3745                 nfs_pubfhset = 0;
3746                 error = 0;
3747         } else if (uap->flag & NFSSVC_STABLERESTART) {
3748                 error = copyin(uap->argp, (caddr_t)&stablefd,
3749                     sizeof (int));
3750                 if (!error)
3751                         error = fp_getfvp(p, stablefd, &fp, &vp);
3752                 if (!error && (NFSFPFLAG(fp) & (FREAD | FWRITE)) != (FREAD | FWRITE))
3753                         error = EBADF;
3754                 if (!error && newnfs_numnfsd != 0)
3755                         error = EPERM;
3756                 if (!error) {
3757                         nfsrv_stablefirst.nsf_fp = fp;
3758                         nfsrv_setupstable(p);
3759                 }
3760         } else if (uap->flag & NFSSVC_ADMINREVOKE) {
3761                 error = copyin(uap->argp, (caddr_t)&adminrevoke,
3762                     sizeof (struct nfsd_clid));
3763                 if (!error)
3764                         error = nfsrv_adminrevoke(&adminrevoke, p);
3765         } else if (uap->flag & NFSSVC_DUMPCLIENTS) {
3766                 error = copyin(uap->argp, (caddr_t)&dumplist,
3767                     sizeof (struct nfsd_dumplist));
3768                 if (!error && (dumplist.ndl_size < 1 ||
3769                         dumplist.ndl_size > NFSRV_MAXDUMPLIST))
3770                         error = EPERM;
3771                 if (!error) {
3772                     len = sizeof (struct nfsd_dumpclients) * dumplist.ndl_size;
3773                     dumpclients = malloc(len, M_TEMP, M_WAITOK | M_ZERO);
3774                     nfsrv_dumpclients(dumpclients, dumplist.ndl_size);
3775                     error = copyout(dumpclients, dumplist.ndl_list, len);
3776                     free(dumpclients, M_TEMP);
3777                 }
3778         } else if (uap->flag & NFSSVC_DUMPLOCKS) {
3779                 error = copyin(uap->argp, (caddr_t)&dumplocklist,
3780                     sizeof (struct nfsd_dumplocklist));
3781                 if (!error && (dumplocklist.ndllck_size < 1 ||
3782                         dumplocklist.ndllck_size > NFSRV_MAXDUMPLIST))
3783                         error = EPERM;
3784                 if (!error)
3785                         error = nfsrv_lookupfilename(&nd,
3786                                 dumplocklist.ndllck_fname, p);
3787                 if (!error) {
3788                         len = sizeof (struct nfsd_dumplocks) *
3789                                 dumplocklist.ndllck_size;
3790                         dumplocks = malloc(len, M_TEMP, M_WAITOK | M_ZERO);
3791                         nfsrv_dumplocks(nd.ni_vp, dumplocks,
3792                             dumplocklist.ndllck_size, p);
3793                         vput(nd.ni_vp);
3794                         error = copyout(dumplocks, dumplocklist.ndllck_list,
3795                             len);
3796                         free(dumplocks, M_TEMP);
3797                 }
3798         } else if (uap->flag & NFSSVC_BACKUPSTABLE) {
3799                 procp = p->td_proc;
3800                 PROC_LOCK(procp);
3801                 nfsd_master_pid = procp->p_pid;
3802                 bcopy(procp->p_comm, nfsd_master_comm, MAXCOMLEN + 1);
3803                 nfsd_master_start = procp->p_stats->p_start;
3804                 nfsd_master_proc = procp;
3805                 PROC_UNLOCK(procp);
3806         } else if ((uap->flag & NFSSVC_SUSPENDNFSD) != 0) {
3807                 NFSLOCKV4ROOTMUTEX();
3808                 if (suspend_nfsd == 0) {
3809                         /* Lock out all nfsd threads */
3810                         do {
3811                                 igotlock = nfsv4_lock(&nfsd_suspend_lock, 1,
3812                                     NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
3813                         } while (igotlock == 0 && suspend_nfsd == 0);
3814                         suspend_nfsd = 1;
3815                 }
3816                 NFSUNLOCKV4ROOTMUTEX();
3817                 error = 0;
3818         } else if ((uap->flag & NFSSVC_RESUMENFSD) != 0) {
3819                 NFSLOCKV4ROOTMUTEX();
3820                 if (suspend_nfsd != 0) {
3821                         nfsv4_unlock(&nfsd_suspend_lock, 0);
3822                         suspend_nfsd = 0;
3823                 }
3824                 NFSUNLOCKV4ROOTMUTEX();
3825                 error = 0;
3826         }
3827
3828         NFSEXITCODE(error);
3829         return (error);
3830 }
3831
3832 /*
3833  * Check exports.
3834  * Returns 0 if ok, 1 otherwise.
3835  */
3836 int
3837 nfsvno_testexp(struct nfsrv_descript *nd, struct nfsexstuff *exp)
3838 {
3839         int i;
3840
3841         /*
3842          * This seems odd, but allow the case where the security flavor
3843          * list is empty. This happens when NFSv4 is traversing non-exported
3844          * file systems. Exported file systems should always have a non-empty
3845          * security flavor list.
3846          */
3847         if (exp->nes_numsecflavor == 0)
3848                 return (0);
3849
3850         for (i = 0; i < exp->nes_numsecflavor; i++) {
3851                 /*
3852                  * The tests for privacy and integrity must be first,
3853                  * since ND_GSS is set for everything but AUTH_SYS.
3854                  */
3855                 if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5P &&
3856                     (nd->nd_flag & ND_GSSPRIVACY))
3857                         return (0);
3858                 if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5I &&
3859                     (nd->nd_flag & ND_GSSINTEGRITY))
3860                         return (0);
3861                 if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5 &&
3862                     (nd->nd_flag & ND_GSS))
3863                         return (0);
3864                 if (exp->nes_secflavors[i] == AUTH_SYS &&
3865                     (nd->nd_flag & ND_GSS) == 0)
3866                         return (0);
3867         }
3868         return (1);
3869 }
3870
3871 /*
3872  * Calculate a hash value for the fid in a file handle.
3873  */
3874 uint32_t
3875 nfsrv_hashfh(fhandle_t *fhp)
3876 {
3877         uint32_t hashval;
3878
3879         hashval = hash32_buf(&fhp->fh_fid, sizeof(struct fid), 0);
3880         return (hashval);
3881 }
3882
3883 /*
3884  * Calculate a hash value for the sessionid.
3885  */
3886 uint32_t
3887 nfsrv_hashsessionid(uint8_t *sessionid)
3888 {
3889         uint32_t hashval;
3890
3891         hashval = hash32_buf(sessionid, NFSX_V4SESSIONID, 0);
3892         return (hashval);
3893 }
3894
3895 /*
3896  * Signal the userland master nfsd to backup the stable restart file.
3897  */
3898 void
3899 nfsrv_backupstable(void)
3900 {
3901         struct proc *procp;
3902
3903         if (nfsd_master_proc != NULL) {
3904                 procp = pfind(nfsd_master_pid);
3905                 /* Try to make sure it is the correct process. */
3906                 if (procp == nfsd_master_proc &&
3907                     procp->p_stats->p_start.tv_sec ==
3908                     nfsd_master_start.tv_sec &&
3909                     procp->p_stats->p_start.tv_usec ==
3910                     nfsd_master_start.tv_usec &&
3911                     strcmp(procp->p_comm, nfsd_master_comm) == 0)
3912                         kern_psignal(procp, SIGUSR2);
3913                 else
3914                         nfsd_master_proc = NULL;
3915
3916                 if (procp != NULL)
3917                         PROC_UNLOCK(procp);
3918         }
3919 }
3920
3921 /*
3922  * Create a DS data file for nfsrv_pnfscreate(). Called for each mirror.
3923  * The arguments are in a structure, so that they can be passed through
3924  * taskqueue for a kernel process to execute this function.
3925  */
3926 struct nfsrvdscreate {
3927         int                     done;
3928         int                     inprog;
3929         struct task             tsk;
3930         struct ucred            *tcred;
3931         struct vnode            *dvp;
3932         NFSPROC_T               *p;
3933         struct pnfsdsfile       *pf;
3934         int                     err;
3935         fhandle_t               fh;
3936         struct vattr            va;
3937         struct vattr            createva;
3938 };
3939
3940 int
3941 nfsrv_dscreate(struct vnode *dvp, struct vattr *vap, struct vattr *nvap,
3942     fhandle_t *fhp, struct pnfsdsfile *pf, struct pnfsdsattr *dsa,
3943     char *fnamep, struct ucred *tcred, NFSPROC_T *p, struct vnode **nvpp)
3944 {
3945         struct vnode *nvp;
3946         struct nameidata named;
3947         struct vattr va;
3948         char *bufp;
3949         u_long *hashp;
3950         struct nfsnode *np;
3951         struct nfsmount *nmp;
3952         int error;
3953
3954         NFSNAMEICNDSET(&named.ni_cnd, tcred, CREATE,
3955             LOCKPARENT | LOCKLEAF | SAVESTART | NOCACHE);
3956         nfsvno_setpathbuf(&named, &bufp, &hashp);
3957         named.ni_cnd.cn_lkflags = LK_EXCLUSIVE;
3958         named.ni_cnd.cn_thread = p;
3959         named.ni_cnd.cn_nameptr = bufp;
3960         if (fnamep != NULL) {
3961                 strlcpy(bufp, fnamep, PNFS_FILENAME_LEN + 1);
3962                 named.ni_cnd.cn_namelen = strlen(bufp);
3963         } else
3964                 named.ni_cnd.cn_namelen = nfsrv_putfhname(fhp, bufp);
3965         NFSD_DEBUG(4, "nfsrv_dscreate: dvp=%p fname=%s\n", dvp, bufp);
3966
3967         /* Create the date file in the DS mount. */
3968         error = NFSVOPLOCK(dvp, LK_EXCLUSIVE);
3969         if (error == 0) {
3970                 error = VOP_CREATE(dvp, &nvp, &named.ni_cnd, vap);
3971                 NFSVOPUNLOCK(dvp);
3972                 if (error == 0) {
3973                         /* Set the ownership of the file. */
3974                         error = VOP_SETATTR(nvp, nvap, tcred);
3975                         NFSD_DEBUG(4, "nfsrv_dscreate:"
3976                             " setattr-uid=%d\n", error);
3977                         if (error != 0)
3978                                 vput(nvp);
3979                 }
3980                 if (error != 0)
3981                         printf("pNFS: pnfscreate failed=%d\n", error);
3982         } else
3983                 printf("pNFS: pnfscreate vnlock=%d\n", error);
3984         if (error == 0) {
3985                 np = VTONFS(nvp);
3986                 nmp = VFSTONFS(nvp->v_mount);
3987                 if (strcmp(nvp->v_mount->mnt_vfc->vfc_name, "nfs")
3988                     != 0 || nmp->nm_nam->sa_len > sizeof(
3989                     struct sockaddr_in6) ||
3990                     np->n_fhp->nfh_len != NFSX_MYFH) {
3991                         printf("Bad DS file: fstype=%s salen=%d"
3992                             " fhlen=%d\n",
3993                             nvp->v_mount->mnt_vfc->vfc_name,
3994                             nmp->nm_nam->sa_len, np->n_fhp->nfh_len);
3995                         error = ENOENT;
3996                 }
3997
3998                 /* Set extattrs for the DS on the MDS file. */
3999                 if (error == 0) {
4000                         if (dsa != NULL) {
4001                                 error = VOP_GETATTR(nvp, &va, tcred);
4002                                 if (error == 0) {
4003                                         dsa->dsa_filerev = va.va_filerev;
4004                                         dsa->dsa_size = va.va_size;
4005                                         dsa->dsa_atime = va.va_atime;
4006                                         dsa->dsa_mtime = va.va_mtime;
4007                                         dsa->dsa_bytes = va.va_bytes;
4008                                 }
4009                         }
4010                         if (error == 0) {
4011                                 NFSBCOPY(np->n_fhp->nfh_fh, &pf->dsf_fh,
4012                                     NFSX_MYFH);
4013                                 NFSBCOPY(nmp->nm_nam, &pf->dsf_sin,
4014                                     nmp->nm_nam->sa_len);
4015                                 NFSBCOPY(named.ni_cnd.cn_nameptr,
4016                                     pf->dsf_filename,
4017                                     sizeof(pf->dsf_filename));
4018                         }
4019                 } else
4020                         printf("pNFS: pnfscreate can't get DS"
4021                             " attr=%d\n", error);
4022                 if (nvpp != NULL && error == 0)
4023                         *nvpp = nvp;
4024                 else
4025                         vput(nvp);
4026         }
4027         nfsvno_relpathbuf(&named);
4028         return (error);
4029 }
4030
4031 /*
4032  * Start up the thread that will execute nfsrv_dscreate().
4033  */
4034 static void
4035 start_dscreate(void *arg, int pending)
4036 {
4037         struct nfsrvdscreate *dsc;
4038
4039         dsc = (struct nfsrvdscreate *)arg;
4040         dsc->err = nfsrv_dscreate(dsc->dvp, &dsc->createva, &dsc->va, &dsc->fh,
4041             dsc->pf, NULL, NULL, dsc->tcred, dsc->p, NULL);
4042         dsc->done = 1;
4043         NFSD_DEBUG(4, "start_dscreate: err=%d\n", dsc->err);
4044 }
4045
4046 /*
4047  * Create a pNFS data file on the Data Server(s).
4048  */
4049 static void
4050 nfsrv_pnfscreate(struct vnode *vp, struct vattr *vap, struct ucred *cred,
4051     NFSPROC_T *p)
4052 {
4053         struct nfsrvdscreate *dsc, *tdsc = NULL;
4054         struct nfsdevice *ds, *tds, *fds;
4055         struct mount *mp;
4056         struct pnfsdsfile *pf, *tpf;
4057         struct pnfsdsattr dsattr;
4058         struct vattr va;
4059         struct vnode *dvp[NFSDEV_MAXMIRRORS];
4060         struct nfsmount *nmp;
4061         fhandle_t fh;
4062         uid_t vauid;
4063         gid_t vagid;
4064         u_short vamode;
4065         struct ucred *tcred;
4066         int dsdir[NFSDEV_MAXMIRRORS], error, i, mirrorcnt, ret;
4067         int failpos, timo;
4068
4069         /* Get a DS server directory in a round-robin order. */
4070         mirrorcnt = 1;
4071         mp = vp->v_mount;
4072         ds = fds = NULL;
4073         NFSDDSLOCK();
4074         /*
4075          * Search for the first entry that handles this MDS fs, but use the
4076          * first entry for all MDS fs's otherwise.
4077          */
4078         TAILQ_FOREACH(tds, &nfsrv_devidhead, nfsdev_list) {
4079                 if (tds->nfsdev_nmp != NULL) {
4080                         if (tds->nfsdev_mdsisset == 0 && ds == NULL)
4081                                 ds = tds;
4082                         else if (tds->nfsdev_mdsisset != 0 && fsidcmp(
4083                             &mp->mnt_stat.f_fsid, &tds->nfsdev_mdsfsid) == 0) {
4084                                 ds = fds = tds;
4085                                 break;
4086                         }
4087                 }
4088         }
4089         if (ds == NULL) {
4090                 NFSDDSUNLOCK();
4091                 NFSD_DEBUG(4, "nfsrv_pnfscreate: no srv\n");
4092                 return;
4093         }
4094         i = dsdir[0] = ds->nfsdev_nextdir;
4095         ds->nfsdev_nextdir = (ds->nfsdev_nextdir + 1) % nfsrv_dsdirsize;
4096         dvp[0] = ds->nfsdev_dsdir[i];
4097         tds = TAILQ_NEXT(ds, nfsdev_list);
4098         if (nfsrv_maxpnfsmirror > 1 && tds != NULL) {
4099                 TAILQ_FOREACH_FROM(tds, &nfsrv_devidhead, nfsdev_list) {
4100                         if (tds->nfsdev_nmp != NULL &&
4101                             ((tds->nfsdev_mdsisset == 0 && fds == NULL) ||
4102                              (tds->nfsdev_mdsisset != 0 && fds != NULL &&
4103                               fsidcmp(&mp->mnt_stat.f_fsid,
4104                               &tds->nfsdev_mdsfsid) == 0))) {
4105                                 dsdir[mirrorcnt] = i;
4106                                 dvp[mirrorcnt] = tds->nfsdev_dsdir[i];
4107                                 mirrorcnt++;
4108                                 if (mirrorcnt >= nfsrv_maxpnfsmirror)
4109                                         break;
4110                         }
4111                 }
4112         }
4113         /* Put at end of list to implement round-robin usage. */
4114         TAILQ_REMOVE(&nfsrv_devidhead, ds, nfsdev_list);
4115         TAILQ_INSERT_TAIL(&nfsrv_devidhead, ds, nfsdev_list);
4116         NFSDDSUNLOCK();
4117         dsc = NULL;
4118         if (mirrorcnt > 1)
4119                 tdsc = dsc = malloc(sizeof(*dsc) * (mirrorcnt - 1), M_TEMP,
4120                     M_WAITOK | M_ZERO);
4121         tpf = pf = malloc(sizeof(*pf) * nfsrv_maxpnfsmirror, M_TEMP, M_WAITOK |
4122             M_ZERO);
4123
4124         error = nfsvno_getfh(vp, &fh, p);
4125         if (error == 0)
4126                 error = VOP_GETATTR(vp, &va, cred);
4127         if (error == 0) {
4128                 /* Set the attributes for "vp" to Setattr the DS vp. */
4129                 vauid = va.va_uid;
4130                 vagid = va.va_gid;
4131                 vamode = va.va_mode;
4132                 VATTR_NULL(&va);
4133                 va.va_uid = vauid;
4134                 va.va_gid = vagid;
4135                 va.va_mode = vamode;
4136                 va.va_size = 0;
4137         } else
4138                 printf("pNFS: pnfscreate getfh+attr=%d\n", error);
4139
4140         NFSD_DEBUG(4, "nfsrv_pnfscreate: cruid=%d crgid=%d\n", cred->cr_uid,
4141             cred->cr_gid);
4142         /* Make data file name based on FH. */
4143         tcred = newnfs_getcred();
4144
4145         /*
4146          * Create the file on each DS mirror, using kernel process(es) for the
4147          * additional mirrors.
4148          */
4149         failpos = -1;
4150         for (i = 0; i < mirrorcnt - 1 && error == 0; i++, tpf++, tdsc++) {
4151                 tpf->dsf_dir = dsdir[i];
4152                 tdsc->tcred = tcred;
4153                 tdsc->p = p;
4154                 tdsc->pf = tpf;
4155                 tdsc->createva = *vap;
4156                 NFSBCOPY(&fh, &tdsc->fh, sizeof(fh));
4157                 tdsc->va = va;
4158                 tdsc->dvp = dvp[i];
4159                 tdsc->done = 0;
4160                 tdsc->inprog = 0;
4161                 tdsc->err = 0;
4162                 ret = EIO;
4163                 if (nfs_pnfsiothreads != 0) {
4164                         ret = nfs_pnfsio(start_dscreate, tdsc);
4165                         NFSD_DEBUG(4, "nfsrv_pnfscreate: nfs_pnfsio=%d\n", ret);
4166                 }
4167                 if (ret != 0) {
4168                         ret = nfsrv_dscreate(dvp[i], vap, &va, &fh, tpf, NULL,
4169                             NULL, tcred, p, NULL);
4170                         if (ret != 0) {
4171                                 KASSERT(error == 0, ("nfsrv_dscreate err=%d",
4172                                     error));
4173                                 if (failpos == -1 && nfsds_failerr(ret))
4174                                         failpos = i;
4175                                 else
4176                                         error = ret;
4177                         }
4178                 }
4179         }
4180         if (error == 0) {
4181                 tpf->dsf_dir = dsdir[mirrorcnt - 1];
4182                 error = nfsrv_dscreate(dvp[mirrorcnt - 1], vap, &va, &fh, tpf,
4183                     &dsattr, NULL, tcred, p, NULL);
4184                 if (failpos == -1 && mirrorcnt > 1 && nfsds_failerr(error)) {
4185                         failpos = mirrorcnt - 1;
4186                         error = 0;
4187                 }
4188         }
4189         timo = hz / 50;         /* Wait for 20msec. */
4190         if (timo < 1)
4191                 timo = 1;
4192         /* Wait for kernel task(s) to complete. */
4193         for (tdsc = dsc, i = 0; i < mirrorcnt - 1; i++, tdsc++) {
4194                 while (tdsc->inprog != 0 && tdsc->done == 0)
4195                         tsleep(&tdsc->tsk, PVFS, "srvdcr", timo);
4196                 if (tdsc->err != 0) {
4197                         if (failpos == -1 && nfsds_failerr(tdsc->err))
4198                                 failpos = i;
4199                         else if (error == 0)
4200                                 error = tdsc->err;
4201                 }
4202         }
4203
4204         /*
4205          * If failpos has been set, that mirror has failed, so it needs
4206          * to be disabled.
4207          */
4208         if (failpos >= 0) {
4209                 nmp = VFSTONFS(dvp[failpos]->v_mount);
4210                 NFSLOCKMNT(nmp);
4211                 if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
4212                      NFSMNTP_CANCELRPCS)) == 0) {
4213                         nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
4214                         NFSUNLOCKMNT(nmp);
4215                         ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER, nmp, p);
4216                         NFSD_DEBUG(4, "dscreatfail fail=%d ds=%p\n", failpos,
4217                             ds);
4218                         if (ds != NULL)
4219                                 nfsrv_killrpcs(nmp);
4220                         NFSLOCKMNT(nmp);
4221                         nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
4222                         wakeup(nmp);
4223                 }
4224                 NFSUNLOCKMNT(nmp);
4225         }
4226
4227         NFSFREECRED(tcred);
4228         if (error == 0) {
4229                 ASSERT_VOP_ELOCKED(vp, "nfsrv_pnfscreate vp");
4230
4231                 NFSD_DEBUG(4, "nfsrv_pnfscreate: mirrorcnt=%d maxmirror=%d\n",
4232                     mirrorcnt, nfsrv_maxpnfsmirror);
4233                 /*
4234                  * For all mirrors that couldn't be created, fill in the
4235                  * *pf structure, but with an IP address == 0.0.0.0.
4236                  */
4237                 tpf = pf + mirrorcnt;
4238                 for (i = mirrorcnt; i < nfsrv_maxpnfsmirror; i++, tpf++) {
4239                         *tpf = *pf;
4240                         tpf->dsf_sin.sin_family = AF_INET;
4241                         tpf->dsf_sin.sin_len = sizeof(struct sockaddr_in);
4242                         tpf->dsf_sin.sin_addr.s_addr = 0;
4243                         tpf->dsf_sin.sin_port = 0;
4244                 }
4245
4246                 error = vn_extattr_set(vp, IO_NODELOCKED,
4247                     EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile",
4248                     sizeof(*pf) * nfsrv_maxpnfsmirror, (char *)pf, p);
4249                 if (error == 0)
4250                         error = vn_extattr_set(vp, IO_NODELOCKED,
4251                             EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsattr",
4252                             sizeof(dsattr), (char *)&dsattr, p);
4253                 if (error != 0)
4254                         printf("pNFS: pnfscreate setextattr=%d\n",
4255                             error);
4256         } else
4257                 printf("pNFS: pnfscreate=%d\n", error);
4258         free(pf, M_TEMP);
4259         free(dsc, M_TEMP);
4260 }
4261
4262 /*
4263  * Get the information needed to remove the pNFS Data Server file from the
4264  * Metadata file.  Upon success, ddvp is set non-NULL to the locked
4265  * DS directory vnode.  The caller must unlock *ddvp when done with it.
4266  */
4267 static void
4268 nfsrv_pnfsremovesetup(struct vnode *vp, NFSPROC_T *p, struct vnode **dvpp,
4269     int *mirrorcntp, char *fname, fhandle_t *fhp)
4270 {
4271         struct vattr va;
4272         struct ucred *tcred;
4273         char *buf;
4274         int buflen, error;
4275
4276         dvpp[0] = NULL;
4277         /* If not an exported regular file or not a pNFS server, just return. */
4278         if (vp->v_type != VREG || (vp->v_mount->mnt_flag & MNT_EXPORTED) == 0 ||
4279             nfsrv_devidcnt == 0)
4280                 return;
4281
4282         /* Check to see if this is the last hard link. */
4283         tcred = newnfs_getcred();
4284         error = VOP_GETATTR(vp, &va, tcred);
4285         NFSFREECRED(tcred);
4286         if (error != 0) {
4287                 printf("pNFS: nfsrv_pnfsremovesetup getattr=%d\n", error);
4288                 return;
4289         }
4290         if (va.va_nlink > 1)
4291                 return;
4292
4293         error = nfsvno_getfh(vp, fhp, p);
4294         if (error != 0) {
4295                 printf("pNFS: nfsrv_pnfsremovesetup getfh=%d\n", error);
4296                 return;
4297         }
4298
4299         buflen = 1024;
4300         buf = malloc(buflen, M_TEMP, M_WAITOK);
4301         /* Get the directory vnode for the DS mount and the file handle. */
4302         error = nfsrv_dsgetsockmnt(vp, 0, buf, &buflen, mirrorcntp, p, dvpp,
4303             NULL, NULL, fname, NULL, NULL, NULL, NULL, NULL);
4304         free(buf, M_TEMP);
4305         if (error != 0)
4306                 printf("pNFS: nfsrv_pnfsremovesetup getsockmnt=%d\n", error);
4307 }
4308
4309 /*
4310  * Remove a DS data file for nfsrv_pnfsremove(). Called for each mirror.
4311  * The arguments are in a structure, so that they can be passed through
4312  * taskqueue for a kernel process to execute this function.
4313  */
4314 struct nfsrvdsremove {
4315         int                     done;
4316         int                     inprog;
4317         struct task             tsk;
4318         struct ucred            *tcred;
4319         struct vnode            *dvp;
4320         NFSPROC_T               *p;
4321         int                     err;
4322         char                    fname[PNFS_FILENAME_LEN + 1];
4323 };
4324
4325 static int
4326 nfsrv_dsremove(struct vnode *dvp, char *fname, struct ucred *tcred,
4327     NFSPROC_T *p)
4328 {
4329         struct nameidata named;
4330         struct vnode *nvp;
4331         char *bufp;
4332         u_long *hashp;
4333         int error;
4334
4335         error = NFSVOPLOCK(dvp, LK_EXCLUSIVE);
4336         if (error != 0)
4337                 return (error);
4338         named.ni_cnd.cn_nameiop = DELETE;
4339         named.ni_cnd.cn_lkflags = LK_EXCLUSIVE | LK_RETRY;
4340         named.ni_cnd.cn_cred = tcred;
4341         named.ni_cnd.cn_thread = p;
4342         named.ni_cnd.cn_flags = ISLASTCN | LOCKPARENT | LOCKLEAF | SAVENAME;
4343         nfsvno_setpathbuf(&named, &bufp, &hashp);
4344         named.ni_cnd.cn_nameptr = bufp;
4345         named.ni_cnd.cn_namelen = strlen(fname);
4346         strlcpy(bufp, fname, NAME_MAX);
4347         NFSD_DEBUG(4, "nfsrv_pnfsremove: filename=%s\n", bufp);
4348         error = VOP_LOOKUP(dvp, &nvp, &named.ni_cnd);
4349         NFSD_DEBUG(4, "nfsrv_pnfsremove: aft LOOKUP=%d\n", error);
4350         if (error == 0) {
4351                 error = VOP_REMOVE(dvp, nvp, &named.ni_cnd);
4352                 vput(nvp);
4353         }
4354         NFSVOPUNLOCK(dvp);
4355         nfsvno_relpathbuf(&named);
4356         if (error != 0)
4357                 printf("pNFS: nfsrv_pnfsremove failed=%d\n", error);
4358         return (error);
4359 }
4360
4361 /*
4362  * Start up the thread that will execute nfsrv_dsremove().
4363  */
4364 static void
4365 start_dsremove(void *arg, int pending)
4366 {
4367         struct nfsrvdsremove *dsrm;
4368
4369         dsrm = (struct nfsrvdsremove *)arg;
4370         dsrm->err = nfsrv_dsremove(dsrm->dvp, dsrm->fname, dsrm->tcred,
4371             dsrm->p);
4372         dsrm->done = 1;
4373         NFSD_DEBUG(4, "start_dsremove: err=%d\n", dsrm->err);
4374 }
4375
4376 /*
4377  * Remove a pNFS data file from a Data Server.
4378  * nfsrv_pnfsremovesetup() must have been called before the MDS file was
4379  * removed to set up the dvp and fill in the FH.
4380  */
4381 static void
4382 nfsrv_pnfsremove(struct vnode **dvp, int mirrorcnt, char *fname, fhandle_t *fhp,
4383     NFSPROC_T *p)
4384 {
4385         struct ucred *tcred;
4386         struct nfsrvdsremove *dsrm, *tdsrm;
4387         struct nfsdevice *ds;
4388         struct nfsmount *nmp;
4389         int failpos, i, ret, timo;
4390
4391         tcred = newnfs_getcred();
4392         dsrm = NULL;
4393         if (mirrorcnt > 1)
4394                 dsrm = malloc(sizeof(*dsrm) * mirrorcnt - 1, M_TEMP, M_WAITOK);
4395         /*
4396          * Remove the file on each DS mirror, using kernel process(es) for the
4397          * additional mirrors.
4398          */
4399         failpos = -1;
4400         for (tdsrm = dsrm, i = 0; i < mirrorcnt - 1; i++, tdsrm++) {
4401                 tdsrm->tcred = tcred;
4402                 tdsrm->p = p;
4403                 tdsrm->dvp = dvp[i];
4404                 strlcpy(tdsrm->fname, fname, PNFS_FILENAME_LEN + 1);
4405                 tdsrm->inprog = 0;
4406                 tdsrm->done = 0;
4407                 tdsrm->err = 0;
4408                 ret = EIO;
4409                 if (nfs_pnfsiothreads != 0) {
4410                         ret = nfs_pnfsio(start_dsremove, tdsrm);
4411                         NFSD_DEBUG(4, "nfsrv_pnfsremove: nfs_pnfsio=%d\n", ret);
4412                 }
4413                 if (ret != 0) {
4414                         ret = nfsrv_dsremove(dvp[i], fname, tcred, p);
4415                         if (failpos == -1 && nfsds_failerr(ret))
4416                                 failpos = i;
4417                 }
4418         }
4419         ret = nfsrv_dsremove(dvp[mirrorcnt - 1], fname, tcred, p);
4420         if (failpos == -1 && mirrorcnt > 1 && nfsds_failerr(ret))
4421                 failpos = mirrorcnt - 1;
4422         timo = hz / 50;         /* Wait for 20msec. */
4423         if (timo < 1)
4424                 timo = 1;
4425         /* Wait for kernel task(s) to complete. */
4426         for (tdsrm = dsrm, i = 0; i < mirrorcnt - 1; i++, tdsrm++) {
4427                 while (tdsrm->inprog != 0 && tdsrm->done == 0)
4428                         tsleep(&tdsrm->tsk, PVFS, "srvdsrm", timo);
4429                 if (failpos == -1 && nfsds_failerr(tdsrm->err))
4430                         failpos = i;
4431         }
4432
4433         /*
4434          * If failpos has been set, that mirror has failed, so it needs
4435          * to be disabled.
4436          */
4437         if (failpos >= 0) {
4438                 nmp = VFSTONFS(dvp[failpos]->v_mount);
4439                 NFSLOCKMNT(nmp);
4440                 if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
4441                      NFSMNTP_CANCELRPCS)) == 0) {
4442                         nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
4443                         NFSUNLOCKMNT(nmp);
4444                         ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER, nmp, p);
4445                         NFSD_DEBUG(4, "dsremovefail fail=%d ds=%p\n", failpos,
4446                             ds);
4447                         if (ds != NULL)
4448                                 nfsrv_killrpcs(nmp);
4449                         NFSLOCKMNT(nmp);
4450                         nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
4451                         wakeup(nmp);
4452                 }
4453                 NFSUNLOCKMNT(nmp);
4454         }
4455
4456         /* Get rid all layouts for the file. */
4457         nfsrv_freefilelayouts(fhp);
4458
4459         NFSFREECRED(tcred);
4460         free(dsrm, M_TEMP);
4461 }
4462
4463 /*
4464  * Generate a file name based on the file handle and put it in *bufp.
4465  * Return the number of bytes generated.
4466  */
4467 static int
4468 nfsrv_putfhname(fhandle_t *fhp, char *bufp)
4469 {
4470         int i;
4471         uint8_t *cp;
4472         const uint8_t *hexdigits = "0123456789abcdef";
4473
4474         cp = (uint8_t *)fhp;
4475         for (i = 0; i < sizeof(*fhp); i++) {
4476                 bufp[2 * i] = hexdigits[(*cp >> 4) & 0xf];
4477                 bufp[2 * i + 1] = hexdigits[*cp++ & 0xf];
4478         }
4479         bufp[2 * i] = '\0';
4480         return (2 * i);
4481 }
4482
4483 /*
4484  * Update the Metadata file's attributes from the DS file when a Read/Write
4485  * layout is returned.
4486  * Basically just call nfsrv_proxyds() with procedure == NFSPROC_LAYOUTRETURN
4487  * so that it does a nfsrv_getattrdsrpc() and nfsrv_setextattr() on the DS file.
4488  */
4489 int
4490 nfsrv_updatemdsattr(struct vnode *vp, struct nfsvattr *nap, NFSPROC_T *p)
4491 {
4492         struct ucred *tcred;
4493         int error;
4494
4495         /* Do this as root so that it won't fail with EACCES. */
4496         tcred = newnfs_getcred();
4497         error = nfsrv_proxyds(vp, 0, 0, tcred, p, NFSPROC_LAYOUTRETURN,
4498             NULL, NULL, NULL, nap, NULL, NULL, 0, NULL);
4499         NFSFREECRED(tcred);
4500         return (error);
4501 }
4502
4503 /*
4504  * Set the NFSv4 ACL on the DS file to the same ACL as the MDS file.
4505  */
4506 static int
4507 nfsrv_dssetacl(struct vnode *vp, struct acl *aclp, struct ucred *cred,
4508     NFSPROC_T *p)
4509 {
4510         int error;
4511
4512         error = nfsrv_proxyds(vp, 0, 0, cred, p, NFSPROC_SETACL,
4513             NULL, NULL, NULL, NULL, aclp, NULL, 0, NULL);
4514         return (error);
4515 }
4516
4517 static int
4518 nfsrv_proxyds(struct vnode *vp, off_t off, int cnt, struct ucred *cred,
4519     struct thread *p, int ioproc, struct mbuf **mpp, char *cp,
4520     struct mbuf **mpp2, struct nfsvattr *nap, struct acl *aclp,
4521     off_t *offp, int content, bool *eofp)
4522 {
4523         struct nfsmount *nmp[NFSDEV_MAXMIRRORS], *failnmp;
4524         fhandle_t fh[NFSDEV_MAXMIRRORS];
4525         struct vnode *dvp[NFSDEV_MAXMIRRORS];
4526         struct nfsdevice *ds;
4527         struct pnfsdsattr dsattr;
4528         struct opnfsdsattr odsattr;
4529         char *buf;
4530         int buflen, error, failpos, i, mirrorcnt, origmircnt, trycnt;
4531
4532         NFSD_DEBUG(4, "in nfsrv_proxyds\n");
4533         /*
4534          * If not a regular file, not exported or not a pNFS server,
4535          * just return ENOENT.
4536          */
4537         if (vp->v_type != VREG || (vp->v_mount->mnt_flag & MNT_EXPORTED) == 0 ||
4538             nfsrv_devidcnt == 0)
4539                 return (ENOENT);
4540
4541         buflen = 1024;
4542         buf = malloc(buflen, M_TEMP, M_WAITOK);
4543         error = 0;
4544
4545         /*
4546          * For Getattr, get the Change attribute (va_filerev) and size (va_size)
4547          * from the MetaData file's extended attribute.
4548          */
4549         if (ioproc == NFSPROC_GETATTR) {
4550                 error = vn_extattr_get(vp, IO_NODELOCKED,
4551                     EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsattr", &buflen, buf,
4552                     p);
4553                 if (error == 0) {
4554                         if (buflen == sizeof(odsattr)) {
4555                                 NFSBCOPY(buf, &odsattr, buflen);
4556                                 nap->na_filerev = odsattr.dsa_filerev;
4557                                 nap->na_size = odsattr.dsa_size;
4558                                 nap->na_atime = odsattr.dsa_atime;
4559                                 nap->na_mtime = odsattr.dsa_mtime;
4560                                 /*
4561                                  * Fake na_bytes by rounding up na_size.
4562                                  * Since we don't know the block size, just
4563                                  * use BLKDEV_IOSIZE.
4564                                  */
4565                                 nap->na_bytes = (odsattr.dsa_size +
4566                                     BLKDEV_IOSIZE - 1) & ~(BLKDEV_IOSIZE - 1);
4567                         } else if (buflen == sizeof(dsattr)) {
4568                                 NFSBCOPY(buf, &dsattr, buflen);
4569                                 nap->na_filerev = dsattr.dsa_filerev;
4570                                 nap->na_size = dsattr.dsa_size;
4571                                 nap->na_atime = dsattr.dsa_atime;
4572                                 nap->na_mtime = dsattr.dsa_mtime;
4573                                 nap->na_bytes = dsattr.dsa_bytes;
4574                         } else
4575                                 error = ENXIO;
4576                 }
4577                 if (error == 0) {
4578                         /*
4579                          * If nfsrv_pnfsgetdsattr is 0 or nfsrv_checkdsattr()
4580                          * returns 0, just return now.  nfsrv_checkdsattr()
4581                          * returns 0 if there is no Read/Write layout
4582                          * plus either an Open/Write_access or Write
4583                          * delegation issued to a client for the file.
4584                          */
4585                         if (nfsrv_pnfsgetdsattr == 0 ||
4586                             nfsrv_checkdsattr(vp, p) == 0) {
4587                                 free(buf, M_TEMP);
4588                                 return (error);
4589                         }
4590                 }
4591
4592                 /*
4593                  * Clear ENOATTR so the code below will attempt to do a
4594                  * nfsrv_getattrdsrpc() to get the attributes and (re)create
4595                  * the extended attribute.
4596                  */
4597                 if (error == ENOATTR)
4598                         error = 0;
4599         }
4600
4601         origmircnt = -1;
4602         trycnt = 0;
4603 tryagain:
4604         if (error == 0) {
4605                 buflen = 1024;
4606                 if (ioproc == NFSPROC_READDS && NFSVOPISLOCKED(vp) ==
4607                     LK_EXCLUSIVE)
4608                         printf("nfsrv_proxyds: Readds vp exclusively locked\n");
4609                 error = nfsrv_dsgetsockmnt(vp, LK_SHARED, buf, &buflen,
4610                     &mirrorcnt, p, dvp, fh, NULL, NULL, NULL, NULL, NULL,
4611                     NULL, NULL);
4612                 if (error == 0) {
4613                         for (i = 0; i < mirrorcnt; i++)
4614                                 nmp[i] = VFSTONFS(dvp[i]->v_mount);
4615                 } else
4616                         printf("pNFS: proxy getextattr sockaddr=%d\n", error);
4617         } else
4618                 printf("pNFS: nfsrv_dsgetsockmnt=%d\n", error);
4619         if (error == 0) {
4620                 failpos = -1;
4621                 if (origmircnt == -1)
4622                         origmircnt = mirrorcnt;
4623                 /*
4624                  * If failpos is set to a mirror#, then that mirror has
4625                  * failed and will be disabled. For Read, Getattr and Seek, the
4626                  * function only tries one mirror, so if that mirror has
4627                  * failed, it will need to be retried. As such, increment
4628                  * tryitagain for these cases.
4629                  * For Write, Setattr and Setacl, the function tries all
4630                  * mirrors and will not return an error for the case where
4631                  * one mirror has failed. For these cases, the functioning
4632                  * mirror(s) will have been modified, so a retry isn't
4633                  * necessary. These functions will set failpos for the
4634                  * failed mirror#.
4635                  */
4636                 if (ioproc == NFSPROC_READDS) {
4637                         error = nfsrv_readdsrpc(fh, off, cnt, cred, p, nmp[0],
4638                             mpp, mpp2);
4639                         if (nfsds_failerr(error) && mirrorcnt > 1) {
4640                                 /*
4641                                  * Setting failpos will cause the mirror
4642                                  * to be disabled and then a retry of this
4643                                  * read is required.
4644                                  */
4645                                 failpos = 0;
4646                                 error = 0;
4647                                 trycnt++;
4648                         }
4649                 } else if (ioproc == NFSPROC_WRITEDS)
4650                         error = nfsrv_writedsrpc(fh, off, cnt, cred, p, vp,
4651                             &nmp[0], mirrorcnt, mpp, cp, &failpos);
4652                 else if (ioproc == NFSPROC_SETATTR)
4653                         error = nfsrv_setattrdsrpc(fh, cred, p, vp, &nmp[0],
4654                             mirrorcnt, nap, &failpos);
4655                 else if (ioproc == NFSPROC_SETACL)
4656                         error = nfsrv_setacldsrpc(fh, cred, p, vp, &nmp[0],
4657                             mirrorcnt, aclp, &failpos);
4658                 else if (ioproc == NFSPROC_SEEKDS) {
4659                         error = nfsrv_seekdsrpc(fh, offp, content, eofp, cred,
4660                             p, nmp[0]);
4661                         if (nfsds_failerr(error) && mirrorcnt > 1) {
4662                                 /*
4663                                  * Setting failpos will cause the mirror
4664                                  * to be disabled and then a retry of this
4665                                  * read is required.
4666                                  */
4667                                 failpos = 0;
4668                                 error = 0;
4669                                 trycnt++;
4670                         }
4671                 } else if (ioproc == NFSPROC_ALLOCATE)
4672                         error = nfsrv_allocatedsrpc(fh, off, *offp, cred, p, vp,
4673                             &nmp[0], mirrorcnt, &failpos);
4674                 else {
4675                         error = nfsrv_getattrdsrpc(&fh[mirrorcnt - 1], cred, p,
4676                             vp, nmp[mirrorcnt - 1], nap);
4677                         if (nfsds_failerr(error) && mirrorcnt > 1) {
4678                                 /*
4679                                  * Setting failpos will cause the mirror
4680                                  * to be disabled and then a retry of this
4681                                  * getattr is required.
4682                                  */
4683                                 failpos = mirrorcnt - 1;
4684                                 error = 0;
4685                                 trycnt++;
4686                         }
4687                 }
4688                 ds = NULL;
4689                 if (failpos >= 0) {
4690                         failnmp = nmp[failpos];
4691                         NFSLOCKMNT(failnmp);
4692                         if ((failnmp->nm_privflag & (NFSMNTP_FORCEDISM |
4693                              NFSMNTP_CANCELRPCS)) == 0) {
4694                                 failnmp->nm_privflag |= NFSMNTP_CANCELRPCS;
4695                                 NFSUNLOCKMNT(failnmp);
4696                                 ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER,
4697                                     failnmp, p);
4698                                 NFSD_DEBUG(4, "dsldsnmp fail=%d ds=%p\n",
4699                                     failpos, ds);
4700                                 if (ds != NULL)
4701                                         nfsrv_killrpcs(failnmp);
4702                                 NFSLOCKMNT(failnmp);
4703                                 failnmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
4704                                 wakeup(failnmp);
4705                         }
4706                         NFSUNLOCKMNT(failnmp);
4707                 }
4708                 for (i = 0; i < mirrorcnt; i++)
4709                         NFSVOPUNLOCK(dvp[i]);
4710                 NFSD_DEBUG(4, "nfsrv_proxyds: aft RPC=%d trya=%d\n", error,
4711                     trycnt);
4712                 /* Try the Read/Getattr again if a mirror was deleted. */
4713                 if (ds != NULL && trycnt > 0 && trycnt < origmircnt)
4714                         goto tryagain;
4715         } else {
4716                 /* Return ENOENT for any Extended Attribute error. */
4717                 error = ENOENT;
4718         }
4719         free(buf, M_TEMP);
4720         NFSD_DEBUG(4, "nfsrv_proxyds: error=%d\n", error);
4721         return (error);
4722 }
4723
4724 /*
4725  * Get the DS mount point, fh and directory from the "pnfsd.dsfile" extended
4726  * attribute.
4727  * newnmpp - If it points to a non-NULL nmp, that is the destination and needs
4728  *           to be checked.  If it points to a NULL nmp, then it returns
4729  *           a suitable destination.
4730  * curnmp - If non-NULL, it is the source mount for the copy.
4731  */
4732 int
4733 nfsrv_dsgetsockmnt(struct vnode *vp, int lktype, char *buf, int *buflenp,
4734     int *mirrorcntp, NFSPROC_T *p, struct vnode **dvpp, fhandle_t *fhp,
4735     char *devid, char *fnamep, struct vnode **nvpp, struct nfsmount **newnmpp,
4736     struct nfsmount *curnmp, int *ippos, int *dsdirp)
4737 {
4738         struct vnode *dvp, *nvp = NULL, **tdvpp;
4739         struct mount *mp;
4740         struct nfsmount *nmp, *newnmp;
4741         struct sockaddr *sad;
4742         struct sockaddr_in *sin;
4743         struct nfsdevice *ds, *tds, *fndds;
4744         struct pnfsdsfile *pf;
4745         uint32_t dsdir;
4746         int error, fhiszero, fnd, gotone, i, mirrorcnt;
4747
4748         ASSERT_VOP_LOCKED(vp, "nfsrv_dsgetsockmnt vp");
4749         *mirrorcntp = 1;
4750         tdvpp = dvpp;
4751         if (nvpp != NULL)
4752                 *nvpp = NULL;
4753         if (dvpp != NULL)
4754                 *dvpp = NULL;
4755         if (ippos != NULL)
4756                 *ippos = -1;
4757         if (newnmpp != NULL)
4758                 newnmp = *newnmpp;
4759         else
4760                 newnmp = NULL;
4761         mp = vp->v_mount;
4762         error = vn_extattr_get(vp, IO_NODELOCKED, EXTATTR_NAMESPACE_SYSTEM,
4763             "pnfsd.dsfile", buflenp, buf, p);
4764         mirrorcnt = *buflenp / sizeof(*pf);
4765         if (error == 0 && (mirrorcnt < 1 || mirrorcnt > NFSDEV_MAXMIRRORS ||
4766             *buflenp != sizeof(*pf) * mirrorcnt))
4767                 error = ENOATTR;
4768
4769         pf = (struct pnfsdsfile *)buf;
4770         /* If curnmp != NULL, check for a match in the mirror list. */
4771         if (curnmp != NULL && error == 0) {
4772                 fnd = 0;
4773                 for (i = 0; i < mirrorcnt; i++, pf++) {
4774                         sad = (struct sockaddr *)&pf->dsf_sin;
4775                         if (nfsaddr2_match(sad, curnmp->nm_nam)) {
4776                                 if (ippos != NULL)
4777                                         *ippos = i;
4778                                 fnd = 1;
4779                                 break;
4780                         }
4781                 }
4782                 if (fnd == 0)
4783                         error = ENXIO;
4784         }
4785
4786         gotone = 0;
4787         pf = (struct pnfsdsfile *)buf;
4788         NFSD_DEBUG(4, "nfsrv_dsgetsockmnt: mirrorcnt=%d err=%d\n", mirrorcnt,
4789             error);
4790         for (i = 0; i < mirrorcnt && error == 0; i++, pf++) {
4791                 fhiszero = 0;
4792                 sad = (struct sockaddr *)&pf->dsf_sin;
4793                 sin = &pf->dsf_sin;
4794                 dsdir = pf->dsf_dir;
4795                 if (dsdir >= nfsrv_dsdirsize) {
4796                         printf("nfsrv_dsgetsockmnt: dsdir=%d\n", dsdir);
4797                         error = ENOATTR;
4798                 } else if (nvpp != NULL && newnmp != NULL &&
4799                     nfsaddr2_match(sad, newnmp->nm_nam))
4800                         error = EEXIST;
4801                 if (error == 0) {
4802                         if (ippos != NULL && curnmp == NULL &&
4803                             sad->sa_family == AF_INET &&
4804                             sin->sin_addr.s_addr == 0)
4805                                 *ippos = i;
4806                         if (NFSBCMP(&zerofh, &pf->dsf_fh, sizeof(zerofh)) == 0)
4807                                 fhiszero = 1;
4808                         /* Use the socket address to find the mount point. */
4809                         fndds = NULL;
4810                         NFSDDSLOCK();
4811                         /* Find a match for the IP address. */
4812                         TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
4813                                 if (ds->nfsdev_nmp != NULL) {
4814                                         dvp = ds->nfsdev_dvp;
4815                                         nmp = VFSTONFS(dvp->v_mount);
4816                                         if (nmp != ds->nfsdev_nmp)
4817                                                 printf("different2 nmp %p %p\n",
4818                                                     nmp, ds->nfsdev_nmp);
4819                                         if (nfsaddr2_match(sad, nmp->nm_nam)) {
4820                                                 fndds = ds;
4821                                                 break;
4822                                         }
4823                                 }
4824                         }
4825                         if (fndds != NULL && newnmpp != NULL &&
4826                             newnmp == NULL) {
4827                                 /* Search for a place to make a mirror copy. */
4828                                 TAILQ_FOREACH(tds, &nfsrv_devidhead,
4829                                     nfsdev_list) {
4830                                         if (tds->nfsdev_nmp != NULL &&
4831                                             fndds != tds &&
4832                                             ((tds->nfsdev_mdsisset == 0 &&
4833                                               fndds->nfsdev_mdsisset == 0) ||
4834                                              (tds->nfsdev_mdsisset != 0 &&
4835                                               fndds->nfsdev_mdsisset != 0 &&
4836                                               fsidcmp(&tds->nfsdev_mdsfsid,
4837                                               &mp->mnt_stat.f_fsid) == 0))) {
4838                                                 *newnmpp = tds->nfsdev_nmp;
4839                                                 break;
4840                                         }
4841                                 }
4842                                 if (tds != NULL) {
4843                                         /*
4844                                          * Move this entry to the end of the
4845                                          * list, so it won't be selected as
4846                                          * easily the next time.
4847                                          */
4848                                         TAILQ_REMOVE(&nfsrv_devidhead, tds,
4849                                             nfsdev_list);
4850                                         TAILQ_INSERT_TAIL(&nfsrv_devidhead, tds,
4851                                             nfsdev_list);
4852                                 }
4853                         }
4854                         NFSDDSUNLOCK();
4855                         if (fndds != NULL) {
4856                                 dvp = fndds->nfsdev_dsdir[dsdir];
4857                                 if (lktype != 0 || fhiszero != 0 ||
4858                                     (nvpp != NULL && *nvpp == NULL)) {
4859                                         if (fhiszero != 0)
4860                                                 error = vn_lock(dvp,
4861                                                     LK_EXCLUSIVE);
4862                                         else if (lktype != 0)
4863                                                 error = vn_lock(dvp, lktype);
4864                                         else
4865                                                 error = vn_lock(dvp, LK_SHARED);
4866                                         /*
4867                                          * If the file handle is all 0's, try to
4868                                          * do a Lookup against the DS to acquire
4869                                          * it.
4870                                          * If dvpp == NULL or the Lookup fails,
4871                                          * unlock dvp after the call.
4872                                          */
4873                                         if (error == 0 && (fhiszero != 0 ||
4874                                             (nvpp != NULL && *nvpp == NULL))) {
4875                                                 error = nfsrv_pnfslookupds(vp,
4876                                                     dvp, pf, &nvp, p);
4877                                                 if (error == 0) {
4878                                                         if (fhiszero != 0)
4879                                                                 nfsrv_pnfssetfh(
4880                                                                     vp, pf,
4881                                                                     devid,
4882                                                                     fnamep,
4883                                                                     nvp, p);
4884                                                         if (nvpp != NULL &&
4885                                                             *nvpp == NULL) {
4886                                                                 *nvpp = nvp;
4887                                                                 *dsdirp = dsdir;
4888                                                         } else
4889                                                                 vput(nvp);
4890                                                 }
4891                                                 if (error != 0 || lktype == 0)
4892                                                         NFSVOPUNLOCK(dvp);
4893                                         }
4894                                 }
4895                                 if (error == 0) {
4896                                         gotone++;
4897                                         NFSD_DEBUG(4, "gotone=%d\n", gotone);
4898                                         if (devid != NULL) {
4899                                                 NFSBCOPY(fndds->nfsdev_deviceid,
4900                                                     devid, NFSX_V4DEVICEID);
4901                                                 devid += NFSX_V4DEVICEID;
4902                                         }
4903                                         if (dvpp != NULL)
4904                                                 *tdvpp++ = dvp;
4905                                         if (fhp != NULL)
4906                                                 NFSBCOPY(&pf->dsf_fh, fhp++,
4907                                                     NFSX_MYFH);
4908                                         if (fnamep != NULL && gotone == 1)
4909                                                 strlcpy(fnamep,
4910                                                     pf->dsf_filename,
4911                                                     sizeof(pf->dsf_filename));
4912                                 } else
4913                                         NFSD_DEBUG(4, "nfsrv_dsgetsockmnt "
4914                                             "err=%d\n", error);
4915                         }
4916                 }
4917         }
4918         if (error == 0 && gotone == 0)
4919                 error = ENOENT;
4920
4921         NFSD_DEBUG(4, "eo nfsrv_dsgetsockmnt: gotone=%d err=%d\n", gotone,
4922             error);
4923         if (error == 0)
4924                 *mirrorcntp = gotone;
4925         else {
4926                 if (gotone > 0 && dvpp != NULL) {
4927                         /*
4928                          * If the error didn't occur on the first one and
4929                          * dvpp != NULL, the one(s) prior to the failure will
4930                          * have locked dvp's that need to be unlocked.
4931                          */
4932                         for (i = 0; i < gotone; i++) {
4933                                 NFSVOPUNLOCK(*dvpp);
4934                                 *dvpp++ = NULL;
4935                         }
4936                 }
4937                 /*
4938                  * If it found the vnode to be copied from before a failure,
4939                  * it needs to be vput()'d.
4940                  */
4941                 if (nvpp != NULL && *nvpp != NULL) {
4942                         vput(*nvpp);
4943                         *nvpp = NULL;
4944                 }
4945         }
4946         return (error);
4947 }
4948
4949 /*
4950  * Set the extended attribute for the Change attribute.
4951  */
4952 static int
4953 nfsrv_setextattr(struct vnode *vp, struct nfsvattr *nap, NFSPROC_T *p)
4954 {
4955         struct pnfsdsattr dsattr;
4956         int error;
4957
4958         ASSERT_VOP_ELOCKED(vp, "nfsrv_setextattr vp");
4959         dsattr.dsa_filerev = nap->na_filerev;
4960         dsattr.dsa_size = nap->na_size;
4961         dsattr.dsa_atime = nap->na_atime;
4962         dsattr.dsa_mtime = nap->na_mtime;
4963         dsattr.dsa_bytes = nap->na_bytes;
4964         error = vn_extattr_set(vp, IO_NODELOCKED, EXTATTR_NAMESPACE_SYSTEM,
4965             "pnfsd.dsattr", sizeof(dsattr), (char *)&dsattr, p);
4966         if (error != 0)
4967                 printf("pNFS: setextattr=%d\n", error);
4968         return (error);
4969 }
4970
4971 static int
4972 nfsrv_readdsrpc(fhandle_t *fhp, off_t off, int len, struct ucred *cred,
4973     NFSPROC_T *p, struct nfsmount *nmp, struct mbuf **mpp, struct mbuf **mpendp)
4974 {
4975         uint32_t *tl;
4976         struct nfsrv_descript *nd;
4977         nfsv4stateid_t st;
4978         struct mbuf *m, *m2;
4979         int error = 0, retlen, tlen, trimlen;
4980
4981         NFSD_DEBUG(4, "in nfsrv_readdsrpc\n");
4982         nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
4983         *mpp = NULL;
4984         /*
4985          * Use a stateid where other is an alternating 01010 pattern and
4986          * seqid is 0xffffffff.  This value is not defined as special by
4987          * the RFC and is used by the FreeBSD NFS server to indicate an
4988          * MDS->DS proxy operation.
4989          */
4990         st.other[0] = 0x55555555;
4991         st.other[1] = 0x55555555;
4992         st.other[2] = 0x55555555;
4993         st.seqid = 0xffffffff;
4994         nfscl_reqstart(nd, NFSPROC_READDS, nmp, (u_int8_t *)fhp, sizeof(*fhp),
4995             NULL, NULL, 0, 0, false);
4996         nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
4997         NFSM_BUILD(tl, uint32_t *, NFSX_UNSIGNED * 3);
4998         txdr_hyper(off, tl);
4999         *(tl + 2) = txdr_unsigned(len);
5000         error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
5001             NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5002         if (error != 0) {
5003                 free(nd, M_TEMP);
5004                 return (error);
5005         }
5006         if (nd->nd_repstat == 0) {
5007                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
5008                 NFSM_STRSIZ(retlen, len);
5009                 if (retlen > 0) {
5010                         /* Trim off the pre-data XDR from the mbuf chain. */
5011                         m = nd->nd_mrep;
5012                         while (m != NULL && m != nd->nd_md) {
5013                                 if (m->m_next == nd->nd_md) {
5014                                         m->m_next = NULL;
5015                                         m_freem(nd->nd_mrep);
5016                                         nd->nd_mrep = m = nd->nd_md;
5017                                 } else
5018                                         m = m->m_next;
5019                         }
5020                         if (m == NULL) {
5021                                 printf("nfsrv_readdsrpc: busted mbuf list\n");
5022                                 error = ENOENT;
5023                                 goto nfsmout;
5024                         }
5025         
5026                         /*
5027                          * Now, adjust first mbuf so that any XDR before the
5028                          * read data is skipped over.
5029                          */
5030                         trimlen = nd->nd_dpos - mtod(m, char *);
5031                         if (trimlen > 0) {
5032                                 m->m_len -= trimlen;
5033                                 NFSM_DATAP(m, trimlen);
5034                         }
5035         
5036                         /*
5037                          * Truncate the mbuf chain at retlen bytes of data,
5038                          * plus XDR padding that brings the length up to a
5039                          * multiple of 4.
5040                          */
5041                         tlen = NFSM_RNDUP(retlen);
5042                         do {
5043                                 if (m->m_len >= tlen) {
5044                                         m->m_len = tlen;
5045                                         tlen = 0;
5046                                         m2 = m->m_next;
5047                                         m->m_next = NULL;
5048                                         m_freem(m2);
5049                                         break;
5050                                 }
5051                                 tlen -= m->m_len;
5052                                 m = m->m_next;
5053                         } while (m != NULL);
5054                         if (tlen > 0) {
5055                                 printf("nfsrv_readdsrpc: busted mbuf list\n");
5056                                 error = ENOENT;
5057                                 goto nfsmout;
5058                         }
5059                         *mpp = nd->nd_mrep;
5060                         *mpendp = m;
5061                         nd->nd_mrep = NULL;
5062                 }
5063         } else
5064                 error = nd->nd_repstat;
5065 nfsmout:
5066         /* If nd->nd_mrep is already NULL, this is a no-op. */
5067         m_freem(nd->nd_mrep);
5068         free(nd, M_TEMP);
5069         NFSD_DEBUG(4, "nfsrv_readdsrpc error=%d\n", error);
5070         return (error);
5071 }
5072
5073 /*
5074  * Do a write RPC on a DS data file, using this structure for the arguments,
5075  * so that this function can be executed by a separate kernel process.
5076  */
5077 struct nfsrvwritedsdorpc {
5078         int                     done;
5079         int                     inprog;
5080         struct task             tsk;
5081         fhandle_t               fh;
5082         off_t                   off;
5083         int                     len;
5084         struct nfsmount         *nmp;
5085         struct ucred            *cred;
5086         NFSPROC_T               *p;
5087         struct mbuf             *m;
5088         int                     err;
5089 };
5090
5091 static int
5092 nfsrv_writedsdorpc(struct nfsmount *nmp, fhandle_t *fhp, off_t off, int len,
5093     struct nfsvattr *nap, struct mbuf *m, struct ucred *cred, NFSPROC_T *p)
5094 {
5095         uint32_t *tl;
5096         struct nfsrv_descript *nd;
5097         nfsattrbit_t attrbits;
5098         nfsv4stateid_t st;
5099         int commit, error, retlen;
5100
5101         nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5102         nfscl_reqstart(nd, NFSPROC_WRITE, nmp, (u_int8_t *)fhp,
5103             sizeof(fhandle_t), NULL, NULL, 0, 0, false);
5104
5105         /*
5106          * Use a stateid where other is an alternating 01010 pattern and
5107          * seqid is 0xffffffff.  This value is not defined as special by
5108          * the RFC and is used by the FreeBSD NFS server to indicate an
5109          * MDS->DS proxy operation.
5110          */
5111         st.other[0] = 0x55555555;
5112         st.other[1] = 0x55555555;
5113         st.other[2] = 0x55555555;
5114         st.seqid = 0xffffffff;
5115         nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5116         NFSM_BUILD(tl, u_int32_t *, NFSX_HYPER + 2 * NFSX_UNSIGNED);
5117         txdr_hyper(off, tl);
5118         tl += 2;
5119         /*
5120          * Do all writes FileSync, since the server doesn't hold onto dirty
5121          * buffers.  Since clients should be accessing the DS servers directly
5122          * using the pNFS layouts, this just needs to work correctly as a
5123          * fallback.
5124          */
5125         *tl++ = txdr_unsigned(NFSWRITE_FILESYNC);
5126         *tl = txdr_unsigned(len);
5127         NFSD_DEBUG(4, "nfsrv_writedsdorpc: len=%d\n", len);
5128
5129         /* Put data in mbuf chain. */
5130         nd->nd_mb->m_next = m;
5131
5132         /* Set nd_mb and nd_bpos to end of data. */
5133         while (m->m_next != NULL)
5134                 m = m->m_next;
5135         nd->nd_mb = m;
5136         nfsm_set(nd, m->m_len);
5137         NFSD_DEBUG(4, "nfsrv_writedsdorpc: lastmb len=%d\n", m->m_len);
5138
5139         /* Do a Getattr for the attributes that change upon writing. */
5140         NFSZERO_ATTRBIT(&attrbits);
5141         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
5142         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
5143         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
5144         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
5145         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
5146         NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
5147         *tl = txdr_unsigned(NFSV4OP_GETATTR);
5148         (void) nfsrv_putattrbit(nd, &attrbits);
5149         error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p,
5150             cred, NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5151         if (error != 0) {
5152                 free(nd, M_TEMP);
5153                 return (error);
5154         }
5155         NFSD_DEBUG(4, "nfsrv_writedsdorpc: aft writerpc=%d\n", nd->nd_repstat);
5156         /* Get rid of weak cache consistency data for now. */
5157         if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
5158             (ND_NFSV4 | ND_V4WCCATTR)) {
5159                 error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5160                     NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5161                 NFSD_DEBUG(4, "nfsrv_writedsdorpc: wcc attr=%d\n", error);
5162                 if (error != 0)
5163                         goto nfsmout;
5164                 /*
5165                  * Get rid of Op# and status for next op.
5166                  */
5167                 NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5168                 if (*++tl != 0)
5169                         nd->nd_flag |= ND_NOMOREDATA;
5170         }
5171         if (nd->nd_repstat == 0) {
5172                 NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED + NFSX_VERF);
5173                 retlen = fxdr_unsigned(int, *tl++);
5174                 commit = fxdr_unsigned(int, *tl);
5175                 if (commit != NFSWRITE_FILESYNC)
5176                         error = NFSERR_IO;
5177                 NFSD_DEBUG(4, "nfsrv_writedsdorpc:retlen=%d commit=%d err=%d\n",
5178                     retlen, commit, error);
5179         } else
5180                 error = nd->nd_repstat;
5181         /* We have no use for the Write Verifier since we use FileSync. */
5182
5183         /*
5184          * Get the Change, Size, Access Time and Modify Time attributes and set
5185          * on the Metadata file, so its attributes will be what the file's
5186          * would be if it had been written.
5187          */
5188         if (error == 0) {
5189                 NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5190                 error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5191                     NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5192         }
5193         NFSD_DEBUG(4, "nfsrv_writedsdorpc: aft loadattr=%d\n", error);
5194 nfsmout:
5195         m_freem(nd->nd_mrep);
5196         free(nd, M_TEMP);
5197         NFSD_DEBUG(4, "nfsrv_writedsdorpc error=%d\n", error);
5198         return (error);
5199 }
5200
5201 /*
5202  * Start up the thread that will execute nfsrv_writedsdorpc().
5203  */
5204 static void
5205 start_writedsdorpc(void *arg, int pending)
5206 {
5207         struct nfsrvwritedsdorpc *drpc;
5208
5209         drpc = (struct nfsrvwritedsdorpc *)arg;
5210         drpc->err = nfsrv_writedsdorpc(drpc->nmp, &drpc->fh, drpc->off,
5211             drpc->len, NULL, drpc->m, drpc->cred, drpc->p);
5212         drpc->done = 1;
5213         NFSD_DEBUG(4, "start_writedsdorpc: err=%d\n", drpc->err);
5214 }
5215
5216 static int
5217 nfsrv_writedsrpc(fhandle_t *fhp, off_t off, int len, struct ucred *cred,
5218     NFSPROC_T *p, struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
5219     struct mbuf **mpp, char *cp, int *failposp)
5220 {
5221         struct nfsrvwritedsdorpc *drpc, *tdrpc = NULL;
5222         struct nfsvattr na;
5223         struct mbuf *m;
5224         int error, i, offs, ret, timo;
5225
5226         NFSD_DEBUG(4, "in nfsrv_writedsrpc\n");
5227         KASSERT(*mpp != NULL, ("nfsrv_writedsrpc: NULL mbuf chain"));
5228         drpc = NULL;
5229         if (mirrorcnt > 1)
5230                 tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5231                     M_WAITOK);
5232
5233         /* Calculate offset in mbuf chain that data starts. */
5234         offs = cp - mtod(*mpp, char *);
5235         NFSD_DEBUG(4, "nfsrv_writedsrpc: mcopy offs=%d len=%d\n", offs, len);
5236
5237         /*
5238          * Do the write RPC for every DS, using a separate kernel process
5239          * for every DS except the last one.
5240          */
5241         error = 0;
5242         for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5243                 tdrpc->done = 0;
5244                 NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5245                 tdrpc->off = off;
5246                 tdrpc->len = len;
5247                 tdrpc->nmp = *nmpp;
5248                 tdrpc->cred = cred;
5249                 tdrpc->p = p;
5250                 tdrpc->inprog = 0;
5251                 tdrpc->err = 0;
5252                 tdrpc->m = m_copym(*mpp, offs, NFSM_RNDUP(len), M_WAITOK);
5253                 ret = EIO;
5254                 if (nfs_pnfsiothreads != 0) {
5255                         ret = nfs_pnfsio(start_writedsdorpc, tdrpc);
5256                         NFSD_DEBUG(4, "nfsrv_writedsrpc: nfs_pnfsio=%d\n",
5257                             ret);
5258                 }
5259                 if (ret != 0) {
5260                         ret = nfsrv_writedsdorpc(*nmpp, fhp, off, len, NULL,
5261                             tdrpc->m, cred, p);
5262                         if (nfsds_failerr(ret) && *failposp == -1)
5263                                 *failposp = i;
5264                         else if (error == 0 && ret != 0)
5265                                 error = ret;
5266                 }
5267                 nmpp++;
5268                 fhp++;
5269         }
5270         m = m_copym(*mpp, offs, NFSM_RNDUP(len), M_WAITOK);
5271         ret = nfsrv_writedsdorpc(*nmpp, fhp, off, len, &na, m, cred, p);
5272         if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5273                 *failposp = mirrorcnt - 1;
5274         else if (error == 0 && ret != 0)
5275                 error = ret;
5276         if (error == 0)
5277                 error = nfsrv_setextattr(vp, &na, p);
5278         NFSD_DEBUG(4, "nfsrv_writedsrpc: aft setextat=%d\n", error);
5279         tdrpc = drpc;
5280         timo = hz / 50;         /* Wait for 20msec. */
5281         if (timo < 1)
5282                 timo = 1;
5283         for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5284                 /* Wait for RPCs on separate threads to complete. */
5285                 while (tdrpc->inprog != 0 && tdrpc->done == 0)
5286                         tsleep(&tdrpc->tsk, PVFS, "srvwrds", timo);
5287                 if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5288                         *failposp = i;
5289                 else if (error == 0 && tdrpc->err != 0)
5290                         error = tdrpc->err;
5291         }
5292         free(drpc, M_TEMP);
5293         return (error);
5294 }
5295
5296 /*
5297  * Do a allocate RPC on a DS data file, using this structure for the arguments,
5298  * so that this function can be executed by a separate kernel process.
5299  */
5300 struct nfsrvallocatedsdorpc {
5301         int                     done;
5302         int                     inprog;
5303         struct task             tsk;
5304         fhandle_t               fh;
5305         off_t                   off;
5306         off_t                   len;
5307         struct nfsmount         *nmp;
5308         struct ucred            *cred;
5309         NFSPROC_T               *p;
5310         int                     err;
5311 };
5312
5313 static int
5314 nfsrv_allocatedsdorpc(struct nfsmount *nmp, fhandle_t *fhp, off_t off,
5315     off_t len, struct nfsvattr *nap, struct ucred *cred, NFSPROC_T *p)
5316 {
5317         uint32_t *tl;
5318         struct nfsrv_descript *nd;
5319         nfsattrbit_t attrbits;
5320         nfsv4stateid_t st;
5321         int error;
5322
5323         nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5324         nfscl_reqstart(nd, NFSPROC_ALLOCATE, nmp, (u_int8_t *)fhp,
5325             sizeof(fhandle_t), NULL, NULL, 0, 0, false);
5326
5327         /*
5328          * Use a stateid where other is an alternating 01010 pattern and
5329          * seqid is 0xffffffff.  This value is not defined as special by
5330          * the RFC and is used by the FreeBSD NFS server to indicate an
5331          * MDS->DS proxy operation.
5332          */
5333         st.other[0] = 0x55555555;
5334         st.other[1] = 0x55555555;
5335         st.other[2] = 0x55555555;
5336         st.seqid = 0xffffffff;
5337         nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5338         NFSM_BUILD(tl, uint32_t *, 2 * NFSX_HYPER + NFSX_UNSIGNED);
5339         txdr_hyper(off, tl); tl += 2;
5340         txdr_hyper(len, tl); tl += 2;
5341         NFSD_DEBUG(4, "nfsrv_allocatedsdorpc: len=%jd\n", (intmax_t)len);
5342
5343         *tl = txdr_unsigned(NFSV4OP_GETATTR);
5344         NFSGETATTR_ATTRBIT(&attrbits);
5345         nfsrv_putattrbit(nd, &attrbits);
5346         error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p,
5347             cred, NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5348         if (error != 0) {
5349                 free(nd, M_TEMP);
5350                 return (error);
5351         }
5352         NFSD_DEBUG(4, "nfsrv_allocatedsdorpc: aft allocaterpc=%d\n",
5353             nd->nd_repstat);
5354         if (nd->nd_repstat == 0) {
5355                 NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5356                 error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5357                     NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5358         } else
5359                 error = nd->nd_repstat;
5360         NFSD_DEBUG(4, "nfsrv_allocatedsdorpc: aft loadattr=%d\n", error);
5361 nfsmout:
5362         m_freem(nd->nd_mrep);
5363         free(nd, M_TEMP);
5364         NFSD_DEBUG(4, "nfsrv_allocatedsdorpc error=%d\n", error);
5365         return (error);
5366 }
5367
5368 /*
5369  * Start up the thread that will execute nfsrv_allocatedsdorpc().
5370  */
5371 static void
5372 start_allocatedsdorpc(void *arg, int pending)
5373 {
5374         struct nfsrvallocatedsdorpc *drpc;
5375
5376         drpc = (struct nfsrvallocatedsdorpc *)arg;
5377         drpc->err = nfsrv_allocatedsdorpc(drpc->nmp, &drpc->fh, drpc->off,
5378             drpc->len, NULL, drpc->cred, drpc->p);
5379         drpc->done = 1;
5380         NFSD_DEBUG(4, "start_allocatedsdorpc: err=%d\n", drpc->err);
5381 }
5382
5383 static int
5384 nfsrv_allocatedsrpc(fhandle_t *fhp, off_t off, off_t len, struct ucred *cred,
5385     NFSPROC_T *p, struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
5386     int *failposp)
5387 {
5388         struct nfsrvallocatedsdorpc *drpc, *tdrpc = NULL;
5389         struct nfsvattr na;
5390         int error, i, ret, timo;
5391
5392         NFSD_DEBUG(4, "in nfsrv_allocatedsrpc\n");
5393         drpc = NULL;
5394         if (mirrorcnt > 1)
5395                 tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5396                     M_WAITOK);
5397
5398         /*
5399          * Do the allocate RPC for every DS, using a separate kernel process
5400          * for every DS except the last one.
5401          */
5402         error = 0;
5403         for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5404                 tdrpc->done = 0;
5405                 NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5406                 tdrpc->off = off;
5407                 tdrpc->len = len;
5408                 tdrpc->nmp = *nmpp;
5409                 tdrpc->cred = cred;
5410                 tdrpc->p = p;
5411                 tdrpc->inprog = 0;
5412                 tdrpc->err = 0;
5413                 ret = EIO;
5414                 if (nfs_pnfsiothreads != 0) {
5415                         ret = nfs_pnfsio(start_allocatedsdorpc, tdrpc);
5416                         NFSD_DEBUG(4, "nfsrv_allocatedsrpc: nfs_pnfsio=%d\n",
5417                             ret);
5418                 }
5419                 if (ret != 0) {
5420                         ret = nfsrv_allocatedsdorpc(*nmpp, fhp, off, len, NULL,
5421                             cred, p);
5422                         if (nfsds_failerr(ret) && *failposp == -1)
5423                                 *failposp = i;
5424                         else if (error == 0 && ret != 0)
5425                                 error = ret;
5426                 }
5427                 nmpp++;
5428                 fhp++;
5429         }
5430         ret = nfsrv_allocatedsdorpc(*nmpp, fhp, off, len, &na, cred, p);
5431         if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5432                 *failposp = mirrorcnt - 1;
5433         else if (error == 0 && ret != 0)
5434                 error = ret;
5435         if (error == 0)
5436                 error = nfsrv_setextattr(vp, &na, p);
5437         NFSD_DEBUG(4, "nfsrv_allocatedsrpc: aft setextat=%d\n", error);
5438         tdrpc = drpc;
5439         timo = hz / 50;         /* Wait for 20msec. */
5440         if (timo < 1)
5441                 timo = 1;
5442         for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5443                 /* Wait for RPCs on separate threads to complete. */
5444                 while (tdrpc->inprog != 0 && tdrpc->done == 0)
5445                         tsleep(&tdrpc->tsk, PVFS, "srvalds", timo);
5446                 if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5447                         *failposp = i;
5448                 else if (error == 0 && tdrpc->err != 0)
5449                         error = tdrpc->err;
5450         }
5451         free(drpc, M_TEMP);
5452         return (error);
5453 }
5454
5455 static int
5456 nfsrv_setattrdsdorpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5457     struct vnode *vp, struct nfsmount *nmp, struct nfsvattr *nap,
5458     struct nfsvattr *dsnap)
5459 {
5460         uint32_t *tl;
5461         struct nfsrv_descript *nd;
5462         nfsv4stateid_t st;
5463         nfsattrbit_t attrbits;
5464         int error;
5465
5466         NFSD_DEBUG(4, "in nfsrv_setattrdsdorpc\n");
5467         nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5468         /*
5469          * Use a stateid where other is an alternating 01010 pattern and
5470          * seqid is 0xffffffff.  This value is not defined as special by
5471          * the RFC and is used by the FreeBSD NFS server to indicate an
5472          * MDS->DS proxy operation.
5473          */
5474         st.other[0] = 0x55555555;
5475         st.other[1] = 0x55555555;
5476         st.other[2] = 0x55555555;
5477         st.seqid = 0xffffffff;
5478         nfscl_reqstart(nd, NFSPROC_SETATTR, nmp, (u_int8_t *)fhp, sizeof(*fhp),
5479             NULL, NULL, 0, 0, false);
5480         nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5481         nfscl_fillsattr(nd, &nap->na_vattr, vp, NFSSATTR_FULL, 0);
5482
5483         /* Do a Getattr for the attributes that change due to writing. */
5484         NFSZERO_ATTRBIT(&attrbits);
5485         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
5486         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
5487         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
5488         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
5489         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
5490         NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
5491         *tl = txdr_unsigned(NFSV4OP_GETATTR);
5492         (void) nfsrv_putattrbit(nd, &attrbits);
5493         error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
5494             NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5495         if (error != 0) {
5496                 free(nd, M_TEMP);
5497                 return (error);
5498         }
5499         NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: aft setattrrpc=%d\n",
5500             nd->nd_repstat);
5501         /* Get rid of weak cache consistency data for now. */
5502         if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
5503             (ND_NFSV4 | ND_V4WCCATTR)) {
5504                 error = nfsv4_loadattr(nd, NULL, dsnap, NULL, NULL, 0, NULL,
5505                     NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5506                 NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: wcc attr=%d\n", error);
5507                 if (error != 0)
5508                         goto nfsmout;
5509                 /*
5510                  * Get rid of Op# and status for next op.
5511                  */
5512                 NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5513                 if (*++tl != 0)
5514                         nd->nd_flag |= ND_NOMOREDATA;
5515         }
5516         error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
5517         if (error != 0)
5518                 goto nfsmout;
5519         if (nd->nd_repstat != 0)
5520                 error = nd->nd_repstat;
5521         /*
5522          * Get the Change, Size, Access Time and Modify Time attributes and set
5523          * on the Metadata file, so its attributes will be what the file's
5524          * would be if it had been written.
5525          */
5526         if (error == 0) {
5527                 NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5528                 error = nfsv4_loadattr(nd, NULL, dsnap, NULL, NULL, 0, NULL,
5529                     NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5530         }
5531         NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: aft setattr loadattr=%d\n", error);
5532 nfsmout:
5533         m_freem(nd->nd_mrep);
5534         free(nd, M_TEMP);
5535         NFSD_DEBUG(4, "nfsrv_setattrdsdorpc error=%d\n", error);
5536         return (error);
5537 }
5538
5539 struct nfsrvsetattrdsdorpc {
5540         int                     done;
5541         int                     inprog;
5542         struct task             tsk;
5543         fhandle_t               fh;
5544         struct nfsmount         *nmp;
5545         struct vnode            *vp;
5546         struct ucred            *cred;
5547         NFSPROC_T               *p;
5548         struct nfsvattr         na;
5549         struct nfsvattr         dsna;
5550         int                     err;
5551 };
5552
5553 /*
5554  * Start up the thread that will execute nfsrv_setattrdsdorpc().
5555  */
5556 static void
5557 start_setattrdsdorpc(void *arg, int pending)
5558 {
5559         struct nfsrvsetattrdsdorpc *drpc;
5560
5561         drpc = (struct nfsrvsetattrdsdorpc *)arg;
5562         drpc->err = nfsrv_setattrdsdorpc(&drpc->fh, drpc->cred, drpc->p,
5563             drpc->vp, drpc->nmp, &drpc->na, &drpc->dsna);
5564         drpc->done = 1;
5565 }
5566
5567 static int
5568 nfsrv_setattrdsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5569     struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
5570     struct nfsvattr *nap, int *failposp)
5571 {
5572         struct nfsrvsetattrdsdorpc *drpc, *tdrpc = NULL;
5573         struct nfsvattr na;
5574         int error, i, ret, timo;
5575
5576         NFSD_DEBUG(4, "in nfsrv_setattrdsrpc\n");
5577         drpc = NULL;
5578         if (mirrorcnt > 1)
5579                 tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5580                     M_WAITOK);
5581
5582         /*
5583          * Do the setattr RPC for every DS, using a separate kernel process
5584          * for every DS except the last one.
5585          */
5586         error = 0;
5587         for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5588                 tdrpc->done = 0;
5589                 tdrpc->inprog = 0;
5590                 NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5591                 tdrpc->nmp = *nmpp;
5592                 tdrpc->vp = vp;
5593                 tdrpc->cred = cred;
5594                 tdrpc->p = p;
5595                 tdrpc->na = *nap;
5596                 tdrpc->err = 0;
5597                 ret = EIO;
5598                 if (nfs_pnfsiothreads != 0) {
5599                         ret = nfs_pnfsio(start_setattrdsdorpc, tdrpc);
5600                         NFSD_DEBUG(4, "nfsrv_setattrdsrpc: nfs_pnfsio=%d\n",
5601                             ret);
5602                 }
5603                 if (ret != 0) {
5604                         ret = nfsrv_setattrdsdorpc(fhp, cred, p, vp, *nmpp, nap,
5605                             &na);
5606                         if (nfsds_failerr(ret) && *failposp == -1)
5607                                 *failposp = i;
5608                         else if (error == 0 && ret != 0)
5609                                 error = ret;
5610                 }
5611                 nmpp++;
5612                 fhp++;
5613         }
5614         ret = nfsrv_setattrdsdorpc(fhp, cred, p, vp, *nmpp, nap, &na);
5615         if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5616                 *failposp = mirrorcnt - 1;
5617         else if (error == 0 && ret != 0)
5618                 error = ret;
5619         if (error == 0)
5620                 error = nfsrv_setextattr(vp, &na, p);
5621         NFSD_DEBUG(4, "nfsrv_setattrdsrpc: aft setextat=%d\n", error);
5622         tdrpc = drpc;
5623         timo = hz / 50;         /* Wait for 20msec. */
5624         if (timo < 1)
5625                 timo = 1;
5626         for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5627                 /* Wait for RPCs on separate threads to complete. */
5628                 while (tdrpc->inprog != 0 && tdrpc->done == 0)
5629                         tsleep(&tdrpc->tsk, PVFS, "srvsads", timo);
5630                 if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5631                         *failposp = i;
5632                 else if (error == 0 && tdrpc->err != 0)
5633                         error = tdrpc->err;
5634         }
5635         free(drpc, M_TEMP);
5636         return (error);
5637 }
5638
5639 /*
5640  * Do a Setattr of an NFSv4 ACL on the DS file.
5641  */
5642 static int
5643 nfsrv_setacldsdorpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5644     struct vnode *vp, struct nfsmount *nmp, struct acl *aclp)
5645 {
5646         struct nfsrv_descript *nd;
5647         nfsv4stateid_t st;
5648         nfsattrbit_t attrbits;
5649         int error;
5650
5651         NFSD_DEBUG(4, "in nfsrv_setacldsdorpc\n");
5652         nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5653         /*
5654          * Use a stateid where other is an alternating 01010 pattern and
5655          * seqid is 0xffffffff.  This value is not defined as special by
5656          * the RFC and is used by the FreeBSD NFS server to indicate an
5657          * MDS->DS proxy operation.
5658          */
5659         st.other[0] = 0x55555555;
5660         st.other[1] = 0x55555555;
5661         st.other[2] = 0x55555555;
5662         st.seqid = 0xffffffff;
5663         nfscl_reqstart(nd, NFSPROC_SETACL, nmp, (u_int8_t *)fhp, sizeof(*fhp),
5664             NULL, NULL, 0, 0, false);
5665         nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5666         NFSZERO_ATTRBIT(&attrbits);
5667         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_ACL);
5668         /*
5669          * The "vp" argument to nfsv4_fillattr() is only used for vnode_type(),
5670          * so passing in the metadata "vp" will be ok, since it is of
5671          * the same type (VREG).
5672          */
5673         nfsv4_fillattr(nd, NULL, vp, aclp, NULL, NULL, 0, &attrbits, NULL,
5674             NULL, 0, 0, 0, 0, 0, NULL);
5675         error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
5676             NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5677         if (error != 0) {
5678                 free(nd, M_TEMP);
5679                 return (error);
5680         }
5681         NFSD_DEBUG(4, "nfsrv_setacldsdorpc: aft setaclrpc=%d\n",
5682             nd->nd_repstat);
5683         error = nd->nd_repstat;
5684         m_freem(nd->nd_mrep);
5685         free(nd, M_TEMP);
5686         return (error);
5687 }
5688
5689 struct nfsrvsetacldsdorpc {
5690         int                     done;
5691         int                     inprog;
5692         struct task             tsk;
5693         fhandle_t               fh;
5694         struct nfsmount         *nmp;
5695         struct vnode            *vp;
5696         struct ucred            *cred;
5697         NFSPROC_T               *p;
5698         struct acl              *aclp;
5699         int                     err;
5700 };
5701
5702 /*
5703  * Start up the thread that will execute nfsrv_setacldsdorpc().
5704  */
5705 static void
5706 start_setacldsdorpc(void *arg, int pending)
5707 {
5708         struct nfsrvsetacldsdorpc *drpc;
5709
5710         drpc = (struct nfsrvsetacldsdorpc *)arg;
5711         drpc->err = nfsrv_setacldsdorpc(&drpc->fh, drpc->cred, drpc->p,
5712             drpc->vp, drpc->nmp, drpc->aclp);
5713         drpc->done = 1;
5714 }
5715
5716 static int
5717 nfsrv_setacldsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5718     struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt, struct acl *aclp,
5719     int *failposp)
5720 {
5721         struct nfsrvsetacldsdorpc *drpc, *tdrpc = NULL;
5722         int error, i, ret, timo;
5723
5724         NFSD_DEBUG(4, "in nfsrv_setacldsrpc\n");
5725         drpc = NULL;
5726         if (mirrorcnt > 1)
5727                 tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5728                     M_WAITOK);
5729
5730         /*
5731          * Do the setattr RPC for every DS, using a separate kernel process
5732          * for every DS except the last one.
5733          */
5734         error = 0;
5735         for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5736                 tdrpc->done = 0;
5737                 tdrpc->inprog = 0;
5738                 NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5739                 tdrpc->nmp = *nmpp;
5740                 tdrpc->vp = vp;
5741                 tdrpc->cred = cred;
5742                 tdrpc->p = p;
5743                 tdrpc->aclp = aclp;
5744                 tdrpc->err = 0;
5745                 ret = EIO;
5746                 if (nfs_pnfsiothreads != 0) {
5747                         ret = nfs_pnfsio(start_setacldsdorpc, tdrpc);
5748                         NFSD_DEBUG(4, "nfsrv_setacldsrpc: nfs_pnfsio=%d\n",
5749                             ret);
5750                 }
5751                 if (ret != 0) {
5752                         ret = nfsrv_setacldsdorpc(fhp, cred, p, vp, *nmpp,
5753                             aclp);
5754                         if (nfsds_failerr(ret) && *failposp == -1)
5755                                 *failposp = i;
5756                         else if (error == 0 && ret != 0)
5757                                 error = ret;
5758                 }
5759                 nmpp++;
5760                 fhp++;
5761         }
5762         ret = nfsrv_setacldsdorpc(fhp, cred, p, vp, *nmpp, aclp);
5763         if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5764                 *failposp = mirrorcnt - 1;
5765         else if (error == 0 && ret != 0)
5766                 error = ret;
5767         NFSD_DEBUG(4, "nfsrv_setacldsrpc: aft setextat=%d\n", error);
5768         tdrpc = drpc;
5769         timo = hz / 50;         /* Wait for 20msec. */
5770         if (timo < 1)
5771                 timo = 1;
5772         for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5773                 /* Wait for RPCs on separate threads to complete. */
5774                 while (tdrpc->inprog != 0 && tdrpc->done == 0)
5775                         tsleep(&tdrpc->tsk, PVFS, "srvacds", timo);
5776                 if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5777                         *failposp = i;
5778                 else if (error == 0 && tdrpc->err != 0)
5779                         error = tdrpc->err;
5780         }
5781         free(drpc, M_TEMP);
5782         return (error);
5783 }
5784
5785 /*
5786  * Getattr call to the DS for the attributes that change due to writing.
5787  */
5788 static int
5789 nfsrv_getattrdsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5790     struct vnode *vp, struct nfsmount *nmp, struct nfsvattr *nap)
5791 {
5792         struct nfsrv_descript *nd;
5793         int error;
5794         nfsattrbit_t attrbits;
5795         
5796         NFSD_DEBUG(4, "in nfsrv_getattrdsrpc\n");
5797         nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5798         nfscl_reqstart(nd, NFSPROC_GETATTR, nmp, (u_int8_t *)fhp,
5799             sizeof(fhandle_t), NULL, NULL, 0, 0, false);
5800         NFSZERO_ATTRBIT(&attrbits);
5801         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
5802         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
5803         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
5804         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
5805         NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
5806         (void) nfsrv_putattrbit(nd, &attrbits);
5807         error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
5808             NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5809         if (error != 0) {
5810                 free(nd, M_TEMP);
5811                 return (error);
5812         }
5813         NFSD_DEBUG(4, "nfsrv_getattrdsrpc: aft getattrrpc=%d\n",
5814             nd->nd_repstat);
5815         if (nd->nd_repstat == 0) {
5816                 error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0,
5817                     NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL,
5818                     NULL, NULL);
5819                 /*
5820                  * We can only save the updated values in the extended
5821                  * attribute if the vp is exclusively locked.
5822                  * This should happen when any of the following operations
5823                  * occur on the vnode:
5824                  *    Close, Delegreturn, LayoutCommit, LayoutReturn
5825                  * As such, the updated extended attribute should get saved
5826                  * before nfsrv_checkdsattr() returns 0 and allows the cached
5827                  * attributes to be returned without calling this function.
5828                  */
5829                 if (error == 0 && VOP_ISLOCKED(vp) == LK_EXCLUSIVE) {
5830                         error = nfsrv_setextattr(vp, nap, p);
5831                         NFSD_DEBUG(4, "nfsrv_getattrdsrpc: aft setextat=%d\n",
5832                             error);
5833                 }
5834         } else
5835                 error = nd->nd_repstat;
5836         m_freem(nd->nd_mrep);
5837         free(nd, M_TEMP);
5838         NFSD_DEBUG(4, "nfsrv_getattrdsrpc error=%d\n", error);
5839         return (error);
5840 }
5841
5842 /*
5843  * Seek call to a DS.
5844  */
5845 static int
5846 nfsrv_seekdsrpc(fhandle_t *fhp, off_t *offp, int content, bool *eofp,
5847     struct ucred *cred, NFSPROC_T *p, struct nfsmount *nmp)
5848 {
5849         uint32_t *tl;
5850         struct nfsrv_descript *nd;
5851         nfsv4stateid_t st;
5852         int error;
5853         
5854         NFSD_DEBUG(4, "in nfsrv_seekdsrpc\n");
5855         /*
5856          * Use a stateid where other is an alternating 01010 pattern and
5857          * seqid is 0xffffffff.  This value is not defined as special by
5858          * the RFC and is used by the FreeBSD NFS server to indicate an
5859          * MDS->DS proxy operation.
5860          */
5861         st.other[0] = 0x55555555;
5862         st.other[1] = 0x55555555;
5863         st.other[2] = 0x55555555;
5864         st.seqid = 0xffffffff;
5865         nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5866         nfscl_reqstart(nd, NFSPROC_SEEKDS, nmp, (u_int8_t *)fhp,
5867             sizeof(fhandle_t), NULL, NULL, 0, 0, false);
5868         nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5869         NFSM_BUILD(tl, uint32_t *, NFSX_HYPER + NFSX_UNSIGNED);
5870         txdr_hyper(*offp, tl); tl += 2;
5871         *tl = txdr_unsigned(content);
5872         error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
5873             NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5874         if (error != 0) {
5875                 free(nd, M_TEMP);
5876                 return (error);
5877         }
5878         NFSD_DEBUG(4, "nfsrv_seekdsrpc: aft seekrpc=%d\n", nd->nd_repstat);
5879         if (nd->nd_repstat == 0) {
5880                 NFSM_DISSECT(tl, uint32_t *, NFSX_UNSIGNED + NFSX_HYPER);
5881                 if (*tl++ == newnfs_true)
5882                         *eofp = true;
5883                 else
5884                         *eofp = false;
5885                 *offp = fxdr_hyper(tl);
5886         } else
5887                 error = nd->nd_repstat;
5888 nfsmout:
5889         m_freem(nd->nd_mrep);
5890         free(nd, M_TEMP);
5891         NFSD_DEBUG(4, "nfsrv_seekdsrpc error=%d\n", error);
5892         return (error);
5893 }
5894
5895 /*
5896  * Get the device id and file handle for a DS file.
5897  */
5898 int
5899 nfsrv_dsgetdevandfh(struct vnode *vp, NFSPROC_T *p, int *mirrorcntp,
5900     fhandle_t *fhp, char *devid)
5901 {
5902         int buflen, error;
5903         char *buf;
5904
5905         buflen = 1024;
5906         buf = malloc(buflen, M_TEMP, M_WAITOK);
5907         error = nfsrv_dsgetsockmnt(vp, 0, buf, &buflen, mirrorcntp, p, NULL,
5908             fhp, devid, NULL, NULL, NULL, NULL, NULL, NULL);
5909         free(buf, M_TEMP);
5910         return (error);
5911 }
5912
5913 /*
5914  * Do a Lookup against the DS for the filename.
5915  */
5916 static int
5917 nfsrv_pnfslookupds(struct vnode *vp, struct vnode *dvp, struct pnfsdsfile *pf,
5918     struct vnode **nvpp, NFSPROC_T *p)
5919 {
5920         struct nameidata named;
5921         struct ucred *tcred;
5922         char *bufp;
5923         u_long *hashp;
5924         struct vnode *nvp;
5925         int error;
5926
5927         tcred = newnfs_getcred();
5928         named.ni_cnd.cn_nameiop = LOOKUP;
5929         named.ni_cnd.cn_lkflags = LK_SHARED | LK_RETRY;
5930         named.ni_cnd.cn_cred = tcred;
5931         named.ni_cnd.cn_thread = p;
5932         named.ni_cnd.cn_flags = ISLASTCN | LOCKPARENT | LOCKLEAF | SAVENAME;
5933         nfsvno_setpathbuf(&named, &bufp, &hashp);
5934         named.ni_cnd.cn_nameptr = bufp;
5935         named.ni_cnd.cn_namelen = strlen(pf->dsf_filename);
5936         strlcpy(bufp, pf->dsf_filename, NAME_MAX);
5937         NFSD_DEBUG(4, "nfsrv_pnfslookupds: filename=%s\n", bufp);
5938         error = VOP_LOOKUP(dvp, &nvp, &named.ni_cnd);
5939         NFSD_DEBUG(4, "nfsrv_pnfslookupds: aft LOOKUP=%d\n", error);
5940         NFSFREECRED(tcred);
5941         nfsvno_relpathbuf(&named);
5942         if (error == 0)
5943                 *nvpp = nvp;
5944         NFSD_DEBUG(4, "eo nfsrv_pnfslookupds=%d\n", error);
5945         return (error);
5946 }
5947
5948 /*
5949  * Set the file handle to the correct one.
5950  */
5951 static void
5952 nfsrv_pnfssetfh(struct vnode *vp, struct pnfsdsfile *pf, char *devid,
5953     char *fnamep, struct vnode *nvp, NFSPROC_T *p)
5954 {
5955         struct nfsnode *np;
5956         int ret = 0;
5957
5958         np = VTONFS(nvp);
5959         NFSBCOPY(np->n_fhp->nfh_fh, &pf->dsf_fh, NFSX_MYFH);
5960         /*
5961          * We can only do a vn_set_extattr() if the vnode is exclusively
5962          * locked and vn_start_write() has been done.  If devid != NULL or
5963          * fnamep != NULL or the vnode is shared locked, vn_start_write()
5964          * may not have been done.
5965          * If not done now, it will be done on a future call.
5966          */
5967         if (devid == NULL && fnamep == NULL && NFSVOPISLOCKED(vp) ==
5968             LK_EXCLUSIVE)
5969                 ret = vn_extattr_set(vp, IO_NODELOCKED,
5970                     EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile", sizeof(*pf),
5971                     (char *)pf, p);
5972         NFSD_DEBUG(4, "eo nfsrv_pnfssetfh=%d\n", ret);
5973 }
5974
5975 /*
5976  * Cause RPCs waiting on "nmp" to fail.  This is called for a DS mount point
5977  * when the DS has failed.
5978  */
5979 void
5980 nfsrv_killrpcs(struct nfsmount *nmp)
5981 {
5982
5983         /*
5984          * Call newnfs_nmcancelreqs() to cause
5985          * any RPCs in progress on the mount point to
5986          * fail.
5987          * This will cause any process waiting for an
5988          * RPC to complete while holding a vnode lock
5989          * on the mounted-on vnode (such as "df" or
5990          * a non-forced "umount") to fail.
5991          * This will unlock the mounted-on vnode so
5992          * a forced dismount can succeed.
5993          * The NFSMNTP_CANCELRPCS flag should be set when this function is
5994          * called.
5995          */
5996         newnfs_nmcancelreqs(nmp);
5997 }
5998
5999 /*
6000  * Sum up the statfs info for each of the DSs, so that the client will
6001  * receive the total for all DSs.
6002  */
6003 static int
6004 nfsrv_pnfsstatfs(struct statfs *sf, struct mount *mp)
6005 {
6006         struct statfs *tsf;
6007         struct nfsdevice *ds;
6008         struct vnode **dvpp, **tdvpp, *dvp;
6009         uint64_t tot;
6010         int cnt, error = 0, i;
6011
6012         if (nfsrv_devidcnt <= 0)
6013                 return (ENXIO);
6014         dvpp = mallocarray(nfsrv_devidcnt, sizeof(*dvpp), M_TEMP, M_WAITOK);
6015         tsf = malloc(sizeof(*tsf), M_TEMP, M_WAITOK);
6016
6017         /* Get an array of the dvps for the DSs. */
6018         tdvpp = dvpp;
6019         i = 0;
6020         NFSDDSLOCK();
6021         /* First, search for matches for same file system. */
6022         TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
6023                 if (ds->nfsdev_nmp != NULL && ds->nfsdev_mdsisset != 0 &&
6024                     fsidcmp(&ds->nfsdev_mdsfsid, &mp->mnt_stat.f_fsid) == 0) {
6025                         if (++i > nfsrv_devidcnt)
6026                                 break;
6027                         *tdvpp++ = ds->nfsdev_dvp;
6028                 }
6029         }
6030         /*
6031          * If no matches for same file system, total all servers not assigned
6032          * to a file system.
6033          */
6034         if (i == 0) {
6035                 TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
6036                         if (ds->nfsdev_nmp != NULL &&
6037                             ds->nfsdev_mdsisset == 0) {
6038                                 if (++i > nfsrv_devidcnt)
6039                                         break;
6040                                 *tdvpp++ = ds->nfsdev_dvp;
6041                         }
6042                 }
6043         }
6044         NFSDDSUNLOCK();
6045         cnt = i;
6046
6047         /* Do a VFS_STATFS() for each of the DSs and sum them up. */
6048         tdvpp = dvpp;
6049         for (i = 0; i < cnt && error == 0; i++) {
6050                 dvp = *tdvpp++;
6051                 error = VFS_STATFS(dvp->v_mount, tsf);
6052                 if (error == 0) {
6053                         if (sf->f_bsize == 0) {
6054                                 if (tsf->f_bsize > 0)
6055                                         sf->f_bsize = tsf->f_bsize;
6056                                 else
6057                                         sf->f_bsize = 8192;
6058                         }
6059                         if (tsf->f_blocks > 0) {
6060                                 if (sf->f_bsize != tsf->f_bsize) {
6061                                         tot = tsf->f_blocks * tsf->f_bsize;
6062                                         sf->f_blocks += (tot / sf->f_bsize);
6063                                 } else
6064                                         sf->f_blocks += tsf->f_blocks;
6065                         }
6066                         if (tsf->f_bfree > 0) {
6067                                 if (sf->f_bsize != tsf->f_bsize) {
6068                                         tot = tsf->f_bfree * tsf->f_bsize;
6069                                         sf->f_bfree += (tot / sf->f_bsize);
6070                                 } else
6071                                         sf->f_bfree += tsf->f_bfree;
6072                         }
6073                         if (tsf->f_bavail > 0) {
6074                                 if (sf->f_bsize != tsf->f_bsize) {
6075                                         tot = tsf->f_bavail * tsf->f_bsize;
6076                                         sf->f_bavail += (tot / sf->f_bsize);
6077                                 } else
6078                                         sf->f_bavail += tsf->f_bavail;
6079                         }
6080                 }
6081         }
6082         free(tsf, M_TEMP);
6083         free(dvpp, M_TEMP);
6084         return (error);
6085 }
6086
6087 /*
6088  * Set an NFSv4 acl.
6089  */
6090 int
6091 nfsrv_setacl(struct vnode *vp, NFSACL_T *aclp, struct ucred *cred, NFSPROC_T *p)
6092 {
6093         int error;
6094
6095         if (nfsrv_useacl == 0 || nfs_supportsnfsv4acls(vp) == 0) {
6096                 error = NFSERR_ATTRNOTSUPP;
6097                 goto out;
6098         }
6099         /*
6100          * With NFSv4 ACLs, chmod(2) may need to add additional entries.
6101          * Make sure it has enough room for that - splitting every entry
6102          * into two and appending "canonical six" entries at the end.
6103          * Cribbed out of kern/vfs_acl.c - Rick M.
6104          */
6105         if (aclp->acl_cnt > (ACL_MAX_ENTRIES - 6) / 2) {
6106                 error = NFSERR_ATTRNOTSUPP;
6107                 goto out;
6108         }
6109         error = VOP_SETACL(vp, ACL_TYPE_NFS4, aclp, cred, p);
6110         if (error == 0) {
6111                 error = nfsrv_dssetacl(vp, aclp, cred, p);
6112                 if (error == ENOENT)
6113                         error = 0;
6114         }
6115
6116 out:
6117         NFSEXITCODE(error);
6118         return (error);
6119 }
6120
6121 /*
6122  * Seek vnode op call (actually it is a VOP_IOCTL()).
6123  * This function is called with the vnode locked, but unlocks and vrele()s
6124  * the vp before returning.
6125  */
6126 int
6127 nfsvno_seek(struct nfsrv_descript *nd, struct vnode *vp, u_long cmd,
6128     off_t *offp, int content, bool *eofp, struct ucred *cred, NFSPROC_T *p)
6129 {
6130         struct nfsvattr at;
6131         int error, ret;
6132
6133         ASSERT_VOP_LOCKED(vp, "nfsvno_seek vp");
6134         /*
6135          * Attempt to seek on a DS file. A return of ENOENT implies
6136          * there is no DS file to seek on.
6137          */
6138         error = nfsrv_proxyds(vp, 0, 0, cred, p, NFSPROC_SEEKDS, NULL,
6139             NULL, NULL, NULL, NULL, offp, content, eofp);
6140         if (error != ENOENT) {
6141                 vput(vp);
6142                 return (error);
6143         }
6144
6145         /*
6146          * Do the VOP_IOCTL() call.  For the case where *offp == file_size,
6147          * VOP_IOCTL() will return ENXIO.  However, the correct reply for
6148          * NFSv4.2 is *eofp == true and error == 0 for this case.
6149          */
6150         NFSVOPUNLOCK(vp);
6151         error = VOP_IOCTL(vp, cmd, offp, 0, cred, p);
6152         *eofp = false;
6153         if (error == ENXIO || (error == 0 && cmd == FIOSEEKHOLE)) {
6154                 /* Handle the cases where we might be at EOF. */
6155                 ret = nfsvno_getattr(vp, &at, nd, p, 0, NULL);
6156                 if (ret == 0 && *offp == at.na_size) {
6157                         *eofp = true;
6158                         error = 0;
6159                 }
6160                 if (ret != 0 && error == 0)
6161                         error = ret;
6162         }
6163         vrele(vp);
6164         NFSEXITCODE(error);
6165         return (error);
6166 }
6167
6168 /*
6169  * Allocate vnode op call.
6170  */
6171 int
6172 nfsvno_allocate(struct vnode *vp, off_t off, off_t len, struct ucred *cred,
6173     NFSPROC_T *p)
6174 {
6175         int error, trycnt;
6176
6177         ASSERT_VOP_ELOCKED(vp, "nfsvno_allocate vp");
6178         /*
6179          * Attempt to allocate on a DS file. A return of ENOENT implies
6180          * there is no DS file to allocate on.
6181          */
6182         error = nfsrv_proxyds(vp, off, 0, cred, p, NFSPROC_ALLOCATE, NULL,
6183             NULL, NULL, NULL, NULL, &len, 0, NULL);
6184         if (error != ENOENT)
6185                 return (error);
6186         error = 0;
6187
6188         /*
6189          * Do the actual VOP_ALLOCATE(), looping a reasonable number of
6190          * times to achieve completion.
6191          */
6192         trycnt = 0;
6193         while (error == 0 && len > 0 && trycnt++ < 20)
6194                 error = VOP_ALLOCATE(vp, &off, &len);
6195         if (error == 0 && len > 0)
6196                 error = NFSERR_IO;
6197         NFSEXITCODE(error);
6198         return (error);
6199 }
6200
6201 /*
6202  * Get Extended Atribute vnode op into an mbuf list.
6203  */
6204 int
6205 nfsvno_getxattr(struct vnode *vp, char *name, uint32_t maxresp,
6206     struct ucred *cred, struct thread *p, struct mbuf **mpp,
6207     struct mbuf **mpendp, int *lenp)
6208 {
6209         struct iovec *iv;
6210         struct uio io, *uiop = &io;
6211         struct mbuf *m, *m2;
6212         int alen, error, len, tlen;
6213         size_t siz;
6214
6215         /* First, find out the size of the extended attribute. */
6216         error = VOP_GETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, NULL,
6217             &siz, cred, p);
6218         if (error != 0)
6219                 return (NFSERR_NOXATTR);
6220         if (siz > maxresp - NFS_MAXXDR)
6221                 return (NFSERR_XATTR2BIG);
6222         len = siz;
6223         tlen = NFSM_RNDUP(len);
6224         if (tlen > 0) {
6225                 uiop->uio_iovcnt = nfsrv_createiovec(tlen, &m, &m2, &iv);
6226                 uiop->uio_iov = iv;
6227         } else {
6228                 uiop->uio_iovcnt = 0;
6229                 uiop->uio_iov = iv = NULL;
6230                 m = m2 = NULL;
6231         }
6232         uiop->uio_offset = 0;
6233         uiop->uio_resid = tlen;
6234         uiop->uio_rw = UIO_READ;
6235         uiop->uio_segflg = UIO_SYSSPACE;
6236         uiop->uio_td = p;
6237 #ifdef MAC
6238         error = mac_vnode_check_getextattr(cred, vp, EXTATTR_NAMESPACE_USER,
6239             name);
6240         if (error != 0)
6241                 goto out;
6242 #endif
6243
6244         if (tlen > 0)
6245                 error = VOP_GETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, uiop,
6246                     NULL, cred, p);
6247         if (error != 0)
6248                 goto out;
6249         if (uiop->uio_resid > 0) {
6250                 alen = tlen;
6251                 len = tlen - uiop->uio_resid;
6252                 tlen = NFSM_RNDUP(len);
6253                 if (alen != tlen)
6254                         printf("nfsvno_getxattr: weird size read\n");
6255                 if (tlen == 0) {
6256                         m_freem(m);
6257                         m = m2 = NULL;
6258                 } else if (alen != tlen || tlen != len)
6259                         m2 = nfsrv_adj(m, alen - tlen, tlen - len);
6260         }
6261         *lenp = len;
6262         *mpp = m;
6263         *mpendp = m2;
6264
6265 out:
6266         if (error != 0) {
6267                 if (m != NULL)
6268                         m_freem(m);
6269                 *lenp = 0;
6270         }
6271         free(iv, M_TEMP);
6272         NFSEXITCODE(error);
6273         return (error);
6274 }
6275
6276 /*
6277  * Set Extended attribute vnode op from an mbuf list.
6278  */
6279 int
6280 nfsvno_setxattr(struct vnode *vp, char *name, int len, struct mbuf *m,
6281     char *cp, struct ucred *cred, struct thread *p)
6282 {
6283         struct iovec *iv;
6284         struct uio uio, *uiop = &uio;
6285         int cnt, error;
6286
6287         error = 0;
6288 #ifdef MAC
6289         error = mac_vnode_check_setextattr(cred, vp, EXTATTR_NAMESPACE_USER,
6290             name);
6291 #endif
6292         if (error != 0)
6293                 goto out;
6294
6295         uiop->uio_rw = UIO_WRITE;
6296         uiop->uio_segflg = UIO_SYSSPACE;
6297         uiop->uio_td = p;
6298         uiop->uio_offset = 0;
6299         uiop->uio_resid = len;
6300         if (len > 0) {
6301                 error = nfsrv_createiovecw(len, m, cp, &iv, &cnt);
6302                 uiop->uio_iov = iv;
6303                 uiop->uio_iovcnt = cnt;
6304         } else {
6305                 uiop->uio_iov = iv = NULL;
6306                 uiop->uio_iovcnt = 0;
6307         }
6308         if (error == 0) {
6309                 error = VOP_SETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, uiop,
6310                     cred, p);
6311                 free(iv, M_TEMP);
6312         }
6313
6314 out:
6315         NFSEXITCODE(error);
6316         return (error);
6317 }
6318
6319 /*
6320  * Remove Extended attribute vnode op.
6321  */
6322 int
6323 nfsvno_rmxattr(struct nfsrv_descript *nd, struct vnode *vp, char *name,
6324     struct ucred *cred, struct thread *p)
6325 {
6326         int error;
6327
6328         /*
6329          * Get rid of any delegations.  I am not sure why this is required,
6330          * but RFC-8276 says so.
6331          */
6332         error = nfsrv_checkremove(vp, 0, nd, nd->nd_clientid, p);
6333         if (error != 0)
6334                 goto out;
6335 #ifdef MAC
6336         error = mac_vnode_check_deleteextattr(cred, vp, EXTATTR_NAMESPACE_USER,
6337             name);
6338         if (error != 0)
6339                 goto out;
6340 #endif
6341
6342         error = VOP_DELETEEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, cred, p);
6343         if (error == EOPNOTSUPP)
6344                 error = VOP_SETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, NULL,
6345                     cred, p);
6346 out:
6347         NFSEXITCODE(error);
6348         return (error);
6349 }
6350
6351 /*
6352  * List Extended Atribute vnode op into an mbuf list.
6353  */
6354 int
6355 nfsvno_listxattr(struct vnode *vp, uint64_t cookie, struct ucred *cred,
6356     struct thread *p, u_char **bufp, uint32_t *lenp, bool *eofp)
6357 {
6358         struct iovec iv;
6359         struct uio io;
6360         int error;
6361         size_t siz;
6362
6363         *bufp = NULL;
6364         /* First, find out the size of the extended attribute. */
6365         error = VOP_LISTEXTATTR(vp, EXTATTR_NAMESPACE_USER, NULL, &siz, cred,
6366             p);
6367         if (error != 0)
6368                 return (NFSERR_NOXATTR);
6369         if (siz <= cookie) {
6370                 *lenp = 0;
6371                 *eofp = true;
6372                 goto out;
6373         }
6374         if (siz > cookie + *lenp) {
6375                 siz = cookie + *lenp;
6376                 *eofp = false;
6377         } else
6378                 *eofp = true;
6379         /* Just choose a sanity limit of 10Mbytes for malloc(M_TEMP). */
6380         if (siz > 10 * 1024 * 1024) {
6381                 error = NFSERR_XATTR2BIG;
6382                 goto out;
6383         }
6384         *bufp = malloc(siz, M_TEMP, M_WAITOK);
6385         iv.iov_base = *bufp;
6386         iv.iov_len = siz;
6387         io.uio_iovcnt = 1;
6388         io.uio_iov = &iv;
6389         io.uio_offset = 0;
6390         io.uio_resid = siz;
6391         io.uio_rw = UIO_READ;
6392         io.uio_segflg = UIO_SYSSPACE;
6393         io.uio_td = p;
6394 #ifdef MAC
6395         error = mac_vnode_check_listextattr(cred, vp, EXTATTR_NAMESPACE_USER);
6396         if (error != 0)
6397                 goto out;
6398 #endif
6399
6400         error = VOP_LISTEXTATTR(vp, EXTATTR_NAMESPACE_USER, &io, NULL, cred,
6401             p);
6402         if (error != 0)
6403                 goto out;
6404         if (io.uio_resid > 0)
6405                 siz -= io.uio_resid;
6406         *lenp = siz;
6407
6408 out:
6409         if (error != 0) {
6410                 free(*bufp, M_TEMP);
6411                 *bufp = NULL;
6412         }
6413         NFSEXITCODE(error);
6414         return (error);
6415 }
6416
6417 extern int (*nfsd_call_nfsd)(struct thread *, struct nfssvc_args *);
6418
6419 /*
6420  * Called once to initialize data structures...
6421  */
6422 static int
6423 nfsd_modevent(module_t mod, int type, void *data)
6424 {
6425         int error = 0, i;
6426         static int loaded = 0;
6427
6428         switch (type) {
6429         case MOD_LOAD:
6430                 if (loaded)
6431                         goto out;
6432                 newnfs_portinit();
6433                 for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
6434                         mtx_init(&nfsrchash_table[i].mtx, "nfsrtc", NULL,
6435                             MTX_DEF);
6436                         mtx_init(&nfsrcahash_table[i].mtx, "nfsrtca", NULL,
6437                             MTX_DEF);
6438                 }
6439                 mtx_init(&nfsrc_udpmtx, "nfsuc", NULL, MTX_DEF);
6440                 mtx_init(&nfs_v4root_mutex, "nfs4rt", NULL, MTX_DEF);
6441                 mtx_init(&nfsv4root_mnt.mnt_mtx, "nfs4mnt", NULL, MTX_DEF);
6442                 mtx_init(&nfsrv_dontlistlock_mtx, "nfs4dnl", NULL, MTX_DEF);
6443                 mtx_init(&nfsrv_recalllock_mtx, "nfs4rec", NULL, MTX_DEF);
6444                 lockinit(&nfsv4root_mnt.mnt_explock, PVFS, "explock", 0, 0);
6445                 nfsrvd_initcache();
6446                 nfsd_init();
6447                 NFSD_LOCK();
6448                 nfsrvd_init(0);
6449                 NFSD_UNLOCK();
6450                 nfsd_mntinit();
6451 #ifdef VV_DISABLEDELEG
6452                 vn_deleg_ops.vndeleg_recall = nfsd_recalldelegation;
6453                 vn_deleg_ops.vndeleg_disable = nfsd_disabledelegation;
6454 #endif
6455                 nfsd_call_servertimer = nfsrv_servertimer;
6456                 nfsd_call_nfsd = nfssvc_nfsd;
6457                 loaded = 1;
6458                 break;
6459
6460         case MOD_UNLOAD:
6461                 if (newnfs_numnfsd != 0) {
6462                         error = EBUSY;
6463                         break;
6464                 }
6465
6466 #ifdef VV_DISABLEDELEG
6467                 vn_deleg_ops.vndeleg_recall = NULL;
6468                 vn_deleg_ops.vndeleg_disable = NULL;
6469 #endif
6470                 nfsd_call_servertimer = NULL;
6471                 nfsd_call_nfsd = NULL;
6472
6473                 /* Clean out all NFSv4 state. */
6474                 nfsrv_throwawayallstate(curthread);
6475
6476                 /* Clean the NFS server reply cache */
6477                 nfsrvd_cleancache();
6478
6479                 /* Free up the krpc server pool. */
6480                 if (nfsrvd_pool != NULL)
6481                         svcpool_destroy(nfsrvd_pool);
6482
6483                 /* and get rid of the locks */
6484                 for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
6485                         mtx_destroy(&nfsrchash_table[i].mtx);
6486                         mtx_destroy(&nfsrcahash_table[i].mtx);
6487                 }
6488                 mtx_destroy(&nfsrc_udpmtx);
6489                 mtx_destroy(&nfs_v4root_mutex);
6490                 mtx_destroy(&nfsv4root_mnt.mnt_mtx);
6491                 mtx_destroy(&nfsrv_dontlistlock_mtx);
6492                 mtx_destroy(&nfsrv_recalllock_mtx);
6493                 for (i = 0; i < nfsrv_sessionhashsize; i++)
6494                         mtx_destroy(&nfssessionhash[i].mtx);
6495                 if (nfslayouthash != NULL) {
6496                         for (i = 0; i < nfsrv_layouthashsize; i++)
6497                                 mtx_destroy(&nfslayouthash[i].mtx);
6498                         free(nfslayouthash, M_NFSDSESSION);
6499                 }
6500                 lockdestroy(&nfsv4root_mnt.mnt_explock);
6501                 free(nfsclienthash, M_NFSDCLIENT);
6502                 free(nfslockhash, M_NFSDLOCKFILE);
6503                 free(nfssessionhash, M_NFSDSESSION);
6504                 loaded = 0;
6505                 break;
6506         default:
6507                 error = EOPNOTSUPP;
6508                 break;
6509         }
6510
6511 out:
6512         NFSEXITCODE(error);
6513         return (error);
6514 }
6515 static moduledata_t nfsd_mod = {
6516         "nfsd",
6517         nfsd_modevent,
6518         NULL,
6519 };
6520 DECLARE_MODULE(nfsd, nfsd_mod, SI_SUB_VFS, SI_ORDER_ANY);
6521
6522 /* So that loader and kldload(2) can find us, wherever we are.. */
6523 MODULE_VERSION(nfsd, 1);
6524 MODULE_DEPEND(nfsd, nfscommon, 1, 1, 1);
6525 MODULE_DEPEND(nfsd, nfslockd, 1, 1, 1);
6526 MODULE_DEPEND(nfsd, krpc, 1, 1, 1);
6527 MODULE_DEPEND(nfsd, nfssvc, 1, 1, 1);
6528