Moved the code for freeing the ring of I/O context structures to a separate function.
[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 /* Free the ring of SRPT I/O context structures. */
586 static void srpt_free_ioctx_ring(struct srpt_device *sdev)
587 {
588         int i;
589
590         for (i = 0; i < SRPT_SRQ_SIZE; ++i) {
591                 srpt_free_ioctx(sdev, sdev->ioctx_ring[i]);
592                 sdev->ioctx_ring[i] = NULL;
593         }
594 }
595
596 /*
597  * Post a receive request on the work queue of InfiniBand device 'sdev'.
598  */
599 static int srpt_post_recv(struct srpt_device *sdev, struct srpt_ioctx *ioctx)
600 {
601         struct ib_sge list;
602         struct ib_recv_wr wr, *bad_wr;
603
604         wr.wr_id = ioctx->index | SRPT_OP_RECV;
605
606         list.addr = ioctx->dma;
607         list.length = MAX_MESSAGE_SIZE;
608         list.lkey = sdev->mr->lkey;
609
610         wr.next = NULL;
611         wr.sg_list = &list;
612         wr.num_sge = 1;
613
614         return ib_post_srq_recv(sdev->srq, &wr, &bad_wr);
615 }
616
617 /*
618  * Post a send request on the SRPT RDMA channel 'ch'.
619  */
620 static int srpt_post_send(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx,
621                           int len)
622 {
623         struct ib_sge list;
624         struct ib_send_wr wr, *bad_wr;
625         struct srpt_device *sdev = ch->sport->sdev;
626
627         dma_sync_single_for_device(sdev->device->dma_device, ioctx->dma,
628                                    MAX_MESSAGE_SIZE, DMA_TO_DEVICE);
629
630         list.addr = ioctx->dma;
631         list.length = len;
632         list.lkey = sdev->mr->lkey;
633
634         wr.next = NULL;
635         wr.wr_id = ioctx->index;
636         wr.sg_list = &list;
637         wr.num_sge = 1;
638         wr.opcode = IB_WR_SEND;
639         wr.send_flags = IB_SEND_SIGNALED;
640
641         return ib_post_send(ch->qp, &wr, &bad_wr);
642 }
643
644 static int srpt_get_desc_tbl(struct srpt_ioctx *ioctx, struct srp_cmd *srp_cmd,
645                              int *ind)
646 {
647         struct srp_indirect_buf *idb;
648         struct srp_direct_buf *db;
649
650         *ind = 0;
651         if (((srp_cmd->buf_fmt & 0xf) == SRP_DATA_DESC_DIRECT) ||
652             ((srp_cmd->buf_fmt >> 4) == SRP_DATA_DESC_DIRECT)) {
653                 ioctx->n_rbuf = 1;
654                 ioctx->rbufs = &ioctx->single_rbuf;
655
656                 db = (void *)srp_cmd->add_data;
657                 memcpy(ioctx->rbufs, db, sizeof *db);
658                 ioctx->data_len = be32_to_cpu(db->len);
659         } else {
660                 idb = (void *)srp_cmd->add_data;
661
662                 ioctx->n_rbuf = be32_to_cpu(idb->table_desc.len) / sizeof *db;
663
664                 if (ioctx->n_rbuf >
665                     (srp_cmd->data_out_desc_cnt + srp_cmd->data_in_desc_cnt)) {
666                         *ind = 1;
667                         ioctx->n_rbuf = 0;
668                         goto out;
669                 }
670
671                 if (ioctx->n_rbuf == 1)
672                         ioctx->rbufs = &ioctx->single_rbuf;
673                 else
674                         ioctx->rbufs =
675                                 kmalloc(ioctx->n_rbuf * sizeof *db, GFP_ATOMIC);
676                 if (!ioctx->rbufs) {
677                         ioctx->n_rbuf = 0;
678                         return -ENOMEM;
679                 }
680
681                 db = idb->desc_list;
682                 memcpy(ioctx->rbufs, db, ioctx->n_rbuf * sizeof *db);
683                 ioctx->data_len = be32_to_cpu(idb->len);
684         }
685 out:
686         return 0;
687 }
688
689 /*
690  * Modify the attributes of queue pair 'qp': allow local write, remote read,
691  * and remote write. Also transition 'qp' to state IB_QPS_INIT.
692  */
693 static int srpt_init_ch_qp(struct srpt_rdma_ch *ch, struct ib_qp *qp)
694 {
695         struct ib_qp_attr *attr;
696         int ret;
697
698         attr = kzalloc(sizeof *attr, GFP_KERNEL);
699         if (!attr)
700                 return -ENOMEM;
701
702         attr->qp_state = IB_QPS_INIT;
703         attr->qp_access_flags = IB_ACCESS_LOCAL_WRITE | IB_ACCESS_REMOTE_READ |
704             IB_ACCESS_REMOTE_WRITE;
705         attr->port_num = ch->sport->port;
706         attr->pkey_index = 0;
707
708         ret = ib_modify_qp(qp, attr,
709                            IB_QP_STATE | IB_QP_ACCESS_FLAGS | IB_QP_PORT |
710                            IB_QP_PKEY_INDEX);
711
712         kfree(attr);
713         return ret;
714 }
715
716 static int srpt_ch_qp_rtr_rts(struct srpt_rdma_ch *ch, struct ib_qp *qp,
717                               enum ib_qp_state qp_state)
718 {
719         struct ib_qp_attr *qp_attr;
720         int attr_mask;
721         int ret;
722
723         qp_attr = kmalloc(sizeof *qp_attr, GFP_KERNEL);
724         if (!qp_attr)
725                 return -ENOMEM;
726
727         qp_attr->qp_state = qp_state;
728         ret = ib_cm_init_qp_attr(ch->cm_id, qp_attr, &attr_mask);
729         if (ret)
730                 goto out;
731
732         if (qp_state == IB_QPS_RTR)
733                 qp_attr->max_dest_rd_atomic = 4;
734         else
735                 qp_attr->max_rd_atomic = 4;
736
737         ret = ib_modify_qp(qp, qp_attr, attr_mask);
738
739 out:
740         kfree(qp_attr);
741         return ret;
742 }
743
744 static void srpt_reset_ioctx(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx)
745 {
746         int i;
747
748         if (ioctx->n_rdma_ius > 0 && ioctx->rdma_ius) {
749                 struct rdma_iu *riu = ioctx->rdma_ius;
750
751                 for (i = 0; i < ioctx->n_rdma_ius; ++i, ++riu)
752                         kfree(riu->sge);
753                 kfree(ioctx->rdma_ius);
754         }
755
756         if (ioctx->n_rbuf > 1)
757                 kfree(ioctx->rbufs);
758
759         if (srpt_post_recv(ch->sport->sdev, ioctx))
760                 printk(KERN_ERR PFX "SRQ post_recv failed - this is serious\n");
761                 /* we should queue it back to free_ioctx queue */
762         else
763                 atomic_inc(&ch->req_lim_delta);
764 }
765
766 static void srpt_handle_err_comp(struct srpt_rdma_ch *ch, struct ib_wc *wc)
767 {
768         struct srpt_ioctx *ioctx;
769         struct srpt_device *sdev = ch->sport->sdev;
770         scst_data_direction dir = SCST_DATA_NONE;
771
772         if (wc->wr_id & SRPT_OP_RECV) {
773                 ioctx = sdev->ioctx_ring[wc->wr_id & ~SRPT_OP_RECV];
774                 printk(KERN_ERR PFX "This is serious - SRQ is in bad state\n");
775         } else {
776                 ioctx = sdev->ioctx_ring[wc->wr_id];
777
778                 if (ioctx->scmnd) {
779                         struct scst_cmd *scmnd = ioctx->scmnd;
780
781                         dir = scst_cmd_get_data_direction(scmnd);
782
783                         if (dir == SCST_DATA_NONE)
784                                 scst_tgt_cmd_done(scmnd,
785                                         scst_estimate_context());
786                         else {
787                                 dma_unmap_sg(sdev->device->dma_device,
788                                              scst_cmd_get_sg(scmnd),
789                                              scst_cmd_get_sg_cnt(scmnd),
790                                              scst_to_tgt_dma_dir(dir));
791
792                                 if (scmnd->state == SCST_CMD_STATE_DATA_WAIT)
793                                         scst_rx_data(scmnd,
794                                                      SCST_RX_STATUS_ERROR,
795                                                      SCST_CONTEXT_THREAD);
796                                 else if (scmnd->state == SCST_CMD_STATE_XMIT_WAIT)
797                                         scst_tgt_cmd_done(scmnd,
798                                                 scst_estimate_context());
799                         }
800                 } else
801                         srpt_reset_ioctx(ch, ioctx);
802         }
803 }
804
805 static void srpt_handle_send_comp(struct srpt_rdma_ch *ch,
806                                   struct srpt_ioctx *ioctx,
807                                   enum scst_exec_context context)
808 {
809         if (ioctx->scmnd) {
810                 scst_data_direction dir =
811                         scst_cmd_get_data_direction(ioctx->scmnd);
812
813                 if (dir != SCST_DATA_NONE)
814                         dma_unmap_sg(ch->sport->sdev->device->dma_device,
815                                      scst_cmd_get_sg(ioctx->scmnd),
816                                      scst_cmd_get_sg_cnt(ioctx->scmnd),
817                                      scst_to_tgt_dma_dir(dir));
818
819                 scst_tgt_cmd_done(ioctx->scmnd, context);
820         } else
821                 srpt_reset_ioctx(ch, ioctx);
822 }
823
824 static void srpt_handle_rdma_comp(struct srpt_rdma_ch *ch,
825                                   struct srpt_ioctx *ioctx)
826 {
827         if (!ioctx->scmnd) {
828                 srpt_reset_ioctx(ch, ioctx);
829                 return;
830         }
831
832         if (scst_cmd_get_data_direction(ioctx->scmnd) == SCST_DATA_WRITE)
833                 scst_rx_data(ioctx->scmnd, SCST_RX_STATUS_SUCCESS,
834                         scst_estimate_context());
835 }
836
837 static void srpt_build_cmd_rsp(struct srpt_rdma_ch *ch,
838                                struct srpt_ioctx *ioctx, u8 s_key, u8 s_code,
839                                u64 tag)
840 {
841         struct srp_rsp *srp_rsp;
842         struct sense_data *sense;
843         int limit_delta;
844
845         srp_rsp = ioctx->buf;
846         memset(srp_rsp, 0, sizeof *srp_rsp);
847
848         limit_delta = atomic_read(&ch->req_lim_delta);
849         atomic_sub(limit_delta, &ch->req_lim_delta);
850
851         srp_rsp->opcode = SRP_RSP;
852         srp_rsp->req_lim_delta = cpu_to_be32(limit_delta);
853         srp_rsp->tag = tag;
854
855         if (s_key != NO_SENSE) {
856                 srp_rsp->flags |= SRP_RSP_FLAG_SNSVALID;
857                 srp_rsp->status = SAM_STAT_CHECK_CONDITION;
858                 srp_rsp->sense_data_len =
859                     cpu_to_be32(sizeof *sense + (sizeof *sense % 4));
860
861                 sense = (struct sense_data *)(srp_rsp + 1);
862                 sense->err_code = 0x70;
863                 sense->key = s_key;
864                 sense->asc_ascq = s_code;
865         }
866 }
867
868 static void srpt_build_tskmgmt_rsp(struct srpt_rdma_ch *ch,
869                                    struct srpt_ioctx *ioctx, u8 rsp_code,
870                                    u64 tag)
871 {
872         struct srp_rsp *srp_rsp;
873         int limit_delta;
874
875         dma_sync_single_for_cpu(ch->sport->sdev->device->dma_device, ioctx->dma,
876                                 MAX_MESSAGE_SIZE, DMA_TO_DEVICE);
877
878         srp_rsp = ioctx->buf;
879         memset(srp_rsp, 0, sizeof *srp_rsp);
880
881         limit_delta = atomic_read(&ch->req_lim_delta);
882         atomic_sub(limit_delta, &ch->req_lim_delta);
883
884         srp_rsp->opcode = SRP_RSP;
885         srp_rsp->req_lim_delta = cpu_to_be32(limit_delta);
886         srp_rsp->tag = tag;
887
888         if (rsp_code != SRP_TSK_MGMT_SUCCESS) {
889                 srp_rsp->flags |= SRP_RSP_FLAG_RSPVALID;
890                 srp_rsp->resp_data_len = cpu_to_be32(4);
891                 srp_rsp->data[3] = rsp_code;
892         }
893 }
894
895 /*
896  * Process SRP_CMD.
897  */
898 static int srpt_handle_cmd(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx)
899 {
900         struct scst_cmd *scmnd = NULL;
901         struct srp_cmd *srp_cmd = NULL;
902         scst_data_direction dir = SCST_DATA_NONE;
903         int indirect_desc = 0;
904         int ret;
905
906         srp_cmd = ioctx->buf;
907
908         if (srp_cmd->buf_fmt) {
909                 ret = srpt_get_desc_tbl(ioctx, srp_cmd, &indirect_desc);
910                 if (ret) {
911                         srpt_build_cmd_rsp(ch, ioctx, NO_SENSE,
912                                            NO_ADD_SENSE, srp_cmd->tag);
913                         ((struct srp_rsp *)ioctx->buf)->status =
914                                         SAM_STAT_TASK_SET_FULL;
915                         goto send_rsp;
916                 }
917
918                 if (indirect_desc) {
919                         srpt_build_cmd_rsp(ch, ioctx, NO_SENSE,
920                                            NO_ADD_SENSE, srp_cmd->tag);
921                         ((struct srp_rsp *)ioctx->buf)->status =
922                                         SAM_STAT_TASK_SET_FULL;
923                         goto send_rsp;
924                 }
925
926                 if (srp_cmd->buf_fmt & 0xf)
927                         dir = SCST_DATA_READ;
928                 else if (srp_cmd->buf_fmt >> 4)
929                         dir = SCST_DATA_WRITE;
930                 else
931                         dir = SCST_DATA_NONE;
932         } else
933                 dir = SCST_DATA_NONE;
934
935         scmnd = scst_rx_cmd(ch->scst_sess, (u8 *) &srp_cmd->lun,
936                             sizeof srp_cmd->lun, srp_cmd->cdb, 16,
937                             thread ? SCST_NON_ATOMIC : SCST_ATOMIC);
938         if (!scmnd) {
939                 srpt_build_cmd_rsp(ch, ioctx, NO_SENSE,
940                                    NO_ADD_SENSE, srp_cmd->tag);
941                 ((struct srp_rsp *)ioctx->buf)->status =
942                         SAM_STAT_TASK_SET_FULL;
943                 goto send_rsp;
944         }
945
946         ioctx->scmnd = scmnd;
947
948         switch (srp_cmd->task_attr) {
949         case SRP_CMD_HEAD_OF_Q:
950                 scmnd->queue_type = SCST_CMD_QUEUE_HEAD_OF_QUEUE;
951                 break;
952         case SRP_CMD_ORDERED_Q:
953                 scmnd->queue_type = SCST_CMD_QUEUE_ORDERED;
954                 break;
955         case SRP_CMD_SIMPLE_Q:
956                 scmnd->queue_type = SCST_CMD_QUEUE_SIMPLE;
957                 break;
958         case SRP_CMD_ACA:
959                 scmnd->queue_type = SCST_CMD_QUEUE_ACA;
960                 break;
961         default:
962                 scmnd->queue_type = SCST_CMD_QUEUE_ORDERED;
963                 break;
964         }
965
966         scst_cmd_set_tag(scmnd, srp_cmd->tag);
967         scst_cmd_set_tgt_priv(scmnd, ioctx);
968         scst_cmd_set_expected(scmnd, dir, ioctx->data_len);
969
970         spin_lock_irq(&ch->spinlock);
971         list_add_tail(&ioctx->scmnd_list, &ch->active_scmnd_list);
972         ch->active_scmnd_cnt++;
973         spin_unlock_irq(&ch->spinlock);
974
975         scst_cmd_init_done(scmnd, scst_estimate_context());
976
977         return 0;
978
979 send_rsp:
980         return -1;
981 }
982
983 /*
984  * Process SRP_TSK_MGMT. See also table 19 in the T10 SRP r16a document.
985  */
986 static int srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,
987                                 struct srpt_ioctx *ioctx)
988 {
989         struct srp_tsk_mgmt *srp_tsk = NULL;
990         struct srpt_mgmt_ioctx *mgmt_ioctx;
991         int ret;
992
993         srp_tsk = ioctx->buf;
994
995         printk(KERN_WARNING PFX
996                "recv_tsk_mgmt= %d for task_tag= %lld"
997                " using tag= %lld cm_id= %p sess= %p\n",
998                srp_tsk->tsk_mgmt_func,
999                (unsigned long long) srp_tsk->task_tag,
1000                (unsigned long long) srp_tsk->tag,
1001                ch->cm_id, ch->scst_sess);
1002
1003         mgmt_ioctx = kmalloc(sizeof *mgmt_ioctx, GFP_ATOMIC);
1004         if (!mgmt_ioctx) {
1005                 srpt_build_tskmgmt_rsp(ch, ioctx, SRP_TSK_MGMT_FAILED,
1006                                        srp_tsk->tag);
1007                 goto send_rsp;
1008         }
1009
1010         mgmt_ioctx->ioctx = ioctx;
1011         mgmt_ioctx->ch = ch;
1012         mgmt_ioctx->tag = srp_tsk->tag;
1013
1014         switch (srp_tsk->tsk_mgmt_func) {
1015         case SRP_TSK_ABORT_TASK:
1016                 ret = scst_rx_mgmt_fn_tag(ch->scst_sess,
1017                                           SCST_ABORT_TASK,
1018                                           srp_tsk->task_tag,
1019                                           thread ?
1020                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1021                                           mgmt_ioctx);
1022                 break;
1023         case SRP_TSK_ABORT_TASK_SET:
1024                 ret = scst_rx_mgmt_fn_lun(ch->scst_sess,
1025                                           SCST_ABORT_TASK_SET,
1026                                           (u8 *) &srp_tsk->lun,
1027                                           sizeof srp_tsk->lun,
1028                                           thread ?
1029                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1030                                           mgmt_ioctx);
1031                 break;
1032         case SRP_TSK_CLEAR_TASK_SET:
1033                 ret = scst_rx_mgmt_fn_lun(ch->scst_sess,
1034                                           SCST_CLEAR_TASK_SET,
1035                                           (u8 *) &srp_tsk->lun,
1036                                           sizeof srp_tsk->lun,
1037                                           thread ?
1038                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1039                                           mgmt_ioctx);
1040                 break;
1041 #if 0
1042         case SRP_TSK_LUN_RESET:
1043                 ret = scst_rx_mgmt_fn_lun(ch->scst_sess,
1044                                           SCST_LUN_RESET,
1045                                           (u8 *) &srp_tsk->lun,
1046                                           sizeof srp_tsk->lun,
1047                                           thread ?
1048                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1049                                           mgmt_ioctx);
1050                 break;
1051 #endif
1052         case SRP_TSK_CLEAR_ACA:
1053                 ret = scst_rx_mgmt_fn_lun(ch->scst_sess,
1054                                           SCST_CLEAR_ACA,
1055                                           (u8 *) &srp_tsk->lun,
1056                                           sizeof srp_tsk->lun,
1057                                           thread ?
1058                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1059                                           mgmt_ioctx);
1060                 break;
1061         default:
1062                 srpt_build_tskmgmt_rsp(ch, ioctx,
1063                                        SRP_TSK_MGMT_FUNC_NOT_SUPP,
1064                                        srp_tsk->tag);
1065                 goto send_rsp;
1066         }
1067         return 0;
1068
1069 send_rsp:
1070         return -1;
1071 }
1072
1073 static void srpt_handle_new_iu(struct srpt_rdma_ch *ch,
1074                                struct srpt_ioctx *ioctx)
1075 {
1076         u8 op;
1077
1078         if (ch->state != RDMA_CHANNEL_LIVE) {
1079                 if (ch->state == RDMA_CHANNEL_CONNECTING) {
1080                         spin_lock_irq(&ch->spinlock);
1081                         list_add_tail(&ioctx->wait_list, &ch->cmd_wait_list);
1082                         spin_unlock_irq(&ch->spinlock);
1083                 } else
1084                         srpt_reset_ioctx(ch, ioctx);
1085
1086                 return;
1087         }
1088
1089         dma_sync_single_for_cpu(ch->sport->sdev->device->dma_device, ioctx->dma,
1090                                 MAX_MESSAGE_SIZE, DMA_FROM_DEVICE);
1091
1092         ioctx->data_len = 0;
1093         ioctx->n_rbuf = 0;
1094         ioctx->rbufs = NULL;
1095         ioctx->n_rdma = 0;
1096         ioctx->n_rdma_ius = 0;
1097         ioctx->rdma_ius = NULL;
1098         ioctx->scmnd = NULL;
1099
1100         op = *(u8 *) ioctx->buf;
1101         switch (op) {
1102         case SRP_CMD:
1103                 if (srpt_handle_cmd(ch, ioctx) < 0)
1104                         goto send_rsp;
1105                 break;
1106
1107         case SRP_TSK_MGMT:
1108                 if (srpt_handle_tsk_mgmt(ch, ioctx) < 0)
1109                         goto send_rsp;
1110                 break;
1111
1112         case SRP_I_LOGOUT:
1113         case SRP_AER_REQ:
1114         default:
1115                 srpt_build_cmd_rsp(ch, ioctx, ILLEGAL_REQUEST, INVALID_CDB,
1116                                    ((struct srp_cmd *)ioctx->buf)->tag);
1117
1118                 goto send_rsp;
1119         }
1120
1121         dma_sync_single_for_device(ch->sport->sdev->device->dma_device,
1122                                    ioctx->dma, MAX_MESSAGE_SIZE,
1123                                    DMA_FROM_DEVICE);
1124
1125         return;
1126
1127 send_rsp:
1128         if (ch->state != RDMA_CHANNEL_LIVE ||
1129             srpt_post_send(ch, ioctx,
1130                            sizeof(struct srp_rsp) +
1131                            be32_to_cpu(((struct srp_rsp *)ioctx->buf)->
1132                                        sense_data_len)))
1133                 srpt_reset_ioctx(ch, ioctx);
1134 }
1135
1136 /*
1137  * Returns true if the ioctx list is non-empty or if the ib_srpt kernel thread
1138  * should stop.
1139  * @pre thread != 0
1140  */
1141 static inline int srpt_test_ioctx_list(void)
1142 {
1143         int res = (!list_empty(&srpt_thread.thread_ioctx_list) ||
1144                    unlikely(kthread_should_stop()));
1145         return res;
1146 }
1147
1148 /*
1149  * Add 'ioctx' to the tail of the ioctx list and wake up the kernel thread.
1150  *
1151  * @pre thread != 0
1152  */
1153 static inline void srpt_schedule_thread(struct srpt_ioctx *ioctx)
1154 {
1155         unsigned long flags;
1156
1157         spin_lock_irqsave(&srpt_thread.thread_lock, flags);
1158         list_add_tail(&ioctx->comp_list, &srpt_thread.thread_ioctx_list);
1159         spin_unlock_irqrestore(&srpt_thread.thread_lock, flags);
1160         wake_up(&ioctx_list_waitQ);
1161 }
1162
1163 /*
1164  * InfiniBand CQ (completion queue) event handler for asynchronous events not
1165  * associated with a completion.
1166  */
1167 static void srpt_completion(struct ib_cq *cq, void *ctx)
1168 {
1169         struct srpt_rdma_ch *ch = ctx;
1170         struct srpt_device *sdev = ch->sport->sdev;
1171         struct ib_wc wc;
1172         struct srpt_ioctx *ioctx;
1173
1174         ib_req_notify_cq(ch->cq, IB_CQ_NEXT_COMP);
1175         while (ib_poll_cq(ch->cq, 1, &wc) > 0) {
1176                 if (wc.status) {
1177                         printk(KERN_ERR PFX "failed %s status= %d\n",
1178                                wc.wr_id & SRPT_OP_RECV ? "receive" : "send",
1179                                wc.status);
1180                         srpt_handle_err_comp(ch, &wc);
1181                         break;
1182                 }
1183
1184                 if (wc.wr_id & SRPT_OP_RECV) {
1185                         ioctx = sdev->ioctx_ring[wc.wr_id & ~SRPT_OP_RECV];
1186                         if (thread) {
1187                                 ioctx->ch = ch;
1188                                 ioctx->op = IB_WC_RECV;
1189                                 srpt_schedule_thread(ioctx);
1190                         } else
1191                                 srpt_handle_new_iu(ch, ioctx);
1192                         continue;
1193                 } else
1194                         ioctx = sdev->ioctx_ring[wc.wr_id];
1195
1196                 if (thread) {
1197                         ioctx->ch = ch;
1198                         ioctx->op = wc.opcode;
1199                         srpt_schedule_thread(ioctx);
1200                 } else {
1201                         switch (wc.opcode) {
1202                         case IB_WC_SEND:
1203                                 srpt_handle_send_comp(ch, ioctx,
1204                                         scst_estimate_context());
1205                                 break;
1206                         case IB_WC_RDMA_WRITE:
1207                         case IB_WC_RDMA_READ:
1208                                 srpt_handle_rdma_comp(ch, ioctx);
1209                                 break;
1210                         default:
1211                                 break;
1212                         }
1213                 }
1214         }
1215 }
1216
1217 /*
1218  * Create a completion queue on the specified device.
1219  */
1220 static int srpt_create_ch_ib(struct srpt_rdma_ch *ch)
1221 {
1222         struct ib_qp_init_attr *qp_init;
1223         struct srpt_device *sdev = ch->sport->sdev;
1224         int cqe;
1225         int ret;
1226
1227         qp_init = kzalloc(sizeof *qp_init, GFP_KERNEL);
1228         if (!qp_init)
1229                 return -ENOMEM;
1230
1231         /* Create a completion queue (CQ). */
1232
1233         cqe = SRPT_RQ_SIZE + SRPT_SQ_SIZE - 1;
1234 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20) && ! defined(RHEL_RELEASE_CODE)
1235         ch->cq = ib_create_cq(sdev->device, srpt_completion, NULL, ch, cqe);
1236 #else
1237         ch->cq = ib_create_cq(sdev->device, srpt_completion, NULL, ch, cqe, 0);
1238 #endif
1239         if (IS_ERR(ch->cq)) {
1240                 ret = PTR_ERR(ch->cq);
1241                 printk(KERN_ERR PFX "failed to create_cq cqe= %d ret= %d\n",
1242                         cqe, ret);
1243                 goto out;
1244         }
1245
1246         /* Request completion notification. */
1247
1248         ib_req_notify_cq(ch->cq, IB_CQ_NEXT_COMP);
1249
1250         /* Create a queue pair (QP). */
1251
1252         qp_init->qp_context = (void *)ch;
1253         qp_init->event_handler = srpt_qp_event;
1254         qp_init->send_cq = ch->cq;
1255         qp_init->recv_cq = ch->cq;
1256         qp_init->srq = sdev->srq;
1257         qp_init->sq_sig_type = IB_SIGNAL_REQ_WR;
1258         qp_init->qp_type = IB_QPT_RC;
1259         qp_init->cap.max_send_wr = SRPT_SQ_SIZE;
1260         qp_init->cap.max_send_sge = SRPT_DEF_SG_PER_WQE;
1261
1262         ch->qp = ib_create_qp(sdev->pd, qp_init);
1263         if (IS_ERR(ch->qp)) {
1264                 ret = PTR_ERR(ch->qp);
1265                 ib_destroy_cq(ch->cq);
1266                 printk(KERN_ERR PFX "failed to create_qp ret= %d\n", ret);
1267                 goto out;
1268         }
1269
1270         printk(KERN_DEBUG PFX "%s: max_cqe= %d max_sge= %d cm_id= %p\n",
1271                __func__, ch->cq->cqe, qp_init->cap.max_send_sge,
1272                ch->cm_id);
1273
1274         /* Modify the attributes and the state of queue pair ch->qp. */
1275
1276         ret = srpt_init_ch_qp(ch, ch->qp);
1277         if (ret) {
1278                 ib_destroy_qp(ch->qp);
1279                 ib_destroy_cq(ch->cq);
1280                 goto out;
1281         }
1282
1283         atomic_set(&ch->req_lim_delta, SRPT_RQ_SIZE);
1284 out:
1285         kfree(qp_init);
1286         return ret;
1287 }
1288
1289 static struct srpt_rdma_ch *srpt_find_channel(struct ib_cm_id *cm_id)
1290 {
1291         struct srpt_device *sdev = cm_id->context;
1292         struct srpt_rdma_ch *ch, *tmp_ch;
1293
1294         spin_lock_irq(&sdev->spinlock);
1295         list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list) {
1296                 if (ch->cm_id == cm_id) {
1297                         spin_unlock_irq(&sdev->spinlock);
1298                         return ch;
1299                 }
1300         }
1301
1302         spin_unlock_irq(&sdev->spinlock);
1303
1304         return NULL;
1305 }
1306
1307 static int srpt_release_channel(struct srpt_rdma_ch *ch, int destroy_cmid)
1308 {
1309         spin_lock_irq(&ch->sport->sdev->spinlock);
1310         list_del(&ch->list);
1311         spin_unlock_irq(&ch->sport->sdev->spinlock);
1312
1313         if (ch->cm_id && destroy_cmid) {
1314                 printk(KERN_WARNING PFX
1315                        "%s: destroy cm_id= %p\n", __func__, ch->cm_id);
1316                 ib_destroy_cm_id(ch->cm_id);
1317                 ch->cm_id = NULL;
1318         }
1319
1320         ib_destroy_qp(ch->qp);
1321         ib_destroy_cq(ch->cq);
1322
1323         if (ch->scst_sess) {
1324                 struct srpt_ioctx *ioctx, *ioctx_tmp;
1325
1326                 printk(KERN_WARNING PFX
1327                        "%s: release sess= %p sess_name= %s active_cmd= %d\n",
1328                        __func__, ch->scst_sess, ch->sess_name,
1329                        ch->active_scmnd_cnt);
1330
1331                 list_for_each_entry_safe(ioctx, ioctx_tmp,
1332                                          &ch->active_scmnd_list, scmnd_list) {
1333                         list_del(&ioctx->scmnd_list);
1334                         ch->active_scmnd_cnt--;
1335                 }
1336
1337                 scst_unregister_session(ch->scst_sess, 0, NULL);
1338                 ch->scst_sess = NULL;
1339         }
1340
1341         kfree(ch);
1342
1343         return destroy_cmid ? 0 : 1;
1344 }
1345
1346 static int srpt_disconnect_channel(struct srpt_rdma_ch *ch, int dreq)
1347 {
1348         spin_lock_irq(&ch->spinlock);
1349         ch->state = RDMA_CHANNEL_DISCONNECTING;
1350         spin_unlock_irq(&ch->spinlock);
1351
1352         if (dreq)
1353                 ib_send_cm_dreq(ch->cm_id, NULL, 0);
1354         else
1355                 ib_send_cm_drep(ch->cm_id, NULL, 0);
1356
1357         return 0;
1358 }
1359
1360 static int srpt_cm_req_recv(struct ib_cm_id *cm_id,
1361                             struct ib_cm_req_event_param *param,
1362                             void *private_data)
1363 {
1364         struct srpt_device *sdev = cm_id->context;
1365         struct srp_login_req *req;
1366         struct srp_login_rsp *rsp;
1367         struct srp_login_rej *rej;
1368         struct ib_cm_rep_param *rep_param;
1369         struct srpt_rdma_ch *ch, *tmp_ch;
1370         u32 it_iu_len;
1371         int ret = 0;
1372
1373         if (!sdev || !private_data)
1374                 return -EINVAL;
1375
1376         rsp = kzalloc(sizeof *rsp, GFP_KERNEL);
1377         rej = kzalloc(sizeof *rej, GFP_KERNEL);
1378         rep_param = kzalloc(sizeof *rep_param, GFP_KERNEL);
1379
1380         if (!rsp || !rej || !rep_param) {
1381                 ret = -ENOMEM;
1382                 goto out;
1383         }
1384
1385         req = (struct srp_login_req *)private_data;
1386
1387         it_iu_len = be32_to_cpu(req->req_it_iu_len);
1388
1389         printk(KERN_DEBUG PFX
1390                "Host login i_port_id=0x%llx:0x%llx t_port_id=0x%llx:0x%llx"
1391                " it_iu_len=%d\n",
1392                (unsigned long long)
1393                be64_to_cpu(*(u64 *)&req->initiator_port_id[0]),
1394                (unsigned long long)
1395                be64_to_cpu(*(u64 *)&req->initiator_port_id[8]),
1396                (unsigned long long)be64_to_cpu(*(u64 *)&req->target_port_id[0]),
1397                (unsigned long long)be64_to_cpu(*(u64 *)&req->target_port_id[8]),
1398                it_iu_len);
1399
1400         if (it_iu_len > MAX_MESSAGE_SIZE || it_iu_len < 64) {
1401                 rej->reason =
1402                     cpu_to_be32(SRP_LOGIN_REJ_REQ_IT_IU_LENGTH_TOO_LARGE);
1403                 ret = -EINVAL;
1404                 printk(KERN_WARNING PFX
1405                        "Reject invalid it_iu_len=%d\n", it_iu_len);
1406                 goto reject;
1407         }
1408
1409         if ((req->req_flags & 0x3) == SRP_MULTICHAN_SINGLE) {
1410                 rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_NO_CHAN;
1411
1412                 spin_lock_irq(&sdev->spinlock);
1413
1414                 list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list) {
1415                         if (!memcmp(ch->i_port_id, req->initiator_port_id, 16)
1416                             && !memcmp(ch->t_port_id, req->target_port_id, 16)
1417                             && param->port == ch->sport->port
1418                             && param->listen_id == ch->sport->sdev->cm_id
1419                             && ch->cm_id) {
1420                                 /* found an existing channel */
1421                                 printk(KERN_WARNING PFX
1422                                        "Found existing channel name= %s"
1423                                        " cm_id= %p state= %d\n",
1424                                        ch->sess_name, ch->cm_id, ch->state);
1425
1426                                 spin_unlock_irq(&sdev->spinlock);
1427
1428                                 rsp->rsp_flags =
1429                                     SRP_LOGIN_RSP_MULTICHAN_TERMINATED;
1430
1431                                 if (ch->state == RDMA_CHANNEL_LIVE)
1432                                         srpt_disconnect_channel(ch, 1);
1433                                 else if (ch->state == RDMA_CHANNEL_CONNECTING) {
1434                                         ib_send_cm_rej(ch->cm_id,
1435                                                        IB_CM_REJ_NO_RESOURCES,
1436                                                        NULL, 0, NULL, 0);
1437                                         srpt_release_channel(ch, 1);
1438                                 }
1439
1440                                 spin_lock_irq(&sdev->spinlock);
1441                         }
1442                 }
1443
1444                 spin_unlock_irq(&sdev->spinlock);
1445
1446         } else
1447                 rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_MAINTAINED;
1448
1449         if (((u64) (*(u64 *) req->target_port_id) !=
1450              cpu_to_be64(mellanox_ioc_guid)) ||
1451             ((u64) (*(u64 *) (req->target_port_id + 8)) !=
1452              cpu_to_be64(mellanox_ioc_guid))) {
1453                 rej->reason =
1454                     cpu_to_be32(SRP_LOGIN_REJ_UNABLE_ASSOCIATE_CHANNEL);
1455                 ret = -ENOMEM;
1456                 printk(KERN_WARNING PFX "Reject invalid target_port_id\n");
1457                 goto reject;
1458         }
1459
1460         ch = kzalloc(sizeof *ch, GFP_KERNEL);
1461         if (!ch) {
1462                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
1463                 printk(KERN_WARNING PFX "Reject failed allocate rdma_ch\n");
1464                 ret = -ENOMEM;
1465                 goto reject;
1466         }
1467
1468         spin_lock_init(&ch->spinlock);
1469         memcpy(ch->i_port_id, req->initiator_port_id, 16);
1470         memcpy(ch->t_port_id, req->target_port_id, 16);
1471         ch->sport = &sdev->port[param->port - 1];
1472         ch->cm_id = cm_id;
1473         ch->state = RDMA_CHANNEL_CONNECTING;
1474         INIT_LIST_HEAD(&ch->cmd_wait_list);
1475         INIT_LIST_HEAD(&ch->active_scmnd_list);
1476
1477         ret = srpt_create_ch_ib(ch);
1478         if (ret) {
1479                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
1480                 printk(KERN_WARNING PFX "Reject failed to create rdma_ch\n");
1481                 goto free_ch;
1482         }
1483
1484         ret = srpt_ch_qp_rtr_rts(ch, ch->qp, IB_QPS_RTR);
1485         if (ret) {
1486                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
1487                 printk(KERN_WARNING PFX
1488                        "Reject failed qp to rtr/rts ret=%d\n", ret);
1489                 goto destroy_ib;
1490         }
1491
1492         sprintf(ch->sess_name, "0x%016llx%016llx",
1493                 (unsigned long long)be64_to_cpu(*(u64 *)ch->i_port_id),
1494                 (unsigned long long)be64_to_cpu(*(u64 *)(ch->i_port_id + 8)));
1495
1496         ch->scst_sess = scst_register_session(sdev->scst_tgt, 0, ch->sess_name,
1497                                   NULL, NULL);
1498         if (!ch->scst_sess) {
1499                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
1500                 printk(KERN_WARNING PFX "Failed to create scst sess\n");
1501                 goto destroy_ib;
1502         }
1503
1504         spin_lock_irq(&sdev->spinlock);
1505         list_add_tail(&ch->list, &sdev->rch_list);
1506         spin_unlock_irq(&sdev->spinlock);
1507
1508         printk(KERN_DEBUG PFX "Establish connection sess=%p name=%s cm_id=%p\n",
1509                ch->scst_sess, ch->sess_name, ch->cm_id);
1510
1511         scst_sess_set_tgt_priv(ch->scst_sess, ch);
1512
1513         /* create srp_login_response */
1514         rsp->opcode = SRP_LOGIN_RSP;
1515         rsp->tag = req->tag;
1516         rsp->max_it_iu_len = req->req_it_iu_len;
1517         rsp->max_ti_iu_len = req->req_it_iu_len;
1518         rsp->buf_fmt =
1519             cpu_to_be16(SRP_BUF_FORMAT_DIRECT | SRP_BUF_FORMAT_INDIRECT);
1520         rsp->req_lim_delta = cpu_to_be32(SRPT_RQ_SIZE);
1521         atomic_set(&ch->req_lim_delta, 0);
1522
1523         /* create cm reply */
1524         rep_param->qp_num = ch->qp->qp_num;
1525         rep_param->private_data = (void *)rsp;
1526         rep_param->private_data_len = sizeof *rsp;
1527         rep_param->rnr_retry_count = 7;
1528         rep_param->flow_control = 1;
1529         rep_param->failover_accepted = 0;
1530         rep_param->srq = 1;
1531         rep_param->responder_resources = 4;
1532         rep_param->initiator_depth = 4;
1533
1534         ret = ib_send_cm_rep(cm_id, rep_param);
1535         if (ret)
1536                 srpt_release_channel(ch, 0);
1537
1538         goto out;
1539
1540 destroy_ib:
1541         ib_destroy_qp(ch->qp);
1542         ib_destroy_cq(ch->cq);
1543
1544 free_ch:
1545         kfree(ch);
1546
1547 reject:
1548         rej->opcode = SRP_LOGIN_REJ;
1549         rej->tag = req->tag;
1550         rej->buf_fmt =
1551             cpu_to_be16(SRP_BUF_FORMAT_DIRECT | SRP_BUF_FORMAT_INDIRECT);
1552
1553         ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0,
1554                              (void *)rej, sizeof *rej);
1555
1556 out:
1557         kfree(rep_param);
1558         kfree(rsp);
1559         kfree(rej);
1560
1561         return ret;
1562 }
1563
1564 static int srpt_find_and_release_channel(struct ib_cm_id *cm_id)
1565 {
1566         struct srpt_rdma_ch *ch;
1567
1568         ch = srpt_find_channel(cm_id);
1569         if (!ch)
1570                 return -EINVAL;
1571
1572         return srpt_release_channel(ch, 0);
1573 }
1574
1575 static int srpt_cm_rej_recv(struct ib_cm_id *cm_id)
1576 {
1577         printk(KERN_DEBUG PFX "%s: cm_id=%p\n", __func__, cm_id);
1578         return srpt_find_and_release_channel(cm_id);
1579 }
1580
1581 static int srpt_cm_rtu_recv(struct ib_cm_id *cm_id)
1582 {
1583         struct srpt_rdma_ch *ch;
1584         int ret;
1585
1586         ch = srpt_find_channel(cm_id);
1587         if (!ch)
1588                 return -EINVAL;
1589
1590         if (ch->state == RDMA_CHANNEL_CONNECTING) {
1591                 struct srpt_ioctx *ioctx, *ioctx_tmp;
1592
1593                 spin_lock_irq(&ch->spinlock);
1594                 ch->state = RDMA_CHANNEL_LIVE;
1595                 spin_unlock_irq(&ch->spinlock);
1596                 ret = srpt_ch_qp_rtr_rts(ch, ch->qp, IB_QPS_RTS);
1597
1598                 list_for_each_entry_safe(ioctx, ioctx_tmp, &ch->cmd_wait_list,
1599                                          wait_list) {
1600                         list_del(&ioctx->wait_list);
1601                         srpt_handle_new_iu(ch, ioctx);
1602                 }
1603         } else if (ch->state == RDMA_CHANNEL_DISCONNECTING)
1604                 ret = -EAGAIN;
1605         else
1606                 ret = 0;
1607
1608         if (ret) {
1609                 printk(KERN_ERR PFX "cm_id=%p sess_name=%s state=%d\n",
1610                        cm_id, ch->sess_name, ch->state);
1611                 srpt_disconnect_channel(ch, 1);
1612         }
1613
1614         return ret;
1615 }
1616
1617 static int srpt_cm_timewait_exit(struct ib_cm_id *cm_id)
1618 {
1619         printk(KERN_DEBUG PFX "%s: cm_id=%p\n", __func__, cm_id);
1620         return srpt_find_and_release_channel(cm_id);
1621 }
1622
1623 static int srpt_cm_rep_error(struct ib_cm_id *cm_id)
1624 {
1625         printk(KERN_DEBUG PFX "%s: cm_id=%p\n", __func__, cm_id);
1626         return srpt_find_and_release_channel(cm_id);
1627 }
1628
1629 static int srpt_cm_dreq_recv(struct ib_cm_id *cm_id)
1630 {
1631         struct srpt_rdma_ch *ch;
1632         int ret = 0;
1633
1634         ch = srpt_find_channel(cm_id);
1635
1636         if (!ch)
1637                 return -EINVAL;
1638
1639         printk(KERN_DEBUG PFX "%s: cm_id= %p ch->state= %d\n",
1640                  __func__, cm_id, ch->state);
1641
1642         switch (ch->state) {
1643         case RDMA_CHANNEL_LIVE:
1644         case RDMA_CHANNEL_CONNECTING:
1645                 ret = srpt_disconnect_channel(ch, 0);
1646                 break;
1647         case RDMA_CHANNEL_DISCONNECTING:
1648         default:
1649                 break;
1650         }
1651
1652         return ret;
1653 }
1654
1655 static int srpt_cm_drep_recv(struct ib_cm_id *cm_id)
1656 {
1657         printk(KERN_DEBUG PFX "%s: cm_id=%p\n", __func__, cm_id);
1658         return srpt_find_and_release_channel(cm_id);
1659 }
1660
1661 static int srpt_cm_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event)
1662 {
1663         int ret = 0;
1664
1665         switch (event->event) {
1666         case IB_CM_REQ_RECEIVED:
1667                 ret = srpt_cm_req_recv(cm_id, &event->param.req_rcvd,
1668                                        event->private_data);
1669                 break;
1670         case IB_CM_REJ_RECEIVED:
1671                 ret = srpt_cm_rej_recv(cm_id);
1672                 break;
1673         case IB_CM_RTU_RECEIVED:
1674         case IB_CM_USER_ESTABLISHED:
1675                 ret = srpt_cm_rtu_recv(cm_id);
1676                 break;
1677         case IB_CM_DREQ_RECEIVED:
1678                 ret = srpt_cm_dreq_recv(cm_id);
1679                 break;
1680         case IB_CM_DREP_RECEIVED:
1681                 ret = srpt_cm_drep_recv(cm_id);
1682                 break;
1683         case IB_CM_TIMEWAIT_EXIT:
1684                 ret = srpt_cm_timewait_exit(cm_id);
1685                 break;
1686         case IB_CM_REP_ERROR:
1687                 ret = srpt_cm_rep_error(cm_id);
1688                 break;
1689         default:
1690                 break;
1691         }
1692
1693         return ret;
1694 }
1695
1696 static int srpt_map_sg_to_ib_sge(struct srpt_rdma_ch *ch,
1697                                  struct srpt_ioctx *ioctx,
1698                                  struct scst_cmd *scmnd)
1699 {
1700         struct scatterlist *scat;
1701         scst_data_direction dir;
1702         struct rdma_iu *riu;
1703         struct srp_direct_buf *db;
1704         dma_addr_t dma_addr;
1705         struct ib_sge *sge;
1706         u64 raddr;
1707         u32 rsize;
1708         u32 tsize;
1709         u32 dma_len;
1710         int count, nrdma;
1711         int i, j, k;
1712
1713         scat = scst_cmd_get_sg(scmnd);
1714         dir = scst_cmd_get_data_direction(scmnd);
1715         count = dma_map_sg(ch->sport->sdev->device->dma_device, scat,
1716                            scst_cmd_get_sg_cnt(scmnd),
1717                            scst_to_tgt_dma_dir(dir));
1718         if (unlikely(!count))
1719                 return -EBUSY;
1720
1721         if (ioctx->rdma_ius && ioctx->n_rdma_ius)
1722                 nrdma = ioctx->n_rdma_ius;
1723         else {
1724                 nrdma = count / SRPT_DEF_SG_PER_WQE + ioctx->n_rbuf;
1725
1726                 ioctx->rdma_ius = kzalloc(nrdma * sizeof *riu,
1727                                           scst_cmd_atomic(scmnd)
1728                                           ? GFP_ATOMIC : GFP_KERNEL);
1729                 if (!ioctx->rdma_ius) {
1730                         dma_unmap_sg(ch->sport->sdev->device->dma_device,
1731                                      scat, scst_cmd_get_sg_cnt(scmnd),
1732                                      scst_to_tgt_dma_dir(dir));
1733                         return -ENOMEM;
1734                 }
1735
1736                 ioctx->n_rdma_ius = nrdma;
1737         }
1738
1739         db = ioctx->rbufs;
1740         tsize = (dir == SCST_DATA_READ) ?
1741                 scst_cmd_get_resp_data_len(scmnd) : scst_cmd_get_bufflen(scmnd);
1742         dma_len = sg_dma_len(&scat[0]);
1743         riu = ioctx->rdma_ius;
1744
1745         /*
1746          * For each remote desc - calculate the #ib_sge.
1747          * If #ib_sge < SRPT_DEF_SG_PER_WQE per rdma operation then
1748          *      each remote desc rdma_iu is required a rdma wr;
1749          * else
1750          *      we need to allocate extra rdma_iu to carry extra #ib_sge in
1751          *      another rdma wr
1752          */
1753         for (i = 0, j = 0;
1754              j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
1755                 rsize = be32_to_cpu(db->len);
1756                 raddr = be64_to_cpu(db->va);
1757                 riu->raddr = raddr;
1758                 riu->rkey = be32_to_cpu(db->key);
1759                 riu->sge_cnt = 0;
1760
1761                 /* calculate how many sge required for this remote_buf */
1762                 while (rsize > 0 && tsize > 0) {
1763
1764                         if (rsize >= dma_len) {
1765                                 tsize -= dma_len;
1766                                 rsize -= dma_len;
1767                                 raddr += dma_len;
1768
1769                                 if (tsize > 0) {
1770                                         ++j;
1771                                         if (j < count)
1772                                                 dma_len = sg_dma_len(&scat[j]);
1773                                 }
1774                         } else {
1775                                 tsize -= rsize;
1776                                 dma_len -= rsize;
1777                                 rsize = 0;
1778                         }
1779
1780                         ++riu->sge_cnt;
1781
1782                         if (rsize > 0 && riu->sge_cnt == SRPT_DEF_SG_PER_WQE) {
1783                                 riu->sge =
1784                                     kmalloc(riu->sge_cnt * sizeof *riu->sge,
1785                                             scst_cmd_atomic(scmnd)
1786                                             ? GFP_ATOMIC : GFP_KERNEL);
1787                                 if (!riu->sge)
1788                                         goto free_mem;
1789
1790                                 ++ioctx->n_rdma;
1791                                 ++riu;
1792                                 riu->sge_cnt = 0;
1793                                 riu->raddr = raddr;
1794                                 riu->rkey = be32_to_cpu(db->key);
1795                         }
1796                 }
1797
1798                 riu->sge = kmalloc(riu->sge_cnt * sizeof *riu->sge,
1799                                    scst_cmd_atomic(scmnd)
1800                                    ? GFP_ATOMIC : GFP_KERNEL);
1801
1802                 if (!riu->sge)
1803                         goto free_mem;
1804
1805                 ++ioctx->n_rdma;
1806         }
1807
1808         db = ioctx->rbufs;
1809         scat = scst_cmd_get_sg(scmnd);
1810         tsize = (dir == SCST_DATA_READ) ?
1811                 scst_cmd_get_resp_data_len(scmnd) : scst_cmd_get_bufflen(scmnd);
1812         riu = ioctx->rdma_ius;
1813         dma_len = sg_dma_len(&scat[0]);
1814         dma_addr = sg_dma_address(&scat[0]);
1815
1816         /* this second loop is really mapped sg_addres to rdma_iu->ib_sge */
1817         for (i = 0, j = 0;
1818              j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
1819                 rsize = be32_to_cpu(db->len);
1820                 sge = riu->sge;
1821                 k = 0;
1822
1823                 while (rsize > 0 && tsize > 0) {
1824                         sge->addr = dma_addr;
1825                         sge->lkey = ch->sport->sdev->mr->lkey;
1826
1827                         if (rsize >= dma_len) {
1828                                 sge->length =
1829                                         (tsize < dma_len) ? tsize : dma_len;
1830                                 tsize -= dma_len;
1831                                 rsize -= dma_len;
1832
1833                                 if (tsize > 0) {
1834                                         ++j;
1835                                         if (j < count) {
1836                                                 dma_len = sg_dma_len(&scat[j]);
1837                                                 dma_addr =
1838                                                     sg_dma_address(&scat[j]);
1839                                         }
1840                                 }
1841                         } else {
1842                                 sge->length = (tsize < rsize) ? tsize : rsize;
1843                                 tsize -= rsize;
1844                                 dma_len -= rsize;
1845                                 dma_addr += rsize;
1846                                 rsize = 0;
1847                         }
1848
1849                         ++k;
1850                         if (k == riu->sge_cnt && rsize > 0) {
1851                                 ++riu;
1852                                 sge = riu->sge;
1853                                 k = 0;
1854                         } else if (rsize > 0)
1855                                 ++sge;
1856                 }
1857         }
1858
1859         return 0;
1860
1861 free_mem:
1862         while (ioctx->n_rdma)
1863                 kfree(ioctx->rdma_ius[ioctx->n_rdma--].sge);
1864
1865         kfree(ioctx->rdma_ius);
1866
1867         dma_unmap_sg(ch->sport->sdev->device->dma_device,
1868                      scat, scst_cmd_get_sg_cnt(scmnd),
1869                      scst_to_tgt_dma_dir(dir));
1870
1871         return -ENOMEM;
1872 }
1873
1874 static int srpt_perform_rdmas(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx,
1875                               scst_data_direction dir)
1876 {
1877         struct ib_send_wr wr;
1878         struct ib_send_wr *bad_wr;
1879         struct rdma_iu *riu;
1880         int i;
1881         int ret = 0;
1882
1883         riu = ioctx->rdma_ius;
1884         memset(&wr, 0, sizeof wr);
1885
1886         for (i = 0; i < ioctx->n_rdma; ++i, ++riu) {
1887                 wr.opcode = (dir == SCST_DATA_READ) ?
1888                     IB_WR_RDMA_WRITE : IB_WR_RDMA_READ;
1889                 wr.next = NULL;
1890                 wr.wr_id = ioctx->index;
1891                 wr.wr.rdma.remote_addr = riu->raddr;
1892                 wr.wr.rdma.rkey = riu->rkey;
1893                 wr.num_sge = riu->sge_cnt;
1894                 wr.sg_list = riu->sge;
1895
1896                 /* only get completion event for the last rdma wr */
1897                 if (i == (ioctx->n_rdma - 1) && dir == SCST_DATA_WRITE)
1898                         wr.send_flags = IB_SEND_SIGNALED;
1899
1900                 ret = ib_post_send(ch->qp, &wr, &bad_wr);
1901                 if (ret)
1902                         break;
1903         }
1904
1905         return ret;
1906 }
1907
1908 /*
1909  * Start data reception. Must not block.
1910  */
1911 static int srpt_xfer_data(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx,
1912                           struct scst_cmd *scmnd)
1913 {
1914         int ret;
1915
1916         ret = srpt_map_sg_to_ib_sge(ch, ioctx, scmnd);
1917         if (ret) {
1918                 printk(KERN_ERR PFX "%s[%d] ret=%d\n", __func__, __LINE__, ret);
1919                 ret = SCST_TGT_RES_QUEUE_FULL;
1920                 goto out;
1921         }
1922
1923         ret = srpt_perform_rdmas(ch, ioctx, scst_cmd_get_data_direction(scmnd));
1924         if (ret) {
1925                 printk(KERN_ERR PFX "%s[%d] ret=%d\n", __func__, __LINE__, ret);
1926                 if (ret == -EAGAIN || ret == -ENOMEM)
1927                         ret = SCST_TGT_RES_QUEUE_FULL;
1928                 else
1929                         ret = SCST_TGT_RES_FATAL_ERROR;
1930                 goto out;
1931         }
1932
1933         ret = SCST_TGT_RES_SUCCESS;
1934
1935 out:
1936         return ret;
1937 }
1938
1939 /*
1940  * Called by the SCST core to inform ib_srpt that data reception should start.
1941  * Must not block.
1942  */
1943 static int srpt_rdy_to_xfer(struct scst_cmd *scmnd)
1944 {
1945         struct srpt_rdma_ch *ch;
1946         struct srpt_ioctx *ioctx;
1947
1948         ioctx = scst_cmd_get_tgt_priv(scmnd);
1949         BUG_ON(!ioctx);
1950
1951         ch = scst_sess_get_tgt_priv(scst_cmd_get_session(scmnd));
1952         BUG_ON(!ch);
1953
1954         if (ch->state == RDMA_CHANNEL_DISCONNECTING)
1955                 return SCST_TGT_RES_FATAL_ERROR;
1956         else if (ch->state == RDMA_CHANNEL_CONNECTING)
1957                 return SCST_TGT_RES_QUEUE_FULL;
1958
1959         return srpt_xfer_data(ch, ioctx, scmnd);
1960 }
1961
1962 /*
1963  * Called by the SCST core. Transmits the response buffer and status held in
1964  * 'scmnd'. Must not block.
1965  */
1966 static int srpt_xmit_response(struct scst_cmd *scmnd)
1967 {
1968         struct srpt_rdma_ch *ch;
1969         struct srpt_ioctx *ioctx;
1970         struct srp_rsp *srp_rsp;
1971         u64 tag;
1972         int ret = SCST_TGT_RES_SUCCESS;
1973         int dir;
1974         int status;
1975
1976         ioctx = scst_cmd_get_tgt_priv(scmnd);
1977         BUG_ON(!ioctx);
1978
1979         ch = scst_sess_get_tgt_priv(scst_cmd_get_session(scmnd));
1980         BUG_ON(!ch);
1981
1982         tag = scst_cmd_get_tag(scmnd);
1983
1984         if (ch->state != RDMA_CHANNEL_LIVE) {
1985                 printk(KERN_ERR PFX
1986                        "%s: tag= %lld channel in bad state %d\n",
1987                        __func__, (unsigned long long)tag, ch->state);
1988
1989                 if (ch->state == RDMA_CHANNEL_DISCONNECTING)
1990                         ret = SCST_TGT_RES_FATAL_ERROR;
1991                 else if (ch->state == RDMA_CHANNEL_CONNECTING)
1992                         ret = SCST_TGT_RES_QUEUE_FULL;
1993
1994                 if (unlikely(scst_cmd_aborted(scmnd)))
1995                         goto out_aborted;
1996
1997                 goto out;
1998         }
1999
2000         dma_sync_single_for_cpu(ch->sport->sdev->device->dma_device, ioctx->dma,
2001                                 MAX_MESSAGE_SIZE, DMA_TO_DEVICE);
2002
2003         srp_rsp = ioctx->buf;
2004
2005         if (unlikely(scst_cmd_aborted(scmnd))) {
2006                 printk(KERN_ERR PFX
2007                        "%s: tag= %lld already get aborted\n",
2008                        __func__, (unsigned long long)tag);
2009                 goto out_aborted;
2010         }
2011
2012         dir = scst_cmd_get_data_direction(scmnd);
2013         status = scst_cmd_get_status(scmnd) & 0xff;
2014
2015         srpt_build_cmd_rsp(ch, ioctx, NO_SENSE, NO_ADD_SENSE, tag);
2016
2017         if (SCST_SENSE_VALID(scst_cmd_get_sense_buffer(scmnd))) {
2018                 srp_rsp->sense_data_len = scst_cmd_get_sense_buffer_len(scmnd);
2019                 if (srp_rsp->sense_data_len >
2020                     (MAX_MESSAGE_SIZE - sizeof *srp_rsp))
2021                         srp_rsp->sense_data_len =
2022                             MAX_MESSAGE_SIZE - sizeof *srp_rsp;
2023
2024                 memcpy((u8 *) (srp_rsp + 1), scst_cmd_get_sense_buffer(scmnd),
2025                        srp_rsp->sense_data_len);
2026
2027                 srp_rsp->sense_data_len = cpu_to_be32(srp_rsp->sense_data_len);
2028                 srp_rsp->flags |= SRP_RSP_FLAG_SNSVALID;
2029
2030                 if (!status)
2031                         status = SAM_STAT_CHECK_CONDITION;
2032         }
2033
2034         srp_rsp->status = status;
2035
2036         /* transfer read data if any */
2037         if (dir == SCST_DATA_READ && scst_cmd_get_resp_data_len(scmnd)) {
2038                 ret = srpt_xfer_data(ch, ioctx, scmnd);
2039                 if (ret != SCST_TGT_RES_SUCCESS) {
2040                         printk(KERN_ERR PFX
2041                                "%s: tag= %lld xfer_data failed\n",
2042                                __func__, (unsigned long long)tag);
2043                         goto out;
2044                 }
2045         }
2046
2047         if (srpt_post_send(ch, ioctx,
2048                            sizeof *srp_rsp +
2049                            be32_to_cpu(srp_rsp->sense_data_len))) {
2050                 printk(KERN_ERR PFX "%s: ch->state= %d tag= %lld\n",
2051                        __func__, ch->state,
2052                        (unsigned long long)tag);
2053                 ret = SCST_TGT_RES_FATAL_ERROR;
2054         }
2055
2056 out:
2057         return ret;
2058
2059 out_aborted:
2060         ret = SCST_TGT_RES_SUCCESS;
2061         scst_set_delivery_status(scmnd, SCST_CMD_DELIVERY_ABORTED);
2062         scst_tgt_cmd_done(scmnd, SCST_CONTEXT_SAME);
2063         goto out;
2064 }
2065
2066 /*
2067  * Called by the SCST core to inform ib_srpt that a received task management
2068  * function has been completed. Must not block.
2069  */
2070 static void srpt_tsk_mgmt_done(struct scst_mgmt_cmd *mcmnd)
2071 {
2072         struct srpt_rdma_ch *ch;
2073         struct srpt_mgmt_ioctx *mgmt_ioctx;
2074         struct srpt_ioctx *ioctx;
2075
2076         mgmt_ioctx = scst_mgmt_cmd_get_tgt_priv(mcmnd);
2077         BUG_ON(!mgmt_ioctx);
2078
2079         ch = mgmt_ioctx->ch;
2080         BUG_ON(!ch);
2081
2082         ioctx = mgmt_ioctx->ioctx;
2083         BUG_ON(!ioctx);
2084
2085         printk(KERN_WARNING PFX
2086                "%s: tsk_mgmt_done for tag= %lld status=%d\n",
2087                __func__, (unsigned long long)mgmt_ioctx->tag,
2088                scst_mgmt_cmd_get_status(mcmnd));
2089
2090         srpt_build_tskmgmt_rsp(ch, ioctx,
2091                                (scst_mgmt_cmd_get_status(mcmnd) ==
2092                                 SCST_MGMT_STATUS_SUCCESS) ?
2093                                SRP_TSK_MGMT_SUCCESS : SRP_TSK_MGMT_FAILED,
2094                                mgmt_ioctx->tag);
2095         srpt_post_send(ch, ioctx, sizeof(struct srp_rsp) + 4);
2096
2097         scst_mgmt_cmd_set_tgt_priv(mcmnd, NULL);
2098
2099         kfree(mgmt_ioctx);
2100 }
2101
2102 /*
2103  * Called by the SCST core to inform ib_srpt that the command 'scmnd' is about
2104  * to be freed. May be called in IRQ context.
2105  */
2106 static void srpt_on_free_cmd(struct scst_cmd *scmnd)
2107 {
2108         struct srpt_rdma_ch *ch;
2109         struct srpt_ioctx *ioctx;
2110
2111         ioctx = scst_cmd_get_tgt_priv(scmnd);
2112         BUG_ON(!ioctx);
2113
2114         ch = scst_sess_get_tgt_priv(scst_cmd_get_session(scmnd));
2115         BUG_ON(!ch);
2116
2117         spin_lock_irq(&ch->spinlock);
2118         list_del(&ioctx->scmnd_list);
2119         ch->active_scmnd_cnt--;
2120         spin_unlock_irq(&ch->spinlock);
2121
2122         srpt_reset_ioctx(ch, ioctx);
2123         scst_cmd_set_tgt_priv(scmnd, NULL);
2124 }
2125
2126 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20)
2127 static void srpt_refresh_port_work(void *ctx)
2128 #else
2129 static void srpt_refresh_port_work(struct work_struct *work)
2130 #endif
2131 {
2132 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20)
2133         struct srpt_port *sport = (struct srpt_port *)ctx;
2134 #else
2135         struct srpt_port *sport = container_of(work, struct srpt_port, work);
2136 #endif
2137
2138         srpt_refresh_port(sport);
2139 }
2140
2141 /*
2142  * Called by the SCST core to detect target adapters. Returns the number of
2143  * detected target adapters.
2144  */
2145 static int srpt_detect(struct scst_tgt_template *tp)
2146 {
2147         struct srpt_device *sdev;
2148         struct srpt_port *sport;
2149         int i;
2150         int count = 0;
2151
2152         list_for_each_entry(sdev, &srpt_devices, list) {
2153
2154                 sdev->scst_tgt = scst_register(tp, NULL);
2155                 if (!sdev->scst_tgt)
2156                         goto out;
2157
2158                 scst_tgt_set_tgt_priv(sdev->scst_tgt, sdev);
2159
2160                 for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
2161                         sport = &sdev->port[i - 1];
2162                         sport->sdev = sdev;
2163                         sport->port = i;
2164 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20) && ! defined(BACKPORT_LINUX_WORKQUEUE_TO_2_6_19)
2165                         INIT_WORK(&sport->work, srpt_refresh_port_work, sport);
2166 #else
2167                         INIT_WORK(&sport->work, srpt_refresh_port_work);
2168 #endif
2169
2170                         if (srpt_refresh_port(sport)) {
2171                                 scst_unregister(sdev->scst_tgt);
2172                                 goto out;
2173                         }
2174                 }
2175
2176                 ++count;
2177         }
2178 out:
2179         return count;
2180 }
2181
2182 /*
2183  * Called by the SCST core to free up the resources associated with device
2184  * 'scst_tgt'.
2185  */
2186 static int srpt_release(struct scst_tgt *scst_tgt)
2187 {
2188         struct srpt_device *sdev = scst_tgt_get_tgt_priv(scst_tgt);
2189         struct srpt_rdma_ch *ch, *tmp_ch;
2190
2191         list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list)
2192             srpt_release_channel(ch, 1);
2193
2194         srpt_unregister_mad_agent(sdev);
2195
2196         scst_tgt_set_tgt_priv(scst_tgt, NULL);
2197
2198         complete(&sdev->scst_released);
2199
2200         return 0;
2201 }
2202
2203 /*
2204  * Entry point for ib_srpt's kernel thread. This kernel thread is only created
2205  * when the module parameter 'thread' is not zero (the default is zero).
2206  * This thread processes the ioctx list srpt_thread.thread_ioctx_list.
2207  *
2208  * @pre thread != 0
2209  */
2210 static int srpt_ioctx_thread(void *arg)
2211 {
2212         struct srpt_ioctx *ioctx;
2213
2214         /* Hibernation / freezing of the SRPT kernel thread is not supported. */
2215         current->flags |= PF_NOFREEZE;
2216
2217         spin_lock_irq(&srpt_thread.thread_lock);
2218         while (!kthread_should_stop()) {
2219                 wait_queue_t wait;
2220                 init_waitqueue_entry(&wait, current);
2221
2222                 if (!srpt_test_ioctx_list()) {
2223                         add_wait_queue_exclusive(&ioctx_list_waitQ, &wait);
2224
2225                         for (;;) {
2226                                 set_current_state(TASK_INTERRUPTIBLE);
2227                                 if (srpt_test_ioctx_list())
2228                                         break;
2229                                 spin_unlock_irq(&srpt_thread.thread_lock);
2230                                 schedule();
2231                                 spin_lock_irq(&srpt_thread.thread_lock);
2232                         }
2233                         set_current_state(TASK_RUNNING);
2234                         remove_wait_queue(&ioctx_list_waitQ, &wait);
2235                 }
2236
2237                 while (!list_empty(&srpt_thread.thread_ioctx_list)) {
2238                         ioctx = list_entry(srpt_thread.thread_ioctx_list.next,
2239                                            struct srpt_ioctx, comp_list);
2240
2241                         list_del(&ioctx->comp_list);
2242
2243                         spin_unlock_irq(&srpt_thread.thread_lock);
2244                         switch (ioctx->op) {
2245                         case IB_WC_SEND:
2246                                 srpt_handle_send_comp(ioctx->ch, ioctx,
2247                                         SCST_CONTEXT_DIRECT);
2248                                 break;
2249                         case IB_WC_RDMA_WRITE:
2250                         case IB_WC_RDMA_READ:
2251                                 srpt_handle_rdma_comp(ioctx->ch, ioctx);
2252                                 break;
2253                         case IB_WC_RECV:
2254                                 srpt_handle_new_iu(ioctx->ch, ioctx);
2255                                 break;
2256                         default:
2257                                 break;
2258                         }
2259                         spin_lock_irq(&srpt_thread.thread_lock);
2260                 }
2261         }
2262         spin_unlock_irq(&srpt_thread.thread_lock);
2263
2264         return 0;
2265 }
2266
2267 /* SCST target template for the SRP target implementation. */
2268 static struct scst_tgt_template srpt_template = {
2269         .name = DRV_NAME,
2270         .sg_tablesize = SRPT_DEF_SG_TABLESIZE,
2271         .xmit_response_atomic = 1,
2272         .rdy_to_xfer_atomic = 1,
2273         .no_proc_entry = 1,
2274         .detect = srpt_detect,
2275         .release = srpt_release,
2276         .xmit_response = srpt_xmit_response,
2277         .rdy_to_xfer = srpt_rdy_to_xfer,
2278         .on_free_cmd = srpt_on_free_cmd,
2279         .task_mgmt_fn_done = srpt_tsk_mgmt_done
2280 };
2281
2282 /*
2283  * The callback function srpt_release_class_dev() is called whenever a
2284  * device is removed from the /sys/class/infiniband_srpt device class.
2285  */
2286 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2287 static void srpt_release_class_dev(struct class_device *class_dev)
2288 #else
2289 static void srpt_release_class_dev(struct device *dev)
2290 #endif
2291 {
2292 }
2293
2294 static struct class srpt_class = {
2295         .name = "infiniband_srpt",
2296 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2297         .release = srpt_release_class_dev
2298 #else
2299         .dev_release = srpt_release_class_dev
2300 #endif
2301 };
2302
2303 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2304 static ssize_t show_login_info(struct class_device *class_dev, char *buf)
2305 #else
2306 static ssize_t show_login_info(struct device *dev,
2307                                struct device_attribute *attr, char *buf)
2308 #endif
2309 {
2310         struct srpt_device *sdev =
2311 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2312                 container_of(class_dev, struct srpt_device, class_dev);
2313 #else
2314                 container_of(dev, struct srpt_device, dev);
2315 #endif
2316         struct srpt_port *sport;
2317         int i;
2318         int len = 0;
2319
2320         for (i = 0; i < sdev->device->phys_port_cnt; i++) {
2321                 sport = &sdev->port[i];
2322
2323                 len += sprintf(buf + len,
2324                                "tid_ext=%016llx,ioc_guid=%016llx,pkey=ffff,"
2325                                "dgid=%04x%04x%04x%04x%04x%04x%04x%04x,"
2326                                "service_id=%016llx\n",
2327                                (unsigned long long) mellanox_ioc_guid,
2328                                (unsigned long long) mellanox_ioc_guid,
2329                                be16_to_cpu(((__be16 *) sport->gid.raw)[0]),
2330                                be16_to_cpu(((__be16 *) sport->gid.raw)[1]),
2331                                be16_to_cpu(((__be16 *) sport->gid.raw)[2]),
2332                                be16_to_cpu(((__be16 *) sport->gid.raw)[3]),
2333                                be16_to_cpu(((__be16 *) sport->gid.raw)[4]),
2334                                be16_to_cpu(((__be16 *) sport->gid.raw)[5]),
2335                                be16_to_cpu(((__be16 *) sport->gid.raw)[6]),
2336                                be16_to_cpu(((__be16 *) sport->gid.raw)[7]),
2337                                (unsigned long long) mellanox_ioc_guid);
2338         }
2339
2340         return len;
2341 }
2342
2343 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2344 static CLASS_DEVICE_ATTR(login_info, S_IRUGO, show_login_info, NULL);
2345 #else
2346 static DEVICE_ATTR(login_info, S_IRUGO, show_login_info, NULL);
2347 #endif
2348
2349 /*
2350  * Callback function called by the InfiniBand core when either an InfiniBand
2351  * device has been added or during the ib_register_client() call for each
2352  * registered InfiniBand device.
2353  */
2354 static void srpt_add_one(struct ib_device *device)
2355 {
2356         struct srpt_device *sdev;
2357         struct ib_srq_init_attr srq_attr;
2358         int i;
2359
2360         sdev = kzalloc(sizeof *sdev, GFP_KERNEL);
2361         if (!sdev)
2362                 return;
2363
2364         sdev->device = device;
2365         init_completion(&sdev->scst_released);
2366
2367 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2368         sdev->class_dev.class = &srpt_class;
2369         sdev->class_dev.dev = device->dma_device;
2370         snprintf(sdev->class_dev.class_id, BUS_ID_SIZE,
2371                  "srpt-%s", device->name);
2372 #else
2373         sdev->dev.class = &srpt_class;
2374         sdev->dev.parent = device->dma_device;
2375         snprintf(sdev->dev.bus_id, BUS_ID_SIZE, "srpt-%s", device->name);
2376 #endif
2377
2378 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2379         if (class_device_register(&sdev->class_dev))
2380                 goto free_dev;
2381         if (class_device_create_file(&sdev->class_dev,
2382                                      &class_device_attr_login_info))
2383                 goto err_dev;
2384 #else
2385         if (device_register(&sdev->dev))
2386                 goto free_dev;
2387         if (device_create_file(&sdev->dev, &dev_attr_login_info))
2388                 goto err_dev;
2389 #endif
2390
2391         if (ib_query_device(device, &sdev->dev_attr))
2392                 goto err_dev;
2393
2394         sdev->pd = ib_alloc_pd(device);
2395         if (IS_ERR(sdev->pd))
2396                 goto err_dev;
2397
2398         sdev->mr = ib_get_dma_mr(sdev->pd, IB_ACCESS_LOCAL_WRITE);
2399         if (IS_ERR(sdev->mr))
2400                 goto err_pd;
2401
2402         srq_attr.event_handler = srpt_srq_event;
2403         srq_attr.srq_context = (void *)sdev;
2404         srq_attr.attr.max_wr = min(SRPT_SRQ_SIZE, sdev->dev_attr.max_srq_wr);
2405         srq_attr.attr.max_sge = 1;
2406         srq_attr.attr.srq_limit = 0;
2407
2408         sdev->srq = ib_create_srq(sdev->pd, &srq_attr);
2409         if (IS_ERR(sdev->srq))
2410                 goto err_mr;
2411
2412         printk(KERN_DEBUG PFX "%s: create SRQ #wr= %d max_allow=%d dev= %s\n",
2413                __func__, srq_attr.attr.max_wr,
2414               sdev->dev_attr.max_srq_wr, device->name);
2415
2416         if (!mellanox_ioc_guid)
2417                 mellanox_ioc_guid = be64_to_cpu(device->node_guid);
2418
2419         sdev->cm_id = ib_create_cm_id(device, srpt_cm_handler, sdev);
2420         if (IS_ERR(sdev->cm_id))
2421                 goto err_srq;
2422
2423         /* print out target login information */
2424         printk(KERN_DEBUG PFX "Target login info: id_ext=%016llx,"
2425                 "ioc_guid=%016llx,pkey=ffff,service_id=%016llx\n",
2426                 (unsigned long long) mellanox_ioc_guid,
2427                 (unsigned long long) mellanox_ioc_guid,
2428                 (unsigned long long) mellanox_ioc_guid);
2429
2430         /*
2431          * We do not have a consistent service_id (ie. also id_ext of target_id)
2432          * to identify this target. We currently use the guid of the first HCA
2433          * in the system as service_id; therefore, the target_id will change
2434          * if this HCA is gone bad and replaced by different HCA
2435          */
2436         if (ib_cm_listen(sdev->cm_id, cpu_to_be64(mellanox_ioc_guid), 0, NULL))
2437                 goto err_cm;
2438
2439         INIT_IB_EVENT_HANDLER(&sdev->event_handler, sdev->device,
2440                               srpt_event_handler);
2441         if (ib_register_event_handler(&sdev->event_handler))
2442                 goto err_cm;
2443
2444         if (srpt_alloc_ioctx_ring(sdev))
2445                 goto err_event;
2446
2447         INIT_LIST_HEAD(&sdev->rch_list);
2448         spin_lock_init(&sdev->spinlock);
2449
2450         for (i = 0; i < SRPT_SRQ_SIZE; ++i)
2451                 srpt_post_recv(sdev, sdev->ioctx_ring[i]);
2452
2453         list_add_tail(&sdev->list, &srpt_devices);
2454
2455         ib_set_client_data(device, &srpt_client, sdev);
2456
2457         return;
2458
2459 err_event:
2460         ib_unregister_event_handler(&sdev->event_handler);
2461 err_cm:
2462         ib_destroy_cm_id(sdev->cm_id);
2463 err_srq:
2464         ib_destroy_srq(sdev->srq);
2465 err_mr:
2466         ib_dereg_mr(sdev->mr);
2467 err_pd:
2468         ib_dealloc_pd(sdev->pd);
2469 err_dev:
2470 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2471         class_device_unregister(&sdev->class_dev);
2472 #else
2473         device_unregister(&sdev->dev);
2474 #endif
2475 free_dev:
2476         kfree(sdev);
2477 }
2478
2479 /*
2480  * Callback function called by the InfiniBand core when either an InfiniBand
2481  * device has been removed or during the ib_unregister_client() call for each
2482  * registered InfiniBand device.
2483  */
2484 static void srpt_remove_one(struct ib_device *device)
2485 {
2486         struct srpt_device *sdev;
2487
2488         sdev = ib_get_client_data(device, &srpt_client);
2489         if (!WARN_ON(sdev))
2490                 return;
2491
2492         wait_for_completion(&sdev->scst_released);
2493
2494         ib_unregister_event_handler(&sdev->event_handler);
2495         ib_destroy_cm_id(sdev->cm_id);
2496         ib_destroy_srq(sdev->srq);
2497         ib_dereg_mr(sdev->mr);
2498         ib_dealloc_pd(sdev->pd);
2499 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2500         class_device_unregister(&sdev->class_dev);
2501 #else
2502         device_unregister(&sdev->dev);
2503 #endif
2504
2505         srpt_free_ioctx_ring(sdev);
2506         list_del(&sdev->list);
2507         kfree(sdev);
2508 }
2509
2510 static int __init srpt_init_module(void)
2511 {
2512         int ret;
2513
2514         INIT_LIST_HEAD(&srpt_devices);
2515
2516         ret = class_register(&srpt_class);
2517         if (ret) {
2518                 printk(KERN_ERR PFX "couldn't register class ib_srpt\n");
2519                 return ret;
2520         }
2521
2522         ret = ib_register_client(&srpt_client);
2523         if (ret) {
2524                 printk(KERN_ERR PFX "couldn't register IB client\n");
2525                 goto mem_out;
2526         }
2527
2528         ret = scst_register_target_template(&srpt_template);
2529         if (ret < 0) {
2530                 printk(KERN_ERR PFX "couldn't register with scst\n");
2531                 ret = -ENODEV;
2532                 goto ib_out;
2533         }
2534
2535         if (thread) {
2536                 spin_lock_init(&srpt_thread.thread_lock);
2537                 INIT_LIST_HEAD(&srpt_thread.thread_ioctx_list);
2538                 srpt_thread.thread = kthread_run(srpt_ioctx_thread,
2539                                                  NULL, "srpt_thread");
2540                 if (IS_ERR(srpt_thread.thread)) {
2541                         srpt_thread.thread = NULL;
2542                         thread = 0;
2543                 }
2544         }
2545
2546         return 0;
2547
2548 ib_out:
2549         ib_unregister_client(&srpt_client);
2550 mem_out:
2551         class_unregister(&srpt_class);
2552         return ret;
2553 }
2554
2555 static void __exit srpt_cleanup_module(void)
2556 {
2557         if (srpt_thread.thread)
2558                 kthread_stop(srpt_thread.thread);
2559         scst_unregister_target_template(&srpt_template);
2560         ib_unregister_client(&srpt_client);
2561         class_unregister(&srpt_class);
2562 }
2563
2564 module_init(srpt_init_module);
2565 module_exit(srpt_cleanup_module);