xref: /linux/net/smc/smc_rx.c (revision 8288ba942cfd20621c05e16978b7c3da91513ae1)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Shared Memory Communications over RDMA (SMC-R) and RoCE
4  *
5  * Manage RMBE
6  * copy new RMBE data into user space
7  *
8  * Copyright IBM Corp. 2016
9  *
10  * Author(s):  Ursula Braun <ubraun@linux.vnet.ibm.com>
11  */
12 
13 #include <linux/net.h>
14 #include <linux/rcupdate.h>
15 #include <linux/sched/signal.h>
16 #include <linux/splice.h>
17 
18 #include <net/sock.h>
19 #include <trace/events/sock.h>
20 
21 #include "smc.h"
22 #include "smc_core.h"
23 #include "smc_cdc.h"
24 #include "smc_tx.h" /* smc_tx_consumer_update() */
25 #include "smc_rx.h"
26 #include "smc_stats.h"
27 #include "smc_tracepoint.h"
28 
29 /* callback implementation to wakeup consumers blocked with smc_rx_wait().
30  * indirectly called by smc_cdc_msg_recv_action().
31  */
32 static void smc_rx_wake_up(struct sock *sk)
33 {
34 	struct socket_wq *wq;
35 
36 	trace_sk_data_ready(sk);
37 
38 	/* derived from sock_def_readable() */
39 	/* called already in smc_listen_work() */
40 	rcu_read_lock();
41 	wq = rcu_dereference(sk->sk_wq);
42 	if (skwq_has_sleeper(wq))
43 		wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN | EPOLLPRI |
44 						EPOLLRDNORM | EPOLLRDBAND);
45 	sk_wake_async_rcu(sk, SOCK_WAKE_WAITD, POLL_IN);
46 	if ((sk->sk_shutdown == SHUTDOWN_MASK) ||
47 	    (sk->sk_state == SMC_CLOSED))
48 		sk_wake_async_rcu(sk, SOCK_WAKE_WAITD, POLL_HUP);
49 	rcu_read_unlock();
50 }
51 
52 /* Update consumer cursor
53  *   @conn   connection to update
54  *   @cons   consumer cursor
55  *   @len    number of Bytes consumed
56  *   Returns:
57  *   1 if we should end our receive, 0 otherwise
58  */
59 static int smc_rx_update_consumer(struct smc_sock *smc,
60 				  union smc_host_cursor cons, size_t len)
61 {
62 	struct smc_connection *conn = &smc->conn;
63 	struct sock *sk = &smc->sk;
64 	bool force = false;
65 	int diff, rc = 0;
66 
67 	smc_curs_add(conn->rmb_desc->len, &cons, len);
68 
69 	/* did we process urgent data? */
70 	if (conn->urg_state == SMC_URG_VALID || conn->urg_rx_skip_pend) {
71 		diff = smc_curs_comp(conn->rmb_desc->len, &cons,
72 				     &conn->urg_curs);
73 		if (sock_flag(sk, SOCK_URGINLINE)) {
74 			if (diff == 0) {
75 				force = true;
76 				rc = 1;
77 				conn->urg_state = SMC_URG_READ;
78 			}
79 		} else {
80 			if (diff == 1) {
81 				/* skip urgent byte */
82 				force = true;
83 				smc_curs_add(conn->rmb_desc->len, &cons, 1);
84 				conn->urg_rx_skip_pend = false;
85 			} else if (diff < -1)
86 				/* we read past urgent byte */
87 				conn->urg_state = SMC_URG_READ;
88 		}
89 	}
90 
91 	smc_curs_copy(&conn->local_tx_ctrl.cons, &cons, conn);
92 
93 	/* send consumer cursor update if required */
94 	/* similar to advertising new TCP rcv_wnd if required */
95 	smc_tx_consumer_update(conn, force);
96 
97 	return rc;
98 }
99 
100 static void smc_rx_update_cons(struct smc_sock *smc, size_t len)
101 {
102 	struct smc_connection *conn = &smc->conn;
103 	union smc_host_cursor cons;
104 
105 	smc_curs_copy(&cons, &conn->local_tx_ctrl.cons, conn);
106 	smc_rx_update_consumer(smc, cons, len);
107 }
108 
109 struct smc_spd_priv {
110 	struct smc_sock *smc;
111 	size_t		 len;
112 };
113 
114 static void smc_rx_pipe_buf_release(struct pipe_inode_info *pipe,
115 				    struct pipe_buffer *buf)
116 {
117 	struct smc_spd_priv *priv = (struct smc_spd_priv *)buf->private;
118 	struct smc_connection *conn = &priv->smc->conn;
119 	struct smc_sock *smc = priv->smc;
120 	struct sock *sk = &smc->sk;
121 
122 	lock_sock(sk);
123 	if (conn->freed) {
124 		release_sock(sk);
125 		goto out;
126 	}
127 	smc_rx_update_cons(smc, priv->len);
128 	release_sock(sk);
129 	if (atomic_sub_and_test(priv->len, &conn->splice_pending))
130 		smc_rx_wake_up(sk);
131 out:
132 	kfree(priv);
133 	put_page(buf->page);
134 	sock_put(sk);
135 }
136 
137 static bool smc_rx_pipe_buf_get(struct pipe_inode_info *pipe,
138 				struct pipe_buffer *buf)
139 {
140 	/* smc_spd_priv in buf->private is not shareable; disallow cloning. */
141 	return false;
142 }
143 
144 static const struct pipe_buf_operations smc_pipe_ops = {
145 	.release = smc_rx_pipe_buf_release,
146 	.get	 = smc_rx_pipe_buf_get,
147 };
148 
149 static void smc_rx_spd_release(struct splice_pipe_desc *spd,
150 			       unsigned int i)
151 {
152 	struct smc_spd_priv *priv = (struct smc_spd_priv *)spd->partial[i].private;
153 	struct sock *sk = &priv->smc->sk;
154 
155 	kfree(priv);
156 	put_page(spd->pages[i]);
157 	sock_put(sk);
158 }
159 
160 static int smc_rx_splice(struct pipe_inode_info *pipe, char *src, size_t len,
161 			 struct smc_sock *smc)
162 {
163 	struct smc_link_group *lgr = smc->conn.lgr;
164 	int offset = offset_in_page(src);
165 	struct partial_page *partial;
166 	struct splice_pipe_desc spd;
167 	struct smc_spd_priv **priv;
168 	struct page **pages;
169 	int bytes, nr_pages;
170 	int i;
171 
172 	nr_pages = !lgr->is_smcd && smc->conn.rmb_desc->is_vm ?
173 		   PAGE_ALIGN(len + offset) / PAGE_SIZE : 1;
174 
175 	pages = kzalloc_objs(*pages, nr_pages);
176 	if (!pages)
177 		goto out;
178 	partial = kzalloc_objs(*partial, nr_pages);
179 	if (!partial)
180 		goto out_page;
181 	priv = kzalloc_objs(*priv, nr_pages);
182 	if (!priv)
183 		goto out_part;
184 	for (i = 0; i < nr_pages; i++) {
185 		priv[i] = kzalloc_obj(**priv);
186 		if (!priv[i])
187 			goto out_priv;
188 	}
189 
190 	if (lgr->is_smcd ||
191 	    (!lgr->is_smcd && !smc->conn.rmb_desc->is_vm)) {
192 		/* smcd or smcr that uses physically contiguous RMBs */
193 		priv[0]->len = len;
194 		priv[0]->smc = smc;
195 		partial[0].offset = src - (char *)smc->conn.rmb_desc->cpu_addr;
196 		partial[0].len = len;
197 		partial[0].private = (unsigned long)priv[0];
198 		pages[0] = smc->conn.rmb_desc->pages;
199 	} else {
200 		int size, left = len;
201 		void *buf = src;
202 		/* smcr that uses virtually contiguous RMBs*/
203 		for (i = 0; i < nr_pages; i++) {
204 			size = min_t(int, PAGE_SIZE - offset, left);
205 			priv[i]->len = size;
206 			priv[i]->smc = smc;
207 			pages[i] = vmalloc_to_page(buf);
208 			partial[i].offset = offset;
209 			partial[i].len = size;
210 			partial[i].private = (unsigned long)priv[i];
211 			buf += size;
212 			left -= size;
213 			offset = 0;
214 		}
215 	}
216 	for (i = 0; i < nr_pages; i++) {
217 		get_page(pages[i]);
218 		sock_hold(&smc->sk);
219 	}
220 	spd.nr_pages_max = nr_pages;
221 	spd.nr_pages = nr_pages;
222 	spd.pages = pages;
223 	spd.partial = partial;
224 	spd.ops = &smc_pipe_ops;
225 	spd.spd_release = smc_rx_spd_release;
226 
227 	bytes = splice_to_pipe(pipe, &spd);
228 	if (bytes > 0)
229 		atomic_add(bytes, &smc->conn.splice_pending);
230 	kfree(priv);
231 	kfree(partial);
232 	kfree(pages);
233 
234 	return bytes;
235 
236 out_priv:
237 	for (i = (i - 1); i >= 0; i--)
238 		kfree(priv[i]);
239 	kfree(priv);
240 out_part:
241 	kfree(partial);
242 out_page:
243 	kfree(pages);
244 out:
245 	return -ENOMEM;
246 }
247 
248 static int smc_rx_data_available_and_no_splice_pend(struct smc_connection *conn, size_t peeked)
249 {
250 	return smc_rx_data_available(conn, peeked) &&
251 	       !atomic_read(&conn->splice_pending);
252 }
253 
254 /* blocks rcvbuf consumer until >=len bytes available or timeout or interrupted
255  *   @smc    smc socket
256  *   @timeo  pointer to max seconds to wait, pointer to value 0 for no timeout
257  *   @peeked  number of bytes already peeked
258  *   @fcrit  add'l criterion to evaluate as function pointer
259  * Returns:
260  * 1 if at least 1 byte available in rcvbuf or if socket error/shutdown.
261  * 0 otherwise (nothing in rcvbuf nor timeout, e.g. interrupted).
262  */
263 int smc_rx_wait(struct smc_sock *smc, long *timeo, size_t peeked,
264 		int (*fcrit)(struct smc_connection *conn, size_t baseline))
265 {
266 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
267 	struct smc_connection *conn = &smc->conn;
268 	struct smc_cdc_conn_state_flags *cflags =
269 					&conn->local_tx_ctrl.conn_state_flags;
270 	struct sock *sk = &smc->sk;
271 	int rc;
272 
273 	if (fcrit(conn, peeked))
274 		return 1;
275 	sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
276 	add_wait_queue(sk_sleep(sk), &wait);
277 	rc = sk_wait_event(sk, timeo,
278 			   READ_ONCE(sk->sk_err) ||
279 			   cflags->peer_conn_abort ||
280 			   READ_ONCE(sk->sk_shutdown) & RCV_SHUTDOWN ||
281 			   conn->killed ||
282 			   fcrit(conn, peeked),
283 			   &wait);
284 	remove_wait_queue(sk_sleep(sk), &wait);
285 	sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
286 	return rc;
287 }
288 
289 /* Wait for the pipe to release the spliced data. Unlike smc_rx_wait()
290  * it does not end on shutdown or sk_err, the data is already in the
291  * RMB; smc_conn_kill() wakes it and the caller checks conn->killed.
292  */
293 static void smc_rx_wait_splice(struct smc_sock *smc, long *timeo)
294 {
295 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
296 	struct smc_connection *conn = &smc->conn;
297 	struct sock *sk = &smc->sk;
298 
299 	sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
300 	add_wait_queue(sk_sleep(sk), &wait);
301 	/* pairs with the smp_mb() in wq_has_sleeper(): the release drops
302 	 * splice_pending, then looks for a sleeper
303 	 */
304 	smp_mb();
305 	sk_wait_event(sk, timeo, !atomic_read(&conn->splice_pending), &wait);
306 	remove_wait_queue(sk_sleep(sk), &wait);
307 	sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
308 }
309 
310 static int smc_rx_recv_urg(struct smc_sock *smc, struct msghdr *msg, int len,
311 			   int flags)
312 {
313 	struct smc_connection *conn = &smc->conn;
314 	union smc_host_cursor cons;
315 	struct sock *sk = &smc->sk;
316 	int rc = 0;
317 
318 	if (sock_flag(sk, SOCK_URGINLINE) ||
319 	    !(conn->urg_state == SMC_URG_VALID) ||
320 	    conn->urg_state == SMC_URG_READ)
321 		return -EINVAL;
322 
323 	SMC_STAT_INC(smc, urg_data_cnt);
324 	if (conn->urg_state == SMC_URG_VALID) {
325 		if (!(flags & MSG_PEEK))
326 			smc->conn.urg_state = SMC_URG_READ;
327 		msg->msg_flags |= MSG_OOB;
328 		if (len > 0) {
329 			if (!(flags & MSG_TRUNC))
330 				rc = memcpy_to_msg(msg, &conn->urg_rx_byte, 1);
331 			len = 1;
332 			smc_curs_copy(&cons, &conn->local_tx_ctrl.cons, conn);
333 			if (smc_curs_diff(conn->rmb_desc->len, &cons,
334 					  &conn->urg_curs) > 1)
335 				conn->urg_rx_skip_pend = true;
336 			/* Urgent Byte was already accounted for, but trigger
337 			 * skipping the urgent byte in non-inline case
338 			 */
339 			if (!(flags & MSG_PEEK))
340 				smc_rx_update_consumer(smc, cons, 0);
341 		} else {
342 			msg->msg_flags |= MSG_TRUNC;
343 		}
344 
345 		return rc ? -EFAULT : len;
346 	}
347 
348 	if (sk->sk_state == SMC_CLOSED || sk->sk_shutdown & RCV_SHUTDOWN)
349 		return 0;
350 
351 	return -EAGAIN;
352 }
353 
354 static bool smc_rx_recvmsg_data_available(struct smc_sock *smc, size_t peeked)
355 {
356 	struct smc_connection *conn = &smc->conn;
357 
358 	if (smc_rx_data_available(conn, peeked))
359 		return true;
360 	else if (conn->urg_state == SMC_URG_VALID)
361 		/* we received a single urgent Byte - skip */
362 		smc_rx_update_cons(smc, 0);
363 	return false;
364 }
365 
366 /* smc_rx_recvmsg - receive data from RMBE
367  * @msg:	copy data to receive buffer
368  * @pipe:	copy data to pipe if set - indicates splice() call
369  *
370  * rcvbuf consumer: main API called by socket layer.
371  * Called under sk lock.
372  */
373 int smc_rx_recvmsg(struct smc_sock *smc, struct msghdr *msg,
374 		   struct pipe_inode_info *pipe, size_t len, int flags)
375 {
376 	size_t copylen, read_done = 0, read_remaining = len, peeked_bytes = 0;
377 	size_t chunk_len, chunk_off, chunk_len_sum;
378 	struct smc_connection *conn = &smc->conn;
379 	int (*func)(struct smc_connection *conn, size_t baseline);
380 	union smc_host_cursor cons;
381 	int readable, chunk;
382 	char *rcvbuf_base;
383 	struct sock *sk;
384 	int splbytes;
385 	long timeo;
386 	int target;		/* Read at least these many bytes */
387 	int rc;
388 
389 	if (unlikely(flags & MSG_ERRQUEUE))
390 		return -EINVAL; /* future work for sk.sk_family == AF_SMC */
391 
392 	sk = &smc->sk;
393 	if (sk->sk_state == SMC_LISTEN)
394 		return -ENOTCONN;
395 	if (flags & MSG_OOB)
396 		return smc_rx_recv_urg(smc, msg, len, flags);
397 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
398 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
399 
400 	readable = atomic_read(&conn->bytes_to_rcv);
401 	if (readable >= conn->rmb_desc->len)
402 		SMC_STAT_RMB_RX_FULL(smc, !conn->lnk);
403 
404 	if (len < readable)
405 		SMC_STAT_RMB_RX_SIZE_SMALL(smc, !conn->lnk);
406 	/* we currently use 1 RMBE per RMB, so RMBE == RMB base addr */
407 	rcvbuf_base = conn->rx_off + conn->rmb_desc->cpu_addr;
408 
409 	do { /* while (read_remaining) */
410 		if (read_done >= target || (pipe && read_done))
411 			break;
412 
413 		if (conn->killed)
414 			break;
415 
416 		if (smc_rx_recvmsg_data_available(smc, peeked_bytes))
417 			goto copy;
418 
419 		if (sk->sk_shutdown & RCV_SHUTDOWN) {
420 			/* smc_cdc_msg_recv_action() could have run after
421 			 * above smc_rx_recvmsg_data_available()
422 			 */
423 			if (smc_rx_recvmsg_data_available(smc, peeked_bytes))
424 				goto copy;
425 			break;
426 		}
427 
428 		if (read_done) {
429 			if (sk->sk_err ||
430 			    sk->sk_state == SMC_CLOSED ||
431 			    !timeo ||
432 			    signal_pending(current))
433 				break;
434 		} else {
435 			if (sk->sk_err) {
436 				read_done = sock_error(sk);
437 				break;
438 			}
439 			if (sk->sk_state == SMC_CLOSED) {
440 				if (!sock_flag(sk, SOCK_DONE)) {
441 					/* This occurs when user tries to read
442 					 * from never connected socket.
443 					 */
444 					read_done = -ENOTCONN;
445 					break;
446 				}
447 				break;
448 			}
449 			if (!timeo)
450 				return -EAGAIN;
451 			if (signal_pending(current)) {
452 				read_done = sock_intr_errno(timeo);
453 				break;
454 			}
455 		}
456 
457 		if (!smc_rx_data_available(conn, peeked_bytes)) {
458 			smc_rx_wait(smc, &timeo, peeked_bytes, smc_rx_data_available);
459 			continue;
460 		}
461 
462 copy:
463 		/* initialize variables for 1st iteration of subsequent loop */
464 		/* could be just 1 byte, even after waiting on data above */
465 		readable = smc_rx_data_available(conn, peeked_bytes);
466 		splbytes = atomic_read(&conn->splice_pending);
467 		if (msg && splbytes) {
468 			/* a pipe holds bytes ahead of these; the copy path
469 			 * skips the timeout and signal checks
470 			 */
471 			if (!read_remaining)
472 				break;
473 			if (!timeo || signal_pending(current)) {
474 				if (!read_done)
475 					read_done = timeo ?
476 						    sock_intr_errno(timeo) :
477 						    -EAGAIN;
478 				break;
479 			}
480 			smc_rx_wait_splice(smc, &timeo);
481 			continue;
482 		}
483 		if (!readable) {
484 			if (splbytes)
485 				func = smc_rx_data_available_and_no_splice_pend;
486 			else
487 				func = smc_rx_data_available;
488 			smc_rx_wait(smc, &timeo, peeked_bytes, func);
489 			continue;
490 		}
491 
492 		smc_curs_copy(&cons, &conn->local_tx_ctrl.cons, conn);
493 		if ((flags & MSG_PEEK) && peeked_bytes)
494 			smc_curs_add(conn->rmb_desc->len, &cons, peeked_bytes);
495 		/* subsequent splice() calls pick up where previous left */
496 		if (splbytes)
497 			smc_curs_add(conn->rmb_desc->len, &cons, splbytes);
498 		if (conn->urg_state == SMC_URG_VALID &&
499 		    sock_flag(&smc->sk, SOCK_URGINLINE) &&
500 		    readable > 1)
501 			readable--;	/* always stop at urgent Byte */
502 		/* not more than what user space asked for */
503 		copylen = min_t(size_t, read_remaining, readable);
504 		/* determine chunks where to read from rcvbuf */
505 		/* either unwrapped case, or 1st chunk of wrapped case */
506 		chunk_len = min_t(size_t, copylen, conn->rmb_desc->len -
507 				  cons.count);
508 		chunk_len_sum = chunk_len;
509 		chunk_off = cons.count;
510 		smc_rmb_sync_sg_for_cpu(conn);
511 		for (chunk = 0; chunk < 2; chunk++) {
512 			if (!(flags & MSG_TRUNC)) {
513 				if (msg) {
514 					rc = memcpy_to_msg(msg, rcvbuf_base +
515 							   chunk_off,
516 							   chunk_len);
517 				} else {
518 					rc = smc_rx_splice(pipe, rcvbuf_base +
519 							chunk_off, chunk_len,
520 							smc);
521 				}
522 				if (rc < 0) {
523 					if (!read_done)
524 						read_done = -EFAULT;
525 					goto out;
526 				}
527 			}
528 			read_remaining -= chunk_len;
529 			read_done += chunk_len;
530 			if (flags & MSG_PEEK)
531 				peeked_bytes += chunk_len;
532 
533 			if (chunk_len_sum == copylen)
534 				break; /* either on 1st or 2nd iteration */
535 			/* prepare next (== 2nd) iteration */
536 			chunk_len = copylen - chunk_len; /* remainder */
537 			chunk_len_sum += chunk_len;
538 			chunk_off = 0; /* modulo offset in recv ring buffer */
539 		}
540 
541 		/* update cursors */
542 		if (!(flags & MSG_PEEK)) {
543 			/* increased in recv tasklet smc_cdc_msg_rcv() */
544 			smp_mb__before_atomic();
545 			atomic_sub(copylen, &conn->bytes_to_rcv);
546 			/* guarantee 0 <= bytes_to_rcv <= rmb_desc->len */
547 			smp_mb__after_atomic();
548 			if (msg && smc_rx_update_consumer(smc, cons, copylen))
549 				goto out;
550 		}
551 
552 		trace_smc_rx_recvmsg(smc, copylen);
553 	} while (read_remaining);
554 out:
555 	return read_done;
556 }
557 
558 /* Initialize receive properties on connection establishment. NB: not __init! */
559 void smc_rx_init(struct smc_sock *smc)
560 {
561 	smc->sk.sk_data_ready = smc_rx_wake_up;
562 	atomic_set(&smc->conn.splice_pending, 0);
563 	smc->conn.urg_state = SMC_URG_READ;
564 }
565