xref: /freebsd/sys/fs/nfsclient/nfs_clport.c (revision d4eeb02986980bf33dd56c41ceb9fc5f180c0d47)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Rick Macklem at The University of Guelph.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  */
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include "opt_inet.h"
40 #include "opt_inet6.h"
41 
42 #include <sys/capsicum.h>
43 
44 /*
45  * generally, I don't like #includes inside .h files, but it seems to
46  * be the easiest way to handle the port.
47  */
48 #include <sys/fail.h>
49 #include <sys/hash.h>
50 #include <sys/sysctl.h>
51 #include <fs/nfs/nfsport.h>
52 #include <netinet/in_fib.h>
53 #include <netinet/if_ether.h>
54 #include <netinet6/ip6_var.h>
55 #include <net/if_types.h>
56 #include <net/route/nhop.h>
57 
58 #include <fs/nfsclient/nfs_kdtrace.h>
59 
60 #ifdef KDTRACE_HOOKS
61 dtrace_nfsclient_attrcache_flush_probe_func_t
62 		dtrace_nfscl_attrcache_flush_done_probe;
63 uint32_t	nfscl_attrcache_flush_done_id;
64 
65 dtrace_nfsclient_attrcache_get_hit_probe_func_t
66 		dtrace_nfscl_attrcache_get_hit_probe;
67 uint32_t	nfscl_attrcache_get_hit_id;
68 
69 dtrace_nfsclient_attrcache_get_miss_probe_func_t
70 		dtrace_nfscl_attrcache_get_miss_probe;
71 uint32_t	nfscl_attrcache_get_miss_id;
72 
73 dtrace_nfsclient_attrcache_load_probe_func_t
74 		dtrace_nfscl_attrcache_load_done_probe;
75 uint32_t	nfscl_attrcache_load_done_id;
76 #endif /* !KDTRACE_HOOKS */
77 
78 extern u_int32_t newnfs_true, newnfs_false, newnfs_xdrneg1;
79 extern struct vop_vector newnfs_vnodeops;
80 extern struct vop_vector newnfs_fifoops;
81 extern uma_zone_t newnfsnode_zone;
82 extern struct buf_ops buf_ops_newnfs;
83 extern uma_zone_t ncl_pbuf_zone;
84 extern short nfsv4_cbport;
85 extern int nfscl_enablecallb;
86 extern int nfs_numnfscbd;
87 extern int nfscl_inited;
88 struct mtx ncl_iod_mutex;
89 NFSDLOCKMUTEX;
90 extern struct mtx nfsrv_dslock_mtx;
91 
92 extern void (*ncl_call_invalcaches)(struct vnode *);
93 
94 SYSCTL_DECL(_vfs_nfs);
95 static int ncl_fileid_maxwarnings = 10;
96 SYSCTL_INT(_vfs_nfs, OID_AUTO, fileid_maxwarnings, CTLFLAG_RWTUN,
97     &ncl_fileid_maxwarnings, 0,
98     "Limit fileid corruption warnings; 0 is off; -1 is unlimited");
99 static volatile int ncl_fileid_nwarnings;
100 
101 static void nfscl_warn_fileid(struct nfsmount *, struct nfsvattr *,
102     struct nfsvattr *);
103 
104 /*
105  * Comparison function for vfs_hash functions.
106  */
107 int
108 newnfs_vncmpf(struct vnode *vp, void *arg)
109 {
110 	struct nfsfh *nfhp = (struct nfsfh *)arg;
111 	struct nfsnode *np = VTONFS(vp);
112 
113 	if (np->n_fhp->nfh_len != nfhp->nfh_len ||
114 	    NFSBCMP(np->n_fhp->nfh_fh, nfhp->nfh_fh, nfhp->nfh_len))
115 		return (1);
116 	return (0);
117 }
118 
119 /*
120  * Look up a vnode/nfsnode by file handle.
121  * Callers must check for mount points!!
122  * In all cases, a pointer to a
123  * nfsnode structure is returned.
124  * This variant takes a "struct nfsfh *" as second argument and uses
125  * that structure up, either by hanging off the nfsnode or FREEing it.
126  */
127 int
128 nfscl_nget(struct mount *mntp, struct vnode *dvp, struct nfsfh *nfhp,
129     struct componentname *cnp, struct thread *td, struct nfsnode **npp,
130     int lkflags)
131 {
132 	struct nfsnode *np, *dnp;
133 	struct vnode *vp, *nvp;
134 	struct nfsv4node *newd, *oldd;
135 	int error;
136 	u_int hash;
137 	struct nfsmount *nmp;
138 
139 	nmp = VFSTONFS(mntp);
140 	dnp = VTONFS(dvp);
141 	*npp = NULL;
142 
143 	hash = fnv_32_buf(nfhp->nfh_fh, nfhp->nfh_len, FNV1_32_INIT);
144 
145 	error = vfs_hash_get(mntp, hash, lkflags,
146 	    td, &nvp, newnfs_vncmpf, nfhp);
147 	if (error == 0 && nvp != NULL) {
148 		/*
149 		 * I believe there is a slight chance that vgonel() could
150 		 * get called on this vnode between when NFSVOPLOCK() drops
151 		 * the VI_LOCK() and vget() acquires it again, so that it
152 		 * hasn't yet had v_usecount incremented. If this were to
153 		 * happen, the VIRF_DOOMED flag would be set, so check for
154 		 * that here. Since we now have the v_usecount incremented,
155 		 * we should be ok until we vrele() it, if the VIRF_DOOMED
156 		 * flag isn't set now.
157 		 */
158 		VI_LOCK(nvp);
159 		if (VN_IS_DOOMED(nvp)) {
160 			VI_UNLOCK(nvp);
161 			vrele(nvp);
162 			error = ENOENT;
163 		} else {
164 			VI_UNLOCK(nvp);
165 		}
166 	}
167 	if (error) {
168 		free(nfhp, M_NFSFH);
169 		return (error);
170 	}
171 	if (nvp != NULL) {
172 		np = VTONFS(nvp);
173 		/*
174 		 * For NFSv4, check to see if it is the same name and
175 		 * replace the name, if it is different.
176 		 */
177 		oldd = newd = NULL;
178 		if ((nmp->nm_flag & NFSMNT_NFSV4) && np->n_v4 != NULL &&
179 		    nvp->v_type == VREG &&
180 		    (np->n_v4->n4_namelen != cnp->cn_namelen ||
181 		     NFSBCMP(cnp->cn_nameptr, NFS4NODENAME(np->n_v4),
182 		     cnp->cn_namelen) ||
183 		     dnp->n_fhp->nfh_len != np->n_v4->n4_fhlen ||
184 		     NFSBCMP(dnp->n_fhp->nfh_fh, np->n_v4->n4_data,
185 		     dnp->n_fhp->nfh_len))) {
186 		    newd = malloc(
187 			sizeof (struct nfsv4node) + dnp->n_fhp->nfh_len +
188 			+ cnp->cn_namelen - 1, M_NFSV4NODE, M_WAITOK);
189 		    NFSLOCKNODE(np);
190 		    if (newd != NULL && np->n_v4 != NULL && nvp->v_type == VREG
191 			&& (np->n_v4->n4_namelen != cnp->cn_namelen ||
192 			 NFSBCMP(cnp->cn_nameptr, NFS4NODENAME(np->n_v4),
193 			 cnp->cn_namelen) ||
194 			 dnp->n_fhp->nfh_len != np->n_v4->n4_fhlen ||
195 			 NFSBCMP(dnp->n_fhp->nfh_fh, np->n_v4->n4_data,
196 			 dnp->n_fhp->nfh_len))) {
197 			oldd = np->n_v4;
198 			np->n_v4 = newd;
199 			newd = NULL;
200 			np->n_v4->n4_fhlen = dnp->n_fhp->nfh_len;
201 			np->n_v4->n4_namelen = cnp->cn_namelen;
202 			NFSBCOPY(dnp->n_fhp->nfh_fh, np->n_v4->n4_data,
203 			    dnp->n_fhp->nfh_len);
204 			NFSBCOPY(cnp->cn_nameptr, NFS4NODENAME(np->n_v4),
205 			    cnp->cn_namelen);
206 		    }
207 		    NFSUNLOCKNODE(np);
208 		}
209 		if (newd != NULL)
210 			free(newd, M_NFSV4NODE);
211 		if (oldd != NULL)
212 			free(oldd, M_NFSV4NODE);
213 		*npp = np;
214 		free(nfhp, M_NFSFH);
215 		return (0);
216 	}
217 	np = uma_zalloc(newnfsnode_zone, M_WAITOK | M_ZERO);
218 
219 	error = getnewvnode(nfs_vnode_tag, mntp, &newnfs_vnodeops, &nvp);
220 	if (error) {
221 		uma_zfree(newnfsnode_zone, np);
222 		free(nfhp, M_NFSFH);
223 		return (error);
224 	}
225 	vp = nvp;
226 	KASSERT(vp->v_bufobj.bo_bsize != 0, ("nfscl_nget: bo_bsize == 0"));
227 	vp->v_bufobj.bo_ops = &buf_ops_newnfs;
228 	vp->v_data = np;
229 	np->n_vnode = vp;
230 	/*
231 	 * Initialize the mutex even if the vnode is going to be a loser.
232 	 * This simplifies the logic in reclaim, which can then unconditionally
233 	 * destroy the mutex (in the case of the loser, or if hash_insert
234 	 * happened to return an error no special casing is needed).
235 	 */
236 	mtx_init(&np->n_mtx, "NEWNFSnode lock", NULL, MTX_DEF | MTX_DUPOK);
237 	lockinit(&np->n_excl, PVFS, "nfsupg", VLKTIMEOUT, LK_NOSHARE |
238 	    LK_CANRECURSE);
239 
240 	/*
241 	 * Are we getting the root? If so, make sure the vnode flags
242 	 * are correct
243 	 */
244 	if ((nfhp->nfh_len == nmp->nm_fhsize) &&
245 	    !bcmp(nfhp->nfh_fh, nmp->nm_fh, nfhp->nfh_len)) {
246 		if (vp->v_type == VNON)
247 			vp->v_type = VDIR;
248 		vp->v_vflag |= VV_ROOT;
249 	}
250 
251 	vp->v_vflag |= VV_VMSIZEVNLOCK;
252 
253 	np->n_fhp = nfhp;
254 	/*
255 	 * For NFSv4, we have to attach the directory file handle and
256 	 * file name, so that Open Ops can be done later.
257 	 */
258 	if (nmp->nm_flag & NFSMNT_NFSV4) {
259 		np->n_v4 = malloc(sizeof (struct nfsv4node)
260 		    + dnp->n_fhp->nfh_len + cnp->cn_namelen - 1, M_NFSV4NODE,
261 		    M_WAITOK);
262 		np->n_v4->n4_fhlen = dnp->n_fhp->nfh_len;
263 		np->n_v4->n4_namelen = cnp->cn_namelen;
264 		NFSBCOPY(dnp->n_fhp->nfh_fh, np->n_v4->n4_data,
265 		    dnp->n_fhp->nfh_len);
266 		NFSBCOPY(cnp->cn_nameptr, NFS4NODENAME(np->n_v4),
267 		    cnp->cn_namelen);
268 	} else {
269 		np->n_v4 = NULL;
270 	}
271 
272 	/*
273 	 * NFS supports recursive and shared locking.
274 	 */
275 	lockmgr(vp->v_vnlock, LK_EXCLUSIVE | LK_NOWITNESS, NULL);
276 	VN_LOCK_AREC(vp);
277 	VN_LOCK_ASHARE(vp);
278 	error = insmntque(vp, mntp);
279 	if (error != 0) {
280 		*npp = NULL;
281 		mtx_destroy(&np->n_mtx);
282 		lockdestroy(&np->n_excl);
283 		free(nfhp, M_NFSFH);
284 		if (np->n_v4 != NULL)
285 			free(np->n_v4, M_NFSV4NODE);
286 		uma_zfree(newnfsnode_zone, np);
287 		return (error);
288 	}
289 	error = vfs_hash_insert(vp, hash, lkflags,
290 	    td, &nvp, newnfs_vncmpf, nfhp);
291 	if (error)
292 		return (error);
293 	if (nvp != NULL) {
294 		*npp = VTONFS(nvp);
295 		/* vfs_hash_insert() vput()'s the losing vnode */
296 		return (0);
297 	}
298 	*npp = np;
299 
300 	return (0);
301 }
302 
303 /*
304  * Another variant of nfs_nget(). This one is only used by reopen. It
305  * takes almost the same args as nfs_nget(), but only succeeds if an entry
306  * exists in the cache. (Since files should already be "open" with a
307  * vnode ref cnt on the node when reopen calls this, it should always
308  * succeed.)
309  * Also, don't get a vnode lock, since it may already be locked by some
310  * other process that is handling it. This is ok, since all other threads
311  * on the client are blocked by the nfsc_lock being exclusively held by the
312  * caller of this function.
313  */
314 int
315 nfscl_ngetreopen(struct mount *mntp, u_int8_t *fhp, int fhsize,
316     struct thread *td, struct nfsnode **npp)
317 {
318 	struct vnode *nvp;
319 	u_int hash;
320 	struct nfsfh *nfhp;
321 	int error;
322 
323 	*npp = NULL;
324 	/* For forced dismounts, just return error. */
325 	if (NFSCL_FORCEDISM(mntp))
326 		return (EINTR);
327 	nfhp = malloc(sizeof (struct nfsfh) + fhsize,
328 	    M_NFSFH, M_WAITOK);
329 	bcopy(fhp, &nfhp->nfh_fh[0], fhsize);
330 	nfhp->nfh_len = fhsize;
331 
332 	hash = fnv_32_buf(fhp, fhsize, FNV1_32_INIT);
333 
334 	/*
335 	 * First, try to get the vnode locked, but don't block for the lock.
336 	 */
337 	error = vfs_hash_get(mntp, hash, (LK_EXCLUSIVE | LK_NOWAIT), td, &nvp,
338 	    newnfs_vncmpf, nfhp);
339 	if (error == 0 && nvp != NULL) {
340 		NFSVOPUNLOCK(nvp);
341 	} else if (error == EBUSY) {
342 		/*
343 		 * It is safe so long as a vflush() with
344 		 * FORCECLOSE has not been done. Since the Renew thread is
345 		 * stopped and the MNTK_UNMOUNTF flag is set before doing
346 		 * a vflush() with FORCECLOSE, we should be ok here.
347 		 */
348 		if (NFSCL_FORCEDISM(mntp))
349 			error = EINTR;
350 		else {
351 			vfs_hash_ref(mntp, hash, td, &nvp, newnfs_vncmpf, nfhp);
352 			if (nvp == NULL) {
353 				error = ENOENT;
354 			} else if (VN_IS_DOOMED(nvp)) {
355 				error = ENOENT;
356 				vrele(nvp);
357 			} else {
358 				error = 0;
359 			}
360 		}
361 	}
362 	free(nfhp, M_NFSFH);
363 	if (error)
364 		return (error);
365 	if (nvp != NULL) {
366 		*npp = VTONFS(nvp);
367 		return (0);
368 	}
369 	return (EINVAL);
370 }
371 
372 static void
373 nfscl_warn_fileid(struct nfsmount *nmp, struct nfsvattr *oldnap,
374     struct nfsvattr *newnap)
375 {
376 	int off;
377 
378 	if (ncl_fileid_maxwarnings >= 0 &&
379 	    ncl_fileid_nwarnings >= ncl_fileid_maxwarnings)
380 		return;
381 	off = 0;
382 	if (ncl_fileid_maxwarnings >= 0) {
383 		if (++ncl_fileid_nwarnings >= ncl_fileid_maxwarnings)
384 			off = 1;
385 	}
386 
387 	printf("newnfs: server '%s' error: fileid changed. "
388 	    "fsid %jx:%jx: expected fileid %#jx, got %#jx. "
389 	    "(BROKEN NFS SERVER OR MIDDLEWARE)\n",
390 	    nmp->nm_com.nmcom_hostname,
391 	    (uintmax_t)nmp->nm_fsid[0],
392 	    (uintmax_t)nmp->nm_fsid[1],
393 	    (uintmax_t)oldnap->na_fileid,
394 	    (uintmax_t)newnap->na_fileid);
395 
396 	if (off)
397 		printf("newnfs: Logged %d times about fileid corruption; "
398 		    "going quiet to avoid spamming logs excessively. (Limit "
399 		    "is: %d).\n", ncl_fileid_nwarnings,
400 		    ncl_fileid_maxwarnings);
401 }
402 
403 void
404 ncl_copy_vattr(struct vattr *dst, struct vattr *src)
405 {
406 	dst->va_type = src->va_type;
407 	dst->va_mode = src->va_mode;
408 	dst->va_nlink = src->va_nlink;
409 	dst->va_uid = src->va_uid;
410 	dst->va_gid = src->va_gid;
411 	dst->va_fsid = src->va_fsid;
412 	dst->va_fileid = src->va_fileid;
413 	dst->va_size = src->va_size;
414 	dst->va_blocksize = src->va_blocksize;
415 	dst->va_atime = src->va_atime;
416 	dst->va_mtime = src->va_mtime;
417 	dst->va_ctime = src->va_ctime;
418 	dst->va_birthtime = src->va_birthtime;
419 	dst->va_gen = src->va_gen;
420 	dst->va_flags = src->va_flags;
421 	dst->va_rdev = src->va_rdev;
422 	dst->va_bytes = src->va_bytes;
423 	dst->va_filerev = src->va_filerev;
424 }
425 
426 /*
427  * Load the attribute cache (that lives in the nfsnode entry) with
428  * the attributes of the second argument and
429  * Iff vaper not NULL
430  *    copy the attributes to *vaper
431  * Similar to nfs_loadattrcache(), except the attributes are passed in
432  * instead of being parsed out of the mbuf list.
433  */
434 int
435 nfscl_loadattrcache(struct vnode **vpp, struct nfsvattr *nap, void *nvaper,
436     int writeattr, int dontshrink)
437 {
438 	struct vnode *vp = *vpp;
439 	struct vattr *vap, *nvap = &nap->na_vattr, *vaper = nvaper;
440 	struct nfsnode *np;
441 	struct nfsmount *nmp;
442 	struct timespec mtime_save;
443 	int error, force_fid_err;
444 	dev_t topfsid;
445 
446 	error = 0;
447 
448 	/*
449 	 * If v_type == VNON it is a new node, so fill in the v_type,
450 	 * n_mtime fields. Check to see if it represents a special
451 	 * device, and if so, check for a possible alias. Once the
452 	 * correct vnode has been obtained, fill in the rest of the
453 	 * information.
454 	 */
455 	np = VTONFS(vp);
456 	NFSLOCKNODE(np);
457 	if (vp->v_type != nvap->va_type) {
458 		vp->v_type = nvap->va_type;
459 		if (vp->v_type == VFIFO)
460 			vp->v_op = &newnfs_fifoops;
461 		np->n_mtime = nvap->va_mtime;
462 	}
463 	nmp = VFSTONFS(vp->v_mount);
464 	vap = &np->n_vattr.na_vattr;
465 	mtime_save = vap->va_mtime;
466 	if (writeattr) {
467 		np->n_vattr.na_filerev = nap->na_filerev;
468 		np->n_vattr.na_size = nap->na_size;
469 		np->n_vattr.na_mtime = nap->na_mtime;
470 		np->n_vattr.na_ctime = nap->na_ctime;
471 		np->n_vattr.na_btime = nap->na_btime;
472 		np->n_vattr.na_fsid = nap->na_fsid;
473 		np->n_vattr.na_mode = nap->na_mode;
474 	} else {
475 		force_fid_err = 0;
476 		KFAIL_POINT_ERROR(DEBUG_FP, nfscl_force_fileid_warning,
477 		    force_fid_err);
478 		/*
479 		 * BROKEN NFS SERVER OR MIDDLEWARE
480 		 *
481 		 * Certain NFS servers (certain old proprietary filers ca.
482 		 * 2006) or broken middleboxes (e.g. WAN accelerator products)
483 		 * will respond to GETATTR requests with results for a
484 		 * different fileid.
485 		 *
486 		 * The WAN accelerator we've observed not only serves stale
487 		 * cache results for a given file, it also occasionally serves
488 		 * results for wholly different files.  This causes surprising
489 		 * problems; for example the cached size attribute of a file
490 		 * may truncate down and then back up, resulting in zero
491 		 * regions in file contents read by applications.  We observed
492 		 * this reliably with Clang and .c files during parallel build.
493 		 * A pcap revealed packet fragmentation and GETATTR RPC
494 		 * responses with wholly wrong fileids.
495 		 */
496 		if ((np->n_vattr.na_fileid != 0 &&
497 		     np->n_vattr.na_fileid != nap->na_fileid) ||
498 		    force_fid_err) {
499 			nfscl_warn_fileid(nmp, &np->n_vattr, nap);
500 			error = EIDRM;
501 			goto out;
502 		}
503 		NFSBCOPY((caddr_t)nap, (caddr_t)&np->n_vattr,
504 		    sizeof (struct nfsvattr));
505 	}
506 
507 	/*
508 	 * For NFSv4, the server's export may be a tree of file systems
509 	 * where a fileno is a unique value within each file system.
510 	 * na_filesid[0,1] uniquely identify the server file system
511 	 * and nm_fsid[0,1] is the value for the root file system mounted.
512 	 * As such, the value of va_fsid generated by vn_fsid() represents
513 	 * the root file system on the server and a different value for
514 	 * va_fsid is needed for the other server file systems.  This
515 	 * va_fsid is ideally unique for all of the server file systems,
516 	 * so a 64bit hash on na_filesid[0,1] is calculated.
517 	 * Although highly unlikely that the fnv_64_hash() will be
518 	 * the same as the root, test for this case and recalculate the hash.
519 	 */
520 	vn_fsid(vp, vap);
521 	if (NFSHASNFSV4(nmp) && NFSHASHASSETFSID(nmp) &&
522 	    (nmp->nm_fsid[0] != np->n_vattr.na_filesid[0] ||
523 	     nmp->nm_fsid[1] != np->n_vattr.na_filesid[1])) {
524 		topfsid = vap->va_fsid;
525 		vap->va_fsid = FNV1_64_INIT;
526 		do {
527 			vap->va_fsid = fnv_64_buf(np->n_vattr.na_filesid,
528 			    sizeof(np->n_vattr.na_filesid), vap->va_fsid);
529 		} while (vap->va_fsid == topfsid);
530 	}
531 
532 	np->n_attrstamp = time_second;
533 	if (vap->va_size != np->n_size) {
534 		if (vap->va_type == VREG) {
535 			if (dontshrink && vap->va_size < np->n_size) {
536 				/*
537 				 * We've been told not to shrink the file;
538 				 * zero np->n_attrstamp to indicate that
539 				 * the attributes are stale.
540 				 */
541 				vap->va_size = np->n_size;
542 				np->n_attrstamp = 0;
543 				KDTRACE_NFS_ATTRCACHE_FLUSH_DONE(vp);
544 			} else if (np->n_flag & NMODIFIED) {
545 				/*
546 				 * We've modified the file: Use the larger
547 				 * of our size, and the server's size.
548 				 */
549 				if (vap->va_size < np->n_size) {
550 					vap->va_size = np->n_size;
551 				} else {
552 					np->n_size = vap->va_size;
553 					np->n_flag |= NSIZECHANGED;
554 				}
555 			} else {
556 				np->n_size = vap->va_size;
557 				np->n_flag |= NSIZECHANGED;
558 			}
559 		} else {
560 			np->n_size = vap->va_size;
561 		}
562 	}
563 	/*
564 	 * The following checks are added to prevent a race between (say)
565 	 * a READDIR+ and a WRITE.
566 	 * READDIR+, WRITE requests sent out.
567 	 * READDIR+ resp, WRITE resp received on client.
568 	 * However, the WRITE resp was handled before the READDIR+ resp
569 	 * causing the post op attrs from the write to be loaded first
570 	 * and the attrs from the READDIR+ to be loaded later. If this
571 	 * happens, we have stale attrs loaded into the attrcache.
572 	 * We detect this by for the mtime moving back. We invalidate the
573 	 * attrcache when this happens.
574 	 */
575 	if (timespeccmp(&mtime_save, &vap->va_mtime, >)) {
576 		/* Size changed or mtime went backwards */
577 		np->n_attrstamp = 0;
578 		KDTRACE_NFS_ATTRCACHE_FLUSH_DONE(vp);
579 	}
580 	if (vaper != NULL) {
581 		ncl_copy_vattr(vaper, vap);
582 		if (np->n_flag & NCHG) {
583 			if (np->n_flag & NACC)
584 				vaper->va_atime = np->n_atim;
585 			if (np->n_flag & NUPD)
586 				vaper->va_mtime = np->n_mtim;
587 		}
588 	}
589 
590 out:
591 #ifdef KDTRACE_HOOKS
592 	if (np->n_attrstamp != 0)
593 		KDTRACE_NFS_ATTRCACHE_LOAD_DONE(vp, vap, error);
594 #endif
595 	(void)ncl_pager_setsize(vp, NULL);
596 	return (error);
597 }
598 
599 /*
600  * Call vnode_pager_setsize() if the size of the node changed, as
601  * recorded in nfsnode vs. v_object, or delay the call if notifying
602  * the pager is not possible at the moment.
603  *
604  * If nsizep is non-NULL, the call is delayed and the new node size is
605  * provided.  Caller should itself call vnode_pager_setsize() if
606  * function returned true.  If nsizep is NULL, function tries to call
607  * vnode_pager_setsize() itself if needed and possible, and the nfs
608  * node is unlocked unconditionally, the return value is not useful.
609  */
610 bool
611 ncl_pager_setsize(struct vnode *vp, u_quad_t *nsizep)
612 {
613 	struct nfsnode *np;
614 	vm_object_t object;
615 	struct vattr *vap;
616 	u_quad_t nsize;
617 	bool setnsize;
618 
619 	np = VTONFS(vp);
620 	NFSASSERTNODE(np);
621 
622 	vap = &np->n_vattr.na_vattr;
623 	nsize = vap->va_size;
624 	object = vp->v_object;
625 	setnsize = false;
626 
627 	if (object != NULL && nsize != object->un_pager.vnp.vnp_size) {
628 		if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
629 		    (curthread->td_pflags2 & TDP2_SBPAGES) == 0)
630 			setnsize = true;
631 		else
632 			np->n_flag |= NVNSETSZSKIP;
633 	}
634 	if (nsizep == NULL) {
635 		NFSUNLOCKNODE(np);
636 		if (setnsize)
637 			vnode_pager_setsize(vp, nsize);
638 		setnsize = false;
639 	} else {
640 		*nsizep = nsize;
641 	}
642 	return (setnsize);
643 }
644 
645 /*
646  * Fill in the client id name. For these bytes:
647  * 1 - they must be unique
648  * 2 - they should be persistent across client reboots
649  * 1 is more critical than 2
650  * Use the mount point's unique id plus either the uuid or, if that
651  * isn't set, random junk.
652  */
653 void
654 nfscl_fillclid(u_int64_t clval, char *uuid, u_int8_t *cp, u_int16_t idlen)
655 {
656 	int uuidlen;
657 
658 	/*
659 	 * First, put in the 64bit mount point identifier.
660 	 */
661 	if (idlen >= sizeof (u_int64_t)) {
662 		NFSBCOPY((caddr_t)&clval, cp, sizeof (u_int64_t));
663 		cp += sizeof (u_int64_t);
664 		idlen -= sizeof (u_int64_t);
665 	}
666 
667 	/*
668 	 * If uuid is non-zero length, use it.
669 	 */
670 	uuidlen = strlen(uuid);
671 	if (uuidlen > 0 && idlen >= uuidlen) {
672 		NFSBCOPY(uuid, cp, uuidlen);
673 		cp += uuidlen;
674 		idlen -= uuidlen;
675 	}
676 
677 	/*
678 	 * This only normally happens if the uuid isn't set.
679 	 */
680 	while (idlen > 0) {
681 		*cp++ = (u_int8_t)(arc4random() % 256);
682 		idlen--;
683 	}
684 }
685 
686 /*
687  * Fill in a lock owner name. For now, pid + the process's creation time.
688  */
689 void
690 nfscl_filllockowner(void *id, u_int8_t *cp, int flags)
691 {
692 	union {
693 		u_int32_t	lval;
694 		u_int8_t	cval[4];
695 	} tl;
696 	struct proc *p;
697 
698 	if (id == NULL) {
699 		/* Return the single open_owner of all 0 bytes. */
700 		bzero(cp, NFSV4CL_LOCKNAMELEN);
701 		return;
702 	}
703 	if ((flags & F_POSIX) != 0) {
704 		p = (struct proc *)id;
705 		tl.lval = p->p_pid;
706 		*cp++ = tl.cval[0];
707 		*cp++ = tl.cval[1];
708 		*cp++ = tl.cval[2];
709 		*cp++ = tl.cval[3];
710 		tl.lval = p->p_stats->p_start.tv_sec;
711 		*cp++ = tl.cval[0];
712 		*cp++ = tl.cval[1];
713 		*cp++ = tl.cval[2];
714 		*cp++ = tl.cval[3];
715 		tl.lval = p->p_stats->p_start.tv_usec;
716 		*cp++ = tl.cval[0];
717 		*cp++ = tl.cval[1];
718 		*cp++ = tl.cval[2];
719 		*cp = tl.cval[3];
720 	} else if ((flags & F_FLOCK) != 0) {
721 		bcopy(&id, cp, sizeof(id));
722 		bzero(&cp[sizeof(id)], NFSV4CL_LOCKNAMELEN - sizeof(id));
723 	} else {
724 		printf("nfscl_filllockowner: not F_POSIX or F_FLOCK\n");
725 		bzero(cp, NFSV4CL_LOCKNAMELEN);
726 	}
727 }
728 
729 /*
730  * Find the parent process for the thread passed in as an argument.
731  * If none exists, return NULL, otherwise return a thread for the parent.
732  * (Can be any of the threads, since it is only used for td->td_proc.)
733  */
734 NFSPROC_T *
735 nfscl_getparent(struct thread *td)
736 {
737 	struct proc *p;
738 	struct thread *ptd;
739 
740 	if (td == NULL)
741 		return (NULL);
742 	p = td->td_proc;
743 	if (p->p_pid == 0)
744 		return (NULL);
745 	p = p->p_pptr;
746 	if (p == NULL)
747 		return (NULL);
748 	ptd = TAILQ_FIRST(&p->p_threads);
749 	return (ptd);
750 }
751 
752 /*
753  * Start up the renew kernel thread.
754  */
755 static void
756 start_nfscl(void *arg)
757 {
758 	struct nfsclclient *clp;
759 	struct thread *td;
760 
761 	clp = (struct nfsclclient *)arg;
762 	td = TAILQ_FIRST(&clp->nfsc_renewthread->p_threads);
763 	nfscl_renewthread(clp, td);
764 	kproc_exit(0);
765 }
766 
767 void
768 nfscl_start_renewthread(struct nfsclclient *clp)
769 {
770 
771 	kproc_create(start_nfscl, (void *)clp, &clp->nfsc_renewthread, 0, 0,
772 	    "nfscl");
773 }
774 
775 /*
776  * Handle wcc_data.
777  * For NFSv4, it assumes that nfsv4_wccattr() was used to set up the getattr
778  * as the first Op after PutFH.
779  * (For NFSv4, the postop attributes are after the Op, so they can't be
780  *  parsed here. A separate call to nfscl_postop_attr() is required.)
781  */
782 int
783 nfscl_wcc_data(struct nfsrv_descript *nd, struct vnode *vp,
784     struct nfsvattr *nap, int *flagp, int *wccflagp, uint64_t *repsizep)
785 {
786 	u_int32_t *tl;
787 	struct nfsnode *np = VTONFS(vp);
788 	struct nfsvattr nfsva;
789 	int error = 0;
790 
791 	if (wccflagp != NULL)
792 		*wccflagp = 0;
793 	if (nd->nd_flag & ND_NFSV3) {
794 		*flagp = 0;
795 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
796 		if (*tl == newnfs_true) {
797 			NFSM_DISSECT(tl, u_int32_t *, 6 * NFSX_UNSIGNED);
798 			if (wccflagp != NULL) {
799 				NFSLOCKNODE(np);
800 				*wccflagp = (np->n_mtime.tv_sec ==
801 				    fxdr_unsigned(u_int32_t, *(tl + 2)) &&
802 				    np->n_mtime.tv_nsec ==
803 				    fxdr_unsigned(u_int32_t, *(tl + 3)));
804 				NFSUNLOCKNODE(np);
805 			}
806 		}
807 		error = nfscl_postop_attr(nd, nap, flagp);
808 		if (wccflagp != NULL && *flagp == 0)
809 			*wccflagp = 0;
810 	} else if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR))
811 	    == (ND_NFSV4 | ND_V4WCCATTR)) {
812 		error = nfsv4_loadattr(nd, NULL, &nfsva, NULL,
813 		    NULL, 0, NULL, NULL, NULL, NULL, NULL, 0,
814 		    NULL, NULL, NULL, NULL, NULL);
815 		if (error)
816 			return (error);
817 		/*
818 		 * Get rid of Op# and status for next op.
819 		 */
820 		NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
821 		if (*++tl)
822 			nd->nd_flag |= ND_NOMOREDATA;
823 		if (repsizep != NULL)
824 			*repsizep = nfsva.na_size;
825 		if (wccflagp != NULL &&
826 		    nfsva.na_vattr.va_mtime.tv_sec != 0) {
827 			NFSLOCKNODE(np);
828 			*wccflagp = (np->n_mtime.tv_sec ==
829 			    nfsva.na_vattr.va_mtime.tv_sec &&
830 			    np->n_mtime.tv_nsec ==
831 			    nfsva.na_vattr.va_mtime.tv_sec);
832 			NFSUNLOCKNODE(np);
833 		}
834 	}
835 nfsmout:
836 	return (error);
837 }
838 
839 /*
840  * Get postop attributes.
841  */
842 int
843 nfscl_postop_attr(struct nfsrv_descript *nd, struct nfsvattr *nap, int *retp)
844 {
845 	u_int32_t *tl;
846 	int error = 0;
847 
848 	*retp = 0;
849 	if (nd->nd_flag & ND_NOMOREDATA)
850 		return (error);
851 	if (nd->nd_flag & ND_NFSV3) {
852 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
853 		*retp = fxdr_unsigned(int, *tl);
854 	} else if (nd->nd_flag & ND_NFSV4) {
855 		/*
856 		 * For NFSv4, the postop attr are at the end, so no point
857 		 * in looking if nd_repstat != 0.
858 		 */
859 		if (!nd->nd_repstat) {
860 			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
861 			if (*(tl + 1))
862 				/* should never happen since nd_repstat != 0 */
863 				nd->nd_flag |= ND_NOMOREDATA;
864 			else
865 				*retp = 1;
866 		}
867 	} else if (!nd->nd_repstat) {
868 		/* For NFSv2, the attributes are here iff nd_repstat == 0 */
869 		*retp = 1;
870 	}
871 	if (*retp) {
872 		error = nfsm_loadattr(nd, nap);
873 		if (error)
874 			*retp = 0;
875 	}
876 nfsmout:
877 	return (error);
878 }
879 
880 /*
881  * nfscl_request() - mostly a wrapper for newnfs_request().
882  */
883 int
884 nfscl_request(struct nfsrv_descript *nd, struct vnode *vp, NFSPROC_T *p,
885     struct ucred *cred)
886 {
887 	int ret, vers;
888 	struct nfsmount *nmp;
889 
890 	nmp = VFSTONFS(vp->v_mount);
891 	if (nd->nd_flag & ND_NFSV4)
892 		vers = NFS_VER4;
893 	else if (nd->nd_flag & ND_NFSV3)
894 		vers = NFS_VER3;
895 	else
896 		vers = NFS_VER2;
897 	ret = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, vp, p, cred,
898 		NFS_PROG, vers, NULL, 1, NULL, NULL);
899 	return (ret);
900 }
901 
902 /*
903  * fill in this bsden's variant of statfs using nfsstatfs.
904  */
905 void
906 nfscl_loadsbinfo(struct nfsmount *nmp, struct nfsstatfs *sfp, void *statfs)
907 {
908 	struct statfs *sbp = (struct statfs *)statfs;
909 
910 	if (nmp->nm_flag & (NFSMNT_NFSV3 | NFSMNT_NFSV4)) {
911 		sbp->f_bsize = NFS_FABLKSIZE;
912 		sbp->f_blocks = sfp->sf_tbytes / NFS_FABLKSIZE;
913 		sbp->f_bfree = sfp->sf_fbytes / NFS_FABLKSIZE;
914 		/*
915 		 * Although sf_abytes is uint64_t and f_bavail is int64_t,
916 		 * the value after dividing by NFS_FABLKSIZE is small
917 		 * enough that it will fit in 63bits, so it is ok to
918 		 * assign it to f_bavail without fear that it will become
919 		 * negative.
920 		 */
921 		sbp->f_bavail = sfp->sf_abytes / NFS_FABLKSIZE;
922 		sbp->f_files = sfp->sf_tfiles;
923 		/* Since f_ffree is int64_t, clip it to 63bits. */
924 		if (sfp->sf_ffiles > INT64_MAX)
925 			sbp->f_ffree = INT64_MAX;
926 		else
927 			sbp->f_ffree = sfp->sf_ffiles;
928 	} else if ((nmp->nm_flag & NFSMNT_NFSV4) == 0) {
929 		/*
930 		 * The type casts to (int32_t) ensure that this code is
931 		 * compatible with the old NFS client, in that it will
932 		 * propagate bit31 to the high order bits. This may or may
933 		 * not be correct for NFSv2, but since it is a legacy
934 		 * environment, I'd rather retain backwards compatibility.
935 		 */
936 		sbp->f_bsize = (int32_t)sfp->sf_bsize;
937 		sbp->f_blocks = (int32_t)sfp->sf_blocks;
938 		sbp->f_bfree = (int32_t)sfp->sf_bfree;
939 		sbp->f_bavail = (int32_t)sfp->sf_bavail;
940 		sbp->f_files = 0;
941 		sbp->f_ffree = 0;
942 	}
943 }
944 
945 /*
946  * Use the fsinfo stuff to update the mount point.
947  */
948 void
949 nfscl_loadfsinfo(struct nfsmount *nmp, struct nfsfsinfo *fsp)
950 {
951 
952 	if ((nmp->nm_wsize == 0 || fsp->fs_wtpref < nmp->nm_wsize) &&
953 	    fsp->fs_wtpref >= NFS_FABLKSIZE)
954 		nmp->nm_wsize = (fsp->fs_wtpref + NFS_FABLKSIZE - 1) &
955 		    ~(NFS_FABLKSIZE - 1);
956 	if (fsp->fs_wtmax < nmp->nm_wsize && fsp->fs_wtmax > 0) {
957 		nmp->nm_wsize = fsp->fs_wtmax & ~(NFS_FABLKSIZE - 1);
958 		if (nmp->nm_wsize == 0)
959 			nmp->nm_wsize = fsp->fs_wtmax;
960 	}
961 	if (nmp->nm_wsize < NFS_FABLKSIZE)
962 		nmp->nm_wsize = NFS_FABLKSIZE;
963 	if ((nmp->nm_rsize == 0 || fsp->fs_rtpref < nmp->nm_rsize) &&
964 	    fsp->fs_rtpref >= NFS_FABLKSIZE)
965 		nmp->nm_rsize = (fsp->fs_rtpref + NFS_FABLKSIZE - 1) &
966 		    ~(NFS_FABLKSIZE - 1);
967 	if (fsp->fs_rtmax < nmp->nm_rsize && fsp->fs_rtmax > 0) {
968 		nmp->nm_rsize = fsp->fs_rtmax & ~(NFS_FABLKSIZE - 1);
969 		if (nmp->nm_rsize == 0)
970 			nmp->nm_rsize = fsp->fs_rtmax;
971 	}
972 	if (nmp->nm_rsize < NFS_FABLKSIZE)
973 		nmp->nm_rsize = NFS_FABLKSIZE;
974 	if ((nmp->nm_readdirsize == 0 || fsp->fs_dtpref < nmp->nm_readdirsize)
975 	    && fsp->fs_dtpref >= NFS_DIRBLKSIZ)
976 		nmp->nm_readdirsize = (fsp->fs_dtpref + NFS_DIRBLKSIZ - 1) &
977 		    ~(NFS_DIRBLKSIZ - 1);
978 	if (fsp->fs_rtmax < nmp->nm_readdirsize && fsp->fs_rtmax > 0) {
979 		nmp->nm_readdirsize = fsp->fs_rtmax & ~(NFS_DIRBLKSIZ - 1);
980 		if (nmp->nm_readdirsize == 0)
981 			nmp->nm_readdirsize = fsp->fs_rtmax;
982 	}
983 	if (nmp->nm_readdirsize < NFS_DIRBLKSIZ)
984 		nmp->nm_readdirsize = NFS_DIRBLKSIZ;
985 	if (fsp->fs_maxfilesize > 0 &&
986 	    fsp->fs_maxfilesize < nmp->nm_maxfilesize)
987 		nmp->nm_maxfilesize = fsp->fs_maxfilesize;
988 	nmp->nm_mountp->mnt_stat.f_iosize = newnfs_iosize(nmp);
989 	nmp->nm_state |= NFSSTA_GOTFSINFO;
990 }
991 
992 /*
993  * Lookups source address which should be used to communicate with
994  * @nmp and stores it inside @pdst.
995  *
996  * Returns 0 on success.
997  */
998 u_int8_t *
999 nfscl_getmyip(struct nfsmount *nmp, struct in6_addr *paddr, int *isinet6p)
1000 {
1001 #if defined(INET6) || defined(INET)
1002 	int fibnum;
1003 
1004 	fibnum = curthread->td_proc->p_fibnum;
1005 #endif
1006 #ifdef INET
1007 	if (nmp->nm_nam->sa_family == AF_INET) {
1008 		struct epoch_tracker et;
1009 		struct nhop_object *nh;
1010 		struct sockaddr_in *sin;
1011 		struct in_addr addr = {};
1012 
1013 		sin = (struct sockaddr_in *)nmp->nm_nam;
1014 		NET_EPOCH_ENTER(et);
1015 		CURVNET_SET(CRED_TO_VNET(nmp->nm_sockreq.nr_cred));
1016 		nh = fib4_lookup(fibnum, sin->sin_addr, 0, NHR_NONE, 0);
1017 		CURVNET_RESTORE();
1018 		if (nh != NULL)
1019 			addr = IA_SIN(ifatoia(nh->nh_ifa))->sin_addr;
1020 		NET_EPOCH_EXIT(et);
1021 		if (nh == NULL)
1022 			return (NULL);
1023 
1024 		if (IN_LOOPBACK(ntohl(addr.s_addr))) {
1025 			/* Ignore loopback addresses */
1026 			return (NULL);
1027 		}
1028 
1029 		*isinet6p = 0;
1030 		*((struct in_addr *)paddr) = addr;
1031 
1032 		return (u_int8_t *)paddr;
1033 	}
1034 #endif
1035 #ifdef INET6
1036 	if (nmp->nm_nam->sa_family == AF_INET6) {
1037 		struct epoch_tracker et;
1038 		struct sockaddr_in6 *sin6;
1039 		int error;
1040 
1041 		sin6 = (struct sockaddr_in6 *)nmp->nm_nam;
1042 
1043 		NET_EPOCH_ENTER(et);
1044 		CURVNET_SET(CRED_TO_VNET(nmp->nm_sockreq.nr_cred));
1045 		error = in6_selectsrc_addr(fibnum, &sin6->sin6_addr,
1046 		    sin6->sin6_scope_id, NULL, paddr, NULL);
1047 		CURVNET_RESTORE();
1048 		NET_EPOCH_EXIT(et);
1049 		if (error != 0)
1050 			return (NULL);
1051 
1052 		if (IN6_IS_ADDR_LOOPBACK(paddr))
1053 			return (NULL);
1054 
1055 		/* Scope is embedded in */
1056 		*isinet6p = 1;
1057 
1058 		return (u_int8_t *)paddr;
1059 	}
1060 #endif
1061 	return (NULL);
1062 }
1063 
1064 /*
1065  * Copy NFS uid, gids from the cred structure.
1066  */
1067 void
1068 newnfs_copyincred(struct ucred *cr, struct nfscred *nfscr)
1069 {
1070 	int i;
1071 
1072 	KASSERT(cr->cr_ngroups >= 0,
1073 	    ("newnfs_copyincred: negative cr_ngroups"));
1074 	nfscr->nfsc_uid = cr->cr_uid;
1075 	nfscr->nfsc_ngroups = MIN(cr->cr_ngroups, NFS_MAXGRPS + 1);
1076 	for (i = 0; i < nfscr->nfsc_ngroups; i++)
1077 		nfscr->nfsc_groups[i] = cr->cr_groups[i];
1078 }
1079 
1080 /*
1081  * Do any client specific initialization.
1082  */
1083 void
1084 nfscl_init(void)
1085 {
1086 	static int inited = 0;
1087 
1088 	if (inited)
1089 		return;
1090 	inited = 1;
1091 	nfscl_inited = 1;
1092 	ncl_pbuf_zone = pbuf_zsecond_create("nfspbuf", nswbuf / 2);
1093 }
1094 
1095 /*
1096  * Check each of the attributes to be set, to ensure they aren't already
1097  * the correct value. Disable setting ones already correct.
1098  */
1099 int
1100 nfscl_checksattr(struct vattr *vap, struct nfsvattr *nvap)
1101 {
1102 
1103 	if (vap->va_mode != (mode_t)VNOVAL) {
1104 		if (vap->va_mode == nvap->na_mode)
1105 			vap->va_mode = (mode_t)VNOVAL;
1106 	}
1107 	if (vap->va_uid != (uid_t)VNOVAL) {
1108 		if (vap->va_uid == nvap->na_uid)
1109 			vap->va_uid = (uid_t)VNOVAL;
1110 	}
1111 	if (vap->va_gid != (gid_t)VNOVAL) {
1112 		if (vap->va_gid == nvap->na_gid)
1113 			vap->va_gid = (gid_t)VNOVAL;
1114 	}
1115 	if (vap->va_size != VNOVAL) {
1116 		if (vap->va_size == nvap->na_size)
1117 			vap->va_size = VNOVAL;
1118 	}
1119 
1120 	/*
1121 	 * We are normally called with only a partially initialized
1122 	 * VAP.  Since the NFSv3 spec says that server may use the
1123 	 * file attributes to store the verifier, the spec requires
1124 	 * us to do a SETATTR RPC. FreeBSD servers store the verifier
1125 	 * in atime, but we can't really assume that all servers will
1126 	 * so we ensure that our SETATTR sets both atime and mtime.
1127 	 * Set the VA_UTIMES_NULL flag for this case, so that
1128 	 * the server's time will be used.  This is needed to
1129 	 * work around a bug in some Solaris servers, where
1130 	 * setting the time TOCLIENT causes the Setattr RPC
1131 	 * to return NFS_OK, but not set va_mode.
1132 	 */
1133 	if (vap->va_mtime.tv_sec == VNOVAL) {
1134 		vfs_timestamp(&vap->va_mtime);
1135 		vap->va_vaflags |= VA_UTIMES_NULL;
1136 	}
1137 	if (vap->va_atime.tv_sec == VNOVAL)
1138 		vap->va_atime = vap->va_mtime;
1139 	return (1);
1140 }
1141 
1142 /*
1143  * Map nfsv4 errors to errno.h errors.
1144  * The uid and gid arguments are only used for NFSERR_BADOWNER and that
1145  * error should only be returned for the Open, Create and Setattr Ops.
1146  * As such, most calls can just pass in 0 for those arguments.
1147  */
1148 int
1149 nfscl_maperr(struct thread *td, int error, uid_t uid, gid_t gid)
1150 {
1151 	struct proc *p;
1152 
1153 	if (error < 10000 || error >= NFSERR_STALEWRITEVERF)
1154 		return (error);
1155 	if (td != NULL)
1156 		p = td->td_proc;
1157 	else
1158 		p = NULL;
1159 	switch (error) {
1160 	case NFSERR_BADOWNER:
1161 		tprintf(p, LOG_INFO,
1162 		    "No name and/or group mapping for uid,gid:(%d,%d)\n",
1163 		    uid, gid);
1164 		return (EPERM);
1165 	case NFSERR_BADNAME:
1166 	case NFSERR_BADCHAR:
1167 		printf("nfsv4 char/name not handled by server\n");
1168 		return (ENOENT);
1169 	case NFSERR_STALECLIENTID:
1170 	case NFSERR_STALESTATEID:
1171 	case NFSERR_EXPIRED:
1172 	case NFSERR_BADSTATEID:
1173 	case NFSERR_BADSESSION:
1174 		printf("nfsv4 recover err returned %d\n", error);
1175 		return (EIO);
1176 	case NFSERR_BADHANDLE:
1177 	case NFSERR_SERVERFAULT:
1178 	case NFSERR_BADTYPE:
1179 	case NFSERR_FHEXPIRED:
1180 	case NFSERR_RESOURCE:
1181 	case NFSERR_MOVED:
1182 	case NFSERR_NOFILEHANDLE:
1183 	case NFSERR_MINORVERMISMATCH:
1184 	case NFSERR_OLDSTATEID:
1185 	case NFSERR_BADSEQID:
1186 	case NFSERR_LEASEMOVED:
1187 	case NFSERR_RECLAIMBAD:
1188 	case NFSERR_BADXDR:
1189 	case NFSERR_OPILLEGAL:
1190 		printf("nfsv4 client/server protocol prob err=%d\n",
1191 		    error);
1192 		return (EIO);
1193 	default:
1194 		tprintf(p, LOG_INFO, "nfsv4 err=%d\n", error);
1195 		return (EIO);
1196 	};
1197 }
1198 
1199 /*
1200  * Check to see if the process for this owner exists. Return 1 if it doesn't
1201  * and 0 otherwise.
1202  */
1203 int
1204 nfscl_procdoesntexist(u_int8_t *own)
1205 {
1206 	union {
1207 		u_int32_t	lval;
1208 		u_int8_t	cval[4];
1209 	} tl;
1210 	struct proc *p;
1211 	pid_t pid;
1212 	int i, ret = 0;
1213 
1214 	/* For the single open_owner of all 0 bytes, just return 0. */
1215 	for (i = 0; i < NFSV4CL_LOCKNAMELEN; i++)
1216 		if (own[i] != 0)
1217 			break;
1218 	if (i == NFSV4CL_LOCKNAMELEN)
1219 		return (0);
1220 
1221 	tl.cval[0] = *own++;
1222 	tl.cval[1] = *own++;
1223 	tl.cval[2] = *own++;
1224 	tl.cval[3] = *own++;
1225 	pid = tl.lval;
1226 	p = pfind_any_locked(pid);
1227 	if (p == NULL)
1228 		return (1);
1229 	if (p->p_stats == NULL) {
1230 		PROC_UNLOCK(p);
1231 		return (0);
1232 	}
1233 	tl.cval[0] = *own++;
1234 	tl.cval[1] = *own++;
1235 	tl.cval[2] = *own++;
1236 	tl.cval[3] = *own++;
1237 	if (tl.lval != p->p_stats->p_start.tv_sec) {
1238 		ret = 1;
1239 	} else {
1240 		tl.cval[0] = *own++;
1241 		tl.cval[1] = *own++;
1242 		tl.cval[2] = *own++;
1243 		tl.cval[3] = *own;
1244 		if (tl.lval != p->p_stats->p_start.tv_usec)
1245 			ret = 1;
1246 	}
1247 	PROC_UNLOCK(p);
1248 	return (ret);
1249 }
1250 
1251 /*
1252  * - nfs pseudo system call for the client
1253  */
1254 /*
1255  * MPSAFE
1256  */
1257 static int
1258 nfssvc_nfscl(struct thread *td, struct nfssvc_args *uap)
1259 {
1260 	struct file *fp;
1261 	struct nfscbd_args nfscbdarg;
1262 	struct nfsd_nfscbd_args nfscbdarg2;
1263 	struct nameidata nd;
1264 	struct nfscl_dumpmntopts dumpmntopts;
1265 	cap_rights_t rights;
1266 	char *buf;
1267 	int error;
1268 	struct mount *mp;
1269 	struct nfsmount *nmp;
1270 
1271 	if (uap->flag & NFSSVC_CBADDSOCK) {
1272 		error = copyin(uap->argp, (caddr_t)&nfscbdarg, sizeof(nfscbdarg));
1273 		if (error)
1274 			return (error);
1275 		/*
1276 		 * Since we don't know what rights might be required,
1277 		 * pretend that we need them all. It is better to be too
1278 		 * careful than too reckless.
1279 		 */
1280 		error = fget(td, nfscbdarg.sock,
1281 		    cap_rights_init_one(&rights, CAP_SOCK_CLIENT), &fp);
1282 		if (error)
1283 			return (error);
1284 		if (fp->f_type != DTYPE_SOCKET) {
1285 			fdrop(fp, td);
1286 			return (EPERM);
1287 		}
1288 		error = nfscbd_addsock(fp);
1289 		fdrop(fp, td);
1290 		if (!error && nfscl_enablecallb == 0) {
1291 			nfsv4_cbport = nfscbdarg.port;
1292 			nfscl_enablecallb = 1;
1293 		}
1294 	} else if (uap->flag & NFSSVC_NFSCBD) {
1295 		if (uap->argp == NULL)
1296 			return (EINVAL);
1297 		error = copyin(uap->argp, (caddr_t)&nfscbdarg2,
1298 		    sizeof(nfscbdarg2));
1299 		if (error)
1300 			return (error);
1301 		error = nfscbd_nfsd(td, &nfscbdarg2);
1302 	} else if (uap->flag & NFSSVC_DUMPMNTOPTS) {
1303 		error = copyin(uap->argp, &dumpmntopts, sizeof(dumpmntopts));
1304 		if (error == 0 && (dumpmntopts.ndmnt_blen < 256 ||
1305 		    dumpmntopts.ndmnt_blen > 1024))
1306 			error = EINVAL;
1307 		if (error == 0)
1308 			error = nfsrv_lookupfilename(&nd,
1309 			    dumpmntopts.ndmnt_fname, td);
1310 		if (error == 0 && strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name,
1311 		    "nfs") != 0) {
1312 			vput(nd.ni_vp);
1313 			error = EINVAL;
1314 		}
1315 		if (error == 0) {
1316 			buf = malloc(dumpmntopts.ndmnt_blen, M_TEMP, M_WAITOK |
1317 			    M_ZERO);
1318 			nfscl_retopts(VFSTONFS(nd.ni_vp->v_mount), buf,
1319 			    dumpmntopts.ndmnt_blen);
1320 			vput(nd.ni_vp);
1321 			error = copyout(buf, dumpmntopts.ndmnt_buf,
1322 			    dumpmntopts.ndmnt_blen);
1323 			free(buf, M_TEMP);
1324 		}
1325 	} else if (uap->flag & NFSSVC_FORCEDISM) {
1326 		buf = malloc(MNAMELEN + 1, M_TEMP, M_WAITOK);
1327 		error = copyinstr(uap->argp, buf, MNAMELEN + 1, NULL);
1328 		if (error == 0) {
1329 			nmp = NULL;
1330 			mtx_lock(&mountlist_mtx);
1331 			TAILQ_FOREACH(mp, &mountlist, mnt_list) {
1332 				if (strcmp(mp->mnt_stat.f_mntonname, buf) ==
1333 				    0 && strcmp(mp->mnt_stat.f_fstypename,
1334 				    "nfs") == 0 && mp->mnt_data != NULL) {
1335 					nmp = VFSTONFS(mp);
1336 					NFSDDSLOCK();
1337 					if (nfsv4_findmirror(nmp) != NULL) {
1338 						NFSDDSUNLOCK();
1339 						error = ENXIO;
1340 						nmp = NULL;
1341 						break;
1342 					}
1343 					mtx_lock(&nmp->nm_mtx);
1344 					if ((nmp->nm_privflag &
1345 					    NFSMNTP_FORCEDISM) == 0) {
1346 						nmp->nm_privflag |=
1347 						   (NFSMNTP_FORCEDISM |
1348 						    NFSMNTP_CANCELRPCS);
1349 						mtx_unlock(&nmp->nm_mtx);
1350 					} else {
1351 						mtx_unlock(&nmp->nm_mtx);
1352 						nmp = NULL;
1353 					}
1354 					NFSDDSUNLOCK();
1355 					break;
1356 				}
1357 			}
1358 			mtx_unlock(&mountlist_mtx);
1359 
1360 			if (nmp != NULL) {
1361 				/*
1362 				 * Call newnfs_nmcancelreqs() to cause
1363 				 * any RPCs in progress on the mount point to
1364 				 * fail.
1365 				 * This will cause any process waiting for an
1366 				 * RPC to complete while holding a vnode lock
1367 				 * on the mounted-on vnode (such as "df" or
1368 				 * a non-forced "umount") to fail.
1369 				 * This will unlock the mounted-on vnode so
1370 				 * a forced dismount can succeed.
1371 				 * Then clear NFSMNTP_CANCELRPCS and wakeup(),
1372 				 * so that nfs_unmount() can complete.
1373 				 */
1374 				newnfs_nmcancelreqs(nmp);
1375 				mtx_lock(&nmp->nm_mtx);
1376 				nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
1377 				wakeup(nmp);
1378 				mtx_unlock(&nmp->nm_mtx);
1379 			} else if (error == 0)
1380 				error = EINVAL;
1381 		}
1382 		free(buf, M_TEMP);
1383 	} else {
1384 		error = EINVAL;
1385 	}
1386 	return (error);
1387 }
1388 
1389 extern int (*nfsd_call_nfscl)(struct thread *, struct nfssvc_args *);
1390 
1391 /*
1392  * Called once to initialize data structures...
1393  */
1394 static int
1395 nfscl_modevent(module_t mod, int type, void *data)
1396 {
1397 	int error = 0;
1398 	static int loaded = 0;
1399 
1400 	switch (type) {
1401 	case MOD_LOAD:
1402 		if (loaded)
1403 			return (0);
1404 		newnfs_portinit();
1405 		mtx_init(&ncl_iod_mutex, "ncl_iod_mutex", NULL, MTX_DEF);
1406 		nfscl_init();
1407 		NFSD_LOCK();
1408 		nfsrvd_cbinit(0);
1409 		NFSD_UNLOCK();
1410 		ncl_call_invalcaches = ncl_invalcaches;
1411 		nfsd_call_nfscl = nfssvc_nfscl;
1412 		loaded = 1;
1413 		break;
1414 
1415 	case MOD_UNLOAD:
1416 		if (nfs_numnfscbd != 0) {
1417 			error = EBUSY;
1418 			break;
1419 		}
1420 
1421 		/*
1422 		 * XXX: Unloading of nfscl module is unsupported.
1423 		 */
1424 #if 0
1425 		ncl_call_invalcaches = NULL;
1426 		nfsd_call_nfscl = NULL;
1427 		uma_zdestroy(ncl_pbuf_zone);
1428 		/* and get rid of the mutexes */
1429 		mtx_destroy(&ncl_iod_mutex);
1430 		loaded = 0;
1431 		break;
1432 #else
1433 		/* FALLTHROUGH */
1434 #endif
1435 	default:
1436 		error = EOPNOTSUPP;
1437 		break;
1438 	}
1439 	return error;
1440 }
1441 static moduledata_t nfscl_mod = {
1442 	"nfscl",
1443 	nfscl_modevent,
1444 	NULL,
1445 };
1446 /*
1447  * This is the main module declaration for the NFS client.  The
1448  * nfscl_modevent() function is needed to ensure that the module
1449  * cannot be unloaded, among other things.
1450  * There is also a module declaration in sys/fs/nfsclient/nfs_clvfsops.c
1451  * for the name "nfs" within the VFS_SET() macro that defines the "nfs"
1452  * file system type.
1453  */
1454 DECLARE_MODULE(nfscl, nfscl_mod, SI_SUB_VFS, SI_ORDER_FIRST);
1455 
1456 /* So that loader and kldload(2) can find us, wherever we are.. */
1457 MODULE_VERSION(nfscl, 1);
1458 MODULE_DEPEND(nfscl, nfscommon, 1, 1, 1);
1459 MODULE_DEPEND(nfscl, krpc, 1, 1, 1);
1460 MODULE_DEPEND(nfscl, nfssvc, 1, 1, 1);
1461 MODULE_DEPEND(nfscl, xdr, 1, 1, 1);
1462