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