1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * RDMA Transport Layer
4  *
5  * Copyright (c) 2014 - 2018 ProfitBricks GmbH. All rights reserved.
6  * Copyright (c) 2018 - 2019 1&1 IONOS Cloud GmbH. All rights reserved.
7  * Copyright (c) 2019 - 2020 1&1 IONOS SE. All rights reserved.
8  */
9 
10 #undef pr_fmt
11 #define pr_fmt(fmt) KBUILD_MODNAME " L" __stringify(__LINE__) ": " fmt
12 
13 #include <linux/module.h>
14 #include <linux/rculist.h>
15 #include <linux/random.h>
16 
17 #include "rtrs-clt.h"
18 #include "rtrs-log.h"
19 
20 #define RTRS_CONNECT_TIMEOUT_MS 30000
21 /*
22  * Wait a bit before trying to reconnect after a failure
23  * in order to give server time to finish clean up which
24  * leads to "false positives" failed reconnect attempts
25  */
26 #define RTRS_RECONNECT_BACKOFF 1000
27 /*
28  * Wait for additional random time between 0 and 8 seconds
29  * before starting to reconnect to avoid clients reconnecting
30  * all at once in case of a major network outage
31  */
32 #define RTRS_RECONNECT_SEED 8
33 
34 #define FIRST_CONN 0x01
35 /* limit to 128 * 4k = 512k max IO */
36 #define RTRS_MAX_SEGMENTS          128
37 
38 MODULE_DESCRIPTION("RDMA Transport Client");
39 MODULE_LICENSE("GPL");
40 
41 static const struct rtrs_rdma_dev_pd_ops dev_pd_ops;
42 static struct rtrs_rdma_dev_pd dev_pd = {
43 	.ops = &dev_pd_ops
44 };
45 
46 static struct workqueue_struct *rtrs_wq;
47 static struct class *rtrs_clt_dev_class;
48 
49 static inline bool rtrs_clt_is_connected(const struct rtrs_clt_sess *clt)
50 {
51 	struct rtrs_clt_path *clt_path;
52 	bool connected = false;
53 
54 	rcu_read_lock();
55 	list_for_each_entry_rcu(clt_path, &clt->paths_list, s.entry)
56 		connected |= READ_ONCE(clt_path->state) == RTRS_CLT_CONNECTED;
57 	rcu_read_unlock();
58 
59 	return connected;
60 }
61 
62 static struct rtrs_permit *
63 __rtrs_get_permit(struct rtrs_clt_sess *clt, enum rtrs_clt_con_type con_type)
64 {
65 	size_t max_depth = clt->queue_depth;
66 	struct rtrs_permit *permit;
67 	int bit;
68 
69 	/*
70 	 * Adapted from null_blk get_tag(). Callers from different cpus may
71 	 * grab the same bit, since find_first_zero_bit is not atomic.
72 	 * But then the test_and_set_bit_lock will fail for all the
73 	 * callers but one, so that they will loop again.
74 	 * This way an explicit spinlock is not required.
75 	 */
76 	do {
77 		bit = find_first_zero_bit(clt->permits_map, max_depth);
78 		if (bit >= max_depth)
79 			return NULL;
80 	} while (test_and_set_bit_lock(bit, clt->permits_map));
81 
82 	permit = get_permit(clt, bit);
83 	WARN_ON(permit->mem_id != bit);
84 	permit->cpu_id = raw_smp_processor_id();
85 	permit->con_type = con_type;
86 
87 	return permit;
88 }
89 
90 static inline void __rtrs_put_permit(struct rtrs_clt_sess *clt,
91 				      struct rtrs_permit *permit)
92 {
93 	clear_bit_unlock(permit->mem_id, clt->permits_map);
94 }
95 
96 /**
97  * rtrs_clt_get_permit() - allocates permit for future RDMA operation
98  * @clt:	Current session
99  * @con_type:	Type of connection to use with the permit
100  * @can_wait:	Wait type
101  *
102  * Description:
103  *    Allocates permit for the following RDMA operation.  Permit is used
104  *    to preallocate all resources and to propagate memory pressure
105  *    up earlier.
106  *
107  * Context:
108  *    Can sleep if @wait == RTRS_PERMIT_WAIT
109  */
110 struct rtrs_permit *rtrs_clt_get_permit(struct rtrs_clt_sess *clt,
111 					  enum rtrs_clt_con_type con_type,
112 					  enum wait_type can_wait)
113 {
114 	struct rtrs_permit *permit;
115 	DEFINE_WAIT(wait);
116 
117 	permit = __rtrs_get_permit(clt, con_type);
118 	if (permit || !can_wait)
119 		return permit;
120 
121 	do {
122 		prepare_to_wait(&clt->permits_wait, &wait,
123 				TASK_UNINTERRUPTIBLE);
124 		permit = __rtrs_get_permit(clt, con_type);
125 		if (permit)
126 			break;
127 
128 		io_schedule();
129 	} while (1);
130 
131 	finish_wait(&clt->permits_wait, &wait);
132 
133 	return permit;
134 }
135 EXPORT_SYMBOL(rtrs_clt_get_permit);
136 
137 /**
138  * rtrs_clt_put_permit() - puts allocated permit
139  * @clt:	Current session
140  * @permit:	Permit to be freed
141  *
142  * Context:
143  *    Does not matter
144  */
145 void rtrs_clt_put_permit(struct rtrs_clt_sess *clt,
146 			 struct rtrs_permit *permit)
147 {
148 	if (WARN_ON(!test_bit(permit->mem_id, clt->permits_map)))
149 		return;
150 
151 	__rtrs_put_permit(clt, permit);
152 
153 	/*
154 	 * rtrs_clt_get_permit() adds itself to the &clt->permits_wait list
155 	 * before calling schedule(). So if rtrs_clt_get_permit() is sleeping
156 	 * it must have added itself to &clt->permits_wait before
157 	 * __rtrs_put_permit() finished.
158 	 * Hence it is safe to guard wake_up() with a waitqueue_active() test.
159 	 */
160 	if (waitqueue_active(&clt->permits_wait))
161 		wake_up(&clt->permits_wait);
162 }
163 EXPORT_SYMBOL(rtrs_clt_put_permit);
164 
165 /**
166  * rtrs_permit_to_clt_con() - returns RDMA connection pointer by the permit
167  * @clt_path: client path pointer
168  * @permit: permit for the allocation of the RDMA buffer
169  * Note:
170  *     IO connection starts from 1.
171  *     0 connection is for user messages.
172  */
173 static
174 struct rtrs_clt_con *rtrs_permit_to_clt_con(struct rtrs_clt_path *clt_path,
175 					    struct rtrs_permit *permit)
176 {
177 	int id = 0;
178 
179 	if (permit->con_type == RTRS_IO_CON)
180 		id = (permit->cpu_id % (clt_path->s.irq_con_num - 1)) + 1;
181 
182 	return to_clt_con(clt_path->s.con[id]);
183 }
184 
185 /**
186  * rtrs_clt_change_state() - change the session state through session state
187  * machine.
188  *
189  * @clt_path: client path to change the state of.
190  * @new_state: state to change to.
191  *
192  * returns true if sess's state is changed to new state, otherwise return false.
193  *
194  * Locks:
195  * state_wq lock must be hold.
196  */
197 static bool rtrs_clt_change_state(struct rtrs_clt_path *clt_path,
198 				     enum rtrs_clt_state new_state)
199 {
200 	enum rtrs_clt_state old_state;
201 	bool changed = false;
202 
203 	lockdep_assert_held(&clt_path->state_wq.lock);
204 
205 	old_state = clt_path->state;
206 	switch (new_state) {
207 	case RTRS_CLT_CONNECTING:
208 		switch (old_state) {
209 		case RTRS_CLT_RECONNECTING:
210 			changed = true;
211 			fallthrough;
212 		default:
213 			break;
214 		}
215 		break;
216 	case RTRS_CLT_RECONNECTING:
217 		switch (old_state) {
218 		case RTRS_CLT_CONNECTED:
219 		case RTRS_CLT_CONNECTING_ERR:
220 		case RTRS_CLT_CLOSED:
221 			changed = true;
222 			fallthrough;
223 		default:
224 			break;
225 		}
226 		break;
227 	case RTRS_CLT_CONNECTED:
228 		switch (old_state) {
229 		case RTRS_CLT_CONNECTING:
230 			changed = true;
231 			fallthrough;
232 		default:
233 			break;
234 		}
235 		break;
236 	case RTRS_CLT_CONNECTING_ERR:
237 		switch (old_state) {
238 		case RTRS_CLT_CONNECTING:
239 			changed = true;
240 			fallthrough;
241 		default:
242 			break;
243 		}
244 		break;
245 	case RTRS_CLT_CLOSING:
246 		switch (old_state) {
247 		case RTRS_CLT_CONNECTING:
248 		case RTRS_CLT_CONNECTING_ERR:
249 		case RTRS_CLT_RECONNECTING:
250 		case RTRS_CLT_CONNECTED:
251 			changed = true;
252 			fallthrough;
253 		default:
254 			break;
255 		}
256 		break;
257 	case RTRS_CLT_CLOSED:
258 		switch (old_state) {
259 		case RTRS_CLT_CLOSING:
260 			changed = true;
261 			fallthrough;
262 		default:
263 			break;
264 		}
265 		break;
266 	case RTRS_CLT_DEAD:
267 		switch (old_state) {
268 		case RTRS_CLT_CLOSED:
269 			changed = true;
270 			fallthrough;
271 		default:
272 			break;
273 		}
274 		break;
275 	default:
276 		break;
277 	}
278 	if (changed) {
279 		clt_path->state = new_state;
280 		wake_up_locked(&clt_path->state_wq);
281 	}
282 
283 	return changed;
284 }
285 
286 static bool rtrs_clt_change_state_from_to(struct rtrs_clt_path *clt_path,
287 					   enum rtrs_clt_state old_state,
288 					   enum rtrs_clt_state new_state)
289 {
290 	bool changed = false;
291 
292 	spin_lock_irq(&clt_path->state_wq.lock);
293 	if (clt_path->state == old_state)
294 		changed = rtrs_clt_change_state(clt_path, new_state);
295 	spin_unlock_irq(&clt_path->state_wq.lock);
296 
297 	return changed;
298 }
299 
300 static void rtrs_clt_stop_and_destroy_conns(struct rtrs_clt_path *clt_path);
301 static void rtrs_rdma_error_recovery(struct rtrs_clt_con *con)
302 {
303 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
304 
305 	if (rtrs_clt_change_state_from_to(clt_path,
306 					   RTRS_CLT_CONNECTED,
307 					   RTRS_CLT_RECONNECTING)) {
308 		queue_work(rtrs_wq, &clt_path->err_recovery_work);
309 	} else {
310 		/*
311 		 * Error can happen just on establishing new connection,
312 		 * so notify waiter with error state, waiter is responsible
313 		 * for cleaning the rest and reconnect if needed.
314 		 */
315 		rtrs_clt_change_state_from_to(clt_path,
316 					       RTRS_CLT_CONNECTING,
317 					       RTRS_CLT_CONNECTING_ERR);
318 	}
319 }
320 
321 static void rtrs_clt_fast_reg_done(struct ib_cq *cq, struct ib_wc *wc)
322 {
323 	struct rtrs_clt_con *con = to_clt_con(wc->qp->qp_context);
324 
325 	if (wc->status != IB_WC_SUCCESS) {
326 		rtrs_err(con->c.path, "Failed IB_WR_REG_MR: %s\n",
327 			  ib_wc_status_msg(wc->status));
328 		rtrs_rdma_error_recovery(con);
329 	}
330 }
331 
332 static struct ib_cqe fast_reg_cqe = {
333 	.done = rtrs_clt_fast_reg_done
334 };
335 
336 static void complete_rdma_req(struct rtrs_clt_io_req *req, int errno,
337 			      bool notify, bool can_wait);
338 
339 static void rtrs_clt_inv_rkey_done(struct ib_cq *cq, struct ib_wc *wc)
340 {
341 	struct rtrs_clt_io_req *req =
342 		container_of(wc->wr_cqe, typeof(*req), inv_cqe);
343 	struct rtrs_clt_con *con = to_clt_con(wc->qp->qp_context);
344 
345 	if (wc->status != IB_WC_SUCCESS) {
346 		rtrs_err(con->c.path, "Failed IB_WR_LOCAL_INV: %s\n",
347 			  ib_wc_status_msg(wc->status));
348 		rtrs_rdma_error_recovery(con);
349 	}
350 	req->need_inv = false;
351 	if (req->need_inv_comp)
352 		complete(&req->inv_comp);
353 	else
354 		/* Complete request from INV callback */
355 		complete_rdma_req(req, req->inv_errno, true, false);
356 }
357 
358 static int rtrs_inv_rkey(struct rtrs_clt_io_req *req)
359 {
360 	struct rtrs_clt_con *con = req->con;
361 	struct ib_send_wr wr = {
362 		.opcode		    = IB_WR_LOCAL_INV,
363 		.wr_cqe		    = &req->inv_cqe,
364 		.send_flags	    = IB_SEND_SIGNALED,
365 		.ex.invalidate_rkey = req->mr->rkey,
366 	};
367 	req->inv_cqe.done = rtrs_clt_inv_rkey_done;
368 
369 	return ib_post_send(con->c.qp, &wr, NULL);
370 }
371 
372 static void complete_rdma_req(struct rtrs_clt_io_req *req, int errno,
373 			      bool notify, bool can_wait)
374 {
375 	struct rtrs_clt_con *con = req->con;
376 	struct rtrs_clt_path *clt_path;
377 	int err;
378 
379 	if (WARN_ON(!req->in_use))
380 		return;
381 	if (WARN_ON(!req->con))
382 		return;
383 	clt_path = to_clt_path(con->c.path);
384 
385 	if (req->sg_cnt) {
386 		if (req->dir == DMA_FROM_DEVICE && req->need_inv) {
387 			/*
388 			 * We are here to invalidate read requests
389 			 * ourselves.  In normal scenario server should
390 			 * send INV for all read requests, but
391 			 * we are here, thus two things could happen:
392 			 *
393 			 *    1.  this is failover, when errno != 0
394 			 *        and can_wait == 1,
395 			 *
396 			 *    2.  something totally bad happened and
397 			 *        server forgot to send INV, so we
398 			 *        should do that ourselves.
399 			 */
400 
401 			if (can_wait) {
402 				req->need_inv_comp = true;
403 			} else {
404 				/* This should be IO path, so always notify */
405 				WARN_ON(!notify);
406 				/* Save errno for INV callback */
407 				req->inv_errno = errno;
408 			}
409 
410 			refcount_inc(&req->ref);
411 			err = rtrs_inv_rkey(req);
412 			if (err) {
413 				rtrs_err(con->c.path, "Send INV WR key=%#x: %d\n",
414 					  req->mr->rkey, err);
415 			} else if (can_wait) {
416 				wait_for_completion(&req->inv_comp);
417 			} else {
418 				/*
419 				 * Something went wrong, so request will be
420 				 * completed from INV callback.
421 				 */
422 				WARN_ON_ONCE(1);
423 
424 				return;
425 			}
426 			if (!refcount_dec_and_test(&req->ref))
427 				return;
428 		}
429 		ib_dma_unmap_sg(clt_path->s.dev->ib_dev, req->sglist,
430 				req->sg_cnt, req->dir);
431 	}
432 	if (!refcount_dec_and_test(&req->ref))
433 		return;
434 	if (req->mp_policy == MP_POLICY_MIN_INFLIGHT)
435 		atomic_dec(&clt_path->stats->inflight);
436 
437 	req->in_use = false;
438 	req->con = NULL;
439 
440 	if (errno) {
441 		rtrs_err_rl(con->c.path, "IO request failed: error=%d path=%s [%s:%u] notify=%d\n",
442 			    errno, kobject_name(&clt_path->kobj), clt_path->hca_name,
443 			    clt_path->hca_port, notify);
444 	}
445 
446 	if (notify)
447 		req->conf(req->priv, errno);
448 }
449 
450 static int rtrs_post_send_rdma(struct rtrs_clt_con *con,
451 				struct rtrs_clt_io_req *req,
452 				struct rtrs_rbuf *rbuf, u32 off,
453 				u32 imm, struct ib_send_wr *wr)
454 {
455 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
456 	enum ib_send_flags flags;
457 	struct ib_sge sge;
458 
459 	if (!req->sg_size) {
460 		rtrs_wrn(con->c.path,
461 			 "Doing RDMA Write failed, no data supplied\n");
462 		return -EINVAL;
463 	}
464 
465 	/* user data and user message in the first list element */
466 	sge.addr   = req->iu->dma_addr;
467 	sge.length = req->sg_size;
468 	sge.lkey   = clt_path->s.dev->ib_pd->local_dma_lkey;
469 
470 	/*
471 	 * From time to time we have to post signalled sends,
472 	 * or send queue will fill up and only QP reset can help.
473 	 */
474 	flags = atomic_inc_return(&con->c.wr_cnt) % clt_path->s.signal_interval ?
475 			0 : IB_SEND_SIGNALED;
476 
477 	ib_dma_sync_single_for_device(clt_path->s.dev->ib_dev,
478 				      req->iu->dma_addr,
479 				      req->sg_size, DMA_TO_DEVICE);
480 
481 	return rtrs_iu_post_rdma_write_imm(&con->c, req->iu, &sge, 1,
482 					    rbuf->rkey, rbuf->addr + off,
483 					    imm, flags, wr, NULL);
484 }
485 
486 static void process_io_rsp(struct rtrs_clt_path *clt_path, u32 msg_id,
487 			   s16 errno, bool w_inval)
488 {
489 	struct rtrs_clt_io_req *req;
490 
491 	if (WARN_ON(msg_id >= clt_path->queue_depth))
492 		return;
493 
494 	req = &clt_path->reqs[msg_id];
495 	/* Drop need_inv if server responded with send with invalidation */
496 	req->need_inv &= !w_inval;
497 	complete_rdma_req(req, errno, true, false);
498 }
499 
500 static void rtrs_clt_recv_done(struct rtrs_clt_con *con, struct ib_wc *wc)
501 {
502 	struct rtrs_iu *iu;
503 	int err;
504 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
505 
506 	WARN_ON((clt_path->flags & RTRS_MSG_NEW_RKEY_F) == 0);
507 	iu = container_of(wc->wr_cqe, struct rtrs_iu,
508 			  cqe);
509 	err = rtrs_iu_post_recv(&con->c, iu);
510 	if (err) {
511 		rtrs_err(con->c.path, "post iu failed %d\n", err);
512 		rtrs_rdma_error_recovery(con);
513 	}
514 }
515 
516 static void rtrs_clt_rkey_rsp_done(struct rtrs_clt_con *con, struct ib_wc *wc)
517 {
518 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
519 	struct rtrs_msg_rkey_rsp *msg;
520 	u32 imm_type, imm_payload;
521 	bool w_inval = false;
522 	struct rtrs_iu *iu;
523 	u32 buf_id;
524 	int err;
525 
526 	WARN_ON((clt_path->flags & RTRS_MSG_NEW_RKEY_F) == 0);
527 
528 	iu = container_of(wc->wr_cqe, struct rtrs_iu, cqe);
529 
530 	if (wc->byte_len < sizeof(*msg)) {
531 		rtrs_err(con->c.path, "rkey response is malformed: size %d\n",
532 			  wc->byte_len);
533 		goto out;
534 	}
535 	ib_dma_sync_single_for_cpu(clt_path->s.dev->ib_dev, iu->dma_addr,
536 				   iu->size, DMA_FROM_DEVICE);
537 	msg = iu->buf;
538 	if (le16_to_cpu(msg->type) != RTRS_MSG_RKEY_RSP) {
539 		rtrs_err(clt_path->clt,
540 			  "rkey response is malformed: type %d\n",
541 			  le16_to_cpu(msg->type));
542 		goto out;
543 	}
544 	buf_id = le16_to_cpu(msg->buf_id);
545 	if (WARN_ON(buf_id >= clt_path->queue_depth))
546 		goto out;
547 
548 	rtrs_from_imm(be32_to_cpu(wc->ex.imm_data), &imm_type, &imm_payload);
549 	if (imm_type == RTRS_IO_RSP_IMM ||
550 	    imm_type == RTRS_IO_RSP_W_INV_IMM) {
551 		u32 msg_id;
552 
553 		w_inval = (imm_type == RTRS_IO_RSP_W_INV_IMM);
554 		rtrs_from_io_rsp_imm(imm_payload, &msg_id, &err);
555 
556 		if (WARN_ON(buf_id != msg_id))
557 			goto out;
558 		clt_path->rbufs[buf_id].rkey = le32_to_cpu(msg->rkey);
559 		process_io_rsp(clt_path, msg_id, err, w_inval);
560 	}
561 	ib_dma_sync_single_for_device(clt_path->s.dev->ib_dev, iu->dma_addr,
562 				      iu->size, DMA_FROM_DEVICE);
563 	return rtrs_clt_recv_done(con, wc);
564 out:
565 	rtrs_rdma_error_recovery(con);
566 }
567 
568 static void rtrs_clt_rdma_done(struct ib_cq *cq, struct ib_wc *wc);
569 
570 static struct ib_cqe io_comp_cqe = {
571 	.done = rtrs_clt_rdma_done
572 };
573 
574 /*
575  * Post x2 empty WRs: first is for this RDMA with IMM,
576  * second is for RECV with INV, which happened earlier.
577  */
578 static int rtrs_post_recv_empty_x2(struct rtrs_con *con, struct ib_cqe *cqe)
579 {
580 	struct ib_recv_wr wr_arr[2], *wr;
581 	int i;
582 
583 	memset(wr_arr, 0, sizeof(wr_arr));
584 	for (i = 0; i < ARRAY_SIZE(wr_arr); i++) {
585 		wr = &wr_arr[i];
586 		wr->wr_cqe  = cqe;
587 		if (i)
588 			/* Chain backwards */
589 			wr->next = &wr_arr[i - 1];
590 	}
591 
592 	return ib_post_recv(con->qp, wr, NULL);
593 }
594 
595 static void rtrs_clt_rdma_done(struct ib_cq *cq, struct ib_wc *wc)
596 {
597 	struct rtrs_clt_con *con = to_clt_con(wc->qp->qp_context);
598 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
599 	u32 imm_type, imm_payload;
600 	bool w_inval = false;
601 	int err;
602 
603 	if (wc->status != IB_WC_SUCCESS) {
604 		if (wc->status != IB_WC_WR_FLUSH_ERR) {
605 			rtrs_err(clt_path->clt, "RDMA failed: %s\n",
606 				  ib_wc_status_msg(wc->status));
607 			rtrs_rdma_error_recovery(con);
608 		}
609 		return;
610 	}
611 	rtrs_clt_update_wc_stats(con);
612 
613 	switch (wc->opcode) {
614 	case IB_WC_RECV_RDMA_WITH_IMM:
615 		/*
616 		 * post_recv() RDMA write completions of IO reqs (read/write)
617 		 * and hb
618 		 */
619 		if (WARN_ON(wc->wr_cqe->done != rtrs_clt_rdma_done))
620 			return;
621 		rtrs_from_imm(be32_to_cpu(wc->ex.imm_data),
622 			       &imm_type, &imm_payload);
623 		if (imm_type == RTRS_IO_RSP_IMM ||
624 		    imm_type == RTRS_IO_RSP_W_INV_IMM) {
625 			u32 msg_id;
626 
627 			w_inval = (imm_type == RTRS_IO_RSP_W_INV_IMM);
628 			rtrs_from_io_rsp_imm(imm_payload, &msg_id, &err);
629 
630 			process_io_rsp(clt_path, msg_id, err, w_inval);
631 		} else if (imm_type == RTRS_HB_MSG_IMM) {
632 			WARN_ON(con->c.cid);
633 			rtrs_send_hb_ack(&clt_path->s);
634 			if (clt_path->flags & RTRS_MSG_NEW_RKEY_F)
635 				return  rtrs_clt_recv_done(con, wc);
636 		} else if (imm_type == RTRS_HB_ACK_IMM) {
637 			WARN_ON(con->c.cid);
638 			clt_path->s.hb_missed_cnt = 0;
639 			clt_path->s.hb_cur_latency =
640 				ktime_sub(ktime_get(), clt_path->s.hb_last_sent);
641 			if (clt_path->flags & RTRS_MSG_NEW_RKEY_F)
642 				return  rtrs_clt_recv_done(con, wc);
643 		} else {
644 			rtrs_wrn(con->c.path, "Unknown IMM type %u\n",
645 				  imm_type);
646 		}
647 		if (w_inval)
648 			/*
649 			 * Post x2 empty WRs: first is for this RDMA with IMM,
650 			 * second is for RECV with INV, which happened earlier.
651 			 */
652 			err = rtrs_post_recv_empty_x2(&con->c, &io_comp_cqe);
653 		else
654 			err = rtrs_post_recv_empty(&con->c, &io_comp_cqe);
655 		if (err) {
656 			rtrs_err(con->c.path, "rtrs_post_recv_empty(): %d\n",
657 				  err);
658 			rtrs_rdma_error_recovery(con);
659 		}
660 		break;
661 	case IB_WC_RECV:
662 		/*
663 		 * Key invalidations from server side
664 		 */
665 		WARN_ON(!(wc->wc_flags & IB_WC_WITH_INVALIDATE ||
666 			  wc->wc_flags & IB_WC_WITH_IMM));
667 		WARN_ON(wc->wr_cqe->done != rtrs_clt_rdma_done);
668 		if (clt_path->flags & RTRS_MSG_NEW_RKEY_F) {
669 			if (wc->wc_flags & IB_WC_WITH_INVALIDATE)
670 				return  rtrs_clt_recv_done(con, wc);
671 
672 			return  rtrs_clt_rkey_rsp_done(con, wc);
673 		}
674 		break;
675 	case IB_WC_RDMA_WRITE:
676 		/*
677 		 * post_send() RDMA write completions of IO reqs (read/write)
678 		 * and hb.
679 		 */
680 		break;
681 
682 	default:
683 		rtrs_wrn(clt_path->clt, "Unexpected WC type: %d\n", wc->opcode);
684 		return;
685 	}
686 }
687 
688 static int post_recv_io(struct rtrs_clt_con *con, size_t q_size)
689 {
690 	int err, i;
691 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
692 
693 	for (i = 0; i < q_size; i++) {
694 		if (clt_path->flags & RTRS_MSG_NEW_RKEY_F) {
695 			struct rtrs_iu *iu = &con->rsp_ius[i];
696 
697 			err = rtrs_iu_post_recv(&con->c, iu);
698 		} else {
699 			err = rtrs_post_recv_empty(&con->c, &io_comp_cqe);
700 		}
701 		if (err)
702 			return err;
703 	}
704 
705 	return 0;
706 }
707 
708 static int post_recv_path(struct rtrs_clt_path *clt_path)
709 {
710 	size_t q_size = 0;
711 	int err, cid;
712 
713 	for (cid = 0; cid < clt_path->s.con_num; cid++) {
714 		if (cid == 0)
715 			q_size = SERVICE_CON_QUEUE_DEPTH;
716 		else
717 			q_size = clt_path->queue_depth;
718 
719 		/*
720 		 * x2 for RDMA read responses + FR key invalidations,
721 		 * RDMA writes do not require any FR registrations.
722 		 */
723 		q_size *= 2;
724 
725 		err = post_recv_io(to_clt_con(clt_path->s.con[cid]), q_size);
726 		if (err) {
727 			rtrs_err(clt_path->clt, "post_recv_io(), err: %d\n",
728 				 err);
729 			return err;
730 		}
731 	}
732 
733 	return 0;
734 }
735 
736 struct path_it {
737 	int i;
738 	struct list_head skip_list;
739 	struct rtrs_clt_sess *clt;
740 	struct rtrs_clt_path *(*next_path)(struct path_it *it);
741 };
742 
743 /*
744  * rtrs_clt_get_next_path_or_null - get clt path from the list or return NULL
745  * @head:	the head for the list.
746  * @clt_path:	The element to take the next clt_path from.
747  *
748  * Next clt path returned in round-robin fashion, i.e. head will be skipped,
749  * but if list is observed as empty, NULL will be returned.
750  *
751  * This function may safely run concurrently with the _rcu list-mutation
752  * primitives such as list_add_rcu() as long as it's guarded by rcu_read_lock().
753  */
754 static inline struct rtrs_clt_path *
755 rtrs_clt_get_next_path_or_null(struct list_head *head, struct rtrs_clt_path *clt_path)
756 {
757 	return list_next_or_null_rcu(head, &clt_path->s.entry, typeof(*clt_path), s.entry) ?:
758 				     list_next_or_null_rcu(head,
759 							   READ_ONCE((&clt_path->s.entry)->next),
760 							   typeof(*clt_path), s.entry);
761 }
762 
763 /**
764  * get_next_path_rr() - Returns path in round-robin fashion.
765  * @it:	the path pointer
766  *
767  * Related to @MP_POLICY_RR
768  *
769  * Locks:
770  *    rcu_read_lock() must be hold.
771  */
772 static struct rtrs_clt_path *get_next_path_rr(struct path_it *it)
773 {
774 	struct rtrs_clt_path __rcu **ppcpu_path;
775 	struct rtrs_clt_path *path;
776 	struct rtrs_clt_sess *clt;
777 
778 	clt = it->clt;
779 
780 	/*
781 	 * Here we use two RCU objects: @paths_list and @pcpu_path
782 	 * pointer.  See rtrs_clt_remove_path_from_arr() for details
783 	 * how that is handled.
784 	 */
785 
786 	ppcpu_path = this_cpu_ptr(clt->pcpu_path);
787 	path = rcu_dereference(*ppcpu_path);
788 	if (!path)
789 		path = list_first_or_null_rcu(&clt->paths_list,
790 					      typeof(*path), s.entry);
791 	else
792 		path = rtrs_clt_get_next_path_or_null(&clt->paths_list, path);
793 
794 	rcu_assign_pointer(*ppcpu_path, path);
795 
796 	return path;
797 }
798 
799 /**
800  * get_next_path_min_inflight() - Returns path with minimal inflight count.
801  * @it:	the path pointer
802  *
803  * Related to @MP_POLICY_MIN_INFLIGHT
804  *
805  * Locks:
806  *    rcu_read_lock() must be hold.
807  */
808 static struct rtrs_clt_path *get_next_path_min_inflight(struct path_it *it)
809 {
810 	struct rtrs_clt_path *min_path = NULL;
811 	struct rtrs_clt_sess *clt = it->clt;
812 	struct rtrs_clt_path *clt_path;
813 	int min_inflight = INT_MAX;
814 	int inflight;
815 
816 	list_for_each_entry_rcu(clt_path, &clt->paths_list, s.entry) {
817 		if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTED)
818 			continue;
819 
820 		if (!list_empty(raw_cpu_ptr(clt_path->mp_skip_entry)))
821 			continue;
822 
823 		inflight = atomic_read(&clt_path->stats->inflight);
824 
825 		if (inflight < min_inflight) {
826 			min_inflight = inflight;
827 			min_path = clt_path;
828 		}
829 	}
830 
831 	/*
832 	 * add the path to the skip list, so that next time we can get
833 	 * a different one
834 	 */
835 	if (min_path)
836 		list_add(raw_cpu_ptr(min_path->mp_skip_entry), &it->skip_list);
837 
838 	return min_path;
839 }
840 
841 /**
842  * get_next_path_min_latency() - Returns path with minimal latency.
843  * @it:	the path pointer
844  *
845  * Return: a path with the lowest latency or NULL if all paths are tried
846  *
847  * Locks:
848  *    rcu_read_lock() must be hold.
849  *
850  * Related to @MP_POLICY_MIN_LATENCY
851  *
852  * This DOES skip an already-tried path.
853  * There is a skip-list to skip a path if the path has tried but failed.
854  * It will try the minimum latency path and then the second minimum latency
855  * path and so on. Finally it will return NULL if all paths are tried.
856  * Therefore the caller MUST check the returned
857  * path is NULL and trigger the IO error.
858  */
859 static struct rtrs_clt_path *get_next_path_min_latency(struct path_it *it)
860 {
861 	struct rtrs_clt_path *min_path = NULL;
862 	struct rtrs_clt_sess *clt = it->clt;
863 	struct rtrs_clt_path *clt_path;
864 	ktime_t min_latency = KTIME_MAX;
865 	ktime_t latency;
866 
867 	list_for_each_entry_rcu(clt_path, &clt->paths_list, s.entry) {
868 		if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTED)
869 			continue;
870 
871 		if (!list_empty(raw_cpu_ptr(clt_path->mp_skip_entry)))
872 			continue;
873 
874 		latency = clt_path->s.hb_cur_latency;
875 
876 		if (latency < min_latency) {
877 			min_latency = latency;
878 			min_path = clt_path;
879 		}
880 	}
881 
882 	/*
883 	 * add the path to the skip list, so that next time we can get
884 	 * a different one
885 	 */
886 	if (min_path)
887 		list_add(raw_cpu_ptr(min_path->mp_skip_entry), &it->skip_list);
888 
889 	return min_path;
890 }
891 
892 static inline void path_it_init(struct path_it *it, struct rtrs_clt_sess *clt)
893 {
894 	INIT_LIST_HEAD(&it->skip_list);
895 	it->clt = clt;
896 	it->i = 0;
897 
898 	if (clt->mp_policy == MP_POLICY_RR)
899 		it->next_path = get_next_path_rr;
900 	else if (clt->mp_policy == MP_POLICY_MIN_INFLIGHT)
901 		it->next_path = get_next_path_min_inflight;
902 	else
903 		it->next_path = get_next_path_min_latency;
904 }
905 
906 static inline void path_it_deinit(struct path_it *it)
907 {
908 	struct list_head *skip, *tmp;
909 	/*
910 	 * The skip_list is used only for the MIN_INFLIGHT and MIN_LATENCY policies.
911 	 * We need to remove paths from it, so that next IO can insert
912 	 * paths (->mp_skip_entry) into a skip_list again.
913 	 */
914 	list_for_each_safe(skip, tmp, &it->skip_list)
915 		list_del_init(skip);
916 }
917 
918 /**
919  * rtrs_clt_init_req() - Initialize an rtrs_clt_io_req holding information
920  * about an inflight IO.
921  * The user buffer holding user control message (not data) is copied into
922  * the corresponding buffer of rtrs_iu (req->iu->buf), which later on will
923  * also hold the control message of rtrs.
924  * @req: an io request holding information about IO.
925  * @clt_path: client path
926  * @conf: conformation callback function to notify upper layer.
927  * @permit: permit for allocation of RDMA remote buffer
928  * @priv: private pointer
929  * @vec: kernel vector containing control message
930  * @usr_len: length of the user message
931  * @sg: scater list for IO data
932  * @sg_cnt: number of scater list entries
933  * @data_len: length of the IO data
934  * @dir: direction of the IO.
935  */
936 static void rtrs_clt_init_req(struct rtrs_clt_io_req *req,
937 			      struct rtrs_clt_path *clt_path,
938 			      void (*conf)(void *priv, int errno),
939 			      struct rtrs_permit *permit, void *priv,
940 			      const struct kvec *vec, size_t usr_len,
941 			      struct scatterlist *sg, size_t sg_cnt,
942 			      size_t data_len, int dir)
943 {
944 	struct iov_iter iter;
945 	size_t len;
946 
947 	req->permit = permit;
948 	req->in_use = true;
949 	req->usr_len = usr_len;
950 	req->data_len = data_len;
951 	req->sglist = sg;
952 	req->sg_cnt = sg_cnt;
953 	req->priv = priv;
954 	req->dir = dir;
955 	req->con = rtrs_permit_to_clt_con(clt_path, permit);
956 	req->conf = conf;
957 	req->need_inv = false;
958 	req->need_inv_comp = false;
959 	req->inv_errno = 0;
960 	refcount_set(&req->ref, 1);
961 	req->mp_policy = clt_path->clt->mp_policy;
962 
963 	iov_iter_kvec(&iter, READ, vec, 1, usr_len);
964 	len = _copy_from_iter(req->iu->buf, usr_len, &iter);
965 	WARN_ON(len != usr_len);
966 
967 	reinit_completion(&req->inv_comp);
968 }
969 
970 static struct rtrs_clt_io_req *
971 rtrs_clt_get_req(struct rtrs_clt_path *clt_path,
972 		 void (*conf)(void *priv, int errno),
973 		 struct rtrs_permit *permit, void *priv,
974 		 const struct kvec *vec, size_t usr_len,
975 		 struct scatterlist *sg, size_t sg_cnt,
976 		 size_t data_len, int dir)
977 {
978 	struct rtrs_clt_io_req *req;
979 
980 	req = &clt_path->reqs[permit->mem_id];
981 	rtrs_clt_init_req(req, clt_path, conf, permit, priv, vec, usr_len,
982 			   sg, sg_cnt, data_len, dir);
983 	return req;
984 }
985 
986 static struct rtrs_clt_io_req *
987 rtrs_clt_get_copy_req(struct rtrs_clt_path *alive_path,
988 		       struct rtrs_clt_io_req *fail_req)
989 {
990 	struct rtrs_clt_io_req *req;
991 	struct kvec vec = {
992 		.iov_base = fail_req->iu->buf,
993 		.iov_len  = fail_req->usr_len
994 	};
995 
996 	req = &alive_path->reqs[fail_req->permit->mem_id];
997 	rtrs_clt_init_req(req, alive_path, fail_req->conf, fail_req->permit,
998 			   fail_req->priv, &vec, fail_req->usr_len,
999 			   fail_req->sglist, fail_req->sg_cnt,
1000 			   fail_req->data_len, fail_req->dir);
1001 	return req;
1002 }
1003 
1004 static int rtrs_post_rdma_write_sg(struct rtrs_clt_con *con,
1005 				   struct rtrs_clt_io_req *req,
1006 				   struct rtrs_rbuf *rbuf, bool fr_en,
1007 				   u32 size, u32 imm, struct ib_send_wr *wr,
1008 				   struct ib_send_wr *tail)
1009 {
1010 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
1011 	struct ib_sge *sge = req->sge;
1012 	enum ib_send_flags flags;
1013 	struct scatterlist *sg;
1014 	size_t num_sge;
1015 	int i;
1016 	struct ib_send_wr *ptail = NULL;
1017 
1018 	if (fr_en) {
1019 		i = 0;
1020 		sge[i].addr   = req->mr->iova;
1021 		sge[i].length = req->mr->length;
1022 		sge[i].lkey   = req->mr->lkey;
1023 		i++;
1024 		num_sge = 2;
1025 		ptail = tail;
1026 	} else {
1027 		for_each_sg(req->sglist, sg, req->sg_cnt, i) {
1028 			sge[i].addr   = sg_dma_address(sg);
1029 			sge[i].length = sg_dma_len(sg);
1030 			sge[i].lkey   = clt_path->s.dev->ib_pd->local_dma_lkey;
1031 		}
1032 		num_sge = 1 + req->sg_cnt;
1033 	}
1034 	sge[i].addr   = req->iu->dma_addr;
1035 	sge[i].length = size;
1036 	sge[i].lkey   = clt_path->s.dev->ib_pd->local_dma_lkey;
1037 
1038 	/*
1039 	 * From time to time we have to post signalled sends,
1040 	 * or send queue will fill up and only QP reset can help.
1041 	 */
1042 	flags = atomic_inc_return(&con->c.wr_cnt) % clt_path->s.signal_interval ?
1043 			0 : IB_SEND_SIGNALED;
1044 
1045 	ib_dma_sync_single_for_device(clt_path->s.dev->ib_dev,
1046 				      req->iu->dma_addr,
1047 				      size, DMA_TO_DEVICE);
1048 
1049 	return rtrs_iu_post_rdma_write_imm(&con->c, req->iu, sge, num_sge,
1050 					    rbuf->rkey, rbuf->addr, imm,
1051 					    flags, wr, ptail);
1052 }
1053 
1054 static int rtrs_map_sg_fr(struct rtrs_clt_io_req *req, size_t count)
1055 {
1056 	int nr;
1057 
1058 	/* Align the MR to a 4K page size to match the block virt boundary */
1059 	nr = ib_map_mr_sg(req->mr, req->sglist, count, NULL, SZ_4K);
1060 	if (nr < 0)
1061 		return nr;
1062 	if (nr < req->sg_cnt)
1063 		return -EINVAL;
1064 	ib_update_fast_reg_key(req->mr, ib_inc_rkey(req->mr->rkey));
1065 
1066 	return nr;
1067 }
1068 
1069 static int rtrs_clt_write_req(struct rtrs_clt_io_req *req)
1070 {
1071 	struct rtrs_clt_con *con = req->con;
1072 	struct rtrs_path *s = con->c.path;
1073 	struct rtrs_clt_path *clt_path = to_clt_path(s);
1074 	struct rtrs_msg_rdma_write *msg;
1075 
1076 	struct rtrs_rbuf *rbuf;
1077 	int ret, count = 0;
1078 	u32 imm, buf_id;
1079 	struct ib_reg_wr rwr;
1080 	struct ib_send_wr inv_wr;
1081 	struct ib_send_wr *wr = NULL;
1082 	bool fr_en = false;
1083 
1084 	const size_t tsize = sizeof(*msg) + req->data_len + req->usr_len;
1085 
1086 	if (tsize > clt_path->chunk_size) {
1087 		rtrs_wrn(s, "Write request failed, size too big %zu > %d\n",
1088 			  tsize, clt_path->chunk_size);
1089 		return -EMSGSIZE;
1090 	}
1091 	if (req->sg_cnt) {
1092 		count = ib_dma_map_sg(clt_path->s.dev->ib_dev, req->sglist,
1093 				      req->sg_cnt, req->dir);
1094 		if (!count) {
1095 			rtrs_wrn(s, "Write request failed, map failed\n");
1096 			return -EINVAL;
1097 		}
1098 	}
1099 	/* put rtrs msg after sg and user message */
1100 	msg = req->iu->buf + req->usr_len;
1101 	msg->type = cpu_to_le16(RTRS_MSG_WRITE);
1102 	msg->usr_len = cpu_to_le16(req->usr_len);
1103 
1104 	/* rtrs message on server side will be after user data and message */
1105 	imm = req->permit->mem_off + req->data_len + req->usr_len;
1106 	imm = rtrs_to_io_req_imm(imm);
1107 	buf_id = req->permit->mem_id;
1108 	req->sg_size = tsize;
1109 	rbuf = &clt_path->rbufs[buf_id];
1110 
1111 	if (count) {
1112 		ret = rtrs_map_sg_fr(req, count);
1113 		if (ret < 0) {
1114 			rtrs_err_rl(s,
1115 				    "Write request failed, failed to map fast reg. data, err: %d\n",
1116 				    ret);
1117 			ib_dma_unmap_sg(clt_path->s.dev->ib_dev, req->sglist,
1118 					req->sg_cnt, req->dir);
1119 			return ret;
1120 		}
1121 		inv_wr = (struct ib_send_wr) {
1122 			.opcode		    = IB_WR_LOCAL_INV,
1123 			.wr_cqe		    = &req->inv_cqe,
1124 			.send_flags	    = IB_SEND_SIGNALED,
1125 			.ex.invalidate_rkey = req->mr->rkey,
1126 		};
1127 		req->inv_cqe.done = rtrs_clt_inv_rkey_done;
1128 		rwr = (struct ib_reg_wr) {
1129 			.wr.opcode = IB_WR_REG_MR,
1130 			.wr.wr_cqe = &fast_reg_cqe,
1131 			.mr = req->mr,
1132 			.key = req->mr->rkey,
1133 			.access = (IB_ACCESS_LOCAL_WRITE),
1134 		};
1135 		wr = &rwr.wr;
1136 		fr_en = true;
1137 		refcount_inc(&req->ref);
1138 	}
1139 	/*
1140 	 * Update stats now, after request is successfully sent it is not
1141 	 * safe anymore to touch it.
1142 	 */
1143 	rtrs_clt_update_all_stats(req, WRITE);
1144 
1145 	ret = rtrs_post_rdma_write_sg(req->con, req, rbuf, fr_en,
1146 				      req->usr_len + sizeof(*msg),
1147 				      imm, wr, &inv_wr);
1148 	if (ret) {
1149 		rtrs_err_rl(s,
1150 			    "Write request failed: error=%d path=%s [%s:%u]\n",
1151 			    ret, kobject_name(&clt_path->kobj), clt_path->hca_name,
1152 			    clt_path->hca_port);
1153 		if (req->mp_policy == MP_POLICY_MIN_INFLIGHT)
1154 			atomic_dec(&clt_path->stats->inflight);
1155 		if (req->sg_cnt)
1156 			ib_dma_unmap_sg(clt_path->s.dev->ib_dev, req->sglist,
1157 					req->sg_cnt, req->dir);
1158 	}
1159 
1160 	return ret;
1161 }
1162 
1163 static int rtrs_clt_read_req(struct rtrs_clt_io_req *req)
1164 {
1165 	struct rtrs_clt_con *con = req->con;
1166 	struct rtrs_path *s = con->c.path;
1167 	struct rtrs_clt_path *clt_path = to_clt_path(s);
1168 	struct rtrs_msg_rdma_read *msg;
1169 	struct rtrs_ib_dev *dev = clt_path->s.dev;
1170 
1171 	struct ib_reg_wr rwr;
1172 	struct ib_send_wr *wr = NULL;
1173 
1174 	int ret, count = 0;
1175 	u32 imm, buf_id;
1176 
1177 	const size_t tsize = sizeof(*msg) + req->data_len + req->usr_len;
1178 
1179 	if (tsize > clt_path->chunk_size) {
1180 		rtrs_wrn(s,
1181 			  "Read request failed, message size is %zu, bigger than CHUNK_SIZE %d\n",
1182 			  tsize, clt_path->chunk_size);
1183 		return -EMSGSIZE;
1184 	}
1185 
1186 	if (req->sg_cnt) {
1187 		count = ib_dma_map_sg(dev->ib_dev, req->sglist, req->sg_cnt,
1188 				      req->dir);
1189 		if (!count) {
1190 			rtrs_wrn(s,
1191 				  "Read request failed, dma map failed\n");
1192 			return -EINVAL;
1193 		}
1194 	}
1195 	/* put our message into req->buf after user message*/
1196 	msg = req->iu->buf + req->usr_len;
1197 	msg->type = cpu_to_le16(RTRS_MSG_READ);
1198 	msg->usr_len = cpu_to_le16(req->usr_len);
1199 
1200 	if (count) {
1201 		ret = rtrs_map_sg_fr(req, count);
1202 		if (ret < 0) {
1203 			rtrs_err_rl(s,
1204 				     "Read request failed, failed to map  fast reg. data, err: %d\n",
1205 				     ret);
1206 			ib_dma_unmap_sg(dev->ib_dev, req->sglist, req->sg_cnt,
1207 					req->dir);
1208 			return ret;
1209 		}
1210 		rwr = (struct ib_reg_wr) {
1211 			.wr.opcode = IB_WR_REG_MR,
1212 			.wr.wr_cqe = &fast_reg_cqe,
1213 			.mr = req->mr,
1214 			.key = req->mr->rkey,
1215 			.access = (IB_ACCESS_LOCAL_WRITE |
1216 				   IB_ACCESS_REMOTE_WRITE),
1217 		};
1218 		wr = &rwr.wr;
1219 
1220 		msg->sg_cnt = cpu_to_le16(1);
1221 		msg->flags = cpu_to_le16(RTRS_MSG_NEED_INVAL_F);
1222 
1223 		msg->desc[0].addr = cpu_to_le64(req->mr->iova);
1224 		msg->desc[0].key = cpu_to_le32(req->mr->rkey);
1225 		msg->desc[0].len = cpu_to_le32(req->mr->length);
1226 
1227 		/* Further invalidation is required */
1228 		req->need_inv = !!RTRS_MSG_NEED_INVAL_F;
1229 
1230 	} else {
1231 		msg->sg_cnt = 0;
1232 		msg->flags = 0;
1233 	}
1234 	/*
1235 	 * rtrs message will be after the space reserved for disk data and
1236 	 * user message
1237 	 */
1238 	imm = req->permit->mem_off + req->data_len + req->usr_len;
1239 	imm = rtrs_to_io_req_imm(imm);
1240 	buf_id = req->permit->mem_id;
1241 
1242 	req->sg_size  = sizeof(*msg);
1243 	req->sg_size += le16_to_cpu(msg->sg_cnt) * sizeof(struct rtrs_sg_desc);
1244 	req->sg_size += req->usr_len;
1245 
1246 	/*
1247 	 * Update stats now, after request is successfully sent it is not
1248 	 * safe anymore to touch it.
1249 	 */
1250 	rtrs_clt_update_all_stats(req, READ);
1251 
1252 	ret = rtrs_post_send_rdma(req->con, req, &clt_path->rbufs[buf_id],
1253 				   req->data_len, imm, wr);
1254 	if (ret) {
1255 		rtrs_err_rl(s,
1256 			    "Read request failed: error=%d path=%s [%s:%u]\n",
1257 			    ret, kobject_name(&clt_path->kobj), clt_path->hca_name,
1258 			    clt_path->hca_port);
1259 		if (req->mp_policy == MP_POLICY_MIN_INFLIGHT)
1260 			atomic_dec(&clt_path->stats->inflight);
1261 		req->need_inv = false;
1262 		if (req->sg_cnt)
1263 			ib_dma_unmap_sg(dev->ib_dev, req->sglist,
1264 					req->sg_cnt, req->dir);
1265 	}
1266 
1267 	return ret;
1268 }
1269 
1270 /**
1271  * rtrs_clt_failover_req() - Try to find an active path for a failed request
1272  * @clt: clt context
1273  * @fail_req: a failed io request.
1274  */
1275 static int rtrs_clt_failover_req(struct rtrs_clt_sess *clt,
1276 				 struct rtrs_clt_io_req *fail_req)
1277 {
1278 	struct rtrs_clt_path *alive_path;
1279 	struct rtrs_clt_io_req *req;
1280 	int err = -ECONNABORTED;
1281 	struct path_it it;
1282 
1283 	rcu_read_lock();
1284 	for (path_it_init(&it, clt);
1285 	     (alive_path = it.next_path(&it)) && it.i < it.clt->paths_num;
1286 	     it.i++) {
1287 		if (READ_ONCE(alive_path->state) != RTRS_CLT_CONNECTED)
1288 			continue;
1289 		req = rtrs_clt_get_copy_req(alive_path, fail_req);
1290 		if (req->dir == DMA_TO_DEVICE)
1291 			err = rtrs_clt_write_req(req);
1292 		else
1293 			err = rtrs_clt_read_req(req);
1294 		if (err) {
1295 			req->in_use = false;
1296 			continue;
1297 		}
1298 		/* Success path */
1299 		rtrs_clt_inc_failover_cnt(alive_path->stats);
1300 		break;
1301 	}
1302 	path_it_deinit(&it);
1303 	rcu_read_unlock();
1304 
1305 	return err;
1306 }
1307 
1308 static void fail_all_outstanding_reqs(struct rtrs_clt_path *clt_path)
1309 {
1310 	struct rtrs_clt_sess *clt = clt_path->clt;
1311 	struct rtrs_clt_io_req *req;
1312 	int i, err;
1313 
1314 	if (!clt_path->reqs)
1315 		return;
1316 	for (i = 0; i < clt_path->queue_depth; ++i) {
1317 		req = &clt_path->reqs[i];
1318 		if (!req->in_use)
1319 			continue;
1320 
1321 		/*
1322 		 * Safely (without notification) complete failed request.
1323 		 * After completion this request is still useble and can
1324 		 * be failovered to another path.
1325 		 */
1326 		complete_rdma_req(req, -ECONNABORTED, false, true);
1327 
1328 		err = rtrs_clt_failover_req(clt, req);
1329 		if (err)
1330 			/* Failover failed, notify anyway */
1331 			req->conf(req->priv, err);
1332 	}
1333 }
1334 
1335 static void free_path_reqs(struct rtrs_clt_path *clt_path)
1336 {
1337 	struct rtrs_clt_io_req *req;
1338 	int i;
1339 
1340 	if (!clt_path->reqs)
1341 		return;
1342 	for (i = 0; i < clt_path->queue_depth; ++i) {
1343 		req = &clt_path->reqs[i];
1344 		if (req->mr)
1345 			ib_dereg_mr(req->mr);
1346 		kfree(req->sge);
1347 		rtrs_iu_free(req->iu, clt_path->s.dev->ib_dev, 1);
1348 	}
1349 	kfree(clt_path->reqs);
1350 	clt_path->reqs = NULL;
1351 }
1352 
1353 static int alloc_path_reqs(struct rtrs_clt_path *clt_path)
1354 {
1355 	struct rtrs_clt_io_req *req;
1356 	int i, err = -ENOMEM;
1357 
1358 	clt_path->reqs = kcalloc(clt_path->queue_depth,
1359 				 sizeof(*clt_path->reqs),
1360 				 GFP_KERNEL);
1361 	if (!clt_path->reqs)
1362 		return -ENOMEM;
1363 
1364 	for (i = 0; i < clt_path->queue_depth; ++i) {
1365 		req = &clt_path->reqs[i];
1366 		req->iu = rtrs_iu_alloc(1, clt_path->max_hdr_size, GFP_KERNEL,
1367 					 clt_path->s.dev->ib_dev,
1368 					 DMA_TO_DEVICE,
1369 					 rtrs_clt_rdma_done);
1370 		if (!req->iu)
1371 			goto out;
1372 
1373 		req->sge = kcalloc(2, sizeof(*req->sge), GFP_KERNEL);
1374 		if (!req->sge)
1375 			goto out;
1376 
1377 		req->mr = ib_alloc_mr(clt_path->s.dev->ib_pd,
1378 				      IB_MR_TYPE_MEM_REG,
1379 				      clt_path->max_pages_per_mr);
1380 		if (IS_ERR(req->mr)) {
1381 			err = PTR_ERR(req->mr);
1382 			req->mr = NULL;
1383 			pr_err("Failed to alloc clt_path->max_pages_per_mr %d\n",
1384 			       clt_path->max_pages_per_mr);
1385 			goto out;
1386 		}
1387 
1388 		init_completion(&req->inv_comp);
1389 	}
1390 
1391 	return 0;
1392 
1393 out:
1394 	free_path_reqs(clt_path);
1395 
1396 	return err;
1397 }
1398 
1399 static int alloc_permits(struct rtrs_clt_sess *clt)
1400 {
1401 	unsigned int chunk_bits;
1402 	int err, i;
1403 
1404 	clt->permits_map = bitmap_zalloc(clt->queue_depth, GFP_KERNEL);
1405 	if (!clt->permits_map) {
1406 		err = -ENOMEM;
1407 		goto out_err;
1408 	}
1409 	clt->permits = kcalloc(clt->queue_depth, permit_size(clt), GFP_KERNEL);
1410 	if (!clt->permits) {
1411 		err = -ENOMEM;
1412 		goto err_map;
1413 	}
1414 	chunk_bits = ilog2(clt->queue_depth - 1) + 1;
1415 	for (i = 0; i < clt->queue_depth; i++) {
1416 		struct rtrs_permit *permit;
1417 
1418 		permit = get_permit(clt, i);
1419 		permit->mem_id = i;
1420 		permit->mem_off = i << (MAX_IMM_PAYL_BITS - chunk_bits);
1421 	}
1422 
1423 	return 0;
1424 
1425 err_map:
1426 	bitmap_free(clt->permits_map);
1427 	clt->permits_map = NULL;
1428 out_err:
1429 	return err;
1430 }
1431 
1432 static void free_permits(struct rtrs_clt_sess *clt)
1433 {
1434 	if (clt->permits_map)
1435 		wait_event(clt->permits_wait,
1436 			   bitmap_empty(clt->permits_map, clt->queue_depth));
1437 
1438 	bitmap_free(clt->permits_map);
1439 	clt->permits_map = NULL;
1440 	kfree(clt->permits);
1441 	clt->permits = NULL;
1442 }
1443 
1444 static void query_fast_reg_mode(struct rtrs_clt_path *clt_path)
1445 {
1446 	struct ib_device *ib_dev;
1447 	u64 max_pages_per_mr;
1448 	int mr_page_shift;
1449 
1450 	ib_dev = clt_path->s.dev->ib_dev;
1451 
1452 	/*
1453 	 * Use the smallest page size supported by the HCA, down to a
1454 	 * minimum of 4096 bytes. We're unlikely to build large sglists
1455 	 * out of smaller entries.
1456 	 */
1457 	mr_page_shift      = max(12, ffs(ib_dev->attrs.page_size_cap) - 1);
1458 	max_pages_per_mr   = ib_dev->attrs.max_mr_size;
1459 	do_div(max_pages_per_mr, (1ull << mr_page_shift));
1460 	clt_path->max_pages_per_mr =
1461 		min3(clt_path->max_pages_per_mr, (u32)max_pages_per_mr,
1462 		     ib_dev->attrs.max_fast_reg_page_list_len);
1463 	clt_path->clt->max_segments =
1464 		min(clt_path->max_pages_per_mr, clt_path->clt->max_segments);
1465 }
1466 
1467 static bool rtrs_clt_change_state_get_old(struct rtrs_clt_path *clt_path,
1468 					   enum rtrs_clt_state new_state,
1469 					   enum rtrs_clt_state *old_state)
1470 {
1471 	bool changed;
1472 
1473 	spin_lock_irq(&clt_path->state_wq.lock);
1474 	if (old_state)
1475 		*old_state = clt_path->state;
1476 	changed = rtrs_clt_change_state(clt_path, new_state);
1477 	spin_unlock_irq(&clt_path->state_wq.lock);
1478 
1479 	return changed;
1480 }
1481 
1482 static void rtrs_clt_hb_err_handler(struct rtrs_con *c)
1483 {
1484 	struct rtrs_clt_con *con = container_of(c, typeof(*con), c);
1485 
1486 	rtrs_rdma_error_recovery(con);
1487 }
1488 
1489 static void rtrs_clt_init_hb(struct rtrs_clt_path *clt_path)
1490 {
1491 	rtrs_init_hb(&clt_path->s, &io_comp_cqe,
1492 		      RTRS_HB_INTERVAL_MS,
1493 		      RTRS_HB_MISSED_MAX,
1494 		      rtrs_clt_hb_err_handler,
1495 		      rtrs_wq);
1496 }
1497 
1498 static void rtrs_clt_reconnect_work(struct work_struct *work);
1499 static void rtrs_clt_close_work(struct work_struct *work);
1500 
1501 static void rtrs_clt_err_recovery_work(struct work_struct *work)
1502 {
1503 	struct rtrs_clt_path *clt_path;
1504 	struct rtrs_clt_sess *clt;
1505 	int delay_ms;
1506 
1507 	clt_path = container_of(work, struct rtrs_clt_path, err_recovery_work);
1508 	clt = clt_path->clt;
1509 	delay_ms = clt->reconnect_delay_sec * 1000;
1510 	rtrs_clt_stop_and_destroy_conns(clt_path);
1511 	queue_delayed_work(rtrs_wq, &clt_path->reconnect_dwork,
1512 			   msecs_to_jiffies(delay_ms +
1513 					    prandom_u32() %
1514 					    RTRS_RECONNECT_SEED));
1515 }
1516 
1517 static struct rtrs_clt_path *alloc_path(struct rtrs_clt_sess *clt,
1518 					const struct rtrs_addr *path,
1519 					size_t con_num, u32 nr_poll_queues)
1520 {
1521 	struct rtrs_clt_path *clt_path;
1522 	int err = -ENOMEM;
1523 	int cpu;
1524 	size_t total_con;
1525 
1526 	clt_path = kzalloc(sizeof(*clt_path), GFP_KERNEL);
1527 	if (!clt_path)
1528 		goto err;
1529 
1530 	/*
1531 	 * irqmode and poll
1532 	 * +1: Extra connection for user messages
1533 	 */
1534 	total_con = con_num + nr_poll_queues + 1;
1535 	clt_path->s.con = kcalloc(total_con, sizeof(*clt_path->s.con),
1536 				  GFP_KERNEL);
1537 	if (!clt_path->s.con)
1538 		goto err_free_path;
1539 
1540 	clt_path->s.con_num = total_con;
1541 	clt_path->s.irq_con_num = con_num + 1;
1542 
1543 	clt_path->stats = kzalloc(sizeof(*clt_path->stats), GFP_KERNEL);
1544 	if (!clt_path->stats)
1545 		goto err_free_con;
1546 
1547 	mutex_init(&clt_path->init_mutex);
1548 	uuid_gen(&clt_path->s.uuid);
1549 	memcpy(&clt_path->s.dst_addr, path->dst,
1550 	       rdma_addr_size((struct sockaddr *)path->dst));
1551 
1552 	/*
1553 	 * rdma_resolve_addr() passes src_addr to cma_bind_addr, which
1554 	 * checks the sa_family to be non-zero. If user passed src_addr=NULL
1555 	 * the sess->src_addr will contain only zeros, which is then fine.
1556 	 */
1557 	if (path->src)
1558 		memcpy(&clt_path->s.src_addr, path->src,
1559 		       rdma_addr_size((struct sockaddr *)path->src));
1560 	strscpy(clt_path->s.sessname, clt->sessname,
1561 		sizeof(clt_path->s.sessname));
1562 	clt_path->clt = clt;
1563 	clt_path->max_pages_per_mr = RTRS_MAX_SEGMENTS;
1564 	init_waitqueue_head(&clt_path->state_wq);
1565 	clt_path->state = RTRS_CLT_CONNECTING;
1566 	atomic_set(&clt_path->connected_cnt, 0);
1567 	INIT_WORK(&clt_path->close_work, rtrs_clt_close_work);
1568 	INIT_WORK(&clt_path->err_recovery_work, rtrs_clt_err_recovery_work);
1569 	INIT_DELAYED_WORK(&clt_path->reconnect_dwork, rtrs_clt_reconnect_work);
1570 	rtrs_clt_init_hb(clt_path);
1571 
1572 	clt_path->mp_skip_entry = alloc_percpu(typeof(*clt_path->mp_skip_entry));
1573 	if (!clt_path->mp_skip_entry)
1574 		goto err_free_stats;
1575 
1576 	for_each_possible_cpu(cpu)
1577 		INIT_LIST_HEAD(per_cpu_ptr(clt_path->mp_skip_entry, cpu));
1578 
1579 	err = rtrs_clt_init_stats(clt_path->stats);
1580 	if (err)
1581 		goto err_free_percpu;
1582 
1583 	return clt_path;
1584 
1585 err_free_percpu:
1586 	free_percpu(clt_path->mp_skip_entry);
1587 err_free_stats:
1588 	kfree(clt_path->stats);
1589 err_free_con:
1590 	kfree(clt_path->s.con);
1591 err_free_path:
1592 	kfree(clt_path);
1593 err:
1594 	return ERR_PTR(err);
1595 }
1596 
1597 void free_path(struct rtrs_clt_path *clt_path)
1598 {
1599 	free_percpu(clt_path->mp_skip_entry);
1600 	mutex_destroy(&clt_path->init_mutex);
1601 	kfree(clt_path->s.con);
1602 	kfree(clt_path->rbufs);
1603 	kfree(clt_path);
1604 }
1605 
1606 static int create_con(struct rtrs_clt_path *clt_path, unsigned int cid)
1607 {
1608 	struct rtrs_clt_con *con;
1609 
1610 	con = kzalloc(sizeof(*con), GFP_KERNEL);
1611 	if (!con)
1612 		return -ENOMEM;
1613 
1614 	/* Map first two connections to the first CPU */
1615 	con->cpu  = (cid ? cid - 1 : 0) % nr_cpu_ids;
1616 	con->c.cid = cid;
1617 	con->c.path = &clt_path->s;
1618 	/* Align with srv, init as 1 */
1619 	atomic_set(&con->c.wr_cnt, 1);
1620 	mutex_init(&con->con_mutex);
1621 
1622 	clt_path->s.con[cid] = &con->c;
1623 
1624 	return 0;
1625 }
1626 
1627 static void destroy_con(struct rtrs_clt_con *con)
1628 {
1629 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
1630 
1631 	clt_path->s.con[con->c.cid] = NULL;
1632 	mutex_destroy(&con->con_mutex);
1633 	kfree(con);
1634 }
1635 
1636 static int create_con_cq_qp(struct rtrs_clt_con *con)
1637 {
1638 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
1639 	u32 max_send_wr, max_recv_wr, cq_num, max_send_sge, wr_limit;
1640 	int err, cq_vector;
1641 	struct rtrs_msg_rkey_rsp *rsp;
1642 
1643 	lockdep_assert_held(&con->con_mutex);
1644 	if (con->c.cid == 0) {
1645 		max_send_sge = 1;
1646 		/* We must be the first here */
1647 		if (WARN_ON(clt_path->s.dev))
1648 			return -EINVAL;
1649 
1650 		/*
1651 		 * The whole session uses device from user connection.
1652 		 * Be careful not to close user connection before ib dev
1653 		 * is gracefully put.
1654 		 */
1655 		clt_path->s.dev = rtrs_ib_dev_find_or_add(con->c.cm_id->device,
1656 						       &dev_pd);
1657 		if (!clt_path->s.dev) {
1658 			rtrs_wrn(clt_path->clt,
1659 				  "rtrs_ib_dev_find_get_or_add(): no memory\n");
1660 			return -ENOMEM;
1661 		}
1662 		clt_path->s.dev_ref = 1;
1663 		query_fast_reg_mode(clt_path);
1664 		wr_limit = clt_path->s.dev->ib_dev->attrs.max_qp_wr;
1665 		/*
1666 		 * Two (request + registration) completion for send
1667 		 * Two for recv if always_invalidate is set on server
1668 		 * or one for recv.
1669 		 * + 2 for drain and heartbeat
1670 		 * in case qp gets into error state.
1671 		 */
1672 		max_send_wr =
1673 			min_t(int, wr_limit, SERVICE_CON_QUEUE_DEPTH * 2 + 2);
1674 		max_recv_wr = max_send_wr;
1675 	} else {
1676 		/*
1677 		 * Here we assume that session members are correctly set.
1678 		 * This is always true if user connection (cid == 0) is
1679 		 * established first.
1680 		 */
1681 		if (WARN_ON(!clt_path->s.dev))
1682 			return -EINVAL;
1683 		if (WARN_ON(!clt_path->queue_depth))
1684 			return -EINVAL;
1685 
1686 		wr_limit = clt_path->s.dev->ib_dev->attrs.max_qp_wr;
1687 		/* Shared between connections */
1688 		clt_path->s.dev_ref++;
1689 		max_send_wr = min_t(int, wr_limit,
1690 			      /* QD * (REQ + RSP + FR REGS or INVS) + drain */
1691 			      clt_path->queue_depth * 3 + 1);
1692 		max_recv_wr = min_t(int, wr_limit,
1693 			      clt_path->queue_depth * 3 + 1);
1694 		max_send_sge = 2;
1695 	}
1696 	atomic_set(&con->c.sq_wr_avail, max_send_wr);
1697 	cq_num = max_send_wr + max_recv_wr;
1698 	/* alloc iu to recv new rkey reply when server reports flags set */
1699 	if (clt_path->flags & RTRS_MSG_NEW_RKEY_F || con->c.cid == 0) {
1700 		con->rsp_ius = rtrs_iu_alloc(cq_num, sizeof(*rsp),
1701 					      GFP_KERNEL,
1702 					      clt_path->s.dev->ib_dev,
1703 					      DMA_FROM_DEVICE,
1704 					      rtrs_clt_rdma_done);
1705 		if (!con->rsp_ius)
1706 			return -ENOMEM;
1707 		con->queue_num = cq_num;
1708 	}
1709 	cq_num = max_send_wr + max_recv_wr;
1710 	cq_vector = con->cpu % clt_path->s.dev->ib_dev->num_comp_vectors;
1711 	if (con->c.cid >= clt_path->s.irq_con_num)
1712 		err = rtrs_cq_qp_create(&clt_path->s, &con->c, max_send_sge,
1713 					cq_vector, cq_num, max_send_wr,
1714 					max_recv_wr, IB_POLL_DIRECT);
1715 	else
1716 		err = rtrs_cq_qp_create(&clt_path->s, &con->c, max_send_sge,
1717 					cq_vector, cq_num, max_send_wr,
1718 					max_recv_wr, IB_POLL_SOFTIRQ);
1719 	/*
1720 	 * In case of error we do not bother to clean previous allocations,
1721 	 * since destroy_con_cq_qp() must be called.
1722 	 */
1723 	return err;
1724 }
1725 
1726 static void destroy_con_cq_qp(struct rtrs_clt_con *con)
1727 {
1728 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
1729 
1730 	/*
1731 	 * Be careful here: destroy_con_cq_qp() can be called even
1732 	 * create_con_cq_qp() failed, see comments there.
1733 	 */
1734 	lockdep_assert_held(&con->con_mutex);
1735 	rtrs_cq_qp_destroy(&con->c);
1736 	if (con->rsp_ius) {
1737 		rtrs_iu_free(con->rsp_ius, clt_path->s.dev->ib_dev,
1738 			     con->queue_num);
1739 		con->rsp_ius = NULL;
1740 		con->queue_num = 0;
1741 	}
1742 	if (clt_path->s.dev_ref && !--clt_path->s.dev_ref) {
1743 		rtrs_ib_dev_put(clt_path->s.dev);
1744 		clt_path->s.dev = NULL;
1745 	}
1746 }
1747 
1748 static void stop_cm(struct rtrs_clt_con *con)
1749 {
1750 	rdma_disconnect(con->c.cm_id);
1751 	if (con->c.qp)
1752 		ib_drain_qp(con->c.qp);
1753 }
1754 
1755 static void destroy_cm(struct rtrs_clt_con *con)
1756 {
1757 	rdma_destroy_id(con->c.cm_id);
1758 	con->c.cm_id = NULL;
1759 }
1760 
1761 static int rtrs_rdma_addr_resolved(struct rtrs_clt_con *con)
1762 {
1763 	struct rtrs_path *s = con->c.path;
1764 	int err;
1765 
1766 	mutex_lock(&con->con_mutex);
1767 	err = create_con_cq_qp(con);
1768 	mutex_unlock(&con->con_mutex);
1769 	if (err) {
1770 		rtrs_err(s, "create_con_cq_qp(), err: %d\n", err);
1771 		return err;
1772 	}
1773 	err = rdma_resolve_route(con->c.cm_id, RTRS_CONNECT_TIMEOUT_MS);
1774 	if (err)
1775 		rtrs_err(s, "Resolving route failed, err: %d\n", err);
1776 
1777 	return err;
1778 }
1779 
1780 static int rtrs_rdma_route_resolved(struct rtrs_clt_con *con)
1781 {
1782 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
1783 	struct rtrs_clt_sess *clt = clt_path->clt;
1784 	struct rtrs_msg_conn_req msg;
1785 	struct rdma_conn_param param;
1786 
1787 	int err;
1788 
1789 	param = (struct rdma_conn_param) {
1790 		.retry_count = 7,
1791 		.rnr_retry_count = 7,
1792 		.private_data = &msg,
1793 		.private_data_len = sizeof(msg),
1794 	};
1795 
1796 	msg = (struct rtrs_msg_conn_req) {
1797 		.magic = cpu_to_le16(RTRS_MAGIC),
1798 		.version = cpu_to_le16(RTRS_PROTO_VER),
1799 		.cid = cpu_to_le16(con->c.cid),
1800 		.cid_num = cpu_to_le16(clt_path->s.con_num),
1801 		.recon_cnt = cpu_to_le16(clt_path->s.recon_cnt),
1802 	};
1803 	msg.first_conn = clt_path->for_new_clt ? FIRST_CONN : 0;
1804 	uuid_copy(&msg.sess_uuid, &clt_path->s.uuid);
1805 	uuid_copy(&msg.paths_uuid, &clt->paths_uuid);
1806 
1807 	err = rdma_connect_locked(con->c.cm_id, &param);
1808 	if (err)
1809 		rtrs_err(clt, "rdma_connect_locked(): %d\n", err);
1810 
1811 	return err;
1812 }
1813 
1814 static int rtrs_rdma_conn_established(struct rtrs_clt_con *con,
1815 				       struct rdma_cm_event *ev)
1816 {
1817 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
1818 	struct rtrs_clt_sess *clt = clt_path->clt;
1819 	const struct rtrs_msg_conn_rsp *msg;
1820 	u16 version, queue_depth;
1821 	int errno;
1822 	u8 len;
1823 
1824 	msg = ev->param.conn.private_data;
1825 	len = ev->param.conn.private_data_len;
1826 	if (len < sizeof(*msg)) {
1827 		rtrs_err(clt, "Invalid RTRS connection response\n");
1828 		return -ECONNRESET;
1829 	}
1830 	if (le16_to_cpu(msg->magic) != RTRS_MAGIC) {
1831 		rtrs_err(clt, "Invalid RTRS magic\n");
1832 		return -ECONNRESET;
1833 	}
1834 	version = le16_to_cpu(msg->version);
1835 	if (version >> 8 != RTRS_PROTO_VER_MAJOR) {
1836 		rtrs_err(clt, "Unsupported major RTRS version: %d, expected %d\n",
1837 			  version >> 8, RTRS_PROTO_VER_MAJOR);
1838 		return -ECONNRESET;
1839 	}
1840 	errno = le16_to_cpu(msg->errno);
1841 	if (errno) {
1842 		rtrs_err(clt, "Invalid RTRS message: errno %d\n",
1843 			  errno);
1844 		return -ECONNRESET;
1845 	}
1846 	if (con->c.cid == 0) {
1847 		queue_depth = le16_to_cpu(msg->queue_depth);
1848 
1849 		if (clt_path->queue_depth > 0 && queue_depth != clt_path->queue_depth) {
1850 			rtrs_err(clt, "Error: queue depth changed\n");
1851 
1852 			/*
1853 			 * Stop any more reconnection attempts
1854 			 */
1855 			clt_path->reconnect_attempts = -1;
1856 			rtrs_err(clt,
1857 				"Disabling auto-reconnect. Trigger a manual reconnect after issue is resolved\n");
1858 			return -ECONNRESET;
1859 		}
1860 
1861 		if (!clt_path->rbufs) {
1862 			clt_path->rbufs = kcalloc(queue_depth,
1863 						  sizeof(*clt_path->rbufs),
1864 						  GFP_KERNEL);
1865 			if (!clt_path->rbufs)
1866 				return -ENOMEM;
1867 		}
1868 		clt_path->queue_depth = queue_depth;
1869 		clt_path->s.signal_interval = min_not_zero(queue_depth,
1870 						(unsigned short) SERVICE_CON_QUEUE_DEPTH);
1871 		clt_path->max_hdr_size = le32_to_cpu(msg->max_hdr_size);
1872 		clt_path->max_io_size = le32_to_cpu(msg->max_io_size);
1873 		clt_path->flags = le32_to_cpu(msg->flags);
1874 		clt_path->chunk_size = clt_path->max_io_size + clt_path->max_hdr_size;
1875 
1876 		/*
1877 		 * Global IO size is always a minimum.
1878 		 * If while a reconnection server sends us a value a bit
1879 		 * higher - client does not care and uses cached minimum.
1880 		 *
1881 		 * Since we can have several sessions (paths) restablishing
1882 		 * connections in parallel, use lock.
1883 		 */
1884 		mutex_lock(&clt->paths_mutex);
1885 		clt->queue_depth = clt_path->queue_depth;
1886 		clt->max_io_size = min_not_zero(clt_path->max_io_size,
1887 						clt->max_io_size);
1888 		mutex_unlock(&clt->paths_mutex);
1889 
1890 		/*
1891 		 * Cache the hca_port and hca_name for sysfs
1892 		 */
1893 		clt_path->hca_port = con->c.cm_id->port_num;
1894 		scnprintf(clt_path->hca_name, sizeof(clt_path->hca_name),
1895 			  clt_path->s.dev->ib_dev->name);
1896 		clt_path->s.src_addr = con->c.cm_id->route.addr.src_addr;
1897 		/* set for_new_clt, to allow future reconnect on any path */
1898 		clt_path->for_new_clt = 1;
1899 	}
1900 
1901 	return 0;
1902 }
1903 
1904 static inline void flag_success_on_conn(struct rtrs_clt_con *con)
1905 {
1906 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
1907 
1908 	atomic_inc(&clt_path->connected_cnt);
1909 	con->cm_err = 1;
1910 }
1911 
1912 static int rtrs_rdma_conn_rejected(struct rtrs_clt_con *con,
1913 				    struct rdma_cm_event *ev)
1914 {
1915 	struct rtrs_path *s = con->c.path;
1916 	const struct rtrs_msg_conn_rsp *msg;
1917 	const char *rej_msg;
1918 	int status, errno;
1919 	u8 data_len;
1920 
1921 	status = ev->status;
1922 	rej_msg = rdma_reject_msg(con->c.cm_id, status);
1923 	msg = rdma_consumer_reject_data(con->c.cm_id, ev, &data_len);
1924 
1925 	if (msg && data_len >= sizeof(*msg)) {
1926 		errno = (int16_t)le16_to_cpu(msg->errno);
1927 		if (errno == -EBUSY)
1928 			rtrs_err(s,
1929 				  "Previous session is still exists on the server, please reconnect later\n");
1930 		else
1931 			rtrs_err(s,
1932 				  "Connect rejected: status %d (%s), rtrs errno %d\n",
1933 				  status, rej_msg, errno);
1934 	} else {
1935 		rtrs_err(s,
1936 			  "Connect rejected but with malformed message: status %d (%s)\n",
1937 			  status, rej_msg);
1938 	}
1939 
1940 	return -ECONNRESET;
1941 }
1942 
1943 void rtrs_clt_close_conns(struct rtrs_clt_path *clt_path, bool wait)
1944 {
1945 	if (rtrs_clt_change_state_get_old(clt_path, RTRS_CLT_CLOSING, NULL))
1946 		queue_work(rtrs_wq, &clt_path->close_work);
1947 	if (wait)
1948 		flush_work(&clt_path->close_work);
1949 }
1950 
1951 static inline void flag_error_on_conn(struct rtrs_clt_con *con, int cm_err)
1952 {
1953 	if (con->cm_err == 1) {
1954 		struct rtrs_clt_path *clt_path;
1955 
1956 		clt_path = to_clt_path(con->c.path);
1957 		if (atomic_dec_and_test(&clt_path->connected_cnt))
1958 
1959 			wake_up(&clt_path->state_wq);
1960 	}
1961 	con->cm_err = cm_err;
1962 }
1963 
1964 static int rtrs_clt_rdma_cm_handler(struct rdma_cm_id *cm_id,
1965 				     struct rdma_cm_event *ev)
1966 {
1967 	struct rtrs_clt_con *con = cm_id->context;
1968 	struct rtrs_path *s = con->c.path;
1969 	struct rtrs_clt_path *clt_path = to_clt_path(s);
1970 	int cm_err = 0;
1971 
1972 	switch (ev->event) {
1973 	case RDMA_CM_EVENT_ADDR_RESOLVED:
1974 		cm_err = rtrs_rdma_addr_resolved(con);
1975 		break;
1976 	case RDMA_CM_EVENT_ROUTE_RESOLVED:
1977 		cm_err = rtrs_rdma_route_resolved(con);
1978 		break;
1979 	case RDMA_CM_EVENT_ESTABLISHED:
1980 		cm_err = rtrs_rdma_conn_established(con, ev);
1981 		if (!cm_err) {
1982 			/*
1983 			 * Report success and wake up. Here we abuse state_wq,
1984 			 * i.e. wake up without state change, but we set cm_err.
1985 			 */
1986 			flag_success_on_conn(con);
1987 			wake_up(&clt_path->state_wq);
1988 			return 0;
1989 		}
1990 		break;
1991 	case RDMA_CM_EVENT_REJECTED:
1992 		cm_err = rtrs_rdma_conn_rejected(con, ev);
1993 		break;
1994 	case RDMA_CM_EVENT_DISCONNECTED:
1995 		/* No message for disconnecting */
1996 		cm_err = -ECONNRESET;
1997 		break;
1998 	case RDMA_CM_EVENT_CONNECT_ERROR:
1999 	case RDMA_CM_EVENT_UNREACHABLE:
2000 	case RDMA_CM_EVENT_ADDR_CHANGE:
2001 	case RDMA_CM_EVENT_TIMEWAIT_EXIT:
2002 		rtrs_wrn(s, "CM error (CM event: %s, err: %d)\n",
2003 			 rdma_event_msg(ev->event), ev->status);
2004 		cm_err = -ECONNRESET;
2005 		break;
2006 	case RDMA_CM_EVENT_ADDR_ERROR:
2007 	case RDMA_CM_EVENT_ROUTE_ERROR:
2008 		rtrs_wrn(s, "CM error (CM event: %s, err: %d)\n",
2009 			 rdma_event_msg(ev->event), ev->status);
2010 		cm_err = -EHOSTUNREACH;
2011 		break;
2012 	case RDMA_CM_EVENT_DEVICE_REMOVAL:
2013 		/*
2014 		 * Device removal is a special case.  Queue close and return 0.
2015 		 */
2016 		rtrs_clt_close_conns(clt_path, false);
2017 		return 0;
2018 	default:
2019 		rtrs_err(s, "Unexpected RDMA CM error (CM event: %s, err: %d)\n",
2020 			 rdma_event_msg(ev->event), ev->status);
2021 		cm_err = -ECONNRESET;
2022 		break;
2023 	}
2024 
2025 	if (cm_err) {
2026 		/*
2027 		 * cm error makes sense only on connection establishing,
2028 		 * in other cases we rely on normal procedure of reconnecting.
2029 		 */
2030 		flag_error_on_conn(con, cm_err);
2031 		rtrs_rdma_error_recovery(con);
2032 	}
2033 
2034 	return 0;
2035 }
2036 
2037 static int create_cm(struct rtrs_clt_con *con)
2038 {
2039 	struct rtrs_path *s = con->c.path;
2040 	struct rtrs_clt_path *clt_path = to_clt_path(s);
2041 	struct rdma_cm_id *cm_id;
2042 	int err;
2043 
2044 	cm_id = rdma_create_id(&init_net, rtrs_clt_rdma_cm_handler, con,
2045 			       clt_path->s.dst_addr.ss_family == AF_IB ?
2046 			       RDMA_PS_IB : RDMA_PS_TCP, IB_QPT_RC);
2047 	if (IS_ERR(cm_id)) {
2048 		err = PTR_ERR(cm_id);
2049 		rtrs_err(s, "Failed to create CM ID, err: %d\n", err);
2050 
2051 		return err;
2052 	}
2053 	con->c.cm_id = cm_id;
2054 	con->cm_err = 0;
2055 	/* allow the port to be reused */
2056 	err = rdma_set_reuseaddr(cm_id, 1);
2057 	if (err != 0) {
2058 		rtrs_err(s, "Set address reuse failed, err: %d\n", err);
2059 		goto destroy_cm;
2060 	}
2061 	err = rdma_resolve_addr(cm_id, (struct sockaddr *)&clt_path->s.src_addr,
2062 				(struct sockaddr *)&clt_path->s.dst_addr,
2063 				RTRS_CONNECT_TIMEOUT_MS);
2064 	if (err) {
2065 		rtrs_err(s, "Failed to resolve address, err: %d\n", err);
2066 		goto destroy_cm;
2067 	}
2068 	/*
2069 	 * Combine connection status and session events. This is needed
2070 	 * for waiting two possible cases: cm_err has something meaningful
2071 	 * or session state was really changed to error by device removal.
2072 	 */
2073 	err = wait_event_interruptible_timeout(
2074 			clt_path->state_wq,
2075 			con->cm_err || clt_path->state != RTRS_CLT_CONNECTING,
2076 			msecs_to_jiffies(RTRS_CONNECT_TIMEOUT_MS));
2077 	if (err == 0 || err == -ERESTARTSYS) {
2078 		if (err == 0)
2079 			err = -ETIMEDOUT;
2080 		/* Timedout or interrupted */
2081 		goto errr;
2082 	}
2083 	if (con->cm_err < 0) {
2084 		err = con->cm_err;
2085 		goto errr;
2086 	}
2087 	if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTING) {
2088 		/* Device removal */
2089 		err = -ECONNABORTED;
2090 		goto errr;
2091 	}
2092 
2093 	return 0;
2094 
2095 errr:
2096 	stop_cm(con);
2097 	mutex_lock(&con->con_mutex);
2098 	destroy_con_cq_qp(con);
2099 	mutex_unlock(&con->con_mutex);
2100 destroy_cm:
2101 	destroy_cm(con);
2102 
2103 	return err;
2104 }
2105 
2106 static void rtrs_clt_path_up(struct rtrs_clt_path *clt_path)
2107 {
2108 	struct rtrs_clt_sess *clt = clt_path->clt;
2109 	int up;
2110 
2111 	/*
2112 	 * We can fire RECONNECTED event only when all paths were
2113 	 * connected on rtrs_clt_open(), then each was disconnected
2114 	 * and the first one connected again.  That's why this nasty
2115 	 * game with counter value.
2116 	 */
2117 
2118 	mutex_lock(&clt->paths_ev_mutex);
2119 	up = ++clt->paths_up;
2120 	/*
2121 	 * Here it is safe to access paths num directly since up counter
2122 	 * is greater than MAX_PATHS_NUM only while rtrs_clt_open() is
2123 	 * in progress, thus paths removals are impossible.
2124 	 */
2125 	if (up > MAX_PATHS_NUM && up == MAX_PATHS_NUM + clt->paths_num)
2126 		clt->paths_up = clt->paths_num;
2127 	else if (up == 1)
2128 		clt->link_ev(clt->priv, RTRS_CLT_LINK_EV_RECONNECTED);
2129 	mutex_unlock(&clt->paths_ev_mutex);
2130 
2131 	/* Mark session as established */
2132 	clt_path->established = true;
2133 	clt_path->reconnect_attempts = 0;
2134 	clt_path->stats->reconnects.successful_cnt++;
2135 }
2136 
2137 static void rtrs_clt_path_down(struct rtrs_clt_path *clt_path)
2138 {
2139 	struct rtrs_clt_sess *clt = clt_path->clt;
2140 
2141 	if (!clt_path->established)
2142 		return;
2143 
2144 	clt_path->established = false;
2145 	mutex_lock(&clt->paths_ev_mutex);
2146 	WARN_ON(!clt->paths_up);
2147 	if (--clt->paths_up == 0)
2148 		clt->link_ev(clt->priv, RTRS_CLT_LINK_EV_DISCONNECTED);
2149 	mutex_unlock(&clt->paths_ev_mutex);
2150 }
2151 
2152 static void rtrs_clt_stop_and_destroy_conns(struct rtrs_clt_path *clt_path)
2153 {
2154 	struct rtrs_clt_con *con;
2155 	unsigned int cid;
2156 
2157 	WARN_ON(READ_ONCE(clt_path->state) == RTRS_CLT_CONNECTED);
2158 
2159 	/*
2160 	 * Possible race with rtrs_clt_open(), when DEVICE_REMOVAL comes
2161 	 * exactly in between.  Start destroying after it finishes.
2162 	 */
2163 	mutex_lock(&clt_path->init_mutex);
2164 	mutex_unlock(&clt_path->init_mutex);
2165 
2166 	/*
2167 	 * All IO paths must observe !CONNECTED state before we
2168 	 * free everything.
2169 	 */
2170 	synchronize_rcu();
2171 
2172 	rtrs_stop_hb(&clt_path->s);
2173 
2174 	/*
2175 	 * The order it utterly crucial: firstly disconnect and complete all
2176 	 * rdma requests with error (thus set in_use=false for requests),
2177 	 * then fail outstanding requests checking in_use for each, and
2178 	 * eventually notify upper layer about session disconnection.
2179 	 */
2180 
2181 	for (cid = 0; cid < clt_path->s.con_num; cid++) {
2182 		if (!clt_path->s.con[cid])
2183 			break;
2184 		con = to_clt_con(clt_path->s.con[cid]);
2185 		stop_cm(con);
2186 	}
2187 	fail_all_outstanding_reqs(clt_path);
2188 	free_path_reqs(clt_path);
2189 	rtrs_clt_path_down(clt_path);
2190 
2191 	/*
2192 	 * Wait for graceful shutdown, namely when peer side invokes
2193 	 * rdma_disconnect(). 'connected_cnt' is decremented only on
2194 	 * CM events, thus if other side had crashed and hb has detected
2195 	 * something is wrong, here we will stuck for exactly timeout ms,
2196 	 * since CM does not fire anything.  That is fine, we are not in
2197 	 * hurry.
2198 	 */
2199 	wait_event_timeout(clt_path->state_wq,
2200 			   !atomic_read(&clt_path->connected_cnt),
2201 			   msecs_to_jiffies(RTRS_CONNECT_TIMEOUT_MS));
2202 
2203 	for (cid = 0; cid < clt_path->s.con_num; cid++) {
2204 		if (!clt_path->s.con[cid])
2205 			break;
2206 		con = to_clt_con(clt_path->s.con[cid]);
2207 		mutex_lock(&con->con_mutex);
2208 		destroy_con_cq_qp(con);
2209 		mutex_unlock(&con->con_mutex);
2210 		destroy_cm(con);
2211 		destroy_con(con);
2212 	}
2213 }
2214 
2215 static inline bool xchg_paths(struct rtrs_clt_path __rcu **rcu_ppcpu_path,
2216 			      struct rtrs_clt_path *clt_path,
2217 			      struct rtrs_clt_path *next)
2218 {
2219 	struct rtrs_clt_path **ppcpu_path;
2220 
2221 	/* Call cmpxchg() without sparse warnings */
2222 	ppcpu_path = (typeof(ppcpu_path))rcu_ppcpu_path;
2223 	return clt_path == cmpxchg(ppcpu_path, clt_path, next);
2224 }
2225 
2226 static void rtrs_clt_remove_path_from_arr(struct rtrs_clt_path *clt_path)
2227 {
2228 	struct rtrs_clt_sess *clt = clt_path->clt;
2229 	struct rtrs_clt_path *next;
2230 	bool wait_for_grace = false;
2231 	int cpu;
2232 
2233 	mutex_lock(&clt->paths_mutex);
2234 	list_del_rcu(&clt_path->s.entry);
2235 
2236 	/* Make sure everybody observes path removal. */
2237 	synchronize_rcu();
2238 
2239 	/*
2240 	 * At this point nobody sees @sess in the list, but still we have
2241 	 * dangling pointer @pcpu_path which _can_ point to @sess.  Since
2242 	 * nobody can observe @sess in the list, we guarantee that IO path
2243 	 * will not assign @sess to @pcpu_path, i.e. @pcpu_path can be equal
2244 	 * to @sess, but can never again become @sess.
2245 	 */
2246 
2247 	/*
2248 	 * Decrement paths number only after grace period, because
2249 	 * caller of do_each_path() must firstly observe list without
2250 	 * path and only then decremented paths number.
2251 	 *
2252 	 * Otherwise there can be the following situation:
2253 	 *    o Two paths exist and IO is coming.
2254 	 *    o One path is removed:
2255 	 *      CPU#0                          CPU#1
2256 	 *      do_each_path():                rtrs_clt_remove_path_from_arr():
2257 	 *          path = get_next_path()
2258 	 *          ^^^                            list_del_rcu(path)
2259 	 *          [!CONNECTED path]              clt->paths_num--
2260 	 *                                              ^^^^^^^^^
2261 	 *          load clt->paths_num                 from 2 to 1
2262 	 *                    ^^^^^^^^^
2263 	 *                    sees 1
2264 	 *
2265 	 *      path is observed as !CONNECTED, but do_each_path() loop
2266 	 *      ends, because expression i < clt->paths_num is false.
2267 	 */
2268 	clt->paths_num--;
2269 
2270 	/*
2271 	 * Get @next connection from current @sess which is going to be
2272 	 * removed.  If @sess is the last element, then @next is NULL.
2273 	 */
2274 	rcu_read_lock();
2275 	next = rtrs_clt_get_next_path_or_null(&clt->paths_list, clt_path);
2276 	rcu_read_unlock();
2277 
2278 	/*
2279 	 * @pcpu paths can still point to the path which is going to be
2280 	 * removed, so change the pointer manually.
2281 	 */
2282 	for_each_possible_cpu(cpu) {
2283 		struct rtrs_clt_path __rcu **ppcpu_path;
2284 
2285 		ppcpu_path = per_cpu_ptr(clt->pcpu_path, cpu);
2286 		if (rcu_dereference_protected(*ppcpu_path,
2287 			lockdep_is_held(&clt->paths_mutex)) != clt_path)
2288 			/*
2289 			 * synchronize_rcu() was called just after deleting
2290 			 * entry from the list, thus IO code path cannot
2291 			 * change pointer back to the pointer which is going
2292 			 * to be removed, we are safe here.
2293 			 */
2294 			continue;
2295 
2296 		/*
2297 		 * We race with IO code path, which also changes pointer,
2298 		 * thus we have to be careful not to overwrite it.
2299 		 */
2300 		if (xchg_paths(ppcpu_path, clt_path, next))
2301 			/*
2302 			 * @ppcpu_path was successfully replaced with @next,
2303 			 * that means that someone could also pick up the
2304 			 * @sess and dereferencing it right now, so wait for
2305 			 * a grace period is required.
2306 			 */
2307 			wait_for_grace = true;
2308 	}
2309 	if (wait_for_grace)
2310 		synchronize_rcu();
2311 
2312 	mutex_unlock(&clt->paths_mutex);
2313 }
2314 
2315 static void rtrs_clt_add_path_to_arr(struct rtrs_clt_path *clt_path)
2316 {
2317 	struct rtrs_clt_sess *clt = clt_path->clt;
2318 
2319 	mutex_lock(&clt->paths_mutex);
2320 	clt->paths_num++;
2321 
2322 	list_add_tail_rcu(&clt_path->s.entry, &clt->paths_list);
2323 	mutex_unlock(&clt->paths_mutex);
2324 }
2325 
2326 static void rtrs_clt_close_work(struct work_struct *work)
2327 {
2328 	struct rtrs_clt_path *clt_path;
2329 
2330 	clt_path = container_of(work, struct rtrs_clt_path, close_work);
2331 
2332 	cancel_work_sync(&clt_path->err_recovery_work);
2333 	cancel_delayed_work_sync(&clt_path->reconnect_dwork);
2334 	rtrs_clt_stop_and_destroy_conns(clt_path);
2335 	rtrs_clt_change_state_get_old(clt_path, RTRS_CLT_CLOSED, NULL);
2336 }
2337 
2338 static int init_conns(struct rtrs_clt_path *clt_path)
2339 {
2340 	unsigned int cid;
2341 	int err;
2342 
2343 	/*
2344 	 * On every new session connections increase reconnect counter
2345 	 * to avoid clashes with previous sessions not yet closed
2346 	 * sessions on a server side.
2347 	 */
2348 	clt_path->s.recon_cnt++;
2349 
2350 	/* Establish all RDMA connections  */
2351 	for (cid = 0; cid < clt_path->s.con_num; cid++) {
2352 		err = create_con(clt_path, cid);
2353 		if (err)
2354 			goto destroy;
2355 
2356 		err = create_cm(to_clt_con(clt_path->s.con[cid]));
2357 		if (err) {
2358 			destroy_con(to_clt_con(clt_path->s.con[cid]));
2359 			goto destroy;
2360 		}
2361 	}
2362 	err = alloc_path_reqs(clt_path);
2363 	if (err)
2364 		goto destroy;
2365 
2366 	rtrs_start_hb(&clt_path->s);
2367 
2368 	return 0;
2369 
2370 destroy:
2371 	while (cid--) {
2372 		struct rtrs_clt_con *con = to_clt_con(clt_path->s.con[cid]);
2373 
2374 		stop_cm(con);
2375 
2376 		mutex_lock(&con->con_mutex);
2377 		destroy_con_cq_qp(con);
2378 		mutex_unlock(&con->con_mutex);
2379 		destroy_cm(con);
2380 		destroy_con(con);
2381 	}
2382 	/*
2383 	 * If we've never taken async path and got an error, say,
2384 	 * doing rdma_resolve_addr(), switch to CONNECTION_ERR state
2385 	 * manually to keep reconnecting.
2386 	 */
2387 	rtrs_clt_change_state_get_old(clt_path, RTRS_CLT_CONNECTING_ERR, NULL);
2388 
2389 	return err;
2390 }
2391 
2392 static void rtrs_clt_info_req_done(struct ib_cq *cq, struct ib_wc *wc)
2393 {
2394 	struct rtrs_clt_con *con = to_clt_con(wc->qp->qp_context);
2395 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
2396 	struct rtrs_iu *iu;
2397 
2398 	iu = container_of(wc->wr_cqe, struct rtrs_iu, cqe);
2399 	rtrs_iu_free(iu, clt_path->s.dev->ib_dev, 1);
2400 
2401 	if (wc->status != IB_WC_SUCCESS) {
2402 		rtrs_err(clt_path->clt, "Path info request send failed: %s\n",
2403 			  ib_wc_status_msg(wc->status));
2404 		rtrs_clt_change_state_get_old(clt_path, RTRS_CLT_CONNECTING_ERR, NULL);
2405 		return;
2406 	}
2407 
2408 	rtrs_clt_update_wc_stats(con);
2409 }
2410 
2411 static int process_info_rsp(struct rtrs_clt_path *clt_path,
2412 			    const struct rtrs_msg_info_rsp *msg)
2413 {
2414 	unsigned int sg_cnt, total_len;
2415 	int i, sgi;
2416 
2417 	sg_cnt = le16_to_cpu(msg->sg_cnt);
2418 	if (!sg_cnt || (clt_path->queue_depth % sg_cnt)) {
2419 		rtrs_err(clt_path->clt,
2420 			  "Incorrect sg_cnt %d, is not multiple\n",
2421 			  sg_cnt);
2422 		return -EINVAL;
2423 	}
2424 
2425 	/*
2426 	 * Check if IB immediate data size is enough to hold the mem_id and
2427 	 * the offset inside the memory chunk.
2428 	 */
2429 	if ((ilog2(sg_cnt - 1) + 1) + (ilog2(clt_path->chunk_size - 1) + 1) >
2430 	    MAX_IMM_PAYL_BITS) {
2431 		rtrs_err(clt_path->clt,
2432 			  "RDMA immediate size (%db) not enough to encode %d buffers of size %dB\n",
2433 			  MAX_IMM_PAYL_BITS, sg_cnt, clt_path->chunk_size);
2434 		return -EINVAL;
2435 	}
2436 	total_len = 0;
2437 	for (sgi = 0, i = 0; sgi < sg_cnt && i < clt_path->queue_depth; sgi++) {
2438 		const struct rtrs_sg_desc *desc = &msg->desc[sgi];
2439 		u32 len, rkey;
2440 		u64 addr;
2441 
2442 		addr = le64_to_cpu(desc->addr);
2443 		rkey = le32_to_cpu(desc->key);
2444 		len  = le32_to_cpu(desc->len);
2445 
2446 		total_len += len;
2447 
2448 		if (!len || (len % clt_path->chunk_size)) {
2449 			rtrs_err(clt_path->clt, "Incorrect [%d].len %d\n",
2450 				  sgi,
2451 				  len);
2452 			return -EINVAL;
2453 		}
2454 		for ( ; len && i < clt_path->queue_depth; i++) {
2455 			clt_path->rbufs[i].addr = addr;
2456 			clt_path->rbufs[i].rkey = rkey;
2457 
2458 			len  -= clt_path->chunk_size;
2459 			addr += clt_path->chunk_size;
2460 		}
2461 	}
2462 	/* Sanity check */
2463 	if (sgi != sg_cnt || i != clt_path->queue_depth) {
2464 		rtrs_err(clt_path->clt,
2465 			 "Incorrect sg vector, not fully mapped\n");
2466 		return -EINVAL;
2467 	}
2468 	if (total_len != clt_path->chunk_size * clt_path->queue_depth) {
2469 		rtrs_err(clt_path->clt, "Incorrect total_len %d\n", total_len);
2470 		return -EINVAL;
2471 	}
2472 
2473 	return 0;
2474 }
2475 
2476 static void rtrs_clt_info_rsp_done(struct ib_cq *cq, struct ib_wc *wc)
2477 {
2478 	struct rtrs_clt_con *con = to_clt_con(wc->qp->qp_context);
2479 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
2480 	struct rtrs_msg_info_rsp *msg;
2481 	enum rtrs_clt_state state;
2482 	struct rtrs_iu *iu;
2483 	size_t rx_sz;
2484 	int err;
2485 
2486 	state = RTRS_CLT_CONNECTING_ERR;
2487 
2488 	WARN_ON(con->c.cid);
2489 	iu = container_of(wc->wr_cqe, struct rtrs_iu, cqe);
2490 	if (wc->status != IB_WC_SUCCESS) {
2491 		rtrs_err(clt_path->clt, "Path info response recv failed: %s\n",
2492 			  ib_wc_status_msg(wc->status));
2493 		goto out;
2494 	}
2495 	WARN_ON(wc->opcode != IB_WC_RECV);
2496 
2497 	if (wc->byte_len < sizeof(*msg)) {
2498 		rtrs_err(clt_path->clt, "Path info response is malformed: size %d\n",
2499 			  wc->byte_len);
2500 		goto out;
2501 	}
2502 	ib_dma_sync_single_for_cpu(clt_path->s.dev->ib_dev, iu->dma_addr,
2503 				   iu->size, DMA_FROM_DEVICE);
2504 	msg = iu->buf;
2505 	if (le16_to_cpu(msg->type) != RTRS_MSG_INFO_RSP) {
2506 		rtrs_err(clt_path->clt, "Path info response is malformed: type %d\n",
2507 			  le16_to_cpu(msg->type));
2508 		goto out;
2509 	}
2510 	rx_sz  = sizeof(*msg);
2511 	rx_sz += sizeof(msg->desc[0]) * le16_to_cpu(msg->sg_cnt);
2512 	if (wc->byte_len < rx_sz) {
2513 		rtrs_err(clt_path->clt, "Path info response is malformed: size %d\n",
2514 			  wc->byte_len);
2515 		goto out;
2516 	}
2517 	err = process_info_rsp(clt_path, msg);
2518 	if (err)
2519 		goto out;
2520 
2521 	err = post_recv_path(clt_path);
2522 	if (err)
2523 		goto out;
2524 
2525 	state = RTRS_CLT_CONNECTED;
2526 
2527 out:
2528 	rtrs_clt_update_wc_stats(con);
2529 	rtrs_iu_free(iu, clt_path->s.dev->ib_dev, 1);
2530 	rtrs_clt_change_state_get_old(clt_path, state, NULL);
2531 }
2532 
2533 static int rtrs_send_path_info(struct rtrs_clt_path *clt_path)
2534 {
2535 	struct rtrs_clt_con *usr_con = to_clt_con(clt_path->s.con[0]);
2536 	struct rtrs_msg_info_req *msg;
2537 	struct rtrs_iu *tx_iu, *rx_iu;
2538 	size_t rx_sz;
2539 	int err;
2540 
2541 	rx_sz  = sizeof(struct rtrs_msg_info_rsp);
2542 	rx_sz += sizeof(struct rtrs_sg_desc) * clt_path->queue_depth;
2543 
2544 	tx_iu = rtrs_iu_alloc(1, sizeof(struct rtrs_msg_info_req), GFP_KERNEL,
2545 			       clt_path->s.dev->ib_dev, DMA_TO_DEVICE,
2546 			       rtrs_clt_info_req_done);
2547 	rx_iu = rtrs_iu_alloc(1, rx_sz, GFP_KERNEL, clt_path->s.dev->ib_dev,
2548 			       DMA_FROM_DEVICE, rtrs_clt_info_rsp_done);
2549 	if (!tx_iu || !rx_iu) {
2550 		err = -ENOMEM;
2551 		goto out;
2552 	}
2553 	/* Prepare for getting info response */
2554 	err = rtrs_iu_post_recv(&usr_con->c, rx_iu);
2555 	if (err) {
2556 		rtrs_err(clt_path->clt, "rtrs_iu_post_recv(), err: %d\n", err);
2557 		goto out;
2558 	}
2559 	rx_iu = NULL;
2560 
2561 	msg = tx_iu->buf;
2562 	msg->type = cpu_to_le16(RTRS_MSG_INFO_REQ);
2563 	memcpy(msg->pathname, clt_path->s.sessname, sizeof(msg->pathname));
2564 
2565 	ib_dma_sync_single_for_device(clt_path->s.dev->ib_dev,
2566 				      tx_iu->dma_addr,
2567 				      tx_iu->size, DMA_TO_DEVICE);
2568 
2569 	/* Send info request */
2570 	err = rtrs_iu_post_send(&usr_con->c, tx_iu, sizeof(*msg), NULL);
2571 	if (err) {
2572 		rtrs_err(clt_path->clt, "rtrs_iu_post_send(), err: %d\n", err);
2573 		goto out;
2574 	}
2575 	tx_iu = NULL;
2576 
2577 	/* Wait for state change */
2578 	wait_event_interruptible_timeout(clt_path->state_wq,
2579 					 clt_path->state != RTRS_CLT_CONNECTING,
2580 					 msecs_to_jiffies(
2581 						 RTRS_CONNECT_TIMEOUT_MS));
2582 	if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTED) {
2583 		if (READ_ONCE(clt_path->state) == RTRS_CLT_CONNECTING_ERR)
2584 			err = -ECONNRESET;
2585 		else
2586 			err = -ETIMEDOUT;
2587 	}
2588 
2589 out:
2590 	if (tx_iu)
2591 		rtrs_iu_free(tx_iu, clt_path->s.dev->ib_dev, 1);
2592 	if (rx_iu)
2593 		rtrs_iu_free(rx_iu, clt_path->s.dev->ib_dev, 1);
2594 	if (err)
2595 		/* If we've never taken async path because of malloc problems */
2596 		rtrs_clt_change_state_get_old(clt_path,
2597 					      RTRS_CLT_CONNECTING_ERR, NULL);
2598 
2599 	return err;
2600 }
2601 
2602 /**
2603  * init_path() - establishes all path connections and does handshake
2604  * @clt_path: client path.
2605  * In case of error full close or reconnect procedure should be taken,
2606  * because reconnect or close async works can be started.
2607  */
2608 static int init_path(struct rtrs_clt_path *clt_path)
2609 {
2610 	int err;
2611 	char str[NAME_MAX];
2612 	struct rtrs_addr path = {
2613 		.src = &clt_path->s.src_addr,
2614 		.dst = &clt_path->s.dst_addr,
2615 	};
2616 
2617 	rtrs_addr_to_str(&path, str, sizeof(str));
2618 
2619 	mutex_lock(&clt_path->init_mutex);
2620 	err = init_conns(clt_path);
2621 	if (err) {
2622 		rtrs_err(clt_path->clt,
2623 			 "init_conns() failed: err=%d path=%s [%s:%u]\n", err,
2624 			 str, clt_path->hca_name, clt_path->hca_port);
2625 		goto out;
2626 	}
2627 	err = rtrs_send_path_info(clt_path);
2628 	if (err) {
2629 		rtrs_err(clt_path->clt,
2630 			 "rtrs_send_path_info() failed: err=%d path=%s [%s:%u]\n",
2631 			 err, str, clt_path->hca_name, clt_path->hca_port);
2632 		goto out;
2633 	}
2634 	rtrs_clt_path_up(clt_path);
2635 out:
2636 	mutex_unlock(&clt_path->init_mutex);
2637 
2638 	return err;
2639 }
2640 
2641 static void rtrs_clt_reconnect_work(struct work_struct *work)
2642 {
2643 	struct rtrs_clt_path *clt_path;
2644 	struct rtrs_clt_sess *clt;
2645 	int err;
2646 
2647 	clt_path = container_of(to_delayed_work(work), struct rtrs_clt_path,
2648 				reconnect_dwork);
2649 	clt = clt_path->clt;
2650 
2651 	if (READ_ONCE(clt_path->state) != RTRS_CLT_RECONNECTING)
2652 		return;
2653 
2654 	if (clt_path->reconnect_attempts >= clt->max_reconnect_attempts) {
2655 		/* Close a path completely if max attempts is reached */
2656 		rtrs_clt_close_conns(clt_path, false);
2657 		return;
2658 	}
2659 	clt_path->reconnect_attempts++;
2660 
2661 	msleep(RTRS_RECONNECT_BACKOFF);
2662 	if (rtrs_clt_change_state_get_old(clt_path, RTRS_CLT_CONNECTING, NULL)) {
2663 		err = init_path(clt_path);
2664 		if (err)
2665 			goto reconnect_again;
2666 	}
2667 
2668 	return;
2669 
2670 reconnect_again:
2671 	if (rtrs_clt_change_state_get_old(clt_path, RTRS_CLT_RECONNECTING, NULL)) {
2672 		clt_path->stats->reconnects.fail_cnt++;
2673 		queue_work(rtrs_wq, &clt_path->err_recovery_work);
2674 	}
2675 }
2676 
2677 static void rtrs_clt_dev_release(struct device *dev)
2678 {
2679 	struct rtrs_clt_sess *clt = container_of(dev, struct rtrs_clt_sess,
2680 						 dev);
2681 
2682 	mutex_destroy(&clt->paths_ev_mutex);
2683 	mutex_destroy(&clt->paths_mutex);
2684 	kfree(clt);
2685 }
2686 
2687 static struct rtrs_clt_sess *alloc_clt(const char *sessname, size_t paths_num,
2688 				  u16 port, size_t pdu_sz, void *priv,
2689 				  void	(*link_ev)(void *priv,
2690 						   enum rtrs_clt_link_ev ev),
2691 				  unsigned int reconnect_delay_sec,
2692 				  unsigned int max_reconnect_attempts)
2693 {
2694 	struct rtrs_clt_sess *clt;
2695 	int err;
2696 
2697 	if (!paths_num || paths_num > MAX_PATHS_NUM)
2698 		return ERR_PTR(-EINVAL);
2699 
2700 	if (strlen(sessname) >= sizeof(clt->sessname))
2701 		return ERR_PTR(-EINVAL);
2702 
2703 	clt = kzalloc(sizeof(*clt), GFP_KERNEL);
2704 	if (!clt)
2705 		return ERR_PTR(-ENOMEM);
2706 
2707 	clt->pcpu_path = alloc_percpu(typeof(*clt->pcpu_path));
2708 	if (!clt->pcpu_path) {
2709 		kfree(clt);
2710 		return ERR_PTR(-ENOMEM);
2711 	}
2712 
2713 	clt->dev.class = rtrs_clt_dev_class;
2714 	clt->dev.release = rtrs_clt_dev_release;
2715 	uuid_gen(&clt->paths_uuid);
2716 	INIT_LIST_HEAD_RCU(&clt->paths_list);
2717 	clt->paths_num = paths_num;
2718 	clt->paths_up = MAX_PATHS_NUM;
2719 	clt->port = port;
2720 	clt->pdu_sz = pdu_sz;
2721 	clt->max_segments = RTRS_MAX_SEGMENTS;
2722 	clt->reconnect_delay_sec = reconnect_delay_sec;
2723 	clt->max_reconnect_attempts = max_reconnect_attempts;
2724 	clt->priv = priv;
2725 	clt->link_ev = link_ev;
2726 	clt->mp_policy = MP_POLICY_MIN_INFLIGHT;
2727 	strscpy(clt->sessname, sessname, sizeof(clt->sessname));
2728 	init_waitqueue_head(&clt->permits_wait);
2729 	mutex_init(&clt->paths_ev_mutex);
2730 	mutex_init(&clt->paths_mutex);
2731 	device_initialize(&clt->dev);
2732 
2733 	err = dev_set_name(&clt->dev, "%s", sessname);
2734 	if (err)
2735 		goto err_put;
2736 
2737 	/*
2738 	 * Suppress user space notification until
2739 	 * sysfs files are created
2740 	 */
2741 	dev_set_uevent_suppress(&clt->dev, true);
2742 	err = device_add(&clt->dev);
2743 	if (err)
2744 		goto err_put;
2745 
2746 	clt->kobj_paths = kobject_create_and_add("paths", &clt->dev.kobj);
2747 	if (!clt->kobj_paths) {
2748 		err = -ENOMEM;
2749 		goto err_del;
2750 	}
2751 	err = rtrs_clt_create_sysfs_root_files(clt);
2752 	if (err) {
2753 		kobject_del(clt->kobj_paths);
2754 		kobject_put(clt->kobj_paths);
2755 		goto err_del;
2756 	}
2757 	dev_set_uevent_suppress(&clt->dev, false);
2758 	kobject_uevent(&clt->dev.kobj, KOBJ_ADD);
2759 
2760 	return clt;
2761 err_del:
2762 	device_del(&clt->dev);
2763 err_put:
2764 	free_percpu(clt->pcpu_path);
2765 	put_device(&clt->dev);
2766 	return ERR_PTR(err);
2767 }
2768 
2769 static void free_clt(struct rtrs_clt_sess *clt)
2770 {
2771 	free_percpu(clt->pcpu_path);
2772 
2773 	/*
2774 	 * release callback will free clt and destroy mutexes in last put
2775 	 */
2776 	device_unregister(&clt->dev);
2777 }
2778 
2779 /**
2780  * rtrs_clt_open() - Open a path to an RTRS server
2781  * @ops: holds the link event callback and the private pointer.
2782  * @pathname: name of the path to an RTRS server
2783  * @paths: Paths to be established defined by their src and dst addresses
2784  * @paths_num: Number of elements in the @paths array
2785  * @port: port to be used by the RTRS session
2786  * @pdu_sz: Size of extra payload which can be accessed after permit allocation.
2787  * @reconnect_delay_sec: time between reconnect tries
2788  * @max_reconnect_attempts: Number of times to reconnect on error before giving
2789  *			    up, 0 for * disabled, -1 for forever
2790  * @nr_poll_queues: number of polling mode connection using IB_POLL_DIRECT flag
2791  *
2792  * Starts session establishment with the rtrs_server. The function can block
2793  * up to ~2000ms before it returns.
2794  *
2795  * Return a valid pointer on success otherwise PTR_ERR.
2796  */
2797 struct rtrs_clt_sess *rtrs_clt_open(struct rtrs_clt_ops *ops,
2798 				 const char *pathname,
2799 				 const struct rtrs_addr *paths,
2800 				 size_t paths_num, u16 port,
2801 				 size_t pdu_sz, u8 reconnect_delay_sec,
2802 				 s16 max_reconnect_attempts, u32 nr_poll_queues)
2803 {
2804 	struct rtrs_clt_path *clt_path, *tmp;
2805 	struct rtrs_clt_sess *clt;
2806 	int err, i;
2807 
2808 	if (strchr(pathname, '/') || strchr(pathname, '.')) {
2809 		pr_err("pathname cannot contain / and .\n");
2810 		err = -EINVAL;
2811 		goto out;
2812 	}
2813 
2814 	clt = alloc_clt(pathname, paths_num, port, pdu_sz, ops->priv,
2815 			ops->link_ev,
2816 			reconnect_delay_sec,
2817 			max_reconnect_attempts);
2818 	if (IS_ERR(clt)) {
2819 		err = PTR_ERR(clt);
2820 		goto out;
2821 	}
2822 	for (i = 0; i < paths_num; i++) {
2823 		struct rtrs_clt_path *clt_path;
2824 
2825 		clt_path = alloc_path(clt, &paths[i], nr_cpu_ids,
2826 				  nr_poll_queues);
2827 		if (IS_ERR(clt_path)) {
2828 			err = PTR_ERR(clt_path);
2829 			goto close_all_path;
2830 		}
2831 		if (!i)
2832 			clt_path->for_new_clt = 1;
2833 		list_add_tail_rcu(&clt_path->s.entry, &clt->paths_list);
2834 
2835 		err = init_path(clt_path);
2836 		if (err) {
2837 			list_del_rcu(&clt_path->s.entry);
2838 			rtrs_clt_close_conns(clt_path, true);
2839 			free_percpu(clt_path->stats->pcpu_stats);
2840 			kfree(clt_path->stats);
2841 			free_path(clt_path);
2842 			goto close_all_path;
2843 		}
2844 
2845 		err = rtrs_clt_create_path_files(clt_path);
2846 		if (err) {
2847 			list_del_rcu(&clt_path->s.entry);
2848 			rtrs_clt_close_conns(clt_path, true);
2849 			free_percpu(clt_path->stats->pcpu_stats);
2850 			kfree(clt_path->stats);
2851 			free_path(clt_path);
2852 			goto close_all_path;
2853 		}
2854 	}
2855 	err = alloc_permits(clt);
2856 	if (err)
2857 		goto close_all_path;
2858 
2859 	return clt;
2860 
2861 close_all_path:
2862 	list_for_each_entry_safe(clt_path, tmp, &clt->paths_list, s.entry) {
2863 		rtrs_clt_destroy_path_files(clt_path, NULL);
2864 		rtrs_clt_close_conns(clt_path, true);
2865 		kobject_put(&clt_path->kobj);
2866 	}
2867 	rtrs_clt_destroy_sysfs_root(clt);
2868 	free_clt(clt);
2869 
2870 out:
2871 	return ERR_PTR(err);
2872 }
2873 EXPORT_SYMBOL(rtrs_clt_open);
2874 
2875 /**
2876  * rtrs_clt_close() - Close a path
2877  * @clt: Session handle. Session is freed upon return.
2878  */
2879 void rtrs_clt_close(struct rtrs_clt_sess *clt)
2880 {
2881 	struct rtrs_clt_path *clt_path, *tmp;
2882 
2883 	/* Firstly forbid sysfs access */
2884 	rtrs_clt_destroy_sysfs_root(clt);
2885 
2886 	/* Now it is safe to iterate over all paths without locks */
2887 	list_for_each_entry_safe(clt_path, tmp, &clt->paths_list, s.entry) {
2888 		rtrs_clt_close_conns(clt_path, true);
2889 		rtrs_clt_destroy_path_files(clt_path, NULL);
2890 		kobject_put(&clt_path->kobj);
2891 	}
2892 	free_permits(clt);
2893 	free_clt(clt);
2894 }
2895 EXPORT_SYMBOL(rtrs_clt_close);
2896 
2897 int rtrs_clt_reconnect_from_sysfs(struct rtrs_clt_path *clt_path)
2898 {
2899 	enum rtrs_clt_state old_state;
2900 	int err = -EBUSY;
2901 	bool changed;
2902 
2903 	changed = rtrs_clt_change_state_get_old(clt_path,
2904 						 RTRS_CLT_RECONNECTING,
2905 						 &old_state);
2906 	if (changed) {
2907 		clt_path->reconnect_attempts = 0;
2908 		rtrs_clt_stop_and_destroy_conns(clt_path);
2909 		queue_delayed_work(rtrs_wq, &clt_path->reconnect_dwork, 0);
2910 	}
2911 	if (changed || old_state == RTRS_CLT_RECONNECTING) {
2912 		/*
2913 		 * flush_delayed_work() queues pending work for immediate
2914 		 * execution, so do the flush if we have queued something
2915 		 * right now or work is pending.
2916 		 */
2917 		flush_delayed_work(&clt_path->reconnect_dwork);
2918 		err = (READ_ONCE(clt_path->state) ==
2919 		       RTRS_CLT_CONNECTED ? 0 : -ENOTCONN);
2920 	}
2921 
2922 	return err;
2923 }
2924 
2925 int rtrs_clt_remove_path_from_sysfs(struct rtrs_clt_path *clt_path,
2926 				     const struct attribute *sysfs_self)
2927 {
2928 	enum rtrs_clt_state old_state;
2929 	bool changed;
2930 
2931 	/*
2932 	 * Continue stopping path till state was changed to DEAD or
2933 	 * state was observed as DEAD:
2934 	 * 1. State was changed to DEAD - we were fast and nobody
2935 	 *    invoked rtrs_clt_reconnect(), which can again start
2936 	 *    reconnecting.
2937 	 * 2. State was observed as DEAD - we have someone in parallel
2938 	 *    removing the path.
2939 	 */
2940 	do {
2941 		rtrs_clt_close_conns(clt_path, true);
2942 		changed = rtrs_clt_change_state_get_old(clt_path,
2943 							RTRS_CLT_DEAD,
2944 							&old_state);
2945 	} while (!changed && old_state != RTRS_CLT_DEAD);
2946 
2947 	if (changed) {
2948 		rtrs_clt_remove_path_from_arr(clt_path);
2949 		rtrs_clt_destroy_path_files(clt_path, sysfs_self);
2950 		kobject_put(&clt_path->kobj);
2951 	}
2952 
2953 	return 0;
2954 }
2955 
2956 void rtrs_clt_set_max_reconnect_attempts(struct rtrs_clt_sess *clt, int value)
2957 {
2958 	clt->max_reconnect_attempts = (unsigned int)value;
2959 }
2960 
2961 int rtrs_clt_get_max_reconnect_attempts(const struct rtrs_clt_sess *clt)
2962 {
2963 	return (int)clt->max_reconnect_attempts;
2964 }
2965 
2966 /**
2967  * rtrs_clt_request() - Request data transfer to/from server via RDMA.
2968  *
2969  * @dir:	READ/WRITE
2970  * @ops:	callback function to be called as confirmation, and the pointer.
2971  * @clt:	Session
2972  * @permit:	Preallocated permit
2973  * @vec:	Message that is sent to server together with the request.
2974  *		Sum of len of all @vec elements limited to <= IO_MSG_SIZE.
2975  *		Since the msg is copied internally it can be allocated on stack.
2976  * @nr:		Number of elements in @vec.
2977  * @data_len:	length of data sent to/from server
2978  * @sg:		Pages to be sent/received to/from server.
2979  * @sg_cnt:	Number of elements in the @sg
2980  *
2981  * Return:
2982  * 0:		Success
2983  * <0:		Error
2984  *
2985  * On dir=READ rtrs client will request a data transfer from Server to client.
2986  * The data that the server will respond with will be stored in @sg when
2987  * the user receives an %RTRS_CLT_RDMA_EV_RDMA_REQUEST_WRITE_COMPL event.
2988  * On dir=WRITE rtrs client will rdma write data in sg to server side.
2989  */
2990 int rtrs_clt_request(int dir, struct rtrs_clt_req_ops *ops,
2991 		     struct rtrs_clt_sess *clt, struct rtrs_permit *permit,
2992 		     const struct kvec *vec, size_t nr, size_t data_len,
2993 		     struct scatterlist *sg, unsigned int sg_cnt)
2994 {
2995 	struct rtrs_clt_io_req *req;
2996 	struct rtrs_clt_path *clt_path;
2997 
2998 	enum dma_data_direction dma_dir;
2999 	int err = -ECONNABORTED, i;
3000 	size_t usr_len, hdr_len;
3001 	struct path_it it;
3002 
3003 	/* Get kvec length */
3004 	for (i = 0, usr_len = 0; i < nr; i++)
3005 		usr_len += vec[i].iov_len;
3006 
3007 	if (dir == READ) {
3008 		hdr_len = sizeof(struct rtrs_msg_rdma_read) +
3009 			  sg_cnt * sizeof(struct rtrs_sg_desc);
3010 		dma_dir = DMA_FROM_DEVICE;
3011 	} else {
3012 		hdr_len = sizeof(struct rtrs_msg_rdma_write);
3013 		dma_dir = DMA_TO_DEVICE;
3014 	}
3015 
3016 	rcu_read_lock();
3017 	for (path_it_init(&it, clt);
3018 	     (clt_path = it.next_path(&it)) && it.i < it.clt->paths_num; it.i++) {
3019 		if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTED)
3020 			continue;
3021 
3022 		if (usr_len + hdr_len > clt_path->max_hdr_size) {
3023 			rtrs_wrn_rl(clt_path->clt,
3024 				     "%s request failed, user message size is %zu and header length %zu, but max size is %u\n",
3025 				     dir == READ ? "Read" : "Write",
3026 				     usr_len, hdr_len, clt_path->max_hdr_size);
3027 			err = -EMSGSIZE;
3028 			break;
3029 		}
3030 		req = rtrs_clt_get_req(clt_path, ops->conf_fn, permit, ops->priv,
3031 				       vec, usr_len, sg, sg_cnt, data_len,
3032 				       dma_dir);
3033 		if (dir == READ)
3034 			err = rtrs_clt_read_req(req);
3035 		else
3036 			err = rtrs_clt_write_req(req);
3037 		if (err) {
3038 			req->in_use = false;
3039 			continue;
3040 		}
3041 		/* Success path */
3042 		break;
3043 	}
3044 	path_it_deinit(&it);
3045 	rcu_read_unlock();
3046 
3047 	return err;
3048 }
3049 EXPORT_SYMBOL(rtrs_clt_request);
3050 
3051 int rtrs_clt_rdma_cq_direct(struct rtrs_clt_sess *clt, unsigned int index)
3052 {
3053 	/* If no path, return -1 for block layer not to try again */
3054 	int cnt = -1;
3055 	struct rtrs_con *con;
3056 	struct rtrs_clt_path *clt_path;
3057 	struct path_it it;
3058 
3059 	rcu_read_lock();
3060 	for (path_it_init(&it, clt);
3061 	     (clt_path = it.next_path(&it)) && it.i < it.clt->paths_num; it.i++) {
3062 		if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTED)
3063 			continue;
3064 
3065 		con = clt_path->s.con[index + 1];
3066 		cnt = ib_process_cq_direct(con->cq, -1);
3067 		if (cnt)
3068 			break;
3069 	}
3070 	path_it_deinit(&it);
3071 	rcu_read_unlock();
3072 
3073 	return cnt;
3074 }
3075 EXPORT_SYMBOL(rtrs_clt_rdma_cq_direct);
3076 
3077 /**
3078  * rtrs_clt_query() - queries RTRS session attributes
3079  *@clt: session pointer
3080  *@attr: query results for session attributes.
3081  * Returns:
3082  *    0 on success
3083  *    -ECOMM		no connection to the server
3084  */
3085 int rtrs_clt_query(struct rtrs_clt_sess *clt, struct rtrs_attrs *attr)
3086 {
3087 	if (!rtrs_clt_is_connected(clt))
3088 		return -ECOMM;
3089 
3090 	attr->queue_depth      = clt->queue_depth;
3091 	attr->max_segments     = clt->max_segments;
3092 	/* Cap max_io_size to min of remote buffer size and the fr pages */
3093 	attr->max_io_size = min_t(int, clt->max_io_size,
3094 				  clt->max_segments * SZ_4K);
3095 
3096 	return 0;
3097 }
3098 EXPORT_SYMBOL(rtrs_clt_query);
3099 
3100 int rtrs_clt_create_path_from_sysfs(struct rtrs_clt_sess *clt,
3101 				     struct rtrs_addr *addr)
3102 {
3103 	struct rtrs_clt_path *clt_path;
3104 	int err;
3105 
3106 	clt_path = alloc_path(clt, addr, nr_cpu_ids, 0);
3107 	if (IS_ERR(clt_path))
3108 		return PTR_ERR(clt_path);
3109 
3110 	mutex_lock(&clt->paths_mutex);
3111 	if (clt->paths_num == 0) {
3112 		/*
3113 		 * When all the paths are removed for a session,
3114 		 * the addition of the first path is like a new session for
3115 		 * the storage server
3116 		 */
3117 		clt_path->for_new_clt = 1;
3118 	}
3119 
3120 	mutex_unlock(&clt->paths_mutex);
3121 
3122 	/*
3123 	 * It is totally safe to add path in CONNECTING state: coming
3124 	 * IO will never grab it.  Also it is very important to add
3125 	 * path before init, since init fires LINK_CONNECTED event.
3126 	 */
3127 	rtrs_clt_add_path_to_arr(clt_path);
3128 
3129 	err = init_path(clt_path);
3130 	if (err)
3131 		goto close_path;
3132 
3133 	err = rtrs_clt_create_path_files(clt_path);
3134 	if (err)
3135 		goto close_path;
3136 
3137 	return 0;
3138 
3139 close_path:
3140 	rtrs_clt_remove_path_from_arr(clt_path);
3141 	rtrs_clt_close_conns(clt_path, true);
3142 	free_percpu(clt_path->stats->pcpu_stats);
3143 	kfree(clt_path->stats);
3144 	free_path(clt_path);
3145 
3146 	return err;
3147 }
3148 
3149 static int rtrs_clt_ib_dev_init(struct rtrs_ib_dev *dev)
3150 {
3151 	if (!(dev->ib_dev->attrs.device_cap_flags &
3152 	      IB_DEVICE_MEM_MGT_EXTENSIONS)) {
3153 		pr_err("Memory registrations not supported.\n");
3154 		return -ENOTSUPP;
3155 	}
3156 
3157 	return 0;
3158 }
3159 
3160 static const struct rtrs_rdma_dev_pd_ops dev_pd_ops = {
3161 	.init = rtrs_clt_ib_dev_init
3162 };
3163 
3164 static int __init rtrs_client_init(void)
3165 {
3166 	rtrs_rdma_dev_pd_init(0, &dev_pd);
3167 
3168 	rtrs_clt_dev_class = class_create(THIS_MODULE, "rtrs-client");
3169 	if (IS_ERR(rtrs_clt_dev_class)) {
3170 		pr_err("Failed to create rtrs-client dev class\n");
3171 		return PTR_ERR(rtrs_clt_dev_class);
3172 	}
3173 	rtrs_wq = alloc_workqueue("rtrs_client_wq", 0, 0);
3174 	if (!rtrs_wq) {
3175 		class_destroy(rtrs_clt_dev_class);
3176 		return -ENOMEM;
3177 	}
3178 
3179 	return 0;
3180 }
3181 
3182 static void __exit rtrs_client_exit(void)
3183 {
3184 	destroy_workqueue(rtrs_wq);
3185 	class_destroy(rtrs_clt_dev_class);
3186 	rtrs_rdma_dev_pd_deinit(&dev_pd);
3187 }
3188 
3189 module_init(rtrs_client_init);
3190 module_exit(rtrs_client_exit);
3191