xref: /netbsd-src/sys/nfs/nfs_socket.c (revision 1ca06f9c9235889e2ff6dc77279d01d151d70a9a)
1 /*	$NetBSD: nfs_socket.c,v 1.183 2009/12/06 18:00:15 dyoung Exp $	*/
2 
3 /*
4  * Copyright (c) 1989, 1991, 1993, 1995
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  *	@(#)nfs_socket.c	8.5 (Berkeley) 3/30/95
35  */
36 
37 /*
38  * Socket operations for use by nfs
39  */
40 
41 #include <sys/cdefs.h>
42 __KERNEL_RCSID(0, "$NetBSD: nfs_socket.c,v 1.183 2009/12/06 18:00:15 dyoung Exp $");
43 
44 #ifdef _KERNEL_OPT
45 #include "fs_nfs.h"
46 #include "opt_nfs.h"
47 #include "opt_mbuftrace.h"
48 #endif
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/evcnt.h>
53 #include <sys/callout.h>
54 #include <sys/proc.h>
55 #include <sys/mount.h>
56 #include <sys/kernel.h>
57 #include <sys/kmem.h>
58 #include <sys/mbuf.h>
59 #include <sys/vnode.h>
60 #include <sys/domain.h>
61 #include <sys/protosw.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/syslog.h>
65 #include <sys/tprintf.h>
66 #include <sys/namei.h>
67 #include <sys/signal.h>
68 #include <sys/signalvar.h>
69 #include <sys/kauth.h>
70 
71 #include <netinet/in.h>
72 #include <netinet/tcp.h>
73 
74 #include <nfs/rpcv2.h>
75 #include <nfs/nfsproto.h>
76 #include <nfs/nfs.h>
77 #include <nfs/xdr_subs.h>
78 #include <nfs/nfsm_subs.h>
79 #include <nfs/nfsmount.h>
80 #include <nfs/nfsnode.h>
81 #include <nfs/nfsrtt.h>
82 #include <nfs/nfs_var.h>
83 
84 #ifdef MBUFTRACE
85 struct mowner nfs_mowner = MOWNER_INIT("nfs","");
86 #endif
87 
88 /*
89  * Estimate rto for an nfs rpc sent via. an unreliable datagram.
90  * Use the mean and mean deviation of rtt for the appropriate type of rpc
91  * for the frequent rpcs and a default for the others.
92  * The justification for doing "other" this way is that these rpcs
93  * happen so infrequently that timer est. would probably be stale.
94  * Also, since many of these rpcs are
95  * non-idempotent, a conservative timeout is desired.
96  * getattr, lookup - A+2D
97  * read, write     - A+4D
98  * other           - nm_timeo
99  */
100 #define	NFS_RTO(n, t) \
101 	((t) == 0 ? (n)->nm_timeo : \
102 	 ((t) < 3 ? \
103 	  (((((n)->nm_srtt[t-1] + 3) >> 2) + (n)->nm_sdrtt[t-1] + 1) >> 1) : \
104 	  ((((n)->nm_srtt[t-1] + 7) >> 3) + (n)->nm_sdrtt[t-1] + 1)))
105 #define	NFS_SRTT(r)	(r)->r_nmp->nm_srtt[proct[(r)->r_procnum] - 1]
106 #define	NFS_SDRTT(r)	(r)->r_nmp->nm_sdrtt[proct[(r)->r_procnum] - 1]
107 /*
108  * External data, mostly RPC constants in XDR form
109  */
110 extern u_int32_t rpc_reply, rpc_msgdenied, rpc_mismatch, rpc_vers,
111 	rpc_auth_unix, rpc_msgaccepted, rpc_call, rpc_autherr,
112 	rpc_auth_kerb;
113 extern u_int32_t nfs_prog;
114 extern const int nfsv3_procid[NFS_NPROCS];
115 extern int nfs_ticks;
116 
117 #ifdef DEBUG
118 /*
119  * Avoid spamming the console with debugging messages.  We only print
120  * the nfs timer and reply error debugs every 10 seconds.
121  */
122 static const struct timeval nfs_err_interval = { 10, 0 };
123 static struct timeval nfs_reply_last_err_time;
124 static struct timeval nfs_timer_last_err_time;
125 #endif
126 
127 /*
128  * Defines which timer to use for the procnum.
129  * 0 - default
130  * 1 - getattr
131  * 2 - lookup
132  * 3 - read
133  * 4 - write
134  */
135 static const int proct[NFS_NPROCS] = {
136 	[NFSPROC_NULL] = 0,
137 	[NFSPROC_GETATTR] = 1,
138 	[NFSPROC_SETATTR] = 0,
139 	[NFSPROC_LOOKUP] = 2,
140 	[NFSPROC_ACCESS] = 1,
141 	[NFSPROC_READLINK] = 3,
142 	[NFSPROC_READ] = 3,
143 	[NFSPROC_WRITE] = 4,
144 	[NFSPROC_CREATE] = 0,
145 	[NFSPROC_MKDIR] = 0,
146 	[NFSPROC_SYMLINK] = 0,
147 	[NFSPROC_MKNOD] = 0,
148 	[NFSPROC_REMOVE] = 0,
149 	[NFSPROC_RMDIR] = 0,
150 	[NFSPROC_RENAME] = 0,
151 	[NFSPROC_LINK] = 0,
152 	[NFSPROC_READDIR] = 3,
153 	[NFSPROC_READDIRPLUS] = 3,
154 	[NFSPROC_FSSTAT] = 0,
155 	[NFSPROC_FSINFO] = 0,
156 	[NFSPROC_PATHCONF] = 0,
157 	[NFSPROC_COMMIT] = 0,
158 	[NFSPROC_NOOP] = 0,
159 };
160 
161 /*
162  * There is a congestion window for outstanding rpcs maintained per mount
163  * point. The cwnd size is adjusted in roughly the way that:
164  * Van Jacobson, Congestion avoidance and Control, In "Proceedings of
165  * SIGCOMM '88". ACM, August 1988.
166  * describes for TCP. The cwnd size is chopped in half on a retransmit timeout
167  * and incremented by 1/cwnd when each rpc reply is received and a full cwnd
168  * of rpcs is in progress.
169  * (The sent count and cwnd are scaled for integer arith.)
170  * Variants of "slow start" were tried and were found to be too much of a
171  * performance hit (ave. rtt 3 times larger),
172  * I suspect due to the large rtt that nfs rpcs have.
173  */
174 #define	NFS_CWNDSCALE	256
175 #define	NFS_MAXCWND	(NFS_CWNDSCALE * 32)
176 static const int nfs_backoff[8] = { 2, 4, 8, 16, 32, 64, 128, 256, };
177 int nfsrtton = 0;
178 struct nfsrtt nfsrtt;
179 struct nfsreqhead nfs_reqq;
180 static callout_t nfs_timer_ch;
181 static struct evcnt nfs_timer_ev;
182 static struct evcnt nfs_timer_start_ev;
183 static struct evcnt nfs_timer_stop_ev;
184 static kmutex_t nfs_timer_lock;
185 static bool (*nfs_timer_srvvec)(void);
186 
187 #ifdef NFS
188 static int nfs_sndlock(struct nfsmount *, struct nfsreq *);
189 static void nfs_sndunlock(struct nfsmount *);
190 #endif
191 static int nfs_rcvlock(struct nfsmount *, struct nfsreq *);
192 static void nfs_rcvunlock(struct nfsmount *);
193 
194 /*
195  * Initialize sockets and congestion for a new NFS connection.
196  * We do not free the sockaddr if error.
197  */
198 int
199 nfs_connect(struct nfsmount *nmp, struct nfsreq *rep, struct lwp *l)
200 {
201 	struct socket *so;
202 	int error, rcvreserve, sndreserve;
203 	struct sockaddr *saddr;
204 	struct sockaddr_in *sin;
205 	struct sockaddr_in6 *sin6;
206 	struct mbuf *m;
207 	int val;
208 
209 	nmp->nm_so = NULL;
210 	saddr = mtod(nmp->nm_nam, struct sockaddr *);
211 	error = socreate(saddr->sa_family, &nmp->nm_so,
212 		nmp->nm_sotype, nmp->nm_soproto, l, NULL);
213 	if (error)
214 		goto bad;
215 	so = nmp->nm_so;
216 #ifdef MBUFTRACE
217 	so->so_mowner = &nfs_mowner;
218 	so->so_rcv.sb_mowner = &nfs_mowner;
219 	so->so_snd.sb_mowner = &nfs_mowner;
220 #endif
221 	nmp->nm_soflags = so->so_proto->pr_flags;
222 
223 	/*
224 	 * Some servers require that the client port be a reserved port number.
225 	 */
226 	if (saddr->sa_family == AF_INET && (nmp->nm_flag & NFSMNT_RESVPORT)) {
227 		val = IP_PORTRANGE_LOW;
228 
229 		if ((error = so_setsockopt(NULL, so, IPPROTO_IP, IP_PORTRANGE,
230 		    &val, sizeof(val))))
231 			goto bad;
232 		m = m_get(M_WAIT, MT_SONAME);
233 		MCLAIM(m, so->so_mowner);
234 		sin = mtod(m, struct sockaddr_in *);
235 		sin->sin_len = m->m_len = sizeof (struct sockaddr_in);
236 		sin->sin_family = AF_INET;
237 		sin->sin_addr.s_addr = INADDR_ANY;
238 		sin->sin_port = 0;
239 		error = sobind(so, m, &lwp0);
240 		m_freem(m);
241 		if (error)
242 			goto bad;
243 	}
244 	if (saddr->sa_family == AF_INET6 && (nmp->nm_flag & NFSMNT_RESVPORT)) {
245 		val = IPV6_PORTRANGE_LOW;
246 
247 		if ((error = so_setsockopt(NULL, so, IPPROTO_IPV6,
248 		    IPV6_PORTRANGE, &val, sizeof(val))))
249 			goto bad;
250 		m = m_get(M_WAIT, MT_SONAME);
251 		MCLAIM(m, so->so_mowner);
252 		sin6 = mtod(m, struct sockaddr_in6 *);
253 		memset(sin6, 0, sizeof(*sin6));
254 		sin6->sin6_len = m->m_len = sizeof (struct sockaddr_in6);
255 		sin6->sin6_family = AF_INET6;
256 		error = sobind(so, m, &lwp0);
257 		m_freem(m);
258 		if (error)
259 			goto bad;
260 	}
261 
262 	/*
263 	 * Protocols that do not require connections may be optionally left
264 	 * unconnected for servers that reply from a port other than NFS_PORT.
265 	 */
266 	solock(so);
267 	if (nmp->nm_flag & NFSMNT_NOCONN) {
268 		if (nmp->nm_soflags & PR_CONNREQUIRED) {
269 			sounlock(so);
270 			error = ENOTCONN;
271 			goto bad;
272 		}
273 	} else {
274 		error = soconnect(so, nmp->nm_nam, l);
275 		if (error) {
276 			sounlock(so);
277 			goto bad;
278 		}
279 
280 		/*
281 		 * Wait for the connection to complete. Cribbed from the
282 		 * connect system call but with the wait timing out so
283 		 * that interruptible mounts don't hang here for a long time.
284 		 */
285 		while ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
286 			(void)sowait(so, false, 2 * hz);
287 			if ((so->so_state & SS_ISCONNECTING) &&
288 			    so->so_error == 0 && rep &&
289 			    (error = nfs_sigintr(nmp, rep, rep->r_lwp)) != 0){
290 				so->so_state &= ~SS_ISCONNECTING;
291 				sounlock(so);
292 				goto bad;
293 			}
294 		}
295 		if (so->so_error) {
296 			error = so->so_error;
297 			so->so_error = 0;
298 			sounlock(so);
299 			goto bad;
300 		}
301 	}
302 	if (nmp->nm_flag & (NFSMNT_SOFT | NFSMNT_INT)) {
303 		so->so_rcv.sb_timeo = (5 * hz);
304 		so->so_snd.sb_timeo = (5 * hz);
305 	} else {
306 		/*
307 		 * enable receive timeout to detect server crash and reconnect.
308 		 * otherwise, we can be stuck in soreceive forever.
309 		 */
310 		so->so_rcv.sb_timeo = (5 * hz);
311 		so->so_snd.sb_timeo = 0;
312 	}
313 	if (nmp->nm_sotype == SOCK_DGRAM) {
314 		sndreserve = (nmp->nm_wsize + NFS_MAXPKTHDR) * 2;
315 		rcvreserve = (max(nmp->nm_rsize, nmp->nm_readdirsize) +
316 		    NFS_MAXPKTHDR) * 2;
317 	} else if (nmp->nm_sotype == SOCK_SEQPACKET) {
318 		sndreserve = (nmp->nm_wsize + NFS_MAXPKTHDR) * 2;
319 		rcvreserve = (max(nmp->nm_rsize, nmp->nm_readdirsize) +
320 		    NFS_MAXPKTHDR) * 2;
321 	} else {
322 		sounlock(so);
323 		if (nmp->nm_sotype != SOCK_STREAM)
324 			panic("nfscon sotype");
325 		if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
326 			val = 1;
327 			so_setsockopt(NULL, so, SOL_SOCKET, SO_KEEPALIVE, &val,
328 			    sizeof(val));
329 		}
330 		if (so->so_proto->pr_protocol == IPPROTO_TCP) {
331 			val = 1;
332 			so_setsockopt(NULL, so, IPPROTO_TCP, TCP_NODELAY, &val,
333 			    sizeof(val));
334 		}
335 		sndreserve = (nmp->nm_wsize + NFS_MAXPKTHDR +
336 		    sizeof (u_int32_t)) * 2;
337 		rcvreserve = (nmp->nm_rsize + NFS_MAXPKTHDR +
338 		    sizeof (u_int32_t)) * 2;
339 		solock(so);
340 	}
341 	error = soreserve(so, sndreserve, rcvreserve);
342 	if (error) {
343 		sounlock(so);
344 		goto bad;
345 	}
346 	so->so_rcv.sb_flags |= SB_NOINTR;
347 	so->so_snd.sb_flags |= SB_NOINTR;
348 	sounlock(so);
349 
350 	/* Initialize other non-zero congestion variables */
351 	nmp->nm_srtt[0] = nmp->nm_srtt[1] = nmp->nm_srtt[2] = nmp->nm_srtt[3] =
352 		NFS_TIMEO << 3;
353 	nmp->nm_sdrtt[0] = nmp->nm_sdrtt[1] = nmp->nm_sdrtt[2] =
354 		nmp->nm_sdrtt[3] = 0;
355 	nmp->nm_cwnd = NFS_MAXCWND / 2;	    /* Initial send window */
356 	nmp->nm_sent = 0;
357 	nmp->nm_timeouts = 0;
358 	return (0);
359 
360 bad:
361 	nfs_disconnect(nmp);
362 	return (error);
363 }
364 
365 /*
366  * Reconnect routine:
367  * Called when a connection is broken on a reliable protocol.
368  * - clean up the old socket
369  * - nfs_connect() again
370  * - set R_MUSTRESEND for all outstanding requests on mount point
371  * If this fails the mount point is DEAD!
372  * nb: Must be called with the nfs_sndlock() set on the mount point.
373  */
374 int
375 nfs_reconnect(struct nfsreq *rep)
376 {
377 	struct nfsreq *rp;
378 	struct nfsmount *nmp = rep->r_nmp;
379 	int error;
380 
381 	nfs_disconnect(nmp);
382 	while ((error = nfs_connect(nmp, rep, &lwp0)) != 0) {
383 		if (error == EINTR || error == ERESTART)
384 			return (EINTR);
385 		kpause("nfscn2", false, hz, NULL);
386 	}
387 
388 	/*
389 	 * Loop through outstanding request list and fix up all requests
390 	 * on old socket.
391 	 */
392 	TAILQ_FOREACH(rp, &nfs_reqq, r_chain) {
393 		if (rp->r_nmp == nmp) {
394 			if ((rp->r_flags & R_MUSTRESEND) == 0)
395 				rp->r_flags |= R_MUSTRESEND | R_REXMITTED;
396 			rp->r_rexmit = 0;
397 		}
398 	}
399 	return (0);
400 }
401 
402 /*
403  * NFS disconnect. Clean up and unlink.
404  */
405 void
406 nfs_disconnect(struct nfsmount *nmp)
407 {
408 	struct socket *so;
409 	int drain = 0;
410 
411 	if (nmp->nm_so) {
412 		so = nmp->nm_so;
413 		nmp->nm_so = NULL;
414 		solock(so);
415 		soshutdown(so, SHUT_RDWR);
416 		sounlock(so);
417 		drain = (nmp->nm_iflag & NFSMNT_DISMNT) != 0;
418 		if (drain) {
419 			/*
420 			 * soshutdown() above should wake up the current
421 			 * listener.
422 			 * Now wake up those waiting for the receive lock, and
423 			 * wait for them to go away unhappy, to prevent *nmp
424 			 * from evaporating while they're sleeping.
425 			 */
426 			mutex_enter(&nmp->nm_lock);
427 			while (nmp->nm_waiters > 0) {
428 				cv_broadcast(&nmp->nm_rcvcv);
429 				cv_broadcast(&nmp->nm_sndcv);
430 				cv_wait(&nmp->nm_disconcv, &nmp->nm_lock);
431 			}
432 			mutex_exit(&nmp->nm_lock);
433 		}
434 		soclose(so);
435 	}
436 #ifdef DIAGNOSTIC
437 	if (drain && (nmp->nm_waiters > 0))
438 		panic("nfs_disconnect: waiters left after drain?");
439 #endif
440 }
441 
442 void
443 nfs_safedisconnect(struct nfsmount *nmp)
444 {
445 	struct nfsreq dummyreq;
446 
447 	memset(&dummyreq, 0, sizeof(dummyreq));
448 	dummyreq.r_nmp = nmp;
449 	nfs_rcvlock(nmp, &dummyreq); /* XXX ignored error return */
450 	nfs_disconnect(nmp);
451 	nfs_rcvunlock(nmp);
452 }
453 
454 /*
455  * This is the nfs send routine. For connection based socket types, it
456  * must be called with an nfs_sndlock() on the socket.
457  * "rep == NULL" indicates that it has been called from a server.
458  * For the client side:
459  * - return EINTR if the RPC is terminated, 0 otherwise
460  * - set R_MUSTRESEND if the send fails for any reason
461  * - do any cleanup required by recoverable socket errors (? ? ?)
462  * For the server side:
463  * - return EINTR or ERESTART if interrupted by a signal
464  * - return EPIPE if a connection is lost for connection based sockets (TCP...)
465  * - do any cleanup required by recoverable socket errors (? ? ?)
466  */
467 int
468 nfs_send(struct socket *so, struct mbuf *nam, struct mbuf *top, struct nfsreq *rep, struct lwp *l)
469 {
470 	struct mbuf *sendnam;
471 	int error, soflags, flags;
472 
473 	/* XXX nfs_doio()/nfs_request() calls with  rep->r_lwp == NULL */
474 	if (l == NULL && rep->r_lwp == NULL)
475 		l = curlwp;
476 
477 	if (rep) {
478 		if (rep->r_flags & R_SOFTTERM) {
479 			m_freem(top);
480 			return (EINTR);
481 		}
482 		if ((so = rep->r_nmp->nm_so) == NULL) {
483 			rep->r_flags |= R_MUSTRESEND;
484 			m_freem(top);
485 			return (0);
486 		}
487 		rep->r_flags &= ~R_MUSTRESEND;
488 		soflags = rep->r_nmp->nm_soflags;
489 	} else
490 		soflags = so->so_proto->pr_flags;
491 	if ((soflags & PR_CONNREQUIRED) || (so->so_state & SS_ISCONNECTED))
492 		sendnam = NULL;
493 	else
494 		sendnam = nam;
495 	if (so->so_type == SOCK_SEQPACKET)
496 		flags = MSG_EOR;
497 	else
498 		flags = 0;
499 
500 	error = (*so->so_send)(so, sendnam, NULL, top, NULL, flags,  l);
501 	if (error) {
502 		if (rep) {
503 			if (error == ENOBUFS && so->so_type == SOCK_DGRAM) {
504 				/*
505 				 * We're too fast for the network/driver,
506 				 * and UDP isn't flowcontrolled.
507 				 * We need to resend. This is not fatal,
508 				 * just try again.
509 				 *
510 				 * Could be smarter here by doing some sort
511 				 * of a backoff, but this is rare.
512 				 */
513 				rep->r_flags |= R_MUSTRESEND;
514 			} else {
515 				if (error != EPIPE)
516 					log(LOG_INFO,
517 					    "nfs send error %d for %s\n",
518 					    error,
519 					    rep->r_nmp->nm_mountp->
520 						    mnt_stat.f_mntfromname);
521 				/*
522 				 * Deal with errors for the client side.
523 				 */
524 				if (rep->r_flags & R_SOFTTERM)
525 					error = EINTR;
526 				else if (error != EMSGSIZE)
527 					rep->r_flags |= R_MUSTRESEND;
528 			}
529 		} else {
530 			/*
531 			 * See above. This error can happen under normal
532 			 * circumstances and the log is too noisy.
533 			 * The error will still show up in nfsstat.
534 			 */
535 			if (error != ENOBUFS || so->so_type != SOCK_DGRAM)
536 				log(LOG_INFO, "nfsd send error %d\n", error);
537 		}
538 
539 		/*
540 		 * Handle any recoverable (soft) socket errors here. (? ? ?)
541 		 */
542 		if (error != EINTR && error != ERESTART &&
543 		    error != EWOULDBLOCK && error != EPIPE &&
544 		    error != EMSGSIZE)
545 			error = 0;
546 	}
547 	return (error);
548 }
549 
550 #ifdef NFS
551 /*
552  * Receive a Sun RPC Request/Reply. For SOCK_DGRAM, the work is all
553  * done by soreceive(), but for SOCK_STREAM we must deal with the Record
554  * Mark and consolidate the data into a new mbuf list.
555  * nb: Sometimes TCP passes the data up to soreceive() in long lists of
556  *     small mbufs.
557  * For SOCK_STREAM we must be very careful to read an entire record once
558  * we have read any of it, even if the system call has been interrupted.
559  */
560 static int
561 nfs_receive(struct nfsreq *rep, struct mbuf **aname, struct mbuf **mp,
562     struct lwp *l)
563 {
564 	struct socket *so;
565 	struct uio auio;
566 	struct iovec aio;
567 	struct mbuf *m;
568 	struct mbuf *control;
569 	u_int32_t len;
570 	struct mbuf **getnam;
571 	int error, sotype, rcvflg;
572 
573 	/*
574 	 * Set up arguments for soreceive()
575 	 */
576 	*mp = NULL;
577 	*aname = NULL;
578 	sotype = rep->r_nmp->nm_sotype;
579 
580 	/*
581 	 * For reliable protocols, lock against other senders/receivers
582 	 * in case a reconnect is necessary.
583 	 * For SOCK_STREAM, first get the Record Mark to find out how much
584 	 * more there is to get.
585 	 * We must lock the socket against other receivers
586 	 * until we have an entire rpc request/reply.
587 	 */
588 	if (sotype != SOCK_DGRAM) {
589 		error = nfs_sndlock(rep->r_nmp, rep);
590 		if (error)
591 			return (error);
592 tryagain:
593 		/*
594 		 * Check for fatal errors and resending request.
595 		 */
596 		/*
597 		 * Ugh: If a reconnect attempt just happened, nm_so
598 		 * would have changed. NULL indicates a failed
599 		 * attempt that has essentially shut down this
600 		 * mount point.
601 		 */
602 		if (rep->r_mrep || (rep->r_flags & R_SOFTTERM)) {
603 			nfs_sndunlock(rep->r_nmp);
604 			return (EINTR);
605 		}
606 		so = rep->r_nmp->nm_so;
607 		if (!so) {
608 			error = nfs_reconnect(rep);
609 			if (error) {
610 				nfs_sndunlock(rep->r_nmp);
611 				return (error);
612 			}
613 			goto tryagain;
614 		}
615 		while (rep->r_flags & R_MUSTRESEND) {
616 			m = m_copym(rep->r_mreq, 0, M_COPYALL, M_WAIT);
617 			nfsstats.rpcretries++;
618 			rep->r_rtt = 0;
619 			rep->r_flags &= ~R_TIMING;
620 			error = nfs_send(so, rep->r_nmp->nm_nam, m, rep, l);
621 			if (error) {
622 				if (error == EINTR || error == ERESTART ||
623 				    (error = nfs_reconnect(rep)) != 0) {
624 					nfs_sndunlock(rep->r_nmp);
625 					return (error);
626 				}
627 				goto tryagain;
628 			}
629 		}
630 		nfs_sndunlock(rep->r_nmp);
631 		if (sotype == SOCK_STREAM) {
632 			aio.iov_base = (void *) &len;
633 			aio.iov_len = sizeof(u_int32_t);
634 			auio.uio_iov = &aio;
635 			auio.uio_iovcnt = 1;
636 			auio.uio_rw = UIO_READ;
637 			auio.uio_offset = 0;
638 			auio.uio_resid = sizeof(u_int32_t);
639 			UIO_SETUP_SYSSPACE(&auio);
640 			do {
641 			   rcvflg = MSG_WAITALL;
642 			   error = (*so->so_receive)(so, NULL, &auio,
643 				NULL, NULL, &rcvflg);
644 			   if (error == EWOULDBLOCK && rep) {
645 				if (rep->r_flags & R_SOFTTERM)
646 					return (EINTR);
647 				/*
648 				 * if it seems that the server died after it
649 				 * received our request, set EPIPE so that
650 				 * we'll reconnect and retransmit requests.
651 				 */
652 				if (rep->r_rexmit >= rep->r_nmp->nm_retry) {
653 					nfsstats.rpctimeouts++;
654 					error = EPIPE;
655 				}
656 			   }
657 			} while (error == EWOULDBLOCK);
658 			if (!error && auio.uio_resid > 0) {
659 			    /*
660 			     * Don't log a 0 byte receive; it means
661 			     * that the socket has been closed, and
662 			     * can happen during normal operation
663 			     * (forcible unmount or Solaris server).
664 			     */
665 			    if (auio.uio_resid != sizeof (u_int32_t))
666 			      log(LOG_INFO,
667 				 "short receive (%lu/%lu) from nfs server %s\n",
668 				 (u_long)sizeof(u_int32_t) - auio.uio_resid,
669 				 (u_long)sizeof(u_int32_t),
670 				 rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
671 			    error = EPIPE;
672 			}
673 			if (error)
674 				goto errout;
675 			len = ntohl(len) & ~0x80000000;
676 			/*
677 			 * This is SERIOUS! We are out of sync with the sender
678 			 * and forcing a disconnect/reconnect is all I can do.
679 			 */
680 			if (len > NFS_MAXPACKET) {
681 			    log(LOG_ERR, "%s (%d) from nfs server %s\n",
682 				"impossible packet length",
683 				len,
684 				rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
685 			    error = EFBIG;
686 			    goto errout;
687 			}
688 			auio.uio_resid = len;
689 			do {
690 			    rcvflg = MSG_WAITALL;
691 			    error =  (*so->so_receive)(so, NULL,
692 				&auio, mp, NULL, &rcvflg);
693 			} while (error == EWOULDBLOCK || error == EINTR ||
694 				 error == ERESTART);
695 			if (!error && auio.uio_resid > 0) {
696 			    if (len != auio.uio_resid)
697 			      log(LOG_INFO,
698 				"short receive (%lu/%d) from nfs server %s\n",
699 				(u_long)len - auio.uio_resid, len,
700 				rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
701 			    error = EPIPE;
702 			}
703 		} else {
704 			/*
705 			 * NB: Since uio_resid is big, MSG_WAITALL is ignored
706 			 * and soreceive() will return when it has either a
707 			 * control msg or a data msg.
708 			 * We have no use for control msg., but must grab them
709 			 * and then throw them away so we know what is going
710 			 * on.
711 			 */
712 			auio.uio_resid = len = 100000000; /* Anything Big */
713 			/* not need to setup uio_vmspace */
714 			do {
715 			    rcvflg = 0;
716 			    error =  (*so->so_receive)(so, NULL,
717 				&auio, mp, &control, &rcvflg);
718 			    if (control)
719 				m_freem(control);
720 			    if (error == EWOULDBLOCK && rep) {
721 				if (rep->r_flags & R_SOFTTERM)
722 					return (EINTR);
723 			    }
724 			} while (error == EWOULDBLOCK ||
725 				 (!error && *mp == NULL && control));
726 			if ((rcvflg & MSG_EOR) == 0)
727 				printf("Egad!!\n");
728 			if (!error && *mp == NULL)
729 				error = EPIPE;
730 			len -= auio.uio_resid;
731 		}
732 errout:
733 		if (error && error != EINTR && error != ERESTART) {
734 			m_freem(*mp);
735 			*mp = NULL;
736 			if (error != EPIPE)
737 				log(LOG_INFO,
738 				    "receive error %d from nfs server %s\n",
739 				    error,
740 				 rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
741 			error = nfs_sndlock(rep->r_nmp, rep);
742 			if (!error)
743 				error = nfs_reconnect(rep);
744 			if (!error)
745 				goto tryagain;
746 			else
747 				nfs_sndunlock(rep->r_nmp);
748 		}
749 	} else {
750 		if ((so = rep->r_nmp->nm_so) == NULL)
751 			return (EACCES);
752 		if (so->so_state & SS_ISCONNECTED)
753 			getnam = NULL;
754 		else
755 			getnam = aname;
756 		auio.uio_resid = len = 1000000;
757 		/* not need to setup uio_vmspace */
758 		do {
759 			rcvflg = 0;
760 			error =  (*so->so_receive)(so, getnam, &auio, mp,
761 				NULL, &rcvflg);
762 			if (error == EWOULDBLOCK &&
763 			    (rep->r_flags & R_SOFTTERM))
764 				return (EINTR);
765 		} while (error == EWOULDBLOCK);
766 		len -= auio.uio_resid;
767 		if (!error && *mp == NULL)
768 			error = EPIPE;
769 	}
770 	if (error) {
771 		m_freem(*mp);
772 		*mp = NULL;
773 	}
774 	return (error);
775 }
776 
777 /*
778  * Implement receipt of reply on a socket.
779  * We must search through the list of received datagrams matching them
780  * with outstanding requests using the xid, until ours is found.
781  */
782 /* ARGSUSED */
783 static int
784 nfs_reply(struct nfsreq *myrep, struct lwp *lwp)
785 {
786 	struct nfsreq *rep;
787 	struct nfsmount *nmp = myrep->r_nmp;
788 	int32_t t1;
789 	struct mbuf *mrep, *nam, *md;
790 	u_int32_t rxid, *tl;
791 	char *dpos, *cp2;
792 	int error;
793 
794 	/*
795 	 * Loop around until we get our own reply
796 	 */
797 	for (;;) {
798 		/*
799 		 * Lock against other receivers so that I don't get stuck in
800 		 * sbwait() after someone else has received my reply for me.
801 		 * Also necessary for connection based protocols to avoid
802 		 * race conditions during a reconnect.
803 		 */
804 		error = nfs_rcvlock(nmp, myrep);
805 		if (error == EALREADY)
806 			return (0);
807 		if (error)
808 			return (error);
809 		/*
810 		 * Get the next Rpc reply off the socket
811 		 */
812 
813 		mutex_enter(&nmp->nm_lock);
814 		nmp->nm_waiters++;
815 		mutex_exit(&nmp->nm_lock);
816 
817 		error = nfs_receive(myrep, &nam, &mrep, lwp);
818 
819 		mutex_enter(&nmp->nm_lock);
820 		nmp->nm_waiters--;
821 		cv_signal(&nmp->nm_disconcv);
822 		mutex_exit(&nmp->nm_lock);
823 
824 		if (error) {
825 			nfs_rcvunlock(nmp);
826 
827 			if (nmp->nm_iflag & NFSMNT_DISMNT) {
828 				/*
829 				 * Oops, we're going away now..
830 				 */
831 				return error;
832 			}
833 			/*
834 			 * Ignore routing errors on connectionless protocols? ?
835 			 */
836 			if (NFSIGNORE_SOERROR(nmp->nm_soflags, error)) {
837 				nmp->nm_so->so_error = 0;
838 #ifdef DEBUG
839 				if (ratecheck(&nfs_reply_last_err_time,
840 				    &nfs_err_interval))
841 					printf("%s: ignoring error %d\n",
842 					       __func__, error);
843 #endif
844 				continue;
845 			}
846 			return (error);
847 		}
848 		if (nam)
849 			m_freem(nam);
850 
851 		/*
852 		 * Get the xid and check that it is an rpc reply
853 		 */
854 		md = mrep;
855 		dpos = mtod(md, void *);
856 		nfsm_dissect(tl, u_int32_t *, 2*NFSX_UNSIGNED);
857 		rxid = *tl++;
858 		if (*tl != rpc_reply) {
859 			nfsstats.rpcinvalid++;
860 			m_freem(mrep);
861 nfsmout:
862 			nfs_rcvunlock(nmp);
863 			continue;
864 		}
865 
866 		/*
867 		 * Loop through the request list to match up the reply
868 		 * Iff no match, just drop the datagram
869 		 */
870 		TAILQ_FOREACH(rep, &nfs_reqq, r_chain) {
871 			if (rep->r_mrep == NULL && rxid == rep->r_xid) {
872 				/* Found it.. */
873 				rep->r_mrep = mrep;
874 				rep->r_md = md;
875 				rep->r_dpos = dpos;
876 				if (nfsrtton) {
877 					struct rttl *rt;
878 
879 					rt = &nfsrtt.rttl[nfsrtt.pos];
880 					rt->proc = rep->r_procnum;
881 					rt->rto = NFS_RTO(nmp, proct[rep->r_procnum]);
882 					rt->sent = nmp->nm_sent;
883 					rt->cwnd = nmp->nm_cwnd;
884 					rt->srtt = nmp->nm_srtt[proct[rep->r_procnum] - 1];
885 					rt->sdrtt = nmp->nm_sdrtt[proct[rep->r_procnum] - 1];
886 					rt->fsid = nmp->nm_mountp->mnt_stat.f_fsidx;
887 					getmicrotime(&rt->tstamp);
888 					if (rep->r_flags & R_TIMING)
889 						rt->rtt = rep->r_rtt;
890 					else
891 						rt->rtt = 1000000;
892 					nfsrtt.pos = (nfsrtt.pos + 1) % NFSRTTLOGSIZ;
893 				}
894 				/*
895 				 * Update congestion window.
896 				 * Do the additive increase of
897 				 * one rpc/rtt.
898 				 */
899 				if (nmp->nm_cwnd <= nmp->nm_sent) {
900 					nmp->nm_cwnd +=
901 					   (NFS_CWNDSCALE * NFS_CWNDSCALE +
902 					   (nmp->nm_cwnd >> 1)) / nmp->nm_cwnd;
903 					if (nmp->nm_cwnd > NFS_MAXCWND)
904 						nmp->nm_cwnd = NFS_MAXCWND;
905 				}
906 				rep->r_flags &= ~R_SENT;
907 				nmp->nm_sent -= NFS_CWNDSCALE;
908 				/*
909 				 * Update rtt using a gain of 0.125 on the mean
910 				 * and a gain of 0.25 on the deviation.
911 				 */
912 				if (rep->r_flags & R_TIMING) {
913 					/*
914 					 * Since the timer resolution of
915 					 * NFS_HZ is so course, it can often
916 					 * result in r_rtt == 0. Since
917 					 * r_rtt == N means that the actual
918 					 * rtt is between N+dt and N+2-dt ticks,
919 					 * add 1.
920 					 */
921 					t1 = rep->r_rtt + 1;
922 					t1 -= (NFS_SRTT(rep) >> 3);
923 					NFS_SRTT(rep) += t1;
924 					if (t1 < 0)
925 						t1 = -t1;
926 					t1 -= (NFS_SDRTT(rep) >> 2);
927 					NFS_SDRTT(rep) += t1;
928 				}
929 				nmp->nm_timeouts = 0;
930 				break;
931 			}
932 		}
933 		nfs_rcvunlock(nmp);
934 		/*
935 		 * If not matched to a request, drop it.
936 		 * If it's mine, get out.
937 		 */
938 		if (rep == 0) {
939 			nfsstats.rpcunexpected++;
940 			m_freem(mrep);
941 		} else if (rep == myrep) {
942 			if (rep->r_mrep == NULL)
943 				panic("nfsreply nil");
944 			return (0);
945 		}
946 	}
947 }
948 
949 /*
950  * nfs_request - goes something like this
951  *	- fill in request struct
952  *	- links it into list
953  *	- calls nfs_send() for first transmit
954  *	- calls nfs_receive() to get reply
955  *	- break down rpc header and return with nfs reply pointed to
956  *	  by mrep or error
957  * nb: always frees up mreq mbuf list
958  */
959 int
960 nfs_request(struct nfsnode *np, struct mbuf *mrest, int procnum, struct lwp *lwp, kauth_cred_t cred, struct mbuf **mrp, struct mbuf **mdp, char **dposp, int *rexmitp)
961 {
962 	struct mbuf *m, *mrep;
963 	struct nfsreq *rep;
964 	u_int32_t *tl;
965 	int i;
966 	struct nfsmount *nmp = VFSTONFS(np->n_vnode->v_mount);
967 	struct mbuf *md, *mheadend;
968 	char nickv[RPCX_NICKVERF];
969 	time_t waituntil;
970 	char *dpos, *cp2;
971 	int t1, s, error = 0, mrest_len, auth_len, auth_type;
972 	int trylater_delay = NFS_TRYLATERDEL, failed_auth = 0;
973 	int verf_len, verf_type;
974 	u_int32_t xid;
975 	char *auth_str, *verf_str;
976 	NFSKERBKEY_T key;		/* save session key */
977 	kauth_cred_t acred;
978 	struct mbuf *mrest_backup = NULL;
979 	kauth_cred_t origcred = NULL; /* XXX: gcc */
980 	bool retry_cred = true;
981 	bool use_opencred = (np->n_flag & NUSEOPENCRED) != 0;
982 
983 	if (rexmitp != NULL)
984 		*rexmitp = 0;
985 
986 	acred = kauth_cred_alloc();
987 
988 tryagain_cred:
989 	KASSERT(cred != NULL);
990 	rep = kmem_alloc(sizeof(*rep), KM_SLEEP);
991 	rep->r_nmp = nmp;
992 	KASSERT(lwp == NULL || lwp == curlwp);
993 	rep->r_lwp = lwp;
994 	rep->r_procnum = procnum;
995 	i = 0;
996 	m = mrest;
997 	while (m) {
998 		i += m->m_len;
999 		m = m->m_next;
1000 	}
1001 	mrest_len = i;
1002 
1003 	/*
1004 	 * Get the RPC header with authorization.
1005 	 */
1006 kerbauth:
1007 	verf_str = auth_str = NULL;
1008 	if (nmp->nm_flag & NFSMNT_KERB) {
1009 		verf_str = nickv;
1010 		verf_len = sizeof (nickv);
1011 		auth_type = RPCAUTH_KERB4;
1012 		memset((void *)key, 0, sizeof (key));
1013 		if (failed_auth || nfs_getnickauth(nmp, cred, &auth_str,
1014 			&auth_len, verf_str, verf_len)) {
1015 			error = nfs_getauth(nmp, rep, cred, &auth_str,
1016 				&auth_len, verf_str, &verf_len, key);
1017 			if (error) {
1018 				kmem_free(rep, sizeof(*rep));
1019 				m_freem(mrest);
1020 				KASSERT(kauth_cred_getrefcnt(acred) == 1);
1021 				kauth_cred_free(acred);
1022 				return (error);
1023 			}
1024 		}
1025 		retry_cred = false;
1026 	} else {
1027 		/* AUTH_UNIX */
1028 		uid_t uid;
1029 		gid_t gid;
1030 
1031 		/*
1032 		 * on the most unix filesystems, permission checks are
1033 		 * done when the file is open(2)'ed.
1034 		 * ie. once a file is successfully open'ed,
1035 		 * following i/o operations never fail with EACCES.
1036 		 * we try to follow the semantics as far as possible.
1037 		 *
1038 		 * note that we expect that the nfs server always grant
1039 		 * accesses by the file's owner.
1040 		 */
1041 		origcred = cred;
1042 		switch (procnum) {
1043 		case NFSPROC_READ:
1044 		case NFSPROC_WRITE:
1045 		case NFSPROC_COMMIT:
1046 			uid = np->n_vattr->va_uid;
1047 			gid = np->n_vattr->va_gid;
1048 			if (kauth_cred_geteuid(cred) == uid &&
1049 			    kauth_cred_getegid(cred) == gid) {
1050 				retry_cred = false;
1051 				break;
1052 			}
1053 			if (use_opencred)
1054 				break;
1055 			kauth_cred_setuid(acred, uid);
1056 			kauth_cred_seteuid(acred, uid);
1057 			kauth_cred_setsvuid(acred, uid);
1058 			kauth_cred_setgid(acred, gid);
1059 			kauth_cred_setegid(acred, gid);
1060 			kauth_cred_setsvgid(acred, gid);
1061 			cred = acred;
1062 			break;
1063 		default:
1064 			retry_cred = false;
1065 			break;
1066 		}
1067 		/*
1068 		 * backup mbuf chain if we can need it later to retry.
1069 		 *
1070 		 * XXX maybe we can keep a direct reference to
1071 		 * mrest without doing m_copym, but it's ...ugly.
1072 		 */
1073 		if (retry_cred)
1074 			mrest_backup = m_copym(mrest, 0, M_COPYALL, M_WAIT);
1075 		auth_type = RPCAUTH_UNIX;
1076 		/* XXX elad - ngroups */
1077 		auth_len = (((kauth_cred_ngroups(cred) > nmp->nm_numgrps) ?
1078 			nmp->nm_numgrps : kauth_cred_ngroups(cred)) << 2) +
1079 			5 * NFSX_UNSIGNED;
1080 	}
1081 	m = nfsm_rpchead(cred, nmp->nm_flag, procnum, auth_type, auth_len,
1082 	     auth_str, verf_len, verf_str, mrest, mrest_len, &mheadend, &xid);
1083 	if (auth_str)
1084 		free(auth_str, M_TEMP);
1085 
1086 	/*
1087 	 * For stream protocols, insert a Sun RPC Record Mark.
1088 	 */
1089 	if (nmp->nm_sotype == SOCK_STREAM) {
1090 		M_PREPEND(m, NFSX_UNSIGNED, M_WAIT);
1091 		*mtod(m, u_int32_t *) = htonl(0x80000000 |
1092 			 (m->m_pkthdr.len - NFSX_UNSIGNED));
1093 	}
1094 	rep->r_mreq = m;
1095 	rep->r_xid = xid;
1096 tryagain:
1097 	if (nmp->nm_flag & NFSMNT_SOFT)
1098 		rep->r_retry = nmp->nm_retry;
1099 	else
1100 		rep->r_retry = NFS_MAXREXMIT + 1;	/* past clip limit */
1101 	rep->r_rtt = rep->r_rexmit = 0;
1102 	if (proct[procnum] > 0)
1103 		rep->r_flags = R_TIMING;
1104 	else
1105 		rep->r_flags = 0;
1106 	rep->r_mrep = NULL;
1107 
1108 	/*
1109 	 * Do the client side RPC.
1110 	 */
1111 	nfsstats.rpcrequests++;
1112 	/*
1113 	 * Chain request into list of outstanding requests. Be sure
1114 	 * to put it LAST so timer finds oldest requests first.
1115 	 */
1116 	s = splsoftnet();
1117 	TAILQ_INSERT_TAIL(&nfs_reqq, rep, r_chain);
1118 	nfs_timer_start();
1119 
1120 	/*
1121 	 * If backing off another request or avoiding congestion, don't
1122 	 * send this one now but let timer do it. If not timing a request,
1123 	 * do it now.
1124 	 */
1125 	if (nmp->nm_so && (nmp->nm_sotype != SOCK_DGRAM ||
1126 	    (nmp->nm_flag & NFSMNT_DUMBTIMR) || nmp->nm_sent < nmp->nm_cwnd)) {
1127 		splx(s);
1128 		if (nmp->nm_soflags & PR_CONNREQUIRED)
1129 			error = nfs_sndlock(nmp, rep);
1130 		if (!error) {
1131 			m = m_copym(rep->r_mreq, 0, M_COPYALL, M_WAIT);
1132 			error = nfs_send(nmp->nm_so, nmp->nm_nam, m, rep, lwp);
1133 			if (nmp->nm_soflags & PR_CONNREQUIRED)
1134 				nfs_sndunlock(nmp);
1135 		}
1136 		if (!error && (rep->r_flags & R_MUSTRESEND) == 0) {
1137 			nmp->nm_sent += NFS_CWNDSCALE;
1138 			rep->r_flags |= R_SENT;
1139 		}
1140 	} else {
1141 		splx(s);
1142 		rep->r_rtt = -1;
1143 	}
1144 
1145 	/*
1146 	 * Wait for the reply from our send or the timer's.
1147 	 */
1148 	if (!error || error == EPIPE || error == EWOULDBLOCK)
1149 		error = nfs_reply(rep, lwp);
1150 
1151 	/*
1152 	 * RPC done, unlink the request.
1153 	 */
1154 	s = splsoftnet();
1155 	TAILQ_REMOVE(&nfs_reqq, rep, r_chain);
1156 	splx(s);
1157 
1158 	/*
1159 	 * Decrement the outstanding request count.
1160 	 */
1161 	if (rep->r_flags & R_SENT) {
1162 		rep->r_flags &= ~R_SENT;	/* paranoia */
1163 		nmp->nm_sent -= NFS_CWNDSCALE;
1164 	}
1165 
1166 	if (rexmitp != NULL) {
1167 		int rexmit;
1168 
1169 		if (nmp->nm_sotype != SOCK_DGRAM)
1170 			rexmit = (rep->r_flags & R_REXMITTED) != 0;
1171 		else
1172 			rexmit = rep->r_rexmit;
1173 		*rexmitp = rexmit;
1174 	}
1175 
1176 	/*
1177 	 * If there was a successful reply and a tprintf msg.
1178 	 * tprintf a response.
1179 	 */
1180 	if (!error && (rep->r_flags & R_TPRINTFMSG))
1181 		nfs_msg(rep->r_lwp, nmp->nm_mountp->mnt_stat.f_mntfromname,
1182 		    "is alive again");
1183 	mrep = rep->r_mrep;
1184 	md = rep->r_md;
1185 	dpos = rep->r_dpos;
1186 	if (error)
1187 		goto nfsmout;
1188 
1189 	/*
1190 	 * break down the rpc header and check if ok
1191 	 */
1192 	nfsm_dissect(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
1193 	if (*tl++ == rpc_msgdenied) {
1194 		if (*tl == rpc_mismatch)
1195 			error = EOPNOTSUPP;
1196 		else if ((nmp->nm_flag & NFSMNT_KERB) && *tl++ == rpc_autherr) {
1197 			if (!failed_auth) {
1198 				failed_auth++;
1199 				mheadend->m_next = NULL;
1200 				m_freem(mrep);
1201 				m_freem(rep->r_mreq);
1202 				goto kerbauth;
1203 			} else
1204 				error = EAUTH;
1205 		} else
1206 			error = EACCES;
1207 		m_freem(mrep);
1208 		goto nfsmout;
1209 	}
1210 
1211 	/*
1212 	 * Grab any Kerberos verifier, otherwise just throw it away.
1213 	 */
1214 	verf_type = fxdr_unsigned(int, *tl++);
1215 	i = fxdr_unsigned(int32_t, *tl);
1216 	if ((nmp->nm_flag & NFSMNT_KERB) && verf_type == RPCAUTH_KERB4) {
1217 		error = nfs_savenickauth(nmp, cred, i, key, &md, &dpos, mrep);
1218 		if (error)
1219 			goto nfsmout;
1220 	} else if (i > 0)
1221 		nfsm_adv(nfsm_rndup(i));
1222 	nfsm_dissect(tl, u_int32_t *, NFSX_UNSIGNED);
1223 	/* 0 == ok */
1224 	if (*tl == 0) {
1225 		nfsm_dissect(tl, u_int32_t *, NFSX_UNSIGNED);
1226 		if (*tl != 0) {
1227 			error = fxdr_unsigned(int, *tl);
1228 			switch (error) {
1229 			case NFSERR_PERM:
1230 				error = EPERM;
1231 				break;
1232 
1233 			case NFSERR_NOENT:
1234 				error = ENOENT;
1235 				break;
1236 
1237 			case NFSERR_IO:
1238 				error = EIO;
1239 				break;
1240 
1241 			case NFSERR_NXIO:
1242 				error = ENXIO;
1243 				break;
1244 
1245 			case NFSERR_ACCES:
1246 				error = EACCES;
1247 				if (!retry_cred)
1248 					break;
1249 				m_freem(mrep);
1250 				m_freem(rep->r_mreq);
1251 				kmem_free(rep, sizeof(*rep));
1252 				use_opencred = !use_opencred;
1253 				if (mrest_backup == NULL) {
1254 					/* m_copym failure */
1255 					KASSERT(
1256 					    kauth_cred_getrefcnt(acred) == 1);
1257 					kauth_cred_free(acred);
1258 					return ENOMEM;
1259 				}
1260 				mrest = mrest_backup;
1261 				mrest_backup = NULL;
1262 				cred = origcred;
1263 				error = 0;
1264 				retry_cred = false;
1265 				goto tryagain_cred;
1266 
1267 			case NFSERR_EXIST:
1268 				error = EEXIST;
1269 				break;
1270 
1271 			case NFSERR_XDEV:
1272 				error = EXDEV;
1273 				break;
1274 
1275 			case NFSERR_NODEV:
1276 				error = ENODEV;
1277 				break;
1278 
1279 			case NFSERR_NOTDIR:
1280 				error = ENOTDIR;
1281 				break;
1282 
1283 			case NFSERR_ISDIR:
1284 				error = EISDIR;
1285 				break;
1286 
1287 			case NFSERR_INVAL:
1288 				error = EINVAL;
1289 				break;
1290 
1291 			case NFSERR_FBIG:
1292 				error = EFBIG;
1293 				break;
1294 
1295 			case NFSERR_NOSPC:
1296 				error = ENOSPC;
1297 				break;
1298 
1299 			case NFSERR_ROFS:
1300 				error = EROFS;
1301 				break;
1302 
1303 			case NFSERR_MLINK:
1304 				error = EMLINK;
1305 				break;
1306 
1307 			case NFSERR_TIMEDOUT:
1308 				error = ETIMEDOUT;
1309 				break;
1310 
1311 			case NFSERR_NAMETOL:
1312 				error = ENAMETOOLONG;
1313 				break;
1314 
1315 			case NFSERR_NOTEMPTY:
1316 				error = ENOTEMPTY;
1317 				break;
1318 
1319 			case NFSERR_DQUOT:
1320 				error = EDQUOT;
1321 				break;
1322 
1323 			case NFSERR_STALE:
1324 				/*
1325 				 * If the File Handle was stale, invalidate the
1326 				 * lookup cache, just in case.
1327 				 */
1328 				error = ESTALE;
1329 				cache_purge(NFSTOV(np));
1330 				break;
1331 
1332 			case NFSERR_REMOTE:
1333 				error = EREMOTE;
1334 				break;
1335 
1336 			case NFSERR_WFLUSH:
1337 			case NFSERR_BADHANDLE:
1338 			case NFSERR_NOT_SYNC:
1339 			case NFSERR_BAD_COOKIE:
1340 				error = EINVAL;
1341 				break;
1342 
1343 			case NFSERR_NOTSUPP:
1344 				error = ENOTSUP;
1345 				break;
1346 
1347 			case NFSERR_TOOSMALL:
1348 			case NFSERR_SERVERFAULT:
1349 			case NFSERR_BADTYPE:
1350 				error = EINVAL;
1351 				break;
1352 
1353 			case NFSERR_TRYLATER:
1354 				if ((nmp->nm_flag & NFSMNT_NFSV3) == 0)
1355 					break;
1356 				m_freem(mrep);
1357 				error = 0;
1358 				waituntil = time_second + trylater_delay;
1359 				while (time_second < waituntil) {
1360 					kpause("nfstrylater", false, hz, NULL);
1361 				}
1362 				trylater_delay *= NFS_TRYLATERDELMUL;
1363 				if (trylater_delay > NFS_TRYLATERDELMAX)
1364 					trylater_delay = NFS_TRYLATERDELMAX;
1365 				/*
1366 				 * RFC1813:
1367 				 * The client should wait and then try
1368 				 * the request with a new RPC transaction ID.
1369 				 */
1370 				nfs_renewxid(rep);
1371 				goto tryagain;
1372 
1373 			default:
1374 #ifdef DIAGNOSTIC
1375 				printf("Invalid rpc error code %d\n", error);
1376 #endif
1377 				error = EINVAL;
1378 				break;
1379 			}
1380 
1381 			if (nmp->nm_flag & NFSMNT_NFSV3) {
1382 				*mrp = mrep;
1383 				*mdp = md;
1384 				*dposp = dpos;
1385 				error |= NFSERR_RETERR;
1386 			} else
1387 				m_freem(mrep);
1388 			goto nfsmout;
1389 		}
1390 
1391 		/*
1392 		 * note which credential worked to minimize number of retries.
1393 		 */
1394 		if (use_opencred)
1395 			np->n_flag |= NUSEOPENCRED;
1396 		else
1397 			np->n_flag &= ~NUSEOPENCRED;
1398 
1399 		*mrp = mrep;
1400 		*mdp = md;
1401 		*dposp = dpos;
1402 
1403 		KASSERT(error == 0);
1404 		goto nfsmout;
1405 	}
1406 	m_freem(mrep);
1407 	error = EPROTONOSUPPORT;
1408 nfsmout:
1409 	KASSERT(kauth_cred_getrefcnt(acred) == 1);
1410 	kauth_cred_free(acred);
1411 	m_freem(rep->r_mreq);
1412 	kmem_free(rep, sizeof(*rep));
1413 	m_freem(mrest_backup);
1414 	return (error);
1415 }
1416 #endif /* NFS */
1417 
1418 /*
1419  * Generate the rpc reply header
1420  * siz arg. is used to decide if adding a cluster is worthwhile
1421  */
1422 int
1423 nfs_rephead(int siz, struct nfsrv_descript *nd, struct nfssvc_sock *slp, int err, int cache, u_quad_t *frev, struct mbuf **mrq, struct mbuf **mbp, char **bposp)
1424 {
1425 	u_int32_t *tl;
1426 	struct mbuf *mreq;
1427 	char *bpos;
1428 	struct mbuf *mb;
1429 
1430 	mreq = m_gethdr(M_WAIT, MT_DATA);
1431 	MCLAIM(mreq, &nfs_mowner);
1432 	mb = mreq;
1433 	/*
1434 	 * If this is a big reply, use a cluster else
1435 	 * try and leave leading space for the lower level headers.
1436 	 */
1437 	siz += RPC_REPLYSIZ;
1438 	if (siz >= max_datalen) {
1439 		m_clget(mreq, M_WAIT);
1440 	} else
1441 		mreq->m_data += max_hdr;
1442 	tl = mtod(mreq, u_int32_t *);
1443 	mreq->m_len = 6 * NFSX_UNSIGNED;
1444 	bpos = ((char *)tl) + mreq->m_len;
1445 	*tl++ = txdr_unsigned(nd->nd_retxid);
1446 	*tl++ = rpc_reply;
1447 	if (err == ERPCMISMATCH || (err & NFSERR_AUTHERR)) {
1448 		*tl++ = rpc_msgdenied;
1449 		if (err & NFSERR_AUTHERR) {
1450 			*tl++ = rpc_autherr;
1451 			*tl = txdr_unsigned(err & ~NFSERR_AUTHERR);
1452 			mreq->m_len -= NFSX_UNSIGNED;
1453 			bpos -= NFSX_UNSIGNED;
1454 		} else {
1455 			*tl++ = rpc_mismatch;
1456 			*tl++ = txdr_unsigned(RPC_VER2);
1457 			*tl = txdr_unsigned(RPC_VER2);
1458 		}
1459 	} else {
1460 		*tl++ = rpc_msgaccepted;
1461 
1462 		/*
1463 		 * For Kerberos authentication, we must send the nickname
1464 		 * verifier back, otherwise just RPCAUTH_NULL.
1465 		 */
1466 		if (nd->nd_flag & ND_KERBFULL) {
1467 			struct nfsuid *nuidp;
1468 			struct timeval ktvin, ktvout;
1469 
1470 			memset(&ktvout, 0, sizeof ktvout);	/* XXX gcc */
1471 
1472 			LIST_FOREACH(nuidp,
1473 			    NUIDHASH(slp, kauth_cred_geteuid(nd->nd_cr)),
1474 			    nu_hash) {
1475 				if (kauth_cred_geteuid(nuidp->nu_cr) ==
1476 				kauth_cred_geteuid(nd->nd_cr) &&
1477 				    (!nd->nd_nam2 || netaddr_match(
1478 				    NU_NETFAM(nuidp), &nuidp->nu_haddr,
1479 				    nd->nd_nam2)))
1480 					break;
1481 			}
1482 			if (nuidp) {
1483 				ktvin.tv_sec =
1484 				    txdr_unsigned(nuidp->nu_timestamp.tv_sec
1485 					- 1);
1486 				ktvin.tv_usec =
1487 				    txdr_unsigned(nuidp->nu_timestamp.tv_usec);
1488 
1489 				/*
1490 				 * Encrypt the timestamp in ecb mode using the
1491 				 * session key.
1492 				 */
1493 #ifdef NFSKERB
1494 				XXX
1495 #endif
1496 
1497 				*tl++ = rpc_auth_kerb;
1498 				*tl++ = txdr_unsigned(3 * NFSX_UNSIGNED);
1499 				*tl = ktvout.tv_sec;
1500 				nfsm_build(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
1501 				*tl++ = ktvout.tv_usec;
1502 				*tl++ = txdr_unsigned(
1503 				    kauth_cred_geteuid(nuidp->nu_cr));
1504 			} else {
1505 				*tl++ = 0;
1506 				*tl++ = 0;
1507 			}
1508 		} else {
1509 			*tl++ = 0;
1510 			*tl++ = 0;
1511 		}
1512 		switch (err) {
1513 		case EPROGUNAVAIL:
1514 			*tl = txdr_unsigned(RPC_PROGUNAVAIL);
1515 			break;
1516 		case EPROGMISMATCH:
1517 			*tl = txdr_unsigned(RPC_PROGMISMATCH);
1518 			nfsm_build(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1519 			*tl++ = txdr_unsigned(2);
1520 			*tl = txdr_unsigned(3);
1521 			break;
1522 		case EPROCUNAVAIL:
1523 			*tl = txdr_unsigned(RPC_PROCUNAVAIL);
1524 			break;
1525 		case EBADRPC:
1526 			*tl = txdr_unsigned(RPC_GARBAGE);
1527 			break;
1528 		default:
1529 			*tl = 0;
1530 			if (err != NFSERR_RETVOID) {
1531 				nfsm_build(tl, u_int32_t *, NFSX_UNSIGNED);
1532 				if (err)
1533 				    *tl = txdr_unsigned(nfsrv_errmap(nd, err));
1534 				else
1535 				    *tl = 0;
1536 			}
1537 			break;
1538 		};
1539 	}
1540 
1541 	if (mrq != NULL)
1542 		*mrq = mreq;
1543 	*mbp = mb;
1544 	*bposp = bpos;
1545 	if (err != 0 && err != NFSERR_RETVOID)
1546 		nfsstats.srvrpc_errs++;
1547 	return (0);
1548 }
1549 
1550 static void
1551 nfs_timer_schedule(void)
1552 {
1553 
1554 	callout_schedule(&nfs_timer_ch, nfs_ticks);
1555 }
1556 
1557 void
1558 nfs_timer_start(void)
1559 {
1560 
1561 	if (callout_pending(&nfs_timer_ch))
1562 		return;
1563 
1564 	nfs_timer_start_ev.ev_count++;
1565 	nfs_timer_schedule();
1566 }
1567 
1568 void
1569 nfs_timer_init(void)
1570 {
1571 
1572 	mutex_init(&nfs_timer_lock, MUTEX_DEFAULT, IPL_NONE);
1573 	callout_init(&nfs_timer_ch, 0);
1574 	callout_setfunc(&nfs_timer_ch, nfs_timer, NULL);
1575 	evcnt_attach_dynamic(&nfs_timer_ev, EVCNT_TYPE_MISC, NULL,
1576 	    "nfs", "timer");
1577 	evcnt_attach_dynamic(&nfs_timer_start_ev, EVCNT_TYPE_MISC, NULL,
1578 	    "nfs", "timer start");
1579 	evcnt_attach_dynamic(&nfs_timer_stop_ev, EVCNT_TYPE_MISC, NULL,
1580 	    "nfs", "timer stop");
1581 }
1582 
1583 void
1584 nfs_timer_fini(void)
1585 {
1586 
1587 	callout_halt(&nfs_timer_ch, NULL);
1588 	callout_destroy(&nfs_timer_ch);
1589 	mutex_destroy(&nfs_timer_lock);
1590 	evcnt_detach(&nfs_timer_ev);
1591 	evcnt_detach(&nfs_timer_start_ev);
1592 	evcnt_detach(&nfs_timer_stop_ev);
1593 }
1594 
1595 void
1596 nfs_timer_srvinit(bool (*func)(void))
1597 {
1598 
1599 	nfs_timer_srvvec = func;
1600 }
1601 
1602 void
1603 nfs_timer_srvfini(void)
1604 {
1605 
1606 	mutex_enter(&nfs_timer_lock);
1607 	nfs_timer_srvvec = NULL;
1608 	mutex_exit(&nfs_timer_lock);
1609 }
1610 
1611 
1612 /*
1613  * Nfs timer routine
1614  * Scan the nfsreq list and retranmit any requests that have timed out
1615  * To avoid retransmission attempts on STREAM sockets (in the future) make
1616  * sure to set the r_retry field to 0 (implies nm_retry == 0).
1617  */
1618 void
1619 nfs_timer(void *arg)
1620 {
1621 	struct nfsreq *rep;
1622 	struct mbuf *m;
1623 	struct socket *so;
1624 	struct nfsmount *nmp;
1625 	int timeo;
1626 	int error;
1627 	bool more = false;
1628 
1629 	nfs_timer_ev.ev_count++;
1630 
1631 	mutex_enter(softnet_lock);	/* XXX PR 40491 */
1632 	TAILQ_FOREACH(rep, &nfs_reqq, r_chain) {
1633 		more = true;
1634 		nmp = rep->r_nmp;
1635 		if (rep->r_mrep || (rep->r_flags & R_SOFTTERM))
1636 			continue;
1637 		if (nfs_sigintr(nmp, rep, rep->r_lwp)) {
1638 			rep->r_flags |= R_SOFTTERM;
1639 			continue;
1640 		}
1641 		if (rep->r_rtt >= 0) {
1642 			rep->r_rtt++;
1643 			if (nmp->nm_flag & NFSMNT_DUMBTIMR)
1644 				timeo = nmp->nm_timeo;
1645 			else
1646 				timeo = NFS_RTO(nmp, proct[rep->r_procnum]);
1647 			if (nmp->nm_timeouts > 0)
1648 				timeo *= nfs_backoff[nmp->nm_timeouts - 1];
1649 			if (timeo > NFS_MAXTIMEO)
1650 				timeo = NFS_MAXTIMEO;
1651 			if (rep->r_rtt <= timeo)
1652 				continue;
1653 			if (nmp->nm_timeouts <
1654 			    (sizeof(nfs_backoff) / sizeof(nfs_backoff[0])))
1655 				nmp->nm_timeouts++;
1656 		}
1657 		/*
1658 		 * Check for server not responding
1659 		 */
1660 		if ((rep->r_flags & R_TPRINTFMSG) == 0 &&
1661 		     rep->r_rexmit > nmp->nm_deadthresh) {
1662 			nfs_msg(rep->r_lwp,
1663 			    nmp->nm_mountp->mnt_stat.f_mntfromname,
1664 			    "not responding");
1665 			rep->r_flags |= R_TPRINTFMSG;
1666 		}
1667 		if (rep->r_rexmit >= rep->r_retry) {	/* too many */
1668 			nfsstats.rpctimeouts++;
1669 			rep->r_flags |= R_SOFTTERM;
1670 			continue;
1671 		}
1672 		if (nmp->nm_sotype != SOCK_DGRAM) {
1673 			if (++rep->r_rexmit > NFS_MAXREXMIT)
1674 				rep->r_rexmit = NFS_MAXREXMIT;
1675 			continue;
1676 		}
1677 		if ((so = nmp->nm_so) == NULL)
1678 			continue;
1679 
1680 		/*
1681 		 * If there is enough space and the window allows..
1682 		 *	Resend it
1683 		 * Set r_rtt to -1 in case we fail to send it now.
1684 		 */
1685 		/* solock(so);		XXX PR 40491 */
1686 		rep->r_rtt = -1;
1687 		if (sbspace(&so->so_snd) >= rep->r_mreq->m_pkthdr.len &&
1688 		   ((nmp->nm_flag & NFSMNT_DUMBTIMR) ||
1689 		    (rep->r_flags & R_SENT) ||
1690 		    nmp->nm_sent < nmp->nm_cwnd) &&
1691 		   (m = m_copym(rep->r_mreq, 0, M_COPYALL, M_DONTWAIT))){
1692 		        if (so->so_state & SS_ISCONNECTED)
1693 			    error = (*so->so_proto->pr_usrreq)(so, PRU_SEND, m,
1694 			    NULL, NULL, NULL);
1695 			else
1696 			    error = (*so->so_proto->pr_usrreq)(so, PRU_SEND, m,
1697 			    nmp->nm_nam, NULL, NULL);
1698 			if (error) {
1699 				if (NFSIGNORE_SOERROR(nmp->nm_soflags, error)) {
1700 #ifdef DEBUG
1701 					if (ratecheck(&nfs_timer_last_err_time,
1702 					    &nfs_err_interval))
1703 						printf("%s: ignoring error "
1704 						       "%d\n", __func__, error);
1705 #endif
1706 					so->so_error = 0;
1707 				}
1708 			} else {
1709 				/*
1710 				 * Iff first send, start timing
1711 				 * else turn timing off, backoff timer
1712 				 * and divide congestion window by 2.
1713 				 */
1714 				if (rep->r_flags & R_SENT) {
1715 					rep->r_flags &= ~R_TIMING;
1716 					if (++rep->r_rexmit > NFS_MAXREXMIT)
1717 						rep->r_rexmit = NFS_MAXREXMIT;
1718 					nmp->nm_cwnd >>= 1;
1719 					if (nmp->nm_cwnd < NFS_CWNDSCALE)
1720 						nmp->nm_cwnd = NFS_CWNDSCALE;
1721 					nfsstats.rpcretries++;
1722 				} else {
1723 					rep->r_flags |= R_SENT;
1724 					nmp->nm_sent += NFS_CWNDSCALE;
1725 				}
1726 				rep->r_rtt = 0;
1727 			}
1728 		}
1729 		/* sounlock(so);	XXX PR 40491 */
1730 	}
1731 	mutex_exit(softnet_lock);	/* XXX PR 40491 */
1732 
1733 	mutex_enter(&nfs_timer_lock);
1734 	if (nfs_timer_srvvec != NULL) {
1735 		more |= (*nfs_timer_srvvec)();
1736 	}
1737 	mutex_exit(&nfs_timer_lock);
1738 
1739 	if (more) {
1740 		nfs_timer_schedule();
1741 	} else {
1742 		nfs_timer_stop_ev.ev_count++;
1743 	}
1744 }
1745 
1746 /*
1747  * Test for a termination condition pending on the process.
1748  * This is used for NFSMNT_INT mounts.
1749  */
1750 int
1751 nfs_sigintr(struct nfsmount *nmp, struct nfsreq *rep, struct lwp *l)
1752 {
1753 	sigset_t ss;
1754 
1755 	if (rep && (rep->r_flags & R_SOFTTERM))
1756 		return (EINTR);
1757 	if (!(nmp->nm_flag & NFSMNT_INT))
1758 		return (0);
1759 	if (l) {
1760 		sigpending1(l, &ss);
1761 #if 0
1762 		sigminusset(&l->l_proc->p_sigctx.ps_sigignore, &ss);
1763 #endif
1764 		if (sigismember(&ss, SIGINT) || sigismember(&ss, SIGTERM) ||
1765 		    sigismember(&ss, SIGKILL) || sigismember(&ss, SIGHUP) ||
1766 		    sigismember(&ss, SIGQUIT))
1767 			return (EINTR);
1768 	}
1769 	return (0);
1770 }
1771 
1772 #ifdef NFS
1773 /*
1774  * Lock a socket against others.
1775  * Necessary for STREAM sockets to ensure you get an entire rpc request/reply
1776  * and also to avoid race conditions between the processes with nfs requests
1777  * in progress when a reconnect is necessary.
1778  */
1779 static int
1780 nfs_sndlock(struct nfsmount *nmp, struct nfsreq *rep)
1781 {
1782 	struct lwp *l;
1783 	int timeo = 0;
1784 	bool catch = false;
1785 	int error = 0;
1786 
1787 	if (rep) {
1788 		l = rep->r_lwp;
1789 		if (rep->r_nmp->nm_flag & NFSMNT_INT)
1790 			catch = true;
1791 	} else
1792 		l = NULL;
1793 	mutex_enter(&nmp->nm_lock);
1794 	while ((nmp->nm_iflag & NFSMNT_SNDLOCK) != 0) {
1795 		if (rep && nfs_sigintr(rep->r_nmp, rep, l)) {
1796 			error = EINTR;
1797 			goto quit;
1798 		}
1799 		if (catch) {
1800 			cv_timedwait_sig(&nmp->nm_sndcv, &nmp->nm_lock, timeo);
1801 		} else {
1802 			cv_timedwait(&nmp->nm_sndcv, &nmp->nm_lock, timeo);
1803 		}
1804 		if (catch) {
1805 			catch = false;
1806 			timeo = 2 * hz;
1807 		}
1808 	}
1809 	nmp->nm_iflag |= NFSMNT_SNDLOCK;
1810 quit:
1811 	mutex_exit(&nmp->nm_lock);
1812 	return error;
1813 }
1814 
1815 /*
1816  * Unlock the stream socket for others.
1817  */
1818 static void
1819 nfs_sndunlock(struct nfsmount *nmp)
1820 {
1821 
1822 	mutex_enter(&nmp->nm_lock);
1823 	if ((nmp->nm_iflag & NFSMNT_SNDLOCK) == 0)
1824 		panic("nfs sndunlock");
1825 	nmp->nm_iflag &= ~NFSMNT_SNDLOCK;
1826 	cv_signal(&nmp->nm_sndcv);
1827 	mutex_exit(&nmp->nm_lock);
1828 }
1829 #endif /* NFS */
1830 
1831 static int
1832 nfs_rcvlock(struct nfsmount *nmp, struct nfsreq *rep)
1833 {
1834 	int *flagp = &nmp->nm_iflag;
1835 	int slptimeo = 0;
1836 	bool catch;
1837 	int error = 0;
1838 
1839 	KASSERT(nmp == rep->r_nmp);
1840 
1841 	catch = (nmp->nm_flag & NFSMNT_INT) != 0;
1842 	mutex_enter(&nmp->nm_lock);
1843 	while (/* CONSTCOND */ true) {
1844 		if (*flagp & NFSMNT_DISMNT) {
1845 			cv_signal(&nmp->nm_disconcv);
1846 			error = EIO;
1847 			break;
1848 		}
1849 		/* If our reply was received while we were sleeping,
1850 		 * then just return without taking the lock to avoid a
1851 		 * situation where a single iod could 'capture' the
1852 		 * receive lock.
1853 		 */
1854 		if (rep->r_mrep != NULL) {
1855 			error = EALREADY;
1856 			break;
1857 		}
1858 		if (nfs_sigintr(rep->r_nmp, rep, rep->r_lwp)) {
1859 			error = EINTR;
1860 			break;
1861 		}
1862 		if ((*flagp & NFSMNT_RCVLOCK) == 0) {
1863 			*flagp |= NFSMNT_RCVLOCK;
1864 			break;
1865 		}
1866 		if (catch) {
1867 			cv_timedwait_sig(&nmp->nm_rcvcv, &nmp->nm_lock,
1868 			    slptimeo);
1869 		} else {
1870 			cv_timedwait(&nmp->nm_rcvcv, &nmp->nm_lock,
1871 			    slptimeo);
1872 		}
1873 		if (catch) {
1874 			catch = false;
1875 			slptimeo = 2 * hz;
1876 		}
1877 	}
1878 	mutex_exit(&nmp->nm_lock);
1879 	return error;
1880 }
1881 
1882 /*
1883  * Unlock the stream socket for others.
1884  */
1885 static void
1886 nfs_rcvunlock(struct nfsmount *nmp)
1887 {
1888 
1889 	mutex_enter(&nmp->nm_lock);
1890 	if ((nmp->nm_iflag & NFSMNT_RCVLOCK) == 0)
1891 		panic("nfs rcvunlock");
1892 	nmp->nm_iflag &= ~NFSMNT_RCVLOCK;
1893 	cv_broadcast(&nmp->nm_rcvcv);
1894 	mutex_exit(&nmp->nm_lock);
1895 }
1896 
1897 /*
1898  * Parse an RPC request
1899  * - verify it
1900  * - allocate and fill in the cred.
1901  */
1902 int
1903 nfs_getreq(struct nfsrv_descript *nd, struct nfsd *nfsd, int has_header)
1904 {
1905 	int len, i;
1906 	u_int32_t *tl;
1907 	int32_t t1;
1908 	struct uio uio;
1909 	struct iovec iov;
1910 	char *dpos, *cp2, *cp;
1911 	u_int32_t nfsvers, auth_type;
1912 	uid_t nickuid;
1913 	int error = 0, ticklen;
1914 	struct mbuf *mrep, *md;
1915 	struct nfsuid *nuidp;
1916 	struct timeval tvin, tvout;
1917 
1918 	memset(&tvout, 0, sizeof tvout);	/* XXX gcc */
1919 
1920 	KASSERT(nd->nd_cr == NULL);
1921 	mrep = nd->nd_mrep;
1922 	md = nd->nd_md;
1923 	dpos = nd->nd_dpos;
1924 	if (has_header) {
1925 		nfsm_dissect(tl, u_int32_t *, 10 * NFSX_UNSIGNED);
1926 		nd->nd_retxid = fxdr_unsigned(u_int32_t, *tl++);
1927 		if (*tl++ != rpc_call) {
1928 			m_freem(mrep);
1929 			return (EBADRPC);
1930 		}
1931 	} else
1932 		nfsm_dissect(tl, u_int32_t *, 8 * NFSX_UNSIGNED);
1933 	nd->nd_repstat = 0;
1934 	nd->nd_flag = 0;
1935 	if (*tl++ != rpc_vers) {
1936 		nd->nd_repstat = ERPCMISMATCH;
1937 		nd->nd_procnum = NFSPROC_NOOP;
1938 		return (0);
1939 	}
1940 	if (*tl != nfs_prog) {
1941 		nd->nd_repstat = EPROGUNAVAIL;
1942 		nd->nd_procnum = NFSPROC_NOOP;
1943 		return (0);
1944 	}
1945 	tl++;
1946 	nfsvers = fxdr_unsigned(u_int32_t, *tl++);
1947 	if (nfsvers < NFS_VER2 || nfsvers > NFS_VER3) {
1948 		nd->nd_repstat = EPROGMISMATCH;
1949 		nd->nd_procnum = NFSPROC_NOOP;
1950 		return (0);
1951 	}
1952 	if (nfsvers == NFS_VER3)
1953 		nd->nd_flag = ND_NFSV3;
1954 	nd->nd_procnum = fxdr_unsigned(u_int32_t, *tl++);
1955 	if (nd->nd_procnum == NFSPROC_NULL)
1956 		return (0);
1957 	if (nd->nd_procnum > NFSPROC_COMMIT ||
1958 	    (!nd->nd_flag && nd->nd_procnum > NFSV2PROC_STATFS)) {
1959 		nd->nd_repstat = EPROCUNAVAIL;
1960 		nd->nd_procnum = NFSPROC_NOOP;
1961 		return (0);
1962 	}
1963 	if ((nd->nd_flag & ND_NFSV3) == 0)
1964 		nd->nd_procnum = nfsv3_procid[nd->nd_procnum];
1965 	auth_type = *tl++;
1966 	len = fxdr_unsigned(int, *tl++);
1967 	if (len < 0 || len > RPCAUTH_MAXSIZ) {
1968 		m_freem(mrep);
1969 		return (EBADRPC);
1970 	}
1971 
1972 	nd->nd_flag &= ~ND_KERBAUTH;
1973 	/*
1974 	 * Handle auth_unix or auth_kerb.
1975 	 */
1976 	if (auth_type == rpc_auth_unix) {
1977 		uid_t uid;
1978 		gid_t gid;
1979 
1980 		nd->nd_cr = kauth_cred_alloc();
1981 		len = fxdr_unsigned(int, *++tl);
1982 		if (len < 0 || len > NFS_MAXNAMLEN) {
1983 			m_freem(mrep);
1984 			error = EBADRPC;
1985 			goto errout;
1986 		}
1987 		nfsm_adv(nfsm_rndup(len));
1988 		nfsm_dissect(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
1989 
1990 		uid = fxdr_unsigned(uid_t, *tl++);
1991 		gid = fxdr_unsigned(gid_t, *tl++);
1992 		kauth_cred_setuid(nd->nd_cr, uid);
1993 		kauth_cred_seteuid(nd->nd_cr, uid);
1994 		kauth_cred_setsvuid(nd->nd_cr, uid);
1995 		kauth_cred_setgid(nd->nd_cr, gid);
1996 		kauth_cred_setegid(nd->nd_cr, gid);
1997 		kauth_cred_setsvgid(nd->nd_cr, gid);
1998 
1999 		len = fxdr_unsigned(int, *tl);
2000 		if (len < 0 || len > RPCAUTH_UNIXGIDS) {
2001 			m_freem(mrep);
2002 			error = EBADRPC;
2003 			goto errout;
2004 		}
2005 		nfsm_dissect(tl, u_int32_t *, (len + 2) * NFSX_UNSIGNED);
2006 
2007 		if (len > 0) {
2008 			size_t grbuf_size = min(len, NGROUPS) * sizeof(gid_t);
2009 			gid_t *grbuf = kmem_alloc(grbuf_size, KM_SLEEP);
2010 
2011 			for (i = 0; i < len; i++) {
2012 				if (i < NGROUPS) /* XXX elad */
2013 					grbuf[i] = fxdr_unsigned(gid_t, *tl++);
2014 				else
2015 					tl++;
2016 			}
2017 			kauth_cred_setgroups(nd->nd_cr, grbuf,
2018 			    min(len, NGROUPS), -1, UIO_SYSSPACE);
2019 			kmem_free(grbuf, grbuf_size);
2020 		}
2021 
2022 		len = fxdr_unsigned(int, *++tl);
2023 		if (len < 0 || len > RPCAUTH_MAXSIZ) {
2024 			m_freem(mrep);
2025 			error = EBADRPC;
2026 			goto errout;
2027 		}
2028 		if (len > 0)
2029 			nfsm_adv(nfsm_rndup(len));
2030 	} else if (auth_type == rpc_auth_kerb) {
2031 		switch (fxdr_unsigned(int, *tl++)) {
2032 		case RPCAKN_FULLNAME:
2033 			ticklen = fxdr_unsigned(int, *tl);
2034 			*((u_int32_t *)nfsd->nfsd_authstr) = *tl;
2035 			uio.uio_resid = nfsm_rndup(ticklen) + NFSX_UNSIGNED;
2036 			nfsd->nfsd_authlen = uio.uio_resid + NFSX_UNSIGNED;
2037 			if (uio.uio_resid > (len - 2 * NFSX_UNSIGNED)) {
2038 				m_freem(mrep);
2039 				error = EBADRPC;
2040 				goto errout;
2041 			}
2042 			uio.uio_offset = 0;
2043 			uio.uio_iov = &iov;
2044 			uio.uio_iovcnt = 1;
2045 			UIO_SETUP_SYSSPACE(&uio);
2046 			iov.iov_base = (void *)&nfsd->nfsd_authstr[4];
2047 			iov.iov_len = RPCAUTH_MAXSIZ - 4;
2048 			nfsm_mtouio(&uio, uio.uio_resid);
2049 			nfsm_dissect(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2050 			if (*tl++ != rpc_auth_kerb ||
2051 				fxdr_unsigned(int, *tl) != 4 * NFSX_UNSIGNED) {
2052 				printf("Bad kerb verifier\n");
2053 				nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2054 				nd->nd_procnum = NFSPROC_NOOP;
2055 				return (0);
2056 			}
2057 			nfsm_dissect(cp, void *, 4 * NFSX_UNSIGNED);
2058 			tl = (u_int32_t *)cp;
2059 			if (fxdr_unsigned(int, *tl) != RPCAKN_FULLNAME) {
2060 				printf("Not fullname kerb verifier\n");
2061 				nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2062 				nd->nd_procnum = NFSPROC_NOOP;
2063 				return (0);
2064 			}
2065 			cp += NFSX_UNSIGNED;
2066 			memcpy(nfsd->nfsd_verfstr, cp, 3 * NFSX_UNSIGNED);
2067 			nfsd->nfsd_verflen = 3 * NFSX_UNSIGNED;
2068 			nd->nd_flag |= ND_KERBFULL;
2069 			nfsd->nfsd_flag |= NFSD_NEEDAUTH;
2070 			break;
2071 		case RPCAKN_NICKNAME:
2072 			if (len != 2 * NFSX_UNSIGNED) {
2073 				printf("Kerb nickname short\n");
2074 				nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADCRED);
2075 				nd->nd_procnum = NFSPROC_NOOP;
2076 				return (0);
2077 			}
2078 			nickuid = fxdr_unsigned(uid_t, *tl);
2079 			nfsm_dissect(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2080 			if (*tl++ != rpc_auth_kerb ||
2081 				fxdr_unsigned(int, *tl) != 3 * NFSX_UNSIGNED) {
2082 				printf("Kerb nick verifier bad\n");
2083 				nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2084 				nd->nd_procnum = NFSPROC_NOOP;
2085 				return (0);
2086 			}
2087 			nfsm_dissect(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2088 			tvin.tv_sec = *tl++;
2089 			tvin.tv_usec = *tl;
2090 
2091 			LIST_FOREACH(nuidp, NUIDHASH(nfsd->nfsd_slp, nickuid),
2092 			    nu_hash) {
2093 				if (kauth_cred_geteuid(nuidp->nu_cr) == nickuid &&
2094 				    (!nd->nd_nam2 ||
2095 				     netaddr_match(NU_NETFAM(nuidp),
2096 				      &nuidp->nu_haddr, nd->nd_nam2)))
2097 					break;
2098 			}
2099 			if (!nuidp) {
2100 				nd->nd_repstat =
2101 					(NFSERR_AUTHERR|AUTH_REJECTCRED);
2102 				nd->nd_procnum = NFSPROC_NOOP;
2103 				return (0);
2104 			}
2105 
2106 			/*
2107 			 * Now, decrypt the timestamp using the session key
2108 			 * and validate it.
2109 			 */
2110 #ifdef NFSKERB
2111 			XXX
2112 #endif
2113 
2114 			tvout.tv_sec = fxdr_unsigned(long, tvout.tv_sec);
2115 			tvout.tv_usec = fxdr_unsigned(long, tvout.tv_usec);
2116 			if (nuidp->nu_expire < time_second ||
2117 			    nuidp->nu_timestamp.tv_sec > tvout.tv_sec ||
2118 			    (nuidp->nu_timestamp.tv_sec == tvout.tv_sec &&
2119 			     nuidp->nu_timestamp.tv_usec > tvout.tv_usec)) {
2120 				nuidp->nu_expire = 0;
2121 				nd->nd_repstat =
2122 				    (NFSERR_AUTHERR|AUTH_REJECTVERF);
2123 				nd->nd_procnum = NFSPROC_NOOP;
2124 				return (0);
2125 			}
2126 			kauth_cred_hold(nuidp->nu_cr);
2127 			nd->nd_cr = nuidp->nu_cr;
2128 			nd->nd_flag |= ND_KERBNICK;
2129 		}
2130 	} else {
2131 		nd->nd_repstat = (NFSERR_AUTHERR | AUTH_REJECTCRED);
2132 		nd->nd_procnum = NFSPROC_NOOP;
2133 		return (0);
2134 	}
2135 
2136 	nd->nd_md = md;
2137 	nd->nd_dpos = dpos;
2138 	KASSERT((nd->nd_cr == NULL && (nfsd->nfsd_flag & NFSD_NEEDAUTH) != 0)
2139 	     || (nd->nd_cr != NULL && (nfsd->nfsd_flag & NFSD_NEEDAUTH) == 0));
2140 	return (0);
2141 nfsmout:
2142 errout:
2143 	KASSERT(error != 0);
2144 	if (nd->nd_cr != NULL) {
2145 		kauth_cred_free(nd->nd_cr);
2146 		nd->nd_cr = NULL;
2147 	}
2148 	return (error);
2149 }
2150 
2151 int
2152 nfs_msg(struct lwp *l, const char *server, const char *msg)
2153 {
2154 	tpr_t tpr;
2155 
2156 	if (l)
2157 		tpr = tprintf_open(l->l_proc);
2158 	else
2159 		tpr = NULL;
2160 	tprintf(tpr, "nfs server %s: %s\n", server, msg);
2161 	tprintf_close(tpr);
2162 	return (0);
2163 }
2164 
2165 static struct pool nfs_srvdesc_pool;
2166 
2167 void
2168 nfsdreq_init(void)
2169 {
2170 
2171 	pool_init(&nfs_srvdesc_pool, sizeof(struct nfsrv_descript),
2172 	    0, 0, 0, "nfsrvdescpl", &pool_allocator_nointr, IPL_NONE);
2173 }
2174 
2175 void
2176 nfsdreq_fini(void)
2177 {
2178 
2179 	pool_destroy(&nfs_srvdesc_pool);
2180 }
2181 
2182 struct nfsrv_descript *
2183 nfsdreq_alloc(void)
2184 {
2185 	struct nfsrv_descript *nd;
2186 
2187 	nd = pool_get(&nfs_srvdesc_pool, PR_WAITOK);
2188 	nd->nd_cr = NULL;
2189 	return nd;
2190 }
2191 
2192 void
2193 nfsdreq_free(struct nfsrv_descript *nd)
2194 {
2195 	kauth_cred_t cr;
2196 
2197 	cr = nd->nd_cr;
2198 	if (cr != NULL) {
2199 		kauth_cred_free(cr);
2200 	}
2201 	pool_put(&nfs_srvdesc_pool, nd);
2202 }
2203