xref: /linux/net/sunrpc/xprtsock.c (revision baf67f6aa9d29512809f1b1fbab624fce57fd16d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * linux/net/sunrpc/xprtsock.c
4  *
5  * Client-side transport implementation for sockets.
6  *
7  * TCP callback races fixes (C) 1998 Red Hat
8  * TCP send fixes (C) 1998 Red Hat
9  * TCP NFS related read + write fixes
10  *  (C) 1999 Dave Airlie, University of Limerick, Ireland <airlied@linux.ie>
11  *
12  * Rewrite of larges part of the code in order to stabilize TCP stuff.
13  * Fix behaviour when socket buffer is full.
14  *  (C) 1999 Trond Myklebust <trond.myklebust@fys.uio.no>
15  *
16  * IP socket transport implementation, (C) 2005 Chuck Lever <cel@netapp.com>
17  *
18  * IPv6 support contributed by Gilles Quillard, Bull Open Source, 2005.
19  *   <gilles.quillard@bull.net>
20  */
21 
22 #include <linux/types.h>
23 #include <linux/string.h>
24 #include <linux/slab.h>
25 #include <linux/module.h>
26 #include <linux/capability.h>
27 #include <linux/pagemap.h>
28 #include <linux/errno.h>
29 #include <linux/socket.h>
30 #include <linux/in.h>
31 #include <linux/net.h>
32 #include <linux/mm.h>
33 #include <linux/un.h>
34 #include <linux/udp.h>
35 #include <linux/tcp.h>
36 #include <linux/sunrpc/clnt.h>
37 #include <linux/sunrpc/addr.h>
38 #include <linux/sunrpc/sched.h>
39 #include <linux/sunrpc/svcsock.h>
40 #include <linux/sunrpc/xprtsock.h>
41 #include <linux/file.h>
42 #ifdef CONFIG_SUNRPC_BACKCHANNEL
43 #include <linux/sunrpc/bc_xprt.h>
44 #endif
45 
46 #include <net/sock.h>
47 #include <net/checksum.h>
48 #include <net/udp.h>
49 #include <net/tcp.h>
50 #include <net/tls_prot.h>
51 #include <net/handshake.h>
52 
53 #include <linux/bvec.h>
54 #include <linux/highmem.h>
55 #include <linux/uio.h>
56 #include <linux/sched/mm.h>
57 
58 #include <trace/events/sock.h>
59 #include <trace/events/sunrpc.h>
60 
61 #include "socklib.h"
62 #include "sunrpc.h"
63 
64 static void xs_close(struct rpc_xprt *xprt);
65 static void xs_reset_srcport(struct sock_xprt *transport);
66 static void xs_set_srcport(struct sock_xprt *transport, struct socket *sock);
67 static void xs_tcp_set_socket_timeouts(struct rpc_xprt *xprt,
68 		struct socket *sock);
69 
70 /*
71  * xprtsock tunables
72  */
73 static unsigned int xprt_udp_slot_table_entries = RPC_DEF_SLOT_TABLE;
74 static unsigned int xprt_tcp_slot_table_entries = RPC_MIN_SLOT_TABLE;
75 static unsigned int xprt_max_tcp_slot_table_entries = RPC_MAX_SLOT_TABLE;
76 
77 static unsigned int xprt_min_resvport = RPC_DEF_MIN_RESVPORT;
78 static unsigned int xprt_max_resvport = RPC_DEF_MAX_RESVPORT;
79 
80 #define XS_TCP_LINGER_TO	(15U * HZ)
81 static unsigned int xs_tcp_fin_timeout __read_mostly = XS_TCP_LINGER_TO;
82 
83 /*
84  * We can register our own files under /proc/sys/sunrpc by
85  * calling register_sysctl() again.  The files in that
86  * directory become the union of all files registered there.
87  *
88  * We simply need to make sure that we don't collide with
89  * someone else's file names!
90  */
91 
92 static unsigned int min_slot_table_size = RPC_MIN_SLOT_TABLE;
93 static unsigned int max_slot_table_size = RPC_MAX_SLOT_TABLE;
94 static unsigned int max_tcp_slot_table_limit = RPC_MAX_SLOT_TABLE_LIMIT;
95 static unsigned int xprt_min_resvport_limit = RPC_MIN_RESVPORT;
96 static unsigned int xprt_max_resvport_limit = RPC_MAX_RESVPORT;
97 
98 static struct ctl_table_header *sunrpc_table_header;
99 
100 static struct xprt_class xs_local_transport;
101 static struct xprt_class xs_udp_transport;
102 static struct xprt_class xs_tcp_transport;
103 static struct xprt_class xs_tcp_tls_transport;
104 static struct xprt_class xs_bc_tcp_transport;
105 
106 /*
107  * FIXME: changing the UDP slot table size should also resize the UDP
108  *        socket buffers for existing UDP transports
109  */
110 static struct ctl_table xs_tunables_table[] = {
111 	{
112 		.procname	= "udp_slot_table_entries",
113 		.data		= &xprt_udp_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_slot_table_size
119 	},
120 	{
121 		.procname	= "tcp_slot_table_entries",
122 		.data		= &xprt_tcp_slot_table_entries,
123 		.maxlen		= sizeof(unsigned int),
124 		.mode		= 0644,
125 		.proc_handler	= proc_dointvec_minmax,
126 		.extra1		= &min_slot_table_size,
127 		.extra2		= &max_slot_table_size
128 	},
129 	{
130 		.procname	= "tcp_max_slot_table_entries",
131 		.data		= &xprt_max_tcp_slot_table_entries,
132 		.maxlen		= sizeof(unsigned int),
133 		.mode		= 0644,
134 		.proc_handler	= proc_dointvec_minmax,
135 		.extra1		= &min_slot_table_size,
136 		.extra2		= &max_tcp_slot_table_limit
137 	},
138 	{
139 		.procname	= "min_resvport",
140 		.data		= &xprt_min_resvport,
141 		.maxlen		= sizeof(unsigned int),
142 		.mode		= 0644,
143 		.proc_handler	= proc_dointvec_minmax,
144 		.extra1		= &xprt_min_resvport_limit,
145 		.extra2		= &xprt_max_resvport_limit
146 	},
147 	{
148 		.procname	= "max_resvport",
149 		.data		= &xprt_max_resvport,
150 		.maxlen		= sizeof(unsigned int),
151 		.mode		= 0644,
152 		.proc_handler	= proc_dointvec_minmax,
153 		.extra1		= &xprt_min_resvport_limit,
154 		.extra2		= &xprt_max_resvport_limit
155 	},
156 	{
157 		.procname	= "tcp_fin_timeout",
158 		.data		= &xs_tcp_fin_timeout,
159 		.maxlen		= sizeof(xs_tcp_fin_timeout),
160 		.mode		= 0644,
161 		.proc_handler	= proc_dointvec_jiffies,
162 	},
163 };
164 
165 /*
166  * Wait duration for a reply from the RPC portmapper.
167  */
168 #define XS_BIND_TO		(60U * HZ)
169 
170 /*
171  * Delay if a UDP socket connect error occurs.  This is most likely some
172  * kind of resource problem on the local host.
173  */
174 #define XS_UDP_REEST_TO		(2U * HZ)
175 
176 /*
177  * The reestablish timeout allows clients to delay for a bit before attempting
178  * to reconnect to a server that just dropped our connection.
179  *
180  * We implement an exponential backoff when trying to reestablish a TCP
181  * transport connection with the server.  Some servers like to drop a TCP
182  * connection when they are overworked, so we start with a short timeout and
183  * increase over time if the server is down or not responding.
184  */
185 #define XS_TCP_INIT_REEST_TO	(3U * HZ)
186 
187 /*
188  * TCP idle timeout; client drops the transport socket if it is idle
189  * for this long.  Note that we also timeout UDP sockets to prevent
190  * holding port numbers when there is no RPC traffic.
191  */
192 #define XS_IDLE_DISC_TO		(5U * 60 * HZ)
193 
194 /*
195  * TLS handshake timeout.
196  */
197 #define XS_TLS_HANDSHAKE_TO	(10U * HZ)
198 
199 #if IS_ENABLED(CONFIG_SUNRPC_DEBUG)
200 # undef  RPC_DEBUG_DATA
201 # define RPCDBG_FACILITY	RPCDBG_TRANS
202 #endif
203 
204 #ifdef RPC_DEBUG_DATA
xs_pktdump(char * msg,u32 * packet,unsigned int count)205 static void xs_pktdump(char *msg, u32 *packet, unsigned int count)
206 {
207 	u8 *buf = (u8 *) packet;
208 	int j;
209 
210 	dprintk("RPC:       %s\n", msg);
211 	for (j = 0; j < count && j < 128; j += 4) {
212 		if (!(j & 31)) {
213 			if (j)
214 				dprintk("\n");
215 			dprintk("0x%04x ", j);
216 		}
217 		dprintk("%02x%02x%02x%02x ",
218 			buf[j], buf[j+1], buf[j+2], buf[j+3]);
219 	}
220 	dprintk("\n");
221 }
222 #else
xs_pktdump(char * msg,u32 * packet,unsigned int count)223 static inline void xs_pktdump(char *msg, u32 *packet, unsigned int count)
224 {
225 	/* NOP */
226 }
227 #endif
228 
xprt_from_sock(struct sock * sk)229 static inline struct rpc_xprt *xprt_from_sock(struct sock *sk)
230 {
231 	return (struct rpc_xprt *) sk->sk_user_data;
232 }
233 
xs_addr(struct rpc_xprt * xprt)234 static inline struct sockaddr *xs_addr(struct rpc_xprt *xprt)
235 {
236 	return (struct sockaddr *) &xprt->addr;
237 }
238 
xs_addr_un(struct rpc_xprt * xprt)239 static inline struct sockaddr_un *xs_addr_un(struct rpc_xprt *xprt)
240 {
241 	return (struct sockaddr_un *) &xprt->addr;
242 }
243 
xs_addr_in(struct rpc_xprt * xprt)244 static inline struct sockaddr_in *xs_addr_in(struct rpc_xprt *xprt)
245 {
246 	return (struct sockaddr_in *) &xprt->addr;
247 }
248 
xs_addr_in6(struct rpc_xprt * xprt)249 static inline struct sockaddr_in6 *xs_addr_in6(struct rpc_xprt *xprt)
250 {
251 	return (struct sockaddr_in6 *) &xprt->addr;
252 }
253 
xs_format_common_peer_addresses(struct rpc_xprt * xprt)254 static void xs_format_common_peer_addresses(struct rpc_xprt *xprt)
255 {
256 	struct sockaddr *sap = xs_addr(xprt);
257 	struct sockaddr_in6 *sin6;
258 	struct sockaddr_in *sin;
259 	struct sockaddr_un *sun;
260 	char buf[128];
261 
262 	switch (sap->sa_family) {
263 	case AF_LOCAL:
264 		sun = xs_addr_un(xprt);
265 		if (sun->sun_path[0]) {
266 			strscpy(buf, sun->sun_path, sizeof(buf));
267 		} else {
268 			buf[0] = '@';
269 			strscpy(buf+1, sun->sun_path+1, sizeof(buf)-1);
270 		}
271 		xprt->address_strings[RPC_DISPLAY_ADDR] =
272 						kstrdup(buf, GFP_KERNEL);
273 		break;
274 	case AF_INET:
275 		(void)rpc_ntop(sap, buf, sizeof(buf));
276 		xprt->address_strings[RPC_DISPLAY_ADDR] =
277 						kstrdup(buf, GFP_KERNEL);
278 		sin = xs_addr_in(xprt);
279 		snprintf(buf, sizeof(buf), "%08x", ntohl(sin->sin_addr.s_addr));
280 		break;
281 	case AF_INET6:
282 		(void)rpc_ntop(sap, buf, sizeof(buf));
283 		xprt->address_strings[RPC_DISPLAY_ADDR] =
284 						kstrdup(buf, GFP_KERNEL);
285 		sin6 = xs_addr_in6(xprt);
286 		snprintf(buf, sizeof(buf), "%pi6", &sin6->sin6_addr);
287 		break;
288 	default:
289 		BUG();
290 	}
291 
292 	xprt->address_strings[RPC_DISPLAY_HEX_ADDR] = kstrdup(buf, GFP_KERNEL);
293 }
294 
xs_format_common_peer_ports(struct rpc_xprt * xprt)295 static void xs_format_common_peer_ports(struct rpc_xprt *xprt)
296 {
297 	struct sockaddr *sap = xs_addr(xprt);
298 	char buf[128];
299 
300 	snprintf(buf, sizeof(buf), "%u", rpc_get_port(sap));
301 	xprt->address_strings[RPC_DISPLAY_PORT] = kstrdup(buf, GFP_KERNEL);
302 
303 	snprintf(buf, sizeof(buf), "%4hx", rpc_get_port(sap));
304 	xprt->address_strings[RPC_DISPLAY_HEX_PORT] = kstrdup(buf, GFP_KERNEL);
305 }
306 
xs_format_peer_addresses(struct rpc_xprt * xprt,const char * protocol,const char * netid)307 static void xs_format_peer_addresses(struct rpc_xprt *xprt,
308 				     const char *protocol,
309 				     const char *netid)
310 {
311 	xprt->address_strings[RPC_DISPLAY_PROTO] = protocol;
312 	xprt->address_strings[RPC_DISPLAY_NETID] = netid;
313 	xs_format_common_peer_addresses(xprt);
314 	xs_format_common_peer_ports(xprt);
315 }
316 
xs_update_peer_port(struct rpc_xprt * xprt)317 static void xs_update_peer_port(struct rpc_xprt *xprt)
318 {
319 	kfree(xprt->address_strings[RPC_DISPLAY_HEX_PORT]);
320 	kfree(xprt->address_strings[RPC_DISPLAY_PORT]);
321 
322 	xs_format_common_peer_ports(xprt);
323 }
324 
xs_free_peer_addresses(struct rpc_xprt * xprt)325 static void xs_free_peer_addresses(struct rpc_xprt *xprt)
326 {
327 	unsigned int i;
328 
329 	for (i = 0; i < RPC_DISPLAY_MAX; i++)
330 		switch (i) {
331 		case RPC_DISPLAY_PROTO:
332 		case RPC_DISPLAY_NETID:
333 			continue;
334 		default:
335 			kfree(xprt->address_strings[i]);
336 		}
337 }
338 
339 static size_t
xs_alloc_sparse_pages(struct xdr_buf * buf,size_t want,gfp_t gfp)340 xs_alloc_sparse_pages(struct xdr_buf *buf, size_t want, gfp_t gfp)
341 {
342 	size_t i,n;
343 
344 	if (!want || !(buf->flags & XDRBUF_SPARSE_PAGES))
345 		return want;
346 	n = (buf->page_base + want + PAGE_SIZE - 1) >> PAGE_SHIFT;
347 	for (i = 0; i < n; i++) {
348 		if (buf->pages[i])
349 			continue;
350 		buf->bvec[i].bv_page = buf->pages[i] = alloc_page(gfp);
351 		if (!buf->pages[i]) {
352 			i *= PAGE_SIZE;
353 			return i > buf->page_base ? i - buf->page_base : 0;
354 		}
355 	}
356 	return want;
357 }
358 
359 static int
xs_sock_process_cmsg(struct socket * sock,struct msghdr * msg,struct cmsghdr * cmsg,int ret)360 xs_sock_process_cmsg(struct socket *sock, struct msghdr *msg,
361 		     struct cmsghdr *cmsg, int ret)
362 {
363 	u8 content_type = tls_get_record_type(sock->sk, cmsg);
364 	u8 level, description;
365 
366 	switch (content_type) {
367 	case 0:
368 		break;
369 	case TLS_RECORD_TYPE_DATA:
370 		/* TLS sets EOR at the end of each application data
371 		 * record, even though there might be more frames
372 		 * waiting to be decrypted.
373 		 */
374 		msg->msg_flags &= ~MSG_EOR;
375 		break;
376 	case TLS_RECORD_TYPE_ALERT:
377 		tls_alert_recv(sock->sk, msg, &level, &description);
378 		ret = (level == TLS_ALERT_LEVEL_FATAL) ?
379 			-EACCES : -EAGAIN;
380 		break;
381 	default:
382 		/* discard this record type */
383 		ret = -EAGAIN;
384 	}
385 	return ret;
386 }
387 
388 static int
xs_sock_recv_cmsg(struct socket * sock,struct msghdr * msg,int flags)389 xs_sock_recv_cmsg(struct socket *sock, struct msghdr *msg, int flags)
390 {
391 	union {
392 		struct cmsghdr	cmsg;
393 		u8		buf[CMSG_SPACE(sizeof(u8))];
394 	} u;
395 	int ret;
396 
397 	msg->msg_control = &u;
398 	msg->msg_controllen = sizeof(u);
399 	ret = sock_recvmsg(sock, msg, flags);
400 	if (msg->msg_controllen != sizeof(u))
401 		ret = xs_sock_process_cmsg(sock, msg, &u.cmsg, ret);
402 	return ret;
403 }
404 
405 static ssize_t
xs_sock_recvmsg(struct socket * sock,struct msghdr * msg,int flags,size_t seek)406 xs_sock_recvmsg(struct socket *sock, struct msghdr *msg, int flags, size_t seek)
407 {
408 	ssize_t ret;
409 	if (seek != 0)
410 		iov_iter_advance(&msg->msg_iter, seek);
411 	ret = xs_sock_recv_cmsg(sock, msg, flags);
412 	return ret > 0 ? ret + seek : ret;
413 }
414 
415 static ssize_t
xs_read_kvec(struct socket * sock,struct msghdr * msg,int flags,struct kvec * kvec,size_t count,size_t seek)416 xs_read_kvec(struct socket *sock, struct msghdr *msg, int flags,
417 		struct kvec *kvec, size_t count, size_t seek)
418 {
419 	iov_iter_kvec(&msg->msg_iter, ITER_DEST, kvec, 1, count);
420 	return xs_sock_recvmsg(sock, msg, flags, seek);
421 }
422 
423 static ssize_t
xs_read_bvec(struct socket * sock,struct msghdr * msg,int flags,struct bio_vec * bvec,unsigned long nr,size_t count,size_t seek)424 xs_read_bvec(struct socket *sock, struct msghdr *msg, int flags,
425 		struct bio_vec *bvec, unsigned long nr, size_t count,
426 		size_t seek)
427 {
428 	iov_iter_bvec(&msg->msg_iter, ITER_DEST, bvec, nr, count);
429 	return xs_sock_recvmsg(sock, msg, flags, seek);
430 }
431 
432 static ssize_t
xs_read_discard(struct socket * sock,struct msghdr * msg,int flags,size_t count)433 xs_read_discard(struct socket *sock, struct msghdr *msg, int flags,
434 		size_t count)
435 {
436 	iov_iter_discard(&msg->msg_iter, ITER_DEST, count);
437 	return xs_sock_recv_cmsg(sock, msg, flags);
438 }
439 
440 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
441 static void
xs_flush_bvec(const struct bio_vec * bvec,size_t count,size_t seek)442 xs_flush_bvec(const struct bio_vec *bvec, size_t count, size_t seek)
443 {
444 	struct bvec_iter bi = {
445 		.bi_size = count,
446 	};
447 	struct bio_vec bv;
448 
449 	bvec_iter_advance(bvec, &bi, seek & PAGE_MASK);
450 	for_each_bvec(bv, bvec, bi, bi)
451 		flush_dcache_page(bv.bv_page);
452 }
453 #else
454 static inline void
xs_flush_bvec(const struct bio_vec * bvec,size_t count,size_t seek)455 xs_flush_bvec(const struct bio_vec *bvec, size_t count, size_t seek)
456 {
457 }
458 #endif
459 
460 static ssize_t
xs_read_xdr_buf(struct socket * sock,struct msghdr * msg,int flags,struct xdr_buf * buf,size_t count,size_t seek,size_t * read)461 xs_read_xdr_buf(struct socket *sock, struct msghdr *msg, int flags,
462 		struct xdr_buf *buf, size_t count, size_t seek, size_t *read)
463 {
464 	size_t want, seek_init = seek, offset = 0;
465 	ssize_t ret;
466 
467 	want = min_t(size_t, count, buf->head[0].iov_len);
468 	if (seek < want) {
469 		ret = xs_read_kvec(sock, msg, flags, &buf->head[0], want, seek);
470 		if (ret <= 0)
471 			goto sock_err;
472 		offset += ret;
473 		if (offset == count || msg->msg_flags & (MSG_EOR|MSG_TRUNC))
474 			goto out;
475 		if (ret != want)
476 			goto out;
477 		seek = 0;
478 	} else {
479 		seek -= want;
480 		offset += want;
481 	}
482 
483 	want = xs_alloc_sparse_pages(
484 		buf, min_t(size_t, count - offset, buf->page_len),
485 		GFP_KERNEL | __GFP_NORETRY | __GFP_NOWARN);
486 	if (seek < want) {
487 		ret = xs_read_bvec(sock, msg, flags, buf->bvec,
488 				xdr_buf_pagecount(buf),
489 				want + buf->page_base,
490 				seek + buf->page_base);
491 		if (ret <= 0)
492 			goto sock_err;
493 		xs_flush_bvec(buf->bvec, ret, seek + buf->page_base);
494 		ret -= buf->page_base;
495 		offset += ret;
496 		if (offset == count || msg->msg_flags & (MSG_EOR|MSG_TRUNC))
497 			goto out;
498 		if (ret != want)
499 			goto out;
500 		seek = 0;
501 	} else {
502 		seek -= want;
503 		offset += want;
504 	}
505 
506 	want = min_t(size_t, count - offset, buf->tail[0].iov_len);
507 	if (seek < want) {
508 		ret = xs_read_kvec(sock, msg, flags, &buf->tail[0], want, seek);
509 		if (ret <= 0)
510 			goto sock_err;
511 		offset += ret;
512 		if (offset == count || msg->msg_flags & (MSG_EOR|MSG_TRUNC))
513 			goto out;
514 		if (ret != want)
515 			goto out;
516 	} else if (offset < seek_init)
517 		offset = seek_init;
518 	ret = -EMSGSIZE;
519 out:
520 	*read = offset - seek_init;
521 	return ret;
522 sock_err:
523 	offset += seek;
524 	goto out;
525 }
526 
527 static void
xs_read_header(struct sock_xprt * transport,struct xdr_buf * buf)528 xs_read_header(struct sock_xprt *transport, struct xdr_buf *buf)
529 {
530 	if (!transport->recv.copied) {
531 		if (buf->head[0].iov_len >= transport->recv.offset)
532 			memcpy(buf->head[0].iov_base,
533 					&transport->recv.xid,
534 					transport->recv.offset);
535 		transport->recv.copied = transport->recv.offset;
536 	}
537 }
538 
539 static bool
xs_read_stream_request_done(struct sock_xprt * transport)540 xs_read_stream_request_done(struct sock_xprt *transport)
541 {
542 	return transport->recv.fraghdr & cpu_to_be32(RPC_LAST_STREAM_FRAGMENT);
543 }
544 
545 static void
xs_read_stream_check_eor(struct sock_xprt * transport,struct msghdr * msg)546 xs_read_stream_check_eor(struct sock_xprt *transport,
547 		struct msghdr *msg)
548 {
549 	if (xs_read_stream_request_done(transport))
550 		msg->msg_flags |= MSG_EOR;
551 }
552 
553 static ssize_t
xs_read_stream_request(struct sock_xprt * transport,struct msghdr * msg,int flags,struct rpc_rqst * req)554 xs_read_stream_request(struct sock_xprt *transport, struct msghdr *msg,
555 		int flags, struct rpc_rqst *req)
556 {
557 	struct xdr_buf *buf = &req->rq_private_buf;
558 	size_t want, read;
559 	ssize_t ret;
560 
561 	xs_read_header(transport, buf);
562 
563 	want = transport->recv.len - transport->recv.offset;
564 	if (want != 0) {
565 		ret = xs_read_xdr_buf(transport->sock, msg, flags, buf,
566 				transport->recv.copied + want,
567 				transport->recv.copied,
568 				&read);
569 		transport->recv.offset += read;
570 		transport->recv.copied += read;
571 	}
572 
573 	if (transport->recv.offset == transport->recv.len)
574 		xs_read_stream_check_eor(transport, msg);
575 
576 	if (want == 0)
577 		return 0;
578 
579 	switch (ret) {
580 	default:
581 		break;
582 	case -EFAULT:
583 	case -EMSGSIZE:
584 		msg->msg_flags |= MSG_TRUNC;
585 		return read;
586 	case 0:
587 		return -ESHUTDOWN;
588 	}
589 	return ret < 0 ? ret : read;
590 }
591 
592 static size_t
xs_read_stream_headersize(bool isfrag)593 xs_read_stream_headersize(bool isfrag)
594 {
595 	if (isfrag)
596 		return sizeof(__be32);
597 	return 3 * sizeof(__be32);
598 }
599 
600 static ssize_t
xs_read_stream_header(struct sock_xprt * transport,struct msghdr * msg,int flags,size_t want,size_t seek)601 xs_read_stream_header(struct sock_xprt *transport, struct msghdr *msg,
602 		int flags, size_t want, size_t seek)
603 {
604 	struct kvec kvec = {
605 		.iov_base = &transport->recv.fraghdr,
606 		.iov_len = want,
607 	};
608 	return xs_read_kvec(transport->sock, msg, flags, &kvec, want, seek);
609 }
610 
611 #if defined(CONFIG_SUNRPC_BACKCHANNEL)
612 static ssize_t
xs_read_stream_call(struct sock_xprt * transport,struct msghdr * msg,int flags)613 xs_read_stream_call(struct sock_xprt *transport, struct msghdr *msg, int flags)
614 {
615 	struct rpc_xprt *xprt = &transport->xprt;
616 	struct rpc_rqst *req;
617 	ssize_t ret;
618 
619 	/* Is this transport associated with the backchannel? */
620 	if (!xprt->bc_serv)
621 		return -ESHUTDOWN;
622 
623 	/* Look up and lock the request corresponding to the given XID */
624 	req = xprt_lookup_bc_request(xprt, transport->recv.xid);
625 	if (!req) {
626 		printk(KERN_WARNING "Callback slot table overflowed\n");
627 		return -ESHUTDOWN;
628 	}
629 	if (transport->recv.copied && !req->rq_private_buf.len)
630 		return -ESHUTDOWN;
631 
632 	ret = xs_read_stream_request(transport, msg, flags, req);
633 	if (msg->msg_flags & (MSG_EOR|MSG_TRUNC))
634 		xprt_complete_bc_request(req, transport->recv.copied);
635 	else
636 		req->rq_private_buf.len = transport->recv.copied;
637 
638 	return ret;
639 }
640 #else /* CONFIG_SUNRPC_BACKCHANNEL */
641 static ssize_t
xs_read_stream_call(struct sock_xprt * transport,struct msghdr * msg,int flags)642 xs_read_stream_call(struct sock_xprt *transport, struct msghdr *msg, int flags)
643 {
644 	return -ESHUTDOWN;
645 }
646 #endif /* CONFIG_SUNRPC_BACKCHANNEL */
647 
648 static ssize_t
xs_read_stream_reply(struct sock_xprt * transport,struct msghdr * msg,int flags)649 xs_read_stream_reply(struct sock_xprt *transport, struct msghdr *msg, int flags)
650 {
651 	struct rpc_xprt *xprt = &transport->xprt;
652 	struct rpc_rqst *req;
653 	ssize_t ret = 0;
654 
655 	/* Look up and lock the request corresponding to the given XID */
656 	spin_lock(&xprt->queue_lock);
657 	req = xprt_lookup_rqst(xprt, transport->recv.xid);
658 	if (!req || (transport->recv.copied && !req->rq_private_buf.len)) {
659 		msg->msg_flags |= MSG_TRUNC;
660 		goto out;
661 	}
662 	xprt_pin_rqst(req);
663 	spin_unlock(&xprt->queue_lock);
664 
665 	ret = xs_read_stream_request(transport, msg, flags, req);
666 
667 	spin_lock(&xprt->queue_lock);
668 	if (msg->msg_flags & (MSG_EOR|MSG_TRUNC))
669 		xprt_complete_rqst(req->rq_task, transport->recv.copied);
670 	else
671 		req->rq_private_buf.len = transport->recv.copied;
672 	xprt_unpin_rqst(req);
673 out:
674 	spin_unlock(&xprt->queue_lock);
675 	return ret;
676 }
677 
678 static ssize_t
xs_read_stream(struct sock_xprt * transport,int flags)679 xs_read_stream(struct sock_xprt *transport, int flags)
680 {
681 	struct msghdr msg = { 0 };
682 	size_t want, read = 0;
683 	ssize_t ret = 0;
684 
685 	if (transport->recv.len == 0) {
686 		want = xs_read_stream_headersize(transport->recv.copied != 0);
687 		ret = xs_read_stream_header(transport, &msg, flags, want,
688 				transport->recv.offset);
689 		if (ret <= 0)
690 			goto out_err;
691 		transport->recv.offset = ret;
692 		if (transport->recv.offset != want)
693 			return transport->recv.offset;
694 		transport->recv.len = be32_to_cpu(transport->recv.fraghdr) &
695 			RPC_FRAGMENT_SIZE_MASK;
696 		transport->recv.offset -= sizeof(transport->recv.fraghdr);
697 		read = ret;
698 	}
699 
700 	switch (be32_to_cpu(transport->recv.calldir)) {
701 	default:
702 		msg.msg_flags |= MSG_TRUNC;
703 		break;
704 	case RPC_CALL:
705 		ret = xs_read_stream_call(transport, &msg, flags);
706 		break;
707 	case RPC_REPLY:
708 		ret = xs_read_stream_reply(transport, &msg, flags);
709 	}
710 	if (msg.msg_flags & MSG_TRUNC) {
711 		transport->recv.calldir = cpu_to_be32(-1);
712 		transport->recv.copied = -1;
713 	}
714 	if (ret < 0)
715 		goto out_err;
716 	read += ret;
717 	if (transport->recv.offset < transport->recv.len) {
718 		if (!(msg.msg_flags & MSG_TRUNC))
719 			return read;
720 		msg.msg_flags = 0;
721 		ret = xs_read_discard(transport->sock, &msg, flags,
722 				transport->recv.len - transport->recv.offset);
723 		if (ret <= 0)
724 			goto out_err;
725 		transport->recv.offset += ret;
726 		read += ret;
727 		if (transport->recv.offset != transport->recv.len)
728 			return read;
729 	}
730 	if (xs_read_stream_request_done(transport)) {
731 		trace_xs_stream_read_request(transport);
732 		transport->recv.copied = 0;
733 	}
734 	transport->recv.offset = 0;
735 	transport->recv.len = 0;
736 	return read;
737 out_err:
738 	return ret != 0 ? ret : -ESHUTDOWN;
739 }
740 
xs_poll_socket(struct sock_xprt * transport)741 static __poll_t xs_poll_socket(struct sock_xprt *transport)
742 {
743 	return transport->sock->ops->poll(transport->file, transport->sock,
744 			NULL);
745 }
746 
xs_poll_socket_readable(struct sock_xprt * transport)747 static bool xs_poll_socket_readable(struct sock_xprt *transport)
748 {
749 	__poll_t events = xs_poll_socket(transport);
750 
751 	return (events & (EPOLLIN | EPOLLRDNORM)) && !(events & EPOLLRDHUP);
752 }
753 
xs_poll_check_readable(struct sock_xprt * transport)754 static void xs_poll_check_readable(struct sock_xprt *transport)
755 {
756 
757 	clear_bit(XPRT_SOCK_DATA_READY, &transport->sock_state);
758 	if (test_bit(XPRT_SOCK_IGNORE_RECV, &transport->sock_state))
759 		return;
760 	if (!xs_poll_socket_readable(transport))
761 		return;
762 	if (!test_and_set_bit(XPRT_SOCK_DATA_READY, &transport->sock_state))
763 		queue_work(xprtiod_workqueue, &transport->recv_worker);
764 }
765 
xs_stream_data_receive(struct sock_xprt * transport)766 static void xs_stream_data_receive(struct sock_xprt *transport)
767 {
768 	size_t read = 0;
769 	ssize_t ret = 0;
770 
771 	mutex_lock(&transport->recv_mutex);
772 	if (transport->sock == NULL)
773 		goto out;
774 	for (;;) {
775 		ret = xs_read_stream(transport, MSG_DONTWAIT);
776 		if (ret < 0)
777 			break;
778 		read += ret;
779 		cond_resched();
780 	}
781 	if (ret == -ESHUTDOWN)
782 		kernel_sock_shutdown(transport->sock, SHUT_RDWR);
783 	else if (ret == -EACCES)
784 		xprt_wake_pending_tasks(&transport->xprt, -EACCES);
785 	else
786 		xs_poll_check_readable(transport);
787 out:
788 	mutex_unlock(&transport->recv_mutex);
789 	trace_xs_stream_read_data(&transport->xprt, ret, read);
790 }
791 
xs_stream_data_receive_workfn(struct work_struct * work)792 static void xs_stream_data_receive_workfn(struct work_struct *work)
793 {
794 	struct sock_xprt *transport =
795 		container_of(work, struct sock_xprt, recv_worker);
796 	unsigned int pflags = memalloc_nofs_save();
797 
798 	xs_stream_data_receive(transport);
799 	memalloc_nofs_restore(pflags);
800 }
801 
802 static void
xs_stream_reset_connect(struct sock_xprt * transport)803 xs_stream_reset_connect(struct sock_xprt *transport)
804 {
805 	transport->recv.offset = 0;
806 	transport->recv.len = 0;
807 	transport->recv.copied = 0;
808 	transport->xmit.offset = 0;
809 }
810 
811 static void
xs_stream_start_connect(struct sock_xprt * transport)812 xs_stream_start_connect(struct sock_xprt *transport)
813 {
814 	transport->xprt.stat.connect_count++;
815 	transport->xprt.stat.connect_start = jiffies;
816 }
817 
818 #define XS_SENDMSG_FLAGS	(MSG_DONTWAIT | MSG_NOSIGNAL)
819 
820 /**
821  * xs_nospace - handle transmit was incomplete
822  * @req: pointer to RPC request
823  * @transport: pointer to struct sock_xprt
824  *
825  */
xs_nospace(struct rpc_rqst * req,struct sock_xprt * transport)826 static int xs_nospace(struct rpc_rqst *req, struct sock_xprt *transport)
827 {
828 	struct rpc_xprt *xprt = &transport->xprt;
829 	struct sock *sk = transport->inet;
830 	int ret = -EAGAIN;
831 
832 	trace_rpc_socket_nospace(req, transport);
833 
834 	/* Protect against races with write_space */
835 	spin_lock(&xprt->transport_lock);
836 
837 	/* Don't race with disconnect */
838 	if (xprt_connected(xprt)) {
839 		/* wait for more buffer space */
840 		set_bit(XPRT_SOCK_NOSPACE, &transport->sock_state);
841 		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
842 		sk->sk_write_pending++;
843 		xprt_wait_for_buffer_space(xprt);
844 	} else
845 		ret = -ENOTCONN;
846 
847 	spin_unlock(&xprt->transport_lock);
848 	return ret;
849 }
850 
xs_sock_nospace(struct rpc_rqst * req)851 static int xs_sock_nospace(struct rpc_rqst *req)
852 {
853 	struct sock_xprt *transport =
854 		container_of(req->rq_xprt, struct sock_xprt, xprt);
855 	struct sock *sk = transport->inet;
856 	int ret = -EAGAIN;
857 
858 	lock_sock(sk);
859 	if (!sock_writeable(sk))
860 		ret = xs_nospace(req, transport);
861 	release_sock(sk);
862 	return ret;
863 }
864 
xs_stream_nospace(struct rpc_rqst * req,bool vm_wait)865 static int xs_stream_nospace(struct rpc_rqst *req, bool vm_wait)
866 {
867 	struct sock_xprt *transport =
868 		container_of(req->rq_xprt, struct sock_xprt, xprt);
869 	struct sock *sk = transport->inet;
870 	int ret = -EAGAIN;
871 
872 	if (vm_wait)
873 		return -ENOBUFS;
874 	lock_sock(sk);
875 	if (!sk_stream_memory_free(sk))
876 		ret = xs_nospace(req, transport);
877 	release_sock(sk);
878 	return ret;
879 }
880 
xs_stream_prepare_request(struct rpc_rqst * req,struct xdr_buf * buf)881 static int xs_stream_prepare_request(struct rpc_rqst *req, struct xdr_buf *buf)
882 {
883 	return xdr_alloc_bvec(buf, rpc_task_gfp_mask());
884 }
885 
xs_stream_abort_send_request(struct rpc_rqst * req)886 static void xs_stream_abort_send_request(struct rpc_rqst *req)
887 {
888 	struct rpc_xprt *xprt = req->rq_xprt;
889 	struct sock_xprt *transport =
890 		container_of(xprt, struct sock_xprt, xprt);
891 
892 	if (transport->xmit.offset != 0 &&
893 	    !test_bit(XPRT_CLOSE_WAIT, &xprt->state))
894 		xprt_force_disconnect(xprt);
895 }
896 
897 /*
898  * Determine if the previous message in the stream was aborted before it
899  * could complete transmission.
900  */
901 static bool
xs_send_request_was_aborted(struct sock_xprt * transport,struct rpc_rqst * req)902 xs_send_request_was_aborted(struct sock_xprt *transport, struct rpc_rqst *req)
903 {
904 	return transport->xmit.offset != 0 && req->rq_bytes_sent == 0;
905 }
906 
907 /*
908  * Return the stream record marker field for a record of length < 2^31-1
909  */
910 static rpc_fraghdr
xs_stream_record_marker(struct xdr_buf * xdr)911 xs_stream_record_marker(struct xdr_buf *xdr)
912 {
913 	if (!xdr->len)
914 		return 0;
915 	return cpu_to_be32(RPC_LAST_STREAM_FRAGMENT | (u32)xdr->len);
916 }
917 
918 /**
919  * xs_local_send_request - write an RPC request to an AF_LOCAL socket
920  * @req: pointer to RPC request
921  *
922  * Return values:
923  *        0:	The request has been sent
924  *   EAGAIN:	The socket was blocked, please call again later to
925  *		complete the request
926  * ENOTCONN:	Caller needs to invoke connect logic then call again
927  *    other:	Some other error occurred, the request was not sent
928  */
xs_local_send_request(struct rpc_rqst * req)929 static int xs_local_send_request(struct rpc_rqst *req)
930 {
931 	struct rpc_xprt *xprt = req->rq_xprt;
932 	struct sock_xprt *transport =
933 				container_of(xprt, struct sock_xprt, xprt);
934 	struct xdr_buf *xdr = &req->rq_snd_buf;
935 	rpc_fraghdr rm = xs_stream_record_marker(xdr);
936 	unsigned int msglen = rm ? req->rq_slen + sizeof(rm) : req->rq_slen;
937 	struct msghdr msg = {
938 		.msg_flags	= XS_SENDMSG_FLAGS,
939 	};
940 	bool vm_wait;
941 	unsigned int sent;
942 	int status;
943 
944 	/* Close the stream if the previous transmission was incomplete */
945 	if (xs_send_request_was_aborted(transport, req)) {
946 		xprt_force_disconnect(xprt);
947 		return -ENOTCONN;
948 	}
949 
950 	xs_pktdump("packet data:",
951 			req->rq_svec->iov_base, req->rq_svec->iov_len);
952 
953 	vm_wait = sk_stream_is_writeable(transport->inet) ? true : false;
954 
955 	req->rq_xtime = ktime_get();
956 	status = xprt_sock_sendmsg(transport->sock, &msg, xdr,
957 				   transport->xmit.offset, rm, &sent);
958 	dprintk("RPC:       %s(%u) = %d\n",
959 			__func__, xdr->len - transport->xmit.offset, status);
960 
961 	if (likely(sent > 0) || status == 0) {
962 		transport->xmit.offset += sent;
963 		req->rq_bytes_sent = transport->xmit.offset;
964 		if (likely(req->rq_bytes_sent >= msglen)) {
965 			req->rq_xmit_bytes_sent += transport->xmit.offset;
966 			transport->xmit.offset = 0;
967 			return 0;
968 		}
969 		status = -EAGAIN;
970 		vm_wait = false;
971 	}
972 
973 	switch (status) {
974 	case -EAGAIN:
975 		status = xs_stream_nospace(req, vm_wait);
976 		break;
977 	default:
978 		dprintk("RPC:       sendmsg returned unrecognized error %d\n",
979 			-status);
980 		fallthrough;
981 	case -EPIPE:
982 		xprt_force_disconnect(xprt);
983 		status = -ENOTCONN;
984 	}
985 
986 	return status;
987 }
988 
989 /**
990  * xs_udp_send_request - write an RPC request to a UDP socket
991  * @req: pointer to RPC request
992  *
993  * Return values:
994  *        0:	The request has been sent
995  *   EAGAIN:	The socket was blocked, please call again later to
996  *		complete the request
997  * ENOTCONN:	Caller needs to invoke connect logic then call again
998  *    other:	Some other error occurred, the request was not sent
999  */
xs_udp_send_request(struct rpc_rqst * req)1000 static int xs_udp_send_request(struct rpc_rqst *req)
1001 {
1002 	struct rpc_xprt *xprt = req->rq_xprt;
1003 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1004 	struct xdr_buf *xdr = &req->rq_snd_buf;
1005 	struct msghdr msg = {
1006 		.msg_name	= xs_addr(xprt),
1007 		.msg_namelen	= xprt->addrlen,
1008 		.msg_flags	= XS_SENDMSG_FLAGS,
1009 	};
1010 	unsigned int sent;
1011 	int status;
1012 
1013 	xs_pktdump("packet data:",
1014 				req->rq_svec->iov_base,
1015 				req->rq_svec->iov_len);
1016 
1017 	if (!xprt_bound(xprt))
1018 		return -ENOTCONN;
1019 
1020 	if (!xprt_request_get_cong(xprt, req))
1021 		return -EBADSLT;
1022 
1023 	status = xdr_alloc_bvec(xdr, rpc_task_gfp_mask());
1024 	if (status < 0)
1025 		return status;
1026 	req->rq_xtime = ktime_get();
1027 	status = xprt_sock_sendmsg(transport->sock, &msg, xdr, 0, 0, &sent);
1028 
1029 	dprintk("RPC:       xs_udp_send_request(%u) = %d\n",
1030 			xdr->len, status);
1031 
1032 	/* firewall is blocking us, don't return -EAGAIN or we end up looping */
1033 	if (status == -EPERM)
1034 		goto process_status;
1035 
1036 	if (status == -EAGAIN && sock_writeable(transport->inet))
1037 		status = -ENOBUFS;
1038 
1039 	if (sent > 0 || status == 0) {
1040 		req->rq_xmit_bytes_sent += sent;
1041 		if (sent >= req->rq_slen)
1042 			return 0;
1043 		/* Still some bytes left; set up for a retry later. */
1044 		status = -EAGAIN;
1045 	}
1046 
1047 process_status:
1048 	switch (status) {
1049 	case -ENOTSOCK:
1050 		status = -ENOTCONN;
1051 		/* Should we call xs_close() here? */
1052 		break;
1053 	case -EAGAIN:
1054 		status = xs_sock_nospace(req);
1055 		break;
1056 	case -ENETUNREACH:
1057 	case -ENOBUFS:
1058 	case -EPIPE:
1059 	case -ECONNREFUSED:
1060 	case -EPERM:
1061 		/* When the server has died, an ICMP port unreachable message
1062 		 * prompts ECONNREFUSED. */
1063 		break;
1064 	default:
1065 		dprintk("RPC:       sendmsg returned unrecognized error %d\n",
1066 			-status);
1067 	}
1068 
1069 	return status;
1070 }
1071 
1072 /**
1073  * xs_tcp_send_request - write an RPC request to a TCP socket
1074  * @req: pointer to RPC request
1075  *
1076  * Return values:
1077  *        0:	The request has been sent
1078  *   EAGAIN:	The socket was blocked, please call again later to
1079  *		complete the request
1080  * ENOTCONN:	Caller needs to invoke connect logic then call again
1081  *    other:	Some other error occurred, the request was not sent
1082  *
1083  * XXX: In the case of soft timeouts, should we eventually give up
1084  *	if sendmsg is not able to make progress?
1085  */
xs_tcp_send_request(struct rpc_rqst * req)1086 static int xs_tcp_send_request(struct rpc_rqst *req)
1087 {
1088 	struct rpc_xprt *xprt = req->rq_xprt;
1089 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1090 	struct xdr_buf *xdr = &req->rq_snd_buf;
1091 	rpc_fraghdr rm = xs_stream_record_marker(xdr);
1092 	unsigned int msglen = rm ? req->rq_slen + sizeof(rm) : req->rq_slen;
1093 	struct msghdr msg = {
1094 		.msg_flags	= XS_SENDMSG_FLAGS,
1095 	};
1096 	bool vm_wait;
1097 	unsigned int sent;
1098 	int status;
1099 
1100 	/* Close the stream if the previous transmission was incomplete */
1101 	if (xs_send_request_was_aborted(transport, req)) {
1102 		if (transport->sock != NULL)
1103 			kernel_sock_shutdown(transport->sock, SHUT_RDWR);
1104 		return -ENOTCONN;
1105 	}
1106 	if (!transport->inet)
1107 		return -ENOTCONN;
1108 
1109 	xs_pktdump("packet data:",
1110 				req->rq_svec->iov_base,
1111 				req->rq_svec->iov_len);
1112 
1113 	if (test_bit(XPRT_SOCK_UPD_TIMEOUT, &transport->sock_state))
1114 		xs_tcp_set_socket_timeouts(xprt, transport->sock);
1115 
1116 	xs_set_srcport(transport, transport->sock);
1117 
1118 	/* Continue transmitting the packet/record. We must be careful
1119 	 * to cope with writespace callbacks arriving _after_ we have
1120 	 * called sendmsg(). */
1121 	req->rq_xtime = ktime_get();
1122 	tcp_sock_set_cork(transport->inet, true);
1123 
1124 	vm_wait = sk_stream_is_writeable(transport->inet) ? true : false;
1125 
1126 	do {
1127 		status = xprt_sock_sendmsg(transport->sock, &msg, xdr,
1128 					   transport->xmit.offset, rm, &sent);
1129 
1130 		dprintk("RPC:       xs_tcp_send_request(%u) = %d\n",
1131 				xdr->len - transport->xmit.offset, status);
1132 
1133 		/* If we've sent the entire packet, immediately
1134 		 * reset the count of bytes sent. */
1135 		transport->xmit.offset += sent;
1136 		req->rq_bytes_sent = transport->xmit.offset;
1137 		if (likely(req->rq_bytes_sent >= msglen)) {
1138 			req->rq_xmit_bytes_sent += transport->xmit.offset;
1139 			transport->xmit.offset = 0;
1140 			if (atomic_long_read(&xprt->xmit_queuelen) == 1)
1141 				tcp_sock_set_cork(transport->inet, false);
1142 			return 0;
1143 		}
1144 
1145 		WARN_ON_ONCE(sent == 0 && status == 0);
1146 
1147 		if (sent > 0)
1148 			vm_wait = false;
1149 
1150 	} while (status == 0);
1151 
1152 	switch (status) {
1153 	case -ENOTSOCK:
1154 		status = -ENOTCONN;
1155 		/* Should we call xs_close() here? */
1156 		break;
1157 	case -EAGAIN:
1158 		status = xs_stream_nospace(req, vm_wait);
1159 		break;
1160 	case -ECONNRESET:
1161 	case -ECONNREFUSED:
1162 	case -ENOTCONN:
1163 	case -EADDRINUSE:
1164 	case -ENOBUFS:
1165 	case -EPIPE:
1166 		break;
1167 	default:
1168 		dprintk("RPC:       sendmsg returned unrecognized error %d\n",
1169 			-status);
1170 	}
1171 
1172 	return status;
1173 }
1174 
xs_save_old_callbacks(struct sock_xprt * transport,struct sock * sk)1175 static void xs_save_old_callbacks(struct sock_xprt *transport, struct sock *sk)
1176 {
1177 	transport->old_data_ready = sk->sk_data_ready;
1178 	transport->old_state_change = sk->sk_state_change;
1179 	transport->old_write_space = sk->sk_write_space;
1180 	transport->old_error_report = sk->sk_error_report;
1181 }
1182 
xs_restore_old_callbacks(struct sock_xprt * transport,struct sock * sk)1183 static void xs_restore_old_callbacks(struct sock_xprt *transport, struct sock *sk)
1184 {
1185 	sk->sk_data_ready = transport->old_data_ready;
1186 	sk->sk_state_change = transport->old_state_change;
1187 	sk->sk_write_space = transport->old_write_space;
1188 	sk->sk_error_report = transport->old_error_report;
1189 }
1190 
xs_sock_reset_state_flags(struct rpc_xprt * xprt)1191 static void xs_sock_reset_state_flags(struct rpc_xprt *xprt)
1192 {
1193 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1194 
1195 	transport->xprt_err = 0;
1196 	clear_bit(XPRT_SOCK_DATA_READY, &transport->sock_state);
1197 	clear_bit(XPRT_SOCK_WAKE_ERROR, &transport->sock_state);
1198 	clear_bit(XPRT_SOCK_WAKE_WRITE, &transport->sock_state);
1199 	clear_bit(XPRT_SOCK_WAKE_DISCONNECT, &transport->sock_state);
1200 	clear_bit(XPRT_SOCK_NOSPACE, &transport->sock_state);
1201 	clear_bit(XPRT_SOCK_UPD_TIMEOUT, &transport->sock_state);
1202 }
1203 
xs_run_error_worker(struct sock_xprt * transport,unsigned int nr)1204 static void xs_run_error_worker(struct sock_xprt *transport, unsigned int nr)
1205 {
1206 	set_bit(nr, &transport->sock_state);
1207 	queue_work(xprtiod_workqueue, &transport->error_worker);
1208 }
1209 
xs_sock_reset_connection_flags(struct rpc_xprt * xprt)1210 static void xs_sock_reset_connection_flags(struct rpc_xprt *xprt)
1211 {
1212 	xprt->connect_cookie++;
1213 	smp_mb__before_atomic();
1214 	clear_bit(XPRT_CLOSE_WAIT, &xprt->state);
1215 	clear_bit(XPRT_CLOSING, &xprt->state);
1216 	xs_sock_reset_state_flags(xprt);
1217 	smp_mb__after_atomic();
1218 }
1219 
1220 /**
1221  * xs_error_report - callback to handle TCP socket state errors
1222  * @sk: socket
1223  *
1224  * Note: we don't call sock_error() since there may be a rpc_task
1225  * using the socket, and so we don't want to clear sk->sk_err.
1226  */
xs_error_report(struct sock * sk)1227 static void xs_error_report(struct sock *sk)
1228 {
1229 	struct sock_xprt *transport;
1230 	struct rpc_xprt *xprt;
1231 
1232 	if (!(xprt = xprt_from_sock(sk)))
1233 		return;
1234 
1235 	transport = container_of(xprt, struct sock_xprt, xprt);
1236 	transport->xprt_err = -sk->sk_err;
1237 	if (transport->xprt_err == 0)
1238 		return;
1239 	dprintk("RPC:       xs_error_report client %p, error=%d...\n",
1240 			xprt, -transport->xprt_err);
1241 	trace_rpc_socket_error(xprt, sk->sk_socket, transport->xprt_err);
1242 
1243 	/* barrier ensures xprt_err is set before XPRT_SOCK_WAKE_ERROR */
1244 	smp_mb__before_atomic();
1245 	xs_run_error_worker(transport, XPRT_SOCK_WAKE_ERROR);
1246 }
1247 
xs_reset_transport(struct sock_xprt * transport)1248 static void xs_reset_transport(struct sock_xprt *transport)
1249 {
1250 	struct socket *sock = transport->sock;
1251 	struct sock *sk = transport->inet;
1252 	struct rpc_xprt *xprt = &transport->xprt;
1253 	struct file *filp = transport->file;
1254 
1255 	if (sk == NULL)
1256 		return;
1257 	/*
1258 	 * Make sure we're calling this in a context from which it is safe
1259 	 * to call __fput_sync(). In practice that means rpciod and the
1260 	 * system workqueue.
1261 	 */
1262 	if (!(current->flags & PF_WQ_WORKER)) {
1263 		WARN_ON_ONCE(1);
1264 		set_bit(XPRT_CLOSE_WAIT, &xprt->state);
1265 		return;
1266 	}
1267 
1268 	if (atomic_read(&transport->xprt.swapper))
1269 		sk_clear_memalloc(sk);
1270 
1271 	tls_handshake_cancel(sk);
1272 
1273 	kernel_sock_shutdown(sock, SHUT_RDWR);
1274 
1275 	mutex_lock(&transport->recv_mutex);
1276 	lock_sock(sk);
1277 	transport->inet = NULL;
1278 	transport->sock = NULL;
1279 	transport->file = NULL;
1280 
1281 	sk->sk_user_data = NULL;
1282 	sk->sk_sndtimeo = 0;
1283 
1284 	xs_restore_old_callbacks(transport, sk);
1285 	xprt_clear_connected(xprt);
1286 	xs_sock_reset_connection_flags(xprt);
1287 	/* Reset stream record info */
1288 	xs_stream_reset_connect(transport);
1289 	release_sock(sk);
1290 	mutex_unlock(&transport->recv_mutex);
1291 
1292 	trace_rpc_socket_close(xprt, sock);
1293 	__fput_sync(filp);
1294 
1295 	xprt_disconnect_done(xprt);
1296 }
1297 
1298 /**
1299  * xs_close - close a socket
1300  * @xprt: transport
1301  *
1302  * This is used when all requests are complete; ie, no DRC state remains
1303  * on the server we want to save.
1304  *
1305  * The caller _must_ be holding XPRT_LOCKED in order to avoid issues with
1306  * xs_reset_transport() zeroing the socket from underneath a writer.
1307  */
xs_close(struct rpc_xprt * xprt)1308 static void xs_close(struct rpc_xprt *xprt)
1309 {
1310 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1311 
1312 	dprintk("RPC:       xs_close xprt %p\n", xprt);
1313 
1314 	if (transport->sock)
1315 		tls_handshake_close(transport->sock);
1316 	xs_reset_transport(transport);
1317 	xprt->reestablish_timeout = 0;
1318 }
1319 
xs_inject_disconnect(struct rpc_xprt * xprt)1320 static void xs_inject_disconnect(struct rpc_xprt *xprt)
1321 {
1322 	dprintk("RPC:       injecting transport disconnect on xprt=%p\n",
1323 		xprt);
1324 	xprt_disconnect_done(xprt);
1325 }
1326 
xs_xprt_free(struct rpc_xprt * xprt)1327 static void xs_xprt_free(struct rpc_xprt *xprt)
1328 {
1329 	xs_free_peer_addresses(xprt);
1330 	xprt_free(xprt);
1331 }
1332 
1333 /**
1334  * xs_destroy - prepare to shutdown a transport
1335  * @xprt: doomed transport
1336  *
1337  */
xs_destroy(struct rpc_xprt * xprt)1338 static void xs_destroy(struct rpc_xprt *xprt)
1339 {
1340 	struct sock_xprt *transport = container_of(xprt,
1341 			struct sock_xprt, xprt);
1342 	dprintk("RPC:       xs_destroy xprt %p\n", xprt);
1343 
1344 	cancel_delayed_work_sync(&transport->connect_worker);
1345 	xs_close(xprt);
1346 	cancel_work_sync(&transport->recv_worker);
1347 	cancel_work_sync(&transport->error_worker);
1348 	xs_xprt_free(xprt);
1349 	module_put(THIS_MODULE);
1350 }
1351 
1352 /**
1353  * xs_udp_data_read_skb - receive callback for UDP sockets
1354  * @xprt: transport
1355  * @sk: socket
1356  * @skb: skbuff
1357  *
1358  */
xs_udp_data_read_skb(struct rpc_xprt * xprt,struct sock * sk,struct sk_buff * skb)1359 static void xs_udp_data_read_skb(struct rpc_xprt *xprt,
1360 		struct sock *sk,
1361 		struct sk_buff *skb)
1362 {
1363 	struct rpc_task *task;
1364 	struct rpc_rqst *rovr;
1365 	int repsize, copied;
1366 	u32 _xid;
1367 	__be32 *xp;
1368 
1369 	repsize = skb->len;
1370 	if (repsize < 4) {
1371 		dprintk("RPC:       impossible RPC reply size %d!\n", repsize);
1372 		return;
1373 	}
1374 
1375 	/* Copy the XID from the skb... */
1376 	xp = skb_header_pointer(skb, 0, sizeof(_xid), &_xid);
1377 	if (xp == NULL)
1378 		return;
1379 
1380 	/* Look up and lock the request corresponding to the given XID */
1381 	spin_lock(&xprt->queue_lock);
1382 	rovr = xprt_lookup_rqst(xprt, *xp);
1383 	if (!rovr)
1384 		goto out_unlock;
1385 	xprt_pin_rqst(rovr);
1386 	xprt_update_rtt(rovr->rq_task);
1387 	spin_unlock(&xprt->queue_lock);
1388 	task = rovr->rq_task;
1389 
1390 	if ((copied = rovr->rq_private_buf.buflen) > repsize)
1391 		copied = repsize;
1392 
1393 	/* Suck it into the iovec, verify checksum if not done by hw. */
1394 	if (csum_partial_copy_to_xdr(&rovr->rq_private_buf, skb)) {
1395 		spin_lock(&xprt->queue_lock);
1396 		__UDPX_INC_STATS(sk, UDP_MIB_INERRORS);
1397 		goto out_unpin;
1398 	}
1399 
1400 
1401 	spin_lock(&xprt->transport_lock);
1402 	xprt_adjust_cwnd(xprt, task, copied);
1403 	spin_unlock(&xprt->transport_lock);
1404 	spin_lock(&xprt->queue_lock);
1405 	xprt_complete_rqst(task, copied);
1406 	__UDPX_INC_STATS(sk, UDP_MIB_INDATAGRAMS);
1407 out_unpin:
1408 	xprt_unpin_rqst(rovr);
1409  out_unlock:
1410 	spin_unlock(&xprt->queue_lock);
1411 }
1412 
xs_udp_data_receive(struct sock_xprt * transport)1413 static void xs_udp_data_receive(struct sock_xprt *transport)
1414 {
1415 	struct sk_buff *skb;
1416 	struct sock *sk;
1417 	int err;
1418 
1419 	mutex_lock(&transport->recv_mutex);
1420 	sk = transport->inet;
1421 	if (sk == NULL)
1422 		goto out;
1423 	for (;;) {
1424 		skb = skb_recv_udp(sk, MSG_DONTWAIT, &err);
1425 		if (skb == NULL)
1426 			break;
1427 		xs_udp_data_read_skb(&transport->xprt, sk, skb);
1428 		consume_skb(skb);
1429 		cond_resched();
1430 	}
1431 	xs_poll_check_readable(transport);
1432 out:
1433 	mutex_unlock(&transport->recv_mutex);
1434 }
1435 
xs_udp_data_receive_workfn(struct work_struct * work)1436 static void xs_udp_data_receive_workfn(struct work_struct *work)
1437 {
1438 	struct sock_xprt *transport =
1439 		container_of(work, struct sock_xprt, recv_worker);
1440 	unsigned int pflags = memalloc_nofs_save();
1441 
1442 	xs_udp_data_receive(transport);
1443 	memalloc_nofs_restore(pflags);
1444 }
1445 
1446 /**
1447  * xs_data_ready - "data ready" callback for sockets
1448  * @sk: socket with data to read
1449  *
1450  */
xs_data_ready(struct sock * sk)1451 static void xs_data_ready(struct sock *sk)
1452 {
1453 	struct rpc_xprt *xprt;
1454 
1455 	trace_sk_data_ready(sk);
1456 
1457 	xprt = xprt_from_sock(sk);
1458 	if (xprt != NULL) {
1459 		struct sock_xprt *transport = container_of(xprt,
1460 				struct sock_xprt, xprt);
1461 
1462 		trace_xs_data_ready(xprt);
1463 
1464 		transport->old_data_ready(sk);
1465 
1466 		if (test_bit(XPRT_SOCK_IGNORE_RECV, &transport->sock_state))
1467 			return;
1468 
1469 		/* Any data means we had a useful conversation, so
1470 		 * then we don't need to delay the next reconnect
1471 		 */
1472 		if (xprt->reestablish_timeout)
1473 			xprt->reestablish_timeout = 0;
1474 		if (!test_and_set_bit(XPRT_SOCK_DATA_READY, &transport->sock_state))
1475 			queue_work(xprtiod_workqueue, &transport->recv_worker);
1476 	}
1477 }
1478 
1479 /*
1480  * Helper function to force a TCP close if the server is sending
1481  * junk and/or it has put us in CLOSE_WAIT
1482  */
xs_tcp_force_close(struct rpc_xprt * xprt)1483 static void xs_tcp_force_close(struct rpc_xprt *xprt)
1484 {
1485 	xprt_force_disconnect(xprt);
1486 }
1487 
1488 #if defined(CONFIG_SUNRPC_BACKCHANNEL)
xs_tcp_bc_maxpayload(struct rpc_xprt * xprt)1489 static size_t xs_tcp_bc_maxpayload(struct rpc_xprt *xprt)
1490 {
1491 	return PAGE_SIZE;
1492 }
1493 #endif /* CONFIG_SUNRPC_BACKCHANNEL */
1494 
1495 /**
1496  * xs_local_state_change - callback to handle AF_LOCAL socket state changes
1497  * @sk: socket whose state has changed
1498  *
1499  */
xs_local_state_change(struct sock * sk)1500 static void xs_local_state_change(struct sock *sk)
1501 {
1502 	struct rpc_xprt *xprt;
1503 	struct sock_xprt *transport;
1504 
1505 	if (!(xprt = xprt_from_sock(sk)))
1506 		return;
1507 	transport = container_of(xprt, struct sock_xprt, xprt);
1508 	if (sk->sk_shutdown & SHUTDOWN_MASK) {
1509 		clear_bit(XPRT_CONNECTED, &xprt->state);
1510 		/* Trigger the socket release */
1511 		xs_run_error_worker(transport, XPRT_SOCK_WAKE_DISCONNECT);
1512 	}
1513 }
1514 
1515 /**
1516  * xs_tcp_state_change - callback to handle TCP socket state changes
1517  * @sk: socket whose state has changed
1518  *
1519  */
xs_tcp_state_change(struct sock * sk)1520 static void xs_tcp_state_change(struct sock *sk)
1521 {
1522 	struct rpc_xprt *xprt;
1523 	struct sock_xprt *transport;
1524 
1525 	if (!(xprt = xprt_from_sock(sk)))
1526 		return;
1527 	dprintk("RPC:       xs_tcp_state_change client %p...\n", xprt);
1528 	dprintk("RPC:       state %x conn %d dead %d zapped %d sk_shutdown %d\n",
1529 			sk->sk_state, xprt_connected(xprt),
1530 			sock_flag(sk, SOCK_DEAD),
1531 			sock_flag(sk, SOCK_ZAPPED),
1532 			sk->sk_shutdown);
1533 
1534 	transport = container_of(xprt, struct sock_xprt, xprt);
1535 	trace_rpc_socket_state_change(xprt, sk->sk_socket);
1536 	switch (sk->sk_state) {
1537 	case TCP_ESTABLISHED:
1538 		if (!xprt_test_and_set_connected(xprt)) {
1539 			xprt->connect_cookie++;
1540 			clear_bit(XPRT_SOCK_CONNECTING, &transport->sock_state);
1541 			xprt_clear_connecting(xprt);
1542 
1543 			xprt->stat.connect_count++;
1544 			xprt->stat.connect_time += (long)jiffies -
1545 						   xprt->stat.connect_start;
1546 			xs_run_error_worker(transport, XPRT_SOCK_WAKE_PENDING);
1547 		}
1548 		break;
1549 	case TCP_FIN_WAIT1:
1550 		/* The client initiated a shutdown of the socket */
1551 		xprt->connect_cookie++;
1552 		xprt->reestablish_timeout = 0;
1553 		set_bit(XPRT_CLOSING, &xprt->state);
1554 		smp_mb__before_atomic();
1555 		clear_bit(XPRT_CONNECTED, &xprt->state);
1556 		clear_bit(XPRT_CLOSE_WAIT, &xprt->state);
1557 		smp_mb__after_atomic();
1558 		break;
1559 	case TCP_CLOSE_WAIT:
1560 		/* The server initiated a shutdown of the socket */
1561 		xprt->connect_cookie++;
1562 		clear_bit(XPRT_CONNECTED, &xprt->state);
1563 		xs_run_error_worker(transport, XPRT_SOCK_WAKE_DISCONNECT);
1564 		fallthrough;
1565 	case TCP_CLOSING:
1566 		/*
1567 		 * If the server closed down the connection, make sure that
1568 		 * we back off before reconnecting
1569 		 */
1570 		if (xprt->reestablish_timeout < XS_TCP_INIT_REEST_TO)
1571 			xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
1572 		break;
1573 	case TCP_LAST_ACK:
1574 		set_bit(XPRT_CLOSING, &xprt->state);
1575 		smp_mb__before_atomic();
1576 		clear_bit(XPRT_CONNECTED, &xprt->state);
1577 		smp_mb__after_atomic();
1578 		break;
1579 	case TCP_CLOSE:
1580 		if (test_and_clear_bit(XPRT_SOCK_CONNECTING,
1581 				       &transport->sock_state)) {
1582 			xs_reset_srcport(transport);
1583 			xprt_clear_connecting(xprt);
1584 		}
1585 		clear_bit(XPRT_CLOSING, &xprt->state);
1586 		/* Trigger the socket release */
1587 		xs_run_error_worker(transport, XPRT_SOCK_WAKE_DISCONNECT);
1588 	}
1589 }
1590 
xs_write_space(struct sock * sk)1591 static void xs_write_space(struct sock *sk)
1592 {
1593 	struct sock_xprt *transport;
1594 	struct rpc_xprt *xprt;
1595 
1596 	if (!sk->sk_socket)
1597 		return;
1598 	clear_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1599 
1600 	if (unlikely(!(xprt = xprt_from_sock(sk))))
1601 		return;
1602 	transport = container_of(xprt, struct sock_xprt, xprt);
1603 	if (!test_and_clear_bit(XPRT_SOCK_NOSPACE, &transport->sock_state))
1604 		return;
1605 	xs_run_error_worker(transport, XPRT_SOCK_WAKE_WRITE);
1606 	sk->sk_write_pending--;
1607 }
1608 
1609 /**
1610  * xs_udp_write_space - callback invoked when socket buffer space
1611  *                             becomes available
1612  * @sk: socket whose state has changed
1613  *
1614  * Called when more output buffer space is available for this socket.
1615  * We try not to wake our writers until they can make "significant"
1616  * progress, otherwise we'll waste resources thrashing kernel_sendmsg
1617  * with a bunch of small requests.
1618  */
xs_udp_write_space(struct sock * sk)1619 static void xs_udp_write_space(struct sock *sk)
1620 {
1621 	/* from net/core/sock.c:sock_def_write_space */
1622 	if (sock_writeable(sk))
1623 		xs_write_space(sk);
1624 }
1625 
1626 /**
1627  * xs_tcp_write_space - callback invoked when socket buffer space
1628  *                             becomes available
1629  * @sk: socket whose state has changed
1630  *
1631  * Called when more output buffer space is available for this socket.
1632  * We try not to wake our writers until they can make "significant"
1633  * progress, otherwise we'll waste resources thrashing kernel_sendmsg
1634  * with a bunch of small requests.
1635  */
xs_tcp_write_space(struct sock * sk)1636 static void xs_tcp_write_space(struct sock *sk)
1637 {
1638 	/* from net/core/stream.c:sk_stream_write_space */
1639 	if (sk_stream_is_writeable(sk))
1640 		xs_write_space(sk);
1641 }
1642 
xs_udp_do_set_buffer_size(struct rpc_xprt * xprt)1643 static void xs_udp_do_set_buffer_size(struct rpc_xprt *xprt)
1644 {
1645 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1646 	struct sock *sk = transport->inet;
1647 
1648 	if (transport->rcvsize) {
1649 		sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
1650 		sk->sk_rcvbuf = transport->rcvsize * xprt->max_reqs * 2;
1651 	}
1652 	if (transport->sndsize) {
1653 		sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
1654 		sk->sk_sndbuf = transport->sndsize * xprt->max_reqs * 2;
1655 		sk->sk_write_space(sk);
1656 	}
1657 }
1658 
1659 /**
1660  * xs_udp_set_buffer_size - set send and receive limits
1661  * @xprt: generic transport
1662  * @sndsize: requested size of send buffer, in bytes
1663  * @rcvsize: requested size of receive buffer, in bytes
1664  *
1665  * Set socket send and receive buffer size limits.
1666  */
xs_udp_set_buffer_size(struct rpc_xprt * xprt,size_t sndsize,size_t rcvsize)1667 static void xs_udp_set_buffer_size(struct rpc_xprt *xprt, size_t sndsize, size_t rcvsize)
1668 {
1669 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
1670 
1671 	transport->sndsize = 0;
1672 	if (sndsize)
1673 		transport->sndsize = sndsize + 1024;
1674 	transport->rcvsize = 0;
1675 	if (rcvsize)
1676 		transport->rcvsize = rcvsize + 1024;
1677 
1678 	xs_udp_do_set_buffer_size(xprt);
1679 }
1680 
1681 /**
1682  * xs_udp_timer - called when a retransmit timeout occurs on a UDP transport
1683  * @xprt: controlling transport
1684  * @task: task that timed out
1685  *
1686  * Adjust the congestion window after a retransmit timeout has occurred.
1687  */
xs_udp_timer(struct rpc_xprt * xprt,struct rpc_task * task)1688 static void xs_udp_timer(struct rpc_xprt *xprt, struct rpc_task *task)
1689 {
1690 	spin_lock(&xprt->transport_lock);
1691 	xprt_adjust_cwnd(xprt, task, -ETIMEDOUT);
1692 	spin_unlock(&xprt->transport_lock);
1693 }
1694 
xs_get_random_port(void)1695 static int xs_get_random_port(void)
1696 {
1697 	unsigned short min = xprt_min_resvport, max = xprt_max_resvport;
1698 	unsigned short range;
1699 	unsigned short rand;
1700 
1701 	if (max < min)
1702 		return -EADDRINUSE;
1703 	range = max - min + 1;
1704 	rand = get_random_u32_below(range);
1705 	return rand + min;
1706 }
1707 
xs_sock_getport(struct socket * sock)1708 static unsigned short xs_sock_getport(struct socket *sock)
1709 {
1710 	struct sockaddr_storage buf;
1711 	unsigned short port = 0;
1712 
1713 	if (kernel_getsockname(sock, (struct sockaddr *)&buf) < 0)
1714 		goto out;
1715 	switch (buf.ss_family) {
1716 	case AF_INET6:
1717 		port = ntohs(((struct sockaddr_in6 *)&buf)->sin6_port);
1718 		break;
1719 	case AF_INET:
1720 		port = ntohs(((struct sockaddr_in *)&buf)->sin_port);
1721 	}
1722 out:
1723 	return port;
1724 }
1725 
1726 /**
1727  * xs_set_port - reset the port number in the remote endpoint address
1728  * @xprt: generic transport
1729  * @port: new port number
1730  *
1731  */
xs_set_port(struct rpc_xprt * xprt,unsigned short port)1732 static void xs_set_port(struct rpc_xprt *xprt, unsigned short port)
1733 {
1734 	dprintk("RPC:       setting port for xprt %p to %u\n", xprt, port);
1735 
1736 	rpc_set_port(xs_addr(xprt), port);
1737 	xs_update_peer_port(xprt);
1738 }
1739 
xs_reset_srcport(struct sock_xprt * transport)1740 static void xs_reset_srcport(struct sock_xprt *transport)
1741 {
1742 	transport->srcport = 0;
1743 }
1744 
xs_set_srcport(struct sock_xprt * transport,struct socket * sock)1745 static void xs_set_srcport(struct sock_xprt *transport, struct socket *sock)
1746 {
1747 	if (transport->srcport == 0 && transport->xprt.reuseport)
1748 		transport->srcport = xs_sock_getport(sock);
1749 }
1750 
xs_get_srcport(struct sock_xprt * transport)1751 static int xs_get_srcport(struct sock_xprt *transport)
1752 {
1753 	int port = transport->srcport;
1754 
1755 	if (port == 0 && transport->xprt.resvport)
1756 		port = xs_get_random_port();
1757 	return port;
1758 }
1759 
xs_sock_srcport(struct rpc_xprt * xprt)1760 static unsigned short xs_sock_srcport(struct rpc_xprt *xprt)
1761 {
1762 	struct sock_xprt *sock = container_of(xprt, struct sock_xprt, xprt);
1763 	unsigned short ret = 0;
1764 	mutex_lock(&sock->recv_mutex);
1765 	if (sock->sock)
1766 		ret = xs_sock_getport(sock->sock);
1767 	mutex_unlock(&sock->recv_mutex);
1768 	return ret;
1769 }
1770 
xs_sock_srcaddr(struct rpc_xprt * xprt,char * buf,size_t buflen)1771 static int xs_sock_srcaddr(struct rpc_xprt *xprt, char *buf, size_t buflen)
1772 {
1773 	struct sock_xprt *sock = container_of(xprt, struct sock_xprt, xprt);
1774 	union {
1775 		struct sockaddr sa;
1776 		struct sockaddr_storage st;
1777 	} saddr;
1778 	int ret = -ENOTCONN;
1779 
1780 	mutex_lock(&sock->recv_mutex);
1781 	if (sock->sock) {
1782 		ret = kernel_getsockname(sock->sock, &saddr.sa);
1783 		if (ret >= 0)
1784 			ret = snprintf(buf, buflen, "%pISc", &saddr.sa);
1785 	}
1786 	mutex_unlock(&sock->recv_mutex);
1787 	return ret;
1788 }
1789 
xs_next_srcport(struct sock_xprt * transport,unsigned short port)1790 static unsigned short xs_next_srcport(struct sock_xprt *transport, unsigned short port)
1791 {
1792 	if (transport->srcport != 0)
1793 		transport->srcport = 0;
1794 	if (!transport->xprt.resvport)
1795 		return 0;
1796 	if (port <= xprt_min_resvport || port > xprt_max_resvport)
1797 		return xprt_max_resvport;
1798 	return --port;
1799 }
xs_bind(struct sock_xprt * transport,struct socket * sock)1800 static int xs_bind(struct sock_xprt *transport, struct socket *sock)
1801 {
1802 	struct sockaddr_storage myaddr;
1803 	int err, nloop = 0;
1804 	int port = xs_get_srcport(transport);
1805 	unsigned short last;
1806 
1807 	/*
1808 	 * If we are asking for any ephemeral port (i.e. port == 0 &&
1809 	 * transport->xprt.resvport == 0), don't bind.  Let the local
1810 	 * port selection happen implicitly when the socket is used
1811 	 * (for example at connect time).
1812 	 *
1813 	 * This ensures that we can continue to establish TCP
1814 	 * connections even when all local ephemeral ports are already
1815 	 * a part of some TCP connection.  This makes no difference
1816 	 * for UDP sockets, but also doesn't harm them.
1817 	 *
1818 	 * If we're asking for any reserved port (i.e. port == 0 &&
1819 	 * transport->xprt.resvport == 1) xs_get_srcport above will
1820 	 * ensure that port is non-zero and we will bind as needed.
1821 	 */
1822 	if (port <= 0)
1823 		return port;
1824 
1825 	memcpy(&myaddr, &transport->srcaddr, transport->xprt.addrlen);
1826 	do {
1827 		rpc_set_port((struct sockaddr *)&myaddr, port);
1828 		err = kernel_bind(sock, (struct sockaddr *)&myaddr,
1829 				transport->xprt.addrlen);
1830 		if (err == 0) {
1831 			if (transport->xprt.reuseport)
1832 				transport->srcport = port;
1833 			break;
1834 		}
1835 		last = port;
1836 		port = xs_next_srcport(transport, port);
1837 		if (port > last)
1838 			nloop++;
1839 	} while (err == -EADDRINUSE && nloop != 2);
1840 
1841 	if (myaddr.ss_family == AF_INET)
1842 		dprintk("RPC:       %s %pI4:%u: %s (%d)\n", __func__,
1843 				&((struct sockaddr_in *)&myaddr)->sin_addr,
1844 				port, err ? "failed" : "ok", err);
1845 	else
1846 		dprintk("RPC:       %s %pI6:%u: %s (%d)\n", __func__,
1847 				&((struct sockaddr_in6 *)&myaddr)->sin6_addr,
1848 				port, err ? "failed" : "ok", err);
1849 	return err;
1850 }
1851 
1852 /*
1853  * We don't support autobind on AF_LOCAL sockets
1854  */
xs_local_rpcbind(struct rpc_task * task)1855 static void xs_local_rpcbind(struct rpc_task *task)
1856 {
1857 	xprt_set_bound(task->tk_xprt);
1858 }
1859 
xs_local_set_port(struct rpc_xprt * xprt,unsigned short port)1860 static void xs_local_set_port(struct rpc_xprt *xprt, unsigned short port)
1861 {
1862 }
1863 
1864 #ifdef CONFIG_DEBUG_LOCK_ALLOC
1865 static struct lock_class_key xs_key[3];
1866 static struct lock_class_key xs_slock_key[3];
1867 
xs_reclassify_socketu(struct socket * sock)1868 static inline void xs_reclassify_socketu(struct socket *sock)
1869 {
1870 	struct sock *sk = sock->sk;
1871 
1872 	sock_lock_init_class_and_name(sk, "slock-AF_LOCAL-RPC",
1873 		&xs_slock_key[0], "sk_lock-AF_LOCAL-RPC", &xs_key[0]);
1874 }
1875 
xs_reclassify_socket4(struct socket * sock)1876 static inline void xs_reclassify_socket4(struct socket *sock)
1877 {
1878 	struct sock *sk = sock->sk;
1879 
1880 	sock_lock_init_class_and_name(sk, "slock-AF_INET-RPC",
1881 		&xs_slock_key[1], "sk_lock-AF_INET-RPC", &xs_key[1]);
1882 }
1883 
xs_reclassify_socket6(struct socket * sock)1884 static inline void xs_reclassify_socket6(struct socket *sock)
1885 {
1886 	struct sock *sk = sock->sk;
1887 
1888 	sock_lock_init_class_and_name(sk, "slock-AF_INET6-RPC",
1889 		&xs_slock_key[2], "sk_lock-AF_INET6-RPC", &xs_key[2]);
1890 }
1891 
xs_reclassify_socket(int family,struct socket * sock)1892 static inline void xs_reclassify_socket(int family, struct socket *sock)
1893 {
1894 	if (WARN_ON_ONCE(!sock_allow_reclassification(sock->sk)))
1895 		return;
1896 
1897 	switch (family) {
1898 	case AF_LOCAL:
1899 		xs_reclassify_socketu(sock);
1900 		break;
1901 	case AF_INET:
1902 		xs_reclassify_socket4(sock);
1903 		break;
1904 	case AF_INET6:
1905 		xs_reclassify_socket6(sock);
1906 		break;
1907 	}
1908 }
1909 #else
xs_reclassify_socket(int family,struct socket * sock)1910 static inline void xs_reclassify_socket(int family, struct socket *sock)
1911 {
1912 }
1913 #endif
1914 
xs_dummy_setup_socket(struct work_struct * work)1915 static void xs_dummy_setup_socket(struct work_struct *work)
1916 {
1917 }
1918 
xs_create_sock(struct rpc_xprt * xprt,struct sock_xprt * transport,int family,int type,int protocol,bool reuseport)1919 static struct socket *xs_create_sock(struct rpc_xprt *xprt,
1920 		struct sock_xprt *transport, int family, int type,
1921 		int protocol, bool reuseport)
1922 {
1923 	struct file *filp;
1924 	struct socket *sock;
1925 	int err;
1926 
1927 	err = __sock_create(xprt->xprt_net, family, type, protocol, &sock, 1);
1928 	if (err < 0) {
1929 		dprintk("RPC:       can't create %d transport socket (%d).\n",
1930 				protocol, -err);
1931 		goto out;
1932 	}
1933 	xs_reclassify_socket(family, sock);
1934 
1935 	if (reuseport)
1936 		sock_set_reuseport(sock->sk);
1937 
1938 	err = xs_bind(transport, sock);
1939 	if (err) {
1940 		sock_release(sock);
1941 		goto out;
1942 	}
1943 
1944 	if (protocol == IPPROTO_TCP) {
1945 		__netns_tracker_free(xprt->xprt_net, &sock->sk->ns_tracker, false);
1946 		sock->sk->sk_net_refcnt = 1;
1947 		get_net_track(xprt->xprt_net, &sock->sk->ns_tracker, GFP_KERNEL);
1948 		sock_inuse_add(xprt->xprt_net, 1);
1949 	}
1950 
1951 	filp = sock_alloc_file(sock, O_NONBLOCK, NULL);
1952 	if (IS_ERR(filp))
1953 		return ERR_CAST(filp);
1954 	transport->file = filp;
1955 
1956 	return sock;
1957 out:
1958 	return ERR_PTR(err);
1959 }
1960 
xs_local_finish_connecting(struct rpc_xprt * xprt,struct socket * sock)1961 static int xs_local_finish_connecting(struct rpc_xprt *xprt,
1962 				      struct socket *sock)
1963 {
1964 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt,
1965 									xprt);
1966 
1967 	if (!transport->inet) {
1968 		struct sock *sk = sock->sk;
1969 
1970 		lock_sock(sk);
1971 
1972 		xs_save_old_callbacks(transport, sk);
1973 
1974 		sk->sk_user_data = xprt;
1975 		sk->sk_data_ready = xs_data_ready;
1976 		sk->sk_write_space = xs_udp_write_space;
1977 		sk->sk_state_change = xs_local_state_change;
1978 		sk->sk_error_report = xs_error_report;
1979 		sk->sk_use_task_frag = false;
1980 
1981 		xprt_clear_connected(xprt);
1982 
1983 		/* Reset to new socket */
1984 		transport->sock = sock;
1985 		transport->inet = sk;
1986 
1987 		release_sock(sk);
1988 	}
1989 
1990 	xs_stream_start_connect(transport);
1991 
1992 	return kernel_connect(sock, xs_addr(xprt), xprt->addrlen, 0);
1993 }
1994 
1995 /**
1996  * xs_local_setup_socket - create AF_LOCAL socket, connect to a local endpoint
1997  * @transport: socket transport to connect
1998  */
xs_local_setup_socket(struct sock_xprt * transport)1999 static int xs_local_setup_socket(struct sock_xprt *transport)
2000 {
2001 	struct rpc_xprt *xprt = &transport->xprt;
2002 	struct file *filp;
2003 	struct socket *sock;
2004 	int status;
2005 
2006 	status = __sock_create(xprt->xprt_net, AF_LOCAL,
2007 					SOCK_STREAM, 0, &sock, 1);
2008 	if (status < 0) {
2009 		dprintk("RPC:       can't create AF_LOCAL "
2010 			"transport socket (%d).\n", -status);
2011 		goto out;
2012 	}
2013 	xs_reclassify_socket(AF_LOCAL, sock);
2014 
2015 	filp = sock_alloc_file(sock, O_NONBLOCK, NULL);
2016 	if (IS_ERR(filp)) {
2017 		status = PTR_ERR(filp);
2018 		goto out;
2019 	}
2020 	transport->file = filp;
2021 
2022 	dprintk("RPC:       worker connecting xprt %p via AF_LOCAL to %s\n",
2023 			xprt, xprt->address_strings[RPC_DISPLAY_ADDR]);
2024 
2025 	status = xs_local_finish_connecting(xprt, sock);
2026 	trace_rpc_socket_connect(xprt, sock, status);
2027 	switch (status) {
2028 	case 0:
2029 		dprintk("RPC:       xprt %p connected to %s\n",
2030 				xprt, xprt->address_strings[RPC_DISPLAY_ADDR]);
2031 		xprt->stat.connect_count++;
2032 		xprt->stat.connect_time += (long)jiffies -
2033 					   xprt->stat.connect_start;
2034 		xprt_set_connected(xprt);
2035 		break;
2036 	case -ENOBUFS:
2037 		break;
2038 	case -ENOENT:
2039 		dprintk("RPC:       xprt %p: socket %s does not exist\n",
2040 				xprt, xprt->address_strings[RPC_DISPLAY_ADDR]);
2041 		break;
2042 	case -ECONNREFUSED:
2043 		dprintk("RPC:       xprt %p: connection refused for %s\n",
2044 				xprt, xprt->address_strings[RPC_DISPLAY_ADDR]);
2045 		break;
2046 	default:
2047 		printk(KERN_ERR "%s: unhandled error (%d) connecting to %s\n",
2048 				__func__, -status,
2049 				xprt->address_strings[RPC_DISPLAY_ADDR]);
2050 	}
2051 
2052 out:
2053 	xprt_clear_connecting(xprt);
2054 	xprt_wake_pending_tasks(xprt, status);
2055 	return status;
2056 }
2057 
xs_local_connect(struct rpc_xprt * xprt,struct rpc_task * task)2058 static void xs_local_connect(struct rpc_xprt *xprt, struct rpc_task *task)
2059 {
2060 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
2061 	int ret;
2062 
2063 	if (transport->file)
2064 		goto force_disconnect;
2065 
2066 	if (RPC_IS_ASYNC(task)) {
2067 		/*
2068 		 * We want the AF_LOCAL connect to be resolved in the
2069 		 * filesystem namespace of the process making the rpc
2070 		 * call.  Thus we connect synchronously.
2071 		 *
2072 		 * If we want to support asynchronous AF_LOCAL calls,
2073 		 * we'll need to figure out how to pass a namespace to
2074 		 * connect.
2075 		 */
2076 		rpc_task_set_rpc_status(task, -ENOTCONN);
2077 		goto out_wake;
2078 	}
2079 	ret = xs_local_setup_socket(transport);
2080 	if (ret && !RPC_IS_SOFTCONN(task))
2081 		msleep_interruptible(15000);
2082 	return;
2083 force_disconnect:
2084 	xprt_force_disconnect(xprt);
2085 out_wake:
2086 	xprt_clear_connecting(xprt);
2087 	xprt_wake_pending_tasks(xprt, -ENOTCONN);
2088 }
2089 
2090 #if IS_ENABLED(CONFIG_SUNRPC_SWAP)
2091 /*
2092  * Note that this should be called with XPRT_LOCKED held, or recv_mutex
2093  * held, or when we otherwise know that we have exclusive access to the
2094  * socket, to guard against races with xs_reset_transport.
2095  */
xs_set_memalloc(struct rpc_xprt * xprt)2096 static void xs_set_memalloc(struct rpc_xprt *xprt)
2097 {
2098 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt,
2099 			xprt);
2100 
2101 	/*
2102 	 * If there's no sock, then we have nothing to set. The
2103 	 * reconnecting process will get it for us.
2104 	 */
2105 	if (!transport->inet)
2106 		return;
2107 	if (atomic_read(&xprt->swapper))
2108 		sk_set_memalloc(transport->inet);
2109 }
2110 
2111 /**
2112  * xs_enable_swap - Tag this transport as being used for swap.
2113  * @xprt: transport to tag
2114  *
2115  * Take a reference to this transport on behalf of the rpc_clnt, and
2116  * optionally mark it for swapping if it wasn't already.
2117  */
2118 static int
xs_enable_swap(struct rpc_xprt * xprt)2119 xs_enable_swap(struct rpc_xprt *xprt)
2120 {
2121 	struct sock_xprt *xs = container_of(xprt, struct sock_xprt, xprt);
2122 
2123 	mutex_lock(&xs->recv_mutex);
2124 	if (atomic_inc_return(&xprt->swapper) == 1 &&
2125 	    xs->inet)
2126 		sk_set_memalloc(xs->inet);
2127 	mutex_unlock(&xs->recv_mutex);
2128 	return 0;
2129 }
2130 
2131 /**
2132  * xs_disable_swap - Untag this transport as being used for swap.
2133  * @xprt: transport to tag
2134  *
2135  * Drop a "swapper" reference to this xprt on behalf of the rpc_clnt. If the
2136  * swapper refcount goes to 0, untag the socket as a memalloc socket.
2137  */
2138 static void
xs_disable_swap(struct rpc_xprt * xprt)2139 xs_disable_swap(struct rpc_xprt *xprt)
2140 {
2141 	struct sock_xprt *xs = container_of(xprt, struct sock_xprt, xprt);
2142 
2143 	mutex_lock(&xs->recv_mutex);
2144 	if (atomic_dec_and_test(&xprt->swapper) &&
2145 	    xs->inet)
2146 		sk_clear_memalloc(xs->inet);
2147 	mutex_unlock(&xs->recv_mutex);
2148 }
2149 #else
xs_set_memalloc(struct rpc_xprt * xprt)2150 static void xs_set_memalloc(struct rpc_xprt *xprt)
2151 {
2152 }
2153 
2154 static int
xs_enable_swap(struct rpc_xprt * xprt)2155 xs_enable_swap(struct rpc_xprt *xprt)
2156 {
2157 	return -EINVAL;
2158 }
2159 
2160 static void
xs_disable_swap(struct rpc_xprt * xprt)2161 xs_disable_swap(struct rpc_xprt *xprt)
2162 {
2163 }
2164 #endif
2165 
xs_udp_finish_connecting(struct rpc_xprt * xprt,struct socket * sock)2166 static void xs_udp_finish_connecting(struct rpc_xprt *xprt, struct socket *sock)
2167 {
2168 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
2169 
2170 	if (!transport->inet) {
2171 		struct sock *sk = sock->sk;
2172 
2173 		lock_sock(sk);
2174 
2175 		xs_save_old_callbacks(transport, sk);
2176 
2177 		sk->sk_user_data = xprt;
2178 		sk->sk_data_ready = xs_data_ready;
2179 		sk->sk_write_space = xs_udp_write_space;
2180 		sk->sk_use_task_frag = false;
2181 
2182 		xprt_set_connected(xprt);
2183 
2184 		/* Reset to new socket */
2185 		transport->sock = sock;
2186 		transport->inet = sk;
2187 
2188 		xs_set_memalloc(xprt);
2189 
2190 		release_sock(sk);
2191 	}
2192 	xs_udp_do_set_buffer_size(xprt);
2193 
2194 	xprt->stat.connect_start = jiffies;
2195 }
2196 
xs_udp_setup_socket(struct work_struct * work)2197 static void xs_udp_setup_socket(struct work_struct *work)
2198 {
2199 	struct sock_xprt *transport =
2200 		container_of(work, struct sock_xprt, connect_worker.work);
2201 	struct rpc_xprt *xprt = &transport->xprt;
2202 	struct socket *sock;
2203 	int status = -EIO;
2204 	unsigned int pflags = current->flags;
2205 
2206 	if (atomic_read(&xprt->swapper))
2207 		current->flags |= PF_MEMALLOC;
2208 	sock = xs_create_sock(xprt, transport,
2209 			xs_addr(xprt)->sa_family, SOCK_DGRAM,
2210 			IPPROTO_UDP, false);
2211 	if (IS_ERR(sock))
2212 		goto out;
2213 
2214 	dprintk("RPC:       worker connecting xprt %p via %s to "
2215 				"%s (port %s)\n", xprt,
2216 			xprt->address_strings[RPC_DISPLAY_PROTO],
2217 			xprt->address_strings[RPC_DISPLAY_ADDR],
2218 			xprt->address_strings[RPC_DISPLAY_PORT]);
2219 
2220 	xs_udp_finish_connecting(xprt, sock);
2221 	trace_rpc_socket_connect(xprt, sock, 0);
2222 	status = 0;
2223 out:
2224 	xprt_clear_connecting(xprt);
2225 	xprt_unlock_connect(xprt, transport);
2226 	xprt_wake_pending_tasks(xprt, status);
2227 	current_restore_flags(pflags, PF_MEMALLOC);
2228 }
2229 
2230 /**
2231  * xs_tcp_shutdown - gracefully shut down a TCP socket
2232  * @xprt: transport
2233  *
2234  * Initiates a graceful shutdown of the TCP socket by calling the
2235  * equivalent of shutdown(SHUT_RDWR);
2236  */
xs_tcp_shutdown(struct rpc_xprt * xprt)2237 static void xs_tcp_shutdown(struct rpc_xprt *xprt)
2238 {
2239 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
2240 	struct socket *sock = transport->sock;
2241 	int skst = transport->inet ? transport->inet->sk_state : TCP_CLOSE;
2242 
2243 	if (sock == NULL)
2244 		return;
2245 	if (!xprt->reuseport) {
2246 		xs_close(xprt);
2247 		return;
2248 	}
2249 	switch (skst) {
2250 	case TCP_FIN_WAIT1:
2251 	case TCP_FIN_WAIT2:
2252 	case TCP_LAST_ACK:
2253 		break;
2254 	case TCP_ESTABLISHED:
2255 	case TCP_CLOSE_WAIT:
2256 		kernel_sock_shutdown(sock, SHUT_RDWR);
2257 		trace_rpc_socket_shutdown(xprt, sock);
2258 		break;
2259 	default:
2260 		xs_reset_transport(transport);
2261 	}
2262 }
2263 
xs_tcp_set_socket_timeouts(struct rpc_xprt * xprt,struct socket * sock)2264 static void xs_tcp_set_socket_timeouts(struct rpc_xprt *xprt,
2265 		struct socket *sock)
2266 {
2267 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
2268 	struct net *net = sock_net(sock->sk);
2269 	unsigned long connect_timeout;
2270 	unsigned long syn_retries;
2271 	unsigned int keepidle;
2272 	unsigned int keepcnt;
2273 	unsigned int timeo;
2274 	unsigned long t;
2275 
2276 	spin_lock(&xprt->transport_lock);
2277 	keepidle = DIV_ROUND_UP(xprt->timeout->to_initval, HZ);
2278 	keepcnt = xprt->timeout->to_retries + 1;
2279 	timeo = jiffies_to_msecs(xprt->timeout->to_initval) *
2280 		(xprt->timeout->to_retries + 1);
2281 	clear_bit(XPRT_SOCK_UPD_TIMEOUT, &transport->sock_state);
2282 	spin_unlock(&xprt->transport_lock);
2283 
2284 	/* TCP Keepalive options */
2285 	sock_set_keepalive(sock->sk);
2286 	tcp_sock_set_keepidle(sock->sk, keepidle);
2287 	tcp_sock_set_keepintvl(sock->sk, keepidle);
2288 	tcp_sock_set_keepcnt(sock->sk, keepcnt);
2289 
2290 	/* TCP user timeout (see RFC5482) */
2291 	tcp_sock_set_user_timeout(sock->sk, timeo);
2292 
2293 	/* Connect timeout */
2294 	connect_timeout = max_t(unsigned long,
2295 				DIV_ROUND_UP(xprt->connect_timeout, HZ), 1);
2296 	syn_retries = max_t(unsigned long,
2297 			    READ_ONCE(net->ipv4.sysctl_tcp_syn_retries), 1);
2298 	for (t = 0; t <= syn_retries && (1UL << t) < connect_timeout; t++)
2299 		;
2300 	if (t <= syn_retries)
2301 		tcp_sock_set_syncnt(sock->sk, t - 1);
2302 }
2303 
xs_tcp_do_set_connect_timeout(struct rpc_xprt * xprt,unsigned long connect_timeout)2304 static void xs_tcp_do_set_connect_timeout(struct rpc_xprt *xprt,
2305 					  unsigned long connect_timeout)
2306 {
2307 	struct sock_xprt *transport =
2308 		container_of(xprt, struct sock_xprt, xprt);
2309 	struct rpc_timeout to;
2310 	unsigned long initval;
2311 
2312 	memcpy(&to, xprt->timeout, sizeof(to));
2313 	/* Arbitrary lower limit */
2314 	initval = max_t(unsigned long, connect_timeout, XS_TCP_INIT_REEST_TO);
2315 	to.to_initval = initval;
2316 	to.to_maxval = initval;
2317 	to.to_retries = 0;
2318 	memcpy(&transport->tcp_timeout, &to, sizeof(transport->tcp_timeout));
2319 	xprt->timeout = &transport->tcp_timeout;
2320 	xprt->connect_timeout = connect_timeout;
2321 }
2322 
xs_tcp_set_connect_timeout(struct rpc_xprt * xprt,unsigned long connect_timeout,unsigned long reconnect_timeout)2323 static void xs_tcp_set_connect_timeout(struct rpc_xprt *xprt,
2324 		unsigned long connect_timeout,
2325 		unsigned long reconnect_timeout)
2326 {
2327 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
2328 
2329 	spin_lock(&xprt->transport_lock);
2330 	if (reconnect_timeout < xprt->max_reconnect_timeout)
2331 		xprt->max_reconnect_timeout = reconnect_timeout;
2332 	if (connect_timeout < xprt->connect_timeout)
2333 		xs_tcp_do_set_connect_timeout(xprt, connect_timeout);
2334 	set_bit(XPRT_SOCK_UPD_TIMEOUT, &transport->sock_state);
2335 	spin_unlock(&xprt->transport_lock);
2336 }
2337 
xs_tcp_finish_connecting(struct rpc_xprt * xprt,struct socket * sock)2338 static int xs_tcp_finish_connecting(struct rpc_xprt *xprt, struct socket *sock)
2339 {
2340 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
2341 
2342 	if (!transport->inet) {
2343 		struct sock *sk = sock->sk;
2344 
2345 		/* Avoid temporary address, they are bad for long-lived
2346 		 * connections such as NFS mounts.
2347 		 * RFC4941, section 3.6 suggests that:
2348 		 *    Individual applications, which have specific
2349 		 *    knowledge about the normal duration of connections,
2350 		 *    MAY override this as appropriate.
2351 		 */
2352 		if (xs_addr(xprt)->sa_family == PF_INET6) {
2353 			ip6_sock_set_addr_preferences(sk,
2354 				IPV6_PREFER_SRC_PUBLIC);
2355 		}
2356 
2357 		xs_tcp_set_socket_timeouts(xprt, sock);
2358 		tcp_sock_set_nodelay(sk);
2359 
2360 		lock_sock(sk);
2361 
2362 		xs_save_old_callbacks(transport, sk);
2363 
2364 		sk->sk_user_data = xprt;
2365 		sk->sk_data_ready = xs_data_ready;
2366 		sk->sk_state_change = xs_tcp_state_change;
2367 		sk->sk_write_space = xs_tcp_write_space;
2368 		sk->sk_error_report = xs_error_report;
2369 		sk->sk_use_task_frag = false;
2370 
2371 		/* socket options */
2372 		sock_reset_flag(sk, SOCK_LINGER);
2373 
2374 		xprt_clear_connected(xprt);
2375 
2376 		/* Reset to new socket */
2377 		transport->sock = sock;
2378 		transport->inet = sk;
2379 
2380 		release_sock(sk);
2381 	}
2382 
2383 	if (!xprt_bound(xprt))
2384 		return -ENOTCONN;
2385 
2386 	xs_set_memalloc(xprt);
2387 
2388 	xs_stream_start_connect(transport);
2389 
2390 	/* Tell the socket layer to start connecting... */
2391 	set_bit(XPRT_SOCK_CONNECTING, &transport->sock_state);
2392 	return kernel_connect(sock, xs_addr(xprt), xprt->addrlen, O_NONBLOCK);
2393 }
2394 
2395 /**
2396  * xs_tcp_setup_socket - create a TCP socket and connect to a remote endpoint
2397  * @work: queued work item
2398  *
2399  * Invoked by a work queue tasklet.
2400  */
xs_tcp_setup_socket(struct work_struct * work)2401 static void xs_tcp_setup_socket(struct work_struct *work)
2402 {
2403 	struct sock_xprt *transport =
2404 		container_of(work, struct sock_xprt, connect_worker.work);
2405 	struct socket *sock = transport->sock;
2406 	struct rpc_xprt *xprt = &transport->xprt;
2407 	int status;
2408 	unsigned int pflags = current->flags;
2409 
2410 	if (atomic_read(&xprt->swapper))
2411 		current->flags |= PF_MEMALLOC;
2412 
2413 	if (xprt_connected(xprt))
2414 		goto out;
2415 	if (test_and_clear_bit(XPRT_SOCK_CONNECT_SENT,
2416 			       &transport->sock_state) ||
2417 	    !sock) {
2418 		xs_reset_transport(transport);
2419 		sock = xs_create_sock(xprt, transport, xs_addr(xprt)->sa_family,
2420 				      SOCK_STREAM, IPPROTO_TCP, true);
2421 		if (IS_ERR(sock)) {
2422 			xprt_wake_pending_tasks(xprt, PTR_ERR(sock));
2423 			goto out;
2424 		}
2425 	}
2426 
2427 	dprintk("RPC:       worker connecting xprt %p via %s to "
2428 				"%s (port %s)\n", xprt,
2429 			xprt->address_strings[RPC_DISPLAY_PROTO],
2430 			xprt->address_strings[RPC_DISPLAY_ADDR],
2431 			xprt->address_strings[RPC_DISPLAY_PORT]);
2432 
2433 	status = xs_tcp_finish_connecting(xprt, sock);
2434 	trace_rpc_socket_connect(xprt, sock, status);
2435 	dprintk("RPC:       %p connect status %d connected %d sock state %d\n",
2436 			xprt, -status, xprt_connected(xprt),
2437 			sock->sk->sk_state);
2438 	switch (status) {
2439 	case 0:
2440 	case -EINPROGRESS:
2441 		/* SYN_SENT! */
2442 		set_bit(XPRT_SOCK_CONNECT_SENT, &transport->sock_state);
2443 		if (xprt->reestablish_timeout < XS_TCP_INIT_REEST_TO)
2444 			xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
2445 		fallthrough;
2446 	case -EALREADY:
2447 		goto out_unlock;
2448 	case -EADDRNOTAVAIL:
2449 		/* Source port number is unavailable. Try a new one! */
2450 		transport->srcport = 0;
2451 		status = -EAGAIN;
2452 		break;
2453 	case -EPERM:
2454 		/* Happens, for instance, if a BPF program is preventing
2455 		 * the connect. Remap the error so upper layers can better
2456 		 * deal with it.
2457 		 */
2458 		status = -ECONNREFUSED;
2459 		fallthrough;
2460 	case -EINVAL:
2461 		/* Happens, for instance, if the user specified a link
2462 		 * local IPv6 address without a scope-id.
2463 		 */
2464 	case -ECONNREFUSED:
2465 	case -ECONNRESET:
2466 	case -ENETDOWN:
2467 	case -ENETUNREACH:
2468 	case -EHOSTUNREACH:
2469 	case -EADDRINUSE:
2470 	case -ENOBUFS:
2471 	case -ENOTCONN:
2472 		break;
2473 	default:
2474 		printk("%s: connect returned unhandled error %d\n",
2475 			__func__, status);
2476 		status = -EAGAIN;
2477 	}
2478 
2479 	/* xs_tcp_force_close() wakes tasks with a fixed error code.
2480 	 * We need to wake them first to ensure the correct error code.
2481 	 */
2482 	xprt_wake_pending_tasks(xprt, status);
2483 	xs_tcp_force_close(xprt);
2484 out:
2485 	xprt_clear_connecting(xprt);
2486 out_unlock:
2487 	xprt_unlock_connect(xprt, transport);
2488 	current_restore_flags(pflags, PF_MEMALLOC);
2489 }
2490 
2491 /*
2492  * Transfer the connected socket to @upper_transport, then mark that
2493  * xprt CONNECTED.
2494  */
xs_tcp_tls_finish_connecting(struct rpc_xprt * lower_xprt,struct sock_xprt * upper_transport)2495 static int xs_tcp_tls_finish_connecting(struct rpc_xprt *lower_xprt,
2496 					struct sock_xprt *upper_transport)
2497 {
2498 	struct sock_xprt *lower_transport =
2499 			container_of(lower_xprt, struct sock_xprt, xprt);
2500 	struct rpc_xprt *upper_xprt = &upper_transport->xprt;
2501 
2502 	if (!upper_transport->inet) {
2503 		struct socket *sock = lower_transport->sock;
2504 		struct sock *sk = sock->sk;
2505 
2506 		/* Avoid temporary address, they are bad for long-lived
2507 		 * connections such as NFS mounts.
2508 		 * RFC4941, section 3.6 suggests that:
2509 		 *    Individual applications, which have specific
2510 		 *    knowledge about the normal duration of connections,
2511 		 *    MAY override this as appropriate.
2512 		 */
2513 		if (xs_addr(upper_xprt)->sa_family == PF_INET6)
2514 			ip6_sock_set_addr_preferences(sk, IPV6_PREFER_SRC_PUBLIC);
2515 
2516 		xs_tcp_set_socket_timeouts(upper_xprt, sock);
2517 		tcp_sock_set_nodelay(sk);
2518 
2519 		lock_sock(sk);
2520 
2521 		/* @sk is already connected, so it now has the RPC callbacks.
2522 		 * Reach into @lower_transport to save the original ones.
2523 		 */
2524 		upper_transport->old_data_ready = lower_transport->old_data_ready;
2525 		upper_transport->old_state_change = lower_transport->old_state_change;
2526 		upper_transport->old_write_space = lower_transport->old_write_space;
2527 		upper_transport->old_error_report = lower_transport->old_error_report;
2528 		sk->sk_user_data = upper_xprt;
2529 
2530 		/* socket options */
2531 		sock_reset_flag(sk, SOCK_LINGER);
2532 
2533 		xprt_clear_connected(upper_xprt);
2534 
2535 		upper_transport->sock = sock;
2536 		upper_transport->inet = sk;
2537 		upper_transport->file = lower_transport->file;
2538 
2539 		release_sock(sk);
2540 
2541 		/* Reset lower_transport before shutting down its clnt */
2542 		mutex_lock(&lower_transport->recv_mutex);
2543 		lower_transport->inet = NULL;
2544 		lower_transport->sock = NULL;
2545 		lower_transport->file = NULL;
2546 
2547 		xprt_clear_connected(lower_xprt);
2548 		xs_sock_reset_connection_flags(lower_xprt);
2549 		xs_stream_reset_connect(lower_transport);
2550 		mutex_unlock(&lower_transport->recv_mutex);
2551 	}
2552 
2553 	if (!xprt_bound(upper_xprt))
2554 		return -ENOTCONN;
2555 
2556 	xs_set_memalloc(upper_xprt);
2557 
2558 	if (!xprt_test_and_set_connected(upper_xprt)) {
2559 		upper_xprt->connect_cookie++;
2560 		clear_bit(XPRT_SOCK_CONNECTING, &upper_transport->sock_state);
2561 		xprt_clear_connecting(upper_xprt);
2562 
2563 		upper_xprt->stat.connect_count++;
2564 		upper_xprt->stat.connect_time += (long)jiffies -
2565 					   upper_xprt->stat.connect_start;
2566 		xs_run_error_worker(upper_transport, XPRT_SOCK_WAKE_PENDING);
2567 	}
2568 	return 0;
2569 }
2570 
2571 /**
2572  * xs_tls_handshake_done - TLS handshake completion handler
2573  * @data: address of xprt to wake
2574  * @status: status of handshake
2575  * @peerid: serial number of key containing the remote's identity
2576  *
2577  */
xs_tls_handshake_done(void * data,int status,key_serial_t peerid)2578 static void xs_tls_handshake_done(void *data, int status, key_serial_t peerid)
2579 {
2580 	struct rpc_xprt *lower_xprt = data;
2581 	struct sock_xprt *lower_transport =
2582 				container_of(lower_xprt, struct sock_xprt, xprt);
2583 
2584 	lower_transport->xprt_err = status ? -EACCES : 0;
2585 	complete(&lower_transport->handshake_done);
2586 	xprt_put(lower_xprt);
2587 }
2588 
xs_tls_handshake_sync(struct rpc_xprt * lower_xprt,struct xprtsec_parms * xprtsec)2589 static int xs_tls_handshake_sync(struct rpc_xprt *lower_xprt, struct xprtsec_parms *xprtsec)
2590 {
2591 	struct sock_xprt *lower_transport =
2592 				container_of(lower_xprt, struct sock_xprt, xprt);
2593 	struct tls_handshake_args args = {
2594 		.ta_sock	= lower_transport->sock,
2595 		.ta_done	= xs_tls_handshake_done,
2596 		.ta_data	= xprt_get(lower_xprt),
2597 		.ta_peername	= lower_xprt->servername,
2598 	};
2599 	struct sock *sk = lower_transport->inet;
2600 	int rc;
2601 
2602 	init_completion(&lower_transport->handshake_done);
2603 	set_bit(XPRT_SOCK_IGNORE_RECV, &lower_transport->sock_state);
2604 	lower_transport->xprt_err = -ETIMEDOUT;
2605 	switch (xprtsec->policy) {
2606 	case RPC_XPRTSEC_TLS_ANON:
2607 		rc = tls_client_hello_anon(&args, GFP_KERNEL);
2608 		if (rc)
2609 			goto out_put_xprt;
2610 		break;
2611 	case RPC_XPRTSEC_TLS_X509:
2612 		args.ta_my_cert = xprtsec->cert_serial;
2613 		args.ta_my_privkey = xprtsec->privkey_serial;
2614 		rc = tls_client_hello_x509(&args, GFP_KERNEL);
2615 		if (rc)
2616 			goto out_put_xprt;
2617 		break;
2618 	default:
2619 		rc = -EACCES;
2620 		goto out_put_xprt;
2621 	}
2622 
2623 	rc = wait_for_completion_interruptible_timeout(&lower_transport->handshake_done,
2624 						       XS_TLS_HANDSHAKE_TO);
2625 	if (rc <= 0) {
2626 		tls_handshake_cancel(sk);
2627 		if (rc == 0)
2628 			rc = -ETIMEDOUT;
2629 		goto out_put_xprt;
2630 	}
2631 
2632 	rc = lower_transport->xprt_err;
2633 
2634 out:
2635 	xs_stream_reset_connect(lower_transport);
2636 	clear_bit(XPRT_SOCK_IGNORE_RECV, &lower_transport->sock_state);
2637 	return rc;
2638 
2639 out_put_xprt:
2640 	xprt_put(lower_xprt);
2641 	goto out;
2642 }
2643 
2644 /**
2645  * xs_tcp_tls_setup_socket - establish a TLS session on a TCP socket
2646  * @work: queued work item
2647  *
2648  * Invoked by a work queue tasklet.
2649  *
2650  * For RPC-with-TLS, there is a two-stage connection process.
2651  *
2652  * The "upper-layer xprt" is visible to the RPC consumer. Once it has
2653  * been marked connected, the consumer knows that a TCP connection and
2654  * a TLS session have been established.
2655  *
2656  * A "lower-layer xprt", created in this function, handles the mechanics
2657  * of connecting the TCP socket, performing the RPC_AUTH_TLS probe, and
2658  * then driving the TLS handshake. Once all that is complete, the upper
2659  * layer xprt is marked connected.
2660  */
xs_tcp_tls_setup_socket(struct work_struct * work)2661 static void xs_tcp_tls_setup_socket(struct work_struct *work)
2662 {
2663 	struct sock_xprt *upper_transport =
2664 		container_of(work, struct sock_xprt, connect_worker.work);
2665 	struct rpc_clnt *upper_clnt = upper_transport->clnt;
2666 	struct rpc_xprt *upper_xprt = &upper_transport->xprt;
2667 	struct rpc_create_args args = {
2668 		.net		= upper_xprt->xprt_net,
2669 		.protocol	= upper_xprt->prot,
2670 		.address	= (struct sockaddr *)&upper_xprt->addr,
2671 		.addrsize	= upper_xprt->addrlen,
2672 		.timeout	= upper_clnt->cl_timeout,
2673 		.servername	= upper_xprt->servername,
2674 		.program	= upper_clnt->cl_program,
2675 		.prognumber	= upper_clnt->cl_prog,
2676 		.version	= upper_clnt->cl_vers,
2677 		.authflavor	= RPC_AUTH_TLS,
2678 		.cred		= upper_clnt->cl_cred,
2679 		.xprtsec	= {
2680 			.policy		= RPC_XPRTSEC_NONE,
2681 		},
2682 		.stats		= upper_clnt->cl_stats,
2683 	};
2684 	unsigned int pflags = current->flags;
2685 	struct rpc_clnt *lower_clnt;
2686 	struct rpc_xprt *lower_xprt;
2687 	int status;
2688 
2689 	if (atomic_read(&upper_xprt->swapper))
2690 		current->flags |= PF_MEMALLOC;
2691 
2692 	xs_stream_start_connect(upper_transport);
2693 
2694 	/* This implicitly sends an RPC_AUTH_TLS probe */
2695 	lower_clnt = rpc_create(&args);
2696 	if (IS_ERR(lower_clnt)) {
2697 		trace_rpc_tls_unavailable(upper_clnt, upper_xprt);
2698 		clear_bit(XPRT_SOCK_CONNECTING, &upper_transport->sock_state);
2699 		xprt_clear_connecting(upper_xprt);
2700 		xprt_wake_pending_tasks(upper_xprt, PTR_ERR(lower_clnt));
2701 		xs_run_error_worker(upper_transport, XPRT_SOCK_WAKE_PENDING);
2702 		goto out_unlock;
2703 	}
2704 
2705 	/* RPC_AUTH_TLS probe was successful. Try a TLS handshake on
2706 	 * the lower xprt.
2707 	 */
2708 	rcu_read_lock();
2709 	lower_xprt = rcu_dereference(lower_clnt->cl_xprt);
2710 	rcu_read_unlock();
2711 
2712 	if (wait_on_bit_lock(&lower_xprt->state, XPRT_LOCKED, TASK_KILLABLE))
2713 		goto out_unlock;
2714 
2715 	status = xs_tls_handshake_sync(lower_xprt, &upper_xprt->xprtsec);
2716 	if (status) {
2717 		trace_rpc_tls_not_started(upper_clnt, upper_xprt);
2718 		goto out_close;
2719 	}
2720 
2721 	status = xs_tcp_tls_finish_connecting(lower_xprt, upper_transport);
2722 	if (status)
2723 		goto out_close;
2724 	xprt_release_write(lower_xprt, NULL);
2725 
2726 	trace_rpc_socket_connect(upper_xprt, upper_transport->sock, 0);
2727 	if (!xprt_test_and_set_connected(upper_xprt)) {
2728 		upper_xprt->connect_cookie++;
2729 		clear_bit(XPRT_SOCK_CONNECTING, &upper_transport->sock_state);
2730 		xprt_clear_connecting(upper_xprt);
2731 
2732 		upper_xprt->stat.connect_count++;
2733 		upper_xprt->stat.connect_time += (long)jiffies -
2734 					   upper_xprt->stat.connect_start;
2735 		xs_run_error_worker(upper_transport, XPRT_SOCK_WAKE_PENDING);
2736 	}
2737 	rpc_shutdown_client(lower_clnt);
2738 
2739 out_unlock:
2740 	current_restore_flags(pflags, PF_MEMALLOC);
2741 	upper_transport->clnt = NULL;
2742 	xprt_unlock_connect(upper_xprt, upper_transport);
2743 	return;
2744 
2745 out_close:
2746 	xprt_release_write(lower_xprt, NULL);
2747 	rpc_shutdown_client(lower_clnt);
2748 
2749 	/* xprt_force_disconnect() wakes tasks with a fixed tk_status code.
2750 	 * Wake them first here to ensure they get our tk_status code.
2751 	 */
2752 	xprt_wake_pending_tasks(upper_xprt, status);
2753 	xs_tcp_force_close(upper_xprt);
2754 	xprt_clear_connecting(upper_xprt);
2755 	goto out_unlock;
2756 }
2757 
2758 /**
2759  * xs_connect - connect a socket to a remote endpoint
2760  * @xprt: pointer to transport structure
2761  * @task: address of RPC task that manages state of connect request
2762  *
2763  * TCP: If the remote end dropped the connection, delay reconnecting.
2764  *
2765  * UDP socket connects are synchronous, but we use a work queue anyway
2766  * to guarantee that even unprivileged user processes can set up a
2767  * socket on a privileged port.
2768  *
2769  * If a UDP socket connect fails, the delay behavior here prevents
2770  * retry floods (hard mounts).
2771  */
xs_connect(struct rpc_xprt * xprt,struct rpc_task * task)2772 static void xs_connect(struct rpc_xprt *xprt, struct rpc_task *task)
2773 {
2774 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
2775 	unsigned long delay = 0;
2776 
2777 	WARN_ON_ONCE(!xprt_lock_connect(xprt, task, transport));
2778 
2779 	if (transport->sock != NULL) {
2780 		dprintk("RPC:       xs_connect delayed xprt %p for %lu "
2781 			"seconds\n", xprt, xprt->reestablish_timeout / HZ);
2782 
2783 		delay = xprt_reconnect_delay(xprt);
2784 		xprt_reconnect_backoff(xprt, XS_TCP_INIT_REEST_TO);
2785 
2786 	} else
2787 		dprintk("RPC:       xs_connect scheduled xprt %p\n", xprt);
2788 
2789 	transport->clnt = task->tk_client;
2790 	queue_delayed_work(xprtiod_workqueue,
2791 			&transport->connect_worker,
2792 			delay);
2793 }
2794 
xs_wake_disconnect(struct sock_xprt * transport)2795 static void xs_wake_disconnect(struct sock_xprt *transport)
2796 {
2797 	if (test_and_clear_bit(XPRT_SOCK_WAKE_DISCONNECT, &transport->sock_state))
2798 		xs_tcp_force_close(&transport->xprt);
2799 }
2800 
xs_wake_write(struct sock_xprt * transport)2801 static void xs_wake_write(struct sock_xprt *transport)
2802 {
2803 	if (test_and_clear_bit(XPRT_SOCK_WAKE_WRITE, &transport->sock_state))
2804 		xprt_write_space(&transport->xprt);
2805 }
2806 
xs_wake_error(struct sock_xprt * transport)2807 static void xs_wake_error(struct sock_xprt *transport)
2808 {
2809 	int sockerr;
2810 
2811 	if (!test_and_clear_bit(XPRT_SOCK_WAKE_ERROR, &transport->sock_state))
2812 		return;
2813 	sockerr = xchg(&transport->xprt_err, 0);
2814 	if (sockerr < 0) {
2815 		xprt_wake_pending_tasks(&transport->xprt, sockerr);
2816 		xs_tcp_force_close(&transport->xprt);
2817 	}
2818 }
2819 
xs_wake_pending(struct sock_xprt * transport)2820 static void xs_wake_pending(struct sock_xprt *transport)
2821 {
2822 	if (test_and_clear_bit(XPRT_SOCK_WAKE_PENDING, &transport->sock_state))
2823 		xprt_wake_pending_tasks(&transport->xprt, -EAGAIN);
2824 }
2825 
xs_error_handle(struct work_struct * work)2826 static void xs_error_handle(struct work_struct *work)
2827 {
2828 	struct sock_xprt *transport = container_of(work,
2829 			struct sock_xprt, error_worker);
2830 
2831 	xs_wake_disconnect(transport);
2832 	xs_wake_write(transport);
2833 	xs_wake_error(transport);
2834 	xs_wake_pending(transport);
2835 }
2836 
2837 /**
2838  * xs_local_print_stats - display AF_LOCAL socket-specific stats
2839  * @xprt: rpc_xprt struct containing statistics
2840  * @seq: output file
2841  *
2842  */
xs_local_print_stats(struct rpc_xprt * xprt,struct seq_file * seq)2843 static void xs_local_print_stats(struct rpc_xprt *xprt, struct seq_file *seq)
2844 {
2845 	long idle_time = 0;
2846 
2847 	if (xprt_connected(xprt))
2848 		idle_time = (long)(jiffies - xprt->last_used) / HZ;
2849 
2850 	seq_printf(seq, "\txprt:\tlocal %lu %lu %lu %ld %lu %lu %lu "
2851 			"%llu %llu %lu %llu %llu\n",
2852 			xprt->stat.bind_count,
2853 			xprt->stat.connect_count,
2854 			xprt->stat.connect_time / HZ,
2855 			idle_time,
2856 			xprt->stat.sends,
2857 			xprt->stat.recvs,
2858 			xprt->stat.bad_xids,
2859 			xprt->stat.req_u,
2860 			xprt->stat.bklog_u,
2861 			xprt->stat.max_slots,
2862 			xprt->stat.sending_u,
2863 			xprt->stat.pending_u);
2864 }
2865 
2866 /**
2867  * xs_udp_print_stats - display UDP socket-specific stats
2868  * @xprt: rpc_xprt struct containing statistics
2869  * @seq: output file
2870  *
2871  */
xs_udp_print_stats(struct rpc_xprt * xprt,struct seq_file * seq)2872 static void xs_udp_print_stats(struct rpc_xprt *xprt, struct seq_file *seq)
2873 {
2874 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
2875 
2876 	seq_printf(seq, "\txprt:\tudp %u %lu %lu %lu %lu %llu %llu "
2877 			"%lu %llu %llu\n",
2878 			transport->srcport,
2879 			xprt->stat.bind_count,
2880 			xprt->stat.sends,
2881 			xprt->stat.recvs,
2882 			xprt->stat.bad_xids,
2883 			xprt->stat.req_u,
2884 			xprt->stat.bklog_u,
2885 			xprt->stat.max_slots,
2886 			xprt->stat.sending_u,
2887 			xprt->stat.pending_u);
2888 }
2889 
2890 /**
2891  * xs_tcp_print_stats - display TCP socket-specific stats
2892  * @xprt: rpc_xprt struct containing statistics
2893  * @seq: output file
2894  *
2895  */
xs_tcp_print_stats(struct rpc_xprt * xprt,struct seq_file * seq)2896 static void xs_tcp_print_stats(struct rpc_xprt *xprt, struct seq_file *seq)
2897 {
2898 	struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
2899 	long idle_time = 0;
2900 
2901 	if (xprt_connected(xprt))
2902 		idle_time = (long)(jiffies - xprt->last_used) / HZ;
2903 
2904 	seq_printf(seq, "\txprt:\ttcp %u %lu %lu %lu %ld %lu %lu %lu "
2905 			"%llu %llu %lu %llu %llu\n",
2906 			transport->srcport,
2907 			xprt->stat.bind_count,
2908 			xprt->stat.connect_count,
2909 			xprt->stat.connect_time / HZ,
2910 			idle_time,
2911 			xprt->stat.sends,
2912 			xprt->stat.recvs,
2913 			xprt->stat.bad_xids,
2914 			xprt->stat.req_u,
2915 			xprt->stat.bklog_u,
2916 			xprt->stat.max_slots,
2917 			xprt->stat.sending_u,
2918 			xprt->stat.pending_u);
2919 }
2920 
2921 /*
2922  * Allocate a bunch of pages for a scratch buffer for the rpc code. The reason
2923  * we allocate pages instead doing a kmalloc like rpc_malloc is because we want
2924  * to use the server side send routines.
2925  */
bc_malloc(struct rpc_task * task)2926 static int bc_malloc(struct rpc_task *task)
2927 {
2928 	struct rpc_rqst *rqst = task->tk_rqstp;
2929 	size_t size = rqst->rq_callsize;
2930 	struct page *page;
2931 	struct rpc_buffer *buf;
2932 
2933 	if (size > PAGE_SIZE - sizeof(struct rpc_buffer)) {
2934 		WARN_ONCE(1, "xprtsock: large bc buffer request (size %zu)\n",
2935 			  size);
2936 		return -EINVAL;
2937 	}
2938 
2939 	page = alloc_page(GFP_KERNEL | __GFP_NORETRY | __GFP_NOWARN);
2940 	if (!page)
2941 		return -ENOMEM;
2942 
2943 	buf = page_address(page);
2944 	buf->len = PAGE_SIZE;
2945 
2946 	rqst->rq_buffer = buf->data;
2947 	rqst->rq_rbuffer = (char *)rqst->rq_buffer + rqst->rq_callsize;
2948 	return 0;
2949 }
2950 
2951 /*
2952  * Free the space allocated in the bc_alloc routine
2953  */
bc_free(struct rpc_task * task)2954 static void bc_free(struct rpc_task *task)
2955 {
2956 	void *buffer = task->tk_rqstp->rq_buffer;
2957 	struct rpc_buffer *buf;
2958 
2959 	buf = container_of(buffer, struct rpc_buffer, data);
2960 	free_page((unsigned long)buf);
2961 }
2962 
bc_sendto(struct rpc_rqst * req)2963 static int bc_sendto(struct rpc_rqst *req)
2964 {
2965 	struct xdr_buf *xdr = &req->rq_snd_buf;
2966 	struct sock_xprt *transport =
2967 			container_of(req->rq_xprt, struct sock_xprt, xprt);
2968 	struct msghdr msg = {
2969 		.msg_flags	= 0,
2970 	};
2971 	rpc_fraghdr marker = cpu_to_be32(RPC_LAST_STREAM_FRAGMENT |
2972 					 (u32)xdr->len);
2973 	unsigned int sent = 0;
2974 	int err;
2975 
2976 	req->rq_xtime = ktime_get();
2977 	err = xdr_alloc_bvec(xdr, rpc_task_gfp_mask());
2978 	if (err < 0)
2979 		return err;
2980 	err = xprt_sock_sendmsg(transport->sock, &msg, xdr, 0, marker, &sent);
2981 	xdr_free_bvec(xdr);
2982 	if (err < 0 || sent != (xdr->len + sizeof(marker)))
2983 		return -EAGAIN;
2984 	return sent;
2985 }
2986 
2987 /**
2988  * bc_send_request - Send a backchannel Call on a TCP socket
2989  * @req: rpc_rqst containing Call message to be sent
2990  *
2991  * xpt_mutex ensures @rqstp's whole message is written to the socket
2992  * without interruption.
2993  *
2994  * Return values:
2995  *   %0 if the message was sent successfully
2996  *   %ENOTCONN if the message was not sent
2997  */
bc_send_request(struct rpc_rqst * req)2998 static int bc_send_request(struct rpc_rqst *req)
2999 {
3000 	struct svc_xprt	*xprt;
3001 	int len;
3002 
3003 	/*
3004 	 * Get the server socket associated with this callback xprt
3005 	 */
3006 	xprt = req->rq_xprt->bc_xprt;
3007 
3008 	/*
3009 	 * Grab the mutex to serialize data as the connection is shared
3010 	 * with the fore channel
3011 	 */
3012 	mutex_lock(&xprt->xpt_mutex);
3013 	if (test_bit(XPT_DEAD, &xprt->xpt_flags))
3014 		len = -ENOTCONN;
3015 	else
3016 		len = bc_sendto(req);
3017 	mutex_unlock(&xprt->xpt_mutex);
3018 
3019 	if (len > 0)
3020 		len = 0;
3021 
3022 	return len;
3023 }
3024 
bc_close(struct rpc_xprt * xprt)3025 static void bc_close(struct rpc_xprt *xprt)
3026 {
3027 	xprt_disconnect_done(xprt);
3028 }
3029 
bc_destroy(struct rpc_xprt * xprt)3030 static void bc_destroy(struct rpc_xprt *xprt)
3031 {
3032 	dprintk("RPC:       bc_destroy xprt %p\n", xprt);
3033 
3034 	xs_xprt_free(xprt);
3035 	module_put(THIS_MODULE);
3036 }
3037 
3038 static const struct rpc_xprt_ops xs_local_ops = {
3039 	.reserve_xprt		= xprt_reserve_xprt,
3040 	.release_xprt		= xprt_release_xprt,
3041 	.alloc_slot		= xprt_alloc_slot,
3042 	.free_slot		= xprt_free_slot,
3043 	.rpcbind		= xs_local_rpcbind,
3044 	.set_port		= xs_local_set_port,
3045 	.connect		= xs_local_connect,
3046 	.buf_alloc		= rpc_malloc,
3047 	.buf_free		= rpc_free,
3048 	.prepare_request	= xs_stream_prepare_request,
3049 	.send_request		= xs_local_send_request,
3050 	.abort_send_request	= xs_stream_abort_send_request,
3051 	.wait_for_reply_request	= xprt_wait_for_reply_request_def,
3052 	.close			= xs_close,
3053 	.destroy		= xs_destroy,
3054 	.print_stats		= xs_local_print_stats,
3055 	.enable_swap		= xs_enable_swap,
3056 	.disable_swap		= xs_disable_swap,
3057 };
3058 
3059 static const struct rpc_xprt_ops xs_udp_ops = {
3060 	.set_buffer_size	= xs_udp_set_buffer_size,
3061 	.reserve_xprt		= xprt_reserve_xprt_cong,
3062 	.release_xprt		= xprt_release_xprt_cong,
3063 	.alloc_slot		= xprt_alloc_slot,
3064 	.free_slot		= xprt_free_slot,
3065 	.rpcbind		= rpcb_getport_async,
3066 	.set_port		= xs_set_port,
3067 	.connect		= xs_connect,
3068 	.get_srcaddr		= xs_sock_srcaddr,
3069 	.get_srcport		= xs_sock_srcport,
3070 	.buf_alloc		= rpc_malloc,
3071 	.buf_free		= rpc_free,
3072 	.send_request		= xs_udp_send_request,
3073 	.wait_for_reply_request	= xprt_wait_for_reply_request_rtt,
3074 	.timer			= xs_udp_timer,
3075 	.release_request	= xprt_release_rqst_cong,
3076 	.close			= xs_close,
3077 	.destroy		= xs_destroy,
3078 	.print_stats		= xs_udp_print_stats,
3079 	.enable_swap		= xs_enable_swap,
3080 	.disable_swap		= xs_disable_swap,
3081 	.inject_disconnect	= xs_inject_disconnect,
3082 };
3083 
3084 static const struct rpc_xprt_ops xs_tcp_ops = {
3085 	.reserve_xprt		= xprt_reserve_xprt,
3086 	.release_xprt		= xprt_release_xprt,
3087 	.alloc_slot		= xprt_alloc_slot,
3088 	.free_slot		= xprt_free_slot,
3089 	.rpcbind		= rpcb_getport_async,
3090 	.set_port		= xs_set_port,
3091 	.connect		= xs_connect,
3092 	.get_srcaddr		= xs_sock_srcaddr,
3093 	.get_srcport		= xs_sock_srcport,
3094 	.buf_alloc		= rpc_malloc,
3095 	.buf_free		= rpc_free,
3096 	.prepare_request	= xs_stream_prepare_request,
3097 	.send_request		= xs_tcp_send_request,
3098 	.abort_send_request	= xs_stream_abort_send_request,
3099 	.wait_for_reply_request	= xprt_wait_for_reply_request_def,
3100 	.close			= xs_tcp_shutdown,
3101 	.destroy		= xs_destroy,
3102 	.set_connect_timeout	= xs_tcp_set_connect_timeout,
3103 	.print_stats		= xs_tcp_print_stats,
3104 	.enable_swap		= xs_enable_swap,
3105 	.disable_swap		= xs_disable_swap,
3106 	.inject_disconnect	= xs_inject_disconnect,
3107 #ifdef CONFIG_SUNRPC_BACKCHANNEL
3108 	.bc_setup		= xprt_setup_bc,
3109 	.bc_maxpayload		= xs_tcp_bc_maxpayload,
3110 	.bc_num_slots		= xprt_bc_max_slots,
3111 	.bc_free_rqst		= xprt_free_bc_rqst,
3112 	.bc_destroy		= xprt_destroy_bc,
3113 #endif
3114 };
3115 
3116 /*
3117  * The rpc_xprt_ops for the server backchannel
3118  */
3119 
3120 static const struct rpc_xprt_ops bc_tcp_ops = {
3121 	.reserve_xprt		= xprt_reserve_xprt,
3122 	.release_xprt		= xprt_release_xprt,
3123 	.alloc_slot		= xprt_alloc_slot,
3124 	.free_slot		= xprt_free_slot,
3125 	.buf_alloc		= bc_malloc,
3126 	.buf_free		= bc_free,
3127 	.send_request		= bc_send_request,
3128 	.wait_for_reply_request	= xprt_wait_for_reply_request_def,
3129 	.close			= bc_close,
3130 	.destroy		= bc_destroy,
3131 	.print_stats		= xs_tcp_print_stats,
3132 	.enable_swap		= xs_enable_swap,
3133 	.disable_swap		= xs_disable_swap,
3134 	.inject_disconnect	= xs_inject_disconnect,
3135 };
3136 
xs_init_anyaddr(const int family,struct sockaddr * sap)3137 static int xs_init_anyaddr(const int family, struct sockaddr *sap)
3138 {
3139 	static const struct sockaddr_in sin = {
3140 		.sin_family		= AF_INET,
3141 		.sin_addr.s_addr	= htonl(INADDR_ANY),
3142 	};
3143 	static const struct sockaddr_in6 sin6 = {
3144 		.sin6_family		= AF_INET6,
3145 		.sin6_addr		= IN6ADDR_ANY_INIT,
3146 	};
3147 
3148 	switch (family) {
3149 	case AF_LOCAL:
3150 		break;
3151 	case AF_INET:
3152 		memcpy(sap, &sin, sizeof(sin));
3153 		break;
3154 	case AF_INET6:
3155 		memcpy(sap, &sin6, sizeof(sin6));
3156 		break;
3157 	default:
3158 		dprintk("RPC:       %s: Bad address family\n", __func__);
3159 		return -EAFNOSUPPORT;
3160 	}
3161 	return 0;
3162 }
3163 
xs_setup_xprt(struct xprt_create * args,unsigned int slot_table_size,unsigned int max_slot_table_size)3164 static struct rpc_xprt *xs_setup_xprt(struct xprt_create *args,
3165 				      unsigned int slot_table_size,
3166 				      unsigned int max_slot_table_size)
3167 {
3168 	struct rpc_xprt *xprt;
3169 	struct sock_xprt *new;
3170 
3171 	if (args->addrlen > sizeof(xprt->addr)) {
3172 		dprintk("RPC:       xs_setup_xprt: address too large\n");
3173 		return ERR_PTR(-EBADF);
3174 	}
3175 
3176 	xprt = xprt_alloc(args->net, sizeof(*new), slot_table_size,
3177 			max_slot_table_size);
3178 	if (xprt == NULL) {
3179 		dprintk("RPC:       xs_setup_xprt: couldn't allocate "
3180 				"rpc_xprt\n");
3181 		return ERR_PTR(-ENOMEM);
3182 	}
3183 
3184 	new = container_of(xprt, struct sock_xprt, xprt);
3185 	mutex_init(&new->recv_mutex);
3186 	memcpy(&xprt->addr, args->dstaddr, args->addrlen);
3187 	xprt->addrlen = args->addrlen;
3188 	if (args->srcaddr)
3189 		memcpy(&new->srcaddr, args->srcaddr, args->addrlen);
3190 	else {
3191 		int err;
3192 		err = xs_init_anyaddr(args->dstaddr->sa_family,
3193 					(struct sockaddr *)&new->srcaddr);
3194 		if (err != 0) {
3195 			xprt_free(xprt);
3196 			return ERR_PTR(err);
3197 		}
3198 	}
3199 
3200 	return xprt;
3201 }
3202 
3203 static const struct rpc_timeout xs_local_default_timeout = {
3204 	.to_initval = 10 * HZ,
3205 	.to_maxval = 10 * HZ,
3206 	.to_retries = 2,
3207 };
3208 
3209 /**
3210  * xs_setup_local - Set up transport to use an AF_LOCAL socket
3211  * @args: rpc transport creation arguments
3212  *
3213  * AF_LOCAL is a "tpi_cots_ord" transport, just like TCP
3214  */
xs_setup_local(struct xprt_create * args)3215 static struct rpc_xprt *xs_setup_local(struct xprt_create *args)
3216 {
3217 	struct sockaddr_un *sun = (struct sockaddr_un *)args->dstaddr;
3218 	struct sock_xprt *transport;
3219 	struct rpc_xprt *xprt;
3220 	struct rpc_xprt *ret;
3221 
3222 	xprt = xs_setup_xprt(args, xprt_tcp_slot_table_entries,
3223 			xprt_max_tcp_slot_table_entries);
3224 	if (IS_ERR(xprt))
3225 		return xprt;
3226 	transport = container_of(xprt, struct sock_xprt, xprt);
3227 
3228 	xprt->prot = 0;
3229 	xprt->xprt_class = &xs_local_transport;
3230 	xprt->max_payload = RPC_MAX_FRAGMENT_SIZE;
3231 
3232 	xprt->bind_timeout = XS_BIND_TO;
3233 	xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
3234 	xprt->idle_timeout = XS_IDLE_DISC_TO;
3235 
3236 	xprt->ops = &xs_local_ops;
3237 	xprt->timeout = &xs_local_default_timeout;
3238 
3239 	INIT_WORK(&transport->recv_worker, xs_stream_data_receive_workfn);
3240 	INIT_WORK(&transport->error_worker, xs_error_handle);
3241 	INIT_DELAYED_WORK(&transport->connect_worker, xs_dummy_setup_socket);
3242 
3243 	switch (sun->sun_family) {
3244 	case AF_LOCAL:
3245 		if (sun->sun_path[0] != '/' && sun->sun_path[0] != '\0') {
3246 			dprintk("RPC:       bad AF_LOCAL address: %s\n",
3247 					sun->sun_path);
3248 			ret = ERR_PTR(-EINVAL);
3249 			goto out_err;
3250 		}
3251 		xprt_set_bound(xprt);
3252 		xs_format_peer_addresses(xprt, "local", RPCBIND_NETID_LOCAL);
3253 		break;
3254 	default:
3255 		ret = ERR_PTR(-EAFNOSUPPORT);
3256 		goto out_err;
3257 	}
3258 
3259 	dprintk("RPC:       set up xprt to %s via AF_LOCAL\n",
3260 			xprt->address_strings[RPC_DISPLAY_ADDR]);
3261 
3262 	if (try_module_get(THIS_MODULE))
3263 		return xprt;
3264 	ret = ERR_PTR(-EINVAL);
3265 out_err:
3266 	xs_xprt_free(xprt);
3267 	return ret;
3268 }
3269 
3270 static const struct rpc_timeout xs_udp_default_timeout = {
3271 	.to_initval = 5 * HZ,
3272 	.to_maxval = 30 * HZ,
3273 	.to_increment = 5 * HZ,
3274 	.to_retries = 5,
3275 };
3276 
3277 /**
3278  * xs_setup_udp - Set up transport to use a UDP socket
3279  * @args: rpc transport creation arguments
3280  *
3281  */
xs_setup_udp(struct xprt_create * args)3282 static struct rpc_xprt *xs_setup_udp(struct xprt_create *args)
3283 {
3284 	struct sockaddr *addr = args->dstaddr;
3285 	struct rpc_xprt *xprt;
3286 	struct sock_xprt *transport;
3287 	struct rpc_xprt *ret;
3288 
3289 	xprt = xs_setup_xprt(args, xprt_udp_slot_table_entries,
3290 			xprt_udp_slot_table_entries);
3291 	if (IS_ERR(xprt))
3292 		return xprt;
3293 	transport = container_of(xprt, struct sock_xprt, xprt);
3294 
3295 	xprt->prot = IPPROTO_UDP;
3296 	xprt->xprt_class = &xs_udp_transport;
3297 	/* XXX: header size can vary due to auth type, IPv6, etc. */
3298 	xprt->max_payload = (1U << 16) - (MAX_HEADER << 3);
3299 
3300 	xprt->bind_timeout = XS_BIND_TO;
3301 	xprt->reestablish_timeout = XS_UDP_REEST_TO;
3302 	xprt->idle_timeout = XS_IDLE_DISC_TO;
3303 
3304 	xprt->ops = &xs_udp_ops;
3305 
3306 	xprt->timeout = &xs_udp_default_timeout;
3307 
3308 	INIT_WORK(&transport->recv_worker, xs_udp_data_receive_workfn);
3309 	INIT_WORK(&transport->error_worker, xs_error_handle);
3310 	INIT_DELAYED_WORK(&transport->connect_worker, xs_udp_setup_socket);
3311 
3312 	switch (addr->sa_family) {
3313 	case AF_INET:
3314 		if (((struct sockaddr_in *)addr)->sin_port != htons(0))
3315 			xprt_set_bound(xprt);
3316 
3317 		xs_format_peer_addresses(xprt, "udp", RPCBIND_NETID_UDP);
3318 		break;
3319 	case AF_INET6:
3320 		if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
3321 			xprt_set_bound(xprt);
3322 
3323 		xs_format_peer_addresses(xprt, "udp", RPCBIND_NETID_UDP6);
3324 		break;
3325 	default:
3326 		ret = ERR_PTR(-EAFNOSUPPORT);
3327 		goto out_err;
3328 	}
3329 
3330 	if (xprt_bound(xprt))
3331 		dprintk("RPC:       set up xprt to %s (port %s) via %s\n",
3332 				xprt->address_strings[RPC_DISPLAY_ADDR],
3333 				xprt->address_strings[RPC_DISPLAY_PORT],
3334 				xprt->address_strings[RPC_DISPLAY_PROTO]);
3335 	else
3336 		dprintk("RPC:       set up xprt to %s (autobind) via %s\n",
3337 				xprt->address_strings[RPC_DISPLAY_ADDR],
3338 				xprt->address_strings[RPC_DISPLAY_PROTO]);
3339 
3340 	if (try_module_get(THIS_MODULE))
3341 		return xprt;
3342 	ret = ERR_PTR(-EINVAL);
3343 out_err:
3344 	xs_xprt_free(xprt);
3345 	return ret;
3346 }
3347 
3348 static const struct rpc_timeout xs_tcp_default_timeout = {
3349 	.to_initval = 60 * HZ,
3350 	.to_maxval = 60 * HZ,
3351 	.to_retries = 2,
3352 };
3353 
3354 /**
3355  * xs_setup_tcp - Set up transport to use a TCP socket
3356  * @args: rpc transport creation arguments
3357  *
3358  */
xs_setup_tcp(struct xprt_create * args)3359 static struct rpc_xprt *xs_setup_tcp(struct xprt_create *args)
3360 {
3361 	struct sockaddr *addr = args->dstaddr;
3362 	struct rpc_xprt *xprt;
3363 	struct sock_xprt *transport;
3364 	struct rpc_xprt *ret;
3365 	unsigned int max_slot_table_size = xprt_max_tcp_slot_table_entries;
3366 
3367 	if (args->flags & XPRT_CREATE_INFINITE_SLOTS)
3368 		max_slot_table_size = RPC_MAX_SLOT_TABLE_LIMIT;
3369 
3370 	xprt = xs_setup_xprt(args, xprt_tcp_slot_table_entries,
3371 			max_slot_table_size);
3372 	if (IS_ERR(xprt))
3373 		return xprt;
3374 	transport = container_of(xprt, struct sock_xprt, xprt);
3375 
3376 	xprt->prot = IPPROTO_TCP;
3377 	xprt->xprt_class = &xs_tcp_transport;
3378 	xprt->max_payload = RPC_MAX_FRAGMENT_SIZE;
3379 
3380 	xprt->bind_timeout = XS_BIND_TO;
3381 	xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
3382 	xprt->idle_timeout = XS_IDLE_DISC_TO;
3383 
3384 	xprt->ops = &xs_tcp_ops;
3385 	xprt->timeout = &xs_tcp_default_timeout;
3386 
3387 	xprt->max_reconnect_timeout = xprt->timeout->to_maxval;
3388 	if (args->reconnect_timeout)
3389 		xprt->max_reconnect_timeout = args->reconnect_timeout;
3390 
3391 	xprt->connect_timeout = xprt->timeout->to_initval *
3392 		(xprt->timeout->to_retries + 1);
3393 	if (args->connect_timeout)
3394 		xs_tcp_do_set_connect_timeout(xprt, args->connect_timeout);
3395 
3396 	INIT_WORK(&transport->recv_worker, xs_stream_data_receive_workfn);
3397 	INIT_WORK(&transport->error_worker, xs_error_handle);
3398 	INIT_DELAYED_WORK(&transport->connect_worker, xs_tcp_setup_socket);
3399 
3400 	switch (addr->sa_family) {
3401 	case AF_INET:
3402 		if (((struct sockaddr_in *)addr)->sin_port != htons(0))
3403 			xprt_set_bound(xprt);
3404 
3405 		xs_format_peer_addresses(xprt, "tcp", RPCBIND_NETID_TCP);
3406 		break;
3407 	case AF_INET6:
3408 		if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
3409 			xprt_set_bound(xprt);
3410 
3411 		xs_format_peer_addresses(xprt, "tcp", RPCBIND_NETID_TCP6);
3412 		break;
3413 	default:
3414 		ret = ERR_PTR(-EAFNOSUPPORT);
3415 		goto out_err;
3416 	}
3417 
3418 	if (xprt_bound(xprt))
3419 		dprintk("RPC:       set up xprt to %s (port %s) via %s\n",
3420 				xprt->address_strings[RPC_DISPLAY_ADDR],
3421 				xprt->address_strings[RPC_DISPLAY_PORT],
3422 				xprt->address_strings[RPC_DISPLAY_PROTO]);
3423 	else
3424 		dprintk("RPC:       set up xprt to %s (autobind) via %s\n",
3425 				xprt->address_strings[RPC_DISPLAY_ADDR],
3426 				xprt->address_strings[RPC_DISPLAY_PROTO]);
3427 
3428 	if (try_module_get(THIS_MODULE))
3429 		return xprt;
3430 	ret = ERR_PTR(-EINVAL);
3431 out_err:
3432 	xs_xprt_free(xprt);
3433 	return ret;
3434 }
3435 
3436 /**
3437  * xs_setup_tcp_tls - Set up transport to use a TCP with TLS
3438  * @args: rpc transport creation arguments
3439  *
3440  */
xs_setup_tcp_tls(struct xprt_create * args)3441 static struct rpc_xprt *xs_setup_tcp_tls(struct xprt_create *args)
3442 {
3443 	struct sockaddr *addr = args->dstaddr;
3444 	struct rpc_xprt *xprt;
3445 	struct sock_xprt *transport;
3446 	struct rpc_xprt *ret;
3447 	unsigned int max_slot_table_size = xprt_max_tcp_slot_table_entries;
3448 
3449 	if (args->flags & XPRT_CREATE_INFINITE_SLOTS)
3450 		max_slot_table_size = RPC_MAX_SLOT_TABLE_LIMIT;
3451 
3452 	xprt = xs_setup_xprt(args, xprt_tcp_slot_table_entries,
3453 			     max_slot_table_size);
3454 	if (IS_ERR(xprt))
3455 		return xprt;
3456 	transport = container_of(xprt, struct sock_xprt, xprt);
3457 
3458 	xprt->prot = IPPROTO_TCP;
3459 	xprt->xprt_class = &xs_tcp_transport;
3460 	xprt->max_payload = RPC_MAX_FRAGMENT_SIZE;
3461 
3462 	xprt->bind_timeout = XS_BIND_TO;
3463 	xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
3464 	xprt->idle_timeout = XS_IDLE_DISC_TO;
3465 
3466 	xprt->ops = &xs_tcp_ops;
3467 	xprt->timeout = &xs_tcp_default_timeout;
3468 
3469 	xprt->max_reconnect_timeout = xprt->timeout->to_maxval;
3470 	xprt->connect_timeout = xprt->timeout->to_initval *
3471 		(xprt->timeout->to_retries + 1);
3472 
3473 	INIT_WORK(&transport->recv_worker, xs_stream_data_receive_workfn);
3474 	INIT_WORK(&transport->error_worker, xs_error_handle);
3475 
3476 	switch (args->xprtsec.policy) {
3477 	case RPC_XPRTSEC_TLS_ANON:
3478 	case RPC_XPRTSEC_TLS_X509:
3479 		xprt->xprtsec = args->xprtsec;
3480 		INIT_DELAYED_WORK(&transport->connect_worker,
3481 				  xs_tcp_tls_setup_socket);
3482 		break;
3483 	default:
3484 		ret = ERR_PTR(-EACCES);
3485 		goto out_err;
3486 	}
3487 
3488 	switch (addr->sa_family) {
3489 	case AF_INET:
3490 		if (((struct sockaddr_in *)addr)->sin_port != htons(0))
3491 			xprt_set_bound(xprt);
3492 
3493 		xs_format_peer_addresses(xprt, "tcp", RPCBIND_NETID_TCP);
3494 		break;
3495 	case AF_INET6:
3496 		if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
3497 			xprt_set_bound(xprt);
3498 
3499 		xs_format_peer_addresses(xprt, "tcp", RPCBIND_NETID_TCP6);
3500 		break;
3501 	default:
3502 		ret = ERR_PTR(-EAFNOSUPPORT);
3503 		goto out_err;
3504 	}
3505 
3506 	if (xprt_bound(xprt))
3507 		dprintk("RPC:       set up xprt to %s (port %s) via %s\n",
3508 			xprt->address_strings[RPC_DISPLAY_ADDR],
3509 			xprt->address_strings[RPC_DISPLAY_PORT],
3510 			xprt->address_strings[RPC_DISPLAY_PROTO]);
3511 	else
3512 		dprintk("RPC:       set up xprt to %s (autobind) via %s\n",
3513 			xprt->address_strings[RPC_DISPLAY_ADDR],
3514 			xprt->address_strings[RPC_DISPLAY_PROTO]);
3515 
3516 	if (try_module_get(THIS_MODULE))
3517 		return xprt;
3518 	ret = ERR_PTR(-EINVAL);
3519 out_err:
3520 	xs_xprt_free(xprt);
3521 	return ret;
3522 }
3523 
3524 /**
3525  * xs_setup_bc_tcp - Set up transport to use a TCP backchannel socket
3526  * @args: rpc transport creation arguments
3527  *
3528  */
xs_setup_bc_tcp(struct xprt_create * args)3529 static struct rpc_xprt *xs_setup_bc_tcp(struct xprt_create *args)
3530 {
3531 	struct sockaddr *addr = args->dstaddr;
3532 	struct rpc_xprt *xprt;
3533 	struct sock_xprt *transport;
3534 	struct svc_sock *bc_sock;
3535 	struct rpc_xprt *ret;
3536 
3537 	xprt = xs_setup_xprt(args, xprt_tcp_slot_table_entries,
3538 			xprt_tcp_slot_table_entries);
3539 	if (IS_ERR(xprt))
3540 		return xprt;
3541 	transport = container_of(xprt, struct sock_xprt, xprt);
3542 
3543 	xprt->prot = IPPROTO_TCP;
3544 	xprt->xprt_class = &xs_bc_tcp_transport;
3545 	xprt->max_payload = RPC_MAX_FRAGMENT_SIZE;
3546 	xprt->timeout = &xs_tcp_default_timeout;
3547 
3548 	/* backchannel */
3549 	xprt_set_bound(xprt);
3550 	xprt->bind_timeout = 0;
3551 	xprt->reestablish_timeout = 0;
3552 	xprt->idle_timeout = 0;
3553 
3554 	xprt->ops = &bc_tcp_ops;
3555 
3556 	switch (addr->sa_family) {
3557 	case AF_INET:
3558 		xs_format_peer_addresses(xprt, "tcp",
3559 					 RPCBIND_NETID_TCP);
3560 		break;
3561 	case AF_INET6:
3562 		xs_format_peer_addresses(xprt, "tcp",
3563 				   RPCBIND_NETID_TCP6);
3564 		break;
3565 	default:
3566 		ret = ERR_PTR(-EAFNOSUPPORT);
3567 		goto out_err;
3568 	}
3569 
3570 	dprintk("RPC:       set up xprt to %s (port %s) via %s\n",
3571 			xprt->address_strings[RPC_DISPLAY_ADDR],
3572 			xprt->address_strings[RPC_DISPLAY_PORT],
3573 			xprt->address_strings[RPC_DISPLAY_PROTO]);
3574 
3575 	/*
3576 	 * Once we've associated a backchannel xprt with a connection,
3577 	 * we want to keep it around as long as the connection lasts,
3578 	 * in case we need to start using it for a backchannel again;
3579 	 * this reference won't be dropped until bc_xprt is destroyed.
3580 	 */
3581 	xprt_get(xprt);
3582 	args->bc_xprt->xpt_bc_xprt = xprt;
3583 	xprt->bc_xprt = args->bc_xprt;
3584 	bc_sock = container_of(args->bc_xprt, struct svc_sock, sk_xprt);
3585 	transport->sock = bc_sock->sk_sock;
3586 	transport->inet = bc_sock->sk_sk;
3587 
3588 	/*
3589 	 * Since we don't want connections for the backchannel, we set
3590 	 * the xprt status to connected
3591 	 */
3592 	xprt_set_connected(xprt);
3593 
3594 	if (try_module_get(THIS_MODULE))
3595 		return xprt;
3596 
3597 	args->bc_xprt->xpt_bc_xprt = NULL;
3598 	args->bc_xprt->xpt_bc_xps = NULL;
3599 	xprt_put(xprt);
3600 	ret = ERR_PTR(-EINVAL);
3601 out_err:
3602 	xs_xprt_free(xprt);
3603 	return ret;
3604 }
3605 
3606 static struct xprt_class	xs_local_transport = {
3607 	.list		= LIST_HEAD_INIT(xs_local_transport.list),
3608 	.name		= "named UNIX socket",
3609 	.owner		= THIS_MODULE,
3610 	.ident		= XPRT_TRANSPORT_LOCAL,
3611 	.setup		= xs_setup_local,
3612 	.netid		= { "" },
3613 };
3614 
3615 static struct xprt_class	xs_udp_transport = {
3616 	.list		= LIST_HEAD_INIT(xs_udp_transport.list),
3617 	.name		= "udp",
3618 	.owner		= THIS_MODULE,
3619 	.ident		= XPRT_TRANSPORT_UDP,
3620 	.setup		= xs_setup_udp,
3621 	.netid		= { "udp", "udp6", "" },
3622 };
3623 
3624 static struct xprt_class	xs_tcp_transport = {
3625 	.list		= LIST_HEAD_INIT(xs_tcp_transport.list),
3626 	.name		= "tcp",
3627 	.owner		= THIS_MODULE,
3628 	.ident		= XPRT_TRANSPORT_TCP,
3629 	.setup		= xs_setup_tcp,
3630 	.netid		= { "tcp", "tcp6", "" },
3631 };
3632 
3633 static struct xprt_class	xs_tcp_tls_transport = {
3634 	.list		= LIST_HEAD_INIT(xs_tcp_tls_transport.list),
3635 	.name		= "tcp-with-tls",
3636 	.owner		= THIS_MODULE,
3637 	.ident		= XPRT_TRANSPORT_TCP_TLS,
3638 	.setup		= xs_setup_tcp_tls,
3639 	.netid		= { "tcp", "tcp6", "" },
3640 };
3641 
3642 static struct xprt_class	xs_bc_tcp_transport = {
3643 	.list		= LIST_HEAD_INIT(xs_bc_tcp_transport.list),
3644 	.name		= "tcp NFSv4.1 backchannel",
3645 	.owner		= THIS_MODULE,
3646 	.ident		= XPRT_TRANSPORT_BC_TCP,
3647 	.setup		= xs_setup_bc_tcp,
3648 	.netid		= { "" },
3649 };
3650 
3651 /**
3652  * init_socket_xprt - set up xprtsock's sysctls, register with RPC client
3653  *
3654  */
init_socket_xprt(void)3655 int init_socket_xprt(void)
3656 {
3657 	if (!sunrpc_table_header)
3658 		sunrpc_table_header = register_sysctl("sunrpc", xs_tunables_table);
3659 
3660 	xprt_register_transport(&xs_local_transport);
3661 	xprt_register_transport(&xs_udp_transport);
3662 	xprt_register_transport(&xs_tcp_transport);
3663 	xprt_register_transport(&xs_tcp_tls_transport);
3664 	xprt_register_transport(&xs_bc_tcp_transport);
3665 
3666 	return 0;
3667 }
3668 
3669 /**
3670  * cleanup_socket_xprt - remove xprtsock's sysctls, unregister
3671  *
3672  */
cleanup_socket_xprt(void)3673 void cleanup_socket_xprt(void)
3674 {
3675 	if (sunrpc_table_header) {
3676 		unregister_sysctl_table(sunrpc_table_header);
3677 		sunrpc_table_header = NULL;
3678 	}
3679 
3680 	xprt_unregister_transport(&xs_local_transport);
3681 	xprt_unregister_transport(&xs_udp_transport);
3682 	xprt_unregister_transport(&xs_tcp_transport);
3683 	xprt_unregister_transport(&xs_tcp_tls_transport);
3684 	xprt_unregister_transport(&xs_bc_tcp_transport);
3685 }
3686 
param_set_portnr(const char * val,const struct kernel_param * kp)3687 static int param_set_portnr(const char *val, const struct kernel_param *kp)
3688 {
3689 	return param_set_uint_minmax(val, kp,
3690 			RPC_MIN_RESVPORT,
3691 			RPC_MAX_RESVPORT);
3692 }
3693 
3694 static const struct kernel_param_ops param_ops_portnr = {
3695 	.set = param_set_portnr,
3696 	.get = param_get_uint,
3697 };
3698 
3699 #define param_check_portnr(name, p) \
3700 	__param_check(name, p, unsigned int);
3701 
3702 module_param_named(min_resvport, xprt_min_resvport, portnr, 0644);
3703 module_param_named(max_resvport, xprt_max_resvport, portnr, 0644);
3704 
param_set_slot_table_size(const char * val,const struct kernel_param * kp)3705 static int param_set_slot_table_size(const char *val,
3706 				     const struct kernel_param *kp)
3707 {
3708 	return param_set_uint_minmax(val, kp,
3709 			RPC_MIN_SLOT_TABLE,
3710 			RPC_MAX_SLOT_TABLE);
3711 }
3712 
3713 static const struct kernel_param_ops param_ops_slot_table_size = {
3714 	.set = param_set_slot_table_size,
3715 	.get = param_get_uint,
3716 };
3717 
3718 #define param_check_slot_table_size(name, p) \
3719 	__param_check(name, p, unsigned int);
3720 
param_set_max_slot_table_size(const char * val,const struct kernel_param * kp)3721 static int param_set_max_slot_table_size(const char *val,
3722 				     const struct kernel_param *kp)
3723 {
3724 	return param_set_uint_minmax(val, kp,
3725 			RPC_MIN_SLOT_TABLE,
3726 			RPC_MAX_SLOT_TABLE_LIMIT);
3727 }
3728 
3729 static const struct kernel_param_ops param_ops_max_slot_table_size = {
3730 	.set = param_set_max_slot_table_size,
3731 	.get = param_get_uint,
3732 };
3733 
3734 #define param_check_max_slot_table_size(name, p) \
3735 	__param_check(name, p, unsigned int);
3736 
3737 module_param_named(tcp_slot_table_entries, xprt_tcp_slot_table_entries,
3738 		   slot_table_size, 0644);
3739 module_param_named(tcp_max_slot_table_entries, xprt_max_tcp_slot_table_entries,
3740 		   max_slot_table_size, 0644);
3741 module_param_named(udp_slot_table_entries, xprt_udp_slot_table_entries,
3742 		   slot_table_size, 0644);
3743