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