2 * Copyright (c) 2006 - 2009 Mellanox Technology Inc. All rights reserved.
3 * Copyright (C) 2008 - 2011 Bart Van Assche <bvanassche@acm.org>.
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:
11 * Redistribution and use in source and binary forms, with or
12 * without modification, are permitted provided that the following
15 * - Redistributions of source code must retain the above
16 * copyright notice, this list of conditions and the following
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.
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
35 #include <linux/module.h>
36 #include <linux/init.h>
37 #include <linux/slab.h>
38 #include <linux/err.h>
39 #include <linux/ctype.h>
40 #include <linux/kthread.h>
41 #include <linux/string.h>
42 #include <linux/delay.h>
43 #include <linux/atomic.h>
44 #include <scsi/scsi_proto.h>
45 #include <scsi/scsi_tcq.h>
46 #include <target/configfs_macros.h>
47 #include <target/target_core_base.h>
48 #include <target/target_core_fabric_configfs.h>
49 #include <target/target_core_fabric.h>
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"
57 #define SRPT_ID_STRING "Linux SRP target"
60 #define pr_fmt(fmt) DRV_NAME " " fmt
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");
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. */
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.");
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.");
85 static int srpt_get_u64_x(char *buffer, struct kernel_param *kp)
87 return sprintf(buffer, "0x%016llx", *(u64 *)kp->arg);
89 module_param_call(srpt_service_guid, NULL, srpt_get_u64_x, &srpt_service_guid,
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.");
95 static struct ib_client srpt_client;
96 static void srpt_release_channel(struct srpt_rdma_ch *ch);
97 static int srpt_queue_status(struct se_cmd *cmd);
100 * opposite_dma_dir() - Swap DMA_TO_DEVICE and DMA_FROM_DEVICE.
103 enum dma_data_direction opposite_dma_dir(enum dma_data_direction dir)
106 case DMA_TO_DEVICE: return DMA_FROM_DEVICE;
107 case DMA_FROM_DEVICE: return DMA_TO_DEVICE;
113 * srpt_sdev_name() - Return the name associated with the HCA.
115 * Examples are ib0, ib1, ...
117 static inline const char *srpt_sdev_name(struct srpt_device *sdev)
119 return sdev->device->name;
122 static enum rdma_ch_state srpt_get_ch_state(struct srpt_rdma_ch *ch)
125 enum rdma_ch_state state;
127 spin_lock_irqsave(&ch->spinlock, flags);
129 spin_unlock_irqrestore(&ch->spinlock, flags);
133 static enum rdma_ch_state
134 srpt_set_ch_state(struct srpt_rdma_ch *ch, enum rdma_ch_state new_state)
137 enum rdma_ch_state prev;
139 spin_lock_irqsave(&ch->spinlock, flags);
141 ch->state = new_state;
142 spin_unlock_irqrestore(&ch->spinlock, flags);
147 * srpt_test_and_set_ch_state() - Test and set the channel state.
149 * Returns true if and only if the channel state has been set to the new state.
152 srpt_test_and_set_ch_state(struct srpt_rdma_ch *ch, enum rdma_ch_state old,
153 enum rdma_ch_state new)
156 enum rdma_ch_state prev;
158 spin_lock_irqsave(&ch->spinlock, flags);
162 spin_unlock_irqrestore(&ch->spinlock, flags);
167 * srpt_event_handler() - Asynchronous IB event callback function.
169 * Callback function called by the InfiniBand core when an asynchronous IB
170 * event occurs. This callback may occur in interrupt context. See also
171 * section 11.5.2, Set Asynchronous Event Handler in the InfiniBand
172 * Architecture Specification.
174 static void srpt_event_handler(struct ib_event_handler *handler,
175 struct ib_event *event)
177 struct srpt_device *sdev;
178 struct srpt_port *sport;
180 sdev = ib_get_client_data(event->device, &srpt_client);
181 if (!sdev || sdev->device != event->device)
184 pr_debug("ASYNC event= %d on device= %s\n", event->event,
185 srpt_sdev_name(sdev));
187 switch (event->event) {
188 case IB_EVENT_PORT_ERR:
189 if (event->element.port_num <= sdev->device->phys_port_cnt) {
190 sport = &sdev->port[event->element.port_num - 1];
195 case IB_EVENT_PORT_ACTIVE:
196 case IB_EVENT_LID_CHANGE:
197 case IB_EVENT_PKEY_CHANGE:
198 case IB_EVENT_SM_CHANGE:
199 case IB_EVENT_CLIENT_REREGISTER:
200 case IB_EVENT_GID_CHANGE:
201 /* Refresh port data asynchronously. */
202 if (event->element.port_num <= sdev->device->phys_port_cnt) {
203 sport = &sdev->port[event->element.port_num - 1];
204 if (!sport->lid && !sport->sm_lid)
205 schedule_work(&sport->work);
209 pr_err("received unrecognized IB event %d\n",
216 * srpt_srq_event() - SRQ event callback function.
218 static void srpt_srq_event(struct ib_event *event, void *ctx)
220 pr_info("SRQ event %d\n", event->event);
224 * srpt_qp_event() - QP event callback function.
226 static void srpt_qp_event(struct ib_event *event, struct srpt_rdma_ch *ch)
228 pr_debug("QP event %d on cm_id=%p sess_name=%s state=%d\n",
229 event->event, ch->cm_id, ch->sess_name, srpt_get_ch_state(ch));
231 switch (event->event) {
232 case IB_EVENT_COMM_EST:
233 ib_cm_notify(ch->cm_id, event->event);
235 case IB_EVENT_QP_LAST_WQE_REACHED:
236 if (srpt_test_and_set_ch_state(ch, CH_DRAINING,
238 srpt_release_channel(ch);
240 pr_debug("%s: state %d - ignored LAST_WQE.\n",
241 ch->sess_name, srpt_get_ch_state(ch));
244 pr_err("received unrecognized IB QP event %d\n", event->event);
250 * srpt_set_ioc() - Helper function for initializing an IOUnitInfo structure.
252 * @slot: one-based slot number.
253 * @value: four-bit value.
255 * Copies the lowest four bits of value in element slot of the array of four
256 * bit elements called c_list (controller list). The index slot is one-based.
258 static void srpt_set_ioc(u8 *c_list, u32 slot, u8 value)
265 tmp = c_list[id] & 0xf;
266 c_list[id] = (value << 4) | tmp;
268 tmp = c_list[id] & 0xf0;
269 c_list[id] = (value & 0xf) | tmp;
274 * srpt_get_class_port_info() - Copy ClassPortInfo to a management datagram.
276 * See also section 16.3.3.1 ClassPortInfo in the InfiniBand Architecture
279 static void srpt_get_class_port_info(struct ib_dm_mad *mad)
281 struct ib_class_port_info *cif;
283 cif = (struct ib_class_port_info *)mad->data;
284 memset(cif, 0, sizeof *cif);
285 cif->base_version = 1;
286 cif->class_version = 1;
287 cif->resp_time_value = 20;
289 mad->mad_hdr.status = 0;
293 * srpt_get_iou() - Write IOUnitInfo to a management datagram.
295 * See also section 16.3.3.3 IOUnitInfo in the InfiniBand Architecture
296 * Specification. See also section B.7, table B.6 in the SRP r16a document.
298 static void srpt_get_iou(struct ib_dm_mad *mad)
300 struct ib_dm_iou_info *ioui;
304 ioui = (struct ib_dm_iou_info *)mad->data;
305 ioui->change_id = cpu_to_be16(1);
306 ioui->max_controllers = 16;
308 /* set present for slot 1 and empty for the rest */
309 srpt_set_ioc(ioui->controller_list, 1, 1);
310 for (i = 1, slot = 2; i < 16; i++, slot++)
311 srpt_set_ioc(ioui->controller_list, slot, 0);
313 mad->mad_hdr.status = 0;
317 * srpt_get_ioc() - Write IOControllerprofile to a management datagram.
319 * See also section 16.3.3.4 IOControllerProfile in the InfiniBand
320 * Architecture Specification. See also section B.7, table B.7 in the SRP
323 static void srpt_get_ioc(struct srpt_port *sport, u32 slot,
324 struct ib_dm_mad *mad)
326 struct srpt_device *sdev = sport->sdev;
327 struct ib_dm_ioc_profile *iocp;
329 iocp = (struct ib_dm_ioc_profile *)mad->data;
331 if (!slot || slot > 16) {
333 = cpu_to_be16(DM_MAD_STATUS_INVALID_FIELD);
339 = cpu_to_be16(DM_MAD_STATUS_NO_IOC);
343 memset(iocp, 0, sizeof *iocp);
344 strcpy(iocp->id_string, SRPT_ID_STRING);
345 iocp->guid = cpu_to_be64(srpt_service_guid);
346 iocp->vendor_id = cpu_to_be32(sdev->dev_attr.vendor_id);
347 iocp->device_id = cpu_to_be32(sdev->dev_attr.vendor_part_id);
348 iocp->device_version = cpu_to_be16(sdev->dev_attr.hw_ver);
349 iocp->subsys_vendor_id = cpu_to_be32(sdev->dev_attr.vendor_id);
350 iocp->subsys_device_id = 0x0;
351 iocp->io_class = cpu_to_be16(SRP_REV16A_IB_IO_CLASS);
352 iocp->io_subclass = cpu_to_be16(SRP_IO_SUBCLASS);
353 iocp->protocol = cpu_to_be16(SRP_PROTOCOL);
354 iocp->protocol_version = cpu_to_be16(SRP_PROTOCOL_VERSION);
355 iocp->send_queue_depth = cpu_to_be16(sdev->srq_size);
356 iocp->rdma_read_depth = 4;
357 iocp->send_size = cpu_to_be32(srp_max_req_size);
358 iocp->rdma_size = cpu_to_be32(min(sport->port_attrib.srp_max_rdma_size,
360 iocp->num_svc_entries = 1;
361 iocp->op_cap_mask = SRP_SEND_TO_IOC | SRP_SEND_FROM_IOC |
362 SRP_RDMA_READ_FROM_IOC | SRP_RDMA_WRITE_FROM_IOC;
364 mad->mad_hdr.status = 0;
368 * srpt_get_svc_entries() - Write ServiceEntries to a management datagram.
370 * See also section 16.3.3.5 ServiceEntries in the InfiniBand Architecture
371 * Specification. See also section B.7, table B.8 in the SRP r16a document.
373 static void srpt_get_svc_entries(u64 ioc_guid,
374 u16 slot, u8 hi, u8 lo, struct ib_dm_mad *mad)
376 struct ib_dm_svc_entries *svc_entries;
380 if (!slot || slot > 16) {
382 = cpu_to_be16(DM_MAD_STATUS_INVALID_FIELD);
386 if (slot > 2 || lo > hi || hi > 1) {
388 = cpu_to_be16(DM_MAD_STATUS_NO_IOC);
392 svc_entries = (struct ib_dm_svc_entries *)mad->data;
393 memset(svc_entries, 0, sizeof *svc_entries);
394 svc_entries->service_entries[0].id = cpu_to_be64(ioc_guid);
395 snprintf(svc_entries->service_entries[0].name,
396 sizeof(svc_entries->service_entries[0].name),
398 SRP_SERVICE_NAME_PREFIX,
401 mad->mad_hdr.status = 0;
405 * srpt_mgmt_method_get() - Process a received management datagram.
406 * @sp: source port through which the MAD has been received.
407 * @rq_mad: received MAD.
408 * @rsp_mad: response MAD.
410 static void srpt_mgmt_method_get(struct srpt_port *sp, struct ib_mad *rq_mad,
411 struct ib_dm_mad *rsp_mad)
417 attr_id = be16_to_cpu(rq_mad->mad_hdr.attr_id);
419 case DM_ATTR_CLASS_PORT_INFO:
420 srpt_get_class_port_info(rsp_mad);
422 case DM_ATTR_IOU_INFO:
423 srpt_get_iou(rsp_mad);
425 case DM_ATTR_IOC_PROFILE:
426 slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
427 srpt_get_ioc(sp, slot, rsp_mad);
429 case DM_ATTR_SVC_ENTRIES:
430 slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
431 hi = (u8) ((slot >> 8) & 0xff);
432 lo = (u8) (slot & 0xff);
433 slot = (u16) ((slot >> 16) & 0xffff);
434 srpt_get_svc_entries(srpt_service_guid,
435 slot, hi, lo, rsp_mad);
438 rsp_mad->mad_hdr.status =
439 cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
445 * srpt_mad_send_handler() - Post MAD-send callback function.
447 static void srpt_mad_send_handler(struct ib_mad_agent *mad_agent,
448 struct ib_mad_send_wc *mad_wc)
450 ib_destroy_ah(mad_wc->send_buf->ah);
451 ib_free_send_mad(mad_wc->send_buf);
455 * srpt_mad_recv_handler() - MAD reception callback function.
457 static void srpt_mad_recv_handler(struct ib_mad_agent *mad_agent,
458 struct ib_mad_recv_wc *mad_wc)
460 struct srpt_port *sport = (struct srpt_port *)mad_agent->context;
462 struct ib_mad_send_buf *rsp;
463 struct ib_dm_mad *dm_mad;
465 if (!mad_wc || !mad_wc->recv_buf.mad)
468 ah = ib_create_ah_from_wc(mad_agent->qp->pd, mad_wc->wc,
469 mad_wc->recv_buf.grh, mad_agent->port_num);
473 BUILD_BUG_ON(offsetof(struct ib_dm_mad, data) != IB_MGMT_DEVICE_HDR);
475 rsp = ib_create_send_mad(mad_agent, mad_wc->wc->src_qp,
476 mad_wc->wc->pkey_index, 0,
477 IB_MGMT_DEVICE_HDR, IB_MGMT_DEVICE_DATA,
479 IB_MGMT_BASE_VERSION);
486 memcpy(dm_mad, mad_wc->recv_buf.mad, sizeof *dm_mad);
487 dm_mad->mad_hdr.method = IB_MGMT_METHOD_GET_RESP;
488 dm_mad->mad_hdr.status = 0;
490 switch (mad_wc->recv_buf.mad->mad_hdr.method) {
491 case IB_MGMT_METHOD_GET:
492 srpt_mgmt_method_get(sport, mad_wc->recv_buf.mad, dm_mad);
494 case IB_MGMT_METHOD_SET:
495 dm_mad->mad_hdr.status =
496 cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
499 dm_mad->mad_hdr.status =
500 cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD);
504 if (!ib_post_send_mad(rsp, NULL)) {
505 ib_free_recv_mad(mad_wc);
506 /* will destroy_ah & free_send_mad in send completion */
510 ib_free_send_mad(rsp);
515 ib_free_recv_mad(mad_wc);
519 * srpt_refresh_port() - Configure a HCA port.
521 * Enable InfiniBand management datagram processing, update the cached sm_lid,
522 * lid and gid values, and register a callback function for processing MADs
523 * on the specified port.
525 * Note: It is safe to call this function more than once for the same port.
527 static int srpt_refresh_port(struct srpt_port *sport)
529 struct ib_mad_reg_req reg_req;
530 struct ib_port_modify port_modify;
531 struct ib_port_attr port_attr;
534 memset(&port_modify, 0, sizeof port_modify);
535 port_modify.set_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP;
536 port_modify.clr_port_cap_mask = 0;
538 ret = ib_modify_port(sport->sdev->device, sport->port, 0, &port_modify);
542 ret = ib_query_port(sport->sdev->device, sport->port, &port_attr);
546 sport->sm_lid = port_attr.sm_lid;
547 sport->lid = port_attr.lid;
549 ret = ib_query_gid(sport->sdev->device, sport->port, 0, &sport->gid,
554 if (!sport->mad_agent) {
555 memset(®_req, 0, sizeof reg_req);
556 reg_req.mgmt_class = IB_MGMT_CLASS_DEVICE_MGMT;
557 reg_req.mgmt_class_version = IB_MGMT_BASE_VERSION;
558 set_bit(IB_MGMT_METHOD_GET, reg_req.method_mask);
559 set_bit(IB_MGMT_METHOD_SET, reg_req.method_mask);
561 sport->mad_agent = ib_register_mad_agent(sport->sdev->device,
565 srpt_mad_send_handler,
566 srpt_mad_recv_handler,
568 if (IS_ERR(sport->mad_agent)) {
569 ret = PTR_ERR(sport->mad_agent);
570 sport->mad_agent = NULL;
579 port_modify.set_port_cap_mask = 0;
580 port_modify.clr_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP;
581 ib_modify_port(sport->sdev->device, sport->port, 0, &port_modify);
589 * srpt_unregister_mad_agent() - Unregister MAD callback functions.
591 * Note: It is safe to call this function more than once for the same device.
593 static void srpt_unregister_mad_agent(struct srpt_device *sdev)
595 struct ib_port_modify port_modify = {
596 .clr_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP,
598 struct srpt_port *sport;
601 for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
602 sport = &sdev->port[i - 1];
603 WARN_ON(sport->port != i);
604 if (ib_modify_port(sdev->device, i, 0, &port_modify) < 0)
605 pr_err("disabling MAD processing failed.\n");
606 if (sport->mad_agent) {
607 ib_unregister_mad_agent(sport->mad_agent);
608 sport->mad_agent = NULL;
614 * srpt_alloc_ioctx() - Allocate an SRPT I/O context structure.
616 static struct srpt_ioctx *srpt_alloc_ioctx(struct srpt_device *sdev,
617 int ioctx_size, int dma_size,
618 enum dma_data_direction dir)
620 struct srpt_ioctx *ioctx;
622 ioctx = kmalloc(ioctx_size, GFP_KERNEL);
626 ioctx->buf = kmalloc(dma_size, GFP_KERNEL);
630 ioctx->dma = ib_dma_map_single(sdev->device, ioctx->buf, dma_size, dir);
631 if (ib_dma_mapping_error(sdev->device, ioctx->dma))
645 * srpt_free_ioctx() - Free an SRPT I/O context structure.
647 static void srpt_free_ioctx(struct srpt_device *sdev, struct srpt_ioctx *ioctx,
648 int dma_size, enum dma_data_direction dir)
653 ib_dma_unmap_single(sdev->device, ioctx->dma, dma_size, dir);
659 * srpt_alloc_ioctx_ring() - Allocate a ring of SRPT I/O context structures.
660 * @sdev: Device to allocate the I/O context ring for.
661 * @ring_size: Number of elements in the I/O context ring.
662 * @ioctx_size: I/O context size.
663 * @dma_size: DMA buffer size.
664 * @dir: DMA data direction.
666 static struct srpt_ioctx **srpt_alloc_ioctx_ring(struct srpt_device *sdev,
667 int ring_size, int ioctx_size,
668 int dma_size, enum dma_data_direction dir)
670 struct srpt_ioctx **ring;
673 WARN_ON(ioctx_size != sizeof(struct srpt_recv_ioctx)
674 && ioctx_size != sizeof(struct srpt_send_ioctx));
676 ring = kmalloc(ring_size * sizeof(ring[0]), GFP_KERNEL);
679 for (i = 0; i < ring_size; ++i) {
680 ring[i] = srpt_alloc_ioctx(sdev, ioctx_size, dma_size, dir);
689 srpt_free_ioctx(sdev, ring[i], dma_size, dir);
697 * srpt_free_ioctx_ring() - Free the ring of SRPT I/O context structures.
699 static void srpt_free_ioctx_ring(struct srpt_ioctx **ioctx_ring,
700 struct srpt_device *sdev, int ring_size,
701 int dma_size, enum dma_data_direction dir)
705 for (i = 0; i < ring_size; ++i)
706 srpt_free_ioctx(sdev, ioctx_ring[i], dma_size, dir);
711 * srpt_get_cmd_state() - Get the state of a SCSI command.
713 static enum srpt_command_state srpt_get_cmd_state(struct srpt_send_ioctx *ioctx)
715 enum srpt_command_state state;
720 spin_lock_irqsave(&ioctx->spinlock, flags);
721 state = ioctx->state;
722 spin_unlock_irqrestore(&ioctx->spinlock, flags);
727 * srpt_set_cmd_state() - Set the state of a SCSI command.
729 * Does not modify the state of aborted commands. Returns the previous command
732 static enum srpt_command_state srpt_set_cmd_state(struct srpt_send_ioctx *ioctx,
733 enum srpt_command_state new)
735 enum srpt_command_state previous;
740 spin_lock_irqsave(&ioctx->spinlock, flags);
741 previous = ioctx->state;
742 if (previous != SRPT_STATE_DONE)
744 spin_unlock_irqrestore(&ioctx->spinlock, flags);
750 * srpt_test_and_set_cmd_state() - Test and set the state of a command.
752 * Returns true if and only if the previous command state was equal to 'old'.
754 static bool srpt_test_and_set_cmd_state(struct srpt_send_ioctx *ioctx,
755 enum srpt_command_state old,
756 enum srpt_command_state new)
758 enum srpt_command_state previous;
762 WARN_ON(old == SRPT_STATE_DONE);
763 WARN_ON(new == SRPT_STATE_NEW);
765 spin_lock_irqsave(&ioctx->spinlock, flags);
766 previous = ioctx->state;
769 spin_unlock_irqrestore(&ioctx->spinlock, flags);
770 return previous == old;
774 * srpt_post_recv() - Post an IB receive request.
776 static int srpt_post_recv(struct srpt_device *sdev,
777 struct srpt_recv_ioctx *ioctx)
780 struct ib_recv_wr wr, *bad_wr;
783 wr.wr_id = encode_wr_id(SRPT_RECV, ioctx->ioctx.index);
785 list.addr = ioctx->ioctx.dma;
786 list.length = srp_max_req_size;
787 list.lkey = sdev->pd->local_dma_lkey;
793 return ib_post_srq_recv(sdev->srq, &wr, &bad_wr);
797 * srpt_post_send() - Post an IB send request.
799 * Returns zero upon success and a non-zero value upon failure.
801 static int srpt_post_send(struct srpt_rdma_ch *ch,
802 struct srpt_send_ioctx *ioctx, int len)
805 struct ib_send_wr wr, *bad_wr;
806 struct srpt_device *sdev = ch->sport->sdev;
809 atomic_inc(&ch->req_lim);
812 if (unlikely(atomic_dec_return(&ch->sq_wr_avail) < 0)) {
813 pr_warn("IB send queue full (needed 1)\n");
817 ib_dma_sync_single_for_device(sdev->device, ioctx->ioctx.dma, len,
820 list.addr = ioctx->ioctx.dma;
822 list.lkey = sdev->pd->local_dma_lkey;
825 wr.wr_id = encode_wr_id(SRPT_SEND, ioctx->ioctx.index);
828 wr.opcode = IB_WR_SEND;
829 wr.send_flags = IB_SEND_SIGNALED;
831 ret = ib_post_send(ch->qp, &wr, &bad_wr);
835 atomic_inc(&ch->sq_wr_avail);
836 atomic_dec(&ch->req_lim);
842 * srpt_get_desc_tbl() - Parse the data descriptors of an SRP_CMD request.
843 * @ioctx: Pointer to the I/O context associated with the request.
844 * @srp_cmd: Pointer to the SRP_CMD request data.
845 * @dir: Pointer to the variable to which the transfer direction will be
847 * @data_len: Pointer to the variable to which the total data length of all
848 * descriptors in the SRP_CMD request will be written.
850 * This function initializes ioctx->nrbuf and ioctx->r_bufs.
852 * Returns -EINVAL when the SRP_CMD request contains inconsistent descriptors;
853 * -ENOMEM when memory allocation fails and zero upon success.
855 static int srpt_get_desc_tbl(struct srpt_send_ioctx *ioctx,
856 struct srp_cmd *srp_cmd,
857 enum dma_data_direction *dir, u64 *data_len)
859 struct srp_indirect_buf *idb;
860 struct srp_direct_buf *db;
861 unsigned add_cdb_offset;
865 * The pointer computations below will only be compiled correctly
866 * if srp_cmd::add_data is declared as s8*, u8*, s8[] or u8[], so check
867 * whether srp_cmd::add_data has been declared as a byte pointer.
869 BUILD_BUG_ON(!__same_type(srp_cmd->add_data[0], (s8)0)
870 && !__same_type(srp_cmd->add_data[0], (u8)0));
879 * The lower four bits of the buffer format field contain the DATA-IN
880 * buffer descriptor format, and the highest four bits contain the
881 * DATA-OUT buffer descriptor format.
884 if (srp_cmd->buf_fmt & 0xf)
885 /* DATA-IN: transfer data from target to initiator (read). */
886 *dir = DMA_FROM_DEVICE;
887 else if (srp_cmd->buf_fmt >> 4)
888 /* DATA-OUT: transfer data from initiator to target (write). */
889 *dir = DMA_TO_DEVICE;
892 * According to the SRP spec, the lower two bits of the 'ADDITIONAL
893 * CDB LENGTH' field are reserved and the size in bytes of this field
894 * is four times the value specified in bits 3..7. Hence the "& ~3".
896 add_cdb_offset = srp_cmd->add_cdb_len & ~3;
897 if (((srp_cmd->buf_fmt & 0xf) == SRP_DATA_DESC_DIRECT) ||
898 ((srp_cmd->buf_fmt >> 4) == SRP_DATA_DESC_DIRECT)) {
900 ioctx->rbufs = &ioctx->single_rbuf;
902 db = (struct srp_direct_buf *)(srp_cmd->add_data
904 memcpy(ioctx->rbufs, db, sizeof *db);
905 *data_len = be32_to_cpu(db->len);
906 } else if (((srp_cmd->buf_fmt & 0xf) == SRP_DATA_DESC_INDIRECT) ||
907 ((srp_cmd->buf_fmt >> 4) == SRP_DATA_DESC_INDIRECT)) {
908 idb = (struct srp_indirect_buf *)(srp_cmd->add_data
911 ioctx->n_rbuf = be32_to_cpu(idb->table_desc.len) / sizeof *db;
914 (srp_cmd->data_out_desc_cnt + srp_cmd->data_in_desc_cnt)) {
915 pr_err("received unsupported SRP_CMD request"
916 " type (%u out + %u in != %u / %zu)\n",
917 srp_cmd->data_out_desc_cnt,
918 srp_cmd->data_in_desc_cnt,
919 be32_to_cpu(idb->table_desc.len),
926 if (ioctx->n_rbuf == 1)
927 ioctx->rbufs = &ioctx->single_rbuf;
930 kmalloc(ioctx->n_rbuf * sizeof *db, GFP_ATOMIC);
939 memcpy(ioctx->rbufs, db, ioctx->n_rbuf * sizeof *db);
940 *data_len = be32_to_cpu(idb->len);
947 * srpt_init_ch_qp() - Initialize queue pair attributes.
949 * Initialized the attributes of queue pair 'qp' by allowing local write,
950 * remote read and remote write. Also transitions 'qp' to state IB_QPS_INIT.
952 static int srpt_init_ch_qp(struct srpt_rdma_ch *ch, struct ib_qp *qp)
954 struct ib_qp_attr *attr;
957 attr = kzalloc(sizeof *attr, GFP_KERNEL);
961 attr->qp_state = IB_QPS_INIT;
962 attr->qp_access_flags = IB_ACCESS_LOCAL_WRITE | IB_ACCESS_REMOTE_READ |
963 IB_ACCESS_REMOTE_WRITE;
964 attr->port_num = ch->sport->port;
965 attr->pkey_index = 0;
967 ret = ib_modify_qp(qp, attr,
968 IB_QP_STATE | IB_QP_ACCESS_FLAGS | IB_QP_PORT |
976 * srpt_ch_qp_rtr() - Change the state of a channel to 'ready to receive' (RTR).
977 * @ch: channel of the queue pair.
978 * @qp: queue pair to change the state of.
980 * Returns zero upon success and a negative value upon failure.
982 * Note: currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
983 * If this structure ever becomes larger, it might be necessary to allocate
984 * it dynamically instead of on the stack.
986 static int srpt_ch_qp_rtr(struct srpt_rdma_ch *ch, struct ib_qp *qp)
988 struct ib_qp_attr qp_attr;
992 qp_attr.qp_state = IB_QPS_RTR;
993 ret = ib_cm_init_qp_attr(ch->cm_id, &qp_attr, &attr_mask);
997 qp_attr.max_dest_rd_atomic = 4;
999 ret = ib_modify_qp(qp, &qp_attr, attr_mask);
1006 * srpt_ch_qp_rts() - Change the state of a channel to 'ready to send' (RTS).
1007 * @ch: channel of the queue pair.
1008 * @qp: queue pair to change the state of.
1010 * Returns zero upon success and a negative value upon failure.
1012 * Note: currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
1013 * If this structure ever becomes larger, it might be necessary to allocate
1014 * it dynamically instead of on the stack.
1016 static int srpt_ch_qp_rts(struct srpt_rdma_ch *ch, struct ib_qp *qp)
1018 struct ib_qp_attr qp_attr;
1022 qp_attr.qp_state = IB_QPS_RTS;
1023 ret = ib_cm_init_qp_attr(ch->cm_id, &qp_attr, &attr_mask);
1027 qp_attr.max_rd_atomic = 4;
1029 ret = ib_modify_qp(qp, &qp_attr, attr_mask);
1036 * srpt_ch_qp_err() - Set the channel queue pair state to 'error'.
1038 static int srpt_ch_qp_err(struct srpt_rdma_ch *ch)
1040 struct ib_qp_attr qp_attr;
1042 qp_attr.qp_state = IB_QPS_ERR;
1043 return ib_modify_qp(ch->qp, &qp_attr, IB_QP_STATE);
1047 * srpt_unmap_sg_to_ib_sge() - Unmap an IB SGE list.
1049 static void srpt_unmap_sg_to_ib_sge(struct srpt_rdma_ch *ch,
1050 struct srpt_send_ioctx *ioctx)
1052 struct scatterlist *sg;
1053 enum dma_data_direction dir;
1057 BUG_ON(ioctx->n_rdma && !ioctx->rdma_ius);
1059 while (ioctx->n_rdma)
1060 kfree(ioctx->rdma_ius[--ioctx->n_rdma].sge);
1062 kfree(ioctx->rdma_ius);
1063 ioctx->rdma_ius = NULL;
1065 if (ioctx->mapped_sg_count) {
1068 dir = ioctx->cmd.data_direction;
1069 BUG_ON(dir == DMA_NONE);
1070 ib_dma_unmap_sg(ch->sport->sdev->device, sg, ioctx->sg_cnt,
1071 opposite_dma_dir(dir));
1072 ioctx->mapped_sg_count = 0;
1077 * srpt_map_sg_to_ib_sge() - Map an SG list to an IB SGE list.
1079 static int srpt_map_sg_to_ib_sge(struct srpt_rdma_ch *ch,
1080 struct srpt_send_ioctx *ioctx)
1082 struct ib_device *dev = ch->sport->sdev->device;
1084 struct scatterlist *sg, *sg_orig;
1086 enum dma_data_direction dir;
1087 struct rdma_iu *riu;
1088 struct srp_direct_buf *db;
1089 dma_addr_t dma_addr;
1101 dir = cmd->data_direction;
1102 BUG_ON(dir == DMA_NONE);
1104 ioctx->sg = sg = sg_orig = cmd->t_data_sg;
1105 ioctx->sg_cnt = sg_cnt = cmd->t_data_nents;
1107 count = ib_dma_map_sg(ch->sport->sdev->device, sg, sg_cnt,
1108 opposite_dma_dir(dir));
1109 if (unlikely(!count))
1112 ioctx->mapped_sg_count = count;
1114 if (ioctx->rdma_ius && ioctx->n_rdma_ius)
1115 nrdma = ioctx->n_rdma_ius;
1117 nrdma = (count + SRPT_DEF_SG_PER_WQE - 1) / SRPT_DEF_SG_PER_WQE
1120 ioctx->rdma_ius = kzalloc(nrdma * sizeof *riu, GFP_KERNEL);
1121 if (!ioctx->rdma_ius)
1124 ioctx->n_rdma_ius = nrdma;
1128 tsize = cmd->data_length;
1129 dma_len = ib_sg_dma_len(dev, &sg[0]);
1130 riu = ioctx->rdma_ius;
1133 * For each remote desc - calculate the #ib_sge.
1134 * If #ib_sge < SRPT_DEF_SG_PER_WQE per rdma operation then
1135 * each remote desc rdma_iu is required a rdma wr;
1137 * we need to allocate extra rdma_iu to carry extra #ib_sge in
1141 j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
1142 rsize = be32_to_cpu(db->len);
1143 raddr = be64_to_cpu(db->va);
1145 riu->rkey = be32_to_cpu(db->key);
1148 /* calculate how many sge required for this remote_buf */
1149 while (rsize > 0 && tsize > 0) {
1151 if (rsize >= dma_len) {
1160 dma_len = ib_sg_dma_len(
1172 if (rsize > 0 && riu->sge_cnt == SRPT_DEF_SG_PER_WQE) {
1175 kmalloc(riu->sge_cnt * sizeof *riu->sge,
1183 riu->rkey = be32_to_cpu(db->key);
1188 riu->sge = kmalloc(riu->sge_cnt * sizeof *riu->sge,
1195 tsize = cmd->data_length;
1196 riu = ioctx->rdma_ius;
1198 dma_len = ib_sg_dma_len(dev, &sg[0]);
1199 dma_addr = ib_sg_dma_address(dev, &sg[0]);
1201 /* this second loop is really mapped sg_addres to rdma_iu->ib_sge */
1203 j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
1204 rsize = be32_to_cpu(db->len);
1208 while (rsize > 0 && tsize > 0) {
1209 sge->addr = dma_addr;
1210 sge->lkey = ch->sport->sdev->pd->local_dma_lkey;
1212 if (rsize >= dma_len) {
1214 (tsize < dma_len) ? tsize : dma_len;
1222 dma_len = ib_sg_dma_len(
1224 dma_addr = ib_sg_dma_address(
1229 sge->length = (tsize < rsize) ? tsize : rsize;
1237 if (k == riu->sge_cnt && rsize > 0 && tsize > 0) {
1241 } else if (rsize > 0 && tsize > 0)
1249 srpt_unmap_sg_to_ib_sge(ch, ioctx);
1255 * srpt_get_send_ioctx() - Obtain an I/O context for sending to the initiator.
1257 static struct srpt_send_ioctx *srpt_get_send_ioctx(struct srpt_rdma_ch *ch)
1259 struct srpt_send_ioctx *ioctx;
1260 unsigned long flags;
1265 spin_lock_irqsave(&ch->spinlock, flags);
1266 if (!list_empty(&ch->free_list)) {
1267 ioctx = list_first_entry(&ch->free_list,
1268 struct srpt_send_ioctx, free_list);
1269 list_del(&ioctx->free_list);
1271 spin_unlock_irqrestore(&ch->spinlock, flags);
1276 BUG_ON(ioctx->ch != ch);
1277 spin_lock_init(&ioctx->spinlock);
1278 ioctx->state = SRPT_STATE_NEW;
1280 ioctx->rbufs = NULL;
1282 ioctx->n_rdma_ius = 0;
1283 ioctx->rdma_ius = NULL;
1284 ioctx->mapped_sg_count = 0;
1285 init_completion(&ioctx->tx_done);
1286 ioctx->queue_status_only = false;
1288 * transport_init_se_cmd() does not initialize all fields, so do it
1291 memset(&ioctx->cmd, 0, sizeof(ioctx->cmd));
1292 memset(&ioctx->sense_data, 0, sizeof(ioctx->sense_data));
1298 * srpt_abort_cmd() - Abort a SCSI command.
1299 * @ioctx: I/O context associated with the SCSI command.
1300 * @context: Preferred execution context.
1302 static int srpt_abort_cmd(struct srpt_send_ioctx *ioctx)
1304 enum srpt_command_state state;
1305 unsigned long flags;
1310 * If the command is in a state where the target core is waiting for
1311 * the ib_srpt driver, change the state to the next state. Changing
1312 * the state of the command from SRPT_STATE_NEED_DATA to
1313 * SRPT_STATE_DATA_IN ensures that srpt_xmit_response() will call this
1314 * function a second time.
1317 spin_lock_irqsave(&ioctx->spinlock, flags);
1318 state = ioctx->state;
1320 case SRPT_STATE_NEED_DATA:
1321 ioctx->state = SRPT_STATE_DATA_IN;
1323 case SRPT_STATE_DATA_IN:
1324 case SRPT_STATE_CMD_RSP_SENT:
1325 case SRPT_STATE_MGMT_RSP_SENT:
1326 ioctx->state = SRPT_STATE_DONE;
1331 spin_unlock_irqrestore(&ioctx->spinlock, flags);
1333 if (state == SRPT_STATE_DONE) {
1334 struct srpt_rdma_ch *ch = ioctx->ch;
1336 BUG_ON(ch->sess == NULL);
1338 target_put_sess_cmd(&ioctx->cmd);
1342 pr_debug("Aborting cmd with state %d and tag %lld\n", state,
1346 case SRPT_STATE_NEW:
1347 case SRPT_STATE_DATA_IN:
1348 case SRPT_STATE_MGMT:
1350 * Do nothing - defer abort processing until
1351 * srpt_queue_response() is invoked.
1353 WARN_ON(!transport_check_aborted_status(&ioctx->cmd, false));
1355 case SRPT_STATE_NEED_DATA:
1356 /* DMA_TO_DEVICE (write) - RDMA read error. */
1358 /* XXX(hch): this is a horrible layering violation.. */
1359 spin_lock_irqsave(&ioctx->cmd.t_state_lock, flags);
1360 ioctx->cmd.transport_state &= ~CMD_T_ACTIVE;
1361 spin_unlock_irqrestore(&ioctx->cmd.t_state_lock, flags);
1363 case SRPT_STATE_CMD_RSP_SENT:
1365 * SRP_RSP sending failed or the SRP_RSP send completion has
1366 * not been received in time.
1368 srpt_unmap_sg_to_ib_sge(ioctx->ch, ioctx);
1369 target_put_sess_cmd(&ioctx->cmd);
1371 case SRPT_STATE_MGMT_RSP_SENT:
1372 srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
1373 target_put_sess_cmd(&ioctx->cmd);
1376 WARN(1, "Unexpected command state (%d)", state);
1385 * srpt_handle_send_err_comp() - Process an IB_WC_SEND error completion.
1387 static void srpt_handle_send_err_comp(struct srpt_rdma_ch *ch, u64 wr_id)
1389 struct srpt_send_ioctx *ioctx;
1390 enum srpt_command_state state;
1393 atomic_inc(&ch->sq_wr_avail);
1395 index = idx_from_wr_id(wr_id);
1396 ioctx = ch->ioctx_ring[index];
1397 state = srpt_get_cmd_state(ioctx);
1399 WARN_ON(state != SRPT_STATE_CMD_RSP_SENT
1400 && state != SRPT_STATE_MGMT_RSP_SENT
1401 && state != SRPT_STATE_NEED_DATA
1402 && state != SRPT_STATE_DONE);
1404 /* If SRP_RSP sending failed, undo the ch->req_lim change. */
1405 if (state == SRPT_STATE_CMD_RSP_SENT
1406 || state == SRPT_STATE_MGMT_RSP_SENT)
1407 atomic_dec(&ch->req_lim);
1409 srpt_abort_cmd(ioctx);
1413 * srpt_handle_send_comp() - Process an IB send completion notification.
1415 static void srpt_handle_send_comp(struct srpt_rdma_ch *ch,
1416 struct srpt_send_ioctx *ioctx)
1418 enum srpt_command_state state;
1420 atomic_inc(&ch->sq_wr_avail);
1422 state = srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
1424 if (WARN_ON(state != SRPT_STATE_CMD_RSP_SENT
1425 && state != SRPT_STATE_MGMT_RSP_SENT
1426 && state != SRPT_STATE_DONE))
1427 pr_debug("state = %d\n", state);
1429 if (state != SRPT_STATE_DONE) {
1430 srpt_unmap_sg_to_ib_sge(ch, ioctx);
1431 transport_generic_free_cmd(&ioctx->cmd, 0);
1433 pr_err("IB completion has been received too late for"
1434 " wr_id = %u.\n", ioctx->ioctx.index);
1439 * srpt_handle_rdma_comp() - Process an IB RDMA completion notification.
1441 * XXX: what is now target_execute_cmd used to be asynchronous, and unmapping
1442 * the data that has been transferred via IB RDMA had to be postponed until the
1443 * check_stop_free() callback. None of this is necessary anymore and needs to
1446 static void srpt_handle_rdma_comp(struct srpt_rdma_ch *ch,
1447 struct srpt_send_ioctx *ioctx,
1448 enum srpt_opcode opcode)
1450 WARN_ON(ioctx->n_rdma <= 0);
1451 atomic_add(ioctx->n_rdma, &ch->sq_wr_avail);
1453 if (opcode == SRPT_RDMA_READ_LAST) {
1454 if (srpt_test_and_set_cmd_state(ioctx, SRPT_STATE_NEED_DATA,
1455 SRPT_STATE_DATA_IN))
1456 target_execute_cmd(&ioctx->cmd);
1458 pr_err("%s[%d]: wrong state = %d\n", __func__,
1459 __LINE__, srpt_get_cmd_state(ioctx));
1460 } else if (opcode == SRPT_RDMA_ABORT) {
1461 ioctx->rdma_aborted = true;
1463 WARN(true, "unexpected opcode %d\n", opcode);
1468 * srpt_handle_rdma_err_comp() - Process an IB RDMA error completion.
1470 static void srpt_handle_rdma_err_comp(struct srpt_rdma_ch *ch,
1471 struct srpt_send_ioctx *ioctx,
1472 enum srpt_opcode opcode)
1474 enum srpt_command_state state;
1476 state = srpt_get_cmd_state(ioctx);
1478 case SRPT_RDMA_READ_LAST:
1479 if (ioctx->n_rdma <= 0) {
1480 pr_err("Received invalid RDMA read"
1481 " error completion with idx %d\n",
1482 ioctx->ioctx.index);
1485 atomic_add(ioctx->n_rdma, &ch->sq_wr_avail);
1486 if (state == SRPT_STATE_NEED_DATA)
1487 srpt_abort_cmd(ioctx);
1489 pr_err("%s[%d]: wrong state = %d\n",
1490 __func__, __LINE__, state);
1492 case SRPT_RDMA_WRITE_LAST:
1495 pr_err("%s[%d]: opcode = %u\n", __func__, __LINE__, opcode);
1501 * srpt_build_cmd_rsp() - Build an SRP_RSP response.
1502 * @ch: RDMA channel through which the request has been received.
1503 * @ioctx: I/O context associated with the SRP_CMD request. The response will
1504 * be built in the buffer ioctx->buf points at and hence this function will
1505 * overwrite the request data.
1506 * @tag: tag of the request for which this response is being generated.
1507 * @status: value for the STATUS field of the SRP_RSP information unit.
1509 * Returns the size in bytes of the SRP_RSP response.
1511 * An SRP_RSP response contains a SCSI status or service response. See also
1512 * section 6.9 in the SRP r16a document for the format of an SRP_RSP
1513 * response. See also SPC-2 for more information about sense data.
1515 static int srpt_build_cmd_rsp(struct srpt_rdma_ch *ch,
1516 struct srpt_send_ioctx *ioctx, u64 tag,
1519 struct srp_rsp *srp_rsp;
1520 const u8 *sense_data;
1521 int sense_data_len, max_sense_len;
1524 * The lowest bit of all SAM-3 status codes is zero (see also
1525 * paragraph 5.3 in SAM-3).
1527 WARN_ON(status & 1);
1529 srp_rsp = ioctx->ioctx.buf;
1532 sense_data = ioctx->sense_data;
1533 sense_data_len = ioctx->cmd.scsi_sense_length;
1534 WARN_ON(sense_data_len > sizeof(ioctx->sense_data));
1536 memset(srp_rsp, 0, sizeof *srp_rsp);
1537 srp_rsp->opcode = SRP_RSP;
1538 srp_rsp->req_lim_delta =
1539 cpu_to_be32(1 + atomic_xchg(&ch->req_lim_delta, 0));
1541 srp_rsp->status = status;
1543 if (sense_data_len) {
1544 BUILD_BUG_ON(MIN_MAX_RSP_SIZE <= sizeof(*srp_rsp));
1545 max_sense_len = ch->max_ti_iu_len - sizeof(*srp_rsp);
1546 if (sense_data_len > max_sense_len) {
1547 pr_warn("truncated sense data from %d to %d"
1548 " bytes\n", sense_data_len, max_sense_len);
1549 sense_data_len = max_sense_len;
1552 srp_rsp->flags |= SRP_RSP_FLAG_SNSVALID;
1553 srp_rsp->sense_data_len = cpu_to_be32(sense_data_len);
1554 memcpy(srp_rsp + 1, sense_data, sense_data_len);
1557 return sizeof(*srp_rsp) + sense_data_len;
1561 * srpt_build_tskmgmt_rsp() - Build a task management response.
1562 * @ch: RDMA channel through which the request has been received.
1563 * @ioctx: I/O context in which the SRP_RSP response will be built.
1564 * @rsp_code: RSP_CODE that will be stored in the response.
1565 * @tag: Tag of the request for which this response is being generated.
1567 * Returns the size in bytes of the SRP_RSP response.
1569 * An SRP_RSP response contains a SCSI status or service response. See also
1570 * section 6.9 in the SRP r16a document for the format of an SRP_RSP
1573 static int srpt_build_tskmgmt_rsp(struct srpt_rdma_ch *ch,
1574 struct srpt_send_ioctx *ioctx,
1575 u8 rsp_code, u64 tag)
1577 struct srp_rsp *srp_rsp;
1582 resp_len = sizeof(*srp_rsp) + resp_data_len;
1584 srp_rsp = ioctx->ioctx.buf;
1586 memset(srp_rsp, 0, sizeof *srp_rsp);
1588 srp_rsp->opcode = SRP_RSP;
1589 srp_rsp->req_lim_delta =
1590 cpu_to_be32(1 + atomic_xchg(&ch->req_lim_delta, 0));
1593 srp_rsp->flags |= SRP_RSP_FLAG_RSPVALID;
1594 srp_rsp->resp_data_len = cpu_to_be32(resp_data_len);
1595 srp_rsp->data[3] = rsp_code;
1600 #define NO_SUCH_LUN ((uint64_t)-1LL)
1603 * SCSI LUN addressing method. See also SAM-2 and the section about
1606 enum scsi_lun_addr_method {
1607 SCSI_LUN_ADDR_METHOD_PERIPHERAL = 0,
1608 SCSI_LUN_ADDR_METHOD_FLAT = 1,
1609 SCSI_LUN_ADDR_METHOD_LUN = 2,
1610 SCSI_LUN_ADDR_METHOD_EXTENDED_LUN = 3,
1614 * srpt_unpack_lun() - Convert from network LUN to linear LUN.
1616 * Convert an 2-byte, 4-byte, 6-byte or 8-byte LUN structure in network byte
1617 * order (big endian) to a linear LUN. Supports three LUN addressing methods:
1618 * peripheral, flat and logical unit. See also SAM-2, section 4.9.4 (page 40).
1620 static uint64_t srpt_unpack_lun(const uint8_t *lun, int len)
1622 uint64_t res = NO_SUCH_LUN;
1623 int addressing_method;
1625 if (unlikely(len < 2)) {
1626 pr_err("Illegal LUN length %d, expected 2 bytes or more\n",
1633 if ((*((__be64 *)lun) &
1634 cpu_to_be64(0x0000FFFFFFFFFFFFLL)) != 0)
1638 if (*((__be16 *)&lun[2]) != 0)
1642 if (*((__be32 *)&lun[2]) != 0)
1651 addressing_method = (*lun) >> 6; /* highest two bits of byte 0 */
1652 switch (addressing_method) {
1653 case SCSI_LUN_ADDR_METHOD_PERIPHERAL:
1654 case SCSI_LUN_ADDR_METHOD_FLAT:
1655 case SCSI_LUN_ADDR_METHOD_LUN:
1656 res = *(lun + 1) | (((*lun) & 0x3f) << 8);
1659 case SCSI_LUN_ADDR_METHOD_EXTENDED_LUN:
1661 pr_err("Unimplemented LUN addressing method %u\n",
1670 pr_err("Support for multi-level LUNs has not yet been implemented\n");
1674 static int srpt_check_stop_free(struct se_cmd *cmd)
1676 struct srpt_send_ioctx *ioctx = container_of(cmd,
1677 struct srpt_send_ioctx, cmd);
1679 return target_put_sess_cmd(&ioctx->cmd);
1683 * srpt_handle_cmd() - Process SRP_CMD.
1685 static int srpt_handle_cmd(struct srpt_rdma_ch *ch,
1686 struct srpt_recv_ioctx *recv_ioctx,
1687 struct srpt_send_ioctx *send_ioctx)
1690 struct srp_cmd *srp_cmd;
1691 uint64_t unpacked_lun;
1693 enum dma_data_direction dir;
1697 BUG_ON(!send_ioctx);
1699 srp_cmd = recv_ioctx->ioctx.buf;
1700 cmd = &send_ioctx->cmd;
1701 cmd->tag = srp_cmd->tag;
1703 switch (srp_cmd->task_attr) {
1704 case SRP_CMD_SIMPLE_Q:
1705 cmd->sam_task_attr = TCM_SIMPLE_TAG;
1707 case SRP_CMD_ORDERED_Q:
1709 cmd->sam_task_attr = TCM_ORDERED_TAG;
1711 case SRP_CMD_HEAD_OF_Q:
1712 cmd->sam_task_attr = TCM_HEAD_TAG;
1715 cmd->sam_task_attr = TCM_ACA_TAG;
1719 if (srpt_get_desc_tbl(send_ioctx, srp_cmd, &dir, &data_len)) {
1720 pr_err("0x%llx: parsing SRP descriptor table failed.\n",
1722 ret = TCM_INVALID_CDB_FIELD;
1726 unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_cmd->lun,
1727 sizeof(srp_cmd->lun));
1728 rc = target_submit_cmd(cmd, ch->sess, srp_cmd->cdb,
1729 &send_ioctx->sense_data[0], unpacked_lun, data_len,
1730 TCM_SIMPLE_TAG, dir, TARGET_SCF_ACK_KREF);
1732 ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1738 transport_send_check_condition_and_sense(cmd, ret, 0);
1743 * srpt_rx_mgmt_fn_tag() - Process a task management function by tag.
1744 * @ch: RDMA channel of the task management request.
1745 * @fn: Task management function to perform.
1746 * @req_tag: Tag of the SRP task management request.
1747 * @mgmt_ioctx: I/O context of the task management request.
1749 * Returns zero if the target core will process the task management
1750 * request asynchronously.
1752 * Note: It is assumed that the initiator serializes tag-based task management
1755 static int srpt_rx_mgmt_fn_tag(struct srpt_send_ioctx *ioctx, u64 tag)
1757 struct srpt_device *sdev;
1758 struct srpt_rdma_ch *ch;
1759 struct srpt_send_ioctx *target;
1766 sdev = ch->sport->sdev;
1768 spin_lock_irq(&sdev->spinlock);
1769 for (i = 0; i < ch->rq_size; ++i) {
1770 target = ch->ioctx_ring[i];
1771 if (target->cmd.se_lun == ioctx->cmd.se_lun &&
1772 target->cmd.tag == tag &&
1773 srpt_get_cmd_state(target) != SRPT_STATE_DONE) {
1775 /* now let the target core abort &target->cmd; */
1779 spin_unlock_irq(&sdev->spinlock);
1783 static int srp_tmr_to_tcm(int fn)
1786 case SRP_TSK_ABORT_TASK:
1787 return TMR_ABORT_TASK;
1788 case SRP_TSK_ABORT_TASK_SET:
1789 return TMR_ABORT_TASK_SET;
1790 case SRP_TSK_CLEAR_TASK_SET:
1791 return TMR_CLEAR_TASK_SET;
1792 case SRP_TSK_LUN_RESET:
1793 return TMR_LUN_RESET;
1794 case SRP_TSK_CLEAR_ACA:
1795 return TMR_CLEAR_ACA;
1802 * srpt_handle_tsk_mgmt() - Process an SRP_TSK_MGMT information unit.
1804 * Returns 0 if and only if the request will be processed by the target core.
1806 * For more information about SRP_TSK_MGMT information units, see also section
1807 * 6.7 in the SRP r16a document.
1809 static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,
1810 struct srpt_recv_ioctx *recv_ioctx,
1811 struct srpt_send_ioctx *send_ioctx)
1813 struct srp_tsk_mgmt *srp_tsk;
1815 struct se_session *sess = ch->sess;
1816 uint64_t unpacked_lun;
1821 BUG_ON(!send_ioctx);
1823 srp_tsk = recv_ioctx->ioctx.buf;
1824 cmd = &send_ioctx->cmd;
1826 pr_debug("recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld"
1827 " cm_id %p sess %p\n", srp_tsk->tsk_mgmt_func,
1828 srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess);
1830 srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT);
1831 send_ioctx->cmd.tag = srp_tsk->tag;
1832 tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func);
1834 send_ioctx->cmd.se_tmr_req->response =
1835 TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
1838 unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun,
1839 sizeof(srp_tsk->lun));
1841 if (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK) {
1842 rc = srpt_rx_mgmt_fn_tag(send_ioctx, srp_tsk->task_tag);
1844 send_ioctx->cmd.se_tmr_req->response =
1845 TMR_TASK_DOES_NOT_EXIST;
1848 tag = srp_tsk->task_tag;
1850 rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun,
1851 srp_tsk, tcm_tmr, GFP_KERNEL, tag,
1852 TARGET_SCF_ACK_KREF);
1854 send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED;
1859 transport_send_check_condition_and_sense(cmd, 0, 0); // XXX:
1863 * srpt_handle_new_iu() - Process a newly received information unit.
1864 * @ch: RDMA channel through which the information unit has been received.
1865 * @ioctx: SRPT I/O context associated with the information unit.
1867 static void srpt_handle_new_iu(struct srpt_rdma_ch *ch,
1868 struct srpt_recv_ioctx *recv_ioctx,
1869 struct srpt_send_ioctx *send_ioctx)
1871 struct srp_cmd *srp_cmd;
1872 enum rdma_ch_state ch_state;
1875 BUG_ON(!recv_ioctx);
1877 ib_dma_sync_single_for_cpu(ch->sport->sdev->device,
1878 recv_ioctx->ioctx.dma, srp_max_req_size,
1881 ch_state = srpt_get_ch_state(ch);
1882 if (unlikely(ch_state == CH_CONNECTING)) {
1883 list_add_tail(&recv_ioctx->wait_list, &ch->cmd_wait_list);
1887 if (unlikely(ch_state != CH_LIVE))
1890 srp_cmd = recv_ioctx->ioctx.buf;
1891 if (srp_cmd->opcode == SRP_CMD || srp_cmd->opcode == SRP_TSK_MGMT) {
1893 send_ioctx = srpt_get_send_ioctx(ch);
1894 if (unlikely(!send_ioctx)) {
1895 list_add_tail(&recv_ioctx->wait_list,
1896 &ch->cmd_wait_list);
1901 switch (srp_cmd->opcode) {
1903 srpt_handle_cmd(ch, recv_ioctx, send_ioctx);
1906 srpt_handle_tsk_mgmt(ch, recv_ioctx, send_ioctx);
1909 pr_err("Not yet implemented: SRP_I_LOGOUT\n");
1912 pr_debug("received SRP_CRED_RSP\n");
1915 pr_debug("received SRP_AER_RSP\n");
1918 pr_err("Received SRP_RSP\n");
1921 pr_err("received IU with unknown opcode 0x%x\n",
1926 srpt_post_recv(ch->sport->sdev, recv_ioctx);
1931 static void srpt_process_rcv_completion(struct ib_cq *cq,
1932 struct srpt_rdma_ch *ch,
1935 struct srpt_device *sdev = ch->sport->sdev;
1936 struct srpt_recv_ioctx *ioctx;
1939 index = idx_from_wr_id(wc->wr_id);
1940 if (wc->status == IB_WC_SUCCESS) {
1943 req_lim = atomic_dec_return(&ch->req_lim);
1944 if (unlikely(req_lim < 0))
1945 pr_err("req_lim = %d < 0\n", req_lim);
1946 ioctx = sdev->ioctx_ring[index];
1947 srpt_handle_new_iu(ch, ioctx, NULL);
1949 pr_info("receiving failed for idx %u with status %d\n",
1955 * srpt_process_send_completion() - Process an IB send completion.
1957 * Note: Although this has not yet been observed during tests, at least in
1958 * theory it is possible that the srpt_get_send_ioctx() call invoked by
1959 * srpt_handle_new_iu() fails. This is possible because the req_lim_delta
1960 * value in each response is set to one, and it is possible that this response
1961 * makes the initiator send a new request before the send completion for that
1962 * response has been processed. This could e.g. happen if the call to
1963 * srpt_put_send_iotcx() is delayed because of a higher priority interrupt or
1964 * if IB retransmission causes generation of the send completion to be
1965 * delayed. Incoming information units for which srpt_get_send_ioctx() fails
1966 * are queued on cmd_wait_list. The code below processes these delayed
1967 * requests one at a time.
1969 static void srpt_process_send_completion(struct ib_cq *cq,
1970 struct srpt_rdma_ch *ch,
1973 struct srpt_send_ioctx *send_ioctx;
1975 enum srpt_opcode opcode;
1977 index = idx_from_wr_id(wc->wr_id);
1978 opcode = opcode_from_wr_id(wc->wr_id);
1979 send_ioctx = ch->ioctx_ring[index];
1980 if (wc->status == IB_WC_SUCCESS) {
1981 if (opcode == SRPT_SEND)
1982 srpt_handle_send_comp(ch, send_ioctx);
1984 WARN_ON(opcode != SRPT_RDMA_ABORT &&
1985 wc->opcode != IB_WC_RDMA_READ);
1986 srpt_handle_rdma_comp(ch, send_ioctx, opcode);
1989 if (opcode == SRPT_SEND) {
1990 pr_info("sending response for idx %u failed"
1991 " with status %d\n", index, wc->status);
1992 srpt_handle_send_err_comp(ch, wc->wr_id);
1993 } else if (opcode != SRPT_RDMA_MID) {
1994 pr_info("RDMA t %d for idx %u failed with"
1995 " status %d\n", opcode, index, wc->status);
1996 srpt_handle_rdma_err_comp(ch, send_ioctx, opcode);
2000 while (unlikely(opcode == SRPT_SEND
2001 && !list_empty(&ch->cmd_wait_list)
2002 && srpt_get_ch_state(ch) == CH_LIVE
2003 && (send_ioctx = srpt_get_send_ioctx(ch)) != NULL)) {
2004 struct srpt_recv_ioctx *recv_ioctx;
2006 recv_ioctx = list_first_entry(&ch->cmd_wait_list,
2007 struct srpt_recv_ioctx,
2009 list_del(&recv_ioctx->wait_list);
2010 srpt_handle_new_iu(ch, recv_ioctx, send_ioctx);
2014 static void srpt_process_completion(struct ib_cq *cq, struct srpt_rdma_ch *ch)
2016 struct ib_wc *const wc = ch->wc;
2019 WARN_ON(cq != ch->cq);
2021 ib_req_notify_cq(cq, IB_CQ_NEXT_COMP);
2022 while ((n = ib_poll_cq(cq, ARRAY_SIZE(ch->wc), wc)) > 0) {
2023 for (i = 0; i < n; i++) {
2024 if (opcode_from_wr_id(wc[i].wr_id) == SRPT_RECV)
2025 srpt_process_rcv_completion(cq, ch, &wc[i]);
2027 srpt_process_send_completion(cq, ch, &wc[i]);
2033 * srpt_completion() - IB completion queue callback function.
2036 * - It is guaranteed that a completion handler will never be invoked
2037 * concurrently on two different CPUs for the same completion queue. See also
2038 * Documentation/infiniband/core_locking.txt and the implementation of
2039 * handle_edge_irq() in kernel/irq/chip.c.
2040 * - When threaded IRQs are enabled, completion handlers are invoked in thread
2041 * context instead of interrupt context.
2043 static void srpt_completion(struct ib_cq *cq, void *ctx)
2045 struct srpt_rdma_ch *ch = ctx;
2047 wake_up_interruptible(&ch->wait_queue);
2050 static int srpt_compl_thread(void *arg)
2052 struct srpt_rdma_ch *ch;
2054 /* Hibernation / freezing of the SRPT kernel thread is not supported. */
2055 current->flags |= PF_NOFREEZE;
2059 pr_info("Session %s: kernel thread %s (PID %d) started\n",
2060 ch->sess_name, ch->thread->comm, current->pid);
2061 while (!kthread_should_stop()) {
2062 wait_event_interruptible(ch->wait_queue,
2063 (srpt_process_completion(ch->cq, ch),
2064 kthread_should_stop()));
2066 pr_info("Session %s: kernel thread %s (PID %d) stopped\n",
2067 ch->sess_name, ch->thread->comm, current->pid);
2072 * srpt_create_ch_ib() - Create receive and send completion queues.
2074 static int srpt_create_ch_ib(struct srpt_rdma_ch *ch)
2076 struct ib_qp_init_attr *qp_init;
2077 struct srpt_port *sport = ch->sport;
2078 struct srpt_device *sdev = sport->sdev;
2079 u32 srp_sq_size = sport->port_attrib.srp_sq_size;
2080 struct ib_cq_init_attr cq_attr = {};
2083 WARN_ON(ch->rq_size < 1);
2086 qp_init = kzalloc(sizeof *qp_init, GFP_KERNEL);
2091 cq_attr.cqe = ch->rq_size + srp_sq_size;
2092 ch->cq = ib_create_cq(sdev->device, srpt_completion, NULL, ch,
2094 if (IS_ERR(ch->cq)) {
2095 ret = PTR_ERR(ch->cq);
2096 pr_err("failed to create CQ cqe= %d ret= %d\n",
2097 ch->rq_size + srp_sq_size, ret);
2101 qp_init->qp_context = (void *)ch;
2102 qp_init->event_handler
2103 = (void(*)(struct ib_event *, void*))srpt_qp_event;
2104 qp_init->send_cq = ch->cq;
2105 qp_init->recv_cq = ch->cq;
2106 qp_init->srq = sdev->srq;
2107 qp_init->sq_sig_type = IB_SIGNAL_REQ_WR;
2108 qp_init->qp_type = IB_QPT_RC;
2109 qp_init->cap.max_send_wr = srp_sq_size;
2110 qp_init->cap.max_send_sge = SRPT_DEF_SG_PER_WQE;
2112 ch->qp = ib_create_qp(sdev->pd, qp_init);
2113 if (IS_ERR(ch->qp)) {
2114 ret = PTR_ERR(ch->qp);
2115 if (ret == -ENOMEM) {
2117 if (srp_sq_size >= MIN_SRPT_SQ_SIZE) {
2118 ib_destroy_cq(ch->cq);
2122 pr_err("failed to create_qp ret= %d\n", ret);
2123 goto err_destroy_cq;
2126 atomic_set(&ch->sq_wr_avail, qp_init->cap.max_send_wr);
2128 pr_debug("%s: max_cqe= %d max_sge= %d sq_size = %d cm_id= %p\n",
2129 __func__, ch->cq->cqe, qp_init->cap.max_send_sge,
2130 qp_init->cap.max_send_wr, ch->cm_id);
2132 ret = srpt_init_ch_qp(ch, ch->qp);
2134 goto err_destroy_qp;
2136 init_waitqueue_head(&ch->wait_queue);
2138 pr_debug("creating thread for session %s\n", ch->sess_name);
2140 ch->thread = kthread_run(srpt_compl_thread, ch, "ib_srpt_compl");
2141 if (IS_ERR(ch->thread)) {
2142 pr_err("failed to create kernel thread %ld\n",
2143 PTR_ERR(ch->thread));
2145 goto err_destroy_qp;
2153 ib_destroy_qp(ch->qp);
2155 ib_destroy_cq(ch->cq);
2159 static void srpt_destroy_ch_ib(struct srpt_rdma_ch *ch)
2162 kthread_stop(ch->thread);
2164 ib_destroy_qp(ch->qp);
2165 ib_destroy_cq(ch->cq);
2169 * __srpt_close_ch() - Close an RDMA channel by setting the QP error state.
2171 * Reset the QP and make sure all resources associated with the channel will
2172 * be deallocated at an appropriate time.
2174 * Note: The caller must hold ch->sport->sdev->spinlock.
2176 static void __srpt_close_ch(struct srpt_rdma_ch *ch)
2178 enum rdma_ch_state prev_state;
2179 unsigned long flags;
2181 spin_lock_irqsave(&ch->spinlock, flags);
2182 prev_state = ch->state;
2183 switch (prev_state) {
2186 ch->state = CH_DISCONNECTING;
2191 spin_unlock_irqrestore(&ch->spinlock, flags);
2193 switch (prev_state) {
2195 ib_send_cm_rej(ch->cm_id, IB_CM_REJ_NO_RESOURCES, NULL, 0,
2199 if (ib_send_cm_dreq(ch->cm_id, NULL, 0) < 0)
2200 pr_err("sending CM DREQ failed.\n");
2202 case CH_DISCONNECTING:
2211 * srpt_close_ch() - Close an RDMA channel.
2213 static void srpt_close_ch(struct srpt_rdma_ch *ch)
2215 struct srpt_device *sdev;
2217 sdev = ch->sport->sdev;
2218 spin_lock_irq(&sdev->spinlock);
2219 __srpt_close_ch(ch);
2220 spin_unlock_irq(&sdev->spinlock);
2224 * srpt_shutdown_session() - Whether or not a session may be shut down.
2226 static int srpt_shutdown_session(struct se_session *se_sess)
2228 struct srpt_rdma_ch *ch = se_sess->fabric_sess_ptr;
2229 unsigned long flags;
2231 spin_lock_irqsave(&ch->spinlock, flags);
2232 if (ch->in_shutdown) {
2233 spin_unlock_irqrestore(&ch->spinlock, flags);
2237 ch->in_shutdown = true;
2238 target_sess_cmd_list_set_waiting(se_sess);
2239 spin_unlock_irqrestore(&ch->spinlock, flags);
2245 * srpt_drain_channel() - Drain a channel by resetting the IB queue pair.
2246 * @cm_id: Pointer to the CM ID of the channel to be drained.
2248 * Note: Must be called from inside srpt_cm_handler to avoid a race between
2249 * accessing sdev->spinlock and the call to kfree(sdev) in srpt_remove_one()
2250 * (the caller of srpt_cm_handler holds the cm_id spinlock; srpt_remove_one()
2251 * waits until all target sessions for the associated IB device have been
2252 * unregistered and target session registration involves a call to
2253 * ib_destroy_cm_id(), which locks the cm_id spinlock and hence waits until
2254 * this function has finished).
2256 static void srpt_drain_channel(struct ib_cm_id *cm_id)
2258 struct srpt_device *sdev;
2259 struct srpt_rdma_ch *ch;
2261 bool do_reset = false;
2263 WARN_ON_ONCE(irqs_disabled());
2265 sdev = cm_id->context;
2267 spin_lock_irq(&sdev->spinlock);
2268 list_for_each_entry(ch, &sdev->rch_list, list) {
2269 if (ch->cm_id == cm_id) {
2270 do_reset = srpt_test_and_set_ch_state(ch,
2271 CH_CONNECTING, CH_DRAINING) ||
2272 srpt_test_and_set_ch_state(ch,
2273 CH_LIVE, CH_DRAINING) ||
2274 srpt_test_and_set_ch_state(ch,
2275 CH_DISCONNECTING, CH_DRAINING);
2279 spin_unlock_irq(&sdev->spinlock);
2283 srpt_shutdown_session(ch->sess);
2285 ret = srpt_ch_qp_err(ch);
2287 pr_err("Setting queue pair in error state"
2288 " failed: %d\n", ret);
2293 * srpt_find_channel() - Look up an RDMA channel.
2294 * @cm_id: Pointer to the CM ID of the channel to be looked up.
2296 * Return NULL if no matching RDMA channel has been found.
2298 static struct srpt_rdma_ch *srpt_find_channel(struct srpt_device *sdev,
2299 struct ib_cm_id *cm_id)
2301 struct srpt_rdma_ch *ch;
2304 WARN_ON_ONCE(irqs_disabled());
2308 spin_lock_irq(&sdev->spinlock);
2309 list_for_each_entry(ch, &sdev->rch_list, list) {
2310 if (ch->cm_id == cm_id) {
2315 spin_unlock_irq(&sdev->spinlock);
2317 return found ? ch : NULL;
2321 * srpt_release_channel() - Release channel resources.
2323 * Schedules the actual release because:
2324 * - Calling the ib_destroy_cm_id() call from inside an IB CM callback would
2325 * trigger a deadlock.
2326 * - It is not safe to call TCM transport_* functions from interrupt context.
2328 static void srpt_release_channel(struct srpt_rdma_ch *ch)
2330 schedule_work(&ch->release_work);
2333 static void srpt_release_channel_work(struct work_struct *w)
2335 struct srpt_rdma_ch *ch;
2336 struct srpt_device *sdev;
2337 struct se_session *se_sess;
2339 ch = container_of(w, struct srpt_rdma_ch, release_work);
2340 pr_debug("ch = %p; ch->sess = %p; release_done = %p\n", ch, ch->sess,
2343 sdev = ch->sport->sdev;
2349 target_wait_for_sess_cmds(se_sess);
2351 transport_deregister_session_configfs(se_sess);
2352 transport_deregister_session(se_sess);
2355 ib_destroy_cm_id(ch->cm_id);
2357 srpt_destroy_ch_ib(ch);
2359 srpt_free_ioctx_ring((struct srpt_ioctx **)ch->ioctx_ring,
2360 ch->sport->sdev, ch->rq_size,
2361 ch->rsp_size, DMA_TO_DEVICE);
2363 spin_lock_irq(&sdev->spinlock);
2364 list_del(&ch->list);
2365 spin_unlock_irq(&sdev->spinlock);
2367 if (ch->release_done)
2368 complete(ch->release_done);
2370 wake_up(&sdev->ch_releaseQ);
2375 static struct srpt_node_acl *__srpt_lookup_acl(struct srpt_port *sport,
2378 struct srpt_node_acl *nacl;
2380 list_for_each_entry(nacl, &sport->port_acl_list, list)
2381 if (memcmp(nacl->i_port_id, i_port_id,
2382 sizeof(nacl->i_port_id)) == 0)
2388 static struct srpt_node_acl *srpt_lookup_acl(struct srpt_port *sport,
2391 struct srpt_node_acl *nacl;
2393 spin_lock_irq(&sport->port_acl_lock);
2394 nacl = __srpt_lookup_acl(sport, i_port_id);
2395 spin_unlock_irq(&sport->port_acl_lock);
2401 * srpt_cm_req_recv() - Process the event IB_CM_REQ_RECEIVED.
2403 * Ownership of the cm_id is transferred to the target session if this
2404 * functions returns zero. Otherwise the caller remains the owner of cm_id.
2406 static int srpt_cm_req_recv(struct ib_cm_id *cm_id,
2407 struct ib_cm_req_event_param *param,
2410 struct srpt_device *sdev = cm_id->context;
2411 struct srpt_port *sport = &sdev->port[param->port - 1];
2412 struct srp_login_req *req;
2413 struct srp_login_rsp *rsp;
2414 struct srp_login_rej *rej;
2415 struct ib_cm_rep_param *rep_param;
2416 struct srpt_rdma_ch *ch, *tmp_ch;
2417 struct srpt_node_acl *nacl;
2422 WARN_ON_ONCE(irqs_disabled());
2424 if (WARN_ON(!sdev || !private_data))
2427 req = (struct srp_login_req *)private_data;
2429 it_iu_len = be32_to_cpu(req->req_it_iu_len);
2431 pr_info("Received SRP_LOGIN_REQ with i_port_id 0x%llx:0x%llx,"
2432 " t_port_id 0x%llx:0x%llx and it_iu_len %d on port %d"
2433 " (guid=0x%llx:0x%llx)\n",
2434 be64_to_cpu(*(__be64 *)&req->initiator_port_id[0]),
2435 be64_to_cpu(*(__be64 *)&req->initiator_port_id[8]),
2436 be64_to_cpu(*(__be64 *)&req->target_port_id[0]),
2437 be64_to_cpu(*(__be64 *)&req->target_port_id[8]),
2440 be64_to_cpu(*(__be64 *)&sdev->port[param->port - 1].gid.raw[0]),
2441 be64_to_cpu(*(__be64 *)&sdev->port[param->port - 1].gid.raw[8]));
2443 rsp = kzalloc(sizeof *rsp, GFP_KERNEL);
2444 rej = kzalloc(sizeof *rej, GFP_KERNEL);
2445 rep_param = kzalloc(sizeof *rep_param, GFP_KERNEL);
2447 if (!rsp || !rej || !rep_param) {
2452 if (it_iu_len > srp_max_req_size || it_iu_len < 64) {
2453 rej->reason = cpu_to_be32(
2454 SRP_LOGIN_REJ_REQ_IT_IU_LENGTH_TOO_LARGE);
2456 pr_err("rejected SRP_LOGIN_REQ because its"
2457 " length (%d bytes) is out of range (%d .. %d)\n",
2458 it_iu_len, 64, srp_max_req_size);
2462 if (!sport->enabled) {
2463 rej->reason = cpu_to_be32(
2464 SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2466 pr_err("rejected SRP_LOGIN_REQ because the target port"
2467 " has not yet been enabled\n");
2471 if ((req->req_flags & SRP_MTCH_ACTION) == SRP_MULTICHAN_SINGLE) {
2472 rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_NO_CHAN;
2474 spin_lock_irq(&sdev->spinlock);
2476 list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list) {
2477 if (!memcmp(ch->i_port_id, req->initiator_port_id, 16)
2478 && !memcmp(ch->t_port_id, req->target_port_id, 16)
2479 && param->port == ch->sport->port
2480 && param->listen_id == ch->sport->sdev->cm_id
2482 enum rdma_ch_state ch_state;
2484 ch_state = srpt_get_ch_state(ch);
2485 if (ch_state != CH_CONNECTING
2486 && ch_state != CH_LIVE)
2489 /* found an existing channel */
2490 pr_debug("Found existing channel %s"
2491 " cm_id= %p state= %d\n",
2492 ch->sess_name, ch->cm_id, ch_state);
2494 __srpt_close_ch(ch);
2497 SRP_LOGIN_RSP_MULTICHAN_TERMINATED;
2501 spin_unlock_irq(&sdev->spinlock);
2504 rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_MAINTAINED;
2506 if (*(__be64 *)req->target_port_id != cpu_to_be64(srpt_service_guid)
2507 || *(__be64 *)(req->target_port_id + 8) !=
2508 cpu_to_be64(srpt_service_guid)) {
2509 rej->reason = cpu_to_be32(
2510 SRP_LOGIN_REJ_UNABLE_ASSOCIATE_CHANNEL);
2512 pr_err("rejected SRP_LOGIN_REQ because it"
2513 " has an invalid target port identifier.\n");
2517 ch = kzalloc(sizeof *ch, GFP_KERNEL);
2519 rej->reason = cpu_to_be32(
2520 SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2521 pr_err("rejected SRP_LOGIN_REQ because no memory.\n");
2526 INIT_WORK(&ch->release_work, srpt_release_channel_work);
2527 memcpy(ch->i_port_id, req->initiator_port_id, 16);
2528 memcpy(ch->t_port_id, req->target_port_id, 16);
2529 ch->sport = &sdev->port[param->port - 1];
2532 * Avoid QUEUE_FULL conditions by limiting the number of buffers used
2533 * for the SRP protocol to the command queue size.
2535 ch->rq_size = SRPT_RQ_SIZE;
2536 spin_lock_init(&ch->spinlock);
2537 ch->state = CH_CONNECTING;
2538 INIT_LIST_HEAD(&ch->cmd_wait_list);
2539 ch->rsp_size = ch->sport->port_attrib.srp_max_rsp_size;
2541 ch->ioctx_ring = (struct srpt_send_ioctx **)
2542 srpt_alloc_ioctx_ring(ch->sport->sdev, ch->rq_size,
2543 sizeof(*ch->ioctx_ring[0]),
2544 ch->rsp_size, DMA_TO_DEVICE);
2545 if (!ch->ioctx_ring)
2548 INIT_LIST_HEAD(&ch->free_list);
2549 for (i = 0; i < ch->rq_size; i++) {
2550 ch->ioctx_ring[i]->ch = ch;
2551 list_add_tail(&ch->ioctx_ring[i]->free_list, &ch->free_list);
2554 ret = srpt_create_ch_ib(ch);
2556 rej->reason = cpu_to_be32(
2557 SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2558 pr_err("rejected SRP_LOGIN_REQ because creating"
2559 " a new RDMA channel failed.\n");
2563 ret = srpt_ch_qp_rtr(ch, ch->qp);
2565 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2566 pr_err("rejected SRP_LOGIN_REQ because enabling"
2567 " RTR failed (error code = %d)\n", ret);
2571 * Use the initator port identifier as the session name.
2573 snprintf(ch->sess_name, sizeof(ch->sess_name), "0x%016llx%016llx",
2574 be64_to_cpu(*(__be64 *)ch->i_port_id),
2575 be64_to_cpu(*(__be64 *)(ch->i_port_id + 8)));
2577 pr_debug("registering session %s\n", ch->sess_name);
2579 nacl = srpt_lookup_acl(sport, ch->i_port_id);
2581 pr_info("Rejected login because no ACL has been"
2582 " configured yet for initiator %s.\n", ch->sess_name);
2583 rej->reason = cpu_to_be32(
2584 SRP_LOGIN_REJ_CHANNEL_LIMIT_REACHED);
2588 ch->sess = transport_init_session(TARGET_PROT_NORMAL);
2589 if (IS_ERR(ch->sess)) {
2590 rej->reason = cpu_to_be32(
2591 SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2592 pr_debug("Failed to create session\n");
2593 goto deregister_session;
2595 ch->sess->se_node_acl = &nacl->nacl;
2596 transport_register_session(&sport->port_tpg_1, &nacl->nacl, ch->sess, ch);
2598 pr_debug("Establish connection sess=%p name=%s cm_id=%p\n", ch->sess,
2599 ch->sess_name, ch->cm_id);
2601 /* create srp_login_response */
2602 rsp->opcode = SRP_LOGIN_RSP;
2603 rsp->tag = req->tag;
2604 rsp->max_it_iu_len = req->req_it_iu_len;
2605 rsp->max_ti_iu_len = req->req_it_iu_len;
2606 ch->max_ti_iu_len = it_iu_len;
2607 rsp->buf_fmt = cpu_to_be16(SRP_BUF_FORMAT_DIRECT
2608 | SRP_BUF_FORMAT_INDIRECT);
2609 rsp->req_lim_delta = cpu_to_be32(ch->rq_size);
2610 atomic_set(&ch->req_lim, ch->rq_size);
2611 atomic_set(&ch->req_lim_delta, 0);
2613 /* create cm reply */
2614 rep_param->qp_num = ch->qp->qp_num;
2615 rep_param->private_data = (void *)rsp;
2616 rep_param->private_data_len = sizeof *rsp;
2617 rep_param->rnr_retry_count = 7;
2618 rep_param->flow_control = 1;
2619 rep_param->failover_accepted = 0;
2621 rep_param->responder_resources = 4;
2622 rep_param->initiator_depth = 4;
2624 ret = ib_send_cm_rep(cm_id, rep_param);
2626 pr_err("sending SRP_LOGIN_REQ response failed"
2627 " (error code = %d)\n", ret);
2628 goto release_channel;
2631 spin_lock_irq(&sdev->spinlock);
2632 list_add_tail(&ch->list, &sdev->rch_list);
2633 spin_unlock_irq(&sdev->spinlock);
2638 srpt_set_ch_state(ch, CH_RELEASING);
2639 transport_deregister_session_configfs(ch->sess);
2642 transport_deregister_session(ch->sess);
2646 srpt_destroy_ch_ib(ch);
2649 srpt_free_ioctx_ring((struct srpt_ioctx **)ch->ioctx_ring,
2650 ch->sport->sdev, ch->rq_size,
2651 ch->rsp_size, DMA_TO_DEVICE);
2656 rej->opcode = SRP_LOGIN_REJ;
2657 rej->tag = req->tag;
2658 rej->buf_fmt = cpu_to_be16(SRP_BUF_FORMAT_DIRECT
2659 | SRP_BUF_FORMAT_INDIRECT);
2661 ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0,
2662 (void *)rej, sizeof *rej);
2672 static void srpt_cm_rej_recv(struct ib_cm_id *cm_id)
2674 pr_info("Received IB REJ for cm_id %p.\n", cm_id);
2675 srpt_drain_channel(cm_id);
2679 * srpt_cm_rtu_recv() - Process an IB_CM_RTU_RECEIVED or USER_ESTABLISHED event.
2681 * An IB_CM_RTU_RECEIVED message indicates that the connection is established
2682 * and that the recipient may begin transmitting (RTU = ready to use).
2684 static void srpt_cm_rtu_recv(struct ib_cm_id *cm_id)
2686 struct srpt_rdma_ch *ch;
2689 ch = srpt_find_channel(cm_id->context, cm_id);
2692 if (srpt_test_and_set_ch_state(ch, CH_CONNECTING, CH_LIVE)) {
2693 struct srpt_recv_ioctx *ioctx, *ioctx_tmp;
2695 ret = srpt_ch_qp_rts(ch, ch->qp);
2697 list_for_each_entry_safe(ioctx, ioctx_tmp, &ch->cmd_wait_list,
2699 list_del(&ioctx->wait_list);
2700 srpt_handle_new_iu(ch, ioctx, NULL);
2707 static void srpt_cm_timewait_exit(struct ib_cm_id *cm_id)
2709 pr_info("Received IB TimeWait exit for cm_id %p.\n", cm_id);
2710 srpt_drain_channel(cm_id);
2713 static void srpt_cm_rep_error(struct ib_cm_id *cm_id)
2715 pr_info("Received IB REP error for cm_id %p.\n", cm_id);
2716 srpt_drain_channel(cm_id);
2720 * srpt_cm_dreq_recv() - Process reception of a DREQ message.
2722 static void srpt_cm_dreq_recv(struct ib_cm_id *cm_id)
2724 struct srpt_rdma_ch *ch;
2725 unsigned long flags;
2726 bool send_drep = false;
2728 ch = srpt_find_channel(cm_id->context, cm_id);
2731 pr_debug("cm_id= %p ch->state= %d\n", cm_id, srpt_get_ch_state(ch));
2733 spin_lock_irqsave(&ch->spinlock, flags);
2734 switch (ch->state) {
2738 ch->state = CH_DISCONNECTING;
2740 case CH_DISCONNECTING:
2743 WARN(true, "unexpected channel state %d\n", ch->state);
2746 spin_unlock_irqrestore(&ch->spinlock, flags);
2749 if (ib_send_cm_drep(ch->cm_id, NULL, 0) < 0)
2750 pr_err("Sending IB DREP failed.\n");
2751 pr_info("Received DREQ and sent DREP for session %s.\n",
2757 * srpt_cm_drep_recv() - Process reception of a DREP message.
2759 static void srpt_cm_drep_recv(struct ib_cm_id *cm_id)
2761 pr_info("Received InfiniBand DREP message for cm_id %p.\n", cm_id);
2762 srpt_drain_channel(cm_id);
2766 * srpt_cm_handler() - IB connection manager callback function.
2768 * A non-zero return value will cause the caller destroy the CM ID.
2770 * Note: srpt_cm_handler() must only return a non-zero value when transferring
2771 * ownership of the cm_id to a channel by srpt_cm_req_recv() failed. Returning
2772 * a non-zero value in any other case will trigger a race with the
2773 * ib_destroy_cm_id() call in srpt_release_channel().
2775 static int srpt_cm_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event)
2780 switch (event->event) {
2781 case IB_CM_REQ_RECEIVED:
2782 ret = srpt_cm_req_recv(cm_id, &event->param.req_rcvd,
2783 event->private_data);
2785 case IB_CM_REJ_RECEIVED:
2786 srpt_cm_rej_recv(cm_id);
2788 case IB_CM_RTU_RECEIVED:
2789 case IB_CM_USER_ESTABLISHED:
2790 srpt_cm_rtu_recv(cm_id);
2792 case IB_CM_DREQ_RECEIVED:
2793 srpt_cm_dreq_recv(cm_id);
2795 case IB_CM_DREP_RECEIVED:
2796 srpt_cm_drep_recv(cm_id);
2798 case IB_CM_TIMEWAIT_EXIT:
2799 srpt_cm_timewait_exit(cm_id);
2801 case IB_CM_REP_ERROR:
2802 srpt_cm_rep_error(cm_id);
2804 case IB_CM_DREQ_ERROR:
2805 pr_info("Received IB DREQ ERROR event.\n");
2807 case IB_CM_MRA_RECEIVED:
2808 pr_info("Received IB MRA event\n");
2811 pr_err("received unrecognized IB CM event %d\n", event->event);
2819 * srpt_perform_rdmas() - Perform IB RDMA.
2821 * Returns zero upon success or a negative number upon failure.
2823 static int srpt_perform_rdmas(struct srpt_rdma_ch *ch,
2824 struct srpt_send_ioctx *ioctx)
2826 struct ib_rdma_wr wr;
2827 struct ib_send_wr *bad_wr;
2828 struct rdma_iu *riu;
2832 enum dma_data_direction dir;
2833 const int n_rdma = ioctx->n_rdma;
2835 dir = ioctx->cmd.data_direction;
2836 if (dir == DMA_TO_DEVICE) {
2839 sq_wr_avail = atomic_sub_return(n_rdma, &ch->sq_wr_avail);
2840 if (sq_wr_avail < 0) {
2841 pr_warn("IB send queue full (needed %d)\n",
2847 ioctx->rdma_aborted = false;
2849 riu = ioctx->rdma_ius;
2850 memset(&wr, 0, sizeof wr);
2852 for (i = 0; i < n_rdma; ++i, ++riu) {
2853 if (dir == DMA_FROM_DEVICE) {
2854 wr.wr.opcode = IB_WR_RDMA_WRITE;
2855 wr.wr.wr_id = encode_wr_id(i == n_rdma - 1 ?
2856 SRPT_RDMA_WRITE_LAST :
2858 ioctx->ioctx.index);
2860 wr.wr.opcode = IB_WR_RDMA_READ;
2861 wr.wr.wr_id = encode_wr_id(i == n_rdma - 1 ?
2862 SRPT_RDMA_READ_LAST :
2864 ioctx->ioctx.index);
2867 wr.remote_addr = riu->raddr;
2868 wr.rkey = riu->rkey;
2869 wr.wr.num_sge = riu->sge_cnt;
2870 wr.wr.sg_list = riu->sge;
2872 /* only get completion event for the last rdma write */
2873 if (i == (n_rdma - 1) && dir == DMA_TO_DEVICE)
2874 wr.wr.send_flags = IB_SEND_SIGNALED;
2876 ret = ib_post_send(ch->qp, &wr.wr, &bad_wr);
2882 pr_err("%s[%d]: ib_post_send() returned %d for %d/%d\n",
2883 __func__, __LINE__, ret, i, n_rdma);
2886 wr.wr.wr_id = encode_wr_id(SRPT_RDMA_ABORT, ioctx->ioctx.index);
2887 wr.wr.send_flags = IB_SEND_SIGNALED;
2888 while (ch->state == CH_LIVE &&
2889 ib_post_send(ch->qp, &wr.wr, &bad_wr) != 0) {
2890 pr_info("Trying to abort failed RDMA transfer [%d]\n",
2891 ioctx->ioctx.index);
2894 while (ch->state != CH_RELEASING && !ioctx->rdma_aborted) {
2895 pr_info("Waiting until RDMA abort finished [%d]\n",
2896 ioctx->ioctx.index);
2901 if (unlikely(dir == DMA_TO_DEVICE && ret < 0))
2902 atomic_add(n_rdma, &ch->sq_wr_avail);
2907 * srpt_xfer_data() - Start data transfer from initiator to target.
2909 static int srpt_xfer_data(struct srpt_rdma_ch *ch,
2910 struct srpt_send_ioctx *ioctx)
2914 ret = srpt_map_sg_to_ib_sge(ch, ioctx);
2916 pr_err("%s[%d] ret=%d\n", __func__, __LINE__, ret);
2920 ret = srpt_perform_rdmas(ch, ioctx);
2922 if (ret == -EAGAIN || ret == -ENOMEM)
2923 pr_info("%s[%d] queue full -- ret=%d\n",
2924 __func__, __LINE__, ret);
2926 pr_err("%s[%d] fatal error -- ret=%d\n",
2927 __func__, __LINE__, ret);
2934 srpt_unmap_sg_to_ib_sge(ch, ioctx);
2938 static int srpt_write_pending_status(struct se_cmd *se_cmd)
2940 struct srpt_send_ioctx *ioctx;
2942 ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
2943 return srpt_get_cmd_state(ioctx) == SRPT_STATE_NEED_DATA;
2947 * srpt_write_pending() - Start data transfer from initiator to target (write).
2949 static int srpt_write_pending(struct se_cmd *se_cmd)
2951 struct srpt_rdma_ch *ch;
2952 struct srpt_send_ioctx *ioctx;
2953 enum srpt_command_state new_state;
2954 enum rdma_ch_state ch_state;
2957 ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
2959 new_state = srpt_set_cmd_state(ioctx, SRPT_STATE_NEED_DATA);
2960 WARN_ON(new_state == SRPT_STATE_DONE);
2965 ch_state = srpt_get_ch_state(ch);
2968 WARN(true, "unexpected channel state %d\n", ch_state);
2973 case CH_DISCONNECTING:
2976 pr_debug("cmd with tag %lld: channel disconnecting\n",
2978 srpt_set_cmd_state(ioctx, SRPT_STATE_DATA_IN);
2982 ret = srpt_xfer_data(ch, ioctx);
2988 static u8 tcm_to_srp_tsk_mgmt_status(const int tcm_mgmt_status)
2990 switch (tcm_mgmt_status) {
2991 case TMR_FUNCTION_COMPLETE:
2992 return SRP_TSK_MGMT_SUCCESS;
2993 case TMR_FUNCTION_REJECTED:
2994 return SRP_TSK_MGMT_FUNC_NOT_SUPP;
2996 return SRP_TSK_MGMT_FAILED;
3000 * srpt_queue_response() - Transmits the response to a SCSI command.
3002 * Callback function called by the TCM core. Must not block since it can be
3003 * invoked on the context of the IB completion handler.
3005 static void srpt_queue_response(struct se_cmd *cmd)
3007 struct srpt_rdma_ch *ch;
3008 struct srpt_send_ioctx *ioctx;
3009 enum srpt_command_state state;
3010 unsigned long flags;
3012 enum dma_data_direction dir;
3016 ioctx = container_of(cmd, struct srpt_send_ioctx, cmd);
3020 spin_lock_irqsave(&ioctx->spinlock, flags);
3021 state = ioctx->state;
3023 case SRPT_STATE_NEW:
3024 case SRPT_STATE_DATA_IN:
3025 ioctx->state = SRPT_STATE_CMD_RSP_SENT;
3027 case SRPT_STATE_MGMT:
3028 ioctx->state = SRPT_STATE_MGMT_RSP_SENT;
3031 WARN(true, "ch %p; cmd %d: unexpected command state %d\n",
3032 ch, ioctx->ioctx.index, ioctx->state);
3035 spin_unlock_irqrestore(&ioctx->spinlock, flags);
3037 if (unlikely(transport_check_aborted_status(&ioctx->cmd, false)
3038 || WARN_ON_ONCE(state == SRPT_STATE_CMD_RSP_SENT))) {
3039 atomic_inc(&ch->req_lim_delta);
3040 srpt_abort_cmd(ioctx);
3044 dir = ioctx->cmd.data_direction;
3046 /* For read commands, transfer the data to the initiator. */
3047 if (dir == DMA_FROM_DEVICE && ioctx->cmd.data_length &&
3048 !ioctx->queue_status_only) {
3049 ret = srpt_xfer_data(ch, ioctx);
3051 pr_err("xfer_data failed for tag %llu\n",
3057 if (state != SRPT_STATE_MGMT)
3058 resp_len = srpt_build_cmd_rsp(ch, ioctx, ioctx->cmd.tag,
3062 = tcm_to_srp_tsk_mgmt_status(cmd->se_tmr_req->response);
3063 resp_len = srpt_build_tskmgmt_rsp(ch, ioctx, srp_tm_status,
3066 ret = srpt_post_send(ch, ioctx, resp_len);
3068 pr_err("sending cmd response failed for tag %llu\n",
3070 srpt_unmap_sg_to_ib_sge(ch, ioctx);
3071 srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
3072 target_put_sess_cmd(&ioctx->cmd);
3076 static int srpt_queue_data_in(struct se_cmd *cmd)
3078 srpt_queue_response(cmd);
3082 static void srpt_queue_tm_rsp(struct se_cmd *cmd)
3084 srpt_queue_response(cmd);
3087 static void srpt_aborted_task(struct se_cmd *cmd)
3089 struct srpt_send_ioctx *ioctx = container_of(cmd,
3090 struct srpt_send_ioctx, cmd);
3092 srpt_unmap_sg_to_ib_sge(ioctx->ch, ioctx);
3095 static int srpt_queue_status(struct se_cmd *cmd)
3097 struct srpt_send_ioctx *ioctx;
3099 ioctx = container_of(cmd, struct srpt_send_ioctx, cmd);
3100 BUG_ON(ioctx->sense_data != cmd->sense_buffer);
3101 if (cmd->se_cmd_flags &
3102 (SCF_TRANSPORT_TASK_SENSE | SCF_EMULATED_TASK_SENSE))
3103 WARN_ON(cmd->scsi_status != SAM_STAT_CHECK_CONDITION);
3104 ioctx->queue_status_only = true;
3105 srpt_queue_response(cmd);
3109 static void srpt_refresh_port_work(struct work_struct *work)
3111 struct srpt_port *sport = container_of(work, struct srpt_port, work);
3113 srpt_refresh_port(sport);
3116 static int srpt_ch_list_empty(struct srpt_device *sdev)
3120 spin_lock_irq(&sdev->spinlock);
3121 res = list_empty(&sdev->rch_list);
3122 spin_unlock_irq(&sdev->spinlock);
3128 * srpt_release_sdev() - Free the channel resources associated with a target.
3130 static int srpt_release_sdev(struct srpt_device *sdev)
3132 struct srpt_rdma_ch *ch, *tmp_ch;
3135 WARN_ON_ONCE(irqs_disabled());
3139 spin_lock_irq(&sdev->spinlock);
3140 list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list)
3141 __srpt_close_ch(ch);
3142 spin_unlock_irq(&sdev->spinlock);
3144 res = wait_event_interruptible(sdev->ch_releaseQ,
3145 srpt_ch_list_empty(sdev));
3147 pr_err("%s: interrupted.\n", __func__);
3152 static struct srpt_port *__srpt_lookup_port(const char *name)
3154 struct ib_device *dev;
3155 struct srpt_device *sdev;
3156 struct srpt_port *sport;
3159 list_for_each_entry(sdev, &srpt_dev_list, list) {
3164 for (i = 0; i < dev->phys_port_cnt; i++) {
3165 sport = &sdev->port[i];
3167 if (!strcmp(sport->port_guid, name))
3175 static struct srpt_port *srpt_lookup_port(const char *name)
3177 struct srpt_port *sport;
3179 spin_lock(&srpt_dev_lock);
3180 sport = __srpt_lookup_port(name);
3181 spin_unlock(&srpt_dev_lock);
3187 * srpt_add_one() - Infiniband device addition callback function.
3189 static void srpt_add_one(struct ib_device *device)
3191 struct srpt_device *sdev;
3192 struct srpt_port *sport;
3193 struct ib_srq_init_attr srq_attr;
3196 pr_debug("device = %p, device->dma_ops = %p\n", device,
3199 sdev = kzalloc(sizeof *sdev, GFP_KERNEL);
3203 sdev->device = device;
3204 INIT_LIST_HEAD(&sdev->rch_list);
3205 init_waitqueue_head(&sdev->ch_releaseQ);
3206 spin_lock_init(&sdev->spinlock);
3208 if (ib_query_device(device, &sdev->dev_attr))
3211 sdev->pd = ib_alloc_pd(device);
3212 if (IS_ERR(sdev->pd))
3215 sdev->srq_size = min(srpt_srq_size, sdev->dev_attr.max_srq_wr);
3217 srq_attr.event_handler = srpt_srq_event;
3218 srq_attr.srq_context = (void *)sdev;
3219 srq_attr.attr.max_wr = sdev->srq_size;
3220 srq_attr.attr.max_sge = 1;
3221 srq_attr.attr.srq_limit = 0;
3222 srq_attr.srq_type = IB_SRQT_BASIC;
3224 sdev->srq = ib_create_srq(sdev->pd, &srq_attr);
3225 if (IS_ERR(sdev->srq))
3228 pr_debug("%s: create SRQ #wr= %d max_allow=%d dev= %s\n",
3229 __func__, sdev->srq_size, sdev->dev_attr.max_srq_wr,
3232 if (!srpt_service_guid)
3233 srpt_service_guid = be64_to_cpu(device->node_guid);
3235 sdev->cm_id = ib_create_cm_id(device, srpt_cm_handler, sdev);
3236 if (IS_ERR(sdev->cm_id))
3239 /* print out target login information */
3240 pr_debug("Target login info: id_ext=%016llx,ioc_guid=%016llx,"
3241 "pkey=ffff,service_id=%016llx\n", srpt_service_guid,
3242 srpt_service_guid, srpt_service_guid);
3245 * We do not have a consistent service_id (ie. also id_ext of target_id)
3246 * to identify this target. We currently use the guid of the first HCA
3247 * in the system as service_id; therefore, the target_id will change
3248 * if this HCA is gone bad and replaced by different HCA
3250 if (ib_cm_listen(sdev->cm_id, cpu_to_be64(srpt_service_guid), 0))
3253 INIT_IB_EVENT_HANDLER(&sdev->event_handler, sdev->device,
3254 srpt_event_handler);
3255 if (ib_register_event_handler(&sdev->event_handler))
3258 sdev->ioctx_ring = (struct srpt_recv_ioctx **)
3259 srpt_alloc_ioctx_ring(sdev, sdev->srq_size,
3260 sizeof(*sdev->ioctx_ring[0]),
3261 srp_max_req_size, DMA_FROM_DEVICE);
3262 if (!sdev->ioctx_ring)
3265 for (i = 0; i < sdev->srq_size; ++i)
3266 srpt_post_recv(sdev, sdev->ioctx_ring[i]);
3268 WARN_ON(sdev->device->phys_port_cnt > ARRAY_SIZE(sdev->port));
3270 for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
3271 sport = &sdev->port[i - 1];
3274 sport->port_attrib.srp_max_rdma_size = DEFAULT_MAX_RDMA_SIZE;
3275 sport->port_attrib.srp_max_rsp_size = DEFAULT_MAX_RSP_SIZE;
3276 sport->port_attrib.srp_sq_size = DEF_SRPT_SQ_SIZE;
3277 INIT_WORK(&sport->work, srpt_refresh_port_work);
3278 INIT_LIST_HEAD(&sport->port_acl_list);
3279 spin_lock_init(&sport->port_acl_lock);
3281 if (srpt_refresh_port(sport)) {
3282 pr_err("MAD registration failed for %s-%d.\n",
3283 srpt_sdev_name(sdev), i);
3286 snprintf(sport->port_guid, sizeof(sport->port_guid),
3288 be64_to_cpu(sport->gid.global.subnet_prefix),
3289 be64_to_cpu(sport->gid.global.interface_id));
3292 spin_lock(&srpt_dev_lock);
3293 list_add_tail(&sdev->list, &srpt_dev_list);
3294 spin_unlock(&srpt_dev_lock);
3297 ib_set_client_data(device, &srpt_client, sdev);
3298 pr_debug("added %s.\n", device->name);
3302 srpt_free_ioctx_ring((struct srpt_ioctx **)sdev->ioctx_ring, sdev,
3303 sdev->srq_size, srp_max_req_size,
3306 ib_unregister_event_handler(&sdev->event_handler);
3308 ib_destroy_cm_id(sdev->cm_id);
3310 ib_destroy_srq(sdev->srq);
3312 ib_dealloc_pd(sdev->pd);
3317 pr_info("%s(%s) failed.\n", __func__, device->name);
3322 * srpt_remove_one() - InfiniBand device removal callback function.
3324 static void srpt_remove_one(struct ib_device *device, void *client_data)
3326 struct srpt_device *sdev = client_data;
3330 pr_info("%s(%s): nothing to do.\n", __func__, device->name);
3334 srpt_unregister_mad_agent(sdev);
3336 ib_unregister_event_handler(&sdev->event_handler);
3338 /* Cancel any work queued by the just unregistered IB event handler. */
3339 for (i = 0; i < sdev->device->phys_port_cnt; i++)
3340 cancel_work_sync(&sdev->port[i].work);
3342 ib_destroy_cm_id(sdev->cm_id);
3345 * Unregistering a target must happen after destroying sdev->cm_id
3346 * such that no new SRP_LOGIN_REQ information units can arrive while
3347 * destroying the target.
3349 spin_lock(&srpt_dev_lock);
3350 list_del(&sdev->list);
3351 spin_unlock(&srpt_dev_lock);
3352 srpt_release_sdev(sdev);
3354 ib_destroy_srq(sdev->srq);
3355 ib_dealloc_pd(sdev->pd);
3357 srpt_free_ioctx_ring((struct srpt_ioctx **)sdev->ioctx_ring, sdev,
3358 sdev->srq_size, srp_max_req_size, DMA_FROM_DEVICE);
3359 sdev->ioctx_ring = NULL;
3363 static struct ib_client srpt_client = {
3365 .add = srpt_add_one,
3366 .remove = srpt_remove_one
3369 static int srpt_check_true(struct se_portal_group *se_tpg)
3374 static int srpt_check_false(struct se_portal_group *se_tpg)
3379 static char *srpt_get_fabric_name(void)
3384 static char *srpt_get_fabric_wwn(struct se_portal_group *tpg)
3386 struct srpt_port *sport = container_of(tpg, struct srpt_port, port_tpg_1);
3388 return sport->port_guid;
3391 static u16 srpt_get_tag(struct se_portal_group *tpg)
3396 static u32 srpt_tpg_get_inst_index(struct se_portal_group *se_tpg)
3401 static void srpt_release_cmd(struct se_cmd *se_cmd)
3403 struct srpt_send_ioctx *ioctx = container_of(se_cmd,
3404 struct srpt_send_ioctx, cmd);
3405 struct srpt_rdma_ch *ch = ioctx->ch;
3406 unsigned long flags;
3408 WARN_ON(ioctx->state != SRPT_STATE_DONE);
3409 WARN_ON(ioctx->mapped_sg_count != 0);
3411 if (ioctx->n_rbuf > 1) {
3412 kfree(ioctx->rbufs);
3413 ioctx->rbufs = NULL;
3417 spin_lock_irqsave(&ch->spinlock, flags);
3418 list_add(&ioctx->free_list, &ch->free_list);
3419 spin_unlock_irqrestore(&ch->spinlock, flags);
3423 * srpt_close_session() - Forcibly close a session.
3425 * Callback function invoked by the TCM core to clean up sessions associated
3426 * with a node ACL when the user invokes
3427 * rmdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id
3429 static void srpt_close_session(struct se_session *se_sess)
3431 DECLARE_COMPLETION_ONSTACK(release_done);
3432 struct srpt_rdma_ch *ch;
3433 struct srpt_device *sdev;
3436 ch = se_sess->fabric_sess_ptr;
3437 WARN_ON(ch->sess != se_sess);
3439 pr_debug("ch %p state %d\n", ch, srpt_get_ch_state(ch));
3441 sdev = ch->sport->sdev;
3442 spin_lock_irq(&sdev->spinlock);
3443 BUG_ON(ch->release_done);
3444 ch->release_done = &release_done;
3445 __srpt_close_ch(ch);
3446 spin_unlock_irq(&sdev->spinlock);
3448 res = wait_for_completion_timeout(&release_done, 60 * HZ);
3453 * srpt_sess_get_index() - Return the value of scsiAttIntrPortIndex (SCSI-MIB).
3455 * A quote from RFC 4455 (SCSI-MIB) about this MIB object:
3456 * This object represents an arbitrary integer used to uniquely identify a
3457 * particular attached remote initiator port to a particular SCSI target port
3458 * within a particular SCSI target device within a particular SCSI instance.
3460 static u32 srpt_sess_get_index(struct se_session *se_sess)
3465 static void srpt_set_default_node_attrs(struct se_node_acl *nacl)
3469 /* Note: only used from inside debug printk's by the TCM core. */
3470 static int srpt_get_tcm_cmd_state(struct se_cmd *se_cmd)
3472 struct srpt_send_ioctx *ioctx;
3474 ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
3475 return srpt_get_cmd_state(ioctx);
3479 * srpt_parse_i_port_id() - Parse an initiator port ID.
3480 * @name: ASCII representation of a 128-bit initiator port ID.
3481 * @i_port_id: Binary 128-bit port ID.
3483 static int srpt_parse_i_port_id(u8 i_port_id[16], const char *name)
3486 unsigned len, count, leading_zero_bytes;
3490 if (strncasecmp(p, "0x", 2) == 0)
3496 count = min(len / 2, 16U);
3497 leading_zero_bytes = 16 - count;
3498 memset(i_port_id, 0, leading_zero_bytes);
3499 rc = hex2bin(i_port_id + leading_zero_bytes, p, count);
3501 pr_debug("hex2bin failed for srpt_parse_i_port_id: %d\n", rc);
3508 * configfs callback function invoked for
3509 * mkdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id
3511 static int srpt_init_nodeacl(struct se_node_acl *se_nacl, const char *name)
3513 struct srpt_port *sport =
3514 container_of(se_nacl->se_tpg, struct srpt_port, port_tpg_1);
3515 struct srpt_node_acl *nacl =
3516 container_of(se_nacl, struct srpt_node_acl, nacl);
3519 if (srpt_parse_i_port_id(i_port_id, name) < 0) {
3520 pr_err("invalid initiator port ID %s\n", name);
3524 memcpy(&nacl->i_port_id[0], &i_port_id[0], 16);
3525 nacl->sport = sport;
3527 spin_lock_irq(&sport->port_acl_lock);
3528 list_add_tail(&nacl->list, &sport->port_acl_list);
3529 spin_unlock_irq(&sport->port_acl_lock);
3535 * configfs callback function invoked for
3536 * rmdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id
3538 static void srpt_cleanup_nodeacl(struct se_node_acl *se_nacl)
3540 struct srpt_node_acl *nacl =
3541 container_of(se_nacl, struct srpt_node_acl, nacl);
3542 struct srpt_port *sport = nacl->sport;
3544 spin_lock_irq(&sport->port_acl_lock);
3545 list_del(&nacl->list);
3546 spin_unlock_irq(&sport->port_acl_lock);
3549 static ssize_t srpt_tpg_attrib_show_srp_max_rdma_size(
3550 struct se_portal_group *se_tpg,
3553 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3555 return sprintf(page, "%u\n", sport->port_attrib.srp_max_rdma_size);
3558 static ssize_t srpt_tpg_attrib_store_srp_max_rdma_size(
3559 struct se_portal_group *se_tpg,
3563 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3567 ret = kstrtoul(page, 0, &val);
3569 pr_err("kstrtoul() failed with ret: %d\n", ret);
3572 if (val > MAX_SRPT_RDMA_SIZE) {
3573 pr_err("val: %lu exceeds MAX_SRPT_RDMA_SIZE: %d\n", val,
3574 MAX_SRPT_RDMA_SIZE);
3577 if (val < DEFAULT_MAX_RDMA_SIZE) {
3578 pr_err("val: %lu smaller than DEFAULT_MAX_RDMA_SIZE: %d\n",
3579 val, DEFAULT_MAX_RDMA_SIZE);
3582 sport->port_attrib.srp_max_rdma_size = val;
3587 TF_TPG_ATTRIB_ATTR(srpt, srp_max_rdma_size, S_IRUGO | S_IWUSR);
3589 static ssize_t srpt_tpg_attrib_show_srp_max_rsp_size(
3590 struct se_portal_group *se_tpg,
3593 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3595 return sprintf(page, "%u\n", sport->port_attrib.srp_max_rsp_size);
3598 static ssize_t srpt_tpg_attrib_store_srp_max_rsp_size(
3599 struct se_portal_group *se_tpg,
3603 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3607 ret = kstrtoul(page, 0, &val);
3609 pr_err("kstrtoul() failed with ret: %d\n", ret);
3612 if (val > MAX_SRPT_RSP_SIZE) {
3613 pr_err("val: %lu exceeds MAX_SRPT_RSP_SIZE: %d\n", val,
3617 if (val < MIN_MAX_RSP_SIZE) {
3618 pr_err("val: %lu smaller than MIN_MAX_RSP_SIZE: %d\n", val,
3622 sport->port_attrib.srp_max_rsp_size = val;
3627 TF_TPG_ATTRIB_ATTR(srpt, srp_max_rsp_size, S_IRUGO | S_IWUSR);
3629 static ssize_t srpt_tpg_attrib_show_srp_sq_size(
3630 struct se_portal_group *se_tpg,
3633 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3635 return sprintf(page, "%u\n", sport->port_attrib.srp_sq_size);
3638 static ssize_t srpt_tpg_attrib_store_srp_sq_size(
3639 struct se_portal_group *se_tpg,
3643 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3647 ret = kstrtoul(page, 0, &val);
3649 pr_err("kstrtoul() failed with ret: %d\n", ret);
3652 if (val > MAX_SRPT_SRQ_SIZE) {
3653 pr_err("val: %lu exceeds MAX_SRPT_SRQ_SIZE: %d\n", val,
3657 if (val < MIN_SRPT_SRQ_SIZE) {
3658 pr_err("val: %lu smaller than MIN_SRPT_SRQ_SIZE: %d\n", val,
3662 sport->port_attrib.srp_sq_size = val;
3667 TF_TPG_ATTRIB_ATTR(srpt, srp_sq_size, S_IRUGO | S_IWUSR);
3669 static struct configfs_attribute *srpt_tpg_attrib_attrs[] = {
3670 &srpt_tpg_attrib_srp_max_rdma_size.attr,
3671 &srpt_tpg_attrib_srp_max_rsp_size.attr,
3672 &srpt_tpg_attrib_srp_sq_size.attr,
3676 static ssize_t srpt_tpg_show_enable(
3677 struct se_portal_group *se_tpg,
3680 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3682 return snprintf(page, PAGE_SIZE, "%d\n", (sport->enabled) ? 1: 0);
3685 static ssize_t srpt_tpg_store_enable(
3686 struct se_portal_group *se_tpg,
3690 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3694 ret = kstrtoul(page, 0, &tmp);
3696 pr_err("Unable to extract srpt_tpg_store_enable\n");
3700 if ((tmp != 0) && (tmp != 1)) {
3701 pr_err("Illegal value for srpt_tpg_store_enable: %lu\n", tmp);
3705 sport->enabled = true;
3707 sport->enabled = false;
3712 TF_TPG_BASE_ATTR(srpt, enable, S_IRUGO | S_IWUSR);
3714 static struct configfs_attribute *srpt_tpg_attrs[] = {
3715 &srpt_tpg_enable.attr,
3720 * configfs callback invoked for
3721 * mkdir /sys/kernel/config/target/$driver/$port/$tpg
3723 static struct se_portal_group *srpt_make_tpg(struct se_wwn *wwn,
3724 struct config_group *group,
3727 struct srpt_port *sport = container_of(wwn, struct srpt_port, port_wwn);
3730 /* Initialize sport->port_wwn and sport->port_tpg_1 */
3731 res = core_tpg_register(&sport->port_wwn, &sport->port_tpg_1, SCSI_PROTOCOL_SRP);
3733 return ERR_PTR(res);
3735 return &sport->port_tpg_1;
3739 * configfs callback invoked for
3740 * rmdir /sys/kernel/config/target/$driver/$port/$tpg
3742 static void srpt_drop_tpg(struct se_portal_group *tpg)
3744 struct srpt_port *sport = container_of(tpg,
3745 struct srpt_port, port_tpg_1);
3747 sport->enabled = false;
3748 core_tpg_deregister(&sport->port_tpg_1);
3752 * configfs callback invoked for
3753 * mkdir /sys/kernel/config/target/$driver/$port
3755 static struct se_wwn *srpt_make_tport(struct target_fabric_configfs *tf,
3756 struct config_group *group,
3759 struct srpt_port *sport;
3762 sport = srpt_lookup_port(name);
3763 pr_debug("make_tport(%s)\n", name);
3768 return &sport->port_wwn;
3771 return ERR_PTR(ret);
3775 * configfs callback invoked for
3776 * rmdir /sys/kernel/config/target/$driver/$port
3778 static void srpt_drop_tport(struct se_wwn *wwn)
3780 struct srpt_port *sport = container_of(wwn, struct srpt_port, port_wwn);
3782 pr_debug("drop_tport(%s\n", config_item_name(&sport->port_wwn.wwn_group.cg_item));
3785 static ssize_t srpt_wwn_show_attr_version(struct target_fabric_configfs *tf,
3788 return scnprintf(buf, PAGE_SIZE, "%s\n", DRV_VERSION);
3791 TF_WWN_ATTR_RO(srpt, version);
3793 static struct configfs_attribute *srpt_wwn_attrs[] = {
3794 &srpt_wwn_version.attr,
3798 static const struct target_core_fabric_ops srpt_template = {
3799 .module = THIS_MODULE,
3801 .node_acl_size = sizeof(struct srpt_node_acl),
3802 .get_fabric_name = srpt_get_fabric_name,
3803 .tpg_get_wwn = srpt_get_fabric_wwn,
3804 .tpg_get_tag = srpt_get_tag,
3805 .tpg_check_demo_mode = srpt_check_false,
3806 .tpg_check_demo_mode_cache = srpt_check_true,
3807 .tpg_check_demo_mode_write_protect = srpt_check_true,
3808 .tpg_check_prod_mode_write_protect = srpt_check_false,
3809 .tpg_get_inst_index = srpt_tpg_get_inst_index,
3810 .release_cmd = srpt_release_cmd,
3811 .check_stop_free = srpt_check_stop_free,
3812 .shutdown_session = srpt_shutdown_session,
3813 .close_session = srpt_close_session,
3814 .sess_get_index = srpt_sess_get_index,
3815 .sess_get_initiator_sid = NULL,
3816 .write_pending = srpt_write_pending,
3817 .write_pending_status = srpt_write_pending_status,
3818 .set_default_node_attributes = srpt_set_default_node_attrs,
3819 .get_cmd_state = srpt_get_tcm_cmd_state,
3820 .queue_data_in = srpt_queue_data_in,
3821 .queue_status = srpt_queue_status,
3822 .queue_tm_rsp = srpt_queue_tm_rsp,
3823 .aborted_task = srpt_aborted_task,
3825 * Setup function pointers for generic logic in
3826 * target_core_fabric_configfs.c
3828 .fabric_make_wwn = srpt_make_tport,
3829 .fabric_drop_wwn = srpt_drop_tport,
3830 .fabric_make_tpg = srpt_make_tpg,
3831 .fabric_drop_tpg = srpt_drop_tpg,
3832 .fabric_init_nodeacl = srpt_init_nodeacl,
3833 .fabric_cleanup_nodeacl = srpt_cleanup_nodeacl,
3835 .tfc_wwn_attrs = srpt_wwn_attrs,
3836 .tfc_tpg_base_attrs = srpt_tpg_attrs,
3837 .tfc_tpg_attrib_attrs = srpt_tpg_attrib_attrs,
3841 * srpt_init_module() - Kernel module initialization.
3843 * Note: Since ib_register_client() registers callback functions, and since at
3844 * least one of these callback functions (srpt_add_one()) calls target core
3845 * functions, this driver must be registered with the target core before
3846 * ib_register_client() is called.
3848 static int __init srpt_init_module(void)
3853 if (srp_max_req_size < MIN_MAX_REQ_SIZE) {
3854 pr_err("invalid value %d for kernel module parameter"
3855 " srp_max_req_size -- must be at least %d.\n",
3856 srp_max_req_size, MIN_MAX_REQ_SIZE);
3860 if (srpt_srq_size < MIN_SRPT_SRQ_SIZE
3861 || srpt_srq_size > MAX_SRPT_SRQ_SIZE) {
3862 pr_err("invalid value %d for kernel module parameter"
3863 " srpt_srq_size -- must be in the range [%d..%d].\n",
3864 srpt_srq_size, MIN_SRPT_SRQ_SIZE, MAX_SRPT_SRQ_SIZE);
3868 ret = target_register_template(&srpt_template);
3872 ret = ib_register_client(&srpt_client);
3874 pr_err("couldn't register IB client\n");
3875 goto out_unregister_target;
3880 out_unregister_target:
3881 target_unregister_template(&srpt_template);
3886 static void __exit srpt_cleanup_module(void)
3888 ib_unregister_client(&srpt_client);
3889 target_unregister_template(&srpt_template);
3892 module_init(srpt_init_module);
3893 module_exit(srpt_cleanup_module);