bffca47ade4e8addb68ffe15cf9e5f45ce107773
[linux-2.6-microblaze.git] / drivers / infiniband / ulp / srpt / ib_srpt.c
1 /*
2  * Copyright (c) 2006 - 2009 Mellanox Technology Inc.  All rights reserved.
3  * Copyright (C) 2008 - 2011 Bart Van Assche <bvanassche@acm.org>.
4  *
5  * This software is available to you under a choice of one of two
6  * licenses.  You may choose to be licensed under the terms of the GNU
7  * General Public License (GPL) Version 2, available from the file
8  * COPYING in the main directory of this source tree, or the
9  * OpenIB.org BSD license below:
10  *
11  *     Redistribution and use in source and binary forms, with or
12  *     without modification, are permitted provided that the following
13  *     conditions are met:
14  *
15  *      - Redistributions of source code must retain the above
16  *        copyright notice, this list of conditions and the following
17  *        disclaimer.
18  *
19  *      - Redistributions in binary form must reproduce the above
20  *        copyright notice, this list of conditions and the following
21  *        disclaimer in the documentation and/or other materials
22  *        provided with the distribution.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31  * SOFTWARE.
32  *
33  */
34
35 #include <linux/module.h>
36 #include <linux/init.h>
37 #include <linux/slab.h>
38 #include <linux/err.h>
39 #include <linux/ctype.h>
40 #include <linux/kthread.h>
41 #include <linux/string.h>
42 #include <linux/delay.h>
43 #include <linux/atomic.h>
44 #include <scsi/scsi_proto.h>
45 #include <scsi/scsi_tcq.h>
46 #include <target/target_core_base.h>
47 #include <target/target_core_fabric.h>
48 #include "ib_srpt.h"
49
50 /* Name of this kernel module. */
51 #define DRV_NAME                "ib_srpt"
52 #define DRV_VERSION             "2.0.0"
53 #define DRV_RELDATE             "2011-02-14"
54
55 #define SRPT_ID_STRING  "Linux SRP target"
56
57 #undef pr_fmt
58 #define pr_fmt(fmt) DRV_NAME " " fmt
59
60 MODULE_AUTHOR("Vu Pham and Bart Van Assche");
61 MODULE_DESCRIPTION("InfiniBand SCSI RDMA Protocol target "
62                    "v" DRV_VERSION " (" DRV_RELDATE ")");
63 MODULE_LICENSE("Dual BSD/GPL");
64
65 /*
66  * Global Variables
67  */
68
69 static u64 srpt_service_guid;
70 static DEFINE_SPINLOCK(srpt_dev_lock);  /* Protects srpt_dev_list. */
71 static LIST_HEAD(srpt_dev_list);        /* List of srpt_device structures. */
72
73 static unsigned srp_max_req_size = DEFAULT_MAX_REQ_SIZE;
74 module_param(srp_max_req_size, int, 0444);
75 MODULE_PARM_DESC(srp_max_req_size,
76                  "Maximum size of SRP request messages in bytes.");
77
78 static int srpt_srq_size = DEFAULT_SRPT_SRQ_SIZE;
79 module_param(srpt_srq_size, int, 0444);
80 MODULE_PARM_DESC(srpt_srq_size,
81                  "Shared receive queue (SRQ) size.");
82
83 static int srpt_get_u64_x(char *buffer, struct kernel_param *kp)
84 {
85         return sprintf(buffer, "0x%016llx", *(u64 *)kp->arg);
86 }
87 module_param_call(srpt_service_guid, NULL, srpt_get_u64_x, &srpt_service_guid,
88                   0444);
89 MODULE_PARM_DESC(srpt_service_guid,
90                  "Using this value for ioc_guid, id_ext, and cm_listen_id"
91                  " instead of using the node_guid of the first HCA.");
92
93 static struct ib_client srpt_client;
94 static void srpt_release_channel(struct srpt_rdma_ch *ch);
95 static int srpt_queue_status(struct se_cmd *cmd);
96 static void srpt_recv_done(struct ib_cq *cq, struct ib_wc *wc);
97 static void srpt_send_done(struct ib_cq *cq, struct ib_wc *wc);
98
99 /*
100  * The only allowed channel state changes are those that change the channel
101  * state into a state with a higher numerical value. Hence the new > prev test.
102  */
103 static bool srpt_set_ch_state(struct srpt_rdma_ch *ch, enum rdma_ch_state new)
104 {
105         unsigned long flags;
106         enum rdma_ch_state prev;
107         bool changed = false;
108
109         spin_lock_irqsave(&ch->spinlock, flags);
110         prev = ch->state;
111         if (new > prev) {
112                 ch->state = new;
113                 changed = true;
114         }
115         spin_unlock_irqrestore(&ch->spinlock, flags);
116
117         return changed;
118 }
119
120 /**
121  * srpt_event_handler() - Asynchronous IB event callback function.
122  *
123  * Callback function called by the InfiniBand core when an asynchronous IB
124  * event occurs. This callback may occur in interrupt context. See also
125  * section 11.5.2, Set Asynchronous Event Handler in the InfiniBand
126  * Architecture Specification.
127  */
128 static void srpt_event_handler(struct ib_event_handler *handler,
129                                struct ib_event *event)
130 {
131         struct srpt_device *sdev;
132         struct srpt_port *sport;
133
134         sdev = ib_get_client_data(event->device, &srpt_client);
135         if (!sdev || sdev->device != event->device)
136                 return;
137
138         pr_debug("ASYNC event= %d on device= %s\n", event->event,
139                  sdev->device->name);
140
141         switch (event->event) {
142         case IB_EVENT_PORT_ERR:
143                 if (event->element.port_num <= sdev->device->phys_port_cnt) {
144                         sport = &sdev->port[event->element.port_num - 1];
145                         sport->lid = 0;
146                         sport->sm_lid = 0;
147                 }
148                 break;
149         case IB_EVENT_PORT_ACTIVE:
150         case IB_EVENT_LID_CHANGE:
151         case IB_EVENT_PKEY_CHANGE:
152         case IB_EVENT_SM_CHANGE:
153         case IB_EVENT_CLIENT_REREGISTER:
154         case IB_EVENT_GID_CHANGE:
155                 /* Refresh port data asynchronously. */
156                 if (event->element.port_num <= sdev->device->phys_port_cnt) {
157                         sport = &sdev->port[event->element.port_num - 1];
158                         if (!sport->lid && !sport->sm_lid)
159                                 schedule_work(&sport->work);
160                 }
161                 break;
162         default:
163                 pr_err("received unrecognized IB event %d\n",
164                        event->event);
165                 break;
166         }
167 }
168
169 /**
170  * srpt_srq_event() - SRQ event callback function.
171  */
172 static void srpt_srq_event(struct ib_event *event, void *ctx)
173 {
174         pr_info("SRQ event %d\n", event->event);
175 }
176
177 /**
178  * srpt_qp_event() - QP event callback function.
179  */
180 static void srpt_qp_event(struct ib_event *event, struct srpt_rdma_ch *ch)
181 {
182         pr_debug("QP event %d on cm_id=%p sess_name=%s state=%d\n",
183                  event->event, ch->cm_id, ch->sess_name, ch->state);
184
185         switch (event->event) {
186         case IB_EVENT_COMM_EST:
187                 ib_cm_notify(ch->cm_id, event->event);
188                 break;
189         case IB_EVENT_QP_LAST_WQE_REACHED:
190                 if (srpt_set_ch_state(ch, CH_RELEASING))
191                         srpt_release_channel(ch);
192                 else
193                         pr_debug("%s: state %d - ignored LAST_WQE.\n",
194                                  ch->sess_name, ch->state);
195                 break;
196         default:
197                 pr_err("received unrecognized IB QP event %d\n", event->event);
198                 break;
199         }
200 }
201
202 /**
203  * srpt_set_ioc() - Helper function for initializing an IOUnitInfo structure.
204  *
205  * @slot: one-based slot number.
206  * @value: four-bit value.
207  *
208  * Copies the lowest four bits of value in element slot of the array of four
209  * bit elements called c_list (controller list). The index slot is one-based.
210  */
211 static void srpt_set_ioc(u8 *c_list, u32 slot, u8 value)
212 {
213         u16 id;
214         u8 tmp;
215
216         id = (slot - 1) / 2;
217         if (slot & 0x1) {
218                 tmp = c_list[id] & 0xf;
219                 c_list[id] = (value << 4) | tmp;
220         } else {
221                 tmp = c_list[id] & 0xf0;
222                 c_list[id] = (value & 0xf) | tmp;
223         }
224 }
225
226 /**
227  * srpt_get_class_port_info() - Copy ClassPortInfo to a management datagram.
228  *
229  * See also section 16.3.3.1 ClassPortInfo in the InfiniBand Architecture
230  * Specification.
231  */
232 static void srpt_get_class_port_info(struct ib_dm_mad *mad)
233 {
234         struct ib_class_port_info *cif;
235
236         cif = (struct ib_class_port_info *)mad->data;
237         memset(cif, 0, sizeof(*cif));
238         cif->base_version = 1;
239         cif->class_version = 1;
240         cif->resp_time_value = 20;
241
242         mad->mad_hdr.status = 0;
243 }
244
245 /**
246  * srpt_get_iou() - Write IOUnitInfo to a management datagram.
247  *
248  * See also section 16.3.3.3 IOUnitInfo in the InfiniBand Architecture
249  * Specification. See also section B.7, table B.6 in the SRP r16a document.
250  */
251 static void srpt_get_iou(struct ib_dm_mad *mad)
252 {
253         struct ib_dm_iou_info *ioui;
254         u8 slot;
255         int i;
256
257         ioui = (struct ib_dm_iou_info *)mad->data;
258         ioui->change_id = cpu_to_be16(1);
259         ioui->max_controllers = 16;
260
261         /* set present for slot 1 and empty for the rest */
262         srpt_set_ioc(ioui->controller_list, 1, 1);
263         for (i = 1, slot = 2; i < 16; i++, slot++)
264                 srpt_set_ioc(ioui->controller_list, slot, 0);
265
266         mad->mad_hdr.status = 0;
267 }
268
269 /**
270  * srpt_get_ioc() - Write IOControllerprofile to a management datagram.
271  *
272  * See also section 16.3.3.4 IOControllerProfile in the InfiniBand
273  * Architecture Specification. See also section B.7, table B.7 in the SRP
274  * r16a document.
275  */
276 static void srpt_get_ioc(struct srpt_port *sport, u32 slot,
277                          struct ib_dm_mad *mad)
278 {
279         struct srpt_device *sdev = sport->sdev;
280         struct ib_dm_ioc_profile *iocp;
281
282         iocp = (struct ib_dm_ioc_profile *)mad->data;
283
284         if (!slot || slot > 16) {
285                 mad->mad_hdr.status
286                         = cpu_to_be16(DM_MAD_STATUS_INVALID_FIELD);
287                 return;
288         }
289
290         if (slot > 2) {
291                 mad->mad_hdr.status
292                         = cpu_to_be16(DM_MAD_STATUS_NO_IOC);
293                 return;
294         }
295
296         memset(iocp, 0, sizeof(*iocp));
297         strcpy(iocp->id_string, SRPT_ID_STRING);
298         iocp->guid = cpu_to_be64(srpt_service_guid);
299         iocp->vendor_id = cpu_to_be32(sdev->device->attrs.vendor_id);
300         iocp->device_id = cpu_to_be32(sdev->device->attrs.vendor_part_id);
301         iocp->device_version = cpu_to_be16(sdev->device->attrs.hw_ver);
302         iocp->subsys_vendor_id = cpu_to_be32(sdev->device->attrs.vendor_id);
303         iocp->subsys_device_id = 0x0;
304         iocp->io_class = cpu_to_be16(SRP_REV16A_IB_IO_CLASS);
305         iocp->io_subclass = cpu_to_be16(SRP_IO_SUBCLASS);
306         iocp->protocol = cpu_to_be16(SRP_PROTOCOL);
307         iocp->protocol_version = cpu_to_be16(SRP_PROTOCOL_VERSION);
308         iocp->send_queue_depth = cpu_to_be16(sdev->srq_size);
309         iocp->rdma_read_depth = 4;
310         iocp->send_size = cpu_to_be32(srp_max_req_size);
311         iocp->rdma_size = cpu_to_be32(min(sport->port_attrib.srp_max_rdma_size,
312                                           1U << 24));
313         iocp->num_svc_entries = 1;
314         iocp->op_cap_mask = SRP_SEND_TO_IOC | SRP_SEND_FROM_IOC |
315                 SRP_RDMA_READ_FROM_IOC | SRP_RDMA_WRITE_FROM_IOC;
316
317         mad->mad_hdr.status = 0;
318 }
319
320 /**
321  * srpt_get_svc_entries() - Write ServiceEntries to a management datagram.
322  *
323  * See also section 16.3.3.5 ServiceEntries in the InfiniBand Architecture
324  * Specification. See also section B.7, table B.8 in the SRP r16a document.
325  */
326 static void srpt_get_svc_entries(u64 ioc_guid,
327                                  u16 slot, u8 hi, u8 lo, struct ib_dm_mad *mad)
328 {
329         struct ib_dm_svc_entries *svc_entries;
330
331         WARN_ON(!ioc_guid);
332
333         if (!slot || slot > 16) {
334                 mad->mad_hdr.status
335                         = cpu_to_be16(DM_MAD_STATUS_INVALID_FIELD);
336                 return;
337         }
338
339         if (slot > 2 || lo > hi || hi > 1) {
340                 mad->mad_hdr.status
341                         = cpu_to_be16(DM_MAD_STATUS_NO_IOC);
342                 return;
343         }
344
345         svc_entries = (struct ib_dm_svc_entries *)mad->data;
346         memset(svc_entries, 0, sizeof(*svc_entries));
347         svc_entries->service_entries[0].id = cpu_to_be64(ioc_guid);
348         snprintf(svc_entries->service_entries[0].name,
349                  sizeof(svc_entries->service_entries[0].name),
350                  "%s%016llx",
351                  SRP_SERVICE_NAME_PREFIX,
352                  ioc_guid);
353
354         mad->mad_hdr.status = 0;
355 }
356
357 /**
358  * srpt_mgmt_method_get() - Process a received management datagram.
359  * @sp:      source port through which the MAD has been received.
360  * @rq_mad:  received MAD.
361  * @rsp_mad: response MAD.
362  */
363 static void srpt_mgmt_method_get(struct srpt_port *sp, struct ib_mad *rq_mad,
364                                  struct ib_dm_mad *rsp_mad)
365 {
366         u16 attr_id;
367         u32 slot;
368         u8 hi, lo;
369
370         attr_id = be16_to_cpu(rq_mad->mad_hdr.attr_id);
371         switch (attr_id) {
372         case DM_ATTR_CLASS_PORT_INFO:
373                 srpt_get_class_port_info(rsp_mad);
374                 break;
375         case DM_ATTR_IOU_INFO:
376                 srpt_get_iou(rsp_mad);
377                 break;
378         case DM_ATTR_IOC_PROFILE:
379                 slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
380                 srpt_get_ioc(sp, slot, rsp_mad);
381                 break;
382         case DM_ATTR_SVC_ENTRIES:
383                 slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
384                 hi = (u8) ((slot >> 8) & 0xff);
385                 lo = (u8) (slot & 0xff);
386                 slot = (u16) ((slot >> 16) & 0xffff);
387                 srpt_get_svc_entries(srpt_service_guid,
388                                      slot, hi, lo, rsp_mad);
389                 break;
390         default:
391                 rsp_mad->mad_hdr.status =
392                     cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
393                 break;
394         }
395 }
396
397 /**
398  * srpt_mad_send_handler() - Post MAD-send callback function.
399  */
400 static void srpt_mad_send_handler(struct ib_mad_agent *mad_agent,
401                                   struct ib_mad_send_wc *mad_wc)
402 {
403         ib_destroy_ah(mad_wc->send_buf->ah);
404         ib_free_send_mad(mad_wc->send_buf);
405 }
406
407 /**
408  * srpt_mad_recv_handler() - MAD reception callback function.
409  */
410 static void srpt_mad_recv_handler(struct ib_mad_agent *mad_agent,
411                                   struct ib_mad_send_buf *send_buf,
412                                   struct ib_mad_recv_wc *mad_wc)
413 {
414         struct srpt_port *sport = (struct srpt_port *)mad_agent->context;
415         struct ib_ah *ah;
416         struct ib_mad_send_buf *rsp;
417         struct ib_dm_mad *dm_mad;
418
419         if (!mad_wc || !mad_wc->recv_buf.mad)
420                 return;
421
422         ah = ib_create_ah_from_wc(mad_agent->qp->pd, mad_wc->wc,
423                                   mad_wc->recv_buf.grh, mad_agent->port_num);
424         if (IS_ERR(ah))
425                 goto err;
426
427         BUILD_BUG_ON(offsetof(struct ib_dm_mad, data) != IB_MGMT_DEVICE_HDR);
428
429         rsp = ib_create_send_mad(mad_agent, mad_wc->wc->src_qp,
430                                  mad_wc->wc->pkey_index, 0,
431                                  IB_MGMT_DEVICE_HDR, IB_MGMT_DEVICE_DATA,
432                                  GFP_KERNEL,
433                                  IB_MGMT_BASE_VERSION);
434         if (IS_ERR(rsp))
435                 goto err_rsp;
436
437         rsp->ah = ah;
438
439         dm_mad = rsp->mad;
440         memcpy(dm_mad, mad_wc->recv_buf.mad, sizeof(*dm_mad));
441         dm_mad->mad_hdr.method = IB_MGMT_METHOD_GET_RESP;
442         dm_mad->mad_hdr.status = 0;
443
444         switch (mad_wc->recv_buf.mad->mad_hdr.method) {
445         case IB_MGMT_METHOD_GET:
446                 srpt_mgmt_method_get(sport, mad_wc->recv_buf.mad, dm_mad);
447                 break;
448         case IB_MGMT_METHOD_SET:
449                 dm_mad->mad_hdr.status =
450                     cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
451                 break;
452         default:
453                 dm_mad->mad_hdr.status =
454                     cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD);
455                 break;
456         }
457
458         if (!ib_post_send_mad(rsp, NULL)) {
459                 ib_free_recv_mad(mad_wc);
460                 /* will destroy_ah & free_send_mad in send completion */
461                 return;
462         }
463
464         ib_free_send_mad(rsp);
465
466 err_rsp:
467         ib_destroy_ah(ah);
468 err:
469         ib_free_recv_mad(mad_wc);
470 }
471
472 /**
473  * srpt_refresh_port() - Configure a HCA port.
474  *
475  * Enable InfiniBand management datagram processing, update the cached sm_lid,
476  * lid and gid values, and register a callback function for processing MADs
477  * on the specified port.
478  *
479  * Note: It is safe to call this function more than once for the same port.
480  */
481 static int srpt_refresh_port(struct srpt_port *sport)
482 {
483         struct ib_mad_reg_req reg_req;
484         struct ib_port_modify port_modify;
485         struct ib_port_attr port_attr;
486         int ret;
487
488         memset(&port_modify, 0, sizeof(port_modify));
489         port_modify.set_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP;
490         port_modify.clr_port_cap_mask = 0;
491
492         ret = ib_modify_port(sport->sdev->device, sport->port, 0, &port_modify);
493         if (ret)
494                 goto err_mod_port;
495
496         ret = ib_query_port(sport->sdev->device, sport->port, &port_attr);
497         if (ret)
498                 goto err_query_port;
499
500         sport->sm_lid = port_attr.sm_lid;
501         sport->lid = port_attr.lid;
502
503         ret = ib_query_gid(sport->sdev->device, sport->port, 0, &sport->gid,
504                            NULL);
505         if (ret)
506                 goto err_query_port;
507
508         if (!sport->mad_agent) {
509                 memset(&reg_req, 0, sizeof(reg_req));
510                 reg_req.mgmt_class = IB_MGMT_CLASS_DEVICE_MGMT;
511                 reg_req.mgmt_class_version = IB_MGMT_BASE_VERSION;
512                 set_bit(IB_MGMT_METHOD_GET, reg_req.method_mask);
513                 set_bit(IB_MGMT_METHOD_SET, reg_req.method_mask);
514
515                 sport->mad_agent = ib_register_mad_agent(sport->sdev->device,
516                                                          sport->port,
517                                                          IB_QPT_GSI,
518                                                          &reg_req, 0,
519                                                          srpt_mad_send_handler,
520                                                          srpt_mad_recv_handler,
521                                                          sport, 0);
522                 if (IS_ERR(sport->mad_agent)) {
523                         ret = PTR_ERR(sport->mad_agent);
524                         sport->mad_agent = NULL;
525                         goto err_query_port;
526                 }
527         }
528
529         return 0;
530
531 err_query_port:
532
533         port_modify.set_port_cap_mask = 0;
534         port_modify.clr_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP;
535         ib_modify_port(sport->sdev->device, sport->port, 0, &port_modify);
536
537 err_mod_port:
538
539         return ret;
540 }
541
542 /**
543  * srpt_unregister_mad_agent() - Unregister MAD callback functions.
544  *
545  * Note: It is safe to call this function more than once for the same device.
546  */
547 static void srpt_unregister_mad_agent(struct srpt_device *sdev)
548 {
549         struct ib_port_modify port_modify = {
550                 .clr_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP,
551         };
552         struct srpt_port *sport;
553         int i;
554
555         for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
556                 sport = &sdev->port[i - 1];
557                 WARN_ON(sport->port != i);
558                 if (ib_modify_port(sdev->device, i, 0, &port_modify) < 0)
559                         pr_err("disabling MAD processing failed.\n");
560                 if (sport->mad_agent) {
561                         ib_unregister_mad_agent(sport->mad_agent);
562                         sport->mad_agent = NULL;
563                 }
564         }
565 }
566
567 /**
568  * srpt_alloc_ioctx() - Allocate an SRPT I/O context structure.
569  */
570 static struct srpt_ioctx *srpt_alloc_ioctx(struct srpt_device *sdev,
571                                            int ioctx_size, int dma_size,
572                                            enum dma_data_direction dir)
573 {
574         struct srpt_ioctx *ioctx;
575
576         ioctx = kmalloc(ioctx_size, GFP_KERNEL);
577         if (!ioctx)
578                 goto err;
579
580         ioctx->buf = kmalloc(dma_size, GFP_KERNEL);
581         if (!ioctx->buf)
582                 goto err_free_ioctx;
583
584         ioctx->dma = ib_dma_map_single(sdev->device, ioctx->buf, dma_size, dir);
585         if (ib_dma_mapping_error(sdev->device, ioctx->dma))
586                 goto err_free_buf;
587
588         return ioctx;
589
590 err_free_buf:
591         kfree(ioctx->buf);
592 err_free_ioctx:
593         kfree(ioctx);
594 err:
595         return NULL;
596 }
597
598 /**
599  * srpt_free_ioctx() - Free an SRPT I/O context structure.
600  */
601 static void srpt_free_ioctx(struct srpt_device *sdev, struct srpt_ioctx *ioctx,
602                             int dma_size, enum dma_data_direction dir)
603 {
604         if (!ioctx)
605                 return;
606
607         ib_dma_unmap_single(sdev->device, ioctx->dma, dma_size, dir);
608         kfree(ioctx->buf);
609         kfree(ioctx);
610 }
611
612 /**
613  * srpt_alloc_ioctx_ring() - Allocate a ring of SRPT I/O context structures.
614  * @sdev:       Device to allocate the I/O context ring for.
615  * @ring_size:  Number of elements in the I/O context ring.
616  * @ioctx_size: I/O context size.
617  * @dma_size:   DMA buffer size.
618  * @dir:        DMA data direction.
619  */
620 static struct srpt_ioctx **srpt_alloc_ioctx_ring(struct srpt_device *sdev,
621                                 int ring_size, int ioctx_size,
622                                 int dma_size, enum dma_data_direction dir)
623 {
624         struct srpt_ioctx **ring;
625         int i;
626
627         WARN_ON(ioctx_size != sizeof(struct srpt_recv_ioctx)
628                 && ioctx_size != sizeof(struct srpt_send_ioctx));
629
630         ring = kmalloc(ring_size * sizeof(ring[0]), GFP_KERNEL);
631         if (!ring)
632                 goto out;
633         for (i = 0; i < ring_size; ++i) {
634                 ring[i] = srpt_alloc_ioctx(sdev, ioctx_size, dma_size, dir);
635                 if (!ring[i])
636                         goto err;
637                 ring[i]->index = i;
638         }
639         goto out;
640
641 err:
642         while (--i >= 0)
643                 srpt_free_ioctx(sdev, ring[i], dma_size, dir);
644         kfree(ring);
645         ring = NULL;
646 out:
647         return ring;
648 }
649
650 /**
651  * srpt_free_ioctx_ring() - Free the ring of SRPT I/O context structures.
652  */
653 static void srpt_free_ioctx_ring(struct srpt_ioctx **ioctx_ring,
654                                  struct srpt_device *sdev, int ring_size,
655                                  int dma_size, enum dma_data_direction dir)
656 {
657         int i;
658
659         for (i = 0; i < ring_size; ++i)
660                 srpt_free_ioctx(sdev, ioctx_ring[i], dma_size, dir);
661         kfree(ioctx_ring);
662 }
663
664 /**
665  * srpt_get_cmd_state() - Get the state of a SCSI command.
666  */
667 static enum srpt_command_state srpt_get_cmd_state(struct srpt_send_ioctx *ioctx)
668 {
669         enum srpt_command_state state;
670         unsigned long flags;
671
672         BUG_ON(!ioctx);
673
674         spin_lock_irqsave(&ioctx->spinlock, flags);
675         state = ioctx->state;
676         spin_unlock_irqrestore(&ioctx->spinlock, flags);
677         return state;
678 }
679
680 /**
681  * srpt_set_cmd_state() - Set the state of a SCSI command.
682  *
683  * Does not modify the state of aborted commands. Returns the previous command
684  * state.
685  */
686 static enum srpt_command_state srpt_set_cmd_state(struct srpt_send_ioctx *ioctx,
687                                                   enum srpt_command_state new)
688 {
689         enum srpt_command_state previous;
690         unsigned long flags;
691
692         BUG_ON(!ioctx);
693
694         spin_lock_irqsave(&ioctx->spinlock, flags);
695         previous = ioctx->state;
696         if (previous != SRPT_STATE_DONE)
697                 ioctx->state = new;
698         spin_unlock_irqrestore(&ioctx->spinlock, flags);
699
700         return previous;
701 }
702
703 /**
704  * srpt_test_and_set_cmd_state() - Test and set the state of a command.
705  *
706  * Returns true if and only if the previous command state was equal to 'old'.
707  */
708 static bool srpt_test_and_set_cmd_state(struct srpt_send_ioctx *ioctx,
709                                         enum srpt_command_state old,
710                                         enum srpt_command_state new)
711 {
712         enum srpt_command_state previous;
713         unsigned long flags;
714
715         WARN_ON(!ioctx);
716         WARN_ON(old == SRPT_STATE_DONE);
717         WARN_ON(new == SRPT_STATE_NEW);
718
719         spin_lock_irqsave(&ioctx->spinlock, flags);
720         previous = ioctx->state;
721         if (previous == old)
722                 ioctx->state = new;
723         spin_unlock_irqrestore(&ioctx->spinlock, flags);
724         return previous == old;
725 }
726
727 /**
728  * srpt_post_recv() - Post an IB receive request.
729  */
730 static int srpt_post_recv(struct srpt_device *sdev,
731                           struct srpt_recv_ioctx *ioctx)
732 {
733         struct ib_sge list;
734         struct ib_recv_wr wr, *bad_wr;
735
736         BUG_ON(!sdev);
737         list.addr = ioctx->ioctx.dma;
738         list.length = srp_max_req_size;
739         list.lkey = sdev->pd->local_dma_lkey;
740
741         ioctx->ioctx.cqe.done = srpt_recv_done;
742         wr.wr_cqe = &ioctx->ioctx.cqe;
743         wr.next = NULL;
744         wr.sg_list = &list;
745         wr.num_sge = 1;
746
747         return ib_post_srq_recv(sdev->srq, &wr, &bad_wr);
748 }
749
750 /**
751  * srpt_post_send() - Post an IB send request.
752  *
753  * Returns zero upon success and a non-zero value upon failure.
754  */
755 static int srpt_post_send(struct srpt_rdma_ch *ch,
756                           struct srpt_send_ioctx *ioctx, int len)
757 {
758         struct ib_sge list;
759         struct ib_send_wr wr, *bad_wr;
760         struct srpt_device *sdev = ch->sport->sdev;
761         int ret;
762
763         atomic_inc(&ch->req_lim);
764
765         ret = -ENOMEM;
766         if (unlikely(atomic_dec_return(&ch->sq_wr_avail) < 0)) {
767                 pr_warn("IB send queue full (needed 1)\n");
768                 goto out;
769         }
770
771         ib_dma_sync_single_for_device(sdev->device, ioctx->ioctx.dma, len,
772                                       DMA_TO_DEVICE);
773
774         list.addr = ioctx->ioctx.dma;
775         list.length = len;
776         list.lkey = sdev->pd->local_dma_lkey;
777
778         ioctx->ioctx.cqe.done = srpt_send_done;
779         wr.next = NULL;
780         wr.wr_cqe = &ioctx->ioctx.cqe;
781         wr.sg_list = &list;
782         wr.num_sge = 1;
783         wr.opcode = IB_WR_SEND;
784         wr.send_flags = IB_SEND_SIGNALED;
785
786         ret = ib_post_send(ch->qp, &wr, &bad_wr);
787
788 out:
789         if (ret < 0) {
790                 atomic_inc(&ch->sq_wr_avail);
791                 atomic_dec(&ch->req_lim);
792         }
793         return ret;
794 }
795
796 /**
797  * srpt_get_desc_tbl() - Parse the data descriptors of an SRP_CMD request.
798  * @ioctx: Pointer to the I/O context associated with the request.
799  * @srp_cmd: Pointer to the SRP_CMD request data.
800  * @dir: Pointer to the variable to which the transfer direction will be
801  *   written.
802  * @data_len: Pointer to the variable to which the total data length of all
803  *   descriptors in the SRP_CMD request will be written.
804  *
805  * This function initializes ioctx->nrbuf and ioctx->r_bufs.
806  *
807  * Returns -EINVAL when the SRP_CMD request contains inconsistent descriptors;
808  * -ENOMEM when memory allocation fails and zero upon success.
809  */
810 static int srpt_get_desc_tbl(struct srpt_send_ioctx *ioctx,
811                              struct srp_cmd *srp_cmd,
812                              enum dma_data_direction *dir, u64 *data_len)
813 {
814         struct srp_indirect_buf *idb;
815         struct srp_direct_buf *db;
816         unsigned add_cdb_offset;
817         int ret;
818
819         /*
820          * The pointer computations below will only be compiled correctly
821          * if srp_cmd::add_data is declared as s8*, u8*, s8[] or u8[], so check
822          * whether srp_cmd::add_data has been declared as a byte pointer.
823          */
824         BUILD_BUG_ON(!__same_type(srp_cmd->add_data[0], (s8)0)
825                      && !__same_type(srp_cmd->add_data[0], (u8)0));
826
827         BUG_ON(!dir);
828         BUG_ON(!data_len);
829
830         ret = 0;
831         *data_len = 0;
832
833         /*
834          * The lower four bits of the buffer format field contain the DATA-IN
835          * buffer descriptor format, and the highest four bits contain the
836          * DATA-OUT buffer descriptor format.
837          */
838         *dir = DMA_NONE;
839         if (srp_cmd->buf_fmt & 0xf)
840                 /* DATA-IN: transfer data from target to initiator (read). */
841                 *dir = DMA_FROM_DEVICE;
842         else if (srp_cmd->buf_fmt >> 4)
843                 /* DATA-OUT: transfer data from initiator to target (write). */
844                 *dir = DMA_TO_DEVICE;
845
846         /*
847          * According to the SRP spec, the lower two bits of the 'ADDITIONAL
848          * CDB LENGTH' field are reserved and the size in bytes of this field
849          * is four times the value specified in bits 3..7. Hence the "& ~3".
850          */
851         add_cdb_offset = srp_cmd->add_cdb_len & ~3;
852         if (((srp_cmd->buf_fmt & 0xf) == SRP_DATA_DESC_DIRECT) ||
853             ((srp_cmd->buf_fmt >> 4) == SRP_DATA_DESC_DIRECT)) {
854                 ioctx->n_rbuf = 1;
855                 ioctx->rbufs = &ioctx->single_rbuf;
856
857                 db = (struct srp_direct_buf *)(srp_cmd->add_data
858                                                + add_cdb_offset);
859                 memcpy(ioctx->rbufs, db, sizeof(*db));
860                 *data_len = be32_to_cpu(db->len);
861         } else if (((srp_cmd->buf_fmt & 0xf) == SRP_DATA_DESC_INDIRECT) ||
862                    ((srp_cmd->buf_fmt >> 4) == SRP_DATA_DESC_INDIRECT)) {
863                 idb = (struct srp_indirect_buf *)(srp_cmd->add_data
864                                                   + add_cdb_offset);
865
866                 ioctx->n_rbuf = be32_to_cpu(idb->table_desc.len) / sizeof(*db);
867
868                 if (ioctx->n_rbuf >
869                     (srp_cmd->data_out_desc_cnt + srp_cmd->data_in_desc_cnt)) {
870                         pr_err("received unsupported SRP_CMD request"
871                                " type (%u out + %u in != %u / %zu)\n",
872                                srp_cmd->data_out_desc_cnt,
873                                srp_cmd->data_in_desc_cnt,
874                                be32_to_cpu(idb->table_desc.len),
875                                sizeof(*db));
876                         ioctx->n_rbuf = 0;
877                         ret = -EINVAL;
878                         goto out;
879                 }
880
881                 if (ioctx->n_rbuf == 1)
882                         ioctx->rbufs = &ioctx->single_rbuf;
883                 else {
884                         ioctx->rbufs =
885                                 kmalloc(ioctx->n_rbuf * sizeof(*db), GFP_ATOMIC);
886                         if (!ioctx->rbufs) {
887                                 ioctx->n_rbuf = 0;
888                                 ret = -ENOMEM;
889                                 goto out;
890                         }
891                 }
892
893                 db = idb->desc_list;
894                 memcpy(ioctx->rbufs, db, ioctx->n_rbuf * sizeof(*db));
895                 *data_len = be32_to_cpu(idb->len);
896         }
897 out:
898         return ret;
899 }
900
901 /**
902  * srpt_init_ch_qp() - Initialize queue pair attributes.
903  *
904  * Initialized the attributes of queue pair 'qp' by allowing local write,
905  * remote read and remote write. Also transitions 'qp' to state IB_QPS_INIT.
906  */
907 static int srpt_init_ch_qp(struct srpt_rdma_ch *ch, struct ib_qp *qp)
908 {
909         struct ib_qp_attr *attr;
910         int ret;
911
912         attr = kzalloc(sizeof(*attr), GFP_KERNEL);
913         if (!attr)
914                 return -ENOMEM;
915
916         attr->qp_state = IB_QPS_INIT;
917         attr->qp_access_flags = IB_ACCESS_LOCAL_WRITE | IB_ACCESS_REMOTE_READ |
918             IB_ACCESS_REMOTE_WRITE;
919         attr->port_num = ch->sport->port;
920         attr->pkey_index = 0;
921
922         ret = ib_modify_qp(qp, attr,
923                            IB_QP_STATE | IB_QP_ACCESS_FLAGS | IB_QP_PORT |
924                            IB_QP_PKEY_INDEX);
925
926         kfree(attr);
927         return ret;
928 }
929
930 /**
931  * srpt_ch_qp_rtr() - Change the state of a channel to 'ready to receive' (RTR).
932  * @ch: channel of the queue pair.
933  * @qp: queue pair to change the state of.
934  *
935  * Returns zero upon success and a negative value upon failure.
936  *
937  * Note: currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
938  * If this structure ever becomes larger, it might be necessary to allocate
939  * it dynamically instead of on the stack.
940  */
941 static int srpt_ch_qp_rtr(struct srpt_rdma_ch *ch, struct ib_qp *qp)
942 {
943         struct ib_qp_attr qp_attr;
944         int attr_mask;
945         int ret;
946
947         qp_attr.qp_state = IB_QPS_RTR;
948         ret = ib_cm_init_qp_attr(ch->cm_id, &qp_attr, &attr_mask);
949         if (ret)
950                 goto out;
951
952         qp_attr.max_dest_rd_atomic = 4;
953
954         ret = ib_modify_qp(qp, &qp_attr, attr_mask);
955
956 out:
957         return ret;
958 }
959
960 /**
961  * srpt_ch_qp_rts() - Change the state of a channel to 'ready to send' (RTS).
962  * @ch: channel of the queue pair.
963  * @qp: queue pair to change the state of.
964  *
965  * Returns zero upon success and a negative value upon failure.
966  *
967  * Note: currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
968  * If this structure ever becomes larger, it might be necessary to allocate
969  * it dynamically instead of on the stack.
970  */
971 static int srpt_ch_qp_rts(struct srpt_rdma_ch *ch, struct ib_qp *qp)
972 {
973         struct ib_qp_attr qp_attr;
974         int attr_mask;
975         int ret;
976
977         qp_attr.qp_state = IB_QPS_RTS;
978         ret = ib_cm_init_qp_attr(ch->cm_id, &qp_attr, &attr_mask);
979         if (ret)
980                 goto out;
981
982         qp_attr.max_rd_atomic = 4;
983
984         ret = ib_modify_qp(qp, &qp_attr, attr_mask);
985
986 out:
987         return ret;
988 }
989
990 /**
991  * srpt_ch_qp_err() - Set the channel queue pair state to 'error'.
992  */
993 static int srpt_ch_qp_err(struct srpt_rdma_ch *ch)
994 {
995         struct ib_qp_attr qp_attr;
996
997         qp_attr.qp_state = IB_QPS_ERR;
998         return ib_modify_qp(ch->qp, &qp_attr, IB_QP_STATE);
999 }
1000
1001 /**
1002  * srpt_unmap_sg_to_ib_sge() - Unmap an IB SGE list.
1003  */
1004 static void srpt_unmap_sg_to_ib_sge(struct srpt_rdma_ch *ch,
1005                                     struct srpt_send_ioctx *ioctx)
1006 {
1007         struct scatterlist *sg;
1008         enum dma_data_direction dir;
1009
1010         BUG_ON(!ch);
1011         BUG_ON(!ioctx);
1012         BUG_ON(ioctx->n_rdma && !ioctx->rdma_wrs);
1013
1014         while (ioctx->n_rdma)
1015                 kfree(ioctx->rdma_wrs[--ioctx->n_rdma].wr.sg_list);
1016
1017         kfree(ioctx->rdma_wrs);
1018         ioctx->rdma_wrs = NULL;
1019
1020         if (ioctx->mapped_sg_count) {
1021                 sg = ioctx->sg;
1022                 WARN_ON(!sg);
1023                 dir = ioctx->cmd.data_direction;
1024                 BUG_ON(dir == DMA_NONE);
1025                 ib_dma_unmap_sg(ch->sport->sdev->device, sg, ioctx->sg_cnt,
1026                                 target_reverse_dma_direction(&ioctx->cmd));
1027                 ioctx->mapped_sg_count = 0;
1028         }
1029 }
1030
1031 /**
1032  * srpt_map_sg_to_ib_sge() - Map an SG list to an IB SGE list.
1033  */
1034 static int srpt_map_sg_to_ib_sge(struct srpt_rdma_ch *ch,
1035                                  struct srpt_send_ioctx *ioctx)
1036 {
1037         struct ib_device *dev = ch->sport->sdev->device;
1038         struct se_cmd *cmd;
1039         struct scatterlist *sg, *sg_orig;
1040         int sg_cnt;
1041         enum dma_data_direction dir;
1042         struct ib_rdma_wr *riu;
1043         struct srp_direct_buf *db;
1044         dma_addr_t dma_addr;
1045         struct ib_sge *sge;
1046         u64 raddr;
1047         u32 rsize;
1048         u32 tsize;
1049         u32 dma_len;
1050         int count, nrdma;
1051         int i, j, k;
1052
1053         BUG_ON(!ch);
1054         BUG_ON(!ioctx);
1055         cmd = &ioctx->cmd;
1056         dir = cmd->data_direction;
1057         BUG_ON(dir == DMA_NONE);
1058
1059         ioctx->sg = sg = sg_orig = cmd->t_data_sg;
1060         ioctx->sg_cnt = sg_cnt = cmd->t_data_nents;
1061
1062         count = ib_dma_map_sg(ch->sport->sdev->device, sg, sg_cnt,
1063                               target_reverse_dma_direction(cmd));
1064         if (unlikely(!count))
1065                 return -EAGAIN;
1066
1067         ioctx->mapped_sg_count = count;
1068
1069         if (ioctx->rdma_wrs && ioctx->n_rdma_wrs)
1070                 nrdma = ioctx->n_rdma_wrs;
1071         else {
1072                 nrdma = (count + SRPT_DEF_SG_PER_WQE - 1) / SRPT_DEF_SG_PER_WQE
1073                         + ioctx->n_rbuf;
1074
1075                 ioctx->rdma_wrs = kcalloc(nrdma, sizeof(*ioctx->rdma_wrs),
1076                                 GFP_KERNEL);
1077                 if (!ioctx->rdma_wrs)
1078                         goto free_mem;
1079
1080                 ioctx->n_rdma_wrs = nrdma;
1081         }
1082
1083         db = ioctx->rbufs;
1084         tsize = cmd->data_length;
1085         dma_len = ib_sg_dma_len(dev, &sg[0]);
1086         riu = ioctx->rdma_wrs;
1087
1088         /*
1089          * For each remote desc - calculate the #ib_sge.
1090          * If #ib_sge < SRPT_DEF_SG_PER_WQE per rdma operation then
1091          *      each remote desc rdma_iu is required a rdma wr;
1092          * else
1093          *      we need to allocate extra rdma_iu to carry extra #ib_sge in
1094          *      another rdma wr
1095          */
1096         for (i = 0, j = 0;
1097              j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
1098                 rsize = be32_to_cpu(db->len);
1099                 raddr = be64_to_cpu(db->va);
1100                 riu->remote_addr = raddr;
1101                 riu->rkey = be32_to_cpu(db->key);
1102                 riu->wr.num_sge = 0;
1103
1104                 /* calculate how many sge required for this remote_buf */
1105                 while (rsize > 0 && tsize > 0) {
1106
1107                         if (rsize >= dma_len) {
1108                                 tsize -= dma_len;
1109                                 rsize -= dma_len;
1110                                 raddr += dma_len;
1111
1112                                 if (tsize > 0) {
1113                                         ++j;
1114                                         if (j < count) {
1115                                                 sg = sg_next(sg);
1116                                                 dma_len = ib_sg_dma_len(
1117                                                                 dev, sg);
1118                                         }
1119                                 }
1120                         } else {
1121                                 tsize -= rsize;
1122                                 dma_len -= rsize;
1123                                 rsize = 0;
1124                         }
1125
1126                         ++riu->wr.num_sge;
1127
1128                         if (rsize > 0 &&
1129                             riu->wr.num_sge == SRPT_DEF_SG_PER_WQE) {
1130                                 ++ioctx->n_rdma;
1131                                 riu->wr.sg_list = kmalloc_array(riu->wr.num_sge,
1132                                                 sizeof(*riu->wr.sg_list),
1133                                                 GFP_KERNEL);
1134                                 if (!riu->wr.sg_list)
1135                                         goto free_mem;
1136
1137                                 ++riu;
1138                                 riu->wr.num_sge = 0;
1139                                 riu->remote_addr = raddr;
1140                                 riu->rkey = be32_to_cpu(db->key);
1141                         }
1142                 }
1143
1144                 ++ioctx->n_rdma;
1145                 riu->wr.sg_list = kmalloc_array(riu->wr.num_sge,
1146                                         sizeof(*riu->wr.sg_list),
1147                                         GFP_KERNEL);
1148                 if (!riu->wr.sg_list)
1149                         goto free_mem;
1150         }
1151
1152         db = ioctx->rbufs;
1153         tsize = cmd->data_length;
1154         riu = ioctx->rdma_wrs;
1155         sg = sg_orig;
1156         dma_len = ib_sg_dma_len(dev, &sg[0]);
1157         dma_addr = ib_sg_dma_address(dev, &sg[0]);
1158
1159         /* this second loop is really mapped sg_addres to rdma_iu->ib_sge */
1160         for (i = 0, j = 0;
1161              j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
1162                 rsize = be32_to_cpu(db->len);
1163                 sge = riu->wr.sg_list;
1164                 k = 0;
1165
1166                 while (rsize > 0 && tsize > 0) {
1167                         sge->addr = dma_addr;
1168                         sge->lkey = ch->sport->sdev->pd->local_dma_lkey;
1169
1170                         if (rsize >= dma_len) {
1171                                 sge->length =
1172                                         (tsize < dma_len) ? tsize : dma_len;
1173                                 tsize -= dma_len;
1174                                 rsize -= dma_len;
1175
1176                                 if (tsize > 0) {
1177                                         ++j;
1178                                         if (j < count) {
1179                                                 sg = sg_next(sg);
1180                                                 dma_len = ib_sg_dma_len(
1181                                                                 dev, sg);
1182                                                 dma_addr = ib_sg_dma_address(
1183                                                                 dev, sg);
1184                                         }
1185                                 }
1186                         } else {
1187                                 sge->length = (tsize < rsize) ? tsize : rsize;
1188                                 tsize -= rsize;
1189                                 dma_len -= rsize;
1190                                 dma_addr += rsize;
1191                                 rsize = 0;
1192                         }
1193
1194                         ++k;
1195                         if (k == riu->wr.num_sge && rsize > 0 && tsize > 0) {
1196                                 ++riu;
1197                                 sge = riu->wr.sg_list;
1198                                 k = 0;
1199                         } else if (rsize > 0 && tsize > 0)
1200                                 ++sge;
1201                 }
1202         }
1203
1204         return 0;
1205
1206 free_mem:
1207         srpt_unmap_sg_to_ib_sge(ch, ioctx);
1208
1209         return -ENOMEM;
1210 }
1211
1212 /**
1213  * srpt_get_send_ioctx() - Obtain an I/O context for sending to the initiator.
1214  */
1215 static struct srpt_send_ioctx *srpt_get_send_ioctx(struct srpt_rdma_ch *ch)
1216 {
1217         struct srpt_send_ioctx *ioctx;
1218         unsigned long flags;
1219
1220         BUG_ON(!ch);
1221
1222         ioctx = NULL;
1223         spin_lock_irqsave(&ch->spinlock, flags);
1224         if (!list_empty(&ch->free_list)) {
1225                 ioctx = list_first_entry(&ch->free_list,
1226                                          struct srpt_send_ioctx, free_list);
1227                 list_del(&ioctx->free_list);
1228         }
1229         spin_unlock_irqrestore(&ch->spinlock, flags);
1230
1231         if (!ioctx)
1232                 return ioctx;
1233
1234         BUG_ON(ioctx->ch != ch);
1235         spin_lock_init(&ioctx->spinlock);
1236         ioctx->state = SRPT_STATE_NEW;
1237         ioctx->n_rbuf = 0;
1238         ioctx->rbufs = NULL;
1239         ioctx->n_rdma = 0;
1240         ioctx->n_rdma_wrs = 0;
1241         ioctx->rdma_wrs = NULL;
1242         ioctx->mapped_sg_count = 0;
1243         init_completion(&ioctx->tx_done);
1244         ioctx->queue_status_only = false;
1245         /*
1246          * transport_init_se_cmd() does not initialize all fields, so do it
1247          * here.
1248          */
1249         memset(&ioctx->cmd, 0, sizeof(ioctx->cmd));
1250         memset(&ioctx->sense_data, 0, sizeof(ioctx->sense_data));
1251
1252         return ioctx;
1253 }
1254
1255 /**
1256  * srpt_abort_cmd() - Abort a SCSI command.
1257  * @ioctx:   I/O context associated with the SCSI command.
1258  * @context: Preferred execution context.
1259  */
1260 static int srpt_abort_cmd(struct srpt_send_ioctx *ioctx)
1261 {
1262         enum srpt_command_state state;
1263         unsigned long flags;
1264
1265         BUG_ON(!ioctx);
1266
1267         /*
1268          * If the command is in a state where the target core is waiting for
1269          * the ib_srpt driver, change the state to the next state. Changing
1270          * the state of the command from SRPT_STATE_NEED_DATA to
1271          * SRPT_STATE_DATA_IN ensures that srpt_xmit_response() will call this
1272          * function a second time.
1273          */
1274
1275         spin_lock_irqsave(&ioctx->spinlock, flags);
1276         state = ioctx->state;
1277         switch (state) {
1278         case SRPT_STATE_NEED_DATA:
1279                 ioctx->state = SRPT_STATE_DATA_IN;
1280                 break;
1281         case SRPT_STATE_DATA_IN:
1282         case SRPT_STATE_CMD_RSP_SENT:
1283         case SRPT_STATE_MGMT_RSP_SENT:
1284                 ioctx->state = SRPT_STATE_DONE;
1285                 break;
1286         default:
1287                 break;
1288         }
1289         spin_unlock_irqrestore(&ioctx->spinlock, flags);
1290
1291         if (state == SRPT_STATE_DONE) {
1292                 struct srpt_rdma_ch *ch = ioctx->ch;
1293
1294                 BUG_ON(ch->sess == NULL);
1295
1296                 target_put_sess_cmd(&ioctx->cmd);
1297                 goto out;
1298         }
1299
1300         pr_debug("Aborting cmd with state %d and tag %lld\n", state,
1301                  ioctx->cmd.tag);
1302
1303         switch (state) {
1304         case SRPT_STATE_NEW:
1305         case SRPT_STATE_DATA_IN:
1306         case SRPT_STATE_MGMT:
1307                 /*
1308                  * Do nothing - defer abort processing until
1309                  * srpt_queue_response() is invoked.
1310                  */
1311                 WARN_ON(!transport_check_aborted_status(&ioctx->cmd, false));
1312                 break;
1313         case SRPT_STATE_NEED_DATA:
1314                 /* DMA_TO_DEVICE (write) - RDMA read error. */
1315
1316                 /* XXX(hch): this is a horrible layering violation.. */
1317                 spin_lock_irqsave(&ioctx->cmd.t_state_lock, flags);
1318                 ioctx->cmd.transport_state &= ~CMD_T_ACTIVE;
1319                 spin_unlock_irqrestore(&ioctx->cmd.t_state_lock, flags);
1320                 break;
1321         case SRPT_STATE_CMD_RSP_SENT:
1322                 /*
1323                  * SRP_RSP sending failed or the SRP_RSP send completion has
1324                  * not been received in time.
1325                  */
1326                 srpt_unmap_sg_to_ib_sge(ioctx->ch, ioctx);
1327                 target_put_sess_cmd(&ioctx->cmd);
1328                 break;
1329         case SRPT_STATE_MGMT_RSP_SENT:
1330                 srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
1331                 target_put_sess_cmd(&ioctx->cmd);
1332                 break;
1333         default:
1334                 WARN(1, "Unexpected command state (%d)", state);
1335                 break;
1336         }
1337
1338 out:
1339         return state;
1340 }
1341
1342 /**
1343  * XXX: what is now target_execute_cmd used to be asynchronous, and unmapping
1344  * the data that has been transferred via IB RDMA had to be postponed until the
1345  * check_stop_free() callback.  None of this is necessary anymore and needs to
1346  * be cleaned up.
1347  */
1348 static void srpt_rdma_read_done(struct ib_cq *cq, struct ib_wc *wc)
1349 {
1350         struct srpt_rdma_ch *ch = cq->cq_context;
1351         struct srpt_send_ioctx *ioctx =
1352                 container_of(wc->wr_cqe, struct srpt_send_ioctx, rdma_cqe);
1353
1354         WARN_ON(ioctx->n_rdma <= 0);
1355         atomic_add(ioctx->n_rdma, &ch->sq_wr_avail);
1356
1357         if (unlikely(wc->status != IB_WC_SUCCESS)) {
1358                 pr_info("RDMA_READ for ioctx 0x%p failed with status %d\n",
1359                         ioctx, wc->status);
1360                 srpt_abort_cmd(ioctx);
1361                 return;
1362         }
1363
1364         if (srpt_test_and_set_cmd_state(ioctx, SRPT_STATE_NEED_DATA,
1365                                         SRPT_STATE_DATA_IN))
1366                 target_execute_cmd(&ioctx->cmd);
1367         else
1368                 pr_err("%s[%d]: wrong state = %d\n", __func__,
1369                        __LINE__, srpt_get_cmd_state(ioctx));
1370 }
1371
1372 static void srpt_rdma_write_done(struct ib_cq *cq, struct ib_wc *wc)
1373 {
1374         struct srpt_send_ioctx *ioctx =
1375                 container_of(wc->wr_cqe, struct srpt_send_ioctx, rdma_cqe);
1376
1377         if (unlikely(wc->status != IB_WC_SUCCESS)) {
1378                 pr_info("RDMA_WRITE for ioctx 0x%p failed with status %d\n",
1379                         ioctx, wc->status);
1380                 srpt_abort_cmd(ioctx);
1381         }
1382 }
1383
1384 /**
1385  * srpt_build_cmd_rsp() - Build an SRP_RSP response.
1386  * @ch: RDMA channel through which the request has been received.
1387  * @ioctx: I/O context associated with the SRP_CMD request. The response will
1388  *   be built in the buffer ioctx->buf points at and hence this function will
1389  *   overwrite the request data.
1390  * @tag: tag of the request for which this response is being generated.
1391  * @status: value for the STATUS field of the SRP_RSP information unit.
1392  *
1393  * Returns the size in bytes of the SRP_RSP response.
1394  *
1395  * An SRP_RSP response contains a SCSI status or service response. See also
1396  * section 6.9 in the SRP r16a document for the format of an SRP_RSP
1397  * response. See also SPC-2 for more information about sense data.
1398  */
1399 static int srpt_build_cmd_rsp(struct srpt_rdma_ch *ch,
1400                               struct srpt_send_ioctx *ioctx, u64 tag,
1401                               int status)
1402 {
1403         struct srp_rsp *srp_rsp;
1404         const u8 *sense_data;
1405         int sense_data_len, max_sense_len;
1406
1407         /*
1408          * The lowest bit of all SAM-3 status codes is zero (see also
1409          * paragraph 5.3 in SAM-3).
1410          */
1411         WARN_ON(status & 1);
1412
1413         srp_rsp = ioctx->ioctx.buf;
1414         BUG_ON(!srp_rsp);
1415
1416         sense_data = ioctx->sense_data;
1417         sense_data_len = ioctx->cmd.scsi_sense_length;
1418         WARN_ON(sense_data_len > sizeof(ioctx->sense_data));
1419
1420         memset(srp_rsp, 0, sizeof(*srp_rsp));
1421         srp_rsp->opcode = SRP_RSP;
1422         srp_rsp->req_lim_delta =
1423                 cpu_to_be32(1 + atomic_xchg(&ch->req_lim_delta, 0));
1424         srp_rsp->tag = tag;
1425         srp_rsp->status = status;
1426
1427         if (sense_data_len) {
1428                 BUILD_BUG_ON(MIN_MAX_RSP_SIZE <= sizeof(*srp_rsp));
1429                 max_sense_len = ch->max_ti_iu_len - sizeof(*srp_rsp);
1430                 if (sense_data_len > max_sense_len) {
1431                         pr_warn("truncated sense data from %d to %d"
1432                                 " bytes\n", sense_data_len, max_sense_len);
1433                         sense_data_len = max_sense_len;
1434                 }
1435
1436                 srp_rsp->flags |= SRP_RSP_FLAG_SNSVALID;
1437                 srp_rsp->sense_data_len = cpu_to_be32(sense_data_len);
1438                 memcpy(srp_rsp + 1, sense_data, sense_data_len);
1439         }
1440
1441         return sizeof(*srp_rsp) + sense_data_len;
1442 }
1443
1444 /**
1445  * srpt_build_tskmgmt_rsp() - Build a task management response.
1446  * @ch:       RDMA channel through which the request has been received.
1447  * @ioctx:    I/O context in which the SRP_RSP response will be built.
1448  * @rsp_code: RSP_CODE that will be stored in the response.
1449  * @tag:      Tag of the request for which this response is being generated.
1450  *
1451  * Returns the size in bytes of the SRP_RSP response.
1452  *
1453  * An SRP_RSP response contains a SCSI status or service response. See also
1454  * section 6.9 in the SRP r16a document for the format of an SRP_RSP
1455  * response.
1456  */
1457 static int srpt_build_tskmgmt_rsp(struct srpt_rdma_ch *ch,
1458                                   struct srpt_send_ioctx *ioctx,
1459                                   u8 rsp_code, u64 tag)
1460 {
1461         struct srp_rsp *srp_rsp;
1462         int resp_data_len;
1463         int resp_len;
1464
1465         resp_data_len = 4;
1466         resp_len = sizeof(*srp_rsp) + resp_data_len;
1467
1468         srp_rsp = ioctx->ioctx.buf;
1469         BUG_ON(!srp_rsp);
1470         memset(srp_rsp, 0, sizeof(*srp_rsp));
1471
1472         srp_rsp->opcode = SRP_RSP;
1473         srp_rsp->req_lim_delta =
1474                 cpu_to_be32(1 + atomic_xchg(&ch->req_lim_delta, 0));
1475         srp_rsp->tag = tag;
1476
1477         srp_rsp->flags |= SRP_RSP_FLAG_RSPVALID;
1478         srp_rsp->resp_data_len = cpu_to_be32(resp_data_len);
1479         srp_rsp->data[3] = rsp_code;
1480
1481         return resp_len;
1482 }
1483
1484 static int srpt_check_stop_free(struct se_cmd *cmd)
1485 {
1486         struct srpt_send_ioctx *ioctx = container_of(cmd,
1487                                 struct srpt_send_ioctx, cmd);
1488
1489         return target_put_sess_cmd(&ioctx->cmd);
1490 }
1491
1492 /**
1493  * srpt_handle_cmd() - Process SRP_CMD.
1494  */
1495 static int srpt_handle_cmd(struct srpt_rdma_ch *ch,
1496                            struct srpt_recv_ioctx *recv_ioctx,
1497                            struct srpt_send_ioctx *send_ioctx)
1498 {
1499         struct se_cmd *cmd;
1500         struct srp_cmd *srp_cmd;
1501         u64 data_len;
1502         enum dma_data_direction dir;
1503         sense_reason_t ret;
1504         int rc;
1505
1506         BUG_ON(!send_ioctx);
1507
1508         srp_cmd = recv_ioctx->ioctx.buf;
1509         cmd = &send_ioctx->cmd;
1510         cmd->tag = srp_cmd->tag;
1511
1512         switch (srp_cmd->task_attr) {
1513         case SRP_CMD_SIMPLE_Q:
1514                 cmd->sam_task_attr = TCM_SIMPLE_TAG;
1515                 break;
1516         case SRP_CMD_ORDERED_Q:
1517         default:
1518                 cmd->sam_task_attr = TCM_ORDERED_TAG;
1519                 break;
1520         case SRP_CMD_HEAD_OF_Q:
1521                 cmd->sam_task_attr = TCM_HEAD_TAG;
1522                 break;
1523         case SRP_CMD_ACA:
1524                 cmd->sam_task_attr = TCM_ACA_TAG;
1525                 break;
1526         }
1527
1528         if (srpt_get_desc_tbl(send_ioctx, srp_cmd, &dir, &data_len)) {
1529                 pr_err("0x%llx: parsing SRP descriptor table failed.\n",
1530                        srp_cmd->tag);
1531                 ret = TCM_INVALID_CDB_FIELD;
1532                 goto send_sense;
1533         }
1534
1535         rc = target_submit_cmd(cmd, ch->sess, srp_cmd->cdb,
1536                                &send_ioctx->sense_data[0],
1537                                scsilun_to_int(&srp_cmd->lun), data_len,
1538                                TCM_SIMPLE_TAG, dir, TARGET_SCF_ACK_KREF);
1539         if (rc != 0) {
1540                 ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1541                 goto send_sense;
1542         }
1543         return 0;
1544
1545 send_sense:
1546         transport_send_check_condition_and_sense(cmd, ret, 0);
1547         return -1;
1548 }
1549
1550 static int srp_tmr_to_tcm(int fn)
1551 {
1552         switch (fn) {
1553         case SRP_TSK_ABORT_TASK:
1554                 return TMR_ABORT_TASK;
1555         case SRP_TSK_ABORT_TASK_SET:
1556                 return TMR_ABORT_TASK_SET;
1557         case SRP_TSK_CLEAR_TASK_SET:
1558                 return TMR_CLEAR_TASK_SET;
1559         case SRP_TSK_LUN_RESET:
1560                 return TMR_LUN_RESET;
1561         case SRP_TSK_CLEAR_ACA:
1562                 return TMR_CLEAR_ACA;
1563         default:
1564                 return -1;
1565         }
1566 }
1567
1568 /**
1569  * srpt_handle_tsk_mgmt() - Process an SRP_TSK_MGMT information unit.
1570  *
1571  * Returns 0 if and only if the request will be processed by the target core.
1572  *
1573  * For more information about SRP_TSK_MGMT information units, see also section
1574  * 6.7 in the SRP r16a document.
1575  */
1576 static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,
1577                                  struct srpt_recv_ioctx *recv_ioctx,
1578                                  struct srpt_send_ioctx *send_ioctx)
1579 {
1580         struct srp_tsk_mgmt *srp_tsk;
1581         struct se_cmd *cmd;
1582         struct se_session *sess = ch->sess;
1583         int tcm_tmr;
1584         int rc;
1585
1586         BUG_ON(!send_ioctx);
1587
1588         srp_tsk = recv_ioctx->ioctx.buf;
1589         cmd = &send_ioctx->cmd;
1590
1591         pr_debug("recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld"
1592                  " cm_id %p sess %p\n", srp_tsk->tsk_mgmt_func,
1593                  srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess);
1594
1595         srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT);
1596         send_ioctx->cmd.tag = srp_tsk->tag;
1597         tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func);
1598         rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL,
1599                                scsilun_to_int(&srp_tsk->lun), srp_tsk, tcm_tmr,
1600                                GFP_KERNEL, srp_tsk->task_tag,
1601                                TARGET_SCF_ACK_KREF);
1602         if (rc != 0) {
1603                 send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED;
1604                 goto fail;
1605         }
1606         return;
1607 fail:
1608         transport_send_check_condition_and_sense(cmd, 0, 0); // XXX:
1609 }
1610
1611 /**
1612  * srpt_handle_new_iu() - Process a newly received information unit.
1613  * @ch:    RDMA channel through which the information unit has been received.
1614  * @ioctx: SRPT I/O context associated with the information unit.
1615  */
1616 static void srpt_handle_new_iu(struct srpt_rdma_ch *ch,
1617                                struct srpt_recv_ioctx *recv_ioctx,
1618                                struct srpt_send_ioctx *send_ioctx)
1619 {
1620         struct srp_cmd *srp_cmd;
1621
1622         BUG_ON(!ch);
1623         BUG_ON(!recv_ioctx);
1624
1625         ib_dma_sync_single_for_cpu(ch->sport->sdev->device,
1626                                    recv_ioctx->ioctx.dma, srp_max_req_size,
1627                                    DMA_FROM_DEVICE);
1628
1629         if (unlikely(ch->state == CH_CONNECTING)) {
1630                 list_add_tail(&recv_ioctx->wait_list, &ch->cmd_wait_list);
1631                 goto out;
1632         }
1633
1634         if (unlikely(ch->state != CH_LIVE))
1635                 goto out;
1636
1637         srp_cmd = recv_ioctx->ioctx.buf;
1638         if (srp_cmd->opcode == SRP_CMD || srp_cmd->opcode == SRP_TSK_MGMT) {
1639                 if (!send_ioctx)
1640                         send_ioctx = srpt_get_send_ioctx(ch);
1641                 if (unlikely(!send_ioctx)) {
1642                         list_add_tail(&recv_ioctx->wait_list,
1643                                       &ch->cmd_wait_list);
1644                         goto out;
1645                 }
1646         }
1647
1648         switch (srp_cmd->opcode) {
1649         case SRP_CMD:
1650                 srpt_handle_cmd(ch, recv_ioctx, send_ioctx);
1651                 break;
1652         case SRP_TSK_MGMT:
1653                 srpt_handle_tsk_mgmt(ch, recv_ioctx, send_ioctx);
1654                 break;
1655         case SRP_I_LOGOUT:
1656                 pr_err("Not yet implemented: SRP_I_LOGOUT\n");
1657                 break;
1658         case SRP_CRED_RSP:
1659                 pr_debug("received SRP_CRED_RSP\n");
1660                 break;
1661         case SRP_AER_RSP:
1662                 pr_debug("received SRP_AER_RSP\n");
1663                 break;
1664         case SRP_RSP:
1665                 pr_err("Received SRP_RSP\n");
1666                 break;
1667         default:
1668                 pr_err("received IU with unknown opcode 0x%x\n",
1669                        srp_cmd->opcode);
1670                 break;
1671         }
1672
1673         srpt_post_recv(ch->sport->sdev, recv_ioctx);
1674 out:
1675         return;
1676 }
1677
1678 static void srpt_recv_done(struct ib_cq *cq, struct ib_wc *wc)
1679 {
1680         struct srpt_rdma_ch *ch = cq->cq_context;
1681         struct srpt_recv_ioctx *ioctx =
1682                 container_of(wc->wr_cqe, struct srpt_recv_ioctx, ioctx.cqe);
1683
1684         if (wc->status == IB_WC_SUCCESS) {
1685                 int req_lim;
1686
1687                 req_lim = atomic_dec_return(&ch->req_lim);
1688                 if (unlikely(req_lim < 0))
1689                         pr_err("req_lim = %d < 0\n", req_lim);
1690                 srpt_handle_new_iu(ch, ioctx, NULL);
1691         } else {
1692                 pr_info("receiving failed for ioctx %p with status %d\n",
1693                         ioctx, wc->status);
1694         }
1695 }
1696
1697 /**
1698  * Note: Although this has not yet been observed during tests, at least in
1699  * theory it is possible that the srpt_get_send_ioctx() call invoked by
1700  * srpt_handle_new_iu() fails. This is possible because the req_lim_delta
1701  * value in each response is set to one, and it is possible that this response
1702  * makes the initiator send a new request before the send completion for that
1703  * response has been processed. This could e.g. happen if the call to
1704  * srpt_put_send_iotcx() is delayed because of a higher priority interrupt or
1705  * if IB retransmission causes generation of the send completion to be
1706  * delayed. Incoming information units for which srpt_get_send_ioctx() fails
1707  * are queued on cmd_wait_list. The code below processes these delayed
1708  * requests one at a time.
1709  */
1710 static void srpt_send_done(struct ib_cq *cq, struct ib_wc *wc)
1711 {
1712         struct srpt_rdma_ch *ch = cq->cq_context;
1713         struct srpt_send_ioctx *ioctx =
1714                 container_of(wc->wr_cqe, struct srpt_send_ioctx, ioctx.cqe);
1715         enum srpt_command_state state;
1716
1717         state = srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
1718
1719         WARN_ON(state != SRPT_STATE_CMD_RSP_SENT &&
1720                 state != SRPT_STATE_MGMT_RSP_SENT);
1721
1722         atomic_inc(&ch->sq_wr_avail);
1723
1724         if (wc->status != IB_WC_SUCCESS) {
1725                 pr_info("sending response for ioctx 0x%p failed"
1726                         " with status %d\n", ioctx, wc->status);
1727
1728                 atomic_dec(&ch->req_lim);
1729                 srpt_abort_cmd(ioctx);
1730                 goto out;
1731         }
1732
1733         if (state != SRPT_STATE_DONE) {
1734                 srpt_unmap_sg_to_ib_sge(ch, ioctx);
1735                 transport_generic_free_cmd(&ioctx->cmd, 0);
1736         } else {
1737                 pr_err("IB completion has been received too late for"
1738                        " wr_id = %u.\n", ioctx->ioctx.index);
1739         }
1740
1741 out:
1742         while (!list_empty(&ch->cmd_wait_list) &&
1743                ch->state == CH_LIVE &&
1744                (ioctx = srpt_get_send_ioctx(ch)) != NULL) {
1745                 struct srpt_recv_ioctx *recv_ioctx;
1746
1747                 recv_ioctx = list_first_entry(&ch->cmd_wait_list,
1748                                               struct srpt_recv_ioctx,
1749                                               wait_list);
1750                 list_del(&recv_ioctx->wait_list);
1751                 srpt_handle_new_iu(ch, recv_ioctx, ioctx);
1752         }
1753 }
1754
1755 /**
1756  * srpt_create_ch_ib() - Create receive and send completion queues.
1757  */
1758 static int srpt_create_ch_ib(struct srpt_rdma_ch *ch)
1759 {
1760         struct ib_qp_init_attr *qp_init;
1761         struct srpt_port *sport = ch->sport;
1762         struct srpt_device *sdev = sport->sdev;
1763         u32 srp_sq_size = sport->port_attrib.srp_sq_size;
1764         int ret;
1765
1766         WARN_ON(ch->rq_size < 1);
1767
1768         ret = -ENOMEM;
1769         qp_init = kzalloc(sizeof(*qp_init), GFP_KERNEL);
1770         if (!qp_init)
1771                 goto out;
1772
1773 retry:
1774         ch->cq = ib_alloc_cq(sdev->device, ch, ch->rq_size + srp_sq_size,
1775                         0 /* XXX: spread CQs */, IB_POLL_WORKQUEUE);
1776         if (IS_ERR(ch->cq)) {
1777                 ret = PTR_ERR(ch->cq);
1778                 pr_err("failed to create CQ cqe= %d ret= %d\n",
1779                        ch->rq_size + srp_sq_size, ret);
1780                 goto out;
1781         }
1782
1783         qp_init->qp_context = (void *)ch;
1784         qp_init->event_handler
1785                 = (void(*)(struct ib_event *, void*))srpt_qp_event;
1786         qp_init->send_cq = ch->cq;
1787         qp_init->recv_cq = ch->cq;
1788         qp_init->srq = sdev->srq;
1789         qp_init->sq_sig_type = IB_SIGNAL_REQ_WR;
1790         qp_init->qp_type = IB_QPT_RC;
1791         qp_init->cap.max_send_wr = srp_sq_size;
1792         qp_init->cap.max_send_sge = SRPT_DEF_SG_PER_WQE;
1793
1794         ch->qp = ib_create_qp(sdev->pd, qp_init);
1795         if (IS_ERR(ch->qp)) {
1796                 ret = PTR_ERR(ch->qp);
1797                 if (ret == -ENOMEM) {
1798                         srp_sq_size /= 2;
1799                         if (srp_sq_size >= MIN_SRPT_SQ_SIZE) {
1800                                 ib_destroy_cq(ch->cq);
1801                                 goto retry;
1802                         }
1803                 }
1804                 pr_err("failed to create_qp ret= %d\n", ret);
1805                 goto err_destroy_cq;
1806         }
1807
1808         atomic_set(&ch->sq_wr_avail, qp_init->cap.max_send_wr);
1809
1810         pr_debug("%s: max_cqe= %d max_sge= %d sq_size = %d cm_id= %p\n",
1811                  __func__, ch->cq->cqe, qp_init->cap.max_send_sge,
1812                  qp_init->cap.max_send_wr, ch->cm_id);
1813
1814         ret = srpt_init_ch_qp(ch, ch->qp);
1815         if (ret)
1816                 goto err_destroy_qp;
1817
1818 out:
1819         kfree(qp_init);
1820         return ret;
1821
1822 err_destroy_qp:
1823         ib_destroy_qp(ch->qp);
1824 err_destroy_cq:
1825         ib_free_cq(ch->cq);
1826         goto out;
1827 }
1828
1829 static void srpt_destroy_ch_ib(struct srpt_rdma_ch *ch)
1830 {
1831         ib_destroy_qp(ch->qp);
1832         ib_free_cq(ch->cq);
1833 }
1834
1835 /**
1836  * __srpt_close_ch() - Close an RDMA channel by setting the QP error state.
1837  *
1838  * Reset the QP and make sure all resources associated with the channel will
1839  * be deallocated at an appropriate time.
1840  *
1841  * Note: The caller must hold ch->sport->sdev->spinlock.
1842  */
1843 static void __srpt_close_ch(struct srpt_rdma_ch *ch)
1844 {
1845         enum rdma_ch_state prev_state;
1846         unsigned long flags;
1847
1848         spin_lock_irqsave(&ch->spinlock, flags);
1849         prev_state = ch->state;
1850         switch (prev_state) {
1851         case CH_CONNECTING:
1852         case CH_LIVE:
1853                 ch->state = CH_DISCONNECTING;
1854                 break;
1855         default:
1856                 break;
1857         }
1858         spin_unlock_irqrestore(&ch->spinlock, flags);
1859
1860         switch (prev_state) {
1861         case CH_CONNECTING:
1862                 ib_send_cm_rej(ch->cm_id, IB_CM_REJ_NO_RESOURCES, NULL, 0,
1863                                NULL, 0);
1864                 /* fall through */
1865         case CH_LIVE:
1866                 if (ib_send_cm_dreq(ch->cm_id, NULL, 0) < 0)
1867                         pr_err("sending CM DREQ failed.\n");
1868                 break;
1869         case CH_DISCONNECTING:
1870                 break;
1871         case CH_DRAINING:
1872         case CH_RELEASING:
1873                 break;
1874         }
1875 }
1876
1877 /**
1878  * srpt_close_ch() - Close an RDMA channel.
1879  */
1880 static void srpt_close_ch(struct srpt_rdma_ch *ch)
1881 {
1882         struct srpt_device *sdev;
1883
1884         sdev = ch->sport->sdev;
1885         spin_lock_irq(&sdev->spinlock);
1886         __srpt_close_ch(ch);
1887         spin_unlock_irq(&sdev->spinlock);
1888 }
1889
1890 /**
1891  * srpt_shutdown_session() - Whether or not a session may be shut down.
1892  */
1893 static int srpt_shutdown_session(struct se_session *se_sess)
1894 {
1895         return 1;
1896 }
1897
1898 /**
1899  * srpt_drain_channel() - Drain a channel by resetting the IB queue pair.
1900  * @cm_id: Pointer to the CM ID of the channel to be drained.
1901  *
1902  * Note: Must be called from inside srpt_cm_handler to avoid a race between
1903  * accessing sdev->spinlock and the call to kfree(sdev) in srpt_remove_one()
1904  * (the caller of srpt_cm_handler holds the cm_id spinlock; srpt_remove_one()
1905  * waits until all target sessions for the associated IB device have been
1906  * unregistered and target session registration involves a call to
1907  * ib_destroy_cm_id(), which locks the cm_id spinlock and hence waits until
1908  * this function has finished).
1909  */
1910 static void srpt_drain_channel(struct ib_cm_id *cm_id)
1911 {
1912         struct srpt_device *sdev;
1913         struct srpt_rdma_ch *ch;
1914         int ret;
1915         bool do_reset = false;
1916
1917         WARN_ON_ONCE(irqs_disabled());
1918
1919         sdev = cm_id->context;
1920         BUG_ON(!sdev);
1921         spin_lock_irq(&sdev->spinlock);
1922         list_for_each_entry(ch, &sdev->rch_list, list) {
1923                 if (ch->cm_id == cm_id) {
1924                         do_reset = srpt_set_ch_state(ch, CH_DRAINING);
1925                         break;
1926                 }
1927         }
1928         spin_unlock_irq(&sdev->spinlock);
1929
1930         if (do_reset) {
1931                 if (ch->sess)
1932                         srpt_shutdown_session(ch->sess);
1933
1934                 ret = srpt_ch_qp_err(ch);
1935                 if (ret < 0)
1936                         pr_err("Setting queue pair in error state"
1937                                " failed: %d\n", ret);
1938         }
1939 }
1940
1941 /**
1942  * srpt_find_channel() - Look up an RDMA channel.
1943  * @cm_id: Pointer to the CM ID of the channel to be looked up.
1944  *
1945  * Return NULL if no matching RDMA channel has been found.
1946  */
1947 static struct srpt_rdma_ch *srpt_find_channel(struct srpt_device *sdev,
1948                                               struct ib_cm_id *cm_id)
1949 {
1950         struct srpt_rdma_ch *ch;
1951         bool found;
1952
1953         WARN_ON_ONCE(irqs_disabled());
1954         BUG_ON(!sdev);
1955
1956         found = false;
1957         spin_lock_irq(&sdev->spinlock);
1958         list_for_each_entry(ch, &sdev->rch_list, list) {
1959                 if (ch->cm_id == cm_id) {
1960                         found = true;
1961                         break;
1962                 }
1963         }
1964         spin_unlock_irq(&sdev->spinlock);
1965
1966         return found ? ch : NULL;
1967 }
1968
1969 /**
1970  * srpt_release_channel() - Release channel resources.
1971  *
1972  * Schedules the actual release because:
1973  * - Calling the ib_destroy_cm_id() call from inside an IB CM callback would
1974  *   trigger a deadlock.
1975  * - It is not safe to call TCM transport_* functions from interrupt context.
1976  */
1977 static void srpt_release_channel(struct srpt_rdma_ch *ch)
1978 {
1979         schedule_work(&ch->release_work);
1980 }
1981
1982 static void srpt_release_channel_work(struct work_struct *w)
1983 {
1984         struct srpt_rdma_ch *ch;
1985         struct srpt_device *sdev;
1986         struct se_session *se_sess;
1987
1988         ch = container_of(w, struct srpt_rdma_ch, release_work);
1989         pr_debug("ch = %p; ch->sess = %p; release_done = %p\n", ch, ch->sess,
1990                  ch->release_done);
1991
1992         sdev = ch->sport->sdev;
1993         BUG_ON(!sdev);
1994
1995         se_sess = ch->sess;
1996         BUG_ON(!se_sess);
1997
1998         target_sess_cmd_list_set_waiting(se_sess);
1999         target_wait_for_sess_cmds(se_sess);
2000
2001         transport_deregister_session_configfs(se_sess);
2002         transport_deregister_session(se_sess);
2003         ch->sess = NULL;
2004
2005         ib_destroy_cm_id(ch->cm_id);
2006
2007         srpt_destroy_ch_ib(ch);
2008
2009         srpt_free_ioctx_ring((struct srpt_ioctx **)ch->ioctx_ring,
2010                              ch->sport->sdev, ch->rq_size,
2011                              ch->rsp_size, DMA_TO_DEVICE);
2012
2013         spin_lock_irq(&sdev->spinlock);
2014         list_del(&ch->list);
2015         spin_unlock_irq(&sdev->spinlock);
2016
2017         if (ch->release_done)
2018                 complete(ch->release_done);
2019
2020         wake_up(&sdev->ch_releaseQ);
2021
2022         kfree(ch);
2023 }
2024
2025 /**
2026  * srpt_cm_req_recv() - Process the event IB_CM_REQ_RECEIVED.
2027  *
2028  * Ownership of the cm_id is transferred to the target session if this
2029  * functions returns zero. Otherwise the caller remains the owner of cm_id.
2030  */
2031 static int srpt_cm_req_recv(struct ib_cm_id *cm_id,
2032                             struct ib_cm_req_event_param *param,
2033                             void *private_data)
2034 {
2035         struct srpt_device *sdev = cm_id->context;
2036         struct srpt_port *sport = &sdev->port[param->port - 1];
2037         struct srp_login_req *req;
2038         struct srp_login_rsp *rsp;
2039         struct srp_login_rej *rej;
2040         struct ib_cm_rep_param *rep_param;
2041         struct srpt_rdma_ch *ch, *tmp_ch;
2042         struct se_node_acl *se_acl;
2043         u32 it_iu_len;
2044         int i, ret = 0;
2045         unsigned char *p;
2046
2047         WARN_ON_ONCE(irqs_disabled());
2048
2049         if (WARN_ON(!sdev || !private_data))
2050                 return -EINVAL;
2051
2052         req = (struct srp_login_req *)private_data;
2053
2054         it_iu_len = be32_to_cpu(req->req_it_iu_len);
2055
2056         pr_info("Received SRP_LOGIN_REQ with i_port_id 0x%llx:0x%llx,"
2057                 " t_port_id 0x%llx:0x%llx and it_iu_len %d on port %d"
2058                 " (guid=0x%llx:0x%llx)\n",
2059                 be64_to_cpu(*(__be64 *)&req->initiator_port_id[0]),
2060                 be64_to_cpu(*(__be64 *)&req->initiator_port_id[8]),
2061                 be64_to_cpu(*(__be64 *)&req->target_port_id[0]),
2062                 be64_to_cpu(*(__be64 *)&req->target_port_id[8]),
2063                 it_iu_len,
2064                 param->port,
2065                 be64_to_cpu(*(__be64 *)&sdev->port[param->port - 1].gid.raw[0]),
2066                 be64_to_cpu(*(__be64 *)&sdev->port[param->port - 1].gid.raw[8]));
2067
2068         rsp = kzalloc(sizeof(*rsp), GFP_KERNEL);
2069         rej = kzalloc(sizeof(*rej), GFP_KERNEL);
2070         rep_param = kzalloc(sizeof(*rep_param), GFP_KERNEL);
2071
2072         if (!rsp || !rej || !rep_param) {
2073                 ret = -ENOMEM;
2074                 goto out;
2075         }
2076
2077         if (it_iu_len > srp_max_req_size || it_iu_len < 64) {
2078                 rej->reason = cpu_to_be32(
2079                               SRP_LOGIN_REJ_REQ_IT_IU_LENGTH_TOO_LARGE);
2080                 ret = -EINVAL;
2081                 pr_err("rejected SRP_LOGIN_REQ because its"
2082                        " length (%d bytes) is out of range (%d .. %d)\n",
2083                        it_iu_len, 64, srp_max_req_size);
2084                 goto reject;
2085         }
2086
2087         if (!sport->enabled) {
2088                 rej->reason = cpu_to_be32(
2089                               SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2090                 ret = -EINVAL;
2091                 pr_err("rejected SRP_LOGIN_REQ because the target port"
2092                        " has not yet been enabled\n");
2093                 goto reject;
2094         }
2095
2096         if ((req->req_flags & SRP_MTCH_ACTION) == SRP_MULTICHAN_SINGLE) {
2097                 rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_NO_CHAN;
2098
2099                 spin_lock_irq(&sdev->spinlock);
2100
2101                 list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list) {
2102                         if (!memcmp(ch->i_port_id, req->initiator_port_id, 16)
2103                             && !memcmp(ch->t_port_id, req->target_port_id, 16)
2104                             && param->port == ch->sport->port
2105                             && param->listen_id == ch->sport->sdev->cm_id
2106                             && ch->cm_id) {
2107                                 if (ch->state != CH_CONNECTING
2108                                     && ch->state != CH_LIVE)
2109                                         continue;
2110
2111                                 /* found an existing channel */
2112                                 pr_debug("Found existing channel %s"
2113                                          " cm_id= %p state= %d\n",
2114                                          ch->sess_name, ch->cm_id, ch->state);
2115
2116                                 __srpt_close_ch(ch);
2117
2118                                 rsp->rsp_flags =
2119                                         SRP_LOGIN_RSP_MULTICHAN_TERMINATED;
2120                         }
2121                 }
2122
2123                 spin_unlock_irq(&sdev->spinlock);
2124
2125         } else
2126                 rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_MAINTAINED;
2127
2128         if (*(__be64 *)req->target_port_id != cpu_to_be64(srpt_service_guid)
2129             || *(__be64 *)(req->target_port_id + 8) !=
2130                cpu_to_be64(srpt_service_guid)) {
2131                 rej->reason = cpu_to_be32(
2132                               SRP_LOGIN_REJ_UNABLE_ASSOCIATE_CHANNEL);
2133                 ret = -ENOMEM;
2134                 pr_err("rejected SRP_LOGIN_REQ because it"
2135                        " has an invalid target port identifier.\n");
2136                 goto reject;
2137         }
2138
2139         ch = kzalloc(sizeof(*ch), GFP_KERNEL);
2140         if (!ch) {
2141                 rej->reason = cpu_to_be32(
2142                               SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2143                 pr_err("rejected SRP_LOGIN_REQ because no memory.\n");
2144                 ret = -ENOMEM;
2145                 goto reject;
2146         }
2147
2148         INIT_WORK(&ch->release_work, srpt_release_channel_work);
2149         memcpy(ch->i_port_id, req->initiator_port_id, 16);
2150         memcpy(ch->t_port_id, req->target_port_id, 16);
2151         ch->sport = &sdev->port[param->port - 1];
2152         ch->cm_id = cm_id;
2153         /*
2154          * Avoid QUEUE_FULL conditions by limiting the number of buffers used
2155          * for the SRP protocol to the command queue size.
2156          */
2157         ch->rq_size = SRPT_RQ_SIZE;
2158         spin_lock_init(&ch->spinlock);
2159         ch->state = CH_CONNECTING;
2160         INIT_LIST_HEAD(&ch->cmd_wait_list);
2161         ch->rsp_size = ch->sport->port_attrib.srp_max_rsp_size;
2162
2163         ch->ioctx_ring = (struct srpt_send_ioctx **)
2164                 srpt_alloc_ioctx_ring(ch->sport->sdev, ch->rq_size,
2165                                       sizeof(*ch->ioctx_ring[0]),
2166                                       ch->rsp_size, DMA_TO_DEVICE);
2167         if (!ch->ioctx_ring)
2168                 goto free_ch;
2169
2170         INIT_LIST_HEAD(&ch->free_list);
2171         for (i = 0; i < ch->rq_size; i++) {
2172                 ch->ioctx_ring[i]->ch = ch;
2173                 list_add_tail(&ch->ioctx_ring[i]->free_list, &ch->free_list);
2174         }
2175
2176         ret = srpt_create_ch_ib(ch);
2177         if (ret) {
2178                 rej->reason = cpu_to_be32(
2179                               SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2180                 pr_err("rejected SRP_LOGIN_REQ because creating"
2181                        " a new RDMA channel failed.\n");
2182                 goto free_ring;
2183         }
2184
2185         ret = srpt_ch_qp_rtr(ch, ch->qp);
2186         if (ret) {
2187                 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2188                 pr_err("rejected SRP_LOGIN_REQ because enabling"
2189                        " RTR failed (error code = %d)\n", ret);
2190                 goto destroy_ib;
2191         }
2192
2193         /*
2194          * Use the initator port identifier as the session name, when
2195          * checking against se_node_acl->initiatorname[] this can be
2196          * with or without preceeding '0x'.
2197          */
2198         snprintf(ch->sess_name, sizeof(ch->sess_name), "0x%016llx%016llx",
2199                         be64_to_cpu(*(__be64 *)ch->i_port_id),
2200                         be64_to_cpu(*(__be64 *)(ch->i_port_id + 8)));
2201
2202         pr_debug("registering session %s\n", ch->sess_name);
2203         p = &ch->sess_name[0];
2204
2205         ch->sess = transport_init_session(TARGET_PROT_NORMAL);
2206         if (IS_ERR(ch->sess)) {
2207                 rej->reason = cpu_to_be32(
2208                                 SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2209                 pr_debug("Failed to create session\n");
2210                 goto destroy_ib;
2211         }
2212
2213 try_again:
2214         se_acl = core_tpg_get_initiator_node_acl(&sport->port_tpg_1, p);
2215         if (!se_acl) {
2216                 pr_info("Rejected login because no ACL has been"
2217                         " configured yet for initiator %s.\n", ch->sess_name);
2218                 /*
2219                  * XXX: Hack to retry of ch->i_port_id without leading '0x'
2220                  */
2221                 if (p == &ch->sess_name[0]) {
2222                         p += 2;
2223                         goto try_again;
2224                 }
2225                 rej->reason = cpu_to_be32(
2226                                 SRP_LOGIN_REJ_CHANNEL_LIMIT_REACHED);
2227                 transport_free_session(ch->sess);
2228                 goto destroy_ib;
2229         }
2230         ch->sess->se_node_acl = se_acl;
2231
2232         transport_register_session(&sport->port_tpg_1, se_acl, ch->sess, ch);
2233
2234         pr_debug("Establish connection sess=%p name=%s cm_id=%p\n", ch->sess,
2235                  ch->sess_name, ch->cm_id);
2236
2237         /* create srp_login_response */
2238         rsp->opcode = SRP_LOGIN_RSP;
2239         rsp->tag = req->tag;
2240         rsp->max_it_iu_len = req->req_it_iu_len;
2241         rsp->max_ti_iu_len = req->req_it_iu_len;
2242         ch->max_ti_iu_len = it_iu_len;
2243         rsp->buf_fmt = cpu_to_be16(SRP_BUF_FORMAT_DIRECT
2244                                    | SRP_BUF_FORMAT_INDIRECT);
2245         rsp->req_lim_delta = cpu_to_be32(ch->rq_size);
2246         atomic_set(&ch->req_lim, ch->rq_size);
2247         atomic_set(&ch->req_lim_delta, 0);
2248
2249         /* create cm reply */
2250         rep_param->qp_num = ch->qp->qp_num;
2251         rep_param->private_data = (void *)rsp;
2252         rep_param->private_data_len = sizeof(*rsp);
2253         rep_param->rnr_retry_count = 7;
2254         rep_param->flow_control = 1;
2255         rep_param->failover_accepted = 0;
2256         rep_param->srq = 1;
2257         rep_param->responder_resources = 4;
2258         rep_param->initiator_depth = 4;
2259
2260         ret = ib_send_cm_rep(cm_id, rep_param);
2261         if (ret) {
2262                 pr_err("sending SRP_LOGIN_REQ response failed"
2263                        " (error code = %d)\n", ret);
2264                 goto release_channel;
2265         }
2266
2267         spin_lock_irq(&sdev->spinlock);
2268         list_add_tail(&ch->list, &sdev->rch_list);
2269         spin_unlock_irq(&sdev->spinlock);
2270
2271         goto out;
2272
2273 release_channel:
2274         srpt_set_ch_state(ch, CH_RELEASING);
2275         transport_deregister_session_configfs(ch->sess);
2276         transport_deregister_session(ch->sess);
2277         ch->sess = NULL;
2278
2279 destroy_ib:
2280         srpt_destroy_ch_ib(ch);
2281
2282 free_ring:
2283         srpt_free_ioctx_ring((struct srpt_ioctx **)ch->ioctx_ring,
2284                              ch->sport->sdev, ch->rq_size,
2285                              ch->rsp_size, DMA_TO_DEVICE);
2286 free_ch:
2287         kfree(ch);
2288
2289 reject:
2290         rej->opcode = SRP_LOGIN_REJ;
2291         rej->tag = req->tag;
2292         rej->buf_fmt = cpu_to_be16(SRP_BUF_FORMAT_DIRECT
2293                                    | SRP_BUF_FORMAT_INDIRECT);
2294
2295         ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0,
2296                              (void *)rej, sizeof(*rej));
2297
2298 out:
2299         kfree(rep_param);
2300         kfree(rsp);
2301         kfree(rej);
2302
2303         return ret;
2304 }
2305
2306 static void srpt_cm_rej_recv(struct ib_cm_id *cm_id)
2307 {
2308         pr_info("Received IB REJ for cm_id %p.\n", cm_id);
2309         srpt_drain_channel(cm_id);
2310 }
2311
2312 /**
2313  * srpt_cm_rtu_recv() - Process an IB_CM_RTU_RECEIVED or USER_ESTABLISHED event.
2314  *
2315  * An IB_CM_RTU_RECEIVED message indicates that the connection is established
2316  * and that the recipient may begin transmitting (RTU = ready to use).
2317  */
2318 static void srpt_cm_rtu_recv(struct ib_cm_id *cm_id)
2319 {
2320         struct srpt_rdma_ch *ch;
2321         int ret;
2322
2323         ch = srpt_find_channel(cm_id->context, cm_id);
2324         BUG_ON(!ch);
2325
2326         if (srpt_set_ch_state(ch, CH_LIVE)) {
2327                 struct srpt_recv_ioctx *ioctx, *ioctx_tmp;
2328
2329                 ret = srpt_ch_qp_rts(ch, ch->qp);
2330
2331                 list_for_each_entry_safe(ioctx, ioctx_tmp, &ch->cmd_wait_list,
2332                                          wait_list) {
2333                         list_del(&ioctx->wait_list);
2334                         srpt_handle_new_iu(ch, ioctx, NULL);
2335                 }
2336                 if (ret)
2337                         srpt_close_ch(ch);
2338         }
2339 }
2340
2341 static void srpt_cm_timewait_exit(struct ib_cm_id *cm_id)
2342 {
2343         pr_info("Received IB TimeWait exit for cm_id %p.\n", cm_id);
2344         srpt_drain_channel(cm_id);
2345 }
2346
2347 static void srpt_cm_rep_error(struct ib_cm_id *cm_id)
2348 {
2349         pr_info("Received IB REP error for cm_id %p.\n", cm_id);
2350         srpt_drain_channel(cm_id);
2351 }
2352
2353 /**
2354  * srpt_cm_dreq_recv() - Process reception of a DREQ message.
2355  */
2356 static void srpt_cm_dreq_recv(struct ib_cm_id *cm_id)
2357 {
2358         struct srpt_rdma_ch *ch;
2359         unsigned long flags;
2360         bool send_drep = false;
2361
2362         ch = srpt_find_channel(cm_id->context, cm_id);
2363         BUG_ON(!ch);
2364
2365         pr_debug("cm_id= %p ch->state= %d\n", cm_id, ch->state);
2366
2367         spin_lock_irqsave(&ch->spinlock, flags);
2368         switch (ch->state) {
2369         case CH_CONNECTING:
2370         case CH_LIVE:
2371                 send_drep = true;
2372                 ch->state = CH_DISCONNECTING;
2373                 break;
2374         case CH_DISCONNECTING:
2375         case CH_DRAINING:
2376         case CH_RELEASING:
2377                 WARN(true, "unexpected channel state %d\n", ch->state);
2378                 break;
2379         }
2380         spin_unlock_irqrestore(&ch->spinlock, flags);
2381
2382         if (send_drep) {
2383                 if (ib_send_cm_drep(ch->cm_id, NULL, 0) < 0)
2384                         pr_err("Sending IB DREP failed.\n");
2385                 pr_info("Received DREQ and sent DREP for session %s.\n",
2386                         ch->sess_name);
2387         }
2388 }
2389
2390 /**
2391  * srpt_cm_drep_recv() - Process reception of a DREP message.
2392  */
2393 static void srpt_cm_drep_recv(struct ib_cm_id *cm_id)
2394 {
2395         pr_info("Received InfiniBand DREP message for cm_id %p.\n", cm_id);
2396         srpt_drain_channel(cm_id);
2397 }
2398
2399 /**
2400  * srpt_cm_handler() - IB connection manager callback function.
2401  *
2402  * A non-zero return value will cause the caller destroy the CM ID.
2403  *
2404  * Note: srpt_cm_handler() must only return a non-zero value when transferring
2405  * ownership of the cm_id to a channel by srpt_cm_req_recv() failed. Returning
2406  * a non-zero value in any other case will trigger a race with the
2407  * ib_destroy_cm_id() call in srpt_release_channel().
2408  */
2409 static int srpt_cm_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event)
2410 {
2411         int ret;
2412
2413         ret = 0;
2414         switch (event->event) {
2415         case IB_CM_REQ_RECEIVED:
2416                 ret = srpt_cm_req_recv(cm_id, &event->param.req_rcvd,
2417                                        event->private_data);
2418                 break;
2419         case IB_CM_REJ_RECEIVED:
2420                 srpt_cm_rej_recv(cm_id);
2421                 break;
2422         case IB_CM_RTU_RECEIVED:
2423         case IB_CM_USER_ESTABLISHED:
2424                 srpt_cm_rtu_recv(cm_id);
2425                 break;
2426         case IB_CM_DREQ_RECEIVED:
2427                 srpt_cm_dreq_recv(cm_id);
2428                 break;
2429         case IB_CM_DREP_RECEIVED:
2430                 srpt_cm_drep_recv(cm_id);
2431                 break;
2432         case IB_CM_TIMEWAIT_EXIT:
2433                 srpt_cm_timewait_exit(cm_id);
2434                 break;
2435         case IB_CM_REP_ERROR:
2436                 srpt_cm_rep_error(cm_id);
2437                 break;
2438         case IB_CM_DREQ_ERROR:
2439                 pr_info("Received IB DREQ ERROR event.\n");
2440                 break;
2441         case IB_CM_MRA_RECEIVED:
2442                 pr_info("Received IB MRA event\n");
2443                 break;
2444         default:
2445                 pr_err("received unrecognized IB CM event %d\n", event->event);
2446                 break;
2447         }
2448
2449         return ret;
2450 }
2451
2452 /**
2453  * srpt_perform_rdmas() - Perform IB RDMA.
2454  *
2455  * Returns zero upon success or a negative number upon failure.
2456  */
2457 static int srpt_perform_rdmas(struct srpt_rdma_ch *ch,
2458                               struct srpt_send_ioctx *ioctx)
2459 {
2460         struct ib_send_wr *bad_wr;
2461         int sq_wr_avail, ret, i;
2462         enum dma_data_direction dir;
2463         const int n_rdma = ioctx->n_rdma;
2464
2465         dir = ioctx->cmd.data_direction;
2466         if (dir == DMA_TO_DEVICE) {
2467                 /* write */
2468                 ret = -ENOMEM;
2469                 sq_wr_avail = atomic_sub_return(n_rdma, &ch->sq_wr_avail);
2470                 if (sq_wr_avail < 0) {
2471                         pr_warn("IB send queue full (needed %d)\n",
2472                                 n_rdma);
2473                         goto out;
2474                 }
2475         }
2476
2477         for (i = 0; i < n_rdma; i++) {
2478                 struct ib_send_wr *wr = &ioctx->rdma_wrs[i].wr;
2479
2480                 wr->opcode = (dir == DMA_FROM_DEVICE) ?
2481                                 IB_WR_RDMA_WRITE : IB_WR_RDMA_READ;
2482
2483                 if (i == n_rdma - 1) {
2484                         /* only get completion event for the last rdma read */
2485                         if (dir == DMA_TO_DEVICE) {
2486                                 wr->send_flags = IB_SEND_SIGNALED;
2487                                 ioctx->rdma_cqe.done = srpt_rdma_read_done;
2488                         } else {
2489                                 ioctx->rdma_cqe.done = srpt_rdma_write_done;
2490                         }
2491                         wr->wr_cqe = &ioctx->rdma_cqe;
2492                         wr->next = NULL;
2493                 } else {
2494                         wr->wr_cqe = NULL;
2495                         wr->next = &ioctx->rdma_wrs[i + 1].wr;
2496                 }
2497         }
2498
2499         ret = ib_post_send(ch->qp, &ioctx->rdma_wrs->wr, &bad_wr);
2500         if (ret)
2501                 pr_err("%s[%d]: ib_post_send() returned %d for %d/%d\n",
2502                                  __func__, __LINE__, ret, i, n_rdma);
2503 out:
2504         if (unlikely(dir == DMA_TO_DEVICE && ret < 0))
2505                 atomic_add(n_rdma, &ch->sq_wr_avail);
2506         return ret;
2507 }
2508
2509 /**
2510  * srpt_xfer_data() - Start data transfer from initiator to target.
2511  */
2512 static int srpt_xfer_data(struct srpt_rdma_ch *ch,
2513                           struct srpt_send_ioctx *ioctx)
2514 {
2515         int ret;
2516
2517         ret = srpt_map_sg_to_ib_sge(ch, ioctx);
2518         if (ret) {
2519                 pr_err("%s[%d] ret=%d\n", __func__, __LINE__, ret);
2520                 goto out;
2521         }
2522
2523         ret = srpt_perform_rdmas(ch, ioctx);
2524         if (ret) {
2525                 if (ret == -EAGAIN || ret == -ENOMEM)
2526                         pr_info("%s[%d] queue full -- ret=%d\n",
2527                                 __func__, __LINE__, ret);
2528                 else
2529                         pr_err("%s[%d] fatal error -- ret=%d\n",
2530                                __func__, __LINE__, ret);
2531                 goto out_unmap;
2532         }
2533
2534 out:
2535         return ret;
2536 out_unmap:
2537         srpt_unmap_sg_to_ib_sge(ch, ioctx);
2538         goto out;
2539 }
2540
2541 static int srpt_write_pending_status(struct se_cmd *se_cmd)
2542 {
2543         struct srpt_send_ioctx *ioctx;
2544
2545         ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
2546         return srpt_get_cmd_state(ioctx) == SRPT_STATE_NEED_DATA;
2547 }
2548
2549 /*
2550  * srpt_write_pending() - Start data transfer from initiator to target (write).
2551  */
2552 static int srpt_write_pending(struct se_cmd *se_cmd)
2553 {
2554         struct srpt_rdma_ch *ch;
2555         struct srpt_send_ioctx *ioctx;
2556         enum srpt_command_state new_state;
2557         int ret;
2558
2559         ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
2560
2561         new_state = srpt_set_cmd_state(ioctx, SRPT_STATE_NEED_DATA);
2562         WARN_ON(new_state == SRPT_STATE_DONE);
2563
2564         ch = ioctx->ch;
2565         BUG_ON(!ch);
2566
2567         switch (ch->state) {
2568         case CH_CONNECTING:
2569                 WARN(true, "unexpected channel state %d\n", ch->state);
2570                 ret = -EINVAL;
2571                 goto out;
2572         case CH_LIVE:
2573                 break;
2574         case CH_DISCONNECTING:
2575         case CH_DRAINING:
2576         case CH_RELEASING:
2577                 pr_debug("cmd with tag %lld: channel disconnecting\n",
2578                          ioctx->cmd.tag);
2579                 srpt_set_cmd_state(ioctx, SRPT_STATE_DATA_IN);
2580                 ret = -EINVAL;
2581                 goto out;
2582         }
2583         ret = srpt_xfer_data(ch, ioctx);
2584
2585 out:
2586         return ret;
2587 }
2588
2589 static u8 tcm_to_srp_tsk_mgmt_status(const int tcm_mgmt_status)
2590 {
2591         switch (tcm_mgmt_status) {
2592         case TMR_FUNCTION_COMPLETE:
2593                 return SRP_TSK_MGMT_SUCCESS;
2594         case TMR_FUNCTION_REJECTED:
2595                 return SRP_TSK_MGMT_FUNC_NOT_SUPP;
2596         }
2597         return SRP_TSK_MGMT_FAILED;
2598 }
2599
2600 /**
2601  * srpt_queue_response() - Transmits the response to a SCSI command.
2602  *
2603  * Callback function called by the TCM core. Must not block since it can be
2604  * invoked on the context of the IB completion handler.
2605  */
2606 static void srpt_queue_response(struct se_cmd *cmd)
2607 {
2608         struct srpt_rdma_ch *ch;
2609         struct srpt_send_ioctx *ioctx;
2610         enum srpt_command_state state;
2611         unsigned long flags;
2612         int ret;
2613         enum dma_data_direction dir;
2614         int resp_len;
2615         u8 srp_tm_status;
2616
2617         ioctx = container_of(cmd, struct srpt_send_ioctx, cmd);
2618         ch = ioctx->ch;
2619         BUG_ON(!ch);
2620
2621         spin_lock_irqsave(&ioctx->spinlock, flags);
2622         state = ioctx->state;
2623         switch (state) {
2624         case SRPT_STATE_NEW:
2625         case SRPT_STATE_DATA_IN:
2626                 ioctx->state = SRPT_STATE_CMD_RSP_SENT;
2627                 break;
2628         case SRPT_STATE_MGMT:
2629                 ioctx->state = SRPT_STATE_MGMT_RSP_SENT;
2630                 break;
2631         default:
2632                 WARN(true, "ch %p; cmd %d: unexpected command state %d\n",
2633                         ch, ioctx->ioctx.index, ioctx->state);
2634                 break;
2635         }
2636         spin_unlock_irqrestore(&ioctx->spinlock, flags);
2637
2638         if (unlikely(transport_check_aborted_status(&ioctx->cmd, false)
2639                      || WARN_ON_ONCE(state == SRPT_STATE_CMD_RSP_SENT))) {
2640                 atomic_inc(&ch->req_lim_delta);
2641                 srpt_abort_cmd(ioctx);
2642                 return;
2643         }
2644
2645         dir = ioctx->cmd.data_direction;
2646
2647         /* For read commands, transfer the data to the initiator. */
2648         if (dir == DMA_FROM_DEVICE && ioctx->cmd.data_length &&
2649             !ioctx->queue_status_only) {
2650                 ret = srpt_xfer_data(ch, ioctx);
2651                 if (ret) {
2652                         pr_err("xfer_data failed for tag %llu\n",
2653                                ioctx->cmd.tag);
2654                         return;
2655                 }
2656         }
2657
2658         if (state != SRPT_STATE_MGMT)
2659                 resp_len = srpt_build_cmd_rsp(ch, ioctx, ioctx->cmd.tag,
2660                                               cmd->scsi_status);
2661         else {
2662                 srp_tm_status
2663                         = tcm_to_srp_tsk_mgmt_status(cmd->se_tmr_req->response);
2664                 resp_len = srpt_build_tskmgmt_rsp(ch, ioctx, srp_tm_status,
2665                                                  ioctx->cmd.tag);
2666         }
2667         ret = srpt_post_send(ch, ioctx, resp_len);
2668         if (ret) {
2669                 pr_err("sending cmd response failed for tag %llu\n",
2670                        ioctx->cmd.tag);
2671                 srpt_unmap_sg_to_ib_sge(ch, ioctx);
2672                 srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
2673                 target_put_sess_cmd(&ioctx->cmd);
2674         }
2675 }
2676
2677 static int srpt_queue_data_in(struct se_cmd *cmd)
2678 {
2679         srpt_queue_response(cmd);
2680         return 0;
2681 }
2682
2683 static void srpt_queue_tm_rsp(struct se_cmd *cmd)
2684 {
2685         srpt_queue_response(cmd);
2686 }
2687
2688 static void srpt_aborted_task(struct se_cmd *cmd)
2689 {
2690         struct srpt_send_ioctx *ioctx = container_of(cmd,
2691                                 struct srpt_send_ioctx, cmd);
2692
2693         srpt_unmap_sg_to_ib_sge(ioctx->ch, ioctx);
2694 }
2695
2696 static int srpt_queue_status(struct se_cmd *cmd)
2697 {
2698         struct srpt_send_ioctx *ioctx;
2699
2700         ioctx = container_of(cmd, struct srpt_send_ioctx, cmd);
2701         BUG_ON(ioctx->sense_data != cmd->sense_buffer);
2702         if (cmd->se_cmd_flags &
2703             (SCF_TRANSPORT_TASK_SENSE | SCF_EMULATED_TASK_SENSE))
2704                 WARN_ON(cmd->scsi_status != SAM_STAT_CHECK_CONDITION);
2705         ioctx->queue_status_only = true;
2706         srpt_queue_response(cmd);
2707         return 0;
2708 }
2709
2710 static void srpt_refresh_port_work(struct work_struct *work)
2711 {
2712         struct srpt_port *sport = container_of(work, struct srpt_port, work);
2713
2714         srpt_refresh_port(sport);
2715 }
2716
2717 static int srpt_ch_list_empty(struct srpt_device *sdev)
2718 {
2719         int res;
2720
2721         spin_lock_irq(&sdev->spinlock);
2722         res = list_empty(&sdev->rch_list);
2723         spin_unlock_irq(&sdev->spinlock);
2724
2725         return res;
2726 }
2727
2728 /**
2729  * srpt_release_sdev() - Free the channel resources associated with a target.
2730  */
2731 static int srpt_release_sdev(struct srpt_device *sdev)
2732 {
2733         struct srpt_rdma_ch *ch, *tmp_ch;
2734         int res;
2735
2736         WARN_ON_ONCE(irqs_disabled());
2737
2738         BUG_ON(!sdev);
2739
2740         spin_lock_irq(&sdev->spinlock);
2741         list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list)
2742                 __srpt_close_ch(ch);
2743         spin_unlock_irq(&sdev->spinlock);
2744
2745         res = wait_event_interruptible(sdev->ch_releaseQ,
2746                                        srpt_ch_list_empty(sdev));
2747         if (res)
2748                 pr_err("%s: interrupted.\n", __func__);
2749
2750         return 0;
2751 }
2752
2753 static struct srpt_port *__srpt_lookup_port(const char *name)
2754 {
2755         struct ib_device *dev;
2756         struct srpt_device *sdev;
2757         struct srpt_port *sport;
2758         int i;
2759
2760         list_for_each_entry(sdev, &srpt_dev_list, list) {
2761                 dev = sdev->device;
2762                 if (!dev)
2763                         continue;
2764
2765                 for (i = 0; i < dev->phys_port_cnt; i++) {
2766                         sport = &sdev->port[i];
2767
2768                         if (!strcmp(sport->port_guid, name))
2769                                 return sport;
2770                 }
2771         }
2772
2773         return NULL;
2774 }
2775
2776 static struct srpt_port *srpt_lookup_port(const char *name)
2777 {
2778         struct srpt_port *sport;
2779
2780         spin_lock(&srpt_dev_lock);
2781         sport = __srpt_lookup_port(name);
2782         spin_unlock(&srpt_dev_lock);
2783
2784         return sport;
2785 }
2786
2787 /**
2788  * srpt_add_one() - Infiniband device addition callback function.
2789  */
2790 static void srpt_add_one(struct ib_device *device)
2791 {
2792         struct srpt_device *sdev;
2793         struct srpt_port *sport;
2794         struct ib_srq_init_attr srq_attr;
2795         int i;
2796
2797         pr_debug("device = %p, device->dma_ops = %p\n", device,
2798                  device->dma_ops);
2799
2800         sdev = kzalloc(sizeof(*sdev), GFP_KERNEL);
2801         if (!sdev)
2802                 goto err;
2803
2804         sdev->device = device;
2805         INIT_LIST_HEAD(&sdev->rch_list);
2806         init_waitqueue_head(&sdev->ch_releaseQ);
2807         spin_lock_init(&sdev->spinlock);
2808
2809         sdev->pd = ib_alloc_pd(device);
2810         if (IS_ERR(sdev->pd))
2811                 goto free_dev;
2812
2813         sdev->srq_size = min(srpt_srq_size, sdev->device->attrs.max_srq_wr);
2814
2815         srq_attr.event_handler = srpt_srq_event;
2816         srq_attr.srq_context = (void *)sdev;
2817         srq_attr.attr.max_wr = sdev->srq_size;
2818         srq_attr.attr.max_sge = 1;
2819         srq_attr.attr.srq_limit = 0;
2820         srq_attr.srq_type = IB_SRQT_BASIC;
2821
2822         sdev->srq = ib_create_srq(sdev->pd, &srq_attr);
2823         if (IS_ERR(sdev->srq))
2824                 goto err_pd;
2825
2826         pr_debug("%s: create SRQ #wr= %d max_allow=%d dev= %s\n",
2827                  __func__, sdev->srq_size, sdev->device->attrs.max_srq_wr,
2828                  device->name);
2829
2830         if (!srpt_service_guid)
2831                 srpt_service_guid = be64_to_cpu(device->node_guid);
2832
2833         sdev->cm_id = ib_create_cm_id(device, srpt_cm_handler, sdev);
2834         if (IS_ERR(sdev->cm_id))
2835                 goto err_srq;
2836
2837         /* print out target login information */
2838         pr_debug("Target login info: id_ext=%016llx,ioc_guid=%016llx,"
2839                  "pkey=ffff,service_id=%016llx\n", srpt_service_guid,
2840                  srpt_service_guid, srpt_service_guid);
2841
2842         /*
2843          * We do not have a consistent service_id (ie. also id_ext of target_id)
2844          * to identify this target. We currently use the guid of the first HCA
2845          * in the system as service_id; therefore, the target_id will change
2846          * if this HCA is gone bad and replaced by different HCA
2847          */
2848         if (ib_cm_listen(sdev->cm_id, cpu_to_be64(srpt_service_guid), 0))
2849                 goto err_cm;
2850
2851         INIT_IB_EVENT_HANDLER(&sdev->event_handler, sdev->device,
2852                               srpt_event_handler);
2853         if (ib_register_event_handler(&sdev->event_handler))
2854                 goto err_cm;
2855
2856         sdev->ioctx_ring = (struct srpt_recv_ioctx **)
2857                 srpt_alloc_ioctx_ring(sdev, sdev->srq_size,
2858                                       sizeof(*sdev->ioctx_ring[0]),
2859                                       srp_max_req_size, DMA_FROM_DEVICE);
2860         if (!sdev->ioctx_ring)
2861                 goto err_event;
2862
2863         for (i = 0; i < sdev->srq_size; ++i)
2864                 srpt_post_recv(sdev, sdev->ioctx_ring[i]);
2865
2866         WARN_ON(sdev->device->phys_port_cnt > ARRAY_SIZE(sdev->port));
2867
2868         for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
2869                 sport = &sdev->port[i - 1];
2870                 sport->sdev = sdev;
2871                 sport->port = i;
2872                 sport->port_attrib.srp_max_rdma_size = DEFAULT_MAX_RDMA_SIZE;
2873                 sport->port_attrib.srp_max_rsp_size = DEFAULT_MAX_RSP_SIZE;
2874                 sport->port_attrib.srp_sq_size = DEF_SRPT_SQ_SIZE;
2875                 INIT_WORK(&sport->work, srpt_refresh_port_work);
2876
2877                 if (srpt_refresh_port(sport)) {
2878                         pr_err("MAD registration failed for %s-%d.\n",
2879                                sdev->device->name, i);
2880                         goto err_ring;
2881                 }
2882                 snprintf(sport->port_guid, sizeof(sport->port_guid),
2883                         "0x%016llx%016llx",
2884                         be64_to_cpu(sport->gid.global.subnet_prefix),
2885                         be64_to_cpu(sport->gid.global.interface_id));
2886         }
2887
2888         spin_lock(&srpt_dev_lock);
2889         list_add_tail(&sdev->list, &srpt_dev_list);
2890         spin_unlock(&srpt_dev_lock);
2891
2892 out:
2893         ib_set_client_data(device, &srpt_client, sdev);
2894         pr_debug("added %s.\n", device->name);
2895         return;
2896
2897 err_ring:
2898         srpt_free_ioctx_ring((struct srpt_ioctx **)sdev->ioctx_ring, sdev,
2899                              sdev->srq_size, srp_max_req_size,
2900                              DMA_FROM_DEVICE);
2901 err_event:
2902         ib_unregister_event_handler(&sdev->event_handler);
2903 err_cm:
2904         ib_destroy_cm_id(sdev->cm_id);
2905 err_srq:
2906         ib_destroy_srq(sdev->srq);
2907 err_pd:
2908         ib_dealloc_pd(sdev->pd);
2909 free_dev:
2910         kfree(sdev);
2911 err:
2912         sdev = NULL;
2913         pr_info("%s(%s) failed.\n", __func__, device->name);
2914         goto out;
2915 }
2916
2917 /**
2918  * srpt_remove_one() - InfiniBand device removal callback function.
2919  */
2920 static void srpt_remove_one(struct ib_device *device, void *client_data)
2921 {
2922         struct srpt_device *sdev = client_data;
2923         int i;
2924
2925         if (!sdev) {
2926                 pr_info("%s(%s): nothing to do.\n", __func__, device->name);
2927                 return;
2928         }
2929
2930         srpt_unregister_mad_agent(sdev);
2931
2932         ib_unregister_event_handler(&sdev->event_handler);
2933
2934         /* Cancel any work queued by the just unregistered IB event handler. */
2935         for (i = 0; i < sdev->device->phys_port_cnt; i++)
2936                 cancel_work_sync(&sdev->port[i].work);
2937
2938         ib_destroy_cm_id(sdev->cm_id);
2939
2940         /*
2941          * Unregistering a target must happen after destroying sdev->cm_id
2942          * such that no new SRP_LOGIN_REQ information units can arrive while
2943          * destroying the target.
2944          */
2945         spin_lock(&srpt_dev_lock);
2946         list_del(&sdev->list);
2947         spin_unlock(&srpt_dev_lock);
2948         srpt_release_sdev(sdev);
2949
2950         ib_destroy_srq(sdev->srq);
2951         ib_dealloc_pd(sdev->pd);
2952
2953         srpt_free_ioctx_ring((struct srpt_ioctx **)sdev->ioctx_ring, sdev,
2954                              sdev->srq_size, srp_max_req_size, DMA_FROM_DEVICE);
2955         sdev->ioctx_ring = NULL;
2956         kfree(sdev);
2957 }
2958
2959 static struct ib_client srpt_client = {
2960         .name = DRV_NAME,
2961         .add = srpt_add_one,
2962         .remove = srpt_remove_one
2963 };
2964
2965 static int srpt_check_true(struct se_portal_group *se_tpg)
2966 {
2967         return 1;
2968 }
2969
2970 static int srpt_check_false(struct se_portal_group *se_tpg)
2971 {
2972         return 0;
2973 }
2974
2975 static char *srpt_get_fabric_name(void)
2976 {
2977         return "srpt";
2978 }
2979
2980 static char *srpt_get_fabric_wwn(struct se_portal_group *tpg)
2981 {
2982         struct srpt_port *sport = container_of(tpg, struct srpt_port, port_tpg_1);
2983
2984         return sport->port_guid;
2985 }
2986
2987 static u16 srpt_get_tag(struct se_portal_group *tpg)
2988 {
2989         return 1;
2990 }
2991
2992 static u32 srpt_tpg_get_inst_index(struct se_portal_group *se_tpg)
2993 {
2994         return 1;
2995 }
2996
2997 static void srpt_release_cmd(struct se_cmd *se_cmd)
2998 {
2999         struct srpt_send_ioctx *ioctx = container_of(se_cmd,
3000                                 struct srpt_send_ioctx, cmd);
3001         struct srpt_rdma_ch *ch = ioctx->ch;
3002         unsigned long flags;
3003
3004         WARN_ON(ioctx->state != SRPT_STATE_DONE);
3005         WARN_ON(ioctx->mapped_sg_count != 0);
3006
3007         if (ioctx->n_rbuf > 1) {
3008                 kfree(ioctx->rbufs);
3009                 ioctx->rbufs = NULL;
3010                 ioctx->n_rbuf = 0;
3011         }
3012
3013         spin_lock_irqsave(&ch->spinlock, flags);
3014         list_add(&ioctx->free_list, &ch->free_list);
3015         spin_unlock_irqrestore(&ch->spinlock, flags);
3016 }
3017
3018 /**
3019  * srpt_close_session() - Forcibly close a session.
3020  *
3021  * Callback function invoked by the TCM core to clean up sessions associated
3022  * with a node ACL when the user invokes
3023  * rmdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id
3024  */
3025 static void srpt_close_session(struct se_session *se_sess)
3026 {
3027         DECLARE_COMPLETION_ONSTACK(release_done);
3028         struct srpt_rdma_ch *ch;
3029         struct srpt_device *sdev;
3030         unsigned long res;
3031
3032         ch = se_sess->fabric_sess_ptr;
3033         WARN_ON(ch->sess != se_sess);
3034
3035         pr_debug("ch %p state %d\n", ch, ch->state);
3036
3037         sdev = ch->sport->sdev;
3038         spin_lock_irq(&sdev->spinlock);
3039         BUG_ON(ch->release_done);
3040         ch->release_done = &release_done;
3041         __srpt_close_ch(ch);
3042         spin_unlock_irq(&sdev->spinlock);
3043
3044         res = wait_for_completion_timeout(&release_done, 60 * HZ);
3045         WARN_ON(res == 0);
3046 }
3047
3048 /**
3049  * srpt_sess_get_index() - Return the value of scsiAttIntrPortIndex (SCSI-MIB).
3050  *
3051  * A quote from RFC 4455 (SCSI-MIB) about this MIB object:
3052  * This object represents an arbitrary integer used to uniquely identify a
3053  * particular attached remote initiator port to a particular SCSI target port
3054  * within a particular SCSI target device within a particular SCSI instance.
3055  */
3056 static u32 srpt_sess_get_index(struct se_session *se_sess)
3057 {
3058         return 0;
3059 }
3060
3061 static void srpt_set_default_node_attrs(struct se_node_acl *nacl)
3062 {
3063 }
3064
3065 /* Note: only used from inside debug printk's by the TCM core. */
3066 static int srpt_get_tcm_cmd_state(struct se_cmd *se_cmd)
3067 {
3068         struct srpt_send_ioctx *ioctx;
3069
3070         ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
3071         return srpt_get_cmd_state(ioctx);
3072 }
3073
3074 /**
3075  * srpt_parse_i_port_id() - Parse an initiator port ID.
3076  * @name: ASCII representation of a 128-bit initiator port ID.
3077  * @i_port_id: Binary 128-bit port ID.
3078  */
3079 static int srpt_parse_i_port_id(u8 i_port_id[16], const char *name)
3080 {
3081         const char *p;
3082         unsigned len, count, leading_zero_bytes;
3083         int ret, rc;
3084
3085         p = name;
3086         if (strncasecmp(p, "0x", 2) == 0)
3087                 p += 2;
3088         ret = -EINVAL;
3089         len = strlen(p);
3090         if (len % 2)
3091                 goto out;
3092         count = min(len / 2, 16U);
3093         leading_zero_bytes = 16 - count;
3094         memset(i_port_id, 0, leading_zero_bytes);
3095         rc = hex2bin(i_port_id + leading_zero_bytes, p, count);
3096         if (rc < 0)
3097                 pr_debug("hex2bin failed for srpt_parse_i_port_id: %d\n", rc);
3098         ret = 0;
3099 out:
3100         return ret;
3101 }
3102
3103 /*
3104  * configfs callback function invoked for
3105  * mkdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id
3106  */
3107 static int srpt_init_nodeacl(struct se_node_acl *se_nacl, const char *name)
3108 {
3109         u8 i_port_id[16];
3110
3111         if (srpt_parse_i_port_id(i_port_id, name) < 0) {
3112                 pr_err("invalid initiator port ID %s\n", name);
3113                 return -EINVAL;
3114         }
3115         return 0;
3116 }
3117
3118 static ssize_t srpt_tpg_attrib_srp_max_rdma_size_show(struct config_item *item,
3119                 char *page)
3120 {
3121         struct se_portal_group *se_tpg = attrib_to_tpg(item);
3122         struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3123
3124         return sprintf(page, "%u\n", sport->port_attrib.srp_max_rdma_size);
3125 }
3126
3127 static ssize_t srpt_tpg_attrib_srp_max_rdma_size_store(struct config_item *item,
3128                 const char *page, size_t count)
3129 {
3130         struct se_portal_group *se_tpg = attrib_to_tpg(item);
3131         struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3132         unsigned long val;
3133         int ret;
3134
3135         ret = kstrtoul(page, 0, &val);
3136         if (ret < 0) {
3137                 pr_err("kstrtoul() failed with ret: %d\n", ret);
3138                 return -EINVAL;
3139         }
3140         if (val > MAX_SRPT_RDMA_SIZE) {
3141                 pr_err("val: %lu exceeds MAX_SRPT_RDMA_SIZE: %d\n", val,
3142                         MAX_SRPT_RDMA_SIZE);
3143                 return -EINVAL;
3144         }
3145         if (val < DEFAULT_MAX_RDMA_SIZE) {
3146                 pr_err("val: %lu smaller than DEFAULT_MAX_RDMA_SIZE: %d\n",
3147                         val, DEFAULT_MAX_RDMA_SIZE);
3148                 return -EINVAL;
3149         }
3150         sport->port_attrib.srp_max_rdma_size = val;
3151
3152         return count;
3153 }
3154
3155 static ssize_t srpt_tpg_attrib_srp_max_rsp_size_show(struct config_item *item,
3156                 char *page)
3157 {
3158         struct se_portal_group *se_tpg = attrib_to_tpg(item);
3159         struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3160
3161         return sprintf(page, "%u\n", sport->port_attrib.srp_max_rsp_size);
3162 }
3163
3164 static ssize_t srpt_tpg_attrib_srp_max_rsp_size_store(struct config_item *item,
3165                 const char *page, size_t count)
3166 {
3167         struct se_portal_group *se_tpg = attrib_to_tpg(item);
3168         struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3169         unsigned long val;
3170         int ret;
3171
3172         ret = kstrtoul(page, 0, &val);
3173         if (ret < 0) {
3174                 pr_err("kstrtoul() failed with ret: %d\n", ret);
3175                 return -EINVAL;
3176         }
3177         if (val > MAX_SRPT_RSP_SIZE) {
3178                 pr_err("val: %lu exceeds MAX_SRPT_RSP_SIZE: %d\n", val,
3179                         MAX_SRPT_RSP_SIZE);
3180                 return -EINVAL;
3181         }
3182         if (val < MIN_MAX_RSP_SIZE) {
3183                 pr_err("val: %lu smaller than MIN_MAX_RSP_SIZE: %d\n", val,
3184                         MIN_MAX_RSP_SIZE);
3185                 return -EINVAL;
3186         }
3187         sport->port_attrib.srp_max_rsp_size = val;
3188
3189         return count;
3190 }
3191
3192 static ssize_t srpt_tpg_attrib_srp_sq_size_show(struct config_item *item,
3193                 char *page)
3194 {
3195         struct se_portal_group *se_tpg = attrib_to_tpg(item);
3196         struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3197
3198         return sprintf(page, "%u\n", sport->port_attrib.srp_sq_size);
3199 }
3200
3201 static ssize_t srpt_tpg_attrib_srp_sq_size_store(struct config_item *item,
3202                 const char *page, size_t count)
3203 {
3204         struct se_portal_group *se_tpg = attrib_to_tpg(item);
3205         struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3206         unsigned long val;
3207         int ret;
3208
3209         ret = kstrtoul(page, 0, &val);
3210         if (ret < 0) {
3211                 pr_err("kstrtoul() failed with ret: %d\n", ret);
3212                 return -EINVAL;
3213         }
3214         if (val > MAX_SRPT_SRQ_SIZE) {
3215                 pr_err("val: %lu exceeds MAX_SRPT_SRQ_SIZE: %d\n", val,
3216                         MAX_SRPT_SRQ_SIZE);
3217                 return -EINVAL;
3218         }
3219         if (val < MIN_SRPT_SRQ_SIZE) {
3220                 pr_err("val: %lu smaller than MIN_SRPT_SRQ_SIZE: %d\n", val,
3221                         MIN_SRPT_SRQ_SIZE);
3222                 return -EINVAL;
3223         }
3224         sport->port_attrib.srp_sq_size = val;
3225
3226         return count;
3227 }
3228
3229 CONFIGFS_ATTR(srpt_tpg_attrib_,  srp_max_rdma_size);
3230 CONFIGFS_ATTR(srpt_tpg_attrib_,  srp_max_rsp_size);
3231 CONFIGFS_ATTR(srpt_tpg_attrib_,  srp_sq_size);
3232
3233 static struct configfs_attribute *srpt_tpg_attrib_attrs[] = {
3234         &srpt_tpg_attrib_attr_srp_max_rdma_size,
3235         &srpt_tpg_attrib_attr_srp_max_rsp_size,
3236         &srpt_tpg_attrib_attr_srp_sq_size,
3237         NULL,
3238 };
3239
3240 static ssize_t srpt_tpg_enable_show(struct config_item *item, char *page)
3241 {
3242         struct se_portal_group *se_tpg = to_tpg(item);
3243         struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3244
3245         return snprintf(page, PAGE_SIZE, "%d\n", (sport->enabled) ? 1: 0);
3246 }
3247
3248 static ssize_t srpt_tpg_enable_store(struct config_item *item,
3249                 const char *page, size_t count)
3250 {
3251         struct se_portal_group *se_tpg = to_tpg(item);
3252         struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3253         unsigned long tmp;
3254         int ret;
3255
3256         ret = kstrtoul(page, 0, &tmp);
3257         if (ret < 0) {
3258                 pr_err("Unable to extract srpt_tpg_store_enable\n");
3259                 return -EINVAL;
3260         }
3261
3262         if ((tmp != 0) && (tmp != 1)) {
3263                 pr_err("Illegal value for srpt_tpg_store_enable: %lu\n", tmp);
3264                 return -EINVAL;
3265         }
3266         if (tmp == 1)
3267                 sport->enabled = true;
3268         else
3269                 sport->enabled = false;
3270
3271         return count;
3272 }
3273
3274 CONFIGFS_ATTR(srpt_tpg_, enable);
3275
3276 static struct configfs_attribute *srpt_tpg_attrs[] = {
3277         &srpt_tpg_attr_enable,
3278         NULL,
3279 };
3280
3281 /**
3282  * configfs callback invoked for
3283  * mkdir /sys/kernel/config/target/$driver/$port/$tpg
3284  */
3285 static struct se_portal_group *srpt_make_tpg(struct se_wwn *wwn,
3286                                              struct config_group *group,
3287                                              const char *name)
3288 {
3289         struct srpt_port *sport = container_of(wwn, struct srpt_port, port_wwn);
3290         int res;
3291
3292         /* Initialize sport->port_wwn and sport->port_tpg_1 */
3293         res = core_tpg_register(&sport->port_wwn, &sport->port_tpg_1, SCSI_PROTOCOL_SRP);
3294         if (res)
3295                 return ERR_PTR(res);
3296
3297         return &sport->port_tpg_1;
3298 }
3299
3300 /**
3301  * configfs callback invoked for
3302  * rmdir /sys/kernel/config/target/$driver/$port/$tpg
3303  */
3304 static void srpt_drop_tpg(struct se_portal_group *tpg)
3305 {
3306         struct srpt_port *sport = container_of(tpg,
3307                                 struct srpt_port, port_tpg_1);
3308
3309         sport->enabled = false;
3310         core_tpg_deregister(&sport->port_tpg_1);
3311 }
3312
3313 /**
3314  * configfs callback invoked for
3315  * mkdir /sys/kernel/config/target/$driver/$port
3316  */
3317 static struct se_wwn *srpt_make_tport(struct target_fabric_configfs *tf,
3318                                       struct config_group *group,
3319                                       const char *name)
3320 {
3321         struct srpt_port *sport;
3322         int ret;
3323
3324         sport = srpt_lookup_port(name);
3325         pr_debug("make_tport(%s)\n", name);
3326         ret = -EINVAL;
3327         if (!sport)
3328                 goto err;
3329
3330         return &sport->port_wwn;
3331
3332 err:
3333         return ERR_PTR(ret);
3334 }
3335
3336 /**
3337  * configfs callback invoked for
3338  * rmdir /sys/kernel/config/target/$driver/$port
3339  */
3340 static void srpt_drop_tport(struct se_wwn *wwn)
3341 {
3342         struct srpt_port *sport = container_of(wwn, struct srpt_port, port_wwn);
3343
3344         pr_debug("drop_tport(%s\n", config_item_name(&sport->port_wwn.wwn_group.cg_item));
3345 }
3346
3347 static ssize_t srpt_wwn_version_show(struct config_item *item, char *buf)
3348 {
3349         return scnprintf(buf, PAGE_SIZE, "%s\n", DRV_VERSION);
3350 }
3351
3352 CONFIGFS_ATTR_RO(srpt_wwn_, version);
3353
3354 static struct configfs_attribute *srpt_wwn_attrs[] = {
3355         &srpt_wwn_attr_version,
3356         NULL,
3357 };
3358
3359 static const struct target_core_fabric_ops srpt_template = {
3360         .module                         = THIS_MODULE,
3361         .name                           = "srpt",
3362         .get_fabric_name                = srpt_get_fabric_name,
3363         .tpg_get_wwn                    = srpt_get_fabric_wwn,
3364         .tpg_get_tag                    = srpt_get_tag,
3365         .tpg_check_demo_mode            = srpt_check_false,
3366         .tpg_check_demo_mode_cache      = srpt_check_true,
3367         .tpg_check_demo_mode_write_protect = srpt_check_true,
3368         .tpg_check_prod_mode_write_protect = srpt_check_false,
3369         .tpg_get_inst_index             = srpt_tpg_get_inst_index,
3370         .release_cmd                    = srpt_release_cmd,
3371         .check_stop_free                = srpt_check_stop_free,
3372         .shutdown_session               = srpt_shutdown_session,
3373         .close_session                  = srpt_close_session,
3374         .sess_get_index                 = srpt_sess_get_index,
3375         .sess_get_initiator_sid         = NULL,
3376         .write_pending                  = srpt_write_pending,
3377         .write_pending_status           = srpt_write_pending_status,
3378         .set_default_node_attributes    = srpt_set_default_node_attrs,
3379         .get_cmd_state                  = srpt_get_tcm_cmd_state,
3380         .queue_data_in                  = srpt_queue_data_in,
3381         .queue_status                   = srpt_queue_status,
3382         .queue_tm_rsp                   = srpt_queue_tm_rsp,
3383         .aborted_task                   = srpt_aborted_task,
3384         /*
3385          * Setup function pointers for generic logic in
3386          * target_core_fabric_configfs.c
3387          */
3388         .fabric_make_wwn                = srpt_make_tport,
3389         .fabric_drop_wwn                = srpt_drop_tport,
3390         .fabric_make_tpg                = srpt_make_tpg,
3391         .fabric_drop_tpg                = srpt_drop_tpg,
3392         .fabric_init_nodeacl            = srpt_init_nodeacl,
3393
3394         .tfc_wwn_attrs                  = srpt_wwn_attrs,
3395         .tfc_tpg_base_attrs             = srpt_tpg_attrs,
3396         .tfc_tpg_attrib_attrs           = srpt_tpg_attrib_attrs,
3397 };
3398
3399 /**
3400  * srpt_init_module() - Kernel module initialization.
3401  *
3402  * Note: Since ib_register_client() registers callback functions, and since at
3403  * least one of these callback functions (srpt_add_one()) calls target core
3404  * functions, this driver must be registered with the target core before
3405  * ib_register_client() is called.
3406  */
3407 static int __init srpt_init_module(void)
3408 {
3409         int ret;
3410
3411         ret = -EINVAL;
3412         if (srp_max_req_size < MIN_MAX_REQ_SIZE) {
3413                 pr_err("invalid value %d for kernel module parameter"
3414                        " srp_max_req_size -- must be at least %d.\n",
3415                        srp_max_req_size, MIN_MAX_REQ_SIZE);
3416                 goto out;
3417         }
3418
3419         if (srpt_srq_size < MIN_SRPT_SRQ_SIZE
3420             || srpt_srq_size > MAX_SRPT_SRQ_SIZE) {
3421                 pr_err("invalid value %d for kernel module parameter"
3422                        " srpt_srq_size -- must be in the range [%d..%d].\n",
3423                        srpt_srq_size, MIN_SRPT_SRQ_SIZE, MAX_SRPT_SRQ_SIZE);
3424                 goto out;
3425         }
3426
3427         ret = target_register_template(&srpt_template);
3428         if (ret)
3429                 goto out;
3430
3431         ret = ib_register_client(&srpt_client);
3432         if (ret) {
3433                 pr_err("couldn't register IB client\n");
3434                 goto out_unregister_target;
3435         }
3436
3437         return 0;
3438
3439 out_unregister_target:
3440         target_unregister_template(&srpt_template);
3441 out:
3442         return ret;
3443 }
3444
3445 static void __exit srpt_cleanup_module(void)
3446 {
3447         ib_unregister_client(&srpt_client);
3448         target_unregister_template(&srpt_template);
3449 }
3450
3451 module_init(srpt_init_module);
3452 module_exit(srpt_cleanup_module);