xref: /linux/net/rds/recv.c (revision 3fe64a5f670dbd6c7c84c2345b0b9726b3b79b31)
1 /*
2  * Copyright (c) 2006, 2019 Oracle and/or its affiliates. All rights reserved.
3  *
4  * This software is available to you under a choice of one of two
5  * licenses.  You may choose to be licensed under the terms of the GNU
6  * General Public License (GPL) Version 2, available from the file
7  * COPYING in the main directory of this source tree, or the
8  * OpenIB.org BSD license below:
9  *
10  *     Redistribution and use in source and binary forms, with or
11  *     without modification, are permitted provided that the following
12  *     conditions are met:
13  *
14  *      - Redistributions of source code must retain the above
15  *        copyright notice, this list of conditions and the following
16  *        disclaimer.
17  *
18  *      - Redistributions in binary form must reproduce the above
19  *        copyright notice, this list of conditions and the following
20  *        disclaimer in the documentation and/or other materials
21  *        provided with the distribution.
22  *
23  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
27  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
28  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
29  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30  * SOFTWARE.
31  *
32  */
33 #include <linux/kernel.h>
34 #include <linux/slab.h>
35 #include <net/sock.h>
36 #include <linux/in.h>
37 #include <linux/export.h>
38 #include <linux/sched/clock.h>
39 #include <linux/time.h>
40 #include <linux/rds.h>
41 
42 #include "rds.h"
43 
44 void rds_inc_init(struct rds_incoming *inc, struct rds_connection *conn,
45 		 struct in6_addr *saddr)
46 {
47 	refcount_set(&inc->i_refcount, 1);
48 	INIT_LIST_HEAD(&inc->i_item);
49 	inc->i_conn = conn;
50 	inc->i_conn_path = NULL;
51 	inc->i_saddr = *saddr;
52 	inc->i_usercopy.rdma_cookie = 0;
53 	inc->i_usercopy.rx_tstamp = ktime_set(0, 0);
54 
55 	memset(inc->i_rx_lat_trace, 0, sizeof(inc->i_rx_lat_trace));
56 }
57 EXPORT_SYMBOL_GPL(rds_inc_init);
58 
59 void rds_inc_path_init(struct rds_incoming *inc, struct rds_conn_path *cp,
60 		       struct in6_addr  *saddr)
61 {
62 	refcount_set(&inc->i_refcount, 1);
63 	INIT_LIST_HEAD(&inc->i_item);
64 	inc->i_conn = cp->cp_conn;
65 	inc->i_conn_path = cp;
66 	inc->i_saddr = *saddr;
67 	inc->i_usercopy.rdma_cookie = 0;
68 	inc->i_usercopy.rx_tstamp = ktime_set(0, 0);
69 
70 	memset(inc->i_rx_lat_trace, 0, sizeof(inc->i_rx_lat_trace));
71 }
72 EXPORT_SYMBOL_GPL(rds_inc_path_init);
73 
74 static void rds_inc_addref(struct rds_incoming *inc)
75 {
76 	rdsdebug("addref inc %p ref %d\n", inc, refcount_read(&inc->i_refcount));
77 	refcount_inc(&inc->i_refcount);
78 }
79 
80 void rds_inc_put(struct rds_incoming *inc)
81 {
82 	rdsdebug("put inc %p ref %d\n", inc, refcount_read(&inc->i_refcount));
83 	if (refcount_dec_and_test(&inc->i_refcount)) {
84 		BUG_ON(!list_empty(&inc->i_item));
85 
86 		inc->i_conn->c_trans->inc_free(inc);
87 	}
88 }
89 EXPORT_SYMBOL_GPL(rds_inc_put);
90 
91 static void rds_recv_rcvbuf_delta(struct rds_sock *rs, struct sock *sk,
92 				  struct rds_cong_map *map,
93 				  int delta, __be16 port)
94 {
95 	int now_congested;
96 
97 	if (delta == 0)
98 		return;
99 
100 	rs->rs_rcv_bytes += delta;
101 	if (delta > 0)
102 		rds_stats_add(s_recv_bytes_added_to_socket, delta);
103 	else
104 		rds_stats_add(s_recv_bytes_removed_from_socket, -delta);
105 
106 	/* loop transport doesn't send/recv congestion updates */
107 	if (rs->rs_transport->t_type == RDS_TRANS_LOOP)
108 		return;
109 
110 	now_congested = rs->rs_rcv_bytes > rds_sk_rcvbuf(rs);
111 
112 	rdsdebug("rs %p (%pI6c:%u) recv bytes %d buf %d "
113 	  "now_cong %d delta %d\n",
114 	  rs, &rs->rs_bound_addr,
115 	  ntohs(rs->rs_bound_port), rs->rs_rcv_bytes,
116 	  rds_sk_rcvbuf(rs), now_congested, delta);
117 
118 	/* wasn't -> am congested */
119 	if (!rs->rs_congested && now_congested) {
120 		rs->rs_congested = 1;
121 		rds_cong_set_bit(map, port);
122 		rds_cong_queue_updates(map);
123 	}
124 	/* was -> aren't congested */
125 	/* Require more free space before reporting uncongested to prevent
126 	   bouncing cong/uncong state too often */
127 	else if (rs->rs_congested && (rs->rs_rcv_bytes < (rds_sk_rcvbuf(rs)/2))) {
128 		rs->rs_congested = 0;
129 		rds_cong_clear_bit(map, port);
130 		rds_cong_queue_updates(map);
131 	}
132 
133 	/* do nothing if no change in cong state */
134 }
135 
136 static void rds_conn_peer_gen_update(struct rds_connection *conn,
137 				     u32 peer_gen_num)
138 {
139 	int i;
140 	struct rds_message *rm, *tmp;
141 	unsigned long flags;
142 
143 	WARN_ON(conn->c_trans->t_type != RDS_TRANS_TCP);
144 	if (peer_gen_num != 0) {
145 		if (conn->c_peer_gen_num != 0 &&
146 		    peer_gen_num != conn->c_peer_gen_num) {
147 			for (i = 0; i < RDS_MPATH_WORKERS; i++) {
148 				struct rds_conn_path *cp;
149 
150 				cp = &conn->c_path[i];
151 				spin_lock_irqsave(&cp->cp_lock, flags);
152 				cp->cp_next_tx_seq = 1;
153 				cp->cp_next_rx_seq = 0;
154 				list_for_each_entry_safe(rm, tmp,
155 							 &cp->cp_retrans,
156 							 m_conn_item) {
157 					set_bit(RDS_MSG_FLUSH, &rm->m_flags);
158 				}
159 				spin_unlock_irqrestore(&cp->cp_lock, flags);
160 			}
161 		}
162 		conn->c_peer_gen_num = peer_gen_num;
163 	}
164 }
165 
166 /*
167  * Process all extension headers that come with this message.
168  */
169 static void rds_recv_incoming_exthdrs(struct rds_incoming *inc, struct rds_sock *rs)
170 {
171 	struct rds_header *hdr = &inc->i_hdr;
172 	unsigned int pos = 0, type, len;
173 	union {
174 		struct rds_ext_header_version version;
175 		struct rds_ext_header_rdma rdma;
176 		struct rds_ext_header_rdma_dest rdma_dest;
177 	} buffer;
178 
179 	while (1) {
180 		len = sizeof(buffer);
181 		type = rds_message_next_extension(hdr, &pos, &buffer, &len);
182 		if (type == RDS_EXTHDR_NONE)
183 			break;
184 		/* Process extension header here */
185 		switch (type) {
186 		case RDS_EXTHDR_RDMA:
187 			rds_rdma_unuse(rs, be32_to_cpu(buffer.rdma.h_rdma_rkey), 0);
188 			break;
189 
190 		case RDS_EXTHDR_RDMA_DEST:
191 			/* We ignore the size for now. We could stash it
192 			 * somewhere and use it for error checking. */
193 			inc->i_usercopy.rdma_cookie = rds_rdma_make_cookie(
194 					be32_to_cpu(buffer.rdma_dest.h_rdma_rkey),
195 					be32_to_cpu(buffer.rdma_dest.h_rdma_offset));
196 
197 			break;
198 		}
199 	}
200 }
201 
202 static void rds_recv_hs_exthdrs(struct rds_header *hdr,
203 				struct rds_connection *conn)
204 {
205 	unsigned int pos = 0, type, len;
206 	union {
207 		struct rds_ext_header_version version;
208 		__be16 rds_npaths;
209 		__be32 rds_gen_num;
210 		u8 dummy;
211 	} buffer;
212 	bool new_with_sport_idx = false;
213 	u32 new_peer_gen_num = 0;
214 	int new_npaths;
215 	bool fan_out;
216 
217 	new_npaths = conn->c_npaths;
218 
219 	while (1) {
220 		len = sizeof(buffer);
221 		type = rds_message_next_extension(hdr, &pos, &buffer, &len);
222 		if (type == RDS_EXTHDR_NONE)
223 			break;
224 		/* Process extension header here */
225 		switch (type) {
226 		case RDS_EXTHDR_NPATHS:
227 			new_npaths = min_t(int, RDS_MPATH_WORKERS,
228 					   be16_to_cpu(buffer.rds_npaths));
229 			break;
230 		case RDS_EXTHDR_GEN_NUM:
231 			new_peer_gen_num = be32_to_cpu(buffer.rds_gen_num);
232 			break;
233 		case RDS_EXTHDR_SPORT_IDX:
234 			new_with_sport_idx = true;
235 			break;
236 		default:
237 			pr_warn_ratelimited("ignoring unknown exthdr type "
238 					     "0x%x\n", type);
239 		}
240 	}
241 
242 	conn->c_with_sport_idx = new_with_sport_idx;
243 
244 	if (new_npaths > 1 && new_npaths != conn->c_npaths) {
245 		/* We're about to fan-out.
246 		 * Make sure that messages from cp_index#0
247 		 * are sent prior to handling other lanes.
248 		 */
249 		struct rds_conn_path *cp0 = conn->c_path;
250 		unsigned long flags;
251 
252 		spin_lock_irqsave(&cp0->cp_lock, flags);
253 		conn->c_cp0_mprds_catchup_tx_seq = cp0->cp_next_tx_seq;
254 		spin_unlock_irqrestore(&cp0->cp_lock, flags);
255 		fan_out = true;
256 	} else {
257 		fan_out = false;
258 	}
259 
260 	/* if RDS_EXTHDR_NPATHS was not found, default to a single-path */
261 	conn->c_npaths = max_t(int, new_npaths, 1);
262 
263 	conn->c_ping_triggered = 0;
264 	rds_conn_peer_gen_update(conn, new_peer_gen_num);
265 
266 	if (conn->c_npaths > 1 &&
267 	    conn->c_trans->conn_slots_available)
268 		conn->c_trans->conn_slots_available(conn, fan_out);
269 }
270 
271 /* rds_start_mprds() will synchronously start multiple paths when appropriate.
272  * The scheme is based on the following rules:
273  *
274  * 1. rds_sendmsg on first connect attempt sends the probe ping, with the
275  *    sender's npaths (s_npaths)
276  * 2. rcvr of probe-ping knows the mprds_paths = min(s_npaths, r_npaths). It
277  *    sends back a probe-pong with r_npaths. After that, if rcvr is the
278  *    smaller ip addr, it starts rds_conn_path_connect_if_down on all
279  *    mprds_paths.
280  * 3. sender gets woken up, and can move to rds_conn_path_connect_if_down.
281  *    If it is the smaller ipaddr, rds_conn_path_connect_if_down can be
282  *    called after reception of the probe-pong on all mprds_paths.
283  *    Otherwise (sender of probe-ping is not the smaller ip addr): just call
284  *    rds_conn_path_connect_if_down on the hashed path. (see rule 4)
285  * 4. rds_connect_worker must only trigger a connection if laddr < faddr.
286  * 5. sender may end up queuing the packet on the cp. will get sent out later.
287  *    when connection is completed.
288  */
289 static void rds_start_mprds(struct rds_connection *conn)
290 {
291 	int i;
292 	struct rds_conn_path *cp;
293 
294 	if (conn->c_npaths > 1 &&
295 	    rds_addr_cmp(&conn->c_laddr, &conn->c_faddr) < 0) {
296 		for (i = 0; i < conn->c_npaths; i++) {
297 			cp = &conn->c_path[i];
298 			rds_conn_path_connect_if_down(cp);
299 		}
300 	}
301 }
302 
303 /*
304  * The transport must make sure that this is serialized against other
305  * rx and conn reset on this specific conn.
306  *
307  * We currently assert that only one fragmented message will be sent
308  * down a connection at a time.  This lets us reassemble in the conn
309  * instead of per-flow which means that we don't have to go digging through
310  * flows to tear down partial reassembly progress on conn failure and
311  * we save flow lookup and locking for each frag arrival.  It does mean
312  * that small messages will wait behind large ones.  Fragmenting at all
313  * is only to reduce the memory consumption of pre-posted buffers.
314  *
315  * The caller passes in saddr and daddr instead of us getting it from the
316  * conn.  This lets loopback, who only has one conn for both directions,
317  * tell us which roles the addrs in the conn are playing for this message.
318  */
319 void rds_recv_incoming(struct rds_connection *conn, struct in6_addr *saddr,
320 		       struct in6_addr *daddr,
321 		       struct rds_incoming *inc, gfp_t gfp)
322 {
323 	struct rds_sock *rs = NULL;
324 	struct sock *sk;
325 	unsigned long flags;
326 	struct rds_conn_path *cp;
327 
328 	inc->i_conn = conn;
329 	inc->i_rx_jiffies = jiffies;
330 	if (conn->c_trans->t_mp_capable)
331 		cp = inc->i_conn_path;
332 	else
333 		cp = &conn->c_path[0];
334 
335 	rdsdebug("conn %p next %llu inc %p seq %llu len %u sport %u dport %u "
336 		 "flags 0x%x rx_jiffies %lu\n", conn,
337 		 (unsigned long long)cp->cp_next_rx_seq,
338 		 inc,
339 		 (unsigned long long)be64_to_cpu(inc->i_hdr.h_sequence),
340 		 be32_to_cpu(inc->i_hdr.h_len),
341 		 be16_to_cpu(inc->i_hdr.h_sport),
342 		 be16_to_cpu(inc->i_hdr.h_dport),
343 		 inc->i_hdr.h_flags,
344 		 inc->i_rx_jiffies);
345 
346 	/*
347 	 * Sequence numbers should only increase.  Messages get their
348 	 * sequence number as they're queued in a sending conn.  They
349 	 * can be dropped, though, if the sending socket is closed before
350 	 * they hit the wire.  So sequence numbers can skip forward
351 	 * under normal operation.  They can also drop back in the conn
352 	 * failover case as previously sent messages are resent down the
353 	 * new instance of a conn.  We drop those, otherwise we have
354 	 * to assume that the next valid seq does not come after a
355 	 * hole in the fragment stream.
356 	 *
357 	 * The headers don't give us a way to realize if fragments of
358 	 * a message have been dropped.  We assume that frags that arrive
359 	 * to a flow are part of the current message on the flow that is
360 	 * being reassembled.  This means that senders can't drop messages
361 	 * from the sending conn until all their frags are sent.
362 	 *
363 	 * XXX we could spend more on the wire to get more robust failure
364 	 * detection, arguably worth it to avoid data corruption.
365 	 */
366 	if (be64_to_cpu(inc->i_hdr.h_sequence) < cp->cp_next_rx_seq &&
367 	    (inc->i_hdr.h_flags & RDS_FLAG_RETRANSMITTED)) {
368 		rds_stats_inc(s_recv_drop_old_seq);
369 		goto out;
370 	}
371 	cp->cp_next_rx_seq = be64_to_cpu(inc->i_hdr.h_sequence) + 1;
372 
373 	if (rds_sysctl_ping_enable && inc->i_hdr.h_dport == 0) {
374 		if (inc->i_hdr.h_sport == 0) {
375 			rdsdebug("ignore ping with 0 sport from %pI6c\n",
376 				 saddr);
377 			goto out;
378 		}
379 		rds_stats_inc(s_recv_ping);
380 		rds_send_pong(cp, inc->i_hdr.h_sport);
381 		/* if this is a handshake ping, start multipath if necessary */
382 		if (conn->c_trans->t_mp_capable &&
383 		    RDS_HS_PROBE(be16_to_cpu(inc->i_hdr.h_sport),
384 				 be16_to_cpu(inc->i_hdr.h_dport))) {
385 			rds_recv_hs_exthdrs(&inc->i_hdr, cp->cp_conn);
386 			rds_start_mprds(cp->cp_conn);
387 		}
388 		goto out;
389 	}
390 
391 	if (conn->c_trans->t_mp_capable &&
392 	    be16_to_cpu(inc->i_hdr.h_dport) ==  RDS_FLAG_PROBE_PORT &&
393 	    inc->i_hdr.h_sport == 0) {
394 		rds_recv_hs_exthdrs(&inc->i_hdr, cp->cp_conn);
395 		/* if this is a handshake pong, start multipath if necessary */
396 		rds_start_mprds(cp->cp_conn);
397 		wake_up(&cp->cp_conn->c_hs_waitq);
398 		goto out;
399 	}
400 
401 	rs = rds_find_bound(daddr, inc->i_hdr.h_dport, conn->c_bound_if);
402 	if (!rs) {
403 		rds_stats_inc(s_recv_drop_no_sock);
404 		goto out;
405 	}
406 
407 	/*
408 	 * rds_find_bound() uses a global (netns-agnostic) hash table.
409 	 * An RDS connection created in netns A can match a socket bound
410 	 * in the init netns, delivering inc cross-netns with inc->i_conn
411 	 * pointing into netns A.  When cleanup_net() then frees that conn,
412 	 * any subsequent dereference of inc->i_conn is a use-after-free.
413 	 * Drop the inc if the receiving socket lives in a different netns.
414 	 */
415 	if (!net_eq(sock_net(rds_rs_to_sk(rs)), rds_conn_net(conn))) {
416 		rds_stats_inc(s_recv_drop_no_sock);
417 		rds_sock_put(rs);
418 		rs = NULL;
419 		goto out;
420 	}
421 
422 	/* Process extension headers */
423 	rds_recv_incoming_exthdrs(inc, rs);
424 
425 	/* We can be racing with rds_release() which marks the socket dead. */
426 	sk = rds_rs_to_sk(rs);
427 
428 	/* serialize with rds_release -> sock_orphan */
429 	write_lock_irqsave(&rs->rs_recv_lock, flags);
430 	if (!sock_flag(sk, SOCK_DEAD)) {
431 		rdsdebug("adding inc %p to rs %p's recv queue\n", inc, rs);
432 		rds_stats_inc(s_recv_queued);
433 		rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong,
434 				      be32_to_cpu(inc->i_hdr.h_len),
435 				      inc->i_hdr.h_dport);
436 		if (sock_flag(sk, SOCK_RCVTSTAMP))
437 			inc->i_usercopy.rx_tstamp = ktime_get_real();
438 		rds_inc_addref(inc);
439 		inc->i_rx_lat_trace[RDS_MSG_RX_END] = local_clock();
440 		list_add_tail(&inc->i_item, &rs->rs_recv_queue);
441 		__rds_wake_sk_sleep(sk);
442 	} else {
443 		rds_stats_inc(s_recv_drop_dead_sock);
444 	}
445 	write_unlock_irqrestore(&rs->rs_recv_lock, flags);
446 
447 out:
448 	if (rs)
449 		rds_sock_put(rs);
450 }
451 EXPORT_SYMBOL_GPL(rds_recv_incoming);
452 
453 /*
454  * be very careful here.  This is being called as the condition in
455  * wait_event_*() needs to cope with being called many times.
456  */
457 static int rds_next_incoming(struct rds_sock *rs, struct rds_incoming **inc)
458 {
459 	unsigned long flags;
460 
461 	if (!*inc) {
462 		read_lock_irqsave(&rs->rs_recv_lock, flags);
463 		if (!list_empty(&rs->rs_recv_queue)) {
464 			*inc = list_entry(rs->rs_recv_queue.next,
465 					  struct rds_incoming,
466 					  i_item);
467 			rds_inc_addref(*inc);
468 		}
469 		read_unlock_irqrestore(&rs->rs_recv_lock, flags);
470 	}
471 
472 	return *inc != NULL;
473 }
474 
475 static int rds_still_queued(struct rds_sock *rs, struct rds_incoming *inc,
476 			    int drop)
477 {
478 	struct sock *sk = rds_rs_to_sk(rs);
479 	int ret = 0;
480 	unsigned long flags;
481 	struct rds_incoming *to_drop = NULL;
482 
483 	write_lock_irqsave(&rs->rs_recv_lock, flags);
484 	if (!list_empty(&inc->i_item)) {
485 		ret = 1;
486 		if (drop) {
487 			/* XXX make sure this i_conn is reliable */
488 			rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong,
489 					      -be32_to_cpu(inc->i_hdr.h_len),
490 					      inc->i_hdr.h_dport);
491 			list_del_init(&inc->i_item);
492 			to_drop = inc;
493 		}
494 	}
495 	write_unlock_irqrestore(&rs->rs_recv_lock, flags);
496 
497 	if (to_drop)
498 		rds_inc_put(to_drop);
499 
500 	rdsdebug("inc %p rs %p still %d dropped %d\n", inc, rs, ret, drop);
501 	return ret;
502 }
503 
504 /*
505  * Pull errors off the error queue.
506  * If msghdr is NULL, we will just purge the error queue.
507  */
508 int rds_notify_queue_get(struct rds_sock *rs, struct msghdr *msghdr)
509 {
510 	struct rds_notifier *notifier;
511 	struct rds_rdma_notify cmsg;
512 	unsigned int count = 0, max_messages = ~0U;
513 	unsigned long flags;
514 	LIST_HEAD(copy);
515 	int err = 0;
516 
517 	memset(&cmsg, 0, sizeof(cmsg));	/* fill holes with zero */
518 
519 	/* put_cmsg copies to user space and thus may sleep. We can't do this
520 	 * with rs_lock held, so first grab as many notifications as we can stuff
521 	 * in the user provided cmsg buffer. We don't try to copy more, to avoid
522 	 * losing notifications - except when the buffer is so small that it wouldn't
523 	 * even hold a single notification. Then we give him as much of this single
524 	 * msg as we can squeeze in, and set MSG_CTRUNC.
525 	 */
526 	if (msghdr) {
527 		max_messages = msghdr->msg_controllen / CMSG_SPACE(sizeof(cmsg));
528 		if (!max_messages)
529 			max_messages = 1;
530 	}
531 
532 	spin_lock_irqsave(&rs->rs_lock, flags);
533 	while (!list_empty(&rs->rs_notify_queue) && count < max_messages) {
534 		notifier = list_entry(rs->rs_notify_queue.next,
535 				struct rds_notifier, n_list);
536 		list_move(&notifier->n_list, &copy);
537 		count++;
538 	}
539 	spin_unlock_irqrestore(&rs->rs_lock, flags);
540 
541 	if (!count)
542 		return 0;
543 
544 	while (!list_empty(&copy)) {
545 		notifier = list_entry(copy.next, struct rds_notifier, n_list);
546 
547 		if (msghdr) {
548 			cmsg.user_token = notifier->n_user_token;
549 			cmsg.status = notifier->n_status;
550 
551 			err = put_cmsg(msghdr, SOL_RDS, RDS_CMSG_RDMA_STATUS,
552 				       sizeof(cmsg), &cmsg);
553 			if (err)
554 				break;
555 		}
556 
557 		list_del_init(&notifier->n_list);
558 		kfree(notifier);
559 	}
560 
561 	/* If we bailed out because of an error in put_cmsg,
562 	 * we may be left with one or more notifications that we
563 	 * didn't process. Return them to the head of the list. */
564 	if (!list_empty(&copy)) {
565 		spin_lock_irqsave(&rs->rs_lock, flags);
566 		list_splice(&copy, &rs->rs_notify_queue);
567 		spin_unlock_irqrestore(&rs->rs_lock, flags);
568 	}
569 
570 	return err;
571 }
572 
573 /*
574  * Queue a congestion notification
575  */
576 static int rds_notify_cong(struct rds_sock *rs, struct msghdr *msghdr)
577 {
578 	uint64_t notify = rs->rs_cong_notify;
579 	unsigned long flags;
580 	int err;
581 
582 	err = put_cmsg(msghdr, SOL_RDS, RDS_CMSG_CONG_UPDATE,
583 			sizeof(notify), &notify);
584 	if (err)
585 		return err;
586 
587 	spin_lock_irqsave(&rs->rs_lock, flags);
588 	rs->rs_cong_notify &= ~notify;
589 	spin_unlock_irqrestore(&rs->rs_lock, flags);
590 
591 	return 0;
592 }
593 
594 /*
595  * Receive any control messages.
596  */
597 static int rds_cmsg_recv(struct rds_incoming *inc, struct msghdr *msg,
598 			 struct rds_sock *rs)
599 {
600 	int ret = 0;
601 
602 	if (inc->i_usercopy.rdma_cookie) {
603 		ret = put_cmsg(msg, SOL_RDS, RDS_CMSG_RDMA_DEST,
604 				sizeof(inc->i_usercopy.rdma_cookie),
605 				&inc->i_usercopy.rdma_cookie);
606 		if (ret)
607 			goto out;
608 	}
609 
610 	if ((inc->i_usercopy.rx_tstamp != 0) &&
611 	    sock_flag(rds_rs_to_sk(rs), SOCK_RCVTSTAMP)) {
612 		struct __kernel_old_timeval tv =
613 			ns_to_kernel_old_timeval(inc->i_usercopy.rx_tstamp);
614 
615 		if (!sock_flag(rds_rs_to_sk(rs), SOCK_TSTAMP_NEW)) {
616 			ret = put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_OLD,
617 				       sizeof(tv), &tv);
618 		} else {
619 			struct __kernel_sock_timeval sk_tv;
620 
621 			sk_tv.tv_sec = tv.tv_sec;
622 			sk_tv.tv_usec = tv.tv_usec;
623 
624 			ret = put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_NEW,
625 				       sizeof(sk_tv), &sk_tv);
626 		}
627 
628 		if (ret)
629 			goto out;
630 	}
631 
632 	if (rs->rs_rx_traces) {
633 		struct rds_cmsg_rx_trace t;
634 		int i, j;
635 
636 		memset(&t, 0, sizeof(t));
637 		inc->i_rx_lat_trace[RDS_MSG_RX_CMSG] = local_clock();
638 		t.rx_traces =  rs->rs_rx_traces;
639 		for (i = 0; i < rs->rs_rx_traces; i++) {
640 			j = rs->rs_rx_trace[i];
641 			t.rx_trace_pos[i] = j;
642 			t.rx_trace[i] = inc->i_rx_lat_trace[j + 1] -
643 					  inc->i_rx_lat_trace[j];
644 		}
645 
646 		ret = put_cmsg(msg, SOL_RDS, RDS_CMSG_RXPATH_LATENCY,
647 			       sizeof(t), &t);
648 		if (ret)
649 			goto out;
650 	}
651 
652 out:
653 	return ret;
654 }
655 
656 static bool rds_recvmsg_zcookie(struct rds_sock *rs, struct msghdr *msg)
657 {
658 	struct rds_msg_zcopy_queue *q = &rs->rs_zcookie_queue;
659 	struct rds_msg_zcopy_info *info = NULL;
660 	struct rds_zcopy_cookies *done;
661 	unsigned long flags;
662 
663 	if (!msg->msg_control)
664 		return false;
665 
666 	if (!sock_flag(rds_rs_to_sk(rs), SOCK_ZEROCOPY) ||
667 	    msg->msg_controllen < CMSG_SPACE(sizeof(*done)))
668 		return false;
669 
670 	spin_lock_irqsave(&q->lock, flags);
671 	if (!list_empty(&q->zcookie_head)) {
672 		info = list_entry(q->zcookie_head.next,
673 				  struct rds_msg_zcopy_info, rs_zcookie_next);
674 		list_del(&info->rs_zcookie_next);
675 	}
676 	spin_unlock_irqrestore(&q->lock, flags);
677 	if (!info)
678 		return false;
679 	done = &info->zcookies;
680 	if (put_cmsg(msg, SOL_RDS, RDS_CMSG_ZCOPY_COMPLETION, sizeof(*done),
681 		     done)) {
682 		spin_lock_irqsave(&q->lock, flags);
683 		list_add(&info->rs_zcookie_next, &q->zcookie_head);
684 		spin_unlock_irqrestore(&q->lock, flags);
685 		return false;
686 	}
687 	kfree(info);
688 	return true;
689 }
690 
691 int rds_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
692 		int msg_flags)
693 {
694 	struct sock *sk = sock->sk;
695 	struct rds_sock *rs = rds_sk_to_rs(sk);
696 	long timeo;
697 	int ret = 0, nonblock = msg_flags & MSG_DONTWAIT;
698 	DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
699 	DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
700 	struct rds_incoming *inc = NULL;
701 
702 	/* udp_recvmsg()->sock_recvtimeo() gets away without locking too.. */
703 	timeo = sock_rcvtimeo(sk, nonblock);
704 
705 	rdsdebug("size %zu flags 0x%x timeo %ld\n", size, msg_flags, timeo);
706 
707 	if (msg_flags & MSG_OOB)
708 		goto out;
709 	if (msg_flags & MSG_ERRQUEUE)
710 		return sock_recv_errqueue(sk, msg, size, SOL_IP, IP_RECVERR);
711 
712 	while (1) {
713 		/* If there are pending notifications, do those - and nothing else */
714 		if (!list_empty(&rs->rs_notify_queue)) {
715 			ret = rds_notify_queue_get(rs, msg);
716 			break;
717 		}
718 
719 		if (rs->rs_cong_notify) {
720 			ret = rds_notify_cong(rs, msg);
721 			break;
722 		}
723 
724 		if (!rds_next_incoming(rs, &inc)) {
725 			if (nonblock) {
726 				bool reaped = rds_recvmsg_zcookie(rs, msg);
727 
728 				ret = reaped ?  0 : -EAGAIN;
729 				break;
730 			}
731 
732 			timeo = wait_event_interruptible_timeout(*sk_sleep(sk),
733 					(!list_empty(&rs->rs_notify_queue) ||
734 					 rs->rs_cong_notify ||
735 					 rds_next_incoming(rs, &inc)), timeo);
736 			rdsdebug("recvmsg woke inc %p timeo %ld\n", inc,
737 				 timeo);
738 			if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT)
739 				continue;
740 
741 			ret = timeo;
742 			if (ret == 0)
743 				ret = -ETIMEDOUT;
744 			break;
745 		}
746 
747 		rdsdebug("copying inc %p from %pI6c:%u to user\n", inc,
748 			 &inc->i_conn->c_faddr,
749 			 ntohs(inc->i_hdr.h_sport));
750 		ret = inc->i_conn->c_trans->inc_copy_to_user(inc, &msg->msg_iter);
751 		if (ret < 0)
752 			break;
753 
754 		/*
755 		 * if the message we just copied isn't at the head of the
756 		 * recv queue then someone else raced us to return it, try
757 		 * to get the next message.
758 		 */
759 		if (!rds_still_queued(rs, inc, !(msg_flags & MSG_PEEK))) {
760 			rds_inc_put(inc);
761 			inc = NULL;
762 			rds_stats_inc(s_recv_deliver_raced);
763 			iov_iter_revert(&msg->msg_iter, ret);
764 			continue;
765 		}
766 
767 		if (ret < be32_to_cpu(inc->i_hdr.h_len)) {
768 			if (msg_flags & MSG_TRUNC)
769 				ret = be32_to_cpu(inc->i_hdr.h_len);
770 			msg->msg_flags |= MSG_TRUNC;
771 		}
772 
773 		if (rds_cmsg_recv(inc, msg, rs)) {
774 			ret = -EFAULT;
775 			break;
776 		}
777 		rds_recvmsg_zcookie(rs, msg);
778 
779 		rds_stats_inc(s_recv_delivered);
780 
781 		if (msg->msg_name) {
782 			if (ipv6_addr_v4mapped(&inc->i_saddr)) {
783 				sin->sin_family = AF_INET;
784 				sin->sin_port = inc->i_hdr.h_sport;
785 				sin->sin_addr.s_addr =
786 				    inc->i_saddr.s6_addr32[3];
787 				memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
788 				msg->msg_namelen = sizeof(*sin);
789 			} else {
790 				sin6->sin6_family = AF_INET6;
791 				sin6->sin6_port = inc->i_hdr.h_sport;
792 				sin6->sin6_addr = inc->i_saddr;
793 				sin6->sin6_flowinfo = 0;
794 				/* A link-local sender is reported with the
795 				 * interface recorded on its connection (the
796 				 * accepting socket's device for TCP, the one
797 				 * resolved for the local address on IB); any
798 				 * other sender has no scope.
799 				 */
800 				sin6->sin6_scope_id =
801 					(ipv6_addr_type(&inc->i_saddr) &
802 					 IPV6_ADDR_LINKLOCAL) ?
803 					inc->i_conn->c_dev_if : 0;
804 				msg->msg_namelen = sizeof(*sin6);
805 			}
806 		}
807 		break;
808 	}
809 
810 	if (inc)
811 		rds_inc_put(inc);
812 
813 out:
814 	return ret;
815 }
816 
817 /*
818  * The socket is being shut down and we're asked to drop messages that were
819  * queued for recvmsg.  The caller has unbound the socket so the receive path
820  * won't queue any more incoming fragments or messages on the socket.
821  */
822 void rds_clear_recv_queue(struct rds_sock *rs)
823 {
824 	struct sock *sk = rds_rs_to_sk(rs);
825 	struct rds_incoming *inc, *tmp;
826 	unsigned long flags;
827 	LIST_HEAD(to_drop);
828 
829 	write_lock_irqsave(&rs->rs_recv_lock, flags);
830 	list_for_each_entry_safe(inc, tmp, &rs->rs_recv_queue, i_item) {
831 		rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong,
832 				      -be32_to_cpu(inc->i_hdr.h_len),
833 				      inc->i_hdr.h_dport);
834 		list_move(&inc->i_item, &to_drop);
835 	}
836 	write_unlock_irqrestore(&rs->rs_recv_lock, flags);
837 
838 	list_for_each_entry_safe(inc, tmp, &to_drop, i_item) {
839 		list_del_init(&inc->i_item);
840 		rds_inc_put(inc);
841 	}
842 }
843 
844 /*
845  * inc->i_saddr isn't used here because it is only set in the receive
846  * path.
847  */
848 void rds_inc_info_copy(struct rds_incoming *inc,
849 		       struct rds_info_iterator *iter,
850 		       __be32 saddr, __be32 daddr, int flip)
851 {
852 	struct rds_info_message minfo;
853 
854 	minfo.seq = be64_to_cpu(inc->i_hdr.h_sequence);
855 	minfo.len = be32_to_cpu(inc->i_hdr.h_len);
856 	minfo.tos = inc->i_conn->c_tos;
857 
858 	if (flip) {
859 		minfo.laddr = daddr;
860 		minfo.faddr = saddr;
861 		minfo.lport = inc->i_hdr.h_dport;
862 		minfo.fport = inc->i_hdr.h_sport;
863 	} else {
864 		minfo.laddr = saddr;
865 		minfo.faddr = daddr;
866 		minfo.lport = inc->i_hdr.h_sport;
867 		minfo.fport = inc->i_hdr.h_dport;
868 	}
869 
870 	minfo.flags = 0;
871 
872 	rds_info_copy(iter, &minfo, sizeof(minfo));
873 }
874 
875 #if IS_ENABLED(CONFIG_IPV6)
876 void rds6_inc_info_copy(struct rds_incoming *inc,
877 			struct rds_info_iterator *iter,
878 			struct in6_addr *saddr, struct in6_addr *daddr,
879 			int flip)
880 {
881 	struct rds6_info_message minfo6;
882 
883 	minfo6.seq = be64_to_cpu(inc->i_hdr.h_sequence);
884 	minfo6.len = be32_to_cpu(inc->i_hdr.h_len);
885 	minfo6.tos = inc->i_conn->c_tos;
886 
887 	if (flip) {
888 		minfo6.laddr = *daddr;
889 		minfo6.faddr = *saddr;
890 		minfo6.lport = inc->i_hdr.h_dport;
891 		minfo6.fport = inc->i_hdr.h_sport;
892 	} else {
893 		minfo6.laddr = *saddr;
894 		minfo6.faddr = *daddr;
895 		minfo6.lport = inc->i_hdr.h_sport;
896 		minfo6.fport = inc->i_hdr.h_dport;
897 	}
898 
899 	minfo6.flags = 0;
900 
901 	rds_info_copy(iter, &minfo6, sizeof(minfo6));
902 }
903 #endif
904