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