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