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