nfs41: Add ability to read RPC call direction on TCP stream.
[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
7  * TCP send fixes (C) 1998 Red Hat
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  * IPv6 support contributed by Gilles Quillard, Bull Open Source, 2005.
18  *   <gilles.quillard@bull.net>
19  */
20
21 #include <linux/types.h>
22 #include <linux/slab.h>
23 #include <linux/module.h>
24 #include <linux/capability.h>
25 #include <linux/pagemap.h>
26 #include <linux/errno.h>
27 #include <linux/socket.h>
28 #include <linux/in.h>
29 #include <linux/net.h>
30 #include <linux/mm.h>
31 #include <linux/udp.h>
32 #include <linux/tcp.h>
33 #include <linux/sunrpc/clnt.h>
34 #include <linux/sunrpc/sched.h>
35 #include <linux/sunrpc/xprtsock.h>
36 #include <linux/file.h>
37
38 #include <net/sock.h>
39 #include <net/checksum.h>
40 #include <net/udp.h>
41 #include <net/tcp.h>
42
43 /*
44  * xprtsock tunables
45  */
46 unsigned int xprt_udp_slot_table_entries = RPC_DEF_SLOT_TABLE;
47 unsigned int xprt_tcp_slot_table_entries = RPC_DEF_SLOT_TABLE;
48
49 unsigned int xprt_min_resvport = RPC_DEF_MIN_RESVPORT;
50 unsigned int xprt_max_resvport = RPC_DEF_MAX_RESVPORT;
51
52 #define XS_TCP_LINGER_TO        (15U * HZ)
53 static unsigned int xs_tcp_fin_timeout __read_mostly = XS_TCP_LINGER_TO;
54
55 /*
56  * We can register our own files under /proc/sys/sunrpc by
57  * calling register_sysctl_table() again.  The files in that
58  * directory become the union of all files registered there.
59  *
60  * We simply need to make sure that we don't collide with
61  * someone else's file names!
62  */
63
64 #ifdef RPC_DEBUG
65
66 static unsigned int min_slot_table_size = RPC_MIN_SLOT_TABLE;
67 static unsigned int max_slot_table_size = RPC_MAX_SLOT_TABLE;
68 static unsigned int xprt_min_resvport_limit = RPC_MIN_RESVPORT;
69 static unsigned int xprt_max_resvport_limit = RPC_MAX_RESVPORT;
70
71 static struct ctl_table_header *sunrpc_table_header;
72
73 /*
74  * FIXME: changing the UDP slot table size should also resize the UDP
75  *        socket buffers for existing UDP transports
76  */
77 static ctl_table xs_tunables_table[] = {
78         {
79                 .ctl_name       = CTL_SLOTTABLE_UDP,
80                 .procname       = "udp_slot_table_entries",
81                 .data           = &xprt_udp_slot_table_entries,
82                 .maxlen         = sizeof(unsigned int),
83                 .mode           = 0644,
84                 .proc_handler   = &proc_dointvec_minmax,
85                 .strategy       = &sysctl_intvec,
86                 .extra1         = &min_slot_table_size,
87                 .extra2         = &max_slot_table_size
88         },
89         {
90                 .ctl_name       = CTL_SLOTTABLE_TCP,
91                 .procname       = "tcp_slot_table_entries",
92                 .data           = &xprt_tcp_slot_table_entries,
93                 .maxlen         = sizeof(unsigned int),
94                 .mode           = 0644,
95                 .proc_handler   = &proc_dointvec_minmax,
96                 .strategy       = &sysctl_intvec,
97                 .extra1         = &min_slot_table_size,
98                 .extra2         = &max_slot_table_size
99         },
100         {
101                 .ctl_name       = CTL_MIN_RESVPORT,
102                 .procname       = "min_resvport",
103                 .data           = &xprt_min_resvport,
104                 .maxlen         = sizeof(unsigned int),
105                 .mode           = 0644,
106                 .proc_handler   = &proc_dointvec_minmax,
107                 .strategy       = &sysctl_intvec,
108                 .extra1         = &xprt_min_resvport_limit,
109                 .extra2         = &xprt_max_resvport_limit
110         },
111         {
112                 .ctl_name       = CTL_MAX_RESVPORT,
113                 .procname       = "max_resvport",
114                 .data           = &xprt_max_resvport,
115                 .maxlen         = sizeof(unsigned int),
116                 .mode           = 0644,
117                 .proc_handler   = &proc_dointvec_minmax,
118                 .strategy       = &sysctl_intvec,
119                 .extra1         = &xprt_min_resvport_limit,
120                 .extra2         = &xprt_max_resvport_limit
121         },
122         {
123                 .procname       = "tcp_fin_timeout",
124                 .data           = &xs_tcp_fin_timeout,
125                 .maxlen         = sizeof(xs_tcp_fin_timeout),
126                 .mode           = 0644,
127                 .proc_handler   = &proc_dointvec_jiffies,
128                 .strategy       = sysctl_jiffies
129         },
130         {
131                 .ctl_name = 0,
132         },
133 };
134
135 static ctl_table sunrpc_table[] = {
136         {
137                 .ctl_name       = CTL_SUNRPC,
138                 .procname       = "sunrpc",
139                 .mode           = 0555,
140                 .child          = xs_tunables_table
141         },
142         {
143                 .ctl_name = 0,
144         },
145 };
146
147 #endif
148
149 /*
150  * Time out for an RPC UDP socket connect.  UDP socket connects are
151  * synchronous, but we set a timeout anyway in case of resource
152  * exhaustion on the local host.
153  */
154 #define XS_UDP_CONN_TO          (5U * HZ)
155
156 /*
157  * Wait duration for an RPC TCP connection to be established.  Solaris
158  * NFS over TCP uses 60 seconds, for example, which is in line with how
159  * long a server takes to reboot.
160  */
161 #define XS_TCP_CONN_TO          (60U * HZ)
162
163 /*
164  * Wait duration for a reply from the RPC portmapper.
165  */
166 #define XS_BIND_TO              (60U * HZ)
167
168 /*
169  * Delay if a UDP socket connect error occurs.  This is most likely some
170  * kind of resource problem on the local host.
171  */
172 #define XS_UDP_REEST_TO         (2U * HZ)
173
174 /*
175  * The reestablish timeout allows clients to delay for a bit before attempting
176  * to reconnect to a server that just dropped our connection.
177  *
178  * We implement an exponential backoff when trying to reestablish a TCP
179  * transport connection with the server.  Some servers like to drop a TCP
180  * connection when they are overworked, so we start with a short timeout and
181  * increase over time if the server is down or not responding.
182  */
183 #define XS_TCP_INIT_REEST_TO    (3U * HZ)
184 #define XS_TCP_MAX_REEST_TO     (5U * 60 * HZ)
185
186 /*
187  * TCP idle timeout; client drops the transport socket if it is idle
188  * for this long.  Note that we also timeout UDP sockets to prevent
189  * holding port numbers when there is no RPC traffic.
190  */
191 #define XS_IDLE_DISC_TO         (5U * 60 * HZ)
192
193 #ifdef RPC_DEBUG
194 # undef  RPC_DEBUG_DATA
195 # define RPCDBG_FACILITY        RPCDBG_TRANS
196 #endif
197
198 #ifdef RPC_DEBUG_DATA
199 static void xs_pktdump(char *msg, u32 *packet, unsigned int count)
200 {
201         u8 *buf = (u8 *) packet;
202         int j;
203
204         dprintk("RPC:       %s\n", msg);
205         for (j = 0; j < count && j < 128; j += 4) {
206                 if (!(j & 31)) {
207                         if (j)
208                                 dprintk("\n");
209                         dprintk("0x%04x ", j);
210                 }
211                 dprintk("%02x%02x%02x%02x ",
212                         buf[j], buf[j+1], buf[j+2], buf[j+3]);
213         }
214         dprintk("\n");
215 }
216 #else
217 static inline void xs_pktdump(char *msg, u32 *packet, unsigned int count)
218 {
219         /* NOP */
220 }
221 #endif
222
223 struct sock_xprt {
224         struct rpc_xprt         xprt;
225
226         /*
227          * Network layer
228          */
229         struct socket *         sock;
230         struct sock *           inet;
231
232         /*
233          * State of TCP reply receive
234          */
235         __be32                  tcp_fraghdr,
236                                 tcp_xid;
237
238         u32                     tcp_offset,
239                                 tcp_reclen;
240
241         unsigned long           tcp_copied,
242                                 tcp_flags;
243
244         /*
245          * Connection of transports
246          */
247         struct delayed_work     connect_worker;
248         struct sockaddr_storage addr;
249         unsigned short          port;
250
251         /*
252          * UDP socket buffer size parameters
253          */
254         size_t                  rcvsize,
255                                 sndsize;
256
257         /*
258          * Saved socket callback addresses
259          */
260         void                    (*old_data_ready)(struct sock *, int);
261         void                    (*old_state_change)(struct sock *);
262         void                    (*old_write_space)(struct sock *);
263         void                    (*old_error_report)(struct sock *);
264 };
265
266 /*
267  * TCP receive state flags
268  */
269 #define TCP_RCV_LAST_FRAG       (1UL << 0)
270 #define TCP_RCV_COPY_FRAGHDR    (1UL << 1)
271 #define TCP_RCV_COPY_XID        (1UL << 2)
272 #define TCP_RCV_COPY_DATA       (1UL << 3)
273 #define TCP_RCV_COPY_CALLDIR    (1UL << 4)
274
275 /*
276  * TCP RPC flags
277  */
278 #define TCP_RPC_REPLY           (1UL << 5)
279
280 static inline struct sockaddr *xs_addr(struct rpc_xprt *xprt)
281 {
282         return (struct sockaddr *) &xprt->addr;
283 }
284
285 static inline struct sockaddr_in *xs_addr_in(struct rpc_xprt *xprt)
286 {
287         return (struct sockaddr_in *) &xprt->addr;
288 }
289
290 static inline struct sockaddr_in6 *xs_addr_in6(struct rpc_xprt *xprt)
291 {
292         return (struct sockaddr_in6 *) &xprt->addr;
293 }
294
295 static void xs_format_ipv4_peer_addresses(struct rpc_xprt *xprt,
296                                           const char *protocol,
297                                           const char *netid)
298 {
299         struct sockaddr_in *addr = xs_addr_in(xprt);
300         char *buf;
301
302         buf = kzalloc(20, GFP_KERNEL);
303         if (buf) {
304                 snprintf(buf, 20, "%pI4", &addr->sin_addr.s_addr);
305         }
306         xprt->address_strings[RPC_DISPLAY_ADDR] = buf;
307
308         buf = kzalloc(8, GFP_KERNEL);
309         if (buf) {
310                 snprintf(buf, 8, "%u",
311                                 ntohs(addr->sin_port));
312         }
313         xprt->address_strings[RPC_DISPLAY_PORT] = buf;
314
315         xprt->address_strings[RPC_DISPLAY_PROTO] = protocol;
316
317         buf = kzalloc(48, GFP_KERNEL);
318         if (buf) {
319                 snprintf(buf, 48, "addr=%pI4 port=%u proto=%s",
320                         &addr->sin_addr.s_addr,
321                         ntohs(addr->sin_port),
322                         protocol);
323         }
324         xprt->address_strings[RPC_DISPLAY_ALL] = buf;
325
326         buf = kzalloc(10, GFP_KERNEL);
327         if (buf) {
328                 snprintf(buf, 10, "%02x%02x%02x%02x",
329                                 NIPQUAD(addr->sin_addr.s_addr));
330         }
331         xprt->address_strings[RPC_DISPLAY_HEX_ADDR] = buf;
332
333         buf = kzalloc(8, GFP_KERNEL);
334         if (buf) {
335                 snprintf(buf, 8, "%4hx",
336                                 ntohs(addr->sin_port));
337         }
338         xprt->address_strings[RPC_DISPLAY_HEX_PORT] = buf;
339
340         buf = kzalloc(30, GFP_KERNEL);
341         if (buf) {
342                 snprintf(buf, 30, "%pI4.%u.%u",
343                                 &addr->sin_addr.s_addr,
344                                 ntohs(addr->sin_port) >> 8,
345                                 ntohs(addr->sin_port) & 0xff);
346         }
347         xprt->address_strings[RPC_DISPLAY_UNIVERSAL_ADDR] = buf;
348
349         xprt->address_strings[RPC_DISPLAY_NETID] = netid;
350 }
351
352 static void xs_format_ipv6_peer_addresses(struct rpc_xprt *xprt,
353                                           const char *protocol,
354                                           const char *netid)
355 {
356         struct sockaddr_in6 *addr = xs_addr_in6(xprt);
357         char *buf;
358
359         buf = kzalloc(40, GFP_KERNEL);
360         if (buf) {
361                 snprintf(buf, 40, "%pI6",&addr->sin6_addr);
362         }
363         xprt->address_strings[RPC_DISPLAY_ADDR] = buf;
364
365         buf = kzalloc(8, GFP_KERNEL);
366         if (buf) {
367                 snprintf(buf, 8, "%u",
368                                 ntohs(addr->sin6_port));
369         }
370         xprt->address_strings[RPC_DISPLAY_PORT] = buf;
371
372         xprt->address_strings[RPC_DISPLAY_PROTO] = protocol;
373
374         buf = kzalloc(64, GFP_KERNEL);
375         if (buf) {
376                 snprintf(buf, 64, "addr=%pI6 port=%u proto=%s",
377                                 &addr->sin6_addr,
378                                 ntohs(addr->sin6_port),
379                                 protocol);
380         }
381         xprt->address_strings[RPC_DISPLAY_ALL] = buf;
382
383         buf = kzalloc(36, GFP_KERNEL);
384         if (buf)
385                 snprintf(buf, 36, "%pi6", &addr->sin6_addr);
386
387         xprt->address_strings[RPC_DISPLAY_HEX_ADDR] = buf;
388
389         buf = kzalloc(8, GFP_KERNEL);
390         if (buf) {
391                 snprintf(buf, 8, "%4hx",
392                                 ntohs(addr->sin6_port));
393         }
394         xprt->address_strings[RPC_DISPLAY_HEX_PORT] = buf;
395
396         buf = kzalloc(50, GFP_KERNEL);
397         if (buf) {
398                 snprintf(buf, 50, "%pI6.%u.%u",
399                          &addr->sin6_addr,
400                          ntohs(addr->sin6_port) >> 8,
401                          ntohs(addr->sin6_port) & 0xff);
402         }
403         xprt->address_strings[RPC_DISPLAY_UNIVERSAL_ADDR] = buf;
404
405         xprt->address_strings[RPC_DISPLAY_NETID] = netid;
406 }
407
408 static void xs_free_peer_addresses(struct rpc_xprt *xprt)
409 {
410         unsigned int i;
411
412         for (i = 0; i < RPC_DISPLAY_MAX; i++)
413                 switch (i) {
414                 case RPC_DISPLAY_PROTO:
415                 case RPC_DISPLAY_NETID:
416                         continue;
417                 default:
418                         kfree(xprt->address_strings[i]);
419                 }
420 }
421
422 #define XS_SENDMSG_FLAGS        (MSG_DONTWAIT | MSG_NOSIGNAL)
423
424 static int xs_send_kvec(struct socket *sock, struct sockaddr *addr, int addrlen, struct kvec *vec, unsigned int base, int more)
425 {
426         struct msghdr msg = {
427                 .msg_name       = addr,
428                 .msg_namelen    = addrlen,
429                 .msg_flags      = XS_SENDMSG_FLAGS | (more ? MSG_MORE : 0),
430         };
431         struct kvec iov = {
432                 .iov_base       = vec->iov_base + base,
433                 .iov_len        = vec->iov_len - base,
434         };
435
436         if (iov.iov_len != 0)
437                 return kernel_sendmsg(sock, &msg, &iov, 1, iov.iov_len);
438         return kernel_sendmsg(sock, &msg, NULL, 0, 0);
439 }
440
441 static int xs_send_pagedata(struct socket *sock, struct xdr_buf *xdr, unsigned int base, int more)
442 {
443         struct page **ppage;
444         unsigned int remainder;
445         int err, sent = 0;
446
447         remainder = xdr->page_len - base;
448         base += xdr->page_base;
449         ppage = xdr->pages + (base >> PAGE_SHIFT);
450         base &= ~PAGE_MASK;
451         for(;;) {
452                 unsigned int len = min_t(unsigned int, PAGE_SIZE - base, remainder);
453                 int flags = XS_SENDMSG_FLAGS;
454
455                 remainder -= len;
456                 if (remainder != 0 || more)
457                         flags |= MSG_MORE;
458                 err = sock->ops->sendpage(sock, *ppage, base, len, flags);
459                 if (remainder == 0 || err != len)
460                         break;
461                 sent += err;
462                 ppage++;
463                 base = 0;
464         }
465         if (sent == 0)
466                 return err;
467         if (err > 0)
468                 sent += err;
469         return sent;
470 }
471
472 /**
473  * xs_sendpages - write pages directly to a socket
474  * @sock: socket to send on
475  * @addr: UDP only -- address of destination
476  * @addrlen: UDP only -- length of destination address
477  * @xdr: buffer containing this request
478  * @base: starting position in the buffer
479  *
480  */
481 static int xs_sendpages(struct socket *sock, struct sockaddr *addr, int addrlen, struct xdr_buf *xdr, unsigned int base)
482 {
483         unsigned int remainder = xdr->len - base;
484         int err, sent = 0;
485
486         if (unlikely(!sock))
487                 return -ENOTSOCK;
488
489         clear_bit(SOCK_ASYNC_NOSPACE, &sock->flags);
490         if (base != 0) {
491                 addr = NULL;
492                 addrlen = 0;
493         }
494
495         if (base < xdr->head[0].iov_len || addr != NULL) {
496                 unsigned int len = xdr->head[0].iov_len - base;
497                 remainder -= len;
498                 err = xs_send_kvec(sock, addr, addrlen, &xdr->head[0], base, remainder != 0);
499                 if (remainder == 0 || err != len)
500                         goto out;
501                 sent += err;
502                 base = 0;
503         } else
504                 base -= xdr->head[0].iov_len;
505
506         if (base < xdr->page_len) {
507                 unsigned int len = xdr->page_len - base;
508                 remainder -= len;
509                 err = xs_send_pagedata(sock, xdr, base, remainder != 0);
510                 if (remainder == 0 || err != len)
511                         goto out;
512                 sent += err;
513                 base = 0;
514         } else
515                 base -= xdr->page_len;
516
517         if (base >= xdr->tail[0].iov_len)
518                 return sent;
519         err = xs_send_kvec(sock, NULL, 0, &xdr->tail[0], base, 0);
520 out:
521         if (sent == 0)
522                 return err;
523         if (err > 0)
524                 sent += err;
525         return sent;
526 }
527
528 static void xs_nospace_callback(struct rpc_task *task)
529 {
530         struct sock_xprt *transport = container_of(task->tk_rqstp->rq_xprt, struct sock_xprt, xprt);
531
532         transport->inet->sk_write_pending--;
533         clear_bit(SOCK_ASYNC_NOSPACE, &transport->sock->flags);
534 }
535
536 /**
537  * xs_nospace - place task on wait queue if transmit was incomplete
538  * @task: task to put to sleep
539  *
540  */
541 static int xs_nospace(struct rpc_task *task)
542 {
543         struct rpc_rqst *req = task->tk_rqstp;
544         struct rpc_xprt *xprt = req->rq_xprt;
545         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
546         int ret = 0;
547
548         dprintk("RPC: %5u xmit incomplete (%u left of %u)\n",
549                         task->tk_pid, req->rq_slen - req->rq_bytes_sent,
550                         req->rq_slen);
551
552         /* Protect against races with write_space */
553         spin_lock_bh(&xprt->transport_lock);
554
555         /* Don't race with disconnect */
556         if (xprt_connected(xprt)) {
557                 if (test_bit(SOCK_ASYNC_NOSPACE, &transport->sock->flags)) {
558                         ret = -EAGAIN;
559                         /*
560                          * Notify TCP that we're limited by the application
561                          * window size
562                          */
563                         set_bit(SOCK_NOSPACE, &transport->sock->flags);
564                         transport->inet->sk_write_pending++;
565                         /* ...and wait for more buffer space */
566                         xprt_wait_for_buffer_space(task, xs_nospace_callback);
567                 }
568         } else {
569                 clear_bit(SOCK_ASYNC_NOSPACE, &transport->sock->flags);
570                 ret = -ENOTCONN;
571         }
572
573         spin_unlock_bh(&xprt->transport_lock);
574         return ret;
575 }
576
577 /**
578  * xs_udp_send_request - write an RPC request to a UDP socket
579  * @task: address of RPC task that manages the state of an RPC request
580  *
581  * Return values:
582  *        0:    The request has been sent
583  *   EAGAIN:    The socket was blocked, please call again later to
584  *              complete the request
585  * ENOTCONN:    Caller needs to invoke connect logic then call again
586  *    other:    Some other error occured, the request was not sent
587  */
588 static int xs_udp_send_request(struct rpc_task *task)
589 {
590         struct rpc_rqst *req = task->tk_rqstp;
591         struct rpc_xprt *xprt = req->rq_xprt;
592         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
593         struct xdr_buf *xdr = &req->rq_snd_buf;
594         int status;
595
596         xs_pktdump("packet data:",
597                                 req->rq_svec->iov_base,
598                                 req->rq_svec->iov_len);
599
600         if (!xprt_bound(xprt))
601                 return -ENOTCONN;
602         status = xs_sendpages(transport->sock,
603                               xs_addr(xprt),
604                               xprt->addrlen, xdr,
605                               req->rq_bytes_sent);
606
607         dprintk("RPC:       xs_udp_send_request(%u) = %d\n",
608                         xdr->len - req->rq_bytes_sent, status);
609
610         if (status >= 0) {
611                 task->tk_bytes_sent += status;
612                 if (status >= req->rq_slen)
613                         return 0;
614                 /* Still some bytes left; set up for a retry later. */
615                 status = -EAGAIN;
616         }
617         if (!transport->sock)
618                 goto out;
619
620         switch (status) {
621         case -ENOTSOCK:
622                 status = -ENOTCONN;
623                 /* Should we call xs_close() here? */
624                 break;
625         case -EAGAIN:
626                 status = xs_nospace(task);
627                 break;
628         default:
629                 dprintk("RPC:       sendmsg returned unrecognized error %d\n",
630                         -status);
631         case -ENETUNREACH:
632         case -EPIPE:
633         case -ECONNREFUSED:
634                 /* When the server has died, an ICMP port unreachable message
635                  * prompts ECONNREFUSED. */
636                 clear_bit(SOCK_ASYNC_NOSPACE, &transport->sock->flags);
637         }
638 out:
639         return status;
640 }
641
642 /**
643  * xs_tcp_shutdown - gracefully shut down a TCP socket
644  * @xprt: transport
645  *
646  * Initiates a graceful shutdown of the TCP socket by calling the
647  * equivalent of shutdown(SHUT_WR);
648  */
649 static void xs_tcp_shutdown(struct rpc_xprt *xprt)
650 {
651         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
652         struct socket *sock = transport->sock;
653
654         if (sock != NULL)
655                 kernel_sock_shutdown(sock, SHUT_WR);
656 }
657
658 static inline void xs_encode_tcp_record_marker(struct xdr_buf *buf)
659 {
660         u32 reclen = buf->len - sizeof(rpc_fraghdr);
661         rpc_fraghdr *base = buf->head[0].iov_base;
662         *base = htonl(RPC_LAST_STREAM_FRAGMENT | reclen);
663 }
664
665 /**
666  * xs_tcp_send_request - write an RPC request to a TCP socket
667  * @task: address of RPC task that manages the state of an RPC request
668  *
669  * Return values:
670  *        0:    The request has been sent
671  *   EAGAIN:    The socket was blocked, please call again later to
672  *              complete the request
673  * ENOTCONN:    Caller needs to invoke connect logic then call again
674  *    other:    Some other error occured, the request was not sent
675  *
676  * XXX: In the case of soft timeouts, should we eventually give up
677  *      if sendmsg is not able to make progress?
678  */
679 static int xs_tcp_send_request(struct rpc_task *task)
680 {
681         struct rpc_rqst *req = task->tk_rqstp;
682         struct rpc_xprt *xprt = req->rq_xprt;
683         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
684         struct xdr_buf *xdr = &req->rq_snd_buf;
685         int status;
686
687         xs_encode_tcp_record_marker(&req->rq_snd_buf);
688
689         xs_pktdump("packet data:",
690                                 req->rq_svec->iov_base,
691                                 req->rq_svec->iov_len);
692
693         /* Continue transmitting the packet/record. We must be careful
694          * to cope with writespace callbacks arriving _after_ we have
695          * called sendmsg(). */
696         while (1) {
697                 status = xs_sendpages(transport->sock,
698                                         NULL, 0, xdr, req->rq_bytes_sent);
699
700                 dprintk("RPC:       xs_tcp_send_request(%u) = %d\n",
701                                 xdr->len - req->rq_bytes_sent, status);
702
703                 if (unlikely(status < 0))
704                         break;
705
706                 /* If we've sent the entire packet, immediately
707                  * reset the count of bytes sent. */
708                 req->rq_bytes_sent += status;
709                 task->tk_bytes_sent += status;
710                 if (likely(req->rq_bytes_sent >= req->rq_slen)) {
711                         req->rq_bytes_sent = 0;
712                         return 0;
713                 }
714
715                 if (status != 0)
716                         continue;
717                 status = -EAGAIN;
718                 break;
719         }
720         if (!transport->sock)
721                 goto out;
722
723         switch (status) {
724         case -ENOTSOCK:
725                 status = -ENOTCONN;
726                 /* Should we call xs_close() here? */
727                 break;
728         case -EAGAIN:
729                 status = xs_nospace(task);
730                 break;
731         default:
732                 dprintk("RPC:       sendmsg returned unrecognized error %d\n",
733                         -status);
734         case -ECONNRESET:
735         case -EPIPE:
736                 xs_tcp_shutdown(xprt);
737         case -ECONNREFUSED:
738         case -ENOTCONN:
739                 clear_bit(SOCK_ASYNC_NOSPACE, &transport->sock->flags);
740         }
741 out:
742         return status;
743 }
744
745 /**
746  * xs_tcp_release_xprt - clean up after a tcp transmission
747  * @xprt: transport
748  * @task: rpc task
749  *
750  * This cleans up if an error causes us to abort the transmission of a request.
751  * In this case, the socket may need to be reset in order to avoid confusing
752  * the server.
753  */
754 static void xs_tcp_release_xprt(struct rpc_xprt *xprt, struct rpc_task *task)
755 {
756         struct rpc_rqst *req;
757
758         if (task != xprt->snd_task)
759                 return;
760         if (task == NULL)
761                 goto out_release;
762         req = task->tk_rqstp;
763         if (req->rq_bytes_sent == 0)
764                 goto out_release;
765         if (req->rq_bytes_sent == req->rq_snd_buf.len)
766                 goto out_release;
767         set_bit(XPRT_CLOSE_WAIT, &task->tk_xprt->state);
768 out_release:
769         xprt_release_xprt(xprt, task);
770 }
771
772 static void xs_save_old_callbacks(struct sock_xprt *transport, struct sock *sk)
773 {
774         transport->old_data_ready = sk->sk_data_ready;
775         transport->old_state_change = sk->sk_state_change;
776         transport->old_write_space = sk->sk_write_space;
777         transport->old_error_report = sk->sk_error_report;
778 }
779
780 static void xs_restore_old_callbacks(struct sock_xprt *transport, struct sock *sk)
781 {
782         sk->sk_data_ready = transport->old_data_ready;
783         sk->sk_state_change = transport->old_state_change;
784         sk->sk_write_space = transport->old_write_space;
785         sk->sk_error_report = transport->old_error_report;
786 }
787
788 static void xs_reset_transport(struct sock_xprt *transport)
789 {
790         struct socket *sock = transport->sock;
791         struct sock *sk = transport->inet;
792
793         if (sk == NULL)
794                 return;
795
796         write_lock_bh(&sk->sk_callback_lock);
797         transport->inet = NULL;
798         transport->sock = NULL;
799
800         sk->sk_user_data = NULL;
801
802         xs_restore_old_callbacks(transport, sk);
803         write_unlock_bh(&sk->sk_callback_lock);
804
805         sk->sk_no_check = 0;
806
807         sock_release(sock);
808 }
809
810 /**
811  * xs_close - close a socket
812  * @xprt: transport
813  *
814  * This is used when all requests are complete; ie, no DRC state remains
815  * on the server we want to save.
816  *
817  * The caller _must_ be holding XPRT_LOCKED in order to avoid issues with
818  * xs_reset_transport() zeroing the socket from underneath a writer.
819  */
820 static void xs_close(struct rpc_xprt *xprt)
821 {
822         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
823
824         dprintk("RPC:       xs_close xprt %p\n", xprt);
825
826         xs_reset_transport(transport);
827
828         smp_mb__before_clear_bit();
829         clear_bit(XPRT_CONNECTION_ABORT, &xprt->state);
830         clear_bit(XPRT_CLOSE_WAIT, &xprt->state);
831         clear_bit(XPRT_CLOSING, &xprt->state);
832         smp_mb__after_clear_bit();
833         xprt_disconnect_done(xprt);
834 }
835
836 static void xs_tcp_close(struct rpc_xprt *xprt)
837 {
838         if (test_and_clear_bit(XPRT_CONNECTION_CLOSE, &xprt->state))
839                 xs_close(xprt);
840         else
841                 xs_tcp_shutdown(xprt);
842 }
843
844 /**
845  * xs_destroy - prepare to shutdown a transport
846  * @xprt: doomed transport
847  *
848  */
849 static void xs_destroy(struct rpc_xprt *xprt)
850 {
851         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
852
853         dprintk("RPC:       xs_destroy xprt %p\n", xprt);
854
855         cancel_rearming_delayed_work(&transport->connect_worker);
856
857         xs_close(xprt);
858         xs_free_peer_addresses(xprt);
859         kfree(xprt->slot);
860         kfree(xprt);
861         module_put(THIS_MODULE);
862 }
863
864 static inline struct rpc_xprt *xprt_from_sock(struct sock *sk)
865 {
866         return (struct rpc_xprt *) sk->sk_user_data;
867 }
868
869 /**
870  * xs_udp_data_ready - "data ready" callback for UDP sockets
871  * @sk: socket with data to read
872  * @len: how much data to read
873  *
874  */
875 static void xs_udp_data_ready(struct sock *sk, int len)
876 {
877         struct rpc_task *task;
878         struct rpc_xprt *xprt;
879         struct rpc_rqst *rovr;
880         struct sk_buff *skb;
881         int err, repsize, copied;
882         u32 _xid;
883         __be32 *xp;
884
885         read_lock(&sk->sk_callback_lock);
886         dprintk("RPC:       xs_udp_data_ready...\n");
887         if (!(xprt = xprt_from_sock(sk)))
888                 goto out;
889
890         if ((skb = skb_recv_datagram(sk, 0, 1, &err)) == NULL)
891                 goto out;
892
893         if (xprt->shutdown)
894                 goto dropit;
895
896         repsize = skb->len - sizeof(struct udphdr);
897         if (repsize < 4) {
898                 dprintk("RPC:       impossible RPC reply size %d!\n", repsize);
899                 goto dropit;
900         }
901
902         /* Copy the XID from the skb... */
903         xp = skb_header_pointer(skb, sizeof(struct udphdr),
904                                 sizeof(_xid), &_xid);
905         if (xp == NULL)
906                 goto dropit;
907
908         /* Look up and lock the request corresponding to the given XID */
909         spin_lock(&xprt->transport_lock);
910         rovr = xprt_lookup_rqst(xprt, *xp);
911         if (!rovr)
912                 goto out_unlock;
913         task = rovr->rq_task;
914
915         if ((copied = rovr->rq_private_buf.buflen) > repsize)
916                 copied = repsize;
917
918         /* Suck it into the iovec, verify checksum if not done by hw. */
919         if (csum_partial_copy_to_xdr(&rovr->rq_private_buf, skb)) {
920                 UDPX_INC_STATS_BH(sk, UDP_MIB_INERRORS);
921                 goto out_unlock;
922         }
923
924         UDPX_INC_STATS_BH(sk, UDP_MIB_INDATAGRAMS);
925
926         /* Something worked... */
927         dst_confirm(skb->dst);
928
929         xprt_adjust_cwnd(task, copied);
930         xprt_update_rtt(task);
931         xprt_complete_rqst(task, copied);
932
933  out_unlock:
934         spin_unlock(&xprt->transport_lock);
935  dropit:
936         skb_free_datagram(sk, skb);
937  out:
938         read_unlock(&sk->sk_callback_lock);
939 }
940
941 static inline void xs_tcp_read_fraghdr(struct rpc_xprt *xprt, struct xdr_skb_reader *desc)
942 {
943         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
944         size_t len, used;
945         char *p;
946
947         p = ((char *) &transport->tcp_fraghdr) + transport->tcp_offset;
948         len = sizeof(transport->tcp_fraghdr) - transport->tcp_offset;
949         used = xdr_skb_read_bits(desc, p, len);
950         transport->tcp_offset += used;
951         if (used != len)
952                 return;
953
954         transport->tcp_reclen = ntohl(transport->tcp_fraghdr);
955         if (transport->tcp_reclen & RPC_LAST_STREAM_FRAGMENT)
956                 transport->tcp_flags |= TCP_RCV_LAST_FRAG;
957         else
958                 transport->tcp_flags &= ~TCP_RCV_LAST_FRAG;
959         transport->tcp_reclen &= RPC_FRAGMENT_SIZE_MASK;
960
961         transport->tcp_flags &= ~TCP_RCV_COPY_FRAGHDR;
962         transport->tcp_offset = 0;
963
964         /* Sanity check of the record length */
965         if (unlikely(transport->tcp_reclen < 8)) {
966                 dprintk("RPC:       invalid TCP record fragment length\n");
967                 xprt_force_disconnect(xprt);
968                 return;
969         }
970         dprintk("RPC:       reading TCP record fragment of length %d\n",
971                         transport->tcp_reclen);
972 }
973
974 static void xs_tcp_check_fraghdr(struct sock_xprt *transport)
975 {
976         if (transport->tcp_offset == transport->tcp_reclen) {
977                 transport->tcp_flags |= TCP_RCV_COPY_FRAGHDR;
978                 transport->tcp_offset = 0;
979                 if (transport->tcp_flags & TCP_RCV_LAST_FRAG) {
980                         transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
981                         transport->tcp_flags |= TCP_RCV_COPY_XID;
982                         transport->tcp_copied = 0;
983                 }
984         }
985 }
986
987 static inline void xs_tcp_read_xid(struct sock_xprt *transport, struct xdr_skb_reader *desc)
988 {
989         size_t len, used;
990         char *p;
991
992         len = sizeof(transport->tcp_xid) - transport->tcp_offset;
993         dprintk("RPC:       reading XID (%Zu bytes)\n", len);
994         p = ((char *) &transport->tcp_xid) + transport->tcp_offset;
995         used = xdr_skb_read_bits(desc, p, len);
996         transport->tcp_offset += used;
997         if (used != len)
998                 return;
999         transport->tcp_flags &= ~TCP_RCV_COPY_XID;
1000         transport->tcp_flags |= TCP_RCV_COPY_CALLDIR;
1001         transport->tcp_copied = 4;
1002         dprintk("RPC:       reading %s XID %08x\n",
1003                         (transport->tcp_flags & TCP_RPC_REPLY) ? "reply for"
1004                                                               : "request with",
1005                         ntohl(transport->tcp_xid));
1006         xs_tcp_check_fraghdr(transport);
1007 }
1008
1009 static inline void xs_tcp_read_calldir(struct sock_xprt *transport,
1010                                        struct xdr_skb_reader *desc)
1011 {
1012         size_t len, used;
1013         u32 offset;
1014         __be32  calldir;
1015
1016         /*
1017          * We want transport->tcp_offset to be 8 at the end of this routine
1018          * (4 bytes for the xid and 4 bytes for the call/reply flag).
1019          * When this function is called for the first time,
1020          * transport->tcp_offset is 4 (after having already read the xid).
1021          */
1022         offset = transport->tcp_offset - sizeof(transport->tcp_xid);
1023         len = sizeof(calldir) - offset;
1024         dprintk("RPC:       reading CALL/REPLY flag (%Zu bytes)\n", len);
1025         used = xdr_skb_read_bits(desc, &calldir, len);
1026         transport->tcp_offset += used;
1027         if (used != len)
1028                 return;
1029         transport->tcp_flags &= ~TCP_RCV_COPY_CALLDIR;
1030         transport->tcp_flags |= TCP_RCV_COPY_DATA;
1031         transport->tcp_copied += 4;
1032         if (ntohl(calldir) == RPC_REPLY)
1033                 transport->tcp_flags |= TCP_RPC_REPLY;
1034         else
1035                 transport->tcp_flags &= ~TCP_RPC_REPLY;
1036         dprintk("RPC:       reading %s CALL/REPLY flag %08x\n",
1037                         (transport->tcp_flags & TCP_RPC_REPLY) ?
1038                                 "reply for" : "request with", calldir);
1039         xs_tcp_check_fraghdr(transport);
1040 }
1041
1042 static inline void xs_tcp_read_request(struct rpc_xprt *xprt, struct xdr_skb_reader *desc)
1043 {
1044         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1045         struct rpc_rqst *req;
1046         struct xdr_buf *rcvbuf;
1047         size_t len;
1048         ssize_t r;
1049
1050         /* Find and lock the request corresponding to this xid */
1051         spin_lock(&xprt->transport_lock);
1052         req = xprt_lookup_rqst(xprt, transport->tcp_xid);
1053         if (!req) {
1054                 transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
1055                 dprintk("RPC:       XID %08x request not found!\n",
1056                                 ntohl(transport->tcp_xid));
1057                 spin_unlock(&xprt->transport_lock);
1058                 return;
1059         }
1060
1061         rcvbuf = &req->rq_private_buf;
1062         len = desc->count;
1063         if (len > transport->tcp_reclen - transport->tcp_offset) {
1064                 struct xdr_skb_reader my_desc;
1065
1066                 len = transport->tcp_reclen - transport->tcp_offset;
1067                 memcpy(&my_desc, desc, sizeof(my_desc));
1068                 my_desc.count = len;
1069                 r = xdr_partial_copy_from_skb(rcvbuf, transport->tcp_copied,
1070                                           &my_desc, xdr_skb_read_bits);
1071                 desc->count -= r;
1072                 desc->offset += r;
1073         } else
1074                 r = xdr_partial_copy_from_skb(rcvbuf, transport->tcp_copied,
1075                                           desc, xdr_skb_read_bits);
1076
1077         if (r > 0) {
1078                 transport->tcp_copied += r;
1079                 transport->tcp_offset += r;
1080         }
1081         if (r != len) {
1082                 /* Error when copying to the receive buffer,
1083                  * usually because we weren't able to allocate
1084                  * additional buffer pages. All we can do now
1085                  * is turn off TCP_RCV_COPY_DATA, so the request
1086                  * will not receive any additional updates,
1087                  * and time out.
1088                  * Any remaining data from this record will
1089                  * be discarded.
1090                  */
1091                 transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
1092                 dprintk("RPC:       XID %08x truncated request\n",
1093                                 ntohl(transport->tcp_xid));
1094                 dprintk("RPC:       xprt = %p, tcp_copied = %lu, "
1095                                 "tcp_offset = %u, tcp_reclen = %u\n",
1096                                 xprt, transport->tcp_copied,
1097                                 transport->tcp_offset, transport->tcp_reclen);
1098                 goto out;
1099         }
1100
1101         dprintk("RPC:       XID %08x read %Zd bytes\n",
1102                         ntohl(transport->tcp_xid), r);
1103         dprintk("RPC:       xprt = %p, tcp_copied = %lu, tcp_offset = %u, "
1104                         "tcp_reclen = %u\n", xprt, transport->tcp_copied,
1105                         transport->tcp_offset, transport->tcp_reclen);
1106
1107         if (transport->tcp_copied == req->rq_private_buf.buflen)
1108                 transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
1109         else if (transport->tcp_offset == transport->tcp_reclen) {
1110                 if (transport->tcp_flags & TCP_RCV_LAST_FRAG)
1111                         transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
1112         }
1113
1114 out:
1115         if (!(transport->tcp_flags & TCP_RCV_COPY_DATA))
1116                 xprt_complete_rqst(req->rq_task, transport->tcp_copied);
1117         spin_unlock(&xprt->transport_lock);
1118         xs_tcp_check_fraghdr(transport);
1119 }
1120
1121 static inline void xs_tcp_read_discard(struct sock_xprt *transport, struct xdr_skb_reader *desc)
1122 {
1123         size_t len;
1124
1125         len = transport->tcp_reclen - transport->tcp_offset;
1126         if (len > desc->count)
1127                 len = desc->count;
1128         desc->count -= len;
1129         desc->offset += len;
1130         transport->tcp_offset += len;
1131         dprintk("RPC:       discarded %Zu bytes\n", len);
1132         xs_tcp_check_fraghdr(transport);
1133 }
1134
1135 static int xs_tcp_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb, unsigned int offset, size_t len)
1136 {
1137         struct rpc_xprt *xprt = rd_desc->arg.data;
1138         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1139         struct xdr_skb_reader desc = {
1140                 .skb    = skb,
1141                 .offset = offset,
1142                 .count  = len,
1143         };
1144
1145         dprintk("RPC:       xs_tcp_data_recv started\n");
1146         do {
1147                 /* Read in a new fragment marker if necessary */
1148                 /* Can we ever really expect to get completely empty fragments? */
1149                 if (transport->tcp_flags & TCP_RCV_COPY_FRAGHDR) {
1150                         xs_tcp_read_fraghdr(xprt, &desc);
1151                         continue;
1152                 }
1153                 /* Read in the xid if necessary */
1154                 if (transport->tcp_flags & TCP_RCV_COPY_XID) {
1155                         xs_tcp_read_xid(transport, &desc);
1156                         continue;
1157                 }
1158                 /* Read in the call/reply flag */
1159                 if (transport->tcp_flags & TCP_RCV_COPY_CALLDIR) {
1160                         xs_tcp_read_calldir(transport, &desc);
1161                         continue;
1162                 }
1163                 /* Read in the request data */
1164                 if (transport->tcp_flags & TCP_RCV_COPY_DATA) {
1165                         xs_tcp_read_request(xprt, &desc);
1166                         continue;
1167                 }
1168                 /* Skip over any trailing bytes on short reads */
1169                 xs_tcp_read_discard(transport, &desc);
1170         } while (desc.count);
1171         dprintk("RPC:       xs_tcp_data_recv done\n");
1172         return len - desc.count;
1173 }
1174
1175 /**
1176  * xs_tcp_data_ready - "data ready" callback for TCP sockets
1177  * @sk: socket with data to read
1178  * @bytes: how much data to read
1179  *
1180  */
1181 static void xs_tcp_data_ready(struct sock *sk, int bytes)
1182 {
1183         struct rpc_xprt *xprt;
1184         read_descriptor_t rd_desc;
1185         int read;
1186
1187         dprintk("RPC:       xs_tcp_data_ready...\n");
1188
1189         read_lock(&sk->sk_callback_lock);
1190         if (!(xprt = xprt_from_sock(sk)))
1191                 goto out;
1192         if (xprt->shutdown)
1193                 goto out;
1194
1195         /* We use rd_desc to pass struct xprt to xs_tcp_data_recv */
1196         rd_desc.arg.data = xprt;
1197         do {
1198                 rd_desc.count = 65536;
1199                 read = tcp_read_sock(sk, &rd_desc, xs_tcp_data_recv);
1200         } while (read > 0);
1201 out:
1202         read_unlock(&sk->sk_callback_lock);
1203 }
1204
1205 /*
1206  * Do the equivalent of linger/linger2 handling for dealing with
1207  * broken servers that don't close the socket in a timely
1208  * fashion
1209  */
1210 static void xs_tcp_schedule_linger_timeout(struct rpc_xprt *xprt,
1211                 unsigned long timeout)
1212 {
1213         struct sock_xprt *transport;
1214
1215         if (xprt_test_and_set_connecting(xprt))
1216                 return;
1217         set_bit(XPRT_CONNECTION_ABORT, &xprt->state);
1218         transport = container_of(xprt, struct sock_xprt, xprt);
1219         queue_delayed_work(rpciod_workqueue, &transport->connect_worker,
1220                            timeout);
1221 }
1222
1223 static void xs_tcp_cancel_linger_timeout(struct rpc_xprt *xprt)
1224 {
1225         struct sock_xprt *transport;
1226
1227         transport = container_of(xprt, struct sock_xprt, xprt);
1228
1229         if (!test_bit(XPRT_CONNECTION_ABORT, &xprt->state) ||
1230             !cancel_delayed_work(&transport->connect_worker))
1231                 return;
1232         clear_bit(XPRT_CONNECTION_ABORT, &xprt->state);
1233         xprt_clear_connecting(xprt);
1234 }
1235
1236 static void xs_sock_mark_closed(struct rpc_xprt *xprt)
1237 {
1238         smp_mb__before_clear_bit();
1239         clear_bit(XPRT_CLOSE_WAIT, &xprt->state);
1240         clear_bit(XPRT_CLOSING, &xprt->state);
1241         smp_mb__after_clear_bit();
1242         /* Mark transport as closed and wake up all pending tasks */
1243         xprt_disconnect_done(xprt);
1244 }
1245
1246 /**
1247  * xs_tcp_state_change - callback to handle TCP socket state changes
1248  * @sk: socket whose state has changed
1249  *
1250  */
1251 static void xs_tcp_state_change(struct sock *sk)
1252 {
1253         struct rpc_xprt *xprt;
1254
1255         read_lock(&sk->sk_callback_lock);
1256         if (!(xprt = xprt_from_sock(sk)))
1257                 goto out;
1258         dprintk("RPC:       xs_tcp_state_change client %p...\n", xprt);
1259         dprintk("RPC:       state %x conn %d dead %d zapped %d\n",
1260                         sk->sk_state, xprt_connected(xprt),
1261                         sock_flag(sk, SOCK_DEAD),
1262                         sock_flag(sk, SOCK_ZAPPED));
1263
1264         switch (sk->sk_state) {
1265         case TCP_ESTABLISHED:
1266                 spin_lock_bh(&xprt->transport_lock);
1267                 if (!xprt_test_and_set_connected(xprt)) {
1268                         struct sock_xprt *transport = container_of(xprt,
1269                                         struct sock_xprt, xprt);
1270
1271                         /* Reset TCP record info */
1272                         transport->tcp_offset = 0;
1273                         transport->tcp_reclen = 0;
1274                         transport->tcp_copied = 0;
1275                         transport->tcp_flags =
1276                                 TCP_RCV_COPY_FRAGHDR | TCP_RCV_COPY_XID;
1277
1278                         xprt_wake_pending_tasks(xprt, -EAGAIN);
1279                 }
1280                 spin_unlock_bh(&xprt->transport_lock);
1281                 break;
1282         case TCP_FIN_WAIT1:
1283                 /* The client initiated a shutdown of the socket */
1284                 xprt->connect_cookie++;
1285                 xprt->reestablish_timeout = 0;
1286                 set_bit(XPRT_CLOSING, &xprt->state);
1287                 smp_mb__before_clear_bit();
1288                 clear_bit(XPRT_CONNECTED, &xprt->state);
1289                 clear_bit(XPRT_CLOSE_WAIT, &xprt->state);
1290                 smp_mb__after_clear_bit();
1291                 xs_tcp_schedule_linger_timeout(xprt, xs_tcp_fin_timeout);
1292                 break;
1293         case TCP_CLOSE_WAIT:
1294                 /* The server initiated a shutdown of the socket */
1295                 xprt_force_disconnect(xprt);
1296         case TCP_SYN_SENT:
1297                 xprt->connect_cookie++;
1298         case TCP_CLOSING:
1299                 /*
1300                  * If the server closed down the connection, make sure that
1301                  * we back off before reconnecting
1302                  */
1303                 if (xprt->reestablish_timeout < XS_TCP_INIT_REEST_TO)
1304                         xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
1305                 break;
1306         case TCP_LAST_ACK:
1307                 set_bit(XPRT_CLOSING, &xprt->state);
1308                 xs_tcp_schedule_linger_timeout(xprt, xs_tcp_fin_timeout);
1309                 smp_mb__before_clear_bit();
1310                 clear_bit(XPRT_CONNECTED, &xprt->state);
1311                 smp_mb__after_clear_bit();
1312                 break;
1313         case TCP_CLOSE:
1314                 xs_tcp_cancel_linger_timeout(xprt);
1315                 xs_sock_mark_closed(xprt);
1316         }
1317  out:
1318         read_unlock(&sk->sk_callback_lock);
1319 }
1320
1321 /**
1322  * xs_error_report - callback mainly for catching socket errors
1323  * @sk: socket
1324  */
1325 static void xs_error_report(struct sock *sk)
1326 {
1327         struct rpc_xprt *xprt;
1328
1329         read_lock(&sk->sk_callback_lock);
1330         if (!(xprt = xprt_from_sock(sk)))
1331                 goto out;
1332         dprintk("RPC:       %s client %p...\n"
1333                         "RPC:       error %d\n",
1334                         __func__, xprt, sk->sk_err);
1335         xprt_wake_pending_tasks(xprt, -EAGAIN);
1336 out:
1337         read_unlock(&sk->sk_callback_lock);
1338 }
1339
1340 static void xs_write_space(struct sock *sk)
1341 {
1342         struct socket *sock;
1343         struct rpc_xprt *xprt;
1344
1345         if (unlikely(!(sock = sk->sk_socket)))
1346                 return;
1347         clear_bit(SOCK_NOSPACE, &sock->flags);
1348
1349         if (unlikely(!(xprt = xprt_from_sock(sk))))
1350                 return;
1351         if (test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sock->flags) == 0)
1352                 return;
1353
1354         xprt_write_space(xprt);
1355 }
1356
1357 /**
1358  * xs_udp_write_space - callback invoked when socket buffer space
1359  *                             becomes available
1360  * @sk: socket whose state has changed
1361  *
1362  * Called when more output buffer space is available for this socket.
1363  * We try not to wake our writers until they can make "significant"
1364  * progress, otherwise we'll waste resources thrashing kernel_sendmsg
1365  * with a bunch of small requests.
1366  */
1367 static void xs_udp_write_space(struct sock *sk)
1368 {
1369         read_lock(&sk->sk_callback_lock);
1370
1371         /* from net/core/sock.c:sock_def_write_space */
1372         if (sock_writeable(sk))
1373                 xs_write_space(sk);
1374
1375         read_unlock(&sk->sk_callback_lock);
1376 }
1377
1378 /**
1379  * xs_tcp_write_space - callback invoked when socket buffer space
1380  *                             becomes available
1381  * @sk: socket whose state has changed
1382  *
1383  * Called when more output buffer space is available for this socket.
1384  * We try not to wake our writers until they can make "significant"
1385  * progress, otherwise we'll waste resources thrashing kernel_sendmsg
1386  * with a bunch of small requests.
1387  */
1388 static void xs_tcp_write_space(struct sock *sk)
1389 {
1390         read_lock(&sk->sk_callback_lock);
1391
1392         /* from net/core/stream.c:sk_stream_write_space */
1393         if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk))
1394                 xs_write_space(sk);
1395
1396         read_unlock(&sk->sk_callback_lock);
1397 }
1398
1399 static void xs_udp_do_set_buffer_size(struct rpc_xprt *xprt)
1400 {
1401         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1402         struct sock *sk = transport->inet;
1403
1404         if (transport->rcvsize) {
1405                 sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
1406                 sk->sk_rcvbuf = transport->rcvsize * xprt->max_reqs * 2;
1407         }
1408         if (transport->sndsize) {
1409                 sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
1410                 sk->sk_sndbuf = transport->sndsize * xprt->max_reqs * 2;
1411                 sk->sk_write_space(sk);
1412         }
1413 }
1414
1415 /**
1416  * xs_udp_set_buffer_size - set send and receive limits
1417  * @xprt: generic transport
1418  * @sndsize: requested size of send buffer, in bytes
1419  * @rcvsize: requested size of receive buffer, in bytes
1420  *
1421  * Set socket send and receive buffer size limits.
1422  */
1423 static void xs_udp_set_buffer_size(struct rpc_xprt *xprt, size_t sndsize, size_t rcvsize)
1424 {
1425         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1426
1427         transport->sndsize = 0;
1428         if (sndsize)
1429                 transport->sndsize = sndsize + 1024;
1430         transport->rcvsize = 0;
1431         if (rcvsize)
1432                 transport->rcvsize = rcvsize + 1024;
1433
1434         xs_udp_do_set_buffer_size(xprt);
1435 }
1436
1437 /**
1438  * xs_udp_timer - called when a retransmit timeout occurs on a UDP transport
1439  * @task: task that timed out
1440  *
1441  * Adjust the congestion window after a retransmit timeout has occurred.
1442  */
1443 static void xs_udp_timer(struct rpc_task *task)
1444 {
1445         xprt_adjust_cwnd(task, -ETIMEDOUT);
1446 }
1447
1448 static unsigned short xs_get_random_port(void)
1449 {
1450         unsigned short range = xprt_max_resvport - xprt_min_resvport;
1451         unsigned short rand = (unsigned short) net_random() % range;
1452         return rand + xprt_min_resvport;
1453 }
1454
1455 /**
1456  * xs_set_port - reset the port number in the remote endpoint address
1457  * @xprt: generic transport
1458  * @port: new port number
1459  *
1460  */
1461 static void xs_set_port(struct rpc_xprt *xprt, unsigned short port)
1462 {
1463         struct sockaddr *addr = xs_addr(xprt);
1464
1465         dprintk("RPC:       setting port for xprt %p to %u\n", xprt, port);
1466
1467         switch (addr->sa_family) {
1468         case AF_INET:
1469                 ((struct sockaddr_in *)addr)->sin_port = htons(port);
1470                 break;
1471         case AF_INET6:
1472                 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
1473                 break;
1474         default:
1475                 BUG();
1476         }
1477 }
1478
1479 static unsigned short xs_get_srcport(struct sock_xprt *transport, struct socket *sock)
1480 {
1481         unsigned short port = transport->port;
1482
1483         if (port == 0 && transport->xprt.resvport)
1484                 port = xs_get_random_port();
1485         return port;
1486 }
1487
1488 static unsigned short xs_next_srcport(struct sock_xprt *transport, struct socket *sock, unsigned short port)
1489 {
1490         if (transport->port != 0)
1491                 transport->port = 0;
1492         if (!transport->xprt.resvport)
1493                 return 0;
1494         if (port <= xprt_min_resvport || port > xprt_max_resvport)
1495                 return xprt_max_resvport;
1496         return --port;
1497 }
1498
1499 static int xs_bind4(struct sock_xprt *transport, struct socket *sock)
1500 {
1501         struct sockaddr_in myaddr = {
1502                 .sin_family = AF_INET,
1503         };
1504         struct sockaddr_in *sa;
1505         int err, nloop = 0;
1506         unsigned short port = xs_get_srcport(transport, sock);
1507         unsigned short last;
1508
1509         sa = (struct sockaddr_in *)&transport->addr;
1510         myaddr.sin_addr = sa->sin_addr;
1511         do {
1512                 myaddr.sin_port = htons(port);
1513                 err = kernel_bind(sock, (struct sockaddr *) &myaddr,
1514                                                 sizeof(myaddr));
1515                 if (port == 0)
1516                         break;
1517                 if (err == 0) {
1518                         transport->port = port;
1519                         break;
1520                 }
1521                 last = port;
1522                 port = xs_next_srcport(transport, sock, port);
1523                 if (port > last)
1524                         nloop++;
1525         } while (err == -EADDRINUSE && nloop != 2);
1526         dprintk("RPC:       %s %pI4:%u: %s (%d)\n",
1527                         __func__, &myaddr.sin_addr,
1528                         port, err ? "failed" : "ok", err);
1529         return err;
1530 }
1531
1532 static int xs_bind6(struct sock_xprt *transport, struct socket *sock)
1533 {
1534         struct sockaddr_in6 myaddr = {
1535                 .sin6_family = AF_INET6,
1536         };
1537         struct sockaddr_in6 *sa;
1538         int err, nloop = 0;
1539         unsigned short port = xs_get_srcport(transport, sock);
1540         unsigned short last;
1541
1542         sa = (struct sockaddr_in6 *)&transport->addr;
1543         myaddr.sin6_addr = sa->sin6_addr;
1544         do {
1545                 myaddr.sin6_port = htons(port);
1546                 err = kernel_bind(sock, (struct sockaddr *) &myaddr,
1547                                                 sizeof(myaddr));
1548                 if (port == 0)
1549                         break;
1550                 if (err == 0) {
1551                         transport->port = port;
1552                         break;
1553                 }
1554                 last = port;
1555                 port = xs_next_srcport(transport, sock, port);
1556                 if (port > last)
1557                         nloop++;
1558         } while (err == -EADDRINUSE && nloop != 2);
1559         dprintk("RPC:       xs_bind6 %pI6:%u: %s (%d)\n",
1560                 &myaddr.sin6_addr, port, err ? "failed" : "ok", err);
1561         return err;
1562 }
1563
1564 #ifdef CONFIG_DEBUG_LOCK_ALLOC
1565 static struct lock_class_key xs_key[2];
1566 static struct lock_class_key xs_slock_key[2];
1567
1568 static inline void xs_reclassify_socket4(struct socket *sock)
1569 {
1570         struct sock *sk = sock->sk;
1571
1572         BUG_ON(sock_owned_by_user(sk));
1573         sock_lock_init_class_and_name(sk, "slock-AF_INET-RPC",
1574                 &xs_slock_key[0], "sk_lock-AF_INET-RPC", &xs_key[0]);
1575 }
1576
1577 static inline void xs_reclassify_socket6(struct socket *sock)
1578 {
1579         struct sock *sk = sock->sk;
1580
1581         BUG_ON(sock_owned_by_user(sk));
1582         sock_lock_init_class_and_name(sk, "slock-AF_INET6-RPC",
1583                 &xs_slock_key[1], "sk_lock-AF_INET6-RPC", &xs_key[1]);
1584 }
1585 #else
1586 static inline void xs_reclassify_socket4(struct socket *sock)
1587 {
1588 }
1589
1590 static inline void xs_reclassify_socket6(struct socket *sock)
1591 {
1592 }
1593 #endif
1594
1595 static void xs_udp_finish_connecting(struct rpc_xprt *xprt, struct socket *sock)
1596 {
1597         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1598
1599         if (!transport->inet) {
1600                 struct sock *sk = sock->sk;
1601
1602                 write_lock_bh(&sk->sk_callback_lock);
1603
1604                 xs_save_old_callbacks(transport, sk);
1605
1606                 sk->sk_user_data = xprt;
1607                 sk->sk_data_ready = xs_udp_data_ready;
1608                 sk->sk_write_space = xs_udp_write_space;
1609                 sk->sk_error_report = xs_error_report;
1610                 sk->sk_no_check = UDP_CSUM_NORCV;
1611                 sk->sk_allocation = GFP_ATOMIC;
1612
1613                 xprt_set_connected(xprt);
1614
1615                 /* Reset to new socket */
1616                 transport->sock = sock;
1617                 transport->inet = sk;
1618
1619                 write_unlock_bh(&sk->sk_callback_lock);
1620         }
1621         xs_udp_do_set_buffer_size(xprt);
1622 }
1623
1624 /**
1625  * xs_udp_connect_worker4 - set up a UDP socket
1626  * @work: RPC transport to connect
1627  *
1628  * Invoked by a work queue tasklet.
1629  */
1630 static void xs_udp_connect_worker4(struct work_struct *work)
1631 {
1632         struct sock_xprt *transport =
1633                 container_of(work, struct sock_xprt, connect_worker.work);
1634         struct rpc_xprt *xprt = &transport->xprt;
1635         struct socket *sock = transport->sock;
1636         int err, status = -EIO;
1637
1638         if (xprt->shutdown)
1639                 goto out;
1640
1641         /* Start by resetting any existing state */
1642         xs_reset_transport(transport);
1643
1644         err = sock_create_kern(PF_INET, SOCK_DGRAM, IPPROTO_UDP, &sock);
1645         if (err < 0) {
1646                 dprintk("RPC:       can't create UDP transport socket (%d).\n", -err);
1647                 goto out;
1648         }
1649         xs_reclassify_socket4(sock);
1650
1651         if (xs_bind4(transport, sock)) {
1652                 sock_release(sock);
1653                 goto out;
1654         }
1655
1656         dprintk("RPC:       worker connecting xprt %p to address: %s\n",
1657                         xprt, xprt->address_strings[RPC_DISPLAY_ALL]);
1658
1659         xs_udp_finish_connecting(xprt, sock);
1660         status = 0;
1661 out:
1662         xprt_clear_connecting(xprt);
1663         xprt_wake_pending_tasks(xprt, status);
1664 }
1665
1666 /**
1667  * xs_udp_connect_worker6 - set up a UDP socket
1668  * @work: RPC transport to connect
1669  *
1670  * Invoked by a work queue tasklet.
1671  */
1672 static void xs_udp_connect_worker6(struct work_struct *work)
1673 {
1674         struct sock_xprt *transport =
1675                 container_of(work, struct sock_xprt, connect_worker.work);
1676         struct rpc_xprt *xprt = &transport->xprt;
1677         struct socket *sock = transport->sock;
1678         int err, status = -EIO;
1679
1680         if (xprt->shutdown)
1681                 goto out;
1682
1683         /* Start by resetting any existing state */
1684         xs_reset_transport(transport);
1685
1686         err = sock_create_kern(PF_INET6, SOCK_DGRAM, IPPROTO_UDP, &sock);
1687         if (err < 0) {
1688                 dprintk("RPC:       can't create UDP transport socket (%d).\n", -err);
1689                 goto out;
1690         }
1691         xs_reclassify_socket6(sock);
1692
1693         if (xs_bind6(transport, sock) < 0) {
1694                 sock_release(sock);
1695                 goto out;
1696         }
1697
1698         dprintk("RPC:       worker connecting xprt %p to address: %s\n",
1699                         xprt, xprt->address_strings[RPC_DISPLAY_ALL]);
1700
1701         xs_udp_finish_connecting(xprt, sock);
1702         status = 0;
1703 out:
1704         xprt_clear_connecting(xprt);
1705         xprt_wake_pending_tasks(xprt, status);
1706 }
1707
1708 /*
1709  * We need to preserve the port number so the reply cache on the server can
1710  * find our cached RPC replies when we get around to reconnecting.
1711  */
1712 static void xs_abort_connection(struct rpc_xprt *xprt, struct sock_xprt *transport)
1713 {
1714         int result;
1715         struct sockaddr any;
1716
1717         dprintk("RPC:       disconnecting xprt %p to reuse port\n", xprt);
1718
1719         /*
1720          * Disconnect the transport socket by doing a connect operation
1721          * with AF_UNSPEC.  This should return immediately...
1722          */
1723         memset(&any, 0, sizeof(any));
1724         any.sa_family = AF_UNSPEC;
1725         result = kernel_connect(transport->sock, &any, sizeof(any), 0);
1726         if (!result)
1727                 xs_sock_mark_closed(xprt);
1728         else
1729                 dprintk("RPC:       AF_UNSPEC connect return code %d\n",
1730                                 result);
1731 }
1732
1733 static void xs_tcp_reuse_connection(struct rpc_xprt *xprt, struct sock_xprt *transport)
1734 {
1735         unsigned int state = transport->inet->sk_state;
1736
1737         if (state == TCP_CLOSE && transport->sock->state == SS_UNCONNECTED)
1738                 return;
1739         if ((1 << state) & (TCPF_ESTABLISHED|TCPF_SYN_SENT))
1740                 return;
1741         xs_abort_connection(xprt, transport);
1742 }
1743
1744 static int xs_tcp_finish_connecting(struct rpc_xprt *xprt, struct socket *sock)
1745 {
1746         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1747
1748         if (!transport->inet) {
1749                 struct sock *sk = sock->sk;
1750
1751                 write_lock_bh(&sk->sk_callback_lock);
1752
1753                 xs_save_old_callbacks(transport, sk);
1754
1755                 sk->sk_user_data = xprt;
1756                 sk->sk_data_ready = xs_tcp_data_ready;
1757                 sk->sk_state_change = xs_tcp_state_change;
1758                 sk->sk_write_space = xs_tcp_write_space;
1759                 sk->sk_error_report = xs_error_report;
1760                 sk->sk_allocation = GFP_ATOMIC;
1761
1762                 /* socket options */
1763                 sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
1764                 sock_reset_flag(sk, SOCK_LINGER);
1765                 tcp_sk(sk)->linger2 = 0;
1766                 tcp_sk(sk)->nonagle |= TCP_NAGLE_OFF;
1767
1768                 xprt_clear_connected(xprt);
1769
1770                 /* Reset to new socket */
1771                 transport->sock = sock;
1772                 transport->inet = sk;
1773
1774                 write_unlock_bh(&sk->sk_callback_lock);
1775         }
1776
1777         if (!xprt_bound(xprt))
1778                 return -ENOTCONN;
1779
1780         /* Tell the socket layer to start connecting... */
1781         xprt->stat.connect_count++;
1782         xprt->stat.connect_start = jiffies;
1783         return kernel_connect(sock, xs_addr(xprt), xprt->addrlen, O_NONBLOCK);
1784 }
1785
1786 /**
1787  * xs_tcp_setup_socket - create a TCP socket and connect to a remote endpoint
1788  * @xprt: RPC transport to connect
1789  * @transport: socket transport to connect
1790  * @create_sock: function to create a socket of the correct type
1791  *
1792  * Invoked by a work queue tasklet.
1793  */
1794 static void xs_tcp_setup_socket(struct rpc_xprt *xprt,
1795                 struct sock_xprt *transport,
1796                 struct socket *(*create_sock)(struct rpc_xprt *,
1797                         struct sock_xprt *))
1798 {
1799         struct socket *sock = transport->sock;
1800         int status = -EIO;
1801
1802         if (xprt->shutdown)
1803                 goto out;
1804
1805         if (!sock) {
1806                 clear_bit(XPRT_CONNECTION_ABORT, &xprt->state);
1807                 sock = create_sock(xprt, transport);
1808                 if (IS_ERR(sock)) {
1809                         status = PTR_ERR(sock);
1810                         goto out;
1811                 }
1812         } else {
1813                 int abort_and_exit;
1814
1815                 abort_and_exit = test_and_clear_bit(XPRT_CONNECTION_ABORT,
1816                                 &xprt->state);
1817                 /* "close" the socket, preserving the local port */
1818                 xs_tcp_reuse_connection(xprt, transport);
1819
1820                 if (abort_and_exit)
1821                         goto out_eagain;
1822         }
1823
1824         dprintk("RPC:       worker connecting xprt %p to address: %s\n",
1825                         xprt, xprt->address_strings[RPC_DISPLAY_ALL]);
1826
1827         status = xs_tcp_finish_connecting(xprt, sock);
1828         dprintk("RPC:       %p connect status %d connected %d sock state %d\n",
1829                         xprt, -status, xprt_connected(xprt),
1830                         sock->sk->sk_state);
1831         switch (status) {
1832         default:
1833                 printk("%s: connect returned unhandled error %d\n",
1834                         __func__, status);
1835         case -EADDRNOTAVAIL:
1836                 /* We're probably in TIME_WAIT. Get rid of existing socket,
1837                  * and retry
1838                  */
1839                 set_bit(XPRT_CONNECTION_CLOSE, &xprt->state);
1840                 xprt_force_disconnect(xprt);
1841         case -ECONNREFUSED:
1842         case -ECONNRESET:
1843         case -ENETUNREACH:
1844                 /* retry with existing socket, after a delay */
1845         case 0:
1846         case -EINPROGRESS:
1847         case -EALREADY:
1848                 xprt_clear_connecting(xprt);
1849                 return;
1850         }
1851 out_eagain:
1852         status = -EAGAIN;
1853 out:
1854         xprt_clear_connecting(xprt);
1855         xprt_wake_pending_tasks(xprt, status);
1856 }
1857
1858 static struct socket *xs_create_tcp_sock4(struct rpc_xprt *xprt,
1859                 struct sock_xprt *transport)
1860 {
1861         struct socket *sock;
1862         int err;
1863
1864         /* start from scratch */
1865         err = sock_create_kern(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock);
1866         if (err < 0) {
1867                 dprintk("RPC:       can't create TCP transport socket (%d).\n",
1868                                 -err);
1869                 goto out_err;
1870         }
1871         xs_reclassify_socket4(sock);
1872
1873         if (xs_bind4(transport, sock) < 0) {
1874                 sock_release(sock);
1875                 goto out_err;
1876         }
1877         return sock;
1878 out_err:
1879         return ERR_PTR(-EIO);
1880 }
1881
1882 /**
1883  * xs_tcp_connect_worker4 - connect a TCP socket to a remote endpoint
1884  * @work: RPC transport to connect
1885  *
1886  * Invoked by a work queue tasklet.
1887  */
1888 static void xs_tcp_connect_worker4(struct work_struct *work)
1889 {
1890         struct sock_xprt *transport =
1891                 container_of(work, struct sock_xprt, connect_worker.work);
1892         struct rpc_xprt *xprt = &transport->xprt;
1893
1894         xs_tcp_setup_socket(xprt, transport, xs_create_tcp_sock4);
1895 }
1896
1897 static struct socket *xs_create_tcp_sock6(struct rpc_xprt *xprt,
1898                 struct sock_xprt *transport)
1899 {
1900         struct socket *sock;
1901         int err;
1902
1903         /* start from scratch */
1904         err = sock_create_kern(PF_INET6, SOCK_STREAM, IPPROTO_TCP, &sock);
1905         if (err < 0) {
1906                 dprintk("RPC:       can't create TCP transport socket (%d).\n",
1907                                 -err);
1908                 goto out_err;
1909         }
1910         xs_reclassify_socket6(sock);
1911
1912         if (xs_bind6(transport, sock) < 0) {
1913                 sock_release(sock);
1914                 goto out_err;
1915         }
1916         return sock;
1917 out_err:
1918         return ERR_PTR(-EIO);
1919 }
1920
1921 /**
1922  * xs_tcp_connect_worker6 - connect a TCP socket to a remote endpoint
1923  * @work: RPC transport to connect
1924  *
1925  * Invoked by a work queue tasklet.
1926  */
1927 static void xs_tcp_connect_worker6(struct work_struct *work)
1928 {
1929         struct sock_xprt *transport =
1930                 container_of(work, struct sock_xprt, connect_worker.work);
1931         struct rpc_xprt *xprt = &transport->xprt;
1932
1933         xs_tcp_setup_socket(xprt, transport, xs_create_tcp_sock6);
1934 }
1935
1936 /**
1937  * xs_connect - connect a socket to a remote endpoint
1938  * @task: address of RPC task that manages state of connect request
1939  *
1940  * TCP: If the remote end dropped the connection, delay reconnecting.
1941  *
1942  * UDP socket connects are synchronous, but we use a work queue anyway
1943  * to guarantee that even unprivileged user processes can set up a
1944  * socket on a privileged port.
1945  *
1946  * If a UDP socket connect fails, the delay behavior here prevents
1947  * retry floods (hard mounts).
1948  */
1949 static void xs_connect(struct rpc_task *task)
1950 {
1951         struct rpc_xprt *xprt = task->tk_xprt;
1952         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1953
1954         if (xprt_test_and_set_connecting(xprt))
1955                 return;
1956
1957         if (transport->sock != NULL) {
1958                 dprintk("RPC:       xs_connect delayed xprt %p for %lu "
1959                                 "seconds\n",
1960                                 xprt, xprt->reestablish_timeout / HZ);
1961                 queue_delayed_work(rpciod_workqueue,
1962                                    &transport->connect_worker,
1963                                    xprt->reestablish_timeout);
1964                 xprt->reestablish_timeout <<= 1;
1965                 if (xprt->reestablish_timeout > XS_TCP_MAX_REEST_TO)
1966                         xprt->reestablish_timeout = XS_TCP_MAX_REEST_TO;
1967         } else {
1968                 dprintk("RPC:       xs_connect scheduled xprt %p\n", xprt);
1969                 queue_delayed_work(rpciod_workqueue,
1970                                    &transport->connect_worker, 0);
1971         }
1972 }
1973
1974 static void xs_tcp_connect(struct rpc_task *task)
1975 {
1976         struct rpc_xprt *xprt = task->tk_xprt;
1977
1978         /* Exit if we need to wait for socket shutdown to complete */
1979         if (test_bit(XPRT_CLOSING, &xprt->state))
1980                 return;
1981         xs_connect(task);
1982 }
1983
1984 /**
1985  * xs_udp_print_stats - display UDP socket-specifc stats
1986  * @xprt: rpc_xprt struct containing statistics
1987  * @seq: output file
1988  *
1989  */
1990 static void xs_udp_print_stats(struct rpc_xprt *xprt, struct seq_file *seq)
1991 {
1992         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1993
1994         seq_printf(seq, "\txprt:\tudp %u %lu %lu %lu %lu %Lu %Lu\n",
1995                         transport->port,
1996                         xprt->stat.bind_count,
1997                         xprt->stat.sends,
1998                         xprt->stat.recvs,
1999                         xprt->stat.bad_xids,
2000                         xprt->stat.req_u,
2001                         xprt->stat.bklog_u);
2002 }
2003
2004 /**
2005  * xs_tcp_print_stats - display TCP socket-specifc stats
2006  * @xprt: rpc_xprt struct containing statistics
2007  * @seq: output file
2008  *
2009  */
2010 static void xs_tcp_print_stats(struct rpc_xprt *xprt, struct seq_file *seq)
2011 {
2012         struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
2013         long idle_time = 0;
2014
2015         if (xprt_connected(xprt))
2016                 idle_time = (long)(jiffies - xprt->last_used) / HZ;
2017
2018         seq_printf(seq, "\txprt:\ttcp %u %lu %lu %lu %ld %lu %lu %lu %Lu %Lu\n",
2019                         transport->port,
2020                         xprt->stat.bind_count,
2021                         xprt->stat.connect_count,
2022                         xprt->stat.connect_time,
2023                         idle_time,
2024                         xprt->stat.sends,
2025                         xprt->stat.recvs,
2026                         xprt->stat.bad_xids,
2027                         xprt->stat.req_u,
2028                         xprt->stat.bklog_u);
2029 }
2030
2031 static struct rpc_xprt_ops xs_udp_ops = {
2032         .set_buffer_size        = xs_udp_set_buffer_size,
2033         .reserve_xprt           = xprt_reserve_xprt_cong,
2034         .release_xprt           = xprt_release_xprt_cong,
2035         .rpcbind                = rpcb_getport_async,
2036         .set_port               = xs_set_port,
2037         .connect                = xs_connect,
2038         .buf_alloc              = rpc_malloc,
2039         .buf_free               = rpc_free,
2040         .send_request           = xs_udp_send_request,
2041         .set_retrans_timeout    = xprt_set_retrans_timeout_rtt,
2042         .timer                  = xs_udp_timer,
2043         .release_request        = xprt_release_rqst_cong,
2044         .close                  = xs_close,
2045         .destroy                = xs_destroy,
2046         .print_stats            = xs_udp_print_stats,
2047 };
2048
2049 static struct rpc_xprt_ops xs_tcp_ops = {
2050         .reserve_xprt           = xprt_reserve_xprt,
2051         .release_xprt           = xs_tcp_release_xprt,
2052         .rpcbind                = rpcb_getport_async,
2053         .set_port               = xs_set_port,
2054         .connect                = xs_tcp_connect,
2055         .buf_alloc              = rpc_malloc,
2056         .buf_free               = rpc_free,
2057         .send_request           = xs_tcp_send_request,
2058         .set_retrans_timeout    = xprt_set_retrans_timeout_def,
2059         .close                  = xs_tcp_close,
2060         .destroy                = xs_destroy,
2061         .print_stats            = xs_tcp_print_stats,
2062 };
2063
2064 static struct rpc_xprt *xs_setup_xprt(struct xprt_create *args,
2065                                       unsigned int slot_table_size)
2066 {
2067         struct rpc_xprt *xprt;
2068         struct sock_xprt *new;
2069
2070         if (args->addrlen > sizeof(xprt->addr)) {
2071                 dprintk("RPC:       xs_setup_xprt: address too large\n");
2072                 return ERR_PTR(-EBADF);
2073         }
2074
2075         new = kzalloc(sizeof(*new), GFP_KERNEL);
2076         if (new == NULL) {
2077                 dprintk("RPC:       xs_setup_xprt: couldn't allocate "
2078                                 "rpc_xprt\n");
2079                 return ERR_PTR(-ENOMEM);
2080         }
2081         xprt = &new->xprt;
2082
2083         xprt->max_reqs = slot_table_size;
2084         xprt->slot = kcalloc(xprt->max_reqs, sizeof(struct rpc_rqst), GFP_KERNEL);
2085         if (xprt->slot == NULL) {
2086                 kfree(xprt);
2087                 dprintk("RPC:       xs_setup_xprt: couldn't allocate slot "
2088                                 "table\n");
2089                 return ERR_PTR(-ENOMEM);
2090         }
2091
2092         memcpy(&xprt->addr, args->dstaddr, args->addrlen);
2093         xprt->addrlen = args->addrlen;
2094         if (args->srcaddr)
2095                 memcpy(&new->addr, args->srcaddr, args->addrlen);
2096
2097         return xprt;
2098 }
2099
2100 static const struct rpc_timeout xs_udp_default_timeout = {
2101         .to_initval = 5 * HZ,
2102         .to_maxval = 30 * HZ,
2103         .to_increment = 5 * HZ,
2104         .to_retries = 5,
2105 };
2106
2107 /**
2108  * xs_setup_udp - Set up transport to use a UDP socket
2109  * @args: rpc transport creation arguments
2110  *
2111  */
2112 static struct rpc_xprt *xs_setup_udp(struct xprt_create *args)
2113 {
2114         struct sockaddr *addr = args->dstaddr;
2115         struct rpc_xprt *xprt;
2116         struct sock_xprt *transport;
2117
2118         xprt = xs_setup_xprt(args, xprt_udp_slot_table_entries);
2119         if (IS_ERR(xprt))
2120                 return xprt;
2121         transport = container_of(xprt, struct sock_xprt, xprt);
2122
2123         xprt->prot = IPPROTO_UDP;
2124         xprt->tsh_size = 0;
2125         /* XXX: header size can vary due to auth type, IPv6, etc. */
2126         xprt->max_payload = (1U << 16) - (MAX_HEADER << 3);
2127
2128         xprt->bind_timeout = XS_BIND_TO;
2129         xprt->connect_timeout = XS_UDP_CONN_TO;
2130         xprt->reestablish_timeout = XS_UDP_REEST_TO;
2131         xprt->idle_timeout = XS_IDLE_DISC_TO;
2132
2133         xprt->ops = &xs_udp_ops;
2134
2135         xprt->timeout = &xs_udp_default_timeout;
2136
2137         switch (addr->sa_family) {
2138         case AF_INET:
2139                 if (((struct sockaddr_in *)addr)->sin_port != htons(0))
2140                         xprt_set_bound(xprt);
2141
2142                 INIT_DELAYED_WORK(&transport->connect_worker,
2143                                         xs_udp_connect_worker4);
2144                 xs_format_ipv4_peer_addresses(xprt, "udp", RPCBIND_NETID_UDP);
2145                 break;
2146         case AF_INET6:
2147                 if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
2148                         xprt_set_bound(xprt);
2149
2150                 INIT_DELAYED_WORK(&transport->connect_worker,
2151                                         xs_udp_connect_worker6);
2152                 xs_format_ipv6_peer_addresses(xprt, "udp", RPCBIND_NETID_UDP6);
2153                 break;
2154         default:
2155                 kfree(xprt);
2156                 return ERR_PTR(-EAFNOSUPPORT);
2157         }
2158
2159         dprintk("RPC:       set up transport to address %s\n",
2160                         xprt->address_strings[RPC_DISPLAY_ALL]);
2161
2162         if (try_module_get(THIS_MODULE))
2163                 return xprt;
2164
2165         kfree(xprt->slot);
2166         kfree(xprt);
2167         return ERR_PTR(-EINVAL);
2168 }
2169
2170 static const struct rpc_timeout xs_tcp_default_timeout = {
2171         .to_initval = 60 * HZ,
2172         .to_maxval = 60 * HZ,
2173         .to_retries = 2,
2174 };
2175
2176 /**
2177  * xs_setup_tcp - Set up transport to use a TCP socket
2178  * @args: rpc transport creation arguments
2179  *
2180  */
2181 static struct rpc_xprt *xs_setup_tcp(struct xprt_create *args)
2182 {
2183         struct sockaddr *addr = args->dstaddr;
2184         struct rpc_xprt *xprt;
2185         struct sock_xprt *transport;
2186
2187         xprt = xs_setup_xprt(args, xprt_tcp_slot_table_entries);
2188         if (IS_ERR(xprt))
2189                 return xprt;
2190         transport = container_of(xprt, struct sock_xprt, xprt);
2191
2192         xprt->prot = IPPROTO_TCP;
2193         xprt->tsh_size = sizeof(rpc_fraghdr) / sizeof(u32);
2194         xprt->max_payload = RPC_MAX_FRAGMENT_SIZE;
2195
2196         xprt->bind_timeout = XS_BIND_TO;
2197         xprt->connect_timeout = XS_TCP_CONN_TO;
2198         xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
2199         xprt->idle_timeout = XS_IDLE_DISC_TO;
2200
2201         xprt->ops = &xs_tcp_ops;
2202         xprt->timeout = &xs_tcp_default_timeout;
2203
2204         switch (addr->sa_family) {
2205         case AF_INET:
2206                 if (((struct sockaddr_in *)addr)->sin_port != htons(0))
2207                         xprt_set_bound(xprt);
2208
2209                 INIT_DELAYED_WORK(&transport->connect_worker, xs_tcp_connect_worker4);
2210                 xs_format_ipv4_peer_addresses(xprt, "tcp", RPCBIND_NETID_TCP);
2211                 break;
2212         case AF_INET6:
2213                 if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
2214                         xprt_set_bound(xprt);
2215
2216                 INIT_DELAYED_WORK(&transport->connect_worker, xs_tcp_connect_worker6);
2217                 xs_format_ipv6_peer_addresses(xprt, "tcp", RPCBIND_NETID_TCP6);
2218                 break;
2219         default:
2220                 kfree(xprt);
2221                 return ERR_PTR(-EAFNOSUPPORT);
2222         }
2223
2224         dprintk("RPC:       set up transport to address %s\n",
2225                         xprt->address_strings[RPC_DISPLAY_ALL]);
2226
2227         if (try_module_get(THIS_MODULE))
2228                 return xprt;
2229
2230         kfree(xprt->slot);
2231         kfree(xprt);
2232         return ERR_PTR(-EINVAL);
2233 }
2234
2235 static struct xprt_class        xs_udp_transport = {
2236         .list           = LIST_HEAD_INIT(xs_udp_transport.list),
2237         .name           = "udp",
2238         .owner          = THIS_MODULE,
2239         .ident          = IPPROTO_UDP,
2240         .setup          = xs_setup_udp,
2241 };
2242
2243 static struct xprt_class        xs_tcp_transport = {
2244         .list           = LIST_HEAD_INIT(xs_tcp_transport.list),
2245         .name           = "tcp",
2246         .owner          = THIS_MODULE,
2247         .ident          = IPPROTO_TCP,
2248         .setup          = xs_setup_tcp,
2249 };
2250
2251 /**
2252  * init_socket_xprt - set up xprtsock's sysctls, register with RPC client
2253  *
2254  */
2255 int init_socket_xprt(void)
2256 {
2257 #ifdef RPC_DEBUG
2258         if (!sunrpc_table_header)
2259                 sunrpc_table_header = register_sysctl_table(sunrpc_table);
2260 #endif
2261
2262         xprt_register_transport(&xs_udp_transport);
2263         xprt_register_transport(&xs_tcp_transport);
2264
2265         return 0;
2266 }
2267
2268 /**
2269  * cleanup_socket_xprt - remove xprtsock's sysctls, unregister
2270  *
2271  */
2272 void cleanup_socket_xprt(void)
2273 {
2274 #ifdef RPC_DEBUG
2275         if (sunrpc_table_header) {
2276                 unregister_sysctl_table(sunrpc_table_header);
2277                 sunrpc_table_header = NULL;
2278         }
2279 #endif
2280
2281         xprt_unregister_transport(&xs_udp_transport);
2282         xprt_unregister_transport(&xs_tcp_transport);
2283 }