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