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