kernel - Fix excessive mbuf use in nfs_realign()
[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
2182         /*
2183          * Check for misalignemnt
2184          */
2185         ++nfs_realign_test;
2186         while ((m = *pm) != NULL) {
2187                 if ((m->m_len & 0x3) || (mtod(m, intptr_t) & 0x3))
2188                         break;
2189                 pm = &m->m_next;
2190         }
2191
2192         /*
2193          * If misalignment found make a completely new copy.
2194          */
2195         if (m) {
2196                 ++nfs_realign_count;
2197                 n = m_dup_data(m, MB_WAIT);
2198                 m_freem(*pm);
2199                 *pm = n;
2200         }
2201 }
2202
2203 #ifndef NFS_NOSERVER
2204
2205 /*
2206  * Parse an RPC request
2207  * - verify it
2208  * - fill in the cred struct.
2209  */
2210 int
2211 nfs_getreq(struct nfsrv_descript *nd, struct nfsd *nfsd, int has_header)
2212 {
2213         int len, i;
2214         u_int32_t *tl;
2215         struct uio uio;
2216         struct iovec iov;
2217         caddr_t cp;
2218         u_int32_t nfsvers, auth_type;
2219         uid_t nickuid;
2220         int error = 0, ticklen;
2221         struct nfsuid *nuidp;
2222         struct timeval tvin, tvout;
2223         struct nfsm_info info;
2224 #if 0                           /* until encrypted keys are implemented */
2225         NFSKERBKEYSCHED_T keys; /* stores key schedule */
2226 #endif
2227
2228         info.mrep = nd->nd_mrep;
2229         info.md = nd->nd_md;
2230         info.dpos = nd->nd_dpos;
2231
2232         if (has_header) {
2233                 NULLOUT(tl = nfsm_dissect(&info, 10 * NFSX_UNSIGNED));
2234                 nd->nd_retxid = fxdr_unsigned(u_int32_t, *tl++);
2235                 if (*tl++ != rpc_call) {
2236                         m_freem(info.mrep);
2237                         return (EBADRPC);
2238                 }
2239         } else {
2240                 NULLOUT(tl = nfsm_dissect(&info, 8 * NFSX_UNSIGNED));
2241         }
2242         nd->nd_repstat = 0;
2243         nd->nd_flag = 0;
2244         if (*tl++ != rpc_vers) {
2245                 nd->nd_repstat = ERPCMISMATCH;
2246                 nd->nd_procnum = NFSPROC_NOOP;
2247                 return (0);
2248         }
2249         if (*tl != nfs_prog) {
2250                 nd->nd_repstat = EPROGUNAVAIL;
2251                 nd->nd_procnum = NFSPROC_NOOP;
2252                 return (0);
2253         }
2254         tl++;
2255         nfsvers = fxdr_unsigned(u_int32_t, *tl++);
2256         if (nfsvers < NFS_VER2 || nfsvers > NFS_VER3) {
2257                 nd->nd_repstat = EPROGMISMATCH;
2258                 nd->nd_procnum = NFSPROC_NOOP;
2259                 return (0);
2260         }
2261         if (nfsvers == NFS_VER3)
2262                 nd->nd_flag = ND_NFSV3;
2263         nd->nd_procnum = fxdr_unsigned(u_int32_t, *tl++);
2264         if (nd->nd_procnum == NFSPROC_NULL)
2265                 return (0);
2266         if (nd->nd_procnum >= NFS_NPROCS ||
2267                 (nd->nd_procnum >= NQNFSPROC_GETLEASE) ||
2268                 (!nd->nd_flag && nd->nd_procnum > NFSV2PROC_STATFS)) {
2269                 nd->nd_repstat = EPROCUNAVAIL;
2270                 nd->nd_procnum = NFSPROC_NOOP;
2271                 return (0);
2272         }
2273         if ((nd->nd_flag & ND_NFSV3) == 0)
2274                 nd->nd_procnum = nfsv3_procid[nd->nd_procnum];
2275         auth_type = *tl++;
2276         len = fxdr_unsigned(int, *tl++);
2277         if (len < 0 || len > RPCAUTH_MAXSIZ) {
2278                 m_freem(info.mrep);
2279                 return (EBADRPC);
2280         }
2281
2282         nd->nd_flag &= ~ND_KERBAUTH;
2283         /*
2284          * Handle auth_unix or auth_kerb.
2285          */
2286         if (auth_type == rpc_auth_unix) {
2287                 len = fxdr_unsigned(int, *++tl);
2288                 if (len < 0 || len > NFS_MAXNAMLEN) {
2289                         m_freem(info.mrep);
2290                         return (EBADRPC);
2291                 }
2292                 ERROROUT(nfsm_adv(&info, nfsm_rndup(len)));
2293                 NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2294                 bzero((caddr_t)&nd->nd_cr, sizeof (struct ucred));
2295                 nd->nd_cr.cr_ref = 1;
2296                 nd->nd_cr.cr_uid = fxdr_unsigned(uid_t, *tl++);
2297                 nd->nd_cr.cr_ruid = nd->nd_cr.cr_svuid = nd->nd_cr.cr_uid;
2298                 nd->nd_cr.cr_gid = fxdr_unsigned(gid_t, *tl++);
2299                 nd->nd_cr.cr_rgid = nd->nd_cr.cr_svgid = nd->nd_cr.cr_gid;
2300                 len = fxdr_unsigned(int, *tl);
2301                 if (len < 0 || len > RPCAUTH_UNIXGIDS) {
2302                         m_freem(info.mrep);
2303                         return (EBADRPC);
2304                 }
2305                 NULLOUT(tl = nfsm_dissect(&info, (len + 2) * NFSX_UNSIGNED));
2306                 for (i = 1; i <= len; i++)
2307                     if (i < NGROUPS)
2308                         nd->nd_cr.cr_groups[i] = fxdr_unsigned(gid_t, *tl++);
2309                     else
2310                         tl++;
2311                 nd->nd_cr.cr_ngroups = (len >= NGROUPS) ? NGROUPS : (len + 1);
2312                 if (nd->nd_cr.cr_ngroups > 1)
2313                     nfsrvw_sort(nd->nd_cr.cr_groups, nd->nd_cr.cr_ngroups);
2314                 len = fxdr_unsigned(int, *++tl);
2315                 if (len < 0 || len > RPCAUTH_MAXSIZ) {
2316                         m_freem(info.mrep);
2317                         return (EBADRPC);
2318                 }
2319                 if (len > 0) {
2320                         ERROROUT(nfsm_adv(&info, nfsm_rndup(len)));
2321                 }
2322         } else if (auth_type == rpc_auth_kerb) {
2323                 switch (fxdr_unsigned(int, *tl++)) {
2324                 case RPCAKN_FULLNAME:
2325                         ticklen = fxdr_unsigned(int, *tl);
2326                         *((u_int32_t *)nfsd->nfsd_authstr) = *tl;
2327                         uio.uio_resid = nfsm_rndup(ticklen) + NFSX_UNSIGNED;
2328                         nfsd->nfsd_authlen = uio.uio_resid + NFSX_UNSIGNED;
2329                         if (uio.uio_resid > (len - 2 * NFSX_UNSIGNED)) {
2330                                 m_freem(info.mrep);
2331                                 return (EBADRPC);
2332                         }
2333                         uio.uio_offset = 0;
2334                         uio.uio_iov = &iov;
2335                         uio.uio_iovcnt = 1;
2336                         uio.uio_segflg = UIO_SYSSPACE;
2337                         iov.iov_base = (caddr_t)&nfsd->nfsd_authstr[4];
2338                         iov.iov_len = RPCAUTH_MAXSIZ - 4;
2339                         ERROROUT(nfsm_mtouio(&info, &uio, uio.uio_resid));
2340                         NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED));
2341                         if (*tl++ != rpc_auth_kerb ||
2342                                 fxdr_unsigned(int, *tl) != 4 * NFSX_UNSIGNED) {
2343                                 kprintf("Bad kerb verifier\n");
2344                                 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2345                                 nd->nd_procnum = NFSPROC_NOOP;
2346                                 return (0);
2347                         }
2348                         NULLOUT(cp = nfsm_dissect(&info, 4 * NFSX_UNSIGNED));
2349                         tl = (u_int32_t *)cp;
2350                         if (fxdr_unsigned(int, *tl) != RPCAKN_FULLNAME) {
2351                                 kprintf("Not fullname kerb verifier\n");
2352                                 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2353                                 nd->nd_procnum = NFSPROC_NOOP;
2354                                 return (0);
2355                         }
2356                         cp += NFSX_UNSIGNED;
2357                         bcopy(cp, nfsd->nfsd_verfstr, 3 * NFSX_UNSIGNED);
2358                         nfsd->nfsd_verflen = 3 * NFSX_UNSIGNED;
2359                         nd->nd_flag |= ND_KERBFULL;
2360                         nfsd->nfsd_flag |= NFSD_NEEDAUTH;
2361                         break;
2362                 case RPCAKN_NICKNAME:
2363                         if (len != 2 * NFSX_UNSIGNED) {
2364                                 kprintf("Kerb nickname short\n");
2365                                 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADCRED);
2366                                 nd->nd_procnum = NFSPROC_NOOP;
2367                                 return (0);
2368                         }
2369                         nickuid = fxdr_unsigned(uid_t, *tl);
2370                         NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED));
2371                         if (*tl++ != rpc_auth_kerb ||
2372                                 fxdr_unsigned(int, *tl) != 3 * NFSX_UNSIGNED) {
2373                                 kprintf("Kerb nick verifier bad\n");
2374                                 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2375                                 nd->nd_procnum = NFSPROC_NOOP;
2376                                 return (0);
2377                         }
2378                         NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2379                         tvin.tv_sec = *tl++;
2380                         tvin.tv_usec = *tl;
2381
2382                         for (nuidp = NUIDHASH(nfsd->nfsd_slp,nickuid)->lh_first;
2383                             nuidp != 0; nuidp = nuidp->nu_hash.le_next) {
2384                                 if (nuidp->nu_cr.cr_uid == nickuid &&
2385                                     (!nd->nd_nam2 ||
2386                                      netaddr_match(NU_NETFAM(nuidp),
2387                                       &nuidp->nu_haddr, nd->nd_nam2)))
2388                                         break;
2389                         }
2390                         if (!nuidp) {
2391                                 nd->nd_repstat =
2392                                         (NFSERR_AUTHERR|AUTH_REJECTCRED);
2393                                 nd->nd_procnum = NFSPROC_NOOP;
2394                                 return (0);
2395                         }
2396
2397                         /*
2398                          * Now, decrypt the timestamp using the session key
2399                          * and validate it.
2400                          */
2401 #ifdef NFSKERB
2402                         XXX
2403 #else
2404                         tvout.tv_sec = 0;
2405                         tvout.tv_usec = 0;
2406 #endif
2407
2408                         tvout.tv_sec = fxdr_unsigned(long, tvout.tv_sec);
2409                         tvout.tv_usec = fxdr_unsigned(long, tvout.tv_usec);
2410                         if (nuidp->nu_expire < time_second ||
2411                             nuidp->nu_timestamp.tv_sec > tvout.tv_sec ||
2412                             (nuidp->nu_timestamp.tv_sec == tvout.tv_sec &&
2413                              nuidp->nu_timestamp.tv_usec > tvout.tv_usec)) {
2414                                 nuidp->nu_expire = 0;
2415                                 nd->nd_repstat =
2416                                     (NFSERR_AUTHERR|AUTH_REJECTVERF);
2417                                 nd->nd_procnum = NFSPROC_NOOP;
2418                                 return (0);
2419                         }
2420                         nfsrv_setcred(&nuidp->nu_cr, &nd->nd_cr);
2421                         nd->nd_flag |= ND_KERBNICK;
2422                 };
2423         } else {
2424                 nd->nd_repstat = (NFSERR_AUTHERR | AUTH_REJECTCRED);
2425                 nd->nd_procnum = NFSPROC_NOOP;
2426                 return (0);
2427         }
2428
2429         nd->nd_md = info.md;
2430         nd->nd_dpos = info.dpos;
2431         return (0);
2432 nfsmout:
2433         return (error);
2434 }
2435
2436 #endif
2437
2438 /*
2439  * Send a message to the originating process's terminal.  The thread and/or
2440  * process may be NULL.  YYY the thread should not be NULL but there may
2441  * still be some uio_td's that are still being passed as NULL through to
2442  * nfsm_request().
2443  */
2444 static int
2445 nfs_msg(struct thread *td, char *server, char *msg)
2446 {
2447         tpr_t tpr;
2448
2449         if (td && td->td_proc)
2450                 tpr = tprintf_open(td->td_proc);
2451         else
2452                 tpr = NULL;
2453         tprintf(tpr, "nfs server %s: %s\n", server, msg);
2454         tprintf_close(tpr);
2455         return (0);
2456 }
2457
2458 #ifndef NFS_NOSERVER
2459 /*
2460  * Socket upcall routine for the nfsd sockets.
2461  * The caddr_t arg is a pointer to the "struct nfssvc_sock".
2462  * Essentially do as much as possible non-blocking, else punt and it will
2463  * be called with MB_WAIT from an nfsd.
2464  */
2465 void
2466 nfsrv_rcv(struct socket *so, void *arg, int waitflag)
2467 {
2468         struct nfssvc_sock *slp = (struct nfssvc_sock *)arg;
2469         struct mbuf *m;
2470         struct sockaddr *nam;
2471         struct sockbuf sio;
2472         int flags, error;
2473         int nparallel_wakeup = 0;
2474
2475         if ((slp->ns_flag & SLP_VALID) == 0)
2476                 return;
2477
2478         /*
2479          * Do not allow an infinite number of completed RPC records to build 
2480          * up before we stop reading data from the socket.  Otherwise we could
2481          * end up holding onto an unreasonable number of mbufs for requests
2482          * waiting for service.
2483          *
2484          * This should give pretty good feedback to the TCP
2485          * layer and prevents a memory crunch for other protocols.
2486          *
2487          * Note that the same service socket can be dispatched to several
2488          * nfs servers simultaniously.
2489          *
2490          * the tcp protocol callback calls us with MB_DONTWAIT.  
2491          * nfsd calls us with MB_WAIT (typically).
2492          */
2493         if (waitflag == MB_DONTWAIT && slp->ns_numrec >= nfsd_waiting / 2 + 1) {
2494                 slp->ns_flag |= SLP_NEEDQ;
2495                 goto dorecs;
2496         }
2497
2498         /*
2499          * Handle protocol specifics to parse an RPC request.  We always
2500          * pull from the socket using non-blocking I/O.
2501          */
2502         if (so->so_type == SOCK_STREAM) {
2503                 /*
2504                  * The data has to be read in an orderly fashion from a TCP
2505                  * stream, unlike a UDP socket.  It is possible for soreceive
2506                  * and/or nfsrv_getstream() to block, so make sure only one
2507                  * entity is messing around with the TCP stream at any given
2508                  * moment.  The receive sockbuf's lock in soreceive is not
2509                  * sufficient.
2510                  *
2511                  * Note that this procedure can be called from any number of
2512                  * NFS severs *OR* can be upcalled directly from a TCP
2513                  * protocol thread.
2514                  */
2515                 if (slp->ns_flag & SLP_GETSTREAM) {
2516                         slp->ns_flag |= SLP_NEEDQ;
2517                         goto dorecs;
2518                 }
2519                 slp->ns_flag |= SLP_GETSTREAM;
2520
2521                 /*
2522                  * Do soreceive().  Pull out as much data as possible without
2523                  * blocking.
2524                  */
2525                 sbinit(&sio, 1000000000);
2526                 flags = MSG_DONTWAIT;
2527                 error = so_pru_soreceive(so, &nam, NULL, &sio, NULL, &flags);
2528                 if (error || sio.sb_mb == NULL) {
2529                         if (error == EWOULDBLOCK)
2530                                 slp->ns_flag |= SLP_NEEDQ;
2531                         else
2532                                 slp->ns_flag |= SLP_DISCONN;
2533                         slp->ns_flag &= ~SLP_GETSTREAM;
2534                         goto dorecs;
2535                 }
2536                 m = sio.sb_mb;
2537                 if (slp->ns_rawend) {
2538                         slp->ns_rawend->m_next = m;
2539                         slp->ns_cc += sio.sb_cc;
2540                 } else {
2541                         slp->ns_raw = m;
2542                         slp->ns_cc = sio.sb_cc;
2543                 }
2544                 while (m->m_next)
2545                         m = m->m_next;
2546                 slp->ns_rawend = m;
2547
2548                 /*
2549                  * Now try and parse as many record(s) as we can out of the
2550                  * raw stream data.
2551                  */
2552                 error = nfsrv_getstream(slp, waitflag, &nparallel_wakeup);
2553                 if (error) {
2554                         if (error == EPERM)
2555                                 slp->ns_flag |= SLP_DISCONN;
2556                         else
2557                                 slp->ns_flag |= SLP_NEEDQ;
2558                 }
2559                 slp->ns_flag &= ~SLP_GETSTREAM;
2560         } else {
2561                 /*
2562                  * For UDP soreceive typically pulls just one packet, loop
2563                  * to get the whole batch.
2564                  */
2565                 do {
2566                         sbinit(&sio, 1000000000);
2567                         flags = MSG_DONTWAIT;
2568                         error = so_pru_soreceive(so, &nam, NULL, &sio,
2569                                                  NULL, &flags);
2570                         if (sio.sb_mb) {
2571                                 struct nfsrv_rec *rec;
2572                                 int mf = (waitflag & MB_DONTWAIT) ?
2573                                             M_NOWAIT : M_WAITOK;
2574                                 rec = kmalloc(sizeof(struct nfsrv_rec),
2575                                              M_NFSRVDESC, mf);
2576                                 if (!rec) {
2577                                         if (nam)
2578                                                 FREE(nam, M_SONAME);
2579                                         m_freem(sio.sb_mb);
2580                                         continue;
2581                                 }
2582                                 nfs_realign(&sio.sb_mb, 10 * NFSX_UNSIGNED);
2583                                 rec->nr_address = nam;
2584                                 rec->nr_packet = sio.sb_mb;
2585                                 STAILQ_INSERT_TAIL(&slp->ns_rec, rec, nr_link);
2586                                 ++slp->ns_numrec;
2587                                 ++nparallel_wakeup;
2588                         }
2589                         if (error) {
2590                                 if ((so->so_proto->pr_flags & PR_CONNREQUIRED)
2591                                         && error != EWOULDBLOCK) {
2592                                         slp->ns_flag |= SLP_DISCONN;
2593                                         goto dorecs;
2594                                 }
2595                         }
2596                 } while (sio.sb_mb);
2597         }
2598
2599         /*
2600          * If we were upcalled from the tcp protocol layer and we have
2601          * fully parsed records ready to go, or there is new data pending,
2602          * or something went wrong, try to wake up an nfsd thread to deal
2603          * with it.
2604          */
2605 dorecs:
2606         if (waitflag == MB_DONTWAIT && (slp->ns_numrec > 0
2607              || (slp->ns_flag & (SLP_NEEDQ | SLP_DISCONN)))) {
2608                 nfsrv_wakenfsd(slp, nparallel_wakeup);
2609         }
2610 }
2611
2612 /*
2613  * Try and extract an RPC request from the mbuf data list received on a
2614  * stream socket. The "waitflag" argument indicates whether or not it
2615  * can sleep.
2616  */
2617 static int
2618 nfsrv_getstream(struct nfssvc_sock *slp, int waitflag, int *countp)
2619 {
2620         struct mbuf *m, **mpp;
2621         char *cp1, *cp2;
2622         int len;
2623         struct mbuf *om, *m2, *recm;
2624         u_int32_t recmark;
2625
2626         for (;;) {
2627             if (slp->ns_reclen == 0) {
2628                 if (slp->ns_cc < NFSX_UNSIGNED)
2629                         return (0);
2630                 m = slp->ns_raw;
2631                 if (m->m_len >= NFSX_UNSIGNED) {
2632                         bcopy(mtod(m, caddr_t), (caddr_t)&recmark, NFSX_UNSIGNED);
2633                         m->m_data += NFSX_UNSIGNED;
2634                         m->m_len -= NFSX_UNSIGNED;
2635                 } else {
2636                         cp1 = (caddr_t)&recmark;
2637                         cp2 = mtod(m, caddr_t);
2638                         while (cp1 < ((caddr_t)&recmark) + NFSX_UNSIGNED) {
2639                                 while (m->m_len == 0) {
2640                                         m = m->m_next;
2641                                         cp2 = mtod(m, caddr_t);
2642                                 }
2643                                 *cp1++ = *cp2++;
2644                                 m->m_data++;
2645                                 m->m_len--;
2646                         }
2647                 }
2648                 slp->ns_cc -= NFSX_UNSIGNED;
2649                 recmark = ntohl(recmark);
2650                 slp->ns_reclen = recmark & ~0x80000000;
2651                 if (recmark & 0x80000000)
2652                         slp->ns_flag |= SLP_LASTFRAG;
2653                 else
2654                         slp->ns_flag &= ~SLP_LASTFRAG;
2655                 if (slp->ns_reclen > NFS_MAXPACKET || slp->ns_reclen <= 0) {
2656                         log(LOG_ERR, "%s (%d) from nfs client\n",
2657                             "impossible packet length",
2658                             slp->ns_reclen);
2659                         return (EPERM);
2660                 }
2661             }
2662
2663             /*
2664              * Now get the record part.
2665              *
2666              * Note that slp->ns_reclen may be 0.  Linux sometimes
2667              * generates 0-length RPCs
2668              */
2669             recm = NULL;
2670             if (slp->ns_cc == slp->ns_reclen) {
2671                 recm = slp->ns_raw;
2672                 slp->ns_raw = slp->ns_rawend = NULL;
2673                 slp->ns_cc = slp->ns_reclen = 0;
2674             } else if (slp->ns_cc > slp->ns_reclen) {
2675                 len = 0;
2676                 m = slp->ns_raw;
2677                 om = NULL;
2678
2679                 while (len < slp->ns_reclen) {
2680                         if ((len + m->m_len) > slp->ns_reclen) {
2681                                 m2 = m_copym(m, 0, slp->ns_reclen - len,
2682                                         waitflag);
2683                                 if (m2) {
2684                                         if (om) {
2685                                                 om->m_next = m2;
2686                                                 recm = slp->ns_raw;
2687                                         } else
2688                                                 recm = m2;
2689                                         m->m_data += slp->ns_reclen - len;
2690                                         m->m_len -= slp->ns_reclen - len;
2691                                         len = slp->ns_reclen;
2692                                 } else {
2693                                         return (EWOULDBLOCK);
2694                                 }
2695                         } else if ((len + m->m_len) == slp->ns_reclen) {
2696                                 om = m;
2697                                 len += m->m_len;
2698                                 m = m->m_next;
2699                                 recm = slp->ns_raw;
2700                                 om->m_next = NULL;
2701                         } else {
2702                                 om = m;
2703                                 len += m->m_len;
2704                                 m = m->m_next;
2705                         }
2706                 }
2707                 slp->ns_raw = m;
2708                 slp->ns_cc -= len;
2709                 slp->ns_reclen = 0;
2710             } else {
2711                 return (0);
2712             }
2713
2714             /*
2715              * Accumulate the fragments into a record.
2716              */
2717             mpp = &slp->ns_frag;
2718             while (*mpp)
2719                 mpp = &((*mpp)->m_next);
2720             *mpp = recm;
2721             if (slp->ns_flag & SLP_LASTFRAG) {
2722                 struct nfsrv_rec *rec;
2723                 int mf = (waitflag & MB_DONTWAIT) ? M_NOWAIT : M_WAITOK;
2724                 rec = kmalloc(sizeof(struct nfsrv_rec), M_NFSRVDESC, mf);
2725                 if (!rec) {
2726                     m_freem(slp->ns_frag);
2727                 } else {
2728                     nfs_realign(&slp->ns_frag, 10 * NFSX_UNSIGNED);
2729                     rec->nr_address = NULL;
2730                     rec->nr_packet = slp->ns_frag;
2731                     STAILQ_INSERT_TAIL(&slp->ns_rec, rec, nr_link);
2732                     ++slp->ns_numrec;
2733                     ++*countp;
2734                 }
2735                 slp->ns_frag = NULL;
2736             }
2737         }
2738 }
2739
2740 /*
2741  * Parse an RPC header.
2742  */
2743 int
2744 nfsrv_dorec(struct nfssvc_sock *slp, struct nfsd *nfsd,
2745             struct nfsrv_descript **ndp)
2746 {
2747         struct nfsrv_rec *rec;
2748         struct mbuf *m;
2749         struct sockaddr *nam;
2750         struct nfsrv_descript *nd;
2751         int error;
2752
2753         *ndp = NULL;
2754         if ((slp->ns_flag & SLP_VALID) == 0 || !STAILQ_FIRST(&slp->ns_rec))
2755                 return (ENOBUFS);
2756         rec = STAILQ_FIRST(&slp->ns_rec);
2757         STAILQ_REMOVE_HEAD(&slp->ns_rec, nr_link);
2758         KKASSERT(slp->ns_numrec > 0);
2759         --slp->ns_numrec;
2760         nam = rec->nr_address;
2761         m = rec->nr_packet;
2762         kfree(rec, M_NFSRVDESC);
2763         MALLOC(nd, struct nfsrv_descript *, sizeof (struct nfsrv_descript),
2764                 M_NFSRVDESC, M_WAITOK);
2765         nd->nd_md = nd->nd_mrep = m;
2766         nd->nd_nam2 = nam;
2767         nd->nd_dpos = mtod(m, caddr_t);
2768         error = nfs_getreq(nd, nfsd, TRUE);
2769         if (error) {
2770                 if (nam) {
2771                         FREE(nam, M_SONAME);
2772                 }
2773                 kfree((caddr_t)nd, M_NFSRVDESC);
2774                 return (error);
2775         }
2776         *ndp = nd;
2777         nfsd->nfsd_nd = nd;
2778         return (0);
2779 }
2780
2781 /*
2782  * Try to assign service sockets to nfsd threads based on the number
2783  * of new rpc requests that have been queued on the service socket.
2784  *
2785  * If no nfsd's are available or additonal requests are pending, set the
2786  * NFSD_CHECKSLP flag so that one of the running nfsds will go look for
2787  * the work in the nfssvc_sock list when it is finished processing its
2788  * current work.  This flag is only cleared when an nfsd can not find
2789  * any new work to perform.
2790  */
2791 void
2792 nfsrv_wakenfsd(struct nfssvc_sock *slp, int nparallel)
2793 {
2794         struct nfsd *nd;
2795
2796         if ((slp->ns_flag & SLP_VALID) == 0)
2797                 return;
2798         if (nparallel <= 1)
2799                 nparallel = 1;
2800         TAILQ_FOREACH(nd, &nfsd_head, nfsd_chain) {
2801                 if (nd->nfsd_flag & NFSD_WAITING) {
2802                         nd->nfsd_flag &= ~NFSD_WAITING;
2803                         if (nd->nfsd_slp)
2804                                 panic("nfsd wakeup");
2805                         slp->ns_sref++;
2806                         nd->nfsd_slp = slp;
2807                         wakeup((caddr_t)nd);
2808                         if (--nparallel == 0)
2809                                 break;
2810                 }
2811         }
2812         if (nparallel) {
2813                 slp->ns_flag |= SLP_DOREC;
2814                 nfsd_head_flag |= NFSD_CHECKSLP;
2815         }
2816 }
2817 #endif /* NFS_NOSERVER */