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