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