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