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