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