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_vector = con->cpu % clt_path->s.dev->ib_dev->num_comp_vectors;
1714 	if (con->c.cid >= clt_path->s.irq_con_num)
1715 		err = rtrs_cq_qp_create(&clt_path->s, &con->c, max_send_sge,
1716 					cq_vector, cq_num, max_send_wr,
1717 					max_recv_wr, IB_POLL_DIRECT);
1718 	else
1719 		err = rtrs_cq_qp_create(&clt_path->s, &con->c, max_send_sge,
1720 					cq_vector, cq_num, max_send_wr,
1721 					max_recv_wr, IB_POLL_SOFTIRQ);
1722 	/*
1723 	 * In case of error we do not bother to clean previous allocations,
1724 	 * since destroy_con_cq_qp() must be called.
1725 	 */
1726 	return err;
1727 }
1728 
1729 static void destroy_con_cq_qp(struct rtrs_clt_con *con)
1730 {
1731 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
1732 
1733 	/*
1734 	 * Be careful here: destroy_con_cq_qp() can be called even
1735 	 * create_con_cq_qp() failed, see comments there.
1736 	 */
1737 	lockdep_assert_held(&con->con_mutex);
1738 	rtrs_cq_qp_destroy(&con->c);
1739 	if (con->rsp_ius) {
1740 		rtrs_iu_free(con->rsp_ius, clt_path->s.dev->ib_dev,
1741 			     con->queue_num);
1742 		con->rsp_ius = NULL;
1743 		con->queue_num = 0;
1744 	}
1745 	if (clt_path->s.dev_ref && !--clt_path->s.dev_ref) {
1746 		rtrs_ib_dev_put(clt_path->s.dev);
1747 		clt_path->s.dev = NULL;
1748 	}
1749 }
1750 
1751 static void stop_cm(struct rtrs_clt_con *con)
1752 {
1753 	rdma_disconnect(con->c.cm_id);
1754 	if (con->c.qp)
1755 		ib_drain_qp(con->c.qp);
1756 }
1757 
1758 static void destroy_cm(struct rtrs_clt_con *con)
1759 {
1760 	rdma_destroy_id(con->c.cm_id);
1761 	con->c.cm_id = NULL;
1762 }
1763 
1764 static int rtrs_rdma_addr_resolved(struct rtrs_clt_con *con)
1765 {
1766 	struct rtrs_path *s = con->c.path;
1767 	int err;
1768 
1769 	mutex_lock(&con->con_mutex);
1770 	err = create_con_cq_qp(con);
1771 	mutex_unlock(&con->con_mutex);
1772 	if (err) {
1773 		rtrs_err(s, "create_con_cq_qp(), err: %d\n", err);
1774 		return err;
1775 	}
1776 	err = rdma_resolve_route(con->c.cm_id, RTRS_CONNECT_TIMEOUT_MS);
1777 	if (err)
1778 		rtrs_err(s, "Resolving route failed, err: %d\n", err);
1779 
1780 	return err;
1781 }
1782 
1783 static int rtrs_rdma_route_resolved(struct rtrs_clt_con *con)
1784 {
1785 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
1786 	struct rtrs_clt_sess *clt = clt_path->clt;
1787 	struct rtrs_msg_conn_req msg;
1788 	struct rdma_conn_param param;
1789 
1790 	int err;
1791 
1792 	param = (struct rdma_conn_param) {
1793 		.retry_count = 7,
1794 		.rnr_retry_count = 7,
1795 		.private_data = &msg,
1796 		.private_data_len = sizeof(msg),
1797 	};
1798 
1799 	msg = (struct rtrs_msg_conn_req) {
1800 		.magic = cpu_to_le16(RTRS_MAGIC),
1801 		.version = cpu_to_le16(RTRS_PROTO_VER),
1802 		.cid = cpu_to_le16(con->c.cid),
1803 		.cid_num = cpu_to_le16(clt_path->s.con_num),
1804 		.recon_cnt = cpu_to_le16(clt_path->s.recon_cnt),
1805 	};
1806 	msg.first_conn = clt_path->for_new_clt ? FIRST_CONN : 0;
1807 	uuid_copy(&msg.sess_uuid, &clt_path->s.uuid);
1808 	uuid_copy(&msg.paths_uuid, &clt->paths_uuid);
1809 
1810 	err = rdma_connect_locked(con->c.cm_id, &param);
1811 	if (err)
1812 		rtrs_err(clt, "rdma_connect_locked(): %d\n", err);
1813 
1814 	return err;
1815 }
1816 
1817 static int rtrs_rdma_conn_established(struct rtrs_clt_con *con,
1818 				       struct rdma_cm_event *ev)
1819 {
1820 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
1821 	struct rtrs_clt_sess *clt = clt_path->clt;
1822 	const struct rtrs_msg_conn_rsp *msg;
1823 	u16 version, queue_depth;
1824 	int errno;
1825 	u8 len;
1826 
1827 	msg = ev->param.conn.private_data;
1828 	len = ev->param.conn.private_data_len;
1829 	if (len < sizeof(*msg)) {
1830 		rtrs_err(clt, "Invalid RTRS connection response\n");
1831 		return -ECONNRESET;
1832 	}
1833 	if (le16_to_cpu(msg->magic) != RTRS_MAGIC) {
1834 		rtrs_err(clt, "Invalid RTRS magic\n");
1835 		return -ECONNRESET;
1836 	}
1837 	version = le16_to_cpu(msg->version);
1838 	if (version >> 8 != RTRS_PROTO_VER_MAJOR) {
1839 		rtrs_err(clt, "Unsupported major RTRS version: %d, expected %d\n",
1840 			  version >> 8, RTRS_PROTO_VER_MAJOR);
1841 		return -ECONNRESET;
1842 	}
1843 	errno = le16_to_cpu(msg->errno);
1844 	if (errno) {
1845 		rtrs_err(clt, "Invalid RTRS message: errno %d\n",
1846 			  errno);
1847 		return -ECONNRESET;
1848 	}
1849 	if (con->c.cid == 0) {
1850 		queue_depth = le16_to_cpu(msg->queue_depth);
1851 
1852 		if (clt_path->queue_depth > 0 && queue_depth != clt_path->queue_depth) {
1853 			rtrs_err(clt, "Error: queue depth changed\n");
1854 
1855 			/*
1856 			 * Stop any more reconnection attempts
1857 			 */
1858 			clt_path->reconnect_attempts = -1;
1859 			rtrs_err(clt,
1860 				"Disabling auto-reconnect. Trigger a manual reconnect after issue is resolved\n");
1861 			return -ECONNRESET;
1862 		}
1863 
1864 		if (!clt_path->rbufs) {
1865 			clt_path->rbufs = kcalloc(queue_depth,
1866 						  sizeof(*clt_path->rbufs),
1867 						  GFP_KERNEL);
1868 			if (!clt_path->rbufs)
1869 				return -ENOMEM;
1870 		}
1871 		clt_path->queue_depth = queue_depth;
1872 		clt_path->s.signal_interval = min_not_zero(queue_depth,
1873 						(unsigned short) SERVICE_CON_QUEUE_DEPTH);
1874 		clt_path->max_hdr_size = le32_to_cpu(msg->max_hdr_size);
1875 		clt_path->max_io_size = le32_to_cpu(msg->max_io_size);
1876 		clt_path->flags = le32_to_cpu(msg->flags);
1877 		clt_path->chunk_size = clt_path->max_io_size + clt_path->max_hdr_size;
1878 
1879 		/*
1880 		 * Global IO size is always a minimum.
1881 		 * If while a reconnection server sends us a value a bit
1882 		 * higher - client does not care and uses cached minimum.
1883 		 *
1884 		 * Since we can have several sessions (paths) restablishing
1885 		 * connections in parallel, use lock.
1886 		 */
1887 		mutex_lock(&clt->paths_mutex);
1888 		clt->queue_depth = clt_path->queue_depth;
1889 		clt->max_io_size = min_not_zero(clt_path->max_io_size,
1890 						clt->max_io_size);
1891 		mutex_unlock(&clt->paths_mutex);
1892 
1893 		/*
1894 		 * Cache the hca_port and hca_name for sysfs
1895 		 */
1896 		clt_path->hca_port = con->c.cm_id->port_num;
1897 		scnprintf(clt_path->hca_name, sizeof(clt_path->hca_name),
1898 			  clt_path->s.dev->ib_dev->name);
1899 		clt_path->s.src_addr = con->c.cm_id->route.addr.src_addr;
1900 		/* set for_new_clt, to allow future reconnect on any path */
1901 		clt_path->for_new_clt = 1;
1902 	}
1903 
1904 	return 0;
1905 }
1906 
1907 static inline void flag_success_on_conn(struct rtrs_clt_con *con)
1908 {
1909 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
1910 
1911 	atomic_inc(&clt_path->connected_cnt);
1912 	con->cm_err = 1;
1913 }
1914 
1915 static int rtrs_rdma_conn_rejected(struct rtrs_clt_con *con,
1916 				    struct rdma_cm_event *ev)
1917 {
1918 	struct rtrs_path *s = con->c.path;
1919 	const struct rtrs_msg_conn_rsp *msg;
1920 	const char *rej_msg;
1921 	int status, errno;
1922 	u8 data_len;
1923 
1924 	status = ev->status;
1925 	rej_msg = rdma_reject_msg(con->c.cm_id, status);
1926 	msg = rdma_consumer_reject_data(con->c.cm_id, ev, &data_len);
1927 
1928 	if (msg && data_len >= sizeof(*msg)) {
1929 		errno = (int16_t)le16_to_cpu(msg->errno);
1930 		if (errno == -EBUSY)
1931 			rtrs_err(s,
1932 				  "Previous session is still exists on the server, please reconnect later\n");
1933 		else
1934 			rtrs_err(s,
1935 				  "Connect rejected: status %d (%s), rtrs errno %d\n",
1936 				  status, rej_msg, errno);
1937 	} else {
1938 		rtrs_err(s,
1939 			  "Connect rejected but with malformed message: status %d (%s)\n",
1940 			  status, rej_msg);
1941 	}
1942 
1943 	return -ECONNRESET;
1944 }
1945 
1946 void rtrs_clt_close_conns(struct rtrs_clt_path *clt_path, bool wait)
1947 {
1948 	trace_rtrs_clt_close_conns(clt_path);
1949 
1950 	if (rtrs_clt_change_state_get_old(clt_path, RTRS_CLT_CLOSING, NULL))
1951 		queue_work(rtrs_wq, &clt_path->close_work);
1952 	if (wait)
1953 		flush_work(&clt_path->close_work);
1954 }
1955 
1956 static inline void flag_error_on_conn(struct rtrs_clt_con *con, int cm_err)
1957 {
1958 	if (con->cm_err == 1) {
1959 		struct rtrs_clt_path *clt_path;
1960 
1961 		clt_path = to_clt_path(con->c.path);
1962 		if (atomic_dec_and_test(&clt_path->connected_cnt))
1963 
1964 			wake_up(&clt_path->state_wq);
1965 	}
1966 	con->cm_err = cm_err;
1967 }
1968 
1969 static int rtrs_clt_rdma_cm_handler(struct rdma_cm_id *cm_id,
1970 				     struct rdma_cm_event *ev)
1971 {
1972 	struct rtrs_clt_con *con = cm_id->context;
1973 	struct rtrs_path *s = con->c.path;
1974 	struct rtrs_clt_path *clt_path = to_clt_path(s);
1975 	int cm_err = 0;
1976 
1977 	switch (ev->event) {
1978 	case RDMA_CM_EVENT_ADDR_RESOLVED:
1979 		cm_err = rtrs_rdma_addr_resolved(con);
1980 		break;
1981 	case RDMA_CM_EVENT_ROUTE_RESOLVED:
1982 		cm_err = rtrs_rdma_route_resolved(con);
1983 		break;
1984 	case RDMA_CM_EVENT_ESTABLISHED:
1985 		cm_err = rtrs_rdma_conn_established(con, ev);
1986 		if (!cm_err) {
1987 			/*
1988 			 * Report success and wake up. Here we abuse state_wq,
1989 			 * i.e. wake up without state change, but we set cm_err.
1990 			 */
1991 			flag_success_on_conn(con);
1992 			wake_up(&clt_path->state_wq);
1993 			return 0;
1994 		}
1995 		break;
1996 	case RDMA_CM_EVENT_REJECTED:
1997 		cm_err = rtrs_rdma_conn_rejected(con, ev);
1998 		break;
1999 	case RDMA_CM_EVENT_DISCONNECTED:
2000 		/* No message for disconnecting */
2001 		cm_err = -ECONNRESET;
2002 		break;
2003 	case RDMA_CM_EVENT_CONNECT_ERROR:
2004 	case RDMA_CM_EVENT_UNREACHABLE:
2005 	case RDMA_CM_EVENT_ADDR_CHANGE:
2006 	case RDMA_CM_EVENT_TIMEWAIT_EXIT:
2007 		rtrs_wrn(s, "CM error (CM event: %s, err: %d)\n",
2008 			 rdma_event_msg(ev->event), ev->status);
2009 		cm_err = -ECONNRESET;
2010 		break;
2011 	case RDMA_CM_EVENT_ADDR_ERROR:
2012 	case RDMA_CM_EVENT_ROUTE_ERROR:
2013 		rtrs_wrn(s, "CM error (CM event: %s, err: %d)\n",
2014 			 rdma_event_msg(ev->event), ev->status);
2015 		cm_err = -EHOSTUNREACH;
2016 		break;
2017 	case RDMA_CM_EVENT_DEVICE_REMOVAL:
2018 		/*
2019 		 * Device removal is a special case.  Queue close and return 0.
2020 		 */
2021 		rtrs_clt_close_conns(clt_path, false);
2022 		return 0;
2023 	default:
2024 		rtrs_err(s, "Unexpected RDMA CM error (CM event: %s, err: %d)\n",
2025 			 rdma_event_msg(ev->event), ev->status);
2026 		cm_err = -ECONNRESET;
2027 		break;
2028 	}
2029 
2030 	if (cm_err) {
2031 		/*
2032 		 * cm error makes sense only on connection establishing,
2033 		 * in other cases we rely on normal procedure of reconnecting.
2034 		 */
2035 		flag_error_on_conn(con, cm_err);
2036 		rtrs_rdma_error_recovery(con);
2037 	}
2038 
2039 	return 0;
2040 }
2041 
2042 /* The caller should do the cleanup in case of error */
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 		return err;
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 		return err;
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 		return err;
2088 	}
2089 	if (con->cm_err < 0)
2090 		return con->cm_err;
2091 	if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTING)
2092 		/* Device removal */
2093 		return -ECONNABORTED;
2094 
2095 	return 0;
2096 }
2097 
2098 static void rtrs_clt_path_up(struct rtrs_clt_path *clt_path)
2099 {
2100 	struct rtrs_clt_sess *clt = clt_path->clt;
2101 	int up;
2102 
2103 	/*
2104 	 * We can fire RECONNECTED event only when all paths were
2105 	 * connected on rtrs_clt_open(), then each was disconnected
2106 	 * and the first one connected again.  That's why this nasty
2107 	 * game with counter value.
2108 	 */
2109 
2110 	mutex_lock(&clt->paths_ev_mutex);
2111 	up = ++clt->paths_up;
2112 	/*
2113 	 * Here it is safe to access paths num directly since up counter
2114 	 * is greater than MAX_PATHS_NUM only while rtrs_clt_open() is
2115 	 * in progress, thus paths removals are impossible.
2116 	 */
2117 	if (up > MAX_PATHS_NUM && up == MAX_PATHS_NUM + clt->paths_num)
2118 		clt->paths_up = clt->paths_num;
2119 	else if (up == 1)
2120 		clt->link_ev(clt->priv, RTRS_CLT_LINK_EV_RECONNECTED);
2121 	mutex_unlock(&clt->paths_ev_mutex);
2122 
2123 	/* Mark session as established */
2124 	clt_path->established = true;
2125 	clt_path->reconnect_attempts = 0;
2126 	clt_path->stats->reconnects.successful_cnt++;
2127 }
2128 
2129 static void rtrs_clt_path_down(struct rtrs_clt_path *clt_path)
2130 {
2131 	struct rtrs_clt_sess *clt = clt_path->clt;
2132 
2133 	if (!clt_path->established)
2134 		return;
2135 
2136 	clt_path->established = false;
2137 	mutex_lock(&clt->paths_ev_mutex);
2138 	WARN_ON(!clt->paths_up);
2139 	if (--clt->paths_up == 0)
2140 		clt->link_ev(clt->priv, RTRS_CLT_LINK_EV_DISCONNECTED);
2141 	mutex_unlock(&clt->paths_ev_mutex);
2142 }
2143 
2144 static void rtrs_clt_stop_and_destroy_conns(struct rtrs_clt_path *clt_path)
2145 {
2146 	struct rtrs_clt_con *con;
2147 	unsigned int cid;
2148 
2149 	WARN_ON(READ_ONCE(clt_path->state) == RTRS_CLT_CONNECTED);
2150 
2151 	/*
2152 	 * Possible race with rtrs_clt_open(), when DEVICE_REMOVAL comes
2153 	 * exactly in between.  Start destroying after it finishes.
2154 	 */
2155 	mutex_lock(&clt_path->init_mutex);
2156 	mutex_unlock(&clt_path->init_mutex);
2157 
2158 	/*
2159 	 * All IO paths must observe !CONNECTED state before we
2160 	 * free everything.
2161 	 */
2162 	synchronize_rcu();
2163 
2164 	rtrs_stop_hb(&clt_path->s);
2165 
2166 	/*
2167 	 * The order it utterly crucial: firstly disconnect and complete all
2168 	 * rdma requests with error (thus set in_use=false for requests),
2169 	 * then fail outstanding requests checking in_use for each, and
2170 	 * eventually notify upper layer about session disconnection.
2171 	 */
2172 
2173 	for (cid = 0; cid < clt_path->s.con_num; cid++) {
2174 		if (!clt_path->s.con[cid])
2175 			break;
2176 		con = to_clt_con(clt_path->s.con[cid]);
2177 		stop_cm(con);
2178 	}
2179 	fail_all_outstanding_reqs(clt_path);
2180 	free_path_reqs(clt_path);
2181 	rtrs_clt_path_down(clt_path);
2182 
2183 	/*
2184 	 * Wait for graceful shutdown, namely when peer side invokes
2185 	 * rdma_disconnect(). 'connected_cnt' is decremented only on
2186 	 * CM events, thus if other side had crashed and hb has detected
2187 	 * something is wrong, here we will stuck for exactly timeout ms,
2188 	 * since CM does not fire anything.  That is fine, we are not in
2189 	 * hurry.
2190 	 */
2191 	wait_event_timeout(clt_path->state_wq,
2192 			   !atomic_read(&clt_path->connected_cnt),
2193 			   msecs_to_jiffies(RTRS_CONNECT_TIMEOUT_MS));
2194 
2195 	for (cid = 0; cid < clt_path->s.con_num; cid++) {
2196 		if (!clt_path->s.con[cid])
2197 			break;
2198 		con = to_clt_con(clt_path->s.con[cid]);
2199 		mutex_lock(&con->con_mutex);
2200 		destroy_con_cq_qp(con);
2201 		mutex_unlock(&con->con_mutex);
2202 		destroy_cm(con);
2203 		destroy_con(con);
2204 	}
2205 }
2206 
2207 static void rtrs_clt_remove_path_from_arr(struct rtrs_clt_path *clt_path)
2208 {
2209 	struct rtrs_clt_sess *clt = clt_path->clt;
2210 	struct rtrs_clt_path *next;
2211 	bool wait_for_grace = false;
2212 	int cpu;
2213 
2214 	mutex_lock(&clt->paths_mutex);
2215 	list_del_rcu(&clt_path->s.entry);
2216 
2217 	/* Make sure everybody observes path removal. */
2218 	synchronize_rcu();
2219 
2220 	/*
2221 	 * At this point nobody sees @sess in the list, but still we have
2222 	 * dangling pointer @pcpu_path which _can_ point to @sess.  Since
2223 	 * nobody can observe @sess in the list, we guarantee that IO path
2224 	 * will not assign @sess to @pcpu_path, i.e. @pcpu_path can be equal
2225 	 * to @sess, but can never again become @sess.
2226 	 */
2227 
2228 	/*
2229 	 * Decrement paths number only after grace period, because
2230 	 * caller of do_each_path() must firstly observe list without
2231 	 * path and only then decremented paths number.
2232 	 *
2233 	 * Otherwise there can be the following situation:
2234 	 *    o Two paths exist and IO is coming.
2235 	 *    o One path is removed:
2236 	 *      CPU#0                          CPU#1
2237 	 *      do_each_path():                rtrs_clt_remove_path_from_arr():
2238 	 *          path = get_next_path()
2239 	 *          ^^^                            list_del_rcu(path)
2240 	 *          [!CONNECTED path]              clt->paths_num--
2241 	 *                                              ^^^^^^^^^
2242 	 *          load clt->paths_num                 from 2 to 1
2243 	 *                    ^^^^^^^^^
2244 	 *                    sees 1
2245 	 *
2246 	 *      path is observed as !CONNECTED, but do_each_path() loop
2247 	 *      ends, because expression i < clt->paths_num is false.
2248 	 */
2249 	clt->paths_num--;
2250 
2251 	/*
2252 	 * Get @next connection from current @sess which is going to be
2253 	 * removed.  If @sess is the last element, then @next is NULL.
2254 	 */
2255 	rcu_read_lock();
2256 	next = rtrs_clt_get_next_path_or_null(&clt->paths_list, clt_path);
2257 	rcu_read_unlock();
2258 
2259 	/*
2260 	 * @pcpu paths can still point to the path which is going to be
2261 	 * removed, so change the pointer manually.
2262 	 */
2263 	for_each_possible_cpu(cpu) {
2264 		struct rtrs_clt_path __rcu **ppcpu_path;
2265 
2266 		ppcpu_path = per_cpu_ptr(clt->pcpu_path, cpu);
2267 		if (rcu_dereference_protected(*ppcpu_path,
2268 			lockdep_is_held(&clt->paths_mutex)) != clt_path)
2269 			/*
2270 			 * synchronize_rcu() was called just after deleting
2271 			 * entry from the list, thus IO code path cannot
2272 			 * change pointer back to the pointer which is going
2273 			 * to be removed, we are safe here.
2274 			 */
2275 			continue;
2276 
2277 		/*
2278 		 * We race with IO code path, which also changes pointer,
2279 		 * thus we have to be careful not to overwrite it.
2280 		 */
2281 		if (try_cmpxchg((struct rtrs_clt_path **)ppcpu_path, &clt_path,
2282 				next))
2283 			/*
2284 			 * @ppcpu_path was successfully replaced with @next,
2285 			 * that means that someone could also pick up the
2286 			 * @sess and dereferencing it right now, so wait for
2287 			 * a grace period is required.
2288 			 */
2289 			wait_for_grace = true;
2290 	}
2291 	if (wait_for_grace)
2292 		synchronize_rcu();
2293 
2294 	mutex_unlock(&clt->paths_mutex);
2295 }
2296 
2297 static void rtrs_clt_add_path_to_arr(struct rtrs_clt_path *clt_path)
2298 {
2299 	struct rtrs_clt_sess *clt = clt_path->clt;
2300 
2301 	mutex_lock(&clt->paths_mutex);
2302 	clt->paths_num++;
2303 
2304 	list_add_tail_rcu(&clt_path->s.entry, &clt->paths_list);
2305 	mutex_unlock(&clt->paths_mutex);
2306 }
2307 
2308 static void rtrs_clt_close_work(struct work_struct *work)
2309 {
2310 	struct rtrs_clt_path *clt_path;
2311 
2312 	clt_path = container_of(work, struct rtrs_clt_path, close_work);
2313 
2314 	cancel_work_sync(&clt_path->err_recovery_work);
2315 	cancel_delayed_work_sync(&clt_path->reconnect_dwork);
2316 	rtrs_clt_stop_and_destroy_conns(clt_path);
2317 	rtrs_clt_change_state_get_old(clt_path, RTRS_CLT_CLOSED, NULL);
2318 }
2319 
2320 static int init_conns(struct rtrs_clt_path *clt_path)
2321 {
2322 	unsigned int cid;
2323 	int err, i;
2324 
2325 	/*
2326 	 * On every new session connections increase reconnect counter
2327 	 * to avoid clashes with previous sessions not yet closed
2328 	 * sessions on a server side.
2329 	 */
2330 	clt_path->s.recon_cnt++;
2331 
2332 	/* Establish all RDMA connections  */
2333 	for (cid = 0; cid < clt_path->s.con_num; cid++) {
2334 		err = create_con(clt_path, cid);
2335 		if (err)
2336 			goto destroy;
2337 
2338 		err = create_cm(to_clt_con(clt_path->s.con[cid]));
2339 		if (err)
2340 			goto destroy;
2341 	}
2342 	err = alloc_path_reqs(clt_path);
2343 	if (err)
2344 		goto destroy;
2345 
2346 	rtrs_start_hb(&clt_path->s);
2347 
2348 	return 0;
2349 
2350 destroy:
2351 	/* Make sure we do the cleanup in the order they are created */
2352 	for (i = 0; i <= cid; i++) {
2353 		struct rtrs_clt_con *con;
2354 
2355 		if (!clt_path->s.con[i])
2356 			break;
2357 
2358 		con = to_clt_con(clt_path->s.con[i]);
2359 		if (con->c.cm_id) {
2360 			stop_cm(con);
2361 			mutex_lock(&con->con_mutex);
2362 			destroy_con_cq_qp(con);
2363 			mutex_unlock(&con->con_mutex);
2364 			destroy_cm(con);
2365 		}
2366 		destroy_con(con);
2367 	}
2368 	/*
2369 	 * If we've never taken async path and got an error, say,
2370 	 * doing rdma_resolve_addr(), switch to CONNECTION_ERR state
2371 	 * manually to keep reconnecting.
2372 	 */
2373 	rtrs_clt_change_state_get_old(clt_path, RTRS_CLT_CONNECTING_ERR, NULL);
2374 
2375 	return err;
2376 }
2377 
2378 static void rtrs_clt_info_req_done(struct ib_cq *cq, struct ib_wc *wc)
2379 {
2380 	struct rtrs_clt_con *con = to_clt_con(wc->qp->qp_context);
2381 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
2382 	struct rtrs_iu *iu;
2383 
2384 	iu = container_of(wc->wr_cqe, struct rtrs_iu, cqe);
2385 	rtrs_iu_free(iu, clt_path->s.dev->ib_dev, 1);
2386 
2387 	if (wc->status != IB_WC_SUCCESS) {
2388 		rtrs_err(clt_path->clt, "Path info request send failed: %s\n",
2389 			  ib_wc_status_msg(wc->status));
2390 		rtrs_clt_change_state_get_old(clt_path, RTRS_CLT_CONNECTING_ERR, NULL);
2391 		return;
2392 	}
2393 
2394 	rtrs_clt_update_wc_stats(con);
2395 }
2396 
2397 static int process_info_rsp(struct rtrs_clt_path *clt_path,
2398 			    const struct rtrs_msg_info_rsp *msg)
2399 {
2400 	unsigned int sg_cnt, total_len;
2401 	int i, sgi;
2402 
2403 	sg_cnt = le16_to_cpu(msg->sg_cnt);
2404 	if (!sg_cnt || (clt_path->queue_depth % sg_cnt)) {
2405 		rtrs_err(clt_path->clt,
2406 			  "Incorrect sg_cnt %d, is not multiple\n",
2407 			  sg_cnt);
2408 		return -EINVAL;
2409 	}
2410 
2411 	/*
2412 	 * Check if IB immediate data size is enough to hold the mem_id and
2413 	 * the offset inside the memory chunk.
2414 	 */
2415 	if ((ilog2(sg_cnt - 1) + 1) + (ilog2(clt_path->chunk_size - 1) + 1) >
2416 	    MAX_IMM_PAYL_BITS) {
2417 		rtrs_err(clt_path->clt,
2418 			  "RDMA immediate size (%db) not enough to encode %d buffers of size %dB\n",
2419 			  MAX_IMM_PAYL_BITS, sg_cnt, clt_path->chunk_size);
2420 		return -EINVAL;
2421 	}
2422 	total_len = 0;
2423 	for (sgi = 0, i = 0; sgi < sg_cnt && i < clt_path->queue_depth; sgi++) {
2424 		const struct rtrs_sg_desc *desc = &msg->desc[sgi];
2425 		u32 len, rkey;
2426 		u64 addr;
2427 
2428 		addr = le64_to_cpu(desc->addr);
2429 		rkey = le32_to_cpu(desc->key);
2430 		len  = le32_to_cpu(desc->len);
2431 
2432 		total_len += len;
2433 
2434 		if (!len || (len % clt_path->chunk_size)) {
2435 			rtrs_err(clt_path->clt, "Incorrect [%d].len %d\n",
2436 				  sgi,
2437 				  len);
2438 			return -EINVAL;
2439 		}
2440 		for ( ; len && i < clt_path->queue_depth; i++) {
2441 			clt_path->rbufs[i].addr = addr;
2442 			clt_path->rbufs[i].rkey = rkey;
2443 
2444 			len  -= clt_path->chunk_size;
2445 			addr += clt_path->chunk_size;
2446 		}
2447 	}
2448 	/* Sanity check */
2449 	if (sgi != sg_cnt || i != clt_path->queue_depth) {
2450 		rtrs_err(clt_path->clt,
2451 			 "Incorrect sg vector, not fully mapped\n");
2452 		return -EINVAL;
2453 	}
2454 	if (total_len != clt_path->chunk_size * clt_path->queue_depth) {
2455 		rtrs_err(clt_path->clt, "Incorrect total_len %d\n", total_len);
2456 		return -EINVAL;
2457 	}
2458 
2459 	return 0;
2460 }
2461 
2462 static void rtrs_clt_info_rsp_done(struct ib_cq *cq, struct ib_wc *wc)
2463 {
2464 	struct rtrs_clt_con *con = to_clt_con(wc->qp->qp_context);
2465 	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
2466 	struct rtrs_msg_info_rsp *msg;
2467 	enum rtrs_clt_state state;
2468 	struct rtrs_iu *iu;
2469 	size_t rx_sz;
2470 	int err;
2471 
2472 	state = RTRS_CLT_CONNECTING_ERR;
2473 
2474 	WARN_ON(con->c.cid);
2475 	iu = container_of(wc->wr_cqe, struct rtrs_iu, cqe);
2476 	if (wc->status != IB_WC_SUCCESS) {
2477 		rtrs_err(clt_path->clt, "Path info response recv failed: %s\n",
2478 			  ib_wc_status_msg(wc->status));
2479 		goto out;
2480 	}
2481 	WARN_ON(wc->opcode != IB_WC_RECV);
2482 
2483 	if (wc->byte_len < sizeof(*msg)) {
2484 		rtrs_err(clt_path->clt, "Path info response is malformed: size %d\n",
2485 			  wc->byte_len);
2486 		goto out;
2487 	}
2488 	ib_dma_sync_single_for_cpu(clt_path->s.dev->ib_dev, iu->dma_addr,
2489 				   iu->size, DMA_FROM_DEVICE);
2490 	msg = iu->buf;
2491 	if (le16_to_cpu(msg->type) != RTRS_MSG_INFO_RSP) {
2492 		rtrs_err(clt_path->clt, "Path info response is malformed: type %d\n",
2493 			  le16_to_cpu(msg->type));
2494 		goto out;
2495 	}
2496 	rx_sz  = sizeof(*msg);
2497 	rx_sz += sizeof(msg->desc[0]) * le16_to_cpu(msg->sg_cnt);
2498 	if (wc->byte_len < rx_sz) {
2499 		rtrs_err(clt_path->clt, "Path info response is malformed: size %d\n",
2500 			  wc->byte_len);
2501 		goto out;
2502 	}
2503 	err = process_info_rsp(clt_path, msg);
2504 	if (err)
2505 		goto out;
2506 
2507 	err = post_recv_path(clt_path);
2508 	if (err)
2509 		goto out;
2510 
2511 	state = RTRS_CLT_CONNECTED;
2512 
2513 out:
2514 	rtrs_clt_update_wc_stats(con);
2515 	rtrs_iu_free(iu, clt_path->s.dev->ib_dev, 1);
2516 	rtrs_clt_change_state_get_old(clt_path, state, NULL);
2517 }
2518 
2519 static int rtrs_send_path_info(struct rtrs_clt_path *clt_path)
2520 {
2521 	struct rtrs_clt_con *usr_con = to_clt_con(clt_path->s.con[0]);
2522 	struct rtrs_msg_info_req *msg;
2523 	struct rtrs_iu *tx_iu, *rx_iu;
2524 	size_t rx_sz;
2525 	int err;
2526 
2527 	rx_sz  = sizeof(struct rtrs_msg_info_rsp);
2528 	rx_sz += sizeof(struct rtrs_sg_desc) * clt_path->queue_depth;
2529 
2530 	tx_iu = rtrs_iu_alloc(1, sizeof(struct rtrs_msg_info_req), GFP_KERNEL,
2531 			       clt_path->s.dev->ib_dev, DMA_TO_DEVICE,
2532 			       rtrs_clt_info_req_done);
2533 	rx_iu = rtrs_iu_alloc(1, rx_sz, GFP_KERNEL, clt_path->s.dev->ib_dev,
2534 			       DMA_FROM_DEVICE, rtrs_clt_info_rsp_done);
2535 	if (!tx_iu || !rx_iu) {
2536 		err = -ENOMEM;
2537 		goto out;
2538 	}
2539 	/* Prepare for getting info response */
2540 	err = rtrs_iu_post_recv(&usr_con->c, rx_iu);
2541 	if (err) {
2542 		rtrs_err(clt_path->clt, "rtrs_iu_post_recv(), err: %d\n", err);
2543 		goto out;
2544 	}
2545 	rx_iu = NULL;
2546 
2547 	msg = tx_iu->buf;
2548 	msg->type = cpu_to_le16(RTRS_MSG_INFO_REQ);
2549 	memcpy(msg->pathname, clt_path->s.sessname, sizeof(msg->pathname));
2550 
2551 	ib_dma_sync_single_for_device(clt_path->s.dev->ib_dev,
2552 				      tx_iu->dma_addr,
2553 				      tx_iu->size, DMA_TO_DEVICE);
2554 
2555 	/* Send info request */
2556 	err = rtrs_iu_post_send(&usr_con->c, tx_iu, sizeof(*msg), NULL);
2557 	if (err) {
2558 		rtrs_err(clt_path->clt, "rtrs_iu_post_send(), err: %d\n", err);
2559 		goto out;
2560 	}
2561 	tx_iu = NULL;
2562 
2563 	/* Wait for state change */
2564 	wait_event_interruptible_timeout(clt_path->state_wq,
2565 					 clt_path->state != RTRS_CLT_CONNECTING,
2566 					 msecs_to_jiffies(
2567 						 RTRS_CONNECT_TIMEOUT_MS));
2568 	if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTED) {
2569 		if (READ_ONCE(clt_path->state) == RTRS_CLT_CONNECTING_ERR)
2570 			err = -ECONNRESET;
2571 		else
2572 			err = -ETIMEDOUT;
2573 	}
2574 
2575 out:
2576 	if (tx_iu)
2577 		rtrs_iu_free(tx_iu, clt_path->s.dev->ib_dev, 1);
2578 	if (rx_iu)
2579 		rtrs_iu_free(rx_iu, clt_path->s.dev->ib_dev, 1);
2580 	if (err)
2581 		/* If we've never taken async path because of malloc problems */
2582 		rtrs_clt_change_state_get_old(clt_path,
2583 					      RTRS_CLT_CONNECTING_ERR, NULL);
2584 
2585 	return err;
2586 }
2587 
2588 /**
2589  * init_path() - establishes all path connections and does handshake
2590  * @clt_path: client path.
2591  * In case of error full close or reconnect procedure should be taken,
2592  * because reconnect or close async works can be started.
2593  */
2594 static int init_path(struct rtrs_clt_path *clt_path)
2595 {
2596 	int err;
2597 	char str[NAME_MAX];
2598 	struct rtrs_addr path = {
2599 		.src = &clt_path->s.src_addr,
2600 		.dst = &clt_path->s.dst_addr,
2601 	};
2602 
2603 	rtrs_addr_to_str(&path, str, sizeof(str));
2604 
2605 	mutex_lock(&clt_path->init_mutex);
2606 	err = init_conns(clt_path);
2607 	if (err) {
2608 		rtrs_err(clt_path->clt,
2609 			 "init_conns() failed: err=%d path=%s [%s:%u]\n", err,
2610 			 str, clt_path->hca_name, clt_path->hca_port);
2611 		goto out;
2612 	}
2613 	err = rtrs_send_path_info(clt_path);
2614 	if (err) {
2615 		rtrs_err(clt_path->clt,
2616 			 "rtrs_send_path_info() failed: err=%d path=%s [%s:%u]\n",
2617 			 err, str, clt_path->hca_name, clt_path->hca_port);
2618 		goto out;
2619 	}
2620 	rtrs_clt_path_up(clt_path);
2621 out:
2622 	mutex_unlock(&clt_path->init_mutex);
2623 
2624 	return err;
2625 }
2626 
2627 static void rtrs_clt_reconnect_work(struct work_struct *work)
2628 {
2629 	struct rtrs_clt_path *clt_path;
2630 	struct rtrs_clt_sess *clt;
2631 	int err;
2632 
2633 	clt_path = container_of(to_delayed_work(work), struct rtrs_clt_path,
2634 				reconnect_dwork);
2635 	clt = clt_path->clt;
2636 
2637 	trace_rtrs_clt_reconnect_work(clt_path);
2638 
2639 	if (READ_ONCE(clt_path->state) != RTRS_CLT_RECONNECTING)
2640 		return;
2641 
2642 	if (clt_path->reconnect_attempts >= clt->max_reconnect_attempts) {
2643 		/* Close a path completely if max attempts is reached */
2644 		rtrs_clt_close_conns(clt_path, false);
2645 		return;
2646 	}
2647 	clt_path->reconnect_attempts++;
2648 
2649 	msleep(RTRS_RECONNECT_BACKOFF);
2650 	if (rtrs_clt_change_state_get_old(clt_path, RTRS_CLT_CONNECTING, NULL)) {
2651 		err = init_path(clt_path);
2652 		if (err)
2653 			goto reconnect_again;
2654 	}
2655 
2656 	return;
2657 
2658 reconnect_again:
2659 	if (rtrs_clt_change_state_get_old(clt_path, RTRS_CLT_RECONNECTING, NULL)) {
2660 		clt_path->stats->reconnects.fail_cnt++;
2661 		queue_work(rtrs_wq, &clt_path->err_recovery_work);
2662 	}
2663 }
2664 
2665 static void rtrs_clt_dev_release(struct device *dev)
2666 {
2667 	struct rtrs_clt_sess *clt = container_of(dev, struct rtrs_clt_sess,
2668 						 dev);
2669 
2670 	mutex_destroy(&clt->paths_ev_mutex);
2671 	mutex_destroy(&clt->paths_mutex);
2672 	kfree(clt);
2673 }
2674 
2675 static struct rtrs_clt_sess *alloc_clt(const char *sessname, size_t paths_num,
2676 				  u16 port, size_t pdu_sz, void *priv,
2677 				  void	(*link_ev)(void *priv,
2678 						   enum rtrs_clt_link_ev ev),
2679 				  unsigned int reconnect_delay_sec,
2680 				  unsigned int max_reconnect_attempts)
2681 {
2682 	struct rtrs_clt_sess *clt;
2683 	int err;
2684 
2685 	if (!paths_num || paths_num > MAX_PATHS_NUM)
2686 		return ERR_PTR(-EINVAL);
2687 
2688 	if (strlen(sessname) >= sizeof(clt->sessname))
2689 		return ERR_PTR(-EINVAL);
2690 
2691 	clt = kzalloc(sizeof(*clt), GFP_KERNEL);
2692 	if (!clt)
2693 		return ERR_PTR(-ENOMEM);
2694 
2695 	clt->pcpu_path = alloc_percpu(typeof(*clt->pcpu_path));
2696 	if (!clt->pcpu_path) {
2697 		kfree(clt);
2698 		return ERR_PTR(-ENOMEM);
2699 	}
2700 
2701 	clt->dev.class = rtrs_clt_dev_class;
2702 	clt->dev.release = rtrs_clt_dev_release;
2703 	uuid_gen(&clt->paths_uuid);
2704 	INIT_LIST_HEAD_RCU(&clt->paths_list);
2705 	clt->paths_num = paths_num;
2706 	clt->paths_up = MAX_PATHS_NUM;
2707 	clt->port = port;
2708 	clt->pdu_sz = pdu_sz;
2709 	clt->max_segments = RTRS_MAX_SEGMENTS;
2710 	clt->reconnect_delay_sec = reconnect_delay_sec;
2711 	clt->max_reconnect_attempts = max_reconnect_attempts;
2712 	clt->priv = priv;
2713 	clt->link_ev = link_ev;
2714 	clt->mp_policy = MP_POLICY_MIN_INFLIGHT;
2715 	strscpy(clt->sessname, sessname, sizeof(clt->sessname));
2716 	init_waitqueue_head(&clt->permits_wait);
2717 	mutex_init(&clt->paths_ev_mutex);
2718 	mutex_init(&clt->paths_mutex);
2719 	device_initialize(&clt->dev);
2720 
2721 	err = dev_set_name(&clt->dev, "%s", sessname);
2722 	if (err)
2723 		goto err_put;
2724 
2725 	/*
2726 	 * Suppress user space notification until
2727 	 * sysfs files are created
2728 	 */
2729 	dev_set_uevent_suppress(&clt->dev, true);
2730 	err = device_add(&clt->dev);
2731 	if (err)
2732 		goto err_put;
2733 
2734 	clt->kobj_paths = kobject_create_and_add("paths", &clt->dev.kobj);
2735 	if (!clt->kobj_paths) {
2736 		err = -ENOMEM;
2737 		goto err_del;
2738 	}
2739 	err = rtrs_clt_create_sysfs_root_files(clt);
2740 	if (err) {
2741 		kobject_del(clt->kobj_paths);
2742 		kobject_put(clt->kobj_paths);
2743 		goto err_del;
2744 	}
2745 	dev_set_uevent_suppress(&clt->dev, false);
2746 	kobject_uevent(&clt->dev.kobj, KOBJ_ADD);
2747 
2748 	return clt;
2749 err_del:
2750 	device_del(&clt->dev);
2751 err_put:
2752 	free_percpu(clt->pcpu_path);
2753 	put_device(&clt->dev);
2754 	return ERR_PTR(err);
2755 }
2756 
2757 static void free_clt(struct rtrs_clt_sess *clt)
2758 {
2759 	free_percpu(clt->pcpu_path);
2760 
2761 	/*
2762 	 * release callback will free clt and destroy mutexes in last put
2763 	 */
2764 	device_unregister(&clt->dev);
2765 }
2766 
2767 /**
2768  * rtrs_clt_open() - Open a path to an RTRS server
2769  * @ops: holds the link event callback and the private pointer.
2770  * @pathname: name of the path to an RTRS server
2771  * @paths: Paths to be established defined by their src and dst addresses
2772  * @paths_num: Number of elements in the @paths array
2773  * @port: port to be used by the RTRS session
2774  * @pdu_sz: Size of extra payload which can be accessed after permit allocation.
2775  * @reconnect_delay_sec: time between reconnect tries
2776  * @max_reconnect_attempts: Number of times to reconnect on error before giving
2777  *			    up, 0 for * disabled, -1 for forever
2778  * @nr_poll_queues: number of polling mode connection using IB_POLL_DIRECT flag
2779  *
2780  * Starts session establishment with the rtrs_server. The function can block
2781  * up to ~2000ms before it returns.
2782  *
2783  * Return a valid pointer on success otherwise PTR_ERR.
2784  */
2785 struct rtrs_clt_sess *rtrs_clt_open(struct rtrs_clt_ops *ops,
2786 				 const char *pathname,
2787 				 const struct rtrs_addr *paths,
2788 				 size_t paths_num, u16 port,
2789 				 size_t pdu_sz, u8 reconnect_delay_sec,
2790 				 s16 max_reconnect_attempts, u32 nr_poll_queues)
2791 {
2792 	struct rtrs_clt_path *clt_path, *tmp;
2793 	struct rtrs_clt_sess *clt;
2794 	int err, i;
2795 
2796 	if (strchr(pathname, '/') || strchr(pathname, '.')) {
2797 		pr_err("pathname cannot contain / and .\n");
2798 		err = -EINVAL;
2799 		goto out;
2800 	}
2801 
2802 	clt = alloc_clt(pathname, paths_num, port, pdu_sz, ops->priv,
2803 			ops->link_ev,
2804 			reconnect_delay_sec,
2805 			max_reconnect_attempts);
2806 	if (IS_ERR(clt)) {
2807 		err = PTR_ERR(clt);
2808 		goto out;
2809 	}
2810 	for (i = 0; i < paths_num; i++) {
2811 		struct rtrs_clt_path *clt_path;
2812 
2813 		clt_path = alloc_path(clt, &paths[i], nr_cpu_ids,
2814 				  nr_poll_queues);
2815 		if (IS_ERR(clt_path)) {
2816 			err = PTR_ERR(clt_path);
2817 			goto close_all_path;
2818 		}
2819 		if (!i)
2820 			clt_path->for_new_clt = 1;
2821 		list_add_tail_rcu(&clt_path->s.entry, &clt->paths_list);
2822 
2823 		err = init_path(clt_path);
2824 		if (err) {
2825 			list_del_rcu(&clt_path->s.entry);
2826 			rtrs_clt_close_conns(clt_path, true);
2827 			free_percpu(clt_path->stats->pcpu_stats);
2828 			kfree(clt_path->stats);
2829 			free_path(clt_path);
2830 			goto close_all_path;
2831 		}
2832 
2833 		err = rtrs_clt_create_path_files(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 = alloc_permits(clt);
2844 	if (err)
2845 		goto close_all_path;
2846 
2847 	return clt;
2848 
2849 close_all_path:
2850 	list_for_each_entry_safe(clt_path, tmp, &clt->paths_list, s.entry) {
2851 		rtrs_clt_destroy_path_files(clt_path, NULL);
2852 		rtrs_clt_close_conns(clt_path, true);
2853 		kobject_put(&clt_path->kobj);
2854 	}
2855 	rtrs_clt_destroy_sysfs_root(clt);
2856 	free_clt(clt);
2857 
2858 out:
2859 	return ERR_PTR(err);
2860 }
2861 EXPORT_SYMBOL(rtrs_clt_open);
2862 
2863 /**
2864  * rtrs_clt_close() - Close a path
2865  * @clt: Session handle. Session is freed upon return.
2866  */
2867 void rtrs_clt_close(struct rtrs_clt_sess *clt)
2868 {
2869 	struct rtrs_clt_path *clt_path, *tmp;
2870 
2871 	/* Firstly forbid sysfs access */
2872 	rtrs_clt_destroy_sysfs_root(clt);
2873 
2874 	/* Now it is safe to iterate over all paths without locks */
2875 	list_for_each_entry_safe(clt_path, tmp, &clt->paths_list, s.entry) {
2876 		rtrs_clt_close_conns(clt_path, true);
2877 		rtrs_clt_destroy_path_files(clt_path, NULL);
2878 		kobject_put(&clt_path->kobj);
2879 	}
2880 	free_permits(clt);
2881 	free_clt(clt);
2882 }
2883 EXPORT_SYMBOL(rtrs_clt_close);
2884 
2885 int rtrs_clt_reconnect_from_sysfs(struct rtrs_clt_path *clt_path)
2886 {
2887 	enum rtrs_clt_state old_state;
2888 	int err = -EBUSY;
2889 	bool changed;
2890 
2891 	changed = rtrs_clt_change_state_get_old(clt_path,
2892 						 RTRS_CLT_RECONNECTING,
2893 						 &old_state);
2894 	if (changed) {
2895 		clt_path->reconnect_attempts = 0;
2896 		rtrs_clt_stop_and_destroy_conns(clt_path);
2897 		queue_delayed_work(rtrs_wq, &clt_path->reconnect_dwork, 0);
2898 	}
2899 	if (changed || old_state == RTRS_CLT_RECONNECTING) {
2900 		/*
2901 		 * flush_delayed_work() queues pending work for immediate
2902 		 * execution, so do the flush if we have queued something
2903 		 * right now or work is pending.
2904 		 */
2905 		flush_delayed_work(&clt_path->reconnect_dwork);
2906 		err = (READ_ONCE(clt_path->state) ==
2907 		       RTRS_CLT_CONNECTED ? 0 : -ENOTCONN);
2908 	}
2909 
2910 	return err;
2911 }
2912 
2913 int rtrs_clt_remove_path_from_sysfs(struct rtrs_clt_path *clt_path,
2914 				     const struct attribute *sysfs_self)
2915 {
2916 	enum rtrs_clt_state old_state;
2917 	bool changed;
2918 
2919 	/*
2920 	 * Continue stopping path till state was changed to DEAD or
2921 	 * state was observed as DEAD:
2922 	 * 1. State was changed to DEAD - we were fast and nobody
2923 	 *    invoked rtrs_clt_reconnect(), which can again start
2924 	 *    reconnecting.
2925 	 * 2. State was observed as DEAD - we have someone in parallel
2926 	 *    removing the path.
2927 	 */
2928 	do {
2929 		rtrs_clt_close_conns(clt_path, true);
2930 		changed = rtrs_clt_change_state_get_old(clt_path,
2931 							RTRS_CLT_DEAD,
2932 							&old_state);
2933 	} while (!changed && old_state != RTRS_CLT_DEAD);
2934 
2935 	if (changed) {
2936 		rtrs_clt_remove_path_from_arr(clt_path);
2937 		rtrs_clt_destroy_path_files(clt_path, sysfs_self);
2938 		kobject_put(&clt_path->kobj);
2939 	}
2940 
2941 	return 0;
2942 }
2943 
2944 void rtrs_clt_set_max_reconnect_attempts(struct rtrs_clt_sess *clt, int value)
2945 {
2946 	clt->max_reconnect_attempts = (unsigned int)value;
2947 }
2948 
2949 int rtrs_clt_get_max_reconnect_attempts(const struct rtrs_clt_sess *clt)
2950 {
2951 	return (int)clt->max_reconnect_attempts;
2952 }
2953 
2954 /**
2955  * rtrs_clt_request() - Request data transfer to/from server via RDMA.
2956  *
2957  * @dir:	READ/WRITE
2958  * @ops:	callback function to be called as confirmation, and the pointer.
2959  * @clt:	Session
2960  * @permit:	Preallocated permit
2961  * @vec:	Message that is sent to server together with the request.
2962  *		Sum of len of all @vec elements limited to <= IO_MSG_SIZE.
2963  *		Since the msg is copied internally it can be allocated on stack.
2964  * @nr:		Number of elements in @vec.
2965  * @data_len:	length of data sent to/from server
2966  * @sg:		Pages to be sent/received to/from server.
2967  * @sg_cnt:	Number of elements in the @sg
2968  *
2969  * Return:
2970  * 0:		Success
2971  * <0:		Error
2972  *
2973  * On dir=READ rtrs client will request a data transfer from Server to client.
2974  * The data that the server will respond with will be stored in @sg when
2975  * the user receives an %RTRS_CLT_RDMA_EV_RDMA_REQUEST_WRITE_COMPL event.
2976  * On dir=WRITE rtrs client will rdma write data in sg to server side.
2977  */
2978 int rtrs_clt_request(int dir, struct rtrs_clt_req_ops *ops,
2979 		     struct rtrs_clt_sess *clt, struct rtrs_permit *permit,
2980 		     const struct kvec *vec, size_t nr, size_t data_len,
2981 		     struct scatterlist *sg, unsigned int sg_cnt)
2982 {
2983 	struct rtrs_clt_io_req *req;
2984 	struct rtrs_clt_path *clt_path;
2985 
2986 	enum dma_data_direction dma_dir;
2987 	int err = -ECONNABORTED, i;
2988 	size_t usr_len, hdr_len;
2989 	struct path_it it;
2990 
2991 	/* Get kvec length */
2992 	for (i = 0, usr_len = 0; i < nr; i++)
2993 		usr_len += vec[i].iov_len;
2994 
2995 	if (dir == READ) {
2996 		hdr_len = sizeof(struct rtrs_msg_rdma_read) +
2997 			  sg_cnt * sizeof(struct rtrs_sg_desc);
2998 		dma_dir = DMA_FROM_DEVICE;
2999 	} else {
3000 		hdr_len = sizeof(struct rtrs_msg_rdma_write);
3001 		dma_dir = DMA_TO_DEVICE;
3002 	}
3003 
3004 	rcu_read_lock();
3005 	for (path_it_init(&it, clt);
3006 	     (clt_path = it.next_path(&it)) && it.i < it.clt->paths_num; it.i++) {
3007 		if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTED)
3008 			continue;
3009 
3010 		if (usr_len + hdr_len > clt_path->max_hdr_size) {
3011 			rtrs_wrn_rl(clt_path->clt,
3012 				     "%s request failed, user message size is %zu and header length %zu, but max size is %u\n",
3013 				     dir == READ ? "Read" : "Write",
3014 				     usr_len, hdr_len, clt_path->max_hdr_size);
3015 			err = -EMSGSIZE;
3016 			break;
3017 		}
3018 		req = rtrs_clt_get_req(clt_path, ops->conf_fn, permit, ops->priv,
3019 				       vec, usr_len, sg, sg_cnt, data_len,
3020 				       dma_dir);
3021 		if (dir == READ)
3022 			err = rtrs_clt_read_req(req);
3023 		else
3024 			err = rtrs_clt_write_req(req);
3025 		if (err) {
3026 			req->in_use = false;
3027 			continue;
3028 		}
3029 		/* Success path */
3030 		break;
3031 	}
3032 	path_it_deinit(&it);
3033 	rcu_read_unlock();
3034 
3035 	return err;
3036 }
3037 EXPORT_SYMBOL(rtrs_clt_request);
3038 
3039 int rtrs_clt_rdma_cq_direct(struct rtrs_clt_sess *clt, unsigned int index)
3040 {
3041 	/* If no path, return -1 for block layer not to try again */
3042 	int cnt = -1;
3043 	struct rtrs_con *con;
3044 	struct rtrs_clt_path *clt_path;
3045 	struct path_it it;
3046 
3047 	rcu_read_lock();
3048 	for (path_it_init(&it, clt);
3049 	     (clt_path = it.next_path(&it)) && it.i < it.clt->paths_num; it.i++) {
3050 		if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTED)
3051 			continue;
3052 
3053 		con = clt_path->s.con[index + 1];
3054 		cnt = ib_process_cq_direct(con->cq, -1);
3055 		if (cnt)
3056 			break;
3057 	}
3058 	path_it_deinit(&it);
3059 	rcu_read_unlock();
3060 
3061 	return cnt;
3062 }
3063 EXPORT_SYMBOL(rtrs_clt_rdma_cq_direct);
3064 
3065 /**
3066  * rtrs_clt_query() - queries RTRS session attributes
3067  *@clt: session pointer
3068  *@attr: query results for session attributes.
3069  * Returns:
3070  *    0 on success
3071  *    -ECOMM		no connection to the server
3072  */
3073 int rtrs_clt_query(struct rtrs_clt_sess *clt, struct rtrs_attrs *attr)
3074 {
3075 	if (!rtrs_clt_is_connected(clt))
3076 		return -ECOMM;
3077 
3078 	attr->queue_depth      = clt->queue_depth;
3079 	attr->max_segments     = clt->max_segments;
3080 	/* Cap max_io_size to min of remote buffer size and the fr pages */
3081 	attr->max_io_size = min_t(int, clt->max_io_size,
3082 				  clt->max_segments * SZ_4K);
3083 
3084 	return 0;
3085 }
3086 EXPORT_SYMBOL(rtrs_clt_query);
3087 
3088 int rtrs_clt_create_path_from_sysfs(struct rtrs_clt_sess *clt,
3089 				     struct rtrs_addr *addr)
3090 {
3091 	struct rtrs_clt_path *clt_path;
3092 	int err;
3093 
3094 	clt_path = alloc_path(clt, addr, nr_cpu_ids, 0);
3095 	if (IS_ERR(clt_path))
3096 		return PTR_ERR(clt_path);
3097 
3098 	mutex_lock(&clt->paths_mutex);
3099 	if (clt->paths_num == 0) {
3100 		/*
3101 		 * When all the paths are removed for a session,
3102 		 * the addition of the first path is like a new session for
3103 		 * the storage server
3104 		 */
3105 		clt_path->for_new_clt = 1;
3106 	}
3107 
3108 	mutex_unlock(&clt->paths_mutex);
3109 
3110 	/*
3111 	 * It is totally safe to add path in CONNECTING state: coming
3112 	 * IO will never grab it.  Also it is very important to add
3113 	 * path before init, since init fires LINK_CONNECTED event.
3114 	 */
3115 	rtrs_clt_add_path_to_arr(clt_path);
3116 
3117 	err = init_path(clt_path);
3118 	if (err)
3119 		goto close_path;
3120 
3121 	err = rtrs_clt_create_path_files(clt_path);
3122 	if (err)
3123 		goto close_path;
3124 
3125 	return 0;
3126 
3127 close_path:
3128 	rtrs_clt_remove_path_from_arr(clt_path);
3129 	rtrs_clt_close_conns(clt_path, true);
3130 	free_percpu(clt_path->stats->pcpu_stats);
3131 	kfree(clt_path->stats);
3132 	free_path(clt_path);
3133 
3134 	return err;
3135 }
3136 
3137 static int rtrs_clt_ib_dev_init(struct rtrs_ib_dev *dev)
3138 {
3139 	if (!(dev->ib_dev->attrs.device_cap_flags &
3140 	      IB_DEVICE_MEM_MGT_EXTENSIONS)) {
3141 		pr_err("Memory registrations not supported.\n");
3142 		return -ENOTSUPP;
3143 	}
3144 
3145 	return 0;
3146 }
3147 
3148 static const struct rtrs_rdma_dev_pd_ops dev_pd_ops = {
3149 	.init = rtrs_clt_ib_dev_init
3150 };
3151 
3152 static int __init rtrs_client_init(void)
3153 {
3154 	rtrs_rdma_dev_pd_init(0, &dev_pd);
3155 
3156 	rtrs_clt_dev_class = class_create("rtrs-client");
3157 	if (IS_ERR(rtrs_clt_dev_class)) {
3158 		pr_err("Failed to create rtrs-client dev class\n");
3159 		return PTR_ERR(rtrs_clt_dev_class);
3160 	}
3161 	rtrs_wq = alloc_workqueue("rtrs_client_wq", 0, 0);
3162 	if (!rtrs_wq) {
3163 		class_destroy(rtrs_clt_dev_class);
3164 		return -ENOMEM;
3165 	}
3166 
3167 	return 0;
3168 }
3169 
3170 static void __exit rtrs_client_exit(void)
3171 {
3172 	destroy_workqueue(rtrs_wq);
3173 	class_destroy(rtrs_clt_dev_class);
3174 	rtrs_rdma_dev_pd_deinit(&dev_pd);
3175 }
3176 
3177 module_init(rtrs_client_init);
3178 module_exit(rtrs_client_exit);
3179