]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/nfsclient/nfs_socket.c
This commit was generated by cvs2svn to compensate for changes in r147078,
[FreeBSD/FreeBSD.git] / sys / nfsclient / nfs_socket.c
1 /*-
2  * Copyright (c) 1989, 1991, 1993, 1995
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Rick Macklem at The University of Guelph.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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  * 4. 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.
19  *
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
30  * SUCH DAMAGE.
31  *
32  *      @(#)nfs_socket.c        8.5 (Berkeley) 3/30/95
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 /*
39  * Socket operations for use by nfs
40  */
41
42 #include "opt_inet6.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/lock.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/mount.h>
51 #include <sys/mutex.h>
52 #include <sys/proc.h>
53 #include <sys/protosw.h>
54 #include <sys/signalvar.h>
55 #include <sys/syscallsubr.h>
56 #include <sys/socket.h>
57 #include <sys/socketvar.h>
58 #include <sys/sysctl.h>
59 #include <sys/syslog.h>
60 #include <sys/vnode.h>
61
62 #include <netinet/in.h>
63 #include <netinet/tcp.h>
64
65 #include <rpc/rpcclnt.h>
66
67 #include <nfs/rpcv2.h>
68 #include <nfs/nfsproto.h>
69 #include <nfsclient/nfs.h>
70 #include <nfs/xdr_subs.h>
71 #include <nfsclient/nfsm_subs.h>
72 #include <nfsclient/nfsmount.h>
73 #include <nfsclient/nfsnode.h>
74
75 #include <nfs4client/nfs4.h>
76
77 #define TRUE    1
78 #define FALSE   0
79
80 /*
81  * Estimate rto for an nfs rpc sent via. an unreliable datagram.
82  * Use the mean and mean deviation of rtt for the appropriate type of rpc
83  * for the frequent rpcs and a default for the others.
84  * The justification for doing "other" this way is that these rpcs
85  * happen so infrequently that timer est. would probably be stale.
86  * Also, since many of these rpcs are
87  * non-idempotent, a conservative timeout is desired.
88  * getattr, lookup - A+2D
89  * read, write     - A+4D
90  * other           - nm_timeo
91  */
92 #define NFS_RTO(n, t) \
93         ((t) == 0 ? (n)->nm_timeo : \
94          ((t) < 3 ? \
95           (((((n)->nm_srtt[t-1] + 3) >> 2) + (n)->nm_sdrtt[t-1] + 1) >> 1) : \
96           ((((n)->nm_srtt[t-1] + 7) >> 3) + (n)->nm_sdrtt[t-1] + 1)))
97 #define NFS_SRTT(r)     (r)->r_nmp->nm_srtt[proct[(r)->r_procnum] - 1]
98 #define NFS_SDRTT(r)    (r)->r_nmp->nm_sdrtt[proct[(r)->r_procnum] - 1]
99
100 /*
101  * Defines which timer to use for the procnum.
102  * 0 - default
103  * 1 - getattr
104  * 2 - lookup
105  * 3 - read
106  * 4 - write
107  */
108 static int proct[NFS_NPROCS] = {
109         0, 1, 0, 2, 1, 3, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0,
110 };
111
112 static int      nfs_realign_test;
113 static int      nfs_realign_count;
114 static int      nfs_bufpackets = 4;
115 static int      nfs_reconnects;
116
117 SYSCTL_DECL(_vfs_nfs);
118
119 SYSCTL_INT(_vfs_nfs, OID_AUTO, realign_test, CTLFLAG_RW, &nfs_realign_test, 0, "");
120 SYSCTL_INT(_vfs_nfs, OID_AUTO, realign_count, CTLFLAG_RW, &nfs_realign_count, 0, "");
121 SYSCTL_INT(_vfs_nfs, OID_AUTO, bufpackets, CTLFLAG_RW, &nfs_bufpackets, 0, "");
122 SYSCTL_INT(_vfs_nfs, OID_AUTO, reconnects, CTLFLAG_RD, &nfs_reconnects, 0,
123     "number of times the nfs client has had to reconnect");
124
125
126 /*
127  * There is a congestion window for outstanding rpcs maintained per mount
128  * point. The cwnd size is adjusted in roughly the way that:
129  * Van Jacobson, Congestion avoidance and Control, In "Proceedings of
130  * SIGCOMM '88". ACM, August 1988.
131  * describes for TCP. The cwnd size is chopped in half on a retransmit timeout
132  * and incremented by 1/cwnd when each rpc reply is received and a full cwnd
133  * of rpcs is in progress.
134  * (The sent count and cwnd are scaled for integer arith.)
135  * Variants of "slow start" were tried and were found to be too much of a
136  * performance hit (ave. rtt 3 times larger),
137  * I suspect due to the large rtt that nfs rpcs have.
138  */
139 #define NFS_CWNDSCALE   256
140 #define NFS_MAXCWND     (NFS_CWNDSCALE * 32)
141 #define NFS_NBACKOFF    8
142 static int nfs_backoff[NFS_NBACKOFF] = { 2, 4, 8, 16, 32, 64, 128, 256, };
143 struct callout  nfs_callout;
144
145 static int      nfs_msg(struct thread *, const char *, const char *, int);
146 static int      nfs_realign(struct mbuf **pm, int hsiz);
147 static int      nfs_reply(struct nfsreq *);
148 static void     nfs_softterm(struct nfsreq *rep);
149 static int      nfs_reconnect(struct nfsreq *rep);
150 static void nfs_clnt_tcp_soupcall(struct socket *so, void *arg, int waitflag);
151 static void nfs_clnt_udp_soupcall(struct socket *so, void *arg, int waitflag);
152 static void wakeup_nfsreq(struct nfsreq *req);
153
154 extern struct mtx nfs_reqq_mtx;
155 extern struct mtx nfs_reply_mtx;
156
157 /*
158  * Initialize sockets and congestion for a new NFS connection.
159  * We do not free the sockaddr if error.
160  */
161 int
162 nfs_connect(struct nfsmount *nmp, struct nfsreq *rep)
163 {
164         struct socket *so;
165         int error, rcvreserve, sndreserve;
166         int pktscale;
167         struct sockaddr *saddr;
168         struct thread *td = &thread0; /* only used for socreate and sobind */
169
170         NET_ASSERT_GIANT();
171
172         if (nmp->nm_sotype == SOCK_STREAM) {
173                 mtx_lock(&nmp->nm_nfstcpstate.mtx);
174                 nmp->nm_nfstcpstate.flags |= NFS_TCP_EXPECT_RPCMARKER;
175                 nmp->nm_nfstcpstate.rpcresid = 0;
176                 mtx_unlock(&nmp->nm_nfstcpstate.mtx);
177         }       
178         nmp->nm_so = NULL;
179         saddr = nmp->nm_nam;
180         error = socreate(saddr->sa_family, &nmp->nm_so, nmp->nm_sotype,
181                 nmp->nm_soproto, nmp->nm_mountp->mnt_cred, td);
182         if (error)
183                 goto bad;
184         so = nmp->nm_so;
185         nmp->nm_soflags = so->so_proto->pr_flags;
186
187         /*
188          * Some servers require that the client port be a reserved port number.
189          */
190         if (nmp->nm_flag & NFSMNT_RESVPORT) {
191                 struct sockopt sopt;
192                 int ip, ip2, len;
193                 struct sockaddr_in6 ssin;
194                 struct sockaddr *sa;
195
196                 bzero(&sopt, sizeof sopt);
197                 switch(saddr->sa_family) {
198                 case AF_INET:
199                         sopt.sopt_level = IPPROTO_IP;
200                         sopt.sopt_name = IP_PORTRANGE;
201                         ip = IP_PORTRANGE_LOW;
202                         ip2 = IP_PORTRANGE_DEFAULT;
203                         len = sizeof (struct sockaddr_in);
204                         break;
205 #ifdef INET6
206                 case AF_INET6:
207                         sopt.sopt_level = IPPROTO_IPV6;
208                         sopt.sopt_name = IPV6_PORTRANGE;
209                         ip = IPV6_PORTRANGE_LOW;
210                         ip2 = IPV6_PORTRANGE_DEFAULT;
211                         len = sizeof (struct sockaddr_in6);
212                         break;
213 #endif
214                 default:
215                         goto noresvport;
216                 }
217                 sa = (struct sockaddr *)&ssin;
218                 bzero(sa, len);
219                 sa->sa_len = len;
220                 sa->sa_family = saddr->sa_family;
221                 sopt.sopt_dir = SOPT_SET;
222                 sopt.sopt_val = (void *)&ip;
223                 sopt.sopt_valsize = sizeof(ip);
224                 error = sosetopt(so, &sopt);
225                 if (error)
226                         goto bad;
227                 error = sobind(so, sa, td);
228                 if (error)
229                         goto bad;
230                 ip = ip2;
231                 error = sosetopt(so, &sopt);
232                 if (error)
233                         goto bad;
234         noresvport: ;
235         }
236
237         /*
238          * Protocols that do not require connections may be optionally left
239          * unconnected for servers that reply from a port other than NFS_PORT.
240          */
241         if (nmp->nm_flag & NFSMNT_NOCONN) {
242                 if (nmp->nm_soflags & PR_CONNREQUIRED) {
243                         error = ENOTCONN;
244                         goto bad;
245                 }
246         } else {
247                 error = soconnect(so, nmp->nm_nam, td);
248                 if (error)
249                         goto bad;
250
251                 /*
252                  * Wait for the connection to complete. Cribbed from the
253                  * connect system call but with the wait timing out so
254                  * that interruptible mounts don't hang here for a long time.
255                  */
256                 SOCK_LOCK(so);
257                 while ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
258                         (void) msleep(&so->so_timeo, SOCK_MTX(so),
259                             PSOCK, "nfscon", 2 * hz);
260                         if ((so->so_state & SS_ISCONNECTING) &&
261                             so->so_error == 0 && rep &&
262                             (error = nfs_sigintr(nmp, rep, rep->r_td)) != 0) {
263                                 so->so_state &= ~SS_ISCONNECTING;
264                                 SOCK_UNLOCK(so);
265                                 goto bad;
266                         }
267                 }
268                 if (so->so_error) {
269                         error = so->so_error;
270                         so->so_error = 0;
271                         SOCK_UNLOCK(so);
272                         goto bad;
273                 }
274                 SOCK_UNLOCK(so);
275         }
276         so->so_rcv.sb_timeo = 12 * hz;
277         so->so_snd.sb_timeo = 5 * hz;
278
279         /*
280          * Get buffer reservation size from sysctl, but impose reasonable
281          * limits.
282          */
283         pktscale = nfs_bufpackets;
284         if (pktscale < 2)
285                 pktscale = 2;
286         if (pktscale > 64)
287                 pktscale = 64;
288
289         if (nmp->nm_sotype == SOCK_DGRAM) {
290                 sndreserve = (nmp->nm_wsize + NFS_MAXPKTHDR) * pktscale;
291                 rcvreserve = (max(nmp->nm_rsize, nmp->nm_readdirsize) +
292                     NFS_MAXPKTHDR) * pktscale;
293         } else if (nmp->nm_sotype == SOCK_SEQPACKET) {
294                 sndreserve = (nmp->nm_wsize + NFS_MAXPKTHDR) * pktscale;
295                 rcvreserve = (max(nmp->nm_rsize, nmp->nm_readdirsize) +
296                     NFS_MAXPKTHDR) * pktscale;
297         } else {
298                 if (nmp->nm_sotype != SOCK_STREAM)
299                         panic("nfscon sotype");
300                 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
301                         struct sockopt sopt;
302                         int val;
303
304                         bzero(&sopt, sizeof sopt);
305                         sopt.sopt_dir = SOPT_SET;
306                         sopt.sopt_level = SOL_SOCKET;
307                         sopt.sopt_name = SO_KEEPALIVE;
308                         sopt.sopt_val = &val;
309                         sopt.sopt_valsize = sizeof val;
310                         val = 1;
311                         sosetopt(so, &sopt);
312                 }
313                 if (so->so_proto->pr_protocol == IPPROTO_TCP) {
314                         struct sockopt sopt;
315                         int val;
316
317                         bzero(&sopt, sizeof sopt);
318                         sopt.sopt_dir = SOPT_SET;
319                         sopt.sopt_level = IPPROTO_TCP;
320                         sopt.sopt_name = TCP_NODELAY;
321                         sopt.sopt_val = &val;
322                         sopt.sopt_valsize = sizeof val;
323                         val = 1;
324                         sosetopt(so, &sopt);
325                 }
326                 sndreserve = (nmp->nm_wsize + NFS_MAXPKTHDR +
327                     sizeof (u_int32_t)) * pktscale;
328                 rcvreserve = (nmp->nm_rsize + NFS_MAXPKTHDR +
329                     sizeof (u_int32_t)) * pktscale;
330         }
331         error = soreserve(so, sndreserve, rcvreserve);
332         if (error)
333                 goto bad;
334         SOCKBUF_LOCK(&so->so_rcv);
335         so->so_rcv.sb_flags |= SB_NOINTR;
336         so->so_upcallarg = (caddr_t)nmp;
337         if (so->so_type == SOCK_STREAM)
338                 so->so_upcall = nfs_clnt_tcp_soupcall;
339         else    
340                 so->so_upcall = nfs_clnt_udp_soupcall;
341         so->so_rcv.sb_flags |= SB_UPCALL;
342         SOCKBUF_UNLOCK(&so->so_rcv);
343         SOCKBUF_LOCK(&so->so_snd);
344         so->so_snd.sb_flags |= SB_NOINTR;
345         SOCKBUF_UNLOCK(&so->so_snd);
346
347         /* Initialize other non-zero congestion variables */
348         nmp->nm_srtt[0] = nmp->nm_srtt[1] = nmp->nm_srtt[2] =
349                 nmp->nm_srtt[3] = (NFS_TIMEO << 3);
350         nmp->nm_sdrtt[0] = nmp->nm_sdrtt[1] = nmp->nm_sdrtt[2] =
351                 nmp->nm_sdrtt[3] = 0;
352         nmp->nm_cwnd = NFS_MAXCWND / 2;     /* Initial send window */
353         nmp->nm_sent = 0;
354         nmp->nm_timeouts = 0;
355         return (0);
356
357 bad:
358         nfs_disconnect(nmp);
359         return (error);
360 }
361
362 /*
363  * Reconnect routine:
364  * Called when a connection is broken on a reliable protocol.
365  * - clean up the old socket
366  * - nfs_connect() again
367  * - set R_MUSTRESEND for all outstanding requests on mount point
368  * If this fails the mount point is DEAD!
369  * nb: Must be called with the nfs_sndlock() set on the mount point.
370  */
371 static int
372 nfs_reconnect(struct nfsreq *rep)
373 {
374         struct nfsreq *rp;
375         struct nfsmount *nmp = rep->r_nmp;
376         int error;
377
378         nfs_reconnects++;
379         nfs_disconnect(nmp);
380         while ((error = nfs_connect(nmp, rep)) != 0) {
381                 if (error == ERESTART)
382                         error = EINTR;
383                 if (error == EIO || error == EINTR)
384                         return (error);
385                 (void) tsleep(&lbolt, PSOCK, "nfscon", 0);
386         }
387
388         /*
389          * Clear the FORCE_RECONNECT flag only after the connect 
390          * succeeds. To prevent races between multiple processes 
391          * waiting on the mountpoint where the connection is being
392          * torn down. The first one to acquire the sndlock will 
393          * retry the connection. The others block on the sndlock
394          * until the connection is established successfully, and 
395          * then re-transmit the request.
396          */
397         mtx_lock(&nmp->nm_nfstcpstate.mtx);
398         nmp->nm_nfstcpstate.flags &= ~NFS_TCP_FORCE_RECONNECT;
399         mtx_unlock(&nmp->nm_nfstcpstate.mtx);   
400
401         /*
402          * Loop through outstanding request list and fix up all requests
403          * on old socket.
404          */
405         mtx_lock(&nfs_reqq_mtx);
406         TAILQ_FOREACH(rp, &nfs_reqq, r_chain) {
407                 if (rp->r_nmp == nmp)
408                         rp->r_flags |= R_MUSTRESEND;
409         }
410         mtx_unlock(&nfs_reqq_mtx);
411         return (0);
412 }
413
414 /*
415  * NFS disconnect. Clean up and unlink.
416  */
417 void
418 nfs_disconnect(struct nfsmount *nmp)
419 {
420         struct socket *so;
421
422         NET_ASSERT_GIANT();
423
424         if (nmp->nm_so) {
425                 so = nmp->nm_so;
426                 nmp->nm_so = NULL;
427                 SOCKBUF_LOCK(&so->so_rcv);
428                 so->so_upcallarg = NULL;
429                 so->so_upcall = NULL;
430                 so->so_rcv.sb_flags &= ~SB_UPCALL;
431                 SOCKBUF_UNLOCK(&so->so_rcv);
432                 soshutdown(so, SHUT_WR);
433                 soclose(so);
434         }
435 }
436
437 void
438 nfs_safedisconnect(struct nfsmount *nmp)
439 {
440         struct nfsreq dummyreq;
441
442         bzero(&dummyreq, sizeof(dummyreq));
443         dummyreq.r_nmp = nmp;
444         nfs_disconnect(nmp);
445 }
446
447 /*
448  * This is the nfs send routine. For connection based socket types, it
449  * must be called with an nfs_sndlock() on the socket.
450  * - return EINTR if the RPC is terminated, 0 otherwise
451  * - set R_MUSTRESEND if the send fails for any reason
452  * - do any cleanup required by recoverable socket errors (?)
453  */
454 int
455 nfs_send(struct socket *so, struct sockaddr *nam, struct mbuf *top,
456     struct nfsreq *rep)
457 {
458         struct sockaddr *sendnam;
459         int error, error2, soflags, flags;
460
461         NET_ASSERT_GIANT();
462
463         KASSERT(rep, ("nfs_send: called with rep == NULL"));
464
465         error = nfs_sigintr(rep->r_nmp, rep, rep->r_td);
466         if (error) {
467                 m_freem(top);
468                 return (error);
469         }
470         if ((so = rep->r_nmp->nm_so) == NULL) {
471                 rep->r_flags |= R_MUSTRESEND;
472                 m_freem(top);
473                 return (0);
474         }
475         rep->r_flags &= ~R_MUSTRESEND;
476         soflags = rep->r_nmp->nm_soflags;
477
478         if ((soflags & PR_CONNREQUIRED) || (so->so_state & SS_ISCONNECTED))
479                 sendnam = NULL;
480         else
481                 sendnam = nam;
482         if (so->so_type == SOCK_SEQPACKET)
483                 flags = MSG_EOR;
484         else
485                 flags = 0;
486
487         error = so->so_proto->pr_usrreqs->pru_sosend(so, sendnam, 0, top, 0,
488                                                      flags, curthread /*XXX*/);
489         if (error == ENOBUFS && so->so_type == SOCK_DGRAM) {
490                 error = 0;
491                 rep->r_flags |= R_MUSTRESEND;
492         }
493
494         if (error) {
495                 /*
496                  * Don't report EPIPE errors on nfs sockets.
497                  * These can be due to idle tcp mounts which will be closed by
498                  * netapp, solaris, etc. if left idle too long.
499                  */
500                 if (error != EPIPE) {
501                         log(LOG_INFO, "nfs send error %d for server %s\n",
502                             error,
503                             rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
504                 }
505                 /*
506                  * Deal with errors for the client side.
507                  */
508                 error2 = NFS_SIGREP(rep);
509                 if (error2)
510                         error = error2;
511                 else
512                         rep->r_flags |= R_MUSTRESEND;
513
514                 /*
515                  * Handle any recoverable (soft) socket errors here. (?)
516                  */
517                 if (error != EINTR && error != ERESTART && error != EIO &&
518                         error != EWOULDBLOCK && error != EPIPE)
519                         error = 0;
520         }
521         return (error);
522 }
523
524 int
525 nfs_reply(struct nfsreq *rep)
526 {
527         register struct socket *so;
528         register struct mbuf *m;
529         int error = 0, sotype, slpflag;
530
531         NET_ASSERT_GIANT();
532
533         sotype = rep->r_nmp->nm_sotype;
534         /*
535          * For reliable protocols, lock against other senders/receivers
536          * in case a reconnect is necessary.
537          */
538         if (sotype != SOCK_DGRAM) {
539                 error = nfs_sndlock(rep);
540                 if (error)
541                         return (error);
542 tryagain:
543                 if (rep->r_mrep) {
544                         nfs_sndunlock(rep);
545                         return (0);
546                 }
547                 if (rep->r_flags & R_SOFTTERM) {
548                         nfs_sndunlock(rep);
549                         return (EINTR);
550                 }
551                 so = rep->r_nmp->nm_so;
552                 mtx_lock(&rep->r_nmp->nm_nfstcpstate.mtx);
553                 if (!so || 
554                     (rep->r_nmp->nm_nfstcpstate.flags & NFS_TCP_FORCE_RECONNECT)) {
555                         mtx_unlock(&rep->r_nmp->nm_nfstcpstate.mtx);
556                         error = nfs_reconnect(rep);
557                         if (error) {
558                                 nfs_sndunlock(rep);
559                                 return (error);
560                         }
561                         goto tryagain;
562                 } else
563                         mtx_unlock(&rep->r_nmp->nm_nfstcpstate.mtx);
564                 while (rep->r_flags & R_MUSTRESEND) {
565                         m = m_copym(rep->r_mreq, 0, M_COPYALL, M_WAIT);
566                         nfsstats.rpcretries++;
567                         error = nfs_send(so, rep->r_nmp->nm_nam, m, rep);
568                         if (error) {
569                                 if (error == EINTR || error == ERESTART ||
570                                     (error = nfs_reconnect(rep)) != 0) {
571                                         nfs_sndunlock(rep);
572                                         return (error);
573                                 }
574                                 goto tryagain;
575                         }
576                 }
577                 nfs_sndunlock(rep);
578         }
579         slpflag = 0;
580         if (rep->r_nmp->nm_flag & NFSMNT_INT)
581                 slpflag = PCATCH;
582         mtx_lock(&nfs_reply_mtx);
583         while ((rep->r_mrep == NULL) && (error == 0) &&
584                ((sotype == SOCK_DGRAM) || ((rep->r_flags & R_MUSTRESEND) == 0)))
585                 error = msleep((caddr_t)rep, &nfs_reply_mtx, 
586                                slpflag | (PZERO - 1), "nfsreq", 0);
587         mtx_unlock(&nfs_reply_mtx);
588         if (error == EINTR || error == ERESTART)
589                 /* NFS operations aren't restartable. Map ERESTART to EINTR */
590                 return (EINTR);
591         if (rep->r_flags & R_SOFTTERM)
592                 /* Request was terminated because we exceeded the retries (soft mount) */
593                 return (ETIMEDOUT);
594         if (sotype == SOCK_STREAM) {
595                 mtx_lock(&rep->r_nmp->nm_nfstcpstate.mtx);
596                 if (((rep->r_nmp->nm_nfstcpstate.flags & NFS_TCP_FORCE_RECONNECT) || 
597                      (rep->r_flags & R_MUSTRESEND))) {
598                         mtx_unlock(&rep->r_nmp->nm_nfstcpstate.mtx);    
599                         error = nfs_sndlock(rep);
600                         if (error)
601                                 return (error);
602                         goto tryagain;
603                 } else
604                         mtx_unlock(&rep->r_nmp->nm_nfstcpstate.mtx);
605         }
606         return (error);
607 }
608
609 /*
610  * XXX TO DO
611  * Make nfs_realign() non-blocking. Also make nfsm_dissect() nonblocking.
612  */
613 static void
614 nfs_clnt_match_xid(struct socket *so, 
615                    struct nfsmount *nmp, 
616                    struct mbuf *mrep)
617 {
618         struct mbuf *md;
619         caddr_t dpos;
620         u_int32_t rxid, *tl;
621         struct nfsreq *rep;
622         register int32_t t1;
623         int error;
624         
625         /*
626          * Search for any mbufs that are not a multiple of 4 bytes long
627          * or with m_data not longword aligned.
628          * These could cause pointer alignment problems, so copy them to
629          * well aligned mbufs.
630          */
631         if (nfs_realign(&mrep, 5 * NFSX_UNSIGNED) == ENOMEM) {
632                 m_freem(mrep);
633                 nfsstats.rpcinvalid++;
634                 return;
635         }
636         
637         /*
638          * Get the xid and check that it is an rpc reply
639          */
640         md = mrep;
641         dpos = mtod(md, caddr_t);
642         tl = nfsm_dissect_nonblock(u_int32_t *, 2*NFSX_UNSIGNED);
643         rxid = *tl++;
644         if (*tl != rpc_reply) {
645                 m_freem(mrep);
646 nfsmout:
647                 nfsstats.rpcinvalid++;
648                 return;
649         }
650
651         mtx_lock(&nfs_reqq_mtx);
652         /*
653          * Loop through the request list to match up the reply
654          * Iff no match, just drop the datagram
655          */
656         TAILQ_FOREACH(rep, &nfs_reqq, r_chain) {
657                 if (rep->r_mrep == NULL && rxid == rep->r_xid) {
658                         /* Found it.. */
659                         rep->r_mrep = mrep;
660                         rep->r_md = md;
661                         rep->r_dpos = dpos;
662                         /*
663                          * Update congestion window.
664                          * Do the additive increase of
665                          * one rpc/rtt.
666                          */
667                         if (nmp->nm_cwnd <= nmp->nm_sent) {
668                                 nmp->nm_cwnd +=
669                                         (NFS_CWNDSCALE * NFS_CWNDSCALE +
670                                          (nmp->nm_cwnd >> 1)) / nmp->nm_cwnd;
671                                 if (nmp->nm_cwnd > NFS_MAXCWND)
672                                         nmp->nm_cwnd = NFS_MAXCWND;
673                         }       
674                         if (rep->r_flags & R_SENT) {
675                                 rep->r_flags &= ~R_SENT;
676                                 nmp->nm_sent -= NFS_CWNDSCALE;
677                         }
678                         /*
679                          * Update rtt using a gain of 0.125 on the mean
680                          * and a gain of 0.25 on the deviation.
681                          */
682                         if (rep->r_flags & R_TIMING) {
683                                 /*
684                                  * Since the timer resolution of
685                                  * NFS_HZ is so course, it can often
686                                  * result in r_rtt == 0. Since
687                                  * r_rtt == N means that the actual
688                                  * rtt is between N+dt and N+2-dt ticks,
689                                  * add 1.
690                                  */
691                                 t1 = rep->r_rtt + 1;
692                                 t1 -= (NFS_SRTT(rep) >> 3);
693                                 NFS_SRTT(rep) += t1;
694                                 if (t1 < 0)
695                                         t1 = -t1;
696                                 t1 -= (NFS_SDRTT(rep) >> 2);
697                                 NFS_SDRTT(rep) += t1;
698                         }
699                         nmp->nm_timeouts = 0;
700                         break;
701                 }
702         }
703         /*
704          * If not matched to a request, drop it.
705          * If it's mine, wake up requestor.
706          */
707         if (rep == 0) {
708                 nfsstats.rpcunexpected++;
709                 m_freem(mrep);
710         } else
711                 wakeup_nfsreq(rep);
712         mtx_unlock(&nfs_reqq_mtx);
713 }
714
715 /* 
716  * The wakeup of the requestor should be done under the mutex
717  * to avoid potential missed wakeups.
718  */
719 static void 
720 wakeup_nfsreq(struct nfsreq *req)
721 {
722         mtx_lock(&nfs_reply_mtx);
723         wakeup((caddr_t)req);
724         mtx_unlock(&nfs_reply_mtx);     
725 }
726
727 static void
728 nfs_mark_for_reconnect(struct nfsmount *nmp)
729 {
730         struct nfsreq *rp;
731
732         mtx_lock(&nmp->nm_nfstcpstate.mtx);
733         nmp->nm_nfstcpstate.flags |= NFS_TCP_FORCE_RECONNECT;
734         mtx_unlock(&nmp->nm_nfstcpstate.mtx);
735         /* 
736          * Wakeup all processes that are waiting for replies 
737          * on this mount point. One of them does the reconnect.
738          */
739         mtx_lock(&nfs_reqq_mtx);
740         TAILQ_FOREACH(rp, &nfs_reqq, r_chain) {
741                 if (rp->r_nmp == nmp) {
742                         rp->r_flags |= R_MUSTRESEND;
743                         wakeup_nfsreq(rp);
744                 }
745         }
746         mtx_unlock(&nfs_reqq_mtx);
747 }
748
749 static int
750 nfstcp_readable(struct socket *so, int bytes)
751 {
752         int retval;
753         
754         SOCKBUF_LOCK(&so->so_rcv);
755         retval = (so->so_rcv.sb_cc >= (bytes) ||
756                   (so->so_state & SBS_CANTRCVMORE) ||
757                   so->so_error);
758         SOCKBUF_UNLOCK(&so->so_rcv);
759         return (retval);
760 }
761
762 #define nfstcp_marker_readable(so)      nfstcp_readable(so, sizeof(u_int32_t))
763
764 static void
765 nfs_clnt_tcp_soupcall(struct socket *so, void *arg, int waitflag)
766 {
767         struct nfsmount *nmp = (struct nfsmount *)arg;
768         struct mbuf *mp = NULL;
769         struct uio auio;
770         int error;
771         u_int32_t len;
772         int rcvflg;
773
774         /*
775          * Don't pick any more data from the socket if we've marked the 
776          * mountpoint for reconnect.
777          */
778         mtx_lock(&nmp->nm_nfstcpstate.mtx);
779         if (nmp->nm_nfstcpstate.flags & NFS_TCP_FORCE_RECONNECT) {
780                 mtx_unlock(&nmp->nm_nfstcpstate.mtx);           
781                 return;
782         } else                  
783                 mtx_unlock(&nmp->nm_nfstcpstate.mtx);
784         auio.uio_td = curthread;
785         auio.uio_segflg = UIO_SYSSPACE;
786         auio.uio_rw = UIO_READ;
787         for ( ; ; ) {
788                 if (nmp->nm_nfstcpstate.flags & NFS_TCP_EXPECT_RPCMARKER) {
789                         if (!nfstcp_marker_readable(so)) {
790                                 /* Marker is not readable */
791                                 return;
792                         }
793                         auio.uio_resid = sizeof(u_int32_t);
794                         auio.uio_iov = NULL;
795                         auio.uio_iovcnt = 0;
796                         mp = NULL;
797                         rcvflg = (MSG_DONTWAIT | MSG_SOCALLBCK);
798                         error =  so->so_proto->pr_usrreqs->pru_soreceive
799                                 (so, (struct sockaddr **)0,
800                                  &auio, &mp, (struct mbuf **)0, &rcvflg);
801                         /*
802                          * We've already tested that the socket is readable. 2 cases 
803                          * here, we either read 0 bytes (client closed connection), 
804                          * or got some other error. In both cases, we tear down the 
805                          * connection.
806                          */
807                         if (error || auio.uio_resid > 0) {
808                                 if (error != ECONNRESET) {
809                                         log(LOG_ERR, 
810                                             "nfs/tcp clnt: Error %d reading socket, tearing down TCP connection\n",
811                                             error);
812                                 }
813                                 goto mark_reconnect;
814                         }
815                         if (mp == NULL)
816                                 panic("nfs_clnt_tcp_soupcall: Got empty mbuf chain from sorecv\n");
817                         len = ntohl(*mtod(mp, u_int32_t *)) & ~0x80000000;
818                         m_freem(mp);
819                         /*
820                          * This is SERIOUS! We are out of sync with the sender
821                          * and forcing a disconnect/reconnect is all I can do.
822                          */
823                         if (len > NFS_MAXPACKET || len == 0) {
824                                 log(LOG_ERR, "%s (%d) from nfs server %s\n",
825                                     "impossible packet length",
826                                     len,
827                                     nmp->nm_mountp->mnt_stat.f_mntfromname);
828                                 goto mark_reconnect;
829                         }
830                         nmp->nm_nfstcpstate.rpcresid = len;
831                         nmp->nm_nfstcpstate.flags &= ~(NFS_TCP_EXPECT_RPCMARKER);
832                 }
833                 /* 
834                  * Processed RPC marker or no RPC marker to process. 
835                  * Pull in and process data.
836                  */
837                 if (nmp->nm_nfstcpstate.rpcresid > 0) {
838                         if (!nfstcp_readable(so, nmp->nm_nfstcpstate.rpcresid)) {
839                                 /* All data not readable */
840                                 return;
841                         }
842                         auio.uio_resid = nmp->nm_nfstcpstate.rpcresid;
843                         auio.uio_iov = NULL;
844                         auio.uio_iovcnt = 0;
845                         mp = NULL;
846                         rcvflg = (MSG_DONTWAIT | MSG_SOCALLBCK);
847                         error =  so->so_proto->pr_usrreqs->pru_soreceive
848                                 (so, (struct sockaddr **)0,
849                                  &auio, &mp, (struct mbuf **)0, &rcvflg);
850                         if (error || auio.uio_resid > 0) {
851                                 if (error != ECONNRESET) {
852                                         log(LOG_ERR, 
853                                             "nfs/tcp clnt: Error %d reading socket, tearing down TCP connection\n",
854                                             error);
855                                 }
856                                 goto mark_reconnect;                            
857                         }
858                         if (mp == NULL)
859                                 panic("nfs_clnt_tcp_soupcall: Got empty mbuf chain from sorecv\n");
860                         nmp->nm_nfstcpstate.rpcresid = 0;
861                         nmp->nm_nfstcpstate.flags |= NFS_TCP_EXPECT_RPCMARKER;
862                         /* We got the entire RPC reply. Match XIDs and wake up requestor */
863                         nfs_clnt_match_xid(so, nmp, mp);
864                 }
865         }
866
867 mark_reconnect:
868         nfs_mark_for_reconnect(nmp);
869 }
870
871 static void
872 nfs_clnt_udp_soupcall(struct socket *so, void *arg, int waitflag)
873 {
874         struct nfsmount *nmp = (struct nfsmount *)arg;
875         struct uio auio;
876         struct mbuf *mp = NULL;
877         struct mbuf *control = NULL;
878         int error, rcvflag;
879
880         auio.uio_resid = 1000000;
881         auio.uio_td = curthread;
882         rcvflag = MSG_DONTWAIT;
883         auio.uio_resid = 1000000000;
884         do {
885                 mp = control = NULL;
886                 error = so->so_proto->pr_usrreqs->pru_soreceive(so,
887                                         NULL, &auio, &mp,
888                                         &control, &rcvflag);
889                 if (control)
890                         m_freem(control);
891                 if (mp)
892                         nfs_clnt_match_xid(so, nmp, mp);
893         } while (mp && !error);
894 }
895
896 /*
897  * nfs_request - goes something like this
898  *      - fill in request struct
899  *      - links it into list
900  *      - calls nfs_send() for first transmit
901  *      - calls nfs_receive() to get reply
902  *      - break down rpc header and return with nfs reply pointed to
903  *        by mrep or error
904  * nb: always frees up mreq mbuf list
905  */
906 /* XXX overloaded before */
907 #define NQ_TRYLATERDEL  15      /* Initial try later delay (sec) */
908
909 int
910 nfs_request(struct vnode *vp, struct mbuf *mrest, int procnum,
911     struct thread *td, struct ucred *cred, struct mbuf **mrp,
912     struct mbuf **mdp, caddr_t *dposp)
913 {
914         struct mbuf *mrep, *m2;
915         struct nfsreq *rep;
916         u_int32_t *tl;
917         int i;
918         struct nfsmount *nmp;
919         struct mbuf *m, *md, *mheadend;
920         time_t waituntil;
921         caddr_t dpos;
922         int s, error = 0, mrest_len, auth_len, auth_type;
923         int trylater_delay = NQ_TRYLATERDEL, trylater_cnt = 0;
924         struct timeval now;
925         u_int32_t xid;
926
927         /* Reject requests while attempting a forced unmount. */
928         if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF) {
929                 m_freem(mrest);
930                 return (ESTALE);
931         }
932         nmp = VFSTONFS(vp->v_mount);
933         if ((nmp->nm_flag & NFSMNT_NFSV4) != 0)
934                 return nfs4_request(vp, mrest, procnum, td, cred, mrp, mdp, dposp);
935         MALLOC(rep, struct nfsreq *, sizeof(struct nfsreq), M_NFSREQ, M_WAITOK);
936         rep->r_mrep = rep->r_md = NULL;
937         rep->r_nmp = nmp;
938         rep->r_vp = vp;
939         rep->r_td = td;
940         rep->r_procnum = procnum;
941
942         getmicrouptime(&now);
943         rep->r_lastmsg = now.tv_sec -
944             ((nmp->nm_tprintf_delay) - (nmp->nm_tprintf_initial_delay));
945         mrest_len = m_length(mrest, NULL);
946
947         /*
948          * Get the RPC header with authorization.
949          */
950         auth_type = RPCAUTH_UNIX;
951         if (cred->cr_ngroups < 1)
952                 panic("nfsreq nogrps");
953         auth_len = ((((cred->cr_ngroups - 1) > nmp->nm_numgrps) ?
954                 nmp->nm_numgrps : (cred->cr_ngroups - 1)) << 2) +
955                 5 * NFSX_UNSIGNED;
956         m = nfsm_rpchead(cred, nmp->nm_flag, procnum, auth_type, auth_len,
957              mrest, mrest_len, &mheadend, &xid);
958
959         /*
960          * For stream protocols, insert a Sun RPC Record Mark.
961          */
962         if (nmp->nm_sotype == SOCK_STREAM) {
963                 M_PREPEND(m, NFSX_UNSIGNED, M_TRYWAIT);
964                 *mtod(m, u_int32_t *) = htonl(0x80000000 |
965                          (m->m_pkthdr.len - NFSX_UNSIGNED));
966         }
967         rep->r_mreq = m;
968         rep->r_xid = xid;
969 tryagain:
970         if (nmp->nm_flag & NFSMNT_SOFT)
971                 rep->r_retry = nmp->nm_retry;
972         else
973                 rep->r_retry = NFS_MAXREXMIT + 1;       /* past clip limit */
974         rep->r_rtt = rep->r_rexmit = 0;
975         if (proct[procnum] > 0)
976                 rep->r_flags = R_TIMING;
977         else
978                 rep->r_flags = 0;
979         rep->r_mrep = NULL;
980
981         /*
982          * Do the client side RPC.
983          */
984         nfsstats.rpcrequests++;
985         /*
986          * Chain request into list of outstanding requests. Be sure
987          * to put it LAST so timer finds oldest requests first.
988          */
989         s = splsoftclock();
990         mtx_lock(&nfs_reqq_mtx);
991         if (TAILQ_EMPTY(&nfs_reqq))
992                 callout_reset(&nfs_callout, nfs_ticks, nfs_timer, NULL);
993         TAILQ_INSERT_TAIL(&nfs_reqq, rep, r_chain);
994         mtx_unlock(&nfs_reqq_mtx);
995
996         /*
997          * If backing off another request or avoiding congestion, don't
998          * send this one now but let timer do it. If not timing a request,
999          * do it now.
1000          */
1001         if (nmp->nm_so && (nmp->nm_sotype != SOCK_DGRAM ||
1002                 (nmp->nm_flag & NFSMNT_DUMBTIMR) ||
1003                 nmp->nm_sent < nmp->nm_cwnd)) {
1004                 splx(s);
1005                 error = nfs_sndlock(rep);
1006                 if (!error) {
1007                         m2 = m_copym(m, 0, M_COPYALL, M_TRYWAIT);
1008                         error = nfs_send(nmp->nm_so, nmp->nm_nam, m2, rep);
1009                         nfs_sndunlock(rep);
1010                 }
1011                 mtx_lock(&nfs_reqq_mtx);
1012                 if (!error && (rep->r_flags & R_MUSTRESEND) == 0) {
1013                         nmp->nm_sent += NFS_CWNDSCALE;
1014                         rep->r_flags |= R_SENT;
1015                 }
1016                 mtx_unlock(&nfs_reqq_mtx);
1017         } else {
1018                 splx(s);
1019                 rep->r_rtt = -1;
1020         }
1021
1022         /*
1023          * Wait for the reply from our send or the timer's.
1024          */
1025         if (!error || error == EPIPE)
1026                 error = nfs_reply(rep);
1027
1028         /*
1029          * RPC done, unlink the request.
1030          */
1031         s = splsoftclock();
1032         mtx_lock(&nfs_reqq_mtx);
1033         TAILQ_REMOVE(&nfs_reqq, rep, r_chain);
1034         if (TAILQ_EMPTY(&nfs_reqq))
1035                 callout_stop(&nfs_callout);
1036         /*
1037          * Decrement the outstanding request count.
1038          */
1039         if (rep->r_flags & R_SENT) {
1040                 rep->r_flags &= ~R_SENT;        /* paranoia */
1041                 nmp->nm_sent -= NFS_CWNDSCALE;
1042         }
1043         mtx_unlock(&nfs_reqq_mtx);
1044         splx(s);
1045
1046         /*
1047          * If there was a successful reply and a tprintf msg.
1048          * tprintf a response.
1049          */
1050         if (!error)
1051                 nfs_up(rep, nmp, rep->r_td, "is alive again", NFSSTA_TIMEO);
1052         mrep = rep->r_mrep;
1053         md = rep->r_md;
1054         dpos = rep->r_dpos;
1055         if (error) {
1056                 /*
1057                  * If we got interrupted by a signal in nfs_reply(), there's
1058                  * a very small window where the reply could've come in before
1059                  * this process got scheduled in. To handle that case, we need 
1060                  * to free the reply if it was delivered.
1061                  */
1062                 if (rep->r_mrep != NULL)
1063                         m_freem(rep->r_mrep);
1064                 m_freem(rep->r_mreq);
1065                 free((caddr_t)rep, M_NFSREQ);
1066                 return (error);
1067         }
1068
1069         if (rep->r_mrep == NULL)
1070                 panic("nfs_request: rep->r_mrep shouldn't be NULL if no error\n");
1071
1072         /*
1073          * break down the rpc header and check if ok
1074          */
1075         tl = nfsm_dissect(u_int32_t *, 3 * NFSX_UNSIGNED);
1076         if (*tl++ == rpc_msgdenied) {
1077                 if (*tl == rpc_mismatch)
1078                         error = EOPNOTSUPP;
1079                 else
1080                         error = EACCES;
1081                 m_freem(mrep);
1082                 m_freem(rep->r_mreq);
1083                 free((caddr_t)rep, M_NFSREQ);
1084                 return (error);
1085         }
1086
1087         /*
1088          * Just throw away any verifyer (ie: kerberos etc).
1089          */
1090         i = fxdr_unsigned(int, *tl++);          /* verf type */
1091         i = fxdr_unsigned(int32_t, *tl);        /* len */
1092         if (i > 0)
1093                 nfsm_adv(nfsm_rndup(i));
1094         tl = nfsm_dissect(u_int32_t *, NFSX_UNSIGNED);
1095         /* 0 == ok */
1096         if (*tl == 0) {
1097                 tl = nfsm_dissect(u_int32_t *, NFSX_UNSIGNED);
1098                 if (*tl != 0) {
1099                         error = fxdr_unsigned(int, *tl);
1100                         if ((nmp->nm_flag & NFSMNT_NFSV3) &&
1101                                 error == NFSERR_TRYLATER) {
1102                                 m_freem(mrep);
1103                                 error = 0;
1104                                 waituntil = time_second + trylater_delay;
1105                                 while (time_second < waituntil)
1106                                         (void) tsleep(&lbolt,
1107                                                 PSOCK, "nqnfstry", 0);
1108                                 trylater_delay *= nfs_backoff[trylater_cnt];
1109                                 if (trylater_cnt < NFS_NBACKOFF - 1)
1110                                         trylater_cnt++;
1111                                 goto tryagain;
1112                         }
1113
1114                         /*
1115                          * If the File Handle was stale, invalidate the
1116                          * lookup cache, just in case.
1117                          */
1118                         if (error == ESTALE)
1119                                 cache_purge(vp);
1120                         if (nmp->nm_flag & NFSMNT_NFSV3) {
1121                                 *mrp = mrep;
1122                                 *mdp = md;
1123                                 *dposp = dpos;
1124                                 error |= NFSERR_RETERR;
1125                         } else
1126                                 m_freem(mrep);
1127                         m_freem(rep->r_mreq);
1128                         free((caddr_t)rep, M_NFSREQ);
1129                         return (error);
1130                 }
1131
1132                 *mrp = mrep;
1133                 *mdp = md;
1134                 *dposp = dpos;
1135                 m_freem(rep->r_mreq);
1136                 FREE((caddr_t)rep, M_NFSREQ);
1137                 return (0);
1138         }
1139         m_freem(mrep);
1140         error = EPROTONOSUPPORT;
1141 nfsmout:
1142         m_freem(rep->r_mreq);
1143         free((caddr_t)rep, M_NFSREQ);
1144         return (error);
1145 }
1146
1147 /*
1148  * Nfs timer routine
1149  * Scan the nfsreq list and retranmit any requests that have timed out
1150  * To avoid retransmission attempts on STREAM sockets (in the future) make
1151  * sure to set the r_retry field to 0 (implies nm_retry == 0).
1152  * 
1153  * XXX - 
1154  * For now, since we don't register MPSAFE callouts for the NFS client -
1155  * softclock() acquires Giant before calling us. That prevents req entries
1156  * from being removed from the list (from nfs_request()). But we still 
1157  * acquire the nfs reqq mutex to make sure the state of individual req
1158  * entries is not modified from RPC reply handling (from socket callback)
1159  * while nfs_timer is walking the list of reqs.
1160  * The nfs reqq lock cannot be held while we do the pru_send() because of a
1161  * lock ordering violation. The NFS client socket callback acquires 
1162  * inp_lock->nfsreq mutex and pru_send acquires inp_lock. So we drop the 
1163  * reqq mutex (and reacquire it after the pru_send()). This won't work
1164  * when we move to fine grained locking for NFS. When we get to that point, 
1165  * a rewrite of nfs_timer() will be needed.
1166  */
1167 void
1168 nfs_timer(void *arg)
1169 {
1170         struct nfsreq *rep;
1171         struct mbuf *m;
1172         struct socket *so;
1173         struct nfsmount *nmp;
1174         int timeo;
1175         int s, error;
1176         struct timeval now;
1177
1178         getmicrouptime(&now);
1179         s = splnet();
1180         mtx_lock(&nfs_reqq_mtx);
1181         TAILQ_FOREACH(rep, &nfs_reqq, r_chain) {
1182                 nmp = rep->r_nmp;
1183                 if (rep->r_mrep || (rep->r_flags & R_SOFTTERM))
1184                         continue;
1185                 if (nfs_sigintr(nmp, rep, rep->r_td))
1186                         continue;
1187                 if (nmp->nm_tprintf_initial_delay != 0 &&
1188                     (rep->r_rexmit > 2 || (rep->r_flags & R_RESENDERR)) &&
1189                     rep->r_lastmsg + nmp->nm_tprintf_delay < now.tv_sec) {
1190                         rep->r_lastmsg = now.tv_sec;
1191                         nfs_down(rep, nmp, rep->r_td, "not responding",
1192                             0, NFSSTA_TIMEO);
1193 #if 0
1194                         if (!(nmp->nm_state & NFSSTA_MOUNTED)) {
1195                                 /* we're not yet completely mounted and */
1196                                 /* we can't complete an RPC, so we fail */
1197                                 nfsstats.rpctimeouts++;
1198                                 nfs_softterm(rep);
1199                                 continue;
1200                         }
1201 #endif
1202                 }
1203                 if (rep->r_rtt >= 0) {
1204                         rep->r_rtt++;
1205                         if (nmp->nm_flag & NFSMNT_DUMBTIMR)
1206                                 timeo = nmp->nm_timeo;
1207                         else
1208                                 timeo = NFS_RTO(nmp, proct[rep->r_procnum]);
1209                         if (nmp->nm_timeouts > 0)
1210                                 timeo *= nfs_backoff[nmp->nm_timeouts - 1];
1211                         if (rep->r_rtt <= timeo)
1212                                 continue;
1213                         if (nmp->nm_timeouts < NFS_NBACKOFF)
1214                                 nmp->nm_timeouts++;
1215                 }
1216                 if (rep->r_rexmit >= rep->r_retry) {    /* too many */
1217                         nfsstats.rpctimeouts++;
1218                         nfs_softterm(rep);
1219                         continue;
1220                 }
1221                 if (nmp->nm_sotype != SOCK_DGRAM) {
1222                         if (++rep->r_rexmit > NFS_MAXREXMIT)
1223                                 rep->r_rexmit = NFS_MAXREXMIT;
1224                         /*
1225                          * For NFS/TCP, setting R_MUSTRESEND and waking up 
1226                          * the requester will cause the request to be   
1227                          * retransmitted (in nfs_reply()), re-connecting
1228                          * if necessary.
1229                          */
1230                         rep->r_flags |= R_MUSTRESEND;
1231                         wakeup_nfsreq(rep);
1232                         continue;
1233                 }
1234                 if ((so = nmp->nm_so) == NULL)
1235                         continue;
1236                 /*
1237                  * If there is enough space and the window allows..
1238                  *      Resend it
1239                  * Set r_rtt to -1 in case we fail to send it now.
1240                  */
1241                 rep->r_rtt = -1;
1242                 if (sbspace(&so->so_snd) >= rep->r_mreq->m_pkthdr.len &&
1243                    ((nmp->nm_flag & NFSMNT_DUMBTIMR) ||
1244                     (rep->r_flags & R_SENT) ||
1245                     nmp->nm_sent < nmp->nm_cwnd) &&
1246                    (m = m_copym(rep->r_mreq, 0, M_COPYALL, M_DONTWAIT))){
1247                         mtx_unlock(&nfs_reqq_mtx);
1248                         if ((nmp->nm_flag & NFSMNT_NOCONN) == 0)
1249                             error = (*so->so_proto->pr_usrreqs->pru_send)
1250                                     (so, 0, m, NULL, NULL, curthread);
1251                         else
1252                             error = (*so->so_proto->pr_usrreqs->pru_send)
1253                                     (so, 0, m, nmp->nm_nam, NULL, curthread);
1254                         mtx_lock(&nfs_reqq_mtx);
1255                         if (error) {
1256                                 if (NFSIGNORE_SOERROR(nmp->nm_soflags, error))
1257                                         so->so_error = 0;
1258                                 rep->r_flags |= R_RESENDERR;
1259                         } else {
1260                                 /*
1261                                  * Iff first send, start timing
1262                                  * else turn timing off, backoff timer
1263                                  * and divide congestion window by 2.
1264                                  */
1265                                 rep->r_flags &= ~R_RESENDERR;
1266                                 if (rep->r_flags & R_SENT) {
1267                                         rep->r_flags &= ~R_TIMING;
1268                                         if (++rep->r_rexmit > NFS_MAXREXMIT)
1269                                                 rep->r_rexmit = NFS_MAXREXMIT;
1270                                         nmp->nm_cwnd >>= 1;
1271                                         if (nmp->nm_cwnd < NFS_CWNDSCALE)
1272                                                 nmp->nm_cwnd = NFS_CWNDSCALE;
1273                                         nfsstats.rpcretries++;
1274                                 } else {
1275                                         rep->r_flags |= R_SENT;
1276                                         nmp->nm_sent += NFS_CWNDSCALE;
1277                                 }
1278                                 rep->r_rtt = 0;
1279                         }
1280                 }
1281         }
1282         mtx_unlock(&nfs_reqq_mtx);
1283         splx(s);
1284         callout_reset(&nfs_callout, nfs_ticks, nfs_timer, NULL);
1285 }
1286
1287 /*
1288  * Mark all of an nfs mount's outstanding requests with R_SOFTTERM and
1289  * wait for all requests to complete. This is used by forced unmounts
1290  * to terminate any outstanding RPCs.
1291  */
1292 int
1293 nfs_nmcancelreqs(nmp)
1294         struct nfsmount *nmp;
1295 {
1296         struct nfsreq *req;
1297         int i, s;
1298
1299         s = splnet();
1300         mtx_lock(&nfs_reqq_mtx);
1301         TAILQ_FOREACH(req, &nfs_reqq, r_chain) {
1302                 if (nmp != req->r_nmp || req->r_mrep != NULL ||
1303                     (req->r_flags & R_SOFTTERM))
1304                         continue;
1305                 nfs_softterm(req);
1306         }
1307         mtx_unlock(&nfs_reqq_mtx);
1308         splx(s);
1309
1310         for (i = 0; i < 30; i++) {
1311                 s = splnet();
1312                 mtx_lock(&nfs_reqq_mtx);
1313                 TAILQ_FOREACH(req, &nfs_reqq, r_chain) {
1314                         if (nmp == req->r_nmp)
1315                                 break;
1316                 }
1317                 mtx_unlock(&nfs_reqq_mtx);
1318                 splx(s);
1319                 if (req == NULL)
1320                         return (0);
1321                 tsleep(&lbolt, PSOCK, "nfscancel", 0);
1322         }
1323         return (EBUSY);
1324 }
1325
1326 /*
1327  * Flag a request as being about to terminate (due to NFSMNT_INT/NFSMNT_SOFT).
1328  * The nm_send count is decremented now to avoid deadlocks when the process in
1329  * soreceive() hasn't yet managed to send its own request.
1330  */
1331
1332 static void
1333 nfs_softterm(struct nfsreq *rep)
1334 {
1335
1336         rep->r_flags |= R_SOFTTERM;
1337         if (rep->r_flags & R_SENT) {
1338                 rep->r_nmp->nm_sent -= NFS_CWNDSCALE;
1339                 rep->r_flags &= ~R_SENT;
1340         }
1341         /* 
1342          * Request terminated, wakeup the blocked process, so that we
1343          * can return EINTR back.
1344          */
1345         wakeup_nfsreq(rep);
1346 }
1347
1348 /*
1349  * Any signal that can interrupt an NFS operation in an intr mount
1350  * should be added to this set. SIGSTOP and SIGKILL cannot be masked.
1351  */
1352 int nfs_sig_set[] = {
1353         SIGINT,
1354         SIGTERM,
1355         SIGHUP,
1356         SIGKILL,
1357         SIGSTOP,
1358         SIGQUIT
1359 };
1360
1361 /*
1362  * Check to see if one of the signals in our subset is pending on
1363  * the process (in an intr mount).
1364  */
1365 static int
1366 nfs_sig_pending(sigset_t set)
1367 {
1368         int i;
1369         
1370         for (i = 0 ; i < sizeof(nfs_sig_set)/sizeof(int) ; i++)
1371                 if (SIGISMEMBER(set, nfs_sig_set[i]))
1372                         return (1);
1373         return (0);
1374 }
1375  
1376 /*
1377  * The set/restore sigmask functions are used to (temporarily) overwrite
1378  * the process p_sigmask during an RPC call (for example). These are also
1379  * used in other places in the NFS client that might tsleep().
1380  */
1381 void
1382 nfs_set_sigmask(struct thread *td, sigset_t *oldset)
1383 {
1384         sigset_t newset;
1385         int i;
1386         struct proc *p;
1387         
1388         SIGFILLSET(newset);
1389         if (td == NULL)
1390                 td = curthread; /* XXX */
1391         p = td->td_proc;
1392         /* Remove the NFS set of signals from newset */
1393         PROC_LOCK(p);
1394         mtx_lock(&p->p_sigacts->ps_mtx);
1395         for (i = 0 ; i < sizeof(nfs_sig_set)/sizeof(int) ; i++) {
1396                 /*
1397                  * But make sure we leave the ones already masked
1398                  * by the process, ie. remove the signal from the
1399                  * temporary signalmask only if it wasn't already
1400                  * in p_sigmask.
1401                  */
1402                 if (!SIGISMEMBER(td->td_sigmask, nfs_sig_set[i]) &&
1403                     !SIGISMEMBER(p->p_sigacts->ps_sigignore, nfs_sig_set[i]))
1404                         SIGDELSET(newset, nfs_sig_set[i]);
1405         }
1406         mtx_unlock(&p->p_sigacts->ps_mtx);
1407         PROC_UNLOCK(p);
1408         kern_sigprocmask(td, SIG_SETMASK, &newset, oldset, 0);
1409 }
1410
1411 void
1412 nfs_restore_sigmask(struct thread *td, sigset_t *set)
1413 {
1414         if (td == NULL)
1415                 td = curthread; /* XXX */
1416         kern_sigprocmask(td, SIG_SETMASK, set, NULL, 0);
1417 }
1418
1419 /*
1420  * NFS wrapper to msleep(), that shoves a new p_sigmask and restores the
1421  * old one after msleep() returns.
1422  */
1423 int
1424 nfs_msleep(struct thread *td, void *ident, struct mtx *mtx, int priority, char *wmesg, int timo)
1425 {
1426         sigset_t oldset;
1427         int error;
1428         struct proc *p;
1429         
1430         if ((priority & PCATCH) == 0)
1431                 return msleep(ident, mtx, priority, wmesg, timo);
1432         if (td == NULL)
1433                 td = curthread; /* XXX */
1434         nfs_set_sigmask(td, &oldset);
1435         error = msleep(ident, mtx, priority, wmesg, timo);
1436         nfs_restore_sigmask(td, &oldset);
1437         p = td->td_proc;
1438         return (error);
1439 }
1440
1441 /*
1442  * NFS wrapper to tsleep(), that shoves a new p_sigmask and restores the
1443  * old one after tsleep() returns.
1444  */
1445 int
1446 nfs_tsleep(struct thread *td, void *ident, int priority, char *wmesg, int timo)
1447 {
1448         sigset_t oldset;
1449         int error;
1450         struct proc *p;
1451         
1452         if ((priority & PCATCH) == 0)
1453                 return tsleep(ident, priority, wmesg, timo);
1454         if (td == NULL)
1455                 td = curthread; /* XXX */
1456         nfs_set_sigmask(td, &oldset);
1457         error = tsleep(ident, priority, wmesg, timo);
1458         nfs_restore_sigmask(td, &oldset);
1459         p = td->td_proc;
1460         return (error);
1461 }
1462
1463 /*
1464  * Test for a termination condition pending on the process.
1465  * This is used for NFSMNT_INT mounts.
1466  */
1467 int
1468 nfs_sigintr(struct nfsmount *nmp, struct nfsreq *rep, struct thread *td)
1469 {
1470         struct proc *p;
1471         sigset_t tmpset;
1472
1473         if ((nmp->nm_flag & NFSMNT_NFSV4) != 0)
1474                 return nfs4_sigintr(nmp, rep, td);
1475         if (rep && (rep->r_flags & R_SOFTTERM))
1476                 return (EIO);
1477         /* Terminate all requests while attempting a forced unmount. */
1478         if (nmp->nm_mountp->mnt_kern_flag & MNTK_UNMOUNTF)
1479                 return (EIO);
1480         if (!(nmp->nm_flag & NFSMNT_INT))
1481                 return (0);
1482         if (td == NULL)
1483                 return (0);
1484
1485         p = td->td_proc;
1486         PROC_LOCK(p);
1487         tmpset = p->p_siglist;
1488         SIGSETNAND(tmpset, td->td_sigmask);
1489         mtx_lock(&p->p_sigacts->ps_mtx);
1490         SIGSETNAND(tmpset, p->p_sigacts->ps_sigignore);
1491         mtx_unlock(&p->p_sigacts->ps_mtx);
1492         if (SIGNOTEMPTY(p->p_siglist) && nfs_sig_pending(tmpset)) {
1493                 PROC_UNLOCK(p);
1494                 return (EINTR);
1495         }
1496         PROC_UNLOCK(p);
1497
1498         return (0);
1499 }
1500
1501 /*
1502  * Lock a socket against others.
1503  * Necessary for STREAM sockets to ensure you get an entire rpc request/reply
1504  * and also to avoid race conditions between the processes with nfs requests
1505  * in progress when a reconnect is necessary.
1506  */
1507 int
1508 nfs_sndlock(struct nfsreq *rep)
1509 {
1510         int *statep = &rep->r_nmp->nm_state;
1511         struct thread *td;
1512         int error, slpflag = 0, slptimeo = 0;
1513
1514         td = rep->r_td;
1515         if (rep->r_nmp->nm_flag & NFSMNT_INT)
1516                 slpflag = PCATCH;
1517         while (*statep & NFSSTA_SNDLOCK) {
1518                 error = nfs_sigintr(rep->r_nmp, rep, td);
1519                 if (error)
1520                         return (error);
1521                 *statep |= NFSSTA_WANTSND;
1522                 (void) tsleep(statep, slpflag | (PZERO - 1),
1523                         "nfsndlck", slptimeo);
1524                 if (slpflag == PCATCH) {
1525                         slpflag = 0;
1526                         slptimeo = 2 * hz;
1527                 }
1528         }
1529         *statep |= NFSSTA_SNDLOCK;
1530         return (0);
1531 }
1532
1533 /*
1534  * Unlock the stream socket for others.
1535  */
1536 void
1537 nfs_sndunlock(struct nfsreq *rep)
1538 {
1539         int *statep = &rep->r_nmp->nm_state;
1540
1541         if ((*statep & NFSSTA_SNDLOCK) == 0)
1542                 panic("nfs sndunlock");
1543         *statep &= ~NFSSTA_SNDLOCK;
1544         if (*statep & NFSSTA_WANTSND) {
1545                 *statep &= ~NFSSTA_WANTSND;
1546                 wakeup(statep);
1547         }
1548 }
1549
1550 /*
1551  *      nfs_realign:
1552  *
1553  *      Check for badly aligned mbuf data and realign by copying the unaligned
1554  *      portion of the data into a new mbuf chain and freeing the portions
1555  *      of the old chain that were replaced.
1556  *
1557  *      We cannot simply realign the data within the existing mbuf chain
1558  *      because the underlying buffers may contain other rpc commands and
1559  *      we cannot afford to overwrite them.
1560  *
1561  *      We would prefer to avoid this situation entirely.  The situation does
1562  *      not occur with NFS/UDP and is supposed to only occassionally occur
1563  *      with TCP.  Use vfs.nfs.realign_count and realign_test to check this.
1564  *
1565  */
1566 static int
1567 nfs_realign(struct mbuf **pm, int hsiz)
1568 {
1569         struct mbuf *m;
1570         struct mbuf *n = NULL;
1571         int off = 0;
1572
1573         ++nfs_realign_test;
1574         while ((m = *pm) != NULL) {
1575                 if ((m->m_len & 0x3) || (mtod(m, intptr_t) & 0x3)) {
1576                         MGET(n, M_DONTWAIT, MT_DATA);
1577                         if (n == NULL)
1578                                 return (ENOMEM);
1579                         if (m->m_len >= MINCLSIZE) {
1580                                 MCLGET(n, M_DONTWAIT);
1581                                 if (n->m_ext.ext_buf == NULL) {
1582                                         m_freem(n);
1583                                         return (ENOMEM);
1584                                 }
1585                         }
1586                         n->m_len = 0;
1587                         break;
1588                 }
1589                 pm = &m->m_next;
1590         }
1591         /*
1592          * If n is non-NULL, loop on m copying data, then replace the
1593          * portion of the chain that had to be realigned.
1594          */
1595         if (n != NULL) {
1596                 ++nfs_realign_count;
1597                 while (m) {
1598                         m_copyback(n, off, m->m_len, mtod(m, caddr_t));
1599                         off += m->m_len;
1600                         m = m->m_next;
1601                 }
1602                 m_freem(*pm);
1603                 *pm = n;
1604         }
1605         return (0);
1606 }
1607
1608
1609 static int
1610 nfs_msg(struct thread *td, const char *server, const char *msg, int error)
1611 {
1612         struct proc *p;
1613
1614         p = td ? td->td_proc : NULL;
1615         if (error) {
1616                 tprintf(p, LOG_INFO, "nfs server %s: %s, error %d\n", server,
1617                     msg, error);
1618         } else {
1619                 tprintf(p, LOG_INFO, "nfs server %s: %s\n", server, msg);
1620         }
1621         return (0);
1622 }
1623
1624 void
1625 nfs_down(rep, nmp, td, msg, error, flags)
1626         struct nfsreq *rep;
1627         struct nfsmount *nmp;
1628         struct thread *td;
1629         const char *msg;
1630         int error, flags;
1631 {
1632
1633         if (nmp == NULL)
1634                 return;
1635         if ((flags & NFSSTA_TIMEO) && !(nmp->nm_state & NFSSTA_TIMEO)) {
1636                 vfs_event_signal(&nmp->nm_mountp->mnt_stat.f_fsid,
1637                     VQ_NOTRESP, 0);
1638                 nmp->nm_state |= NFSSTA_TIMEO;
1639         }
1640 #ifdef NFSSTA_LOCKTIMEO
1641         if ((flags & NFSSTA_LOCKTIMEO) && !(nmp->nm_state & NFSSTA_LOCKTIMEO)) {
1642                 vfs_event_signal(&nmp->nm_mountp->mnt_stat.f_fsid,
1643                     VQ_NOTRESPLOCK, 0);
1644                 nmp->nm_state |= NFSSTA_LOCKTIMEO;
1645         }
1646 #endif
1647         if (rep)
1648                 rep->r_flags |= R_TPRINTFMSG;
1649         nfs_msg(td, nmp->nm_mountp->mnt_stat.f_mntfromname, msg, error);
1650 }
1651
1652 void
1653 nfs_up(rep, nmp, td, msg, flags)
1654         struct nfsreq *rep;
1655         struct nfsmount *nmp;
1656         struct thread *td;
1657         const char *msg;
1658         int flags;
1659 {
1660         if (nmp == NULL)
1661                 return;
1662         if ((rep == NULL) || (rep->r_flags & R_TPRINTFMSG) != 0)
1663                 nfs_msg(td, nmp->nm_mountp->mnt_stat.f_mntfromname, msg, 0);
1664         if ((flags & NFSSTA_TIMEO) && (nmp->nm_state & NFSSTA_TIMEO)) {
1665                 nmp->nm_state &= ~NFSSTA_TIMEO;
1666                 vfs_event_signal(&nmp->nm_mountp->mnt_stat.f_fsid,
1667                     VQ_NOTRESP, 1);
1668         }
1669 #ifdef NFSSTA_LOCKTIMEO
1670         if ((flags & NFSSTA_LOCKTIMEO) && (nmp->nm_state & NFSSTA_LOCKTIMEO)) {
1671                 nmp->nm_state &= ~NFSSTA_LOCKTIMEO;
1672                 vfs_event_signal(&nmp->nm_mountp->mnt_stat.f_fsid,
1673                     VQ_NOTRESPLOCK, 1);
1674         }
1675 #endif
1676 }
1677