xref: /freebsd/sys/fs/nfsserver/nfs_nfsdport.c (revision d516e52373e1768ea84bf1ca220671a44f413abe)
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/capsicum.h>
37 #include <sys/extattr.h>
38 
39 /*
40  * Functions that perform the vfs operations required by the routines in
41  * nfsd_serv.c. It is hoped that this change will make the server more
42  * portable.
43  */
44 
45 #include <fs/nfs/nfsport.h>
46 #include <security/mac/mac_framework.h>
47 #include <sys/callout.h>
48 #include <sys/filio.h>
49 #include <sys/hash.h>
50 #include <sys/netexport.h>
51 #include <sys/osd.h>
52 #include <sys/sysctl.h>
53 #include <nlm/nlm_prot.h>
54 #include <nlm/nlm.h>
55 #include <vm/vm_param.h>
56 #include <vm/vnode_pager.h>
57 
58 FEATURE(nfsd, "NFSv4 server");
59 
60 extern u_int32_t newnfs_true, newnfs_false, newnfs_xdrneg1;
61 extern int nfsrv_useacl;
62 extern int newnfs_numnfsd;
63 extern int nfsrv_sessionhashsize;
64 extern struct nfslayouthash *nfslayouthash;
65 extern int nfsrv_layouthashsize;
66 extern struct mtx nfsrv_dslock_mtx;
67 extern int nfs_pnfsiothreads;
68 extern volatile int nfsrv_devidcnt;
69 extern int nfsrv_maxpnfsmirror;
70 extern uint32_t nfs_srvmaxio;
71 extern int nfs_bufpackets;
72 extern u_long sb_max_adj;
73 extern struct nfsv4lock nfsv4rootfs_lock;
74 
75 uint64_t nfsrv_stripesiz = 0;
76 static int nfsrv_maxstripecnt = 1;
77 
78 VNET_DECLARE(int, nfsrv_numnfsd);
79 VNET_DECLARE(struct nfsrv_stablefirst, nfsrv_stablefirst);
80 VNET_DECLARE(SVCPOOL *, nfsrvd_pool);
81 VNET_DECLARE(struct nfsclienthashhead *, nfsclienthash);
82 VNET_DECLARE(struct nfslockhashhead *, nfslockhash);
83 VNET_DECLARE(struct nfssessionhash *, nfssessionhash);
84 VNET_DECLARE(struct nfsv4lock, nfsd_suspend_lock);
85 VNET_DECLARE(struct nfsstatsv1 *, nfsstatsv1_p);
86 
87 NFSDLOCKMUTEX;
88 NFSSTATESPINLOCK;
89 struct mtx nfsrc_udpmtx;
90 struct mtx nfs_v4root_mutex;
91 struct mtx nfsrv_dontlistlock_mtx;
92 struct mtx nfsrv_recalllock_mtx;
93 struct nfsrvfh nfs_pubfh;
94 int nfs_pubfhset = 0;
95 int nfsd_debuglevel = 0;
96 static pid_t nfsd_master_pid = (pid_t)-1;
97 static char nfsd_master_comm[MAXCOMLEN + 1];
98 static struct timeval nfsd_master_start;
99 static uint32_t nfsv4_sysid = 0;
100 static fhandle_t zerofh;
101 
102 VNET_DEFINE(struct proc *, nfsd_master_proc) = NULL;
103 VNET_DEFINE(struct nfsrvhashhead *, nfsrvudphashtbl);
104 VNET_DEFINE(struct nfsrchash_bucket *, nfsrchash_table);
105 VNET_DEFINE(struct nfsrchash_bucket *, nfsrcahash_table);
106 VNET_DEFINE(struct nfsrvfh, nfs_rootfh);
107 VNET_DEFINE(int, nfs_rootfhset) = 0;
108 VNET_DEFINE(struct callout, nfsd_callout);
109 VNET_DEFINE_STATIC(struct mount *, nfsv4root_mnt);
110 VNET_DEFINE_STATIC(struct vfsoptlist, nfsv4root_opt);
111 VNET_DEFINE_STATIC(struct vfsoptlist, nfsv4root_newopt);
112 VNET_DEFINE_STATIC(bool, nfsrv_suspend_nfsd) = false;
113 VNET_DEFINE_STATIC(bool, nfsrv_mntinited) = false;
114 
115 static int nfssvc_srvcall(struct thread *, struct nfssvc_args *,
116     struct ucred *);
117 static void nfsvno_updateds(struct vnode *, struct ucred *, struct thread *);
118 static void nfsvno_pnfsreplenish(void *);
119 static int nfsvno_pnfsusenumfile(struct nameidata *, struct vattr *);
120 
121 int nfsrv_enable_crossmntpt = 1;
122 static int nfs_commit_blks;
123 static int nfs_commit_miss;
124 extern int nfsrv_issuedelegs;
125 extern int nfsrv_dolocallocks;
126 extern struct nfsdevicehead nfsrv_devidhead;
127 
128 /* Map d_type to vnode type. */
129 static uint8_t dtype_to_vnode[DT_WHT + 1] = { VNON, VFIFO, VCHR, VNON, VDIR,
130     VNON, VBLK, VNON, VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON };
131 
132 static int nfsrv_createiovec(int, struct mbuf **, struct mbuf **,
133     struct iovec **);
134 static int nfsrv_createiovec_extpgs(int, int, struct mbuf **,
135     struct mbuf **, struct iovec **);
136 static int nfsrv_createiovecw(int, struct mbuf *, char *, struct iovec **,
137     int *);
138 static void nfs_dtypetovtype(struct nfsvattr *, struct vnode *, uint8_t);
139 static void nfsrv_pnfscreate(struct vnode *, struct vattr *, struct ucred *,
140     NFSPROC_T *);
141 static void nfsrv_pnfsremovesetup(struct vnode *, NFSPROC_T *, struct vnode ***,
142     int *, char *, fhandle_t *);
143 static void nfsrv_pnfsremove(struct vnode **, int, char *, fhandle_t *,
144     NFSPROC_T *);
145 static int nfsrv_proxyds(struct vnode *, off_t, int, struct ucred *,
146     struct thread *, int, struct mbuf **, char *, struct mbuf **,
147     struct nfsvattr *, struct acl *, off_t *, int, bool *);
148 static int nfsrv_setextattr(struct vnode *, struct nfsvattr *, NFSPROC_T *);
149 static int nfsrv_readdsrpc(fhandle_t *, off_t, int, struct ucred *,
150     NFSPROC_T *, struct nfsmount **, int, int, uint64_t, struct mbuf **,
151     struct mbuf **, int *);
152 static int nfsrv_writedsrpc(fhandle_t *, off_t, int, struct ucred *,
153     NFSPROC_T *, struct vnode *, struct nfsmount **, int, int, uint64_t,
154     struct mbuf **, char *, int *);
155 #ifdef notnow
156 static int nfsrv_allocatedsrpc(fhandle_t *, off_t, off_t, struct ucred *,
157     NFSPROC_T *, struct vnode *, struct nfsmount **, int, int *);
158 static int nfsrv_deallocatedsrpc(fhandle_t *, off_t, off_t, struct ucred *,
159     NFSPROC_T *, struct vnode *, struct nfsmount **, int, int *);
160 static int nfsrv_setacldsrpc(fhandle_t *, struct ucred *, NFSPROC_T *,
161     struct vnode *, struct nfsmount **, int, struct acl *, int *);
162 #endif
163 static int nfsrv_setattrdsrpc(fhandle_t *, struct vnode *, struct ucred *,
164     NFSPROC_T *, struct nfsmount **, int, int, struct nfsvattr *, int *);
165 static int nfsrv_setattrdsdorpc(fhandle_t *, struct vnode *, struct ucred *,
166     NFSPROC_T *, struct nfsmount *, struct nfsvattr *, struct nfsvattr *);
167 static int nfsrv_getattrdsrpc(fhandle_t *, struct vnode *, struct ucred *,
168     NFSPROC_T *, struct nfsmount **, int, struct nfsvattr *, int *);
169 static int nfsrv_getattrdsdorpc(fhandle_t *, struct vnode *, struct ucred *,
170     NFSPROC_T *, struct nfsmount *, struct nfsvattr *);
171 #ifdef notnow
172 static int nfsrv_seekdsrpc(fhandle_t *, off_t *, int, bool *, struct ucred *,
173     NFSPROC_T *, struct nfsmount *);
174 #endif
175 static int nfsrv_putfhname(fhandle_t *, char *);
176 static int nfsrv_pnfslookupds(struct vnode *, struct vnode *,
177     struct pnfsdsfile *, struct vnode **, NFSPROC_T *);
178 static void nfsrv_pnfssetfh(struct vnode *, struct pnfsdsfile *, char **,
179     char *, struct vnode *, NFSPROC_T *);
180 static int nfsrv_dsremove(struct vnode *, char *, struct ucred *, NFSPROC_T *);
181 static int nfsrv_dssetacl(struct vnode *, struct acl *, struct ucred *,
182     NFSPROC_T *);
183 static int nfsrv_pnfsstatfs(struct statfs *, struct mount *);
184 
185 int nfs_pnfsio(task_fn_t *, void *);
186 
187 SYSCTL_NODE(_vfs, OID_AUTO, nfsd, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
188     "NFS server");
189 SYSCTL_INT(_vfs_nfsd, OID_AUTO, mirrormnt, CTLFLAG_RW,
190     &nfsrv_enable_crossmntpt, 0, "Enable nfsd to cross mount points");
191 SYSCTL_INT(_vfs_nfsd, OID_AUTO, commit_blks, CTLFLAG_RW, &nfs_commit_blks,
192     0, "");
193 SYSCTL_INT(_vfs_nfsd, OID_AUTO, commit_miss, CTLFLAG_RW, &nfs_commit_miss,
194     0, "");
195 SYSCTL_INT(_vfs_nfsd, OID_AUTO, issue_delegations, CTLFLAG_RW,
196     &nfsrv_issuedelegs, 0, "Enable nfsd to issue delegations");
197 SYSCTL_INT(_vfs_nfsd, OID_AUTO, debuglevel, CTLFLAG_RW, &nfsd_debuglevel,
198     0, "Debug level for NFS server");
199 VNET_DECLARE(int, nfsd_enable_stringtouid);
200 SYSCTL_INT(_vfs_nfsd, OID_AUTO, enable_stringtouid,
201     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(nfsd_enable_stringtouid),
202     0, "Enable nfsd to accept numeric owner_names");
203 /*
204  * vfs.nfsd.pnfsswitchforw and vfs.nfsd.pnfsnumfilemiss are writable so that
205  * statistics can be reset.
206  */
207 static uint64_t nfsrv_pnfsswitchforw = 0;
208 SYSCTL_U64(_vfs_nfsd, OID_AUTO, pnfsswitchforw, CTLFLAG_RW,
209     &nfsrv_pnfsswitchforw, 0, "Number of times replenish switches to forward");
210 static uint64_t nfsrv_pnfsnumfilemiss = 0;
211 SYSCTL_U64(_vfs_nfsd, OID_AUTO, pnfsnumfilemiss, CTLFLAG_RW,
212     &nfsrv_pnfsnumfilemiss, 0, "Number of numfile misses");
213 static u_int nfsrv_pnfsforwcnt = 5;
214 SYSCTL_UINT(_vfs_nfsd, OID_AUTO, pnfsreplenishforwcnt, CTLFLAG_RW,
215     &nfsrv_pnfsforwcnt, 0, "Forward replenish cnt before switch to back");
216 static int nfsrv_pnfsgetdsattr = 1;
217 SYSCTL_INT(_vfs_nfsd, OID_AUTO, pnfsgetdsattr, CTLFLAG_RW,
218     &nfsrv_pnfsgetdsattr, 0, "When set getattr gets DS attributes via RPC");
219 static bool nfsrv_recalldeleg = false;
220 SYSCTL_BOOL(_vfs_nfsd, OID_AUTO, recalldeleg, CTLFLAG_RW,
221     &nfsrv_recalldeleg, 0,
222     "When set remove/rename recalls delegations for same client");
223 
224 /*
225  * nfsrv_dsdirsize can only be increased and only when the nfsd threads are
226  * not running.
227  * The dsN subdirectories for the increased values must have been created
228  * on all DS servers before this increase is done.
229  */
230 u_int	nfsrv_dsdirsize = 20;
231 static int
sysctl_dsdirsize(SYSCTL_HANDLER_ARGS)232 sysctl_dsdirsize(SYSCTL_HANDLER_ARGS)
233 {
234 	int error, newdsdirsize;
235 
236 	newdsdirsize = nfsrv_dsdirsize;
237 	error = sysctl_handle_int(oidp, &newdsdirsize, 0, req);
238 	if (error != 0 || req->newptr == NULL)
239 		return (error);
240 	if (newdsdirsize <= nfsrv_dsdirsize || newdsdirsize > 10000 ||
241 	    newnfs_numnfsd != 0)
242 		return (EINVAL);
243 	nfsrv_dsdirsize = newdsdirsize;
244 	return (0);
245 }
246 SYSCTL_PROC(_vfs_nfsd, OID_AUTO, dsdirsize,
247     CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(nfsrv_dsdirsize),
248     sysctl_dsdirsize, "IU", "Number of dsN subdirs on the DS servers");
249 
250 /*
251  * nfsrv_pnfsmaxnumfiles can only be decreased when the nfsd is not
252  * running.  It can be increased when the nfsd is running, but the
253  * additional numfiles should have been precreated in .pnfshide/numfiles
254  * for all file systems before it is increased.
255  */
256 static u_int nfsrv_pnfsmaxnumfiles = 1000;
257 static int
sysctl_pnfsmaxnumfiles(SYSCTL_HANDLER_ARGS)258 sysctl_pnfsmaxnumfiles(SYSCTL_HANDLER_ARGS)
259 {
260 	int error, new_maxnumfiles;
261 
262 	new_maxnumfiles = nfsrv_pnfsmaxnumfiles;
263 	error = sysctl_handle_int(oidp, &new_maxnumfiles, 0, req);
264 	if (error != 0 || req->newptr == NULL)
265 		return (error);
266 	if (new_maxnumfiles < nfsrv_pnfsmaxnumfiles && newnfs_numnfsd != 0)
267 		return (EBUSY);
268 	if (new_maxnumfiles > 10000 || new_maxnumfiles < 100)
269 		return (EINVAL);
270 	nfsrv_pnfsmaxnumfiles = new_maxnumfiles;
271 	return (0);
272 }
273 SYSCTL_PROC(_vfs_nfsd, OID_AUTO, pnfsmaxnumfiles,
274     CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0,
275     sizeof(nfsrv_pnfsmaxnumfiles), sysctl_pnfsmaxnumfiles,
276     "IU", "Maximum number of entries in .pnfshide/numfiles");
277 
278 /*
279  * nfs_srvmaxio can only be increased and only when the nfsd threads are
280  * not running.  The setting must be a power of 2, with the current limit of
281  * 1Mbyte.
282  */
283 static int
sysctl_srvmaxio(SYSCTL_HANDLER_ARGS)284 sysctl_srvmaxio(SYSCTL_HANDLER_ARGS)
285 {
286 	int error;
287 	u_int newsrvmaxio;
288 	uint64_t tval;
289 
290 	newsrvmaxio = nfs_srvmaxio;
291 	error = sysctl_handle_int(oidp, &newsrvmaxio, 0, req);
292 	if (error != 0 || req->newptr == NULL)
293 		return (error);
294 	if (newsrvmaxio == nfs_srvmaxio)
295 		return (0);
296 	if (newsrvmaxio < nfs_srvmaxio) {
297 		printf("nfsd: vfs.nfsd.srvmaxio can only be increased\n");
298 		return (EINVAL);
299 	}
300 	if (newsrvmaxio > NFS_SRVLIMITIO) {
301 		printf("nfsd: vfs.nfsd.srvmaxio cannot be > %d\n",
302 		    NFS_SRVLIMITIO);
303 		return (EINVAL);
304 	}
305 	if ((newsrvmaxio & (newsrvmaxio - 1)) != 0) {
306 		printf("nfsd: vfs.nfsd.srvmaxio must be a power of 2\n");
307 		return (EINVAL);
308 	}
309 
310 	/*
311 	 * Check that kern.ipc.maxsockbuf is large enough for
312 	 * newsrviomax, given the setting of vfs.nfs.bufpackets.
313 	 */
314 	if ((newsrvmaxio + NFS_MAXXDR) * nfs_bufpackets >
315 	    sb_max_adj) {
316 		/*
317 		 * Suggest vfs.nfs.bufpackets * maximum RPC message for
318 		 * sb_max_adj.
319 		 */
320 		tval = (newsrvmaxio + NFS_MAXXDR) * nfs_bufpackets;
321 
322 		/*
323 		 * Convert suggested sb_max_adj value to a suggested
324 		 * sb_max value, which is what is set via kern.ipc.maxsockbuf.
325 		 * Perform the inverse calculation of (from uipc_sockbuf.c):
326 		 * sb_max_adj = (u_quad_t)sb_max * MCLBYTES /
327 		 *     (MSIZE + MCLBYTES);
328 		 * XXX If the calculation of sb_max_adj from sb_max changes,
329 		 *     this calculation must be changed as well.
330 		 */
331 		tval *= (MSIZE + MCLBYTES);  /* Brackets for readability. */
332 		tval += MCLBYTES - 1;        /* Round up divide. */
333 		tval /= MCLBYTES;
334 		printf("nfsd: set kern.ipc.maxsockbuf to a minimum of "
335 		    "%ju to support %ubyte NFS I/O\n", (uintmax_t)tval,
336 		    newsrvmaxio);
337 		return (EINVAL);
338 	}
339 
340 	NFSD_LOCK();
341 	if (newnfs_numnfsd != 0) {
342 		NFSD_UNLOCK();
343 		printf("nfsd: cannot set vfs.nfsd.srvmaxio when nfsd "
344 		    "threads are running\n");
345 		return (EINVAL);
346 	}
347 
348 
349 	nfs_srvmaxio = newsrvmaxio;
350 	NFSD_UNLOCK();
351 	return (0);
352 }
353 SYSCTL_PROC(_vfs_nfsd, OID_AUTO, srvmaxio,
354     CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0,
355     sysctl_srvmaxio, "IU", "Maximum I/O size in bytes");
356 
357 static int
sysctl_dolocallocks(SYSCTL_HANDLER_ARGS)358 sysctl_dolocallocks(SYSCTL_HANDLER_ARGS)
359 {
360 	int error, igotlock, newdolocallocks;
361 
362 	newdolocallocks = nfsrv_dolocallocks;
363 	error = sysctl_handle_int(oidp, &newdolocallocks, 0, req);
364 	if (error != 0 || req->newptr == NULL)
365 		return (error);
366 	if (newdolocallocks == nfsrv_dolocallocks)
367 		return (0);
368 	if (jailed(curthread->td_ucred))
369 		return (EINVAL);
370 
371 	NFSLOCKV4ROOTMUTEX();
372 	do {
373 		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
374 		    NFSV4ROOTLOCKMUTEXPTR, NULL);
375 	} while (!igotlock);
376 	NFSUNLOCKV4ROOTMUTEX();
377 
378 	nfsrv_dolocallocks = newdolocallocks;
379 
380 	NFSLOCKV4ROOTMUTEX();
381 	nfsv4_unlock(&nfsv4rootfs_lock, 0);
382 	NFSUNLOCKV4ROOTMUTEX();
383 	return (0);
384 }
385 SYSCTL_PROC(_vfs_nfsd, OID_AUTO, enable_locallocks,
386     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0,
387     sysctl_dolocallocks, "IU", "Enable nfsd to acquire local locks on files");
388 
389 static int
sysctl_stripecnt(SYSCTL_HANDLER_ARGS)390 sysctl_stripecnt(SYSCTL_HANDLER_ARGS)
391 {
392 	int error, newmaxstripecnt;
393 
394 	newmaxstripecnt = nfsrv_maxstripecnt;
395 	error = sysctl_handle_int(oidp, &newmaxstripecnt, 0, req);
396 	if (error != 0 || req->newptr == NULL)
397 		return (error);
398 	if (newmaxstripecnt == nfsrv_maxstripecnt)
399 		return (0);
400 	if (newnfs_numnfsd > 0)
401 		return (EPERM);
402 	if (jailed(curthread->td_ucred))
403 		return (EINVAL);
404 	if (newmaxstripecnt <= 0 || newmaxstripecnt > NFSDEV_MAXSTRIPE)
405 		return (EINVAL);
406 	nfsrv_maxstripecnt = newmaxstripecnt;
407 	return (0);
408 }
409 SYSCTL_PROC(_vfs_nfsd, OID_AUTO, pnfsstripecnt,
410     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0,
411     sysctl_stripecnt, "IU", "Set the #stripes for a pNFS server");
412 
413 static int
sysctl_stripeunit(SYSCTL_HANDLER_ARGS)414 sysctl_stripeunit(SYSCTL_HANDLER_ARGS)
415 {
416 	uint64_t newstripesiz;
417 	int error;
418 
419 	newstripesiz = nfsrv_stripesiz;
420 	error = sysctl_handle_64(oidp, &newstripesiz, 0, req);
421 	if (error != 0 || req->newptr == NULL)
422 		return (error);
423 	if (newstripesiz == nfsrv_stripesiz)
424 		return (0);
425 	if (newnfs_numnfsd > 0)
426 		return (EPERM);
427 	if (jailed(curthread->td_ucred))
428 		return (EINVAL);
429 	nfsrv_stripesiz = newstripesiz;
430 	if (newstripesiz == 0)
431 		nfsrv_maxstripecnt = 1;
432 	return (0);
433 }
434 SYSCTL_PROC(_vfs_nfsd, OID_AUTO, pnfsstripeunit,
435     CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0,
436     sysctl_stripeunit, "QU", "Set the stripe unit length for a pNFS server");
437 
438 #define	MAX_REORDERED_RPC	16
439 #define	NUM_HEURISTIC		1031
440 #define	NHUSE_INIT		64
441 #define	NHUSE_INC		16
442 #define	NHUSE_MAX		2048
443 
444 static struct nfsheur {
445 	struct vnode *nh_vp;	/* vp to match (unreferenced pointer) */
446 	off_t nh_nextoff;	/* next offset for sequential detection */
447 	int nh_use;		/* use count for selection */
448 	int nh_seqcount;	/* heuristic */
449 } nfsheur[NUM_HEURISTIC];
450 
451 /*
452  * Heuristic to detect sequential operation.
453  */
454 static struct nfsheur *
nfsrv_sequential_heuristic(struct uio * uio,struct vnode * vp)455 nfsrv_sequential_heuristic(struct uio *uio, struct vnode *vp)
456 {
457 	struct nfsheur *nh;
458 	int hi, try;
459 
460 	/* Locate best candidate. */
461 	try = 32;
462 	hi = ((int)(vm_offset_t)vp / sizeof(struct vnode)) % NUM_HEURISTIC;
463 	nh = &nfsheur[hi];
464 	while (try--) {
465 		if (nfsheur[hi].nh_vp == vp) {
466 			nh = &nfsheur[hi];
467 			break;
468 		}
469 		if (nfsheur[hi].nh_use > 0)
470 			--nfsheur[hi].nh_use;
471 		hi = (hi + 1) % NUM_HEURISTIC;
472 		if (nfsheur[hi].nh_use < nh->nh_use)
473 			nh = &nfsheur[hi];
474 	}
475 
476 	/* Initialize hint if this is a new file. */
477 	if (nh->nh_vp != vp) {
478 		nh->nh_vp = vp;
479 		nh->nh_nextoff = uio->uio_offset;
480 		nh->nh_use = NHUSE_INIT;
481 		if (uio->uio_offset == 0)
482 			nh->nh_seqcount = 4;
483 		else
484 			nh->nh_seqcount = 1;
485 	}
486 
487 	/* Calculate heuristic. */
488 	if ((uio->uio_offset == 0 && nh->nh_seqcount > 0) ||
489 	    uio->uio_offset == nh->nh_nextoff) {
490 		/* See comments in vfs_vnops.c:sequential_heuristic(). */
491 		nh->nh_seqcount += howmany(uio->uio_resid, 16384);
492 		if (nh->nh_seqcount > IO_SEQMAX)
493 			nh->nh_seqcount = IO_SEQMAX;
494 	} else if (qabs(uio->uio_offset - nh->nh_nextoff) <= MAX_REORDERED_RPC *
495 	    imax(vp->v_mount->mnt_stat.f_iosize, uio->uio_resid)) {
496 		/* Probably a reordered RPC, leave seqcount alone. */
497 	} else if (nh->nh_seqcount > 1) {
498 		nh->nh_seqcount /= 2;
499 	} else {
500 		nh->nh_seqcount = 0;
501 	}
502 	nh->nh_use += NHUSE_INC;
503 	if (nh->nh_use > NHUSE_MAX)
504 		nh->nh_use = NHUSE_MAX;
505 	return (nh);
506 }
507 
508 /*
509  * Get attributes into nfsvattr structure.
510  */
511 int
nfsvno_getattr(struct vnode * vp,struct nfsvattr * nvap,struct nfsrv_descript * nd,struct thread * p,int vpislocked,nfsattrbit_t * attrbitp)512 nfsvno_getattr(struct vnode *vp, struct nfsvattr *nvap,
513     struct nfsrv_descript *nd, struct thread *p, int vpislocked,
514     nfsattrbit_t *attrbitp)
515 {
516 	int error, gotattr, lockedit = 0;
517 	struct nfsvattr na;
518 
519 	if (vpislocked == 0) {
520 		/*
521 		 * When vpislocked == 0, the vnode is either exclusively
522 		 * locked by this thread or not locked by this thread.
523 		 * As such, shared lock it, if not exclusively locked.
524 		 */
525 		if (NFSVOPISLOCKED(vp) != LK_EXCLUSIVE) {
526 			lockedit = 1;
527 			NFSVOPLOCK(vp, LK_SHARED | LK_RETRY);
528 		}
529 	}
530 
531 	/*
532 	 * Acquire the Change, Size, TimeAccess, TimeModify and SpaceUsed
533 	 * attributes, as required.
534 	 * This needs to be done for regular files if:
535 	 * - non-NFSv4 RPCs or
536 	 * - when attrbitp == NULL or
537 	 * - an NFSv4 RPC with any of the above attributes in attrbitp.
538 	 * A return of 0 for nfsrv_proxyds() indicates that it has acquired
539 	 * these attributes.  nfsrv_proxyds() will return an error if the
540 	 * server is not a pNFS one.
541 	 */
542 	gotattr = 0;
543 	if (vp->v_type == VREG && nfsrv_devidcnt > 0 && (attrbitp == NULL ||
544 	    (nd->nd_flag & ND_NFSV4) == 0 ||
545 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_CHANGE) ||
546 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SIZE) ||
547 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_TIMEACCESS) ||
548 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_TIMEMODIFY) ||
549 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SPACEUSED))) {
550 		error = nfsrv_proxyds(vp, 0, 0, nd->nd_cred, p,
551 		    NFSPROC_GETATTR, NULL, NULL, NULL, &na, NULL, NULL, 0,
552 		    NULL);
553 		if (error == 0)
554 			gotattr = 1;
555 	}
556 
557 	nvap->na_bsdflags = 0;
558 	nvap->na_flags = 0;
559 	error = VOP_GETATTR(vp, &nvap->na_vattr, nd->nd_cred);
560 	if (lockedit != 0)
561 		NFSVOPUNLOCK(vp);
562 
563 	/*
564 	 * If we got the Change, Size and Modify Time from the DS,
565 	 * replace them.
566 	 */
567 	if (gotattr != 0) {
568 		nvap->na_atime = na.na_atime;
569 		nvap->na_mtime = na.na_mtime;
570 		nvap->na_filerev = na.na_filerev;
571 		nvap->na_size = na.na_size;
572 		nvap->na_bytes = na.na_bytes;
573 	}
574 	NFSD_DEBUG(4, "nfsvno_getattr: gotattr=%d err=%d chg=%ju\n", gotattr,
575 	    error, (uintmax_t)na.na_filerev);
576 
577 	NFSEXITCODE(error);
578 	return (error);
579 }
580 
581 /*
582  * Get a file handle for a vnode.
583  */
584 int
nfsvno_getfh(struct vnode * vp,fhandle_t * fhp,struct thread * p)585 nfsvno_getfh(struct vnode *vp, fhandle_t *fhp, struct thread *p)
586 {
587 	int error;
588 
589 	NFSBZERO((caddr_t)fhp, sizeof(fhandle_t));
590 	fhp->fh_fsid = vp->v_mount->mnt_stat.f_fsid;
591 	error = VOP_VPTOFH(vp, &fhp->fh_fid);
592 
593 	NFSEXITCODE(error);
594 	return (error);
595 }
596 
597 /*
598  * Perform access checking for vnodes obtained from file handles that would
599  * refer to files already opened by a Unix client. You cannot just use
600  * vn_writechk() and VOP_ACCESSX() for two reasons.
601  * 1 - You must check for exported rdonly as well as MNT_RDONLY for the write
602  *     case.
603  * 2 - The owner is to be given access irrespective of mode bits for some
604  *     operations, so that processes that chmod after opening a file don't
605  *     break.
606  */
607 int
nfsvno_accchk(struct vnode * vp,accmode_t accmode,struct ucred * cred,struct nfsexstuff * exp,struct thread * p,int override,int vpislocked,u_int32_t * supportedtypep)608 nfsvno_accchk(struct vnode *vp, accmode_t accmode, struct ucred *cred,
609     struct nfsexstuff *exp, struct thread *p, int override, int vpislocked,
610     u_int32_t *supportedtypep)
611 {
612 	struct vattr vattr;
613 	int error = 0, getret = 0;
614 
615 	if (vpislocked == 0) {
616 		if (NFSVOPLOCK(vp, LK_SHARED) != 0) {
617 			error = EPERM;
618 			goto out;
619 		}
620 	}
621 	if (accmode & VWRITE) {
622 		/* Just vn_writechk() changed to check rdonly */
623 		/*
624 		 * Disallow write attempts on read-only file systems;
625 		 * unless the file is a socket or a block or character
626 		 * device resident on the file system.
627 		 */
628 		if (NFSVNO_EXRDONLY(exp) ||
629 		    (vp->v_mount->mnt_flag & MNT_RDONLY)) {
630 			switch (vp->v_type) {
631 			case VREG:
632 			case VDIR:
633 			case VLNK:
634 				error = EROFS;
635 			default:
636 				break;
637 			}
638 		}
639 		/*
640 		 * If there's shared text associated with
641 		 * the inode, try to free it up once.  If
642 		 * we fail, we can't allow writing.
643 		 */
644 		if (VOP_IS_TEXT(vp) && error == 0)
645 			error = ETXTBSY;
646 	}
647 	if (error != 0) {
648 		if (vpislocked == 0)
649 			NFSVOPUNLOCK(vp);
650 		goto out;
651 	}
652 
653 	/*
654 	 * Should the override still be applied when ACLs are enabled?
655 	 */
656 	error = VOP_ACCESSX(vp, accmode, cred, p);
657 	if (error != 0 && (accmode & (VDELETE | VDELETE_CHILD))) {
658 		/*
659 		 * Try again with VEXPLICIT_DENY, to see if the test for
660 		 * deletion is supported.
661 		 */
662 		error = VOP_ACCESSX(vp, accmode | VEXPLICIT_DENY, cred, p);
663 		if (error == 0) {
664 			if (vp->v_type == VDIR) {
665 				accmode &= ~(VDELETE | VDELETE_CHILD);
666 				accmode |= VWRITE;
667 				error = VOP_ACCESSX(vp, accmode, cred, p);
668 			} else if (supportedtypep != NULL) {
669 				*supportedtypep &= ~NFSACCESS_DELETE;
670 			}
671 		}
672 	}
673 
674 	/*
675 	 * Allow certain operations for the owner (reads and writes
676 	 * on files that are already open).
677 	 */
678 	if (override != NFSACCCHK_NOOVERRIDE &&
679 	    (error == EPERM || error == EACCES)) {
680 		if (cred->cr_uid == 0 && (override & NFSACCCHK_ALLOWROOT))
681 			error = 0;
682 		else if (override & NFSACCCHK_ALLOWOWNER) {
683 			getret = VOP_GETATTR(vp, &vattr, cred);
684 			if (getret == 0 && cred->cr_uid == vattr.va_uid)
685 				error = 0;
686 		}
687 	}
688 	if (vpislocked == 0)
689 		NFSVOPUNLOCK(vp);
690 
691 out:
692 	NFSEXITCODE(error);
693 	return (error);
694 }
695 
696 /*
697  * Set attribute(s) vnop.
698  */
699 int
nfsvno_setattr(struct vnode * vp,struct nfsvattr * nvap,struct ucred * cred,struct thread * p,struct nfsexstuff * exp)700 nfsvno_setattr(struct vnode *vp, struct nfsvattr *nvap, struct ucred *cred,
701     struct thread *p, struct nfsexstuff *exp)
702 {
703 	u_quad_t savsize = 0;
704 	int error, savedit;
705 	time_t savbtime;
706 
707 	/*
708 	 * If this is an exported file system and a pNFS service is running,
709 	 * don't VOP_SETATTR() of size for the MDS file system.
710 	 */
711 	savedit = 0;
712 	error = 0;
713 	if (vp->v_type == VREG && (vp->v_mount->mnt_flag & MNT_EXPORTED) != 0 &&
714 	    nfsrv_devidcnt != 0 && nvap->na_vattr.va_size != VNOVAL &&
715 	    nvap->na_vattr.va_size > 0) {
716 		savsize = nvap->na_vattr.va_size;
717 		nvap->na_vattr.va_size = VNOVAL;
718 		if (nvap->na_vattr.va_uid != (uid_t)VNOVAL ||
719 		    nvap->na_vattr.va_gid != (gid_t)VNOVAL ||
720 		    nvap->na_vattr.va_mode != (mode_t)VNOVAL ||
721 		    nvap->na_vattr.va_atime.tv_sec != VNOVAL ||
722 		    nvap->na_vattr.va_mtime.tv_sec != VNOVAL)
723 			savedit = 1;
724 		else
725 			savedit = 2;
726 	}
727 	if (savedit != 2)
728 		error = VOP_SETATTR(vp, &nvap->na_vattr, cred);
729 	if (savedit != 0)
730 		nvap->na_vattr.va_size = savsize;
731 	if (error == 0 && (nvap->na_vattr.va_uid != (uid_t)VNOVAL ||
732 	    nvap->na_vattr.va_gid != (gid_t)VNOVAL ||
733 	    nvap->na_vattr.va_size != VNOVAL ||
734 	    nvap->na_vattr.va_mode != (mode_t)VNOVAL ||
735 	    nvap->na_vattr.va_atime.tv_sec != VNOVAL ||
736 	    nvap->na_vattr.va_mtime.tv_sec != VNOVAL)) {
737 		/* Never modify birthtime on a DS file. */
738 		savbtime = nvap->na_vattr.va_birthtime.tv_sec;
739 		nvap->na_vattr.va_birthtime.tv_sec = VNOVAL;
740 		/* For a pNFS server, set the attributes on the DS file. */
741 		error = nfsrv_proxyds(vp, 0, 0, cred, p, NFSPROC_SETATTR,
742 		    NULL, NULL, NULL, nvap, NULL, NULL, 0, NULL);
743 		nvap->na_vattr.va_birthtime.tv_sec = savbtime;
744 		if (error == ENOENT)
745 			error = 0;
746 	}
747 	NFSEXITCODE(error);
748 	return (error);
749 }
750 
751 /*
752  * Set up nameidata for a lookup() call and do it.
753  */
754 int
nfsvno_namei(struct nfsrv_descript * nd,struct nameidata * ndp,struct vnode * dp,int islocked,struct nfsexstuff * exp,struct vnode ** retdirp)755 nfsvno_namei(struct nfsrv_descript *nd, struct nameidata *ndp,
756     struct vnode *dp, int islocked, struct nfsexstuff *exp,
757     struct vnode **retdirp)
758 {
759 	struct componentname *cnp = &ndp->ni_cnd;
760 	int i;
761 	struct iovec aiov;
762 	struct uio auio;
763 	int lockleaf = (cnp->cn_flags & LOCKLEAF) != 0, linklen;
764 	int error = 0;
765 	char *cp;
766 
767 	*retdirp = NULL;
768 	cnp->cn_nameptr = cnp->cn_pnbuf;
769 	ndp->ni_lcf = 0;
770 	/*
771 	 * Extract and set starting directory.
772 	 */
773 	if (dp->v_type != VDIR) {
774 		if (islocked)
775 			vput(dp);
776 		else
777 			vrele(dp);
778 		nfsvno_relpathbuf(ndp);
779 		error = ENOTDIR;
780 		goto out1;
781 	}
782 	if (islocked)
783 		NFSVOPUNLOCK(dp);
784 	vref(dp);
785 	*retdirp = dp;
786 	if (NFSVNO_EXRDONLY(exp))
787 		cnp->cn_flags |= RDONLY;
788 	ndp->ni_segflg = UIO_SYSSPACE;
789 
790 	if (nd->nd_flag & ND_PUBLOOKUP) {
791 		ndp->ni_loopcnt = 0;
792 		if (cnp->cn_pnbuf[0] == '/') {
793 			vrele(dp);
794 			/*
795 			 * Check for degenerate pathnames here, since lookup()
796 			 * panics on them.
797 			 */
798 			for (i = 1; i < ndp->ni_pathlen; i++)
799 				if (cnp->cn_pnbuf[i] != '/')
800 					break;
801 			if (i == ndp->ni_pathlen) {
802 				error = NFSERR_ACCES;
803 				goto out;
804 			}
805 			dp = rootvnode;
806 			vref(dp);
807 		}
808 	} else if ((nfsrv_enable_crossmntpt == 0 && NFSVNO_EXPORTED(exp)) ||
809 	    (nd->nd_flag & ND_NFSV4) == 0) {
810 		/*
811 		 * Only cross mount points for NFSv4 when doing a
812 		 * mount while traversing the file system above
813 		 * the mount point, unless nfsrv_enable_crossmntpt is set.
814 		 */
815 		cnp->cn_flags |= NOCROSSMOUNT;
816 	}
817 
818 	/*
819 	 * Initialize for scan, set ni_startdir and bump ref on dp again
820 	 * because lookup() will dereference ni_startdir.
821 	 */
822 
823 	ndp->ni_startdir = dp;
824 	ndp->ni_rootdir = rootvnode;
825 	ndp->ni_topdir = NULL;
826 
827 	if (!lockleaf)
828 		cnp->cn_flags |= LOCKLEAF;
829 	for (;;) {
830 		cnp->cn_nameptr = cnp->cn_pnbuf;
831 		/*
832 		 * Call lookup() to do the real work.  If an error occurs,
833 		 * ndp->ni_vp and ni_dvp are left uninitialized or NULL and
834 		 * we do not have to dereference anything before returning.
835 		 * In either case ni_startdir will be dereferenced and NULLed
836 		 * out.
837 		 */
838 		error = vfs_lookup(ndp);
839 		if (error)
840 			break;
841 
842 		/*
843 		 * Check for encountering a symbolic link.  Trivial
844 		 * termination occurs if no symlink encountered.
845 		 */
846 		if ((cnp->cn_flags & ISSYMLINK) == 0) {
847 			if (ndp->ni_vp && !lockleaf)
848 				NFSVOPUNLOCK(ndp->ni_vp);
849 			break;
850 		}
851 
852 		/*
853 		 * Validate symlink
854 		 */
855 		if ((cnp->cn_flags & LOCKPARENT) && ndp->ni_pathlen == 1)
856 			NFSVOPUNLOCK(ndp->ni_dvp);
857 		if (!(nd->nd_flag & ND_PUBLOOKUP)) {
858 			error = EINVAL;
859 			goto badlink2;
860 		}
861 
862 		if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
863 			error = ELOOP;
864 			goto badlink2;
865 		}
866 		if (ndp->ni_pathlen > 1)
867 			cp = uma_zalloc(namei_zone, M_WAITOK);
868 		else
869 			cp = cnp->cn_pnbuf;
870 		aiov.iov_base = cp;
871 		aiov.iov_len = MAXPATHLEN;
872 		auio.uio_iov = &aiov;
873 		auio.uio_iovcnt = 1;
874 		auio.uio_offset = 0;
875 		auio.uio_rw = UIO_READ;
876 		auio.uio_segflg = UIO_SYSSPACE;
877 		auio.uio_td = NULL;
878 		auio.uio_resid = MAXPATHLEN;
879 		error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
880 		if (error) {
881 		badlink1:
882 			if (ndp->ni_pathlen > 1)
883 				uma_zfree(namei_zone, cp);
884 		badlink2:
885 			vrele(ndp->ni_dvp);
886 			vput(ndp->ni_vp);
887 			break;
888 		}
889 		linklen = MAXPATHLEN - auio.uio_resid;
890 		if (linklen == 0) {
891 			error = ENOENT;
892 			goto badlink1;
893 		}
894 		if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
895 			error = ENAMETOOLONG;
896 			goto badlink1;
897 		}
898 
899 		/*
900 		 * Adjust or replace path
901 		 */
902 		if (ndp->ni_pathlen > 1) {
903 			NFSBCOPY(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
904 			uma_zfree(namei_zone, cnp->cn_pnbuf);
905 			cnp->cn_pnbuf = cp;
906 		} else
907 			cnp->cn_pnbuf[linklen] = '\0';
908 		ndp->ni_pathlen += linklen;
909 
910 		/*
911 		 * Cleanup refs for next loop and check if root directory
912 		 * should replace current directory.  Normally ni_dvp
913 		 * becomes the new base directory and is cleaned up when
914 		 * we loop.  Explicitly null pointers after invalidation
915 		 * to clarify operation.
916 		 */
917 		vput(ndp->ni_vp);
918 		ndp->ni_vp = NULL;
919 
920 		if (cnp->cn_pnbuf[0] == '/') {
921 			vrele(ndp->ni_dvp);
922 			ndp->ni_dvp = ndp->ni_rootdir;
923 			vref(ndp->ni_dvp);
924 		}
925 		ndp->ni_startdir = ndp->ni_dvp;
926 		ndp->ni_dvp = NULL;
927 	}
928 	if (!lockleaf)
929 		cnp->cn_flags &= ~LOCKLEAF;
930 
931 out:
932 	if (error) {
933 		nfsvno_relpathbuf(ndp);
934 		ndp->ni_vp = NULL;
935 		ndp->ni_dvp = NULL;
936 		ndp->ni_startdir = NULL;
937 	} else if ((ndp->ni_cnd.cn_flags & (WANTPARENT|LOCKPARENT)) == 0) {
938 		ndp->ni_dvp = NULL;
939 	}
940 
941 out1:
942 	NFSEXITCODE2(error, nd);
943 	return (error);
944 }
945 
946 /*
947  * Set up a pathname buffer and return a pointer to it and, optionally
948  * set a hash pointer.
949  */
950 void
nfsvno_setpathbuf(struct nameidata * ndp,char ** bufpp,u_long ** hashpp)951 nfsvno_setpathbuf(struct nameidata *ndp, char **bufpp, u_long **hashpp)
952 {
953 	struct componentname *cnp = &ndp->ni_cnd;
954 
955 	cnp->cn_flags |= (NOMACCHECK);
956 	cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
957 	if (hashpp != NULL)
958 		*hashpp = NULL;
959 	*bufpp = cnp->cn_pnbuf;
960 }
961 
962 /*
963  * Release the above path buffer, if not released by nfsvno_namei().
964  */
965 void
nfsvno_relpathbuf(struct nameidata * ndp)966 nfsvno_relpathbuf(struct nameidata *ndp)
967 {
968 
969 	uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
970 	ndp->ni_cnd.cn_pnbuf = NULL;
971 }
972 
973 /*
974  * Readlink vnode op into an mbuf list.
975  */
976 int
nfsvno_readlink(struct vnode * vp,struct ucred * cred,int maxextsiz,struct thread * p,struct mbuf ** mpp,struct mbuf ** mpendp,int * lenp)977 nfsvno_readlink(struct vnode *vp, struct ucred *cred, int maxextsiz,
978     struct thread *p, struct mbuf **mpp, struct mbuf **mpendp, int *lenp)
979 {
980 	struct iovec *iv;
981 	struct uio io, *uiop = &io;
982 	struct mbuf *mp, *mp3;
983 	int len, tlen, error = 0;
984 
985 	len = NFS_MAXPATHLEN;
986 	if (maxextsiz > 0)
987 		uiop->uio_iovcnt = nfsrv_createiovec_extpgs(len, maxextsiz,
988 		    &mp3, &mp, &iv);
989 	else
990 		uiop->uio_iovcnt = nfsrv_createiovec(len, &mp3, &mp, &iv);
991 	uiop->uio_iov = iv;
992 	uiop->uio_offset = 0;
993 	uiop->uio_resid = len;
994 	uiop->uio_rw = UIO_READ;
995 	uiop->uio_segflg = UIO_SYSSPACE;
996 	uiop->uio_td = NULL;
997 	error = VOP_READLINK(vp, uiop, cred);
998 	free(iv, M_TEMP);
999 	if (error) {
1000 		m_freem(mp3);
1001 		*lenp = 0;
1002 		goto out;
1003 	}
1004 	if (uiop->uio_resid > 0) {
1005 		len -= uiop->uio_resid;
1006 		tlen = NFSM_RNDUP(len);
1007 		if (tlen == 0) {
1008 			m_freem(mp3);
1009 			mp3 = mp = NULL;
1010 		} else if (tlen != NFS_MAXPATHLEN || tlen != len)
1011 			mp = nfsrv_adj(mp3, NFS_MAXPATHLEN - tlen,
1012 			    tlen - len);
1013 	}
1014 	*lenp = len;
1015 	*mpp = mp3;
1016 	*mpendp = mp;
1017 
1018 out:
1019 	NFSEXITCODE(error);
1020 	return (error);
1021 }
1022 
1023 /*
1024  * Create an mbuf chain and an associated iovec that can be used to Read
1025  * or Getextattr of data.
1026  * Upon success, return pointers to the first and last mbufs in the chain
1027  * plus the malloc'd iovec and its iovlen.
1028  */
1029 static int
nfsrv_createiovec(int len,struct mbuf ** mpp,struct mbuf ** mpendp,struct iovec ** ivp)1030 nfsrv_createiovec(int len, struct mbuf **mpp, struct mbuf **mpendp,
1031     struct iovec **ivp)
1032 {
1033 	struct mbuf *m, *m2 = NULL, *m3;
1034 	struct iovec *iv;
1035 	int i, left, siz;
1036 
1037 	left = len;
1038 	m3 = NULL;
1039 	/*
1040 	 * Generate the mbuf list with the uio_iov ref. to it.
1041 	 */
1042 	i = 0;
1043 	while (left > 0) {
1044 		NFSMGET(m);
1045 		MCLGET(m, M_WAITOK);
1046 		m->m_len = 0;
1047 		siz = min(M_TRAILINGSPACE(m), left);
1048 		left -= siz;
1049 		i++;
1050 		if (m3)
1051 			m2->m_next = m;
1052 		else
1053 			m3 = m;
1054 		m2 = m;
1055 	}
1056 	*ivp = iv = malloc(i * sizeof (struct iovec), M_TEMP, M_WAITOK);
1057 	m = m3;
1058 	left = len;
1059 	i = 0;
1060 	while (left > 0) {
1061 		if (m == NULL)
1062 			panic("nfsrv_createiovec iov");
1063 		siz = min(M_TRAILINGSPACE(m), left);
1064 		if (siz > 0) {
1065 			iv->iov_base = mtod(m, caddr_t) + m->m_len;
1066 			iv->iov_len = siz;
1067 			m->m_len += siz;
1068 			left -= siz;
1069 			iv++;
1070 			i++;
1071 		}
1072 		m = m->m_next;
1073 	}
1074 	*mpp = m3;
1075 	*mpendp = m2;
1076 	return (i);
1077 }
1078 
1079 /*
1080  * Create an mbuf chain and an associated iovec that can be used to Read
1081  * or Getextattr of data.
1082  * Upon success, return pointers to the first and last mbufs in the chain
1083  * plus the malloc'd iovec and its iovlen.
1084  * Same as above, but creates ext_pgs mbuf(s).
1085  */
1086 static int
nfsrv_createiovec_extpgs(int len,int maxextsiz,struct mbuf ** mpp,struct mbuf ** mpendp,struct iovec ** ivp)1087 nfsrv_createiovec_extpgs(int len, int maxextsiz, struct mbuf **mpp,
1088     struct mbuf **mpendp, struct iovec **ivp)
1089 {
1090 	struct mbuf *m, *m2 = NULL, *m3;
1091 	struct iovec *iv;
1092 	int i, left, pgno, siz;
1093 
1094 	left = len;
1095 	m3 = NULL;
1096 	/*
1097 	 * Generate the mbuf list with the uio_iov ref. to it.
1098 	 */
1099 	i = 0;
1100 	while (left > 0) {
1101 		siz = min(left, maxextsiz);
1102 		m = mb_alloc_ext_plus_pages(siz, M_WAITOK);
1103 		left -= siz;
1104 		i += m->m_epg_npgs;
1105 		if (m3 != NULL)
1106 			m2->m_next = m;
1107 		else
1108 			m3 = m;
1109 		m2 = m;
1110 	}
1111 	*ivp = iv = malloc(i * sizeof (struct iovec), M_TEMP, M_WAITOK);
1112 	m = m3;
1113 	left = len;
1114 	i = 0;
1115 	pgno = 0;
1116 	while (left > 0) {
1117 		if (m == NULL)
1118 			panic("nfsvno_createiovec_extpgs iov");
1119 		siz = min(PAGE_SIZE, left);
1120 		if (siz > 0) {
1121 			iv->iov_base = PHYS_TO_DMAP(m->m_epg_pa[pgno]);
1122 			iv->iov_len = siz;
1123 			m->m_len += siz;
1124 			if (pgno == m->m_epg_npgs - 1)
1125 				m->m_epg_last_len = siz;
1126 			left -= siz;
1127 			iv++;
1128 			i++;
1129 			pgno++;
1130 		}
1131 		if (pgno == m->m_epg_npgs && left > 0) {
1132 			m = m->m_next;
1133 			if (m == NULL)
1134 				panic("nfsvno_createiovec_extpgs iov");
1135 			pgno = 0;
1136 		}
1137 	}
1138 	*mpp = m3;
1139 	*mpendp = m2;
1140 	return (i);
1141 }
1142 
1143 /*
1144  * Read vnode op call into mbuf list.
1145  */
1146 int
nfsvno_read(struct vnode * vp,off_t off,int cnt,struct ucred * cred,int maxextsiz,struct thread * p,struct mbuf ** mpp,struct mbuf ** mpendp)1147 nfsvno_read(struct vnode *vp, off_t off, int cnt, struct ucred *cred,
1148     int maxextsiz, struct thread *p, struct mbuf **mpp,
1149     struct mbuf **mpendp)
1150 {
1151 	struct mbuf *m;
1152 	struct iovec *iv;
1153 	int error = 0, len, tlen, ioflag = 0;
1154 	struct mbuf *m3;
1155 	struct uio io, *uiop = &io;
1156 	struct nfsheur *nh;
1157 
1158 	/*
1159 	 * Attempt to read from a DS file. A return of ENOENT implies
1160 	 * there is no DS file to read.
1161 	 */
1162 	error = nfsrv_proxyds(vp, off, cnt, cred, p, NFSPROC_READDS, mpp,
1163 	    NULL, mpendp, NULL, NULL, NULL, 0, NULL);
1164 	if (error != ENOENT)
1165 		return (error);
1166 
1167 	len = NFSM_RNDUP(cnt);
1168 	if (maxextsiz > 0)
1169 		uiop->uio_iovcnt = nfsrv_createiovec_extpgs(len, maxextsiz,
1170 		    &m3, &m, &iv);
1171 	else
1172 		uiop->uio_iovcnt = nfsrv_createiovec(len, &m3, &m, &iv);
1173 	uiop->uio_iov = iv;
1174 	uiop->uio_offset = off;
1175 	uiop->uio_resid = len;
1176 	uiop->uio_rw = UIO_READ;
1177 	uiop->uio_segflg = UIO_SYSSPACE;
1178 	uiop->uio_td = NULL;
1179 	nh = nfsrv_sequential_heuristic(uiop, vp);
1180 	ioflag |= nh->nh_seqcount << IO_SEQSHIFT;
1181 	/* XXX KDM make this more systematic? */
1182 	VNET(nfsstatsv1_p)->srvbytes[NFSV4OP_READ] += uiop->uio_resid;
1183 	error = VOP_READ(vp, uiop, IO_NODELOCKED | ioflag, cred);
1184 	free(iv, M_TEMP);
1185 	if (error) {
1186 		m_freem(m3);
1187 		*mpp = NULL;
1188 		goto out;
1189 	}
1190 	nh->nh_nextoff = uiop->uio_offset;
1191 	tlen = len - uiop->uio_resid;
1192 	cnt = cnt < tlen ? cnt : tlen;
1193 	tlen = NFSM_RNDUP(cnt);
1194 	if (tlen == 0) {
1195 		m_freem(m3);
1196 		m3 = m = NULL;
1197 	} else if (len != tlen || tlen != cnt)
1198 		m = nfsrv_adj(m3, len - tlen, tlen - cnt);
1199 	*mpp = m3;
1200 	*mpendp = m;
1201 
1202 out:
1203 	NFSEXITCODE(error);
1204 	return (error);
1205 }
1206 
1207 /*
1208  * Create the iovec for the mbuf chain passed in as an argument.
1209  * The "cp" argument is where the data starts within the first mbuf in
1210  * the chain. It returns the iovec and the iovcnt.
1211  */
1212 static int
nfsrv_createiovecw(int retlen,struct mbuf * m,char * cp,struct iovec ** ivpp,int * iovcntp)1213 nfsrv_createiovecw(int retlen, struct mbuf *m, char *cp, struct iovec **ivpp,
1214     int *iovcntp)
1215 {
1216 	struct mbuf *mp;
1217 	struct iovec *ivp;
1218 	int cnt, i, len;
1219 
1220 	/*
1221 	 * Loop through the mbuf chain, counting how many mbufs are a
1222 	 * part of this write operation, so the iovec size is known.
1223 	 */
1224 	cnt = 0;
1225 	len = retlen;
1226 	mp = m;
1227 	i = mtod(mp, caddr_t) + mp->m_len - cp;
1228 	while (len > 0) {
1229 		if (i > 0) {
1230 			len -= i;
1231 			cnt++;
1232 		}
1233 		mp = mp->m_next;
1234 		if (!mp) {
1235 			if (len > 0)
1236 				return (EBADRPC);
1237 		} else
1238 			i = mp->m_len;
1239 	}
1240 
1241 	/* Now, create the iovec. */
1242 	mp = m;
1243 	*ivpp = ivp = malloc(cnt * sizeof (struct iovec), M_TEMP,
1244 	    M_WAITOK);
1245 	*iovcntp = cnt;
1246 	i = mtod(mp, caddr_t) + mp->m_len - cp;
1247 	len = retlen;
1248 	while (len > 0) {
1249 		if (mp == NULL)
1250 			panic("nfsrv_createiovecw");
1251 		if (i > 0) {
1252 			i = min(i, len);
1253 			ivp->iov_base = cp;
1254 			ivp->iov_len = i;
1255 			ivp++;
1256 			len -= i;
1257 		}
1258 		mp = mp->m_next;
1259 		if (mp) {
1260 			i = mp->m_len;
1261 			cp = mtod(mp, caddr_t);
1262 		}
1263 	}
1264 	return (0);
1265 }
1266 
1267 /*
1268  * Write vnode op from an mbuf list.
1269  */
1270 int
nfsvno_write(struct vnode * vp,off_t off,int retlen,int * stable,struct mbuf * mp,char * cp,struct ucred * cred,struct thread * p)1271 nfsvno_write(struct vnode *vp, off_t off, int retlen, int *stable,
1272     struct mbuf *mp, char *cp, struct ucred *cred, struct thread *p)
1273 {
1274 	struct iovec *iv;
1275 	int cnt, ioflags, error;
1276 	struct uio io, *uiop = &io;
1277 	struct nfsheur *nh;
1278 
1279 	/*
1280 	 * Attempt to write to a DS file. A return of ENOENT implies
1281 	 * there is no DS file to write.
1282 	 */
1283 	error = nfsrv_proxyds(vp, off, retlen, cred, p, NFSPROC_WRITEDS,
1284 	    &mp, cp, NULL, NULL, NULL, NULL, 0, NULL);
1285 	if (error != ENOENT) {
1286 		*stable = NFSWRITE_FILESYNC;
1287 		return (error);
1288 	}
1289 
1290 	if (*stable == NFSWRITE_UNSTABLE)
1291 		ioflags = IO_NODELOCKED;
1292 	else
1293 		ioflags = (IO_SYNC | IO_NODELOCKED);
1294 	error = nfsrv_createiovecw(retlen, mp, cp, &iv, &cnt);
1295 	if (error != 0)
1296 		return (error);
1297 	uiop->uio_iov = iv;
1298 	uiop->uio_iovcnt = cnt;
1299 	uiop->uio_resid = retlen;
1300 	uiop->uio_rw = UIO_WRITE;
1301 	uiop->uio_segflg = UIO_SYSSPACE;
1302 	NFSUIOPROC(uiop, p);
1303 	uiop->uio_offset = off;
1304 	nh = nfsrv_sequential_heuristic(uiop, vp);
1305 	ioflags |= nh->nh_seqcount << IO_SEQSHIFT;
1306 	/* XXX KDM make this more systematic? */
1307 	VNET(nfsstatsv1_p)->srvbytes[NFSV4OP_WRITE] += uiop->uio_resid;
1308 	error = VOP_WRITE(vp, uiop, ioflags, cred);
1309 	if (error == 0)
1310 		nh->nh_nextoff = uiop->uio_offset;
1311 	free(iv, M_TEMP);
1312 
1313 	NFSEXITCODE(error);
1314 	return (error);
1315 }
1316 
1317 /*
1318  * Common code for creating a regular file (plus special files for V2).
1319  */
1320 int
nfsvno_createsub(struct nfsrv_descript * nd,struct nameidata * ndp,struct vnode ** vpp,struct nfsvattr * nvap,int * exclusive_flagp,int32_t * cverf,NFSDEV_T rdev,struct nfsexstuff * exp)1321 nfsvno_createsub(struct nfsrv_descript *nd, struct nameidata *ndp,
1322     struct vnode **vpp, struct nfsvattr *nvap, int *exclusive_flagp,
1323     int32_t *cverf, NFSDEV_T rdev, struct nfsexstuff *exp)
1324 {
1325 	u_quad_t tempsize;
1326 	int error;
1327 	struct thread *p = curthread;
1328 
1329 	error = nd->nd_repstat;
1330 	if (!error && ndp->ni_vp == NULL) {
1331 		if (nvap->na_type == VREG || nvap->na_type == VSOCK) {
1332 			error = ENOENT;
1333 			if (nvap->na_type == VREG &&
1334 			    !TAILQ_EMPTY(&nfsrv_devidhead))
1335 				error = nfsvno_pnfsusenumfile(ndp,
1336 				    &nvap->na_vattr);
1337 			if (error == ENOENT) {
1338 				error = VOP_CREATE(ndp->ni_dvp,
1339 				    &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
1340 				/*
1341 				 * For a pNFS server, create the data file
1342 				 * on a DS.
1343 				 */
1344 				if (error == 0 && nvap->na_type == VREG) {
1345 					/*
1346 					 * Create a data file on a DS for a
1347 					 * pNFS server.
1348 					 * This function just returns if not
1349 					 * running a pNFS DS or the creation
1350 					 * fails.
1351 					 */
1352 					nfsrv_pnfscreate(ndp->ni_vp,
1353 					    &nvap->na_vattr, nd->nd_cred, p);
1354 				}
1355 				VOP_VPUT_PAIR(ndp->ni_dvp, error == 0 ?
1356 				    &ndp->ni_vp : NULL, false);
1357 			}
1358 			nfsvno_relpathbuf(ndp);
1359 			if (!error) {
1360 				if (*exclusive_flagp) {
1361 					*exclusive_flagp = 0;
1362 					NFSVNO_ATTRINIT(nvap);
1363 					nvap->na_atime.tv_sec = cverf[0];
1364 					nvap->na_atime.tv_nsec = cverf[1];
1365 					error = VOP_SETATTR(ndp->ni_vp,
1366 					    &nvap->na_vattr, nd->nd_cred);
1367 					if (error != 0) {
1368 						vput(ndp->ni_vp);
1369 						ndp->ni_vp = NULL;
1370 						error = NFSERR_NOTSUPP;
1371 					}
1372 				}
1373 			}
1374 		/*
1375 		 * NFS V2 Only. nfsrvd_mknod() does this for V3.
1376 		 * (This implies, just get out on an error.)
1377 		 */
1378 		} else if (nvap->na_type == VCHR || nvap->na_type == VBLK ||
1379 			nvap->na_type == VFIFO) {
1380 			if (nvap->na_type == VCHR && rdev == 0xffffffff)
1381 				nvap->na_type = VFIFO;
1382                         if (nvap->na_type != VFIFO &&
1383 			    (error = priv_check_cred(nd->nd_cred, PRIV_VFS_MKNOD_DEV))) {
1384 				nfsvno_relpathbuf(ndp);
1385 				vput(ndp->ni_dvp);
1386 				goto out;
1387 			}
1388 			nvap->na_rdev = rdev;
1389 			error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
1390 			    &ndp->ni_cnd, &nvap->na_vattr);
1391 			VOP_VPUT_PAIR(ndp->ni_dvp, error == 0 ? &ndp->ni_vp :
1392 			    NULL, false);
1393 			nfsvno_relpathbuf(ndp);
1394 			if (error)
1395 				goto out;
1396 		} else {
1397 			nfsvno_relpathbuf(ndp);
1398 			vput(ndp->ni_dvp);
1399 			error = ENXIO;
1400 			goto out;
1401 		}
1402 		*vpp = ndp->ni_vp;
1403 	} else {
1404 		/*
1405 		 * Handle cases where error is already set and/or
1406 		 * the file exists.
1407 		 * 1 - clean up the lookup
1408 		 * 2 - iff !error and na_size set, truncate it
1409 		 */
1410 		nfsvno_relpathbuf(ndp);
1411 		*vpp = ndp->ni_vp;
1412 		if (ndp->ni_dvp == *vpp)
1413 			vrele(ndp->ni_dvp);
1414 		else
1415 			vput(ndp->ni_dvp);
1416 		if (!error && nvap->na_size != VNOVAL) {
1417 			error = nfsvno_accchk(*vpp, VWRITE,
1418 			    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1419 			    NFSACCCHK_VPISLOCKED, NULL);
1420 			if (!error) {
1421 				tempsize = nvap->na_size;
1422 				NFSVNO_ATTRINIT(nvap);
1423 				nvap->na_size = tempsize;
1424 				error = nfsvno_setattr(*vpp, nvap,
1425 				    nd->nd_cred, p, exp);
1426 			}
1427 		}
1428 		if (error)
1429 			vput(*vpp);
1430 	}
1431 
1432 out:
1433 	NFSEXITCODE(error);
1434 	return (error);
1435 }
1436 
1437 /*
1438  * Do a mknod vnode op.
1439  */
1440 int
nfsvno_mknod(struct nameidata * ndp,struct nfsvattr * nvap,struct ucred * cred,struct thread * p)1441 nfsvno_mknod(struct nameidata *ndp, struct nfsvattr *nvap, struct ucred *cred,
1442     struct thread *p)
1443 {
1444 	int error = 0;
1445 	__enum_uint8(vtype) vtyp;
1446 
1447 	vtyp = nvap->na_type;
1448 	/*
1449 	 * Iff doesn't exist, create it.
1450 	 */
1451 	if (ndp->ni_vp) {
1452 		nfsvno_relpathbuf(ndp);
1453 		vput(ndp->ni_dvp);
1454 		vrele(ndp->ni_vp);
1455 		error = EEXIST;
1456 		goto out;
1457 	}
1458 	if (vtyp != VCHR && vtyp != VBLK && vtyp != VSOCK && vtyp != VFIFO) {
1459 		nfsvno_relpathbuf(ndp);
1460 		vput(ndp->ni_dvp);
1461 		error = NFSERR_BADTYPE;
1462 		goto out;
1463 	}
1464 	if (vtyp == VSOCK) {
1465 		error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
1466 		    &ndp->ni_cnd, &nvap->na_vattr);
1467 		VOP_VPUT_PAIR(ndp->ni_dvp, error == 0 ? &ndp->ni_vp : NULL,
1468 		    false);
1469 		nfsvno_relpathbuf(ndp);
1470 	} else {
1471 		if (nvap->na_type != VFIFO &&
1472 		    (error = priv_check_cred(cred, PRIV_VFS_MKNOD_DEV))) {
1473 			nfsvno_relpathbuf(ndp);
1474 			vput(ndp->ni_dvp);
1475 			goto out;
1476 		}
1477 		error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
1478 		    &ndp->ni_cnd, &nvap->na_vattr);
1479 		VOP_VPUT_PAIR(ndp->ni_dvp, error == 0 ? &ndp->ni_vp : NULL,
1480 		    false);
1481 		nfsvno_relpathbuf(ndp);
1482 		/*
1483 		 * Since VOP_MKNOD returns the ni_vp, I can't
1484 		 * see any reason to do the lookup.
1485 		 */
1486 	}
1487 
1488 out:
1489 	NFSEXITCODE(error);
1490 	return (error);
1491 }
1492 
1493 /*
1494  * Mkdir vnode op.
1495  */
1496 int
nfsvno_mkdir(struct nameidata * ndp,struct nfsvattr * nvap,uid_t saved_uid,struct ucred * cred,struct thread * p,struct nfsexstuff * exp)1497 nfsvno_mkdir(struct nameidata *ndp, struct nfsvattr *nvap, uid_t saved_uid,
1498     struct ucred *cred, struct thread *p, struct nfsexstuff *exp)
1499 {
1500 	int error = 0;
1501 
1502 	if (ndp->ni_vp != NULL) {
1503 		if (ndp->ni_dvp == ndp->ni_vp)
1504 			vrele(ndp->ni_dvp);
1505 		else
1506 			vput(ndp->ni_dvp);
1507 		vrele(ndp->ni_vp);
1508 		nfsvno_relpathbuf(ndp);
1509 		error = EEXIST;
1510 		goto out;
1511 	}
1512 	error = VOP_MKDIR(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
1513 	    &nvap->na_vattr);
1514 	VOP_VPUT_PAIR(ndp->ni_dvp, error == 0 ? &ndp->ni_vp : NULL, false);
1515 	nfsvno_relpathbuf(ndp);
1516 
1517 out:
1518 	NFSEXITCODE(error);
1519 	return (error);
1520 }
1521 
1522 /*
1523  * symlink vnode op.
1524  */
1525 int
nfsvno_symlink(struct nameidata * ndp,struct nfsvattr * nvap,char * pathcp,int pathlen,int not_v2,uid_t saved_uid,struct ucred * cred,struct thread * p,struct nfsexstuff * exp)1526 nfsvno_symlink(struct nameidata *ndp, struct nfsvattr *nvap, char *pathcp,
1527     int pathlen, int not_v2, uid_t saved_uid, struct ucred *cred, struct thread *p,
1528     struct nfsexstuff *exp)
1529 {
1530 	int error = 0;
1531 
1532 	if (ndp->ni_vp) {
1533 		nfsvno_relpathbuf(ndp);
1534 		if (ndp->ni_dvp == ndp->ni_vp)
1535 			vrele(ndp->ni_dvp);
1536 		else
1537 			vput(ndp->ni_dvp);
1538 		vrele(ndp->ni_vp);
1539 		error = EEXIST;
1540 		goto out;
1541 	}
1542 
1543 	error = VOP_SYMLINK(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
1544 	    &nvap->na_vattr, pathcp);
1545 	/*
1546 	 * Although FreeBSD still had the lookup code in
1547 	 * it for 7/current, there doesn't seem to be any
1548 	 * point, since VOP_SYMLINK() returns the ni_vp.
1549 	 * Just vput it for v2.
1550 	 */
1551 	VOP_VPUT_PAIR(ndp->ni_dvp, &ndp->ni_vp, !not_v2 && error == 0);
1552 	nfsvno_relpathbuf(ndp);
1553 
1554 out:
1555 	NFSEXITCODE(error);
1556 	return (error);
1557 }
1558 
1559 /*
1560  * Parse symbolic link arguments.
1561  * This function has an ugly side effect. It will malloc() an area for
1562  * the symlink and set iov_base to point to it, only if it succeeds.
1563  * So, if it returns with uiop->uio_iov->iov_base != NULL, that must
1564  * be FREE'd later.
1565  */
1566 int
nfsvno_getsymlink(struct nfsrv_descript * nd,struct nfsvattr * nvap,struct thread * p,char ** pathcpp,int * lenp)1567 nfsvno_getsymlink(struct nfsrv_descript *nd, struct nfsvattr *nvap,
1568     struct thread *p, char **pathcpp, int *lenp)
1569 {
1570 	u_int32_t *tl;
1571 	char *pathcp = NULL;
1572 	int error = 0, len;
1573 	struct nfsv2_sattr *sp;
1574 
1575 	*pathcpp = NULL;
1576 	*lenp = 0;
1577 	if ((nd->nd_flag & ND_NFSV3) &&
1578 	    (error = nfsrv_sattr(nd, NULL, nvap, NULL, NULL, NULL, p)))
1579 		goto nfsmout;
1580 	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
1581 	len = fxdr_unsigned(int, *tl);
1582 	if (len > NFS_MAXPATHLEN || len <= 0) {
1583 		error = EBADRPC;
1584 		goto nfsmout;
1585 	}
1586 	pathcp = malloc(len + 1, M_TEMP, M_WAITOK);
1587 	error = nfsrv_mtostr(nd, pathcp, len);
1588 	if (error)
1589 		goto nfsmout;
1590 	if (nd->nd_flag & ND_NFSV2) {
1591 		NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
1592 		nvap->na_mode = fxdr_unsigned(u_int16_t, sp->sa_mode);
1593 	}
1594 	*pathcpp = pathcp;
1595 	*lenp = len;
1596 	NFSEXITCODE2(0, nd);
1597 	return (0);
1598 nfsmout:
1599 	if (pathcp)
1600 		free(pathcp, M_TEMP);
1601 	NFSEXITCODE2(error, nd);
1602 	return (error);
1603 }
1604 
1605 /*
1606  * Remove a non-directory object.
1607  */
1608 int
nfsvno_removesub(struct nameidata * ndp,bool is_v4,struct nfsrv_descript * nd,struct thread * p,struct nfsexstuff * exp)1609 nfsvno_removesub(struct nameidata *ndp, bool is_v4, struct nfsrv_descript *nd,
1610     struct thread *p, struct nfsexstuff *exp)
1611 {
1612 	struct vnode *vp, **dsdvpp, *newvp;
1613 	struct mount *mp;
1614 	int error = 0, dsfilecnt, ret;
1615 	char fname[PNFS_FILENAME_LEN + 1];
1616 	fhandle_t fh;
1617 
1618 	vp = ndp->ni_vp;
1619 	dsdvpp = NULL;
1620 	if (vp->v_type == VDIR) {
1621 		error = NFSERR_ISDIR;
1622 	} else if (is_v4) {
1623 		if (nfsrv_recalldeleg || (nd->nd_flag & ND_NFSV41) == 0)
1624 			error = nfsrv_checkremove(vp, 1, NULL,
1625 			    (nfsquad_t)((u_quad_t)0), p);
1626 		else
1627 			error = nfsrv_checkremove(vp, 1, NULL, nd->nd_clientid,
1628 			    p);
1629 	}
1630 	if (error == 0) {
1631 		nfsrv_pnfsremovesetup(vp, p, &dsdvpp, &dsfilecnt, fname, &fh);
1632 		NFSD_DEBUG(4, "nfsrv_pnfsremovesetup err=%d dsfilecnt=%d\n",
1633 		    error, dsfilecnt);
1634 		error = VOP_REMOVE(ndp->ni_dvp, vp, &ndp->ni_cnd);
1635 	}
1636 	if (error == 0 && dsdvpp != NULL) {
1637 		nfsrv_pnfsremove(dsdvpp, dsfilecnt, fname, &fh, p);
1638 		NFSD_DEBUG(4, "aft nfsrv_pnfsremove dsfilecnt=%d fname=%s\n",
1639 		    dsfilecnt, fname);
1640 	}
1641 	free(dsdvpp, M_TEMP);
1642 	if (is_v4 && (nd->nd_flag & ND_NFSV41) != 0 && error == 0)
1643 		error = nfsvno_getfh(vp, &fh, p);
1644 	if (ndp->ni_dvp == vp)
1645 		vrele(ndp->ni_dvp);
1646 	else
1647 		vput(ndp->ni_dvp);
1648 	vput(vp);
1649 
1650 	/* Use ret to determine if the file still exists. */
1651 	if (is_v4 && (nd->nd_flag & ND_NFSV41) != 0 && error == 0) {
1652 		mp = vfs_busyfs(&fh.fh_fsid);
1653 		if (mp != NULL) {
1654 			/* Find out if the file still exists. */
1655 			ret = VFS_FHTOVP(mp, &fh.fh_fid, LK_SHARED, &newvp);
1656 			if (ret == 0)
1657 				vput(newvp);
1658 			else
1659 				ret = ESTALE;
1660 			vfs_unbusy(mp);
1661 		} else {
1662 			ret = ESTALE;
1663 		}
1664 		if (ret == ESTALE) {
1665 			/* Get rid of any delegation. */
1666 			nfsrv_removedeleg(&fh, nd, p);
1667 		}
1668 	}
1669 
1670 	nfsvno_relpathbuf(ndp);
1671 	NFSEXITCODE(error);
1672 	return (error);
1673 }
1674 
1675 /*
1676  * Remove a directory.
1677  */
1678 int
nfsvno_rmdirsub(struct nameidata * ndp,int is_v4,struct ucred * cred,struct thread * p,struct nfsexstuff * exp)1679 nfsvno_rmdirsub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1680     struct thread *p, struct nfsexstuff *exp)
1681 {
1682 	struct vnode *vp;
1683 	int error = 0;
1684 
1685 	vp = ndp->ni_vp;
1686 	if (vp->v_type != VDIR) {
1687 		error = ENOTDIR;
1688 		goto out;
1689 	}
1690 	/*
1691 	 * No rmdir "." please.
1692 	 */
1693 	if (ndp->ni_dvp == vp) {
1694 		error = EINVAL;
1695 		goto out;
1696 	}
1697 	/*
1698 	 * The root of a mounted filesystem cannot be deleted.
1699 	 */
1700 	if (vp->v_vflag & VV_ROOT)
1701 		error = EBUSY;
1702 out:
1703 	if (!error)
1704 		error = VOP_RMDIR(ndp->ni_dvp, vp, &ndp->ni_cnd);
1705 	if (ndp->ni_dvp == vp)
1706 		vrele(ndp->ni_dvp);
1707 	else
1708 		vput(ndp->ni_dvp);
1709 	vput(vp);
1710 	nfsvno_relpathbuf(ndp);
1711 	NFSEXITCODE(error);
1712 	return (error);
1713 }
1714 
1715 /*
1716  * Rename vnode op.
1717  */
1718 int
nfsvno_rename(struct nameidata * fromndp,struct nameidata * tondp,struct nfsrv_descript * nd,struct thread * p)1719 nfsvno_rename(struct nameidata *fromndp, struct nameidata *tondp,
1720     struct nfsrv_descript *nd, struct thread *p)
1721 {
1722 	struct vnode *fvp, *tvp, *tdvp, **dsdvpp, *newvp;
1723 	struct mount *mp;
1724 	int error = 0, dsfilecnt, ret;
1725 	char fname[PNFS_FILENAME_LEN + 1];
1726 	fhandle_t fh, fh2;
1727 
1728 	dsdvpp = NULL;
1729 	fvp = fromndp->ni_vp;
1730 	if (nd->nd_repstat != 0) {
1731 		vrele(fromndp->ni_dvp);
1732 		vrele(fvp);
1733 		error = nd->nd_repstat;
1734 		goto out1;
1735 	}
1736 	tdvp = tondp->ni_dvp;
1737 	tvp = tondp->ni_vp;
1738 	if (tvp != NULL) {
1739 		if (fvp->v_type == VDIR && tvp->v_type != VDIR) {
1740 			error = (nd->nd_flag & ND_NFSV2) ? EISDIR : EEXIST;
1741 			goto out;
1742 		} else if (fvp->v_type != VDIR && tvp->v_type == VDIR) {
1743 			error = (nd->nd_flag & ND_NFSV2) ? ENOTDIR : EEXIST;
1744 			goto out;
1745 		}
1746 		if (tvp->v_type == VDIR && tvp->v_mountedhere) {
1747 			error = (nd->nd_flag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1748 			goto out;
1749 		}
1750 
1751 		/*
1752 		 * A rename to '.' or '..' results in a prematurely
1753 		 * unlocked vnode on FreeBSD5, so I'm just going to fail that
1754 		 * here.
1755 		 */
1756 		if ((tondp->ni_cnd.cn_namelen == 1 &&
1757 		     tondp->ni_cnd.cn_nameptr[0] == '.') ||
1758 		    (tondp->ni_cnd.cn_namelen == 2 &&
1759 		     tondp->ni_cnd.cn_nameptr[0] == '.' &&
1760 		     tondp->ni_cnd.cn_nameptr[1] == '.')) {
1761 			error = EINVAL;
1762 			goto out;
1763 		}
1764 	}
1765 	if (fvp->v_type == VDIR && fvp->v_mountedhere) {
1766 		error = (nd->nd_flag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1767 		goto out;
1768 	}
1769 	if (fvp->v_mount != tdvp->v_mount) {
1770 		error = (nd->nd_flag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1771 		goto out;
1772 	}
1773 	if (fvp == tdvp) {
1774 		error = (nd->nd_flag & ND_NFSV2) ? ENOTEMPTY : EINVAL;
1775 		goto out;
1776 	}
1777 	if (fvp == tvp) {
1778 		/*
1779 		 * If source and destination are the same, there is
1780 		 * nothing to do. Set error to EJUSTRETURN to indicate
1781 		 * this.
1782 		 */
1783 		error = EJUSTRETURN;
1784 		goto out;
1785 	}
1786 	if (nd->nd_flag & ND_NFSV4) {
1787 		if (NFSVOPLOCK(fvp, LK_EXCLUSIVE) == 0) {
1788 			if (nfsrv_recalldeleg || (nd->nd_flag & ND_NFSV41) == 0)
1789 				error = nfsrv_checkremove(fvp, 0, NULL,
1790 				    (nfsquad_t)((u_quad_t)0), p);
1791 			else
1792 				error = nfsrv_checkremove(fvp, 0, NULL,
1793 				    nd->nd_clientid, p);
1794 			NFSVOPUNLOCK(fvp);
1795 		} else
1796 			error = EPERM;
1797 		if (tvp && !error) {
1798 			if (nfsrv_recalldeleg || (nd->nd_flag & ND_NFSV41) == 0)
1799 				error = nfsrv_checkremove(tvp, 1, NULL,
1800 				    (nfsquad_t)((u_quad_t)0), p);
1801 			else
1802 				error = nfsrv_checkremove(tvp, 1, NULL,
1803 				    nd->nd_clientid, p);
1804 		}
1805 	} else {
1806 		/*
1807 		 * For NFSv2 and NFSv3, try to get rid of the delegation, so
1808 		 * that the NFSv4 client won't be confused by the rename.
1809 		 * Since nfsd_recalldelegation() can only be called on an
1810 		 * unlocked vnode at this point and fvp is the file that will
1811 		 * still exist after the rename, just do fvp.
1812 		 */
1813 		nfsd_recalldelegation(fvp, p);
1814 	}
1815 	if (error == 0 && tvp != NULL) {
1816 		if ((nd->nd_flag & ND_NFSV41) != 0)
1817 			error = nfsvno_getfh(tvp, &fh2, p);
1818 		if (error == 0)
1819 			nfsrv_pnfsremovesetup(tvp, p, &dsdvpp, &dsfilecnt,
1820 			    fname, &fh);
1821 		NFSD_DEBUG(4, "nfsvno_rename: pnfsremovesetup"
1822 		    " dsdvpp=%p\n", dsdvpp);
1823 	}
1824 out:
1825 	mp = NULL;
1826 	if (error == 0) {
1827 		error = VOP_GETWRITEMOUNT(tondp->ni_dvp, &mp);
1828 		if (error == 0) {
1829 			if (mp == NULL) {
1830 				error = ENOENT;
1831 			} else {
1832 				error = lockmgr(&mp->mnt_renamelock,
1833 				    LK_EXCLUSIVE | LK_NOWAIT, NULL);
1834 				if (error != 0)
1835 					error = ERELOOKUP;
1836 			}
1837 		}
1838 	}
1839 	if (error == 0) {
1840 		error = VOP_RENAME(fromndp->ni_dvp, fromndp->ni_vp,
1841 		    &fromndp->ni_cnd, tondp->ni_dvp, tondp->ni_vp,
1842 		    &tondp->ni_cnd, 0);
1843 		lockmgr(&mp->mnt_renamelock, LK_RELEASE, 0);
1844 		vfs_rel(mp);
1845 	} else {
1846 		if (tdvp == tvp)
1847 			vrele(tdvp);
1848 		else
1849 			vput(tdvp);
1850 		if (tvp)
1851 			vput(tvp);
1852 		vrele(fromndp->ni_dvp);
1853 		vrele(fvp);
1854 		if (error == EJUSTRETURN) {
1855 			error = 0;
1856 		} else if (error == ERELOOKUP && mp != NULL) {
1857 			lockmgr(&mp->mnt_renamelock, LK_EXCLUSIVE, 0);
1858 			lockmgr(&mp->mnt_renamelock, LK_RELEASE, 0);
1859 			vfs_rel(mp);
1860 		}
1861 	}
1862 
1863 	/*
1864 	 * If dsdvpp != NULL, it was set up by nfsrv_pnfsremovesetup() and
1865 	 * if the rename succeeded, the DS file for the tvp needs to be
1866 	 * removed.
1867 	 */
1868 	if (error == 0 && dsdvpp != NULL) {
1869 		nfsrv_pnfsremove(dsdvpp, dsfilecnt, fname, &fh, p);
1870 		NFSD_DEBUG(4, "nfsvno_rename: pnfsremove\n");
1871 		free(dsdvpp, M_TEMP);
1872 	}
1873 
1874 	/* Use ret to determine if the file still exists. */
1875 	if ((nd->nd_flag & ND_NFSV41) != 0 && error == 0) {
1876 		mp = vfs_busyfs(&fh2.fh_fsid);
1877 		if (mp != NULL) {
1878 			/* Find out if the file still exists. */
1879 			ret = VFS_FHTOVP(mp, &fh2.fh_fid, LK_SHARED, &newvp);
1880 			if (ret == 0)
1881 				vput(newvp);
1882 			else
1883 				ret = ESTALE;
1884 			vfs_unbusy(mp);
1885 		} else {
1886 			ret = ESTALE;
1887 		}
1888 		if (ret == ESTALE) {
1889 			/* Get rid of any delegation. */
1890 			nfsrv_removedeleg(&fh2, nd, p);
1891 		}
1892 	}
1893 
1894 	nfsvno_relpathbuf(tondp);
1895 out1:
1896 	nfsvno_relpathbuf(fromndp);
1897 	NFSEXITCODE(error);
1898 	return (error);
1899 }
1900 
1901 /*
1902  * Link vnode op.
1903  */
1904 int
nfsvno_link(struct nameidata * ndp,struct vnode * vp,nfsquad_t clientid,struct ucred * cred,struct thread * p,struct nfsexstuff * exp)1905 nfsvno_link(struct nameidata *ndp, struct vnode *vp, nfsquad_t clientid,
1906     struct ucred *cred, struct thread *p, struct nfsexstuff *exp)
1907 {
1908 	struct vnode *xp;
1909 	int error = 0;
1910 
1911 	xp = ndp->ni_vp;
1912 	if (xp != NULL) {
1913 		error = EEXIST;
1914 	} else {
1915 		xp = ndp->ni_dvp;
1916 		if (vp->v_mount != xp->v_mount)
1917 			error = EXDEV;
1918 	}
1919 	if (!error) {
1920 		NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
1921 		if (!VN_IS_DOOMED(vp)) {
1922 			error = nfsrv_checkremove(vp, 0, NULL, clientid, p);
1923 			if (error == 0)
1924 				error = VOP_LINK(ndp->ni_dvp, vp, &ndp->ni_cnd);
1925 		} else
1926 			error = EPERM;
1927 		if (ndp->ni_dvp == vp) {
1928 			vrele(ndp->ni_dvp);
1929 			NFSVOPUNLOCK(vp);
1930 		} else {
1931 			vref(vp);
1932 			VOP_VPUT_PAIR(ndp->ni_dvp, &vp, true);
1933 		}
1934 	} else {
1935 		if (ndp->ni_dvp == ndp->ni_vp)
1936 			vrele(ndp->ni_dvp);
1937 		else
1938 			vput(ndp->ni_dvp);
1939 		if (ndp->ni_vp)
1940 			vrele(ndp->ni_vp);
1941 	}
1942 	nfsvno_relpathbuf(ndp);
1943 	NFSEXITCODE(error);
1944 	return (error);
1945 }
1946 
1947 /*
1948  * Do the fsync() appropriate for the commit.
1949  */
1950 int
nfsvno_fsync(struct vnode * vp,u_int64_t off,int cnt,struct ucred * cred,struct thread * td)1951 nfsvno_fsync(struct vnode *vp, u_int64_t off, int cnt, struct ucred *cred,
1952     struct thread *td)
1953 {
1954 	int error = 0;
1955 
1956 	/*
1957 	 * RFC 1813 3.3.21: if count is 0, a flush from offset to the end of
1958 	 * file is done.  At this time VOP_FSYNC does not accept offset and
1959 	 * byte count parameters so call VOP_FSYNC the whole file for now.
1960 	 * The same is true for NFSv4: RFC 3530 Sec. 14.2.3.
1961 	 * File systems that do not use the buffer cache (as indicated
1962 	 * by MNTK_USES_BCACHE not being set) must use VOP_FSYNC().
1963 	 */
1964 	if (cnt == 0 || cnt > MAX_COMMIT_COUNT ||
1965 	    (vp->v_mount->mnt_kern_flag & MNTK_USES_BCACHE) == 0) {
1966 		/*
1967 		 * Give up and do the whole thing
1968 		 */
1969 		vnode_pager_clean_sync(vp);
1970 		error = VOP_FSYNC(vp, MNT_WAIT, td);
1971 	} else {
1972 		/*
1973 		 * Locate and synchronously write any buffers that fall
1974 		 * into the requested range.  Note:  we are assuming that
1975 		 * f_iosize is a power of 2.
1976 		 */
1977 		int iosize = vp->v_mount->mnt_stat.f_iosize;
1978 		int iomask = iosize - 1;
1979 		struct bufobj *bo;
1980 		daddr_t lblkno;
1981 
1982 		/*
1983 		 * Align to iosize boundary, super-align to page boundary.
1984 		 */
1985 		if (off & iomask) {
1986 			cnt += off & iomask;
1987 			off &= ~(u_quad_t)iomask;
1988 		}
1989 		if (off & PAGE_MASK) {
1990 			cnt += off & PAGE_MASK;
1991 			off &= ~(u_quad_t)PAGE_MASK;
1992 		}
1993 		lblkno = off / iosize;
1994 
1995 		if (vp->v_object && vm_object_mightbedirty(vp->v_object)) {
1996 			VM_OBJECT_WLOCK(vp->v_object);
1997 			vm_object_page_clean(vp->v_object, off, off + cnt,
1998 			    OBJPC_SYNC);
1999 			VM_OBJECT_WUNLOCK(vp->v_object);
2000 		}
2001 
2002 		bo = &vp->v_bufobj;
2003 		BO_LOCK(bo);
2004 		while (cnt > 0) {
2005 			struct buf *bp;
2006 
2007 			/*
2008 			 * If we have a buffer and it is marked B_DELWRI we
2009 			 * have to lock and write it.  Otherwise the prior
2010 			 * write is assumed to have already been committed.
2011 			 *
2012 			 * gbincore() can return invalid buffers now so we
2013 			 * have to check that bit as well (though B_DELWRI
2014 			 * should not be set if B_INVAL is set there could be
2015 			 * a race here since we haven't locked the buffer).
2016 			 */
2017 			if ((bp = gbincore(&vp->v_bufobj, lblkno)) != NULL) {
2018 				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2019 				    LK_INTERLOCK, BO_LOCKPTR(bo)) == ENOLCK) {
2020 					BO_LOCK(bo);
2021 					continue; /* retry */
2022 				}
2023 			    	if ((bp->b_flags & (B_DELWRI|B_INVAL)) ==
2024 				    B_DELWRI) {
2025 					bremfree(bp);
2026 					bp->b_flags &= ~B_ASYNC;
2027 					bwrite(bp);
2028 					++nfs_commit_miss;
2029 				} else
2030 					BUF_UNLOCK(bp);
2031 				BO_LOCK(bo);
2032 			}
2033 			++nfs_commit_blks;
2034 			if (cnt < iosize)
2035 				break;
2036 			cnt -= iosize;
2037 			++lblkno;
2038 		}
2039 		BO_UNLOCK(bo);
2040 	}
2041 	NFSEXITCODE(error);
2042 	return (error);
2043 }
2044 
2045 /*
2046  * Statfs vnode op.
2047  */
2048 int
nfsvno_statfs(struct vnode * vp,struct statfs * sf)2049 nfsvno_statfs(struct vnode *vp, struct statfs *sf)
2050 {
2051 	struct statfs *tsf;
2052 	int error;
2053 
2054 	tsf = NULL;
2055 	if (nfsrv_devidcnt > 0) {
2056 		/* For a pNFS service, get the DS numbers. */
2057 		tsf = malloc(sizeof(*tsf), M_TEMP, M_WAITOK | M_ZERO);
2058 		error = nfsrv_pnfsstatfs(tsf, vp->v_mount);
2059 		if (error != 0) {
2060 			free(tsf, M_TEMP);
2061 			tsf = NULL;
2062 		}
2063 	}
2064 	error = VFS_STATFS(vp->v_mount, sf);
2065 	if (error == 0) {
2066 		if (tsf != NULL) {
2067 			sf->f_blocks = tsf->f_blocks;
2068 			sf->f_bavail = tsf->f_bavail;
2069 			sf->f_bfree = tsf->f_bfree;
2070 			sf->f_bsize = tsf->f_bsize;
2071 		}
2072 		/*
2073 		 * Since NFS handles these values as unsigned on the
2074 		 * wire, there is no way to represent negative values,
2075 		 * so set them to 0. Without this, they will appear
2076 		 * to be very large positive values for clients like
2077 		 * Solaris10.
2078 		 */
2079 		if (sf->f_bavail < 0)
2080 			sf->f_bavail = 0;
2081 		if (sf->f_ffree < 0)
2082 			sf->f_ffree = 0;
2083 	}
2084 	free(tsf, M_TEMP);
2085 	NFSEXITCODE(error);
2086 	return (error);
2087 }
2088 
2089 /*
2090  * Replenish the numfiles in .pnfshide/numfiles directory.
2091  * These files are used for the pNFS server when an Open/Create needs a
2092  * new regular file.  By creating them here asynchronously, we can avoid
2093  * the delay of doing do for Open/Create, since creation requires RPCs to
2094  * the DSs be done.
2095  * (A) - When the sleep times out, work backwards creating
2096  *       one new numfile for each cycle.
2097  *       (Use a timeout of 10msec for now.)
2098  * (B) - When the sleep returns 0, this indicates that a
2099  *       nfsd thread didn't find a numfiles.  For this case
2100  *       be more agressive and create numfiles going forward.
2101  *       (Use a timeout of 1msec for now.)
2102  * Runs as a kernel process.
2103  */
2104 static char pnfshide_name[] = ".pnfshide";
2105 static char numfiles_name[] = "numfiles";
2106 
2107 static void
nfsvno_pnfsreplenish(void * arg)2108 nfsvno_pnfsreplenish(void *arg)
2109 {
2110 	struct componentname cn;
2111 	struct vattr va;
2112 	char name[11];
2113 	struct timespec ts;
2114 	struct mount *mp = (struct mount *)arg, *temp_mp;
2115 	struct ucred *cred;
2116 	struct vnode *numfiledvp, *vp;
2117 	struct netexport *nep;
2118 	uint64_t prevcnt;
2119 	time_t prevsec;
2120 	u_int cnt, last_back, next_back, next_forw, prevrate[4];
2121 	int averate, error, i, timo;
2122 	bool back, use_same_num;
2123 
2124 	cred = curthread->td_ucred;
2125 	if (cred->cr_uid != 0)
2126 		printf("nfsvno_pnfsreplenish: not root\n");
2127 
2128 	/*
2129 	 * Do a lookup for ".pnfshide" in the root dir
2130 	 * of the file system.
2131 	 */
2132 	cn.cn_nameiop = LOOKUP;
2133 	cn.cn_lkflags = LK_SHARED;
2134 	cn.cn_flags = ISLASTCN | NOFOLLOW | LOCKLEAF | NOCROSSMOUNT;
2135 	cn.cn_cred = cred;
2136 	cn.cn_nameptr = pnfshide_name;
2137 	cn.cn_namelen = sizeof(pnfshide_name) - 1;
2138 	vp = NULL;
2139 	numfiledvp = NULL;
2140 	error = vn_lock(mp->mnt_rootvnode, LK_SHARED);
2141 	if (error == 0) {
2142 		error = VOP_LOOKUP(mp->mnt_rootvnode, &vp, &cn);
2143 		VOP_UNLOCK(mp->mnt_rootvnode);
2144 	}
2145 
2146 	/*
2147 	 * Do a lookup for "numfiles" in the ".pnfshide" dir
2148 	 * of the file system.
2149 	 */
2150 	if (error == 0) {
2151 		cn.cn_nameiop = LOOKUP;
2152 		cn.cn_lkflags = LK_SHARED;
2153 		cn.cn_flags = ISLASTCN | NOFOLLOW | LOCKLEAF | NOCROSSMOUNT;
2154 		cn.cn_cred = cred;
2155 		cn.cn_nameptr = numfiles_name;
2156 		cn.cn_namelen = sizeof(numfiles_name) - 1;
2157 		error = VOP_LOOKUP(vp, &numfiledvp, &cn);
2158 		vput(vp);
2159 		if (error == 0)
2160 			VOP_UNLOCK(numfiledvp);
2161 	}
2162 	lockmgr(&mp->mnt_explock, LK_SHARED, NULL);
2163 	nep = mp->mnt_export;
2164 	if (nep != NULL)
2165 		(void)vfs_netexport_acquire(nep);
2166 	lockmgr(&mp->mnt_explock, LK_RELEASE, NULL);
2167 
2168 	/*
2169 	 * The states for ne_pnfsnumfile are as follows:
2170 	 * NULL - Initial state for normal operation.
2171 	 * PNFSD_START - Transition state when the
2172 	 *    replenisher kernel process is starting up.
2173 	 * non-NULL valid pointer - Points to the directory vnode for the
2174 	 *    "numfiles" directory.
2175 	 * PNFSD_STOP - Transition state when the
2176 	 *    replenisher kernel process is shutting down.
2177 	 * PNFSD_STOPPED - Replenisher kernel process has stopped and
2178 	 *    vrele()'d the "numfiles" directory vnode.
2179 	 */
2180 	if (error != 0 || nep == NULL) {
2181 		if (error == 0)
2182 			error = ENOENT;
2183 		goto out;
2184 	}
2185 	MNTEXP_LOCK(nep);
2186 	KASSERT(nep->ne_pnfsnumfile == PNFSD_START ||
2187 	    nep->ne_pnfsnumfile == PNFSD_STOP,
2188 	    ("nfsvno_pnfsreplenish: ne_pnfsnumfile not PNFSD_START/STOP"));
2189 	if (nep->ne_pnfsnumfile == PNFSD_START) {
2190 		nep->ne_pnfsnumfile = numfiledvp;
2191 		wakeup(&nep->ne_pnfsnumfile);
2192 	}
2193 	MNTEXP_UNLOCK(nep);
2194 
2195 	VATTR_NULL(&va);
2196 	va.va_mode = 0644;
2197 	va.va_type = VREG;
2198 	timo = hz / 1000;
2199 	if (timo == 0)
2200 		timo = 1;
2201 	cnt = 5;
2202 	back = false;
2203 	use_same_num = false;
2204 	prevcnt = 0;
2205 	for (i = 0; i < 4; i++)
2206 		prevrate[i] = 1;
2207 	prevsec = 0;
2208 	averate = 100;
2209 	last_back = next_back = next_forw = UINT_MAX;
2210 
2211 	/* Loop around sleeping and then doing (A) or (B) */
2212 	for (;;) {
2213 		/* Sample replenish rate once/sec. */
2214 		getnanouptime(&ts);
2215 		if (ts.tv_sec != prevsec) {
2216 			/* Calculate a moving ave. of creates/sec. */
2217 			prevsec = ts.tv_sec;
2218 			for (i = 0; i < 3; i++)
2219 				prevrate[i + 1] = prevrate[i];
2220 			prevrate[0] = atomic_load_int(&nep->ne_pnfsnumcnt) -
2221 			    prevcnt;
2222 			if (prevrate[0] < 1)
2223 				prevrate[0] = 1;
2224 			prevcnt = atomic_load_int(&nep->ne_pnfsnumcnt);
2225 			averate = prevrate[0] * 4 / 10 + prevrate[1] * 3 / 10 +
2226 			    prevrate[2] * 2 / 10 + prevrate[3] / 10;
2227 			if (averate < 1)
2228 				averate = 1;
2229 			averate *= 2;
2230 		}
2231 
2232 		if (cnt == 0) {
2233 			error = tsleep(&mp->mnt_export, PVFS, "pnfsrpl", timo);
2234 			if (error == ETIMEDOUT || error == EAGAIN) {
2235 				if (!back)
2236 					next_back = last_back;
2237 				back = true;
2238 				timo = hz / averate;
2239 				if (timo == 0)
2240 					timo = 1;
2241 			} else {
2242 				if (back) {
2243 					next_forw = UINT_MAX;
2244 					last_back = next_back;
2245 				}
2246 				back = false;
2247 				cnt = nfsrv_pnfsforwcnt;
2248 				timo = hz / 1000;
2249 				if (timo == 0)
2250 					timo = 1;
2251 				nfsrv_pnfsswitchforw++;
2252 			}
2253 		}
2254 
2255 		/* Check for exports having gone away. */
2256 		if (mp->mnt_export == NULL)
2257 			break;
2258 		/* And check for replenisher being stopped. */
2259 		MNTEXP_LOCK(nep);
2260 		if (nep->ne_pnfsnumfile != PNFSD_START &&
2261 		    nep->ne_pnfsnumfile != PNFSD_STOP) {
2262 			KASSERT(numfiledvp == nep->ne_pnfsnumfile,
2263 			    ("nfsvno_pnfsreplenish: numfiledvp changed"));
2264 			MNTEXP_UNLOCK(nep);
2265 		} else {
2266 			MNTEXP_UNLOCK(nep);
2267 			break;
2268 		}
2269 
2270 		if (back) {
2271 			/* This is (A) in this function's comment above. */
2272 			error = vn_start_write(numfiledvp, &temp_mp, V_NOWAIT);
2273 			if (error == 0)
2274 				error = vn_lock(numfiledvp, LK_EXCLUSIVE |
2275 				    LK_NOWAIT);
2276 			if (error != 0 && temp_mp != NULL)
2277 				vn_finished_write(temp_mp);
2278 			if (error == EBUSY || error == EWOULDBLOCK)
2279 				continue;
2280 			if (error != 0)
2281 				break;
2282 			if (next_back == UINT_MAX) {
2283 				if (nep->ne_pnfsnextfile == 0)
2284 					next_back = nfsrv_pnfsmaxnumfiles - 1;
2285 				else
2286 					next_back = nep->ne_pnfsnextfile - 1;
2287 			} else if (!use_same_num) {
2288 				if (next_back == 0)
2289 					next_back = nfsrv_pnfsmaxnumfiles - 1;
2290 				else
2291 					next_back--;
2292 			}
2293 			snprintf(name, sizeof(name), "%d", next_back);
2294 		} else {
2295 			/* This is (B) in this function's comment, above. */
2296 			vn_start_write(numfiledvp, &temp_mp, V_WAIT);
2297 			error = vn_lock(numfiledvp, LK_EXCLUSIVE);
2298 			if (error != 0 && temp_mp != NULL)
2299 				vn_finished_write(temp_mp);
2300 			if (error != 0)
2301 				break;
2302 			if (next_forw == UINT_MAX)
2303 				next_forw = nep->ne_pnfsnextfile;
2304 			else if (!use_same_num)
2305 				next_forw = (next_forw + 1) %
2306 				    nfsrv_pnfsmaxnumfiles;
2307 			snprintf(name, sizeof(name), "%d", next_forw);
2308 		}
2309 		use_same_num = false;
2310 
2311 		/* Do a lookup for the file. */
2312 		cn.cn_nameiop = CREATE;
2313 		cn.cn_lkflags = LK_EXCLUSIVE;
2314 		cn.cn_flags = ISLASTCN | NOFOLLOW | LOCKLEAF | LOCKPARENT |
2315 		    NOCROSSMOUNT | MAKEENTRY;
2316 		cn.cn_cred = cred;
2317 		cn.cn_nameptr = name;
2318 		cn.cn_namelen = strlen(name);
2319 		vref(numfiledvp);
2320 		error = VOP_LOOKUP(numfiledvp, &vp, &cn);
2321 		if (error == 0) {
2322 			VOP_VPUT_PAIR(numfiledvp, &vp, true);
2323 			if (temp_mp != NULL)
2324 				vn_finished_write(temp_mp);
2325 			if (back) {
2326 				last_back = next_back = UINT_MAX;
2327 				timo = hz / 10;
2328 				if (timo == 0)
2329 					timo = 1;
2330 			} else {
2331 				timo = hz / 100;
2332 				if (timo == 0)
2333 					timo = 1;
2334 			}
2335 			cnt = 0;
2336 			continue;
2337 		} else if (error != ENOENT && error != EJUSTRETURN) {
2338 			VOP_VPUT_PAIR(numfiledvp, NULL, true);
2339 			if (temp_mp != NULL)
2340 				vn_finished_write(temp_mp);
2341 			if (error == ERELOOKUP) {
2342 				use_same_num = true;
2343 				continue;
2344 			}
2345 			printf("nfsvno_pnfsreplenish: lookup failed %d\n",
2346 			    error);
2347 			break;
2348 		}
2349 
2350 		/* Create the numfile and its DS file(s). */
2351 		error = VOP_CREATE(numfiledvp, &vp, &cn, &va);
2352 		if (error == 0) {
2353 			/*
2354 			 * Create a data file on a DS for a pNFS
2355 			 * server. This function just returns if
2356 			 * not running a pNFS DS or the creation
2357 			 * fails.
2358 			 */
2359 			nfsrv_pnfscreate(vp, &va, cred, curthread);
2360 		} else
2361 			printf("nfsvno_pnfsreplenish: vop_create failed %d\n",
2362 			    error);
2363 		VOP_VPUT_PAIR(numfiledvp, error == 0 ? &vp : NULL, true);
2364 		if (temp_mp != NULL)
2365 			vn_finished_write(temp_mp);
2366 		cnt = cnt > 0 ? cnt - 1 : 0;
2367 	}
2368 out:
2369 	if (numfiledvp != NULL)
2370 		vrele(numfiledvp);
2371 	if (nep != NULL) {
2372 		MNTEXP_LOCK(nep);
2373 		nep->ne_pnfsnumfile = PNFSD_STOPPED;
2374 		wakeup(&mp->mnt_explock);
2375 		MNTEXP_UNLOCK(nep);
2376 		vfs_netexport_release(nep);
2377 	} else
2378 		wakeup(&mp->mnt_explock);
2379 	kproc_exit(0);
2380 }
2381 
2382 /*
2383  * Do a lookup of a file in the .numfiles directory.
2384  * If successful, use VOP_SETATTR() to set the uid/gid/mode and
2385  * then VOP_LINK()/VOP_REMOVE() the num file.
2386  * Return ENOENT to indicate that nfsvno_open() should fall back to
2387  * doing VOP_CREATE(), other errors for failure.
2388  * XXX This code probably is not correct for a stacked file
2389  * system, but should never be used for that case.
2390  */
2391 static int
nfsvno_pnfsusenumfile(struct nameidata * ndp,struct vattr * vap)2392 nfsvno_pnfsusenumfile(struct nameidata *ndp, struct vattr *vap)
2393 {
2394 	struct componentname cn;
2395 	struct vattr va;
2396 	char name[11];
2397 	gid_t gid;
2398 	struct ucred *cred, *savcred;
2399 	struct vnode *numfiledvp;
2400 	struct mount *mp;
2401 	struct netexport *nep;
2402 	u_int nextf;
2403 	int error;
2404 
2405 	cred = newnfs_getcred();
2406 	/*
2407 	 * Not sure if this is necessary.  If all VOP calls use
2408 	 * cn_cred, it is not.
2409 	 */
2410 	savcred = curthread->td_ucred;
2411 	curthread->td_ucred = cred;
2412 
2413 	/*
2414 	 * If the replenish kernel process is not yet running,
2415 	 * start it up now.
2416 	 */
2417 	numfiledvp = NULL;
2418 	ndp->ni_vp = NULL;
2419 	mp = ndp->ni_dvp->v_mount;
2420 	lockmgr(&mp->mnt_explock, LK_SHARED, NULL);
2421 	nep = mp->mnt_export;
2422 	if (nep == NULL) {
2423 		error = ENOENT;
2424 		lockmgr(&mp->mnt_explock, LK_RELEASE, NULL);
2425 		goto out;
2426 	}
2427 	(void)vfs_netexport_acquire(nep);
2428 	lockmgr(&mp->mnt_explock, LK_RELEASE, NULL);
2429 	MNTEXP_LOCK(nep);
2430 	if (nep->ne_pnfsnumfile == NULL) {
2431 		/* Mark kernel process startup in-progress. */
2432 		nep->ne_pnfsnumfile = PNFSD_START;
2433 		MNTEXP_UNLOCK(nep);
2434 
2435 		/* Create the replenish kernel process. */
2436 		error = kproc_create(nfsvno_pnfsreplenish, mp, NULL, RFHIGHPID,
2437 		    0, "pnfsreplenish");
2438 		if (error != 0) {
2439 			printf("nfsvno_pnfsusenumfile: replenish won't start"
2440 			    " %d\n", error);
2441 			error = ENOENT;
2442 			goto out;
2443 		}
2444 
2445 		/* And wait for it to set up ne_pnfsnumfile. */
2446 		MNTEXP_LOCK(nep);
2447 		(void)msleep(&nep->ne_pnfsnumfile, MNTEXP_MTX(nep), PVFS,
2448 		    "pnfsnumf", hz);
2449 	}
2450 
2451 	if (nep->ne_pnfsnumfile == NULL ||
2452 	    nep->ne_pnfsnumfile == PNFSD_START ||
2453 	    nep->ne_pnfsnumfile == PNFSD_STOP) {
2454 		MNTEXP_UNLOCK(nep);
2455 		error = ENOENT;
2456 		goto out;
2457 	} else {
2458 		numfiledvp = nep->ne_pnfsnumfile;
2459 		MNTEXP_UNLOCK(nep);
2460 		/*
2461 		 * Check to ensure the new file is not in ".pnfshide/numfiles".
2462 		 */
2463 		if (numfiledvp == ndp->ni_dvp) {
2464 			error = ENOENT;
2465 			numfiledvp = NULL;
2466 			goto out;
2467 		}
2468 	}
2469 
2470 	error = vn_lock(numfiledvp, LK_EXCLUSIVE);
2471 	if (error != 0) {
2472 		error = ENOENT;
2473 		numfiledvp = NULL;
2474 		goto out;
2475 	}
2476 	vref(numfiledvp);
2477 
2478 	/* Get the next filenum. */
2479 	nextf = nep->ne_pnfsnextfile;
2480 	snprintf(name, sizeof(name), "%d", nextf);
2481 
2482 	/* Now, look up the numbered file. */
2483 	cn.cn_nameiop = DELETE;
2484 	cn.cn_lkflags = LK_EXCLUSIVE;
2485 	cn.cn_flags = ISLASTCN | NOFOLLOW | LOCKLEAF | LOCKPARENT |
2486 	    NOCROSSMOUNT;
2487 	cn.cn_cred = cred;
2488 	cn.cn_nameptr = name;
2489 	cn.cn_namelen = strlen(name);
2490 	error = VOP_LOOKUP(numfiledvp, &ndp->ni_vp, &cn);
2491 	if (error != 0) {
2492 		nfsrv_pnfsnumfilemiss++;
2493 		VOP_UNLOCK(numfiledvp);
2494 		ndp->ni_vp = NULL;
2495 		if (error == ENOENT || error == EJUSTRETURN)
2496 			wakeup(&mp->mnt_export);
2497 		else
2498 			VOP_VPUT_PAIR(ndp->ni_dvp, NULL, true);
2499 		goto out;
2500 	}
2501 
2502 	/*
2503 	 * Set the new file's attributes to what VOP_CREATE() would
2504 	 * have set them to.
2505 	 */
2506 	gid = GID_NOGROUP;
2507 	if (vap->va_gid == VNOVAL &&
2508 	    VOP_GETATTR(ndp->ni_dvp, &va, cred) == 0)
2509 		gid = va.va_gid;
2510 	VATTR_NULL(&va);
2511 	va.va_gid = gid;
2512 	va.va_uid = ndp->ni_cnd.cn_cred->cr_uid;
2513 	va.va_mode = vap->va_mode;
2514 	error = VOP_SETATTR(ndp->ni_vp, &va, cred);
2515 	if (error != 0) {
2516 		VOP_UNLOCK(numfiledvp);
2517 		VOP_VPUT_PAIR(ndp->ni_dvp, &ndp->ni_vp, true);
2518 		ndp->ni_vp = NULL;
2519 		printf("nfsvno_pnfsusenumfile: setattr failed %d\n",
2520 		    error);
2521 		if (error == ENOENT)
2522 			error = ENXIO;
2523 		goto out;
2524 	}
2525 
2526 	/*
2527 	 * Link the numbered file to the name VOP_CREATE() would have
2528 	 * created in the correct directory and then VOP_REMOVE() the
2529 	 * numbered file.
2530 	 * Use VOP_LINK()/VOP_REMOVE() so that the numbered file
2531 	 * directory can remain locked.
2532 	 */
2533 	error = VOP_LINK(ndp->ni_dvp, ndp->ni_vp, &ndp->ni_cnd);
2534 	/* Remove the file in .numfiles. */
2535 	if (error == 0) {
2536 		nep->ne_pnfsnextfile = (nextf + 1) %
2537 		    nfsrv_pnfsmaxnumfiles;
2538 		error = VOP_REMOVE(numfiledvp, ndp->ni_vp, &cn);
2539 		if (error != 0) {
2540 			/* Shut down the numfiles stuff. */
2541 			MNTEXP_LOCK(nep);
2542 			nep->ne_pnfsnumfile = PNFSD_STOP;
2543 			MNTEXP_UNLOCK(nep);
2544 			printf("nfsvno_pnfsusenumfile: remove failed "
2545 			    "%d %s\n", error, name);
2546 		}
2547 	}
2548 	VOP_UNLOCK(numfiledvp);
2549 	if (error != 0) {
2550 		VOP_VPUT_PAIR(ndp->ni_dvp, &ndp->ni_vp, true);
2551 		ndp->ni_vp = NULL;
2552 	} else {
2553 		atomic_add_int(&nep->ne_pnfsnumcnt, 1);
2554 		VOP_VPUT_PAIR(ndp->ni_dvp, &ndp->ni_vp, false);
2555 	}
2556 	if (error == ENOENT)
2557 		error = ENXIO;
2558 
2559 out:
2560 	if (numfiledvp != NULL)
2561 		vrele(numfiledvp);
2562 	if (nep != NULL)
2563 		vfs_netexport_release(nep);
2564 	curthread->td_ucred = savcred;		/* Reset the thread's cred. */
2565 	NFSFREECRED(cred);
2566 	return (error);
2567 }
2568 
2569 /*
2570  * Do the vnode op stuff for Open. Similar to nfsvno_createsub(), but
2571  * must handle nfsrv_opencheck() calls after any other access checks.
2572  */
2573 void
nfsvno_open(struct nfsrv_descript * nd,struct nameidata * ndp,nfsquad_t clientid,nfsv4stateid_t * stateidp,struct nfsstate * stp,int * exclusive_flagp,struct nfsvattr * nvap,int32_t * cverf,int create,NFSACL_T * aclp,NFSACL_T * daclp,nfsattrbit_t * attrbitp,struct ucred * cred,bool done_namei,struct nfsexstuff * exp,struct vnode ** vpp)2574 nfsvno_open(struct nfsrv_descript *nd, struct nameidata *ndp,
2575     nfsquad_t clientid, nfsv4stateid_t *stateidp, struct nfsstate *stp,
2576     int *exclusive_flagp, struct nfsvattr *nvap, int32_t *cverf, int create,
2577     NFSACL_T *aclp, NFSACL_T *daclp, nfsattrbit_t *attrbitp, struct ucred *cred,
2578     bool done_namei, struct nfsexstuff *exp, struct vnode **vpp)
2579 {
2580 	struct vattr va;
2581 	struct vnode *vp = NULL;
2582 	u_quad_t tempsize;
2583 	struct nfsexstuff nes;
2584 	struct thread *p = curthread;
2585 	uint32_t oldrepstat;
2586 	u_long savflags;
2587 	int error;
2588 
2589 	if (ndp->ni_vp == NULL) {
2590 		/*
2591 		 * If nfsrv_opencheck() sets nd_repstat, done_namei needs to be
2592 		 * set true, since cleanup after nfsvno_namei() is needed.
2593 		 */
2594 		oldrepstat = nd->nd_repstat;
2595 		nd->nd_repstat = nfsrv_opencheck(clientid,
2596 		    stateidp, stp, NULL, nd, p, nd->nd_repstat);
2597 		if (nd->nd_repstat != 0 && oldrepstat == 0)
2598 			done_namei = true;
2599 	}
2600 	if (!nd->nd_repstat) {
2601 		if (ndp->ni_vp == NULL) {
2602 			struct sockaddr_in *sin;
2603 			struct sockaddr_in6 *sin6;
2604 			bool try_pnfs;
2605 
2606 			sin = (struct sockaddr_in *)nd->nd_nam;
2607 			sin6 = (struct sockaddr_in6 *)nd->nd_nam;
2608 			error = ENOENT;
2609 			try_pnfs = !TAILQ_EMPTY(&nfsrv_devidhead);
2610 
2611 			if (try_pnfs && !(sin->sin_family == AF_INET &&
2612 			    IN_LOOPBACK(ntohl(sin->sin_addr.s_addr))) &&
2613 			    !(sin6->sin6_family == AF_INET6 &&
2614 			    IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))) {
2615 				error = nfsvno_pnfsusenumfile(ndp,
2616 				    &nvap->na_vattr);
2617 				if (error != ENOENT)
2618 					nd->nd_repstat = error;
2619 			}
2620 			if (error == ENOENT) {
2621 				/*
2622 				 * Most file systems ignore va_flags for
2623 				 * VOP_CREATE(), however setting va_flags
2624 				 * for VOP_CREATE() causes problems for ZFS.
2625 				 * So disable them and let nfsrv_fixattr()
2626 				 * do them, as required.
2627 				 */
2628 				savflags = nvap->na_flags;
2629 				nvap->na_flags = VNOVAL;
2630 				nd->nd_repstat = VOP_CREATE(ndp->ni_dvp,
2631 				    &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
2632 				if (try_pnfs && nd->nd_repstat == 0) {
2633 					/*
2634 					 * Create a data file on a DS for a pNFS
2635 					 * server. This function just returns if
2636 					 * not running a pNFS DS or the creation
2637 					 * fails.
2638 					 */
2639 					nfsrv_pnfscreate(ndp->ni_vp,
2640 					    &nvap->na_vattr, cred, p);
2641 				}
2642 				VOP_VPUT_PAIR(ndp->ni_dvp, nd->nd_repstat == 0 ?
2643 				    &ndp->ni_vp : NULL, false);
2644 				nvap->na_flags = savflags;
2645 			}
2646 			nfsvno_relpathbuf(ndp);
2647 			if (!nd->nd_repstat) {
2648 				if (*exclusive_flagp != NFSV4_EXCLUSIVE_NONE) {
2649 					VATTR_NULL(&va);
2650 					va.va_atime.tv_sec = cverf[0];
2651 					va.va_atime.tv_nsec = cverf[1];
2652 					nd->nd_repstat = VOP_SETATTR(ndp->ni_vp,
2653 					    &va, cred);
2654 					if (nd->nd_repstat != 0) {
2655 						vput(ndp->ni_vp);
2656 						ndp->ni_vp = NULL;
2657 						nd->nd_repstat = NFSERR_NOTSUPP;
2658 					} else {
2659 						/*
2660 						 * Few clients set these
2661 						 * attributes in Open/Create
2662 						 * Exclusive_41.  If this
2663 						 * changes, this should include
2664 						 * setting atime, instead of
2665 						 * the above.
2666 						 */
2667 						if (*exclusive_flagp ==
2668 						    NFSV4_EXCLUSIVE_41 &&
2669 						    (NFSISSET_ATTRBIT(attrbitp,
2670 						     NFSATTRBIT_OWNER) ||
2671 						     NFSISSET_ATTRBIT(attrbitp,
2672 						     NFSATTRBIT_OWNERGROUP) ||
2673 						     NFSISSET_ATTRBIT(attrbitp,
2674 						     NFSATTRBIT_TIMEMODIFYSET)||
2675 						     NFSISSET_ATTRBIT(attrbitp,
2676 						     NFSATTRBIT_ARCHIVE) ||
2677 						     NFSISSET_ATTRBIT(attrbitp,
2678 						     NFSATTRBIT_HIDDEN) ||
2679 						     NFSISSET_ATTRBIT(attrbitp,
2680 						     NFSATTRBIT_SYSTEM) ||
2681 						     aclp != NULL ||
2682 						     daclp != NULL))
2683 							nfsrv_fixattr(nd,
2684 							    ndp->ni_vp, nvap,
2685 							    aclp, daclp, p,
2686 							    attrbitp, true);
2687 						NFSSETBIT_ATTRBIT(attrbitp,
2688 						    NFSATTRBIT_TIMEACCESS);
2689 					}
2690 					*exclusive_flagp = NFSV4_EXCLUSIVE_NONE;
2691 				} else {
2692 					nfsrv_fixattr(nd, ndp->ni_vp, nvap,
2693 					    aclp, daclp, p, attrbitp, false);
2694 				}
2695 			}
2696 			vp = ndp->ni_vp;
2697 		} else {
2698 			nfsvno_relpathbuf(ndp);
2699 			vp = ndp->ni_vp;
2700 			if (create == NFSV4OPEN_CREATE) {
2701 				if (ndp->ni_dvp == vp)
2702 					vrele(ndp->ni_dvp);
2703 				else
2704 					vput(ndp->ni_dvp);
2705 			}
2706 			if (NFSVNO_ISSETSIZE(nvap) && vp->v_type == VREG) {
2707 				if (ndp->ni_cnd.cn_flags & RDONLY)
2708 					NFSVNO_SETEXRDONLY(&nes);
2709 				else
2710 					NFSVNO_EXINIT(&nes);
2711 				nd->nd_repstat = nfsvno_accchk(vp,
2712 				    VWRITE, cred, &nes, p,
2713 				    NFSACCCHK_NOOVERRIDE,
2714 				    NFSACCCHK_VPISLOCKED, NULL);
2715 				nd->nd_repstat = nfsrv_opencheck(clientid,
2716 				    stateidp, stp, vp, nd, p, nd->nd_repstat);
2717 				if (!nd->nd_repstat) {
2718 					tempsize = nvap->na_size;
2719 					NFSVNO_ATTRINIT(nvap);
2720 					nvap->na_size = tempsize;
2721 					nd->nd_repstat = nfsvno_setattr(vp,
2722 					    nvap, cred, p, exp);
2723 				}
2724 			} else if (vp->v_type == VREG) {
2725 				nd->nd_repstat = nfsrv_opencheck(clientid,
2726 				    stateidp, stp, vp, nd, p, nd->nd_repstat);
2727 			}
2728 		}
2729 	} else if (done_namei) {
2730 		KASSERT(create == NFSV4OPEN_CREATE,
2731 		    ("nfsvno_open: not create"));
2732 		/*
2733 		 * done_namei is set when nfsvno_namei() has completed
2734 		 * successfully, but a subsequent error was set in
2735 		 * nd_repstat.  As such, cleanup of the nfsvno_namei()
2736 		 * results is required.
2737 		 */
2738 		nfsvno_relpathbuf(ndp);
2739 		if (ndp->ni_dvp == ndp->ni_vp)
2740 			vrele(ndp->ni_dvp);
2741 		else
2742 			vput(ndp->ni_dvp);
2743 		if (ndp->ni_vp)
2744 			vput(ndp->ni_vp);
2745 	}
2746 	*vpp = vp;
2747 
2748 	NFSEXITCODE2(0, nd);
2749 }
2750 
2751 /*
2752  * Updates the file rev and sets the mtime and ctime
2753  * to the current clock time, returning the va_filerev and va_Xtime
2754  * values.
2755  * Return ESTALE to indicate the vnode is VIRF_DOOMED.
2756  */
2757 int
nfsvno_updfilerev(struct vnode * vp,struct nfsvattr * nvap,struct nfsrv_descript * nd,struct thread * p)2758 nfsvno_updfilerev(struct vnode *vp, struct nfsvattr *nvap,
2759     struct nfsrv_descript *nd, struct thread *p)
2760 {
2761 	struct vattr va;
2762 
2763 	VATTR_NULL(&va);
2764 	vfs_timestamp(&va.va_mtime);
2765 	if (NFSVOPISLOCKED(vp) != LK_EXCLUSIVE) {
2766 		NFSVOPLOCK(vp, LK_UPGRADE | LK_RETRY);
2767 		if (VN_IS_DOOMED(vp))
2768 			return (ESTALE);
2769 	}
2770 	(void) VOP_SETATTR(vp, &va, nd->nd_cred);
2771 	(void) nfsvno_getattr(vp, nvap, nd, p, 1, NULL);
2772 	return (0);
2773 }
2774 
2775 /*
2776  * Glue routine to nfsv4_fillattr().
2777  */
2778 int
nfsvno_fillattr(struct nfsrv_descript * nd,struct mount * mp,struct vnode * vp,struct nfsvattr * nvap,fhandle_t * fhp,int rderror,nfsattrbit_t * attrbitp,struct ucred * cred,struct thread * p,int isdgram,int reterr,int supports_nfsv4acls,int at_root,uint64_t mounted_on_fileno,bool xattrsupp,bool has_hiddensystem,bool has_namedattr,uint32_t clone_blksize,bool has_caseinsensitive)2779 nfsvno_fillattr(struct nfsrv_descript *nd, struct mount *mp, struct vnode *vp,
2780     struct nfsvattr *nvap, fhandle_t *fhp, int rderror, nfsattrbit_t *attrbitp,
2781     struct ucred *cred, struct thread *p, int isdgram, int reterr,
2782     int supports_nfsv4acls, int at_root, uint64_t mounted_on_fileno,
2783     bool xattrsupp, bool has_hiddensystem, bool has_namedattr,
2784     uint32_t clone_blksize, bool has_caseinsensitive)
2785 {
2786 	struct statfs *sf;
2787 	int error;
2788 
2789 	sf = NULL;
2790 	if (nfsrv_devidcnt > 0 &&
2791 	    (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SPACEAVAIL) ||
2792 	     NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SPACEFREE) ||
2793 	     NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SPACETOTAL))) {
2794 		sf = malloc(sizeof(*sf), M_TEMP, M_WAITOK | M_ZERO);
2795 		error = nfsrv_pnfsstatfs(sf, mp);
2796 		if (error != 0) {
2797 			free(sf, M_TEMP);
2798 			sf = NULL;
2799 		}
2800 	}
2801 
2802 	error = nfsv4_fillattr(nd, mp, vp, NULL, &nvap->na_vattr, fhp, rderror,
2803 	    attrbitp, cred, p, isdgram, reterr, supports_nfsv4acls, at_root,
2804 	    mounted_on_fileno, sf, xattrsupp, has_hiddensystem, has_namedattr,
2805 	    clone_blksize, NULL, has_caseinsensitive);
2806 	free(sf, M_TEMP);
2807 	NFSEXITCODE2(0, nd);
2808 	return (error);
2809 }
2810 
2811 /*
2812  * Convert a dirent d_type to a vnode type.
2813  */
nfs_dtypetovtype(struct nfsvattr * nvap,struct vnode * vp,uint8_t dtype)2814 static void nfs_dtypetovtype(struct nfsvattr *nvap, struct vnode *vp,
2815     uint8_t dtype)
2816 {
2817 
2818 	if ((vn_irflag_read(vp) & VIRF_NAMEDDIR) != 0) {
2819 		nvap->na_type = VREG;
2820 		nvap->na_bsdflags |= SFBSD_NAMEDATTR;
2821 	} else if (dtype <= DT_WHT) {
2822 		nvap->na_type = dtype_to_vnode[dtype];
2823 	} else {
2824 		nvap->na_type = VNON;
2825 	}
2826 }
2827 
2828 /* Since the Readdir vnode ops vary, put the entire functions in here. */
2829 /*
2830  * nfs readdir service
2831  * - mallocs what it thinks is enough to read
2832  *	count rounded up to a multiple of DIRBLKSIZ <= NFS_MAXREADDIR
2833  * - calls VOP_READDIR()
2834  * - loops around building the reply
2835  *	if the output generated exceeds count break out of loop
2836  *	The NFSM_CLGET macro is used here so that the reply will be packed
2837  *	tightly in mbuf clusters.
2838  * - it trims out records with d_fileno == 0
2839  *	this doesn't matter for Unix clients, but they might confuse clients
2840  *	for other os'.
2841  * - it trims out records with d_type == DT_WHT
2842  *	these cannot be seen through NFS (unless we extend the protocol)
2843  *     The alternate call nfsrvd_readdirplus() does lookups as well.
2844  * PS: The NFS protocol spec. does not clarify what the "count" byte
2845  *	argument is a count of.. just name strings and file id's or the
2846  *	entire reply rpc or ...
2847  *	I tried just file name and id sizes and it confused the Sun client,
2848  *	so I am using the full rpc size now. The "paranoia.." comment refers
2849  *	to including the status longwords that are not a part of the dir.
2850  *	"entry" structures, but are in the rpc.
2851  */
2852 int
nfsrvd_readdir(struct nfsrv_descript * nd,int isdgram,struct vnode * vp,struct nfsexstuff * exp)2853 nfsrvd_readdir(struct nfsrv_descript *nd, int isdgram,
2854     struct vnode *vp, struct nfsexstuff *exp)
2855 {
2856 	struct dirent *dp;
2857 	u_int32_t *tl;
2858 	int dirlen;
2859 	char *cpos, *cend, *rbuf;
2860 	struct nfsvattr at;
2861 	int nlen, error = 0, getret = 1;
2862 	int siz, cnt, fullsiz, eofflag, ncookies;
2863 	u_int64_t off, toff, verf __unused;
2864 	uint64_t *cookies = NULL, *cookiep;
2865 	struct uio io;
2866 	struct iovec iv;
2867 	int is_ufs;
2868 	struct thread *p = curthread;
2869 
2870 	if (nd->nd_repstat) {
2871 		nfsrv_postopattr(nd, getret, &at);
2872 		goto out;
2873 	}
2874 	if (nd->nd_flag & ND_NFSV2) {
2875 		NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2876 		off = fxdr_unsigned(u_quad_t, *tl++);
2877 	} else {
2878 		NFSM_DISSECT(tl, u_int32_t *, 5 * NFSX_UNSIGNED);
2879 		off = fxdr_hyper(tl);
2880 		tl += 2;
2881 		verf = fxdr_hyper(tl);
2882 		tl += 2;
2883 	}
2884 	toff = off;
2885 	cnt = fxdr_unsigned(int, *tl);
2886 	if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
2887 		cnt = NFS_SRVMAXDATA(nd);
2888 	siz = ((cnt + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
2889 	fullsiz = siz;
2890 	if (nd->nd_flag & ND_NFSV3) {
2891 		nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd, p, 1,
2892 		    NULL);
2893 #if 0
2894 		/*
2895 		 * va_filerev is not sufficient as a cookie verifier,
2896 		 * since it is not supposed to change when entries are
2897 		 * removed/added unless that offset cookies returned to
2898 		 * the client are no longer valid.
2899 		 */
2900 		if (!nd->nd_repstat && toff && verf != at.na_filerev)
2901 			nd->nd_repstat = NFSERR_BAD_COOKIE;
2902 #endif
2903 	}
2904 	if (!nd->nd_repstat && vp->v_type != VDIR)
2905 		nd->nd_repstat = NFSERR_NOTDIR;
2906 	if (nd->nd_repstat == 0 && cnt == 0) {
2907 		if (nd->nd_flag & ND_NFSV2)
2908 			/* NFSv2 does not have NFSERR_TOOSMALL */
2909 			nd->nd_repstat = EPERM;
2910 		else
2911 			nd->nd_repstat = NFSERR_TOOSMALL;
2912 	}
2913 	if (!nd->nd_repstat)
2914 		nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
2915 		    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
2916 		    NFSACCCHK_VPISLOCKED, NULL);
2917 	if (nd->nd_repstat) {
2918 		vput(vp);
2919 		if (nd->nd_flag & ND_NFSV3)
2920 			nfsrv_postopattr(nd, getret, &at);
2921 		goto out;
2922 	}
2923 	is_ufs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "ufs") == 0;
2924 	rbuf = malloc(siz, M_TEMP, M_WAITOK);
2925 again:
2926 	eofflag = 0;
2927 	if (cookies) {
2928 		free(cookies, M_TEMP);
2929 		cookies = NULL;
2930 	}
2931 
2932 	iv.iov_base = rbuf;
2933 	iv.iov_len = siz;
2934 	io.uio_iov = &iv;
2935 	io.uio_iovcnt = 1;
2936 	io.uio_offset = (off_t)off;
2937 	io.uio_resid = siz;
2938 	io.uio_segflg = UIO_SYSSPACE;
2939 	io.uio_rw = UIO_READ;
2940 	io.uio_td = NULL;
2941 	nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
2942 	    &cookies);
2943 	off = (u_int64_t)io.uio_offset;
2944 	if (io.uio_resid)
2945 		siz -= io.uio_resid;
2946 
2947 	if (!cookies && !nd->nd_repstat)
2948 		nd->nd_repstat = NFSERR_PERM;
2949 	if (nd->nd_flag & ND_NFSV3) {
2950 		getret = nfsvno_getattr(vp, &at, nd, p, 1, NULL);
2951 		if (!nd->nd_repstat)
2952 			nd->nd_repstat = getret;
2953 	}
2954 
2955 	/*
2956 	 * Handles the failed cases. nd->nd_repstat == 0 past here.
2957 	 */
2958 	if (nd->nd_repstat) {
2959 		vput(vp);
2960 		free(rbuf, M_TEMP);
2961 		if (cookies)
2962 			free(cookies, M_TEMP);
2963 		if (nd->nd_flag & ND_NFSV3)
2964 			nfsrv_postopattr(nd, getret, &at);
2965 		goto out;
2966 	}
2967 	/*
2968 	 * If nothing read, return eof
2969 	 * rpc reply
2970 	 */
2971 	if (siz == 0) {
2972 		vput(vp);
2973 		if (nd->nd_flag & ND_NFSV2) {
2974 			NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2975 		} else {
2976 			nfsrv_postopattr(nd, getret, &at);
2977 			NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
2978 			txdr_hyper(at.na_filerev, tl);
2979 			tl += 2;
2980 		}
2981 		*tl++ = newnfs_false;
2982 		*tl = newnfs_true;
2983 		free(rbuf, M_TEMP);
2984 		free(cookies, M_TEMP);
2985 		goto out;
2986 	}
2987 
2988 	/*
2989 	 * Check for degenerate cases of nothing useful read.
2990 	 * If so go try again
2991 	 */
2992 	cpos = rbuf;
2993 	cend = rbuf + siz;
2994 	dp = (struct dirent *)cpos;
2995 	cookiep = cookies;
2996 
2997 	/*
2998 	 * For some reason FreeBSD's ufs_readdir() chooses to back the
2999 	 * directory offset up to a block boundary, so it is necessary to
3000 	 * skip over the records that precede the requested offset. This
3001 	 * requires the assumption that file offset cookies monotonically
3002 	 * increase.
3003 	 */
3004 	while (cpos < cend && ncookies > 0 &&
3005 	    (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
3006 	     (is_ufs == 1 && ((u_quad_t)(*cookiep)) <= toff))) {
3007 		cpos += dp->d_reclen;
3008 		dp = (struct dirent *)cpos;
3009 		cookiep++;
3010 		ncookies--;
3011 	}
3012 	if (cpos >= cend || ncookies == 0) {
3013 		siz = fullsiz;
3014 		toff = off;
3015 		goto again;
3016 	}
3017 	vput(vp);
3018 
3019 	/*
3020 	 * If cnt > MCLBYTES and the reply will not be saved, use
3021 	 * ext_pgs mbufs for TLS or if enabled via vfs.nfsd.enable_mextpg.
3022 	 * For NFSv4.0, we do not know for sure if the reply will
3023 	 * be saved, so do not use ext_pgs mbufs for NFSv4.0.
3024 	 */
3025 	if (cnt > MCLBYTES && siz > MCLBYTES &&
3026 	    ((nd->nd_flag & (ND_TLS | ND_SAVEREPLY)) == ND_TLS ||
3027 	     (nd->nd_flag & (ND_CANEXTPG | ND_SAVEREPLY)) == ND_CANEXTPG) &&
3028 	    (nd->nd_flag & (ND_NFSV4 | ND_NFSV41)) != ND_NFSV4)
3029 		nd->nd_flag |= ND_EXTPG;
3030 
3031 	/*
3032 	 * dirlen is the size of the reply, including all XDR and must
3033 	 * not exceed cnt. For NFSv2, RFC1094 didn't clearly indicate
3034 	 * if the XDR should be included in "count", but to be safe, we do.
3035 	 * (Include the two booleans at the end of the reply in dirlen now.)
3036 	 */
3037 	if (nd->nd_flag & ND_NFSV3) {
3038 		nfsrv_postopattr(nd, getret, &at);
3039 		NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
3040 		txdr_hyper(at.na_filerev, tl);
3041 		dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
3042 	} else {
3043 		dirlen = 2 * NFSX_UNSIGNED;
3044 	}
3045 
3046 	/* Loop through the records and build reply */
3047 	while (cpos < cend && ncookies > 0) {
3048 		nlen = dp->d_namlen;
3049 		if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
3050 			nlen <= NFS_MAXNAMLEN) {
3051 			if (nd->nd_flag & ND_NFSV3)
3052 				dirlen += (6*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
3053 			else
3054 				dirlen += (4*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
3055 			if (dirlen > cnt) {
3056 				eofflag = 0;
3057 				break;
3058 			}
3059 
3060 			/*
3061 			 * Build the directory record xdr from
3062 			 * the dirent entry.
3063 			 */
3064 			if (nd->nd_flag & ND_NFSV3) {
3065 				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
3066 				*tl++ = newnfs_true;
3067 				txdr_hyper(dp->d_fileno, tl);
3068 			} else {
3069 				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
3070 				*tl++ = newnfs_true;
3071 				*tl = txdr_unsigned(dp->d_fileno);
3072 			}
3073 			(void) nfsm_strtom(nd, dp->d_name, nlen);
3074 			if (nd->nd_flag & ND_NFSV3) {
3075 				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
3076 				txdr_hyper(*cookiep, tl);
3077 			} else {
3078 				NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
3079 				*tl = txdr_unsigned(*cookiep);
3080 			}
3081 		}
3082 		cpos += dp->d_reclen;
3083 		dp = (struct dirent *)cpos;
3084 		cookiep++;
3085 		ncookies--;
3086 	}
3087 	if (cpos < cend)
3088 		eofflag = 0;
3089 	NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
3090 	*tl++ = newnfs_false;
3091 	if (eofflag)
3092 		*tl = newnfs_true;
3093 	else
3094 		*tl = newnfs_false;
3095 	free(rbuf, M_TEMP);
3096 	free(cookies, M_TEMP);
3097 
3098 out:
3099 	NFSEXITCODE2(0, nd);
3100 	return (0);
3101 nfsmout:
3102 	vput(vp);
3103 	NFSEXITCODE2(error, nd);
3104 	return (error);
3105 }
3106 
3107 /*
3108  * Readdirplus for V3 and Readdir for V4.
3109  */
3110 int
nfsrvd_readdirplus(struct nfsrv_descript * nd,int isdgram,struct vnode * vp,struct nfsexstuff * exp)3111 nfsrvd_readdirplus(struct nfsrv_descript *nd, int isdgram,
3112     struct vnode *vp, struct nfsexstuff *exp)
3113 {
3114 	struct dirent *dp;
3115 	uint32_t clone_blksize, *tl;
3116 	int dirlen;
3117 	char *cpos, *cend, *rbuf;
3118 	struct vnode *nvp;
3119 	fhandle_t nfh;
3120 	struct nfsvattr nva, at, *nvap = &nva;
3121 	struct mbuf *mb0, *mb1;
3122 	struct nfsreferral *refp;
3123 	int nlen, r, error = 0, getret = 1, ret, usevget = 1;
3124 	int siz, cnt, fullsiz, eofflag, ncookies, entrycnt;
3125 	caddr_t bpos0, bpos1;
3126 	u_int64_t off, toff, verf __unused;
3127 	uint64_t *cookies = NULL, *cookiep;
3128 	nfsattrbit_t attrbits, rderrbits, savbits, refbits;
3129 	struct uio io;
3130 	struct iovec iv;
3131 	struct componentname cn;
3132 	int at_root, is_ufs, is_zfs, needs_unbusy, supports_nfsv4acls;
3133 	struct mount *mp, *new_mp;
3134 	uint64_t mounted_on_fileno;
3135 	struct thread *p = curthread;
3136 	int bextpg0, bextpg1, bextpgsiz0, bextpgsiz1;
3137 	size_t atsiz;
3138 	long pathval;
3139 	bool has_caseinsensitive, has_hiddensystem, has_namedattr, xattrsupp;
3140 
3141 	NFSZERO_ATTRBIT(&savbits);			/* Shut up gcc. */
3142 	if (nd->nd_repstat) {
3143 		nfsrv_postopattr(nd, getret, &at);
3144 		goto out;
3145 	}
3146 	NFSM_DISSECT(tl, u_int32_t *, 6 * NFSX_UNSIGNED);
3147 	off = fxdr_hyper(tl);
3148 	toff = off;
3149 	tl += 2;
3150 	verf = fxdr_hyper(tl);
3151 	tl += 2;
3152 	siz = fxdr_unsigned(int, *tl++);
3153 	cnt = fxdr_unsigned(int, *tl);
3154 
3155 	/*
3156 	 * Use the server's maximum data transfer size as the upper bound
3157 	 * on reply datalen.
3158 	 */
3159 	if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
3160 		cnt = NFS_SRVMAXDATA(nd);
3161 
3162 	/*
3163 	 * siz is a "hint" of how much directory information (name, fileid,
3164 	 * cookie) should be in the reply. At least one client "hints" 0,
3165 	 * so I set it to cnt for that case. I also round it up to the
3166 	 * next multiple of DIRBLKSIZ.
3167 	 * Since the size of a Readdirplus directory entry reply will always
3168 	 * be greater than a directory entry returned by VOP_READDIR(), it
3169 	 * does not make sense to read more than NFS_SRVMAXDATA() via
3170 	 * VOP_READDIR().
3171 	 */
3172 	if (siz <= 0)
3173 		siz = cnt;
3174 	else if (siz > NFS_SRVMAXDATA(nd))
3175 		siz = NFS_SRVMAXDATA(nd);
3176 	siz = ((siz + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
3177 
3178 	if (nd->nd_flag & ND_NFSV4) {
3179 		error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
3180 		if (error)
3181 			goto nfsmout;
3182 		NFSSET_ATTRBIT(&savbits, &attrbits);
3183 		NFSSET_ATTRBIT(&refbits, &attrbits);
3184 		NFSCLRNOTFILLABLE_ATTRBIT(&attrbits, nd);
3185 		NFSZERO_ATTRBIT(&rderrbits);
3186 		NFSSETBIT_ATTRBIT(&rderrbits, NFSATTRBIT_RDATTRERROR);
3187 		/*
3188 		 * If these 4 bits are the only attributes requested by the
3189 		 * client, they can be satisfied without acquiring the vnode
3190 		 * for the file object unless it is a directory.
3191 		 * This will be indicated by savbits being all 0s.
3192 		 */
3193 		NFSCLRBIT_ATTRBIT(&savbits, NFSATTRBIT_TYPE);
3194 		NFSCLRBIT_ATTRBIT(&savbits, NFSATTRBIT_FILEID);
3195 		NFSCLRBIT_ATTRBIT(&savbits, NFSATTRBIT_MOUNTEDONFILEID);
3196 		NFSCLRBIT_ATTRBIT(&savbits, NFSATTRBIT_RDATTRERROR);
3197 	} else {
3198 		NFSZERO_ATTRBIT(&attrbits);
3199 	}
3200 	fullsiz = siz;
3201 	nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd, p, 1, NULL);
3202 #if 0
3203 	if (!nd->nd_repstat) {
3204 	    if (off && verf != at.na_filerev) {
3205 		/*
3206 		 * va_filerev is not sufficient as a cookie verifier,
3207 		 * since it is not supposed to change when entries are
3208 		 * removed/added unless that offset cookies returned to
3209 		 * the client are no longer valid.
3210 		 */
3211 		if (nd->nd_flag & ND_NFSV4) {
3212 			nd->nd_repstat = NFSERR_NOTSAME;
3213 		} else {
3214 			nd->nd_repstat = NFSERR_BAD_COOKIE;
3215 		}
3216 	    }
3217 	}
3218 #endif
3219 	if (!nd->nd_repstat && vp->v_type != VDIR)
3220 		nd->nd_repstat = NFSERR_NOTDIR;
3221 	if (!nd->nd_repstat && cnt == 0)
3222 		nd->nd_repstat = NFSERR_TOOSMALL;
3223 	if (!nd->nd_repstat)
3224 		nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
3225 		    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
3226 		    NFSACCCHK_VPISLOCKED, NULL);
3227 	if (nd->nd_repstat) {
3228 		vput(vp);
3229 		if (nd->nd_flag & ND_NFSV3)
3230 			nfsrv_postopattr(nd, getret, &at);
3231 		goto out;
3232 	}
3233 	is_ufs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "ufs") == 0;
3234 	is_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs") == 0;
3235 
3236 	rbuf = malloc(siz, M_TEMP, M_WAITOK);
3237 again:
3238 	eofflag = 0;
3239 	if (cookies) {
3240 		free(cookies, M_TEMP);
3241 		cookies = NULL;
3242 	}
3243 
3244 	iv.iov_base = rbuf;
3245 	iv.iov_len = siz;
3246 	io.uio_iov = &iv;
3247 	io.uio_iovcnt = 1;
3248 	io.uio_offset = (off_t)off;
3249 	io.uio_resid = siz;
3250 	io.uio_segflg = UIO_SYSSPACE;
3251 	io.uio_rw = UIO_READ;
3252 	io.uio_td = NULL;
3253 	nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
3254 	    &cookies);
3255 	off = (u_int64_t)io.uio_offset;
3256 	if (io.uio_resid)
3257 		siz -= io.uio_resid;
3258 
3259 	getret = nfsvno_getattr(vp, &at, nd, p, 1, NULL);
3260 
3261 	if (!cookies && !nd->nd_repstat)
3262 		nd->nd_repstat = NFSERR_PERM;
3263 	if (!nd->nd_repstat)
3264 		nd->nd_repstat = getret;
3265 	if (nd->nd_repstat) {
3266 		vput(vp);
3267 		if (cookies)
3268 			free(cookies, M_TEMP);
3269 		free(rbuf, M_TEMP);
3270 		if (nd->nd_flag & ND_NFSV3)
3271 			nfsrv_postopattr(nd, getret, &at);
3272 		goto out;
3273 	}
3274 	/*
3275 	 * If nothing read, return eof
3276 	 * rpc reply
3277 	 */
3278 	if (siz == 0) {
3279 ateof:
3280 		vput(vp);
3281 		if (nd->nd_flag & ND_NFSV3)
3282 			nfsrv_postopattr(nd, getret, &at);
3283 		NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
3284 		txdr_hyper(at.na_filerev, tl);
3285 		tl += 2;
3286 		*tl++ = newnfs_false;
3287 		*tl = newnfs_true;
3288 		free(cookies, M_TEMP);
3289 		free(rbuf, M_TEMP);
3290 		goto out;
3291 	}
3292 
3293 	/*
3294 	 * Check for degenerate cases of nothing useful read.
3295 	 * If so go try again
3296 	 */
3297 	cpos = rbuf;
3298 	cend = rbuf + siz;
3299 	dp = (struct dirent *)cpos;
3300 	cookiep = cookies;
3301 
3302 	/*
3303 	 * For some reason FreeBSD's ufs_readdir() chooses to back the
3304 	 * directory offset up to a block boundary, so it is necessary to
3305 	 * skip over the records that precede the requested offset. This
3306 	 * requires the assumption that file offset cookies monotonically
3307 	 * increase.
3308 	 */
3309 	while (cpos < cend && ncookies > 0 &&
3310 	  (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
3311 	   (is_ufs == 1 && ((u_quad_t)(*cookiep)) <= toff) ||
3312 	   ((nd->nd_flag & ND_NFSV4) &&
3313 	    ((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
3314 	     (dp->d_namlen==2 && dp->d_name[0]=='.' && dp->d_name[1]=='.'))))) {
3315 		cpos += dp->d_reclen;
3316 		dp = (struct dirent *)cpos;
3317 		cookiep++;
3318 		ncookies--;
3319 	}
3320 	if (cpos >= cend || ncookies == 0) {
3321 		if (eofflag != 0)
3322 			goto ateof;
3323 		siz = fullsiz;
3324 		toff = off;
3325 		goto again;
3326 	}
3327 
3328 	/*
3329 	 * Busy the file system so that the mount point won't go away
3330 	 * and, as such, VFS_VGET() can be used safely.
3331 	 */
3332 	mp = vp->v_mount;
3333 	vfs_ref(mp);
3334 	NFSVOPUNLOCK(vp);
3335 	nd->nd_repstat = vfs_busy(mp, 0);
3336 	vfs_rel(mp);
3337 	if (nd->nd_repstat != 0) {
3338 		vrele(vp);
3339 		free(cookies, M_TEMP);
3340 		free(rbuf, M_TEMP);
3341 		if (nd->nd_flag & ND_NFSV3)
3342 			nfsrv_postopattr(nd, getret, &at);
3343 		goto out;
3344 	}
3345 
3346 	/*
3347 	 * Check to see if entries in this directory can be safely acquired
3348 	 * via VFS_VGET() or if a switch to VOP_LOOKUP() is required.
3349 	 * ZFS snapshot directories need VOP_LOOKUP(), so that any
3350 	 * automount of the snapshot directory that is required will
3351 	 * be done.
3352 	 * This needs to be done here for NFSv4, since NFSv4 never does
3353 	 * a VFS_VGET() for "." or "..".
3354 	 */
3355 	if (is_zfs == 1) {
3356 		r = VFS_VGET(mp, at.na_fileid, LK_SHARED, &nvp);
3357 		if (r == EOPNOTSUPP) {
3358 			usevget = 0;
3359 			cn.cn_nameiop = LOOKUP;
3360 			cn.cn_lkflags = LK_SHARED | LK_RETRY;
3361 			cn.cn_cred = nd->nd_cred;
3362 		} else if (r == 0)
3363 			vput(nvp);
3364 	}
3365 
3366 	/*
3367 	 * If the reply is likely to exceed MCLBYTES and the reply will
3368 	 * not be saved, use ext_pgs mbufs for TLS or if enabled via
3369 	 * vfs.nfsd.enable_mextpg.
3370 	 * It is difficult to predict how large each entry will be and
3371 	 * how many entries have been read, so just assume the directory
3372 	 * entries grow by a factor of 4 when attributes are included.
3373 	 * For NFSv4.0, we do not know for sure if the reply will
3374 	 * be saved, so do not use ext_pgs mbufs for NFSv4.0.
3375 	 */
3376 	if (cnt > MCLBYTES && siz > MCLBYTES / 4 &&
3377 	    ((nd->nd_flag & (ND_TLS | ND_SAVEREPLY)) == ND_TLS ||
3378 	     (nd->nd_flag & (ND_CANEXTPG | ND_SAVEREPLY)) == ND_CANEXTPG) &&
3379 	    (nd->nd_flag & (ND_NFSV4 | ND_NFSV41)) != ND_NFSV4)
3380 		nd->nd_flag |= ND_EXTPG;
3381 
3382 	/*
3383 	 * Save this position, in case there is an error before one entry
3384 	 * is created.
3385 	 */
3386 	mb0 = nd->nd_mb;
3387 	bpos0 = nd->nd_bpos;
3388 	bextpg0 = nd->nd_bextpg;
3389 	bextpgsiz0 = nd->nd_bextpgsiz;
3390 
3391 	/*
3392 	 * Fill in the first part of the reply.
3393 	 * dirlen is the reply length in bytes and cannot exceed cnt.
3394 	 * (Include the two booleans at the end of the reply in dirlen now,
3395 	 *  so we recognize when we have exceeded cnt.)
3396 	 */
3397 	if (nd->nd_flag & ND_NFSV3) {
3398 		dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
3399 		nfsrv_postopattr(nd, getret, &at);
3400 	} else {
3401 		dirlen = NFSX_VERF + 2 * NFSX_UNSIGNED;
3402 	}
3403 	NFSM_BUILD(tl, u_int32_t *, NFSX_VERF);
3404 	txdr_hyper(at.na_filerev, tl);
3405 
3406 	/*
3407 	 * Save this position, in case there is an empty reply needed.
3408 	 */
3409 	mb1 = nd->nd_mb;
3410 	bpos1 = nd->nd_bpos;
3411 	bextpg1 = nd->nd_bextpg;
3412 	bextpgsiz1 = nd->nd_bextpgsiz;
3413 
3414 	/* Loop through the records and build reply */
3415 	entrycnt = 0;
3416 	while (cpos < cend && ncookies > 0 && dirlen < cnt) {
3417 		nlen = dp->d_namlen;
3418 		if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
3419 		    nlen <= NFS_MAXNAMLEN &&
3420 		    ((nd->nd_flag & ND_NFSV3) || nlen > 2 ||
3421 		     (nlen==2 && (dp->d_name[0]!='.' || dp->d_name[1]!='.'))
3422 		      || (nlen == 1 && dp->d_name[0] != '.'))) {
3423 			/*
3424 			 * Save the current position in the reply, in case
3425 			 * this entry exceeds cnt.
3426 			 */
3427 			mb1 = nd->nd_mb;
3428 			bpos1 = nd->nd_bpos;
3429 			bextpg1 = nd->nd_bextpg;
3430 			bextpgsiz1 = nd->nd_bextpgsiz;
3431 
3432 			/*
3433 			 * For readdir_and_lookup get the vnode using
3434 			 * the file number.
3435 			 */
3436 			nvp = NULL;
3437 			refp = NULL;
3438 			r = 0;
3439 			at_root = 0;
3440 			needs_unbusy = 0;
3441 			new_mp = mp;
3442 			mounted_on_fileno = (uint64_t)dp->d_fileno;
3443 			if ((nd->nd_flag & ND_NFSV3) ||
3444 			    NFSNONZERO_ATTRBIT(&savbits) ||
3445 			    dp->d_type == DT_UNKNOWN ||
3446 			    (dp->d_type == DT_DIR &&
3447 			     nfsrv_enable_crossmntpt != 0)) {
3448 				if (nd->nd_flag & ND_NFSV4)
3449 					refp = nfsv4root_getreferral(NULL,
3450 					    vp, dp->d_fileno);
3451 				if (refp == NULL) {
3452 					if (usevget)
3453 						r = VFS_VGET(mp, dp->d_fileno,
3454 						    LK_SHARED, &nvp);
3455 					else
3456 						r = EOPNOTSUPP;
3457 					if (r == 0 && (vn_irflag_read(vp) &
3458 					    VIRF_NAMEDDIR) != 0)
3459 						vn_irflag_set_cond(nvp,
3460 						    VIRF_NAMEDATTR);
3461 					if (r == EOPNOTSUPP) {
3462 						if (usevget) {
3463 							usevget = 0;
3464 							cn.cn_nameiop = LOOKUP;
3465 							cn.cn_lkflags =
3466 							    LK_SHARED |
3467 							    LK_RETRY;
3468 							cn.cn_cred =
3469 							    nd->nd_cred;
3470 						}
3471 						cn.cn_nameptr = dp->d_name;
3472 						cn.cn_namelen = nlen;
3473 						cn.cn_flags = ISLASTCN |
3474 						    NOFOLLOW | LOCKLEAF;
3475 						if ((vn_irflag_read(vp) &
3476 						    VIRF_NAMEDDIR) != 0)
3477 							cn.cn_flags |=
3478 							    OPENNAMED;
3479 						if (nlen == 2 &&
3480 						    dp->d_name[0] == '.' &&
3481 						    dp->d_name[1] == '.')
3482 							cn.cn_flags |=
3483 							    ISDOTDOT;
3484 						if (NFSVOPLOCK(vp, LK_SHARED)
3485 						    != 0) {
3486 							nd->nd_repstat = EPERM;
3487 							break;
3488 						}
3489 						if ((vp->v_vflag & VV_ROOT) != 0
3490 						    && (cn.cn_flags & ISDOTDOT)
3491 						    != 0) {
3492 							vref(vp);
3493 							nvp = vp;
3494 							r = 0;
3495 						} else {
3496 							r = VOP_LOOKUP(vp, &nvp,
3497 							    &cn);
3498 							if (vp != nvp)
3499 								NFSVOPUNLOCK(vp);
3500 						}
3501 					}
3502 
3503 					/*
3504 					 * For NFSv4, check to see if nvp is
3505 					 * a mount point and get the mount
3506 					 * point vnode, as required.
3507 					 */
3508 					if (r == 0 &&
3509 					    nfsrv_enable_crossmntpt != 0 &&
3510 					    (nd->nd_flag & ND_NFSV4) != 0 &&
3511 					    nvp->v_type == VDIR &&
3512 					    nvp->v_mountedhere != NULL) {
3513 						new_mp = nvp->v_mountedhere;
3514 						r = vfs_busy(new_mp, 0);
3515 						vput(nvp);
3516 						nvp = NULL;
3517 						if (r == 0) {
3518 							r = VFS_ROOT(new_mp,
3519 							    LK_SHARED, &nvp);
3520 							needs_unbusy = 1;
3521 							if (r == 0)
3522 								at_root = 1;
3523 						}
3524 					}
3525 				}
3526 
3527 				/*
3528 				 * If we failed to look up the entry, then it
3529 				 * has become invalid, most likely removed.
3530 				 */
3531 				if (r != 0) {
3532 					if (needs_unbusy)
3533 						vfs_unbusy(new_mp);
3534 					goto invalid;
3535 				}
3536 				KASSERT(refp != NULL || nvp != NULL,
3537 				    ("%s: undetected lookup error", __func__));
3538 
3539 				if (refp == NULL &&
3540 				    ((nd->nd_flag & ND_NFSV3) ||
3541 				     NFSNONZERO_ATTRBIT(&attrbits))) {
3542 					r = nfsvno_getfh(nvp, &nfh, p);
3543 					if (!r)
3544 					    r = nfsvno_getattr(nvp, nvap, nd, p,
3545 						1, &attrbits);
3546 					if (r == 0 && is_zfs == 1 &&
3547 					    nfsrv_enable_crossmntpt != 0 &&
3548 					    (nd->nd_flag & ND_NFSV4) != 0 &&
3549 					    nvp->v_type == VDIR &&
3550 					    vp->v_mount != nvp->v_mount) {
3551 					    /*
3552 					     * For a ZFS snapshot, there is a
3553 					     * pseudo mount that does not set
3554 					     * v_mountedhere, so it needs to
3555 					     * be detected via a different
3556 					     * mount structure.
3557 					     */
3558 					    at_root = 1;
3559 					    if (new_mp == mp)
3560 						new_mp = nvp->v_mount;
3561 					}
3562 				}
3563 
3564 				/*
3565 				 * If we failed to get attributes of the entry,
3566 				 * then just skip it for NFSv3 (the traditional
3567 				 * behavior in the old NFS server).
3568 				 * For NFSv4 the behavior is controlled by
3569 				 * RDATTRERROR: we either ignore the error or
3570 				 * fail the request.
3571 				 * The exception is EOPNOTSUPP, which can be
3572 				 * returned by nfsvno_getfh() for certain
3573 				 * file systems, such as devfs.  This indicates
3574 				 * that the file system cannot be exported,
3575 				 * so just skip over the entry.
3576 				 * Note that RDATTRERROR is never set for NFSv3.
3577 				 */
3578 				if (r != 0) {
3579 					if (!NFSISSET_ATTRBIT(&attrbits,
3580 					    NFSATTRBIT_RDATTRERROR) ||
3581 					    r == EOPNOTSUPP) {
3582 						vput(nvp);
3583 						if (needs_unbusy != 0)
3584 							vfs_unbusy(new_mp);
3585 						if ((nd->nd_flag & ND_NFSV3) ||
3586 						    r == EOPNOTSUPP)
3587 							goto invalid;
3588 						nd->nd_repstat = r;
3589 						break;
3590 					}
3591 				}
3592 			} else if (NFSNONZERO_ATTRBIT(&attrbits)) {
3593 				/* Only need Type and/or Fileid. */
3594 				VATTR_NULL(&nvap->na_vattr);
3595 				nvap->na_fileid = dp->d_fileno;
3596 				nfs_dtypetovtype(nvap, vp, dp->d_type);
3597 			}
3598 
3599 			/*
3600 			 * Build the directory record xdr
3601 			 */
3602 			if (nd->nd_flag & ND_NFSV3) {
3603 				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
3604 				*tl++ = newnfs_true;
3605 				txdr_hyper(dp->d_fileno, tl);
3606 				dirlen += nfsm_strtom(nd, dp->d_name, nlen);
3607 				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
3608 				txdr_hyper(*cookiep, tl);
3609 				nfsrv_postopattr(nd, 0, nvap);
3610 				dirlen += nfsm_fhtom(NULL, nd, (u_int8_t *)&nfh,
3611 				    0, 1);
3612 				dirlen += (5*NFSX_UNSIGNED+NFSX_V3POSTOPATTR);
3613 				if (nvp != NULL)
3614 					vput(nvp);
3615 			} else {
3616 				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
3617 				*tl++ = newnfs_true;
3618 				txdr_hyper(*cookiep, tl);
3619 				dirlen += nfsm_strtom(nd, dp->d_name, nlen);
3620 				xattrsupp = false;
3621 				has_hiddensystem = false;
3622 				has_namedattr = false;
3623 				has_caseinsensitive = false;
3624 				clone_blksize = 0;
3625 				if (nvp != NULL) {
3626 					supports_nfsv4acls =
3627 					    nfs_supportsacls(nvp);
3628 					if (NFSISSET_ATTRBIT(&attrbits,
3629 					    NFSATTRBIT_XATTRSUPPORT)) {
3630 						ret = VOP_GETEXTATTR(nvp,
3631 						    EXTATTR_NAMESPACE_USER,
3632 						    "xxx", NULL, &atsiz,
3633 						    nd->nd_cred, p);
3634 						xattrsupp = ret != EOPNOTSUPP;
3635 					}
3636 					if (VOP_PATHCONF(nvp,
3637 					    _PC_HAS_HIDDENSYSTEM, &pathval) !=
3638 					    0)
3639 						pathval = 0;
3640 					has_hiddensystem = pathval > 0;
3641 					pathval = 0;
3642 					if (NFSISSET_ATTRBIT(&attrbits,
3643 					    NFSATTRBIT_NAMEDATTR) &&
3644 					    VOP_PATHCONF(nvp, _PC_HAS_NAMEDATTR,
3645 					    &pathval) != 0)
3646 						pathval = 0;
3647 					has_namedattr = pathval > 0;
3648 					pathval = 0;
3649 					if (VOP_PATHCONF(nvp, _PC_CLONE_BLKSIZE,
3650 					    &pathval) != 0)
3651 						pathval = 0;
3652 					clone_blksize = pathval;
3653 					if (VOP_PATHCONF(nvp,
3654 					    _PC_CASE_INSENSITIVE,
3655 					    &pathval) != 0)
3656 						pathval = 0;
3657 					has_caseinsensitive = pathval > 0;
3658 					NFSVOPUNLOCK(nvp);
3659 				} else
3660 					supports_nfsv4acls = 0;
3661 				if (refp != NULL) {
3662 					dirlen += nfsrv_putreferralattr(nd,
3663 					    &refbits, refp, 0,
3664 					    &nd->nd_repstat);
3665 					if (nd->nd_repstat) {
3666 						if (nvp != NULL)
3667 							vrele(nvp);
3668 						if (needs_unbusy != 0)
3669 							vfs_unbusy(new_mp);
3670 						break;
3671 					}
3672 				} else if (r) {
3673 					dirlen += nfsvno_fillattr(nd, new_mp,
3674 					    nvp, nvap, &nfh, r, &rderrbits,
3675 					    nd->nd_cred, p, isdgram, 0,
3676 					    supports_nfsv4acls, at_root,
3677 					    mounted_on_fileno, xattrsupp,
3678 					    has_hiddensystem, has_namedattr,
3679 					    clone_blksize, has_caseinsensitive);
3680 				} else {
3681 					dirlen += nfsvno_fillattr(nd, new_mp,
3682 					    nvp, nvap, &nfh, r, &attrbits,
3683 					    nd->nd_cred, p, isdgram, 0,
3684 					    supports_nfsv4acls, at_root,
3685 					    mounted_on_fileno, xattrsupp,
3686 					    has_hiddensystem, has_namedattr,
3687 					    clone_blksize, has_caseinsensitive);
3688 				}
3689 				if (nvp != NULL)
3690 					vrele(nvp);
3691 				dirlen += (3 * NFSX_UNSIGNED);
3692 			}
3693 			if (needs_unbusy != 0)
3694 				vfs_unbusy(new_mp);
3695 			if (dirlen <= cnt)
3696 				entrycnt++;
3697 		}
3698 invalid:
3699 		cpos += dp->d_reclen;
3700 		dp = (struct dirent *)cpos;
3701 		cookiep++;
3702 		ncookies--;
3703 	}
3704 	vrele(vp);
3705 	vfs_unbusy(mp);
3706 
3707 	/*
3708 	 * If dirlen > cnt, we must strip off the last entry. If that
3709 	 * results in an empty reply, report NFSERR_TOOSMALL.
3710 	 */
3711 	if (dirlen > cnt || nd->nd_repstat) {
3712 		if (!nd->nd_repstat && entrycnt == 0)
3713 			nd->nd_repstat = NFSERR_TOOSMALL;
3714 		if (nd->nd_repstat) {
3715 			nfsm_trimtrailing(nd, mb0, bpos0, bextpg0, bextpgsiz0);
3716 			if (nd->nd_flag & ND_NFSV3)
3717 				nfsrv_postopattr(nd, getret, &at);
3718 		} else
3719 			nfsm_trimtrailing(nd, mb1, bpos1, bextpg1, bextpgsiz1);
3720 		eofflag = 0;
3721 	} else if (cpos < cend)
3722 		eofflag = 0;
3723 	if (!nd->nd_repstat) {
3724 		NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
3725 		*tl++ = newnfs_false;
3726 		if (eofflag)
3727 			*tl = newnfs_true;
3728 		else
3729 			*tl = newnfs_false;
3730 	}
3731 	free(cookies, M_TEMP);
3732 	free(rbuf, M_TEMP);
3733 
3734 out:
3735 	NFSEXITCODE2(0, nd);
3736 	return (0);
3737 nfsmout:
3738 	vput(vp);
3739 	NFSEXITCODE2(error, nd);
3740 	return (error);
3741 }
3742 
3743 /*
3744  * Get the settable attributes out of the mbuf list.
3745  * (Return 0 or EBADRPC)
3746  */
3747 int
nfsrv_sattr(struct nfsrv_descript * nd,vnode_t vp,struct nfsvattr * nvap,nfsattrbit_t * attrbitp,NFSACL_T * aclp,NFSACL_T * daclp,struct thread * p)3748 nfsrv_sattr(struct nfsrv_descript *nd, vnode_t vp, struct nfsvattr *nvap,
3749     nfsattrbit_t *attrbitp, NFSACL_T *aclp, NFSACL_T *daclp, struct thread *p)
3750 {
3751 	u_int32_t *tl;
3752 	struct nfsv2_sattr *sp;
3753 	int error = 0, toclient = 0;
3754 
3755 	switch (nd->nd_flag & (ND_NFSV2 | ND_NFSV3 | ND_NFSV4)) {
3756 	case ND_NFSV2:
3757 		NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
3758 		/*
3759 		 * Some old clients didn't fill in the high order 16bits.
3760 		 * --> check the low order 2 bytes for 0xffff
3761 		 */
3762 		if ((fxdr_unsigned(int, sp->sa_mode) & 0xffff) != 0xffff)
3763 			nvap->na_mode = nfstov_mode(sp->sa_mode);
3764 		if (sp->sa_uid != newnfs_xdrneg1)
3765 			nvap->na_uid = fxdr_unsigned(uid_t, sp->sa_uid);
3766 		if (sp->sa_gid != newnfs_xdrneg1)
3767 			nvap->na_gid = fxdr_unsigned(gid_t, sp->sa_gid);
3768 		if (sp->sa_size != newnfs_xdrneg1)
3769 			nvap->na_size = fxdr_unsigned(u_quad_t, sp->sa_size);
3770 		if (sp->sa_atime.nfsv2_sec != newnfs_xdrneg1) {
3771 #ifdef notyet
3772 			fxdr_nfsv2time(&sp->sa_atime, &nvap->na_atime);
3773 #else
3774 			nvap->na_atime.tv_sec =
3775 				fxdr_unsigned(u_int32_t,sp->sa_atime.nfsv2_sec);
3776 			nvap->na_atime.tv_nsec = 0;
3777 #endif
3778 		}
3779 		if (sp->sa_mtime.nfsv2_sec != newnfs_xdrneg1)
3780 			fxdr_nfsv2time(&sp->sa_mtime, &nvap->na_mtime);
3781 		break;
3782 	case ND_NFSV3:
3783 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3784 		if (*tl == newnfs_true) {
3785 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3786 			nvap->na_mode = nfstov_mode(*tl);
3787 		}
3788 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3789 		if (*tl == newnfs_true) {
3790 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3791 			nvap->na_uid = fxdr_unsigned(uid_t, *tl);
3792 		}
3793 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3794 		if (*tl == newnfs_true) {
3795 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3796 			nvap->na_gid = fxdr_unsigned(gid_t, *tl);
3797 		}
3798 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3799 		if (*tl == newnfs_true) {
3800 			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
3801 			nvap->na_size = fxdr_hyper(tl);
3802 		}
3803 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3804 		switch (fxdr_unsigned(int, *tl)) {
3805 		case NFSV3SATTRTIME_TOCLIENT:
3806 			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
3807 			fxdr_nfsv3time(tl, &nvap->na_atime);
3808 			toclient = 1;
3809 			break;
3810 		case NFSV3SATTRTIME_TOSERVER:
3811 			vfs_timestamp(&nvap->na_atime);
3812 			nvap->na_vaflags |= VA_UTIMES_NULL;
3813 			break;
3814 		}
3815 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3816 		switch (fxdr_unsigned(int, *tl)) {
3817 		case NFSV3SATTRTIME_TOCLIENT:
3818 			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
3819 			fxdr_nfsv3time(tl, &nvap->na_mtime);
3820 			nvap->na_vaflags &= ~VA_UTIMES_NULL;
3821 			break;
3822 		case NFSV3SATTRTIME_TOSERVER:
3823 			vfs_timestamp(&nvap->na_mtime);
3824 			if (!toclient)
3825 				nvap->na_vaflags |= VA_UTIMES_NULL;
3826 			break;
3827 		}
3828 		break;
3829 	case ND_NFSV4:
3830 		error = nfsv4_sattr(nd, vp, nvap, attrbitp, aclp, daclp, p);
3831 	}
3832 nfsmout:
3833 	NFSEXITCODE2(error, nd);
3834 	return (error);
3835 }
3836 
3837 /*
3838  * Handle the setable attributes for V4.
3839  * Returns NFSERR_BADXDR if it can't be parsed, 0 otherwise.
3840  */
3841 int
nfsv4_sattr(struct nfsrv_descript * nd,vnode_t vp,struct nfsvattr * nvap,nfsattrbit_t * attrbitp,NFSACL_T * aclp,NFSACL_T * daclp,struct thread * p)3842 nfsv4_sattr(struct nfsrv_descript *nd, vnode_t vp, struct nfsvattr *nvap,
3843     nfsattrbit_t *attrbitp, NFSACL_T *aclp, NFSACL_T *daclp, struct thread *p)
3844 {
3845 	u_int32_t *tl;
3846 	int attrsum = 0;
3847 	int i, j;
3848 	int error, attrsize, bitpos, aclsize, aceerr, retnotsup = 0;
3849 	int moderet, toclient = 0;
3850 	u_char *cp, namestr[NFSV4_SMALLSTR + 1];
3851 	uid_t uid;
3852 	gid_t gid;
3853 	u_short mode, mask;		/* Same type as va_mode. */
3854 	struct vattr va;
3855 
3856 	error = nfsrv_getattrbits(nd, attrbitp, NULL, &retnotsup);
3857 	if (error)
3858 		goto nfsmout;
3859 	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3860 	attrsize = fxdr_unsigned(int, *tl);
3861 
3862 	/*
3863 	 * Loop around getting the setable attributes. If an unsupported
3864 	 * one is found, set nd_repstat == NFSERR_ATTRNOTSUPP and return.
3865 	 * Once nd_repstat != 0, do not set the attribute value, but keep
3866 	 * parsing the attribute(s).
3867 	 */
3868 	if (retnotsup) {
3869 		nd->nd_repstat = NFSERR_ATTRNOTSUPP;
3870 		bitpos = NFSATTRBIT_MAX;
3871 	} else {
3872 		bitpos = 0;
3873 		if (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_ARCHIVE) ||
3874 		    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_HIDDEN) ||
3875 		    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SYSTEM))
3876 			nvap->na_flags = 0;
3877 		if (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_ACL) &&
3878 		    (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_POSIXDEFAULTACL) ||
3879 		     NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_POSIXACCESSACL)))
3880 			nd->nd_repstat = NFSERR_INVAL;
3881 	}
3882 	moderet = 0;
3883 	for (; bitpos < NFSATTRBIT_MAX; bitpos++) {
3884 	    if (attrsum > attrsize) {
3885 		error = NFSERR_BADXDR;
3886 		goto nfsmout;
3887 	    }
3888 	    if (NFSISSET_ATTRBIT(attrbitp, bitpos))
3889 		switch (bitpos) {
3890 		case NFSATTRBIT_SIZE:
3891 			NFSM_DISSECT(tl, u_int32_t *, NFSX_HYPER);
3892 			if (!nd->nd_repstat) {
3893 				if (vp != NULL && vp->v_type != VREG)
3894 					nd->nd_repstat = (vp->v_type == VDIR) ?
3895 					    NFSERR_ISDIR : NFSERR_INVAL;
3896 				else
3897 					nvap->na_size = fxdr_hyper(tl);
3898 			}
3899 			attrsum += NFSX_HYPER;
3900 			break;
3901 		case NFSATTRBIT_ACL:
3902 			error = nfsrv_dissectacl(nd, aclp, true, false, &aceerr,
3903 			    &aclsize);
3904 			if (error)
3905 				goto nfsmout;
3906 			if (aceerr && !nd->nd_repstat)
3907 				nd->nd_repstat = aceerr;
3908 			attrsum += aclsize;
3909 			break;
3910 		case NFSATTRBIT_ARCHIVE:
3911 			NFSM_DISSECT(tl, uint32_t *, NFSX_UNSIGNED);
3912 			if (nd->nd_repstat == 0) {
3913 				if (*tl == newnfs_true)
3914 					nvap->na_flags |= UF_ARCHIVE;
3915 			}
3916 			attrsum += NFSX_UNSIGNED;
3917 			break;
3918 		case NFSATTRBIT_HIDDEN:
3919 			NFSM_DISSECT(tl, uint32_t *, NFSX_UNSIGNED);
3920 			if (nd->nd_repstat == 0) {
3921 				if (*tl == newnfs_true)
3922 					nvap->na_flags |= UF_HIDDEN;
3923 			}
3924 			attrsum += NFSX_UNSIGNED;
3925 			break;
3926 		case NFSATTRBIT_MIMETYPE:
3927 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3928 			i = fxdr_unsigned(int, *tl);
3929 			error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
3930 			if (error)
3931 				goto nfsmout;
3932 			if (!nd->nd_repstat)
3933 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
3934 			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(i));
3935 			break;
3936 		case NFSATTRBIT_MODE:
3937 			moderet = NFSERR_INVAL;	/* Can't do MODESETMASKED. */
3938 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3939 			if (!nd->nd_repstat)
3940 				nvap->na_mode = nfstov_mode(*tl);
3941 			attrsum += NFSX_UNSIGNED;
3942 			break;
3943 		case NFSATTRBIT_OWNER:
3944 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3945 			j = fxdr_unsigned(int, *tl);
3946 			if (j < 0) {
3947 				error = NFSERR_BADXDR;
3948 				goto nfsmout;
3949 			}
3950 			if (j > NFSV4_SMALLSTR)
3951 				cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
3952 			else
3953 				cp = namestr;
3954 			error = nfsrv_mtostr(nd, cp, j);
3955 			if (error) {
3956 				if (j > NFSV4_SMALLSTR)
3957 					free(cp, M_NFSSTRING);
3958 				goto nfsmout;
3959 			}
3960 			if (!nd->nd_repstat) {
3961 				nd->nd_repstat = nfsv4_strtouid(nd, cp, j,
3962 				    &uid);
3963 				if (!nd->nd_repstat)
3964 					nvap->na_uid = uid;
3965 			}
3966 			if (j > NFSV4_SMALLSTR)
3967 				free(cp, M_NFSSTRING);
3968 			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
3969 			break;
3970 		case NFSATTRBIT_OWNERGROUP:
3971 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3972 			j = fxdr_unsigned(int, *tl);
3973 			if (j < 0) {
3974 				error = NFSERR_BADXDR;
3975 				goto nfsmout;
3976 			}
3977 			if (j > NFSV4_SMALLSTR)
3978 				cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
3979 			else
3980 				cp = namestr;
3981 			error = nfsrv_mtostr(nd, cp, j);
3982 			if (error) {
3983 				if (j > NFSV4_SMALLSTR)
3984 					free(cp, M_NFSSTRING);
3985 				goto nfsmout;
3986 			}
3987 			if (!nd->nd_repstat) {
3988 				nd->nd_repstat = nfsv4_strtogid(nd, cp, j,
3989 				    &gid);
3990 				if (!nd->nd_repstat)
3991 					nvap->na_gid = gid;
3992 			}
3993 			if (j > NFSV4_SMALLSTR)
3994 				free(cp, M_NFSSTRING);
3995 			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
3996 			break;
3997 		case NFSATTRBIT_SYSTEM:
3998 			NFSM_DISSECT(tl, uint32_t *, NFSX_UNSIGNED);
3999 			if (nd->nd_repstat == 0) {
4000 				if (*tl == newnfs_true)
4001 					nvap->na_flags |= UF_SYSTEM;
4002 			}
4003 			attrsum += NFSX_UNSIGNED;
4004 			break;
4005 		case NFSATTRBIT_TIMEACCESSSET:
4006 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
4007 			attrsum += NFSX_UNSIGNED;
4008 			if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
4009 			    NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
4010 			    if (!nd->nd_repstat)
4011 				fxdr_nfsv4time(tl, &nvap->na_atime);
4012 			    toclient = 1;
4013 			    attrsum += NFSX_V4TIME;
4014 			} else if (!nd->nd_repstat) {
4015 			    vfs_timestamp(&nvap->na_atime);
4016 			    nvap->na_vaflags |= VA_UTIMES_NULL;
4017 			}
4018 			break;
4019 		case NFSATTRBIT_TIMEBACKUP:
4020 			NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
4021 			if (!nd->nd_repstat)
4022 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
4023 			attrsum += NFSX_V4TIME;
4024 			break;
4025 		case NFSATTRBIT_TIMECREATE:
4026 			NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
4027 			if (!nd->nd_repstat)
4028 				fxdr_nfsv4time(tl, &nvap->na_btime);
4029 			attrsum += NFSX_V4TIME;
4030 			break;
4031 		case NFSATTRBIT_TIMEMODIFYSET:
4032 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
4033 			attrsum += NFSX_UNSIGNED;
4034 			if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
4035 			    NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
4036 			    if (!nd->nd_repstat)
4037 				fxdr_nfsv4time(tl, &nvap->na_mtime);
4038 			    nvap->na_vaflags &= ~VA_UTIMES_NULL;
4039 			    attrsum += NFSX_V4TIME;
4040 			} else if (!nd->nd_repstat) {
4041 			    vfs_timestamp(&nvap->na_mtime);
4042 			    if (!toclient)
4043 				nvap->na_vaflags |= VA_UTIMES_NULL;
4044 			}
4045 			break;
4046 		case NFSATTRBIT_MODESETMASKED:
4047 			NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
4048 			mode = fxdr_unsigned(u_short, *tl++);
4049 			mask = fxdr_unsigned(u_short, *tl);
4050 			/*
4051 			 * vp == NULL implies an Open/Create operation.
4052 			 * This attribute can only be used for Setattr and
4053 			 * only for NFSv4.1 or higher.
4054 			 * If moderet != 0, a mode attribute has also been
4055 			 * specified and this attribute cannot be done in the
4056 			 * same Setattr operation.
4057 			 */
4058 			if (!nd->nd_repstat) {
4059 				if ((nd->nd_flag & ND_NFSV41) == 0)
4060 					nd->nd_repstat = NFSERR_ATTRNOTSUPP;
4061 				else if ((mode & ~07777) != 0 ||
4062 				    (mask & ~07777) != 0 || vp == NULL)
4063 					nd->nd_repstat = NFSERR_INVAL;
4064 				else if (moderet == 0)
4065 					moderet = VOP_GETATTR(vp, &va,
4066 					    nd->nd_cred);
4067 				if (moderet == 0)
4068 					nvap->na_mode = (mode & mask) |
4069 					    (va.va_mode & ~mask);
4070 				else
4071 					nd->nd_repstat = moderet;
4072 			}
4073 			attrsum += 2 * NFSX_UNSIGNED;
4074 			break;
4075 		case NFSATTRBIT_MODEUMASK:
4076 			NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
4077 			mode = fxdr_unsigned(u_short, *tl++);
4078 			mask = fxdr_unsigned(u_short, *tl);
4079 			/*
4080 			 * If moderet != 0, mode has already been done.
4081 			 * If vp != NULL, this is not a file object creation.
4082 			 */
4083 			if (!nd->nd_repstat) {
4084 				if ((nd->nd_flag & ND_NFSV42) == 0)
4085 					nd->nd_repstat = NFSERR_ATTRNOTSUPP;
4086 				else if ((mask & ~0777) != 0 || vp != NULL ||
4087 				    moderet != 0)
4088 					nd->nd_repstat = NFSERR_INVAL;
4089 				else
4090 					nvap->na_mode = (mode & ~mask);
4091 			}
4092 			attrsum += 2 * NFSX_UNSIGNED;
4093 			break;
4094 		case NFSATTRBIT_POSIXACCESSACL:
4095 			error = nfsrv_dissectacl(nd, aclp, true, true, &aceerr,
4096 			    &aclsize);
4097 			if (error != 0)
4098 				goto nfsmout;
4099 			if (!nd->nd_repstat) {
4100 				if ((nd->nd_flag & ND_NFSV42) == 0)
4101 					nd->nd_repstat = NFSERR_ATTRNOTSUPP;
4102 				else if (aclp != NULL && aclp->acl_cnt == 0)
4103 					nd->nd_repstat = NFSERR_INVAL;
4104 				else if (aceerr != 0)
4105 					nd->nd_repstat = aceerr;
4106 			}
4107 			attrsum += aclsize;
4108 			break;
4109 		case NFSATTRBIT_POSIXDEFAULTACL:
4110 			error = nfsrv_dissectacl(nd, daclp, true, true, &aceerr,
4111 			    &aclsize);
4112 			if (error != 0)
4113 				goto nfsmout;
4114 			if (!nd->nd_repstat) {
4115 				if ((nd->nd_flag & ND_NFSV42) == 0)
4116 					nd->nd_repstat = NFSERR_ATTRNOTSUPP;
4117 				else if (aclp != NULL && aclp->acl_cnt == 0)
4118 					nd->nd_repstat = NFSERR_INVAL;
4119 				else if (aceerr != 0)
4120 					nd->nd_repstat = aceerr;
4121 				else if (vp != NULL && vp->v_type != VDIR)
4122 					nd->nd_repstat = NFSERR_INVAL;
4123 			}
4124 			attrsum += aclsize;
4125 			break;
4126 		default:
4127 			nd->nd_repstat = NFSERR_ATTRNOTSUPP;
4128 			/*
4129 			 * set bitpos so we drop out of the loop.
4130 			 */
4131 			bitpos = NFSATTRBIT_MAX;
4132 			break;
4133 		}
4134 	}
4135 
4136 	/*
4137 	 * some clients pad the attrlist, so we need to skip over the
4138 	 * padding.  This also skips over unparsed non-supported attributes.
4139 	 */
4140 	if (attrsum > attrsize) {
4141 		error = NFSERR_BADXDR;
4142 	} else {
4143 		attrsize = NFSM_RNDUP(attrsize);
4144 		if (attrsum < attrsize)
4145 			error = nfsm_advance(nd, attrsize - attrsum, -1);
4146 	}
4147 nfsmout:
4148 	NFSEXITCODE2(error, nd);
4149 	return (error);
4150 }
4151 
4152 /*
4153  * Check/setup export credentials.
4154  */
4155 int
nfsd_excred(struct nfsrv_descript * nd,struct nfsexstuff * exp,struct ucred * credanon,bool testsec)4156 nfsd_excred(struct nfsrv_descript *nd, struct nfsexstuff *exp,
4157     struct ucred *credanon, bool testsec)
4158 {
4159 	int error;
4160 
4161 	/*
4162 	 * Check/setup credentials.
4163 	 */
4164 	if (nd->nd_flag & ND_GSS)
4165 		exp->nes_exflag &= ~MNT_EXPORTANON;
4166 
4167 	/*
4168 	 * Check to see if the operation is allowed for this security flavor.
4169 	 */
4170 	error = 0;
4171 	if (testsec) {
4172 		error = nfsvno_testexp(nd, exp);
4173 		if (error != 0)
4174 			goto out;
4175 	}
4176 
4177 	/*
4178 	 * Check to see if the file system is exported V4 only.
4179 	 */
4180 	if (NFSVNO_EXV4ONLY(exp) && !(nd->nd_flag & ND_NFSV4)) {
4181 		error = NFSERR_PROGNOTV4;
4182 		goto out;
4183 	}
4184 
4185 	/*
4186 	 * Now, map the user credentials.
4187 	 * (Note that ND_AUTHNONE will only be set for an NFSv3
4188 	 *  Fsinfo RPC. If set for anything else, this code might need
4189 	 *  to change.)
4190 	 */
4191 	if (NFSVNO_EXPORTED(exp)) {
4192 		if (((nd->nd_flag & ND_GSS) == 0 && nd->nd_cred->cr_uid == 0) ||
4193 		     NFSVNO_EXPORTANON(exp) ||
4194 		     (nd->nd_flag & ND_AUTHNONE) != 0) {
4195 			nd->nd_cred->cr_uid = credanon->cr_uid;
4196 			nd->nd_cred->cr_gid = credanon->cr_gid;
4197 			crsetgroups(nd->nd_cred, credanon->cr_ngroups,
4198 			    credanon->cr_groups);
4199 		} else if ((nd->nd_flag & ND_GSS) == 0) {
4200 			/*
4201 			 * If using AUTH_SYS, call nfsrv_getgrpscred() to see
4202 			 * if there is a replacement credential with a group
4203 			 * list set up by "nfsuserd -manage-gids".
4204 			 * If there is no replacement, nfsrv_getgrpscred()
4205 			 * simply returns its argument.
4206 			 */
4207 			nd->nd_cred = nfsrv_getgrpscred(nd->nd_cred);
4208 		}
4209 	}
4210 
4211 out:
4212 	NFSEXITCODE2(error, nd);
4213 	return (error);
4214 }
4215 
4216 /*
4217  * Check exports.
4218  */
4219 int
nfsvno_checkexp(struct mount * mp,struct sockaddr * nam,struct nfsexstuff * exp,struct ucred ** credp)4220 nfsvno_checkexp(struct mount *mp, struct sockaddr *nam, struct nfsexstuff *exp,
4221     struct ucred **credp)
4222 {
4223 	int error;
4224 
4225 	error = 0;
4226 	*credp = NULL;
4227 	MNT_ILOCK(mp);
4228 	if (mp->mnt_exjail == NULL ||
4229 	    mp->mnt_exjail->cr_prison != curthread->td_ucred->cr_prison)
4230 		error = EACCES;
4231 	MNT_IUNLOCK(mp);
4232 	if (error == 0)
4233 		error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
4234 		    &exp->nes_numsecflavor, exp->nes_secflavors);
4235 	if (error) {
4236 		if (VNET(nfs_rootfhset)) {
4237 			exp->nes_exflag = 0;
4238 			exp->nes_numsecflavor = 0;
4239 			error = 0;
4240 		}
4241 	} else if (exp->nes_numsecflavor < 1 || exp->nes_numsecflavor >
4242 	    MAXSECFLAVORS) {
4243 		printf("nfsvno_checkexp: numsecflavors out of range\n");
4244 		exp->nes_numsecflavor = 0;
4245 		error = EACCES;
4246 	}
4247 	NFSEXITCODE(error);
4248 	return (error);
4249 }
4250 
4251 /*
4252  * Get a vnode for a file handle and export stuff.
4253  */
4254 int
nfsvno_fhtovp(struct mount * mp,fhandle_t * fhp,struct sockaddr * nam,int lktype,struct vnode ** vpp,struct nfsexstuff * exp,struct ucred ** credp)4255 nfsvno_fhtovp(struct mount *mp, fhandle_t *fhp, struct sockaddr *nam,
4256     int lktype, struct vnode **vpp, struct nfsexstuff *exp,
4257     struct ucred **credp)
4258 {
4259 	int error;
4260 
4261 	*credp = NULL;
4262 	exp->nes_numsecflavor = 0;
4263 	error = VFS_FHTOVP(mp, &fhp->fh_fid, lktype, vpp);
4264 	if (error != 0)
4265 		/* Make sure the server replies ESTALE to the client. */
4266 		error = ESTALE;
4267 	if (nam && !error) {
4268 		MNT_ILOCK(mp);
4269 		if (mp->mnt_exjail == NULL ||
4270 		    mp->mnt_exjail->cr_prison != curthread->td_ucred->cr_prison)
4271 			error = EACCES;
4272 		MNT_IUNLOCK(mp);
4273 		if (error == 0)
4274 			error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
4275 			    &exp->nes_numsecflavor, exp->nes_secflavors);
4276 		if (error) {
4277 			if (VNET(nfs_rootfhset)) {
4278 				exp->nes_exflag = 0;
4279 				exp->nes_numsecflavor = 0;
4280 				error = 0;
4281 			} else {
4282 				vput(*vpp);
4283 			}
4284 		} else if (exp->nes_numsecflavor < 1 || exp->nes_numsecflavor >
4285 		    MAXSECFLAVORS) {
4286 			printf("nfsvno_fhtovp: numsecflavors out of range\n");
4287 			exp->nes_numsecflavor = 0;
4288 			error = EACCES;
4289 			vput(*vpp);
4290 		}
4291 	}
4292 	NFSEXITCODE(error);
4293 	return (error);
4294 }
4295 
4296 /*
4297  * nfsd_fhtovp() - convert a fh to a vnode ptr
4298  * 	- look up fsid in mount list (if not found ret error)
4299  *	- get vp and export rights by calling nfsvno_fhtovp()
4300  *	- if cred->cr_uid == 0 or MNT_EXPORTANON set it to credanon
4301  *	  for AUTH_SYS
4302  *	- if mpp != NULL, return the mount point so that it can
4303  *	  be used for vn_finished_write() by the caller
4304  */
4305 void
nfsd_fhtovp(struct nfsrv_descript * nd,struct nfsrvfh * nfp,int lktype,struct vnode ** vpp,struct nfsexstuff * exp,struct mount ** mpp,int startwrite,int nextop)4306 nfsd_fhtovp(struct nfsrv_descript *nd, struct nfsrvfh *nfp, int lktype,
4307     struct vnode **vpp, struct nfsexstuff *exp,
4308     struct mount **mpp, int startwrite, int nextop)
4309 {
4310 	struct mount *mp, *mpw;
4311 	struct ucred *credanon;
4312 	fhandle_t *fhp;
4313 	int error;
4314 
4315 	if (mpp != NULL)
4316 		*mpp = NULL;
4317 	*vpp = NULL;
4318 	fhp = (fhandle_t *)nfp->nfsrvfh_data;
4319 	mp = vfs_busyfs(&fhp->fh_fsid);
4320 	if (mp == NULL) {
4321 		nd->nd_repstat = ESTALE;
4322 		goto out;
4323 	}
4324 
4325 	if (startwrite) {
4326 		mpw = mp;
4327 		error = vn_start_write(NULL, &mpw, V_WAIT);
4328 		if (error != 0) {
4329 			mpw = NULL;
4330 			vfs_unbusy(mp);
4331 			nd->nd_repstat = ESTALE;
4332 			goto out;
4333 		}
4334 		if (lktype == LK_SHARED && !(MNT_SHARED_WRITES(mp)))
4335 			lktype = LK_EXCLUSIVE;
4336 	} else
4337 		mpw = NULL;
4338 
4339 	nd->nd_repstat = nfsvno_fhtovp(mp, fhp, nd->nd_nam, lktype, vpp, exp,
4340 	    &credanon);
4341 	vfs_unbusy(mp);
4342 
4343 	if (nd->nd_repstat == 0 &&
4344 	    nfp->nfsrvfh_len >= NFSX_MYFH + NFSX_V4NAMEDDIRFH &&
4345 	    nfp->nfsrvfh_len <= NFSX_MYFH + NFSX_V4NAMEDATTRFH) {
4346 		if (nfp->nfsrvfh_len == NFSX_MYFH + NFSX_V4NAMEDDIRFH)
4347 			vn_irflag_set_cond(*vpp, VIRF_NAMEDDIR);
4348 		else
4349 			vn_irflag_set_cond(*vpp, VIRF_NAMEDATTR);
4350 	}
4351 
4352 	/*
4353 	 * For NFSv4 without a pseudo root fs, unexported file handles
4354 	 * can be returned, so that Lookup works everywhere.
4355 	 */
4356 	if (!nd->nd_repstat && exp->nes_exflag == 0 &&
4357 	    !(nd->nd_flag & ND_NFSV4)) {
4358 		vput(*vpp);
4359 		*vpp = NULL;
4360 		nd->nd_repstat = EACCES;
4361 	}
4362 
4363 	/*
4364 	 * Personally, I've never seen any point in requiring a
4365 	 * reserved port#, since only in the rare case where the
4366 	 * clients are all boxes with secure system privileges,
4367 	 * does it provide any enhanced security, but... some people
4368 	 * believe it to be useful and keep putting this code back in.
4369 	 * (There is also some "security checker" out there that
4370 	 *  complains if the nfs server doesn't enforce this.)
4371 	 * However, note the following:
4372 	 * RFC3530 (NFSv4) specifies that a reserved port# not be
4373 	 *	required.
4374 	 * RFC2623 recommends that, if a reserved port# is checked for,
4375 	 *	that there be a way to turn that off--> ifdef'd.
4376 	 */
4377 #ifdef NFS_REQRSVPORT
4378 	if (!nd->nd_repstat) {
4379 		struct sockaddr_in *saddr;
4380 		struct sockaddr_in6 *saddr6;
4381 
4382 		saddr = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in *);
4383 		saddr6 = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in6 *);
4384 		if (!(nd->nd_flag & ND_NFSV4) &&
4385 		    ((saddr->sin_family == AF_INET &&
4386 		      ntohs(saddr->sin_port) >= IPPORT_RESERVED) ||
4387 		     (saddr6->sin6_family == AF_INET6 &&
4388 		      ntohs(saddr6->sin6_port) >= IPPORT_RESERVED))) {
4389 			vput(*vpp);
4390 			nd->nd_repstat = (NFSERR_AUTHERR | AUTH_TOOWEAK);
4391 		}
4392 	}
4393 #endif	/* NFS_REQRSVPORT */
4394 
4395 	/*
4396 	 * Check/setup credentials.
4397 	 */
4398 	if (!nd->nd_repstat) {
4399 		nd->nd_saveduid = nd->nd_cred->cr_uid;
4400 		nd->nd_repstat = nfsd_excred(nd, exp, credanon,
4401 		    nfsrv_checkwrongsec(nd, nextop, (*vpp)->v_type));
4402 		if (nd->nd_repstat)
4403 			vput(*vpp);
4404 	}
4405 	if (credanon != NULL)
4406 		crfree(credanon);
4407 	if (nd->nd_repstat) {
4408 		vn_finished_write(mpw);
4409 		*vpp = NULL;
4410 	} else if (mpp != NULL) {
4411 		*mpp = mpw;
4412 	}
4413 
4414 out:
4415 	NFSEXITCODE2(0, nd);
4416 }
4417 
4418 /*
4419  * glue for fp.
4420  */
4421 static int
fp_getfvp(struct thread * p,int fd,struct file ** fpp,struct vnode ** vpp)4422 fp_getfvp(struct thread *p, int fd, struct file **fpp, struct vnode **vpp)
4423 {
4424 	struct filedesc *fdp;
4425 	struct file *fp;
4426 	int error = 0;
4427 
4428 	fdp = p->td_proc->p_fd;
4429 	if (fd < 0 || fd >= fdp->fd_nfiles ||
4430 	    (fp = fdp->fd_ofiles[fd].fde_file) == NULL) {
4431 		error = EBADF;
4432 		goto out;
4433 	}
4434 	*fpp = fp;
4435 
4436 out:
4437 	NFSEXITCODE(error);
4438 	return (error);
4439 }
4440 
4441 /*
4442  * Called from nfssvc() to update the exports list. Just call
4443  * vfs_export(). This has to be done, since the v4 root fake fs isn't
4444  * in the mount list.
4445  */
4446 int
nfsrv_v4rootexport(void * argp,struct ucred * cred,struct thread * p)4447 nfsrv_v4rootexport(void *argp, struct ucred *cred, struct thread *p)
4448 {
4449 	struct nfsex_args *nfsexargp = (struct nfsex_args *)argp;
4450 	int error = 0;
4451 	struct nameidata nd;
4452 	fhandle_t fh;
4453 
4454 	error = vfs_export(VNET(nfsv4root_mnt), &nfsexargp->export, false);
4455 	if ((nfsexargp->export.ex_flags & MNT_DELEXPORT) != 0)
4456 		VNET(nfs_rootfhset) = 0;
4457 	else if (error == 0) {
4458 		if (nfsexargp->fspec == NULL) {
4459 			error = EPERM;
4460 			goto out;
4461 		}
4462 		/*
4463 		 * If fspec != NULL, this is the v4root path.
4464 		 */
4465 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, nfsexargp->fspec);
4466 		if ((error = namei(&nd)) != 0)
4467 			goto out;
4468 		NDFREE_PNBUF(&nd);
4469 		error = nfsvno_getfh(nd.ni_vp, &fh, p);
4470 		vrele(nd.ni_vp);
4471 		if (!error) {
4472 			VNET(nfs_rootfh).nfsrvfh_len = NFSX_MYFH;
4473 			NFSBCOPY((caddr_t)&fh,
4474 			    VNET(nfs_rootfh).nfsrvfh_data,
4475 			    sizeof (fhandle_t));
4476 			VNET(nfs_rootfhset) = 1;
4477 		}
4478 	}
4479 
4480 out:
4481 	NFSEXITCODE(error);
4482 	return (error);
4483 }
4484 
4485 /*
4486  * This function needs to test to see if the system is near its limit
4487  * for memory allocation via malloc() or mget() and return True iff
4488  * either of these resources are near their limit.
4489  * XXX (For now, this is just a stub.)
4490  */
4491 int nfsrv_testmalloclimit = 0;
4492 int
nfsrv_mallocmget_limit(void)4493 nfsrv_mallocmget_limit(void)
4494 {
4495 	static int printmesg = 0;
4496 	static int testval = 1;
4497 
4498 	if (nfsrv_testmalloclimit && (testval++ % 1000) == 0) {
4499 		if ((printmesg++ % 100) == 0)
4500 			printf("nfsd: malloc/mget near limit\n");
4501 		return (1);
4502 	}
4503 	return (0);
4504 }
4505 
4506 /*
4507  * BSD specific initialization of a mount point.
4508  */
4509 void
nfsd_mntinit(void)4510 nfsd_mntinit(void)
4511 {
4512 
4513 	NFSD_LOCK();
4514 	if (VNET(nfsrv_mntinited)) {
4515 		NFSD_UNLOCK();
4516 		return;
4517 	}
4518 	VNET(nfsrv_mntinited) = true;
4519 	nfsrvd_init(0);
4520 	NFSD_UNLOCK();
4521 
4522 	VNET(nfsv4root_mnt) = malloc(sizeof(struct mount), M_TEMP,
4523 	    M_WAITOK | M_ZERO);
4524 	VNET(nfsv4root_mnt)->mnt_flag = (MNT_RDONLY | MNT_EXPORTED);
4525 	mtx_init(&VNET(nfsv4root_mnt)->mnt_mtx, "nfs4mnt", NULL, MTX_DEF);
4526 	lockinit(&VNET(nfsv4root_mnt)->mnt_explock, PVFS, "explock", 0, 0);
4527 	TAILQ_INIT(&VNET(nfsv4root_mnt)->mnt_nvnodelist);
4528 	TAILQ_INIT(&VNET(nfsv4root_mnt)->mnt_lazyvnodelist);
4529 	VNET(nfsv4root_mnt)->mnt_export = NULL;
4530 	TAILQ_INIT(&VNET(nfsv4root_opt));
4531 	TAILQ_INIT(&VNET(nfsv4root_newopt));
4532 	VNET(nfsv4root_mnt)->mnt_opt = &VNET(nfsv4root_opt);
4533 	VNET(nfsv4root_mnt)->mnt_optnew = &VNET(nfsv4root_newopt);
4534 	VNET(nfsv4root_mnt)->mnt_nvnodelistsize = 0;
4535 	VNET(nfsv4root_mnt)->mnt_lazyvnodelistsize = 0;
4536 	callout_init(&VNET(nfsd_callout), 1);
4537 
4538 	nfsrvd_initcache();
4539 	nfsd_init();
4540 }
4541 
4542 static void
nfsd_timer(void * arg)4543 nfsd_timer(void *arg)
4544 {
4545 	struct vnet *vnetp;
4546 
4547 	vnetp = (struct vnet *)arg;
4548 	CURVNET_SET_QUIET(vnetp);
4549 	nfsrv_servertimer(vnetp);
4550 	callout_reset_sbt(&VNET(nfsd_callout), SBT_1S, SBT_1S, nfsd_timer,
4551 	    arg, 0);
4552 	CURVNET_RESTORE();
4553 }
4554 
4555 /*
4556  * Get a vnode for a file handle, without checking exports, etc.
4557  */
4558 struct vnode *
nfsvno_getvp(fhandle_t * fhp)4559 nfsvno_getvp(fhandle_t *fhp)
4560 {
4561 	struct mount *mp;
4562 	struct vnode *vp;
4563 	int error;
4564 
4565 	mp = vfs_busyfs(&fhp->fh_fsid);
4566 	if (mp == NULL)
4567 		return (NULL);
4568 	error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, &vp);
4569 	vfs_unbusy(mp);
4570 	if (error)
4571 		return (NULL);
4572 	return (vp);
4573 }
4574 
4575 /*
4576  * Do a local VOP_ADVLOCK().
4577  */
4578 int
nfsvno_advlock(struct vnode * vp,int ftype,u_int64_t first,u_int64_t end,struct thread * td)4579 nfsvno_advlock(struct vnode *vp, int ftype, u_int64_t first,
4580     u_int64_t end, struct thread *td)
4581 {
4582 	int error = 0;
4583 	struct flock fl;
4584 	u_int64_t tlen;
4585 
4586 	if (nfsrv_dolocallocks == 0)
4587 		goto out;
4588 	ASSERT_VOP_UNLOCKED(vp, "nfsvno_advlock: vp locked");
4589 
4590 	fl.l_whence = SEEK_SET;
4591 	fl.l_type = ftype;
4592 	fl.l_start = (off_t)first;
4593 	if (end == NFS64BITSSET) {
4594 		fl.l_len = 0;
4595 	} else {
4596 		tlen = end - first;
4597 		fl.l_len = (off_t)tlen;
4598 	}
4599 	/*
4600 	 * For FreeBSD8, the l_pid and l_sysid must be set to the same
4601 	 * values for all calls, so that all locks will be held by the
4602 	 * nfsd server. (The nfsd server handles conflicts between the
4603 	 * various clients.)
4604 	 * Since an NFSv4 lockowner is a ClientID plus an array of up to 1024
4605 	 * bytes, so it can't be put in l_sysid.
4606 	 */
4607 	if (nfsv4_sysid == 0)
4608 		nfsv4_sysid = nlm_acquire_next_sysid();
4609 	fl.l_pid = (pid_t)0;
4610 	fl.l_sysid = (int)nfsv4_sysid;
4611 
4612 	if (ftype == F_UNLCK)
4613 		error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_UNLCK, &fl,
4614 		    (F_POSIX | F_REMOTE));
4615 	else
4616 		error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_SETLK, &fl,
4617 		    (F_POSIX | F_REMOTE));
4618 
4619 out:
4620 	NFSEXITCODE(error);
4621 	return (error);
4622 }
4623 
4624 /*
4625  * Check the nfsv4 root exports.
4626  */
4627 int
nfsvno_v4rootexport(struct nfsrv_descript * nd)4628 nfsvno_v4rootexport(struct nfsrv_descript *nd)
4629 {
4630 	struct ucred *credanon;
4631 	int error = 0, numsecflavor, secflavors[MAXSECFLAVORS], i;
4632 	uint64_t exflags;
4633 
4634 	error = vfs_stdcheckexp(VNET(nfsv4root_mnt), nd->nd_nam, &exflags,
4635 	    &credanon, &numsecflavor, secflavors);
4636 	if (error) {
4637 		error = NFSERR_PROGUNAVAIL;
4638 		goto out;
4639 	}
4640 	if (credanon != NULL)
4641 		crfree(credanon);
4642 	for (i = 0; i < numsecflavor; i++) {
4643 		if (secflavors[i] == AUTH_SYS)
4644 			nd->nd_flag |= ND_EXAUTHSYS;
4645 		else if (secflavors[i] == RPCSEC_GSS_KRB5)
4646 			nd->nd_flag |= ND_EXGSS;
4647 		else if (secflavors[i] == RPCSEC_GSS_KRB5I)
4648 			nd->nd_flag |= ND_EXGSSINTEGRITY;
4649 		else if (secflavors[i] == RPCSEC_GSS_KRB5P)
4650 			nd->nd_flag |= ND_EXGSSPRIVACY;
4651 	}
4652 
4653 	/* And set ND_EXxx flags for TLS. */
4654 	if ((exflags & MNT_EXTLS) != 0) {
4655 		nd->nd_flag |= ND_EXTLS;
4656 		if ((exflags & MNT_EXTLSCERT) != 0)
4657 			nd->nd_flag |= ND_EXTLSCERT;
4658 		if ((exflags & MNT_EXTLSCERTUSER) != 0)
4659 			nd->nd_flag |= ND_EXTLSCERTUSER;
4660 	}
4661 
4662 out:
4663 	NFSEXITCODE(error);
4664 	return (error);
4665 }
4666 
4667 /*
4668  * Nfs server pseudo system call for the nfsd's
4669  */
4670 /*
4671  * MPSAFE
4672  */
4673 static int
nfssvc_nfsd(struct thread * td,struct nfssvc_args * uap)4674 nfssvc_nfsd(struct thread *td, struct nfssvc_args *uap)
4675 {
4676 	struct file *fp;
4677 	struct nfsd_addsock_args sockarg;
4678 	struct nfsd_nfsd_args nfsdarg;
4679 	struct nfsd_nfsd_oargs onfsdarg;
4680 	struct nfsd_pnfsd_args pnfsdarg;
4681 	struct vnode *vp, *nvp, *curdvp;
4682 	struct pnfsdsfile *pf;
4683 	struct nfsdevice *ds, *fds;
4684 	cap_rights_t rights;
4685 	int buflen, error, ret;
4686 	char *buf, *cp, *cp2, *cp3;
4687 	char fname[PNFS_FILENAME_LEN + 1];
4688 
4689 	CURVNET_SET(TD_TO_VNET(td));
4690 	if (uap->flag & NFSSVC_NFSDADDSOCK) {
4691 		error = copyin(uap->argp, (caddr_t)&sockarg, sizeof (sockarg));
4692 		if (error)
4693 			goto out;
4694 		/*
4695 		 * Since we don't know what rights might be required,
4696 		 * pretend that we need them all. It is better to be too
4697 		 * careful than too reckless.
4698 		 */
4699 		error = fget(td, sockarg.sock,
4700 		    cap_rights_init_one(&rights, CAP_SOCK_SERVER), &fp);
4701 		if (error != 0)
4702 			goto out;
4703 		if (fp->f_type != DTYPE_SOCKET) {
4704 			fdrop(fp, td);
4705 			error = EPERM;
4706 			goto out;
4707 		}
4708 		error = nfsrvd_addsock(fp);
4709 		fdrop(fp, td);
4710 	} else if (uap->flag & NFSSVC_NFSDNFSD) {
4711 		if (uap->argp == NULL) {
4712 			error = EINVAL;
4713 			goto out;
4714 		}
4715 		if ((uap->flag & NFSSVC_NEWSTRUCT) == 0) {
4716 			error = copyin(uap->argp, &onfsdarg, sizeof(onfsdarg));
4717 			if (error == 0) {
4718 				nfsdarg.principal = onfsdarg.principal;
4719 				nfsdarg.minthreads = onfsdarg.minthreads;
4720 				nfsdarg.maxthreads = onfsdarg.maxthreads;
4721 				nfsdarg.version = 1;
4722 				nfsdarg.addr = NULL;
4723 				nfsdarg.addrlen = 0;
4724 				nfsdarg.dnshost = NULL;
4725 				nfsdarg.dnshostlen = 0;
4726 				nfsdarg.dspath = NULL;
4727 				nfsdarg.dspathlen = 0;
4728 				nfsdarg.mdspath = NULL;
4729 				nfsdarg.mdspathlen = 0;
4730 				nfsdarg.mirrorcnt = 1;
4731 			}
4732 		} else
4733 			error = copyin(uap->argp, &nfsdarg, sizeof(nfsdarg));
4734 		if (error)
4735 			goto out;
4736 		if (nfsdarg.addrlen > 0 && nfsdarg.addrlen < 10000 &&
4737 		    nfsdarg.dnshostlen > 0 && nfsdarg.dnshostlen < 10000 &&
4738 		    nfsdarg.dspathlen > 0 && nfsdarg.dspathlen < 10000 &&
4739 		    nfsdarg.mdspathlen > 0 && nfsdarg.mdspathlen < 10000 &&
4740 		    nfsdarg.mirrorcnt >= 1 &&
4741 		    nfsdarg.mirrorcnt <= NFSDEV_MAXMIRRORS &&
4742 		    nfsdarg.addr != NULL && nfsdarg.dnshost != NULL &&
4743 		    nfsdarg.dspath != NULL && nfsdarg.mdspath != NULL) {
4744 			NFSD_DEBUG(1, "addrlen=%d dspathlen=%d dnslen=%d"
4745 			    " mdspathlen=%d mirrorcnt=%d\n", nfsdarg.addrlen,
4746 			    nfsdarg.dspathlen, nfsdarg.dnshostlen,
4747 			    nfsdarg.mdspathlen, nfsdarg.mirrorcnt);
4748 			cp = malloc(nfsdarg.addrlen + 1, M_TEMP, M_WAITOK);
4749 			error = copyin(nfsdarg.addr, cp, nfsdarg.addrlen);
4750 			if (error != 0) {
4751 				free(cp, M_TEMP);
4752 				goto out;
4753 			}
4754 			cp[nfsdarg.addrlen] = '\0';	/* Ensure nul term. */
4755 			nfsdarg.addr = cp;
4756 			cp = malloc(nfsdarg.dnshostlen + 1, M_TEMP, M_WAITOK);
4757 			error = copyin(nfsdarg.dnshost, cp, nfsdarg.dnshostlen);
4758 			if (error != 0) {
4759 				free(nfsdarg.addr, M_TEMP);
4760 				free(cp, M_TEMP);
4761 				goto out;
4762 			}
4763 			cp[nfsdarg.dnshostlen] = '\0';	/* Ensure nul term. */
4764 			nfsdarg.dnshost = cp;
4765 			cp = malloc(nfsdarg.dspathlen + 1, M_TEMP, M_WAITOK);
4766 			error = copyin(nfsdarg.dspath, cp, nfsdarg.dspathlen);
4767 			if (error != 0) {
4768 				free(nfsdarg.addr, M_TEMP);
4769 				free(nfsdarg.dnshost, M_TEMP);
4770 				free(cp, M_TEMP);
4771 				goto out;
4772 			}
4773 			cp[nfsdarg.dspathlen] = '\0';	/* Ensure nul term. */
4774 			nfsdarg.dspath = cp;
4775 			cp = malloc(nfsdarg.mdspathlen + 1, M_TEMP, M_WAITOK);
4776 			error = copyin(nfsdarg.mdspath, cp, nfsdarg.mdspathlen);
4777 			if (error != 0) {
4778 				free(nfsdarg.addr, M_TEMP);
4779 				free(nfsdarg.dnshost, M_TEMP);
4780 				free(nfsdarg.dspath, M_TEMP);
4781 				free(cp, M_TEMP);
4782 				goto out;
4783 			}
4784 			cp[nfsdarg.mdspathlen] = '\0';	/* Ensure nul term. */
4785 			nfsdarg.mdspath = cp;
4786 		} else {
4787 			nfsdarg.addr = NULL;
4788 			nfsdarg.addrlen = 0;
4789 			nfsdarg.dnshost = NULL;
4790 			nfsdarg.dnshostlen = 0;
4791 			nfsdarg.dspath = NULL;
4792 			nfsdarg.dspathlen = 0;
4793 			nfsdarg.mdspath = NULL;
4794 			nfsdarg.mdspathlen = 0;
4795 			nfsdarg.mirrorcnt = 1;
4796 		}
4797 		nfsd_timer(TD_TO_VNET(td));
4798 		error = nfsrvd_nfsd(td, &nfsdarg);
4799 		callout_drain(&VNET(nfsd_callout));
4800 		free(nfsdarg.addr, M_TEMP);
4801 		free(nfsdarg.dnshost, M_TEMP);
4802 		free(nfsdarg.dspath, M_TEMP);
4803 		free(nfsdarg.mdspath, M_TEMP);
4804 	} else if (uap->flag & NFSSVC_PNFSDS) {
4805 		error = copyin(uap->argp, &pnfsdarg, sizeof(pnfsdarg));
4806 		if (error == 0 && (pnfsdarg.op == PNFSDOP_DELDSSERVER ||
4807 		    pnfsdarg.op == PNFSDOP_FORCEDELDS)) {
4808 			cp = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
4809 			error = copyinstr(pnfsdarg.dspath, cp, PATH_MAX + 1,
4810 			    NULL);
4811 			if (error == 0)
4812 				error = nfsrv_deldsserver(pnfsdarg.op, cp, td);
4813 			free(cp, M_TEMP);
4814 		} else if (error == 0 && pnfsdarg.op == PNFSDOP_COPYMR) {
4815 			cp = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
4816 			buflen = sizeof(*pf) * NFSDEV_MAXMIRRORS;
4817 			buf = malloc(buflen, M_TEMP, M_WAITOK);
4818 			error = copyinstr(pnfsdarg.mdspath, cp, PATH_MAX + 1,
4819 			    NULL);
4820 			NFSD_DEBUG(4, "pnfsdcopymr cp mdspath=%d\n", error);
4821 			if (error == 0 && pnfsdarg.dspath != NULL) {
4822 				cp2 = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
4823 				error = copyinstr(pnfsdarg.dspath, cp2,
4824 				    PATH_MAX + 1, NULL);
4825 				NFSD_DEBUG(4, "pnfsdcopymr cp dspath=%d\n",
4826 				    error);
4827 			} else
4828 				cp2 = NULL;
4829 			if (error == 0 && pnfsdarg.curdspath != NULL) {
4830 				cp3 = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
4831 				error = copyinstr(pnfsdarg.curdspath, cp3,
4832 				    PATH_MAX + 1, NULL);
4833 				NFSD_DEBUG(4, "pnfsdcopymr cp curdspath=%d\n",
4834 				    error);
4835 			} else
4836 				cp3 = NULL;
4837 			curdvp = NULL;
4838 			fds = NULL;
4839 			if (error == 0)
4840 				error = nfsrv_mdscopymr(cp, cp2, cp3, buf,
4841 				    &buflen, fname, td, &vp, &nvp, &pf, &ds,
4842 				    &fds);
4843 			NFSD_DEBUG(4, "nfsrv_mdscopymr=%d\n", error);
4844 			if (error == 0) {
4845 				if (pf->dsf_dir >= nfsrv_dsdirsize) {
4846 					printf("copymr: dsdir out of range\n");
4847 					pf->dsf_dir = 0;
4848 				}
4849 				NFSD_DEBUG(4, "copymr: buflen=%d\n", buflen);
4850 				error = nfsrv_copymr(vp, nvp,
4851 				    ds->nfsdev_dsdir[pf->dsf_dir], ds, pf,
4852 				    (struct pnfsdsfile *)buf,
4853 				    buflen / sizeof(*pf), td->td_ucred, td);
4854 				vput(vp);
4855 				vput(nvp);
4856 				if (fds != NULL && error == 0) {
4857 					curdvp = fds->nfsdev_dsdir[pf->dsf_dir];
4858 					ret = vn_lock(curdvp, LK_EXCLUSIVE);
4859 					if (ret == 0) {
4860 						nfsrv_dsremove(curdvp, fname,
4861 						    td->td_ucred, td);
4862 						NFSVOPUNLOCK(curdvp);
4863 					}
4864 				}
4865 				NFSD_DEBUG(4, "nfsrv_copymr=%d\n", error);
4866 			}
4867 			free(cp, M_TEMP);
4868 			free(cp2, M_TEMP);
4869 			free(cp3, M_TEMP);
4870 			free(buf, M_TEMP);
4871 		}
4872 	} else {
4873 		error = nfssvc_srvcall(td, uap, td->td_ucred);
4874 	}
4875 
4876 out:
4877 	CURVNET_RESTORE();
4878 	NFSEXITCODE(error);
4879 	return (error);
4880 }
4881 
4882 static int
nfssvc_srvcall(struct thread * p,struct nfssvc_args * uap,struct ucred * cred)4883 nfssvc_srvcall(struct thread *p, struct nfssvc_args *uap, struct ucred *cred)
4884 {
4885 	struct nfsex_args export;
4886 	struct nfsex_oldargs oexp;
4887 	struct file *fp = NULL;
4888 	int stablefd, i, len;
4889 	struct nfsd_clid adminrevoke;
4890 	struct nfsd_dumplist dumplist;
4891 	struct nfsd_dumpclients *dumpclients;
4892 	struct nfsd_dumplocklist dumplocklist;
4893 	struct nfsd_dumplocks *dumplocks;
4894 	struct nameidata nd;
4895 	vnode_t vp;
4896 	int error = EINVAL, igotlock;
4897 	struct proc *procp;
4898 	gid_t *grps;
4899 
4900 	if (uap->flag & NFSSVC_PUBLICFH) {
4901 		NFSBZERO((caddr_t)&nfs_pubfh.nfsrvfh_data,
4902 		    sizeof (fhandle_t));
4903 		error = copyin(uap->argp,
4904 		    &nfs_pubfh.nfsrvfh_data, sizeof (fhandle_t));
4905 		if (!error)
4906 			nfs_pubfhset = 1;
4907 	} else if ((uap->flag & (NFSSVC_V4ROOTEXPORT | NFSSVC_NEWSTRUCT)) ==
4908 	    (NFSSVC_V4ROOTEXPORT | NFSSVC_NEWSTRUCT)) {
4909 		error = copyin(uap->argp,(caddr_t)&export,
4910 		    sizeof (struct nfsex_args));
4911 		if (!error) {
4912 			grps = NULL;
4913 			if (export.export.ex_ngroups > NGROUPS_MAX ||
4914 			    export.export.ex_ngroups < 0)
4915 				error = EINVAL;
4916 			else if (export.export.ex_ngroups > 0) {
4917 				grps = malloc(export.export.ex_ngroups *
4918 				    sizeof(gid_t), M_TEMP, M_WAITOK);
4919 				error = copyin(export.export.ex_groups, grps,
4920 				    export.export.ex_ngroups * sizeof(gid_t));
4921 				export.export.ex_groups = grps;
4922 			} else
4923 				export.export.ex_groups = NULL;
4924 			if (!error)
4925 				error = nfsrv_v4rootexport(&export, cred, p);
4926 			free(grps, M_TEMP);
4927 		}
4928 	} else if ((uap->flag & (NFSSVC_V4ROOTEXPORT | NFSSVC_NEWSTRUCT)) ==
4929 	    NFSSVC_V4ROOTEXPORT) {
4930 		error = copyin(uap->argp,(caddr_t)&oexp,
4931 		    sizeof (struct nfsex_oldargs));
4932 		if (!error) {
4933 			memset(&export.export, 0, sizeof(export.export));
4934 			export.export.ex_flags = (uint64_t)oexp.export.ex_flags;
4935 			export.export.ex_root = oexp.export.ex_root;
4936 			export.export.ex_uid = oexp.export.ex_anon.cr_uid;
4937 			export.export.ex_ngroups =
4938 			    oexp.export.ex_anon.cr_ngroups;
4939 			export.export.ex_groups = NULL;
4940 			if (export.export.ex_ngroups > XU_NGROUPS ||
4941 			    export.export.ex_ngroups < 0)
4942 				error = EINVAL;
4943 			else if (export.export.ex_ngroups > 0) {
4944 				export.export.ex_groups = malloc(
4945 				    export.export.ex_ngroups * sizeof(gid_t),
4946 				    M_TEMP, M_WAITOK);
4947 				for (i = 0; i < export.export.ex_ngroups; i++)
4948 					export.export.ex_groups[i] =
4949 					    oexp.export.ex_anon.cr_groups[i];
4950 			}
4951 			export.export.ex_addr = oexp.export.ex_addr;
4952 			export.export.ex_addrlen = oexp.export.ex_addrlen;
4953 			export.export.ex_mask = oexp.export.ex_mask;
4954 			export.export.ex_masklen = oexp.export.ex_masklen;
4955 			export.export.ex_indexfile = oexp.export.ex_indexfile;
4956 			export.export.ex_numsecflavors =
4957 			    oexp.export.ex_numsecflavors;
4958 			if (export.export.ex_numsecflavors >= MAXSECFLAVORS ||
4959 			    export.export.ex_numsecflavors < 0)
4960 				error = EINVAL;
4961 			else {
4962 				for (i = 0; i < export.export.ex_numsecflavors;
4963 				    i++)
4964 					export.export.ex_secflavors[i] =
4965 					    oexp.export.ex_secflavors[i];
4966 			}
4967 			export.fspec = oexp.fspec;
4968 			if (error == 0)
4969 				error = nfsrv_v4rootexport(&export, cred, p);
4970 			free(export.export.ex_groups, M_TEMP);
4971 		}
4972 	} else if (uap->flag & NFSSVC_NOPUBLICFH) {
4973 		nfs_pubfhset = 0;
4974 		error = 0;
4975 	} else if (uap->flag & NFSSVC_STABLERESTART) {
4976 		error = copyin(uap->argp, (caddr_t)&stablefd,
4977 		    sizeof (int));
4978 		if (!error)
4979 			error = fp_getfvp(p, stablefd, &fp, &vp);
4980 		if (!error && (NFSFPFLAG(fp) & (FREAD | FWRITE)) != (FREAD | FWRITE))
4981 			error = EBADF;
4982 		if (!error && VNET(nfsrv_numnfsd) != 0)
4983 			error = ENXIO;
4984 		if (!error) {
4985 			VNET(nfsrv_stablefirst).nsf_fp = fp;
4986 			nfsrv_setupstable(p);
4987 		}
4988 	} else if (uap->flag & NFSSVC_ADMINREVOKE) {
4989 		error = copyin(uap->argp, (caddr_t)&adminrevoke,
4990 		    sizeof (struct nfsd_clid));
4991 		if (!error)
4992 			error = nfsrv_adminrevoke(&adminrevoke, p);
4993 	} else if (uap->flag & NFSSVC_DUMPCLIENTS) {
4994 		error = copyin(uap->argp, (caddr_t)&dumplist,
4995 		    sizeof (struct nfsd_dumplist));
4996 		if (!error && (dumplist.ndl_size < 1 ||
4997 			dumplist.ndl_size > NFSRV_MAXDUMPLIST))
4998 			error = EPERM;
4999 		if (!error) {
5000 		    len = sizeof (struct nfsd_dumpclients) * dumplist.ndl_size;
5001 		    dumpclients = malloc(len, M_TEMP, M_WAITOK | M_ZERO);
5002 		    nfsrv_dumpclients(dumpclients, dumplist.ndl_size);
5003 		    error = copyout(dumpclients, dumplist.ndl_list, len);
5004 		    free(dumpclients, M_TEMP);
5005 		}
5006 	} else if (uap->flag & NFSSVC_DUMPLOCKS) {
5007 		error = copyin(uap->argp, (caddr_t)&dumplocklist,
5008 		    sizeof (struct nfsd_dumplocklist));
5009 		if (!error && (dumplocklist.ndllck_size < 1 ||
5010 			dumplocklist.ndllck_size > NFSRV_MAXDUMPLIST))
5011 			error = EPERM;
5012 		if (!error)
5013 			error = nfsrv_lookupfilename(&nd,
5014 				dumplocklist.ndllck_fname, p);
5015 		if (!error) {
5016 			len = sizeof (struct nfsd_dumplocks) *
5017 				dumplocklist.ndllck_size;
5018 			dumplocks = malloc(len, M_TEMP, M_WAITOK | M_ZERO);
5019 			nfsrv_dumplocks(nd.ni_vp, dumplocks,
5020 			    dumplocklist.ndllck_size, p);
5021 			vput(nd.ni_vp);
5022 			error = copyout(dumplocks, dumplocklist.ndllck_list,
5023 			    len);
5024 			free(dumplocks, M_TEMP);
5025 		}
5026 	} else if (uap->flag & NFSSVC_BACKUPSTABLE) {
5027 		procp = p->td_proc;
5028 		PROC_LOCK(procp);
5029 		nfsd_master_pid = procp->p_pid;
5030 		bcopy(procp->p_comm, nfsd_master_comm, MAXCOMLEN + 1);
5031 		nfsd_master_start = procp->p_stats->p_start;
5032 		VNET(nfsd_master_proc) = procp;
5033 		PROC_UNLOCK(procp);
5034 	} else if ((uap->flag & NFSSVC_SUSPENDNFSD) != 0) {
5035 		NFSLOCKV4ROOTMUTEX();
5036 		if (!VNET(nfsrv_suspend_nfsd)) {
5037 			/* Lock out all nfsd threads */
5038 			do {
5039 				igotlock = nfsv4_lock(
5040 				    &VNET(nfsd_suspend_lock), 1, NULL,
5041 				    NFSV4ROOTLOCKMUTEXPTR, NULL);
5042 			} while (igotlock == 0 &&
5043 			    !VNET(nfsrv_suspend_nfsd));
5044 			VNET(nfsrv_suspend_nfsd) = true;
5045 		}
5046 		NFSUNLOCKV4ROOTMUTEX();
5047 		error = 0;
5048 	} else if ((uap->flag & NFSSVC_RESUMENFSD) != 0) {
5049 		NFSLOCKV4ROOTMUTEX();
5050 		if (VNET(nfsrv_suspend_nfsd)) {
5051 			nfsv4_unlock(&VNET(nfsd_suspend_lock), 0);
5052 			VNET(nfsrv_suspend_nfsd) = false;
5053 		}
5054 		NFSUNLOCKV4ROOTMUTEX();
5055 		error = 0;
5056 	}
5057 
5058 	NFSEXITCODE(error);
5059 	return (error);
5060 }
5061 
5062 /*
5063  * Check exports.
5064  * Returns 0 if ok, 1 otherwise.
5065  */
5066 int
nfsvno_testexp(struct nfsrv_descript * nd,struct nfsexstuff * exp)5067 nfsvno_testexp(struct nfsrv_descript *nd, struct nfsexstuff *exp)
5068 {
5069 	int i;
5070 
5071 	if ((NFSVNO_EXTLS(exp) && (nd->nd_flag & ND_TLS) == 0) ||
5072 	    (NFSVNO_EXTLSCERT(exp) &&
5073 	     (nd->nd_flag & ND_TLSCERT) == 0) ||
5074 	    (NFSVNO_EXTLSCERTUSER(exp) &&
5075 	     (nd->nd_flag & ND_TLSCERTUSER) == 0)) {
5076 		if ((nd->nd_flag & ND_NFSV4) != 0)
5077 			return (NFSERR_WRONGSEC);
5078 #ifdef notnow
5079 		/* There is currently no auth_stat for this. */
5080 		else if ((nd->nd_flag & ND_TLS) == 0)
5081 			return (NFSERR_AUTHERR | AUTH_NEEDS_TLS);
5082 		else
5083 			return (NFSERR_AUTHERR | AUTH_NEEDS_TLS_MUTUAL_HOST);
5084 #endif
5085 		else
5086 			return (NFSERR_AUTHERR | AUTH_TOOWEAK);
5087 	}
5088 
5089 	/*
5090 	 * RFC2623 suggests that the NFSv3 Fsinfo RPC be allowed to use
5091 	 * AUTH_NONE or AUTH_SYS for file systems requiring RPCSEC_GSS.
5092 	 */
5093 	if ((nd->nd_flag & ND_NFSV3) != 0 && nd->nd_procnum == NFSPROC_FSINFO)
5094 		return (0);
5095 
5096 	/*
5097 	 * This seems odd, but allow the case where the security flavor
5098 	 * list is empty. This happens when NFSv4 is traversing non-exported
5099 	 * file systems. Exported file systems should always have a non-empty
5100 	 * security flavor list.
5101 	 */
5102 	if (exp->nes_numsecflavor == 0)
5103 		return (0);
5104 
5105 	for (i = 0; i < exp->nes_numsecflavor; i++) {
5106 		/*
5107 		 * The tests for privacy and integrity must be first,
5108 		 * since ND_GSS is set for everything but AUTH_SYS.
5109 		 */
5110 		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5P &&
5111 		    (nd->nd_flag & ND_GSSPRIVACY))
5112 			return (0);
5113 		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5I &&
5114 		    (nd->nd_flag & ND_GSSINTEGRITY))
5115 			return (0);
5116 		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5 &&
5117 		    (nd->nd_flag & ND_GSS))
5118 			return (0);
5119 		if (exp->nes_secflavors[i] == AUTH_SYS &&
5120 		    (nd->nd_flag & ND_GSS) == 0)
5121 			return (0);
5122 	}
5123 	if ((nd->nd_flag & ND_NFSV4) != 0)
5124 		return (NFSERR_WRONGSEC);
5125 	return (NFSERR_AUTHERR | AUTH_TOOWEAK);
5126 }
5127 
5128 /*
5129  * Calculate a hash value for the fid in a file handle.
5130  */
5131 uint32_t
nfsrv_hashfh(fhandle_t * fhp)5132 nfsrv_hashfh(fhandle_t *fhp)
5133 {
5134 	uint32_t hashval;
5135 
5136 	hashval = hash32_buf(&fhp->fh_fid, sizeof(struct fid), 0);
5137 	return (hashval);
5138 }
5139 
5140 /*
5141  * Calculate a hash value for the sessionid.
5142  */
5143 uint32_t
nfsrv_hashsessionid(uint8_t * sessionid)5144 nfsrv_hashsessionid(uint8_t *sessionid)
5145 {
5146 	uint32_t hashval;
5147 
5148 	hashval = hash32_buf(sessionid, NFSX_V4SESSIONID, 0);
5149 	return (hashval);
5150 }
5151 
5152 /*
5153  * Signal the userland master nfsd to backup the stable restart file.
5154  */
5155 void
nfsrv_backupstable(void)5156 nfsrv_backupstable(void)
5157 {
5158 	struct proc *procp;
5159 
5160 	if (VNET(nfsd_master_proc) != NULL) {
5161 		procp = pfind(nfsd_master_pid);
5162 		/* Try to make sure it is the correct process. */
5163 		if (procp == VNET(nfsd_master_proc) &&
5164 		    procp->p_stats->p_start.tv_sec ==
5165 		    nfsd_master_start.tv_sec &&
5166 		    procp->p_stats->p_start.tv_usec ==
5167 		    nfsd_master_start.tv_usec &&
5168 		    strcmp(procp->p_comm, nfsd_master_comm) == 0)
5169 			kern_psignal(procp, SIGUSR2);
5170 		else
5171 			VNET(nfsd_master_proc) = NULL;
5172 
5173 		if (procp != NULL)
5174 			PROC_UNLOCK(procp);
5175 	}
5176 }
5177 
5178 /*
5179  * Create a DS data file for nfsrv_pnfscreate(). Called for each mirror.
5180  * The arguments are in a structure, so that they can be passed through
5181  * taskqueue for a kernel process to execute this function.
5182  */
5183 struct nfsrvdscreate {
5184 	int			done;
5185 	int			inprog;
5186 	struct task		tsk;
5187 	struct ucred		*tcred;
5188 	struct vnode		*dvp;
5189 	NFSPROC_T		*p;
5190 	struct pnfsdsfile	*pf;
5191 	int			err;
5192 	fhandle_t		fh;
5193 	struct vattr		va;
5194 	struct vattr		createva;
5195 };
5196 
5197 int
nfsrv_dscreate(struct vnode * dvp,struct vattr * vap,struct vattr * nvap,fhandle_t * fhp,struct pnfsdsfile * pf,struct pnfsdsattr * dsa,char * fnamep,struct ucred * tcred,NFSPROC_T * p,struct vnode ** nvpp)5198 nfsrv_dscreate(struct vnode *dvp, struct vattr *vap, struct vattr *nvap,
5199     fhandle_t *fhp, struct pnfsdsfile *pf, struct pnfsdsattr *dsa,
5200     char *fnamep, struct ucred *tcred, NFSPROC_T *p, struct vnode **nvpp)
5201 {
5202 	struct vnode *nvp;
5203 	struct nameidata named;
5204 	struct vattr va;
5205 	char *bufp;
5206 	u_long *hashp;
5207 	struct nfsnode *np;
5208 	struct nfsmount *nmp;
5209 	int error;
5210 
5211 	NFSNAMEICNDSET(&named.ni_cnd, tcred, CREATE,
5212 	    LOCKPARENT | LOCKLEAF | NOCACHE);
5213 	nfsvno_setpathbuf(&named, &bufp, &hashp);
5214 	named.ni_cnd.cn_lkflags = LK_EXCLUSIVE;
5215 	named.ni_cnd.cn_nameptr = bufp;
5216 	if (fnamep != NULL) {
5217 		strlcpy(bufp, fnamep, PNFS_FILENAME_LEN + 1);
5218 		named.ni_cnd.cn_namelen = strlen(bufp);
5219 	} else
5220 		named.ni_cnd.cn_namelen = nfsrv_putfhname(fhp, bufp);
5221 	NFSD_DEBUG(4, "nfsrv_dscreate: dvp=%p fname=%s\n", dvp, bufp);
5222 
5223 	/* Create the date file in the DS mount. */
5224 	error = NFSVOPLOCK(dvp, LK_EXCLUSIVE);
5225 	if (error == 0) {
5226 		error = VOP_CREATE(dvp, &nvp, &named.ni_cnd, vap);
5227 		vref(dvp);
5228 		VOP_VPUT_PAIR(dvp, error == 0 ? &nvp : NULL, false);
5229 		if (error == 0) {
5230 			/* Set the ownership of the file. */
5231 			error = VOP_SETATTR(nvp, nvap, tcred);
5232 			NFSD_DEBUG(4, "nfsrv_dscreate:"
5233 			    " setattr-uid=%d\n", error);
5234 			if (error != 0)
5235 				vput(nvp);
5236 		}
5237 		if (error != 0)
5238 			printf("pNFS: pnfscreate failed=%d\n", error);
5239 	} else
5240 		printf("pNFS: pnfscreate vnlock=%d\n", error);
5241 	if (error == 0) {
5242 		np = VTONFS(nvp);
5243 		nmp = VFSTONFS(nvp->v_mount);
5244 		if (strcmp(nvp->v_mount->mnt_vfc->vfc_name, "nfs")
5245 		    != 0 || nmp->nm_nam->sa_len > sizeof(
5246 		    struct sockaddr_in6) ||
5247 		    np->n_fhp->nfh_len != NFSX_MYFH) {
5248 			printf("Bad DS file: fstype=%s salen=%d"
5249 			    " fhlen=%d\n",
5250 			    nvp->v_mount->mnt_vfc->vfc_name,
5251 			    nmp->nm_nam->sa_len, np->n_fhp->nfh_len);
5252 			error = ENOENT;
5253 		}
5254 
5255 		/* Set extattrs for the DS on the MDS file. */
5256 		if (error == 0) {
5257 			if (dsa != NULL) {
5258 				error = VOP_GETATTR(nvp, &va, tcred);
5259 				if (error == 0) {
5260 					dsa->dsa_filerev = va.va_filerev;
5261 					dsa->dsa_size = va.va_size;
5262 					dsa->dsa_atime = va.va_atime;
5263 					dsa->dsa_mtime = va.va_mtime;
5264 					dsa->dsa_bytes = va.va_bytes;
5265 				}
5266 			}
5267 			if (error == 0) {
5268 				NFSBCOPY(np->n_fhp->nfh_fh, &pf->dsf_fh,
5269 				    NFSX_MYFH);
5270 				NFSBCOPY(nmp->nm_nam, &pf->dsf_sin,
5271 				    nmp->nm_nam->sa_len);
5272 				NFSBCOPY(named.ni_cnd.cn_nameptr,
5273 				    pf->dsf_filename,
5274 				    sizeof(pf->dsf_filename));
5275 			}
5276 		} else
5277 			printf("pNFS: pnfscreate can't get DS"
5278 			    " attr=%d\n", error);
5279 		if (nvpp != NULL && error == 0)
5280 			*nvpp = nvp;
5281 		else
5282 			vput(nvp);
5283 	}
5284 	nfsvno_relpathbuf(&named);
5285 	return (error);
5286 }
5287 
5288 /*
5289  * Start up the thread that will execute nfsrv_dscreate().
5290  */
5291 static void
start_dscreate(void * arg,int pending)5292 start_dscreate(void *arg, int pending)
5293 {
5294 	struct nfsrvdscreate *dsc;
5295 
5296 	dsc = (struct nfsrvdscreate *)arg;
5297 	dsc->err = nfsrv_dscreate(dsc->dvp, &dsc->createva, &dsc->va, &dsc->fh,
5298 	    dsc->pf, NULL, NULL, dsc->tcred, dsc->p, NULL);
5299 	dsc->done = 1;
5300 	NFSD_DEBUG(4, "start_dscreate: err=%d\n", dsc->err);
5301 }
5302 
5303 /*
5304  * Create a pNFS data file on the Data Server(s).
5305  */
5306 static void
nfsrv_pnfscreate(struct vnode * vp,struct vattr * vap,struct ucred * cred,NFSPROC_T * p)5307 nfsrv_pnfscreate(struct vnode *vp, struct vattr *vap, struct ucred *cred,
5308     NFSPROC_T *p)
5309 {
5310 	struct nfsrvdscreate *dsc, *tdsc = NULL;	/* Shut up gcc. */
5311 	struct nfsdevice *ds, *tds, *fds;
5312 	struct mount *mp;
5313 	struct pnfsdsfile *pf, *tpf;
5314 	struct pnfsdsattr dsattr;
5315 	struct vattr va;
5316 	struct vnode **dvp;
5317 	struct nfsmount *nmp;
5318 	fhandle_t fh;
5319 	uid_t vauid;
5320 	gid_t vagid;
5321 	u_short vamode;
5322 	struct ucred *tcred;
5323 	int *dsdir, error, i, j, mirrorcnt, ret, stripecnt;
5324 	int failpos, timo;
5325 	uint64_t stripesiz;
5326 
5327 	/* Get a DS server directory in a round-robin order. */
5328 	mirrorcnt = 1;
5329 	mp = vp->v_mount;
5330 	ds = fds = NULL;
5331 	i = j = 0;
5332 	dvp = malloc(sizeof(*dvp) * nfsrv_maxpnfsmirror * nfsrv_maxstripecnt,
5333 	    M_TEMP, M_WAITOK);
5334 	dsdir = malloc(sizeof(*dsdir) * nfsrv_maxpnfsmirror *
5335 	    nfsrv_maxstripecnt, M_TEMP, M_WAITOK);
5336 	stripesiz = nfsrv_stripesiz;
5337 	NFSDDSLOCK();
5338 	/*
5339 	 * Search for the first entry that handles this MDS fs, but use the
5340 	 * first entry for all MDS fs's otherwise.
5341 	 */
5342 	TAILQ_FOREACH(tds, &nfsrv_devidhead, nfsdev_list) {
5343 		if (tds->nfsdev_nmp != NULL) {
5344 			i++;
5345 			if (tds->nfsdev_mdsisset == 0 && ds == NULL)
5346 				ds = tds;
5347 			else if (tds->nfsdev_mdsisset != 0 && fsidcmp(
5348 			    &mp->mnt_stat.f_fsid, &tds->nfsdev_mdsfsid) == 0) {
5349 				if (j == 0) {
5350 					ds = fds = tds;
5351 					if (nfsrv_maxstripecnt > 1)
5352 						stripesiz =
5353 						    tds->nfsdev_mdsstripesiz;
5354 				}
5355 				if (stripesiz == 0)
5356 					break;
5357 				j++;
5358 			}
5359 		}
5360 	}
5361 	if (ds == NULL) {
5362 		NFSDDSUNLOCK();
5363 		free(dvp, M_TEMP);
5364 		free(dsdir, M_TEMP);
5365 		NFSD_DEBUG(4, "nfsrv_pnfscreate: no srv\n");
5366 		return;
5367 	}
5368 
5369 	/*
5370 	 * i or j is the count of devices.  The stripecnt is that number
5371 	 * of devices devided by the number of mirrors.
5372 	 */
5373 	stripecnt = 0;
5374 	if (stripesiz > 0) {
5375 		if (j > 0)
5376 			stripecnt = j / nfsrv_maxpnfsmirror;
5377 		else
5378 			stripecnt = i / nfsrv_maxpnfsmirror;
5379 		if (stripecnt > nfsrv_maxstripecnt)
5380 			stripecnt = nfsrv_maxstripecnt;
5381 	}
5382 	if (stripecnt == 0)
5383 		stripecnt = 1;
5384 
5385 	/* Set the first device as found above. */
5386 	i = dsdir[0] = ds->nfsdev_nextdir;
5387 	ds->nfsdev_nextdir = (ds->nfsdev_nextdir + 1) % nfsrv_dsdirsize;
5388 	dvp[0] = ds->nfsdev_dsdir[i];
5389 	tds = TAILQ_NEXT(ds, nfsdev_list);
5390 	if ((nfsrv_maxpnfsmirror > 1 || stripecnt > 1) && tds != NULL) {
5391 		j = 1;		/* Stripe number */
5392 		mirrorcnt = 0;
5393 		TAILQ_FOREACH_FROM(tds, &nfsrv_devidhead, nfsdev_list) {
5394 			if (tds->nfsdev_nmp != NULL &&
5395 			    ((tds->nfsdev_mdsisset == 0 && fds == NULL) ||
5396 			     (tds->nfsdev_mdsisset != 0 && fds != NULL &&
5397 			      fsidcmp(&mp->mnt_stat.f_fsid,
5398 			      &tds->nfsdev_mdsfsid) == 0))) {
5399 				dsdir[mirrorcnt * stripecnt + j] = i;
5400 				dvp[mirrorcnt * stripecnt + j] =
5401 				    tds->nfsdev_dsdir[i];
5402 				j++;
5403 				if (j >= stripecnt) {
5404 					mirrorcnt++;
5405 					if (mirrorcnt >= nfsrv_maxpnfsmirror)
5406 						break;
5407 					j = 0;
5408 				}
5409 			}
5410 		}
5411 		if (mirrorcnt == 0) {
5412 			mirrorcnt = 1;
5413 			stripecnt = j;
5414 		}
5415 	} else
5416 		stripecnt = 1;
5417 	/* Put at end of list to implement round-robin usage. */
5418 	TAILQ_REMOVE(&nfsrv_devidhead, ds, nfsdev_list);
5419 	TAILQ_INSERT_TAIL(&nfsrv_devidhead, ds, nfsdev_list);
5420 	NFSDDSUNLOCK();
5421 	dsc = NULL;
5422 	j = mirrorcnt * stripecnt;
5423 	if (j > 1)
5424 		tdsc = dsc = malloc(sizeof(*dsc) * (j - 1), M_TEMP,
5425 		    M_WAITOK | M_ZERO);
5426 	tpf = pf = malloc(sizeof(*pf) * j, M_TEMP, M_WAITOK | M_ZERO);
5427 
5428 	error = nfsvno_getfh(vp, &fh, p);
5429 	if (error == 0)
5430 		error = VOP_GETATTR(vp, &va, cred);
5431 	if (error == 0) {
5432 		/* Set the attributes for "vp" to Setattr the DS vp. */
5433 		vauid = va.va_uid;
5434 		vagid = va.va_gid;
5435 		vamode = va.va_mode;
5436 		VATTR_NULL(&va);
5437 		va.va_uid = vauid;
5438 		va.va_gid = vagid;
5439 		va.va_mode = vamode;
5440 		va.va_size = 0;
5441 	} else
5442 		printf("pNFS: pnfscreate getfh+attr=%d\n", error);
5443 
5444 	NFSD_DEBUG(4, "nfsrv_pnfscreate: cruid=%d crgid=%d\n", cred->cr_uid,
5445 	    cred->cr_gid);
5446 	/* Make data file name based on FH. */
5447 	tcred = newnfs_getcred();
5448 
5449 	/*
5450 	 * Create the file on each DS mirror, using kernel process(es) for the
5451 	 * additional mirrors.
5452 	 */
5453 	failpos = -1;
5454 	for (i = 0; i < j - 1 && error == 0; i++, tpf++, tdsc++) {
5455 		tpf->dsf_stripecnt = stripecnt;
5456 		tpf->dsf_stripesiz = stripesiz;
5457 		tpf->dsf_dir = dsdir[i];
5458 		tdsc->tcred = tcred;
5459 		tdsc->p = p;
5460 		tdsc->pf = tpf;
5461 		tdsc->createva = *vap;
5462 		NFSBCOPY(&fh, &tdsc->fh, sizeof(fh));
5463 		tdsc->va = va;
5464 		tdsc->dvp = dvp[i];
5465 		tdsc->done = 0;
5466 		tdsc->inprog = 0;
5467 		tdsc->err = 0;
5468 		ret = EIO;
5469 		if (nfs_pnfsiothreads != 0) {
5470 			ret = nfs_pnfsio(start_dscreate, tdsc);
5471 			NFSD_DEBUG(4, "nfsrv_pnfscreate: nfs_pnfsio=%d\n", ret);
5472 		}
5473 		if (ret != 0) {
5474 			ret = nfsrv_dscreate(dvp[i], vap, &va, &fh, tpf, NULL,
5475 			    NULL, tcred, p, NULL);
5476 			if (ret != 0) {
5477 				KASSERT(error == 0, ("nfsrv_dscreate err=%d",
5478 				    error));
5479 				if (failpos == -1 && nfsds_failerr(ret))
5480 					failpos = i;
5481 				else
5482 					error = ret;
5483 			}
5484 		}
5485 	}
5486 	if (error == 0) {
5487 		tpf->dsf_stripecnt = stripecnt;
5488 		tpf->dsf_stripesiz = stripesiz;
5489 		tpf->dsf_dir = dsdir[j - 1];
5490 		error = nfsrv_dscreate(dvp[j - 1], vap, &va, &fh, tpf,
5491 		    &dsattr, NULL, tcred, p, NULL);
5492 		if (failpos == -1 && j > 1 && nfsds_failerr(error)) {
5493 			failpos = j - 1;
5494 			error = 0;
5495 		}
5496 	}
5497 	timo = hz / 50;		/* Wait for 20msec. */
5498 	if (timo < 1)
5499 		timo = 1;
5500 	/* Wait for kernel task(s) to complete. */
5501 	for (tdsc = dsc, i = 0; i < j - 1; i++, tdsc++) {
5502 		while (tdsc->inprog != 0 && tdsc->done == 0)
5503 			tsleep(&tdsc->tsk, PVFS, "srvdcr", timo);
5504 		if (tdsc->err != 0) {
5505 			if (failpos == -1 && nfsds_failerr(tdsc->err))
5506 				failpos = i;
5507 			else if (error == 0)
5508 				error = tdsc->err;
5509 		}
5510 	}
5511 
5512 	/*
5513 	 * If failpos has been set, that DS has failed, so it needs
5514 	 * to be disabled.
5515 	 */
5516 	if (failpos >= 0) {
5517 		nmp = VFSTONFS(dvp[failpos]->v_mount);
5518 		NFSLOCKMNT(nmp);
5519 		if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
5520 		     NFSMNTP_CANCELRPCS)) == 0) {
5521 			nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
5522 			NFSUNLOCKMNT(nmp);
5523 			ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER, nmp, p);
5524 			NFSD_DEBUG(4, "dscreatfail fail=%d ds=%p\n", failpos,
5525 			    ds);
5526 			if (ds != NULL)
5527 				nfsrv_killrpcs(nmp);
5528 			NFSLOCKMNT(nmp);
5529 			nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
5530 			wakeup(nmp);
5531 		}
5532 		NFSUNLOCKMNT(nmp);
5533 	}
5534 
5535 	NFSFREECRED(tcred);
5536 	if (error == 0) {
5537 		ASSERT_VOP_ELOCKED(vp, "nfsrv_pnfscreate vp");
5538 		NFSD_DEBUG(4, "nfsrv_pnfscreate: mirrorcnt=%d stripecnt=%d\n",
5539 		    mirrorcnt, stripecnt);
5540 
5541 		error = vn_extattr_set(vp, IO_NODELOCKED,
5542 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile",
5543 		    sizeof(*pf) * mirrorcnt * stripecnt, (char *)pf, p);
5544 		if (error == 0)
5545 			error = vn_extattr_set(vp, IO_NODELOCKED,
5546 			    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsattr",
5547 			    sizeof(dsattr), (char *)&dsattr, p);
5548 		if (error != 0)
5549 			printf("pNFS: pnfscreate setextattr=%d\n",
5550 			    error);
5551 	} else
5552 		printf("pNFS: pnfscreate=%d\n", error);
5553 	free(dvp, M_TEMP);
5554 	free(dsdir, M_TEMP);
5555 	free(pf, M_TEMP);
5556 	free(dsc, M_TEMP);
5557 }
5558 
5559 /*
5560  * Get the information needed to remove the pNFS Data Server file from the
5561  * Metadata file.  Upon success, *dvppp is set to an array of locked
5562  * DS directory vnode(s).  The caller must unlock this array of *dvp when done
5563  * with it.
5564  */
5565 static void
nfsrv_pnfsremovesetup(struct vnode * vp,NFSPROC_T * p,struct vnode *** dvppp,int * dsfilecntp,char * fname,fhandle_t * fhp)5566 nfsrv_pnfsremovesetup(struct vnode *vp, NFSPROC_T *p, struct vnode ***dvppp,
5567     int *dsfilecntp, char *fname, fhandle_t *fhp)
5568 {
5569 	struct vattr va;
5570 	struct ucred *tcred;
5571 	char *buf;
5572 	int buflen, error;
5573 
5574 	*dvppp = NULL;
5575 	/* If not an exported regular file or not a pNFS server, just return. */
5576 	if (vp->v_type != VREG || (vp->v_mount->mnt_flag & MNT_EXPORTED) == 0 ||
5577 	    nfsrv_devidcnt == 0)
5578 		return;
5579 
5580 	/* Check to see if this is the last hard link. */
5581 	tcred = newnfs_getcred();
5582 	error = VOP_GETATTR(vp, &va, tcred);
5583 	NFSFREECRED(tcred);
5584 	if (error != 0) {
5585 		printf("pNFS: nfsrv_pnfsremovesetup getattr=%d\n", error);
5586 		return;
5587 	}
5588 	if (va.va_nlink > 1)
5589 		return;
5590 
5591 	error = nfsvno_getfh(vp, fhp, p);
5592 	if (error != 0) {
5593 		printf("pNFS: nfsrv_pnfsremovesetup getfh=%d\n", error);
5594 		return;
5595 	}
5596 
5597 	buflen = sizeof(struct pnfsdsfile) * NFSDEV_MAXMIRRORS *
5598 	    NFSDEV_MAXSTRIPE;
5599 	buf = malloc(buflen, M_TEMP, M_WAITOK);
5600 	/* Get the directory vnode for the DS mount and the file handle. */
5601 	error = nfsrv_dsgetsockmnt(vp, 0, buf, &buflen, dsfilecntp, NULL, NULL,
5602 	    p, dvppp, NULL, NULL, fname, NULL, NULL, NULL, NULL, NULL);
5603 	free(buf, M_TEMP);
5604 	if (error != 0)
5605 		printf("pNFS: nfsrv_pnfsremovesetup getsockmnt=%d\n", error);
5606 }
5607 
5608 /*
5609  * Remove a DS data file for nfsrv_pnfsremove(). Called for each mirror.
5610  * The arguments are in a structure, so that they can be passed through
5611  * taskqueue for a kernel process to execute this function.
5612  */
5613 struct nfsrvdsremove {
5614 	int			done;
5615 	int			inprog;
5616 	struct task		tsk;
5617 	struct ucred		*tcred;
5618 	struct vnode		*dvp;
5619 	NFSPROC_T		*p;
5620 	int			err;
5621 	char			fname[PNFS_FILENAME_LEN + 1];
5622 };
5623 
5624 static int
nfsrv_dsremove(struct vnode * dvp,char * fname,struct ucred * tcred,NFSPROC_T * p)5625 nfsrv_dsremove(struct vnode *dvp, char *fname, struct ucred *tcred,
5626     NFSPROC_T *p)
5627 {
5628 	struct nameidata named;
5629 	struct vnode *nvp;
5630 	char *bufp;
5631 	u_long *hashp;
5632 	int error;
5633 
5634 	error = NFSVOPLOCK(dvp, LK_EXCLUSIVE);
5635 	if (error != 0)
5636 		return (error);
5637 	named.ni_cnd.cn_nameiop = DELETE;
5638 	named.ni_cnd.cn_lkflags = LK_EXCLUSIVE | LK_RETRY;
5639 	named.ni_cnd.cn_cred = tcred;
5640 	named.ni_cnd.cn_flags = ISLASTCN | LOCKPARENT | LOCKLEAF;
5641 	nfsvno_setpathbuf(&named, &bufp, &hashp);
5642 	named.ni_cnd.cn_nameptr = bufp;
5643 	named.ni_cnd.cn_namelen = strlen(fname);
5644 	strlcpy(bufp, fname, NAME_MAX);
5645 	NFSD_DEBUG(4, "nfsrv_pnfsremove: filename=%s\n", bufp);
5646 	error = VOP_LOOKUP(dvp, &nvp, &named.ni_cnd);
5647 	NFSD_DEBUG(4, "nfsrv_pnfsremove: aft LOOKUP=%d\n", error);
5648 	if (error == 0) {
5649 		error = VOP_REMOVE(dvp, nvp, &named.ni_cnd);
5650 		vput(nvp);
5651 	}
5652 	NFSVOPUNLOCK(dvp);
5653 	nfsvno_relpathbuf(&named);
5654 	if (error != 0)
5655 		printf("pNFS: nfsrv_pnfsremove failed=%d\n", error);
5656 	return (error);
5657 }
5658 
5659 /*
5660  * Start up the thread that will execute nfsrv_dsremove().
5661  */
5662 static void
start_dsremove(void * arg,int pending)5663 start_dsremove(void *arg, int pending)
5664 {
5665 	struct nfsrvdsremove *dsrm;
5666 
5667 	dsrm = (struct nfsrvdsremove *)arg;
5668 	dsrm->err = nfsrv_dsremove(dsrm->dvp, dsrm->fname, dsrm->tcred,
5669 	    dsrm->p);
5670 	dsrm->done = 1;
5671 	NFSD_DEBUG(4, "start_dsremove: err=%d\n", dsrm->err);
5672 }
5673 
5674 /*
5675  * Remove a pNFS data file from a Data Server.
5676  * nfsrv_pnfsremovesetup() must have been called before the MDS file was
5677  * removed to set up the dvp and fill in the FH.
5678  */
5679 static void
nfsrv_pnfsremove(struct vnode ** dvpp,int dsfilecnt,char * fname,fhandle_t * fhp,NFSPROC_T * p)5680 nfsrv_pnfsremove(struct vnode **dvpp, int dsfilecnt, char *fname,
5681     fhandle_t *fhp, NFSPROC_T *p)
5682 {
5683 	struct ucred *tcred;
5684 	struct nfsrvdsremove *dsrm, *tdsrm = NULL;	/* Shut up gcc. */
5685 	struct nfsdevice *ds;
5686 	struct nfsmount *nmp;
5687 	struct vnode **tdvpp;
5688 	int failpos, i, ret, timo;
5689 
5690 	tcred = newnfs_getcred();
5691 	dsrm = NULL;
5692 	if (dsfilecnt > 1)
5693 		tdsrm = dsrm = malloc(sizeof(*dsrm) * dsfilecnt - 1, M_TEMP,
5694 		    M_WAITOK);
5695 	/*
5696 	 * Remove the file on each DS mirror, using kernel process(es) for the
5697 	 * additional mirrors.
5698 	 */
5699 	failpos = -1;
5700 	tdvpp = dvpp;
5701 	for (i = 0; i < dsfilecnt - 1; i++, tdsrm++, tdvpp++) {
5702 		tdsrm->tcred = tcred;
5703 		tdsrm->p = p;
5704 		tdsrm->dvp = *tdvpp;
5705 		strlcpy(tdsrm->fname, fname, PNFS_FILENAME_LEN + 1);
5706 		tdsrm->inprog = 0;
5707 		tdsrm->done = 0;
5708 		tdsrm->err = 0;
5709 		ret = EIO;
5710 		if (nfs_pnfsiothreads != 0) {
5711 			ret = nfs_pnfsio(start_dsremove, tdsrm);
5712 			NFSD_DEBUG(4, "nfsrv_pnfsremove: nfs_pnfsio=%d\n", ret);
5713 		}
5714 		if (ret != 0) {
5715 			ret = nfsrv_dsremove(tdsrm->dvp, fname, tcred, p);
5716 			if (failpos == -1 && nfsds_failerr(ret))
5717 				failpos = i;
5718 		}
5719 	}
5720 	ret = nfsrv_dsremove(*tdvpp, fname, tcred, p);
5721 	if (failpos == -1 && dsfilecnt > 1 && nfsds_failerr(ret))
5722 		failpos = dsfilecnt - 1;
5723 	timo = hz / 50;		/* Wait for 20msec. */
5724 	if (timo < 1)
5725 		timo = 1;
5726 	/* Wait for kernel task(s) to complete. */
5727 	for (tdsrm = dsrm, i = 0; i < dsfilecnt - 1; i++, tdsrm++) {
5728 		while (tdsrm->inprog != 0 && tdsrm->done == 0)
5729 			tsleep(&tdsrm->tsk, PVFS, "srvdsrm", timo);
5730 		if (failpos == -1 && nfsds_failerr(tdsrm->err))
5731 			failpos = i;
5732 	}
5733 
5734 	/*
5735 	 * If failpos has been set, that mirror has failed, so it needs
5736 	 * to be disabled.
5737 	 */
5738 	if (failpos >= 0) {
5739 		tdvpp = dvpp + failpos;
5740 		nmp = VFSTONFS((*tdvpp)->v_mount);
5741 		NFSLOCKMNT(nmp);
5742 		if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
5743 		     NFSMNTP_CANCELRPCS)) == 0) {
5744 			nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
5745 			NFSUNLOCKMNT(nmp);
5746 			ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER, nmp, p);
5747 			NFSD_DEBUG(4, "dsremovefail fail=%d ds=%p\n", failpos,
5748 			    ds);
5749 			if (ds != NULL)
5750 				nfsrv_killrpcs(nmp);
5751 			NFSLOCKMNT(nmp);
5752 			nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
5753 			wakeup(nmp);
5754 		}
5755 		NFSUNLOCKMNT(nmp);
5756 	}
5757 
5758 	/* Get rid all layouts for the file. */
5759 	nfsrv_freefilelayouts(fhp);
5760 
5761 	NFSFREECRED(tcred);
5762 	free(dsrm, M_TEMP);
5763 }
5764 
5765 /*
5766  * Generate a file name based on the file handle and put it in *bufp.
5767  * Return the number of bytes generated.
5768  */
5769 static int
nfsrv_putfhname(fhandle_t * fhp,char * bufp)5770 nfsrv_putfhname(fhandle_t *fhp, char *bufp)
5771 {
5772 	int i;
5773 	uint8_t *cp;
5774 	const uint8_t *hexdigits = "0123456789abcdef";
5775 
5776 	cp = (uint8_t *)fhp;
5777 	for (i = 0; i < sizeof(*fhp); i++) {
5778 		bufp[2 * i] = hexdigits[(*cp >> 4) & 0xf];
5779 		bufp[2 * i + 1] = hexdigits[*cp++ & 0xf];
5780 	}
5781 	bufp[2 * i] = '\0';
5782 	return (2 * i);
5783 }
5784 
5785 /*
5786  * Update the Metadata file's attributes from the DS file when a Read/Write
5787  * layout is returned.
5788  * Basically just call nfsrv_proxyds() with procedure == NFSPROC_LAYOUTRETURN
5789  * so that it does a nfsrv_getattrdsrpc() and nfsrv_setextattr() on the DS file.
5790  */
5791 int
nfsrv_updatemdsattr(struct vnode * vp,struct nfsvattr * nap,NFSPROC_T * p)5792 nfsrv_updatemdsattr(struct vnode *vp, struct nfsvattr *nap, NFSPROC_T *p)
5793 {
5794 	struct ucred *tcred;
5795 	int error;
5796 
5797 	/* Do this as root so that it won't fail with EACCES. */
5798 	tcred = newnfs_getcred();
5799 	error = nfsrv_proxyds(vp, 0, 0, tcred, p, NFSPROC_LAYOUTRETURN,
5800 	    NULL, NULL, NULL, nap, NULL, NULL, 0, NULL);
5801 	NFSFREECRED(tcred);
5802 	return (error);
5803 }
5804 
5805 /*
5806  * Set the NFSv4 ACL on the DS file to the same ACL as the MDS file.
5807  */
5808 static int
nfsrv_dssetacl(struct vnode * vp,struct acl * aclp,struct ucred * cred,NFSPROC_T * p)5809 nfsrv_dssetacl(struct vnode *vp, struct acl *aclp, struct ucred *cred,
5810     NFSPROC_T *p)
5811 {
5812 	int error;
5813 
5814 	error = nfsrv_proxyds(vp, 0, 0, cred, p, NFSPROC_SETACL,
5815 	    NULL, NULL, NULL, NULL, aclp, NULL, 0, NULL);
5816 	return (error);
5817 }
5818 
5819 static int
nfsrv_proxyds(struct vnode * vp,off_t off,int cnt,struct ucred * cred,struct thread * p,int ioproc,struct mbuf ** mpp,char * cp,struct mbuf ** mpp2,struct nfsvattr * nap,struct acl * aclp,off_t * offp,int content,bool * eofp)5820 nfsrv_proxyds(struct vnode *vp, off_t off, int cnt, struct ucred *cred,
5821     struct thread *p, int ioproc, struct mbuf **mpp, char *cp,
5822     struct mbuf **mpp2, struct nfsvattr *nap, struct acl *aclp,
5823     off_t *offp, int content, bool *eofp)
5824 {
5825 	struct nfsmount **nmp, *failnmp;
5826 	fhandle_t *fhp;
5827 	struct vnode **dvp;
5828 	struct nfsdevice *ds;
5829 	struct pnfsdsattr dsattr;
5830 	struct opnfsdsattr odsattr;
5831 	char *buf;
5832 	int buflen, error, failpos, i, mirrorcnt, origmircnt, trycnt;
5833 	int stripecnt;
5834 	uint64_t stripesiz;
5835 
5836 	NFSD_DEBUG(4, "in nfsrv_proxyds\n");
5837 	/*
5838 	 * If not a regular file, not exported or not a pNFS server,
5839 	 * just return ENOENT.
5840 	 */
5841 	if (vp->v_type != VREG || (vp->v_mount->mnt_flag & MNT_EXPORTED) == 0 ||
5842 	    nfsrv_devidcnt == 0)
5843 		return (ENOENT);
5844 
5845 	buflen = sizeof(struct pnfsdsfile) * NFSDEV_MAXMIRRORS *
5846 	    NFSDEV_MAXSTRIPE;
5847 	buf = malloc(buflen, M_TEMP, M_WAITOK);
5848 	error = 0;
5849 
5850 	/*
5851 	 * For Getattr, get the Change attribute (va_filerev) and size (va_size)
5852 	 * from the MetaData file's extended attribute.
5853 	 */
5854 	if (ioproc == NFSPROC_GETATTR) {
5855 		error = vn_extattr_get(vp, IO_NODELOCKED,
5856 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsattr", &buflen, buf,
5857 		    p);
5858 		if (error == 0) {
5859 			if (buflen == sizeof(odsattr)) {
5860 				NFSBCOPY(buf, &odsattr, buflen);
5861 				nap->na_filerev = odsattr.dsa_filerev;
5862 				nap->na_size = odsattr.dsa_size;
5863 				nap->na_atime = odsattr.dsa_atime;
5864 				nap->na_mtime = odsattr.dsa_mtime;
5865 				/*
5866 				 * Fake na_bytes by rounding up na_size.
5867 				 * Since we don't know the block size, just
5868 				 * use BLKDEV_IOSIZE.
5869 				 */
5870 				nap->na_bytes = (odsattr.dsa_size +
5871 				    BLKDEV_IOSIZE - 1) & ~(BLKDEV_IOSIZE - 1);
5872 			} else if (buflen == sizeof(dsattr)) {
5873 				NFSBCOPY(buf, &dsattr, buflen);
5874 				nap->na_filerev = dsattr.dsa_filerev;
5875 				nap->na_size = dsattr.dsa_size;
5876 				nap->na_atime = dsattr.dsa_atime;
5877 				nap->na_mtime = dsattr.dsa_mtime;
5878 				nap->na_bytes = dsattr.dsa_bytes;
5879 			} else
5880 				error = ENXIO;
5881 		}
5882 		if (error == 0) {
5883 			/*
5884 			 * If nfsrv_pnfsgetdsattr is 0 or nfsrv_checkdsattr()
5885 			 * returns 0, just return now.  nfsrv_checkdsattr()
5886 			 * returns 0 if there is no Read/Write layout
5887 			 * plus either an Open/Write_access or Write
5888 			 * delegation issued to a client for the file.
5889 			 */
5890 			if (nfsrv_pnfsgetdsattr == 0 ||
5891 			    nfsrv_checkdsattr(vp, p) == 0) {
5892 				free(buf, M_TEMP);
5893 				return (error);
5894 			}
5895 		}
5896 
5897 		/*
5898 		 * Clear ENOATTR so the code below will attempt to do a
5899 		 * nfsrv_getattrdsrpc() to get the attributes and (re)create
5900 		 * the extended attribute.
5901 		 */
5902 		if (error == ENOATTR)
5903 			error = 0;
5904 	}
5905 
5906 	origmircnt = -1;
5907 	trycnt = 0;
5908 tryagain:
5909 	nmp = NULL;
5910 	dvp = NULL;
5911 	fhp = NULL;
5912 	if (error == 0) {
5913 		buflen = sizeof(struct pnfsdsfile) * NFSDEV_MAXMIRRORS *
5914 		    NFSDEV_MAXSTRIPE;
5915 		if (ioproc == NFSPROC_READDS && NFSVOPISLOCKED(vp) ==
5916 		    LK_EXCLUSIVE)
5917 			printf("nfsrv_proxyds: Readds vp exclusively locked\n");
5918 		if (ioproc == NFSPROC_WRITEDS && NFSVOPISLOCKED(vp) ==
5919 		    LK_SHARED)
5920 			NFSVOPLOCK(vp, LK_UPGRADE | LK_RETRY);
5921 		error = nfsrv_dsgetsockmnt(vp, LK_SHARED, buf, &buflen,
5922 		    &mirrorcnt, &stripecnt, &stripesiz, p, &dvp, &fhp, NULL,
5923 		    NULL, NULL, NULL, NULL, NULL, NULL);
5924 		if (error == 0) {
5925 			nmp = malloc(sizeof(*nmp) * mirrorcnt * stripecnt,
5926 			    M_TEMP, M_WAITOK);
5927 			for (i = 0; i < mirrorcnt * stripecnt; i++)
5928 				if (dvp[i] != NULL)
5929 					nmp[i] = VFSTONFS(dvp[i]->v_mount);
5930 				else
5931 					nmp[i] = NULL;
5932 		} else
5933 			printf("pNFS: proxy getextattr sockaddr=%d\n", error);
5934 	} else
5935 		printf("pNFS: nfsrv_dsgetsockmnt=%d\n", error);
5936 	if (error == 0) {
5937 		if (origmircnt == -1)
5938 			origmircnt = mirrorcnt;
5939 		/*
5940 		 * If failpos is set to a mirror#, then that mirror has
5941 		 * failed and will be disabled. For Read, Getattr and Seek, the
5942 		 * function only tries one mirror, so if that mirror has
5943 		 * failed, it will need to be retried. As such, increment
5944 		 * tryitagain for these cases.
5945 		 * For Write, Setattr and Setacl, the function tries all
5946 		 * mirrors and will not return an error for the case where
5947 		 * one mirror has failed. For these cases, the functioning
5948 		 * mirror(s) will have been modified, so a retry isn't
5949 		 * necessary. These functions will set failpos for the
5950 		 * failed mirror#.
5951 		 */
5952 		if (ioproc == NFSPROC_READDS) {
5953 			error = nfsrv_readdsrpc(fhp, off, cnt, cred, p, nmp,
5954 			    mirrorcnt, stripecnt, stripesiz, mpp, mpp2,
5955 			    &failpos);
5956 			if (failpos >= 0 && mirrorcnt > 1) {
5957 				/*
5958 				 * Setting failpos will cause the mirror
5959 				 * to be disabled and then a retry of this
5960 				 * read is required.
5961 				 */
5962 				error = 0;
5963 				trycnt++;
5964 			}
5965 		} else if (ioproc == NFSPROC_WRITEDS)
5966 			error = nfsrv_writedsrpc(fhp, off, cnt, cred, p, vp,
5967 			    nmp, mirrorcnt, stripecnt, stripesiz, mpp, cp,
5968 			    &failpos);
5969 		else if (ioproc == NFSPROC_SETATTR)
5970 			error = nfsrv_setattrdsrpc(fhp, vp, cred, p, nmp,
5971 			    mirrorcnt, stripecnt, nap, &failpos);
5972 #ifdef notnow
5973 		else if (ioproc == NFSPROC_SETACL)
5974 			error = nfsrv_setacldsrpc(fh, cred, p, vp, &nmp[0],
5975 			    mirrorcnt, aclp, &failpos);
5976 		else if (ioproc == NFSPROC_SEEKDS) {
5977 			error = nfsrv_seekdsrpc(fh, offp, content, eofp, cred,
5978 			    p, nmp[0]);
5979 			if (nfsds_failerr(error) && mirrorcnt > 1) {
5980 				/*
5981 				 * Setting failpos will cause the mirror
5982 				 * to be disabled and then a retry of this
5983 				 * read is required.
5984 				 */
5985 				failpos = 0;
5986 				error = 0;
5987 				trycnt++;
5988 			}
5989 		} else if (ioproc == NFSPROC_ALLOCATE)
5990 			error = nfsrv_allocatedsrpc(fh, off, *offp, cred, p, vp,
5991 			    &nmp[0], mirrorcnt, &failpos);
5992 		else if (ioproc == NFSPROC_DEALLOCATE)
5993 			error = nfsrv_deallocatedsrpc(fh, off, *offp, cred, p,
5994 			    vp, &nmp[0], mirrorcnt, &failpos);
5995 #endif
5996 		else {
5997 			error = nfsrv_getattrdsrpc(fhp, vp, cred, p,
5998 			    nmp, stripecnt, nap, &failpos);
5999 			if (failpos >= 0 && mirrorcnt > 1) {
6000 				/*
6001 				 * Setting failpos will cause the mirror
6002 				 * to be disabled and then a retry of this
6003 				 * getattr is required.
6004 				 */
6005 				error = 0;
6006 				trycnt++;
6007 			}
6008 		}
6009 		ds = NULL;
6010 		if (failpos >= 0) {
6011 			failnmp = nmp[failpos];
6012 			NFSLOCKMNT(failnmp);
6013 			if ((failnmp->nm_privflag & (NFSMNTP_FORCEDISM |
6014 			     NFSMNTP_CANCELRPCS)) == 0) {
6015 				failnmp->nm_privflag |= NFSMNTP_CANCELRPCS;
6016 				NFSUNLOCKMNT(failnmp);
6017 				ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER,
6018 				    failnmp, p);
6019 				NFSD_DEBUG(4, "dsldsnmp fail=%d ds=%p\n",
6020 				    failpos, ds);
6021 				if (ds != NULL)
6022 					nfsrv_killrpcs(failnmp);
6023 				NFSLOCKMNT(failnmp);
6024 				failnmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
6025 				wakeup(failnmp);
6026 			}
6027 			NFSUNLOCKMNT(failnmp);
6028 		}
6029 		for (i = 0; i < mirrorcnt * stripecnt; i++)
6030 			if (dvp[i] != NULL)
6031 				NFSVOPUNLOCK(dvp[i]);
6032 		free(dvp, M_TEMP);
6033 		free(nmp, M_TEMP);
6034 		free(fhp, M_TEMP);
6035 		NFSD_DEBUG(4, "nfsrv_proxyds: aft RPC=%d trya=%d\n", error,
6036 		    trycnt);
6037 		/* Try the Read/Getattr again if a mirror was deleted. */
6038 		if (ds != NULL && trycnt > 0 && trycnt < origmircnt)
6039 			goto tryagain;
6040 	} else {
6041 		/* Return ENOENT for any Extended Attribute error. */
6042 		error = ENOENT;
6043 	}
6044 	free(buf, M_TEMP);
6045 	NFSD_DEBUG(4, "nfsrv_proxyds: error=%d\n", error);
6046 	return (error);
6047 }
6048 
6049 /*
6050  * Get the DS mount point, fh and directory from the "pnfsd.dsfile" extended
6051  * attribute.
6052  * newnmpp - If it points to a non-NULL nmp, that is the destination and needs
6053  *           to be checked.  If it points to a NULL nmp, then it returns
6054  *           a suitable destination.
6055  * curnmp - If non-NULL, it is the source mount for the copy.
6056  */
6057 int
nfsrv_dsgetsockmnt(struct vnode * vp,int lktype,char * buf,int * buflenp,int * mirrorcntp,int * stripecntp,uint64_t * stripesizp,NFSPROC_T * p,struct vnode *** dvppp,fhandle_t ** fhpp,char ** devid,char * fnamep,struct vnode ** nvpp,struct nfsmount ** newnmpp,struct nfsmount * curnmp,int * ippos,int * dsdirp)6058 nfsrv_dsgetsockmnt(struct vnode *vp, int lktype, char *buf, int *buflenp,
6059     int *mirrorcntp, int *stripecntp, uint64_t *stripesizp, NFSPROC_T *p,
6060     struct vnode ***dvppp, fhandle_t **fhpp,
6061     char **devid, char *fnamep, struct vnode **nvpp, struct nfsmount **newnmpp,
6062     struct nfsmount *curnmp, int *ippos, int *dsdirp)
6063 {
6064 	struct vnode *dvp, *nvp = NULL, **tdvpp = NULL;	/* Shut up gcc. */
6065 	struct mount *mp;
6066 	struct nfsmount *nmp, *newnmp;
6067 	fhandle_t *tfhp = NULL;				/* Shut up gcc. */
6068 	struct sockaddr *sad;
6069 	struct sockaddr_in *sin;
6070 	struct nfsdevice *ds, *tds, *fndds;
6071 	struct pnfsdsfile *pf;
6072 	struct opnfsdsfile *opf;
6073 	uint32_t dsdir;
6074 	int error, fhiszero, fnd, gotmirror, gotone, i, j, k, l, m, mirrorcnt;
6075 	char *tdevid;
6076 	bool dvplocked;
6077 
6078 	ASSERT_VOP_LOCKED(vp, "nfsrv_dsgetsockmnt vp");
6079 	dvplocked = false;
6080 	if (mirrorcntp != NULL)
6081 		*mirrorcntp = 1;
6082 	if (stripecntp != NULL)
6083 		*stripecntp = 1;
6084 	if (stripesizp != NULL)
6085 		*stripesizp = 0;
6086 	if (nvpp != NULL)
6087 		*nvpp = NULL;
6088 	if (dvppp != NULL)
6089 		*dvppp = NULL;
6090 	if (fhpp != NULL)
6091 		*fhpp = NULL;
6092 	if (devid != NULL)
6093 		*devid = NULL;
6094 	tdevid = NULL;
6095 	if (ippos != NULL)
6096 		*ippos = -1;
6097 	if (newnmpp != NULL)
6098 		newnmp = *newnmpp;
6099 	else
6100 		newnmp = NULL;
6101 	if (fnamep != NULL)
6102 		fnamep[0] = '\0';
6103 	mp = vp->v_mount;
6104 	error = vn_extattr_get(vp, IO_NODELOCKED, EXTATTR_NAMESPACE_SYSTEM,
6105 	    "pnfsd.dsfile", buflenp, buf, p);
6106 	if (error == 0 && *buflenp > 0) {
6107 		j = *buflenp / sizeof(*pf);
6108 		if (*buflenp != sizeof(*pf) * j) {
6109 			/* Try opnfsdsfile. */
6110 			j = *buflenp / sizeof(*opf);
6111 			if (j >= 1 && *buflenp == sizeof(*opf) * j) {
6112 				char *tbuf;
6113 
6114 				tbuf = malloc(*buflenp, M_TEMP, M_WAITOK);
6115 				memcpy(tbuf, buf, *buflenp);
6116 				pf = (struct pnfsdsfile *)buf;
6117 				opf = (struct opnfsdsfile *)tbuf;
6118 				for (k = 0; k < j; k++, pf++, opf++) {
6119 					memcpy(&pf->dsf_fh, opf, sizeof(*opf));
6120 					pf->dsf_stripecnt = 1;
6121 					pf->dsf_stripesiz = 0;
6122 				}
6123 				free(tbuf, M_TEMP);
6124 			} else
6125 				error = ENOATTR;
6126 		} else if (j < 1)
6127 			error = ENOATTR;
6128 	} else if (error == 0)
6129 		error = ENOATTR;
6130 	if (error != 0)
6131 		return (error);
6132 
6133 	pf = (struct pnfsdsfile *)buf;
6134 	if (pf->dsf_stripesiz > 0) {
6135 		mirrorcnt = j / pf->dsf_stripecnt;
6136 		k = pf->dsf_stripecnt;
6137 	} else {
6138 		mirrorcnt = j;
6139 		k = 1;
6140 	}
6141 	if (mirrorcnt < 1 || mirrorcnt > NFSDEV_MAXMIRRORS ||
6142 	    k < 1 || k > NFSDEV_MAXSTRIPE || j != mirrorcnt * k)
6143 		return (ENOATTR);
6144 	if (stripecntp != NULL)
6145 		*stripecntp = k;
6146 	if (stripesizp != NULL)
6147 		*stripesizp = pf->dsf_stripesiz;
6148 
6149 	/* Allocate a large enough array for dvppp, if required. */
6150 	if (dvppp != NULL)
6151 		tdvpp = *dvppp = malloc(sizeof(*tdvpp) * mirrorcnt * k, M_TEMP,
6152 		    M_WAITOK | M_ZERO);
6153 	if (fhpp != NULL)
6154 		tfhp = *fhpp = malloc(sizeof(*tfhp) * mirrorcnt * k, M_TEMP,
6155 		    M_WAITOK);
6156 	if (devid != NULL)
6157 		tdevid = *devid = malloc(NFSX_V4DEVICEID * mirrorcnt * k,
6158 		    M_TEMP, M_WAITOK);
6159 
6160 	/* If curnmp != NULL, check for a match in the mirror list. */
6161 	if (curnmp != NULL) {
6162 		fnd = 0;
6163 		for (i = 0; i < j; i += k, pf += k) {
6164 			sad = (struct sockaddr *)&pf->dsf_sin;
6165 			if (nfsaddr2_match(sad, curnmp->nm_nam)) {
6166 				if (ippos != NULL)
6167 					*ippos = i;
6168 				fnd = 1;
6169 				break;
6170 			}
6171 		}
6172 		if (fnd == 0)
6173 			error = ENXIO;
6174 	}
6175 
6176 	gotmirror = gotone = 0;
6177 	l = 0;			/* Index for tdvpp and tfhp. */
6178 	pf = (struct pnfsdsfile *)buf;
6179 	NFSD_DEBUG(4, "nfsrv_dsgetsockmnt: mirrorcnt=%d stripecnt=%d err=%d\n",
6180 	    mirrorcnt, k, error);
6181 	for (i = 0; i < j && error == 0; i++, pf++) {
6182 		fhiszero = 0;
6183 		sad = (struct sockaddr *)&pf->dsf_sin;
6184 		sin = &pf->dsf_sin;
6185 		dsdir = pf->dsf_dir;
6186 		if (dsdir >= nfsrv_dsdirsize) {
6187 			printf("nfsrv_dsgetsockmnt: dsdir=%d\n", dsdir);
6188 			error = ENOATTR;
6189 		} else if (nvpp != NULL && newnmp != NULL &&
6190 		    nfsaddr2_match(sad, newnmp->nm_nam))
6191 			error = EEXIST;
6192 		if (error == 0) {
6193 			if (ippos != NULL && curnmp == NULL &&
6194 			    sad->sa_family == AF_INET &&
6195 			    sin->sin_addr.s_addr == 0)
6196 				*ippos = i;
6197 			if (NFSBCMP(&zerofh, &pf->dsf_fh, sizeof(zerofh)) == 0)
6198 				fhiszero = 1;
6199 			/* Use the socket address to find the mount point. */
6200 			fndds = NULL;
6201 			NFSDDSLOCK();
6202 			/* Find a match for the IP address. */
6203 			TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
6204 				if (ds->nfsdev_nmp != NULL) {
6205 					dvp = ds->nfsdev_dvp;
6206 					nmp = VFSTONFS(dvp->v_mount);
6207 					if (nmp != ds->nfsdev_nmp)
6208 						printf("different2 nmp %p %p\n",
6209 						    nmp, ds->nfsdev_nmp);
6210 					if (nfsaddr2_match(sad, nmp->nm_nam)) {
6211 						fndds = ds;
6212 						break;
6213 					}
6214 				}
6215 			}
6216 			if (fndds != NULL && newnmpp != NULL &&
6217 			    newnmp == NULL) {
6218 				/* Search for a place to make a mirror copy. */
6219 				TAILQ_FOREACH(tds, &nfsrv_devidhead,
6220 				    nfsdev_list) {
6221 					if (tds->nfsdev_nmp != NULL &&
6222 					    fndds != tds &&
6223 					    ((tds->nfsdev_mdsisset == 0 &&
6224 					      fndds->nfsdev_mdsisset == 0) ||
6225 					     (tds->nfsdev_mdsisset != 0 &&
6226 					      fndds->nfsdev_mdsisset != 0 &&
6227 					      fsidcmp(&tds->nfsdev_mdsfsid,
6228 					      &mp->mnt_stat.f_fsid) == 0))) {
6229 						*newnmpp = tds->nfsdev_nmp;
6230 						break;
6231 					}
6232 				}
6233 				if (tds != NULL) {
6234 					/*
6235 					 * Move this entry to the end of the
6236 					 * list, so it won't be selected as
6237 					 * easily the next time.
6238 					 */
6239 					TAILQ_REMOVE(&nfsrv_devidhead, tds,
6240 					    nfsdev_list);
6241 					TAILQ_INSERT_TAIL(&nfsrv_devidhead, tds,
6242 					    nfsdev_list);
6243 				}
6244 			}
6245 			NFSDDSUNLOCK();
6246 			if (fndds != NULL) {
6247 				dvp = fndds->nfsdev_dsdir[dsdir];
6248 				if (lktype != 0 || fhiszero != 0 ||
6249 				    (nvpp != NULL && *nvpp == NULL)) {
6250 					dvplocked = true;
6251 					if (fhiszero != 0)
6252 						error = vn_lock(dvp,
6253 						    LK_EXCLUSIVE);
6254 					else if (lktype != 0)
6255 						error = vn_lock(dvp, lktype);
6256 					else
6257 						error = vn_lock(dvp, LK_SHARED);
6258 					/*
6259 					 * If the file handle is all 0's, try to
6260 					 * do a Lookup against the DS to acquire
6261 					 * it.
6262 					 * If dvpp == NULL or the Lookup fails,
6263 					 * unlock dvp after the call.
6264 					 */
6265 					if (error == 0 && (fhiszero != 0 ||
6266 					    (nvpp != NULL && *nvpp == NULL))) {
6267 						error = nfsrv_pnfslookupds(vp,
6268 						    dvp, pf, &nvp, p);
6269 						if (error == 0) {
6270 							if (fhiszero != 0)
6271 								nfsrv_pnfssetfh(
6272 								    vp, pf,
6273 								    devid,
6274 								    fnamep,
6275 								    nvp, p);
6276 							if (nvpp != NULL &&
6277 							    *nvpp == NULL) {
6278 								*nvpp = nvp;
6279 								*dsdirp = dsdir;
6280 							} else
6281 								vput(nvp);
6282 						}
6283 						if (error != 0 || lktype == 0)
6284 							NFSVOPUNLOCK(dvp);
6285 					}
6286 				}
6287 				if (error == 0) {
6288 					gotone++;
6289 					NFSD_DEBUG(4, "gotone=%d\n", gotone);
6290 					if (tdevid != NULL) {
6291 						NFSBCOPY(fndds->nfsdev_deviceid,
6292 						    tdevid, NFSX_V4DEVICEID);
6293 						tdevid += NFSX_V4DEVICEID;
6294 					}
6295 					if (dvppp != NULL)
6296 						tdvpp[l] = dvp;
6297 					if (fhpp != NULL)
6298 						NFSBCOPY(&pf->dsf_fh, &tfhp[l],
6299 						    NFSX_MYFH);
6300 					if (dvppp != NULL || fhpp != NULL) {
6301 						l++;
6302 						if (l % k == 0)
6303 							gotmirror++;
6304 					}
6305 					if (fnamep != NULL && gotone == 1)
6306 						strlcpy(fnamep,
6307 						    pf->dsf_filename,
6308 						    sizeof(pf->dsf_filename));
6309 				} else
6310 					NFSD_DEBUG(4, "nfsrv_dsgetsockmnt "
6311 					    "err=%d\n", error);
6312 			} else if (fnamep == NULL) {
6313 				/*
6314 				 * fnamep is NULL for ReadDS, WriteDS,
6315 				 * SetattrDS and GetattrDS.  For these cases,
6316 				 * do not use a partial stripe set as a
6317 				 * mirror.
6318 				 */
6319 				for (m = l / k * k; m < l; m++) {
6320 					if (dvplocked)
6321 						NFSVOPUNLOCK(tdvpp[m]);
6322 					tdvpp[m] = NULL;
6323 				}
6324 				l = l / k * k;
6325 			}
6326 		}
6327 	}
6328 	if (fnamep != NULL) {
6329 		/*
6330 		 * If fnamep != NULL, a list of all DSs is wanted.
6331 		 * For this, cheat and return the total cound of DSs in
6332 		 * mirrorcnt.
6333 		 */
6334 		gotmirror = gotone;
6335 		NFSD_DEBUG(4, "nfsrv_dsgetsockmnt: fname=%s, gotmirror=%d\n",
6336 		    fnamep, gotmirror);
6337 	}
6338 	if (error == 0 && gotmirror == 0)
6339 		error = ENOENT;
6340 
6341 	NFSD_DEBUG(4, "eo nfsrv_dsgetsockmnt: gotone=%d err=%d\n", gotone,
6342 	    error);
6343 	if (error == 0) {
6344 		if (mirrorcntp != NULL)
6345 			*mirrorcntp = gotmirror;
6346 	} else {
6347 		if (dvppp != NULL) {
6348 			if (l > 0 && dvplocked) {
6349 				/*
6350 				 * If the error didn't occur on the first one
6351 				 * and dvppp != NULL, the one(s) prior to the
6352 				 * failure will have locked dvp's that need to
6353 				 * be unlocked.
6354 				 */
6355 				tdvpp = *dvppp;
6356 				for (i = 0; i < l; i++)
6357 					NFSVOPUNLOCK(*tdvpp++);
6358 			}
6359 			free(*dvppp, M_TEMP);
6360 			*dvppp = NULL;
6361 		}
6362 		if (fhpp != NULL) {
6363 			free(*fhpp, M_TEMP);
6364 			*fhpp = NULL;
6365 		}
6366 		if (devid != NULL) {
6367 			free(*devid, M_TEMP);
6368 			*devid = NULL;
6369 		}
6370 		/*
6371 		 * If it found the vnode to be copied from before a failure,
6372 		 * it needs to be vput()'d.
6373 		 */
6374 		if (nvpp != NULL && *nvpp != NULL) {
6375 			vput(*nvpp);
6376 			*nvpp = NULL;
6377 		}
6378 	}
6379 	return (error);
6380 }
6381 
6382 /*
6383  * Set the extended attribute for the Change attribute.
6384  */
6385 static int
nfsrv_setextattr(struct vnode * vp,struct nfsvattr * nap,NFSPROC_T * p)6386 nfsrv_setextattr(struct vnode *vp, struct nfsvattr *nap, NFSPROC_T *p)
6387 {
6388 	struct pnfsdsattr dsattr;
6389 	int error;
6390 
6391 	ASSERT_VOP_ELOCKED(vp, "nfsrv_setextattr vp");
6392 	dsattr.dsa_filerev = nap->na_filerev;
6393 	dsattr.dsa_size = nap->na_size;
6394 	dsattr.dsa_atime = nap->na_atime;
6395 	dsattr.dsa_mtime = nap->na_mtime;
6396 	dsattr.dsa_bytes = nap->na_bytes;
6397 	error = vn_extattr_set(vp, IO_NODELOCKED, EXTATTR_NAMESPACE_SYSTEM,
6398 	    "pnfsd.dsattr", sizeof(dsattr), (char *)&dsattr, p);
6399 	if (error != 0)
6400 		printf("pNFS: setextattr=%d\n", error);
6401 	return (error);
6402 }
6403 
6404 /*
6405  * Do a read RPC on a DS data file, using this structure for the arguments,
6406  * so that this function can be executed by a separate kernel process.
6407  */
6408 struct nfsrvreaddsdorpc {
6409 	int			done;
6410 	int			inprog;
6411 	struct task		tsk;
6412 	fhandle_t		fh;
6413 	off_t			off;
6414 	int			len;
6415 	struct nfsmount		*nmp;
6416 	struct ucred		*cred;
6417 	NFSPROC_T		*p;
6418 	struct mbuf		*m;
6419 	struct mbuf		*mend;
6420 	int			err;
6421 };
6422 
6423 static int
nfsrv_readdsdorpc(fhandle_t * fhp,off_t off,int len,struct ucred * cred,NFSPROC_T * p,struct nfsmount * nmp,struct mbuf ** mpp,struct mbuf ** mpendp)6424 nfsrv_readdsdorpc(fhandle_t *fhp, off_t off, int len, struct ucred *cred,
6425     NFSPROC_T *p, struct nfsmount *nmp, struct mbuf **mpp, struct mbuf **mpendp)
6426 {
6427 	uint32_t *tl;
6428 	struct nfsrv_descript *nd;
6429 	nfsv4stateid_t st;
6430 	struct mbuf *m, *m2;
6431 	int error = 0, retlen, tlen, trimlen;
6432 
6433 	NFSD_DEBUG(4, "in nfsrv_readdsdorpc\n");
6434 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
6435 	*mpp = NULL;
6436 	/*
6437 	 * Use a stateid where other is an alternating 01010 pattern and
6438 	 * seqid is 0xffffffff.  This value is not defined as special by
6439 	 * the RFC and is used by the FreeBSD NFS server to indicate an
6440 	 * MDS->DS proxy operation.
6441 	 */
6442 	st.other[0] = 0x55555555;
6443 	st.other[1] = 0x55555555;
6444 	st.other[2] = 0x55555555;
6445 	st.seqid = 0xffffffff;
6446 	nfscl_reqstart(nd, NFSPROC_READDS, nmp, (u_int8_t *)fhp, sizeof(*fhp),
6447 	    NULL, NULL, 0, 0, cred);
6448 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
6449 	NFSM_BUILD(tl, uint32_t *, NFSX_UNSIGNED * 3);
6450 	txdr_hyper(off, tl);
6451 	*(tl + 2) = txdr_unsigned(len);
6452 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
6453 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
6454 	if (error != 0) {
6455 		free(nd, M_TEMP);
6456 		return (error);
6457 	}
6458 	if (nd->nd_repstat == 0) {
6459 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
6460 		NFSM_STRSIZ(retlen, len);
6461 		if (retlen > 0) {
6462 			/* Trim off the pre-data XDR from the mbuf chain. */
6463 			m = nd->nd_mrep;
6464 			while (m != NULL && m != nd->nd_md) {
6465 				if (m->m_next == nd->nd_md) {
6466 					m->m_next = NULL;
6467 					m_freem(nd->nd_mrep);
6468 					nd->nd_mrep = m = nd->nd_md;
6469 				} else
6470 					m = m->m_next;
6471 			}
6472 			if (m == NULL) {
6473 				printf("nfsrv_readdsdorpc: busted mbuf list\n");
6474 				error = ENOENT;
6475 				goto nfsmout;
6476 			}
6477 
6478 			/*
6479 			 * Now, adjust first mbuf so that any XDR before the
6480 			 * read data is skipped over.
6481 			 */
6482 			trimlen = nd->nd_dpos - mtod(m, char *);
6483 			if (trimlen > 0) {
6484 				m->m_len -= trimlen;
6485 				NFSM_DATAP(m, trimlen);
6486 			}
6487 
6488 			/*
6489 			 * Truncate the mbuf chain at retlen bytes of data,
6490 			 * plus XDR padding that brings the length up to a
6491 			 * multiple of 4.
6492 			 */
6493 			tlen = NFSM_RNDUP(retlen);
6494 			do {
6495 				if (m->m_len >= tlen) {
6496 					m->m_len = tlen;
6497 					tlen = 0;
6498 					m2 = m->m_next;
6499 					m->m_next = NULL;
6500 					m_freem(m2);
6501 					break;
6502 				}
6503 				tlen -= m->m_len;
6504 				m = m->m_next;
6505 			} while (m != NULL);
6506 			if (tlen > 0) {
6507 				printf("nfsrv_readdsdorpc: busted mbuf list\n");
6508 				error = ENOENT;
6509 				goto nfsmout;
6510 			}
6511 			*mpp = nd->nd_mrep;
6512 			*mpendp = m;
6513 			nd->nd_mrep = NULL;
6514 		}
6515 	} else
6516 		error = nd->nd_repstat;
6517 nfsmout:
6518 	/* If nd->nd_mrep is already NULL, this is a no-op. */
6519 	m_freem(nd->nd_mrep);
6520 	free(nd, M_TEMP);
6521 	NFSD_DEBUG(4, "nfsrv_readdsdorpc error=%d\n", error);
6522 	return (error);
6523 }
6524 
6525 /*
6526  * Start up the thread that will execute nfsrv_readdsdorpc().
6527  */
6528 static void
start_readdsdorpc(void * arg,int pending)6529 start_readdsdorpc(void *arg, int pending)
6530 {
6531 	struct nfsrvreaddsdorpc *drpc;
6532 
6533 	drpc = (struct nfsrvreaddsdorpc *)arg;
6534 	drpc->err = nfsrv_readdsdorpc(&drpc->fh, drpc->off, drpc->len,
6535 	    drpc->cred, drpc->p, drpc->nmp, &drpc->m, &drpc->mend);
6536 	drpc->done = 1;
6537 	NFSD_DEBUG(4, "start_readdsdorpc: err=%d\n", drpc->err);
6538 }
6539 
6540 static int
nfsrv_readdsrpc(fhandle_t * fhp,off_t off,int len,struct ucred * cred,NFSPROC_T * p,struct nfsmount ** nmp,int mirrorcnt,int stripecnt,uint64_t stripesiz,struct mbuf ** mpp,struct mbuf ** mendp,int * failposp)6541 nfsrv_readdsrpc(fhandle_t *fhp, off_t off, int len, struct ucred *cred,
6542     NFSPROC_T *p, struct nfsmount **nmp, int mirrorcnt, int stripecnt,
6543     uint64_t stripesiz, struct mbuf **mpp, struct mbuf **mendp, int *failposp)
6544 {
6545 	struct nfsrvreaddsdorpc *drpc, *tdrpc;
6546 	struct mbuf *m, *m2, *mend;
6547 	fhandle_t *tfhp;
6548 	struct nfsmount **tnmp;
6549 	uint64_t scnt;
6550 	int error, i, j, k, l, n, ret, timo;
6551 
6552 	NFSD_DEBUG(4, "in nfsrv_readdsrpc\n");
6553 	drpc = NULL;
6554 	m2 = *mpp = NULL;
6555 	*failposp = -1;
6556 	if (stripecnt > 1) {
6557 		/* Set j to the upper bound of the # of stripes to read. */
6558 		j = (len + len - 1) / stripesiz + 1;
6559 		tdrpc = drpc = malloc(sizeof(*drpc) * j, M_TEMP, M_WAITOK);
6560 	}
6561 
6562 	/* For each stripe except last one, read the stripe. */
6563 	for (j = 0; ; j++, tdrpc++) {
6564 		if (stripecnt > 1) {
6565 			k = (off / stripesiz) % (uint64_t)stripecnt;
6566 			scnt = stripesiz - (off % stripesiz);
6567 			l = ((uint64_t)len < scnt) ? len : (int)scnt;
6568 		} else {
6569 			k = 0;
6570 			l = len;
6571 		}
6572 		if (j == 0)
6573 			n = k;		/* Save first stripe# for later. */
6574 		tfhp = fhp + k;
6575 		tnmp = nmp + k;
6576 		NFSD_DEBUG(4, "nfsrv_readdsrpc: mcopy k=%d l=%d\n", k, l);
6577 
6578 		/* Break out of the loop for the last stripe. */
6579 		if (l == len)
6580 			break;
6581 
6582 		/*
6583 		 * Do the read RPC for every DS, using a separate kernel
6584 		 * process for every DS, except the last one.
6585 		 */
6586 		error = 0;
6587 		tdrpc->done = 0;
6588 		NFSBCOPY(tfhp, &tdrpc->fh, sizeof(*tfhp));
6589 		tdrpc->off = off;
6590 		tdrpc->len = l;
6591 		tdrpc->nmp = *tnmp;
6592 		tdrpc->cred = cred;
6593 		tdrpc->p = p;
6594 		tdrpc->inprog = 0;
6595 		tdrpc->err = 0;
6596 		ret = EIO;
6597 		if (nfs_pnfsiothreads != 0) {
6598 			ret = nfs_pnfsio(start_readdsdorpc, tdrpc);
6599 			NFSD_DEBUG(4, "nfsrv_readdsrpc: "
6600 			    "nfs_pnfsio=%d\n", ret);
6601 		}
6602 		if (ret != 0) {
6603 			ret = nfsrv_readdsdorpc(tfhp, off, l, cred, p,
6604 			    *tnmp, &tdrpc->m, &tdrpc->mend);
6605 			if (nfsds_failerr(ret) && *failposp == -1)
6606 				*failposp = k;
6607 			else if (error == 0 && ret != 0)
6608 				tdrpc->err = ret;
6609 			tdrpc->inprog = 0;
6610 			tdrpc->done = 1;
6611 		}
6612 		off += l;
6613 		len -= l;
6614 	}
6615 	ret = nfsrv_readdsdorpc(tfhp, off, l, cred, p, *tnmp, &m, &mend);
6616 	if (nfsds_failerr(ret) && *failposp == -1)
6617 		*failposp = k;
6618 	if (error == 0 && ret != 0)
6619 		error = ret;
6620 	NFSD_DEBUG(4, "nfsrv_readdsrpc: aft stripes=%d\n", error);
6621 	tdrpc = drpc;
6622 	timo = hz / 50;		/* Wait for 20msec. */
6623 	if (timo < 1)
6624 		timo = 1;
6625 	k = n;			/* Keep track of stripe#. */
6626 	for (i = 0; i < j - 1; i++, tdrpc++) {
6627 		/* Wait for RPCs on separate threads to complete. */
6628 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
6629 			tsleep(&tdrpc->tsk, PVFS, "srvwrds", timo);
6630 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
6631 			*failposp = k;
6632 		else if (error == 0 && tdrpc->err != 0)
6633 			error = tdrpc->err;
6634 		else {
6635 			if (m2 != NULL)
6636 				m2->m_next = tdrpc->m;
6637 			else
6638 				*mpp = tdrpc->m;
6639 			m2 = tdrpc->mend;
6640 		}
6641 		k = (k + 1) % stripecnt;
6642 	}
6643 	if (m2 != NULL)
6644 		m2->m_next = m;
6645 	else
6646 		*mpp = m;
6647 	*mendp = mend;
6648 
6649 	free(drpc, M_TEMP);
6650 	return (error);
6651 }
6652 
6653 /*
6654  * Do a write RPC on a DS data file, using this structure for the arguments,
6655  * so that this function can be executed by a separate kernel process.
6656  */
6657 struct nfsrvwritedsdorpc {
6658 	int			done;
6659 	int			inprog;
6660 	struct task		tsk;
6661 	fhandle_t		fh;
6662 	off_t			off;
6663 	int			len;
6664 	struct nfsmount		*nmp;
6665 	struct ucred		*cred;
6666 	NFSPROC_T		*p;
6667 	struct mbuf		*m;
6668 	int			err;
6669 };
6670 
6671 static int
nfsrv_writedsdorpc(struct nfsmount * nmp,fhandle_t * fhp,off_t off,int len,struct nfsvattr * nap,struct mbuf * m,struct ucred * cred,NFSPROC_T * p)6672 nfsrv_writedsdorpc(struct nfsmount *nmp, fhandle_t *fhp, off_t off, int len,
6673     struct nfsvattr *nap, struct mbuf *m, struct ucred *cred, NFSPROC_T *p)
6674 {
6675 	uint32_t *tl;
6676 	struct nfsrv_descript *nd;
6677 	nfsattrbit_t attrbits;
6678 	nfsv4stateid_t st;
6679 	int commit, error, retlen;
6680 
6681 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
6682 	nfscl_reqstart(nd, NFSPROC_WRITE, nmp, (u_int8_t *)fhp,
6683 	    sizeof(fhandle_t), NULL, NULL, 0, 0, cred);
6684 
6685 	/*
6686 	 * Use a stateid where other is an alternating 01010 pattern and
6687 	 * seqid is 0xffffffff.  This value is not defined as special by
6688 	 * the RFC and is used by the FreeBSD NFS server to indicate an
6689 	 * MDS->DS proxy operation.
6690 	 */
6691 	st.other[0] = 0x55555555;
6692 	st.other[1] = 0x55555555;
6693 	st.other[2] = 0x55555555;
6694 	st.seqid = 0xffffffff;
6695 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
6696 	NFSM_BUILD(tl, u_int32_t *, NFSX_HYPER + 2 * NFSX_UNSIGNED);
6697 	txdr_hyper(off, tl);
6698 	tl += 2;
6699 	/*
6700 	 * Do all writes FileSync, since the server doesn't hold onto dirty
6701 	 * buffers.  Since clients should be accessing the DS servers directly
6702 	 * using the pNFS layouts, this just needs to work correctly as a
6703 	 * fallback.
6704 	 */
6705 	*tl++ = txdr_unsigned(NFSWRITE_FILESYNC);
6706 	*tl = txdr_unsigned(len);
6707 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: len=%d\n", len);
6708 
6709 	/* Put data in mbuf chain. */
6710 	nd->nd_mb->m_next = m;
6711 
6712 	/* Set nd_mb and nd_bpos to end of data. */
6713 	while (m->m_next != NULL)
6714 		m = m->m_next;
6715 	nd->nd_mb = m;
6716 	nfsm_set(nd, m->m_len);
6717 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: lastmb len=%d\n", m->m_len);
6718 
6719 	/* Do a Getattr for the attributes that change upon writing. */
6720 	NFSZERO_ATTRBIT(&attrbits);
6721 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
6722 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
6723 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
6724 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
6725 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
6726 	NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
6727 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
6728 	(void) nfsrv_putattrbit(nd, &attrbits);
6729 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p,
6730 	    cred, NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
6731 	if (error != 0) {
6732 		free(nd, M_TEMP);
6733 		return (error);
6734 	}
6735 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: aft writerpc=%d\n", nd->nd_repstat);
6736 	/* Get rid of weak cache consistency data for now. */
6737 	if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
6738 	    (ND_NFSV4 | ND_V4WCCATTR)) {
6739 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
6740 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL,
6741 		    NULL, NULL);
6742 		NFSD_DEBUG(4, "nfsrv_writedsdorpc: wcc attr=%d\n", error);
6743 		if (error != 0)
6744 			goto nfsmout;
6745 		/*
6746 		 * Get rid of Op# and status for next op.
6747 		 */
6748 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
6749 		if (*++tl != 0)
6750 			nd->nd_flag |= ND_NOMOREDATA;
6751 	}
6752 	if (nd->nd_repstat == 0) {
6753 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED + NFSX_VERF);
6754 		retlen = fxdr_unsigned(int, *tl++);
6755 		commit = fxdr_unsigned(int, *tl);
6756 		if (commit != NFSWRITE_FILESYNC)
6757 			error = NFSERR_IO;
6758 		NFSD_DEBUG(4, "nfsrv_writedsdorpc:retlen=%d commit=%d err=%d\n",
6759 		    retlen, commit, error);
6760 	} else
6761 		error = nd->nd_repstat;
6762 	/* We have no use for the Write Verifier since we use FileSync. */
6763 
6764 	/*
6765 	 * Get the Change, Size, Access Time and Modify Time attributes and set
6766 	 * on the Metadata file, so its attributes will be what the file's
6767 	 * would be if it had been written.
6768 	 */
6769 	if (error == 0) {
6770 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
6771 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
6772 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL,
6773 		    NULL, NULL);
6774 	}
6775 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: aft loadattr=%d\n", error);
6776 nfsmout:
6777 	m_freem(nd->nd_mrep);
6778 	free(nd, M_TEMP);
6779 	NFSD_DEBUG(4, "nfsrv_writedsdorpc error=%d\n", error);
6780 	return (error);
6781 }
6782 
6783 /*
6784  * Start up the thread that will execute nfsrv_writedsdorpc().
6785  */
6786 static void
start_writedsdorpc(void * arg,int pending)6787 start_writedsdorpc(void *arg, int pending)
6788 {
6789 	struct nfsrvwritedsdorpc *drpc;
6790 
6791 	drpc = (struct nfsrvwritedsdorpc *)arg;
6792 	drpc->err = nfsrv_writedsdorpc(drpc->nmp, &drpc->fh, drpc->off,
6793 	    drpc->len, NULL, drpc->m, drpc->cred, drpc->p);
6794 	drpc->done = 1;
6795 	NFSD_DEBUG(4, "start_writedsdorpc: err=%d\n", drpc->err);
6796 }
6797 
6798 static int
nfsrv_writedsrpc(fhandle_t * fhp,off_t off,int len,struct ucred * cred,NFSPROC_T * p,struct vnode * vp,struct nfsmount ** nmp,int mirrorcnt,int stripecnt,uint64_t stripesiz,struct mbuf ** mpp,char * cp,int * failposp)6799 nfsrv_writedsrpc(fhandle_t *fhp, off_t off, int len, struct ucred *cred,
6800     NFSPROC_T *p, struct vnode *vp, struct nfsmount **nmp, int mirrorcnt,
6801     int stripecnt, uint64_t stripesiz, struct mbuf **mpp, char *cp,
6802     int *failposp)
6803 {
6804 	struct nfsrvwritedsdorpc *drpc, *tdrpc = NULL;	/* Shut up gcc. */
6805 	struct nfsvattr na;
6806 	struct mbuf *m;
6807 	fhandle_t *tfhp;
6808 	struct nfsmount **tnmp;
6809 	uint64_t scnt;
6810 	int error, i, j, k, l, n, o, offs, ret, timo;
6811 
6812 	NFSD_DEBUG(4, "in nfsrv_writedsrpc\n");
6813 	KASSERT(*mpp != NULL, ("nfsrv_writedsrpc: NULL mbuf chain"));
6814 	drpc = NULL;
6815 	*failposp = -1;
6816 	if (mirrorcnt > 1 || stripecnt > 1) {
6817 		/* Set j to the upper bound of the # of DSs to read. */
6818 		if (stripecnt > 1)
6819 			j = (len + len - 1) / stripesiz + 1;
6820 		else
6821 			j = 1;
6822 		j *= mirrorcnt;
6823 		tdrpc = drpc = malloc(sizeof(*drpc) * j, M_TEMP, M_WAITOK);
6824 	}
6825 
6826 	/* Calculate offset in mbuf chain that data starts. */
6827 	offs = cp - mtod(*mpp, char *);
6828 	/* For each stripe, write to all the mirrors. */
6829 	for (j = 0; ; j++) {
6830 		if (stripecnt > 1) {
6831 			k = (off / stripesiz) % (uint64_t)stripecnt;
6832 			scnt = stripesiz - (off % stripesiz);
6833 			l = ((uint64_t)len < scnt) ? len : (int)scnt;
6834 		} else {
6835 			k = 0;
6836 			l = len;
6837 		}
6838 		if (j == 0)
6839 			o = k;		/* Save first stripe# for later. */
6840 		tfhp = fhp + k;
6841 		tnmp = nmp + k;
6842 		NFSD_DEBUG(4, "nfsrv_writedsrpc: mcopy offs=%d k=%d "
6843 		    "l=%d\n", offs, k, l);
6844 
6845 		/*
6846 		 * Do the write RPC for every DS, using a separate kernel
6847 		 * process for every DS, except the last one.
6848 		 */
6849 		error = 0;
6850 		n = mirrorcnt;
6851 		if (l == len)
6852 			n--;
6853 		for (i = 0; i < n; i++, tdrpc++) {
6854 			tdrpc->done = 0;
6855 			NFSBCOPY(tfhp, &tdrpc->fh, sizeof(*tfhp));
6856 			tdrpc->off = off;
6857 			tdrpc->len = l;
6858 			tdrpc->nmp = *tnmp;
6859 			tdrpc->cred = cred;
6860 			tdrpc->p = p;
6861 			tdrpc->inprog = 0;
6862 			tdrpc->err = 0;
6863 			tdrpc->m = m_copym(*mpp, offs, NFSM_RNDUP(l),
6864 			    M_WAITOK);
6865 			ret = EIO;
6866 			if (nfs_pnfsiothreads != 0) {
6867 				ret = nfs_pnfsio(start_writedsdorpc, tdrpc);
6868 				NFSD_DEBUG(4, "nfsrv_writedsrpc: "
6869 				    "nfs_pnfsio=%d\n", ret);
6870 			}
6871 			if (ret != 0) {
6872 				ret = nfsrv_writedsdorpc(*tnmp, tfhp, off, l,
6873 				    NULL, tdrpc->m, cred, p);
6874 				if (nfsds_failerr(ret) && *failposp == -1)
6875 					*failposp = k;
6876 				else if (error == 0 && ret != 0)
6877 					tdrpc->err = ret;
6878 				tdrpc->inprog = 0;
6879 				tdrpc->done = 1;
6880 			}
6881 			tnmp += stripecnt;
6882 			tfhp += stripecnt;
6883 		}
6884 		if (l == len)
6885 			break;
6886 		offs += l;
6887 		off += l;
6888 		len -= l;
6889 	}
6890 	m = m_copym(*mpp, offs, NFSM_RNDUP(l), M_WAITOK);
6891 	ret = nfsrv_writedsdorpc(*tnmp, tfhp, off, l, &na, m, cred, p);
6892 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
6893 		*failposp = k;
6894 	else if (error == 0 && ret != 0)
6895 		error = ret;
6896 	if (error == 0)
6897 		error = nfsrv_setextattr(vp, &na, p);
6898 	NFSD_DEBUG(4, "nfsrv_writedsrpc: aft setextat=%d\n", error);
6899 	tdrpc = drpc;
6900 	timo = hz / 50;		/* Wait for 20msec. */
6901 	if (timo < 1)
6902 		timo = 1;
6903 	k = o;
6904 	for (i = 0; i < j * mirrorcnt - 1; i++, tdrpc++) {
6905 		/* Wait for RPCs on separate threads to complete. */
6906 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
6907 			tsleep(&tdrpc->tsk, PVFS, "srvwrds", timo);
6908 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
6909 			*failposp = k;
6910 		else if (error == 0 && tdrpc->err != 0)
6911 			error = tdrpc->err;
6912 		k = (k + 1) % stripecnt;
6913 	}
6914 	free(drpc, M_TEMP);
6915 	return (error);
6916 }
6917 
6918 #ifdef notnow
6919 /*
6920  * Do a allocate RPC on a DS data file, using this structure for the arguments,
6921  * so that this function can be executed by a separate kernel process.
6922  */
6923 struct nfsrvallocatedsdorpc {
6924 	int			done;
6925 	int			inprog;
6926 	struct task		tsk;
6927 	fhandle_t		fh;
6928 	off_t			off;
6929 	off_t			len;
6930 	struct nfsmount		*nmp;
6931 	struct ucred		*cred;
6932 	NFSPROC_T		*p;
6933 	int			err;
6934 };
6935 
6936 static int
nfsrv_allocatedsdorpc(struct nfsmount * nmp,fhandle_t * fhp,off_t off,off_t len,struct nfsvattr * nap,struct ucred * cred,NFSPROC_T * p)6937 nfsrv_allocatedsdorpc(struct nfsmount *nmp, fhandle_t *fhp, off_t off,
6938     off_t len, struct nfsvattr *nap, struct ucred *cred, NFSPROC_T *p)
6939 {
6940 	uint32_t *tl;
6941 	struct nfsrv_descript *nd;
6942 	nfsattrbit_t attrbits;
6943 	nfsv4stateid_t st;
6944 	int error;
6945 
6946 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
6947 	nfscl_reqstart(nd, NFSPROC_ALLOCATE, nmp, (u_int8_t *)fhp,
6948 	    sizeof(fhandle_t), NULL, NULL, 0, 0, cred);
6949 
6950 	/*
6951 	 * Use a stateid where other is an alternating 01010 pattern and
6952 	 * seqid is 0xffffffff.  This value is not defined as special by
6953 	 * the RFC and is used by the FreeBSD NFS server to indicate an
6954 	 * MDS->DS proxy operation.
6955 	 */
6956 	st.other[0] = 0x55555555;
6957 	st.other[1] = 0x55555555;
6958 	st.other[2] = 0x55555555;
6959 	st.seqid = 0xffffffff;
6960 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
6961 	NFSM_BUILD(tl, uint32_t *, 2 * NFSX_HYPER + NFSX_UNSIGNED);
6962 	txdr_hyper(off, tl); tl += 2;
6963 	txdr_hyper(len, tl); tl += 2;
6964 	NFSD_DEBUG(4, "nfsrv_allocatedsdorpc: len=%jd\n", (intmax_t)len);
6965 
6966 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
6967 	NFSGETATTR_ATTRBIT(&attrbits);
6968 	nfsrv_putattrbit(nd, &attrbits);
6969 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p,
6970 	    cred, NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
6971 	if (error != 0) {
6972 		free(nd, M_TEMP);
6973 		return (error);
6974 	}
6975 	NFSD_DEBUG(4, "nfsrv_allocatedsdorpc: aft allocaterpc=%d\n",
6976 	    nd->nd_repstat);
6977 	if (nd->nd_repstat == 0) {
6978 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
6979 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
6980 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL,
6981 		    NULL, NULL);
6982 	} else
6983 		error = nd->nd_repstat;
6984 	NFSD_DEBUG(4, "nfsrv_allocatedsdorpc: aft loadattr=%d\n", error);
6985 nfsmout:
6986 	m_freem(nd->nd_mrep);
6987 	free(nd, M_TEMP);
6988 	NFSD_DEBUG(4, "nfsrv_allocatedsdorpc error=%d\n", error);
6989 	return (error);
6990 }
6991 
6992 /*
6993  * Start up the thread that will execute nfsrv_allocatedsdorpc().
6994  */
6995 static void
start_allocatedsdorpc(void * arg,int pending)6996 start_allocatedsdorpc(void *arg, int pending)
6997 {
6998 	struct nfsrvallocatedsdorpc *drpc;
6999 
7000 	drpc = (struct nfsrvallocatedsdorpc *)arg;
7001 	drpc->err = nfsrv_allocatedsdorpc(drpc->nmp, &drpc->fh, drpc->off,
7002 	    drpc->len, NULL, drpc->cred, drpc->p);
7003 	drpc->done = 1;
7004 	NFSD_DEBUG(4, "start_allocatedsdorpc: err=%d\n", drpc->err);
7005 }
7006 
7007 static int
nfsrv_allocatedsrpc(fhandle_t * fhp,off_t off,off_t len,struct ucred * cred,NFSPROC_T * p,struct vnode * vp,struct nfsmount ** nmpp,int mirrorcnt,int * failposp)7008 nfsrv_allocatedsrpc(fhandle_t *fhp, off_t off, off_t len, struct ucred *cred,
7009     NFSPROC_T *p, struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
7010     int *failposp)
7011 {
7012 	struct nfsrvallocatedsdorpc *drpc, *tdrpc = NULL;
7013 	struct nfsvattr na;
7014 	int error, i, ret, timo;
7015 
7016 	NFSD_DEBUG(4, "in nfsrv_allocatedsrpc\n");
7017 	drpc = NULL;
7018 	if (mirrorcnt > 1)
7019 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
7020 		    M_WAITOK);
7021 
7022 	/*
7023 	 * Do the allocate RPC for every DS, using a separate kernel process
7024 	 * for every DS except the last one.
7025 	 */
7026 	error = 0;
7027 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
7028 		tdrpc->done = 0;
7029 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
7030 		tdrpc->off = off;
7031 		tdrpc->len = len;
7032 		tdrpc->nmp = *nmpp;
7033 		tdrpc->cred = cred;
7034 		tdrpc->p = p;
7035 		tdrpc->inprog = 0;
7036 		tdrpc->err = 0;
7037 		ret = EIO;
7038 		if (nfs_pnfsiothreads != 0) {
7039 			ret = nfs_pnfsio(start_allocatedsdorpc, tdrpc);
7040 			NFSD_DEBUG(4, "nfsrv_allocatedsrpc: nfs_pnfsio=%d\n",
7041 			    ret);
7042 		}
7043 		if (ret != 0) {
7044 			ret = nfsrv_allocatedsdorpc(*nmpp, fhp, off, len, NULL,
7045 			    cred, p);
7046 			if (nfsds_failerr(ret) && *failposp == -1)
7047 				*failposp = i;
7048 			else if (error == 0 && ret != 0)
7049 				error = ret;
7050 		}
7051 		nmpp++;
7052 		fhp++;
7053 	}
7054 	ret = nfsrv_allocatedsdorpc(*nmpp, fhp, off, len, &na, cred, p);
7055 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
7056 		*failposp = mirrorcnt - 1;
7057 	else if (error == 0 && ret != 0)
7058 		error = ret;
7059 	if (error == 0)
7060 		error = nfsrv_setextattr(vp, &na, p);
7061 	NFSD_DEBUG(4, "nfsrv_allocatedsrpc: aft setextat=%d\n", error);
7062 	tdrpc = drpc;
7063 	timo = hz / 50;		/* Wait for 20msec. */
7064 	if (timo < 1)
7065 		timo = 1;
7066 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
7067 		/* Wait for RPCs on separate threads to complete. */
7068 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
7069 			tsleep(&tdrpc->tsk, PVFS, "srvalds", timo);
7070 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
7071 			*failposp = i;
7072 		else if (error == 0 && tdrpc->err != 0)
7073 			error = tdrpc->err;
7074 	}
7075 	free(drpc, M_TEMP);
7076 	return (error);
7077 }
7078 
7079 /*
7080  * Do a deallocate RPC on a DS data file, using this structure for the
7081  * arguments, so that this function can be executed by a separate kernel
7082  * process.
7083  */
7084 struct nfsrvdeallocatedsdorpc {
7085 	int			done;
7086 	int			inprog;
7087 	struct task		tsk;
7088 	fhandle_t		fh;
7089 	off_t			off;
7090 	off_t			len;
7091 	struct nfsmount		*nmp;
7092 	struct ucred		*cred;
7093 	NFSPROC_T		*p;
7094 	int			err;
7095 };
7096 
7097 static int
nfsrv_deallocatedsdorpc(struct nfsmount * nmp,fhandle_t * fhp,off_t off,off_t len,struct nfsvattr * nap,struct ucred * cred,NFSPROC_T * p)7098 nfsrv_deallocatedsdorpc(struct nfsmount *nmp, fhandle_t *fhp, off_t off,
7099     off_t len, struct nfsvattr *nap, struct ucred *cred, NFSPROC_T *p)
7100 {
7101 	uint32_t *tl;
7102 	struct nfsrv_descript *nd;
7103 	nfsattrbit_t attrbits;
7104 	nfsv4stateid_t st;
7105 	int error;
7106 
7107 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
7108 	nfscl_reqstart(nd, NFSPROC_DEALLOCATE, nmp, (u_int8_t *)fhp,
7109 	    sizeof(fhandle_t), NULL, NULL, 0, 0, cred);
7110 
7111 	/*
7112 	 * Use a stateid where other is an alternating 01010 pattern and
7113 	 * seqid is 0xffffffff.  This value is not defined as special by
7114 	 * the RFC and is used by the FreeBSD NFS server to indicate an
7115 	 * MDS->DS proxy operation.
7116 	 */
7117 	st.other[0] = 0x55555555;
7118 	st.other[1] = 0x55555555;
7119 	st.other[2] = 0x55555555;
7120 	st.seqid = 0xffffffff;
7121 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
7122 	NFSM_BUILD(tl, uint32_t *, 2 * NFSX_HYPER + NFSX_UNSIGNED);
7123 	txdr_hyper(off, tl); tl += 2;
7124 	txdr_hyper(len, tl); tl += 2;
7125 	NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc: len=%jd\n", (intmax_t)len);
7126 
7127 	/* Do a Getattr for the attributes that change upon writing. */
7128 	NFSZERO_ATTRBIT(&attrbits);
7129 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
7130 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
7131 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
7132 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
7133 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
7134 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
7135 	nfsrv_putattrbit(nd, &attrbits);
7136 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p,
7137 	    cred, NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
7138 	if (error != 0) {
7139 		free(nd, M_TEMP);
7140 		return (error);
7141 	}
7142 	NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc: aft deallocaterpc=%d\n",
7143 	    nd->nd_repstat);
7144 	/* Get rid of weak cache consistency data for now. */
7145 	if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
7146 	    (ND_NFSV4 | ND_V4WCCATTR)) {
7147 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
7148 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL,
7149 		    NULL, NULL);
7150 		NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc: wcc attr=%d\n", error);
7151 		if (error != 0)
7152 			goto nfsmout;
7153 		/*
7154 		 * Get rid of Op# and status for next op.
7155 		 */
7156 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
7157 		if (*++tl != 0)
7158 			nd->nd_flag |= ND_NOMOREDATA;
7159 	}
7160 	if (nd->nd_repstat == 0) {
7161 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
7162 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
7163 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL,
7164 		    NULL, NULL);
7165 	} else
7166 		error = nd->nd_repstat;
7167 	NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc: aft loadattr=%d\n", error);
7168 nfsmout:
7169 	m_freem(nd->nd_mrep);
7170 	free(nd, M_TEMP);
7171 	NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc error=%d\n", error);
7172 	return (error);
7173 }
7174 
7175 /*
7176  * Start up the thread that will execute nfsrv_deallocatedsdorpc().
7177  */
7178 static void
start_deallocatedsdorpc(void * arg,int pending)7179 start_deallocatedsdorpc(void *arg, int pending)
7180 {
7181 	struct nfsrvdeallocatedsdorpc *drpc;
7182 
7183 	drpc = (struct nfsrvdeallocatedsdorpc *)arg;
7184 	drpc->err = nfsrv_deallocatedsdorpc(drpc->nmp, &drpc->fh, drpc->off,
7185 	    drpc->len, NULL, drpc->cred, drpc->p);
7186 	drpc->done = 1;
7187 	NFSD_DEBUG(4, "start_deallocatedsdorpc: err=%d\n", drpc->err);
7188 }
7189 
7190 static int
nfsrv_deallocatedsrpc(fhandle_t * fhp,off_t off,off_t len,struct ucred * cred,NFSPROC_T * p,struct vnode * vp,struct nfsmount ** nmpp,int mirrorcnt,int * failposp)7191 nfsrv_deallocatedsrpc(fhandle_t *fhp, off_t off, off_t len, struct ucred *cred,
7192     NFSPROC_T *p, struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
7193     int *failposp)
7194 {
7195 	struct nfsrvdeallocatedsdorpc *drpc, *tdrpc = NULL;
7196 	struct nfsvattr na;
7197 	int error, i, ret, timo;
7198 
7199 	NFSD_DEBUG(4, "in nfsrv_deallocatedsrpc\n");
7200 	drpc = NULL;
7201 	if (mirrorcnt > 1)
7202 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
7203 		    M_WAITOK);
7204 
7205 	/*
7206 	 * Do the deallocate RPC for every DS, using a separate kernel process
7207 	 * for every DS except the last one.
7208 	 */
7209 	error = 0;
7210 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
7211 		tdrpc->done = 0;
7212 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
7213 		tdrpc->off = off;
7214 		tdrpc->len = len;
7215 		tdrpc->nmp = *nmpp;
7216 		tdrpc->cred = cred;
7217 		tdrpc->p = p;
7218 		tdrpc->inprog = 0;
7219 		tdrpc->err = 0;
7220 		ret = EIO;
7221 		if (nfs_pnfsiothreads != 0) {
7222 			ret = nfs_pnfsio(start_deallocatedsdorpc, tdrpc);
7223 			NFSD_DEBUG(4, "nfsrv_deallocatedsrpc: nfs_pnfsio=%d\n",
7224 			    ret);
7225 		}
7226 		if (ret != 0) {
7227 			ret = nfsrv_deallocatedsdorpc(*nmpp, fhp, off, len,
7228 			    NULL, cred, p);
7229 			if (nfsds_failerr(ret) && *failposp == -1)
7230 				*failposp = i;
7231 			else if (error == 0 && ret != 0)
7232 				error = ret;
7233 		}
7234 		nmpp++;
7235 		fhp++;
7236 	}
7237 	ret = nfsrv_deallocatedsdorpc(*nmpp, fhp, off, len, &na, cred, p);
7238 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
7239 		*failposp = mirrorcnt - 1;
7240 	else if (error == 0 && ret != 0)
7241 		error = ret;
7242 	if (error == 0)
7243 		error = nfsrv_setextattr(vp, &na, p);
7244 	NFSD_DEBUG(4, "nfsrv_deallocatedsrpc: aft setextat=%d\n", error);
7245 	tdrpc = drpc;
7246 	timo = hz / 50;		/* Wait for 20msec. */
7247 	if (timo < 1)
7248 		timo = 1;
7249 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
7250 		/* Wait for RPCs on separate threads to complete. */
7251 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
7252 			tsleep(&tdrpc->tsk, PVFS, "srvalds", timo);
7253 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
7254 			*failposp = i;
7255 		else if (error == 0 && tdrpc->err != 0)
7256 			error = tdrpc->err;
7257 	}
7258 	free(drpc, M_TEMP);
7259 	return (error);
7260 }
7261 #endif
7262 
7263 static int
nfsrv_setattrdsdorpc(fhandle_t * fhp,struct vnode * vp,struct ucred * cred,NFSPROC_T * p,struct nfsmount * nmp,struct nfsvattr * nap,struct nfsvattr * dsnap)7264 nfsrv_setattrdsdorpc(fhandle_t *fhp, struct vnode *vp, struct ucred *cred,
7265     NFSPROC_T *p, struct nfsmount *nmp, struct nfsvattr *nap,
7266     struct nfsvattr *dsnap)
7267 {
7268 	uint32_t *tl;
7269 	struct nfsrv_descript *nd;
7270 	nfsv4stateid_t st;
7271 	nfsattrbit_t attrbits;
7272 	int error;
7273 
7274 	NFSD_DEBUG(4, "in nfsrv_setattrdsdorpc\n");
7275 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
7276 	/*
7277 	 * Use a stateid where other is an alternating 01010 pattern and
7278 	 * seqid is 0xffffffff.  This value is not defined as special by
7279 	 * the RFC and is used by the FreeBSD NFS server to indicate an
7280 	 * MDS->DS proxy operation.
7281 	 */
7282 	st.other[0] = 0x55555555;
7283 	st.other[1] = 0x55555555;
7284 	st.other[2] = 0x55555555;
7285 	st.seqid = 0xffffffff;
7286 	nfscl_reqstart(nd, NFSPROC_SETATTR, nmp, (uint8_t *)fhp, sizeof(*fhp),
7287 	    NULL, NULL, 0, 0, cred);
7288 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
7289 	nfscl_fillsattr(nd, &nap->na_vattr, vp, NFSSATTR_FULL, 0);
7290 
7291 	/* Do a Getattr for the attributes that change due to writing. */
7292 	NFSZERO_ATTRBIT(&attrbits);
7293 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
7294 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
7295 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
7296 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
7297 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
7298 	NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
7299 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
7300 	(void) nfsrv_putattrbit(nd, &attrbits);
7301 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
7302 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
7303 	if (error != 0) {
7304 		free(nd, M_TEMP);
7305 		return (error);
7306 	}
7307 	NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: aft setattrrpc=%d\n",
7308 	    nd->nd_repstat);
7309 	/* Get rid of weak cache consistency data for now. */
7310 	if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
7311 	    (ND_NFSV4 | ND_V4WCCATTR)) {
7312 		error = nfsv4_loadattr(nd, NULL, dsnap, NULL, NULL, 0, NULL,
7313 		    NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL,
7314 		    NULL, NULL, NULL);
7315 		NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: wcc attr=%d\n", error);
7316 		if (error != 0)
7317 			goto nfsmout;
7318 		/*
7319 		 * Get rid of Op# and status for next op.
7320 		 */
7321 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
7322 		if (*++tl != 0)
7323 			nd->nd_flag |= ND_NOMOREDATA;
7324 	}
7325 	error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
7326 	if (error != 0)
7327 		goto nfsmout;
7328 	if (nd->nd_repstat != 0)
7329 		error = nd->nd_repstat;
7330 	/*
7331 	 * Get the Change, Size, Access Time and Modify Time attributes and set
7332 	 * on the Metadata file, so its attributes will be what the file's
7333 	 * would be if it had been written.
7334 	 */
7335 	if (error == 0) {
7336 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
7337 		error = nfsv4_loadattr(nd, NULL, dsnap, NULL, NULL, 0, NULL,
7338 		    NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL,
7339 		    NULL, NULL, NULL);
7340 	}
7341 	NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: aft setattr loadattr=%d\n", error);
7342 nfsmout:
7343 	m_freem(nd->nd_mrep);
7344 	free(nd, M_TEMP);
7345 	NFSD_DEBUG(4, "nfsrv_setattrdsdorpc error=%d\n", error);
7346 	return (error);
7347 }
7348 
7349 struct nfsrvsetattrdsdorpc {
7350 	int			done;
7351 	int			inprog;
7352 	struct task		tsk;
7353 	fhandle_t		fh;
7354 	struct nfsmount		*nmp;
7355 	struct vnode		*vp;
7356 	struct ucred		*cred;
7357 	NFSPROC_T		*p;
7358 	struct nfsvattr		na;
7359 	struct nfsvattr		dsna;
7360 	int			err;
7361 };
7362 
7363 /*
7364  * Start up the thread that will execute nfsrv_setattrdsdorpc().
7365  */
7366 static void
start_setattrdsdorpc(void * arg,int pending)7367 start_setattrdsdorpc(void *arg, int pending)
7368 {
7369 	struct nfsrvsetattrdsdorpc *drpc;
7370 
7371 	drpc = (struct nfsrvsetattrdsdorpc *)arg;
7372 	drpc->err = nfsrv_setattrdsdorpc(&drpc->fh, drpc->vp,  drpc->cred,
7373 	    drpc->p, drpc->nmp, &drpc->na, &drpc->dsna);
7374 	drpc->done = 1;
7375 }
7376 
7377 static int
nfsrv_setattrdsrpc(fhandle_t * fhp,struct vnode * vp,struct ucred * cred,NFSPROC_T * p,struct nfsmount ** nmp,int mirrorcnt,int stripecnt,struct nfsvattr * nap,int * failposp)7378 nfsrv_setattrdsrpc(fhandle_t *fhp, struct vnode *vp, struct ucred *cred,
7379     NFSPROC_T *p, struct nfsmount **nmp, int mirrorcnt, int stripecnt,
7380     struct nfsvattr *nap, int *failposp)
7381 {
7382 	struct nfsrvsetattrdsdorpc *drpc, *tdrpc = NULL;  /* Shut up gcc. */
7383 	fhandle_t *tfhp;
7384 	struct nfsmount **tnmp;
7385 	struct nfsvattr na;
7386 	int error, i, j, ret, timo;
7387 
7388 	NFSD_DEBUG(4, "in nfsrv_setattrdsrpc\n");
7389 	drpc = NULL;
7390 	*failposp = -1;
7391 	error = 0;
7392 	if (mirrorcnt > 1 || stripecnt > 1)
7393 		tdrpc = drpc = malloc(sizeof(*drpc) * stripecnt * mirrorcnt,
7394 		    M_TEMP, M_WAITOK);
7395 
7396 	/* For each stripe, write to all the mirrors. */
7397 	tfhp = fhp;
7398 	tnmp = nmp;
7399 	for (i = 0; i < stripecnt * mirrorcnt - 1; i++, tdrpc++, tfhp++,
7400 	    tnmp++) {
7401 		j = i / stripecnt;
7402 		NFSD_DEBUG(4, "nfsrv_setattrdsrpc: stripe=%d mirror=%d\n",
7403 		    i, j);
7404 		tdrpc->done = 0;
7405 		NFSBCOPY(nap, &tdrpc->na, sizeof(*nap));
7406 		NFSBCOPY(tfhp, &tdrpc->fh, sizeof(*tfhp));
7407 		tdrpc->vp = vp;
7408 		tdrpc->nmp = *tnmp;
7409 		tdrpc->cred = cred;
7410 		tdrpc->p = p;
7411 		tdrpc->inprog = 0;
7412 		tdrpc->err = 0;
7413 		ret = EIO;
7414 		if (nfs_pnfsiothreads != 0) {
7415 			ret = nfs_pnfsio(start_setattrdsdorpc, tdrpc);
7416 			NFSD_DEBUG(4, "nfsrv_setattrdsrpc: "
7417 			    "nfs_pnfsio=%d\n", ret);
7418 		}
7419 		if (ret != 0) {
7420 			ret = nfsrv_setattrdsdorpc(tfhp, vp, cred, p,
7421 			    *tnmp, &tdrpc->na, &tdrpc->dsna);
7422 			if (nfsds_failerr(ret) && *failposp == -1)
7423 				*failposp = i;
7424 			else if (error == 0 && ret != 0)
7425 				tdrpc->err = ret;
7426 			tdrpc->inprog = 0;
7427 			tdrpc->done = 1;
7428 		}
7429 	}
7430 	ret = nfsrv_setattrdsdorpc(tfhp, vp, cred, p, *tnmp, nap, &na);
7431 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
7432 		*failposp = i;
7433 	else if (error == 0 && ret != 0)
7434 		error = ret;
7435 	tdrpc = drpc;
7436 	timo = hz / 50;		/* Wait for 20msec. */
7437 	if (timo < 1)
7438 		timo = 1;
7439 	for (i = 0; i < stripecnt * mirrorcnt - 1; i++, tdrpc++) {
7440 		/* Wait for RPCs on separate threads to complete. */
7441 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
7442 			tsleep(&tdrpc->tsk, PVFS, "srvwrds", timo);
7443 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
7444 			*failposp = i;
7445 		else if (error == 0 && tdrpc->err != 0)
7446 			error = tdrpc->err;
7447 	}
7448 
7449 	/* Find the reply attribute with the largest size and set that one. */
7450 	if (error == 0 && (mirrorcnt > 1 || stripecnt > 1)) {
7451 		tdrpc = drpc;
7452 		for (i = 0; i < stripecnt * mirrorcnt - 1; i++, tdrpc++) {
7453 			if (tdrpc->dsna.na_size > na.na_size)
7454 				NFSBCOPY(&tdrpc->dsna, &na, sizeof(*nap));
7455 		}
7456 	}
7457 	if (error == 0)
7458 		error = nfsrv_setextattr(vp, &na, p);
7459 	free(drpc, M_TEMP);
7460 	return (error);
7461 }
7462 
7463 #ifdef notnow
7464 /*
7465  * Do a Setattr of an NFSv4 ACL on the DS file.
7466  */
7467 static int
nfsrv_setacldsdorpc(fhandle_t * fhp,struct ucred * cred,NFSPROC_T * p,struct vnode * vp,struct nfsmount * nmp,struct acl * aclp)7468 nfsrv_setacldsdorpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
7469     struct vnode *vp, struct nfsmount *nmp, struct acl *aclp)
7470 {
7471 	struct nfsrv_descript *nd;
7472 	nfsv4stateid_t st;
7473 	nfsattrbit_t attrbits;
7474 	int error;
7475 
7476 	NFSD_DEBUG(4, "in nfsrv_setacldsdorpc\n");
7477 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
7478 	/*
7479 	 * Use a stateid where other is an alternating 01010 pattern and
7480 	 * seqid is 0xffffffff.  This value is not defined as special by
7481 	 * the RFC and is used by the FreeBSD NFS server to indicate an
7482 	 * MDS->DS proxy operation.
7483 	 */
7484 	st.other[0] = 0x55555555;
7485 	st.other[1] = 0x55555555;
7486 	st.other[2] = 0x55555555;
7487 	st.seqid = 0xffffffff;
7488 	nfscl_reqstart(nd, NFSPROC_SETACL, nmp, (u_int8_t *)fhp, sizeof(*fhp),
7489 	    NULL, NULL, 0, 0, cred);
7490 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
7491 	NFSZERO_ATTRBIT(&attrbits);
7492 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_ACL);
7493 	/*
7494 	 * The "vp" argument to nfsv4_fillattr() is only used for vnode_type(),
7495 	 * so passing in the metadata "vp" will be ok, since it is of
7496 	 * the same type (VREG).
7497 	 */
7498 	nfsv4_fillattr(nd, NULL, vp, aclp, NULL, NULL, 0, &attrbits, NULL,
7499 	    NULL, 0, 0, 0, 0, 0, NULL, false, false, false, 0, NULL, false);
7500 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
7501 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
7502 	if (error != 0) {
7503 		free(nd, M_TEMP);
7504 		return (error);
7505 	}
7506 	NFSD_DEBUG(4, "nfsrv_setacldsdorpc: aft setaclrpc=%d\n",
7507 	    nd->nd_repstat);
7508 	error = nd->nd_repstat;
7509 	m_freem(nd->nd_mrep);
7510 	free(nd, M_TEMP);
7511 	return (error);
7512 }
7513 
7514 struct nfsrvsetacldsdorpc {
7515 	int			done;
7516 	int			inprog;
7517 	struct task		tsk;
7518 	fhandle_t		fh;
7519 	struct nfsmount		*nmp;
7520 	struct vnode		*vp;
7521 	struct ucred		*cred;
7522 	NFSPROC_T		*p;
7523 	struct acl		*aclp;
7524 	int			err;
7525 };
7526 
7527 /*
7528  * Start up the thread that will execute nfsrv_setacldsdorpc().
7529  */
7530 static void
start_setacldsdorpc(void * arg,int pending)7531 start_setacldsdorpc(void *arg, int pending)
7532 {
7533 	struct nfsrvsetacldsdorpc *drpc;
7534 
7535 	drpc = (struct nfsrvsetacldsdorpc *)arg;
7536 	drpc->err = nfsrv_setacldsdorpc(&drpc->fh, drpc->cred, drpc->p,
7537 	    drpc->vp, drpc->nmp, drpc->aclp);
7538 	drpc->done = 1;
7539 }
7540 
7541 static int
nfsrv_setacldsrpc(fhandle_t * fhp,struct ucred * cred,NFSPROC_T * p,struct vnode * vp,struct nfsmount ** nmpp,int mirrorcnt,struct acl * aclp,int * failposp)7542 nfsrv_setacldsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
7543     struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt, struct acl *aclp,
7544     int *failposp)
7545 {
7546 	struct nfsrvsetacldsdorpc *drpc, *tdrpc = NULL;
7547 	int error, i, ret, timo;
7548 
7549 	NFSD_DEBUG(4, "in nfsrv_setacldsrpc\n");
7550 	drpc = NULL;
7551 	if (mirrorcnt > 1)
7552 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
7553 		    M_WAITOK);
7554 
7555 	/*
7556 	 * Do the setattr RPC for every DS, using a separate kernel process
7557 	 * for every DS except the last one.
7558 	 */
7559 	error = 0;
7560 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
7561 		tdrpc->done = 0;
7562 		tdrpc->inprog = 0;
7563 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
7564 		tdrpc->nmp = *nmpp;
7565 		tdrpc->vp = vp;
7566 		tdrpc->cred = cred;
7567 		tdrpc->p = p;
7568 		tdrpc->aclp = aclp;
7569 		tdrpc->err = 0;
7570 		ret = EIO;
7571 		if (nfs_pnfsiothreads != 0) {
7572 			ret = nfs_pnfsio(start_setacldsdorpc, tdrpc);
7573 			NFSD_DEBUG(4, "nfsrv_setacldsrpc: nfs_pnfsio=%d\n",
7574 			    ret);
7575 		}
7576 		if (ret != 0) {
7577 			ret = nfsrv_setacldsdorpc(fhp, cred, p, vp, *nmpp,
7578 			    aclp);
7579 			if (nfsds_failerr(ret) && *failposp == -1)
7580 				*failposp = i;
7581 			else if (error == 0 && ret != 0)
7582 				error = ret;
7583 		}
7584 		nmpp++;
7585 		fhp++;
7586 	}
7587 	ret = nfsrv_setacldsdorpc(fhp, cred, p, vp, *nmpp, aclp);
7588 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
7589 		*failposp = mirrorcnt - 1;
7590 	else if (error == 0 && ret != 0)
7591 		error = ret;
7592 	NFSD_DEBUG(4, "nfsrv_setacldsrpc: aft setextat=%d\n", error);
7593 	tdrpc = drpc;
7594 	timo = hz / 50;		/* Wait for 20msec. */
7595 	if (timo < 1)
7596 		timo = 1;
7597 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
7598 		/* Wait for RPCs on separate threads to complete. */
7599 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
7600 			tsleep(&tdrpc->tsk, PVFS, "srvacds", timo);
7601 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
7602 			*failposp = i;
7603 		else if (error == 0 && tdrpc->err != 0)
7604 			error = tdrpc->err;
7605 	}
7606 	free(drpc, M_TEMP);
7607 	return (error);
7608 }
7609 #endif
7610 
7611 struct nfsrvgetattrdsdorpc {
7612 	int			done;
7613 	int			inprog;
7614 	struct task		tsk;
7615 	fhandle_t		fh;
7616 	struct vnode		*vp;
7617 	struct nfsvattr		na;
7618 	struct nfsmount		*nmp;
7619 	struct ucred		*cred;
7620 	NFSPROC_T		*p;
7621 	int			err;
7622 };
7623 
7624 /*
7625  * Start up the thread that will execute nfsrv_getattrdsdorpc().
7626  */
7627 static void
start_getattrdsdorpc(void * arg,int pending)7628 start_getattrdsdorpc(void *arg, int pending)
7629 {
7630 	struct nfsrvgetattrdsdorpc *drpc;
7631 
7632 	drpc = (struct nfsrvgetattrdsdorpc *)arg;
7633 	drpc->err = nfsrv_getattrdsdorpc(&drpc->fh, drpc->vp, drpc->cred,
7634 	    drpc->p, drpc->nmp, &drpc->na);
7635 	drpc->done = 1;
7636 	NFSD_DEBUG(4, "start_getattrdsdorpc: err=%d\n", drpc->err);
7637 }
7638 
7639 /*
7640  * For a striped configuration, a getattr RPC must be done on all stripes,
7641  * since there is no way of knowing which DS currently stores the last
7642  * bytes of the file.
7643  */
7644 static int
nfsrv_getattrdsrpc(fhandle_t * fhp,struct vnode * vp,struct ucred * cred,NFSPROC_T * p,struct nfsmount ** nmp,int stripecnt,struct nfsvattr * nap,int * failposp)7645 nfsrv_getattrdsrpc(fhandle_t *fhp, struct vnode *vp, struct ucred *cred,
7646     NFSPROC_T *p, struct nfsmount **nmp, int stripecnt, struct nfsvattr *nap,
7647     int *failposp)
7648 {
7649 	struct nfsrvgetattrdsdorpc *drpc, *tdrpc = NULL;    /* Shut up gcc. */
7650 	fhandle_t *tfhp;
7651 	struct nfsmount **tnmp;
7652 	int error, i, ret, timo;
7653 
7654 	NFSD_DEBUG(4, "in nfsrv_getattrdsrpc\n");
7655 	drpc = NULL;
7656 	*failposp = -1;
7657 	if (stripecnt > 1)
7658 		tdrpc = drpc = malloc(sizeof(*drpc) * stripecnt, M_TEMP,
7659 		    M_WAITOK);
7660 
7661 	/* For each stripe except last one, do a Getattr.. */
7662 	tfhp = fhp;
7663 	tnmp = nmp;
7664 	for (i = 0; i < stripecnt - 1; i++, tdrpc++, tfhp++, tnmp++) {
7665 		NFSD_DEBUG(4, "nfsrv_getattrdsrpc: stripe=%d\n", i);
7666 		error = 0;
7667 		tdrpc->done = 0;
7668 		NFSBCOPY(tfhp, &tdrpc->fh, sizeof(*tfhp));
7669 		tdrpc->nmp = *tnmp;
7670 		tdrpc->vp = vp;
7671 		tdrpc->cred = cred;
7672 		tdrpc->p = p;
7673 		tdrpc->inprog = 0;
7674 		tdrpc->err = 0;
7675 		ret = EIO;
7676 		if (nfs_pnfsiothreads != 0) {
7677 			ret = nfs_pnfsio(start_getattrdsdorpc, tdrpc);
7678 			NFSD_DEBUG(4, "nfsrv_getattrdsrpc: "
7679 			    "nfs_pnfsio=%d\n", ret);
7680 		}
7681 		if (ret != 0) {
7682 			ret = nfsrv_getattrdsdorpc(tfhp, vp, cred, p, *tnmp,
7683 			    &tdrpc->na);
7684 			if (nfsds_failerr(ret) && *failposp == -1)
7685 				*failposp = i;
7686 			else if (error == 0 && ret != 0)
7687 				tdrpc->err = ret;
7688 			tdrpc->inprog = 0;
7689 			tdrpc->done = 1;
7690 		}
7691 	}
7692 	ret = nfsrv_getattrdsdorpc(tfhp, vp, cred, p, *tnmp, nap);
7693 	if (nfsds_failerr(ret) && *failposp == -1)
7694 		*failposp = i;
7695 	if (error == 0 && ret != 0)
7696 		error = ret;
7697 	NFSD_DEBUG(4, "nfsrv_getattrdsrpc: aft stripes=%d\n", error);
7698 	timo = hz / 50;		/* Wait for 20msec. */
7699 	if (timo < 1)
7700 		timo = 1;
7701 	tdrpc = drpc;
7702 	for (i = 0; i < stripecnt - 1; i++, tdrpc++) {
7703 		/* Wait for RPCs on separate threads to complete. */
7704 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
7705 			tsleep(&tdrpc->tsk, PVFS, "srvwrds", timo);
7706 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
7707 			*failposp = i;
7708 		else if (error == 0 && tdrpc->err != 0)
7709 			error = tdrpc->err;
7710 	}
7711 
7712 	/* Find the attribute with the largest size and return that one. */
7713 	if (stripecnt > 1) {
7714 		tdrpc = drpc;
7715 		for (i = 0; i < stripecnt - 1; i++, tdrpc++) {
7716 			if (tdrpc->na.na_size > nap->na_size)
7717 				NFSBCOPY(&tdrpc->na, nap, sizeof(*nap));
7718 		}
7719 	}
7720 	/*
7721 	 * We can only save the updated values in the extended
7722 	 * attribute if the vp is exclusively locked.
7723 	 */
7724 	if (error == 0 && VOP_ISLOCKED(vp) == LK_EXCLUSIVE) {
7725 		error = nfsrv_setextattr(vp, nap, p);
7726 		NFSD_DEBUG(4, "nfsrv_getattrdsrpc: aft setextat=%d\n",
7727 		    error);
7728 	}
7729 
7730 	free(drpc, M_TEMP);
7731 	return (error);
7732 }
7733 
7734 /*
7735  * Getattr call to the DS for the attributes that change due to writing.
7736  */
7737 static int
nfsrv_getattrdsdorpc(fhandle_t * fhp,struct vnode * vp,struct ucred * cred,NFSPROC_T * p,struct nfsmount * nmp,struct nfsvattr * nap)7738 nfsrv_getattrdsdorpc(fhandle_t *fhp, struct vnode *vp, struct ucred *cred,
7739     NFSPROC_T *p, struct nfsmount *nmp, struct nfsvattr *nap)
7740 {
7741 	struct nfsrv_descript *nd;
7742 	int error;
7743 	nfsattrbit_t attrbits;
7744 
7745 	NFSD_DEBUG(4, "in nfsrv_getattrdsdorpc\n");
7746 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
7747 	nfscl_reqstart(nd, NFSPROC_GETATTR, nmp, (u_int8_t *)fhp,
7748 	    sizeof(fhandle_t), NULL, NULL, 0, 0, cred);
7749 	NFSZERO_ATTRBIT(&attrbits);
7750 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
7751 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
7752 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
7753 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
7754 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
7755 	(void) nfsrv_putattrbit(nd, &attrbits);
7756 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
7757 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
7758 	if (error != 0) {
7759 		free(nd, M_TEMP);
7760 		return (error);
7761 	}
7762 	NFSD_DEBUG(4, "nfsrv_getattrdsdorpc: aft getattrrpc=%d\n",
7763 	    nd->nd_repstat);
7764 	if (nd->nd_repstat == 0)
7765 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0,
7766 		    NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL,
7767 		    NULL, NULL, NULL, NULL, NULL);
7768 	else
7769 		error = nd->nd_repstat;
7770 	m_freem(nd->nd_mrep);
7771 	free(nd, M_TEMP);
7772 	NFSD_DEBUG(4, "nfsrv_getattrdsdorpc error=%d\n", error);
7773 	return (error);
7774 }
7775 
7776 #ifdef notnow
7777 /*
7778  * Seek call to a DS.
7779  */
7780 static int
nfsrv_seekdsrpc(fhandle_t * fhp,off_t * offp,int content,bool * eofp,struct ucred * cred,NFSPROC_T * p,struct nfsmount * nmp)7781 nfsrv_seekdsrpc(fhandle_t *fhp, off_t *offp, int content, bool *eofp,
7782     struct ucred *cred, NFSPROC_T *p, struct nfsmount *nmp)
7783 {
7784 	uint32_t *tl;
7785 	struct nfsrv_descript *nd;
7786 	nfsv4stateid_t st;
7787 	int error;
7788 
7789 	NFSD_DEBUG(4, "in nfsrv_seekdsrpc\n");
7790 	/*
7791 	 * Use a stateid where other is an alternating 01010 pattern and
7792 	 * seqid is 0xffffffff.  This value is not defined as special by
7793 	 * the RFC and is used by the FreeBSD NFS server to indicate an
7794 	 * MDS->DS proxy operation.
7795 	 */
7796 	st.other[0] = 0x55555555;
7797 	st.other[1] = 0x55555555;
7798 	st.other[2] = 0x55555555;
7799 	st.seqid = 0xffffffff;
7800 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
7801 	nfscl_reqstart(nd, NFSPROC_SEEKDS, nmp, (u_int8_t *)fhp,
7802 	    sizeof(fhandle_t), NULL, NULL, 0, 0, cred);
7803 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
7804 	NFSM_BUILD(tl, uint32_t *, NFSX_HYPER + NFSX_UNSIGNED);
7805 	txdr_hyper(*offp, tl); tl += 2;
7806 	*tl = txdr_unsigned(content);
7807 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
7808 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
7809 	if (error != 0) {
7810 		free(nd, M_TEMP);
7811 		return (error);
7812 	}
7813 	NFSD_DEBUG(4, "nfsrv_seekdsrpc: aft seekrpc=%d\n", nd->nd_repstat);
7814 	if (nd->nd_repstat == 0) {
7815 		NFSM_DISSECT(tl, uint32_t *, NFSX_UNSIGNED + NFSX_HYPER);
7816 		if (*tl++ == newnfs_true)
7817 			*eofp = true;
7818 		else
7819 			*eofp = false;
7820 		*offp = fxdr_hyper(tl);
7821 	} else
7822 		error = nd->nd_repstat;
7823 nfsmout:
7824 	m_freem(nd->nd_mrep);
7825 	free(nd, M_TEMP);
7826 	NFSD_DEBUG(4, "nfsrv_seekdsrpc error=%d\n", error);
7827 	return (error);
7828 }
7829 #endif
7830 
7831 /*
7832  * Get the device id and file handle for a DS file.
7833  */
7834 int
nfsrv_dsgetdevandfh(struct vnode * vp,NFSPROC_T * p,int * mirrorcntp,uint64_t * stripesizp,int * stripecntp,fhandle_t ** fhpp,char ** devid)7835 nfsrv_dsgetdevandfh(struct vnode *vp, NFSPROC_T *p, int *mirrorcntp,
7836     uint64_t *stripesizp, int *stripecntp, fhandle_t **fhpp, char **devid)
7837 {
7838 	int buflen, error;
7839 	char *buf;
7840 
7841 	buflen = sizeof(struct pnfsdsfile) * NFSDEV_MAXMIRRORS *
7842 	    NFSDEV_MAXSTRIPE;
7843 	buf = malloc(buflen, M_TEMP, M_WAITOK);
7844 	error = nfsrv_dsgetsockmnt(vp, 0, buf, &buflen, mirrorcntp, stripecntp,
7845 	    stripesizp, p, NULL, fhpp, devid, NULL, NULL, NULL, NULL, NULL,
7846 	    NULL);
7847 	free(buf, M_TEMP);
7848 	return (error);
7849 }
7850 
7851 /*
7852  * Do a Lookup against the DS for the filename.
7853  */
7854 static int
nfsrv_pnfslookupds(struct vnode * vp,struct vnode * dvp,struct pnfsdsfile * pf,struct vnode ** nvpp,NFSPROC_T * p)7855 nfsrv_pnfslookupds(struct vnode *vp, struct vnode *dvp, struct pnfsdsfile *pf,
7856     struct vnode **nvpp, NFSPROC_T *p)
7857 {
7858 	struct nameidata named;
7859 	struct ucred *tcred;
7860 	char *bufp;
7861 	u_long *hashp;
7862 	struct vnode *nvp;
7863 	int error;
7864 
7865 	tcred = newnfs_getcred();
7866 	named.ni_cnd.cn_nameiop = LOOKUP;
7867 	named.ni_cnd.cn_lkflags = LK_SHARED | LK_RETRY;
7868 	named.ni_cnd.cn_cred = tcred;
7869 	named.ni_cnd.cn_flags = ISLASTCN | LOCKPARENT | LOCKLEAF;
7870 	nfsvno_setpathbuf(&named, &bufp, &hashp);
7871 	named.ni_cnd.cn_nameptr = bufp;
7872 	named.ni_cnd.cn_namelen = strlen(pf->dsf_filename);
7873 	strlcpy(bufp, pf->dsf_filename, NAME_MAX);
7874 	NFSD_DEBUG(4, "nfsrv_pnfslookupds: filename=%s\n", bufp);
7875 	error = VOP_LOOKUP(dvp, &nvp, &named.ni_cnd);
7876 	NFSD_DEBUG(4, "nfsrv_pnfslookupds: aft LOOKUP=%d\n", error);
7877 	NFSFREECRED(tcred);
7878 	nfsvno_relpathbuf(&named);
7879 	if (error == 0)
7880 		*nvpp = nvp;
7881 	NFSD_DEBUG(4, "eo nfsrv_pnfslookupds=%d\n", error);
7882 	return (error);
7883 }
7884 
7885 /*
7886  * Set the file handle to the correct one.
7887  */
7888 static void
nfsrv_pnfssetfh(struct vnode * vp,struct pnfsdsfile * pf,char ** devid,char * fnamep,struct vnode * nvp,NFSPROC_T * p)7889 nfsrv_pnfssetfh(struct vnode *vp, struct pnfsdsfile *pf, char **devid,
7890     char *fnamep, struct vnode *nvp, NFSPROC_T *p)
7891 {
7892 	struct nfsnode *np;
7893 	int ret = 0;
7894 
7895 	np = VTONFS(nvp);
7896 	NFSBCOPY(np->n_fhp->nfh_fh, &pf->dsf_fh, NFSX_MYFH);
7897 	/*
7898 	 * We can only do a vn_set_extattr() if the vnode is exclusively
7899 	 * locked and vn_start_write() has been done.  If devid != NULL or
7900 	 * fnamep != NULL or the vnode is shared locked, vn_start_write()
7901 	 * may not have been done.
7902 	 * If not done now, it will be done on a future call.
7903 	 */
7904 	if (devid == NULL && fnamep == NULL && NFSVOPISLOCKED(vp) ==
7905 	    LK_EXCLUSIVE)
7906 		ret = vn_extattr_set(vp, IO_NODELOCKED,
7907 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile", sizeof(*pf),
7908 		    (char *)pf, p);
7909 	NFSD_DEBUG(4, "eo nfsrv_pnfssetfh=%d\n", ret);
7910 }
7911 
7912 /*
7913  * Cause RPCs waiting on "nmp" to fail.  This is called for a DS mount point
7914  * when the DS has failed.
7915  */
7916 void
nfsrv_killrpcs(struct nfsmount * nmp)7917 nfsrv_killrpcs(struct nfsmount *nmp)
7918 {
7919 
7920 	/*
7921 	 * Call newnfs_nmcancelreqs() to cause
7922 	 * any RPCs in progress on the mount point to
7923 	 * fail.
7924 	 * This will cause any process waiting for an
7925 	 * RPC to complete while holding a vnode lock
7926 	 * on the mounted-on vnode (such as "df" or
7927 	 * a non-forced "umount") to fail.
7928 	 * This will unlock the mounted-on vnode so
7929 	 * a forced dismount can succeed.
7930 	 * The NFSMNTP_CANCELRPCS flag should be set when this function is
7931 	 * called.
7932 	 */
7933 	newnfs_nmcancelreqs(nmp);
7934 }
7935 
7936 /*
7937  * Sum up the statfs info for each of the DSs, so that the client will
7938  * receive the total for all DSs.
7939  */
7940 static int
nfsrv_pnfsstatfs(struct statfs * sf,struct mount * mp)7941 nfsrv_pnfsstatfs(struct statfs *sf, struct mount *mp)
7942 {
7943 	struct statfs *tsf;
7944 	struct nfsdevice *ds;
7945 	struct vnode **dvpp, **tdvpp, *dvp;
7946 	uint64_t tot;
7947 	int cnt, error = 0, i;
7948 
7949 	if (nfsrv_devidcnt <= 0)
7950 		return (ENXIO);
7951 	dvpp = mallocarray(nfsrv_devidcnt, sizeof(*dvpp), M_TEMP, M_WAITOK);
7952 	tsf = malloc(sizeof(*tsf), M_TEMP, M_WAITOK);
7953 
7954 	/* Get an array of the dvps for the DSs. */
7955 	tdvpp = dvpp;
7956 	i = 0;
7957 	NFSDDSLOCK();
7958 	/* First, search for matches for same file system. */
7959 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
7960 		if (ds->nfsdev_nmp != NULL && ds->nfsdev_mdsisset != 0 &&
7961 		    fsidcmp(&ds->nfsdev_mdsfsid, &mp->mnt_stat.f_fsid) == 0) {
7962 			if (++i > nfsrv_devidcnt)
7963 				break;
7964 			*tdvpp++ = ds->nfsdev_dvp;
7965 		}
7966 	}
7967 	/*
7968 	 * If no matches for same file system, total all servers not assigned
7969 	 * to a file system.
7970 	 */
7971 	if (i == 0) {
7972 		TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
7973 			if (ds->nfsdev_nmp != NULL &&
7974 			    ds->nfsdev_mdsisset == 0) {
7975 				if (++i > nfsrv_devidcnt)
7976 					break;
7977 				*tdvpp++ = ds->nfsdev_dvp;
7978 			}
7979 		}
7980 	}
7981 	NFSDDSUNLOCK();
7982 	cnt = i;
7983 
7984 	/* Do a VFS_STATFS() for each of the DSs and sum them up. */
7985 	tdvpp = dvpp;
7986 	for (i = 0; i < cnt && error == 0; i++) {
7987 		dvp = *tdvpp++;
7988 		error = VFS_STATFS(dvp->v_mount, tsf);
7989 		if (error == 0) {
7990 			if (sf->f_bsize == 0) {
7991 				if (tsf->f_bsize > 0)
7992 					sf->f_bsize = tsf->f_bsize;
7993 				else
7994 					sf->f_bsize = 8192;
7995 			}
7996 			if (tsf->f_blocks > 0) {
7997 				if (sf->f_bsize != tsf->f_bsize) {
7998 					tot = tsf->f_blocks * tsf->f_bsize;
7999 					sf->f_blocks += (tot / sf->f_bsize);
8000 				} else
8001 					sf->f_blocks += tsf->f_blocks;
8002 			}
8003 			if (tsf->f_bfree > 0) {
8004 				if (sf->f_bsize != tsf->f_bsize) {
8005 					tot = tsf->f_bfree * tsf->f_bsize;
8006 					sf->f_bfree += (tot / sf->f_bsize);
8007 				} else
8008 					sf->f_bfree += tsf->f_bfree;
8009 			}
8010 			if (tsf->f_bavail > 0) {
8011 				if (sf->f_bsize != tsf->f_bsize) {
8012 					tot = tsf->f_bavail * tsf->f_bsize;
8013 					sf->f_bavail += (tot / sf->f_bsize);
8014 				} else
8015 					sf->f_bavail += tsf->f_bavail;
8016 			}
8017 		}
8018 	}
8019 	free(tsf, M_TEMP);
8020 	free(dvpp, M_TEMP);
8021 	return (error);
8022 }
8023 
8024 /*
8025  * Set an acl.
8026  */
8027 int
nfsrv_setacl(struct vnode * vp,NFSACL_T * aclp,acl_type_t atype,struct ucred * cred,NFSPROC_T * p)8028 nfsrv_setacl(struct vnode *vp, NFSACL_T *aclp, acl_type_t atype,
8029     struct ucred *cred, NFSPROC_T *p)
8030 {
8031 	int error;
8032 
8033 	if (nfsrv_useacl == 0 || (atype == ACL_TYPE_NFS4 &&
8034 	    nfs_supportsnfsv4acls(vp) == 0) || (atype != ACL_TYPE_NFS4 &&
8035 	    nfs_supportsposixacls(vp) == 0)) {
8036 		error = NFSERR_ATTRNOTSUPP;
8037 		goto out;
8038 	}
8039 	/*
8040 	 * With NFSv4 ACLs, chmod(2) may need to add additional entries.
8041 	 * Make sure it has enough room for that - splitting every entry
8042 	 * into two and appending "canonical six" entries at the end.
8043 	 * Cribbed out of kern/vfs_acl.c - Rick M.
8044 	 */
8045 	if (aclp->acl_cnt > (ACL_MAX_ENTRIES - 6) / 2) {
8046 		error = NFSERR_ATTRNOTSUPP;
8047 		goto out;
8048 	}
8049 	if (aclp->acl_cnt == 0) {
8050 		if (atype != ACL_TYPE_DEFAULT || vp->v_type != VDIR) {
8051 			error = NFSERR_INVAL;
8052 			goto out;
8053 		}
8054 		error = VOP_SETACL(vp, atype, NULL, cred, p);
8055 	} else
8056 		error = VOP_SETACL(vp, atype, aclp, cred, p);
8057 	if (error == 0) {
8058 		error = nfsrv_dssetacl(vp, aclp, cred, p);
8059 		if (error == ENOENT)
8060 			error = 0;
8061 	}
8062 
8063 out:
8064 	NFSEXITCODE(error);
8065 	return (error);
8066 }
8067 
8068 /*
8069  * Seek vnode op call (actually it is a VOP_IOCTL()).
8070  * This function is called with the vnode locked, but unlocks and vrele()s
8071  * the vp before returning.
8072  */
8073 int
nfsvno_seek(struct nfsrv_descript * nd,struct vnode * vp,u_long cmd,off_t * offp,int content,bool * eofp,struct ucred * cred,NFSPROC_T * p)8074 nfsvno_seek(struct nfsrv_descript *nd, struct vnode *vp, u_long cmd,
8075     off_t *offp, int content, bool *eofp, struct ucred *cred, NFSPROC_T *p)
8076 {
8077 	struct nfsvattr at;
8078 	int error, ret;
8079 
8080 	ASSERT_VOP_LOCKED(vp, "nfsvno_seek vp");
8081 #ifdef notnow
8082 	/*
8083 	 * Attempt to seek on a DS file. A return of ENOENT implies
8084 	 * there is no DS file to seek on.
8085 	 */
8086 	error = nfsrv_proxyds(vp, 0, 0, cred, p, NFSPROC_SEEKDS, NULL,
8087 	    NULL, NULL, NULL, NULL, offp, content, eofp);
8088 	if (error != ENOENT) {
8089 		vput(vp);
8090 		return (error);
8091 	}
8092 #endif
8093 
8094 	/*
8095 	 * Do the VOP_IOCTL() call.  For the case where *offp == file_size,
8096 	 * VOP_IOCTL() will return ENXIO.  However, the correct reply for
8097 	 * NFSv4.2 is *eofp == true and error == 0 for this case.
8098 	 */
8099 	NFSVOPUNLOCK(vp);
8100 	error = VOP_IOCTL(vp, cmd, offp, 0, cred, p);
8101 	*eofp = false;
8102 	if (error == ENXIO || (error == 0 && cmd == FIOSEEKHOLE)) {
8103 		/* Handle the cases where we might be at EOF. */
8104 		ret = nfsvno_getattr(vp, &at, nd, p, 0, NULL);
8105 		if (ret == 0 && *offp == at.na_size) {
8106 			*eofp = true;
8107 			error = 0;
8108 		}
8109 		if (ret != 0 && error == 0)
8110 			error = ret;
8111 	}
8112 	vrele(vp);
8113 	NFSEXITCODE(error);
8114 	return (error);
8115 }
8116 
8117 /*
8118  * Allocate vnode op call.
8119  */
8120 int
nfsvno_allocate(struct vnode * vp,off_t off,off_t len,struct ucred * cred,NFSPROC_T * p)8121 nfsvno_allocate(struct vnode *vp, off_t off, off_t len, struct ucred *cred,
8122     NFSPROC_T *p)
8123 {
8124 	int error;
8125 	off_t olen;
8126 
8127 	ASSERT_VOP_ELOCKED(vp, "nfsvno_allocate vp");
8128 #ifdef notnow
8129 	/*
8130 	 * Attempt to allocate on a DS file. A return of ENOENT implies
8131 	 * there is no DS file to allocate on.
8132 	 */
8133 	error = nfsrv_proxyds(vp, off, 0, cred, p, NFSPROC_ALLOCATE, NULL,
8134 	    NULL, NULL, NULL, NULL, &len, 0, NULL);
8135 	if (error != ENOENT)
8136 		return (error);
8137 #endif
8138 
8139 	/*
8140 	 * Do the actual VOP_ALLOCATE(), looping so long as
8141 	 * progress is being made, to achieve completion.
8142 	 */
8143 	do {
8144 		olen = len;
8145 		error = VOP_ALLOCATE(vp, &off, &len, IO_SYNC, cred);
8146 		if (error == 0 && len > 0 && olen > len)
8147 			maybe_yield();
8148 	} while (error == 0 && len > 0 && olen > len);
8149 	if (error == 0 && len > 0)
8150 		error = NFSERR_IO;
8151 	NFSEXITCODE(error);
8152 	return (error);
8153 }
8154 
8155 /*
8156  * Deallocate vnode op call.
8157  */
8158 int
nfsvno_deallocate(struct vnode * vp,off_t off,off_t len,struct ucred * cred,NFSPROC_T * p)8159 nfsvno_deallocate(struct vnode *vp, off_t off, off_t len, struct ucred *cred,
8160     NFSPROC_T *p)
8161 {
8162 	int error;
8163 	off_t olen;
8164 
8165 	ASSERT_VOP_ELOCKED(vp, "nfsvno_deallocate vp");
8166 #ifdef notnow
8167 	/*
8168 	 * Attempt to deallocate on a DS file. A return of ENOENT implies
8169 	 * there is no DS file to deallocate on.
8170 	 */
8171 	error = nfsrv_proxyds(vp, off, 0, cred, p, NFSPROC_DEALLOCATE, NULL,
8172 	    NULL, NULL, NULL, NULL, &len, 0, NULL);
8173 	if (error != ENOENT)
8174 		return (error);
8175 #endif
8176 
8177 	/*
8178 	 * Do the actual VOP_DEALLOCATE(), looping so long as
8179 	 * progress is being made, to achieve completion.
8180 	 */
8181 	do {
8182 		olen = len;
8183 		error = VOP_DEALLOCATE(vp, &off, &len, 0, IO_SYNC, cred);
8184 		if (error == 0 && len > 0 && olen > len)
8185 			maybe_yield();
8186 	} while (error == 0 && len > 0 && olen > len);
8187 	if (error == 0 && len > 0)
8188 		error = NFSERR_IO;
8189 	NFSEXITCODE(error);
8190 	return (error);
8191 }
8192 
8193 /*
8194  * Get Extended Atribute vnode op into an mbuf list.
8195  */
8196 int
nfsvno_getxattr(struct vnode * vp,char * name,uint32_t maxresp,struct ucred * cred,uint64_t flag,int maxextsiz,struct thread * p,struct mbuf ** mpp,struct mbuf ** mpendp,int * lenp)8197 nfsvno_getxattr(struct vnode *vp, char *name, uint32_t maxresp,
8198     struct ucred *cred, uint64_t flag, int maxextsiz, struct thread *p,
8199     struct mbuf **mpp, struct mbuf **mpendp, int *lenp)
8200 {
8201 	struct iovec *iv;
8202 	struct uio io, *uiop = &io;
8203 	struct mbuf *m, *m2;
8204 	int alen, error, len, tlen;
8205 	size_t siz;
8206 
8207 	/* First, find out the size of the extended attribute. */
8208 	error = VOP_GETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, NULL,
8209 	    &siz, cred, p);
8210 	if (error != 0)
8211 		return (NFSERR_NOXATTR);
8212 	if (siz > maxresp - NFS_MAXXDR)
8213 		return (NFSERR_XATTR2BIG);
8214 	len = siz;
8215 	tlen = NFSM_RNDUP(len);
8216 	if (tlen > 0) {
8217 		/*
8218 		 * If cnt > MCLBYTES and the reply will not be saved, use
8219 		 * ext_pgs mbufs for TLS or enabled via vfs.nfsd.enable_mextpg.
8220 		 * For NFSv4.0, we do not know for sure if the reply will
8221 		 * be saved, so do not use ext_pgs mbufs for NFSv4.0.
8222 		 * Always use ext_pgs mbufs if ND_EXTPG is set.
8223 		 */
8224 		if ((flag & ND_EXTPG) != 0 || (tlen > MCLBYTES &&
8225 		    ((flag & (ND_TLS | ND_SAVEREPLY)) == ND_TLS ||
8226 		     (flag & (ND_CANEXTPG | ND_SAVEREPLY)) == ND_CANEXTPG) &&
8227 		    (flag & (ND_NFSV4 | ND_NFSV41)) != ND_NFSV4))
8228 			uiop->uio_iovcnt = nfsrv_createiovec_extpgs(tlen,
8229 			    maxextsiz, &m, &m2, &iv);
8230 		else
8231 			uiop->uio_iovcnt = nfsrv_createiovec(tlen, &m, &m2,
8232 			    &iv);
8233 		uiop->uio_iov = iv;
8234 	} else {
8235 		uiop->uio_iovcnt = 0;
8236 		uiop->uio_iov = iv = NULL;
8237 		m = m2 = NULL;
8238 	}
8239 	uiop->uio_offset = 0;
8240 	uiop->uio_resid = tlen;
8241 	uiop->uio_rw = UIO_READ;
8242 	uiop->uio_segflg = UIO_SYSSPACE;
8243 	uiop->uio_td = p;
8244 #ifdef MAC
8245 	error = mac_vnode_check_getextattr(cred, vp, EXTATTR_NAMESPACE_USER,
8246 	    name);
8247 	if (error != 0)
8248 		goto out;
8249 #endif
8250 
8251 	if (tlen > 0)
8252 		error = VOP_GETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, uiop,
8253 		    NULL, cred, p);
8254 	if (error != 0)
8255 		goto out;
8256 	if (uiop->uio_resid > 0) {
8257 		alen = tlen;
8258 		len = tlen - uiop->uio_resid;
8259 		tlen = NFSM_RNDUP(len);
8260 		if (alen != tlen)
8261 			printf("nfsvno_getxattr: weird size read\n");
8262 		if (tlen == 0) {
8263 			m_freem(m);
8264 			m = m2 = NULL;
8265 		} else if (alen != tlen || tlen != len)
8266 			m2 = nfsrv_adj(m, alen - tlen, tlen - len);
8267 	}
8268 	*lenp = len;
8269 	*mpp = m;
8270 	*mpendp = m2;
8271 
8272 out:
8273 	if (error != 0) {
8274 		if (m != NULL)
8275 			m_freem(m);
8276 		*lenp = 0;
8277 	}
8278 	free(iv, M_TEMP);
8279 	NFSEXITCODE(error);
8280 	return (error);
8281 }
8282 
8283 /*
8284  * Set Extended attribute vnode op from an mbuf list.
8285  */
8286 int
nfsvno_setxattr(struct vnode * vp,char * name,int len,struct mbuf * m,char * cp,struct ucred * cred,struct thread * p)8287 nfsvno_setxattr(struct vnode *vp, char *name, int len, struct mbuf *m,
8288     char *cp, struct ucred *cred, struct thread *p)
8289 {
8290 	struct iovec *iv;
8291 	struct uio uio, *uiop = &uio;
8292 	int cnt, error;
8293 
8294 	error = 0;
8295 #ifdef MAC
8296 	error = mac_vnode_check_setextattr(cred, vp, EXTATTR_NAMESPACE_USER,
8297 	    name);
8298 #endif
8299 	if (error != 0)
8300 		goto out;
8301 
8302 	uiop->uio_rw = UIO_WRITE;
8303 	uiop->uio_segflg = UIO_SYSSPACE;
8304 	uiop->uio_td = p;
8305 	uiop->uio_offset = 0;
8306 	uiop->uio_resid = len;
8307 	if (len > 0) {
8308 		error = nfsrv_createiovecw(len, m, cp, &iv, &cnt);
8309 		uiop->uio_iov = iv;
8310 		uiop->uio_iovcnt = cnt;
8311 	} else {
8312 		uiop->uio_iov = iv = NULL;
8313 		uiop->uio_iovcnt = 0;
8314 	}
8315 	if (error == 0) {
8316 		error = VOP_SETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, uiop,
8317 		    cred, p);
8318 		if (error == 0) {
8319 			if (vp->v_type == VREG && nfsrv_devidcnt != 0)
8320 				nfsvno_updateds(vp, cred, p);
8321 			error = VOP_FSYNC(vp, MNT_WAIT, p);
8322 		}
8323 		free(iv, M_TEMP);
8324 	}
8325 
8326 out:
8327 	NFSEXITCODE(error);
8328 	return (error);
8329 }
8330 
8331 /*
8332  * For a pNFS server, the DS file's ctime and
8333  * va_filerev (TimeMetadata and Change) needs to
8334  * be updated.  This is a hack, but works by
8335  * flipping the S_ISGID bit in va_mode and then
8336  * flipping it back.
8337  * It does result in two MDS->DS RPCs, but creating
8338  * a custom RPC just to do this seems overkill, since
8339  * Setxattr/Rmxattr will not be done that frequently.
8340  * If it fails part way through, that is not too
8341  * serious, since the DS file is never executed.
8342  */
8343 static void
nfsvno_updateds(struct vnode * vp,struct ucred * cred,NFSPROC_T * p)8344 nfsvno_updateds(struct vnode *vp, struct ucred *cred, NFSPROC_T *p)
8345 {
8346 	struct nfsvattr nva;
8347 	int ret;
8348 	u_short tmode;
8349 
8350 	ret = VOP_GETATTR(vp, &nva.na_vattr, cred);
8351 	if (ret == 0) {
8352 		tmode = nva.na_mode;
8353 		NFSVNO_ATTRINIT(&nva);
8354 		tmode ^= S_ISGID;
8355 		NFSVNO_SETATTRVAL(&nva, mode, tmode);
8356 		ret = nfsrv_proxyds(vp, 0, 0, cred, p,
8357 		    NFSPROC_SETATTR, NULL, NULL, NULL, &nva,
8358 		    NULL, NULL, 0, NULL);
8359 		if (ret == 0) {
8360 			tmode ^= S_ISGID;
8361 			NFSVNO_SETATTRVAL(&nva, mode, tmode);
8362 			ret = nfsrv_proxyds(vp, 0, 0, cred, p,
8363 			    NFSPROC_SETATTR, NULL, NULL, NULL,
8364 			    &nva, NULL, NULL, 0, NULL);
8365 		}
8366 	}
8367 }
8368 
8369 /*
8370  * Remove Extended attribute vnode op.
8371  */
8372 int
nfsvno_rmxattr(struct nfsrv_descript * nd,struct vnode * vp,char * name,struct ucred * cred,struct thread * p)8373 nfsvno_rmxattr(struct nfsrv_descript *nd, struct vnode *vp, char *name,
8374     struct ucred *cred, struct thread *p)
8375 {
8376 	int error;
8377 
8378 	/*
8379 	 * Get rid of any delegations.  I am not sure why this is required,
8380 	 * but RFC-8276 says so.
8381 	 */
8382 	error = nfsrv_checkremove(vp, 0, nd, nd->nd_clientid, p);
8383 	if (error != 0)
8384 		goto out;
8385 #ifdef MAC
8386 	error = mac_vnode_check_deleteextattr(cred, vp, EXTATTR_NAMESPACE_USER,
8387 	    name);
8388 	if (error != 0)
8389 		goto out;
8390 #endif
8391 
8392 	error = VOP_DELETEEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, cred, p);
8393 	if (error == EOPNOTSUPP)
8394 		error = VOP_SETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, NULL,
8395 		    cred, p);
8396 	if (error == 0) {
8397 		if (vp->v_type == VREG && nfsrv_devidcnt != 0)
8398 			nfsvno_updateds(vp, cred, p);
8399 		error = VOP_FSYNC(vp, MNT_WAIT, p);
8400 	}
8401 out:
8402 	NFSEXITCODE(error);
8403 	return (error);
8404 }
8405 
8406 /*
8407  * List Extended Atribute vnode op into an mbuf list.
8408  */
8409 int
nfsvno_listxattr(struct vnode * vp,uint64_t cookie,struct ucred * cred,struct thread * p,u_char ** bufp,uint32_t * lenp,bool * eofp)8410 nfsvno_listxattr(struct vnode *vp, uint64_t cookie, struct ucred *cred,
8411     struct thread *p, u_char **bufp, uint32_t *lenp, bool *eofp)
8412 {
8413 	struct iovec iv;
8414 	struct uio io;
8415 	int error;
8416 	size_t siz;
8417 
8418 	*bufp = NULL;
8419 	/* First, find out the size of the extended attribute. */
8420 	error = VOP_LISTEXTATTR(vp, EXTATTR_NAMESPACE_USER, NULL, &siz, cred,
8421 	    p);
8422 	if (error != 0)
8423 		return (NFSERR_NOXATTR);
8424 	if (siz <= cookie) {
8425 		*lenp = 0;
8426 		*eofp = true;
8427 		goto out;
8428 	}
8429 	if (siz > cookie + *lenp) {
8430 		siz = cookie + *lenp;
8431 		*eofp = false;
8432 	} else
8433 		*eofp = true;
8434 	/* Just choose a sanity limit of 10Mbytes for malloc(M_TEMP). */
8435 	if (siz > 10 * 1024 * 1024) {
8436 		error = NFSERR_XATTR2BIG;
8437 		goto out;
8438 	}
8439 	*bufp = malloc(siz, M_TEMP, M_WAITOK);
8440 	iv.iov_base = *bufp;
8441 	iv.iov_len = siz;
8442 	io.uio_iovcnt = 1;
8443 	io.uio_iov = &iv;
8444 	io.uio_offset = 0;
8445 	io.uio_resid = siz;
8446 	io.uio_rw = UIO_READ;
8447 	io.uio_segflg = UIO_SYSSPACE;
8448 	io.uio_td = p;
8449 #ifdef MAC
8450 	error = mac_vnode_check_listextattr(cred, vp, EXTATTR_NAMESPACE_USER);
8451 	if (error != 0)
8452 		goto out;
8453 #endif
8454 
8455 	error = VOP_LISTEXTATTR(vp, EXTATTR_NAMESPACE_USER, &io, NULL, cred,
8456 	    p);
8457 	if (error != 0)
8458 		goto out;
8459 	if (io.uio_resid > 0)
8460 		siz -= io.uio_resid;
8461 	*lenp = siz;
8462 
8463 out:
8464 	if (error != 0) {
8465 		free(*bufp, M_TEMP);
8466 		*bufp = NULL;
8467 	}
8468 	NFSEXITCODE(error);
8469 	return (error);
8470 }
8471 
8472 /*
8473  * Trim trailing data off the mbuf list being built.
8474  */
8475 void
nfsm_trimtrailing(struct nfsrv_descript * nd,struct mbuf * mb,char * bpos,int bextpg,int bextpgsiz)8476 nfsm_trimtrailing(struct nfsrv_descript *nd, struct mbuf *mb, char *bpos,
8477     int bextpg, int bextpgsiz)
8478 {
8479 	vm_page_t pg;
8480 	int fullpgsiz, i;
8481 
8482 	if (mb->m_next != NULL) {
8483 		m_freem(mb->m_next);
8484 		mb->m_next = NULL;
8485 	}
8486 	if ((mb->m_flags & M_EXTPG) != 0) {
8487 		KASSERT(bextpg >= 0 && bextpg < mb->m_epg_npgs,
8488 		    ("nfsm_trimtrailing: bextpg out of range"));
8489 		KASSERT(bpos == (char *)
8490 		    PHYS_TO_DMAP(mb->m_epg_pa[bextpg]) + PAGE_SIZE - bextpgsiz,
8491 		    ("nfsm_trimtrailing: bextpgsiz bad!"));
8492 
8493 		/* First, get rid of any pages after this position. */
8494 		for (i = mb->m_epg_npgs - 1; i > bextpg; i--) {
8495 			pg = PHYS_TO_VM_PAGE(mb->m_epg_pa[i]);
8496 			vm_page_unwire_noq(pg);
8497 			vm_page_free(pg);
8498 		}
8499 		mb->m_epg_npgs = bextpg + 1;
8500 		if (bextpg == 0)
8501 			fullpgsiz = PAGE_SIZE - mb->m_epg_1st_off;
8502 		else
8503 			fullpgsiz = PAGE_SIZE;
8504 		mb->m_epg_last_len = fullpgsiz - bextpgsiz;
8505 		mb->m_len = m_epg_pagelen(mb, 0, mb->m_epg_1st_off);
8506 		for (i = 1; i < mb->m_epg_npgs; i++)
8507 			mb->m_len += m_epg_pagelen(mb, i, 0);
8508 		nd->nd_bextpgsiz = bextpgsiz;
8509 		nd->nd_bextpg = bextpg;
8510 	} else
8511 		mb->m_len = bpos - mtod(mb, char *);
8512 	nd->nd_mb = mb;
8513 	nd->nd_bpos = bpos;
8514 }
8515 
8516 
8517 /*
8518  * Check to see if a put file handle operation should test for
8519  * NFSERR_WRONGSEC, although NFSv3 actually returns NFSERR_AUTHERR.
8520  * When Open is the next operation, NFSERR_WRONGSEC cannot be
8521  * replied for the Open cases that use a component.  This can
8522  * be identified by the fact that the file handle's type is VDIR.
8523  */
8524 bool
nfsrv_checkwrongsec(struct nfsrv_descript * nd,int nextop,__enum_uint8 (vtype)vtyp)8525 nfsrv_checkwrongsec(struct nfsrv_descript *nd, int nextop, __enum_uint8(vtype) vtyp)
8526 {
8527 
8528 	if ((nd->nd_flag & ND_NFSV4) == 0)
8529 		return (true);
8530 
8531 	if ((nd->nd_flag & ND_LASTOP) != 0)
8532 		return (false);
8533 
8534 	if (nextop == NFSV4OP_PUTROOTFH || nextop == NFSV4OP_PUTFH ||
8535 	    nextop == NFSV4OP_PUTPUBFH || nextop == NFSV4OP_RESTOREFH ||
8536 	    nextop == NFSV4OP_LOOKUP || nextop == NFSV4OP_LOOKUPP ||
8537 	    nextop == NFSV4OP_SECINFO || nextop == NFSV4OP_SECINFONONAME)
8538 		return (false);
8539 	if (nextop == NFSV4OP_OPEN && vtyp == VDIR)
8540 		return (false);
8541 	return (true);
8542 }
8543 
8544 /*
8545  * Check DSs marked no space.
8546  */
8547 void
nfsrv_checknospc(void)8548 nfsrv_checknospc(void)
8549 {
8550 	struct statfs *tsf;
8551 	struct nfsdevice *ds;
8552 	struct vnode **dvpp, **tdvpp, *dvp;
8553 	char *devid, *tdevid;
8554 	int cnt, error = 0, i;
8555 
8556 	if (nfsrv_devidcnt <= 0)
8557 		return;
8558 	dvpp = mallocarray(nfsrv_devidcnt, sizeof(*dvpp), M_TEMP, M_WAITOK);
8559 	devid = malloc(nfsrv_devidcnt * NFSX_V4DEVICEID, M_TEMP, M_WAITOK);
8560 	tsf = malloc(sizeof(*tsf), M_TEMP, M_WAITOK);
8561 
8562 	/* Get an array of the dvps for the DSs. */
8563 	tdvpp = dvpp;
8564 	tdevid = devid;
8565 	i = 0;
8566 	NFSDDSLOCK();
8567 	/* First, search for matches for same file system. */
8568 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
8569 		if (ds->nfsdev_nmp != NULL && ds->nfsdev_nospc) {
8570 			if (++i > nfsrv_devidcnt)
8571 				break;
8572 			*tdvpp++ = ds->nfsdev_dvp;
8573 			NFSBCOPY(ds->nfsdev_deviceid, tdevid, NFSX_V4DEVICEID);
8574 			tdevid += NFSX_V4DEVICEID;
8575 		}
8576 	}
8577 	NFSDDSUNLOCK();
8578 
8579 	/* Do a VFS_STATFS() for each of the DSs and clear no space. */
8580 	cnt = i;
8581 	tdvpp = dvpp;
8582 	tdevid = devid;
8583 	for (i = 0; i < cnt && error == 0; i++) {
8584 		dvp = *tdvpp++;
8585 		error = VFS_STATFS(dvp->v_mount, tsf);
8586 		if (error == 0 && tsf->f_bavail > 0) {
8587 			NFSD_DEBUG(1, "nfsrv_checknospc: reset nospc\n");
8588 			nfsrv_marknospc(tdevid, false);
8589 		}
8590 		tdevid += NFSX_V4DEVICEID;
8591 	}
8592 	free(tsf, M_TEMP);
8593 	free(dvpp, M_TEMP);
8594 	free(devid, M_TEMP);
8595 }
8596 
8597 /*
8598  * Return the correct ACL support value for a vnode.
8599  */
8600 int
nfs_supportsacls(struct vnode * vp)8601 nfs_supportsacls(struct vnode *vp)
8602 {
8603 
8604 	if (nfs_supportsnfsv4acls(vp) != 0)
8605 		return (SUPPACL_NFSV4);
8606 	else if (nfs_supportsposixacls(vp) != 0)
8607 		return (SUPPACL_POSIX);
8608 	return (SUPPACL_NONE);
8609 }
8610 
8611 /*
8612  * Initialize everything that needs to be initialized for a vnet.
8613  */
8614 static void
nfsrv_vnetinit(const void * unused __unused)8615 nfsrv_vnetinit(const void *unused __unused)
8616 {
8617 
8618 	nfsd_mntinit();
8619 }
8620 VNET_SYSINIT(nfsrv_vnetinit, SI_SUB_VNET_DONE, SI_ORDER_ANY,
8621     nfsrv_vnetinit, NULL);
8622 
8623 /*
8624  * Clean up everything that is in a vnet and needs to be
8625  * done when the jail is destroyed or the module unloaded.
8626  */
8627 static void
nfsrv_cleanup(const void * unused __unused)8628 nfsrv_cleanup(const void *unused __unused)
8629 {
8630 	int i;
8631 
8632 	NFSD_LOCK();
8633 	if (!VNET(nfsrv_mntinited)) {
8634 		NFSD_UNLOCK();
8635 		return;
8636 	}
8637 	VNET(nfsrv_mntinited) = false;
8638 	NFSD_UNLOCK();
8639 
8640 	/* Clean out all NFSv4 state. */
8641 	nfsrv_throwawayallstate(curthread);
8642 
8643 	/* Clean the NFS server reply cache */
8644 	nfsrvd_cleancache();
8645 
8646 	/* Clean out v4root exports. */
8647 	if (VNET(nfsv4root_mnt)->mnt_export != NULL) {
8648 		vfs_free_addrlist(VNET(nfsv4root_mnt)->mnt_export);
8649 		free(VNET(nfsv4root_mnt)->mnt_export, M_MOUNT);
8650 		VNET(nfsv4root_mnt)->mnt_export = NULL;
8651 	}
8652 
8653 	/* Free up the krpc server pool. */
8654 	if (VNET(nfsrvd_pool) != NULL)
8655 		svcpool_destroy(VNET(nfsrvd_pool));
8656 
8657 	/* and get rid of the locks */
8658 	for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
8659 		mtx_destroy(&VNET(nfsrchash_table)[i].mtx);
8660 		mtx_destroy(&VNET(nfsrcahash_table)[i].mtx);
8661 	}
8662 	mtx_destroy(&VNET(nfsv4root_mnt)->mnt_mtx);
8663 	for (i = 0; i < nfsrv_sessionhashsize; i++)
8664 		mtx_destroy(&VNET(nfssessionhash)[i].mtx);
8665 	lockdestroy(&VNET(nfsv4root_mnt)->mnt_explock);
8666 	free(VNET(nfsrvudphashtbl), M_NFSRVCACHE);
8667 	free(VNET(nfsrchash_table), M_NFSRVCACHE);
8668 	free(VNET(nfsrcahash_table), M_NFSRVCACHE);
8669 	free(VNET(nfsclienthash), M_NFSDCLIENT);
8670 	free(VNET(nfslockhash), M_NFSDLOCKFILE);
8671 	free(VNET(nfssessionhash), M_NFSDSESSION);
8672 	free(VNET(nfsv4root_mnt), M_TEMP);
8673 	VNET(nfsv4root_mnt) = NULL;
8674 }
8675 VNET_SYSUNINIT(nfsrv_cleanup, SI_SUB_VNET_DONE, SI_ORDER_ANY,
8676     nfsrv_cleanup, NULL);
8677 
8678 extern int (*nfsd_call_nfsd)(struct thread *, struct nfssvc_args *);
8679 
8680 /*
8681  * Called once to initialize data structures...
8682  */
8683 static int
nfsd_modevent(module_t mod,int type,void * data)8684 nfsd_modevent(module_t mod, int type, void *data)
8685 {
8686 	int error = 0, i;
8687 	static int loaded = 0;
8688 
8689 	switch (type) {
8690 	case MOD_LOAD:
8691 		if (loaded)
8692 			goto out;
8693 		newnfs_portinit();
8694 		mtx_init(&nfsrc_udpmtx, "nfsuc", NULL, MTX_DEF);
8695 		mtx_init(&nfs_v4root_mutex, "nfs4rt", NULL, MTX_DEF);
8696 		mtx_init(&nfsrv_dontlistlock_mtx, "nfs4dnl", NULL, MTX_DEF);
8697 		mtx_init(&nfsrv_recalllock_mtx, "nfs4rec", NULL, MTX_DEF);
8698 #ifdef VV_DISABLEDELEG
8699 		vn_deleg_ops.vndeleg_recall = nfsd_recalldelegation;
8700 		vn_deleg_ops.vndeleg_disable = nfsd_disabledelegation;
8701 #endif
8702 		nfsd_call_nfsd = nfssvc_nfsd;
8703 		loaded = 1;
8704 		break;
8705 
8706 	case MOD_UNLOAD:
8707 		if (newnfs_numnfsd != 0) {
8708 			error = EBUSY;
8709 			break;
8710 		}
8711 
8712 #ifdef VV_DISABLEDELEG
8713 		vn_deleg_ops.vndeleg_recall = NULL;
8714 		vn_deleg_ops.vndeleg_disable = NULL;
8715 #endif
8716 		nfsd_call_nfsd = NULL;
8717 		mtx_destroy(&nfsrc_udpmtx);
8718 		mtx_destroy(&nfs_v4root_mutex);
8719 		mtx_destroy(&nfsrv_dontlistlock_mtx);
8720 		mtx_destroy(&nfsrv_recalllock_mtx);
8721 		if (nfslayouthash != NULL) {
8722 			for (i = 0; i < nfsrv_layouthashsize; i++)
8723 				mtx_destroy(&nfslayouthash[i].mtx);
8724 			free(nfslayouthash, M_NFSDSESSION);
8725 		}
8726 		loaded = 0;
8727 		break;
8728 	default:
8729 		error = EOPNOTSUPP;
8730 		break;
8731 	}
8732 
8733 out:
8734 	NFSEXITCODE(error);
8735 	return (error);
8736 }
8737 static moduledata_t nfsd_mod = {
8738 	"nfsd",
8739 	nfsd_modevent,
8740 	NULL,
8741 };
8742 DECLARE_MODULE(nfsd, nfsd_mod, SI_SUB_VFS, SI_ORDER_ANY);
8743 
8744 /* So that loader and kldload(2) can find us, wherever we are.. */
8745 MODULE_VERSION(nfsd, 1);
8746 MODULE_DEPEND(nfsd, nfscommon, 1, 1, 1);
8747 MODULE_DEPEND(nfsd, nfslockd, 1, 1, 1);
8748 MODULE_DEPEND(nfsd, krpc, 1, 1, 1);
8749 MODULE_DEPEND(nfsd, nfssvc, 1, 1, 1);
8750