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