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