1 /*******************************************************************************
2  * IBM Virtual SCSI Target Driver
3  * Copyright (C) 2003-2005 Dave Boutcher (boutcher@us.ibm.com) IBM Corp.
4  *			   Santiago Leon (santil@us.ibm.com) IBM Corp.
5  *			   Linda Xie (lxie@us.ibm.com) IBM Corp.
6  *
7  * Copyright (C) 2005-2011 FUJITA Tomonori <tomof@acm.org>
8  * Copyright (C) 2010 Nicholas A. Bellinger <nab@kernel.org>
9  *
10  * Authors: Bryant G. Ly <bryantly@linux.vnet.ibm.com>
11  * Authors: Michael Cyr <mikecyr@linux.vnet.ibm.com>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  ****************************************************************************/
24 
25 #define pr_fmt(fmt)	KBUILD_MODNAME ": " fmt
26 
27 #include <linux/module.h>
28 #include <linux/kernel.h>
29 #include <linux/slab.h>
30 #include <linux/types.h>
31 #include <linux/list.h>
32 #include <linux/string.h>
33 #include <linux/delay.h>
34 
35 #include <target/target_core_base.h>
36 #include <target/target_core_fabric.h>
37 
38 #include <asm/hvcall.h>
39 #include <asm/vio.h>
40 
41 #include <scsi/viosrp.h>
42 
43 #include "ibmvscsi_tgt.h"
44 
45 #define IBMVSCSIS_VERSION	"v0.2"
46 
47 #define	INITIAL_SRP_LIMIT	800
48 #define	DEFAULT_MAX_SECTORS	256
49 #define MAX_TXU			1024 * 1024
50 
51 static uint max_vdma_size = MAX_H_COPY_RDMA;
52 
53 static char system_id[SYS_ID_NAME_LEN] = "";
54 static char partition_name[PARTITION_NAMELEN] = "UNKNOWN";
55 static uint partition_number = -1;
56 
57 /* Adapter list and lock to control it */
58 static DEFINE_SPINLOCK(ibmvscsis_dev_lock);
59 static LIST_HEAD(ibmvscsis_dev_list);
60 
61 static long ibmvscsis_parse_command(struct scsi_info *vscsi,
62 				    struct viosrp_crq *crq);
63 
64 static void ibmvscsis_adapter_idle(struct scsi_info *vscsi);
65 
66 static void ibmvscsis_determine_resid(struct se_cmd *se_cmd,
67 				      struct srp_rsp *rsp)
68 {
69 	u32 residual_count = se_cmd->residual_count;
70 
71 	if (!residual_count)
72 		return;
73 
74 	if (se_cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
75 		if (se_cmd->data_direction == DMA_TO_DEVICE) {
76 			/* residual data from an underflow write */
77 			rsp->flags = SRP_RSP_FLAG_DOUNDER;
78 			rsp->data_out_res_cnt = cpu_to_be32(residual_count);
79 		} else if (se_cmd->data_direction == DMA_FROM_DEVICE) {
80 			/* residual data from an underflow read */
81 			rsp->flags = SRP_RSP_FLAG_DIUNDER;
82 			rsp->data_in_res_cnt = cpu_to_be32(residual_count);
83 		}
84 	} else if (se_cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
85 		if (se_cmd->data_direction == DMA_TO_DEVICE) {
86 			/* residual data from an overflow write */
87 			rsp->flags = SRP_RSP_FLAG_DOOVER;
88 			rsp->data_out_res_cnt = cpu_to_be32(residual_count);
89 		} else if (se_cmd->data_direction == DMA_FROM_DEVICE) {
90 			/* residual data from an overflow read */
91 			rsp->flags = SRP_RSP_FLAG_DIOVER;
92 			rsp->data_in_res_cnt = cpu_to_be32(residual_count);
93 		}
94 	}
95 }
96 
97 /**
98  * connection_broken() - Determine if the connection to the client is good
99  * @vscsi:	Pointer to our adapter structure
100  *
101  * This function attempts to send a ping MAD to the client. If the call to
102  * queue the request returns H_CLOSED then the connection has been broken
103  * and the function returns TRUE.
104  *
105  * EXECUTION ENVIRONMENT:
106  *	Interrupt or Process environment
107  */
108 static bool connection_broken(struct scsi_info *vscsi)
109 {
110 	struct viosrp_crq *crq;
111 	u64 buffer[2] = { 0, 0 };
112 	long h_return_code;
113 	bool rc = false;
114 
115 	/* create a PING crq */
116 	crq = (struct viosrp_crq *)&buffer;
117 	crq->valid = VALID_CMD_RESP_EL;
118 	crq->format = MESSAGE_IN_CRQ;
119 	crq->status = PING;
120 
121 	h_return_code = h_send_crq(vscsi->dds.unit_id,
122 				   cpu_to_be64(buffer[MSG_HI]),
123 				   cpu_to_be64(buffer[MSG_LOW]));
124 
125 	pr_debug("connection_broken: rc %ld\n", h_return_code);
126 
127 	if (h_return_code == H_CLOSED)
128 		rc = true;
129 
130 	return rc;
131 }
132 
133 /**
134  * ibmvscsis_unregister_command_q() - Helper Function-Unregister Command Queue
135  * @vscsi:	Pointer to our adapter structure
136  *
137  * This function calls h_free_q then frees the interrupt bit etc.
138  * It must release the lock before doing so because of the time it can take
139  * for h_free_crq in PHYP
140  * NOTE: the caller must make sure that state and or flags will prevent
141  *	 interrupt handler from scheduling work.
142  * NOTE: anyone calling this function may need to set the CRQ_CLOSED flag
143  *	 we can't do it here, because we don't have the lock
144  *
145  * EXECUTION ENVIRONMENT:
146  *	Process level
147  */
148 static long ibmvscsis_unregister_command_q(struct scsi_info *vscsi)
149 {
150 	long qrc;
151 	long rc = ADAPT_SUCCESS;
152 	int ticks = 0;
153 
154 	do {
155 		qrc = h_free_crq(vscsi->dds.unit_id);
156 		switch (qrc) {
157 		case H_SUCCESS:
158 			break;
159 
160 		case H_HARDWARE:
161 		case H_PARAMETER:
162 			dev_err(&vscsi->dev, "unregister_command_q: error from h_free_crq %ld\n",
163 				qrc);
164 			rc = ERROR;
165 			break;
166 
167 		case H_BUSY:
168 		case H_LONG_BUSY_ORDER_1_MSEC:
169 			/* msleep not good for small values */
170 			usleep_range(1000, 2000);
171 			ticks += 1;
172 			break;
173 		case H_LONG_BUSY_ORDER_10_MSEC:
174 			usleep_range(10000, 20000);
175 			ticks += 10;
176 			break;
177 		case H_LONG_BUSY_ORDER_100_MSEC:
178 			msleep(100);
179 			ticks += 100;
180 			break;
181 		case H_LONG_BUSY_ORDER_1_SEC:
182 			ssleep(1);
183 			ticks += 1000;
184 			break;
185 		case H_LONG_BUSY_ORDER_10_SEC:
186 			ssleep(10);
187 			ticks += 10000;
188 			break;
189 		case H_LONG_BUSY_ORDER_100_SEC:
190 			ssleep(100);
191 			ticks += 100000;
192 			break;
193 		default:
194 			dev_err(&vscsi->dev, "unregister_command_q: unknown error %ld from h_free_crq\n",
195 				qrc);
196 			rc = ERROR;
197 			break;
198 		}
199 
200 		/*
201 		 * dont wait more then 300 seconds
202 		 * ticks are in milliseconds more or less
203 		 */
204 		if (ticks > 300000 && qrc != H_SUCCESS) {
205 			rc = ERROR;
206 			dev_err(&vscsi->dev, "Excessive wait for h_free_crq\n");
207 		}
208 	} while (qrc != H_SUCCESS && rc == ADAPT_SUCCESS);
209 
210 	pr_debug("Freeing CRQ: phyp rc %ld, rc %ld\n", qrc, rc);
211 
212 	return rc;
213 }
214 
215 /**
216  * ibmvscsis_delete_client_info() - Helper function to Delete Client Info
217  * @vscsi:	Pointer to our adapter structure
218  * @client_closed:	True if client closed its queue
219  *
220  * Deletes information specific to the client when the client goes away
221  *
222  * EXECUTION ENVIRONMENT:
223  *	Interrupt or Process
224  */
225 static void ibmvscsis_delete_client_info(struct scsi_info *vscsi,
226 					 bool client_closed)
227 {
228 	vscsi->client_cap = 0;
229 
230 	/*
231 	 * Some things we don't want to clear if we're closing the queue,
232 	 * because some clients don't resend the host handshake when they
233 	 * get a transport event.
234 	 */
235 	if (client_closed)
236 		vscsi->client_data.os_type = 0;
237 }
238 
239 /**
240  * ibmvscsis_free_command_q() - Free Command Queue
241  * @vscsi:	Pointer to our adapter structure
242  *
243  * This function calls unregister_command_q, then clears interrupts and
244  * any pending interrupt acknowledgments associated with the command q.
245  * It also clears memory if there is no error.
246  *
247  * PHYP did not meet the PAPR architecture so that we must give up the
248  * lock. This causes a timing hole regarding state change.  To close the
249  * hole this routine does accounting on any change that occurred during
250  * the time the lock is not held.
251  * NOTE: must give up and then acquire the interrupt lock, the caller must
252  *	 make sure that state and or flags will prevent interrupt handler from
253  *	 scheduling work.
254  *
255  * EXECUTION ENVIRONMENT:
256  *	Process level, interrupt lock is held
257  */
258 static long ibmvscsis_free_command_q(struct scsi_info *vscsi)
259 {
260 	int bytes;
261 	u32 flags_under_lock;
262 	u16 state_under_lock;
263 	long rc = ADAPT_SUCCESS;
264 
265 	if (!(vscsi->flags & CRQ_CLOSED)) {
266 		vio_disable_interrupts(vscsi->dma_dev);
267 
268 		state_under_lock = vscsi->new_state;
269 		flags_under_lock = vscsi->flags;
270 		vscsi->phyp_acr_state = 0;
271 		vscsi->phyp_acr_flags = 0;
272 
273 		spin_unlock_bh(&vscsi->intr_lock);
274 		rc = ibmvscsis_unregister_command_q(vscsi);
275 		spin_lock_bh(&vscsi->intr_lock);
276 
277 		if (state_under_lock != vscsi->new_state)
278 			vscsi->phyp_acr_state = vscsi->new_state;
279 
280 		vscsi->phyp_acr_flags = ((~flags_under_lock) & vscsi->flags);
281 
282 		if (rc == ADAPT_SUCCESS) {
283 			bytes = vscsi->cmd_q.size * PAGE_SIZE;
284 			memset(vscsi->cmd_q.base_addr, 0, bytes);
285 			vscsi->cmd_q.index = 0;
286 			vscsi->flags |= CRQ_CLOSED;
287 
288 			ibmvscsis_delete_client_info(vscsi, false);
289 		}
290 
291 		pr_debug("free_command_q: flags 0x%x, state 0x%hx, acr_flags 0x%x, acr_state 0x%hx\n",
292 			 vscsi->flags, vscsi->state, vscsi->phyp_acr_flags,
293 			 vscsi->phyp_acr_state);
294 	}
295 	return rc;
296 }
297 
298 /**
299  * ibmvscsis_cmd_q_dequeue() - Get valid Command element
300  * @mask:	Mask to use in case index wraps
301  * @current_index:	Current index into command queue
302  * @base_addr:	Pointer to start of command queue
303  *
304  * Returns a pointer to a valid command element or NULL, if the command
305  * queue is empty
306  *
307  * EXECUTION ENVIRONMENT:
308  *	Interrupt environment, interrupt lock held
309  */
310 static struct viosrp_crq *ibmvscsis_cmd_q_dequeue(uint mask,
311 						  uint *current_index,
312 						  struct viosrp_crq *base_addr)
313 {
314 	struct viosrp_crq *ptr;
315 
316 	ptr = base_addr + *current_index;
317 
318 	if (ptr->valid) {
319 		*current_index = (*current_index + 1) & mask;
320 		dma_rmb();
321 	} else {
322 		ptr = NULL;
323 	}
324 
325 	return ptr;
326 }
327 
328 /**
329  * ibmvscsis_send_init_message() - send initialize message to the client
330  * @vscsi:	Pointer to our adapter structure
331  * @format:	Which Init Message format to send
332  *
333  * EXECUTION ENVIRONMENT:
334  *	Interrupt environment interrupt lock held
335  */
336 static long ibmvscsis_send_init_message(struct scsi_info *vscsi, u8 format)
337 {
338 	struct viosrp_crq *crq;
339 	u64 buffer[2] = { 0, 0 };
340 	long rc;
341 
342 	crq = (struct viosrp_crq *)&buffer;
343 	crq->valid = VALID_INIT_MSG;
344 	crq->format = format;
345 	rc = h_send_crq(vscsi->dds.unit_id, cpu_to_be64(buffer[MSG_HI]),
346 			cpu_to_be64(buffer[MSG_LOW]));
347 
348 	return rc;
349 }
350 
351 /**
352  * ibmvscsis_check_init_msg() - Check init message valid
353  * @vscsi:	Pointer to our adapter structure
354  * @format:	Pointer to return format of Init Message, if any.
355  *		Set to UNUSED_FORMAT if no Init Message in queue.
356  *
357  * Checks if an initialize message was queued by the initiatior
358  * after the queue was created and before the interrupt was enabled.
359  *
360  * EXECUTION ENVIRONMENT:
361  *	Process level only, interrupt lock held
362  */
363 static long ibmvscsis_check_init_msg(struct scsi_info *vscsi, uint *format)
364 {
365 	struct viosrp_crq *crq;
366 	long rc = ADAPT_SUCCESS;
367 
368 	crq = ibmvscsis_cmd_q_dequeue(vscsi->cmd_q.mask, &vscsi->cmd_q.index,
369 				      vscsi->cmd_q.base_addr);
370 	if (!crq) {
371 		*format = (uint)UNUSED_FORMAT;
372 	} else if (crq->valid == VALID_INIT_MSG && crq->format == INIT_MSG) {
373 		*format = (uint)INIT_MSG;
374 		crq->valid = INVALIDATE_CMD_RESP_EL;
375 		dma_rmb();
376 
377 		/*
378 		 * the caller has ensured no initialize message was
379 		 * sent after the queue was
380 		 * created so there should be no other message on the queue.
381 		 */
382 		crq = ibmvscsis_cmd_q_dequeue(vscsi->cmd_q.mask,
383 					      &vscsi->cmd_q.index,
384 					      vscsi->cmd_q.base_addr);
385 		if (crq) {
386 			*format = (uint)(crq->format);
387 			rc = ERROR;
388 			crq->valid = INVALIDATE_CMD_RESP_EL;
389 			dma_rmb();
390 		}
391 	} else {
392 		*format = (uint)(crq->format);
393 		rc = ERROR;
394 		crq->valid = INVALIDATE_CMD_RESP_EL;
395 		dma_rmb();
396 	}
397 
398 	return rc;
399 }
400 
401 /**
402  * ibmvscsis_disconnect() - Helper function to disconnect
403  * @work:	Pointer to work_struct, gives access to our adapter structure
404  *
405  * An error has occurred or the driver received a Transport event,
406  * and the driver is requesting that the command queue be de-registered
407  * in a safe manner. If there is no outstanding I/O then we can stop the
408  * queue. If we are restarting the queue it will be reflected in the
409  * the state of the adapter.
410  *
411  * EXECUTION ENVIRONMENT:
412  *	Process environment
413  */
414 static void ibmvscsis_disconnect(struct work_struct *work)
415 {
416 	struct scsi_info *vscsi = container_of(work, struct scsi_info,
417 					       proc_work);
418 	u16 new_state;
419 	bool wait_idle = false;
420 
421 	spin_lock_bh(&vscsi->intr_lock);
422 	new_state = vscsi->new_state;
423 	vscsi->new_state = 0;
424 
425 	pr_debug("disconnect: flags 0x%x, state 0x%hx\n", vscsi->flags,
426 		 vscsi->state);
427 
428 	/*
429 	 * check which state we are in and see if we
430 	 * should transitition to the new state
431 	 */
432 	switch (vscsi->state) {
433 	/* Should never be called while in this state. */
434 	case NO_QUEUE:
435 	/*
436 	 * Can never transition from this state;
437 	 * igonore errors and logout.
438 	 */
439 	case UNCONFIGURING:
440 		break;
441 
442 	/* can transition from this state to UNCONFIGURING */
443 	case ERR_DISCONNECT:
444 		if (new_state == UNCONFIGURING)
445 			vscsi->state = new_state;
446 		break;
447 
448 	/*
449 	 * Can transition from this state to to unconfiguring
450 	 * or err disconnect.
451 	 */
452 	case ERR_DISCONNECT_RECONNECT:
453 		switch (new_state) {
454 		case UNCONFIGURING:
455 		case ERR_DISCONNECT:
456 			vscsi->state = new_state;
457 			break;
458 
459 		case WAIT_IDLE:
460 			break;
461 		default:
462 			break;
463 		}
464 		break;
465 
466 	/* can transition from this state to UNCONFIGURING */
467 	case ERR_DISCONNECTED:
468 		if (new_state == UNCONFIGURING)
469 			vscsi->state = new_state;
470 		break;
471 
472 	case WAIT_ENABLED:
473 		switch (new_state) {
474 		case UNCONFIGURING:
475 			vscsi->state = new_state;
476 			vscsi->flags |= RESPONSE_Q_DOWN;
477 			vscsi->flags &= ~(SCHEDULE_DISCONNECT |
478 					  DISCONNECT_SCHEDULED);
479 			dma_rmb();
480 			if (vscsi->flags & CFG_SLEEPING) {
481 				vscsi->flags &= ~CFG_SLEEPING;
482 				complete(&vscsi->unconfig);
483 			}
484 			break;
485 
486 		/* should never happen */
487 		case ERR_DISCONNECT:
488 		case ERR_DISCONNECT_RECONNECT:
489 		case WAIT_IDLE:
490 			dev_err(&vscsi->dev, "disconnect: invalid state %d for WAIT_IDLE\n",
491 				vscsi->state);
492 			break;
493 		}
494 		break;
495 
496 	case WAIT_IDLE:
497 		switch (new_state) {
498 		case UNCONFIGURING:
499 			vscsi->flags |= RESPONSE_Q_DOWN;
500 			vscsi->state = new_state;
501 			vscsi->flags &= ~(SCHEDULE_DISCONNECT |
502 					  DISCONNECT_SCHEDULED);
503 			ibmvscsis_free_command_q(vscsi);
504 			break;
505 		case ERR_DISCONNECT:
506 		case ERR_DISCONNECT_RECONNECT:
507 			vscsi->state = new_state;
508 			break;
509 		}
510 		break;
511 
512 	/*
513 	 * Initiator has not done a successful srp login
514 	 * or has done a successful srp logout ( adapter was not
515 	 * busy). In the first case there can be responses queued
516 	 * waiting for space on the initiators response queue (MAD)
517 	 * The second case the adapter is idle. Assume the worse case,
518 	 * i.e. the second case.
519 	 */
520 	case WAIT_CONNECTION:
521 	case CONNECTED:
522 	case SRP_PROCESSING:
523 		wait_idle = true;
524 		vscsi->state = new_state;
525 		break;
526 
527 	/* can transition from this state to UNCONFIGURING */
528 	case UNDEFINED:
529 		if (new_state == UNCONFIGURING)
530 			vscsi->state = new_state;
531 		break;
532 	default:
533 		break;
534 	}
535 
536 	if (wait_idle) {
537 		pr_debug("disconnect start wait, active %d, sched %d\n",
538 			 (int)list_empty(&vscsi->active_q),
539 			 (int)list_empty(&vscsi->schedule_q));
540 		if (!list_empty(&vscsi->active_q) ||
541 		    !list_empty(&vscsi->schedule_q)) {
542 			vscsi->flags |= WAIT_FOR_IDLE;
543 			pr_debug("disconnect flags 0x%x\n", vscsi->flags);
544 			/*
545 			 * This routine is can not be called with the interrupt
546 			 * lock held.
547 			 */
548 			spin_unlock_bh(&vscsi->intr_lock);
549 			wait_for_completion(&vscsi->wait_idle);
550 			spin_lock_bh(&vscsi->intr_lock);
551 		}
552 		pr_debug("disconnect stop wait\n");
553 
554 		ibmvscsis_adapter_idle(vscsi);
555 	}
556 
557 	spin_unlock_bh(&vscsi->intr_lock);
558 }
559 
560 /**
561  * ibmvscsis_post_disconnect() - Schedule the disconnect
562  * @vscsi:	Pointer to our adapter structure
563  * @new_state:	State to move to after disconnecting
564  * @flag_bits:	Flags to turn on in adapter structure
565  *
566  * If it's already been scheduled, then see if we need to "upgrade"
567  * the new state (if the one passed in is more "severe" than the
568  * previous one).
569  *
570  * PRECONDITION:
571  *	interrupt lock is held
572  */
573 static void ibmvscsis_post_disconnect(struct scsi_info *vscsi, uint new_state,
574 				      uint flag_bits)
575 {
576 	uint state;
577 
578 	/* check the validity of the new state */
579 	switch (new_state) {
580 	case UNCONFIGURING:
581 	case ERR_DISCONNECT:
582 	case ERR_DISCONNECT_RECONNECT:
583 	case WAIT_IDLE:
584 		break;
585 
586 	default:
587 		dev_err(&vscsi->dev, "post_disconnect: Invalid new state %d\n",
588 			new_state);
589 		return;
590 	}
591 
592 	vscsi->flags |= flag_bits;
593 
594 	pr_debug("post_disconnect: new_state 0x%x, flag_bits 0x%x, vscsi->flags 0x%x, state %hx\n",
595 		 new_state, flag_bits, vscsi->flags, vscsi->state);
596 
597 	if (!(vscsi->flags & (DISCONNECT_SCHEDULED | SCHEDULE_DISCONNECT))) {
598 		vscsi->flags |= SCHEDULE_DISCONNECT;
599 		vscsi->new_state = new_state;
600 
601 		INIT_WORK(&vscsi->proc_work, ibmvscsis_disconnect);
602 		(void)queue_work(vscsi->work_q, &vscsi->proc_work);
603 	} else {
604 		if (vscsi->new_state)
605 			state = vscsi->new_state;
606 		else
607 			state = vscsi->state;
608 
609 		switch (state) {
610 		case NO_QUEUE:
611 		case UNCONFIGURING:
612 			break;
613 
614 		case ERR_DISCONNECTED:
615 		case ERR_DISCONNECT:
616 		case UNDEFINED:
617 			if (new_state == UNCONFIGURING)
618 				vscsi->new_state = new_state;
619 			break;
620 
621 		case ERR_DISCONNECT_RECONNECT:
622 			switch (new_state) {
623 			case UNCONFIGURING:
624 			case ERR_DISCONNECT:
625 				vscsi->new_state = new_state;
626 				break;
627 			default:
628 				break;
629 			}
630 			break;
631 
632 		case WAIT_ENABLED:
633 		case WAIT_IDLE:
634 		case WAIT_CONNECTION:
635 		case CONNECTED:
636 		case SRP_PROCESSING:
637 			vscsi->new_state = new_state;
638 			break;
639 
640 		default:
641 			break;
642 		}
643 	}
644 
645 	pr_debug("Leaving post_disconnect: flags 0x%x, new_state 0x%x\n",
646 		 vscsi->flags, vscsi->new_state);
647 }
648 
649 /**
650  * ibmvscsis_handle_init_compl_msg() - Respond to an Init Complete Message
651  * @vscsi:	Pointer to our adapter structure
652  *
653  * Must be called with interrupt lock held.
654  */
655 static long ibmvscsis_handle_init_compl_msg(struct scsi_info *vscsi)
656 {
657 	long rc = ADAPT_SUCCESS;
658 
659 	switch (vscsi->state) {
660 	case NO_QUEUE:
661 	case ERR_DISCONNECT:
662 	case ERR_DISCONNECT_RECONNECT:
663 	case ERR_DISCONNECTED:
664 	case UNCONFIGURING:
665 	case UNDEFINED:
666 		rc = ERROR;
667 		break;
668 
669 	case WAIT_CONNECTION:
670 		vscsi->state = CONNECTED;
671 		break;
672 
673 	case WAIT_IDLE:
674 	case SRP_PROCESSING:
675 	case CONNECTED:
676 	case WAIT_ENABLED:
677 	default:
678 		rc = ERROR;
679 		dev_err(&vscsi->dev, "init_msg: invalid state %d to get init compl msg\n",
680 			vscsi->state);
681 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
682 		break;
683 	}
684 
685 	return rc;
686 }
687 
688 /**
689  * ibmvscsis_handle_init_msg() - Respond to an Init Message
690  * @vscsi:	Pointer to our adapter structure
691  *
692  * Must be called with interrupt lock held.
693  */
694 static long ibmvscsis_handle_init_msg(struct scsi_info *vscsi)
695 {
696 	long rc = ADAPT_SUCCESS;
697 
698 	switch (vscsi->state) {
699 	case WAIT_CONNECTION:
700 		rc = ibmvscsis_send_init_message(vscsi, INIT_COMPLETE_MSG);
701 		switch (rc) {
702 		case H_SUCCESS:
703 			vscsi->state = CONNECTED;
704 			break;
705 
706 		case H_PARAMETER:
707 			dev_err(&vscsi->dev, "init_msg: failed to send, rc %ld\n",
708 				rc);
709 			ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT, 0);
710 			break;
711 
712 		case H_DROPPED:
713 			dev_err(&vscsi->dev, "init_msg: failed to send, rc %ld\n",
714 				rc);
715 			rc = ERROR;
716 			ibmvscsis_post_disconnect(vscsi,
717 						  ERR_DISCONNECT_RECONNECT, 0);
718 			break;
719 
720 		case H_CLOSED:
721 			pr_warn("init_msg: failed to send, rc %ld\n", rc);
722 			rc = 0;
723 			break;
724 		}
725 		break;
726 
727 	case UNDEFINED:
728 		rc = ERROR;
729 		break;
730 
731 	case UNCONFIGURING:
732 		break;
733 
734 	case WAIT_ENABLED:
735 	case CONNECTED:
736 	case SRP_PROCESSING:
737 	case WAIT_IDLE:
738 	case NO_QUEUE:
739 	case ERR_DISCONNECT:
740 	case ERR_DISCONNECT_RECONNECT:
741 	case ERR_DISCONNECTED:
742 	default:
743 		rc = ERROR;
744 		dev_err(&vscsi->dev, "init_msg: invalid state %d to get init msg\n",
745 			vscsi->state);
746 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
747 		break;
748 	}
749 
750 	return rc;
751 }
752 
753 /**
754  * ibmvscsis_init_msg() - Respond to an init message
755  * @vscsi:	Pointer to our adapter structure
756  * @crq:	Pointer to CRQ element containing the Init Message
757  *
758  * EXECUTION ENVIRONMENT:
759  *	Interrupt, interrupt lock held
760  */
761 static long ibmvscsis_init_msg(struct scsi_info *vscsi, struct viosrp_crq *crq)
762 {
763 	long rc = ADAPT_SUCCESS;
764 
765 	pr_debug("init_msg: state 0x%hx\n", vscsi->state);
766 
767 	rc = h_vioctl(vscsi->dds.unit_id, H_GET_PARTNER_INFO,
768 		      (u64)vscsi->map_ioba | ((u64)PAGE_SIZE << 32), 0, 0, 0,
769 		      0);
770 	if (rc == H_SUCCESS) {
771 		vscsi->client_data.partition_number =
772 			be64_to_cpu(*(u64 *)vscsi->map_buf);
773 		pr_debug("init_msg, part num %d\n",
774 			 vscsi->client_data.partition_number);
775 	} else {
776 		pr_debug("init_msg h_vioctl rc %ld\n", rc);
777 		rc = ADAPT_SUCCESS;
778 	}
779 
780 	if (crq->format == INIT_MSG) {
781 		rc = ibmvscsis_handle_init_msg(vscsi);
782 	} else if (crq->format == INIT_COMPLETE_MSG) {
783 		rc = ibmvscsis_handle_init_compl_msg(vscsi);
784 	} else {
785 		rc = ERROR;
786 		dev_err(&vscsi->dev, "init_msg: invalid format %d\n",
787 			(uint)crq->format);
788 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
789 	}
790 
791 	return rc;
792 }
793 
794 /**
795  * ibmvscsis_establish_new_q() - Establish new CRQ queue
796  * @vscsi:	Pointer to our adapter structure
797  *
798  * Must be called with interrupt lock held.
799  */
800 static long ibmvscsis_establish_new_q(struct scsi_info *vscsi)
801 {
802 	long rc = ADAPT_SUCCESS;
803 	uint format;
804 
805 	vscsi->flags &= PRESERVE_FLAG_FIELDS;
806 	vscsi->rsp_q_timer.timer_pops = 0;
807 	vscsi->debit = 0;
808 	vscsi->credit = 0;
809 
810 	rc = vio_enable_interrupts(vscsi->dma_dev);
811 	if (rc) {
812 		pr_warn("establish_new_q: failed to enable interrupts, rc %ld\n",
813 			rc);
814 		return rc;
815 	}
816 
817 	rc = ibmvscsis_check_init_msg(vscsi, &format);
818 	if (rc) {
819 		dev_err(&vscsi->dev, "establish_new_q: check_init_msg failed, rc %ld\n",
820 			rc);
821 		return rc;
822 	}
823 
824 	if (format == UNUSED_FORMAT) {
825 		rc = ibmvscsis_send_init_message(vscsi, INIT_MSG);
826 		switch (rc) {
827 		case H_SUCCESS:
828 		case H_DROPPED:
829 		case H_CLOSED:
830 			rc = ADAPT_SUCCESS;
831 			break;
832 
833 		case H_PARAMETER:
834 		case H_HARDWARE:
835 			break;
836 
837 		default:
838 			vscsi->state = UNDEFINED;
839 			rc = H_HARDWARE;
840 			break;
841 		}
842 	} else if (format == INIT_MSG) {
843 		rc = ibmvscsis_handle_init_msg(vscsi);
844 	}
845 
846 	return rc;
847 }
848 
849 /**
850  * ibmvscsis_reset_queue() - Reset CRQ Queue
851  * @vscsi:	Pointer to our adapter structure
852  *
853  * This function calls h_free_q and then calls h_reg_q and does all
854  * of the bookkeeping to get us back to where we can communicate.
855  *
856  * Actually, we don't always call h_free_crq.  A problem was discovered
857  * where one partition would close and reopen his queue, which would
858  * cause his partner to get a transport event, which would cause him to
859  * close and reopen his queue, which would cause the original partition
860  * to get a transport event, etc., etc.  To prevent this, we don't
861  * actually close our queue if the client initiated the reset, (i.e.
862  * either we got a transport event or we have detected that the client's
863  * queue is gone)
864  *
865  * EXECUTION ENVIRONMENT:
866  *	Process environment, called with interrupt lock held
867  */
868 static void ibmvscsis_reset_queue(struct scsi_info *vscsi)
869 {
870 	int bytes;
871 	long rc = ADAPT_SUCCESS;
872 
873 	pr_debug("reset_queue: flags 0x%x\n", vscsi->flags);
874 
875 	/* don't reset, the client did it for us */
876 	if (vscsi->flags & (CLIENT_FAILED | TRANS_EVENT)) {
877 		vscsi->flags &= PRESERVE_FLAG_FIELDS;
878 		vscsi->rsp_q_timer.timer_pops = 0;
879 		vscsi->debit = 0;
880 		vscsi->credit = 0;
881 		vscsi->state = WAIT_CONNECTION;
882 		vio_enable_interrupts(vscsi->dma_dev);
883 	} else {
884 		rc = ibmvscsis_free_command_q(vscsi);
885 		if (rc == ADAPT_SUCCESS) {
886 			vscsi->state = WAIT_CONNECTION;
887 
888 			bytes = vscsi->cmd_q.size * PAGE_SIZE;
889 			rc = h_reg_crq(vscsi->dds.unit_id,
890 				       vscsi->cmd_q.crq_token, bytes);
891 			if (rc == H_CLOSED || rc == H_SUCCESS) {
892 				rc = ibmvscsis_establish_new_q(vscsi);
893 			}
894 
895 			if (rc != ADAPT_SUCCESS) {
896 				pr_debug("reset_queue: reg_crq rc %ld\n", rc);
897 
898 				vscsi->state = ERR_DISCONNECTED;
899 				vscsi->flags |= RESPONSE_Q_DOWN;
900 				ibmvscsis_free_command_q(vscsi);
901 			}
902 		} else {
903 			vscsi->state = ERR_DISCONNECTED;
904 			vscsi->flags |= RESPONSE_Q_DOWN;
905 		}
906 	}
907 }
908 
909 /**
910  * ibmvscsis_free_cmd_resources() - Free command resources
911  * @vscsi:	Pointer to our adapter structure
912  * @cmd:	Command which is not longer in use
913  *
914  * Must be called with interrupt lock held.
915  */
916 static void ibmvscsis_free_cmd_resources(struct scsi_info *vscsi,
917 					 struct ibmvscsis_cmd *cmd)
918 {
919 	struct iu_entry *iue = cmd->iue;
920 
921 	switch (cmd->type) {
922 	case TASK_MANAGEMENT:
923 	case SCSI_CDB:
924 		/*
925 		 * When the queue goes down this value is cleared, so it
926 		 * cannot be cleared in this general purpose function.
927 		 */
928 		if (vscsi->debit)
929 			vscsi->debit -= 1;
930 		break;
931 	case ADAPTER_MAD:
932 		vscsi->flags &= ~PROCESSING_MAD;
933 		break;
934 	case UNSET_TYPE:
935 		break;
936 	default:
937 		dev_err(&vscsi->dev, "free_cmd_resources unknown type %d\n",
938 			cmd->type);
939 		break;
940 	}
941 
942 	cmd->iue = NULL;
943 	list_add_tail(&cmd->list, &vscsi->free_cmd);
944 	srp_iu_put(iue);
945 
946 	if (list_empty(&vscsi->active_q) && list_empty(&vscsi->schedule_q) &&
947 	    list_empty(&vscsi->waiting_rsp) && (vscsi->flags & WAIT_FOR_IDLE)) {
948 		vscsi->flags &= ~WAIT_FOR_IDLE;
949 		complete(&vscsi->wait_idle);
950 	}
951 }
952 
953 /**
954  * ibmvscsis_trans_event() - Handle a Transport Event
955  * @vscsi:	Pointer to our adapter structure
956  * @crq:	Pointer to CRQ entry containing the Transport Event
957  *
958  * Do the logic to close the I_T nexus.  This function may not
959  * behave to specification.
960  *
961  * EXECUTION ENVIRONMENT:
962  *	Interrupt, interrupt lock held
963  */
964 static long ibmvscsis_trans_event(struct scsi_info *vscsi,
965 				  struct viosrp_crq *crq)
966 {
967 	long rc = ADAPT_SUCCESS;
968 
969 	pr_debug("trans_event: format %d, flags 0x%x, state 0x%hx\n",
970 		 (int)crq->format, vscsi->flags, vscsi->state);
971 
972 	switch (crq->format) {
973 	case MIGRATED:
974 	case PARTNER_FAILED:
975 	case PARTNER_DEREGISTER:
976 		ibmvscsis_delete_client_info(vscsi, true);
977 		break;
978 
979 	default:
980 		rc = ERROR;
981 		dev_err(&vscsi->dev, "trans_event: invalid format %d\n",
982 			(uint)crq->format);
983 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT,
984 					  RESPONSE_Q_DOWN);
985 		break;
986 	}
987 
988 	if (rc == ADAPT_SUCCESS) {
989 		switch (vscsi->state) {
990 		case NO_QUEUE:
991 		case ERR_DISCONNECTED:
992 		case UNDEFINED:
993 			break;
994 
995 		case UNCONFIGURING:
996 			vscsi->flags |= (RESPONSE_Q_DOWN | TRANS_EVENT);
997 			break;
998 
999 		case WAIT_ENABLED:
1000 			break;
1001 
1002 		case WAIT_CONNECTION:
1003 			break;
1004 
1005 		case CONNECTED:
1006 			ibmvscsis_post_disconnect(vscsi, WAIT_IDLE,
1007 						  (RESPONSE_Q_DOWN |
1008 						   TRANS_EVENT));
1009 			break;
1010 
1011 		case SRP_PROCESSING:
1012 			if ((vscsi->debit > 0) ||
1013 			    !list_empty(&vscsi->schedule_q) ||
1014 			    !list_empty(&vscsi->waiting_rsp) ||
1015 			    !list_empty(&vscsi->active_q)) {
1016 				pr_debug("debit %d, sched %d, wait %d, active %d\n",
1017 					 vscsi->debit,
1018 					 (int)list_empty(&vscsi->schedule_q),
1019 					 (int)list_empty(&vscsi->waiting_rsp),
1020 					 (int)list_empty(&vscsi->active_q));
1021 				pr_warn("connection lost with outstanding work\n");
1022 			} else {
1023 				pr_debug("trans_event: SRP Processing, but no outstanding work\n");
1024 			}
1025 
1026 			ibmvscsis_post_disconnect(vscsi, WAIT_IDLE,
1027 						  (RESPONSE_Q_DOWN |
1028 						   TRANS_EVENT));
1029 			break;
1030 
1031 		case ERR_DISCONNECT:
1032 		case ERR_DISCONNECT_RECONNECT:
1033 		case WAIT_IDLE:
1034 			vscsi->flags |= (RESPONSE_Q_DOWN | TRANS_EVENT);
1035 			break;
1036 		}
1037 	}
1038 
1039 	rc = vscsi->flags & SCHEDULE_DISCONNECT;
1040 
1041 	pr_debug("Leaving trans_event: flags 0x%x, state 0x%hx, rc %ld\n",
1042 		 vscsi->flags, vscsi->state, rc);
1043 
1044 	return rc;
1045 }
1046 
1047 /**
1048  * ibmvscsis_poll_cmd_q() - Poll Command Queue
1049  * @vscsi:	Pointer to our adapter structure
1050  *
1051  * Called to handle command elements that may have arrived while
1052  * interrupts were disabled.
1053  *
1054  * EXECUTION ENVIRONMENT:
1055  *	intr_lock must be held
1056  */
1057 static void ibmvscsis_poll_cmd_q(struct scsi_info *vscsi)
1058 {
1059 	struct viosrp_crq *crq;
1060 	long rc;
1061 	bool ack = true;
1062 	volatile u8 valid;
1063 
1064 	pr_debug("poll_cmd_q: flags 0x%x, state 0x%hx, q index %ud\n",
1065 		 vscsi->flags, vscsi->state, vscsi->cmd_q.index);
1066 
1067 	rc = vscsi->flags & SCHEDULE_DISCONNECT;
1068 	crq = vscsi->cmd_q.base_addr + vscsi->cmd_q.index;
1069 	valid = crq->valid;
1070 	dma_rmb();
1071 
1072 	while (valid) {
1073 poll_work:
1074 		vscsi->cmd_q.index =
1075 			(vscsi->cmd_q.index + 1) & vscsi->cmd_q.mask;
1076 
1077 		if (!rc) {
1078 			rc = ibmvscsis_parse_command(vscsi, crq);
1079 		} else {
1080 			if ((uint)crq->valid == VALID_TRANS_EVENT) {
1081 				/*
1082 				 * must service the transport layer events even
1083 				 * in an error state, dont break out until all
1084 				 * the consecutive transport events have been
1085 				 * processed
1086 				 */
1087 				rc = ibmvscsis_trans_event(vscsi, crq);
1088 			} else if (vscsi->flags & TRANS_EVENT) {
1089 				/*
1090 				 * if a tranport event has occurred leave
1091 				 * everything but transport events on the queue
1092 				 */
1093 				pr_debug("poll_cmd_q, ignoring\n");
1094 
1095 				/*
1096 				 * need to decrement the queue index so we can
1097 				 * look at the elment again
1098 				 */
1099 				if (vscsi->cmd_q.index)
1100 					vscsi->cmd_q.index -= 1;
1101 				else
1102 					/*
1103 					 * index is at 0 it just wrapped.
1104 					 * have it index last element in q
1105 					 */
1106 					vscsi->cmd_q.index = vscsi->cmd_q.mask;
1107 				break;
1108 			}
1109 		}
1110 
1111 		crq->valid = INVALIDATE_CMD_RESP_EL;
1112 
1113 		crq = vscsi->cmd_q.base_addr + vscsi->cmd_q.index;
1114 		valid = crq->valid;
1115 		dma_rmb();
1116 	}
1117 
1118 	if (!rc) {
1119 		if (ack) {
1120 			vio_enable_interrupts(vscsi->dma_dev);
1121 			ack = false;
1122 			pr_debug("poll_cmd_q, reenabling interrupts\n");
1123 		}
1124 		valid = crq->valid;
1125 		dma_rmb();
1126 		if (valid)
1127 			goto poll_work;
1128 	}
1129 
1130 	pr_debug("Leaving poll_cmd_q: rc %ld\n", rc);
1131 }
1132 
1133 /**
1134  * ibmvscsis_free_cmd_qs() - Free elements in queue
1135  * @vscsi:	Pointer to our adapter structure
1136  *
1137  * Free all of the elements on all queues that are waiting for
1138  * whatever reason.
1139  *
1140  * PRECONDITION:
1141  *	Called with interrupt lock held
1142  */
1143 static void ibmvscsis_free_cmd_qs(struct scsi_info *vscsi)
1144 {
1145 	struct ibmvscsis_cmd *cmd, *nxt;
1146 
1147 	pr_debug("free_cmd_qs: waiting_rsp empty %d, timer starter %d\n",
1148 		 (int)list_empty(&vscsi->waiting_rsp),
1149 		 vscsi->rsp_q_timer.started);
1150 
1151 	list_for_each_entry_safe(cmd, nxt, &vscsi->waiting_rsp, list) {
1152 		list_del(&cmd->list);
1153 		ibmvscsis_free_cmd_resources(vscsi, cmd);
1154 	}
1155 }
1156 
1157 /**
1158  * ibmvscsis_get_free_cmd() - Get free command from list
1159  * @vscsi:	Pointer to our adapter structure
1160  *
1161  * Must be called with interrupt lock held.
1162  */
1163 static struct ibmvscsis_cmd *ibmvscsis_get_free_cmd(struct scsi_info *vscsi)
1164 {
1165 	struct ibmvscsis_cmd *cmd = NULL;
1166 	struct iu_entry *iue;
1167 
1168 	iue = srp_iu_get(&vscsi->target);
1169 	if (iue) {
1170 		cmd = list_first_entry_or_null(&vscsi->free_cmd,
1171 					       struct ibmvscsis_cmd, list);
1172 		if (cmd) {
1173 			cmd->flags &= ~(DELAY_SEND);
1174 			list_del(&cmd->list);
1175 			cmd->iue = iue;
1176 			cmd->type = UNSET_TYPE;
1177 			memset(&cmd->se_cmd, 0, sizeof(cmd->se_cmd));
1178 		} else {
1179 			srp_iu_put(iue);
1180 		}
1181 	}
1182 
1183 	return cmd;
1184 }
1185 
1186 /**
1187  * ibmvscsis_adapter_idle() - Helper function to handle idle adapter
1188  * @vscsi:	Pointer to our adapter structure
1189  *
1190  * This function is called when the adapter is idle when the driver
1191  * is attempting to clear an error condition.
1192  * The adapter is considered busy if any of its cmd queues
1193  * are non-empty. This function can be invoked
1194  * from the off level disconnect function.
1195  *
1196  * EXECUTION ENVIRONMENT:
1197  *	Process environment called with interrupt lock held
1198  */
1199 static void ibmvscsis_adapter_idle(struct scsi_info *vscsi)
1200 {
1201 	int free_qs = false;
1202 
1203 	pr_debug("adapter_idle: flags 0x%x, state 0x%hx\n", vscsi->flags,
1204 		 vscsi->state);
1205 
1206 	/* Only need to free qs if we're disconnecting from client */
1207 	if (vscsi->state != WAIT_CONNECTION || vscsi->flags & TRANS_EVENT)
1208 		free_qs = true;
1209 
1210 	switch (vscsi->state) {
1211 	case UNCONFIGURING:
1212 		ibmvscsis_free_command_q(vscsi);
1213 		dma_rmb();
1214 		isync();
1215 		if (vscsi->flags & CFG_SLEEPING) {
1216 			vscsi->flags &= ~CFG_SLEEPING;
1217 			complete(&vscsi->unconfig);
1218 		}
1219 		break;
1220 	case ERR_DISCONNECT_RECONNECT:
1221 		ibmvscsis_reset_queue(vscsi);
1222 		pr_debug("adapter_idle, disc_rec: flags 0x%x\n", vscsi->flags);
1223 		break;
1224 
1225 	case ERR_DISCONNECT:
1226 		ibmvscsis_free_command_q(vscsi);
1227 		vscsi->flags &= ~(SCHEDULE_DISCONNECT | DISCONNECT_SCHEDULED);
1228 		vscsi->flags |= RESPONSE_Q_DOWN;
1229 		if (vscsi->tport.enabled)
1230 			vscsi->state = ERR_DISCONNECTED;
1231 		else
1232 			vscsi->state = WAIT_ENABLED;
1233 		pr_debug("adapter_idle, disc: flags 0x%x, state 0x%hx\n",
1234 			 vscsi->flags, vscsi->state);
1235 		break;
1236 
1237 	case WAIT_IDLE:
1238 		vscsi->rsp_q_timer.timer_pops = 0;
1239 		vscsi->debit = 0;
1240 		vscsi->credit = 0;
1241 		if (vscsi->flags & TRANS_EVENT) {
1242 			vscsi->state = WAIT_CONNECTION;
1243 			vscsi->flags &= PRESERVE_FLAG_FIELDS;
1244 		} else {
1245 			vscsi->state = CONNECTED;
1246 			vscsi->flags &= ~DISCONNECT_SCHEDULED;
1247 		}
1248 
1249 		pr_debug("adapter_idle, wait: flags 0x%x, state 0x%hx\n",
1250 			 vscsi->flags, vscsi->state);
1251 		ibmvscsis_poll_cmd_q(vscsi);
1252 		break;
1253 
1254 	case ERR_DISCONNECTED:
1255 		vscsi->flags &= ~DISCONNECT_SCHEDULED;
1256 		pr_debug("adapter_idle, disconnected: flags 0x%x, state 0x%hx\n",
1257 			 vscsi->flags, vscsi->state);
1258 		break;
1259 
1260 	default:
1261 		dev_err(&vscsi->dev, "adapter_idle: in invalid state %d\n",
1262 			vscsi->state);
1263 		break;
1264 	}
1265 
1266 	if (free_qs)
1267 		ibmvscsis_free_cmd_qs(vscsi);
1268 
1269 	/*
1270 	 * There is a timing window where we could lose a disconnect request.
1271 	 * The known path to this window occurs during the DISCONNECT_RECONNECT
1272 	 * case above: reset_queue calls free_command_q, which will release the
1273 	 * interrupt lock.  During that time, a new post_disconnect call can be
1274 	 * made with a "more severe" state (DISCONNECT or UNCONFIGURING).
1275 	 * Because the DISCONNECT_SCHEDULED flag is already set, post_disconnect
1276 	 * will only set the new_state.  Now free_command_q reacquires the intr
1277 	 * lock and clears the DISCONNECT_SCHEDULED flag (using PRESERVE_FLAG_
1278 	 * FIELDS), and the disconnect is lost.  This is particularly bad when
1279 	 * the new disconnect was for UNCONFIGURING, since the unconfigure hangs
1280 	 * forever.
1281 	 * Fix is that free command queue sets acr state and acr flags if there
1282 	 * is a change under the lock
1283 	 * note free command queue writes to this state it clears it
1284 	 * before releasing the lock, different drivers call the free command
1285 	 * queue different times so dont initialize above
1286 	 */
1287 	if (vscsi->phyp_acr_state != 0)	{
1288 		/*
1289 		 * set any bits in flags that may have been cleared by
1290 		 * a call to free command queue in switch statement
1291 		 * or reset queue
1292 		 */
1293 		vscsi->flags |= vscsi->phyp_acr_flags;
1294 		ibmvscsis_post_disconnect(vscsi, vscsi->phyp_acr_state, 0);
1295 		vscsi->phyp_acr_state = 0;
1296 		vscsi->phyp_acr_flags = 0;
1297 
1298 		pr_debug("adapter_idle: flags 0x%x, state 0x%hx, acr_flags 0x%x, acr_state 0x%hx\n",
1299 			 vscsi->flags, vscsi->state, vscsi->phyp_acr_flags,
1300 			 vscsi->phyp_acr_state);
1301 	}
1302 
1303 	pr_debug("Leaving adapter_idle: flags 0x%x, state 0x%hx, new_state 0x%x\n",
1304 		 vscsi->flags, vscsi->state, vscsi->new_state);
1305 }
1306 
1307 /**
1308  * ibmvscsis_copy_crq_packet() - Copy CRQ Packet
1309  * @vscsi:	Pointer to our adapter structure
1310  * @cmd:	Pointer to command element to use to process the request
1311  * @crq:	Pointer to CRQ entry containing the request
1312  *
1313  * Copy the srp information unit from the hosted
1314  * partition using remote dma
1315  *
1316  * EXECUTION ENVIRONMENT:
1317  *	Interrupt, interrupt lock held
1318  */
1319 static long ibmvscsis_copy_crq_packet(struct scsi_info *vscsi,
1320 				      struct ibmvscsis_cmd *cmd,
1321 				      struct viosrp_crq *crq)
1322 {
1323 	struct iu_entry *iue = cmd->iue;
1324 	long rc = 0;
1325 	u16 len;
1326 
1327 	len = be16_to_cpu(crq->IU_length);
1328 	if ((len > SRP_MAX_IU_LEN) || (len == 0)) {
1329 		dev_err(&vscsi->dev, "copy_crq: Invalid len %d passed", len);
1330 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
1331 		return SRP_VIOLATION;
1332 	}
1333 
1334 	rc = h_copy_rdma(len, vscsi->dds.window[REMOTE].liobn,
1335 			 be64_to_cpu(crq->IU_data_ptr),
1336 			 vscsi->dds.window[LOCAL].liobn, iue->sbuf->dma);
1337 
1338 	switch (rc) {
1339 	case H_SUCCESS:
1340 		cmd->init_time = mftb();
1341 		iue->remote_token = crq->IU_data_ptr;
1342 		iue->iu_len = len;
1343 		pr_debug("copy_crq: ioba 0x%llx, init_time 0x%llx\n",
1344 			 be64_to_cpu(crq->IU_data_ptr), cmd->init_time);
1345 		break;
1346 	case H_PERMISSION:
1347 		if (connection_broken(vscsi))
1348 			ibmvscsis_post_disconnect(vscsi,
1349 						  ERR_DISCONNECT_RECONNECT,
1350 						  (RESPONSE_Q_DOWN |
1351 						   CLIENT_FAILED));
1352 		else
1353 			ibmvscsis_post_disconnect(vscsi,
1354 						  ERR_DISCONNECT_RECONNECT, 0);
1355 
1356 		dev_err(&vscsi->dev, "copy_crq: h_copy_rdma failed, rc %ld\n",
1357 			rc);
1358 		break;
1359 	case H_DEST_PARM:
1360 	case H_SOURCE_PARM:
1361 	default:
1362 		dev_err(&vscsi->dev, "copy_crq: h_copy_rdma failed, rc %ld\n",
1363 			rc);
1364 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
1365 		break;
1366 	}
1367 
1368 	return rc;
1369 }
1370 
1371 /**
1372  * ibmvscsis_adapter_info - Service an Adapter Info MAnagement Data gram
1373  * @vscsi:	Pointer to our adapter structure
1374  * @iue:	Information Unit containing the Adapter Info MAD request
1375  *
1376  * EXECUTION ENVIRONMENT:
1377  *	Interrupt adapter lock is held
1378  */
1379 static long ibmvscsis_adapter_info(struct scsi_info *vscsi,
1380 				   struct iu_entry *iue)
1381 {
1382 	struct viosrp_adapter_info *mad = &vio_iu(iue)->mad.adapter_info;
1383 	struct mad_adapter_info_data *info;
1384 	uint flag_bits = 0;
1385 	dma_addr_t token;
1386 	long rc;
1387 
1388 	mad->common.status = cpu_to_be16(VIOSRP_MAD_SUCCESS);
1389 
1390 	if (be16_to_cpu(mad->common.length) > sizeof(*info)) {
1391 		mad->common.status = cpu_to_be16(VIOSRP_MAD_FAILED);
1392 		return 0;
1393 	}
1394 
1395 	info = dma_alloc_coherent(&vscsi->dma_dev->dev, sizeof(*info), &token,
1396 				  GFP_ATOMIC);
1397 	if (!info) {
1398 		dev_err(&vscsi->dev, "bad dma_alloc_coherent %p\n",
1399 			iue->target);
1400 		mad->common.status = cpu_to_be16(VIOSRP_MAD_FAILED);
1401 		return 0;
1402 	}
1403 
1404 	/* Get remote info */
1405 	rc = h_copy_rdma(be16_to_cpu(mad->common.length),
1406 			 vscsi->dds.window[REMOTE].liobn,
1407 			 be64_to_cpu(mad->buffer),
1408 			 vscsi->dds.window[LOCAL].liobn, token);
1409 
1410 	if (rc != H_SUCCESS) {
1411 		if (rc == H_PERMISSION) {
1412 			if (connection_broken(vscsi))
1413 				flag_bits = (RESPONSE_Q_DOWN | CLIENT_FAILED);
1414 		}
1415 		pr_warn("adapter_info: h_copy_rdma from client failed, rc %ld\n",
1416 			rc);
1417 		pr_debug("adapter_info: ioba 0x%llx, flags 0x%x, flag_bits 0x%x\n",
1418 			 be64_to_cpu(mad->buffer), vscsi->flags, flag_bits);
1419 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT,
1420 					  flag_bits);
1421 		goto free_dma;
1422 	}
1423 
1424 	/*
1425 	 * Copy client info, but ignore partition number, which we
1426 	 * already got from phyp - unless we failed to get it from
1427 	 * phyp (e.g. if we're running on a p5 system).
1428 	 */
1429 	if (vscsi->client_data.partition_number == 0)
1430 		vscsi->client_data.partition_number =
1431 			be32_to_cpu(info->partition_number);
1432 	strncpy(vscsi->client_data.srp_version, info->srp_version,
1433 		sizeof(vscsi->client_data.srp_version));
1434 	strncpy(vscsi->client_data.partition_name, info->partition_name,
1435 		sizeof(vscsi->client_data.partition_name));
1436 	vscsi->client_data.mad_version = be32_to_cpu(info->mad_version);
1437 	vscsi->client_data.os_type = be32_to_cpu(info->os_type);
1438 
1439 	/* Copy our info */
1440 	strncpy(info->srp_version, SRP_VERSION,
1441 		sizeof(info->srp_version));
1442 	strncpy(info->partition_name, vscsi->dds.partition_name,
1443 		sizeof(info->partition_name));
1444 	info->partition_number = cpu_to_be32(vscsi->dds.partition_num);
1445 	info->mad_version = cpu_to_be32(MAD_VERSION_1);
1446 	info->os_type = cpu_to_be32(LINUX);
1447 	memset(&info->port_max_txu[0], 0, sizeof(info->port_max_txu));
1448 	info->port_max_txu[0] = cpu_to_be32(MAX_TXU);
1449 
1450 	dma_wmb();
1451 	rc = h_copy_rdma(sizeof(*info), vscsi->dds.window[LOCAL].liobn,
1452 			 token, vscsi->dds.window[REMOTE].liobn,
1453 			 be64_to_cpu(mad->buffer));
1454 	switch (rc) {
1455 	case H_SUCCESS:
1456 		break;
1457 
1458 	case H_SOURCE_PARM:
1459 	case H_DEST_PARM:
1460 	case H_PERMISSION:
1461 		if (connection_broken(vscsi))
1462 			flag_bits = (RESPONSE_Q_DOWN | CLIENT_FAILED);
1463 	default:
1464 		dev_err(&vscsi->dev, "adapter_info: h_copy_rdma to client failed, rc %ld\n",
1465 			rc);
1466 		ibmvscsis_post_disconnect(vscsi,
1467 					  ERR_DISCONNECT_RECONNECT,
1468 					  flag_bits);
1469 		break;
1470 	}
1471 
1472 free_dma:
1473 	dma_free_coherent(&vscsi->dma_dev->dev, sizeof(*info), info, token);
1474 	pr_debug("Leaving adapter_info, rc %ld\n", rc);
1475 
1476 	return rc;
1477 }
1478 
1479 /**
1480  * ibmvscsis_cap_mad() - Service a Capabilities MAnagement Data gram
1481  * @vscsi:	Pointer to our adapter structure
1482  * @iue:	Information Unit containing the Capabilities MAD request
1483  *
1484  * NOTE: if you return an error from this routine you must be
1485  * disconnecting or you will cause a hang
1486  *
1487  * EXECUTION ENVIRONMENT:
1488  *	Interrupt called with adapter lock held
1489  */
1490 static int ibmvscsis_cap_mad(struct scsi_info *vscsi, struct iu_entry *iue)
1491 {
1492 	struct viosrp_capabilities *mad = &vio_iu(iue)->mad.capabilities;
1493 	struct capabilities *cap;
1494 	struct mad_capability_common *common;
1495 	dma_addr_t token;
1496 	u16 olen, len, status, min_len, cap_len;
1497 	u32 flag;
1498 	uint flag_bits = 0;
1499 	long rc = 0;
1500 
1501 	olen = be16_to_cpu(mad->common.length);
1502 	/*
1503 	 * struct capabilities hardcodes a couple capabilities after the
1504 	 * header, but the capabilities can actually be in any order.
1505 	 */
1506 	min_len = offsetof(struct capabilities, migration);
1507 	if ((olen < min_len) || (olen > PAGE_SIZE)) {
1508 		pr_warn("cap_mad: invalid len %d\n", olen);
1509 		mad->common.status = cpu_to_be16(VIOSRP_MAD_FAILED);
1510 		return 0;
1511 	}
1512 
1513 	cap = dma_alloc_coherent(&vscsi->dma_dev->dev, olen, &token,
1514 				 GFP_ATOMIC);
1515 	if (!cap) {
1516 		dev_err(&vscsi->dev, "bad dma_alloc_coherent %p\n",
1517 			iue->target);
1518 		mad->common.status = cpu_to_be16(VIOSRP_MAD_FAILED);
1519 		return 0;
1520 	}
1521 	rc = h_copy_rdma(olen, vscsi->dds.window[REMOTE].liobn,
1522 			 be64_to_cpu(mad->buffer),
1523 			 vscsi->dds.window[LOCAL].liobn, token);
1524 	if (rc == H_SUCCESS) {
1525 		strncpy(cap->name, dev_name(&vscsi->dma_dev->dev),
1526 			SRP_MAX_LOC_LEN);
1527 
1528 		len = olen - min_len;
1529 		status = VIOSRP_MAD_SUCCESS;
1530 		common = (struct mad_capability_common *)&cap->migration;
1531 
1532 		while ((len > 0) && (status == VIOSRP_MAD_SUCCESS) && !rc) {
1533 			pr_debug("cap_mad: len left %hd, cap type %d, cap len %hd\n",
1534 				 len, be32_to_cpu(common->cap_type),
1535 				 be16_to_cpu(common->length));
1536 
1537 			cap_len = be16_to_cpu(common->length);
1538 			if (cap_len > len) {
1539 				dev_err(&vscsi->dev, "cap_mad: cap len mismatch with total len\n");
1540 				status = VIOSRP_MAD_FAILED;
1541 				break;
1542 			}
1543 
1544 			if (cap_len == 0) {
1545 				dev_err(&vscsi->dev, "cap_mad: cap len is 0\n");
1546 				status = VIOSRP_MAD_FAILED;
1547 				break;
1548 			}
1549 
1550 			switch (common->cap_type) {
1551 			default:
1552 				pr_debug("cap_mad: unsupported capability\n");
1553 				common->server_support = 0;
1554 				flag = cpu_to_be32((u32)CAP_LIST_SUPPORTED);
1555 				cap->flags &= ~flag;
1556 				break;
1557 			}
1558 
1559 			len = len - cap_len;
1560 			common = (struct mad_capability_common *)
1561 				((char *)common + cap_len);
1562 		}
1563 
1564 		mad->common.status = cpu_to_be16(status);
1565 
1566 		dma_wmb();
1567 		rc = h_copy_rdma(olen, vscsi->dds.window[LOCAL].liobn, token,
1568 				 vscsi->dds.window[REMOTE].liobn,
1569 				 be64_to_cpu(mad->buffer));
1570 
1571 		if (rc != H_SUCCESS) {
1572 			pr_debug("cap_mad: failed to copy to client, rc %ld\n",
1573 				 rc);
1574 
1575 			if (rc == H_PERMISSION) {
1576 				if (connection_broken(vscsi))
1577 					flag_bits = (RESPONSE_Q_DOWN |
1578 						     CLIENT_FAILED);
1579 			}
1580 
1581 			pr_warn("cap_mad: error copying data to client, rc %ld\n",
1582 				rc);
1583 			ibmvscsis_post_disconnect(vscsi,
1584 						  ERR_DISCONNECT_RECONNECT,
1585 						  flag_bits);
1586 		}
1587 	}
1588 
1589 	dma_free_coherent(&vscsi->dma_dev->dev, olen, cap, token);
1590 
1591 	pr_debug("Leaving cap_mad, rc %ld, client_cap 0x%x\n",
1592 		 rc, vscsi->client_cap);
1593 
1594 	return rc;
1595 }
1596 
1597 /**
1598  * ibmvscsis_process_mad() - Service a MAnagement Data gram
1599  * @vscsi:	Pointer to our adapter structure
1600  * @iue:	Information Unit containing the MAD request
1601  *
1602  * Must be called with interrupt lock held.
1603  */
1604 static long ibmvscsis_process_mad(struct scsi_info *vscsi, struct iu_entry *iue)
1605 {
1606 	struct mad_common *mad = (struct mad_common *)&vio_iu(iue)->mad;
1607 	struct viosrp_empty_iu *empty;
1608 	long rc = ADAPT_SUCCESS;
1609 
1610 	switch (be32_to_cpu(mad->type)) {
1611 	case VIOSRP_EMPTY_IU_TYPE:
1612 		empty = &vio_iu(iue)->mad.empty_iu;
1613 		vscsi->empty_iu_id = be64_to_cpu(empty->buffer);
1614 		vscsi->empty_iu_tag = be64_to_cpu(empty->common.tag);
1615 		mad->status = cpu_to_be16(VIOSRP_MAD_SUCCESS);
1616 		break;
1617 	case VIOSRP_ADAPTER_INFO_TYPE:
1618 		rc = ibmvscsis_adapter_info(vscsi, iue);
1619 		break;
1620 	case VIOSRP_CAPABILITIES_TYPE:
1621 		rc = ibmvscsis_cap_mad(vscsi, iue);
1622 		break;
1623 	case VIOSRP_ENABLE_FAST_FAIL:
1624 		if (vscsi->state == CONNECTED) {
1625 			vscsi->fast_fail = true;
1626 			mad->status = cpu_to_be16(VIOSRP_MAD_SUCCESS);
1627 		} else {
1628 			pr_warn("fast fail mad sent after login\n");
1629 			mad->status = cpu_to_be16(VIOSRP_MAD_FAILED);
1630 		}
1631 		break;
1632 	default:
1633 		mad->status = cpu_to_be16(VIOSRP_MAD_NOT_SUPPORTED);
1634 		break;
1635 	}
1636 
1637 	return rc;
1638 }
1639 
1640 /**
1641  * srp_snd_msg_failed() - Handle an error when sending a response
1642  * @vscsi:	Pointer to our adapter structure
1643  * @rc:		The return code from the h_send_crq command
1644  *
1645  * Must be called with interrupt lock held.
1646  */
1647 static void srp_snd_msg_failed(struct scsi_info *vscsi, long rc)
1648 {
1649 	ktime_t kt;
1650 
1651 	if (rc != H_DROPPED) {
1652 		ibmvscsis_free_cmd_qs(vscsi);
1653 
1654 		if (rc == H_CLOSED)
1655 			vscsi->flags |= CLIENT_FAILED;
1656 
1657 		/* don't flag the same problem multiple times */
1658 		if (!(vscsi->flags & RESPONSE_Q_DOWN)) {
1659 			vscsi->flags |= RESPONSE_Q_DOWN;
1660 			if (!(vscsi->state & (ERR_DISCONNECT |
1661 					      ERR_DISCONNECT_RECONNECT |
1662 					      ERR_DISCONNECTED | UNDEFINED))) {
1663 				dev_err(&vscsi->dev, "snd_msg_failed: setting RESPONSE_Q_DOWN, state 0x%hx, flags 0x%x, rc %ld\n",
1664 					vscsi->state, vscsi->flags, rc);
1665 			}
1666 			ibmvscsis_post_disconnect(vscsi,
1667 						  ERR_DISCONNECT_RECONNECT, 0);
1668 		}
1669 		return;
1670 	}
1671 
1672 	/*
1673 	 * The response queue is full.
1674 	 * If the server is processing SRP requests, i.e.
1675 	 * the client has successfully done an
1676 	 * SRP_LOGIN, then it will wait forever for room in
1677 	 * the queue.  However if the system admin
1678 	 * is attempting to unconfigure the server then one
1679 	 * or more children will be in a state where
1680 	 * they are being removed. So if there is even one
1681 	 * child being removed then the driver assumes
1682 	 * the system admin is attempting to break the
1683 	 * connection with the client and MAX_TIMER_POPS
1684 	 * is honored.
1685 	 */
1686 	if ((vscsi->rsp_q_timer.timer_pops < MAX_TIMER_POPS) ||
1687 	    (vscsi->state == SRP_PROCESSING)) {
1688 		pr_debug("snd_msg_failed: response queue full, flags 0x%x, timer started %d, pops %d\n",
1689 			 vscsi->flags, (int)vscsi->rsp_q_timer.started,
1690 			 vscsi->rsp_q_timer.timer_pops);
1691 
1692 		/*
1693 		 * Check if the timer is running; if it
1694 		 * is not then start it up.
1695 		 */
1696 		if (!vscsi->rsp_q_timer.started) {
1697 			if (vscsi->rsp_q_timer.timer_pops <
1698 			    MAX_TIMER_POPS) {
1699 				kt = WAIT_NANO_SECONDS;
1700 			} else {
1701 				/*
1702 				 * slide the timeslice if the maximum
1703 				 * timer pops have already happened
1704 				 */
1705 				kt = ktime_set(WAIT_SECONDS, 0);
1706 			}
1707 
1708 			vscsi->rsp_q_timer.started = true;
1709 			hrtimer_start(&vscsi->rsp_q_timer.timer, kt,
1710 				      HRTIMER_MODE_REL);
1711 		}
1712 	} else {
1713 		/*
1714 		 * TBD: Do we need to worry about this? Need to get
1715 		 *      remove working.
1716 		 */
1717 		/*
1718 		 * waited a long time and it appears the system admin
1719 		 * is bring this driver down
1720 		 */
1721 		vscsi->flags |= RESPONSE_Q_DOWN;
1722 		ibmvscsis_free_cmd_qs(vscsi);
1723 		/*
1724 		 * if the driver is already attempting to disconnect
1725 		 * from the client and has already logged an error
1726 		 * trace this event but don't put it in the error log
1727 		 */
1728 		if (!(vscsi->state & (ERR_DISCONNECT |
1729 				      ERR_DISCONNECT_RECONNECT |
1730 				      ERR_DISCONNECTED | UNDEFINED))) {
1731 			dev_err(&vscsi->dev, "client crq full too long\n");
1732 			ibmvscsis_post_disconnect(vscsi,
1733 						  ERR_DISCONNECT_RECONNECT,
1734 						  0);
1735 		}
1736 	}
1737 }
1738 
1739 /**
1740  * ibmvscsis_send_messages() - Send a Response
1741  * @vscsi:	Pointer to our adapter structure
1742  *
1743  * Send a response, first checking the waiting queue. Responses are
1744  * sent in order they are received. If the response cannot be sent,
1745  * because the client queue is full, it stays on the waiting queue.
1746  *
1747  * PRECONDITION:
1748  *	Called with interrupt lock held
1749  */
1750 static void ibmvscsis_send_messages(struct scsi_info *vscsi)
1751 {
1752 	u64 msg_hi = 0;
1753 	/* note do not attempt to access the IU_data_ptr with this pointer
1754 	 * it is not valid
1755 	 */
1756 	struct viosrp_crq *crq = (struct viosrp_crq *)&msg_hi;
1757 	struct ibmvscsis_cmd *cmd, *nxt;
1758 	struct iu_entry *iue;
1759 	long rc = ADAPT_SUCCESS;
1760 	bool retry = false;
1761 
1762 	if (!(vscsi->flags & RESPONSE_Q_DOWN)) {
1763 		do {
1764 			retry = false;
1765 			list_for_each_entry_safe(cmd, nxt, &vscsi->waiting_rsp,
1766 						 list) {
1767 				/*
1768 				 * Check to make sure abort cmd gets processed
1769 				 * prior to the abort tmr cmd
1770 				 */
1771 				if (cmd->flags & DELAY_SEND)
1772 					continue;
1773 
1774 				if (cmd->abort_cmd) {
1775 					retry = true;
1776 					cmd->abort_cmd->flags &= ~(DELAY_SEND);
1777 				}
1778 
1779 				/*
1780 				 * If CMD_T_ABORTED w/o CMD_T_TAS scenarios and
1781 				 * the case where LIO issued a
1782 				 * ABORT_TASK: Sending TMR_TASK_DOES_NOT_EXIST
1783 				 * case then we dont send a response, since it
1784 				 * was already done.
1785 				 */
1786 				if (cmd->se_cmd.transport_state & CMD_T_ABORTED &&
1787 				    !(cmd->se_cmd.transport_state & CMD_T_TAS)) {
1788 					list_del(&cmd->list);
1789 					ibmvscsis_free_cmd_resources(vscsi,
1790 								     cmd);
1791 				} else {
1792 					iue = cmd->iue;
1793 
1794 					crq->valid = VALID_CMD_RESP_EL;
1795 					crq->format = cmd->rsp.format;
1796 
1797 					if (cmd->flags & CMD_FAST_FAIL)
1798 						crq->status = VIOSRP_ADAPTER_FAIL;
1799 
1800 					crq->IU_length = cpu_to_be16(cmd->rsp.len);
1801 
1802 					rc = h_send_crq(vscsi->dma_dev->unit_address,
1803 							be64_to_cpu(msg_hi),
1804 							be64_to_cpu(cmd->rsp.tag));
1805 
1806 					pr_debug("send_messages: cmd %p, tag 0x%llx, rc %ld\n",
1807 						 cmd, be64_to_cpu(cmd->rsp.tag), rc);
1808 
1809 					/* if all ok free up the command
1810 					 * element resources
1811 					 */
1812 					if (rc == H_SUCCESS) {
1813 						/* some movement has occurred */
1814 						vscsi->rsp_q_timer.timer_pops = 0;
1815 						list_del(&cmd->list);
1816 
1817 						ibmvscsis_free_cmd_resources(vscsi,
1818 									     cmd);
1819 					} else {
1820 						srp_snd_msg_failed(vscsi, rc);
1821 						break;
1822 					}
1823 				}
1824 			}
1825 		} while (retry);
1826 
1827 		if (!rc) {
1828 			/*
1829 			 * The timer could pop with the queue empty.  If
1830 			 * this happens, rc will always indicate a
1831 			 * success; clear the pop count.
1832 			 */
1833 			vscsi->rsp_q_timer.timer_pops = 0;
1834 		}
1835 	} else {
1836 		ibmvscsis_free_cmd_qs(vscsi);
1837 	}
1838 }
1839 
1840 /* Called with intr lock held */
1841 static void ibmvscsis_send_mad_resp(struct scsi_info *vscsi,
1842 				    struct ibmvscsis_cmd *cmd,
1843 				    struct viosrp_crq *crq)
1844 {
1845 	struct iu_entry *iue = cmd->iue;
1846 	struct mad_common *mad = (struct mad_common *)&vio_iu(iue)->mad;
1847 	uint flag_bits = 0;
1848 	long rc;
1849 
1850 	dma_wmb();
1851 	rc = h_copy_rdma(sizeof(struct mad_common),
1852 			 vscsi->dds.window[LOCAL].liobn, iue->sbuf->dma,
1853 			 vscsi->dds.window[REMOTE].liobn,
1854 			 be64_to_cpu(crq->IU_data_ptr));
1855 	if (!rc) {
1856 		cmd->rsp.format = VIOSRP_MAD_FORMAT;
1857 		cmd->rsp.len = sizeof(struct mad_common);
1858 		cmd->rsp.tag = mad->tag;
1859 		list_add_tail(&cmd->list, &vscsi->waiting_rsp);
1860 		ibmvscsis_send_messages(vscsi);
1861 	} else {
1862 		pr_debug("Error sending mad response, rc %ld\n", rc);
1863 		if (rc == H_PERMISSION) {
1864 			if (connection_broken(vscsi))
1865 				flag_bits = (RESPONSE_Q_DOWN | CLIENT_FAILED);
1866 		}
1867 		dev_err(&vscsi->dev, "mad: failed to copy to client, rc %ld\n",
1868 			rc);
1869 
1870 		ibmvscsis_free_cmd_resources(vscsi, cmd);
1871 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT,
1872 					  flag_bits);
1873 	}
1874 }
1875 
1876 /**
1877  * ibmvscsis_mad() - Service a MAnagement Data gram.
1878  * @vscsi:	Pointer to our adapter structure
1879  * @crq:	Pointer to the CRQ entry containing the MAD request
1880  *
1881  * EXECUTION ENVIRONMENT:
1882  *	Interrupt, called with adapter lock held
1883  */
1884 static long ibmvscsis_mad(struct scsi_info *vscsi, struct viosrp_crq *crq)
1885 {
1886 	struct iu_entry *iue;
1887 	struct ibmvscsis_cmd *cmd;
1888 	struct mad_common *mad;
1889 	long rc = ADAPT_SUCCESS;
1890 
1891 	switch (vscsi->state) {
1892 		/*
1893 		 * We have not exchanged Init Msgs yet, so this MAD was sent
1894 		 * before the last Transport Event; client will not be
1895 		 * expecting a response.
1896 		 */
1897 	case WAIT_CONNECTION:
1898 		pr_debug("mad: in Wait Connection state, ignoring MAD, flags %d\n",
1899 			 vscsi->flags);
1900 		return ADAPT_SUCCESS;
1901 
1902 	case SRP_PROCESSING:
1903 	case CONNECTED:
1904 		break;
1905 
1906 		/*
1907 		 * We should never get here while we're in these states.
1908 		 * Just log an error and get out.
1909 		 */
1910 	case UNCONFIGURING:
1911 	case WAIT_IDLE:
1912 	case ERR_DISCONNECT:
1913 	case ERR_DISCONNECT_RECONNECT:
1914 	default:
1915 		dev_err(&vscsi->dev, "mad: invalid adapter state %d for mad\n",
1916 			vscsi->state);
1917 		return ADAPT_SUCCESS;
1918 	}
1919 
1920 	cmd = ibmvscsis_get_free_cmd(vscsi);
1921 	if (!cmd) {
1922 		dev_err(&vscsi->dev, "mad: failed to get cmd, debit %d\n",
1923 			vscsi->debit);
1924 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
1925 		return ERROR;
1926 	}
1927 	iue = cmd->iue;
1928 	cmd->type = ADAPTER_MAD;
1929 
1930 	rc = ibmvscsis_copy_crq_packet(vscsi, cmd, crq);
1931 	if (!rc) {
1932 		mad = (struct mad_common *)&vio_iu(iue)->mad;
1933 
1934 		pr_debug("mad: type %d\n", be32_to_cpu(mad->type));
1935 
1936 		rc = ibmvscsis_process_mad(vscsi, iue);
1937 
1938 		pr_debug("mad: status %hd, rc %ld\n", be16_to_cpu(mad->status),
1939 			 rc);
1940 
1941 		if (!rc)
1942 			ibmvscsis_send_mad_resp(vscsi, cmd, crq);
1943 	} else {
1944 		ibmvscsis_free_cmd_resources(vscsi, cmd);
1945 	}
1946 
1947 	pr_debug("Leaving mad, rc %ld\n", rc);
1948 	return rc;
1949 }
1950 
1951 /**
1952  * ibmvscsis_login_rsp() - Create/copy a login response notice to the client
1953  * @vscsi:	Pointer to our adapter structure
1954  * @cmd:	Pointer to the command for the SRP Login request
1955  *
1956  * EXECUTION ENVIRONMENT:
1957  *	Interrupt, interrupt lock held
1958  */
1959 static long ibmvscsis_login_rsp(struct scsi_info *vscsi,
1960 				struct ibmvscsis_cmd *cmd)
1961 {
1962 	struct iu_entry *iue = cmd->iue;
1963 	struct srp_login_rsp *rsp = &vio_iu(iue)->srp.login_rsp;
1964 	struct format_code *fmt;
1965 	uint flag_bits = 0;
1966 	long rc = ADAPT_SUCCESS;
1967 
1968 	memset(rsp, 0, sizeof(struct srp_login_rsp));
1969 
1970 	rsp->opcode = SRP_LOGIN_RSP;
1971 	rsp->req_lim_delta = cpu_to_be32(vscsi->request_limit);
1972 	rsp->tag = cmd->rsp.tag;
1973 	rsp->max_it_iu_len = cpu_to_be32(SRP_MAX_IU_LEN);
1974 	rsp->max_ti_iu_len = cpu_to_be32(SRP_MAX_IU_LEN);
1975 	fmt = (struct format_code *)&rsp->buf_fmt;
1976 	fmt->buffers = SUPPORTED_FORMATS;
1977 	vscsi->credit = 0;
1978 
1979 	cmd->rsp.len = sizeof(struct srp_login_rsp);
1980 
1981 	dma_wmb();
1982 	rc = h_copy_rdma(cmd->rsp.len, vscsi->dds.window[LOCAL].liobn,
1983 			 iue->sbuf->dma, vscsi->dds.window[REMOTE].liobn,
1984 			 be64_to_cpu(iue->remote_token));
1985 
1986 	switch (rc) {
1987 	case H_SUCCESS:
1988 		break;
1989 
1990 	case H_PERMISSION:
1991 		if (connection_broken(vscsi))
1992 			flag_bits = RESPONSE_Q_DOWN | CLIENT_FAILED;
1993 		dev_err(&vscsi->dev, "login_rsp: error copying to client, rc %ld\n",
1994 			rc);
1995 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT,
1996 					  flag_bits);
1997 		break;
1998 	case H_SOURCE_PARM:
1999 	case H_DEST_PARM:
2000 	default:
2001 		dev_err(&vscsi->dev, "login_rsp: error copying to client, rc %ld\n",
2002 			rc);
2003 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
2004 		break;
2005 	}
2006 
2007 	return rc;
2008 }
2009 
2010 /**
2011  * ibmvscsis_srp_login_rej() - Create/copy a login rejection notice to client
2012  * @vscsi:	Pointer to our adapter structure
2013  * @cmd:	Pointer to the command for the SRP Login request
2014  * @reason:	The reason the SRP Login is being rejected, per SRP protocol
2015  *
2016  * EXECUTION ENVIRONMENT:
2017  *	Interrupt, interrupt lock held
2018  */
2019 static long ibmvscsis_srp_login_rej(struct scsi_info *vscsi,
2020 				    struct ibmvscsis_cmd *cmd, u32 reason)
2021 {
2022 	struct iu_entry *iue = cmd->iue;
2023 	struct srp_login_rej *rej = &vio_iu(iue)->srp.login_rej;
2024 	struct format_code *fmt;
2025 	uint flag_bits = 0;
2026 	long rc = ADAPT_SUCCESS;
2027 
2028 	memset(rej, 0, sizeof(*rej));
2029 
2030 	rej->opcode = SRP_LOGIN_REJ;
2031 	rej->reason = cpu_to_be32(reason);
2032 	rej->tag = cmd->rsp.tag;
2033 	fmt = (struct format_code *)&rej->buf_fmt;
2034 	fmt->buffers = SUPPORTED_FORMATS;
2035 
2036 	cmd->rsp.len = sizeof(*rej);
2037 
2038 	dma_wmb();
2039 	rc = h_copy_rdma(cmd->rsp.len, vscsi->dds.window[LOCAL].liobn,
2040 			 iue->sbuf->dma, vscsi->dds.window[REMOTE].liobn,
2041 			 be64_to_cpu(iue->remote_token));
2042 
2043 	switch (rc) {
2044 	case H_SUCCESS:
2045 		break;
2046 	case H_PERMISSION:
2047 		if (connection_broken(vscsi))
2048 			flag_bits = RESPONSE_Q_DOWN | CLIENT_FAILED;
2049 		dev_err(&vscsi->dev, "login_rej: error copying to client, rc %ld\n",
2050 			rc);
2051 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT,
2052 					  flag_bits);
2053 		break;
2054 	case H_SOURCE_PARM:
2055 	case H_DEST_PARM:
2056 	default:
2057 		dev_err(&vscsi->dev, "login_rej: error copying to client, rc %ld\n",
2058 			rc);
2059 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
2060 		break;
2061 	}
2062 
2063 	return rc;
2064 }
2065 
2066 static int ibmvscsis_make_nexus(struct ibmvscsis_tport *tport)
2067 {
2068 	char *name = tport->tport_name;
2069 	struct ibmvscsis_nexus *nexus;
2070 	int rc;
2071 
2072 	if (tport->ibmv_nexus) {
2073 		pr_debug("tport->ibmv_nexus already exists\n");
2074 		return 0;
2075 	}
2076 
2077 	nexus = kzalloc(sizeof(*nexus), GFP_KERNEL);
2078 	if (!nexus) {
2079 		pr_err("Unable to allocate struct ibmvscsis_nexus\n");
2080 		return -ENOMEM;
2081 	}
2082 
2083 	nexus->se_sess = target_alloc_session(&tport->se_tpg, 0, 0,
2084 					      TARGET_PROT_NORMAL, name, nexus,
2085 					      NULL);
2086 	if (IS_ERR(nexus->se_sess)) {
2087 		rc = PTR_ERR(nexus->se_sess);
2088 		goto transport_init_fail;
2089 	}
2090 
2091 	tport->ibmv_nexus = nexus;
2092 
2093 	return 0;
2094 
2095 transport_init_fail:
2096 	kfree(nexus);
2097 	return rc;
2098 }
2099 
2100 static int ibmvscsis_drop_nexus(struct ibmvscsis_tport *tport)
2101 {
2102 	struct se_session *se_sess;
2103 	struct ibmvscsis_nexus *nexus;
2104 
2105 	nexus = tport->ibmv_nexus;
2106 	if (!nexus)
2107 		return -ENODEV;
2108 
2109 	se_sess = nexus->se_sess;
2110 	if (!se_sess)
2111 		return -ENODEV;
2112 
2113 	/*
2114 	 * Release the SCSI I_T Nexus to the emulated ibmvscsis Target Port
2115 	 */
2116 	target_wait_for_sess_cmds(se_sess);
2117 	transport_deregister_session_configfs(se_sess);
2118 	transport_deregister_session(se_sess);
2119 	tport->ibmv_nexus = NULL;
2120 	kfree(nexus);
2121 
2122 	return 0;
2123 }
2124 
2125 /**
2126  * ibmvscsis_srp_login() - Process an SRP Login Request
2127  * @vscsi:	Pointer to our adapter structure
2128  * @cmd:	Command element to use to process the SRP Login request
2129  * @crq:	Pointer to CRQ entry containing the SRP Login request
2130  *
2131  * EXECUTION ENVIRONMENT:
2132  *	Interrupt, called with interrupt lock held
2133  */
2134 static long ibmvscsis_srp_login(struct scsi_info *vscsi,
2135 				struct ibmvscsis_cmd *cmd,
2136 				struct viosrp_crq *crq)
2137 {
2138 	struct iu_entry *iue = cmd->iue;
2139 	struct srp_login_req *req = &vio_iu(iue)->srp.login_req;
2140 	struct port_id {
2141 		__be64 id_extension;
2142 		__be64 io_guid;
2143 	} *iport, *tport;
2144 	struct format_code *fmt;
2145 	u32 reason = 0x0;
2146 	long rc = ADAPT_SUCCESS;
2147 
2148 	iport = (struct port_id *)req->initiator_port_id;
2149 	tport = (struct port_id *)req->target_port_id;
2150 	fmt = (struct format_code *)&req->req_buf_fmt;
2151 	if (be32_to_cpu(req->req_it_iu_len) > SRP_MAX_IU_LEN)
2152 		reason = SRP_LOGIN_REJ_REQ_IT_IU_LENGTH_TOO_LARGE;
2153 	else if (be32_to_cpu(req->req_it_iu_len) < 64)
2154 		reason = SRP_LOGIN_REJ_UNABLE_ESTABLISH_CHANNEL;
2155 	else if ((be64_to_cpu(iport->id_extension) > (MAX_NUM_PORTS - 1)) ||
2156 		 (be64_to_cpu(tport->id_extension) > (MAX_NUM_PORTS - 1)))
2157 		reason = SRP_LOGIN_REJ_UNABLE_ASSOCIATE_CHANNEL;
2158 	else if (req->req_flags & SRP_MULTICHAN_MULTI)
2159 		reason = SRP_LOGIN_REJ_MULTI_CHANNEL_UNSUPPORTED;
2160 	else if (fmt->buffers & (~SUPPORTED_FORMATS))
2161 		reason = SRP_LOGIN_REJ_UNSUPPORTED_DESCRIPTOR_FMT;
2162 	else if ((fmt->buffers & SUPPORTED_FORMATS) == 0)
2163 		reason = SRP_LOGIN_REJ_UNSUPPORTED_DESCRIPTOR_FMT;
2164 
2165 	if (vscsi->state == SRP_PROCESSING)
2166 		reason = SRP_LOGIN_REJ_CHANNEL_LIMIT_REACHED;
2167 
2168 	rc = ibmvscsis_make_nexus(&vscsi->tport);
2169 	if (rc)
2170 		reason = SRP_LOGIN_REJ_UNABLE_ESTABLISH_CHANNEL;
2171 
2172 	cmd->rsp.format = VIOSRP_SRP_FORMAT;
2173 	cmd->rsp.tag = req->tag;
2174 
2175 	pr_debug("srp_login: reason 0x%x\n", reason);
2176 
2177 	if (reason)
2178 		rc = ibmvscsis_srp_login_rej(vscsi, cmd, reason);
2179 	else
2180 		rc = ibmvscsis_login_rsp(vscsi, cmd);
2181 
2182 	if (!rc) {
2183 		if (!reason)
2184 			vscsi->state = SRP_PROCESSING;
2185 
2186 		list_add_tail(&cmd->list, &vscsi->waiting_rsp);
2187 		ibmvscsis_send_messages(vscsi);
2188 	} else {
2189 		ibmvscsis_free_cmd_resources(vscsi, cmd);
2190 	}
2191 
2192 	pr_debug("Leaving srp_login, rc %ld\n", rc);
2193 	return rc;
2194 }
2195 
2196 /**
2197  * ibmvscsis_srp_i_logout() - Helper Function to close I_T Nexus
2198  * @vscsi:	Pointer to our adapter structure
2199  * @cmd:	Command element to use to process the Implicit Logout request
2200  * @crq:	Pointer to CRQ entry containing the Implicit Logout request
2201  *
2202  * Do the logic to close the I_T nexus.  This function may not
2203  * behave to specification.
2204  *
2205  * EXECUTION ENVIRONMENT:
2206  *	Interrupt, interrupt lock held
2207  */
2208 static long ibmvscsis_srp_i_logout(struct scsi_info *vscsi,
2209 				   struct ibmvscsis_cmd *cmd,
2210 				   struct viosrp_crq *crq)
2211 {
2212 	struct iu_entry *iue = cmd->iue;
2213 	struct srp_i_logout *log_out = &vio_iu(iue)->srp.i_logout;
2214 	long rc = ADAPT_SUCCESS;
2215 
2216 	if ((vscsi->debit > 0) || !list_empty(&vscsi->schedule_q) ||
2217 	    !list_empty(&vscsi->waiting_rsp)) {
2218 		dev_err(&vscsi->dev, "i_logout: outstanding work\n");
2219 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT, 0);
2220 	} else {
2221 		cmd->rsp.format = SRP_FORMAT;
2222 		cmd->rsp.tag = log_out->tag;
2223 		cmd->rsp.len = sizeof(struct mad_common);
2224 		list_add_tail(&cmd->list, &vscsi->waiting_rsp);
2225 		ibmvscsis_send_messages(vscsi);
2226 
2227 		ibmvscsis_post_disconnect(vscsi, WAIT_IDLE, 0);
2228 	}
2229 
2230 	return rc;
2231 }
2232 
2233 /* Called with intr lock held */
2234 static void ibmvscsis_srp_cmd(struct scsi_info *vscsi, struct viosrp_crq *crq)
2235 {
2236 	struct ibmvscsis_cmd *cmd;
2237 	struct iu_entry *iue;
2238 	struct srp_cmd *srp;
2239 	struct srp_tsk_mgmt *tsk;
2240 	long rc;
2241 
2242 	if (vscsi->request_limit - vscsi->debit <= 0) {
2243 		/* Client has exceeded request limit */
2244 		dev_err(&vscsi->dev, "Client exceeded the request limit (%d), debit %d\n",
2245 			vscsi->request_limit, vscsi->debit);
2246 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
2247 		return;
2248 	}
2249 
2250 	cmd = ibmvscsis_get_free_cmd(vscsi);
2251 	if (!cmd) {
2252 		dev_err(&vscsi->dev, "srp_cmd failed to get cmd, debit %d\n",
2253 			vscsi->debit);
2254 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
2255 		return;
2256 	}
2257 	iue = cmd->iue;
2258 	srp = &vio_iu(iue)->srp.cmd;
2259 
2260 	rc = ibmvscsis_copy_crq_packet(vscsi, cmd, crq);
2261 	if (rc) {
2262 		ibmvscsis_free_cmd_resources(vscsi, cmd);
2263 		return;
2264 	}
2265 
2266 	if (vscsi->state == SRP_PROCESSING) {
2267 		switch (srp->opcode) {
2268 		case SRP_LOGIN_REQ:
2269 			rc = ibmvscsis_srp_login(vscsi, cmd, crq);
2270 			break;
2271 
2272 		case SRP_TSK_MGMT:
2273 			tsk = &vio_iu(iue)->srp.tsk_mgmt;
2274 			pr_debug("tsk_mgmt tag: %llu (0x%llx)\n", tsk->tag,
2275 				 tsk->tag);
2276 			cmd->rsp.tag = tsk->tag;
2277 			vscsi->debit += 1;
2278 			cmd->type = TASK_MANAGEMENT;
2279 			list_add_tail(&cmd->list, &vscsi->schedule_q);
2280 			queue_work(vscsi->work_q, &cmd->work);
2281 			break;
2282 
2283 		case SRP_CMD:
2284 			pr_debug("srp_cmd tag: %llu (0x%llx)\n", srp->tag,
2285 				 srp->tag);
2286 			cmd->rsp.tag = srp->tag;
2287 			vscsi->debit += 1;
2288 			cmd->type = SCSI_CDB;
2289 			/*
2290 			 * We want to keep track of work waiting for
2291 			 * the workqueue.
2292 			 */
2293 			list_add_tail(&cmd->list, &vscsi->schedule_q);
2294 			queue_work(vscsi->work_q, &cmd->work);
2295 			break;
2296 
2297 		case SRP_I_LOGOUT:
2298 			rc = ibmvscsis_srp_i_logout(vscsi, cmd, crq);
2299 			break;
2300 
2301 		case SRP_CRED_RSP:
2302 		case SRP_AER_RSP:
2303 		default:
2304 			ibmvscsis_free_cmd_resources(vscsi, cmd);
2305 			dev_err(&vscsi->dev, "invalid srp cmd, opcode %d\n",
2306 				(uint)srp->opcode);
2307 			ibmvscsis_post_disconnect(vscsi,
2308 						  ERR_DISCONNECT_RECONNECT, 0);
2309 			break;
2310 		}
2311 	} else if (srp->opcode == SRP_LOGIN_REQ && vscsi->state == CONNECTED) {
2312 		rc = ibmvscsis_srp_login(vscsi, cmd, crq);
2313 	} else {
2314 		ibmvscsis_free_cmd_resources(vscsi, cmd);
2315 		dev_err(&vscsi->dev, "Invalid state %d to handle srp cmd\n",
2316 			vscsi->state);
2317 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
2318 	}
2319 }
2320 
2321 /**
2322  * ibmvscsis_ping_response() - Respond to a ping request
2323  * @vscsi:	Pointer to our adapter structure
2324  *
2325  * Let the client know that the server is alive and waiting on
2326  * its native I/O stack.
2327  * If any type of error occurs from the call to queue a ping
2328  * response then the client is either not accepting or receiving
2329  * interrupts.  Disconnect with an error.
2330  *
2331  * EXECUTION ENVIRONMENT:
2332  *	Interrupt, interrupt lock held
2333  */
2334 static long ibmvscsis_ping_response(struct scsi_info *vscsi)
2335 {
2336 	struct viosrp_crq *crq;
2337 	u64 buffer[2] = { 0, 0 };
2338 	long rc;
2339 
2340 	crq = (struct viosrp_crq *)&buffer;
2341 	crq->valid = VALID_CMD_RESP_EL;
2342 	crq->format = (u8)MESSAGE_IN_CRQ;
2343 	crq->status = PING_RESPONSE;
2344 
2345 	rc = h_send_crq(vscsi->dds.unit_id, cpu_to_be64(buffer[MSG_HI]),
2346 			cpu_to_be64(buffer[MSG_LOW]));
2347 
2348 	switch (rc) {
2349 	case H_SUCCESS:
2350 		break;
2351 	case H_CLOSED:
2352 		vscsi->flags |= CLIENT_FAILED;
2353 	case H_DROPPED:
2354 		vscsi->flags |= RESPONSE_Q_DOWN;
2355 	case H_REMOTE_PARM:
2356 		dev_err(&vscsi->dev, "ping_response: h_send_crq failed, rc %ld\n",
2357 			rc);
2358 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
2359 		break;
2360 	default:
2361 		dev_err(&vscsi->dev, "ping_response: h_send_crq returned unknown rc %ld\n",
2362 			rc);
2363 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT, 0);
2364 		break;
2365 	}
2366 
2367 	return rc;
2368 }
2369 
2370 /**
2371  * ibmvscsis_parse_command() - Parse an element taken from the cmd rsp queue.
2372  * @vscsi:	Pointer to our adapter structure
2373  * @crq:	Pointer to CRQ element containing the SRP request
2374  *
2375  * This function will return success if the command queue element is valid
2376  * and the srp iu or MAD request it pointed to was also valid.  That does
2377  * not mean that an error was not returned to the client.
2378  *
2379  * EXECUTION ENVIRONMENT:
2380  *	Interrupt, intr lock held
2381  */
2382 static long ibmvscsis_parse_command(struct scsi_info *vscsi,
2383 				    struct viosrp_crq *crq)
2384 {
2385 	long rc = ADAPT_SUCCESS;
2386 
2387 	switch (crq->valid) {
2388 	case VALID_CMD_RESP_EL:
2389 		switch (crq->format) {
2390 		case OS400_FORMAT:
2391 		case AIX_FORMAT:
2392 		case LINUX_FORMAT:
2393 		case MAD_FORMAT:
2394 			if (vscsi->flags & PROCESSING_MAD) {
2395 				rc = ERROR;
2396 				dev_err(&vscsi->dev, "parse_command: already processing mad\n");
2397 				ibmvscsis_post_disconnect(vscsi,
2398 						       ERR_DISCONNECT_RECONNECT,
2399 						       0);
2400 			} else {
2401 				vscsi->flags |= PROCESSING_MAD;
2402 				rc = ibmvscsis_mad(vscsi, crq);
2403 			}
2404 			break;
2405 
2406 		case SRP_FORMAT:
2407 			ibmvscsis_srp_cmd(vscsi, crq);
2408 			break;
2409 
2410 		case MESSAGE_IN_CRQ:
2411 			if (crq->status == PING)
2412 				ibmvscsis_ping_response(vscsi);
2413 			break;
2414 
2415 		default:
2416 			dev_err(&vscsi->dev, "parse_command: invalid format %d\n",
2417 				(uint)crq->format);
2418 			ibmvscsis_post_disconnect(vscsi,
2419 						  ERR_DISCONNECT_RECONNECT, 0);
2420 			break;
2421 		}
2422 		break;
2423 
2424 	case VALID_TRANS_EVENT:
2425 		rc = ibmvscsis_trans_event(vscsi, crq);
2426 		break;
2427 
2428 	case VALID_INIT_MSG:
2429 		rc = ibmvscsis_init_msg(vscsi, crq);
2430 		break;
2431 
2432 	default:
2433 		dev_err(&vscsi->dev, "parse_command: invalid valid field %d\n",
2434 			(uint)crq->valid);
2435 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
2436 		break;
2437 	}
2438 
2439 	/*
2440 	 * Return only what the interrupt handler cares
2441 	 * about. Most errors we keep right on trucking.
2442 	 */
2443 	rc = vscsi->flags & SCHEDULE_DISCONNECT;
2444 
2445 	return rc;
2446 }
2447 
2448 static int read_dma_window(struct scsi_info *vscsi)
2449 {
2450 	struct vio_dev *vdev = vscsi->dma_dev;
2451 	const __be32 *dma_window;
2452 	const __be32 *prop;
2453 
2454 	/* TODO Using of_parse_dma_window would be better, but it doesn't give
2455 	 * a way to read multiple windows without already knowing the size of
2456 	 * a window or the number of windows.
2457 	 */
2458 	dma_window = (const __be32 *)vio_get_attribute(vdev,
2459 						       "ibm,my-dma-window",
2460 						       NULL);
2461 	if (!dma_window) {
2462 		pr_err("Couldn't find ibm,my-dma-window property\n");
2463 		return -1;
2464 	}
2465 
2466 	vscsi->dds.window[LOCAL].liobn = be32_to_cpu(*dma_window);
2467 	dma_window++;
2468 
2469 	prop = (const __be32 *)vio_get_attribute(vdev, "ibm,#dma-address-cells",
2470 						 NULL);
2471 	if (!prop) {
2472 		pr_warn("Couldn't find ibm,#dma-address-cells property\n");
2473 		dma_window++;
2474 	} else {
2475 		dma_window += be32_to_cpu(*prop);
2476 	}
2477 
2478 	prop = (const __be32 *)vio_get_attribute(vdev, "ibm,#dma-size-cells",
2479 						 NULL);
2480 	if (!prop) {
2481 		pr_warn("Couldn't find ibm,#dma-size-cells property\n");
2482 		dma_window++;
2483 	} else {
2484 		dma_window += be32_to_cpu(*prop);
2485 	}
2486 
2487 	/* dma_window should point to the second window now */
2488 	vscsi->dds.window[REMOTE].liobn = be32_to_cpu(*dma_window);
2489 
2490 	return 0;
2491 }
2492 
2493 static struct ibmvscsis_tport *ibmvscsis_lookup_port(const char *name)
2494 {
2495 	struct ibmvscsis_tport *tport = NULL;
2496 	struct vio_dev *vdev;
2497 	struct scsi_info *vscsi;
2498 
2499 	spin_lock_bh(&ibmvscsis_dev_lock);
2500 	list_for_each_entry(vscsi, &ibmvscsis_dev_list, list) {
2501 		vdev = vscsi->dma_dev;
2502 		if (!strcmp(dev_name(&vdev->dev), name)) {
2503 			tport = &vscsi->tport;
2504 			break;
2505 		}
2506 	}
2507 	spin_unlock_bh(&ibmvscsis_dev_lock);
2508 
2509 	return tport;
2510 }
2511 
2512 /**
2513  * ibmvscsis_parse_cmd() - Parse SRP Command
2514  * @vscsi:	Pointer to our adapter structure
2515  * @cmd:	Pointer to command element with SRP command
2516  *
2517  * Parse the srp command; if it is valid then submit it to tcm.
2518  * Note: The return code does not reflect the status of the SCSI CDB.
2519  *
2520  * EXECUTION ENVIRONMENT:
2521  *	Process level
2522  */
2523 static void ibmvscsis_parse_cmd(struct scsi_info *vscsi,
2524 				struct ibmvscsis_cmd *cmd)
2525 {
2526 	struct iu_entry *iue = cmd->iue;
2527 	struct srp_cmd *srp = (struct srp_cmd *)iue->sbuf->buf;
2528 	struct ibmvscsis_nexus *nexus;
2529 	u64 data_len = 0;
2530 	enum dma_data_direction dir;
2531 	int attr = 0;
2532 	int rc = 0;
2533 
2534 	nexus = vscsi->tport.ibmv_nexus;
2535 	/*
2536 	 * additional length in bytes.  Note that the SRP spec says that
2537 	 * additional length is in 4-byte words, but technically the
2538 	 * additional length field is only the upper 6 bits of the byte.
2539 	 * The lower 2 bits are reserved.  If the lower 2 bits are 0 (as
2540 	 * all reserved fields should be), then interpreting the byte as
2541 	 * an int will yield the length in bytes.
2542 	 */
2543 	if (srp->add_cdb_len & 0x03) {
2544 		dev_err(&vscsi->dev, "parse_cmd: reserved bits set in IU\n");
2545 		spin_lock_bh(&vscsi->intr_lock);
2546 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
2547 		ibmvscsis_free_cmd_resources(vscsi, cmd);
2548 		spin_unlock_bh(&vscsi->intr_lock);
2549 		return;
2550 	}
2551 
2552 	if (srp_get_desc_table(srp, &dir, &data_len)) {
2553 		dev_err(&vscsi->dev, "0x%llx: parsing SRP descriptor table failed.\n",
2554 			srp->tag);
2555 		goto fail;
2556 	}
2557 
2558 	cmd->rsp.sol_not = srp->sol_not;
2559 
2560 	switch (srp->task_attr) {
2561 	case SRP_SIMPLE_TASK:
2562 		attr = TCM_SIMPLE_TAG;
2563 		break;
2564 	case SRP_ORDERED_TASK:
2565 		attr = TCM_ORDERED_TAG;
2566 		break;
2567 	case SRP_HEAD_TASK:
2568 		attr = TCM_HEAD_TAG;
2569 		break;
2570 	case SRP_ACA_TASK:
2571 		attr = TCM_ACA_TAG;
2572 		break;
2573 	default:
2574 		dev_err(&vscsi->dev, "Invalid task attribute %d\n",
2575 			srp->task_attr);
2576 		goto fail;
2577 	}
2578 
2579 	cmd->se_cmd.tag = be64_to_cpu(srp->tag);
2580 
2581 	spin_lock_bh(&vscsi->intr_lock);
2582 	list_add_tail(&cmd->list, &vscsi->active_q);
2583 	spin_unlock_bh(&vscsi->intr_lock);
2584 
2585 	srp->lun.scsi_lun[0] &= 0x3f;
2586 
2587 	rc = target_submit_cmd(&cmd->se_cmd, nexus->se_sess, srp->cdb,
2588 			       cmd->sense_buf, scsilun_to_int(&srp->lun),
2589 			       data_len, attr, dir, 0);
2590 	if (rc) {
2591 		dev_err(&vscsi->dev, "target_submit_cmd failed, rc %d\n", rc);
2592 		spin_lock_bh(&vscsi->intr_lock);
2593 		list_del(&cmd->list);
2594 		ibmvscsis_free_cmd_resources(vscsi, cmd);
2595 		spin_unlock_bh(&vscsi->intr_lock);
2596 		goto fail;
2597 	}
2598 	return;
2599 
2600 fail:
2601 	spin_lock_bh(&vscsi->intr_lock);
2602 	ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT_RECONNECT, 0);
2603 	spin_unlock_bh(&vscsi->intr_lock);
2604 }
2605 
2606 /**
2607  * ibmvscsis_parse_task() - Parse SRP Task Management Request
2608  * @vscsi:	Pointer to our adapter structure
2609  * @cmd:	Pointer to command element with SRP task management request
2610  *
2611  * Parse the srp task management request; if it is valid then submit it to tcm.
2612  * Note: The return code does not reflect the status of the task management
2613  * request.
2614  *
2615  * EXECUTION ENVIRONMENT:
2616  *	Processor level
2617  */
2618 static void ibmvscsis_parse_task(struct scsi_info *vscsi,
2619 				 struct ibmvscsis_cmd *cmd)
2620 {
2621 	struct iu_entry *iue = cmd->iue;
2622 	struct srp_tsk_mgmt *srp_tsk = &vio_iu(iue)->srp.tsk_mgmt;
2623 	int tcm_type;
2624 	u64 tag_to_abort = 0;
2625 	int rc = 0;
2626 	struct ibmvscsis_nexus *nexus;
2627 
2628 	nexus = vscsi->tport.ibmv_nexus;
2629 
2630 	cmd->rsp.sol_not = srp_tsk->sol_not;
2631 
2632 	switch (srp_tsk->tsk_mgmt_func) {
2633 	case SRP_TSK_ABORT_TASK:
2634 		tcm_type = TMR_ABORT_TASK;
2635 		tag_to_abort = be64_to_cpu(srp_tsk->task_tag);
2636 		break;
2637 	case SRP_TSK_ABORT_TASK_SET:
2638 		tcm_type = TMR_ABORT_TASK_SET;
2639 		break;
2640 	case SRP_TSK_CLEAR_TASK_SET:
2641 		tcm_type = TMR_CLEAR_TASK_SET;
2642 		break;
2643 	case SRP_TSK_LUN_RESET:
2644 		tcm_type = TMR_LUN_RESET;
2645 		break;
2646 	case SRP_TSK_CLEAR_ACA:
2647 		tcm_type = TMR_CLEAR_ACA;
2648 		break;
2649 	default:
2650 		dev_err(&vscsi->dev, "unknown task mgmt func %d\n",
2651 			srp_tsk->tsk_mgmt_func);
2652 		cmd->se_cmd.se_tmr_req->response =
2653 			TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
2654 		rc = -1;
2655 		break;
2656 	}
2657 
2658 	if (!rc) {
2659 		cmd->se_cmd.tag = be64_to_cpu(srp_tsk->tag);
2660 
2661 		spin_lock_bh(&vscsi->intr_lock);
2662 		list_add_tail(&cmd->list, &vscsi->active_q);
2663 		spin_unlock_bh(&vscsi->intr_lock);
2664 
2665 		srp_tsk->lun.scsi_lun[0] &= 0x3f;
2666 
2667 		pr_debug("calling submit_tmr, func %d\n",
2668 			 srp_tsk->tsk_mgmt_func);
2669 		rc = target_submit_tmr(&cmd->se_cmd, nexus->se_sess, NULL,
2670 				       scsilun_to_int(&srp_tsk->lun), srp_tsk,
2671 				       tcm_type, GFP_KERNEL, tag_to_abort, 0);
2672 		if (rc) {
2673 			dev_err(&vscsi->dev, "target_submit_tmr failed, rc %d\n",
2674 				rc);
2675 			spin_lock_bh(&vscsi->intr_lock);
2676 			list_del(&cmd->list);
2677 			spin_unlock_bh(&vscsi->intr_lock);
2678 			cmd->se_cmd.se_tmr_req->response =
2679 				TMR_FUNCTION_REJECTED;
2680 		}
2681 	}
2682 
2683 	if (rc)
2684 		transport_send_check_condition_and_sense(&cmd->se_cmd, 0, 0);
2685 }
2686 
2687 static void ibmvscsis_scheduler(struct work_struct *work)
2688 {
2689 	struct ibmvscsis_cmd *cmd = container_of(work, struct ibmvscsis_cmd,
2690 						 work);
2691 	struct scsi_info *vscsi = cmd->adapter;
2692 
2693 	spin_lock_bh(&vscsi->intr_lock);
2694 
2695 	/* Remove from schedule_q */
2696 	list_del(&cmd->list);
2697 
2698 	/* Don't submit cmd if we're disconnecting */
2699 	if (vscsi->flags & (SCHEDULE_DISCONNECT | DISCONNECT_SCHEDULED)) {
2700 		ibmvscsis_free_cmd_resources(vscsi, cmd);
2701 
2702 		/* ibmvscsis_disconnect might be waiting for us */
2703 		if (list_empty(&vscsi->active_q) &&
2704 		    list_empty(&vscsi->schedule_q) &&
2705 		    (vscsi->flags & WAIT_FOR_IDLE)) {
2706 			vscsi->flags &= ~WAIT_FOR_IDLE;
2707 			complete(&vscsi->wait_idle);
2708 		}
2709 
2710 		spin_unlock_bh(&vscsi->intr_lock);
2711 		return;
2712 	}
2713 
2714 	spin_unlock_bh(&vscsi->intr_lock);
2715 
2716 	switch (cmd->type) {
2717 	case SCSI_CDB:
2718 		ibmvscsis_parse_cmd(vscsi, cmd);
2719 		break;
2720 	case TASK_MANAGEMENT:
2721 		ibmvscsis_parse_task(vscsi, cmd);
2722 		break;
2723 	default:
2724 		dev_err(&vscsi->dev, "scheduler, invalid cmd type %d\n",
2725 			cmd->type);
2726 		spin_lock_bh(&vscsi->intr_lock);
2727 		ibmvscsis_free_cmd_resources(vscsi, cmd);
2728 		spin_unlock_bh(&vscsi->intr_lock);
2729 		break;
2730 	}
2731 }
2732 
2733 static int ibmvscsis_alloc_cmds(struct scsi_info *vscsi, int num)
2734 {
2735 	struct ibmvscsis_cmd *cmd;
2736 	int i;
2737 
2738 	INIT_LIST_HEAD(&vscsi->free_cmd);
2739 	vscsi->cmd_pool = kcalloc(num, sizeof(struct ibmvscsis_cmd),
2740 				  GFP_KERNEL);
2741 	if (!vscsi->cmd_pool)
2742 		return -ENOMEM;
2743 
2744 	for (i = 0, cmd = (struct ibmvscsis_cmd *)vscsi->cmd_pool; i < num;
2745 	     i++, cmd++) {
2746 		cmd->abort_cmd = NULL;
2747 		cmd->adapter = vscsi;
2748 		INIT_WORK(&cmd->work, ibmvscsis_scheduler);
2749 		list_add_tail(&cmd->list, &vscsi->free_cmd);
2750 	}
2751 
2752 	return 0;
2753 }
2754 
2755 static void ibmvscsis_free_cmds(struct scsi_info *vscsi)
2756 {
2757 	kfree(vscsi->cmd_pool);
2758 	vscsi->cmd_pool = NULL;
2759 	INIT_LIST_HEAD(&vscsi->free_cmd);
2760 }
2761 
2762 /**
2763  * ibmvscsis_service_wait_q() - Service Waiting Queue
2764  * @timer:	Pointer to timer which has expired
2765  *
2766  * This routine is called when the timer pops to service the waiting
2767  * queue. Elements on the queue have completed, their responses have been
2768  * copied to the client, but the client's response queue was full so
2769  * the queue message could not be sent. The routine grabs the proper locks
2770  * and calls send messages.
2771  *
2772  * EXECUTION ENVIRONMENT:
2773  *	called at interrupt level
2774  */
2775 static enum hrtimer_restart ibmvscsis_service_wait_q(struct hrtimer *timer)
2776 {
2777 	struct timer_cb *p_timer = container_of(timer, struct timer_cb, timer);
2778 	struct scsi_info *vscsi = container_of(p_timer, struct scsi_info,
2779 					       rsp_q_timer);
2780 
2781 	spin_lock_bh(&vscsi->intr_lock);
2782 	p_timer->timer_pops += 1;
2783 	p_timer->started = false;
2784 	ibmvscsis_send_messages(vscsi);
2785 	spin_unlock_bh(&vscsi->intr_lock);
2786 
2787 	return HRTIMER_NORESTART;
2788 }
2789 
2790 static long ibmvscsis_alloctimer(struct scsi_info *vscsi)
2791 {
2792 	struct timer_cb *p_timer;
2793 
2794 	p_timer = &vscsi->rsp_q_timer;
2795 	hrtimer_init(&p_timer->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2796 
2797 	p_timer->timer.function = ibmvscsis_service_wait_q;
2798 	p_timer->started = false;
2799 	p_timer->timer_pops = 0;
2800 
2801 	return ADAPT_SUCCESS;
2802 }
2803 
2804 static void ibmvscsis_freetimer(struct scsi_info *vscsi)
2805 {
2806 	struct timer_cb *p_timer;
2807 
2808 	p_timer = &vscsi->rsp_q_timer;
2809 
2810 	(void)hrtimer_cancel(&p_timer->timer);
2811 
2812 	p_timer->started = false;
2813 	p_timer->timer_pops = 0;
2814 }
2815 
2816 static irqreturn_t ibmvscsis_interrupt(int dummy, void *data)
2817 {
2818 	struct scsi_info *vscsi = data;
2819 
2820 	vio_disable_interrupts(vscsi->dma_dev);
2821 	tasklet_schedule(&vscsi->work_task);
2822 
2823 	return IRQ_HANDLED;
2824 }
2825 
2826 /**
2827  * ibmvscsis_enable_change_state() - Set new state based on enabled status
2828  * @vscsi:	Pointer to our adapter structure
2829  *
2830  * This function determines our new state now that we are enabled.  This
2831  * may involve sending an Init Complete message to the client.
2832  *
2833  * Must be called with interrupt lock held.
2834  */
2835 static long ibmvscsis_enable_change_state(struct scsi_info *vscsi)
2836 {
2837 	int bytes;
2838 	long rc = ADAPT_SUCCESS;
2839 
2840 	bytes = vscsi->cmd_q.size * PAGE_SIZE;
2841 	rc = h_reg_crq(vscsi->dds.unit_id, vscsi->cmd_q.crq_token, bytes);
2842 	if (rc == H_CLOSED || rc == H_SUCCESS) {
2843 		vscsi->state = WAIT_CONNECTION;
2844 		rc = ibmvscsis_establish_new_q(vscsi);
2845 	}
2846 
2847 	if (rc != ADAPT_SUCCESS) {
2848 		vscsi->state = ERR_DISCONNECTED;
2849 		vscsi->flags |= RESPONSE_Q_DOWN;
2850 	}
2851 
2852 	return rc;
2853 }
2854 
2855 /**
2856  * ibmvscsis_create_command_q() - Create Command Queue
2857  * @vscsi:	Pointer to our adapter structure
2858  * @num_cmds:	Currently unused.  In the future, may be used to determine
2859  *		the size of the CRQ.
2860  *
2861  * Allocates memory for command queue maps remote memory into an ioba
2862  * initializes the command response queue
2863  *
2864  * EXECUTION ENVIRONMENT:
2865  *	Process level only
2866  */
2867 static long ibmvscsis_create_command_q(struct scsi_info *vscsi, int num_cmds)
2868 {
2869 	int pages;
2870 	struct vio_dev *vdev = vscsi->dma_dev;
2871 
2872 	/* We might support multiple pages in the future, but just 1 for now */
2873 	pages = 1;
2874 
2875 	vscsi->cmd_q.size = pages;
2876 
2877 	vscsi->cmd_q.base_addr =
2878 		(struct viosrp_crq *)get_zeroed_page(GFP_KERNEL);
2879 	if (!vscsi->cmd_q.base_addr)
2880 		return -ENOMEM;
2881 
2882 	vscsi->cmd_q.mask = ((uint)pages * CRQ_PER_PAGE) - 1;
2883 
2884 	vscsi->cmd_q.crq_token = dma_map_single(&vdev->dev,
2885 						vscsi->cmd_q.base_addr,
2886 						PAGE_SIZE, DMA_BIDIRECTIONAL);
2887 	if (dma_mapping_error(&vdev->dev, vscsi->cmd_q.crq_token)) {
2888 		free_page((unsigned long)vscsi->cmd_q.base_addr);
2889 		return -ENOMEM;
2890 	}
2891 
2892 	return 0;
2893 }
2894 
2895 /**
2896  * ibmvscsis_destroy_command_q - Destroy Command Queue
2897  * @vscsi:	Pointer to our adapter structure
2898  *
2899  * Releases memory for command queue and unmaps mapped remote memory.
2900  *
2901  * EXECUTION ENVIRONMENT:
2902  *	Process level only
2903  */
2904 static void ibmvscsis_destroy_command_q(struct scsi_info *vscsi)
2905 {
2906 	dma_unmap_single(&vscsi->dma_dev->dev, vscsi->cmd_q.crq_token,
2907 			 PAGE_SIZE, DMA_BIDIRECTIONAL);
2908 	free_page((unsigned long)vscsi->cmd_q.base_addr);
2909 	vscsi->cmd_q.base_addr = NULL;
2910 	vscsi->state = NO_QUEUE;
2911 }
2912 
2913 static u8 ibmvscsis_fast_fail(struct scsi_info *vscsi,
2914 			      struct ibmvscsis_cmd *cmd)
2915 {
2916 	struct iu_entry *iue = cmd->iue;
2917 	struct se_cmd *se_cmd = &cmd->se_cmd;
2918 	struct srp_cmd *srp = (struct srp_cmd *)iue->sbuf->buf;
2919 	struct scsi_sense_hdr sshdr;
2920 	u8 rc = se_cmd->scsi_status;
2921 
2922 	if (vscsi->fast_fail && (READ_CMD(srp->cdb) || WRITE_CMD(srp->cdb)))
2923 		if (scsi_normalize_sense(se_cmd->sense_buffer,
2924 					 se_cmd->scsi_sense_length, &sshdr))
2925 			if (sshdr.sense_key == HARDWARE_ERROR &&
2926 			    (se_cmd->residual_count == 0 ||
2927 			     se_cmd->residual_count == se_cmd->data_length)) {
2928 				rc = NO_SENSE;
2929 				cmd->flags |= CMD_FAST_FAIL;
2930 			}
2931 
2932 	return rc;
2933 }
2934 
2935 /**
2936  * srp_build_response() - Build an SRP response buffer
2937  * @vscsi:	Pointer to our adapter structure
2938  * @cmd:	Pointer to command for which to send the response
2939  * @len_p:	Where to return the length of the IU response sent.  This
2940  *		is needed to construct the CRQ response.
2941  *
2942  * Build the SRP response buffer and copy it to the client's memory space.
2943  */
2944 static long srp_build_response(struct scsi_info *vscsi,
2945 			       struct ibmvscsis_cmd *cmd, uint *len_p)
2946 {
2947 	struct iu_entry *iue = cmd->iue;
2948 	struct se_cmd *se_cmd = &cmd->se_cmd;
2949 	struct srp_rsp *rsp;
2950 	uint len;
2951 	u32 rsp_code;
2952 	char *data;
2953 	u32 *tsk_status;
2954 	long rc = ADAPT_SUCCESS;
2955 
2956 	spin_lock_bh(&vscsi->intr_lock);
2957 
2958 	rsp = &vio_iu(iue)->srp.rsp;
2959 	len = sizeof(*rsp);
2960 	memset(rsp, 0, len);
2961 	data = rsp->data;
2962 
2963 	rsp->opcode = SRP_RSP;
2964 
2965 	if (vscsi->credit > 0 && vscsi->state == SRP_PROCESSING)
2966 		rsp->req_lim_delta = cpu_to_be32(vscsi->credit);
2967 	else
2968 		rsp->req_lim_delta = cpu_to_be32(1 + vscsi->credit);
2969 	rsp->tag = cmd->rsp.tag;
2970 	rsp->flags = 0;
2971 
2972 	if (cmd->type == SCSI_CDB) {
2973 		rsp->status = ibmvscsis_fast_fail(vscsi, cmd);
2974 		if (rsp->status) {
2975 			pr_debug("build_resp: cmd %p, scsi status %d\n", cmd,
2976 				 (int)rsp->status);
2977 			ibmvscsis_determine_resid(se_cmd, rsp);
2978 			if (se_cmd->scsi_sense_length && se_cmd->sense_buffer) {
2979 				rsp->sense_data_len =
2980 					cpu_to_be32(se_cmd->scsi_sense_length);
2981 				rsp->flags |= SRP_RSP_FLAG_SNSVALID;
2982 				len += se_cmd->scsi_sense_length;
2983 				memcpy(data, se_cmd->sense_buffer,
2984 				       se_cmd->scsi_sense_length);
2985 			}
2986 			rsp->sol_not = (cmd->rsp.sol_not & UCSOLNT) >>
2987 				UCSOLNT_RESP_SHIFT;
2988 		} else if (cmd->flags & CMD_FAST_FAIL) {
2989 			pr_debug("build_resp: cmd %p, fast fail\n", cmd);
2990 			rsp->sol_not = (cmd->rsp.sol_not & UCSOLNT) >>
2991 				UCSOLNT_RESP_SHIFT;
2992 		} else {
2993 			rsp->sol_not = (cmd->rsp.sol_not & SCSOLNT) >>
2994 				SCSOLNT_RESP_SHIFT;
2995 		}
2996 	} else {
2997 		/* this is task management */
2998 		rsp->status = 0;
2999 		rsp->resp_data_len = cpu_to_be32(4);
3000 		rsp->flags |= SRP_RSP_FLAG_RSPVALID;
3001 
3002 		switch (se_cmd->se_tmr_req->response) {
3003 		case TMR_FUNCTION_COMPLETE:
3004 		case TMR_TASK_DOES_NOT_EXIST:
3005 			rsp_code = SRP_TASK_MANAGEMENT_FUNCTION_COMPLETE;
3006 			rsp->sol_not = (cmd->rsp.sol_not & SCSOLNT) >>
3007 				SCSOLNT_RESP_SHIFT;
3008 			break;
3009 		case TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED:
3010 		case TMR_LUN_DOES_NOT_EXIST:
3011 			rsp_code = SRP_TASK_MANAGEMENT_FUNCTION_NOT_SUPPORTED;
3012 			rsp->sol_not = (cmd->rsp.sol_not & UCSOLNT) >>
3013 				UCSOLNT_RESP_SHIFT;
3014 			break;
3015 		case TMR_FUNCTION_FAILED:
3016 		case TMR_FUNCTION_REJECTED:
3017 		default:
3018 			rsp_code = SRP_TASK_MANAGEMENT_FUNCTION_FAILED;
3019 			rsp->sol_not = (cmd->rsp.sol_not & UCSOLNT) >>
3020 				UCSOLNT_RESP_SHIFT;
3021 			break;
3022 		}
3023 
3024 		tsk_status = (u32 *)data;
3025 		*tsk_status = cpu_to_be32(rsp_code);
3026 		data = (char *)(tsk_status + 1);
3027 		len += 4;
3028 	}
3029 
3030 	dma_wmb();
3031 	rc = h_copy_rdma(len, vscsi->dds.window[LOCAL].liobn, iue->sbuf->dma,
3032 			 vscsi->dds.window[REMOTE].liobn,
3033 			 be64_to_cpu(iue->remote_token));
3034 
3035 	switch (rc) {
3036 	case H_SUCCESS:
3037 		vscsi->credit = 0;
3038 		*len_p = len;
3039 		break;
3040 	case H_PERMISSION:
3041 		if (connection_broken(vscsi))
3042 			vscsi->flags |= RESPONSE_Q_DOWN | CLIENT_FAILED;
3043 
3044 		dev_err(&vscsi->dev, "build_response: error copying to client, rc %ld, flags 0x%x, state 0x%hx\n",
3045 			rc, vscsi->flags, vscsi->state);
3046 		break;
3047 	case H_SOURCE_PARM:
3048 	case H_DEST_PARM:
3049 	default:
3050 		dev_err(&vscsi->dev, "build_response: error copying to client, rc %ld\n",
3051 			rc);
3052 		break;
3053 	}
3054 
3055 	spin_unlock_bh(&vscsi->intr_lock);
3056 
3057 	return rc;
3058 }
3059 
3060 static int ibmvscsis_rdma(struct ibmvscsis_cmd *cmd, struct scatterlist *sg,
3061 			  int nsg, struct srp_direct_buf *md, int nmd,
3062 			  enum dma_data_direction dir, unsigned int bytes)
3063 {
3064 	struct iu_entry *iue = cmd->iue;
3065 	struct srp_target *target = iue->target;
3066 	struct scsi_info *vscsi = target->ldata;
3067 	struct scatterlist *sgp;
3068 	dma_addr_t client_ioba, server_ioba;
3069 	ulong buf_len;
3070 	ulong client_len, server_len;
3071 	int md_idx;
3072 	long tx_len;
3073 	long rc = 0;
3074 
3075 	if (bytes == 0)
3076 		return 0;
3077 
3078 	sgp = sg;
3079 	client_len = 0;
3080 	server_len = 0;
3081 	md_idx = 0;
3082 	tx_len = bytes;
3083 
3084 	do {
3085 		if (client_len == 0) {
3086 			if (md_idx >= nmd) {
3087 				dev_err(&vscsi->dev, "rdma: ran out of client memory descriptors\n");
3088 				rc = -EIO;
3089 				break;
3090 			}
3091 			client_ioba = be64_to_cpu(md[md_idx].va);
3092 			client_len = be32_to_cpu(md[md_idx].len);
3093 		}
3094 		if (server_len == 0) {
3095 			if (!sgp) {
3096 				dev_err(&vscsi->dev, "rdma: ran out of scatter/gather list\n");
3097 				rc = -EIO;
3098 				break;
3099 			}
3100 			server_ioba = sg_dma_address(sgp);
3101 			server_len = sg_dma_len(sgp);
3102 		}
3103 
3104 		buf_len = tx_len;
3105 
3106 		if (buf_len > client_len)
3107 			buf_len = client_len;
3108 
3109 		if (buf_len > server_len)
3110 			buf_len = server_len;
3111 
3112 		if (buf_len > max_vdma_size)
3113 			buf_len = max_vdma_size;
3114 
3115 		if (dir == DMA_TO_DEVICE) {
3116 			/* read from client */
3117 			rc = h_copy_rdma(buf_len,
3118 					 vscsi->dds.window[REMOTE].liobn,
3119 					 client_ioba,
3120 					 vscsi->dds.window[LOCAL].liobn,
3121 					 server_ioba);
3122 		} else {
3123 			/* The h_copy_rdma will cause phyp, running in another
3124 			 * partition, to read memory, so we need to make sure
3125 			 * the data has been written out, hence these syncs.
3126 			 */
3127 			/* ensure that everything is in memory */
3128 			isync();
3129 			/* ensure that memory has been made visible */
3130 			dma_wmb();
3131 			rc = h_copy_rdma(buf_len,
3132 					 vscsi->dds.window[LOCAL].liobn,
3133 					 server_ioba,
3134 					 vscsi->dds.window[REMOTE].liobn,
3135 					 client_ioba);
3136 		}
3137 		switch (rc) {
3138 		case H_SUCCESS:
3139 			break;
3140 		case H_PERMISSION:
3141 		case H_SOURCE_PARM:
3142 		case H_DEST_PARM:
3143 			if (connection_broken(vscsi)) {
3144 				spin_lock_bh(&vscsi->intr_lock);
3145 				vscsi->flags |=
3146 					(RESPONSE_Q_DOWN | CLIENT_FAILED);
3147 				spin_unlock_bh(&vscsi->intr_lock);
3148 			}
3149 			dev_err(&vscsi->dev, "rdma: h_copy_rdma failed, rc %ld\n",
3150 				rc);
3151 			break;
3152 
3153 		default:
3154 			dev_err(&vscsi->dev, "rdma: unknown error %ld from h_copy_rdma\n",
3155 				rc);
3156 			break;
3157 		}
3158 
3159 		if (!rc) {
3160 			tx_len -= buf_len;
3161 			if (tx_len) {
3162 				client_len -= buf_len;
3163 				if (client_len == 0)
3164 					md_idx++;
3165 				else
3166 					client_ioba += buf_len;
3167 
3168 				server_len -= buf_len;
3169 				if (server_len == 0)
3170 					sgp = sg_next(sgp);
3171 				else
3172 					server_ioba += buf_len;
3173 			} else {
3174 				break;
3175 			}
3176 		}
3177 	} while (!rc);
3178 
3179 	return rc;
3180 }
3181 
3182 /**
3183  * ibmvscsis_handle_crq() - Handle CRQ
3184  * @data:	Pointer to our adapter structure
3185  *
3186  * Read the command elements from the command queue and copy the payloads
3187  * associated with the command elements to local memory and execute the
3188  * SRP requests.
3189  *
3190  * Note: this is an edge triggered interrupt. It can not be shared.
3191  */
3192 static void ibmvscsis_handle_crq(unsigned long data)
3193 {
3194 	struct scsi_info *vscsi = (struct scsi_info *)data;
3195 	struct viosrp_crq *crq;
3196 	long rc;
3197 	bool ack = true;
3198 	volatile u8 valid;
3199 
3200 	spin_lock_bh(&vscsi->intr_lock);
3201 
3202 	pr_debug("got interrupt\n");
3203 
3204 	/*
3205 	 * if we are in a path where we are waiting for all pending commands
3206 	 * to complete because we received a transport event and anything in
3207 	 * the command queue is for a new connection, do nothing
3208 	 */
3209 	if (TARGET_STOP(vscsi)) {
3210 		vio_enable_interrupts(vscsi->dma_dev);
3211 
3212 		pr_debug("handle_crq, don't process: flags 0x%x, state 0x%hx\n",
3213 			 vscsi->flags, vscsi->state);
3214 		spin_unlock_bh(&vscsi->intr_lock);
3215 		return;
3216 	}
3217 
3218 	rc = vscsi->flags & SCHEDULE_DISCONNECT;
3219 	crq = vscsi->cmd_q.base_addr + vscsi->cmd_q.index;
3220 	valid = crq->valid;
3221 	dma_rmb();
3222 
3223 	while (valid) {
3224 		/*
3225 		 * These are edege triggered interrupts. After dropping out of
3226 		 * the while loop, the code must check for work since an
3227 		 * interrupt could be lost, and an elment be left on the queue,
3228 		 * hence the label.
3229 		 */
3230 cmd_work:
3231 		vscsi->cmd_q.index =
3232 			(vscsi->cmd_q.index + 1) & vscsi->cmd_q.mask;
3233 
3234 		if (!rc) {
3235 			rc = ibmvscsis_parse_command(vscsi, crq);
3236 		} else {
3237 			if ((uint)crq->valid == VALID_TRANS_EVENT) {
3238 				/*
3239 				 * must service the transport layer events even
3240 				 * in an error state, dont break out until all
3241 				 * the consecutive transport events have been
3242 				 * processed
3243 				 */
3244 				rc = ibmvscsis_trans_event(vscsi, crq);
3245 			} else if (vscsi->flags & TRANS_EVENT) {
3246 				/*
3247 				 * if a transport event has occurred leave
3248 				 * everything but transport events on the queue
3249 				 *
3250 				 * need to decrement the queue index so we can
3251 				 * look at the element again
3252 				 */
3253 				if (vscsi->cmd_q.index)
3254 					vscsi->cmd_q.index -= 1;
3255 				else
3256 					/*
3257 					 * index is at 0 it just wrapped.
3258 					 * have it index last element in q
3259 					 */
3260 					vscsi->cmd_q.index = vscsi->cmd_q.mask;
3261 				break;
3262 			}
3263 		}
3264 
3265 		crq->valid = INVALIDATE_CMD_RESP_EL;
3266 
3267 		crq = vscsi->cmd_q.base_addr + vscsi->cmd_q.index;
3268 		valid = crq->valid;
3269 		dma_rmb();
3270 	}
3271 
3272 	if (!rc) {
3273 		if (ack) {
3274 			vio_enable_interrupts(vscsi->dma_dev);
3275 			ack = false;
3276 			pr_debug("handle_crq, reenabling interrupts\n");
3277 		}
3278 		valid = crq->valid;
3279 		dma_rmb();
3280 		if (valid)
3281 			goto cmd_work;
3282 	} else {
3283 		pr_debug("handle_crq, error: flags 0x%x, state 0x%hx, crq index 0x%x\n",
3284 			 vscsi->flags, vscsi->state, vscsi->cmd_q.index);
3285 	}
3286 
3287 	pr_debug("Leaving handle_crq: schedule_q empty %d, flags 0x%x, state 0x%hx\n",
3288 		 (int)list_empty(&vscsi->schedule_q), vscsi->flags,
3289 		 vscsi->state);
3290 
3291 	spin_unlock_bh(&vscsi->intr_lock);
3292 }
3293 
3294 static int ibmvscsis_probe(struct vio_dev *vdev,
3295 			   const struct vio_device_id *id)
3296 {
3297 	struct scsi_info *vscsi;
3298 	int rc = 0;
3299 	long hrc = 0;
3300 	char wq_name[24];
3301 
3302 	vscsi = kzalloc(sizeof(*vscsi), GFP_KERNEL);
3303 	if (!vscsi) {
3304 		rc = -ENOMEM;
3305 		pr_err("probe: allocation of adapter failed\n");
3306 		return rc;
3307 	}
3308 
3309 	vscsi->dma_dev = vdev;
3310 	vscsi->dev = vdev->dev;
3311 	INIT_LIST_HEAD(&vscsi->schedule_q);
3312 	INIT_LIST_HEAD(&vscsi->waiting_rsp);
3313 	INIT_LIST_HEAD(&vscsi->active_q);
3314 
3315 	snprintf(vscsi->tport.tport_name, IBMVSCSIS_NAMELEN, "%s",
3316 		 dev_name(&vdev->dev));
3317 
3318 	pr_debug("probe tport_name: %s\n", vscsi->tport.tport_name);
3319 
3320 	rc = read_dma_window(vscsi);
3321 	if (rc)
3322 		goto free_adapter;
3323 	pr_debug("Probe: liobn 0x%x, riobn 0x%x\n",
3324 		 vscsi->dds.window[LOCAL].liobn,
3325 		 vscsi->dds.window[REMOTE].liobn);
3326 
3327 	strcpy(vscsi->eye, "VSCSI ");
3328 	strncat(vscsi->eye, vdev->name, MAX_EYE);
3329 
3330 	vscsi->dds.unit_id = vdev->unit_address;
3331 	strncpy(vscsi->dds.partition_name, partition_name,
3332 		sizeof(vscsi->dds.partition_name));
3333 	vscsi->dds.partition_num = partition_number;
3334 
3335 	spin_lock_bh(&ibmvscsis_dev_lock);
3336 	list_add_tail(&vscsi->list, &ibmvscsis_dev_list);
3337 	spin_unlock_bh(&ibmvscsis_dev_lock);
3338 
3339 	/*
3340 	 * TBD: How do we determine # of cmds to request?  Do we know how
3341 	 * many "children" we have?
3342 	 */
3343 	vscsi->request_limit = INITIAL_SRP_LIMIT;
3344 	rc = srp_target_alloc(&vscsi->target, &vdev->dev, vscsi->request_limit,
3345 			      SRP_MAX_IU_LEN);
3346 	if (rc)
3347 		goto rem_list;
3348 
3349 	vscsi->target.ldata = vscsi;
3350 
3351 	rc = ibmvscsis_alloc_cmds(vscsi, vscsi->request_limit);
3352 	if (rc) {
3353 		dev_err(&vscsi->dev, "alloc_cmds failed, rc %d, num %d\n",
3354 			rc, vscsi->request_limit);
3355 		goto free_target;
3356 	}
3357 
3358 	/*
3359 	 * Note: the lock is used in freeing timers, so must initialize
3360 	 * first so that ordering in case of error is correct.
3361 	 */
3362 	spin_lock_init(&vscsi->intr_lock);
3363 
3364 	rc = ibmvscsis_alloctimer(vscsi);
3365 	if (rc) {
3366 		dev_err(&vscsi->dev, "probe: alloctimer failed, rc %d\n", rc);
3367 		goto free_cmds;
3368 	}
3369 
3370 	rc = ibmvscsis_create_command_q(vscsi, 256);
3371 	if (rc) {
3372 		dev_err(&vscsi->dev, "probe: create_command_q failed, rc %d\n",
3373 			rc);
3374 		goto free_timer;
3375 	}
3376 
3377 	vscsi->map_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
3378 	if (!vscsi->map_buf) {
3379 		rc = -ENOMEM;
3380 		dev_err(&vscsi->dev, "probe: allocating cmd buffer failed\n");
3381 		goto destroy_queue;
3382 	}
3383 
3384 	vscsi->map_ioba = dma_map_single(&vdev->dev, vscsi->map_buf, PAGE_SIZE,
3385 					 DMA_BIDIRECTIONAL);
3386 	if (dma_mapping_error(&vdev->dev, vscsi->map_ioba)) {
3387 		rc = -ENOMEM;
3388 		dev_err(&vscsi->dev, "probe: error mapping command buffer\n");
3389 		goto free_buf;
3390 	}
3391 
3392 	hrc = h_vioctl(vscsi->dds.unit_id, H_GET_PARTNER_INFO,
3393 		       (u64)vscsi->map_ioba | ((u64)PAGE_SIZE << 32), 0, 0, 0,
3394 		       0);
3395 	if (hrc == H_SUCCESS)
3396 		vscsi->client_data.partition_number =
3397 			be64_to_cpu(*(u64 *)vscsi->map_buf);
3398 	/*
3399 	 * We expect the VIOCTL to fail if we're configured as "any
3400 	 * client can connect" and the client isn't activated yet.
3401 	 * We'll make the call again when he sends an init msg.
3402 	 */
3403 	pr_debug("probe hrc %ld, client partition num %d\n",
3404 		 hrc, vscsi->client_data.partition_number);
3405 
3406 	tasklet_init(&vscsi->work_task, ibmvscsis_handle_crq,
3407 		     (unsigned long)vscsi);
3408 
3409 	init_completion(&vscsi->wait_idle);
3410 	init_completion(&vscsi->unconfig);
3411 
3412 	snprintf(wq_name, 24, "ibmvscsis%s", dev_name(&vdev->dev));
3413 	vscsi->work_q = create_workqueue(wq_name);
3414 	if (!vscsi->work_q) {
3415 		rc = -ENOMEM;
3416 		dev_err(&vscsi->dev, "create_workqueue failed\n");
3417 		goto unmap_buf;
3418 	}
3419 
3420 	rc = request_irq(vdev->irq, ibmvscsis_interrupt, 0, "ibmvscsis", vscsi);
3421 	if (rc) {
3422 		rc = -EPERM;
3423 		dev_err(&vscsi->dev, "probe: request_irq failed, rc %d\n", rc);
3424 		goto destroy_WQ;
3425 	}
3426 
3427 	vscsi->state = WAIT_ENABLED;
3428 
3429 	dev_set_drvdata(&vdev->dev, vscsi);
3430 
3431 	return 0;
3432 
3433 destroy_WQ:
3434 	destroy_workqueue(vscsi->work_q);
3435 unmap_buf:
3436 	dma_unmap_single(&vdev->dev, vscsi->map_ioba, PAGE_SIZE,
3437 			 DMA_BIDIRECTIONAL);
3438 free_buf:
3439 	kfree(vscsi->map_buf);
3440 destroy_queue:
3441 	tasklet_kill(&vscsi->work_task);
3442 	ibmvscsis_unregister_command_q(vscsi);
3443 	ibmvscsis_destroy_command_q(vscsi);
3444 free_timer:
3445 	ibmvscsis_freetimer(vscsi);
3446 free_cmds:
3447 	ibmvscsis_free_cmds(vscsi);
3448 free_target:
3449 	srp_target_free(&vscsi->target);
3450 rem_list:
3451 	spin_lock_bh(&ibmvscsis_dev_lock);
3452 	list_del(&vscsi->list);
3453 	spin_unlock_bh(&ibmvscsis_dev_lock);
3454 free_adapter:
3455 	kfree(vscsi);
3456 
3457 	return rc;
3458 }
3459 
3460 static int ibmvscsis_remove(struct vio_dev *vdev)
3461 {
3462 	struct scsi_info *vscsi = dev_get_drvdata(&vdev->dev);
3463 
3464 	pr_debug("remove (%s)\n", dev_name(&vscsi->dma_dev->dev));
3465 
3466 	spin_lock_bh(&vscsi->intr_lock);
3467 	ibmvscsis_post_disconnect(vscsi, UNCONFIGURING, 0);
3468 	vscsi->flags |= CFG_SLEEPING;
3469 	spin_unlock_bh(&vscsi->intr_lock);
3470 	wait_for_completion(&vscsi->unconfig);
3471 
3472 	vio_disable_interrupts(vdev);
3473 	free_irq(vdev->irq, vscsi);
3474 	destroy_workqueue(vscsi->work_q);
3475 	dma_unmap_single(&vdev->dev, vscsi->map_ioba, PAGE_SIZE,
3476 			 DMA_BIDIRECTIONAL);
3477 	kfree(vscsi->map_buf);
3478 	tasklet_kill(&vscsi->work_task);
3479 	ibmvscsis_destroy_command_q(vscsi);
3480 	ibmvscsis_freetimer(vscsi);
3481 	ibmvscsis_free_cmds(vscsi);
3482 	srp_target_free(&vscsi->target);
3483 	spin_lock_bh(&ibmvscsis_dev_lock);
3484 	list_del(&vscsi->list);
3485 	spin_unlock_bh(&ibmvscsis_dev_lock);
3486 	kfree(vscsi);
3487 
3488 	return 0;
3489 }
3490 
3491 static ssize_t system_id_show(struct device *dev,
3492 			      struct device_attribute *attr, char *buf)
3493 {
3494 	return snprintf(buf, PAGE_SIZE, "%s\n", system_id);
3495 }
3496 
3497 static ssize_t partition_number_show(struct device *dev,
3498 				     struct device_attribute *attr, char *buf)
3499 {
3500 	return snprintf(buf, PAGE_SIZE, "%x\n", partition_number);
3501 }
3502 
3503 static ssize_t unit_address_show(struct device *dev,
3504 				 struct device_attribute *attr, char *buf)
3505 {
3506 	struct scsi_info *vscsi = container_of(dev, struct scsi_info, dev);
3507 
3508 	return snprintf(buf, PAGE_SIZE, "%x\n", vscsi->dma_dev->unit_address);
3509 }
3510 
3511 static int ibmvscsis_get_system_info(void)
3512 {
3513 	struct device_node *rootdn, *vdevdn;
3514 	const char *id, *model, *name;
3515 	const uint *num;
3516 
3517 	rootdn = of_find_node_by_path("/");
3518 	if (!rootdn)
3519 		return -ENOENT;
3520 
3521 	model = of_get_property(rootdn, "model", NULL);
3522 	id = of_get_property(rootdn, "system-id", NULL);
3523 	if (model && id)
3524 		snprintf(system_id, sizeof(system_id), "%s-%s", model, id);
3525 
3526 	name = of_get_property(rootdn, "ibm,partition-name", NULL);
3527 	if (name)
3528 		strncpy(partition_name, name, sizeof(partition_name));
3529 
3530 	num = of_get_property(rootdn, "ibm,partition-no", NULL);
3531 	if (num)
3532 		partition_number = of_read_number(num, 1);
3533 
3534 	of_node_put(rootdn);
3535 
3536 	vdevdn = of_find_node_by_path("/vdevice");
3537 	if (vdevdn) {
3538 		const uint *mvds;
3539 
3540 		mvds = of_get_property(vdevdn, "ibm,max-virtual-dma-size",
3541 				       NULL);
3542 		if (mvds)
3543 			max_vdma_size = *mvds;
3544 		of_node_put(vdevdn);
3545 	}
3546 
3547 	return 0;
3548 }
3549 
3550 static char *ibmvscsis_get_fabric_name(void)
3551 {
3552 	return "ibmvscsis";
3553 }
3554 
3555 static char *ibmvscsis_get_fabric_wwn(struct se_portal_group *se_tpg)
3556 {
3557 	struct ibmvscsis_tport *tport =
3558 		container_of(se_tpg, struct ibmvscsis_tport, se_tpg);
3559 
3560 	return tport->tport_name;
3561 }
3562 
3563 static u16 ibmvscsis_get_tag(struct se_portal_group *se_tpg)
3564 {
3565 	struct ibmvscsis_tport *tport =
3566 		container_of(se_tpg, struct ibmvscsis_tport, se_tpg);
3567 
3568 	return tport->tport_tpgt;
3569 }
3570 
3571 static u32 ibmvscsis_get_default_depth(struct se_portal_group *se_tpg)
3572 {
3573 	return 1;
3574 }
3575 
3576 static int ibmvscsis_check_true(struct se_portal_group *se_tpg)
3577 {
3578 	return 1;
3579 }
3580 
3581 static int ibmvscsis_check_false(struct se_portal_group *se_tpg)
3582 {
3583 	return 0;
3584 }
3585 
3586 static u32 ibmvscsis_tpg_get_inst_index(struct se_portal_group *se_tpg)
3587 {
3588 	return 1;
3589 }
3590 
3591 static int ibmvscsis_check_stop_free(struct se_cmd *se_cmd)
3592 {
3593 	return target_put_sess_cmd(se_cmd);
3594 }
3595 
3596 static void ibmvscsis_release_cmd(struct se_cmd *se_cmd)
3597 {
3598 	struct ibmvscsis_cmd *cmd = container_of(se_cmd, struct ibmvscsis_cmd,
3599 						 se_cmd);
3600 	struct scsi_info *vscsi = cmd->adapter;
3601 
3602 	spin_lock_bh(&vscsi->intr_lock);
3603 	/* Remove from active_q */
3604 	list_move_tail(&cmd->list, &vscsi->waiting_rsp);
3605 	ibmvscsis_send_messages(vscsi);
3606 	spin_unlock_bh(&vscsi->intr_lock);
3607 }
3608 
3609 static u32 ibmvscsis_sess_get_index(struct se_session *se_sess)
3610 {
3611 	return 0;
3612 }
3613 
3614 static int ibmvscsis_write_pending(struct se_cmd *se_cmd)
3615 {
3616 	struct ibmvscsis_cmd *cmd = container_of(se_cmd, struct ibmvscsis_cmd,
3617 						 se_cmd);
3618 	struct scsi_info *vscsi = cmd->adapter;
3619 	struct iu_entry *iue = cmd->iue;
3620 	int rc;
3621 
3622 	/*
3623 	 * If CLIENT_FAILED OR RESPONSE_Q_DOWN, then just return success
3624 	 * since LIO can't do anything about it, and we dont want to
3625 	 * attempt an srp_transfer_data.
3626 	 */
3627 	if ((vscsi->flags & (CLIENT_FAILED | RESPONSE_Q_DOWN))) {
3628 		pr_err("write_pending failed since: %d\n", vscsi->flags);
3629 		return 0;
3630 	}
3631 
3632 	rc = srp_transfer_data(cmd, &vio_iu(iue)->srp.cmd, ibmvscsis_rdma,
3633 			       1, 1);
3634 	if (rc) {
3635 		pr_err("srp_transfer_data() failed: %d\n", rc);
3636 		return -EIO;
3637 	}
3638 	/*
3639 	 * We now tell TCM to add this WRITE CDB directly into the TCM storage
3640 	 * object execution queue.
3641 	 */
3642 	target_execute_cmd(se_cmd);
3643 	return 0;
3644 }
3645 
3646 static int ibmvscsis_write_pending_status(struct se_cmd *se_cmd)
3647 {
3648 	return 0;
3649 }
3650 
3651 static void ibmvscsis_set_default_node_attrs(struct se_node_acl *nacl)
3652 {
3653 }
3654 
3655 static int ibmvscsis_get_cmd_state(struct se_cmd *se_cmd)
3656 {
3657 	return 0;
3658 }
3659 
3660 static int ibmvscsis_queue_data_in(struct se_cmd *se_cmd)
3661 {
3662 	struct ibmvscsis_cmd *cmd = container_of(se_cmd, struct ibmvscsis_cmd,
3663 						 se_cmd);
3664 	struct iu_entry *iue = cmd->iue;
3665 	struct scsi_info *vscsi = cmd->adapter;
3666 	char *sd;
3667 	uint len = 0;
3668 	int rc;
3669 
3670 	rc = srp_transfer_data(cmd, &vio_iu(iue)->srp.cmd, ibmvscsis_rdma, 1,
3671 			       1);
3672 	if (rc) {
3673 		pr_err("srp_transfer_data failed: %d\n", rc);
3674 		sd = se_cmd->sense_buffer;
3675 		se_cmd->scsi_sense_length = 18;
3676 		memset(se_cmd->sense_buffer, 0, se_cmd->scsi_sense_length);
3677 		/* Logical Unit Communication Time-out asc/ascq = 0x0801 */
3678 		scsi_build_sense_buffer(0, se_cmd->sense_buffer, MEDIUM_ERROR,
3679 					0x08, 0x01);
3680 	}
3681 
3682 	srp_build_response(vscsi, cmd, &len);
3683 	cmd->rsp.format = SRP_FORMAT;
3684 	cmd->rsp.len = len;
3685 
3686 	return 0;
3687 }
3688 
3689 static int ibmvscsis_queue_status(struct se_cmd *se_cmd)
3690 {
3691 	struct ibmvscsis_cmd *cmd = container_of(se_cmd, struct ibmvscsis_cmd,
3692 						 se_cmd);
3693 	struct scsi_info *vscsi = cmd->adapter;
3694 	uint len;
3695 
3696 	pr_debug("queue_status %p\n", se_cmd);
3697 
3698 	srp_build_response(vscsi, cmd, &len);
3699 	cmd->rsp.format = SRP_FORMAT;
3700 	cmd->rsp.len = len;
3701 
3702 	return 0;
3703 }
3704 
3705 static void ibmvscsis_queue_tm_rsp(struct se_cmd *se_cmd)
3706 {
3707 	struct ibmvscsis_cmd *cmd = container_of(se_cmd, struct ibmvscsis_cmd,
3708 						 se_cmd);
3709 	struct scsi_info *vscsi = cmd->adapter;
3710 	struct ibmvscsis_cmd *cmd_itr;
3711 	struct iu_entry *iue = iue = cmd->iue;
3712 	struct srp_tsk_mgmt *srp_tsk = &vio_iu(iue)->srp.tsk_mgmt;
3713 	u64 tag_to_abort = be64_to_cpu(srp_tsk->task_tag);
3714 	uint len;
3715 
3716 	pr_debug("queue_tm_rsp %p, status %d\n",
3717 		 se_cmd, (int)se_cmd->se_tmr_req->response);
3718 
3719 	if (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK &&
3720 	    cmd->se_cmd.se_tmr_req->response == TMR_TASK_DOES_NOT_EXIST) {
3721 		spin_lock_bh(&vscsi->intr_lock);
3722 		list_for_each_entry(cmd_itr, &vscsi->active_q, list) {
3723 			if (tag_to_abort == cmd_itr->se_cmd.tag) {
3724 				cmd_itr->abort_cmd = cmd;
3725 				cmd->flags |= DELAY_SEND;
3726 				break;
3727 			}
3728 		}
3729 		spin_unlock_bh(&vscsi->intr_lock);
3730 	}
3731 
3732 	srp_build_response(vscsi, cmd, &len);
3733 	cmd->rsp.format = SRP_FORMAT;
3734 	cmd->rsp.len = len;
3735 }
3736 
3737 static void ibmvscsis_aborted_task(struct se_cmd *se_cmd)
3738 {
3739 	pr_debug("ibmvscsis_aborted_task %p task_tag: %llu\n",
3740 		 se_cmd, se_cmd->tag);
3741 }
3742 
3743 static struct se_wwn *ibmvscsis_make_tport(struct target_fabric_configfs *tf,
3744 					   struct config_group *group,
3745 					   const char *name)
3746 {
3747 	struct ibmvscsis_tport *tport;
3748 
3749 	tport = ibmvscsis_lookup_port(name);
3750 	if (tport) {
3751 		tport->tport_proto_id = SCSI_PROTOCOL_SRP;
3752 		pr_debug("make_tport(%s), pointer:%p, tport_id:%x\n",
3753 			 name, tport, tport->tport_proto_id);
3754 		return &tport->tport_wwn;
3755 	}
3756 
3757 	return ERR_PTR(-EINVAL);
3758 }
3759 
3760 static void ibmvscsis_drop_tport(struct se_wwn *wwn)
3761 {
3762 	struct ibmvscsis_tport *tport = container_of(wwn,
3763 						     struct ibmvscsis_tport,
3764 						     tport_wwn);
3765 
3766 	pr_debug("drop_tport(%s)\n",
3767 		 config_item_name(&tport->tport_wwn.wwn_group.cg_item));
3768 }
3769 
3770 static struct se_portal_group *ibmvscsis_make_tpg(struct se_wwn *wwn,
3771 						  struct config_group *group,
3772 						  const char *name)
3773 {
3774 	struct ibmvscsis_tport *tport =
3775 		container_of(wwn, struct ibmvscsis_tport, tport_wwn);
3776 	int rc;
3777 
3778 	tport->releasing = false;
3779 
3780 	rc = core_tpg_register(&tport->tport_wwn, &tport->se_tpg,
3781 			       tport->tport_proto_id);
3782 	if (rc)
3783 		return ERR_PTR(rc);
3784 
3785 	return &tport->se_tpg;
3786 }
3787 
3788 static void ibmvscsis_drop_tpg(struct se_portal_group *se_tpg)
3789 {
3790 	struct ibmvscsis_tport *tport = container_of(se_tpg,
3791 						     struct ibmvscsis_tport,
3792 						     se_tpg);
3793 
3794 	tport->releasing = true;
3795 	tport->enabled = false;
3796 
3797 	/*
3798 	 * Release the virtual I_T Nexus for this ibmvscsis TPG
3799 	 */
3800 	ibmvscsis_drop_nexus(tport);
3801 	/*
3802 	 * Deregister the se_tpg from TCM..
3803 	 */
3804 	core_tpg_deregister(se_tpg);
3805 }
3806 
3807 static ssize_t ibmvscsis_wwn_version_show(struct config_item *item,
3808 					  char *page)
3809 {
3810 	return scnprintf(page, PAGE_SIZE, "%s\n", IBMVSCSIS_VERSION);
3811 }
3812 CONFIGFS_ATTR_RO(ibmvscsis_wwn_, version);
3813 
3814 static struct configfs_attribute *ibmvscsis_wwn_attrs[] = {
3815 	&ibmvscsis_wwn_attr_version,
3816 	NULL,
3817 };
3818 
3819 static ssize_t ibmvscsis_tpg_enable_show(struct config_item *item,
3820 					 char *page)
3821 {
3822 	struct se_portal_group *se_tpg = to_tpg(item);
3823 	struct ibmvscsis_tport *tport = container_of(se_tpg,
3824 						     struct ibmvscsis_tport,
3825 						     se_tpg);
3826 
3827 	return snprintf(page, PAGE_SIZE, "%d\n", (tport->enabled) ? 1 : 0);
3828 }
3829 
3830 static ssize_t ibmvscsis_tpg_enable_store(struct config_item *item,
3831 					  const char *page, size_t count)
3832 {
3833 	struct se_portal_group *se_tpg = to_tpg(item);
3834 	struct ibmvscsis_tport *tport = container_of(se_tpg,
3835 						     struct ibmvscsis_tport,
3836 						     se_tpg);
3837 	struct scsi_info *vscsi = container_of(tport, struct scsi_info, tport);
3838 	unsigned long tmp;
3839 	int rc;
3840 	long lrc;
3841 
3842 	rc = kstrtoul(page, 0, &tmp);
3843 	if (rc < 0) {
3844 		pr_err("Unable to extract srpt_tpg_store_enable\n");
3845 		return -EINVAL;
3846 	}
3847 
3848 	if ((tmp != 0) && (tmp != 1)) {
3849 		pr_err("Illegal value for srpt_tpg_store_enable\n");
3850 		return -EINVAL;
3851 	}
3852 
3853 	if (tmp) {
3854 		spin_lock_bh(&vscsi->intr_lock);
3855 		tport->enabled = true;
3856 		lrc = ibmvscsis_enable_change_state(vscsi);
3857 		if (lrc)
3858 			pr_err("enable_change_state failed, rc %ld state %d\n",
3859 			       lrc, vscsi->state);
3860 		spin_unlock_bh(&vscsi->intr_lock);
3861 	} else {
3862 		spin_lock_bh(&vscsi->intr_lock);
3863 		tport->enabled = false;
3864 		/* This simulates the server going down */
3865 		ibmvscsis_post_disconnect(vscsi, ERR_DISCONNECT, 0);
3866 		spin_unlock_bh(&vscsi->intr_lock);
3867 	}
3868 
3869 	pr_debug("tpg_enable_store, tmp %ld, state %d\n", tmp, vscsi->state);
3870 
3871 	return count;
3872 }
3873 CONFIGFS_ATTR(ibmvscsis_tpg_, enable);
3874 
3875 static struct configfs_attribute *ibmvscsis_tpg_attrs[] = {
3876 	&ibmvscsis_tpg_attr_enable,
3877 	NULL,
3878 };
3879 
3880 static const struct target_core_fabric_ops ibmvscsis_ops = {
3881 	.module				= THIS_MODULE,
3882 	.name				= "ibmvscsis",
3883 	.max_data_sg_nents		= MAX_TXU / PAGE_SIZE,
3884 	.get_fabric_name		= ibmvscsis_get_fabric_name,
3885 	.tpg_get_wwn			= ibmvscsis_get_fabric_wwn,
3886 	.tpg_get_tag			= ibmvscsis_get_tag,
3887 	.tpg_get_default_depth		= ibmvscsis_get_default_depth,
3888 	.tpg_check_demo_mode		= ibmvscsis_check_true,
3889 	.tpg_check_demo_mode_cache	= ibmvscsis_check_true,
3890 	.tpg_check_demo_mode_write_protect = ibmvscsis_check_false,
3891 	.tpg_check_prod_mode_write_protect = ibmvscsis_check_false,
3892 	.tpg_get_inst_index		= ibmvscsis_tpg_get_inst_index,
3893 	.check_stop_free		= ibmvscsis_check_stop_free,
3894 	.release_cmd			= ibmvscsis_release_cmd,
3895 	.sess_get_index			= ibmvscsis_sess_get_index,
3896 	.write_pending			= ibmvscsis_write_pending,
3897 	.write_pending_status		= ibmvscsis_write_pending_status,
3898 	.set_default_node_attributes	= ibmvscsis_set_default_node_attrs,
3899 	.get_cmd_state			= ibmvscsis_get_cmd_state,
3900 	.queue_data_in			= ibmvscsis_queue_data_in,
3901 	.queue_status			= ibmvscsis_queue_status,
3902 	.queue_tm_rsp			= ibmvscsis_queue_tm_rsp,
3903 	.aborted_task			= ibmvscsis_aborted_task,
3904 	/*
3905 	 * Setup function pointers for logic in target_core_fabric_configfs.c
3906 	 */
3907 	.fabric_make_wwn		= ibmvscsis_make_tport,
3908 	.fabric_drop_wwn		= ibmvscsis_drop_tport,
3909 	.fabric_make_tpg		= ibmvscsis_make_tpg,
3910 	.fabric_drop_tpg		= ibmvscsis_drop_tpg,
3911 
3912 	.tfc_wwn_attrs			= ibmvscsis_wwn_attrs,
3913 	.tfc_tpg_base_attrs		= ibmvscsis_tpg_attrs,
3914 };
3915 
3916 static void ibmvscsis_dev_release(struct device *dev) {};
3917 
3918 static struct class_attribute ibmvscsis_class_attrs[] = {
3919 	__ATTR_NULL,
3920 };
3921 
3922 static struct device_attribute dev_attr_system_id =
3923 	__ATTR(system_id, S_IRUGO, system_id_show, NULL);
3924 
3925 static struct device_attribute dev_attr_partition_number =
3926 	__ATTR(partition_number, S_IRUGO, partition_number_show, NULL);
3927 
3928 static struct device_attribute dev_attr_unit_address =
3929 	__ATTR(unit_address, S_IRUGO, unit_address_show, NULL);
3930 
3931 static struct attribute *ibmvscsis_dev_attrs[] = {
3932 	&dev_attr_system_id.attr,
3933 	&dev_attr_partition_number.attr,
3934 	&dev_attr_unit_address.attr,
3935 };
3936 ATTRIBUTE_GROUPS(ibmvscsis_dev);
3937 
3938 static struct class ibmvscsis_class = {
3939 	.name		= "ibmvscsis",
3940 	.dev_release	= ibmvscsis_dev_release,
3941 	.class_attrs	= ibmvscsis_class_attrs,
3942 	.dev_groups	= ibmvscsis_dev_groups,
3943 };
3944 
3945 static struct vio_device_id ibmvscsis_device_table[] = {
3946 	{ "v-scsi-host", "IBM,v-scsi-host" },
3947 	{ "", "" }
3948 };
3949 MODULE_DEVICE_TABLE(vio, ibmvscsis_device_table);
3950 
3951 static struct vio_driver ibmvscsis_driver = {
3952 	.name = "ibmvscsis",
3953 	.id_table = ibmvscsis_device_table,
3954 	.probe = ibmvscsis_probe,
3955 	.remove = ibmvscsis_remove,
3956 };
3957 
3958 /*
3959  * ibmvscsis_init() - Kernel Module initialization
3960  *
3961  * Note: vio_register_driver() registers callback functions, and at least one
3962  * of those callback functions calls TCM - Linux IO Target Subsystem, thus
3963  * the SCSI Target template must be registered before vio_register_driver()
3964  * is called.
3965  */
3966 static int __init ibmvscsis_init(void)
3967 {
3968 	int rc = 0;
3969 
3970 	rc = ibmvscsis_get_system_info();
3971 	if (rc) {
3972 		pr_err("rc %d from get_system_info\n", rc);
3973 		goto out;
3974 	}
3975 
3976 	rc = class_register(&ibmvscsis_class);
3977 	if (rc) {
3978 		pr_err("failed class register\n");
3979 		goto out;
3980 	}
3981 
3982 	rc = target_register_template(&ibmvscsis_ops);
3983 	if (rc) {
3984 		pr_err("rc %d from target_register_template\n", rc);
3985 		goto unregister_class;
3986 	}
3987 
3988 	rc = vio_register_driver(&ibmvscsis_driver);
3989 	if (rc) {
3990 		pr_err("rc %d from vio_register_driver\n", rc);
3991 		goto unregister_target;
3992 	}
3993 
3994 	return 0;
3995 
3996 unregister_target:
3997 	target_unregister_template(&ibmvscsis_ops);
3998 unregister_class:
3999 	class_unregister(&ibmvscsis_class);
4000 out:
4001 	return rc;
4002 }
4003 
4004 static void __exit ibmvscsis_exit(void)
4005 {
4006 	pr_info("Unregister IBM virtual SCSI host driver\n");
4007 	vio_unregister_driver(&ibmvscsis_driver);
4008 	target_unregister_template(&ibmvscsis_ops);
4009 	class_unregister(&ibmvscsis_class);
4010 }
4011 
4012 MODULE_DESCRIPTION("IBMVSCSIS fabric driver");
4013 MODULE_AUTHOR("Bryant G. Ly and Michael Cyr");
4014 MODULE_LICENSE("GPL");
4015 MODULE_VERSION(IBMVSCSIS_VERSION);
4016 module_init(ibmvscsis_init);
4017 module_exit(ibmvscsis_exit);
4018