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