Home | History | Annotate | Line # | Download | only in nfs
nfs_socket.c revision 1.114.2.8
      1 /*	$NetBSD: nfs_socket.c,v 1.114.2.8 2008/02/15 10:40:08 yamt 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.114.2.8 2008/02/15 10:40:08 yamt Exp $");
     43 
     44 #include "fs_nfs.h"
     45 #include "opt_nfs.h"
     46 #include "opt_nfsserver.h"
     47 #include "opt_mbuftrace.h"
     48 #include "opt_inet.h"
     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 /*
    118  * Defines which timer to use for the procnum.
    119  * 0 - default
    120  * 1 - getattr
    121  * 2 - lookup
    122  * 3 - read
    123  * 4 - write
    124  */
    125 static const int proct[NFS_NPROCS] = {
    126 	[NFSPROC_NULL] = 0,
    127 	[NFSPROC_GETATTR] = 1,
    128 	[NFSPROC_SETATTR] = 0,
    129 	[NFSPROC_LOOKUP] = 2,
    130 	[NFSPROC_ACCESS] = 1,
    131 	[NFSPROC_READLINK] = 3,
    132 	[NFSPROC_READ] = 3,
    133 	[NFSPROC_WRITE] = 4,
    134 	[NFSPROC_CREATE] = 0,
    135 	[NFSPROC_MKDIR] = 0,
    136 	[NFSPROC_SYMLINK] = 0,
    137 	[NFSPROC_MKNOD] = 0,
    138 	[NFSPROC_REMOVE] = 0,
    139 	[NFSPROC_RMDIR] = 0,
    140 	[NFSPROC_RENAME] = 0,
    141 	[NFSPROC_LINK] = 0,
    142 	[NFSPROC_READDIR] = 3,
    143 	[NFSPROC_READDIRPLUS] = 3,
    144 	[NFSPROC_FSSTAT] = 0,
    145 	[NFSPROC_FSINFO] = 0,
    146 	[NFSPROC_PATHCONF] = 0,
    147 	[NFSPROC_COMMIT] = 0,
    148 	[NFSPROC_NOOP] = 0,
    149 };
    150 
    151 /*
    152  * There is a congestion window for outstanding rpcs maintained per mount
    153  * point. The cwnd size is adjusted in roughly the way that:
    154  * Van Jacobson, Congestion avoidance and Control, In "Proceedings of
    155  * SIGCOMM '88". ACM, August 1988.
    156  * describes for TCP. The cwnd size is chopped in half on a retransmit timeout
    157  * and incremented by 1/cwnd when each rpc reply is received and a full cwnd
    158  * of rpcs is in progress.
    159  * (The sent count and cwnd are scaled for integer arith.)
    160  * Variants of "slow start" were tried and were found to be too much of a
    161  * performance hit (ave. rtt 3 times larger),
    162  * I suspect due to the large rtt that nfs rpcs have.
    163  */
    164 #define	NFS_CWNDSCALE	256
    165 #define	NFS_MAXCWND	(NFS_CWNDSCALE * 32)
    166 static const int nfs_backoff[8] = { 2, 4, 8, 16, 32, 64, 128, 256, };
    167 int nfsrtton = 0;
    168 struct nfsrtt nfsrtt;
    169 kmutex_t nfs_reqq_lock;
    170 struct nfsreqhead nfs_reqq;
    171 static callout_t nfs_timer_ch;
    172 static struct evcnt nfs_timer_ev;
    173 static struct evcnt nfs_timer_start_ev;
    174 static struct evcnt nfs_timer_stop_ev;
    175 
    176 static int nfs_sndlock(struct nfsmount *, struct nfsreq *);
    177 static void nfs_sndunlock(struct nfsmount *);
    178 static int nfs_rcvlock(struct nfsmount *, struct nfsreq *);
    179 static void nfs_rcvunlock(struct nfsmount *);
    180 
    181 #if defined(NFSSERVER)
    182 static void nfsrv_wakenfsd_locked(struct nfssvc_sock *);
    183 #endif /* defined(NFSSERVER) */
    184 
    185 /*
    186  * Initialize sockets and congestion for a new NFS connection.
    187  * We do not free the sockaddr if error.
    188  */
    189 int
    190 nfs_connect(nmp, rep, l)
    191 	struct nfsmount *nmp;
    192 	struct nfsreq *rep;
    193 	struct lwp *l;
    194 {
    195 	struct socket *so;
    196 	int s, error, rcvreserve, sndreserve;
    197 	struct sockaddr *saddr;
    198 	struct sockaddr_in *sin;
    199 #ifdef INET6
    200 	struct sockaddr_in6 *sin6;
    201 #endif
    202 	struct mbuf *m;
    203 
    204 	KERNEL_LOCK(1, NULL);
    205 
    206 	nmp->nm_so = (struct socket *)0;
    207 	saddr = mtod(nmp->nm_nam, struct sockaddr *);
    208 	error = socreate(saddr->sa_family, &nmp->nm_so,
    209 		nmp->nm_sotype, nmp->nm_soproto, l);
    210 	if (error)
    211 		goto bad;
    212 	so = nmp->nm_so;
    213 #ifdef MBUFTRACE
    214 	so->so_mowner = &nfs_mowner;
    215 	so->so_rcv.sb_mowner = &nfs_mowner;
    216 	so->so_snd.sb_mowner = &nfs_mowner;
    217 #endif
    218 	nmp->nm_soflags = so->so_proto->pr_flags;
    219 
    220 	/*
    221 	 * Some servers require that the client port be a reserved port number.
    222 	 */
    223 	if (saddr->sa_family == AF_INET && (nmp->nm_flag & NFSMNT_RESVPORT)) {
    224 		m = m_get(M_WAIT, MT_SOOPTS);
    225 		MCLAIM(m, so->so_mowner);
    226 		*mtod(m, int32_t *) = IP_PORTRANGE_LOW;
    227 		m->m_len = sizeof(int32_t);
    228 		if ((error = sosetopt(so, IPPROTO_IP, IP_PORTRANGE, m)))
    229 			goto bad;
    230 		m = m_get(M_WAIT, MT_SONAME);
    231 		MCLAIM(m, so->so_mowner);
    232 		sin = mtod(m, struct sockaddr_in *);
    233 		sin->sin_len = m->m_len = sizeof (struct sockaddr_in);
    234 		sin->sin_family = AF_INET;
    235 		sin->sin_addr.s_addr = INADDR_ANY;
    236 		sin->sin_port = 0;
    237 		error = sobind(so, m, &lwp0);
    238 		m_freem(m);
    239 		if (error)
    240 			goto bad;
    241 	}
    242 #ifdef INET6
    243 	if (saddr->sa_family == AF_INET6 && (nmp->nm_flag & NFSMNT_RESVPORT)) {
    244 		m = m_get(M_WAIT, MT_SOOPTS);
    245 		MCLAIM(m, so->so_mowner);
    246 		*mtod(m, int32_t *) = IPV6_PORTRANGE_LOW;
    247 		m->m_len = sizeof(int32_t);
    248 		if ((error = sosetopt(so, IPPROTO_IPV6, IPV6_PORTRANGE, m)))
    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 		sin6->sin6_len = m->m_len = sizeof (struct sockaddr_in6);
    254 		sin6->sin6_family = AF_INET6;
    255 		sin6->sin6_addr = in6addr_any;
    256 		sin6->sin6_port = 0;
    257 		error = sobind(so, m, &lwp0);
    258 		m_freem(m);
    259 		if (error)
    260 			goto bad;
    261 	}
    262 #endif
    263 
    264 	/*
    265 	 * Protocols that do not require connections may be optionally left
    266 	 * unconnected for servers that reply from a port other than NFS_PORT.
    267 	 */
    268 	if (nmp->nm_flag & NFSMNT_NOCONN) {
    269 		if (nmp->nm_soflags & PR_CONNREQUIRED) {
    270 			error = ENOTCONN;
    271 			goto bad;
    272 		}
    273 	} else {
    274 		error = soconnect(so, nmp->nm_nam, l);
    275 		if (error)
    276 			goto bad;
    277 
    278 		/*
    279 		 * Wait for the connection to complete. Cribbed from the
    280 		 * connect system call but with the wait timing out so
    281 		 * that interruptible mounts don't hang here for a long time.
    282 		 */
    283 		s = splsoftnet();
    284 		while ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
    285 			(void) tsleep((void *)&so->so_timeo, PSOCK,
    286 				"nfscn1", 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 				splx(s);
    292 				goto bad;
    293 			}
    294 		}
    295 		if (so->so_error) {
    296 			error = so->so_error;
    297 			so->so_error = 0;
    298 			splx(s);
    299 			goto bad;
    300 		}
    301 		splx(s);
    302 	}
    303 	if (nmp->nm_flag & (NFSMNT_SOFT | NFSMNT_INT)) {
    304 		so->so_rcv.sb_timeo = (5 * hz);
    305 		so->so_snd.sb_timeo = (5 * hz);
    306 	} else {
    307 		/*
    308 		 * enable receive timeout to detect server crash and reconnect.
    309 		 * otherwise, we can be stuck in soreceive forever.
    310 		 */
    311 		so->so_rcv.sb_timeo = (5 * hz);
    312 		so->so_snd.sb_timeo = 0;
    313 	}
    314 	if (nmp->nm_sotype == SOCK_DGRAM) {
    315 		sndreserve = (nmp->nm_wsize + NFS_MAXPKTHDR) * 2;
    316 		rcvreserve = (max(nmp->nm_rsize, nmp->nm_readdirsize) +
    317 		    NFS_MAXPKTHDR) * 2;
    318 	} else if (nmp->nm_sotype == SOCK_SEQPACKET) {
    319 		sndreserve = (nmp->nm_wsize + NFS_MAXPKTHDR) * 2;
    320 		rcvreserve = (max(nmp->nm_rsize, nmp->nm_readdirsize) +
    321 		    NFS_MAXPKTHDR) * 2;
    322 	} else {
    323 		if (nmp->nm_sotype != SOCK_STREAM)
    324 			panic("nfscon sotype");
    325 		if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
    326 			m = m_get(M_WAIT, MT_SOOPTS);
    327 			MCLAIM(m, so->so_mowner);
    328 			*mtod(m, int32_t *) = 1;
    329 			m->m_len = sizeof(int32_t);
    330 			sosetopt(so, SOL_SOCKET, SO_KEEPALIVE, m);
    331 		}
    332 		if (so->so_proto->pr_protocol == IPPROTO_TCP) {
    333 			m = m_get(M_WAIT, MT_SOOPTS);
    334 			MCLAIM(m, so->so_mowner);
    335 			*mtod(m, int32_t *) = 1;
    336 			m->m_len = sizeof(int32_t);
    337 			sosetopt(so, IPPROTO_TCP, TCP_NODELAY, m);
    338 		}
    339 		sndreserve = (nmp->nm_wsize + NFS_MAXPKTHDR +
    340 		    sizeof (u_int32_t)) * 2;
    341 		rcvreserve = (nmp->nm_rsize + NFS_MAXPKTHDR +
    342 		    sizeof (u_int32_t)) * 2;
    343 	}
    344 	error = soreserve(so, sndreserve, rcvreserve);
    345 	if (error)
    346 		goto bad;
    347 	so->so_rcv.sb_flags |= SB_NOINTR;
    348 	so->so_snd.sb_flags |= SB_NOINTR;
    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 	KERNEL_UNLOCK_ONE(NULL);
    359 	return (0);
    360 
    361 bad:
    362 	nfs_disconnect(nmp);
    363 	KERNEL_UNLOCK_ONE(NULL);
    364 	return (error);
    365 }
    366 
    367 /*
    368  * Reconnect routine:
    369  * Called when a connection is broken on a reliable protocol.
    370  * - clean up the old socket
    371  * - nfs_connect() again
    372  * - set R_MUSTRESEND for all outstanding requests on mount point
    373  * If this fails the mount point is DEAD!
    374  * nb: Must be called with the nfs_sndlock() set on the mount point.
    375  */
    376 int
    377 nfs_reconnect(struct nfsreq *rep)
    378 {
    379 	struct nfsreq *rp;
    380 	struct nfsmount *nmp = rep->r_nmp;
    381 	int error;
    382 
    383 	nfs_disconnect(nmp);
    384 	while ((error = nfs_connect(nmp, rep, &lwp0)) != 0) {
    385 		if (error == EINTR || error == ERESTART)
    386 			return (EINTR);
    387 		kpause("nfscn2", false, hz, NULL);
    388 	}
    389 
    390 	/*
    391 	 * Loop through outstanding request list and fix up all requests
    392 	 * on old socket.
    393 	 */
    394 	mutex_enter(&nfs_reqq_lock);
    395 	TAILQ_FOREACH(rp, &nfs_reqq, r_chain) {
    396 		if (rp->r_nmp == nmp) {
    397 			if ((rp->r_flags & R_MUSTRESEND) == 0)
    398 				rp->r_flags |= R_MUSTRESEND | R_REXMITTED;
    399 			rp->r_rexmit = 0;
    400 		}
    401 	}
    402 	mutex_exit(&nfs_reqq_lock);
    403 	return (0);
    404 }
    405 
    406 /*
    407  * NFS disconnect. Clean up and unlink.
    408  */
    409 void
    410 nfs_disconnect(nmp)
    411 	struct nfsmount *nmp;
    412 {
    413 	struct socket *so;
    414 	int drain = 0;
    415 
    416 	KERNEL_LOCK(1, NULL);
    417 	if (nmp->nm_so) {
    418 		so = nmp->nm_so;
    419 		nmp->nm_so = (struct socket *)0;
    420 		soshutdown(so, SHUT_RDWR);
    421 		drain = (nmp->nm_iflag & NFSMNT_DISMNT) != 0;
    422 		if (drain) {
    423 			/*
    424 			 * soshutdown() above should wake up the current
    425 			 * listener.
    426 			 * Now wake up those waiting for the receive lock, and
    427 			 * wait for them to go away unhappy, to prevent *nmp
    428 			 * from evaporating while they're sleeping.
    429 			 */
    430 			mutex_enter(&nmp->nm_lock);
    431 			while (nmp->nm_waiters > 0) {
    432 				cv_broadcast(&nmp->nm_rcvcv);
    433 				cv_broadcast(&nmp->nm_sndcv);
    434 				cv_wait(&nmp->nm_disconcv, &nmp->nm_lock);
    435 			}
    436 			mutex_exit(&nmp->nm_lock);
    437 		}
    438 		soclose(so);
    439 	}
    440 	KERNEL_UNLOCK_ONE(NULL);
    441 
    442 #ifdef DIAGNOSTIC
    443 	if (drain && (nmp->nm_waiters > 0))
    444 		panic("nfs_disconnect: waiters left after drain?");
    445 #endif
    446 }
    447 
    448 void
    449 nfs_safedisconnect(nmp)
    450 	struct nfsmount *nmp;
    451 {
    452 	struct nfsreq dummyreq;
    453 
    454 	memset(&dummyreq, 0, sizeof(dummyreq));
    455 	dummyreq.r_nmp = nmp;
    456 	nfs_rcvlock(nmp, &dummyreq); /* XXX ignored error return */
    457 	nfs_disconnect(nmp);
    458 	nfs_rcvunlock(nmp);
    459 }
    460 
    461 /*
    462  * This is the nfs send routine. For connection based socket types, it
    463  * must be called with an nfs_sndlock() on the socket.
    464  * "rep == NULL" indicates that it has been called from a server.
    465  * For the client side:
    466  * - return EINTR if the RPC is terminated, 0 otherwise
    467  * - set R_MUSTRESEND if the send fails for any reason
    468  * - do any cleanup required by recoverable socket errors (? ? ?)
    469  * For the server side:
    470  * - return EINTR or ERESTART if interrupted by a signal
    471  * - return EPIPE if a connection is lost for connection based sockets (TCP...)
    472  * - do any cleanup required by recoverable socket errors (? ? ?)
    473  */
    474 int
    475 nfs_send(so, nam, top, rep, l)
    476 	struct socket *so;
    477 	struct mbuf *nam;
    478 	struct mbuf *top;
    479 	struct nfsreq *rep;
    480 	struct lwp *l;
    481 {
    482 	struct mbuf *sendnam;
    483 	int error, soflags, flags;
    484 
    485 	/* XXX nfs_doio()/nfs_request() calls with  rep->r_lwp == NULL */
    486 	if (l == NULL && rep->r_lwp == NULL)
    487 		l = curlwp;
    488 
    489 	if (rep) {
    490 		if (rep->r_flags & R_SOFTTERM) {
    491 			m_freem(top);
    492 			return (EINTR);
    493 		}
    494 		if ((so = rep->r_nmp->nm_so) == NULL) {
    495 			rep->r_flags |= R_MUSTRESEND;
    496 			m_freem(top);
    497 			return (0);
    498 		}
    499 		rep->r_flags &= ~R_MUSTRESEND;
    500 		soflags = rep->r_nmp->nm_soflags;
    501 	} else
    502 		soflags = so->so_proto->pr_flags;
    503 	if ((soflags & PR_CONNREQUIRED) || (so->so_state & SS_ISCONNECTED))
    504 		sendnam = (struct mbuf *)0;
    505 	else
    506 		sendnam = nam;
    507 	if (so->so_type == SOCK_SEQPACKET)
    508 		flags = MSG_EOR;
    509 	else
    510 		flags = 0;
    511 
    512 	KERNEL_LOCK(1, curlwp);
    513 	error = (*so->so_send)(so, sendnam, NULL, top, NULL, flags,  l);
    514 	KERNEL_UNLOCK_ONE(curlwp);
    515 	if (error) {
    516 		if (rep) {
    517 			if (error == ENOBUFS && so->so_type == SOCK_DGRAM) {
    518 				/*
    519 				 * We're too fast for the network/driver,
    520 				 * and UDP isn't flowcontrolled.
    521 				 * We need to resend. This is not fatal,
    522 				 * just try again.
    523 				 *
    524 				 * Could be smarter here by doing some sort
    525 				 * of a backoff, but this is rare.
    526 				 */
    527 				rep->r_flags |= R_MUSTRESEND;
    528 			} else {
    529 				if (error != EPIPE)
    530 					log(LOG_INFO,
    531 					    "nfs send error %d for %s\n",
    532 					    error,
    533 					    rep->r_nmp->nm_mountp->
    534 						    mnt_stat.f_mntfromname);
    535 				/*
    536 				 * Deal with errors for the client side.
    537 				 */
    538 				if (rep->r_flags & R_SOFTTERM)
    539 					error = EINTR;
    540 				else
    541 					rep->r_flags |= R_MUSTRESEND;
    542 			}
    543 		} else {
    544 			/*
    545 			 * See above. This error can happen under normal
    546 			 * circumstances and the log is too noisy.
    547 			 * The error will still show up in nfsstat.
    548 			 */
    549 			if (error != ENOBUFS || so->so_type != SOCK_DGRAM)
    550 				log(LOG_INFO, "nfsd send error %d\n", error);
    551 		}
    552 
    553 		/*
    554 		 * Handle any recoverable (soft) socket errors here. (? ? ?)
    555 		 */
    556 		if (error != EINTR && error != ERESTART &&
    557 			error != EWOULDBLOCK && error != EPIPE)
    558 			error = 0;
    559 	}
    560 	return (error);
    561 }
    562 
    563 #ifdef NFS
    564 /*
    565  * Receive a Sun RPC Request/Reply. For SOCK_DGRAM, the work is all
    566  * done by soreceive(), but for SOCK_STREAM we must deal with the Record
    567  * Mark and consolidate the data into a new mbuf list.
    568  * nb: Sometimes TCP passes the data up to soreceive() in long lists of
    569  *     small mbufs.
    570  * For SOCK_STREAM we must be very careful to read an entire record once
    571  * we have read any of it, even if the system call has been interrupted.
    572  */
    573 int
    574 nfs_receive(rep, aname, mp, l)
    575 	struct nfsreq *rep;
    576 	struct mbuf **aname;
    577 	struct mbuf **mp;
    578 	struct lwp *l;
    579 {
    580 	struct socket *so;
    581 	struct uio auio;
    582 	struct iovec aio;
    583 	struct mbuf *m;
    584 	struct mbuf *control;
    585 	u_int32_t len;
    586 	struct mbuf **getnam;
    587 	int error, sotype, rcvflg;
    588 
    589 	/*
    590 	 * Set up arguments for soreceive()
    591 	 */
    592 	*mp = (struct mbuf *)0;
    593 	*aname = (struct mbuf *)0;
    594 	sotype = rep->r_nmp->nm_sotype;
    595 
    596 	/*
    597 	 * For reliable protocols, lock against other senders/receivers
    598 	 * in case a reconnect is necessary.
    599 	 * For SOCK_STREAM, first get the Record Mark to find out how much
    600 	 * more there is to get.
    601 	 * We must lock the socket against other receivers
    602 	 * until we have an entire rpc request/reply.
    603 	 */
    604 	if (sotype != SOCK_DGRAM) {
    605 		error = nfs_sndlock(rep->r_nmp, rep);
    606 		if (error)
    607 			return (error);
    608 tryagain:
    609 		/*
    610 		 * Check for fatal errors and resending request.
    611 		 */
    612 		/*
    613 		 * Ugh: If a reconnect attempt just happened, nm_so
    614 		 * would have changed. NULL indicates a failed
    615 		 * attempt that has essentially shut down this
    616 		 * mount point.
    617 		 */
    618 		if (rep->r_mrep || (rep->r_flags & R_SOFTTERM)) {
    619 			nfs_sndunlock(rep->r_nmp);
    620 			return (EINTR);
    621 		}
    622 		so = rep->r_nmp->nm_so;
    623 		if (!so) {
    624 			error = nfs_reconnect(rep);
    625 			if (error) {
    626 				nfs_sndunlock(rep->r_nmp);
    627 				return (error);
    628 			}
    629 			goto tryagain;
    630 		}
    631 		while (rep->r_flags & R_MUSTRESEND) {
    632 			m = m_copym(rep->r_mreq, 0, M_COPYALL, M_WAIT);
    633 			nfsstats.rpcretries++;
    634 			rep->r_rtt = 0;
    635 			rep->r_flags &= ~R_TIMING;
    636 			error = nfs_send(so, rep->r_nmp->nm_nam, m, rep, l);
    637 			if (error) {
    638 				if (error == EINTR || error == ERESTART ||
    639 				    (error = nfs_reconnect(rep)) != 0) {
    640 					nfs_sndunlock(rep->r_nmp);
    641 					return (error);
    642 				}
    643 				goto tryagain;
    644 			}
    645 		}
    646 		nfs_sndunlock(rep->r_nmp);
    647 		if (sotype == SOCK_STREAM) {
    648 			aio.iov_base = (void *) &len;
    649 			aio.iov_len = sizeof(u_int32_t);
    650 			auio.uio_iov = &aio;
    651 			auio.uio_iovcnt = 1;
    652 			auio.uio_rw = UIO_READ;
    653 			auio.uio_offset = 0;
    654 			auio.uio_resid = sizeof(u_int32_t);
    655 			UIO_SETUP_SYSSPACE(&auio);
    656 			do {
    657 			   rcvflg = MSG_WAITALL;
    658 			   KERNEL_LOCK(1, NULL);
    659 			   error = (*so->so_receive)(so, (struct mbuf **)0, &auio,
    660 				(struct mbuf **)0, (struct mbuf **)0, &rcvflg);
    661 			   KERNEL_UNLOCK_ONE(NULL);
    662 			   if (error == EWOULDBLOCK && rep) {
    663 				if (rep->r_flags & R_SOFTTERM)
    664 					return (EINTR);
    665 				/*
    666 				 * if it seems that the server died after it
    667 				 * received our request, set EPIPE so that
    668 				 * we'll reconnect and retransmit requests.
    669 				 */
    670 				if (rep->r_rexmit >= rep->r_nmp->nm_retry) {
    671 					nfsstats.rpctimeouts++;
    672 					error = EPIPE;
    673 				}
    674 			   }
    675 			} while (error == EWOULDBLOCK);
    676 			if (!error && auio.uio_resid > 0) {
    677 			    /*
    678 			     * Don't log a 0 byte receive; it means
    679 			     * that the socket has been closed, and
    680 			     * can happen during normal operation
    681 			     * (forcible unmount or Solaris server).
    682 			     */
    683 			    if (auio.uio_resid != sizeof (u_int32_t))
    684 			      log(LOG_INFO,
    685 				 "short receive (%lu/%lu) from nfs server %s\n",
    686 				 (u_long)sizeof(u_int32_t) - auio.uio_resid,
    687 				 (u_long)sizeof(u_int32_t),
    688 				 rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
    689 			    error = EPIPE;
    690 			}
    691 			if (error)
    692 				goto errout;
    693 			len = ntohl(len) & ~0x80000000;
    694 			/*
    695 			 * This is SERIOUS! We are out of sync with the sender
    696 			 * and forcing a disconnect/reconnect is all I can do.
    697 			 */
    698 			if (len > NFS_MAXPACKET) {
    699 			    log(LOG_ERR, "%s (%d) from nfs server %s\n",
    700 				"impossible packet length",
    701 				len,
    702 				rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
    703 			    error = EFBIG;
    704 			    goto errout;
    705 			}
    706 			auio.uio_resid = len;
    707 			do {
    708 			    rcvflg = MSG_WAITALL;
    709 			    KERNEL_LOCK(1, NULL);
    710 			    error =  (*so->so_receive)(so, (struct mbuf **)0,
    711 				&auio, mp, (struct mbuf **)0, &rcvflg);
    712 			    KERNEL_UNLOCK_ONE(NULL);
    713 			} while (error == EWOULDBLOCK || error == EINTR ||
    714 				 error == ERESTART);
    715 			if (!error && auio.uio_resid > 0) {
    716 			    if (len != auio.uio_resid)
    717 			      log(LOG_INFO,
    718 				"short receive (%lu/%d) from nfs server %s\n",
    719 				(u_long)len - auio.uio_resid, len,
    720 				rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
    721 			    error = EPIPE;
    722 			}
    723 		} else {
    724 			/*
    725 			 * NB: Since uio_resid is big, MSG_WAITALL is ignored
    726 			 * and soreceive() will return when it has either a
    727 			 * control msg or a data msg.
    728 			 * We have no use for control msg., but must grab them
    729 			 * and then throw them away so we know what is going
    730 			 * on.
    731 			 */
    732 			auio.uio_resid = len = 100000000; /* Anything Big */
    733 			/* not need to setup uio_vmspace */
    734 			do {
    735 			    rcvflg = 0;
    736 			    KERNEL_LOCK(1, NULL);
    737 			    error =  (*so->so_receive)(so, (struct mbuf **)0,
    738 				&auio, mp, &control, &rcvflg);
    739 			    KERNEL_UNLOCK_ONE(NULL);
    740 			    if (control)
    741 				m_freem(control);
    742 			    if (error == EWOULDBLOCK && rep) {
    743 				if (rep->r_flags & R_SOFTTERM)
    744 					return (EINTR);
    745 			    }
    746 			} while (error == EWOULDBLOCK ||
    747 				 (!error && *mp == NULL && control));
    748 			if ((rcvflg & MSG_EOR) == 0)
    749 				printf("Egad!!\n");
    750 			if (!error && *mp == NULL)
    751 				error = EPIPE;
    752 			len -= auio.uio_resid;
    753 		}
    754 errout:
    755 		if (error && error != EINTR && error != ERESTART) {
    756 			m_freem(*mp);
    757 			*mp = (struct mbuf *)0;
    758 			if (error != EPIPE)
    759 				log(LOG_INFO,
    760 				    "receive error %d from nfs server %s\n",
    761 				    error,
    762 				 rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
    763 			error = nfs_sndlock(rep->r_nmp, rep);
    764 			if (!error)
    765 				error = nfs_reconnect(rep);
    766 			if (!error)
    767 				goto tryagain;
    768 			else
    769 				nfs_sndunlock(rep->r_nmp);
    770 		}
    771 	} else {
    772 		if ((so = rep->r_nmp->nm_so) == NULL)
    773 			return (EACCES);
    774 		if (so->so_state & SS_ISCONNECTED)
    775 			getnam = (struct mbuf **)0;
    776 		else
    777 			getnam = aname;
    778 		auio.uio_resid = len = 1000000;
    779 		/* not need to setup uio_vmspace */
    780 		do {
    781 			rcvflg = 0;
    782 			KERNEL_LOCK(1, NULL);
    783 			error =  (*so->so_receive)(so, getnam, &auio, mp,
    784 				(struct mbuf **)0, &rcvflg);
    785 			KERNEL_UNLOCK_ONE(NULL);
    786 			if (error == EWOULDBLOCK &&
    787 			    (rep->r_flags & R_SOFTTERM))
    788 				return (EINTR);
    789 		} while (error == EWOULDBLOCK);
    790 		len -= auio.uio_resid;
    791 		if (!error && *mp == NULL)
    792 			error = EPIPE;
    793 	}
    794 	if (error) {
    795 		m_freem(*mp);
    796 		*mp = (struct mbuf *)0;
    797 	}
    798 	return (error);
    799 }
    800 
    801 /*
    802  * Implement receipt of reply on a socket.
    803  * We must search through the list of received datagrams matching them
    804  * with outstanding requests using the xid, until ours is found.
    805  */
    806 /* ARGSUSED */
    807 int
    808 nfs_reply(myrep, lwp)
    809 	struct nfsreq *myrep;
    810 	struct lwp *lwp;
    811 {
    812 	struct nfsreq *rep;
    813 	struct nfsmount *nmp = myrep->r_nmp;
    814 	int32_t t1;
    815 	struct mbuf *mrep, *nam, *md;
    816 	u_int32_t rxid, *tl;
    817 	char *dpos, *cp2;
    818 	int error;
    819 
    820 	/*
    821 	 * Loop around until we get our own reply
    822 	 */
    823 	for (;;) {
    824 		/*
    825 		 * Lock against other receivers so that I don't get stuck in
    826 		 * sbwait() after someone else has received my reply for me.
    827 		 * Also necessary for connection based protocols to avoid
    828 		 * race conditions during a reconnect.
    829 		 */
    830 		error = nfs_rcvlock(nmp, myrep);
    831 		if (error == EALREADY)
    832 			return (0);
    833 		if (error)
    834 			return (error);
    835 		/*
    836 		 * Get the next Rpc reply off the socket
    837 		 */
    838 
    839 		mutex_enter(&nmp->nm_lock);
    840 		nmp->nm_waiters++;
    841 		mutex_exit(&nmp->nm_lock);
    842 
    843 		error = nfs_receive(myrep, &nam, &mrep, lwp);
    844 
    845 		mutex_enter(&nmp->nm_lock);
    846 		nmp->nm_waiters--;
    847 		cv_signal(&nmp->nm_disconcv);
    848 		mutex_exit(&nmp->nm_lock);
    849 
    850 		if (error) {
    851 			nfs_rcvunlock(nmp);
    852 
    853 			if (nmp->nm_iflag & NFSMNT_DISMNT) {
    854 				/*
    855 				 * Oops, we're going away now..
    856 				 */
    857 				return error;
    858 			}
    859 			/*
    860 			 * Ignore routing errors on connectionless protocols? ?
    861 			 */
    862 			if (NFSIGNORE_SOERROR(nmp->nm_soflags, error)) {
    863 				nmp->nm_so->so_error = 0;
    864 #ifdef DEBUG
    865 				printf("nfs_reply: ignoring error %d\n", error);
    866 #endif
    867 				continue;
    868 			}
    869 			return (error);
    870 		}
    871 		if (nam)
    872 			m_freem(nam);
    873 
    874 		/*
    875 		 * Get the xid and check that it is an rpc reply
    876 		 */
    877 		md = mrep;
    878 		dpos = mtod(md, void *);
    879 		nfsm_dissect(tl, u_int32_t *, 2*NFSX_UNSIGNED);
    880 		rxid = *tl++;
    881 		if (*tl != rpc_reply) {
    882 			nfsstats.rpcinvalid++;
    883 			m_freem(mrep);
    884 nfsmout:
    885 			nfs_rcvunlock(nmp);
    886 			continue;
    887 		}
    888 
    889 		/*
    890 		 * Loop through the request list to match up the reply
    891 		 * Iff no match, just drop the datagram
    892 		 */
    893 		mutex_enter(&nfs_reqq_lock);
    894 		TAILQ_FOREACH(rep, &nfs_reqq, r_chain) {
    895 			if (rep->r_mrep == NULL && rxid == rep->r_xid) {
    896 				/* Found it.. */
    897 				rep->r_mrep = mrep;
    898 				rep->r_md = md;
    899 				rep->r_dpos = dpos;
    900 				if (nfsrtton) {
    901 					struct rttl *rt;
    902 
    903 					rt = &nfsrtt.rttl[nfsrtt.pos];
    904 					rt->proc = rep->r_procnum;
    905 					rt->rto = NFS_RTO(nmp, proct[rep->r_procnum]);
    906 					rt->sent = nmp->nm_sent;
    907 					rt->cwnd = nmp->nm_cwnd;
    908 					rt->srtt = nmp->nm_srtt[proct[rep->r_procnum] - 1];
    909 					rt->sdrtt = nmp->nm_sdrtt[proct[rep->r_procnum] - 1];
    910 					rt->fsid = nmp->nm_mountp->mnt_stat.f_fsidx;
    911 					getmicrotime(&rt->tstamp);
    912 					if (rep->r_flags & R_TIMING)
    913 						rt->rtt = rep->r_rtt;
    914 					else
    915 						rt->rtt = 1000000;
    916 					nfsrtt.pos = (nfsrtt.pos + 1) % NFSRTTLOGSIZ;
    917 				}
    918 				/*
    919 				 * Update congestion window.
    920 				 * Do the additive increase of
    921 				 * one rpc/rtt.
    922 				 */
    923 				if (nmp->nm_cwnd <= nmp->nm_sent) {
    924 					nmp->nm_cwnd +=
    925 					   (NFS_CWNDSCALE * NFS_CWNDSCALE +
    926 					   (nmp->nm_cwnd >> 1)) / nmp->nm_cwnd;
    927 					if (nmp->nm_cwnd > NFS_MAXCWND)
    928 						nmp->nm_cwnd = NFS_MAXCWND;
    929 				}
    930 				rep->r_flags &= ~R_SENT;
    931 				nmp->nm_sent -= NFS_CWNDSCALE;
    932 				/*
    933 				 * Update rtt using a gain of 0.125 on the mean
    934 				 * and a gain of 0.25 on the deviation.
    935 				 */
    936 				if (rep->r_flags & R_TIMING) {
    937 					/*
    938 					 * Since the timer resolution of
    939 					 * NFS_HZ is so course, it can often
    940 					 * result in r_rtt == 0. Since
    941 					 * r_rtt == N means that the actual
    942 					 * rtt is between N+dt and N+2-dt ticks,
    943 					 * add 1.
    944 					 */
    945 					t1 = rep->r_rtt + 1;
    946 					t1 -= (NFS_SRTT(rep) >> 3);
    947 					NFS_SRTT(rep) += t1;
    948 					if (t1 < 0)
    949 						t1 = -t1;
    950 					t1 -= (NFS_SDRTT(rep) >> 2);
    951 					NFS_SDRTT(rep) += t1;
    952 				}
    953 				nmp->nm_timeouts = 0;
    954 				break;
    955 			}
    956 		}
    957 		mutex_exit(&nfs_reqq_lock);
    958 		nfs_rcvunlock(nmp);
    959 		/*
    960 		 * If not matched to a request, drop it.
    961 		 * If it's mine, get out.
    962 		 */
    963 		if (rep == 0) {
    964 			nfsstats.rpcunexpected++;
    965 			m_freem(mrep);
    966 		} else if (rep == myrep) {
    967 			if (rep->r_mrep == NULL)
    968 				panic("nfsreply nil");
    969 			return (0);
    970 		}
    971 	}
    972 }
    973 
    974 /*
    975  * nfs_request - goes something like this
    976  *	- fill in request struct
    977  *	- links it into list
    978  *	- calls nfs_send() for first transmit
    979  *	- calls nfs_receive() to get reply
    980  *	- break down rpc header and return with nfs reply pointed to
    981  *	  by mrep or error
    982  * nb: always frees up mreq mbuf list
    983  */
    984 int
    985 nfs_request(np, mrest, procnum, lwp, cred, mrp, mdp, dposp, rexmitp)
    986 	struct nfsnode *np;
    987 	struct mbuf *mrest;
    988 	int procnum;
    989 	struct lwp *lwp;
    990 	kauth_cred_t cred;
    991 	struct mbuf **mrp;
    992 	struct mbuf **mdp;
    993 	char **dposp;
    994 	int *rexmitp;
    995 {
    996 	struct mbuf *m, *mrep;
    997 	struct nfsreq *rep;
    998 	u_int32_t *tl;
    999 	int i;
   1000 	struct nfsmount *nmp = VFSTONFS(np->n_vnode->v_mount);
   1001 	struct mbuf *md, *mheadend;
   1002 	char nickv[RPCX_NICKVERF];
   1003 	time_t waituntil;
   1004 	char *dpos, *cp2;
   1005 	int t1, error = 0, mrest_len, auth_len, auth_type;
   1006 	int trylater_delay = NFS_TRYLATERDEL, failed_auth = 0;
   1007 	int verf_len, verf_type;
   1008 	u_int32_t xid;
   1009 	char *auth_str, *verf_str;
   1010 	NFSKERBKEY_T key;		/* save session key */
   1011 	kauth_cred_t acred;
   1012 	struct mbuf *mrest_backup = NULL;
   1013 	kauth_cred_t origcred = NULL; /* XXX: gcc */
   1014 	bool retry_cred = true;
   1015 	bool use_opencred = (np->n_flag & NUSEOPENCRED) != 0;
   1016 
   1017 	if (rexmitp != NULL)
   1018 		*rexmitp = 0;
   1019 
   1020 	acred = kauth_cred_alloc();
   1021 
   1022 tryagain_cred:
   1023 	KASSERT(cred != NULL);
   1024 	rep = kmem_alloc(sizeof(*rep), KM_SLEEP);
   1025 	rep->r_nmp = nmp;
   1026 	KASSERT(lwp == NULL || lwp == curlwp);
   1027 	rep->r_lwp = lwp;
   1028 	rep->r_procnum = procnum;
   1029 	i = 0;
   1030 	m = mrest;
   1031 	while (m) {
   1032 		i += m->m_len;
   1033 		m = m->m_next;
   1034 	}
   1035 	mrest_len = i;
   1036 
   1037 	/*
   1038 	 * Get the RPC header with authorization.
   1039 	 */
   1040 kerbauth:
   1041 	verf_str = auth_str = (char *)0;
   1042 	if (nmp->nm_flag & NFSMNT_KERB) {
   1043 		verf_str = nickv;
   1044 		verf_len = sizeof (nickv);
   1045 		auth_type = RPCAUTH_KERB4;
   1046 		memset((void *)key, 0, sizeof (key));
   1047 		if (failed_auth || nfs_getnickauth(nmp, cred, &auth_str,
   1048 			&auth_len, verf_str, verf_len)) {
   1049 			error = nfs_getauth(nmp, rep, cred, &auth_str,
   1050 				&auth_len, verf_str, &verf_len, key);
   1051 			if (error) {
   1052 				kmem_free(rep, sizeof(*rep));
   1053 				m_freem(mrest);
   1054 				KASSERT(kauth_cred_getrefcnt(acred) == 1);
   1055 				kauth_cred_free(acred);
   1056 				return (error);
   1057 			}
   1058 		}
   1059 		retry_cred = false;
   1060 	} else {
   1061 		/* AUTH_UNIX */
   1062 		uid_t uid;
   1063 		gid_t gid;
   1064 
   1065 		/*
   1066 		 * on the most unix filesystems, permission checks are
   1067 		 * done when the file is open(2)'ed.
   1068 		 * ie. once a file is successfully open'ed,
   1069 		 * following i/o operations never fail with EACCES.
   1070 		 * we try to follow the semantics as far as possible.
   1071 		 *
   1072 		 * note that we expect that the nfs server always grant
   1073 		 * accesses by the file's owner.
   1074 		 */
   1075 		origcred = cred;
   1076 		switch (procnum) {
   1077 		case NFSPROC_READ:
   1078 		case NFSPROC_WRITE:
   1079 		case NFSPROC_COMMIT:
   1080 			uid = np->n_vattr->va_uid;
   1081 			gid = np->n_vattr->va_gid;
   1082 			if (kauth_cred_geteuid(cred) == uid &&
   1083 			    kauth_cred_getegid(cred) == gid) {
   1084 				retry_cred = false;
   1085 				break;
   1086 			}
   1087 			if (use_opencred)
   1088 				break;
   1089 			kauth_cred_setuid(acred, uid);
   1090 			kauth_cred_seteuid(acred, uid);
   1091 			kauth_cred_setsvuid(acred, uid);
   1092 			kauth_cred_setgid(acred, gid);
   1093 			kauth_cred_setegid(acred, gid);
   1094 			kauth_cred_setsvgid(acred, gid);
   1095 			cred = acred;
   1096 			break;
   1097 		default:
   1098 			retry_cred = false;
   1099 			break;
   1100 		}
   1101 		/*
   1102 		 * backup mbuf chain if we can need it later to retry.
   1103 		 *
   1104 		 * XXX maybe we can keep a direct reference to
   1105 		 * mrest without doing m_copym, but it's ...ugly.
   1106 		 */
   1107 		if (retry_cred)
   1108 			mrest_backup = m_copym(mrest, 0, M_COPYALL, M_WAIT);
   1109 		auth_type = RPCAUTH_UNIX;
   1110 		/* XXX elad - ngroups */
   1111 		auth_len = (((kauth_cred_ngroups(cred) > nmp->nm_numgrps) ?
   1112 			nmp->nm_numgrps : kauth_cred_ngroups(cred)) << 2) +
   1113 			5 * NFSX_UNSIGNED;
   1114 	}
   1115 	m = nfsm_rpchead(cred, nmp->nm_flag, procnum, auth_type, auth_len,
   1116 	     auth_str, verf_len, verf_str, mrest, mrest_len, &mheadend, &xid);
   1117 	if (auth_str)
   1118 		free(auth_str, M_TEMP);
   1119 
   1120 	/*
   1121 	 * For stream protocols, insert a Sun RPC Record Mark.
   1122 	 */
   1123 	if (nmp->nm_sotype == SOCK_STREAM) {
   1124 		M_PREPEND(m, NFSX_UNSIGNED, M_WAIT);
   1125 		*mtod(m, u_int32_t *) = htonl(0x80000000 |
   1126 			 (m->m_pkthdr.len - NFSX_UNSIGNED));
   1127 	}
   1128 	rep->r_mreq = m;
   1129 	rep->r_xid = xid;
   1130 tryagain:
   1131 	if (nmp->nm_flag & NFSMNT_SOFT)
   1132 		rep->r_retry = nmp->nm_retry;
   1133 	else
   1134 		rep->r_retry = NFS_MAXREXMIT + 1;	/* past clip limit */
   1135 	rep->r_rtt = rep->r_rexmit = 0;
   1136 	if (proct[procnum] > 0)
   1137 		rep->r_flags = R_TIMING;
   1138 	else
   1139 		rep->r_flags = 0;
   1140 	rep->r_mrep = NULL;
   1141 
   1142 	/*
   1143 	 * Do the client side RPC.
   1144 	 */
   1145 	nfsstats.rpcrequests++;
   1146 	/*
   1147 	 * Chain request into list of outstanding requests. Be sure
   1148 	 * to put it LAST so timer finds oldest requests first.
   1149 	 */
   1150 	mutex_enter(&nfs_reqq_lock);
   1151 	TAILQ_INSERT_TAIL(&nfs_reqq, rep, r_chain);
   1152 
   1153 	nfs_timer_start();
   1154 
   1155 	/*
   1156 	 * If backing off another request or avoiding congestion, don't
   1157 	 * send this one now but let timer do it. If not timing a request,
   1158 	 * do it now.
   1159 	 */
   1160 	if (nmp->nm_so && (nmp->nm_sotype != SOCK_DGRAM ||
   1161 	    (nmp->nm_flag & NFSMNT_DUMBTIMR) || nmp->nm_sent < nmp->nm_cwnd)) {
   1162 		if (nmp->nm_soflags & PR_CONNREQUIRED)
   1163 			error = nfs_sndlock(nmp, rep);
   1164 		if (!error) {
   1165 			m = m_copym(rep->r_mreq, 0, M_COPYALL, M_WAIT);
   1166 			error = nfs_send(nmp->nm_so, nmp->nm_nam, m, rep, lwp);
   1167 			if (nmp->nm_soflags & PR_CONNREQUIRED)
   1168 				nfs_sndunlock(nmp);
   1169 		}
   1170 		if (!error && (rep->r_flags & R_MUSTRESEND) == 0) {
   1171 			nmp->nm_sent += NFS_CWNDSCALE;
   1172 			rep->r_flags |= R_SENT;
   1173 		}
   1174 	} else {
   1175 		rep->r_rtt = -1;
   1176 	}
   1177 
   1178 	/*
   1179 	 * Wait for the reply from our send or the timer's.
   1180 	 */
   1181 	if (!error || error == EPIPE) {
   1182 		mutex_exit(&nfs_reqq_lock);
   1183 		error = nfs_reply(rep, lwp);
   1184 		mutex_enter(&nfs_reqq_lock);
   1185 	}
   1186 
   1187 	/*
   1188 	 * RPC done, unlink the request.
   1189 	 */
   1190 	TAILQ_REMOVE(&nfs_reqq, rep, r_chain);
   1191 
   1192 	/*
   1193 	 * Decrement the outstanding request count.
   1194 	 */
   1195 	if (rep->r_flags & R_SENT) {
   1196 		rep->r_flags &= ~R_SENT;	/* paranoia */
   1197 		nmp->nm_sent -= NFS_CWNDSCALE;
   1198 	}
   1199 	mutex_exit(&nfs_reqq_lock);
   1200 
   1201 	if (rexmitp != NULL) {
   1202 		int rexmit;
   1203 
   1204 		if (nmp->nm_sotype != SOCK_DGRAM)
   1205 			rexmit = (rep->r_flags & R_REXMITTED) != 0;
   1206 		else
   1207 			rexmit = rep->r_rexmit;
   1208 		*rexmitp = rexmit;
   1209 	}
   1210 
   1211 	/*
   1212 	 * If there was a successful reply and a tprintf msg.
   1213 	 * tprintf a response.
   1214 	 */
   1215 	if (!error && (rep->r_flags & R_TPRINTFMSG))
   1216 		nfs_msg(rep->r_lwp, nmp->nm_mountp->mnt_stat.f_mntfromname,
   1217 		    "is alive again");
   1218 	mrep = rep->r_mrep;
   1219 	md = rep->r_md;
   1220 	dpos = rep->r_dpos;
   1221 	if (error)
   1222 		goto nfsmout;
   1223 
   1224 	/*
   1225 	 * break down the rpc header and check if ok
   1226 	 */
   1227 	nfsm_dissect(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
   1228 	if (*tl++ == rpc_msgdenied) {
   1229 		if (*tl == rpc_mismatch)
   1230 			error = EOPNOTSUPP;
   1231 		else if ((nmp->nm_flag & NFSMNT_KERB) && *tl++ == rpc_autherr) {
   1232 			if (!failed_auth) {
   1233 				failed_auth++;
   1234 				mheadend->m_next = (struct mbuf *)0;
   1235 				m_freem(mrep);
   1236 				m_freem(rep->r_mreq);
   1237 				goto kerbauth;
   1238 			} else
   1239 				error = EAUTH;
   1240 		} else
   1241 			error = EACCES;
   1242 		m_freem(mrep);
   1243 		goto nfsmout;
   1244 	}
   1245 
   1246 	/*
   1247 	 * Grab any Kerberos verifier, otherwise just throw it away.
   1248 	 */
   1249 	verf_type = fxdr_unsigned(int, *tl++);
   1250 	i = fxdr_unsigned(int32_t, *tl);
   1251 	if ((nmp->nm_flag & NFSMNT_KERB) && verf_type == RPCAUTH_KERB4) {
   1252 		error = nfs_savenickauth(nmp, cred, i, key, &md, &dpos, mrep);
   1253 		if (error)
   1254 			goto nfsmout;
   1255 	} else if (i > 0)
   1256 		nfsm_adv(nfsm_rndup(i));
   1257 	nfsm_dissect(tl, u_int32_t *, NFSX_UNSIGNED);
   1258 	/* 0 == ok */
   1259 	if (*tl == 0) {
   1260 		nfsm_dissect(tl, u_int32_t *, NFSX_UNSIGNED);
   1261 		if (*tl != 0) {
   1262 			error = fxdr_unsigned(int, *tl);
   1263 			switch (error) {
   1264 			case NFSERR_PERM:
   1265 				error = EPERM;
   1266 				break;
   1267 
   1268 			case NFSERR_NOENT:
   1269 				error = ENOENT;
   1270 				break;
   1271 
   1272 			case NFSERR_IO:
   1273 				error = EIO;
   1274 				break;
   1275 
   1276 			case NFSERR_NXIO:
   1277 				error = ENXIO;
   1278 				break;
   1279 
   1280 			case NFSERR_ACCES:
   1281 				error = EACCES;
   1282 				if (!retry_cred)
   1283 					break;
   1284 				m_freem(mrep);
   1285 				m_freem(rep->r_mreq);
   1286 				kmem_free(rep, sizeof(*rep));
   1287 				use_opencred = !use_opencred;
   1288 				if (mrest_backup == NULL) {
   1289 					/* m_copym failure */
   1290 					KASSERT(
   1291 					    kauth_cred_getrefcnt(acred) == 1);
   1292 					kauth_cred_free(acred);
   1293 					return ENOMEM;
   1294 				}
   1295 				mrest = mrest_backup;
   1296 				mrest_backup = NULL;
   1297 				cred = origcred;
   1298 				error = 0;
   1299 				retry_cred = false;
   1300 				goto tryagain_cred;
   1301 
   1302 			case NFSERR_EXIST:
   1303 				error = EEXIST;
   1304 				break;
   1305 
   1306 			case NFSERR_XDEV:
   1307 				error = EXDEV;
   1308 				break;
   1309 
   1310 			case NFSERR_NODEV:
   1311 				error = ENODEV;
   1312 				break;
   1313 
   1314 			case NFSERR_NOTDIR:
   1315 				error = ENOTDIR;
   1316 				break;
   1317 
   1318 			case NFSERR_ISDIR:
   1319 				error = EISDIR;
   1320 				break;
   1321 
   1322 			case NFSERR_INVAL:
   1323 				error = EINVAL;
   1324 				break;
   1325 
   1326 			case NFSERR_FBIG:
   1327 				error = EFBIG;
   1328 				break;
   1329 
   1330 			case NFSERR_NOSPC:
   1331 				error = ENOSPC;
   1332 				break;
   1333 
   1334 			case NFSERR_ROFS:
   1335 				error = EROFS;
   1336 				break;
   1337 
   1338 			case NFSERR_MLINK:
   1339 				error = EMLINK;
   1340 				break;
   1341 
   1342 			case NFSERR_TIMEDOUT:
   1343 				error = ETIMEDOUT;
   1344 				break;
   1345 
   1346 			case NFSERR_NAMETOL:
   1347 				error = ENAMETOOLONG;
   1348 				break;
   1349 
   1350 			case NFSERR_NOTEMPTY:
   1351 				error = ENOTEMPTY;
   1352 				break;
   1353 
   1354 			case NFSERR_DQUOT:
   1355 				error = EDQUOT;
   1356 				break;
   1357 
   1358 			case NFSERR_STALE:
   1359 				/*
   1360 				 * If the File Handle was stale, invalidate the
   1361 				 * lookup cache, just in case.
   1362 				 */
   1363 				error = ESTALE;
   1364 				cache_purge(NFSTOV(np));
   1365 				break;
   1366 
   1367 			case NFSERR_REMOTE:
   1368 				error = EREMOTE;
   1369 				break;
   1370 
   1371 			case NFSERR_WFLUSH:
   1372 			case NFSERR_BADHANDLE:
   1373 			case NFSERR_NOT_SYNC:
   1374 			case NFSERR_BAD_COOKIE:
   1375 				error = EINVAL;
   1376 				break;
   1377 
   1378 			case NFSERR_NOTSUPP:
   1379 				error = ENOTSUP;
   1380 				break;
   1381 
   1382 			case NFSERR_TOOSMALL:
   1383 			case NFSERR_SERVERFAULT:
   1384 			case NFSERR_BADTYPE:
   1385 				error = EINVAL;
   1386 				break;
   1387 
   1388 			case NFSERR_TRYLATER:
   1389 				if ((nmp->nm_flag & NFSMNT_NFSV3) == 0)
   1390 					break;
   1391 				m_freem(mrep);
   1392 				error = 0;
   1393 				waituntil = time_second + trylater_delay;
   1394 				while (time_second < waituntil) {
   1395 					kpause("nfstrylater", false, hz, NULL);
   1396 				}
   1397 				trylater_delay *= NFS_TRYLATERDELMUL;
   1398 				if (trylater_delay > NFS_TRYLATERDELMAX)
   1399 					trylater_delay = NFS_TRYLATERDELMAX;
   1400 				/*
   1401 				 * RFC1813:
   1402 				 * The client should wait and then try
   1403 				 * the request with a new RPC transaction ID.
   1404 				 */
   1405 				nfs_renewxid(rep);
   1406 				goto tryagain;
   1407 
   1408 			default:
   1409 #ifdef DIAGNOSTIC
   1410 				printf("Invalid rpc error code %d\n", error);
   1411 #endif
   1412 				error = EINVAL;
   1413 				break;
   1414 			}
   1415 
   1416 			if (nmp->nm_flag & NFSMNT_NFSV3) {
   1417 				*mrp = mrep;
   1418 				*mdp = md;
   1419 				*dposp = dpos;
   1420 				error |= NFSERR_RETERR;
   1421 			} else
   1422 				m_freem(mrep);
   1423 			goto nfsmout;
   1424 		}
   1425 
   1426 		/*
   1427 		 * note which credential worked to minimize number of retries.
   1428 		 */
   1429 		if (use_opencred)
   1430 			np->n_flag |= NUSEOPENCRED;
   1431 		else
   1432 			np->n_flag &= ~NUSEOPENCRED;
   1433 
   1434 		*mrp = mrep;
   1435 		*mdp = md;
   1436 		*dposp = dpos;
   1437 
   1438 		KASSERT(error == 0);
   1439 		goto nfsmout;
   1440 	}
   1441 	m_freem(mrep);
   1442 	error = EPROTONOSUPPORT;
   1443 nfsmout:
   1444 	KASSERT(kauth_cred_getrefcnt(acred) == 1);
   1445 	kauth_cred_free(acred);
   1446 	m_freem(rep->r_mreq);
   1447 	kmem_free(rep, sizeof(*rep));
   1448 	m_freem(mrest_backup);
   1449 	return (error);
   1450 }
   1451 #endif /* NFS */
   1452 
   1453 /*
   1454  * Generate the rpc reply header
   1455  * siz arg. is used to decide if adding a cluster is worthwhile
   1456  */
   1457 int
   1458 nfs_rephead(siz, nd, slp, err, cache, frev, mrq, mbp, bposp)
   1459 	int siz;
   1460 	struct nfsrv_descript *nd;
   1461 	struct nfssvc_sock *slp;
   1462 	int err;
   1463 	int cache;
   1464 	u_quad_t *frev;
   1465 	struct mbuf **mrq;
   1466 	struct mbuf **mbp;
   1467 	char **bposp;
   1468 {
   1469 	u_int32_t *tl;
   1470 	struct mbuf *mreq;
   1471 	char *bpos;
   1472 	struct mbuf *mb;
   1473 
   1474 	mreq = m_gethdr(M_WAIT, MT_DATA);
   1475 	MCLAIM(mreq, &nfs_mowner);
   1476 	mb = mreq;
   1477 	/*
   1478 	 * If this is a big reply, use a cluster else
   1479 	 * try and leave leading space for the lower level headers.
   1480 	 */
   1481 	siz += RPC_REPLYSIZ;
   1482 	if (siz >= max_datalen) {
   1483 		m_clget(mreq, M_WAIT);
   1484 	} else
   1485 		mreq->m_data += max_hdr;
   1486 	tl = mtod(mreq, u_int32_t *);
   1487 	mreq->m_len = 6 * NFSX_UNSIGNED;
   1488 	bpos = ((char *)tl) + mreq->m_len;
   1489 	*tl++ = txdr_unsigned(nd->nd_retxid);
   1490 	*tl++ = rpc_reply;
   1491 	if (err == ERPCMISMATCH || (err & NFSERR_AUTHERR)) {
   1492 		*tl++ = rpc_msgdenied;
   1493 		if (err & NFSERR_AUTHERR) {
   1494 			*tl++ = rpc_autherr;
   1495 			*tl = txdr_unsigned(err & ~NFSERR_AUTHERR);
   1496 			mreq->m_len -= NFSX_UNSIGNED;
   1497 			bpos -= NFSX_UNSIGNED;
   1498 		} else {
   1499 			*tl++ = rpc_mismatch;
   1500 			*tl++ = txdr_unsigned(RPC_VER2);
   1501 			*tl = txdr_unsigned(RPC_VER2);
   1502 		}
   1503 	} else {
   1504 		*tl++ = rpc_msgaccepted;
   1505 
   1506 		/*
   1507 		 * For Kerberos authentication, we must send the nickname
   1508 		 * verifier back, otherwise just RPCAUTH_NULL.
   1509 		 */
   1510 		if (nd->nd_flag & ND_KERBFULL) {
   1511 			struct nfsuid *nuidp;
   1512 			struct timeval ktvin, ktvout;
   1513 
   1514 			memset(&ktvout, 0, sizeof ktvout);	/* XXX gcc */
   1515 
   1516 			LIST_FOREACH(nuidp,
   1517 			    NUIDHASH(slp, kauth_cred_geteuid(nd->nd_cr)),
   1518 			    nu_hash) {
   1519 				if (kauth_cred_geteuid(nuidp->nu_cr) ==
   1520 				kauth_cred_geteuid(nd->nd_cr) &&
   1521 				    (!nd->nd_nam2 || netaddr_match(
   1522 				    NU_NETFAM(nuidp), &nuidp->nu_haddr,
   1523 				    nd->nd_nam2)))
   1524 					break;
   1525 			}
   1526 			if (nuidp) {
   1527 				ktvin.tv_sec =
   1528 				    txdr_unsigned(nuidp->nu_timestamp.tv_sec
   1529 					- 1);
   1530 				ktvin.tv_usec =
   1531 				    txdr_unsigned(nuidp->nu_timestamp.tv_usec);
   1532 
   1533 				/*
   1534 				 * Encrypt the timestamp in ecb mode using the
   1535 				 * session key.
   1536 				 */
   1537 #ifdef NFSKERB
   1538 				XXX
   1539 #endif
   1540 
   1541 				*tl++ = rpc_auth_kerb;
   1542 				*tl++ = txdr_unsigned(3 * NFSX_UNSIGNED);
   1543 				*tl = ktvout.tv_sec;
   1544 				nfsm_build(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
   1545 				*tl++ = ktvout.tv_usec;
   1546 				*tl++ = txdr_unsigned(
   1547 				    kauth_cred_geteuid(nuidp->nu_cr));
   1548 			} else {
   1549 				*tl++ = 0;
   1550 				*tl++ = 0;
   1551 			}
   1552 		} else {
   1553 			*tl++ = 0;
   1554 			*tl++ = 0;
   1555 		}
   1556 		switch (err) {
   1557 		case EPROGUNAVAIL:
   1558 			*tl = txdr_unsigned(RPC_PROGUNAVAIL);
   1559 			break;
   1560 		case EPROGMISMATCH:
   1561 			*tl = txdr_unsigned(RPC_PROGMISMATCH);
   1562 			nfsm_build(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
   1563 			*tl++ = txdr_unsigned(2);
   1564 			*tl = txdr_unsigned(3);
   1565 			break;
   1566 		case EPROCUNAVAIL:
   1567 			*tl = txdr_unsigned(RPC_PROCUNAVAIL);
   1568 			break;
   1569 		case EBADRPC:
   1570 			*tl = txdr_unsigned(RPC_GARBAGE);
   1571 			break;
   1572 		default:
   1573 			*tl = 0;
   1574 			if (err != NFSERR_RETVOID) {
   1575 				nfsm_build(tl, u_int32_t *, NFSX_UNSIGNED);
   1576 				if (err)
   1577 				    *tl = txdr_unsigned(nfsrv_errmap(nd, err));
   1578 				else
   1579 				    *tl = 0;
   1580 			}
   1581 			break;
   1582 		};
   1583 	}
   1584 
   1585 	if (mrq != NULL)
   1586 		*mrq = mreq;
   1587 	*mbp = mb;
   1588 	*bposp = bpos;
   1589 	if (err != 0 && err != NFSERR_RETVOID)
   1590 		nfsstats.srvrpc_errs++;
   1591 	return (0);
   1592 }
   1593 
   1594 static void
   1595 nfs_timer_schedule(void)
   1596 {
   1597 
   1598 	callout_schedule(&nfs_timer_ch, nfs_ticks);
   1599 }
   1600 
   1601 void
   1602 nfs_timer_start(void)
   1603 {
   1604 
   1605 	if (callout_pending(&nfs_timer_ch))
   1606 		return;
   1607 
   1608 	nfs_timer_start_ev.ev_count++;
   1609 	nfs_timer_schedule();
   1610 }
   1611 
   1612 void
   1613 nfs_timer_init(void)
   1614 {
   1615 
   1616 	callout_init(&nfs_timer_ch, 0);
   1617 	callout_setfunc(&nfs_timer_ch, nfs_timer, NULL);
   1618 	evcnt_attach_dynamic(&nfs_timer_ev, EVCNT_TYPE_MISC, NULL,
   1619 	    "nfs", "timer");
   1620 	evcnt_attach_dynamic(&nfs_timer_start_ev, EVCNT_TYPE_MISC, NULL,
   1621 	    "nfs", "timer start");
   1622 	evcnt_attach_dynamic(&nfs_timer_stop_ev, EVCNT_TYPE_MISC, NULL,
   1623 	    "nfs", "timer stop");
   1624 }
   1625 
   1626 /*
   1627  * Nfs timer routine
   1628  * Scan the nfsreq list and retranmit any requests that have timed out
   1629  * To avoid retransmission attempts on STREAM sockets (in the future) make
   1630  * sure to set the r_retry field to 0 (implies nm_retry == 0).
   1631  * A non-NULL argument means 'initialize'.
   1632  */
   1633 void
   1634 nfs_timer(void *arg)
   1635 {
   1636 	struct nfsreq *rep;
   1637 	struct mbuf *m;
   1638 	struct socket *so;
   1639 	struct nfsmount *nmp;
   1640 	int timeo;
   1641 	int error;
   1642 	bool more = false;
   1643 #ifdef NFSSERVER
   1644 	struct timeval tv;
   1645 	struct nfssvc_sock *slp;
   1646 	u_quad_t cur_usec;
   1647 #endif
   1648 
   1649 	nfs_timer_ev.ev_count++;
   1650 
   1651 	mutex_enter(&nfs_reqq_lock);
   1652 	TAILQ_FOREACH(rep, &nfs_reqq, r_chain) {
   1653 		more = true;
   1654 		nmp = rep->r_nmp;
   1655 		if (rep->r_mrep || (rep->r_flags & R_SOFTTERM))
   1656 			continue;
   1657 		if (nfs_sigintr(nmp, rep, rep->r_lwp)) {
   1658 			rep->r_flags |= R_SOFTTERM;
   1659 			continue;
   1660 		}
   1661 		if (rep->r_rtt >= 0) {
   1662 			rep->r_rtt++;
   1663 			if (nmp->nm_flag & NFSMNT_DUMBTIMR)
   1664 				timeo = nmp->nm_timeo;
   1665 			else
   1666 				timeo = NFS_RTO(nmp, proct[rep->r_procnum]);
   1667 			if (nmp->nm_timeouts > 0)
   1668 				timeo *= nfs_backoff[nmp->nm_timeouts - 1];
   1669 			if (rep->r_rtt <= timeo)
   1670 				continue;
   1671 			if (nmp->nm_timeouts <
   1672 			    (sizeof(nfs_backoff) / sizeof(nfs_backoff[0])))
   1673 				nmp->nm_timeouts++;
   1674 		}
   1675 		/*
   1676 		 * Check for server not responding
   1677 		 */
   1678 		if ((rep->r_flags & R_TPRINTFMSG) == 0 &&
   1679 		     rep->r_rexmit > nmp->nm_deadthresh) {
   1680 			nfs_msg(rep->r_lwp,
   1681 			    nmp->nm_mountp->mnt_stat.f_mntfromname,
   1682 			    "not responding");
   1683 			rep->r_flags |= R_TPRINTFMSG;
   1684 		}
   1685 		if (rep->r_rexmit >= rep->r_retry) {	/* too many */
   1686 			nfsstats.rpctimeouts++;
   1687 			rep->r_flags |= R_SOFTTERM;
   1688 			continue;
   1689 		}
   1690 		if (nmp->nm_sotype != SOCK_DGRAM) {
   1691 			if (++rep->r_rexmit > NFS_MAXREXMIT)
   1692 				rep->r_rexmit = NFS_MAXREXMIT;
   1693 			continue;
   1694 		}
   1695 		if ((so = nmp->nm_so) == NULL)
   1696 			continue;
   1697 
   1698 		/*
   1699 		 * If there is enough space and the window allows..
   1700 		 *	Resend it
   1701 		 * Set r_rtt to -1 in case we fail to send it now.
   1702 		 */
   1703 		rep->r_rtt = -1;
   1704 		if (sbspace(&so->so_snd) >= rep->r_mreq->m_pkthdr.len &&
   1705 		   ((nmp->nm_flag & NFSMNT_DUMBTIMR) ||
   1706 		    (rep->r_flags & R_SENT) ||
   1707 		    nmp->nm_sent < nmp->nm_cwnd) &&
   1708 		   (m = m_copym(rep->r_mreq, 0, M_COPYALL, M_DONTWAIT))){
   1709 		        if (so->so_state & SS_ISCONNECTED)
   1710 			    error = (*so->so_proto->pr_usrreq)(so, PRU_SEND, m,
   1711 			    (struct mbuf *)0, (struct mbuf *)0, (struct lwp *)0);
   1712 			else
   1713 			    error = (*so->so_proto->pr_usrreq)(so, PRU_SEND, m,
   1714 			    nmp->nm_nam, (struct mbuf *)0, (struct lwp *)0);
   1715 			if (error) {
   1716 				if (NFSIGNORE_SOERROR(nmp->nm_soflags, error)) {
   1717 #ifdef DEBUG
   1718 					printf("nfs_timer: ignoring error %d\n",
   1719 						error);
   1720 #endif
   1721 					so->so_error = 0;
   1722 				}
   1723 			} else {
   1724 				/*
   1725 				 * Iff first send, start timing
   1726 				 * else turn timing off, backoff timer
   1727 				 * and divide congestion window by 2.
   1728 				 */
   1729 				if (rep->r_flags & R_SENT) {
   1730 					rep->r_flags &= ~R_TIMING;
   1731 					if (++rep->r_rexmit > NFS_MAXREXMIT)
   1732 						rep->r_rexmit = NFS_MAXREXMIT;
   1733 					nmp->nm_cwnd >>= 1;
   1734 					if (nmp->nm_cwnd < NFS_CWNDSCALE)
   1735 						nmp->nm_cwnd = NFS_CWNDSCALE;
   1736 					nfsstats.rpcretries++;
   1737 				} else {
   1738 					rep->r_flags |= R_SENT;
   1739 					nmp->nm_sent += NFS_CWNDSCALE;
   1740 				}
   1741 				rep->r_rtt = 0;
   1742 			}
   1743 		}
   1744 	}
   1745 	mutex_exit(&nfs_reqq_lock);
   1746 
   1747 #ifdef NFSSERVER
   1748 	/*
   1749 	 * Scan the write gathering queues for writes that need to be
   1750 	 * completed now.
   1751 	 */
   1752 	getmicrotime(&tv);
   1753 	cur_usec = (u_quad_t)tv.tv_sec * 1000000 + (u_quad_t)tv.tv_usec;
   1754 	mutex_enter(&nfsd_lock);
   1755 	TAILQ_FOREACH(slp, &nfssvc_sockhead, ns_chain) {
   1756 		struct nfsrv_descript *nd;
   1757 
   1758 		nd = LIST_FIRST(&slp->ns_tq);
   1759 		if (nd != NULL) {
   1760 			if (nd->nd_time <= cur_usec) {
   1761 				nfsrv_wakenfsd_locked(slp);
   1762 			}
   1763 			more = true;
   1764 		}
   1765 	}
   1766 	mutex_exit(&nfsd_lock);
   1767 #endif /* NFSSERVER */
   1768 	if (more) {
   1769 		nfs_timer_schedule();
   1770 	} else {
   1771 		nfs_timer_stop_ev.ev_count++;
   1772 	}
   1773 }
   1774 
   1775 /*
   1776  * Test for a termination condition pending on the process.
   1777  * This is used for NFSMNT_INT mounts.
   1778  */
   1779 int
   1780 nfs_sigintr(nmp, rep, l)
   1781 	struct nfsmount *nmp;
   1782 	struct nfsreq *rep;
   1783 	struct lwp *l;
   1784 {
   1785 	sigset_t ss;
   1786 
   1787 	if (rep && (rep->r_flags & R_SOFTTERM))
   1788 		return (EINTR);
   1789 	if (!(nmp->nm_flag & NFSMNT_INT))
   1790 		return (0);
   1791 	if (l) {
   1792 		sigpending1(l, &ss);
   1793 #if 0
   1794 		sigminusset(&l->l_proc->p_sigctx.ps_sigignore, &ss);
   1795 #endif
   1796 		if (sigismember(&ss, SIGINT) || sigismember(&ss, SIGTERM) ||
   1797 		    sigismember(&ss, SIGKILL) || sigismember(&ss, SIGHUP) ||
   1798 		    sigismember(&ss, SIGQUIT))
   1799 			return (EINTR);
   1800 	}
   1801 	return (0);
   1802 }
   1803 
   1804 /*
   1805  * Lock a socket against others.
   1806  * Necessary for STREAM sockets to ensure you get an entire rpc request/reply
   1807  * and also to avoid race conditions between the processes with nfs requests
   1808  * in progress when a reconnect is necessary.
   1809  */
   1810 static int
   1811 nfs_sndlock(struct nfsmount *nmp, struct nfsreq *rep)
   1812 {
   1813 	struct lwp *l;
   1814 	int timeo = 0;
   1815 	bool catch = false;
   1816 	int error = 0;
   1817 
   1818 	KASSERT(nmp == rep->r_nmp);
   1819 
   1820 	if (rep) {
   1821 		l = rep->r_lwp;
   1822 		if (rep->r_nmp->nm_flag & NFSMNT_INT)
   1823 			catch = true;
   1824 	} else
   1825 		l = NULL;
   1826 	mutex_enter(&nmp->nm_lock);
   1827 	while ((nmp->nm_iflag & NFSMNT_SNDLOCK) != 0) {
   1828 		if (rep && nfs_sigintr(rep->r_nmp, rep, l)) {
   1829 			error = EINTR;
   1830 			goto quit;
   1831 		}
   1832 		if (catch) {
   1833 			cv_timedwait_sig(&nmp->nm_sndcv, &nmp->nm_lock, timeo);
   1834 		} else {
   1835 			cv_timedwait(&nmp->nm_sndcv, &nmp->nm_lock, timeo);
   1836 		}
   1837 		if (catch) {
   1838 			catch = false;
   1839 			timeo = 2 * hz;
   1840 		}
   1841 	}
   1842 	nmp->nm_iflag |= NFSMNT_SNDLOCK;
   1843 quit:
   1844 	mutex_exit(&nmp->nm_lock);
   1845 	return error;
   1846 }
   1847 
   1848 /*
   1849  * Unlock the stream socket for others.
   1850  */
   1851 static void
   1852 nfs_sndunlock(struct nfsmount *nmp)
   1853 {
   1854 
   1855 	mutex_enter(&nmp->nm_lock);
   1856 	if ((nmp->nm_iflag & NFSMNT_SNDLOCK) == 0)
   1857 		panic("nfs sndunlock");
   1858 	nmp->nm_iflag &= ~NFSMNT_SNDLOCK;
   1859 	cv_signal(&nmp->nm_sndcv);
   1860 	mutex_exit(&nmp->nm_lock);
   1861 }
   1862 
   1863 static int
   1864 nfs_rcvlock(struct nfsmount *nmp, struct nfsreq *rep)
   1865 {
   1866 	int *flagp = &nmp->nm_iflag;
   1867 	int slptimeo = 0;
   1868 	bool catch;
   1869 	int error = 0;
   1870 
   1871 	KASSERT(nmp == rep->r_nmp);
   1872 
   1873 	catch = (nmp->nm_flag & NFSMNT_INT) != 0;
   1874 	mutex_enter(&nmp->nm_lock);
   1875 	while (/* CONSTCOND */ true) {
   1876 		if (*flagp & NFSMNT_DISMNT) {
   1877 			cv_signal(&nmp->nm_disconcv);
   1878 			error = EIO;
   1879 			break;
   1880 		}
   1881 		/* If our reply was received while we were sleeping,
   1882 		 * then just return without taking the lock to avoid a
   1883 		 * situation where a single iod could 'capture' the
   1884 		 * receive lock.
   1885 		 */
   1886 		if (rep->r_mrep != NULL) {
   1887 			error = EALREADY;
   1888 			break;
   1889 		}
   1890 		if (nfs_sigintr(rep->r_nmp, rep, rep->r_lwp)) {
   1891 			error = EINTR;
   1892 			break;
   1893 		}
   1894 		if ((*flagp & NFSMNT_RCVLOCK) == 0) {
   1895 			*flagp |= NFSMNT_RCVLOCK;
   1896 			break;
   1897 		}
   1898 		if (catch) {
   1899 			cv_timedwait_sig(&nmp->nm_rcvcv, &nmp->nm_lock,
   1900 			    slptimeo);
   1901 		} else {
   1902 			cv_timedwait(&nmp->nm_rcvcv, &nmp->nm_lock,
   1903 			    slptimeo);
   1904 		}
   1905 		if (catch) {
   1906 			catch = false;
   1907 			slptimeo = 2 * hz;
   1908 		}
   1909 	}
   1910 	mutex_exit(&nmp->nm_lock);
   1911 	return error;
   1912 }
   1913 
   1914 /*
   1915  * Unlock the stream socket for others.
   1916  */
   1917 static void
   1918 nfs_rcvunlock(struct nfsmount *nmp)
   1919 {
   1920 
   1921 	mutex_enter(&nmp->nm_lock);
   1922 	if ((nmp->nm_iflag & NFSMNT_RCVLOCK) == 0)
   1923 		panic("nfs rcvunlock");
   1924 	nmp->nm_iflag &= ~NFSMNT_RCVLOCK;
   1925 	cv_broadcast(&nmp->nm_rcvcv);
   1926 	mutex_exit(&nmp->nm_lock);
   1927 }
   1928 
   1929 /*
   1930  * Parse an RPC request
   1931  * - verify it
   1932  * - allocate and fill in the cred.
   1933  */
   1934 int
   1935 nfs_getreq(nd, nfsd, has_header)
   1936 	struct nfsrv_descript *nd;
   1937 	struct nfsd *nfsd;
   1938 	int has_header;
   1939 {
   1940 	int len, i;
   1941 	u_int32_t *tl;
   1942 	int32_t t1;
   1943 	struct uio uio;
   1944 	struct iovec iov;
   1945 	char *dpos, *cp2, *cp;
   1946 	u_int32_t nfsvers, auth_type;
   1947 	uid_t nickuid;
   1948 	int error = 0, ticklen;
   1949 	struct mbuf *mrep, *md;
   1950 	struct nfsuid *nuidp;
   1951 	struct timeval tvin, tvout;
   1952 
   1953 	memset(&tvout, 0, sizeof tvout);	/* XXX gcc */
   1954 
   1955 	KASSERT(nd->nd_cr == NULL);
   1956 	mrep = nd->nd_mrep;
   1957 	md = nd->nd_md;
   1958 	dpos = nd->nd_dpos;
   1959 	if (has_header) {
   1960 		nfsm_dissect(tl, u_int32_t *, 10 * NFSX_UNSIGNED);
   1961 		nd->nd_retxid = fxdr_unsigned(u_int32_t, *tl++);
   1962 		if (*tl++ != rpc_call) {
   1963 			m_freem(mrep);
   1964 			return (EBADRPC);
   1965 		}
   1966 	} else
   1967 		nfsm_dissect(tl, u_int32_t *, 8 * NFSX_UNSIGNED);
   1968 	nd->nd_repstat = 0;
   1969 	nd->nd_flag = 0;
   1970 	if (*tl++ != rpc_vers) {
   1971 		nd->nd_repstat = ERPCMISMATCH;
   1972 		nd->nd_procnum = NFSPROC_NOOP;
   1973 		return (0);
   1974 	}
   1975 	if (*tl != nfs_prog) {
   1976 		nd->nd_repstat = EPROGUNAVAIL;
   1977 		nd->nd_procnum = NFSPROC_NOOP;
   1978 		return (0);
   1979 	}
   1980 	tl++;
   1981 	nfsvers = fxdr_unsigned(u_int32_t, *tl++);
   1982 	if (nfsvers < NFS_VER2 || nfsvers > NFS_VER3) {
   1983 		nd->nd_repstat = EPROGMISMATCH;
   1984 		nd->nd_procnum = NFSPROC_NOOP;
   1985 		return (0);
   1986 	}
   1987 	if (nfsvers == NFS_VER3)
   1988 		nd->nd_flag = ND_NFSV3;
   1989 	nd->nd_procnum = fxdr_unsigned(u_int32_t, *tl++);
   1990 	if (nd->nd_procnum == NFSPROC_NULL)
   1991 		return (0);
   1992 	if (nd->nd_procnum > NFSPROC_COMMIT ||
   1993 	    (!nd->nd_flag && nd->nd_procnum > NFSV2PROC_STATFS)) {
   1994 		nd->nd_repstat = EPROCUNAVAIL;
   1995 		nd->nd_procnum = NFSPROC_NOOP;
   1996 		return (0);
   1997 	}
   1998 	if ((nd->nd_flag & ND_NFSV3) == 0)
   1999 		nd->nd_procnum = nfsv3_procid[nd->nd_procnum];
   2000 	auth_type = *tl++;
   2001 	len = fxdr_unsigned(int, *tl++);
   2002 	if (len < 0 || len > RPCAUTH_MAXSIZ) {
   2003 		m_freem(mrep);
   2004 		return (EBADRPC);
   2005 	}
   2006 
   2007 	nd->nd_flag &= ~ND_KERBAUTH;
   2008 	/*
   2009 	 * Handle auth_unix or auth_kerb.
   2010 	 */
   2011 	if (auth_type == rpc_auth_unix) {
   2012 		uid_t uid;
   2013 		gid_t gid;
   2014 
   2015 		nd->nd_cr = kauth_cred_alloc();
   2016 		len = fxdr_unsigned(int, *++tl);
   2017 		if (len < 0 || len > NFS_MAXNAMLEN) {
   2018 			m_freem(mrep);
   2019 			error = EBADRPC;
   2020 			goto errout;
   2021 		}
   2022 		nfsm_adv(nfsm_rndup(len));
   2023 		nfsm_dissect(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
   2024 
   2025 		uid = fxdr_unsigned(uid_t, *tl++);
   2026 		gid = fxdr_unsigned(gid_t, *tl++);
   2027 		kauth_cred_setuid(nd->nd_cr, uid);
   2028 		kauth_cred_seteuid(nd->nd_cr, uid);
   2029 		kauth_cred_setsvuid(nd->nd_cr, uid);
   2030 		kauth_cred_setgid(nd->nd_cr, gid);
   2031 		kauth_cred_setegid(nd->nd_cr, gid);
   2032 		kauth_cred_setsvgid(nd->nd_cr, gid);
   2033 
   2034 		len = fxdr_unsigned(int, *tl);
   2035 		if (len < 0 || len > RPCAUTH_UNIXGIDS) {
   2036 			m_freem(mrep);
   2037 			error = EBADRPC;
   2038 			goto errout;
   2039 		}
   2040 		nfsm_dissect(tl, u_int32_t *, (len + 2) * NFSX_UNSIGNED);
   2041 
   2042 		if (len > 0) {
   2043 			size_t grbuf_size = min(len, NGROUPS) * sizeof(gid_t);
   2044 			gid_t *grbuf = kmem_alloc(grbuf_size, KM_SLEEP);
   2045 
   2046 			for (i = 0; i < len; i++) {
   2047 				if (i < NGROUPS) /* XXX elad */
   2048 					grbuf[i] = fxdr_unsigned(gid_t, *tl++);
   2049 				else
   2050 					tl++;
   2051 			}
   2052 			kauth_cred_setgroups(nd->nd_cr, grbuf,
   2053 			    min(len, NGROUPS), -1, UIO_SYSSPACE);
   2054 			kmem_free(grbuf, grbuf_size);
   2055 		}
   2056 
   2057 		len = fxdr_unsigned(int, *++tl);
   2058 		if (len < 0 || len > RPCAUTH_MAXSIZ) {
   2059 			m_freem(mrep);
   2060 			error = EBADRPC;
   2061 			goto errout;
   2062 		}
   2063 		if (len > 0)
   2064 			nfsm_adv(nfsm_rndup(len));
   2065 	} else if (auth_type == rpc_auth_kerb) {
   2066 		switch (fxdr_unsigned(int, *tl++)) {
   2067 		case RPCAKN_FULLNAME:
   2068 			ticklen = fxdr_unsigned(int, *tl);
   2069 			*((u_int32_t *)nfsd->nfsd_authstr) = *tl;
   2070 			uio.uio_resid = nfsm_rndup(ticklen) + NFSX_UNSIGNED;
   2071 			nfsd->nfsd_authlen = uio.uio_resid + NFSX_UNSIGNED;
   2072 			if (uio.uio_resid > (len - 2 * NFSX_UNSIGNED)) {
   2073 				m_freem(mrep);
   2074 				error = EBADRPC;
   2075 				goto errout;
   2076 			}
   2077 			uio.uio_offset = 0;
   2078 			uio.uio_iov = &iov;
   2079 			uio.uio_iovcnt = 1;
   2080 			UIO_SETUP_SYSSPACE(&uio);
   2081 			iov.iov_base = (void *)&nfsd->nfsd_authstr[4];
   2082 			iov.iov_len = RPCAUTH_MAXSIZ - 4;
   2083 			nfsm_mtouio(&uio, uio.uio_resid);
   2084 			nfsm_dissect(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
   2085 			if (*tl++ != rpc_auth_kerb ||
   2086 				fxdr_unsigned(int, *tl) != 4 * NFSX_UNSIGNED) {
   2087 				printf("Bad kerb verifier\n");
   2088 				nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
   2089 				nd->nd_procnum = NFSPROC_NOOP;
   2090 				return (0);
   2091 			}
   2092 			nfsm_dissect(cp, void *, 4 * NFSX_UNSIGNED);
   2093 			tl = (u_int32_t *)cp;
   2094 			if (fxdr_unsigned(int, *tl) != RPCAKN_FULLNAME) {
   2095 				printf("Not fullname kerb verifier\n");
   2096 				nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
   2097 				nd->nd_procnum = NFSPROC_NOOP;
   2098 				return (0);
   2099 			}
   2100 			cp += NFSX_UNSIGNED;
   2101 			memcpy(nfsd->nfsd_verfstr, cp, 3 * NFSX_UNSIGNED);
   2102 			nfsd->nfsd_verflen = 3 * NFSX_UNSIGNED;
   2103 			nd->nd_flag |= ND_KERBFULL;
   2104 			nfsd->nfsd_flag |= NFSD_NEEDAUTH;
   2105 			break;
   2106 		case RPCAKN_NICKNAME:
   2107 			if (len != 2 * NFSX_UNSIGNED) {
   2108 				printf("Kerb nickname short\n");
   2109 				nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADCRED);
   2110 				nd->nd_procnum = NFSPROC_NOOP;
   2111 				return (0);
   2112 			}
   2113 			nickuid = fxdr_unsigned(uid_t, *tl);
   2114 			nfsm_dissect(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
   2115 			if (*tl++ != rpc_auth_kerb ||
   2116 				fxdr_unsigned(int, *tl) != 3 * NFSX_UNSIGNED) {
   2117 				printf("Kerb nick verifier bad\n");
   2118 				nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
   2119 				nd->nd_procnum = NFSPROC_NOOP;
   2120 				return (0);
   2121 			}
   2122 			nfsm_dissect(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
   2123 			tvin.tv_sec = *tl++;
   2124 			tvin.tv_usec = *tl;
   2125 
   2126 			LIST_FOREACH(nuidp, NUIDHASH(nfsd->nfsd_slp, nickuid),
   2127 			    nu_hash) {
   2128 				if (kauth_cred_geteuid(nuidp->nu_cr) == nickuid &&
   2129 				    (!nd->nd_nam2 ||
   2130 				     netaddr_match(NU_NETFAM(nuidp),
   2131 				      &nuidp->nu_haddr, nd->nd_nam2)))
   2132 					break;
   2133 			}
   2134 			if (!nuidp) {
   2135 				nd->nd_repstat =
   2136 					(NFSERR_AUTHERR|AUTH_REJECTCRED);
   2137 				nd->nd_procnum = NFSPROC_NOOP;
   2138 				return (0);
   2139 			}
   2140 
   2141 			/*
   2142 			 * Now, decrypt the timestamp using the session key
   2143 			 * and validate it.
   2144 			 */
   2145 #ifdef NFSKERB
   2146 			XXX
   2147 #endif
   2148 
   2149 			tvout.tv_sec = fxdr_unsigned(long, tvout.tv_sec);
   2150 			tvout.tv_usec = fxdr_unsigned(long, tvout.tv_usec);
   2151 			if (nuidp->nu_expire < time_second ||
   2152 			    nuidp->nu_timestamp.tv_sec > tvout.tv_sec ||
   2153 			    (nuidp->nu_timestamp.tv_sec == tvout.tv_sec &&
   2154 			     nuidp->nu_timestamp.tv_usec > tvout.tv_usec)) {
   2155 				nuidp->nu_expire = 0;
   2156 				nd->nd_repstat =
   2157 				    (NFSERR_AUTHERR|AUTH_REJECTVERF);
   2158 				nd->nd_procnum = NFSPROC_NOOP;
   2159 				return (0);
   2160 			}
   2161 			kauth_cred_hold(nuidp->nu_cr);
   2162 			nd->nd_cr = nuidp->nu_cr;
   2163 			nd->nd_flag |= ND_KERBNICK;
   2164 		}
   2165 	} else {
   2166 		nd->nd_repstat = (NFSERR_AUTHERR | AUTH_REJECTCRED);
   2167 		nd->nd_procnum = NFSPROC_NOOP;
   2168 		return (0);
   2169 	}
   2170 
   2171 	nd->nd_md = md;
   2172 	nd->nd_dpos = dpos;
   2173 	KASSERT((nd->nd_cr == NULL && (nfsd->nfsd_flag & NFSD_NEEDAUTH) != 0)
   2174 	     || (nd->nd_cr != NULL && (nfsd->nfsd_flag & NFSD_NEEDAUTH) == 0));
   2175 	return (0);
   2176 nfsmout:
   2177 errout:
   2178 	KASSERT(error != 0);
   2179 	if (nd->nd_cr != NULL) {
   2180 		kauth_cred_free(nd->nd_cr);
   2181 		nd->nd_cr = NULL;
   2182 	}
   2183 	return (error);
   2184 }
   2185 
   2186 int
   2187 nfs_msg(l, server, msg)
   2188 	struct lwp *l;
   2189 	const char *server, *msg;
   2190 {
   2191 	tpr_t tpr;
   2192 
   2193 	if (l)
   2194 		tpr = tprintf_open(l->l_proc);
   2195 	else
   2196 		tpr = NULL;
   2197 	tprintf(tpr, "nfs server %s: %s\n", server, msg);
   2198 	tprintf_close(tpr);
   2199 	return (0);
   2200 }
   2201 
   2202 #ifdef NFSSERVER
   2203 int (*nfsrv3_procs[NFS_NPROCS]) __P((struct nfsrv_descript *,
   2204 				    struct nfssvc_sock *, struct lwp *,
   2205 				    struct mbuf **)) = {
   2206 	nfsrv_null,
   2207 	nfsrv_getattr,
   2208 	nfsrv_setattr,
   2209 	nfsrv_lookup,
   2210 	nfsrv3_access,
   2211 	nfsrv_readlink,
   2212 	nfsrv_read,
   2213 	nfsrv_write,
   2214 	nfsrv_create,
   2215 	nfsrv_mkdir,
   2216 	nfsrv_symlink,
   2217 	nfsrv_mknod,
   2218 	nfsrv_remove,
   2219 	nfsrv_rmdir,
   2220 	nfsrv_rename,
   2221 	nfsrv_link,
   2222 	nfsrv_readdir,
   2223 	nfsrv_readdirplus,
   2224 	nfsrv_statfs,
   2225 	nfsrv_fsinfo,
   2226 	nfsrv_pathconf,
   2227 	nfsrv_commit,
   2228 	nfsrv_noop
   2229 };
   2230 
   2231 /*
   2232  * Socket upcall routine for the nfsd sockets.
   2233  * The void *arg is a pointer to the "struct nfssvc_sock".
   2234  */
   2235 void
   2236 nfsrv_soupcall(struct socket *so, void *arg, int waitflag)
   2237 {
   2238 	struct nfssvc_sock *slp = (struct nfssvc_sock *)arg;
   2239 
   2240 	nfsdsock_setbits(slp, SLP_A_NEEDQ);
   2241 	nfsrv_wakenfsd(slp);
   2242 }
   2243 
   2244 void
   2245 nfsrv_rcv(struct nfssvc_sock *slp)
   2246 {
   2247 	struct socket *so;
   2248 	struct mbuf *m;
   2249 	struct mbuf *mp, *nam;
   2250 	struct uio auio;
   2251 	int flags;
   2252 	int error;
   2253 	int setflags = 0;
   2254 
   2255 	error = nfsdsock_lock(slp, true);
   2256 	if (error) {
   2257 		setflags |= SLP_A_NEEDQ;
   2258 		goto dorecs_unlocked;
   2259 	}
   2260 
   2261 	nfsdsock_clearbits(slp, SLP_A_NEEDQ);
   2262 
   2263 	so = slp->ns_so;
   2264 	if (so->so_type == SOCK_STREAM) {
   2265 		/*
   2266 		 * Do soreceive().
   2267 		 */
   2268 		auio.uio_resid = 1000000000;
   2269 		/* not need to setup uio_vmspace */
   2270 		flags = MSG_DONTWAIT;
   2271 		KERNEL_LOCK(1, curlwp);
   2272 		error = (*so->so_receive)(so, &nam, &auio, &mp, NULL, &flags);
   2273 		KERNEL_UNLOCK_ONE(curlwp);
   2274 		if (error || mp == NULL) {
   2275 			if (error == EWOULDBLOCK)
   2276 				setflags |= SLP_A_NEEDQ;
   2277 			else
   2278 				setflags |= SLP_A_DISCONN;
   2279 			goto dorecs;
   2280 		}
   2281 		m = mp;
   2282 		m_claimm(m, &nfs_mowner);
   2283 		if (slp->ns_rawend) {
   2284 			slp->ns_rawend->m_next = m;
   2285 			slp->ns_cc += 1000000000 - auio.uio_resid;
   2286 		} else {
   2287 			slp->ns_raw = m;
   2288 			slp->ns_cc = 1000000000 - auio.uio_resid;
   2289 		}
   2290 		while (m->m_next)
   2291 			m = m->m_next;
   2292 		slp->ns_rawend = m;
   2293 
   2294 		/*
   2295 		 * Now try and parse record(s) out of the raw stream data.
   2296 		 */
   2297 		error = nfsrv_getstream(slp, M_WAIT);
   2298 		if (error) {
   2299 			if (error == EPERM)
   2300 				setflags |= SLP_A_DISCONN;
   2301 			else
   2302 				setflags |= SLP_A_NEEDQ;
   2303 		}
   2304 	} else {
   2305 		do {
   2306 			auio.uio_resid = 1000000000;
   2307 			/* not need to setup uio_vmspace */
   2308 			flags = MSG_DONTWAIT;
   2309 			KERNEL_LOCK(1, curlwp);
   2310 			error = (*so->so_receive)(so, &nam, &auio, &mp, NULL,
   2311 			    &flags);
   2312 			KERNEL_UNLOCK_ONE(curlwp);
   2313 			if (mp) {
   2314 				if (nam) {
   2315 					m = nam;
   2316 					m->m_next = mp;
   2317 				} else
   2318 					m = mp;
   2319 				m_claimm(m, &nfs_mowner);
   2320 				if (slp->ns_recend)
   2321 					slp->ns_recend->m_nextpkt = m;
   2322 				else
   2323 					slp->ns_rec = m;
   2324 				slp->ns_recend = m;
   2325 				m->m_nextpkt = (struct mbuf *)0;
   2326 			}
   2327 			if (error) {
   2328 				if ((so->so_proto->pr_flags & PR_CONNREQUIRED)
   2329 				    && error != EWOULDBLOCK) {
   2330 					setflags |= SLP_A_DISCONN;
   2331 					goto dorecs;
   2332 				}
   2333 			}
   2334 		} while (mp);
   2335 	}
   2336 dorecs:
   2337 	nfsdsock_unlock(slp);
   2338 
   2339 dorecs_unlocked:
   2340 	if (setflags) {
   2341 		nfsdsock_setbits(slp, setflags);
   2342 	}
   2343 }
   2344 
   2345 int
   2346 nfsdsock_lock(struct nfssvc_sock *slp, bool waitok)
   2347 {
   2348 
   2349 	mutex_enter(&slp->ns_lock);
   2350 	while ((~slp->ns_flags & (SLP_BUSY|SLP_VALID)) == 0) {
   2351 		if (!waitok) {
   2352 			mutex_exit(&slp->ns_lock);
   2353 			return EWOULDBLOCK;
   2354 		}
   2355 		cv_wait(&slp->ns_cv, &slp->ns_lock);
   2356 	}
   2357 	if ((slp->ns_flags & SLP_VALID) == 0) {
   2358 		mutex_exit(&slp->ns_lock);
   2359 		return EINVAL;
   2360 	}
   2361 	KASSERT((slp->ns_flags & SLP_BUSY) == 0);
   2362 	slp->ns_flags |= SLP_BUSY;
   2363 	mutex_exit(&slp->ns_lock);
   2364 
   2365 	return 0;
   2366 }
   2367 
   2368 void
   2369 nfsdsock_unlock(struct nfssvc_sock *slp)
   2370 {
   2371 
   2372 	mutex_enter(&slp->ns_lock);
   2373 	KASSERT((slp->ns_flags & SLP_BUSY) != 0);
   2374 	cv_broadcast(&slp->ns_cv);
   2375 	slp->ns_flags &= ~SLP_BUSY;
   2376 	mutex_exit(&slp->ns_lock);
   2377 }
   2378 
   2379 int
   2380 nfsdsock_drain(struct nfssvc_sock *slp)
   2381 {
   2382 	int error = 0;
   2383 
   2384 	mutex_enter(&slp->ns_lock);
   2385 	if ((slp->ns_flags & SLP_VALID) == 0) {
   2386 		error = EINVAL;
   2387 		goto done;
   2388 	}
   2389 	slp->ns_flags &= ~SLP_VALID;
   2390 	while ((slp->ns_flags & SLP_BUSY) != 0) {
   2391 		cv_wait(&slp->ns_cv, &slp->ns_lock);
   2392 	}
   2393 done:
   2394 	mutex_exit(&slp->ns_lock);
   2395 
   2396 	return error;
   2397 }
   2398 
   2399 /*
   2400  * Try and extract an RPC request from the mbuf data list received on a
   2401  * stream socket. The "waitflag" argument indicates whether or not it
   2402  * can sleep.
   2403  */
   2404 int
   2405 nfsrv_getstream(slp, waitflag)
   2406 	struct nfssvc_sock *slp;
   2407 	int waitflag;
   2408 {
   2409 	struct mbuf *m, **mpp;
   2410 	struct mbuf *recm;
   2411 	u_int32_t recmark;
   2412 	int error = 0;
   2413 
   2414 	KASSERT((slp->ns_flags & SLP_BUSY) != 0);
   2415 	for (;;) {
   2416 		if (slp->ns_reclen == 0) {
   2417 			if (slp->ns_cc < NFSX_UNSIGNED) {
   2418 				break;
   2419 			}
   2420 			m = slp->ns_raw;
   2421 			m_copydata(m, 0, NFSX_UNSIGNED, (void *)&recmark);
   2422 			m_adj(m, NFSX_UNSIGNED);
   2423 			slp->ns_cc -= NFSX_UNSIGNED;
   2424 			recmark = ntohl(recmark);
   2425 			slp->ns_reclen = recmark & ~0x80000000;
   2426 			if (recmark & 0x80000000)
   2427 				slp->ns_sflags |= SLP_S_LASTFRAG;
   2428 			else
   2429 				slp->ns_sflags &= ~SLP_S_LASTFRAG;
   2430 			if (slp->ns_reclen > NFS_MAXPACKET) {
   2431 				error = EPERM;
   2432 				break;
   2433 			}
   2434 		}
   2435 
   2436 		/*
   2437 		 * Now get the record part.
   2438 		 *
   2439 		 * Note that slp->ns_reclen may be 0.  Linux sometimes
   2440 		 * generates 0-length records.
   2441 		 */
   2442 		if (slp->ns_cc == slp->ns_reclen) {
   2443 			recm = slp->ns_raw;
   2444 			slp->ns_raw = slp->ns_rawend = (struct mbuf *)0;
   2445 			slp->ns_cc = slp->ns_reclen = 0;
   2446 		} else if (slp->ns_cc > slp->ns_reclen) {
   2447 			recm = slp->ns_raw;
   2448 			m = m_split(recm, slp->ns_reclen, waitflag);
   2449 			if (m == NULL) {
   2450 				error = EWOULDBLOCK;
   2451 				break;
   2452 			}
   2453 			m_claimm(recm, &nfs_mowner);
   2454 			slp->ns_raw = m;
   2455 			if (m->m_next == NULL)
   2456 				slp->ns_rawend = m;
   2457 			slp->ns_cc -= slp->ns_reclen;
   2458 			slp->ns_reclen = 0;
   2459 		} else {
   2460 			break;
   2461 		}
   2462 
   2463 		/*
   2464 		 * Accumulate the fragments into a record.
   2465 		 */
   2466 		mpp = &slp->ns_frag;
   2467 		while (*mpp)
   2468 			mpp = &((*mpp)->m_next);
   2469 		*mpp = recm;
   2470 		if (slp->ns_sflags & SLP_S_LASTFRAG) {
   2471 			if (slp->ns_recend)
   2472 				slp->ns_recend->m_nextpkt = slp->ns_frag;
   2473 			else
   2474 				slp->ns_rec = slp->ns_frag;
   2475 			slp->ns_recend = slp->ns_frag;
   2476 			slp->ns_frag = NULL;
   2477 		}
   2478 	}
   2479 
   2480 	return error;
   2481 }
   2482 
   2483 /*
   2484  * Parse an RPC header.
   2485  */
   2486 int
   2487 nfsrv_dorec(struct nfssvc_sock *slp, struct nfsd *nfsd,
   2488     struct nfsrv_descript **ndp, bool *more)
   2489 {
   2490 	struct mbuf *m, *nam;
   2491 	struct nfsrv_descript *nd;
   2492 	int error;
   2493 
   2494 	*ndp = NULL;
   2495 	*more = false;
   2496 
   2497 	if (nfsdsock_lock(slp, true)) {
   2498 		return ENOBUFS;
   2499 	}
   2500 	m = slp->ns_rec;
   2501 	if (m == NULL) {
   2502 		nfsdsock_unlock(slp);
   2503 		return ENOBUFS;
   2504 	}
   2505 	slp->ns_rec = m->m_nextpkt;
   2506 	if (slp->ns_rec) {
   2507 		m->m_nextpkt = NULL;
   2508 		*more = true;
   2509 	} else {
   2510 		slp->ns_recend = NULL;
   2511 	}
   2512 	nfsdsock_unlock(slp);
   2513 
   2514 	if (m->m_type == MT_SONAME) {
   2515 		nam = m;
   2516 		m = m->m_next;
   2517 		nam->m_next = NULL;
   2518 	} else
   2519 		nam = NULL;
   2520 	nd = nfsdreq_alloc();
   2521 	nd->nd_md = nd->nd_mrep = m;
   2522 	nd->nd_nam2 = nam;
   2523 	nd->nd_dpos = mtod(m, void *);
   2524 	error = nfs_getreq(nd, nfsd, true);
   2525 	if (error) {
   2526 		m_freem(nam);
   2527 		nfsdreq_free(nd);
   2528 		return (error);
   2529 	}
   2530 	*ndp = nd;
   2531 	nfsd->nfsd_nd = nd;
   2532 	return (0);
   2533 }
   2534 
   2535 /*
   2536  * Search for a sleeping nfsd and wake it up.
   2537  * SIDE EFFECT: If none found, set NFSD_CHECKSLP flag, so that one of the
   2538  * running nfsds will go look for the work in the nfssvc_sock list.
   2539  */
   2540 static void
   2541 nfsrv_wakenfsd_locked(struct nfssvc_sock *slp)
   2542 {
   2543 	struct nfsd *nd;
   2544 
   2545 	KASSERT(mutex_owned(&nfsd_lock));
   2546 
   2547 	if ((slp->ns_flags & SLP_VALID) == 0)
   2548 		return;
   2549 	if (slp->ns_gflags & SLP_G_DOREC)
   2550 		return;
   2551 	nd = SLIST_FIRST(&nfsd_idle_head);
   2552 	if (nd) {
   2553 		SLIST_REMOVE_HEAD(&nfsd_idle_head, nfsd_idle);
   2554 		if (nd->nfsd_slp)
   2555 			panic("nfsd wakeup");
   2556 		slp->ns_sref++;
   2557 		KASSERT(slp->ns_sref > 0);
   2558 		nd->nfsd_slp = slp;
   2559 		cv_signal(&nd->nfsd_cv);
   2560 	} else {
   2561 		slp->ns_gflags |= SLP_G_DOREC;
   2562 		nfsd_head_flag |= NFSD_CHECKSLP;
   2563 		TAILQ_INSERT_TAIL(&nfssvc_sockpending, slp, ns_pending);
   2564 	}
   2565 }
   2566 
   2567 void
   2568 nfsrv_wakenfsd(struct nfssvc_sock *slp)
   2569 {
   2570 
   2571 	mutex_enter(&nfsd_lock);
   2572 	nfsrv_wakenfsd_locked(slp);
   2573 	mutex_exit(&nfsd_lock);
   2574 }
   2575 
   2576 int
   2577 nfsdsock_sendreply(struct nfssvc_sock *slp, struct nfsrv_descript *nd)
   2578 {
   2579 	int error;
   2580 
   2581 	if (nd->nd_mrep != NULL) {
   2582 		m_freem(nd->nd_mrep);
   2583 		nd->nd_mrep = NULL;
   2584 	}
   2585 
   2586 	mutex_enter(&slp->ns_lock);
   2587 	if ((slp->ns_flags & SLP_SENDING) != 0) {
   2588 		SIMPLEQ_INSERT_TAIL(&slp->ns_sendq, nd, nd_sendq);
   2589 		mutex_exit(&slp->ns_lock);
   2590 		return 0;
   2591 	}
   2592 	KASSERT(SIMPLEQ_EMPTY(&slp->ns_sendq));
   2593 	slp->ns_flags |= SLP_SENDING;
   2594 	mutex_exit(&slp->ns_lock);
   2595 
   2596 again:
   2597 	error = nfs_send(slp->ns_so, nd->nd_nam2, nd->nd_mreq, NULL, curlwp);
   2598 	if (nd->nd_nam2) {
   2599 		m_free(nd->nd_nam2);
   2600 	}
   2601 	nfsdreq_free(nd);
   2602 
   2603 	mutex_enter(&slp->ns_lock);
   2604 	KASSERT((slp->ns_flags & SLP_SENDING) != 0);
   2605 	nd = SIMPLEQ_FIRST(&slp->ns_sendq);
   2606 	if (nd != NULL) {
   2607 		SIMPLEQ_REMOVE_HEAD(&slp->ns_sendq, nd_sendq);
   2608 		mutex_exit(&slp->ns_lock);
   2609 		goto again;
   2610 	}
   2611 	slp->ns_flags &= ~SLP_SENDING;
   2612 	mutex_exit(&slp->ns_lock);
   2613 
   2614 	return error;
   2615 }
   2616 
   2617 void
   2618 nfsdsock_setbits(struct nfssvc_sock *slp, int bits)
   2619 {
   2620 
   2621 	mutex_enter(&slp->ns_alock);
   2622 	slp->ns_aflags |= bits;
   2623 	mutex_exit(&slp->ns_alock);
   2624 }
   2625 
   2626 void
   2627 nfsdsock_clearbits(struct nfssvc_sock *slp, int bits)
   2628 {
   2629 
   2630 	mutex_enter(&slp->ns_alock);
   2631 	slp->ns_aflags &= ~bits;
   2632 	mutex_exit(&slp->ns_alock);
   2633 }
   2634 
   2635 bool
   2636 nfsdsock_testbits(struct nfssvc_sock *slp, int bits)
   2637 {
   2638 
   2639 	return (slp->ns_aflags & bits);
   2640 }
   2641 #endif /* NFSSERVER */
   2642 
   2643 #if defined(NFSSERVER) || (defined(NFS) && !defined(NFS_V2_ONLY))
   2644 static struct pool nfs_srvdesc_pool;
   2645 
   2646 void
   2647 nfsdreq_init(void)
   2648 {
   2649 
   2650 	pool_init(&nfs_srvdesc_pool, sizeof(struct nfsrv_descript),
   2651 	    0, 0, 0, "nfsrvdescpl", &pool_allocator_nointr, IPL_NONE);
   2652 }
   2653 
   2654 struct nfsrv_descript *
   2655 nfsdreq_alloc(void)
   2656 {
   2657 	struct nfsrv_descript *nd;
   2658 
   2659 	nd = pool_get(&nfs_srvdesc_pool, PR_WAITOK);
   2660 	nd->nd_cr = NULL;
   2661 	return nd;
   2662 }
   2663 
   2664 void
   2665 nfsdreq_free(struct nfsrv_descript *nd)
   2666 {
   2667 	kauth_cred_t cr;
   2668 
   2669 	cr = nd->nd_cr;
   2670 	if (cr != NULL) {
   2671 		kauth_cred_free(cr);
   2672 	}
   2673 	pool_put(&nfs_srvdesc_pool, nd);
   2674 }
   2675 #endif /* defined(NFSSERVER) || (defined(NFS) && !defined(NFS_V2_ONLY)) */
   2676