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