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