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