]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/nfsclient/nfs_socket.c
This commit was generated by cvs2svn to compensate for changes in r92282,
[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  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      @(#)nfs_socket.c        8.5 (Berkeley) 3/30/95
37  */
38
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41
42 /*
43  * Socket operations for use by nfs
44  */
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/lock.h>
50 #include <sys/malloc.h>
51 #include <sys/mbuf.h>
52 #include <sys/mount.h>
53 #include <sys/mutex.h>
54 #include <sys/proc.h>
55 #include <sys/protosw.h>
56 #include <sys/signalvar.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/sysctl.h>
60 #include <sys/syslog.h>
61 #include <sys/vnode.h>
62
63 #include <netinet/in.h>
64 #include <netinet/tcp.h>
65
66 #include <nfs/rpcv2.h>
67 #include <nfs/nfsproto.h>
68 #include <nfsclient/nfs.h>
69 #include <nfs/xdr_subs.h>
70 #include <nfsclient/nfsm_subs.h>
71 #include <nfsclient/nfsmount.h>
72 #include <nfsclient/nfsnode.h>
73
74 #define TRUE    1
75 #define FALSE   0
76
77 /*
78  * Estimate rto for an nfs rpc sent via. an unreliable datagram.
79  * Use the mean and mean deviation of rtt for the appropriate type of rpc
80  * for the frequent rpcs and a default for the others.
81  * The justification for doing "other" this way is that these rpcs
82  * happen so infrequently that timer est. would probably be stale.
83  * Also, since many of these rpcs are
84  * non-idempotent, a conservative timeout is desired.
85  * getattr, lookup - A+2D
86  * read, write     - A+4D
87  * other           - nm_timeo
88  */
89 #define NFS_RTO(n, t) \
90         ((t) == 0 ? (n)->nm_timeo : \
91          ((t) < 3 ? \
92           (((((n)->nm_srtt[t-1] + 3) >> 2) + (n)->nm_sdrtt[t-1] + 1) >> 1) : \
93           ((((n)->nm_srtt[t-1] + 7) >> 3) + (n)->nm_sdrtt[t-1] + 1)))
94 #define NFS_SRTT(r)     (r)->r_nmp->nm_srtt[proct[(r)->r_procnum] - 1]
95 #define NFS_SDRTT(r)    (r)->r_nmp->nm_sdrtt[proct[(r)->r_procnum] - 1]
96
97 /*
98  * Defines which timer to use for the procnum.
99  * 0 - default
100  * 1 - getattr
101  * 2 - lookup
102  * 3 - read
103  * 4 - write
104  */
105 static int proct[NFS_NPROCS] = {
106         0, 1, 0, 2, 1, 3, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0,
107 };
108
109 static int      nfs_realign_test;
110 static int      nfs_realign_count;
111 static int      nfs_bufpackets = 4;
112
113 SYSCTL_DECL(_vfs_nfs);
114
115 SYSCTL_INT(_vfs_nfs, OID_AUTO, realign_test, CTLFLAG_RW, &nfs_realign_test, 0, "");
116 SYSCTL_INT(_vfs_nfs, OID_AUTO, realign_count, CTLFLAG_RW, &nfs_realign_count, 0, "");
117 SYSCTL_INT(_vfs_nfs, OID_AUTO, bufpackets, CTLFLAG_RW, &nfs_bufpackets, 0, "");
118
119
120 /*
121  * There is a congestion window for outstanding rpcs maintained per mount
122  * point. The cwnd size is adjusted in roughly the way that:
123  * Van Jacobson, Congestion avoidance and Control, In "Proceedings of
124  * SIGCOMM '88". ACM, August 1988.
125  * describes for TCP. The cwnd size is chopped in half on a retransmit timeout
126  * and incremented by 1/cwnd when each rpc reply is received and a full cwnd
127  * of rpcs is in progress.
128  * (The sent count and cwnd are scaled for integer arith.)
129  * Variants of "slow start" were tried and were found to be too much of a
130  * performance hit (ave. rtt 3 times larger),
131  * I suspect due to the large rtt that nfs rpcs have.
132  */
133 #define NFS_CWNDSCALE   256
134 #define NFS_MAXCWND     (NFS_CWNDSCALE * 32)
135 #define NFS_NBACKOFF    8
136 static int nfs_backoff[NFS_NBACKOFF] = { 2, 4, 8, 16, 32, 64, 128, 256, };
137 struct callout_handle   nfs_timer_handle;
138
139 static int      nfs_msg(struct thread *, char *, char *);
140 static int      nfs_rcvlock(struct nfsreq *);
141 static void     nfs_rcvunlock(struct nfsreq *);
142 static void     nfs_realign(struct mbuf **pm, int hsiz);
143 static int      nfs_receive(struct nfsreq *rep, struct sockaddr **aname,
144                     struct mbuf **mp);
145 static int      nfs_reply(struct nfsreq *);
146 static void     nfs_softterm(struct nfsreq *rep);
147 static int      nfs_reconnect(struct nfsreq *rep);
148
149 /*
150  * Initialize sockets and congestion for a new NFS connection.
151  * We do not free the sockaddr if error.
152  */
153 int
154 nfs_connect(struct nfsmount *nmp, struct nfsreq *rep)
155 {
156         struct socket *so;
157         int s, error, rcvreserve, sndreserve;
158         int pktscale;
159         struct sockaddr *saddr;
160         struct sockaddr_in *sin;
161         struct thread *td = &thread0; /* only used for socreate and sobind */
162
163         nmp->nm_so = (struct socket *)0;
164         saddr = nmp->nm_nam;
165         error = socreate(saddr->sa_family, &nmp->nm_so, nmp->nm_sotype,
166                 nmp->nm_soproto, nmp->nm_cred, td);
167         if (error)
168                 goto bad;
169         so = nmp->nm_so;
170         nmp->nm_soflags = so->so_proto->pr_flags;
171
172         /*
173          * Some servers require that the client port be a reserved port number.
174          */
175         if (saddr->sa_family == AF_INET && (nmp->nm_flag & NFSMNT_RESVPORT)) {
176                 struct sockopt sopt;
177                 int ip;
178                 struct sockaddr_in ssin;
179
180                 bzero(&sopt, sizeof sopt);
181                 ip = IP_PORTRANGE_LOW;
182                 sopt.sopt_dir = SOPT_SET;
183                 sopt.sopt_level = IPPROTO_IP;
184                 sopt.sopt_name = IP_PORTRANGE;
185                 sopt.sopt_val = (void *)&ip;
186                 sopt.sopt_valsize = sizeof(ip);
187                 sopt.sopt_td = NULL;
188                 error = sosetopt(so, &sopt);
189                 if (error)
190                         goto bad;
191                 bzero(&ssin, sizeof ssin);
192                 sin = &ssin;
193                 sin->sin_len = sizeof (struct sockaddr_in);
194                 sin->sin_family = AF_INET;
195                 sin->sin_addr.s_addr = INADDR_ANY;
196                 sin->sin_port = htons(0);
197                 error = sobind(so, (struct sockaddr *)sin, td);
198                 if (error)
199                         goto bad;
200                 bzero(&sopt, sizeof sopt);
201                 ip = IP_PORTRANGE_DEFAULT;
202                 sopt.sopt_dir = SOPT_SET;
203                 sopt.sopt_level = IPPROTO_IP;
204                 sopt.sopt_name = IP_PORTRANGE;
205                 sopt.sopt_val = (void *)&ip;
206                 sopt.sopt_valsize = sizeof(ip);
207                 sopt.sopt_td = NULL;
208                 error = sosetopt(so, &sopt);
209                 if (error)
210                         goto bad;
211         }
212
213         /*
214          * Protocols that do not require connections may be optionally left
215          * unconnected for servers that reply from a port other than NFS_PORT.
216          */
217         if (nmp->nm_flag & NFSMNT_NOCONN) {
218                 if (nmp->nm_soflags & PR_CONNREQUIRED) {
219                         error = ENOTCONN;
220                         goto bad;
221                 }
222         } else {
223                 error = soconnect(so, nmp->nm_nam, td);
224                 if (error)
225                         goto bad;
226
227                 /*
228                  * Wait for the connection to complete. Cribbed from the
229                  * connect system call but with the wait timing out so
230                  * that interruptible mounts don't hang here for a long time.
231                  */
232                 s = splnet();
233                 while ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
234                         (void) tsleep((caddr_t)&so->so_timeo, PSOCK,
235                                 "nfscon", 2 * hz);
236                         if ((so->so_state & SS_ISCONNECTING) &&
237                             so->so_error == 0 && rep &&
238                             (error = nfs_sigintr(nmp, rep,
239                               (rep->r_td ? rep->r_td->td_proc : NULL))) != 0){
240                                 so->so_state &= ~SS_ISCONNECTING;
241                                 splx(s);
242                                 goto bad;
243                         }
244                 }
245                 if (so->so_error) {
246                         error = so->so_error;
247                         so->so_error = 0;
248                         splx(s);
249                         goto bad;
250                 }
251                 splx(s);
252         }
253         so->so_rcv.sb_timeo = 5 * hz;
254         so->so_snd.sb_timeo = 5 * hz;
255
256         /*
257          * Get buffer reservation size from sysctl, but impose reasonable
258          * limits.
259          */
260         pktscale = nfs_bufpackets;
261         if (pktscale < 2)
262                 pktscale = 2;
263         if (pktscale > 64)
264                 pktscale = 64;
265
266         if (nmp->nm_sotype == SOCK_DGRAM) {
267                 sndreserve = (nmp->nm_wsize + NFS_MAXPKTHDR) * pktscale;
268                 rcvreserve = (max(nmp->nm_rsize, nmp->nm_readdirsize) +
269                     NFS_MAXPKTHDR) * pktscale;
270         } else if (nmp->nm_sotype == SOCK_SEQPACKET) {
271                 sndreserve = (nmp->nm_wsize + NFS_MAXPKTHDR) * pktscale;
272                 rcvreserve = (max(nmp->nm_rsize, nmp->nm_readdirsize) +
273                     NFS_MAXPKTHDR) * pktscale;
274         } else {
275                 if (nmp->nm_sotype != SOCK_STREAM)
276                         panic("nfscon sotype");
277                 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
278                         struct sockopt sopt;
279                         int val;
280
281                         bzero(&sopt, sizeof sopt);
282                         sopt.sopt_level = SOL_SOCKET;
283                         sopt.sopt_name = SO_KEEPALIVE;
284                         sopt.sopt_val = &val;
285                         sopt.sopt_valsize = sizeof val;
286                         val = 1;
287                         sosetopt(so, &sopt);
288                 }
289                 if (so->so_proto->pr_protocol == IPPROTO_TCP) {
290                         struct sockopt sopt;
291                         int val;
292
293                         bzero(&sopt, sizeof sopt);
294                         sopt.sopt_level = IPPROTO_TCP;
295                         sopt.sopt_name = TCP_NODELAY;
296                         sopt.sopt_val = &val;
297                         sopt.sopt_valsize = sizeof val;
298                         val = 1;
299                         sosetopt(so, &sopt);
300                 }
301                 sndreserve = (nmp->nm_wsize + NFS_MAXPKTHDR +
302                     sizeof (u_int32_t)) * pktscale;
303                 rcvreserve = (nmp->nm_rsize + NFS_MAXPKTHDR +
304                     sizeof (u_int32_t)) * pktscale;
305         }
306         error = soreserve(so, sndreserve, rcvreserve);
307         if (error)
308                 goto bad;
309         so->so_rcv.sb_flags |= SB_NOINTR;
310         so->so_snd.sb_flags |= SB_NOINTR;
311
312         /* Initialize other non-zero congestion variables */
313         nmp->nm_srtt[0] = nmp->nm_srtt[1] = nmp->nm_srtt[2] =
314                 nmp->nm_srtt[3] = (NFS_TIMEO << 3);
315         nmp->nm_sdrtt[0] = nmp->nm_sdrtt[1] = nmp->nm_sdrtt[2] =
316                 nmp->nm_sdrtt[3] = 0;
317         nmp->nm_cwnd = NFS_MAXCWND / 2;     /* Initial send window */
318         nmp->nm_sent = 0;
319         nmp->nm_timeouts = 0;
320         return (0);
321
322 bad:
323         nfs_disconnect(nmp);
324         return (error);
325 }
326
327 /*
328  * Reconnect routine:
329  * Called when a connection is broken on a reliable protocol.
330  * - clean up the old socket
331  * - nfs_connect() again
332  * - set R_MUSTRESEND for all outstanding requests on mount point
333  * If this fails the mount point is DEAD!
334  * nb: Must be called with the nfs_sndlock() set on the mount point.
335  */
336 static int
337 nfs_reconnect(struct nfsreq *rep)
338 {
339         struct nfsreq *rp;
340         struct nfsmount *nmp = rep->r_nmp;
341         int error;
342
343         nfs_disconnect(nmp);
344         while ((error = nfs_connect(nmp, rep)) != 0) {
345                 if (error == EINTR || error == ERESTART)
346                         return (EINTR);
347                 (void) tsleep((caddr_t)&lbolt, PSOCK, "nfscon", 0);
348         }
349
350         /*
351          * Loop through outstanding request list and fix up all requests
352          * on old socket.
353          */
354         TAILQ_FOREACH(rp, &nfs_reqq, r_chain) {
355                 if (rp->r_nmp == nmp)
356                         rp->r_flags |= R_MUSTRESEND;
357         }
358         return (0);
359 }
360
361 /*
362  * NFS disconnect. Clean up and unlink.
363  */
364 void
365 nfs_disconnect(struct nfsmount *nmp)
366 {
367         struct socket *so;
368
369         if (nmp->nm_so) {
370                 so = nmp->nm_so;
371                 nmp->nm_so = (struct socket *)0;
372                 soshutdown(so, 2);
373                 soclose(so);
374         }
375 }
376
377 void
378 nfs_safedisconnect(struct nfsmount *nmp)
379 {
380         struct nfsreq dummyreq;
381
382         bzero(&dummyreq, sizeof(dummyreq));
383         dummyreq.r_nmp = nmp;
384         nfs_rcvlock(&dummyreq);
385         nfs_disconnect(nmp);
386         nfs_rcvunlock(&dummyreq);
387 }
388
389 /*
390  * This is the nfs send routine. For connection based socket types, it
391  * must be called with an nfs_sndlock() on the socket.
392  * - return EINTR if the RPC is terminated, 0 otherwise
393  * - set R_MUSTRESEND if the send fails for any reason
394  * - do any cleanup required by recoverable socket errors (?)
395  */
396 int
397 nfs_send(struct socket *so, struct sockaddr *nam, struct mbuf *top,
398     struct nfsreq *rep)
399 {
400         struct sockaddr *sendnam;
401         int error, soflags, flags;
402
403         KASSERT(rep, ("nfs_send: called with rep == NULL"));
404
405         if (rep->r_flags & R_SOFTTERM) {
406                 m_freem(top);
407                 return (EINTR);
408         }
409         if ((so = rep->r_nmp->nm_so) == NULL) {
410                 rep->r_flags |= R_MUSTRESEND;
411                 m_freem(top);
412                 return (0);
413         }
414         rep->r_flags &= ~R_MUSTRESEND;
415         soflags = rep->r_nmp->nm_soflags;
416
417         if ((soflags & PR_CONNREQUIRED) || (so->so_state & SS_ISCONNECTED))
418                 sendnam = (struct sockaddr *)0;
419         else
420                 sendnam = nam;
421         if (so->so_type == SOCK_SEQPACKET)
422                 flags = MSG_EOR;
423         else
424                 flags = 0;
425
426         error = so->so_proto->pr_usrreqs->pru_sosend(so, sendnam, 0, top, 0,
427                                                      flags, curthread /*XXX*/);
428         if (error == ENOBUFS && so->so_type == SOCK_DGRAM) {
429                 error = 0;
430                 rep->r_flags |= R_MUSTRESEND;
431         }
432
433         if (error) {
434                 log(LOG_INFO, "nfs send error %d for server %s\n", error,
435                     rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
436                 /*
437                  * Deal with errors for the client side.
438                  */
439                 if (rep->r_flags & R_SOFTTERM)
440                         error = EINTR;
441                 else
442                         rep->r_flags |= R_MUSTRESEND;
443
444                 /*
445                  * Handle any recoverable (soft) socket errors here. (?)
446                  */
447                 if (error != EINTR && error != ERESTART &&
448                         error != EWOULDBLOCK && error != EPIPE)
449                         error = 0;
450         }
451         return (error);
452 }
453
454 /*
455  * Receive a Sun RPC Request/Reply. For SOCK_DGRAM, the work is all
456  * done by soreceive(), but for SOCK_STREAM we must deal with the Record
457  * Mark and consolidate the data into a new mbuf list.
458  * nb: Sometimes TCP passes the data up to soreceive() in long lists of
459  *     small mbufs.
460  * For SOCK_STREAM we must be very careful to read an entire record once
461  * we have read any of it, even if the system call has been interrupted.
462  */
463 static int
464 nfs_receive(struct nfsreq *rep, struct sockaddr **aname, struct mbuf **mp)
465 {
466         struct socket *so;
467         struct uio auio;
468         struct iovec aio;
469         struct mbuf *m;
470         struct mbuf *control;
471         u_int32_t len;
472         struct sockaddr **getnam;
473         int error, sotype, rcvflg;
474         struct thread *td = curthread;  /* XXX */
475
476         /*
477          * Set up arguments for soreceive()
478          */
479         *mp = (struct mbuf *)0;
480         *aname = (struct sockaddr *)0;
481         sotype = rep->r_nmp->nm_sotype;
482
483         /*
484          * For reliable protocols, lock against other senders/receivers
485          * in case a reconnect is necessary.
486          * For SOCK_STREAM, first get the Record Mark to find out how much
487          * more there is to get.
488          * We must lock the socket against other receivers
489          * until we have an entire rpc request/reply.
490          */
491         if (sotype != SOCK_DGRAM) {
492                 error = nfs_sndlock(rep);
493                 if (error)
494                         return (error);
495 tryagain:
496                 /*
497                  * Check for fatal errors and resending request.
498                  */
499                 /*
500                  * Ugh: If a reconnect attempt just happened, nm_so
501                  * would have changed. NULL indicates a failed
502                  * attempt that has essentially shut down this
503                  * mount point.
504                  */
505                 if (rep->r_mrep || (rep->r_flags & R_SOFTTERM)) {
506                         nfs_sndunlock(rep);
507                         return (EINTR);
508                 }
509                 so = rep->r_nmp->nm_so;
510                 if (!so) {
511                         error = nfs_reconnect(rep);
512                         if (error) {
513                                 nfs_sndunlock(rep);
514                                 return (error);
515                         }
516                         goto tryagain;
517                 }
518                 while (rep->r_flags & R_MUSTRESEND) {
519                         m = m_copym(rep->r_mreq, 0, M_COPYALL, M_TRYWAIT);
520                         nfsstats.rpcretries++;
521                         error = nfs_send(so, rep->r_nmp->nm_nam, m, rep);
522                         if (error) {
523                                 if (error == EINTR || error == ERESTART ||
524                                     (error = nfs_reconnect(rep)) != 0) {
525                                         nfs_sndunlock(rep);
526                                         return (error);
527                                 }
528                                 goto tryagain;
529                         }
530                 }
531                 nfs_sndunlock(rep);
532                 if (sotype == SOCK_STREAM) {
533                         aio.iov_base = (caddr_t) &len;
534                         aio.iov_len = sizeof(u_int32_t);
535                         auio.uio_iov = &aio;
536                         auio.uio_iovcnt = 1;
537                         auio.uio_segflg = UIO_SYSSPACE;
538                         auio.uio_rw = UIO_READ;
539                         auio.uio_offset = 0;
540                         auio.uio_resid = sizeof(u_int32_t);
541                         auio.uio_td = td;
542                         do {
543                            rcvflg = MSG_WAITALL;
544                            error = so->so_proto->pr_usrreqs->pru_soreceive
545                                    (so, (struct sockaddr **)0, &auio,
546                                     (struct mbuf **)0, (struct mbuf **)0,
547                                     &rcvflg);
548                            if (error == EWOULDBLOCK && rep) {
549                                 if (rep->r_flags & R_SOFTTERM)
550                                         return (EINTR);
551                            }
552                         } while (error == EWOULDBLOCK);
553                         if (!error && auio.uio_resid > 0) {
554                             /*
555                              * Don't log a 0 byte receive; it means
556                              * that the socket has been closed, and
557                              * can happen during normal operation
558                              * (forcible unmount or Solaris server).
559                              */
560                             if (auio.uio_resid != sizeof (u_int32_t))
561                             log(LOG_INFO,
562                                  "short receive (%d/%d) from nfs server %s\n",
563                                  (int)(sizeof(u_int32_t) - auio.uio_resid),
564                                  (int)sizeof(u_int32_t),
565                                  rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
566                             error = EPIPE;
567                         }
568                         if (error)
569                                 goto errout;
570                         len = ntohl(len) & ~0x80000000;
571                         /*
572                          * This is SERIOUS! We are out of sync with the sender
573                          * and forcing a disconnect/reconnect is all I can do.
574                          */
575                         if (len > NFS_MAXPACKET) {
576                             log(LOG_ERR, "%s (%d) from nfs server %s\n",
577                                 "impossible packet length",
578                                 len,
579                                 rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
580                             error = EFBIG;
581                             goto errout;
582                         }
583                         auio.uio_resid = len;
584                         do {
585                             rcvflg = MSG_WAITALL;
586                             error =  so->so_proto->pr_usrreqs->pru_soreceive
587                                     (so, (struct sockaddr **)0,
588                                      &auio, mp, (struct mbuf **)0, &rcvflg);
589                         } while (error == EWOULDBLOCK || error == EINTR ||
590                                  error == ERESTART);
591                         if (!error && auio.uio_resid > 0) {
592                             if (len != auio.uio_resid)
593                             log(LOG_INFO,
594                                 "short receive (%d/%d) from nfs server %s\n",
595                                 len - auio.uio_resid, len,
596                                 rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
597                             error = EPIPE;
598                         }
599                 } else {
600                         /*
601                          * NB: Since uio_resid is big, MSG_WAITALL is ignored
602                          * and soreceive() will return when it has either a
603                          * control msg or a data msg.
604                          * We have no use for control msg., but must grab them
605                          * and then throw them away so we know what is going
606                          * on.
607                          */
608                         auio.uio_resid = len = 100000000; /* Anything Big */
609                         auio.uio_td = td;
610                         do {
611                             rcvflg = 0;
612                             error =  so->so_proto->pr_usrreqs->pru_soreceive
613                                     (so, (struct sockaddr **)0,
614                                 &auio, mp, &control, &rcvflg);
615                             if (control)
616                                 m_freem(control);
617                             if (error == EWOULDBLOCK && rep) {
618                                 if (rep->r_flags & R_SOFTTERM)
619                                         return (EINTR);
620                             }
621                         } while (error == EWOULDBLOCK ||
622                                  (!error && *mp == NULL && control));
623                         if ((rcvflg & MSG_EOR) == 0)
624                                 printf("Egad!!\n");
625                         if (!error && *mp == NULL)
626                                 error = EPIPE;
627                         len -= auio.uio_resid;
628                 }
629 errout:
630                 if (error && error != EINTR && error != ERESTART) {
631                         m_freem(*mp);
632                         *mp = (struct mbuf *)0;
633                         if (error != EPIPE)
634                                 log(LOG_INFO,
635                                     "receive error %d from nfs server %s\n",
636                                     error,
637                                  rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
638                         error = nfs_sndlock(rep);
639                         if (!error)
640                                 error = nfs_reconnect(rep);
641                         if (!error)
642                                 goto tryagain;
643                         else
644                                 nfs_sndunlock(rep);
645                 }
646         } else {
647                 if ((so = rep->r_nmp->nm_so) == NULL)
648                         return (EACCES);
649                 if (so->so_state & SS_ISCONNECTED)
650                         getnam = (struct sockaddr **)0;
651                 else
652                         getnam = aname;
653                 auio.uio_resid = len = 1000000;
654                 auio.uio_td = td;
655                 do {
656                         rcvflg = 0;
657                         error =  so->so_proto->pr_usrreqs->pru_soreceive
658                                 (so, getnam, &auio, mp,
659                                 (struct mbuf **)0, &rcvflg);
660                         if (error == EWOULDBLOCK &&
661                             (rep->r_flags & R_SOFTTERM))
662                                 return (EINTR);
663                 } while (error == EWOULDBLOCK);
664                 len -= auio.uio_resid;
665         }
666         if (error) {
667                 m_freem(*mp);
668                 *mp = (struct mbuf *)0;
669         }
670         /*
671          * Search for any mbufs that are not a multiple of 4 bytes long
672          * or with m_data not longword aligned.
673          * These could cause pointer alignment problems, so copy them to
674          * well aligned mbufs.
675          */
676         nfs_realign(mp, 5 * NFSX_UNSIGNED);
677         return (error);
678 }
679
680 /*
681  * Implement receipt of reply on a socket.
682  * We must search through the list of received datagrams matching them
683  * with outstanding requests using the xid, until ours is found.
684  */
685 /* ARGSUSED */
686 static int
687 nfs_reply(struct nfsreq *myrep)
688 {
689         struct nfsreq *rep;
690         struct nfsmount *nmp = myrep->r_nmp;
691         int32_t t1;
692         struct mbuf *mrep, *md;
693         struct sockaddr *nam;
694         u_int32_t rxid, *tl;
695         caddr_t dpos;
696         int error;
697
698         /*
699          * Loop around until we get our own reply
700          */
701         for (;;) {
702                 /*
703                  * Lock against other receivers so that I don't get stuck in
704                  * sbwait() after someone else has received my reply for me.
705                  * Also necessary for connection based protocols to avoid
706                  * race conditions during a reconnect.
707                  * If nfs_rcvlock() returns EALREADY, that means that
708                  * the reply has already been recieved by another
709                  * process and we can return immediately.  In this
710                  * case, the lock is not taken to avoid races with
711                  * other processes.
712                  */
713                 error = nfs_rcvlock(myrep);
714                 if (error == EALREADY)
715                         return (0);
716                 if (error)
717                         return (error);
718                 /*
719                  * Get the next Rpc reply off the socket
720                  */
721                 error = nfs_receive(myrep, &nam, &mrep);
722                 nfs_rcvunlock(myrep);
723                 if (error) {
724
725                         /*
726                          * Ignore routing errors on connectionless protocols??
727                          */
728                         if (NFSIGNORE_SOERROR(nmp->nm_soflags, error)) {
729                                 nmp->nm_so->so_error = 0;
730                                 if (myrep->r_flags & R_GETONEREP)
731                                         return (0);
732                                 continue;
733                         }
734                         return (error);
735                 }
736                 if (nam)
737                         FREE(nam, M_SONAME);
738
739                 /*
740                  * Get the xid and check that it is an rpc reply
741                  */
742                 md = mrep;
743                 dpos = mtod(md, caddr_t);
744                 tl = nfsm_dissect(u_int32_t *, 2 * NFSX_UNSIGNED);
745                 rxid = *tl++;
746                 if (*tl != rpc_reply) {
747                         nfsstats.rpcinvalid++;
748                         m_freem(mrep);
749 nfsmout:
750                         if (myrep->r_flags & R_GETONEREP)
751                                 return (0);
752                         continue;
753                 }
754
755                 /*
756                  * Loop through the request list to match up the reply
757                  * Iff no match, just drop the datagram
758                  */
759                 TAILQ_FOREACH(rep, &nfs_reqq, r_chain) {
760                         if (rep->r_mrep == NULL && rxid == rep->r_xid) {
761                                 /* Found it.. */
762                                 rep->r_mrep = mrep;
763                                 rep->r_md = md;
764                                 rep->r_dpos = dpos;
765                                 /*
766                                  * Update congestion window.
767                                  * Do the additive increase of
768                                  * one rpc/rtt.
769                                  */
770                                 if (nmp->nm_cwnd <= nmp->nm_sent) {
771                                         nmp->nm_cwnd +=
772                                            (NFS_CWNDSCALE * NFS_CWNDSCALE +
773                                            (nmp->nm_cwnd >> 1)) / nmp->nm_cwnd;
774                                         if (nmp->nm_cwnd > NFS_MAXCWND)
775                                                 nmp->nm_cwnd = NFS_MAXCWND;
776                                 }
777                                 if (rep->r_flags & R_SENT) {
778                                         rep->r_flags &= ~R_SENT;
779                                         nmp->nm_sent -= NFS_CWNDSCALE;
780                                 }
781                                 /*
782                                  * Update rtt using a gain of 0.125 on the mean
783                                  * and a gain of 0.25 on the deviation.
784                                  */
785                                 if (rep->r_flags & R_TIMING) {
786                                         /*
787                                          * Since the timer resolution of
788                                          * NFS_HZ is so course, it can often
789                                          * result in r_rtt == 0. Since
790                                          * r_rtt == N means that the actual
791                                          * rtt is between N+dt and N+2-dt ticks,
792                                          * add 1.
793                                          */
794                                         t1 = rep->r_rtt + 1;
795                                         t1 -= (NFS_SRTT(rep) >> 3);
796                                         NFS_SRTT(rep) += t1;
797                                         if (t1 < 0)
798                                                 t1 = -t1;
799                                         t1 -= (NFS_SDRTT(rep) >> 2);
800                                         NFS_SDRTT(rep) += t1;
801                                 }
802                                 nmp->nm_timeouts = 0;
803                                 break;
804                         }
805                 }
806                 /*
807                  * If not matched to a request, drop it.
808                  * If it's mine, get out.
809                  */
810                 if (rep == 0) {
811                         nfsstats.rpcunexpected++;
812                         m_freem(mrep);
813                 } else if (rep == myrep) {
814                         if (rep->r_mrep == NULL)
815                                 panic("nfsreply nil");
816                         return (0);
817                 }
818                 if (myrep->r_flags & R_GETONEREP)
819                         return (0);
820         }
821 }
822
823 /*
824  * nfs_request - goes something like this
825  *      - fill in request struct
826  *      - links it into list
827  *      - calls nfs_send() for first transmit
828  *      - calls nfs_receive() to get reply
829  *      - break down rpc header and return with nfs reply pointed to
830  *        by mrep or error
831  * nb: always frees up mreq mbuf list
832  */
833 /* XXX overloaded before */
834 #define NQ_TRYLATERDEL  15      /* Initial try later delay (sec) */
835
836 int
837 nfs_request(struct vnode *vp, struct mbuf *mrest, int procnum,
838     struct thread *td, struct ucred *cred, struct mbuf **mrp,
839     struct mbuf **mdp, caddr_t *dposp)
840 {
841         struct mbuf *mrep, *m2;
842         struct nfsreq *rep;
843         u_int32_t *tl;
844         int i;
845         struct nfsmount *nmp;
846         struct mbuf *m, *md, *mheadend;
847         time_t waituntil;
848         caddr_t dpos;
849         int s, error = 0, mrest_len, auth_len, auth_type;
850         int trylater_delay = NQ_TRYLATERDEL, trylater_cnt = 0;
851         u_int32_t xid;
852
853         /* Reject requests while attempting to unmount. */
854         if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNT) {
855                 m_freem(mrest);
856                 return (ESTALE);
857         }
858         nmp = VFSTONFS(vp->v_mount);
859         MALLOC(rep, struct nfsreq *, sizeof(struct nfsreq), M_NFSREQ, M_WAITOK);
860         rep->r_nmp = nmp;
861         rep->r_vp = vp;
862         rep->r_td = td;
863         rep->r_procnum = procnum;
864         i = 0;
865         m = mrest;
866         while (m) {
867                 i += m->m_len;
868                 m = m->m_next;
869         }
870         mrest_len = i;
871
872         /*
873          * Get the RPC header with authorization.
874          */
875         auth_type = RPCAUTH_UNIX;
876         if (cred->cr_ngroups < 1)
877                 panic("nfsreq nogrps");
878         auth_len = ((((cred->cr_ngroups - 1) > nmp->nm_numgrps) ?
879                 nmp->nm_numgrps : (cred->cr_ngroups - 1)) << 2) +
880                 5 * NFSX_UNSIGNED;
881         m = nfsm_rpchead(cred, nmp->nm_flag, procnum, auth_type, auth_len,
882              mrest, mrest_len, &mheadend, &xid);
883
884         /*
885          * For stream protocols, insert a Sun RPC Record Mark.
886          */
887         if (nmp->nm_sotype == SOCK_STREAM) {
888                 M_PREPEND(m, NFSX_UNSIGNED, M_TRYWAIT);
889                 *mtod(m, u_int32_t *) = htonl(0x80000000 |
890                          (m->m_pkthdr.len - NFSX_UNSIGNED));
891         }
892         rep->r_mreq = m;
893         rep->r_xid = xid;
894 tryagain:
895         if (nmp->nm_flag & NFSMNT_SOFT)
896                 rep->r_retry = nmp->nm_retry;
897         else
898                 rep->r_retry = NFS_MAXREXMIT + 1;       /* past clip limit */
899         rep->r_rtt = rep->r_rexmit = 0;
900         if (proct[procnum] > 0)
901                 rep->r_flags = R_TIMING;
902         else
903                 rep->r_flags = 0;
904         rep->r_mrep = NULL;
905
906         /*
907          * Do the client side RPC.
908          */
909         nfsstats.rpcrequests++;
910         /*
911          * Chain request into list of outstanding requests. Be sure
912          * to put it LAST so timer finds oldest requests first.
913          */
914         s = splsoftclock();
915         TAILQ_INSERT_TAIL(&nfs_reqq, rep, r_chain);
916
917         /*
918          * If backing off another request or avoiding congestion, don't
919          * send this one now but let timer do it. If not timing a request,
920          * do it now.
921          */
922         if (nmp->nm_so && (nmp->nm_sotype != SOCK_DGRAM ||
923                 (nmp->nm_flag & NFSMNT_DUMBTIMR) ||
924                 nmp->nm_sent < nmp->nm_cwnd)) {
925                 splx(s);
926                 if (nmp->nm_soflags & PR_CONNREQUIRED)
927                         error = nfs_sndlock(rep);
928                 if (!error) {
929                         m2 = m_copym(m, 0, M_COPYALL, M_TRYWAIT);
930                         error = nfs_send(nmp->nm_so, nmp->nm_nam, m2, rep);
931                         if (nmp->nm_soflags & PR_CONNREQUIRED)
932                                 nfs_sndunlock(rep);
933                 }
934                 if (!error && (rep->r_flags & R_MUSTRESEND) == 0) {
935                         nmp->nm_sent += NFS_CWNDSCALE;
936                         rep->r_flags |= R_SENT;
937                 }
938         } else {
939                 splx(s);
940                 rep->r_rtt = -1;
941         }
942
943         /*
944          * Wait for the reply from our send or the timer's.
945          */
946         if (!error || error == EPIPE)
947                 error = nfs_reply(rep);
948
949         /*
950          * RPC done, unlink the request.
951          */
952         s = splsoftclock();
953         TAILQ_REMOVE(&nfs_reqq, rep, r_chain);
954         splx(s);
955
956         /*
957          * Decrement the outstanding request count.
958          */
959         if (rep->r_flags & R_SENT) {
960                 rep->r_flags &= ~R_SENT;        /* paranoia */
961                 nmp->nm_sent -= NFS_CWNDSCALE;
962         }
963
964         /*
965          * If there was a successful reply and a tprintf msg.
966          * tprintf a response.
967          */
968         if (!error && (rep->r_flags & R_TPRINTFMSG))
969                 nfs_msg(rep->r_td, nmp->nm_mountp->mnt_stat.f_mntfromname,
970                     "is alive again");
971         mrep = rep->r_mrep;
972         md = rep->r_md;
973         dpos = rep->r_dpos;
974         if (error) {
975                 m_freem(rep->r_mreq);
976                 free((caddr_t)rep, M_NFSREQ);
977                 return (error);
978         }
979
980         /*
981          * break down the rpc header and check if ok
982          */
983         tl = nfsm_dissect(u_int32_t *, 3 * NFSX_UNSIGNED);
984         if (*tl++ == rpc_msgdenied) {
985                 if (*tl == rpc_mismatch)
986                         error = EOPNOTSUPP;
987                 else
988                         error = EACCES;
989                 m_freem(mrep);
990                 m_freem(rep->r_mreq);
991                 free((caddr_t)rep, M_NFSREQ);
992                 return (error);
993         }
994
995         /*
996          * Just throw away any verifyer (ie: kerberos etc).
997          */
998         i = fxdr_unsigned(int, *tl++);          /* verf type */
999         i = fxdr_unsigned(int32_t, *tl);        /* len */
1000         if (i > 0)
1001                 nfsm_adv(nfsm_rndup(i));
1002         tl = nfsm_dissect(u_int32_t *, NFSX_UNSIGNED);
1003         /* 0 == ok */
1004         if (*tl == 0) {
1005                 tl = nfsm_dissect(u_int32_t *, NFSX_UNSIGNED);
1006                 if (*tl != 0) {
1007                         error = fxdr_unsigned(int, *tl);
1008                         if ((nmp->nm_flag & NFSMNT_NFSV3) &&
1009                                 error == NFSERR_TRYLATER) {
1010                                 m_freem(mrep);
1011                                 error = 0;
1012                                 waituntil = time_second + trylater_delay;
1013                                 while (time_second < waituntil)
1014                                         (void) tsleep((caddr_t)&lbolt,
1015                                                 PSOCK, "nqnfstry", 0);
1016                                 trylater_delay *= nfs_backoff[trylater_cnt];
1017                                 if (trylater_cnt < NFS_NBACKOFF - 1)
1018                                         trylater_cnt++;
1019                                 goto tryagain;
1020                         }
1021
1022                         /*
1023                          * If the File Handle was stale, invalidate the
1024                          * lookup cache, just in case.
1025                          */
1026                         if (error == ESTALE)
1027                                 cache_purge(vp);
1028                         if (nmp->nm_flag & NFSMNT_NFSV3) {
1029                                 *mrp = mrep;
1030                                 *mdp = md;
1031                                 *dposp = dpos;
1032                                 error |= NFSERR_RETERR;
1033                         } else
1034                                 m_freem(mrep);
1035                         m_freem(rep->r_mreq);
1036                         free((caddr_t)rep, M_NFSREQ);
1037                         return (error);
1038                 }
1039
1040                 *mrp = mrep;
1041                 *mdp = md;
1042                 *dposp = dpos;
1043                 m_freem(rep->r_mreq);
1044                 FREE((caddr_t)rep, M_NFSREQ);
1045                 return (0);
1046         }
1047         m_freem(mrep);
1048         error = EPROTONOSUPPORT;
1049 nfsmout:
1050         m_freem(rep->r_mreq);
1051         free((caddr_t)rep, M_NFSREQ);
1052         return (error);
1053 }
1054
1055 /*
1056  * Nfs timer routine
1057  * Scan the nfsreq list and retranmit any requests that have timed out
1058  * To avoid retransmission attempts on STREAM sockets (in the future) make
1059  * sure to set the r_retry field to 0 (implies nm_retry == 0).
1060  */
1061 void
1062 nfs_timer(void *arg)
1063 {
1064         struct nfsreq *rep;
1065         struct mbuf *m;
1066         struct socket *so;
1067         struct nfsmount *nmp;
1068         int timeo;
1069         int s, error;
1070         struct thread *td;
1071
1072         td = &thread0; /* XXX for credentials, may break if sleep */
1073         s = splnet();
1074         TAILQ_FOREACH(rep, &nfs_reqq, r_chain) {
1075                 nmp = rep->r_nmp;
1076                 if (rep->r_mrep || (rep->r_flags & R_SOFTTERM))
1077                         continue;
1078                 if (nfs_sigintr(nmp, rep,
1079                     (rep->r_td ? rep->r_td->td_proc : NULL))) {
1080                         nfs_softterm(rep);
1081                         continue;
1082                 }
1083                 if (rep->r_rtt >= 0) {
1084                         rep->r_rtt++;
1085                         if (nmp->nm_flag & NFSMNT_DUMBTIMR)
1086                                 timeo = nmp->nm_timeo;
1087                         else
1088                                 timeo = NFS_RTO(nmp, proct[rep->r_procnum]);
1089                         if (nmp->nm_timeouts > 0)
1090                                 timeo *= nfs_backoff[nmp->nm_timeouts - 1];
1091                         if (rep->r_rtt <= timeo)
1092                                 continue;
1093                         if (nmp->nm_timeouts < NFS_NBACKOFF)
1094                                 nmp->nm_timeouts++;
1095                 }
1096                 /*
1097                  * Check for server not responding
1098                  */
1099                 if ((rep->r_flags & R_TPRINTFMSG) == 0 &&
1100                      rep->r_rexmit > nmp->nm_deadthresh) {
1101                         char buf[40];
1102                         sprintf(buf, "not responding %d > %d",
1103                         rep->r_rexmit, nmp->nm_deadthresh);
1104                         nfs_msg(rep->r_td,
1105                             nmp->nm_mountp->mnt_stat.f_mntfromname,
1106                             buf /* "not responding" */);
1107                         rep->r_flags |= R_TPRINTFMSG;
1108                 }
1109                 if (rep->r_rexmit >= rep->r_retry) {    /* too many */
1110                         nfsstats.rpctimeouts++;
1111                         nfs_softterm(rep);
1112                         continue;
1113                 }
1114                 if (nmp->nm_sotype != SOCK_DGRAM) {
1115                         if (++rep->r_rexmit > NFS_MAXREXMIT)
1116                                 rep->r_rexmit = NFS_MAXREXMIT;
1117                         continue;
1118                 }
1119                 if ((so = nmp->nm_so) == NULL)
1120                         continue;
1121
1122                 /*
1123                  * If there is enough space and the window allows..
1124                  *      Resend it
1125                  * Set r_rtt to -1 in case we fail to send it now.
1126                  */
1127                 rep->r_rtt = -1;
1128                 if (sbspace(&so->so_snd) >= rep->r_mreq->m_pkthdr.len &&
1129                    ((nmp->nm_flag & NFSMNT_DUMBTIMR) ||
1130                     (rep->r_flags & R_SENT) ||
1131                     nmp->nm_sent < nmp->nm_cwnd) &&
1132                    (m = m_copym(rep->r_mreq, 0, M_COPYALL, M_DONTWAIT))){
1133                         if ((nmp->nm_flag & NFSMNT_NOCONN) == 0)
1134                             error = (*so->so_proto->pr_usrreqs->pru_send)
1135                                     (so, 0, m, (struct sockaddr *)0,
1136                                      (struct mbuf *)0, td);
1137                         else
1138                             error = (*so->so_proto->pr_usrreqs->pru_send)
1139                                     (so, 0, m, nmp->nm_nam, (struct mbuf *)0,
1140                                      td);
1141                         if (error) {
1142                                 if (NFSIGNORE_SOERROR(nmp->nm_soflags, error))
1143                                         so->so_error = 0;
1144                         } else {
1145                                 /*
1146                                  * Iff first send, start timing
1147                                  * else turn timing off, backoff timer
1148                                  * and divide congestion window by 2.
1149                                  */
1150                                 if (rep->r_flags & R_SENT) {
1151                                         rep->r_flags &= ~R_TIMING;
1152                                         if (++rep->r_rexmit > NFS_MAXREXMIT)
1153                                                 rep->r_rexmit = NFS_MAXREXMIT;
1154                                         nmp->nm_cwnd >>= 1;
1155                                         if (nmp->nm_cwnd < NFS_CWNDSCALE)
1156                                                 nmp->nm_cwnd = NFS_CWNDSCALE;
1157                                         nfsstats.rpcretries++;
1158                                 } else {
1159                                         rep->r_flags |= R_SENT;
1160                                         nmp->nm_sent += NFS_CWNDSCALE;
1161                                 }
1162                                 rep->r_rtt = 0;
1163                         }
1164                 }
1165         }
1166         splx(s);
1167         nfs_timer_handle = timeout(nfs_timer, (void *)0, nfs_ticks);
1168 }
1169
1170 /*
1171  * Mark all of an nfs mount's outstanding requests with R_SOFTTERM and
1172  * wait for all requests to complete. This is used by forced unmounts
1173  * to terminate any outstanding RPCs.
1174  */
1175 int
1176 nfs_nmcancelreqs(nmp)
1177         struct nfsmount *nmp;
1178 {
1179         struct nfsreq *req;
1180         int i, s;
1181
1182         s = splnet();
1183         TAILQ_FOREACH(req, &nfs_reqq, r_chain) {
1184                 if (nmp != req->r_nmp || req->r_mrep != NULL ||
1185                     (req->r_flags & R_SOFTTERM))
1186                         continue;
1187                 nfs_softterm(req);
1188         }
1189         splx(s);
1190
1191         for (i = 0; i < 30; i++) {
1192                 s = splnet();
1193                 TAILQ_FOREACH(req, &nfs_reqq, r_chain) {
1194                         if (nmp == req->r_nmp)
1195                                 break;
1196                 }
1197                 splx(s);
1198                 if (req == NULL)
1199                         return (0);
1200                 tsleep(&lbolt, PSOCK, "nfscancel", 0);
1201         }
1202         return (EBUSY);
1203 }
1204
1205 /*
1206  * Flag a request as being about to terminate (due to NFSMNT_INT/NFSMNT_SOFT).
1207  * The nm_send count is decremented now to avoid deadlocks when the process in
1208  * soreceive() hasn't yet managed to send its own request.
1209  */
1210
1211 static void
1212 nfs_softterm(struct nfsreq *rep)
1213 {
1214
1215         rep->r_flags |= R_SOFTTERM;
1216         if (rep->r_flags & R_SENT) {
1217                 rep->r_nmp->nm_sent -= NFS_CWNDSCALE;
1218                 rep->r_flags &= ~R_SENT;
1219         }
1220 }
1221
1222 /*
1223  * Test for a termination condition pending on the process.
1224  * This is used for NFSMNT_INT mounts.
1225  */
1226 int
1227 nfs_sigintr(struct nfsmount *nmp, struct nfsreq *rep, struct proc *p)
1228 {
1229         sigset_t tmpset;
1230
1231         if (rep && (rep->r_flags & R_SOFTTERM))
1232                 return (EINTR);
1233         /* Terminate all requests while attempting to unmount. */
1234         if (nmp->nm_mountp->mnt_kern_flag & MNTK_UNMOUNT)
1235                 return (EINTR);
1236         if (!(nmp->nm_flag & NFSMNT_INT))
1237                 return (0);
1238         if (p == NULL)
1239                 return (0);
1240
1241         tmpset = p->p_siglist;
1242         SIGSETNAND(tmpset, p->p_sigmask);
1243         SIGSETNAND(tmpset, p->p_sigignore);
1244         if (SIGNOTEMPTY(p->p_siglist) && NFSINT_SIGMASK(tmpset))
1245                 return (EINTR);
1246
1247         return (0);
1248 }
1249
1250 /*
1251  * Lock a socket against others.
1252  * Necessary for STREAM sockets to ensure you get an entire rpc request/reply
1253  * and also to avoid race conditions between the processes with nfs requests
1254  * in progress when a reconnect is necessary.
1255  */
1256 int
1257 nfs_sndlock(struct nfsreq *rep)
1258 {
1259         int *statep = &rep->r_nmp->nm_state;
1260         struct thread *td;
1261         int slpflag = 0, slptimeo = 0;
1262
1263         if (rep) {
1264                 td = rep->r_td;
1265                 if (rep->r_nmp->nm_flag & NFSMNT_INT)
1266                         slpflag = PCATCH;
1267         } else
1268                 td = (struct thread *)0;
1269         while (*statep & NFSSTA_SNDLOCK) {
1270                 if (nfs_sigintr(rep->r_nmp, rep, td ? td->td_proc : NULL))
1271                         return (EINTR);
1272                 *statep |= NFSSTA_WANTSND;
1273                 (void) tsleep((caddr_t)statep, slpflag | (PZERO - 1),
1274                         "nfsndlck", slptimeo);
1275                 if (slpflag == PCATCH) {
1276                         slpflag = 0;
1277                         slptimeo = 2 * hz;
1278                 }
1279         }
1280         *statep |= NFSSTA_SNDLOCK;
1281         return (0);
1282 }
1283
1284 /*
1285  * Unlock the stream socket for others.
1286  */
1287 void
1288 nfs_sndunlock(struct nfsreq *rep)
1289 {
1290         int *statep = &rep->r_nmp->nm_state;
1291
1292         if ((*statep & NFSSTA_SNDLOCK) == 0)
1293                 panic("nfs sndunlock");
1294         *statep &= ~NFSSTA_SNDLOCK;
1295         if (*statep & NFSSTA_WANTSND) {
1296                 *statep &= ~NFSSTA_WANTSND;
1297                 wakeup((caddr_t)statep);
1298         }
1299 }
1300
1301 static int
1302 nfs_rcvlock(struct nfsreq *rep)
1303 {
1304         int *statep = &rep->r_nmp->nm_state;
1305         int slpflag, slptimeo = 0;
1306
1307         if (rep->r_nmp->nm_flag & NFSMNT_INT)
1308                 slpflag = PCATCH;
1309         else
1310                 slpflag = 0;
1311         while (*statep & NFSSTA_RCVLOCK) {
1312                 if (nfs_sigintr(rep->r_nmp, rep,
1313                     (rep->r_td ? rep->r_td->td_proc : NULL)))
1314                         return (EINTR);
1315                 *statep |= NFSSTA_WANTRCV;
1316                 (void) tsleep((caddr_t)statep, slpflag | (PZERO - 1), "nfsrcvlk",
1317                         slptimeo);
1318                 /*
1319                  * If our reply was recieved while we were sleeping,
1320                  * then just return without taking the lock to avoid a
1321                  * situation where a single iod could 'capture' the
1322                  * recieve lock.
1323                  */
1324                 if (rep->r_mrep != NULL)
1325                         return (EALREADY);
1326                 if (slpflag == PCATCH) {
1327                         slpflag = 0;
1328                         slptimeo = 2 * hz;
1329                 }
1330         }
1331         /* Always fail if our request has been cancelled. */
1332         if (rep != NULL && (rep->r_flags & R_SOFTTERM))
1333                 return (EINTR);
1334         *statep |= NFSSTA_RCVLOCK;
1335         return (0);
1336 }
1337
1338 /*
1339  * Unlock the stream socket for others.
1340  */
1341 static void
1342 nfs_rcvunlock(struct nfsreq *rep)
1343 {
1344         int *statep = &rep->r_nmp->nm_state;
1345
1346         if ((*statep & NFSSTA_RCVLOCK) == 0)
1347                 panic("nfs rcvunlock");
1348         *statep &= ~NFSSTA_RCVLOCK;
1349         if (*statep & NFSSTA_WANTRCV) {
1350                 *statep &= ~NFSSTA_WANTRCV;
1351                 wakeup((caddr_t)statep);
1352         }
1353 }
1354
1355 /*
1356  *      nfs_realign:
1357  *
1358  *      Check for badly aligned mbuf data and realign by copying the unaligned
1359  *      portion of the data into a new mbuf chain and freeing the portions
1360  *      of the old chain that were replaced.
1361  *
1362  *      We cannot simply realign the data within the existing mbuf chain
1363  *      because the underlying buffers may contain other rpc commands and
1364  *      we cannot afford to overwrite them.
1365  *
1366  *      We would prefer to avoid this situation entirely.  The situation does
1367  *      not occur with NFS/UDP and is supposed to only occassionally occur
1368  *      with TCP.  Use vfs.nfs.realign_count and realign_test to check this.
1369  */
1370 static void
1371 nfs_realign(struct mbuf **pm, int hsiz)
1372 {
1373         struct mbuf *m;
1374         struct mbuf *n = NULL;
1375         int off = 0;
1376
1377         ++nfs_realign_test;
1378         while ((m = *pm) != NULL) {
1379                 if ((m->m_len & 0x3) || (mtod(m, intptr_t) & 0x3)) {
1380                         MGET(n, M_TRYWAIT, MT_DATA);
1381                         if (m->m_len >= MINCLSIZE) {
1382                                 MCLGET(n, M_TRYWAIT);
1383                         }
1384                         n->m_len = 0;
1385                         break;
1386                 }
1387                 pm = &m->m_next;
1388         }
1389         /*
1390          * If n is non-NULL, loop on m copying data, then replace the
1391          * portion of the chain that had to be realigned.
1392          */
1393         if (n != NULL) {
1394                 ++nfs_realign_count;
1395                 while (m) {
1396                         m_copyback(n, off, m->m_len, mtod(m, caddr_t));
1397                         off += m->m_len;
1398                         m = m->m_next;
1399                 }
1400                 m_freem(*pm);
1401                 *pm = n;
1402         }
1403 }
1404
1405
1406 static int
1407 nfs_msg(struct thread *td, char *server, char *msg)
1408 {
1409
1410         tprintf(td ? td->td_proc : NULL, LOG_INFO,
1411             "nfs server %s: %s\n", server, msg);
1412         return (0);
1413 }