xref: /linux/net/rds/recv.c (revision c36461825469a9ceee2346a2e89286c522525da7)
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 (RDS_HS_PROBE(be16_to_cpu(inc->i_hdr.h_sport),
383 				 be16_to_cpu(inc->i_hdr.h_dport))) {
384 			rds_recv_hs_exthdrs(&inc->i_hdr, cp->cp_conn);
385 			rds_start_mprds(cp->cp_conn);
386 		}
387 		goto out;
388 	}
389 
390 	if (be16_to_cpu(inc->i_hdr.h_dport) ==  RDS_FLAG_PROBE_PORT &&
391 	    inc->i_hdr.h_sport == 0) {
392 		rds_recv_hs_exthdrs(&inc->i_hdr, cp->cp_conn);
393 		/* if this is a handshake pong, start multipath if necessary */
394 		rds_start_mprds(cp->cp_conn);
395 		wake_up(&cp->cp_conn->c_hs_waitq);
396 		goto out;
397 	}
398 
399 	rs = rds_find_bound(daddr, inc->i_hdr.h_dport, conn->c_bound_if);
400 	if (!rs) {
401 		rds_stats_inc(s_recv_drop_no_sock);
402 		goto out;
403 	}
404 
405 	/*
406 	 * rds_find_bound() uses a global (netns-agnostic) hash table.
407 	 * An RDS connection created in netns A can match a socket bound
408 	 * in the init netns, delivering inc cross-netns with inc->i_conn
409 	 * pointing into netns A.  When cleanup_net() then frees that conn,
410 	 * any subsequent dereference of inc->i_conn is a use-after-free.
411 	 * Drop the inc if the receiving socket lives in a different netns.
412 	 */
413 	if (!net_eq(sock_net(rds_rs_to_sk(rs)), rds_conn_net(conn))) {
414 		rds_stats_inc(s_recv_drop_no_sock);
415 		rds_sock_put(rs);
416 		rs = NULL;
417 		goto out;
418 	}
419 
420 	/* Process extension headers */
421 	rds_recv_incoming_exthdrs(inc, rs);
422 
423 	/* We can be racing with rds_release() which marks the socket dead. */
424 	sk = rds_rs_to_sk(rs);
425 
426 	/* serialize with rds_release -> sock_orphan */
427 	write_lock_irqsave(&rs->rs_recv_lock, flags);
428 	if (!sock_flag(sk, SOCK_DEAD)) {
429 		rdsdebug("adding inc %p to rs %p's recv queue\n", inc, rs);
430 		rds_stats_inc(s_recv_queued);
431 		rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong,
432 				      be32_to_cpu(inc->i_hdr.h_len),
433 				      inc->i_hdr.h_dport);
434 		if (sock_flag(sk, SOCK_RCVTSTAMP))
435 			inc->i_usercopy.rx_tstamp = ktime_get_real();
436 		rds_inc_addref(inc);
437 		inc->i_rx_lat_trace[RDS_MSG_RX_END] = local_clock();
438 		list_add_tail(&inc->i_item, &rs->rs_recv_queue);
439 		__rds_wake_sk_sleep(sk);
440 	} else {
441 		rds_stats_inc(s_recv_drop_dead_sock);
442 	}
443 	write_unlock_irqrestore(&rs->rs_recv_lock, flags);
444 
445 out:
446 	if (rs)
447 		rds_sock_put(rs);
448 }
449 EXPORT_SYMBOL_GPL(rds_recv_incoming);
450 
451 /*
452  * be very careful here.  This is being called as the condition in
453  * wait_event_*() needs to cope with being called many times.
454  */
455 static int rds_next_incoming(struct rds_sock *rs, struct rds_incoming **inc)
456 {
457 	unsigned long flags;
458 
459 	if (!*inc) {
460 		read_lock_irqsave(&rs->rs_recv_lock, flags);
461 		if (!list_empty(&rs->rs_recv_queue)) {
462 			*inc = list_entry(rs->rs_recv_queue.next,
463 					  struct rds_incoming,
464 					  i_item);
465 			rds_inc_addref(*inc);
466 		}
467 		read_unlock_irqrestore(&rs->rs_recv_lock, flags);
468 	}
469 
470 	return *inc != NULL;
471 }
472 
473 static int rds_still_queued(struct rds_sock *rs, struct rds_incoming *inc,
474 			    int drop)
475 {
476 	struct sock *sk = rds_rs_to_sk(rs);
477 	int ret = 0;
478 	unsigned long flags;
479 	struct rds_incoming *to_drop = NULL;
480 
481 	write_lock_irqsave(&rs->rs_recv_lock, flags);
482 	if (!list_empty(&inc->i_item)) {
483 		ret = 1;
484 		if (drop) {
485 			/* XXX make sure this i_conn is reliable */
486 			rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong,
487 					      -be32_to_cpu(inc->i_hdr.h_len),
488 					      inc->i_hdr.h_dport);
489 			list_del_init(&inc->i_item);
490 			to_drop = inc;
491 		}
492 	}
493 	write_unlock_irqrestore(&rs->rs_recv_lock, flags);
494 
495 	if (to_drop)
496 		rds_inc_put(to_drop);
497 
498 	rdsdebug("inc %p rs %p still %d dropped %d\n", inc, rs, ret, drop);
499 	return ret;
500 }
501 
502 /*
503  * Pull errors off the error queue.
504  * If msghdr is NULL, we will just purge the error queue.
505  */
506 int rds_notify_queue_get(struct rds_sock *rs, struct msghdr *msghdr)
507 {
508 	struct rds_notifier *notifier;
509 	struct rds_rdma_notify cmsg;
510 	unsigned int count = 0, max_messages = ~0U;
511 	unsigned long flags;
512 	LIST_HEAD(copy);
513 	int err = 0;
514 
515 	memset(&cmsg, 0, sizeof(cmsg));	/* fill holes with zero */
516 
517 	/* put_cmsg copies to user space and thus may sleep. We can't do this
518 	 * with rs_lock held, so first grab as many notifications as we can stuff
519 	 * in the user provided cmsg buffer. We don't try to copy more, to avoid
520 	 * losing notifications - except when the buffer is so small that it wouldn't
521 	 * even hold a single notification. Then we give him as much of this single
522 	 * msg as we can squeeze in, and set MSG_CTRUNC.
523 	 */
524 	if (msghdr) {
525 		max_messages = msghdr->msg_controllen / CMSG_SPACE(sizeof(cmsg));
526 		if (!max_messages)
527 			max_messages = 1;
528 	}
529 
530 	spin_lock_irqsave(&rs->rs_lock, flags);
531 	while (!list_empty(&rs->rs_notify_queue) && count < max_messages) {
532 		notifier = list_entry(rs->rs_notify_queue.next,
533 				struct rds_notifier, n_list);
534 		list_move(&notifier->n_list, &copy);
535 		count++;
536 	}
537 	spin_unlock_irqrestore(&rs->rs_lock, flags);
538 
539 	if (!count)
540 		return 0;
541 
542 	while (!list_empty(&copy)) {
543 		notifier = list_entry(copy.next, struct rds_notifier, n_list);
544 
545 		if (msghdr) {
546 			cmsg.user_token = notifier->n_user_token;
547 			cmsg.status = notifier->n_status;
548 
549 			err = put_cmsg(msghdr, SOL_RDS, RDS_CMSG_RDMA_STATUS,
550 				       sizeof(cmsg), &cmsg);
551 			if (err)
552 				break;
553 		}
554 
555 		list_del_init(&notifier->n_list);
556 		kfree(notifier);
557 	}
558 
559 	/* If we bailed out because of an error in put_cmsg,
560 	 * we may be left with one or more notifications that we
561 	 * didn't process. Return them to the head of the list. */
562 	if (!list_empty(&copy)) {
563 		spin_lock_irqsave(&rs->rs_lock, flags);
564 		list_splice(&copy, &rs->rs_notify_queue);
565 		spin_unlock_irqrestore(&rs->rs_lock, flags);
566 	}
567 
568 	return err;
569 }
570 
571 /*
572  * Queue a congestion notification
573  */
574 static int rds_notify_cong(struct rds_sock *rs, struct msghdr *msghdr)
575 {
576 	uint64_t notify = rs->rs_cong_notify;
577 	unsigned long flags;
578 	int err;
579 
580 	err = put_cmsg(msghdr, SOL_RDS, RDS_CMSG_CONG_UPDATE,
581 			sizeof(notify), &notify);
582 	if (err)
583 		return err;
584 
585 	spin_lock_irqsave(&rs->rs_lock, flags);
586 	rs->rs_cong_notify &= ~notify;
587 	spin_unlock_irqrestore(&rs->rs_lock, flags);
588 
589 	return 0;
590 }
591 
592 /*
593  * Receive any control messages.
594  */
595 static int rds_cmsg_recv(struct rds_incoming *inc, struct msghdr *msg,
596 			 struct rds_sock *rs)
597 {
598 	int ret = 0;
599 
600 	if (inc->i_usercopy.rdma_cookie) {
601 		ret = put_cmsg(msg, SOL_RDS, RDS_CMSG_RDMA_DEST,
602 				sizeof(inc->i_usercopy.rdma_cookie),
603 				&inc->i_usercopy.rdma_cookie);
604 		if (ret)
605 			goto out;
606 	}
607 
608 	if ((inc->i_usercopy.rx_tstamp != 0) &&
609 	    sock_flag(rds_rs_to_sk(rs), SOCK_RCVTSTAMP)) {
610 		struct __kernel_old_timeval tv =
611 			ns_to_kernel_old_timeval(inc->i_usercopy.rx_tstamp);
612 
613 		if (!sock_flag(rds_rs_to_sk(rs), SOCK_TSTAMP_NEW)) {
614 			ret = put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_OLD,
615 				       sizeof(tv), &tv);
616 		} else {
617 			struct __kernel_sock_timeval sk_tv;
618 
619 			sk_tv.tv_sec = tv.tv_sec;
620 			sk_tv.tv_usec = tv.tv_usec;
621 
622 			ret = put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_NEW,
623 				       sizeof(sk_tv), &sk_tv);
624 		}
625 
626 		if (ret)
627 			goto out;
628 	}
629 
630 	if (rs->rs_rx_traces) {
631 		struct rds_cmsg_rx_trace t;
632 		int i, j;
633 
634 		memset(&t, 0, sizeof(t));
635 		inc->i_rx_lat_trace[RDS_MSG_RX_CMSG] = local_clock();
636 		t.rx_traces =  rs->rs_rx_traces;
637 		for (i = 0; i < rs->rs_rx_traces; i++) {
638 			j = rs->rs_rx_trace[i];
639 			t.rx_trace_pos[i] = j;
640 			t.rx_trace[i] = inc->i_rx_lat_trace[j + 1] -
641 					  inc->i_rx_lat_trace[j];
642 		}
643 
644 		ret = put_cmsg(msg, SOL_RDS, RDS_CMSG_RXPATH_LATENCY,
645 			       sizeof(t), &t);
646 		if (ret)
647 			goto out;
648 	}
649 
650 out:
651 	return ret;
652 }
653 
654 static bool rds_recvmsg_zcookie(struct rds_sock *rs, struct msghdr *msg)
655 {
656 	struct rds_msg_zcopy_queue *q = &rs->rs_zcookie_queue;
657 	struct rds_msg_zcopy_info *info = NULL;
658 	struct rds_zcopy_cookies *done;
659 	unsigned long flags;
660 
661 	if (!msg->msg_control)
662 		return false;
663 
664 	if (!sock_flag(rds_rs_to_sk(rs), SOCK_ZEROCOPY) ||
665 	    msg->msg_controllen < CMSG_SPACE(sizeof(*done)))
666 		return false;
667 
668 	spin_lock_irqsave(&q->lock, flags);
669 	if (!list_empty(&q->zcookie_head)) {
670 		info = list_entry(q->zcookie_head.next,
671 				  struct rds_msg_zcopy_info, rs_zcookie_next);
672 		list_del(&info->rs_zcookie_next);
673 	}
674 	spin_unlock_irqrestore(&q->lock, flags);
675 	if (!info)
676 		return false;
677 	done = &info->zcookies;
678 	if (put_cmsg(msg, SOL_RDS, RDS_CMSG_ZCOPY_COMPLETION, sizeof(*done),
679 		     done)) {
680 		spin_lock_irqsave(&q->lock, flags);
681 		list_add(&info->rs_zcookie_next, &q->zcookie_head);
682 		spin_unlock_irqrestore(&q->lock, flags);
683 		return false;
684 	}
685 	kfree(info);
686 	return true;
687 }
688 
689 int rds_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
690 		int msg_flags)
691 {
692 	struct sock *sk = sock->sk;
693 	struct rds_sock *rs = rds_sk_to_rs(sk);
694 	long timeo;
695 	int ret = 0, nonblock = msg_flags & MSG_DONTWAIT;
696 	DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
697 	DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
698 	struct rds_incoming *inc = NULL;
699 
700 	/* udp_recvmsg()->sock_recvtimeo() gets away without locking too.. */
701 	timeo = sock_rcvtimeo(sk, nonblock);
702 
703 	rdsdebug("size %zu flags 0x%x timeo %ld\n", size, msg_flags, timeo);
704 
705 	if (msg_flags & MSG_OOB)
706 		goto out;
707 	if (msg_flags & MSG_ERRQUEUE)
708 		return sock_recv_errqueue(sk, msg, size, SOL_IP, IP_RECVERR);
709 
710 	while (1) {
711 		/* If there are pending notifications, do those - and nothing else */
712 		if (!list_empty(&rs->rs_notify_queue)) {
713 			ret = rds_notify_queue_get(rs, msg);
714 			break;
715 		}
716 
717 		if (rs->rs_cong_notify) {
718 			ret = rds_notify_cong(rs, msg);
719 			break;
720 		}
721 
722 		if (!rds_next_incoming(rs, &inc)) {
723 			if (nonblock) {
724 				bool reaped = rds_recvmsg_zcookie(rs, msg);
725 
726 				ret = reaped ?  0 : -EAGAIN;
727 				break;
728 			}
729 
730 			timeo = wait_event_interruptible_timeout(*sk_sleep(sk),
731 					(!list_empty(&rs->rs_notify_queue) ||
732 					 rs->rs_cong_notify ||
733 					 rds_next_incoming(rs, &inc)), timeo);
734 			rdsdebug("recvmsg woke inc %p timeo %ld\n", inc,
735 				 timeo);
736 			if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT)
737 				continue;
738 
739 			ret = timeo;
740 			if (ret == 0)
741 				ret = -ETIMEDOUT;
742 			break;
743 		}
744 
745 		rdsdebug("copying inc %p from %pI6c:%u to user\n", inc,
746 			 &inc->i_conn->c_faddr,
747 			 ntohs(inc->i_hdr.h_sport));
748 		ret = inc->i_conn->c_trans->inc_copy_to_user(inc, &msg->msg_iter);
749 		if (ret < 0)
750 			break;
751 
752 		/*
753 		 * if the message we just copied isn't at the head of the
754 		 * recv queue then someone else raced us to return it, try
755 		 * to get the next message.
756 		 */
757 		if (!rds_still_queued(rs, inc, !(msg_flags & MSG_PEEK))) {
758 			rds_inc_put(inc);
759 			inc = NULL;
760 			rds_stats_inc(s_recv_deliver_raced);
761 			iov_iter_revert(&msg->msg_iter, ret);
762 			continue;
763 		}
764 
765 		if (ret < be32_to_cpu(inc->i_hdr.h_len)) {
766 			if (msg_flags & MSG_TRUNC)
767 				ret = be32_to_cpu(inc->i_hdr.h_len);
768 			msg->msg_flags |= MSG_TRUNC;
769 		}
770 
771 		if (rds_cmsg_recv(inc, msg, rs)) {
772 			ret = -EFAULT;
773 			break;
774 		}
775 		rds_recvmsg_zcookie(rs, msg);
776 
777 		rds_stats_inc(s_recv_delivered);
778 
779 		if (msg->msg_name) {
780 			if (ipv6_addr_v4mapped(&inc->i_saddr)) {
781 				sin->sin_family = AF_INET;
782 				sin->sin_port = inc->i_hdr.h_sport;
783 				sin->sin_addr.s_addr =
784 				    inc->i_saddr.s6_addr32[3];
785 				memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
786 				msg->msg_namelen = sizeof(*sin);
787 			} else {
788 				sin6->sin6_family = AF_INET6;
789 				sin6->sin6_port = inc->i_hdr.h_sport;
790 				sin6->sin6_addr = inc->i_saddr;
791 				sin6->sin6_flowinfo = 0;
792 				sin6->sin6_scope_id = rs->rs_bound_scope_id;
793 				msg->msg_namelen = sizeof(*sin6);
794 			}
795 		}
796 		break;
797 	}
798 
799 	if (inc)
800 		rds_inc_put(inc);
801 
802 out:
803 	return ret;
804 }
805 
806 /*
807  * The socket is being shut down and we're asked to drop messages that were
808  * queued for recvmsg.  The caller has unbound the socket so the receive path
809  * won't queue any more incoming fragments or messages on the socket.
810  */
811 void rds_clear_recv_queue(struct rds_sock *rs)
812 {
813 	struct sock *sk = rds_rs_to_sk(rs);
814 	struct rds_incoming *inc, *tmp;
815 	unsigned long flags;
816 	LIST_HEAD(to_drop);
817 
818 	write_lock_irqsave(&rs->rs_recv_lock, flags);
819 	list_for_each_entry_safe(inc, tmp, &rs->rs_recv_queue, i_item) {
820 		rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong,
821 				      -be32_to_cpu(inc->i_hdr.h_len),
822 				      inc->i_hdr.h_dport);
823 		list_move(&inc->i_item, &to_drop);
824 	}
825 	write_unlock_irqrestore(&rs->rs_recv_lock, flags);
826 
827 	list_for_each_entry_safe(inc, tmp, &to_drop, i_item) {
828 		list_del_init(&inc->i_item);
829 		rds_inc_put(inc);
830 	}
831 }
832 
833 /*
834  * inc->i_saddr isn't used here because it is only set in the receive
835  * path.
836  */
837 void rds_inc_info_copy(struct rds_incoming *inc,
838 		       struct rds_info_iterator *iter,
839 		       __be32 saddr, __be32 daddr, int flip)
840 {
841 	struct rds_info_message minfo;
842 
843 	minfo.seq = be64_to_cpu(inc->i_hdr.h_sequence);
844 	minfo.len = be32_to_cpu(inc->i_hdr.h_len);
845 	minfo.tos = inc->i_conn->c_tos;
846 
847 	if (flip) {
848 		minfo.laddr = daddr;
849 		minfo.faddr = saddr;
850 		minfo.lport = inc->i_hdr.h_dport;
851 		minfo.fport = inc->i_hdr.h_sport;
852 	} else {
853 		minfo.laddr = saddr;
854 		minfo.faddr = daddr;
855 		minfo.lport = inc->i_hdr.h_sport;
856 		minfo.fport = inc->i_hdr.h_dport;
857 	}
858 
859 	minfo.flags = 0;
860 
861 	rds_info_copy(iter, &minfo, sizeof(minfo));
862 }
863 
864 #if IS_ENABLED(CONFIG_IPV6)
865 void rds6_inc_info_copy(struct rds_incoming *inc,
866 			struct rds_info_iterator *iter,
867 			struct in6_addr *saddr, struct in6_addr *daddr,
868 			int flip)
869 {
870 	struct rds6_info_message minfo6;
871 
872 	minfo6.seq = be64_to_cpu(inc->i_hdr.h_sequence);
873 	minfo6.len = be32_to_cpu(inc->i_hdr.h_len);
874 	minfo6.tos = inc->i_conn->c_tos;
875 
876 	if (flip) {
877 		minfo6.laddr = *daddr;
878 		minfo6.faddr = *saddr;
879 		minfo6.lport = inc->i_hdr.h_dport;
880 		minfo6.fport = inc->i_hdr.h_sport;
881 	} else {
882 		minfo6.laddr = *saddr;
883 		minfo6.faddr = *daddr;
884 		minfo6.lport = inc->i_hdr.h_sport;
885 		minfo6.fport = inc->i_hdr.h_dport;
886 	}
887 
888 	minfo6.flags = 0;
889 
890 	rds_info_copy(iter, &minfo6, sizeof(minfo6));
891 }
892 #endif
893