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