xref: /linux/net/rds/send.c (revision 24e4aff8983fe663a85b5b157476f87ae0819e2c)
1 /*
2  * Copyright (c) 2006, 2018 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/moduleparam.h>
35 #include <linux/gfp.h>
36 #include <net/sock.h>
37 #include <linux/in.h>
38 #include <linux/list.h>
39 #include <linux/ratelimit.h>
40 #include <linux/export.h>
41 #include <linux/sizes.h>
42 
43 #include "rds.h"
44 
45 /* When transmitting messages in rds_send_xmit, we need to emerge from
46  * time to time and briefly release the CPU. Otherwise the softlock watchdog
47  * will kick our shin.
48  * Also, it seems fairer to not let one busy connection stall all the
49  * others.
50  *
51  * send_batch_count is the number of times we'll loop in send_xmit. Setting
52  * it to 0 will restore the old behavior (where we looped until we had
53  * drained the queue).
54  */
55 static int send_batch_count = SZ_1K;
56 module_param(send_batch_count, int, 0444);
57 MODULE_PARM_DESC(send_batch_count, " batch factor when working the send queue");
58 
59 static void rds_send_remove_from_sock(struct list_head *messages, int status);
60 
61 /*
62  * Reset the send state.  Callers must ensure that this doesn't race with
63  * rds_send_xmit().
64  */
65 void rds_send_path_reset(struct rds_conn_path *cp)
66 {
67 	struct rds_message *rm, *tmp;
68 	unsigned long flags;
69 
70 	if (cp->cp_xmit_rm) {
71 		rm = cp->cp_xmit_rm;
72 		cp->cp_xmit_rm = NULL;
73 		/* Tell the user the RDMA op is no longer mapped by the
74 		 * transport. This isn't entirely true (it's flushed out
75 		 * independently) but as the connection is down, there's
76 		 * no ongoing RDMA to/from that memory */
77 		rds_message_unmapped(rm);
78 		rds_message_put(rm);
79 	}
80 
81 	cp->cp_xmit_sg = 0;
82 	cp->cp_xmit_hdr_off = 0;
83 	cp->cp_xmit_data_off = 0;
84 	cp->cp_xmit_atomic_sent = 0;
85 	cp->cp_xmit_rdma_sent = 0;
86 	cp->cp_xmit_data_sent = 0;
87 
88 	cp->cp_conn->c_map_queued = 0;
89 
90 	cp->cp_unacked_packets = rds_sysctl_max_unacked_packets;
91 	cp->cp_unacked_bytes = rds_sysctl_max_unacked_bytes;
92 
93 	/* Mark messages as retransmissions, and move them to the send q */
94 	spin_lock_irqsave(&cp->cp_lock, flags);
95 	list_for_each_entry_safe(rm, tmp, &cp->cp_retrans, m_conn_item) {
96 		set_bit(RDS_MSG_ACK_REQUIRED, &rm->m_flags);
97 		set_bit(RDS_MSG_RETRANSMITTED, &rm->m_flags);
98 	}
99 	list_splice_init(&cp->cp_retrans, &cp->cp_send_queue);
100 	spin_unlock_irqrestore(&cp->cp_lock, flags);
101 }
102 EXPORT_SYMBOL_GPL(rds_send_path_reset);
103 
104 static int acquire_in_xmit(struct rds_conn_path *cp)
105 {
106 	return test_and_set_bit_lock(RDS_IN_XMIT, &cp->cp_flags) == 0;
107 }
108 
109 static void release_in_xmit(struct rds_conn_path *cp)
110 {
111 	clear_bit_unlock(RDS_IN_XMIT, &cp->cp_flags);
112 	/*
113 	 * We don't use wait_on_bit()/wake_up_bit() because our waking is in a
114 	 * hot path and finding waiters is very rare.  We don't want to walk
115 	 * the system-wide hashed waitqueue buckets in the fast path only to
116 	 * almost never find waiters.
117 	 */
118 	if (waitqueue_active(&cp->cp_waitq))
119 		wake_up_all(&cp->cp_waitq);
120 }
121 
122 /*
123  * Helper function for multipath fanout to ensure lane 0 transmits queued
124  * messages before other lanes to prevent out-of-order delivery.
125  *
126  * Returns true if lane 0 still has messages or false otherwise
127  */
128 static bool rds_mprds_cp0_catchup(struct rds_connection *conn)
129 {
130 	struct rds_conn_path *cp0 = conn->c_path;
131 	struct rds_message *rm0;
132 	unsigned long flags;
133 	bool ret = false;
134 
135 	spin_lock_irqsave(&cp0->cp_lock, flags);
136 
137 	/* the oldest / first message in the retransmit queue
138 	 * has to be at or beyond c_cp0_mprds_catchup_tx_seq
139 	 */
140 	if (!list_empty(&cp0->cp_retrans)) {
141 		rm0 = list_entry(cp0->cp_retrans.next, struct rds_message,
142 				 m_conn_item);
143 		if (be64_to_cpu(rm0->m_inc.i_hdr.h_sequence) <
144 		    conn->c_cp0_mprds_catchup_tx_seq) {
145 			/* the retransmit queue of cp_index#0 has not
146 			 * quite caught up yet
147 			 */
148 			ret = true;
149 			goto unlock;
150 		}
151 	}
152 
153 	/* the oldest / first message of the send queue
154 	 * has to be at or beyond c_cp0_mprds_catchup_tx_seq
155 	 */
156 	rm0 = cp0->cp_xmit_rm;
157 	if (!rm0 && !list_empty(&cp0->cp_send_queue))
158 		rm0 = list_entry(cp0->cp_send_queue.next, struct rds_message,
159 				 m_conn_item);
160 	if (rm0 && be64_to_cpu(rm0->m_inc.i_hdr.h_sequence) <
161 	    conn->c_cp0_mprds_catchup_tx_seq) {
162 		/* the send queue of cp_index#0 has not quite
163 		 * caught up yet
164 		 */
165 		ret = true;
166 	}
167 
168 unlock:
169 	spin_unlock_irqrestore(&cp0->cp_lock, flags);
170 	return ret;
171 }
172 
173 /*
174  * We're making the conscious trade-off here to only send one message
175  * down the connection at a time.
176  *   Pro:
177  *      - tx queueing is a simple fifo list
178  *   	- reassembly is optional and easily done by transports per conn
179  *      - no per flow rx lookup at all, straight to the socket
180  *   	- less per-frag memory and wire overhead
181  *   Con:
182  *      - queued acks can be delayed behind large messages
183  *   Depends:
184  *      - small message latency is higher behind queued large messages
185  *      - large message latency isn't starved by intervening small sends
186  */
187 int rds_send_xmit(struct rds_conn_path *cp)
188 {
189 	struct rds_connection *conn = cp->cp_conn;
190 	struct rds_message *rm;
191 	unsigned long flags;
192 	unsigned int tmp;
193 	struct scatterlist *sg;
194 	int ret = 0;
195 	LIST_HEAD(to_be_dropped);
196 	int batch_count;
197 	unsigned long send_gen = 0;
198 	int same_rm = 0;
199 
200 restart:
201 	batch_count = 0;
202 
203 	/*
204 	 * sendmsg calls here after having queued its message on the send
205 	 * queue.  We only have one task feeding the connection at a time.  If
206 	 * another thread is already feeding the queue then we back off.  This
207 	 * avoids blocking the caller and trading per-connection data between
208 	 * caches per message.
209 	 */
210 	if (!acquire_in_xmit(cp)) {
211 		rds_stats_inc(s_send_lock_contention);
212 		ret = -ENOMEM;
213 		goto out;
214 	}
215 
216 	if (rds_destroy_pending(cp->cp_conn)) {
217 		release_in_xmit(cp);
218 		ret = -ENETUNREACH; /* dont requeue send work */
219 		goto out;
220 	}
221 
222 	/*
223 	 * we record the send generation after doing the xmit acquire.
224 	 * if someone else manages to jump in and do some work, we'll use
225 	 * this to avoid a goto restart farther down.
226 	 *
227 	 * The acquire_in_xmit() check above ensures that only one
228 	 * caller can increment c_send_gen at any time.
229 	 */
230 	send_gen = READ_ONCE(cp->cp_send_gen) + 1;
231 	WRITE_ONCE(cp->cp_send_gen, send_gen);
232 
233 	/*
234 	 * rds_conn_shutdown() sets the conn state and then tests RDS_IN_XMIT,
235 	 * we do the opposite to avoid races.
236 	 */
237 	if (!rds_conn_path_up(cp)) {
238 		release_in_xmit(cp);
239 		ret = 0;
240 		goto out;
241 	}
242 
243 	if (conn->c_trans->xmit_path_prepare)
244 		conn->c_trans->xmit_path_prepare(cp);
245 
246 	/*
247 	 * spin trying to push headers and data down the connection until
248 	 * the connection doesn't make forward progress.
249 	 */
250 	while (1) {
251 
252 		rm = cp->cp_xmit_rm;
253 
254 		if (!rm) {
255 			same_rm = 0;
256 		} else {
257 			same_rm++;
258 			if (same_rm >= 4096) {
259 				rds_stats_inc(s_send_stuck_rm);
260 				ret = -EAGAIN;
261 				break;
262 			}
263 		}
264 
265 		/*
266 		 * If between sending messages, we can send a pending congestion
267 		 * map update.
268 		 */
269 		if (!rm && test_and_clear_bit(0, &conn->c_map_queued)) {
270 			rm = rds_cong_update_alloc(conn);
271 			if (IS_ERR(rm)) {
272 				ret = PTR_ERR(rm);
273 				break;
274 			}
275 			rm->data.op_active = 1;
276 			rm->m_inc.i_conn_path = cp;
277 			rm->m_inc.i_conn = cp->cp_conn;
278 
279 			cp->cp_xmit_rm = rm;
280 		}
281 
282 		/*
283 		 * If not already working on one, grab the next message.
284 		 *
285 		 * cp_xmit_rm holds a ref while we're sending this message down
286 		 * the connection.  We can use this ref while holding the
287 		 * send_sem.. rds_send_path_reset() is serialized with it.
288 		 */
289 		if (!rm) {
290 			unsigned int len;
291 
292 			batch_count++;
293 
294 			/* we want to process as big a batch as we can, but
295 			 * we also want to avoid softlockups.  If we've been
296 			 * through a lot of messages, lets back off and see
297 			 * if anyone else jumps in
298 			 */
299 			if (batch_count >= send_batch_count)
300 				goto over_batch;
301 
302 			/* make sure cp_index#0 caught up during fan-out in
303 			 * order to avoid lane races
304 			 */
305 			if (cp->cp_index > 0 && rds_mprds_cp0_catchup(conn)) {
306 				rds_stats_inc(s_mprds_catchup_tx0_retries);
307 				goto over_batch;
308 			}
309 
310 			spin_lock_irqsave(&cp->cp_lock, flags);
311 
312 			if (!list_empty(&cp->cp_send_queue)) {
313 				rm = list_entry(cp->cp_send_queue.next,
314 						struct rds_message,
315 						m_conn_item);
316 				rds_message_addref(rm);
317 
318 				/*
319 				 * Move the message from the send queue to the retransmit
320 				 * list right away.
321 				 */
322 				list_move_tail(&rm->m_conn_item,
323 					       &cp->cp_retrans);
324 			}
325 
326 			spin_unlock_irqrestore(&cp->cp_lock, flags);
327 
328 			if (!rm)
329 				break;
330 
331 			/* Unfortunately, the way Infiniband deals with
332 			 * RDMA to a bad MR key is by moving the entire
333 			 * queue pair to error state. We could possibly
334 			 * recover from that, but right now we drop the
335 			 * connection.
336 			 * Therefore, we never retransmit messages with RDMA ops.
337 			 */
338 			if (test_bit(RDS_MSG_FLUSH, &rm->m_flags) ||
339 			    (rm->rdma.op_active &&
340 			    test_bit(RDS_MSG_RETRANSMITTED, &rm->m_flags))) {
341 				spin_lock_irqsave(&cp->cp_lock, flags);
342 				if (test_and_clear_bit(RDS_MSG_ON_CONN,
343 						       &rm->m_flags)) {
344 					/* our ref is put after the batch */
345 					list_move(&rm->m_conn_item,
346 						  &to_be_dropped);
347 					spin_unlock_irqrestore(&cp->cp_lock,
348 							       flags);
349 				} else {
350 					/* already off the conn list; drop
351 					 * the ref taken above ourselves
352 					 */
353 					spin_unlock_irqrestore(&cp->cp_lock,
354 							       flags);
355 					rds_message_put(rm);
356 				}
357 				continue;
358 			}
359 
360 			/* Require an ACK every once in a while */
361 			len = ntohl(rm->m_inc.i_hdr.h_len);
362 			if (cp->cp_unacked_packets == 0 ||
363 			    cp->cp_unacked_bytes < len) {
364 				set_bit(RDS_MSG_ACK_REQUIRED, &rm->m_flags);
365 
366 				cp->cp_unacked_packets =
367 					rds_sysctl_max_unacked_packets;
368 				cp->cp_unacked_bytes =
369 					rds_sysctl_max_unacked_bytes;
370 				rds_stats_inc(s_send_ack_required);
371 			} else {
372 				cp->cp_unacked_bytes -= len;
373 				cp->cp_unacked_packets--;
374 			}
375 
376 			cp->cp_xmit_rm = rm;
377 		}
378 
379 		/* The transport either sends the whole rdma or none of it */
380 		if (rm->rdma.op_active && !cp->cp_xmit_rdma_sent) {
381 			rm->m_final_op = &rm->rdma;
382 			/* The transport owns the mapped memory for now.
383 			 * You can't unmap it while it's on the send queue
384 			 */
385 			set_bit(RDS_MSG_MAPPED, &rm->m_flags);
386 			ret = conn->c_trans->xmit_rdma(conn, &rm->rdma);
387 			if (ret) {
388 				clear_bit(RDS_MSG_MAPPED, &rm->m_flags);
389 				wake_up_interruptible(&rm->m_flush_wait);
390 				break;
391 			}
392 			cp->cp_xmit_rdma_sent = 1;
393 
394 		}
395 
396 		if (rm->atomic.op_active && !cp->cp_xmit_atomic_sent) {
397 			rm->m_final_op = &rm->atomic;
398 			/* The transport owns the mapped memory for now.
399 			 * You can't unmap it while it's on the send queue
400 			 */
401 			set_bit(RDS_MSG_MAPPED, &rm->m_flags);
402 			ret = conn->c_trans->xmit_atomic(conn, &rm->atomic);
403 			if (ret) {
404 				clear_bit(RDS_MSG_MAPPED, &rm->m_flags);
405 				wake_up_interruptible(&rm->m_flush_wait);
406 				break;
407 			}
408 			cp->cp_xmit_atomic_sent = 1;
409 
410 		}
411 
412 		/*
413 		 * A number of cases require an RDS header to be sent
414 		 * even if there is no data.
415 		 * We permit 0-byte sends; rds-ping depends on this.
416 		 * However, if there are exclusively attached silent ops,
417 		 * we skip the hdr/data send, to enable silent operation.
418 		 */
419 		if (rm->data.op_nents == 0) {
420 			int ops_present;
421 			int all_ops_are_silent = 1;
422 
423 			ops_present = (rm->atomic.op_active || rm->rdma.op_active);
424 			if (rm->atomic.op_active && !rm->atomic.op_silent)
425 				all_ops_are_silent = 0;
426 			if (rm->rdma.op_active && !rm->rdma.op_silent)
427 				all_ops_are_silent = 0;
428 
429 			if (ops_present && all_ops_are_silent
430 			    && !rm->m_rdma_cookie)
431 				rm->data.op_active = 0;
432 		}
433 
434 		if (rm->data.op_active && !cp->cp_xmit_data_sent) {
435 			rm->m_final_op = &rm->data;
436 
437 			ret = conn->c_trans->xmit(conn, rm,
438 						  cp->cp_xmit_hdr_off,
439 						  cp->cp_xmit_sg,
440 						  cp->cp_xmit_data_off);
441 			if (ret <= 0)
442 				break;
443 
444 			if (cp->cp_xmit_hdr_off < sizeof(struct rds_header)) {
445 				tmp = min_t(int, ret,
446 					    sizeof(struct rds_header) -
447 					    cp->cp_xmit_hdr_off);
448 				cp->cp_xmit_hdr_off += tmp;
449 				ret -= tmp;
450 			}
451 
452 			sg = &rm->data.op_sg[cp->cp_xmit_sg];
453 			while (ret) {
454 				tmp = min_t(int, ret, sg->length -
455 						      cp->cp_xmit_data_off);
456 				cp->cp_xmit_data_off += tmp;
457 				ret -= tmp;
458 				if (cp->cp_xmit_data_off == sg->length) {
459 					cp->cp_xmit_data_off = 0;
460 					sg++;
461 					cp->cp_xmit_sg++;
462 					BUG_ON(ret != 0 && cp->cp_xmit_sg ==
463 					       rm->data.op_nents);
464 				}
465 			}
466 
467 			if (cp->cp_xmit_hdr_off == sizeof(struct rds_header) &&
468 			    (cp->cp_xmit_sg == rm->data.op_nents))
469 				cp->cp_xmit_data_sent = 1;
470 		}
471 
472 		/*
473 		 * A rm will only take multiple times through this loop
474 		 * if there is a data op. Thus, if the data is sent (or there was
475 		 * none), then we're done with the rm.
476 		 */
477 		if (!rm->data.op_active || cp->cp_xmit_data_sent) {
478 			cp->cp_xmit_rm = NULL;
479 			cp->cp_xmit_sg = 0;
480 			cp->cp_xmit_hdr_off = 0;
481 			cp->cp_xmit_data_off = 0;
482 			cp->cp_xmit_rdma_sent = 0;
483 			cp->cp_xmit_atomic_sent = 0;
484 			cp->cp_xmit_data_sent = 0;
485 
486 			rds_message_put(rm);
487 		}
488 	}
489 
490 over_batch:
491 	if (conn->c_trans->xmit_path_complete)
492 		conn->c_trans->xmit_path_complete(cp);
493 	release_in_xmit(cp);
494 
495 	/* Nuke any messages we decided not to retransmit. */
496 	if (!list_empty(&to_be_dropped)) {
497 		/* irqs on here, so we can put(), unlike above */
498 		list_for_each_entry(rm, &to_be_dropped, m_conn_item)
499 			rds_message_put(rm);
500 		rds_send_remove_from_sock(&to_be_dropped, RDS_RDMA_DROPPED);
501 	}
502 
503 	/*
504 	 * Other senders can queue a message after we last test the send queue
505 	 * but before we clear RDS_IN_XMIT.  In that case they'd back off and
506 	 * not try and send their newly queued message.  We need to check the
507 	 * send queue after having cleared RDS_IN_XMIT so that their message
508 	 * doesn't get stuck on the send queue.
509 	 *
510 	 * If the transport cannot continue (i.e ret != 0), then it must
511 	 * call us when more room is available, such as from the tx
512 	 * completion handler.
513 	 *
514 	 * We have an extra generation check here so that if someone manages
515 	 * to jump in after our release_in_xmit, we'll see that they have done
516 	 * some work and we will skip our goto
517 	 */
518 	if (ret == 0) {
519 		bool raced;
520 
521 		smp_mb();
522 		raced = send_gen != READ_ONCE(cp->cp_send_gen);
523 
524 		if ((test_bit(0, &conn->c_map_queued) ||
525 		    !list_empty(&cp->cp_send_queue)) && !raced) {
526 			if (batch_count < send_batch_count)
527 				goto restart;
528 			rcu_read_lock();
529 			if (rds_destroy_pending(cp->cp_conn))
530 				ret = -ENETUNREACH;
531 			else
532 				queue_delayed_work(cp->cp_wq,
533 						   &cp->cp_send_w, 1);
534 			rcu_read_unlock();
535 		} else if (raced) {
536 			rds_stats_inc(s_send_lock_queue_raced);
537 		}
538 	}
539 out:
540 	return ret;
541 }
542 EXPORT_SYMBOL_GPL(rds_send_xmit);
543 
544 static void rds_send_sndbuf_remove(struct rds_sock *rs, struct rds_message *rm)
545 {
546 	u32 len = be32_to_cpu(rm->m_inc.i_hdr.h_len);
547 
548 	assert_spin_locked(&rs->rs_lock);
549 
550 	BUG_ON(rs->rs_snd_bytes < len);
551 	rs->rs_snd_bytes -= len;
552 
553 	if (rs->rs_snd_bytes == 0)
554 		rds_stats_inc(s_send_queue_empty);
555 }
556 
557 static inline int rds_send_is_acked(struct rds_message *rm, u64 ack,
558 				    is_acked_func is_acked)
559 {
560 	if (is_acked)
561 		return is_acked(rm, ack);
562 	return be64_to_cpu(rm->m_inc.i_hdr.h_sequence) <= ack;
563 }
564 
565 /*
566  * This is pretty similar to what happens below in the ACK
567  * handling code - except that we call here as soon as we get
568  * the IB send completion on the RDMA op and the accompanying
569  * message.
570  */
571 void rds_rdma_send_complete(struct rds_message *rm, int status)
572 {
573 	struct rds_sock *rs = NULL;
574 	struct rm_rdma_op *ro;
575 	struct rds_notifier *notifier;
576 	unsigned long flags;
577 
578 	spin_lock_irqsave(&rm->m_rs_lock, flags);
579 
580 	ro = &rm->rdma;
581 	if (test_bit(RDS_MSG_ON_SOCK, &rm->m_flags) &&
582 	    ro->op_active && ro->op_notify && ro->op_notifier) {
583 		notifier = ro->op_notifier;
584 		rs = rm->m_rs;
585 		sock_hold(rds_rs_to_sk(rs));
586 
587 		notifier->n_status = status;
588 		spin_lock(&rs->rs_lock);
589 		list_add_tail(&notifier->n_list, &rs->rs_notify_queue);
590 		spin_unlock(&rs->rs_lock);
591 
592 		ro->op_notifier = NULL;
593 	}
594 
595 	spin_unlock_irqrestore(&rm->m_rs_lock, flags);
596 
597 	if (rs) {
598 		rds_wake_sk_sleep(rs);
599 		sock_put(rds_rs_to_sk(rs));
600 	}
601 }
602 EXPORT_SYMBOL_GPL(rds_rdma_send_complete);
603 
604 /*
605  * Just like above, except looks at atomic op
606  */
607 void rds_atomic_send_complete(struct rds_message *rm, int status)
608 {
609 	struct rds_sock *rs = NULL;
610 	struct rm_atomic_op *ao;
611 	struct rds_notifier *notifier;
612 	unsigned long flags;
613 
614 	spin_lock_irqsave(&rm->m_rs_lock, flags);
615 
616 	ao = &rm->atomic;
617 	if (test_bit(RDS_MSG_ON_SOCK, &rm->m_flags)
618 	    && ao->op_active && ao->op_notify && ao->op_notifier) {
619 		notifier = ao->op_notifier;
620 		rs = rm->m_rs;
621 		sock_hold(rds_rs_to_sk(rs));
622 
623 		notifier->n_status = status;
624 		spin_lock(&rs->rs_lock);
625 		list_add_tail(&notifier->n_list, &rs->rs_notify_queue);
626 		spin_unlock(&rs->rs_lock);
627 
628 		ao->op_notifier = NULL;
629 	}
630 
631 	spin_unlock_irqrestore(&rm->m_rs_lock, flags);
632 
633 	if (rs) {
634 		rds_wake_sk_sleep(rs);
635 		sock_put(rds_rs_to_sk(rs));
636 	}
637 }
638 EXPORT_SYMBOL_GPL(rds_atomic_send_complete);
639 
640 /*
641  * This is the same as rds_rdma_send_complete except we
642  * don't do any locking - we have all the ingredients (message,
643  * socket, socket lock) and can just move the notifier.
644  */
645 static inline void
646 __rds_send_complete(struct rds_sock *rs, struct rds_message *rm, int status)
647 {
648 	struct rm_rdma_op *ro;
649 	struct rm_atomic_op *ao;
650 
651 	ro = &rm->rdma;
652 	if (ro->op_active && ro->op_notify && ro->op_notifier) {
653 		ro->op_notifier->n_status = status;
654 		list_add_tail(&ro->op_notifier->n_list, &rs->rs_notify_queue);
655 		ro->op_notifier = NULL;
656 	}
657 
658 	ao = &rm->atomic;
659 	if (ao->op_active && ao->op_notify && ao->op_notifier) {
660 		ao->op_notifier->n_status = status;
661 		list_add_tail(&ao->op_notifier->n_list, &rs->rs_notify_queue);
662 		ao->op_notifier = NULL;
663 	}
664 
665 	/* No need to wake the app - caller does this */
666 }
667 
668 /*
669  * This removes messages from the socket's list if they're on it.  The list
670  * argument must be private to the caller, we must be able to modify it
671  * without locks.  The messages must have a reference held for their
672  * position on the list.  This function will drop that reference after
673  * removing the messages from the 'messages' list regardless of if it found
674  * the messages on the socket list or not.
675  */
676 static void rds_send_remove_from_sock(struct list_head *messages, int status)
677 {
678 	unsigned long flags;
679 	struct rds_sock *rs = NULL;
680 	struct rds_message *rm;
681 
682 	while (!list_empty(messages)) {
683 		int was_on_sock = 0;
684 
685 		rm = list_entry(messages->next, struct rds_message,
686 				m_conn_item);
687 		list_del_init(&rm->m_conn_item);
688 
689 		/*
690 		 * If we see this flag cleared then we're *sure* that someone
691 		 * else beat us to removing it from the sock.  If we race
692 		 * with their flag update we'll get the lock and then really
693 		 * see that the flag has been cleared.
694 		 *
695 		 * The message spinlock makes sure nobody clears rm->m_rs
696 		 * while we're messing with it. It does not prevent the
697 		 * message from being removed from the socket, though.
698 		 */
699 		spin_lock_irqsave(&rm->m_rs_lock, flags);
700 		if (!test_bit(RDS_MSG_ON_SOCK, &rm->m_flags))
701 			goto unlock_and_drop;
702 
703 		if (rs != rm->m_rs) {
704 			if (rs) {
705 				rds_wake_sk_sleep(rs);
706 				sock_put(rds_rs_to_sk(rs));
707 			}
708 			rs = rm->m_rs;
709 			if (rs)
710 				sock_hold(rds_rs_to_sk(rs));
711 		}
712 		if (!rs)
713 			goto unlock_and_drop;
714 		spin_lock(&rs->rs_lock);
715 
716 		if (test_and_clear_bit(RDS_MSG_ON_SOCK, &rm->m_flags)) {
717 			struct rm_rdma_op *ro = &rm->rdma;
718 			struct rds_notifier *notifier;
719 
720 			list_del_init(&rm->m_sock_item);
721 			rds_send_sndbuf_remove(rs, rm);
722 
723 			if (ro->op_active && ro->op_notifier &&
724 			       (ro->op_notify || (ro->op_recverr && status))) {
725 				notifier = ro->op_notifier;
726 				list_add_tail(&notifier->n_list,
727 						&rs->rs_notify_queue);
728 				if (!notifier->n_status)
729 					notifier->n_status = status;
730 				rm->rdma.op_notifier = NULL;
731 			}
732 			was_on_sock = 1;
733 		}
734 		spin_unlock(&rs->rs_lock);
735 
736 unlock_and_drop:
737 		spin_unlock_irqrestore(&rm->m_rs_lock, flags);
738 		rds_message_put(rm);
739 		if (was_on_sock)
740 			rds_message_put(rm);
741 	}
742 
743 	if (rs) {
744 		rds_wake_sk_sleep(rs);
745 		sock_put(rds_rs_to_sk(rs));
746 	}
747 }
748 
749 /*
750  * Transports call here when they've determined that the receiver queued
751  * messages up to, and including, the given sequence number.  Messages are
752  * moved to the retrans queue when rds_send_xmit picks them off the send
753  * queue. This means that in the TCP case, the message may not have been
754  * assigned the m_ack_seq yet - but that's fine as long as tcp_is_acked
755  * checks the RDS_MSG_HAS_ACK_SEQ bit.
756  */
757 void rds_send_path_drop_acked(struct rds_conn_path *cp, u64 ack,
758 			      is_acked_func is_acked)
759 {
760 	struct rds_message *rm, *tmp;
761 	unsigned long flags;
762 	LIST_HEAD(list);
763 
764 	spin_lock_irqsave(&cp->cp_lock, flags);
765 
766 	list_for_each_entry_safe(rm, tmp, &cp->cp_retrans, m_conn_item) {
767 		if (!rds_send_is_acked(rm, ack, is_acked))
768 			break;
769 
770 		list_move(&rm->m_conn_item, &list);
771 		clear_bit(RDS_MSG_ON_CONN, &rm->m_flags);
772 	}
773 
774 	/* order flag updates with spin locks */
775 	if (!list_empty(&list))
776 		smp_mb__after_atomic();
777 
778 	spin_unlock_irqrestore(&cp->cp_lock, flags);
779 
780 	/* now remove the messages from the sock list as needed */
781 	rds_send_remove_from_sock(&list, RDS_RDMA_SUCCESS);
782 }
783 EXPORT_SYMBOL_GPL(rds_send_path_drop_acked);
784 
785 void rds_send_drop_acked(struct rds_connection *conn, u64 ack,
786 			 is_acked_func is_acked)
787 {
788 	WARN_ON(conn->c_trans->t_mp_capable);
789 	rds_send_path_drop_acked(&conn->c_path[0], ack, is_acked);
790 }
791 EXPORT_SYMBOL_GPL(rds_send_drop_acked);
792 
793 void rds_send_drop_to(struct rds_sock *rs, struct sockaddr_in6 *dest)
794 {
795 	struct rds_message *rm, *tmp;
796 	struct rds_connection *conn;
797 	struct rds_conn_path *cp;
798 	unsigned long flags;
799 	LIST_HEAD(list);
800 
801 	/* get all the messages we're dropping under the rs lock */
802 	spin_lock_irqsave(&rs->rs_lock, flags);
803 
804 	list_for_each_entry_safe(rm, tmp, &rs->rs_send_queue, m_sock_item) {
805 		if (dest &&
806 		    (!ipv6_addr_equal(&dest->sin6_addr, &rm->m_daddr) ||
807 		     dest->sin6_port != rm->m_inc.i_hdr.h_dport))
808 			continue;
809 
810 		list_move(&rm->m_sock_item, &list);
811 		rds_send_sndbuf_remove(rs, rm);
812 		clear_bit(RDS_MSG_ON_SOCK, &rm->m_flags);
813 	}
814 
815 	/* order flag updates with the rs lock */
816 	smp_mb__after_atomic();
817 
818 	spin_unlock_irqrestore(&rs->rs_lock, flags);
819 
820 	if (list_empty(&list))
821 		return;
822 
823 	/* Remove the messages from the conn */
824 	list_for_each_entry(rm, &list, m_sock_item) {
825 
826 		conn = rm->m_inc.i_conn;
827 		if (conn->c_trans->t_mp_capable)
828 			cp = rm->m_inc.i_conn_path;
829 		else
830 			cp = &conn->c_path[0];
831 
832 		spin_lock_irqsave(&cp->cp_lock, flags);
833 		/*
834 		 * Maybe someone else beat us to removing rm from the conn.
835 		 * If we race with their flag update we'll get the lock and
836 		 * then really see that the flag has been cleared.
837 		 */
838 		if (!test_and_clear_bit(RDS_MSG_ON_CONN, &rm->m_flags)) {
839 			spin_unlock_irqrestore(&cp->cp_lock, flags);
840 			continue;
841 		}
842 		list_del_init(&rm->m_conn_item);
843 		spin_unlock_irqrestore(&cp->cp_lock, flags);
844 
845 		/*
846 		 * Couldn't grab m_rs_lock in top loop (lock ordering),
847 		 * but we can now.
848 		 */
849 		spin_lock_irqsave(&rm->m_rs_lock, flags);
850 
851 		spin_lock(&rs->rs_lock);
852 		__rds_send_complete(rs, rm, RDS_RDMA_CANCELED);
853 		spin_unlock(&rs->rs_lock);
854 
855 		spin_unlock_irqrestore(&rm->m_rs_lock, flags);
856 
857 		rds_message_put(rm);
858 	}
859 
860 	rds_wake_sk_sleep(rs);
861 
862 	while (!list_empty(&list)) {
863 		rm = list_entry(list.next, struct rds_message, m_sock_item);
864 		list_del_init(&rm->m_sock_item);
865 		rds_message_wait(rm);
866 
867 		/* just in case the code above skipped this message
868 		 * because RDS_MSG_ON_CONN wasn't set, run it again here
869 		 * taking m_rs_lock is the only thing that keeps us
870 		 * from racing with ack processing.
871 		 */
872 		spin_lock_irqsave(&rm->m_rs_lock, flags);
873 
874 		spin_lock(&rs->rs_lock);
875 		__rds_send_complete(rs, rm, RDS_RDMA_CANCELED);
876 		spin_unlock(&rs->rs_lock);
877 
878 		spin_unlock_irqrestore(&rm->m_rs_lock, flags);
879 
880 		rds_message_put(rm);
881 	}
882 }
883 
884 /*
885  * we only want this to fire once so we use the callers 'queued'.  It's
886  * possible that another thread can race with us and remove the
887  * message from the flow with RDS_CANCEL_SENT_TO.
888  */
889 static int rds_send_queue_rm(struct rds_sock *rs, struct rds_connection *conn,
890 			     struct rds_conn_path *cp,
891 			     struct rds_message *rm, __be16 sport,
892 			     __be16 dport, int *queued)
893 {
894 	unsigned long flags;
895 	u32 len;
896 
897 	if (*queued)
898 		goto out;
899 
900 	len = be32_to_cpu(rm->m_inc.i_hdr.h_len);
901 
902 	/* this is the only place which holds both the socket's rs_lock
903 	 * and the connection's c_lock */
904 	spin_lock_irqsave(&rs->rs_lock, flags);
905 
906 	/*
907 	 * If there is a little space in sndbuf, we don't queue anything,
908 	 * and userspace gets -EAGAIN. But poll() indicates there's send
909 	 * room. This can lead to bad behavior (spinning) if snd_bytes isn't
910 	 * freed up by incoming acks. So we check the *old* value of
911 	 * rs_snd_bytes here to allow the last msg to exceed the buffer,
912 	 * and poll() now knows no more data can be sent.
913 	 */
914 	if (rs->rs_snd_bytes < rds_sk_sndbuf(rs)) {
915 		rs->rs_snd_bytes += len;
916 
917 		/* let recv side know we are close to send space exhaustion.
918 		 * This is probably not the optimal way to do it, as this
919 		 * means we set the flag on *all* messages as soon as our
920 		 * throughput hits a certain threshold.
921 		 */
922 		if (rs->rs_snd_bytes >= rds_sk_sndbuf(rs) / 2)
923 			set_bit(RDS_MSG_ACK_REQUIRED, &rm->m_flags);
924 
925 		list_add_tail(&rm->m_sock_item, &rs->rs_send_queue);
926 		set_bit(RDS_MSG_ON_SOCK, &rm->m_flags);
927 		rds_message_addref(rm);
928 		sock_hold(rds_rs_to_sk(rs));
929 		rm->m_rs = rs;
930 
931 		/* The code ordering is a little weird, but we're
932 		   trying to minimize the time we hold c_lock */
933 		rds_message_populate_header(&rm->m_inc.i_hdr, sport, dport, 0);
934 		rm->m_inc.i_conn = conn;
935 		rm->m_inc.i_conn_path = cp;
936 		rds_message_addref(rm);
937 
938 		spin_lock(&cp->cp_lock);
939 		rm->m_inc.i_hdr.h_sequence = cpu_to_be64(cp->cp_next_tx_seq++);
940 		list_add_tail(&rm->m_conn_item, &cp->cp_send_queue);
941 		set_bit(RDS_MSG_ON_CONN, &rm->m_flags);
942 		spin_unlock(&cp->cp_lock);
943 
944 		rdsdebug("queued msg %p len %d, rs %p bytes %d seq %llu\n",
945 			 rm, len, rs, rs->rs_snd_bytes,
946 			 (unsigned long long)be64_to_cpu(rm->m_inc.i_hdr.h_sequence));
947 
948 		*queued = 1;
949 	}
950 
951 	spin_unlock_irqrestore(&rs->rs_lock, flags);
952 out:
953 	return *queued;
954 }
955 
956 /*
957  * rds_message is getting to be quite complicated, and we'd like to allocate
958  * it all in one go. This figures out how big it needs to be up front.
959  */
960 static int rds_rm_size(struct msghdr *msg, int num_sgs,
961 		       struct rds_iov_vector_arr *vct)
962 {
963 	struct cmsghdr *cmsg;
964 	int size = 0;
965 	int cmsg_groups = 0;
966 	int retval;
967 	bool zcopy_cookie = false;
968 	struct rds_iov_vector *iov, *tmp_iov;
969 
970 	if (num_sgs < 0)
971 		return -EINVAL;
972 
973 	for_each_cmsghdr(cmsg, msg) {
974 		if (!CMSG_OK(msg, cmsg))
975 			return -EINVAL;
976 
977 		if (cmsg->cmsg_level != SOL_RDS)
978 			continue;
979 
980 		switch (cmsg->cmsg_type) {
981 		case RDS_CMSG_RDMA_ARGS:
982 			if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_rdma_args)))
983 				return -EINVAL;
984 			if (vct->indx >= vct->len) {
985 				vct->len += vct->incr;
986 				tmp_iov = krealloc_array(vct->vec, vct->len,
987 							 sizeof(*vct->vec), GFP_KERNEL);
988 				if (!tmp_iov) {
989 					vct->len -= vct->incr;
990 					return -ENOMEM;
991 				}
992 				vct->vec = tmp_iov;
993 			}
994 			iov = &vct->vec[vct->indx];
995 			memset(iov, 0, sizeof(struct rds_iov_vector));
996 			vct->indx++;
997 			cmsg_groups |= 1;
998 			retval = rds_rdma_extra_size(CMSG_DATA(cmsg), iov);
999 			if (retval < 0)
1000 				return retval;
1001 			size += retval;
1002 
1003 			break;
1004 
1005 		case RDS_CMSG_ZCOPY_COOKIE:
1006 			zcopy_cookie = true;
1007 			fallthrough;
1008 
1009 		case RDS_CMSG_RDMA_DEST:
1010 		case RDS_CMSG_RDMA_MAP:
1011 			cmsg_groups |= 2;
1012 			/* these are valid but do no add any size */
1013 			break;
1014 
1015 		case RDS_CMSG_ATOMIC_CSWP:
1016 		case RDS_CMSG_ATOMIC_FADD:
1017 		case RDS_CMSG_MASKED_ATOMIC_CSWP:
1018 		case RDS_CMSG_MASKED_ATOMIC_FADD:
1019 			cmsg_groups |= 1;
1020 			size += sizeof(struct scatterlist);
1021 			break;
1022 
1023 		default:
1024 			return -EINVAL;
1025 		}
1026 
1027 	}
1028 
1029 	if ((msg->msg_flags & MSG_ZEROCOPY) && !zcopy_cookie)
1030 		return -EINVAL;
1031 
1032 	size += num_sgs * sizeof(struct scatterlist);
1033 
1034 	/* Ensure (DEST, MAP) are never used with (ARGS, ATOMIC) */
1035 	if (cmsg_groups == 3)
1036 		return -EINVAL;
1037 
1038 	return size;
1039 }
1040 
1041 static int rds_cmsg_zcopy(struct rds_sock *rs, struct rds_message *rm,
1042 			  struct cmsghdr *cmsg)
1043 {
1044 	u32 *cookie;
1045 
1046 	if (cmsg->cmsg_len < CMSG_LEN(sizeof(*cookie)) ||
1047 	    !rm->data.op_mmp_znotifier)
1048 		return -EINVAL;
1049 	cookie = CMSG_DATA(cmsg);
1050 	rm->data.op_mmp_znotifier->z_cookie = *cookie;
1051 	return 0;
1052 }
1053 
1054 static int rds_cmsg_send(struct rds_sock *rs, struct rds_message *rm,
1055 			 struct msghdr *msg, int *allocated_mr,
1056 			 struct rds_iov_vector_arr *vct)
1057 {
1058 	struct cmsghdr *cmsg;
1059 	int ret = 0, ind = 0;
1060 
1061 	for_each_cmsghdr(cmsg, msg) {
1062 		if (!CMSG_OK(msg, cmsg))
1063 			return -EINVAL;
1064 
1065 		if (cmsg->cmsg_level != SOL_RDS)
1066 			continue;
1067 
1068 		/* As a side effect, RDMA_DEST and RDMA_MAP will set
1069 		 * rm->rdma.m_rdma_cookie and rm->rdma.m_rdma_mr.
1070 		 */
1071 		switch (cmsg->cmsg_type) {
1072 		case RDS_CMSG_RDMA_ARGS:
1073 			if (ind >= vct->indx)
1074 				return -ENOMEM;
1075 			ret = rds_cmsg_rdma_args(rs, rm, cmsg, &vct->vec[ind]);
1076 			ind++;
1077 			break;
1078 
1079 		case RDS_CMSG_RDMA_DEST:
1080 			ret = rds_cmsg_rdma_dest(rs, rm, cmsg);
1081 			break;
1082 
1083 		case RDS_CMSG_RDMA_MAP:
1084 			ret = rds_cmsg_rdma_map(rs, rm, cmsg);
1085 			if (!ret)
1086 				*allocated_mr = 1;
1087 			else if (ret == -ENODEV)
1088 				/* Accommodate the get_mr() case which can fail
1089 				 * if connection isn't established yet.
1090 				 */
1091 				ret = -EAGAIN;
1092 			break;
1093 		case RDS_CMSG_ATOMIC_CSWP:
1094 		case RDS_CMSG_ATOMIC_FADD:
1095 		case RDS_CMSG_MASKED_ATOMIC_CSWP:
1096 		case RDS_CMSG_MASKED_ATOMIC_FADD:
1097 			ret = rds_cmsg_atomic(rs, rm, cmsg);
1098 			break;
1099 
1100 		case RDS_CMSG_ZCOPY_COOKIE:
1101 			ret = rds_cmsg_zcopy(rs, rm, cmsg);
1102 			break;
1103 
1104 		default:
1105 			return -EINVAL;
1106 		}
1107 
1108 		if (ret)
1109 			break;
1110 	}
1111 
1112 	return ret;
1113 }
1114 
1115 static int rds_rdma_bytes(struct msghdr *msg, size_t *rdma_bytes)
1116 {
1117 	struct rds_rdma_args *args;
1118 	struct cmsghdr *cmsg;
1119 
1120 	for_each_cmsghdr(cmsg, msg) {
1121 		if (!CMSG_OK(msg, cmsg))
1122 			return -EINVAL;
1123 
1124 		if (cmsg->cmsg_level != SOL_RDS)
1125 			continue;
1126 
1127 		if (cmsg->cmsg_type == RDS_CMSG_RDMA_ARGS) {
1128 			if (cmsg->cmsg_len <
1129 			    CMSG_LEN(sizeof(struct rds_rdma_args)))
1130 				return -EINVAL;
1131 			args = CMSG_DATA(cmsg);
1132 			*rdma_bytes += args->remote_vec.bytes;
1133 		}
1134 	}
1135 	return 0;
1136 }
1137 
1138 int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)
1139 {
1140 	struct sock *sk = sock->sk;
1141 	struct rds_sock *rs = rds_sk_to_rs(sk);
1142 	DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
1143 	DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
1144 	__be16 dport;
1145 	struct rds_message *rm = NULL;
1146 	struct rds_connection *conn;
1147 	int ret = 0;
1148 	int queued = 0, allocated_mr = 0;
1149 	int nonblock = msg->msg_flags & MSG_DONTWAIT;
1150 	long timeo = sock_sndtimeo(sk, nonblock);
1151 	struct rds_conn_path *cpath;
1152 	struct in6_addr daddr;
1153 	__u32 scope_id = 0;
1154 	size_t rdma_payload_len = 0;
1155 	bool zcopy = ((msg->msg_flags & MSG_ZEROCOPY) &&
1156 		      sock_flag(rds_rs_to_sk(rs), SOCK_ZEROCOPY));
1157 	int num_sgs = DIV_ROUND_UP(payload_len, PAGE_SIZE);
1158 	int namelen;
1159 	struct rds_iov_vector_arr vct;
1160 	int ind;
1161 
1162 	memset(&vct, 0, sizeof(vct));
1163 
1164 	/* expect 1 RDMA CMSG per rds_sendmsg. can still grow if more needed. */
1165 	vct.incr = 1;
1166 
1167 	/* Mirror Linux UDP mirror of BSD error message compatibility */
1168 	/* XXX: Perhaps MSG_MORE someday */
1169 	if (msg->msg_flags & ~(MSG_DONTWAIT | MSG_CMSG_COMPAT | MSG_ZEROCOPY)) {
1170 		ret = -EOPNOTSUPP;
1171 		goto out;
1172 	}
1173 
1174 	namelen = msg->msg_namelen;
1175 	if (namelen != 0) {
1176 		if (namelen < sizeof(*usin)) {
1177 			ret = -EINVAL;
1178 			goto out;
1179 		}
1180 		switch (usin->sin_family) {
1181 		case AF_INET:
1182 			if (usin->sin_addr.s_addr == htonl(INADDR_ANY) ||
1183 			    usin->sin_addr.s_addr == htonl(INADDR_BROADCAST) ||
1184 			    ipv4_is_multicast(usin->sin_addr.s_addr)) {
1185 				ret = -EINVAL;
1186 				goto out;
1187 			}
1188 			ipv6_addr_set_v4mapped(usin->sin_addr.s_addr, &daddr);
1189 			dport = usin->sin_port;
1190 			break;
1191 
1192 #if IS_ENABLED(CONFIG_IPV6)
1193 		case AF_INET6: {
1194 			int addr_type;
1195 
1196 			if (namelen < sizeof(*sin6)) {
1197 				ret = -EINVAL;
1198 				goto out;
1199 			}
1200 			addr_type = ipv6_addr_type(&sin6->sin6_addr);
1201 			if (!(addr_type & IPV6_ADDR_UNICAST)) {
1202 				__be32 addr4;
1203 
1204 				if (!(addr_type & IPV6_ADDR_MAPPED)) {
1205 					ret = -EINVAL;
1206 					goto out;
1207 				}
1208 
1209 				/* It is a mapped address.  Need to do some
1210 				 * sanity checks.
1211 				 */
1212 				addr4 = sin6->sin6_addr.s6_addr32[3];
1213 				if (addr4 == htonl(INADDR_ANY) ||
1214 				    addr4 == htonl(INADDR_BROADCAST) ||
1215 				    ipv4_is_multicast(addr4)) {
1216 					ret = -EINVAL;
1217 					goto out;
1218 				}
1219 			}
1220 			if (addr_type & IPV6_ADDR_LINKLOCAL) {
1221 				if (sin6->sin6_scope_id == 0) {
1222 					ret = -EINVAL;
1223 					goto out;
1224 				}
1225 				scope_id = sin6->sin6_scope_id;
1226 			}
1227 
1228 			daddr = sin6->sin6_addr;
1229 			dport = sin6->sin6_port;
1230 			break;
1231 		}
1232 #endif
1233 
1234 		default:
1235 			ret = -EINVAL;
1236 			goto out;
1237 		}
1238 	} else {
1239 		/* We only care about consistency with ->connect() */
1240 		lock_sock(sk);
1241 		daddr = rs->rs_conn_addr;
1242 		dport = rs->rs_conn_port;
1243 		scope_id = rs->rs_bound_scope_id;
1244 		release_sock(sk);
1245 	}
1246 
1247 	lock_sock(sk);
1248 	if (ipv6_addr_any(&rs->rs_bound_addr) || ipv6_addr_any(&daddr)) {
1249 		release_sock(sk);
1250 		ret = -ENOTCONN;
1251 		goto out;
1252 	} else if (namelen != 0) {
1253 		/* Cannot send to an IPv4 address using an IPv6 source
1254 		 * address and cannot send to an IPv6 address using an
1255 		 * IPv4 source address.
1256 		 */
1257 		if (ipv6_addr_v4mapped(&daddr) ^
1258 		    ipv6_addr_v4mapped(&rs->rs_bound_addr)) {
1259 			release_sock(sk);
1260 			ret = -EOPNOTSUPP;
1261 			goto out;
1262 		}
1263 		/* If the socket is already bound to a link local address,
1264 		 * it can only send to peers on the same link.  But allow
1265 		 * communicating between link local and non-link local address.
1266 		 */
1267 		if (scope_id != rs->rs_bound_scope_id) {
1268 			if (!scope_id) {
1269 				scope_id = rs->rs_bound_scope_id;
1270 			} else if (rs->rs_bound_scope_id) {
1271 				release_sock(sk);
1272 				ret = -EINVAL;
1273 				goto out;
1274 			}
1275 		}
1276 	}
1277 	release_sock(sk);
1278 
1279 	ret = rds_rdma_bytes(msg, &rdma_payload_len);
1280 	if (ret)
1281 		goto out;
1282 
1283 	if (max_t(size_t, payload_len, rdma_payload_len) > RDS_MAX_MSG_SIZE) {
1284 		ret = -EMSGSIZE;
1285 		goto out;
1286 	}
1287 
1288 	if (payload_len > rds_sk_sndbuf(rs)) {
1289 		ret = -EMSGSIZE;
1290 		goto out;
1291 	}
1292 
1293 	if (zcopy) {
1294 		if (rs->rs_transport->t_type != RDS_TRANS_TCP) {
1295 			ret = -EOPNOTSUPP;
1296 			goto out;
1297 		}
1298 		num_sgs = iov_iter_npages(&msg->msg_iter, INT_MAX);
1299 	}
1300 	/* size of rm including all sgs */
1301 	ret = rds_rm_size(msg, num_sgs, &vct);
1302 	if (ret < 0)
1303 		goto out;
1304 
1305 	rm = rds_message_alloc(ret, GFP_KERNEL);
1306 	if (!rm) {
1307 		ret = -ENOMEM;
1308 		goto out;
1309 	}
1310 
1311 	/* Attach data to the rm */
1312 	if (payload_len) {
1313 		rm->data.op_sg = rds_message_alloc_sgs(rm, num_sgs);
1314 		if (IS_ERR(rm->data.op_sg)) {
1315 			ret = PTR_ERR(rm->data.op_sg);
1316 			goto out;
1317 		}
1318 		ret = rds_message_copy_from_user(rm, &msg->msg_iter, zcopy);
1319 		if (ret)
1320 			goto out;
1321 	}
1322 	rm->data.op_active = 1;
1323 
1324 	rm->m_daddr = daddr;
1325 
1326 	/* rds_conn_create has a spinlock that runs with IRQ off.
1327 	 * Caching the conn in the socket helps a lot. */
1328 	if (rs->rs_conn && ipv6_addr_equal(&rs->rs_conn->c_faddr, &daddr) &&
1329 	    rs->rs_tos == rs->rs_conn->c_tos) {
1330 		conn = rs->rs_conn;
1331 	} else {
1332 		conn = rds_conn_create_outgoing(sock_net(sock->sk),
1333 						&rs->rs_bound_addr, &daddr,
1334 						rs->rs_transport, rs->rs_tos,
1335 						sock->sk->sk_allocation,
1336 						scope_id);
1337 		if (IS_ERR(conn)) {
1338 			ret = PTR_ERR(conn);
1339 			goto out;
1340 		}
1341 		rs->rs_conn = conn;
1342 	}
1343 
1344 	if (conn->c_trans->t_mp_capable) {
1345 		/* Use c_path[0] until we learn that
1346 		 * the peer supports more (c_npaths > 1)
1347 		 */
1348 		cpath = &conn->c_path[RDS_MPATH_HASH(rs, conn->c_npaths ? : 1)];
1349 	} else {
1350 		cpath = &conn->c_path[0];
1351 	}
1352 
1353 	 /* If we're multipath capable and path 0 is down, queue reconnect
1354 	  * and send a ping. This initiates the multipath handshake through
1355 	  * rds_send_probe(), which sends RDS_EXTHDR_NPATHS to the peer,
1356 	  * starting multipath capability negotiation.
1357 	  */
1358 	if (conn->c_trans->t_mp_capable &&
1359 	    !rds_conn_path_up(&conn->c_path[0])) {
1360 		/* Ensures that only one request is queued.  And
1361 		 * rds_send_ping() ensures that only one ping is
1362 		 * outstanding.
1363 		 */
1364 		if (!test_and_set_bit(RDS_RECONNECT_PENDING,
1365 				      &conn->c_path[0].cp_flags))
1366 			queue_delayed_work(conn->c_path[0].cp_wq,
1367 					   &conn->c_path[0].cp_conn_w, 0);
1368 		rds_send_ping(conn, 0);
1369 	}
1370 
1371 	rm->m_conn_path = cpath;
1372 
1373 	/* Parse any control messages the user may have included. */
1374 	ret = rds_cmsg_send(rs, rm, msg, &allocated_mr, &vct);
1375 	if (ret)
1376 		goto out;
1377 
1378 	if (rm->rdma.op_active && !conn->c_trans->xmit_rdma) {
1379 		printk_ratelimited(KERN_NOTICE "rdma_op %p conn xmit_rdma %p\n",
1380 			       &rm->rdma, conn->c_trans->xmit_rdma);
1381 		ret = -EOPNOTSUPP;
1382 		goto out;
1383 	}
1384 
1385 	if (rm->atomic.op_active && !conn->c_trans->xmit_atomic) {
1386 		printk_ratelimited(KERN_NOTICE "atomic_op %p conn xmit_atomic %p\n",
1387 			       &rm->atomic, conn->c_trans->xmit_atomic);
1388 		ret = -EOPNOTSUPP;
1389 		goto out;
1390 	}
1391 
1392 	if (rds_destroy_pending(conn)) {
1393 		ret = -EAGAIN;
1394 		goto out;
1395 	}
1396 
1397 	if (rds_conn_path_down(cpath))
1398 		rds_check_all_paths(conn);
1399 
1400 	ret = rds_cong_wait(conn->c_fcong, dport, nonblock, rs);
1401 	if (ret) {
1402 		WRITE_ONCE(rs->rs_seen_congestion, 1);
1403 		goto out;
1404 	}
1405 	while (!rds_send_queue_rm(rs, conn, cpath, rm, rs->rs_bound_port,
1406 				  dport, &queued)) {
1407 		rds_stats_inc(s_send_queue_full);
1408 
1409 		if (nonblock) {
1410 			ret = -EAGAIN;
1411 			goto out;
1412 		}
1413 
1414 		timeo = wait_event_interruptible_timeout(*sk_sleep(sk),
1415 					rds_send_queue_rm(rs, conn, cpath, rm,
1416 							  rs->rs_bound_port,
1417 							  dport,
1418 							  &queued),
1419 					timeo);
1420 		rdsdebug("sendmsg woke queued %d timeo %ld\n", queued, timeo);
1421 		if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT)
1422 			continue;
1423 
1424 		ret = timeo;
1425 		if (ret == 0)
1426 			ret = -ETIMEDOUT;
1427 		goto out;
1428 	}
1429 
1430 	/*
1431 	 * By now we've committed to the send.  We reuse rds_send_worker()
1432 	 * to retry sends in the rds thread if the transport asks us to.
1433 	 */
1434 	rds_stats_inc(s_send_queued);
1435 
1436 	ret = rds_send_xmit(cpath);
1437 	if (ret == -ENOMEM || ret == -EAGAIN) {
1438 		ret = 0;
1439 		rcu_read_lock();
1440 		if (rds_destroy_pending(cpath->cp_conn))
1441 			ret = -ENETUNREACH;
1442 		else
1443 			queue_delayed_work(cpath->cp_wq, &cpath->cp_send_w, 1);
1444 		rcu_read_unlock();
1445 
1446 		if (ret)
1447 			goto out;
1448 	}
1449 
1450 	rds_message_put(rm);
1451 
1452 	for (ind = 0; ind < vct.indx; ind++)
1453 		kfree(vct.vec[ind].iov);
1454 	kfree(vct.vec);
1455 
1456 	return payload_len;
1457 
1458 out:
1459 	for (ind = 0; ind < vct.indx; ind++)
1460 		kfree(vct.vec[ind].iov);
1461 	kfree(vct.vec);
1462 
1463 	/* If the user included a RDMA_MAP cmsg, we allocated a MR on the fly.
1464 	 * If the sendmsg goes through, we keep the MR. If it fails with EAGAIN
1465 	 * or in any other way, we need to destroy the MR again */
1466 	if (allocated_mr)
1467 		rds_rdma_unuse(rs, rds_rdma_cookie_key(rm->m_rdma_cookie), 1);
1468 
1469 	if (rm)
1470 		rds_message_put(rm);
1471 	return ret;
1472 }
1473 
1474 /*
1475  * send out a probe. Can be shared by rds_send_ping,
1476  * rds_send_pong, rds_send_hb.
1477  * rds_send_hb should use h_flags
1478  *   RDS_FLAG_HB_PING|RDS_FLAG_ACK_REQUIRED
1479  * or
1480  *   RDS_FLAG_HB_PONG|RDS_FLAG_ACK_REQUIRED
1481  */
1482 static int
1483 rds_send_probe(struct rds_conn_path *cp, __be16 sport,
1484 	       __be16 dport, u8 h_flags)
1485 {
1486 	struct rds_message *rm;
1487 	unsigned long flags;
1488 	int ret = 0;
1489 
1490 	rm = rds_message_alloc(0, GFP_ATOMIC);
1491 	if (!rm) {
1492 		ret = -ENOMEM;
1493 		goto out;
1494 	}
1495 
1496 	rm->m_daddr = cp->cp_conn->c_faddr;
1497 	rm->data.op_active = 1;
1498 
1499 	rds_conn_path_connect_if_down(cp);
1500 
1501 	ret = rds_cong_wait(cp->cp_conn->c_fcong, dport, 1, NULL);
1502 	if (ret)
1503 		goto out;
1504 
1505 	spin_lock_irqsave(&cp->cp_lock, flags);
1506 	list_add_tail(&rm->m_conn_item, &cp->cp_send_queue);
1507 	set_bit(RDS_MSG_ON_CONN, &rm->m_flags);
1508 	rds_message_addref(rm);
1509 	rm->m_inc.i_conn = cp->cp_conn;
1510 	rm->m_inc.i_conn_path = cp;
1511 
1512 	rds_message_populate_header(&rm->m_inc.i_hdr, sport, dport,
1513 				    cp->cp_next_tx_seq);
1514 	rm->m_inc.i_hdr.h_flags |= h_flags;
1515 	cp->cp_next_tx_seq++;
1516 
1517 	if (RDS_HS_PROBE(be16_to_cpu(sport), be16_to_cpu(dport)) &&
1518 	    cp->cp_conn->c_trans->t_mp_capable) {
1519 		__be16 npaths = cpu_to_be16(RDS_MPATH_WORKERS);
1520 		__be32 my_gen_num = cpu_to_be32(cp->cp_conn->c_my_gen_num);
1521 		u8 dummy = 0;
1522 
1523 		rds_message_add_extension(&rm->m_inc.i_hdr,
1524 					  RDS_EXTHDR_NPATHS, &npaths);
1525 		rds_message_add_extension(&rm->m_inc.i_hdr,
1526 					  RDS_EXTHDR_GEN_NUM,
1527 					  &my_gen_num);
1528 		rds_message_add_extension(&rm->m_inc.i_hdr,
1529 					  RDS_EXTHDR_SPORT_IDX,
1530 					  &dummy);
1531 	}
1532 	spin_unlock_irqrestore(&cp->cp_lock, flags);
1533 
1534 	rds_stats_inc(s_send_queued);
1535 	rds_stats_inc(s_send_pong);
1536 
1537 	/* schedule the send work on cp_wq */
1538 	rcu_read_lock();
1539 	if (!rds_destroy_pending(cp->cp_conn))
1540 		queue_delayed_work(cp->cp_wq, &cp->cp_send_w, 1);
1541 	rcu_read_unlock();
1542 
1543 	rds_message_put(rm);
1544 	return 0;
1545 
1546 out:
1547 	if (rm)
1548 		rds_message_put(rm);
1549 	return ret;
1550 }
1551 
1552 int
1553 rds_send_pong(struct rds_conn_path *cp, __be16 dport)
1554 {
1555 	return rds_send_probe(cp, 0, dport, 0);
1556 }
1557 
1558 void
1559 rds_send_ping(struct rds_connection *conn, int cp_index)
1560 {
1561 	unsigned long flags;
1562 	struct rds_conn_path *cp = &conn->c_path[cp_index];
1563 
1564 	spin_lock_irqsave(&cp->cp_lock, flags);
1565 	if (conn->c_ping_triggered) {
1566 		spin_unlock_irqrestore(&cp->cp_lock, flags);
1567 		return;
1568 	}
1569 	conn->c_ping_triggered = 1;
1570 	spin_unlock_irqrestore(&cp->cp_lock, flags);
1571 	rds_send_probe(cp, cpu_to_be16(RDS_FLAG_PROBE_PORT), 0, 0);
1572 }
1573 EXPORT_SYMBOL_GPL(rds_send_ping);
1574