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/target_core_base.h>
47 #include <target/target_core_fabric.h>
50 /* Name of this kernel module. */
51 #define DRV_NAME "ib_srpt"
52 #define DRV_VERSION "2.0.0"
53 #define DRV_RELDATE "2011-02-14"
55 #define SRPT_ID_STRING "Linux SRP target"
58 #define pr_fmt(fmt) DRV_NAME " " fmt
60 MODULE_AUTHOR("Vu Pham and Bart Van Assche");
61 MODULE_DESCRIPTION("InfiniBand SCSI RDMA Protocol target "
62 "v" DRV_VERSION " (" DRV_RELDATE ")");
63 MODULE_LICENSE("Dual BSD/GPL");
69 static u64 srpt_service_guid;
70 static DEFINE_SPINLOCK(srpt_dev_lock); /* Protects srpt_dev_list. */
71 static LIST_HEAD(srpt_dev_list); /* List of srpt_device structures. */
73 static unsigned srp_max_req_size = DEFAULT_MAX_REQ_SIZE;
74 module_param(srp_max_req_size, int, 0444);
75 MODULE_PARM_DESC(srp_max_req_size,
76 "Maximum size of SRP request messages in bytes.");
78 static int srpt_srq_size = DEFAULT_SRPT_SRQ_SIZE;
79 module_param(srpt_srq_size, int, 0444);
80 MODULE_PARM_DESC(srpt_srq_size,
81 "Shared receive queue (SRQ) size.");
83 static int srpt_get_u64_x(char *buffer, struct kernel_param *kp)
85 return sprintf(buffer, "0x%016llx", *(u64 *)kp->arg);
87 module_param_call(srpt_service_guid, NULL, srpt_get_u64_x, &srpt_service_guid,
89 MODULE_PARM_DESC(srpt_service_guid,
90 "Using this value for ioc_guid, id_ext, and cm_listen_id"
91 " instead of using the node_guid of the first HCA.");
93 static struct ib_client srpt_client;
94 static void srpt_release_channel(struct srpt_rdma_ch *ch);
95 static int srpt_queue_status(struct se_cmd *cmd);
98 * opposite_dma_dir() - Swap DMA_TO_DEVICE and DMA_FROM_DEVICE.
101 enum dma_data_direction opposite_dma_dir(enum dma_data_direction dir)
104 case DMA_TO_DEVICE: return DMA_FROM_DEVICE;
105 case DMA_FROM_DEVICE: return DMA_TO_DEVICE;
111 * srpt_sdev_name() - Return the name associated with the HCA.
113 * Examples are ib0, ib1, ...
115 static inline const char *srpt_sdev_name(struct srpt_device *sdev)
117 return sdev->device->name;
120 static enum rdma_ch_state srpt_get_ch_state(struct srpt_rdma_ch *ch)
123 enum rdma_ch_state state;
125 spin_lock_irqsave(&ch->spinlock, flags);
127 spin_unlock_irqrestore(&ch->spinlock, flags);
131 static enum rdma_ch_state
132 srpt_set_ch_state(struct srpt_rdma_ch *ch, enum rdma_ch_state new_state)
135 enum rdma_ch_state prev;
137 spin_lock_irqsave(&ch->spinlock, flags);
139 ch->state = new_state;
140 spin_unlock_irqrestore(&ch->spinlock, flags);
145 * srpt_test_and_set_ch_state() - Test and set the channel state.
147 * Returns true if and only if the channel state has been set to the new state.
150 srpt_test_and_set_ch_state(struct srpt_rdma_ch *ch, enum rdma_ch_state old,
151 enum rdma_ch_state new)
154 enum rdma_ch_state prev;
156 spin_lock_irqsave(&ch->spinlock, flags);
160 spin_unlock_irqrestore(&ch->spinlock, flags);
165 * srpt_event_handler() - Asynchronous IB event callback function.
167 * Callback function called by the InfiniBand core when an asynchronous IB
168 * event occurs. This callback may occur in interrupt context. See also
169 * section 11.5.2, Set Asynchronous Event Handler in the InfiniBand
170 * Architecture Specification.
172 static void srpt_event_handler(struct ib_event_handler *handler,
173 struct ib_event *event)
175 struct srpt_device *sdev;
176 struct srpt_port *sport;
178 sdev = ib_get_client_data(event->device, &srpt_client);
179 if (!sdev || sdev->device != event->device)
182 pr_debug("ASYNC event= %d on device= %s\n", event->event,
183 srpt_sdev_name(sdev));
185 switch (event->event) {
186 case IB_EVENT_PORT_ERR:
187 if (event->element.port_num <= sdev->device->phys_port_cnt) {
188 sport = &sdev->port[event->element.port_num - 1];
193 case IB_EVENT_PORT_ACTIVE:
194 case IB_EVENT_LID_CHANGE:
195 case IB_EVENT_PKEY_CHANGE:
196 case IB_EVENT_SM_CHANGE:
197 case IB_EVENT_CLIENT_REREGISTER:
198 case IB_EVENT_GID_CHANGE:
199 /* Refresh port data asynchronously. */
200 if (event->element.port_num <= sdev->device->phys_port_cnt) {
201 sport = &sdev->port[event->element.port_num - 1];
202 if (!sport->lid && !sport->sm_lid)
203 schedule_work(&sport->work);
207 pr_err("received unrecognized IB event %d\n",
214 * srpt_srq_event() - SRQ event callback function.
216 static void srpt_srq_event(struct ib_event *event, void *ctx)
218 pr_info("SRQ event %d\n", event->event);
222 * srpt_qp_event() - QP event callback function.
224 static void srpt_qp_event(struct ib_event *event, struct srpt_rdma_ch *ch)
226 pr_debug("QP event %d on cm_id=%p sess_name=%s state=%d\n",
227 event->event, ch->cm_id, ch->sess_name, srpt_get_ch_state(ch));
229 switch (event->event) {
230 case IB_EVENT_COMM_EST:
231 ib_cm_notify(ch->cm_id, event->event);
233 case IB_EVENT_QP_LAST_WQE_REACHED:
234 if (srpt_test_and_set_ch_state(ch, CH_DRAINING,
236 srpt_release_channel(ch);
238 pr_debug("%s: state %d - ignored LAST_WQE.\n",
239 ch->sess_name, srpt_get_ch_state(ch));
242 pr_err("received unrecognized IB QP event %d\n", event->event);
248 * srpt_set_ioc() - Helper function for initializing an IOUnitInfo structure.
250 * @slot: one-based slot number.
251 * @value: four-bit value.
253 * Copies the lowest four bits of value in element slot of the array of four
254 * bit elements called c_list (controller list). The index slot is one-based.
256 static void srpt_set_ioc(u8 *c_list, u32 slot, u8 value)
263 tmp = c_list[id] & 0xf;
264 c_list[id] = (value << 4) | tmp;
266 tmp = c_list[id] & 0xf0;
267 c_list[id] = (value & 0xf) | tmp;
272 * srpt_get_class_port_info() - Copy ClassPortInfo to a management datagram.
274 * See also section 16.3.3.1 ClassPortInfo in the InfiniBand Architecture
277 static void srpt_get_class_port_info(struct ib_dm_mad *mad)
279 struct ib_class_port_info *cif;
281 cif = (struct ib_class_port_info *)mad->data;
282 memset(cif, 0, sizeof *cif);
283 cif->base_version = 1;
284 cif->class_version = 1;
285 cif->resp_time_value = 20;
287 mad->mad_hdr.status = 0;
291 * srpt_get_iou() - Write IOUnitInfo to a management datagram.
293 * See also section 16.3.3.3 IOUnitInfo in the InfiniBand Architecture
294 * Specification. See also section B.7, table B.6 in the SRP r16a document.
296 static void srpt_get_iou(struct ib_dm_mad *mad)
298 struct ib_dm_iou_info *ioui;
302 ioui = (struct ib_dm_iou_info *)mad->data;
303 ioui->change_id = cpu_to_be16(1);
304 ioui->max_controllers = 16;
306 /* set present for slot 1 and empty for the rest */
307 srpt_set_ioc(ioui->controller_list, 1, 1);
308 for (i = 1, slot = 2; i < 16; i++, slot++)
309 srpt_set_ioc(ioui->controller_list, slot, 0);
311 mad->mad_hdr.status = 0;
315 * srpt_get_ioc() - Write IOControllerprofile to a management datagram.
317 * See also section 16.3.3.4 IOControllerProfile in the InfiniBand
318 * Architecture Specification. See also section B.7, table B.7 in the SRP
321 static void srpt_get_ioc(struct srpt_port *sport, u32 slot,
322 struct ib_dm_mad *mad)
324 struct srpt_device *sdev = sport->sdev;
325 struct ib_dm_ioc_profile *iocp;
327 iocp = (struct ib_dm_ioc_profile *)mad->data;
329 if (!slot || slot > 16) {
331 = cpu_to_be16(DM_MAD_STATUS_INVALID_FIELD);
337 = cpu_to_be16(DM_MAD_STATUS_NO_IOC);
341 memset(iocp, 0, sizeof *iocp);
342 strcpy(iocp->id_string, SRPT_ID_STRING);
343 iocp->guid = cpu_to_be64(srpt_service_guid);
344 iocp->vendor_id = cpu_to_be32(sdev->dev_attr.vendor_id);
345 iocp->device_id = cpu_to_be32(sdev->dev_attr.vendor_part_id);
346 iocp->device_version = cpu_to_be16(sdev->dev_attr.hw_ver);
347 iocp->subsys_vendor_id = cpu_to_be32(sdev->dev_attr.vendor_id);
348 iocp->subsys_device_id = 0x0;
349 iocp->io_class = cpu_to_be16(SRP_REV16A_IB_IO_CLASS);
350 iocp->io_subclass = cpu_to_be16(SRP_IO_SUBCLASS);
351 iocp->protocol = cpu_to_be16(SRP_PROTOCOL);
352 iocp->protocol_version = cpu_to_be16(SRP_PROTOCOL_VERSION);
353 iocp->send_queue_depth = cpu_to_be16(sdev->srq_size);
354 iocp->rdma_read_depth = 4;
355 iocp->send_size = cpu_to_be32(srp_max_req_size);
356 iocp->rdma_size = cpu_to_be32(min(sport->port_attrib.srp_max_rdma_size,
358 iocp->num_svc_entries = 1;
359 iocp->op_cap_mask = SRP_SEND_TO_IOC | SRP_SEND_FROM_IOC |
360 SRP_RDMA_READ_FROM_IOC | SRP_RDMA_WRITE_FROM_IOC;
362 mad->mad_hdr.status = 0;
366 * srpt_get_svc_entries() - Write ServiceEntries to a management datagram.
368 * See also section 16.3.3.5 ServiceEntries in the InfiniBand Architecture
369 * Specification. See also section B.7, table B.8 in the SRP r16a document.
371 static void srpt_get_svc_entries(u64 ioc_guid,
372 u16 slot, u8 hi, u8 lo, struct ib_dm_mad *mad)
374 struct ib_dm_svc_entries *svc_entries;
378 if (!slot || slot > 16) {
380 = cpu_to_be16(DM_MAD_STATUS_INVALID_FIELD);
384 if (slot > 2 || lo > hi || hi > 1) {
386 = cpu_to_be16(DM_MAD_STATUS_NO_IOC);
390 svc_entries = (struct ib_dm_svc_entries *)mad->data;
391 memset(svc_entries, 0, sizeof *svc_entries);
392 svc_entries->service_entries[0].id = cpu_to_be64(ioc_guid);
393 snprintf(svc_entries->service_entries[0].name,
394 sizeof(svc_entries->service_entries[0].name),
396 SRP_SERVICE_NAME_PREFIX,
399 mad->mad_hdr.status = 0;
403 * srpt_mgmt_method_get() - Process a received management datagram.
404 * @sp: source port through which the MAD has been received.
405 * @rq_mad: received MAD.
406 * @rsp_mad: response MAD.
408 static void srpt_mgmt_method_get(struct srpt_port *sp, struct ib_mad *rq_mad,
409 struct ib_dm_mad *rsp_mad)
415 attr_id = be16_to_cpu(rq_mad->mad_hdr.attr_id);
417 case DM_ATTR_CLASS_PORT_INFO:
418 srpt_get_class_port_info(rsp_mad);
420 case DM_ATTR_IOU_INFO:
421 srpt_get_iou(rsp_mad);
423 case DM_ATTR_IOC_PROFILE:
424 slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
425 srpt_get_ioc(sp, slot, rsp_mad);
427 case DM_ATTR_SVC_ENTRIES:
428 slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
429 hi = (u8) ((slot >> 8) & 0xff);
430 lo = (u8) (slot & 0xff);
431 slot = (u16) ((slot >> 16) & 0xffff);
432 srpt_get_svc_entries(srpt_service_guid,
433 slot, hi, lo, rsp_mad);
436 rsp_mad->mad_hdr.status =
437 cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
443 * srpt_mad_send_handler() - Post MAD-send callback function.
445 static void srpt_mad_send_handler(struct ib_mad_agent *mad_agent,
446 struct ib_mad_send_wc *mad_wc)
448 ib_destroy_ah(mad_wc->send_buf->ah);
449 ib_free_send_mad(mad_wc->send_buf);
453 * srpt_mad_recv_handler() - MAD reception callback function.
455 static void srpt_mad_recv_handler(struct ib_mad_agent *mad_agent,
456 struct ib_mad_recv_wc *mad_wc)
458 struct srpt_port *sport = (struct srpt_port *)mad_agent->context;
460 struct ib_mad_send_buf *rsp;
461 struct ib_dm_mad *dm_mad;
463 if (!mad_wc || !mad_wc->recv_buf.mad)
466 ah = ib_create_ah_from_wc(mad_agent->qp->pd, mad_wc->wc,
467 mad_wc->recv_buf.grh, mad_agent->port_num);
471 BUILD_BUG_ON(offsetof(struct ib_dm_mad, data) != IB_MGMT_DEVICE_HDR);
473 rsp = ib_create_send_mad(mad_agent, mad_wc->wc->src_qp,
474 mad_wc->wc->pkey_index, 0,
475 IB_MGMT_DEVICE_HDR, IB_MGMT_DEVICE_DATA,
477 IB_MGMT_BASE_VERSION);
484 memcpy(dm_mad, mad_wc->recv_buf.mad, sizeof *dm_mad);
485 dm_mad->mad_hdr.method = IB_MGMT_METHOD_GET_RESP;
486 dm_mad->mad_hdr.status = 0;
488 switch (mad_wc->recv_buf.mad->mad_hdr.method) {
489 case IB_MGMT_METHOD_GET:
490 srpt_mgmt_method_get(sport, mad_wc->recv_buf.mad, dm_mad);
492 case IB_MGMT_METHOD_SET:
493 dm_mad->mad_hdr.status =
494 cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
497 dm_mad->mad_hdr.status =
498 cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD);
502 if (!ib_post_send_mad(rsp, NULL)) {
503 ib_free_recv_mad(mad_wc);
504 /* will destroy_ah & free_send_mad in send completion */
508 ib_free_send_mad(rsp);
513 ib_free_recv_mad(mad_wc);
517 * srpt_refresh_port() - Configure a HCA port.
519 * Enable InfiniBand management datagram processing, update the cached sm_lid,
520 * lid and gid values, and register a callback function for processing MADs
521 * on the specified port.
523 * Note: It is safe to call this function more than once for the same port.
525 static int srpt_refresh_port(struct srpt_port *sport)
527 struct ib_mad_reg_req reg_req;
528 struct ib_port_modify port_modify;
529 struct ib_port_attr port_attr;
532 memset(&port_modify, 0, sizeof port_modify);
533 port_modify.set_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP;
534 port_modify.clr_port_cap_mask = 0;
536 ret = ib_modify_port(sport->sdev->device, sport->port, 0, &port_modify);
540 ret = ib_query_port(sport->sdev->device, sport->port, &port_attr);
544 sport->sm_lid = port_attr.sm_lid;
545 sport->lid = port_attr.lid;
547 ret = ib_query_gid(sport->sdev->device, sport->port, 0, &sport->gid,
552 if (!sport->mad_agent) {
553 memset(®_req, 0, sizeof reg_req);
554 reg_req.mgmt_class = IB_MGMT_CLASS_DEVICE_MGMT;
555 reg_req.mgmt_class_version = IB_MGMT_BASE_VERSION;
556 set_bit(IB_MGMT_METHOD_GET, reg_req.method_mask);
557 set_bit(IB_MGMT_METHOD_SET, reg_req.method_mask);
559 sport->mad_agent = ib_register_mad_agent(sport->sdev->device,
563 srpt_mad_send_handler,
564 srpt_mad_recv_handler,
566 if (IS_ERR(sport->mad_agent)) {
567 ret = PTR_ERR(sport->mad_agent);
568 sport->mad_agent = NULL;
577 port_modify.set_port_cap_mask = 0;
578 port_modify.clr_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP;
579 ib_modify_port(sport->sdev->device, sport->port, 0, &port_modify);
587 * srpt_unregister_mad_agent() - Unregister MAD callback functions.
589 * Note: It is safe to call this function more than once for the same device.
591 static void srpt_unregister_mad_agent(struct srpt_device *sdev)
593 struct ib_port_modify port_modify = {
594 .clr_port_cap_mask = IB_PORT_DEVICE_MGMT_SUP,
596 struct srpt_port *sport;
599 for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
600 sport = &sdev->port[i - 1];
601 WARN_ON(sport->port != i);
602 if (ib_modify_port(sdev->device, i, 0, &port_modify) < 0)
603 pr_err("disabling MAD processing failed.\n");
604 if (sport->mad_agent) {
605 ib_unregister_mad_agent(sport->mad_agent);
606 sport->mad_agent = NULL;
612 * srpt_alloc_ioctx() - Allocate an SRPT I/O context structure.
614 static struct srpt_ioctx *srpt_alloc_ioctx(struct srpt_device *sdev,
615 int ioctx_size, int dma_size,
616 enum dma_data_direction dir)
618 struct srpt_ioctx *ioctx;
620 ioctx = kmalloc(ioctx_size, GFP_KERNEL);
624 ioctx->buf = kmalloc(dma_size, GFP_KERNEL);
628 ioctx->dma = ib_dma_map_single(sdev->device, ioctx->buf, dma_size, dir);
629 if (ib_dma_mapping_error(sdev->device, ioctx->dma))
643 * srpt_free_ioctx() - Free an SRPT I/O context structure.
645 static void srpt_free_ioctx(struct srpt_device *sdev, struct srpt_ioctx *ioctx,
646 int dma_size, enum dma_data_direction dir)
651 ib_dma_unmap_single(sdev->device, ioctx->dma, dma_size, dir);
657 * srpt_alloc_ioctx_ring() - Allocate a ring of SRPT I/O context structures.
658 * @sdev: Device to allocate the I/O context ring for.
659 * @ring_size: Number of elements in the I/O context ring.
660 * @ioctx_size: I/O context size.
661 * @dma_size: DMA buffer size.
662 * @dir: DMA data direction.
664 static struct srpt_ioctx **srpt_alloc_ioctx_ring(struct srpt_device *sdev,
665 int ring_size, int ioctx_size,
666 int dma_size, enum dma_data_direction dir)
668 struct srpt_ioctx **ring;
671 WARN_ON(ioctx_size != sizeof(struct srpt_recv_ioctx)
672 && ioctx_size != sizeof(struct srpt_send_ioctx));
674 ring = kmalloc(ring_size * sizeof(ring[0]), GFP_KERNEL);
677 for (i = 0; i < ring_size; ++i) {
678 ring[i] = srpt_alloc_ioctx(sdev, ioctx_size, dma_size, dir);
687 srpt_free_ioctx(sdev, ring[i], dma_size, dir);
695 * srpt_free_ioctx_ring() - Free the ring of SRPT I/O context structures.
697 static void srpt_free_ioctx_ring(struct srpt_ioctx **ioctx_ring,
698 struct srpt_device *sdev, int ring_size,
699 int dma_size, enum dma_data_direction dir)
703 for (i = 0; i < ring_size; ++i)
704 srpt_free_ioctx(sdev, ioctx_ring[i], dma_size, dir);
709 * srpt_get_cmd_state() - Get the state of a SCSI command.
711 static enum srpt_command_state srpt_get_cmd_state(struct srpt_send_ioctx *ioctx)
713 enum srpt_command_state state;
718 spin_lock_irqsave(&ioctx->spinlock, flags);
719 state = ioctx->state;
720 spin_unlock_irqrestore(&ioctx->spinlock, flags);
725 * srpt_set_cmd_state() - Set the state of a SCSI command.
727 * Does not modify the state of aborted commands. Returns the previous command
730 static enum srpt_command_state srpt_set_cmd_state(struct srpt_send_ioctx *ioctx,
731 enum srpt_command_state new)
733 enum srpt_command_state previous;
738 spin_lock_irqsave(&ioctx->spinlock, flags);
739 previous = ioctx->state;
740 if (previous != SRPT_STATE_DONE)
742 spin_unlock_irqrestore(&ioctx->spinlock, flags);
748 * srpt_test_and_set_cmd_state() - Test and set the state of a command.
750 * Returns true if and only if the previous command state was equal to 'old'.
752 static bool srpt_test_and_set_cmd_state(struct srpt_send_ioctx *ioctx,
753 enum srpt_command_state old,
754 enum srpt_command_state new)
756 enum srpt_command_state previous;
760 WARN_ON(old == SRPT_STATE_DONE);
761 WARN_ON(new == SRPT_STATE_NEW);
763 spin_lock_irqsave(&ioctx->spinlock, flags);
764 previous = ioctx->state;
767 spin_unlock_irqrestore(&ioctx->spinlock, flags);
768 return previous == old;
772 * srpt_post_recv() - Post an IB receive request.
774 static int srpt_post_recv(struct srpt_device *sdev,
775 struct srpt_recv_ioctx *ioctx)
778 struct ib_recv_wr wr, *bad_wr;
781 wr.wr_id = encode_wr_id(SRPT_RECV, ioctx->ioctx.index);
783 list.addr = ioctx->ioctx.dma;
784 list.length = srp_max_req_size;
785 list.lkey = sdev->pd->local_dma_lkey;
791 return ib_post_srq_recv(sdev->srq, &wr, &bad_wr);
795 * srpt_post_send() - Post an IB send request.
797 * Returns zero upon success and a non-zero value upon failure.
799 static int srpt_post_send(struct srpt_rdma_ch *ch,
800 struct srpt_send_ioctx *ioctx, int len)
803 struct ib_send_wr wr, *bad_wr;
804 struct srpt_device *sdev = ch->sport->sdev;
807 atomic_inc(&ch->req_lim);
810 if (unlikely(atomic_dec_return(&ch->sq_wr_avail) < 0)) {
811 pr_warn("IB send queue full (needed 1)\n");
815 ib_dma_sync_single_for_device(sdev->device, ioctx->ioctx.dma, len,
818 list.addr = ioctx->ioctx.dma;
820 list.lkey = sdev->pd->local_dma_lkey;
823 wr.wr_id = encode_wr_id(SRPT_SEND, ioctx->ioctx.index);
826 wr.opcode = IB_WR_SEND;
827 wr.send_flags = IB_SEND_SIGNALED;
829 ret = ib_post_send(ch->qp, &wr, &bad_wr);
833 atomic_inc(&ch->sq_wr_avail);
834 atomic_dec(&ch->req_lim);
840 * srpt_get_desc_tbl() - Parse the data descriptors of an SRP_CMD request.
841 * @ioctx: Pointer to the I/O context associated with the request.
842 * @srp_cmd: Pointer to the SRP_CMD request data.
843 * @dir: Pointer to the variable to which the transfer direction will be
845 * @data_len: Pointer to the variable to which the total data length of all
846 * descriptors in the SRP_CMD request will be written.
848 * This function initializes ioctx->nrbuf and ioctx->r_bufs.
850 * Returns -EINVAL when the SRP_CMD request contains inconsistent descriptors;
851 * -ENOMEM when memory allocation fails and zero upon success.
853 static int srpt_get_desc_tbl(struct srpt_send_ioctx *ioctx,
854 struct srp_cmd *srp_cmd,
855 enum dma_data_direction *dir, u64 *data_len)
857 struct srp_indirect_buf *idb;
858 struct srp_direct_buf *db;
859 unsigned add_cdb_offset;
863 * The pointer computations below will only be compiled correctly
864 * if srp_cmd::add_data is declared as s8*, u8*, s8[] or u8[], so check
865 * whether srp_cmd::add_data has been declared as a byte pointer.
867 BUILD_BUG_ON(!__same_type(srp_cmd->add_data[0], (s8)0)
868 && !__same_type(srp_cmd->add_data[0], (u8)0));
877 * The lower four bits of the buffer format field contain the DATA-IN
878 * buffer descriptor format, and the highest four bits contain the
879 * DATA-OUT buffer descriptor format.
882 if (srp_cmd->buf_fmt & 0xf)
883 /* DATA-IN: transfer data from target to initiator (read). */
884 *dir = DMA_FROM_DEVICE;
885 else if (srp_cmd->buf_fmt >> 4)
886 /* DATA-OUT: transfer data from initiator to target (write). */
887 *dir = DMA_TO_DEVICE;
890 * According to the SRP spec, the lower two bits of the 'ADDITIONAL
891 * CDB LENGTH' field are reserved and the size in bytes of this field
892 * is four times the value specified in bits 3..7. Hence the "& ~3".
894 add_cdb_offset = srp_cmd->add_cdb_len & ~3;
895 if (((srp_cmd->buf_fmt & 0xf) == SRP_DATA_DESC_DIRECT) ||
896 ((srp_cmd->buf_fmt >> 4) == SRP_DATA_DESC_DIRECT)) {
898 ioctx->rbufs = &ioctx->single_rbuf;
900 db = (struct srp_direct_buf *)(srp_cmd->add_data
902 memcpy(ioctx->rbufs, db, sizeof *db);
903 *data_len = be32_to_cpu(db->len);
904 } else if (((srp_cmd->buf_fmt & 0xf) == SRP_DATA_DESC_INDIRECT) ||
905 ((srp_cmd->buf_fmt >> 4) == SRP_DATA_DESC_INDIRECT)) {
906 idb = (struct srp_indirect_buf *)(srp_cmd->add_data
909 ioctx->n_rbuf = be32_to_cpu(idb->table_desc.len) / sizeof *db;
912 (srp_cmd->data_out_desc_cnt + srp_cmd->data_in_desc_cnt)) {
913 pr_err("received unsupported SRP_CMD request"
914 " type (%u out + %u in != %u / %zu)\n",
915 srp_cmd->data_out_desc_cnt,
916 srp_cmd->data_in_desc_cnt,
917 be32_to_cpu(idb->table_desc.len),
924 if (ioctx->n_rbuf == 1)
925 ioctx->rbufs = &ioctx->single_rbuf;
928 kmalloc(ioctx->n_rbuf * sizeof *db, GFP_ATOMIC);
937 memcpy(ioctx->rbufs, db, ioctx->n_rbuf * sizeof *db);
938 *data_len = be32_to_cpu(idb->len);
945 * srpt_init_ch_qp() - Initialize queue pair attributes.
947 * Initialized the attributes of queue pair 'qp' by allowing local write,
948 * remote read and remote write. Also transitions 'qp' to state IB_QPS_INIT.
950 static int srpt_init_ch_qp(struct srpt_rdma_ch *ch, struct ib_qp *qp)
952 struct ib_qp_attr *attr;
955 attr = kzalloc(sizeof *attr, GFP_KERNEL);
959 attr->qp_state = IB_QPS_INIT;
960 attr->qp_access_flags = IB_ACCESS_LOCAL_WRITE;
961 attr->port_num = ch->sport->port;
962 attr->pkey_index = 0;
964 ret = ib_modify_qp(qp, attr,
965 IB_QP_STATE | IB_QP_ACCESS_FLAGS | IB_QP_PORT |
973 * srpt_ch_qp_rtr() - Change the state of a channel to 'ready to receive' (RTR).
974 * @ch: channel of the queue pair.
975 * @qp: queue pair to change the state of.
977 * Returns zero upon success and a negative value upon failure.
979 * Note: currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
980 * If this structure ever becomes larger, it might be necessary to allocate
981 * it dynamically instead of on the stack.
983 static int srpt_ch_qp_rtr(struct srpt_rdma_ch *ch, struct ib_qp *qp)
985 struct ib_qp_attr qp_attr;
989 qp_attr.qp_state = IB_QPS_RTR;
990 ret = ib_cm_init_qp_attr(ch->cm_id, &qp_attr, &attr_mask);
994 qp_attr.max_dest_rd_atomic = 4;
996 ret = ib_modify_qp(qp, &qp_attr, attr_mask);
1003 * srpt_ch_qp_rts() - Change the state of a channel to 'ready to send' (RTS).
1004 * @ch: channel of the queue pair.
1005 * @qp: queue pair to change the state of.
1007 * Returns zero upon success and a negative value upon failure.
1009 * Note: currently a struct ib_qp_attr takes 136 bytes on a 64-bit system.
1010 * If this structure ever becomes larger, it might be necessary to allocate
1011 * it dynamically instead of on the stack.
1013 static int srpt_ch_qp_rts(struct srpt_rdma_ch *ch, struct ib_qp *qp)
1015 struct ib_qp_attr qp_attr;
1019 qp_attr.qp_state = IB_QPS_RTS;
1020 ret = ib_cm_init_qp_attr(ch->cm_id, &qp_attr, &attr_mask);
1024 qp_attr.max_rd_atomic = 4;
1026 ret = ib_modify_qp(qp, &qp_attr, attr_mask);
1033 * srpt_ch_qp_err() - Set the channel queue pair state to 'error'.
1035 static int srpt_ch_qp_err(struct srpt_rdma_ch *ch)
1037 struct ib_qp_attr qp_attr;
1039 qp_attr.qp_state = IB_QPS_ERR;
1040 return ib_modify_qp(ch->qp, &qp_attr, IB_QP_STATE);
1044 * srpt_unmap_sg_to_ib_sge() - Unmap an IB SGE list.
1046 static void srpt_unmap_sg_to_ib_sge(struct srpt_rdma_ch *ch,
1047 struct srpt_send_ioctx *ioctx)
1049 struct scatterlist *sg;
1050 enum dma_data_direction dir;
1054 BUG_ON(ioctx->n_rdma && !ioctx->rdma_ius);
1056 while (ioctx->n_rdma)
1057 kfree(ioctx->rdma_ius[--ioctx->n_rdma].sge);
1059 kfree(ioctx->rdma_ius);
1060 ioctx->rdma_ius = NULL;
1062 if (ioctx->mapped_sg_count) {
1065 dir = ioctx->cmd.data_direction;
1066 BUG_ON(dir == DMA_NONE);
1067 ib_dma_unmap_sg(ch->sport->sdev->device, sg, ioctx->sg_cnt,
1068 opposite_dma_dir(dir));
1069 ioctx->mapped_sg_count = 0;
1074 * srpt_map_sg_to_ib_sge() - Map an SG list to an IB SGE list.
1076 static int srpt_map_sg_to_ib_sge(struct srpt_rdma_ch *ch,
1077 struct srpt_send_ioctx *ioctx)
1079 struct ib_device *dev = ch->sport->sdev->device;
1081 struct scatterlist *sg, *sg_orig;
1083 enum dma_data_direction dir;
1084 struct rdma_iu *riu;
1085 struct srp_direct_buf *db;
1086 dma_addr_t dma_addr;
1098 dir = cmd->data_direction;
1099 BUG_ON(dir == DMA_NONE);
1101 ioctx->sg = sg = sg_orig = cmd->t_data_sg;
1102 ioctx->sg_cnt = sg_cnt = cmd->t_data_nents;
1104 count = ib_dma_map_sg(ch->sport->sdev->device, sg, sg_cnt,
1105 opposite_dma_dir(dir));
1106 if (unlikely(!count))
1109 ioctx->mapped_sg_count = count;
1111 if (ioctx->rdma_ius && ioctx->n_rdma_ius)
1112 nrdma = ioctx->n_rdma_ius;
1114 nrdma = (count + SRPT_DEF_SG_PER_WQE - 1) / SRPT_DEF_SG_PER_WQE
1117 ioctx->rdma_ius = kzalloc(nrdma * sizeof *riu, GFP_KERNEL);
1118 if (!ioctx->rdma_ius)
1121 ioctx->n_rdma_ius = nrdma;
1125 tsize = cmd->data_length;
1126 dma_len = ib_sg_dma_len(dev, &sg[0]);
1127 riu = ioctx->rdma_ius;
1130 * For each remote desc - calculate the #ib_sge.
1131 * If #ib_sge < SRPT_DEF_SG_PER_WQE per rdma operation then
1132 * each remote desc rdma_iu is required a rdma wr;
1134 * we need to allocate extra rdma_iu to carry extra #ib_sge in
1138 j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
1139 rsize = be32_to_cpu(db->len);
1140 raddr = be64_to_cpu(db->va);
1142 riu->rkey = be32_to_cpu(db->key);
1145 /* calculate how many sge required for this remote_buf */
1146 while (rsize > 0 && tsize > 0) {
1148 if (rsize >= dma_len) {
1157 dma_len = ib_sg_dma_len(
1169 if (rsize > 0 && riu->sge_cnt == SRPT_DEF_SG_PER_WQE) {
1172 kmalloc(riu->sge_cnt * sizeof *riu->sge,
1180 riu->rkey = be32_to_cpu(db->key);
1185 riu->sge = kmalloc(riu->sge_cnt * sizeof *riu->sge,
1192 tsize = cmd->data_length;
1193 riu = ioctx->rdma_ius;
1195 dma_len = ib_sg_dma_len(dev, &sg[0]);
1196 dma_addr = ib_sg_dma_address(dev, &sg[0]);
1198 /* this second loop is really mapped sg_addres to rdma_iu->ib_sge */
1200 j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) {
1201 rsize = be32_to_cpu(db->len);
1205 while (rsize > 0 && tsize > 0) {
1206 sge->addr = dma_addr;
1207 sge->lkey = ch->sport->sdev->pd->local_dma_lkey;
1209 if (rsize >= dma_len) {
1211 (tsize < dma_len) ? tsize : dma_len;
1219 dma_len = ib_sg_dma_len(
1221 dma_addr = ib_sg_dma_address(
1226 sge->length = (tsize < rsize) ? tsize : rsize;
1234 if (k == riu->sge_cnt && rsize > 0 && tsize > 0) {
1238 } else if (rsize > 0 && tsize > 0)
1246 srpt_unmap_sg_to_ib_sge(ch, ioctx);
1252 * srpt_get_send_ioctx() - Obtain an I/O context for sending to the initiator.
1254 static struct srpt_send_ioctx *srpt_get_send_ioctx(struct srpt_rdma_ch *ch)
1256 struct srpt_send_ioctx *ioctx;
1257 unsigned long flags;
1262 spin_lock_irqsave(&ch->spinlock, flags);
1263 if (!list_empty(&ch->free_list)) {
1264 ioctx = list_first_entry(&ch->free_list,
1265 struct srpt_send_ioctx, free_list);
1266 list_del(&ioctx->free_list);
1268 spin_unlock_irqrestore(&ch->spinlock, flags);
1273 BUG_ON(ioctx->ch != ch);
1274 spin_lock_init(&ioctx->spinlock);
1275 ioctx->state = SRPT_STATE_NEW;
1277 ioctx->rbufs = NULL;
1279 ioctx->n_rdma_ius = 0;
1280 ioctx->rdma_ius = NULL;
1281 ioctx->mapped_sg_count = 0;
1282 init_completion(&ioctx->tx_done);
1283 ioctx->queue_status_only = false;
1285 * transport_init_se_cmd() does not initialize all fields, so do it
1288 memset(&ioctx->cmd, 0, sizeof(ioctx->cmd));
1289 memset(&ioctx->sense_data, 0, sizeof(ioctx->sense_data));
1295 * srpt_abort_cmd() - Abort a SCSI command.
1296 * @ioctx: I/O context associated with the SCSI command.
1297 * @context: Preferred execution context.
1299 static int srpt_abort_cmd(struct srpt_send_ioctx *ioctx)
1301 enum srpt_command_state state;
1302 unsigned long flags;
1307 * If the command is in a state where the target core is waiting for
1308 * the ib_srpt driver, change the state to the next state. Changing
1309 * the state of the command from SRPT_STATE_NEED_DATA to
1310 * SRPT_STATE_DATA_IN ensures that srpt_xmit_response() will call this
1311 * function a second time.
1314 spin_lock_irqsave(&ioctx->spinlock, flags);
1315 state = ioctx->state;
1317 case SRPT_STATE_NEED_DATA:
1318 ioctx->state = SRPT_STATE_DATA_IN;
1320 case SRPT_STATE_DATA_IN:
1321 case SRPT_STATE_CMD_RSP_SENT:
1322 case SRPT_STATE_MGMT_RSP_SENT:
1323 ioctx->state = SRPT_STATE_DONE;
1328 spin_unlock_irqrestore(&ioctx->spinlock, flags);
1330 if (state == SRPT_STATE_DONE) {
1331 struct srpt_rdma_ch *ch = ioctx->ch;
1333 BUG_ON(ch->sess == NULL);
1335 target_put_sess_cmd(&ioctx->cmd);
1339 pr_debug("Aborting cmd with state %d and tag %lld\n", state,
1343 case SRPT_STATE_NEW:
1344 case SRPT_STATE_DATA_IN:
1345 case SRPT_STATE_MGMT:
1347 * Do nothing - defer abort processing until
1348 * srpt_queue_response() is invoked.
1350 WARN_ON(!transport_check_aborted_status(&ioctx->cmd, false));
1352 case SRPT_STATE_NEED_DATA:
1353 /* DMA_TO_DEVICE (write) - RDMA read error. */
1355 /* XXX(hch): this is a horrible layering violation.. */
1356 spin_lock_irqsave(&ioctx->cmd.t_state_lock, flags);
1357 ioctx->cmd.transport_state &= ~CMD_T_ACTIVE;
1358 spin_unlock_irqrestore(&ioctx->cmd.t_state_lock, flags);
1360 case SRPT_STATE_CMD_RSP_SENT:
1362 * SRP_RSP sending failed or the SRP_RSP send completion has
1363 * not been received in time.
1365 srpt_unmap_sg_to_ib_sge(ioctx->ch, ioctx);
1366 target_put_sess_cmd(&ioctx->cmd);
1368 case SRPT_STATE_MGMT_RSP_SENT:
1369 srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
1370 target_put_sess_cmd(&ioctx->cmd);
1373 WARN(1, "Unexpected command state (%d)", state);
1382 * srpt_handle_send_err_comp() - Process an IB_WC_SEND error completion.
1384 static void srpt_handle_send_err_comp(struct srpt_rdma_ch *ch, u64 wr_id)
1386 struct srpt_send_ioctx *ioctx;
1387 enum srpt_command_state state;
1390 atomic_inc(&ch->sq_wr_avail);
1392 index = idx_from_wr_id(wr_id);
1393 ioctx = ch->ioctx_ring[index];
1394 state = srpt_get_cmd_state(ioctx);
1396 WARN_ON(state != SRPT_STATE_CMD_RSP_SENT
1397 && state != SRPT_STATE_MGMT_RSP_SENT
1398 && state != SRPT_STATE_NEED_DATA
1399 && state != SRPT_STATE_DONE);
1401 /* If SRP_RSP sending failed, undo the ch->req_lim change. */
1402 if (state == SRPT_STATE_CMD_RSP_SENT
1403 || state == SRPT_STATE_MGMT_RSP_SENT)
1404 atomic_dec(&ch->req_lim);
1406 srpt_abort_cmd(ioctx);
1410 * srpt_handle_send_comp() - Process an IB send completion notification.
1412 static void srpt_handle_send_comp(struct srpt_rdma_ch *ch,
1413 struct srpt_send_ioctx *ioctx)
1415 enum srpt_command_state state;
1417 atomic_inc(&ch->sq_wr_avail);
1419 state = srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
1421 if (WARN_ON(state != SRPT_STATE_CMD_RSP_SENT
1422 && state != SRPT_STATE_MGMT_RSP_SENT
1423 && state != SRPT_STATE_DONE))
1424 pr_debug("state = %d\n", state);
1426 if (state != SRPT_STATE_DONE) {
1427 srpt_unmap_sg_to_ib_sge(ch, ioctx);
1428 transport_generic_free_cmd(&ioctx->cmd, 0);
1430 pr_err("IB completion has been received too late for"
1431 " wr_id = %u.\n", ioctx->ioctx.index);
1436 * srpt_handle_rdma_comp() - Process an IB RDMA completion notification.
1438 * XXX: what is now target_execute_cmd used to be asynchronous, and unmapping
1439 * the data that has been transferred via IB RDMA had to be postponed until the
1440 * check_stop_free() callback. None of this is necessary anymore and needs to
1443 static void srpt_handle_rdma_comp(struct srpt_rdma_ch *ch,
1444 struct srpt_send_ioctx *ioctx,
1445 enum srpt_opcode opcode)
1447 WARN_ON(ioctx->n_rdma <= 0);
1448 atomic_add(ioctx->n_rdma, &ch->sq_wr_avail);
1450 if (opcode == SRPT_RDMA_READ_LAST) {
1451 if (srpt_test_and_set_cmd_state(ioctx, SRPT_STATE_NEED_DATA,
1452 SRPT_STATE_DATA_IN))
1453 target_execute_cmd(&ioctx->cmd);
1455 pr_err("%s[%d]: wrong state = %d\n", __func__,
1456 __LINE__, srpt_get_cmd_state(ioctx));
1457 } else if (opcode == SRPT_RDMA_ABORT) {
1458 ioctx->rdma_aborted = true;
1460 WARN(true, "unexpected opcode %d\n", opcode);
1465 * srpt_handle_rdma_err_comp() - Process an IB RDMA error completion.
1467 static void srpt_handle_rdma_err_comp(struct srpt_rdma_ch *ch,
1468 struct srpt_send_ioctx *ioctx,
1469 enum srpt_opcode opcode)
1471 enum srpt_command_state state;
1473 state = srpt_get_cmd_state(ioctx);
1475 case SRPT_RDMA_READ_LAST:
1476 if (ioctx->n_rdma <= 0) {
1477 pr_err("Received invalid RDMA read"
1478 " error completion with idx %d\n",
1479 ioctx->ioctx.index);
1482 atomic_add(ioctx->n_rdma, &ch->sq_wr_avail);
1483 if (state == SRPT_STATE_NEED_DATA)
1484 srpt_abort_cmd(ioctx);
1486 pr_err("%s[%d]: wrong state = %d\n",
1487 __func__, __LINE__, state);
1489 case SRPT_RDMA_WRITE_LAST:
1492 pr_err("%s[%d]: opcode = %u\n", __func__, __LINE__, opcode);
1498 * srpt_build_cmd_rsp() - Build an SRP_RSP response.
1499 * @ch: RDMA channel through which the request has been received.
1500 * @ioctx: I/O context associated with the SRP_CMD request. The response will
1501 * be built in the buffer ioctx->buf points at and hence this function will
1502 * overwrite the request data.
1503 * @tag: tag of the request for which this response is being generated.
1504 * @status: value for the STATUS field of the SRP_RSP information unit.
1506 * Returns the size in bytes of the SRP_RSP response.
1508 * An SRP_RSP response contains a SCSI status or service response. See also
1509 * section 6.9 in the SRP r16a document for the format of an SRP_RSP
1510 * response. See also SPC-2 for more information about sense data.
1512 static int srpt_build_cmd_rsp(struct srpt_rdma_ch *ch,
1513 struct srpt_send_ioctx *ioctx, u64 tag,
1516 struct se_cmd *cmd = &ioctx->cmd;
1517 struct srp_rsp *srp_rsp;
1518 const u8 *sense_data;
1519 int sense_data_len, max_sense_len;
1520 u32 resid = cmd->residual_count;
1523 * The lowest bit of all SAM-3 status codes is zero (see also
1524 * paragraph 5.3 in SAM-3).
1526 WARN_ON(status & 1);
1528 srp_rsp = ioctx->ioctx.buf;
1531 sense_data = ioctx->sense_data;
1532 sense_data_len = ioctx->cmd.scsi_sense_length;
1533 WARN_ON(sense_data_len > sizeof(ioctx->sense_data));
1535 memset(srp_rsp, 0, sizeof *srp_rsp);
1536 srp_rsp->opcode = SRP_RSP;
1537 srp_rsp->req_lim_delta =
1538 cpu_to_be32(1 + atomic_xchg(&ch->req_lim_delta, 0));
1540 srp_rsp->status = status;
1542 if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
1543 if (cmd->data_direction == DMA_TO_DEVICE) {
1544 /* residual data from an underflow write */
1545 srp_rsp->flags = SRP_RSP_FLAG_DOUNDER;
1546 srp_rsp->data_out_res_cnt = cpu_to_be32(resid);
1547 } else if (cmd->data_direction == DMA_FROM_DEVICE) {
1548 /* residual data from an underflow read */
1549 srp_rsp->flags = SRP_RSP_FLAG_DIUNDER;
1550 srp_rsp->data_in_res_cnt = cpu_to_be32(resid);
1552 } else if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1553 if (cmd->data_direction == DMA_TO_DEVICE) {
1554 /* residual data from an overflow write */
1555 srp_rsp->flags = SRP_RSP_FLAG_DOOVER;
1556 srp_rsp->data_out_res_cnt = cpu_to_be32(resid);
1557 } else if (cmd->data_direction == DMA_FROM_DEVICE) {
1558 /* residual data from an overflow read */
1559 srp_rsp->flags = SRP_RSP_FLAG_DIOVER;
1560 srp_rsp->data_in_res_cnt = cpu_to_be32(resid);
1564 if (sense_data_len) {
1565 BUILD_BUG_ON(MIN_MAX_RSP_SIZE <= sizeof(*srp_rsp));
1566 max_sense_len = ch->max_ti_iu_len - sizeof(*srp_rsp);
1567 if (sense_data_len > max_sense_len) {
1568 pr_warn("truncated sense data from %d to %d"
1569 " bytes\n", sense_data_len, max_sense_len);
1570 sense_data_len = max_sense_len;
1573 srp_rsp->flags |= SRP_RSP_FLAG_SNSVALID;
1574 srp_rsp->sense_data_len = cpu_to_be32(sense_data_len);
1575 memcpy(srp_rsp + 1, sense_data, sense_data_len);
1578 return sizeof(*srp_rsp) + sense_data_len;
1582 * srpt_build_tskmgmt_rsp() - Build a task management response.
1583 * @ch: RDMA channel through which the request has been received.
1584 * @ioctx: I/O context in which the SRP_RSP response will be built.
1585 * @rsp_code: RSP_CODE that will be stored in the response.
1586 * @tag: Tag of the request for which this response is being generated.
1588 * Returns the size in bytes of the SRP_RSP response.
1590 * An SRP_RSP response contains a SCSI status or service response. See also
1591 * section 6.9 in the SRP r16a document for the format of an SRP_RSP
1594 static int srpt_build_tskmgmt_rsp(struct srpt_rdma_ch *ch,
1595 struct srpt_send_ioctx *ioctx,
1596 u8 rsp_code, u64 tag)
1598 struct srp_rsp *srp_rsp;
1603 resp_len = sizeof(*srp_rsp) + resp_data_len;
1605 srp_rsp = ioctx->ioctx.buf;
1607 memset(srp_rsp, 0, sizeof *srp_rsp);
1609 srp_rsp->opcode = SRP_RSP;
1610 srp_rsp->req_lim_delta =
1611 cpu_to_be32(1 + atomic_xchg(&ch->req_lim_delta, 0));
1614 srp_rsp->flags |= SRP_RSP_FLAG_RSPVALID;
1615 srp_rsp->resp_data_len = cpu_to_be32(resp_data_len);
1616 srp_rsp->data[3] = rsp_code;
1621 #define NO_SUCH_LUN ((uint64_t)-1LL)
1624 * SCSI LUN addressing method. See also SAM-2 and the section about
1627 enum scsi_lun_addr_method {
1628 SCSI_LUN_ADDR_METHOD_PERIPHERAL = 0,
1629 SCSI_LUN_ADDR_METHOD_FLAT = 1,
1630 SCSI_LUN_ADDR_METHOD_LUN = 2,
1631 SCSI_LUN_ADDR_METHOD_EXTENDED_LUN = 3,
1635 * srpt_unpack_lun() - Convert from network LUN to linear LUN.
1637 * Convert an 2-byte, 4-byte, 6-byte or 8-byte LUN structure in network byte
1638 * order (big endian) to a linear LUN. Supports three LUN addressing methods:
1639 * peripheral, flat and logical unit. See also SAM-2, section 4.9.4 (page 40).
1641 static uint64_t srpt_unpack_lun(const uint8_t *lun, int len)
1643 uint64_t res = NO_SUCH_LUN;
1644 int addressing_method;
1646 if (unlikely(len < 2)) {
1647 pr_err("Illegal LUN length %d, expected 2 bytes or more\n",
1654 if ((*((__be64 *)lun) &
1655 cpu_to_be64(0x0000FFFFFFFFFFFFLL)) != 0)
1659 if (*((__be16 *)&lun[2]) != 0)
1663 if (*((__be32 *)&lun[2]) != 0)
1672 addressing_method = (*lun) >> 6; /* highest two bits of byte 0 */
1673 switch (addressing_method) {
1674 case SCSI_LUN_ADDR_METHOD_PERIPHERAL:
1675 case SCSI_LUN_ADDR_METHOD_FLAT:
1676 case SCSI_LUN_ADDR_METHOD_LUN:
1677 res = *(lun + 1) | (((*lun) & 0x3f) << 8);
1680 case SCSI_LUN_ADDR_METHOD_EXTENDED_LUN:
1682 pr_err("Unimplemented LUN addressing method %u\n",
1691 pr_err("Support for multi-level LUNs has not yet been implemented\n");
1695 static int srpt_check_stop_free(struct se_cmd *cmd)
1697 struct srpt_send_ioctx *ioctx = container_of(cmd,
1698 struct srpt_send_ioctx, cmd);
1700 return target_put_sess_cmd(&ioctx->cmd);
1704 * srpt_handle_cmd() - Process SRP_CMD.
1706 static int srpt_handle_cmd(struct srpt_rdma_ch *ch,
1707 struct srpt_recv_ioctx *recv_ioctx,
1708 struct srpt_send_ioctx *send_ioctx)
1711 struct srp_cmd *srp_cmd;
1712 uint64_t unpacked_lun;
1714 enum dma_data_direction dir;
1718 BUG_ON(!send_ioctx);
1720 srp_cmd = recv_ioctx->ioctx.buf;
1721 cmd = &send_ioctx->cmd;
1722 cmd->tag = srp_cmd->tag;
1724 switch (srp_cmd->task_attr) {
1725 case SRP_CMD_SIMPLE_Q:
1726 cmd->sam_task_attr = TCM_SIMPLE_TAG;
1728 case SRP_CMD_ORDERED_Q:
1730 cmd->sam_task_attr = TCM_ORDERED_TAG;
1732 case SRP_CMD_HEAD_OF_Q:
1733 cmd->sam_task_attr = TCM_HEAD_TAG;
1736 cmd->sam_task_attr = TCM_ACA_TAG;
1740 if (srpt_get_desc_tbl(send_ioctx, srp_cmd, &dir, &data_len)) {
1741 pr_err("0x%llx: parsing SRP descriptor table failed.\n",
1743 ret = TCM_INVALID_CDB_FIELD;
1747 unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_cmd->lun,
1748 sizeof(srp_cmd->lun));
1749 rc = target_submit_cmd(cmd, ch->sess, srp_cmd->cdb,
1750 &send_ioctx->sense_data[0], unpacked_lun, data_len,
1751 TCM_SIMPLE_TAG, dir, TARGET_SCF_ACK_KREF);
1753 ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1759 transport_send_check_condition_and_sense(cmd, ret, 0);
1763 static int srp_tmr_to_tcm(int fn)
1766 case SRP_TSK_ABORT_TASK:
1767 return TMR_ABORT_TASK;
1768 case SRP_TSK_ABORT_TASK_SET:
1769 return TMR_ABORT_TASK_SET;
1770 case SRP_TSK_CLEAR_TASK_SET:
1771 return TMR_CLEAR_TASK_SET;
1772 case SRP_TSK_LUN_RESET:
1773 return TMR_LUN_RESET;
1774 case SRP_TSK_CLEAR_ACA:
1775 return TMR_CLEAR_ACA;
1782 * srpt_handle_tsk_mgmt() - Process an SRP_TSK_MGMT information unit.
1784 * Returns 0 if and only if the request will be processed by the target core.
1786 * For more information about SRP_TSK_MGMT information units, see also section
1787 * 6.7 in the SRP r16a document.
1789 static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,
1790 struct srpt_recv_ioctx *recv_ioctx,
1791 struct srpt_send_ioctx *send_ioctx)
1793 struct srp_tsk_mgmt *srp_tsk;
1795 struct se_session *sess = ch->sess;
1796 uint64_t unpacked_lun;
1800 BUG_ON(!send_ioctx);
1802 srp_tsk = recv_ioctx->ioctx.buf;
1803 cmd = &send_ioctx->cmd;
1805 pr_debug("recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld"
1806 " cm_id %p sess %p\n", srp_tsk->tsk_mgmt_func,
1807 srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess);
1809 srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT);
1810 send_ioctx->cmd.tag = srp_tsk->tag;
1811 tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func);
1812 unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun,
1813 sizeof(srp_tsk->lun));
1814 rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun,
1815 srp_tsk, tcm_tmr, GFP_KERNEL, srp_tsk->task_tag,
1816 TARGET_SCF_ACK_KREF);
1818 send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED;
1823 transport_send_check_condition_and_sense(cmd, 0, 0); // XXX:
1827 * srpt_handle_new_iu() - Process a newly received information unit.
1828 * @ch: RDMA channel through which the information unit has been received.
1829 * @ioctx: SRPT I/O context associated with the information unit.
1831 static void srpt_handle_new_iu(struct srpt_rdma_ch *ch,
1832 struct srpt_recv_ioctx *recv_ioctx,
1833 struct srpt_send_ioctx *send_ioctx)
1835 struct srp_cmd *srp_cmd;
1836 enum rdma_ch_state ch_state;
1839 BUG_ON(!recv_ioctx);
1841 ib_dma_sync_single_for_cpu(ch->sport->sdev->device,
1842 recv_ioctx->ioctx.dma, srp_max_req_size,
1845 ch_state = srpt_get_ch_state(ch);
1846 if (unlikely(ch_state == CH_CONNECTING)) {
1847 list_add_tail(&recv_ioctx->wait_list, &ch->cmd_wait_list);
1851 if (unlikely(ch_state != CH_LIVE))
1854 srp_cmd = recv_ioctx->ioctx.buf;
1855 if (srp_cmd->opcode == SRP_CMD || srp_cmd->opcode == SRP_TSK_MGMT) {
1857 send_ioctx = srpt_get_send_ioctx(ch);
1858 if (unlikely(!send_ioctx)) {
1859 list_add_tail(&recv_ioctx->wait_list,
1860 &ch->cmd_wait_list);
1865 switch (srp_cmd->opcode) {
1867 srpt_handle_cmd(ch, recv_ioctx, send_ioctx);
1870 srpt_handle_tsk_mgmt(ch, recv_ioctx, send_ioctx);
1873 pr_err("Not yet implemented: SRP_I_LOGOUT\n");
1876 pr_debug("received SRP_CRED_RSP\n");
1879 pr_debug("received SRP_AER_RSP\n");
1882 pr_err("Received SRP_RSP\n");
1885 pr_err("received IU with unknown opcode 0x%x\n",
1890 srpt_post_recv(ch->sport->sdev, recv_ioctx);
1895 static void srpt_process_rcv_completion(struct ib_cq *cq,
1896 struct srpt_rdma_ch *ch,
1899 struct srpt_device *sdev = ch->sport->sdev;
1900 struct srpt_recv_ioctx *ioctx;
1903 index = idx_from_wr_id(wc->wr_id);
1904 if (wc->status == IB_WC_SUCCESS) {
1907 req_lim = atomic_dec_return(&ch->req_lim);
1908 if (unlikely(req_lim < 0))
1909 pr_err("req_lim = %d < 0\n", req_lim);
1910 ioctx = sdev->ioctx_ring[index];
1911 srpt_handle_new_iu(ch, ioctx, NULL);
1913 pr_info("receiving failed for idx %u with status %d\n",
1919 * srpt_process_send_completion() - Process an IB send completion.
1921 * Note: Although this has not yet been observed during tests, at least in
1922 * theory it is possible that the srpt_get_send_ioctx() call invoked by
1923 * srpt_handle_new_iu() fails. This is possible because the req_lim_delta
1924 * value in each response is set to one, and it is possible that this response
1925 * makes the initiator send a new request before the send completion for that
1926 * response has been processed. This could e.g. happen if the call to
1927 * srpt_put_send_iotcx() is delayed because of a higher priority interrupt or
1928 * if IB retransmission causes generation of the send completion to be
1929 * delayed. Incoming information units for which srpt_get_send_ioctx() fails
1930 * are queued on cmd_wait_list. The code below processes these delayed
1931 * requests one at a time.
1933 static void srpt_process_send_completion(struct ib_cq *cq,
1934 struct srpt_rdma_ch *ch,
1937 struct srpt_send_ioctx *send_ioctx;
1939 enum srpt_opcode opcode;
1941 index = idx_from_wr_id(wc->wr_id);
1942 opcode = opcode_from_wr_id(wc->wr_id);
1943 send_ioctx = ch->ioctx_ring[index];
1944 if (wc->status == IB_WC_SUCCESS) {
1945 if (opcode == SRPT_SEND)
1946 srpt_handle_send_comp(ch, send_ioctx);
1948 WARN_ON(opcode != SRPT_RDMA_ABORT &&
1949 wc->opcode != IB_WC_RDMA_READ);
1950 srpt_handle_rdma_comp(ch, send_ioctx, opcode);
1953 if (opcode == SRPT_SEND) {
1954 pr_info("sending response for idx %u failed"
1955 " with status %d\n", index, wc->status);
1956 srpt_handle_send_err_comp(ch, wc->wr_id);
1957 } else if (opcode != SRPT_RDMA_MID) {
1958 pr_info("RDMA t %d for idx %u failed with"
1959 " status %d\n", opcode, index, wc->status);
1960 srpt_handle_rdma_err_comp(ch, send_ioctx, opcode);
1964 while (unlikely(opcode == SRPT_SEND
1965 && !list_empty(&ch->cmd_wait_list)
1966 && srpt_get_ch_state(ch) == CH_LIVE
1967 && (send_ioctx = srpt_get_send_ioctx(ch)) != NULL)) {
1968 struct srpt_recv_ioctx *recv_ioctx;
1970 recv_ioctx = list_first_entry(&ch->cmd_wait_list,
1971 struct srpt_recv_ioctx,
1973 list_del(&recv_ioctx->wait_list);
1974 srpt_handle_new_iu(ch, recv_ioctx, send_ioctx);
1978 static void srpt_process_completion(struct ib_cq *cq, struct srpt_rdma_ch *ch)
1980 struct ib_wc *const wc = ch->wc;
1983 WARN_ON(cq != ch->cq);
1985 ib_req_notify_cq(cq, IB_CQ_NEXT_COMP);
1986 while ((n = ib_poll_cq(cq, ARRAY_SIZE(ch->wc), wc)) > 0) {
1987 for (i = 0; i < n; i++) {
1988 if (opcode_from_wr_id(wc[i].wr_id) == SRPT_RECV)
1989 srpt_process_rcv_completion(cq, ch, &wc[i]);
1991 srpt_process_send_completion(cq, ch, &wc[i]);
1997 * srpt_completion() - IB completion queue callback function.
2000 * - It is guaranteed that a completion handler will never be invoked
2001 * concurrently on two different CPUs for the same completion queue. See also
2002 * Documentation/infiniband/core_locking.txt and the implementation of
2003 * handle_edge_irq() in kernel/irq/chip.c.
2004 * - When threaded IRQs are enabled, completion handlers are invoked in thread
2005 * context instead of interrupt context.
2007 static void srpt_completion(struct ib_cq *cq, void *ctx)
2009 struct srpt_rdma_ch *ch = ctx;
2011 wake_up_interruptible(&ch->wait_queue);
2014 static int srpt_compl_thread(void *arg)
2016 struct srpt_rdma_ch *ch;
2018 /* Hibernation / freezing of the SRPT kernel thread is not supported. */
2019 current->flags |= PF_NOFREEZE;
2023 pr_info("Session %s: kernel thread %s (PID %d) started\n",
2024 ch->sess_name, ch->thread->comm, current->pid);
2025 while (!kthread_should_stop()) {
2026 wait_event_interruptible(ch->wait_queue,
2027 (srpt_process_completion(ch->cq, ch),
2028 kthread_should_stop()));
2030 pr_info("Session %s: kernel thread %s (PID %d) stopped\n",
2031 ch->sess_name, ch->thread->comm, current->pid);
2036 * srpt_create_ch_ib() - Create receive and send completion queues.
2038 static int srpt_create_ch_ib(struct srpt_rdma_ch *ch)
2040 struct ib_qp_init_attr *qp_init;
2041 struct srpt_port *sport = ch->sport;
2042 struct srpt_device *sdev = sport->sdev;
2043 u32 srp_sq_size = sport->port_attrib.srp_sq_size;
2044 struct ib_cq_init_attr cq_attr = {};
2047 WARN_ON(ch->rq_size < 1);
2050 qp_init = kzalloc(sizeof *qp_init, GFP_KERNEL);
2055 cq_attr.cqe = ch->rq_size + srp_sq_size;
2056 ch->cq = ib_create_cq(sdev->device, srpt_completion, NULL, ch,
2058 if (IS_ERR(ch->cq)) {
2059 ret = PTR_ERR(ch->cq);
2060 pr_err("failed to create CQ cqe= %d ret= %d\n",
2061 ch->rq_size + srp_sq_size, ret);
2065 qp_init->qp_context = (void *)ch;
2066 qp_init->event_handler
2067 = (void(*)(struct ib_event *, void*))srpt_qp_event;
2068 qp_init->send_cq = ch->cq;
2069 qp_init->recv_cq = ch->cq;
2070 qp_init->srq = sdev->srq;
2071 qp_init->sq_sig_type = IB_SIGNAL_REQ_WR;
2072 qp_init->qp_type = IB_QPT_RC;
2073 qp_init->cap.max_send_wr = srp_sq_size;
2074 qp_init->cap.max_send_sge = SRPT_DEF_SG_PER_WQE;
2076 ch->qp = ib_create_qp(sdev->pd, qp_init);
2077 if (IS_ERR(ch->qp)) {
2078 ret = PTR_ERR(ch->qp);
2079 if (ret == -ENOMEM) {
2081 if (srp_sq_size >= MIN_SRPT_SQ_SIZE) {
2082 ib_destroy_cq(ch->cq);
2086 pr_err("failed to create_qp ret= %d\n", ret);
2087 goto err_destroy_cq;
2090 atomic_set(&ch->sq_wr_avail, qp_init->cap.max_send_wr);
2092 pr_debug("%s: max_cqe= %d max_sge= %d sq_size = %d cm_id= %p\n",
2093 __func__, ch->cq->cqe, qp_init->cap.max_send_sge,
2094 qp_init->cap.max_send_wr, ch->cm_id);
2096 ret = srpt_init_ch_qp(ch, ch->qp);
2098 goto err_destroy_qp;
2100 init_waitqueue_head(&ch->wait_queue);
2102 pr_debug("creating thread for session %s\n", ch->sess_name);
2104 ch->thread = kthread_run(srpt_compl_thread, ch, "ib_srpt_compl");
2105 if (IS_ERR(ch->thread)) {
2106 pr_err("failed to create kernel thread %ld\n",
2107 PTR_ERR(ch->thread));
2109 goto err_destroy_qp;
2117 ib_destroy_qp(ch->qp);
2119 ib_destroy_cq(ch->cq);
2123 static void srpt_destroy_ch_ib(struct srpt_rdma_ch *ch)
2126 kthread_stop(ch->thread);
2128 ib_destroy_qp(ch->qp);
2129 ib_destroy_cq(ch->cq);
2133 * __srpt_close_ch() - Close an RDMA channel by setting the QP error state.
2135 * Reset the QP and make sure all resources associated with the channel will
2136 * be deallocated at an appropriate time.
2138 * Note: The caller must hold ch->sport->sdev->spinlock.
2140 static void __srpt_close_ch(struct srpt_rdma_ch *ch)
2142 enum rdma_ch_state prev_state;
2143 unsigned long flags;
2145 spin_lock_irqsave(&ch->spinlock, flags);
2146 prev_state = ch->state;
2147 switch (prev_state) {
2150 ch->state = CH_DISCONNECTING;
2155 spin_unlock_irqrestore(&ch->spinlock, flags);
2157 switch (prev_state) {
2159 ib_send_cm_rej(ch->cm_id, IB_CM_REJ_NO_RESOURCES, NULL, 0,
2163 if (ib_send_cm_dreq(ch->cm_id, NULL, 0) < 0)
2164 pr_err("sending CM DREQ failed.\n");
2166 case CH_DISCONNECTING:
2175 * srpt_close_ch() - Close an RDMA channel.
2177 static void srpt_close_ch(struct srpt_rdma_ch *ch)
2179 struct srpt_device *sdev;
2181 sdev = ch->sport->sdev;
2182 spin_lock_irq(&sdev->spinlock);
2183 __srpt_close_ch(ch);
2184 spin_unlock_irq(&sdev->spinlock);
2188 * srpt_shutdown_session() - Whether or not a session may be shut down.
2190 static int srpt_shutdown_session(struct se_session *se_sess)
2192 struct srpt_rdma_ch *ch = se_sess->fabric_sess_ptr;
2193 unsigned long flags;
2195 spin_lock_irqsave(&ch->spinlock, flags);
2196 if (ch->in_shutdown) {
2197 spin_unlock_irqrestore(&ch->spinlock, flags);
2201 ch->in_shutdown = true;
2202 target_sess_cmd_list_set_waiting(se_sess);
2203 spin_unlock_irqrestore(&ch->spinlock, flags);
2209 * srpt_drain_channel() - Drain a channel by resetting the IB queue pair.
2210 * @cm_id: Pointer to the CM ID of the channel to be drained.
2212 * Note: Must be called from inside srpt_cm_handler to avoid a race between
2213 * accessing sdev->spinlock and the call to kfree(sdev) in srpt_remove_one()
2214 * (the caller of srpt_cm_handler holds the cm_id spinlock; srpt_remove_one()
2215 * waits until all target sessions for the associated IB device have been
2216 * unregistered and target session registration involves a call to
2217 * ib_destroy_cm_id(), which locks the cm_id spinlock and hence waits until
2218 * this function has finished).
2220 static void srpt_drain_channel(struct ib_cm_id *cm_id)
2222 struct srpt_device *sdev;
2223 struct srpt_rdma_ch *ch;
2225 bool do_reset = false;
2227 WARN_ON_ONCE(irqs_disabled());
2229 sdev = cm_id->context;
2231 spin_lock_irq(&sdev->spinlock);
2232 list_for_each_entry(ch, &sdev->rch_list, list) {
2233 if (ch->cm_id == cm_id) {
2234 do_reset = srpt_test_and_set_ch_state(ch,
2235 CH_CONNECTING, CH_DRAINING) ||
2236 srpt_test_and_set_ch_state(ch,
2237 CH_LIVE, CH_DRAINING) ||
2238 srpt_test_and_set_ch_state(ch,
2239 CH_DISCONNECTING, CH_DRAINING);
2243 spin_unlock_irq(&sdev->spinlock);
2247 srpt_shutdown_session(ch->sess);
2249 ret = srpt_ch_qp_err(ch);
2251 pr_err("Setting queue pair in error state"
2252 " failed: %d\n", ret);
2257 * srpt_find_channel() - Look up an RDMA channel.
2258 * @cm_id: Pointer to the CM ID of the channel to be looked up.
2260 * Return NULL if no matching RDMA channel has been found.
2262 static struct srpt_rdma_ch *srpt_find_channel(struct srpt_device *sdev,
2263 struct ib_cm_id *cm_id)
2265 struct srpt_rdma_ch *ch;
2268 WARN_ON_ONCE(irqs_disabled());
2272 spin_lock_irq(&sdev->spinlock);
2273 list_for_each_entry(ch, &sdev->rch_list, list) {
2274 if (ch->cm_id == cm_id) {
2279 spin_unlock_irq(&sdev->spinlock);
2281 return found ? ch : NULL;
2285 * srpt_release_channel() - Release channel resources.
2287 * Schedules the actual release because:
2288 * - Calling the ib_destroy_cm_id() call from inside an IB CM callback would
2289 * trigger a deadlock.
2290 * - It is not safe to call TCM transport_* functions from interrupt context.
2292 static void srpt_release_channel(struct srpt_rdma_ch *ch)
2294 schedule_work(&ch->release_work);
2297 static void srpt_release_channel_work(struct work_struct *w)
2299 struct srpt_rdma_ch *ch;
2300 struct srpt_device *sdev;
2301 struct se_session *se_sess;
2303 ch = container_of(w, struct srpt_rdma_ch, release_work);
2304 pr_debug("ch = %p; ch->sess = %p; release_done = %p\n", ch, ch->sess,
2307 sdev = ch->sport->sdev;
2313 target_wait_for_sess_cmds(se_sess);
2315 transport_deregister_session_configfs(se_sess);
2316 transport_deregister_session(se_sess);
2319 ib_destroy_cm_id(ch->cm_id);
2321 srpt_destroy_ch_ib(ch);
2323 srpt_free_ioctx_ring((struct srpt_ioctx **)ch->ioctx_ring,
2324 ch->sport->sdev, ch->rq_size,
2325 ch->rsp_size, DMA_TO_DEVICE);
2327 spin_lock_irq(&sdev->spinlock);
2328 list_del(&ch->list);
2329 spin_unlock_irq(&sdev->spinlock);
2331 if (ch->release_done)
2332 complete(ch->release_done);
2334 wake_up(&sdev->ch_releaseQ);
2339 static struct srpt_node_acl *__srpt_lookup_acl(struct srpt_port *sport,
2342 struct srpt_node_acl *nacl;
2344 list_for_each_entry(nacl, &sport->port_acl_list, list)
2345 if (memcmp(nacl->i_port_id, i_port_id,
2346 sizeof(nacl->i_port_id)) == 0)
2352 static struct srpt_node_acl *srpt_lookup_acl(struct srpt_port *sport,
2355 struct srpt_node_acl *nacl;
2357 spin_lock_irq(&sport->port_acl_lock);
2358 nacl = __srpt_lookup_acl(sport, i_port_id);
2359 spin_unlock_irq(&sport->port_acl_lock);
2365 * srpt_cm_req_recv() - Process the event IB_CM_REQ_RECEIVED.
2367 * Ownership of the cm_id is transferred to the target session if this
2368 * functions returns zero. Otherwise the caller remains the owner of cm_id.
2370 static int srpt_cm_req_recv(struct ib_cm_id *cm_id,
2371 struct ib_cm_req_event_param *param,
2374 struct srpt_device *sdev = cm_id->context;
2375 struct srpt_port *sport = &sdev->port[param->port - 1];
2376 struct srp_login_req *req;
2377 struct srp_login_rsp *rsp;
2378 struct srp_login_rej *rej;
2379 struct ib_cm_rep_param *rep_param;
2380 struct srpt_rdma_ch *ch, *tmp_ch;
2381 struct srpt_node_acl *nacl;
2386 WARN_ON_ONCE(irqs_disabled());
2388 if (WARN_ON(!sdev || !private_data))
2391 req = (struct srp_login_req *)private_data;
2393 it_iu_len = be32_to_cpu(req->req_it_iu_len);
2395 pr_info("Received SRP_LOGIN_REQ with i_port_id 0x%llx:0x%llx,"
2396 " t_port_id 0x%llx:0x%llx and it_iu_len %d on port %d"
2397 " (guid=0x%llx:0x%llx)\n",
2398 be64_to_cpu(*(__be64 *)&req->initiator_port_id[0]),
2399 be64_to_cpu(*(__be64 *)&req->initiator_port_id[8]),
2400 be64_to_cpu(*(__be64 *)&req->target_port_id[0]),
2401 be64_to_cpu(*(__be64 *)&req->target_port_id[8]),
2404 be64_to_cpu(*(__be64 *)&sdev->port[param->port - 1].gid.raw[0]),
2405 be64_to_cpu(*(__be64 *)&sdev->port[param->port - 1].gid.raw[8]));
2407 rsp = kzalloc(sizeof *rsp, GFP_KERNEL);
2408 rej = kzalloc(sizeof *rej, GFP_KERNEL);
2409 rep_param = kzalloc(sizeof *rep_param, GFP_KERNEL);
2411 if (!rsp || !rej || !rep_param) {
2416 if (it_iu_len > srp_max_req_size || it_iu_len < 64) {
2417 rej->reason = cpu_to_be32(
2418 SRP_LOGIN_REJ_REQ_IT_IU_LENGTH_TOO_LARGE);
2420 pr_err("rejected SRP_LOGIN_REQ because its"
2421 " length (%d bytes) is out of range (%d .. %d)\n",
2422 it_iu_len, 64, srp_max_req_size);
2426 if (!sport->enabled) {
2427 rej->reason = cpu_to_be32(
2428 SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2430 pr_err("rejected SRP_LOGIN_REQ because the target port"
2431 " has not yet been enabled\n");
2435 if ((req->req_flags & SRP_MTCH_ACTION) == SRP_MULTICHAN_SINGLE) {
2436 rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_NO_CHAN;
2438 spin_lock_irq(&sdev->spinlock);
2440 list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list) {
2441 if (!memcmp(ch->i_port_id, req->initiator_port_id, 16)
2442 && !memcmp(ch->t_port_id, req->target_port_id, 16)
2443 && param->port == ch->sport->port
2444 && param->listen_id == ch->sport->sdev->cm_id
2446 enum rdma_ch_state ch_state;
2448 ch_state = srpt_get_ch_state(ch);
2449 if (ch_state != CH_CONNECTING
2450 && ch_state != CH_LIVE)
2453 /* found an existing channel */
2454 pr_debug("Found existing channel %s"
2455 " cm_id= %p state= %d\n",
2456 ch->sess_name, ch->cm_id, ch_state);
2458 __srpt_close_ch(ch);
2461 SRP_LOGIN_RSP_MULTICHAN_TERMINATED;
2465 spin_unlock_irq(&sdev->spinlock);
2468 rsp->rsp_flags = SRP_LOGIN_RSP_MULTICHAN_MAINTAINED;
2470 if (*(__be64 *)req->target_port_id != cpu_to_be64(srpt_service_guid)
2471 || *(__be64 *)(req->target_port_id + 8) !=
2472 cpu_to_be64(srpt_service_guid)) {
2473 rej->reason = cpu_to_be32(
2474 SRP_LOGIN_REJ_UNABLE_ASSOCIATE_CHANNEL);
2476 pr_err("rejected SRP_LOGIN_REQ because it"
2477 " has an invalid target port identifier.\n");
2481 ch = kzalloc(sizeof *ch, GFP_KERNEL);
2483 rej->reason = cpu_to_be32(
2484 SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2485 pr_err("rejected SRP_LOGIN_REQ because no memory.\n");
2490 INIT_WORK(&ch->release_work, srpt_release_channel_work);
2491 memcpy(ch->i_port_id, req->initiator_port_id, 16);
2492 memcpy(ch->t_port_id, req->target_port_id, 16);
2493 ch->sport = &sdev->port[param->port - 1];
2496 * Avoid QUEUE_FULL conditions by limiting the number of buffers used
2497 * for the SRP protocol to the command queue size.
2499 ch->rq_size = SRPT_RQ_SIZE;
2500 spin_lock_init(&ch->spinlock);
2501 ch->state = CH_CONNECTING;
2502 INIT_LIST_HEAD(&ch->cmd_wait_list);
2503 ch->rsp_size = ch->sport->port_attrib.srp_max_rsp_size;
2505 ch->ioctx_ring = (struct srpt_send_ioctx **)
2506 srpt_alloc_ioctx_ring(ch->sport->sdev, ch->rq_size,
2507 sizeof(*ch->ioctx_ring[0]),
2508 ch->rsp_size, DMA_TO_DEVICE);
2509 if (!ch->ioctx_ring)
2512 INIT_LIST_HEAD(&ch->free_list);
2513 for (i = 0; i < ch->rq_size; i++) {
2514 ch->ioctx_ring[i]->ch = ch;
2515 list_add_tail(&ch->ioctx_ring[i]->free_list, &ch->free_list);
2518 ret = srpt_create_ch_ib(ch);
2520 rej->reason = cpu_to_be32(
2521 SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2522 pr_err("rejected SRP_LOGIN_REQ because creating"
2523 " a new RDMA channel failed.\n");
2527 ret = srpt_ch_qp_rtr(ch, ch->qp);
2529 rej->reason = cpu_to_be32(SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2530 pr_err("rejected SRP_LOGIN_REQ because enabling"
2531 " RTR failed (error code = %d)\n", ret);
2535 * Use the initator port identifier as the session name.
2537 snprintf(ch->sess_name, sizeof(ch->sess_name), "0x%016llx%016llx",
2538 be64_to_cpu(*(__be64 *)ch->i_port_id),
2539 be64_to_cpu(*(__be64 *)(ch->i_port_id + 8)));
2541 pr_debug("registering session %s\n", ch->sess_name);
2543 nacl = srpt_lookup_acl(sport, ch->i_port_id);
2545 pr_info("Rejected login because no ACL has been"
2546 " configured yet for initiator %s.\n", ch->sess_name);
2547 rej->reason = cpu_to_be32(
2548 SRP_LOGIN_REJ_CHANNEL_LIMIT_REACHED);
2552 ch->sess = transport_init_session(TARGET_PROT_NORMAL);
2553 if (IS_ERR(ch->sess)) {
2554 rej->reason = cpu_to_be32(
2555 SRP_LOGIN_REJ_INSUFFICIENT_RESOURCES);
2556 pr_debug("Failed to create session\n");
2557 goto deregister_session;
2559 ch->sess->se_node_acl = &nacl->nacl;
2560 transport_register_session(&sport->port_tpg_1, &nacl->nacl, ch->sess, ch);
2562 pr_debug("Establish connection sess=%p name=%s cm_id=%p\n", ch->sess,
2563 ch->sess_name, ch->cm_id);
2565 /* create srp_login_response */
2566 rsp->opcode = SRP_LOGIN_RSP;
2567 rsp->tag = req->tag;
2568 rsp->max_it_iu_len = req->req_it_iu_len;
2569 rsp->max_ti_iu_len = req->req_it_iu_len;
2570 ch->max_ti_iu_len = it_iu_len;
2571 rsp->buf_fmt = cpu_to_be16(SRP_BUF_FORMAT_DIRECT
2572 | SRP_BUF_FORMAT_INDIRECT);
2573 rsp->req_lim_delta = cpu_to_be32(ch->rq_size);
2574 atomic_set(&ch->req_lim, ch->rq_size);
2575 atomic_set(&ch->req_lim_delta, 0);
2577 /* create cm reply */
2578 rep_param->qp_num = ch->qp->qp_num;
2579 rep_param->private_data = (void *)rsp;
2580 rep_param->private_data_len = sizeof *rsp;
2581 rep_param->rnr_retry_count = 7;
2582 rep_param->flow_control = 1;
2583 rep_param->failover_accepted = 0;
2585 rep_param->responder_resources = 4;
2586 rep_param->initiator_depth = 4;
2588 ret = ib_send_cm_rep(cm_id, rep_param);
2590 pr_err("sending SRP_LOGIN_REQ response failed"
2591 " (error code = %d)\n", ret);
2592 goto release_channel;
2595 spin_lock_irq(&sdev->spinlock);
2596 list_add_tail(&ch->list, &sdev->rch_list);
2597 spin_unlock_irq(&sdev->spinlock);
2602 srpt_set_ch_state(ch, CH_RELEASING);
2603 transport_deregister_session_configfs(ch->sess);
2606 transport_deregister_session(ch->sess);
2610 srpt_destroy_ch_ib(ch);
2613 srpt_free_ioctx_ring((struct srpt_ioctx **)ch->ioctx_ring,
2614 ch->sport->sdev, ch->rq_size,
2615 ch->rsp_size, DMA_TO_DEVICE);
2620 rej->opcode = SRP_LOGIN_REJ;
2621 rej->tag = req->tag;
2622 rej->buf_fmt = cpu_to_be16(SRP_BUF_FORMAT_DIRECT
2623 | SRP_BUF_FORMAT_INDIRECT);
2625 ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0,
2626 (void *)rej, sizeof *rej);
2636 static void srpt_cm_rej_recv(struct ib_cm_id *cm_id)
2638 pr_info("Received IB REJ for cm_id %p.\n", cm_id);
2639 srpt_drain_channel(cm_id);
2643 * srpt_cm_rtu_recv() - Process an IB_CM_RTU_RECEIVED or USER_ESTABLISHED event.
2645 * An IB_CM_RTU_RECEIVED message indicates that the connection is established
2646 * and that the recipient may begin transmitting (RTU = ready to use).
2648 static void srpt_cm_rtu_recv(struct ib_cm_id *cm_id)
2650 struct srpt_rdma_ch *ch;
2653 ch = srpt_find_channel(cm_id->context, cm_id);
2656 if (srpt_test_and_set_ch_state(ch, CH_CONNECTING, CH_LIVE)) {
2657 struct srpt_recv_ioctx *ioctx, *ioctx_tmp;
2659 ret = srpt_ch_qp_rts(ch, ch->qp);
2661 list_for_each_entry_safe(ioctx, ioctx_tmp, &ch->cmd_wait_list,
2663 list_del(&ioctx->wait_list);
2664 srpt_handle_new_iu(ch, ioctx, NULL);
2671 static void srpt_cm_timewait_exit(struct ib_cm_id *cm_id)
2673 pr_info("Received IB TimeWait exit for cm_id %p.\n", cm_id);
2674 srpt_drain_channel(cm_id);
2677 static void srpt_cm_rep_error(struct ib_cm_id *cm_id)
2679 pr_info("Received IB REP error for cm_id %p.\n", cm_id);
2680 srpt_drain_channel(cm_id);
2684 * srpt_cm_dreq_recv() - Process reception of a DREQ message.
2686 static void srpt_cm_dreq_recv(struct ib_cm_id *cm_id)
2688 struct srpt_rdma_ch *ch;
2689 unsigned long flags;
2690 bool send_drep = false;
2692 ch = srpt_find_channel(cm_id->context, cm_id);
2695 pr_debug("cm_id= %p ch->state= %d\n", cm_id, srpt_get_ch_state(ch));
2697 spin_lock_irqsave(&ch->spinlock, flags);
2698 switch (ch->state) {
2702 ch->state = CH_DISCONNECTING;
2704 case CH_DISCONNECTING:
2707 WARN(true, "unexpected channel state %d\n", ch->state);
2710 spin_unlock_irqrestore(&ch->spinlock, flags);
2713 if (ib_send_cm_drep(ch->cm_id, NULL, 0) < 0)
2714 pr_err("Sending IB DREP failed.\n");
2715 pr_info("Received DREQ and sent DREP for session %s.\n",
2721 * srpt_cm_drep_recv() - Process reception of a DREP message.
2723 static void srpt_cm_drep_recv(struct ib_cm_id *cm_id)
2725 pr_info("Received InfiniBand DREP message for cm_id %p.\n", cm_id);
2726 srpt_drain_channel(cm_id);
2730 * srpt_cm_handler() - IB connection manager callback function.
2732 * A non-zero return value will cause the caller destroy the CM ID.
2734 * Note: srpt_cm_handler() must only return a non-zero value when transferring
2735 * ownership of the cm_id to a channel by srpt_cm_req_recv() failed. Returning
2736 * a non-zero value in any other case will trigger a race with the
2737 * ib_destroy_cm_id() call in srpt_release_channel().
2739 static int srpt_cm_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event)
2744 switch (event->event) {
2745 case IB_CM_REQ_RECEIVED:
2746 ret = srpt_cm_req_recv(cm_id, &event->param.req_rcvd,
2747 event->private_data);
2749 case IB_CM_REJ_RECEIVED:
2750 srpt_cm_rej_recv(cm_id);
2752 case IB_CM_RTU_RECEIVED:
2753 case IB_CM_USER_ESTABLISHED:
2754 srpt_cm_rtu_recv(cm_id);
2756 case IB_CM_DREQ_RECEIVED:
2757 srpt_cm_dreq_recv(cm_id);
2759 case IB_CM_DREP_RECEIVED:
2760 srpt_cm_drep_recv(cm_id);
2762 case IB_CM_TIMEWAIT_EXIT:
2763 srpt_cm_timewait_exit(cm_id);
2765 case IB_CM_REP_ERROR:
2766 srpt_cm_rep_error(cm_id);
2768 case IB_CM_DREQ_ERROR:
2769 pr_info("Received IB DREQ ERROR event.\n");
2771 case IB_CM_MRA_RECEIVED:
2772 pr_info("Received IB MRA event\n");
2775 pr_err("received unrecognized IB CM event %d\n", event->event);
2783 * srpt_perform_rdmas() - Perform IB RDMA.
2785 * Returns zero upon success or a negative number upon failure.
2787 static int srpt_perform_rdmas(struct srpt_rdma_ch *ch,
2788 struct srpt_send_ioctx *ioctx)
2790 struct ib_rdma_wr wr;
2791 struct ib_send_wr *bad_wr;
2792 struct rdma_iu *riu;
2796 enum dma_data_direction dir;
2797 const int n_rdma = ioctx->n_rdma;
2799 dir = ioctx->cmd.data_direction;
2800 if (dir == DMA_TO_DEVICE) {
2803 sq_wr_avail = atomic_sub_return(n_rdma, &ch->sq_wr_avail);
2804 if (sq_wr_avail < 0) {
2805 pr_warn("IB send queue full (needed %d)\n",
2811 ioctx->rdma_aborted = false;
2813 riu = ioctx->rdma_ius;
2814 memset(&wr, 0, sizeof wr);
2816 for (i = 0; i < n_rdma; ++i, ++riu) {
2817 if (dir == DMA_FROM_DEVICE) {
2818 wr.wr.opcode = IB_WR_RDMA_WRITE;
2819 wr.wr.wr_id = encode_wr_id(i == n_rdma - 1 ?
2820 SRPT_RDMA_WRITE_LAST :
2822 ioctx->ioctx.index);
2824 wr.wr.opcode = IB_WR_RDMA_READ;
2825 wr.wr.wr_id = encode_wr_id(i == n_rdma - 1 ?
2826 SRPT_RDMA_READ_LAST :
2828 ioctx->ioctx.index);
2831 wr.remote_addr = riu->raddr;
2832 wr.rkey = riu->rkey;
2833 wr.wr.num_sge = riu->sge_cnt;
2834 wr.wr.sg_list = riu->sge;
2836 /* only get completion event for the last rdma write */
2837 if (i == (n_rdma - 1) && dir == DMA_TO_DEVICE)
2838 wr.wr.send_flags = IB_SEND_SIGNALED;
2840 ret = ib_post_send(ch->qp, &wr.wr, &bad_wr);
2846 pr_err("%s[%d]: ib_post_send() returned %d for %d/%d\n",
2847 __func__, __LINE__, ret, i, n_rdma);
2850 wr.wr.wr_id = encode_wr_id(SRPT_RDMA_ABORT, ioctx->ioctx.index);
2851 wr.wr.send_flags = IB_SEND_SIGNALED;
2852 while (ch->state == CH_LIVE &&
2853 ib_post_send(ch->qp, &wr.wr, &bad_wr) != 0) {
2854 pr_info("Trying to abort failed RDMA transfer [%d]\n",
2855 ioctx->ioctx.index);
2858 while (ch->state != CH_RELEASING && !ioctx->rdma_aborted) {
2859 pr_info("Waiting until RDMA abort finished [%d]\n",
2860 ioctx->ioctx.index);
2865 if (unlikely(dir == DMA_TO_DEVICE && ret < 0))
2866 atomic_add(n_rdma, &ch->sq_wr_avail);
2871 * srpt_xfer_data() - Start data transfer from initiator to target.
2873 static int srpt_xfer_data(struct srpt_rdma_ch *ch,
2874 struct srpt_send_ioctx *ioctx)
2878 ret = srpt_map_sg_to_ib_sge(ch, ioctx);
2880 pr_err("%s[%d] ret=%d\n", __func__, __LINE__, ret);
2884 ret = srpt_perform_rdmas(ch, ioctx);
2886 if (ret == -EAGAIN || ret == -ENOMEM)
2887 pr_info("%s[%d] queue full -- ret=%d\n",
2888 __func__, __LINE__, ret);
2890 pr_err("%s[%d] fatal error -- ret=%d\n",
2891 __func__, __LINE__, ret);
2898 srpt_unmap_sg_to_ib_sge(ch, ioctx);
2902 static int srpt_write_pending_status(struct se_cmd *se_cmd)
2904 struct srpt_send_ioctx *ioctx;
2906 ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
2907 return srpt_get_cmd_state(ioctx) == SRPT_STATE_NEED_DATA;
2911 * srpt_write_pending() - Start data transfer from initiator to target (write).
2913 static int srpt_write_pending(struct se_cmd *se_cmd)
2915 struct srpt_rdma_ch *ch;
2916 struct srpt_send_ioctx *ioctx;
2917 enum srpt_command_state new_state;
2918 enum rdma_ch_state ch_state;
2921 ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
2923 new_state = srpt_set_cmd_state(ioctx, SRPT_STATE_NEED_DATA);
2924 WARN_ON(new_state == SRPT_STATE_DONE);
2929 ch_state = srpt_get_ch_state(ch);
2932 WARN(true, "unexpected channel state %d\n", ch_state);
2937 case CH_DISCONNECTING:
2940 pr_debug("cmd with tag %lld: channel disconnecting\n",
2942 srpt_set_cmd_state(ioctx, SRPT_STATE_DATA_IN);
2946 ret = srpt_xfer_data(ch, ioctx);
2952 static u8 tcm_to_srp_tsk_mgmt_status(const int tcm_mgmt_status)
2954 switch (tcm_mgmt_status) {
2955 case TMR_FUNCTION_COMPLETE:
2956 return SRP_TSK_MGMT_SUCCESS;
2957 case TMR_FUNCTION_REJECTED:
2958 return SRP_TSK_MGMT_FUNC_NOT_SUPP;
2960 return SRP_TSK_MGMT_FAILED;
2964 * srpt_queue_response() - Transmits the response to a SCSI command.
2966 * Callback function called by the TCM core. Must not block since it can be
2967 * invoked on the context of the IB completion handler.
2969 static void srpt_queue_response(struct se_cmd *cmd)
2971 struct srpt_rdma_ch *ch;
2972 struct srpt_send_ioctx *ioctx;
2973 enum srpt_command_state state;
2974 unsigned long flags;
2976 enum dma_data_direction dir;
2980 ioctx = container_of(cmd, struct srpt_send_ioctx, cmd);
2984 spin_lock_irqsave(&ioctx->spinlock, flags);
2985 state = ioctx->state;
2987 case SRPT_STATE_NEW:
2988 case SRPT_STATE_DATA_IN:
2989 ioctx->state = SRPT_STATE_CMD_RSP_SENT;
2991 case SRPT_STATE_MGMT:
2992 ioctx->state = SRPT_STATE_MGMT_RSP_SENT;
2995 WARN(true, "ch %p; cmd %d: unexpected command state %d\n",
2996 ch, ioctx->ioctx.index, ioctx->state);
2999 spin_unlock_irqrestore(&ioctx->spinlock, flags);
3001 if (unlikely(WARN_ON_ONCE(state == SRPT_STATE_CMD_RSP_SENT)))
3004 dir = ioctx->cmd.data_direction;
3006 /* For read commands, transfer the data to the initiator. */
3007 if (dir == DMA_FROM_DEVICE && ioctx->cmd.data_length &&
3008 !ioctx->queue_status_only) {
3009 ret = srpt_xfer_data(ch, ioctx);
3011 pr_err("xfer_data failed for tag %llu\n",
3017 if (state != SRPT_STATE_MGMT)
3018 resp_len = srpt_build_cmd_rsp(ch, ioctx, ioctx->cmd.tag,
3022 = tcm_to_srp_tsk_mgmt_status(cmd->se_tmr_req->response);
3023 resp_len = srpt_build_tskmgmt_rsp(ch, ioctx, srp_tm_status,
3026 ret = srpt_post_send(ch, ioctx, resp_len);
3028 pr_err("sending cmd response failed for tag %llu\n",
3030 srpt_unmap_sg_to_ib_sge(ch, ioctx);
3031 srpt_set_cmd_state(ioctx, SRPT_STATE_DONE);
3032 target_put_sess_cmd(&ioctx->cmd);
3036 static int srpt_queue_data_in(struct se_cmd *cmd)
3038 srpt_queue_response(cmd);
3042 static void srpt_queue_tm_rsp(struct se_cmd *cmd)
3044 srpt_queue_response(cmd);
3047 static void srpt_aborted_task(struct se_cmd *cmd)
3049 struct srpt_send_ioctx *ioctx = container_of(cmd,
3050 struct srpt_send_ioctx, cmd);
3052 srpt_unmap_sg_to_ib_sge(ioctx->ch, ioctx);
3055 static int srpt_queue_status(struct se_cmd *cmd)
3057 struct srpt_send_ioctx *ioctx;
3059 ioctx = container_of(cmd, struct srpt_send_ioctx, cmd);
3060 BUG_ON(ioctx->sense_data != cmd->sense_buffer);
3061 if (cmd->se_cmd_flags &
3062 (SCF_TRANSPORT_TASK_SENSE | SCF_EMULATED_TASK_SENSE))
3063 WARN_ON(cmd->scsi_status != SAM_STAT_CHECK_CONDITION);
3064 ioctx->queue_status_only = true;
3065 srpt_queue_response(cmd);
3069 static void srpt_refresh_port_work(struct work_struct *work)
3071 struct srpt_port *sport = container_of(work, struct srpt_port, work);
3073 srpt_refresh_port(sport);
3076 static int srpt_ch_list_empty(struct srpt_device *sdev)
3080 spin_lock_irq(&sdev->spinlock);
3081 res = list_empty(&sdev->rch_list);
3082 spin_unlock_irq(&sdev->spinlock);
3088 * srpt_release_sdev() - Free the channel resources associated with a target.
3090 static int srpt_release_sdev(struct srpt_device *sdev)
3092 struct srpt_rdma_ch *ch, *tmp_ch;
3095 WARN_ON_ONCE(irqs_disabled());
3099 spin_lock_irq(&sdev->spinlock);
3100 list_for_each_entry_safe(ch, tmp_ch, &sdev->rch_list, list)
3101 __srpt_close_ch(ch);
3102 spin_unlock_irq(&sdev->spinlock);
3104 res = wait_event_interruptible(sdev->ch_releaseQ,
3105 srpt_ch_list_empty(sdev));
3107 pr_err("%s: interrupted.\n", __func__);
3112 static struct srpt_port *__srpt_lookup_port(const char *name)
3114 struct ib_device *dev;
3115 struct srpt_device *sdev;
3116 struct srpt_port *sport;
3119 list_for_each_entry(sdev, &srpt_dev_list, list) {
3124 for (i = 0; i < dev->phys_port_cnt; i++) {
3125 sport = &sdev->port[i];
3127 if (!strcmp(sport->port_guid, name))
3135 static struct srpt_port *srpt_lookup_port(const char *name)
3137 struct srpt_port *sport;
3139 spin_lock(&srpt_dev_lock);
3140 sport = __srpt_lookup_port(name);
3141 spin_unlock(&srpt_dev_lock);
3147 * srpt_add_one() - Infiniband device addition callback function.
3149 static void srpt_add_one(struct ib_device *device)
3151 struct srpt_device *sdev;
3152 struct srpt_port *sport;
3153 struct ib_srq_init_attr srq_attr;
3156 pr_debug("device = %p, device->dma_ops = %p\n", device,
3159 sdev = kzalloc(sizeof *sdev, GFP_KERNEL);
3163 sdev->device = device;
3164 INIT_LIST_HEAD(&sdev->rch_list);
3165 init_waitqueue_head(&sdev->ch_releaseQ);
3166 spin_lock_init(&sdev->spinlock);
3168 if (ib_query_device(device, &sdev->dev_attr))
3171 sdev->pd = ib_alloc_pd(device);
3172 if (IS_ERR(sdev->pd))
3175 sdev->srq_size = min(srpt_srq_size, sdev->dev_attr.max_srq_wr);
3177 srq_attr.event_handler = srpt_srq_event;
3178 srq_attr.srq_context = (void *)sdev;
3179 srq_attr.attr.max_wr = sdev->srq_size;
3180 srq_attr.attr.max_sge = 1;
3181 srq_attr.attr.srq_limit = 0;
3182 srq_attr.srq_type = IB_SRQT_BASIC;
3184 sdev->srq = ib_create_srq(sdev->pd, &srq_attr);
3185 if (IS_ERR(sdev->srq))
3188 pr_debug("%s: create SRQ #wr= %d max_allow=%d dev= %s\n",
3189 __func__, sdev->srq_size, sdev->dev_attr.max_srq_wr,
3192 if (!srpt_service_guid)
3193 srpt_service_guid = be64_to_cpu(device->node_guid);
3195 sdev->cm_id = ib_create_cm_id(device, srpt_cm_handler, sdev);
3196 if (IS_ERR(sdev->cm_id))
3199 /* print out target login information */
3200 pr_debug("Target login info: id_ext=%016llx,ioc_guid=%016llx,"
3201 "pkey=ffff,service_id=%016llx\n", srpt_service_guid,
3202 srpt_service_guid, srpt_service_guid);
3205 * We do not have a consistent service_id (ie. also id_ext of target_id)
3206 * to identify this target. We currently use the guid of the first HCA
3207 * in the system as service_id; therefore, the target_id will change
3208 * if this HCA is gone bad and replaced by different HCA
3210 if (ib_cm_listen(sdev->cm_id, cpu_to_be64(srpt_service_guid), 0))
3213 INIT_IB_EVENT_HANDLER(&sdev->event_handler, sdev->device,
3214 srpt_event_handler);
3215 if (ib_register_event_handler(&sdev->event_handler))
3218 sdev->ioctx_ring = (struct srpt_recv_ioctx **)
3219 srpt_alloc_ioctx_ring(sdev, sdev->srq_size,
3220 sizeof(*sdev->ioctx_ring[0]),
3221 srp_max_req_size, DMA_FROM_DEVICE);
3222 if (!sdev->ioctx_ring)
3225 for (i = 0; i < sdev->srq_size; ++i)
3226 srpt_post_recv(sdev, sdev->ioctx_ring[i]);
3228 WARN_ON(sdev->device->phys_port_cnt > ARRAY_SIZE(sdev->port));
3230 for (i = 1; i <= sdev->device->phys_port_cnt; i++) {
3231 sport = &sdev->port[i - 1];
3234 sport->port_attrib.srp_max_rdma_size = DEFAULT_MAX_RDMA_SIZE;
3235 sport->port_attrib.srp_max_rsp_size = DEFAULT_MAX_RSP_SIZE;
3236 sport->port_attrib.srp_sq_size = DEF_SRPT_SQ_SIZE;
3237 INIT_WORK(&sport->work, srpt_refresh_port_work);
3238 INIT_LIST_HEAD(&sport->port_acl_list);
3239 spin_lock_init(&sport->port_acl_lock);
3241 if (srpt_refresh_port(sport)) {
3242 pr_err("MAD registration failed for %s-%d.\n",
3243 srpt_sdev_name(sdev), i);
3246 snprintf(sport->port_guid, sizeof(sport->port_guid),
3248 be64_to_cpu(sport->gid.global.subnet_prefix),
3249 be64_to_cpu(sport->gid.global.interface_id));
3252 spin_lock(&srpt_dev_lock);
3253 list_add_tail(&sdev->list, &srpt_dev_list);
3254 spin_unlock(&srpt_dev_lock);
3257 ib_set_client_data(device, &srpt_client, sdev);
3258 pr_debug("added %s.\n", device->name);
3262 srpt_free_ioctx_ring((struct srpt_ioctx **)sdev->ioctx_ring, sdev,
3263 sdev->srq_size, srp_max_req_size,
3266 ib_unregister_event_handler(&sdev->event_handler);
3268 ib_destroy_cm_id(sdev->cm_id);
3270 ib_destroy_srq(sdev->srq);
3272 ib_dealloc_pd(sdev->pd);
3277 pr_info("%s(%s) failed.\n", __func__, device->name);
3282 * srpt_remove_one() - InfiniBand device removal callback function.
3284 static void srpt_remove_one(struct ib_device *device, void *client_data)
3286 struct srpt_device *sdev = client_data;
3290 pr_info("%s(%s): nothing to do.\n", __func__, device->name);
3294 srpt_unregister_mad_agent(sdev);
3296 ib_unregister_event_handler(&sdev->event_handler);
3298 /* Cancel any work queued by the just unregistered IB event handler. */
3299 for (i = 0; i < sdev->device->phys_port_cnt; i++)
3300 cancel_work_sync(&sdev->port[i].work);
3302 ib_destroy_cm_id(sdev->cm_id);
3305 * Unregistering a target must happen after destroying sdev->cm_id
3306 * such that no new SRP_LOGIN_REQ information units can arrive while
3307 * destroying the target.
3309 spin_lock(&srpt_dev_lock);
3310 list_del(&sdev->list);
3311 spin_unlock(&srpt_dev_lock);
3312 srpt_release_sdev(sdev);
3314 ib_destroy_srq(sdev->srq);
3315 ib_dealloc_pd(sdev->pd);
3317 srpt_free_ioctx_ring((struct srpt_ioctx **)sdev->ioctx_ring, sdev,
3318 sdev->srq_size, srp_max_req_size, DMA_FROM_DEVICE);
3319 sdev->ioctx_ring = NULL;
3323 static struct ib_client srpt_client = {
3325 .add = srpt_add_one,
3326 .remove = srpt_remove_one
3329 static int srpt_check_true(struct se_portal_group *se_tpg)
3334 static int srpt_check_false(struct se_portal_group *se_tpg)
3339 static char *srpt_get_fabric_name(void)
3344 static char *srpt_get_fabric_wwn(struct se_portal_group *tpg)
3346 struct srpt_port *sport = container_of(tpg, struct srpt_port, port_tpg_1);
3348 return sport->port_guid;
3351 static u16 srpt_get_tag(struct se_portal_group *tpg)
3356 static u32 srpt_tpg_get_inst_index(struct se_portal_group *se_tpg)
3361 static void srpt_release_cmd(struct se_cmd *se_cmd)
3363 struct srpt_send_ioctx *ioctx = container_of(se_cmd,
3364 struct srpt_send_ioctx, cmd);
3365 struct srpt_rdma_ch *ch = ioctx->ch;
3366 unsigned long flags;
3368 WARN_ON(ioctx->state != SRPT_STATE_DONE);
3369 WARN_ON(ioctx->mapped_sg_count != 0);
3371 if (ioctx->n_rbuf > 1) {
3372 kfree(ioctx->rbufs);
3373 ioctx->rbufs = NULL;
3377 spin_lock_irqsave(&ch->spinlock, flags);
3378 list_add(&ioctx->free_list, &ch->free_list);
3379 spin_unlock_irqrestore(&ch->spinlock, flags);
3383 * srpt_close_session() - Forcibly close a session.
3385 * Callback function invoked by the TCM core to clean up sessions associated
3386 * with a node ACL when the user invokes
3387 * rmdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id
3389 static void srpt_close_session(struct se_session *se_sess)
3391 DECLARE_COMPLETION_ONSTACK(release_done);
3392 struct srpt_rdma_ch *ch;
3393 struct srpt_device *sdev;
3396 ch = se_sess->fabric_sess_ptr;
3397 WARN_ON(ch->sess != se_sess);
3399 pr_debug("ch %p state %d\n", ch, srpt_get_ch_state(ch));
3401 sdev = ch->sport->sdev;
3402 spin_lock_irq(&sdev->spinlock);
3403 BUG_ON(ch->release_done);
3404 ch->release_done = &release_done;
3405 __srpt_close_ch(ch);
3406 spin_unlock_irq(&sdev->spinlock);
3408 res = wait_for_completion_timeout(&release_done, 60 * HZ);
3413 * srpt_sess_get_index() - Return the value of scsiAttIntrPortIndex (SCSI-MIB).
3415 * A quote from RFC 4455 (SCSI-MIB) about this MIB object:
3416 * This object represents an arbitrary integer used to uniquely identify a
3417 * particular attached remote initiator port to a particular SCSI target port
3418 * within a particular SCSI target device within a particular SCSI instance.
3420 static u32 srpt_sess_get_index(struct se_session *se_sess)
3425 static void srpt_set_default_node_attrs(struct se_node_acl *nacl)
3429 /* Note: only used from inside debug printk's by the TCM core. */
3430 static int srpt_get_tcm_cmd_state(struct se_cmd *se_cmd)
3432 struct srpt_send_ioctx *ioctx;
3434 ioctx = container_of(se_cmd, struct srpt_send_ioctx, cmd);
3435 return srpt_get_cmd_state(ioctx);
3439 * srpt_parse_i_port_id() - Parse an initiator port ID.
3440 * @name: ASCII representation of a 128-bit initiator port ID.
3441 * @i_port_id: Binary 128-bit port ID.
3443 static int srpt_parse_i_port_id(u8 i_port_id[16], const char *name)
3446 unsigned len, count, leading_zero_bytes;
3450 if (strncasecmp(p, "0x", 2) == 0)
3456 count = min(len / 2, 16U);
3457 leading_zero_bytes = 16 - count;
3458 memset(i_port_id, 0, leading_zero_bytes);
3459 ret = hex2bin(i_port_id + leading_zero_bytes, p, count);
3461 pr_debug("hex2bin failed for srpt_parse_i_port_id: %d\n", ret);
3467 * configfs callback function invoked for
3468 * mkdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id
3470 static int srpt_init_nodeacl(struct se_node_acl *se_nacl, const char *name)
3472 struct srpt_port *sport =
3473 container_of(se_nacl->se_tpg, struct srpt_port, port_tpg_1);
3474 struct srpt_node_acl *nacl =
3475 container_of(se_nacl, struct srpt_node_acl, nacl);
3478 if (srpt_parse_i_port_id(i_port_id, name) < 0) {
3479 pr_err("invalid initiator port ID %s\n", name);
3483 memcpy(&nacl->i_port_id[0], &i_port_id[0], 16);
3484 nacl->sport = sport;
3486 spin_lock_irq(&sport->port_acl_lock);
3487 list_add_tail(&nacl->list, &sport->port_acl_list);
3488 spin_unlock_irq(&sport->port_acl_lock);
3494 * configfs callback function invoked for
3495 * rmdir /sys/kernel/config/target/$driver/$port/$tpg/acls/$i_port_id
3497 static void srpt_cleanup_nodeacl(struct se_node_acl *se_nacl)
3499 struct srpt_node_acl *nacl =
3500 container_of(se_nacl, struct srpt_node_acl, nacl);
3501 struct srpt_port *sport = nacl->sport;
3503 spin_lock_irq(&sport->port_acl_lock);
3504 list_del(&nacl->list);
3505 spin_unlock_irq(&sport->port_acl_lock);
3508 static ssize_t srpt_tpg_attrib_srp_max_rdma_size_show(struct config_item *item,
3511 struct se_portal_group *se_tpg = attrib_to_tpg(item);
3512 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3514 return sprintf(page, "%u\n", sport->port_attrib.srp_max_rdma_size);
3517 static ssize_t srpt_tpg_attrib_srp_max_rdma_size_store(struct config_item *item,
3518 const char *page, size_t count)
3520 struct se_portal_group *se_tpg = attrib_to_tpg(item);
3521 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3525 ret = kstrtoul(page, 0, &val);
3527 pr_err("kstrtoul() failed with ret: %d\n", ret);
3530 if (val > MAX_SRPT_RDMA_SIZE) {
3531 pr_err("val: %lu exceeds MAX_SRPT_RDMA_SIZE: %d\n", val,
3532 MAX_SRPT_RDMA_SIZE);
3535 if (val < DEFAULT_MAX_RDMA_SIZE) {
3536 pr_err("val: %lu smaller than DEFAULT_MAX_RDMA_SIZE: %d\n",
3537 val, DEFAULT_MAX_RDMA_SIZE);
3540 sport->port_attrib.srp_max_rdma_size = val;
3545 static ssize_t srpt_tpg_attrib_srp_max_rsp_size_show(struct config_item *item,
3548 struct se_portal_group *se_tpg = attrib_to_tpg(item);
3549 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3551 return sprintf(page, "%u\n", sport->port_attrib.srp_max_rsp_size);
3554 static ssize_t srpt_tpg_attrib_srp_max_rsp_size_store(struct config_item *item,
3555 const char *page, size_t count)
3557 struct se_portal_group *se_tpg = attrib_to_tpg(item);
3558 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3562 ret = kstrtoul(page, 0, &val);
3564 pr_err("kstrtoul() failed with ret: %d\n", ret);
3567 if (val > MAX_SRPT_RSP_SIZE) {
3568 pr_err("val: %lu exceeds MAX_SRPT_RSP_SIZE: %d\n", val,
3572 if (val < MIN_MAX_RSP_SIZE) {
3573 pr_err("val: %lu smaller than MIN_MAX_RSP_SIZE: %d\n", val,
3577 sport->port_attrib.srp_max_rsp_size = val;
3582 static ssize_t srpt_tpg_attrib_srp_sq_size_show(struct config_item *item,
3585 struct se_portal_group *se_tpg = attrib_to_tpg(item);
3586 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3588 return sprintf(page, "%u\n", sport->port_attrib.srp_sq_size);
3591 static ssize_t srpt_tpg_attrib_srp_sq_size_store(struct config_item *item,
3592 const char *page, size_t count)
3594 struct se_portal_group *se_tpg = attrib_to_tpg(item);
3595 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3599 ret = kstrtoul(page, 0, &val);
3601 pr_err("kstrtoul() failed with ret: %d\n", ret);
3604 if (val > MAX_SRPT_SRQ_SIZE) {
3605 pr_err("val: %lu exceeds MAX_SRPT_SRQ_SIZE: %d\n", val,
3609 if (val < MIN_SRPT_SRQ_SIZE) {
3610 pr_err("val: %lu smaller than MIN_SRPT_SRQ_SIZE: %d\n", val,
3614 sport->port_attrib.srp_sq_size = val;
3619 CONFIGFS_ATTR(srpt_tpg_attrib_, srp_max_rdma_size);
3620 CONFIGFS_ATTR(srpt_tpg_attrib_, srp_max_rsp_size);
3621 CONFIGFS_ATTR(srpt_tpg_attrib_, srp_sq_size);
3623 static struct configfs_attribute *srpt_tpg_attrib_attrs[] = {
3624 &srpt_tpg_attrib_attr_srp_max_rdma_size,
3625 &srpt_tpg_attrib_attr_srp_max_rsp_size,
3626 &srpt_tpg_attrib_attr_srp_sq_size,
3630 static ssize_t srpt_tpg_enable_show(struct config_item *item, char *page)
3632 struct se_portal_group *se_tpg = to_tpg(item);
3633 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3635 return snprintf(page, PAGE_SIZE, "%d\n", (sport->enabled) ? 1: 0);
3638 static ssize_t srpt_tpg_enable_store(struct config_item *item,
3639 const char *page, size_t count)
3641 struct se_portal_group *se_tpg = to_tpg(item);
3642 struct srpt_port *sport = container_of(se_tpg, struct srpt_port, port_tpg_1);
3646 ret = kstrtoul(page, 0, &tmp);
3648 pr_err("Unable to extract srpt_tpg_store_enable\n");
3652 if ((tmp != 0) && (tmp != 1)) {
3653 pr_err("Illegal value for srpt_tpg_store_enable: %lu\n", tmp);
3657 sport->enabled = true;
3659 sport->enabled = false;
3664 CONFIGFS_ATTR(srpt_tpg_, enable);
3666 static struct configfs_attribute *srpt_tpg_attrs[] = {
3667 &srpt_tpg_attr_enable,
3672 * configfs callback invoked for
3673 * mkdir /sys/kernel/config/target/$driver/$port/$tpg
3675 static struct se_portal_group *srpt_make_tpg(struct se_wwn *wwn,
3676 struct config_group *group,
3679 struct srpt_port *sport = container_of(wwn, struct srpt_port, port_wwn);
3682 /* Initialize sport->port_wwn and sport->port_tpg_1 */
3683 res = core_tpg_register(&sport->port_wwn, &sport->port_tpg_1, SCSI_PROTOCOL_SRP);
3685 return ERR_PTR(res);
3687 return &sport->port_tpg_1;
3691 * configfs callback invoked for
3692 * rmdir /sys/kernel/config/target/$driver/$port/$tpg
3694 static void srpt_drop_tpg(struct se_portal_group *tpg)
3696 struct srpt_port *sport = container_of(tpg,
3697 struct srpt_port, port_tpg_1);
3699 sport->enabled = false;
3700 core_tpg_deregister(&sport->port_tpg_1);
3704 * configfs callback invoked for
3705 * mkdir /sys/kernel/config/target/$driver/$port
3707 static struct se_wwn *srpt_make_tport(struct target_fabric_configfs *tf,
3708 struct config_group *group,
3711 struct srpt_port *sport;
3714 sport = srpt_lookup_port(name);
3715 pr_debug("make_tport(%s)\n", name);
3720 return &sport->port_wwn;
3723 return ERR_PTR(ret);
3727 * configfs callback invoked for
3728 * rmdir /sys/kernel/config/target/$driver/$port
3730 static void srpt_drop_tport(struct se_wwn *wwn)
3732 struct srpt_port *sport = container_of(wwn, struct srpt_port, port_wwn);
3734 pr_debug("drop_tport(%s\n", config_item_name(&sport->port_wwn.wwn_group.cg_item));
3737 static ssize_t srpt_wwn_version_show(struct config_item *item, char *buf)
3739 return scnprintf(buf, PAGE_SIZE, "%s\n", DRV_VERSION);
3742 CONFIGFS_ATTR_RO(srpt_wwn_, version);
3744 static struct configfs_attribute *srpt_wwn_attrs[] = {
3745 &srpt_wwn_attr_version,
3749 static const struct target_core_fabric_ops srpt_template = {
3750 .module = THIS_MODULE,
3752 .node_acl_size = sizeof(struct srpt_node_acl),
3753 .get_fabric_name = srpt_get_fabric_name,
3754 .tpg_get_wwn = srpt_get_fabric_wwn,
3755 .tpg_get_tag = srpt_get_tag,
3756 .tpg_check_demo_mode = srpt_check_false,
3757 .tpg_check_demo_mode_cache = srpt_check_true,
3758 .tpg_check_demo_mode_write_protect = srpt_check_true,
3759 .tpg_check_prod_mode_write_protect = srpt_check_false,
3760 .tpg_get_inst_index = srpt_tpg_get_inst_index,
3761 .release_cmd = srpt_release_cmd,
3762 .check_stop_free = srpt_check_stop_free,
3763 .shutdown_session = srpt_shutdown_session,
3764 .close_session = srpt_close_session,
3765 .sess_get_index = srpt_sess_get_index,
3766 .sess_get_initiator_sid = NULL,
3767 .write_pending = srpt_write_pending,
3768 .write_pending_status = srpt_write_pending_status,
3769 .set_default_node_attributes = srpt_set_default_node_attrs,
3770 .get_cmd_state = srpt_get_tcm_cmd_state,
3771 .queue_data_in = srpt_queue_data_in,
3772 .queue_status = srpt_queue_status,
3773 .queue_tm_rsp = srpt_queue_tm_rsp,
3774 .aborted_task = srpt_aborted_task,
3776 * Setup function pointers for generic logic in
3777 * target_core_fabric_configfs.c
3779 .fabric_make_wwn = srpt_make_tport,
3780 .fabric_drop_wwn = srpt_drop_tport,
3781 .fabric_make_tpg = srpt_make_tpg,
3782 .fabric_drop_tpg = srpt_drop_tpg,
3783 .fabric_init_nodeacl = srpt_init_nodeacl,
3784 .fabric_cleanup_nodeacl = srpt_cleanup_nodeacl,
3786 .tfc_wwn_attrs = srpt_wwn_attrs,
3787 .tfc_tpg_base_attrs = srpt_tpg_attrs,
3788 .tfc_tpg_attrib_attrs = srpt_tpg_attrib_attrs,
3792 * srpt_init_module() - Kernel module initialization.
3794 * Note: Since ib_register_client() registers callback functions, and since at
3795 * least one of these callback functions (srpt_add_one()) calls target core
3796 * functions, this driver must be registered with the target core before
3797 * ib_register_client() is called.
3799 static int __init srpt_init_module(void)
3804 if (srp_max_req_size < MIN_MAX_REQ_SIZE) {
3805 pr_err("invalid value %d for kernel module parameter"
3806 " srp_max_req_size -- must be at least %d.\n",
3807 srp_max_req_size, MIN_MAX_REQ_SIZE);
3811 if (srpt_srq_size < MIN_SRPT_SRQ_SIZE
3812 || srpt_srq_size > MAX_SRPT_SRQ_SIZE) {
3813 pr_err("invalid value %d for kernel module parameter"
3814 " srpt_srq_size -- must be in the range [%d..%d].\n",
3815 srpt_srq_size, MIN_SRPT_SRQ_SIZE, MAX_SRPT_SRQ_SIZE);
3819 ret = target_register_template(&srpt_template);
3823 ret = ib_register_client(&srpt_client);
3825 pr_err("couldn't register IB client\n");
3826 goto out_unregister_target;
3831 out_unregister_target:
3832 target_unregister_template(&srpt_template);
3837 static void __exit srpt_cleanup_module(void)
3839 ib_unregister_client(&srpt_client);
3840 target_unregister_template(&srpt_template);
3843 module_init(srpt_init_module);
3844 module_exit(srpt_cleanup_module);