Correct BSD License clause numbering from 1-2-4 to 1-2-3.
[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);
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                         /*
1512                          * If the File Handle was stale, invalidate the
1513                          * lookup cache, just in case.
1514                          *
1515                          * To avoid namecache<->vnode deadlocks we must
1516                          * release the vnode lock if we hold it.
1517                          */
1518                         if (error == ESTALE) {
1519                                 struct vnode *vp = req->r_vp;
1520                                 int ltype;
1521
1522                                 ltype = lockstatus(&vp->v_lock, curthread);
1523                                 if (ltype == LK_EXCLUSIVE || ltype == LK_SHARED)
1524                                         lockmgr(&vp->v_lock, LK_RELEASE);
1525                                 cache_inval_vp(vp, CINV_CHILDREN);
1526                                 if (ltype == LK_EXCLUSIVE || ltype == LK_SHARED)
1527                                         lockmgr(&vp->v_lock, ltype);
1528                         }
1529                         if (nmp->nm_flag & NFSMNT_NFSV3) {
1530                                 KKASSERT(*req->r_mrp == info->mrep);
1531                                 KKASSERT(*req->r_mdp == info->md);
1532                                 KKASSERT(*req->r_dposp == info->dpos);
1533                                 error |= NFSERR_RETERR;
1534                         } else {
1535                                 m_freem(info->mrep);
1536                                 info->mrep = NULL;
1537                         }
1538                         m_freem(req->r_mreq);
1539                         req->r_mreq = NULL;
1540                         kfree(req, M_NFSREQ);
1541                         info->req = NULL;
1542                         return (error);
1543                 }
1544
1545                 KKASSERT(*req->r_mrp == info->mrep);
1546                 KKASSERT(*req->r_mdp == info->md);
1547                 KKASSERT(*req->r_dposp == info->dpos);
1548                 m_freem(req->r_mreq);
1549                 req->r_mreq = NULL;
1550                 kfree(req, M_NFSREQ);
1551                 return (0);
1552         }
1553         m_freem(info->mrep);
1554         info->mrep = NULL;
1555         error = EPROTONOSUPPORT;
1556 nfsmout:
1557         m_freem(req->r_mreq);
1558         req->r_mreq = NULL;
1559         kfree(req, M_NFSREQ);
1560         info->req = NULL;
1561         return (error);
1562 }
1563
1564 #ifndef NFS_NOSERVER
1565 /*
1566  * Generate the rpc reply header
1567  * siz arg. is used to decide if adding a cluster is worthwhile
1568  */
1569 int
1570 nfs_rephead(int siz, struct nfsrv_descript *nd, struct nfssvc_sock *slp,
1571             int err, struct mbuf **mrq, struct mbuf **mbp, caddr_t *bposp)
1572 {
1573         u_int32_t *tl;
1574         struct nfsm_info info;
1575
1576         siz += RPC_REPLYSIZ;
1577         info.mb = m_getl(max_hdr + siz, MB_WAIT, MT_DATA, M_PKTHDR, NULL);
1578         info.mreq = info.mb;
1579         info.mreq->m_pkthdr.len = 0;
1580         /*
1581          * If this is not a cluster, try and leave leading space
1582          * for the lower level headers.
1583          */
1584         if ((max_hdr + siz) < MINCLSIZE)
1585                 info.mreq->m_data += max_hdr;
1586         tl = mtod(info.mreq, u_int32_t *);
1587         info.mreq->m_len = 6 * NFSX_UNSIGNED;
1588         info.bpos = ((caddr_t)tl) + info.mreq->m_len;
1589         *tl++ = txdr_unsigned(nd->nd_retxid);
1590         *tl++ = rpc_reply;
1591         if (err == ERPCMISMATCH || (err & NFSERR_AUTHERR)) {
1592                 *tl++ = rpc_msgdenied;
1593                 if (err & NFSERR_AUTHERR) {
1594                         *tl++ = rpc_autherr;
1595                         *tl = txdr_unsigned(err & ~NFSERR_AUTHERR);
1596                         info.mreq->m_len -= NFSX_UNSIGNED;
1597                         info.bpos -= NFSX_UNSIGNED;
1598                 } else {
1599                         *tl++ = rpc_mismatch;
1600                         *tl++ = txdr_unsigned(RPC_VER2);
1601                         *tl = txdr_unsigned(RPC_VER2);
1602                 }
1603         } else {
1604                 *tl++ = rpc_msgaccepted;
1605
1606                 /*
1607                  * For Kerberos authentication, we must send the nickname
1608                  * verifier back, otherwise just RPCAUTH_NULL.
1609                  */
1610                 if (nd->nd_flag & ND_KERBFULL) {
1611                     struct nfsuid *nuidp;
1612                     struct timeval ktvout;
1613
1614                     for (nuidp = NUIDHASH(slp, nd->nd_cr.cr_uid)->lh_first;
1615                         nuidp != NULL; nuidp = nuidp->nu_hash.le_next) {
1616                         if (nuidp->nu_cr.cr_uid == nd->nd_cr.cr_uid &&
1617                             (!nd->nd_nam2 || netaddr_match(NU_NETFAM(nuidp),
1618                              &nuidp->nu_haddr, nd->nd_nam2)))
1619                             break;
1620                     }
1621                     if (nuidp) {
1622                         /*
1623                          * Encrypt the timestamp in ecb mode using the
1624                          * session key.
1625                          */
1626 #ifdef NFSKERB
1627                         XXX
1628 #else
1629                         ktvout.tv_sec = 0;
1630                         ktvout.tv_usec = 0;
1631 #endif
1632
1633                         *tl++ = rpc_auth_kerb;
1634                         *tl++ = txdr_unsigned(3 * NFSX_UNSIGNED);
1635                         *tl = ktvout.tv_sec;
1636                         tl = nfsm_build(&info, 3 * NFSX_UNSIGNED);
1637                         *tl++ = ktvout.tv_usec;
1638                         *tl++ = txdr_unsigned(nuidp->nu_cr.cr_uid);
1639                     } else {
1640                         *tl++ = 0;
1641                         *tl++ = 0;
1642                     }
1643                 } else {
1644                         *tl++ = 0;
1645                         *tl++ = 0;
1646                 }
1647                 switch (err) {
1648                 case EPROGUNAVAIL:
1649                         *tl = txdr_unsigned(RPC_PROGUNAVAIL);
1650                         break;
1651                 case EPROGMISMATCH:
1652                         *tl = txdr_unsigned(RPC_PROGMISMATCH);
1653                         tl = nfsm_build(&info, 2 * NFSX_UNSIGNED);
1654                         *tl++ = txdr_unsigned(2);
1655                         *tl = txdr_unsigned(3);
1656                         break;
1657                 case EPROCUNAVAIL:
1658                         *tl = txdr_unsigned(RPC_PROCUNAVAIL);
1659                         break;
1660                 case EBADRPC:
1661                         *tl = txdr_unsigned(RPC_GARBAGE);
1662                         break;
1663                 default:
1664                         *tl = 0;
1665                         if (err != NFSERR_RETVOID) {
1666                                 tl = nfsm_build(&info, NFSX_UNSIGNED);
1667                                 if (err)
1668                                     *tl = txdr_unsigned(nfsrv_errmap(nd, err));
1669                                 else
1670                                     *tl = 0;
1671                         }
1672                         break;
1673                 };
1674         }
1675
1676         if (mrq != NULL)
1677             *mrq = info.mreq;
1678         *mbp = info.mb;
1679         *bposp = info.bpos;
1680         if (err != 0 && err != NFSERR_RETVOID)
1681                 nfsstats.srvrpc_errs++;
1682         return (0);
1683 }
1684
1685
1686 #endif /* NFS_NOSERVER */
1687
1688 /*
1689  * Nfs timer routine.
1690  *
1691  * Scan the nfsreq list and retranmit any requests that have timed out
1692  * To avoid retransmission attempts on STREAM sockets (in the future) make
1693  * sure to set the r_retry field to 0 (implies nm_retry == 0).
1694  *
1695  * Requests with attached responses, terminated requests, and
1696  * locked requests are ignored.  Locked requests will be picked up
1697  * in a later timer call.
1698  */
1699 void
1700 nfs_timer_callout(void *arg /* never used */)
1701 {
1702         struct nfsmount *nmp;
1703         struct nfsreq *req;
1704 #ifndef NFS_NOSERVER
1705         struct nfssvc_sock *slp;
1706         u_quad_t cur_usec;
1707 #endif /* NFS_NOSERVER */
1708
1709         lwkt_gettoken(&nfs_token);
1710         TAILQ_FOREACH(nmp, &nfs_mountq, nm_entry) {
1711                 lwkt_gettoken(&nmp->nm_token);
1712                 TAILQ_FOREACH(req, &nmp->nm_reqq, r_chain) {
1713                         KKASSERT(nmp == req->r_nmp);
1714                         if (req->r_mrep)
1715                                 continue;
1716                         if (req->r_flags & (R_SOFTTERM | R_LOCKED))
1717                                 continue;
1718
1719                         /*
1720                          * Handle timeout/retry.  Be sure to process r_mrep
1721                          * for async requests that completed while we had
1722                          * the request locked or they will hang in the reqq
1723                          * forever.
1724                          */
1725                         req->r_flags |= R_LOCKED;
1726                         if (nfs_sigintr(nmp, req, req->r_td)) {
1727                                 nfs_softterm(req, 1);
1728                                 req->r_flags &= ~R_LOCKED;
1729                         } else {
1730                                 nfs_timer_req(req);
1731                                 if (req->r_flags & R_ASYNC) {
1732                                         if (req->r_mrep)
1733                                                 nfs_hardterm(req, 1);
1734                                         req->r_flags &= ~R_LOCKED;
1735                                         nfssvc_iod_reader_wakeup(nmp);
1736                                 } else {
1737                                         req->r_flags &= ~R_LOCKED;
1738                                 }
1739                         }
1740                         if (req->r_flags & R_WANTED) {
1741                                 req->r_flags &= ~R_WANTED;
1742                                 wakeup(req);
1743                         }
1744                 }
1745                 lwkt_reltoken(&nmp->nm_token);
1746         }
1747 #ifndef NFS_NOSERVER
1748
1749         /*
1750          * Scan the write gathering queues for writes that need to be
1751          * completed now.
1752          */
1753         cur_usec = nfs_curusec();
1754
1755         TAILQ_FOREACH(slp, &nfssvc_sockhead, ns_chain) {
1756                 /* XXX race against removal */
1757                 if (lwkt_trytoken(&slp->ns_token)) {
1758                         if (slp->ns_tq.lh_first &&
1759                             (slp->ns_tq.lh_first->nd_time <= cur_usec)) {
1760                                 nfsrv_wakenfsd(slp, 1);
1761                         }
1762                         lwkt_reltoken(&slp->ns_token);
1763                 }
1764         }
1765 #endif /* NFS_NOSERVER */
1766
1767         callout_reset(&nfs_timer_handle, nfs_ticks, nfs_timer_callout, NULL);
1768         lwkt_reltoken(&nfs_token);
1769 }
1770
1771 static
1772 void
1773 nfs_timer_req(struct nfsreq *req)
1774 {
1775         struct thread *td = &thread0; /* XXX for creds, will break if sleep */
1776         struct nfsmount *nmp = req->r_nmp;
1777         struct mbuf *m;
1778         struct socket *so;
1779         int timeo;
1780         int error;
1781
1782         /*
1783          * rtt ticks and timeout calculation.  Return if the timeout
1784          * has not been reached yet, unless the packet is flagged
1785          * for an immediate send.
1786          *
1787          * The mean rtt doesn't help when we get random I/Os, we have
1788          * to multiply by fairly large numbers.
1789          */
1790         if (req->r_rtt >= 0) {
1791                 /*
1792                  * Calculate the timeout to test against.
1793                  */
1794                 req->r_rtt++;
1795                 if (nmp->nm_flag & NFSMNT_DUMBTIMR) {
1796                         timeo = nmp->nm_timeo << NFS_RTT_SCALE_BITS;
1797                 } else if (req->r_flags & R_TIMING) {
1798                         timeo = NFS_SRTT(req) + NFS_SDRTT(req);
1799                 } else {
1800                         timeo = nmp->nm_timeo << NFS_RTT_SCALE_BITS;
1801                 }
1802                 timeo *= multt[req->r_procnum];
1803                 /* timeo is still scaled by SCALE_BITS */
1804
1805 #define NFSFS   (NFS_RTT_SCALE * NFS_HZ)
1806                 if (req->r_flags & R_TIMING) {
1807                         static long last_time;
1808                         if (nfs_showrtt && last_time != time_second) {
1809                                 kprintf("rpccmd %d NFS SRTT %d SDRTT %d "
1810                                         "timeo %d.%03d\n",
1811                                         proct[req->r_procnum],
1812                                         NFS_SRTT(req), NFS_SDRTT(req),
1813                                         timeo / NFSFS,
1814                                         timeo % NFSFS * 1000 /  NFSFS);
1815                                 last_time = time_second;
1816                         }
1817                 }
1818 #undef NFSFS
1819
1820                 /*
1821                  * deal with nfs_timer jitter.
1822                  */
1823                 timeo = (timeo >> NFS_RTT_SCALE_BITS) + 1;
1824                 if (timeo < 2)
1825                         timeo = 2;
1826
1827                 if (nmp->nm_timeouts > 0)
1828                         timeo *= nfs_backoff[nmp->nm_timeouts - 1];
1829                 if (timeo > NFS_MAXTIMEO)
1830                         timeo = NFS_MAXTIMEO;
1831                 if (req->r_rtt <= timeo) {
1832                         if ((req->r_flags & R_NEEDSXMIT) == 0)
1833                                 return;
1834                 } else if (nmp->nm_timeouts < 8) {
1835                         nmp->nm_timeouts++;
1836                 }
1837         }
1838
1839         /*
1840          * Check for server not responding
1841          */
1842         if ((req->r_flags & R_TPRINTFMSG) == 0 &&
1843              req->r_rexmit > nmp->nm_deadthresh) {
1844                 nfs_msg(req->r_td, nmp->nm_mountp->mnt_stat.f_mntfromname,
1845                         "not responding");
1846                 req->r_flags |= R_TPRINTFMSG;
1847         }
1848         if (req->r_rexmit >= req->r_retry) {    /* too many */
1849                 nfsstats.rpctimeouts++;
1850                 nfs_softterm(req, 1);
1851                 return;
1852         }
1853
1854         /*
1855          * Generally disable retransmission on reliable sockets,
1856          * unless the request is flagged for immediate send.
1857          */
1858         if (nmp->nm_sotype != SOCK_DGRAM) {
1859                 if (++req->r_rexmit > NFS_MAXREXMIT)
1860                         req->r_rexmit = NFS_MAXREXMIT;
1861                 if ((req->r_flags & R_NEEDSXMIT) == 0)
1862                         return;
1863         }
1864
1865         /*
1866          * Stop here if we do not have a socket!
1867          */
1868         if ((so = nmp->nm_so) == NULL)
1869                 return;
1870
1871         /*
1872          * If there is enough space and the window allows.. resend it.
1873          *
1874          * r_rtt is left intact in case we get an answer after the
1875          * retry that was a reply to the original packet.
1876          *
1877          * NOTE: so_pru_send()
1878          */
1879         if (ssb_space(&so->so_snd) >= req->r_mreq->m_pkthdr.len &&
1880             (req->r_flags & (R_SENT | R_NEEDSXMIT)) &&
1881            (m = m_copym(req->r_mreq, 0, M_COPYALL, MB_DONTWAIT))){
1882                 if ((nmp->nm_flag & NFSMNT_NOCONN) == 0)
1883                     error = so_pru_send(so, 0, m, NULL, NULL, td);
1884                 else
1885                     error = so_pru_send(so, 0, m, nmp->nm_nam, NULL, td);
1886                 if (error) {
1887                         if (NFSIGNORE_SOERROR(nmp->nm_soflags, error))
1888                                 so->so_error = 0;
1889                         req->r_flags |= R_NEEDSXMIT;
1890                 } else if (req->r_mrep == NULL) {
1891                         /*
1892                          * Iff first send, start timing
1893                          * else turn timing off, backoff timer
1894                          * and divide congestion window by 2.
1895                          *
1896                          * It is possible for the so_pru_send() to
1897                          * block and for us to race a reply so we
1898                          * only do this if the reply field has not
1899                          * been filled in.  R_LOCKED will prevent
1900                          * the request from being ripped out from under
1901                          * us entirely.
1902                          *
1903                          * Record the last resent procnum to aid us
1904                          * in duplicate detection on receive.
1905                          */
1906                         if ((req->r_flags & R_NEEDSXMIT) == 0) {
1907                                 if (nfs_showrexmit)
1908                                         kprintf("X");
1909                                 if (++req->r_rexmit > NFS_MAXREXMIT)
1910                                         req->r_rexmit = NFS_MAXREXMIT;
1911                                 nmp->nm_maxasync_scaled >>= 1;
1912                                 if (nmp->nm_maxasync_scaled < NFS_MINASYNC_SCALED)
1913                                         nmp->nm_maxasync_scaled = NFS_MINASYNC_SCALED;
1914                                 nfsstats.rpcretries++;
1915                                 nmp->nm_lastreprocnum = req->r_procnum;
1916                         } else {
1917                                 req->r_flags |= R_SENT;
1918                                 req->r_flags &= ~R_NEEDSXMIT;
1919                         }
1920                 }
1921         }
1922 }
1923
1924 /*
1925  * Mark all of an nfs mount's outstanding requests with R_SOFTTERM and
1926  * wait for all requests to complete. This is used by forced unmounts
1927  * to terminate any outstanding RPCs.
1928  *
1929  * Locked requests cannot be canceled but will be marked for
1930  * soft-termination.
1931  */
1932 int
1933 nfs_nmcancelreqs(struct nfsmount *nmp)
1934 {
1935         struct nfsreq *req;
1936         int i;
1937
1938         crit_enter();
1939         TAILQ_FOREACH(req, &nmp->nm_reqq, r_chain) {
1940                 if (req->r_mrep != NULL || (req->r_flags & R_SOFTTERM))
1941                         continue;
1942                 nfs_softterm(req, 0);
1943         }
1944         /* XXX  the other two queues as well */
1945         crit_exit();
1946
1947         for (i = 0; i < 30; i++) {
1948                 crit_enter();
1949                 TAILQ_FOREACH(req, &nmp->nm_reqq, r_chain) {
1950                         if (nmp == req->r_nmp)
1951                                 break;
1952                 }
1953                 crit_exit();
1954                 if (req == NULL)
1955                         return (0);
1956                 tsleep(&lbolt, 0, "nfscancel", 0);
1957         }
1958         return (EBUSY);
1959 }
1960
1961 /*
1962  * Soft-terminate a request, effectively marking it as failed.
1963  *
1964  * Must be called from within a critical section.
1965  */
1966 static void
1967 nfs_softterm(struct nfsreq *rep, int islocked)
1968 {
1969         rep->r_flags |= R_SOFTTERM;
1970         nfs_hardterm(rep, islocked);
1971 }
1972
1973 /*
1974  * Hard-terminate a request, typically after getting a response.
1975  *
1976  * The state machine can still decide to re-issue it later if necessary.
1977  *
1978  * Must be called from within a critical section.
1979  */
1980 static void
1981 nfs_hardterm(struct nfsreq *rep, int islocked)
1982 {
1983         struct nfsmount *nmp = rep->r_nmp;
1984
1985         /*
1986          * The nm_send count is decremented now to avoid deadlocks
1987          * when the process in soreceive() hasn't yet managed to send
1988          * its own request.
1989          */
1990         if (rep->r_flags & R_SENT) {
1991                 rep->r_flags &= ~R_SENT;
1992         }
1993
1994         /*
1995          * If we locked the request or nobody else has locked the request,
1996          * and the request is async, we can move it to the reader thread's
1997          * queue now and fix up the state.
1998          *
1999          * If we locked the request or nobody else has locked the request,
2000          * we can wake up anyone blocked waiting for a response on the
2001          * request.
2002          */
2003         if (islocked || (rep->r_flags & R_LOCKED) == 0) {
2004                 if ((rep->r_flags & (R_ONREQQ | R_ASYNC)) ==
2005                     (R_ONREQQ | R_ASYNC)) {
2006                         rep->r_flags &= ~R_ONREQQ;
2007                         TAILQ_REMOVE(&nmp->nm_reqq, rep, r_chain);
2008                         --nmp->nm_reqqlen;
2009                         TAILQ_INSERT_TAIL(&nmp->nm_reqrxq, rep, r_chain);
2010                         KKASSERT(rep->r_info->state == NFSM_STATE_TRY ||
2011                                  rep->r_info->state == NFSM_STATE_WAITREPLY);
2012                         rep->r_info->state = NFSM_STATE_PROCESSREPLY;
2013                         nfssvc_iod_reader_wakeup(nmp);
2014                         if (TAILQ_FIRST(&nmp->nm_bioq) &&
2015                             nmp->nm_reqqlen <= nfs_maxasyncbio * 2 / 3) {
2016                                 nfssvc_iod_writer_wakeup(nmp);
2017                         }
2018                 }
2019                 mtx_abort_ex_link(&nmp->nm_rxlock, &rep->r_link);
2020         }
2021 }
2022
2023 /*
2024  * Test for a termination condition pending on the process.
2025  * This is used for NFSMNT_INT mounts.
2026  */
2027 int
2028 nfs_sigintr(struct nfsmount *nmp, struct nfsreq *rep, struct thread *td)
2029 {
2030         sigset_t tmpset;
2031         struct proc *p;
2032         struct lwp *lp;
2033
2034         if (rep && (rep->r_flags & R_SOFTTERM))
2035                 return (EINTR);
2036         /* Terminate all requests while attempting a forced unmount. */
2037         if (nmp->nm_mountp->mnt_kern_flag & MNTK_UNMOUNTF)
2038                 return (EINTR);
2039         if (!(nmp->nm_flag & NFSMNT_INT))
2040                 return (0);
2041         /* td might be NULL YYY */
2042         if (td == NULL || (p = td->td_proc) == NULL)
2043                 return (0);
2044
2045         lp = td->td_lwp;
2046         tmpset = lwp_sigpend(lp);
2047         SIGSETNAND(tmpset, lp->lwp_sigmask);
2048         SIGSETNAND(tmpset, p->p_sigignore);
2049         if (SIGNOTEMPTY(tmpset) && NFSINT_SIGMASK(tmpset))
2050                 return (EINTR);
2051
2052         return (0);
2053 }
2054
2055 /*
2056  * Lock a socket against others.
2057  * Necessary for STREAM sockets to ensure you get an entire rpc request/reply
2058  * and also to avoid race conditions between the processes with nfs requests
2059  * in progress when a reconnect is necessary.
2060  */
2061 int
2062 nfs_sndlock(struct nfsmount *nmp, struct nfsreq *rep)
2063 {
2064         mtx_t mtx = &nmp->nm_txlock;
2065         struct thread *td;
2066         int slptimeo;
2067         int slpflag;
2068         int error;
2069
2070         slpflag = 0;
2071         slptimeo = 0;
2072         td = rep ? rep->r_td : NULL;
2073         if (nmp->nm_flag & NFSMNT_INT)
2074                 slpflag = PCATCH;
2075
2076         while ((error = mtx_lock_ex_try(mtx)) != 0) {
2077                 if (nfs_sigintr(nmp, rep, td)) {
2078                         error = EINTR;
2079                         break;
2080                 }
2081                 error = mtx_lock_ex(mtx, "nfsndlck", slpflag, slptimeo);
2082                 if (error == 0)
2083                         break;
2084                 if (slpflag == PCATCH) {
2085                         slpflag = 0;
2086                         slptimeo = 2 * hz;
2087                 }
2088         }
2089         /* Always fail if our request has been cancelled. */
2090         if (rep && (rep->r_flags & R_SOFTTERM)) {
2091                 if (error == 0)
2092                         mtx_unlock(mtx);
2093                 error = EINTR;
2094         }
2095         return (error);
2096 }
2097
2098 /*
2099  * Unlock the stream socket for others.
2100  */
2101 void
2102 nfs_sndunlock(struct nfsmount *nmp)
2103 {
2104         mtx_unlock(&nmp->nm_txlock);
2105 }
2106
2107 /*
2108  * Lock the receiver side of the socket.
2109  *
2110  * rep may be NULL.
2111  */
2112 static int
2113 nfs_rcvlock(struct nfsmount *nmp, struct nfsreq *rep)
2114 {
2115         mtx_t mtx = &nmp->nm_rxlock;
2116         int slpflag;
2117         int slptimeo;
2118         int error;
2119
2120         /*
2121          * Unconditionally check for completion in case another nfsiod
2122          * get the packet while the caller was blocked, before the caller
2123          * called us.  Packet reception is handled by mainline code which
2124          * is protected by the BGL at the moment.
2125          *
2126          * We do not strictly need the second check just before the
2127          * tsleep(), but it's good defensive programming.
2128          */
2129         if (rep && rep->r_mrep != NULL)
2130                 return (EALREADY);
2131
2132         if (nmp->nm_flag & NFSMNT_INT)
2133                 slpflag = PCATCH;
2134         else
2135                 slpflag = 0;
2136         slptimeo = 0;
2137
2138         while ((error = mtx_lock_ex_try(mtx)) != 0) {
2139                 if (nfs_sigintr(nmp, rep, (rep ? rep->r_td : NULL))) {
2140                         error = EINTR;
2141                         break;
2142                 }
2143                 if (rep && rep->r_mrep != NULL) {
2144                         error = EALREADY;
2145                         break;
2146                 }
2147
2148                 /*
2149                  * NOTE: can return ENOLCK, but in that case rep->r_mrep
2150                  *       will already be set.
2151                  */
2152                 if (rep) {
2153                         error = mtx_lock_ex_link(mtx, &rep->r_link,
2154                                                  "nfsrcvlk",
2155                                                  slpflag, slptimeo);
2156                 } else {
2157                         error = mtx_lock_ex(mtx, "nfsrcvlk", slpflag, slptimeo);
2158                 }
2159                 if (error == 0)
2160                         break;
2161
2162                 /*
2163                  * If our reply was recieved while we were sleeping,
2164                  * then just return without taking the lock to avoid a
2165                  * situation where a single iod could 'capture' the
2166                  * recieve lock.
2167                  */
2168                 if (rep && rep->r_mrep != NULL) {
2169                         error = EALREADY;
2170                         break;
2171                 }
2172                 if (slpflag == PCATCH) {
2173                         slpflag = 0;
2174                         slptimeo = 2 * hz;
2175                 }
2176         }
2177         if (error == 0) {
2178                 if (rep && rep->r_mrep != NULL) {
2179                         error = EALREADY;
2180                         mtx_unlock(mtx);
2181                 }
2182         }
2183         return (error);
2184 }
2185
2186 /*
2187  * Unlock the stream socket for others.
2188  */
2189 static void
2190 nfs_rcvunlock(struct nfsmount *nmp)
2191 {
2192         mtx_unlock(&nmp->nm_rxlock);
2193 }
2194
2195 /*
2196  * nfs_realign:
2197  *
2198  * Check for badly aligned mbuf data and realign by copying the unaligned
2199  * portion of the data into a new mbuf chain and freeing the portions
2200  * of the old chain that were replaced.
2201  *
2202  * We cannot simply realign the data within the existing mbuf chain
2203  * because the underlying buffers may contain other rpc commands and
2204  * we cannot afford to overwrite them.
2205  *
2206  * We would prefer to avoid this situation entirely.  The situation does
2207  * not occur with NFS/UDP and is supposed to only occassionally occur
2208  * with TCP.  Use vfs.nfs.realign_count and realign_test to check this.
2209  *
2210  * NOTE!  MB_DONTWAIT cannot be used here.  The mbufs must be acquired
2211  *        because the rpc request OR reply cannot be thrown away.  TCP NFS
2212  *        mounts do not retry their RPCs unless the TCP connection itself
2213  *        is dropped so throwing away a RPC will basically cause the NFS
2214  *        operation to lockup indefinitely.
2215  */
2216 static void
2217 nfs_realign(struct mbuf **pm, int hsiz)
2218 {
2219         struct mbuf *m;
2220         struct mbuf *n = NULL;
2221
2222         /*
2223          * Check for misalignemnt
2224          */
2225         ++nfs_realign_test;
2226         while ((m = *pm) != NULL) {
2227                 if ((m->m_len & 0x3) || (mtod(m, intptr_t) & 0x3))
2228                         break;
2229                 pm = &m->m_next;
2230         }
2231
2232         /*
2233          * If misalignment found make a completely new copy.
2234          */
2235         if (m) {
2236                 ++nfs_realign_count;
2237                 n = m_dup_data(m, MB_WAIT);
2238                 m_freem(*pm);
2239                 *pm = n;
2240         }
2241 }
2242
2243 #ifndef NFS_NOSERVER
2244
2245 /*
2246  * Parse an RPC request
2247  * - verify it
2248  * - fill in the cred struct.
2249  */
2250 int
2251 nfs_getreq(struct nfsrv_descript *nd, struct nfsd *nfsd, int has_header)
2252 {
2253         int len, i;
2254         u_int32_t *tl;
2255         struct uio uio;
2256         struct iovec iov;
2257         caddr_t cp;
2258         u_int32_t nfsvers, auth_type;
2259         uid_t nickuid;
2260         int error = 0, ticklen;
2261         struct nfsuid *nuidp;
2262         struct timeval tvin, tvout;
2263         struct nfsm_info info;
2264 #if 0                           /* until encrypted keys are implemented */
2265         NFSKERBKEYSCHED_T keys; /* stores key schedule */
2266 #endif
2267
2268         info.mrep = nd->nd_mrep;
2269         info.md = nd->nd_md;
2270         info.dpos = nd->nd_dpos;
2271
2272         if (has_header) {
2273                 NULLOUT(tl = nfsm_dissect(&info, 10 * NFSX_UNSIGNED));
2274                 nd->nd_retxid = fxdr_unsigned(u_int32_t, *tl++);
2275                 if (*tl++ != rpc_call) {
2276                         m_freem(info.mrep);
2277                         return (EBADRPC);
2278                 }
2279         } else {
2280                 NULLOUT(tl = nfsm_dissect(&info, 8 * NFSX_UNSIGNED));
2281         }
2282         nd->nd_repstat = 0;
2283         nd->nd_flag = 0;
2284         if (*tl++ != rpc_vers) {
2285                 nd->nd_repstat = ERPCMISMATCH;
2286                 nd->nd_procnum = NFSPROC_NOOP;
2287                 return (0);
2288         }
2289         if (*tl != nfs_prog) {
2290                 nd->nd_repstat = EPROGUNAVAIL;
2291                 nd->nd_procnum = NFSPROC_NOOP;
2292                 return (0);
2293         }
2294         tl++;
2295         nfsvers = fxdr_unsigned(u_int32_t, *tl++);
2296         if (nfsvers < NFS_VER2 || nfsvers > NFS_VER3) {
2297                 nd->nd_repstat = EPROGMISMATCH;
2298                 nd->nd_procnum = NFSPROC_NOOP;
2299                 return (0);
2300         }
2301         if (nfsvers == NFS_VER3)
2302                 nd->nd_flag = ND_NFSV3;
2303         nd->nd_procnum = fxdr_unsigned(u_int32_t, *tl++);
2304         if (nd->nd_procnum == NFSPROC_NULL)
2305                 return (0);
2306         if (nd->nd_procnum >= NFS_NPROCS ||
2307                 (nd->nd_procnum >= NQNFSPROC_GETLEASE) ||
2308                 (!nd->nd_flag && nd->nd_procnum > NFSV2PROC_STATFS)) {
2309                 nd->nd_repstat = EPROCUNAVAIL;
2310                 nd->nd_procnum = NFSPROC_NOOP;
2311                 return (0);
2312         }
2313         if ((nd->nd_flag & ND_NFSV3) == 0)
2314                 nd->nd_procnum = nfsv3_procid[nd->nd_procnum];
2315         auth_type = *tl++;
2316         len = fxdr_unsigned(int, *tl++);
2317         if (len < 0 || len > RPCAUTH_MAXSIZ) {
2318                 m_freem(info.mrep);
2319                 return (EBADRPC);
2320         }
2321
2322         nd->nd_flag &= ~ND_KERBAUTH;
2323         /*
2324          * Handle auth_unix or auth_kerb.
2325          */
2326         if (auth_type == rpc_auth_unix) {
2327                 len = fxdr_unsigned(int, *++tl);
2328                 if (len < 0 || len > NFS_MAXNAMLEN) {
2329                         m_freem(info.mrep);
2330                         return (EBADRPC);
2331                 }
2332                 ERROROUT(nfsm_adv(&info, nfsm_rndup(len)));
2333                 NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2334                 bzero((caddr_t)&nd->nd_cr, sizeof (struct ucred));
2335                 nd->nd_cr.cr_ref = 1;
2336                 nd->nd_cr.cr_uid = fxdr_unsigned(uid_t, *tl++);
2337                 nd->nd_cr.cr_ruid = nd->nd_cr.cr_svuid = nd->nd_cr.cr_uid;
2338                 nd->nd_cr.cr_gid = fxdr_unsigned(gid_t, *tl++);
2339                 nd->nd_cr.cr_rgid = nd->nd_cr.cr_svgid = nd->nd_cr.cr_gid;
2340                 len = fxdr_unsigned(int, *tl);
2341                 if (len < 0 || len > RPCAUTH_UNIXGIDS) {
2342                         m_freem(info.mrep);
2343                         return (EBADRPC);
2344                 }
2345                 NULLOUT(tl = nfsm_dissect(&info, (len + 2) * NFSX_UNSIGNED));
2346                 for (i = 1; i <= len; i++)
2347                     if (i < NGROUPS)
2348                         nd->nd_cr.cr_groups[i] = fxdr_unsigned(gid_t, *tl++);
2349                     else
2350                         tl++;
2351                 nd->nd_cr.cr_ngroups = (len >= NGROUPS) ? NGROUPS : (len + 1);
2352                 if (nd->nd_cr.cr_ngroups > 1)
2353                     nfsrvw_sort(nd->nd_cr.cr_groups, nd->nd_cr.cr_ngroups);
2354                 len = fxdr_unsigned(int, *++tl);
2355                 if (len < 0 || len > RPCAUTH_MAXSIZ) {
2356                         m_freem(info.mrep);
2357                         return (EBADRPC);
2358                 }
2359                 if (len > 0) {
2360                         ERROROUT(nfsm_adv(&info, nfsm_rndup(len)));
2361                 }
2362         } else if (auth_type == rpc_auth_kerb) {
2363                 switch (fxdr_unsigned(int, *tl++)) {
2364                 case RPCAKN_FULLNAME:
2365                         ticklen = fxdr_unsigned(int, *tl);
2366                         *((u_int32_t *)nfsd->nfsd_authstr) = *tl;
2367                         uio.uio_resid = nfsm_rndup(ticklen) + NFSX_UNSIGNED;
2368                         nfsd->nfsd_authlen = uio.uio_resid + NFSX_UNSIGNED;
2369                         if (uio.uio_resid > (len - 2 * NFSX_UNSIGNED)) {
2370                                 m_freem(info.mrep);
2371                                 return (EBADRPC);
2372                         }
2373                         uio.uio_offset = 0;
2374                         uio.uio_iov = &iov;
2375                         uio.uio_iovcnt = 1;
2376                         uio.uio_segflg = UIO_SYSSPACE;
2377                         iov.iov_base = (caddr_t)&nfsd->nfsd_authstr[4];
2378                         iov.iov_len = RPCAUTH_MAXSIZ - 4;
2379                         ERROROUT(nfsm_mtouio(&info, &uio, uio.uio_resid));
2380                         NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED));
2381                         if (*tl++ != rpc_auth_kerb ||
2382                                 fxdr_unsigned(int, *tl) != 4 * NFSX_UNSIGNED) {
2383                                 kprintf("Bad kerb verifier\n");
2384                                 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2385                                 nd->nd_procnum = NFSPROC_NOOP;
2386                                 return (0);
2387                         }
2388                         NULLOUT(cp = nfsm_dissect(&info, 4 * NFSX_UNSIGNED));
2389                         tl = (u_int32_t *)cp;
2390                         if (fxdr_unsigned(int, *tl) != RPCAKN_FULLNAME) {
2391                                 kprintf("Not fullname kerb verifier\n");
2392                                 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2393                                 nd->nd_procnum = NFSPROC_NOOP;
2394                                 return (0);
2395                         }
2396                         cp += NFSX_UNSIGNED;
2397                         bcopy(cp, nfsd->nfsd_verfstr, 3 * NFSX_UNSIGNED);
2398                         nfsd->nfsd_verflen = 3 * NFSX_UNSIGNED;
2399                         nd->nd_flag |= ND_KERBFULL;
2400                         nfsd->nfsd_flag |= NFSD_NEEDAUTH;
2401                         break;
2402                 case RPCAKN_NICKNAME:
2403                         if (len != 2 * NFSX_UNSIGNED) {
2404                                 kprintf("Kerb nickname short\n");
2405                                 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADCRED);
2406                                 nd->nd_procnum = NFSPROC_NOOP;
2407                                 return (0);
2408                         }
2409                         nickuid = fxdr_unsigned(uid_t, *tl);
2410                         NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED));
2411                         if (*tl++ != rpc_auth_kerb ||
2412                                 fxdr_unsigned(int, *tl) != 3 * NFSX_UNSIGNED) {
2413                                 kprintf("Kerb nick verifier bad\n");
2414                                 nd->nd_repstat = (NFSERR_AUTHERR|AUTH_BADVERF);
2415                                 nd->nd_procnum = NFSPROC_NOOP;
2416                                 return (0);
2417                         }
2418                         NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2419                         tvin.tv_sec = *tl++;
2420                         tvin.tv_usec = *tl;
2421
2422                         for (nuidp = NUIDHASH(nfsd->nfsd_slp,nickuid)->lh_first;
2423                             nuidp != NULL; nuidp = nuidp->nu_hash.le_next) {
2424                                 if (nuidp->nu_cr.cr_uid == nickuid &&
2425                                     (!nd->nd_nam2 ||
2426                                      netaddr_match(NU_NETFAM(nuidp),
2427                                       &nuidp->nu_haddr, nd->nd_nam2)))
2428                                         break;
2429                         }
2430                         if (!nuidp) {
2431                                 nd->nd_repstat =
2432                                         (NFSERR_AUTHERR|AUTH_REJECTCRED);
2433                                 nd->nd_procnum = NFSPROC_NOOP;
2434                                 return (0);
2435                         }
2436
2437                         /*
2438                          * Now, decrypt the timestamp using the session key
2439                          * and validate it.
2440                          */
2441 #ifdef NFSKERB
2442                         XXX
2443 #else
2444                         tvout.tv_sec = 0;
2445                         tvout.tv_usec = 0;
2446 #endif
2447
2448                         tvout.tv_sec = fxdr_unsigned(long, tvout.tv_sec);
2449                         tvout.tv_usec = fxdr_unsigned(long, tvout.tv_usec);
2450                         if (nuidp->nu_expire < time_second ||
2451                             nuidp->nu_timestamp.tv_sec > tvout.tv_sec ||
2452                             (nuidp->nu_timestamp.tv_sec == tvout.tv_sec &&
2453                              nuidp->nu_timestamp.tv_usec > tvout.tv_usec)) {
2454                                 nuidp->nu_expire = 0;
2455                                 nd->nd_repstat =
2456                                     (NFSERR_AUTHERR|AUTH_REJECTVERF);
2457                                 nd->nd_procnum = NFSPROC_NOOP;
2458                                 return (0);
2459                         }
2460                         nfsrv_setcred(&nuidp->nu_cr, &nd->nd_cr);
2461                         nd->nd_flag |= ND_KERBNICK;
2462                         break;
2463                 }
2464         } else {
2465                 nd->nd_repstat = (NFSERR_AUTHERR | AUTH_REJECTCRED);
2466                 nd->nd_procnum = NFSPROC_NOOP;
2467                 return (0);
2468         }
2469
2470         nd->nd_md = info.md;
2471         nd->nd_dpos = info.dpos;
2472         return (0);
2473 nfsmout:
2474         return (error);
2475 }
2476
2477 #endif
2478
2479 /*
2480  * Send a message to the originating process's terminal.  The thread and/or
2481  * process may be NULL.  YYY the thread should not be NULL but there may
2482  * still be some uio_td's that are still being passed as NULL through to
2483  * nfsm_request().
2484  */
2485 static int
2486 nfs_msg(struct thread *td, char *server, char *msg)
2487 {
2488         tpr_t tpr;
2489
2490         if (td && td->td_proc)
2491                 tpr = tprintf_open(td->td_proc);
2492         else
2493                 tpr = NULL;
2494         tprintf(tpr, "nfs server %s: %s\n", server, msg);
2495         tprintf_close(tpr);
2496         return (0);
2497 }
2498
2499 #ifndef NFS_NOSERVER
2500
2501 /*
2502  * Socket upcall routine for nfsd sockets.  This runs in the protocol
2503  * thread and passes waitflag == MB_DONTWAIT.
2504  */
2505 void
2506 nfsrv_rcv_upcall(struct socket *so, void *arg, int waitflag)
2507 {
2508         struct nfssvc_sock *slp = (struct nfssvc_sock *)arg;
2509
2510         if (slp->ns_needq_upcall == 0) {
2511                 slp->ns_needq_upcall = 1;       /* ok to race */
2512                 lwkt_gettoken(&nfs_token);
2513                 nfsrv_wakenfsd(slp, 1);
2514                 lwkt_reltoken(&nfs_token);
2515         }
2516 #if 0
2517         lwkt_gettoken(&slp->ns_token);
2518         slp->ns_flag |= SLP_NEEDQ;
2519         nfsrv_rcv(so, arg, waitflag);
2520         lwkt_reltoken(&slp->ns_token);
2521 #endif
2522 }
2523
2524 /*
2525  * Process new data on a receive socket.  Essentially do as much as we can
2526  * non-blocking, else punt and it will be called with MB_WAIT from an nfsd.
2527  *
2528  * slp->ns_token is held on call
2529  */
2530 void
2531 nfsrv_rcv(struct socket *so, void *arg, int waitflag)
2532 {
2533         struct nfssvc_sock *slp = (struct nfssvc_sock *)arg;
2534         struct mbuf *m;
2535         struct sockaddr *nam;
2536         struct sockbuf sio;
2537         int flags, error;
2538         int nparallel_wakeup = 0;
2539
2540         ASSERT_LWKT_TOKEN_HELD(&slp->ns_token);
2541
2542         if ((slp->ns_flag & SLP_VALID) == 0)
2543                 return;
2544
2545         /*
2546          * Do not allow an infinite number of completed RPC records to build 
2547          * up before we stop reading data from the socket.  Otherwise we could
2548          * end up holding onto an unreasonable number of mbufs for requests
2549          * waiting for service.
2550          *
2551          * This should give pretty good feedback to the TCP layer and
2552          * prevents a memory crunch for other protocols.
2553          *
2554          * Note that the same service socket can be dispatched to several
2555          * nfs servers simultaniously.  The tcp protocol callback calls us
2556          * with MB_DONTWAIT.  nfsd calls us with MB_WAIT (typically).
2557          */
2558         if (NFSRV_RECLIMIT(slp))
2559                 return;
2560
2561         /*
2562          * Handle protocol specifics to parse an RPC request.  We always
2563          * pull from the socket using non-blocking I/O.
2564          */
2565         if (so->so_type == SOCK_STREAM) {
2566                 /*
2567                  * The data has to be read in an orderly fashion from a TCP
2568                  * stream, unlike a UDP socket.  It is possible for soreceive
2569                  * and/or nfsrv_getstream() to block, so make sure only one
2570                  * entity is messing around with the TCP stream at any given
2571                  * moment.  The receive sockbuf's lock in soreceive is not
2572                  * sufficient.
2573                  */
2574                 if (slp->ns_flag & SLP_GETSTREAM)
2575                         return;
2576                 slp->ns_flag |= SLP_GETSTREAM;
2577
2578                 /*
2579                  * Do soreceive().  Pull out as much data as possible without
2580                  * blocking.
2581                  */
2582                 sbinit(&sio, 1000000000);
2583                 flags = MSG_DONTWAIT;
2584                 error = so_pru_soreceive(so, &nam, NULL, &sio, NULL, &flags);
2585                 if (error || sio.sb_mb == NULL) {
2586                         if (error != EWOULDBLOCK)
2587                                 slp->ns_flag |= SLP_DISCONN;
2588                         slp->ns_flag &= ~(SLP_GETSTREAM | SLP_NEEDQ);
2589                         goto done;
2590                 }
2591                 m = sio.sb_mb;
2592                 if (slp->ns_rawend) {
2593                         slp->ns_rawend->m_next = m;
2594                         slp->ns_cc += sio.sb_cc;
2595                 } else {
2596                         slp->ns_raw = m;
2597                         slp->ns_cc = sio.sb_cc;
2598                 }
2599                 while (m->m_next)
2600                         m = m->m_next;
2601                 slp->ns_rawend = m;
2602
2603                 /*
2604                  * Now try and parse as many record(s) as we can out of the
2605                  * raw stream data.  This will set SLP_DOREC.
2606                  */
2607                 error = nfsrv_getstream(slp, waitflag, &nparallel_wakeup);
2608                 if (error && error != EWOULDBLOCK)
2609                         slp->ns_flag |= SLP_DISCONN;
2610                 slp->ns_flag &= ~SLP_GETSTREAM;
2611         } else {
2612                 /*
2613                  * For UDP soreceive typically pulls just one packet, loop
2614                  * to get the whole batch.
2615                  */
2616                 do {
2617                         sbinit(&sio, 1000000000);
2618                         flags = MSG_DONTWAIT;
2619                         error = so_pru_soreceive(so, &nam, NULL, &sio,
2620                                                  NULL, &flags);
2621                         if (sio.sb_mb) {
2622                                 struct nfsrv_rec *rec;
2623                                 int mf = (waitflag & MB_DONTWAIT) ?
2624                                             M_NOWAIT : M_WAITOK;
2625                                 rec = kmalloc(sizeof(struct nfsrv_rec),
2626                                              M_NFSRVDESC, mf);
2627                                 if (!rec) {
2628                                         if (nam)
2629                                                 kfree(nam, M_SONAME);
2630                                         m_freem(sio.sb_mb);
2631                                         continue;
2632                                 }
2633                                 nfs_realign(&sio.sb_mb, 10 * NFSX_UNSIGNED);
2634                                 rec->nr_address = nam;
2635                                 rec->nr_packet = sio.sb_mb;
2636                                 STAILQ_INSERT_TAIL(&slp->ns_rec, rec, nr_link);
2637                                 ++slp->ns_numrec;
2638                                 slp->ns_flag |= SLP_DOREC;
2639                                 ++nparallel_wakeup;
2640                         } else {
2641                                 slp->ns_flag &= ~SLP_NEEDQ;
2642                         }
2643                         if (error) {
2644                                 if ((so->so_proto->pr_flags & PR_CONNREQUIRED)
2645                                     && error != EWOULDBLOCK) {
2646                                         slp->ns_flag |= SLP_DISCONN;
2647                                         break;
2648                                 }
2649                         }
2650                         if (NFSRV_RECLIMIT(slp))
2651                                 break;
2652                 } while (sio.sb_mb);
2653         }
2654
2655         /*
2656          * If we were upcalled from the tcp protocol layer and we have
2657          * fully parsed records ready to go, or there is new data pending,
2658          * or something went wrong, try to wake up a nfsd thread to deal
2659          * with it.
2660          */
2661 done:
2662         /* XXX this code is currently not executed (nfsrv_rcv_upcall) */
2663         if (waitflag == MB_DONTWAIT && (slp->ns_flag & SLP_ACTION_MASK)) {
2664                 lwkt_gettoken(&nfs_token);
2665                 nfsrv_wakenfsd(slp, nparallel_wakeup);
2666                 lwkt_reltoken(&nfs_token);
2667         }
2668 }
2669
2670 /*
2671  * Try and extract an RPC request from the mbuf data list received on a
2672  * stream socket. The "waitflag" argument indicates whether or not it
2673  * can sleep.
2674  */
2675 static int
2676 nfsrv_getstream(struct nfssvc_sock *slp, int waitflag, int *countp)
2677 {
2678         struct mbuf *m, **mpp;
2679         char *cp1, *cp2;
2680         int len;
2681         struct mbuf *om, *m2, *recm;
2682         u_int32_t recmark;
2683
2684         for (;;) {
2685             if (slp->ns_reclen == 0) {
2686                 if (slp->ns_cc < NFSX_UNSIGNED)
2687                         return (0);
2688                 m = slp->ns_raw;
2689                 if (m->m_len >= NFSX_UNSIGNED) {
2690                         bcopy(mtod(m, caddr_t), (caddr_t)&recmark, NFSX_UNSIGNED);
2691                         m->m_data += NFSX_UNSIGNED;
2692                         m->m_len -= NFSX_UNSIGNED;
2693                 } else {
2694                         cp1 = (caddr_t)&recmark;
2695                         cp2 = mtod(m, caddr_t);
2696                         while (cp1 < ((caddr_t)&recmark) + NFSX_UNSIGNED) {
2697                                 while (m->m_len == 0) {
2698                                         m = m->m_next;
2699                                         cp2 = mtod(m, caddr_t);
2700                                 }
2701                                 *cp1++ = *cp2++;
2702                                 m->m_data++;
2703                                 m->m_len--;
2704                         }
2705                 }
2706                 slp->ns_cc -= NFSX_UNSIGNED;
2707                 recmark = ntohl(recmark);
2708                 slp->ns_reclen = recmark & ~0x80000000;
2709                 if (recmark & 0x80000000)
2710                         slp->ns_flag |= SLP_LASTFRAG;
2711                 else
2712                         slp->ns_flag &= ~SLP_LASTFRAG;
2713                 if (slp->ns_reclen > NFS_MAXPACKET || slp->ns_reclen <= 0) {
2714                         log(LOG_ERR, "%s (%d) from nfs client\n",
2715                             "impossible packet length",
2716                             slp->ns_reclen);
2717                         return (EPERM);
2718                 }
2719             }
2720
2721             /*
2722              * Now get the record part.
2723              *
2724              * Note that slp->ns_reclen may be 0.  Linux sometimes
2725              * generates 0-length RPCs
2726              */
2727             recm = NULL;
2728             if (slp->ns_cc == slp->ns_reclen) {
2729                 recm = slp->ns_raw;
2730                 slp->ns_raw = slp->ns_rawend = NULL;
2731                 slp->ns_cc = slp->ns_reclen = 0;
2732             } else if (slp->ns_cc > slp->ns_reclen) {
2733                 len = 0;
2734                 m = slp->ns_raw;
2735                 om = NULL;
2736
2737                 while (len < slp->ns_reclen) {
2738                         if ((len + m->m_len) > slp->ns_reclen) {
2739                                 m2 = m_copym(m, 0, slp->ns_reclen - len,
2740                                         waitflag);
2741                                 if (m2) {
2742                                         if (om) {
2743                                                 om->m_next = m2;
2744                                                 recm = slp->ns_raw;
2745                                         } else
2746                                                 recm = m2;
2747                                         m->m_data += slp->ns_reclen - len;
2748                                         m->m_len -= slp->ns_reclen - len;
2749                                         len = slp->ns_reclen;
2750                                 } else {
2751                                         return (EWOULDBLOCK);
2752                                 }
2753                         } else if ((len + m->m_len) == slp->ns_reclen) {
2754                                 om = m;
2755                                 len += m->m_len;
2756                                 m = m->m_next;
2757                                 recm = slp->ns_raw;
2758                                 om->m_next = NULL;
2759                         } else {
2760                                 om = m;
2761                                 len += m->m_len;
2762                                 m = m->m_next;
2763                         }
2764                 }
2765                 slp->ns_raw = m;
2766                 slp->ns_cc -= len;
2767                 slp->ns_reclen = 0;
2768             } else {
2769                 return (0);
2770             }
2771
2772             /*
2773              * Accumulate the fragments into a record.
2774              */
2775             mpp = &slp->ns_frag;
2776             while (*mpp)
2777                 mpp = &((*mpp)->m_next);
2778             *mpp = recm;
2779             if (slp->ns_flag & SLP_LASTFRAG) {
2780                 struct nfsrv_rec *rec;
2781                 int mf = (waitflag & MB_DONTWAIT) ? M_NOWAIT : M_WAITOK;
2782                 rec = kmalloc(sizeof(struct nfsrv_rec), M_NFSRVDESC, mf);
2783                 if (!rec) {
2784                     m_freem(slp->ns_frag);
2785                 } else {
2786                     nfs_realign(&slp->ns_frag, 10 * NFSX_UNSIGNED);
2787                     rec->nr_address = NULL;
2788                     rec->nr_packet = slp->ns_frag;
2789                     STAILQ_INSERT_TAIL(&slp->ns_rec, rec, nr_link);
2790                     ++slp->ns_numrec;
2791                     slp->ns_flag |= SLP_DOREC;
2792                     ++*countp;
2793                 }
2794                 slp->ns_frag = NULL;
2795             }
2796         }
2797 }
2798
2799 #ifdef INVARIANTS
2800
2801 /*
2802  * Sanity check our mbuf chain.
2803  */
2804 static void
2805 nfs_checkpkt(struct mbuf *m, int len)
2806 {
2807         int xlen = 0;
2808         while (m) {
2809                 xlen += m->m_len;
2810                 m = m->m_next;
2811         }
2812         if (xlen != len) {
2813                 panic("nfs_checkpkt: len mismatch %d/%d mbuf %p",
2814                         xlen, len, m);
2815         }
2816 }
2817
2818 #else
2819
2820 static void
2821 nfs_checkpkt(struct mbuf *m __unused, int len __unused)
2822 {
2823 }
2824
2825 #endif
2826
2827 /*
2828  * Parse an RPC header.
2829  *
2830  * If the socket is invalid or no records are pending we return ENOBUFS.
2831  * The caller must deal with NEEDQ races.
2832  */
2833 int
2834 nfsrv_dorec(struct nfssvc_sock *slp, struct nfsd *nfsd,
2835             struct nfsrv_descript **ndp)
2836 {
2837         struct nfsrv_rec *rec;
2838         struct mbuf *m;
2839         struct sockaddr *nam;
2840         struct nfsrv_descript *nd;
2841         int error;
2842
2843         *ndp = NULL;
2844         if ((slp->ns_flag & SLP_VALID) == 0 || !STAILQ_FIRST(&slp->ns_rec))
2845                 return (ENOBUFS);
2846         rec = STAILQ_FIRST(&slp->ns_rec);
2847         STAILQ_REMOVE_HEAD(&slp->ns_rec, nr_link);
2848         KKASSERT(slp->ns_numrec > 0);
2849         if (--slp->ns_numrec == 0)
2850                 slp->ns_flag &= ~SLP_DOREC;
2851         nam = rec->nr_address;
2852         m = rec->nr_packet;
2853         kfree(rec, M_NFSRVDESC);
2854         nd = kmalloc(sizeof(struct nfsrv_descript), M_NFSRVDESC, M_WAITOK);
2855         nd->nd_md = nd->nd_mrep = m;
2856         nd->nd_nam2 = nam;
2857         nd->nd_dpos = mtod(m, caddr_t);
2858         error = nfs_getreq(nd, nfsd, TRUE);
2859         if (error) {
2860                 if (nam) {
2861                         kfree(nam, M_SONAME);
2862                 }
2863                 kfree((caddr_t)nd, M_NFSRVDESC);
2864                 return (error);
2865         }
2866         *ndp = nd;
2867         nfsd->nfsd_nd = nd;
2868         return (0);
2869 }
2870
2871 /*
2872  * Try to assign service sockets to nfsd threads based on the number
2873  * of new rpc requests that have been queued on the service socket.
2874  *
2875  * If no nfsd's are available or additonal requests are pending, set the
2876  * NFSD_CHECKSLP flag so that one of the running nfsds will go look for
2877  * the work in the nfssvc_sock list when it is finished processing its
2878  * current work.  This flag is only cleared when an nfsd can not find
2879  * any new work to perform.
2880  */
2881 void
2882 nfsrv_wakenfsd(struct nfssvc_sock *slp, int nparallel)
2883 {
2884         struct nfsd *nd;
2885
2886         if ((slp->ns_flag & SLP_VALID) == 0)
2887                 return;
2888         if (nparallel <= 1)
2889                 nparallel = 1;
2890         TAILQ_FOREACH(nd, &nfsd_head, nfsd_chain) {
2891                 if (nd->nfsd_flag & NFSD_WAITING) {
2892                         nd->nfsd_flag &= ~NFSD_WAITING;
2893                         if (nd->nfsd_slp)
2894                                 panic("nfsd wakeup");
2895                         nfsrv_slpref(slp);
2896                         nd->nfsd_slp = slp;
2897                         wakeup((caddr_t)nd);
2898                         if (--nparallel == 0)
2899                                 break;
2900                 }
2901         }
2902
2903         /*
2904          * If we couldn't assign slp then the NFSDs are all busy and
2905          * we set a flag indicating that there is pending work.
2906          */
2907         if (nparallel)
2908                 nfsd_head_flag |= NFSD_CHECKSLP;
2909 }
2910 #endif /* NFS_NOSERVER */