94c4cc3eab912aa0911c208611e189c5b94d104f
[mirror/scst/.git] / srpt / src / ib_srpt.c
1 /*
2  * Copyright (c) 2006 - 2009 Mellanox Technology Inc.  All rights reserved.
3  * Copyright (C) 2008 Vladislav Bolkhovitin <vst@vlnb.net>
4  * Copyright (C) 2008 - 2009 Bart Van Assche <bart.vanassche@gmail.com>
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  */
35
36 #include <linux/module.h>
37 #include <linux/init.h>
38 #include <linux/slab.h>
39 #include <linux/err.h>
40 #include <linux/string.h>
41 #include <linux/kthread.h>
42
43 #include <asm/atomic.h>
44
45 #include "ib_srpt.h"
46
47 /* Name of this kernel module. */
48 #define DRV_NAME                "ib_srpt"
49 /* Prefix for printk() kernel messages. */
50 #define PFX                     DRV_NAME ": "
51 #define DRV_VERSION             "1.0.1"
52 #define DRV_RELDATE             "July 10, 2008"
53
54 #define MELLANOX_SRPT_ID_STRING "Mellanox OFED SRP target"
55
56 MODULE_AUTHOR("Vu Pham");
57 MODULE_DESCRIPTION("InfiniBand SCSI RDMA Protocol target "
58                    "v" DRV_VERSION " (" DRV_RELDATE ")");
59 MODULE_LICENSE("Dual BSD/GPL");
60
61 struct srpt_thread {
62         /* Protects thread_ioctx_list. */
63         spinlock_t thread_lock;
64         /* I/O contexts to be processed by the kernel thread. */
65         struct list_head thread_ioctx_list;
66         /* SRPT kernel thread. */
67         struct task_struct *thread;
68 };
69
70 static u64 mellanox_ioc_guid;
71 /* List of srpt_device structures. */
72 static struct list_head srpt_devices;
73 static int thread;
74 static struct srpt_thread srpt_thread;
75 static DECLARE_WAIT_QUEUE_HEAD(ioctx_list_waitQ);
76
77 module_param(thread, int, 0444);
78 MODULE_PARM_DESC(thread,
79                  "Executing ioctx in thread context. Default 0, i.e. soft IRQ, "
80                  "where possible");
81
82 static void srpt_add_one(struct ib_device *device);
83 static void srpt_remove_one(struct ib_device *device);
84 static int srpt_disconnect_channel(struct srpt_rdma_ch *ch, int dreq);
85 static void srpt_unregister_mad_agent(struct srpt_device *sdev);
86
87 static struct ib_client srpt_client = {
88         .name = DRV_NAME,
89         .add = srpt_add_one,
90         .remove = srpt_remove_one
91 };
92
93 /*
94  * Callback function called by the InfiniBand core when an asynchronous IB
95  * event occurs. This callback may occur in interrupt context. See also
96  * section 11.5.2, Set Asynchronous Event Handler in the InfiniBand
97  * Architecture Specification.
98  */
99 static void srpt_event_handler(struct ib_event_handler *handler,
100                                struct ib_event *event)
101 {
102         struct srpt_device *sdev =
103             ib_get_client_data(event->device, &srpt_client);
104         struct srpt_port *sport;
105
106         if (!sdev || sdev->device != event->device)
107                 return;
108
109         printk(KERN_WARNING PFX "ASYNC event= %d on device= %s\n",
110                 event->event, sdev->device->name);
111
112         switch (event->event) {
113         case IB_EVENT_PORT_ERR:
114                 if (event->element.port_num <= sdev->device->phys_port_cnt) {
115                         sport = &sdev->port[event->element.port_num - 1];
116                         sport->lid = 0;
117                         sport->sm_lid = 0;
118                 }
119                 break;
120         case IB_EVENT_PORT_ACTIVE:
121         case IB_EVENT_LID_CHANGE:
122         case IB_EVENT_PKEY_CHANGE:
123         case IB_EVENT_SM_CHANGE:
124         case IB_EVENT_CLIENT_REREGISTER:
125                 if (event->element.port_num <= sdev->device->phys_port_cnt) {
126                         sport = &sdev->port[event->element.port_num - 1];
127                         if (!sport->lid && !sport->sm_lid)
128                                 schedule_work(&sport->work);
129                 }
130                 break;
131         default:
132                 break;
133         }
134
135 }
136
137 /*
138  * Callback function called by the InfiniBand core for SRQ (shared receive
139  * queue) events.
140  */
141 static void srpt_srq_event(struct ib_event *event, void *ctx)
142 {
143         printk(KERN_WARNING PFX "SRQ event %d\n", event->event);
144 }
145
146 /*
147  * Callback function called by the InfiniBand core for QP (queue pair) events.
148  */
149 static void srpt_qp_event(struct ib_event *event, void *ctx)
150 {
151         struct srpt_rdma_ch *ch = ctx;
152
153         printk(KERN_WARNING PFX
154                "QP event %d on cm_id=%p sess_name=%s state=%d\n",
155                event->event, ch->cm_id, ch->sess_name, ch->state);
156
157         switch (event->event) {
158         case IB_EVENT_COMM_EST:
159                 ib_cm_notify(ch->cm_id, event->event);
160                 break;
161         case IB_EVENT_QP_LAST_WQE_REACHED:
162                 if (ch->state == RDMA_CHANNEL_LIVE) {
163                         printk(KERN_WARNING PFX
164                                "Schedule CM_DISCONNECT_WORK\n");
165                         srpt_disconnect_channel(ch, 1);
166                 }
167                 break;
168         default:
169                 break;
170         }
171 }
172
173 /*
174  * Helper function for filling in an InfiniBand IOUnitInfo structure. Copies
175  * the lowest four bits of value in element slot of the array of four bit
176  * elements called c_list (controller list). The index slot is one-based.
177  *
178  * @pre 1 <= slot && 0 <= value && value < 16
179  */
180 static void srpt_set_ioc(u8 *c_list, u32 slot, u8 value)
181 {
182         u16 id;
183         u8 tmp;
184
185         id = (slot - 1) / 2;
186         if (slot & 0x1) {
187                 tmp = c_list[id] & 0xf;
188                 c_list[id] = (value << 4) | tmp;
189         } else {
190                 tmp = c_list[id] & 0xf0;
191                 c_list[id] = (value & 0xf) | tmp;
192         }
193 }
194
195 /*
196  * Write InfiniBand ClassPortInfo to mad. See also section 16.3.3.1
197  * ClassPortInfo in the InfiniBand Architecture Specification.
198  */
199 static void srpt_get_class_port_info(struct ib_dm_mad *mad)
200 {
201         struct ib_class_port_info *cif;
202
203         cif = (struct ib_class_port_info *)mad->data;
204         memset(cif, 0, sizeof *cif);
205         cif->base_version = 1;
206         cif->class_version = 1;
207         cif->resp_time_value = 20;
208
209         mad->mad_hdr.status = 0;
210 }
211
212 /*
213  * Write IOUnitInfo to mad. See also section 16.3.3.3 IOUnitInfo in the
214  * InfiniBand Architecture Specification. See also section B.7,
215  * table B.6 in the T10 SRP r16a document.
216  */
217 static void srpt_get_iou(struct ib_dm_mad *mad)
218 {
219         struct ib_dm_iou_info *ioui;
220         u8 slot;
221         int i;
222
223         ioui = (struct ib_dm_iou_info *)mad->data;
224         ioui->change_id = 1;
225         ioui->max_controllers = 16;
226
227         /* set present for slot 1 and empty for the rest */
228         srpt_set_ioc(ioui->controller_list, 1, 1);
229         for (i = 1, slot = 2; i < 16; i++, slot++)
230                 srpt_set_ioc(ioui->controller_list, slot, 0);
231
232         mad->mad_hdr.status = 0;
233 }
234
235 /*
236  * Write IOControllerprofile to mad for I/O controller (sdev, slot). See also
237  * section 16.3.3.4 IOControllerProfile in the InfiniBand Architecture
238  * Specification. See also section B.7, table B.7 in the T10 SRP r16a
239  * document.
240  */
241 static void srpt_get_ioc(struct srpt_device *sdev, u32 slot,
242                          struct ib_dm_mad *mad)
243 {
244         struct ib_dm_ioc_profile *iocp;
245
246         iocp = (struct ib_dm_ioc_profile *)mad->data;
247
248         if (!slot || slot > 16) {
249                 mad->mad_hdr.status = cpu_to_be16(DM_MAD_STATUS_INVALID_FIELD);
250                 return;
251         }
252
253         if (slot > 2) {
254                 mad->mad_hdr.status = cpu_to_be16(DM_MAD_STATUS_NO_IOC);
255                 return;
256         }
257
258         memset(iocp, 0, sizeof *iocp);
259         strcpy(iocp->id_string, MELLANOX_SRPT_ID_STRING);
260         iocp->guid = cpu_to_be64(mellanox_ioc_guid);
261         iocp->vendor_id = cpu_to_be32(sdev->dev_attr.vendor_id);
262         iocp->device_id = cpu_to_be32(sdev->dev_attr.vendor_part_id);
263         iocp->device_version = cpu_to_be16(sdev->dev_attr.hw_ver);
264         iocp->subsys_vendor_id = cpu_to_be32(sdev->dev_attr.vendor_id);
265         iocp->subsys_device_id = 0x0;
266         iocp->io_class = cpu_to_be16(SRP_REV16A_IB_IO_CLASS);
267         iocp->io_subclass = cpu_to_be16(SRP_IO_SUBCLASS);
268         iocp->protocol = cpu_to_be16(SRP_PROTOCOL);
269         iocp->protocol_version = cpu_to_be16(SRP_PROTOCOL_VERSION);
270         iocp->send_queue_depth = cpu_to_be16(SRPT_SRQ_SIZE);
271         iocp->rdma_read_depth = 4;
272         iocp->send_size = cpu_to_be32(MAX_MESSAGE_SIZE);
273         iocp->rdma_size = cpu_to_be32(MAX_RDMA_SIZE);
274         iocp->num_svc_entries = 1;
275         iocp->op_cap_mask = SRP_SEND_TO_IOC | SRP_SEND_FROM_IOC |
276             SRP_RDMA_READ_FROM_IOC | SRP_RDMA_WRITE_FROM_IOC;
277
278         mad->mad_hdr.status = 0;
279 }
280
281 /*
282  * Device management: write ServiceEntries to mad for the given slot. See also
283  * section 16.3.3.5 ServiceEntries in the InfiniBand Architecture
284  * Specification. See also section B.7, table B.8 in the T10 SRP r16a document.
285  */
286 static void srpt_get_svc_entries(u16 slot, u8 hi, u8 lo, struct ib_dm_mad *mad)
287 {
288         struct ib_dm_svc_entries *svc_entries;
289
290         if (!slot || slot > 16) {
291                 mad->mad_hdr.status = cpu_to_be16(DM_MAD_STATUS_INVALID_FIELD);
292                 return;
293         }
294
295         if (slot > 2 || lo > hi || hi > 1) {
296                 mad->mad_hdr.status = cpu_to_be16(DM_MAD_STATUS_NO_IOC);
297                 return;
298         }
299
300         svc_entries = (struct ib_dm_svc_entries *)mad->data;
301         memset(svc_entries, 0, sizeof *svc_entries);
302         svc_entries->service_entries[0].id = cpu_to_be64(mellanox_ioc_guid);
303         sprintf(svc_entries->service_entries[0].name, "%s%016llx",
304                 SRP_SERVICE_NAME_PREFIX, (unsigned long long)mellanox_ioc_guid);
305
306         mad->mad_hdr.status = 0;
307 }
308
309 /*
310  * Actual processing of a received MAD *rq_mad received through source port *sp
311  * (MAD = InfiniBand management datagram). The response to be sent back is
312  * written to *rsp_mad.
313  */
314 static void srpt_mgmt_method_get(struct srpt_port *sp, struct ib_mad *rq_mad,
315                                  struct ib_dm_mad *rsp_mad)
316 {
317         u16 attr_id;
318         u32 slot;
319         u8 hi, lo;
320
321         attr_id = be16_to_cpu(rq_mad->mad_hdr.attr_id);
322         switch (attr_id) {
323         case DM_ATTR_CLASS_PORT_INFO:
324                 srpt_get_class_port_info(rsp_mad);
325                 break;
326         case DM_ATTR_IOU_INFO:
327                 srpt_get_iou(rsp_mad);
328                 break;
329         case DM_ATTR_IOC_PROFILE:
330                 slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
331                 srpt_get_ioc(sp->sdev, slot, rsp_mad);
332                 break;
333         case DM_ATTR_SVC_ENTRIES:
334                 slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
335                 hi = (u8) ((slot >> 8) & 0xff);
336                 lo = (u8) (slot & 0xff);
337                 slot = (u16) ((slot >> 16) & 0xffff);
338                 srpt_get_svc_entries(slot, hi, lo, rsp_mad);
339                 break;
340         default:
341                 rsp_mad->mad_hdr.status =
342                     cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
343                 break;
344         }
345 }
346
347 /*
348  * Callback function that is called by the InfiniBand core after transmission of
349  * a MAD. (MAD = management datagram; AH = address handle.)
350  */
351 static void srpt_mad_send_handler(struct ib_mad_agent *mad_agent,
352                                   struct ib_mad_send_wc *mad_wc)
353 {
354         ib_destroy_ah(mad_wc->send_buf->ah);
355         ib_free_send_mad(mad_wc->send_buf);
356 }
357
358 /*
359  * Callback function that is called by the InfiniBand core after reception of
360  * a MAD (management datagram).
361  */
362 static void srpt_mad_recv_handler(struct ib_mad_agent *mad_agent,
363                                   struct ib_mad_recv_wc *mad_wc)
364 {
365         struct srpt_port *sport = (struct srpt_port *)mad_agent->context;
366         struct ib_ah *ah;
367         struct ib_mad_send_buf *rsp;
368         struct ib_dm_mad *dm_mad;
369
370         if (!mad_wc || !mad_wc->recv_buf.mad)
371                 return;
372
373         ah = ib_create_ah_from_wc(mad_agent->qp->pd, mad_wc->wc,
374                                   mad_wc->recv_buf.grh, mad_agent->port_num);
375         if (IS_ERR(ah))
376                 goto err;
377
378         BUILD_BUG_ON(offsetof(struct ib_dm_mad, data) != IB_MGMT_DEVICE_HDR);
379
380         rsp = ib_create_send_mad(mad_agent, mad_wc->wc->src_qp,
381                                  mad_wc->wc->pkey_index, 0,
382                                  IB_MGMT_DEVICE_HDR, IB_MGMT_DEVICE_DATA,
383                                  GFP_KERNEL);
384         if (IS_ERR(rsp))
385                 goto err_rsp;
386
387         rsp->ah = ah;
388
389         dm_mad = rsp->mad;
390         memcpy(dm_mad, mad_wc->recv_buf.mad, sizeof *dm_mad);
391         dm_mad->mad_hdr.method = IB_MGMT_METHOD_GET_RESP;
392         dm_mad->mad_hdr.status = 0;
393
394         switch (mad_wc->recv_buf.mad->mad_hdr.method) {
395         case IB_MGMT_METHOD_GET:
396                 srpt_mgmt_method_get(sport, mad_wc->recv_buf.mad, dm_mad);
397                 break;
398         case IB_MGMT_METHOD_SET:
399                 dm_mad->mad_hdr.status =
400                     cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
401                 break;
402         default:
403                 dm_mad->mad_hdr.status =
404                     cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD);
405                 break;
406         }
407
408         if (!ib_post_send_mad(rsp, NULL)) {
409                 ib_free_recv_mad(mad_wc);
410                 /* will destroy_ah & free_send_mad in send completion */
411                 return;
412         }
413
414         ib_free_send_mad(rsp);
415
416 err_rsp:
417         ib_destroy_ah(ah);
418 err:
419         ib_free_recv_mad(mad_wc);
420 }
421
422 /*
423  * Enable InfiniBand management datagram processing, update the cached sm_lid,
424  * lid and gid values, and register a callback function for processing MADs
425  * on the specified port. It is safe to call this function more than once for
426  * the same port.
427  */
428 static int srpt_refresh_port(struct srpt_port *sport)
429 {
430         struct ib_mad_reg_req reg_req;
431         struct ib_port_modify port_modify;
432         struct ib_port_attr port_attr;
433         int ret;
434
435         memset(&port_modify, 0, sizeof port_modify);
436         port_modify.set_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP;
437         port_modify.clr_port_cap_mask = 0;
438
439         ret = ib_modify_port(sport->sdev->device, sport->port, 0, &port_modify);
440         if (ret)
441                 goto err_mod_port;
442
443         ret = ib_query_port(sport->sdev->device, sport->port, &port_attr);
444         if (ret)
445                 goto err_query_port;
446
447         sport->sm_lid = port_attr.sm_lid;
448         sport->lid = port_attr.lid;
449
450         ret = ib_query_gid(sport->sdev->device, sport->port, 0, &sport->gid);
451         if (ret)
452                 goto err_query_port;
453
454         if (!sport->mad_agent) {
455                 memset(&reg_req, 0, sizeof reg_req);
456                 reg_req.mgmt_class = IB_MGMT_CLASS_DEVICE_MGMT;
457                 reg_req.mgmt_class_version = IB_MGMT_BASE_VERSION;
458                 set_bit(IB_MGMT_METHOD_GET, reg_req.method_mask);
459                 set_bit(IB_MGMT_METHOD_SET, reg_req.method_mask);
460
461                 sport->mad_agent = ib_register_mad_agent(sport->sdev->device,
462                                                          sport->port,
463                                                          IB_QPT_GSI,
464                                                          &reg_req, 0,
465                                                          srpt_mad_send_handler,
466                                                          srpt_mad_recv_handler,
467                                                          sport);
468                 if (IS_ERR(sport->mad_agent))
469                         goto err_query_port;
470         }
471
472         return 0;
473
474 err_query_port:
475
476         port_modify.set_port_cap_mask = 0;
477         port_modify.clr_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP;
478         ib_modify_port(sport->sdev->device, sport->port, 0, &port_modify);
479
480 err_mod_port:
481
482         return ret;
483 }
484
485 /*
486  * Unregister the callback function for processing MADs and disable MAD
487  * processing for all ports of the specified device. It is safe to call this
488  * function more than once for the same device.
489  */
490 static void srpt_unregister_mad_agent(struct srpt_device *sdev)
491 {
492         struct ib_port_modify port_modify = {
493                 .clr_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP,
494         };
495         struct srpt_port *sport;
496         int i;
497
498         for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
499                 sport = &sdev->port[i - 1];
500                 WARN_ON(sport->port != i);
501                 if (ib_modify_port(sdev->device, i, 0, &port_modify) < 0)
502                         printk(KERN_ERR PFX "disabling MAD processing"
503                                " failed.\n");
504                 if (sport->mad_agent && !IS_ERR(sport->mad_agent)) {
505                         ib_unregister_mad_agent(sport->mad_agent);
506                         sport->mad_agent = NULL;
507                 }
508         }
509 }
510
511 /*
512  * Allocate and initialize an SRPT I/O context structure.
513  */
514 static struct srpt_ioctx *srpt_alloc_ioctx(struct srpt_device *sdev)
515 {
516         struct srpt_ioctx *ioctx;
517
518         ioctx = kmalloc(sizeof *ioctx, GFP_KERNEL);
519         if (!ioctx)
520                 goto out;
521
522         ioctx->buf = kzalloc(MAX_MESSAGE_SIZE, GFP_KERNEL);
523         if (!ioctx->buf)
524                 goto out_free_ioctx;
525
526         ioctx->dma = dma_map_single(sdev->device->dma_device, ioctx->buf,
527                                     MAX_MESSAGE_SIZE, DMA_BIDIRECTIONAL);
528 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
529         if (dma_mapping_error(sdev->device->dma_device, ioctx->dma))
530 #else
531         if (dma_mapping_error(ioctx->dma))
532 #endif
533                 goto out_free_buf;
534
535         return ioctx;
536
537 out_free_buf:
538         kfree(ioctx->buf);
539 out_free_ioctx:
540         kfree(ioctx);
541 out:
542         return NULL;
543 }
544
545 /*
546  * Deallocate an SRPT I/O context structure.
547  */
548 static void srpt_free_ioctx(struct srpt_device *sdev, struct srpt_ioctx *ioctx)
549 {
550         if (!ioctx)
551                 return;
552
553         dma_unmap_single(sdev->device->dma_device, ioctx->dma,
554                          MAX_MESSAGE_SIZE, DMA_BIDIRECTIONAL);
555         kfree(ioctx->buf);
556         kfree(ioctx);
557 }
558
559 /*
560  * Associate a ring of SRPT I/O context structures with the specified device.
561  */
562 static int srpt_alloc_ioctx_ring(struct srpt_device *sdev)
563 {
564         int i;
565
566         for (i = 0; i < SRPT_SRQ_SIZE; ++i) {
567                 sdev->ioctx_ring[i] = srpt_alloc_ioctx(sdev);
568
569                 if (!sdev->ioctx_ring[i])
570                         goto err;
571
572                 sdev->ioctx_ring[i]->index = i;
573         }
574
575         return 0;
576
577 err:
578         while (--i > 0) {
579                 srpt_free_ioctx(sdev, sdev->ioctx_ring[i]);
580                 sdev->ioctx_ring[i] = NULL;
581         }
582         return -ENOMEM;
583 }
584
585 /*
586  * Post a receive request on the work queue of InfiniBand device 'sdev'.
587  */
588 static int srpt_post_recv(struct srpt_device *sdev, struct srpt_ioctx *ioctx)
589 {
590         struct ib_sge list;
591         struct ib_recv_wr wr, *bad_wr;
592
593         wr.wr_id = ioctx->index | SRPT_OP_RECV;
594
595         list.addr = ioctx->dma;
596         list.length = MAX_MESSAGE_SIZE;
597         list.lkey = sdev->mr->lkey;
598
599         wr.next = NULL;
600         wr.sg_list = &list;
601         wr.num_sge = 1;
602
603         return ib_post_srq_recv(sdev->srq, &wr, &bad_wr);
604 }
605
606 /*
607  * Post a send request on the SRPT RDMA channel 'ch'.
608  */
609 static int srpt_post_send(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx,
610                           int len)
611 {
612         struct ib_sge list;
613         struct ib_send_wr wr, *bad_wr;
614         struct srpt_device *sdev = ch->sport->sdev;
615
616         dma_sync_single_for_device(sdev->device->dma_device, ioctx->dma,
617                                    MAX_MESSAGE_SIZE, DMA_TO_DEVICE);
618
619         list.addr = ioctx->dma;
620         list.length = len;
621         list.lkey = sdev->mr->lkey;
622
623         wr.next = NULL;
624         wr.wr_id = ioctx->index;
625         wr.sg_list = &list;
626         wr.num_sge = 1;
627         wr.opcode = IB_WR_SEND;
628         wr.send_flags = IB_SEND_SIGNALED;
629
630         return ib_post_send(ch->qp, &wr, &bad_wr);
631 }
632
633 static int srpt_get_desc_tbl(struct srpt_ioctx *ioctx, struct srp_cmd *srp_cmd,
634                              int *ind)
635 {
636         struct srp_indirect_buf *idb;
637         struct srp_direct_buf *db;
638
639         *ind = 0;
640         if (((srp_cmd->buf_fmt & 0xf) == SRP_DATA_DESC_DIRECT) ||
641             ((srp_cmd->buf_fmt >> 4) == SRP_DATA_DESC_DIRECT)) {
642                 ioctx->n_rbuf = 1;
643                 ioctx->rbufs = &ioctx->single_rbuf;
644
645                 db = (void *)srp_cmd->add_data;
646                 memcpy(ioctx->rbufs, db, sizeof *db);
647                 ioctx->data_len = be32_to_cpu(db->len);
648         } else {
649                 idb = (void *)srp_cmd->add_data;
650
651                 ioctx->n_rbuf = be32_to_cpu(idb->table_desc.len) / sizeof *db;
652
653                 if (ioctx->n_rbuf >
654                     (srp_cmd->data_out_desc_cnt + srp_cmd->data_in_desc_cnt)) {
655                         *ind = 1;
656                         ioctx->n_rbuf = 0;
657                         goto out;
658                 }
659
660                 if (ioctx->n_rbuf == 1)
661                         ioctx->rbufs = &ioctx->single_rbuf;
662                 else
663                         ioctx->rbufs =
664                                 kmalloc(ioctx->n_rbuf * sizeof *db, GFP_ATOMIC);
665                 if (!ioctx->rbufs) {
666                         ioctx->n_rbuf = 0;
667                         return -ENOMEM;
668                 }
669
670                 db = idb->desc_list;
671                 memcpy(ioctx->rbufs, db, ioctx->n_rbuf * sizeof *db);
672                 ioctx->data_len = be32_to_cpu(idb->len);
673         }
674 out:
675         return 0;
676 }
677
678 /*
679  * Modify the attributes of queue pair 'qp': allow local write, remote read,
680  * and remote write. Also transition 'qp' to state IB_QPS_INIT.
681  */
682 static int srpt_init_ch_qp(struct srpt_rdma_ch *ch, struct ib_qp *qp)
683 {
684         struct ib_qp_attr *attr;
685         int ret;
686
687         attr = kzalloc(sizeof *attr, GFP_KERNEL);
688         if (!attr)
689                 return -ENOMEM;
690
691         attr->qp_state = IB_QPS_INIT;
692         attr->qp_access_flags = IB_ACCESS_LOCAL_WRITE | IB_ACCESS_REMOTE_READ |
693             IB_ACCESS_REMOTE_WRITE;
694         attr->port_num = ch->sport->port;
695         attr->pkey_index = 0;
696
697         ret = ib_modify_qp(qp, attr,
698                            IB_QP_STATE | IB_QP_ACCESS_FLAGS | IB_QP_PORT |
699                            IB_QP_PKEY_INDEX);
700
701         kfree(attr);
702         return ret;
703 }
704
705 static int srpt_ch_qp_rtr_rts(struct srpt_rdma_ch *ch, struct ib_qp *qp,
706                               enum ib_qp_state qp_state)
707 {
708         struct ib_qp_attr *qp_attr;
709         int attr_mask;
710         int ret;
711
712         qp_attr = kmalloc(sizeof *qp_attr, GFP_KERNEL);
713         if (!qp_attr)
714                 return -ENOMEM;
715
716         qp_attr->qp_state = qp_state;
717         ret = ib_cm_init_qp_attr(ch->cm_id, qp_attr, &attr_mask);
718         if (ret)
719                 goto out;
720
721         if (qp_state == IB_QPS_RTR)
722                 qp_attr->max_dest_rd_atomic = 4;
723         else
724                 qp_attr->max_rd_atomic = 4;
725
726         ret = ib_modify_qp(qp, qp_attr, attr_mask);
727
728 out:
729         kfree(qp_attr);
730         return ret;
731 }
732
733 static void srpt_reset_ioctx(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx)
734 {
735         int i;
736
737         if (ioctx->n_rdma_ius > 0 && ioctx->rdma_ius) {
738                 struct rdma_iu *riu = ioctx->rdma_ius;
739
740                 for (i = 0; i < ioctx->n_rdma_ius; ++i, ++riu)
741                         kfree(riu->sge);
742                 kfree(ioctx->rdma_ius);
743         }
744
745         if (ioctx->n_rbuf > 1)
746                 kfree(ioctx->rbufs);
747
748         if (srpt_post_recv(ch->sport->sdev, ioctx))
749                 printk(KERN_ERR PFX "SRQ post_recv failed - this is serious\n");
750                 /* we should queue it back to free_ioctx queue */
751         else
752                 atomic_inc(&ch->req_lim_delta);
753 }
754
755 static void srpt_handle_err_comp(struct srpt_rdma_ch *ch, struct ib_wc *wc)
756 {
757         struct srpt_ioctx *ioctx;
758         struct srpt_device *sdev = ch->sport->sdev;
759         scst_data_direction dir = SCST_DATA_NONE;
760
761         if (wc->wr_id & SRPT_OP_RECV) {
762                 ioctx = sdev->ioctx_ring[wc->wr_id & ~SRPT_OP_RECV];
763                 printk(KERN_ERR PFX "This is serious - SRQ is in bad state\n");
764         } else {
765                 ioctx = sdev->ioctx_ring[wc->wr_id];
766
767                 if (ioctx->scmnd) {
768                         struct scst_cmd *scmnd = ioctx->scmnd;
769
770                         dir = scst_cmd_get_data_direction(scmnd);
771
772                         if (dir == SCST_DATA_NONE)
773                                 scst_tgt_cmd_done(scmnd,
774                                         scst_estimate_context());
775                         else {
776                                 dma_unmap_sg(sdev->device->dma_device,
777                                              scst_cmd_get_sg(scmnd),
778                                              scst_cmd_get_sg_cnt(scmnd),
779                                              scst_to_tgt_dma_dir(dir));
780
781                                 if (scmnd->state == SCST_CMD_STATE_DATA_WAIT)
782                                         scst_rx_data(scmnd,
783                                                      SCST_RX_STATUS_ERROR,
784                                                      SCST_CONTEXT_THREAD);
785                                 else if (scmnd->state == SCST_CMD_STATE_XMIT_WAIT)
786                                         scst_tgt_cmd_done(scmnd,
787                                                 scst_estimate_context());
788                         }
789                 } else
790                         srpt_reset_ioctx(ch, ioctx);
791         }
792 }
793
794 static void srpt_handle_send_comp(struct srpt_rdma_ch *ch,
795                                   struct srpt_ioctx *ioctx,
796                                   enum scst_exec_context context)
797 {
798         if (ioctx->scmnd) {
799                 scst_data_direction dir =
800                         scst_cmd_get_data_direction(ioctx->scmnd);
801
802                 if (dir != SCST_DATA_NONE)
803                         dma_unmap_sg(ch->sport->sdev->device->dma_device,
804                                      scst_cmd_get_sg(ioctx->scmnd),
805                                      scst_cmd_get_sg_cnt(ioctx->scmnd),
806                                      scst_to_tgt_dma_dir(dir));
807
808                 scst_tgt_cmd_done(ioctx->scmnd, context);
809         } else
810                 srpt_reset_ioctx(ch, ioctx);
811 }
812
813 static void srpt_handle_rdma_comp(struct srpt_rdma_ch *ch,
814                                   struct srpt_ioctx *ioctx)
815 {
816         if (!ioctx->scmnd) {
817                 srpt_reset_ioctx(ch, ioctx);
818                 return;
819         }
820
821         if (scst_cmd_get_data_direction(ioctx->scmnd) == SCST_DATA_WRITE)
822                 scst_rx_data(ioctx->scmnd, SCST_RX_STATUS_SUCCESS,
823                         scst_estimate_context());
824 }
825
826 static void srpt_build_cmd_rsp(struct srpt_rdma_ch *ch,
827                                struct srpt_ioctx *ioctx, u8 s_key, u8 s_code,
828                                u64 tag)
829 {
830         struct srp_rsp *srp_rsp;
831         struct sense_data *sense;
832         int limit_delta;
833
834         srp_rsp = ioctx->buf;
835         memset(srp_rsp, 0, sizeof *srp_rsp);
836
837         limit_delta = atomic_read(&ch->req_lim_delta);
838         atomic_sub(limit_delta, &ch->req_lim_delta);
839
840         srp_rsp->opcode = SRP_RSP;
841         srp_rsp->req_lim_delta = cpu_to_be32(limit_delta);
842         srp_rsp->tag = tag;
843
844         if (s_key != NO_SENSE) {
845                 srp_rsp->flags |= SRP_RSP_FLAG_SNSVALID;
846                 srp_rsp->status = SAM_STAT_CHECK_CONDITION;
847                 srp_rsp->sense_data_len =
848                     cpu_to_be32(sizeof *sense + (sizeof *sense % 4));
849
850                 sense = (struct sense_data *)(srp_rsp + 1);
851                 sense->err_code = 0x70;
852                 sense->key = s_key;
853                 sense->asc_ascq = s_code;
854         }
855 }
856
857 static void srpt_build_tskmgmt_rsp(struct srpt_rdma_ch *ch,
858                                    struct srpt_ioctx *ioctx, u8 rsp_code,
859                                    u64 tag)
860 {
861         struct srp_rsp *srp_rsp;
862         int limit_delta;
863
864         dma_sync_single_for_cpu(ch->sport->sdev->device->dma_device, ioctx->dma,
865                                 MAX_MESSAGE_SIZE, DMA_TO_DEVICE);
866
867         srp_rsp = ioctx->buf;
868         memset(srp_rsp, 0, sizeof *srp_rsp);
869
870         limit_delta = atomic_read(&ch->req_lim_delta);
871         atomic_sub(limit_delta, &ch->req_lim_delta);
872
873         srp_rsp->opcode = SRP_RSP;
874         srp_rsp->req_lim_delta = cpu_to_be32(limit_delta);
875         srp_rsp->tag = tag;
876
877         if (rsp_code != SRP_TSK_MGMT_SUCCESS) {
878                 srp_rsp->flags |= SRP_RSP_FLAG_RSPVALID;
879                 srp_rsp->resp_data_len = cpu_to_be32(4);
880                 srp_rsp->data[3] = rsp_code;
881         }
882 }
883
884 /*
885  * Process SRP_CMD.
886  */
887 static int srpt_handle_cmd(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx)
888 {
889         struct scst_cmd *scmnd = NULL;
890         struct srp_cmd *srp_cmd = NULL;
891         scst_data_direction dir = SCST_DATA_NONE;
892         int indirect_desc = 0;
893         int ret;
894
895         srp_cmd = ioctx->buf;
896
897         if (srp_cmd->buf_fmt) {
898                 ret = srpt_get_desc_tbl(ioctx, srp_cmd, &indirect_desc);
899                 if (ret) {
900                         srpt_build_cmd_rsp(ch, ioctx, NO_SENSE,
901                                            NO_ADD_SENSE, srp_cmd->tag);
902                         ((struct srp_rsp *)ioctx->buf)->status =
903                                         SAM_STAT_TASK_SET_FULL;
904                         goto send_rsp;
905                 }
906
907                 if (indirect_desc) {
908                         srpt_build_cmd_rsp(ch, ioctx, NO_SENSE,
909                                            NO_ADD_SENSE, srp_cmd->tag);
910                         ((struct srp_rsp *)ioctx->buf)->status =
911                                         SAM_STAT_TASK_SET_FULL;
912                         goto send_rsp;
913                 }
914
915                 if (srp_cmd->buf_fmt & 0xf)
916                         dir = SCST_DATA_READ;
917                 else if (srp_cmd->buf_fmt >> 4)
918                         dir = SCST_DATA_WRITE;
919                 else
920                         dir = SCST_DATA_NONE;
921         } else
922                 dir = SCST_DATA_NONE;
923
924         scmnd = scst_rx_cmd(ch->scst_sess, (u8 *) &srp_cmd->lun,
925                             sizeof srp_cmd->lun, srp_cmd->cdb, 16,
926                             thread ? SCST_NON_ATOMIC : SCST_ATOMIC);
927         if (!scmnd) {
928                 srpt_build_cmd_rsp(ch, ioctx, NO_SENSE,
929                                    NO_ADD_SENSE, srp_cmd->tag);
930                 ((struct srp_rsp *)ioctx->buf)->status =
931                         SAM_STAT_TASK_SET_FULL;
932                 goto send_rsp;
933         }
934
935         ioctx->scmnd = scmnd;
936
937         switch (srp_cmd->task_attr) {
938         case SRP_CMD_HEAD_OF_Q:
939                 scmnd->queue_type = SCST_CMD_QUEUE_HEAD_OF_QUEUE;
940                 break;
941         case SRP_CMD_ORDERED_Q:
942                 scmnd->queue_type = SCST_CMD_QUEUE_ORDERED;
943                 break;
944         case SRP_CMD_SIMPLE_Q:
945                 scmnd->queue_type = SCST_CMD_QUEUE_SIMPLE;
946                 break;
947         case SRP_CMD_ACA:
948                 scmnd->queue_type = SCST_CMD_QUEUE_ACA;
949                 break;
950         default:
951                 scmnd->queue_type = SCST_CMD_QUEUE_ORDERED;
952                 break;
953         }
954
955         scst_cmd_set_tag(scmnd, srp_cmd->tag);
956         scst_cmd_set_tgt_priv(scmnd, ioctx);
957         scst_cmd_set_expected(scmnd, dir, ioctx->data_len);
958
959         spin_lock_irq(&ch->spinlock);
960         list_add_tail(&ioctx->scmnd_list, &ch->active_scmnd_list);
961         ch->active_scmnd_cnt++;
962         spin_unlock_irq(&ch->spinlock);
963
964         scst_cmd_init_done(scmnd, scst_estimate_context());
965
966         return 0;
967
968 send_rsp:
969         return -1;
970 }
971
972 /*
973  * Process SRP_TSK_MGMT. See also table 19 in the T10 SRP r16a document.
974  */
975 static int srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,
976                                 struct srpt_ioctx *ioctx)
977 {
978         struct srp_tsk_mgmt *srp_tsk = NULL;
979         struct srpt_mgmt_ioctx *mgmt_ioctx;
980         int ret;
981
982         srp_tsk = ioctx->buf;
983
984         printk(KERN_WARNING PFX
985                "recv_tsk_mgmt= %d for task_tag= %lld"
986                " using tag= %lld cm_id= %p sess= %p\n",
987                srp_tsk->tsk_mgmt_func,
988                (unsigned long long) srp_tsk->task_tag,
989                (unsigned long long) srp_tsk->tag,
990                ch->cm_id, ch->scst_sess);
991
992         mgmt_ioctx = kmalloc(sizeof *mgmt_ioctx, GFP_ATOMIC);
993         if (!mgmt_ioctx) {
994                 srpt_build_tskmgmt_rsp(ch, ioctx, SRP_TSK_MGMT_FAILED,
995                                        srp_tsk->tag);
996                 goto send_rsp;
997         }
998
999         mgmt_ioctx->ioctx = ioctx;
1000         mgmt_ioctx->ch = ch;
1001         mgmt_ioctx->tag = srp_tsk->tag;
1002
1003         switch (srp_tsk->tsk_mgmt_func) {
1004         case SRP_TSK_ABORT_TASK:
1005                 ret = scst_rx_mgmt_fn_tag(ch->scst_sess,
1006                                           SCST_ABORT_TASK,
1007                                           srp_tsk->task_tag,
1008                                           thread ?
1009                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1010                                           mgmt_ioctx);
1011                 break;
1012         case SRP_TSK_ABORT_TASK_SET:
1013                 ret = scst_rx_mgmt_fn_lun(ch->scst_sess,
1014                                           SCST_ABORT_TASK_SET,
1015                                           (u8 *) &srp_tsk->lun,
1016                                           sizeof srp_tsk->lun,
1017                                           thread ?
1018                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1019                                           mgmt_ioctx);
1020                 break;
1021         case SRP_TSK_CLEAR_TASK_SET:
1022                 ret = scst_rx_mgmt_fn_lun(ch->scst_sess,
1023                                           SCST_CLEAR_TASK_SET,
1024                                           (u8 *) &srp_tsk->lun,
1025                                           sizeof srp_tsk->lun,
1026                                           thread ?
1027                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1028                                           mgmt_ioctx);
1029                 break;
1030 #if 0
1031         case SRP_TSK_LUN_RESET:
1032                 ret = scst_rx_mgmt_fn_lun(ch->scst_sess,
1033                                           SCST_LUN_RESET,
1034                                           (u8 *) &srp_tsk->lun,
1035                                           sizeof srp_tsk->lun,
1036                                           thread ?
1037                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1038                                           mgmt_ioctx);
1039                 break;
1040 #endif
1041         case SRP_TSK_CLEAR_ACA:
1042                 ret = scst_rx_mgmt_fn_lun(ch->scst_sess,
1043                                           SCST_CLEAR_ACA,
1044                                           (u8 *) &srp_tsk->lun,
1045                                           sizeof srp_tsk->lun,
1046                                           thread ?
1047                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1048                                           mgmt_ioctx);
1049                 break;
1050         default:
1051                 srpt_build_tskmgmt_rsp(ch, ioctx,
1052                                        SRP_TSK_MGMT_FUNC_NOT_SUPP,
1053                                        srp_tsk->tag);
1054                 goto send_rsp;
1055         }
1056         return 0;
1057
1058 send_rsp:
1059         return -1;
1060 }
1061
1062 static void srpt_handle_new_iu(struct srpt_rdma_ch *ch,
1063                                struct srpt_ioctx *ioctx)
1064 {
1065         u8 op;
1066
1067         if (ch->state != RDMA_CHANNEL_LIVE) {
1068                 if (ch->state == RDMA_CHANNEL_CONNECTING) {
1069                         spin_lock_irq(&ch->spinlock);
1070                         list_add_tail(&ioctx->wait_list, &ch->cmd_wait_list);
1071                         spin_unlock_irq(&ch->spinlock);
1072                 } else
1073                         srpt_reset_ioctx(ch, ioctx);
1074
1075                 return;
1076         }
1077
1078         dma_sync_single_for_cpu(ch->sport->sdev->device->dma_device, ioctx->dma,
1079                                 MAX_MESSAGE_SIZE, DMA_FROM_DEVICE);
1080
1081         ioctx->data_len = 0;
1082         ioctx->n_rbuf = 0;
1083         ioctx->rbufs = NULL;
1084         ioctx->n_rdma = 0;
1085         ioctx->n_rdma_ius = 0;
1086         ioctx->rdma_ius = NULL;
1087         ioctx->scmnd = NULL;
1088
1089         op = *(u8 *) ioctx->buf;
1090         switch (op) {
1091         case SRP_CMD:
1092                 if (srpt_handle_cmd(ch, ioctx) < 0)
1093                         goto send_rsp;
1094                 break;
1095
1096         case SRP_TSK_MGMT:
1097                 if (srpt_handle_tsk_mgmt(ch, ioctx) < 0)
1098                         goto send_rsp;
1099                 break;
1100
1101         case SRP_I_LOGOUT:
1102         case SRP_AER_REQ:
1103         default:
1104                 srpt_build_cmd_rsp(ch, ioctx, ILLEGAL_REQUEST, INVALID_CDB,
1105                                    ((struct srp_cmd *)ioctx->buf)->tag);
1106
1107                 goto send_rsp;
1108         }
1109
1110         dma_sync_single_for_device(ch->sport->sdev->device->dma_device,
1111                                    ioctx->dma, MAX_MESSAGE_SIZE,
1112                                    DMA_FROM_DEVICE);
1113
1114         return;
1115
1116 send_rsp:
1117         if (ch->state != RDMA_CHANNEL_LIVE ||
1118             srpt_post_send(ch, ioctx,
1119                            sizeof(struct srp_rsp) +
1120                            be32_to_cpu(((struct srp_rsp *)ioctx->buf)->
1121                                        sense_data_len)))
1122                 srpt_reset_ioctx(ch, ioctx);
1123 }
1124
1125 /*
1126  * Returns true if the ioctx list is non-empty or if the ib_srpt kernel thread
1127  * should stop.
1128  * @pre thread != 0
1129  */
1130 static inline int srpt_test_ioctx_list(void)
1131 {
1132         int res = (!list_empty(&srpt_thread.thread_ioctx_list) ||
1133                    unlikely(kthread_should_stop()));
1134         return res;
1135 }
1136
1137 /*
1138  * Add 'ioctx' to the tail of the ioctx list and wake up the kernel thread.
1139  *
1140  * @pre thread != 0
1141  */
1142 static inline void srpt_schedule_thread(struct srpt_ioctx *ioctx)
1143 {
1144         unsigned long flags;
1145
1146         spin_lock_irqsave(&srpt_thread.thread_lock, flags);
1147         list_add_tail(&ioctx->comp_list, &srpt_thread.thread_ioctx_list);
1148         spin_unlock_irqrestore(&srpt_thread.thread_lock, flags);
1149         wake_up(&ioctx_list_waitQ);
1150 }
1151
1152 /*
1153  * InfiniBand CQ (completion queue) event handler for asynchronous events not
1154  * associated with a completion.
1155  */
1156 static void srpt_completion(struct ib_cq *cq, void *ctx)
1157 {
1158         struct srpt_rdma_ch *ch = ctx;
1159         struct srpt_device *sdev = ch->sport->sdev;
1160         struct ib_wc wc;
1161         struct srpt_ioctx *ioctx;
1162
1163         ib_req_notify_cq(ch->cq, IB_CQ_NEXT_COMP);
1164         while (ib_poll_cq(ch->cq, 1, &wc) > 0) {
1165                 if (wc.status) {
1166                         printk(KERN_ERR PFX "failed %s status= %d\n",
1167                                wc.wr_id & SRPT_OP_RECV ? "receive" : "send",
1168                                wc.status);
1169                         srpt_handle_err_comp(ch, &wc);
1170                         break;
1171                 }
1172
1173                 if (wc.wr_id & SRPT_OP_RECV) {
1174                         ioctx = sdev->ioctx_ring[wc.wr_id & ~SRPT_OP_RECV];
1175                         if (thread) {
1176                                 ioctx->ch = ch;
1177                                 ioctx->op = IB_WC_RECV;
1178                                 srpt_schedule_thread(ioctx);
1179                         } else
1180                                 srpt_handle_new_iu(ch, ioctx);
1181                         continue;
1182                 } else
1183                         ioctx = sdev->ioctx_ring[wc.wr_id];
1184
1185                 if (thread) {
1186                         ioctx->ch = ch;
1187                         ioctx->op = wc.opcode;
1188                         srpt_schedule_thread(ioctx);
1189                 } else {
1190                         switch (wc.opcode) {
1191                         case IB_WC_SEND:
1192                                 srpt_handle_send_comp(ch, ioctx,
1193                                         scst_estimate_context());
1194                                 break;
1195                         case IB_WC_RDMA_WRITE:
1196                         case IB_WC_RDMA_READ:
1197                                 srpt_handle_rdma_comp(ch, ioctx);
1198                                 break;
1199                         default:
1200                                 break;
1201                         }
1202                 }
1203         }
1204 }
1205
1206 /*
1207  * Create a completion queue on the specified device.
1208  */
1209 static int srpt_create_ch_ib(struct srpt_rdma_ch *ch)
1210 {
1211         struct ib_qp_init_attr *qp_init;
1212         struct srpt_device *sdev = ch->sport->sdev;
1213         int cqe;
1214         int ret;
1215
1216         qp_init = kzalloc(sizeof *qp_init, GFP_KERNEL);
1217         if (!qp_init)
1218                 return -ENOMEM;
1219
1220         /* Create a completion queue (CQ). */
1221
1222         cqe = SRPT_RQ_SIZE + SRPT_SQ_SIZE - 1;
1223 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20) && ! defined(RHEL_RELEASE_CODE)
1224         ch->cq = ib_create_cq(sdev->device, srpt_completion, NULL, ch, cqe);
1225 #else
1226         ch->cq = ib_create_cq(sdev->device, srpt_completion, NULL, ch, cqe, 0);
1227 #endif
1228         if (IS_ERR(ch->cq)) {
1229                 ret = PTR_ERR(ch->cq);
1230                 printk(KERN_ERR PFX "failed to create_cq cqe= %d ret= %d\n",
1231                         cqe, ret);
1232                 goto out;
1233         }
1234
1235         /* Request completion notification. */
1236
1237         ib_req_notify_cq(ch->cq, IB_CQ_NEXT_COMP);
1238
1239         /* Create a queue pair (QP). */
1240
1241         qp_init->qp_context = (void *)ch;
1242         qp_init->event_handler = srpt_qp_event;
1243         qp_init->send_cq = ch->cq;
1244         qp_init->recv_cq = ch->cq;
1245         qp_init->srq = sdev->srq;
1246         qp_init->sq_sig_type = IB_SIGNAL_REQ_WR;
1247         qp_init->qp_type = IB_QPT_RC;
1248         qp_init->cap.max_send_wr = SRPT_SQ_SIZE;
1249         qp_init->cap.max_send_sge = SRPT_DEF_SG_PER_WQE;
1250
1251         ch->qp = ib_create_qp(sdev->pd, qp_init);
1252         if (IS_ERR(ch->qp)) {
1253                 ret = PTR_ERR(ch->qp);
1254                 ib_destroy_cq(ch->cq);
1255                 printk(KERN_ERR PFX "failed to create_qp ret= %d\n", ret);
1256                 goto out;
1257         }
1258
1259         printk(KERN_DEBUG PFX "%s: max_cqe= %d max_sge= %d cm_id= %p\n",
1260                __func__, ch->cq->cqe, qp_init->cap.max_send_sge,
1261                ch->cm_id);
1262
1263         /* Modify the attributes and the state of queue pair ch->qp. */
1264
1265         ret = srpt_init_ch_qp(ch, ch->qp);
1266         if (ret) {
1267                 ib_destroy_qp(ch->qp);
1268                 ib_destroy_cq(ch->cq);
1269                 goto out;
1270         }
1271
1272         atomic_set(&ch->req_lim_delta, SRPT_RQ_SIZE);
1273 out:
1274         kfree(qp_init);
1275         return ret;
1276 }
1277
1278 static struct srpt_rdma_ch *srpt_find_channel(struct ib_cm_id *cm_id)
1279 {
1280         struct srpt_device *sdev = cm_id->context;
1281         struct srpt_rdma_ch *ch, *tmp_ch;
1282
1283         spin_lock_irq(&sdev->spinlock);
1284         list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list) {
1285                 if (ch->cm_id == cm_id) {
1286                         spin_unlock_irq(&sdev->spinlock);
1287                         return ch;
1288                 }
1289         }
1290
1291         spin_unlock_irq(&sdev->spinlock);
1292
1293         return NULL;
1294 }
1295
1296 static int srpt_release_channel(struct srpt_rdma_ch *ch, int destroy_cmid)
1297 {
1298         spin_lock_irq(&ch->sport->sdev->spinlock);
1299         list_del(&ch->list);
1300         spin_unlock_irq(&ch->sport->sdev->spinlock);
1301
1302         if (ch->cm_id && destroy_cmid) {
1303                 printk(KERN_WARNING PFX
1304                        "%s: destroy cm_id= %p\n", __func__, ch->cm_id);
1305                 ib_destroy_cm_id(ch->cm_id);
1306                 ch->cm_id = NULL;
1307         }
1308
1309         ib_destroy_qp(ch->qp);
1310         ib_destroy_cq(ch->cq);
1311
1312         if (ch->scst_sess) {
1313                 struct srpt_ioctx *ioctx, *ioctx_tmp;
1314
1315                 printk(KERN_WARNING PFX
1316                        "%s: release sess= %p sess_name= %s active_cmd= %d\n",
1317                        __func__, ch->scst_sess, ch->sess_name,
1318                        ch->active_scmnd_cnt);
1319
1320                 list_for_each_entry_safe(ioctx, ioctx_tmp,
1321                                          &ch->active_scmnd_list, scmnd_list) {
1322                         list_del(&ioctx->scmnd_list);
1323                         ch->active_scmnd_cnt--;
1324                 }
1325
1326                 scst_unregister_session(ch->scst_sess, 0, NULL);
1327                 ch->scst_sess = NULL;
1328         }
1329
1330         kfree(ch);
1331
1332         return destroy_cmid ? 0 : 1;
1333 }
1334
1335 static int srpt_disconnect_channel(struct srpt_rdma_ch *ch, int dreq)
1336 {
1337         spin_lock_irq(&ch->spinlock);
1338         ch->state = RDMA_CHANNEL_DISCONNECTING;
1339         spin_unlock_irq(&ch->spinlock);
1340
1341         if (dreq)
1342                 ib_send_cm_dreq(ch->cm_id, NULL, 0);
1343         else
1344                 ib_send_cm_drep(ch->cm_id, NULL, 0);
1345
1346         return 0;
1347 }
1348
1349 static int srpt_cm_req_recv(struct ib_cm_id *cm_id,
1350                             struct ib_cm_req_event_param *param,
1351                             void *private_data)
1352 {
1353         struct srpt_device *sdev = cm_id->context;
1354         struct srp_login_req *req;
1355         struct srp_login_rsp *rsp;
1356         struct srp_login_rej *rej;
1357         struct ib_cm_rep_param *rep_param;
1358         struct srpt_rdma_ch *ch, *tmp_ch;
1359         u32 it_iu_len;
1360         int ret = 0;
1361
1362         if (!sdev || !private_data)
1363                 return -EINVAL;
1364
1365         rsp = kzalloc(sizeof *rsp, GFP_KERNEL);
1366         rej = kzalloc(sizeof *rej, GFP_KERNEL);
1367         rep_param = kzalloc(sizeof *rep_param, GFP_KERNEL);
1368
1369         if (!rsp || !rej || !rep_param) {
1370                 ret = -ENOMEM;
1371                 goto out;
1372         }
1373
1374         req = (struct srp_login_req *)private_data;
1375
1376         it_iu_len = be32_to_cpu(req->req_it_iu_len);
1377
1378         printk(KERN_DEBUG PFX
1379                "Host login i_port_id=0x%llx:0x%llx t_port_id=0x%llx:0x%llx"
1380                " it_iu_len=%d\n",
1381                (unsigned long long)
1382                be64_to_cpu(*(u64 *)&req->initiator_port_id[0]),
1383                (unsigned long long)
1384                be64_to_cpu(*(u64 *)&req->initiator_port_id[8]),
1385                (unsigned long long)be64_to_cpu(*(u64 *)&req->target_port_id[0]),
1386                (unsigned long long)be64_to_cpu(*(u64 *)&req->target_port_id[8]),
1387                it_iu_len);
1388
1389         if (it_iu_len > MAX_MESSAGE_SIZE || it_iu_len < 64) {
1390                 rej->reason =
1391                     cpu_to_be32(SRP_LOGIN_REJ_REQ_IT_IU_LENGTH_TOO_LARGE);
1392                 ret = -EINVAL;
1393                 printk(KERN_WARNING PFX
1394                        "Reject invalid it_iu_len=%d\n", it_iu_len);
1395                 goto reject;
1396         }
1397
1398         if ((req->req_flags & 0x3) == SRP_MULTICHAN_SINGLE) {
1399                 rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_NO_CHAN;
1400
1401                 spin_lock_irq(&sdev->spinlock);
1402
1403                 list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list) {
1404                         if (!memcmp(ch->i_port_id, req->initiator_port_id, 16)
1405                             && !memcmp(ch->t_port_id, req->target_port_id, 16)
1406                             && param->port == ch->sport->port
1407                             && param->listen_id == ch->sport->sdev->cm_id
1408                             && ch->cm_id) {
1409                                 /* found an existing channel */
1410                                 printk(KERN_WARNING PFX
1411                                        "Found existing channel name= %s"
1412                                        " cm_id= %p state= %d\n",
1413                                        ch->sess_name, ch->cm_id, ch->state);
1414
1415                                 spin_unlock_irq(&sdev->spinlock);
1416
1417                                 rsp->rsp_flags =
1418                                     SRP_LOGIN_RSP_MULTICHAN_TERMINATED;
1419
1420                                 if (ch->state == RDMA_CHANNEL_LIVE)
1421                                         srpt_disconnect_channel(ch, 1);
1422                                 else if (ch->state == RDMA_CHANNEL_CONNECTING) {
1423                                         ib_send_cm_rej(ch->cm_id,
1424                                                        IB_CM_REJ_NO_RESOURCES,
1425                                                        NULL, 0, NULL, 0);
1426                                         srpt_release_channel(ch, 1);
1427                                 }
1428
1429                                 spin_lock_irq(&sdev->spinlock);
1430                         }
1431                 }
1432
1433                 spin_unlock_irq(&sdev->spinlock);
1434
1435         } else
1436                 rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_MAINTAINED;
1437
1438         if (((u64) (*(u64 *) req->target_port_id) !=
1439              cpu_to_be64(mellanox_ioc_guid)) ||
1440             ((u64) (*(u64 *) (req->target_port_id + 8)) !=
1441              cpu_to_be64(mellanox_ioc_guid))) {
1442                 rej->reason =
1443                     cpu_to_be32(SRP_LOGIN_REJ_UNABLE_ASSOCIATE_CHANNEL);
1444                 ret = -ENOMEM;
1445                 printk(KERN_WARNING PFX "Reject invalid target_port_id\n");
1446                 goto reject;
1447         }
1448
1449         ch = kzalloc(sizeof *ch, GFP_KERNEL);
1450         if (!ch) {
1451                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
1452                 printk(KERN_WARNING PFX "Reject failed allocate rdma_ch\n");
1453                 ret = -ENOMEM;
1454                 goto reject;
1455         }
1456
1457         spin_lock_init(&ch->spinlock);
1458         memcpy(ch->i_port_id, req->initiator_port_id, 16);
1459         memcpy(ch->t_port_id, req->target_port_id, 16);
1460         ch->sport = &sdev->port[param->port - 1];
1461         ch->cm_id = cm_id;
1462         ch->state = RDMA_CHANNEL_CONNECTING;
1463         INIT_LIST_HEAD(&ch->cmd_wait_list);
1464         INIT_LIST_HEAD(&ch->active_scmnd_list);
1465
1466         ret = srpt_create_ch_ib(ch);
1467         if (ret) {
1468                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
1469                 printk(KERN_WARNING PFX "Reject failed to create rdma_ch\n");
1470                 goto free_ch;
1471         }
1472
1473         ret = srpt_ch_qp_rtr_rts(ch, ch->qp, IB_QPS_RTR);
1474         if (ret) {
1475                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
1476                 printk(KERN_WARNING PFX
1477                        "Reject failed qp to rtr/rts ret=%d\n", ret);
1478                 goto destroy_ib;
1479         }
1480
1481         sprintf(ch->sess_name, "0x%016llx%016llx",
1482                 (unsigned long long)be64_to_cpu(*(u64 *)ch->i_port_id),
1483                 (unsigned long long)be64_to_cpu(*(u64 *)(ch->i_port_id + 8)));
1484
1485         ch->scst_sess = scst_register_session(sdev->scst_tgt, 0, ch->sess_name,
1486                                   NULL, NULL);
1487         if (!ch->scst_sess) {
1488                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
1489                 printk(KERN_WARNING PFX "Failed to create scst sess\n");
1490                 goto destroy_ib;
1491         }
1492
1493         spin_lock_irq(&sdev->spinlock);
1494         list_add_tail(&ch->list, &sdev->rch_list);
1495         spin_unlock_irq(&sdev->spinlock);
1496
1497         printk(KERN_DEBUG PFX "Establish connection sess=%p name=%s cm_id=%p\n",
1498                ch->scst_sess, ch->sess_name, ch->cm_id);
1499
1500         scst_sess_set_tgt_priv(ch->scst_sess, ch);
1501
1502         /* create srp_login_response */
1503         rsp->opcode = SRP_LOGIN_RSP;
1504         rsp->tag = req->tag;
1505         rsp->max_it_iu_len = req->req_it_iu_len;
1506         rsp->max_ti_iu_len = req->req_it_iu_len;
1507         rsp->buf_fmt =
1508             cpu_to_be16(SRP_BUF_FORMAT_DIRECT | SRP_BUF_FORMAT_INDIRECT);
1509         rsp->req_lim_delta = cpu_to_be32(SRPT_RQ_SIZE);
1510         atomic_set(&ch->req_lim_delta, 0);
1511
1512         /* create cm reply */
1513         rep_param->qp_num = ch->qp->qp_num;
1514         rep_param->private_data = (void *)rsp;
1515         rep_param->private_data_len = sizeof *rsp;
1516         rep_param->rnr_retry_count = 7;
1517         rep_param->flow_control = 1;
1518         rep_param->failover_accepted = 0;
1519         rep_param->srq = 1;
1520         rep_param->responder_resources = 4;
1521         rep_param->initiator_depth = 4;
1522
1523         ret = ib_send_cm_rep(cm_id, rep_param);
1524         if (ret)
1525                 srpt_release_channel(ch, 0);
1526
1527         goto out;
1528
1529 destroy_ib:
1530         ib_destroy_qp(ch->qp);
1531         ib_destroy_cq(ch->cq);
1532
1533 free_ch:
1534         kfree(ch);
1535
1536 reject:
1537         rej->opcode = SRP_LOGIN_REJ;
1538         rej->tag = req->tag;
1539         rej->buf_fmt =
1540             cpu_to_be16(SRP_BUF_FORMAT_DIRECT | SRP_BUF_FORMAT_INDIRECT);
1541
1542         ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0,
1543                              (void *)rej, sizeof *rej);
1544
1545 out:
1546         kfree(rep_param);
1547         kfree(rsp);
1548         kfree(rej);
1549
1550         return ret;
1551 }
1552
1553 static int srpt_find_and_release_channel(struct ib_cm_id *cm_id)
1554 {
1555         struct srpt_rdma_ch *ch;
1556
1557         ch = srpt_find_channel(cm_id);
1558         if (!ch)
1559                 return -EINVAL;
1560
1561         return srpt_release_channel(ch, 0);
1562 }
1563
1564 static int srpt_cm_rej_recv(struct ib_cm_id *cm_id)
1565 {
1566         printk(KERN_DEBUG PFX "%s: cm_id=%p\n", __func__, cm_id);
1567         return srpt_find_and_release_channel(cm_id);
1568 }
1569
1570 static int srpt_cm_rtu_recv(struct ib_cm_id *cm_id)
1571 {
1572         struct srpt_rdma_ch *ch;
1573         int ret;
1574
1575         ch = srpt_find_channel(cm_id);
1576         if (!ch)
1577                 return -EINVAL;
1578
1579         if (ch->state == RDMA_CHANNEL_CONNECTING) {
1580                 struct srpt_ioctx *ioctx, *ioctx_tmp;
1581
1582                 spin_lock_irq(&ch->spinlock);
1583                 ch->state = RDMA_CHANNEL_LIVE;
1584                 spin_unlock_irq(&ch->spinlock);
1585                 ret = srpt_ch_qp_rtr_rts(ch, ch->qp, IB_QPS_RTS);
1586
1587                 list_for_each_entry_safe(ioctx, ioctx_tmp, &ch->cmd_wait_list,
1588                                          wait_list) {
1589                         list_del(&ioctx->wait_list);
1590                         srpt_handle_new_iu(ch, ioctx);
1591                 }
1592         } else if (ch->state == RDMA_CHANNEL_DISCONNECTING)
1593                 ret = -EAGAIN;
1594         else
1595                 ret = 0;
1596
1597         if (ret) {
1598                 printk(KERN_ERR PFX "cm_id=%p sess_name=%s state=%d\n",
1599                        cm_id, ch->sess_name, ch->state);
1600                 srpt_disconnect_channel(ch, 1);
1601         }
1602
1603         return ret;
1604 }
1605
1606 static int srpt_cm_timewait_exit(struct ib_cm_id *cm_id)
1607 {
1608         printk(KERN_DEBUG PFX "%s: cm_id=%p\n", __func__, cm_id);
1609         return srpt_find_and_release_channel(cm_id);
1610 }
1611
1612 static int srpt_cm_rep_error(struct ib_cm_id *cm_id)
1613 {
1614         printk(KERN_DEBUG PFX "%s: cm_id=%p\n", __func__, cm_id);
1615         return srpt_find_and_release_channel(cm_id);
1616 }
1617
1618 static int srpt_cm_dreq_recv(struct ib_cm_id *cm_id)
1619 {
1620         struct srpt_rdma_ch *ch;
1621         int ret = 0;
1622
1623         ch = srpt_find_channel(cm_id);
1624
1625         if (!ch)
1626                 return -EINVAL;
1627
1628         printk(KERN_DEBUG PFX "%s: cm_id= %p ch->state= %d\n",
1629                  __func__, cm_id, ch->state);
1630
1631         switch (ch->state) {
1632         case RDMA_CHANNEL_LIVE:
1633         case RDMA_CHANNEL_CONNECTING:
1634                 ret = srpt_disconnect_channel(ch, 0);
1635                 break;
1636         case RDMA_CHANNEL_DISCONNECTING:
1637         default:
1638                 break;
1639         }
1640
1641         return ret;
1642 }
1643
1644 static int srpt_cm_drep_recv(struct ib_cm_id *cm_id)
1645 {
1646         printk(KERN_DEBUG PFX "%s: cm_id=%p\n", __func__, cm_id);
1647         return srpt_find_and_release_channel(cm_id);
1648 }
1649
1650 static int srpt_cm_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event)
1651 {
1652         int ret = 0;
1653
1654         switch (event->event) {
1655         case IB_CM_REQ_RECEIVED:
1656                 ret = srpt_cm_req_recv(cm_id, &event->param.req_rcvd,
1657                                        event->private_data);
1658                 break;
1659         case IB_CM_REJ_RECEIVED:
1660                 ret = srpt_cm_rej_recv(cm_id);
1661                 break;
1662         case IB_CM_RTU_RECEIVED:
1663         case IB_CM_USER_ESTABLISHED:
1664                 ret = srpt_cm_rtu_recv(cm_id);
1665                 break;
1666         case IB_CM_DREQ_RECEIVED:
1667                 ret = srpt_cm_dreq_recv(cm_id);
1668                 break;
1669         case IB_CM_DREP_RECEIVED:
1670                 ret = srpt_cm_drep_recv(cm_id);
1671                 break;
1672         case IB_CM_TIMEWAIT_EXIT:
1673                 ret = srpt_cm_timewait_exit(cm_id);
1674                 break;
1675         case IB_CM_REP_ERROR:
1676                 ret = srpt_cm_rep_error(cm_id);
1677                 break;
1678         default:
1679                 break;
1680         }
1681
1682         return ret;
1683 }
1684
1685 static int srpt_map_sg_to_ib_sge(struct srpt_rdma_ch *ch,
1686                                  struct srpt_ioctx *ioctx,
1687                                  struct scst_cmd *scmnd)
1688 {
1689         struct scatterlist *scat;
1690         scst_data_direction dir;
1691         struct rdma_iu *riu;
1692         struct srp_direct_buf *db;
1693         dma_addr_t dma_addr;
1694         struct ib_sge *sge;
1695         u64 raddr;
1696         u32 rsize;
1697         u32 tsize;
1698         u32 dma_len;
1699         int count, nrdma;
1700         int i, j, k;
1701
1702         scat = scst_cmd_get_sg(scmnd);
1703         dir = scst_cmd_get_data_direction(scmnd);
1704         count = dma_map_sg(ch->sport->sdev->device->dma_device, scat,
1705                            scst_cmd_get_sg_cnt(scmnd),
1706                            scst_to_tgt_dma_dir(dir));
1707         if (unlikely(!count))
1708                 return -EBUSY;
1709
1710         if (ioctx->rdma_ius && ioctx->n_rdma_ius)
1711                 nrdma = ioctx->n_rdma_ius;
1712         else {
1713                 nrdma = count / SRPT_DEF_SG_PER_WQE + ioctx->n_rbuf;
1714
1715                 ioctx->rdma_ius = kzalloc(nrdma * sizeof *riu,
1716                                           scst_cmd_atomic(scmnd)
1717                                           ? GFP_ATOMIC : GFP_KERNEL);
1718                 if (!ioctx->rdma_ius) {
1719                         dma_unmap_sg(ch->sport->sdev->device->dma_device,
1720                                      scat, scst_cmd_get_sg_cnt(scmnd),
1721                                      scst_to_tgt_dma_dir(dir));
1722                         return -ENOMEM;
1723                 }
1724
1725                 ioctx->n_rdma_ius = nrdma;
1726         }
1727
1728         db = ioctx->rbufs;
1729         tsize = (dir == SCST_DATA_READ) ?
1730                 scst_cmd_get_resp_data_len(scmnd) : scst_cmd_get_bufflen(scmnd);
1731         dma_len = sg_dma_len(&scat[0]);
1732         riu = ioctx->rdma_ius;
1733
1734         /*
1735          * For each remote desc - calculate the #ib_sge.
1736          * If #ib_sge < SRPT_DEF_SG_PER_WQE per rdma operation then
1737          *      each remote desc rdma_iu is required a rdma wr;
1738          * else
1739          *      we need to allocate extra rdma_iu to carry extra #ib_sge in
1740          *      another rdma wr
1741          */
1742         for (i = 0, j = 0;
1743              j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
1744                 rsize = be32_to_cpu(db->len);
1745                 raddr = be64_to_cpu(db->va);
1746                 riu->raddr = raddr;
1747                 riu->rkey = be32_to_cpu(db->key);
1748                 riu->sge_cnt = 0;
1749
1750                 /* calculate how many sge required for this remote_buf */
1751                 while (rsize > 0 && tsize > 0) {
1752
1753                         if (rsize >= dma_len) {
1754                                 tsize -= dma_len;
1755                                 rsize -= dma_len;
1756                                 raddr += dma_len;
1757
1758                                 if (tsize > 0) {
1759                                         ++j;
1760                                         if (j < count)
1761                                                 dma_len = sg_dma_len(&scat[j]);
1762                                 }
1763                         } else {
1764                                 tsize -= rsize;
1765                                 dma_len -= rsize;
1766                                 rsize = 0;
1767                         }
1768
1769                         ++riu->sge_cnt;
1770
1771                         if (rsize > 0 && riu->sge_cnt == SRPT_DEF_SG_PER_WQE) {
1772                                 riu->sge =
1773                                     kmalloc(riu->sge_cnt * sizeof *riu->sge,
1774                                             scst_cmd_atomic(scmnd)
1775                                             ? GFP_ATOMIC : GFP_KERNEL);
1776                                 if (!riu->sge)
1777                                         goto free_mem;
1778
1779                                 ++ioctx->n_rdma;
1780                                 ++riu;
1781                                 riu->sge_cnt = 0;
1782                                 riu->raddr = raddr;
1783                                 riu->rkey = be32_to_cpu(db->key);
1784                         }
1785                 }
1786
1787                 riu->sge = kmalloc(riu->sge_cnt * sizeof *riu->sge,
1788                                    scst_cmd_atomic(scmnd)
1789                                    ? GFP_ATOMIC : GFP_KERNEL);
1790
1791                 if (!riu->sge)
1792                         goto free_mem;
1793
1794                 ++ioctx->n_rdma;
1795         }
1796
1797         db = ioctx->rbufs;
1798         scat = scst_cmd_get_sg(scmnd);
1799         tsize = (dir == SCST_DATA_READ) ?
1800                 scst_cmd_get_resp_data_len(scmnd) : scst_cmd_get_bufflen(scmnd);
1801         riu = ioctx->rdma_ius;
1802         dma_len = sg_dma_len(&scat[0]);
1803         dma_addr = sg_dma_address(&scat[0]);
1804
1805         /* this second loop is really mapped sg_addres to rdma_iu->ib_sge */
1806         for (i = 0, j = 0;
1807              j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
1808                 rsize = be32_to_cpu(db->len);
1809                 sge = riu->sge;
1810                 k = 0;
1811
1812                 while (rsize > 0 && tsize > 0) {
1813                         sge->addr = dma_addr;
1814                         sge->lkey = ch->sport->sdev->mr->lkey;
1815
1816                         if (rsize >= dma_len) {
1817                                 sge->length =
1818                                         (tsize < dma_len) ? tsize : dma_len;
1819                                 tsize -= dma_len;
1820                                 rsize -= dma_len;
1821
1822                                 if (tsize > 0) {
1823                                         ++j;
1824                                         if (j < count) {
1825                                                 dma_len = sg_dma_len(&scat[j]);
1826                                                 dma_addr =
1827                                                     sg_dma_address(&scat[j]);
1828                                         }
1829                                 }
1830                         } else {
1831                                 sge->length = (tsize < rsize) ? tsize : rsize;
1832                                 tsize -= rsize;
1833                                 dma_len -= rsize;
1834                                 dma_addr += rsize;
1835                                 rsize = 0;
1836                         }
1837
1838                         ++k;
1839                         if (k == riu->sge_cnt && rsize > 0) {
1840                                 ++riu;
1841                                 sge = riu->sge;
1842                                 k = 0;
1843                         } else if (rsize > 0)
1844                                 ++sge;
1845                 }
1846         }
1847
1848         return 0;
1849
1850 free_mem:
1851         while (ioctx->n_rdma)
1852                 kfree(ioctx->rdma_ius[ioctx->n_rdma--].sge);
1853
1854         kfree(ioctx->rdma_ius);
1855
1856         dma_unmap_sg(ch->sport->sdev->device->dma_device,
1857                      scat, scst_cmd_get_sg_cnt(scmnd),
1858                      scst_to_tgt_dma_dir(dir));
1859
1860         return -ENOMEM;
1861 }
1862
1863 static int srpt_perform_rdmas(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx,
1864                               scst_data_direction dir)
1865 {
1866         struct ib_send_wr wr;
1867         struct ib_send_wr *bad_wr;
1868         struct rdma_iu *riu;
1869         int i;
1870         int ret = 0;
1871
1872         riu = ioctx->rdma_ius;
1873         memset(&wr, 0, sizeof wr);
1874
1875         for (i = 0; i < ioctx->n_rdma; ++i, ++riu) {
1876                 wr.opcode = (dir == SCST_DATA_READ) ?
1877                     IB_WR_RDMA_WRITE : IB_WR_RDMA_READ;
1878                 wr.next = NULL;
1879                 wr.wr_id = ioctx->index;
1880                 wr.wr.rdma.remote_addr = riu->raddr;
1881                 wr.wr.rdma.rkey = riu->rkey;
1882                 wr.num_sge = riu->sge_cnt;
1883                 wr.sg_list = riu->sge;
1884
1885                 /* only get completion event for the last rdma wr */
1886                 if (i == (ioctx->n_rdma - 1) && dir == SCST_DATA_WRITE)
1887                         wr.send_flags = IB_SEND_SIGNALED;
1888
1889                 ret = ib_post_send(ch->qp, &wr, &bad_wr);
1890                 if (ret)
1891                         break;
1892         }
1893
1894         return ret;
1895 }
1896
1897 /*
1898  * Start data reception. Must not block.
1899  */
1900 static int srpt_xfer_data(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx,
1901                           struct scst_cmd *scmnd)
1902 {
1903         int ret;
1904
1905         ret = srpt_map_sg_to_ib_sge(ch, ioctx, scmnd);
1906         if (ret) {
1907                 printk(KERN_ERR PFX "%s[%d] ret=%d\n", __func__, __LINE__, ret);
1908                 ret = SCST_TGT_RES_QUEUE_FULL;
1909                 goto out;
1910         }
1911
1912         ret = srpt_perform_rdmas(ch, ioctx, scst_cmd_get_data_direction(scmnd));
1913         if (ret) {
1914                 printk(KERN_ERR PFX "%s[%d] ret=%d\n", __func__, __LINE__, ret);
1915                 if (ret == -EAGAIN || ret == -ENOMEM)
1916                         ret = SCST_TGT_RES_QUEUE_FULL;
1917                 else
1918                         ret = SCST_TGT_RES_FATAL_ERROR;
1919                 goto out;
1920         }
1921
1922         ret = SCST_TGT_RES_SUCCESS;
1923
1924 out:
1925         return ret;
1926 }
1927
1928 /*
1929  * Called by the SCST core to inform ib_srpt that data reception should start.
1930  * Must not block.
1931  */
1932 static int srpt_rdy_to_xfer(struct scst_cmd *scmnd)
1933 {
1934         struct srpt_rdma_ch *ch;
1935         struct srpt_ioctx *ioctx;
1936
1937         ioctx = scst_cmd_get_tgt_priv(scmnd);
1938         BUG_ON(!ioctx);
1939
1940         ch = scst_sess_get_tgt_priv(scst_cmd_get_session(scmnd));
1941         BUG_ON(!ch);
1942
1943         if (ch->state == RDMA_CHANNEL_DISCONNECTING)
1944                 return SCST_TGT_RES_FATAL_ERROR;
1945         else if (ch->state == RDMA_CHANNEL_CONNECTING)
1946                 return SCST_TGT_RES_QUEUE_FULL;
1947
1948         return srpt_xfer_data(ch, ioctx, scmnd);
1949 }
1950
1951 /*
1952  * Called by the SCST core. Transmits the response buffer and status held in
1953  * 'scmnd'. Must not block.
1954  */
1955 static int srpt_xmit_response(struct scst_cmd *scmnd)
1956 {
1957         struct srpt_rdma_ch *ch;
1958         struct srpt_ioctx *ioctx;
1959         struct srp_rsp *srp_rsp;
1960         u64 tag;
1961         int ret = SCST_TGT_RES_SUCCESS;
1962         int dir;
1963         int status;
1964
1965         ioctx = scst_cmd_get_tgt_priv(scmnd);
1966         BUG_ON(!ioctx);
1967
1968         ch = scst_sess_get_tgt_priv(scst_cmd_get_session(scmnd));
1969         BUG_ON(!ch);
1970
1971         tag = scst_cmd_get_tag(scmnd);
1972
1973         if (ch->state != RDMA_CHANNEL_LIVE) {
1974                 printk(KERN_ERR PFX
1975                        "%s: tag= %lld channel in bad state %d\n",
1976                        __func__, (unsigned long long)tag, ch->state);
1977
1978                 if (ch->state == RDMA_CHANNEL_DISCONNECTING)
1979                         ret = SCST_TGT_RES_FATAL_ERROR;
1980                 else if (ch->state == RDMA_CHANNEL_CONNECTING)
1981                         ret = SCST_TGT_RES_QUEUE_FULL;
1982
1983                 if (unlikely(scst_cmd_aborted(scmnd)))
1984                         goto out_aborted;
1985
1986                 goto out;
1987         }
1988
1989         dma_sync_single_for_cpu(ch->sport->sdev->device->dma_device, ioctx->dma,
1990                                 MAX_MESSAGE_SIZE, DMA_TO_DEVICE);
1991
1992         srp_rsp = ioctx->buf;
1993
1994         if (unlikely(scst_cmd_aborted(scmnd))) {
1995                 printk(KERN_ERR PFX
1996                        "%s: tag= %lld already get aborted\n",
1997                        __func__, (unsigned long long)tag);
1998                 goto out_aborted;
1999         }
2000
2001         dir = scst_cmd_get_data_direction(scmnd);
2002         status = scst_cmd_get_status(scmnd) & 0xff;
2003
2004         srpt_build_cmd_rsp(ch, ioctx, NO_SENSE, NO_ADD_SENSE, tag);
2005
2006         if (SCST_SENSE_VALID(scst_cmd_get_sense_buffer(scmnd))) {
2007                 srp_rsp->sense_data_len = scst_cmd_get_sense_buffer_len(scmnd);
2008                 if (srp_rsp->sense_data_len >
2009                     (MAX_MESSAGE_SIZE - sizeof *srp_rsp))
2010                         srp_rsp->sense_data_len =
2011                             MAX_MESSAGE_SIZE - sizeof *srp_rsp;
2012
2013                 memcpy((u8 *) (srp_rsp + 1), scst_cmd_get_sense_buffer(scmnd),
2014                        srp_rsp->sense_data_len);
2015
2016                 srp_rsp->sense_data_len = cpu_to_be32(srp_rsp->sense_data_len);
2017                 srp_rsp->flags |= SRP_RSP_FLAG_SNSVALID;
2018
2019                 if (!status)
2020                         status = SAM_STAT_CHECK_CONDITION;
2021         }
2022
2023         srp_rsp->status = status;
2024
2025         /* transfer read data if any */
2026         if (dir == SCST_DATA_READ && scst_cmd_get_resp_data_len(scmnd)) {
2027                 ret = srpt_xfer_data(ch, ioctx, scmnd);
2028                 if (ret != SCST_TGT_RES_SUCCESS) {
2029                         printk(KERN_ERR PFX
2030                                "%s: tag= %lld xfer_data failed\n",
2031                                __func__, (unsigned long long)tag);
2032                         goto out;
2033                 }
2034         }
2035
2036         if (srpt_post_send(ch, ioctx,
2037                            sizeof *srp_rsp +
2038                            be32_to_cpu(srp_rsp->sense_data_len))) {
2039                 printk(KERN_ERR PFX "%s: ch->state= %d tag= %lld\n",
2040                        __func__, ch->state,
2041                        (unsigned long long)tag);
2042                 ret = SCST_TGT_RES_FATAL_ERROR;
2043         }
2044
2045 out:
2046         return ret;
2047
2048 out_aborted:
2049         ret = SCST_TGT_RES_SUCCESS;
2050         scst_set_delivery_status(scmnd, SCST_CMD_DELIVERY_ABORTED);
2051         scst_tgt_cmd_done(scmnd, SCST_CONTEXT_SAME);
2052         goto out;
2053 }
2054
2055 /*
2056  * Called by the SCST core to inform ib_srpt that a received task management
2057  * function has been completed. Must not block.
2058  */
2059 static void srpt_tsk_mgmt_done(struct scst_mgmt_cmd *mcmnd)
2060 {
2061         struct srpt_rdma_ch *ch;
2062         struct srpt_mgmt_ioctx *mgmt_ioctx;
2063         struct srpt_ioctx *ioctx;
2064
2065         mgmt_ioctx = scst_mgmt_cmd_get_tgt_priv(mcmnd);
2066         BUG_ON(!mgmt_ioctx);
2067
2068         ch = mgmt_ioctx->ch;
2069         BUG_ON(!ch);
2070
2071         ioctx = mgmt_ioctx->ioctx;
2072         BUG_ON(!ioctx);
2073
2074         printk(KERN_WARNING PFX
2075                "%s: tsk_mgmt_done for tag= %lld status=%d\n",
2076                __func__, (unsigned long long)mgmt_ioctx->tag,
2077                scst_mgmt_cmd_get_status(mcmnd));
2078
2079         srpt_build_tskmgmt_rsp(ch, ioctx,
2080                                (scst_mgmt_cmd_get_status(mcmnd) ==
2081                                 SCST_MGMT_STATUS_SUCCESS) ?
2082                                SRP_TSK_MGMT_SUCCESS : SRP_TSK_MGMT_FAILED,
2083                                mgmt_ioctx->tag);
2084         srpt_post_send(ch, ioctx, sizeof(struct srp_rsp) + 4);
2085
2086         scst_mgmt_cmd_set_tgt_priv(mcmnd, NULL);
2087
2088         kfree(mgmt_ioctx);
2089 }
2090
2091 /*
2092  * Called by the SCST core to inform ib_srpt that the command 'scmnd' is about
2093  * to be freed. May be called in IRQ context.
2094  */
2095 static void srpt_on_free_cmd(struct scst_cmd *scmnd)
2096 {
2097         struct srpt_rdma_ch *ch;
2098         struct srpt_ioctx *ioctx;
2099
2100         ioctx = scst_cmd_get_tgt_priv(scmnd);
2101         BUG_ON(!ioctx);
2102
2103         ch = scst_sess_get_tgt_priv(scst_cmd_get_session(scmnd));
2104         BUG_ON(!ch);
2105
2106         spin_lock_irq(&ch->spinlock);
2107         list_del(&ioctx->scmnd_list);
2108         ch->active_scmnd_cnt--;
2109         spin_unlock_irq(&ch->spinlock);
2110
2111         srpt_reset_ioctx(ch, ioctx);
2112         scst_cmd_set_tgt_priv(scmnd, NULL);
2113 }
2114
2115 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20)
2116 static void srpt_refresh_port_work(void *ctx)
2117 #else
2118 static void srpt_refresh_port_work(struct work_struct *work)
2119 #endif
2120 {
2121 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20)
2122         struct srpt_port *sport = (struct srpt_port *)ctx;
2123 #else
2124         struct srpt_port *sport = container_of(work, struct srpt_port, work);
2125 #endif
2126
2127         srpt_refresh_port(sport);
2128 }
2129
2130 /*
2131  * Called by the SCST core to detect target adapters. Returns the number of
2132  * detected target adapters.
2133  */
2134 static int srpt_detect(struct scst_tgt_template *tp)
2135 {
2136         struct srpt_device *sdev;
2137         struct srpt_port *sport;
2138         int i;
2139         int count = 0;
2140
2141         list_for_each_entry(sdev, &srpt_devices, list) {
2142
2143                 sdev->scst_tgt = scst_register(tp, NULL);
2144                 if (!sdev->scst_tgt)
2145                         goto out;
2146
2147                 scst_tgt_set_tgt_priv(sdev->scst_tgt, sdev);
2148
2149                 for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
2150                         sport = &sdev->port[i - 1];
2151                         sport->sdev = sdev;
2152                         sport->port = i;
2153 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20) && ! defined(BACKPORT_LINUX_WORKQUEUE_TO_2_6_19)
2154                         INIT_WORK(&sport->work, srpt_refresh_port_work, sport);
2155 #else
2156                         INIT_WORK(&sport->work, srpt_refresh_port_work);
2157 #endif
2158
2159                         if (srpt_refresh_port(sport)) {
2160                                 scst_unregister(sdev->scst_tgt);
2161                                 goto out;
2162                         }
2163                 }
2164
2165                 ++count;
2166         }
2167 out:
2168         return count;
2169 }
2170
2171 /*
2172  * Called by the SCST core to free up the resources associated with device
2173  * 'scst_tgt'.
2174  */
2175 static int srpt_release(struct scst_tgt *scst_tgt)
2176 {
2177         struct srpt_device *sdev = scst_tgt_get_tgt_priv(scst_tgt);
2178         struct srpt_rdma_ch *ch, *tmp_ch;
2179
2180         list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list)
2181             srpt_release_channel(ch, 1);
2182
2183         srpt_unregister_mad_agent(sdev);
2184
2185         scst_tgt_set_tgt_priv(scst_tgt, NULL);
2186
2187         complete(&sdev->scst_released);
2188
2189         return 0;
2190 }
2191
2192 /*
2193  * Entry point for ib_srpt's kernel thread. This kernel thread is only created
2194  * when the module parameter 'thread' is not zero (the default is zero).
2195  * This thread processes the ioctx list srpt_thread.thread_ioctx_list.
2196  *
2197  * @pre thread != 0
2198  */
2199 static int srpt_ioctx_thread(void *arg)
2200 {
2201         struct srpt_ioctx *ioctx;
2202
2203         /* Hibernation / freezing of the SRPT kernel thread is not supported. */
2204         current->flags |= PF_NOFREEZE;
2205
2206         spin_lock_irq(&srpt_thread.thread_lock);
2207         while (!kthread_should_stop()) {
2208                 wait_queue_t wait;
2209                 init_waitqueue_entry(&wait, current);
2210
2211                 if (!srpt_test_ioctx_list()) {
2212                         add_wait_queue_exclusive(&ioctx_list_waitQ, &wait);
2213
2214                         for (;;) {
2215                                 set_current_state(TASK_INTERRUPTIBLE);
2216                                 if (srpt_test_ioctx_list())
2217                                         break;
2218                                 spin_unlock_irq(&srpt_thread.thread_lock);
2219                                 schedule();
2220                                 spin_lock_irq(&srpt_thread.thread_lock);
2221                         }
2222                         set_current_state(TASK_RUNNING);
2223                         remove_wait_queue(&ioctx_list_waitQ, &wait);
2224                 }
2225
2226                 while (!list_empty(&srpt_thread.thread_ioctx_list)) {
2227                         ioctx = list_entry(srpt_thread.thread_ioctx_list.next,
2228                                            struct srpt_ioctx, comp_list);
2229
2230                         list_del(&ioctx->comp_list);
2231
2232                         spin_unlock_irq(&srpt_thread.thread_lock);
2233                         switch (ioctx->op) {
2234                         case IB_WC_SEND:
2235                                 srpt_handle_send_comp(ioctx->ch, ioctx,
2236                                         SCST_CONTEXT_DIRECT);
2237                                 break;
2238                         case IB_WC_RDMA_WRITE:
2239                         case IB_WC_RDMA_READ:
2240                                 srpt_handle_rdma_comp(ioctx->ch, ioctx);
2241                                 break;
2242                         case IB_WC_RECV:
2243                                 srpt_handle_new_iu(ioctx->ch, ioctx);
2244                                 break;
2245                         default:
2246                                 break;
2247                         }
2248                         spin_lock_irq(&srpt_thread.thread_lock);
2249                 }
2250         }
2251         spin_unlock_irq(&srpt_thread.thread_lock);
2252
2253         return 0;
2254 }
2255
2256 /* SCST target template for the SRP target implementation. */
2257 static struct scst_tgt_template srpt_template = {
2258         .name = DRV_NAME,
2259         .sg_tablesize = SRPT_DEF_SG_TABLESIZE,
2260         .xmit_response_atomic = 1,
2261         .rdy_to_xfer_atomic = 1,
2262         .no_proc_entry = 1,
2263         .detect = srpt_detect,
2264         .release = srpt_release,
2265         .xmit_response = srpt_xmit_response,
2266         .rdy_to_xfer = srpt_rdy_to_xfer,
2267         .on_free_cmd = srpt_on_free_cmd,
2268         .task_mgmt_fn_done = srpt_tsk_mgmt_done
2269 };
2270
2271 /*
2272  * The callback function srpt_release_class_dev() is called whenever a
2273  * device is removed from the /sys/class/infiniband_srpt device class.
2274  */
2275 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2276 static void srpt_release_class_dev(struct class_device *class_dev)
2277 #else
2278 static void srpt_release_class_dev(struct device *dev)
2279 #endif
2280 {
2281 }
2282
2283 static struct class srpt_class = {
2284         .name = "infiniband_srpt",
2285 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2286         .release = srpt_release_class_dev
2287 #else
2288         .dev_release = srpt_release_class_dev
2289 #endif
2290 };
2291
2292 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2293 static ssize_t show_login_info(struct class_device *class_dev, char *buf)
2294 #else
2295 static ssize_t show_login_info(struct device *dev,
2296                                struct device_attribute *attr, char *buf)
2297 #endif
2298 {
2299         struct srpt_device *sdev =
2300 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2301                 container_of(class_dev, struct srpt_device, class_dev);
2302 #else
2303                 container_of(dev, struct srpt_device, dev);
2304 #endif
2305         struct srpt_port *sport;
2306         int i;
2307         int len = 0;
2308
2309         for (i = 0; i < sdev->device->phys_port_cnt; i++) {
2310                 sport = &sdev->port[i];
2311
2312                 len += sprintf(buf + len,
2313                                "tid_ext=%016llx,ioc_guid=%016llx,pkey=ffff,"
2314                                "dgid=%04x%04x%04x%04x%04x%04x%04x%04x,"
2315                                "service_id=%016llx\n",
2316                                (unsigned long long) mellanox_ioc_guid,
2317                                (unsigned long long) mellanox_ioc_guid,
2318                                be16_to_cpu(((__be16 *) sport->gid.raw)[0]),
2319                                be16_to_cpu(((__be16 *) sport->gid.raw)[1]),
2320                                be16_to_cpu(((__be16 *) sport->gid.raw)[2]),
2321                                be16_to_cpu(((__be16 *) sport->gid.raw)[3]),
2322                                be16_to_cpu(((__be16 *) sport->gid.raw)[4]),
2323                                be16_to_cpu(((__be16 *) sport->gid.raw)[5]),
2324                                be16_to_cpu(((__be16 *) sport->gid.raw)[6]),
2325                                be16_to_cpu(((__be16 *) sport->gid.raw)[7]),
2326                                (unsigned long long) mellanox_ioc_guid);
2327         }
2328
2329         return len;
2330 }
2331
2332 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2333 static CLASS_DEVICE_ATTR(login_info, S_IRUGO, show_login_info, NULL);
2334 #else
2335 static DEVICE_ATTR(login_info, S_IRUGO, show_login_info, NULL);
2336 #endif
2337
2338 /*
2339  * Callback function called by the InfiniBand core when either an InfiniBand
2340  * device has been added or during the ib_register_client() call for each
2341  * registered InfiniBand device.
2342  */
2343 static void srpt_add_one(struct ib_device *device)
2344 {
2345         struct srpt_device *sdev;
2346         struct ib_srq_init_attr srq_attr;
2347         int i;
2348
2349         sdev = kzalloc(sizeof *sdev, GFP_KERNEL);
2350         if (!sdev)
2351                 return;
2352
2353         sdev->device = device;
2354         init_completion(&sdev->scst_released);
2355
2356 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2357         sdev->class_dev.class = &srpt_class;
2358         sdev->class_dev.dev = device->dma_device;
2359         snprintf(sdev->class_dev.class_id, BUS_ID_SIZE,
2360                  "srpt-%s", device->name);
2361 #else
2362         sdev->dev.class = &srpt_class;
2363         sdev->dev.parent = device->dma_device;
2364         snprintf(sdev->dev.bus_id, BUS_ID_SIZE, "srpt-%s", device->name);
2365 #endif
2366
2367 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2368         if (class_device_register(&sdev->class_dev))
2369                 goto free_dev;
2370         if (class_device_create_file(&sdev->class_dev,
2371                                      &class_device_attr_login_info))
2372                 goto err_dev;
2373 #else
2374         if (device_register(&sdev->dev))
2375                 goto free_dev;
2376         if (device_create_file(&sdev->dev, &dev_attr_login_info))
2377                 goto err_dev;
2378 #endif
2379
2380         if (ib_query_device(device, &sdev->dev_attr))
2381                 goto err_dev;
2382
2383         sdev->pd = ib_alloc_pd(device);
2384         if (IS_ERR(sdev->pd))
2385                 goto err_dev;
2386
2387         sdev->mr = ib_get_dma_mr(sdev->pd, IB_ACCESS_LOCAL_WRITE);
2388         if (IS_ERR(sdev->mr))
2389                 goto err_pd;
2390
2391         srq_attr.event_handler = srpt_srq_event;
2392         srq_attr.srq_context = (void *)sdev;
2393         srq_attr.attr.max_wr = min(SRPT_SRQ_SIZE, sdev->dev_attr.max_srq_wr);
2394         srq_attr.attr.max_sge = 1;
2395         srq_attr.attr.srq_limit = 0;
2396
2397         sdev->srq = ib_create_srq(sdev->pd, &srq_attr);
2398         if (IS_ERR(sdev->srq))
2399                 goto err_mr;
2400
2401         printk(KERN_DEBUG PFX "%s: create SRQ #wr= %d max_allow=%d dev= %s\n",
2402                __func__, srq_attr.attr.max_wr,
2403               sdev->dev_attr.max_srq_wr, device->name);
2404
2405         if (!mellanox_ioc_guid)
2406                 mellanox_ioc_guid = be64_to_cpu(device->node_guid);
2407
2408         sdev->cm_id = ib_create_cm_id(device, srpt_cm_handler, sdev);
2409         if (IS_ERR(sdev->cm_id))
2410                 goto err_srq;
2411
2412         /* print out target login information */
2413         printk(KERN_DEBUG PFX "Target login info: id_ext=%016llx,"
2414                 "ioc_guid=%016llx,pkey=ffff,service_id=%016llx\n",
2415                 (unsigned long long) mellanox_ioc_guid,
2416                 (unsigned long long) mellanox_ioc_guid,
2417                 (unsigned long long) mellanox_ioc_guid);
2418
2419         /*
2420          * We do not have a consistent service_id (ie. also id_ext of target_id)
2421          * to identify this target. We currently use the guid of the first HCA
2422          * in the system as service_id; therefore, the target_id will change
2423          * if this HCA is gone bad and replaced by different HCA
2424          */
2425         if (ib_cm_listen(sdev->cm_id, cpu_to_be64(mellanox_ioc_guid), 0, NULL))
2426                 goto err_cm;
2427
2428         INIT_IB_EVENT_HANDLER(&sdev->event_handler, sdev->device,
2429                               srpt_event_handler);
2430         if (ib_register_event_handler(&sdev->event_handler))
2431                 goto err_cm;
2432
2433         if (srpt_alloc_ioctx_ring(sdev))
2434                 goto err_event;
2435
2436         INIT_LIST_HEAD(&sdev->rch_list);
2437         spin_lock_init(&sdev->spinlock);
2438
2439         for (i = 0; i < SRPT_SRQ_SIZE; ++i)
2440                 srpt_post_recv(sdev, sdev->ioctx_ring[i]);
2441
2442         list_add_tail(&sdev->list, &srpt_devices);
2443
2444         ib_set_client_data(device, &srpt_client, sdev);
2445
2446         return;
2447
2448 err_event:
2449         ib_unregister_event_handler(&sdev->event_handler);
2450 err_cm:
2451         ib_destroy_cm_id(sdev->cm_id);
2452 err_srq:
2453         ib_destroy_srq(sdev->srq);
2454 err_mr:
2455         ib_dereg_mr(sdev->mr);
2456 err_pd:
2457         ib_dealloc_pd(sdev->pd);
2458 err_dev:
2459 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2460         class_device_unregister(&sdev->class_dev);
2461 #else
2462         device_unregister(&sdev->dev);
2463 #endif
2464 free_dev:
2465         kfree(sdev);
2466 }
2467
2468 /*
2469  * Callback function called by the InfiniBand core when either an InfiniBand
2470  * device has been removed or during the ib_unregister_client() call for each
2471  * registered InfiniBand device.
2472  */
2473 static void srpt_remove_one(struct ib_device *device)
2474 {
2475         struct srpt_device *sdev;
2476         int i;
2477
2478         sdev = ib_get_client_data(device, &srpt_client);
2479         if (!sdev)
2480                 return;
2481
2482         wait_for_completion(&sdev->scst_released);
2483
2484         ib_unregister_event_handler(&sdev->event_handler);
2485         ib_destroy_cm_id(sdev->cm_id);
2486         ib_destroy_srq(sdev->srq);
2487         ib_dereg_mr(sdev->mr);
2488         ib_dealloc_pd(sdev->pd);
2489 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2490         class_device_unregister(&sdev->class_dev);
2491 #else
2492         device_unregister(&sdev->dev);
2493 #endif
2494
2495         for (i = 0; i < SRPT_SRQ_SIZE; ++i)
2496                 srpt_free_ioctx(sdev, sdev->ioctx_ring[i]);
2497
2498         list_del(&sdev->list);
2499         kfree(sdev);
2500 }
2501
2502 static int __init srpt_init_module(void)
2503 {
2504         int ret;
2505
2506         INIT_LIST_HEAD(&srpt_devices);
2507
2508         ret = class_register(&srpt_class);
2509         if (ret) {
2510                 printk(KERN_ERR PFX "couldn't register class ib_srpt\n");
2511                 return ret;
2512         }
2513
2514         ret = ib_register_client(&srpt_client);
2515         if (ret) {
2516                 printk(KERN_ERR PFX "couldn't register IB client\n");
2517                 goto mem_out;
2518         }
2519
2520         ret = scst_register_target_template(&srpt_template);
2521         if (ret < 0) {
2522                 printk(KERN_ERR PFX "couldn't register with scst\n");
2523                 ret = -ENODEV;
2524                 goto ib_out;
2525         }
2526
2527         if (thread) {
2528                 spin_lock_init(&srpt_thread.thread_lock);
2529                 INIT_LIST_HEAD(&srpt_thread.thread_ioctx_list);
2530                 srpt_thread.thread = kthread_run(srpt_ioctx_thread,
2531                                                  NULL, "srpt_thread");
2532                 if (IS_ERR(srpt_thread.thread)) {
2533                         srpt_thread.thread = NULL;
2534                         thread = 0;
2535                 }
2536         }
2537
2538         return 0;
2539
2540 ib_out:
2541         ib_unregister_client(&srpt_client);
2542 mem_out:
2543         class_unregister(&srpt_class);
2544         return ret;
2545 }
2546
2547 static void __exit srpt_cleanup_module(void)
2548 {
2549         if (srpt_thread.thread)
2550                 kthread_stop(srpt_thread.thread);
2551         scst_unregister_target_template(&srpt_template);
2552         ib_unregister_client(&srpt_client);
2553         class_unregister(&srpt_class);
2554 }
2555
2556 module_init(srpt_init_module);
2557 module_exit(srpt_cleanup_module);