SUNRPC: Rename rpcb_getport_external routine
[linux-2.6.git] / net / sunrpc / xprtsock.c
1 /*
2  * linux/net/sunrpc/xprtsock.c
3  *
4  * Client-side transport implementation for sockets.
5  *
6  * TCP callback races fixes (C) 1998 Red Hat Software <alan@redhat.com>
7  * TCP send fixes (C) 1998 Red Hat Software <alan@redhat.com>
8  * TCP NFS related read + write fixes
9  *  (C) 1999 Dave Airlie, University of Limerick, Ireland <airlied@linux.ie>
10  *
11  * Rewrite of larges part of the code in order to stabilize TCP stuff.
12  * Fix behaviour when socket buffer is full.
13  *  (C) 1999 Trond Myklebust <trond.myklebust@fys.uio.no>
14  *
15  * IP socket transport implementation, (C) 2005 Chuck Lever <cel@netapp.com>
16  */
17
18 #include <linux/types.h>
19 #include <linux/slab.h>
20 #include <linux/capability.h>
21 #include <linux/pagemap.h>
22 #include <linux/errno.h>
23 #include <linux/socket.h>
24 #include <linux/in.h>
25 #include <linux/net.h>
26 #include <linux/mm.h>
27 #include <linux/udp.h>
28 #include <linux/tcp.h>
29 #include <linux/sunrpc/clnt.h>
30 #include <linux/sunrpc/sched.h>
31 #include <linux/file.h>
32
33 #include <net/sock.h>
34 #include <net/checksum.h>
35 #include <net/udp.h>
36 #include <net/tcp.h>
37
38 /*
39  * xprtsock tunables
40  */
41 unsigned int xprt_udp_slot_table_entries = RPC_DEF_SLOT_TABLE;
42 unsigned int xprt_tcp_slot_table_entries = RPC_DEF_SLOT_TABLE;
43
44 unsigned int xprt_min_resvport = RPC_DEF_MIN_RESVPORT;
45 unsigned int xprt_max_resvport = RPC_DEF_MAX_RESVPORT;
46
47 /*
48  * We can register our own files under /proc/sys/sunrpc by
49  * calling register_sysctl_table() again.  The files in that
50  * directory become the union of all files registered there.
51  *
52  * We simply need to make sure that we don't collide with
53  * someone else's file names!
54  */
55
56 #ifdef RPC_DEBUG
57
58 static unsigned int min_slot_table_size = RPC_MIN_SLOT_TABLE;
59 static unsigned int max_slot_table_size = RPC_MAX_SLOT_TABLE;
60 static unsigned int xprt_min_resvport_limit = RPC_MIN_RESVPORT;
61 static unsigned int xprt_max_resvport_limit = RPC_MAX_RESVPORT;
62
63 static struct ctl_table_header *sunrpc_table_header;
64
65 /*
66  * FIXME: changing the UDP slot table size should also resize the UDP
67  *        socket buffers for existing UDP transports
68  */
69 static ctl_table xs_tunables_table[] = {
70         {
71                 .ctl_name       = CTL_SLOTTABLE_UDP,
72                 .procname       = "udp_slot_table_entries",
73                 .data           = &xprt_udp_slot_table_entries,
74                 .maxlen         = sizeof(unsigned int),
75                 .mode           = 0644,
76                 .proc_handler   = &proc_dointvec_minmax,
77                 .strategy       = &sysctl_intvec,
78                 .extra1         = &min_slot_table_size,
79                 .extra2         = &max_slot_table_size
80         },
81         {
82                 .ctl_name       = CTL_SLOTTABLE_TCP,
83                 .procname       = "tcp_slot_table_entries",
84                 .data           = &xprt_tcp_slot_table_entries,
85                 .maxlen         = sizeof(unsigned int),
86                 .mode           = 0644,
87                 .proc_handler   = &proc_dointvec_minmax,
88                 .strategy       = &sysctl_intvec,
89                 .extra1         = &min_slot_table_size,
90                 .extra2         = &max_slot_table_size
91         },
92         {
93                 .ctl_name       = CTL_MIN_RESVPORT,
94                 .procname       = "min_resvport",
95                 .data           = &xprt_min_resvport,
96                 .maxlen         = sizeof(unsigned int),
97                 .mode           = 0644,
98                 .proc_handler   = &proc_dointvec_minmax,
99                 .strategy       = &sysctl_intvec,
100                 .extra1         = &xprt_min_resvport_limit,
101                 .extra2         = &xprt_max_resvport_limit
102         },
103         {
104                 .ctl_name       = CTL_MAX_RESVPORT,
105                 .procname       = "max_resvport",
106                 .data           = &xprt_max_resvport,
107                 .maxlen         = sizeof(unsigned int),
108                 .mode           = 0644,
109                 .proc_handler   = &proc_dointvec_minmax,
110                 .strategy       = &sysctl_intvec,
111                 .extra1         = &xprt_min_resvport_limit,
112                 .extra2         = &xprt_max_resvport_limit
113         },
114         {
115                 .ctl_name = 0,
116         },
117 };
118
119 static ctl_table sunrpc_table[] = {
120         {
121                 .ctl_name       = CTL_SUNRPC,
122                 .procname       = "sunrpc",
123                 .mode           = 0555,
124                 .child          = xs_tunables_table
125         },
126         {
127                 .ctl_name = 0,
128         },
129 };
130
131 #endif
132
133 /*
134  * How many times to try sending a request on a socket before waiting
135  * for the socket buffer to clear.
136  */
137 #define XS_SENDMSG_RETRY        (10U)
138
139 /*
140  * Time out for an RPC UDP socket connect.  UDP socket connects are
141  * synchronous, but we set a timeout anyway in case of resource
142  * exhaustion on the local host.
143  */
144 #define XS_UDP_CONN_TO          (5U * HZ)
145
146 /*
147  * Wait duration for an RPC TCP connection to be established.  Solaris
148  * NFS over TCP uses 60 seconds, for example, which is in line with how
149  * long a server takes to reboot.
150  */
151 #define XS_TCP_CONN_TO          (60U * HZ)
152
153 /*
154  * Wait duration for a reply from the RPC portmapper.
155  */
156 #define XS_BIND_TO              (60U * HZ)
157
158 /*
159  * Delay if a UDP socket connect error occurs.  This is most likely some
160  * kind of resource problem on the local host.
161  */
162 #define XS_UDP_REEST_TO         (2U * HZ)
163
164 /*
165  * The reestablish timeout allows clients to delay for a bit before attempting
166  * to reconnect to a server that just dropped our connection.
167  *
168  * We implement an exponential backoff when trying to reestablish a TCP
169  * transport connection with the server.  Some servers like to drop a TCP
170  * connection when they are overworked, so we start with a short timeout and
171  * increase over time if the server is down or not responding.
172  */
173 #define XS_TCP_INIT_REEST_TO    (3U * HZ)
174 #define XS_TCP_MAX_REEST_TO     (5U * 60 * HZ)
175
176 /*
177  * TCP idle timeout; client drops the transport socket if it is idle
178  * for this long.  Note that we also timeout UDP sockets to prevent
179  * holding port numbers when there is no RPC traffic.
180  */
181 #define XS_IDLE_DISC_TO         (5U * 60 * HZ)
182
183 #ifdef RPC_DEBUG
184 # undef  RPC_DEBUG_DATA
185 # define RPCDBG_FACILITY        RPCDBG_TRANS
186 #endif
187
188 #ifdef RPC_DEBUG_DATA
189 static void xs_pktdump(char *msg, u32 *packet, unsigned int count)
190 {
191         u8 *buf = (u8 *) packet;
192         int j;
193
194         dprintk("RPC:       %s\n", msg);
195         for (j = 0; j < count && j < 128; j += 4) {
196                 if (!(j & 31)) {
197                         if (j)
198                                 dprintk("\n");
199                         dprintk("0x%04x ", j);
200                 }
201                 dprintk("%02x%02x%02x%02x ",
202                         buf[j], buf[j+1], buf[j+2], buf[j+3]);
203         }
204         dprintk("\n");
205 }
206 #else
207 static inline void xs_pktdump(char *msg, u32 *packet, unsigned int count)
208 {
209         /* NOP */
210 }
211 #endif
212
213 struct sock_xprt {
214         struct rpc_xprt         xprt;
215
216         /*
217          * Network layer
218          */
219         struct socket *         sock;
220         struct sock *           inet;
221
222         /*
223          * State of TCP reply receive
224          */
225         __be32                  tcp_fraghdr,
226                                 tcp_xid;
227
228         u32                     tcp_offset,
229                                 tcp_reclen;
230
231         unsigned long           tcp_copied,
232                                 tcp_flags;
233
234         /*
235          * Connection of transports
236          */
237         struct delayed_work     connect_worker;
238         unsigned short          port;
239
240         /*
241          * UDP socket buffer size parameters
242          */
243         size_t                  rcvsize,
244                                 sndsize;
245
246         /*
247          * Saved socket callback addresses
248          */
249         void                    (*old_data_ready)(struct sock *, int);
250         void                    (*old_state_change)(struct sock *);
251         void                    (*old_write_space)(struct sock *);
252 };
253
254 /*
255  * TCP receive state flags
256  */
257 #define TCP_RCV_LAST_FRAG       (1UL << 0)
258 #define TCP_RCV_COPY_FRAGHDR    (1UL << 1)
259 #define TCP_RCV_COPY_XID        (1UL << 2)
260 #define TCP_RCV_COPY_DATA       (1UL << 3)
261
262 static void xs_format_peer_addresses(struct rpc_xprt *xprt)
263 {
264         struct sockaddr_in *addr = (struct sockaddr_in *) &xprt->addr;
265         char *buf;
266
267         buf = kzalloc(20, GFP_KERNEL);
268         if (buf) {
269                 snprintf(buf, 20, "%u.%u.%u.%u",
270                                 NIPQUAD(addr->sin_addr.s_addr));
271         }
272         xprt->address_strings[RPC_DISPLAY_ADDR] = buf;
273
274         buf = kzalloc(8, GFP_KERNEL);
275         if (buf) {
276                 snprintf(buf, 8, "%u",
277                                 ntohs(addr->sin_port));
278         }
279         xprt->address_strings[RPC_DISPLAY_PORT] = buf;
280
281         if (xprt->prot == IPPROTO_UDP)
282                 xprt->address_strings[RPC_DISPLAY_PROTO] = "udp";
283         else
284                 xprt->address_strings[RPC_DISPLAY_PROTO] = "tcp";
285
286         buf = kzalloc(48, GFP_KERNEL);
287         if (buf) {
288                 snprintf(buf, 48, "addr=%u.%u.%u.%u port=%u proto=%s",
289                         NIPQUAD(addr->sin_addr.s_addr),
290                         ntohs(addr->sin_port),
291                         xprt->prot == IPPROTO_UDP ? "udp" : "tcp");
292         }
293         xprt->address_strings[RPC_DISPLAY_ALL] = buf;
294 }
295
296 static void xs_free_peer_addresses(struct rpc_xprt *xprt)
297 {
298         kfree(xprt->address_strings[RPC_DISPLAY_ADDR]);
299         kfree(xprt->address_strings[RPC_DISPLAY_PORT]);
300         kfree(xprt->address_strings[RPC_DISPLAY_ALL]);
301 }
302
303 #define XS_SENDMSG_FLAGS        (MSG_DONTWAIT | MSG_NOSIGNAL)
304
305 static int xs_send_kvec(struct socket *sock, struct sockaddr *addr, int addrlen, struct kvec *vec, unsigned int base, int more)
306 {
307         struct msghdr msg = {
308                 .msg_name       = addr,
309                 .msg_namelen    = addrlen,
310                 .msg_flags      = XS_SENDMSG_FLAGS | (more ? MSG_MORE : 0),
311         };
312         struct kvec iov = {
313                 .iov_base       = vec->iov_base + base,
314                 .iov_len        = vec->iov_len - base,
315         };
316
317         if (iov.iov_len != 0)
318                 return kernel_sendmsg(sock, &msg, &iov, 1, iov.iov_len);
319         return kernel_sendmsg(sock, &msg, NULL, 0, 0);
320 }
321
322 static int xs_send_pagedata(struct socket *sock, struct xdr_buf *xdr, unsigned int base, int more)
323 {
324         struct page **ppage;
325         unsigned int remainder;
326         int err, sent = 0;
327
328         remainder = xdr->page_len - base;
329         base += xdr->page_base;
330         ppage = xdr->pages + (base >> PAGE_SHIFT);
331         base &= ~PAGE_MASK;
332         for(;;) {
333                 unsigned int len = min_t(unsigned int, PAGE_SIZE - base, remainder);
334                 int flags = XS_SENDMSG_FLAGS;
335
336                 remainder -= len;
337                 if (remainder != 0 || more)
338                         flags |= MSG_MORE;
339                 err = sock->ops->sendpage(sock, *ppage, base, len, flags);
340                 if (remainder == 0 || err != len)
341                         break;
342                 sent += err;
343                 ppage++;
344                 base = 0;
345         }
346         if (sent == 0)
347                 return err;
348         if (err > 0)
349                 sent += err;
350         return sent;
351 }
352
353 /**
354  * xs_sendpages - write pages directly to a socket
355  * @sock: socket to send on
356  * @addr: UDP only -- address of destination
357  * @addrlen: UDP only -- length of destination address
358  * @xdr: buffer containing this request
359  * @base: starting position in the buffer
360  *
361  */
362 static int xs_sendpages(struct socket *sock, struct sockaddr *addr, int addrlen, struct xdr_buf *xdr, unsigned int base)
363 {
364         unsigned int remainder = xdr->len - base;
365         int err, sent = 0;
366
367         if (unlikely(!sock))
368                 return -ENOTCONN;
369
370         clear_bit(SOCK_ASYNC_NOSPACE, &sock->flags);
371         if (base != 0) {
372                 addr = NULL;
373                 addrlen = 0;
374         }
375
376         if (base < xdr->head[0].iov_len || addr != NULL) {
377                 unsigned int len = xdr->head[0].iov_len - base;
378                 remainder -= len;
379                 err = xs_send_kvec(sock, addr, addrlen, &xdr->head[0], base, remainder != 0);
380                 if (remainder == 0 || err != len)
381                         goto out;
382                 sent += err;
383                 base = 0;
384         } else
385                 base -= xdr->head[0].iov_len;
386
387         if (base < xdr->page_len) {
388                 unsigned int len = xdr->page_len - base;
389                 remainder -= len;
390                 err = xs_send_pagedata(sock, xdr, base, remainder != 0);
391                 if (remainder == 0 || err != len)
392                         goto out;
393                 sent += err;
394                 base = 0;
395         } else
396                 base -= xdr->page_len;
397
398         if (base >= xdr->tail[0].iov_len)
399                 return sent;
400         err = xs_send_kvec(sock, NULL, 0, &xdr->tail[0], base, 0);
401 out:
402         if (sent == 0)
403                 return err;
404         if (err > 0)
405                 sent += err;
406         return sent;
407 }
408
409 /**
410  * xs_nospace - place task on wait queue if transmit was incomplete
411  * @task: task to put to sleep
412  *
413  */
414 static void xs_nospace(struct rpc_task *task)
415 {
416         struct rpc_rqst *req = task->tk_rqstp;
417         struct rpc_xprt *xprt = req->rq_xprt;
418         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
419
420         dprintk("RPC: %5u xmit incomplete (%u left of %u)\n",
421                         task->tk_pid, req->rq_slen - req->rq_bytes_sent,
422                         req->rq_slen);
423
424         if (test_bit(SOCK_ASYNC_NOSPACE, &transport->sock->flags)) {
425                 /* Protect against races with write_space */
426                 spin_lock_bh(&xprt->transport_lock);
427
428                 /* Don't race with disconnect */
429                 if (!xprt_connected(xprt))
430                         task->tk_status = -ENOTCONN;
431                 else if (test_bit(SOCK_NOSPACE, &transport->sock->flags))
432                         xprt_wait_for_buffer_space(task);
433
434                 spin_unlock_bh(&xprt->transport_lock);
435         } else
436                 /* Keep holding the socket if it is blocked */
437                 rpc_delay(task, HZ>>4);
438 }
439
440 /**
441  * xs_udp_send_request - write an RPC request to a UDP socket
442  * @task: address of RPC task that manages the state of an RPC request
443  *
444  * Return values:
445  *        0:    The request has been sent
446  *   EAGAIN:    The socket was blocked, please call again later to
447  *              complete the request
448  * ENOTCONN:    Caller needs to invoke connect logic then call again
449  *    other:    Some other error occured, the request was not sent
450  */
451 static int xs_udp_send_request(struct rpc_task *task)
452 {
453         struct rpc_rqst *req = task->tk_rqstp;
454         struct rpc_xprt *xprt = req->rq_xprt;
455         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
456         struct xdr_buf *xdr = &req->rq_snd_buf;
457         int status;
458
459         xs_pktdump("packet data:",
460                                 req->rq_svec->iov_base,
461                                 req->rq_svec->iov_len);
462
463         req->rq_xtime = jiffies;
464         status = xs_sendpages(transport->sock,
465                               (struct sockaddr *) &xprt->addr,
466                               xprt->addrlen, xdr,
467                               req->rq_bytes_sent);
468
469         dprintk("RPC:       xs_udp_send_request(%u) = %d\n",
470                         xdr->len - req->rq_bytes_sent, status);
471
472         if (likely(status >= (int) req->rq_slen))
473                 return 0;
474
475         /* Still some bytes left; set up for a retry later. */
476         if (status > 0)
477                 status = -EAGAIN;
478
479         switch (status) {
480         case -ENETUNREACH:
481         case -EPIPE:
482         case -ECONNREFUSED:
483                 /* When the server has died, an ICMP port unreachable message
484                  * prompts ECONNREFUSED. */
485                 break;
486         case -EAGAIN:
487                 xs_nospace(task);
488                 break;
489         default:
490                 dprintk("RPC:       sendmsg returned unrecognized error %d\n",
491                         -status);
492                 break;
493         }
494
495         return status;
496 }
497
498 static inline void xs_encode_tcp_record_marker(struct xdr_buf *buf)
499 {
500         u32 reclen = buf->len - sizeof(rpc_fraghdr);
501         rpc_fraghdr *base = buf->head[0].iov_base;
502         *base = htonl(RPC_LAST_STREAM_FRAGMENT | reclen);
503 }
504
505 /**
506  * xs_tcp_send_request - write an RPC request to a TCP socket
507  * @task: address of RPC task that manages the state of an RPC request
508  *
509  * Return values:
510  *        0:    The request has been sent
511  *   EAGAIN:    The socket was blocked, please call again later to
512  *              complete the request
513  * ENOTCONN:    Caller needs to invoke connect logic then call again
514  *    other:    Some other error occured, the request was not sent
515  *
516  * XXX: In the case of soft timeouts, should we eventually give up
517  *      if sendmsg is not able to make progress?
518  */
519 static int xs_tcp_send_request(struct rpc_task *task)
520 {
521         struct rpc_rqst *req = task->tk_rqstp;
522         struct rpc_xprt *xprt = req->rq_xprt;
523         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
524         struct xdr_buf *xdr = &req->rq_snd_buf;
525         int status, retry = 0;
526
527         xs_encode_tcp_record_marker(&req->rq_snd_buf);
528
529         xs_pktdump("packet data:",
530                                 req->rq_svec->iov_base,
531                                 req->rq_svec->iov_len);
532
533         /* Continue transmitting the packet/record. We must be careful
534          * to cope with writespace callbacks arriving _after_ we have
535          * called sendmsg(). */
536         while (1) {
537                 req->rq_xtime = jiffies;
538                 status = xs_sendpages(transport->sock,
539                                         NULL, 0, xdr, req->rq_bytes_sent);
540
541                 dprintk("RPC:       xs_tcp_send_request(%u) = %d\n",
542                                 xdr->len - req->rq_bytes_sent, status);
543
544                 if (unlikely(status < 0))
545                         break;
546
547                 /* If we've sent the entire packet, immediately
548                  * reset the count of bytes sent. */
549                 req->rq_bytes_sent += status;
550                 task->tk_bytes_sent += status;
551                 if (likely(req->rq_bytes_sent >= req->rq_slen)) {
552                         req->rq_bytes_sent = 0;
553                         return 0;
554                 }
555
556                 status = -EAGAIN;
557                 if (retry++ > XS_SENDMSG_RETRY)
558                         break;
559         }
560
561         switch (status) {
562         case -EAGAIN:
563                 xs_nospace(task);
564                 break;
565         case -ECONNREFUSED:
566         case -ECONNRESET:
567         case -ENOTCONN:
568         case -EPIPE:
569                 status = -ENOTCONN;
570                 break;
571         default:
572                 dprintk("RPC:       sendmsg returned unrecognized error %d\n",
573                         -status);
574                 xprt_disconnect(xprt);
575                 break;
576         }
577
578         return status;
579 }
580
581 /**
582  * xs_tcp_release_xprt - clean up after a tcp transmission
583  * @xprt: transport
584  * @task: rpc task
585  *
586  * This cleans up if an error causes us to abort the transmission of a request.
587  * In this case, the socket may need to be reset in order to avoid confusing
588  * the server.
589  */
590 static void xs_tcp_release_xprt(struct rpc_xprt *xprt, struct rpc_task *task)
591 {
592         struct rpc_rqst *req;
593
594         if (task != xprt->snd_task)
595                 return;
596         if (task == NULL)
597                 goto out_release;
598         req = task->tk_rqstp;
599         if (req->rq_bytes_sent == 0)
600                 goto out_release;
601         if (req->rq_bytes_sent == req->rq_snd_buf.len)
602                 goto out_release;
603         set_bit(XPRT_CLOSE_WAIT, &task->tk_xprt->state);
604 out_release:
605         xprt_release_xprt(xprt, task);
606 }
607
608 /**
609  * xs_close - close a socket
610  * @xprt: transport
611  *
612  * This is used when all requests are complete; ie, no DRC state remains
613  * on the server we want to save.
614  */
615 static void xs_close(struct rpc_xprt *xprt)
616 {
617         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
618         struct socket *sock = transport->sock;
619         struct sock *sk = transport->inet;
620
621         if (!sk)
622                 goto clear_close_wait;
623
624         dprintk("RPC:       xs_close xprt %p\n", xprt);
625
626         write_lock_bh(&sk->sk_callback_lock);
627         transport->inet = NULL;
628         transport->sock = NULL;
629
630         sk->sk_user_data = NULL;
631         sk->sk_data_ready = transport->old_data_ready;
632         sk->sk_state_change = transport->old_state_change;
633         sk->sk_write_space = transport->old_write_space;
634         write_unlock_bh(&sk->sk_callback_lock);
635
636         sk->sk_no_check = 0;
637
638         sock_release(sock);
639 clear_close_wait:
640         smp_mb__before_clear_bit();
641         clear_bit(XPRT_CLOSE_WAIT, &xprt->state);
642         smp_mb__after_clear_bit();
643 }
644
645 /**
646  * xs_destroy - prepare to shutdown a transport
647  * @xprt: doomed transport
648  *
649  */
650 static void xs_destroy(struct rpc_xprt *xprt)
651 {
652         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
653
654         dprintk("RPC:       xs_destroy xprt %p\n", xprt);
655
656         cancel_rearming_delayed_work(&transport->connect_worker);
657
658         xprt_disconnect(xprt);
659         xs_close(xprt);
660         xs_free_peer_addresses(xprt);
661         kfree(xprt->slot);
662         kfree(xprt);
663 }
664
665 static inline struct rpc_xprt *xprt_from_sock(struct sock *sk)
666 {
667         return (struct rpc_xprt *) sk->sk_user_data;
668 }
669
670 /**
671  * xs_udp_data_ready - "data ready" callback for UDP sockets
672  * @sk: socket with data to read
673  * @len: how much data to read
674  *
675  */
676 static void xs_udp_data_ready(struct sock *sk, int len)
677 {
678         struct rpc_task *task;
679         struct rpc_xprt *xprt;
680         struct rpc_rqst *rovr;
681         struct sk_buff *skb;
682         int err, repsize, copied;
683         u32 _xid;
684         __be32 *xp;
685
686         read_lock(&sk->sk_callback_lock);
687         dprintk("RPC:       xs_udp_data_ready...\n");
688         if (!(xprt = xprt_from_sock(sk)))
689                 goto out;
690
691         if ((skb = skb_recv_datagram(sk, 0, 1, &err)) == NULL)
692                 goto out;
693
694         if (xprt->shutdown)
695                 goto dropit;
696
697         repsize = skb->len - sizeof(struct udphdr);
698         if (repsize < 4) {
699                 dprintk("RPC:       impossible RPC reply size %d!\n", repsize);
700                 goto dropit;
701         }
702
703         /* Copy the XID from the skb... */
704         xp = skb_header_pointer(skb, sizeof(struct udphdr),
705                                 sizeof(_xid), &_xid);
706         if (xp == NULL)
707                 goto dropit;
708
709         /* Look up and lock the request corresponding to the given XID */
710         spin_lock(&xprt->transport_lock);
711         rovr = xprt_lookup_rqst(xprt, *xp);
712         if (!rovr)
713                 goto out_unlock;
714         task = rovr->rq_task;
715
716         if ((copied = rovr->rq_private_buf.buflen) > repsize)
717                 copied = repsize;
718
719         /* Suck it into the iovec, verify checksum if not done by hw. */
720         if (csum_partial_copy_to_xdr(&rovr->rq_private_buf, skb))
721                 goto out_unlock;
722
723         /* Something worked... */
724         dst_confirm(skb->dst);
725
726         xprt_adjust_cwnd(task, copied);
727         xprt_update_rtt(task);
728         xprt_complete_rqst(task, copied);
729
730  out_unlock:
731         spin_unlock(&xprt->transport_lock);
732  dropit:
733         skb_free_datagram(sk, skb);
734  out:
735         read_unlock(&sk->sk_callback_lock);
736 }
737
738 static inline void xs_tcp_read_fraghdr(struct rpc_xprt *xprt, struct xdr_skb_reader *desc)
739 {
740         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
741         size_t len, used;
742         char *p;
743
744         p = ((char *) &transport->tcp_fraghdr) + transport->tcp_offset;
745         len = sizeof(transport->tcp_fraghdr) - transport->tcp_offset;
746         used = xdr_skb_read_bits(desc, p, len);
747         transport->tcp_offset += used;
748         if (used != len)
749                 return;
750
751         transport->tcp_reclen = ntohl(transport->tcp_fraghdr);
752         if (transport->tcp_reclen & RPC_LAST_STREAM_FRAGMENT)
753                 transport->tcp_flags |= TCP_RCV_LAST_FRAG;
754         else
755                 transport->tcp_flags &= ~TCP_RCV_LAST_FRAG;
756         transport->tcp_reclen &= RPC_FRAGMENT_SIZE_MASK;
757
758         transport->tcp_flags &= ~TCP_RCV_COPY_FRAGHDR;
759         transport->tcp_offset = 0;
760
761         /* Sanity check of the record length */
762         if (unlikely(transport->tcp_reclen < 4)) {
763                 dprintk("RPC:       invalid TCP record fragment length\n");
764                 xprt_disconnect(xprt);
765                 return;
766         }
767         dprintk("RPC:       reading TCP record fragment of length %d\n",
768                         transport->tcp_reclen);
769 }
770
771 static void xs_tcp_check_fraghdr(struct sock_xprt *transport)
772 {
773         if (transport->tcp_offset == transport->tcp_reclen) {
774                 transport->tcp_flags |= TCP_RCV_COPY_FRAGHDR;
775                 transport->tcp_offset = 0;
776                 if (transport->tcp_flags & TCP_RCV_LAST_FRAG) {
777                         transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
778                         transport->tcp_flags |= TCP_RCV_COPY_XID;
779                         transport->tcp_copied = 0;
780                 }
781         }
782 }
783
784 static inline void xs_tcp_read_xid(struct sock_xprt *transport, struct xdr_skb_reader *desc)
785 {
786         size_t len, used;
787         char *p;
788
789         len = sizeof(transport->tcp_xid) - transport->tcp_offset;
790         dprintk("RPC:       reading XID (%Zu bytes)\n", len);
791         p = ((char *) &transport->tcp_xid) + transport->tcp_offset;
792         used = xdr_skb_read_bits(desc, p, len);
793         transport->tcp_offset += used;
794         if (used != len)
795                 return;
796         transport->tcp_flags &= ~TCP_RCV_COPY_XID;
797         transport->tcp_flags |= TCP_RCV_COPY_DATA;
798         transport->tcp_copied = 4;
799         dprintk("RPC:       reading reply for XID %08x\n",
800                         ntohl(transport->tcp_xid));
801         xs_tcp_check_fraghdr(transport);
802 }
803
804 static inline void xs_tcp_read_request(struct rpc_xprt *xprt, struct xdr_skb_reader *desc)
805 {
806         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
807         struct rpc_rqst *req;
808         struct xdr_buf *rcvbuf;
809         size_t len;
810         ssize_t r;
811
812         /* Find and lock the request corresponding to this xid */
813         spin_lock(&xprt->transport_lock);
814         req = xprt_lookup_rqst(xprt, transport->tcp_xid);
815         if (!req) {
816                 transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
817                 dprintk("RPC:       XID %08x request not found!\n",
818                                 ntohl(transport->tcp_xid));
819                 spin_unlock(&xprt->transport_lock);
820                 return;
821         }
822
823         rcvbuf = &req->rq_private_buf;
824         len = desc->count;
825         if (len > transport->tcp_reclen - transport->tcp_offset) {
826                 struct xdr_skb_reader my_desc;
827
828                 len = transport->tcp_reclen - transport->tcp_offset;
829                 memcpy(&my_desc, desc, sizeof(my_desc));
830                 my_desc.count = len;
831                 r = xdr_partial_copy_from_skb(rcvbuf, transport->tcp_copied,
832                                           &my_desc, xdr_skb_read_bits);
833                 desc->count -= r;
834                 desc->offset += r;
835         } else
836                 r = xdr_partial_copy_from_skb(rcvbuf, transport->tcp_copied,
837                                           desc, xdr_skb_read_bits);
838
839         if (r > 0) {
840                 transport->tcp_copied += r;
841                 transport->tcp_offset += r;
842         }
843         if (r != len) {
844                 /* Error when copying to the receive buffer,
845                  * usually because we weren't able to allocate
846                  * additional buffer pages. All we can do now
847                  * is turn off TCP_RCV_COPY_DATA, so the request
848                  * will not receive any additional updates,
849                  * and time out.
850                  * Any remaining data from this record will
851                  * be discarded.
852                  */
853                 transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
854                 dprintk("RPC:       XID %08x truncated request\n",
855                                 ntohl(transport->tcp_xid));
856                 dprintk("RPC:       xprt = %p, tcp_copied = %lu, "
857                                 "tcp_offset = %u, tcp_reclen = %u\n",
858                                 xprt, transport->tcp_copied,
859                                 transport->tcp_offset, transport->tcp_reclen);
860                 goto out;
861         }
862
863         dprintk("RPC:       XID %08x read %Zd bytes\n",
864                         ntohl(transport->tcp_xid), r);
865         dprintk("RPC:       xprt = %p, tcp_copied = %lu, tcp_offset = %u, "
866                         "tcp_reclen = %u\n", xprt, transport->tcp_copied,
867                         transport->tcp_offset, transport->tcp_reclen);
868
869         if (transport->tcp_copied == req->rq_private_buf.buflen)
870                 transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
871         else if (transport->tcp_offset == transport->tcp_reclen) {
872                 if (transport->tcp_flags & TCP_RCV_LAST_FRAG)
873                         transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
874         }
875
876 out:
877         if (!(transport->tcp_flags & TCP_RCV_COPY_DATA))
878                 xprt_complete_rqst(req->rq_task, transport->tcp_copied);
879         spin_unlock(&xprt->transport_lock);
880         xs_tcp_check_fraghdr(transport);
881 }
882
883 static inline void xs_tcp_read_discard(struct sock_xprt *transport, struct xdr_skb_reader *desc)
884 {
885         size_t len;
886
887         len = transport->tcp_reclen - transport->tcp_offset;
888         if (len > desc->count)
889                 len = desc->count;
890         desc->count -= len;
891         desc->offset += len;
892         transport->tcp_offset += len;
893         dprintk("RPC:       discarded %Zu bytes\n", len);
894         xs_tcp_check_fraghdr(transport);
895 }
896
897 static int xs_tcp_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb, unsigned int offset, size_t len)
898 {
899         struct rpc_xprt *xprt = rd_desc->arg.data;
900         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
901         struct xdr_skb_reader desc = {
902                 .skb    = skb,
903                 .offset = offset,
904                 .count  = len,
905         };
906
907         dprintk("RPC:       xs_tcp_data_recv started\n");
908         do {
909                 /* Read in a new fragment marker if necessary */
910                 /* Can we ever really expect to get completely empty fragments? */
911                 if (transport->tcp_flags & TCP_RCV_COPY_FRAGHDR) {
912                         xs_tcp_read_fraghdr(xprt, &desc);
913                         continue;
914                 }
915                 /* Read in the xid if necessary */
916                 if (transport->tcp_flags & TCP_RCV_COPY_XID) {
917                         xs_tcp_read_xid(transport, &desc);
918                         continue;
919                 }
920                 /* Read in the request data */
921                 if (transport->tcp_flags & TCP_RCV_COPY_DATA) {
922                         xs_tcp_read_request(xprt, &desc);
923                         continue;
924                 }
925                 /* Skip over any trailing bytes on short reads */
926                 xs_tcp_read_discard(transport, &desc);
927         } while (desc.count);
928         dprintk("RPC:       xs_tcp_data_recv done\n");
929         return len - desc.count;
930 }
931
932 /**
933  * xs_tcp_data_ready - "data ready" callback for TCP sockets
934  * @sk: socket with data to read
935  * @bytes: how much data to read
936  *
937  */
938 static void xs_tcp_data_ready(struct sock *sk, int bytes)
939 {
940         struct rpc_xprt *xprt;
941         read_descriptor_t rd_desc;
942
943         dprintk("RPC:       xs_tcp_data_ready...\n");
944
945         read_lock(&sk->sk_callback_lock);
946         if (!(xprt = xprt_from_sock(sk)))
947                 goto out;
948         if (xprt->shutdown)
949                 goto out;
950
951         /* We use rd_desc to pass struct xprt to xs_tcp_data_recv */
952         rd_desc.arg.data = xprt;
953         rd_desc.count = 65536;
954         tcp_read_sock(sk, &rd_desc, xs_tcp_data_recv);
955 out:
956         read_unlock(&sk->sk_callback_lock);
957 }
958
959 /**
960  * xs_tcp_state_change - callback to handle TCP socket state changes
961  * @sk: socket whose state has changed
962  *
963  */
964 static void xs_tcp_state_change(struct sock *sk)
965 {
966         struct rpc_xprt *xprt;
967
968         read_lock(&sk->sk_callback_lock);
969         if (!(xprt = xprt_from_sock(sk)))
970                 goto out;
971         dprintk("RPC:       xs_tcp_state_change client %p...\n", xprt);
972         dprintk("RPC:       state %x conn %d dead %d zapped %d\n",
973                         sk->sk_state, xprt_connected(xprt),
974                         sock_flag(sk, SOCK_DEAD),
975                         sock_flag(sk, SOCK_ZAPPED));
976
977         switch (sk->sk_state) {
978         case TCP_ESTABLISHED:
979                 spin_lock_bh(&xprt->transport_lock);
980                 if (!xprt_test_and_set_connected(xprt)) {
981                         struct sock_xprt *transport = container_of(xprt,
982                                         struct sock_xprt, xprt);
983
984                         /* Reset TCP record info */
985                         transport->tcp_offset = 0;
986                         transport->tcp_reclen = 0;
987                         transport->tcp_copied = 0;
988                         transport->tcp_flags =
989                                 TCP_RCV_COPY_FRAGHDR | TCP_RCV_COPY_XID;
990
991                         xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
992                         xprt_wake_pending_tasks(xprt, 0);
993                 }
994                 spin_unlock_bh(&xprt->transport_lock);
995                 break;
996         case TCP_SYN_SENT:
997         case TCP_SYN_RECV:
998                 break;
999         case TCP_CLOSE_WAIT:
1000                 /* Try to schedule an autoclose RPC calls */
1001                 set_bit(XPRT_CLOSE_WAIT, &xprt->state);
1002                 if (test_and_set_bit(XPRT_LOCKED, &xprt->state) == 0)
1003                         queue_work(rpciod_workqueue, &xprt->task_cleanup);
1004         default:
1005                 xprt_disconnect(xprt);
1006         }
1007  out:
1008         read_unlock(&sk->sk_callback_lock);
1009 }
1010
1011 /**
1012  * xs_udp_write_space - callback invoked when socket buffer space
1013  *                             becomes available
1014  * @sk: socket whose state has changed
1015  *
1016  * Called when more output buffer space is available for this socket.
1017  * We try not to wake our writers until they can make "significant"
1018  * progress, otherwise we'll waste resources thrashing kernel_sendmsg
1019  * with a bunch of small requests.
1020  */
1021 static void xs_udp_write_space(struct sock *sk)
1022 {
1023         read_lock(&sk->sk_callback_lock);
1024
1025         /* from net/core/sock.c:sock_def_write_space */
1026         if (sock_writeable(sk)) {
1027                 struct socket *sock;
1028                 struct rpc_xprt *xprt;
1029
1030                 if (unlikely(!(sock = sk->sk_socket)))
1031                         goto out;
1032                 if (unlikely(!(xprt = xprt_from_sock(sk))))
1033                         goto out;
1034                 if (unlikely(!test_and_clear_bit(SOCK_NOSPACE, &sock->flags)))
1035                         goto out;
1036
1037                 xprt_write_space(xprt);
1038         }
1039
1040  out:
1041         read_unlock(&sk->sk_callback_lock);
1042 }
1043
1044 /**
1045  * xs_tcp_write_space - callback invoked when socket buffer space
1046  *                             becomes available
1047  * @sk: socket whose state has changed
1048  *
1049  * Called when more output buffer space is available for this socket.
1050  * We try not to wake our writers until they can make "significant"
1051  * progress, otherwise we'll waste resources thrashing kernel_sendmsg
1052  * with a bunch of small requests.
1053  */
1054 static void xs_tcp_write_space(struct sock *sk)
1055 {
1056         read_lock(&sk->sk_callback_lock);
1057
1058         /* from net/core/stream.c:sk_stream_write_space */
1059         if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk)) {
1060                 struct socket *sock;
1061                 struct rpc_xprt *xprt;
1062
1063                 if (unlikely(!(sock = sk->sk_socket)))
1064                         goto out;
1065                 if (unlikely(!(xprt = xprt_from_sock(sk))))
1066                         goto out;
1067                 if (unlikely(!test_and_clear_bit(SOCK_NOSPACE, &sock->flags)))
1068                         goto out;
1069
1070                 xprt_write_space(xprt);
1071         }
1072
1073  out:
1074         read_unlock(&sk->sk_callback_lock);
1075 }
1076
1077 static void xs_udp_do_set_buffer_size(struct rpc_xprt *xprt)
1078 {
1079         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1080         struct sock *sk = transport->inet;
1081
1082         if (transport->rcvsize) {
1083                 sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
1084                 sk->sk_rcvbuf = transport->rcvsize * xprt->max_reqs * 2;
1085         }
1086         if (transport->sndsize) {
1087                 sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
1088                 sk->sk_sndbuf = transport->sndsize * xprt->max_reqs * 2;
1089                 sk->sk_write_space(sk);
1090         }
1091 }
1092
1093 /**
1094  * xs_udp_set_buffer_size - set send and receive limits
1095  * @xprt: generic transport
1096  * @sndsize: requested size of send buffer, in bytes
1097  * @rcvsize: requested size of receive buffer, in bytes
1098  *
1099  * Set socket send and receive buffer size limits.
1100  */
1101 static void xs_udp_set_buffer_size(struct rpc_xprt *xprt, size_t sndsize, size_t rcvsize)
1102 {
1103         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1104
1105         transport->sndsize = 0;
1106         if (sndsize)
1107                 transport->sndsize = sndsize + 1024;
1108         transport->rcvsize = 0;
1109         if (rcvsize)
1110                 transport->rcvsize = rcvsize + 1024;
1111
1112         xs_udp_do_set_buffer_size(xprt);
1113 }
1114
1115 /**
1116  * xs_udp_timer - called when a retransmit timeout occurs on a UDP transport
1117  * @task: task that timed out
1118  *
1119  * Adjust the congestion window after a retransmit timeout has occurred.
1120  */
1121 static void xs_udp_timer(struct rpc_task *task)
1122 {
1123         xprt_adjust_cwnd(task, -ETIMEDOUT);
1124 }
1125
1126 static unsigned short xs_get_random_port(void)
1127 {
1128         unsigned short range = xprt_max_resvport - xprt_min_resvport;
1129         unsigned short rand = (unsigned short) net_random() % range;
1130         return rand + xprt_min_resvport;
1131 }
1132
1133 /**
1134  * xs_set_port - reset the port number in the remote endpoint address
1135  * @xprt: generic transport
1136  * @port: new port number
1137  *
1138  */
1139 static void xs_set_port(struct rpc_xprt *xprt, unsigned short port)
1140 {
1141         struct sockaddr_in *sap = (struct sockaddr_in *) &xprt->addr;
1142
1143         dprintk("RPC:       setting port for xprt %p to %u\n", xprt, port);
1144
1145         sap->sin_port = htons(port);
1146 }
1147
1148 static int xs_bindresvport(struct sock_xprt *transport, struct socket *sock)
1149 {
1150         struct sockaddr_in myaddr = {
1151                 .sin_family = AF_INET,
1152         };
1153         int err;
1154         unsigned short port = transport->port;
1155
1156         do {
1157                 myaddr.sin_port = htons(port);
1158                 err = kernel_bind(sock, (struct sockaddr *) &myaddr,
1159                                                 sizeof(myaddr));
1160                 if (err == 0) {
1161                         transport->port = port;
1162                         dprintk("RPC:       xs_bindresvport bound to port %u\n",
1163                                         port);
1164                         return 0;
1165                 }
1166                 if (port <= xprt_min_resvport)
1167                         port = xprt_max_resvport;
1168                 else
1169                         port--;
1170         } while (err == -EADDRINUSE && port != transport->port);
1171
1172         dprintk("RPC:       can't bind to reserved port (%d).\n", -err);
1173         return err;
1174 }
1175
1176 #ifdef CONFIG_DEBUG_LOCK_ALLOC
1177 static struct lock_class_key xs_key[2];
1178 static struct lock_class_key xs_slock_key[2];
1179
1180 static inline void xs_reclassify_socket(struct socket *sock)
1181 {
1182         struct sock *sk = sock->sk;
1183         BUG_ON(sk->sk_lock.owner != NULL);
1184         switch (sk->sk_family) {
1185         case AF_INET:
1186                 sock_lock_init_class_and_name(sk, "slock-AF_INET-NFS",
1187                         &xs_slock_key[0], "sk_lock-AF_INET-NFS", &xs_key[0]);
1188                 break;
1189
1190         case AF_INET6:
1191                 sock_lock_init_class_and_name(sk, "slock-AF_INET6-NFS",
1192                         &xs_slock_key[1], "sk_lock-AF_INET6-NFS", &xs_key[1]);
1193                 break;
1194
1195         default:
1196                 BUG();
1197         }
1198 }
1199 #else
1200 static inline void xs_reclassify_socket(struct socket *sock)
1201 {
1202 }
1203 #endif
1204
1205 /**
1206  * xs_udp_connect_worker - set up a UDP socket
1207  * @work: RPC transport to connect
1208  *
1209  * Invoked by a work queue tasklet.
1210  */
1211 static void xs_udp_connect_worker(struct work_struct *work)
1212 {
1213         struct sock_xprt *transport =
1214                 container_of(work, struct sock_xprt, connect_worker.work);
1215         struct rpc_xprt *xprt = &transport->xprt;
1216         struct socket *sock = transport->sock;
1217         int err, status = -EIO;
1218
1219         if (xprt->shutdown || !xprt_bound(xprt))
1220                 goto out;
1221
1222         /* Start by resetting any existing state */
1223         xs_close(xprt);
1224
1225         if ((err = sock_create_kern(PF_INET, SOCK_DGRAM, IPPROTO_UDP, &sock)) < 0) {
1226                 dprintk("RPC:       can't create UDP transport socket (%d).\n", -err);
1227                 goto out;
1228         }
1229         xs_reclassify_socket(sock);
1230
1231         if (xprt->resvport && xs_bindresvport(transport, sock) < 0) {
1232                 sock_release(sock);
1233                 goto out;
1234         }
1235
1236         dprintk("RPC:       worker connecting xprt %p to address: %s\n",
1237                         xprt, xprt->address_strings[RPC_DISPLAY_ALL]);
1238
1239         if (!transport->inet) {
1240                 struct sock *sk = sock->sk;
1241
1242                 write_lock_bh(&sk->sk_callback_lock);
1243
1244                 sk->sk_user_data = xprt;
1245                 transport->old_data_ready = sk->sk_data_ready;
1246                 transport->old_state_change = sk->sk_state_change;
1247                 transport->old_write_space = sk->sk_write_space;
1248                 sk->sk_data_ready = xs_udp_data_ready;
1249                 sk->sk_write_space = xs_udp_write_space;
1250                 sk->sk_no_check = UDP_CSUM_NORCV;
1251                 sk->sk_allocation = GFP_ATOMIC;
1252
1253                 xprt_set_connected(xprt);
1254
1255                 /* Reset to new socket */
1256                 transport->sock = sock;
1257                 transport->inet = sk;
1258
1259                 write_unlock_bh(&sk->sk_callback_lock);
1260         }
1261         xs_udp_do_set_buffer_size(xprt);
1262         status = 0;
1263 out:
1264         xprt_wake_pending_tasks(xprt, status);
1265         xprt_clear_connecting(xprt);
1266 }
1267
1268 /*
1269  * We need to preserve the port number so the reply cache on the server can
1270  * find our cached RPC replies when we get around to reconnecting.
1271  */
1272 static void xs_tcp_reuse_connection(struct rpc_xprt *xprt)
1273 {
1274         int result;
1275         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1276         struct sockaddr any;
1277
1278         dprintk("RPC:       disconnecting xprt %p to reuse port\n", xprt);
1279
1280         /*
1281          * Disconnect the transport socket by doing a connect operation
1282          * with AF_UNSPEC.  This should return immediately...
1283          */
1284         memset(&any, 0, sizeof(any));
1285         any.sa_family = AF_UNSPEC;
1286         result = kernel_connect(transport->sock, &any, sizeof(any), 0);
1287         if (result)
1288                 dprintk("RPC:       AF_UNSPEC connect return code %d\n",
1289                                 result);
1290 }
1291
1292 /**
1293  * xs_tcp_connect_worker - connect a TCP socket to a remote endpoint
1294  * @work: RPC transport to connect
1295  *
1296  * Invoked by a work queue tasklet.
1297  */
1298 static void xs_tcp_connect_worker(struct work_struct *work)
1299 {
1300         struct sock_xprt *transport =
1301                 container_of(work, struct sock_xprt, connect_worker.work);
1302         struct rpc_xprt *xprt = &transport->xprt;
1303         struct socket *sock = transport->sock;
1304         int err, status = -EIO;
1305
1306         if (xprt->shutdown || !xprt_bound(xprt))
1307                 goto out;
1308
1309         if (!sock) {
1310                 /* start from scratch */
1311                 if ((err = sock_create_kern(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock)) < 0) {
1312                         dprintk("RPC:       can't create TCP transport "
1313                                         "socket (%d).\n", -err);
1314                         goto out;
1315                 }
1316                 xs_reclassify_socket(sock);
1317
1318                 if (xprt->resvport && xs_bindresvport(transport, sock) < 0) {
1319                         sock_release(sock);
1320                         goto out;
1321                 }
1322         } else
1323                 /* "close" the socket, preserving the local port */
1324                 xs_tcp_reuse_connection(xprt);
1325
1326         dprintk("RPC:       worker connecting xprt %p to address: %s\n",
1327                         xprt, xprt->address_strings[RPC_DISPLAY_ALL]);
1328
1329         if (!transport->inet) {
1330                 struct sock *sk = sock->sk;
1331
1332                 write_lock_bh(&sk->sk_callback_lock);
1333
1334                 sk->sk_user_data = xprt;
1335                 transport->old_data_ready = sk->sk_data_ready;
1336                 transport->old_state_change = sk->sk_state_change;
1337                 transport->old_write_space = sk->sk_write_space;
1338                 sk->sk_data_ready = xs_tcp_data_ready;
1339                 sk->sk_state_change = xs_tcp_state_change;
1340                 sk->sk_write_space = xs_tcp_write_space;
1341                 sk->sk_allocation = GFP_ATOMIC;
1342
1343                 /* socket options */
1344                 sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
1345                 sock_reset_flag(sk, SOCK_LINGER);
1346                 tcp_sk(sk)->linger2 = 0;
1347                 tcp_sk(sk)->nonagle |= TCP_NAGLE_OFF;
1348
1349                 xprt_clear_connected(xprt);
1350
1351                 /* Reset to new socket */
1352                 transport->sock = sock;
1353                 transport->inet = sk;
1354
1355                 write_unlock_bh(&sk->sk_callback_lock);
1356         }
1357
1358         /* Tell the socket layer to start connecting... */
1359         xprt->stat.connect_count++;
1360         xprt->stat.connect_start = jiffies;
1361         status = kernel_connect(sock, (struct sockaddr *) &xprt->addr,
1362                         xprt->addrlen, O_NONBLOCK);
1363         dprintk("RPC:       %p connect status %d connected %d sock state %d\n",
1364                         xprt, -status, xprt_connected(xprt),
1365                         sock->sk->sk_state);
1366         if (status < 0) {
1367                 switch (status) {
1368                         case -EINPROGRESS:
1369                         case -EALREADY:
1370                                 goto out_clear;
1371                         case -ECONNREFUSED:
1372                         case -ECONNRESET:
1373                                 /* retry with existing socket, after a delay */
1374                                 break;
1375                         default:
1376                                 /* get rid of existing socket, and retry */
1377                                 xs_close(xprt);
1378                                 break;
1379                 }
1380         }
1381 out:
1382         xprt_wake_pending_tasks(xprt, status);
1383 out_clear:
1384         xprt_clear_connecting(xprt);
1385 }
1386
1387 /**
1388  * xs_connect - connect a socket to a remote endpoint
1389  * @task: address of RPC task that manages state of connect request
1390  *
1391  * TCP: If the remote end dropped the connection, delay reconnecting.
1392  *
1393  * UDP socket connects are synchronous, but we use a work queue anyway
1394  * to guarantee that even unprivileged user processes can set up a
1395  * socket on a privileged port.
1396  *
1397  * If a UDP socket connect fails, the delay behavior here prevents
1398  * retry floods (hard mounts).
1399  */
1400 static void xs_connect(struct rpc_task *task)
1401 {
1402         struct rpc_xprt *xprt = task->tk_xprt;
1403         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1404
1405         if (xprt_test_and_set_connecting(xprt))
1406                 return;
1407
1408         if (transport->sock != NULL) {
1409                 dprintk("RPC:       xs_connect delayed xprt %p for %lu "
1410                                 "seconds\n",
1411                                 xprt, xprt->reestablish_timeout / HZ);
1412                 queue_delayed_work(rpciod_workqueue,
1413                                    &transport->connect_worker,
1414                                    xprt->reestablish_timeout);
1415                 xprt->reestablish_timeout <<= 1;
1416                 if (xprt->reestablish_timeout > XS_TCP_MAX_REEST_TO)
1417                         xprt->reestablish_timeout = XS_TCP_MAX_REEST_TO;
1418         } else {
1419                 dprintk("RPC:       xs_connect scheduled xprt %p\n", xprt);
1420                 queue_delayed_work(rpciod_workqueue,
1421                                    &transport->connect_worker, 0);
1422         }
1423 }
1424
1425 /**
1426  * xs_udp_print_stats - display UDP socket-specifc stats
1427  * @xprt: rpc_xprt struct containing statistics
1428  * @seq: output file
1429  *
1430  */
1431 static void xs_udp_print_stats(struct rpc_xprt *xprt, struct seq_file *seq)
1432 {
1433         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1434
1435         seq_printf(seq, "\txprt:\tudp %u %lu %lu %lu %lu %Lu %Lu\n",
1436                         transport->port,
1437                         xprt->stat.bind_count,
1438                         xprt->stat.sends,
1439                         xprt->stat.recvs,
1440                         xprt->stat.bad_xids,
1441                         xprt->stat.req_u,
1442                         xprt->stat.bklog_u);
1443 }
1444
1445 /**
1446  * xs_tcp_print_stats - display TCP socket-specifc stats
1447  * @xprt: rpc_xprt struct containing statistics
1448  * @seq: output file
1449  *
1450  */
1451 static void xs_tcp_print_stats(struct rpc_xprt *xprt, struct seq_file *seq)
1452 {
1453         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1454         long idle_time = 0;
1455
1456         if (xprt_connected(xprt))
1457                 idle_time = (long)(jiffies - xprt->last_used) / HZ;
1458
1459         seq_printf(seq, "\txprt:\ttcp %u %lu %lu %lu %ld %lu %lu %lu %Lu %Lu\n",
1460                         transport->port,
1461                         xprt->stat.bind_count,
1462                         xprt->stat.connect_count,
1463                         xprt->stat.connect_time,
1464                         idle_time,
1465                         xprt->stat.sends,
1466                         xprt->stat.recvs,
1467                         xprt->stat.bad_xids,
1468                         xprt->stat.req_u,
1469                         xprt->stat.bklog_u);
1470 }
1471
1472 static struct rpc_xprt_ops xs_udp_ops = {
1473         .set_buffer_size        = xs_udp_set_buffer_size,
1474         .reserve_xprt           = xprt_reserve_xprt_cong,
1475         .release_xprt           = xprt_release_xprt_cong,
1476         .rpcbind                = rpcb_getport,
1477         .set_port               = xs_set_port,
1478         .connect                = xs_connect,
1479         .buf_alloc              = rpc_malloc,
1480         .buf_free               = rpc_free,
1481         .send_request           = xs_udp_send_request,
1482         .set_retrans_timeout    = xprt_set_retrans_timeout_rtt,
1483         .timer                  = xs_udp_timer,
1484         .release_request        = xprt_release_rqst_cong,
1485         .close                  = xs_close,
1486         .destroy                = xs_destroy,
1487         .print_stats            = xs_udp_print_stats,
1488 };
1489
1490 static struct rpc_xprt_ops xs_tcp_ops = {
1491         .reserve_xprt           = xprt_reserve_xprt,
1492         .release_xprt           = xs_tcp_release_xprt,
1493         .rpcbind                = rpcb_getport,
1494         .set_port               = xs_set_port,
1495         .connect                = xs_connect,
1496         .buf_alloc              = rpc_malloc,
1497         .buf_free               = rpc_free,
1498         .send_request           = xs_tcp_send_request,
1499         .set_retrans_timeout    = xprt_set_retrans_timeout_def,
1500         .close                  = xs_close,
1501         .destroy                = xs_destroy,
1502         .print_stats            = xs_tcp_print_stats,
1503 };
1504
1505 static struct rpc_xprt *xs_setup_xprt(struct sockaddr *addr, size_t addrlen, unsigned int slot_table_size)
1506 {
1507         struct rpc_xprt *xprt;
1508         struct sock_xprt *new;
1509
1510         if (addrlen > sizeof(xprt->addr)) {
1511                 dprintk("RPC:       xs_setup_xprt: address too large\n");
1512                 return ERR_PTR(-EBADF);
1513         }
1514
1515         new = kzalloc(sizeof(*new), GFP_KERNEL);
1516         if (new == NULL) {
1517                 dprintk("RPC:       xs_setup_xprt: couldn't allocate "
1518                                 "rpc_xprt\n");
1519                 return ERR_PTR(-ENOMEM);
1520         }
1521         xprt = &new->xprt;
1522
1523         xprt->max_reqs = slot_table_size;
1524         xprt->slot = kcalloc(xprt->max_reqs, sizeof(struct rpc_rqst), GFP_KERNEL);
1525         if (xprt->slot == NULL) {
1526                 kfree(xprt);
1527                 dprintk("RPC:       xs_setup_xprt: couldn't allocate slot "
1528                                 "table\n");
1529                 return ERR_PTR(-ENOMEM);
1530         }
1531
1532         memcpy(&xprt->addr, addr, addrlen);
1533         xprt->addrlen = addrlen;
1534         new->port = xs_get_random_port();
1535
1536         return xprt;
1537 }
1538
1539 /**
1540  * xs_setup_udp - Set up transport to use a UDP socket
1541  * @addr: address of remote server
1542  * @addrlen: length of address in bytes
1543  * @to:   timeout parameters
1544  *
1545  */
1546 struct rpc_xprt *xs_setup_udp(struct sockaddr *addr, size_t addrlen, struct rpc_timeout *to)
1547 {
1548         struct rpc_xprt *xprt;
1549         struct sock_xprt *transport;
1550
1551         xprt = xs_setup_xprt(addr, addrlen, xprt_udp_slot_table_entries);
1552         if (IS_ERR(xprt))
1553                 return xprt;
1554         transport = container_of(xprt, struct sock_xprt, xprt);
1555
1556         if (ntohs(((struct sockaddr_in *)addr)->sin_port) != 0)
1557                 xprt_set_bound(xprt);
1558
1559         xprt->prot = IPPROTO_UDP;
1560         xprt->tsh_size = 0;
1561         /* XXX: header size can vary due to auth type, IPv6, etc. */
1562         xprt->max_payload = (1U << 16) - (MAX_HEADER << 3);
1563
1564         INIT_DELAYED_WORK(&transport->connect_worker, xs_udp_connect_worker);
1565         xprt->bind_timeout = XS_BIND_TO;
1566         xprt->connect_timeout = XS_UDP_CONN_TO;
1567         xprt->reestablish_timeout = XS_UDP_REEST_TO;
1568         xprt->idle_timeout = XS_IDLE_DISC_TO;
1569
1570         xprt->ops = &xs_udp_ops;
1571
1572         if (to)
1573                 xprt->timeout = *to;
1574         else
1575                 xprt_set_timeout(&xprt->timeout, 5, 5 * HZ);
1576
1577         xs_format_peer_addresses(xprt);
1578         dprintk("RPC:       set up transport to address %s\n",
1579                         xprt->address_strings[RPC_DISPLAY_ALL]);
1580
1581         return xprt;
1582 }
1583
1584 /**
1585  * xs_setup_tcp - Set up transport to use a TCP socket
1586  * @addr: address of remote server
1587  * @addrlen: length of address in bytes
1588  * @to: timeout parameters
1589  *
1590  */
1591 struct rpc_xprt *xs_setup_tcp(struct sockaddr *addr, size_t addrlen, struct rpc_timeout *to)
1592 {
1593         struct rpc_xprt *xprt;
1594         struct sock_xprt *transport;
1595
1596         xprt = xs_setup_xprt(addr, addrlen, xprt_tcp_slot_table_entries);
1597         if (IS_ERR(xprt))
1598                 return xprt;
1599         transport = container_of(xprt, struct sock_xprt, xprt);
1600
1601         if (ntohs(((struct sockaddr_in *)addr)->sin_port) != 0)
1602                 xprt_set_bound(xprt);
1603
1604         xprt->prot = IPPROTO_TCP;
1605         xprt->tsh_size = sizeof(rpc_fraghdr) / sizeof(u32);
1606         xprt->max_payload = RPC_MAX_FRAGMENT_SIZE;
1607
1608         INIT_DELAYED_WORK(&transport->connect_worker, xs_tcp_connect_worker);
1609         xprt->bind_timeout = XS_BIND_TO;
1610         xprt->connect_timeout = XS_TCP_CONN_TO;
1611         xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
1612         xprt->idle_timeout = XS_IDLE_DISC_TO;
1613
1614         xprt->ops = &xs_tcp_ops;
1615
1616         if (to)
1617                 xprt->timeout = *to;
1618         else
1619                 xprt_set_timeout(&xprt->timeout, 2, 60 * HZ);
1620
1621         xs_format_peer_addresses(xprt);
1622         dprintk("RPC:       set up transport to address %s\n",
1623                         xprt->address_strings[RPC_DISPLAY_ALL]);
1624
1625         return xprt;
1626 }
1627
1628 /**
1629  * init_socket_xprt - set up xprtsock's sysctls
1630  *
1631  */
1632 int init_socket_xprt(void)
1633 {
1634 #ifdef RPC_DEBUG
1635         if (!sunrpc_table_header)
1636                 sunrpc_table_header = register_sysctl_table(sunrpc_table);
1637 #endif
1638
1639         return 0;
1640 }
1641
1642 /**
1643  * cleanup_socket_xprt - remove xprtsock's sysctls
1644  *
1645  */
1646 void cleanup_socket_xprt(void)
1647 {
1648 #ifdef RPC_DEBUG
1649         if (sunrpc_table_header) {
1650                 unregister_sysctl_table(sunrpc_table_header);
1651                 sunrpc_table_header = NULL;
1652         }
1653 #endif
1654 }