1 /*
2  *  qla_target.c SCSI LLD infrastructure for QLogic 22xx/23xx/24xx/25xx
3  *
4  *  based on qla2x00t.c code:
5  *
6  *  Copyright (C) 2004 - 2010 Vladislav Bolkhovitin <vst@vlnb.net>
7  *  Copyright (C) 2004 - 2005 Leonid Stoljar
8  *  Copyright (C) 2006 Nathaniel Clark <nate@misrule.us>
9  *  Copyright (C) 2006 - 2010 ID7 Ltd.
10  *
11  *  Forward port and refactoring to modern qla2xxx and target/configfs
12  *
13  *  Copyright (C) 2010-2013 Nicholas A. Bellinger <nab@kernel.org>
14  *
15  *  This program is free software; you can redistribute it and/or
16  *  modify it under the terms of the GNU General Public License
17  *  as published by the Free Software Foundation, version 2
18  *  of the License.
19  *
20  *  This program is distributed in the hope that it will be useful,
21  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23  *  GNU General Public License for more details.
24  */
25 
26 #include <linux/module.h>
27 #include <linux/init.h>
28 #include <linux/types.h>
29 #include <linux/blkdev.h>
30 #include <linux/interrupt.h>
31 #include <linux/pci.h>
32 #include <linux/delay.h>
33 #include <linux/list.h>
34 #include <linux/workqueue.h>
35 #include <asm/unaligned.h>
36 #include <scsi/scsi.h>
37 #include <scsi/scsi_host.h>
38 #include <scsi/scsi_tcq.h>
39 #include <target/target_core_base.h>
40 #include <target/target_core_fabric.h>
41 
42 #include "qla_def.h"
43 #include "qla_target.h"
44 
45 static int ql2xtgt_tape_enable;
46 module_param(ql2xtgt_tape_enable, int, S_IRUGO|S_IWUSR);
47 MODULE_PARM_DESC(ql2xtgt_tape_enable,
48 		"Enables Sequence level error recovery (aka FC Tape). Default is 0 - no SLER. 1 - Enable SLER.");
49 
50 static char *qlini_mode = QLA2XXX_INI_MODE_STR_ENABLED;
51 module_param(qlini_mode, charp, S_IRUGO);
52 MODULE_PARM_DESC(qlini_mode,
53 	"Determines when initiator mode will be enabled. Possible values: "
54 	"\"exclusive\" - initiator mode will be enabled on load, "
55 	"disabled on enabling target mode and then on disabling target mode "
56 	"enabled back; "
57 	"\"disabled\" - initiator mode will never be enabled; "
58 	"\"dual\" - Initiator Modes will be enabled. Target Mode can be activated "
59 	"when ready "
60 	"\"enabled\" (default) - initiator mode will always stay enabled.");
61 
62 static int ql_dm_tgt_ex_pct = 0;
63 module_param(ql_dm_tgt_ex_pct, int, S_IRUGO|S_IWUSR);
64 MODULE_PARM_DESC(ql_dm_tgt_ex_pct,
65 	"For Dual Mode (qlini_mode=dual), this parameter determines "
66 	"the percentage of exchanges/cmds FW will allocate resources "
67 	"for Target mode.");
68 
69 int ql2xuctrlirq = 1;
70 module_param(ql2xuctrlirq, int, 0644);
71 MODULE_PARM_DESC(ql2xuctrlirq,
72     "User to control IRQ placement via smp_affinity."
73     "Valid with qlini_mode=disabled."
74     "1(default): enable");
75 
76 int ql2x_ini_mode = QLA2XXX_INI_MODE_EXCLUSIVE;
77 
78 static int qla_sam_status = SAM_STAT_BUSY;
79 static int tc_sam_status = SAM_STAT_TASK_SET_FULL; /* target core */
80 
81 /*
82  * From scsi/fc/fc_fcp.h
83  */
84 enum fcp_resp_rsp_codes {
85 	FCP_TMF_CMPL = 0,
86 	FCP_DATA_LEN_INVALID = 1,
87 	FCP_CMND_FIELDS_INVALID = 2,
88 	FCP_DATA_PARAM_MISMATCH = 3,
89 	FCP_TMF_REJECTED = 4,
90 	FCP_TMF_FAILED = 5,
91 	FCP_TMF_INVALID_LUN = 9,
92 };
93 
94 /*
95  * fc_pri_ta from scsi/fc/fc_fcp.h
96  */
97 #define FCP_PTA_SIMPLE      0   /* simple task attribute */
98 #define FCP_PTA_HEADQ       1   /* head of queue task attribute */
99 #define FCP_PTA_ORDERED     2   /* ordered task attribute */
100 #define FCP_PTA_ACA         4   /* auto. contingent allegiance */
101 #define FCP_PTA_MASK        7   /* mask for task attribute field */
102 #define FCP_PRI_SHIFT       3   /* priority field starts in bit 3 */
103 #define FCP_PRI_RESVD_MASK  0x80        /* reserved bits in priority field */
104 
105 /*
106  * This driver calls qla2x00_alloc_iocbs() and qla2x00_issue_marker(), which
107  * must be called under HW lock and could unlock/lock it inside.
108  * It isn't an issue, since in the current implementation on the time when
109  * those functions are called:
110  *
111  *   - Either context is IRQ and only IRQ handler can modify HW data,
112  *     including rings related fields,
113  *
114  *   - Or access to target mode variables from struct qla_tgt doesn't
115  *     cross those functions boundaries, except tgt_stop, which
116  *     additionally protected by irq_cmd_count.
117  */
118 /* Predefs for callbacks handed to qla2xxx LLD */
119 static void qlt_24xx_atio_pkt(struct scsi_qla_host *ha,
120 	struct atio_from_isp *pkt, uint8_t);
121 static void qlt_response_pkt(struct scsi_qla_host *ha, struct rsp_que *rsp,
122 	response_t *pkt);
123 static int qlt_issue_task_mgmt(struct fc_port *sess, u64 lun,
124 	int fn, void *iocb, int flags);
125 static void qlt_send_term_exchange(struct qla_qpair *, struct qla_tgt_cmd
126 	*cmd, struct atio_from_isp *atio, int ha_locked, int ul_abort);
127 static void qlt_alloc_qfull_cmd(struct scsi_qla_host *vha,
128 	struct atio_from_isp *atio, uint16_t status, int qfull);
129 static void qlt_disable_vha(struct scsi_qla_host *vha);
130 static void qlt_clear_tgt_db(struct qla_tgt *tgt);
131 static void qlt_send_notify_ack(struct qla_qpair *qpair,
132 	struct imm_ntfy_from_isp *ntfy,
133 	uint32_t add_flags, uint16_t resp_code, int resp_code_valid,
134 	uint16_t srr_flags, uint16_t srr_reject_code, uint8_t srr_explan);
135 static void qlt_send_term_imm_notif(struct scsi_qla_host *vha,
136 	struct imm_ntfy_from_isp *imm, int ha_locked);
137 static struct fc_port *qlt_create_sess(struct scsi_qla_host *vha,
138 	fc_port_t *fcport, bool local);
139 void qlt_unreg_sess(struct fc_port *sess);
140 static void qlt_24xx_handle_abts(struct scsi_qla_host *,
141 	struct abts_recv_from_24xx *);
142 static void qlt_send_busy(struct qla_qpair *, struct atio_from_isp *,
143     uint16_t);
144 
145 /*
146  * Global Variables
147  */
148 static struct kmem_cache *qla_tgt_mgmt_cmd_cachep;
149 struct kmem_cache *qla_tgt_plogi_cachep;
150 static mempool_t *qla_tgt_mgmt_cmd_mempool;
151 static struct workqueue_struct *qla_tgt_wq;
152 static DEFINE_MUTEX(qla_tgt_mutex);
153 static LIST_HEAD(qla_tgt_glist);
154 
155 static const char *prot_op_str(u32 prot_op)
156 {
157 	switch (prot_op) {
158 	case TARGET_PROT_NORMAL:	return "NORMAL";
159 	case TARGET_PROT_DIN_INSERT:	return "DIN_INSERT";
160 	case TARGET_PROT_DOUT_INSERT:	return "DOUT_INSERT";
161 	case TARGET_PROT_DIN_STRIP:	return "DIN_STRIP";
162 	case TARGET_PROT_DOUT_STRIP:	return "DOUT_STRIP";
163 	case TARGET_PROT_DIN_PASS:	return "DIN_PASS";
164 	case TARGET_PROT_DOUT_PASS:	return "DOUT_PASS";
165 	default:			return "UNKNOWN";
166 	}
167 }
168 
169 /* This API intentionally takes dest as a parameter, rather than returning
170  * int value to avoid caller forgetting to issue wmb() after the store */
171 void qlt_do_generation_tick(struct scsi_qla_host *vha, int *dest)
172 {
173 	scsi_qla_host_t *base_vha = pci_get_drvdata(vha->hw->pdev);
174 	*dest = atomic_inc_return(&base_vha->generation_tick);
175 	/* memory barrier */
176 	wmb();
177 }
178 
179 /* Might release hw lock, then reaquire!! */
180 static inline int qlt_issue_marker(struct scsi_qla_host *vha, int vha_locked)
181 {
182 	/* Send marker if required */
183 	if (unlikely(vha->marker_needed != 0)) {
184 		int rc = qla2x00_issue_marker(vha, vha_locked);
185 		if (rc != QLA_SUCCESS) {
186 			ql_dbg(ql_dbg_tgt, vha, 0xe03d,
187 			    "qla_target(%d): issue_marker() failed\n",
188 			    vha->vp_idx);
189 		}
190 		return rc;
191 	}
192 	return QLA_SUCCESS;
193 }
194 
195 static inline
196 struct scsi_qla_host *qlt_find_host_by_d_id(struct scsi_qla_host *vha,
197 	uint8_t *d_id)
198 {
199 	struct scsi_qla_host *host;
200 	uint32_t key = 0;
201 
202 	if ((vha->d_id.b.area == d_id[1]) && (vha->d_id.b.domain == d_id[0]) &&
203 	    (vha->d_id.b.al_pa == d_id[2]))
204 		return vha;
205 
206 	key  = (uint32_t)d_id[0] << 16;
207 	key |= (uint32_t)d_id[1] <<  8;
208 	key |= (uint32_t)d_id[2];
209 
210 	host = btree_lookup32(&vha->hw->tgt.host_map, key);
211 	if (!host)
212 		ql_dbg(ql_dbg_tgt_mgt + ql_dbg_verbose, vha, 0xf005,
213 		    "Unable to find host %06x\n", key);
214 
215 	return host;
216 }
217 
218 static inline
219 struct scsi_qla_host *qlt_find_host_by_vp_idx(struct scsi_qla_host *vha,
220 	uint16_t vp_idx)
221 {
222 	struct qla_hw_data *ha = vha->hw;
223 
224 	if (vha->vp_idx == vp_idx)
225 		return vha;
226 
227 	BUG_ON(ha->tgt.tgt_vp_map == NULL);
228 	if (likely(test_bit(vp_idx, ha->vp_idx_map)))
229 		return ha->tgt.tgt_vp_map[vp_idx].vha;
230 
231 	return NULL;
232 }
233 
234 static inline void qlt_incr_num_pend_cmds(struct scsi_qla_host *vha)
235 {
236 	unsigned long flags;
237 
238 	spin_lock_irqsave(&vha->hw->tgt.q_full_lock, flags);
239 
240 	vha->hw->tgt.num_pend_cmds++;
241 	if (vha->hw->tgt.num_pend_cmds > vha->qla_stats.stat_max_pend_cmds)
242 		vha->qla_stats.stat_max_pend_cmds =
243 			vha->hw->tgt.num_pend_cmds;
244 	spin_unlock_irqrestore(&vha->hw->tgt.q_full_lock, flags);
245 }
246 static inline void qlt_decr_num_pend_cmds(struct scsi_qla_host *vha)
247 {
248 	unsigned long flags;
249 
250 	spin_lock_irqsave(&vha->hw->tgt.q_full_lock, flags);
251 	vha->hw->tgt.num_pend_cmds--;
252 	spin_unlock_irqrestore(&vha->hw->tgt.q_full_lock, flags);
253 }
254 
255 
256 static void qlt_queue_unknown_atio(scsi_qla_host_t *vha,
257 	struct atio_from_isp *atio, uint8_t ha_locked)
258 {
259 	struct qla_tgt_sess_op *u;
260 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
261 	unsigned long flags;
262 
263 	if (tgt->tgt_stop) {
264 		ql_dbg(ql_dbg_async, vha, 0x502c,
265 		    "qla_target(%d): dropping unknown ATIO_TYPE7, because tgt is being stopped",
266 		    vha->vp_idx);
267 		goto out_term;
268 	}
269 
270 	u = kzalloc(sizeof(*u), GFP_ATOMIC);
271 	if (u == NULL)
272 		goto out_term;
273 
274 	u->vha = vha;
275 	memcpy(&u->atio, atio, sizeof(*atio));
276 	INIT_LIST_HEAD(&u->cmd_list);
277 
278 	spin_lock_irqsave(&vha->cmd_list_lock, flags);
279 	list_add_tail(&u->cmd_list, &vha->unknown_atio_list);
280 	spin_unlock_irqrestore(&vha->cmd_list_lock, flags);
281 
282 	schedule_delayed_work(&vha->unknown_atio_work, 1);
283 
284 out:
285 	return;
286 
287 out_term:
288 	qlt_send_term_exchange(vha->hw->base_qpair, NULL, atio, ha_locked, 0);
289 	goto out;
290 }
291 
292 static void qlt_try_to_dequeue_unknown_atios(struct scsi_qla_host *vha,
293 	uint8_t ha_locked)
294 {
295 	struct qla_tgt_sess_op *u, *t;
296 	scsi_qla_host_t *host;
297 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
298 	unsigned long flags;
299 	uint8_t queued = 0;
300 
301 	list_for_each_entry_safe(u, t, &vha->unknown_atio_list, cmd_list) {
302 		if (u->aborted) {
303 			ql_dbg(ql_dbg_async, vha, 0x502e,
304 			    "Freeing unknown %s %p, because of Abort\n",
305 			    "ATIO_TYPE7", u);
306 			qlt_send_term_exchange(vha->hw->base_qpair, NULL,
307 			    &u->atio, ha_locked, 0);
308 			goto abort;
309 		}
310 
311 		host = qlt_find_host_by_d_id(vha, u->atio.u.isp24.fcp_hdr.d_id);
312 		if (host != NULL) {
313 			ql_dbg(ql_dbg_async + ql_dbg_verbose, vha, 0x502f,
314 			    "Requeuing unknown ATIO_TYPE7 %p\n", u);
315 			qlt_24xx_atio_pkt(host, &u->atio, ha_locked);
316 		} else if (tgt->tgt_stop) {
317 			ql_dbg(ql_dbg_async + ql_dbg_verbose, vha, 0x503a,
318 			    "Freeing unknown %s %p, because tgt is being stopped\n",
319 			    "ATIO_TYPE7", u);
320 			qlt_send_term_exchange(vha->hw->base_qpair, NULL,
321 			    &u->atio, ha_locked, 0);
322 		} else {
323 			ql_dbg(ql_dbg_async + ql_dbg_verbose, vha, 0x503d,
324 			    "Reschedule u %p, vha %p, host %p\n", u, vha, host);
325 			if (!queued) {
326 				queued = 1;
327 				schedule_delayed_work(&vha->unknown_atio_work,
328 				    1);
329 			}
330 			continue;
331 		}
332 
333 abort:
334 		spin_lock_irqsave(&vha->cmd_list_lock, flags);
335 		list_del(&u->cmd_list);
336 		spin_unlock_irqrestore(&vha->cmd_list_lock, flags);
337 		kfree(u);
338 	}
339 }
340 
341 void qlt_unknown_atio_work_fn(struct work_struct *work)
342 {
343 	struct scsi_qla_host *vha = container_of(to_delayed_work(work),
344 	    struct scsi_qla_host, unknown_atio_work);
345 
346 	qlt_try_to_dequeue_unknown_atios(vha, 0);
347 }
348 
349 static bool qlt_24xx_atio_pkt_all_vps(struct scsi_qla_host *vha,
350 	struct atio_from_isp *atio, uint8_t ha_locked)
351 {
352 	ql_dbg(ql_dbg_tgt, vha, 0xe072,
353 		"%s: qla_target(%d): type %x ox_id %04x\n",
354 		__func__, vha->vp_idx, atio->u.raw.entry_type,
355 		be16_to_cpu(atio->u.isp24.fcp_hdr.ox_id));
356 
357 	switch (atio->u.raw.entry_type) {
358 	case ATIO_TYPE7:
359 	{
360 		struct scsi_qla_host *host = qlt_find_host_by_d_id(vha,
361 		    atio->u.isp24.fcp_hdr.d_id);
362 		if (unlikely(NULL == host)) {
363 			ql_dbg(ql_dbg_tgt, vha, 0xe03e,
364 			    "qla_target(%d): Received ATIO_TYPE7 "
365 			    "with unknown d_id %x:%x:%x\n", vha->vp_idx,
366 			    atio->u.isp24.fcp_hdr.d_id[0],
367 			    atio->u.isp24.fcp_hdr.d_id[1],
368 			    atio->u.isp24.fcp_hdr.d_id[2]);
369 
370 
371 			qlt_queue_unknown_atio(vha, atio, ha_locked);
372 			break;
373 		}
374 		if (unlikely(!list_empty(&vha->unknown_atio_list)))
375 			qlt_try_to_dequeue_unknown_atios(vha, ha_locked);
376 
377 		qlt_24xx_atio_pkt(host, atio, ha_locked);
378 		break;
379 	}
380 
381 	case IMMED_NOTIFY_TYPE:
382 	{
383 		struct scsi_qla_host *host = vha;
384 		struct imm_ntfy_from_isp *entry =
385 		    (struct imm_ntfy_from_isp *)atio;
386 
387 		qlt_issue_marker(vha, ha_locked);
388 
389 		if ((entry->u.isp24.vp_index != 0xFF) &&
390 		    (entry->u.isp24.nport_handle != 0xFFFF)) {
391 			host = qlt_find_host_by_vp_idx(vha,
392 			    entry->u.isp24.vp_index);
393 			if (unlikely(!host)) {
394 				ql_dbg(ql_dbg_tgt, vha, 0xe03f,
395 				    "qla_target(%d): Received "
396 				    "ATIO (IMMED_NOTIFY_TYPE) "
397 				    "with unknown vp_index %d\n",
398 				    vha->vp_idx, entry->u.isp24.vp_index);
399 				break;
400 			}
401 		}
402 		qlt_24xx_atio_pkt(host, atio, ha_locked);
403 		break;
404 	}
405 
406 	case VP_RPT_ID_IOCB_TYPE:
407 		qla24xx_report_id_acquisition(vha,
408 			(struct vp_rpt_id_entry_24xx *)atio);
409 		break;
410 
411 	case ABTS_RECV_24XX:
412 	{
413 		struct abts_recv_from_24xx *entry =
414 			(struct abts_recv_from_24xx *)atio;
415 		struct scsi_qla_host *host = qlt_find_host_by_vp_idx(vha,
416 			entry->vp_index);
417 		unsigned long flags;
418 
419 		if (unlikely(!host)) {
420 			ql_dbg(ql_dbg_tgt, vha, 0xe00a,
421 			    "qla_target(%d): Response pkt (ABTS_RECV_24XX) "
422 			    "received, with unknown vp_index %d\n",
423 			    vha->vp_idx, entry->vp_index);
424 			break;
425 		}
426 		if (!ha_locked)
427 			spin_lock_irqsave(&host->hw->hardware_lock, flags);
428 		qlt_24xx_handle_abts(host, (struct abts_recv_from_24xx *)atio);
429 		if (!ha_locked)
430 			spin_unlock_irqrestore(&host->hw->hardware_lock, flags);
431 		break;
432 	}
433 
434 	/* case PUREX_IOCB_TYPE: ql2xmvasynctoatio */
435 
436 	default:
437 		ql_dbg(ql_dbg_tgt, vha, 0xe040,
438 		    "qla_target(%d): Received unknown ATIO atio "
439 		    "type %x\n", vha->vp_idx, atio->u.raw.entry_type);
440 		break;
441 	}
442 
443 	return false;
444 }
445 
446 void qlt_response_pkt_all_vps(struct scsi_qla_host *vha,
447 	struct rsp_que *rsp, response_t *pkt)
448 {
449 	switch (pkt->entry_type) {
450 	case CTIO_CRC2:
451 		ql_dbg(ql_dbg_tgt, vha, 0xe073,
452 			"qla_target(%d):%s: CRC2 Response pkt\n",
453 			vha->vp_idx, __func__);
454 		/* fall through */
455 	case CTIO_TYPE7:
456 	{
457 		struct ctio7_from_24xx *entry = (struct ctio7_from_24xx *)pkt;
458 		struct scsi_qla_host *host = qlt_find_host_by_vp_idx(vha,
459 		    entry->vp_index);
460 		if (unlikely(!host)) {
461 			ql_dbg(ql_dbg_tgt, vha, 0xe041,
462 			    "qla_target(%d): Response pkt (CTIO_TYPE7) "
463 			    "received, with unknown vp_index %d\n",
464 			    vha->vp_idx, entry->vp_index);
465 			break;
466 		}
467 		qlt_response_pkt(host, rsp, pkt);
468 		break;
469 	}
470 
471 	case IMMED_NOTIFY_TYPE:
472 	{
473 		struct scsi_qla_host *host = vha;
474 		struct imm_ntfy_from_isp *entry =
475 		    (struct imm_ntfy_from_isp *)pkt;
476 
477 		host = qlt_find_host_by_vp_idx(vha, entry->u.isp24.vp_index);
478 		if (unlikely(!host)) {
479 			ql_dbg(ql_dbg_tgt, vha, 0xe042,
480 			    "qla_target(%d): Response pkt (IMMED_NOTIFY_TYPE) "
481 			    "received, with unknown vp_index %d\n",
482 			    vha->vp_idx, entry->u.isp24.vp_index);
483 			break;
484 		}
485 		qlt_response_pkt(host, rsp, pkt);
486 		break;
487 	}
488 
489 	case NOTIFY_ACK_TYPE:
490 	{
491 		struct scsi_qla_host *host = vha;
492 		struct nack_to_isp *entry = (struct nack_to_isp *)pkt;
493 
494 		if (0xFF != entry->u.isp24.vp_index) {
495 			host = qlt_find_host_by_vp_idx(vha,
496 			    entry->u.isp24.vp_index);
497 			if (unlikely(!host)) {
498 				ql_dbg(ql_dbg_tgt, vha, 0xe043,
499 				    "qla_target(%d): Response "
500 				    "pkt (NOTIFY_ACK_TYPE) "
501 				    "received, with unknown "
502 				    "vp_index %d\n", vha->vp_idx,
503 				    entry->u.isp24.vp_index);
504 				break;
505 			}
506 		}
507 		qlt_response_pkt(host, rsp, pkt);
508 		break;
509 	}
510 
511 	case ABTS_RECV_24XX:
512 	{
513 		struct abts_recv_from_24xx *entry =
514 		    (struct abts_recv_from_24xx *)pkt;
515 		struct scsi_qla_host *host = qlt_find_host_by_vp_idx(vha,
516 		    entry->vp_index);
517 		if (unlikely(!host)) {
518 			ql_dbg(ql_dbg_tgt, vha, 0xe044,
519 			    "qla_target(%d): Response pkt "
520 			    "(ABTS_RECV_24XX) received, with unknown "
521 			    "vp_index %d\n", vha->vp_idx, entry->vp_index);
522 			break;
523 		}
524 		qlt_response_pkt(host, rsp, pkt);
525 		break;
526 	}
527 
528 	case ABTS_RESP_24XX:
529 	{
530 		struct abts_resp_to_24xx *entry =
531 		    (struct abts_resp_to_24xx *)pkt;
532 		struct scsi_qla_host *host = qlt_find_host_by_vp_idx(vha,
533 		    entry->vp_index);
534 		if (unlikely(!host)) {
535 			ql_dbg(ql_dbg_tgt, vha, 0xe045,
536 			    "qla_target(%d): Response pkt "
537 			    "(ABTS_RECV_24XX) received, with unknown "
538 			    "vp_index %d\n", vha->vp_idx, entry->vp_index);
539 			break;
540 		}
541 		qlt_response_pkt(host, rsp, pkt);
542 		break;
543 	}
544 
545 	default:
546 		qlt_response_pkt(vha, rsp, pkt);
547 		break;
548 	}
549 
550 }
551 
552 /*
553  * All qlt_plogi_ack_t operations are protected by hardware_lock
554  */
555 static int qla24xx_post_nack_work(struct scsi_qla_host *vha, fc_port_t *fcport,
556 	struct imm_ntfy_from_isp *ntfy, int type)
557 {
558 	struct qla_work_evt *e;
559 	e = qla2x00_alloc_work(vha, QLA_EVT_NACK);
560 	if (!e)
561 		return QLA_FUNCTION_FAILED;
562 
563 	e->u.nack.fcport = fcport;
564 	e->u.nack.type = type;
565 	memcpy(e->u.nack.iocb, ntfy, sizeof(struct imm_ntfy_from_isp));
566 	return qla2x00_post_work(vha, e);
567 }
568 
569 static
570 void qla2x00_async_nack_sp_done(void *s, int res)
571 {
572 	struct srb *sp = (struct srb *)s;
573 	struct scsi_qla_host *vha = sp->vha;
574 	unsigned long flags;
575 
576 	ql_dbg(ql_dbg_disc, vha, 0x20f2,
577 	    "Async done-%s res %x %8phC  type %d\n",
578 	    sp->name, res, sp->fcport->port_name, sp->type);
579 
580 	spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
581 	sp->fcport->flags &= ~FCF_ASYNC_SENT;
582 	sp->fcport->chip_reset = vha->hw->base_qpair->chip_reset;
583 
584 	switch (sp->type) {
585 	case SRB_NACK_PLOGI:
586 		sp->fcport->login_gen++;
587 		sp->fcport->fw_login_state = DSC_LS_PLOGI_COMP;
588 		sp->fcport->logout_on_delete = 1;
589 		sp->fcport->plogi_nack_done_deadline = jiffies + HZ;
590 		sp->fcport->send_els_logo = 0;
591 		break;
592 
593 	case SRB_NACK_PRLI:
594 		sp->fcport->fw_login_state = DSC_LS_PRLI_COMP;
595 		sp->fcport->deleted = 0;
596 		sp->fcport->send_els_logo = 0;
597 
598 		if (!sp->fcport->login_succ &&
599 		    !IS_SW_RESV_ADDR(sp->fcport->d_id)) {
600 			sp->fcport->login_succ = 1;
601 
602 			vha->fcport_count++;
603 
604 			if (!IS_IIDMA_CAPABLE(vha->hw) ||
605 			    !vha->hw->flags.gpsc_supported) {
606 				ql_dbg(ql_dbg_disc, vha, 0x20f3,
607 				    "%s %d %8phC post upd_fcport fcp_cnt %d\n",
608 				    __func__, __LINE__,
609 				    sp->fcport->port_name,
610 				    vha->fcport_count);
611 				sp->fcport->disc_state = DSC_UPD_FCPORT;
612 				qla24xx_post_upd_fcport_work(vha, sp->fcport);
613 			} else {
614 				ql_dbg(ql_dbg_disc, vha, 0x20f5,
615 				    "%s %d %8phC post gpsc fcp_cnt %d\n",
616 				    __func__, __LINE__,
617 				    sp->fcport->port_name,
618 				    vha->fcport_count);
619 
620 				qla24xx_post_gpsc_work(vha, sp->fcport);
621 			}
622 		}
623 		break;
624 
625 	case SRB_NACK_LOGO:
626 		sp->fcport->login_gen++;
627 		sp->fcport->fw_login_state = DSC_LS_PORT_UNAVAIL;
628 		qlt_logo_completion_handler(sp->fcport, MBS_COMMAND_COMPLETE);
629 		break;
630 	}
631 	spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
632 
633 	sp->free(sp);
634 }
635 
636 int qla24xx_async_notify_ack(scsi_qla_host_t *vha, fc_port_t *fcport,
637 	struct imm_ntfy_from_isp *ntfy, int type)
638 {
639 	int rval = QLA_FUNCTION_FAILED;
640 	srb_t *sp;
641 	char *c = NULL;
642 
643 	fcport->flags |= FCF_ASYNC_SENT;
644 	switch (type) {
645 	case SRB_NACK_PLOGI:
646 		fcport->fw_login_state = DSC_LS_PLOGI_PEND;
647 		c = "PLOGI";
648 		break;
649 	case SRB_NACK_PRLI:
650 		fcport->fw_login_state = DSC_LS_PRLI_PEND;
651 		fcport->deleted = 0;
652 		c = "PRLI";
653 		break;
654 	case SRB_NACK_LOGO:
655 		fcport->fw_login_state = DSC_LS_LOGO_PEND;
656 		c = "LOGO";
657 		break;
658 	}
659 
660 	sp = qla2x00_get_sp(vha, fcport, GFP_ATOMIC);
661 	if (!sp)
662 		goto done;
663 
664 	sp->type = type;
665 	sp->name = "nack";
666 
667 	qla2x00_init_timer(sp, qla2x00_get_async_timeout(vha)+2);
668 
669 	sp->u.iocb_cmd.u.nack.ntfy = ntfy;
670 	sp->u.iocb_cmd.timeout = qla2x00_async_iocb_timeout;
671 	sp->done = qla2x00_async_nack_sp_done;
672 
673 	rval = qla2x00_start_sp(sp);
674 	if (rval != QLA_SUCCESS)
675 		goto done_free_sp;
676 
677 	ql_dbg(ql_dbg_disc, vha, 0x20f4,
678 	    "Async-%s %8phC hndl %x %s\n",
679 	    sp->name, fcport->port_name, sp->handle, c);
680 
681 	return rval;
682 
683 done_free_sp:
684 	sp->free(sp);
685 done:
686 	fcport->flags &= ~FCF_ASYNC_SENT;
687 	return rval;
688 }
689 
690 void qla24xx_do_nack_work(struct scsi_qla_host *vha, struct qla_work_evt *e)
691 {
692 	fc_port_t *t;
693 	unsigned long flags;
694 
695 	switch (e->u.nack.type) {
696 	case SRB_NACK_PRLI:
697 		mutex_lock(&vha->vha_tgt.tgt_mutex);
698 		t = qlt_create_sess(vha, e->u.nack.fcport, 0);
699 		mutex_unlock(&vha->vha_tgt.tgt_mutex);
700 		if (t) {
701 			ql_log(ql_log_info, vha, 0xd034,
702 			    "%s create sess success %p", __func__, t);
703 			spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
704 			/* create sess has an extra kref */
705 			vha->hw->tgt.tgt_ops->put_sess(e->u.nack.fcport);
706 			spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
707 		}
708 		break;
709 	}
710 	qla24xx_async_notify_ack(vha, e->u.nack.fcport,
711 	    (struct imm_ntfy_from_isp*)e->u.nack.iocb, e->u.nack.type);
712 }
713 
714 void qla24xx_delete_sess_fn(struct work_struct *work)
715 {
716 	fc_port_t *fcport = container_of(work, struct fc_port, del_work);
717 	struct qla_hw_data *ha = fcport->vha->hw;
718 	unsigned long flags;
719 
720 	spin_lock_irqsave(&ha->tgt.sess_lock, flags);
721 
722 	if (fcport->se_sess) {
723 		ha->tgt.tgt_ops->shutdown_sess(fcport);
724 		ha->tgt.tgt_ops->put_sess(fcport);
725 	} else {
726 		qlt_unreg_sess(fcport);
727 	}
728 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
729 }
730 
731 /*
732  * Called from qla2x00_reg_remote_port()
733  */
734 void qlt_fc_port_added(struct scsi_qla_host *vha, fc_port_t *fcport)
735 {
736 	struct qla_hw_data *ha = vha->hw;
737 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
738 	struct fc_port *sess = fcport;
739 	unsigned long flags;
740 
741 	if (!vha->hw->tgt.tgt_ops)
742 		return;
743 
744 	spin_lock_irqsave(&ha->tgt.sess_lock, flags);
745 	if (tgt->tgt_stop) {
746 		spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
747 		return;
748 	}
749 
750 	if (fcport->disc_state == DSC_DELETE_PEND) {
751 		spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
752 		return;
753 	}
754 
755 	if (!sess->se_sess) {
756 		spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
757 
758 		mutex_lock(&vha->vha_tgt.tgt_mutex);
759 		sess = qlt_create_sess(vha, fcport, false);
760 		mutex_unlock(&vha->vha_tgt.tgt_mutex);
761 
762 		spin_lock_irqsave(&ha->tgt.sess_lock, flags);
763 	} else {
764 		if (fcport->fw_login_state == DSC_LS_PRLI_COMP) {
765 			spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
766 			return;
767 		}
768 
769 		if (!kref_get_unless_zero(&sess->sess_kref)) {
770 			ql_dbg(ql_dbg_disc, vha, 0x2107,
771 			    "%s: kref_get fail sess %8phC \n",
772 			    __func__, sess->port_name);
773 			spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
774 			return;
775 		}
776 
777 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf04c,
778 		    "qla_target(%u): %ssession for port %8phC "
779 		    "(loop ID %d) reappeared\n", vha->vp_idx,
780 		    sess->local ? "local " : "", sess->port_name, sess->loop_id);
781 
782 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf007,
783 		    "Reappeared sess %p\n", sess);
784 
785 		ha->tgt.tgt_ops->update_sess(sess, fcport->d_id,
786 		    fcport->loop_id,
787 		    (fcport->flags & FCF_CONF_COMP_SUPPORTED));
788 	}
789 
790 	if (sess && sess->local) {
791 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf04d,
792 		    "qla_target(%u): local session for "
793 		    "port %8phC (loop ID %d) became global\n", vha->vp_idx,
794 		    fcport->port_name, sess->loop_id);
795 		sess->local = 0;
796 	}
797 	ha->tgt.tgt_ops->put_sess(sess);
798 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
799 }
800 
801 /*
802  * This is a zero-base ref-counting solution, since hardware_lock
803  * guarantees that ref_count is not modified concurrently.
804  * Upon successful return content of iocb is undefined
805  */
806 static struct qlt_plogi_ack_t *
807 qlt_plogi_ack_find_add(struct scsi_qla_host *vha, port_id_t *id,
808 		       struct imm_ntfy_from_isp *iocb)
809 {
810 	struct qlt_plogi_ack_t *pla;
811 
812 	list_for_each_entry(pla, &vha->plogi_ack_list, list) {
813 		if (pla->id.b24 == id->b24) {
814 			qlt_send_term_imm_notif(vha, &pla->iocb, 1);
815 			memcpy(&pla->iocb, iocb, sizeof(pla->iocb));
816 			return pla;
817 		}
818 	}
819 
820 	pla = kmem_cache_zalloc(qla_tgt_plogi_cachep, GFP_ATOMIC);
821 	if (!pla) {
822 		ql_dbg(ql_dbg_async, vha, 0x5088,
823 		       "qla_target(%d): Allocation of plogi_ack failed\n",
824 		       vha->vp_idx);
825 		return NULL;
826 	}
827 
828 	memcpy(&pla->iocb, iocb, sizeof(pla->iocb));
829 	pla->id = *id;
830 	list_add_tail(&pla->list, &vha->plogi_ack_list);
831 
832 	return pla;
833 }
834 
835 void qlt_plogi_ack_unref(struct scsi_qla_host *vha,
836     struct qlt_plogi_ack_t *pla)
837 {
838 	struct imm_ntfy_from_isp *iocb = &pla->iocb;
839 	port_id_t port_id;
840 	uint16_t loop_id;
841 	fc_port_t *fcport = pla->fcport;
842 
843 	BUG_ON(!pla->ref_count);
844 	pla->ref_count--;
845 
846 	if (pla->ref_count)
847 		return;
848 
849 	ql_dbg(ql_dbg_disc, vha, 0x5089,
850 	    "Sending PLOGI ACK to wwn %8phC s_id %02x:%02x:%02x loop_id %#04x"
851 	    " exch %#x ox_id %#x\n", iocb->u.isp24.port_name,
852 	    iocb->u.isp24.port_id[2], iocb->u.isp24.port_id[1],
853 	    iocb->u.isp24.port_id[0],
854 	    le16_to_cpu(iocb->u.isp24.nport_handle),
855 	    iocb->u.isp24.exchange_address, iocb->ox_id);
856 
857 	port_id.b.domain = iocb->u.isp24.port_id[2];
858 	port_id.b.area   = iocb->u.isp24.port_id[1];
859 	port_id.b.al_pa  = iocb->u.isp24.port_id[0];
860 	port_id.b.rsvd_1 = 0;
861 
862 	loop_id = le16_to_cpu(iocb->u.isp24.nport_handle);
863 
864 	fcport->loop_id = loop_id;
865 	fcport->d_id = port_id;
866 	if (iocb->u.isp24.status_subcode == ELS_PLOGI)
867 		qla24xx_post_nack_work(vha, fcport, iocb, SRB_NACK_PLOGI);
868 	else
869 		qla24xx_post_nack_work(vha, fcport, iocb, SRB_NACK_PRLI);
870 
871 	list_for_each_entry(fcport, &vha->vp_fcports, list) {
872 		if (fcport->plogi_link[QLT_PLOGI_LINK_SAME_WWN] == pla)
873 			fcport->plogi_link[QLT_PLOGI_LINK_SAME_WWN] = NULL;
874 		if (fcport->plogi_link[QLT_PLOGI_LINK_CONFLICT] == pla)
875 			fcport->plogi_link[QLT_PLOGI_LINK_CONFLICT] = NULL;
876 	}
877 
878 	list_del(&pla->list);
879 	kmem_cache_free(qla_tgt_plogi_cachep, pla);
880 }
881 
882 void
883 qlt_plogi_ack_link(struct scsi_qla_host *vha, struct qlt_plogi_ack_t *pla,
884     struct fc_port *sess, enum qlt_plogi_link_t link)
885 {
886 	struct imm_ntfy_from_isp *iocb = &pla->iocb;
887 	/* Inc ref_count first because link might already be pointing at pla */
888 	pla->ref_count++;
889 
890 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf097,
891 		"Linking sess %p [%d] wwn %8phC with PLOGI ACK to wwn %8phC"
892 		" s_id %02x:%02x:%02x, ref=%d pla %p link %d\n",
893 		sess, link, sess->port_name,
894 		iocb->u.isp24.port_name, iocb->u.isp24.port_id[2],
895 		iocb->u.isp24.port_id[1], iocb->u.isp24.port_id[0],
896 		pla->ref_count, pla, link);
897 
898 	if (link == QLT_PLOGI_LINK_CONFLICT) {
899 		switch (sess->disc_state) {
900 		case DSC_DELETED:
901 		case DSC_DELETE_PEND:
902 			pla->ref_count--;
903 			return;
904 		default:
905 			break;
906 		}
907 	}
908 
909 	if (sess->plogi_link[link])
910 		qlt_plogi_ack_unref(vha, sess->plogi_link[link]);
911 
912 	if (link == QLT_PLOGI_LINK_SAME_WWN)
913 		pla->fcport = sess;
914 
915 	sess->plogi_link[link] = pla;
916 }
917 
918 typedef struct {
919 	/* These fields must be initialized by the caller */
920 	port_id_t id;
921 	/*
922 	 * number of cmds dropped while we were waiting for
923 	 * initiator to ack LOGO initialize to 1 if LOGO is
924 	 * triggered by a command, otherwise, to 0
925 	 */
926 	int cmd_count;
927 
928 	/* These fields are used by callee */
929 	struct list_head list;
930 } qlt_port_logo_t;
931 
932 static void
933 qlt_send_first_logo(struct scsi_qla_host *vha, qlt_port_logo_t *logo)
934 {
935 	qlt_port_logo_t *tmp;
936 	int res;
937 
938 	mutex_lock(&vha->vha_tgt.tgt_mutex);
939 
940 	list_for_each_entry(tmp, &vha->logo_list, list) {
941 		if (tmp->id.b24 == logo->id.b24) {
942 			tmp->cmd_count += logo->cmd_count;
943 			mutex_unlock(&vha->vha_tgt.tgt_mutex);
944 			return;
945 		}
946 	}
947 
948 	list_add_tail(&logo->list, &vha->logo_list);
949 
950 	mutex_unlock(&vha->vha_tgt.tgt_mutex);
951 
952 	res = qla24xx_els_dcmd_iocb(vha, ELS_DCMD_LOGO, logo->id);
953 
954 	mutex_lock(&vha->vha_tgt.tgt_mutex);
955 	list_del(&logo->list);
956 	mutex_unlock(&vha->vha_tgt.tgt_mutex);
957 
958 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf098,
959 	    "Finished LOGO to %02x:%02x:%02x, dropped %d cmds, res = %#x\n",
960 	    logo->id.b.domain, logo->id.b.area, logo->id.b.al_pa,
961 	    logo->cmd_count, res);
962 }
963 
964 static void qlt_free_session_done(struct work_struct *work)
965 {
966 	struct fc_port *sess = container_of(work, struct fc_port,
967 	    free_work);
968 	struct qla_tgt *tgt = sess->tgt;
969 	struct scsi_qla_host *vha = sess->vha;
970 	struct qla_hw_data *ha = vha->hw;
971 	unsigned long flags;
972 	bool logout_started = false;
973 	scsi_qla_host_t *base_vha;
974 	struct qlt_plogi_ack_t *own =
975 		sess->plogi_link[QLT_PLOGI_LINK_SAME_WWN];
976 
977 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf084,
978 		"%s: se_sess %p / sess %p from port %8phC loop_id %#04x"
979 		" s_id %02x:%02x:%02x logout %d keep %d els_logo %d\n",
980 		__func__, sess->se_sess, sess, sess->port_name, sess->loop_id,
981 		sess->d_id.b.domain, sess->d_id.b.area, sess->d_id.b.al_pa,
982 		sess->logout_on_delete, sess->keep_nport_handle,
983 		sess->send_els_logo);
984 
985 	if (!IS_SW_RESV_ADDR(sess->d_id)) {
986 		if (sess->send_els_logo) {
987 			qlt_port_logo_t logo;
988 
989 			logo.id = sess->d_id;
990 			logo.cmd_count = 0;
991 			sess->send_els_logo = 0;
992 			qlt_send_first_logo(vha, &logo);
993 		}
994 
995 		if (sess->logout_on_delete && sess->loop_id != FC_NO_LOOP_ID) {
996 			int rc;
997 
998 			if (!own ||
999 			    (own &&
1000 			     (own->iocb.u.isp24.status_subcode == ELS_PLOGI))) {
1001 				rc = qla2x00_post_async_logout_work(vha, sess,
1002 				    NULL);
1003 				if (rc != QLA_SUCCESS)
1004 					ql_log(ql_log_warn, vha, 0xf085,
1005 					    "Schedule logo failed sess %p rc %d\n",
1006 					    sess, rc);
1007 				else
1008 					logout_started = true;
1009 			} else if (own && (own->iocb.u.isp24.status_subcode ==
1010 				ELS_PRLI) && ha->flags.rida_fmt2) {
1011 				rc = qla2x00_post_async_prlo_work(vha, sess,
1012 				    NULL);
1013 				if (rc != QLA_SUCCESS)
1014 					ql_log(ql_log_warn, vha, 0xf085,
1015 					    "Schedule PRLO failed sess %p rc %d\n",
1016 					    sess, rc);
1017 				else
1018 					logout_started = true;
1019 			}
1020 		}
1021 	}
1022 
1023 	/*
1024 	 * Release the target session for FC Nexus from fabric module code.
1025 	 */
1026 	if (sess->se_sess != NULL)
1027 		ha->tgt.tgt_ops->free_session(sess);
1028 
1029 	if (logout_started) {
1030 		bool traced = false;
1031 
1032 		while (!READ_ONCE(sess->logout_completed)) {
1033 			if (!traced) {
1034 				ql_dbg(ql_dbg_tgt_mgt, vha, 0xf086,
1035 					"%s: waiting for sess %p logout\n",
1036 					__func__, sess);
1037 				traced = true;
1038 			}
1039 			msleep(100);
1040 		}
1041 
1042 		ql_dbg(ql_dbg_disc, vha, 0xf087,
1043 		    "%s: sess %p logout completed\n", __func__, sess);
1044 	}
1045 
1046 	if (sess->logo_ack_needed) {
1047 		sess->logo_ack_needed = 0;
1048 		qla24xx_async_notify_ack(vha, sess,
1049 			(struct imm_ntfy_from_isp *)sess->iocb, SRB_NACK_LOGO);
1050 	}
1051 
1052 	spin_lock_irqsave(&ha->tgt.sess_lock, flags);
1053 	if (sess->se_sess) {
1054 		sess->se_sess = NULL;
1055 		if (tgt && !IS_SW_RESV_ADDR(sess->d_id))
1056 			tgt->sess_count--;
1057 	}
1058 
1059 	sess->disc_state = DSC_DELETED;
1060 	sess->fw_login_state = DSC_LS_PORT_UNAVAIL;
1061 	sess->deleted = QLA_SESS_DELETED;
1062 	sess->login_retry = vha->hw->login_retry_count;
1063 
1064 	if (sess->login_succ && !IS_SW_RESV_ADDR(sess->d_id)) {
1065 		vha->fcport_count--;
1066 		sess->login_succ = 0;
1067 	}
1068 
1069 	qla2x00_clear_loop_id(sess);
1070 
1071 	if (sess->conflict) {
1072 		sess->conflict->login_pause = 0;
1073 		sess->conflict = NULL;
1074 		if (!test_bit(UNLOADING, &vha->dpc_flags))
1075 			set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
1076 	}
1077 
1078 	{
1079 		struct qlt_plogi_ack_t *con =
1080 		    sess->plogi_link[QLT_PLOGI_LINK_CONFLICT];
1081 		struct imm_ntfy_from_isp *iocb;
1082 
1083 		if (con) {
1084 			iocb = &con->iocb;
1085 			ql_dbg(ql_dbg_tgt_mgt, vha, 0xf099,
1086 				 "se_sess %p / sess %p port %8phC is gone,"
1087 				 " %s (ref=%d), releasing PLOGI for %8phC (ref=%d)\n",
1088 				 sess->se_sess, sess, sess->port_name,
1089 				 own ? "releasing own PLOGI" : "no own PLOGI pending",
1090 				 own ? own->ref_count : -1,
1091 				 iocb->u.isp24.port_name, con->ref_count);
1092 			qlt_plogi_ack_unref(vha, con);
1093 			sess->plogi_link[QLT_PLOGI_LINK_CONFLICT] = NULL;
1094 		} else {
1095 			ql_dbg(ql_dbg_tgt_mgt, vha, 0xf09a,
1096 			    "se_sess %p / sess %p port %8phC is gone, %s (ref=%d)\n",
1097 			    sess->se_sess, sess, sess->port_name,
1098 			    own ? "releasing own PLOGI" :
1099 			    "no own PLOGI pending",
1100 			    own ? own->ref_count : -1);
1101 		}
1102 
1103 		if (own) {
1104 			sess->fw_login_state = DSC_LS_PLOGI_PEND;
1105 			qlt_plogi_ack_unref(vha, own);
1106 			sess->plogi_link[QLT_PLOGI_LINK_SAME_WWN] = NULL;
1107 		}
1108 	}
1109 
1110 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
1111 
1112 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf001,
1113 	    "Unregistration of sess %p %8phC finished fcp_cnt %d\n",
1114 		sess, sess->port_name, vha->fcport_count);
1115 
1116 	if (tgt && (tgt->sess_count == 0))
1117 		wake_up_all(&tgt->waitQ);
1118 
1119 	if (vha->fcport_count == 0)
1120 		wake_up_all(&vha->fcport_waitQ);
1121 
1122 	base_vha = pci_get_drvdata(ha->pdev);
1123 
1124 	sess->free_pending = 0;
1125 
1126 	if (test_bit(PFLG_DRIVER_REMOVING, &base_vha->pci_flags))
1127 		return;
1128 
1129 	if ((!tgt || !tgt->tgt_stop) && !LOOP_TRANSITION(vha)) {
1130 		switch (vha->host->active_mode) {
1131 		case MODE_INITIATOR:
1132 		case MODE_DUAL:
1133 			set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
1134 			qla2xxx_wake_dpc(vha);
1135 			break;
1136 		case MODE_TARGET:
1137 		default:
1138 			/* no-op */
1139 			break;
1140 		}
1141 	}
1142 }
1143 
1144 /* ha->tgt.sess_lock supposed to be held on entry */
1145 void qlt_unreg_sess(struct fc_port *sess)
1146 {
1147 	struct scsi_qla_host *vha = sess->vha;
1148 	unsigned long flags;
1149 
1150 	ql_dbg(ql_dbg_disc, sess->vha, 0x210a,
1151 	    "%s sess %p for deletion %8phC\n",
1152 	    __func__, sess, sess->port_name);
1153 
1154 	spin_lock_irqsave(&sess->vha->work_lock, flags);
1155 	if (sess->free_pending) {
1156 		spin_unlock_irqrestore(&sess->vha->work_lock, flags);
1157 		return;
1158 	}
1159 	sess->free_pending = 1;
1160 	spin_unlock_irqrestore(&sess->vha->work_lock, flags);
1161 
1162 	if (sess->se_sess)
1163 		vha->hw->tgt.tgt_ops->clear_nacl_from_fcport_map(sess);
1164 
1165 	qla2x00_mark_device_lost(vha, sess, 1, 1);
1166 
1167 	sess->deleted = QLA_SESS_DELETION_IN_PROGRESS;
1168 	sess->disc_state = DSC_DELETE_PEND;
1169 	sess->last_rscn_gen = sess->rscn_gen;
1170 	sess->last_login_gen = sess->login_gen;
1171 
1172 	if (sess->nvme_flag & NVME_FLAG_REGISTERED)
1173 		schedule_work(&sess->nvme_del_work);
1174 
1175 	INIT_WORK(&sess->free_work, qlt_free_session_done);
1176 	schedule_work(&sess->free_work);
1177 }
1178 EXPORT_SYMBOL(qlt_unreg_sess);
1179 
1180 static int qlt_reset(struct scsi_qla_host *vha, void *iocb, int mcmd)
1181 {
1182 	struct qla_hw_data *ha = vha->hw;
1183 	struct fc_port *sess = NULL;
1184 	uint16_t loop_id;
1185 	int res = 0;
1186 	struct imm_ntfy_from_isp *n = (struct imm_ntfy_from_isp *)iocb;
1187 	unsigned long flags;
1188 
1189 	loop_id = le16_to_cpu(n->u.isp24.nport_handle);
1190 	if (loop_id == 0xFFFF) {
1191 		/* Global event */
1192 		atomic_inc(&vha->vha_tgt.qla_tgt->tgt_global_resets_count);
1193 		spin_lock_irqsave(&ha->tgt.sess_lock, flags);
1194 		qlt_clear_tgt_db(vha->vha_tgt.qla_tgt);
1195 		spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
1196 	} else {
1197 		spin_lock_irqsave(&ha->tgt.sess_lock, flags);
1198 		sess = ha->tgt.tgt_ops->find_sess_by_loop_id(vha, loop_id);
1199 		spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
1200 	}
1201 
1202 	ql_dbg(ql_dbg_tgt, vha, 0xe000,
1203 	    "Using sess for qla_tgt_reset: %p\n", sess);
1204 	if (!sess) {
1205 		res = -ESRCH;
1206 		return res;
1207 	}
1208 
1209 	ql_dbg(ql_dbg_tgt, vha, 0xe047,
1210 	    "scsi(%ld): resetting (session %p from port %8phC mcmd %x, "
1211 	    "loop_id %d)\n", vha->host_no, sess, sess->port_name,
1212 	    mcmd, loop_id);
1213 
1214 	return qlt_issue_task_mgmt(sess, 0, mcmd, iocb, QLA24XX_MGMT_SEND_NACK);
1215 }
1216 
1217 static void qla24xx_chk_fcp_state(struct fc_port *sess)
1218 {
1219 	if (sess->chip_reset != sess->vha->hw->base_qpair->chip_reset) {
1220 		sess->logout_on_delete = 0;
1221 		sess->logo_ack_needed = 0;
1222 		sess->fw_login_state = DSC_LS_PORT_UNAVAIL;
1223 		sess->scan_state = 0;
1224 	}
1225 }
1226 
1227 /* ha->tgt.sess_lock supposed to be held on entry */
1228 void qlt_schedule_sess_for_deletion(struct fc_port *sess)
1229 {
1230 	struct qla_tgt *tgt = sess->tgt;
1231 	unsigned long flags;
1232 
1233 	if (sess->disc_state == DSC_DELETE_PEND)
1234 		return;
1235 
1236 	if (sess->disc_state == DSC_DELETED) {
1237 		if (tgt && tgt->tgt_stop && (tgt->sess_count == 0))
1238 			wake_up_all(&tgt->waitQ);
1239 		if (sess->vha->fcport_count == 0)
1240 			wake_up_all(&sess->vha->fcport_waitQ);
1241 
1242 		if (!sess->plogi_link[QLT_PLOGI_LINK_SAME_WWN] &&
1243 			!sess->plogi_link[QLT_PLOGI_LINK_CONFLICT])
1244 			return;
1245 	}
1246 
1247 	if (sess->deleted == QLA_SESS_DELETED)
1248 		sess->logout_on_delete = 0;
1249 
1250 	spin_lock_irqsave(&sess->vha->work_lock, flags);
1251 	if (sess->deleted == QLA_SESS_DELETION_IN_PROGRESS) {
1252 		spin_unlock_irqrestore(&sess->vha->work_lock, flags);
1253 		return;
1254 	}
1255 	sess->deleted = QLA_SESS_DELETION_IN_PROGRESS;
1256 	spin_unlock_irqrestore(&sess->vha->work_lock, flags);
1257 
1258 	sess->disc_state = DSC_DELETE_PEND;
1259 
1260 	qla24xx_chk_fcp_state(sess);
1261 
1262 	ql_dbg(ql_dbg_tgt, sess->vha, 0xe001,
1263 	    "Scheduling sess %p for deletion\n", sess);
1264 
1265 	/* use cancel to push work element through before re-queue */
1266 	cancel_work_sync(&sess->del_work);
1267 	INIT_WORK(&sess->del_work, qla24xx_delete_sess_fn);
1268 	queue_work(sess->vha->hw->wq, &sess->del_work);
1269 }
1270 
1271 /* ha->tgt.sess_lock supposed to be held on entry */
1272 static void qlt_clear_tgt_db(struct qla_tgt *tgt)
1273 {
1274 	struct fc_port *sess;
1275 	scsi_qla_host_t *vha = tgt->vha;
1276 
1277 	list_for_each_entry(sess, &vha->vp_fcports, list) {
1278 		if (sess->se_sess)
1279 			qlt_schedule_sess_for_deletion(sess);
1280 	}
1281 
1282 	/* At this point tgt could be already dead */
1283 }
1284 
1285 static int qla24xx_get_loop_id(struct scsi_qla_host *vha, const uint8_t *s_id,
1286 	uint16_t *loop_id)
1287 {
1288 	struct qla_hw_data *ha = vha->hw;
1289 	dma_addr_t gid_list_dma;
1290 	struct gid_list_info *gid_list;
1291 	char *id_iter;
1292 	int res, rc, i;
1293 	uint16_t entries;
1294 
1295 	gid_list = dma_alloc_coherent(&ha->pdev->dev, qla2x00_gid_list_size(ha),
1296 	    &gid_list_dma, GFP_KERNEL);
1297 	if (!gid_list) {
1298 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf044,
1299 		    "qla_target(%d): DMA Alloc failed of %u\n",
1300 		    vha->vp_idx, qla2x00_gid_list_size(ha));
1301 		return -ENOMEM;
1302 	}
1303 
1304 	/* Get list of logged in devices */
1305 	rc = qla24xx_gidlist_wait(vha, gid_list, gid_list_dma, &entries);
1306 	if (rc != QLA_SUCCESS) {
1307 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf045,
1308 		    "qla_target(%d): get_id_list() failed: %x\n",
1309 		    vha->vp_idx, rc);
1310 		res = -EBUSY;
1311 		goto out_free_id_list;
1312 	}
1313 
1314 	id_iter = (char *)gid_list;
1315 	res = -ENOENT;
1316 	for (i = 0; i < entries; i++) {
1317 		struct gid_list_info *gid = (struct gid_list_info *)id_iter;
1318 		if ((gid->al_pa == s_id[2]) &&
1319 		    (gid->area == s_id[1]) &&
1320 		    (gid->domain == s_id[0])) {
1321 			*loop_id = le16_to_cpu(gid->loop_id);
1322 			res = 0;
1323 			break;
1324 		}
1325 		id_iter += ha->gid_list_info_size;
1326 	}
1327 
1328 out_free_id_list:
1329 	dma_free_coherent(&ha->pdev->dev, qla2x00_gid_list_size(ha),
1330 	    gid_list, gid_list_dma);
1331 	return res;
1332 }
1333 
1334 /*
1335  * Adds an extra ref to allow to drop hw lock after adding sess to the list.
1336  * Caller must put it.
1337  */
1338 static struct fc_port *qlt_create_sess(
1339 	struct scsi_qla_host *vha,
1340 	fc_port_t *fcport,
1341 	bool local)
1342 {
1343 	struct qla_hw_data *ha = vha->hw;
1344 	struct fc_port *sess = fcport;
1345 	unsigned long flags;
1346 
1347 	if (vha->vha_tgt.qla_tgt->tgt_stop)
1348 		return NULL;
1349 
1350 	if (fcport->se_sess) {
1351 		if (!kref_get_unless_zero(&sess->sess_kref)) {
1352 			ql_dbg(ql_dbg_disc, vha, 0x20f6,
1353 			    "%s: kref_get_unless_zero failed for %8phC\n",
1354 			    __func__, sess->port_name);
1355 			return NULL;
1356 		}
1357 		return fcport;
1358 	}
1359 	sess->tgt = vha->vha_tgt.qla_tgt;
1360 	sess->local = local;
1361 
1362 	/*
1363 	 * Under normal circumstances we want to logout from firmware when
1364 	 * session eventually ends and release corresponding nport handle.
1365 	 * In the exception cases (e.g. when new PLOGI is waiting) corresponding
1366 	 * code will adjust these flags as necessary.
1367 	 */
1368 	sess->logout_on_delete = 1;
1369 	sess->keep_nport_handle = 0;
1370 	sess->logout_completed = 0;
1371 
1372 	if (ha->tgt.tgt_ops->check_initiator_node_acl(vha,
1373 	    &fcport->port_name[0], sess) < 0) {
1374 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf015,
1375 		    "(%d) %8phC check_initiator_node_acl failed\n",
1376 		    vha->vp_idx, fcport->port_name);
1377 		return NULL;
1378 	} else {
1379 		kref_init(&fcport->sess_kref);
1380 		/*
1381 		 * Take an extra reference to ->sess_kref here to handle
1382 		 * fc_port access across ->tgt.sess_lock reaquire.
1383 		 */
1384 		if (!kref_get_unless_zero(&sess->sess_kref)) {
1385 			ql_dbg(ql_dbg_disc, vha, 0x20f7,
1386 			    "%s: kref_get_unless_zero failed for %8phC\n",
1387 			    __func__, sess->port_name);
1388 			return NULL;
1389 		}
1390 
1391 		spin_lock_irqsave(&ha->tgt.sess_lock, flags);
1392 		if (!IS_SW_RESV_ADDR(sess->d_id))
1393 			vha->vha_tgt.qla_tgt->sess_count++;
1394 
1395 		qlt_do_generation_tick(vha, &sess->generation);
1396 		spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
1397 	}
1398 
1399 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf006,
1400 	    "Adding sess %p se_sess %p  to tgt %p sess_count %d\n",
1401 	    sess, sess->se_sess, vha->vha_tgt.qla_tgt,
1402 	    vha->vha_tgt.qla_tgt->sess_count);
1403 
1404 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf04b,
1405 	    "qla_target(%d): %ssession for wwn %8phC (loop_id %d, "
1406 	    "s_id %x:%x:%x, confirmed completion %ssupported) added\n",
1407 	    vha->vp_idx, local ?  "local " : "", fcport->port_name,
1408 	    fcport->loop_id, sess->d_id.b.domain, sess->d_id.b.area,
1409 	    sess->d_id.b.al_pa, sess->conf_compl_supported ?  "" : "not ");
1410 
1411 	return sess;
1412 }
1413 
1414 /*
1415  * max_gen - specifies maximum session generation
1416  * at which this deletion requestion is still valid
1417  */
1418 void
1419 qlt_fc_port_deleted(struct scsi_qla_host *vha, fc_port_t *fcport, int max_gen)
1420 {
1421 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
1422 	struct fc_port *sess = fcport;
1423 	unsigned long flags;
1424 
1425 	if (!vha->hw->tgt.tgt_ops)
1426 		return;
1427 
1428 	if (!tgt)
1429 		return;
1430 
1431 	spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
1432 	if (tgt->tgt_stop) {
1433 		spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
1434 		return;
1435 	}
1436 	if (!sess->se_sess) {
1437 		spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
1438 		return;
1439 	}
1440 
1441 	if (max_gen - sess->generation < 0) {
1442 		spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
1443 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf092,
1444 		    "Ignoring stale deletion request for se_sess %p / sess %p"
1445 		    " for port %8phC, req_gen %d, sess_gen %d\n",
1446 		    sess->se_sess, sess, sess->port_name, max_gen,
1447 		    sess->generation);
1448 		return;
1449 	}
1450 
1451 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf008, "qla_tgt_fc_port_deleted %p", sess);
1452 
1453 	sess->local = 1;
1454 	qlt_schedule_sess_for_deletion(sess);
1455 	spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
1456 }
1457 
1458 static inline int test_tgt_sess_count(struct qla_tgt *tgt)
1459 {
1460 	struct qla_hw_data *ha = tgt->ha;
1461 	unsigned long flags;
1462 	int res;
1463 	/*
1464 	 * We need to protect against race, when tgt is freed before or
1465 	 * inside wake_up()
1466 	 */
1467 	spin_lock_irqsave(&ha->tgt.sess_lock, flags);
1468 	ql_dbg(ql_dbg_tgt, tgt->vha, 0xe002,
1469 	    "tgt %p, sess_count=%d\n",
1470 	    tgt, tgt->sess_count);
1471 	res = (tgt->sess_count == 0);
1472 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
1473 
1474 	return res;
1475 }
1476 
1477 /* Called by tcm_qla2xxx configfs code */
1478 int qlt_stop_phase1(struct qla_tgt *tgt)
1479 {
1480 	struct scsi_qla_host *vha = tgt->vha;
1481 	struct qla_hw_data *ha = tgt->ha;
1482 	unsigned long flags;
1483 
1484 	mutex_lock(&qla_tgt_mutex);
1485 	if (!vha->fc_vport) {
1486 		struct Scsi_Host *sh = vha->host;
1487 		struct fc_host_attrs *fc_host = shost_to_fc_host(sh);
1488 		bool npiv_vports;
1489 
1490 		spin_lock_irqsave(sh->host_lock, flags);
1491 		npiv_vports = (fc_host->npiv_vports_inuse);
1492 		spin_unlock_irqrestore(sh->host_lock, flags);
1493 
1494 		if (npiv_vports) {
1495 			mutex_unlock(&qla_tgt_mutex);
1496 			ql_dbg(ql_dbg_tgt_mgt, vha, 0xf021,
1497 			    "NPIV is in use. Can not stop target\n");
1498 			return -EPERM;
1499 		}
1500 	}
1501 	if (tgt->tgt_stop || tgt->tgt_stopped) {
1502 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf04e,
1503 		    "Already in tgt->tgt_stop or tgt_stopped state\n");
1504 		mutex_unlock(&qla_tgt_mutex);
1505 		return -EPERM;
1506 	}
1507 
1508 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xe003, "Stopping target for host %ld(%p)\n",
1509 	    vha->host_no, vha);
1510 	/*
1511 	 * Mutex needed to sync with qla_tgt_fc_port_[added,deleted].
1512 	 * Lock is needed, because we still can get an incoming packet.
1513 	 */
1514 	mutex_lock(&vha->vha_tgt.tgt_mutex);
1515 	spin_lock_irqsave(&ha->tgt.sess_lock, flags);
1516 	tgt->tgt_stop = 1;
1517 	qlt_clear_tgt_db(tgt);
1518 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
1519 	mutex_unlock(&vha->vha_tgt.tgt_mutex);
1520 	mutex_unlock(&qla_tgt_mutex);
1521 
1522 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf009,
1523 	    "Waiting for sess works (tgt %p)", tgt);
1524 	spin_lock_irqsave(&tgt->sess_work_lock, flags);
1525 	while (!list_empty(&tgt->sess_works_list)) {
1526 		spin_unlock_irqrestore(&tgt->sess_work_lock, flags);
1527 		flush_scheduled_work();
1528 		spin_lock_irqsave(&tgt->sess_work_lock, flags);
1529 	}
1530 	spin_unlock_irqrestore(&tgt->sess_work_lock, flags);
1531 
1532 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf00a,
1533 	    "Waiting for tgt %p: sess_count=%d\n", tgt, tgt->sess_count);
1534 
1535 	wait_event_timeout(tgt->waitQ, test_tgt_sess_count(tgt), 10*HZ);
1536 
1537 	/* Big hammer */
1538 	if (!ha->flags.host_shutting_down &&
1539 	    (qla_tgt_mode_enabled(vha) || qla_dual_mode_enabled(vha)))
1540 		qlt_disable_vha(vha);
1541 
1542 	/* Wait for sessions to clear out (just in case) */
1543 	wait_event_timeout(tgt->waitQ, test_tgt_sess_count(tgt), 10*HZ);
1544 	return 0;
1545 }
1546 EXPORT_SYMBOL(qlt_stop_phase1);
1547 
1548 /* Called by tcm_qla2xxx configfs code */
1549 void qlt_stop_phase2(struct qla_tgt *tgt)
1550 {
1551 	scsi_qla_host_t *vha = tgt->vha;
1552 
1553 	if (tgt->tgt_stopped) {
1554 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf04f,
1555 		    "Already in tgt->tgt_stopped state\n");
1556 		dump_stack();
1557 		return;
1558 	}
1559 	if (!tgt->tgt_stop) {
1560 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf00b,
1561 		    "%s: phase1 stop is not completed\n", __func__);
1562 		dump_stack();
1563 		return;
1564 	}
1565 
1566 	mutex_lock(&vha->vha_tgt.tgt_mutex);
1567 	tgt->tgt_stop = 0;
1568 	tgt->tgt_stopped = 1;
1569 	mutex_unlock(&vha->vha_tgt.tgt_mutex);
1570 
1571 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf00c, "Stop of tgt %p finished\n",
1572 	    tgt);
1573 }
1574 EXPORT_SYMBOL(qlt_stop_phase2);
1575 
1576 /* Called from qlt_remove_target() -> qla2x00_remove_one() */
1577 static void qlt_release(struct qla_tgt *tgt)
1578 {
1579 	scsi_qla_host_t *vha = tgt->vha;
1580 	void *node;
1581 	u64 key = 0;
1582 	u16 i;
1583 	struct qla_qpair_hint *h;
1584 	struct qla_hw_data *ha = vha->hw;
1585 
1586 	if ((vha->vha_tgt.qla_tgt != NULL) && !tgt->tgt_stop &&
1587 	    !tgt->tgt_stopped)
1588 		qlt_stop_phase1(tgt);
1589 
1590 	if ((vha->vha_tgt.qla_tgt != NULL) && !tgt->tgt_stopped)
1591 		qlt_stop_phase2(tgt);
1592 
1593 	for (i = 0; i < vha->hw->max_qpairs + 1; i++) {
1594 		unsigned long flags;
1595 
1596 		h = &tgt->qphints[i];
1597 		if (h->qpair) {
1598 			spin_lock_irqsave(h->qpair->qp_lock_ptr, flags);
1599 			list_del(&h->hint_elem);
1600 			spin_unlock_irqrestore(h->qpair->qp_lock_ptr, flags);
1601 			h->qpair = NULL;
1602 		}
1603 	}
1604 	kfree(tgt->qphints);
1605 	mutex_lock(&qla_tgt_mutex);
1606 	list_del(&vha->vha_tgt.qla_tgt->tgt_list_entry);
1607 	mutex_unlock(&qla_tgt_mutex);
1608 
1609 	btree_for_each_safe64(&tgt->lun_qpair_map, key, node)
1610 		btree_remove64(&tgt->lun_qpair_map, key);
1611 
1612 	btree_destroy64(&tgt->lun_qpair_map);
1613 
1614 	if (vha->vp_idx)
1615 		if (ha->tgt.tgt_ops &&
1616 		    ha->tgt.tgt_ops->remove_target &&
1617 		    vha->vha_tgt.target_lport_ptr)
1618 			ha->tgt.tgt_ops->remove_target(vha);
1619 
1620 	vha->vha_tgt.qla_tgt = NULL;
1621 
1622 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf00d,
1623 	    "Release of tgt %p finished\n", tgt);
1624 
1625 	kfree(tgt);
1626 }
1627 
1628 /* ha->hardware_lock supposed to be held on entry */
1629 static int qlt_sched_sess_work(struct qla_tgt *tgt, int type,
1630 	const void *param, unsigned int param_size)
1631 {
1632 	struct qla_tgt_sess_work_param *prm;
1633 	unsigned long flags;
1634 
1635 	prm = kzalloc(sizeof(*prm), GFP_ATOMIC);
1636 	if (!prm) {
1637 		ql_dbg(ql_dbg_tgt_mgt, tgt->vha, 0xf050,
1638 		    "qla_target(%d): Unable to create session "
1639 		    "work, command will be refused", 0);
1640 		return -ENOMEM;
1641 	}
1642 
1643 	ql_dbg(ql_dbg_tgt_mgt, tgt->vha, 0xf00e,
1644 	    "Scheduling work (type %d, prm %p)"
1645 	    " to find session for param %p (size %d, tgt %p)\n",
1646 	    type, prm, param, param_size, tgt);
1647 
1648 	prm->type = type;
1649 	memcpy(&prm->tm_iocb, param, param_size);
1650 
1651 	spin_lock_irqsave(&tgt->sess_work_lock, flags);
1652 	list_add_tail(&prm->sess_works_list_entry, &tgt->sess_works_list);
1653 	spin_unlock_irqrestore(&tgt->sess_work_lock, flags);
1654 
1655 	schedule_work(&tgt->sess_work);
1656 
1657 	return 0;
1658 }
1659 
1660 /*
1661  * ha->hardware_lock supposed to be held on entry. Might drop it, then reaquire
1662  */
1663 static void qlt_send_notify_ack(struct qla_qpair *qpair,
1664 	struct imm_ntfy_from_isp *ntfy,
1665 	uint32_t add_flags, uint16_t resp_code, int resp_code_valid,
1666 	uint16_t srr_flags, uint16_t srr_reject_code, uint8_t srr_explan)
1667 {
1668 	struct scsi_qla_host *vha = qpair->vha;
1669 	struct qla_hw_data *ha = vha->hw;
1670 	request_t *pkt;
1671 	struct nack_to_isp *nack;
1672 
1673 	if (!ha->flags.fw_started)
1674 		return;
1675 
1676 	ql_dbg(ql_dbg_tgt, vha, 0xe004, "Sending NOTIFY_ACK (ha=%p)\n", ha);
1677 
1678 	pkt = (request_t *)__qla2x00_alloc_iocbs(qpair, NULL);
1679 	if (!pkt) {
1680 		ql_dbg(ql_dbg_tgt, vha, 0xe049,
1681 		    "qla_target(%d): %s failed: unable to allocate "
1682 		    "request packet\n", vha->vp_idx, __func__);
1683 		return;
1684 	}
1685 
1686 	if (vha->vha_tgt.qla_tgt != NULL)
1687 		vha->vha_tgt.qla_tgt->notify_ack_expected++;
1688 
1689 	pkt->entry_type = NOTIFY_ACK_TYPE;
1690 	pkt->entry_count = 1;
1691 
1692 	nack = (struct nack_to_isp *)pkt;
1693 	nack->ox_id = ntfy->ox_id;
1694 
1695 	nack->u.isp24.handle = QLA_TGT_SKIP_HANDLE;
1696 	nack->u.isp24.nport_handle = ntfy->u.isp24.nport_handle;
1697 	if (le16_to_cpu(ntfy->u.isp24.status) == IMM_NTFY_ELS) {
1698 		nack->u.isp24.flags = ntfy->u.isp24.flags &
1699 			cpu_to_le32(NOTIFY24XX_FLAGS_PUREX_IOCB);
1700 	}
1701 	nack->u.isp24.srr_rx_id = ntfy->u.isp24.srr_rx_id;
1702 	nack->u.isp24.status = ntfy->u.isp24.status;
1703 	nack->u.isp24.status_subcode = ntfy->u.isp24.status_subcode;
1704 	nack->u.isp24.fw_handle = ntfy->u.isp24.fw_handle;
1705 	nack->u.isp24.exchange_address = ntfy->u.isp24.exchange_address;
1706 	nack->u.isp24.srr_rel_offs = ntfy->u.isp24.srr_rel_offs;
1707 	nack->u.isp24.srr_ui = ntfy->u.isp24.srr_ui;
1708 	nack->u.isp24.srr_flags = cpu_to_le16(srr_flags);
1709 	nack->u.isp24.srr_reject_code = srr_reject_code;
1710 	nack->u.isp24.srr_reject_code_expl = srr_explan;
1711 	nack->u.isp24.vp_index = ntfy->u.isp24.vp_index;
1712 
1713 	ql_dbg(ql_dbg_tgt, vha, 0xe005,
1714 	    "qla_target(%d): Sending 24xx Notify Ack %d\n",
1715 	    vha->vp_idx, nack->u.isp24.status);
1716 
1717 	/* Memory Barrier */
1718 	wmb();
1719 	qla2x00_start_iocbs(vha, qpair->req);
1720 }
1721 
1722 /*
1723  * ha->hardware_lock supposed to be held on entry. Might drop it, then reaquire
1724  */
1725 static void qlt_24xx_send_abts_resp(struct qla_qpair *qpair,
1726 	struct abts_recv_from_24xx *abts, uint32_t status,
1727 	bool ids_reversed)
1728 {
1729 	struct scsi_qla_host *vha = qpair->vha;
1730 	struct qla_hw_data *ha = vha->hw;
1731 	struct abts_resp_to_24xx *resp;
1732 	uint32_t f_ctl;
1733 	uint8_t *p;
1734 
1735 	ql_dbg(ql_dbg_tgt, vha, 0xe006,
1736 	    "Sending task mgmt ABTS response (ha=%p, atio=%p, status=%x\n",
1737 	    ha, abts, status);
1738 
1739 	resp = (struct abts_resp_to_24xx *)qla2x00_alloc_iocbs_ready(qpair,
1740 	    NULL);
1741 	if (!resp) {
1742 		ql_dbg(ql_dbg_tgt, vha, 0xe04a,
1743 		    "qla_target(%d): %s failed: unable to allocate "
1744 		    "request packet", vha->vp_idx, __func__);
1745 		return;
1746 	}
1747 
1748 	resp->entry_type = ABTS_RESP_24XX;
1749 	resp->entry_count = 1;
1750 	resp->nport_handle = abts->nport_handle;
1751 	resp->vp_index = vha->vp_idx;
1752 	resp->sof_type = abts->sof_type;
1753 	resp->exchange_address = abts->exchange_address;
1754 	resp->fcp_hdr_le = abts->fcp_hdr_le;
1755 	f_ctl = cpu_to_le32(F_CTL_EXCH_CONTEXT_RESP |
1756 	    F_CTL_LAST_SEQ | F_CTL_END_SEQ |
1757 	    F_CTL_SEQ_INITIATIVE);
1758 	p = (uint8_t *)&f_ctl;
1759 	resp->fcp_hdr_le.f_ctl[0] = *p++;
1760 	resp->fcp_hdr_le.f_ctl[1] = *p++;
1761 	resp->fcp_hdr_le.f_ctl[2] = *p;
1762 	if (ids_reversed) {
1763 		resp->fcp_hdr_le.d_id[0] = abts->fcp_hdr_le.d_id[0];
1764 		resp->fcp_hdr_le.d_id[1] = abts->fcp_hdr_le.d_id[1];
1765 		resp->fcp_hdr_le.d_id[2] = abts->fcp_hdr_le.d_id[2];
1766 		resp->fcp_hdr_le.s_id[0] = abts->fcp_hdr_le.s_id[0];
1767 		resp->fcp_hdr_le.s_id[1] = abts->fcp_hdr_le.s_id[1];
1768 		resp->fcp_hdr_le.s_id[2] = abts->fcp_hdr_le.s_id[2];
1769 	} else {
1770 		resp->fcp_hdr_le.d_id[0] = abts->fcp_hdr_le.s_id[0];
1771 		resp->fcp_hdr_le.d_id[1] = abts->fcp_hdr_le.s_id[1];
1772 		resp->fcp_hdr_le.d_id[2] = abts->fcp_hdr_le.s_id[2];
1773 		resp->fcp_hdr_le.s_id[0] = abts->fcp_hdr_le.d_id[0];
1774 		resp->fcp_hdr_le.s_id[1] = abts->fcp_hdr_le.d_id[1];
1775 		resp->fcp_hdr_le.s_id[2] = abts->fcp_hdr_le.d_id[2];
1776 	}
1777 	resp->exchange_addr_to_abort = abts->exchange_addr_to_abort;
1778 	if (status == FCP_TMF_CMPL) {
1779 		resp->fcp_hdr_le.r_ctl = R_CTL_BASIC_LINK_SERV | R_CTL_B_ACC;
1780 		resp->payload.ba_acct.seq_id_valid = SEQ_ID_INVALID;
1781 		resp->payload.ba_acct.low_seq_cnt = 0x0000;
1782 		resp->payload.ba_acct.high_seq_cnt = 0xFFFF;
1783 		resp->payload.ba_acct.ox_id = abts->fcp_hdr_le.ox_id;
1784 		resp->payload.ba_acct.rx_id = abts->fcp_hdr_le.rx_id;
1785 	} else {
1786 		resp->fcp_hdr_le.r_ctl = R_CTL_BASIC_LINK_SERV | R_CTL_B_RJT;
1787 		resp->payload.ba_rjt.reason_code =
1788 			BA_RJT_REASON_CODE_UNABLE_TO_PERFORM;
1789 		/* Other bytes are zero */
1790 	}
1791 
1792 	vha->vha_tgt.qla_tgt->abts_resp_expected++;
1793 
1794 	/* Memory Barrier */
1795 	wmb();
1796 	if (qpair->reqq_start_iocbs)
1797 		qpair->reqq_start_iocbs(qpair);
1798 	else
1799 		qla2x00_start_iocbs(vha, qpair->req);
1800 }
1801 
1802 /*
1803  * ha->hardware_lock supposed to be held on entry. Might drop it, then reaquire
1804  */
1805 static void qlt_24xx_retry_term_exchange(struct scsi_qla_host *vha,
1806 	struct abts_resp_from_24xx_fw *entry)
1807 {
1808 	struct ctio7_to_24xx *ctio;
1809 
1810 	ql_dbg(ql_dbg_tgt, vha, 0xe007,
1811 	    "Sending retry TERM EXCH CTIO7 (ha=%p)\n", vha->hw);
1812 
1813 	ctio = (struct ctio7_to_24xx *)qla2x00_alloc_iocbs_ready(
1814 	    vha->hw->base_qpair, NULL);
1815 	if (ctio == NULL) {
1816 		ql_dbg(ql_dbg_tgt, vha, 0xe04b,
1817 		    "qla_target(%d): %s failed: unable to allocate "
1818 		    "request packet\n", vha->vp_idx, __func__);
1819 		return;
1820 	}
1821 
1822 	/*
1823 	 * We've got on entrance firmware's response on by us generated
1824 	 * ABTS response. So, in it ID fields are reversed.
1825 	 */
1826 
1827 	ctio->entry_type = CTIO_TYPE7;
1828 	ctio->entry_count = 1;
1829 	ctio->nport_handle = entry->nport_handle;
1830 	ctio->handle = QLA_TGT_SKIP_HANDLE |	CTIO_COMPLETION_HANDLE_MARK;
1831 	ctio->timeout = cpu_to_le16(QLA_TGT_TIMEOUT);
1832 	ctio->vp_index = vha->vp_idx;
1833 	ctio->initiator_id[0] = entry->fcp_hdr_le.d_id[0];
1834 	ctio->initiator_id[1] = entry->fcp_hdr_le.d_id[1];
1835 	ctio->initiator_id[2] = entry->fcp_hdr_le.d_id[2];
1836 	ctio->exchange_addr = entry->exchange_addr_to_abort;
1837 	ctio->u.status1.flags = cpu_to_le16(CTIO7_FLAGS_STATUS_MODE_1 |
1838 					    CTIO7_FLAGS_TERMINATE);
1839 	ctio->u.status1.ox_id = cpu_to_le16(entry->fcp_hdr_le.ox_id);
1840 
1841 	/* Memory Barrier */
1842 	wmb();
1843 	qla2x00_start_iocbs(vha, vha->req);
1844 
1845 	qlt_24xx_send_abts_resp(vha->hw->base_qpair,
1846 	    (struct abts_recv_from_24xx *)entry,
1847 	    FCP_TMF_CMPL, true);
1848 }
1849 
1850 static int abort_cmd_for_tag(struct scsi_qla_host *vha, uint32_t tag)
1851 {
1852 	struct qla_tgt_sess_op *op;
1853 	struct qla_tgt_cmd *cmd;
1854 	unsigned long flags;
1855 
1856 	spin_lock_irqsave(&vha->cmd_list_lock, flags);
1857 	list_for_each_entry(op, &vha->qla_sess_op_cmd_list, cmd_list) {
1858 		if (tag == op->atio.u.isp24.exchange_addr) {
1859 			op->aborted = true;
1860 			spin_unlock_irqrestore(&vha->cmd_list_lock, flags);
1861 			return 1;
1862 		}
1863 	}
1864 
1865 	list_for_each_entry(op, &vha->unknown_atio_list, cmd_list) {
1866 		if (tag == op->atio.u.isp24.exchange_addr) {
1867 			op->aborted = true;
1868 			spin_unlock_irqrestore(&vha->cmd_list_lock, flags);
1869 			return 1;
1870 		}
1871 	}
1872 
1873 	list_for_each_entry(cmd, &vha->qla_cmd_list, cmd_list) {
1874 		if (tag == cmd->atio.u.isp24.exchange_addr) {
1875 			cmd->aborted = 1;
1876 			spin_unlock_irqrestore(&vha->cmd_list_lock, flags);
1877 			return 1;
1878 		}
1879 	}
1880 	spin_unlock_irqrestore(&vha->cmd_list_lock, flags);
1881 
1882 	return 0;
1883 }
1884 
1885 /* drop cmds for the given lun
1886  * XXX only looks for cmds on the port through which lun reset was recieved
1887  * XXX does not go through the list of other port (which may have cmds
1888  *     for the same lun)
1889  */
1890 static void abort_cmds_for_lun(struct scsi_qla_host *vha,
1891 			        u64 lun, uint8_t *s_id)
1892 {
1893 	struct qla_tgt_sess_op *op;
1894 	struct qla_tgt_cmd *cmd;
1895 	uint32_t key;
1896 	unsigned long flags;
1897 
1898 	key = sid_to_key(s_id);
1899 	spin_lock_irqsave(&vha->cmd_list_lock, flags);
1900 	list_for_each_entry(op, &vha->qla_sess_op_cmd_list, cmd_list) {
1901 		uint32_t op_key;
1902 		u64 op_lun;
1903 
1904 		op_key = sid_to_key(op->atio.u.isp24.fcp_hdr.s_id);
1905 		op_lun = scsilun_to_int(
1906 			(struct scsi_lun *)&op->atio.u.isp24.fcp_cmnd.lun);
1907 		if (op_key == key && op_lun == lun)
1908 			op->aborted = true;
1909 	}
1910 
1911 	list_for_each_entry(op, &vha->unknown_atio_list, cmd_list) {
1912 		uint32_t op_key;
1913 		u64 op_lun;
1914 
1915 		op_key = sid_to_key(op->atio.u.isp24.fcp_hdr.s_id);
1916 		op_lun = scsilun_to_int(
1917 			(struct scsi_lun *)&op->atio.u.isp24.fcp_cmnd.lun);
1918 		if (op_key == key && op_lun == lun)
1919 			op->aborted = true;
1920 	}
1921 
1922 	list_for_each_entry(cmd, &vha->qla_cmd_list, cmd_list) {
1923 		uint32_t cmd_key;
1924 		u64 cmd_lun;
1925 
1926 		cmd_key = sid_to_key(cmd->atio.u.isp24.fcp_hdr.s_id);
1927 		cmd_lun = scsilun_to_int(
1928 			(struct scsi_lun *)&cmd->atio.u.isp24.fcp_cmnd.lun);
1929 		if (cmd_key == key && cmd_lun == lun)
1930 			cmd->aborted = 1;
1931 	}
1932 	spin_unlock_irqrestore(&vha->cmd_list_lock, flags);
1933 }
1934 
1935 /* ha->hardware_lock supposed to be held on entry */
1936 static int __qlt_24xx_handle_abts(struct scsi_qla_host *vha,
1937 	struct abts_recv_from_24xx *abts, struct fc_port *sess)
1938 {
1939 	struct qla_hw_data *ha = vha->hw;
1940 	struct qla_tgt_mgmt_cmd *mcmd;
1941 	int rc;
1942 
1943 	if (abort_cmd_for_tag(vha, abts->exchange_addr_to_abort)) {
1944 		/* send TASK_ABORT response immediately */
1945 		qlt_24xx_send_abts_resp(ha->base_qpair, abts, FCP_TMF_CMPL, false);
1946 		return 0;
1947 	}
1948 
1949 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf00f,
1950 	    "qla_target(%d): task abort (tag=%d)\n",
1951 	    vha->vp_idx, abts->exchange_addr_to_abort);
1952 
1953 	mcmd = mempool_alloc(qla_tgt_mgmt_cmd_mempool, GFP_ATOMIC);
1954 	if (mcmd == NULL) {
1955 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf051,
1956 		    "qla_target(%d): %s: Allocation of ABORT cmd failed",
1957 		    vha->vp_idx, __func__);
1958 		return -ENOMEM;
1959 	}
1960 	memset(mcmd, 0, sizeof(*mcmd));
1961 
1962 	mcmd->sess = sess;
1963 	memcpy(&mcmd->orig_iocb.abts, abts, sizeof(mcmd->orig_iocb.abts));
1964 	mcmd->reset_count = ha->base_qpair->chip_reset;
1965 	mcmd->tmr_func = QLA_TGT_ABTS;
1966 	mcmd->qpair = ha->base_qpair;
1967 	mcmd->vha = vha;
1968 
1969 	/*
1970 	 * LUN is looked up by target-core internally based on the passed
1971 	 * abts->exchange_addr_to_abort tag.
1972 	 */
1973 	rc = ha->tgt.tgt_ops->handle_tmr(mcmd, 0, mcmd->tmr_func,
1974 	    abts->exchange_addr_to_abort);
1975 	if (rc != 0) {
1976 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf052,
1977 		    "qla_target(%d):  tgt_ops->handle_tmr()"
1978 		    " failed: %d", vha->vp_idx, rc);
1979 		mempool_free(mcmd, qla_tgt_mgmt_cmd_mempool);
1980 		return -EFAULT;
1981 	}
1982 
1983 	return 0;
1984 }
1985 
1986 /*
1987  * ha->hardware_lock supposed to be held on entry. Might drop it, then reaquire
1988  */
1989 static void qlt_24xx_handle_abts(struct scsi_qla_host *vha,
1990 	struct abts_recv_from_24xx *abts)
1991 {
1992 	struct qla_hw_data *ha = vha->hw;
1993 	struct fc_port *sess;
1994 	uint32_t tag = abts->exchange_addr_to_abort;
1995 	uint8_t s_id[3];
1996 	int rc;
1997 	unsigned long flags;
1998 
1999 	if (le32_to_cpu(abts->fcp_hdr_le.parameter) & ABTS_PARAM_ABORT_SEQ) {
2000 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf053,
2001 		    "qla_target(%d): ABTS: Abort Sequence not "
2002 		    "supported\n", vha->vp_idx);
2003 		qlt_24xx_send_abts_resp(ha->base_qpair, abts, FCP_TMF_REJECTED,
2004 		    false);
2005 		return;
2006 	}
2007 
2008 	if (tag == ATIO_EXCHANGE_ADDRESS_UNKNOWN) {
2009 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf010,
2010 		    "qla_target(%d): ABTS: Unknown Exchange "
2011 		    "Address received\n", vha->vp_idx);
2012 		qlt_24xx_send_abts_resp(ha->base_qpair, abts, FCP_TMF_REJECTED,
2013 		    false);
2014 		return;
2015 	}
2016 
2017 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf011,
2018 	    "qla_target(%d): task abort (s_id=%x:%x:%x, "
2019 	    "tag=%d, param=%x)\n", vha->vp_idx, abts->fcp_hdr_le.s_id[2],
2020 	    abts->fcp_hdr_le.s_id[1], abts->fcp_hdr_le.s_id[0], tag,
2021 	    le32_to_cpu(abts->fcp_hdr_le.parameter));
2022 
2023 	s_id[0] = abts->fcp_hdr_le.s_id[2];
2024 	s_id[1] = abts->fcp_hdr_le.s_id[1];
2025 	s_id[2] = abts->fcp_hdr_le.s_id[0];
2026 
2027 	spin_lock_irqsave(&ha->tgt.sess_lock, flags);
2028 	sess = ha->tgt.tgt_ops->find_sess_by_s_id(vha, s_id);
2029 	if (!sess) {
2030 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf012,
2031 		    "qla_target(%d): task abort for non-existant session\n",
2032 		    vha->vp_idx);
2033 		spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
2034 
2035 		qlt_24xx_send_abts_resp(ha->base_qpair, abts, FCP_TMF_REJECTED,
2036 			    false);
2037 		return;
2038 	}
2039 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
2040 
2041 
2042 	if (sess->deleted) {
2043 		qlt_24xx_send_abts_resp(ha->base_qpair, abts, FCP_TMF_REJECTED,
2044 		    false);
2045 		return;
2046 	}
2047 
2048 	rc = __qlt_24xx_handle_abts(vha, abts, sess);
2049 	if (rc != 0) {
2050 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf054,
2051 		    "qla_target(%d): __qlt_24xx_handle_abts() failed: %d\n",
2052 		    vha->vp_idx, rc);
2053 		qlt_24xx_send_abts_resp(ha->base_qpair, abts, FCP_TMF_REJECTED,
2054 		    false);
2055 		return;
2056 	}
2057 }
2058 
2059 /*
2060  * ha->hardware_lock supposed to be held on entry. Might drop it, then reaquire
2061  */
2062 static void qlt_24xx_send_task_mgmt_ctio(struct qla_qpair *qpair,
2063 	struct qla_tgt_mgmt_cmd *mcmd, uint32_t resp_code)
2064 {
2065 	struct scsi_qla_host *ha = mcmd->vha;
2066 	struct atio_from_isp *atio = &mcmd->orig_iocb.atio;
2067 	struct ctio7_to_24xx *ctio;
2068 	uint16_t temp;
2069 
2070 	ql_dbg(ql_dbg_tgt, ha, 0xe008,
2071 	    "Sending task mgmt CTIO7 (ha=%p, atio=%p, resp_code=%x\n",
2072 	    ha, atio, resp_code);
2073 
2074 
2075 	ctio = (struct ctio7_to_24xx *)__qla2x00_alloc_iocbs(qpair, NULL);
2076 	if (ctio == NULL) {
2077 		ql_dbg(ql_dbg_tgt, ha, 0xe04c,
2078 		    "qla_target(%d): %s failed: unable to allocate "
2079 		    "request packet\n", ha->vp_idx, __func__);
2080 		return;
2081 	}
2082 
2083 	ctio->entry_type = CTIO_TYPE7;
2084 	ctio->entry_count = 1;
2085 	ctio->handle = QLA_TGT_SKIP_HANDLE | CTIO_COMPLETION_HANDLE_MARK;
2086 	ctio->nport_handle = mcmd->sess->loop_id;
2087 	ctio->timeout = cpu_to_le16(QLA_TGT_TIMEOUT);
2088 	ctio->vp_index = ha->vp_idx;
2089 	ctio->initiator_id[0] = atio->u.isp24.fcp_hdr.s_id[2];
2090 	ctio->initiator_id[1] = atio->u.isp24.fcp_hdr.s_id[1];
2091 	ctio->initiator_id[2] = atio->u.isp24.fcp_hdr.s_id[0];
2092 	ctio->exchange_addr = atio->u.isp24.exchange_addr;
2093 	temp = (atio->u.isp24.attr << 9)|
2094 		CTIO7_FLAGS_STATUS_MODE_1 | CTIO7_FLAGS_SEND_STATUS;
2095 	ctio->u.status1.flags = cpu_to_le16(temp);
2096 	temp = be16_to_cpu(atio->u.isp24.fcp_hdr.ox_id);
2097 	ctio->u.status1.ox_id = cpu_to_le16(temp);
2098 	ctio->u.status1.scsi_status =
2099 	    cpu_to_le16(SS_RESPONSE_INFO_LEN_VALID);
2100 	ctio->u.status1.response_len = cpu_to_le16(8);
2101 	ctio->u.status1.sense_data[0] = resp_code;
2102 
2103 	/* Memory Barrier */
2104 	wmb();
2105 	if (qpair->reqq_start_iocbs)
2106 		qpair->reqq_start_iocbs(qpair);
2107 	else
2108 		qla2x00_start_iocbs(ha, qpair->req);
2109 }
2110 
2111 void qlt_free_mcmd(struct qla_tgt_mgmt_cmd *mcmd)
2112 {
2113 	mempool_free(mcmd, qla_tgt_mgmt_cmd_mempool);
2114 }
2115 EXPORT_SYMBOL(qlt_free_mcmd);
2116 
2117 /*
2118  * ha->hardware_lock supposed to be held on entry. Might drop it, then
2119  * reacquire
2120  */
2121 void qlt_send_resp_ctio(struct qla_qpair *qpair, struct qla_tgt_cmd *cmd,
2122     uint8_t scsi_status, uint8_t sense_key, uint8_t asc, uint8_t ascq)
2123 {
2124 	struct atio_from_isp *atio = &cmd->atio;
2125 	struct ctio7_to_24xx *ctio;
2126 	uint16_t temp;
2127 	struct scsi_qla_host *vha = cmd->vha;
2128 
2129 	ql_dbg(ql_dbg_tgt_dif, vha, 0x3066,
2130 	    "Sending response CTIO7 (vha=%p, atio=%p, scsi_status=%02x, "
2131 	    "sense_key=%02x, asc=%02x, ascq=%02x",
2132 	    vha, atio, scsi_status, sense_key, asc, ascq);
2133 
2134 	ctio = (struct ctio7_to_24xx *)qla2x00_alloc_iocbs(vha, NULL);
2135 	if (!ctio) {
2136 		ql_dbg(ql_dbg_async, vha, 0x3067,
2137 		    "qla2x00t(%ld): %s failed: unable to allocate request packet",
2138 		    vha->host_no, __func__);
2139 		goto out;
2140 	}
2141 
2142 	ctio->entry_type = CTIO_TYPE7;
2143 	ctio->entry_count = 1;
2144 	ctio->handle = QLA_TGT_SKIP_HANDLE;
2145 	ctio->nport_handle = cmd->sess->loop_id;
2146 	ctio->timeout = cpu_to_le16(QLA_TGT_TIMEOUT);
2147 	ctio->vp_index = vha->vp_idx;
2148 	ctio->initiator_id[0] = atio->u.isp24.fcp_hdr.s_id[2];
2149 	ctio->initiator_id[1] = atio->u.isp24.fcp_hdr.s_id[1];
2150 	ctio->initiator_id[2] = atio->u.isp24.fcp_hdr.s_id[0];
2151 	ctio->exchange_addr = atio->u.isp24.exchange_addr;
2152 	temp = (atio->u.isp24.attr << 9) |
2153 	    CTIO7_FLAGS_STATUS_MODE_1 | CTIO7_FLAGS_SEND_STATUS;
2154 	ctio->u.status1.flags = cpu_to_le16(temp);
2155 	temp = be16_to_cpu(atio->u.isp24.fcp_hdr.ox_id);
2156 	ctio->u.status1.ox_id = cpu_to_le16(temp);
2157 	ctio->u.status1.scsi_status =
2158 	    cpu_to_le16(SS_RESPONSE_INFO_LEN_VALID | scsi_status);
2159 	ctio->u.status1.response_len = cpu_to_le16(18);
2160 	ctio->u.status1.residual = cpu_to_le32(get_datalen_for_atio(atio));
2161 
2162 	if (ctio->u.status1.residual != 0)
2163 		ctio->u.status1.scsi_status |=
2164 		    cpu_to_le16(SS_RESIDUAL_UNDER);
2165 
2166 	/* Response code and sense key */
2167 	put_unaligned_le32(((0x70 << 24) | (sense_key << 8)),
2168 	    (&ctio->u.status1.sense_data)[0]);
2169 	/* Additional sense length */
2170 	put_unaligned_le32(0x0a, (&ctio->u.status1.sense_data)[1]);
2171 	/* ASC and ASCQ */
2172 	put_unaligned_le32(((asc << 24) | (ascq << 16)),
2173 	    (&ctio->u.status1.sense_data)[3]);
2174 
2175 	/* Memory Barrier */
2176 	wmb();
2177 
2178 	if (qpair->reqq_start_iocbs)
2179 		qpair->reqq_start_iocbs(qpair);
2180 	else
2181 		qla2x00_start_iocbs(vha, qpair->req);
2182 
2183 out:
2184 	return;
2185 }
2186 
2187 /* callback from target fabric module code */
2188 void qlt_xmit_tm_rsp(struct qla_tgt_mgmt_cmd *mcmd)
2189 {
2190 	struct scsi_qla_host *vha = mcmd->sess->vha;
2191 	struct qla_hw_data *ha = vha->hw;
2192 	unsigned long flags;
2193 	struct qla_qpair *qpair = mcmd->qpair;
2194 
2195 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf013,
2196 	    "TM response mcmd (%p) status %#x state %#x",
2197 	    mcmd, mcmd->fc_tm_rsp, mcmd->flags);
2198 
2199 	spin_lock_irqsave(qpair->qp_lock_ptr, flags);
2200 
2201 	if (!vha->flags.online || mcmd->reset_count != qpair->chip_reset) {
2202 		/*
2203 		 * Either the port is not online or this request was from
2204 		 * previous life, just abort the processing.
2205 		 */
2206 		ql_dbg(ql_dbg_async, vha, 0xe100,
2207 			"RESET-TMR online/active/old-count/new-count = %d/%d/%d/%d.\n",
2208 			vha->flags.online, qla2x00_reset_active(vha),
2209 			mcmd->reset_count, qpair->chip_reset);
2210 		ha->tgt.tgt_ops->free_mcmd(mcmd);
2211 		spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
2212 		return;
2213 	}
2214 
2215 	if (mcmd->flags == QLA24XX_MGMT_SEND_NACK) {
2216 		if (mcmd->orig_iocb.imm_ntfy.u.isp24.status_subcode ==
2217 		    ELS_LOGO ||
2218 		    mcmd->orig_iocb.imm_ntfy.u.isp24.status_subcode ==
2219 		    ELS_PRLO ||
2220 		    mcmd->orig_iocb.imm_ntfy.u.isp24.status_subcode ==
2221 		    ELS_TPRLO) {
2222 			ql_dbg(ql_dbg_disc, vha, 0x2106,
2223 			    "TM response logo %phC status %#x state %#x",
2224 			    mcmd->sess->port_name, mcmd->fc_tm_rsp,
2225 			    mcmd->flags);
2226 			qlt_schedule_sess_for_deletion(mcmd->sess);
2227 		} else {
2228 			qlt_send_notify_ack(vha->hw->base_qpair,
2229 			    &mcmd->orig_iocb.imm_ntfy, 0, 0, 0, 0, 0, 0);
2230 		}
2231 	} else {
2232 		if (mcmd->orig_iocb.atio.u.raw.entry_type == ABTS_RECV_24XX)
2233 			qlt_24xx_send_abts_resp(qpair, &mcmd->orig_iocb.abts,
2234 			    mcmd->fc_tm_rsp, false);
2235 		else
2236 			qlt_24xx_send_task_mgmt_ctio(qpair, mcmd,
2237 			    mcmd->fc_tm_rsp);
2238 	}
2239 	/*
2240 	 * Make the callback for ->free_mcmd() to queue_work() and invoke
2241 	 * target_put_sess_cmd() to drop cmd_kref to 1.  The final
2242 	 * target_put_sess_cmd() call will be made from TFO->check_stop_free()
2243 	 * -> tcm_qla2xxx_check_stop_free() to release the TMR associated se_cmd
2244 	 * descriptor after TFO->queue_tm_rsp() -> tcm_qla2xxx_queue_tm_rsp() ->
2245 	 * qlt_xmit_tm_rsp() returns here..
2246 	 */
2247 	ha->tgt.tgt_ops->free_mcmd(mcmd);
2248 	spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
2249 }
2250 EXPORT_SYMBOL(qlt_xmit_tm_rsp);
2251 
2252 /* No locks */
2253 static int qlt_pci_map_calc_cnt(struct qla_tgt_prm *prm)
2254 {
2255 	struct qla_tgt_cmd *cmd = prm->cmd;
2256 
2257 	BUG_ON(cmd->sg_cnt == 0);
2258 
2259 	prm->sg = (struct scatterlist *)cmd->sg;
2260 	prm->seg_cnt = pci_map_sg(cmd->qpair->pdev, cmd->sg,
2261 	    cmd->sg_cnt, cmd->dma_data_direction);
2262 	if (unlikely(prm->seg_cnt == 0))
2263 		goto out_err;
2264 
2265 	prm->cmd->sg_mapped = 1;
2266 
2267 	if (cmd->se_cmd.prot_op == TARGET_PROT_NORMAL) {
2268 		/*
2269 		 * If greater than four sg entries then we need to allocate
2270 		 * the continuation entries
2271 		 */
2272 		if (prm->seg_cnt > QLA_TGT_DATASEGS_PER_CMD_24XX)
2273 			prm->req_cnt += DIV_ROUND_UP(prm->seg_cnt -
2274 			QLA_TGT_DATASEGS_PER_CMD_24XX,
2275 			QLA_TGT_DATASEGS_PER_CONT_24XX);
2276 	} else {
2277 		/* DIF */
2278 		if ((cmd->se_cmd.prot_op == TARGET_PROT_DIN_INSERT) ||
2279 		    (cmd->se_cmd.prot_op == TARGET_PROT_DOUT_STRIP)) {
2280 			prm->seg_cnt = DIV_ROUND_UP(cmd->bufflen, cmd->blk_sz);
2281 			prm->tot_dsds = prm->seg_cnt;
2282 		} else
2283 			prm->tot_dsds = prm->seg_cnt;
2284 
2285 		if (cmd->prot_sg_cnt) {
2286 			prm->prot_sg      = cmd->prot_sg;
2287 			prm->prot_seg_cnt = pci_map_sg(cmd->qpair->pdev,
2288 				cmd->prot_sg, cmd->prot_sg_cnt,
2289 				cmd->dma_data_direction);
2290 			if (unlikely(prm->prot_seg_cnt == 0))
2291 				goto out_err;
2292 
2293 			if ((cmd->se_cmd.prot_op == TARGET_PROT_DIN_INSERT) ||
2294 			    (cmd->se_cmd.prot_op == TARGET_PROT_DOUT_STRIP)) {
2295 				/* Dif Bundling not support here */
2296 				prm->prot_seg_cnt = DIV_ROUND_UP(cmd->bufflen,
2297 								cmd->blk_sz);
2298 				prm->tot_dsds += prm->prot_seg_cnt;
2299 			} else
2300 				prm->tot_dsds += prm->prot_seg_cnt;
2301 		}
2302 	}
2303 
2304 	return 0;
2305 
2306 out_err:
2307 	ql_dbg_qp(ql_dbg_tgt, prm->cmd->qpair, 0xe04d,
2308 	    "qla_target(%d): PCI mapping failed: sg_cnt=%d",
2309 	    0, prm->cmd->sg_cnt);
2310 	return -1;
2311 }
2312 
2313 static void qlt_unmap_sg(struct scsi_qla_host *vha, struct qla_tgt_cmd *cmd)
2314 {
2315 	struct qla_hw_data *ha;
2316 	struct qla_qpair *qpair;
2317 	if (!cmd->sg_mapped)
2318 		return;
2319 
2320 	qpair = cmd->qpair;
2321 
2322 	pci_unmap_sg(qpair->pdev, cmd->sg, cmd->sg_cnt,
2323 	    cmd->dma_data_direction);
2324 	cmd->sg_mapped = 0;
2325 
2326 	if (cmd->prot_sg_cnt)
2327 		pci_unmap_sg(qpair->pdev, cmd->prot_sg, cmd->prot_sg_cnt,
2328 			cmd->dma_data_direction);
2329 
2330 	if (!cmd->ctx)
2331 		return;
2332 	ha = vha->hw;
2333 	if (cmd->ctx_dsd_alloced)
2334 		qla2x00_clean_dsd_pool(ha, cmd->ctx);
2335 
2336 	dma_pool_free(ha->dl_dma_pool, cmd->ctx, cmd->ctx->crc_ctx_dma);
2337 }
2338 
2339 static int qlt_check_reserve_free_req(struct qla_qpair *qpair,
2340 	uint32_t req_cnt)
2341 {
2342 	uint32_t cnt;
2343 	struct req_que *req = qpair->req;
2344 
2345 	if (req->cnt < (req_cnt + 2)) {
2346 		cnt = (uint16_t)(qpair->use_shadow_reg ? *req->out_ptr :
2347 		    RD_REG_DWORD_RELAXED(req->req_q_out));
2348 
2349 		if  (req->ring_index < cnt)
2350 			req->cnt = cnt - req->ring_index;
2351 		else
2352 			req->cnt = req->length - (req->ring_index - cnt);
2353 
2354 		if (unlikely(req->cnt < (req_cnt + 2)))
2355 			return -EAGAIN;
2356 	}
2357 
2358 	req->cnt -= req_cnt;
2359 
2360 	return 0;
2361 }
2362 
2363 /*
2364  * ha->hardware_lock supposed to be held on entry. Might drop it, then reaquire
2365  */
2366 static inline void *qlt_get_req_pkt(struct req_que *req)
2367 {
2368 	/* Adjust ring index. */
2369 	req->ring_index++;
2370 	if (req->ring_index == req->length) {
2371 		req->ring_index = 0;
2372 		req->ring_ptr = req->ring;
2373 	} else {
2374 		req->ring_ptr++;
2375 	}
2376 	return (cont_entry_t *)req->ring_ptr;
2377 }
2378 
2379 /* ha->hardware_lock supposed to be held on entry */
2380 static inline uint32_t qlt_make_handle(struct qla_qpair *qpair)
2381 {
2382 	uint32_t h;
2383 	int index;
2384 	uint8_t found = 0;
2385 	struct req_que *req = qpair->req;
2386 
2387 	h = req->current_outstanding_cmd;
2388 
2389 	for (index = 1; index < req->num_outstanding_cmds; index++) {
2390 		h++;
2391 		if (h == req->num_outstanding_cmds)
2392 			h = 1;
2393 
2394 		if (h == QLA_TGT_SKIP_HANDLE)
2395 			continue;
2396 
2397 		if (!req->outstanding_cmds[h]) {
2398 			found = 1;
2399 			break;
2400 		}
2401 	}
2402 
2403 	if (found) {
2404 		req->current_outstanding_cmd = h;
2405 	} else {
2406 		ql_dbg(ql_dbg_io, qpair->vha, 0x305b,
2407 		    "qla_target(%d): Ran out of empty cmd slots\n",
2408 		    qpair->vha->vp_idx);
2409 		h = QLA_TGT_NULL_HANDLE;
2410 	}
2411 
2412 	return h;
2413 }
2414 
2415 /* ha->hardware_lock supposed to be held on entry */
2416 static int qlt_24xx_build_ctio_pkt(struct qla_qpair *qpair,
2417 	struct qla_tgt_prm *prm)
2418 {
2419 	uint32_t h;
2420 	struct ctio7_to_24xx *pkt;
2421 	struct atio_from_isp *atio = &prm->cmd->atio;
2422 	uint16_t temp;
2423 
2424 	pkt = (struct ctio7_to_24xx *)qpair->req->ring_ptr;
2425 	prm->pkt = pkt;
2426 	memset(pkt, 0, sizeof(*pkt));
2427 
2428 	pkt->entry_type = CTIO_TYPE7;
2429 	pkt->entry_count = (uint8_t)prm->req_cnt;
2430 	pkt->vp_index = prm->cmd->vp_idx;
2431 
2432 	h = qlt_make_handle(qpair);
2433 	if (unlikely(h == QLA_TGT_NULL_HANDLE)) {
2434 		/*
2435 		 * CTIO type 7 from the firmware doesn't provide a way to
2436 		 * know the initiator's LOOP ID, hence we can't find
2437 		 * the session and, so, the command.
2438 		 */
2439 		return -EAGAIN;
2440 	} else
2441 		qpair->req->outstanding_cmds[h] = (srb_t *)prm->cmd;
2442 
2443 	pkt->handle = MAKE_HANDLE(qpair->req->id, h);
2444 	pkt->handle |= CTIO_COMPLETION_HANDLE_MARK;
2445 	pkt->nport_handle = cpu_to_le16(prm->cmd->loop_id);
2446 	pkt->timeout = cpu_to_le16(QLA_TGT_TIMEOUT);
2447 	pkt->initiator_id[0] = atio->u.isp24.fcp_hdr.s_id[2];
2448 	pkt->initiator_id[1] = atio->u.isp24.fcp_hdr.s_id[1];
2449 	pkt->initiator_id[2] = atio->u.isp24.fcp_hdr.s_id[0];
2450 	pkt->exchange_addr = atio->u.isp24.exchange_addr;
2451 	temp = atio->u.isp24.attr << 9;
2452 	pkt->u.status0.flags |= cpu_to_le16(temp);
2453 	temp = be16_to_cpu(atio->u.isp24.fcp_hdr.ox_id);
2454 	pkt->u.status0.ox_id = cpu_to_le16(temp);
2455 	pkt->u.status0.relative_offset = cpu_to_le32(prm->cmd->offset);
2456 
2457 	return 0;
2458 }
2459 
2460 /*
2461  * ha->hardware_lock supposed to be held on entry. We have already made sure
2462  * that there is sufficient amount of request entries to not drop it.
2463  */
2464 static void qlt_load_cont_data_segments(struct qla_tgt_prm *prm)
2465 {
2466 	int cnt;
2467 	uint32_t *dword_ptr;
2468 
2469 	/* Build continuation packets */
2470 	while (prm->seg_cnt > 0) {
2471 		cont_a64_entry_t *cont_pkt64 =
2472 			(cont_a64_entry_t *)qlt_get_req_pkt(
2473 			   prm->cmd->qpair->req);
2474 
2475 		/*
2476 		 * Make sure that from cont_pkt64 none of
2477 		 * 64-bit specific fields used for 32-bit
2478 		 * addressing. Cast to (cont_entry_t *) for
2479 		 * that.
2480 		 */
2481 
2482 		memset(cont_pkt64, 0, sizeof(*cont_pkt64));
2483 
2484 		cont_pkt64->entry_count = 1;
2485 		cont_pkt64->sys_define = 0;
2486 
2487 		cont_pkt64->entry_type = CONTINUE_A64_TYPE;
2488 		dword_ptr = (uint32_t *)&cont_pkt64->dseg_0_address;
2489 
2490 		/* Load continuation entry data segments */
2491 		for (cnt = 0;
2492 		    cnt < QLA_TGT_DATASEGS_PER_CONT_24XX && prm->seg_cnt;
2493 		    cnt++, prm->seg_cnt--) {
2494 			*dword_ptr++ =
2495 			    cpu_to_le32(pci_dma_lo32
2496 				(sg_dma_address(prm->sg)));
2497 			*dword_ptr++ = cpu_to_le32(pci_dma_hi32
2498 			    (sg_dma_address(prm->sg)));
2499 			*dword_ptr++ = cpu_to_le32(sg_dma_len(prm->sg));
2500 
2501 			prm->sg = sg_next(prm->sg);
2502 		}
2503 	}
2504 }
2505 
2506 /*
2507  * ha->hardware_lock supposed to be held on entry. We have already made sure
2508  * that there is sufficient amount of request entries to not drop it.
2509  */
2510 static void qlt_load_data_segments(struct qla_tgt_prm *prm)
2511 {
2512 	int cnt;
2513 	uint32_t *dword_ptr;
2514 	struct ctio7_to_24xx *pkt24 = (struct ctio7_to_24xx *)prm->pkt;
2515 
2516 	pkt24->u.status0.transfer_length = cpu_to_le32(prm->cmd->bufflen);
2517 
2518 	/* Setup packet address segment pointer */
2519 	dword_ptr = pkt24->u.status0.dseg_0_address;
2520 
2521 	/* Set total data segment count */
2522 	if (prm->seg_cnt)
2523 		pkt24->dseg_count = cpu_to_le16(prm->seg_cnt);
2524 
2525 	if (prm->seg_cnt == 0) {
2526 		/* No data transfer */
2527 		*dword_ptr++ = 0;
2528 		*dword_ptr = 0;
2529 		return;
2530 	}
2531 
2532 	/* If scatter gather */
2533 
2534 	/* Load command entry data segments */
2535 	for (cnt = 0;
2536 	    (cnt < QLA_TGT_DATASEGS_PER_CMD_24XX) && prm->seg_cnt;
2537 	    cnt++, prm->seg_cnt--) {
2538 		*dword_ptr++ =
2539 		    cpu_to_le32(pci_dma_lo32(sg_dma_address(prm->sg)));
2540 
2541 		*dword_ptr++ = cpu_to_le32(pci_dma_hi32(
2542 			sg_dma_address(prm->sg)));
2543 
2544 		*dword_ptr++ = cpu_to_le32(sg_dma_len(prm->sg));
2545 
2546 		prm->sg = sg_next(prm->sg);
2547 	}
2548 
2549 	qlt_load_cont_data_segments(prm);
2550 }
2551 
2552 static inline int qlt_has_data(struct qla_tgt_cmd *cmd)
2553 {
2554 	return cmd->bufflen > 0;
2555 }
2556 
2557 static void qlt_print_dif_err(struct qla_tgt_prm *prm)
2558 {
2559 	struct qla_tgt_cmd *cmd;
2560 	struct scsi_qla_host *vha;
2561 
2562 	/* asc 0x10=dif error */
2563 	if (prm->sense_buffer && (prm->sense_buffer[12] == 0x10)) {
2564 		cmd = prm->cmd;
2565 		vha = cmd->vha;
2566 		/* ASCQ */
2567 		switch (prm->sense_buffer[13]) {
2568 		case 1:
2569 			ql_dbg(ql_dbg_tgt_dif, vha, 0xe00b,
2570 			    "BE detected Guard TAG ERR: lba[0x%llx|%lld] len[0x%x] "
2571 			    "se_cmd=%p tag[%x]",
2572 			    cmd->lba, cmd->lba, cmd->num_blks, &cmd->se_cmd,
2573 			    cmd->atio.u.isp24.exchange_addr);
2574 			break;
2575 		case 2:
2576 			ql_dbg(ql_dbg_tgt_dif, vha, 0xe00c,
2577 			    "BE detected APP TAG ERR: lba[0x%llx|%lld] len[0x%x] "
2578 			    "se_cmd=%p tag[%x]",
2579 			    cmd->lba, cmd->lba, cmd->num_blks, &cmd->se_cmd,
2580 			    cmd->atio.u.isp24.exchange_addr);
2581 			break;
2582 		case 3:
2583 			ql_dbg(ql_dbg_tgt_dif, vha, 0xe00f,
2584 			    "BE detected REF TAG ERR: lba[0x%llx|%lld] len[0x%x] "
2585 			    "se_cmd=%p tag[%x]",
2586 			    cmd->lba, cmd->lba, cmd->num_blks, &cmd->se_cmd,
2587 			    cmd->atio.u.isp24.exchange_addr);
2588 			break;
2589 		default:
2590 			ql_dbg(ql_dbg_tgt_dif, vha, 0xe010,
2591 			    "BE detected Dif ERR: lba[%llx|%lld] len[%x] "
2592 			    "se_cmd=%p tag[%x]",
2593 			    cmd->lba, cmd->lba, cmd->num_blks, &cmd->se_cmd,
2594 			    cmd->atio.u.isp24.exchange_addr);
2595 			break;
2596 		}
2597 		ql_dump_buffer(ql_dbg_tgt_dif, vha, 0xe011, cmd->cdb, 16);
2598 	}
2599 }
2600 
2601 /*
2602  * Called without ha->hardware_lock held
2603  */
2604 static int qlt_pre_xmit_response(struct qla_tgt_cmd *cmd,
2605 	struct qla_tgt_prm *prm, int xmit_type, uint8_t scsi_status,
2606 	uint32_t *full_req_cnt)
2607 {
2608 	struct se_cmd *se_cmd = &cmd->se_cmd;
2609 	struct qla_qpair *qpair = cmd->qpair;
2610 
2611 	prm->cmd = cmd;
2612 	prm->tgt = cmd->tgt;
2613 	prm->pkt = NULL;
2614 	prm->rq_result = scsi_status;
2615 	prm->sense_buffer = &cmd->sense_buffer[0];
2616 	prm->sense_buffer_len = TRANSPORT_SENSE_BUFFER;
2617 	prm->sg = NULL;
2618 	prm->seg_cnt = -1;
2619 	prm->req_cnt = 1;
2620 	prm->residual = 0;
2621 	prm->add_status_pkt = 0;
2622 	prm->prot_sg = NULL;
2623 	prm->prot_seg_cnt = 0;
2624 	prm->tot_dsds = 0;
2625 
2626 	if ((xmit_type & QLA_TGT_XMIT_DATA) && qlt_has_data(cmd)) {
2627 		if  (qlt_pci_map_calc_cnt(prm) != 0)
2628 			return -EAGAIN;
2629 	}
2630 
2631 	*full_req_cnt = prm->req_cnt;
2632 
2633 	if (se_cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
2634 		prm->residual = se_cmd->residual_count;
2635 		ql_dbg_qp(ql_dbg_io + ql_dbg_verbose, qpair, 0x305c,
2636 		    "Residual underflow: %d (tag %lld, op %x, bufflen %d, rq_result %x)\n",
2637 		       prm->residual, se_cmd->tag,
2638 		       se_cmd->t_task_cdb ? se_cmd->t_task_cdb[0] : 0,
2639 		       cmd->bufflen, prm->rq_result);
2640 		prm->rq_result |= SS_RESIDUAL_UNDER;
2641 	} else if (se_cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
2642 		prm->residual = se_cmd->residual_count;
2643 		ql_dbg_qp(ql_dbg_io, qpair, 0x305d,
2644 		    "Residual overflow: %d (tag %lld, op %x, bufflen %d, rq_result %x)\n",
2645 		       prm->residual, se_cmd->tag, se_cmd->t_task_cdb ?
2646 		       se_cmd->t_task_cdb[0] : 0, cmd->bufflen, prm->rq_result);
2647 		prm->rq_result |= SS_RESIDUAL_OVER;
2648 	}
2649 
2650 	if (xmit_type & QLA_TGT_XMIT_STATUS) {
2651 		/*
2652 		 * If QLA_TGT_XMIT_DATA is not set, add_status_pkt will be
2653 		 * ignored in *xmit_response() below
2654 		 */
2655 		if (qlt_has_data(cmd)) {
2656 			if (QLA_TGT_SENSE_VALID(prm->sense_buffer) ||
2657 			    (IS_FWI2_CAPABLE(cmd->vha->hw) &&
2658 			    (prm->rq_result != 0))) {
2659 				prm->add_status_pkt = 1;
2660 				(*full_req_cnt)++;
2661 			}
2662 		}
2663 	}
2664 
2665 	return 0;
2666 }
2667 
2668 static inline int qlt_need_explicit_conf(struct qla_tgt_cmd *cmd,
2669     int sending_sense)
2670 {
2671 	if (cmd->qpair->enable_class_2)
2672 		return 0;
2673 
2674 	if (sending_sense)
2675 		return cmd->conf_compl_supported;
2676 	else
2677 		return cmd->qpair->enable_explicit_conf &&
2678                     cmd->conf_compl_supported;
2679 }
2680 
2681 static void qlt_24xx_init_ctio_to_isp(struct ctio7_to_24xx *ctio,
2682 	struct qla_tgt_prm *prm)
2683 {
2684 	prm->sense_buffer_len = min_t(uint32_t, prm->sense_buffer_len,
2685 	    (uint32_t)sizeof(ctio->u.status1.sense_data));
2686 	ctio->u.status0.flags |= cpu_to_le16(CTIO7_FLAGS_SEND_STATUS);
2687 	if (qlt_need_explicit_conf(prm->cmd, 0)) {
2688 		ctio->u.status0.flags |= cpu_to_le16(
2689 		    CTIO7_FLAGS_EXPLICIT_CONFORM |
2690 		    CTIO7_FLAGS_CONFORM_REQ);
2691 	}
2692 	ctio->u.status0.residual = cpu_to_le32(prm->residual);
2693 	ctio->u.status0.scsi_status = cpu_to_le16(prm->rq_result);
2694 	if (QLA_TGT_SENSE_VALID(prm->sense_buffer)) {
2695 		int i;
2696 
2697 		if (qlt_need_explicit_conf(prm->cmd, 1)) {
2698 			if ((prm->rq_result & SS_SCSI_STATUS_BYTE) != 0) {
2699 				ql_dbg_qp(ql_dbg_tgt, prm->cmd->qpair, 0xe017,
2700 				    "Skipping EXPLICIT_CONFORM and "
2701 				    "CTIO7_FLAGS_CONFORM_REQ for FCP READ w/ "
2702 				    "non GOOD status\n");
2703 				goto skip_explict_conf;
2704 			}
2705 			ctio->u.status1.flags |= cpu_to_le16(
2706 			    CTIO7_FLAGS_EXPLICIT_CONFORM |
2707 			    CTIO7_FLAGS_CONFORM_REQ);
2708 		}
2709 skip_explict_conf:
2710 		ctio->u.status1.flags &=
2711 		    ~cpu_to_le16(CTIO7_FLAGS_STATUS_MODE_0);
2712 		ctio->u.status1.flags |=
2713 		    cpu_to_le16(CTIO7_FLAGS_STATUS_MODE_1);
2714 		ctio->u.status1.scsi_status |=
2715 		    cpu_to_le16(SS_SENSE_LEN_VALID);
2716 		ctio->u.status1.sense_length =
2717 		    cpu_to_le16(prm->sense_buffer_len);
2718 		for (i = 0; i < prm->sense_buffer_len/4; i++)
2719 			((uint32_t *)ctio->u.status1.sense_data)[i] =
2720 				cpu_to_be32(((uint32_t *)prm->sense_buffer)[i]);
2721 
2722 		qlt_print_dif_err(prm);
2723 
2724 	} else {
2725 		ctio->u.status1.flags &=
2726 		    ~cpu_to_le16(CTIO7_FLAGS_STATUS_MODE_0);
2727 		ctio->u.status1.flags |=
2728 		    cpu_to_le16(CTIO7_FLAGS_STATUS_MODE_1);
2729 		ctio->u.status1.sense_length = 0;
2730 		memset(ctio->u.status1.sense_data, 0,
2731 		    sizeof(ctio->u.status1.sense_data));
2732 	}
2733 
2734 	/* Sense with len > 24, is it possible ??? */
2735 }
2736 
2737 static inline int
2738 qlt_hba_err_chk_enabled(struct se_cmd *se_cmd)
2739 {
2740 	switch (se_cmd->prot_op) {
2741 	case TARGET_PROT_DOUT_INSERT:
2742 	case TARGET_PROT_DIN_STRIP:
2743 		if (ql2xenablehba_err_chk >= 1)
2744 			return 1;
2745 		break;
2746 	case TARGET_PROT_DOUT_PASS:
2747 	case TARGET_PROT_DIN_PASS:
2748 		if (ql2xenablehba_err_chk >= 2)
2749 			return 1;
2750 		break;
2751 	case TARGET_PROT_DIN_INSERT:
2752 	case TARGET_PROT_DOUT_STRIP:
2753 		return 1;
2754 	default:
2755 		break;
2756 	}
2757 	return 0;
2758 }
2759 
2760 static inline int
2761 qla_tgt_ref_mask_check(struct se_cmd *se_cmd)
2762 {
2763 	switch (se_cmd->prot_op) {
2764 	case TARGET_PROT_DIN_INSERT:
2765 	case TARGET_PROT_DOUT_INSERT:
2766 	case TARGET_PROT_DIN_STRIP:
2767 	case TARGET_PROT_DOUT_STRIP:
2768 	case TARGET_PROT_DIN_PASS:
2769 	case TARGET_PROT_DOUT_PASS:
2770 	    return 1;
2771 	default:
2772 	    return 0;
2773 	}
2774 	return 0;
2775 }
2776 
2777 /*
2778  * qla_tgt_set_dif_tags - Extract Ref and App tags from SCSI command
2779  */
2780 static void
2781 qla_tgt_set_dif_tags(struct qla_tgt_cmd *cmd, struct crc_context *ctx,
2782     uint16_t *pfw_prot_opts)
2783 {
2784 	struct se_cmd *se_cmd = &cmd->se_cmd;
2785 	uint32_t lba = 0xffffffff & se_cmd->t_task_lba;
2786 	scsi_qla_host_t *vha = cmd->tgt->vha;
2787 	struct qla_hw_data *ha = vha->hw;
2788 	uint32_t t32 = 0;
2789 
2790 	/*
2791 	 * wait till Mode Sense/Select cmd, modepage Ah, subpage 2
2792 	 * have been immplemented by TCM, before AppTag is avail.
2793 	 * Look for modesense_handlers[]
2794 	 */
2795 	ctx->app_tag = 0;
2796 	ctx->app_tag_mask[0] = 0x0;
2797 	ctx->app_tag_mask[1] = 0x0;
2798 
2799 	if (IS_PI_UNINIT_CAPABLE(ha)) {
2800 		if ((se_cmd->prot_type == TARGET_DIF_TYPE1_PROT) ||
2801 		    (se_cmd->prot_type == TARGET_DIF_TYPE2_PROT))
2802 			*pfw_prot_opts |= PO_DIS_VALD_APP_ESC;
2803 		else if (se_cmd->prot_type == TARGET_DIF_TYPE3_PROT)
2804 			*pfw_prot_opts |= PO_DIS_VALD_APP_REF_ESC;
2805 	}
2806 
2807 	t32 = ha->tgt.tgt_ops->get_dif_tags(cmd, pfw_prot_opts);
2808 
2809 	switch (se_cmd->prot_type) {
2810 	case TARGET_DIF_TYPE0_PROT:
2811 		/*
2812 		 * No check for ql2xenablehba_err_chk, as it
2813 		 * would be an I/O error if hba tag generation
2814 		 * is not done.
2815 		 */
2816 		ctx->ref_tag = cpu_to_le32(lba);
2817 		/* enable ALL bytes of the ref tag */
2818 		ctx->ref_tag_mask[0] = 0xff;
2819 		ctx->ref_tag_mask[1] = 0xff;
2820 		ctx->ref_tag_mask[2] = 0xff;
2821 		ctx->ref_tag_mask[3] = 0xff;
2822 		break;
2823 	case TARGET_DIF_TYPE1_PROT:
2824 	    /*
2825 	     * For TYPE 1 protection: 16 bit GUARD tag, 32 bit
2826 	     * REF tag, and 16 bit app tag.
2827 	     */
2828 	    ctx->ref_tag = cpu_to_le32(lba);
2829 	    if (!qla_tgt_ref_mask_check(se_cmd) ||
2830 		!(ha->tgt.tgt_ops->chk_dif_tags(t32))) {
2831 		    *pfw_prot_opts |= PO_DIS_REF_TAG_VALD;
2832 		    break;
2833 	    }
2834 	    /* enable ALL bytes of the ref tag */
2835 	    ctx->ref_tag_mask[0] = 0xff;
2836 	    ctx->ref_tag_mask[1] = 0xff;
2837 	    ctx->ref_tag_mask[2] = 0xff;
2838 	    ctx->ref_tag_mask[3] = 0xff;
2839 	    break;
2840 	case TARGET_DIF_TYPE2_PROT:
2841 	    /*
2842 	     * For TYPE 2 protection: 16 bit GUARD + 32 bit REF
2843 	     * tag has to match LBA in CDB + N
2844 	     */
2845 	    ctx->ref_tag = cpu_to_le32(lba);
2846 	    if (!qla_tgt_ref_mask_check(se_cmd) ||
2847 		!(ha->tgt.tgt_ops->chk_dif_tags(t32))) {
2848 		    *pfw_prot_opts |= PO_DIS_REF_TAG_VALD;
2849 		    break;
2850 	    }
2851 	    /* enable ALL bytes of the ref tag */
2852 	    ctx->ref_tag_mask[0] = 0xff;
2853 	    ctx->ref_tag_mask[1] = 0xff;
2854 	    ctx->ref_tag_mask[2] = 0xff;
2855 	    ctx->ref_tag_mask[3] = 0xff;
2856 	    break;
2857 	case TARGET_DIF_TYPE3_PROT:
2858 	    /* For TYPE 3 protection: 16 bit GUARD only */
2859 	    *pfw_prot_opts |= PO_DIS_REF_TAG_VALD;
2860 	    ctx->ref_tag_mask[0] = ctx->ref_tag_mask[1] =
2861 		ctx->ref_tag_mask[2] = ctx->ref_tag_mask[3] = 0x00;
2862 	    break;
2863 	}
2864 }
2865 
2866 static inline int
2867 qlt_build_ctio_crc2_pkt(struct qla_qpair *qpair, struct qla_tgt_prm *prm)
2868 {
2869 	uint32_t		*cur_dsd;
2870 	uint32_t		transfer_length = 0;
2871 	uint32_t		data_bytes;
2872 	uint32_t		dif_bytes;
2873 	uint8_t			bundling = 1;
2874 	uint8_t			*clr_ptr;
2875 	struct crc_context	*crc_ctx_pkt = NULL;
2876 	struct qla_hw_data	*ha;
2877 	struct ctio_crc2_to_fw	*pkt;
2878 	dma_addr_t		crc_ctx_dma;
2879 	uint16_t		fw_prot_opts = 0;
2880 	struct qla_tgt_cmd	*cmd = prm->cmd;
2881 	struct se_cmd		*se_cmd = &cmd->se_cmd;
2882 	uint32_t h;
2883 	struct atio_from_isp *atio = &prm->cmd->atio;
2884 	struct qla_tc_param	tc;
2885 	uint16_t t16;
2886 	scsi_qla_host_t *vha = cmd->vha;
2887 
2888 	ha = vha->hw;
2889 
2890 	pkt = (struct ctio_crc2_to_fw *)qpair->req->ring_ptr;
2891 	prm->pkt = pkt;
2892 	memset(pkt, 0, sizeof(*pkt));
2893 
2894 	ql_dbg_qp(ql_dbg_tgt, cmd->qpair, 0xe071,
2895 		"qla_target(%d):%s: se_cmd[%p] CRC2 prot_op[0x%x] cmd prot sg:cnt[%p:%x] lba[%llu]\n",
2896 		cmd->vp_idx, __func__, se_cmd, se_cmd->prot_op,
2897 		prm->prot_sg, prm->prot_seg_cnt, se_cmd->t_task_lba);
2898 
2899 	if ((se_cmd->prot_op == TARGET_PROT_DIN_INSERT) ||
2900 	    (se_cmd->prot_op == TARGET_PROT_DOUT_STRIP))
2901 		bundling = 0;
2902 
2903 	/* Compute dif len and adjust data len to incude protection */
2904 	data_bytes = cmd->bufflen;
2905 	dif_bytes  = (data_bytes / cmd->blk_sz) * 8;
2906 
2907 	switch (se_cmd->prot_op) {
2908 	case TARGET_PROT_DIN_INSERT:
2909 	case TARGET_PROT_DOUT_STRIP:
2910 		transfer_length = data_bytes;
2911 		if (cmd->prot_sg_cnt)
2912 			data_bytes += dif_bytes;
2913 		break;
2914 	case TARGET_PROT_DIN_STRIP:
2915 	case TARGET_PROT_DOUT_INSERT:
2916 	case TARGET_PROT_DIN_PASS:
2917 	case TARGET_PROT_DOUT_PASS:
2918 		transfer_length = data_bytes + dif_bytes;
2919 		break;
2920 	default:
2921 		BUG();
2922 		break;
2923 	}
2924 
2925 	if (!qlt_hba_err_chk_enabled(se_cmd))
2926 		fw_prot_opts |= 0x10; /* Disable Guard tag checking */
2927 	/* HBA error checking enabled */
2928 	else if (IS_PI_UNINIT_CAPABLE(ha)) {
2929 		if ((se_cmd->prot_type == TARGET_DIF_TYPE1_PROT) ||
2930 		    (se_cmd->prot_type == TARGET_DIF_TYPE2_PROT))
2931 			fw_prot_opts |= PO_DIS_VALD_APP_ESC;
2932 		else if (se_cmd->prot_type == TARGET_DIF_TYPE3_PROT)
2933 			fw_prot_opts |= PO_DIS_VALD_APP_REF_ESC;
2934 	}
2935 
2936 	switch (se_cmd->prot_op) {
2937 	case TARGET_PROT_DIN_INSERT:
2938 	case TARGET_PROT_DOUT_INSERT:
2939 		fw_prot_opts |= PO_MODE_DIF_INSERT;
2940 		break;
2941 	case TARGET_PROT_DIN_STRIP:
2942 	case TARGET_PROT_DOUT_STRIP:
2943 		fw_prot_opts |= PO_MODE_DIF_REMOVE;
2944 		break;
2945 	case TARGET_PROT_DIN_PASS:
2946 	case TARGET_PROT_DOUT_PASS:
2947 		fw_prot_opts |= PO_MODE_DIF_PASS;
2948 		/* FUTURE: does tcm require T10CRC<->IPCKSUM conversion? */
2949 		break;
2950 	default:/* Normal Request */
2951 		fw_prot_opts |= PO_MODE_DIF_PASS;
2952 		break;
2953 	}
2954 
2955 	/* ---- PKT ---- */
2956 	/* Update entry type to indicate Command Type CRC_2 IOCB */
2957 	pkt->entry_type  = CTIO_CRC2;
2958 	pkt->entry_count = 1;
2959 	pkt->vp_index = cmd->vp_idx;
2960 
2961 	h = qlt_make_handle(qpair);
2962 	if (unlikely(h == QLA_TGT_NULL_HANDLE)) {
2963 		/*
2964 		 * CTIO type 7 from the firmware doesn't provide a way to
2965 		 * know the initiator's LOOP ID, hence we can't find
2966 		 * the session and, so, the command.
2967 		 */
2968 		return -EAGAIN;
2969 	} else
2970 		qpair->req->outstanding_cmds[h] = (srb_t *)prm->cmd;
2971 
2972 	pkt->handle  = MAKE_HANDLE(qpair->req->id, h);
2973 	pkt->handle |= CTIO_COMPLETION_HANDLE_MARK;
2974 	pkt->nport_handle = cpu_to_le16(prm->cmd->loop_id);
2975 	pkt->timeout = cpu_to_le16(QLA_TGT_TIMEOUT);
2976 	pkt->initiator_id[0] = atio->u.isp24.fcp_hdr.s_id[2];
2977 	pkt->initiator_id[1] = atio->u.isp24.fcp_hdr.s_id[1];
2978 	pkt->initiator_id[2] = atio->u.isp24.fcp_hdr.s_id[0];
2979 	pkt->exchange_addr   = atio->u.isp24.exchange_addr;
2980 
2981 	/* silence compile warning */
2982 	t16 = be16_to_cpu(atio->u.isp24.fcp_hdr.ox_id);
2983 	pkt->ox_id  = cpu_to_le16(t16);
2984 
2985 	t16 = (atio->u.isp24.attr << 9);
2986 	pkt->flags |= cpu_to_le16(t16);
2987 	pkt->relative_offset = cpu_to_le32(prm->cmd->offset);
2988 
2989 	/* Set transfer direction */
2990 	if (cmd->dma_data_direction == DMA_TO_DEVICE)
2991 		pkt->flags = cpu_to_le16(CTIO7_FLAGS_DATA_IN);
2992 	else if (cmd->dma_data_direction == DMA_FROM_DEVICE)
2993 		pkt->flags = cpu_to_le16(CTIO7_FLAGS_DATA_OUT);
2994 
2995 	pkt->dseg_count = prm->tot_dsds;
2996 	/* Fibre channel byte count */
2997 	pkt->transfer_length = cpu_to_le32(transfer_length);
2998 
2999 	/* ----- CRC context -------- */
3000 
3001 	/* Allocate CRC context from global pool */
3002 	crc_ctx_pkt = cmd->ctx =
3003 	    dma_pool_alloc(ha->dl_dma_pool, GFP_ATOMIC, &crc_ctx_dma);
3004 
3005 	if (!crc_ctx_pkt)
3006 		goto crc_queuing_error;
3007 
3008 	/* Zero out CTX area. */
3009 	clr_ptr = (uint8_t *)crc_ctx_pkt;
3010 	memset(clr_ptr, 0, sizeof(*crc_ctx_pkt));
3011 
3012 	crc_ctx_pkt->crc_ctx_dma = crc_ctx_dma;
3013 	INIT_LIST_HEAD(&crc_ctx_pkt->dsd_list);
3014 
3015 	/* Set handle */
3016 	crc_ctx_pkt->handle = pkt->handle;
3017 
3018 	qla_tgt_set_dif_tags(cmd, crc_ctx_pkt, &fw_prot_opts);
3019 
3020 	pkt->crc_context_address[0] = cpu_to_le32(LSD(crc_ctx_dma));
3021 	pkt->crc_context_address[1] = cpu_to_le32(MSD(crc_ctx_dma));
3022 	pkt->crc_context_len = CRC_CONTEXT_LEN_FW;
3023 
3024 	if (!bundling) {
3025 		cur_dsd = (uint32_t *) &crc_ctx_pkt->u.nobundling.data_address;
3026 	} else {
3027 		/*
3028 		 * Configure Bundling if we need to fetch interlaving
3029 		 * protection PCI accesses
3030 		 */
3031 		fw_prot_opts |= PO_ENABLE_DIF_BUNDLING;
3032 		crc_ctx_pkt->u.bundling.dif_byte_count = cpu_to_le32(dif_bytes);
3033 		crc_ctx_pkt->u.bundling.dseg_count =
3034 			cpu_to_le16(prm->tot_dsds - prm->prot_seg_cnt);
3035 		cur_dsd = (uint32_t *) &crc_ctx_pkt->u.bundling.data_address;
3036 	}
3037 
3038 	/* Finish the common fields of CRC pkt */
3039 	crc_ctx_pkt->blk_size   = cpu_to_le16(cmd->blk_sz);
3040 	crc_ctx_pkt->prot_opts  = cpu_to_le16(fw_prot_opts);
3041 	crc_ctx_pkt->byte_count = cpu_to_le32(data_bytes);
3042 	crc_ctx_pkt->guard_seed = cpu_to_le16(0);
3043 
3044 	memset((uint8_t *)&tc, 0 , sizeof(tc));
3045 	tc.vha = vha;
3046 	tc.blk_sz = cmd->blk_sz;
3047 	tc.bufflen = cmd->bufflen;
3048 	tc.sg = cmd->sg;
3049 	tc.prot_sg = cmd->prot_sg;
3050 	tc.ctx = crc_ctx_pkt;
3051 	tc.ctx_dsd_alloced = &cmd->ctx_dsd_alloced;
3052 
3053 	/* Walks data segments */
3054 	pkt->flags |= cpu_to_le16(CTIO7_FLAGS_DSD_PTR);
3055 
3056 	if (!bundling && prm->prot_seg_cnt) {
3057 		if (qla24xx_walk_and_build_sglist_no_difb(ha, NULL, cur_dsd,
3058 			prm->tot_dsds, &tc))
3059 			goto crc_queuing_error;
3060 	} else if (qla24xx_walk_and_build_sglist(ha, NULL, cur_dsd,
3061 		(prm->tot_dsds - prm->prot_seg_cnt), &tc))
3062 		goto crc_queuing_error;
3063 
3064 	if (bundling && prm->prot_seg_cnt) {
3065 		/* Walks dif segments */
3066 		pkt->add_flags |= CTIO_CRC2_AF_DIF_DSD_ENA;
3067 
3068 		cur_dsd = (uint32_t *) &crc_ctx_pkt->u.bundling.dif_address;
3069 		if (qla24xx_walk_and_build_prot_sglist(ha, NULL, cur_dsd,
3070 			prm->prot_seg_cnt, &tc))
3071 			goto crc_queuing_error;
3072 	}
3073 	return QLA_SUCCESS;
3074 
3075 crc_queuing_error:
3076 	/* Cleanup will be performed by the caller */
3077 	qpair->req->outstanding_cmds[h] = NULL;
3078 
3079 	return QLA_FUNCTION_FAILED;
3080 }
3081 
3082 /*
3083  * Callback to setup response of xmit_type of QLA_TGT_XMIT_DATA and *
3084  * QLA_TGT_XMIT_STATUS for >= 24xx silicon
3085  */
3086 int qlt_xmit_response(struct qla_tgt_cmd *cmd, int xmit_type,
3087 	uint8_t scsi_status)
3088 {
3089 	struct scsi_qla_host *vha = cmd->vha;
3090 	struct qla_qpair *qpair = cmd->qpair;
3091 	struct ctio7_to_24xx *pkt;
3092 	struct qla_tgt_prm prm;
3093 	uint32_t full_req_cnt = 0;
3094 	unsigned long flags = 0;
3095 	int res;
3096 
3097 	if (cmd->sess && cmd->sess->deleted) {
3098 		cmd->state = QLA_TGT_STATE_PROCESSED;
3099 		if (cmd->sess->logout_completed)
3100 			/* no need to terminate. FW already freed exchange. */
3101 			qlt_abort_cmd_on_host_reset(cmd->vha, cmd);
3102 		else
3103 			qlt_send_term_exchange(qpair, cmd, &cmd->atio, 0, 0);
3104 		return 0;
3105 	}
3106 
3107 	ql_dbg_qp(ql_dbg_tgt, qpair, 0xe018,
3108 	    "is_send_status=%d, cmd->bufflen=%d, cmd->sg_cnt=%d, cmd->dma_data_direction=%d se_cmd[%p] qp %d\n",
3109 	    (xmit_type & QLA_TGT_XMIT_STATUS) ?
3110 	    1 : 0, cmd->bufflen, cmd->sg_cnt, cmd->dma_data_direction,
3111 	    &cmd->se_cmd, qpair->id);
3112 
3113 	res = qlt_pre_xmit_response(cmd, &prm, xmit_type, scsi_status,
3114 	    &full_req_cnt);
3115 	if (unlikely(res != 0)) {
3116 		return res;
3117 	}
3118 
3119 	spin_lock_irqsave(qpair->qp_lock_ptr, flags);
3120 
3121 	if (xmit_type == QLA_TGT_XMIT_STATUS)
3122 		qpair->tgt_counters.core_qla_snd_status++;
3123 	else
3124 		qpair->tgt_counters.core_qla_que_buf++;
3125 
3126 	if (!qpair->fw_started || cmd->reset_count != qpair->chip_reset) {
3127 		/*
3128 		 * Either the port is not online or this request was from
3129 		 * previous life, just abort the processing.
3130 		 */
3131 		cmd->state = QLA_TGT_STATE_PROCESSED;
3132 		qlt_abort_cmd_on_host_reset(cmd->vha, cmd);
3133 		ql_dbg_qp(ql_dbg_async, qpair, 0xe101,
3134 			"RESET-RSP online/active/old-count/new-count = %d/%d/%d/%d.\n",
3135 			vha->flags.online, qla2x00_reset_active(vha),
3136 			cmd->reset_count, qpair->chip_reset);
3137 		spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
3138 		return 0;
3139 	}
3140 
3141 	/* Does F/W have an IOCBs for this request */
3142 	res = qlt_check_reserve_free_req(qpair, full_req_cnt);
3143 	if (unlikely(res))
3144 		goto out_unmap_unlock;
3145 
3146 	if (cmd->se_cmd.prot_op && (xmit_type & QLA_TGT_XMIT_DATA))
3147 		res = qlt_build_ctio_crc2_pkt(qpair, &prm);
3148 	else
3149 		res = qlt_24xx_build_ctio_pkt(qpair, &prm);
3150 	if (unlikely(res != 0)) {
3151 		qpair->req->cnt += full_req_cnt;
3152 		goto out_unmap_unlock;
3153 	}
3154 
3155 	pkt = (struct ctio7_to_24xx *)prm.pkt;
3156 
3157 	if (qlt_has_data(cmd) && (xmit_type & QLA_TGT_XMIT_DATA)) {
3158 		pkt->u.status0.flags |=
3159 		    cpu_to_le16(CTIO7_FLAGS_DATA_IN |
3160 			CTIO7_FLAGS_STATUS_MODE_0);
3161 
3162 		if (cmd->se_cmd.prot_op == TARGET_PROT_NORMAL)
3163 			qlt_load_data_segments(&prm);
3164 
3165 		if (prm.add_status_pkt == 0) {
3166 			if (xmit_type & QLA_TGT_XMIT_STATUS) {
3167 				pkt->u.status0.scsi_status =
3168 				    cpu_to_le16(prm.rq_result);
3169 				pkt->u.status0.residual =
3170 				    cpu_to_le32(prm.residual);
3171 				pkt->u.status0.flags |= cpu_to_le16(
3172 				    CTIO7_FLAGS_SEND_STATUS);
3173 				if (qlt_need_explicit_conf(cmd, 0)) {
3174 					pkt->u.status0.flags |=
3175 					    cpu_to_le16(
3176 						CTIO7_FLAGS_EXPLICIT_CONFORM |
3177 						CTIO7_FLAGS_CONFORM_REQ);
3178 				}
3179 			}
3180 
3181 		} else {
3182 			/*
3183 			 * We have already made sure that there is sufficient
3184 			 * amount of request entries to not drop HW lock in
3185 			 * req_pkt().
3186 			 */
3187 			struct ctio7_to_24xx *ctio =
3188 				(struct ctio7_to_24xx *)qlt_get_req_pkt(
3189 				    qpair->req);
3190 
3191 			ql_dbg_qp(ql_dbg_tgt, qpair, 0x305e,
3192 			    "Building additional status packet 0x%p.\n",
3193 			    ctio);
3194 
3195 			/*
3196 			 * T10Dif: ctio_crc2_to_fw overlay ontop of
3197 			 * ctio7_to_24xx
3198 			 */
3199 			memcpy(ctio, pkt, sizeof(*ctio));
3200 			/* reset back to CTIO7 */
3201 			ctio->entry_count = 1;
3202 			ctio->entry_type = CTIO_TYPE7;
3203 			ctio->dseg_count = 0;
3204 			ctio->u.status1.flags &= ~cpu_to_le16(
3205 			    CTIO7_FLAGS_DATA_IN);
3206 
3207 			/* Real finish is ctio_m1's finish */
3208 			pkt->handle |= CTIO_INTERMEDIATE_HANDLE_MARK;
3209 			pkt->u.status0.flags |= cpu_to_le16(
3210 			    CTIO7_FLAGS_DONT_RET_CTIO);
3211 
3212 			/* qlt_24xx_init_ctio_to_isp will correct
3213 			 * all neccessary fields that's part of CTIO7.
3214 			 * There should be no residual of CTIO-CRC2 data.
3215 			 */
3216 			qlt_24xx_init_ctio_to_isp((struct ctio7_to_24xx *)ctio,
3217 			    &prm);
3218 		}
3219 	} else
3220 		qlt_24xx_init_ctio_to_isp(pkt, &prm);
3221 
3222 
3223 	cmd->state = QLA_TGT_STATE_PROCESSED; /* Mid-level is done processing */
3224 	cmd->cmd_sent_to_fw = 1;
3225 
3226 	/* Memory Barrier */
3227 	wmb();
3228 	if (qpair->reqq_start_iocbs)
3229 		qpair->reqq_start_iocbs(qpair);
3230 	else
3231 		qla2x00_start_iocbs(vha, qpair->req);
3232 	spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
3233 
3234 	return 0;
3235 
3236 out_unmap_unlock:
3237 	qlt_unmap_sg(vha, cmd);
3238 	spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
3239 
3240 	return res;
3241 }
3242 EXPORT_SYMBOL(qlt_xmit_response);
3243 
3244 int qlt_rdy_to_xfer(struct qla_tgt_cmd *cmd)
3245 {
3246 	struct ctio7_to_24xx *pkt;
3247 	struct scsi_qla_host *vha = cmd->vha;
3248 	struct qla_tgt *tgt = cmd->tgt;
3249 	struct qla_tgt_prm prm;
3250 	unsigned long flags = 0;
3251 	int res = 0;
3252 	struct qla_qpair *qpair = cmd->qpair;
3253 
3254 	memset(&prm, 0, sizeof(prm));
3255 	prm.cmd = cmd;
3256 	prm.tgt = tgt;
3257 	prm.sg = NULL;
3258 	prm.req_cnt = 1;
3259 
3260 	/* Calculate number of entries and segments required */
3261 	if (qlt_pci_map_calc_cnt(&prm) != 0)
3262 		return -EAGAIN;
3263 
3264 	if (!qpair->fw_started || (cmd->reset_count != qpair->chip_reset) ||
3265 	    (cmd->sess && cmd->sess->deleted)) {
3266 		/*
3267 		 * Either the port is not online or this request was from
3268 		 * previous life, just abort the processing.
3269 		 */
3270 		cmd->state = QLA_TGT_STATE_NEED_DATA;
3271 		qlt_abort_cmd_on_host_reset(cmd->vha, cmd);
3272 		ql_dbg_qp(ql_dbg_async, qpair, 0xe102,
3273 			"RESET-XFR online/active/old-count/new-count = %d/%d/%d/%d.\n",
3274 			vha->flags.online, qla2x00_reset_active(vha),
3275 			cmd->reset_count, qpair->chip_reset);
3276 		return 0;
3277 	}
3278 
3279 	spin_lock_irqsave(qpair->qp_lock_ptr, flags);
3280 	/* Does F/W have an IOCBs for this request */
3281 	res = qlt_check_reserve_free_req(qpair, prm.req_cnt);
3282 	if (res != 0)
3283 		goto out_unlock_free_unmap;
3284 	if (cmd->se_cmd.prot_op)
3285 		res = qlt_build_ctio_crc2_pkt(qpair, &prm);
3286 	else
3287 		res = qlt_24xx_build_ctio_pkt(qpair, &prm);
3288 
3289 	if (unlikely(res != 0)) {
3290 		qpair->req->cnt += prm.req_cnt;
3291 		goto out_unlock_free_unmap;
3292 	}
3293 
3294 	pkt = (struct ctio7_to_24xx *)prm.pkt;
3295 	pkt->u.status0.flags |= cpu_to_le16(CTIO7_FLAGS_DATA_OUT |
3296 	    CTIO7_FLAGS_STATUS_MODE_0);
3297 
3298 	if (cmd->se_cmd.prot_op == TARGET_PROT_NORMAL)
3299 		qlt_load_data_segments(&prm);
3300 
3301 	cmd->state = QLA_TGT_STATE_NEED_DATA;
3302 	cmd->cmd_sent_to_fw = 1;
3303 
3304 	/* Memory Barrier */
3305 	wmb();
3306 	if (qpair->reqq_start_iocbs)
3307 		qpair->reqq_start_iocbs(qpair);
3308 	else
3309 		qla2x00_start_iocbs(vha, qpair->req);
3310 	spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
3311 
3312 	return res;
3313 
3314 out_unlock_free_unmap:
3315 	qlt_unmap_sg(vha, cmd);
3316 	spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
3317 
3318 	return res;
3319 }
3320 EXPORT_SYMBOL(qlt_rdy_to_xfer);
3321 
3322 
3323 /*
3324  * it is assumed either hardware_lock or qpair lock is held.
3325  */
3326 static void
3327 qlt_handle_dif_error(struct qla_qpair *qpair, struct qla_tgt_cmd *cmd,
3328 	struct ctio_crc_from_fw *sts)
3329 {
3330 	uint8_t		*ap = &sts->actual_dif[0];
3331 	uint8_t		*ep = &sts->expected_dif[0];
3332 	uint64_t	lba = cmd->se_cmd.t_task_lba;
3333 	uint8_t scsi_status, sense_key, asc, ascq;
3334 	unsigned long flags;
3335 	struct scsi_qla_host *vha = cmd->vha;
3336 
3337 	cmd->trc_flags |= TRC_DIF_ERR;
3338 
3339 	cmd->a_guard   = be16_to_cpu(*(uint16_t *)(ap + 0));
3340 	cmd->a_app_tag = be16_to_cpu(*(uint16_t *)(ap + 2));
3341 	cmd->a_ref_tag = be32_to_cpu(*(uint32_t *)(ap + 4));
3342 
3343 	cmd->e_guard   = be16_to_cpu(*(uint16_t *)(ep + 0));
3344 	cmd->e_app_tag = be16_to_cpu(*(uint16_t *)(ep + 2));
3345 	cmd->e_ref_tag = be32_to_cpu(*(uint32_t *)(ep + 4));
3346 
3347 	ql_dbg(ql_dbg_tgt_dif, vha, 0xf075,
3348 	    "%s: aborted %d state %d\n", __func__, cmd->aborted, cmd->state);
3349 
3350 	scsi_status = sense_key = asc = ascq = 0;
3351 
3352 	/* check appl tag */
3353 	if (cmd->e_app_tag != cmd->a_app_tag) {
3354 		ql_dbg(ql_dbg_tgt_dif, vha, 0xe00d,
3355 		    "App Tag ERR: cdb[%x] lba[%llx %llx] blks[%x] [Actual|Expected] Ref[%x|%x], App[%x|%x], Guard [%x|%x] cmd=%p ox_id[%04x]",
3356 		    cmd->cdb[0], lba, (lba+cmd->num_blks), cmd->num_blks,
3357 		    cmd->a_ref_tag, cmd->e_ref_tag, cmd->a_app_tag,
3358 		    cmd->e_app_tag, cmd->a_guard, cmd->e_guard, cmd,
3359 		    cmd->atio.u.isp24.fcp_hdr.ox_id);
3360 
3361 		cmd->dif_err_code = DIF_ERR_APP;
3362 		scsi_status = SAM_STAT_CHECK_CONDITION;
3363 		sense_key = ABORTED_COMMAND;
3364 		asc = 0x10;
3365 		ascq = 0x2;
3366 	}
3367 
3368 	/* check ref tag */
3369 	if (cmd->e_ref_tag != cmd->a_ref_tag) {
3370 		ql_dbg(ql_dbg_tgt_dif, vha, 0xe00e,
3371 		    "Ref Tag ERR: cdb[%x] lba[%llx %llx] blks[%x] [Actual|Expected] Ref[%x|%x], App[%x|%x], Guard[%x|%x] cmd=%p ox_id[%04x] ",
3372 		    cmd->cdb[0], lba, (lba+cmd->num_blks), cmd->num_blks,
3373 		    cmd->a_ref_tag, cmd->e_ref_tag, cmd->a_app_tag,
3374 		    cmd->e_app_tag, cmd->a_guard, cmd->e_guard, cmd,
3375 		    cmd->atio.u.isp24.fcp_hdr.ox_id);
3376 
3377 		cmd->dif_err_code = DIF_ERR_REF;
3378 		scsi_status = SAM_STAT_CHECK_CONDITION;
3379 		sense_key = ABORTED_COMMAND;
3380 		asc = 0x10;
3381 		ascq = 0x3;
3382 		goto out;
3383 	}
3384 
3385 	/* check guard */
3386 	if (cmd->e_guard != cmd->a_guard) {
3387 		ql_dbg(ql_dbg_tgt_dif, vha, 0xe012,
3388 		    "Guard ERR: cdb[%x] lba[%llx %llx] blks[%x] [Actual|Expected] Ref[%x|%x], App[%x|%x], Guard [%x|%x] cmd=%p ox_id[%04x]",
3389 		    cmd->cdb[0], lba, (lba+cmd->num_blks), cmd->num_blks,
3390 		    cmd->a_ref_tag, cmd->e_ref_tag, cmd->a_app_tag,
3391 		    cmd->e_app_tag, cmd->a_guard, cmd->e_guard, cmd,
3392 		    cmd->atio.u.isp24.fcp_hdr.ox_id);
3393 
3394 		cmd->dif_err_code = DIF_ERR_GRD;
3395 		scsi_status = SAM_STAT_CHECK_CONDITION;
3396 		sense_key = ABORTED_COMMAND;
3397 		asc = 0x10;
3398 		ascq = 0x1;
3399 	}
3400 out:
3401 	switch (cmd->state) {
3402 	case QLA_TGT_STATE_NEED_DATA:
3403 		/* handle_data will load DIF error code  */
3404 		cmd->state = QLA_TGT_STATE_DATA_IN;
3405 		vha->hw->tgt.tgt_ops->handle_data(cmd);
3406 		break;
3407 	default:
3408 		spin_lock_irqsave(&cmd->cmd_lock, flags);
3409 		if (cmd->aborted) {
3410 			spin_unlock_irqrestore(&cmd->cmd_lock, flags);
3411 			vha->hw->tgt.tgt_ops->free_cmd(cmd);
3412 			break;
3413 		}
3414 		spin_unlock_irqrestore(&cmd->cmd_lock, flags);
3415 
3416 		qlt_send_resp_ctio(qpair, cmd, scsi_status, sense_key, asc,
3417 		    ascq);
3418 		/* assume scsi status gets out on the wire.
3419 		 * Will not wait for completion.
3420 		 */
3421 		vha->hw->tgt.tgt_ops->free_cmd(cmd);
3422 		break;
3423 	}
3424 }
3425 
3426 /* If hardware_lock held on entry, might drop it, then reaquire */
3427 /* This function sends the appropriate CTIO to ISP 2xxx or 24xx */
3428 static int __qlt_send_term_imm_notif(struct scsi_qla_host *vha,
3429 	struct imm_ntfy_from_isp *ntfy)
3430 {
3431 	struct nack_to_isp *nack;
3432 	struct qla_hw_data *ha = vha->hw;
3433 	request_t *pkt;
3434 	int ret = 0;
3435 
3436 	ql_dbg(ql_dbg_tgt_tmr, vha, 0xe01c,
3437 	    "Sending TERM ELS CTIO (ha=%p)\n", ha);
3438 
3439 	pkt = (request_t *)qla2x00_alloc_iocbs(vha, NULL);
3440 	if (pkt == NULL) {
3441 		ql_dbg(ql_dbg_tgt, vha, 0xe080,
3442 		    "qla_target(%d): %s failed: unable to allocate "
3443 		    "request packet\n", vha->vp_idx, __func__);
3444 		return -ENOMEM;
3445 	}
3446 
3447 	pkt->entry_type = NOTIFY_ACK_TYPE;
3448 	pkt->entry_count = 1;
3449 	pkt->handle = QLA_TGT_SKIP_HANDLE;
3450 
3451 	nack = (struct nack_to_isp *)pkt;
3452 	nack->ox_id = ntfy->ox_id;
3453 
3454 	nack->u.isp24.nport_handle = ntfy->u.isp24.nport_handle;
3455 	if (le16_to_cpu(ntfy->u.isp24.status) == IMM_NTFY_ELS) {
3456 		nack->u.isp24.flags = ntfy->u.isp24.flags &
3457 			__constant_cpu_to_le32(NOTIFY24XX_FLAGS_PUREX_IOCB);
3458 	}
3459 
3460 	/* terminate */
3461 	nack->u.isp24.flags |=
3462 		__constant_cpu_to_le16(NOTIFY_ACK_FLAGS_TERMINATE);
3463 
3464 	nack->u.isp24.srr_rx_id = ntfy->u.isp24.srr_rx_id;
3465 	nack->u.isp24.status = ntfy->u.isp24.status;
3466 	nack->u.isp24.status_subcode = ntfy->u.isp24.status_subcode;
3467 	nack->u.isp24.fw_handle = ntfy->u.isp24.fw_handle;
3468 	nack->u.isp24.exchange_address = ntfy->u.isp24.exchange_address;
3469 	nack->u.isp24.srr_rel_offs = ntfy->u.isp24.srr_rel_offs;
3470 	nack->u.isp24.srr_ui = ntfy->u.isp24.srr_ui;
3471 	nack->u.isp24.vp_index = ntfy->u.isp24.vp_index;
3472 
3473 	qla2x00_start_iocbs(vha, vha->req);
3474 	return ret;
3475 }
3476 
3477 static void qlt_send_term_imm_notif(struct scsi_qla_host *vha,
3478 	struct imm_ntfy_from_isp *imm, int ha_locked)
3479 {
3480 	unsigned long flags = 0;
3481 	int rc;
3482 
3483 	if (ha_locked) {
3484 		rc = __qlt_send_term_imm_notif(vha, imm);
3485 
3486 #if 0	/* Todo  */
3487 		if (rc == -ENOMEM)
3488 			qlt_alloc_qfull_cmd(vha, imm, 0, 0);
3489 #else
3490 		if (rc) {
3491 		}
3492 #endif
3493 		goto done;
3494 	}
3495 
3496 	spin_lock_irqsave(&vha->hw->hardware_lock, flags);
3497 	rc = __qlt_send_term_imm_notif(vha, imm);
3498 
3499 #if 0	/* Todo */
3500 	if (rc == -ENOMEM)
3501 		qlt_alloc_qfull_cmd(vha, imm, 0, 0);
3502 #endif
3503 
3504 done:
3505 	if (!ha_locked)
3506 		spin_unlock_irqrestore(&vha->hw->hardware_lock, flags);
3507 }
3508 
3509 /*
3510  * If hardware_lock held on entry, might drop it, then reaquire
3511  * This function sends the appropriate CTIO to ISP 2xxx or 24xx
3512  */
3513 static int __qlt_send_term_exchange(struct qla_qpair *qpair,
3514 	struct qla_tgt_cmd *cmd,
3515 	struct atio_from_isp *atio)
3516 {
3517 	struct scsi_qla_host *vha = qpair->vha;
3518 	struct ctio7_to_24xx *ctio24;
3519 	struct qla_hw_data *ha = vha->hw;
3520 	request_t *pkt;
3521 	int ret = 0;
3522 	uint16_t temp;
3523 
3524 	ql_dbg(ql_dbg_tgt, vha, 0xe009, "Sending TERM EXCH CTIO (ha=%p)\n", ha);
3525 
3526 	if (cmd)
3527 		vha = cmd->vha;
3528 
3529 	pkt = (request_t *)qla2x00_alloc_iocbs_ready(qpair, NULL);
3530 	if (pkt == NULL) {
3531 		ql_dbg(ql_dbg_tgt, vha, 0xe050,
3532 		    "qla_target(%d): %s failed: unable to allocate "
3533 		    "request packet\n", vha->vp_idx, __func__);
3534 		return -ENOMEM;
3535 	}
3536 
3537 	if (cmd != NULL) {
3538 		if (cmd->state < QLA_TGT_STATE_PROCESSED) {
3539 			ql_dbg(ql_dbg_tgt, vha, 0xe051,
3540 			    "qla_target(%d): Terminating cmd %p with "
3541 			    "incorrect state %d\n", vha->vp_idx, cmd,
3542 			    cmd->state);
3543 		} else
3544 			ret = 1;
3545 	}
3546 
3547 	qpair->tgt_counters.num_term_xchg_sent++;
3548 	pkt->entry_count = 1;
3549 	pkt->handle = QLA_TGT_SKIP_HANDLE | CTIO_COMPLETION_HANDLE_MARK;
3550 
3551 	ctio24 = (struct ctio7_to_24xx *)pkt;
3552 	ctio24->entry_type = CTIO_TYPE7;
3553 	ctio24->nport_handle = CTIO7_NHANDLE_UNRECOGNIZED;
3554 	ctio24->timeout = cpu_to_le16(QLA_TGT_TIMEOUT);
3555 	ctio24->vp_index = vha->vp_idx;
3556 	ctio24->initiator_id[0] = atio->u.isp24.fcp_hdr.s_id[2];
3557 	ctio24->initiator_id[1] = atio->u.isp24.fcp_hdr.s_id[1];
3558 	ctio24->initiator_id[2] = atio->u.isp24.fcp_hdr.s_id[0];
3559 	ctio24->exchange_addr = atio->u.isp24.exchange_addr;
3560 	temp = (atio->u.isp24.attr << 9) | CTIO7_FLAGS_STATUS_MODE_1 |
3561 		CTIO7_FLAGS_TERMINATE;
3562 	ctio24->u.status1.flags = cpu_to_le16(temp);
3563 	temp = be16_to_cpu(atio->u.isp24.fcp_hdr.ox_id);
3564 	ctio24->u.status1.ox_id = cpu_to_le16(temp);
3565 
3566 	/* Most likely, it isn't needed */
3567 	ctio24->u.status1.residual = get_unaligned((uint32_t *)
3568 	    &atio->u.isp24.fcp_cmnd.add_cdb[
3569 	    atio->u.isp24.fcp_cmnd.add_cdb_len]);
3570 	if (ctio24->u.status1.residual != 0)
3571 		ctio24->u.status1.scsi_status |= SS_RESIDUAL_UNDER;
3572 
3573 	/* Memory Barrier */
3574 	wmb();
3575 	if (qpair->reqq_start_iocbs)
3576 		qpair->reqq_start_iocbs(qpair);
3577 	else
3578 		qla2x00_start_iocbs(vha, qpair->req);
3579 	return ret;
3580 }
3581 
3582 static void qlt_send_term_exchange(struct qla_qpair *qpair,
3583 	struct qla_tgt_cmd *cmd, struct atio_from_isp *atio, int ha_locked,
3584 	int ul_abort)
3585 {
3586 	struct scsi_qla_host *vha;
3587 	unsigned long flags = 0;
3588 	int rc;
3589 
3590 	/* why use different vha? NPIV */
3591 	if (cmd)
3592 		vha = cmd->vha;
3593 	else
3594 		vha = qpair->vha;
3595 
3596 	if (ha_locked) {
3597 		rc = __qlt_send_term_exchange(qpair, cmd, atio);
3598 		if (rc == -ENOMEM)
3599 			qlt_alloc_qfull_cmd(vha, atio, 0, 0);
3600 		goto done;
3601 	}
3602 	spin_lock_irqsave(qpair->qp_lock_ptr, flags);
3603 	rc = __qlt_send_term_exchange(qpair, cmd, atio);
3604 	if (rc == -ENOMEM)
3605 		qlt_alloc_qfull_cmd(vha, atio, 0, 0);
3606 
3607 done:
3608 	if (cmd && !ul_abort && !cmd->aborted) {
3609 		if (cmd->sg_mapped)
3610 			qlt_unmap_sg(vha, cmd);
3611 		vha->hw->tgt.tgt_ops->free_cmd(cmd);
3612 	}
3613 
3614 	if (!ha_locked)
3615 		spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
3616 
3617 	return;
3618 }
3619 
3620 static void qlt_init_term_exchange(struct scsi_qla_host *vha)
3621 {
3622 	struct list_head free_list;
3623 	struct qla_tgt_cmd *cmd, *tcmd;
3624 
3625 	vha->hw->tgt.leak_exchg_thresh_hold =
3626 	    (vha->hw->cur_fw_xcb_count/100) * LEAK_EXCHG_THRESH_HOLD_PERCENT;
3627 
3628 	cmd = tcmd = NULL;
3629 	if (!list_empty(&vha->hw->tgt.q_full_list)) {
3630 		INIT_LIST_HEAD(&free_list);
3631 		list_splice_init(&vha->hw->tgt.q_full_list, &free_list);
3632 
3633 		list_for_each_entry_safe(cmd, tcmd, &free_list, cmd_list) {
3634 			list_del(&cmd->cmd_list);
3635 			/* This cmd was never sent to TCM.  There is no need
3636 			 * to schedule free or call free_cmd
3637 			 */
3638 			qlt_free_cmd(cmd);
3639 			vha->hw->tgt.num_qfull_cmds_alloc--;
3640 		}
3641 	}
3642 	vha->hw->tgt.num_qfull_cmds_dropped = 0;
3643 }
3644 
3645 static void qlt_chk_exch_leak_thresh_hold(struct scsi_qla_host *vha)
3646 {
3647 	uint32_t total_leaked;
3648 
3649 	total_leaked = vha->hw->tgt.num_qfull_cmds_dropped;
3650 
3651 	if (vha->hw->tgt.leak_exchg_thresh_hold &&
3652 	    (total_leaked > vha->hw->tgt.leak_exchg_thresh_hold)) {
3653 
3654 		ql_dbg(ql_dbg_tgt, vha, 0xe079,
3655 		    "Chip reset due to exchange starvation: %d/%d.\n",
3656 		    total_leaked, vha->hw->cur_fw_xcb_count);
3657 
3658 		if (IS_P3P_TYPE(vha->hw))
3659 			set_bit(FCOE_CTX_RESET_NEEDED, &vha->dpc_flags);
3660 		else
3661 			set_bit(ISP_ABORT_NEEDED, &vha->dpc_flags);
3662 		qla2xxx_wake_dpc(vha);
3663 	}
3664 
3665 }
3666 
3667 int qlt_abort_cmd(struct qla_tgt_cmd *cmd)
3668 {
3669 	struct qla_tgt *tgt = cmd->tgt;
3670 	struct scsi_qla_host *vha = tgt->vha;
3671 	struct se_cmd *se_cmd = &cmd->se_cmd;
3672 	unsigned long flags;
3673 
3674 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf014,
3675 	    "qla_target(%d): terminating exchange for aborted cmd=%p "
3676 	    "(se_cmd=%p, tag=%llu)", vha->vp_idx, cmd, &cmd->se_cmd,
3677 	    se_cmd->tag);
3678 
3679 	spin_lock_irqsave(&cmd->cmd_lock, flags);
3680 	if (cmd->aborted) {
3681 		spin_unlock_irqrestore(&cmd->cmd_lock, flags);
3682 		/*
3683 		 * It's normal to see 2 calls in this path:
3684 		 *  1) XFER Rdy completion + CMD_T_ABORT
3685 		 *  2) TCM TMR - drain_state_list
3686 		 */
3687 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf016,
3688 		    "multiple abort. %p transport_state %x, t_state %x, "
3689 		    "se_cmd_flags %x\n", cmd, cmd->se_cmd.transport_state,
3690 		    cmd->se_cmd.t_state, cmd->se_cmd.se_cmd_flags);
3691 		return EIO;
3692 	}
3693 	cmd->aborted = 1;
3694 	cmd->trc_flags |= TRC_ABORT;
3695 	spin_unlock_irqrestore(&cmd->cmd_lock, flags);
3696 
3697 	qlt_send_term_exchange(cmd->qpair, cmd, &cmd->atio, 0, 1);
3698 	return 0;
3699 }
3700 EXPORT_SYMBOL(qlt_abort_cmd);
3701 
3702 void qlt_free_cmd(struct qla_tgt_cmd *cmd)
3703 {
3704 	struct fc_port *sess = cmd->sess;
3705 
3706 	ql_dbg(ql_dbg_tgt, cmd->vha, 0xe074,
3707 	    "%s: se_cmd[%p] ox_id %04x\n",
3708 	    __func__, &cmd->se_cmd,
3709 	    be16_to_cpu(cmd->atio.u.isp24.fcp_hdr.ox_id));
3710 
3711 	BUG_ON(cmd->cmd_in_wq);
3712 
3713 	if (cmd->sg_mapped)
3714 		qlt_unmap_sg(cmd->vha, cmd);
3715 
3716 	if (!cmd->q_full)
3717 		qlt_decr_num_pend_cmds(cmd->vha);
3718 
3719 	BUG_ON(cmd->sg_mapped);
3720 	cmd->jiffies_at_free = get_jiffies_64();
3721 	if (unlikely(cmd->free_sg))
3722 		kfree(cmd->sg);
3723 
3724 	if (!sess || !sess->se_sess) {
3725 		WARN_ON(1);
3726 		return;
3727 	}
3728 	cmd->jiffies_at_free = get_jiffies_64();
3729 	percpu_ida_free(&sess->se_sess->sess_tag_pool, cmd->se_cmd.map_tag);
3730 }
3731 EXPORT_SYMBOL(qlt_free_cmd);
3732 
3733 /*
3734  * ha->hardware_lock supposed to be held on entry. Might drop it, then reaquire
3735  */
3736 static int qlt_term_ctio_exchange(struct qla_qpair *qpair, void *ctio,
3737 	struct qla_tgt_cmd *cmd, uint32_t status)
3738 {
3739 	int term = 0;
3740 	struct scsi_qla_host *vha = qpair->vha;
3741 
3742 	if (cmd->se_cmd.prot_op)
3743 		ql_dbg(ql_dbg_tgt_dif, vha, 0xe013,
3744 		    "Term DIF cmd: lba[0x%llx|%lld] len[0x%x] "
3745 		    "se_cmd=%p tag[%x] op %#x/%s",
3746 		     cmd->lba, cmd->lba,
3747 		     cmd->num_blks, &cmd->se_cmd,
3748 		     cmd->atio.u.isp24.exchange_addr,
3749 		     cmd->se_cmd.prot_op,
3750 		     prot_op_str(cmd->se_cmd.prot_op));
3751 
3752 	if (ctio != NULL) {
3753 		struct ctio7_from_24xx *c = (struct ctio7_from_24xx *)ctio;
3754 		term = !(c->flags &
3755 		    cpu_to_le16(OF_TERM_EXCH));
3756 	} else
3757 		term = 1;
3758 
3759 	if (term)
3760 		qlt_send_term_exchange(qpair, cmd, &cmd->atio, 1, 0);
3761 
3762 	return term;
3763 }
3764 
3765 
3766 /* ha->hardware_lock supposed to be held on entry */
3767 static struct qla_tgt_cmd *qlt_ctio_to_cmd(struct scsi_qla_host *vha,
3768 	struct rsp_que *rsp, uint32_t handle, void *ctio)
3769 {
3770 	struct qla_tgt_cmd *cmd = NULL;
3771 	struct req_que *req;
3772 	int qid = GET_QID(handle);
3773 	uint32_t h = handle & ~QLA_TGT_HANDLE_MASK;
3774 
3775 	if (unlikely(h == QLA_TGT_SKIP_HANDLE))
3776 		return NULL;
3777 
3778 	if (qid == rsp->req->id) {
3779 		req = rsp->req;
3780 	} else if (vha->hw->req_q_map[qid]) {
3781 		ql_dbg(ql_dbg_tgt_mgt, vha, 0x1000a,
3782 		    "qla_target(%d): CTIO completion with different QID %d handle %x\n",
3783 		    vha->vp_idx, rsp->id, handle);
3784 		req = vha->hw->req_q_map[qid];
3785 	} else {
3786 		return NULL;
3787 	}
3788 
3789 	h &= QLA_CMD_HANDLE_MASK;
3790 
3791 	if (h != QLA_TGT_NULL_HANDLE) {
3792 		if (unlikely(h >= req->num_outstanding_cmds)) {
3793 			ql_dbg(ql_dbg_tgt, vha, 0xe052,
3794 			    "qla_target(%d): Wrong handle %x received\n",
3795 			    vha->vp_idx, handle);
3796 			return NULL;
3797 		}
3798 
3799 		cmd = (struct qla_tgt_cmd *)req->outstanding_cmds[h];
3800 		if (unlikely(cmd == NULL)) {
3801 			ql_dbg(ql_dbg_async, vha, 0xe053,
3802 			    "qla_target(%d): Suspicious: unable to find the command with handle %x req->id %d rsp->id %d\n",
3803 				vha->vp_idx, handle, req->id, rsp->id);
3804 			return NULL;
3805 		}
3806 		req->outstanding_cmds[h] = NULL;
3807 	} else if (ctio != NULL) {
3808 		/* We can't get loop ID from CTIO7 */
3809 		ql_dbg(ql_dbg_tgt, vha, 0xe054,
3810 		    "qla_target(%d): Wrong CTIO received: QLA24xx doesn't "
3811 		    "support NULL handles\n", vha->vp_idx);
3812 		return NULL;
3813 	}
3814 
3815 	return cmd;
3816 }
3817 
3818 /* hardware_lock should be held by caller. */
3819 void
3820 qlt_abort_cmd_on_host_reset(struct scsi_qla_host *vha, struct qla_tgt_cmd *cmd)
3821 {
3822 	struct qla_hw_data *ha = vha->hw;
3823 
3824 	if (cmd->sg_mapped)
3825 		qlt_unmap_sg(vha, cmd);
3826 
3827 	/* TODO: fix debug message type and ids. */
3828 	if (cmd->state == QLA_TGT_STATE_PROCESSED) {
3829 		ql_dbg(ql_dbg_io, vha, 0xff00,
3830 		    "HOST-ABORT: state=PROCESSED.\n");
3831 	} else if (cmd->state == QLA_TGT_STATE_NEED_DATA) {
3832 		cmd->write_data_transferred = 0;
3833 		cmd->state = QLA_TGT_STATE_DATA_IN;
3834 
3835 		ql_dbg(ql_dbg_io, vha, 0xff01,
3836 		    "HOST-ABORT: state=DATA_IN.\n");
3837 
3838 		ha->tgt.tgt_ops->handle_data(cmd);
3839 		return;
3840 	} else {
3841 		ql_dbg(ql_dbg_io, vha, 0xff03,
3842 		    "HOST-ABORT: state=BAD(%d).\n",
3843 		    cmd->state);
3844 		dump_stack();
3845 	}
3846 
3847 	cmd->trc_flags |= TRC_FLUSH;
3848 	ha->tgt.tgt_ops->free_cmd(cmd);
3849 }
3850 
3851 /*
3852  * ha->hardware_lock supposed to be held on entry. Might drop it, then reaquire
3853  */
3854 static void qlt_do_ctio_completion(struct scsi_qla_host *vha,
3855     struct rsp_que *rsp, uint32_t handle, uint32_t status, void *ctio)
3856 {
3857 	struct qla_hw_data *ha = vha->hw;
3858 	struct se_cmd *se_cmd;
3859 	struct qla_tgt_cmd *cmd;
3860 	struct qla_qpair *qpair = rsp->qpair;
3861 
3862 	if (handle & CTIO_INTERMEDIATE_HANDLE_MARK) {
3863 		/* That could happen only in case of an error/reset/abort */
3864 		if (status != CTIO_SUCCESS) {
3865 			ql_dbg(ql_dbg_tgt_mgt, vha, 0xf01d,
3866 			    "Intermediate CTIO received"
3867 			    " (status %x)\n", status);
3868 		}
3869 		return;
3870 	}
3871 
3872 	cmd = qlt_ctio_to_cmd(vha, rsp, handle, ctio);
3873 	if (cmd == NULL)
3874 		return;
3875 
3876 	se_cmd = &cmd->se_cmd;
3877 	cmd->cmd_sent_to_fw = 0;
3878 
3879 	qlt_unmap_sg(vha, cmd);
3880 
3881 	if (unlikely(status != CTIO_SUCCESS)) {
3882 		switch (status & 0xFFFF) {
3883 		case CTIO_LIP_RESET:
3884 		case CTIO_TARGET_RESET:
3885 		case CTIO_ABORTED:
3886 			/* driver request abort via Terminate exchange */
3887 		case CTIO_TIMEOUT:
3888 		case CTIO_INVALID_RX_ID:
3889 			/* They are OK */
3890 			ql_dbg(ql_dbg_tgt_mgt, vha, 0xf058,
3891 			    "qla_target(%d): CTIO with "
3892 			    "status %#x received, state %x, se_cmd %p, "
3893 			    "(LIP_RESET=e, ABORTED=2, TARGET_RESET=17, "
3894 			    "TIMEOUT=b, INVALID_RX_ID=8)\n", vha->vp_idx,
3895 			    status, cmd->state, se_cmd);
3896 			break;
3897 
3898 		case CTIO_PORT_LOGGED_OUT:
3899 		case CTIO_PORT_UNAVAILABLE:
3900 		{
3901 			int logged_out =
3902 				(status & 0xFFFF) == CTIO_PORT_LOGGED_OUT;
3903 
3904 			ql_dbg(ql_dbg_tgt_mgt, vha, 0xf059,
3905 			    "qla_target(%d): CTIO with %s status %x "
3906 			    "received (state %x, se_cmd %p)\n", vha->vp_idx,
3907 			    logged_out ? "PORT LOGGED OUT" : "PORT UNAVAILABLE",
3908 			    status, cmd->state, se_cmd);
3909 
3910 			if (logged_out && cmd->sess) {
3911 				/*
3912 				 * Session is already logged out, but we need
3913 				 * to notify initiator, who's not aware of this
3914 				 */
3915 				cmd->sess->logout_on_delete = 0;
3916 				cmd->sess->send_els_logo = 1;
3917 				ql_dbg(ql_dbg_disc, vha, 0x20f8,
3918 				    "%s %d %8phC post del sess\n",
3919 				    __func__, __LINE__, cmd->sess->port_name);
3920 
3921 				qlt_schedule_sess_for_deletion(cmd->sess);
3922 			}
3923 			break;
3924 		}
3925 		case CTIO_DIF_ERROR: {
3926 			struct ctio_crc_from_fw *crc =
3927 				(struct ctio_crc_from_fw *)ctio;
3928 			ql_dbg(ql_dbg_tgt_mgt, vha, 0xf073,
3929 			    "qla_target(%d): CTIO with DIF_ERROR status %x "
3930 			    "received (state %x, ulp_cmd %p) actual_dif[0x%llx] "
3931 			    "expect_dif[0x%llx]\n",
3932 			    vha->vp_idx, status, cmd->state, se_cmd,
3933 			    *((u64 *)&crc->actual_dif[0]),
3934 			    *((u64 *)&crc->expected_dif[0]));
3935 
3936 			qlt_handle_dif_error(qpair, cmd, ctio);
3937 			return;
3938 		}
3939 		default:
3940 			ql_dbg(ql_dbg_tgt_mgt, vha, 0xf05b,
3941 			    "qla_target(%d): CTIO with error status 0x%x received (state %x, se_cmd %p\n",
3942 			    vha->vp_idx, status, cmd->state, se_cmd);
3943 			break;
3944 		}
3945 
3946 
3947 		/* "cmd->aborted" means
3948 		 * cmd is already aborted/terminated, we don't
3949 		 * need to terminate again.  The exchange is already
3950 		 * cleaned up/freed at FW level.  Just cleanup at driver
3951 		 * level.
3952 		 */
3953 		if ((cmd->state != QLA_TGT_STATE_NEED_DATA) &&
3954 		    (!cmd->aborted)) {
3955 			cmd->trc_flags |= TRC_CTIO_ERR;
3956 			if (qlt_term_ctio_exchange(qpair, ctio, cmd, status))
3957 				return;
3958 		}
3959 	}
3960 
3961 	if (cmd->state == QLA_TGT_STATE_PROCESSED) {
3962 		cmd->trc_flags |= TRC_CTIO_DONE;
3963 	} else if (cmd->state == QLA_TGT_STATE_NEED_DATA) {
3964 		cmd->state = QLA_TGT_STATE_DATA_IN;
3965 
3966 		if (status == CTIO_SUCCESS)
3967 			cmd->write_data_transferred = 1;
3968 
3969 		ha->tgt.tgt_ops->handle_data(cmd);
3970 		return;
3971 	} else if (cmd->aborted) {
3972 		cmd->trc_flags |= TRC_CTIO_ABORTED;
3973 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf01e,
3974 		  "Aborted command %p (tag %lld) finished\n", cmd, se_cmd->tag);
3975 	} else {
3976 		cmd->trc_flags |= TRC_CTIO_STRANGE;
3977 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf05c,
3978 		    "qla_target(%d): A command in state (%d) should "
3979 		    "not return a CTIO complete\n", vha->vp_idx, cmd->state);
3980 	}
3981 
3982 	if (unlikely(status != CTIO_SUCCESS) &&
3983 		!cmd->aborted) {
3984 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf01f, "Finishing failed CTIO\n");
3985 		dump_stack();
3986 	}
3987 
3988 	ha->tgt.tgt_ops->free_cmd(cmd);
3989 }
3990 
3991 static inline int qlt_get_fcp_task_attr(struct scsi_qla_host *vha,
3992 	uint8_t task_codes)
3993 {
3994 	int fcp_task_attr;
3995 
3996 	switch (task_codes) {
3997 	case ATIO_SIMPLE_QUEUE:
3998 		fcp_task_attr = TCM_SIMPLE_TAG;
3999 		break;
4000 	case ATIO_HEAD_OF_QUEUE:
4001 		fcp_task_attr = TCM_HEAD_TAG;
4002 		break;
4003 	case ATIO_ORDERED_QUEUE:
4004 		fcp_task_attr = TCM_ORDERED_TAG;
4005 		break;
4006 	case ATIO_ACA_QUEUE:
4007 		fcp_task_attr = TCM_ACA_TAG;
4008 		break;
4009 	case ATIO_UNTAGGED:
4010 		fcp_task_attr = TCM_SIMPLE_TAG;
4011 		break;
4012 	default:
4013 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf05d,
4014 		    "qla_target: unknown task code %x, use ORDERED instead\n",
4015 		    task_codes);
4016 		fcp_task_attr = TCM_ORDERED_TAG;
4017 		break;
4018 	}
4019 
4020 	return fcp_task_attr;
4021 }
4022 
4023 static struct fc_port *qlt_make_local_sess(struct scsi_qla_host *,
4024 					uint8_t *);
4025 /*
4026  * Process context for I/O path into tcm_qla2xxx code
4027  */
4028 static void __qlt_do_work(struct qla_tgt_cmd *cmd)
4029 {
4030 	scsi_qla_host_t *vha = cmd->vha;
4031 	struct qla_hw_data *ha = vha->hw;
4032 	struct fc_port *sess = cmd->sess;
4033 	struct atio_from_isp *atio = &cmd->atio;
4034 	unsigned char *cdb;
4035 	unsigned long flags;
4036 	uint32_t data_length;
4037 	int ret, fcp_task_attr, data_dir, bidi = 0;
4038 	struct qla_qpair *qpair = cmd->qpair;
4039 
4040 	cmd->cmd_in_wq = 0;
4041 	cmd->trc_flags |= TRC_DO_WORK;
4042 
4043 	if (cmd->aborted) {
4044 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf082,
4045 		    "cmd with tag %u is aborted\n",
4046 		    cmd->atio.u.isp24.exchange_addr);
4047 		goto out_term;
4048 	}
4049 
4050 	spin_lock_init(&cmd->cmd_lock);
4051 	cdb = &atio->u.isp24.fcp_cmnd.cdb[0];
4052 	cmd->se_cmd.tag = atio->u.isp24.exchange_addr;
4053 
4054 	if (atio->u.isp24.fcp_cmnd.rddata &&
4055 	    atio->u.isp24.fcp_cmnd.wrdata) {
4056 		bidi = 1;
4057 		data_dir = DMA_TO_DEVICE;
4058 	} else if (atio->u.isp24.fcp_cmnd.rddata)
4059 		data_dir = DMA_FROM_DEVICE;
4060 	else if (atio->u.isp24.fcp_cmnd.wrdata)
4061 		data_dir = DMA_TO_DEVICE;
4062 	else
4063 		data_dir = DMA_NONE;
4064 
4065 	fcp_task_attr = qlt_get_fcp_task_attr(vha,
4066 	    atio->u.isp24.fcp_cmnd.task_attr);
4067 	data_length = be32_to_cpu(get_unaligned((uint32_t *)
4068 	    &atio->u.isp24.fcp_cmnd.add_cdb[
4069 	    atio->u.isp24.fcp_cmnd.add_cdb_len]));
4070 
4071 	ret = ha->tgt.tgt_ops->handle_cmd(vha, cmd, cdb, data_length,
4072 				          fcp_task_attr, data_dir, bidi);
4073 	if (ret != 0)
4074 		goto out_term;
4075 	/*
4076 	 * Drop extra session reference from qla_tgt_handle_cmd_for_atio*(
4077 	 */
4078 	spin_lock_irqsave(&ha->tgt.sess_lock, flags);
4079 	ha->tgt.tgt_ops->put_sess(sess);
4080 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
4081 	return;
4082 
4083 out_term:
4084 	ql_dbg(ql_dbg_io, vha, 0x3060, "Terminating work cmd %p", cmd);
4085 	/*
4086 	 * cmd has not sent to target yet, so pass NULL as the second
4087 	 * argument to qlt_send_term_exchange() and free the memory here.
4088 	 */
4089 	cmd->trc_flags |= TRC_DO_WORK_ERR;
4090 	spin_lock_irqsave(qpair->qp_lock_ptr, flags);
4091 	qlt_send_term_exchange(qpair, NULL, &cmd->atio, 1, 0);
4092 
4093 	qlt_decr_num_pend_cmds(vha);
4094 	percpu_ida_free(&sess->se_sess->sess_tag_pool, cmd->se_cmd.map_tag);
4095 	spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
4096 
4097 	spin_lock_irqsave(&ha->tgt.sess_lock, flags);
4098 	ha->tgt.tgt_ops->put_sess(sess);
4099 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
4100 }
4101 
4102 static void qlt_do_work(struct work_struct *work)
4103 {
4104 	struct qla_tgt_cmd *cmd = container_of(work, struct qla_tgt_cmd, work);
4105 	scsi_qla_host_t *vha = cmd->vha;
4106 	unsigned long flags;
4107 
4108 	spin_lock_irqsave(&vha->cmd_list_lock, flags);
4109 	list_del(&cmd->cmd_list);
4110 	spin_unlock_irqrestore(&vha->cmd_list_lock, flags);
4111 
4112 	__qlt_do_work(cmd);
4113 }
4114 
4115 void qlt_clr_qp_table(struct scsi_qla_host *vha)
4116 {
4117 	unsigned long flags;
4118 	struct qla_hw_data *ha = vha->hw;
4119 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
4120 	void *node;
4121 	u64 key = 0;
4122 
4123 	ql_log(ql_log_info, vha, 0x706c,
4124 	    "User update Number of Active Qpairs %d\n",
4125 	    ha->tgt.num_act_qpairs);
4126 
4127 	spin_lock_irqsave(&ha->tgt.atio_lock, flags);
4128 
4129 	btree_for_each_safe64(&tgt->lun_qpair_map, key, node)
4130 		btree_remove64(&tgt->lun_qpair_map, key);
4131 
4132 	ha->base_qpair->lun_cnt = 0;
4133 	for (key = 0; key < ha->max_qpairs; key++)
4134 		if (ha->queue_pair_map[key])
4135 			ha->queue_pair_map[key]->lun_cnt = 0;
4136 
4137 	spin_unlock_irqrestore(&ha->tgt.atio_lock, flags);
4138 }
4139 
4140 static void qlt_assign_qpair(struct scsi_qla_host *vha,
4141 	struct qla_tgt_cmd *cmd)
4142 {
4143 	struct qla_qpair *qpair, *qp;
4144 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
4145 	struct qla_qpair_hint *h;
4146 
4147 	if (vha->flags.qpairs_available) {
4148 		h = btree_lookup64(&tgt->lun_qpair_map, cmd->unpacked_lun);
4149 		if (unlikely(!h)) {
4150 			/* spread lun to qpair ratio evently */
4151 			int lcnt = 0, rc;
4152 			struct scsi_qla_host *base_vha =
4153 				pci_get_drvdata(vha->hw->pdev);
4154 
4155 			qpair = vha->hw->base_qpair;
4156 			if (qpair->lun_cnt == 0) {
4157 				qpair->lun_cnt++;
4158 				h = qla_qpair_to_hint(tgt, qpair);
4159 				BUG_ON(!h);
4160 				rc = btree_insert64(&tgt->lun_qpair_map,
4161 					cmd->unpacked_lun, h, GFP_ATOMIC);
4162 				if (rc) {
4163 					qpair->lun_cnt--;
4164 					ql_log(ql_log_info, vha, 0xd037,
4165 					    "Unable to insert lun %llx into lun_qpair_map\n",
4166 					    cmd->unpacked_lun);
4167 				}
4168 				goto out;
4169 			} else {
4170 				lcnt = qpair->lun_cnt;
4171 			}
4172 
4173 			h = NULL;
4174 			list_for_each_entry(qp, &base_vha->qp_list,
4175 			    qp_list_elem) {
4176 				if (qp->lun_cnt == 0) {
4177 					qp->lun_cnt++;
4178 					h = qla_qpair_to_hint(tgt, qp);
4179 					BUG_ON(!h);
4180 					rc = btree_insert64(&tgt->lun_qpair_map,
4181 					    cmd->unpacked_lun, h, GFP_ATOMIC);
4182 					if (rc) {
4183 						qp->lun_cnt--;
4184 						ql_log(ql_log_info, vha, 0xd038,
4185 							"Unable to insert lun %llx into lun_qpair_map\n",
4186 							cmd->unpacked_lun);
4187 					}
4188 					qpair = qp;
4189 					goto out;
4190 				} else {
4191 					if (qp->lun_cnt < lcnt) {
4192 						lcnt = qp->lun_cnt;
4193 						qpair = qp;
4194 						continue;
4195 					}
4196 				}
4197 			}
4198 			BUG_ON(!qpair);
4199 			qpair->lun_cnt++;
4200 			h = qla_qpair_to_hint(tgt, qpair);
4201 			BUG_ON(!h);
4202 			rc = btree_insert64(&tgt->lun_qpair_map,
4203 				cmd->unpacked_lun, h, GFP_ATOMIC);
4204 			if (rc) {
4205 				qpair->lun_cnt--;
4206 				ql_log(ql_log_info, vha, 0xd039,
4207 				   "Unable to insert lun %llx into lun_qpair_map\n",
4208 				   cmd->unpacked_lun);
4209 			}
4210 		}
4211 	} else {
4212 		h = &tgt->qphints[0];
4213 	}
4214 out:
4215 	cmd->qpair = h->qpair;
4216 	cmd->se_cmd.cpuid = h->cpuid;
4217 }
4218 
4219 static struct qla_tgt_cmd *qlt_get_tag(scsi_qla_host_t *vha,
4220 				       struct fc_port *sess,
4221 				       struct atio_from_isp *atio)
4222 {
4223 	struct se_session *se_sess = sess->se_sess;
4224 	struct qla_tgt_cmd *cmd;
4225 	int tag;
4226 
4227 	tag = percpu_ida_alloc(&se_sess->sess_tag_pool, TASK_RUNNING);
4228 	if (tag < 0)
4229 		return NULL;
4230 
4231 	cmd = &((struct qla_tgt_cmd *)se_sess->sess_cmd_map)[tag];
4232 	memset(cmd, 0, sizeof(struct qla_tgt_cmd));
4233 	cmd->cmd_type = TYPE_TGT_CMD;
4234 	memcpy(&cmd->atio, atio, sizeof(*atio));
4235 	cmd->state = QLA_TGT_STATE_NEW;
4236 	cmd->tgt = vha->vha_tgt.qla_tgt;
4237 	qlt_incr_num_pend_cmds(vha);
4238 	cmd->vha = vha;
4239 	cmd->se_cmd.map_tag = tag;
4240 	cmd->sess = sess;
4241 	cmd->loop_id = sess->loop_id;
4242 	cmd->conf_compl_supported = sess->conf_compl_supported;
4243 
4244 	cmd->trc_flags = 0;
4245 	cmd->jiffies_at_alloc = get_jiffies_64();
4246 
4247 	cmd->unpacked_lun = scsilun_to_int(
4248 	    (struct scsi_lun *)&atio->u.isp24.fcp_cmnd.lun);
4249 	qlt_assign_qpair(vha, cmd);
4250 	cmd->reset_count = vha->hw->base_qpair->chip_reset;
4251 	cmd->vp_idx = vha->vp_idx;
4252 
4253 	return cmd;
4254 }
4255 
4256 /* ha->hardware_lock supposed to be held on entry */
4257 static int qlt_handle_cmd_for_atio(struct scsi_qla_host *vha,
4258 	struct atio_from_isp *atio)
4259 {
4260 	struct qla_hw_data *ha = vha->hw;
4261 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
4262 	struct fc_port *sess;
4263 	struct qla_tgt_cmd *cmd;
4264 	unsigned long flags;
4265 	port_id_t id;
4266 
4267 	if (unlikely(tgt->tgt_stop)) {
4268 		ql_dbg(ql_dbg_io, vha, 0x3061,
4269 		    "New command while device %p is shutting down\n", tgt);
4270 		return -ENODEV;
4271 	}
4272 
4273 	id.b.al_pa = atio->u.isp24.fcp_hdr.s_id[2];
4274 	id.b.area = atio->u.isp24.fcp_hdr.s_id[1];
4275 	id.b.domain = atio->u.isp24.fcp_hdr.s_id[0];
4276 	if (IS_SW_RESV_ADDR(id))
4277 		return -EBUSY;
4278 
4279 	sess = ha->tgt.tgt_ops->find_sess_by_s_id(vha, atio->u.isp24.fcp_hdr.s_id);
4280 	if (unlikely(!sess))
4281 		return -EFAULT;
4282 
4283 	/* Another WWN used to have our s_id. Our PLOGI scheduled its
4284 	 * session deletion, but it's still in sess_del_work wq */
4285 	if (sess->deleted) {
4286 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf002,
4287 		    "New command while old session %p is being deleted\n",
4288 		    sess);
4289 		return -EFAULT;
4290 	}
4291 
4292 	/*
4293 	 * Do kref_get() before returning + dropping qla_hw_data->hardware_lock.
4294 	 */
4295 	if (!kref_get_unless_zero(&sess->sess_kref)) {
4296 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf004,
4297 		    "%s: kref_get fail, %8phC oxid %x \n",
4298 		    __func__, sess->port_name,
4299 		     be16_to_cpu(atio->u.isp24.fcp_hdr.ox_id));
4300 		return -EFAULT;
4301 	}
4302 
4303 	cmd = qlt_get_tag(vha, sess, atio);
4304 	if (!cmd) {
4305 		ql_dbg(ql_dbg_io, vha, 0x3062,
4306 		    "qla_target(%d): Allocation of cmd failed\n", vha->vp_idx);
4307 		spin_lock_irqsave(&ha->tgt.sess_lock, flags);
4308 		ha->tgt.tgt_ops->put_sess(sess);
4309 		spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
4310 		return -EBUSY;
4311 	}
4312 
4313 	cmd->cmd_in_wq = 1;
4314 	cmd->trc_flags |= TRC_NEW_CMD;
4315 
4316 	spin_lock_irqsave(&vha->cmd_list_lock, flags);
4317 	list_add_tail(&cmd->cmd_list, &vha->qla_cmd_list);
4318 	spin_unlock_irqrestore(&vha->cmd_list_lock, flags);
4319 
4320 	INIT_WORK(&cmd->work, qlt_do_work);
4321 	if (vha->flags.qpairs_available) {
4322 		queue_work_on(cmd->se_cmd.cpuid, qla_tgt_wq, &cmd->work);
4323 	} else if (ha->msix_count) {
4324 		if (cmd->atio.u.isp24.fcp_cmnd.rddata)
4325 			queue_work_on(smp_processor_id(), qla_tgt_wq,
4326 			    &cmd->work);
4327 		else
4328 			queue_work_on(cmd->se_cmd.cpuid, qla_tgt_wq,
4329 			    &cmd->work);
4330 	} else {
4331 		queue_work(qla_tgt_wq, &cmd->work);
4332 	}
4333 
4334 	return 0;
4335 }
4336 
4337 /* ha->hardware_lock supposed to be held on entry */
4338 static int qlt_issue_task_mgmt(struct fc_port *sess, u64 lun,
4339 	int fn, void *iocb, int flags)
4340 {
4341 	struct scsi_qla_host *vha = sess->vha;
4342 	struct qla_hw_data *ha = vha->hw;
4343 	struct qla_tgt_mgmt_cmd *mcmd;
4344 	struct atio_from_isp *a = (struct atio_from_isp *)iocb;
4345 	int res;
4346 
4347 	mcmd = mempool_alloc(qla_tgt_mgmt_cmd_mempool, GFP_ATOMIC);
4348 	if (!mcmd) {
4349 		ql_dbg(ql_dbg_tgt_tmr, vha, 0x10009,
4350 		    "qla_target(%d): Allocation of management "
4351 		    "command failed, some commands and their data could "
4352 		    "leak\n", vha->vp_idx);
4353 		return -ENOMEM;
4354 	}
4355 	memset(mcmd, 0, sizeof(*mcmd));
4356 	mcmd->sess = sess;
4357 
4358 	if (iocb) {
4359 		memcpy(&mcmd->orig_iocb.imm_ntfy, iocb,
4360 		    sizeof(mcmd->orig_iocb.imm_ntfy));
4361 	}
4362 	mcmd->tmr_func = fn;
4363 	mcmd->flags = flags;
4364 	mcmd->reset_count = ha->base_qpair->chip_reset;
4365 	mcmd->qpair = ha->base_qpair;
4366 	mcmd->vha = vha;
4367 
4368 	switch (fn) {
4369 	case QLA_TGT_LUN_RESET:
4370 	    abort_cmds_for_lun(vha, lun, a->u.isp24.fcp_hdr.s_id);
4371 	    break;
4372 	}
4373 
4374 	res = ha->tgt.tgt_ops->handle_tmr(mcmd, lun, mcmd->tmr_func, 0);
4375 	if (res != 0) {
4376 		ql_dbg(ql_dbg_tgt_tmr, vha, 0x1000b,
4377 		    "qla_target(%d): tgt.tgt_ops->handle_tmr() failed: %d\n",
4378 		    sess->vha->vp_idx, res);
4379 		mempool_free(mcmd, qla_tgt_mgmt_cmd_mempool);
4380 		return -EFAULT;
4381 	}
4382 
4383 	return 0;
4384 }
4385 
4386 /* ha->hardware_lock supposed to be held on entry */
4387 static int qlt_handle_task_mgmt(struct scsi_qla_host *vha, void *iocb)
4388 {
4389 	struct atio_from_isp *a = (struct atio_from_isp *)iocb;
4390 	struct qla_hw_data *ha = vha->hw;
4391 	struct fc_port *sess;
4392 	u64 unpacked_lun;
4393 	int fn;
4394 	unsigned long flags;
4395 
4396 	fn = a->u.isp24.fcp_cmnd.task_mgmt_flags;
4397 
4398 	spin_lock_irqsave(&ha->tgt.sess_lock, flags);
4399 	sess = ha->tgt.tgt_ops->find_sess_by_s_id(vha,
4400 	    a->u.isp24.fcp_hdr.s_id);
4401 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
4402 
4403 	unpacked_lun =
4404 	    scsilun_to_int((struct scsi_lun *)&a->u.isp24.fcp_cmnd.lun);
4405 
4406 	if (sess == NULL || sess->deleted)
4407 		return -EFAULT;
4408 
4409 	return qlt_issue_task_mgmt(sess, unpacked_lun, fn, iocb, 0);
4410 }
4411 
4412 /* ha->hardware_lock supposed to be held on entry */
4413 static int __qlt_abort_task(struct scsi_qla_host *vha,
4414 	struct imm_ntfy_from_isp *iocb, struct fc_port *sess)
4415 {
4416 	struct atio_from_isp *a = (struct atio_from_isp *)iocb;
4417 	struct qla_hw_data *ha = vha->hw;
4418 	struct qla_tgt_mgmt_cmd *mcmd;
4419 	u64 unpacked_lun;
4420 	int rc;
4421 
4422 	mcmd = mempool_alloc(qla_tgt_mgmt_cmd_mempool, GFP_ATOMIC);
4423 	if (mcmd == NULL) {
4424 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf05f,
4425 		    "qla_target(%d): %s: Allocation of ABORT cmd failed\n",
4426 		    vha->vp_idx, __func__);
4427 		return -ENOMEM;
4428 	}
4429 	memset(mcmd, 0, sizeof(*mcmd));
4430 
4431 	mcmd->sess = sess;
4432 	memcpy(&mcmd->orig_iocb.imm_ntfy, iocb,
4433 	    sizeof(mcmd->orig_iocb.imm_ntfy));
4434 
4435 	unpacked_lun =
4436 	    scsilun_to_int((struct scsi_lun *)&a->u.isp24.fcp_cmnd.lun);
4437 	mcmd->reset_count = ha->base_qpair->chip_reset;
4438 	mcmd->tmr_func = QLA_TGT_2G_ABORT_TASK;
4439 	mcmd->qpair = ha->base_qpair;
4440 
4441 	rc = ha->tgt.tgt_ops->handle_tmr(mcmd, unpacked_lun, mcmd->tmr_func,
4442 	    le16_to_cpu(iocb->u.isp2x.seq_id));
4443 	if (rc != 0) {
4444 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf060,
4445 		    "qla_target(%d): tgt_ops->handle_tmr() failed: %d\n",
4446 		    vha->vp_idx, rc);
4447 		mempool_free(mcmd, qla_tgt_mgmt_cmd_mempool);
4448 		return -EFAULT;
4449 	}
4450 
4451 	return 0;
4452 }
4453 
4454 /* ha->hardware_lock supposed to be held on entry */
4455 static int qlt_abort_task(struct scsi_qla_host *vha,
4456 	struct imm_ntfy_from_isp *iocb)
4457 {
4458 	struct qla_hw_data *ha = vha->hw;
4459 	struct fc_port *sess;
4460 	int loop_id;
4461 	unsigned long flags;
4462 
4463 	loop_id = GET_TARGET_ID(ha, (struct atio_from_isp *)iocb);
4464 
4465 	spin_lock_irqsave(&ha->tgt.sess_lock, flags);
4466 	sess = ha->tgt.tgt_ops->find_sess_by_loop_id(vha, loop_id);
4467 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
4468 
4469 	if (sess == NULL) {
4470 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf025,
4471 		    "qla_target(%d): task abort for unexisting "
4472 		    "session\n", vha->vp_idx);
4473 		return qlt_sched_sess_work(vha->vha_tgt.qla_tgt,
4474 		    QLA_TGT_SESS_WORK_ABORT, iocb, sizeof(*iocb));
4475 	}
4476 
4477 	return __qlt_abort_task(vha, iocb, sess);
4478 }
4479 
4480 void qlt_logo_completion_handler(fc_port_t *fcport, int rc)
4481 {
4482 	if (rc != MBS_COMMAND_COMPLETE) {
4483 		ql_dbg(ql_dbg_tgt_mgt, fcport->vha, 0xf093,
4484 			"%s: se_sess %p / sess %p from"
4485 			" port %8phC loop_id %#04x s_id %02x:%02x:%02x"
4486 			" LOGO failed: %#x\n",
4487 			__func__,
4488 			fcport->se_sess,
4489 			fcport,
4490 			fcport->port_name, fcport->loop_id,
4491 			fcport->d_id.b.domain, fcport->d_id.b.area,
4492 			fcport->d_id.b.al_pa, rc);
4493 	}
4494 
4495 	fcport->logout_completed = 1;
4496 }
4497 
4498 /*
4499 * ha->hardware_lock supposed to be held on entry (to protect tgt->sess_list)
4500 *
4501 * Schedules sessions with matching port_id/loop_id but different wwn for
4502 * deletion. Returns existing session with matching wwn if present.
4503 * Null otherwise.
4504 */
4505 struct fc_port *
4506 qlt_find_sess_invalidate_other(scsi_qla_host_t *vha, uint64_t wwn,
4507     port_id_t port_id, uint16_t loop_id, struct fc_port **conflict_sess)
4508 {
4509 	struct fc_port *sess = NULL, *other_sess;
4510 	uint64_t other_wwn;
4511 
4512 	*conflict_sess = NULL;
4513 
4514 	list_for_each_entry(other_sess, &vha->vp_fcports, list) {
4515 
4516 		other_wwn = wwn_to_u64(other_sess->port_name);
4517 
4518 		if (wwn == other_wwn) {
4519 			WARN_ON(sess);
4520 			sess = other_sess;
4521 			continue;
4522 		}
4523 
4524 		/* find other sess with nport_id collision */
4525 		if (port_id.b24 == other_sess->d_id.b24) {
4526 			if (loop_id != other_sess->loop_id) {
4527 				ql_dbg(ql_dbg_tgt_tmr, vha, 0x1000c,
4528 				    "Invalidating sess %p loop_id %d wwn %llx.\n",
4529 				    other_sess, other_sess->loop_id, other_wwn);
4530 
4531 				/*
4532 				 * logout_on_delete is set by default, but another
4533 				 * session that has the same s_id/loop_id combo
4534 				 * might have cleared it when requested this session
4535 				 * deletion, so don't touch it
4536 				 */
4537 				qlt_schedule_sess_for_deletion(other_sess);
4538 			} else {
4539 				/*
4540 				 * Another wwn used to have our s_id/loop_id
4541 				 * kill the session, but don't free the loop_id
4542 				 */
4543 				ql_dbg(ql_dbg_tgt_tmr, vha, 0xf01b,
4544 				    "Invalidating sess %p loop_id %d wwn %llx.\n",
4545 				    other_sess, other_sess->loop_id, other_wwn);
4546 
4547 				other_sess->keep_nport_handle = 1;
4548 				if (other_sess->disc_state != DSC_DELETED)
4549 					*conflict_sess = other_sess;
4550 				qlt_schedule_sess_for_deletion(other_sess);
4551 			}
4552 			continue;
4553 		}
4554 
4555 		/* find other sess with nport handle collision */
4556 		if ((loop_id == other_sess->loop_id) &&
4557 			(loop_id != FC_NO_LOOP_ID)) {
4558 			ql_dbg(ql_dbg_tgt_tmr, vha, 0x1000d,
4559 			       "Invalidating sess %p loop_id %d wwn %llx.\n",
4560 			       other_sess, other_sess->loop_id, other_wwn);
4561 
4562 			/* Same loop_id but different s_id
4563 			 * Ok to kill and logout */
4564 			qlt_schedule_sess_for_deletion(other_sess);
4565 		}
4566 	}
4567 
4568 	return sess;
4569 }
4570 
4571 /* Abort any commands for this s_id waiting on qla_tgt_wq workqueue */
4572 static int abort_cmds_for_s_id(struct scsi_qla_host *vha, port_id_t *s_id)
4573 {
4574 	struct qla_tgt_sess_op *op;
4575 	struct qla_tgt_cmd *cmd;
4576 	uint32_t key;
4577 	int count = 0;
4578 	unsigned long flags;
4579 
4580 	key = (((u32)s_id->b.domain << 16) |
4581 	       ((u32)s_id->b.area   <<  8) |
4582 	       ((u32)s_id->b.al_pa));
4583 
4584 	spin_lock_irqsave(&vha->cmd_list_lock, flags);
4585 	list_for_each_entry(op, &vha->qla_sess_op_cmd_list, cmd_list) {
4586 		uint32_t op_key = sid_to_key(op->atio.u.isp24.fcp_hdr.s_id);
4587 
4588 		if (op_key == key) {
4589 			op->aborted = true;
4590 			count++;
4591 		}
4592 	}
4593 
4594 	list_for_each_entry(op, &vha->unknown_atio_list, cmd_list) {
4595 		uint32_t op_key = sid_to_key(op->atio.u.isp24.fcp_hdr.s_id);
4596 		if (op_key == key) {
4597 			op->aborted = true;
4598 			count++;
4599 		}
4600 	}
4601 
4602 	list_for_each_entry(cmd, &vha->qla_cmd_list, cmd_list) {
4603 		uint32_t cmd_key = sid_to_key(cmd->atio.u.isp24.fcp_hdr.s_id);
4604 		if (cmd_key == key) {
4605 			cmd->aborted = 1;
4606 			count++;
4607 		}
4608 	}
4609 	spin_unlock_irqrestore(&vha->cmd_list_lock, flags);
4610 
4611 	return count;
4612 }
4613 
4614 static int qlt_handle_login(struct scsi_qla_host *vha,
4615     struct imm_ntfy_from_isp *iocb)
4616 {
4617 	struct fc_port *sess = NULL, *conflict_sess = NULL;
4618 	uint64_t wwn;
4619 	port_id_t port_id;
4620 	uint16_t loop_id, wd3_lo;
4621 	int res = 0;
4622 	struct qlt_plogi_ack_t *pla;
4623 	unsigned long flags;
4624 
4625 	wwn = wwn_to_u64(iocb->u.isp24.port_name);
4626 
4627 	port_id.b.domain = iocb->u.isp24.port_id[2];
4628 	port_id.b.area   = iocb->u.isp24.port_id[1];
4629 	port_id.b.al_pa  = iocb->u.isp24.port_id[0];
4630 	port_id.b.rsvd_1 = 0;
4631 
4632 	loop_id = le16_to_cpu(iocb->u.isp24.nport_handle);
4633 
4634 	/* Mark all stale commands sitting in qla_tgt_wq for deletion */
4635 	abort_cmds_for_s_id(vha, &port_id);
4636 
4637 	if (wwn) {
4638 		spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
4639 		sess = qlt_find_sess_invalidate_other(vha, wwn,
4640 		    port_id, loop_id, &conflict_sess);
4641 		spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
4642 	}
4643 
4644 	if (IS_SW_RESV_ADDR(port_id)) {
4645 		res = 1;
4646 		goto out;
4647 	}
4648 
4649 	pla = qlt_plogi_ack_find_add(vha, &port_id, iocb);
4650 	if (!pla) {
4651 		qlt_send_term_imm_notif(vha, iocb, 1);
4652 		goto out;
4653 	}
4654 
4655 	if (conflict_sess) {
4656 		conflict_sess->login_gen++;
4657 		qlt_plogi_ack_link(vha, pla, conflict_sess,
4658 		    QLT_PLOGI_LINK_CONFLICT);
4659 	}
4660 
4661 	if (!sess) {
4662 		pla->ref_count++;
4663 		ql_dbg(ql_dbg_disc, vha, 0xffff,
4664 		    "%s %d %8phC post new sess\n",
4665 		    __func__, __LINE__, iocb->u.isp24.port_name);
4666 		if (iocb->u.isp24.status_subcode == ELS_PLOGI)
4667 			qla24xx_post_newsess_work(vha, &port_id,
4668 			    iocb->u.isp24.port_name,
4669 			    iocb->u.isp24.u.plogi.node_name,
4670 			    pla, FC4_TYPE_UNKNOWN);
4671 		else
4672 			qla24xx_post_newsess_work(vha, &port_id,
4673 			    iocb->u.isp24.port_name, NULL,
4674 			    pla, FC4_TYPE_UNKNOWN);
4675 
4676 		goto out;
4677 	}
4678 
4679 	qlt_plogi_ack_link(vha, pla, sess, QLT_PLOGI_LINK_SAME_WWN);
4680 	sess->d_id = port_id;
4681 	sess->login_gen++;
4682 
4683 	if (iocb->u.isp24.status_subcode == ELS_PRLI) {
4684 		sess->fw_login_state = DSC_LS_PRLI_PEND;
4685 		sess->local = 0;
4686 		sess->loop_id = loop_id;
4687 		sess->d_id = port_id;
4688 		sess->fw_login_state = DSC_LS_PRLI_PEND;
4689 		wd3_lo = le16_to_cpu(iocb->u.isp24.u.prli.wd3_lo);
4690 
4691 		if (wd3_lo & BIT_7)
4692 			sess->conf_compl_supported = 1;
4693 
4694 		if ((wd3_lo & BIT_4) == 0)
4695 			sess->port_type = FCT_INITIATOR;
4696 		else
4697 			sess->port_type = FCT_TARGET;
4698 
4699 	} else
4700 		sess->fw_login_state = DSC_LS_PLOGI_PEND;
4701 
4702 
4703 	ql_dbg(ql_dbg_disc, vha, 0x20f9,
4704 	    "%s %d %8phC  DS %d\n",
4705 	    __func__, __LINE__, sess->port_name, sess->disc_state);
4706 
4707 	switch (sess->disc_state) {
4708 	case DSC_DELETED:
4709 		qlt_plogi_ack_unref(vha, pla);
4710 		break;
4711 
4712 	default:
4713 		/*
4714 		 * Under normal circumstances we want to release nport handle
4715 		 * during LOGO process to avoid nport handle leaks inside FW.
4716 		 * The exception is when LOGO is done while another PLOGI with
4717 		 * the same nport handle is waiting as might be the case here.
4718 		 * Note: there is always a possibily of a race where session
4719 		 * deletion has already started for other reasons (e.g. ACL
4720 		 * removal) and now PLOGI arrives:
4721 		 * 1. if PLOGI arrived in FW after nport handle has been freed,
4722 		 *    FW must have assigned this PLOGI a new/same handle and we
4723 		 *    can proceed ACK'ing it as usual when session deletion
4724 		 *    completes.
4725 		 * 2. if PLOGI arrived in FW before LOGO with LCF_FREE_NPORT
4726 		 *    bit reached it, the handle has now been released. We'll
4727 		 *    get an error when we ACK this PLOGI. Nothing will be sent
4728 		 *    back to initiator. Initiator should eventually retry
4729 		 *    PLOGI and situation will correct itself.
4730 		 */
4731 		sess->keep_nport_handle = ((sess->loop_id == loop_id) &&
4732 		    (sess->d_id.b24 == port_id.b24));
4733 
4734 		ql_dbg(ql_dbg_disc, vha, 0x20f9,
4735 		    "%s %d %8phC post del sess\n",
4736 		    __func__, __LINE__, sess->port_name);
4737 
4738 
4739 		qlt_schedule_sess_for_deletion(sess);
4740 		break;
4741 	}
4742 out:
4743 	return res;
4744 }
4745 
4746 /*
4747  * ha->hardware_lock supposed to be held on entry. Might drop it, then reaquire
4748  */
4749 static int qlt_24xx_handle_els(struct scsi_qla_host *vha,
4750 	struct imm_ntfy_from_isp *iocb)
4751 {
4752 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
4753 	struct qla_hw_data *ha = vha->hw;
4754 	struct fc_port *sess = NULL, *conflict_sess = NULL;
4755 	uint64_t wwn;
4756 	port_id_t port_id;
4757 	uint16_t loop_id;
4758 	uint16_t wd3_lo;
4759 	int res = 0;
4760 	unsigned long flags;
4761 
4762 	wwn = wwn_to_u64(iocb->u.isp24.port_name);
4763 
4764 	port_id.b.domain = iocb->u.isp24.port_id[2];
4765 	port_id.b.area   = iocb->u.isp24.port_id[1];
4766 	port_id.b.al_pa  = iocb->u.isp24.port_id[0];
4767 	port_id.b.rsvd_1 = 0;
4768 
4769 	loop_id = le16_to_cpu(iocb->u.isp24.nport_handle);
4770 
4771 	ql_dbg(ql_dbg_disc, vha, 0xf026,
4772 	    "qla_target(%d): Port ID: %02x:%02x:%02x ELS opcode: 0x%02x lid %d %8phC\n",
4773 	    vha->vp_idx, iocb->u.isp24.port_id[2],
4774 		iocb->u.isp24.port_id[1], iocb->u.isp24.port_id[0],
4775 		   iocb->u.isp24.status_subcode, loop_id,
4776 		iocb->u.isp24.port_name);
4777 
4778 	/* res = 1 means ack at the end of thread
4779 	 * res = 0 means ack async/later.
4780 	 */
4781 	switch (iocb->u.isp24.status_subcode) {
4782 	case ELS_PLOGI:
4783 		res = qlt_handle_login(vha, iocb);
4784 		break;
4785 
4786 	case ELS_PRLI:
4787 		if (N2N_TOPO(ha)) {
4788 			sess = qla2x00_find_fcport_by_wwpn(vha,
4789 			    iocb->u.isp24.port_name, 1);
4790 
4791 			if (sess && sess->plogi_link[QLT_PLOGI_LINK_SAME_WWN]) {
4792 				ql_dbg(ql_dbg_disc, vha, 0xffff,
4793 				    "%s %d %8phC Term PRLI due to PLOGI ACK not completed\n",
4794 				    __func__, __LINE__,
4795 				    iocb->u.isp24.port_name);
4796 				qlt_send_term_imm_notif(vha, iocb, 1);
4797 				break;
4798 			}
4799 
4800 			res = qlt_handle_login(vha, iocb);
4801 			break;
4802 		}
4803 
4804 		if (IS_SW_RESV_ADDR(port_id)) {
4805 			res = 1;
4806 			break;
4807 		}
4808 
4809 		wd3_lo = le16_to_cpu(iocb->u.isp24.u.prli.wd3_lo);
4810 
4811 		if (wwn) {
4812 			spin_lock_irqsave(&tgt->ha->tgt.sess_lock, flags);
4813 			sess = qlt_find_sess_invalidate_other(vha, wwn, port_id,
4814 				loop_id, &conflict_sess);
4815 			spin_unlock_irqrestore(&tgt->ha->tgt.sess_lock, flags);
4816 		}
4817 
4818 		if (conflict_sess) {
4819 			switch (conflict_sess->disc_state) {
4820 			case DSC_DELETED:
4821 			case DSC_DELETE_PEND:
4822 				break;
4823 			default:
4824 				ql_dbg(ql_dbg_tgt_mgt, vha, 0xf09b,
4825 				    "PRLI with conflicting sess %p port %8phC\n",
4826 				    conflict_sess, conflict_sess->port_name);
4827 				conflict_sess->fw_login_state =
4828 				    DSC_LS_PORT_UNAVAIL;
4829 				qlt_send_term_imm_notif(vha, iocb, 1);
4830 				res = 0;
4831 				break;
4832 			}
4833 		}
4834 
4835 		if (sess != NULL) {
4836 			bool delete = false;
4837 			spin_lock_irqsave(&tgt->ha->tgt.sess_lock, flags);
4838 			switch (sess->fw_login_state) {
4839 			case DSC_LS_PLOGI_PEND:
4840 			case DSC_LS_PLOGI_COMP:
4841 			case DSC_LS_PRLI_COMP:
4842 				break;
4843 			default:
4844 				delete = true;
4845 				break;
4846 			}
4847 
4848 			switch (sess->disc_state) {
4849 			case DSC_LOGIN_PEND:
4850 			case DSC_GPDB:
4851 			case DSC_GPSC:
4852 			case DSC_UPD_FCPORT:
4853 			case DSC_LOGIN_COMPLETE:
4854 			case DSC_ADISC:
4855 				delete = false;
4856 				break;
4857 			default:
4858 				break;
4859 			}
4860 
4861 			if (delete) {
4862 				spin_unlock_irqrestore(&tgt->ha->tgt.sess_lock,
4863 				    flags);
4864 				/*
4865 				 * Impatient initiator sent PRLI before last
4866 				 * PLOGI could finish. Will force him to re-try,
4867 				 * while last one finishes.
4868 				 */
4869 				ql_log(ql_log_warn, sess->vha, 0xf095,
4870 				    "sess %p PRLI received, before plogi ack.\n",
4871 				    sess);
4872 				qlt_send_term_imm_notif(vha, iocb, 1);
4873 				res = 0;
4874 				break;
4875 			}
4876 
4877 			/*
4878 			 * This shouldn't happen under normal circumstances,
4879 			 * since we have deleted the old session during PLOGI
4880 			 */
4881 			ql_dbg(ql_dbg_tgt_mgt, vha, 0xf096,
4882 			    "PRLI (loop_id %#04x) for existing sess %p (loop_id %#04x)\n",
4883 			    sess->loop_id, sess, iocb->u.isp24.nport_handle);
4884 
4885 			sess->local = 0;
4886 			sess->loop_id = loop_id;
4887 			sess->d_id = port_id;
4888 			sess->fw_login_state = DSC_LS_PRLI_PEND;
4889 
4890 			if (wd3_lo & BIT_7)
4891 				sess->conf_compl_supported = 1;
4892 
4893 			if ((wd3_lo & BIT_4) == 0)
4894 				sess->port_type = FCT_INITIATOR;
4895 			else
4896 				sess->port_type = FCT_TARGET;
4897 
4898 			spin_unlock_irqrestore(&tgt->ha->tgt.sess_lock, flags);
4899 		}
4900 		res = 1; /* send notify ack */
4901 
4902 		/* Make session global (not used in fabric mode) */
4903 		if (ha->current_topology != ISP_CFG_F) {
4904 			if (sess) {
4905 				ql_dbg(ql_dbg_disc, vha, 0x20fa,
4906 				    "%s %d %8phC post nack\n",
4907 				    __func__, __LINE__, sess->port_name);
4908 				qla24xx_post_nack_work(vha, sess, iocb,
4909 					SRB_NACK_PRLI);
4910 				res = 0;
4911 			} else {
4912 				set_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags);
4913 				set_bit(LOCAL_LOOP_UPDATE, &vha->dpc_flags);
4914 				qla2xxx_wake_dpc(vha);
4915 			}
4916 		} else {
4917 			if (sess) {
4918 				ql_dbg(ql_dbg_disc, vha, 0x20fb,
4919 				    "%s %d %8phC post nack\n",
4920 				    __func__, __LINE__, sess->port_name);
4921 				qla24xx_post_nack_work(vha, sess, iocb,
4922 					SRB_NACK_PRLI);
4923 				res = 0;
4924 			}
4925 		}
4926 		break;
4927 
4928 	case ELS_TPRLO:
4929 		if (le16_to_cpu(iocb->u.isp24.flags) &
4930 			NOTIFY24XX_FLAGS_GLOBAL_TPRLO) {
4931 			loop_id = 0xFFFF;
4932 			qlt_reset(vha, iocb, QLA_TGT_NEXUS_LOSS);
4933 			res = 1;
4934 			break;
4935 		}
4936 		/* fall through */
4937 	case ELS_LOGO:
4938 	case ELS_PRLO:
4939 		spin_lock_irqsave(&ha->tgt.sess_lock, flags);
4940 		sess = qla2x00_find_fcport_by_loopid(vha, loop_id);
4941 		spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
4942 
4943 		if (sess) {
4944 			sess->login_gen++;
4945 			sess->fw_login_state = DSC_LS_LOGO_PEND;
4946 			sess->logo_ack_needed = 1;
4947 			memcpy(sess->iocb, iocb, IOCB_SIZE);
4948 		}
4949 
4950 		res = qlt_reset(vha, iocb, QLA_TGT_NEXUS_LOSS_SESS);
4951 
4952 		ql_dbg(ql_dbg_disc, vha, 0x20fc,
4953 		    "%s: logo %llx res %d sess %p ",
4954 		    __func__, wwn, res, sess);
4955 		if (res == 0) {
4956 			/*
4957 			 * cmd went upper layer, look for qlt_xmit_tm_rsp()
4958 			 * for LOGO_ACK & sess delete
4959 			 */
4960 			BUG_ON(!sess);
4961 			res = 0;
4962 		} else {
4963 			/* cmd did not go to upper layer. */
4964 			if (sess) {
4965 				qlt_schedule_sess_for_deletion(sess);
4966 				res = 0;
4967 			}
4968 			/* else logo will be ack */
4969 		}
4970 		break;
4971 	case ELS_PDISC:
4972 	case ELS_ADISC:
4973 	{
4974 		struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
4975 		if (tgt->link_reinit_iocb_pending) {
4976 			qlt_send_notify_ack(ha->base_qpair,
4977 			    &tgt->link_reinit_iocb, 0, 0, 0, 0, 0, 0);
4978 			tgt->link_reinit_iocb_pending = 0;
4979 		}
4980 
4981 		sess = qla2x00_find_fcport_by_wwpn(vha,
4982 		    iocb->u.isp24.port_name, 1);
4983 		if (sess) {
4984 			ql_dbg(ql_dbg_disc, vha, 0x20fd,
4985 				"sess %p lid %d|%d DS %d LS %d\n",
4986 				sess, sess->loop_id, loop_id,
4987 				sess->disc_state, sess->fw_login_state);
4988 		}
4989 
4990 		res = 1; /* send notify ack */
4991 		break;
4992 	}
4993 
4994 	case ELS_FLOGI:	/* should never happen */
4995 	default:
4996 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf061,
4997 		    "qla_target(%d): Unsupported ELS command %x "
4998 		    "received\n", vha->vp_idx, iocb->u.isp24.status_subcode);
4999 		res = qlt_reset(vha, iocb, QLA_TGT_NEXUS_LOSS_SESS);
5000 		break;
5001 	}
5002 
5003 	ql_dbg(ql_dbg_disc, vha, 0xf026,
5004 	    "qla_target(%d): Exit ELS opcode: 0x%02x res %d\n",
5005 	    vha->vp_idx, iocb->u.isp24.status_subcode, res);
5006 
5007 	return res;
5008 }
5009 
5010 /*
5011  * ha->hardware_lock supposed to be held on entry. Might drop it, then reaquire
5012  */
5013 static void qlt_handle_imm_notify(struct scsi_qla_host *vha,
5014 	struct imm_ntfy_from_isp *iocb)
5015 {
5016 	struct qla_hw_data *ha = vha->hw;
5017 	uint32_t add_flags = 0;
5018 	int send_notify_ack = 1;
5019 	uint16_t status;
5020 
5021 	status = le16_to_cpu(iocb->u.isp2x.status);
5022 	switch (status) {
5023 	case IMM_NTFY_LIP_RESET:
5024 	{
5025 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf032,
5026 		    "qla_target(%d): LIP reset (loop %#x), subcode %x\n",
5027 		    vha->vp_idx, le16_to_cpu(iocb->u.isp24.nport_handle),
5028 		    iocb->u.isp24.status_subcode);
5029 
5030 		if (qlt_reset(vha, iocb, QLA_TGT_ABORT_ALL) == 0)
5031 			send_notify_ack = 0;
5032 		break;
5033 	}
5034 
5035 	case IMM_NTFY_LIP_LINK_REINIT:
5036 	{
5037 		struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
5038 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf033,
5039 		    "qla_target(%d): LINK REINIT (loop %#x, "
5040 		    "subcode %x)\n", vha->vp_idx,
5041 		    le16_to_cpu(iocb->u.isp24.nport_handle),
5042 		    iocb->u.isp24.status_subcode);
5043 		if (tgt->link_reinit_iocb_pending) {
5044 			qlt_send_notify_ack(ha->base_qpair,
5045 			    &tgt->link_reinit_iocb, 0, 0, 0, 0, 0, 0);
5046 		}
5047 		memcpy(&tgt->link_reinit_iocb, iocb, sizeof(*iocb));
5048 		tgt->link_reinit_iocb_pending = 1;
5049 		/*
5050 		 * QLogic requires to wait after LINK REINIT for possible
5051 		 * PDISC or ADISC ELS commands
5052 		 */
5053 		send_notify_ack = 0;
5054 		break;
5055 	}
5056 
5057 	case IMM_NTFY_PORT_LOGOUT:
5058 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf034,
5059 		    "qla_target(%d): Port logout (loop "
5060 		    "%#x, subcode %x)\n", vha->vp_idx,
5061 		    le16_to_cpu(iocb->u.isp24.nport_handle),
5062 		    iocb->u.isp24.status_subcode);
5063 
5064 		if (qlt_reset(vha, iocb, QLA_TGT_NEXUS_LOSS_SESS) == 0)
5065 			send_notify_ack = 0;
5066 		/* The sessions will be cleared in the callback, if needed */
5067 		break;
5068 
5069 	case IMM_NTFY_GLBL_TPRLO:
5070 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf035,
5071 		    "qla_target(%d): Global TPRLO (%x)\n", vha->vp_idx, status);
5072 		if (qlt_reset(vha, iocb, QLA_TGT_NEXUS_LOSS) == 0)
5073 			send_notify_ack = 0;
5074 		/* The sessions will be cleared in the callback, if needed */
5075 		break;
5076 
5077 	case IMM_NTFY_PORT_CONFIG:
5078 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf036,
5079 		    "qla_target(%d): Port config changed (%x)\n", vha->vp_idx,
5080 		    status);
5081 		if (qlt_reset(vha, iocb, QLA_TGT_ABORT_ALL) == 0)
5082 			send_notify_ack = 0;
5083 		/* The sessions will be cleared in the callback, if needed */
5084 		break;
5085 
5086 	case IMM_NTFY_GLBL_LOGO:
5087 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf06a,
5088 		    "qla_target(%d): Link failure detected\n",
5089 		    vha->vp_idx);
5090 		/* I_T nexus loss */
5091 		if (qlt_reset(vha, iocb, QLA_TGT_NEXUS_LOSS) == 0)
5092 			send_notify_ack = 0;
5093 		break;
5094 
5095 	case IMM_NTFY_IOCB_OVERFLOW:
5096 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf06b,
5097 		    "qla_target(%d): Cannot provide requested "
5098 		    "capability (IOCB overflowed the immediate notify "
5099 		    "resource count)\n", vha->vp_idx);
5100 		break;
5101 
5102 	case IMM_NTFY_ABORT_TASK:
5103 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf037,
5104 		    "qla_target(%d): Abort Task (S %08x I %#x -> "
5105 		    "L %#x)\n", vha->vp_idx,
5106 		    le16_to_cpu(iocb->u.isp2x.seq_id),
5107 		    GET_TARGET_ID(ha, (struct atio_from_isp *)iocb),
5108 		    le16_to_cpu(iocb->u.isp2x.lun));
5109 		if (qlt_abort_task(vha, iocb) == 0)
5110 			send_notify_ack = 0;
5111 		break;
5112 
5113 	case IMM_NTFY_RESOURCE:
5114 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf06c,
5115 		    "qla_target(%d): Out of resources, host %ld\n",
5116 		    vha->vp_idx, vha->host_no);
5117 		break;
5118 
5119 	case IMM_NTFY_MSG_RX:
5120 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf038,
5121 		    "qla_target(%d): Immediate notify task %x\n",
5122 		    vha->vp_idx, iocb->u.isp2x.task_flags);
5123 		if (qlt_handle_task_mgmt(vha, iocb) == 0)
5124 			send_notify_ack = 0;
5125 		break;
5126 
5127 	case IMM_NTFY_ELS:
5128 		if (qlt_24xx_handle_els(vha, iocb) == 0)
5129 			send_notify_ack = 0;
5130 		break;
5131 	default:
5132 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf06d,
5133 		    "qla_target(%d): Received unknown immediate "
5134 		    "notify status %x\n", vha->vp_idx, status);
5135 		break;
5136 	}
5137 
5138 	if (send_notify_ack)
5139 		qlt_send_notify_ack(ha->base_qpair, iocb, add_flags, 0, 0, 0,
5140 		    0, 0);
5141 }
5142 
5143 /*
5144  * ha->hardware_lock supposed to be held on entry. Might drop it, then reaquire
5145  * This function sends busy to ISP 2xxx or 24xx.
5146  */
5147 static int __qlt_send_busy(struct qla_qpair *qpair,
5148 	struct atio_from_isp *atio, uint16_t status)
5149 {
5150 	struct scsi_qla_host *vha = qpair->vha;
5151 	struct ctio7_to_24xx *ctio24;
5152 	struct qla_hw_data *ha = vha->hw;
5153 	request_t *pkt;
5154 	struct fc_port *sess = NULL;
5155 	unsigned long flags;
5156 	u16 temp;
5157 
5158 	spin_lock_irqsave(&ha->tgt.sess_lock, flags);
5159 	sess = ha->tgt.tgt_ops->find_sess_by_s_id(vha,
5160 	    atio->u.isp24.fcp_hdr.s_id);
5161 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
5162 	if (!sess) {
5163 		qlt_send_term_exchange(qpair, NULL, atio, 1, 0);
5164 		return 0;
5165 	}
5166 	/* Sending marker isn't necessary, since we called from ISR */
5167 
5168 	pkt = (request_t *)__qla2x00_alloc_iocbs(qpair, NULL);
5169 	if (!pkt) {
5170 		ql_dbg(ql_dbg_io, vha, 0x3063,
5171 		    "qla_target(%d): %s failed: unable to allocate "
5172 		    "request packet", vha->vp_idx, __func__);
5173 		return -ENOMEM;
5174 	}
5175 
5176 	qpair->tgt_counters.num_q_full_sent++;
5177 	pkt->entry_count = 1;
5178 	pkt->handle = QLA_TGT_SKIP_HANDLE | CTIO_COMPLETION_HANDLE_MARK;
5179 
5180 	ctio24 = (struct ctio7_to_24xx *)pkt;
5181 	ctio24->entry_type = CTIO_TYPE7;
5182 	ctio24->nport_handle = sess->loop_id;
5183 	ctio24->timeout = cpu_to_le16(QLA_TGT_TIMEOUT);
5184 	ctio24->vp_index = vha->vp_idx;
5185 	ctio24->initiator_id[0] = atio->u.isp24.fcp_hdr.s_id[2];
5186 	ctio24->initiator_id[1] = atio->u.isp24.fcp_hdr.s_id[1];
5187 	ctio24->initiator_id[2] = atio->u.isp24.fcp_hdr.s_id[0];
5188 	ctio24->exchange_addr = atio->u.isp24.exchange_addr;
5189 	temp = (atio->u.isp24.attr << 9) |
5190 		CTIO7_FLAGS_STATUS_MODE_1 | CTIO7_FLAGS_SEND_STATUS |
5191 		CTIO7_FLAGS_DONT_RET_CTIO;
5192 	ctio24->u.status1.flags = cpu_to_le16(temp);
5193 	/*
5194 	 * CTIO from fw w/o se_cmd doesn't provide enough info to retry it,
5195 	 * if the explicit conformation is used.
5196 	 */
5197 	ctio24->u.status1.ox_id = swab16(atio->u.isp24.fcp_hdr.ox_id);
5198 	ctio24->u.status1.scsi_status = cpu_to_le16(status);
5199 	/* Memory Barrier */
5200 	wmb();
5201 	if (qpair->reqq_start_iocbs)
5202 		qpair->reqq_start_iocbs(qpair);
5203 	else
5204 		qla2x00_start_iocbs(vha, qpair->req);
5205 	return 0;
5206 }
5207 
5208 /*
5209  * This routine is used to allocate a command for either a QFull condition
5210  * (ie reply SAM_STAT_BUSY) or to terminate an exchange that did not go
5211  * out previously.
5212  */
5213 static void
5214 qlt_alloc_qfull_cmd(struct scsi_qla_host *vha,
5215 	struct atio_from_isp *atio, uint16_t status, int qfull)
5216 {
5217 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
5218 	struct qla_hw_data *ha = vha->hw;
5219 	struct fc_port *sess;
5220 	struct se_session *se_sess;
5221 	struct qla_tgt_cmd *cmd;
5222 	int tag;
5223 	unsigned long flags;
5224 
5225 	if (unlikely(tgt->tgt_stop)) {
5226 		ql_dbg(ql_dbg_io, vha, 0x300a,
5227 			"New command while device %p is shutting down\n", tgt);
5228 		return;
5229 	}
5230 
5231 	if ((vha->hw->tgt.num_qfull_cmds_alloc + 1) > MAX_QFULL_CMDS_ALLOC) {
5232 		vha->hw->tgt.num_qfull_cmds_dropped++;
5233 		if (vha->hw->tgt.num_qfull_cmds_dropped >
5234 			vha->qla_stats.stat_max_qfull_cmds_dropped)
5235 			vha->qla_stats.stat_max_qfull_cmds_dropped =
5236 				vha->hw->tgt.num_qfull_cmds_dropped;
5237 
5238 		ql_dbg(ql_dbg_io, vha, 0x3068,
5239 			"qla_target(%d): %s: QFull CMD dropped[%d]\n",
5240 			vha->vp_idx, __func__,
5241 			vha->hw->tgt.num_qfull_cmds_dropped);
5242 
5243 		qlt_chk_exch_leak_thresh_hold(vha);
5244 		return;
5245 	}
5246 
5247 	sess = ha->tgt.tgt_ops->find_sess_by_s_id
5248 		(vha, atio->u.isp24.fcp_hdr.s_id);
5249 	if (!sess)
5250 		return;
5251 
5252 	se_sess = sess->se_sess;
5253 
5254 	tag = percpu_ida_alloc(&se_sess->sess_tag_pool, TASK_RUNNING);
5255 	if (tag < 0)
5256 		return;
5257 
5258 	cmd = &((struct qla_tgt_cmd *)se_sess->sess_cmd_map)[tag];
5259 	if (!cmd) {
5260 		ql_dbg(ql_dbg_io, vha, 0x3009,
5261 			"qla_target(%d): %s: Allocation of cmd failed\n",
5262 			vha->vp_idx, __func__);
5263 
5264 		vha->hw->tgt.num_qfull_cmds_dropped++;
5265 		if (vha->hw->tgt.num_qfull_cmds_dropped >
5266 			vha->qla_stats.stat_max_qfull_cmds_dropped)
5267 			vha->qla_stats.stat_max_qfull_cmds_dropped =
5268 				vha->hw->tgt.num_qfull_cmds_dropped;
5269 
5270 		qlt_chk_exch_leak_thresh_hold(vha);
5271 		return;
5272 	}
5273 
5274 	memset(cmd, 0, sizeof(struct qla_tgt_cmd));
5275 
5276 	qlt_incr_num_pend_cmds(vha);
5277 	INIT_LIST_HEAD(&cmd->cmd_list);
5278 	memcpy(&cmd->atio, atio, sizeof(*atio));
5279 
5280 	cmd->tgt = vha->vha_tgt.qla_tgt;
5281 	cmd->vha = vha;
5282 	cmd->reset_count = ha->base_qpair->chip_reset;
5283 	cmd->q_full = 1;
5284 	cmd->qpair = ha->base_qpair;
5285 
5286 	if (qfull) {
5287 		cmd->q_full = 1;
5288 		/* NOTE: borrowing the state field to carry the status */
5289 		cmd->state = status;
5290 	} else
5291 		cmd->term_exchg = 1;
5292 
5293 	spin_lock_irqsave(&vha->hw->tgt.q_full_lock, flags);
5294 	list_add_tail(&cmd->cmd_list, &vha->hw->tgt.q_full_list);
5295 
5296 	vha->hw->tgt.num_qfull_cmds_alloc++;
5297 	if (vha->hw->tgt.num_qfull_cmds_alloc >
5298 		vha->qla_stats.stat_max_qfull_cmds_alloc)
5299 		vha->qla_stats.stat_max_qfull_cmds_alloc =
5300 			vha->hw->tgt.num_qfull_cmds_alloc;
5301 	spin_unlock_irqrestore(&vha->hw->tgt.q_full_lock, flags);
5302 }
5303 
5304 int
5305 qlt_free_qfull_cmds(struct qla_qpair *qpair)
5306 {
5307 	struct scsi_qla_host *vha = qpair->vha;
5308 	struct qla_hw_data *ha = vha->hw;
5309 	unsigned long flags;
5310 	struct qla_tgt_cmd *cmd, *tcmd;
5311 	struct list_head free_list, q_full_list;
5312 	int rc = 0;
5313 
5314 	if (list_empty(&ha->tgt.q_full_list))
5315 		return 0;
5316 
5317 	INIT_LIST_HEAD(&free_list);
5318 	INIT_LIST_HEAD(&q_full_list);
5319 
5320 	spin_lock_irqsave(&vha->hw->tgt.q_full_lock, flags);
5321 	if (list_empty(&ha->tgt.q_full_list)) {
5322 		spin_unlock_irqrestore(&vha->hw->tgt.q_full_lock, flags);
5323 		return 0;
5324 	}
5325 
5326 	list_splice_init(&vha->hw->tgt.q_full_list, &q_full_list);
5327 	spin_unlock_irqrestore(&vha->hw->tgt.q_full_lock, flags);
5328 
5329 	spin_lock_irqsave(qpair->qp_lock_ptr, flags);
5330 	list_for_each_entry_safe(cmd, tcmd, &q_full_list, cmd_list) {
5331 		if (cmd->q_full)
5332 			/* cmd->state is a borrowed field to hold status */
5333 			rc = __qlt_send_busy(qpair, &cmd->atio, cmd->state);
5334 		else if (cmd->term_exchg)
5335 			rc = __qlt_send_term_exchange(qpair, NULL, &cmd->atio);
5336 
5337 		if (rc == -ENOMEM)
5338 			break;
5339 
5340 		if (cmd->q_full)
5341 			ql_dbg(ql_dbg_io, vha, 0x3006,
5342 			    "%s: busy sent for ox_id[%04x]\n", __func__,
5343 			    be16_to_cpu(cmd->atio.u.isp24.fcp_hdr.ox_id));
5344 		else if (cmd->term_exchg)
5345 			ql_dbg(ql_dbg_io, vha, 0x3007,
5346 			    "%s: Term exchg sent for ox_id[%04x]\n", __func__,
5347 			    be16_to_cpu(cmd->atio.u.isp24.fcp_hdr.ox_id));
5348 		else
5349 			ql_dbg(ql_dbg_io, vha, 0x3008,
5350 			    "%s: Unexpected cmd in QFull list %p\n", __func__,
5351 			    cmd);
5352 
5353 		list_del(&cmd->cmd_list);
5354 		list_add_tail(&cmd->cmd_list, &free_list);
5355 
5356 		/* piggy back on hardware_lock for protection */
5357 		vha->hw->tgt.num_qfull_cmds_alloc--;
5358 	}
5359 	spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
5360 
5361 	cmd = NULL;
5362 
5363 	list_for_each_entry_safe(cmd, tcmd, &free_list, cmd_list) {
5364 		list_del(&cmd->cmd_list);
5365 		/* This cmd was never sent to TCM.  There is no need
5366 		 * to schedule free or call free_cmd
5367 		 */
5368 		qlt_free_cmd(cmd);
5369 	}
5370 
5371 	if (!list_empty(&q_full_list)) {
5372 		spin_lock_irqsave(&vha->hw->tgt.q_full_lock, flags);
5373 		list_splice(&q_full_list, &vha->hw->tgt.q_full_list);
5374 		spin_unlock_irqrestore(&vha->hw->tgt.q_full_lock, flags);
5375 	}
5376 
5377 	return rc;
5378 }
5379 
5380 static void
5381 qlt_send_busy(struct qla_qpair *qpair, struct atio_from_isp *atio,
5382     uint16_t status)
5383 {
5384 	int rc = 0;
5385 	struct scsi_qla_host *vha = qpair->vha;
5386 
5387 	rc = __qlt_send_busy(qpair, atio, status);
5388 	if (rc == -ENOMEM)
5389 		qlt_alloc_qfull_cmd(vha, atio, status, 1);
5390 }
5391 
5392 static int
5393 qlt_chk_qfull_thresh_hold(struct scsi_qla_host *vha, struct qla_qpair *qpair,
5394 	struct atio_from_isp *atio, uint8_t ha_locked)
5395 {
5396 	struct qla_hw_data *ha = vha->hw;
5397 	unsigned long flags;
5398 
5399 	if (ha->tgt.num_pend_cmds < Q_FULL_THRESH_HOLD(ha))
5400 		return 0;
5401 
5402 	if (!ha_locked)
5403 		spin_lock_irqsave(&ha->hardware_lock, flags);
5404 	qlt_send_busy(qpair, atio, qla_sam_status);
5405 	if (!ha_locked)
5406 		spin_unlock_irqrestore(&ha->hardware_lock, flags);
5407 
5408 	return 1;
5409 }
5410 
5411 /* ha->hardware_lock supposed to be held on entry */
5412 /* called via callback from qla2xxx */
5413 static void qlt_24xx_atio_pkt(struct scsi_qla_host *vha,
5414 	struct atio_from_isp *atio, uint8_t ha_locked)
5415 {
5416 	struct qla_hw_data *ha = vha->hw;
5417 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
5418 	int rc;
5419 	unsigned long flags = 0;
5420 
5421 	if (unlikely(tgt == NULL)) {
5422 		ql_dbg(ql_dbg_tgt, vha, 0x3064,
5423 		    "ATIO pkt, but no tgt (ha %p)", ha);
5424 		return;
5425 	}
5426 	/*
5427 	 * In tgt_stop mode we also should allow all requests to pass.
5428 	 * Otherwise, some commands can stuck.
5429 	 */
5430 
5431 	tgt->atio_irq_cmd_count++;
5432 
5433 	switch (atio->u.raw.entry_type) {
5434 	case ATIO_TYPE7:
5435 		if (unlikely(atio->u.isp24.exchange_addr ==
5436 		    ATIO_EXCHANGE_ADDRESS_UNKNOWN)) {
5437 			ql_dbg(ql_dbg_io, vha, 0x3065,
5438 			    "qla_target(%d): ATIO_TYPE7 "
5439 			    "received with UNKNOWN exchange address, "
5440 			    "sending QUEUE_FULL\n", vha->vp_idx);
5441 			if (!ha_locked)
5442 				spin_lock_irqsave(&ha->hardware_lock, flags);
5443 			qlt_send_busy(ha->base_qpair, atio, qla_sam_status);
5444 			if (!ha_locked)
5445 				spin_unlock_irqrestore(&ha->hardware_lock,
5446 				    flags);
5447 			break;
5448 		}
5449 
5450 		if (likely(atio->u.isp24.fcp_cmnd.task_mgmt_flags == 0)) {
5451 			rc = qlt_chk_qfull_thresh_hold(vha, ha->base_qpair,
5452 			    atio, ha_locked);
5453 			if (rc != 0) {
5454 				tgt->atio_irq_cmd_count--;
5455 				return;
5456 			}
5457 			rc = qlt_handle_cmd_for_atio(vha, atio);
5458 		} else {
5459 			rc = qlt_handle_task_mgmt(vha, atio);
5460 		}
5461 		if (unlikely(rc != 0)) {
5462 			if (!ha_locked)
5463 				spin_lock_irqsave(&ha->hardware_lock, flags);
5464 			switch (rc) {
5465 			case -ENODEV:
5466 				ql_dbg(ql_dbg_tgt, vha, 0xe05f,
5467 				    "qla_target: Unable to send command to target\n");
5468 				break;
5469 			case -EBADF:
5470 				ql_dbg(ql_dbg_tgt, vha, 0xe05f,
5471 				    "qla_target: Unable to send command to target, sending TERM EXCHANGE for rsp\n");
5472 				qlt_send_term_exchange(ha->base_qpair, NULL,
5473 				    atio, 1, 0);
5474 				break;
5475 			case -EBUSY:
5476 				ql_dbg(ql_dbg_tgt, vha, 0xe060,
5477 				    "qla_target(%d): Unable to send command to target, sending BUSY status\n",
5478 				    vha->vp_idx);
5479 				qlt_send_busy(ha->base_qpair, atio,
5480 				    tc_sam_status);
5481 				break;
5482 			default:
5483 				ql_dbg(ql_dbg_tgt, vha, 0xe060,
5484 				    "qla_target(%d): Unable to send command to target, sending BUSY status\n",
5485 				    vha->vp_idx);
5486 				qlt_send_busy(ha->base_qpair, atio,
5487 				    qla_sam_status);
5488 				break;
5489 			}
5490 			if (!ha_locked)
5491 				spin_unlock_irqrestore(&ha->hardware_lock,
5492 				    flags);
5493 		}
5494 		break;
5495 
5496 	case IMMED_NOTIFY_TYPE:
5497 	{
5498 		if (unlikely(atio->u.isp2x.entry_status != 0)) {
5499 			ql_dbg(ql_dbg_tgt, vha, 0xe05b,
5500 			    "qla_target(%d): Received ATIO packet %x "
5501 			    "with error status %x\n", vha->vp_idx,
5502 			    atio->u.raw.entry_type,
5503 			    atio->u.isp2x.entry_status);
5504 			break;
5505 		}
5506 		ql_dbg(ql_dbg_tgt, vha, 0xe02e, "%s", "IMMED_NOTIFY ATIO");
5507 
5508 		if (!ha_locked)
5509 			spin_lock_irqsave(&ha->hardware_lock, flags);
5510 		qlt_handle_imm_notify(vha, (struct imm_ntfy_from_isp *)atio);
5511 		if (!ha_locked)
5512 			spin_unlock_irqrestore(&ha->hardware_lock, flags);
5513 		break;
5514 	}
5515 
5516 	default:
5517 		ql_dbg(ql_dbg_tgt, vha, 0xe05c,
5518 		    "qla_target(%d): Received unknown ATIO atio "
5519 		    "type %x\n", vha->vp_idx, atio->u.raw.entry_type);
5520 		break;
5521 	}
5522 
5523 	tgt->atio_irq_cmd_count--;
5524 }
5525 
5526 /* ha->hardware_lock supposed to be held on entry */
5527 /* called via callback from qla2xxx */
5528 static void qlt_response_pkt(struct scsi_qla_host *vha,
5529 	struct rsp_que *rsp, response_t *pkt)
5530 {
5531 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
5532 
5533 	if (unlikely(tgt == NULL)) {
5534 		ql_dbg(ql_dbg_tgt, vha, 0xe05d,
5535 		    "qla_target(%d): Response pkt %x received, but no tgt (ha %p)\n",
5536 		    vha->vp_idx, pkt->entry_type, vha->hw);
5537 		return;
5538 	}
5539 
5540 	/*
5541 	 * In tgt_stop mode we also should allow all requests to pass.
5542 	 * Otherwise, some commands can stuck.
5543 	 */
5544 
5545 	switch (pkt->entry_type) {
5546 	case CTIO_CRC2:
5547 	case CTIO_TYPE7:
5548 	{
5549 		struct ctio7_from_24xx *entry = (struct ctio7_from_24xx *)pkt;
5550 		qlt_do_ctio_completion(vha, rsp, entry->handle,
5551 		    le16_to_cpu(entry->status)|(pkt->entry_status << 16),
5552 		    entry);
5553 		break;
5554 	}
5555 
5556 	case ACCEPT_TGT_IO_TYPE:
5557 	{
5558 		struct atio_from_isp *atio = (struct atio_from_isp *)pkt;
5559 		int rc;
5560 		if (atio->u.isp2x.status !=
5561 		    cpu_to_le16(ATIO_CDB_VALID)) {
5562 			ql_dbg(ql_dbg_tgt, vha, 0xe05e,
5563 			    "qla_target(%d): ATIO with error "
5564 			    "status %x received\n", vha->vp_idx,
5565 			    le16_to_cpu(atio->u.isp2x.status));
5566 			break;
5567 		}
5568 
5569 		rc = qlt_chk_qfull_thresh_hold(vha, rsp->qpair, atio, 1);
5570 		if (rc != 0)
5571 			return;
5572 
5573 		rc = qlt_handle_cmd_for_atio(vha, atio);
5574 		if (unlikely(rc != 0)) {
5575 			switch (rc) {
5576 			case -ENODEV:
5577 				ql_dbg(ql_dbg_tgt, vha, 0xe05f,
5578 				    "qla_target: Unable to send command to target\n");
5579 				break;
5580 			case -EBADF:
5581 				ql_dbg(ql_dbg_tgt, vha, 0xe05f,
5582 				    "qla_target: Unable to send command to target, sending TERM EXCHANGE for rsp\n");
5583 				qlt_send_term_exchange(rsp->qpair, NULL,
5584 				    atio, 1, 0);
5585 				break;
5586 			case -EBUSY:
5587 				ql_dbg(ql_dbg_tgt, vha, 0xe060,
5588 				    "qla_target(%d): Unable to send command to target, sending BUSY status\n",
5589 				    vha->vp_idx);
5590 				qlt_send_busy(rsp->qpair, atio,
5591 				    tc_sam_status);
5592 				break;
5593 			default:
5594 				ql_dbg(ql_dbg_tgt, vha, 0xe060,
5595 				    "qla_target(%d): Unable to send command to target, sending BUSY status\n",
5596 				    vha->vp_idx);
5597 				qlt_send_busy(rsp->qpair, atio,
5598 				    qla_sam_status);
5599 				break;
5600 			}
5601 		}
5602 	}
5603 	break;
5604 
5605 	case CONTINUE_TGT_IO_TYPE:
5606 	{
5607 		struct ctio_to_2xxx *entry = (struct ctio_to_2xxx *)pkt;
5608 		qlt_do_ctio_completion(vha, rsp, entry->handle,
5609 		    le16_to_cpu(entry->status)|(pkt->entry_status << 16),
5610 		    entry);
5611 		break;
5612 	}
5613 
5614 	case CTIO_A64_TYPE:
5615 	{
5616 		struct ctio_to_2xxx *entry = (struct ctio_to_2xxx *)pkt;
5617 		qlt_do_ctio_completion(vha, rsp, entry->handle,
5618 		    le16_to_cpu(entry->status)|(pkt->entry_status << 16),
5619 		    entry);
5620 		break;
5621 	}
5622 
5623 	case IMMED_NOTIFY_TYPE:
5624 		ql_dbg(ql_dbg_tgt, vha, 0xe035, "%s", "IMMED_NOTIFY\n");
5625 		qlt_handle_imm_notify(vha, (struct imm_ntfy_from_isp *)pkt);
5626 		break;
5627 
5628 	case NOTIFY_ACK_TYPE:
5629 		if (tgt->notify_ack_expected > 0) {
5630 			struct nack_to_isp *entry = (struct nack_to_isp *)pkt;
5631 			ql_dbg(ql_dbg_tgt, vha, 0xe036,
5632 			    "NOTIFY_ACK seq %08x status %x\n",
5633 			    le16_to_cpu(entry->u.isp2x.seq_id),
5634 			    le16_to_cpu(entry->u.isp2x.status));
5635 			tgt->notify_ack_expected--;
5636 			if (entry->u.isp2x.status !=
5637 			    cpu_to_le16(NOTIFY_ACK_SUCCESS)) {
5638 				ql_dbg(ql_dbg_tgt, vha, 0xe061,
5639 				    "qla_target(%d): NOTIFY_ACK "
5640 				    "failed %x\n", vha->vp_idx,
5641 				    le16_to_cpu(entry->u.isp2x.status));
5642 			}
5643 		} else {
5644 			ql_dbg(ql_dbg_tgt, vha, 0xe062,
5645 			    "qla_target(%d): Unexpected NOTIFY_ACK received\n",
5646 			    vha->vp_idx);
5647 		}
5648 		break;
5649 
5650 	case ABTS_RECV_24XX:
5651 		ql_dbg(ql_dbg_tgt, vha, 0xe037,
5652 		    "ABTS_RECV_24XX: instance %d\n", vha->vp_idx);
5653 		qlt_24xx_handle_abts(vha, (struct abts_recv_from_24xx *)pkt);
5654 		break;
5655 
5656 	case ABTS_RESP_24XX:
5657 		if (tgt->abts_resp_expected > 0) {
5658 			struct abts_resp_from_24xx_fw *entry =
5659 				(struct abts_resp_from_24xx_fw *)pkt;
5660 			ql_dbg(ql_dbg_tgt, vha, 0xe038,
5661 			    "ABTS_RESP_24XX: compl_status %x\n",
5662 			    entry->compl_status);
5663 			tgt->abts_resp_expected--;
5664 			if (le16_to_cpu(entry->compl_status) !=
5665 			    ABTS_RESP_COMPL_SUCCESS) {
5666 				if ((entry->error_subcode1 == 0x1E) &&
5667 				    (entry->error_subcode2 == 0)) {
5668 					/*
5669 					 * We've got a race here: aborted
5670 					 * exchange not terminated, i.e.
5671 					 * response for the aborted command was
5672 					 * sent between the abort request was
5673 					 * received and processed.
5674 					 * Unfortunately, the firmware has a
5675 					 * silly requirement that all aborted
5676 					 * exchanges must be explicitely
5677 					 * terminated, otherwise it refuses to
5678 					 * send responses for the abort
5679 					 * requests. So, we have to
5680 					 * (re)terminate the exchange and retry
5681 					 * the abort response.
5682 					 */
5683 					qlt_24xx_retry_term_exchange(vha,
5684 					    entry);
5685 				} else
5686 					ql_dbg(ql_dbg_tgt, vha, 0xe063,
5687 					    "qla_target(%d): ABTS_RESP_24XX "
5688 					    "failed %x (subcode %x:%x)",
5689 					    vha->vp_idx, entry->compl_status,
5690 					    entry->error_subcode1,
5691 					    entry->error_subcode2);
5692 			}
5693 		} else {
5694 			ql_dbg(ql_dbg_tgt, vha, 0xe064,
5695 			    "qla_target(%d): Unexpected ABTS_RESP_24XX "
5696 			    "received\n", vha->vp_idx);
5697 		}
5698 		break;
5699 
5700 	default:
5701 		ql_dbg(ql_dbg_tgt, vha, 0xe065,
5702 		    "qla_target(%d): Received unknown response pkt "
5703 		    "type %x\n", vha->vp_idx, pkt->entry_type);
5704 		break;
5705 	}
5706 
5707 }
5708 
5709 /*
5710  * ha->hardware_lock supposed to be held on entry. Might drop it, then reaquire
5711  */
5712 void qlt_async_event(uint16_t code, struct scsi_qla_host *vha,
5713 	uint16_t *mailbox)
5714 {
5715 	struct qla_hw_data *ha = vha->hw;
5716 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
5717 	int login_code;
5718 
5719 	if (!tgt || tgt->tgt_stop || tgt->tgt_stopped)
5720 		return;
5721 
5722 	if (((code == MBA_POINT_TO_POINT) || (code == MBA_CHG_IN_CONNECTION)) &&
5723 	    IS_QLA2100(ha))
5724 		return;
5725 	/*
5726 	 * In tgt_stop mode we also should allow all requests to pass.
5727 	 * Otherwise, some commands can stuck.
5728 	 */
5729 
5730 
5731 	switch (code) {
5732 	case MBA_RESET:			/* Reset */
5733 	case MBA_SYSTEM_ERR:		/* System Error */
5734 	case MBA_REQ_TRANSFER_ERR:	/* Request Transfer Error */
5735 	case MBA_RSP_TRANSFER_ERR:	/* Response Transfer Error */
5736 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf03a,
5737 		    "qla_target(%d): System error async event %#x "
5738 		    "occurred", vha->vp_idx, code);
5739 		break;
5740 	case MBA_WAKEUP_THRES:		/* Request Queue Wake-up. */
5741 		set_bit(ISP_ABORT_NEEDED, &vha->dpc_flags);
5742 		break;
5743 
5744 	case MBA_LOOP_UP:
5745 	{
5746 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf03b,
5747 		    "qla_target(%d): Async LOOP_UP occurred "
5748 		    "(m[0]=%x, m[1]=%x, m[2]=%x, m[3]=%x)", vha->vp_idx,
5749 		    le16_to_cpu(mailbox[0]), le16_to_cpu(mailbox[1]),
5750 		    le16_to_cpu(mailbox[2]), le16_to_cpu(mailbox[3]));
5751 		if (tgt->link_reinit_iocb_pending) {
5752 			qlt_send_notify_ack(ha->base_qpair,
5753 			    (void *)&tgt->link_reinit_iocb,
5754 			    0, 0, 0, 0, 0, 0);
5755 			tgt->link_reinit_iocb_pending = 0;
5756 		}
5757 		break;
5758 	}
5759 
5760 	case MBA_LIP_OCCURRED:
5761 	case MBA_LOOP_DOWN:
5762 	case MBA_LIP_RESET:
5763 	case MBA_RSCN_UPDATE:
5764 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf03c,
5765 		    "qla_target(%d): Async event %#x occurred "
5766 		    "(m[0]=%x, m[1]=%x, m[2]=%x, m[3]=%x)", vha->vp_idx, code,
5767 		    le16_to_cpu(mailbox[0]), le16_to_cpu(mailbox[1]),
5768 		    le16_to_cpu(mailbox[2]), le16_to_cpu(mailbox[3]));
5769 		break;
5770 
5771 	case MBA_REJECTED_FCP_CMD:
5772 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf017,
5773 		    "qla_target(%d): Async event LS_REJECT occurred (m[0]=%x, m[1]=%x, m[2]=%x, m[3]=%x)",
5774 		    vha->vp_idx,
5775 		    le16_to_cpu(mailbox[0]), le16_to_cpu(mailbox[1]),
5776 		    le16_to_cpu(mailbox[2]), le16_to_cpu(mailbox[3]));
5777 
5778 		if (le16_to_cpu(mailbox[3]) == 1) {
5779 			/* exchange starvation. */
5780 			vha->hw->exch_starvation++;
5781 			if (vha->hw->exch_starvation > 5) {
5782 				ql_log(ql_log_warn, vha, 0xd03a,
5783 				    "Exchange starvation-. Resetting RISC\n");
5784 
5785 				vha->hw->exch_starvation = 0;
5786 				if (IS_P3P_TYPE(vha->hw))
5787 					set_bit(FCOE_CTX_RESET_NEEDED,
5788 					    &vha->dpc_flags);
5789 				else
5790 					set_bit(ISP_ABORT_NEEDED,
5791 					    &vha->dpc_flags);
5792 				qla2xxx_wake_dpc(vha);
5793 			}
5794 		}
5795 		break;
5796 
5797 	case MBA_PORT_UPDATE:
5798 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf03d,
5799 		    "qla_target(%d): Port update async event %#x "
5800 		    "occurred: updating the ports database (m[0]=%x, m[1]=%x, "
5801 		    "m[2]=%x, m[3]=%x)", vha->vp_idx, code,
5802 		    le16_to_cpu(mailbox[0]), le16_to_cpu(mailbox[1]),
5803 		    le16_to_cpu(mailbox[2]), le16_to_cpu(mailbox[3]));
5804 
5805 		login_code = le16_to_cpu(mailbox[2]);
5806 		if (login_code == 0x4) {
5807 			ql_dbg(ql_dbg_tgt_mgt, vha, 0xf03e,
5808 			    "Async MB 2: Got PLOGI Complete\n");
5809 			vha->hw->exch_starvation = 0;
5810 		} else if (login_code == 0x7)
5811 			ql_dbg(ql_dbg_tgt_mgt, vha, 0xf03f,
5812 			    "Async MB 2: Port Logged Out\n");
5813 		break;
5814 	default:
5815 		break;
5816 	}
5817 
5818 }
5819 
5820 static fc_port_t *qlt_get_port_database(struct scsi_qla_host *vha,
5821 	uint16_t loop_id)
5822 {
5823 	fc_port_t *fcport, *tfcp, *del;
5824 	int rc;
5825 	unsigned long flags;
5826 	u8 newfcport = 0;
5827 
5828 	fcport = qla2x00_alloc_fcport(vha, GFP_KERNEL);
5829 	if (!fcport) {
5830 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf06f,
5831 		    "qla_target(%d): Allocation of tmp FC port failed",
5832 		    vha->vp_idx);
5833 		return NULL;
5834 	}
5835 
5836 	fcport->loop_id = loop_id;
5837 
5838 	rc = qla24xx_gpdb_wait(vha, fcport, 0);
5839 	if (rc != QLA_SUCCESS) {
5840 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf070,
5841 		    "qla_target(%d): Failed to retrieve fcport "
5842 		    "information -- get_port_database() returned %x "
5843 		    "(loop_id=0x%04x)", vha->vp_idx, rc, loop_id);
5844 		kfree(fcport);
5845 		return NULL;
5846 	}
5847 
5848 	del = NULL;
5849 	spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
5850 	tfcp = qla2x00_find_fcport_by_wwpn(vha, fcport->port_name, 1);
5851 
5852 	if (tfcp) {
5853 		tfcp->d_id = fcport->d_id;
5854 		tfcp->port_type = fcport->port_type;
5855 		tfcp->supported_classes = fcport->supported_classes;
5856 		tfcp->flags |= fcport->flags;
5857 		tfcp->scan_state = QLA_FCPORT_FOUND;
5858 
5859 		del = fcport;
5860 		fcport = tfcp;
5861 	} else {
5862 		if (vha->hw->current_topology == ISP_CFG_F)
5863 			fcport->flags |= FCF_FABRIC_DEVICE;
5864 
5865 		list_add_tail(&fcport->list, &vha->vp_fcports);
5866 		if (!IS_SW_RESV_ADDR(fcport->d_id))
5867 		   vha->fcport_count++;
5868 		fcport->login_gen++;
5869 		fcport->disc_state = DSC_LOGIN_COMPLETE;
5870 		fcport->login_succ = 1;
5871 		newfcport = 1;
5872 	}
5873 
5874 	fcport->deleted = 0;
5875 	spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
5876 
5877 	switch (vha->host->active_mode) {
5878 	case MODE_INITIATOR:
5879 	case MODE_DUAL:
5880 		if (newfcport) {
5881 			if (!IS_IIDMA_CAPABLE(vha->hw) || !vha->hw->flags.gpsc_supported) {
5882 				ql_dbg(ql_dbg_disc, vha, 0x20fe,
5883 				   "%s %d %8phC post upd_fcport fcp_cnt %d\n",
5884 				   __func__, __LINE__, fcport->port_name, vha->fcport_count);
5885 				qla24xx_post_upd_fcport_work(vha, fcport);
5886 			} else {
5887 				ql_dbg(ql_dbg_disc, vha, 0x20ff,
5888 				   "%s %d %8phC post gpsc fcp_cnt %d\n",
5889 				   __func__, __LINE__, fcport->port_name, vha->fcport_count);
5890 				qla24xx_post_gpsc_work(vha, fcport);
5891 			}
5892 		}
5893 		break;
5894 
5895 	case MODE_TARGET:
5896 	default:
5897 		break;
5898 	}
5899 	if (del)
5900 		qla2x00_free_fcport(del);
5901 
5902 	return fcport;
5903 }
5904 
5905 /* Must be called under tgt_mutex */
5906 static struct fc_port *qlt_make_local_sess(struct scsi_qla_host *vha,
5907 	uint8_t *s_id)
5908 {
5909 	struct fc_port *sess = NULL;
5910 	fc_port_t *fcport = NULL;
5911 	int rc, global_resets;
5912 	uint16_t loop_id = 0;
5913 
5914 	if ((s_id[0] == 0xFF) && (s_id[1] == 0xFC)) {
5915 		/*
5916 		 * This is Domain Controller, so it should be
5917 		 * OK to drop SCSI commands from it.
5918 		 */
5919 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf042,
5920 		    "Unable to find initiator with S_ID %x:%x:%x",
5921 		    s_id[0], s_id[1], s_id[2]);
5922 		return NULL;
5923 	}
5924 
5925 	mutex_lock(&vha->vha_tgt.tgt_mutex);
5926 
5927 retry:
5928 	global_resets =
5929 	    atomic_read(&vha->vha_tgt.qla_tgt->tgt_global_resets_count);
5930 
5931 	rc = qla24xx_get_loop_id(vha, s_id, &loop_id);
5932 	if (rc != 0) {
5933 		mutex_unlock(&vha->vha_tgt.tgt_mutex);
5934 
5935 		ql_log(ql_log_info, vha, 0xf071,
5936 		    "qla_target(%d): Unable to find "
5937 		    "initiator with S_ID %x:%x:%x",
5938 		    vha->vp_idx, s_id[0], s_id[1],
5939 		    s_id[2]);
5940 
5941 		if (rc == -ENOENT) {
5942 			qlt_port_logo_t logo;
5943 			sid_to_portid(s_id, &logo.id);
5944 			logo.cmd_count = 1;
5945 			qlt_send_first_logo(vha, &logo);
5946 		}
5947 
5948 		return NULL;
5949 	}
5950 
5951 	fcport = qlt_get_port_database(vha, loop_id);
5952 	if (!fcport) {
5953 		mutex_unlock(&vha->vha_tgt.tgt_mutex);
5954 		return NULL;
5955 	}
5956 
5957 	if (global_resets !=
5958 	    atomic_read(&vha->vha_tgt.qla_tgt->tgt_global_resets_count)) {
5959 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf043,
5960 		    "qla_target(%d): global reset during session discovery "
5961 		    "(counter was %d, new %d), retrying", vha->vp_idx,
5962 		    global_resets,
5963 		    atomic_read(&vha->vha_tgt.
5964 			qla_tgt->tgt_global_resets_count));
5965 		goto retry;
5966 	}
5967 
5968 	sess = qlt_create_sess(vha, fcport, true);
5969 
5970 	mutex_unlock(&vha->vha_tgt.tgt_mutex);
5971 
5972 	return sess;
5973 }
5974 
5975 static void qlt_abort_work(struct qla_tgt *tgt,
5976 	struct qla_tgt_sess_work_param *prm)
5977 {
5978 	struct scsi_qla_host *vha = tgt->vha;
5979 	struct qla_hw_data *ha = vha->hw;
5980 	struct fc_port *sess = NULL;
5981 	unsigned long flags = 0, flags2 = 0;
5982 	uint32_t be_s_id;
5983 	uint8_t s_id[3];
5984 	int rc;
5985 
5986 	spin_lock_irqsave(&ha->tgt.sess_lock, flags2);
5987 
5988 	if (tgt->tgt_stop)
5989 		goto out_term2;
5990 
5991 	s_id[0] = prm->abts.fcp_hdr_le.s_id[2];
5992 	s_id[1] = prm->abts.fcp_hdr_le.s_id[1];
5993 	s_id[2] = prm->abts.fcp_hdr_le.s_id[0];
5994 
5995 	sess = ha->tgt.tgt_ops->find_sess_by_s_id(vha,
5996 	    (unsigned char *)&be_s_id);
5997 	if (!sess) {
5998 		spin_unlock_irqrestore(&ha->tgt.sess_lock, flags2);
5999 
6000 		sess = qlt_make_local_sess(vha, s_id);
6001 		/* sess has got an extra creation ref */
6002 
6003 		spin_lock_irqsave(&ha->tgt.sess_lock, flags2);
6004 		if (!sess)
6005 			goto out_term2;
6006 	} else {
6007 		if (sess->deleted) {
6008 			sess = NULL;
6009 			goto out_term2;
6010 		}
6011 
6012 		if (!kref_get_unless_zero(&sess->sess_kref)) {
6013 			ql_dbg(ql_dbg_tgt_tmr, vha, 0xf01c,
6014 			    "%s: kref_get fail %8phC \n",
6015 			     __func__, sess->port_name);
6016 			sess = NULL;
6017 			goto out_term2;
6018 		}
6019 	}
6020 
6021 	rc = __qlt_24xx_handle_abts(vha, &prm->abts, sess);
6022 	ha->tgt.tgt_ops->put_sess(sess);
6023 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags2);
6024 
6025 	if (rc != 0)
6026 		goto out_term;
6027 	return;
6028 
6029 out_term2:
6030 	if (sess)
6031 		ha->tgt.tgt_ops->put_sess(sess);
6032 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags2);
6033 
6034 out_term:
6035 	spin_lock_irqsave(&ha->hardware_lock, flags);
6036 	qlt_24xx_send_abts_resp(ha->base_qpair, &prm->abts,
6037 	    FCP_TMF_REJECTED, false);
6038 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
6039 }
6040 
6041 static void qlt_tmr_work(struct qla_tgt *tgt,
6042 	struct qla_tgt_sess_work_param *prm)
6043 {
6044 	struct atio_from_isp *a = &prm->tm_iocb2;
6045 	struct scsi_qla_host *vha = tgt->vha;
6046 	struct qla_hw_data *ha = vha->hw;
6047 	struct fc_port *sess = NULL;
6048 	unsigned long flags;
6049 	uint8_t *s_id = NULL; /* to hide compiler warnings */
6050 	int rc;
6051 	u64 unpacked_lun;
6052 	int fn;
6053 	void *iocb;
6054 
6055 	spin_lock_irqsave(&ha->tgt.sess_lock, flags);
6056 
6057 	if (tgt->tgt_stop)
6058 		goto out_term2;
6059 
6060 	s_id = prm->tm_iocb2.u.isp24.fcp_hdr.s_id;
6061 	sess = ha->tgt.tgt_ops->find_sess_by_s_id(vha, s_id);
6062 	if (!sess) {
6063 		spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
6064 
6065 		sess = qlt_make_local_sess(vha, s_id);
6066 		/* sess has got an extra creation ref */
6067 
6068 		spin_lock_irqsave(&ha->tgt.sess_lock, flags);
6069 		if (!sess)
6070 			goto out_term2;
6071 	} else {
6072 		if (sess->deleted) {
6073 			sess = NULL;
6074 			goto out_term2;
6075 		}
6076 
6077 		if (!kref_get_unless_zero(&sess->sess_kref)) {
6078 			ql_dbg(ql_dbg_tgt_tmr, vha, 0xf020,
6079 			    "%s: kref_get fail %8phC\n",
6080 			     __func__, sess->port_name);
6081 			sess = NULL;
6082 			goto out_term2;
6083 		}
6084 	}
6085 
6086 	iocb = a;
6087 	fn = a->u.isp24.fcp_cmnd.task_mgmt_flags;
6088 	unpacked_lun =
6089 	    scsilun_to_int((struct scsi_lun *)&a->u.isp24.fcp_cmnd.lun);
6090 
6091 	rc = qlt_issue_task_mgmt(sess, unpacked_lun, fn, iocb, 0);
6092 	ha->tgt.tgt_ops->put_sess(sess);
6093 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
6094 
6095 	if (rc != 0)
6096 		goto out_term;
6097 	return;
6098 
6099 out_term2:
6100 	if (sess)
6101 		ha->tgt.tgt_ops->put_sess(sess);
6102 	spin_unlock_irqrestore(&ha->tgt.sess_lock, flags);
6103 out_term:
6104 	qlt_send_term_exchange(ha->base_qpair, NULL, &prm->tm_iocb2, 1, 0);
6105 }
6106 
6107 static void qlt_sess_work_fn(struct work_struct *work)
6108 {
6109 	struct qla_tgt *tgt = container_of(work, struct qla_tgt, sess_work);
6110 	struct scsi_qla_host *vha = tgt->vha;
6111 	unsigned long flags;
6112 
6113 	ql_dbg(ql_dbg_tgt_mgt, vha, 0xf000, "Sess work (tgt %p)", tgt);
6114 
6115 	spin_lock_irqsave(&tgt->sess_work_lock, flags);
6116 	while (!list_empty(&tgt->sess_works_list)) {
6117 		struct qla_tgt_sess_work_param *prm = list_entry(
6118 		    tgt->sess_works_list.next, typeof(*prm),
6119 		    sess_works_list_entry);
6120 
6121 		/*
6122 		 * This work can be scheduled on several CPUs at time, so we
6123 		 * must delete the entry to eliminate double processing
6124 		 */
6125 		list_del(&prm->sess_works_list_entry);
6126 
6127 		spin_unlock_irqrestore(&tgt->sess_work_lock, flags);
6128 
6129 		switch (prm->type) {
6130 		case QLA_TGT_SESS_WORK_ABORT:
6131 			qlt_abort_work(tgt, prm);
6132 			break;
6133 		case QLA_TGT_SESS_WORK_TM:
6134 			qlt_tmr_work(tgt, prm);
6135 			break;
6136 		default:
6137 			BUG_ON(1);
6138 			break;
6139 		}
6140 
6141 		spin_lock_irqsave(&tgt->sess_work_lock, flags);
6142 
6143 		kfree(prm);
6144 	}
6145 	spin_unlock_irqrestore(&tgt->sess_work_lock, flags);
6146 }
6147 
6148 /* Must be called under tgt_host_action_mutex */
6149 int qlt_add_target(struct qla_hw_data *ha, struct scsi_qla_host *base_vha)
6150 {
6151 	struct qla_tgt *tgt;
6152 	int rc, i;
6153 	struct qla_qpair_hint *h;
6154 
6155 	if (!QLA_TGT_MODE_ENABLED())
6156 		return 0;
6157 
6158 	if (!IS_TGT_MODE_CAPABLE(ha)) {
6159 		ql_log(ql_log_warn, base_vha, 0xe070,
6160 		    "This adapter does not support target mode.\n");
6161 		return 0;
6162 	}
6163 
6164 	ql_dbg(ql_dbg_tgt, base_vha, 0xe03b,
6165 	    "Registering target for host %ld(%p).\n", base_vha->host_no, ha);
6166 
6167 	BUG_ON(base_vha->vha_tgt.qla_tgt != NULL);
6168 
6169 	tgt = kzalloc(sizeof(struct qla_tgt), GFP_KERNEL);
6170 	if (!tgt) {
6171 		ql_dbg(ql_dbg_tgt, base_vha, 0xe066,
6172 		    "Unable to allocate struct qla_tgt\n");
6173 		return -ENOMEM;
6174 	}
6175 
6176 	tgt->qphints = kzalloc((ha->max_qpairs + 1) *
6177 	    sizeof(struct qla_qpair_hint), GFP_KERNEL);
6178 	if (!tgt->qphints) {
6179 		kfree(tgt);
6180 		ql_log(ql_log_warn, base_vha, 0x0197,
6181 		    "Unable to allocate qpair hints.\n");
6182 		return -ENOMEM;
6183 	}
6184 
6185 	if (!(base_vha->host->hostt->supported_mode & MODE_TARGET))
6186 		base_vha->host->hostt->supported_mode |= MODE_TARGET;
6187 
6188 	rc = btree_init64(&tgt->lun_qpair_map);
6189 	if (rc) {
6190 		kfree(tgt->qphints);
6191 		kfree(tgt);
6192 		ql_log(ql_log_info, base_vha, 0x0198,
6193 			"Unable to initialize lun_qpair_map btree\n");
6194 		return -EIO;
6195 	}
6196 	h = &tgt->qphints[0];
6197 	h->qpair = ha->base_qpair;
6198 	INIT_LIST_HEAD(&h->hint_elem);
6199 	h->cpuid = ha->base_qpair->cpuid;
6200 	list_add_tail(&h->hint_elem, &ha->base_qpair->hints_list);
6201 
6202 	for (i = 0; i < ha->max_qpairs; i++) {
6203 		unsigned long flags;
6204 
6205 		struct qla_qpair *qpair = ha->queue_pair_map[i];
6206 		h = &tgt->qphints[i + 1];
6207 		INIT_LIST_HEAD(&h->hint_elem);
6208 		if (qpair) {
6209 			h->qpair = qpair;
6210 			spin_lock_irqsave(qpair->qp_lock_ptr, flags);
6211 			list_add_tail(&h->hint_elem, &qpair->hints_list);
6212 			spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
6213 			h->cpuid = qpair->cpuid;
6214 		}
6215 	}
6216 
6217 	tgt->ha = ha;
6218 	tgt->vha = base_vha;
6219 	init_waitqueue_head(&tgt->waitQ);
6220 	INIT_LIST_HEAD(&tgt->del_sess_list);
6221 	spin_lock_init(&tgt->sess_work_lock);
6222 	INIT_WORK(&tgt->sess_work, qlt_sess_work_fn);
6223 	INIT_LIST_HEAD(&tgt->sess_works_list);
6224 	atomic_set(&tgt->tgt_global_resets_count, 0);
6225 
6226 	base_vha->vha_tgt.qla_tgt = tgt;
6227 
6228 	ql_dbg(ql_dbg_tgt, base_vha, 0xe067,
6229 		"qla_target(%d): using 64 Bit PCI addressing",
6230 		base_vha->vp_idx);
6231 	/* 3 is reserved */
6232 	tgt->sg_tablesize = QLA_TGT_MAX_SG_24XX(base_vha->req->length - 3);
6233 
6234 	mutex_lock(&qla_tgt_mutex);
6235 	list_add_tail(&tgt->tgt_list_entry, &qla_tgt_glist);
6236 	mutex_unlock(&qla_tgt_mutex);
6237 
6238 	if (ha->tgt.tgt_ops && ha->tgt.tgt_ops->add_target)
6239 		ha->tgt.tgt_ops->add_target(base_vha);
6240 
6241 	return 0;
6242 }
6243 
6244 /* Must be called under tgt_host_action_mutex */
6245 int qlt_remove_target(struct qla_hw_data *ha, struct scsi_qla_host *vha)
6246 {
6247 	if (!vha->vha_tgt.qla_tgt)
6248 		return 0;
6249 
6250 	if (vha->fc_vport) {
6251 		qlt_release(vha->vha_tgt.qla_tgt);
6252 		return 0;
6253 	}
6254 
6255 	/* free left over qfull cmds */
6256 	qlt_init_term_exchange(vha);
6257 
6258 	ql_dbg(ql_dbg_tgt, vha, 0xe03c, "Unregistering target for host %ld(%p)",
6259 	    vha->host_no, ha);
6260 	qlt_release(vha->vha_tgt.qla_tgt);
6261 
6262 	return 0;
6263 }
6264 
6265 void qlt_remove_target_resources(struct qla_hw_data *ha)
6266 {
6267 	struct scsi_qla_host *node;
6268 	u32 key = 0;
6269 
6270 	btree_for_each_safe32(&ha->tgt.host_map, key, node)
6271 		btree_remove32(&ha->tgt.host_map, key);
6272 
6273 	btree_destroy32(&ha->tgt.host_map);
6274 }
6275 
6276 static void qlt_lport_dump(struct scsi_qla_host *vha, u64 wwpn,
6277 	unsigned char *b)
6278 {
6279 	int i;
6280 
6281 	pr_debug("qla2xxx HW vha->node_name: ");
6282 	for (i = 0; i < WWN_SIZE; i++)
6283 		pr_debug("%02x ", vha->node_name[i]);
6284 	pr_debug("\n");
6285 	pr_debug("qla2xxx HW vha->port_name: ");
6286 	for (i = 0; i < WWN_SIZE; i++)
6287 		pr_debug("%02x ", vha->port_name[i]);
6288 	pr_debug("\n");
6289 
6290 	pr_debug("qla2xxx passed configfs WWPN: ");
6291 	put_unaligned_be64(wwpn, b);
6292 	for (i = 0; i < WWN_SIZE; i++)
6293 		pr_debug("%02x ", b[i]);
6294 	pr_debug("\n");
6295 }
6296 
6297 /**
6298  * qla_tgt_lport_register - register lport with external module
6299  *
6300  * @qla_tgt_ops: Pointer for tcm_qla2xxx qla_tgt_ops
6301  * @wwpn: Passwd FC target WWPN
6302  * @callback:  lport initialization callback for tcm_qla2xxx code
6303  * @target_lport_ptr: pointer for tcm_qla2xxx specific lport data
6304  */
6305 int qlt_lport_register(void *target_lport_ptr, u64 phys_wwpn,
6306 		       u64 npiv_wwpn, u64 npiv_wwnn,
6307 		       int (*callback)(struct scsi_qla_host *, void *, u64, u64))
6308 {
6309 	struct qla_tgt *tgt;
6310 	struct scsi_qla_host *vha;
6311 	struct qla_hw_data *ha;
6312 	struct Scsi_Host *host;
6313 	unsigned long flags;
6314 	int rc;
6315 	u8 b[WWN_SIZE];
6316 
6317 	mutex_lock(&qla_tgt_mutex);
6318 	list_for_each_entry(tgt, &qla_tgt_glist, tgt_list_entry) {
6319 		vha = tgt->vha;
6320 		ha = vha->hw;
6321 
6322 		host = vha->host;
6323 		if (!host)
6324 			continue;
6325 
6326 		if (!(host->hostt->supported_mode & MODE_TARGET))
6327 			continue;
6328 
6329 		spin_lock_irqsave(&ha->hardware_lock, flags);
6330 		if ((!npiv_wwpn || !npiv_wwnn) && host->active_mode & MODE_TARGET) {
6331 			pr_debug("MODE_TARGET already active on qla2xxx(%d)\n",
6332 			    host->host_no);
6333 			spin_unlock_irqrestore(&ha->hardware_lock, flags);
6334 			continue;
6335 		}
6336 		if (tgt->tgt_stop) {
6337 			pr_debug("MODE_TARGET in shutdown on qla2xxx(%d)\n",
6338 				 host->host_no);
6339 			spin_unlock_irqrestore(&ha->hardware_lock, flags);
6340 			continue;
6341 		}
6342 		spin_unlock_irqrestore(&ha->hardware_lock, flags);
6343 
6344 		if (!scsi_host_get(host)) {
6345 			ql_dbg(ql_dbg_tgt, vha, 0xe068,
6346 			    "Unable to scsi_host_get() for"
6347 			    " qla2xxx scsi_host\n");
6348 			continue;
6349 		}
6350 		qlt_lport_dump(vha, phys_wwpn, b);
6351 
6352 		if (memcmp(vha->port_name, b, WWN_SIZE)) {
6353 			scsi_host_put(host);
6354 			continue;
6355 		}
6356 		rc = (*callback)(vha, target_lport_ptr, npiv_wwpn, npiv_wwnn);
6357 		if (rc != 0)
6358 			scsi_host_put(host);
6359 
6360 		mutex_unlock(&qla_tgt_mutex);
6361 		return rc;
6362 	}
6363 	mutex_unlock(&qla_tgt_mutex);
6364 
6365 	return -ENODEV;
6366 }
6367 EXPORT_SYMBOL(qlt_lport_register);
6368 
6369 /**
6370  * qla_tgt_lport_deregister - Degister lport
6371  *
6372  * @vha:  Registered scsi_qla_host pointer
6373  */
6374 void qlt_lport_deregister(struct scsi_qla_host *vha)
6375 {
6376 	struct qla_hw_data *ha = vha->hw;
6377 	struct Scsi_Host *sh = vha->host;
6378 	/*
6379 	 * Clear the target_lport_ptr qla_target_template pointer in qla_hw_data
6380 	 */
6381 	vha->vha_tgt.target_lport_ptr = NULL;
6382 	ha->tgt.tgt_ops = NULL;
6383 	/*
6384 	 * Release the Scsi_Host reference for the underlying qla2xxx host
6385 	 */
6386 	scsi_host_put(sh);
6387 }
6388 EXPORT_SYMBOL(qlt_lport_deregister);
6389 
6390 /* Must be called under HW lock */
6391 static void qlt_set_mode(struct scsi_qla_host *vha)
6392 {
6393 	switch (ql2x_ini_mode) {
6394 	case QLA2XXX_INI_MODE_DISABLED:
6395 	case QLA2XXX_INI_MODE_EXCLUSIVE:
6396 		vha->host->active_mode = MODE_TARGET;
6397 		break;
6398 	case QLA2XXX_INI_MODE_ENABLED:
6399 		vha->host->active_mode = MODE_UNKNOWN;
6400 		break;
6401 	case QLA2XXX_INI_MODE_DUAL:
6402 		vha->host->active_mode = MODE_DUAL;
6403 		break;
6404 	default:
6405 		break;
6406 	}
6407 }
6408 
6409 /* Must be called under HW lock */
6410 static void qlt_clear_mode(struct scsi_qla_host *vha)
6411 {
6412 	switch (ql2x_ini_mode) {
6413 	case QLA2XXX_INI_MODE_DISABLED:
6414 		vha->host->active_mode = MODE_UNKNOWN;
6415 		break;
6416 	case QLA2XXX_INI_MODE_EXCLUSIVE:
6417 		vha->host->active_mode = MODE_INITIATOR;
6418 		break;
6419 	case QLA2XXX_INI_MODE_ENABLED:
6420 	case QLA2XXX_INI_MODE_DUAL:
6421 		vha->host->active_mode = MODE_INITIATOR;
6422 		break;
6423 	default:
6424 		break;
6425 	}
6426 }
6427 
6428 /*
6429  * qla_tgt_enable_vha - NO LOCK HELD
6430  *
6431  * host_reset, bring up w/ Target Mode Enabled
6432  */
6433 void
6434 qlt_enable_vha(struct scsi_qla_host *vha)
6435 {
6436 	struct qla_hw_data *ha = vha->hw;
6437 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
6438 	unsigned long flags;
6439 	scsi_qla_host_t *base_vha = pci_get_drvdata(ha->pdev);
6440 
6441 	if (!tgt) {
6442 		ql_dbg(ql_dbg_tgt, vha, 0xe069,
6443 		    "Unable to locate qla_tgt pointer from"
6444 		    " struct qla_hw_data\n");
6445 		dump_stack();
6446 		return;
6447 	}
6448 
6449 	spin_lock_irqsave(&ha->hardware_lock, flags);
6450 	tgt->tgt_stopped = 0;
6451 	qlt_set_mode(vha);
6452 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
6453 
6454 	if (vha->vp_idx) {
6455 		qla24xx_disable_vp(vha);
6456 		qla24xx_enable_vp(vha);
6457 	} else {
6458 		set_bit(ISP_ABORT_NEEDED, &base_vha->dpc_flags);
6459 		qla2xxx_wake_dpc(base_vha);
6460 		qla2x00_wait_for_hba_online(base_vha);
6461 	}
6462 }
6463 EXPORT_SYMBOL(qlt_enable_vha);
6464 
6465 /*
6466  * qla_tgt_disable_vha - NO LOCK HELD
6467  *
6468  * Disable Target Mode and reset the adapter
6469  */
6470 static void qlt_disable_vha(struct scsi_qla_host *vha)
6471 {
6472 	struct qla_hw_data *ha = vha->hw;
6473 	struct qla_tgt *tgt = vha->vha_tgt.qla_tgt;
6474 	unsigned long flags;
6475 
6476 	if (!tgt) {
6477 		ql_dbg(ql_dbg_tgt, vha, 0xe06a,
6478 		    "Unable to locate qla_tgt pointer from"
6479 		    " struct qla_hw_data\n");
6480 		dump_stack();
6481 		return;
6482 	}
6483 
6484 	spin_lock_irqsave(&ha->hardware_lock, flags);
6485 	qlt_clear_mode(vha);
6486 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
6487 
6488 	set_bit(ISP_ABORT_NEEDED, &vha->dpc_flags);
6489 	qla2xxx_wake_dpc(vha);
6490 	qla2x00_wait_for_hba_online(vha);
6491 }
6492 
6493 /*
6494  * Called from qla_init.c:qla24xx_vport_create() contex to setup
6495  * the target mode specific struct scsi_qla_host and struct qla_hw_data
6496  * members.
6497  */
6498 void
6499 qlt_vport_create(struct scsi_qla_host *vha, struct qla_hw_data *ha)
6500 {
6501 	vha->vha_tgt.qla_tgt = NULL;
6502 
6503 	mutex_init(&vha->vha_tgt.tgt_mutex);
6504 	mutex_init(&vha->vha_tgt.tgt_host_action_mutex);
6505 
6506 	qlt_clear_mode(vha);
6507 
6508 	/*
6509 	 * NOTE: Currently the value is kept the same for <24xx and
6510 	 * >=24xx ISPs. If it is necessary to change it,
6511 	 * the check should be added for specific ISPs,
6512 	 * assigning the value appropriately.
6513 	 */
6514 	ha->tgt.atio_q_length = ATIO_ENTRY_CNT_24XX;
6515 
6516 	qlt_add_target(ha, vha);
6517 }
6518 
6519 u8
6520 qlt_rff_id(struct scsi_qla_host *vha)
6521 {
6522 	u8 fc4_feature = 0;
6523 	/*
6524 	 * FC-4 Feature bit 0 indicates target functionality to the name server.
6525 	 */
6526 	if (qla_tgt_mode_enabled(vha)) {
6527 		fc4_feature = BIT_0;
6528 	} else if (qla_ini_mode_enabled(vha)) {
6529 		fc4_feature = BIT_1;
6530 	} else if (qla_dual_mode_enabled(vha))
6531 		fc4_feature = BIT_0 | BIT_1;
6532 
6533 	return fc4_feature;
6534 }
6535 
6536 /*
6537  * qlt_init_atio_q_entries() - Initializes ATIO queue entries.
6538  * @ha: HA context
6539  *
6540  * Beginning of ATIO ring has initialization control block already built
6541  * by nvram config routine.
6542  *
6543  * Returns 0 on success.
6544  */
6545 void
6546 qlt_init_atio_q_entries(struct scsi_qla_host *vha)
6547 {
6548 	struct qla_hw_data *ha = vha->hw;
6549 	uint16_t cnt;
6550 	struct atio_from_isp *pkt = (struct atio_from_isp *)ha->tgt.atio_ring;
6551 
6552 	if (qla_ini_mode_enabled(vha))
6553 		return;
6554 
6555 	for (cnt = 0; cnt < ha->tgt.atio_q_length; cnt++) {
6556 		pkt->u.raw.signature = ATIO_PROCESSED;
6557 		pkt++;
6558 	}
6559 
6560 }
6561 
6562 /*
6563  * qlt_24xx_process_atio_queue() - Process ATIO queue entries.
6564  * @ha: SCSI driver HA context
6565  */
6566 void
6567 qlt_24xx_process_atio_queue(struct scsi_qla_host *vha, uint8_t ha_locked)
6568 {
6569 	struct qla_hw_data *ha = vha->hw;
6570 	struct atio_from_isp *pkt;
6571 	int cnt, i;
6572 
6573 	if (!ha->flags.fw_started)
6574 		return;
6575 
6576 	while ((ha->tgt.atio_ring_ptr->signature != ATIO_PROCESSED) ||
6577 	    fcpcmd_is_corrupted(ha->tgt.atio_ring_ptr)) {
6578 		pkt = (struct atio_from_isp *)ha->tgt.atio_ring_ptr;
6579 		cnt = pkt->u.raw.entry_count;
6580 
6581 		if (unlikely(fcpcmd_is_corrupted(ha->tgt.atio_ring_ptr))) {
6582 			/*
6583 			 * This packet is corrupted. The header + payload
6584 			 * can not be trusted. There is no point in passing
6585 			 * it further up.
6586 			 */
6587 			ql_log(ql_log_warn, vha, 0xd03c,
6588 			    "corrupted fcp frame SID[%3phN] OXID[%04x] EXCG[%x] %64phN\n",
6589 			    pkt->u.isp24.fcp_hdr.s_id,
6590 			    be16_to_cpu(pkt->u.isp24.fcp_hdr.ox_id),
6591 			    le32_to_cpu(pkt->u.isp24.exchange_addr), pkt);
6592 
6593 			adjust_corrupted_atio(pkt);
6594 			qlt_send_term_exchange(ha->base_qpair, NULL, pkt,
6595 			    ha_locked, 0);
6596 		} else {
6597 			qlt_24xx_atio_pkt_all_vps(vha,
6598 			    (struct atio_from_isp *)pkt, ha_locked);
6599 		}
6600 
6601 		for (i = 0; i < cnt; i++) {
6602 			ha->tgt.atio_ring_index++;
6603 			if (ha->tgt.atio_ring_index == ha->tgt.atio_q_length) {
6604 				ha->tgt.atio_ring_index = 0;
6605 				ha->tgt.atio_ring_ptr = ha->tgt.atio_ring;
6606 			} else
6607 				ha->tgt.atio_ring_ptr++;
6608 
6609 			pkt->u.raw.signature = ATIO_PROCESSED;
6610 			pkt = (struct atio_from_isp *)ha->tgt.atio_ring_ptr;
6611 		}
6612 		wmb();
6613 	}
6614 
6615 	/* Adjust ring index */
6616 	WRT_REG_DWORD(ISP_ATIO_Q_OUT(vha), ha->tgt.atio_ring_index);
6617 }
6618 
6619 void
6620 qlt_24xx_config_rings(struct scsi_qla_host *vha)
6621 {
6622 	struct qla_hw_data *ha = vha->hw;
6623 	struct qla_msix_entry *msix = &ha->msix_entries[2];
6624 	struct init_cb_24xx *icb = (struct init_cb_24xx *)ha->init_cb;
6625 
6626 	if (!QLA_TGT_MODE_ENABLED())
6627 		return;
6628 
6629 	WRT_REG_DWORD(ISP_ATIO_Q_IN(vha), 0);
6630 	WRT_REG_DWORD(ISP_ATIO_Q_OUT(vha), 0);
6631 	RD_REG_DWORD(ISP_ATIO_Q_OUT(vha));
6632 
6633 	if (ha->flags.msix_enabled) {
6634 		if (IS_QLA83XX(ha) || IS_QLA27XX(ha)) {
6635 			if (IS_QLA2071(ha)) {
6636 				/* 4 ports Baker: Enable Interrupt Handshake */
6637 				icb->msix_atio = 0;
6638 				icb->firmware_options_2 |= BIT_26;
6639 			} else {
6640 				icb->msix_atio = cpu_to_le16(msix->entry);
6641 				icb->firmware_options_2 &= ~BIT_26;
6642 			}
6643 			ql_dbg(ql_dbg_init, vha, 0xf072,
6644 			    "Registering ICB vector 0x%x for atio que.\n",
6645 			    msix->entry);
6646 		}
6647 	} else {
6648 		/* INTx|MSI */
6649 		if (IS_QLA83XX(ha) || IS_QLA27XX(ha)) {
6650 			icb->msix_atio = 0;
6651 			icb->firmware_options_2 |= BIT_26;
6652 			ql_dbg(ql_dbg_init, vha, 0xf072,
6653 			    "%s: Use INTx for ATIOQ.\n", __func__);
6654 		}
6655 	}
6656 }
6657 
6658 void
6659 qlt_24xx_config_nvram_stage1(struct scsi_qla_host *vha, struct nvram_24xx *nv)
6660 {
6661 	struct qla_hw_data *ha = vha->hw;
6662 	u32 tmp;
6663 
6664 	if (!QLA_TGT_MODE_ENABLED())
6665 		return;
6666 
6667 	if (qla_tgt_mode_enabled(vha) || qla_dual_mode_enabled(vha)) {
6668 		if (!ha->tgt.saved_set) {
6669 			/* We save only once */
6670 			ha->tgt.saved_exchange_count = nv->exchange_count;
6671 			ha->tgt.saved_firmware_options_1 =
6672 			    nv->firmware_options_1;
6673 			ha->tgt.saved_firmware_options_2 =
6674 			    nv->firmware_options_2;
6675 			ha->tgt.saved_firmware_options_3 =
6676 			    nv->firmware_options_3;
6677 			ha->tgt.saved_set = 1;
6678 		}
6679 
6680 		if (qla_tgt_mode_enabled(vha))
6681 			nv->exchange_count = cpu_to_le16(0xFFFF);
6682 		else			/* dual */
6683 			nv->exchange_count = cpu_to_le16(ql2xexchoffld);
6684 
6685 		/* Enable target mode */
6686 		nv->firmware_options_1 |= cpu_to_le32(BIT_4);
6687 
6688 		/* Disable ini mode, if requested */
6689 		if (qla_tgt_mode_enabled(vha))
6690 			nv->firmware_options_1 |= cpu_to_le32(BIT_5);
6691 
6692 		/* Disable Full Login after LIP */
6693 		nv->firmware_options_1 &= cpu_to_le32(~BIT_13);
6694 		/* Enable initial LIP */
6695 		nv->firmware_options_1 &= cpu_to_le32(~BIT_9);
6696 		if (ql2xtgt_tape_enable)
6697 			/* Enable FC Tape support */
6698 			nv->firmware_options_2 |= cpu_to_le32(BIT_12);
6699 		else
6700 			/* Disable FC Tape support */
6701 			nv->firmware_options_2 &= cpu_to_le32(~BIT_12);
6702 
6703 		/* Disable Full Login after LIP */
6704 		nv->host_p &= cpu_to_le32(~BIT_10);
6705 
6706 		/*
6707 		 * clear BIT 15 explicitly as we have seen at least
6708 		 * a couple of instances where this was set and this
6709 		 * was causing the firmware to not be initialized.
6710 		 */
6711 		nv->firmware_options_1 &= cpu_to_le32(~BIT_15);
6712 		/* Enable target PRLI control */
6713 		nv->firmware_options_2 |= cpu_to_le32(BIT_14);
6714 
6715 		if (IS_QLA25XX(ha)) {
6716 			/* Change Loop-prefer to Pt-Pt */
6717 			tmp = ~(BIT_4|BIT_5|BIT_6);
6718 			nv->firmware_options_2 &= cpu_to_le32(tmp);
6719 			tmp = P2P << 4;
6720 			nv->firmware_options_2 |= cpu_to_le32(tmp);
6721 		}
6722 	} else {
6723 		if (ha->tgt.saved_set) {
6724 			nv->exchange_count = ha->tgt.saved_exchange_count;
6725 			nv->firmware_options_1 =
6726 			    ha->tgt.saved_firmware_options_1;
6727 			nv->firmware_options_2 =
6728 			    ha->tgt.saved_firmware_options_2;
6729 			nv->firmware_options_3 =
6730 			    ha->tgt.saved_firmware_options_3;
6731 		}
6732 		return;
6733 	}
6734 
6735 	if (ha->base_qpair->enable_class_2) {
6736 		if (vha->flags.init_done)
6737 			fc_host_supported_classes(vha->host) =
6738 				FC_COS_CLASS2 | FC_COS_CLASS3;
6739 
6740 		nv->firmware_options_2 |= cpu_to_le32(BIT_8);
6741 	} else {
6742 		if (vha->flags.init_done)
6743 			fc_host_supported_classes(vha->host) = FC_COS_CLASS3;
6744 
6745 		nv->firmware_options_2 &= ~cpu_to_le32(BIT_8);
6746 	}
6747 }
6748 
6749 void
6750 qlt_24xx_config_nvram_stage2(struct scsi_qla_host *vha,
6751 	struct init_cb_24xx *icb)
6752 {
6753 	struct qla_hw_data *ha = vha->hw;
6754 
6755 	if (!QLA_TGT_MODE_ENABLED())
6756 		return;
6757 
6758 	if (ha->tgt.node_name_set) {
6759 		memcpy(icb->node_name, ha->tgt.tgt_node_name, WWN_SIZE);
6760 		icb->firmware_options_1 |= cpu_to_le32(BIT_14);
6761 	}
6762 
6763 	/* disable ZIO at start time. */
6764 	if (!vha->flags.init_done) {
6765 		uint32_t tmp;
6766 		tmp = le32_to_cpu(icb->firmware_options_2);
6767 		tmp &= ~(BIT_3 | BIT_2 | BIT_1 | BIT_0);
6768 		icb->firmware_options_2 = cpu_to_le32(tmp);
6769 	}
6770 }
6771 
6772 void
6773 qlt_81xx_config_nvram_stage1(struct scsi_qla_host *vha, struct nvram_81xx *nv)
6774 {
6775 	struct qla_hw_data *ha = vha->hw;
6776 	u32 tmp;
6777 
6778 	if (!QLA_TGT_MODE_ENABLED())
6779 		return;
6780 
6781 	if (qla_tgt_mode_enabled(vha) || qla_dual_mode_enabled(vha)) {
6782 		if (!ha->tgt.saved_set) {
6783 			/* We save only once */
6784 			ha->tgt.saved_exchange_count = nv->exchange_count;
6785 			ha->tgt.saved_firmware_options_1 =
6786 			    nv->firmware_options_1;
6787 			ha->tgt.saved_firmware_options_2 =
6788 			    nv->firmware_options_2;
6789 			ha->tgt.saved_firmware_options_3 =
6790 			    nv->firmware_options_3;
6791 			ha->tgt.saved_set = 1;
6792 		}
6793 
6794 		if (qla_tgt_mode_enabled(vha))
6795 			nv->exchange_count = cpu_to_le16(0xFFFF);
6796 		else			/* dual */
6797 			nv->exchange_count = cpu_to_le16(ql2xexchoffld);
6798 
6799 		/* Enable target mode */
6800 		nv->firmware_options_1 |= cpu_to_le32(BIT_4);
6801 
6802 		/* Disable ini mode, if requested */
6803 		if (qla_tgt_mode_enabled(vha))
6804 			nv->firmware_options_1 |= cpu_to_le32(BIT_5);
6805 		/* Disable Full Login after LIP */
6806 		nv->firmware_options_1 &= cpu_to_le32(~BIT_13);
6807 		/* Enable initial LIP */
6808 		nv->firmware_options_1 &= cpu_to_le32(~BIT_9);
6809 		/*
6810 		 * clear BIT 15 explicitly as we have seen at
6811 		 * least a couple of instances where this was set
6812 		 * and this was causing the firmware to not be
6813 		 * initialized.
6814 		 */
6815 		nv->firmware_options_1 &= cpu_to_le32(~BIT_15);
6816 		if (ql2xtgt_tape_enable)
6817 			/* Enable FC tape support */
6818 			nv->firmware_options_2 |= cpu_to_le32(BIT_12);
6819 		else
6820 			/* Disable FC tape support */
6821 			nv->firmware_options_2 &= cpu_to_le32(~BIT_12);
6822 
6823 		/* Disable Full Login after LIP */
6824 		nv->host_p &= cpu_to_le32(~BIT_10);
6825 		/* Enable target PRLI control */
6826 		nv->firmware_options_2 |= cpu_to_le32(BIT_14);
6827 
6828 		/* Change Loop-prefer to Pt-Pt */
6829 		tmp = ~(BIT_4|BIT_5|BIT_6);
6830 		nv->firmware_options_2 &= cpu_to_le32(tmp);
6831 		tmp = P2P << 4;
6832 		nv->firmware_options_2 |= cpu_to_le32(tmp);
6833 	} else {
6834 		if (ha->tgt.saved_set) {
6835 			nv->exchange_count = ha->tgt.saved_exchange_count;
6836 			nv->firmware_options_1 =
6837 			    ha->tgt.saved_firmware_options_1;
6838 			nv->firmware_options_2 =
6839 			    ha->tgt.saved_firmware_options_2;
6840 			nv->firmware_options_3 =
6841 			    ha->tgt.saved_firmware_options_3;
6842 		}
6843 		return;
6844 	}
6845 
6846 	if (ha->base_qpair->enable_class_2) {
6847 		if (vha->flags.init_done)
6848 			fc_host_supported_classes(vha->host) =
6849 				FC_COS_CLASS2 | FC_COS_CLASS3;
6850 
6851 		nv->firmware_options_2 |= cpu_to_le32(BIT_8);
6852 	} else {
6853 		if (vha->flags.init_done)
6854 			fc_host_supported_classes(vha->host) = FC_COS_CLASS3;
6855 
6856 		nv->firmware_options_2 &= ~cpu_to_le32(BIT_8);
6857 	}
6858 }
6859 
6860 void
6861 qlt_81xx_config_nvram_stage2(struct scsi_qla_host *vha,
6862 	struct init_cb_81xx *icb)
6863 {
6864 	struct qla_hw_data *ha = vha->hw;
6865 
6866 	if (!QLA_TGT_MODE_ENABLED())
6867 		return;
6868 
6869 	if (ha->tgt.node_name_set) {
6870 		memcpy(icb->node_name, ha->tgt.tgt_node_name, WWN_SIZE);
6871 		icb->firmware_options_1 |= cpu_to_le32(BIT_14);
6872 	}
6873 
6874 	/* disable ZIO at start time. */
6875 	if (!vha->flags.init_done) {
6876 		uint32_t tmp;
6877 		tmp = le32_to_cpu(icb->firmware_options_2);
6878 		tmp &= ~(BIT_3 | BIT_2 | BIT_1 | BIT_0);
6879 		icb->firmware_options_2 = cpu_to_le32(tmp);
6880 	}
6881 
6882 }
6883 
6884 void
6885 qlt_83xx_iospace_config(struct qla_hw_data *ha)
6886 {
6887 	if (!QLA_TGT_MODE_ENABLED())
6888 		return;
6889 
6890 	ha->msix_count += 1; /* For ATIO Q */
6891 }
6892 
6893 
6894 void
6895 qlt_modify_vp_config(struct scsi_qla_host *vha,
6896 	struct vp_config_entry_24xx *vpmod)
6897 {
6898 	/* enable target mode.  Bit5 = 1 => disable */
6899 	if (qla_tgt_mode_enabled(vha) || qla_dual_mode_enabled(vha))
6900 		vpmod->options_idx1 &= ~BIT_5;
6901 
6902 	/* Disable ini mode, if requested.  bit4 = 1 => disable */
6903 	if (qla_tgt_mode_enabled(vha))
6904 		vpmod->options_idx1 &= ~BIT_4;
6905 }
6906 
6907 void
6908 qlt_probe_one_stage1(struct scsi_qla_host *base_vha, struct qla_hw_data *ha)
6909 {
6910 	int rc;
6911 
6912 	if (!QLA_TGT_MODE_ENABLED())
6913 		return;
6914 
6915 	if  ((ql2xenablemsix == 0) || IS_QLA83XX(ha) || IS_QLA27XX(ha)) {
6916 		ISP_ATIO_Q_IN(base_vha) = &ha->mqiobase->isp25mq.atio_q_in;
6917 		ISP_ATIO_Q_OUT(base_vha) = &ha->mqiobase->isp25mq.atio_q_out;
6918 	} else {
6919 		ISP_ATIO_Q_IN(base_vha) = &ha->iobase->isp24.atio_q_in;
6920 		ISP_ATIO_Q_OUT(base_vha) = &ha->iobase->isp24.atio_q_out;
6921 	}
6922 
6923 	mutex_init(&base_vha->vha_tgt.tgt_mutex);
6924 	mutex_init(&base_vha->vha_tgt.tgt_host_action_mutex);
6925 
6926 	INIT_LIST_HEAD(&base_vha->unknown_atio_list);
6927 	INIT_DELAYED_WORK(&base_vha->unknown_atio_work,
6928 	    qlt_unknown_atio_work_fn);
6929 
6930 	qlt_clear_mode(base_vha);
6931 
6932 	rc = btree_init32(&ha->tgt.host_map);
6933 	if (rc)
6934 		ql_log(ql_log_info, base_vha, 0xd03d,
6935 		    "Unable to initialize ha->host_map btree\n");
6936 
6937 	qlt_update_vp_map(base_vha, SET_VP_IDX);
6938 }
6939 
6940 irqreturn_t
6941 qla83xx_msix_atio_q(int irq, void *dev_id)
6942 {
6943 	struct rsp_que *rsp;
6944 	scsi_qla_host_t	*vha;
6945 	struct qla_hw_data *ha;
6946 	unsigned long flags;
6947 
6948 	rsp = (struct rsp_que *) dev_id;
6949 	ha = rsp->hw;
6950 	vha = pci_get_drvdata(ha->pdev);
6951 
6952 	spin_lock_irqsave(&ha->tgt.atio_lock, flags);
6953 
6954 	qlt_24xx_process_atio_queue(vha, 0);
6955 
6956 	spin_unlock_irqrestore(&ha->tgt.atio_lock, flags);
6957 
6958 	return IRQ_HANDLED;
6959 }
6960 
6961 static void
6962 qlt_handle_abts_recv_work(struct work_struct *work)
6963 {
6964 	struct qla_tgt_sess_op *op = container_of(work,
6965 		struct qla_tgt_sess_op, work);
6966 	scsi_qla_host_t *vha = op->vha;
6967 	struct qla_hw_data *ha = vha->hw;
6968 	unsigned long flags;
6969 
6970 	if (qla2x00_reset_active(vha) ||
6971 	    (op->chip_reset != ha->base_qpair->chip_reset))
6972 		return;
6973 
6974 	spin_lock_irqsave(&ha->tgt.atio_lock, flags);
6975 	qlt_24xx_process_atio_queue(vha, 0);
6976 	spin_unlock_irqrestore(&ha->tgt.atio_lock, flags);
6977 
6978 	spin_lock_irqsave(&ha->hardware_lock, flags);
6979 	qlt_response_pkt_all_vps(vha, op->rsp, (response_t *)&op->atio);
6980 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
6981 
6982 	kfree(op);
6983 }
6984 
6985 void
6986 qlt_handle_abts_recv(struct scsi_qla_host *vha, struct rsp_que *rsp,
6987     response_t *pkt)
6988 {
6989 	struct qla_tgt_sess_op *op;
6990 
6991 	op = kzalloc(sizeof(*op), GFP_ATOMIC);
6992 
6993 	if (!op) {
6994 		/* do not reach for ATIO queue here.  This is best effort err
6995 		 * recovery at this point.
6996 		 */
6997 		qlt_response_pkt_all_vps(vha, rsp, pkt);
6998 		return;
6999 	}
7000 
7001 	memcpy(&op->atio, pkt, sizeof(*pkt));
7002 	op->vha = vha;
7003 	op->chip_reset = vha->hw->base_qpair->chip_reset;
7004 	op->rsp = rsp;
7005 	INIT_WORK(&op->work, qlt_handle_abts_recv_work);
7006 	queue_work(qla_tgt_wq, &op->work);
7007 	return;
7008 }
7009 
7010 int
7011 qlt_mem_alloc(struct qla_hw_data *ha)
7012 {
7013 	if (!QLA_TGT_MODE_ENABLED())
7014 		return 0;
7015 
7016 	ha->tgt.tgt_vp_map = kzalloc(sizeof(struct qla_tgt_vp_map) *
7017 	    MAX_MULTI_ID_FABRIC, GFP_KERNEL);
7018 	if (!ha->tgt.tgt_vp_map)
7019 		return -ENOMEM;
7020 
7021 	ha->tgt.atio_ring = dma_alloc_coherent(&ha->pdev->dev,
7022 	    (ha->tgt.atio_q_length + 1) * sizeof(struct atio_from_isp),
7023 	    &ha->tgt.atio_dma, GFP_KERNEL);
7024 	if (!ha->tgt.atio_ring) {
7025 		kfree(ha->tgt.tgt_vp_map);
7026 		return -ENOMEM;
7027 	}
7028 	return 0;
7029 }
7030 
7031 void
7032 qlt_mem_free(struct qla_hw_data *ha)
7033 {
7034 	if (!QLA_TGT_MODE_ENABLED())
7035 		return;
7036 
7037 	if (ha->tgt.atio_ring) {
7038 		dma_free_coherent(&ha->pdev->dev, (ha->tgt.atio_q_length + 1) *
7039 		    sizeof(struct atio_from_isp), ha->tgt.atio_ring,
7040 		    ha->tgt.atio_dma);
7041 	}
7042 	kfree(ha->tgt.tgt_vp_map);
7043 }
7044 
7045 /* vport_slock to be held by the caller */
7046 void
7047 qlt_update_vp_map(struct scsi_qla_host *vha, int cmd)
7048 {
7049 	void *slot;
7050 	u32 key;
7051 	int rc;
7052 
7053 	if (!QLA_TGT_MODE_ENABLED())
7054 		return;
7055 
7056 	key = vha->d_id.b24;
7057 
7058 	switch (cmd) {
7059 	case SET_VP_IDX:
7060 		vha->hw->tgt.tgt_vp_map[vha->vp_idx].vha = vha;
7061 		break;
7062 	case SET_AL_PA:
7063 		slot = btree_lookup32(&vha->hw->tgt.host_map, key);
7064 		if (!slot) {
7065 			ql_dbg(ql_dbg_tgt_mgt, vha, 0xf018,
7066 			    "Save vha in host_map %p %06x\n", vha, key);
7067 			rc = btree_insert32(&vha->hw->tgt.host_map,
7068 				key, vha, GFP_ATOMIC);
7069 			if (rc)
7070 				ql_log(ql_log_info, vha, 0xd03e,
7071 				    "Unable to insert s_id into host_map: %06x\n",
7072 				    key);
7073 			return;
7074 		}
7075 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf019,
7076 		    "replace existing vha in host_map %p %06x\n", vha, key);
7077 		btree_update32(&vha->hw->tgt.host_map, key, vha);
7078 		break;
7079 	case RESET_VP_IDX:
7080 		vha->hw->tgt.tgt_vp_map[vha->vp_idx].vha = NULL;
7081 		break;
7082 	case RESET_AL_PA:
7083 		ql_dbg(ql_dbg_tgt_mgt, vha, 0xf01a,
7084 		   "clear vha in host_map %p %06x\n", vha, key);
7085 		slot = btree_lookup32(&vha->hw->tgt.host_map, key);
7086 		if (slot)
7087 			btree_remove32(&vha->hw->tgt.host_map, key);
7088 		vha->d_id.b24 = 0;
7089 		break;
7090 	}
7091 }
7092 
7093 void qlt_update_host_map(struct scsi_qla_host *vha, port_id_t id)
7094 {
7095 
7096 	if (!vha->d_id.b24) {
7097 		vha->d_id = id;
7098 		qlt_update_vp_map(vha, SET_AL_PA);
7099 	} else if (vha->d_id.b24 != id.b24) {
7100 		qlt_update_vp_map(vha, RESET_AL_PA);
7101 		vha->d_id = id;
7102 		qlt_update_vp_map(vha, SET_AL_PA);
7103 	}
7104 }
7105 
7106 static int __init qlt_parse_ini_mode(void)
7107 {
7108 	if (strcasecmp(qlini_mode, QLA2XXX_INI_MODE_STR_EXCLUSIVE) == 0)
7109 		ql2x_ini_mode = QLA2XXX_INI_MODE_EXCLUSIVE;
7110 	else if (strcasecmp(qlini_mode, QLA2XXX_INI_MODE_STR_DISABLED) == 0)
7111 		ql2x_ini_mode = QLA2XXX_INI_MODE_DISABLED;
7112 	else if (strcasecmp(qlini_mode, QLA2XXX_INI_MODE_STR_ENABLED) == 0)
7113 		ql2x_ini_mode = QLA2XXX_INI_MODE_ENABLED;
7114 	else if (strcasecmp(qlini_mode, QLA2XXX_INI_MODE_STR_DUAL) == 0)
7115 		ql2x_ini_mode = QLA2XXX_INI_MODE_DUAL;
7116 	else
7117 		return false;
7118 
7119 	return true;
7120 }
7121 
7122 int __init qlt_init(void)
7123 {
7124 	int ret;
7125 
7126 	if (!qlt_parse_ini_mode()) {
7127 		ql_log(ql_log_fatal, NULL, 0xe06b,
7128 		    "qlt_parse_ini_mode() failed\n");
7129 		return -EINVAL;
7130 	}
7131 
7132 	if (!QLA_TGT_MODE_ENABLED())
7133 		return 0;
7134 
7135 	qla_tgt_mgmt_cmd_cachep = kmem_cache_create("qla_tgt_mgmt_cmd_cachep",
7136 	    sizeof(struct qla_tgt_mgmt_cmd), __alignof__(struct
7137 	    qla_tgt_mgmt_cmd), 0, NULL);
7138 	if (!qla_tgt_mgmt_cmd_cachep) {
7139 		ql_log(ql_log_fatal, NULL, 0xd04b,
7140 		    "kmem_cache_create for qla_tgt_mgmt_cmd_cachep failed\n");
7141 		return -ENOMEM;
7142 	}
7143 
7144 	qla_tgt_plogi_cachep = kmem_cache_create("qla_tgt_plogi_cachep",
7145 	    sizeof(struct qlt_plogi_ack_t), __alignof__(struct qlt_plogi_ack_t),
7146 	    0, NULL);
7147 
7148 	if (!qla_tgt_plogi_cachep) {
7149 		ql_log(ql_log_fatal, NULL, 0xe06d,
7150 		    "kmem_cache_create for qla_tgt_plogi_cachep failed\n");
7151 		ret = -ENOMEM;
7152 		goto out_mgmt_cmd_cachep;
7153 	}
7154 
7155 	qla_tgt_mgmt_cmd_mempool = mempool_create(25, mempool_alloc_slab,
7156 	    mempool_free_slab, qla_tgt_mgmt_cmd_cachep);
7157 	if (!qla_tgt_mgmt_cmd_mempool) {
7158 		ql_log(ql_log_fatal, NULL, 0xe06e,
7159 		    "mempool_create for qla_tgt_mgmt_cmd_mempool failed\n");
7160 		ret = -ENOMEM;
7161 		goto out_plogi_cachep;
7162 	}
7163 
7164 	qla_tgt_wq = alloc_workqueue("qla_tgt_wq", 0, 0);
7165 	if (!qla_tgt_wq) {
7166 		ql_log(ql_log_fatal, NULL, 0xe06f,
7167 		    "alloc_workqueue for qla_tgt_wq failed\n");
7168 		ret = -ENOMEM;
7169 		goto out_cmd_mempool;
7170 	}
7171 	/*
7172 	 * Return 1 to signal that initiator-mode is being disabled
7173 	 */
7174 	return (ql2x_ini_mode == QLA2XXX_INI_MODE_DISABLED) ? 1 : 0;
7175 
7176 out_cmd_mempool:
7177 	mempool_destroy(qla_tgt_mgmt_cmd_mempool);
7178 out_plogi_cachep:
7179 	kmem_cache_destroy(qla_tgt_plogi_cachep);
7180 out_mgmt_cmd_cachep:
7181 	kmem_cache_destroy(qla_tgt_mgmt_cmd_cachep);
7182 	return ret;
7183 }
7184 
7185 void qlt_exit(void)
7186 {
7187 	if (!QLA_TGT_MODE_ENABLED())
7188 		return;
7189 
7190 	destroy_workqueue(qla_tgt_wq);
7191 	mempool_destroy(qla_tgt_mgmt_cmd_mempool);
7192 	kmem_cache_destroy(qla_tgt_plogi_cachep);
7193 	kmem_cache_destroy(qla_tgt_mgmt_cmd_cachep);
7194 }
7195