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