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