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