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