2 * Copyright (c) 1989, 1991, 1993, 1995
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Rick Macklem at The University of Guelph.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * @(#)nfs_socket.c 8.5 (Berkeley) 3/30/95
33 * $FreeBSD: src/sys/nfs/nfs_socket.c,v 1.60.2.6 2003/03/26 01:44:46 alfred Exp $
37 * Socket operations for use by nfs
40 #include <sys/param.h>
41 #include <sys/systm.h>
43 #include <sys/malloc.h>
44 #include <sys/mount.h>
45 #include <sys/kernel.h>
47 #include <sys/vnode.h>
48 #include <sys/fcntl.h>
49 #include <sys/protosw.h>
50 #include <sys/resourcevar.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/socketops.h>
54 #include <sys/syslog.h>
55 #include <sys/thread.h>
56 #include <sys/tprintf.h>
57 #include <sys/sysctl.h>
58 #include <sys/signalvar.h>
60 #include <sys/signal2.h>
61 #include <sys/mutex2.h>
62 #include <sys/socketvar2.h>
64 #include <netinet/in.h>
65 #include <netinet/tcp.h>
66 #include <sys/thread2.h>
72 #include "nfsm_subs.h"
81 * RTT calculations are scaled by 256 (8 bits). A proper fractional
82 * RTT will still be calculated even with a slow NFS timer.
84 #define NFS_SRTT(r) (r)->r_nmp->nm_srtt[proct[(r)->r_procnum]]
85 #define NFS_SDRTT(r) (r)->r_nmp->nm_sdrtt[proct[(r)->r_procnum]]
86 #define NFS_RTT_SCALE_BITS 8 /* bits */
87 #define NFS_RTT_SCALE 256 /* value */
90 * Defines which timer to use for the procnum.
97 static int proct[NFS_NPROCS] = {
98 0, 1, 0, 2, 1, 3, 3, 4, 0, 0, /* 00-09 */
99 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, /* 10-19 */
100 0, 5, 0, 0, 0, 0, /* 20-29 */
103 static int multt[NFS_NPROCS] = {
104 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-09 */
105 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 10-19 */
106 1, 2, 1, 1, 1, 1, /* 20-29 */
109 static int nfs_backoff[8] = { 2, 3, 5, 8, 13, 21, 34, 55 };
110 static int nfs_realign_test;
111 static int nfs_realign_count;
112 static int nfs_showrtt;
113 static int nfs_showrexmit;
114 int nfs_maxasyncbio = NFS_MAXASYNCBIO;
116 SYSCTL_DECL(_vfs_nfs);
118 SYSCTL_INT(_vfs_nfs, OID_AUTO, realign_test, CTLFLAG_RW, &nfs_realign_test, 0,
119 "Number of times mbufs have been tested for bad alignment");
120 SYSCTL_INT(_vfs_nfs, OID_AUTO, realign_count, CTLFLAG_RW, &nfs_realign_count, 0,
121 "Number of realignments for badly aligned mbuf data");
122 SYSCTL_INT(_vfs_nfs, OID_AUTO, showrtt, CTLFLAG_RW, &nfs_showrtt, 0,
123 "Show round trip time output");
124 SYSCTL_INT(_vfs_nfs, OID_AUTO, showrexmit, CTLFLAG_RW, &nfs_showrexmit, 0,
125 "Show retransmits info");
126 SYSCTL_INT(_vfs_nfs, OID_AUTO, maxasyncbio, CTLFLAG_RW, &nfs_maxasyncbio, 0,
127 "Max number of asynchronous bio's");
129 static int nfs_request_setup(nfsm_info_t info);
130 static int nfs_request_auth(struct nfsreq *rep);
131 static int nfs_request_try(struct nfsreq *rep);
132 static int nfs_request_waitreply(struct nfsreq *rep);
133 static int nfs_request_processreply(nfsm_info_t info, int);
136 struct nfsrtt nfsrtt;
137 struct callout nfs_timer_handle;
139 static int nfs_msg (struct thread *,char *,char *);
140 static int nfs_rcvlock (struct nfsmount *nmp, struct nfsreq *myreq);
141 static void nfs_rcvunlock (struct nfsmount *nmp);
142 static void nfs_realign (struct mbuf **pm, int hsiz);
143 static int nfs_receive (struct nfsmount *nmp, struct nfsreq *rep,
144 struct sockaddr **aname, struct mbuf **mp);
145 static void nfs_softterm (struct nfsreq *rep, int islocked);
146 static void nfs_hardterm (struct nfsreq *rep, int islocked);
147 static int nfs_reconnect (struct nfsmount *nmp, struct nfsreq *rep);
149 static int nfsrv_getstream (struct nfssvc_sock *, int, int *);
150 static void nfs_timer_req(struct nfsreq *req);
151 static void nfs_checkpkt(struct mbuf *m, int len);
153 int (*nfsrv3_procs[NFS_NPROCS]) (struct nfsrv_descript *nd,
154 struct nfssvc_sock *slp,
156 struct mbuf **mreqp) = {
184 #endif /* NFS_NOSERVER */
187 * Initialize sockets and congestion for a new NFS connection.
188 * We do not free the sockaddr if error.
191 nfs_connect(struct nfsmount *nmp, struct nfsreq *rep)
195 struct sockaddr *saddr;
196 struct sockaddr_in *sin;
197 struct thread *td = &thread0; /* only used for socreate and sobind */
199 nmp->nm_so = so = NULL;
200 if (nmp->nm_flag & NFSMNT_FORCE)
203 error = socreate(saddr->sa_family, &so, nmp->nm_sotype,
204 nmp->nm_soproto, td);
207 nmp->nm_soflags = so->so_proto->pr_flags;
210 * Some servers require that the client port be a reserved port number.
212 if (saddr->sa_family == AF_INET && (nmp->nm_flag & NFSMNT_RESVPORT)) {
215 struct sockaddr_in ssin;
217 bzero(&sopt, sizeof sopt);
218 ip = IP_PORTRANGE_LOW;
219 sopt.sopt_level = IPPROTO_IP;
220 sopt.sopt_name = IP_PORTRANGE;
221 sopt.sopt_val = (void *)&ip;
222 sopt.sopt_valsize = sizeof(ip);
224 error = sosetopt(so, &sopt);
227 bzero(&ssin, sizeof ssin);
229 sin->sin_len = sizeof (struct sockaddr_in);
230 sin->sin_family = AF_INET;
231 sin->sin_addr.s_addr = INADDR_ANY;
232 sin->sin_port = htons(0);
233 error = sobind(so, (struct sockaddr *)sin, td);
236 bzero(&sopt, sizeof sopt);
237 ip = IP_PORTRANGE_DEFAULT;
238 sopt.sopt_level = IPPROTO_IP;
239 sopt.sopt_name = IP_PORTRANGE;
240 sopt.sopt_val = (void *)&ip;
241 sopt.sopt_valsize = sizeof(ip);
243 error = sosetopt(so, &sopt);
249 * Protocols that do not require connections may be optionally left
250 * unconnected for servers that reply from a port other than NFS_PORT.
252 if (nmp->nm_flag & NFSMNT_NOCONN) {
253 if (nmp->nm_soflags & PR_CONNREQUIRED) {
258 error = soconnect(so, nmp->nm_nam, td, TRUE);
263 * Wait for the connection to complete. Cribbed from the
264 * connect system call but with the wait timing out so
265 * that interruptible mounts don't hang here for a long time.
268 while ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
269 (void) tsleep((caddr_t)&so->so_timeo, 0,
271 if ((so->so_state & SS_ISCONNECTING) &&
272 so->so_error == 0 && rep &&
273 (error = nfs_sigintr(nmp, rep, rep->r_td)) != 0){
274 soclrstate(so, SS_ISCONNECTING);
280 error = so->so_error;
287 so->so_rcv.ssb_timeo = (5 * hz);
288 so->so_snd.ssb_timeo = (5 * hz);
291 * Get buffer reservation size from sysctl, but impose reasonable
294 if (nmp->nm_sotype == SOCK_STREAM) {
295 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
299 bzero(&sopt, sizeof sopt);
300 sopt.sopt_level = SOL_SOCKET;
301 sopt.sopt_name = SO_KEEPALIVE;
302 sopt.sopt_val = &val;
303 sopt.sopt_valsize = sizeof val;
307 if (so->so_proto->pr_protocol == IPPROTO_TCP) {
311 bzero(&sopt, sizeof sopt);
312 sopt.sopt_level = IPPROTO_TCP;
313 sopt.sopt_name = TCP_NODELAY;
314 sopt.sopt_val = &val;
315 sopt.sopt_valsize = sizeof val;
319 bzero(&sopt, sizeof sopt);
320 sopt.sopt_level = IPPROTO_TCP;
321 sopt.sopt_name = TCP_FASTKEEP;
322 sopt.sopt_val = &val;
323 sopt.sopt_valsize = sizeof val;
328 error = soreserve(so, nfs_soreserve, nfs_soreserve, NULL);
331 atomic_set_int(&so->so_rcv.ssb_flags, SSB_NOINTR);
332 atomic_set_int(&so->so_snd.ssb_flags, SSB_NOINTR);
335 * Clear AUTOSIZE, otherwise the socket buffer could be reduced
336 * to the point where rpc's cannot be queued using the mbuf
339 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
340 atomic_clear_int(&so->so_snd.ssb_flags, SSB_AUTOSIZE);
342 /* Initialize other non-zero congestion variables */
343 nmp->nm_srtt[0] = nmp->nm_srtt[1] = nmp->nm_srtt[2] =
344 nmp->nm_srtt[3] = (NFS_TIMEO << NFS_RTT_SCALE_BITS);
345 nmp->nm_sdrtt[0] = nmp->nm_sdrtt[1] = nmp->nm_sdrtt[2] =
346 nmp->nm_sdrtt[3] = 0;
347 nmp->nm_maxasync_scaled = NFS_MINASYNC_SCALED;
348 nmp->nm_timeouts = 0;
351 * Assign nm_so last. The moment nm_so is assigned the nfs_timer()
352 * can mess with the socket.
359 soshutdown(so, SHUT_RDWR);
360 soclose(so, FNONBLOCK);
367 * Called when a connection is broken on a reliable protocol.
368 * - clean up the old socket
369 * - nfs_connect() again
370 * - set R_NEEDSXMIT 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.
375 nfs_reconnect(struct nfsmount *nmp, struct nfsreq *rep)
381 if (nmp->nm_rxstate >= NFSSVC_STOPPING)
383 while ((error = nfs_connect(nmp, rep)) != 0) {
384 if (error == EINTR || error == ERESTART)
388 if (nmp->nm_rxstate >= NFSSVC_STOPPING)
390 (void) tsleep((caddr_t)&lbolt, 0, "nfscon", 0);
394 * Loop through outstanding request list and fix up all requests
398 TAILQ_FOREACH(req, &nmp->nm_reqq, r_chain) {
399 KKASSERT(req->r_nmp == nmp);
400 req->r_flags |= R_NEEDSXMIT;
407 * NFS disconnect. Clean up and unlink.
410 nfs_disconnect(struct nfsmount *nmp)
417 soshutdown(so, SHUT_RDWR);
418 soclose(so, FNONBLOCK);
423 nfs_safedisconnect(struct nfsmount *nmp)
427 error = nfs_rcvlock(nmp, NULL);
434 * This is the nfs send routine. For connection based socket types, it
435 * must be called with an nfs_sndlock() on the socket.
436 * "rep == NULL" indicates that it has been called from a server.
437 * For the client side:
438 * - return EINTR if the RPC is terminated, 0 otherwise
439 * - set R_NEEDSXMIT if the send fails for any reason
440 * - do any cleanup required by recoverable socket errors (?)
441 * For the server side:
442 * - return EINTR or ERESTART if interrupted by a signal
443 * - return EPIPE if a connection is lost for connection based sockets (TCP...)
444 * - do any cleanup required by recoverable socket errors (?)
447 nfs_send(struct socket *so, struct sockaddr *nam, struct mbuf *top,
450 struct sockaddr *sendnam;
451 int error, soflags, flags;
454 if (rep->r_flags & R_SOFTTERM) {
458 if ((so = rep->r_nmp->nm_so) == NULL) {
459 rep->r_flags |= R_NEEDSXMIT;
463 rep->r_flags &= ~R_NEEDSXMIT;
464 soflags = rep->r_nmp->nm_soflags;
466 soflags = so->so_proto->pr_flags;
468 if ((soflags & PR_CONNREQUIRED) || (so->so_state & SS_ISCONNECTED))
472 if (so->so_type == SOCK_SEQPACKET)
478 * calls pru_sosend -> sosend -> so_pru_send -> netrpc
480 error = so_pru_sosend(so, sendnam, NULL, top, NULL, flags,
484 * ENOBUFS for dgram sockets is transient and non fatal.
485 * No need to log, and no need to break a soft mount.
487 if (error == ENOBUFS && so->so_type == SOCK_DGRAM) {
490 * do backoff retransmit on client
493 if ((rep->r_nmp->nm_state & NFSSTA_SENDSPACE) == 0) {
494 rep->r_nmp->nm_state |= NFSSTA_SENDSPACE;
495 kprintf("Warning: NFS: Insufficient sendspace "
497 "\t You must increase vfs.nfs.soreserve"
498 "or decrease vfs.nfs.maxasyncbio\n",
499 so->so_snd.ssb_hiwat);
501 rep->r_flags |= R_NEEDSXMIT;
507 log(LOG_INFO, "nfs send error %d for server %s\n",error,
508 rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
510 * Deal with errors for the client side.
512 if (rep->r_flags & R_SOFTTERM)
515 rep->r_flags |= R_NEEDSXMIT;
517 log(LOG_INFO, "nfsd send error %d\n", error);
521 * Handle any recoverable (soft) socket errors here. (?)
523 if (error != EINTR && error != ERESTART &&
524 error != EWOULDBLOCK && error != EPIPE)
531 * Receive a Sun RPC Request/Reply. For SOCK_DGRAM, the work is all
532 * done by soreceive(), but for SOCK_STREAM we must deal with the Record
533 * Mark and consolidate the data into a new mbuf list.
534 * nb: Sometimes TCP passes the data up to soreceive() in long lists of
536 * For SOCK_STREAM we must be very careful to read an entire record once
537 * we have read any of it, even if the system call has been interrupted.
540 nfs_receive(struct nfsmount *nmp, struct nfsreq *rep,
541 struct sockaddr **aname, struct mbuf **mp)
548 struct mbuf *control;
550 struct sockaddr **getnam;
551 int error, sotype, rcvflg;
552 struct thread *td = curthread; /* XXX */
555 * Set up arguments for soreceive()
559 sotype = nmp->nm_sotype;
562 * For reliable protocols, lock against other senders/receivers
563 * in case a reconnect is necessary.
564 * For SOCK_STREAM, first get the Record Mark to find out how much
565 * more there is to get.
566 * We must lock the socket against other receivers
567 * until we have an entire rpc request/reply.
569 if (sotype != SOCK_DGRAM) {
570 error = nfs_sndlock(nmp, rep);
575 * Check for fatal errors and resending request.
578 * Ugh: If a reconnect attempt just happened, nm_so
579 * would have changed. NULL indicates a failed
580 * attempt that has essentially shut down this
583 if (rep && (rep->r_mrep || (rep->r_flags & R_SOFTTERM))) {
589 error = nfs_reconnect(nmp, rep);
596 while (rep && (rep->r_flags & R_NEEDSXMIT)) {
597 m = m_copym(rep->r_mreq, 0, M_COPYALL, M_WAITOK);
598 nfsstats.rpcretries++;
599 error = nfs_send(so, rep->r_nmp->nm_nam, m, rep);
601 if (error == EINTR || error == ERESTART ||
602 (error = nfs_reconnect(nmp, rep)) != 0) {
610 if (sotype == SOCK_STREAM) {
612 * Get the length marker from the stream
614 aio.iov_base = (caddr_t)&len;
615 aio.iov_len = sizeof(u_int32_t);
618 auio.uio_segflg = UIO_SYSSPACE;
619 auio.uio_rw = UIO_READ;
621 auio.uio_resid = sizeof(u_int32_t);
624 rcvflg = MSG_WAITALL;
625 error = so_pru_soreceive(so, NULL, &auio, NULL,
627 if (error == EWOULDBLOCK && rep) {
628 if (rep->r_flags & R_SOFTTERM)
631 } while (error == EWOULDBLOCK);
633 if (error == 0 && auio.uio_resid > 0) {
635 * Only log short packets if not EOF
637 if (auio.uio_resid != sizeof(u_int32_t)) {
639 "short receive (%d/%d) from nfs server %s\n",
640 (int)(sizeof(u_int32_t) - auio.uio_resid),
641 (int)sizeof(u_int32_t),
642 nmp->nm_mountp->mnt_stat.f_mntfromname);
648 len = ntohl(len) & ~0x80000000;
650 * This is SERIOUS! We are out of sync with the sender
651 * and forcing a disconnect/reconnect is all I can do.
653 if (len > NFS_MAXPACKET) {
654 log(LOG_ERR, "%s (%d) from nfs server %s\n",
655 "impossible packet length",
657 nmp->nm_mountp->mnt_stat.f_mntfromname);
663 * Get the rest of the packet as an mbuf chain
667 rcvflg = MSG_WAITALL;
668 error = so_pru_soreceive(so, NULL, NULL, &sio,
670 } while (error == EWOULDBLOCK || error == EINTR ||
672 if (error == 0 && sio.sb_cc != len) {
673 if (sio.sb_cc != 0) {
675 "short receive (%zu/%d) from nfs server %s\n",
676 (size_t)len - auio.uio_resid, len,
677 nmp->nm_mountp->mnt_stat.f_mntfromname);
684 * Non-stream, so get the whole packet by not
685 * specifying MSG_WAITALL and by specifying a large
688 * We have no use for control msg., but must grab them
689 * and then throw them away so we know what is going
692 sbinit(&sio, 100000000);
695 error = so_pru_soreceive(so, NULL, NULL, &sio,
699 if (error == EWOULDBLOCK && rep) {
700 if (rep->r_flags & R_SOFTTERM) {
705 } while (error == EWOULDBLOCK ||
706 (error == 0 && sio.sb_mb == NULL && control));
707 if ((rcvflg & MSG_EOR) == 0)
709 if (error == 0 && sio.sb_mb == NULL)
715 if (error && error != EINTR && error != ERESTART) {
718 if (error != EPIPE) {
720 "receive error %d from nfs server %s\n",
722 nmp->nm_mountp->mnt_stat.f_mntfromname);
724 error = nfs_sndlock(nmp, rep);
726 error = nfs_reconnect(nmp, rep);
734 if ((so = nmp->nm_so) == NULL)
736 if (so->so_state & SS_ISCONNECTED)
740 sbinit(&sio, 100000000);
743 error = so_pru_soreceive(so, getnam, NULL, &sio,
745 if (error == EWOULDBLOCK && rep &&
746 (rep->r_flags & R_SOFTTERM)) {
750 } while (error == EWOULDBLOCK);
756 * A shutdown may result in no error and no mbuf.
759 if (*mp == NULL && error == 0)
768 * Search for any mbufs that are not a multiple of 4 bytes long
769 * or with m_data not longword aligned.
770 * These could cause pointer alignment problems, so copy them to
771 * well aligned mbufs.
773 nfs_realign(mp, 5 * NFSX_UNSIGNED);
778 * Implement receipt of reply on a socket.
780 * We must search through the list of received datagrams matching them
781 * with outstanding requests using the xid, until ours is found.
783 * If myrep is NULL we process packets on the socket until
784 * interrupted or until nm_reqrxq is non-empty.
788 nfs_reply(struct nfsmount *nmp, struct nfsreq *myrep)
791 struct sockaddr *nam;
795 struct nfsm_info info;
798 * Loop around until we get our own reply
802 * Lock against other receivers so that I don't get stuck in
803 * sbwait() after someone else has received my reply for me.
804 * Also necessary for connection based protocols to avoid
805 * race conditions during a reconnect.
807 * If nfs_rcvlock() returns EALREADY, that means that
808 * the reply has already been recieved by another
809 * process and we can return immediately. In this
810 * case, the lock is not taken to avoid races with
815 error = nfs_rcvlock(nmp, myrep);
816 if (error == EALREADY)
822 * If myrep is NULL we are the receiver helper thread.
823 * Stop waiting for incoming replies if there are
824 * messages sitting on reqrxq that we need to process,
825 * or if a shutdown request is pending.
827 if (myrep == NULL && (TAILQ_FIRST(&nmp->nm_reqrxq) ||
828 nmp->nm_rxstate > NFSSVC_PENDING)) {
834 * Get the next Rpc reply off the socket
836 * We cannot release the receive lock until we've
837 * filled in rep->r_mrep, otherwise a waiting
838 * thread may deadlock in soreceive with no incoming
841 error = nfs_receive(nmp, myrep, &nam, &info.mrep);
844 * Ignore routing errors on connectionless protocols??
847 if (NFSIGNORE_SOERROR(nmp->nm_soflags, error)) {
848 if (nmp->nm_so == NULL)
850 nmp->nm_so->so_error = 0;
856 kfree(nam, M_SONAME);
859 * Get the xid and check that it is an rpc reply
862 info.dpos = mtod(info.md, caddr_t);
863 NULLOUT(tl = nfsm_dissect(&info, 2*NFSX_UNSIGNED));
865 if (*tl != rpc_reply) {
866 nfsstats.rpcinvalid++;
875 * Loop through the request list to match up the reply
876 * Iff no match, just drop the datagram. On match, set
877 * r_mrep atomically to prevent the timer from messing
878 * around with the request after we have exited the critical
882 TAILQ_FOREACH(rep, &nmp->nm_reqq, r_chain) {
883 if (rep->r_mrep == NULL && rxid == rep->r_xid)
888 * Fill in the rest of the reply if we found a match.
890 * Deal with duplicate responses if there was no match.
894 rep->r_dpos = info.dpos;
898 rt = &nfsrtt.rttl[nfsrtt.pos];
899 rt->proc = rep->r_procnum;
902 rt->cwnd = nmp->nm_maxasync_scaled;
903 rt->srtt = nmp->nm_srtt[proct[rep->r_procnum] - 1];
904 rt->sdrtt = nmp->nm_sdrtt[proct[rep->r_procnum] - 1];
905 rt->fsid = nmp->nm_mountp->mnt_stat.f_fsid;
906 getmicrotime(&rt->tstamp);
907 if (rep->r_flags & R_TIMING)
908 rt->rtt = rep->r_rtt;
911 nfsrtt.pos = (nfsrtt.pos + 1) % NFSRTTLOGSIZ;
915 * New congestion control is based only on async
918 if (nmp->nm_maxasync_scaled < NFS_MAXASYNC_SCALED)
919 ++nmp->nm_maxasync_scaled;
920 if (rep->r_flags & R_SENT) {
921 rep->r_flags &= ~R_SENT;
924 * Update rtt using a gain of 0.125 on the mean
925 * and a gain of 0.25 on the deviation.
927 * NOTE SRTT/SDRTT are only good if R_TIMING is set.
929 if ((rep->r_flags & R_TIMING) && rep->r_rexmit == 0) {
931 * Since the timer resolution of
932 * NFS_HZ is so course, it can often
933 * result in r_rtt == 0. Since
934 * r_rtt == N means that the actual
935 * rtt is between N+dt and N+2-dt ticks,
941 #define NFSRSB NFS_RTT_SCALE_BITS
942 n = ((NFS_SRTT(rep) * 7) +
943 (rep->r_rtt << NFSRSB)) >> 3;
944 d = n - NFS_SRTT(rep);
948 * Don't let the jitter calculation decay
949 * too quickly, but we want a fast rampup.
954 if (d < NFS_SDRTT(rep))
955 n = ((NFS_SDRTT(rep) * 15) + d) >> 4;
957 n = ((NFS_SDRTT(rep) * 3) + d) >> 2;
961 nmp->nm_timeouts = 0;
962 rep->r_mrep = info.mrep;
963 nfs_hardterm(rep, 0);
966 * Extract vers, prog, nfsver, procnum. A duplicate
967 * response means we didn't wait long enough so
968 * we increase the SRTT to avoid future spurious
971 u_int procnum = nmp->nm_lastreprocnum;
974 if (procnum < NFS_NPROCS && proct[procnum]) {
977 n = nmp->nm_srtt[proct[procnum]];
978 n += NFS_ASYSCALE * NFS_HZ;
979 if (n < NFS_ASYSCALE * NFS_HZ * 10)
980 n = NFS_ASYSCALE * NFS_HZ * 10;
981 nmp->nm_srtt[proct[procnum]] = n;
988 * If not matched to a request, drop it.
989 * If it's mine, get out.
992 nfsstats.rpcunexpected++;
995 } else if (rep == myrep) {
996 if (rep->r_mrep == NULL)
997 panic("nfsreply nil");
1004 * Run the request state machine until the target state is reached
1005 * or a fatal error occurs. The target state is not run. Specifying
1006 * a target of NFSM_STATE_DONE runs the state machine until the rpc
1009 * EINPROGRESS is returned for all states other then the DONE state,
1010 * indicating that the rpc is still in progress.
1013 nfs_request(struct nfsm_info *info, nfsm_state_t bstate, nfsm_state_t estate)
1017 while (info->state >= bstate && info->state < estate) {
1018 switch(info->state) {
1019 case NFSM_STATE_SETUP:
1021 * Setup the nfsreq. Any error which occurs during
1022 * this state is fatal.
1024 info->error = nfs_request_setup(info);
1026 info->state = NFSM_STATE_DONE;
1027 return (info->error);
1030 req->r_mrp = &info->mrep;
1031 req->r_mdp = &info->md;
1032 req->r_dposp = &info->dpos;
1033 info->state = NFSM_STATE_AUTH;
1036 case NFSM_STATE_AUTH:
1038 * Authenticate the nfsreq. Any error which occurs
1039 * during this state is fatal.
1041 info->error = nfs_request_auth(info->req);
1043 info->state = NFSM_STATE_DONE;
1044 return (info->error);
1046 info->state = NFSM_STATE_TRY;
1049 case NFSM_STATE_TRY:
1051 * Transmit or retransmit attempt. An error in this
1052 * state is ignored and we always move on to the
1055 * This can trivially race the receiver if the
1056 * request is asynchronous. nfs_request_try()
1057 * will thus set the state for us and we
1058 * must also return immediately if we are
1059 * running an async state machine, because
1060 * info can become invalid due to races after
1063 if (info->req->r_flags & R_ASYNC) {
1064 nfs_request_try(info->req);
1065 if (estate == NFSM_STATE_WAITREPLY)
1066 return (EINPROGRESS);
1068 nfs_request_try(info->req);
1069 info->state = NFSM_STATE_WAITREPLY;
1072 case NFSM_STATE_WAITREPLY:
1074 * Wait for a reply or timeout and move on to the
1075 * next state. The error returned by this state
1076 * is passed to the processing code in the next
1079 info->error = nfs_request_waitreply(info->req);
1080 info->state = NFSM_STATE_PROCESSREPLY;
1082 case NFSM_STATE_PROCESSREPLY:
1084 * Process the reply or timeout. Errors which occur
1085 * in this state may cause the state machine to
1086 * go back to an earlier state, and are fatal
1089 info->error = nfs_request_processreply(info,
1091 switch(info->error) {
1093 info->state = NFSM_STATE_AUTH;
1096 info->state = NFSM_STATE_TRY;
1100 * Operation complete, with or without an
1101 * error. We are done.
1104 info->state = NFSM_STATE_DONE;
1105 return (info->error);
1108 case NFSM_STATE_DONE:
1110 * Shouldn't be reached
1112 return (info->error);
1118 * If we are done return the error code (if any).
1119 * Otherwise return EINPROGRESS.
1121 if (info->state == NFSM_STATE_DONE)
1122 return (info->error);
1123 return (EINPROGRESS);
1127 * nfs_request - goes something like this
1128 * - fill in request struct
1129 * - links it into list
1130 * - calls nfs_send() for first transmit
1131 * - calls nfs_receive() to get reply
1132 * - break down rpc header and return with nfs reply pointed to
1134 * nb: always frees up mreq mbuf list
1137 nfs_request_setup(nfsm_info_t info)
1140 struct nfsmount *nmp;
1145 * Reject requests while attempting a forced unmount.
1147 if (info->vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF) {
1148 m_freem(info->mreq);
1152 nmp = VFSTONFS(info->vp->v_mount);
1153 req = kmalloc(sizeof(struct nfsreq), M_NFSREQ, M_WAITOK);
1155 req->r_vp = info->vp;
1156 req->r_td = info->td;
1157 req->r_procnum = info->procnum;
1159 req->r_cred = info->cred;
1167 req->r_mrest = info->mreq;
1168 req->r_mrest_len = i;
1171 * The presence of a non-NULL r_info in req indicates
1172 * async completion via our helper threads. See the receiver
1177 req->r_flags = R_ASYNC;
1187 nfs_request_auth(struct nfsreq *rep)
1189 struct nfsmount *nmp = rep->r_nmp;
1191 char nickv[RPCX_NICKVERF];
1192 int error = 0, auth_len, auth_type;
1195 char *auth_str, *verf_str;
1199 rep->r_failed_auth = 0;
1202 * Get the RPC header with authorization.
1204 verf_str = auth_str = NULL;
1206 if (nmp->nm_flag & NFSMNT_KERB) {
1208 verf_len = sizeof (nickv);
1209 auth_type = RPCAUTH_KERB4;
1210 bzero((caddr_t)rep->r_key, sizeof(rep->r_key));
1211 if (rep->r_failed_auth ||
1212 nfs_getnickauth(nmp, cred, &auth_str, &auth_len,
1213 verf_str, verf_len)) {
1214 error = nfs_getauth(nmp, rep, cred, &auth_str,
1215 &auth_len, verf_str, &verf_len, rep->r_key);
1217 m_freem(rep->r_mrest);
1218 rep->r_mrest = NULL;
1219 kfree((caddr_t)rep, M_NFSREQ);
1224 auth_type = RPCAUTH_UNIX;
1225 if (cred->cr_ngroups < 1)
1226 panic("nfsreq nogrps");
1227 auth_len = ((((cred->cr_ngroups - 1) > nmp->nm_numgrps) ?
1228 nmp->nm_numgrps : (cred->cr_ngroups - 1)) << 2) +
1232 nfs_checkpkt(rep->r_mrest, rep->r_mrest_len);
1233 m = nfsm_rpchead(cred, nmp->nm_flag, rep->r_procnum, auth_type,
1234 auth_len, auth_str, verf_len, verf_str,
1235 rep->r_mrest, rep->r_mrest_len, &rep->r_mheadend, &xid);
1236 rep->r_mrest = NULL;
1238 kfree(auth_str, M_TEMP);
1241 * For stream protocols, insert a Sun RPC Record Mark.
1243 if (nmp->nm_sotype == SOCK_STREAM) {
1244 M_PREPEND(m, NFSX_UNSIGNED, M_WAITOK);
1245 *mtod(m, u_int32_t *) = htonl(0x80000000 |
1246 (m->m_pkthdr.len - NFSX_UNSIGNED));
1249 nfs_checkpkt(m, m->m_pkthdr.len);
1257 nfs_request_try(struct nfsreq *rep)
1259 struct nfsmount *nmp = rep->r_nmp;
1264 * Request is not on any queue, only the owner has access to it
1265 * so it should not be locked by anyone atm.
1267 * Interlock to prevent races. While locked the only remote
1268 * action possible is for r_mrep to be set (once we enqueue it).
1270 if (rep->r_flags == 0xdeadc0de) {
1271 print_backtrace(-1);
1272 panic("flags nbad");
1274 KKASSERT((rep->r_flags & (R_LOCKED | R_ONREQQ)) == 0);
1275 if (nmp->nm_flag & NFSMNT_SOFT)
1276 rep->r_retry = nmp->nm_retry;
1278 rep->r_retry = NFS_MAXREXMIT + 1; /* past clip limit */
1279 rep->r_rtt = rep->r_rexmit = 0;
1280 if (proct[rep->r_procnum] > 0)
1281 rep->r_flags |= R_TIMING | R_LOCKED;
1283 rep->r_flags |= R_LOCKED;
1286 nfsstats.rpcrequests++;
1288 if (nmp->nm_flag & NFSMNT_FORCE) {
1289 rep->r_flags |= R_SOFTTERM;
1290 rep->r_flags &= ~R_LOCKED;
1292 rep->r_info->error = EINTR;
1295 rep->r_flags |= R_NEEDSXMIT; /* in case send lock races us */
1298 * Do the client side RPC.
1300 * Chain request into list of outstanding requests. Be sure
1301 * to put it LAST so timer finds oldest requests first. Note
1302 * that our control of R_LOCKED prevents the request from
1303 * getting ripped out from under us or transmitted by the
1306 * For requests with info structures we must atomically set the
1307 * info's state because the structure could become invalid upon
1308 * return due to races (i.e., if async)
1311 mtx_link_init(&rep->r_link);
1312 KKASSERT((rep->r_flags & R_ONREQQ) == 0);
1313 TAILQ_INSERT_TAIL(&nmp->nm_reqq, rep, r_chain);
1314 rep->r_flags |= R_ONREQQ;
1316 if (rep->r_flags & R_ASYNC)
1317 rep->r_info->state = NFSM_STATE_WAITREPLY;
1323 * Send if we can. Congestion control is not handled here any more
1324 * becausing trying to defer the initial send based on the nfs_timer
1325 * requires having a very fast nfs_timer, which is silly.
1328 if (nmp->nm_soflags & PR_CONNREQUIRED)
1329 error = nfs_sndlock(nmp, rep);
1330 if (error == 0 && (rep->r_flags & R_NEEDSXMIT)) {
1331 m2 = m_copym(rep->r_mreq, 0, M_COPYALL, M_WAITOK);
1332 error = nfs_send(nmp->nm_so, nmp->nm_nam, m2, rep);
1333 rep->r_flags &= ~R_NEEDSXMIT;
1334 if ((rep->r_flags & R_SENT) == 0) {
1335 rep->r_flags |= R_SENT;
1337 if (nmp->nm_soflags & PR_CONNREQUIRED)
1347 * Release the lock. The only remote action that may have occurred
1348 * would have been the setting of rep->r_mrep. If this occured
1349 * and the request was async we have to move it to the reader
1350 * thread's queue for action.
1352 * For async requests also make sure the reader is woken up so
1353 * it gets on the socket to read responses.
1356 if (rep->r_flags & R_ASYNC) {
1358 nfs_hardterm(rep, 1);
1359 rep->r_flags &= ~R_LOCKED;
1360 nfssvc_iod_reader_wakeup(nmp);
1362 rep->r_flags &= ~R_LOCKED;
1364 if (rep->r_flags & R_WANTED) {
1365 rep->r_flags &= ~R_WANTED;
1373 * This code is only called for synchronous requests. Completed synchronous
1374 * requests are left on reqq and we remove them before moving on to the
1378 nfs_request_waitreply(struct nfsreq *rep)
1380 struct nfsmount *nmp = rep->r_nmp;
1383 KKASSERT((rep->r_flags & R_ASYNC) == 0);
1386 * Wait until the request is finished.
1388 error = nfs_reply(nmp, rep);
1391 * RPC done, unlink the request, but don't rip it out from under
1392 * the callout timer.
1394 * Once unlinked no other receiver or the timer will have
1395 * visibility, so we do not have to set R_LOCKED.
1398 while (rep->r_flags & R_LOCKED) {
1399 rep->r_flags |= R_WANTED;
1400 tsleep(rep, 0, "nfstrac", 0);
1402 KKASSERT(rep->r_flags & R_ONREQQ);
1403 TAILQ_REMOVE(&nmp->nm_reqq, rep, r_chain);
1404 rep->r_flags &= ~R_ONREQQ;
1406 if (TAILQ_FIRST(&nmp->nm_bioq) &&
1407 nmp->nm_reqqlen <= nfs_maxasyncbio * 2 / 3) {
1408 nfssvc_iod_writer_wakeup(nmp);
1413 * Decrement the outstanding request count.
1415 if (rep->r_flags & R_SENT) {
1416 rep->r_flags &= ~R_SENT;
1422 * Process reply with error returned from nfs_requet_waitreply().
1424 * Returns EAGAIN if it wants us to loop up to nfs_request_try() again.
1425 * Returns ENEEDAUTH if it wants us to loop up to nfs_request_auth() again.
1428 nfs_request_processreply(nfsm_info_t info, int error)
1430 struct nfsreq *req = info->req;
1431 struct nfsmount *nmp = req->r_nmp;
1437 * If there was a successful reply and a tprintf msg.
1438 * tprintf a response.
1440 if (error == 0 && (req->r_flags & R_TPRINTFMSG)) {
1442 nmp->nm_mountp->mnt_stat.f_mntfromname,
1447 * Assign response and handle any pre-process error. Response
1448 * fields can be NULL if an error is already pending.
1450 info->mrep = req->r_mrep;
1451 info->md = req->r_md;
1452 info->dpos = req->r_dpos;
1455 m_freem(req->r_mreq);
1457 kfree(req, M_NFSREQ);
1463 * break down the rpc header and check if ok
1465 NULLOUT(tl = nfsm_dissect(info, 3 * NFSX_UNSIGNED));
1466 if (*tl++ == rpc_msgdenied) {
1467 if (*tl == rpc_mismatch) {
1469 } else if ((nmp->nm_flag & NFSMNT_KERB) &&
1470 *tl++ == rpc_autherr) {
1471 if (req->r_failed_auth == 0) {
1472 req->r_failed_auth++;
1473 req->r_mheadend->m_next = NULL;
1474 m_freem(info->mrep);
1476 m_freem(req->r_mreq);
1485 m_freem(info->mrep);
1487 m_freem(req->r_mreq);
1489 kfree(req, M_NFSREQ);
1495 * Grab any Kerberos verifier, otherwise just throw it away.
1497 verf_type = fxdr_unsigned(int, *tl++);
1498 i = fxdr_unsigned(int32_t, *tl);
1499 if ((nmp->nm_flag & NFSMNT_KERB) && verf_type == RPCAUTH_KERB4) {
1500 error = nfs_savenickauth(nmp, req->r_cred, i, req->r_key,
1501 &info->md, &info->dpos, info->mrep);
1505 ERROROUT(nfsm_adv(info, nfsm_rndup(i)));
1507 NULLOUT(tl = nfsm_dissect(info, NFSX_UNSIGNED));
1510 NULLOUT(tl = nfsm_dissect(info, NFSX_UNSIGNED));
1512 error = fxdr_unsigned(int, *tl);
1515 * Does anyone even implement this? Just impose
1518 if ((nmp->nm_flag & NFSMNT_NFSV3) &&
1519 error == NFSERR_TRYLATER) {
1520 m_freem(info->mrep);
1524 tsleep((caddr_t)&lbolt, 0, "nqnfstry", 0);
1525 return (EAGAIN); /* goto tryagain */
1530 * XXX We can't do this here any more because the
1531 * caller may be holding a shared lock on the
1534 * If the File Handle was stale, invalidate the
1535 * lookup cache, just in case.
1537 * To avoid namecache<->vnode deadlocks we must
1538 * release the vnode lock if we hold it.
1540 if (error == ESTALE) {
1541 struct vnode *vp = req->r_vp;
1544 ltype = lockstatus(&vp->v_lock, curthread);
1545 if (ltype == LK_EXCLUSIVE || ltype == LK_SHARED)
1546 lockmgr(&vp->v_lock, LK_RELEASE);
1547 cache_inval_vp(vp, CINV_CHILDREN);
1548 if (ltype == LK_EXCLUSIVE || ltype == LK_SHARED)
1549 lockmgr(&vp->v_lock, ltype);
1552 if (nmp->nm_flag & NFSMNT_NFSV3) {
1553 KKASSERT(*req->r_mrp == info->mrep);
1554 KKASSERT(*req->r_mdp == info->md);
1555 KKASSERT(*req->r_dposp == info->dpos);
1556 error |= NFSERR_RETERR;
1558 m_freem(info->mrep);
1561 m_freem(req->r_mreq);
1563 kfree(req, M_NFSREQ);
1568 KKASSERT(*req->r_mrp == info->mrep);
1569 KKASSERT(*req->r_mdp == info->md);
1570 KKASSERT(*req->r_dposp == info->dpos);
1571 m_freem(req->r_mreq);
1573 kfree(req, M_NFSREQ);
1576 m_freem(info->mrep);
1578 error = EPROTONOSUPPORT;
1580 m_freem(req->r_mreq);
1582 kfree(req, M_NFSREQ);
1587 #ifndef NFS_NOSERVER
1589 * Generate the rpc reply header
1590 * siz arg. is used to decide if adding a cluster is worthwhile
1593 nfs_rephead(int siz, struct nfsrv_descript *nd, struct nfssvc_sock *slp,
1594 int err, struct mbuf **mrq, struct mbuf **mbp, caddr_t *bposp)
1597 struct nfsm_info info;
1599 siz += RPC_REPLYSIZ;
1600 info.mb = m_getl(max_hdr + siz, M_WAITOK, MT_DATA, M_PKTHDR, NULL);
1601 info.mreq = info.mb;
1602 info.mreq->m_pkthdr.len = 0;
1604 * If this is not a cluster, try and leave leading space
1605 * for the lower level headers.
1607 if ((max_hdr + siz) < MINCLSIZE)
1608 info.mreq->m_data += max_hdr;
1609 tl = mtod(info.mreq, u_int32_t *);
1610 info.mreq->m_len = 6 * NFSX_UNSIGNED;
1611 info.bpos = ((caddr_t)tl) + info.mreq->m_len;
1612 *tl++ = txdr_unsigned(nd->nd_retxid);
1614 if (err == ERPCMISMATCH || (err & NFSERR_AUTHERR)) {
1615 *tl++ = rpc_msgdenied;
1616 if (err & NFSERR_AUTHERR) {
1617 *tl++ = rpc_autherr;
1618 *tl = txdr_unsigned(err & ~NFSERR_AUTHERR);
1619 info.mreq->m_len -= NFSX_UNSIGNED;
1620 info.bpos -= NFSX_UNSIGNED;
1622 *tl++ = rpc_mismatch;
1623 *tl++ = txdr_unsigned(RPC_VER2);
1624 *tl = txdr_unsigned(RPC_VER2);
1627 *tl++ = rpc_msgaccepted;
1630 * For Kerberos authentication, we must send the nickname
1631 * verifier back, otherwise just RPCAUTH_NULL.
1633 if (nd->nd_flag & ND_KERBFULL) {
1634 struct nfsuid *nuidp;
1635 struct timeval ktvout;
1637 for (nuidp = NUIDHASH(slp, nd->nd_cr.cr_uid)->lh_first;
1638 nuidp != NULL; nuidp = nuidp->nu_hash.le_next) {
1639 if (nuidp->nu_cr.cr_uid == nd->nd_cr.cr_uid &&
1640 (!nd->nd_nam2 || netaddr_match(AF_INET,
1641 &nuidp->nu_haddr, nd->nd_nam2)))
1646 * Encrypt the timestamp in ecb mode using the
1656 *tl++ = rpc_auth_kerb;
1657 *tl++ = txdr_unsigned(3 * NFSX_UNSIGNED);
1658 *tl = ktvout.tv_sec;
1659 tl = nfsm_build(&info, 3 * NFSX_UNSIGNED);
1660 *tl++ = ktvout.tv_usec;
1661 *tl++ = txdr_unsigned(nuidp->nu_cr.cr_uid);
1672 *tl = txdr_unsigned(RPC_PROGUNAVAIL);
1675 *tl = txdr_unsigned(RPC_PROGMISMATCH);
1676 tl = nfsm_build(&info, 2 * NFSX_UNSIGNED);
1677 *tl++ = txdr_unsigned(2);
1678 *tl = txdr_unsigned(3);
1681 *tl = txdr_unsigned(RPC_PROCUNAVAIL);
1684 *tl = txdr_unsigned(RPC_GARBAGE);
1688 if (err != NFSERR_RETVOID) {
1689 tl = nfsm_build(&info, NFSX_UNSIGNED);
1691 *tl = txdr_unsigned(nfsrv_errmap(nd, err));
1703 if (err != 0 && err != NFSERR_RETVOID)
1704 nfsstats.srvrpc_errs++;
1709 #endif /* NFS_NOSERVER */
1712 * Nfs timer routine.
1714 * Scan the nfsreq list and retranmit any requests that have timed out
1715 * To avoid retransmission attempts on STREAM sockets (in the future) make
1716 * sure to set the r_retry field to 0 (implies nm_retry == 0).
1718 * Requests with attached responses, terminated requests, and
1719 * locked requests are ignored. Locked requests will be picked up
1720 * in a later timer call.
1723 nfs_timer_callout(void *arg /* never used */)
1725 struct nfsmount *nmp;
1727 #ifndef NFS_NOSERVER
1728 struct nfssvc_sock *slp;
1730 #endif /* NFS_NOSERVER */
1732 lwkt_gettoken(&nfs_token);
1733 TAILQ_FOREACH(nmp, &nfs_mountq, nm_entry) {
1734 lwkt_gettoken(&nmp->nm_token);
1735 TAILQ_FOREACH(req, &nmp->nm_reqq, r_chain) {
1736 KKASSERT(nmp == req->r_nmp);
1739 if (req->r_flags & (R_SOFTTERM | R_LOCKED))
1743 * Handle timeout/retry. Be sure to process r_mrep
1744 * for async requests that completed while we had
1745 * the request locked or they will hang in the reqq
1748 req->r_flags |= R_LOCKED;
1749 if (nfs_sigintr(nmp, req, req->r_td)) {
1750 nfs_softterm(req, 1);
1751 req->r_flags &= ~R_LOCKED;
1754 if (req->r_flags & R_ASYNC) {
1756 nfs_hardterm(req, 1);
1757 req->r_flags &= ~R_LOCKED;
1758 nfssvc_iod_reader_wakeup(nmp);
1760 req->r_flags &= ~R_LOCKED;
1763 if (req->r_flags & R_WANTED) {
1764 req->r_flags &= ~R_WANTED;
1768 lwkt_reltoken(&nmp->nm_token);
1770 #ifndef NFS_NOSERVER
1773 * Scan the write gathering queues for writes that need to be
1776 cur_usec = nfs_curusec();
1778 TAILQ_FOREACH(slp, &nfssvc_sockhead, ns_chain) {
1779 /* XXX race against removal */
1780 if (lwkt_trytoken(&slp->ns_token)) {
1781 if (slp->ns_tq.lh_first &&
1782 (slp->ns_tq.lh_first->nd_time <= cur_usec)) {
1783 nfsrv_wakenfsd(slp, 1);
1785 lwkt_reltoken(&slp->ns_token);
1788 #endif /* NFS_NOSERVER */
1790 callout_reset(&nfs_timer_handle, nfs_ticks, nfs_timer_callout, NULL);
1791 lwkt_reltoken(&nfs_token);
1796 nfs_timer_req(struct nfsreq *req)
1798 struct thread *td = &thread0; /* XXX for creds, will break if sleep */
1799 struct nfsmount *nmp = req->r_nmp;
1806 * rtt ticks and timeout calculation. Return if the timeout
1807 * has not been reached yet, unless the packet is flagged
1808 * for an immediate send.
1810 * The mean rtt doesn't help when we get random I/Os, we have
1811 * to multiply by fairly large numbers.
1813 if (req->r_rtt >= 0) {
1815 * Calculate the timeout to test against.
1818 if (nmp->nm_flag & NFSMNT_DUMBTIMR) {
1819 timeo = nmp->nm_timeo << NFS_RTT_SCALE_BITS;
1820 } else if (req->r_flags & R_TIMING) {
1821 timeo = NFS_SRTT(req) + NFS_SDRTT(req);
1823 timeo = nmp->nm_timeo << NFS_RTT_SCALE_BITS;
1825 timeo *= multt[req->r_procnum];
1826 /* timeo is still scaled by SCALE_BITS */
1828 #define NFSFS (NFS_RTT_SCALE * NFS_HZ)
1829 if (req->r_flags & R_TIMING) {
1830 static long last_time;
1831 if (nfs_showrtt && last_time != time_uptime) {
1832 kprintf("rpccmd %d NFS SRTT %d SDRTT %d "
1834 proct[req->r_procnum],
1835 NFS_SRTT(req), NFS_SDRTT(req),
1837 timeo % NFSFS * 1000 / NFSFS);
1838 last_time = time_uptime;
1844 * deal with nfs_timer jitter.
1846 timeo = (timeo >> NFS_RTT_SCALE_BITS) + 1;
1850 if (nmp->nm_timeouts > 0)
1851 timeo *= nfs_backoff[nmp->nm_timeouts - 1];
1852 if (timeo > NFS_MAXTIMEO)
1853 timeo = NFS_MAXTIMEO;
1854 if (req->r_rtt <= timeo) {
1855 if ((req->r_flags & R_NEEDSXMIT) == 0)
1857 } else if (nmp->nm_timeouts < 8) {
1863 * Check for server not responding
1865 if ((req->r_flags & R_TPRINTFMSG) == 0 &&
1866 req->r_rexmit > nmp->nm_deadthresh) {
1867 nfs_msg(req->r_td, nmp->nm_mountp->mnt_stat.f_mntfromname,
1869 req->r_flags |= R_TPRINTFMSG;
1871 if (req->r_rexmit >= req->r_retry) { /* too many */
1872 nfsstats.rpctimeouts++;
1873 nfs_softterm(req, 1);
1878 * Generally disable retransmission on reliable sockets,
1879 * unless the request is flagged for immediate send.
1881 if (nmp->nm_sotype != SOCK_DGRAM) {
1882 if (++req->r_rexmit > NFS_MAXREXMIT)
1883 req->r_rexmit = NFS_MAXREXMIT;
1884 if ((req->r_flags & R_NEEDSXMIT) == 0)
1889 * Stop here if we do not have a socket!
1891 if ((so = nmp->nm_so) == NULL)
1895 * If there is enough space and the window allows.. resend it.
1897 * r_rtt is left intact in case we get an answer after the
1898 * retry that was a reply to the original packet.
1900 * NOTE: so_pru_send()
1902 if (ssb_space(&so->so_snd) >= req->r_mreq->m_pkthdr.len &&
1903 (req->r_flags & (R_SENT | R_NEEDSXMIT)) &&
1904 (m = m_copym(req->r_mreq, 0, M_COPYALL, M_NOWAIT))){
1905 if ((nmp->nm_flag & NFSMNT_NOCONN) == 0)
1906 error = so_pru_send(so, 0, m, NULL, NULL, td);
1908 error = so_pru_send(so, 0, m, nmp->nm_nam, NULL, td);
1910 if (NFSIGNORE_SOERROR(nmp->nm_soflags, error))
1912 req->r_flags |= R_NEEDSXMIT;
1913 } else if (req->r_mrep == NULL) {
1915 * Iff first send, start timing
1916 * else turn timing off, backoff timer
1917 * and divide congestion window by 2.
1919 * It is possible for the so_pru_send() to
1920 * block and for us to race a reply so we
1921 * only do this if the reply field has not
1922 * been filled in. R_LOCKED will prevent
1923 * the request from being ripped out from under
1926 * Record the last resent procnum to aid us
1927 * in duplicate detection on receive.
1929 if ((req->r_flags & R_NEEDSXMIT) == 0) {
1932 if (++req->r_rexmit > NFS_MAXREXMIT)
1933 req->r_rexmit = NFS_MAXREXMIT;
1934 nmp->nm_maxasync_scaled >>= 1;
1935 if (nmp->nm_maxasync_scaled < NFS_MINASYNC_SCALED)
1936 nmp->nm_maxasync_scaled = NFS_MINASYNC_SCALED;
1937 nfsstats.rpcretries++;
1938 nmp->nm_lastreprocnum = req->r_procnum;
1940 req->r_flags |= R_SENT;
1941 req->r_flags &= ~R_NEEDSXMIT;
1948 * Mark all of an nfs mount's outstanding requests with R_SOFTTERM and
1949 * wait for all requests to complete. This is used by forced unmounts
1950 * to terminate any outstanding RPCs.
1952 * Locked requests cannot be canceled but will be marked for
1956 nfs_nmcancelreqs(struct nfsmount *nmp)
1962 TAILQ_FOREACH(req, &nmp->nm_reqq, r_chain) {
1963 if (req->r_mrep != NULL || (req->r_flags & R_SOFTTERM))
1965 nfs_softterm(req, 0);
1967 /* XXX the other two queues as well */
1970 for (i = 0; i < 30; i++) {
1972 TAILQ_FOREACH(req, &nmp->nm_reqq, r_chain) {
1973 if (nmp == req->r_nmp)
1979 tsleep(&lbolt, 0, "nfscancel", 0);
1985 * Soft-terminate a request, effectively marking it as failed.
1987 * Must be called from within a critical section.
1990 nfs_softterm(struct nfsreq *rep, int islocked)
1992 rep->r_flags |= R_SOFTTERM;
1994 rep->r_info->error = EINTR;
1995 nfs_hardterm(rep, islocked);
1999 * Hard-terminate a request, typically after getting a response.
2001 * The state machine can still decide to re-issue it later if necessary.
2003 * Must be called from within a critical section.
2006 nfs_hardterm(struct nfsreq *rep, int islocked)
2008 struct nfsmount *nmp = rep->r_nmp;
2011 * The nm_send count is decremented now to avoid deadlocks
2012 * when the process in soreceive() hasn't yet managed to send
2015 if (rep->r_flags & R_SENT) {
2016 rep->r_flags &= ~R_SENT;
2020 * If we locked the request or nobody else has locked the request,
2021 * and the request is async, we can move it to the reader thread's
2022 * queue now and fix up the state.
2024 * If we locked the request or nobody else has locked the request,
2025 * we can wake up anyone blocked waiting for a response on the
2028 if (islocked || (rep->r_flags & R_LOCKED) == 0) {
2029 if ((rep->r_flags & (R_ONREQQ | R_ASYNC)) ==
2030 (R_ONREQQ | R_ASYNC)) {
2031 rep->r_flags &= ~R_ONREQQ;
2032 TAILQ_REMOVE(&nmp->nm_reqq, rep, r_chain);
2034 TAILQ_INSERT_TAIL(&nmp->nm_reqrxq, rep, r_chain);
2035 KKASSERT(rep->r_info->state == NFSM_STATE_TRY ||
2036 rep->r_info->state == NFSM_STATE_WAITREPLY);
2039 * When setting the state to PROCESSREPLY we must
2040 * roll-up any error not related to the contents of
2041 * the reply (i.e. if there is no contents).
2043 rep->r_info->state = NFSM_STATE_PROCESSREPLY;
2044 nfssvc_iod_reader_wakeup(nmp);
2045 if (TAILQ_FIRST(&nmp->nm_bioq) &&
2046 nmp->nm_reqqlen <= nfs_maxasyncbio * 2 / 3) {
2047 nfssvc_iod_writer_wakeup(nmp);
2050 mtx_abort_link(&nmp->nm_rxlock, &rep->r_link);
2055 * Test for a termination condition pending on the process.
2056 * This is used for NFSMNT_INT mounts.
2059 nfs_sigintr(struct nfsmount *nmp, struct nfsreq *rep, struct thread *td)
2065 if (rep && (rep->r_flags & R_SOFTTERM))
2067 /* Terminate all requests while attempting a forced unmount. */
2068 if (nmp->nm_mountp->mnt_kern_flag & MNTK_UNMOUNTF)
2070 if (!(nmp->nm_flag & NFSMNT_INT))
2072 /* td might be NULL YYY */
2073 if (td == NULL || (p = td->td_proc) == NULL)
2077 tmpset = lwp_sigpend(lp);
2078 SIGSETNAND(tmpset, lp->lwp_sigmask);
2079 SIGSETNAND(tmpset, p->p_sigignore);
2080 if (SIGNOTEMPTY(tmpset) && NFSINT_SIGMASK(tmpset))
2087 * Lock a socket against others.
2088 * Necessary for STREAM sockets to ensure you get an entire rpc request/reply
2089 * and also to avoid race conditions between the processes with nfs requests
2090 * in progress when a reconnect is necessary.
2093 nfs_sndlock(struct nfsmount *nmp, struct nfsreq *rep)
2095 mtx_t *mtx = &nmp->nm_txlock;
2103 td = rep ? rep->r_td : NULL;
2104 if (nmp->nm_flag & NFSMNT_INT)
2107 while ((error = mtx_lock_ex_try(mtx)) != 0) {
2108 if (nfs_sigintr(nmp, rep, td)) {
2112 error = mtx_lock_ex(mtx, slpflag, slptimeo);
2115 if (slpflag == PCATCH) {
2120 /* Always fail if our request has been cancelled. */
2121 if (rep && (rep->r_flags & R_SOFTTERM)) {
2130 * Unlock the stream socket for others.
2133 nfs_sndunlock(struct nfsmount *nmp)
2135 mtx_unlock(&nmp->nm_txlock);
2139 * Lock the receiver side of the socket.
2144 nfs_rcvlock(struct nfsmount *nmp, struct nfsreq *rep)
2146 mtx_t *mtx = &nmp->nm_rxlock;
2152 * Unconditionally check for completion in case another nfsiod
2153 * get the packet while the caller was blocked, before the caller
2154 * called us. Packet reception is handled by mainline code which
2155 * is protected by the BGL at the moment.
2157 * We do not strictly need the second check just before the
2158 * tsleep(), but it's good defensive programming.
2160 if (rep && rep->r_mrep != NULL)
2163 if (nmp->nm_flag & NFSMNT_INT)
2169 while ((error = mtx_lock_ex_try(mtx)) != 0) {
2170 if (nfs_sigintr(nmp, rep, (rep ? rep->r_td : NULL))) {
2174 if (rep && rep->r_mrep != NULL) {
2180 * NOTE: can return ENOLCK, but in that case rep->r_mrep
2181 * will already be set.
2184 error = mtx_lock_ex_link(mtx, &rep->r_link,
2187 error = mtx_lock_ex(mtx, slpflag, slptimeo);
2193 * If our reply was recieved while we were sleeping,
2194 * then just return without taking the lock to avoid a
2195 * situation where a single iod could 'capture' the
2198 if (rep && rep->r_mrep != NULL) {
2202 if (slpflag == PCATCH) {
2208 if (rep && rep->r_mrep != NULL) {
2217 * Unlock the stream socket for others.
2220 nfs_rcvunlock(struct nfsmount *nmp)
2222 mtx_unlock(&nmp->nm_rxlock);
2228 * Check for badly aligned mbuf data and realign by copying the unaligned
2229 * portion of the data into a new mbuf chain and freeing the portions
2230 * of the old chain that were replaced.
2232 * We cannot simply realign the data within the existing mbuf chain
2233 * because the underlying buffers may contain other rpc commands and
2234 * we cannot afford to overwrite them.
2236 * We would prefer to avoid this situation entirely. The situation does
2237 * not occur with NFS/UDP and is supposed to only occassionally occur
2238 * with TCP. Use vfs.nfs.realign_count and realign_test to check this.
2240 * NOTE! M_NOWAIT cannot be used here. The mbufs must be acquired
2241 * because the rpc request OR reply cannot be thrown away. TCP NFS
2242 * mounts do not retry their RPCs unless the TCP connection itself
2243 * is dropped so throwing away a RPC will basically cause the NFS
2244 * operation to lockup indefinitely.
2247 nfs_realign(struct mbuf **pm, int hsiz)
2250 struct mbuf *n = NULL;
2253 * Check for misalignemnt
2256 while ((m = *pm) != NULL) {
2257 if ((m->m_len & 0x3) || (mtod(m, intptr_t) & 0x3))
2263 * If misalignment found make a completely new copy.
2266 ++nfs_realign_count;
2267 n = m_dup_data(m, M_WAITOK);
2273 #ifndef NFS_NOSERVER
2276 * Parse an RPC request
2278 * - fill in the cred struct.
2281 nfs_getreq(struct nfsrv_descript *nd, struct nfsd *nfsd, int has_header)
2288 u_int32_t nfsvers, auth_type;
2290 int error = 0, ticklen;
2291 struct nfsuid *nuidp;
2292 struct timeval tvin, tvout;
2293 struct nfsm_info info;
2294 #if 0 /* until encrypted keys are implemented */
2295 NFSKERBKEYSCHED_T keys; /* stores key schedule */
2298 info.mrep = nd->nd_mrep;
2299 info.md = nd->nd_md;
2300 info.dpos = nd->nd_dpos;
2303 NULLOUT(tl = nfsm_dissect(&info, 10 * NFSX_UNSIGNED));
2304 nd->nd_retxid = fxdr_unsigned(u_int32_t, *tl++);
2305 if (*tl++ != rpc_call) {
2310 NULLOUT(tl = nfsm_dissect(&info, 8 * NFSX_UNSIGNED));
2314 if (*tl++ != rpc_vers) {
2315 nd->nd_repstat = ERPCMISMATCH;
2316 nd->nd_procnum = NFSPROC_NOOP;
2319 if (*tl != nfs_prog) {
2320 nd->nd_repstat = EPROGUNAVAIL;
2321 nd->nd_procnum = NFSPROC_NOOP;
2325 nfsvers = fxdr_unsigned(u_int32_t, *tl++);
2326 if (nfsvers < NFS_VER2 || nfsvers > NFS_VER3) {
2327 nd->nd_repstat = EPROGMISMATCH;
2328 nd->nd_procnum = NFSPROC_NOOP;
2331 if (nfsvers == NFS_VER3)
2332 nd->nd_flag = ND_NFSV3;
2333 nd->nd_procnum = fxdr_unsigned(u_int32_t, *tl++);
2334 if (nd->nd_procnum == NFSPROC_NULL)
2336 if (nd->nd_procnum >= NFS_NPROCS ||
2337 (nd->nd_procnum >= NQNFSPROC_GETLEASE) ||
2338 (!nd->nd_flag && nd->nd_procnum > NFSV2PROC_STATFS)) {
2339 nd->nd_repstat = EPROCUNAVAIL;
2340 nd->nd_procnum = NFSPROC_NOOP;
2343 if ((nd->nd_flag & ND_NFSV3) == 0)
2344 nd->nd_procnum = nfsv3_procid[nd->nd_procnum];
2346 len = fxdr_unsigned(int, *tl++);
2347 if (len < 0 || len > RPCAUTH_MAXSIZ) {
2352 nd->nd_flag &= ~ND_KERBAUTH;
2354 * Handle auth_unix or auth_kerb.
2356 if (auth_type == rpc_auth_unix) {
2357 len = fxdr_unsigned(int, *++tl);
2358 if (len < 0 || len > NFS_MAXNAMLEN) {
2362 ERROROUT(nfsm_adv(&info, nfsm_rndup(len)));
2363 NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2364 bzero((caddr_t)&nd->nd_cr, sizeof (struct ucred));
2365 nd->nd_cr.cr_ref = 1;
2366 nd->nd_cr.cr_uid = fxdr_unsigned(uid_t, *tl++);
2367 nd->nd_cr.cr_ruid = nd->nd_cr.cr_svuid = nd->nd_cr.cr_uid;
2368 nd->nd_cr.cr_gid = fxdr_unsigned(gid_t, *tl++);
2369 nd->nd_cr.cr_rgid = nd->nd_cr.cr_svgid = nd->nd_cr.cr_gid;
2370 len = fxdr_unsigned(int, *tl);
2371 if (len < 0 || len > RPCAUTH_UNIXGIDS) {
2375 NULLOUT(tl = nfsm_dissect(&info, (len + 2) * NFSX_UNSIGNED));
2376 for (i = 1; i <= len; i++)
2378 nd->nd_cr.cr_groups[i] = fxdr_unsigned(gid_t, *tl++);
2381 nd->nd_cr.cr_ngroups = (len >= NGROUPS) ? NGROUPS : (len + 1);
2382 if (nd->nd_cr.cr_ngroups > 1)
2383 nfsrvw_sort(nd->nd_cr.cr_groups, nd->nd_cr.cr_ngroups);
2384 len = fxdr_unsigned(int, *++tl);
2385 if (len < 0 || len > RPCAUTH_MAXSIZ) {
2390 ERROROUT(nfsm_adv(&info, nfsm_rndup(len)));
2392 } else if (auth_type == rpc_auth_kerb) {
2393 switch (fxdr_unsigned(int, *tl++)) {
2394 case RPCAKN_FULLNAME:
2395 ticklen = fxdr_unsigned(int, *tl);
2396 *((u_int32_t *)nfsd->nfsd_authstr) = *tl;
2397 uio.uio_resid = nfsm_rndup(ticklen) + NFSX_UNSIGNED;
2398 nfsd->nfsd_authlen = uio.uio_resid + NFSX_UNSIGNED;
2399 if (uio.uio_resid > (len - 2 * NFSX_UNSIGNED)) {
2406 uio.uio_segflg = UIO_SYSSPACE;
2407 iov.iov_base = (caddr_t)&nfsd->nfsd_authstr[4];
2408 iov.iov_len = RPCAUTH_MAXSIZ - 4;
2409 ERROROUT(nfsm_mtouio(&info, &uio, uio.uio_resid));
2410 NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED));
2411 if (*tl++ != rpc_auth_kerb ||
2412 fxdr_unsigned(int, *tl) != 4 * NFSX_UNSIGNED) {
2413 kprintf("Bad kerb verifier\n");
2414 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2415 nd->nd_procnum = NFSPROC_NOOP;
2418 NULLOUT(cp = nfsm_dissect(&info, 4 * NFSX_UNSIGNED));
2419 tl = (u_int32_t *)cp;
2420 if (fxdr_unsigned(int, *tl) != RPCAKN_FULLNAME) {
2421 kprintf("Not fullname kerb verifier\n");
2422 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2423 nd->nd_procnum = NFSPROC_NOOP;
2426 cp += NFSX_UNSIGNED;
2427 bcopy(cp, nfsd->nfsd_verfstr, 3 * NFSX_UNSIGNED);
2428 nfsd->nfsd_verflen = 3 * NFSX_UNSIGNED;
2429 nd->nd_flag |= ND_KERBFULL;
2430 nfsd->nfsd_flag |= NFSD_NEEDAUTH;
2432 case RPCAKN_NICKNAME:
2433 if (len != 2 * NFSX_UNSIGNED) {
2434 kprintf("Kerb nickname short\n");
2435 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADCRED);
2436 nd->nd_procnum = NFSPROC_NOOP;
2439 nickuid = fxdr_unsigned(uid_t, *tl);
2440 NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED));
2441 if (*tl++ != rpc_auth_kerb ||
2442 fxdr_unsigned(int, *tl) != 3 * NFSX_UNSIGNED) {
2443 kprintf("Kerb nick verifier bad\n");
2444 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2445 nd->nd_procnum = NFSPROC_NOOP;
2448 NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2449 tvin.tv_sec = *tl++;
2452 for (nuidp = NUIDHASH(nfsd->nfsd_slp,nickuid)->lh_first;
2453 nuidp != NULL; nuidp = nuidp->nu_hash.le_next) {
2454 if (nuidp->nu_cr.cr_uid == nickuid &&
2456 netaddr_match(AF_INET,
2457 &nuidp->nu_haddr, nd->nd_nam2)))
2462 (NFSERR_AUTHERR|AUTH_REJECTCRED);
2463 nd->nd_procnum = NFSPROC_NOOP;
2468 * Now, decrypt the timestamp using the session key
2478 tvout.tv_sec = fxdr_unsigned(long, tvout.tv_sec);
2479 tvout.tv_usec = fxdr_unsigned(long, tvout.tv_usec);
2480 if (nuidp->nu_expire != time_uptime ||
2481 nuidp->nu_timestamp.tv_sec > tvout.tv_sec ||
2482 (nuidp->nu_timestamp.tv_sec == tvout.tv_sec &&
2483 nuidp->nu_timestamp.tv_usec > tvout.tv_usec)) {
2484 nuidp->nu_expire = 0;
2486 (NFSERR_AUTHERR|AUTH_REJECTVERF);
2487 nd->nd_procnum = NFSPROC_NOOP;
2490 nfsrv_setcred(&nuidp->nu_cr, &nd->nd_cr);
2491 nd->nd_flag |= ND_KERBNICK;
2495 nd->nd_repstat = (NFSERR_AUTHERR | AUTH_REJECTCRED);
2496 nd->nd_procnum = NFSPROC_NOOP;
2500 nd->nd_md = info.md;
2501 nd->nd_dpos = info.dpos;
2510 * Send a message to the originating process's terminal. The thread and/or
2511 * process may be NULL. YYY the thread should not be NULL but there may
2512 * still be some uio_td's that are still being passed as NULL through to
2516 nfs_msg(struct thread *td, char *server, char *msg)
2520 if (td && td->td_proc)
2521 tpr = tprintf_open(td->td_proc);
2524 tprintf(tpr, "nfs server %s: %s\n", server, msg);
2529 #ifndef NFS_NOSERVER
2532 * Socket upcall routine for nfsd sockets. This runs in the protocol
2533 * thread and passes waitflag == M_NOWAIT.
2536 nfsrv_rcv_upcall(struct socket *so, void *arg, int waitflag)
2538 struct nfssvc_sock *slp = (struct nfssvc_sock *)arg;
2540 if (slp->ns_needq_upcall == 0) {
2541 slp->ns_needq_upcall = 1; /* ok to race */
2542 lwkt_gettoken(&nfs_token);
2543 nfsrv_wakenfsd(slp, 1);
2544 lwkt_reltoken(&nfs_token);
2547 lwkt_gettoken(&slp->ns_token);
2548 slp->ns_flag |= SLP_NEEDQ;
2549 nfsrv_rcv(so, arg, waitflag);
2550 lwkt_reltoken(&slp->ns_token);
2555 * Process new data on a receive socket. Essentially do as much as we can
2556 * non-blocking, else punt and it will be called with M_WAITOK from an nfsd.
2558 * slp->ns_token is held on call
2561 nfsrv_rcv(struct socket *so, void *arg, int waitflag)
2563 struct nfssvc_sock *slp = (struct nfssvc_sock *)arg;
2565 struct sockaddr *nam;
2568 int nparallel_wakeup = 0;
2570 ASSERT_LWKT_TOKEN_HELD(&slp->ns_token);
2572 if ((slp->ns_flag & SLP_VALID) == 0)
2576 * Do not allow an infinite number of completed RPC records to build
2577 * up before we stop reading data from the socket. Otherwise we could
2578 * end up holding onto an unreasonable number of mbufs for requests
2579 * waiting for service.
2581 * This should give pretty good feedback to the TCP layer and
2582 * prevents a memory crunch for other protocols.
2584 * Note that the same service socket can be dispatched to several
2585 * nfs servers simultaniously. The tcp protocol callback calls us
2586 * with M_NOWAIT. nfsd calls us with M_WAITOK (typically).
2588 if (NFSRV_RECLIMIT(slp))
2592 * Handle protocol specifics to parse an RPC request. We always
2593 * pull from the socket using non-blocking I/O.
2595 if (so->so_type == SOCK_STREAM) {
2597 * The data has to be read in an orderly fashion from a TCP
2598 * stream, unlike a UDP socket. It is possible for soreceive
2599 * and/or nfsrv_getstream() to block, so make sure only one
2600 * entity is messing around with the TCP stream at any given
2601 * moment. The receive sockbuf's lock in soreceive is not
2604 if (slp->ns_flag & SLP_GETSTREAM)
2606 slp->ns_flag |= SLP_GETSTREAM;
2609 * Do soreceive(). Pull out as much data as possible without
2612 sbinit(&sio, 1000000000);
2613 flags = MSG_DONTWAIT;
2614 error = so_pru_soreceive(so, NULL, NULL, &sio, NULL, &flags);
2615 if (error || sio.sb_mb == NULL) {
2616 if (error != EWOULDBLOCK)
2617 slp->ns_flag |= SLP_DISCONN;
2618 slp->ns_flag &= ~(SLP_GETSTREAM | SLP_NEEDQ);
2622 if (slp->ns_rawend) {
2623 slp->ns_rawend->m_next = m;
2624 slp->ns_cc += sio.sb_cc;
2627 slp->ns_cc = sio.sb_cc;
2634 * Now try and parse as many record(s) as we can out of the
2635 * raw stream data. This will set SLP_DOREC.
2637 error = nfsrv_getstream(slp, waitflag, &nparallel_wakeup);
2638 if (error && error != EWOULDBLOCK)
2639 slp->ns_flag |= SLP_DISCONN;
2640 slp->ns_flag &= ~SLP_GETSTREAM;
2643 * For UDP soreceive typically pulls just one packet, loop
2644 * to get the whole batch.
2647 sbinit(&sio, 1000000000);
2648 flags = MSG_DONTWAIT;
2649 error = so_pru_soreceive(so, &nam, NULL, &sio,
2652 struct nfsrv_rec *rec;
2653 int mf = (waitflag & M_NOWAIT) ?
2654 M_NOWAIT : M_WAITOK;
2655 rec = kmalloc(sizeof(struct nfsrv_rec),
2659 kfree(nam, M_SONAME);
2663 nfs_realign(&sio.sb_mb, 10 * NFSX_UNSIGNED);
2664 rec->nr_address = nam;
2665 rec->nr_packet = sio.sb_mb;
2666 STAILQ_INSERT_TAIL(&slp->ns_rec, rec, nr_link);
2668 slp->ns_flag |= SLP_DOREC;
2671 slp->ns_flag &= ~SLP_NEEDQ;
2674 if ((so->so_proto->pr_flags & PR_CONNREQUIRED)
2675 && error != EWOULDBLOCK) {
2676 slp->ns_flag |= SLP_DISCONN;
2680 if (NFSRV_RECLIMIT(slp))
2682 } while (sio.sb_mb);
2686 * If we were upcalled from the tcp protocol layer and we have
2687 * fully parsed records ready to go, or there is new data pending,
2688 * or something went wrong, try to wake up a nfsd thread to deal
2692 /* XXX this code is currently not executed (nfsrv_rcv_upcall) */
2693 if (waitflag == M_NOWAIT && (slp->ns_flag & SLP_ACTION_MASK)) {
2694 lwkt_gettoken(&nfs_token);
2695 nfsrv_wakenfsd(slp, nparallel_wakeup);
2696 lwkt_reltoken(&nfs_token);
2701 * Try and extract an RPC request from the mbuf data list received on a
2702 * stream socket. The "waitflag" argument indicates whether or not it
2706 nfsrv_getstream(struct nfssvc_sock *slp, int waitflag, int *countp)
2708 struct mbuf *m, **mpp;
2711 struct mbuf *om, *m2, *recm;
2715 if (slp->ns_reclen == 0) {
2716 if (slp->ns_cc < NFSX_UNSIGNED)
2719 if (m->m_len >= NFSX_UNSIGNED) {
2720 bcopy(mtod(m, caddr_t), (caddr_t)&recmark, NFSX_UNSIGNED);
2721 m->m_data += NFSX_UNSIGNED;
2722 m->m_len -= NFSX_UNSIGNED;
2724 cp1 = (caddr_t)&recmark;
2725 cp2 = mtod(m, caddr_t);
2726 while (cp1 < ((caddr_t)&recmark) + NFSX_UNSIGNED) {
2727 while (m->m_len == 0) {
2729 cp2 = mtod(m, caddr_t);
2736 slp->ns_cc -= NFSX_UNSIGNED;
2737 recmark = ntohl(recmark);
2738 slp->ns_reclen = recmark & ~0x80000000;
2739 if (recmark & 0x80000000)
2740 slp->ns_flag |= SLP_LASTFRAG;
2742 slp->ns_flag &= ~SLP_LASTFRAG;
2743 if (slp->ns_reclen > NFS_MAXPACKET || slp->ns_reclen <= 0) {
2744 log(LOG_ERR, "%s (%d) from nfs client\n",
2745 "impossible packet length",
2752 * Now get the record part.
2754 * Note that slp->ns_reclen may be 0. Linux sometimes
2755 * generates 0-length RPCs
2758 if (slp->ns_cc == slp->ns_reclen) {
2760 slp->ns_raw = slp->ns_rawend = NULL;
2761 slp->ns_cc = slp->ns_reclen = 0;
2762 } else if (slp->ns_cc > slp->ns_reclen) {
2767 while (len < slp->ns_reclen) {
2768 if ((len + m->m_len) > slp->ns_reclen) {
2769 m2 = m_copym(m, 0, slp->ns_reclen - len,
2777 m->m_data += slp->ns_reclen - len;
2778 m->m_len -= slp->ns_reclen - len;
2779 len = slp->ns_reclen;
2781 return (EWOULDBLOCK);
2783 } else if ((len + m->m_len) == slp->ns_reclen) {
2803 * Accumulate the fragments into a record.
2805 mpp = &slp->ns_frag;
2807 mpp = &((*mpp)->m_next);
2809 if (slp->ns_flag & SLP_LASTFRAG) {
2810 struct nfsrv_rec *rec;
2811 int mf = (waitflag & M_NOWAIT) ? M_NOWAIT : M_WAITOK;
2812 rec = kmalloc(sizeof(struct nfsrv_rec), M_NFSRVDESC, mf);
2814 m_freem(slp->ns_frag);
2816 nfs_realign(&slp->ns_frag, 10 * NFSX_UNSIGNED);
2817 rec->nr_address = NULL;
2818 rec->nr_packet = slp->ns_frag;
2819 STAILQ_INSERT_TAIL(&slp->ns_rec, rec, nr_link);
2821 slp->ns_flag |= SLP_DOREC;
2824 slp->ns_frag = NULL;
2832 * Sanity check our mbuf chain.
2835 nfs_checkpkt(struct mbuf *m, int len)
2843 panic("nfs_checkpkt: len mismatch %d/%d mbuf %p",
2851 nfs_checkpkt(struct mbuf *m __unused, int len __unused)
2858 * Parse an RPC header.
2860 * If the socket is invalid or no records are pending we return ENOBUFS.
2861 * The caller must deal with NEEDQ races.
2864 nfsrv_dorec(struct nfssvc_sock *slp, struct nfsd *nfsd,
2865 struct nfsrv_descript **ndp)
2867 struct nfsrv_rec *rec;
2869 struct sockaddr *nam;
2870 struct nfsrv_descript *nd;
2874 if ((slp->ns_flag & SLP_VALID) == 0 || !STAILQ_FIRST(&slp->ns_rec))
2876 rec = STAILQ_FIRST(&slp->ns_rec);
2877 STAILQ_REMOVE_HEAD(&slp->ns_rec, nr_link);
2878 KKASSERT(slp->ns_numrec > 0);
2879 if (--slp->ns_numrec == 0)
2880 slp->ns_flag &= ~SLP_DOREC;
2881 nam = rec->nr_address;
2883 kfree(rec, M_NFSRVDESC);
2884 nd = kmalloc(sizeof(struct nfsrv_descript), M_NFSRVDESC, M_WAITOK);
2885 nd->nd_md = nd->nd_mrep = m;
2887 nd->nd_dpos = mtod(m, caddr_t);
2888 error = nfs_getreq(nd, nfsd, TRUE);
2891 kfree(nam, M_SONAME);
2893 kfree((caddr_t)nd, M_NFSRVDESC);
2902 * Try to assign service sockets to nfsd threads based on the number
2903 * of new rpc requests that have been queued on the service socket.
2905 * If no nfsd's are available or additonal requests are pending, set the
2906 * NFSD_CHECKSLP flag so that one of the running nfsds will go look for
2907 * the work in the nfssvc_sock list when it is finished processing its
2908 * current work. This flag is only cleared when an nfsd can not find
2909 * any new work to perform.
2912 nfsrv_wakenfsd(struct nfssvc_sock *slp, int nparallel)
2916 if ((slp->ns_flag & SLP_VALID) == 0)
2920 TAILQ_FOREACH(nd, &nfsd_head, nfsd_chain) {
2921 if (nd->nfsd_flag & NFSD_WAITING) {
2922 nd->nfsd_flag &= ~NFSD_WAITING;
2924 panic("nfsd wakeup");
2927 wakeup((caddr_t)nd);
2928 if (--nparallel == 0)
2934 * If we couldn't assign slp then the NFSDs are all busy and
2935 * we set a flag indicating that there is pending work.
2938 nfsd_head_flag |= NFSD_CHECKSLP;
2940 #endif /* NFS_NOSERVER */