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