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