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