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