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