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