7399d003d5838f7cdcce8201551021bd1089b115
[dragonfly.git] / sys / vfs / nfs / 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  * $FreeBSD: src/sys/nfs/nfs_socket.c,v 1.60.2.6 2003/03/26 01:44:46 alfred Exp $
38  * $DragonFly: src/sys/vfs/nfs/nfs_socket.c,v 1.45 2007/05/18 17:05:13 dillon Exp $
39  */
40
41 /*
42  * Socket operations for use by nfs
43  */
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/proc.h>
48 #include <sys/malloc.h>
49 #include <sys/mount.h>
50 #include <sys/kernel.h>
51 #include <sys/mbuf.h>
52 #include <sys/vnode.h>
53 #include <sys/fcntl.h>
54 #include <sys/protosw.h>
55 #include <sys/resourcevar.h>
56 #include <sys/socket.h>
57 #include <sys/socketvar.h>
58 #include <sys/socketops.h>
59 #include <sys/syslog.h>
60 #include <sys/thread.h>
61 #include <sys/tprintf.h>
62 #include <sys/sysctl.h>
63 #include <sys/signalvar.h>
64 #include <sys/mutex.h>
65
66 #include <sys/signal2.h>
67 #include <sys/mutex2.h>
68
69 #include <netinet/in.h>
70 #include <netinet/tcp.h>
71 #include <sys/thread2.h>
72
73 #include "rpcv2.h"
74 #include "nfsproto.h"
75 #include "nfs.h"
76 #include "xdr_subs.h"
77 #include "nfsm_subs.h"
78 #include "nfsmount.h"
79 #include "nfsnode.h"
80 #include "nfsrtt.h"
81
82 #define TRUE    1
83 #define FALSE   0
84
85 /*
86  * RTT calculations are scaled by 256 (8 bits).  A proper fractional
87  * RTT will still be calculated even with a slow NFS timer.
88  */
89 #define NFS_SRTT(r)     (r)->r_nmp->nm_srtt[proct[(r)->r_procnum]]
90 #define NFS_SDRTT(r)    (r)->r_nmp->nm_sdrtt[proct[(r)->r_procnum]]
91 #define NFS_RTT_SCALE_BITS      8       /* bits */
92 #define NFS_RTT_SCALE           256     /* value */
93
94 /*
95  * Defines which timer to use for the procnum.
96  * 0 - default
97  * 1 - getattr
98  * 2 - lookup
99  * 3 - read
100  * 4 - write
101  */
102 static int proct[NFS_NPROCS] = {
103         0, 1, 0, 2, 1, 3, 3, 4, 0, 0,   /* 00-09        */
104         0, 0, 0, 0, 0, 0, 3, 3, 0, 0,   /* 10-19        */
105         0, 5, 0, 0, 0, 0,               /* 20-29        */
106 };
107
108 static int multt[NFS_NPROCS] = {
109         1, 1, 1, 1, 1, 1, 1, 1, 1, 1,   /* 00-09        */
110         1, 1, 1, 1, 1, 1, 1, 1, 1, 1,   /* 10-19        */
111         1, 2, 1, 1, 1, 1,               /* 20-29        */
112 };
113
114 static int nfs_backoff[8] = { 2, 3, 5, 8, 13, 21, 34, 55 };
115 static int nfs_realign_test;
116 static int nfs_realign_count;
117 static int nfs_showrtt;
118 static int nfs_showrexmit;
119 int nfs_maxasyncbio = NFS_MAXASYNCBIO;
120
121 SYSCTL_DECL(_vfs_nfs);
122
123 SYSCTL_INT(_vfs_nfs, OID_AUTO, realign_test, CTLFLAG_RW, &nfs_realign_test, 0, "");
124 SYSCTL_INT(_vfs_nfs, OID_AUTO, realign_count, CTLFLAG_RW, &nfs_realign_count, 0, "");
125 SYSCTL_INT(_vfs_nfs, OID_AUTO, showrtt, CTLFLAG_RW, &nfs_showrtt, 0, "");
126 SYSCTL_INT(_vfs_nfs, OID_AUTO, showrexmit, CTLFLAG_RW, &nfs_showrexmit, 0, "");
127 SYSCTL_INT(_vfs_nfs, OID_AUTO, maxasyncbio, CTLFLAG_RW, &nfs_maxasyncbio, 0, "");
128
129 static int nfs_request_setup(nfsm_info_t info);
130 static int nfs_request_auth(struct nfsreq *rep);
131 static int nfs_request_try(struct nfsreq *rep);
132 static int nfs_request_waitreply(struct nfsreq *rep);
133 static int nfs_request_processreply(nfsm_info_t info, int);
134
135 int nfsrtton = 0;
136 struct nfsrtt nfsrtt;
137 struct callout  nfs_timer_handle;
138
139 static int      nfs_msg (struct thread *,char *,char *);
140 static int      nfs_rcvlock (struct nfsmount *nmp, struct nfsreq *myreq);
141 static void     nfs_rcvunlock (struct nfsmount *nmp);
142 static void     nfs_realign (struct mbuf **pm, int hsiz);
143 static int      nfs_receive (struct nfsmount *nmp, struct nfsreq *rep,
144                                 struct sockaddr **aname, struct mbuf **mp);
145 static void     nfs_softterm (struct nfsreq *rep, int islocked);
146 static void     nfs_hardterm (struct nfsreq *rep, int islocked);
147 static int      nfs_reconnect (struct nfsmount *nmp, struct nfsreq *rep);
148 #ifndef NFS_NOSERVER 
149 static int      nfsrv_getstream (struct nfssvc_sock *, int, int *);
150 static void     nfs_timer_req(struct nfsreq *req);
151
152 int (*nfsrv3_procs[NFS_NPROCS]) (struct nfsrv_descript *nd,
153                                     struct nfssvc_sock *slp,
154                                     struct thread *td,
155                                     struct mbuf **mreqp) = {
156         nfsrv_null,
157         nfsrv_getattr,
158         nfsrv_setattr,
159         nfsrv_lookup,
160         nfsrv3_access,
161         nfsrv_readlink,
162         nfsrv_read,
163         nfsrv_write,
164         nfsrv_create,
165         nfsrv_mkdir,
166         nfsrv_symlink,
167         nfsrv_mknod,
168         nfsrv_remove,
169         nfsrv_rmdir,
170         nfsrv_rename,
171         nfsrv_link,
172         nfsrv_readdir,
173         nfsrv_readdirplus,
174         nfsrv_statfs,
175         nfsrv_fsinfo,
176         nfsrv_pathconf,
177         nfsrv_commit,
178         nfsrv_noop,
179         nfsrv_noop,
180         nfsrv_noop,
181         nfsrv_noop
182 };
183 #endif /* NFS_NOSERVER */
184
185 /*
186  * Initialize sockets and congestion for a new NFS connection.
187  * We do not free the sockaddr if error.
188  */
189 int
190 nfs_connect(struct nfsmount *nmp, struct nfsreq *rep)
191 {
192         struct socket *so;
193         int error;
194         struct sockaddr *saddr;
195         struct sockaddr_in *sin;
196         struct thread *td = &thread0; /* only used for socreate and sobind */
197
198         nmp->nm_so = so = NULL;
199         if (nmp->nm_flag & NFSMNT_FORCE)
200                 return (EINVAL);
201         saddr = nmp->nm_nam;
202         error = socreate(saddr->sa_family, &so, nmp->nm_sotype,
203                 nmp->nm_soproto, td);
204         if (error)
205                 goto bad;
206         nmp->nm_soflags = so->so_proto->pr_flags;
207
208         /*
209          * Some servers require that the client port be a reserved port number.
210          */
211         if (saddr->sa_family == AF_INET && (nmp->nm_flag & NFSMNT_RESVPORT)) {
212                 struct sockopt sopt;
213                 int ip;
214                 struct sockaddr_in ssin;
215
216                 bzero(&sopt, sizeof sopt);
217                 ip = IP_PORTRANGE_LOW;
218                 sopt.sopt_level = IPPROTO_IP;
219                 sopt.sopt_name = IP_PORTRANGE;
220                 sopt.sopt_val = (void *)&ip;
221                 sopt.sopt_valsize = sizeof(ip);
222                 sopt.sopt_td = NULL;
223                 error = sosetopt(so, &sopt);
224                 if (error)
225                         goto bad;
226                 bzero(&ssin, sizeof ssin);
227                 sin = &ssin;
228                 sin->sin_len = sizeof (struct sockaddr_in);
229                 sin->sin_family = AF_INET;
230                 sin->sin_addr.s_addr = INADDR_ANY;
231                 sin->sin_port = htons(0);
232                 error = sobind(so, (struct sockaddr *)sin, td);
233                 if (error)
234                         goto bad;
235                 bzero(&sopt, sizeof sopt);
236                 ip = IP_PORTRANGE_DEFAULT;
237                 sopt.sopt_level = IPPROTO_IP;
238                 sopt.sopt_name = IP_PORTRANGE;
239                 sopt.sopt_val = (void *)&ip;
240                 sopt.sopt_valsize = sizeof(ip);
241                 sopt.sopt_td = NULL;
242                 error = sosetopt(so, &sopt);
243                 if (error)
244                         goto bad;
245         }
246
247         /*
248          * Protocols that do not require connections may be optionally left
249          * unconnected for servers that reply from a port other than NFS_PORT.
250          */
251         if (nmp->nm_flag & NFSMNT_NOCONN) {
252                 if (nmp->nm_soflags & PR_CONNREQUIRED) {
253                         error = ENOTCONN;
254                         goto bad;
255                 }
256         } else {
257                 error = soconnect(so, nmp->nm_nam, td);
258                 if (error)
259                         goto bad;
260
261                 /*
262                  * Wait for the connection to complete. Cribbed from the
263                  * connect system call but with the wait timing out so
264                  * that interruptible mounts don't hang here for a long time.
265                  */
266                 crit_enter();
267                 while ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
268                         (void) tsleep((caddr_t)&so->so_timeo, 0,
269                                 "nfscon", 2 * hz);
270                         if ((so->so_state & SS_ISCONNECTING) &&
271                             so->so_error == 0 && rep &&
272                             (error = nfs_sigintr(nmp, rep, rep->r_td)) != 0){
273                                 so->so_state &= ~SS_ISCONNECTING;
274                                 crit_exit();
275                                 goto bad;
276                         }
277                 }
278                 if (so->so_error) {
279                         error = so->so_error;
280                         so->so_error = 0;
281                         crit_exit();
282                         goto bad;
283                 }
284                 crit_exit();
285         }
286         so->so_rcv.ssb_timeo = (5 * hz);
287         so->so_snd.ssb_timeo = (5 * hz);
288
289         /*
290          * Get buffer reservation size from sysctl, but impose reasonable
291          * limits.
292          */
293         if (nmp->nm_sotype == SOCK_STREAM) {
294                 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
295                         struct sockopt sopt;
296                         int val;
297
298                         bzero(&sopt, sizeof sopt);
299                         sopt.sopt_level = SOL_SOCKET;
300                         sopt.sopt_name = SO_KEEPALIVE;
301                         sopt.sopt_val = &val;
302                         sopt.sopt_valsize = sizeof val;
303                         val = 1;
304                         sosetopt(so, &sopt);
305                 }
306                 if (so->so_proto->pr_protocol == IPPROTO_TCP) {
307                         struct sockopt sopt;
308                         int val;
309
310                         bzero(&sopt, sizeof sopt);
311                         sopt.sopt_level = IPPROTO_TCP;
312                         sopt.sopt_name = TCP_NODELAY;
313                         sopt.sopt_val = &val;
314                         sopt.sopt_valsize = sizeof val;
315                         val = 1;
316                         sosetopt(so, &sopt);
317                 }
318         }
319         error = soreserve(so, nfs_soreserve, nfs_soreserve, NULL);
320         if (error)
321                 goto bad;
322         so->so_rcv.ssb_flags |= SSB_NOINTR;
323         so->so_snd.ssb_flags |= SSB_NOINTR;
324
325         /* Initialize other non-zero congestion variables */
326         nmp->nm_srtt[0] = nmp->nm_srtt[1] = nmp->nm_srtt[2] = 
327                 nmp->nm_srtt[3] = (NFS_TIMEO << NFS_RTT_SCALE_BITS);
328         nmp->nm_sdrtt[0] = nmp->nm_sdrtt[1] = nmp->nm_sdrtt[2] =
329                 nmp->nm_sdrtt[3] = 0;
330         nmp->nm_maxasync_scaled = NFS_MINASYNC_SCALED;
331         nmp->nm_timeouts = 0;
332
333         /*
334          * Assign nm_so last.  The moment nm_so is assigned the nfs_timer()
335          * can mess with the socket.
336          */
337         nmp->nm_so = so;
338         return (0);
339
340 bad:
341         if (so) {
342                 soshutdown(so, SHUT_RDWR);
343                 soclose(so, FNONBLOCK);
344         }
345         return (error);
346 }
347
348 /*
349  * Reconnect routine:
350  * Called when a connection is broken on a reliable protocol.
351  * - clean up the old socket
352  * - nfs_connect() again
353  * - set R_NEEDSXMIT for all outstanding requests on mount point
354  * If this fails the mount point is DEAD!
355  * nb: Must be called with the nfs_sndlock() set on the mount point.
356  */
357 static int
358 nfs_reconnect(struct nfsmount *nmp, struct nfsreq *rep)
359 {
360         struct nfsreq *req;
361         int error;
362
363         nfs_disconnect(nmp);
364         if (nmp->nm_rxstate >= NFSSVC_STOPPING)
365                 return (EINTR);
366         while ((error = nfs_connect(nmp, rep)) != 0) {
367                 if (error == EINTR || error == ERESTART)
368                         return (EINTR);
369                 if (error == EINVAL)
370                         return (error);
371                 if (nmp->nm_rxstate >= NFSSVC_STOPPING)
372                         return (EINTR);
373                 (void) tsleep((caddr_t)&lbolt, 0, "nfscon", 0);
374         }
375
376         /*
377          * Loop through outstanding request list and fix up all requests
378          * on old socket.
379          */
380         crit_enter();
381         TAILQ_FOREACH(req, &nmp->nm_reqq, r_chain) {
382                 KKASSERT(req->r_nmp == nmp);
383                 req->r_flags |= R_NEEDSXMIT;
384         }
385         crit_exit();
386         return (0);
387 }
388
389 /*
390  * NFS disconnect. Clean up and unlink.
391  */
392 void
393 nfs_disconnect(struct nfsmount *nmp)
394 {
395         struct socket *so;
396
397         if (nmp->nm_so) {
398                 so = nmp->nm_so;
399                 nmp->nm_so = NULL;
400                 soshutdown(so, SHUT_RDWR);
401                 soclose(so, FNONBLOCK);
402         }
403 }
404
405 void
406 nfs_safedisconnect(struct nfsmount *nmp)
407 {
408         nfs_rcvlock(nmp, NULL);
409         nfs_disconnect(nmp);
410         nfs_rcvunlock(nmp);
411 }
412
413 /*
414  * This is the nfs send routine. For connection based socket types, it
415  * must be called with an nfs_sndlock() on the socket.
416  * "rep == NULL" indicates that it has been called from a server.
417  * For the client side:
418  * - return EINTR if the RPC is terminated, 0 otherwise
419  * - set R_NEEDSXMIT if the send fails for any reason
420  * - do any cleanup required by recoverable socket errors (?)
421  * For the server side:
422  * - return EINTR or ERESTART if interrupted by a signal
423  * - return EPIPE if a connection is lost for connection based sockets (TCP...)
424  * - do any cleanup required by recoverable socket errors (?)
425  */
426 int
427 nfs_send(struct socket *so, struct sockaddr *nam, struct mbuf *top,
428          struct nfsreq *rep)
429 {
430         struct sockaddr *sendnam;
431         int error, soflags, flags;
432
433         if (rep) {
434                 if (rep->r_flags & R_SOFTTERM) {
435                         m_freem(top);
436                         return (EINTR);
437                 }
438                 if ((so = rep->r_nmp->nm_so) == NULL) {
439                         rep->r_flags |= R_NEEDSXMIT;
440                         m_freem(top);
441                         return (0);
442                 }
443                 rep->r_flags &= ~R_NEEDSXMIT;
444                 soflags = rep->r_nmp->nm_soflags;
445         } else {
446                 soflags = so->so_proto->pr_flags;
447         }
448         if ((soflags & PR_CONNREQUIRED) || (so->so_state & SS_ISCONNECTED))
449                 sendnam = NULL;
450         else
451                 sendnam = nam;
452         if (so->so_type == SOCK_SEQPACKET)
453                 flags = MSG_EOR;
454         else
455                 flags = 0;
456
457         error = so_pru_sosend(so, sendnam, NULL, top, NULL, flags,
458             curthread /*XXX*/);
459         /*
460          * ENOBUFS for dgram sockets is transient and non fatal.
461          * No need to log, and no need to break a soft mount.
462          */
463         if (error == ENOBUFS && so->so_type == SOCK_DGRAM) {
464                 error = 0;
465                 /*
466                  * do backoff retransmit on client
467                  */
468                 if (rep) {
469                         if ((rep->r_nmp->nm_state & NFSSTA_SENDSPACE) == 0) {
470                                 rep->r_nmp->nm_state |= NFSSTA_SENDSPACE;
471                                 kprintf("Warning: NFS: Insufficient sendspace "
472                                         "(%lu),\n"
473                                         "\t You must increase vfs.nfs.soreserve"
474                                         "or decrease vfs.nfs.maxasyncbio\n",
475                                         so->so_snd.ssb_hiwat);
476                         }
477                         rep->r_flags |= R_NEEDSXMIT;
478                 }
479         }
480
481         if (error) {
482                 if (rep) {
483                         log(LOG_INFO, "nfs send error %d for server %s\n",error,
484                             rep->r_nmp->nm_mountp->mnt_stat.f_mntfromname);
485                         /*
486                          * Deal with errors for the client side.
487                          */
488                         if (rep->r_flags & R_SOFTTERM)
489                                 error = EINTR;
490                         else
491                                 rep->r_flags |= R_NEEDSXMIT;
492                 } else {
493                         log(LOG_INFO, "nfsd send error %d\n", error);
494                 }
495
496                 /*
497                  * Handle any recoverable (soft) socket errors here. (?)
498                  */
499                 if (error != EINTR && error != ERESTART &&
500                         error != EWOULDBLOCK && error != EPIPE)
501                         error = 0;
502         }
503         return (error);
504 }
505
506 /*
507  * Receive a Sun RPC Request/Reply. For SOCK_DGRAM, the work is all
508  * done by soreceive(), but for SOCK_STREAM we must deal with the Record
509  * Mark and consolidate the data into a new mbuf list.
510  * nb: Sometimes TCP passes the data up to soreceive() in long lists of
511  *     small mbufs.
512  * For SOCK_STREAM we must be very careful to read an entire record once
513  * we have read any of it, even if the system call has been interrupted.
514  */
515 static int
516 nfs_receive(struct nfsmount *nmp, struct nfsreq *rep,
517             struct sockaddr **aname, struct mbuf **mp)
518 {
519         struct socket *so;
520         struct sockbuf sio;
521         struct uio auio;
522         struct iovec aio;
523         struct mbuf *m;
524         struct mbuf *control;
525         u_int32_t len;
526         struct sockaddr **getnam;
527         int error, sotype, rcvflg;
528         struct thread *td = curthread;  /* XXX */
529
530         /*
531          * Set up arguments for soreceive()
532          */
533         *mp = NULL;
534         *aname = NULL;
535         sotype = nmp->nm_sotype;
536
537         /*
538          * For reliable protocols, lock against other senders/receivers
539          * in case a reconnect is necessary.
540          * For SOCK_STREAM, first get the Record Mark to find out how much
541          * more there is to get.
542          * We must lock the socket against other receivers
543          * until we have an entire rpc request/reply.
544          */
545         if (sotype != SOCK_DGRAM) {
546                 error = nfs_sndlock(nmp, rep);
547                 if (error)
548                         return (error);
549 tryagain:
550                 /*
551                  * Check for fatal errors and resending request.
552                  */
553                 /*
554                  * Ugh: If a reconnect attempt just happened, nm_so
555                  * would have changed. NULL indicates a failed
556                  * attempt that has essentially shut down this
557                  * mount point.
558                  */
559                 if (rep && (rep->r_mrep || (rep->r_flags & R_SOFTTERM))) {
560                         nfs_sndunlock(nmp);
561                         return (EINTR);
562                 }
563                 so = nmp->nm_so;
564                 if (so == NULL) {
565                         error = nfs_reconnect(nmp, rep);
566                         if (error) {
567                                 nfs_sndunlock(nmp);
568                                 return (error);
569                         }
570                         goto tryagain;
571                 }
572                 while (rep && (rep->r_flags & R_NEEDSXMIT)) {
573                         m = m_copym(rep->r_mreq, 0, M_COPYALL, MB_WAIT);
574                         nfsstats.rpcretries++;
575                         error = nfs_send(so, rep->r_nmp->nm_nam, m, rep);
576                         if (error) {
577                                 if (error == EINTR || error == ERESTART ||
578                                     (error = nfs_reconnect(nmp, rep)) != 0) {
579                                         nfs_sndunlock(nmp);
580                                         return (error);
581                                 }
582                                 goto tryagain;
583                         }
584                 }
585                 nfs_sndunlock(nmp);
586                 if (sotype == SOCK_STREAM) {
587                         /*
588                          * Get the length marker from the stream
589                          */
590                         aio.iov_base = (caddr_t)&len;
591                         aio.iov_len = sizeof(u_int32_t);
592                         auio.uio_iov = &aio;
593                         auio.uio_iovcnt = 1;
594                         auio.uio_segflg = UIO_SYSSPACE;
595                         auio.uio_rw = UIO_READ;
596                         auio.uio_offset = 0;
597                         auio.uio_resid = sizeof(u_int32_t);
598                         auio.uio_td = td;
599                         do {
600                            rcvflg = MSG_WAITALL;
601                            error = so_pru_soreceive(so, NULL, &auio, NULL,
602                                                     NULL, &rcvflg);
603                            if (error == EWOULDBLOCK && rep) {
604                                 if (rep->r_flags & R_SOFTTERM)
605                                         return (EINTR);
606                            }
607                         } while (error == EWOULDBLOCK);
608
609                         if (error == 0 && auio.uio_resid > 0) {
610                             /*
611                              * Only log short packets if not EOF
612                              */
613                             if (auio.uio_resid != sizeof(u_int32_t))
614                             log(LOG_INFO,
615                                  "short receive (%d/%d) from nfs server %s\n",
616                                  (int)(sizeof(u_int32_t) - auio.uio_resid),
617                                  (int)sizeof(u_int32_t),
618                                  nmp->nm_mountp->mnt_stat.f_mntfromname);
619                             error = EPIPE;
620                         }
621                         if (error)
622                                 goto errout;
623                         len = ntohl(len) & ~0x80000000;
624                         /*
625                          * This is SERIOUS! We are out of sync with the sender
626                          * and forcing a disconnect/reconnect is all I can do.
627                          */
628                         if (len > NFS_MAXPACKET) {
629                             log(LOG_ERR, "%s (%d) from nfs server %s\n",
630                                 "impossible packet length",
631                                 len,
632                                 nmp->nm_mountp->mnt_stat.f_mntfromname);
633                             error = EFBIG;
634                             goto errout;
635                         }
636
637                         /*
638                          * Get the rest of the packet as an mbuf chain
639                          */
640                         sbinit(&sio, len);
641                         do {
642                             rcvflg = MSG_WAITALL;
643                             error = so_pru_soreceive(so, NULL, NULL, &sio,
644                                                      NULL, &rcvflg);
645                         } while (error == EWOULDBLOCK || error == EINTR ||
646                                  error == ERESTART);
647                         if (error == 0 && sio.sb_cc != len) {
648                             if (sio.sb_cc != 0)
649                             log(LOG_INFO,
650                                 "short receive (%zu/%d) from nfs server %s\n",
651                                 (size_t)len - auio.uio_resid, len,
652                                 nmp->nm_mountp->mnt_stat.f_mntfromname);
653                             error = EPIPE;
654                         }
655                         *mp = sio.sb_mb;
656                 } else {
657                         /*
658                          * Non-stream, so get the whole packet by not
659                          * specifying MSG_WAITALL and by specifying a large
660                          * length.
661                          *
662                          * We have no use for control msg., but must grab them
663                          * and then throw them away so we know what is going
664                          * on.
665                          */
666                         sbinit(&sio, 100000000);
667                         do {
668                             rcvflg = 0;
669                             error =  so_pru_soreceive(so, NULL, NULL, &sio,
670                                                       &control, &rcvflg);
671                             if (control)
672                                 m_freem(control);
673                             if (error == EWOULDBLOCK && rep) {
674                                 if (rep->r_flags & R_SOFTTERM) {
675                                         m_freem(sio.sb_mb);
676                                         return (EINTR);
677                                 }
678                             }
679                         } while (error == EWOULDBLOCK ||
680                                  (error == 0 && sio.sb_mb == NULL && control));
681                         if ((rcvflg & MSG_EOR) == 0)
682                                 kprintf("Egad!!\n");
683                         if (error == 0 && sio.sb_mb == NULL)
684                                 error = EPIPE;
685                         len = sio.sb_cc;
686                         *mp = sio.sb_mb;
687                 }
688 errout:
689                 if (error && error != EINTR && error != ERESTART) {
690                         m_freem(*mp);
691                         *mp = NULL;
692                         if (error != EPIPE) {
693                                 log(LOG_INFO,
694                                     "receive error %d from nfs server %s\n",
695                                     error,
696                                  nmp->nm_mountp->mnt_stat.f_mntfromname);
697                         }
698                         error = nfs_sndlock(nmp, rep);
699                         if (!error) {
700                                 error = nfs_reconnect(nmp, rep);
701                                 if (!error)
702                                         goto tryagain;
703                                 else
704                                         nfs_sndunlock(nmp);
705                         }
706                 }
707         } else {
708                 if ((so = nmp->nm_so) == NULL)
709                         return (EACCES);
710                 if (so->so_state & SS_ISCONNECTED)
711                         getnam = NULL;
712                 else
713                         getnam = aname;
714                 sbinit(&sio, 100000000);
715                 do {
716                         rcvflg = 0;
717                         error =  so_pru_soreceive(so, getnam, NULL, &sio,
718                                                   NULL, &rcvflg);
719                         if (error == EWOULDBLOCK && rep &&
720                             (rep->r_flags & R_SOFTTERM)) {
721                                 m_freem(sio.sb_mb);
722                                 return (EINTR);
723                         }
724                 } while (error == EWOULDBLOCK);
725
726                 len = sio.sb_cc;
727                 *mp = sio.sb_mb;
728
729                 /*
730                  * A shutdown may result in no error and no mbuf.
731                  * Convert to EPIPE.
732                  */
733                 if (*mp == NULL && error == 0)
734                         error = EPIPE;
735         }
736         if (error) {
737                 m_freem(*mp);
738                 *mp = NULL;
739         }
740
741         /*
742          * Search for any mbufs that are not a multiple of 4 bytes long
743          * or with m_data not longword aligned.
744          * These could cause pointer alignment problems, so copy them to
745          * well aligned mbufs.
746          */
747         nfs_realign(mp, 5 * NFSX_UNSIGNED);
748         return (error);
749 }
750
751 /*
752  * Implement receipt of reply on a socket.
753  *
754  * We must search through the list of received datagrams matching them
755  * with outstanding requests using the xid, until ours is found.
756  *
757  * If myrep is NULL we process packets on the socket until
758  * interrupted or until nm_reqrxq is non-empty.
759  */
760 /* ARGSUSED */
761 int
762 nfs_reply(struct nfsmount *nmp, struct nfsreq *myrep)
763 {
764         struct nfsreq *rep;
765         struct sockaddr *nam;
766         u_int32_t rxid;
767         u_int32_t *tl;
768         int error;
769         struct nfsm_info info;
770
771         /*
772          * Loop around until we get our own reply
773          */
774         for (;;) {
775                 /*
776                  * Lock against other receivers so that I don't get stuck in
777                  * sbwait() after someone else has received my reply for me.
778                  * Also necessary for connection based protocols to avoid
779                  * race conditions during a reconnect.
780                  *
781                  * If nfs_rcvlock() returns EALREADY, that means that
782                  * the reply has already been recieved by another
783                  * process and we can return immediately.  In this
784                  * case, the lock is not taken to avoid races with
785                  * other processes.
786                  */
787                 info.mrep = NULL;
788
789                 error = nfs_rcvlock(nmp, myrep);
790                 if (error == EALREADY)
791                         return (0);
792                 if (error)
793                         return (error);
794
795                 /*
796                  * If myrep is NULL we are the receiver helper thread.
797                  * Stop waiting for incoming replies if there are
798                  * messages sitting on reqrxq that we need to process,
799                  * or if a shutdown request is pending.
800                  */
801                 if (myrep == NULL && (TAILQ_FIRST(&nmp->nm_reqrxq) ||
802                     nmp->nm_rxstate > NFSSVC_PENDING)) {
803                         nfs_rcvunlock(nmp);
804                         return(EWOULDBLOCK);
805                 }
806
807                 /*
808                  * Get the next Rpc reply off the socket
809                  *
810                  * We cannot release the receive lock until we've
811                  * filled in rep->r_mrep, otherwise a waiting
812                  * thread may deadlock in soreceive with no incoming
813                  * packets expected.
814                  */
815                 error = nfs_receive(nmp, myrep, &nam, &info.mrep);
816                 if (error) {
817                         /*
818                          * Ignore routing errors on connectionless protocols??
819                          */
820                         nfs_rcvunlock(nmp);
821                         if (NFSIGNORE_SOERROR(nmp->nm_soflags, error)) {
822                                 if (nmp->nm_so == NULL)
823                                         return (error);
824                                 nmp->nm_so->so_error = 0;
825                                 continue;
826                         }
827                         return (error);
828                 }
829                 if (nam)
830                         FREE(nam, M_SONAME);
831
832                 /*
833                  * Get the xid and check that it is an rpc reply
834                  */
835                 info.md = info.mrep;
836                 info.dpos = mtod(info.md, caddr_t);
837                 NULLOUT(tl = nfsm_dissect(&info, 2*NFSX_UNSIGNED));
838                 rxid = *tl++;
839                 if (*tl != rpc_reply) {
840                         nfsstats.rpcinvalid++;
841                         m_freem(info.mrep);
842                         info.mrep = NULL;
843 nfsmout:
844                         nfs_rcvunlock(nmp);
845                         continue;
846                 }
847
848                 /*
849                  * Loop through the request list to match up the reply
850                  * Iff no match, just drop the datagram.  On match, set
851                  * r_mrep atomically to prevent the timer from messing
852                  * around with the request after we have exited the critical
853                  * section.
854                  */
855                 crit_enter();
856                 TAILQ_FOREACH(rep, &nmp->nm_reqq, r_chain) {
857                         if (rep->r_mrep == NULL && rxid == rep->r_xid)
858                                 break;
859                 }
860
861                 /*
862                  * Fill in the rest of the reply if we found a match.
863                  *
864                  * Deal with duplicate responses if there was no match.
865                  */
866                 if (rep) {
867                         rep->r_md = info.md;
868                         rep->r_dpos = info.dpos;
869                         if (nfsrtton) {
870                                 struct rttl *rt;
871
872                                 rt = &nfsrtt.rttl[nfsrtt.pos];
873                                 rt->proc = rep->r_procnum;
874                                 rt->rto = 0;
875                                 rt->sent = 0;
876                                 rt->cwnd = nmp->nm_maxasync_scaled;
877                                 rt->srtt = nmp->nm_srtt[proct[rep->r_procnum] - 1];
878                                 rt->sdrtt = nmp->nm_sdrtt[proct[rep->r_procnum] - 1];
879                                 rt->fsid = nmp->nm_mountp->mnt_stat.f_fsid;
880                                 getmicrotime(&rt->tstamp);
881                                 if (rep->r_flags & R_TIMING)
882                                         rt->rtt = rep->r_rtt;
883                                 else
884                                         rt->rtt = 1000000;
885                                 nfsrtt.pos = (nfsrtt.pos + 1) % NFSRTTLOGSIZ;
886                         }
887
888                         /*
889                          * New congestion control is based only on async
890                          * requests.
891                          */
892                         if (nmp->nm_maxasync_scaled < NFS_MAXASYNC_SCALED)
893                                 ++nmp->nm_maxasync_scaled;
894                         if (rep->r_flags & R_SENT) {
895                                 rep->r_flags &= ~R_SENT;
896                         }
897                         /*
898                          * Update rtt using a gain of 0.125 on the mean
899                          * and a gain of 0.25 on the deviation.
900                          *
901                          * NOTE SRTT/SDRTT are only good if R_TIMING is set.
902                          */
903                         if ((rep->r_flags & R_TIMING) && rep->r_rexmit == 0) {
904                                 /*
905                                  * Since the timer resolution of
906                                  * NFS_HZ is so course, it can often
907                                  * result in r_rtt == 0. Since
908                                  * r_rtt == N means that the actual
909                                  * rtt is between N+dt and N+2-dt ticks,
910                                  * add 1.
911                                  */
912                                 int n;
913                                 int d;
914
915 #define NFSRSB  NFS_RTT_SCALE_BITS
916                                 n = ((NFS_SRTT(rep) * 7) +
917                                      (rep->r_rtt << NFSRSB)) >> 3;
918                                 d = n - NFS_SRTT(rep);
919                                 NFS_SRTT(rep) = n;
920
921                                 /*
922                                  * Don't let the jitter calculation decay
923                                  * too quickly, but we want a fast rampup.
924                                  */
925                                 if (d < 0)
926                                         d = -d;
927                                 d <<= NFSRSB;
928                                 if (d < NFS_SDRTT(rep))
929                                         n = ((NFS_SDRTT(rep) * 15) + d) >> 4;
930                                 else
931                                         n = ((NFS_SDRTT(rep) * 3) + d) >> 2;
932                                 NFS_SDRTT(rep) = n;
933 #undef NFSRSB
934                         }
935                         nmp->nm_timeouts = 0;
936                         rep->r_mrep = info.mrep;
937                         nfs_hardterm(rep, 0);
938                 } else {
939                         /*
940                          * Extract vers, prog, nfsver, procnum.  A duplicate
941                          * response means we didn't wait long enough so
942                          * we increase the SRTT to avoid future spurious
943                          * timeouts.
944                          */
945                         u_int procnum = nmp->nm_lastreprocnum;
946                         int n;
947
948                         if (procnum < NFS_NPROCS && proct[procnum]) {
949                                 if (nfs_showrexmit)
950                                         kprintf("D");
951                                 n = nmp->nm_srtt[proct[procnum]];
952                                 n += NFS_ASYSCALE * NFS_HZ;
953                                 if (n < NFS_ASYSCALE * NFS_HZ * 10)
954                                         n = NFS_ASYSCALE * NFS_HZ * 10;
955                                 nmp->nm_srtt[proct[procnum]] = n;
956                         }
957                 }
958                 nfs_rcvunlock(nmp);
959                 crit_exit();
960
961                 /*
962                  * If not matched to a request, drop it.
963                  * If it's mine, get out.
964                  */
965                 if (rep == NULL) {
966                         nfsstats.rpcunexpected++;
967                         m_freem(info.mrep);
968                         info.mrep = NULL;
969                 } else if (rep == myrep) {
970                         if (rep->r_mrep == NULL)
971                                 panic("nfsreply nil");
972                         return (0);
973                 }
974         }
975 }
976
977 /*
978  * Run the request state machine until the target state is reached
979  * or a fatal error occurs.  The target state is not run.  Specifying
980  * a target of NFSM_STATE_DONE runs the state machine until the rpc
981  * is complete.
982  *
983  * EINPROGRESS is returned for all states other then the DONE state,
984  * indicating that the rpc is still in progress.
985  */
986 int
987 nfs_request(struct nfsm_info *info, nfsm_state_t bstate, nfsm_state_t estate)
988 {
989         struct nfsreq *req;
990
991         while (info->state >= bstate && info->state < estate) {
992                 switch(info->state) {
993                 case NFSM_STATE_SETUP:
994                         /*
995                          * Setup the nfsreq.  Any error which occurs during
996                          * this state is fatal.
997                          */
998                         info->error = nfs_request_setup(info);
999                         if (info->error) {
1000                                 info->state = NFSM_STATE_DONE;
1001                                 return (info->error);
1002                         } else {
1003                                 req = info->req;
1004                                 req->r_mrp = &info->mrep;
1005                                 req->r_mdp = &info->md;
1006                                 req->r_dposp = &info->dpos;
1007                                 info->state = NFSM_STATE_AUTH;
1008                         }
1009                         break;
1010                 case NFSM_STATE_AUTH:
1011                         /*
1012                          * Authenticate the nfsreq.  Any error which occurs
1013                          * during this state is fatal.
1014                          */
1015                         info->error = nfs_request_auth(info->req);
1016                         if (info->error) {
1017                                 info->state = NFSM_STATE_DONE;
1018                                 return (info->error);
1019                         } else {
1020                                 info->state = NFSM_STATE_TRY;
1021                         }
1022                         break;
1023                 case NFSM_STATE_TRY:
1024                         /*
1025                          * Transmit or retransmit attempt.  An error in this
1026                          * state is ignored and we always move on to the
1027                          * next state.
1028                          *
1029                          * This can trivially race the receiver if the
1030                          * request is asynchronous.  nfs_request_try()
1031                          * will thus set the state for us and we
1032                          * must also return immediately if we are
1033                          * running an async state machine, because
1034                          * info can become invalid due to races after
1035                          * try() returns.
1036                          */
1037                         if (info->req->r_flags & R_ASYNC) {
1038                                 nfs_request_try(info->req);
1039                                 if (estate == NFSM_STATE_WAITREPLY)
1040                                         return (EINPROGRESS);
1041                         } else {
1042                                 nfs_request_try(info->req);
1043                                 info->state = NFSM_STATE_WAITREPLY;
1044                         }
1045                         break;
1046                 case NFSM_STATE_WAITREPLY:
1047                         /*
1048                          * Wait for a reply or timeout and move on to the
1049                          * next state.  The error returned by this state
1050                          * is passed to the processing code in the next
1051                          * state.
1052                          */
1053                         info->error = nfs_request_waitreply(info->req);
1054                         info->state = NFSM_STATE_PROCESSREPLY;
1055                         break;
1056                 case NFSM_STATE_PROCESSREPLY:
1057                         /*
1058                          * Process the reply or timeout.  Errors which occur
1059                          * in this state may cause the state machine to
1060                          * go back to an earlier state, and are fatal
1061                          * otherwise.
1062                          */
1063                         info->error = nfs_request_processreply(info,
1064                                                                info->error);
1065                         switch(info->error) {
1066                         case ENEEDAUTH:
1067                                 info->state = NFSM_STATE_AUTH;
1068                                 break;
1069                         case EAGAIN:
1070                                 info->state = NFSM_STATE_TRY;
1071                                 break;
1072                         default:
1073                                 /*
1074                                  * Operation complete, with or without an
1075                                  * error.  We are done.
1076                                  */
1077                                 info->req = NULL;
1078                                 info->state = NFSM_STATE_DONE;
1079                                 return (info->error);
1080                         }
1081                         break;
1082                 case NFSM_STATE_DONE:
1083                         /*
1084                          * Shouldn't be reached
1085                          */
1086                         return (info->error);
1087                         /* NOT REACHED */
1088                 }
1089         }
1090
1091         /*
1092          * If we are done return the error code (if any).
1093          * Otherwise return EINPROGRESS.
1094          */
1095         if (info->state == NFSM_STATE_DONE)
1096                 return (info->error);
1097         return (EINPROGRESS);
1098 }
1099
1100 /*
1101  * nfs_request - goes something like this
1102  *      - fill in request struct
1103  *      - links it into list
1104  *      - calls nfs_send() for first transmit
1105  *      - calls nfs_receive() to get reply
1106  *      - break down rpc header and return with nfs reply pointed to
1107  *        by mrep or error
1108  * nb: always frees up mreq mbuf list
1109  */
1110 static int
1111 nfs_request_setup(nfsm_info_t info)
1112 {
1113         struct nfsreq *req;
1114         struct nfsmount *nmp;
1115         struct mbuf *m;
1116         int i;
1117
1118         /*
1119          * Reject requests while attempting a forced unmount.
1120          */
1121         if (info->vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF) {
1122                 m_freem(info->mreq);
1123                 info->mreq = NULL;
1124                 return (ESTALE);
1125         }
1126         nmp = VFSTONFS(info->vp->v_mount);
1127         req = kmalloc(sizeof(struct nfsreq), M_NFSREQ, M_WAITOK);
1128         req->r_nmp = nmp;
1129         req->r_vp = info->vp;
1130         req->r_td = info->td;
1131         req->r_procnum = info->procnum;
1132         req->r_mreq = NULL;
1133         req->r_cred = info->cred;
1134
1135         i = 0;
1136         m = info->mreq;
1137         while (m) {
1138                 i += m->m_len;
1139                 m = m->m_next;
1140         }
1141         req->r_mrest = info->mreq;
1142         req->r_mrest_len = i;
1143
1144         /*
1145          * The presence of a non-NULL r_info in req indicates
1146          * async completion via our helper threads.  See the receiver
1147          * code.
1148          */
1149         if (info->bio) {
1150                 req->r_info = info;
1151                 req->r_flags = R_ASYNC;
1152         } else {
1153                 req->r_info = NULL;
1154                 req->r_flags = 0;
1155         }
1156         info->req = req;
1157         return(0);
1158 }
1159
1160 static int
1161 nfs_request_auth(struct nfsreq *rep)
1162 {
1163         struct nfsmount *nmp = rep->r_nmp;
1164         struct mbuf *m;
1165         char nickv[RPCX_NICKVERF];
1166         int error = 0, auth_len, auth_type;
1167         int verf_len;
1168         u_int32_t xid;
1169         char *auth_str, *verf_str;
1170         struct ucred *cred;
1171
1172         cred = rep->r_cred;
1173         rep->r_failed_auth = 0;
1174
1175         /*
1176          * Get the RPC header with authorization.
1177          */
1178         verf_str = auth_str = NULL;
1179         if (nmp->nm_flag & NFSMNT_KERB) {
1180                 verf_str = nickv;
1181                 verf_len = sizeof (nickv);
1182                 auth_type = RPCAUTH_KERB4;
1183                 bzero((caddr_t)rep->r_key, sizeof(rep->r_key));
1184                 if (rep->r_failed_auth ||
1185                     nfs_getnickauth(nmp, cred, &auth_str, &auth_len,
1186                                     verf_str, verf_len)) {
1187                         error = nfs_getauth(nmp, rep, cred, &auth_str,
1188                                 &auth_len, verf_str, &verf_len, rep->r_key);
1189                         if (error) {
1190                                 m_freem(rep->r_mrest);
1191                                 rep->r_mrest = NULL;
1192                                 kfree((caddr_t)rep, M_NFSREQ);
1193                                 return (error);
1194                         }
1195                 }
1196         } else {
1197                 auth_type = RPCAUTH_UNIX;
1198                 if (cred->cr_ngroups < 1)
1199                         panic("nfsreq nogrps");
1200                 auth_len = ((((cred->cr_ngroups - 1) > nmp->nm_numgrps) ?
1201                         nmp->nm_numgrps : (cred->cr_ngroups - 1)) << 2) +
1202                         5 * NFSX_UNSIGNED;
1203         }
1204         m = nfsm_rpchead(cred, nmp->nm_flag, rep->r_procnum, auth_type,
1205                         auth_len, auth_str, verf_len, verf_str,
1206                         rep->r_mrest, rep->r_mrest_len, &rep->r_mheadend, &xid);
1207         rep->r_mrest = NULL;
1208         if (auth_str)
1209                 kfree(auth_str, M_TEMP);
1210
1211         /*
1212          * For stream protocols, insert a Sun RPC Record Mark.
1213          */
1214         if (nmp->nm_sotype == SOCK_STREAM) {
1215                 M_PREPEND(m, NFSX_UNSIGNED, MB_WAIT);
1216                 if (m == NULL) {
1217                         kfree(rep, M_NFSREQ);
1218                         return (ENOBUFS);
1219                 }
1220                 *mtod(m, u_int32_t *) = htonl(0x80000000 |
1221                          (m->m_pkthdr.len - NFSX_UNSIGNED));
1222         }
1223         rep->r_mreq = m;
1224         rep->r_xid = xid;
1225         return (0);
1226 }
1227
1228 static int
1229 nfs_request_try(struct nfsreq *rep)
1230 {
1231         struct nfsmount *nmp = rep->r_nmp;
1232         struct mbuf *m2;
1233         int error;
1234
1235         /*
1236          * Request is not on any queue, only the owner has access to it
1237          * so it should not be locked by anyone atm.
1238          *
1239          * Interlock to prevent races.  While locked the only remote
1240          * action possible is for r_mrep to be set (once we enqueue it).
1241          */
1242         if (rep->r_flags == 0xdeadc0de) {
1243                 print_backtrace(-1);
1244                 panic("flags nbad\n");
1245         }
1246         KKASSERT((rep->r_flags & (R_LOCKED | R_ONREQQ)) == 0);
1247         if (nmp->nm_flag & NFSMNT_SOFT)
1248                 rep->r_retry = nmp->nm_retry;
1249         else
1250                 rep->r_retry = NFS_MAXREXMIT + 1;       /* past clip limit */
1251         rep->r_rtt = rep->r_rexmit = 0;
1252         if (proct[rep->r_procnum] > 0)
1253                 rep->r_flags |= R_TIMING | R_LOCKED;
1254         else
1255                 rep->r_flags |= R_LOCKED;
1256         rep->r_mrep = NULL;
1257
1258         /*
1259          * Do the client side RPC.
1260          */
1261         nfsstats.rpcrequests++;
1262
1263         if (nmp->nm_flag & NFSMNT_FORCE) {
1264                 rep->r_flags |= R_SOFTTERM;
1265                 rep->r_flags &= ~R_LOCKED;
1266                 return (0);
1267         }
1268
1269         /*
1270          * Chain request into list of outstanding requests. Be sure
1271          * to put it LAST so timer finds oldest requests first.  Note
1272          * that our control of R_LOCKED prevents the request from
1273          * getting ripped out from under us or transmitted by the
1274          * timer code.
1275          *
1276          * For requests with info structures we must atomically set the
1277          * info's state because the structure could become invalid upon
1278          * return due to races (i.e., if async)
1279          */
1280         crit_enter();
1281         mtx_link_init(&rep->r_link);
1282         TAILQ_INSERT_TAIL(&nmp->nm_reqq, rep, r_chain);
1283         rep->r_flags |= R_ONREQQ;
1284         ++nmp->nm_reqqlen;
1285         if (rep->r_flags & R_ASYNC)
1286                 rep->r_info->state = NFSM_STATE_WAITREPLY;
1287         crit_exit();
1288
1289         error = 0;
1290
1291         /*
1292          * Send if we can.  Congestion control is not handled here any more
1293          * becausing trying to defer the initial send based on the nfs_timer
1294          * requires having a very fast nfs_timer, which is silly.
1295          */
1296         if (nmp->nm_so) {
1297                 if (nmp->nm_soflags & PR_CONNREQUIRED)
1298                         error = nfs_sndlock(nmp, rep);
1299                 if (error == 0) {
1300                         m2 = m_copym(rep->r_mreq, 0, M_COPYALL, MB_WAIT);
1301                         error = nfs_send(nmp->nm_so, nmp->nm_nam, m2, rep);
1302                         if (nmp->nm_soflags & PR_CONNREQUIRED)
1303                                 nfs_sndunlock(nmp);
1304                         rep->r_flags &= ~R_NEEDSXMIT;
1305                         if ((rep->r_flags & R_SENT) == 0) {
1306                                 rep->r_flags |= R_SENT;
1307                         }
1308                 } else {
1309                         rep->r_flags |= R_NEEDSXMIT;
1310                 }
1311         } else {
1312                 rep->r_flags |= R_NEEDSXMIT;
1313                 rep->r_rtt = -1;
1314         }
1315         if (error == EPIPE)
1316                 error = 0;
1317
1318         /*
1319          * Release the lock.  The only remote action that may have occurred
1320          * would have been the setting of rep->r_mrep.  If this occured
1321          * and the request was async we have to move it to the reader
1322          * thread's queue for action.
1323          *
1324          * For async requests also make sure the reader is woken up so
1325          * it gets on the socket to read responses.
1326          */
1327         crit_enter();
1328         if (rep->r_flags & R_ASYNC) {
1329                 if (rep->r_mrep)
1330                         nfs_hardterm(rep, 1);
1331                 rep->r_flags &= ~R_LOCKED;
1332                 nfssvc_iod_reader_wakeup(nmp);
1333         } else {
1334                 rep->r_flags &= ~R_LOCKED;
1335         }
1336         if (rep->r_flags & R_WANTED) {
1337                 rep->r_flags &= ~R_WANTED;
1338                 wakeup(rep);
1339         }
1340         crit_exit();
1341         return (error);
1342 }
1343
1344 /*
1345  * This code is only called for synchronous requests.  Completed synchronous
1346  * requests are left on reqq and we remove them before moving on to the
1347  * processing state.
1348  */
1349 static int
1350 nfs_request_waitreply(struct nfsreq *rep)
1351 {
1352         struct nfsmount *nmp = rep->r_nmp;
1353         int error;
1354
1355         KKASSERT((rep->r_flags & R_ASYNC) == 0);
1356
1357         /*
1358          * Wait until the request is finished.
1359          */
1360         error = nfs_reply(nmp, rep);
1361
1362         /*
1363          * RPC done, unlink the request, but don't rip it out from under
1364          * the callout timer.
1365          *
1366          * Once unlinked no other receiver or the timer will have
1367          * visibility, so we do not have to set R_LOCKED.
1368          */
1369         crit_enter();
1370         while (rep->r_flags & R_LOCKED) {
1371                 rep->r_flags |= R_WANTED;
1372                 tsleep(rep, 0, "nfstrac", 0);
1373         }
1374         KKASSERT(rep->r_flags & R_ONREQQ);
1375         TAILQ_REMOVE(&nmp->nm_reqq, rep, r_chain);
1376         rep->r_flags &= ~R_ONREQQ;
1377         --nmp->nm_reqqlen;
1378         if (TAILQ_FIRST(&nmp->nm_bioq) &&
1379             nmp->nm_reqqlen <= nfs_maxasyncbio * 2 / 3) {
1380                 nfssvc_iod_writer_wakeup(nmp);
1381         }
1382         crit_exit();
1383
1384         /*
1385          * Decrement the outstanding request count.
1386          */
1387         if (rep->r_flags & R_SENT) {
1388                 rep->r_flags &= ~R_SENT;
1389         }
1390         return (error);
1391 }
1392
1393 /*
1394  * Process reply with error returned from nfs_requet_waitreply().
1395  *
1396  * Returns EAGAIN if it wants us to loop up to nfs_request_try() again.
1397  * Returns ENEEDAUTH if it wants us to loop up to nfs_request_auth() again.
1398  */
1399 static int
1400 nfs_request_processreply(nfsm_info_t info, int error)
1401 {
1402         struct nfsreq *req = info->req;
1403         struct nfsmount *nmp = req->r_nmp;
1404         u_int32_t *tl;
1405         int verf_type;
1406         int i;
1407
1408         /*
1409          * If there was a successful reply and a tprintf msg.
1410          * tprintf a response.
1411          */
1412         if (error == 0 && (req->r_flags & R_TPRINTFMSG)) {
1413                 nfs_msg(req->r_td, nmp->nm_mountp->mnt_stat.f_mntfromname,
1414                     "is alive again");
1415         }
1416         info->mrep = req->r_mrep;
1417         info->md = req->r_md;
1418         info->dpos = req->r_dpos;
1419         if (error) {
1420                 m_freem(req->r_mreq);
1421                 req->r_mreq = NULL;
1422                 kfree(req, M_NFSREQ);
1423                 info->req = NULL;
1424                 return (error);
1425         }
1426
1427         /*
1428          * break down the rpc header and check if ok
1429          */
1430         NULLOUT(tl = nfsm_dissect(info, 3 * NFSX_UNSIGNED));
1431         if (*tl++ == rpc_msgdenied) {
1432                 if (*tl == rpc_mismatch) {
1433                         error = EOPNOTSUPP;
1434                 } else if ((nmp->nm_flag & NFSMNT_KERB) &&
1435                            *tl++ == rpc_autherr) {
1436                         if (req->r_failed_auth == 0) {
1437                                 req->r_failed_auth++;
1438                                 req->r_mheadend->m_next = NULL;
1439                                 m_freem(info->mrep);
1440                                 info->mrep = NULL;
1441                                 m_freem(req->r_mreq);
1442                                 return (ENEEDAUTH);
1443                         } else {
1444                                 error = EAUTH;
1445                         }
1446                 } else {
1447                         error = EACCES;
1448                 }
1449                 m_freem(info->mrep);
1450                 info->mrep = NULL;
1451                 m_freem(req->r_mreq);
1452                 req->r_mreq = NULL;
1453                 kfree(req, M_NFSREQ);
1454                 info->req = NULL;
1455                 return (error);
1456         }
1457
1458         /*
1459          * Grab any Kerberos verifier, otherwise just throw it away.
1460          */
1461         verf_type = fxdr_unsigned(int, *tl++);
1462         i = fxdr_unsigned(int32_t, *tl);
1463         if ((nmp->nm_flag & NFSMNT_KERB) && verf_type == RPCAUTH_KERB4) {
1464                 error = nfs_savenickauth(nmp, req->r_cred, i, req->r_key,
1465                                          &info->md, &info->dpos, info->mrep);
1466                 if (error)
1467                         goto nfsmout;
1468         } else if (i > 0) {
1469                 ERROROUT(nfsm_adv(info, nfsm_rndup(i)));
1470         }
1471         NULLOUT(tl = nfsm_dissect(info, NFSX_UNSIGNED));
1472         /* 0 == ok */
1473         if (*tl == 0) {
1474                 NULLOUT(tl = nfsm_dissect(info, NFSX_UNSIGNED));
1475                 if (*tl != 0) {
1476                         error = fxdr_unsigned(int, *tl);
1477
1478                         /*
1479                          * Does anyone even implement this?  Just impose
1480                          * a 1-second delay.
1481                          */
1482                         if ((nmp->nm_flag & NFSMNT_NFSV3) &&
1483                                 error == NFSERR_TRYLATER) {
1484                                 m_freem(info->mrep);
1485                                 info->mrep = NULL;
1486                                 error = 0;
1487
1488                                 tsleep((caddr_t)&lbolt, 0, "nqnfstry", 0);
1489                                 return (EAGAIN);        /* goto tryagain */
1490                         }
1491
1492                         /*
1493                          * If the File Handle was stale, invalidate the
1494                          * lookup cache, just in case.
1495                          *
1496                          * To avoid namecache<->vnode deadlocks we must
1497                          * release the vnode lock if we hold it.
1498                          */
1499                         if (error == ESTALE) {
1500                                 struct vnode *vp = req->r_vp;
1501                                 int ltype;
1502
1503                                 ltype = lockstatus(&vp->v_lock, curthread);
1504                                 if (ltype == LK_EXCLUSIVE || ltype == LK_SHARED)
1505                                         lockmgr(&vp->v_lock, LK_RELEASE);
1506                                 cache_inval_vp(vp, CINV_CHILDREN);
1507                                 if (ltype == LK_EXCLUSIVE || ltype == LK_SHARED)
1508                                         lockmgr(&vp->v_lock, ltype);
1509                         }
1510                         if (nmp->nm_flag & NFSMNT_NFSV3) {
1511                                 KKASSERT(*req->r_mrp == info->mrep);
1512                                 KKASSERT(*req->r_mdp == info->md);
1513                                 KKASSERT(*req->r_dposp == info->dpos);
1514                                 error |= NFSERR_RETERR;
1515                         } else {
1516                                 m_freem(info->mrep);
1517                                 info->mrep = NULL;
1518                         }
1519                         m_freem(req->r_mreq);
1520                         req->r_mreq = NULL;
1521                         kfree(req, M_NFSREQ);
1522                         info->req = NULL;
1523                         return (error);
1524                 }
1525
1526                 KKASSERT(*req->r_mrp == info->mrep);
1527                 KKASSERT(*req->r_mdp == info->md);
1528                 KKASSERT(*req->r_dposp == info->dpos);
1529                 m_freem(req->r_mreq);
1530                 req->r_mreq = NULL;
1531                 FREE(req, M_NFSREQ);
1532                 return (0);
1533         }
1534         m_freem(info->mrep);
1535         info->mrep = NULL;
1536         error = EPROTONOSUPPORT;
1537 nfsmout:
1538         m_freem(req->r_mreq);
1539         req->r_mreq = NULL;
1540         kfree(req, M_NFSREQ);
1541         info->req = NULL;
1542         return (error);
1543 }
1544
1545 #ifndef NFS_NOSERVER
1546 /*
1547  * Generate the rpc reply header
1548  * siz arg. is used to decide if adding a cluster is worthwhile
1549  */
1550 int
1551 nfs_rephead(int siz, struct nfsrv_descript *nd, struct nfssvc_sock *slp,
1552             int err, struct mbuf **mrq, struct mbuf **mbp, caddr_t *bposp)
1553 {
1554         u_int32_t *tl;
1555         struct nfsm_info info;
1556
1557         siz += RPC_REPLYSIZ;
1558         info.mb = m_getl(max_hdr + siz, MB_WAIT, MT_DATA, M_PKTHDR, NULL);
1559         info.mreq = info.mb;
1560         info.mreq->m_pkthdr.len = 0;
1561         /*
1562          * If this is not a cluster, try and leave leading space
1563          * for the lower level headers.
1564          */
1565         if ((max_hdr + siz) < MINCLSIZE)
1566                 info.mreq->m_data += max_hdr;
1567         tl = mtod(info.mreq, u_int32_t *);
1568         info.mreq->m_len = 6 * NFSX_UNSIGNED;
1569         info.bpos = ((caddr_t)tl) + info.mreq->m_len;
1570         *tl++ = txdr_unsigned(nd->nd_retxid);
1571         *tl++ = rpc_reply;
1572         if (err == ERPCMISMATCH || (err & NFSERR_AUTHERR)) {
1573                 *tl++ = rpc_msgdenied;
1574                 if (err & NFSERR_AUTHERR) {
1575                         *tl++ = rpc_autherr;
1576                         *tl = txdr_unsigned(err & ~NFSERR_AUTHERR);
1577                         info.mreq->m_len -= NFSX_UNSIGNED;
1578                         info.bpos -= NFSX_UNSIGNED;
1579                 } else {
1580                         *tl++ = rpc_mismatch;
1581                         *tl++ = txdr_unsigned(RPC_VER2);
1582                         *tl = txdr_unsigned(RPC_VER2);
1583                 }
1584         } else {
1585                 *tl++ = rpc_msgaccepted;
1586
1587                 /*
1588                  * For Kerberos authentication, we must send the nickname
1589                  * verifier back, otherwise just RPCAUTH_NULL.
1590                  */
1591                 if (nd->nd_flag & ND_KERBFULL) {
1592                     struct nfsuid *nuidp;
1593                     struct timeval ktvin, ktvout;
1594
1595                     for (nuidp = NUIDHASH(slp, nd->nd_cr.cr_uid)->lh_first;
1596                         nuidp != 0; nuidp = nuidp->nu_hash.le_next) {
1597                         if (nuidp->nu_cr.cr_uid == nd->nd_cr.cr_uid &&
1598                             (!nd->nd_nam2 || netaddr_match(NU_NETFAM(nuidp),
1599                              &nuidp->nu_haddr, nd->nd_nam2)))
1600                             break;
1601                     }
1602                     if (nuidp) {
1603                         ktvin.tv_sec =
1604                             txdr_unsigned(nuidp->nu_timestamp.tv_sec - 1);
1605                         ktvin.tv_usec =
1606                             txdr_unsigned(nuidp->nu_timestamp.tv_usec);
1607
1608                         /*
1609                          * Encrypt the timestamp in ecb mode using the
1610                          * session key.
1611                          */
1612 #ifdef NFSKERB
1613                         XXX
1614 #else
1615                         ktvout.tv_sec = 0;
1616                         ktvout.tv_usec = 0;
1617 #endif
1618
1619                         *tl++ = rpc_auth_kerb;
1620                         *tl++ = txdr_unsigned(3 * NFSX_UNSIGNED);
1621                         *tl = ktvout.tv_sec;
1622                         tl = nfsm_build(&info, 3 * NFSX_UNSIGNED);
1623                         *tl++ = ktvout.tv_usec;
1624                         *tl++ = txdr_unsigned(nuidp->nu_cr.cr_uid);
1625                     } else {
1626                         *tl++ = 0;
1627                         *tl++ = 0;
1628                     }
1629                 } else {
1630                         *tl++ = 0;
1631                         *tl++ = 0;
1632                 }
1633                 switch (err) {
1634                 case EPROGUNAVAIL:
1635                         *tl = txdr_unsigned(RPC_PROGUNAVAIL);
1636                         break;
1637                 case EPROGMISMATCH:
1638                         *tl = txdr_unsigned(RPC_PROGMISMATCH);
1639                         tl = nfsm_build(&info, 2 * NFSX_UNSIGNED);
1640                         *tl++ = txdr_unsigned(2);
1641                         *tl = txdr_unsigned(3);
1642                         break;
1643                 case EPROCUNAVAIL:
1644                         *tl = txdr_unsigned(RPC_PROCUNAVAIL);
1645                         break;
1646                 case EBADRPC:
1647                         *tl = txdr_unsigned(RPC_GARBAGE);
1648                         break;
1649                 default:
1650                         *tl = 0;
1651                         if (err != NFSERR_RETVOID) {
1652                                 tl = nfsm_build(&info, NFSX_UNSIGNED);
1653                                 if (err)
1654                                     *tl = txdr_unsigned(nfsrv_errmap(nd, err));
1655                                 else
1656                                     *tl = 0;
1657                         }
1658                         break;
1659                 };
1660         }
1661
1662         if (mrq != NULL)
1663             *mrq = info.mreq;
1664         *mbp = info.mb;
1665         *bposp = info.bpos;
1666         if (err != 0 && err != NFSERR_RETVOID)
1667                 nfsstats.srvrpc_errs++;
1668         return (0);
1669 }
1670
1671
1672 #endif /* NFS_NOSERVER */
1673
1674 /*
1675  * Nfs timer routine.
1676  *
1677  * Scan the nfsreq list and retranmit any requests that have timed out
1678  * To avoid retransmission attempts on STREAM sockets (in the future) make
1679  * sure to set the r_retry field to 0 (implies nm_retry == 0).
1680  *
1681  * Requests with attached responses, terminated requests, and
1682  * locked requests are ignored.  Locked requests will be picked up
1683  * in a later timer call.
1684  */
1685 void
1686 nfs_timer(void *arg /* never used */)
1687 {
1688         struct nfsmount *nmp;
1689         struct nfsreq *req;
1690 #ifndef NFS_NOSERVER
1691         struct nfssvc_sock *slp;
1692         u_quad_t cur_usec;
1693 #endif /* NFS_NOSERVER */
1694
1695         crit_enter();
1696         TAILQ_FOREACH(nmp, &nfs_mountq, nm_entry) {
1697                 TAILQ_FOREACH(req, &nmp->nm_reqq, r_chain) {
1698                         KKASSERT(nmp == req->r_nmp);
1699                         if (req->r_mrep)
1700                                 continue;
1701                         if (req->r_flags & (R_SOFTTERM | R_LOCKED))
1702                                 continue;
1703                         req->r_flags |= R_LOCKED;
1704                         if (nfs_sigintr(nmp, req, req->r_td)) {
1705                                 nfs_softterm(req, 1);
1706                         } else {
1707                                 nfs_timer_req(req);
1708                         }
1709                         req->r_flags &= ~R_LOCKED;
1710                         if (req->r_flags & R_WANTED) {
1711                                 req->r_flags &= ~R_WANTED;
1712                                 wakeup(req);
1713                         }
1714                 }
1715         }
1716 #ifndef NFS_NOSERVER
1717
1718         /*
1719          * Scan the write gathering queues for writes that need to be
1720          * completed now.
1721          */
1722         cur_usec = nfs_curusec();
1723         TAILQ_FOREACH(slp, &nfssvc_sockhead, ns_chain) {
1724             if (slp->ns_tq.lh_first && slp->ns_tq.lh_first->nd_time<=cur_usec)
1725                 nfsrv_wakenfsd(slp, 1);
1726         }
1727 #endif /* NFS_NOSERVER */
1728         crit_exit();
1729         callout_reset(&nfs_timer_handle, nfs_ticks, nfs_timer, NULL);
1730 }
1731
1732 static
1733 void
1734 nfs_timer_req(struct nfsreq *req)
1735 {
1736         struct thread *td = &thread0; /* XXX for creds, will break if sleep */
1737         struct nfsmount *nmp = req->r_nmp;
1738         struct mbuf *m;
1739         struct socket *so;
1740         int timeo;
1741         int error;
1742
1743         /*
1744          * rtt ticks and timeout calculation.  Return if the timeout
1745          * has not been reached yet, unless the packet is flagged
1746          * for an immediate send.
1747          *
1748          * The mean rtt doesn't help when we get random I/Os, we have
1749          * to multiply by fairly large numbers.
1750          */
1751         if (req->r_rtt >= 0) {
1752                 /*
1753                  * Calculate the timeout to test against.
1754                  */
1755                 req->r_rtt++;
1756                 if (nmp->nm_flag & NFSMNT_DUMBTIMR) {
1757                         timeo = nmp->nm_timeo << NFS_RTT_SCALE_BITS;
1758                 } else if (req->r_flags & R_TIMING) {
1759                         timeo = NFS_SRTT(req) + NFS_SDRTT(req);
1760                 } else {
1761                         timeo = nmp->nm_timeo << NFS_RTT_SCALE_BITS;
1762                 }
1763                 timeo *= multt[req->r_procnum];
1764                 /* timeo is still scaled by SCALE_BITS */
1765
1766 #define NFSFS   (NFS_RTT_SCALE * NFS_HZ)
1767                 if (req->r_flags & R_TIMING) {
1768                         static long last_time;
1769                         if (nfs_showrtt && last_time != time_second) {
1770                                 kprintf("rpccmd %d NFS SRTT %d SDRTT %d "
1771                                         "timeo %d.%03d\n",
1772                                         proct[req->r_procnum],
1773                                         NFS_SRTT(req), NFS_SDRTT(req),
1774                                         timeo / NFSFS,
1775                                         timeo % NFSFS * 1000 /  NFSFS);
1776                                 last_time = time_second;
1777                         }
1778                 }
1779 #undef NFSFS
1780
1781                 /*
1782                  * deal with nfs_timer jitter.
1783                  */
1784                 timeo = (timeo >> NFS_RTT_SCALE_BITS) + 1;
1785                 if (timeo < 2)
1786                         timeo = 2;
1787
1788                 if (nmp->nm_timeouts > 0)
1789                         timeo *= nfs_backoff[nmp->nm_timeouts - 1];
1790                 if (timeo > NFS_MAXTIMEO)
1791                         timeo = NFS_MAXTIMEO;
1792                 if (req->r_rtt <= timeo) {
1793                         if ((req->r_flags & R_NEEDSXMIT) == 0)
1794                                 return;
1795                 } else if (nmp->nm_timeouts < 8) {
1796                         nmp->nm_timeouts++;
1797                 }
1798         }
1799
1800         /*
1801          * Check for server not responding
1802          */
1803         if ((req->r_flags & R_TPRINTFMSG) == 0 &&
1804              req->r_rexmit > nmp->nm_deadthresh) {
1805                 nfs_msg(req->r_td, nmp->nm_mountp->mnt_stat.f_mntfromname,
1806                         "not responding");
1807                 req->r_flags |= R_TPRINTFMSG;
1808         }
1809         if (req->r_rexmit >= req->r_retry) {    /* too many */
1810                 nfsstats.rpctimeouts++;
1811                 nfs_softterm(req, 1);
1812                 return;
1813         }
1814
1815         /*
1816          * Generally disable retransmission on reliable sockets,
1817          * unless the request is flagged for immediate send.
1818          */
1819         if (nmp->nm_sotype != SOCK_DGRAM) {
1820                 if (++req->r_rexmit > NFS_MAXREXMIT)
1821                         req->r_rexmit = NFS_MAXREXMIT;
1822                 if ((req->r_flags & R_NEEDSXMIT) == 0)
1823                         return;
1824         }
1825
1826         /*
1827          * Stop here if we do not have a socket!
1828          */
1829         if ((so = nmp->nm_so) == NULL)
1830                 return;
1831
1832         /*
1833          * If there is enough space and the window allows.. resend it.
1834          *
1835          * r_rtt is left intact in case we get an answer after the
1836          * retry that was a reply to the original packet.
1837          */
1838         if (ssb_space(&so->so_snd) >= req->r_mreq->m_pkthdr.len &&
1839             (req->r_flags & (R_SENT | R_NEEDSXMIT)) &&
1840            (m = m_copym(req->r_mreq, 0, M_COPYALL, MB_DONTWAIT))){
1841                 if ((nmp->nm_flag & NFSMNT_NOCONN) == 0)
1842                     error = so_pru_send(so, 0, m, NULL, NULL, td);
1843                 else
1844                     error = so_pru_send(so, 0, m, nmp->nm_nam,
1845                         NULL, td);
1846                 if (error) {
1847                         if (NFSIGNORE_SOERROR(nmp->nm_soflags, error))
1848                                 so->so_error = 0;
1849                         req->r_flags |= R_NEEDSXMIT;
1850                 } else if (req->r_mrep == NULL) {
1851                         /*
1852                          * Iff first send, start timing
1853                          * else turn timing off, backoff timer
1854                          * and divide congestion window by 2.
1855                          *
1856                          * It is possible for the so_pru_send() to
1857                          * block and for us to race a reply so we
1858                          * only do this if the reply field has not
1859                          * been filled in.  R_LOCKED will prevent
1860                          * the request from being ripped out from under
1861                          * us entirely.
1862                          *
1863                          * Record the last resent procnum to aid us
1864                          * in duplicate detection on receive.
1865                          */
1866                         if ((req->r_flags & R_NEEDSXMIT) == 0) {
1867                                 if (nfs_showrexmit)
1868                                         kprintf("X");
1869                                 if (++req->r_rexmit > NFS_MAXREXMIT)
1870                                         req->r_rexmit = NFS_MAXREXMIT;
1871                                 nmp->nm_maxasync_scaled >>= 1;
1872                                 if (nmp->nm_maxasync_scaled < NFS_MINASYNC_SCALED)
1873                                         nmp->nm_maxasync_scaled = NFS_MINASYNC_SCALED;
1874                                 nfsstats.rpcretries++;
1875                                 nmp->nm_lastreprocnum = req->r_procnum;
1876                         } else {
1877                                 req->r_flags |= R_SENT;
1878                                 req->r_flags &= ~R_NEEDSXMIT;
1879                         }
1880                 }
1881         }
1882 }
1883
1884 /*
1885  * Mark all of an nfs mount's outstanding requests with R_SOFTTERM and
1886  * wait for all requests to complete. This is used by forced unmounts
1887  * to terminate any outstanding RPCs.
1888  *
1889  * Locked requests cannot be canceled but will be marked for
1890  * soft-termination.
1891  */
1892 int
1893 nfs_nmcancelreqs(struct nfsmount *nmp)
1894 {
1895         struct nfsreq *req;
1896         int i;
1897
1898         crit_enter();
1899         TAILQ_FOREACH(req, &nmp->nm_reqq, r_chain) {
1900                 if (req->r_mrep != NULL || (req->r_flags & R_SOFTTERM))
1901                         continue;
1902                 nfs_softterm(req, 0);
1903         }
1904         /* XXX  the other two queues as well */
1905         crit_exit();
1906
1907         for (i = 0; i < 30; i++) {
1908                 crit_enter();
1909                 TAILQ_FOREACH(req, &nmp->nm_reqq, r_chain) {
1910                         if (nmp == req->r_nmp)
1911                                 break;
1912                 }
1913                 crit_exit();
1914                 if (req == NULL)
1915                         return (0);
1916                 tsleep(&lbolt, 0, "nfscancel", 0);
1917         }
1918         return (EBUSY);
1919 }
1920
1921 /*
1922  * Soft-terminate a request, effectively marking it as failed.
1923  *
1924  * Must be called from within a critical section.
1925  */
1926 static void
1927 nfs_softterm(struct nfsreq *rep, int islocked)
1928 {
1929         rep->r_flags |= R_SOFTTERM;
1930         nfs_hardterm(rep, islocked);
1931 }
1932
1933 /*
1934  * Hard-terminate a request, typically after getting a response.
1935  *
1936  * The state machine can still decide to re-issue it later if necessary.
1937  *
1938  * Must be called from within a critical section.
1939  */
1940 static void
1941 nfs_hardterm(struct nfsreq *rep, int islocked)
1942 {
1943         struct nfsmount *nmp = rep->r_nmp;
1944
1945         /*
1946          * The nm_send count is decremented now to avoid deadlocks
1947          * when the process in soreceive() hasn't yet managed to send
1948          * its own request.
1949          */
1950         if (rep->r_flags & R_SENT) {
1951                 rep->r_flags &= ~R_SENT;
1952         }
1953
1954         /*
1955          * If we locked the request or nobody else has locked the request,
1956          * and the request is async, we can move it to the reader thread's
1957          * queue now and fix up the state.
1958          *
1959          * If we locked the request or nobody else has locked the request,
1960          * we can wake up anyone blocked waiting for a response on the
1961          * request.
1962          */
1963         if (islocked || (rep->r_flags & R_LOCKED) == 0) {
1964                 if ((rep->r_flags & (R_ONREQQ | R_ASYNC)) ==
1965                     (R_ONREQQ | R_ASYNC)) {
1966                         rep->r_flags &= ~R_ONREQQ;
1967                         TAILQ_REMOVE(&nmp->nm_reqq, rep, r_chain);
1968                         --nmp->nm_reqqlen;
1969                         TAILQ_INSERT_TAIL(&nmp->nm_reqrxq, rep, r_chain);
1970                         KKASSERT(rep->r_info->state == NFSM_STATE_TRY ||
1971                                  rep->r_info->state == NFSM_STATE_WAITREPLY);
1972                         rep->r_info->state = NFSM_STATE_PROCESSREPLY;
1973                         nfssvc_iod_reader_wakeup(nmp);
1974                         if (TAILQ_FIRST(&nmp->nm_bioq) &&
1975                             nmp->nm_reqqlen <= nfs_maxasyncbio * 2 / 3) {
1976                                 nfssvc_iod_writer_wakeup(nmp);
1977                         }
1978                 }
1979                 mtx_abort_ex_link(&nmp->nm_rxlock, &rep->r_link);
1980         }
1981 }
1982
1983 /*
1984  * Test for a termination condition pending on the process.
1985  * This is used for NFSMNT_INT mounts.
1986  */
1987 int
1988 nfs_sigintr(struct nfsmount *nmp, struct nfsreq *rep, struct thread *td)
1989 {
1990         sigset_t tmpset;
1991         struct proc *p;
1992         struct lwp *lp;
1993
1994         if (rep && (rep->r_flags & R_SOFTTERM))
1995                 return (EINTR);
1996         /* Terminate all requests while attempting a forced unmount. */
1997         if (nmp->nm_mountp->mnt_kern_flag & MNTK_UNMOUNTF)
1998                 return (EINTR);
1999         if (!(nmp->nm_flag & NFSMNT_INT))
2000                 return (0);
2001         /* td might be NULL YYY */
2002         if (td == NULL || (p = td->td_proc) == NULL)
2003                 return (0);
2004
2005         lp = td->td_lwp;
2006         tmpset = lwp_sigpend(lp);
2007         SIGSETNAND(tmpset, lp->lwp_sigmask);
2008         SIGSETNAND(tmpset, p->p_sigignore);
2009         if (SIGNOTEMPTY(tmpset) && NFSINT_SIGMASK(tmpset))
2010                 return (EINTR);
2011
2012         return (0);
2013 }
2014
2015 /*
2016  * Lock a socket against others.
2017  * Necessary for STREAM sockets to ensure you get an entire rpc request/reply
2018  * and also to avoid race conditions between the processes with nfs requests
2019  * in progress when a reconnect is necessary.
2020  */
2021 int
2022 nfs_sndlock(struct nfsmount *nmp, struct nfsreq *rep)
2023 {
2024         mtx_t mtx = &nmp->nm_txlock;
2025         struct thread *td;
2026         int slptimeo;
2027         int slpflag;
2028         int error;
2029
2030         slpflag = 0;
2031         slptimeo = 0;
2032         td = rep ? rep->r_td : NULL;
2033         if (nmp->nm_flag & NFSMNT_INT)
2034                 slpflag = PCATCH;
2035
2036         while ((error = mtx_lock_ex_try(mtx)) != 0) {
2037                 if (nfs_sigintr(nmp, rep, td)) {
2038                         error = EINTR;
2039                         break;
2040                 }
2041                 error = mtx_lock_ex(mtx, "nfsndlck", slpflag, slptimeo);
2042                 if (error == 0)
2043                         break;
2044                 if (slpflag == PCATCH) {
2045                         slpflag = 0;
2046                         slptimeo = 2 * hz;
2047                 }
2048         }
2049         /* Always fail if our request has been cancelled. */
2050         if (rep && (rep->r_flags & R_SOFTTERM)) {
2051                 if (error == 0)
2052                         mtx_unlock(mtx);
2053                 error = EINTR;
2054         }
2055         return (error);
2056 }
2057
2058 /*
2059  * Unlock the stream socket for others.
2060  */
2061 void
2062 nfs_sndunlock(struct nfsmount *nmp)
2063 {
2064         mtx_unlock(&nmp->nm_txlock);
2065 }
2066
2067 /*
2068  * Lock the receiver side of the socket.
2069  *
2070  * rep may be NULL.
2071  */
2072 static int
2073 nfs_rcvlock(struct nfsmount *nmp, struct nfsreq *rep)
2074 {
2075         mtx_t mtx = &nmp->nm_rxlock;
2076         int slpflag;
2077         int slptimeo;
2078         int error;
2079
2080         /*
2081          * Unconditionally check for completion in case another nfsiod
2082          * get the packet while the caller was blocked, before the caller
2083          * called us.  Packet reception is handled by mainline code which
2084          * is protected by the BGL at the moment.
2085          *
2086          * We do not strictly need the second check just before the
2087          * tsleep(), but it's good defensive programming.
2088          */
2089         if (rep && rep->r_mrep != NULL)
2090                 return (EALREADY);
2091
2092         if (nmp->nm_flag & NFSMNT_INT)
2093                 slpflag = PCATCH;
2094         else
2095                 slpflag = 0;
2096         slptimeo = 0;
2097
2098         while ((error = mtx_lock_ex_try(mtx)) != 0) {
2099                 if (nfs_sigintr(nmp, rep, (rep ? rep->r_td : NULL))) {
2100                         error = EINTR;
2101                         break;
2102                 }
2103                 if (rep && rep->r_mrep != NULL) {
2104                         error = EALREADY;
2105                         break;
2106                 }
2107
2108                 /*
2109                  * NOTE: can return ENOLCK, but in that case rep->r_mrep
2110                  *       will already be set.
2111                  */
2112                 if (rep) {
2113                         error = mtx_lock_ex_link(mtx, &rep->r_link,
2114                                                  "nfsrcvlk",
2115                                                  slpflag, slptimeo);
2116                 } else {
2117                         error = mtx_lock_ex(mtx, "nfsrcvlk", slpflag, slptimeo);
2118                 }
2119                 if (error == 0)
2120                         break;
2121
2122                 /*
2123                  * If our reply was recieved while we were sleeping,
2124                  * then just return without taking the lock to avoid a
2125                  * situation where a single iod could 'capture' the
2126                  * recieve lock.
2127                  */
2128                 if (rep && rep->r_mrep != NULL) {
2129                         error = EALREADY;
2130                         break;
2131                 }
2132                 if (slpflag == PCATCH) {
2133                         slpflag = 0;
2134                         slptimeo = 2 * hz;
2135                 }
2136         }
2137         if (error == 0) {
2138                 if (rep && rep->r_mrep != NULL) {
2139                         error = EALREADY;
2140                         mtx_unlock(mtx);
2141                 }
2142         }
2143         return (error);
2144 }
2145
2146 /*
2147  * Unlock the stream socket for others.
2148  */
2149 static void
2150 nfs_rcvunlock(struct nfsmount *nmp)
2151 {
2152         mtx_unlock(&nmp->nm_rxlock);
2153 }
2154
2155 /*
2156  * nfs_realign:
2157  *
2158  * Check for badly aligned mbuf data and realign by copying the unaligned
2159  * portion of the data into a new mbuf chain and freeing the portions
2160  * of the old chain that were replaced.
2161  *
2162  * We cannot simply realign the data within the existing mbuf chain
2163  * because the underlying buffers may contain other rpc commands and
2164  * we cannot afford to overwrite them.
2165  *
2166  * We would prefer to avoid this situation entirely.  The situation does
2167  * not occur with NFS/UDP and is supposed to only occassionally occur
2168  * with TCP.  Use vfs.nfs.realign_count and realign_test to check this.
2169  *
2170  * NOTE!  MB_DONTWAIT cannot be used here.  The mbufs must be acquired
2171  *        because the rpc request OR reply cannot be thrown away.  TCP NFS
2172  *        mounts do not retry their RPCs unless the TCP connection itself
2173  *        is dropped so throwing away a RPC will basically cause the NFS
2174  *        operation to lockup indefinitely.
2175  */
2176 static void
2177 nfs_realign(struct mbuf **pm, int hsiz)
2178 {
2179         struct mbuf *m;
2180         struct mbuf *n = NULL;
2181         int off = 0;
2182
2183         ++nfs_realign_test;
2184
2185         while ((m = *pm) != NULL) {
2186                 if ((m->m_len & 0x3) || (mtod(m, intptr_t) & 0x3)) {
2187                         n = m_getl(m->m_len, MB_WAIT, MT_DATA, 0, NULL);
2188                         n->m_len = 0;
2189                         break;
2190                 }
2191                 pm = &m->m_next;
2192         }
2193
2194         /*
2195          * If n is non-NULL, loop on m copying data, then replace the
2196          * portion of the chain that had to be realigned.
2197          */
2198         if (n != NULL) {
2199                 ++nfs_realign_count;
2200                 while (m) {
2201                         m_copyback(n, off, m->m_len, mtod(m, caddr_t));
2202                         off += m->m_len;
2203                         m = m->m_next;
2204                 }
2205                 m_freem(*pm);
2206                 *pm = n;
2207         }
2208 }
2209
2210 #ifndef NFS_NOSERVER
2211
2212 /*
2213  * Parse an RPC request
2214  * - verify it
2215  * - fill in the cred struct.
2216  */
2217 int
2218 nfs_getreq(struct nfsrv_descript *nd, struct nfsd *nfsd, int has_header)
2219 {
2220         int len, i;
2221         u_int32_t *tl;
2222         struct uio uio;
2223         struct iovec iov;
2224         caddr_t cp;
2225         u_int32_t nfsvers, auth_type;
2226         uid_t nickuid;
2227         int error = 0, ticklen;
2228         struct nfsuid *nuidp;
2229         struct timeval tvin, tvout;
2230         struct nfsm_info info;
2231 #if 0                           /* until encrypted keys are implemented */
2232         NFSKERBKEYSCHED_T keys; /* stores key schedule */
2233 #endif
2234
2235         info.mrep = nd->nd_mrep;
2236         info.md = nd->nd_md;
2237         info.dpos = nd->nd_dpos;
2238
2239         if (has_header) {
2240                 NULLOUT(tl = nfsm_dissect(&info, 10 * NFSX_UNSIGNED));
2241                 nd->nd_retxid = fxdr_unsigned(u_int32_t, *tl++);
2242                 if (*tl++ != rpc_call) {
2243                         m_freem(info.mrep);
2244                         return (EBADRPC);
2245                 }
2246         } else {
2247                 NULLOUT(tl = nfsm_dissect(&info, 8 * NFSX_UNSIGNED));
2248         }
2249         nd->nd_repstat = 0;
2250         nd->nd_flag = 0;
2251         if (*tl++ != rpc_vers) {
2252                 nd->nd_repstat = ERPCMISMATCH;
2253                 nd->nd_procnum = NFSPROC_NOOP;
2254                 return (0);
2255         }
2256         if (*tl != nfs_prog) {
2257                 nd->nd_repstat = EPROGUNAVAIL;
2258                 nd->nd_procnum = NFSPROC_NOOP;
2259                 return (0);
2260         }
2261         tl++;
2262         nfsvers = fxdr_unsigned(u_int32_t, *tl++);
2263         if (nfsvers < NFS_VER2 || nfsvers > NFS_VER3) {
2264                 nd->nd_repstat = EPROGMISMATCH;
2265                 nd->nd_procnum = NFSPROC_NOOP;
2266                 return (0);
2267         }
2268         if (nfsvers == NFS_VER3)
2269                 nd->nd_flag = ND_NFSV3;
2270         nd->nd_procnum = fxdr_unsigned(u_int32_t, *tl++);
2271         if (nd->nd_procnum == NFSPROC_NULL)
2272                 return (0);
2273         if (nd->nd_procnum >= NFS_NPROCS ||
2274                 (nd->nd_procnum >= NQNFSPROC_GETLEASE) ||
2275                 (!nd->nd_flag && nd->nd_procnum > NFSV2PROC_STATFS)) {
2276                 nd->nd_repstat = EPROCUNAVAIL;
2277                 nd->nd_procnum = NFSPROC_NOOP;
2278                 return (0);
2279         }
2280         if ((nd->nd_flag & ND_NFSV3) == 0)
2281                 nd->nd_procnum = nfsv3_procid[nd->nd_procnum];
2282         auth_type = *tl++;
2283         len = fxdr_unsigned(int, *tl++);
2284         if (len < 0 || len > RPCAUTH_MAXSIZ) {
2285                 m_freem(info.mrep);
2286                 return (EBADRPC);
2287         }
2288
2289         nd->nd_flag &= ~ND_KERBAUTH;
2290         /*
2291          * Handle auth_unix or auth_kerb.
2292          */
2293         if (auth_type == rpc_auth_unix) {
2294                 len = fxdr_unsigned(int, *++tl);
2295                 if (len < 0 || len > NFS_MAXNAMLEN) {
2296                         m_freem(info.mrep);
2297                         return (EBADRPC);
2298                 }
2299                 ERROROUT(nfsm_adv(&info, nfsm_rndup(len)));
2300                 NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2301                 bzero((caddr_t)&nd->nd_cr, sizeof (struct ucred));
2302                 nd->nd_cr.cr_ref = 1;
2303                 nd->nd_cr.cr_uid = fxdr_unsigned(uid_t, *tl++);
2304                 nd->nd_cr.cr_ruid = nd->nd_cr.cr_svuid = nd->nd_cr.cr_uid;
2305                 nd->nd_cr.cr_gid = fxdr_unsigned(gid_t, *tl++);
2306                 nd->nd_cr.cr_rgid = nd->nd_cr.cr_svgid = nd->nd_cr.cr_gid;
2307                 len = fxdr_unsigned(int, *tl);
2308                 if (len < 0 || len > RPCAUTH_UNIXGIDS) {
2309                         m_freem(info.mrep);
2310                         return (EBADRPC);
2311                 }
2312                 NULLOUT(tl = nfsm_dissect(&info, (len + 2) * NFSX_UNSIGNED));
2313                 for (i = 1; i <= len; i++)
2314                     if (i < NGROUPS)
2315                         nd->nd_cr.cr_groups[i] = fxdr_unsigned(gid_t, *tl++);
2316                     else
2317                         tl++;
2318                 nd->nd_cr.cr_ngroups = (len >= NGROUPS) ? NGROUPS : (len + 1);
2319                 if (nd->nd_cr.cr_ngroups > 1)
2320                     nfsrvw_sort(nd->nd_cr.cr_groups, nd->nd_cr.cr_ngroups);
2321                 len = fxdr_unsigned(int, *++tl);
2322                 if (len < 0 || len > RPCAUTH_MAXSIZ) {
2323                         m_freem(info.mrep);
2324                         return (EBADRPC);
2325                 }
2326                 if (len > 0) {
2327                         ERROROUT(nfsm_adv(&info, nfsm_rndup(len)));
2328                 }
2329         } else if (auth_type == rpc_auth_kerb) {
2330                 switch (fxdr_unsigned(int, *tl++)) {
2331                 case RPCAKN_FULLNAME:
2332                         ticklen = fxdr_unsigned(int, *tl);
2333                         *((u_int32_t *)nfsd->nfsd_authstr) = *tl;
2334                         uio.uio_resid = nfsm_rndup(ticklen) + NFSX_UNSIGNED;
2335                         nfsd->nfsd_authlen = uio.uio_resid + NFSX_UNSIGNED;
2336                         if (uio.uio_resid > (len - 2 * NFSX_UNSIGNED)) {
2337                                 m_freem(info.mrep);
2338                                 return (EBADRPC);
2339                         }
2340                         uio.uio_offset = 0;
2341                         uio.uio_iov = &iov;
2342                         uio.uio_iovcnt = 1;
2343                         uio.uio_segflg = UIO_SYSSPACE;
2344                         iov.iov_base = (caddr_t)&nfsd->nfsd_authstr[4];
2345                         iov.iov_len = RPCAUTH_MAXSIZ - 4;
2346                         ERROROUT(nfsm_mtouio(&info, &uio, uio.uio_resid));
2347                         NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED));
2348                         if (*tl++ != rpc_auth_kerb ||
2349                                 fxdr_unsigned(int, *tl) != 4 * NFSX_UNSIGNED) {
2350                                 kprintf("Bad kerb verifier\n");
2351                                 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2352                                 nd->nd_procnum = NFSPROC_NOOP;
2353                                 return (0);
2354                         }
2355                         NULLOUT(cp = nfsm_dissect(&info, 4 * NFSX_UNSIGNED));
2356                         tl = (u_int32_t *)cp;
2357                         if (fxdr_unsigned(int, *tl) != RPCAKN_FULLNAME) {
2358                                 kprintf("Not fullname kerb verifier\n");
2359                                 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2360                                 nd->nd_procnum = NFSPROC_NOOP;
2361                                 return (0);
2362                         }
2363                         cp += NFSX_UNSIGNED;
2364                         bcopy(cp, nfsd->nfsd_verfstr, 3 * NFSX_UNSIGNED);
2365                         nfsd->nfsd_verflen = 3 * NFSX_UNSIGNED;
2366                         nd->nd_flag |= ND_KERBFULL;
2367                         nfsd->nfsd_flag |= NFSD_NEEDAUTH;
2368                         break;
2369                 case RPCAKN_NICKNAME:
2370                         if (len != 2 * NFSX_UNSIGNED) {
2371                                 kprintf("Kerb nickname short\n");
2372                                 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADCRED);
2373                                 nd->nd_procnum = NFSPROC_NOOP;
2374                                 return (0);
2375                         }
2376                         nickuid = fxdr_unsigned(uid_t, *tl);
2377                         NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED));
2378                         if (*tl++ != rpc_auth_kerb ||
2379                                 fxdr_unsigned(int, *tl) != 3 * NFSX_UNSIGNED) {
2380                                 kprintf("Kerb nick verifier bad\n");
2381                                 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2382                                 nd->nd_procnum = NFSPROC_NOOP;
2383                                 return (0);
2384                         }
2385                         NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2386                         tvin.tv_sec = *tl++;
2387                         tvin.tv_usec = *tl;
2388
2389                         for (nuidp = NUIDHASH(nfsd->nfsd_slp,nickuid)->lh_first;
2390                             nuidp != 0; nuidp = nuidp->nu_hash.le_next) {
2391                                 if (nuidp->nu_cr.cr_uid == nickuid &&
2392                                     (!nd->nd_nam2 ||
2393                                      netaddr_match(NU_NETFAM(nuidp),
2394                                       &nuidp->nu_haddr, nd->nd_nam2)))
2395                                         break;
2396                         }
2397                         if (!nuidp) {
2398                                 nd->nd_repstat =
2399                                         (NFSERR_AUTHERR|AUTH_REJECTCRED);
2400                                 nd->nd_procnum = NFSPROC_NOOP;
2401                                 return (0);
2402                         }
2403
2404                         /*
2405                          * Now, decrypt the timestamp using the session key
2406                          * and validate it.
2407                          */
2408 #ifdef NFSKERB
2409                         XXX
2410 #else
2411                         tvout.tv_sec = 0;
2412                         tvout.tv_usec = 0;
2413 #endif
2414
2415                         tvout.tv_sec = fxdr_unsigned(long, tvout.tv_sec);
2416                         tvout.tv_usec = fxdr_unsigned(long, tvout.tv_usec);
2417                         if (nuidp->nu_expire < time_second ||
2418                             nuidp->nu_timestamp.tv_sec > tvout.tv_sec ||
2419                             (nuidp->nu_timestamp.tv_sec == tvout.tv_sec &&
2420                              nuidp->nu_timestamp.tv_usec > tvout.tv_usec)) {
2421                                 nuidp->nu_expire = 0;
2422                                 nd->nd_repstat =
2423                                     (NFSERR_AUTHERR|AUTH_REJECTVERF);
2424                                 nd->nd_procnum = NFSPROC_NOOP;
2425                                 return (0);
2426                         }
2427                         nfsrv_setcred(&nuidp->nu_cr, &nd->nd_cr);
2428                         nd->nd_flag |= ND_KERBNICK;
2429                 };
2430         } else {
2431                 nd->nd_repstat = (NFSERR_AUTHERR | AUTH_REJECTCRED);
2432                 nd->nd_procnum = NFSPROC_NOOP;
2433                 return (0);
2434         }
2435
2436         nd->nd_md = info.md;
2437         nd->nd_dpos = info.dpos;
2438         return (0);
2439 nfsmout:
2440         return (error);
2441 }
2442
2443 #endif
2444
2445 /*
2446  * Send a message to the originating process's terminal.  The thread and/or
2447  * process may be NULL.  YYY the thread should not be NULL but there may
2448  * still be some uio_td's that are still being passed as NULL through to
2449  * nfsm_request().
2450  */
2451 static int
2452 nfs_msg(struct thread *td, char *server, char *msg)
2453 {
2454         tpr_t tpr;
2455
2456         if (td && td->td_proc)
2457                 tpr = tprintf_open(td->td_proc);
2458         else
2459                 tpr = NULL;
2460         tprintf(tpr, "nfs server %s: %s\n", server, msg);
2461         tprintf_close(tpr);
2462         return (0);
2463 }
2464
2465 #ifndef NFS_NOSERVER
2466 /*
2467  * Socket upcall routine for the nfsd sockets.
2468  * The caddr_t arg is a pointer to the "struct nfssvc_sock".
2469  * Essentially do as much as possible non-blocking, else punt and it will
2470  * be called with MB_WAIT from an nfsd.
2471  */
2472 void
2473 nfsrv_rcv(struct socket *so, void *arg, int waitflag)
2474 {
2475         struct nfssvc_sock *slp = (struct nfssvc_sock *)arg;
2476         struct mbuf *m;
2477         struct sockaddr *nam;
2478         struct sockbuf sio;
2479         int flags, error;
2480         int nparallel_wakeup = 0;
2481
2482         if ((slp->ns_flag & SLP_VALID) == 0)
2483                 return;
2484
2485         /*
2486          * Do not allow an infinite number of completed RPC records to build 
2487          * up before we stop reading data from the socket.  Otherwise we could
2488          * end up holding onto an unreasonable number of mbufs for requests
2489          * waiting for service.
2490          *
2491          * This should give pretty good feedback to the TCP
2492          * layer and prevents a memory crunch for other protocols.
2493          *
2494          * Note that the same service socket can be dispatched to several
2495          * nfs servers simultaniously.
2496          *
2497          * the tcp protocol callback calls us with MB_DONTWAIT.  
2498          * nfsd calls us with MB_WAIT (typically).
2499          */
2500         if (waitflag == MB_DONTWAIT && slp->ns_numrec >= nfsd_waiting / 2 + 1) {
2501                 slp->ns_flag |= SLP_NEEDQ;
2502                 goto dorecs;
2503         }
2504
2505         /*
2506          * Handle protocol specifics to parse an RPC request.  We always
2507          * pull from the socket using non-blocking I/O.
2508          */
2509         if (so->so_type == SOCK_STREAM) {
2510                 /*
2511                  * The data has to be read in an orderly fashion from a TCP
2512                  * stream, unlike a UDP socket.  It is possible for soreceive
2513                  * and/or nfsrv_getstream() to block, so make sure only one
2514                  * entity is messing around with the TCP stream at any given
2515                  * moment.  The receive sockbuf's lock in soreceive is not
2516                  * sufficient.
2517                  *
2518                  * Note that this procedure can be called from any number of
2519                  * NFS severs *OR* can be upcalled directly from a TCP
2520                  * protocol thread.
2521                  */
2522                 if (slp->ns_flag & SLP_GETSTREAM) {
2523                         slp->ns_flag |= SLP_NEEDQ;
2524                         goto dorecs;
2525                 }
2526                 slp->ns_flag |= SLP_GETSTREAM;
2527
2528                 /*
2529                  * Do soreceive().  Pull out as much data as possible without
2530                  * blocking.
2531                  */
2532                 sbinit(&sio, 1000000000);
2533                 flags = MSG_DONTWAIT;
2534                 error = so_pru_soreceive(so, &nam, NULL, &sio, NULL, &flags);
2535                 if (error || sio.sb_mb == NULL) {
2536                         if (error == EWOULDBLOCK)
2537                                 slp->ns_flag |= SLP_NEEDQ;
2538                         else
2539                                 slp->ns_flag |= SLP_DISCONN;
2540                         slp->ns_flag &= ~SLP_GETSTREAM;
2541                         goto dorecs;
2542                 }
2543                 m = sio.sb_mb;
2544                 if (slp->ns_rawend) {
2545                         slp->ns_rawend->m_next = m;
2546                         slp->ns_cc += sio.sb_cc;
2547                 } else {
2548                         slp->ns_raw = m;
2549                         slp->ns_cc = sio.sb_cc;
2550                 }
2551                 while (m->m_next)
2552                         m = m->m_next;
2553                 slp->ns_rawend = m;
2554
2555                 /*
2556                  * Now try and parse as many record(s) as we can out of the
2557                  * raw stream data.
2558                  */
2559                 error = nfsrv_getstream(slp, waitflag, &nparallel_wakeup);
2560                 if (error) {
2561                         if (error == EPERM)
2562                                 slp->ns_flag |= SLP_DISCONN;
2563                         else
2564                                 slp->ns_flag |= SLP_NEEDQ;
2565                 }
2566                 slp->ns_flag &= ~SLP_GETSTREAM;
2567         } else {
2568                 /*
2569                  * For UDP soreceive typically pulls just one packet, loop
2570                  * to get the whole batch.
2571                  */
2572                 do {
2573                         sbinit(&sio, 1000000000);
2574                         flags = MSG_DONTWAIT;
2575                         error = so_pru_soreceive(so, &nam, NULL, &sio,
2576                                                  NULL, &flags);
2577                         if (sio.sb_mb) {
2578                                 struct nfsrv_rec *rec;
2579                                 int mf = (waitflag & MB_DONTWAIT) ?
2580                                             M_NOWAIT : M_WAITOK;
2581                                 rec = kmalloc(sizeof(struct nfsrv_rec),
2582                                              M_NFSRVDESC, mf);
2583                                 if (!rec) {
2584                                         if (nam)
2585                                                 FREE(nam, M_SONAME);
2586                                         m_freem(sio.sb_mb);
2587                                         continue;
2588                                 }
2589                                 nfs_realign(&sio.sb_mb, 10 * NFSX_UNSIGNED);
2590                                 rec->nr_address = nam;
2591                                 rec->nr_packet = sio.sb_mb;
2592                                 STAILQ_INSERT_TAIL(&slp->ns_rec, rec, nr_link);
2593                                 ++slp->ns_numrec;
2594                                 ++nparallel_wakeup;
2595                         }
2596                         if (error) {
2597                                 if ((so->so_proto->pr_flags & PR_CONNREQUIRED)
2598                                         && error != EWOULDBLOCK) {
2599                                         slp->ns_flag |= SLP_DISCONN;
2600                                         goto dorecs;
2601                                 }
2602                         }
2603                 } while (sio.sb_mb);
2604         }
2605
2606         /*
2607          * If we were upcalled from the tcp protocol layer and we have
2608          * fully parsed records ready to go, or there is new data pending,
2609          * or something went wrong, try to wake up an nfsd thread to deal
2610          * with it.
2611          */
2612 dorecs:
2613         if (waitflag == MB_DONTWAIT && (slp->ns_numrec > 0
2614              || (slp->ns_flag & (SLP_NEEDQ | SLP_DISCONN)))) {
2615                 nfsrv_wakenfsd(slp, nparallel_wakeup);
2616         }
2617 }
2618
2619 /*
2620  * Try and extract an RPC request from the mbuf data list received on a
2621  * stream socket. The "waitflag" argument indicates whether or not it
2622  * can sleep.
2623  */
2624 static int
2625 nfsrv_getstream(struct nfssvc_sock *slp, int waitflag, int *countp)
2626 {
2627         struct mbuf *m, **mpp;
2628         char *cp1, *cp2;
2629         int len;
2630         struct mbuf *om, *m2, *recm;
2631         u_int32_t recmark;
2632
2633         for (;;) {
2634             if (slp->ns_reclen == 0) {
2635                 if (slp->ns_cc < NFSX_UNSIGNED)
2636                         return (0);
2637                 m = slp->ns_raw;
2638                 if (m->m_len >= NFSX_UNSIGNED) {
2639                         bcopy(mtod(m, caddr_t), (caddr_t)&recmark, NFSX_UNSIGNED);
2640                         m->m_data += NFSX_UNSIGNED;
2641                         m->m_len -= NFSX_UNSIGNED;
2642                 } else {
2643                         cp1 = (caddr_t)&recmark;
2644                         cp2 = mtod(m, caddr_t);
2645                         while (cp1 < ((caddr_t)&recmark) + NFSX_UNSIGNED) {
2646                                 while (m->m_len == 0) {
2647                                         m = m->m_next;
2648                                         cp2 = mtod(m, caddr_t);
2649                                 }
2650                                 *cp1++ = *cp2++;
2651                                 m->m_data++;
2652                                 m->m_len--;
2653                         }
2654                 }
2655                 slp->ns_cc -= NFSX_UNSIGNED;
2656                 recmark = ntohl(recmark);
2657                 slp->ns_reclen = recmark & ~0x80000000;
2658                 if (recmark & 0x80000000)
2659                         slp->ns_flag |= SLP_LASTFRAG;
2660                 else
2661                         slp->ns_flag &= ~SLP_LASTFRAG;
2662                 if (slp->ns_reclen > NFS_MAXPACKET || slp->ns_reclen <= 0) {
2663                         log(LOG_ERR, "%s (%d) from nfs client\n",
2664                             "impossible packet length",
2665                             slp->ns_reclen);
2666                         return (EPERM);
2667                 }
2668             }
2669
2670             /*
2671              * Now get the record part.
2672              *
2673              * Note that slp->ns_reclen may be 0.  Linux sometimes
2674              * generates 0-length RPCs
2675              */
2676             recm = NULL;
2677             if (slp->ns_cc == slp->ns_reclen) {
2678                 recm = slp->ns_raw;
2679                 slp->ns_raw = slp->ns_rawend = NULL;
2680                 slp->ns_cc = slp->ns_reclen = 0;
2681             } else if (slp->ns_cc > slp->ns_reclen) {
2682                 len = 0;
2683                 m = slp->ns_raw;
2684                 om = NULL;
2685
2686                 while (len < slp->ns_reclen) {
2687                         if ((len + m->m_len) > slp->ns_reclen) {
2688                                 m2 = m_copym(m, 0, slp->ns_reclen - len,
2689                                         waitflag);
2690                                 if (m2) {
2691                                         if (om) {
2692                                                 om->m_next = m2;
2693                                                 recm = slp->ns_raw;
2694                                         } else
2695                                                 recm = m2;
2696                                         m->m_data += slp->ns_reclen - len;
2697                                         m->m_len -= slp->ns_reclen - len;
2698                                         len = slp->ns_reclen;
2699                                 } else {
2700                                         return (EWOULDBLOCK);
2701                                 }
2702                         } else if ((len + m->m_len) == slp->ns_reclen) {
2703                                 om = m;
2704                                 len += m->m_len;
2705                                 m = m->m_next;
2706                                 recm = slp->ns_raw;
2707                                 om->m_next = NULL;
2708                         } else {
2709                                 om = m;
2710                                 len += m->m_len;
2711                                 m = m->m_next;
2712                         }
2713                 }
2714                 slp->ns_raw = m;
2715                 slp->ns_cc -= len;
2716                 slp->ns_reclen = 0;
2717             } else {
2718                 return (0);
2719             }
2720
2721             /*
2722              * Accumulate the fragments into a record.
2723              */
2724             mpp = &slp->ns_frag;
2725             while (*mpp)
2726                 mpp = &((*mpp)->m_next);
2727             *mpp = recm;
2728             if (slp->ns_flag & SLP_LASTFRAG) {
2729                 struct nfsrv_rec *rec;
2730                 int mf = (waitflag & MB_DONTWAIT) ? M_NOWAIT : M_WAITOK;
2731                 rec = kmalloc(sizeof(struct nfsrv_rec), M_NFSRVDESC, mf);
2732                 if (!rec) {
2733                     m_freem(slp->ns_frag);
2734                 } else {
2735                     nfs_realign(&slp->ns_frag, 10 * NFSX_UNSIGNED);
2736                     rec->nr_address = NULL;
2737                     rec->nr_packet = slp->ns_frag;
2738                     STAILQ_INSERT_TAIL(&slp->ns_rec, rec, nr_link);
2739                     ++slp->ns_numrec;
2740                     ++*countp;
2741                 }
2742                 slp->ns_frag = NULL;
2743             }
2744         }
2745 }
2746
2747 /*
2748  * Parse an RPC header.
2749  */
2750 int
2751 nfsrv_dorec(struct nfssvc_sock *slp, struct nfsd *nfsd,
2752             struct nfsrv_descript **ndp)
2753 {
2754         struct nfsrv_rec *rec;
2755         struct mbuf *m;
2756         struct sockaddr *nam;
2757         struct nfsrv_descript *nd;
2758         int error;
2759
2760         *ndp = NULL;
2761         if ((slp->ns_flag & SLP_VALID) == 0 || !STAILQ_FIRST(&slp->ns_rec))
2762                 return (ENOBUFS);
2763         rec = STAILQ_FIRST(&slp->ns_rec);
2764         STAILQ_REMOVE_HEAD(&slp->ns_rec, nr_link);
2765         KKASSERT(slp->ns_numrec > 0);
2766         --slp->ns_numrec;
2767         nam = rec->nr_address;
2768         m = rec->nr_packet;
2769         kfree(rec, M_NFSRVDESC);
2770         MALLOC(nd, struct nfsrv_descript *, sizeof (struct nfsrv_descript),
2771                 M_NFSRVDESC, M_WAITOK);
2772         nd->nd_md = nd->nd_mrep = m;
2773         nd->nd_nam2 = nam;
2774         nd->nd_dpos = mtod(m, caddr_t);
2775         error = nfs_getreq(nd, nfsd, TRUE);
2776         if (error) {
2777                 if (nam) {
2778                         FREE(nam, M_SONAME);
2779                 }
2780                 kfree((caddr_t)nd, M_NFSRVDESC);
2781                 return (error);
2782         }
2783         *ndp = nd;
2784         nfsd->nfsd_nd = nd;
2785         return (0);
2786 }
2787
2788 /*
2789  * Try to assign service sockets to nfsd threads based on the number
2790  * of new rpc requests that have been queued on the service socket.
2791  *
2792  * If no nfsd's are available or additonal requests are pending, set the
2793  * NFSD_CHECKSLP flag so that one of the running nfsds will go look for
2794  * the work in the nfssvc_sock list when it is finished processing its
2795  * current work.  This flag is only cleared when an nfsd can not find
2796  * any new work to perform.
2797  */
2798 void
2799 nfsrv_wakenfsd(struct nfssvc_sock *slp, int nparallel)
2800 {
2801         struct nfsd *nd;
2802
2803         if ((slp->ns_flag & SLP_VALID) == 0)
2804                 return;
2805         if (nparallel <= 1)
2806                 nparallel = 1;
2807         TAILQ_FOREACH(nd, &nfsd_head, nfsd_chain) {
2808                 if (nd->nfsd_flag & NFSD_WAITING) {
2809                         nd->nfsd_flag &= ~NFSD_WAITING;
2810                         if (nd->nfsd_slp)
2811                                 panic("nfsd wakeup");
2812                         slp->ns_sref++;
2813                         nd->nfsd_slp = slp;
2814                         wakeup((caddr_t)nd);
2815                         if (--nparallel == 0)
2816                                 break;
2817                 }
2818         }
2819         if (nparallel) {
2820                 slp->ns_flag |= SLP_DOREC;
2821                 nfsd_head_flag |= NFSD_CHECKSLP;
2822         }
2823 }
2824 #endif /* NFS_NOSERVER */