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