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