1 /*
2  * Copyright (c) 2004, 2005, 2006 Voltaire, Inc. All rights reserved.
3  * Copyright (c) 2005, 2006 Cisco Systems.  All rights reserved.
4  * Copyright (c) 2013-2014 Mellanox Technologies. All rights reserved.
5  *
6  * This software is available to you under a choice of one of two
7  * licenses.  You may choose to be licensed under the terms of the GNU
8  * General Public License (GPL) Version 2, available from the file
9  * COPYING in the main directory of this source tree, or the
10  * OpenIB.org BSD license below:
11  *
12  *     Redistribution and use in source and binary forms, with or
13  *     without modification, are permitted provided that the following
14  *     conditions are met:
15  *
16  *	- Redistributions of source code must retain the above
17  *	  copyright notice, this list of conditions and the following
18  *	  disclaimer.
19  *
20  *	- Redistributions in binary form must reproduce the above
21  *	  copyright notice, this list of conditions and the following
22  *	  disclaimer in the documentation and/or other materials
23  *	  provided with the distribution.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
29  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
30  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
31  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32  * SOFTWARE.
33  */
34 #include <linux/kernel.h>
35 #include <linux/slab.h>
36 #include <linux/delay.h>
37 
38 #include "iscsi_iser.h"
39 
40 #define ISCSI_ISER_MAX_CONN	8
41 #define ISER_MAX_RX_LEN		(ISER_QP_MAX_RECV_DTOS * ISCSI_ISER_MAX_CONN)
42 #define ISER_MAX_TX_LEN		(ISER_QP_MAX_REQ_DTOS  * ISCSI_ISER_MAX_CONN)
43 #define ISER_MAX_CQ_LEN		(ISER_MAX_RX_LEN + ISER_MAX_TX_LEN + \
44 				 ISCSI_ISER_MAX_CONN)
45 
46 static void iser_qp_event_callback(struct ib_event *cause, void *context)
47 {
48 	iser_err("qp event %s (%d)\n",
49 		 ib_event_msg(cause->event), cause->event);
50 }
51 
52 static void iser_event_handler(struct ib_event_handler *handler,
53 				struct ib_event *event)
54 {
55 	iser_err("async event %s (%d) on device %s port %d\n",
56 		 ib_event_msg(event->event), event->event,
57 		dev_name(&event->device->dev), event->element.port_num);
58 }
59 
60 /*
61  * iser_create_device_ib_res - creates Protection Domain (PD), Completion
62  * Queue (CQ), DMA Memory Region (DMA MR) with the device associated with
63  * the adaptor.
64  *
65  * Return: 0 on success, -1 on failure
66  */
67 static int iser_create_device_ib_res(struct iser_device *device)
68 {
69 	struct ib_device *ib_dev = device->ib_device;
70 
71 	if (!(ib_dev->attrs.device_cap_flags & IB_DEVICE_MEM_MGT_EXTENSIONS)) {
72 		iser_err("IB device does not support memory registrations\n");
73 		return -1;
74 	}
75 
76 	device->pd = ib_alloc_pd(ib_dev,
77 		iser_always_reg ? 0 : IB_PD_UNSAFE_GLOBAL_RKEY);
78 	if (IS_ERR(device->pd))
79 		goto pd_err;
80 
81 	INIT_IB_EVENT_HANDLER(&device->event_handler, ib_dev,
82 			      iser_event_handler);
83 	ib_register_event_handler(&device->event_handler);
84 	return 0;
85 
86 pd_err:
87 	iser_err("failed to allocate an IB resource\n");
88 	return -1;
89 }
90 
91 /*
92  * iser_free_device_ib_res - destroy/dealloc/dereg the DMA MR,
93  * CQ and PD created with the device associated with the adaptor.
94  */
95 static void iser_free_device_ib_res(struct iser_device *device)
96 {
97 	ib_unregister_event_handler(&device->event_handler);
98 	ib_dealloc_pd(device->pd);
99 
100 	device->pd = NULL;
101 }
102 
103 static struct iser_fr_desc *
104 iser_create_fastreg_desc(struct iser_device *device,
105 			 struct ib_pd *pd,
106 			 bool pi_enable,
107 			 unsigned int size)
108 {
109 	struct iser_fr_desc *desc;
110 	struct ib_device *ib_dev = device->ib_device;
111 	enum ib_mr_type mr_type;
112 	int ret;
113 
114 	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
115 	if (!desc)
116 		return ERR_PTR(-ENOMEM);
117 
118 	if (ib_dev->attrs.kernel_cap_flags & IBK_SG_GAPS_REG)
119 		mr_type = IB_MR_TYPE_SG_GAPS;
120 	else
121 		mr_type = IB_MR_TYPE_MEM_REG;
122 
123 	desc->rsc.mr = ib_alloc_mr(pd, mr_type, size);
124 	if (IS_ERR(desc->rsc.mr)) {
125 		ret = PTR_ERR(desc->rsc.mr);
126 		iser_err("Failed to allocate ib_fast_reg_mr err=%d\n", ret);
127 		goto err_alloc_mr;
128 	}
129 
130 	if (pi_enable) {
131 		desc->rsc.sig_mr = ib_alloc_mr_integrity(pd, size, size);
132 		if (IS_ERR(desc->rsc.sig_mr)) {
133 			ret = PTR_ERR(desc->rsc.sig_mr);
134 			iser_err("Failed to allocate sig_mr err=%d\n", ret);
135 			goto err_alloc_mr_integrity;
136 		}
137 	}
138 	desc->rsc.mr_valid = 0;
139 
140 	return desc;
141 
142 err_alloc_mr_integrity:
143 	ib_dereg_mr(desc->rsc.mr);
144 err_alloc_mr:
145 	kfree(desc);
146 
147 	return ERR_PTR(ret);
148 }
149 
150 static void iser_destroy_fastreg_desc(struct iser_fr_desc *desc)
151 {
152 	struct iser_reg_resources *res = &desc->rsc;
153 
154 	ib_dereg_mr(res->mr);
155 	if (res->sig_mr) {
156 		ib_dereg_mr(res->sig_mr);
157 		res->sig_mr = NULL;
158 	}
159 	kfree(desc);
160 }
161 
162 /**
163  * iser_alloc_fastreg_pool - Creates pool of fast_reg descriptors
164  * for fast registration work requests.
165  * @ib_conn: connection RDMA resources
166  * @cmds_max: max number of SCSI commands for this connection
167  * @size: max number of pages per map request
168  *
169  * Return: 0 on success, or errno code on failure
170  */
171 int iser_alloc_fastreg_pool(struct ib_conn *ib_conn,
172 			    unsigned cmds_max,
173 			    unsigned int size)
174 {
175 	struct iser_device *device = ib_conn->device;
176 	struct iser_fr_pool *fr_pool = &ib_conn->fr_pool;
177 	struct iser_fr_desc *desc;
178 	int i, ret;
179 
180 	INIT_LIST_HEAD(&fr_pool->list);
181 	INIT_LIST_HEAD(&fr_pool->all_list);
182 	spin_lock_init(&fr_pool->lock);
183 	fr_pool->size = 0;
184 	for (i = 0; i < cmds_max; i++) {
185 		desc = iser_create_fastreg_desc(device, device->pd,
186 						ib_conn->pi_support, size);
187 		if (IS_ERR(desc)) {
188 			ret = PTR_ERR(desc);
189 			goto err;
190 		}
191 
192 		list_add_tail(&desc->list, &fr_pool->list);
193 		list_add_tail(&desc->all_list, &fr_pool->all_list);
194 		fr_pool->size++;
195 	}
196 
197 	return 0;
198 
199 err:
200 	iser_free_fastreg_pool(ib_conn);
201 	return ret;
202 }
203 
204 /**
205  * iser_free_fastreg_pool - releases the pool of fast_reg descriptors
206  * @ib_conn: connection RDMA resources
207  */
208 void iser_free_fastreg_pool(struct ib_conn *ib_conn)
209 {
210 	struct iser_fr_pool *fr_pool = &ib_conn->fr_pool;
211 	struct iser_fr_desc *desc, *tmp;
212 	int i = 0;
213 
214 	if (list_empty(&fr_pool->all_list))
215 		return;
216 
217 	iser_info("freeing conn %p fr pool\n", ib_conn);
218 
219 	list_for_each_entry_safe(desc, tmp, &fr_pool->all_list, all_list) {
220 		list_del(&desc->all_list);
221 		iser_destroy_fastreg_desc(desc);
222 		++i;
223 	}
224 
225 	if (i < fr_pool->size)
226 		iser_warn("pool still has %d regions registered\n",
227 			  fr_pool->size - i);
228 }
229 
230 /*
231  * iser_create_ib_conn_res - Queue-Pair (QP)
232  *
233  * Return: 0 on success, -1 on failure
234  */
235 static int iser_create_ib_conn_res(struct ib_conn *ib_conn)
236 {
237 	struct iser_conn *iser_conn = to_iser_conn(ib_conn);
238 	struct iser_device	*device;
239 	struct ib_device	*ib_dev;
240 	struct ib_qp_init_attr	init_attr;
241 	int			ret = -ENOMEM;
242 	unsigned int max_send_wr, cq_size;
243 
244 	BUG_ON(ib_conn->device == NULL);
245 
246 	device = ib_conn->device;
247 	ib_dev = device->ib_device;
248 
249 	if (ib_conn->pi_support)
250 		max_send_wr = ISER_QP_SIG_MAX_REQ_DTOS + 1;
251 	else
252 		max_send_wr = ISER_QP_MAX_REQ_DTOS + 1;
253 	max_send_wr = min_t(unsigned int, max_send_wr,
254 			    (unsigned int)ib_dev->attrs.max_qp_wr);
255 
256 	cq_size = max_send_wr + ISER_QP_MAX_RECV_DTOS;
257 	ib_conn->cq = ib_cq_pool_get(ib_dev, cq_size, -1, IB_POLL_SOFTIRQ);
258 	if (IS_ERR(ib_conn->cq)) {
259 		ret = PTR_ERR(ib_conn->cq);
260 		goto cq_err;
261 	}
262 	ib_conn->cq_size = cq_size;
263 
264 	memset(&init_attr, 0, sizeof(init_attr));
265 
266 	init_attr.event_handler = iser_qp_event_callback;
267 	init_attr.qp_context = (void *)ib_conn;
268 	init_attr.send_cq = ib_conn->cq;
269 	init_attr.recv_cq = ib_conn->cq;
270 	init_attr.cap.max_recv_wr = ISER_QP_MAX_RECV_DTOS;
271 	init_attr.cap.max_send_sge = 2;
272 	init_attr.cap.max_recv_sge = 1;
273 	init_attr.sq_sig_type = IB_SIGNAL_REQ_WR;
274 	init_attr.qp_type = IB_QPT_RC;
275 	init_attr.cap.max_send_wr = max_send_wr;
276 	if (ib_conn->pi_support)
277 		init_attr.create_flags |= IB_QP_CREATE_INTEGRITY_EN;
278 	iser_conn->max_cmds = ISER_GET_MAX_XMIT_CMDS(max_send_wr - 1);
279 
280 	ret = rdma_create_qp(ib_conn->cma_id, device->pd, &init_attr);
281 	if (ret)
282 		goto out_err;
283 
284 	ib_conn->qp = ib_conn->cma_id->qp;
285 	iser_info("setting conn %p cma_id %p qp %p max_send_wr %d\n", ib_conn,
286 		  ib_conn->cma_id, ib_conn->cma_id->qp, max_send_wr);
287 	return ret;
288 
289 out_err:
290 	ib_cq_pool_put(ib_conn->cq, ib_conn->cq_size);
291 cq_err:
292 	iser_err("unable to alloc mem or create resource, err %d\n", ret);
293 
294 	return ret;
295 }
296 
297 /*
298  * based on the resolved device node GUID see if there already allocated
299  * device for this device. If there's no such, create one.
300  */
301 static
302 struct iser_device *iser_device_find_by_ib_device(struct rdma_cm_id *cma_id)
303 {
304 	struct iser_device *device;
305 
306 	mutex_lock(&ig.device_list_mutex);
307 
308 	list_for_each_entry(device, &ig.device_list, ig_list)
309 		/* find if there's a match using the node GUID */
310 		if (device->ib_device->node_guid == cma_id->device->node_guid)
311 			goto inc_refcnt;
312 
313 	device = kzalloc(sizeof *device, GFP_KERNEL);
314 	if (!device)
315 		goto out;
316 
317 	/* assign this device to the device */
318 	device->ib_device = cma_id->device;
319 	/* init the device and link it into ig device list */
320 	if (iser_create_device_ib_res(device)) {
321 		kfree(device);
322 		device = NULL;
323 		goto out;
324 	}
325 	list_add(&device->ig_list, &ig.device_list);
326 
327 inc_refcnt:
328 	device->refcount++;
329 out:
330 	mutex_unlock(&ig.device_list_mutex);
331 	return device;
332 }
333 
334 /* if there's no demand for this device, release it */
335 static void iser_device_try_release(struct iser_device *device)
336 {
337 	mutex_lock(&ig.device_list_mutex);
338 	device->refcount--;
339 	iser_info("device %p refcount %d\n", device, device->refcount);
340 	if (!device->refcount) {
341 		iser_free_device_ib_res(device);
342 		list_del(&device->ig_list);
343 		kfree(device);
344 	}
345 	mutex_unlock(&ig.device_list_mutex);
346 }
347 
348 /*
349  * Called with state mutex held
350  */
351 static int iser_conn_state_comp_exch(struct iser_conn *iser_conn,
352 				     enum iser_conn_state comp,
353 				     enum iser_conn_state exch)
354 {
355 	int ret;
356 
357 	ret = (iser_conn->state == comp);
358 	if (ret)
359 		iser_conn->state = exch;
360 
361 	return ret;
362 }
363 
364 void iser_release_work(struct work_struct *work)
365 {
366 	struct iser_conn *iser_conn;
367 
368 	iser_conn = container_of(work, struct iser_conn, release_work);
369 
370 	/* Wait for conn_stop to complete */
371 	wait_for_completion(&iser_conn->stop_completion);
372 	/* Wait for IB resouces cleanup to complete */
373 	wait_for_completion(&iser_conn->ib_completion);
374 
375 	mutex_lock(&iser_conn->state_mutex);
376 	iser_conn->state = ISER_CONN_DOWN;
377 	mutex_unlock(&iser_conn->state_mutex);
378 
379 	iser_conn_release(iser_conn);
380 }
381 
382 /**
383  * iser_free_ib_conn_res - release IB related resources
384  * @iser_conn: iser connection struct
385  * @destroy: indicator if we need to try to release the
386  *     iser device and memory regoins pool (only iscsi
387  *     shutdown and DEVICE_REMOVAL will use this).
388  *
389  * This routine is called with the iser state mutex held
390  * so the cm_id removal is out of here. It is Safe to
391  * be invoked multiple times.
392  */
393 static void iser_free_ib_conn_res(struct iser_conn *iser_conn, bool destroy)
394 {
395 	struct ib_conn *ib_conn = &iser_conn->ib_conn;
396 	struct iser_device *device = ib_conn->device;
397 
398 	iser_info("freeing conn %p cma_id %p qp %p\n",
399 		  iser_conn, ib_conn->cma_id, ib_conn->qp);
400 
401 	if (ib_conn->qp) {
402 		rdma_destroy_qp(ib_conn->cma_id);
403 		ib_cq_pool_put(ib_conn->cq, ib_conn->cq_size);
404 		ib_conn->qp = NULL;
405 	}
406 
407 	if (destroy) {
408 		if (iser_conn->rx_descs)
409 			iser_free_rx_descriptors(iser_conn);
410 
411 		if (device) {
412 			iser_device_try_release(device);
413 			ib_conn->device = NULL;
414 		}
415 	}
416 }
417 
418 /**
419  * iser_conn_release - Frees all conn objects and deallocs conn descriptor
420  * @iser_conn: iSER connection context
421  */
422 void iser_conn_release(struct iser_conn *iser_conn)
423 {
424 	struct ib_conn *ib_conn = &iser_conn->ib_conn;
425 
426 	mutex_lock(&ig.connlist_mutex);
427 	list_del(&iser_conn->conn_list);
428 	mutex_unlock(&ig.connlist_mutex);
429 
430 	mutex_lock(&iser_conn->state_mutex);
431 	/* In case we endup here without ep_disconnect being invoked. */
432 	if (iser_conn->state != ISER_CONN_DOWN) {
433 		iser_warn("iser conn %p state %d, expected state down.\n",
434 			  iser_conn, iser_conn->state);
435 		iscsi_destroy_endpoint(iser_conn->ep);
436 		iser_conn->state = ISER_CONN_DOWN;
437 	}
438 	/*
439 	 * In case we never got to bind stage, we still need to
440 	 * release IB resources (which is safe to call more than once).
441 	 */
442 	iser_free_ib_conn_res(iser_conn, true);
443 	mutex_unlock(&iser_conn->state_mutex);
444 
445 	if (ib_conn->cma_id) {
446 		rdma_destroy_id(ib_conn->cma_id);
447 		ib_conn->cma_id = NULL;
448 	}
449 
450 	kfree(iser_conn);
451 }
452 
453 /**
454  * iser_conn_terminate - triggers start of the disconnect procedures and
455  * waits for them to be done
456  * @iser_conn: iSER connection context
457  *
458  * Called with state mutex held
459  */
460 int iser_conn_terminate(struct iser_conn *iser_conn)
461 {
462 	struct ib_conn *ib_conn = &iser_conn->ib_conn;
463 	int err = 0;
464 
465 	/* terminate the iser conn only if the conn state is UP */
466 	if (!iser_conn_state_comp_exch(iser_conn, ISER_CONN_UP,
467 				       ISER_CONN_TERMINATING))
468 		return 0;
469 
470 	iser_info("iser_conn %p state %d\n", iser_conn, iser_conn->state);
471 
472 	/* suspend queuing of new iscsi commands */
473 	if (iser_conn->iscsi_conn)
474 		iscsi_suspend_queue(iser_conn->iscsi_conn);
475 
476 	/*
477 	 * In case we didn't already clean up the cma_id (peer initiated
478 	 * a disconnection), we need to Cause the CMA to change the QP
479 	 * state to ERROR.
480 	 */
481 	if (ib_conn->cma_id) {
482 		err = rdma_disconnect(ib_conn->cma_id);
483 		if (err)
484 			iser_err("Failed to disconnect, conn: 0x%p err %d\n",
485 				 iser_conn, err);
486 
487 		/* block until all flush errors are consumed */
488 		ib_drain_sq(ib_conn->qp);
489 	}
490 
491 	return 1;
492 }
493 
494 /*
495  * Called with state mutex held
496  */
497 static void iser_connect_error(struct rdma_cm_id *cma_id)
498 {
499 	struct iser_conn *iser_conn;
500 
501 	iser_conn = cma_id->context;
502 	iser_conn->state = ISER_CONN_TERMINATING;
503 }
504 
505 static void iser_calc_scsi_params(struct iser_conn *iser_conn,
506 				  unsigned int max_sectors)
507 {
508 	struct iser_device *device = iser_conn->ib_conn.device;
509 	struct ib_device_attr *attr = &device->ib_device->attrs;
510 	unsigned short sg_tablesize, sup_sg_tablesize;
511 	unsigned short reserved_mr_pages;
512 	u32 max_num_sg;
513 
514 	/*
515 	 * FRs without SG_GAPS can only map up to a (device) page per entry,
516 	 * but if the first entry is misaligned we'll end up using two entries
517 	 * (head and tail) for a single page worth data, so one additional
518 	 * entry is required.
519 	 */
520 	if (attr->kernel_cap_flags & IBK_SG_GAPS_REG)
521 		reserved_mr_pages = 0;
522 	else
523 		reserved_mr_pages = 1;
524 
525 	if (iser_conn->ib_conn.pi_support)
526 		max_num_sg = attr->max_pi_fast_reg_page_list_len;
527 	else
528 		max_num_sg = attr->max_fast_reg_page_list_len;
529 
530 	sg_tablesize = DIV_ROUND_UP(max_sectors * SECTOR_SIZE, SZ_4K);
531 	sup_sg_tablesize = min_t(uint, ISCSI_ISER_MAX_SG_TABLESIZE,
532 				 max_num_sg - reserved_mr_pages);
533 	iser_conn->scsi_sg_tablesize = min(sg_tablesize, sup_sg_tablesize);
534 	iser_conn->pages_per_mr =
535 		iser_conn->scsi_sg_tablesize + reserved_mr_pages;
536 }
537 
538 /*
539  * Called with state mutex held
540  */
541 static void iser_addr_handler(struct rdma_cm_id *cma_id)
542 {
543 	struct iser_device *device;
544 	struct iser_conn *iser_conn;
545 	struct ib_conn *ib_conn;
546 	int    ret;
547 
548 	iser_conn = cma_id->context;
549 	if (iser_conn->state != ISER_CONN_PENDING)
550 		/* bailout */
551 		return;
552 
553 	ib_conn = &iser_conn->ib_conn;
554 	device = iser_device_find_by_ib_device(cma_id);
555 	if (!device) {
556 		iser_err("device lookup/creation failed\n");
557 		iser_connect_error(cma_id);
558 		return;
559 	}
560 
561 	ib_conn->device = device;
562 
563 	/* connection T10-PI support */
564 	if (iser_pi_enable) {
565 		if (!(device->ib_device->attrs.kernel_cap_flags &
566 		      IBK_INTEGRITY_HANDOVER)) {
567 			iser_warn("T10-PI requested but not supported on %s, "
568 				  "continue without T10-PI\n",
569 				  dev_name(&ib_conn->device->ib_device->dev));
570 			ib_conn->pi_support = false;
571 		} else {
572 			ib_conn->pi_support = true;
573 		}
574 	}
575 
576 	iser_calc_scsi_params(iser_conn, iser_max_sectors);
577 
578 	ret = rdma_resolve_route(cma_id, 1000);
579 	if (ret) {
580 		iser_err("resolve route failed: %d\n", ret);
581 		iser_connect_error(cma_id);
582 		return;
583 	}
584 }
585 
586 /*
587  * Called with state mutex held
588  */
589 static void iser_route_handler(struct rdma_cm_id *cma_id)
590 {
591 	struct rdma_conn_param conn_param;
592 	int ret;
593 	struct iser_cm_hdr req_hdr;
594 	struct iser_conn *iser_conn = cma_id->context;
595 	struct ib_conn *ib_conn = &iser_conn->ib_conn;
596 	struct ib_device *ib_dev = ib_conn->device->ib_device;
597 
598 	if (iser_conn->state != ISER_CONN_PENDING)
599 		/* bailout */
600 		return;
601 
602 	ret = iser_create_ib_conn_res(ib_conn);
603 	if (ret)
604 		goto failure;
605 
606 	memset(&conn_param, 0, sizeof conn_param);
607 	conn_param.responder_resources = ib_dev->attrs.max_qp_rd_atom;
608 	conn_param.initiator_depth = 1;
609 	conn_param.retry_count = 7;
610 	conn_param.rnr_retry_count = 6;
611 
612 	memset(&req_hdr, 0, sizeof(req_hdr));
613 	req_hdr.flags = ISER_ZBVA_NOT_SUP;
614 	if (!iser_always_reg)
615 		req_hdr.flags |= ISER_SEND_W_INV_NOT_SUP;
616 	conn_param.private_data	= (void *)&req_hdr;
617 	conn_param.private_data_len = sizeof(struct iser_cm_hdr);
618 
619 	ret = rdma_connect_locked(cma_id, &conn_param);
620 	if (ret) {
621 		iser_err("failure connecting: %d\n", ret);
622 		goto failure;
623 	}
624 
625 	return;
626 failure:
627 	iser_connect_error(cma_id);
628 }
629 
630 static void iser_connected_handler(struct rdma_cm_id *cma_id,
631 				   const void *private_data)
632 {
633 	struct iser_conn *iser_conn;
634 	struct ib_qp_attr attr;
635 	struct ib_qp_init_attr init_attr;
636 
637 	iser_conn = cma_id->context;
638 	if (iser_conn->state != ISER_CONN_PENDING)
639 		/* bailout */
640 		return;
641 
642 	(void)ib_query_qp(cma_id->qp, &attr, ~0, &init_attr);
643 	iser_info("remote qpn:%x my qpn:%x\n", attr.dest_qp_num, cma_id->qp->qp_num);
644 
645 	if (private_data) {
646 		u8 flags = *(u8 *)private_data;
647 
648 		iser_conn->snd_w_inv = !(flags & ISER_SEND_W_INV_NOT_SUP);
649 	}
650 
651 	iser_info("conn %p: negotiated %s invalidation\n",
652 		  iser_conn, iser_conn->snd_w_inv ? "remote" : "local");
653 
654 	iser_conn->state = ISER_CONN_UP;
655 	complete(&iser_conn->up_completion);
656 }
657 
658 static void iser_disconnected_handler(struct rdma_cm_id *cma_id)
659 {
660 	struct iser_conn *iser_conn = cma_id->context;
661 
662 	if (iser_conn_terminate(iser_conn)) {
663 		if (iser_conn->iscsi_conn)
664 			iscsi_conn_failure(iser_conn->iscsi_conn,
665 					   ISCSI_ERR_CONN_FAILED);
666 		else
667 			iser_err("iscsi_iser connection isn't bound\n");
668 	}
669 }
670 
671 static void iser_cleanup_handler(struct rdma_cm_id *cma_id,
672 				 bool destroy)
673 {
674 	struct iser_conn *iser_conn = cma_id->context;
675 
676 	/*
677 	 * We are not guaranteed that we visited disconnected_handler
678 	 * by now, call it here to be safe that we handle CM drep
679 	 * and flush errors.
680 	 */
681 	iser_disconnected_handler(cma_id);
682 	iser_free_ib_conn_res(iser_conn, destroy);
683 	complete(&iser_conn->ib_completion);
684 }
685 
686 static int iser_cma_handler(struct rdma_cm_id *cma_id,
687 			    struct rdma_cm_event *event)
688 {
689 	struct iser_conn *iser_conn;
690 	int ret = 0;
691 
692 	iser_conn = cma_id->context;
693 	iser_info("%s (%d): status %d conn %p id %p\n",
694 		  rdma_event_msg(event->event), event->event,
695 		  event->status, cma_id->context, cma_id);
696 
697 	mutex_lock(&iser_conn->state_mutex);
698 	switch (event->event) {
699 	case RDMA_CM_EVENT_ADDR_RESOLVED:
700 		iser_addr_handler(cma_id);
701 		break;
702 	case RDMA_CM_EVENT_ROUTE_RESOLVED:
703 		iser_route_handler(cma_id);
704 		break;
705 	case RDMA_CM_EVENT_ESTABLISHED:
706 		iser_connected_handler(cma_id, event->param.conn.private_data);
707 		break;
708 	case RDMA_CM_EVENT_REJECTED:
709 		iser_info("Connection rejected: %s\n",
710 			 rdma_reject_msg(cma_id, event->status));
711 		fallthrough;
712 	case RDMA_CM_EVENT_ADDR_ERROR:
713 	case RDMA_CM_EVENT_ROUTE_ERROR:
714 	case RDMA_CM_EVENT_CONNECT_ERROR:
715 	case RDMA_CM_EVENT_UNREACHABLE:
716 		iser_connect_error(cma_id);
717 		break;
718 	case RDMA_CM_EVENT_DISCONNECTED:
719 	case RDMA_CM_EVENT_ADDR_CHANGE:
720 	case RDMA_CM_EVENT_TIMEWAIT_EXIT:
721 		iser_cleanup_handler(cma_id, false);
722 		break;
723 	case RDMA_CM_EVENT_DEVICE_REMOVAL:
724 		/*
725 		 * we *must* destroy the device as we cannot rely
726 		 * on iscsid to be around to initiate error handling.
727 		 * also if we are not in state DOWN implicitly destroy
728 		 * the cma_id.
729 		 */
730 		iser_cleanup_handler(cma_id, true);
731 		if (iser_conn->state != ISER_CONN_DOWN) {
732 			iser_conn->ib_conn.cma_id = NULL;
733 			ret = 1;
734 		}
735 		break;
736 	default:
737 		iser_err("Unexpected RDMA CM event: %s (%d)\n",
738 			 rdma_event_msg(event->event), event->event);
739 		break;
740 	}
741 	mutex_unlock(&iser_conn->state_mutex);
742 
743 	return ret;
744 }
745 
746 void iser_conn_init(struct iser_conn *iser_conn)
747 {
748 	struct ib_conn *ib_conn = &iser_conn->ib_conn;
749 
750 	iser_conn->state = ISER_CONN_INIT;
751 	init_completion(&iser_conn->stop_completion);
752 	init_completion(&iser_conn->ib_completion);
753 	init_completion(&iser_conn->up_completion);
754 	INIT_LIST_HEAD(&iser_conn->conn_list);
755 	mutex_init(&iser_conn->state_mutex);
756 
757 	ib_conn->reg_cqe.done = iser_reg_comp;
758 }
759 
760 /*
761  * starts the process of connecting to the target
762  * sleeps until the connection is established or rejected
763  */
764 int iser_connect(struct iser_conn *iser_conn, struct sockaddr *src_addr,
765 		 struct sockaddr *dst_addr, int non_blocking)
766 {
767 	struct ib_conn *ib_conn = &iser_conn->ib_conn;
768 	int err = 0;
769 
770 	mutex_lock(&iser_conn->state_mutex);
771 
772 	sprintf(iser_conn->name, "%pISp", dst_addr);
773 
774 	iser_info("connecting to: %s\n", iser_conn->name);
775 
776 	/* the device is known only --after-- address resolution */
777 	ib_conn->device = NULL;
778 
779 	iser_conn->state = ISER_CONN_PENDING;
780 
781 	ib_conn->cma_id = rdma_create_id(&init_net, iser_cma_handler,
782 					 iser_conn, RDMA_PS_TCP, IB_QPT_RC);
783 	if (IS_ERR(ib_conn->cma_id)) {
784 		err = PTR_ERR(ib_conn->cma_id);
785 		iser_err("rdma_create_id failed: %d\n", err);
786 		goto id_failure;
787 	}
788 
789 	err = rdma_resolve_addr(ib_conn->cma_id, src_addr, dst_addr, 1000);
790 	if (err) {
791 		iser_err("rdma_resolve_addr failed: %d\n", err);
792 		goto addr_failure;
793 	}
794 
795 	if (!non_blocking) {
796 		wait_for_completion_interruptible(&iser_conn->up_completion);
797 
798 		if (iser_conn->state != ISER_CONN_UP) {
799 			err =  -EIO;
800 			goto connect_failure;
801 		}
802 	}
803 	mutex_unlock(&iser_conn->state_mutex);
804 
805 	mutex_lock(&ig.connlist_mutex);
806 	list_add(&iser_conn->conn_list, &ig.connlist);
807 	mutex_unlock(&ig.connlist_mutex);
808 	return 0;
809 
810 id_failure:
811 	ib_conn->cma_id = NULL;
812 addr_failure:
813 	iser_conn->state = ISER_CONN_DOWN;
814 connect_failure:
815 	mutex_unlock(&iser_conn->state_mutex);
816 	iser_conn_release(iser_conn);
817 	return err;
818 }
819 
820 int iser_post_recvl(struct iser_conn *iser_conn)
821 {
822 	struct ib_conn *ib_conn = &iser_conn->ib_conn;
823 	struct iser_login_desc *desc = &iser_conn->login_desc;
824 	struct ib_recv_wr wr;
825 	int ret;
826 
827 	desc->sge.addr = desc->rsp_dma;
828 	desc->sge.length = ISER_RX_LOGIN_SIZE;
829 	desc->sge.lkey = ib_conn->device->pd->local_dma_lkey;
830 
831 	desc->cqe.done = iser_login_rsp;
832 	wr.wr_cqe = &desc->cqe;
833 	wr.sg_list = &desc->sge;
834 	wr.num_sge = 1;
835 	wr.next = NULL;
836 
837 	ret = ib_post_recv(ib_conn->qp, &wr, NULL);
838 	if (unlikely(ret))
839 		iser_err("ib_post_recv login failed ret=%d\n", ret);
840 
841 	return ret;
842 }
843 
844 int iser_post_recvm(struct iser_conn *iser_conn, struct iser_rx_desc *rx_desc)
845 {
846 	struct ib_conn *ib_conn = &iser_conn->ib_conn;
847 	struct ib_recv_wr wr;
848 	int ret;
849 
850 	rx_desc->cqe.done = iser_task_rsp;
851 	wr.wr_cqe = &rx_desc->cqe;
852 	wr.sg_list = &rx_desc->rx_sg;
853 	wr.num_sge = 1;
854 	wr.next = NULL;
855 
856 	ret = ib_post_recv(ib_conn->qp, &wr, NULL);
857 	if (unlikely(ret))
858 		iser_err("ib_post_recv failed ret=%d\n", ret);
859 
860 	return ret;
861 }
862 
863 
864 /**
865  * iser_post_send - Initiate a Send DTO operation
866  * @ib_conn: connection RDMA resources
867  * @tx_desc: iSER TX descriptor
868  *
869  * Return: 0 on success, -1 on failure
870  */
871 int iser_post_send(struct ib_conn *ib_conn, struct iser_tx_desc *tx_desc)
872 {
873 	struct ib_send_wr *wr = &tx_desc->send_wr;
874 	struct ib_send_wr *first_wr;
875 	int ret;
876 
877 	ib_dma_sync_single_for_device(ib_conn->device->ib_device,
878 				      tx_desc->dma_addr, ISER_HEADERS_LEN,
879 				      DMA_TO_DEVICE);
880 
881 	wr->next = NULL;
882 	wr->wr_cqe = &tx_desc->cqe;
883 	wr->sg_list = tx_desc->tx_sg;
884 	wr->num_sge = tx_desc->num_sge;
885 	wr->opcode = IB_WR_SEND;
886 	wr->send_flags = IB_SEND_SIGNALED;
887 
888 	if (tx_desc->inv_wr.next)
889 		first_wr = &tx_desc->inv_wr;
890 	else if (tx_desc->reg_wr.wr.next)
891 		first_wr = &tx_desc->reg_wr.wr;
892 	else
893 		first_wr = wr;
894 
895 	ret = ib_post_send(ib_conn->qp, first_wr, NULL);
896 	if (unlikely(ret))
897 		iser_err("ib_post_send failed, ret:%d opcode:%d\n",
898 			 ret, wr->opcode);
899 
900 	return ret;
901 }
902 
903 u8 iser_check_task_pi_status(struct iscsi_iser_task *iser_task,
904 			     enum iser_data_dir cmd_dir, sector_t *sector)
905 {
906 	struct iser_mem_reg *reg = &iser_task->rdma_reg[cmd_dir];
907 	struct iser_fr_desc *desc = reg->desc;
908 	unsigned long sector_size = iser_task->sc->device->sector_size;
909 	struct ib_mr_status mr_status;
910 	int ret;
911 
912 	if (desc && desc->sig_protected) {
913 		desc->sig_protected = false;
914 		ret = ib_check_mr_status(desc->rsc.sig_mr,
915 					 IB_MR_CHECK_SIG_STATUS, &mr_status);
916 		if (ret) {
917 			iser_err("ib_check_mr_status failed, ret %d\n", ret);
918 			/* Not a lot we can do, return ambiguous guard error */
919 			*sector = 0;
920 			return 0x1;
921 		}
922 
923 		if (mr_status.fail_status & IB_MR_CHECK_SIG_STATUS) {
924 			sector_t sector_off = mr_status.sig_err.sig_err_offset;
925 
926 			sector_div(sector_off, sector_size + 8);
927 			*sector = scsi_get_sector(iser_task->sc) + sector_off;
928 
929 			iser_err("PI error found type %d at sector %llx "
930 			       "expected %x vs actual %x\n",
931 			       mr_status.sig_err.err_type,
932 			       (unsigned long long)*sector,
933 			       mr_status.sig_err.expected,
934 			       mr_status.sig_err.actual);
935 
936 			switch (mr_status.sig_err.err_type) {
937 			case IB_SIG_BAD_GUARD:
938 				return 0x1;
939 			case IB_SIG_BAD_REFTAG:
940 				return 0x3;
941 			case IB_SIG_BAD_APPTAG:
942 				return 0x2;
943 			}
944 		}
945 	}
946 
947 	return 0;
948 }
949 
950 void iser_err_comp(struct ib_wc *wc, const char *type)
951 {
952 	if (wc->status != IB_WC_WR_FLUSH_ERR) {
953 		struct iser_conn *iser_conn = to_iser_conn(wc->qp->qp_context);
954 
955 		iser_err("%s failure: %s (%d) vend_err %#x\n", type,
956 			 ib_wc_status_msg(wc->status), wc->status,
957 			 wc->vendor_err);
958 
959 		if (iser_conn->iscsi_conn)
960 			iscsi_conn_failure(iser_conn->iscsi_conn,
961 					   ISCSI_ERR_CONN_FAILED);
962 	} else {
963 		iser_dbg("%s failure: %s (%d)\n", type,
964 			 ib_wc_status_msg(wc->status), wc->status);
965 	}
966 }
967