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