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