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