17f43cf354dad859832d9dfabe6db6276e6ab004
[cascardo/linux.git] / drivers / infiniband / ulp / iser / iser_verbs.c
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/module.h>
36 #include <linux/slab.h>
37 #include <linux/delay.h>
38
39 #include "iscsi_iser.h"
40
41 #define ISCSI_ISER_MAX_CONN     8
42 #define ISER_MAX_RX_LEN         (ISER_QP_MAX_RECV_DTOS * ISCSI_ISER_MAX_CONN)
43 #define ISER_MAX_TX_LEN         (ISER_QP_MAX_REQ_DTOS  * ISCSI_ISER_MAX_CONN)
44 #define ISER_MAX_CQ_LEN         (ISER_MAX_RX_LEN + ISER_MAX_TX_LEN + \
45                                  ISCSI_ISER_MAX_CONN)
46
47 static int iser_cq_poll_limit = 512;
48
49 static void iser_cq_tasklet_fn(unsigned long data);
50 static void iser_cq_callback(struct ib_cq *cq, void *cq_context);
51
52 static void iser_cq_event_callback(struct ib_event *cause, void *context)
53 {
54         iser_err("cq event %s (%d)\n",
55                  ib_event_msg(cause->event), cause->event);
56 }
57
58 static void iser_qp_event_callback(struct ib_event *cause, void *context)
59 {
60         iser_err("qp event %s (%d)\n",
61                  ib_event_msg(cause->event), cause->event);
62 }
63
64 static void iser_event_handler(struct ib_event_handler *handler,
65                                 struct ib_event *event)
66 {
67         iser_err("async event %s (%d) on device %s port %d\n",
68                  ib_event_msg(event->event), event->event,
69                  event->device->name, event->element.port_num);
70 }
71
72 /**
73  * iser_create_device_ib_res - creates Protection Domain (PD), Completion
74  * Queue (CQ), DMA Memory Region (DMA MR) with the device associated with
75  * the adapator.
76  *
77  * returns 0 on success, -1 on failure
78  */
79 static int iser_create_device_ib_res(struct iser_device *device)
80 {
81         struct ib_device_attr *dev_attr = &device->dev_attr;
82         int ret, i, max_cqe;
83
84         ret = ib_query_device(device->ib_device, dev_attr);
85         if (ret) {
86                 pr_warn("Query device failed for %s\n", device->ib_device->name);
87                 return ret;
88         }
89
90         ret = iser_assign_reg_ops(device);
91         if (ret)
92                 return ret;
93
94         device->comps_used = min_t(int, num_online_cpus(),
95                                  device->ib_device->num_comp_vectors);
96
97         device->comps = kcalloc(device->comps_used, sizeof(*device->comps),
98                                 GFP_KERNEL);
99         if (!device->comps)
100                 goto comps_err;
101
102         max_cqe = min(ISER_MAX_CQ_LEN, dev_attr->max_cqe);
103
104         iser_info("using %d CQs, device %s supports %d vectors max_cqe %d\n",
105                   device->comps_used, device->ib_device->name,
106                   device->ib_device->num_comp_vectors, max_cqe);
107
108         device->pd = ib_alloc_pd(device->ib_device);
109         if (IS_ERR(device->pd))
110                 goto pd_err;
111
112         for (i = 0; i < device->comps_used; i++) {
113                 struct ib_cq_init_attr cq_attr = {};
114                 struct iser_comp *comp = &device->comps[i];
115
116                 comp->device = device;
117                 cq_attr.cqe = max_cqe;
118                 cq_attr.comp_vector = i;
119                 comp->cq = ib_create_cq(device->ib_device,
120                                         iser_cq_callback,
121                                         iser_cq_event_callback,
122                                         (void *)comp,
123                                         &cq_attr);
124                 if (IS_ERR(comp->cq)) {
125                         comp->cq = NULL;
126                         goto cq_err;
127                 }
128
129                 if (ib_req_notify_cq(comp->cq, IB_CQ_NEXT_COMP))
130                         goto cq_err;
131
132                 tasklet_init(&comp->tasklet, iser_cq_tasklet_fn,
133                              (unsigned long)comp);
134         }
135
136         device->mr = ib_get_dma_mr(device->pd, IB_ACCESS_LOCAL_WRITE |
137                                    IB_ACCESS_REMOTE_WRITE |
138                                    IB_ACCESS_REMOTE_READ);
139         if (IS_ERR(device->mr))
140                 goto dma_mr_err;
141
142         INIT_IB_EVENT_HANDLER(&device->event_handler, device->ib_device,
143                                 iser_event_handler);
144         if (ib_register_event_handler(&device->event_handler))
145                 goto handler_err;
146
147         return 0;
148
149 handler_err:
150         ib_dereg_mr(device->mr);
151 dma_mr_err:
152         for (i = 0; i < device->comps_used; i++)
153                 tasklet_kill(&device->comps[i].tasklet);
154 cq_err:
155         for (i = 0; i < device->comps_used; i++) {
156                 struct iser_comp *comp = &device->comps[i];
157
158                 if (comp->cq)
159                         ib_destroy_cq(comp->cq);
160         }
161         ib_dealloc_pd(device->pd);
162 pd_err:
163         kfree(device->comps);
164 comps_err:
165         iser_err("failed to allocate an IB resource\n");
166         return -1;
167 }
168
169 /**
170  * iser_free_device_ib_res - destroy/dealloc/dereg the DMA MR,
171  * CQ and PD created with the device associated with the adapator.
172  */
173 static void iser_free_device_ib_res(struct iser_device *device)
174 {
175         int i;
176         BUG_ON(device->mr == NULL);
177
178         for (i = 0; i < device->comps_used; i++) {
179                 struct iser_comp *comp = &device->comps[i];
180
181                 tasklet_kill(&comp->tasklet);
182                 ib_destroy_cq(comp->cq);
183                 comp->cq = NULL;
184         }
185
186         (void)ib_unregister_event_handler(&device->event_handler);
187         (void)ib_dereg_mr(device->mr);
188         (void)ib_dealloc_pd(device->pd);
189
190         kfree(device->comps);
191         device->comps = NULL;
192
193         device->mr = NULL;
194         device->pd = NULL;
195 }
196
197 /**
198  * iser_alloc_fmr_pool - Creates FMR pool and page_vector
199  *
200  * returns 0 on success, or errno code on failure
201  */
202 int iser_alloc_fmr_pool(struct ib_conn *ib_conn, unsigned cmds_max)
203 {
204         struct iser_device *device = ib_conn->device;
205         struct ib_fmr_pool_param params;
206         int ret = -ENOMEM;
207
208         ib_conn->fmr.page_vec = kmalloc(sizeof(*ib_conn->fmr.page_vec) +
209                                         (sizeof(u64)*(ISCSI_ISER_SG_TABLESIZE + 1)),
210                                         GFP_KERNEL);
211         if (!ib_conn->fmr.page_vec)
212                 return ret;
213
214         ib_conn->fmr.page_vec->pages = (u64 *)(ib_conn->fmr.page_vec + 1);
215
216         params.page_shift        = SHIFT_4K;
217         /* when the first/last SG element are not start/end *
218          * page aligned, the map whould be of N+1 pages     */
219         params.max_pages_per_fmr = ISCSI_ISER_SG_TABLESIZE + 1;
220         /* make the pool size twice the max number of SCSI commands *
221          * the ML is expected to queue, watermark for unmap at 50%  */
222         params.pool_size         = cmds_max * 2;
223         params.dirty_watermark   = cmds_max;
224         params.cache             = 0;
225         params.flush_function    = NULL;
226         params.access            = (IB_ACCESS_LOCAL_WRITE  |
227                                     IB_ACCESS_REMOTE_WRITE |
228                                     IB_ACCESS_REMOTE_READ);
229
230         ib_conn->fmr.pool = ib_create_fmr_pool(device->pd, &params);
231         if (IS_ERR(ib_conn->fmr.pool)) {
232                 ret = PTR_ERR(ib_conn->fmr.pool);
233                 iser_err("FMR allocation failed, err %d\n", ret);
234                 goto err;
235         }
236
237         return 0;
238
239 err:
240         kfree(ib_conn->fmr.page_vec);
241         ib_conn->fmr.page_vec = NULL;
242         return ret;
243 }
244
245 /**
246  * iser_free_fmr_pool - releases the FMR pool and page vec
247  */
248 void iser_free_fmr_pool(struct ib_conn *ib_conn)
249 {
250         iser_info("freeing conn %p fmr pool %p\n",
251                   ib_conn, ib_conn->fmr.pool);
252
253         ib_destroy_fmr_pool(ib_conn->fmr.pool);
254         ib_conn->fmr.pool = NULL;
255
256         kfree(ib_conn->fmr.page_vec);
257         ib_conn->fmr.page_vec = NULL;
258 }
259
260 static int
261 iser_alloc_reg_res(struct ib_device *ib_device, struct ib_pd *pd,
262                    struct iser_reg_resources *res)
263 {
264         int ret;
265
266         res->frpl = ib_alloc_fast_reg_page_list(ib_device,
267                                                 ISCSI_ISER_SG_TABLESIZE + 1);
268         if (IS_ERR(res->frpl)) {
269                 ret = PTR_ERR(res->frpl);
270                 iser_err("Failed to allocate ib_fast_reg_page_list err=%d\n",
271                          ret);
272                 return PTR_ERR(res->frpl);
273         }
274
275         res->mr = ib_alloc_mr(pd, IB_MR_TYPE_MEM_REG,
276                               ISCSI_ISER_SG_TABLESIZE + 1);
277         if (IS_ERR(res->mr)) {
278                 ret = PTR_ERR(res->mr);
279                 iser_err("Failed to allocate ib_fast_reg_mr err=%d\n", ret);
280                 goto fast_reg_mr_failure;
281         }
282         res->mr_valid = 1;
283
284         return 0;
285
286 fast_reg_mr_failure:
287         ib_free_fast_reg_page_list(res->frpl);
288
289         return ret;
290 }
291
292 static void
293 iser_free_reg_res(struct iser_reg_resources *rsc)
294 {
295         ib_dereg_mr(rsc->mr);
296         ib_free_fast_reg_page_list(rsc->frpl);
297 }
298
299 static int
300 iser_alloc_pi_ctx(struct ib_device *ib_device, struct ib_pd *pd,
301                   struct iser_fr_desc *desc)
302 {
303         struct iser_pi_context *pi_ctx = NULL;
304         int ret;
305
306         desc->pi_ctx = kzalloc(sizeof(*desc->pi_ctx), GFP_KERNEL);
307         if (!desc->pi_ctx)
308                 return -ENOMEM;
309
310         pi_ctx = desc->pi_ctx;
311
312         ret = iser_alloc_reg_res(ib_device, pd, &pi_ctx->rsc);
313         if (ret) {
314                 iser_err("failed to allocate reg_resources\n");
315                 goto alloc_reg_res_err;
316         }
317
318         pi_ctx->sig_mr = ib_alloc_mr(pd, IB_MR_TYPE_SIGNATURE, 2);
319         if (IS_ERR(pi_ctx->sig_mr)) {
320                 ret = PTR_ERR(pi_ctx->sig_mr);
321                 goto sig_mr_failure;
322         }
323         pi_ctx->sig_mr_valid = 1;
324         desc->pi_ctx->sig_protected = 0;
325
326         return 0;
327
328 sig_mr_failure:
329         iser_free_reg_res(&pi_ctx->rsc);
330 alloc_reg_res_err:
331         kfree(desc->pi_ctx);
332
333         return ret;
334 }
335
336 static void
337 iser_free_pi_ctx(struct iser_pi_context *pi_ctx)
338 {
339         iser_free_reg_res(&pi_ctx->rsc);
340         ib_dereg_mr(pi_ctx->sig_mr);
341         kfree(pi_ctx);
342 }
343
344 static int
345 iser_create_fastreg_desc(struct ib_device *ib_device, struct ib_pd *pd,
346                          bool pi_enable, struct iser_fr_desc *desc)
347 {
348         int ret;
349
350         ret = iser_alloc_reg_res(ib_device, pd, &desc->rsc);
351         if (ret) {
352                 iser_err("failed to allocate reg_resources\n");
353                 return ret;
354         }
355
356         if (pi_enable) {
357                 ret = iser_alloc_pi_ctx(ib_device, pd, desc);
358                 if (ret)
359                         goto pi_ctx_alloc_failure;
360         }
361
362         return 0;
363
364 pi_ctx_alloc_failure:
365         iser_free_reg_res(&desc->rsc);
366
367         return ret;
368 }
369
370 /**
371  * iser_alloc_fastreg_pool - Creates pool of fast_reg descriptors
372  * for fast registration work requests.
373  * returns 0 on success, or errno code on failure
374  */
375 int iser_alloc_fastreg_pool(struct ib_conn *ib_conn, unsigned cmds_max)
376 {
377         struct iser_device *device = ib_conn->device;
378         struct iser_fr_desc *desc;
379         int i, ret;
380
381         INIT_LIST_HEAD(&ib_conn->fastreg.pool);
382         ib_conn->fastreg.pool_size = 0;
383         for (i = 0; i < cmds_max; i++) {
384                 desc = kzalloc(sizeof(*desc), GFP_KERNEL);
385                 if (!desc) {
386                         iser_err("Failed to allocate a new fast_reg descriptor\n");
387                         ret = -ENOMEM;
388                         goto err;
389                 }
390
391                 ret = iser_create_fastreg_desc(device->ib_device, device->pd,
392                                                ib_conn->pi_support, desc);
393                 if (ret) {
394                         iser_err("Failed to create fastreg descriptor err=%d\n",
395                                  ret);
396                         kfree(desc);
397                         goto err;
398                 }
399
400                 list_add_tail(&desc->list, &ib_conn->fastreg.pool);
401                 ib_conn->fastreg.pool_size++;
402         }
403
404         return 0;
405
406 err:
407         iser_free_fastreg_pool(ib_conn);
408         return ret;
409 }
410
411 /**
412  * iser_free_fastreg_pool - releases the pool of fast_reg descriptors
413  */
414 void iser_free_fastreg_pool(struct ib_conn *ib_conn)
415 {
416         struct iser_fr_desc *desc, *tmp;
417         int i = 0;
418
419         if (list_empty(&ib_conn->fastreg.pool))
420                 return;
421
422         iser_info("freeing conn %p fr pool\n", ib_conn);
423
424         list_for_each_entry_safe(desc, tmp, &ib_conn->fastreg.pool, list) {
425                 list_del(&desc->list);
426                 iser_free_reg_res(&desc->rsc);
427                 if (desc->pi_ctx)
428                         iser_free_pi_ctx(desc->pi_ctx);
429                 kfree(desc);
430                 ++i;
431         }
432
433         if (i < ib_conn->fastreg.pool_size)
434                 iser_warn("pool still has %d regions registered\n",
435                           ib_conn->fastreg.pool_size - i);
436 }
437
438 /**
439  * iser_create_ib_conn_res - Queue-Pair (QP)
440  *
441  * returns 0 on success, -1 on failure
442  */
443 static int iser_create_ib_conn_res(struct ib_conn *ib_conn)
444 {
445         struct iser_conn *iser_conn = container_of(ib_conn, struct iser_conn,
446                                                    ib_conn);
447         struct iser_device      *device;
448         struct ib_device_attr *dev_attr;
449         struct ib_qp_init_attr  init_attr;
450         int                     ret = -ENOMEM;
451         int index, min_index = 0;
452
453         BUG_ON(ib_conn->device == NULL);
454
455         device = ib_conn->device;
456         dev_attr = &device->dev_attr;
457
458         memset(&init_attr, 0, sizeof init_attr);
459
460         mutex_lock(&ig.connlist_mutex);
461         /* select the CQ with the minimal number of usages */
462         for (index = 0; index < device->comps_used; index++) {
463                 if (device->comps[index].active_qps <
464                     device->comps[min_index].active_qps)
465                         min_index = index;
466         }
467         ib_conn->comp = &device->comps[min_index];
468         ib_conn->comp->active_qps++;
469         mutex_unlock(&ig.connlist_mutex);
470         iser_info("cq index %d used for ib_conn %p\n", min_index, ib_conn);
471
472         init_attr.event_handler = iser_qp_event_callback;
473         init_attr.qp_context    = (void *)ib_conn;
474         init_attr.send_cq       = ib_conn->comp->cq;
475         init_attr.recv_cq       = ib_conn->comp->cq;
476         init_attr.cap.max_recv_wr  = ISER_QP_MAX_RECV_DTOS;
477         init_attr.cap.max_send_sge = 2;
478         init_attr.cap.max_recv_sge = 1;
479         init_attr.sq_sig_type   = IB_SIGNAL_REQ_WR;
480         init_attr.qp_type       = IB_QPT_RC;
481         if (ib_conn->pi_support) {
482                 init_attr.cap.max_send_wr = ISER_QP_SIG_MAX_REQ_DTOS + 1;
483                 init_attr.create_flags |= IB_QP_CREATE_SIGNATURE_EN;
484                 iser_conn->max_cmds =
485                         ISER_GET_MAX_XMIT_CMDS(ISER_QP_SIG_MAX_REQ_DTOS);
486         } else {
487                 if (dev_attr->max_qp_wr > ISER_QP_MAX_REQ_DTOS) {
488                         init_attr.cap.max_send_wr  = ISER_QP_MAX_REQ_DTOS + 1;
489                         iser_conn->max_cmds =
490                                 ISER_GET_MAX_XMIT_CMDS(ISER_QP_MAX_REQ_DTOS);
491                 } else {
492                         init_attr.cap.max_send_wr = dev_attr->max_qp_wr;
493                         iser_conn->max_cmds =
494                                 ISER_GET_MAX_XMIT_CMDS(dev_attr->max_qp_wr);
495                         iser_dbg("device %s supports max_send_wr %d\n",
496                                  device->ib_device->name, dev_attr->max_qp_wr);
497                 }
498         }
499
500         ret = rdma_create_qp(ib_conn->cma_id, device->pd, &init_attr);
501         if (ret)
502                 goto out_err;
503
504         ib_conn->qp = ib_conn->cma_id->qp;
505         iser_info("setting conn %p cma_id %p qp %p\n",
506                   ib_conn, ib_conn->cma_id,
507                   ib_conn->cma_id->qp);
508         return ret;
509
510 out_err:
511         mutex_lock(&ig.connlist_mutex);
512         ib_conn->comp->active_qps--;
513         mutex_unlock(&ig.connlist_mutex);
514         iser_err("unable to alloc mem or create resource, err %d\n", ret);
515
516         return ret;
517 }
518
519 /**
520  * based on the resolved device node GUID see if there already allocated
521  * device for this device. If there's no such, create one.
522  */
523 static
524 struct iser_device *iser_device_find_by_ib_device(struct rdma_cm_id *cma_id)
525 {
526         struct iser_device *device;
527
528         mutex_lock(&ig.device_list_mutex);
529
530         list_for_each_entry(device, &ig.device_list, ig_list)
531                 /* find if there's a match using the node GUID */
532                 if (device->ib_device->node_guid == cma_id->device->node_guid)
533                         goto inc_refcnt;
534
535         device = kzalloc(sizeof *device, GFP_KERNEL);
536         if (device == NULL)
537                 goto out;
538
539         /* assign this device to the device */
540         device->ib_device = cma_id->device;
541         /* init the device and link it into ig device list */
542         if (iser_create_device_ib_res(device)) {
543                 kfree(device);
544                 device = NULL;
545                 goto out;
546         }
547         list_add(&device->ig_list, &ig.device_list);
548
549 inc_refcnt:
550         device->refcount++;
551 out:
552         mutex_unlock(&ig.device_list_mutex);
553         return device;
554 }
555
556 /* if there's no demand for this device, release it */
557 static void iser_device_try_release(struct iser_device *device)
558 {
559         mutex_lock(&ig.device_list_mutex);
560         device->refcount--;
561         iser_info("device %p refcount %d\n", device, device->refcount);
562         if (!device->refcount) {
563                 iser_free_device_ib_res(device);
564                 list_del(&device->ig_list);
565                 kfree(device);
566         }
567         mutex_unlock(&ig.device_list_mutex);
568 }
569
570 /**
571  * Called with state mutex held
572  **/
573 static int iser_conn_state_comp_exch(struct iser_conn *iser_conn,
574                                      enum iser_conn_state comp,
575                                      enum iser_conn_state exch)
576 {
577         int ret;
578
579         ret = (iser_conn->state == comp);
580         if (ret)
581                 iser_conn->state = exch;
582
583         return ret;
584 }
585
586 void iser_release_work(struct work_struct *work)
587 {
588         struct iser_conn *iser_conn;
589
590         iser_conn = container_of(work, struct iser_conn, release_work);
591
592         /* Wait for conn_stop to complete */
593         wait_for_completion(&iser_conn->stop_completion);
594         /* Wait for IB resouces cleanup to complete */
595         wait_for_completion(&iser_conn->ib_completion);
596
597         mutex_lock(&iser_conn->state_mutex);
598         iser_conn->state = ISER_CONN_DOWN;
599         mutex_unlock(&iser_conn->state_mutex);
600
601         iser_conn_release(iser_conn);
602 }
603
604 /**
605  * iser_free_ib_conn_res - release IB related resources
606  * @iser_conn: iser connection struct
607  * @destroy: indicator if we need to try to release the
608  *     iser device and memory regoins pool (only iscsi
609  *     shutdown and DEVICE_REMOVAL will use this).
610  *
611  * This routine is called with the iser state mutex held
612  * so the cm_id removal is out of here. It is Safe to
613  * be invoked multiple times.
614  */
615 static void iser_free_ib_conn_res(struct iser_conn *iser_conn,
616                                   bool destroy)
617 {
618         struct ib_conn *ib_conn = &iser_conn->ib_conn;
619         struct iser_device *device = ib_conn->device;
620
621         iser_info("freeing conn %p cma_id %p qp %p\n",
622                   iser_conn, ib_conn->cma_id, ib_conn->qp);
623
624         if (ib_conn->qp != NULL) {
625                 ib_conn->comp->active_qps--;
626                 rdma_destroy_qp(ib_conn->cma_id);
627                 ib_conn->qp = NULL;
628         }
629
630         if (destroy) {
631                 if (iser_conn->rx_descs)
632                         iser_free_rx_descriptors(iser_conn);
633
634                 if (device != NULL) {
635                         iser_device_try_release(device);
636                         ib_conn->device = NULL;
637                 }
638         }
639 }
640
641 /**
642  * Frees all conn objects and deallocs conn descriptor
643  */
644 void iser_conn_release(struct iser_conn *iser_conn)
645 {
646         struct ib_conn *ib_conn = &iser_conn->ib_conn;
647
648         mutex_lock(&ig.connlist_mutex);
649         list_del(&iser_conn->conn_list);
650         mutex_unlock(&ig.connlist_mutex);
651
652         mutex_lock(&iser_conn->state_mutex);
653         /* In case we endup here without ep_disconnect being invoked. */
654         if (iser_conn->state != ISER_CONN_DOWN) {
655                 iser_warn("iser conn %p state %d, expected state down.\n",
656                           iser_conn, iser_conn->state);
657                 iscsi_destroy_endpoint(iser_conn->ep);
658                 iser_conn->state = ISER_CONN_DOWN;
659         }
660         /*
661          * In case we never got to bind stage, we still need to
662          * release IB resources (which is safe to call more than once).
663          */
664         iser_free_ib_conn_res(iser_conn, true);
665         mutex_unlock(&iser_conn->state_mutex);
666
667         if (ib_conn->cma_id != NULL) {
668                 rdma_destroy_id(ib_conn->cma_id);
669                 ib_conn->cma_id = NULL;
670         }
671
672         kfree(iser_conn);
673 }
674
675 /**
676  * triggers start of the disconnect procedures and wait for them to be done
677  * Called with state mutex held
678  */
679 int iser_conn_terminate(struct iser_conn *iser_conn)
680 {
681         struct ib_conn *ib_conn = &iser_conn->ib_conn;
682         struct ib_send_wr *bad_wr;
683         int err = 0;
684
685         /* terminate the iser conn only if the conn state is UP */
686         if (!iser_conn_state_comp_exch(iser_conn, ISER_CONN_UP,
687                                        ISER_CONN_TERMINATING))
688                 return 0;
689
690         iser_info("iser_conn %p state %d\n", iser_conn, iser_conn->state);
691
692         /* suspend queuing of new iscsi commands */
693         if (iser_conn->iscsi_conn)
694                 iscsi_suspend_queue(iser_conn->iscsi_conn);
695
696         /*
697          * In case we didn't already clean up the cma_id (peer initiated
698          * a disconnection), we need to Cause the CMA to change the QP
699          * state to ERROR.
700          */
701         if (ib_conn->cma_id) {
702                 err = rdma_disconnect(ib_conn->cma_id);
703                 if (err)
704                         iser_err("Failed to disconnect, conn: 0x%p err %d\n",
705                                  iser_conn, err);
706
707                 /* post an indication that all flush errors were consumed */
708                 err = ib_post_send(ib_conn->qp, &ib_conn->beacon, &bad_wr);
709                 if (err) {
710                         iser_err("conn %p failed to post beacon", ib_conn);
711                         return 1;
712                 }
713
714                 wait_for_completion(&ib_conn->flush_comp);
715         }
716
717         return 1;
718 }
719
720 /**
721  * Called with state mutex held
722  **/
723 static void iser_connect_error(struct rdma_cm_id *cma_id)
724 {
725         struct iser_conn *iser_conn;
726
727         iser_conn = (struct iser_conn *)cma_id->context;
728         iser_conn->state = ISER_CONN_TERMINATING;
729 }
730
731 /**
732  * Called with state mutex held
733  **/
734 static void iser_addr_handler(struct rdma_cm_id *cma_id)
735 {
736         struct iser_device *device;
737         struct iser_conn   *iser_conn;
738         struct ib_conn   *ib_conn;
739         int    ret;
740
741         iser_conn = (struct iser_conn *)cma_id->context;
742         if (iser_conn->state != ISER_CONN_PENDING)
743                 /* bailout */
744                 return;
745
746         ib_conn = &iser_conn->ib_conn;
747         device = iser_device_find_by_ib_device(cma_id);
748         if (!device) {
749                 iser_err("device lookup/creation failed\n");
750                 iser_connect_error(cma_id);
751                 return;
752         }
753
754         ib_conn->device = device;
755
756         /* connection T10-PI support */
757         if (iser_pi_enable) {
758                 if (!(device->dev_attr.device_cap_flags &
759                       IB_DEVICE_SIGNATURE_HANDOVER)) {
760                         iser_warn("T10-PI requested but not supported on %s, "
761                                   "continue without T10-PI\n",
762                                   ib_conn->device->ib_device->name);
763                         ib_conn->pi_support = false;
764                 } else {
765                         ib_conn->pi_support = true;
766                 }
767         }
768
769         ret = rdma_resolve_route(cma_id, 1000);
770         if (ret) {
771                 iser_err("resolve route failed: %d\n", ret);
772                 iser_connect_error(cma_id);
773                 return;
774         }
775 }
776
777 /**
778  * Called with state mutex held
779  **/
780 static void iser_route_handler(struct rdma_cm_id *cma_id)
781 {
782         struct rdma_conn_param conn_param;
783         int    ret;
784         struct iser_cm_hdr req_hdr;
785         struct iser_conn *iser_conn = (struct iser_conn *)cma_id->context;
786         struct ib_conn *ib_conn = &iser_conn->ib_conn;
787         struct iser_device *device = ib_conn->device;
788
789         if (iser_conn->state != ISER_CONN_PENDING)
790                 /* bailout */
791                 return;
792
793         ret = iser_create_ib_conn_res(ib_conn);
794         if (ret)
795                 goto failure;
796
797         memset(&conn_param, 0, sizeof conn_param);
798         conn_param.responder_resources = device->dev_attr.max_qp_rd_atom;
799         conn_param.initiator_depth     = 1;
800         conn_param.retry_count         = 7;
801         conn_param.rnr_retry_count     = 6;
802
803         memset(&req_hdr, 0, sizeof(req_hdr));
804         req_hdr.flags = (ISER_ZBVA_NOT_SUPPORTED |
805                         ISER_SEND_W_INV_NOT_SUPPORTED);
806         conn_param.private_data         = (void *)&req_hdr;
807         conn_param.private_data_len     = sizeof(struct iser_cm_hdr);
808
809         ret = rdma_connect(cma_id, &conn_param);
810         if (ret) {
811                 iser_err("failure connecting: %d\n", ret);
812                 goto failure;
813         }
814
815         return;
816 failure:
817         iser_connect_error(cma_id);
818 }
819
820 static void iser_connected_handler(struct rdma_cm_id *cma_id)
821 {
822         struct iser_conn *iser_conn;
823         struct ib_qp_attr attr;
824         struct ib_qp_init_attr init_attr;
825
826         iser_conn = (struct iser_conn *)cma_id->context;
827         if (iser_conn->state != ISER_CONN_PENDING)
828                 /* bailout */
829                 return;
830
831         (void)ib_query_qp(cma_id->qp, &attr, ~0, &init_attr);
832         iser_info("remote qpn:%x my qpn:%x\n", attr.dest_qp_num, cma_id->qp->qp_num);
833
834         iser_conn->state = ISER_CONN_UP;
835         complete(&iser_conn->up_completion);
836 }
837
838 static void iser_disconnected_handler(struct rdma_cm_id *cma_id)
839 {
840         struct iser_conn *iser_conn = (struct iser_conn *)cma_id->context;
841
842         if (iser_conn_terminate(iser_conn)) {
843                 if (iser_conn->iscsi_conn)
844                         iscsi_conn_failure(iser_conn->iscsi_conn,
845                                            ISCSI_ERR_CONN_FAILED);
846                 else
847                         iser_err("iscsi_iser connection isn't bound\n");
848         }
849 }
850
851 static void iser_cleanup_handler(struct rdma_cm_id *cma_id,
852                                  bool destroy)
853 {
854         struct iser_conn *iser_conn = (struct iser_conn *)cma_id->context;
855
856         /*
857          * We are not guaranteed that we visited disconnected_handler
858          * by now, call it here to be safe that we handle CM drep
859          * and flush errors.
860          */
861         iser_disconnected_handler(cma_id);
862         iser_free_ib_conn_res(iser_conn, destroy);
863         complete(&iser_conn->ib_completion);
864 };
865
866 static int iser_cma_handler(struct rdma_cm_id *cma_id, struct rdma_cm_event *event)
867 {
868         struct iser_conn *iser_conn;
869         int ret = 0;
870
871         iser_conn = (struct iser_conn *)cma_id->context;
872         iser_info("%s (%d): status %d conn %p id %p\n",
873                   rdma_event_msg(event->event), event->event,
874                   event->status, cma_id->context, cma_id);
875
876         mutex_lock(&iser_conn->state_mutex);
877         switch (event->event) {
878         case RDMA_CM_EVENT_ADDR_RESOLVED:
879                 iser_addr_handler(cma_id);
880                 break;
881         case RDMA_CM_EVENT_ROUTE_RESOLVED:
882                 iser_route_handler(cma_id);
883                 break;
884         case RDMA_CM_EVENT_ESTABLISHED:
885                 iser_connected_handler(cma_id);
886                 break;
887         case RDMA_CM_EVENT_ADDR_ERROR:
888         case RDMA_CM_EVENT_ROUTE_ERROR:
889         case RDMA_CM_EVENT_CONNECT_ERROR:
890         case RDMA_CM_EVENT_UNREACHABLE:
891         case RDMA_CM_EVENT_REJECTED:
892                 iser_connect_error(cma_id);
893                 break;
894         case RDMA_CM_EVENT_DISCONNECTED:
895         case RDMA_CM_EVENT_ADDR_CHANGE:
896         case RDMA_CM_EVENT_TIMEWAIT_EXIT:
897                 iser_cleanup_handler(cma_id, false);
898                 break;
899         case RDMA_CM_EVENT_DEVICE_REMOVAL:
900                 /*
901                  * we *must* destroy the device as we cannot rely
902                  * on iscsid to be around to initiate error handling.
903                  * also if we are not in state DOWN implicitly destroy
904                  * the cma_id.
905                  */
906                 iser_cleanup_handler(cma_id, true);
907                 if (iser_conn->state != ISER_CONN_DOWN) {
908                         iser_conn->ib_conn.cma_id = NULL;
909                         ret = 1;
910                 }
911                 break;
912         default:
913                 iser_err("Unexpected RDMA CM event: %s (%d)\n",
914                          rdma_event_msg(event->event), event->event);
915                 break;
916         }
917         mutex_unlock(&iser_conn->state_mutex);
918
919         return ret;
920 }
921
922 void iser_conn_init(struct iser_conn *iser_conn)
923 {
924         iser_conn->state = ISER_CONN_INIT;
925         iser_conn->ib_conn.post_recv_buf_count = 0;
926         init_completion(&iser_conn->ib_conn.flush_comp);
927         init_completion(&iser_conn->stop_completion);
928         init_completion(&iser_conn->ib_completion);
929         init_completion(&iser_conn->up_completion);
930         INIT_LIST_HEAD(&iser_conn->conn_list);
931         spin_lock_init(&iser_conn->ib_conn.lock);
932         mutex_init(&iser_conn->state_mutex);
933 }
934
935  /**
936  * starts the process of connecting to the target
937  * sleeps until the connection is established or rejected
938  */
939 int iser_connect(struct iser_conn   *iser_conn,
940                  struct sockaddr    *src_addr,
941                  struct sockaddr    *dst_addr,
942                  int                 non_blocking)
943 {
944         struct ib_conn *ib_conn = &iser_conn->ib_conn;
945         int err = 0;
946
947         mutex_lock(&iser_conn->state_mutex);
948
949         sprintf(iser_conn->name, "%pISp", dst_addr);
950
951         iser_info("connecting to: %s\n", iser_conn->name);
952
953         /* the device is known only --after-- address resolution */
954         ib_conn->device = NULL;
955
956         iser_conn->state = ISER_CONN_PENDING;
957
958         ib_conn->beacon.wr_id = ISER_BEACON_WRID;
959         ib_conn->beacon.opcode = IB_WR_SEND;
960
961         ib_conn->cma_id = rdma_create_id(iser_cma_handler,
962                                          (void *)iser_conn,
963                                          RDMA_PS_TCP, IB_QPT_RC);
964         if (IS_ERR(ib_conn->cma_id)) {
965                 err = PTR_ERR(ib_conn->cma_id);
966                 iser_err("rdma_create_id failed: %d\n", err);
967                 goto id_failure;
968         }
969
970         err = rdma_resolve_addr(ib_conn->cma_id, src_addr, dst_addr, 1000);
971         if (err) {
972                 iser_err("rdma_resolve_addr failed: %d\n", err);
973                 goto addr_failure;
974         }
975
976         if (!non_blocking) {
977                 wait_for_completion_interruptible(&iser_conn->up_completion);
978
979                 if (iser_conn->state != ISER_CONN_UP) {
980                         err =  -EIO;
981                         goto connect_failure;
982                 }
983         }
984         mutex_unlock(&iser_conn->state_mutex);
985
986         mutex_lock(&ig.connlist_mutex);
987         list_add(&iser_conn->conn_list, &ig.connlist);
988         mutex_unlock(&ig.connlist_mutex);
989         return 0;
990
991 id_failure:
992         ib_conn->cma_id = NULL;
993 addr_failure:
994         iser_conn->state = ISER_CONN_DOWN;
995 connect_failure:
996         mutex_unlock(&iser_conn->state_mutex);
997         iser_conn_release(iser_conn);
998         return err;
999 }
1000
1001 int iser_post_recvl(struct iser_conn *iser_conn)
1002 {
1003         struct ib_recv_wr rx_wr, *rx_wr_failed;
1004         struct ib_conn *ib_conn = &iser_conn->ib_conn;
1005         struct ib_sge     sge;
1006         int ib_ret;
1007
1008         sge.addr   = iser_conn->login_resp_dma;
1009         sge.length = ISER_RX_LOGIN_SIZE;
1010         sge.lkey   = ib_conn->device->mr->lkey;
1011
1012         rx_wr.wr_id   = (uintptr_t)iser_conn->login_resp_buf;
1013         rx_wr.sg_list = &sge;
1014         rx_wr.num_sge = 1;
1015         rx_wr.next    = NULL;
1016
1017         ib_conn->post_recv_buf_count++;
1018         ib_ret  = ib_post_recv(ib_conn->qp, &rx_wr, &rx_wr_failed);
1019         if (ib_ret) {
1020                 iser_err("ib_post_recv failed ret=%d\n", ib_ret);
1021                 ib_conn->post_recv_buf_count--;
1022         }
1023         return ib_ret;
1024 }
1025
1026 int iser_post_recvm(struct iser_conn *iser_conn, int count)
1027 {
1028         struct ib_recv_wr *rx_wr, *rx_wr_failed;
1029         int i, ib_ret;
1030         struct ib_conn *ib_conn = &iser_conn->ib_conn;
1031         unsigned int my_rx_head = iser_conn->rx_desc_head;
1032         struct iser_rx_desc *rx_desc;
1033
1034         for (rx_wr = ib_conn->rx_wr, i = 0; i < count; i++, rx_wr++) {
1035                 rx_desc         = &iser_conn->rx_descs[my_rx_head];
1036                 rx_wr->wr_id    = (uintptr_t)rx_desc;
1037                 rx_wr->sg_list  = &rx_desc->rx_sg;
1038                 rx_wr->num_sge  = 1;
1039                 rx_wr->next     = rx_wr + 1;
1040                 my_rx_head = (my_rx_head + 1) & iser_conn->qp_max_recv_dtos_mask;
1041         }
1042
1043         rx_wr--;
1044         rx_wr->next = NULL; /* mark end of work requests list */
1045
1046         ib_conn->post_recv_buf_count += count;
1047         ib_ret  = ib_post_recv(ib_conn->qp, ib_conn->rx_wr, &rx_wr_failed);
1048         if (ib_ret) {
1049                 iser_err("ib_post_recv failed ret=%d\n", ib_ret);
1050                 ib_conn->post_recv_buf_count -= count;
1051         } else
1052                 iser_conn->rx_desc_head = my_rx_head;
1053         return ib_ret;
1054 }
1055
1056
1057 /**
1058  * iser_start_send - Initiate a Send DTO operation
1059  *
1060  * returns 0 on success, -1 on failure
1061  */
1062 int iser_post_send(struct ib_conn *ib_conn, struct iser_tx_desc *tx_desc,
1063                    bool signal)
1064 {
1065         int               ib_ret;
1066         struct ib_send_wr send_wr, *send_wr_failed;
1067
1068         ib_dma_sync_single_for_device(ib_conn->device->ib_device,
1069                                       tx_desc->dma_addr, ISER_HEADERS_LEN,
1070                                       DMA_TO_DEVICE);
1071
1072         send_wr.next       = NULL;
1073         send_wr.wr_id      = (uintptr_t)tx_desc;
1074         send_wr.sg_list    = tx_desc->tx_sg;
1075         send_wr.num_sge    = tx_desc->num_sge;
1076         send_wr.opcode     = IB_WR_SEND;
1077         send_wr.send_flags = signal ? IB_SEND_SIGNALED : 0;
1078
1079         ib_ret = ib_post_send(ib_conn->qp, &send_wr, &send_wr_failed);
1080         if (ib_ret)
1081                 iser_err("ib_post_send failed, ret:%d\n", ib_ret);
1082
1083         return ib_ret;
1084 }
1085
1086 /**
1087  * is_iser_tx_desc - Indicate if the completion wr_id
1088  *     is a TX descriptor or not.
1089  * @iser_conn: iser connection
1090  * @wr_id: completion WR identifier
1091  *
1092  * Since we cannot rely on wc opcode in FLUSH errors
1093  * we must work around it by checking if the wr_id address
1094  * falls in the iser connection rx_descs buffer. If so
1095  * it is an RX descriptor, otherwize it is a TX.
1096  */
1097 static inline bool
1098 is_iser_tx_desc(struct iser_conn *iser_conn, void *wr_id)
1099 {
1100         void *start = iser_conn->rx_descs;
1101         int len = iser_conn->num_rx_descs * sizeof(*iser_conn->rx_descs);
1102
1103         if (wr_id >= start && wr_id < start + len)
1104                 return false;
1105
1106         return true;
1107 }
1108
1109 /**
1110  * iser_handle_comp_error() - Handle error completion
1111  * @ib_conn:   connection RDMA resources
1112  * @wc:        work completion
1113  *
1114  * Notes: We may handle a FLUSH error completion and in this case
1115  *        we only cleanup in case TX type was DATAOUT. For non-FLUSH
1116  *        error completion we should also notify iscsi layer that
1117  *        connection is failed (in case we passed bind stage).
1118  */
1119 static void
1120 iser_handle_comp_error(struct ib_conn *ib_conn,
1121                        struct ib_wc *wc)
1122 {
1123         void *wr_id = (void *)(uintptr_t)wc->wr_id;
1124         struct iser_conn *iser_conn = container_of(ib_conn, struct iser_conn,
1125                                                    ib_conn);
1126
1127         if (wc->status != IB_WC_WR_FLUSH_ERR)
1128                 if (iser_conn->iscsi_conn)
1129                         iscsi_conn_failure(iser_conn->iscsi_conn,
1130                                            ISCSI_ERR_CONN_FAILED);
1131
1132         if (wc->wr_id == ISER_FASTREG_LI_WRID)
1133                 return;
1134
1135         if (is_iser_tx_desc(iser_conn, wr_id)) {
1136                 struct iser_tx_desc *desc = wr_id;
1137
1138                 if (desc->type == ISCSI_TX_DATAOUT)
1139                         kmem_cache_free(ig.desc_cache, desc);
1140         } else {
1141                 ib_conn->post_recv_buf_count--;
1142         }
1143 }
1144
1145 /**
1146  * iser_handle_wc - handle a single work completion
1147  * @wc: work completion
1148  *
1149  * Soft-IRQ context, work completion can be either
1150  * SEND or RECV, and can turn out successful or
1151  * with error (or flush error).
1152  */
1153 static void iser_handle_wc(struct ib_wc *wc)
1154 {
1155         struct ib_conn *ib_conn;
1156         struct iser_tx_desc *tx_desc;
1157         struct iser_rx_desc *rx_desc;
1158
1159         ib_conn = wc->qp->qp_context;
1160         if (likely(wc->status == IB_WC_SUCCESS)) {
1161                 if (wc->opcode == IB_WC_RECV) {
1162                         rx_desc = (struct iser_rx_desc *)(uintptr_t)wc->wr_id;
1163                         iser_rcv_completion(rx_desc, wc->byte_len,
1164                                             ib_conn);
1165                 } else
1166                 if (wc->opcode == IB_WC_SEND) {
1167                         tx_desc = (struct iser_tx_desc *)(uintptr_t)wc->wr_id;
1168                         iser_snd_completion(tx_desc, ib_conn);
1169                 } else {
1170                         iser_err("Unknown wc opcode %d\n", wc->opcode);
1171                 }
1172         } else {
1173                 if (wc->status != IB_WC_WR_FLUSH_ERR)
1174                         iser_err("%s (%d): wr id %llx vend_err %x\n",
1175                                  ib_wc_status_msg(wc->status), wc->status,
1176                                  wc->wr_id, wc->vendor_err);
1177                 else
1178                         iser_dbg("%s (%d): wr id %llx\n",
1179                                  ib_wc_status_msg(wc->status), wc->status,
1180                                  wc->wr_id);
1181
1182                 if (wc->wr_id == ISER_BEACON_WRID)
1183                         /* all flush errors were consumed */
1184                         complete(&ib_conn->flush_comp);
1185                 else
1186                         iser_handle_comp_error(ib_conn, wc);
1187         }
1188 }
1189
1190 /**
1191  * iser_cq_tasklet_fn - iSER completion polling loop
1192  * @data: iSER completion context
1193  *
1194  * Soft-IRQ context, polling connection CQ until
1195  * either CQ was empty or we exausted polling budget
1196  */
1197 static void iser_cq_tasklet_fn(unsigned long data)
1198 {
1199         struct iser_comp *comp = (struct iser_comp *)data;
1200         struct ib_cq *cq = comp->cq;
1201         struct ib_wc *const wcs = comp->wcs;
1202         int i, n, completed = 0;
1203
1204         while ((n = ib_poll_cq(cq, ARRAY_SIZE(comp->wcs), wcs)) > 0) {
1205                 for (i = 0; i < n; i++)
1206                         iser_handle_wc(&wcs[i]);
1207
1208                 completed += n;
1209                 if (completed >= iser_cq_poll_limit)
1210                         break;
1211         }
1212
1213         /*
1214          * It is assumed here that arming CQ only once its empty
1215          * would not cause interrupts to be missed.
1216          */
1217         ib_req_notify_cq(cq, IB_CQ_NEXT_COMP);
1218
1219         iser_dbg("got %d completions\n", completed);
1220 }
1221
1222 static void iser_cq_callback(struct ib_cq *cq, void *cq_context)
1223 {
1224         struct iser_comp *comp = cq_context;
1225
1226         tasklet_schedule(&comp->tasklet);
1227 }
1228
1229 u8 iser_check_task_pi_status(struct iscsi_iser_task *iser_task,
1230                              enum iser_data_dir cmd_dir, sector_t *sector)
1231 {
1232         struct iser_mem_reg *reg = &iser_task->rdma_reg[cmd_dir];
1233         struct iser_fr_desc *desc = reg->mem_h;
1234         unsigned long sector_size = iser_task->sc->device->sector_size;
1235         struct ib_mr_status mr_status;
1236         int ret;
1237
1238         if (desc && desc->pi_ctx->sig_protected) {
1239                 desc->pi_ctx->sig_protected = 0;
1240                 ret = ib_check_mr_status(desc->pi_ctx->sig_mr,
1241                                          IB_MR_CHECK_SIG_STATUS, &mr_status);
1242                 if (ret) {
1243                         pr_err("ib_check_mr_status failed, ret %d\n", ret);
1244                         goto err;
1245                 }
1246
1247                 if (mr_status.fail_status & IB_MR_CHECK_SIG_STATUS) {
1248                         sector_t sector_off = mr_status.sig_err.sig_err_offset;
1249
1250                         do_div(sector_off, sector_size + 8);
1251                         *sector = scsi_get_lba(iser_task->sc) + sector_off;
1252
1253                         pr_err("PI error found type %d at sector %llx "
1254                                "expected %x vs actual %x\n",
1255                                mr_status.sig_err.err_type,
1256                                (unsigned long long)*sector,
1257                                mr_status.sig_err.expected,
1258                                mr_status.sig_err.actual);
1259
1260                         switch (mr_status.sig_err.err_type) {
1261                         case IB_SIG_BAD_GUARD:
1262                                 return 0x1;
1263                         case IB_SIG_BAD_REFTAG:
1264                                 return 0x3;
1265                         case IB_SIG_BAD_APPTAG:
1266                                 return 0x2;
1267                         }
1268                 }
1269         }
1270
1271         return 0;
1272 err:
1273         /* Not alot we can do here, return ambiguous guard error */
1274         return 0x1;
1275 }