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