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