Implemented SRPT command state management. The SRPT target code does no
[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         struct srpt_ioctx *ioctx;
865         scst_data_direction dir;
866
867         ioctx = scst_cmd_get_tgt_priv(scmnd);
868         BUG_ON(!ioctx);
869         dir = scst_cmd_get_data_direction(scmnd);
870         if (dir != SCST_DATA_NONE) {
871                 dma_unmap_sg(sdev->device->dma_device,
872                              scst_cmd_get_sg(scmnd),
873                              scst_cmd_get_sg_cnt(scmnd),
874                              scst_to_tgt_dma_dir(dir));
875
876                 if (ioctx->state == SRPT_STATE_NEED_DATA) {
877                         scst_rx_data(scmnd,
878                                      tell_initiator ? SCST_RX_STATUS_ERROR
879                                      : SCST_RX_STATUS_ERROR_FATAL,
880                                      SCST_CONTEXT_THREAD);
881                         goto out;
882                 } else if (ioctx->state == SRPT_STATE_PROCESSED)
883                         ;
884                 else {
885                         printk(KERN_ERR PFX
886                                "unexpected cmd state %d (SCST) %d (SRPT)\n",
887                                scmnd->state, ioctx->state);
888                         WARN_ON("unexpected cmd state");
889                 }
890         }
891
892         scst_set_delivery_status(scmnd, SCST_CMD_DELIVERY_FAILED);
893         scst_tgt_cmd_done(scmnd, scst_estimate_context());
894 out:
895         return;
896 }
897
898 static void srpt_handle_err_comp(struct srpt_rdma_ch *ch, struct ib_wc *wc)
899 {
900         struct srpt_ioctx *ioctx;
901         struct srpt_device *sdev = ch->sport->sdev;
902
903         if (wc->wr_id & SRPT_OP_RECV) {
904                 ioctx = sdev->ioctx_ring[wc->wr_id & ~SRPT_OP_RECV];
905                 printk(KERN_ERR PFX "This is serious - SRQ is in bad state\n");
906         } else {
907                 ioctx = sdev->ioctx_ring[wc->wr_id];
908
909                 if (ioctx->scmnd)
910                         srpt_abort_scst_cmd(sdev, ioctx->scmnd, true);
911                 else
912                         srpt_reset_ioctx(ch, ioctx);
913         }
914 }
915
916 static void srpt_handle_send_comp(struct srpt_rdma_ch *ch,
917                                   struct srpt_ioctx *ioctx,
918                                   enum scst_exec_context context)
919 {
920         if (ioctx->scmnd) {
921                 scst_data_direction dir =
922                         scst_cmd_get_data_direction(ioctx->scmnd);
923
924                 if (dir != SCST_DATA_NONE)
925                         dma_unmap_sg(ch->sport->sdev->device->dma_device,
926                                      scst_cmd_get_sg(ioctx->scmnd),
927                                      scst_cmd_get_sg_cnt(ioctx->scmnd),
928                                      scst_to_tgt_dma_dir(dir));
929
930                 scst_tgt_cmd_done(ioctx->scmnd, context);
931         } else
932                 srpt_reset_ioctx(ch, ioctx);
933 }
934
935 static void srpt_handle_rdma_comp(struct srpt_rdma_ch *ch,
936                                   struct srpt_ioctx *ioctx)
937 {
938         if (!ioctx->scmnd) {
939                 srpt_reset_ioctx(ch, ioctx);
940                 return;
941         }
942
943         if (scst_cmd_get_data_direction(ioctx->scmnd) == SCST_DATA_WRITE)
944                 scst_rx_data(ioctx->scmnd, SCST_RX_STATUS_SUCCESS,
945                         scst_estimate_context());
946 }
947
948 /**
949  * Build an SRP_RSP response PDU.
950  * @ch: RDMA channel through which the request has been received.
951  * @ioctx: I/O context in which the SRP_RSP PDU will be built.
952  * @s_key: sense key that will be stored in the response.
953  * @s_code: value that will be stored in the asc_ascq field of the sense data.
954  * @tag: tag of the request for which this response is being generated.
955  *
956  * An SRP_RSP PDU contains a SCSI status or service response. See also
957  * section 6.9 in the T10 SRP r16a document for the format of an SRP_RSP PDU.
958  * See also SPC-2 for more information about sense data.
959  */
960 static void srpt_build_cmd_rsp(struct srpt_rdma_ch *ch,
961                                struct srpt_ioctx *ioctx, u8 s_key, u8 s_code,
962                                u64 tag)
963 {
964         struct srp_rsp *srp_rsp;
965         struct sense_data *sense;
966         int limit_delta;
967
968         srp_rsp = ioctx->buf;
969         memset(srp_rsp, 0, sizeof *srp_rsp);
970
971         limit_delta = atomic_read(&ch->req_lim_delta);
972         atomic_sub(limit_delta, &ch->req_lim_delta);
973
974         srp_rsp->opcode = SRP_RSP;
975         srp_rsp->req_lim_delta = cpu_to_be32(limit_delta);
976         srp_rsp->tag = tag;
977
978         if (s_key != NO_SENSE) {
979                 srp_rsp->flags |= SRP_RSP_FLAG_SNSVALID;
980                 srp_rsp->status = SAM_STAT_CHECK_CONDITION;
981                 srp_rsp->sense_data_len =
982                     cpu_to_be32(sizeof *sense + (sizeof *sense % 4));
983
984                 sense = (struct sense_data *)(srp_rsp + 1);
985                 sense->err_code = 0x70;
986                 sense->key = s_key;
987                 sense->asc_ascq = s_code;
988         }
989 }
990
991 static void srpt_build_tskmgmt_rsp(struct srpt_rdma_ch *ch,
992                                    struct srpt_ioctx *ioctx, u8 rsp_code,
993                                    u64 tag)
994 {
995         struct srp_rsp *srp_rsp;
996         int limit_delta;
997
998         dma_sync_single_for_cpu(ch->sport->sdev->device->dma_device, ioctx->dma,
999                                 MAX_MESSAGE_SIZE, DMA_TO_DEVICE);
1000
1001         srp_rsp = ioctx->buf;
1002         memset(srp_rsp, 0, sizeof *srp_rsp);
1003
1004         limit_delta = atomic_read(&ch->req_lim_delta);
1005         atomic_sub(limit_delta, &ch->req_lim_delta);
1006
1007         srp_rsp->opcode = SRP_RSP;
1008         srp_rsp->req_lim_delta = cpu_to_be32(limit_delta);
1009         srp_rsp->tag = tag;
1010
1011         if (rsp_code != SRP_TSK_MGMT_SUCCESS) {
1012                 srp_rsp->flags |= SRP_RSP_FLAG_RSPVALID;
1013                 srp_rsp->resp_data_len = cpu_to_be32(4);
1014                 srp_rsp->data[3] = rsp_code;
1015         }
1016 }
1017
1018 /*
1019  * Process SRP_CMD.
1020  */
1021 static int srpt_handle_cmd(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx)
1022 {
1023         struct scst_cmd *scmnd;
1024         struct srp_cmd *srp_cmd;
1025         struct srp_rsp *srp_rsp;
1026         scst_data_direction dir = SCST_DATA_NONE;
1027         int indirect_desc = 0;
1028         int ret;
1029         unsigned long flags;
1030
1031         srp_cmd = ioctx->buf;
1032         srp_rsp = ioctx->buf;
1033
1034         if (srp_cmd->buf_fmt) {
1035                 ret = srpt_get_desc_tbl(ioctx, srp_cmd, &indirect_desc);
1036                 if (ret) {
1037                         srpt_build_cmd_rsp(ch, ioctx, NO_SENSE,
1038                                            NO_ADD_SENSE, srp_cmd->tag);
1039                         srp_rsp->status = SAM_STAT_TASK_SET_FULL;
1040                         goto err;
1041                 }
1042
1043                 if (indirect_desc) {
1044                         srpt_build_cmd_rsp(ch, ioctx, NO_SENSE,
1045                                            NO_ADD_SENSE, srp_cmd->tag);
1046                         srp_rsp->status = SAM_STAT_TASK_SET_FULL;
1047                         goto err;
1048                 }
1049
1050                 if (srp_cmd->buf_fmt & 0xf)
1051                         dir = SCST_DATA_READ;
1052                 else if (srp_cmd->buf_fmt >> 4)
1053                         dir = SCST_DATA_WRITE;
1054                 else
1055                         dir = SCST_DATA_NONE;
1056         } else
1057                 dir = SCST_DATA_NONE;
1058
1059         scmnd = scst_rx_cmd(ch->scst_sess, (u8 *) &srp_cmd->lun,
1060                             sizeof srp_cmd->lun, srp_cmd->cdb, 16,
1061                             thread ? SCST_NON_ATOMIC : SCST_ATOMIC);
1062         if (!scmnd) {
1063                 srpt_build_cmd_rsp(ch, ioctx, NO_SENSE,
1064                                    NO_ADD_SENSE, srp_cmd->tag);
1065                 srp_rsp->status = SAM_STAT_TASK_SET_FULL;
1066                 goto err;
1067         }
1068
1069         ioctx->scmnd = scmnd;
1070
1071         switch (srp_cmd->task_attr) {
1072         case SRP_CMD_HEAD_OF_Q:
1073                 scmnd->queue_type = SCST_CMD_QUEUE_HEAD_OF_QUEUE;
1074                 break;
1075         case SRP_CMD_ORDERED_Q:
1076                 scmnd->queue_type = SCST_CMD_QUEUE_ORDERED;
1077                 break;
1078         case SRP_CMD_SIMPLE_Q:
1079                 scmnd->queue_type = SCST_CMD_QUEUE_SIMPLE;
1080                 break;
1081         case SRP_CMD_ACA:
1082                 scmnd->queue_type = SCST_CMD_QUEUE_ACA;
1083                 break;
1084         default:
1085                 scmnd->queue_type = SCST_CMD_QUEUE_ORDERED;
1086                 break;
1087         }
1088
1089         scst_cmd_set_tag(scmnd, srp_cmd->tag);
1090         scst_cmd_set_tgt_priv(scmnd, ioctx);
1091         scst_cmd_set_expected(scmnd, dir, ioctx->data_len);
1092
1093         spin_lock_irqsave(&ch->spinlock, flags);
1094         list_add_tail(&ioctx->scmnd_list, &ch->active_scmnd_list);
1095         ch->active_scmnd_cnt++;
1096         spin_unlock_irqrestore(&ch->spinlock, flags);
1097
1098         scst_cmd_init_done(scmnd, scst_estimate_context());
1099
1100         WARN_ON(srp_rsp->opcode == SRP_RSP);
1101
1102         return 0;
1103
1104 err:
1105         WARN_ON(srp_rsp->opcode != SRP_RSP);
1106
1107         return -1;
1108 }
1109
1110 /*
1111  * Process an SRP_TSK_MGMT request PDU.
1112  *
1113  * Returns 0 upon success and -1 upon failure.
1114  *
1115  * Each task management function is performed by calling one of the
1116  * scst_rx_mgmt_fn*() functions. These functions will either report failure
1117  * or process the task management function asynchronously. The function
1118  * srpt_tsk_mgmt_done() will be called by the SCST core upon completion of the
1119  * task management function. When srpt_handle_tsk_mgmt() reports failure
1120  * (i.e. returns -1) a response PDU will have been built in ioctx->buf. This
1121  * PDU has to be sent back by the caller.
1122  *
1123  * For more information about SRP_TSK_MGMT PDU's, see also section 6.7 in
1124  * the T10 SRP r16a document.
1125  */
1126 static int srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,
1127                                 struct srpt_ioctx *ioctx)
1128 {
1129         struct srp_tsk_mgmt *srp_tsk;
1130         struct srpt_mgmt_ioctx *mgmt_ioctx;
1131         int ret;
1132
1133         srp_tsk = ioctx->buf;
1134
1135         TRACE_DBG("recv_tsk_mgmt= %d for task_tag= %lld"
1136                   " using tag= %lld cm_id= %p sess= %p",
1137                   srp_tsk->tsk_mgmt_func,
1138                   (unsigned long long) srp_tsk->task_tag,
1139                   (unsigned long long) srp_tsk->tag,
1140                   ch->cm_id, ch->scst_sess);
1141
1142         mgmt_ioctx = kmalloc(sizeof *mgmt_ioctx, GFP_ATOMIC);
1143         if (!mgmt_ioctx) {
1144                 srpt_build_tskmgmt_rsp(ch, ioctx, SRP_TSK_MGMT_FAILED,
1145                                        srp_tsk->tag);
1146                 goto err;
1147         }
1148
1149         mgmt_ioctx->ioctx = ioctx;
1150         mgmt_ioctx->ch = ch;
1151         mgmt_ioctx->tag = srp_tsk->tag;
1152
1153         switch (srp_tsk->tsk_mgmt_func) {
1154         case SRP_TSK_ABORT_TASK:
1155                 TRACE_DBG("%s", "Processing SRP_TSK_ABORT_TASK");
1156                 ret = scst_rx_mgmt_fn_tag(ch->scst_sess,
1157                                           SCST_ABORT_TASK,
1158                                           srp_tsk->task_tag,
1159                                           thread ?
1160                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1161                                           mgmt_ioctx);
1162                 break;
1163         case SRP_TSK_ABORT_TASK_SET:
1164                 TRACE_DBG("%s", "Processing SRP_TSK_ABORT_TASK_SET");
1165                 ret = scst_rx_mgmt_fn_lun(ch->scst_sess,
1166                                           SCST_ABORT_TASK_SET,
1167                                           (u8 *) &srp_tsk->lun,
1168                                           sizeof srp_tsk->lun,
1169                                           thread ?
1170                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1171                                           mgmt_ioctx);
1172                 break;
1173         case SRP_TSK_CLEAR_TASK_SET:
1174                 TRACE_DBG("%s", "Processing SRP_TSK_CLEAR_TASK_SET");
1175                 ret = scst_rx_mgmt_fn_lun(ch->scst_sess,
1176                                           SCST_CLEAR_TASK_SET,
1177                                           (u8 *) &srp_tsk->lun,
1178                                           sizeof srp_tsk->lun,
1179                                           thread ?
1180                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1181                                           mgmt_ioctx);
1182                 break;
1183         case SRP_TSK_LUN_RESET:
1184                 TRACE_DBG("%s", "Processing SRP_TSK_LUN_RESET");
1185                 ret = scst_rx_mgmt_fn_lun(ch->scst_sess,
1186                                           SCST_LUN_RESET,
1187                                           (u8 *) &srp_tsk->lun,
1188                                           sizeof srp_tsk->lun,
1189                                           thread ?
1190                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1191                                           mgmt_ioctx);
1192                 break;
1193         case SRP_TSK_CLEAR_ACA:
1194                 TRACE_DBG("%s", "Processing SRP_TSK_CLEAR_ACA");
1195                 ret = scst_rx_mgmt_fn_lun(ch->scst_sess,
1196                                           SCST_CLEAR_ACA,
1197                                           (u8 *) &srp_tsk->lun,
1198                                           sizeof srp_tsk->lun,
1199                                           thread ?
1200                                           SCST_NON_ATOMIC : SCST_ATOMIC,
1201                                           mgmt_ioctx);
1202                 break;
1203         default:
1204                 TRACE_DBG("%s", "Unsupported task management function.");
1205                 srpt_build_tskmgmt_rsp(ch, ioctx,
1206                                        SRP_TSK_MGMT_FUNC_NOT_SUPP,
1207                                        srp_tsk->tag);
1208                 goto err;
1209         }
1210
1211         if (ret) {
1212                 TRACE_DBG("%s", "Processing task management function failed.");
1213                 srpt_build_tskmgmt_rsp(ch, ioctx, SRP_TSK_MGMT_FAILED,
1214                                        srp_tsk->tag);
1215                 goto err;
1216         }
1217
1218         WARN_ON(srp_tsk->opcode == SRP_RSP);
1219
1220         return 0;
1221
1222 err:
1223         WARN_ON(srp_tsk->opcode != SRP_RSP);
1224
1225         return -1;
1226 }
1227
1228 /**
1229  * Process a receive completion event.
1230  * @ch: RDMA channel for which the completion event has been received.
1231  * @ioctx: SRPT I/O context for which the completion event has been received.
1232  */
1233 static void srpt_handle_new_iu(struct srpt_rdma_ch *ch,
1234                                struct srpt_ioctx *ioctx)
1235 {
1236         struct srp_cmd *srp_cmd;
1237         struct srp_rsp *srp_rsp;
1238         unsigned long flags;
1239         int len;
1240
1241         spin_lock_irqsave(&ch->spinlock, flags);
1242         if (ch->state != RDMA_CHANNEL_LIVE) {
1243                 if (ch->state == RDMA_CHANNEL_CONNECTING) {
1244                         list_add_tail(&ioctx->wait_list, &ch->cmd_wait_list);
1245                         spin_unlock_irqrestore(&ch->spinlock, flags);
1246                         return;
1247                 } else {
1248                         spin_unlock_irqrestore(&ch->spinlock, flags);
1249                         srpt_reset_ioctx(ch, ioctx);
1250                         return;
1251                 }
1252         }
1253         spin_unlock_irqrestore(&ch->spinlock, flags);
1254
1255         dma_sync_single_for_cpu(ch->sport->sdev->device->dma_device, ioctx->dma,
1256                                 MAX_MESSAGE_SIZE, DMA_FROM_DEVICE);
1257
1258         ioctx->data_len = 0;
1259         ioctx->n_rbuf = 0;
1260         ioctx->rbufs = NULL;
1261         ioctx->n_rdma = 0;
1262         ioctx->n_rdma_ius = 0;
1263         ioctx->rdma_ius = NULL;
1264         ioctx->scmnd = NULL;
1265         ioctx->state = SRPT_STATE_NEW;
1266
1267         srp_cmd = ioctx->buf;
1268         srp_rsp = ioctx->buf;
1269
1270         switch (srp_cmd->opcode) {
1271         case SRP_CMD:
1272                 if (srpt_handle_cmd(ch, ioctx) < 0)
1273                         goto err;
1274                 break;
1275
1276         case SRP_TSK_MGMT:
1277                 if (srpt_handle_tsk_mgmt(ch, ioctx) < 0)
1278                         goto err;
1279                 break;
1280
1281         case SRP_I_LOGOUT:
1282         case SRP_AER_REQ:
1283         default:
1284                 srpt_build_cmd_rsp(ch, ioctx, ILLEGAL_REQUEST, INVALID_CDB,
1285                                    srp_cmd->tag);
1286                 goto err;
1287         }
1288
1289         WARN_ON(srp_rsp->opcode == SRP_RSP);
1290
1291         dma_sync_single_for_device(ch->sport->sdev->device->dma_device,
1292                                    ioctx->dma, MAX_MESSAGE_SIZE,
1293                                    DMA_FROM_DEVICE);
1294
1295         return;
1296
1297 err:
1298         WARN_ON(srp_rsp->opcode != SRP_RSP);
1299         len = (sizeof *srp_rsp) + be32_to_cpu(srp_rsp->sense_data_len);
1300
1301         if (ch->state != RDMA_CHANNEL_LIVE) {
1302                 /* Give up if another thread modified the channel state. */
1303                 printk(KERN_ERR PFX "%s: channel is in state %d",
1304                        __func__, ch->state);
1305                 srpt_reset_ioctx(ch, ioctx);
1306         } else if (srpt_post_send(ch, ioctx, len)) {
1307                 printk(KERN_ERR PFX "%s: sending SRP_RSP PDU failed",
1308                        __func__);
1309                 srpt_reset_ioctx(ch, ioctx);
1310         }
1311 }
1312
1313 /*
1314  * Returns true if the ioctx list is non-empty or if the ib_srpt kernel thread
1315  * should stop.
1316  * @pre thread != 0
1317  */
1318 static inline int srpt_test_ioctx_list(void)
1319 {
1320         int res = (!list_empty(&srpt_thread.thread_ioctx_list) ||
1321                    unlikely(kthread_should_stop()));
1322         return res;
1323 }
1324
1325 /*
1326  * Add 'ioctx' to the tail of the ioctx list and wake up the kernel thread.
1327  *
1328  * @pre thread != 0
1329  */
1330 static inline void srpt_schedule_thread(struct srpt_ioctx *ioctx)
1331 {
1332         unsigned long flags;
1333
1334         spin_lock_irqsave(&srpt_thread.thread_lock, flags);
1335         list_add_tail(&ioctx->comp_list, &srpt_thread.thread_ioctx_list);
1336         spin_unlock_irqrestore(&srpt_thread.thread_lock, flags);
1337         wake_up(&ioctx_list_waitQ);
1338 }
1339
1340 /**
1341  * InfiniBand completion queue callback function.
1342  * @cq: completion queue.
1343  * @ctx: completion queue context, which was passed as the fourth argument of
1344  *       the function ib_create_cq().
1345  */
1346 static void srpt_completion(struct ib_cq *cq, void *ctx)
1347 {
1348         struct srpt_rdma_ch *ch = ctx;
1349         struct srpt_device *sdev = ch->sport->sdev;
1350         struct ib_wc wc;
1351         struct srpt_ioctx *ioctx;
1352
1353         ib_req_notify_cq(ch->cq, IB_CQ_NEXT_COMP);
1354         while (ib_poll_cq(ch->cq, 1, &wc) > 0) {
1355                 if (wc.status) {
1356                         printk(KERN_ERR PFX "failed %s status= %d\n",
1357                                wc.wr_id & SRPT_OP_RECV ? "receive" : "send",
1358                                wc.status);
1359                         srpt_handle_err_comp(ch, &wc);
1360                         break;
1361                 }
1362
1363                 if (wc.wr_id & SRPT_OP_RECV) {
1364                         ioctx = sdev->ioctx_ring[wc.wr_id & ~SRPT_OP_RECV];
1365                         if (thread) {
1366                                 ioctx->ch = ch;
1367                                 ioctx->op = IB_WC_RECV;
1368                                 srpt_schedule_thread(ioctx);
1369                         } else
1370                                 srpt_handle_new_iu(ch, ioctx);
1371                         continue;
1372                 } else
1373                         ioctx = sdev->ioctx_ring[wc.wr_id];
1374
1375                 if (thread) {
1376                         ioctx->ch = ch;
1377                         ioctx->op = wc.opcode;
1378                         srpt_schedule_thread(ioctx);
1379                 } else {
1380                         switch (wc.opcode) {
1381                         case IB_WC_SEND:
1382                                 srpt_handle_send_comp(ch, ioctx,
1383                                         scst_estimate_context());
1384                                 break;
1385                         case IB_WC_RDMA_WRITE:
1386                         case IB_WC_RDMA_READ:
1387                                 srpt_handle_rdma_comp(ch, ioctx);
1388                                 break;
1389                         default:
1390                                 break;
1391                         }
1392                 }
1393         }
1394 }
1395
1396 /*
1397  * Create a completion queue on the specified device.
1398  */
1399 static int srpt_create_ch_ib(struct srpt_rdma_ch *ch)
1400 {
1401         struct ib_qp_init_attr *qp_init;
1402         struct srpt_device *sdev = ch->sport->sdev;
1403         int cqe;
1404         int ret;
1405
1406         qp_init = kzalloc(sizeof *qp_init, GFP_KERNEL);
1407         if (!qp_init)
1408                 return -ENOMEM;
1409
1410         /* Create a completion queue (CQ). */
1411
1412         cqe = SRPT_RQ_SIZE + SRPT_SQ_SIZE - 1;
1413 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20) && ! defined(RHEL_RELEASE_CODE)
1414         ch->cq = ib_create_cq(sdev->device, srpt_completion, NULL, ch, cqe);
1415 #else
1416         ch->cq = ib_create_cq(sdev->device, srpt_completion, NULL, ch, cqe, 0);
1417 #endif
1418         if (IS_ERR(ch->cq)) {
1419                 ret = PTR_ERR(ch->cq);
1420                 printk(KERN_ERR PFX "failed to create_cq cqe= %d ret= %d\n",
1421                         cqe, ret);
1422                 goto out;
1423         }
1424
1425         /* Request completion notification. */
1426
1427         ib_req_notify_cq(ch->cq, IB_CQ_NEXT_COMP);
1428
1429         /* Create a queue pair (QP). */
1430
1431         qp_init->qp_context = (void *)ch;
1432         qp_init->event_handler = srpt_qp_event;
1433         qp_init->send_cq = ch->cq;
1434         qp_init->recv_cq = ch->cq;
1435         qp_init->srq = sdev->srq;
1436         qp_init->sq_sig_type = IB_SIGNAL_REQ_WR;
1437         qp_init->qp_type = IB_QPT_RC;
1438         qp_init->cap.max_send_wr = SRPT_SQ_SIZE;
1439         qp_init->cap.max_send_sge = SRPT_DEF_SG_PER_WQE;
1440
1441         ch->qp = ib_create_qp(sdev->pd, qp_init);
1442         if (IS_ERR(ch->qp)) {
1443                 ret = PTR_ERR(ch->qp);
1444                 ib_destroy_cq(ch->cq);
1445                 printk(KERN_ERR PFX "failed to create_qp ret= %d\n", ret);
1446                 goto out;
1447         }
1448
1449         TRACE_DBG("%s: max_cqe= %d max_sge= %d cm_id= %p",
1450                __func__, ch->cq->cqe, qp_init->cap.max_send_sge,
1451                ch->cm_id);
1452
1453         /* Modify the attributes and the state of queue pair ch->qp. */
1454
1455         ret = srpt_init_ch_qp(ch, ch->qp);
1456         if (ret) {
1457                 ib_destroy_qp(ch->qp);
1458                 ib_destroy_cq(ch->cq);
1459                 goto out;
1460         }
1461
1462         atomic_set(&ch->req_lim_delta, SRPT_RQ_SIZE);
1463 out:
1464         kfree(qp_init);
1465         return ret;
1466 }
1467
1468 /**
1469  * Look up the RDMA channel that corresponds to the specified cm_id.
1470  *
1471  * Return NULL if no matching RDMA channel has been found.
1472  */
1473 static struct srpt_rdma_ch *srpt_find_channel(struct ib_cm_id *cm_id, bool del)
1474 {
1475         struct srpt_device *sdev = cm_id->context;
1476         struct srpt_rdma_ch *ch;
1477
1478         spin_lock_irq(&sdev->spinlock);
1479         list_for_each_entry(ch, &sdev->rch_list, list) {
1480                 if (ch->cm_id == cm_id) {
1481                         if (del)
1482                                 list_del(&ch->list);
1483                         spin_unlock_irq(&sdev->spinlock);
1484                         return ch;
1485                 }
1486         }
1487
1488         spin_unlock_irq(&sdev->spinlock);
1489
1490         return NULL;
1491 }
1492
1493 /**
1494  * Release all resources associated with the specified RDMA channel.
1495  *
1496  * Note: the caller must have removed the channel from the channel list
1497  * before calling this function.
1498  */
1499 static void srpt_release_channel(struct srpt_rdma_ch *ch, int destroy_cmid)
1500 {
1501         TRACE_ENTRY();
1502
1503         WARN_ON(srpt_find_channel(ch->cm_id, false) == ch);
1504
1505         if (ch->cm_id && destroy_cmid) {
1506                 TRACE_DBG("%s: destroy cm_id= %p", __func__, ch->cm_id);
1507                 ib_destroy_cm_id(ch->cm_id);
1508                 ch->cm_id = NULL;
1509         }
1510
1511         ib_destroy_qp(ch->qp);
1512         ib_destroy_cq(ch->cq);
1513
1514         if (ch->scst_sess) {
1515                 struct srpt_ioctx *ioctx, *ioctx_tmp;
1516
1517                 TRACE_DBG("%s: release sess= %p sess_name= %s active_cmd= %d",
1518                           __func__, ch->scst_sess, ch->sess_name,
1519                           ch->active_scmnd_cnt);
1520
1521                 spin_lock_irq(&ch->spinlock);
1522                 list_for_each_entry_safe(ioctx, ioctx_tmp,
1523                                          &ch->active_scmnd_list, scmnd_list) {
1524                         spin_unlock_irq(&ch->spinlock);
1525
1526                         if (ioctx->scmnd)
1527                                 srpt_abort_scst_cmd(ch->sport->sdev,
1528                                                     ioctx->scmnd, true);
1529
1530                         spin_lock_irq(&ch->spinlock);
1531                 }
1532                 WARN_ON(!list_empty(&ch->active_scmnd_list));
1533                 WARN_ON(ch->active_scmnd_cnt != 0);
1534                 spin_unlock_irq(&ch->spinlock);
1535
1536                 scst_unregister_session(ch->scst_sess, 0, NULL);
1537                 ch->scst_sess = NULL;
1538         }
1539
1540         kfree(ch);
1541
1542         TRACE_EXIT();
1543 }
1544
1545 static int srpt_cm_req_recv(struct ib_cm_id *cm_id,
1546                             struct ib_cm_req_event_param *param,
1547                             void *private_data)
1548 {
1549         struct srpt_device *sdev = cm_id->context;
1550         struct srp_login_req *req;
1551         struct srp_login_rsp *rsp;
1552         struct srp_login_rej *rej;
1553         struct ib_cm_rep_param *rep_param;
1554         struct srpt_rdma_ch *ch, *tmp_ch;
1555         u32 it_iu_len;
1556         int ret = 0;
1557
1558         if (!sdev || !private_data)
1559                 return -EINVAL;
1560
1561         rsp = kzalloc(sizeof *rsp, GFP_KERNEL);
1562         rej = kzalloc(sizeof *rej, GFP_KERNEL);
1563         rep_param = kzalloc(sizeof *rep_param, GFP_KERNEL);
1564
1565         if (!rsp || !rej || !rep_param) {
1566                 ret = -ENOMEM;
1567                 goto out;
1568         }
1569
1570         req = (struct srp_login_req *)private_data;
1571
1572         it_iu_len = be32_to_cpu(req->req_it_iu_len);
1573
1574         TRACE_DBG("Host login i_port_id=0x%llx:0x%llx t_port_id=0x%llx:0x%llx"
1575             " it_iu_len=%d",
1576             (unsigned long long)be64_to_cpu(*(u64 *)&req->initiator_port_id[0]),
1577             (unsigned long long)be64_to_cpu(*(u64 *)&req->initiator_port_id[8]),
1578             (unsigned long long)be64_to_cpu(*(u64 *)&req->target_port_id[0]),
1579             (unsigned long long)be64_to_cpu(*(u64 *)&req->target_port_id[8]),
1580             it_iu_len);
1581
1582         if (it_iu_len > MAX_MESSAGE_SIZE || it_iu_len < 64) {
1583                 rej->reason =
1584                     cpu_to_be32(SRP_LOGIN_REJ_REQ_IT_IU_LENGTH_TOO_LARGE);
1585                 ret = -EINVAL;
1586                 TRACE_DBG("Reject invalid it_iu_len=%d", it_iu_len);
1587                 goto reject;
1588         }
1589
1590         if ((req->req_flags & 0x3) == SRP_MULTICHAN_SINGLE) {
1591                 rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_NO_CHAN;
1592
1593                 spin_lock_irq(&sdev->spinlock);
1594
1595                 list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list) {
1596                         if (!memcmp(ch->i_port_id, req->initiator_port_id, 16)
1597                             && !memcmp(ch->t_port_id, req->target_port_id, 16)
1598                             && param->port == ch->sport->port
1599                             && param->listen_id == ch->sport->sdev->cm_id
1600                             && ch->cm_id) {
1601                                 enum rdma_ch_state prev_state;
1602
1603                                 /* found an existing channel */
1604                                 TRACE_DBG("Found existing channel name= %s"
1605                                           " cm_id= %p state= %d",
1606                                           ch->sess_name, ch->cm_id, ch->state);
1607
1608                                 prev_state = ch->state;
1609                                 if (ch->state == RDMA_CHANNEL_LIVE)
1610                                         ch->state = RDMA_CHANNEL_DISCONNECTING;
1611                                 else if (ch->state == RDMA_CHANNEL_CONNECTING)
1612                                         list_del(&ch->list);
1613
1614                                 spin_unlock_irq(&sdev->spinlock);
1615
1616                                 rsp->rsp_flags =
1617                                         SRP_LOGIN_RSP_MULTICHAN_TERMINATED;
1618
1619                                 if (prev_state == RDMA_CHANNEL_LIVE)
1620                                         ib_send_cm_dreq(ch->cm_id, NULL, 0);
1621                                 else if (prev_state ==
1622                                          RDMA_CHANNEL_CONNECTING) {
1623                                         ib_send_cm_rej(ch->cm_id,
1624                                                        IB_CM_REJ_NO_RESOURCES,
1625                                                        NULL, 0, NULL, 0);
1626                                         srpt_release_channel(ch, 1);
1627                                 }
1628
1629                                 spin_lock_irq(&sdev->spinlock);
1630                         }
1631                 }
1632
1633                 spin_unlock_irq(&sdev->spinlock);
1634
1635         } else
1636                 rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_MAINTAINED;
1637
1638         if (((u64) (*(u64 *) req->target_port_id) !=
1639              cpu_to_be64(mellanox_ioc_guid)) ||
1640             ((u64) (*(u64 *) (req->target_port_id + 8)) !=
1641              cpu_to_be64(mellanox_ioc_guid))) {
1642                 rej->reason =
1643                     cpu_to_be32(SRP_LOGIN_REJ_UNABLE_ASSOCIATE_CHANNEL);
1644                 ret = -ENOMEM;
1645                 TRACE_DBG("%s", "Reject invalid target_port_id");
1646                 goto reject;
1647         }
1648
1649         ch = kzalloc(sizeof *ch, GFP_KERNEL);
1650         if (!ch) {
1651                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
1652                 TRACE_DBG("%s", "Reject failed allocate rdma_ch");
1653                 ret = -ENOMEM;
1654                 goto reject;
1655         }
1656
1657         spin_lock_init(&ch->spinlock);
1658         memcpy(ch->i_port_id, req->initiator_port_id, 16);
1659         memcpy(ch->t_port_id, req->target_port_id, 16);
1660         ch->sport = &sdev->port[param->port - 1];
1661         ch->cm_id = cm_id;
1662         ch->state = RDMA_CHANNEL_CONNECTING;
1663         INIT_LIST_HEAD(&ch->cmd_wait_list);
1664         INIT_LIST_HEAD(&ch->active_scmnd_list);
1665
1666         ret = srpt_create_ch_ib(ch);
1667         if (ret) {
1668                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
1669                 TRACE_DBG("%s", "Reject failed to create rdma_ch");
1670                 goto free_ch;
1671         }
1672
1673         ret = srpt_ch_qp_rtr(ch, ch->qp);
1674         if (ret) {
1675                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
1676                 TRACE_DBG("Reject failed qp to rtr/rts ret=%d", ret);
1677                 goto destroy_ib;
1678         }
1679
1680         snprintf(ch->sess_name, sizeof(ch->sess_name),
1681                  "0x%016llx%016llx",
1682                  (unsigned long long)be64_to_cpu(*(u64 *)ch->i_port_id),
1683                  (unsigned long long)be64_to_cpu(*(u64 *)(ch->i_port_id + 8)));
1684
1685         TRACE_DBG("registering session %s", ch->sess_name);
1686
1687         BUG_ON(!sdev->scst_tgt);
1688         ch->scst_sess = scst_register_session(sdev->scst_tgt, 0, ch->sess_name,
1689                                   NULL, NULL);
1690         if (!ch->scst_sess) {
1691                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
1692                 TRACE_DBG("%s", "Failed to create scst sess");
1693                 goto destroy_ib;
1694         }
1695
1696         TRACE_DBG("Establish connection sess=%p name=%s cm_id=%p",
1697                   ch->scst_sess, ch->sess_name, ch->cm_id);
1698
1699         scst_sess_set_tgt_priv(ch->scst_sess, ch);
1700
1701         /* create srp_login_response */
1702         rsp->opcode = SRP_LOGIN_RSP;
1703         rsp->tag = req->tag;
1704         rsp->max_it_iu_len = req->req_it_iu_len;
1705         rsp->max_ti_iu_len = req->req_it_iu_len;
1706         rsp->buf_fmt =
1707             cpu_to_be16(SRP_BUF_FORMAT_DIRECT | SRP_BUF_FORMAT_INDIRECT);
1708         rsp->req_lim_delta = cpu_to_be32(SRPT_RQ_SIZE);
1709         atomic_set(&ch->req_lim_delta, 0);
1710
1711         /* create cm reply */
1712         rep_param->qp_num = ch->qp->qp_num;
1713         rep_param->private_data = (void *)rsp;
1714         rep_param->private_data_len = sizeof *rsp;
1715         rep_param->rnr_retry_count = 7;
1716         rep_param->flow_control = 1;
1717         rep_param->failover_accepted = 0;
1718         rep_param->srq = 1;
1719         rep_param->responder_resources = 4;
1720         rep_param->initiator_depth = 4;
1721
1722         ret = ib_send_cm_rep(cm_id, rep_param);
1723         if (ret)
1724                 goto release_channel;
1725
1726         spin_lock_irq(&sdev->spinlock);
1727         list_add_tail(&ch->list, &sdev->rch_list);
1728         spin_unlock_irq(&sdev->spinlock);
1729
1730         goto out;
1731
1732 release_channel:
1733         scst_unregister_session(ch->scst_sess, 0, NULL);
1734         ch->scst_sess = NULL;
1735
1736 destroy_ib:
1737         ib_destroy_qp(ch->qp);
1738         ib_destroy_cq(ch->cq);
1739
1740 free_ch:
1741         kfree(ch);
1742
1743 reject:
1744         rej->opcode = SRP_LOGIN_REJ;
1745         rej->tag = req->tag;
1746         rej->buf_fmt =
1747             cpu_to_be16(SRP_BUF_FORMAT_DIRECT | SRP_BUF_FORMAT_INDIRECT);
1748
1749         ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0,
1750                              (void *)rej, sizeof *rej);
1751
1752 out:
1753         kfree(rep_param);
1754         kfree(rsp);
1755         kfree(rej);
1756
1757         return ret;
1758 }
1759
1760 /**
1761  * Release the channel with the specified cm_id.
1762  *
1763  * Returns one to indicate that the caller of srpt_cm_handler() should destroy
1764  * the cm_id.
1765  */
1766 static void srpt_find_and_release_channel(struct ib_cm_id *cm_id)
1767 {
1768         struct srpt_rdma_ch *ch;
1769
1770         ch = srpt_find_channel(cm_id, true);
1771         if (ch)
1772                 srpt_release_channel(ch, 0);
1773 }
1774
1775 static void srpt_cm_rej_recv(struct ib_cm_id *cm_id)
1776 {
1777         TRACE_DBG("%s: cm_id=%p", __func__, cm_id);
1778         srpt_find_and_release_channel(cm_id);
1779 }
1780
1781 /**
1782  * Process an IB_CM_RTU_RECEIVED or IB_CM_USER_ESTABLISHED event.
1783  *
1784  * An IB_CM_RTU_RECEIVED message indicates that the connection is established
1785  * and that the recipient may begin transmitting (RTU = ready to use).
1786  */
1787 static int srpt_cm_rtu_recv(struct ib_cm_id *cm_id)
1788 {
1789         struct srpt_rdma_ch *ch;
1790         int ret;
1791
1792         ch = srpt_find_channel(cm_id, false);
1793         if (!ch)
1794                 return -EINVAL;
1795
1796         if (srpt_test_and_set_channel_state(ch, RDMA_CHANNEL_CONNECTING,
1797                                             RDMA_CHANNEL_LIVE)) {
1798                 struct srpt_ioctx *ioctx, *ioctx_tmp;
1799
1800                 ret = srpt_ch_qp_rts(ch, ch->qp);
1801
1802                 list_for_each_entry_safe(ioctx, ioctx_tmp, &ch->cmd_wait_list,
1803                                          wait_list) {
1804                         list_del(&ioctx->wait_list);
1805                         srpt_handle_new_iu(ch, ioctx);
1806                 }
1807                 if (ret && srpt_test_and_set_channel_state(ch,
1808                                         RDMA_CHANNEL_LIVE,
1809                                         RDMA_CHANNEL_DISCONNECTING)) {
1810                         TRACE_DBG("cm_id=%p sess_name=%s state=%d",
1811                                   cm_id, ch->sess_name, ch->state);
1812                         ib_send_cm_dreq(ch->cm_id, NULL, 0);
1813                 }
1814         } else if (ch->state == RDMA_CHANNEL_DISCONNECTING) {
1815                 TRACE_DBG("cm_id=%p sess_name=%s state=%d",
1816                           cm_id, ch->sess_name, ch->state);
1817                 ib_send_cm_dreq(ch->cm_id, NULL, 0);
1818                 ret = -EAGAIN;
1819         } else
1820                 ret = 0;
1821
1822         return ret;
1823 }
1824
1825 static void srpt_cm_timewait_exit(struct ib_cm_id *cm_id)
1826 {
1827         TRACE_DBG("%s: cm_id=%p", __func__, cm_id);
1828         srpt_find_and_release_channel(cm_id);
1829 }
1830
1831 static void srpt_cm_rep_error(struct ib_cm_id *cm_id)
1832 {
1833         TRACE_DBG("%s: cm_id=%p", __func__, cm_id);
1834         srpt_find_and_release_channel(cm_id);
1835 }
1836
1837 static int srpt_cm_dreq_recv(struct ib_cm_id *cm_id)
1838 {
1839         struct srpt_rdma_ch *ch;
1840
1841         ch = srpt_find_channel(cm_id, false);
1842         if (!ch)
1843                 return -EINVAL;
1844
1845         TRACE_DBG("%s: cm_id= %p ch->state= %d",
1846                  __func__, cm_id, ch->state);
1847
1848         switch (ch->state) {
1849         case RDMA_CHANNEL_LIVE:
1850         case RDMA_CHANNEL_CONNECTING:
1851                 ib_send_cm_drep(ch->cm_id, NULL, 0);
1852                 break;
1853         case RDMA_CHANNEL_DISCONNECTING:
1854         default:
1855                 break;
1856         }
1857
1858         return 0;
1859 }
1860
1861 static void srpt_cm_drep_recv(struct ib_cm_id *cm_id)
1862 {
1863         TRACE_DBG("%s: cm_id=%p", __func__, cm_id);
1864         srpt_find_and_release_channel(cm_id);
1865 }
1866
1867 /**
1868  * IB connection manager callback function.
1869  *
1870  * A non-zero return value will make the caller destroy the CM ID.
1871  *
1872  * Note: srpt_add_one passes a struct srpt_device* as the third argument to
1873  * the ib_create_cm_id() call.
1874  */
1875 static int srpt_cm_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event)
1876 {
1877         int ret = 0;
1878
1879         switch (event->event) {
1880         case IB_CM_REQ_RECEIVED:
1881                 ret = srpt_cm_req_recv(cm_id, &event->param.req_rcvd,
1882                                        event->private_data);
1883                 break;
1884         case IB_CM_REJ_RECEIVED:
1885                 srpt_cm_rej_recv(cm_id);
1886                 ret = -EINVAL;
1887                 break;
1888         case IB_CM_RTU_RECEIVED:
1889         case IB_CM_USER_ESTABLISHED:
1890                 ret = srpt_cm_rtu_recv(cm_id);
1891                 break;
1892         case IB_CM_DREQ_RECEIVED:
1893                 ret = srpt_cm_dreq_recv(cm_id);
1894                 break;
1895         case IB_CM_DREP_RECEIVED:
1896                 srpt_cm_drep_recv(cm_id);
1897                 ret = -EINVAL;
1898                 break;
1899         case IB_CM_TIMEWAIT_EXIT:
1900                 srpt_cm_timewait_exit(cm_id);
1901                 ret = -EINVAL;
1902                 break;
1903         case IB_CM_REP_ERROR:
1904                 srpt_cm_rep_error(cm_id);
1905                 ret = -EINVAL;
1906                 break;
1907         default:
1908                 break;
1909         }
1910
1911         return ret;
1912 }
1913
1914 static int srpt_map_sg_to_ib_sge(struct srpt_rdma_ch *ch,
1915                                  struct srpt_ioctx *ioctx,
1916                                  struct scst_cmd *scmnd)
1917 {
1918         struct scatterlist *scat;
1919         scst_data_direction dir;
1920         struct rdma_iu *riu;
1921         struct srp_direct_buf *db;
1922         dma_addr_t dma_addr;
1923         struct ib_sge *sge;
1924         u64 raddr;
1925         u32 rsize;
1926         u32 tsize;
1927         u32 dma_len;
1928         int count, nrdma;
1929         int i, j, k;
1930
1931         scat = scst_cmd_get_sg(scmnd);
1932         dir = scst_cmd_get_data_direction(scmnd);
1933         count = dma_map_sg(ch->sport->sdev->device->dma_device, scat,
1934                            scst_cmd_get_sg_cnt(scmnd),
1935                            scst_to_tgt_dma_dir(dir));
1936         if (unlikely(!count))
1937                 return -EBUSY;
1938
1939         if (ioctx->rdma_ius && ioctx->n_rdma_ius)
1940                 nrdma = ioctx->n_rdma_ius;
1941         else {
1942                 nrdma = count / SRPT_DEF_SG_PER_WQE + ioctx->n_rbuf;
1943
1944                 ioctx->rdma_ius = kzalloc(nrdma * sizeof *riu,
1945                                           scst_cmd_atomic(scmnd)
1946                                           ? GFP_ATOMIC : GFP_KERNEL);
1947                 if (!ioctx->rdma_ius) {
1948                         dma_unmap_sg(ch->sport->sdev->device->dma_device,
1949                                      scat, scst_cmd_get_sg_cnt(scmnd),
1950                                      scst_to_tgt_dma_dir(dir));
1951                         return -ENOMEM;
1952                 }
1953
1954                 ioctx->n_rdma_ius = nrdma;
1955         }
1956
1957         db = ioctx->rbufs;
1958         tsize = (dir == SCST_DATA_READ) ?
1959                 scst_cmd_get_resp_data_len(scmnd) : scst_cmd_get_bufflen(scmnd);
1960         dma_len = sg_dma_len(&scat[0]);
1961         riu = ioctx->rdma_ius;
1962
1963         /*
1964          * For each remote desc - calculate the #ib_sge.
1965          * If #ib_sge < SRPT_DEF_SG_PER_WQE per rdma operation then
1966          *      each remote desc rdma_iu is required a rdma wr;
1967          * else
1968          *      we need to allocate extra rdma_iu to carry extra #ib_sge in
1969          *      another rdma wr
1970          */
1971         for (i = 0, j = 0;
1972              j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
1973                 rsize = be32_to_cpu(db->len);
1974                 raddr = be64_to_cpu(db->va);
1975                 riu->raddr = raddr;
1976                 riu->rkey = be32_to_cpu(db->key);
1977                 riu->sge_cnt = 0;
1978
1979                 /* calculate how many sge required for this remote_buf */
1980                 while (rsize > 0 && tsize > 0) {
1981
1982                         if (rsize >= dma_len) {
1983                                 tsize -= dma_len;
1984                                 rsize -= dma_len;
1985                                 raddr += dma_len;
1986
1987                                 if (tsize > 0) {
1988                                         ++j;
1989                                         if (j < count)
1990                                                 dma_len = sg_dma_len(&scat[j]);
1991                                 }
1992                         } else {
1993                                 tsize -= rsize;
1994                                 dma_len -= rsize;
1995                                 rsize = 0;
1996                         }
1997
1998                         ++riu->sge_cnt;
1999
2000                         if (rsize > 0 && riu->sge_cnt == SRPT_DEF_SG_PER_WQE) {
2001                                 riu->sge =
2002                                     kmalloc(riu->sge_cnt * sizeof *riu->sge,
2003                                             scst_cmd_atomic(scmnd)
2004                                             ? GFP_ATOMIC : GFP_KERNEL);
2005                                 if (!riu->sge)
2006                                         goto free_mem;
2007
2008                                 ++ioctx->n_rdma;
2009                                 ++riu;
2010                                 riu->sge_cnt = 0;
2011                                 riu->raddr = raddr;
2012                                 riu->rkey = be32_to_cpu(db->key);
2013                         }
2014                 }
2015
2016                 riu->sge = kmalloc(riu->sge_cnt * sizeof *riu->sge,
2017                                    scst_cmd_atomic(scmnd)
2018                                    ? GFP_ATOMIC : GFP_KERNEL);
2019
2020                 if (!riu->sge)
2021                         goto free_mem;
2022
2023                 ++ioctx->n_rdma;
2024         }
2025
2026         db = ioctx->rbufs;
2027         scat = scst_cmd_get_sg(scmnd);
2028         tsize = (dir == SCST_DATA_READ) ?
2029                 scst_cmd_get_resp_data_len(scmnd) : scst_cmd_get_bufflen(scmnd);
2030         riu = ioctx->rdma_ius;
2031         dma_len = sg_dma_len(&scat[0]);
2032         dma_addr = sg_dma_address(&scat[0]);
2033
2034         /* this second loop is really mapped sg_addres to rdma_iu->ib_sge */
2035         for (i = 0, j = 0;
2036              j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
2037                 rsize = be32_to_cpu(db->len);
2038                 sge = riu->sge;
2039                 k = 0;
2040
2041                 while (rsize > 0 && tsize > 0) {
2042                         sge->addr = dma_addr;
2043                         sge->lkey = ch->sport->sdev->mr->lkey;
2044
2045                         if (rsize >= dma_len) {
2046                                 sge->length =
2047                                         (tsize < dma_len) ? tsize : dma_len;
2048                                 tsize -= dma_len;
2049                                 rsize -= dma_len;
2050
2051                                 if (tsize > 0) {
2052                                         ++j;
2053                                         if (j < count) {
2054                                                 dma_len = sg_dma_len(&scat[j]);
2055                                                 dma_addr =
2056                                                     sg_dma_address(&scat[j]);
2057                                         }
2058                                 }
2059                         } else {
2060                                 sge->length = (tsize < rsize) ? tsize : rsize;
2061                                 tsize -= rsize;
2062                                 dma_len -= rsize;
2063                                 dma_addr += rsize;
2064                                 rsize = 0;
2065                         }
2066
2067                         ++k;
2068                         if (k == riu->sge_cnt && rsize > 0) {
2069                                 ++riu;
2070                                 sge = riu->sge;
2071                                 k = 0;
2072                         } else if (rsize > 0)
2073                                 ++sge;
2074                 }
2075         }
2076
2077         return 0;
2078
2079 free_mem:
2080         while (ioctx->n_rdma)
2081                 kfree(ioctx->rdma_ius[ioctx->n_rdma--].sge);
2082
2083         kfree(ioctx->rdma_ius);
2084
2085         dma_unmap_sg(ch->sport->sdev->device->dma_device,
2086                      scat, scst_cmd_get_sg_cnt(scmnd),
2087                      scst_to_tgt_dma_dir(dir));
2088
2089         return -ENOMEM;
2090 }
2091
2092 static int srpt_perform_rdmas(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx,
2093                               scst_data_direction dir)
2094 {
2095         struct ib_send_wr wr;
2096         struct ib_send_wr *bad_wr;
2097         struct rdma_iu *riu;
2098         int i;
2099         int ret = 0;
2100
2101         riu = ioctx->rdma_ius;
2102         memset(&wr, 0, sizeof wr);
2103
2104         for (i = 0; i < ioctx->n_rdma; ++i, ++riu) {
2105                 wr.opcode = (dir == SCST_DATA_READ) ?
2106                     IB_WR_RDMA_WRITE : IB_WR_RDMA_READ;
2107                 wr.next = NULL;
2108                 wr.wr_id = ioctx->index;
2109                 wr.wr.rdma.remote_addr = riu->raddr;
2110                 wr.wr.rdma.rkey = riu->rkey;
2111                 wr.num_sge = riu->sge_cnt;
2112                 wr.sg_list = riu->sge;
2113
2114                 /* only get completion event for the last rdma wr */
2115                 if (i == (ioctx->n_rdma - 1) && dir == SCST_DATA_WRITE)
2116                         wr.send_flags = IB_SEND_SIGNALED;
2117
2118                 ret = ib_post_send(ch->qp, &wr, &bad_wr);
2119                 if (ret)
2120                         break;
2121         }
2122
2123         return ret;
2124 }
2125
2126 /*
2127  * Start data reception. Must not block.
2128  */
2129 static int srpt_xfer_data(struct srpt_rdma_ch *ch, struct srpt_ioctx *ioctx,
2130                           struct scst_cmd *scmnd)
2131 {
2132         int ret;
2133
2134         ret = srpt_map_sg_to_ib_sge(ch, ioctx, scmnd);
2135         if (ret) {
2136                 printk(KERN_ERR PFX "%s[%d] ret=%d\n", __func__, __LINE__, ret);
2137                 ret = SCST_TGT_RES_QUEUE_FULL;
2138                 goto out;
2139         }
2140
2141         ret = srpt_perform_rdmas(ch, ioctx, scst_cmd_get_data_direction(scmnd));
2142         if (ret) {
2143                 printk(KERN_ERR PFX "%s[%d] ret=%d\n", __func__, __LINE__, ret);
2144                 if (ret == -EAGAIN || ret == -ENOMEM)
2145                         ret = SCST_TGT_RES_QUEUE_FULL;
2146                 else
2147                         ret = SCST_TGT_RES_FATAL_ERROR;
2148                 goto out;
2149         }
2150
2151         ret = SCST_TGT_RES_SUCCESS;
2152
2153 out:
2154         return ret;
2155 }
2156
2157 /*
2158  * Called by the SCST core to inform ib_srpt that data reception should start.
2159  * Must not block.
2160  */
2161 static int srpt_rdy_to_xfer(struct scst_cmd *scmnd)
2162 {
2163         struct srpt_rdma_ch *ch;
2164         struct srpt_ioctx *ioctx;
2165
2166         ioctx = scst_cmd_get_tgt_priv(scmnd);
2167         BUG_ON(!ioctx);
2168
2169         ch = scst_sess_get_tgt_priv(scst_cmd_get_session(scmnd));
2170         BUG_ON(!ch);
2171
2172         if (ch->state == RDMA_CHANNEL_DISCONNECTING)
2173                 return SCST_TGT_RES_FATAL_ERROR;
2174         else if (ch->state == RDMA_CHANNEL_CONNECTING)
2175                 return SCST_TGT_RES_QUEUE_FULL;
2176
2177         ioctx->state = SRPT_STATE_NEED_DATA;
2178
2179         return srpt_xfer_data(ch, ioctx, scmnd);
2180 }
2181
2182 /*
2183  * Called by the SCST core. Transmits the response buffer and status held in
2184  * 'scmnd'. Must not block.
2185  */
2186 static int srpt_xmit_response(struct scst_cmd *scmnd)
2187 {
2188         struct srpt_rdma_ch *ch;
2189         struct srpt_ioctx *ioctx;
2190         struct srp_rsp *srp_rsp;
2191         u64 tag;
2192         int ret = SCST_TGT_RES_SUCCESS;
2193         int dir;
2194         int status;
2195
2196         ioctx = scst_cmd_get_tgt_priv(scmnd);
2197         BUG_ON(!ioctx);
2198
2199         ch = scst_sess_get_tgt_priv(scst_cmd_get_session(scmnd));
2200         BUG_ON(!ch);
2201
2202         tag = scst_cmd_get_tag(scmnd);
2203
2204         if (ch->state != RDMA_CHANNEL_LIVE) {
2205                 printk(KERN_ERR PFX
2206                        "%s: tag= %lld channel in bad state %d\n",
2207                        __func__, (unsigned long long)tag, ch->state);
2208
2209                 if (ch->state == RDMA_CHANNEL_DISCONNECTING)
2210                         ret = SCST_TGT_RES_FATAL_ERROR;
2211                 else if (ch->state == RDMA_CHANNEL_CONNECTING)
2212                         ret = SCST_TGT_RES_QUEUE_FULL;
2213
2214                 if (unlikely(scst_cmd_aborted(scmnd)))
2215                         goto out_aborted;
2216
2217                 goto out;
2218         }
2219
2220         dma_sync_single_for_cpu(ch->sport->sdev->device->dma_device, ioctx->dma,
2221                                 MAX_MESSAGE_SIZE, DMA_TO_DEVICE);
2222
2223         srp_rsp = ioctx->buf;
2224
2225         if (unlikely(scst_cmd_aborted(scmnd))) {
2226                 printk(KERN_ERR PFX
2227                        "%s: tag= %lld already get aborted\n",
2228                        __func__, (unsigned long long)tag);
2229                 goto out_aborted;
2230         }
2231
2232         dir = scst_cmd_get_data_direction(scmnd);
2233         status = scst_cmd_get_status(scmnd) & 0xff;
2234
2235         srpt_build_cmd_rsp(ch, ioctx, NO_SENSE, NO_ADD_SENSE, tag);
2236
2237         if (SCST_SENSE_VALID(scst_cmd_get_sense_buffer(scmnd))) {
2238                 srp_rsp->sense_data_len = scst_cmd_get_sense_buffer_len(scmnd);
2239                 if (srp_rsp->sense_data_len >
2240                     (MAX_MESSAGE_SIZE - sizeof *srp_rsp))
2241                         srp_rsp->sense_data_len =
2242                             MAX_MESSAGE_SIZE - sizeof *srp_rsp;
2243
2244                 memcpy((u8 *) (srp_rsp + 1), scst_cmd_get_sense_buffer(scmnd),
2245                        srp_rsp->sense_data_len);
2246
2247                 srp_rsp->sense_data_len = cpu_to_be32(srp_rsp->sense_data_len);
2248                 srp_rsp->flags |= SRP_RSP_FLAG_SNSVALID;
2249
2250                 if (!status)
2251                         status = SAM_STAT_CHECK_CONDITION;
2252         }
2253
2254         srp_rsp->status = status;
2255
2256         /* transfer read data if any */
2257         if (dir == SCST_DATA_READ && scst_cmd_get_resp_data_len(scmnd)) {
2258                 ret = srpt_xfer_data(ch, ioctx, scmnd);
2259                 if (ret != SCST_TGT_RES_SUCCESS) {
2260                         printk(KERN_ERR PFX
2261                                "%s: tag= %lld xfer_data failed\n",
2262                                __func__, (unsigned long long)tag);
2263                         goto out;
2264                 }
2265         }
2266
2267         ioctx->state = SRPT_STATE_PROCESSED;
2268
2269         if (srpt_post_send(ch, ioctx,
2270                            sizeof *srp_rsp +
2271                            be32_to_cpu(srp_rsp->sense_data_len))) {
2272                 printk(KERN_ERR PFX "%s: ch->state= %d tag= %lld\n",
2273                        __func__, ch->state,
2274                        (unsigned long long)tag);
2275                 ret = SCST_TGT_RES_FATAL_ERROR;
2276         }
2277
2278 out:
2279         return ret;
2280
2281 out_aborted:
2282         ret = SCST_TGT_RES_SUCCESS;
2283         scst_set_delivery_status(scmnd, SCST_CMD_DELIVERY_ABORTED);
2284         ioctx->state = SRPT_STATE_ABORTED;
2285         scst_tgt_cmd_done(scmnd, SCST_CONTEXT_SAME);
2286         goto out;
2287 }
2288
2289 /*
2290  * Called by the SCST core to inform ib_srpt that a received task management
2291  * function has been completed. Must not block.
2292  */
2293 static void srpt_tsk_mgmt_done(struct scst_mgmt_cmd *mcmnd)
2294 {
2295         struct srpt_rdma_ch *ch;
2296         struct srpt_mgmt_ioctx *mgmt_ioctx;
2297         struct srpt_ioctx *ioctx;
2298
2299         mgmt_ioctx = scst_mgmt_cmd_get_tgt_priv(mcmnd);
2300         BUG_ON(!mgmt_ioctx);
2301
2302         ch = mgmt_ioctx->ch;
2303         BUG_ON(!ch);
2304
2305         ioctx = mgmt_ioctx->ioctx;
2306         BUG_ON(!ioctx);
2307
2308         printk(KERN_WARNING PFX
2309                "%s: tsk_mgmt_done for tag= %lld status=%d\n",
2310                __func__, (unsigned long long)mgmt_ioctx->tag,
2311                scst_mgmt_cmd_get_status(mcmnd));
2312
2313         srpt_build_tskmgmt_rsp(ch, ioctx,
2314                                (scst_mgmt_cmd_get_status(mcmnd) ==
2315                                 SCST_MGMT_STATUS_SUCCESS) ?
2316                                SRP_TSK_MGMT_SUCCESS : SRP_TSK_MGMT_FAILED,
2317                                mgmt_ioctx->tag);
2318         srpt_post_send(ch, ioctx, sizeof(struct srp_rsp) + 4);
2319
2320         scst_mgmt_cmd_set_tgt_priv(mcmnd, NULL);
2321
2322         kfree(mgmt_ioctx);
2323 }
2324
2325 /*
2326  * Called by the SCST core to inform ib_srpt that the command 'scmnd' is about
2327  * to be freed. May be called in IRQ context.
2328  */
2329 static void srpt_on_free_cmd(struct scst_cmd *scmnd)
2330 {
2331         struct srpt_rdma_ch *ch;
2332         struct srpt_ioctx *ioctx;
2333
2334         ioctx = scst_cmd_get_tgt_priv(scmnd);
2335         BUG_ON(!ioctx);
2336
2337         ch = scst_sess_get_tgt_priv(scst_cmd_get_session(scmnd));
2338         BUG_ON(!ch);
2339
2340         spin_lock_irq(&ch->spinlock);
2341         list_del(&ioctx->scmnd_list);
2342         ch->active_scmnd_cnt--;
2343         spin_unlock_irq(&ch->spinlock);
2344
2345         srpt_reset_ioctx(ch, ioctx);
2346         scst_cmd_set_tgt_priv(scmnd, NULL);
2347 }
2348
2349 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20) && ! defined(BACKPORT_LINUX_WORKQUEUE_TO_2_6_19)
2350 /* A vanilla 2.6.19 or older kernel without backported OFED kernel headers. */
2351 static void srpt_refresh_port_work(void *ctx)
2352 #else
2353 static void srpt_refresh_port_work(struct work_struct *work)
2354 #endif
2355 {
2356 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20) && ! defined(BACKPORT_LINUX_WORKQUEUE_TO_2_6_19)
2357         struct srpt_port *sport = (struct srpt_port *)ctx;
2358 #else
2359         struct srpt_port *sport = container_of(work, struct srpt_port, work);
2360 #endif
2361
2362         srpt_refresh_port(sport);
2363 }
2364
2365 /*
2366  * Called by the SCST core to detect target adapters. Returns the number of
2367  * detected target adapters.
2368  */
2369 static int srpt_detect(struct scst_tgt_template *tp)
2370 {
2371         int device_count;
2372
2373         TRACE_ENTRY();
2374
2375         device_count = atomic_read(&srpt_device_count);
2376
2377         TRACE_EXIT_RES(device_count);
2378
2379         return device_count;
2380 }
2381
2382 /*
2383  * Callback function called by the SCST core from scst_unregister() to free up
2384  * the resources associated with device scst_tgt.
2385  */
2386 static int srpt_release(struct scst_tgt *scst_tgt)
2387 {
2388         struct srpt_device *sdev = scst_tgt_get_tgt_priv(scst_tgt);
2389         struct srpt_rdma_ch *ch, *tmp_ch;
2390
2391         TRACE_ENTRY();
2392
2393         BUG_ON(!scst_tgt);
2394 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 18)
2395         WARN_ON(!sdev);
2396         if (!sdev)
2397                 return -ENODEV;
2398 #else
2399         if (WARN_ON(!sdev))
2400                 return -ENODEV;
2401 #endif
2402
2403         srpt_unregister_procfs_entry(scst_tgt->tgtt);
2404
2405         spin_lock_irq(&sdev->spinlock);
2406         list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list) {
2407                 list_del(&ch->list);
2408                 spin_unlock_irq(&sdev->spinlock);
2409                 srpt_release_channel(ch, 1);
2410                 spin_lock_irq(&sdev->spinlock);
2411         }
2412         spin_unlock_irq(&sdev->spinlock);
2413
2414         srpt_unregister_mad_agent(sdev);
2415
2416         scst_tgt_set_tgt_priv(scst_tgt, NULL);
2417
2418         TRACE_EXIT();
2419
2420         return 0;
2421 }
2422
2423 /*
2424  * Entry point for ib_srpt's kernel thread. This kernel thread is only created
2425  * when the module parameter 'thread' is not zero (the default is zero).
2426  * This thread processes the ioctx list srpt_thread.thread_ioctx_list.
2427  *
2428  * @pre thread != 0
2429  */
2430 static int srpt_ioctx_thread(void *arg)
2431 {
2432         struct srpt_ioctx *ioctx;
2433
2434         /* Hibernation / freezing of the SRPT kernel thread is not supported. */
2435         current->flags |= PF_NOFREEZE;
2436
2437         spin_lock_irq(&srpt_thread.thread_lock);
2438         while (!kthread_should_stop()) {
2439                 wait_queue_t wait;
2440                 init_waitqueue_entry(&wait, current);
2441
2442                 if (!srpt_test_ioctx_list()) {
2443                         add_wait_queue_exclusive(&ioctx_list_waitQ, &wait);
2444
2445                         for (;;) {
2446                                 set_current_state(TASK_INTERRUPTIBLE);
2447                                 if (srpt_test_ioctx_list())
2448                                         break;
2449                                 spin_unlock_irq(&srpt_thread.thread_lock);
2450                                 schedule();
2451                                 spin_lock_irq(&srpt_thread.thread_lock);
2452                         }
2453                         set_current_state(TASK_RUNNING);
2454                         remove_wait_queue(&ioctx_list_waitQ, &wait);
2455                 }
2456
2457                 while (!list_empty(&srpt_thread.thread_ioctx_list)) {
2458                         ioctx = list_entry(srpt_thread.thread_ioctx_list.next,
2459                                            struct srpt_ioctx, comp_list);
2460
2461                         list_del(&ioctx->comp_list);
2462
2463                         spin_unlock_irq(&srpt_thread.thread_lock);
2464                         switch (ioctx->op) {
2465                         case IB_WC_SEND:
2466                                 srpt_handle_send_comp(ioctx->ch, ioctx,
2467                                         SCST_CONTEXT_DIRECT);
2468                                 break;
2469                         case IB_WC_RDMA_WRITE:
2470                         case IB_WC_RDMA_READ:
2471                                 srpt_handle_rdma_comp(ioctx->ch, ioctx);
2472                                 break;
2473                         case IB_WC_RECV:
2474                                 srpt_handle_new_iu(ioctx->ch, ioctx);
2475                                 break;
2476                         default:
2477                                 break;
2478                         }
2479                         spin_lock_irq(&srpt_thread.thread_lock);
2480                 }
2481         }
2482         spin_unlock_irq(&srpt_thread.thread_lock);
2483
2484         return 0;
2485 }
2486
2487 /* SCST target template for the SRP target implementation. */
2488 static struct scst_tgt_template srpt_template = {
2489         .name = DRV_NAME,
2490         .sg_tablesize = SRPT_DEF_SG_TABLESIZE,
2491         .xmit_response_atomic = 1,
2492         .rdy_to_xfer_atomic = 1,
2493         .no_proc_entry = 0,
2494         .detect = srpt_detect,
2495         .release = srpt_release,
2496         .xmit_response = srpt_xmit_response,
2497         .rdy_to_xfer = srpt_rdy_to_xfer,
2498         .on_free_cmd = srpt_on_free_cmd,
2499         .task_mgmt_fn_done = srpt_tsk_mgmt_done
2500 };
2501
2502 /*
2503  * The callback function srpt_release_class_dev() is called whenever a
2504  * device is removed from the /sys/class/infiniband_srpt device class.
2505  */
2506 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2507 static void srpt_release_class_dev(struct class_device *class_dev)
2508 #else
2509 static void srpt_release_class_dev(struct device *dev)
2510 #endif
2511 {
2512 }
2513
2514 #if defined(CONFIG_SCST_DEBUG) || defined(CONFIG_SCST_TRACING)
2515 static int srpt_trace_level_show(struct seq_file *seq, void *v)
2516 {
2517         return scst_proc_log_entry_read(seq, trace_flag, NULL);
2518 }
2519
2520 static ssize_t srpt_proc_trace_level_write(struct file *file,
2521         const char __user *buf, size_t length, loff_t *off)
2522 {
2523         return scst_proc_log_entry_write(file, buf, length, &trace_flag,
2524                 DEFAULT_SRPT_TRACE_FLAGS, NULL);
2525 }
2526
2527 static struct scst_proc_data srpt_log_proc_data = {
2528         SCST_DEF_RW_SEQ_OP(srpt_proc_trace_level_write)
2529         .show = srpt_trace_level_show,
2530 };
2531 #endif
2532
2533 static struct class_attribute srpt_class_attrs[] = {
2534         __ATTR_NULL,
2535 };
2536
2537 static struct class srpt_class = {
2538         .name = "infiniband_srpt",
2539 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2540         .release = srpt_release_class_dev,
2541 #else
2542         .dev_release = srpt_release_class_dev,
2543 #endif
2544         .class_attrs = srpt_class_attrs,
2545 };
2546
2547 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2548 static ssize_t show_login_info(struct class_device *class_dev, char *buf)
2549 #else
2550 static ssize_t show_login_info(struct device *dev,
2551                                struct device_attribute *attr, char *buf)
2552 #endif
2553 {
2554         struct srpt_device *sdev =
2555 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2556                 container_of(class_dev, struct srpt_device, class_dev);
2557 #else
2558                 container_of(dev, struct srpt_device, dev);
2559 #endif
2560         struct srpt_port *sport;
2561         int i;
2562         int len = 0;
2563
2564         for (i = 0; i < sdev->device->phys_port_cnt; i++) {
2565                 sport = &sdev->port[i];
2566
2567                 len += sprintf(buf + len,
2568                                "tid_ext=%016llx,ioc_guid=%016llx,pkey=ffff,"
2569                                "dgid=%04x%04x%04x%04x%04x%04x%04x%04x,"
2570                                "service_id=%016llx\n",
2571                                (unsigned long long) mellanox_ioc_guid,
2572                                (unsigned long long) mellanox_ioc_guid,
2573                                be16_to_cpu(((__be16 *) sport->gid.raw)[0]),
2574                                be16_to_cpu(((__be16 *) sport->gid.raw)[1]),
2575                                be16_to_cpu(((__be16 *) sport->gid.raw)[2]),
2576                                be16_to_cpu(((__be16 *) sport->gid.raw)[3]),
2577                                be16_to_cpu(((__be16 *) sport->gid.raw)[4]),
2578                                be16_to_cpu(((__be16 *) sport->gid.raw)[5]),
2579                                be16_to_cpu(((__be16 *) sport->gid.raw)[6]),
2580                                be16_to_cpu(((__be16 *) sport->gid.raw)[7]),
2581                                (unsigned long long) mellanox_ioc_guid);
2582         }
2583
2584         return len;
2585 }
2586
2587 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2588 static CLASS_DEVICE_ATTR(login_info, S_IRUGO, show_login_info, NULL);
2589 #else
2590 static DEVICE_ATTR(login_info, S_IRUGO, show_login_info, NULL);
2591 #endif
2592
2593 /*
2594  * Callback function called by the InfiniBand core when either an InfiniBand
2595  * device has been added or during the ib_register_client() call for each
2596  * registered InfiniBand device.
2597  */
2598 static void srpt_add_one(struct ib_device *device)
2599 {
2600         struct srpt_device *sdev;
2601         struct srpt_port *sport;
2602         struct ib_srq_init_attr srq_attr;
2603         int i;
2604
2605         TRACE_ENTRY();
2606
2607         sdev = kzalloc(sizeof *sdev, GFP_KERNEL);
2608         if (!sdev)
2609                 return;
2610
2611         sdev->device = device;
2612
2613 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2614         sdev->class_dev.class = &srpt_class;
2615         sdev->class_dev.dev = device->dma_device;
2616         snprintf(sdev->class_dev.class_id, BUS_ID_SIZE,
2617                  "srpt-%s", device->name);
2618 #else
2619         sdev->dev.class = &srpt_class;
2620         sdev->dev.parent = device->dma_device;
2621 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 30)
2622         snprintf(sdev->dev.bus_id, BUS_ID_SIZE, "srpt-%s", device->name);
2623 #else
2624         snprintf(sdev->init_name, sizeof(sdev->init_name),
2625                  "srpt-%s", device->name);
2626         sdev->dev.init_name = sdev->init_name;
2627 #endif
2628 #endif
2629
2630 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2631         if (class_device_register(&sdev->class_dev))
2632                 goto free_dev;
2633         if (class_device_create_file(&sdev->class_dev,
2634                                      &class_device_attr_login_info))
2635                 goto err_dev;
2636 #else
2637         if (device_register(&sdev->dev))
2638                 goto free_dev;
2639         if (device_create_file(&sdev->dev, &dev_attr_login_info))
2640                 goto err_dev;
2641 #endif
2642
2643         if (ib_query_device(device, &sdev->dev_attr))
2644                 goto err_dev;
2645
2646         sdev->pd = ib_alloc_pd(device);
2647         if (IS_ERR(sdev->pd))
2648                 goto err_dev;
2649
2650         sdev->mr = ib_get_dma_mr(sdev->pd, IB_ACCESS_LOCAL_WRITE);
2651         if (IS_ERR(sdev->mr))
2652                 goto err_pd;
2653
2654         srq_attr.event_handler = srpt_srq_event;
2655         srq_attr.srq_context = (void *)sdev;
2656         srq_attr.attr.max_wr = min(SRPT_SRQ_SIZE, sdev->dev_attr.max_srq_wr);
2657         srq_attr.attr.max_sge = 1;
2658         srq_attr.attr.srq_limit = 0;
2659
2660         sdev->srq = ib_create_srq(sdev->pd, &srq_attr);
2661         if (IS_ERR(sdev->srq))
2662                 goto err_mr;
2663
2664         TRACE_DBG("%s: create SRQ #wr= %d max_allow=%d dev= %s",
2665                __func__, srq_attr.attr.max_wr,
2666               sdev->dev_attr.max_srq_wr, device->name);
2667
2668         if (!mellanox_ioc_guid)
2669                 mellanox_ioc_guid = be64_to_cpu(device->node_guid);
2670
2671         sdev->cm_id = ib_create_cm_id(device, srpt_cm_handler, sdev);
2672         if (IS_ERR(sdev->cm_id))
2673                 goto err_srq;
2674
2675         /* print out target login information */
2676         TRACE_DBG("Target login info: id_ext=%016llx,"
2677                   "ioc_guid=%016llx,pkey=ffff,service_id=%016llx",
2678                   (unsigned long long) mellanox_ioc_guid,
2679                   (unsigned long long) mellanox_ioc_guid,
2680                   (unsigned long long) mellanox_ioc_guid);
2681
2682         /*
2683          * We do not have a consistent service_id (ie. also id_ext of target_id)
2684          * to identify this target. We currently use the guid of the first HCA
2685          * in the system as service_id; therefore, the target_id will change
2686          * if this HCA is gone bad and replaced by different HCA
2687          */
2688         if (ib_cm_listen(sdev->cm_id, cpu_to_be64(mellanox_ioc_guid), 0, NULL))
2689                 goto err_cm;
2690
2691         INIT_IB_EVENT_HANDLER(&sdev->event_handler, sdev->device,
2692                               srpt_event_handler);
2693         if (ib_register_event_handler(&sdev->event_handler))
2694                 goto err_cm;
2695
2696         if (srpt_alloc_ioctx_ring(sdev))
2697                 goto err_event;
2698
2699         INIT_LIST_HEAD(&sdev->rch_list);
2700         spin_lock_init(&sdev->spinlock);
2701
2702         for (i = 0; i < SRPT_SRQ_SIZE; ++i)
2703                 srpt_post_recv(sdev, sdev->ioctx_ring[i]);
2704
2705         ib_set_client_data(device, &srpt_client, sdev);
2706
2707         sdev->scst_tgt = scst_register(&srpt_template, NULL);
2708         if (!sdev->scst_tgt) {
2709                 printk(KERN_ERR PFX "SCST registration failed for %s.\n",
2710                         sdev->device->name);
2711                 goto err_ring;
2712         }
2713
2714         scst_tgt_set_tgt_priv(sdev->scst_tgt, sdev);
2715
2716         for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
2717                 sport = &sdev->port[i - 1];
2718                 sport->sdev = sdev;
2719                 sport->port = i;
2720 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20) && ! defined(BACKPORT_LINUX_WORKQUEUE_TO_2_6_19)
2721                 /*
2722                  * A vanilla 2.6.19 or older kernel without backported OFED
2723                  * kernel headers.
2724                  */
2725                 INIT_WORK(&sport->work, srpt_refresh_port_work, sport);
2726 #else
2727                 INIT_WORK(&sport->work, srpt_refresh_port_work);
2728 #endif
2729                 if (srpt_refresh_port(sport)) {
2730                         printk(KERN_ERR PFX "MAD registration failed"
2731                                " for %s-%d.\n", sdev->device->name, i);
2732                         goto err_refresh_port;
2733                 }
2734         }
2735
2736         atomic_inc(&srpt_device_count);
2737
2738         TRACE_EXIT();
2739
2740         return;
2741
2742 err_refresh_port:
2743         scst_unregister(sdev->scst_tgt);
2744 err_ring:
2745         ib_set_client_data(device, &srpt_client, NULL);
2746         srpt_free_ioctx_ring(sdev);
2747 err_event:
2748         ib_unregister_event_handler(&sdev->event_handler);
2749 err_cm:
2750         ib_destroy_cm_id(sdev->cm_id);
2751 err_srq:
2752         ib_destroy_srq(sdev->srq);
2753 err_mr:
2754         ib_dereg_mr(sdev->mr);
2755 err_pd:
2756         ib_dealloc_pd(sdev->pd);
2757 err_dev:
2758 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2759         class_device_unregister(&sdev->class_dev);
2760 #else
2761         device_unregister(&sdev->dev);
2762 #endif
2763 free_dev:
2764         kfree(sdev);
2765
2766         TRACE_EXIT();
2767 }
2768
2769 /*
2770  * Callback function called by the InfiniBand core when either an InfiniBand
2771  * device has been removed or during the ib_unregister_client() call for each
2772  * registered InfiniBand device.
2773  */
2774 static void srpt_remove_one(struct ib_device *device)
2775 {
2776         int i;
2777         struct srpt_device *sdev;
2778
2779         TRACE_ENTRY();
2780
2781         sdev = ib_get_client_data(device, &srpt_client);
2782 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 18)
2783         WARN_ON(!sdev);
2784         if (!sdev)
2785                 return;
2786 #else
2787         if (WARN_ON(!sdev))
2788                 return;
2789 #endif
2790
2791         /*
2792          * Cancel the work if it is queued. Wait until srpt_refresh_port_work()
2793          * finished if it is running.
2794          */
2795         for (i = 0; i < sdev->device->phys_port_cnt; i++)
2796 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 22)
2797                 cancel_work_sync(&sdev->port[i].work);
2798 #else
2799                 /*
2800                  * cancel_work_sync() was introduced in kernel 2.6.22. Older
2801                  * kernels do not have a facility to cancel scheduled work.
2802                  */
2803                 printk(KERN_ERR PFX
2804                        "your kernel does not provide cancel_work_sync().\n");
2805 #endif
2806
2807         scst_unregister(sdev->scst_tgt);
2808         sdev->scst_tgt = NULL;
2809
2810         ib_unregister_event_handler(&sdev->event_handler);
2811         ib_destroy_cm_id(sdev->cm_id);
2812         ib_destroy_srq(sdev->srq);
2813         ib_dereg_mr(sdev->mr);
2814         ib_dealloc_pd(sdev->pd);
2815 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26)
2816         class_device_unregister(&sdev->class_dev);
2817 #else
2818         device_unregister(&sdev->dev);
2819 #endif
2820
2821         srpt_free_ioctx_ring(sdev);
2822         kfree(sdev);
2823
2824         TRACE_EXIT();
2825 }
2826
2827 /**
2828  * Create procfs entries for srpt. Currently the only procfs entry created
2829  * by this function is the "trace_level" entry.
2830  */
2831 static int srpt_register_procfs_entry(struct scst_tgt_template *tgt)
2832 {
2833         int res = 0;
2834 #if defined(CONFIG_SCST_DEBUG) || defined(CONFIG_SCST_TRACING)
2835         struct proc_dir_entry *p, *root;
2836
2837         root = scst_proc_get_tgt_root(tgt);
2838         WARN_ON(!root);
2839         if (root) {
2840                 /*
2841                  * Fill in the scst_proc_data::data pointer, which is used in
2842                  * a printk(KERN_INFO ...) statement in
2843                  * scst_proc_log_entry_write() in scst_proc.c.
2844                  */
2845                 srpt_log_proc_data.data = (char *)tgt->name;
2846                 p = scst_create_proc_entry(root, SRPT_PROC_TRACE_LEVEL_NAME,
2847                                            &srpt_log_proc_data);
2848                 if (!p)
2849                         res = -ENOMEM;
2850         } else
2851                 res = -ENOMEM;
2852
2853 #endif
2854         return res;
2855 }
2856
2857 static void srpt_unregister_procfs_entry(struct scst_tgt_template *tgt)
2858 {
2859 #if defined(CONFIG_SCST_DEBUG) || defined(CONFIG_SCST_TRACING)
2860         struct proc_dir_entry *root;
2861
2862         root = scst_proc_get_tgt_root(tgt);
2863         WARN_ON(!root);
2864         if (root)
2865                 remove_proc_entry(SRPT_PROC_TRACE_LEVEL_NAME, root);
2866 #endif
2867 }
2868
2869 /*
2870  * Module initialization.
2871  *
2872  * Note: since ib_register_client() registers callback functions, and since at
2873  * least one of these callback functions (srpt_add_one()) calls SCST functions,
2874  * the SCST target template must be registered before ib_register_client() is
2875  * called.
2876  */
2877 static int __init srpt_init_module(void)
2878 {
2879         int ret;
2880
2881         ret = class_register(&srpt_class);
2882         if (ret) {
2883                 printk(KERN_ERR PFX "couldn't register class ib_srpt\n");
2884                 goto out;
2885         }
2886
2887         ret = scst_register_target_template(&srpt_template);
2888         if (ret < 0) {
2889                 printk(KERN_ERR PFX "couldn't register with scst\n");
2890                 ret = -ENODEV;
2891                 goto out_unregister_class;
2892         }
2893
2894         ret = srpt_register_procfs_entry(&srpt_template);
2895         if (ret) {
2896                 printk(KERN_ERR PFX "couldn't register procfs entry\n");
2897                 goto out_unregister_target;
2898         }
2899
2900         ret = ib_register_client(&srpt_client);
2901         if (ret) {
2902                 printk(KERN_ERR PFX "couldn't register IB client\n");
2903                 goto out_unregister_target;
2904         }
2905
2906         if (thread) {
2907                 spin_lock_init(&srpt_thread.thread_lock);
2908                 INIT_LIST_HEAD(&srpt_thread.thread_ioctx_list);
2909                 srpt_thread.thread = kthread_run(srpt_ioctx_thread,
2910                                                  NULL, "srpt_thread");
2911                 if (IS_ERR(srpt_thread.thread)) {
2912                         srpt_thread.thread = NULL;
2913                         thread = 0;
2914                 }
2915         }
2916
2917         return 0;
2918
2919 out_unregister_target:
2920         /*
2921          * Note: the procfs entry is unregistered in srpt_release(), which is
2922          * called by scst_unregister_target_template().
2923          */
2924         scst_unregister_target_template(&srpt_template);
2925 out_unregister_class:
2926         class_unregister(&srpt_class);
2927 out:
2928         return ret;
2929 }
2930
2931 static void __exit srpt_cleanup_module(void)
2932 {
2933         TRACE_ENTRY();
2934
2935         if (srpt_thread.thread)
2936                 kthread_stop(srpt_thread.thread);
2937         ib_unregister_client(&srpt_client);
2938         scst_unregister_target_template(&srpt_template);
2939         class_unregister(&srpt_class);
2940
2941         TRACE_EXIT();
2942 }
2943
2944 module_init(srpt_init_module);
2945 module_exit(srpt_cleanup_module);