xref: /linux/drivers/scsi/qla2xxx/qla_init.c (revision 1a2ac6d7ecdcde74a4e16f31de64124160fc7237)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * QLogic Fibre Channel HBA Driver
4  * Copyright (c)  2003-2014 QLogic Corporation
5  */
6 #include "qla_def.h"
7 #include "qla_gbl.h"
8 
9 #include <linux/delay.h>
10 #include <linux/slab.h>
11 #include <linux/vmalloc.h>
12 
13 #include "qla_devtbl.h"
14 
15 #ifdef CONFIG_SPARC
16 #include <asm/prom.h>
17 #endif
18 
19 #include "qla_target.h"
20 
21 /*
22 *  QLogic ISP2x00 Hardware Support Function Prototypes.
23 */
24 static int qla2x00_isp_firmware(scsi_qla_host_t *);
25 static int qla2x00_setup_chip(scsi_qla_host_t *);
26 static int qla2x00_fw_ready(scsi_qla_host_t *);
27 static int qla2x00_configure_hba(scsi_qla_host_t *);
28 static int qla2x00_configure_loop(scsi_qla_host_t *);
29 static int qla2x00_configure_local_loop(scsi_qla_host_t *);
30 static int qla2x00_configure_fabric(scsi_qla_host_t *);
31 static int qla2x00_find_all_fabric_devs(scsi_qla_host_t *);
32 static int qla2x00_restart_isp(scsi_qla_host_t *);
33 
34 static struct qla_chip_state_84xx *qla84xx_get_chip(struct scsi_qla_host *);
35 static int qla84xx_init_chip(scsi_qla_host_t *);
36 static int qla25xx_init_queues(struct qla_hw_data *);
37 static void qla24xx_handle_gpdb_event(scsi_qla_host_t *vha,
38 				      struct event_arg *ea);
39 static void qla24xx_handle_prli_done_event(struct scsi_qla_host *,
40     struct event_arg *);
41 static void __qla24xx_handle_gpdb_event(scsi_qla_host_t *, struct event_arg *);
42 
43 /* SRB Extensions ---------------------------------------------------------- */
44 
45 void
46 qla2x00_sp_timeout(struct timer_list *t)
47 {
48 	srb_t *sp = from_timer(sp, t, u.iocb_cmd.timer);
49 	struct srb_iocb *iocb;
50 	scsi_qla_host_t *vha = sp->vha;
51 
52 	WARN_ON(irqs_disabled());
53 	iocb = &sp->u.iocb_cmd;
54 	iocb->timeout(sp);
55 
56 	/* ref: TMR */
57 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
58 
59 	if (vha && qla2x00_isp_reg_stat(vha->hw)) {
60 		ql_log(ql_log_info, vha, 0x9008,
61 		    "PCI/Register disconnect.\n");
62 		qla_pci_set_eeh_busy(vha);
63 	}
64 }
65 
66 void qla2x00_sp_free(srb_t *sp)
67 {
68 	struct srb_iocb *iocb = &sp->u.iocb_cmd;
69 
70 	del_timer(&iocb->timer);
71 	qla2x00_rel_sp(sp);
72 }
73 
74 void qla2xxx_rel_done_warning(srb_t *sp, int res)
75 {
76 	WARN_ONCE(1, "Calling done() of an already freed srb %p object\n", sp);
77 }
78 
79 void qla2xxx_rel_free_warning(srb_t *sp)
80 {
81 	WARN_ONCE(1, "Calling free() of an already freed srb %p object\n", sp);
82 }
83 
84 /* Asynchronous Login/Logout Routines -------------------------------------- */
85 
86 unsigned long
87 qla2x00_get_async_timeout(struct scsi_qla_host *vha)
88 {
89 	unsigned long tmo;
90 	struct qla_hw_data *ha = vha->hw;
91 
92 	/* Firmware should use switch negotiated r_a_tov for timeout. */
93 	tmo = ha->r_a_tov / 10 * 2;
94 	if (IS_QLAFX00(ha)) {
95 		tmo = FX00_DEF_RATOV * 2;
96 	} else if (!IS_FWI2_CAPABLE(ha)) {
97 		/*
98 		 * Except for earlier ISPs where the timeout is seeded from the
99 		 * initialization control block.
100 		 */
101 		tmo = ha->login_timeout;
102 	}
103 	return tmo;
104 }
105 
106 static void qla24xx_abort_iocb_timeout(void *data)
107 {
108 	srb_t *sp = data;
109 	struct srb_iocb *abt = &sp->u.iocb_cmd;
110 	struct qla_qpair *qpair = sp->qpair;
111 	u32 handle;
112 	unsigned long flags;
113 	int sp_found = 0, cmdsp_found = 0;
114 
115 	if (sp->cmd_sp)
116 		ql_dbg(ql_dbg_async, sp->vha, 0x507c,
117 		    "Abort timeout - cmd hdl=%x, cmd type=%x hdl=%x, type=%x\n",
118 		    sp->cmd_sp->handle, sp->cmd_sp->type,
119 		    sp->handle, sp->type);
120 	else
121 		ql_dbg(ql_dbg_async, sp->vha, 0x507c,
122 		    "Abort timeout 2 - hdl=%x, type=%x\n",
123 		    sp->handle, sp->type);
124 
125 	spin_lock_irqsave(qpair->qp_lock_ptr, flags);
126 	for (handle = 1; handle < qpair->req->num_outstanding_cmds; handle++) {
127 		if (sp->cmd_sp && (qpair->req->outstanding_cmds[handle] ==
128 		    sp->cmd_sp)) {
129 			qpair->req->outstanding_cmds[handle] = NULL;
130 			cmdsp_found = 1;
131 			qla_put_fw_resources(qpair, &sp->cmd_sp->iores);
132 		}
133 
134 		/* removing the abort */
135 		if (qpair->req->outstanding_cmds[handle] == sp) {
136 			qpair->req->outstanding_cmds[handle] = NULL;
137 			sp_found = 1;
138 			qla_put_fw_resources(qpair, &sp->iores);
139 			break;
140 		}
141 	}
142 	spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
143 
144 	if (cmdsp_found && sp->cmd_sp) {
145 		/*
146 		 * This done function should take care of
147 		 * original command ref: INIT
148 		 */
149 		sp->cmd_sp->done(sp->cmd_sp, QLA_OS_TIMER_EXPIRED);
150 	}
151 
152 	if (sp_found) {
153 		abt->u.abt.comp_status = cpu_to_le16(CS_TIMEOUT);
154 		sp->done(sp, QLA_OS_TIMER_EXPIRED);
155 	}
156 }
157 
158 static void qla24xx_abort_sp_done(srb_t *sp, int res)
159 {
160 	struct srb_iocb *abt = &sp->u.iocb_cmd;
161 	srb_t *orig_sp = sp->cmd_sp;
162 
163 	if (orig_sp)
164 		qla_wait_nvme_release_cmd_kref(orig_sp);
165 
166 	if (sp->flags & SRB_WAKEUP_ON_COMP)
167 		complete(&abt->u.abt.comp);
168 	else
169 		/* ref: INIT */
170 		kref_put(&sp->cmd_kref, qla2x00_sp_release);
171 }
172 
173 int qla24xx_async_abort_cmd(srb_t *cmd_sp, bool wait)
174 {
175 	scsi_qla_host_t *vha = cmd_sp->vha;
176 	struct srb_iocb *abt_iocb;
177 	srb_t *sp;
178 	int rval = QLA_FUNCTION_FAILED;
179 
180 	/* ref: INIT for ABTS command */
181 	sp = qla2xxx_get_qpair_sp(cmd_sp->vha, cmd_sp->qpair, cmd_sp->fcport,
182 				  GFP_ATOMIC);
183 	if (!sp)
184 		return QLA_MEMORY_ALLOC_FAILED;
185 
186 	qla_vha_mark_busy(vha);
187 	abt_iocb = &sp->u.iocb_cmd;
188 	sp->type = SRB_ABT_CMD;
189 	sp->name = "abort";
190 	sp->qpair = cmd_sp->qpair;
191 	sp->cmd_sp = cmd_sp;
192 	if (wait)
193 		sp->flags = SRB_WAKEUP_ON_COMP;
194 
195 	init_completion(&abt_iocb->u.abt.comp);
196 	/* FW can send 2 x ABTS's timeout/20s */
197 	qla2x00_init_async_sp(sp, 42, qla24xx_abort_sp_done);
198 	sp->u.iocb_cmd.timeout = qla24xx_abort_iocb_timeout;
199 
200 	abt_iocb->u.abt.cmd_hndl = cmd_sp->handle;
201 	abt_iocb->u.abt.req_que_no = cpu_to_le16(cmd_sp->qpair->req->id);
202 
203 	ql_dbg(ql_dbg_async, vha, 0x507c,
204 	       "Abort command issued - hdl=%x, type=%x\n", cmd_sp->handle,
205 	       cmd_sp->type);
206 
207 	rval = qla2x00_start_sp(sp);
208 	if (rval != QLA_SUCCESS) {
209 		/* ref: INIT */
210 		kref_put(&sp->cmd_kref, qla2x00_sp_release);
211 		return rval;
212 	}
213 
214 	if (wait) {
215 		wait_for_completion(&abt_iocb->u.abt.comp);
216 		rval = abt_iocb->u.abt.comp_status == CS_COMPLETE ?
217 			QLA_SUCCESS : QLA_ERR_FROM_FW;
218 		/* ref: INIT */
219 		kref_put(&sp->cmd_kref, qla2x00_sp_release);
220 	}
221 
222 	return rval;
223 }
224 
225 void
226 qla2x00_async_iocb_timeout(void *data)
227 {
228 	srb_t *sp = data;
229 	fc_port_t *fcport = sp->fcport;
230 	struct srb_iocb *lio = &sp->u.iocb_cmd;
231 	int rc, h;
232 	unsigned long flags;
233 
234 	if (fcport) {
235 		ql_dbg(ql_dbg_disc, fcport->vha, 0x2071,
236 		    "Async-%s timeout - hdl=%x portid=%06x %8phC.\n",
237 		    sp->name, sp->handle, fcport->d_id.b24, fcport->port_name);
238 
239 		fcport->flags &= ~(FCF_ASYNC_SENT | FCF_ASYNC_ACTIVE);
240 	} else {
241 		pr_info("Async-%s timeout - hdl=%x.\n",
242 		    sp->name, sp->handle);
243 	}
244 
245 	switch (sp->type) {
246 	case SRB_LOGIN_CMD:
247 		rc = qla24xx_async_abort_cmd(sp, false);
248 		if (rc) {
249 			/* Retry as needed. */
250 			lio->u.logio.data[0] = MBS_COMMAND_ERROR;
251 			lio->u.logio.data[1] =
252 				lio->u.logio.flags & SRB_LOGIN_RETRIED ?
253 				QLA_LOGIO_LOGIN_RETRIED : 0;
254 			spin_lock_irqsave(sp->qpair->qp_lock_ptr, flags);
255 			for (h = 1; h < sp->qpair->req->num_outstanding_cmds;
256 			    h++) {
257 				if (sp->qpair->req->outstanding_cmds[h] ==
258 				    sp) {
259 					sp->qpair->req->outstanding_cmds[h] =
260 					    NULL;
261 					break;
262 				}
263 			}
264 			spin_unlock_irqrestore(sp->qpair->qp_lock_ptr, flags);
265 			sp->done(sp, QLA_FUNCTION_TIMEOUT);
266 		}
267 		break;
268 	case SRB_LOGOUT_CMD:
269 	case SRB_CT_PTHRU_CMD:
270 	case SRB_MB_IOCB:
271 	case SRB_NACK_PLOGI:
272 	case SRB_NACK_PRLI:
273 	case SRB_NACK_LOGO:
274 	case SRB_CTRL_VP:
275 	default:
276 		rc = qla24xx_async_abort_cmd(sp, false);
277 		if (rc) {
278 			spin_lock_irqsave(sp->qpair->qp_lock_ptr, flags);
279 			for (h = 1; h < sp->qpair->req->num_outstanding_cmds;
280 			    h++) {
281 				if (sp->qpair->req->outstanding_cmds[h] ==
282 				    sp) {
283 					sp->qpair->req->outstanding_cmds[h] =
284 					    NULL;
285 					break;
286 				}
287 			}
288 			spin_unlock_irqrestore(sp->qpair->qp_lock_ptr, flags);
289 			sp->done(sp, QLA_FUNCTION_TIMEOUT);
290 		}
291 		break;
292 	}
293 }
294 
295 static void qla2x00_async_login_sp_done(srb_t *sp, int res)
296 {
297 	struct scsi_qla_host *vha = sp->vha;
298 	struct srb_iocb *lio = &sp->u.iocb_cmd;
299 	struct event_arg ea;
300 
301 	ql_dbg(ql_dbg_disc, vha, 0x20dd,
302 	    "%s %8phC res %d \n", __func__, sp->fcport->port_name, res);
303 
304 	sp->fcport->flags &= ~(FCF_ASYNC_SENT | FCF_ASYNC_ACTIVE);
305 
306 	if (!test_bit(UNLOADING, &vha->dpc_flags)) {
307 		memset(&ea, 0, sizeof(ea));
308 		ea.fcport = sp->fcport;
309 		ea.data[0] = lio->u.logio.data[0];
310 		ea.data[1] = lio->u.logio.data[1];
311 		ea.iop[0] = lio->u.logio.iop[0];
312 		ea.iop[1] = lio->u.logio.iop[1];
313 		ea.sp = sp;
314 		if (res)
315 			ea.data[0] = MBS_COMMAND_ERROR;
316 		qla24xx_handle_plogi_done_event(vha, &ea);
317 	}
318 
319 	/* ref: INIT */
320 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
321 }
322 
323 int
324 qla2x00_async_login(struct scsi_qla_host *vha, fc_port_t *fcport,
325     uint16_t *data)
326 {
327 	srb_t *sp;
328 	struct srb_iocb *lio;
329 	int rval = QLA_FUNCTION_FAILED;
330 
331 	if (!vha->flags.online || (fcport->flags & FCF_ASYNC_SENT) ||
332 	    fcport->loop_id == FC_NO_LOOP_ID) {
333 		ql_log(ql_log_warn, vha, 0xffff,
334 		    "%s: %8phC - not sending command.\n",
335 		    __func__, fcport->port_name);
336 		return rval;
337 	}
338 
339 	/* ref: INIT */
340 	sp = qla2x00_get_sp(vha, fcport, GFP_KERNEL);
341 	if (!sp)
342 		goto done;
343 
344 	qla2x00_set_fcport_disc_state(fcport, DSC_LOGIN_PEND);
345 	fcport->flags |= FCF_ASYNC_SENT;
346 	fcport->logout_completed = 0;
347 
348 	sp->type = SRB_LOGIN_CMD;
349 	sp->name = "login";
350 	sp->gen1 = fcport->rscn_gen;
351 	sp->gen2 = fcport->login_gen;
352 	qla2x00_init_async_sp(sp, qla2x00_get_async_timeout(vha) + 2,
353 			      qla2x00_async_login_sp_done);
354 
355 	lio = &sp->u.iocb_cmd;
356 	if (N2N_TOPO(fcport->vha->hw) && fcport_is_bigger(fcport)) {
357 		lio->u.logio.flags |= SRB_LOGIN_PRLI_ONLY;
358 	} else {
359 		if (vha->hw->flags.edif_enabled &&
360 		    DBELL_ACTIVE(vha)) {
361 			lio->u.logio.flags |=
362 				(SRB_LOGIN_FCSP | SRB_LOGIN_SKIP_PRLI);
363 		} else {
364 			lio->u.logio.flags |= SRB_LOGIN_COND_PLOGI;
365 		}
366 	}
367 
368 	if (NVME_TARGET(vha->hw, fcport))
369 		lio->u.logio.flags |= SRB_LOGIN_SKIP_PRLI;
370 
371 	rval = qla2x00_start_sp(sp);
372 
373 	ql_dbg(ql_dbg_disc, vha, 0x2072,
374 	       "Async-login - %8phC hdl=%x, loopid=%x portid=%06x retries=%d %s.\n",
375 	       fcport->port_name, sp->handle, fcport->loop_id,
376 	       fcport->d_id.b24, fcport->login_retry,
377 	       lio->u.logio.flags & SRB_LOGIN_FCSP ? "FCSP" : "");
378 
379 	if (rval != QLA_SUCCESS) {
380 		fcport->flags |= FCF_LOGIN_NEEDED;
381 		set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
382 		goto done_free_sp;
383 	}
384 
385 	return rval;
386 
387 done_free_sp:
388 	/* ref: INIT */
389 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
390 	fcport->flags &= ~FCF_ASYNC_SENT;
391 done:
392 	fcport->flags &= ~FCF_ASYNC_ACTIVE;
393 
394 	/*
395 	 * async login failed. Could be due to iocb/exchange resource
396 	 * being low. Set state DELETED for re-login process to start again.
397 	 */
398 	qla2x00_set_fcport_disc_state(fcport, DSC_DELETED);
399 	return rval;
400 }
401 
402 static void qla2x00_async_logout_sp_done(srb_t *sp, int res)
403 {
404 	sp->fcport->flags &= ~(FCF_ASYNC_SENT | FCF_ASYNC_ACTIVE);
405 	sp->fcport->login_gen++;
406 	qlt_logo_completion_handler(sp->fcport, sp->u.iocb_cmd.u.logio.data[0]);
407 	/* ref: INIT */
408 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
409 }
410 
411 int
412 qla2x00_async_logout(struct scsi_qla_host *vha, fc_port_t *fcport)
413 {
414 	srb_t *sp;
415 	int rval = QLA_FUNCTION_FAILED;
416 
417 	fcport->flags |= FCF_ASYNC_SENT;
418 	/* ref: INIT */
419 	sp = qla2x00_get_sp(vha, fcport, GFP_KERNEL);
420 	if (!sp)
421 		goto done;
422 
423 	sp->type = SRB_LOGOUT_CMD;
424 	sp->name = "logout";
425 	qla2x00_init_async_sp(sp, qla2x00_get_async_timeout(vha) + 2,
426 			      qla2x00_async_logout_sp_done),
427 
428 	ql_dbg(ql_dbg_disc, vha, 0x2070,
429 	    "Async-logout - hdl=%x loop-id=%x portid=%02x%02x%02x %8phC explicit %d.\n",
430 	    sp->handle, fcport->loop_id, fcport->d_id.b.domain,
431 		fcport->d_id.b.area, fcport->d_id.b.al_pa,
432 		fcport->port_name, fcport->explicit_logout);
433 
434 	rval = qla2x00_start_sp(sp);
435 	if (rval != QLA_SUCCESS)
436 		goto done_free_sp;
437 	return rval;
438 
439 done_free_sp:
440 	/* ref: INIT */
441 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
442 done:
443 	fcport->flags &= ~(FCF_ASYNC_SENT | FCF_ASYNC_ACTIVE);
444 	return rval;
445 }
446 
447 void
448 qla2x00_async_prlo_done(struct scsi_qla_host *vha, fc_port_t *fcport,
449     uint16_t *data)
450 {
451 	fcport->flags &= ~FCF_ASYNC_ACTIVE;
452 	/* Don't re-login in target mode */
453 	if (!fcport->tgt_session)
454 		qla2x00_mark_device_lost(vha, fcport, 1);
455 	qlt_logo_completion_handler(fcport, data[0]);
456 }
457 
458 static void qla2x00_async_prlo_sp_done(srb_t *sp, int res)
459 {
460 	struct srb_iocb *lio = &sp->u.iocb_cmd;
461 	struct scsi_qla_host *vha = sp->vha;
462 
463 	sp->fcport->flags &= ~FCF_ASYNC_ACTIVE;
464 	if (!test_bit(UNLOADING, &vha->dpc_flags))
465 		qla2x00_post_async_prlo_done_work(sp->fcport->vha, sp->fcport,
466 		    lio->u.logio.data);
467 	/* ref: INIT */
468 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
469 }
470 
471 int
472 qla2x00_async_prlo(struct scsi_qla_host *vha, fc_port_t *fcport)
473 {
474 	srb_t *sp;
475 	int rval;
476 
477 	rval = QLA_FUNCTION_FAILED;
478 	/* ref: INIT */
479 	sp = qla2x00_get_sp(vha, fcport, GFP_KERNEL);
480 	if (!sp)
481 		goto done;
482 
483 	sp->type = SRB_PRLO_CMD;
484 	sp->name = "prlo";
485 	qla2x00_init_async_sp(sp, qla2x00_get_async_timeout(vha) + 2,
486 			      qla2x00_async_prlo_sp_done);
487 
488 	ql_dbg(ql_dbg_disc, vha, 0x2070,
489 	    "Async-prlo - hdl=%x loop-id=%x portid=%02x%02x%02x.\n",
490 	    sp->handle, fcport->loop_id, fcport->d_id.b.domain,
491 	    fcport->d_id.b.area, fcport->d_id.b.al_pa);
492 
493 	rval = qla2x00_start_sp(sp);
494 	if (rval != QLA_SUCCESS)
495 		goto done_free_sp;
496 
497 	return rval;
498 
499 done_free_sp:
500 	/* ref: INIT */
501 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
502 done:
503 	fcport->flags &= ~FCF_ASYNC_ACTIVE;
504 	return rval;
505 }
506 
507 static
508 void qla24xx_handle_adisc_event(scsi_qla_host_t *vha, struct event_arg *ea)
509 {
510 	struct fc_port *fcport = ea->fcport;
511 
512 	ql_dbg(ql_dbg_disc, vha, 0x20d2,
513 	    "%s %8phC DS %d LS %d rc %d login %d|%d rscn %d|%d lid %d\n",
514 	    __func__, fcport->port_name, fcport->disc_state,
515 	    fcport->fw_login_state, ea->rc, fcport->login_gen, ea->sp->gen2,
516 	    fcport->rscn_gen, ea->sp->gen1, fcport->loop_id);
517 
518 	WARN_ONCE(!qla2xxx_is_valid_mbs(ea->data[0]), "mbs: %#x\n",
519 		  ea->data[0]);
520 
521 	if (ea->data[0] != MBS_COMMAND_COMPLETE) {
522 		ql_dbg(ql_dbg_disc, vha, 0x2066,
523 		    "%s %8phC: adisc fail: post delete\n",
524 		    __func__, ea->fcport->port_name);
525 		/* deleted = 0 & logout_on_delete = force fw cleanup */
526 		fcport->deleted = 0;
527 		fcport->logout_on_delete = 1;
528 		qlt_schedule_sess_for_deletion(ea->fcport);
529 		return;
530 	}
531 
532 	if (ea->fcport->disc_state == DSC_DELETE_PEND)
533 		return;
534 
535 	if (ea->sp->gen2 != ea->fcport->login_gen) {
536 		/* target side must have changed it. */
537 		ql_dbg(ql_dbg_disc, vha, 0x20d3,
538 		    "%s %8phC generation changed\n",
539 		    __func__, ea->fcport->port_name);
540 		return;
541 	} else if (ea->sp->gen1 != ea->fcport->rscn_gen) {
542 		qla_rscn_replay(fcport);
543 		qlt_schedule_sess_for_deletion(fcport);
544 		return;
545 	}
546 
547 	__qla24xx_handle_gpdb_event(vha, ea);
548 }
549 
550 static int qla_post_els_plogi_work(struct scsi_qla_host *vha, fc_port_t *fcport)
551 {
552 	struct qla_work_evt *e;
553 
554 	e = qla2x00_alloc_work(vha, QLA_EVT_ELS_PLOGI);
555 	if (!e)
556 		return QLA_FUNCTION_FAILED;
557 
558 	e->u.fcport.fcport = fcport;
559 	fcport->flags |= FCF_ASYNC_ACTIVE;
560 	qla2x00_set_fcport_disc_state(fcport, DSC_LOGIN_PEND);
561 	return qla2x00_post_work(vha, e);
562 }
563 
564 static void qla2x00_async_adisc_sp_done(srb_t *sp, int res)
565 {
566 	struct scsi_qla_host *vha = sp->vha;
567 	struct event_arg ea;
568 	struct srb_iocb *lio = &sp->u.iocb_cmd;
569 
570 	ql_dbg(ql_dbg_disc, vha, 0x2066,
571 	    "Async done-%s res %x %8phC\n",
572 	    sp->name, res, sp->fcport->port_name);
573 
574 	sp->fcport->flags &= ~(FCF_ASYNC_SENT | FCF_ASYNC_ACTIVE);
575 
576 	memset(&ea, 0, sizeof(ea));
577 	ea.rc = res;
578 	ea.data[0] = lio->u.logio.data[0];
579 	ea.data[1] = lio->u.logio.data[1];
580 	ea.iop[0] = lio->u.logio.iop[0];
581 	ea.iop[1] = lio->u.logio.iop[1];
582 	ea.fcport = sp->fcport;
583 	ea.sp = sp;
584 	if (res)
585 		ea.data[0] = MBS_COMMAND_ERROR;
586 
587 	qla24xx_handle_adisc_event(vha, &ea);
588 	/* ref: INIT */
589 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
590 }
591 
592 int
593 qla2x00_async_adisc(struct scsi_qla_host *vha, fc_port_t *fcport,
594     uint16_t *data)
595 {
596 	srb_t *sp;
597 	struct srb_iocb *lio;
598 	int rval = QLA_FUNCTION_FAILED;
599 
600 	if (IS_SESSION_DELETED(fcport)) {
601 		ql_log(ql_log_warn, vha, 0xffff,
602 		       "%s: %8phC is being delete - not sending command.\n",
603 		       __func__, fcport->port_name);
604 		fcport->flags &= ~FCF_ASYNC_ACTIVE;
605 		return rval;
606 	}
607 
608 	if (!vha->flags.online || (fcport->flags & FCF_ASYNC_SENT))
609 		return rval;
610 
611 	fcport->flags |= FCF_ASYNC_SENT;
612 	/* ref: INIT */
613 	sp = qla2x00_get_sp(vha, fcport, GFP_KERNEL);
614 	if (!sp)
615 		goto done;
616 
617 	sp->type = SRB_ADISC_CMD;
618 	sp->name = "adisc";
619 	sp->gen1 = fcport->rscn_gen;
620 	sp->gen2 = fcport->login_gen;
621 	qla2x00_init_async_sp(sp, qla2x00_get_async_timeout(vha) + 2,
622 			      qla2x00_async_adisc_sp_done);
623 
624 	if (data[1] & QLA_LOGIO_LOGIN_RETRIED) {
625 		lio = &sp->u.iocb_cmd;
626 		lio->u.logio.flags |= SRB_LOGIN_RETRIED;
627 	}
628 
629 	ql_dbg(ql_dbg_disc, vha, 0x206f,
630 	    "Async-adisc - hdl=%x loopid=%x portid=%06x %8phC.\n",
631 	    sp->handle, fcport->loop_id, fcport->d_id.b24, fcport->port_name);
632 
633 	rval = qla2x00_start_sp(sp);
634 	if (rval != QLA_SUCCESS)
635 		goto done_free_sp;
636 
637 	return rval;
638 
639 done_free_sp:
640 	/* ref: INIT */
641 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
642 done:
643 	fcport->flags &= ~(FCF_ASYNC_SENT | FCF_ASYNC_ACTIVE);
644 	qla2x00_post_async_adisc_work(vha, fcport, data);
645 	return rval;
646 }
647 
648 static bool qla2x00_is_reserved_id(scsi_qla_host_t *vha, uint16_t loop_id)
649 {
650 	struct qla_hw_data *ha = vha->hw;
651 
652 	if (IS_FWI2_CAPABLE(ha))
653 		return loop_id > NPH_LAST_HANDLE;
654 
655 	return (loop_id > ha->max_loop_id && loop_id < SNS_FIRST_LOOP_ID) ||
656 		loop_id == MANAGEMENT_SERVER || loop_id == BROADCAST;
657 }
658 
659 /**
660  * qla2x00_find_new_loop_id - scan through our port list and find a new usable loop ID
661  * @vha: adapter state pointer.
662  * @dev: port structure pointer.
663  *
664  * Returns:
665  *	qla2x00 local function return status code.
666  *
667  * Context:
668  *	Kernel context.
669  */
670 static int qla2x00_find_new_loop_id(scsi_qla_host_t *vha, fc_port_t *dev)
671 {
672 	int	rval;
673 	struct qla_hw_data *ha = vha->hw;
674 	unsigned long flags = 0;
675 
676 	rval = QLA_SUCCESS;
677 
678 	spin_lock_irqsave(&ha->vport_slock, flags);
679 
680 	dev->loop_id = find_first_zero_bit(ha->loop_id_map, LOOPID_MAP_SIZE);
681 	if (dev->loop_id >= LOOPID_MAP_SIZE ||
682 	    qla2x00_is_reserved_id(vha, dev->loop_id)) {
683 		dev->loop_id = FC_NO_LOOP_ID;
684 		rval = QLA_FUNCTION_FAILED;
685 	} else {
686 		set_bit(dev->loop_id, ha->loop_id_map);
687 	}
688 	spin_unlock_irqrestore(&ha->vport_slock, flags);
689 
690 	if (rval == QLA_SUCCESS)
691 		ql_dbg(ql_dbg_disc, dev->vha, 0x2086,
692 		       "Assigning new loopid=%x, portid=%x.\n",
693 		       dev->loop_id, dev->d_id.b24);
694 	else
695 		ql_log(ql_log_warn, dev->vha, 0x2087,
696 		       "No loop_id's available, portid=%x.\n",
697 		       dev->d_id.b24);
698 
699 	return rval;
700 }
701 
702 void qla2x00_clear_loop_id(fc_port_t *fcport)
703 {
704 	struct qla_hw_data *ha = fcport->vha->hw;
705 
706 	if (fcport->loop_id == FC_NO_LOOP_ID ||
707 	    qla2x00_is_reserved_id(fcport->vha, fcport->loop_id))
708 		return;
709 
710 	clear_bit(fcport->loop_id, ha->loop_id_map);
711 	fcport->loop_id = FC_NO_LOOP_ID;
712 }
713 
714 static void qla24xx_handle_gnl_done_event(scsi_qla_host_t *vha,
715 	struct event_arg *ea)
716 {
717 	fc_port_t *fcport, *conflict_fcport;
718 	struct get_name_list_extended *e;
719 	u16 i, n, found = 0, loop_id;
720 	port_id_t id;
721 	u64 wwn;
722 	u16 data[2];
723 	u8 current_login_state, nvme_cls;
724 
725 	fcport = ea->fcport;
726 	ql_dbg(ql_dbg_disc, vha, 0xffff,
727 	    "%s %8phC DS %d LS rc %d %d login %d|%d rscn %d|%d lid %d edif %d\n",
728 	    __func__, fcport->port_name, fcport->disc_state,
729 	    fcport->fw_login_state, ea->rc,
730 	    fcport->login_gen, fcport->last_login_gen,
731 	    fcport->rscn_gen, fcport->last_rscn_gen, vha->loop_id, fcport->edif.enable);
732 
733 	if (fcport->disc_state == DSC_DELETE_PEND)
734 		return;
735 
736 	if (ea->rc) { /* rval */
737 		if (fcport->login_retry == 0) {
738 			ql_dbg(ql_dbg_disc, vha, 0x20de,
739 			    "GNL failed Port login retry %8phN, retry cnt=%d.\n",
740 			    fcport->port_name, fcport->login_retry);
741 		}
742 		return;
743 	}
744 
745 	if (fcport->last_rscn_gen != fcport->rscn_gen) {
746 		qla_rscn_replay(fcport);
747 		qlt_schedule_sess_for_deletion(fcport);
748 		return;
749 	} else if (fcport->last_login_gen != fcport->login_gen) {
750 		ql_dbg(ql_dbg_disc, vha, 0x20e0,
751 		    "%s %8phC login gen changed\n",
752 		    __func__, fcport->port_name);
753 		set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
754 		return;
755 	}
756 
757 	n = ea->data[0] / sizeof(struct get_name_list_extended);
758 
759 	ql_dbg(ql_dbg_disc, vha, 0x20e1,
760 	    "%s %d %8phC n %d %02x%02x%02x lid %d \n",
761 	    __func__, __LINE__, fcport->port_name, n,
762 	    fcport->d_id.b.domain, fcport->d_id.b.area,
763 	    fcport->d_id.b.al_pa, fcport->loop_id);
764 
765 	for (i = 0; i < n; i++) {
766 		e = &vha->gnl.l[i];
767 		wwn = wwn_to_u64(e->port_name);
768 		id.b.domain = e->port_id[2];
769 		id.b.area = e->port_id[1];
770 		id.b.al_pa = e->port_id[0];
771 		id.b.rsvd_1 = 0;
772 
773 		if (memcmp((u8 *)&wwn, fcport->port_name, WWN_SIZE))
774 			continue;
775 
776 		if (IS_SW_RESV_ADDR(id))
777 			continue;
778 
779 		found = 1;
780 
781 		loop_id = le16_to_cpu(e->nport_handle);
782 		loop_id = (loop_id & 0x7fff);
783 		nvme_cls = e->current_login_state >> 4;
784 		current_login_state = e->current_login_state & 0xf;
785 
786 		if (PRLI_PHASE(nvme_cls)) {
787 			current_login_state = nvme_cls;
788 			fcport->fc4_type &= ~FS_FC4TYPE_FCP;
789 			fcport->fc4_type |= FS_FC4TYPE_NVME;
790 		} else if (PRLI_PHASE(current_login_state)) {
791 			fcport->fc4_type |= FS_FC4TYPE_FCP;
792 			fcport->fc4_type &= ~FS_FC4TYPE_NVME;
793 		}
794 
795 		ql_dbg(ql_dbg_disc, vha, 0x20e2,
796 		    "%s found %8phC CLS [%x|%x] fc4_type %d ID[%06x|%06x] lid[%d|%d]\n",
797 		    __func__, fcport->port_name,
798 		    e->current_login_state, fcport->fw_login_state,
799 		    fcport->fc4_type, id.b24, fcport->d_id.b24,
800 		    loop_id, fcport->loop_id);
801 
802 		switch (fcport->disc_state) {
803 		case DSC_DELETE_PEND:
804 		case DSC_DELETED:
805 			break;
806 		default:
807 			if ((id.b24 != fcport->d_id.b24 &&
808 			    fcport->d_id.b24 &&
809 			    fcport->loop_id != FC_NO_LOOP_ID) ||
810 			    (fcport->loop_id != FC_NO_LOOP_ID &&
811 				fcport->loop_id != loop_id)) {
812 				ql_dbg(ql_dbg_disc, vha, 0x20e3,
813 				    "%s %d %8phC post del sess\n",
814 				    __func__, __LINE__, fcport->port_name);
815 				if (fcport->n2n_flag)
816 					fcport->d_id.b24 = 0;
817 				qlt_schedule_sess_for_deletion(fcport);
818 				return;
819 			}
820 			break;
821 		}
822 
823 		fcport->loop_id = loop_id;
824 		if (fcport->n2n_flag)
825 			fcport->d_id.b24 = id.b24;
826 
827 		wwn = wwn_to_u64(fcport->port_name);
828 		qlt_find_sess_invalidate_other(vha, wwn,
829 			id, loop_id, &conflict_fcport);
830 
831 		if (conflict_fcport) {
832 			/*
833 			 * Another share fcport share the same loop_id &
834 			 * nport id. Conflict fcport needs to finish
835 			 * cleanup before this fcport can proceed to login.
836 			 */
837 			conflict_fcport->conflict = fcport;
838 			fcport->login_pause = 1;
839 		}
840 
841 		switch (vha->hw->current_topology) {
842 		default:
843 			switch (current_login_state) {
844 			case DSC_LS_PRLI_COMP:
845 				ql_dbg(ql_dbg_disc,
846 				    vha, 0x20e4, "%s %d %8phC post gpdb\n",
847 				    __func__, __LINE__, fcport->port_name);
848 
849 				if ((e->prli_svc_param_word_3[0] & BIT_4) == 0)
850 					fcport->port_type = FCT_INITIATOR;
851 				else
852 					fcport->port_type = FCT_TARGET;
853 				data[0] = data[1] = 0;
854 				qla2x00_post_async_adisc_work(vha, fcport,
855 				    data);
856 				break;
857 			case DSC_LS_PLOGI_COMP:
858 				if (vha->hw->flags.edif_enabled) {
859 					/* check to see if App support Secure */
860 					qla24xx_post_gpdb_work(vha, fcport, 0);
861 					break;
862 				}
863 				fallthrough;
864 			case DSC_LS_PORT_UNAVAIL:
865 			default:
866 				if (fcport->loop_id == FC_NO_LOOP_ID) {
867 					qla2x00_find_new_loop_id(vha, fcport);
868 					fcport->fw_login_state =
869 					    DSC_LS_PORT_UNAVAIL;
870 				}
871 				ql_dbg(ql_dbg_disc, vha, 0x20e5,
872 				    "%s %d %8phC\n", __func__, __LINE__,
873 				    fcport->port_name);
874 				qla24xx_fcport_handle_login(vha, fcport);
875 				break;
876 			}
877 			break;
878 		case ISP_CFG_N:
879 			fcport->fw_login_state = current_login_state;
880 			fcport->d_id = id;
881 			switch (current_login_state) {
882 			case DSC_LS_PRLI_PEND:
883 				/*
884 				 * In the middle of PRLI. Let it finish.
885 				 * Allow relogin code to recheck state again
886 				 * with GNL. Push disc_state back to DELETED
887 				 * so GNL can go out again
888 				 */
889 				qla2x00_set_fcport_disc_state(fcport,
890 				    DSC_DELETED);
891 				set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
892 				break;
893 			case DSC_LS_PRLI_COMP:
894 				if ((e->prli_svc_param_word_3[0] & BIT_4) == 0)
895 					fcport->port_type = FCT_INITIATOR;
896 				else
897 					fcport->port_type = FCT_TARGET;
898 
899 				data[0] = data[1] = 0;
900 				qla2x00_post_async_adisc_work(vha, fcport,
901 				    data);
902 				break;
903 			case DSC_LS_PLOGI_COMP:
904 				if (vha->hw->flags.edif_enabled &&
905 				    DBELL_ACTIVE(vha)) {
906 					/* check to see if App support secure or not */
907 					qla24xx_post_gpdb_work(vha, fcport, 0);
908 					break;
909 				}
910 				if (fcport_is_bigger(fcport)) {
911 					/* local adapter is smaller */
912 					if (fcport->loop_id != FC_NO_LOOP_ID)
913 						qla2x00_clear_loop_id(fcport);
914 
915 					fcport->loop_id = loop_id;
916 					qla24xx_fcport_handle_login(vha,
917 					    fcport);
918 					break;
919 				}
920 				fallthrough;
921 			default:
922 				if (fcport_is_smaller(fcport)) {
923 					/* local adapter is bigger */
924 					if (fcport->loop_id != FC_NO_LOOP_ID)
925 						qla2x00_clear_loop_id(fcport);
926 
927 					fcport->loop_id = loop_id;
928 					qla24xx_fcport_handle_login(vha,
929 					    fcport);
930 				}
931 				break;
932 			}
933 			break;
934 		} /* switch (ha->current_topology) */
935 	}
936 
937 	if (!found) {
938 		switch (vha->hw->current_topology) {
939 		case ISP_CFG_F:
940 		case ISP_CFG_FL:
941 			for (i = 0; i < n; i++) {
942 				e = &vha->gnl.l[i];
943 				id.b.domain = e->port_id[0];
944 				id.b.area = e->port_id[1];
945 				id.b.al_pa = e->port_id[2];
946 				id.b.rsvd_1 = 0;
947 				loop_id = le16_to_cpu(e->nport_handle);
948 
949 				if (fcport->d_id.b24 == id.b24) {
950 					conflict_fcport =
951 					    qla2x00_find_fcport_by_wwpn(vha,
952 						e->port_name, 0);
953 					if (conflict_fcport) {
954 						ql_dbg(ql_dbg_disc + ql_dbg_verbose,
955 						    vha, 0x20e5,
956 						    "%s %d %8phC post del sess\n",
957 						    __func__, __LINE__,
958 						    conflict_fcport->port_name);
959 						qlt_schedule_sess_for_deletion
960 							(conflict_fcport);
961 					}
962 				}
963 				/*
964 				 * FW already picked this loop id for
965 				 * another fcport
966 				 */
967 				if (fcport->loop_id == loop_id)
968 					fcport->loop_id = FC_NO_LOOP_ID;
969 			}
970 			qla24xx_fcport_handle_login(vha, fcport);
971 			break;
972 		case ISP_CFG_N:
973 			qla2x00_set_fcport_disc_state(fcport, DSC_DELETED);
974 			if (time_after_eq(jiffies, fcport->dm_login_expire)) {
975 				if (fcport->n2n_link_reset_cnt < 2) {
976 					fcport->n2n_link_reset_cnt++;
977 					/*
978 					 * remote port is not sending PLOGI.
979 					 * Reset link to kick start his state
980 					 * machine
981 					 */
982 					set_bit(N2N_LINK_RESET,
983 					    &vha->dpc_flags);
984 				} else {
985 					if (fcport->n2n_chip_reset < 1) {
986 						ql_log(ql_log_info, vha, 0x705d,
987 						    "Chip reset to bring laser down");
988 						set_bit(ISP_ABORT_NEEDED,
989 						    &vha->dpc_flags);
990 						fcport->n2n_chip_reset++;
991 					} else {
992 						ql_log(ql_log_info, vha, 0x705d,
993 						    "Remote port %8ph is not coming back\n",
994 						    fcport->port_name);
995 						fcport->scan_state = 0;
996 					}
997 				}
998 				qla2xxx_wake_dpc(vha);
999 			} else {
1000 				/*
1001 				 * report port suppose to do PLOGI. Give him
1002 				 * more time. FW will catch it.
1003 				 */
1004 				set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
1005 			}
1006 			break;
1007 		case ISP_CFG_NL:
1008 			qla24xx_fcport_handle_login(vha, fcport);
1009 			break;
1010 		default:
1011 			break;
1012 		}
1013 	}
1014 } /* gnl_event */
1015 
1016 static void qla24xx_async_gnl_sp_done(srb_t *sp, int res)
1017 {
1018 	struct scsi_qla_host *vha = sp->vha;
1019 	unsigned long flags;
1020 	struct fc_port *fcport = NULL, *tf;
1021 	u16 i, n = 0, loop_id;
1022 	struct event_arg ea;
1023 	struct get_name_list_extended *e;
1024 	u64 wwn;
1025 	struct list_head h;
1026 	bool found = false;
1027 
1028 	ql_dbg(ql_dbg_disc, vha, 0x20e7,
1029 	    "Async done-%s res %x mb[1]=%x mb[2]=%x \n",
1030 	    sp->name, res, sp->u.iocb_cmd.u.mbx.in_mb[1],
1031 	    sp->u.iocb_cmd.u.mbx.in_mb[2]);
1032 
1033 
1034 	sp->fcport->flags &= ~(FCF_ASYNC_SENT|FCF_ASYNC_ACTIVE);
1035 	memset(&ea, 0, sizeof(ea));
1036 	ea.sp = sp;
1037 	ea.rc = res;
1038 
1039 	if (sp->u.iocb_cmd.u.mbx.in_mb[1] >=
1040 	    sizeof(struct get_name_list_extended)) {
1041 		n = sp->u.iocb_cmd.u.mbx.in_mb[1] /
1042 		    sizeof(struct get_name_list_extended);
1043 		ea.data[0] = sp->u.iocb_cmd.u.mbx.in_mb[1]; /* amnt xfered */
1044 	}
1045 
1046 	for (i = 0; i < n; i++) {
1047 		e = &vha->gnl.l[i];
1048 		loop_id = le16_to_cpu(e->nport_handle);
1049 		/* mask out reserve bit */
1050 		loop_id = (loop_id & 0x7fff);
1051 		set_bit(loop_id, vha->hw->loop_id_map);
1052 		wwn = wwn_to_u64(e->port_name);
1053 
1054 		ql_dbg(ql_dbg_disc, vha, 0x20e8,
1055 		    "%s %8phC %02x:%02x:%02x CLS %x/%x lid %x \n",
1056 		    __func__, &wwn, e->port_id[2], e->port_id[1],
1057 		    e->port_id[0], e->current_login_state, e->last_login_state,
1058 		    (loop_id & 0x7fff));
1059 	}
1060 
1061 	spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
1062 
1063 	INIT_LIST_HEAD(&h);
1064 	fcport = tf = NULL;
1065 	if (!list_empty(&vha->gnl.fcports))
1066 		list_splice_init(&vha->gnl.fcports, &h);
1067 	spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
1068 
1069 	list_for_each_entry_safe(fcport, tf, &h, gnl_entry) {
1070 		spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
1071 		list_del_init(&fcport->gnl_entry);
1072 		fcport->flags &= ~(FCF_ASYNC_SENT | FCF_ASYNC_ACTIVE);
1073 		spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
1074 		ea.fcport = fcport;
1075 
1076 		qla24xx_handle_gnl_done_event(vha, &ea);
1077 	}
1078 
1079 	/* create new fcport if fw has knowledge of new sessions */
1080 	for (i = 0; i < n; i++) {
1081 		port_id_t id;
1082 		u64 wwnn;
1083 
1084 		e = &vha->gnl.l[i];
1085 		wwn = wwn_to_u64(e->port_name);
1086 
1087 		found = false;
1088 		list_for_each_entry_safe(fcport, tf, &vha->vp_fcports, list) {
1089 			if (!memcmp((u8 *)&wwn, fcport->port_name,
1090 			    WWN_SIZE)) {
1091 				found = true;
1092 				break;
1093 			}
1094 		}
1095 
1096 		id.b.domain = e->port_id[2];
1097 		id.b.area = e->port_id[1];
1098 		id.b.al_pa = e->port_id[0];
1099 		id.b.rsvd_1 = 0;
1100 
1101 		if (!found && wwn && !IS_SW_RESV_ADDR(id)) {
1102 			ql_dbg(ql_dbg_disc, vha, 0x2065,
1103 			    "%s %d %8phC %06x post new sess\n",
1104 			    __func__, __LINE__, (u8 *)&wwn, id.b24);
1105 			wwnn = wwn_to_u64(e->node_name);
1106 			qla24xx_post_newsess_work(vha, &id, (u8 *)&wwn,
1107 			    (u8 *)&wwnn, NULL, 0);
1108 		}
1109 	}
1110 
1111 	spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
1112 	vha->gnl.sent = 0;
1113 	if (!list_empty(&vha->gnl.fcports)) {
1114 		/* retrigger gnl */
1115 		list_for_each_entry_safe(fcport, tf, &vha->gnl.fcports,
1116 		    gnl_entry) {
1117 			list_del_init(&fcport->gnl_entry);
1118 			fcport->flags &= ~(FCF_ASYNC_SENT | FCF_ASYNC_ACTIVE);
1119 			if (qla24xx_post_gnl_work(vha, fcport) == QLA_SUCCESS)
1120 				break;
1121 		}
1122 	}
1123 	spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
1124 
1125 	/* ref: INIT */
1126 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
1127 }
1128 
1129 int qla24xx_async_gnl(struct scsi_qla_host *vha, fc_port_t *fcport)
1130 {
1131 	srb_t *sp;
1132 	int rval = QLA_FUNCTION_FAILED;
1133 	unsigned long flags;
1134 	u16 *mb;
1135 
1136 	if (!vha->flags.online || (fcport->flags & FCF_ASYNC_SENT))
1137 		return rval;
1138 
1139 	ql_dbg(ql_dbg_disc, vha, 0x20d9,
1140 	    "Async-gnlist WWPN %8phC \n", fcport->port_name);
1141 
1142 	spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
1143 	fcport->flags |= FCF_ASYNC_SENT;
1144 	qla2x00_set_fcport_disc_state(fcport, DSC_GNL);
1145 	fcport->last_rscn_gen = fcport->rscn_gen;
1146 	fcport->last_login_gen = fcport->login_gen;
1147 
1148 	list_add_tail(&fcport->gnl_entry, &vha->gnl.fcports);
1149 	if (vha->gnl.sent) {
1150 		spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
1151 		return QLA_SUCCESS;
1152 	}
1153 	vha->gnl.sent = 1;
1154 	spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
1155 
1156 	/* ref: INIT */
1157 	sp = qla2x00_get_sp(vha, fcport, GFP_KERNEL);
1158 	if (!sp)
1159 		goto done;
1160 
1161 	sp->type = SRB_MB_IOCB;
1162 	sp->name = "gnlist";
1163 	sp->gen1 = fcport->rscn_gen;
1164 	sp->gen2 = fcport->login_gen;
1165 	qla2x00_init_async_sp(sp, qla2x00_get_async_timeout(vha) + 2,
1166 			      qla24xx_async_gnl_sp_done);
1167 
1168 	mb = sp->u.iocb_cmd.u.mbx.out_mb;
1169 	mb[0] = MBC_PORT_NODE_NAME_LIST;
1170 	mb[1] = BIT_2 | BIT_3;
1171 	mb[2] = MSW(vha->gnl.ldma);
1172 	mb[3] = LSW(vha->gnl.ldma);
1173 	mb[6] = MSW(MSD(vha->gnl.ldma));
1174 	mb[7] = LSW(MSD(vha->gnl.ldma));
1175 	mb[8] = vha->gnl.size;
1176 	mb[9] = vha->vp_idx;
1177 
1178 	ql_dbg(ql_dbg_disc, vha, 0x20da,
1179 	    "Async-%s - OUT WWPN %8phC hndl %x\n",
1180 	    sp->name, fcport->port_name, sp->handle);
1181 
1182 	rval = qla2x00_start_sp(sp);
1183 	if (rval != QLA_SUCCESS)
1184 		goto done_free_sp;
1185 
1186 	return rval;
1187 
1188 done_free_sp:
1189 	/* ref: INIT */
1190 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
1191 done:
1192 	fcport->flags &= ~(FCF_ASYNC_ACTIVE | FCF_ASYNC_SENT);
1193 	return rval;
1194 }
1195 
1196 int qla24xx_post_gnl_work(struct scsi_qla_host *vha, fc_port_t *fcport)
1197 {
1198 	struct qla_work_evt *e;
1199 
1200 	e = qla2x00_alloc_work(vha, QLA_EVT_GNL);
1201 	if (!e)
1202 		return QLA_FUNCTION_FAILED;
1203 
1204 	e->u.fcport.fcport = fcport;
1205 	fcport->flags |= FCF_ASYNC_ACTIVE;
1206 	return qla2x00_post_work(vha, e);
1207 }
1208 
1209 static void qla24xx_async_gpdb_sp_done(srb_t *sp, int res)
1210 {
1211 	struct scsi_qla_host *vha = sp->vha;
1212 	struct qla_hw_data *ha = vha->hw;
1213 	fc_port_t *fcport = sp->fcport;
1214 	u16 *mb = sp->u.iocb_cmd.u.mbx.in_mb;
1215 	struct event_arg ea;
1216 
1217 	ql_dbg(ql_dbg_disc, vha, 0x20db,
1218 	    "Async done-%s res %x, WWPN %8phC mb[1]=%x mb[2]=%x \n",
1219 	    sp->name, res, fcport->port_name, mb[1], mb[2]);
1220 
1221 	fcport->flags &= ~(FCF_ASYNC_SENT | FCF_ASYNC_ACTIVE);
1222 
1223 	if (res == QLA_FUNCTION_TIMEOUT)
1224 		goto done;
1225 
1226 	memset(&ea, 0, sizeof(ea));
1227 	ea.fcport = fcport;
1228 	ea.sp = sp;
1229 
1230 	qla24xx_handle_gpdb_event(vha, &ea);
1231 
1232 done:
1233 	dma_pool_free(ha->s_dma_pool, sp->u.iocb_cmd.u.mbx.in,
1234 		sp->u.iocb_cmd.u.mbx.in_dma);
1235 
1236 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
1237 }
1238 
1239 int qla24xx_post_prli_work(struct scsi_qla_host *vha, fc_port_t *fcport)
1240 {
1241 	struct qla_work_evt *e;
1242 
1243 	if (vha->host->active_mode == MODE_TARGET)
1244 		return QLA_FUNCTION_FAILED;
1245 
1246 	e = qla2x00_alloc_work(vha, QLA_EVT_PRLI);
1247 	if (!e)
1248 		return QLA_FUNCTION_FAILED;
1249 
1250 	e->u.fcport.fcport = fcport;
1251 
1252 	return qla2x00_post_work(vha, e);
1253 }
1254 
1255 static void qla2x00_async_prli_sp_done(srb_t *sp, int res)
1256 {
1257 	struct scsi_qla_host *vha = sp->vha;
1258 	struct srb_iocb *lio = &sp->u.iocb_cmd;
1259 	struct event_arg ea;
1260 
1261 	ql_dbg(ql_dbg_disc, vha, 0x2129,
1262 	    "%s %8phC res %x\n", __func__,
1263 	    sp->fcport->port_name, res);
1264 
1265 	sp->fcport->flags &= ~FCF_ASYNC_SENT;
1266 
1267 	if (!test_bit(UNLOADING, &vha->dpc_flags)) {
1268 		memset(&ea, 0, sizeof(ea));
1269 		ea.fcport = sp->fcport;
1270 		ea.data[0] = lio->u.logio.data[0];
1271 		ea.data[1] = lio->u.logio.data[1];
1272 		ea.iop[0] = lio->u.logio.iop[0];
1273 		ea.iop[1] = lio->u.logio.iop[1];
1274 		ea.sp = sp;
1275 		if (res == QLA_OS_TIMER_EXPIRED)
1276 			ea.data[0] = QLA_OS_TIMER_EXPIRED;
1277 		else if (res)
1278 			ea.data[0] = MBS_COMMAND_ERROR;
1279 
1280 		qla24xx_handle_prli_done_event(vha, &ea);
1281 	}
1282 
1283 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
1284 }
1285 
1286 int
1287 qla24xx_async_prli(struct scsi_qla_host *vha, fc_port_t *fcport)
1288 {
1289 	srb_t *sp;
1290 	struct srb_iocb *lio;
1291 	int rval = QLA_FUNCTION_FAILED;
1292 
1293 	if (!vha->flags.online) {
1294 		ql_dbg(ql_dbg_disc, vha, 0xffff, "%s %d %8phC exit\n",
1295 		    __func__, __LINE__, fcport->port_name);
1296 		return rval;
1297 	}
1298 
1299 	if ((fcport->fw_login_state == DSC_LS_PLOGI_PEND ||
1300 	    fcport->fw_login_state == DSC_LS_PRLI_PEND) &&
1301 	    qla_dual_mode_enabled(vha)) {
1302 		ql_dbg(ql_dbg_disc, vha, 0xffff, "%s %d %8phC exit\n",
1303 		    __func__, __LINE__, fcport->port_name);
1304 		return rval;
1305 	}
1306 
1307 	sp = qla2x00_get_sp(vha, fcport, GFP_KERNEL);
1308 	if (!sp)
1309 		return rval;
1310 
1311 	fcport->flags |= FCF_ASYNC_SENT;
1312 	fcport->logout_completed = 0;
1313 
1314 	sp->type = SRB_PRLI_CMD;
1315 	sp->name = "prli";
1316 	qla2x00_init_async_sp(sp, qla2x00_get_async_timeout(vha) + 2,
1317 			      qla2x00_async_prli_sp_done);
1318 
1319 	lio = &sp->u.iocb_cmd;
1320 	lio->u.logio.flags = 0;
1321 
1322 	if (NVME_TARGET(vha->hw, fcport))
1323 		lio->u.logio.flags |= SRB_LOGIN_NVME_PRLI;
1324 
1325 	ql_dbg(ql_dbg_disc, vha, 0x211b,
1326 	    "Async-prli - %8phC hdl=%x, loopid=%x portid=%06x retries=%d fc4type %x priority %x %s.\n",
1327 	    fcport->port_name, sp->handle, fcport->loop_id, fcport->d_id.b24,
1328 	    fcport->login_retry, fcport->fc4_type, vha->hw->fc4_type_priority,
1329 	    NVME_TARGET(vha->hw, fcport) ? "nvme" : "fcp");
1330 
1331 	rval = qla2x00_start_sp(sp);
1332 	if (rval != QLA_SUCCESS) {
1333 		fcport->flags |= FCF_LOGIN_NEEDED;
1334 		set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
1335 		goto done_free_sp;
1336 	}
1337 
1338 	return rval;
1339 
1340 done_free_sp:
1341 	/* ref: INIT */
1342 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
1343 	fcport->flags &= ~FCF_ASYNC_SENT;
1344 	return rval;
1345 }
1346 
1347 int qla24xx_post_gpdb_work(struct scsi_qla_host *vha, fc_port_t *fcport, u8 opt)
1348 {
1349 	struct qla_work_evt *e;
1350 
1351 	e = qla2x00_alloc_work(vha, QLA_EVT_GPDB);
1352 	if (!e)
1353 		return QLA_FUNCTION_FAILED;
1354 
1355 	e->u.fcport.fcport = fcport;
1356 	e->u.fcport.opt = opt;
1357 	fcport->flags |= FCF_ASYNC_ACTIVE;
1358 	return qla2x00_post_work(vha, e);
1359 }
1360 
1361 int qla24xx_async_gpdb(struct scsi_qla_host *vha, fc_port_t *fcport, u8 opt)
1362 {
1363 	srb_t *sp;
1364 	struct srb_iocb *mbx;
1365 	int rval = QLA_FUNCTION_FAILED;
1366 	u16 *mb;
1367 	dma_addr_t pd_dma;
1368 	struct port_database_24xx *pd;
1369 	struct qla_hw_data *ha = vha->hw;
1370 
1371 	if (IS_SESSION_DELETED(fcport)) {
1372 		ql_log(ql_log_warn, vha, 0xffff,
1373 		       "%s: %8phC is being delete - not sending command.\n",
1374 		       __func__, fcport->port_name);
1375 		fcport->flags &= ~FCF_ASYNC_ACTIVE;
1376 		return rval;
1377 	}
1378 
1379 	if (!vha->flags.online || fcport->flags & FCF_ASYNC_SENT) {
1380 		ql_log(ql_log_warn, vha, 0xffff,
1381 		    "%s: %8phC online %d flags %x - not sending command.\n",
1382 		    __func__, fcport->port_name, vha->flags.online, fcport->flags);
1383 		goto done;
1384 	}
1385 
1386 	sp = qla2x00_get_sp(vha, fcport, GFP_KERNEL);
1387 	if (!sp)
1388 		goto done;
1389 
1390 	qla2x00_set_fcport_disc_state(fcport, DSC_GPDB);
1391 
1392 	fcport->flags |= FCF_ASYNC_SENT;
1393 	sp->type = SRB_MB_IOCB;
1394 	sp->name = "gpdb";
1395 	sp->gen1 = fcport->rscn_gen;
1396 	sp->gen2 = fcport->login_gen;
1397 	qla2x00_init_async_sp(sp, qla2x00_get_async_timeout(vha) + 2,
1398 			      qla24xx_async_gpdb_sp_done);
1399 
1400 	pd = dma_pool_zalloc(ha->s_dma_pool, GFP_KERNEL, &pd_dma);
1401 	if (pd == NULL) {
1402 		ql_log(ql_log_warn, vha, 0xd043,
1403 		    "Failed to allocate port database structure.\n");
1404 		goto done_free_sp;
1405 	}
1406 
1407 	mb = sp->u.iocb_cmd.u.mbx.out_mb;
1408 	mb[0] = MBC_GET_PORT_DATABASE;
1409 	mb[1] = fcport->loop_id;
1410 	mb[2] = MSW(pd_dma);
1411 	mb[3] = LSW(pd_dma);
1412 	mb[6] = MSW(MSD(pd_dma));
1413 	mb[7] = LSW(MSD(pd_dma));
1414 	mb[9] = vha->vp_idx;
1415 	mb[10] = opt;
1416 
1417 	mbx = &sp->u.iocb_cmd;
1418 	mbx->u.mbx.in = (void *)pd;
1419 	mbx->u.mbx.in_dma = pd_dma;
1420 
1421 	ql_dbg(ql_dbg_disc, vha, 0x20dc,
1422 	    "Async-%s %8phC hndl %x opt %x\n",
1423 	    sp->name, fcport->port_name, sp->handle, opt);
1424 
1425 	rval = qla2x00_start_sp(sp);
1426 	if (rval != QLA_SUCCESS)
1427 		goto done_free_sp;
1428 	return rval;
1429 
1430 done_free_sp:
1431 	if (pd)
1432 		dma_pool_free(ha->s_dma_pool, pd, pd_dma);
1433 
1434 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
1435 	fcport->flags &= ~FCF_ASYNC_SENT;
1436 done:
1437 	fcport->flags &= ~FCF_ASYNC_ACTIVE;
1438 	qla24xx_post_gpdb_work(vha, fcport, opt);
1439 	return rval;
1440 }
1441 
1442 static
1443 void __qla24xx_handle_gpdb_event(scsi_qla_host_t *vha, struct event_arg *ea)
1444 {
1445 	unsigned long flags;
1446 
1447 	spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
1448 	ea->fcport->login_gen++;
1449 	ea->fcport->deleted = 0;
1450 	ea->fcport->logout_on_delete = 1;
1451 
1452 	if (!ea->fcport->login_succ && !IS_SW_RESV_ADDR(ea->fcport->d_id)) {
1453 		vha->fcport_count++;
1454 		ea->fcport->login_succ = 1;
1455 
1456 		spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
1457 		qla24xx_sched_upd_fcport(ea->fcport);
1458 		spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
1459 	} else if (ea->fcport->login_succ) {
1460 		/*
1461 		 * We have an existing session. A late RSCN delivery
1462 		 * must have triggered the session to be re-validate.
1463 		 * Session is still valid.
1464 		 */
1465 		ql_dbg(ql_dbg_disc, vha, 0x20d6,
1466 		    "%s %d %8phC session revalidate success\n",
1467 		    __func__, __LINE__, ea->fcport->port_name);
1468 		qla2x00_set_fcport_disc_state(ea->fcport, DSC_LOGIN_COMPLETE);
1469 	}
1470 	spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
1471 }
1472 
1473 static int	qla_chk_secure_login(scsi_qla_host_t	*vha, fc_port_t *fcport,
1474 	struct port_database_24xx *pd)
1475 {
1476 	int rc = 0;
1477 
1478 	if (pd->secure_login) {
1479 		ql_dbg(ql_dbg_disc, vha, 0x104d,
1480 		    "Secure Login established on %8phC\n",
1481 		    fcport->port_name);
1482 		fcport->flags |= FCF_FCSP_DEVICE;
1483 	} else {
1484 		ql_dbg(ql_dbg_disc, vha, 0x104d,
1485 		    "non-Secure Login %8phC",
1486 		    fcport->port_name);
1487 		fcport->flags &= ~FCF_FCSP_DEVICE;
1488 	}
1489 	if (vha->hw->flags.edif_enabled) {
1490 		if (fcport->flags & FCF_FCSP_DEVICE) {
1491 			qla2x00_set_fcport_disc_state(fcport, DSC_LOGIN_AUTH_PEND);
1492 			/* Start edif prli timer & ring doorbell for app */
1493 			fcport->edif.rx_sa_set = 0;
1494 			fcport->edif.tx_sa_set = 0;
1495 			fcport->edif.rx_sa_pending = 0;
1496 			fcport->edif.tx_sa_pending = 0;
1497 
1498 			qla2x00_post_aen_work(vha, FCH_EVT_PORT_ONLINE,
1499 			    fcport->d_id.b24);
1500 
1501 			if (DBELL_ACTIVE(vha)) {
1502 				ql_dbg(ql_dbg_disc, vha, 0x20ef,
1503 				    "%s %d %8phC EDIF: post DB_AUTH: AUTH needed\n",
1504 				    __func__, __LINE__, fcport->port_name);
1505 				fcport->edif.app_sess_online = 1;
1506 
1507 				qla_edb_eventcreate(vha, VND_CMD_AUTH_STATE_NEEDED,
1508 				    fcport->d_id.b24, 0, fcport);
1509 			}
1510 
1511 			rc = 1;
1512 		} else if (qla_ini_mode_enabled(vha) || qla_dual_mode_enabled(vha)) {
1513 			ql_dbg(ql_dbg_disc, vha, 0x2117,
1514 			    "%s %d %8phC post prli\n",
1515 			    __func__, __LINE__, fcport->port_name);
1516 			qla24xx_post_prli_work(vha, fcport);
1517 			rc = 1;
1518 		}
1519 	}
1520 	return rc;
1521 }
1522 
1523 static
1524 void qla24xx_handle_gpdb_event(scsi_qla_host_t *vha, struct event_arg *ea)
1525 {
1526 	fc_port_t *fcport = ea->fcport;
1527 	struct port_database_24xx *pd;
1528 	struct srb *sp = ea->sp;
1529 	uint8_t	ls;
1530 
1531 	pd = (struct port_database_24xx *)sp->u.iocb_cmd.u.mbx.in;
1532 
1533 	fcport->flags &= ~FCF_ASYNC_SENT;
1534 
1535 	ql_dbg(ql_dbg_disc, vha, 0x20d2,
1536 	    "%s %8phC DS %d LS %x fc4_type %x rc %x\n", __func__,
1537 	    fcport->port_name, fcport->disc_state, pd->current_login_state,
1538 	    fcport->fc4_type, ea->rc);
1539 
1540 	if (fcport->disc_state == DSC_DELETE_PEND) {
1541 		ql_dbg(ql_dbg_disc, vha, 0x20d5, "%s %d %8phC\n",
1542 		       __func__, __LINE__, fcport->port_name);
1543 		return;
1544 	}
1545 
1546 	if (NVME_TARGET(vha->hw, fcport))
1547 		ls = pd->current_login_state >> 4;
1548 	else
1549 		ls = pd->current_login_state & 0xf;
1550 
1551 	if (ea->sp->gen2 != fcport->login_gen) {
1552 		/* target side must have changed it. */
1553 
1554 		ql_dbg(ql_dbg_disc, vha, 0x20d3,
1555 		    "%s %8phC generation changed\n",
1556 		    __func__, fcport->port_name);
1557 		return;
1558 	} else if (ea->sp->gen1 != fcport->rscn_gen) {
1559 		qla_rscn_replay(fcport);
1560 		qlt_schedule_sess_for_deletion(fcport);
1561 		ql_dbg(ql_dbg_disc, vha, 0x20d5, "%s %d %8phC, ls %x\n",
1562 		       __func__, __LINE__, fcport->port_name, ls);
1563 		return;
1564 	}
1565 
1566 	switch (ls) {
1567 	case PDS_PRLI_COMPLETE:
1568 		__qla24xx_parse_gpdb(vha, fcport, pd);
1569 		break;
1570 	case PDS_PLOGI_COMPLETE:
1571 		if (qla_chk_secure_login(vha, fcport, pd)) {
1572 			ql_dbg(ql_dbg_disc, vha, 0x20d5, "%s %d %8phC, ls %x\n",
1573 			       __func__, __LINE__, fcport->port_name, ls);
1574 			return;
1575 		}
1576 		fallthrough;
1577 	case PDS_PLOGI_PENDING:
1578 	case PDS_PRLI_PENDING:
1579 	case PDS_PRLI2_PENDING:
1580 		/* Set discovery state back to GNL to Relogin attempt */
1581 		if (qla_dual_mode_enabled(vha) ||
1582 		    qla_ini_mode_enabled(vha)) {
1583 			qla2x00_set_fcport_disc_state(fcport, DSC_GNL);
1584 			set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
1585 		}
1586 		ql_dbg(ql_dbg_disc, vha, 0x20d5, "%s %d %8phC, ls %x\n",
1587 		       __func__, __LINE__, fcport->port_name, ls);
1588 		return;
1589 	case PDS_LOGO_PENDING:
1590 	case PDS_PORT_UNAVAILABLE:
1591 	default:
1592 		ql_dbg(ql_dbg_disc, vha, 0x20d5, "%s %d %8phC post del sess\n",
1593 		    __func__, __LINE__, fcport->port_name);
1594 		qlt_schedule_sess_for_deletion(fcport);
1595 		return;
1596 	}
1597 	__qla24xx_handle_gpdb_event(vha, ea);
1598 } /* gpdb event */
1599 
1600 static void qla_chk_n2n_b4_login(struct scsi_qla_host *vha, fc_port_t *fcport)
1601 {
1602 	u8 login = 0;
1603 	int rc;
1604 
1605 	ql_dbg(ql_dbg_disc, vha, 0x307b,
1606 	    "%s %8phC DS %d LS %d lid %d retries=%d\n",
1607 	    __func__, fcport->port_name, fcport->disc_state,
1608 	    fcport->fw_login_state, fcport->loop_id, fcport->login_retry);
1609 
1610 	if (qla_tgt_mode_enabled(vha))
1611 		return;
1612 
1613 	if (qla_dual_mode_enabled(vha)) {
1614 		if (N2N_TOPO(vha->hw)) {
1615 			u64 mywwn, wwn;
1616 
1617 			mywwn = wwn_to_u64(vha->port_name);
1618 			wwn = wwn_to_u64(fcport->port_name);
1619 			if (mywwn > wwn)
1620 				login = 1;
1621 			else if ((fcport->fw_login_state == DSC_LS_PLOGI_COMP)
1622 			    && time_after_eq(jiffies,
1623 				    fcport->plogi_nack_done_deadline))
1624 				login = 1;
1625 		} else {
1626 			login = 1;
1627 		}
1628 	} else {
1629 		/* initiator mode */
1630 		login = 1;
1631 	}
1632 
1633 	if (login && fcport->login_retry) {
1634 		fcport->login_retry--;
1635 		if (fcport->loop_id == FC_NO_LOOP_ID) {
1636 			fcport->fw_login_state = DSC_LS_PORT_UNAVAIL;
1637 			rc = qla2x00_find_new_loop_id(vha, fcport);
1638 			if (rc) {
1639 				ql_dbg(ql_dbg_disc, vha, 0x20e6,
1640 				    "%s %d %8phC post del sess - out of loopid\n",
1641 				    __func__, __LINE__, fcport->port_name);
1642 				fcport->scan_state = 0;
1643 				qlt_schedule_sess_for_deletion(fcport);
1644 				return;
1645 			}
1646 		}
1647 		ql_dbg(ql_dbg_disc, vha, 0x20bf,
1648 		    "%s %d %8phC post login\n",
1649 		    __func__, __LINE__, fcport->port_name);
1650 		qla2x00_post_async_login_work(vha, fcport, NULL);
1651 	}
1652 }
1653 
1654 int qla24xx_fcport_handle_login(struct scsi_qla_host *vha, fc_port_t *fcport)
1655 {
1656 	u16 data[2];
1657 	u16 sec;
1658 
1659 	ql_dbg(ql_dbg_disc, vha, 0x20d8,
1660 	    "%s %8phC DS %d LS %d P %d fl %x confl %p rscn %d|%d login %d lid %d scan %d fc4type %x\n",
1661 	    __func__, fcport->port_name, fcport->disc_state,
1662 	    fcport->fw_login_state, fcport->login_pause, fcport->flags,
1663 	    fcport->conflict, fcport->last_rscn_gen, fcport->rscn_gen,
1664 	    fcport->login_gen, fcport->loop_id, fcport->scan_state,
1665 	    fcport->fc4_type);
1666 
1667 	if (fcport->scan_state != QLA_FCPORT_FOUND ||
1668 	    fcport->disc_state == DSC_DELETE_PEND)
1669 		return 0;
1670 
1671 	if ((fcport->loop_id != FC_NO_LOOP_ID) &&
1672 	    qla_dual_mode_enabled(vha) &&
1673 	    ((fcport->fw_login_state == DSC_LS_PLOGI_PEND) ||
1674 	     (fcport->fw_login_state == DSC_LS_PRLI_PEND)))
1675 		return 0;
1676 
1677 	if (fcport->fw_login_state == DSC_LS_PLOGI_COMP &&
1678 	    !N2N_TOPO(vha->hw)) {
1679 		if (time_before_eq(jiffies, fcport->plogi_nack_done_deadline)) {
1680 			set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
1681 			return 0;
1682 		}
1683 	}
1684 
1685 	/* Target won't initiate port login if fabric is present */
1686 	if (vha->host->active_mode == MODE_TARGET && !N2N_TOPO(vha->hw))
1687 		return 0;
1688 
1689 	if (fcport->flags & (FCF_ASYNC_SENT | FCF_ASYNC_ACTIVE)) {
1690 		set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
1691 		return 0;
1692 	}
1693 
1694 	switch (fcport->disc_state) {
1695 	case DSC_DELETED:
1696 		switch (vha->hw->current_topology) {
1697 		case ISP_CFG_N:
1698 			if (fcport_is_smaller(fcport)) {
1699 				/* this adapter is bigger */
1700 				if (fcport->login_retry) {
1701 					if (fcport->loop_id == FC_NO_LOOP_ID) {
1702 						qla2x00_find_new_loop_id(vha,
1703 						    fcport);
1704 						fcport->fw_login_state =
1705 						    DSC_LS_PORT_UNAVAIL;
1706 					}
1707 					fcport->login_retry--;
1708 					qla_post_els_plogi_work(vha, fcport);
1709 				} else {
1710 					ql_log(ql_log_info, vha, 0x705d,
1711 					    "Unable to reach remote port %8phC",
1712 					    fcport->port_name);
1713 				}
1714 			} else {
1715 				qla24xx_post_gnl_work(vha, fcport);
1716 			}
1717 			break;
1718 		default:
1719 			if (fcport->loop_id == FC_NO_LOOP_ID) {
1720 				ql_dbg(ql_dbg_disc, vha, 0x20bd,
1721 				    "%s %d %8phC post gnl\n",
1722 				    __func__, __LINE__, fcport->port_name);
1723 				qla24xx_post_gnl_work(vha, fcport);
1724 			} else {
1725 				qla_chk_n2n_b4_login(vha, fcport);
1726 			}
1727 			break;
1728 		}
1729 		break;
1730 
1731 	case DSC_GNL:
1732 		switch (vha->hw->current_topology) {
1733 		case ISP_CFG_N:
1734 			if ((fcport->current_login_state & 0xf) == 0x6) {
1735 				ql_dbg(ql_dbg_disc, vha, 0x2118,
1736 				    "%s %d %8phC post GPDB work\n",
1737 				    __func__, __LINE__, fcport->port_name);
1738 				fcport->chip_reset =
1739 					vha->hw->base_qpair->chip_reset;
1740 				qla24xx_post_gpdb_work(vha, fcport, 0);
1741 			}  else {
1742 				ql_dbg(ql_dbg_disc, vha, 0x2118,
1743 				    "%s %d %8phC post %s PRLI\n",
1744 				    __func__, __LINE__, fcport->port_name,
1745 				    NVME_TARGET(vha->hw, fcport) ? "NVME" :
1746 				    "FC");
1747 				qla24xx_post_prli_work(vha, fcport);
1748 			}
1749 			break;
1750 		default:
1751 			if (fcport->login_pause) {
1752 				ql_dbg(ql_dbg_disc, vha, 0x20d8,
1753 				    "%s %d %8phC exit\n",
1754 				    __func__, __LINE__,
1755 				    fcport->port_name);
1756 				fcport->last_rscn_gen = fcport->rscn_gen;
1757 				fcport->last_login_gen = fcport->login_gen;
1758 				set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
1759 				break;
1760 			}
1761 			qla_chk_n2n_b4_login(vha, fcport);
1762 			break;
1763 		}
1764 		break;
1765 
1766 	case DSC_LOGIN_FAILED:
1767 		if (N2N_TOPO(vha->hw))
1768 			qla_chk_n2n_b4_login(vha, fcport);
1769 		else
1770 			qlt_schedule_sess_for_deletion(fcport);
1771 		break;
1772 
1773 	case DSC_LOGIN_COMPLETE:
1774 		/* recheck login state */
1775 		data[0] = data[1] = 0;
1776 		qla2x00_post_async_adisc_work(vha, fcport, data);
1777 		break;
1778 
1779 	case DSC_LOGIN_PEND:
1780 		if (vha->hw->flags.edif_enabled)
1781 			break;
1782 
1783 		if (fcport->fw_login_state == DSC_LS_PLOGI_COMP) {
1784 			ql_dbg(ql_dbg_disc, vha, 0x2118,
1785 			       "%s %d %8phC post %s PRLI\n",
1786 			       __func__, __LINE__, fcport->port_name,
1787 			       NVME_TARGET(vha->hw, fcport) ? "NVME" : "FC");
1788 			qla24xx_post_prli_work(vha, fcport);
1789 		}
1790 		break;
1791 
1792 	case DSC_UPD_FCPORT:
1793 		sec =  jiffies_to_msecs(jiffies -
1794 		    fcport->jiffies_at_registration)/1000;
1795 		if (fcport->sec_since_registration < sec && sec &&
1796 		    !(sec % 60)) {
1797 			fcport->sec_since_registration = sec;
1798 			ql_dbg(ql_dbg_disc, fcport->vha, 0xffff,
1799 			    "%s %8phC - Slow Rport registration(%d Sec)\n",
1800 			    __func__, fcport->port_name, sec);
1801 		}
1802 
1803 		if (fcport->next_disc_state != DSC_DELETE_PEND)
1804 			fcport->next_disc_state = DSC_ADISC;
1805 		set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
1806 		break;
1807 
1808 	default:
1809 		break;
1810 	}
1811 
1812 	return 0;
1813 }
1814 
1815 int qla24xx_post_newsess_work(struct scsi_qla_host *vha, port_id_t *id,
1816     u8 *port_name, u8 *node_name, void *pla, u8 fc4_type)
1817 {
1818 	struct qla_work_evt *e;
1819 
1820 	e = qla2x00_alloc_work(vha, QLA_EVT_NEW_SESS);
1821 	if (!e)
1822 		return QLA_FUNCTION_FAILED;
1823 
1824 	e->u.new_sess.id = *id;
1825 	e->u.new_sess.pla = pla;
1826 	e->u.new_sess.fc4_type = fc4_type;
1827 	memcpy(e->u.new_sess.port_name, port_name, WWN_SIZE);
1828 	if (node_name)
1829 		memcpy(e->u.new_sess.node_name, node_name, WWN_SIZE);
1830 
1831 	return qla2x00_post_work(vha, e);
1832 }
1833 
1834 void qla2x00_handle_rscn(scsi_qla_host_t *vha, struct event_arg *ea)
1835 {
1836 	fc_port_t *fcport;
1837 	unsigned long flags;
1838 
1839 	switch (ea->id.b.rsvd_1) {
1840 	case RSCN_PORT_ADDR:
1841 		fcport = qla2x00_find_fcport_by_nportid(vha, &ea->id, 1);
1842 		if (fcport) {
1843 			if (fcport->flags & FCF_FCP2_DEVICE &&
1844 			    atomic_read(&fcport->state) == FCS_ONLINE) {
1845 				ql_dbg(ql_dbg_disc, vha, 0x2115,
1846 				       "Delaying session delete for FCP2 portid=%06x %8phC ",
1847 					fcport->d_id.b24, fcport->port_name);
1848 				return;
1849 			}
1850 
1851 			if (vha->hw->flags.edif_enabled && DBELL_ACTIVE(vha)) {
1852 				/*
1853 				 * On ipsec start by remote port, Target port
1854 				 * may use RSCN to trigger initiator to
1855 				 * relogin. If driver is already in the
1856 				 * process of a relogin, then ignore the RSCN
1857 				 * and allow the current relogin to continue.
1858 				 * This reduces thrashing of the connection.
1859 				 */
1860 				if (atomic_read(&fcport->state) == FCS_ONLINE) {
1861 					/*
1862 					 * If state = online, then set scan_needed=1 to do relogin.
1863 					 * Otherwise we're already in the middle of a relogin
1864 					 */
1865 					fcport->scan_needed = 1;
1866 					fcport->rscn_gen++;
1867 				}
1868 			} else {
1869 				fcport->scan_needed = 1;
1870 				fcport->rscn_gen++;
1871 			}
1872 		}
1873 		break;
1874 	case RSCN_AREA_ADDR:
1875 		list_for_each_entry(fcport, &vha->vp_fcports, list) {
1876 			if (fcport->flags & FCF_FCP2_DEVICE &&
1877 			    atomic_read(&fcport->state) == FCS_ONLINE)
1878 				continue;
1879 
1880 			if ((ea->id.b24 & 0xffff00) == (fcport->d_id.b24 & 0xffff00)) {
1881 				fcport->scan_needed = 1;
1882 				fcport->rscn_gen++;
1883 			}
1884 		}
1885 		break;
1886 	case RSCN_DOM_ADDR:
1887 		list_for_each_entry(fcport, &vha->vp_fcports, list) {
1888 			if (fcport->flags & FCF_FCP2_DEVICE &&
1889 			    atomic_read(&fcport->state) == FCS_ONLINE)
1890 				continue;
1891 
1892 			if ((ea->id.b24 & 0xff0000) == (fcport->d_id.b24 & 0xff0000)) {
1893 				fcport->scan_needed = 1;
1894 				fcport->rscn_gen++;
1895 			}
1896 		}
1897 		break;
1898 	case RSCN_FAB_ADDR:
1899 	default:
1900 		list_for_each_entry(fcport, &vha->vp_fcports, list) {
1901 			if (fcport->flags & FCF_FCP2_DEVICE &&
1902 			    atomic_read(&fcport->state) == FCS_ONLINE)
1903 				continue;
1904 
1905 			fcport->scan_needed = 1;
1906 			fcport->rscn_gen++;
1907 		}
1908 		break;
1909 	}
1910 
1911 	spin_lock_irqsave(&vha->work_lock, flags);
1912 	if (vha->scan.scan_flags == 0) {
1913 		ql_dbg(ql_dbg_disc, vha, 0xffff, "%s: schedule\n", __func__);
1914 		vha->scan.scan_flags |= SF_QUEUED;
1915 		schedule_delayed_work(&vha->scan.scan_work, 5);
1916 	}
1917 	spin_unlock_irqrestore(&vha->work_lock, flags);
1918 }
1919 
1920 void qla24xx_handle_relogin_event(scsi_qla_host_t *vha,
1921 	struct event_arg *ea)
1922 {
1923 	fc_port_t *fcport = ea->fcport;
1924 
1925 	if (test_bit(UNLOADING, &vha->dpc_flags))
1926 		return;
1927 
1928 	ql_dbg(ql_dbg_disc, vha, 0x2102,
1929 	    "%s %8phC DS %d LS %d P %d del %d cnfl %p rscn %d|%d login %d|%d fl %x\n",
1930 	    __func__, fcport->port_name, fcport->disc_state,
1931 	    fcport->fw_login_state, fcport->login_pause,
1932 	    fcport->deleted, fcport->conflict,
1933 	    fcport->last_rscn_gen, fcport->rscn_gen,
1934 	    fcport->last_login_gen, fcport->login_gen,
1935 	    fcport->flags);
1936 
1937 	if (fcport->last_rscn_gen != fcport->rscn_gen) {
1938 		ql_dbg(ql_dbg_disc, vha, 0x20e9, "%s %d %8phC post gnl\n",
1939 		    __func__, __LINE__, fcport->port_name);
1940 		qla24xx_post_gnl_work(vha, fcport);
1941 		return;
1942 	}
1943 
1944 	qla24xx_fcport_handle_login(vha, fcport);
1945 }
1946 
1947 void qla_handle_els_plogi_done(scsi_qla_host_t *vha,
1948 				      struct event_arg *ea)
1949 {
1950 	if (N2N_TOPO(vha->hw) && fcport_is_smaller(ea->fcport) &&
1951 	    vha->hw->flags.edif_enabled) {
1952 		/* check to see if App support Secure */
1953 		qla24xx_post_gpdb_work(vha, ea->fcport, 0);
1954 		return;
1955 	}
1956 
1957 	/* for pure Target Mode, PRLI will not be initiated */
1958 	if (vha->host->active_mode == MODE_TARGET)
1959 		return;
1960 
1961 	ql_dbg(ql_dbg_disc, vha, 0x2118,
1962 	    "%s %d %8phC post PRLI\n",
1963 	    __func__, __LINE__, ea->fcport->port_name);
1964 	qla24xx_post_prli_work(vha, ea->fcport);
1965 }
1966 
1967 /*
1968  * RSCN(s) came in for this fcport, but the RSCN(s) was not able
1969  * to be consumed by the fcport
1970  */
1971 void qla_rscn_replay(fc_port_t *fcport)
1972 {
1973 	struct event_arg ea;
1974 
1975 	switch (fcport->disc_state) {
1976 	case DSC_DELETE_PEND:
1977 		return;
1978 	default:
1979 		break;
1980 	}
1981 
1982 	if (fcport->scan_needed) {
1983 		memset(&ea, 0, sizeof(ea));
1984 		ea.id = fcport->d_id;
1985 		ea.id.b.rsvd_1 = RSCN_PORT_ADDR;
1986 		qla2x00_handle_rscn(fcport->vha, &ea);
1987 	}
1988 }
1989 
1990 static void
1991 qla2x00_tmf_iocb_timeout(void *data)
1992 {
1993 	srb_t *sp = data;
1994 	struct srb_iocb *tmf = &sp->u.iocb_cmd;
1995 	int rc, h;
1996 	unsigned long flags;
1997 
1998 	rc = qla24xx_async_abort_cmd(sp, false);
1999 	if (rc) {
2000 		spin_lock_irqsave(sp->qpair->qp_lock_ptr, flags);
2001 		for (h = 1; h < sp->qpair->req->num_outstanding_cmds; h++) {
2002 			if (sp->qpair->req->outstanding_cmds[h] == sp) {
2003 				sp->qpair->req->outstanding_cmds[h] = NULL;
2004 				qla_put_fw_resources(sp->qpair, &sp->iores);
2005 				break;
2006 			}
2007 		}
2008 		spin_unlock_irqrestore(sp->qpair->qp_lock_ptr, flags);
2009 		tmf->u.tmf.comp_status = cpu_to_le16(CS_TIMEOUT);
2010 		tmf->u.tmf.data = QLA_FUNCTION_FAILED;
2011 		complete(&tmf->u.tmf.comp);
2012 	}
2013 }
2014 
2015 static void qla2x00_tmf_sp_done(srb_t *sp, int res)
2016 {
2017 	struct srb_iocb *tmf = &sp->u.iocb_cmd;
2018 
2019 	complete(&tmf->u.tmf.comp);
2020 }
2021 
2022 int
2023 qla2x00_async_tm_cmd(fc_port_t *fcport, uint32_t flags, uint32_t lun,
2024 	uint32_t tag)
2025 {
2026 	struct scsi_qla_host *vha = fcport->vha;
2027 	struct srb_iocb *tm_iocb;
2028 	srb_t *sp;
2029 	int rval = QLA_FUNCTION_FAILED;
2030 
2031 	/* ref: INIT */
2032 	sp = qla2x00_get_sp(vha, fcport, GFP_KERNEL);
2033 	if (!sp)
2034 		goto done;
2035 
2036 	qla_vha_mark_busy(vha);
2037 	sp->type = SRB_TM_CMD;
2038 	sp->name = "tmf";
2039 	qla2x00_init_async_sp(sp, qla2x00_get_async_timeout(vha),
2040 			      qla2x00_tmf_sp_done);
2041 	sp->u.iocb_cmd.timeout = qla2x00_tmf_iocb_timeout;
2042 
2043 	tm_iocb = &sp->u.iocb_cmd;
2044 	init_completion(&tm_iocb->u.tmf.comp);
2045 	tm_iocb->u.tmf.flags = flags;
2046 	tm_iocb->u.tmf.lun = lun;
2047 
2048 	ql_dbg(ql_dbg_taskm, vha, 0x802f,
2049 	    "Async-tmf hdl=%x loop-id=%x portid=%02x%02x%02x.\n",
2050 	    sp->handle, fcport->loop_id, fcport->d_id.b.domain,
2051 	    fcport->d_id.b.area, fcport->d_id.b.al_pa);
2052 
2053 	rval = qla2x00_start_sp(sp);
2054 	if (rval != QLA_SUCCESS)
2055 		goto done_free_sp;
2056 	wait_for_completion(&tm_iocb->u.tmf.comp);
2057 
2058 	rval = tm_iocb->u.tmf.data;
2059 
2060 	if (rval != QLA_SUCCESS) {
2061 		ql_log(ql_log_warn, vha, 0x8030,
2062 		    "TM IOCB failed (%x).\n", rval);
2063 	}
2064 
2065 	if (!test_bit(UNLOADING, &vha->dpc_flags) && !IS_QLAFX00(vha->hw)) {
2066 		flags = tm_iocb->u.tmf.flags;
2067 		lun = (uint16_t)tm_iocb->u.tmf.lun;
2068 
2069 		/* Issue Marker IOCB */
2070 		qla2x00_marker(vha, vha->hw->base_qpair,
2071 		    fcport->loop_id, lun,
2072 		    flags == TCF_LUN_RESET ? MK_SYNC_ID_LUN : MK_SYNC_ID);
2073 	}
2074 
2075 done_free_sp:
2076 	/* ref: INIT */
2077 	kref_put(&sp->cmd_kref, qla2x00_sp_release);
2078 done:
2079 	return rval;
2080 }
2081 
2082 int
2083 qla24xx_async_abort_command(srb_t *sp)
2084 {
2085 	unsigned long   flags = 0;
2086 
2087 	uint32_t	handle;
2088 	fc_port_t	*fcport = sp->fcport;
2089 	struct qla_qpair *qpair = sp->qpair;
2090 	struct scsi_qla_host *vha = fcport->vha;
2091 	struct req_que *req = qpair->req;
2092 
2093 	spin_lock_irqsave(qpair->qp_lock_ptr, flags);
2094 	for (handle = 1; handle < req->num_outstanding_cmds; handle++) {
2095 		if (req->outstanding_cmds[handle] == sp)
2096 			break;
2097 	}
2098 	spin_unlock_irqrestore(qpair->qp_lock_ptr, flags);
2099 
2100 	if (handle == req->num_outstanding_cmds) {
2101 		/* Command not found. */
2102 		return QLA_ERR_NOT_FOUND;
2103 	}
2104 	if (sp->type == SRB_FXIOCB_DCMD)
2105 		return qlafx00_fx_disc(vha, &vha->hw->mr.fcport,
2106 		    FXDISC_ABORT_IOCTL);
2107 
2108 	return qla24xx_async_abort_cmd(sp, true);
2109 }
2110 
2111 static void
2112 qla24xx_handle_prli_done_event(struct scsi_qla_host *vha, struct event_arg *ea)
2113 {
2114 	struct srb *sp;
2115 	WARN_ONCE(!qla2xxx_is_valid_mbs(ea->data[0]), "mbs: %#x\n",
2116 		  ea->data[0]);
2117 
2118 	switch (ea->data[0]) {
2119 	case MBS_COMMAND_COMPLETE:
2120 		ql_dbg(ql_dbg_disc, vha, 0x2118,
2121 		    "%s %d %8phC post gpdb\n",
2122 		    __func__, __LINE__, ea->fcport->port_name);
2123 
2124 		ea->fcport->chip_reset = vha->hw->base_qpair->chip_reset;
2125 		ea->fcport->logout_on_delete = 1;
2126 		ea->fcport->nvme_prli_service_param = ea->iop[0];
2127 		if (ea->iop[0] & NVME_PRLI_SP_FIRST_BURST)
2128 			ea->fcport->nvme_first_burst_size =
2129 			    (ea->iop[1] & 0xffff) * 512;
2130 		else
2131 			ea->fcport->nvme_first_burst_size = 0;
2132 		qla24xx_post_gpdb_work(vha, ea->fcport, 0);
2133 		break;
2134 	default:
2135 		sp = ea->sp;
2136 		ql_dbg(ql_dbg_disc, vha, 0x2118,
2137 		       "%s %d %8phC priority %s, fc4type %x prev try %s\n",
2138 		       __func__, __LINE__, ea->fcport->port_name,
2139 		       vha->hw->fc4_type_priority == FC4_PRIORITY_FCP ?
2140 		       "FCP" : "NVMe", ea->fcport->fc4_type,
2141 		       (sp->u.iocb_cmd.u.logio.flags & SRB_LOGIN_NVME_PRLI) ?
2142 			"NVME" : "FCP");
2143 
2144 		if (NVME_FCP_TARGET(ea->fcport)) {
2145 			if (sp->u.iocb_cmd.u.logio.flags & SRB_LOGIN_NVME_PRLI)
2146 				ea->fcport->do_prli_nvme = 0;
2147 			else
2148 				ea->fcport->do_prli_nvme = 1;
2149 		} else {
2150 			ea->fcport->do_prli_nvme = 0;
2151 		}
2152 
2153 		if (N2N_TOPO(vha->hw)) {
2154 			if (ea->fcport->n2n_link_reset_cnt ==
2155 			    vha->hw->login_retry_count &&
2156 			    ea->fcport->flags & FCF_FCSP_DEVICE) {
2157 				/* remote authentication app just started */
2158 				ea->fcport->n2n_link_reset_cnt = 0;
2159 			}
2160 
2161 			if (ea->fcport->n2n_link_reset_cnt <
2162 			    vha->hw->login_retry_count) {
2163 				ea->fcport->n2n_link_reset_cnt++;
2164 				vha->relogin_jif = jiffies + 2 * HZ;
2165 				/*
2166 				 * PRLI failed. Reset link to kick start
2167 				 * state machine
2168 				 */
2169 				set_bit(N2N_LINK_RESET, &vha->dpc_flags);
2170 				qla2xxx_wake_dpc(vha);
2171 			} else {
2172 				ql_log(ql_log_warn, vha, 0x2119,
2173 				       "%s %d %8phC Unable to reconnect\n",
2174 				       __func__, __LINE__,
2175 				       ea->fcport->port_name);
2176 			}
2177 		} else {
2178 			/*
2179 			 * switch connect. login failed. Take connection down
2180 			 * and allow relogin to retrigger
2181 			 */
2182 			ea->fcport->flags &= ~FCF_ASYNC_SENT;
2183 			ea->fcport->keep_nport_handle = 0;
2184 			ea->fcport->logout_on_delete = 1;
2185 			qlt_schedule_sess_for_deletion(ea->fcport);
2186 		}
2187 		break;
2188 	}
2189 }
2190 
2191 void
2192 qla24xx_handle_plogi_done_event(struct scsi_qla_host *vha, struct event_arg *ea)
2193 {
2194 	port_id_t cid;	/* conflict Nport id */
2195 	u16 lid;
2196 	struct fc_port *conflict_fcport;
2197 	unsigned long flags;
2198 	struct fc_port *fcport = ea->fcport;
2199 
2200 	ql_dbg(ql_dbg_disc, vha, 0xffff,
2201 	    "%s %8phC DS %d LS %d rc %d login %d|%d rscn %d|%d data %x|%x iop %x|%x\n",
2202 	    __func__, fcport->port_name, fcport->disc_state,
2203 	    fcport->fw_login_state, ea->rc, ea->sp->gen2, fcport->login_gen,
2204 	    ea->sp->gen1, fcport->rscn_gen,
2205 	    ea->data[0], ea->data[1], ea->iop[0], ea->iop[1]);
2206 
2207 	if ((fcport->fw_login_state == DSC_LS_PLOGI_PEND) ||
2208 	    (fcport->fw_login_state == DSC_LS_PRLI_PEND)) {
2209 		ql_dbg(ql_dbg_disc, vha, 0x20ea,
2210 		    "%s %d %8phC Remote is trying to login\n",
2211 		    __func__, __LINE__, fcport->port_name);
2212 		return;
2213 	}
2214 
2215 	if ((fcport->disc_state == DSC_DELETE_PEND) ||
2216 	    (fcport->disc_state == DSC_DELETED)) {
2217 		set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
2218 		return;
2219 	}
2220 
2221 	if (ea->sp->gen2 != fcport->login_gen) {
2222 		/* target side must have changed it. */
2223 		ql_dbg(ql_dbg_disc, vha, 0x20d3,
2224 		    "%s %8phC generation changed\n",
2225 		    __func__, fcport->port_name);
2226 		set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
2227 		return;
2228 	} else if (ea->sp->gen1 != fcport->rscn_gen) {
2229 		ql_dbg(ql_dbg_disc, vha, 0x20d3,
2230 		    "%s %8phC RSCN generation changed\n",
2231 		    __func__, fcport->port_name);
2232 		qla_rscn_replay(fcport);
2233 		qlt_schedule_sess_for_deletion(fcport);
2234 		return;
2235 	}
2236 
2237 	WARN_ONCE(!qla2xxx_is_valid_mbs(ea->data[0]), "mbs: %#x\n",
2238 		  ea->data[0]);
2239 
2240 	switch (ea->data[0]) {
2241 	case MBS_COMMAND_COMPLETE:
2242 		/*
2243 		 * Driver must validate login state - If PRLI not complete,
2244 		 * force a relogin attempt via implicit LOGO, PLOGI, and PRLI
2245 		 * requests.
2246 		 */
2247 		if (vha->hw->flags.edif_enabled) {
2248 			set_bit(ea->fcport->loop_id, vha->hw->loop_id_map);
2249 			spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
2250 			ea->fcport->chip_reset = vha->hw->base_qpair->chip_reset;
2251 			ea->fcport->logout_on_delete = 1;
2252 			ea->fcport->send_els_logo = 0;
2253 			ea->fcport->fw_login_state = DSC_LS_PLOGI_COMP;
2254 			spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
2255 
2256 			qla24xx_post_gpdb_work(vha, ea->fcport, 0);
2257 		} else {
2258 			if (NVME_TARGET(vha->hw, fcport)) {
2259 				ql_dbg(ql_dbg_disc, vha, 0x2117,
2260 				    "%s %d %8phC post prli\n",
2261 				    __func__, __LINE__, fcport->port_name);
2262 				qla24xx_post_prli_work(vha, fcport);
2263 			} else {
2264 				ql_dbg(ql_dbg_disc, vha, 0x20ea,
2265 				    "%s %d %8phC LoopID 0x%x in use with %06x. post gpdb\n",
2266 				    __func__, __LINE__, fcport->port_name,
2267 				    fcport->loop_id, fcport->d_id.b24);
2268 
2269 				set_bit(fcport->loop_id, vha->hw->loop_id_map);
2270 				spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
2271 				fcport->chip_reset = vha->hw->base_qpair->chip_reset;
2272 				fcport->logout_on_delete = 1;
2273 				fcport->send_els_logo = 0;
2274 				fcport->fw_login_state = DSC_LS_PRLI_COMP;
2275 				spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
2276 
2277 				qla24xx_post_gpdb_work(vha, fcport, 0);
2278 			}
2279 		}
2280 		break;
2281 	case MBS_COMMAND_ERROR:
2282 		ql_dbg(ql_dbg_disc, vha, 0x20eb, "%s %d %8phC cmd error %x\n",
2283 		    __func__, __LINE__, ea->fcport->port_name, ea->data[1]);
2284 
2285 		qlt_schedule_sess_for_deletion(ea->fcport);
2286 		break;
2287 	case MBS_LOOP_ID_USED:
2288 		/* data[1] = IO PARAM 1 = nport ID  */
2289 		cid.b.domain = (ea->iop[1] >> 16) & 0xff;
2290 		cid.b.area   = (ea->iop[1] >>  8) & 0xff;
2291 		cid.b.al_pa  = ea->iop[1] & 0xff;
2292 		cid.b.rsvd_1 = 0;
2293 
2294 		ql_dbg(ql_dbg_disc, vha, 0x20ec,
2295 		    "%s %d %8phC lid %#x in use with pid %06x post gnl\n",
2296 		    __func__, __LINE__, ea->fcport->port_name,
2297 		    ea->fcport->loop_id, cid.b24);
2298 
2299 		set_bit(ea->fcport->loop_id, vha->hw->loop_id_map);
2300 		ea->fcport->loop_id = FC_NO_LOOP_ID;
2301 		qla24xx_post_gnl_work(vha, ea->fcport);
2302 		break;
2303 	case MBS_PORT_ID_USED:
2304 		lid = ea->iop[1] & 0xffff;
2305 		qlt_find_sess_invalidate_other(vha,
2306 		    wwn_to_u64(ea->fcport->port_name),
2307 		    ea->fcport->d_id, lid, &conflict_fcport);
2308 
2309 		if (conflict_fcport) {
2310 			/*
2311 			 * Another fcport share the same loop_id/nport id.
2312 			 * Conflict fcport needs to finish cleanup before this
2313 			 * fcport can proceed to login.
2314 			 */
2315 			conflict_fcport->conflict = ea->fcport;
2316 			ea->fcport->login_pause = 1;
2317 
2318 			ql_dbg(ql_dbg_disc, vha, 0x20ed,
2319 			    "%s %d %8phC NPortId %06x inuse with loopid 0x%x.\n",
2320 			    __func__, __LINE__, ea->fcport->port_name,
2321 			    ea->fcport->d_id.b24, lid);
2322 		} else {
2323 			ql_dbg(ql_dbg_disc, vha, 0x20ed,
2324 			    "%s %d %8phC NPortId %06x inuse with loopid 0x%x. sched delete\n",
2325 			    __func__, __LINE__, ea->fcport->port_name,
2326 			    ea->fcport->d_id.b24, lid);
2327 
2328 			qla2x00_clear_loop_id(ea->fcport);
2329 			set_bit(lid, vha->hw->loop_id_map);
2330 			ea->fcport->loop_id = lid;
2331 			ea->fcport->keep_nport_handle = 0;
2332 			ea->fcport->logout_on_delete = 1;
2333 			qlt_schedule_sess_for_deletion(ea->fcport);
2334 		}
2335 		break;
2336 	}
2337 	return;
2338 }
2339 
2340 /****************************************************************************/
2341 /*                QLogic ISP2x00 Hardware Support Functions.                */
2342 /****************************************************************************/
2343 
2344 static int
2345 qla83xx_nic_core_fw_load(scsi_qla_host_t *vha)
2346 {
2347 	int rval = QLA_SUCCESS;
2348 	struct qla_hw_data *ha = vha->hw;
2349 	uint32_t idc_major_ver, idc_minor_ver;
2350 	uint16_t config[4];
2351 
2352 	qla83xx_idc_lock(vha, 0);
2353 
2354 	/* SV: TODO: Assign initialization timeout from
2355 	 * flash-info / other param
2356 	 */
2357 	ha->fcoe_dev_init_timeout = QLA83XX_IDC_INITIALIZATION_TIMEOUT;
2358 	ha->fcoe_reset_timeout = QLA83XX_IDC_RESET_ACK_TIMEOUT;
2359 
2360 	/* Set our fcoe function presence */
2361 	if (__qla83xx_set_drv_presence(vha) != QLA_SUCCESS) {
2362 		ql_dbg(ql_dbg_p3p, vha, 0xb077,
2363 		    "Error while setting DRV-Presence.\n");
2364 		rval = QLA_FUNCTION_FAILED;
2365 		goto exit;
2366 	}
2367 
2368 	/* Decide the reset ownership */
2369 	qla83xx_reset_ownership(vha);
2370 
2371 	/*
2372 	 * On first protocol driver load:
2373 	 * Init-Owner: Set IDC-Major-Version and Clear IDC-Lock-Recovery
2374 	 * register.
2375 	 * Others: Check compatibility with current IDC Major version.
2376 	 */
2377 	qla83xx_rd_reg(vha, QLA83XX_IDC_MAJOR_VERSION, &idc_major_ver);
2378 	if (ha->flags.nic_core_reset_owner) {
2379 		/* Set IDC Major version */
2380 		idc_major_ver = QLA83XX_SUPP_IDC_MAJOR_VERSION;
2381 		qla83xx_wr_reg(vha, QLA83XX_IDC_MAJOR_VERSION, idc_major_ver);
2382 
2383 		/* Clearing IDC-Lock-Recovery register */
2384 		qla83xx_wr_reg(vha, QLA83XX_IDC_LOCK_RECOVERY, 0);
2385 	} else if (idc_major_ver != QLA83XX_SUPP_IDC_MAJOR_VERSION) {
2386 		/*
2387 		 * Clear further IDC participation if we are not compatible with
2388 		 * the current IDC Major Version.
2389 		 */
2390 		ql_log(ql_log_warn, vha, 0xb07d,
2391 		    "Failing load, idc_major_ver=%d, expected_major_ver=%d.\n",
2392 		    idc_major_ver, QLA83XX_SUPP_IDC_MAJOR_VERSION);
2393 		__qla83xx_clear_drv_presence(vha);
2394 		rval = QLA_FUNCTION_FAILED;
2395 		goto exit;
2396 	}
2397 	/* Each function sets its supported Minor version. */
2398 	qla83xx_rd_reg(vha, QLA83XX_IDC_MINOR_VERSION, &idc_minor_ver);
2399 	idc_minor_ver |= (QLA83XX_SUPP_IDC_MINOR_VERSION << (ha->portnum * 2));
2400 	qla83xx_wr_reg(vha, QLA83XX_IDC_MINOR_VERSION, idc_minor_ver);
2401 
2402 	if (ha->flags.nic_core_reset_owner) {
2403 		memset(config, 0, sizeof(config));
2404 		if (!qla81xx_get_port_config(vha, config))
2405 			qla83xx_wr_reg(vha, QLA83XX_IDC_DEV_STATE,
2406 			    QLA8XXX_DEV_READY);
2407 	}
2408 
2409 	rval = qla83xx_idc_state_handler(vha);
2410 
2411 exit:
2412 	qla83xx_idc_unlock(vha, 0);
2413 
2414 	return rval;
2415 }
2416 
2417 /*
2418 * qla2x00_initialize_adapter
2419 *      Initialize board.
2420 *
2421 * Input:
2422 *      ha = adapter block pointer.
2423 *
2424 * Returns:
2425 *      0 = success
2426 */
2427 int
2428 qla2x00_initialize_adapter(scsi_qla_host_t *vha)
2429 {
2430 	int	rval;
2431 	struct qla_hw_data *ha = vha->hw;
2432 	struct req_que *req = ha->req_q_map[0];
2433 	struct device_reg_24xx __iomem *reg = &ha->iobase->isp24;
2434 
2435 	memset(&vha->qla_stats, 0, sizeof(vha->qla_stats));
2436 	memset(&vha->fc_host_stat, 0, sizeof(vha->fc_host_stat));
2437 
2438 	/* Clear adapter flags. */
2439 	vha->flags.online = 0;
2440 	ha->flags.chip_reset_done = 0;
2441 	vha->flags.reset_active = 0;
2442 	ha->flags.pci_channel_io_perm_failure = 0;
2443 	ha->flags.eeh_busy = 0;
2444 	vha->qla_stats.jiffies_at_last_reset = get_jiffies_64();
2445 	atomic_set(&vha->loop_down_timer, LOOP_DOWN_TIME);
2446 	atomic_set(&vha->loop_state, LOOP_DOWN);
2447 	vha->device_flags = DFLG_NO_CABLE;
2448 	vha->dpc_flags = 0;
2449 	vha->flags.management_server_logged_in = 0;
2450 	vha->marker_needed = 0;
2451 	ha->isp_abort_cnt = 0;
2452 	ha->beacon_blink_led = 0;
2453 
2454 	set_bit(0, ha->req_qid_map);
2455 	set_bit(0, ha->rsp_qid_map);
2456 
2457 	ql_dbg(ql_dbg_init, vha, 0x0040,
2458 	    "Configuring PCI space...\n");
2459 	rval = ha->isp_ops->pci_config(vha);
2460 	if (rval) {
2461 		ql_log(ql_log_warn, vha, 0x0044,
2462 		    "Unable to configure PCI space.\n");
2463 		return (rval);
2464 	}
2465 
2466 	ha->isp_ops->reset_chip(vha);
2467 
2468 	/* Check for secure flash support */
2469 	if (IS_QLA28XX(ha)) {
2470 		if (rd_reg_word(&reg->mailbox12) & BIT_0)
2471 			ha->flags.secure_adapter = 1;
2472 		ql_log(ql_log_info, vha, 0xffff, "Secure Adapter: %s\n",
2473 		    (ha->flags.secure_adapter) ? "Yes" : "No");
2474 	}
2475 
2476 
2477 	rval = qla2xxx_get_flash_info(vha);
2478 	if (rval) {
2479 		ql_log(ql_log_fatal, vha, 0x004f,
2480 		    "Unable to validate FLASH data.\n");
2481 		return rval;
2482 	}
2483 
2484 	if (IS_QLA8044(ha)) {
2485 		qla8044_read_reset_template(vha);
2486 
2487 		/* NOTE: If ql2xdontresethba==1, set IDC_CTRL DONTRESET_BIT0.
2488 		 * If DONRESET_BIT0 is set, drivers should not set dev_state
2489 		 * to NEED_RESET. But if NEED_RESET is set, drivers should
2490 		 * should honor the reset. */
2491 		if (ql2xdontresethba == 1)
2492 			qla8044_set_idc_dontreset(vha);
2493 	}
2494 
2495 	ha->isp_ops->get_flash_version(vha, req->ring);
2496 	ql_dbg(ql_dbg_init, vha, 0x0061,
2497 	    "Configure NVRAM parameters...\n");
2498 
2499 	/* Let priority default to FCP, can be overridden by nvram_config */
2500 	ha->fc4_type_priority = FC4_PRIORITY_FCP;
2501 
2502 	ha->isp_ops->nvram_config(vha);
2503 
2504 	if (ha->fc4_type_priority != FC4_PRIORITY_FCP &&
2505 	    ha->fc4_type_priority != FC4_PRIORITY_NVME)
2506 		ha->fc4_type_priority = FC4_PRIORITY_FCP;
2507 
2508 	ql_log(ql_log_info, vha, 0xffff, "FC4 priority set to %s\n",
2509 	       ha->fc4_type_priority == FC4_PRIORITY_FCP ? "FCP" : "NVMe");
2510 
2511 	if (ha->flags.disable_serdes) {
2512 		/* Mask HBA via NVRAM settings? */
2513 		ql_log(ql_log_info, vha, 0x0077,
2514 		    "Masking HBA WWPN %8phN (via NVRAM).\n", vha->port_name);
2515 		return QLA_FUNCTION_FAILED;
2516 	}
2517 
2518 	ql_dbg(ql_dbg_init, vha, 0x0078,
2519 	    "Verifying loaded RISC code...\n");
2520 
2521 	/* If smartsan enabled then require fdmi and rdp enabled */
2522 	if (ql2xsmartsan) {
2523 		ql2xfdmienable = 1;
2524 		ql2xrdpenable = 1;
2525 	}
2526 
2527 	if (qla2x00_isp_firmware(vha) != QLA_SUCCESS) {
2528 		rval = ha->isp_ops->chip_diag(vha);
2529 		if (rval)
2530 			return (rval);
2531 		rval = qla2x00_setup_chip(vha);
2532 		if (rval)
2533 			return (rval);
2534 	}
2535 
2536 	if (IS_QLA84XX(ha)) {
2537 		ha->cs84xx = qla84xx_get_chip(vha);
2538 		if (!ha->cs84xx) {
2539 			ql_log(ql_log_warn, vha, 0x00d0,
2540 			    "Unable to configure ISP84XX.\n");
2541 			return QLA_FUNCTION_FAILED;
2542 		}
2543 	}
2544 
2545 	if (qla_ini_mode_enabled(vha) || qla_dual_mode_enabled(vha))
2546 		rval = qla2x00_init_rings(vha);
2547 
2548 	/* No point in continuing if firmware initialization failed. */
2549 	if (rval != QLA_SUCCESS)
2550 		return rval;
2551 
2552 	ha->flags.chip_reset_done = 1;
2553 
2554 	if (rval == QLA_SUCCESS && IS_QLA84XX(ha)) {
2555 		/* Issue verify 84xx FW IOCB to complete 84xx initialization */
2556 		rval = qla84xx_init_chip(vha);
2557 		if (rval != QLA_SUCCESS) {
2558 			ql_log(ql_log_warn, vha, 0x00d4,
2559 			    "Unable to initialize ISP84XX.\n");
2560 			qla84xx_put_chip(vha);
2561 		}
2562 	}
2563 
2564 	/* Load the NIC Core f/w if we are the first protocol driver. */
2565 	if (IS_QLA8031(ha)) {
2566 		rval = qla83xx_nic_core_fw_load(vha);
2567 		if (rval)
2568 			ql_log(ql_log_warn, vha, 0x0124,
2569 			    "Error in initializing NIC Core f/w.\n");
2570 	}
2571 
2572 	if (IS_QLA24XX_TYPE(ha) || IS_QLA25XX(ha))
2573 		qla24xx_read_fcp_prio_cfg(vha);
2574 
2575 	if (IS_P3P_TYPE(ha))
2576 		qla82xx_set_driver_version(vha, QLA2XXX_VERSION);
2577 	else
2578 		qla25xx_set_driver_version(vha, QLA2XXX_VERSION);
2579 
2580 	return (rval);
2581 }
2582 
2583 /**
2584  * qla2100_pci_config() - Setup ISP21xx PCI configuration registers.
2585  * @vha: HA context
2586  *
2587  * Returns 0 on success.
2588  */
2589 int
2590 qla2100_pci_config(scsi_qla_host_t *vha)
2591 {
2592 	uint16_t w;
2593 	unsigned long flags;
2594 	struct qla_hw_data *ha = vha->hw;
2595 	struct device_reg_2xxx __iomem *reg = &ha->iobase->isp;
2596 
2597 	pci_set_master(ha->pdev);
2598 	pci_try_set_mwi(ha->pdev);
2599 
2600 	pci_read_config_word(ha->pdev, PCI_COMMAND, &w);
2601 	w |= (PCI_COMMAND_PARITY | PCI_COMMAND_SERR);
2602 	pci_write_config_word(ha->pdev, PCI_COMMAND, w);
2603 
2604 	pci_disable_rom(ha->pdev);
2605 
2606 	/* Get PCI bus information. */
2607 	spin_lock_irqsave(&ha->hardware_lock, flags);
2608 	ha->pci_attr = rd_reg_word(&reg->ctrl_status);
2609 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
2610 
2611 	return QLA_SUCCESS;
2612 }
2613 
2614 /**
2615  * qla2300_pci_config() - Setup ISP23xx PCI configuration registers.
2616  * @vha: HA context
2617  *
2618  * Returns 0 on success.
2619  */
2620 int
2621 qla2300_pci_config(scsi_qla_host_t *vha)
2622 {
2623 	uint16_t	w;
2624 	unsigned long   flags = 0;
2625 	uint32_t	cnt;
2626 	struct qla_hw_data *ha = vha->hw;
2627 	struct device_reg_2xxx __iomem *reg = &ha->iobase->isp;
2628 
2629 	pci_set_master(ha->pdev);
2630 	pci_try_set_mwi(ha->pdev);
2631 
2632 	pci_read_config_word(ha->pdev, PCI_COMMAND, &w);
2633 	w |= (PCI_COMMAND_PARITY | PCI_COMMAND_SERR);
2634 
2635 	if (IS_QLA2322(ha) || IS_QLA6322(ha))
2636 		w &= ~PCI_COMMAND_INTX_DISABLE;
2637 	pci_write_config_word(ha->pdev, PCI_COMMAND, w);
2638 
2639 	/*
2640 	 * If this is a 2300 card and not 2312, reset the
2641 	 * COMMAND_INVALIDATE due to a bug in the 2300. Unfortunately,
2642 	 * the 2310 also reports itself as a 2300 so we need to get the
2643 	 * fb revision level -- a 6 indicates it really is a 2300 and
2644 	 * not a 2310.
2645 	 */
2646 	if (IS_QLA2300(ha)) {
2647 		spin_lock_irqsave(&ha->hardware_lock, flags);
2648 
2649 		/* Pause RISC. */
2650 		wrt_reg_word(&reg->hccr, HCCR_PAUSE_RISC);
2651 		for (cnt = 0; cnt < 30000; cnt++) {
2652 			if ((rd_reg_word(&reg->hccr) & HCCR_RISC_PAUSE) != 0)
2653 				break;
2654 
2655 			udelay(10);
2656 		}
2657 
2658 		/* Select FPM registers. */
2659 		wrt_reg_word(&reg->ctrl_status, 0x20);
2660 		rd_reg_word(&reg->ctrl_status);
2661 
2662 		/* Get the fb rev level */
2663 		ha->fb_rev = RD_FB_CMD_REG(ha, reg);
2664 
2665 		if (ha->fb_rev == FPM_2300)
2666 			pci_clear_mwi(ha->pdev);
2667 
2668 		/* Deselect FPM registers. */
2669 		wrt_reg_word(&reg->ctrl_status, 0x0);
2670 		rd_reg_word(&reg->ctrl_status);
2671 
2672 		/* Release RISC module. */
2673 		wrt_reg_word(&reg->hccr, HCCR_RELEASE_RISC);
2674 		for (cnt = 0; cnt < 30000; cnt++) {
2675 			if ((rd_reg_word(&reg->hccr) & HCCR_RISC_PAUSE) == 0)
2676 				break;
2677 
2678 			udelay(10);
2679 		}
2680 
2681 		spin_unlock_irqrestore(&ha->hardware_lock, flags);
2682 	}
2683 
2684 	pci_write_config_byte(ha->pdev, PCI_LATENCY_TIMER, 0x80);
2685 
2686 	pci_disable_rom(ha->pdev);
2687 
2688 	/* Get PCI bus information. */
2689 	spin_lock_irqsave(&ha->hardware_lock, flags);
2690 	ha->pci_attr = rd_reg_word(&reg->ctrl_status);
2691 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
2692 
2693 	return QLA_SUCCESS;
2694 }
2695 
2696 /**
2697  * qla24xx_pci_config() - Setup ISP24xx PCI configuration registers.
2698  * @vha: HA context
2699  *
2700  * Returns 0 on success.
2701  */
2702 int
2703 qla24xx_pci_config(scsi_qla_host_t *vha)
2704 {
2705 	uint16_t w;
2706 	unsigned long flags = 0;
2707 	struct qla_hw_data *ha = vha->hw;
2708 	struct device_reg_24xx __iomem *reg = &ha->iobase->isp24;
2709 
2710 	pci_set_master(ha->pdev);
2711 	pci_try_set_mwi(ha->pdev);
2712 
2713 	pci_read_config_word(ha->pdev, PCI_COMMAND, &w);
2714 	w |= (PCI_COMMAND_PARITY | PCI_COMMAND_SERR);
2715 	w &= ~PCI_COMMAND_INTX_DISABLE;
2716 	pci_write_config_word(ha->pdev, PCI_COMMAND, w);
2717 
2718 	pci_write_config_byte(ha->pdev, PCI_LATENCY_TIMER, 0x80);
2719 
2720 	/* PCI-X -- adjust Maximum Memory Read Byte Count (2048). */
2721 	if (pci_find_capability(ha->pdev, PCI_CAP_ID_PCIX))
2722 		pcix_set_mmrbc(ha->pdev, 2048);
2723 
2724 	/* PCIe -- adjust Maximum Read Request Size (2048). */
2725 	if (pci_is_pcie(ha->pdev))
2726 		pcie_set_readrq(ha->pdev, 4096);
2727 
2728 	pci_disable_rom(ha->pdev);
2729 
2730 	ha->chip_revision = ha->pdev->revision;
2731 
2732 	/* Get PCI bus information. */
2733 	spin_lock_irqsave(&ha->hardware_lock, flags);
2734 	ha->pci_attr = rd_reg_dword(&reg->ctrl_status);
2735 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
2736 
2737 	return QLA_SUCCESS;
2738 }
2739 
2740 /**
2741  * qla25xx_pci_config() - Setup ISP25xx PCI configuration registers.
2742  * @vha: HA context
2743  *
2744  * Returns 0 on success.
2745  */
2746 int
2747 qla25xx_pci_config(scsi_qla_host_t *vha)
2748 {
2749 	uint16_t w;
2750 	struct qla_hw_data *ha = vha->hw;
2751 
2752 	pci_set_master(ha->pdev);
2753 	pci_try_set_mwi(ha->pdev);
2754 
2755 	pci_read_config_word(ha->pdev, PCI_COMMAND, &w);
2756 	w |= (PCI_COMMAND_PARITY | PCI_COMMAND_SERR);
2757 	w &= ~PCI_COMMAND_INTX_DISABLE;
2758 	pci_write_config_word(ha->pdev, PCI_COMMAND, w);
2759 
2760 	/* PCIe -- adjust Maximum Read Request Size (2048). */
2761 	if (pci_is_pcie(ha->pdev))
2762 		pcie_set_readrq(ha->pdev, 4096);
2763 
2764 	pci_disable_rom(ha->pdev);
2765 
2766 	ha->chip_revision = ha->pdev->revision;
2767 
2768 	return QLA_SUCCESS;
2769 }
2770 
2771 /**
2772  * qla2x00_isp_firmware() - Choose firmware image.
2773  * @vha: HA context
2774  *
2775  * Returns 0 on success.
2776  */
2777 static int
2778 qla2x00_isp_firmware(scsi_qla_host_t *vha)
2779 {
2780 	int  rval;
2781 	uint16_t loop_id, topo, sw_cap;
2782 	uint8_t domain, area, al_pa;
2783 	struct qla_hw_data *ha = vha->hw;
2784 
2785 	/* Assume loading risc code */
2786 	rval = QLA_FUNCTION_FAILED;
2787 
2788 	if (ha->flags.disable_risc_code_load) {
2789 		ql_log(ql_log_info, vha, 0x0079, "RISC CODE NOT loaded.\n");
2790 
2791 		/* Verify checksum of loaded RISC code. */
2792 		rval = qla2x00_verify_checksum(vha, ha->fw_srisc_address);
2793 		if (rval == QLA_SUCCESS) {
2794 			/* And, verify we are not in ROM code. */
2795 			rval = qla2x00_get_adapter_id(vha, &loop_id, &al_pa,
2796 			    &area, &domain, &topo, &sw_cap);
2797 		}
2798 	}
2799 
2800 	if (rval)
2801 		ql_dbg(ql_dbg_init, vha, 0x007a,
2802 		    "**** Load RISC code ****.\n");
2803 
2804 	return (rval);
2805 }
2806 
2807 /**
2808  * qla2x00_reset_chip() - Reset ISP chip.
2809  * @vha: HA context
2810  *
2811  * Returns 0 on success.
2812  */
2813 int
2814 qla2x00_reset_chip(scsi_qla_host_t *vha)
2815 {
2816 	unsigned long   flags = 0;
2817 	struct qla_hw_data *ha = vha->hw;
2818 	struct device_reg_2xxx __iomem *reg = &ha->iobase->isp;
2819 	uint32_t	cnt;
2820 	uint16_t	cmd;
2821 	int rval = QLA_FUNCTION_FAILED;
2822 
2823 	if (unlikely(pci_channel_offline(ha->pdev)))
2824 		return rval;
2825 
2826 	ha->isp_ops->disable_intrs(ha);
2827 
2828 	spin_lock_irqsave(&ha->hardware_lock, flags);
2829 
2830 	/* Turn off master enable */
2831 	cmd = 0;
2832 	pci_read_config_word(ha->pdev, PCI_COMMAND, &cmd);
2833 	cmd &= ~PCI_COMMAND_MASTER;
2834 	pci_write_config_word(ha->pdev, PCI_COMMAND, cmd);
2835 
2836 	if (!IS_QLA2100(ha)) {
2837 		/* Pause RISC. */
2838 		wrt_reg_word(&reg->hccr, HCCR_PAUSE_RISC);
2839 		if (IS_QLA2200(ha) || IS_QLA2300(ha)) {
2840 			for (cnt = 0; cnt < 30000; cnt++) {
2841 				if ((rd_reg_word(&reg->hccr) &
2842 				    HCCR_RISC_PAUSE) != 0)
2843 					break;
2844 				udelay(100);
2845 			}
2846 		} else {
2847 			rd_reg_word(&reg->hccr);	/* PCI Posting. */
2848 			udelay(10);
2849 		}
2850 
2851 		/* Select FPM registers. */
2852 		wrt_reg_word(&reg->ctrl_status, 0x20);
2853 		rd_reg_word(&reg->ctrl_status);		/* PCI Posting. */
2854 
2855 		/* FPM Soft Reset. */
2856 		wrt_reg_word(&reg->fpm_diag_config, 0x100);
2857 		rd_reg_word(&reg->fpm_diag_config);	/* PCI Posting. */
2858 
2859 		/* Toggle Fpm Reset. */
2860 		if (!IS_QLA2200(ha)) {
2861 			wrt_reg_word(&reg->fpm_diag_config, 0x0);
2862 			rd_reg_word(&reg->fpm_diag_config); /* PCI Posting. */
2863 		}
2864 
2865 		/* Select frame buffer registers. */
2866 		wrt_reg_word(&reg->ctrl_status, 0x10);
2867 		rd_reg_word(&reg->ctrl_status);		/* PCI Posting. */
2868 
2869 		/* Reset frame buffer FIFOs. */
2870 		if (IS_QLA2200(ha)) {
2871 			WRT_FB_CMD_REG(ha, reg, 0xa000);
2872 			RD_FB_CMD_REG(ha, reg);		/* PCI Posting. */
2873 		} else {
2874 			WRT_FB_CMD_REG(ha, reg, 0x00fc);
2875 
2876 			/* Read back fb_cmd until zero or 3 seconds max */
2877 			for (cnt = 0; cnt < 3000; cnt++) {
2878 				if ((RD_FB_CMD_REG(ha, reg) & 0xff) == 0)
2879 					break;
2880 				udelay(100);
2881 			}
2882 		}
2883 
2884 		/* Select RISC module registers. */
2885 		wrt_reg_word(&reg->ctrl_status, 0);
2886 		rd_reg_word(&reg->ctrl_status);		/* PCI Posting. */
2887 
2888 		/* Reset RISC processor. */
2889 		wrt_reg_word(&reg->hccr, HCCR_RESET_RISC);
2890 		rd_reg_word(&reg->hccr);		/* PCI Posting. */
2891 
2892 		/* Release RISC processor. */
2893 		wrt_reg_word(&reg->hccr, HCCR_RELEASE_RISC);
2894 		rd_reg_word(&reg->hccr);		/* PCI Posting. */
2895 	}
2896 
2897 	wrt_reg_word(&reg->hccr, HCCR_CLR_RISC_INT);
2898 	wrt_reg_word(&reg->hccr, HCCR_CLR_HOST_INT);
2899 
2900 	/* Reset ISP chip. */
2901 	wrt_reg_word(&reg->ctrl_status, CSR_ISP_SOFT_RESET);
2902 
2903 	/* Wait for RISC to recover from reset. */
2904 	if (IS_QLA2100(ha) || IS_QLA2200(ha) || IS_QLA2300(ha)) {
2905 		/*
2906 		 * It is necessary to for a delay here since the card doesn't
2907 		 * respond to PCI reads during a reset. On some architectures
2908 		 * this will result in an MCA.
2909 		 */
2910 		udelay(20);
2911 		for (cnt = 30000; cnt; cnt--) {
2912 			if ((rd_reg_word(&reg->ctrl_status) &
2913 			    CSR_ISP_SOFT_RESET) == 0)
2914 				break;
2915 			udelay(100);
2916 		}
2917 	} else
2918 		udelay(10);
2919 
2920 	/* Reset RISC processor. */
2921 	wrt_reg_word(&reg->hccr, HCCR_RESET_RISC);
2922 
2923 	wrt_reg_word(&reg->semaphore, 0);
2924 
2925 	/* Release RISC processor. */
2926 	wrt_reg_word(&reg->hccr, HCCR_RELEASE_RISC);
2927 	rd_reg_word(&reg->hccr);			/* PCI Posting. */
2928 
2929 	if (IS_QLA2100(ha) || IS_QLA2200(ha) || IS_QLA2300(ha)) {
2930 		for (cnt = 0; cnt < 30000; cnt++) {
2931 			if (RD_MAILBOX_REG(ha, reg, 0) != MBS_BUSY)
2932 				break;
2933 
2934 			udelay(100);
2935 		}
2936 	} else
2937 		udelay(100);
2938 
2939 	/* Turn on master enable */
2940 	cmd |= PCI_COMMAND_MASTER;
2941 	pci_write_config_word(ha->pdev, PCI_COMMAND, cmd);
2942 
2943 	/* Disable RISC pause on FPM parity error. */
2944 	if (!IS_QLA2100(ha)) {
2945 		wrt_reg_word(&reg->hccr, HCCR_DISABLE_PARITY_PAUSE);
2946 		rd_reg_word(&reg->hccr);		/* PCI Posting. */
2947 	}
2948 
2949 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
2950 
2951 	return QLA_SUCCESS;
2952 }
2953 
2954 /**
2955  * qla81xx_reset_mpi() - Reset's MPI FW via Write MPI Register MBC.
2956  * @vha: HA context
2957  *
2958  * Returns 0 on success.
2959  */
2960 static int
2961 qla81xx_reset_mpi(scsi_qla_host_t *vha)
2962 {
2963 	uint16_t mb[4] = {0x1010, 0, 1, 0};
2964 
2965 	if (!IS_QLA81XX(vha->hw))
2966 		return QLA_SUCCESS;
2967 
2968 	return qla81xx_write_mpi_register(vha, mb);
2969 }
2970 
2971 static int
2972 qla_chk_risc_recovery(scsi_qla_host_t *vha)
2973 {
2974 	struct qla_hw_data *ha = vha->hw;
2975 	struct device_reg_24xx __iomem *reg = &ha->iobase->isp24;
2976 	__le16 __iomem *mbptr = &reg->mailbox0;
2977 	int i;
2978 	u16 mb[32];
2979 	int rc = QLA_SUCCESS;
2980 
2981 	if (!IS_QLA27XX(ha) && !IS_QLA28XX(ha))
2982 		return rc;
2983 
2984 	/* this check is only valid after RISC reset */
2985 	mb[0] = rd_reg_word(mbptr);
2986 	mbptr++;
2987 	if (mb[0] == 0xf) {
2988 		rc = QLA_FUNCTION_FAILED;
2989 
2990 		for (i = 1; i < 32; i++) {
2991 			mb[i] = rd_reg_word(mbptr);
2992 			mbptr++;
2993 		}
2994 
2995 		ql_log(ql_log_warn, vha, 0x1015,
2996 		       "RISC reset failed. mb[0-7] %04xh %04xh %04xh %04xh %04xh %04xh %04xh %04xh\n",
2997 		       mb[0], mb[1], mb[2], mb[3], mb[4], mb[5], mb[6], mb[7]);
2998 		ql_log(ql_log_warn, vha, 0x1015,
2999 		       "RISC reset failed. mb[8-15] %04xh %04xh %04xh %04xh %04xh %04xh %04xh %04xh\n",
3000 		       mb[8], mb[9], mb[10], mb[11], mb[12], mb[13], mb[14],
3001 		       mb[15]);
3002 		ql_log(ql_log_warn, vha, 0x1015,
3003 		       "RISC reset failed. mb[16-23] %04xh %04xh %04xh %04xh %04xh %04xh %04xh %04xh\n",
3004 		       mb[16], mb[17], mb[18], mb[19], mb[20], mb[21], mb[22],
3005 		       mb[23]);
3006 		ql_log(ql_log_warn, vha, 0x1015,
3007 		       "RISC reset failed. mb[24-31] %04xh %04xh %04xh %04xh %04xh %04xh %04xh %04xh\n",
3008 		       mb[24], mb[25], mb[26], mb[27], mb[28], mb[29], mb[30],
3009 		       mb[31]);
3010 	}
3011 	return rc;
3012 }
3013 
3014 /**
3015  * qla24xx_reset_risc() - Perform full reset of ISP24xx RISC.
3016  * @vha: HA context
3017  *
3018  * Returns 0 on success.
3019  */
3020 static inline int
3021 qla24xx_reset_risc(scsi_qla_host_t *vha)
3022 {
3023 	unsigned long flags = 0;
3024 	struct qla_hw_data *ha = vha->hw;
3025 	struct device_reg_24xx __iomem *reg = &ha->iobase->isp24;
3026 	uint32_t cnt;
3027 	uint16_t wd;
3028 	static int abts_cnt; /* ISP abort retry counts */
3029 	int rval = QLA_SUCCESS;
3030 	int print = 1;
3031 
3032 	spin_lock_irqsave(&ha->hardware_lock, flags);
3033 
3034 	/* Reset RISC. */
3035 	wrt_reg_dword(&reg->ctrl_status, CSRX_DMA_SHUTDOWN|MWB_4096_BYTES);
3036 	for (cnt = 0; cnt < 30000; cnt++) {
3037 		if ((rd_reg_dword(&reg->ctrl_status) & CSRX_DMA_ACTIVE) == 0)
3038 			break;
3039 
3040 		udelay(10);
3041 	}
3042 
3043 	if (!(rd_reg_dword(&reg->ctrl_status) & CSRX_DMA_ACTIVE))
3044 		set_bit(DMA_SHUTDOWN_CMPL, &ha->fw_dump_cap_flags);
3045 
3046 	ql_dbg(ql_dbg_init + ql_dbg_verbose, vha, 0x017e,
3047 	    "HCCR: 0x%x, Control Status %x, DMA active status:0x%x\n",
3048 	    rd_reg_dword(&reg->hccr),
3049 	    rd_reg_dword(&reg->ctrl_status),
3050 	    (rd_reg_dword(&reg->ctrl_status) & CSRX_DMA_ACTIVE));
3051 
3052 	wrt_reg_dword(&reg->ctrl_status,
3053 	    CSRX_ISP_SOFT_RESET|CSRX_DMA_SHUTDOWN|MWB_4096_BYTES);
3054 	pci_read_config_word(ha->pdev, PCI_COMMAND, &wd);
3055 
3056 	udelay(100);
3057 
3058 	/* Wait for firmware to complete NVRAM accesses. */
3059 	rd_reg_word(&reg->mailbox0);
3060 	for (cnt = 10000; rd_reg_word(&reg->mailbox0) != 0 &&
3061 	    rval == QLA_SUCCESS; cnt--) {
3062 		barrier();
3063 		if (cnt)
3064 			udelay(5);
3065 		else
3066 			rval = QLA_FUNCTION_TIMEOUT;
3067 	}
3068 
3069 	if (rval == QLA_SUCCESS)
3070 		set_bit(ISP_MBX_RDY, &ha->fw_dump_cap_flags);
3071 
3072 	ql_dbg(ql_dbg_init + ql_dbg_verbose, vha, 0x017f,
3073 	    "HCCR: 0x%x, MailBox0 Status 0x%x\n",
3074 	    rd_reg_dword(&reg->hccr),
3075 	    rd_reg_word(&reg->mailbox0));
3076 
3077 	/* Wait for soft-reset to complete. */
3078 	rd_reg_dword(&reg->ctrl_status);
3079 	for (cnt = 0; cnt < 60; cnt++) {
3080 		barrier();
3081 		if ((rd_reg_dword(&reg->ctrl_status) &
3082 		    CSRX_ISP_SOFT_RESET) == 0)
3083 			break;
3084 
3085 		udelay(5);
3086 	}
3087 	if (!(rd_reg_dword(&reg->ctrl_status) & CSRX_ISP_SOFT_RESET))
3088 		set_bit(ISP_SOFT_RESET_CMPL, &ha->fw_dump_cap_flags);
3089 
3090 	ql_dbg(ql_dbg_init + ql_dbg_verbose, vha, 0x015d,
3091 	    "HCCR: 0x%x, Soft Reset status: 0x%x\n",
3092 	    rd_reg_dword(&reg->hccr),
3093 	    rd_reg_dword(&reg->ctrl_status));
3094 
3095 	/* If required, do an MPI FW reset now */
3096 	if (test_and_clear_bit(MPI_RESET_NEEDED, &vha->dpc_flags)) {
3097 		if (qla81xx_reset_mpi(vha) != QLA_SUCCESS) {
3098 			if (++abts_cnt < 5) {
3099 				set_bit(ISP_ABORT_NEEDED, &vha->dpc_flags);
3100 				set_bit(MPI_RESET_NEEDED, &vha->dpc_flags);
3101 			} else {
3102 				/*
3103 				 * We exhausted the ISP abort retries. We have to
3104 				 * set the board offline.
3105 				 */
3106 				abts_cnt = 0;
3107 				vha->flags.online = 0;
3108 			}
3109 		}
3110 	}
3111 
3112 	wrt_reg_dword(&reg->hccr, HCCRX_SET_RISC_RESET);
3113 	rd_reg_dword(&reg->hccr);
3114 
3115 	wrt_reg_dword(&reg->hccr, HCCRX_REL_RISC_PAUSE);
3116 	rd_reg_dword(&reg->hccr);
3117 
3118 	wrt_reg_dword(&reg->hccr, HCCRX_CLR_RISC_RESET);
3119 	mdelay(10);
3120 	rd_reg_dword(&reg->hccr);
3121 
3122 	wd = rd_reg_word(&reg->mailbox0);
3123 	for (cnt = 300; wd != 0 && rval == QLA_SUCCESS; cnt--) {
3124 		barrier();
3125 		if (cnt) {
3126 			mdelay(1);
3127 			if (print && qla_chk_risc_recovery(vha))
3128 				print = 0;
3129 
3130 			wd = rd_reg_word(&reg->mailbox0);
3131 		} else {
3132 			rval = QLA_FUNCTION_TIMEOUT;
3133 
3134 			ql_log(ql_log_warn, vha, 0x015e,
3135 			       "RISC reset timeout\n");
3136 		}
3137 	}
3138 
3139 	if (rval == QLA_SUCCESS)
3140 		set_bit(RISC_RDY_AFT_RESET, &ha->fw_dump_cap_flags);
3141 
3142 	ql_dbg(ql_dbg_init + ql_dbg_verbose, vha, 0x015e,
3143 	    "Host Risc 0x%x, mailbox0 0x%x\n",
3144 	    rd_reg_dword(&reg->hccr),
3145 	     rd_reg_word(&reg->mailbox0));
3146 
3147 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
3148 
3149 	ql_dbg(ql_dbg_init + ql_dbg_verbose, vha, 0x015f,
3150 	    "Driver in %s mode\n",
3151 	    IS_NOPOLLING_TYPE(ha) ? "Interrupt" : "Polling");
3152 
3153 	if (IS_NOPOLLING_TYPE(ha))
3154 		ha->isp_ops->enable_intrs(ha);
3155 
3156 	return rval;
3157 }
3158 
3159 static void
3160 qla25xx_read_risc_sema_reg(scsi_qla_host_t *vha, uint32_t *data)
3161 {
3162 	struct device_reg_24xx __iomem *reg = &vha->hw->iobase->isp24;
3163 
3164 	wrt_reg_dword(&reg->iobase_addr, RISC_REGISTER_BASE_OFFSET);
3165 	*data = rd_reg_dword(&reg->iobase_window + RISC_REGISTER_WINDOW_OFFSET);
3166 }
3167 
3168 static void
3169 qla25xx_write_risc_sema_reg(scsi_qla_host_t *vha, uint32_t data)
3170 {
3171 	struct device_reg_24xx __iomem *reg = &vha->hw->iobase->isp24;
3172 
3173 	wrt_reg_dword(&reg->iobase_addr, RISC_REGISTER_BASE_OFFSET);
3174 	wrt_reg_dword(&reg->iobase_window + RISC_REGISTER_WINDOW_OFFSET, data);
3175 }
3176 
3177 static void
3178 qla25xx_manipulate_risc_semaphore(scsi_qla_host_t *vha)
3179 {
3180 	uint32_t wd32 = 0;
3181 	uint delta_msec = 100;
3182 	uint elapsed_msec = 0;
3183 	uint timeout_msec;
3184 	ulong n;
3185 
3186 	if (vha->hw->pdev->subsystem_device != 0x0175 &&
3187 	    vha->hw->pdev->subsystem_device != 0x0240)
3188 		return;
3189 
3190 	wrt_reg_dword(&vha->hw->iobase->isp24.hccr, HCCRX_SET_RISC_PAUSE);
3191 	udelay(100);
3192 
3193 attempt:
3194 	timeout_msec = TIMEOUT_SEMAPHORE;
3195 	n = timeout_msec / delta_msec;
3196 	while (n--) {
3197 		qla25xx_write_risc_sema_reg(vha, RISC_SEMAPHORE_SET);
3198 		qla25xx_read_risc_sema_reg(vha, &wd32);
3199 		if (wd32 & RISC_SEMAPHORE)
3200 			break;
3201 		msleep(delta_msec);
3202 		elapsed_msec += delta_msec;
3203 		if (elapsed_msec > TIMEOUT_TOTAL_ELAPSED)
3204 			goto force;
3205 	}
3206 
3207 	if (!(wd32 & RISC_SEMAPHORE))
3208 		goto force;
3209 
3210 	if (!(wd32 & RISC_SEMAPHORE_FORCE))
3211 		goto acquired;
3212 
3213 	qla25xx_write_risc_sema_reg(vha, RISC_SEMAPHORE_CLR);
3214 	timeout_msec = TIMEOUT_SEMAPHORE_FORCE;
3215 	n = timeout_msec / delta_msec;
3216 	while (n--) {
3217 		qla25xx_read_risc_sema_reg(vha, &wd32);
3218 		if (!(wd32 & RISC_SEMAPHORE_FORCE))
3219 			break;
3220 		msleep(delta_msec);
3221 		elapsed_msec += delta_msec;
3222 		if (elapsed_msec > TIMEOUT_TOTAL_ELAPSED)
3223 			goto force;
3224 	}
3225 
3226 	if (wd32 & RISC_SEMAPHORE_FORCE)
3227 		qla25xx_write_risc_sema_reg(vha, RISC_SEMAPHORE_FORCE_CLR);
3228 
3229 	goto attempt;
3230 
3231 force:
3232 	qla25xx_write_risc_sema_reg(vha, RISC_SEMAPHORE_FORCE_SET);
3233 
3234 acquired:
3235 	return;
3236 }
3237 
3238 /**
3239  * qla24xx_reset_chip() - Reset ISP24xx chip.
3240  * @vha: HA context
3241  *
3242  * Returns 0 on success.
3243  */
3244 int
3245 qla24xx_reset_chip(scsi_qla_host_t *vha)
3246 {
3247 	struct qla_hw_data *ha = vha->hw;
3248 	int rval = QLA_FUNCTION_FAILED;
3249 
3250 	if (pci_channel_offline(ha->pdev) &&
3251 	    ha->flags.pci_channel_io_perm_failure) {
3252 		return rval;
3253 	}
3254 
3255 	ha->isp_ops->disable_intrs(ha);
3256 
3257 	qla25xx_manipulate_risc_semaphore(vha);
3258 
3259 	/* Perform RISC reset. */
3260 	rval = qla24xx_reset_risc(vha);
3261 
3262 	return rval;
3263 }
3264 
3265 /**
3266  * qla2x00_chip_diag() - Test chip for proper operation.
3267  * @vha: HA context
3268  *
3269  * Returns 0 on success.
3270  */
3271 int
3272 qla2x00_chip_diag(scsi_qla_host_t *vha)
3273 {
3274 	int		rval;
3275 	struct qla_hw_data *ha = vha->hw;
3276 	struct device_reg_2xxx __iomem *reg = &ha->iobase->isp;
3277 	unsigned long	flags = 0;
3278 	uint16_t	data;
3279 	uint32_t	cnt;
3280 	uint16_t	mb[5];
3281 	struct req_que *req = ha->req_q_map[0];
3282 
3283 	/* Assume a failed state */
3284 	rval = QLA_FUNCTION_FAILED;
3285 
3286 	ql_dbg(ql_dbg_init, vha, 0x007b, "Testing device at %p.\n",
3287 	       &reg->flash_address);
3288 
3289 	spin_lock_irqsave(&ha->hardware_lock, flags);
3290 
3291 	/* Reset ISP chip. */
3292 	wrt_reg_word(&reg->ctrl_status, CSR_ISP_SOFT_RESET);
3293 
3294 	/*
3295 	 * We need to have a delay here since the card will not respond while
3296 	 * in reset causing an MCA on some architectures.
3297 	 */
3298 	udelay(20);
3299 	data = qla2x00_debounce_register(&reg->ctrl_status);
3300 	for (cnt = 6000000 ; cnt && (data & CSR_ISP_SOFT_RESET); cnt--) {
3301 		udelay(5);
3302 		data = rd_reg_word(&reg->ctrl_status);
3303 		barrier();
3304 	}
3305 
3306 	if (!cnt)
3307 		goto chip_diag_failed;
3308 
3309 	ql_dbg(ql_dbg_init, vha, 0x007c,
3310 	    "Reset register cleared by chip reset.\n");
3311 
3312 	/* Reset RISC processor. */
3313 	wrt_reg_word(&reg->hccr, HCCR_RESET_RISC);
3314 	wrt_reg_word(&reg->hccr, HCCR_RELEASE_RISC);
3315 
3316 	/* Workaround for QLA2312 PCI parity error */
3317 	if (IS_QLA2100(ha) || IS_QLA2200(ha) || IS_QLA2300(ha)) {
3318 		data = qla2x00_debounce_register(MAILBOX_REG(ha, reg, 0));
3319 		for (cnt = 6000000; cnt && (data == MBS_BUSY); cnt--) {
3320 			udelay(5);
3321 			data = RD_MAILBOX_REG(ha, reg, 0);
3322 			barrier();
3323 		}
3324 	} else
3325 		udelay(10);
3326 
3327 	if (!cnt)
3328 		goto chip_diag_failed;
3329 
3330 	/* Check product ID of chip */
3331 	ql_dbg(ql_dbg_init, vha, 0x007d, "Checking product ID of chip.\n");
3332 
3333 	mb[1] = RD_MAILBOX_REG(ha, reg, 1);
3334 	mb[2] = RD_MAILBOX_REG(ha, reg, 2);
3335 	mb[3] = RD_MAILBOX_REG(ha, reg, 3);
3336 	mb[4] = qla2x00_debounce_register(MAILBOX_REG(ha, reg, 4));
3337 	if (mb[1] != PROD_ID_1 || (mb[2] != PROD_ID_2 && mb[2] != PROD_ID_2a) ||
3338 	    mb[3] != PROD_ID_3) {
3339 		ql_log(ql_log_warn, vha, 0x0062,
3340 		    "Wrong product ID = 0x%x,0x%x,0x%x.\n",
3341 		    mb[1], mb[2], mb[3]);
3342 
3343 		goto chip_diag_failed;
3344 	}
3345 	ha->product_id[0] = mb[1];
3346 	ha->product_id[1] = mb[2];
3347 	ha->product_id[2] = mb[3];
3348 	ha->product_id[3] = mb[4];
3349 
3350 	/* Adjust fw RISC transfer size */
3351 	if (req->length > 1024)
3352 		ha->fw_transfer_size = REQUEST_ENTRY_SIZE * 1024;
3353 	else
3354 		ha->fw_transfer_size = REQUEST_ENTRY_SIZE *
3355 		    req->length;
3356 
3357 	if (IS_QLA2200(ha) &&
3358 	    RD_MAILBOX_REG(ha, reg, 7) == QLA2200A_RISC_ROM_VER) {
3359 		/* Limit firmware transfer size with a 2200A */
3360 		ql_dbg(ql_dbg_init, vha, 0x007e, "Found QLA2200A Chip.\n");
3361 
3362 		ha->device_type |= DT_ISP2200A;
3363 		ha->fw_transfer_size = 128;
3364 	}
3365 
3366 	/* Wrap Incoming Mailboxes Test. */
3367 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
3368 
3369 	ql_dbg(ql_dbg_init, vha, 0x007f, "Checking mailboxes.\n");
3370 	rval = qla2x00_mbx_reg_test(vha);
3371 	if (rval)
3372 		ql_log(ql_log_warn, vha, 0x0080,
3373 		    "Failed mailbox send register test.\n");
3374 	else
3375 		/* Flag a successful rval */
3376 		rval = QLA_SUCCESS;
3377 	spin_lock_irqsave(&ha->hardware_lock, flags);
3378 
3379 chip_diag_failed:
3380 	if (rval)
3381 		ql_log(ql_log_info, vha, 0x0081,
3382 		    "Chip diagnostics **** FAILED ****.\n");
3383 
3384 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
3385 
3386 	return (rval);
3387 }
3388 
3389 /**
3390  * qla24xx_chip_diag() - Test ISP24xx for proper operation.
3391  * @vha: HA context
3392  *
3393  * Returns 0 on success.
3394  */
3395 int
3396 qla24xx_chip_diag(scsi_qla_host_t *vha)
3397 {
3398 	int rval;
3399 	struct qla_hw_data *ha = vha->hw;
3400 	struct req_que *req = ha->req_q_map[0];
3401 
3402 	if (IS_P3P_TYPE(ha))
3403 		return QLA_SUCCESS;
3404 
3405 	ha->fw_transfer_size = REQUEST_ENTRY_SIZE * req->length;
3406 
3407 	rval = qla2x00_mbx_reg_test(vha);
3408 	if (rval) {
3409 		ql_log(ql_log_warn, vha, 0x0082,
3410 		    "Failed mailbox send register test.\n");
3411 	} else {
3412 		/* Flag a successful rval */
3413 		rval = QLA_SUCCESS;
3414 	}
3415 
3416 	return rval;
3417 }
3418 
3419 static void
3420 qla2x00_init_fce_trace(scsi_qla_host_t *vha)
3421 {
3422 	int rval;
3423 	dma_addr_t tc_dma;
3424 	void *tc;
3425 	struct qla_hw_data *ha = vha->hw;
3426 
3427 	if (!IS_FWI2_CAPABLE(ha))
3428 		return;
3429 
3430 	if (!IS_QLA25XX(ha) && !IS_QLA81XX(ha) && !IS_QLA83XX(ha) &&
3431 	    !IS_QLA27XX(ha) && !IS_QLA28XX(ha))
3432 		return;
3433 
3434 	if (ha->fce) {
3435 		ql_dbg(ql_dbg_init, vha, 0x00bd,
3436 		       "%s: FCE Mem is already allocated.\n",
3437 		       __func__);
3438 		return;
3439 	}
3440 
3441 	/* Allocate memory for Fibre Channel Event Buffer. */
3442 	tc = dma_alloc_coherent(&ha->pdev->dev, FCE_SIZE, &tc_dma,
3443 				GFP_KERNEL);
3444 	if (!tc) {
3445 		ql_log(ql_log_warn, vha, 0x00be,
3446 		       "Unable to allocate (%d KB) for FCE.\n",
3447 		       FCE_SIZE / 1024);
3448 		return;
3449 	}
3450 
3451 	rval = qla2x00_enable_fce_trace(vha, tc_dma, FCE_NUM_BUFFERS,
3452 					ha->fce_mb, &ha->fce_bufs);
3453 	if (rval) {
3454 		ql_log(ql_log_warn, vha, 0x00bf,
3455 		       "Unable to initialize FCE (%d).\n", rval);
3456 		dma_free_coherent(&ha->pdev->dev, FCE_SIZE, tc, tc_dma);
3457 		return;
3458 	}
3459 
3460 	ql_dbg(ql_dbg_init, vha, 0x00c0,
3461 	       "Allocated (%d KB) for FCE...\n", FCE_SIZE / 1024);
3462 
3463 	ha->flags.fce_enabled = 1;
3464 	ha->fce_dma = tc_dma;
3465 	ha->fce = tc;
3466 }
3467 
3468 static void
3469 qla2x00_init_eft_trace(scsi_qla_host_t *vha)
3470 {
3471 	int rval;
3472 	dma_addr_t tc_dma;
3473 	void *tc;
3474 	struct qla_hw_data *ha = vha->hw;
3475 
3476 	if (!IS_FWI2_CAPABLE(ha))
3477 		return;
3478 
3479 	if (ha->eft) {
3480 		ql_dbg(ql_dbg_init, vha, 0x00bd,
3481 		    "%s: EFT Mem is already allocated.\n",
3482 		    __func__);
3483 		return;
3484 	}
3485 
3486 	/* Allocate memory for Extended Trace Buffer. */
3487 	tc = dma_alloc_coherent(&ha->pdev->dev, EFT_SIZE, &tc_dma,
3488 				GFP_KERNEL);
3489 	if (!tc) {
3490 		ql_log(ql_log_warn, vha, 0x00c1,
3491 		       "Unable to allocate (%d KB) for EFT.\n",
3492 		       EFT_SIZE / 1024);
3493 		return;
3494 	}
3495 
3496 	rval = qla2x00_enable_eft_trace(vha, tc_dma, EFT_NUM_BUFFERS);
3497 	if (rval) {
3498 		ql_log(ql_log_warn, vha, 0x00c2,
3499 		       "Unable to initialize EFT (%d).\n", rval);
3500 		dma_free_coherent(&ha->pdev->dev, EFT_SIZE, tc, tc_dma);
3501 		return;
3502 	}
3503 
3504 	ql_dbg(ql_dbg_init, vha, 0x00c3,
3505 	       "Allocated (%d KB) EFT ...\n", EFT_SIZE / 1024);
3506 
3507 	ha->eft_dma = tc_dma;
3508 	ha->eft = tc;
3509 }
3510 
3511 static void
3512 qla2x00_alloc_offload_mem(scsi_qla_host_t *vha)
3513 {
3514 	qla2x00_init_fce_trace(vha);
3515 	qla2x00_init_eft_trace(vha);
3516 }
3517 
3518 void
3519 qla2x00_alloc_fw_dump(scsi_qla_host_t *vha)
3520 {
3521 	uint32_t dump_size, fixed_size, mem_size, req_q_size, rsp_q_size,
3522 	    eft_size, fce_size, mq_size;
3523 	struct qla_hw_data *ha = vha->hw;
3524 	struct req_que *req = ha->req_q_map[0];
3525 	struct rsp_que *rsp = ha->rsp_q_map[0];
3526 	struct qla2xxx_fw_dump *fw_dump;
3527 
3528 	if (ha->fw_dump) {
3529 		ql_dbg(ql_dbg_init, vha, 0x00bd,
3530 		    "Firmware dump already allocated.\n");
3531 		return;
3532 	}
3533 
3534 	ha->fw_dumped = 0;
3535 	ha->fw_dump_cap_flags = 0;
3536 	dump_size = fixed_size = mem_size = eft_size = fce_size = mq_size = 0;
3537 	req_q_size = rsp_q_size = 0;
3538 
3539 	if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
3540 		fixed_size = sizeof(struct qla2100_fw_dump);
3541 	} else if (IS_QLA23XX(ha)) {
3542 		fixed_size = offsetof(struct qla2300_fw_dump, data_ram);
3543 		mem_size = (ha->fw_memory_size - 0x11000 + 1) *
3544 		    sizeof(uint16_t);
3545 	} else if (IS_FWI2_CAPABLE(ha)) {
3546 		if (IS_QLA83XX(ha))
3547 			fixed_size = offsetof(struct qla83xx_fw_dump, ext_mem);
3548 		else if (IS_QLA81XX(ha))
3549 			fixed_size = offsetof(struct qla81xx_fw_dump, ext_mem);
3550 		else if (IS_QLA25XX(ha))
3551 			fixed_size = offsetof(struct qla25xx_fw_dump, ext_mem);
3552 		else
3553 			fixed_size = offsetof(struct qla24xx_fw_dump, ext_mem);
3554 
3555 		mem_size = (ha->fw_memory_size - 0x100000 + 1) *
3556 		    sizeof(uint32_t);
3557 		if (ha->mqenable) {
3558 			if (!IS_QLA83XX(ha))
3559 				mq_size = sizeof(struct qla2xxx_mq_chain);
3560 			/*
3561 			 * Allocate maximum buffer size for all queues - Q0.
3562 			 * Resizing must be done at end-of-dump processing.
3563 			 */
3564 			mq_size += (ha->max_req_queues - 1) *
3565 			    (req->length * sizeof(request_t));
3566 			mq_size += (ha->max_rsp_queues - 1) *
3567 			    (rsp->length * sizeof(response_t));
3568 		}
3569 		if (ha->tgt.atio_ring)
3570 			mq_size += ha->tgt.atio_q_length * sizeof(request_t);
3571 
3572 		qla2x00_init_fce_trace(vha);
3573 		if (ha->fce)
3574 			fce_size = sizeof(struct qla2xxx_fce_chain) + FCE_SIZE;
3575 		qla2x00_init_eft_trace(vha);
3576 		if (ha->eft)
3577 			eft_size = EFT_SIZE;
3578 	}
3579 
3580 	if (IS_QLA27XX(ha) || IS_QLA28XX(ha)) {
3581 		struct fwdt *fwdt = ha->fwdt;
3582 		uint j;
3583 
3584 		for (j = 0; j < 2; j++, fwdt++) {
3585 			if (!fwdt->template) {
3586 				ql_dbg(ql_dbg_init, vha, 0x00ba,
3587 				    "-> fwdt%u no template\n", j);
3588 				continue;
3589 			}
3590 			ql_dbg(ql_dbg_init, vha, 0x00fa,
3591 			    "-> fwdt%u calculating fwdump size...\n", j);
3592 			fwdt->dump_size = qla27xx_fwdt_calculate_dump_size(
3593 			    vha, fwdt->template);
3594 			ql_dbg(ql_dbg_init, vha, 0x00fa,
3595 			    "-> fwdt%u calculated fwdump size = %#lx bytes\n",
3596 			    j, fwdt->dump_size);
3597 			dump_size += fwdt->dump_size;
3598 		}
3599 		/* Add space for spare MPI fw dump. */
3600 		dump_size += ha->fwdt[1].dump_size;
3601 	} else {
3602 		req_q_size = req->length * sizeof(request_t);
3603 		rsp_q_size = rsp->length * sizeof(response_t);
3604 		dump_size = offsetof(struct qla2xxx_fw_dump, isp);
3605 		dump_size += fixed_size + mem_size + req_q_size + rsp_q_size
3606 			+ eft_size;
3607 		ha->chain_offset = dump_size;
3608 		dump_size += mq_size + fce_size;
3609 		if (ha->exchoffld_buf)
3610 			dump_size += sizeof(struct qla2xxx_offld_chain) +
3611 				ha->exchoffld_size;
3612 		if (ha->exlogin_buf)
3613 			dump_size += sizeof(struct qla2xxx_offld_chain) +
3614 				ha->exlogin_size;
3615 	}
3616 
3617 	if (!ha->fw_dump_len || dump_size > ha->fw_dump_alloc_len) {
3618 
3619 		ql_dbg(ql_dbg_init, vha, 0x00c5,
3620 		    "%s dump_size %d fw_dump_len %d fw_dump_alloc_len %d\n",
3621 		    __func__, dump_size, ha->fw_dump_len,
3622 		    ha->fw_dump_alloc_len);
3623 
3624 		fw_dump = vmalloc(dump_size);
3625 		if (!fw_dump) {
3626 			ql_log(ql_log_warn, vha, 0x00c4,
3627 			    "Unable to allocate (%d KB) for firmware dump.\n",
3628 			    dump_size / 1024);
3629 		} else {
3630 			mutex_lock(&ha->optrom_mutex);
3631 			if (ha->fw_dumped) {
3632 				memcpy(fw_dump, ha->fw_dump, ha->fw_dump_len);
3633 				vfree(ha->fw_dump);
3634 				ha->fw_dump = fw_dump;
3635 				ha->fw_dump_alloc_len =  dump_size;
3636 				ql_dbg(ql_dbg_init, vha, 0x00c5,
3637 				    "Re-Allocated (%d KB) and save firmware dump.\n",
3638 				    dump_size / 1024);
3639 			} else {
3640 				vfree(ha->fw_dump);
3641 				ha->fw_dump = fw_dump;
3642 
3643 				ha->fw_dump_len = ha->fw_dump_alloc_len =
3644 				    dump_size;
3645 				ql_dbg(ql_dbg_init, vha, 0x00c5,
3646 				    "Allocated (%d KB) for firmware dump.\n",
3647 				    dump_size / 1024);
3648 
3649 				if (IS_QLA27XX(ha) || IS_QLA28XX(ha)) {
3650 					ha->mpi_fw_dump = (char *)fw_dump +
3651 						ha->fwdt[1].dump_size;
3652 					mutex_unlock(&ha->optrom_mutex);
3653 					return;
3654 				}
3655 
3656 				ha->fw_dump->signature[0] = 'Q';
3657 				ha->fw_dump->signature[1] = 'L';
3658 				ha->fw_dump->signature[2] = 'G';
3659 				ha->fw_dump->signature[3] = 'C';
3660 				ha->fw_dump->version = htonl(1);
3661 
3662 				ha->fw_dump->fixed_size = htonl(fixed_size);
3663 				ha->fw_dump->mem_size = htonl(mem_size);
3664 				ha->fw_dump->req_q_size = htonl(req_q_size);
3665 				ha->fw_dump->rsp_q_size = htonl(rsp_q_size);
3666 
3667 				ha->fw_dump->eft_size = htonl(eft_size);
3668 				ha->fw_dump->eft_addr_l =
3669 				    htonl(LSD(ha->eft_dma));
3670 				ha->fw_dump->eft_addr_h =
3671 				    htonl(MSD(ha->eft_dma));
3672 
3673 				ha->fw_dump->header_size =
3674 					htonl(offsetof
3675 					    (struct qla2xxx_fw_dump, isp));
3676 			}
3677 			mutex_unlock(&ha->optrom_mutex);
3678 		}
3679 	}
3680 }
3681 
3682 static int
3683 qla81xx_mpi_sync(scsi_qla_host_t *vha)
3684 {
3685 #define MPS_MASK	0xe0
3686 	int rval;
3687 	uint16_t dc;
3688 	uint32_t dw;
3689 
3690 	if (!IS_QLA81XX(vha->hw))
3691 		return QLA_SUCCESS;
3692 
3693 	rval = qla2x00_write_ram_word(vha, 0x7c00, 1);
3694 	if (rval != QLA_SUCCESS) {
3695 		ql_log(ql_log_warn, vha, 0x0105,
3696 		    "Unable to acquire semaphore.\n");
3697 		goto done;
3698 	}
3699 
3700 	pci_read_config_word(vha->hw->pdev, 0x54, &dc);
3701 	rval = qla2x00_read_ram_word(vha, 0x7a15, &dw);
3702 	if (rval != QLA_SUCCESS) {
3703 		ql_log(ql_log_warn, vha, 0x0067, "Unable to read sync.\n");
3704 		goto done_release;
3705 	}
3706 
3707 	dc &= MPS_MASK;
3708 	if (dc == (dw & MPS_MASK))
3709 		goto done_release;
3710 
3711 	dw &= ~MPS_MASK;
3712 	dw |= dc;
3713 	rval = qla2x00_write_ram_word(vha, 0x7a15, dw);
3714 	if (rval != QLA_SUCCESS) {
3715 		ql_log(ql_log_warn, vha, 0x0114, "Unable to gain sync.\n");
3716 	}
3717 
3718 done_release:
3719 	rval = qla2x00_write_ram_word(vha, 0x7c00, 0);
3720 	if (rval != QLA_SUCCESS) {
3721 		ql_log(ql_log_warn, vha, 0x006d,
3722 		    "Unable to release semaphore.\n");
3723 	}
3724 
3725 done:
3726 	return rval;
3727 }
3728 
3729 int
3730 qla2x00_alloc_outstanding_cmds(struct qla_hw_data *ha, struct req_que *req)
3731 {
3732 	/* Don't try to reallocate the array */
3733 	if (req->outstanding_cmds)
3734 		return QLA_SUCCESS;
3735 
3736 	if (!IS_FWI2_CAPABLE(ha))
3737 		req->num_outstanding_cmds = DEFAULT_OUTSTANDING_COMMANDS;
3738 	else {
3739 		if (ha->cur_fw_xcb_count <= ha->cur_fw_iocb_count)
3740 			req->num_outstanding_cmds = ha->cur_fw_xcb_count;
3741 		else
3742 			req->num_outstanding_cmds = ha->cur_fw_iocb_count;
3743 	}
3744 
3745 	req->outstanding_cmds = kcalloc(req->num_outstanding_cmds,
3746 					sizeof(srb_t *),
3747 					GFP_KERNEL);
3748 
3749 	if (!req->outstanding_cmds) {
3750 		/*
3751 		 * Try to allocate a minimal size just so we can get through
3752 		 * initialization.
3753 		 */
3754 		req->num_outstanding_cmds = MIN_OUTSTANDING_COMMANDS;
3755 		req->outstanding_cmds = kcalloc(req->num_outstanding_cmds,
3756 						sizeof(srb_t *),
3757 						GFP_KERNEL);
3758 
3759 		if (!req->outstanding_cmds) {
3760 			ql_log(ql_log_fatal, NULL, 0x0126,
3761 			    "Failed to allocate memory for "
3762 			    "outstanding_cmds for req_que %p.\n", req);
3763 			req->num_outstanding_cmds = 0;
3764 			return QLA_FUNCTION_FAILED;
3765 		}
3766 	}
3767 
3768 	return QLA_SUCCESS;
3769 }
3770 
3771 #define PRINT_FIELD(_field, _flag, _str) {		\
3772 	if (a0->_field & _flag) {\
3773 		if (p) {\
3774 			strcat(ptr, "|");\
3775 			ptr++;\
3776 			leftover--;\
3777 		} \
3778 		len = snprintf(ptr, leftover, "%s", _str);	\
3779 		p = 1;\
3780 		leftover -= len;\
3781 		ptr += len; \
3782 	} \
3783 }
3784 
3785 static void qla2xxx_print_sfp_info(struct scsi_qla_host *vha)
3786 {
3787 #define STR_LEN 64
3788 	struct sff_8247_a0 *a0 = (struct sff_8247_a0 *)vha->hw->sfp_data;
3789 	u8 str[STR_LEN], *ptr, p;
3790 	int leftover, len;
3791 
3792 	memset(str, 0, STR_LEN);
3793 	snprintf(str, SFF_VEN_NAME_LEN+1, a0->vendor_name);
3794 	ql_dbg(ql_dbg_init, vha, 0x015a,
3795 	    "SFP MFG Name: %s\n", str);
3796 
3797 	memset(str, 0, STR_LEN);
3798 	snprintf(str, SFF_PART_NAME_LEN+1, a0->vendor_pn);
3799 	ql_dbg(ql_dbg_init, vha, 0x015c,
3800 	    "SFP Part Name: %s\n", str);
3801 
3802 	/* media */
3803 	memset(str, 0, STR_LEN);
3804 	ptr = str;
3805 	leftover = STR_LEN;
3806 	p = len = 0;
3807 	PRINT_FIELD(fc_med_cc9, FC_MED_TW, "Twin AX");
3808 	PRINT_FIELD(fc_med_cc9, FC_MED_TP, "Twisted Pair");
3809 	PRINT_FIELD(fc_med_cc9, FC_MED_MI, "Min Coax");
3810 	PRINT_FIELD(fc_med_cc9, FC_MED_TV, "Video Coax");
3811 	PRINT_FIELD(fc_med_cc9, FC_MED_M6, "MultiMode 62.5um");
3812 	PRINT_FIELD(fc_med_cc9, FC_MED_M5, "MultiMode 50um");
3813 	PRINT_FIELD(fc_med_cc9, FC_MED_SM, "SingleMode");
3814 	ql_dbg(ql_dbg_init, vha, 0x0160,
3815 	    "SFP Media: %s\n", str);
3816 
3817 	/* link length */
3818 	memset(str, 0, STR_LEN);
3819 	ptr = str;
3820 	leftover = STR_LEN;
3821 	p = len = 0;
3822 	PRINT_FIELD(fc_ll_cc7, FC_LL_VL, "Very Long");
3823 	PRINT_FIELD(fc_ll_cc7, FC_LL_S, "Short");
3824 	PRINT_FIELD(fc_ll_cc7, FC_LL_I, "Intermediate");
3825 	PRINT_FIELD(fc_ll_cc7, FC_LL_L, "Long");
3826 	PRINT_FIELD(fc_ll_cc7, FC_LL_M, "Medium");
3827 	ql_dbg(ql_dbg_init, vha, 0x0196,
3828 	    "SFP Link Length: %s\n", str);
3829 
3830 	memset(str, 0, STR_LEN);
3831 	ptr = str;
3832 	leftover = STR_LEN;
3833 	p = len = 0;
3834 	PRINT_FIELD(fc_ll_cc7, FC_LL_SA, "Short Wave (SA)");
3835 	PRINT_FIELD(fc_ll_cc7, FC_LL_LC, "Long Wave(LC)");
3836 	PRINT_FIELD(fc_tec_cc8, FC_TEC_SN, "Short Wave (SN)");
3837 	PRINT_FIELD(fc_tec_cc8, FC_TEC_SL, "Short Wave (SL)");
3838 	PRINT_FIELD(fc_tec_cc8, FC_TEC_LL, "Long Wave (LL)");
3839 	ql_dbg(ql_dbg_init, vha, 0x016e,
3840 	    "SFP FC Link Tech: %s\n", str);
3841 
3842 	if (a0->length_km)
3843 		ql_dbg(ql_dbg_init, vha, 0x016f,
3844 		    "SFP Distant: %d km\n", a0->length_km);
3845 	if (a0->length_100m)
3846 		ql_dbg(ql_dbg_init, vha, 0x0170,
3847 		    "SFP Distant: %d m\n", a0->length_100m*100);
3848 	if (a0->length_50um_10m)
3849 		ql_dbg(ql_dbg_init, vha, 0x0189,
3850 		    "SFP Distant (WL=50um): %d m\n", a0->length_50um_10m * 10);
3851 	if (a0->length_62um_10m)
3852 		ql_dbg(ql_dbg_init, vha, 0x018a,
3853 		  "SFP Distant (WL=62.5um): %d m\n", a0->length_62um_10m * 10);
3854 	if (a0->length_om4_10m)
3855 		ql_dbg(ql_dbg_init, vha, 0x0194,
3856 		    "SFP Distant (OM4): %d m\n", a0->length_om4_10m * 10);
3857 	if (a0->length_om3_10m)
3858 		ql_dbg(ql_dbg_init, vha, 0x0195,
3859 		    "SFP Distant (OM3): %d m\n", a0->length_om3_10m * 10);
3860 }
3861 
3862 
3863 /**
3864  * qla24xx_detect_sfp()
3865  *
3866  * @vha: adapter state pointer.
3867  *
3868  * @return
3869  *	0 -- Configure firmware to use short-range settings -- normal
3870  *	     buffer-to-buffer credits.
3871  *
3872  *	1 -- Configure firmware to use long-range settings -- extra
3873  *	     buffer-to-buffer credits should be allocated with
3874  *	     ha->lr_distance containing distance settings from NVRAM or SFP
3875  *	     (if supported).
3876  */
3877 int
3878 qla24xx_detect_sfp(scsi_qla_host_t *vha)
3879 {
3880 	int rc, used_nvram;
3881 	struct sff_8247_a0 *a;
3882 	struct qla_hw_data *ha = vha->hw;
3883 	struct nvram_81xx *nv = ha->nvram;
3884 #define LR_DISTANCE_UNKNOWN	2
3885 	static const char * const types[] = { "Short", "Long" };
3886 	static const char * const lengths[] = { "(10km)", "(5km)", "" };
3887 	u8 ll = 0;
3888 
3889 	/* Seed with NVRAM settings. */
3890 	used_nvram = 0;
3891 	ha->flags.lr_detected = 0;
3892 	if (IS_BPM_RANGE_CAPABLE(ha) &&
3893 	    (nv->enhanced_features & NEF_LR_DIST_ENABLE)) {
3894 		used_nvram = 1;
3895 		ha->flags.lr_detected = 1;
3896 		ha->lr_distance =
3897 		    (nv->enhanced_features >> LR_DIST_NV_POS)
3898 		     & LR_DIST_NV_MASK;
3899 	}
3900 
3901 	if (!IS_BPM_ENABLED(vha))
3902 		goto out;
3903 	/* Determine SR/LR capabilities of SFP/Transceiver. */
3904 	rc = qla2x00_read_sfp_dev(vha, NULL, 0);
3905 	if (rc)
3906 		goto out;
3907 
3908 	used_nvram = 0;
3909 	a = (struct sff_8247_a0 *)vha->hw->sfp_data;
3910 	qla2xxx_print_sfp_info(vha);
3911 
3912 	ha->flags.lr_detected = 0;
3913 	ll = a->fc_ll_cc7;
3914 	if (ll & FC_LL_VL || ll & FC_LL_L) {
3915 		/* Long range, track length. */
3916 		ha->flags.lr_detected = 1;
3917 
3918 		if (a->length_km > 5 || a->length_100m > 50)
3919 			ha->lr_distance = LR_DISTANCE_10K;
3920 		else
3921 			ha->lr_distance = LR_DISTANCE_5K;
3922 	}
3923 
3924 out:
3925 	ql_dbg(ql_dbg_async, vha, 0x507b,
3926 	    "SFP detect: %s-Range SFP %s (nvr=%x ll=%x lr=%x lrd=%x).\n",
3927 	    types[ha->flags.lr_detected],
3928 	    ha->flags.lr_detected ? lengths[ha->lr_distance] :
3929 	       lengths[LR_DISTANCE_UNKNOWN],
3930 	    used_nvram, ll, ha->flags.lr_detected, ha->lr_distance);
3931 	return ha->flags.lr_detected;
3932 }
3933 
3934 void qla_init_iocb_limit(scsi_qla_host_t *vha)
3935 {
3936 	u16 i, num_qps;
3937 	u32 limit;
3938 	struct qla_hw_data *ha = vha->hw;
3939 
3940 	num_qps = ha->num_qpairs + 1;
3941 	limit = (ha->orig_fw_iocb_count * QLA_IOCB_PCT_LIMIT) / 100;
3942 
3943 	ha->base_qpair->fwres.iocbs_total = ha->orig_fw_iocb_count;
3944 	ha->base_qpair->fwres.iocbs_limit = limit;
3945 	ha->base_qpair->fwres.iocbs_qp_limit = limit / num_qps;
3946 	ha->base_qpair->fwres.iocbs_used = 0;
3947 
3948 	ha->base_qpair->fwres.exch_total = ha->orig_fw_xcb_count;
3949 	ha->base_qpair->fwres.exch_limit = (ha->orig_fw_xcb_count *
3950 					    QLA_IOCB_PCT_LIMIT) / 100;
3951 	ha->base_qpair->fwres.exch_used  = 0;
3952 
3953 	for (i = 0; i < ha->max_qpairs; i++) {
3954 		if (ha->queue_pair_map[i])  {
3955 			ha->queue_pair_map[i]->fwres.iocbs_total =
3956 				ha->orig_fw_iocb_count;
3957 			ha->queue_pair_map[i]->fwres.iocbs_limit = limit;
3958 			ha->queue_pair_map[i]->fwres.iocbs_qp_limit =
3959 				limit / num_qps;
3960 			ha->queue_pair_map[i]->fwres.iocbs_used = 0;
3961 			ha->queue_pair_map[i]->fwres.exch_total = ha->orig_fw_xcb_count;
3962 			ha->queue_pair_map[i]->fwres.exch_limit =
3963 				(ha->orig_fw_xcb_count * QLA_IOCB_PCT_LIMIT) / 100;
3964 			ha->queue_pair_map[i]->fwres.exch_used = 0;
3965 		}
3966 	}
3967 }
3968 
3969 /**
3970  * qla2x00_setup_chip() - Load and start RISC firmware.
3971  * @vha: HA context
3972  *
3973  * Returns 0 on success.
3974  */
3975 static int
3976 qla2x00_setup_chip(scsi_qla_host_t *vha)
3977 {
3978 	int rval;
3979 	uint32_t srisc_address = 0;
3980 	struct qla_hw_data *ha = vha->hw;
3981 	struct device_reg_2xxx __iomem *reg = &ha->iobase->isp;
3982 	unsigned long flags;
3983 	uint16_t fw_major_version;
3984 	int done_once = 0;
3985 
3986 	if (IS_P3P_TYPE(ha)) {
3987 		rval = ha->isp_ops->load_risc(vha, &srisc_address);
3988 		if (rval == QLA_SUCCESS) {
3989 			qla2x00_stop_firmware(vha);
3990 			goto enable_82xx_npiv;
3991 		} else
3992 			goto failed;
3993 	}
3994 
3995 	if (!IS_FWI2_CAPABLE(ha) && !IS_QLA2100(ha) && !IS_QLA2200(ha)) {
3996 		/* Disable SRAM, Instruction RAM and GP RAM parity.  */
3997 		spin_lock_irqsave(&ha->hardware_lock, flags);
3998 		wrt_reg_word(&reg->hccr, (HCCR_ENABLE_PARITY + 0x0));
3999 		rd_reg_word(&reg->hccr);
4000 		spin_unlock_irqrestore(&ha->hardware_lock, flags);
4001 	}
4002 
4003 	qla81xx_mpi_sync(vha);
4004 
4005 execute_fw_with_lr:
4006 	/* Load firmware sequences */
4007 	rval = ha->isp_ops->load_risc(vha, &srisc_address);
4008 	if (rval == QLA_SUCCESS) {
4009 		ql_dbg(ql_dbg_init, vha, 0x00c9,
4010 		    "Verifying Checksum of loaded RISC code.\n");
4011 
4012 		rval = qla2x00_verify_checksum(vha, srisc_address);
4013 		if (rval == QLA_SUCCESS) {
4014 			/* Start firmware execution. */
4015 			ql_dbg(ql_dbg_init, vha, 0x00ca,
4016 			    "Starting firmware.\n");
4017 
4018 			if (ql2xexlogins)
4019 				ha->flags.exlogins_enabled = 1;
4020 
4021 			if (qla_is_exch_offld_enabled(vha))
4022 				ha->flags.exchoffld_enabled = 1;
4023 
4024 			rval = qla2x00_execute_fw(vha, srisc_address);
4025 			/* Retrieve firmware information. */
4026 			if (rval == QLA_SUCCESS) {
4027 				/* Enable BPM support? */
4028 				if (!done_once++ && qla24xx_detect_sfp(vha)) {
4029 					ql_dbg(ql_dbg_init, vha, 0x00ca,
4030 					    "Re-starting firmware -- BPM.\n");
4031 					/* Best-effort - re-init. */
4032 					ha->isp_ops->reset_chip(vha);
4033 					ha->isp_ops->chip_diag(vha);
4034 					goto execute_fw_with_lr;
4035 				}
4036 
4037 				if (IS_ZIO_THRESHOLD_CAPABLE(ha))
4038 					qla27xx_set_zio_threshold(vha,
4039 					    ha->last_zio_threshold);
4040 
4041 				rval = qla2x00_set_exlogins_buffer(vha);
4042 				if (rval != QLA_SUCCESS)
4043 					goto failed;
4044 
4045 				rval = qla2x00_set_exchoffld_buffer(vha);
4046 				if (rval != QLA_SUCCESS)
4047 					goto failed;
4048 
4049 enable_82xx_npiv:
4050 				fw_major_version = ha->fw_major_version;
4051 				if (IS_P3P_TYPE(ha))
4052 					qla82xx_check_md_needed(vha);
4053 				else
4054 					rval = qla2x00_get_fw_version(vha);
4055 				if (rval != QLA_SUCCESS)
4056 					goto failed;
4057 				ha->flags.npiv_supported = 0;
4058 				if (IS_QLA2XXX_MIDTYPE(ha) &&
4059 					 (ha->fw_attributes & BIT_2)) {
4060 					ha->flags.npiv_supported = 1;
4061 					if ((!ha->max_npiv_vports) ||
4062 					    ((ha->max_npiv_vports + 1) %
4063 					    MIN_MULTI_ID_FABRIC))
4064 						ha->max_npiv_vports =
4065 						    MIN_MULTI_ID_FABRIC - 1;
4066 				}
4067 				qla2x00_get_resource_cnts(vha);
4068 				qla_init_iocb_limit(vha);
4069 
4070 				/*
4071 				 * Allocate the array of outstanding commands
4072 				 * now that we know the firmware resources.
4073 				 */
4074 				rval = qla2x00_alloc_outstanding_cmds(ha,
4075 				    vha->req);
4076 				if (rval != QLA_SUCCESS)
4077 					goto failed;
4078 
4079 				if (!fw_major_version && !(IS_P3P_TYPE(ha)))
4080 					qla2x00_alloc_offload_mem(vha);
4081 
4082 				if (ql2xallocfwdump && !(IS_P3P_TYPE(ha)))
4083 					qla2x00_alloc_fw_dump(vha);
4084 
4085 			} else {
4086 				goto failed;
4087 			}
4088 		} else {
4089 			ql_log(ql_log_fatal, vha, 0x00cd,
4090 			    "ISP Firmware failed checksum.\n");
4091 			goto failed;
4092 		}
4093 
4094 		/* Enable PUREX PASSTHRU */
4095 		if (ql2xrdpenable || ha->flags.scm_supported_f ||
4096 		    ha->flags.edif_enabled)
4097 			qla25xx_set_els_cmds_supported(vha);
4098 	} else
4099 		goto failed;
4100 
4101 	if (!IS_FWI2_CAPABLE(ha) && !IS_QLA2100(ha) && !IS_QLA2200(ha)) {
4102 		/* Enable proper parity. */
4103 		spin_lock_irqsave(&ha->hardware_lock, flags);
4104 		if (IS_QLA2300(ha))
4105 			/* SRAM parity */
4106 			wrt_reg_word(&reg->hccr, HCCR_ENABLE_PARITY + 0x1);
4107 		else
4108 			/* SRAM, Instruction RAM and GP RAM parity */
4109 			wrt_reg_word(&reg->hccr, HCCR_ENABLE_PARITY + 0x7);
4110 		rd_reg_word(&reg->hccr);
4111 		spin_unlock_irqrestore(&ha->hardware_lock, flags);
4112 	}
4113 
4114 	if (IS_QLA27XX(ha) || IS_QLA28XX(ha))
4115 		ha->flags.fac_supported = 1;
4116 	else if (rval == QLA_SUCCESS && IS_FAC_REQUIRED(ha)) {
4117 		uint32_t size;
4118 
4119 		rval = qla81xx_fac_get_sector_size(vha, &size);
4120 		if (rval == QLA_SUCCESS) {
4121 			ha->flags.fac_supported = 1;
4122 			ha->fdt_block_size = size << 2;
4123 		} else {
4124 			ql_log(ql_log_warn, vha, 0x00ce,
4125 			    "Unsupported FAC firmware (%d.%02d.%02d).\n",
4126 			    ha->fw_major_version, ha->fw_minor_version,
4127 			    ha->fw_subminor_version);
4128 
4129 			if (IS_QLA83XX(ha)) {
4130 				ha->flags.fac_supported = 0;
4131 				rval = QLA_SUCCESS;
4132 			}
4133 		}
4134 	}
4135 failed:
4136 	if (rval) {
4137 		ql_log(ql_log_fatal, vha, 0x00cf,
4138 		    "Setup chip ****FAILED****.\n");
4139 	}
4140 
4141 	return (rval);
4142 }
4143 
4144 /**
4145  * qla2x00_init_response_q_entries() - Initializes response queue entries.
4146  * @rsp: response queue
4147  *
4148  * Beginning of request ring has initialization control block already built
4149  * by nvram config routine.
4150  *
4151  * Returns 0 on success.
4152  */
4153 void
4154 qla2x00_init_response_q_entries(struct rsp_que *rsp)
4155 {
4156 	uint16_t cnt;
4157 	response_t *pkt;
4158 
4159 	rsp->ring_ptr = rsp->ring;
4160 	rsp->ring_index    = 0;
4161 	rsp->status_srb = NULL;
4162 	pkt = rsp->ring_ptr;
4163 	for (cnt = 0; cnt < rsp->length; cnt++) {
4164 		pkt->signature = RESPONSE_PROCESSED;
4165 		pkt++;
4166 	}
4167 }
4168 
4169 /**
4170  * qla2x00_update_fw_options() - Read and process firmware options.
4171  * @vha: HA context
4172  *
4173  * Returns 0 on success.
4174  */
4175 void
4176 qla2x00_update_fw_options(scsi_qla_host_t *vha)
4177 {
4178 	uint16_t swing, emphasis, tx_sens, rx_sens;
4179 	struct qla_hw_data *ha = vha->hw;
4180 
4181 	memset(ha->fw_options, 0, sizeof(ha->fw_options));
4182 	qla2x00_get_fw_options(vha, ha->fw_options);
4183 
4184 	if (IS_QLA2100(ha) || IS_QLA2200(ha))
4185 		return;
4186 
4187 	/* Serial Link options. */
4188 	ql_dbg(ql_dbg_init + ql_dbg_buffer, vha, 0x0115,
4189 	    "Serial link options.\n");
4190 	ql_dump_buffer(ql_dbg_init + ql_dbg_buffer, vha, 0x0109,
4191 	    ha->fw_seriallink_options, sizeof(ha->fw_seriallink_options));
4192 
4193 	ha->fw_options[1] &= ~FO1_SET_EMPHASIS_SWING;
4194 	if (ha->fw_seriallink_options[3] & BIT_2) {
4195 		ha->fw_options[1] |= FO1_SET_EMPHASIS_SWING;
4196 
4197 		/*  1G settings */
4198 		swing = ha->fw_seriallink_options[2] & (BIT_2 | BIT_1 | BIT_0);
4199 		emphasis = (ha->fw_seriallink_options[2] &
4200 		    (BIT_4 | BIT_3)) >> 3;
4201 		tx_sens = ha->fw_seriallink_options[0] &
4202 		    (BIT_3 | BIT_2 | BIT_1 | BIT_0);
4203 		rx_sens = (ha->fw_seriallink_options[0] &
4204 		    (BIT_7 | BIT_6 | BIT_5 | BIT_4)) >> 4;
4205 		ha->fw_options[10] = (emphasis << 14) | (swing << 8);
4206 		if (IS_QLA2300(ha) || IS_QLA2312(ha) || IS_QLA6312(ha)) {
4207 			if (rx_sens == 0x0)
4208 				rx_sens = 0x3;
4209 			ha->fw_options[10] |= (tx_sens << 4) | rx_sens;
4210 		} else if (IS_QLA2322(ha) || IS_QLA6322(ha))
4211 			ha->fw_options[10] |= BIT_5 |
4212 			    ((rx_sens & (BIT_1 | BIT_0)) << 2) |
4213 			    (tx_sens & (BIT_1 | BIT_0));
4214 
4215 		/*  2G settings */
4216 		swing = (ha->fw_seriallink_options[2] &
4217 		    (BIT_7 | BIT_6 | BIT_5)) >> 5;
4218 		emphasis = ha->fw_seriallink_options[3] & (BIT_1 | BIT_0);
4219 		tx_sens = ha->fw_seriallink_options[1] &
4220 		    (BIT_3 | BIT_2 | BIT_1 | BIT_0);
4221 		rx_sens = (ha->fw_seriallink_options[1] &
4222 		    (BIT_7 | BIT_6 | BIT_5 | BIT_4)) >> 4;
4223 		ha->fw_options[11] = (emphasis << 14) | (swing << 8);
4224 		if (IS_QLA2300(ha) || IS_QLA2312(ha) || IS_QLA6312(ha)) {
4225 			if (rx_sens == 0x0)
4226 				rx_sens = 0x3;
4227 			ha->fw_options[11] |= (tx_sens << 4) | rx_sens;
4228 		} else if (IS_QLA2322(ha) || IS_QLA6322(ha))
4229 			ha->fw_options[11] |= BIT_5 |
4230 			    ((rx_sens & (BIT_1 | BIT_0)) << 2) |
4231 			    (tx_sens & (BIT_1 | BIT_0));
4232 	}
4233 
4234 	/* FCP2 options. */
4235 	/*  Return command IOCBs without waiting for an ABTS to complete. */
4236 	ha->fw_options[3] |= BIT_13;
4237 
4238 	/* LED scheme. */
4239 	if (ha->flags.enable_led_scheme)
4240 		ha->fw_options[2] |= BIT_12;
4241 
4242 	/* Detect ISP6312. */
4243 	if (IS_QLA6312(ha))
4244 		ha->fw_options[2] |= BIT_13;
4245 
4246 	/* Set Retry FLOGI in case of P2P connection */
4247 	if (ha->operating_mode == P2P) {
4248 		ha->fw_options[2] |= BIT_3;
4249 		ql_dbg(ql_dbg_disc, vha, 0x2100,
4250 		    "(%s): Setting FLOGI retry BIT in fw_options[2]: 0x%x\n",
4251 			__func__, ha->fw_options[2]);
4252 	}
4253 
4254 	/* Update firmware options. */
4255 	qla2x00_set_fw_options(vha, ha->fw_options);
4256 }
4257 
4258 void
4259 qla24xx_update_fw_options(scsi_qla_host_t *vha)
4260 {
4261 	int rval;
4262 	struct qla_hw_data *ha = vha->hw;
4263 
4264 	if (IS_P3P_TYPE(ha))
4265 		return;
4266 
4267 	/*  Hold status IOCBs until ABTS response received. */
4268 	if (ql2xfwholdabts)
4269 		ha->fw_options[3] |= BIT_12;
4270 
4271 	/* Set Retry FLOGI in case of P2P connection */
4272 	if (ha->operating_mode == P2P) {
4273 		ha->fw_options[2] |= BIT_3;
4274 		ql_dbg(ql_dbg_disc, vha, 0x2101,
4275 		    "(%s): Setting FLOGI retry BIT in fw_options[2]: 0x%x\n",
4276 			__func__, ha->fw_options[2]);
4277 	}
4278 
4279 	/* Move PUREX, ABTS RX & RIDA to ATIOQ */
4280 	if (ql2xmvasynctoatio && !ha->flags.edif_enabled &&
4281 	    (IS_QLA83XX(ha) || IS_QLA27XX(ha) || IS_QLA28XX(ha))) {
4282 		if (qla_tgt_mode_enabled(vha) ||
4283 		    qla_dual_mode_enabled(vha))
4284 			ha->fw_options[2] |= BIT_11;
4285 		else
4286 			ha->fw_options[2] &= ~BIT_11;
4287 	}
4288 
4289 	if (IS_QLA25XX(ha) || IS_QLA83XX(ha) || IS_QLA27XX(ha) ||
4290 	    IS_QLA28XX(ha)) {
4291 		/*
4292 		 * Tell FW to track each exchange to prevent
4293 		 * driver from using stale exchange.
4294 		 */
4295 		if (qla_tgt_mode_enabled(vha) ||
4296 		    qla_dual_mode_enabled(vha))
4297 			ha->fw_options[2] |= BIT_4;
4298 		else
4299 			ha->fw_options[2] &= ~(BIT_4);
4300 
4301 		/* Reserve 1/2 of emergency exchanges for ELS.*/
4302 		if (qla2xuseresexchforels)
4303 			ha->fw_options[2] |= BIT_8;
4304 		else
4305 			ha->fw_options[2] &= ~BIT_8;
4306 
4307 		/*
4308 		 * N2N: set Secure=1 for PLOGI ACC and
4309 		 * fw shal not send PRLI after PLOGI Acc
4310 		 */
4311 		if (ha->flags.edif_enabled &&
4312 		    DBELL_ACTIVE(vha)) {
4313 			ha->fw_options[3] |= BIT_15;
4314 			ha->flags.n2n_fw_acc_sec = 1;
4315 		} else {
4316 			ha->fw_options[3] &= ~BIT_15;
4317 			ha->flags.n2n_fw_acc_sec = 0;
4318 		}
4319 	}
4320 
4321 	if (ql2xrdpenable || ha->flags.scm_supported_f ||
4322 	    ha->flags.edif_enabled)
4323 		ha->fw_options[1] |= ADD_FO1_ENABLE_PUREX_IOCB;
4324 
4325 	/* Enable Async 8130/8131 events -- transceiver insertion/removal */
4326 	if (IS_BPM_RANGE_CAPABLE(ha))
4327 		ha->fw_options[3] |= BIT_10;
4328 
4329 	ql_dbg(ql_dbg_init, vha, 0x00e8,
4330 	    "%s, add FW options 1-3 = 0x%04x 0x%04x 0x%04x mode %x\n",
4331 	    __func__, ha->fw_options[1], ha->fw_options[2],
4332 	    ha->fw_options[3], vha->host->active_mode);
4333 
4334 	if (ha->fw_options[1] || ha->fw_options[2] || ha->fw_options[3])
4335 		qla2x00_set_fw_options(vha, ha->fw_options);
4336 
4337 	/* Update Serial Link options. */
4338 	if ((le16_to_cpu(ha->fw_seriallink_options24[0]) & BIT_0) == 0)
4339 		return;
4340 
4341 	rval = qla2x00_set_serdes_params(vha,
4342 	    le16_to_cpu(ha->fw_seriallink_options24[1]),
4343 	    le16_to_cpu(ha->fw_seriallink_options24[2]),
4344 	    le16_to_cpu(ha->fw_seriallink_options24[3]));
4345 	if (rval != QLA_SUCCESS) {
4346 		ql_log(ql_log_warn, vha, 0x0104,
4347 		    "Unable to update Serial Link options (%x).\n", rval);
4348 	}
4349 }
4350 
4351 void
4352 qla2x00_config_rings(struct scsi_qla_host *vha)
4353 {
4354 	struct qla_hw_data *ha = vha->hw;
4355 	struct device_reg_2xxx __iomem *reg = &ha->iobase->isp;
4356 	struct req_que *req = ha->req_q_map[0];
4357 	struct rsp_que *rsp = ha->rsp_q_map[0];
4358 
4359 	/* Setup ring parameters in initialization control block. */
4360 	ha->init_cb->request_q_outpointer = cpu_to_le16(0);
4361 	ha->init_cb->response_q_inpointer = cpu_to_le16(0);
4362 	ha->init_cb->request_q_length = cpu_to_le16(req->length);
4363 	ha->init_cb->response_q_length = cpu_to_le16(rsp->length);
4364 	put_unaligned_le64(req->dma, &ha->init_cb->request_q_address);
4365 	put_unaligned_le64(rsp->dma, &ha->init_cb->response_q_address);
4366 
4367 	wrt_reg_word(ISP_REQ_Q_IN(ha, reg), 0);
4368 	wrt_reg_word(ISP_REQ_Q_OUT(ha, reg), 0);
4369 	wrt_reg_word(ISP_RSP_Q_IN(ha, reg), 0);
4370 	wrt_reg_word(ISP_RSP_Q_OUT(ha, reg), 0);
4371 	rd_reg_word(ISP_RSP_Q_OUT(ha, reg));		/* PCI Posting. */
4372 }
4373 
4374 void
4375 qla24xx_config_rings(struct scsi_qla_host *vha)
4376 {
4377 	struct qla_hw_data *ha = vha->hw;
4378 	device_reg_t *reg = ISP_QUE_REG(ha, 0);
4379 	struct device_reg_2xxx __iomem *ioreg = &ha->iobase->isp;
4380 	struct qla_msix_entry *msix;
4381 	struct init_cb_24xx *icb;
4382 	uint16_t rid = 0;
4383 	struct req_que *req = ha->req_q_map[0];
4384 	struct rsp_que *rsp = ha->rsp_q_map[0];
4385 
4386 	/* Setup ring parameters in initialization control block. */
4387 	icb = (struct init_cb_24xx *)ha->init_cb;
4388 	icb->request_q_outpointer = cpu_to_le16(0);
4389 	icb->response_q_inpointer = cpu_to_le16(0);
4390 	icb->request_q_length = cpu_to_le16(req->length);
4391 	icb->response_q_length = cpu_to_le16(rsp->length);
4392 	put_unaligned_le64(req->dma, &icb->request_q_address);
4393 	put_unaligned_le64(rsp->dma, &icb->response_q_address);
4394 
4395 	/* Setup ATIO queue dma pointers for target mode */
4396 	icb->atio_q_inpointer = cpu_to_le16(0);
4397 	icb->atio_q_length = cpu_to_le16(ha->tgt.atio_q_length);
4398 	put_unaligned_le64(ha->tgt.atio_dma, &icb->atio_q_address);
4399 
4400 	if (IS_SHADOW_REG_CAPABLE(ha))
4401 		icb->firmware_options_2 |= cpu_to_le32(BIT_30|BIT_29);
4402 
4403 	if (ha->mqenable || IS_QLA83XX(ha) || IS_QLA27XX(ha) ||
4404 	    IS_QLA28XX(ha)) {
4405 		icb->qos = cpu_to_le16(QLA_DEFAULT_QUE_QOS);
4406 		icb->rid = cpu_to_le16(rid);
4407 		if (ha->flags.msix_enabled) {
4408 			msix = &ha->msix_entries[1];
4409 			ql_dbg(ql_dbg_init, vha, 0x0019,
4410 			    "Registering vector 0x%x for base que.\n",
4411 			    msix->entry);
4412 			icb->msix = cpu_to_le16(msix->entry);
4413 		}
4414 		/* Use alternate PCI bus number */
4415 		if (MSB(rid))
4416 			icb->firmware_options_2 |= cpu_to_le32(BIT_19);
4417 		/* Use alternate PCI devfn */
4418 		if (LSB(rid))
4419 			icb->firmware_options_2 |= cpu_to_le32(BIT_18);
4420 
4421 		/* Use Disable MSIX Handshake mode for capable adapters */
4422 		if ((ha->fw_attributes & BIT_6) && (IS_MSIX_NACK_CAPABLE(ha)) &&
4423 		    (ha->flags.msix_enabled)) {
4424 			icb->firmware_options_2 &= cpu_to_le32(~BIT_22);
4425 			ha->flags.disable_msix_handshake = 1;
4426 			ql_dbg(ql_dbg_init, vha, 0x00fe,
4427 			    "MSIX Handshake Disable Mode turned on.\n");
4428 		} else {
4429 			icb->firmware_options_2 |= cpu_to_le32(BIT_22);
4430 		}
4431 		icb->firmware_options_2 |= cpu_to_le32(BIT_23);
4432 
4433 		wrt_reg_dword(&reg->isp25mq.req_q_in, 0);
4434 		wrt_reg_dword(&reg->isp25mq.req_q_out, 0);
4435 		wrt_reg_dword(&reg->isp25mq.rsp_q_in, 0);
4436 		wrt_reg_dword(&reg->isp25mq.rsp_q_out, 0);
4437 	} else {
4438 		wrt_reg_dword(&reg->isp24.req_q_in, 0);
4439 		wrt_reg_dword(&reg->isp24.req_q_out, 0);
4440 		wrt_reg_dword(&reg->isp24.rsp_q_in, 0);
4441 		wrt_reg_dword(&reg->isp24.rsp_q_out, 0);
4442 	}
4443 
4444 	qlt_24xx_config_rings(vha);
4445 
4446 	/* If the user has configured the speed, set it here */
4447 	if (ha->set_data_rate) {
4448 		ql_dbg(ql_dbg_init, vha, 0x00fd,
4449 		    "Speed set by user : %s Gbps \n",
4450 		    qla2x00_get_link_speed_str(ha, ha->set_data_rate));
4451 		icb->firmware_options_3 = cpu_to_le32(ha->set_data_rate << 13);
4452 	}
4453 
4454 	/* PCI posting */
4455 	rd_reg_word(&ioreg->hccr);
4456 }
4457 
4458 /**
4459  * qla2x00_init_rings() - Initializes firmware.
4460  * @vha: HA context
4461  *
4462  * Beginning of request ring has initialization control block already built
4463  * by nvram config routine.
4464  *
4465  * Returns 0 on success.
4466  */
4467 int
4468 qla2x00_init_rings(scsi_qla_host_t *vha)
4469 {
4470 	int	rval;
4471 	unsigned long flags = 0;
4472 	int cnt, que;
4473 	struct qla_hw_data *ha = vha->hw;
4474 	struct req_que *req;
4475 	struct rsp_que *rsp;
4476 	struct mid_init_cb_24xx *mid_init_cb =
4477 	    (struct mid_init_cb_24xx *) ha->init_cb;
4478 
4479 	spin_lock_irqsave(&ha->hardware_lock, flags);
4480 
4481 	/* Clear outstanding commands array. */
4482 	for (que = 0; que < ha->max_req_queues; que++) {
4483 		req = ha->req_q_map[que];
4484 		if (!req || !test_bit(que, ha->req_qid_map))
4485 			continue;
4486 		req->out_ptr = (uint16_t *)(req->ring + req->length);
4487 		*req->out_ptr = 0;
4488 		for (cnt = 1; cnt < req->num_outstanding_cmds; cnt++)
4489 			req->outstanding_cmds[cnt] = NULL;
4490 
4491 		req->current_outstanding_cmd = 1;
4492 
4493 		/* Initialize firmware. */
4494 		req->ring_ptr  = req->ring;
4495 		req->ring_index    = 0;
4496 		req->cnt      = req->length;
4497 	}
4498 
4499 	for (que = 0; que < ha->max_rsp_queues; que++) {
4500 		rsp = ha->rsp_q_map[que];
4501 		if (!rsp || !test_bit(que, ha->rsp_qid_map))
4502 			continue;
4503 		rsp->in_ptr = (uint16_t *)(rsp->ring + rsp->length);
4504 		*rsp->in_ptr = 0;
4505 		/* Initialize response queue entries */
4506 		if (IS_QLAFX00(ha))
4507 			qlafx00_init_response_q_entries(rsp);
4508 		else
4509 			qla2x00_init_response_q_entries(rsp);
4510 	}
4511 
4512 	ha->tgt.atio_ring_ptr = ha->tgt.atio_ring;
4513 	ha->tgt.atio_ring_index = 0;
4514 	/* Initialize ATIO queue entries */
4515 	qlt_init_atio_q_entries(vha);
4516 
4517 	ha->isp_ops->config_rings(vha);
4518 
4519 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
4520 
4521 	if (IS_QLAFX00(ha)) {
4522 		rval = qlafx00_init_firmware(vha, ha->init_cb_size);
4523 		goto next_check;
4524 	}
4525 
4526 	/* Update any ISP specific firmware options before initialization. */
4527 	ha->isp_ops->update_fw_options(vha);
4528 
4529 	ql_dbg(ql_dbg_init, vha, 0x00d1,
4530 	       "Issue init firmware FW opt 1-3= %08x %08x %08x.\n",
4531 	       le32_to_cpu(mid_init_cb->init_cb.firmware_options_1),
4532 	       le32_to_cpu(mid_init_cb->init_cb.firmware_options_2),
4533 	       le32_to_cpu(mid_init_cb->init_cb.firmware_options_3));
4534 
4535 	if (ha->flags.npiv_supported) {
4536 		if (ha->operating_mode == LOOP && !IS_CNA_CAPABLE(ha))
4537 			ha->max_npiv_vports = MIN_MULTI_ID_FABRIC - 1;
4538 		mid_init_cb->count = cpu_to_le16(ha->max_npiv_vports);
4539 	}
4540 
4541 	if (IS_FWI2_CAPABLE(ha)) {
4542 		mid_init_cb->options = cpu_to_le16(BIT_1);
4543 		mid_init_cb->init_cb.execution_throttle =
4544 		    cpu_to_le16(ha->cur_fw_xcb_count);
4545 		ha->flags.dport_enabled =
4546 			(le32_to_cpu(mid_init_cb->init_cb.firmware_options_1) &
4547 			 BIT_7) != 0;
4548 		ql_dbg(ql_dbg_init, vha, 0x0191, "DPORT Support: %s.\n",
4549 		    (ha->flags.dport_enabled) ? "enabled" : "disabled");
4550 		/* FA-WWPN Status */
4551 		ha->flags.fawwpn_enabled =
4552 			(le32_to_cpu(mid_init_cb->init_cb.firmware_options_1) &
4553 			 BIT_6) != 0;
4554 		ql_dbg(ql_dbg_init, vha, 0x00bc, "FA-WWPN Support: %s.\n",
4555 		    (ha->flags.fawwpn_enabled) ? "enabled" : "disabled");
4556 		/* Init_cb will be reused for other command(s).  Save a backup copy of port_name */
4557 		memcpy(ha->port_name, ha->init_cb->port_name, WWN_SIZE);
4558 	}
4559 
4560 	/* ELS pass through payload is limit by frame size. */
4561 	if (ha->flags.edif_enabled)
4562 		mid_init_cb->init_cb.frame_payload_size = cpu_to_le16(ELS_MAX_PAYLOAD);
4563 
4564 	rval = qla2x00_init_firmware(vha, ha->init_cb_size);
4565 next_check:
4566 	if (rval) {
4567 		ql_log(ql_log_fatal, vha, 0x00d2,
4568 		    "Init Firmware **** FAILED ****.\n");
4569 	} else {
4570 		ql_dbg(ql_dbg_init, vha, 0x00d3,
4571 		    "Init Firmware -- success.\n");
4572 		QLA_FW_STARTED(ha);
4573 		vha->u_ql2xexchoffld = vha->u_ql2xiniexchg = 0;
4574 	}
4575 
4576 	return (rval);
4577 }
4578 
4579 /**
4580  * qla2x00_fw_ready() - Waits for firmware ready.
4581  * @vha: HA context
4582  *
4583  * Returns 0 on success.
4584  */
4585 static int
4586 qla2x00_fw_ready(scsi_qla_host_t *vha)
4587 {
4588 	int		rval;
4589 	unsigned long	wtime, mtime, cs84xx_time;
4590 	uint16_t	min_wait;	/* Minimum wait time if loop is down */
4591 	uint16_t	wait_time;	/* Wait time if loop is coming ready */
4592 	uint16_t	state[6];
4593 	struct qla_hw_data *ha = vha->hw;
4594 
4595 	if (IS_QLAFX00(vha->hw))
4596 		return qlafx00_fw_ready(vha);
4597 
4598 	/* Time to wait for loop down */
4599 	if (IS_P3P_TYPE(ha))
4600 		min_wait = 30;
4601 	else
4602 		min_wait = 20;
4603 
4604 	/*
4605 	 * Firmware should take at most one RATOV to login, plus 5 seconds for
4606 	 * our own processing.
4607 	 */
4608 	if ((wait_time = (ha->retry_count*ha->login_timeout) + 5) < min_wait) {
4609 		wait_time = min_wait;
4610 	}
4611 
4612 	/* Min wait time if loop down */
4613 	mtime = jiffies + (min_wait * HZ);
4614 
4615 	/* wait time before firmware ready */
4616 	wtime = jiffies + (wait_time * HZ);
4617 
4618 	/* Wait for ISP to finish LIP */
4619 	if (!vha->flags.init_done)
4620 		ql_log(ql_log_info, vha, 0x801e,
4621 		    "Waiting for LIP to complete.\n");
4622 
4623 	do {
4624 		memset(state, -1, sizeof(state));
4625 		rval = qla2x00_get_firmware_state(vha, state);
4626 		if (rval == QLA_SUCCESS) {
4627 			if (state[0] < FSTATE_LOSS_OF_SYNC) {
4628 				vha->device_flags &= ~DFLG_NO_CABLE;
4629 			}
4630 			if (IS_QLA84XX(ha) && state[0] != FSTATE_READY) {
4631 				ql_dbg(ql_dbg_taskm, vha, 0x801f,
4632 				    "fw_state=%x 84xx=%x.\n", state[0],
4633 				    state[2]);
4634 				if ((state[2] & FSTATE_LOGGED_IN) &&
4635 				     (state[2] & FSTATE_WAITING_FOR_VERIFY)) {
4636 					ql_dbg(ql_dbg_taskm, vha, 0x8028,
4637 					    "Sending verify iocb.\n");
4638 
4639 					cs84xx_time = jiffies;
4640 					rval = qla84xx_init_chip(vha);
4641 					if (rval != QLA_SUCCESS) {
4642 						ql_log(ql_log_warn,
4643 						    vha, 0x8007,
4644 						    "Init chip failed.\n");
4645 						break;
4646 					}
4647 
4648 					/* Add time taken to initialize. */
4649 					cs84xx_time = jiffies - cs84xx_time;
4650 					wtime += cs84xx_time;
4651 					mtime += cs84xx_time;
4652 					ql_dbg(ql_dbg_taskm, vha, 0x8008,
4653 					    "Increasing wait time by %ld. "
4654 					    "New time %ld.\n", cs84xx_time,
4655 					    wtime);
4656 				}
4657 			} else if (state[0] == FSTATE_READY) {
4658 				ql_dbg(ql_dbg_taskm, vha, 0x8037,
4659 				    "F/W Ready - OK.\n");
4660 
4661 				qla2x00_get_retry_cnt(vha, &ha->retry_count,
4662 				    &ha->login_timeout, &ha->r_a_tov);
4663 
4664 				rval = QLA_SUCCESS;
4665 				break;
4666 			}
4667 
4668 			rval = QLA_FUNCTION_FAILED;
4669 
4670 			if (atomic_read(&vha->loop_down_timer) &&
4671 			    state[0] != FSTATE_READY) {
4672 				/* Loop down. Timeout on min_wait for states
4673 				 * other than Wait for Login.
4674 				 */
4675 				if (time_after_eq(jiffies, mtime)) {
4676 					ql_log(ql_log_info, vha, 0x8038,
4677 					    "Cable is unplugged...\n");
4678 
4679 					vha->device_flags |= DFLG_NO_CABLE;
4680 					break;
4681 				}
4682 			}
4683 		} else {
4684 			/* Mailbox cmd failed. Timeout on min_wait. */
4685 			if (time_after_eq(jiffies, mtime) ||
4686 				ha->flags.isp82xx_fw_hung)
4687 				break;
4688 		}
4689 
4690 		if (time_after_eq(jiffies, wtime))
4691 			break;
4692 
4693 		/* Delay for a while */
4694 		msleep(500);
4695 	} while (1);
4696 
4697 	ql_dbg(ql_dbg_taskm, vha, 0x803a,
4698 	    "fw_state=%x (%x, %x, %x, %x %x) curr time=%lx.\n", state[0],
4699 	    state[1], state[2], state[3], state[4], state[5], jiffies);
4700 
4701 	if (rval && !(vha->device_flags & DFLG_NO_CABLE)) {
4702 		ql_log(ql_log_warn, vha, 0x803b,
4703 		    "Firmware ready **** FAILED ****.\n");
4704 	}
4705 
4706 	return (rval);
4707 }
4708 
4709 /*
4710 *  qla2x00_configure_hba
4711 *      Setup adapter context.
4712 *
4713 * Input:
4714 *      ha = adapter state pointer.
4715 *
4716 * Returns:
4717 *      0 = success
4718 *
4719 * Context:
4720 *      Kernel context.
4721 */
4722 static int
4723 qla2x00_configure_hba(scsi_qla_host_t *vha)
4724 {
4725 	int       rval;
4726 	uint16_t      loop_id;
4727 	uint16_t      topo;
4728 	uint16_t      sw_cap;
4729 	uint8_t       al_pa;
4730 	uint8_t       area;
4731 	uint8_t       domain;
4732 	char		connect_type[22];
4733 	struct qla_hw_data *ha = vha->hw;
4734 	scsi_qla_host_t *base_vha = pci_get_drvdata(ha->pdev);
4735 	port_id_t id;
4736 	unsigned long flags;
4737 
4738 	/* Get host addresses. */
4739 	rval = qla2x00_get_adapter_id(vha,
4740 	    &loop_id, &al_pa, &area, &domain, &topo, &sw_cap);
4741 	if (rval != QLA_SUCCESS) {
4742 		if (LOOP_TRANSITION(vha) || atomic_read(&ha->loop_down_timer) ||
4743 		    IS_CNA_CAPABLE(ha) ||
4744 		    (rval == QLA_COMMAND_ERROR && loop_id == 0x7)) {
4745 			ql_dbg(ql_dbg_disc, vha, 0x2008,
4746 			    "Loop is in a transition state.\n");
4747 		} else {
4748 			ql_log(ql_log_warn, vha, 0x2009,
4749 			    "Unable to get host loop ID.\n");
4750 			if (IS_FWI2_CAPABLE(ha) && (vha == base_vha) &&
4751 			    (rval == QLA_COMMAND_ERROR && loop_id == 0x1b)) {
4752 				ql_log(ql_log_warn, vha, 0x1151,
4753 				    "Doing link init.\n");
4754 				if (qla24xx_link_initialize(vha) == QLA_SUCCESS)
4755 					return rval;
4756 			}
4757 			set_bit(ISP_ABORT_NEEDED, &vha->dpc_flags);
4758 		}
4759 		return (rval);
4760 	}
4761 
4762 	if (topo == 4) {
4763 		ql_log(ql_log_info, vha, 0x200a,
4764 		    "Cannot get topology - retrying.\n");
4765 		return (QLA_FUNCTION_FAILED);
4766 	}
4767 
4768 	vha->loop_id = loop_id;
4769 
4770 	/* initialize */
4771 	ha->min_external_loopid = SNS_FIRST_LOOP_ID;
4772 	ha->operating_mode = LOOP;
4773 
4774 	switch (topo) {
4775 	case 0:
4776 		ql_dbg(ql_dbg_disc, vha, 0x200b, "HBA in NL topology.\n");
4777 		ha->switch_cap = 0;
4778 		ha->current_topology = ISP_CFG_NL;
4779 		strcpy(connect_type, "(Loop)");
4780 		break;
4781 
4782 	case 1:
4783 		ql_dbg(ql_dbg_disc, vha, 0x200c, "HBA in FL topology.\n");
4784 		ha->switch_cap = sw_cap;
4785 		ha->current_topology = ISP_CFG_FL;
4786 		strcpy(connect_type, "(FL_Port)");
4787 		break;
4788 
4789 	case 2:
4790 		ql_dbg(ql_dbg_disc, vha, 0x200d, "HBA in N P2P topology.\n");
4791 		ha->switch_cap = 0;
4792 		ha->operating_mode = P2P;
4793 		ha->current_topology = ISP_CFG_N;
4794 		strcpy(connect_type, "(N_Port-to-N_Port)");
4795 		break;
4796 
4797 	case 3:
4798 		ql_dbg(ql_dbg_disc, vha, 0x200e, "HBA in F P2P topology.\n");
4799 		ha->switch_cap = sw_cap;
4800 		ha->operating_mode = P2P;
4801 		ha->current_topology = ISP_CFG_F;
4802 		strcpy(connect_type, "(F_Port)");
4803 		break;
4804 
4805 	default:
4806 		ql_dbg(ql_dbg_disc, vha, 0x200f,
4807 		    "HBA in unknown topology %x, using NL.\n", topo);
4808 		ha->switch_cap = 0;
4809 		ha->current_topology = ISP_CFG_NL;
4810 		strcpy(connect_type, "(Loop)");
4811 		break;
4812 	}
4813 
4814 	/* Save Host port and loop ID. */
4815 	/* byte order - Big Endian */
4816 	id.b.domain = domain;
4817 	id.b.area = area;
4818 	id.b.al_pa = al_pa;
4819 	id.b.rsvd_1 = 0;
4820 	spin_lock_irqsave(&ha->hardware_lock, flags);
4821 	if (vha->hw->flags.edif_enabled) {
4822 		if (topo != 2)
4823 			qla_update_host_map(vha, id);
4824 	} else if (!(topo == 2 && ha->flags.n2n_bigger))
4825 		qla_update_host_map(vha, id);
4826 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
4827 
4828 	if (!vha->flags.init_done)
4829 		ql_log(ql_log_info, vha, 0x2010,
4830 		    "Topology - %s, Host Loop address 0x%x.\n",
4831 		    connect_type, vha->loop_id);
4832 
4833 	return(rval);
4834 }
4835 
4836 inline void
4837 qla2x00_set_model_info(scsi_qla_host_t *vha, uint8_t *model, size_t len,
4838 		       const char *def)
4839 {
4840 	char *st, *en;
4841 	uint16_t index;
4842 	uint64_t zero[2] = { 0 };
4843 	struct qla_hw_data *ha = vha->hw;
4844 	int use_tbl = !IS_QLA24XX_TYPE(ha) && !IS_QLA25XX(ha) &&
4845 	    !IS_CNA_CAPABLE(ha) && !IS_QLA2031(ha);
4846 
4847 	if (len > sizeof(zero))
4848 		len = sizeof(zero);
4849 	if (memcmp(model, &zero, len) != 0) {
4850 		memcpy(ha->model_number, model, len);
4851 		st = en = ha->model_number;
4852 		en += len - 1;
4853 		while (en > st) {
4854 			if (*en != 0x20 && *en != 0x00)
4855 				break;
4856 			*en-- = '\0';
4857 		}
4858 
4859 		index = (ha->pdev->subsystem_device & 0xff);
4860 		if (use_tbl &&
4861 		    ha->pdev->subsystem_vendor == PCI_VENDOR_ID_QLOGIC &&
4862 		    index < QLA_MODEL_NAMES)
4863 			strlcpy(ha->model_desc,
4864 			    qla2x00_model_name[index * 2 + 1],
4865 			    sizeof(ha->model_desc));
4866 	} else {
4867 		index = (ha->pdev->subsystem_device & 0xff);
4868 		if (use_tbl &&
4869 		    ha->pdev->subsystem_vendor == PCI_VENDOR_ID_QLOGIC &&
4870 		    index < QLA_MODEL_NAMES) {
4871 			strlcpy(ha->model_number,
4872 				qla2x00_model_name[index * 2],
4873 				sizeof(ha->model_number));
4874 			strlcpy(ha->model_desc,
4875 			    qla2x00_model_name[index * 2 + 1],
4876 			    sizeof(ha->model_desc));
4877 		} else {
4878 			strlcpy(ha->model_number, def,
4879 				sizeof(ha->model_number));
4880 		}
4881 	}
4882 	if (IS_FWI2_CAPABLE(ha))
4883 		qla2xxx_get_vpd_field(vha, "\x82", ha->model_desc,
4884 		    sizeof(ha->model_desc));
4885 }
4886 
4887 /* On sparc systems, obtain port and node WWN from firmware
4888  * properties.
4889  */
4890 static void qla2xxx_nvram_wwn_from_ofw(scsi_qla_host_t *vha, nvram_t *nv)
4891 {
4892 #ifdef CONFIG_SPARC
4893 	struct qla_hw_data *ha = vha->hw;
4894 	struct pci_dev *pdev = ha->pdev;
4895 	struct device_node *dp = pci_device_to_OF_node(pdev);
4896 	const u8 *val;
4897 	int len;
4898 
4899 	val = of_get_property(dp, "port-wwn", &len);
4900 	if (val && len >= WWN_SIZE)
4901 		memcpy(nv->port_name, val, WWN_SIZE);
4902 
4903 	val = of_get_property(dp, "node-wwn", &len);
4904 	if (val && len >= WWN_SIZE)
4905 		memcpy(nv->node_name, val, WWN_SIZE);
4906 #endif
4907 }
4908 
4909 /*
4910 * NVRAM configuration for ISP 2xxx
4911 *
4912 * Input:
4913 *      ha                = adapter block pointer.
4914 *
4915 * Output:
4916 *      initialization control block in response_ring
4917 *      host adapters parameters in host adapter block
4918 *
4919 * Returns:
4920 *      0 = success.
4921 */
4922 int
4923 qla2x00_nvram_config(scsi_qla_host_t *vha)
4924 {
4925 	int             rval;
4926 	uint8_t         chksum = 0;
4927 	uint16_t        cnt;
4928 	uint8_t         *dptr1, *dptr2;
4929 	struct qla_hw_data *ha = vha->hw;
4930 	init_cb_t       *icb = ha->init_cb;
4931 	nvram_t         *nv = ha->nvram;
4932 	uint8_t         *ptr = ha->nvram;
4933 	struct device_reg_2xxx __iomem *reg = &ha->iobase->isp;
4934 
4935 	rval = QLA_SUCCESS;
4936 
4937 	/* Determine NVRAM starting address. */
4938 	ha->nvram_size = sizeof(*nv);
4939 	ha->nvram_base = 0;
4940 	if (!IS_QLA2100(ha) && !IS_QLA2200(ha) && !IS_QLA2300(ha))
4941 		if ((rd_reg_word(&reg->ctrl_status) >> 14) == 1)
4942 			ha->nvram_base = 0x80;
4943 
4944 	/* Get NVRAM data and calculate checksum. */
4945 	ha->isp_ops->read_nvram(vha, ptr, ha->nvram_base, ha->nvram_size);
4946 	for (cnt = 0, chksum = 0; cnt < ha->nvram_size; cnt++)
4947 		chksum += *ptr++;
4948 
4949 	ql_dbg(ql_dbg_init + ql_dbg_buffer, vha, 0x010f,
4950 	    "Contents of NVRAM.\n");
4951 	ql_dump_buffer(ql_dbg_init + ql_dbg_buffer, vha, 0x0110,
4952 	    nv, ha->nvram_size);
4953 
4954 	/* Bad NVRAM data, set defaults parameters. */
4955 	if (chksum || memcmp("ISP ", nv->id, sizeof(nv->id)) ||
4956 	    nv->nvram_version < 1) {
4957 		/* Reset NVRAM data. */
4958 		ql_log(ql_log_warn, vha, 0x0064,
4959 		    "Inconsistent NVRAM detected: checksum=%#x id=%.4s version=%#x.\n",
4960 		    chksum, nv->id, nv->nvram_version);
4961 		ql_log(ql_log_warn, vha, 0x0065,
4962 		    "Falling back to "
4963 		    "functioning (yet invalid -- WWPN) defaults.\n");
4964 
4965 		/*
4966 		 * Set default initialization control block.
4967 		 */
4968 		memset(nv, 0, ha->nvram_size);
4969 		nv->parameter_block_version = ICB_VERSION;
4970 
4971 		if (IS_QLA23XX(ha)) {
4972 			nv->firmware_options[0] = BIT_2 | BIT_1;
4973 			nv->firmware_options[1] = BIT_7 | BIT_5;
4974 			nv->add_firmware_options[0] = BIT_5;
4975 			nv->add_firmware_options[1] = BIT_5 | BIT_4;
4976 			nv->frame_payload_size = cpu_to_le16(2048);
4977 			nv->special_options[1] = BIT_7;
4978 		} else if (IS_QLA2200(ha)) {
4979 			nv->firmware_options[0] = BIT_2 | BIT_1;
4980 			nv->firmware_options[1] = BIT_7 | BIT_5;
4981 			nv->add_firmware_options[0] = BIT_5;
4982 			nv->add_firmware_options[1] = BIT_5 | BIT_4;
4983 			nv->frame_payload_size = cpu_to_le16(1024);
4984 		} else if (IS_QLA2100(ha)) {
4985 			nv->firmware_options[0] = BIT_3 | BIT_1;
4986 			nv->firmware_options[1] = BIT_5;
4987 			nv->frame_payload_size = cpu_to_le16(1024);
4988 		}
4989 
4990 		nv->max_iocb_allocation = cpu_to_le16(256);
4991 		nv->execution_throttle = cpu_to_le16(16);
4992 		nv->retry_count = 8;
4993 		nv->retry_delay = 1;
4994 
4995 		nv->port_name[0] = 33;
4996 		nv->port_name[3] = 224;
4997 		nv->port_name[4] = 139;
4998 
4999 		qla2xxx_nvram_wwn_from_ofw(vha, nv);
5000 
5001 		nv->login_timeout = 4;
5002 
5003 		/*
5004 		 * Set default host adapter parameters
5005 		 */
5006 		nv->host_p[1] = BIT_2;
5007 		nv->reset_delay = 5;
5008 		nv->port_down_retry_count = 8;
5009 		nv->max_luns_per_target = cpu_to_le16(8);
5010 		nv->link_down_timeout = 60;
5011 
5012 		rval = 1;
5013 	}
5014 
5015 	/* Reset Initialization control block */
5016 	memset(icb, 0, ha->init_cb_size);
5017 
5018 	/*
5019 	 * Setup driver NVRAM options.
5020 	 */
5021 	nv->firmware_options[0] |= (BIT_6 | BIT_1);
5022 	nv->firmware_options[0] &= ~(BIT_5 | BIT_4);
5023 	nv->firmware_options[1] |= (BIT_5 | BIT_0);
5024 	nv->firmware_options[1] &= ~BIT_4;
5025 
5026 	if (IS_QLA23XX(ha)) {
5027 		nv->firmware_options[0] |= BIT_2;
5028 		nv->firmware_options[0] &= ~BIT_3;
5029 		nv->special_options[0] &= ~BIT_6;
5030 		nv->add_firmware_options[1] |= BIT_5 | BIT_4;
5031 
5032 		if (IS_QLA2300(ha)) {
5033 			if (ha->fb_rev == FPM_2310) {
5034 				strcpy(ha->model_number, "QLA2310");
5035 			} else {
5036 				strcpy(ha->model_number, "QLA2300");
5037 			}
5038 		} else {
5039 			qla2x00_set_model_info(vha, nv->model_number,
5040 			    sizeof(nv->model_number), "QLA23xx");
5041 		}
5042 	} else if (IS_QLA2200(ha)) {
5043 		nv->firmware_options[0] |= BIT_2;
5044 		/*
5045 		 * 'Point-to-point preferred, else loop' is not a safe
5046 		 * connection mode setting.
5047 		 */
5048 		if ((nv->add_firmware_options[0] & (BIT_6 | BIT_5 | BIT_4)) ==
5049 		    (BIT_5 | BIT_4)) {
5050 			/* Force 'loop preferred, else point-to-point'. */
5051 			nv->add_firmware_options[0] &= ~(BIT_6 | BIT_5 | BIT_4);
5052 			nv->add_firmware_options[0] |= BIT_5;
5053 		}
5054 		strcpy(ha->model_number, "QLA22xx");
5055 	} else /*if (IS_QLA2100(ha))*/ {
5056 		strcpy(ha->model_number, "QLA2100");
5057 	}
5058 
5059 	/*
5060 	 * Copy over NVRAM RISC parameter block to initialization control block.
5061 	 */
5062 	dptr1 = (uint8_t *)icb;
5063 	dptr2 = (uint8_t *)&nv->parameter_block_version;
5064 	cnt = (uint8_t *)&icb->request_q_outpointer - (uint8_t *)&icb->version;
5065 	while (cnt--)
5066 		*dptr1++ = *dptr2++;
5067 
5068 	/* Copy 2nd half. */
5069 	dptr1 = (uint8_t *)icb->add_firmware_options;
5070 	cnt = (uint8_t *)icb->reserved_3 - (uint8_t *)icb->add_firmware_options;
5071 	while (cnt--)
5072 		*dptr1++ = *dptr2++;
5073 	ha->frame_payload_size = le16_to_cpu(icb->frame_payload_size);
5074 	/* Use alternate WWN? */
5075 	if (nv->host_p[1] & BIT_7) {
5076 		memcpy(icb->node_name, nv->alternate_node_name, WWN_SIZE);
5077 		memcpy(icb->port_name, nv->alternate_port_name, WWN_SIZE);
5078 	}
5079 
5080 	/* Prepare nodename */
5081 	if ((icb->firmware_options[1] & BIT_6) == 0) {
5082 		/*
5083 		 * Firmware will apply the following mask if the nodename was
5084 		 * not provided.
5085 		 */
5086 		memcpy(icb->node_name, icb->port_name, WWN_SIZE);
5087 		icb->node_name[0] &= 0xF0;
5088 	}
5089 
5090 	/*
5091 	 * Set host adapter parameters.
5092 	 */
5093 
5094 	/*
5095 	 * BIT_7 in the host-parameters section allows for modification to
5096 	 * internal driver logging.
5097 	 */
5098 	if (nv->host_p[0] & BIT_7)
5099 		ql2xextended_error_logging = QL_DBG_DEFAULT1_MASK;
5100 	ha->flags.disable_risc_code_load = ((nv->host_p[0] & BIT_4) ? 1 : 0);
5101 	/* Always load RISC code on non ISP2[12]00 chips. */
5102 	if (!IS_QLA2100(ha) && !IS_QLA2200(ha))
5103 		ha->flags.disable_risc_code_load = 0;
5104 	ha->flags.enable_lip_reset = ((nv->host_p[1] & BIT_1) ? 1 : 0);
5105 	ha->flags.enable_lip_full_login = ((nv->host_p[1] & BIT_2) ? 1 : 0);
5106 	ha->flags.enable_target_reset = ((nv->host_p[1] & BIT_3) ? 1 : 0);
5107 	ha->flags.enable_led_scheme = (nv->special_options[1] & BIT_4) ? 1 : 0;
5108 	ha->flags.disable_serdes = 0;
5109 
5110 	ha->operating_mode =
5111 	    (icb->add_firmware_options[0] & (BIT_6 | BIT_5 | BIT_4)) >> 4;
5112 
5113 	memcpy(ha->fw_seriallink_options, nv->seriallink_options,
5114 	    sizeof(ha->fw_seriallink_options));
5115 
5116 	/* save HBA serial number */
5117 	ha->serial0 = icb->port_name[5];
5118 	ha->serial1 = icb->port_name[6];
5119 	ha->serial2 = icb->port_name[7];
5120 	memcpy(vha->node_name, icb->node_name, WWN_SIZE);
5121 	memcpy(vha->port_name, icb->port_name, WWN_SIZE);
5122 
5123 	icb->execution_throttle = cpu_to_le16(0xFFFF);
5124 
5125 	ha->retry_count = nv->retry_count;
5126 
5127 	/* Set minimum login_timeout to 4 seconds. */
5128 	if (nv->login_timeout != ql2xlogintimeout)
5129 		nv->login_timeout = ql2xlogintimeout;
5130 	if (nv->login_timeout < 4)
5131 		nv->login_timeout = 4;
5132 	ha->login_timeout = nv->login_timeout;
5133 
5134 	/* Set minimum RATOV to 100 tenths of a second. */
5135 	ha->r_a_tov = 100;
5136 
5137 	ha->loop_reset_delay = nv->reset_delay;
5138 
5139 	/* Link Down Timeout = 0:
5140 	 *
5141 	 * 	When Port Down timer expires we will start returning
5142 	 *	I/O's to OS with "DID_NO_CONNECT".
5143 	 *
5144 	 * Link Down Timeout != 0:
5145 	 *
5146 	 *	 The driver waits for the link to come up after link down
5147 	 *	 before returning I/Os to OS with "DID_NO_CONNECT".
5148 	 */
5149 	if (nv->link_down_timeout == 0) {
5150 		ha->loop_down_abort_time =
5151 		    (LOOP_DOWN_TIME - LOOP_DOWN_TIMEOUT);
5152 	} else {
5153 		ha->link_down_timeout =	 nv->link_down_timeout;
5154 		ha->loop_down_abort_time =
5155 		    (LOOP_DOWN_TIME - ha->link_down_timeout);
5156 	}
5157 
5158 	/*
5159 	 * Need enough time to try and get the port back.
5160 	 */
5161 	ha->port_down_retry_count = nv->port_down_retry_count;
5162 	if (qlport_down_retry)
5163 		ha->port_down_retry_count = qlport_down_retry;
5164 	/* Set login_retry_count */
5165 	ha->login_retry_count  = nv->retry_count;
5166 	if (ha->port_down_retry_count == nv->port_down_retry_count &&
5167 	    ha->port_down_retry_count > 3)
5168 		ha->login_retry_count = ha->port_down_retry_count;
5169 	else if (ha->port_down_retry_count > (int)ha->login_retry_count)
5170 		ha->login_retry_count = ha->port_down_retry_count;
5171 	if (ql2xloginretrycount)
5172 		ha->login_retry_count = ql2xloginretrycount;
5173 
5174 	icb->lun_enables = cpu_to_le16(0);
5175 	icb->command_resource_count = 0;
5176 	icb->immediate_notify_resource_count = 0;
5177 	icb->timeout = cpu_to_le16(0);
5178 
5179 	if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
5180 		/* Enable RIO */
5181 		icb->firmware_options[0] &= ~BIT_3;
5182 		icb->add_firmware_options[0] &=
5183 		    ~(BIT_3 | BIT_2 | BIT_1 | BIT_0);
5184 		icb->add_firmware_options[0] |= BIT_2;
5185 		icb->response_accumulation_timer = 3;
5186 		icb->interrupt_delay_timer = 5;
5187 
5188 		vha->flags.process_response_queue = 1;
5189 	} else {
5190 		/* Enable ZIO. */
5191 		if (!vha->flags.init_done) {
5192 			ha->zio_mode = icb->add_firmware_options[0] &
5193 			    (BIT_3 | BIT_2 | BIT_1 | BIT_0);
5194 			ha->zio_timer = icb->interrupt_delay_timer ?
5195 			    icb->interrupt_delay_timer : 2;
5196 		}
5197 		icb->add_firmware_options[0] &=
5198 		    ~(BIT_3 | BIT_2 | BIT_1 | BIT_0);
5199 		vha->flags.process_response_queue = 0;
5200 		if (ha->zio_mode != QLA_ZIO_DISABLED) {
5201 			ha->zio_mode = QLA_ZIO_MODE_6;
5202 
5203 			ql_log(ql_log_info, vha, 0x0068,
5204 			    "ZIO mode %d enabled; timer delay (%d us).\n",
5205 			    ha->zio_mode, ha->zio_timer * 100);
5206 
5207 			icb->add_firmware_options[0] |= (uint8_t)ha->zio_mode;
5208 			icb->interrupt_delay_timer = (uint8_t)ha->zio_timer;
5209 			vha->flags.process_response_queue = 1;
5210 		}
5211 	}
5212 
5213 	if (rval) {
5214 		ql_log(ql_log_warn, vha, 0x0069,
5215 		    "NVRAM configuration failed.\n");
5216 	}
5217 	return (rval);
5218 }
5219 
5220 void qla2x00_set_fcport_state(fc_port_t *fcport, int state)
5221 {
5222 	int old_state;
5223 
5224 	old_state = atomic_read(&fcport->state);
5225 	atomic_set(&fcport->state, state);
5226 
5227 	/* Don't print state transitions during initial allocation of fcport */
5228 	if (old_state && old_state != state) {
5229 		ql_dbg(ql_dbg_disc, fcport->vha, 0x207d,
5230 		       "FCPort %8phC state transitioned from %s to %s - portid=%02x%02x%02x.\n",
5231 		       fcport->port_name, port_state_str[old_state],
5232 		       port_state_str[state], fcport->d_id.b.domain,
5233 		       fcport->d_id.b.area, fcport->d_id.b.al_pa);
5234 	}
5235 }
5236 
5237 /**
5238  * qla2x00_alloc_fcport() - Allocate a generic fcport.
5239  * @vha: HA context
5240  * @flags: allocation flags
5241  *
5242  * Returns a pointer to the allocated fcport, or NULL, if none available.
5243  */
5244 fc_port_t *
5245 qla2x00_alloc_fcport(scsi_qla_host_t *vha, gfp_t flags)
5246 {
5247 	fc_port_t *fcport;
5248 
5249 	fcport = kzalloc(sizeof(fc_port_t), flags);
5250 	if (!fcport)
5251 		return NULL;
5252 
5253 	fcport->ct_desc.ct_sns = dma_alloc_coherent(&vha->hw->pdev->dev,
5254 		sizeof(struct ct_sns_pkt), &fcport->ct_desc.ct_sns_dma,
5255 		flags);
5256 	if (!fcport->ct_desc.ct_sns) {
5257 		ql_log(ql_log_warn, vha, 0xd049,
5258 		    "Failed to allocate ct_sns request.\n");
5259 		kfree(fcport);
5260 		return NULL;
5261 	}
5262 
5263 	/* Setup fcport template structure. */
5264 	fcport->vha = vha;
5265 	fcport->port_type = FCT_UNKNOWN;
5266 	fcport->loop_id = FC_NO_LOOP_ID;
5267 	qla2x00_set_fcport_state(fcport, FCS_UNCONFIGURED);
5268 	fcport->supported_classes = FC_COS_UNSPECIFIED;
5269 	fcport->fp_speed = PORT_SPEED_UNKNOWN;
5270 
5271 	fcport->disc_state = DSC_DELETED;
5272 	fcport->fw_login_state = DSC_LS_PORT_UNAVAIL;
5273 	fcport->deleted = QLA_SESS_DELETED;
5274 	fcport->login_retry = vha->hw->login_retry_count;
5275 	fcport->chip_reset = vha->hw->base_qpair->chip_reset;
5276 	fcport->logout_on_delete = 1;
5277 	fcport->tgt_link_down_time = QLA2XX_MAX_LINK_DOWN_TIME;
5278 	fcport->tgt_short_link_down_cnt = 0;
5279 	fcport->dev_loss_tmo = 0;
5280 
5281 	if (!fcport->ct_desc.ct_sns) {
5282 		ql_log(ql_log_warn, vha, 0xd049,
5283 		    "Failed to allocate ct_sns request.\n");
5284 		kfree(fcport);
5285 		return NULL;
5286 	}
5287 
5288 	INIT_WORK(&fcport->del_work, qla24xx_delete_sess_fn);
5289 	INIT_WORK(&fcport->free_work, qlt_free_session_done);
5290 	INIT_WORK(&fcport->reg_work, qla_register_fcport_fn);
5291 	INIT_LIST_HEAD(&fcport->gnl_entry);
5292 	INIT_LIST_HEAD(&fcport->list);
5293 
5294 	INIT_LIST_HEAD(&fcport->sess_cmd_list);
5295 	spin_lock_init(&fcport->sess_cmd_lock);
5296 
5297 	spin_lock_init(&fcport->edif.sa_list_lock);
5298 	INIT_LIST_HEAD(&fcport->edif.tx_sa_list);
5299 	INIT_LIST_HEAD(&fcport->edif.rx_sa_list);
5300 
5301 	spin_lock_init(&fcport->edif.indx_list_lock);
5302 	INIT_LIST_HEAD(&fcport->edif.edif_indx_list);
5303 
5304 	return fcport;
5305 }
5306 
5307 void
5308 qla2x00_free_fcport(fc_port_t *fcport)
5309 {
5310 	if (fcport->ct_desc.ct_sns) {
5311 		dma_free_coherent(&fcport->vha->hw->pdev->dev,
5312 			sizeof(struct ct_sns_pkt), fcport->ct_desc.ct_sns,
5313 			fcport->ct_desc.ct_sns_dma);
5314 
5315 		fcport->ct_desc.ct_sns = NULL;
5316 	}
5317 
5318 	qla_edif_flush_sa_ctl_lists(fcport);
5319 	list_del(&fcport->list);
5320 	qla2x00_clear_loop_id(fcport);
5321 
5322 	qla_edif_list_del(fcport);
5323 
5324 	kfree(fcport);
5325 }
5326 
5327 static void qla_get_login_template(scsi_qla_host_t *vha)
5328 {
5329 	struct qla_hw_data *ha = vha->hw;
5330 	int rval;
5331 	u32 *bp, sz;
5332 	__be32 *q;
5333 
5334 	memset(ha->init_cb, 0, ha->init_cb_size);
5335 	sz = min_t(int, sizeof(struct fc_els_flogi), ha->init_cb_size);
5336 	rval = qla24xx_get_port_login_templ(vha, ha->init_cb_dma,
5337 					    ha->init_cb, sz);
5338 	if (rval != QLA_SUCCESS) {
5339 		ql_dbg(ql_dbg_init, vha, 0x00d1,
5340 		       "PLOGI ELS param read fail.\n");
5341 		return;
5342 	}
5343 	q = (__be32 *)&ha->plogi_els_payld.fl_csp;
5344 
5345 	bp = (uint32_t *)ha->init_cb;
5346 	cpu_to_be32_array(q, bp, sz / 4);
5347 	ha->flags.plogi_template_valid = 1;
5348 }
5349 
5350 /*
5351  * qla2x00_configure_loop
5352  *      Updates Fibre Channel Device Database with what is actually on loop.
5353  *
5354  * Input:
5355  *      ha                = adapter block pointer.
5356  *
5357  * Returns:
5358  *      0 = success.
5359  *      1 = error.
5360  *      2 = database was full and device was not configured.
5361  */
5362 static int
5363 qla2x00_configure_loop(scsi_qla_host_t *vha)
5364 {
5365 	int  rval;
5366 	unsigned long flags, save_flags;
5367 	struct qla_hw_data *ha = vha->hw;
5368 
5369 	rval = QLA_SUCCESS;
5370 
5371 	/* Get Initiator ID */
5372 	if (test_bit(LOCAL_LOOP_UPDATE, &vha->dpc_flags)) {
5373 		rval = qla2x00_configure_hba(vha);
5374 		if (rval != QLA_SUCCESS) {
5375 			ql_dbg(ql_dbg_disc, vha, 0x2013,
5376 			    "Unable to configure HBA.\n");
5377 			return (rval);
5378 		}
5379 	}
5380 
5381 	save_flags = flags = vha->dpc_flags;
5382 	ql_dbg(ql_dbg_disc, vha, 0x2014,
5383 	    "Configure loop -- dpc flags = 0x%lx.\n", flags);
5384 
5385 	/*
5386 	 * If we have both an RSCN and PORT UPDATE pending then handle them
5387 	 * both at the same time.
5388 	 */
5389 	clear_bit(LOCAL_LOOP_UPDATE, &vha->dpc_flags);
5390 	clear_bit(RSCN_UPDATE, &vha->dpc_flags);
5391 
5392 	qla2x00_get_data_rate(vha);
5393 	qla_get_login_template(vha);
5394 
5395 	/* Determine what we need to do */
5396 	if ((ha->current_topology == ISP_CFG_FL ||
5397 	    ha->current_topology == ISP_CFG_F) &&
5398 	    (test_bit(LOCAL_LOOP_UPDATE, &flags))) {
5399 
5400 		set_bit(RSCN_UPDATE, &flags);
5401 		clear_bit(LOCAL_LOOP_UPDATE, &flags);
5402 
5403 	} else if (ha->current_topology == ISP_CFG_NL ||
5404 		   ha->current_topology == ISP_CFG_N) {
5405 		clear_bit(RSCN_UPDATE, &flags);
5406 		set_bit(LOCAL_LOOP_UPDATE, &flags);
5407 	} else if (!vha->flags.online ||
5408 	    (test_bit(ABORT_ISP_ACTIVE, &flags))) {
5409 		set_bit(RSCN_UPDATE, &flags);
5410 		set_bit(LOCAL_LOOP_UPDATE, &flags);
5411 	}
5412 
5413 	if (test_bit(LOCAL_LOOP_UPDATE, &flags)) {
5414 		if (test_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags)) {
5415 			ql_dbg(ql_dbg_disc, vha, 0x2015,
5416 			    "Loop resync needed, failing.\n");
5417 			rval = QLA_FUNCTION_FAILED;
5418 		} else
5419 			rval = qla2x00_configure_local_loop(vha);
5420 	}
5421 
5422 	if (rval == QLA_SUCCESS && test_bit(RSCN_UPDATE, &flags)) {
5423 		if (LOOP_TRANSITION(vha)) {
5424 			ql_dbg(ql_dbg_disc, vha, 0x2099,
5425 			    "Needs RSCN update and loop transition.\n");
5426 			rval = QLA_FUNCTION_FAILED;
5427 		}
5428 		else
5429 			rval = qla2x00_configure_fabric(vha);
5430 	}
5431 
5432 	if (rval == QLA_SUCCESS) {
5433 		if (atomic_read(&vha->loop_down_timer) ||
5434 		    test_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags)) {
5435 			rval = QLA_FUNCTION_FAILED;
5436 		} else {
5437 			atomic_set(&vha->loop_state, LOOP_READY);
5438 			ql_dbg(ql_dbg_disc, vha, 0x2069,
5439 			    "LOOP READY.\n");
5440 			ha->flags.fw_init_done = 1;
5441 
5442 			/*
5443 			 * use link up to wake up app to get ready for
5444 			 * authentication.
5445 			 */
5446 			if (ha->flags.edif_enabled && DBELL_INACTIVE(vha))
5447 				qla2x00_post_aen_work(vha, FCH_EVT_LINKUP,
5448 						      ha->link_data_rate);
5449 
5450 			/*
5451 			 * Process any ATIO queue entries that came in
5452 			 * while we weren't online.
5453 			 */
5454 			if (qla_tgt_mode_enabled(vha) ||
5455 			    qla_dual_mode_enabled(vha)) {
5456 				spin_lock_irqsave(&ha->tgt.atio_lock, flags);
5457 				qlt_24xx_process_atio_queue(vha, 0);
5458 				spin_unlock_irqrestore(&ha->tgt.atio_lock,
5459 				    flags);
5460 			}
5461 		}
5462 	}
5463 
5464 	if (rval) {
5465 		ql_dbg(ql_dbg_disc, vha, 0x206a,
5466 		    "%s *** FAILED ***.\n", __func__);
5467 	} else {
5468 		ql_dbg(ql_dbg_disc, vha, 0x206b,
5469 		    "%s: exiting normally. local port wwpn %8phN id %06x)\n",
5470 		    __func__, vha->port_name, vha->d_id.b24);
5471 	}
5472 
5473 	/* Restore state if a resync event occurred during processing */
5474 	if (test_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags)) {
5475 		if (test_bit(LOCAL_LOOP_UPDATE, &save_flags))
5476 			set_bit(LOCAL_LOOP_UPDATE, &vha->dpc_flags);
5477 		if (test_bit(RSCN_UPDATE, &save_flags)) {
5478 			set_bit(RSCN_UPDATE, &vha->dpc_flags);
5479 		}
5480 	}
5481 
5482 	return (rval);
5483 }
5484 
5485 static int qla2x00_configure_n2n_loop(scsi_qla_host_t *vha)
5486 {
5487 	unsigned long flags;
5488 	fc_port_t *fcport;
5489 
5490 	ql_dbg(ql_dbg_disc, vha, 0x206a, "%s %d.\n", __func__, __LINE__);
5491 
5492 	if (test_and_clear_bit(N2N_LOGIN_NEEDED, &vha->dpc_flags))
5493 		set_bit(RELOGIN_NEEDED, &vha->dpc_flags);
5494 
5495 	list_for_each_entry(fcport, &vha->vp_fcports, list) {
5496 		if (fcport->n2n_flag) {
5497 			qla24xx_fcport_handle_login(vha, fcport);
5498 			return QLA_SUCCESS;
5499 		}
5500 	}
5501 
5502 	spin_lock_irqsave(&vha->work_lock, flags);
5503 	vha->scan.scan_retry++;
5504 	spin_unlock_irqrestore(&vha->work_lock, flags);
5505 
5506 	if (vha->scan.scan_retry < MAX_SCAN_RETRIES) {
5507 		set_bit(LOCAL_LOOP_UPDATE, &vha->dpc_flags);
5508 		set_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags);
5509 	}
5510 	return QLA_FUNCTION_FAILED;
5511 }
5512 
5513 static void
5514 qla_reinitialize_link(scsi_qla_host_t *vha)
5515 {
5516 	int rval;
5517 
5518 	atomic_set(&vha->loop_state, LOOP_DOWN);
5519 	atomic_set(&vha->loop_down_timer, LOOP_DOWN_TIME);
5520 	rval = qla2x00_full_login_lip(vha);
5521 	if (rval == QLA_SUCCESS) {
5522 		ql_dbg(ql_dbg_disc, vha, 0xd050, "Link reinitialized\n");
5523 	} else {
5524 		ql_dbg(ql_dbg_disc, vha, 0xd051,
5525 			"Link reinitialization failed (%d)\n", rval);
5526 	}
5527 }
5528 
5529 /*
5530  * qla2x00_configure_local_loop
5531  *	Updates Fibre Channel Device Database with local loop devices.
5532  *
5533  * Input:
5534  *	ha = adapter block pointer.
5535  *
5536  * Returns:
5537  *	0 = success.
5538  */
5539 static int
5540 qla2x00_configure_local_loop(scsi_qla_host_t *vha)
5541 {
5542 	int		rval, rval2;
5543 	int		found;
5544 	fc_port_t	*fcport, *new_fcport;
5545 	uint16_t	index;
5546 	uint16_t	entries;
5547 	struct gid_list_info *gid;
5548 	uint16_t	loop_id;
5549 	uint8_t		domain, area, al_pa;
5550 	struct qla_hw_data *ha = vha->hw;
5551 	unsigned long flags;
5552 
5553 	/* Inititae N2N login. */
5554 	if (N2N_TOPO(ha))
5555 		return qla2x00_configure_n2n_loop(vha);
5556 
5557 	new_fcport = NULL;
5558 	entries = MAX_FIBRE_DEVICES_LOOP;
5559 
5560 	/* Get list of logged in devices. */
5561 	memset(ha->gid_list, 0, qla2x00_gid_list_size(ha));
5562 	rval = qla2x00_get_id_list(vha, ha->gid_list, ha->gid_list_dma,
5563 	    &entries);
5564 	if (rval != QLA_SUCCESS)
5565 		goto err;
5566 
5567 	ql_dbg(ql_dbg_disc, vha, 0x2011,
5568 	    "Entries in ID list (%d).\n", entries);
5569 	ql_dump_buffer(ql_dbg_disc + ql_dbg_buffer, vha, 0x2075,
5570 	    ha->gid_list, entries * sizeof(*ha->gid_list));
5571 
5572 	if (entries == 0) {
5573 		spin_lock_irqsave(&vha->work_lock, flags);
5574 		vha->scan.scan_retry++;
5575 		spin_unlock_irqrestore(&vha->work_lock, flags);
5576 
5577 		if (vha->scan.scan_retry < MAX_SCAN_RETRIES) {
5578 			u8 loop_map_entries = 0;
5579 			int rc;
5580 
5581 			rc = qla2x00_get_fcal_position_map(vha, NULL,
5582 						&loop_map_entries);
5583 			if (rc == QLA_SUCCESS && loop_map_entries > 1) {
5584 				/*
5585 				 * There are devices that are still not logged
5586 				 * in. Reinitialize to give them a chance.
5587 				 */
5588 				qla_reinitialize_link(vha);
5589 				return QLA_FUNCTION_FAILED;
5590 			}
5591 			set_bit(LOCAL_LOOP_UPDATE, &vha->dpc_flags);
5592 			set_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags);
5593 		}
5594 	} else {
5595 		vha->scan.scan_retry = 0;
5596 	}
5597 
5598 	list_for_each_entry(fcport, &vha->vp_fcports, list) {
5599 		fcport->scan_state = QLA_FCPORT_SCAN;
5600 	}
5601 
5602 	/* Allocate temporary fcport for any new fcports discovered. */
5603 	new_fcport = qla2x00_alloc_fcport(vha, GFP_KERNEL);
5604 	if (new_fcport == NULL) {
5605 		ql_log(ql_log_warn, vha, 0x2012,
5606 		    "Memory allocation failed for fcport.\n");
5607 		rval = QLA_MEMORY_ALLOC_FAILED;
5608 		goto err;
5609 	}
5610 	new_fcport->flags &= ~FCF_FABRIC_DEVICE;
5611 
5612 	/* Add devices to port list. */
5613 	gid = ha->gid_list;
5614 	for (index = 0; index < entries; index++) {
5615 		domain = gid->domain;
5616 		area = gid->area;
5617 		al_pa = gid->al_pa;
5618 		if (IS_QLA2100(ha) || IS_QLA2200(ha))
5619 			loop_id = gid->loop_id_2100;
5620 		else
5621 			loop_id = le16_to_cpu(gid->loop_id);
5622 		gid = (void *)gid + ha->gid_list_info_size;
5623 
5624 		/* Bypass reserved domain fields. */
5625 		if ((domain & 0xf0) == 0xf0)
5626 			continue;
5627 
5628 		/* Bypass if not same domain and area of adapter. */
5629 		if (area && domain && ((area != vha->d_id.b.area) ||
5630 		    (domain != vha->d_id.b.domain)) &&
5631 		    (ha->current_topology == ISP_CFG_NL))
5632 			continue;
5633 
5634 
5635 		/* Bypass invalid local loop ID. */
5636 		if (loop_id > LAST_LOCAL_LOOP_ID)
5637 			continue;
5638 
5639 		memset(new_fcport->port_name, 0, WWN_SIZE);
5640 
5641 		/* Fill in member data. */
5642 		new_fcport->d_id.b.domain = domain;
5643 		new_fcport->d_id.b.area = area;
5644 		new_fcport->d_id.b.al_pa = al_pa;
5645 		new_fcport->loop_id = loop_id;
5646 		new_fcport->scan_state = QLA_FCPORT_FOUND;
5647 
5648 		rval2 = qla2x00_get_port_database(vha, new_fcport, 0);
5649 		if (rval2 != QLA_SUCCESS) {
5650 			ql_dbg(ql_dbg_disc, vha, 0x2097,
5651 			    "Failed to retrieve fcport information "
5652 			    "-- get_port_database=%x, loop_id=0x%04x.\n",
5653 			    rval2, new_fcport->loop_id);
5654 			/* Skip retry if N2N */
5655 			if (ha->current_topology != ISP_CFG_N) {
5656 				ql_dbg(ql_dbg_disc, vha, 0x2105,
5657 				    "Scheduling resync.\n");
5658 				set_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags);
5659 				continue;
5660 			}
5661 		}
5662 
5663 		spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
5664 		/* Check for matching device in port list. */
5665 		found = 0;
5666 		fcport = NULL;
5667 		list_for_each_entry(fcport, &vha->vp_fcports, list) {
5668 			if (memcmp(new_fcport->port_name, fcport->port_name,
5669 			    WWN_SIZE))
5670 				continue;
5671 
5672 			fcport->flags &= ~FCF_FABRIC_DEVICE;
5673 			fcport->loop_id = new_fcport->loop_id;
5674 			fcport->port_type = new_fcport->port_type;
5675 			fcport->d_id.b24 = new_fcport->d_id.b24;
5676 			memcpy(fcport->node_name, new_fcport->node_name,
5677 			    WWN_SIZE);
5678 			fcport->scan_state = QLA_FCPORT_FOUND;
5679 			if (fcport->login_retry == 0) {
5680 				fcport->login_retry = vha->hw->login_retry_count;
5681 				ql_dbg(ql_dbg_disc, vha, 0x2135,
5682 				    "Port login retry %8phN, lid 0x%04x retry cnt=%d.\n",
5683 				    fcport->port_name, fcport->loop_id,
5684 				    fcport->login_retry);
5685 			}
5686 			found++;
5687 			break;
5688 		}
5689 
5690 		if (!found) {
5691 			/* New device, add to fcports list. */
5692 			list_add_tail(&new_fcport->list, &vha->vp_fcports);
5693 
5694 			/* Allocate a new replacement fcport. */
5695 			fcport = new_fcport;
5696 
5697 			spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
5698 
5699 			new_fcport = qla2x00_alloc_fcport(vha, GFP_KERNEL);
5700 
5701 			if (new_fcport == NULL) {
5702 				ql_log(ql_log_warn, vha, 0xd031,
5703 				    "Failed to allocate memory for fcport.\n");
5704 				rval = QLA_MEMORY_ALLOC_FAILED;
5705 				goto err;
5706 			}
5707 			spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
5708 			new_fcport->flags &= ~FCF_FABRIC_DEVICE;
5709 		}
5710 
5711 		spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
5712 
5713 		/* Base iIDMA settings on HBA port speed. */
5714 		fcport->fp_speed = ha->link_data_rate;
5715 	}
5716 
5717 	list_for_each_entry(fcport, &vha->vp_fcports, list) {
5718 		if (test_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags))
5719 			break;
5720 
5721 		if (fcport->scan_state == QLA_FCPORT_SCAN) {
5722 			if ((qla_dual_mode_enabled(vha) ||
5723 			    qla_ini_mode_enabled(vha)) &&
5724 			    atomic_read(&fcport->state) == FCS_ONLINE) {
5725 				qla2x00_mark_device_lost(vha, fcport,
5726 					ql2xplogiabsentdevice);
5727 				if (fcport->loop_id != FC_NO_LOOP_ID &&
5728 				    (fcport->flags & FCF_FCP2_DEVICE) == 0 &&
5729 				    fcport->port_type != FCT_INITIATOR &&
5730 				    fcport->port_type != FCT_BROADCAST) {
5731 					ql_dbg(ql_dbg_disc, vha, 0x20f0,
5732 					    "%s %d %8phC post del sess\n",
5733 					    __func__, __LINE__,
5734 					    fcport->port_name);
5735 
5736 					qlt_schedule_sess_for_deletion(fcport);
5737 					continue;
5738 				}
5739 			}
5740 		}
5741 
5742 		if (fcport->scan_state == QLA_FCPORT_FOUND)
5743 			qla24xx_fcport_handle_login(vha, fcport);
5744 	}
5745 
5746 	qla2x00_free_fcport(new_fcport);
5747 
5748 	return rval;
5749 
5750 err:
5751 	ql_dbg(ql_dbg_disc, vha, 0x2098,
5752 	       "Configure local loop error exit: rval=%x.\n", rval);
5753 	return rval;
5754 }
5755 
5756 static void
5757 qla2x00_iidma_fcport(scsi_qla_host_t *vha, fc_port_t *fcport)
5758 {
5759 	int rval;
5760 	uint16_t mb[MAILBOX_REGISTER_COUNT];
5761 	struct qla_hw_data *ha = vha->hw;
5762 
5763 	if (!IS_IIDMA_CAPABLE(ha))
5764 		return;
5765 
5766 	if (atomic_read(&fcport->state) != FCS_ONLINE)
5767 		return;
5768 
5769 	if (fcport->fp_speed == PORT_SPEED_UNKNOWN ||
5770 	    fcport->fp_speed > ha->link_data_rate ||
5771 	    !ha->flags.gpsc_supported)
5772 		return;
5773 
5774 	rval = qla2x00_set_idma_speed(vha, fcport->loop_id, fcport->fp_speed,
5775 	    mb);
5776 	if (rval != QLA_SUCCESS) {
5777 		ql_dbg(ql_dbg_disc, vha, 0x2004,
5778 		    "Unable to adjust iIDMA %8phN -- %04x %x %04x %04x.\n",
5779 		    fcport->port_name, rval, fcport->fp_speed, mb[0], mb[1]);
5780 	} else {
5781 		ql_dbg(ql_dbg_disc, vha, 0x2005,
5782 		    "iIDMA adjusted to %s GB/s (%X) on %8phN.\n",
5783 		    qla2x00_get_link_speed_str(ha, fcport->fp_speed),
5784 		    fcport->fp_speed, fcport->port_name);
5785 	}
5786 }
5787 
5788 void qla_do_iidma_work(struct scsi_qla_host *vha, fc_port_t *fcport)
5789 {
5790 	qla2x00_iidma_fcport(vha, fcport);
5791 	qla24xx_update_fcport_fcp_prio(vha, fcport);
5792 }
5793 
5794 int qla_post_iidma_work(struct scsi_qla_host *vha, fc_port_t *fcport)
5795 {
5796 	struct qla_work_evt *e;
5797 
5798 	e = qla2x00_alloc_work(vha, QLA_EVT_IIDMA);
5799 	if (!e)
5800 		return QLA_FUNCTION_FAILED;
5801 
5802 	e->u.fcport.fcport = fcport;
5803 	return qla2x00_post_work(vha, e);
5804 }
5805 
5806 /* qla2x00_reg_remote_port is reserved for Initiator Mode only.*/
5807 static void
5808 qla2x00_reg_remote_port(scsi_qla_host_t *vha, fc_port_t *fcport)
5809 {
5810 	struct fc_rport_identifiers rport_ids;
5811 	struct fc_rport *rport;
5812 	unsigned long flags;
5813 
5814 	if (atomic_read(&fcport->state) == FCS_ONLINE)
5815 		return;
5816 
5817 	rport_ids.node_name = wwn_to_u64(fcport->node_name);
5818 	rport_ids.port_name = wwn_to_u64(fcport->port_name);
5819 	rport_ids.port_id = fcport->d_id.b.domain << 16 |
5820 	    fcport->d_id.b.area << 8 | fcport->d_id.b.al_pa;
5821 	rport_ids.roles = FC_RPORT_ROLE_UNKNOWN;
5822 	fcport->rport = rport = fc_remote_port_add(vha->host, 0, &rport_ids);
5823 	if (!rport) {
5824 		ql_log(ql_log_warn, vha, 0x2006,
5825 		    "Unable to allocate fc remote port.\n");
5826 		return;
5827 	}
5828 
5829 	spin_lock_irqsave(fcport->vha->host->host_lock, flags);
5830 	*((fc_port_t **)rport->dd_data) = fcport;
5831 	spin_unlock_irqrestore(fcport->vha->host->host_lock, flags);
5832 	fcport->dev_loss_tmo = rport->dev_loss_tmo;
5833 
5834 	rport->supported_classes = fcport->supported_classes;
5835 
5836 	rport_ids.roles = FC_PORT_ROLE_UNKNOWN;
5837 	if (fcport->port_type == FCT_INITIATOR)
5838 		rport_ids.roles |= FC_PORT_ROLE_FCP_INITIATOR;
5839 	if (fcport->port_type == FCT_TARGET)
5840 		rport_ids.roles |= FC_PORT_ROLE_FCP_TARGET;
5841 	if (fcport->port_type & FCT_NVME_INITIATOR)
5842 		rport_ids.roles |= FC_PORT_ROLE_NVME_INITIATOR;
5843 	if (fcport->port_type & FCT_NVME_TARGET)
5844 		rport_ids.roles |= FC_PORT_ROLE_NVME_TARGET;
5845 	if (fcport->port_type & FCT_NVME_DISCOVERY)
5846 		rport_ids.roles |= FC_PORT_ROLE_NVME_DISCOVERY;
5847 
5848 	fc_remote_port_rolechg(rport, rport_ids.roles);
5849 
5850 	ql_dbg(ql_dbg_disc, vha, 0x20ee,
5851 	    "%s: %8phN. rport %ld:0:%d (%p) is %s mode\n",
5852 	    __func__, fcport->port_name, vha->host_no,
5853 	    rport->scsi_target_id, rport,
5854 	    (fcport->port_type == FCT_TARGET) ? "tgt" :
5855 	    ((fcport->port_type & FCT_NVME) ? "nvme" : "ini"));
5856 }
5857 
5858 /*
5859  * qla2x00_update_fcport
5860  *	Updates device on list.
5861  *
5862  * Input:
5863  *	ha = adapter block pointer.
5864  *	fcport = port structure pointer.
5865  *
5866  * Return:
5867  *	0  - Success
5868  *  BIT_0 - error
5869  *
5870  * Context:
5871  *	Kernel context.
5872  */
5873 void
5874 qla2x00_update_fcport(scsi_qla_host_t *vha, fc_port_t *fcport)
5875 {
5876 	if (IS_SW_RESV_ADDR(fcport->d_id))
5877 		return;
5878 
5879 	ql_dbg(ql_dbg_disc, vha, 0x20ef, "%s %8phC\n",
5880 	    __func__, fcport->port_name);
5881 
5882 	qla2x00_set_fcport_disc_state(fcport, DSC_UPD_FCPORT);
5883 	fcport->login_retry = vha->hw->login_retry_count;
5884 	fcport->flags &= ~(FCF_LOGIN_NEEDED | FCF_ASYNC_SENT);
5885 	fcport->deleted = 0;
5886 	if (vha->hw->current_topology == ISP_CFG_NL)
5887 		fcport->logout_on_delete = 0;
5888 	else
5889 		fcport->logout_on_delete = 1;
5890 	fcport->n2n_chip_reset = fcport->n2n_link_reset_cnt = 0;
5891 
5892 	if (fcport->tgt_link_down_time < fcport->dev_loss_tmo) {
5893 		fcport->tgt_short_link_down_cnt++;
5894 		fcport->tgt_link_down_time = QLA2XX_MAX_LINK_DOWN_TIME;
5895 	}
5896 
5897 	switch (vha->hw->current_topology) {
5898 	case ISP_CFG_N:
5899 	case ISP_CFG_NL:
5900 		fcport->keep_nport_handle = 1;
5901 		break;
5902 	default:
5903 		break;
5904 	}
5905 
5906 	qla2x00_iidma_fcport(vha, fcport);
5907 
5908 	qla2x00_dfs_create_rport(vha, fcport);
5909 
5910 	qla24xx_update_fcport_fcp_prio(vha, fcport);
5911 
5912 	switch (vha->host->active_mode) {
5913 	case MODE_INITIATOR:
5914 		qla2x00_reg_remote_port(vha, fcport);
5915 		break;
5916 	case MODE_TARGET:
5917 		if (!vha->vha_tgt.qla_tgt->tgt_stop &&
5918 			!vha->vha_tgt.qla_tgt->tgt_stopped)
5919 			qlt_fc_port_added(vha, fcport);
5920 		break;
5921 	case MODE_DUAL:
5922 		qla2x00_reg_remote_port(vha, fcport);
5923 		if (!vha->vha_tgt.qla_tgt->tgt_stop &&
5924 			!vha->vha_tgt.qla_tgt->tgt_stopped)
5925 			qlt_fc_port_added(vha, fcport);
5926 		break;
5927 	default:
5928 		break;
5929 	}
5930 
5931 	if (NVME_TARGET(vha->hw, fcport))
5932 		qla_nvme_register_remote(vha, fcport);
5933 
5934 	qla2x00_set_fcport_state(fcport, FCS_ONLINE);
5935 
5936 	if (IS_IIDMA_CAPABLE(vha->hw) && vha->hw->flags.gpsc_supported) {
5937 		if (fcport->id_changed) {
5938 			fcport->id_changed = 0;
5939 			ql_dbg(ql_dbg_disc, vha, 0x20d7,
5940 			    "%s %d %8phC post gfpnid fcp_cnt %d\n",
5941 			    __func__, __LINE__, fcport->port_name,
5942 			    vha->fcport_count);
5943 			qla24xx_post_gfpnid_work(vha, fcport);
5944 		} else {
5945 			ql_dbg(ql_dbg_disc, vha, 0x20d7,
5946 			    "%s %d %8phC post gpsc fcp_cnt %d\n",
5947 			    __func__, __LINE__, fcport->port_name,
5948 			    vha->fcport_count);
5949 			qla24xx_post_gpsc_work(vha, fcport);
5950 		}
5951 	}
5952 
5953 	qla2x00_set_fcport_disc_state(fcport, DSC_LOGIN_COMPLETE);
5954 }
5955 
5956 void qla_register_fcport_fn(struct work_struct *work)
5957 {
5958 	fc_port_t *fcport = container_of(work, struct fc_port, reg_work);
5959 	u32 rscn_gen = fcport->rscn_gen;
5960 	u16 data[2];
5961 
5962 	if (IS_SW_RESV_ADDR(fcport->d_id))
5963 		return;
5964 
5965 	qla2x00_update_fcport(fcport->vha, fcport);
5966 
5967 	ql_dbg(ql_dbg_disc, fcport->vha, 0x911e,
5968 	       "%s rscn gen %d/%d next DS %d\n", __func__,
5969 	       rscn_gen, fcport->rscn_gen, fcport->next_disc_state);
5970 
5971 	if (rscn_gen != fcport->rscn_gen) {
5972 		/* RSCN(s) came in while registration */
5973 		switch (fcport->next_disc_state) {
5974 		case DSC_DELETE_PEND:
5975 			qlt_schedule_sess_for_deletion(fcport);
5976 			break;
5977 		case DSC_ADISC:
5978 			data[0] = data[1] = 0;
5979 			qla2x00_post_async_adisc_work(fcport->vha, fcport,
5980 			    data);
5981 			break;
5982 		default:
5983 			break;
5984 		}
5985 	}
5986 }
5987 
5988 /*
5989  * qla2x00_configure_fabric
5990  *      Setup SNS devices with loop ID's.
5991  *
5992  * Input:
5993  *      ha = adapter block pointer.
5994  *
5995  * Returns:
5996  *      0 = success.
5997  *      BIT_0 = error
5998  */
5999 static int
6000 qla2x00_configure_fabric(scsi_qla_host_t *vha)
6001 {
6002 	int	rval;
6003 	fc_port_t	*fcport;
6004 	uint16_t	mb[MAILBOX_REGISTER_COUNT];
6005 	uint16_t	loop_id;
6006 	LIST_HEAD(new_fcports);
6007 	struct qla_hw_data *ha = vha->hw;
6008 	int		discovery_gen;
6009 
6010 	/* If FL port exists, then SNS is present */
6011 	if (IS_FWI2_CAPABLE(ha))
6012 		loop_id = NPH_F_PORT;
6013 	else
6014 		loop_id = SNS_FL_PORT;
6015 	rval = qla2x00_get_port_name(vha, loop_id, vha->fabric_node_name, 1);
6016 	if (rval != QLA_SUCCESS) {
6017 		ql_dbg(ql_dbg_disc, vha, 0x20a0,
6018 		    "MBX_GET_PORT_NAME failed, No FL Port.\n");
6019 
6020 		vha->device_flags &= ~SWITCH_FOUND;
6021 		return (QLA_SUCCESS);
6022 	}
6023 	vha->device_flags |= SWITCH_FOUND;
6024 
6025 	rval = qla2x00_get_port_name(vha, loop_id, vha->fabric_port_name, 0);
6026 	if (rval != QLA_SUCCESS)
6027 		ql_dbg(ql_dbg_disc, vha, 0x20ff,
6028 		    "Failed to get Fabric Port Name\n");
6029 
6030 	if (qla_tgt_mode_enabled(vha) || qla_dual_mode_enabled(vha)) {
6031 		rval = qla2x00_send_change_request(vha, 0x3, 0);
6032 		if (rval != QLA_SUCCESS)
6033 			ql_log(ql_log_warn, vha, 0x121,
6034 			    "Failed to enable receiving of RSCN requests: 0x%x.\n",
6035 			    rval);
6036 	}
6037 
6038 	do {
6039 		qla2x00_mgmt_svr_login(vha);
6040 
6041 		/* Ensure we are logged into the SNS. */
6042 		loop_id = NPH_SNS_LID(ha);
6043 		rval = ha->isp_ops->fabric_login(vha, loop_id, 0xff, 0xff,
6044 		    0xfc, mb, BIT_1|BIT_0);
6045 		if (rval != QLA_SUCCESS || mb[0] != MBS_COMMAND_COMPLETE) {
6046 			ql_dbg(ql_dbg_disc, vha, 0x20a1,
6047 			    "Failed SNS login: loop_id=%x mb[0]=%x mb[1]=%x mb[2]=%x mb[6]=%x mb[7]=%x (%x).\n",
6048 			    loop_id, mb[0], mb[1], mb[2], mb[6], mb[7], rval);
6049 			set_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags);
6050 			return rval;
6051 		}
6052 
6053 		/* FDMI support. */
6054 		if (ql2xfdmienable &&
6055 		    test_and_clear_bit(REGISTER_FDMI_NEEDED, &vha->dpc_flags))
6056 			qla2x00_fdmi_register(vha);
6057 
6058 		if (test_and_clear_bit(REGISTER_FC4_NEEDED, &vha->dpc_flags)) {
6059 			if (qla2x00_rft_id(vha)) {
6060 				/* EMPTY */
6061 				ql_dbg(ql_dbg_disc, vha, 0x20a2,
6062 				    "Register FC-4 TYPE failed.\n");
6063 				if (test_bit(LOOP_RESYNC_NEEDED,
6064 				    &vha->dpc_flags))
6065 					break;
6066 			}
6067 			if (qla2x00_rff_id(vha, FC4_TYPE_FCP_SCSI)) {
6068 				/* EMPTY */
6069 				ql_dbg(ql_dbg_disc, vha, 0x209a,
6070 				    "Register FC-4 Features failed.\n");
6071 				if (test_bit(LOOP_RESYNC_NEEDED,
6072 				    &vha->dpc_flags))
6073 					break;
6074 			}
6075 			if (vha->flags.nvme_enabled) {
6076 				if (qla2x00_rff_id(vha, FC_TYPE_NVME)) {
6077 					ql_dbg(ql_dbg_disc, vha, 0x2049,
6078 					    "Register NVME FC Type Features failed.\n");
6079 				}
6080 			}
6081 			if (qla2x00_rnn_id(vha)) {
6082 				/* EMPTY */
6083 				ql_dbg(ql_dbg_disc, vha, 0x2104,
6084 				    "Register Node Name failed.\n");
6085 				if (test_bit(LOOP_RESYNC_NEEDED,
6086 				    &vha->dpc_flags))
6087 					break;
6088 			} else if (qla2x00_rsnn_nn(vha)) {
6089 				/* EMPTY */
6090 				ql_dbg(ql_dbg_disc, vha, 0x209b,
6091 				    "Register Symbolic Node Name failed.\n");
6092 				if (test_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags))
6093 					break;
6094 			}
6095 		}
6096 
6097 
6098 		/* Mark the time right before querying FW for connected ports.
6099 		 * This process is long, asynchronous and by the time it's done,
6100 		 * collected information might not be accurate anymore. E.g.
6101 		 * disconnected port might have re-connected and a brand new
6102 		 * session has been created. In this case session's generation
6103 		 * will be newer than discovery_gen. */
6104 		qlt_do_generation_tick(vha, &discovery_gen);
6105 
6106 		if (USE_ASYNC_SCAN(ha)) {
6107 			rval = qla24xx_async_gpnft(vha, FC4_TYPE_FCP_SCSI,
6108 			    NULL);
6109 			if (rval)
6110 				set_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags);
6111 		} else  {
6112 			list_for_each_entry(fcport, &vha->vp_fcports, list)
6113 				fcport->scan_state = QLA_FCPORT_SCAN;
6114 
6115 			rval = qla2x00_find_all_fabric_devs(vha);
6116 		}
6117 		if (rval != QLA_SUCCESS)
6118 			break;
6119 	} while (0);
6120 
6121 	if (!vha->nvme_local_port && vha->flags.nvme_enabled)
6122 		qla_nvme_register_hba(vha);
6123 
6124 	if (rval)
6125 		ql_dbg(ql_dbg_disc, vha, 0x2068,
6126 		    "Configure fabric error exit rval=%d.\n", rval);
6127 
6128 	return (rval);
6129 }
6130 
6131 /*
6132  * qla2x00_find_all_fabric_devs
6133  *
6134  * Input:
6135  *	ha = adapter block pointer.
6136  *	dev = database device entry pointer.
6137  *
6138  * Returns:
6139  *	0 = success.
6140  *
6141  * Context:
6142  *	Kernel context.
6143  */
6144 static int
6145 qla2x00_find_all_fabric_devs(scsi_qla_host_t *vha)
6146 {
6147 	int		rval;
6148 	uint16_t	loop_id;
6149 	fc_port_t	*fcport, *new_fcport;
6150 	int		found;
6151 
6152 	sw_info_t	*swl;
6153 	int		swl_idx;
6154 	int		first_dev, last_dev;
6155 	port_id_t	wrap = {}, nxt_d_id;
6156 	struct qla_hw_data *ha = vha->hw;
6157 	struct scsi_qla_host *base_vha = pci_get_drvdata(ha->pdev);
6158 	unsigned long flags;
6159 
6160 	rval = QLA_SUCCESS;
6161 
6162 	/* Try GID_PT to get device list, else GAN. */
6163 	if (!ha->swl)
6164 		ha->swl = kcalloc(ha->max_fibre_devices, sizeof(sw_info_t),
6165 		    GFP_KERNEL);
6166 	swl = ha->swl;
6167 	if (!swl) {
6168 		/*EMPTY*/
6169 		ql_dbg(ql_dbg_disc, vha, 0x209c,
6170 		    "GID_PT allocations failed, fallback on GA_NXT.\n");
6171 	} else {
6172 		memset(swl, 0, ha->max_fibre_devices * sizeof(sw_info_t));
6173 		if (qla2x00_gid_pt(vha, swl) != QLA_SUCCESS) {
6174 			swl = NULL;
6175 			if (test_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags))
6176 				return rval;
6177 		} else if (qla2x00_gpn_id(vha, swl) != QLA_SUCCESS) {
6178 			swl = NULL;
6179 			if (test_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags))
6180 				return rval;
6181 		} else if (qla2x00_gnn_id(vha, swl) != QLA_SUCCESS) {
6182 			swl = NULL;
6183 			if (test_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags))
6184 				return rval;
6185 		} else if (qla2x00_gfpn_id(vha, swl) != QLA_SUCCESS) {
6186 			swl = NULL;
6187 			if (test_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags))
6188 				return rval;
6189 		}
6190 
6191 		/* If other queries succeeded probe for FC-4 type */
6192 		if (swl) {
6193 			qla2x00_gff_id(vha, swl);
6194 			if (test_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags))
6195 				return rval;
6196 		}
6197 	}
6198 	swl_idx = 0;
6199 
6200 	/* Allocate temporary fcport for any new fcports discovered. */
6201 	new_fcport = qla2x00_alloc_fcport(vha, GFP_KERNEL);
6202 	if (new_fcport == NULL) {
6203 		ql_log(ql_log_warn, vha, 0x209d,
6204 		    "Failed to allocate memory for fcport.\n");
6205 		return (QLA_MEMORY_ALLOC_FAILED);
6206 	}
6207 	new_fcport->flags |= (FCF_FABRIC_DEVICE | FCF_LOGIN_NEEDED);
6208 	/* Set start port ID scan at adapter ID. */
6209 	first_dev = 1;
6210 	last_dev = 0;
6211 
6212 	/* Starting free loop ID. */
6213 	loop_id = ha->min_external_loopid;
6214 	for (; loop_id <= ha->max_loop_id; loop_id++) {
6215 		if (qla2x00_is_reserved_id(vha, loop_id))
6216 			continue;
6217 
6218 		if (ha->current_topology == ISP_CFG_FL &&
6219 		    (atomic_read(&vha->loop_down_timer) ||
6220 		     LOOP_TRANSITION(vha))) {
6221 			atomic_set(&vha->loop_down_timer, 0);
6222 			set_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags);
6223 			set_bit(LOCAL_LOOP_UPDATE, &vha->dpc_flags);
6224 			break;
6225 		}
6226 
6227 		if (swl != NULL) {
6228 			if (last_dev) {
6229 				wrap.b24 = new_fcport->d_id.b24;
6230 			} else {
6231 				new_fcport->d_id.b24 = swl[swl_idx].d_id.b24;
6232 				memcpy(new_fcport->node_name,
6233 				    swl[swl_idx].node_name, WWN_SIZE);
6234 				memcpy(new_fcport->port_name,
6235 				    swl[swl_idx].port_name, WWN_SIZE);
6236 				memcpy(new_fcport->fabric_port_name,
6237 				    swl[swl_idx].fabric_port_name, WWN_SIZE);
6238 				new_fcport->fp_speed = swl[swl_idx].fp_speed;
6239 				new_fcport->fc4_type = swl[swl_idx].fc4_type;
6240 
6241 				new_fcport->nvme_flag = 0;
6242 				if (vha->flags.nvme_enabled &&
6243 				    swl[swl_idx].fc4_type & FS_FC4TYPE_NVME) {
6244 					ql_log(ql_log_info, vha, 0x2131,
6245 					    "FOUND: NVME port %8phC as FC Type 28h\n",
6246 					    new_fcport->port_name);
6247 				}
6248 
6249 				if (swl[swl_idx].d_id.b.rsvd_1 != 0) {
6250 					last_dev = 1;
6251 				}
6252 				swl_idx++;
6253 			}
6254 		} else {
6255 			/* Send GA_NXT to the switch */
6256 			rval = qla2x00_ga_nxt(vha, new_fcport);
6257 			if (rval != QLA_SUCCESS) {
6258 				ql_log(ql_log_warn, vha, 0x209e,
6259 				    "SNS scan failed -- assuming "
6260 				    "zero-entry result.\n");
6261 				rval = QLA_SUCCESS;
6262 				break;
6263 			}
6264 		}
6265 
6266 		/* If wrap on switch device list, exit. */
6267 		if (first_dev) {
6268 			wrap.b24 = new_fcport->d_id.b24;
6269 			first_dev = 0;
6270 		} else if (new_fcport->d_id.b24 == wrap.b24) {
6271 			ql_dbg(ql_dbg_disc, vha, 0x209f,
6272 			    "Device wrap (%02x%02x%02x).\n",
6273 			    new_fcport->d_id.b.domain,
6274 			    new_fcport->d_id.b.area,
6275 			    new_fcport->d_id.b.al_pa);
6276 			break;
6277 		}
6278 
6279 		/* Bypass if same physical adapter. */
6280 		if (new_fcport->d_id.b24 == base_vha->d_id.b24)
6281 			continue;
6282 
6283 		/* Bypass virtual ports of the same host. */
6284 		if (qla2x00_is_a_vp_did(vha, new_fcport->d_id.b24))
6285 			continue;
6286 
6287 		/* Bypass if same domain and area of adapter. */
6288 		if (((new_fcport->d_id.b24 & 0xffff00) ==
6289 		    (vha->d_id.b24 & 0xffff00)) && ha->current_topology ==
6290 			ISP_CFG_FL)
6291 			    continue;
6292 
6293 		/* Bypass reserved domain fields. */
6294 		if ((new_fcport->d_id.b.domain & 0xf0) == 0xf0)
6295 			continue;
6296 
6297 		/* Bypass ports whose FCP-4 type is not FCP_SCSI */
6298 		if (ql2xgffidenable &&
6299 		    (!(new_fcport->fc4_type & FS_FC4TYPE_FCP) &&
6300 		    new_fcport->fc4_type != 0))
6301 			continue;
6302 
6303 		spin_lock_irqsave(&vha->hw->tgt.sess_lock, flags);
6304 
6305 		/* Locate matching device in database. */
6306 		found = 0;
6307 		list_for_each_entry(fcport, &vha->vp_fcports, list) {
6308 			if (memcmp(new_fcport->port_name, fcport->port_name,
6309 			    WWN_SIZE))
6310 				continue;
6311 
6312 			fcport->scan_state = QLA_FCPORT_FOUND;
6313 
6314 			found++;
6315 
6316 			/* Update port state. */
6317 			memcpy(fcport->fabric_port_name,
6318 			    new_fcport->fabric_port_name, WWN_SIZE);
6319 			fcport->fp_speed = new_fcport->fp_speed;
6320 
6321 			/*
6322 			 * If address the same and state FCS_ONLINE
6323 			 * (or in target mode), nothing changed.
6324 			 */
6325 			if (fcport->d_id.b24 == new_fcport->d_id.b24 &&
6326 			    (atomic_read(&fcport->state) == FCS_ONLINE ||
6327 			     (vha->host->active_mode == MODE_TARGET))) {
6328 				break;
6329 			}
6330 
6331 			if (fcport->login_retry == 0)
6332 				fcport->login_retry =
6333 					vha->hw->login_retry_count;
6334 			/*
6335 			 * If device was not a fabric device before.
6336 			 */
6337 			if ((fcport->flags & FCF_FABRIC_DEVICE) == 0) {
6338 				fcport->d_id.b24 = new_fcport->d_id.b24;
6339 				qla2x00_clear_loop_id(fcport);
6340 				fcport->flags |= (FCF_FABRIC_DEVICE |
6341 				    FCF_LOGIN_NEEDED);
6342 				break;
6343 			}
6344 
6345 			/*
6346 			 * Port ID changed or device was marked to be updated;
6347 			 * Log it out if still logged in and mark it for
6348 			 * relogin later.
6349 			 */
6350 			if (qla_tgt_mode_enabled(base_vha)) {
6351 				ql_dbg(ql_dbg_tgt_mgt, vha, 0xf080,
6352 					 "port changed FC ID, %8phC"
6353 					 " old %x:%x:%x (loop_id 0x%04x)-> new %x:%x:%x\n",
6354 					 fcport->port_name,
6355 					 fcport->d_id.b.domain,
6356 					 fcport->d_id.b.area,
6357 					 fcport->d_id.b.al_pa,
6358 					 fcport->loop_id,
6359 					 new_fcport->d_id.b.domain,
6360 					 new_fcport->d_id.b.area,
6361 					 new_fcport->d_id.b.al_pa);
6362 				fcport->d_id.b24 = new_fcport->d_id.b24;
6363 				break;
6364 			}
6365 
6366 			fcport->d_id.b24 = new_fcport->d_id.b24;
6367 			fcport->flags |= FCF_LOGIN_NEEDED;
6368 			break;
6369 		}
6370 
6371 		if (found && NVME_TARGET(vha->hw, fcport)) {
6372 			if (fcport->disc_state == DSC_DELETE_PEND) {
6373 				qla2x00_set_fcport_disc_state(fcport, DSC_GNL);
6374 				vha->fcport_count--;
6375 				fcport->login_succ = 0;
6376 			}
6377 		}
6378 
6379 		if (found) {
6380 			spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
6381 			continue;
6382 		}
6383 		/* If device was not in our fcports list, then add it. */
6384 		new_fcport->scan_state = QLA_FCPORT_FOUND;
6385 		list_add_tail(&new_fcport->list, &vha->vp_fcports);
6386 
6387 		spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, flags);
6388 
6389 
6390 		/* Allocate a new replacement fcport. */
6391 		nxt_d_id.b24 = new_fcport->d_id.b24;
6392 		new_fcport = qla2x00_alloc_fcport(vha, GFP_KERNEL);
6393 		if (new_fcport == NULL) {
6394 			ql_log(ql_log_warn, vha, 0xd032,
6395 			    "Memory allocation failed for fcport.\n");
6396 			return (QLA_MEMORY_ALLOC_FAILED);
6397 		}
6398 		new_fcport->flags |= (FCF_FABRIC_DEVICE | FCF_LOGIN_NEEDED);
6399 		new_fcport->d_id.b24 = nxt_d_id.b24;
6400 	}
6401 
6402 	qla2x00_free_fcport(new_fcport);
6403 
6404 	/*
6405 	 * Logout all previous fabric dev marked lost, except FCP2 devices.
6406 	 */
6407 	list_for_each_entry(fcport, &vha->vp_fcports, list) {
6408 		if (test_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags))
6409 			break;
6410 
6411 		if ((fcport->flags & FCF_FABRIC_DEVICE) == 0)
6412 			continue;
6413 
6414 		if (fcport->scan_state == QLA_FCPORT_SCAN) {
6415 			if ((qla_dual_mode_enabled(vha) ||
6416 			    qla_ini_mode_enabled(vha)) &&
6417 			    atomic_read(&fcport->state) == FCS_ONLINE) {
6418 				qla2x00_mark_device_lost(vha, fcport,
6419 					ql2xplogiabsentdevice);
6420 				if (fcport->loop_id != FC_NO_LOOP_ID &&
6421 				    (fcport->flags & FCF_FCP2_DEVICE) == 0 &&
6422 				    fcport->port_type != FCT_INITIATOR &&
6423 				    fcport->port_type != FCT_BROADCAST) {
6424 					ql_dbg(ql_dbg_disc, vha, 0x20f0,
6425 					    "%s %d %8phC post del sess\n",
6426 					    __func__, __LINE__,
6427 					    fcport->port_name);
6428 					qlt_schedule_sess_for_deletion(fcport);
6429 					continue;
6430 				}
6431 			}
6432 		}
6433 
6434 		if (fcport->scan_state == QLA_FCPORT_FOUND &&
6435 		    (fcport->flags & FCF_LOGIN_NEEDED) != 0)
6436 			qla24xx_fcport_handle_login(vha, fcport);
6437 	}
6438 	return (rval);
6439 }
6440 
6441 /* FW does not set aside Loop id for MGMT Server/FFFFFAh */
6442 int
6443 qla2x00_reserve_mgmt_server_loop_id(scsi_qla_host_t *vha)
6444 {
6445 	int loop_id = FC_NO_LOOP_ID;
6446 	int lid = NPH_MGMT_SERVER - vha->vp_idx;
6447 	unsigned long flags;
6448 	struct qla_hw_data *ha = vha->hw;
6449 
6450 	if (vha->vp_idx == 0) {
6451 		set_bit(NPH_MGMT_SERVER, ha->loop_id_map);
6452 		return NPH_MGMT_SERVER;
6453 	}
6454 
6455 	/* pick id from high and work down to low */
6456 	spin_lock_irqsave(&ha->vport_slock, flags);
6457 	for (; lid > 0; lid--) {
6458 		if (!test_bit(lid, vha->hw->loop_id_map)) {
6459 			set_bit(lid, vha->hw->loop_id_map);
6460 			loop_id = lid;
6461 			break;
6462 		}
6463 	}
6464 	spin_unlock_irqrestore(&ha->vport_slock, flags);
6465 
6466 	return loop_id;
6467 }
6468 
6469 /*
6470  * qla2x00_fabric_login
6471  *	Issue fabric login command.
6472  *
6473  * Input:
6474  *	ha = adapter block pointer.
6475  *	device = pointer to FC device type structure.
6476  *
6477  * Returns:
6478  *      0 - Login successfully
6479  *      1 - Login failed
6480  *      2 - Initiator device
6481  *      3 - Fatal error
6482  */
6483 int
6484 qla2x00_fabric_login(scsi_qla_host_t *vha, fc_port_t *fcport,
6485     uint16_t *next_loopid)
6486 {
6487 	int	rval;
6488 	int	retry;
6489 	uint16_t tmp_loopid;
6490 	uint16_t mb[MAILBOX_REGISTER_COUNT];
6491 	struct qla_hw_data *ha = vha->hw;
6492 
6493 	retry = 0;
6494 	tmp_loopid = 0;
6495 
6496 	for (;;) {
6497 		ql_dbg(ql_dbg_disc, vha, 0x2000,
6498 		    "Trying Fabric Login w/loop id 0x%04x for port "
6499 		    "%02x%02x%02x.\n",
6500 		    fcport->loop_id, fcport->d_id.b.domain,
6501 		    fcport->d_id.b.area, fcport->d_id.b.al_pa);
6502 
6503 		/* Login fcport on switch. */
6504 		rval = ha->isp_ops->fabric_login(vha, fcport->loop_id,
6505 		    fcport->d_id.b.domain, fcport->d_id.b.area,
6506 		    fcport->d_id.b.al_pa, mb, BIT_0);
6507 		if (rval != QLA_SUCCESS) {
6508 			return rval;
6509 		}
6510 		if (mb[0] == MBS_PORT_ID_USED) {
6511 			/*
6512 			 * Device has another loop ID.  The firmware team
6513 			 * recommends the driver perform an implicit login with
6514 			 * the specified ID again. The ID we just used is save
6515 			 * here so we return with an ID that can be tried by
6516 			 * the next login.
6517 			 */
6518 			retry++;
6519 			tmp_loopid = fcport->loop_id;
6520 			fcport->loop_id = mb[1];
6521 
6522 			ql_dbg(ql_dbg_disc, vha, 0x2001,
6523 			    "Fabric Login: port in use - next loop "
6524 			    "id=0x%04x, port id= %02x%02x%02x.\n",
6525 			    fcport->loop_id, fcport->d_id.b.domain,
6526 			    fcport->d_id.b.area, fcport->d_id.b.al_pa);
6527 
6528 		} else if (mb[0] == MBS_COMMAND_COMPLETE) {
6529 			/*
6530 			 * Login succeeded.
6531 			 */
6532 			if (retry) {
6533 				/* A retry occurred before. */
6534 				*next_loopid = tmp_loopid;
6535 			} else {
6536 				/*
6537 				 * No retry occurred before. Just increment the
6538 				 * ID value for next login.
6539 				 */
6540 				*next_loopid = (fcport->loop_id + 1);
6541 			}
6542 
6543 			if (mb[1] & BIT_0) {
6544 				fcport->port_type = FCT_INITIATOR;
6545 			} else {
6546 				fcport->port_type = FCT_TARGET;
6547 				if (mb[1] & BIT_1) {
6548 					fcport->flags |= FCF_FCP2_DEVICE;
6549 				}
6550 			}
6551 
6552 			if (mb[10] & BIT_0)
6553 				fcport->supported_classes |= FC_COS_CLASS2;
6554 			if (mb[10] & BIT_1)
6555 				fcport->supported_classes |= FC_COS_CLASS3;
6556 
6557 			if (IS_FWI2_CAPABLE(ha)) {
6558 				if (mb[10] & BIT_7)
6559 					fcport->flags |=
6560 					    FCF_CONF_COMP_SUPPORTED;
6561 			}
6562 
6563 			rval = QLA_SUCCESS;
6564 			break;
6565 		} else if (mb[0] == MBS_LOOP_ID_USED) {
6566 			/*
6567 			 * Loop ID already used, try next loop ID.
6568 			 */
6569 			fcport->loop_id++;
6570 			rval = qla2x00_find_new_loop_id(vha, fcport);
6571 			if (rval != QLA_SUCCESS) {
6572 				/* Ran out of loop IDs to use */
6573 				break;
6574 			}
6575 		} else if (mb[0] == MBS_COMMAND_ERROR) {
6576 			/*
6577 			 * Firmware possibly timed out during login. If NO
6578 			 * retries are left to do then the device is declared
6579 			 * dead.
6580 			 */
6581 			*next_loopid = fcport->loop_id;
6582 			ha->isp_ops->fabric_logout(vha, fcport->loop_id,
6583 			    fcport->d_id.b.domain, fcport->d_id.b.area,
6584 			    fcport->d_id.b.al_pa);
6585 			qla2x00_mark_device_lost(vha, fcport, 1);
6586 
6587 			rval = 1;
6588 			break;
6589 		} else {
6590 			/*
6591 			 * unrecoverable / not handled error
6592 			 */
6593 			ql_dbg(ql_dbg_disc, vha, 0x2002,
6594 			    "Failed=%x port_id=%02x%02x%02x loop_id=%x "
6595 			    "jiffies=%lx.\n", mb[0], fcport->d_id.b.domain,
6596 			    fcport->d_id.b.area, fcport->d_id.b.al_pa,
6597 			    fcport->loop_id, jiffies);
6598 
6599 			*next_loopid = fcport->loop_id;
6600 			ha->isp_ops->fabric_logout(vha, fcport->loop_id,
6601 			    fcport->d_id.b.domain, fcport->d_id.b.area,
6602 			    fcport->d_id.b.al_pa);
6603 			qla2x00_clear_loop_id(fcport);
6604 			fcport->login_retry = 0;
6605 
6606 			rval = 3;
6607 			break;
6608 		}
6609 	}
6610 
6611 	return (rval);
6612 }
6613 
6614 /*
6615  * qla2x00_local_device_login
6616  *	Issue local device login command.
6617  *
6618  * Input:
6619  *	ha = adapter block pointer.
6620  *	loop_id = loop id of device to login to.
6621  *
6622  * Returns (Where's the #define!!!!):
6623  *      0 - Login successfully
6624  *      1 - Login failed
6625  *      3 - Fatal error
6626  */
6627 int
6628 qla2x00_local_device_login(scsi_qla_host_t *vha, fc_port_t *fcport)
6629 {
6630 	int		rval;
6631 	uint16_t	mb[MAILBOX_REGISTER_COUNT];
6632 
6633 	memset(mb, 0, sizeof(mb));
6634 	rval = qla2x00_login_local_device(vha, fcport, mb, BIT_0);
6635 	if (rval == QLA_SUCCESS) {
6636 		/* Interrogate mailbox registers for any errors */
6637 		if (mb[0] == MBS_COMMAND_ERROR)
6638 			rval = 1;
6639 		else if (mb[0] == MBS_COMMAND_PARAMETER_ERROR)
6640 			/* device not in PCB table */
6641 			rval = 3;
6642 	}
6643 
6644 	return (rval);
6645 }
6646 
6647 /*
6648  *  qla2x00_loop_resync
6649  *      Resync with fibre channel devices.
6650  *
6651  * Input:
6652  *      ha = adapter block pointer.
6653  *
6654  * Returns:
6655  *      0 = success
6656  */
6657 int
6658 qla2x00_loop_resync(scsi_qla_host_t *vha)
6659 {
6660 	int rval = QLA_SUCCESS;
6661 	uint32_t wait_time;
6662 
6663 	clear_bit(ISP_ABORT_RETRY, &vha->dpc_flags);
6664 	if (vha->flags.online) {
6665 		if (!(rval = qla2x00_fw_ready(vha))) {
6666 			/* Wait at most MAX_TARGET RSCNs for a stable link. */
6667 			wait_time = 256;
6668 			do {
6669 				if (!IS_QLAFX00(vha->hw)) {
6670 					/*
6671 					 * Issue a marker after FW becomes
6672 					 * ready.
6673 					 */
6674 					qla2x00_marker(vha, vha->hw->base_qpair,
6675 					    0, 0, MK_SYNC_ALL);
6676 					vha->marker_needed = 0;
6677 				}
6678 
6679 				/* Remap devices on Loop. */
6680 				clear_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags);
6681 
6682 				if (IS_QLAFX00(vha->hw))
6683 					qlafx00_configure_devices(vha);
6684 				else
6685 					qla2x00_configure_loop(vha);
6686 
6687 				wait_time--;
6688 			} while (!atomic_read(&vha->loop_down_timer) &&
6689 				!(test_bit(ISP_ABORT_NEEDED, &vha->dpc_flags))
6690 				&& wait_time && (test_bit(LOOP_RESYNC_NEEDED,
6691 				&vha->dpc_flags)));
6692 		}
6693 	}
6694 
6695 	if (test_bit(ISP_ABORT_NEEDED, &vha->dpc_flags))
6696 		return (QLA_FUNCTION_FAILED);
6697 
6698 	if (rval)
6699 		ql_dbg(ql_dbg_disc, vha, 0x206c,
6700 		    "%s *** FAILED ***.\n", __func__);
6701 
6702 	return (rval);
6703 }
6704 
6705 /*
6706 * qla2x00_perform_loop_resync
6707 * Description: This function will set the appropriate flags and call
6708 *              qla2x00_loop_resync. If successful loop will be resynced
6709 * Arguments : scsi_qla_host_t pointer
6710 * returm    : Success or Failure
6711 */
6712 
6713 int qla2x00_perform_loop_resync(scsi_qla_host_t *ha)
6714 {
6715 	int32_t rval = 0;
6716 
6717 	if (!test_and_set_bit(LOOP_RESYNC_ACTIVE, &ha->dpc_flags)) {
6718 		/*Configure the flags so that resync happens properly*/
6719 		atomic_set(&ha->loop_down_timer, 0);
6720 		if (!(ha->device_flags & DFLG_NO_CABLE)) {
6721 			atomic_set(&ha->loop_state, LOOP_UP);
6722 			set_bit(LOCAL_LOOP_UPDATE, &ha->dpc_flags);
6723 			set_bit(REGISTER_FC4_NEEDED, &ha->dpc_flags);
6724 			set_bit(LOOP_RESYNC_NEEDED, &ha->dpc_flags);
6725 
6726 			rval = qla2x00_loop_resync(ha);
6727 		} else
6728 			atomic_set(&ha->loop_state, LOOP_DEAD);
6729 
6730 		clear_bit(LOOP_RESYNC_ACTIVE, &ha->dpc_flags);
6731 	}
6732 
6733 	return rval;
6734 }
6735 
6736 /* Assumes idc_lock always held on entry */
6737 void
6738 qla83xx_reset_ownership(scsi_qla_host_t *vha)
6739 {
6740 	struct qla_hw_data *ha = vha->hw;
6741 	uint32_t drv_presence, drv_presence_mask;
6742 	uint32_t dev_part_info1, dev_part_info2, class_type;
6743 	uint32_t class_type_mask = 0x3;
6744 	uint16_t fcoe_other_function = 0xffff, i;
6745 
6746 	if (IS_QLA8044(ha)) {
6747 		drv_presence = qla8044_rd_direct(vha,
6748 		    QLA8044_CRB_DRV_ACTIVE_INDEX);
6749 		dev_part_info1 = qla8044_rd_direct(vha,
6750 		    QLA8044_CRB_DEV_PART_INFO_INDEX);
6751 		dev_part_info2 = qla8044_rd_direct(vha,
6752 		    QLA8044_CRB_DEV_PART_INFO2);
6753 	} else {
6754 		qla83xx_rd_reg(vha, QLA83XX_IDC_DRV_PRESENCE, &drv_presence);
6755 		qla83xx_rd_reg(vha, QLA83XX_DEV_PARTINFO1, &dev_part_info1);
6756 		qla83xx_rd_reg(vha, QLA83XX_DEV_PARTINFO2, &dev_part_info2);
6757 	}
6758 	for (i = 0; i < 8; i++) {
6759 		class_type = ((dev_part_info1 >> (i * 4)) & class_type_mask);
6760 		if ((class_type == QLA83XX_CLASS_TYPE_FCOE) &&
6761 		    (i != ha->portnum)) {
6762 			fcoe_other_function = i;
6763 			break;
6764 		}
6765 	}
6766 	if (fcoe_other_function == 0xffff) {
6767 		for (i = 0; i < 8; i++) {
6768 			class_type = ((dev_part_info2 >> (i * 4)) &
6769 			    class_type_mask);
6770 			if ((class_type == QLA83XX_CLASS_TYPE_FCOE) &&
6771 			    ((i + 8) != ha->portnum)) {
6772 				fcoe_other_function = i + 8;
6773 				break;
6774 			}
6775 		}
6776 	}
6777 	/*
6778 	 * Prepare drv-presence mask based on fcoe functions present.
6779 	 * However consider only valid physical fcoe function numbers (0-15).
6780 	 */
6781 	drv_presence_mask = ~((1 << (ha->portnum)) |
6782 			((fcoe_other_function == 0xffff) ?
6783 			 0 : (1 << (fcoe_other_function))));
6784 
6785 	/* We are the reset owner iff:
6786 	 *    - No other protocol drivers present.
6787 	 *    - This is the lowest among fcoe functions. */
6788 	if (!(drv_presence & drv_presence_mask) &&
6789 			(ha->portnum < fcoe_other_function)) {
6790 		ql_dbg(ql_dbg_p3p, vha, 0xb07f,
6791 		    "This host is Reset owner.\n");
6792 		ha->flags.nic_core_reset_owner = 1;
6793 	}
6794 }
6795 
6796 static int
6797 __qla83xx_set_drv_ack(scsi_qla_host_t *vha)
6798 {
6799 	int rval = QLA_SUCCESS;
6800 	struct qla_hw_data *ha = vha->hw;
6801 	uint32_t drv_ack;
6802 
6803 	rval = qla83xx_rd_reg(vha, QLA83XX_IDC_DRIVER_ACK, &drv_ack);
6804 	if (rval == QLA_SUCCESS) {
6805 		drv_ack |= (1 << ha->portnum);
6806 		rval = qla83xx_wr_reg(vha, QLA83XX_IDC_DRIVER_ACK, drv_ack);
6807 	}
6808 
6809 	return rval;
6810 }
6811 
6812 static int
6813 __qla83xx_clear_drv_ack(scsi_qla_host_t *vha)
6814 {
6815 	int rval = QLA_SUCCESS;
6816 	struct qla_hw_data *ha = vha->hw;
6817 	uint32_t drv_ack;
6818 
6819 	rval = qla83xx_rd_reg(vha, QLA83XX_IDC_DRIVER_ACK, &drv_ack);
6820 	if (rval == QLA_SUCCESS) {
6821 		drv_ack &= ~(1 << ha->portnum);
6822 		rval = qla83xx_wr_reg(vha, QLA83XX_IDC_DRIVER_ACK, drv_ack);
6823 	}
6824 
6825 	return rval;
6826 }
6827 
6828 /* Assumes idc-lock always held on entry */
6829 void
6830 qla83xx_idc_audit(scsi_qla_host_t *vha, int audit_type)
6831 {
6832 	struct qla_hw_data *ha = vha->hw;
6833 	uint32_t idc_audit_reg = 0, duration_secs = 0;
6834 
6835 	switch (audit_type) {
6836 	case IDC_AUDIT_TIMESTAMP:
6837 		ha->idc_audit_ts = (jiffies_to_msecs(jiffies) / 1000);
6838 		idc_audit_reg = (ha->portnum) |
6839 		    (IDC_AUDIT_TIMESTAMP << 7) | (ha->idc_audit_ts << 8);
6840 		qla83xx_wr_reg(vha, QLA83XX_IDC_AUDIT, idc_audit_reg);
6841 		break;
6842 
6843 	case IDC_AUDIT_COMPLETION:
6844 		duration_secs = ((jiffies_to_msecs(jiffies) -
6845 		    jiffies_to_msecs(ha->idc_audit_ts)) / 1000);
6846 		idc_audit_reg = (ha->portnum) |
6847 		    (IDC_AUDIT_COMPLETION << 7) | (duration_secs << 8);
6848 		qla83xx_wr_reg(vha, QLA83XX_IDC_AUDIT, idc_audit_reg);
6849 		break;
6850 
6851 	default:
6852 		ql_log(ql_log_warn, vha, 0xb078,
6853 		    "Invalid audit type specified.\n");
6854 		break;
6855 	}
6856 }
6857 
6858 /* Assumes idc_lock always held on entry */
6859 static int
6860 qla83xx_initiating_reset(scsi_qla_host_t *vha)
6861 {
6862 	struct qla_hw_data *ha = vha->hw;
6863 	uint32_t  idc_control, dev_state;
6864 
6865 	__qla83xx_get_idc_control(vha, &idc_control);
6866 	if ((idc_control & QLA83XX_IDC_RESET_DISABLED)) {
6867 		ql_log(ql_log_info, vha, 0xb080,
6868 		    "NIC Core reset has been disabled. idc-control=0x%x\n",
6869 		    idc_control);
6870 		return QLA_FUNCTION_FAILED;
6871 	}
6872 
6873 	/* Set NEED-RESET iff in READY state and we are the reset-owner */
6874 	qla83xx_rd_reg(vha, QLA83XX_IDC_DEV_STATE, &dev_state);
6875 	if (ha->flags.nic_core_reset_owner && dev_state == QLA8XXX_DEV_READY) {
6876 		qla83xx_wr_reg(vha, QLA83XX_IDC_DEV_STATE,
6877 		    QLA8XXX_DEV_NEED_RESET);
6878 		ql_log(ql_log_info, vha, 0xb056, "HW State: NEED RESET.\n");
6879 		qla83xx_idc_audit(vha, IDC_AUDIT_TIMESTAMP);
6880 	} else {
6881 		ql_log(ql_log_info, vha, 0xb057, "HW State: %s.\n",
6882 				qdev_state(dev_state));
6883 
6884 		/* SV: XXX: Is timeout required here? */
6885 		/* Wait for IDC state change READY -> NEED_RESET */
6886 		while (dev_state == QLA8XXX_DEV_READY) {
6887 			qla83xx_idc_unlock(vha, 0);
6888 			msleep(200);
6889 			qla83xx_idc_lock(vha, 0);
6890 			qla83xx_rd_reg(vha, QLA83XX_IDC_DEV_STATE, &dev_state);
6891 		}
6892 	}
6893 
6894 	/* Send IDC ack by writing to drv-ack register */
6895 	__qla83xx_set_drv_ack(vha);
6896 
6897 	return QLA_SUCCESS;
6898 }
6899 
6900 int
6901 __qla83xx_set_idc_control(scsi_qla_host_t *vha, uint32_t idc_control)
6902 {
6903 	return qla83xx_wr_reg(vha, QLA83XX_IDC_CONTROL, idc_control);
6904 }
6905 
6906 int
6907 __qla83xx_get_idc_control(scsi_qla_host_t *vha, uint32_t *idc_control)
6908 {
6909 	return qla83xx_rd_reg(vha, QLA83XX_IDC_CONTROL, idc_control);
6910 }
6911 
6912 static int
6913 qla83xx_check_driver_presence(scsi_qla_host_t *vha)
6914 {
6915 	uint32_t drv_presence = 0;
6916 	struct qla_hw_data *ha = vha->hw;
6917 
6918 	qla83xx_rd_reg(vha, QLA83XX_IDC_DRV_PRESENCE, &drv_presence);
6919 	if (drv_presence & (1 << ha->portnum))
6920 		return QLA_SUCCESS;
6921 	else
6922 		return QLA_TEST_FAILED;
6923 }
6924 
6925 int
6926 qla83xx_nic_core_reset(scsi_qla_host_t *vha)
6927 {
6928 	int rval = QLA_SUCCESS;
6929 	struct qla_hw_data *ha = vha->hw;
6930 
6931 	ql_dbg(ql_dbg_p3p, vha, 0xb058,
6932 	    "Entered  %s().\n", __func__);
6933 
6934 	if (vha->device_flags & DFLG_DEV_FAILED) {
6935 		ql_log(ql_log_warn, vha, 0xb059,
6936 		    "Device in unrecoverable FAILED state.\n");
6937 		return QLA_FUNCTION_FAILED;
6938 	}
6939 
6940 	qla83xx_idc_lock(vha, 0);
6941 
6942 	if (qla83xx_check_driver_presence(vha) != QLA_SUCCESS) {
6943 		ql_log(ql_log_warn, vha, 0xb05a,
6944 		    "Function=0x%x has been removed from IDC participation.\n",
6945 		    ha->portnum);
6946 		rval = QLA_FUNCTION_FAILED;
6947 		goto exit;
6948 	}
6949 
6950 	qla83xx_reset_ownership(vha);
6951 
6952 	rval = qla83xx_initiating_reset(vha);
6953 
6954 	/*
6955 	 * Perform reset if we are the reset-owner,
6956 	 * else wait till IDC state changes to READY/FAILED.
6957 	 */
6958 	if (rval == QLA_SUCCESS) {
6959 		rval = qla83xx_idc_state_handler(vha);
6960 
6961 		if (rval == QLA_SUCCESS)
6962 			ha->flags.nic_core_hung = 0;
6963 		__qla83xx_clear_drv_ack(vha);
6964 	}
6965 
6966 exit:
6967 	qla83xx_idc_unlock(vha, 0);
6968 
6969 	ql_dbg(ql_dbg_p3p, vha, 0xb05b, "Exiting %s.\n", __func__);
6970 
6971 	return rval;
6972 }
6973 
6974 int
6975 qla2xxx_mctp_dump(scsi_qla_host_t *vha)
6976 {
6977 	struct qla_hw_data *ha = vha->hw;
6978 	int rval = QLA_FUNCTION_FAILED;
6979 
6980 	if (!IS_MCTP_CAPABLE(ha)) {
6981 		/* This message can be removed from the final version */
6982 		ql_log(ql_log_info, vha, 0x506d,
6983 		    "This board is not MCTP capable\n");
6984 		return rval;
6985 	}
6986 
6987 	if (!ha->mctp_dump) {
6988 		ha->mctp_dump = dma_alloc_coherent(&ha->pdev->dev,
6989 		    MCTP_DUMP_SIZE, &ha->mctp_dump_dma, GFP_KERNEL);
6990 
6991 		if (!ha->mctp_dump) {
6992 			ql_log(ql_log_warn, vha, 0x506e,
6993 			    "Failed to allocate memory for mctp dump\n");
6994 			return rval;
6995 		}
6996 	}
6997 
6998 #define MCTP_DUMP_STR_ADDR	0x00000000
6999 	rval = qla2x00_dump_mctp_data(vha, ha->mctp_dump_dma,
7000 	    MCTP_DUMP_STR_ADDR, MCTP_DUMP_SIZE/4);
7001 	if (rval != QLA_SUCCESS) {
7002 		ql_log(ql_log_warn, vha, 0x506f,
7003 		    "Failed to capture mctp dump\n");
7004 	} else {
7005 		ql_log(ql_log_info, vha, 0x5070,
7006 		    "Mctp dump capture for host (%ld/%p).\n",
7007 		    vha->host_no, ha->mctp_dump);
7008 		ha->mctp_dumped = 1;
7009 	}
7010 
7011 	if (!ha->flags.nic_core_reset_hdlr_active && !ha->portnum) {
7012 		ha->flags.nic_core_reset_hdlr_active = 1;
7013 		rval = qla83xx_restart_nic_firmware(vha);
7014 		if (rval)
7015 			/* NIC Core reset failed. */
7016 			ql_log(ql_log_warn, vha, 0x5071,
7017 			    "Failed to restart nic firmware\n");
7018 		else
7019 			ql_dbg(ql_dbg_p3p, vha, 0xb084,
7020 			    "Restarted NIC firmware successfully.\n");
7021 		ha->flags.nic_core_reset_hdlr_active = 0;
7022 	}
7023 
7024 	return rval;
7025 
7026 }
7027 
7028 /*
7029 * qla2x00_quiesce_io
7030 * Description: This function will block the new I/Os
7031 *              Its not aborting any I/Os as context
7032 *              is not destroyed during quiescence
7033 * Arguments: scsi_qla_host_t
7034 * return   : void
7035 */
7036 void
7037 qla2x00_quiesce_io(scsi_qla_host_t *vha)
7038 {
7039 	struct qla_hw_data *ha = vha->hw;
7040 	struct scsi_qla_host *vp, *tvp;
7041 	unsigned long flags;
7042 
7043 	ql_dbg(ql_dbg_dpc, vha, 0x401d,
7044 	    "Quiescing I/O - ha=%p.\n", ha);
7045 
7046 	atomic_set(&ha->loop_down_timer, LOOP_DOWN_TIME);
7047 	if (atomic_read(&vha->loop_state) != LOOP_DOWN) {
7048 		atomic_set(&vha->loop_state, LOOP_DOWN);
7049 		qla2x00_mark_all_devices_lost(vha);
7050 
7051 		spin_lock_irqsave(&ha->vport_slock, flags);
7052 		list_for_each_entry_safe(vp, tvp, &ha->vp_list, list) {
7053 			atomic_inc(&vp->vref_count);
7054 			spin_unlock_irqrestore(&ha->vport_slock, flags);
7055 
7056 			qla2x00_mark_all_devices_lost(vp);
7057 
7058 			spin_lock_irqsave(&ha->vport_slock, flags);
7059 			atomic_dec(&vp->vref_count);
7060 		}
7061 		spin_unlock_irqrestore(&ha->vport_slock, flags);
7062 	} else {
7063 		if (!atomic_read(&vha->loop_down_timer))
7064 			atomic_set(&vha->loop_down_timer,
7065 					LOOP_DOWN_TIME);
7066 	}
7067 	/* Wait for pending cmds to complete */
7068 	WARN_ON_ONCE(qla2x00_eh_wait_for_pending_commands(vha, 0, 0, WAIT_HOST)
7069 		     != QLA_SUCCESS);
7070 }
7071 
7072 void
7073 qla2x00_abort_isp_cleanup(scsi_qla_host_t *vha)
7074 {
7075 	struct qla_hw_data *ha = vha->hw;
7076 	struct scsi_qla_host *vp, *tvp;
7077 	unsigned long flags;
7078 	fc_port_t *fcport;
7079 	u16 i;
7080 
7081 	/* For ISP82XX, driver waits for completion of the commands.
7082 	 * online flag should be set.
7083 	 */
7084 	if (!(IS_P3P_TYPE(ha)))
7085 		vha->flags.online = 0;
7086 	ha->flags.chip_reset_done = 0;
7087 	clear_bit(ISP_ABORT_NEEDED, &vha->dpc_flags);
7088 	vha->qla_stats.total_isp_aborts++;
7089 
7090 	ql_log(ql_log_info, vha, 0x00af,
7091 	    "Performing ISP error recovery - ha=%p.\n", ha);
7092 
7093 	ha->flags.purge_mbox = 1;
7094 	/* For ISP82XX, reset_chip is just disabling interrupts.
7095 	 * Driver waits for the completion of the commands.
7096 	 * the interrupts need to be enabled.
7097 	 */
7098 	if (!(IS_P3P_TYPE(ha)))
7099 		ha->isp_ops->reset_chip(vha);
7100 
7101 	ha->link_data_rate = PORT_SPEED_UNKNOWN;
7102 	SAVE_TOPO(ha);
7103 	ha->flags.rida_fmt2 = 0;
7104 	ha->flags.n2n_ae = 0;
7105 	ha->flags.lip_ae = 0;
7106 	ha->current_topology = 0;
7107 	QLA_FW_STOPPED(ha);
7108 	ha->flags.fw_init_done = 0;
7109 	ha->chip_reset++;
7110 	ha->base_qpair->chip_reset = ha->chip_reset;
7111 	ha->base_qpair->cmd_cnt = ha->base_qpair->cmd_completion_cnt = 0;
7112 	ha->base_qpair->prev_completion_cnt = 0;
7113 	for (i = 0; i < ha->max_qpairs; i++) {
7114 		if (ha->queue_pair_map[i]) {
7115 			ha->queue_pair_map[i]->chip_reset =
7116 				ha->base_qpair->chip_reset;
7117 			ha->queue_pair_map[i]->cmd_cnt =
7118 			    ha->queue_pair_map[i]->cmd_completion_cnt = 0;
7119 			ha->base_qpair->prev_completion_cnt = 0;
7120 		}
7121 	}
7122 
7123 	/* purge MBox commands */
7124 	if (atomic_read(&ha->num_pend_mbx_stage3)) {
7125 		clear_bit(MBX_INTR_WAIT, &ha->mbx_cmd_flags);
7126 		complete(&ha->mbx_intr_comp);
7127 	}
7128 
7129 	i = 0;
7130 	while (atomic_read(&ha->num_pend_mbx_stage3) ||
7131 	    atomic_read(&ha->num_pend_mbx_stage2) ||
7132 	    atomic_read(&ha->num_pend_mbx_stage1)) {
7133 		msleep(20);
7134 		i++;
7135 		if (i > 50)
7136 			break;
7137 	}
7138 	ha->flags.purge_mbox = 0;
7139 
7140 	atomic_set(&vha->loop_down_timer, LOOP_DOWN_TIME);
7141 	if (atomic_read(&vha->loop_state) != LOOP_DOWN) {
7142 		atomic_set(&vha->loop_state, LOOP_DOWN);
7143 		qla2x00_mark_all_devices_lost(vha);
7144 
7145 		spin_lock_irqsave(&ha->vport_slock, flags);
7146 		list_for_each_entry_safe(vp, tvp, &ha->vp_list, list) {
7147 			atomic_inc(&vp->vref_count);
7148 			spin_unlock_irqrestore(&ha->vport_slock, flags);
7149 
7150 			qla2x00_mark_all_devices_lost(vp);
7151 
7152 			spin_lock_irqsave(&ha->vport_slock, flags);
7153 			atomic_dec(&vp->vref_count);
7154 		}
7155 		spin_unlock_irqrestore(&ha->vport_slock, flags);
7156 	} else {
7157 		if (!atomic_read(&vha->loop_down_timer))
7158 			atomic_set(&vha->loop_down_timer,
7159 			    LOOP_DOWN_TIME);
7160 	}
7161 
7162 	/* Clear all async request states across all VPs. */
7163 	list_for_each_entry(fcport, &vha->vp_fcports, list) {
7164 		fcport->flags &= ~(FCF_LOGIN_NEEDED | FCF_ASYNC_SENT);
7165 		fcport->scan_state = 0;
7166 	}
7167 	spin_lock_irqsave(&ha->vport_slock, flags);
7168 	list_for_each_entry_safe(vp, tvp, &ha->vp_list, list) {
7169 		atomic_inc(&vp->vref_count);
7170 		spin_unlock_irqrestore(&ha->vport_slock, flags);
7171 
7172 		list_for_each_entry(fcport, &vp->vp_fcports, list)
7173 			fcport->flags &= ~(FCF_LOGIN_NEEDED | FCF_ASYNC_SENT);
7174 
7175 		spin_lock_irqsave(&ha->vport_slock, flags);
7176 		atomic_dec(&vp->vref_count);
7177 	}
7178 	spin_unlock_irqrestore(&ha->vport_slock, flags);
7179 
7180 	/* Make sure for ISP 82XX IO DMA is complete */
7181 	if (IS_P3P_TYPE(ha)) {
7182 		qla82xx_chip_reset_cleanup(vha);
7183 		ql_log(ql_log_info, vha, 0x00b4,
7184 		       "Done chip reset cleanup.\n");
7185 
7186 		/* Done waiting for pending commands. Reset online flag */
7187 		vha->flags.online = 0;
7188 	}
7189 
7190 	/* Requeue all commands in outstanding command list. */
7191 	qla2x00_abort_all_cmds(vha, DID_RESET << 16);
7192 	/* memory barrier */
7193 	wmb();
7194 }
7195 
7196 /*
7197 *  qla2x00_abort_isp
7198 *      Resets ISP and aborts all outstanding commands.
7199 *
7200 * Input:
7201 *      ha           = adapter block pointer.
7202 *
7203 * Returns:
7204 *      0 = success
7205 */
7206 int
7207 qla2x00_abort_isp(scsi_qla_host_t *vha)
7208 {
7209 	int rval;
7210 	uint8_t        status = 0;
7211 	struct qla_hw_data *ha = vha->hw;
7212 	struct scsi_qla_host *vp, *tvp;
7213 	struct req_que *req = ha->req_q_map[0];
7214 	unsigned long flags;
7215 
7216 	if (vha->flags.online) {
7217 		qla2x00_abort_isp_cleanup(vha);
7218 
7219 		vha->dport_status |= DPORT_DIAG_CHIP_RESET_IN_PROGRESS;
7220 		vha->dport_status &= ~DPORT_DIAG_IN_PROGRESS;
7221 
7222 		if (vha->hw->flags.port_isolated)
7223 			return status;
7224 
7225 		if (qla2x00_isp_reg_stat(ha)) {
7226 			ql_log(ql_log_info, vha, 0x803f,
7227 			       "ISP Abort - ISP reg disconnect, exiting.\n");
7228 			return status;
7229 		}
7230 
7231 		if (test_and_clear_bit(ISP_ABORT_TO_ROM, &vha->dpc_flags)) {
7232 			ha->flags.chip_reset_done = 1;
7233 			vha->flags.online = 1;
7234 			status = 0;
7235 			clear_bit(ISP_ABORT_RETRY, &vha->dpc_flags);
7236 			return status;
7237 		}
7238 
7239 		if (IS_QLA8031(ha)) {
7240 			ql_dbg(ql_dbg_p3p, vha, 0xb05c,
7241 			    "Clearing fcoe driver presence.\n");
7242 			if (qla83xx_clear_drv_presence(vha) != QLA_SUCCESS)
7243 				ql_dbg(ql_dbg_p3p, vha, 0xb073,
7244 				    "Error while clearing DRV-Presence.\n");
7245 		}
7246 
7247 		if (unlikely(pci_channel_offline(ha->pdev) &&
7248 		    ha->flags.pci_channel_io_perm_failure)) {
7249 			clear_bit(ISP_ABORT_RETRY, &vha->dpc_flags);
7250 			status = 0;
7251 			return status;
7252 		}
7253 
7254 		switch (vha->qlini_mode) {
7255 		case QLA2XXX_INI_MODE_DISABLED:
7256 			if (!qla_tgt_mode_enabled(vha))
7257 				return 0;
7258 			break;
7259 		case QLA2XXX_INI_MODE_DUAL:
7260 			if (!qla_dual_mode_enabled(vha) &&
7261 			    !qla_ini_mode_enabled(vha))
7262 				return 0;
7263 			break;
7264 		case QLA2XXX_INI_MODE_ENABLED:
7265 		default:
7266 			break;
7267 		}
7268 
7269 		ha->isp_ops->get_flash_version(vha, req->ring);
7270 
7271 		if (qla2x00_isp_reg_stat(ha)) {
7272 			ql_log(ql_log_info, vha, 0x803f,
7273 			       "ISP Abort - ISP reg disconnect pre nvram config, exiting.\n");
7274 			return status;
7275 		}
7276 		ha->isp_ops->nvram_config(vha);
7277 
7278 		if (qla2x00_isp_reg_stat(ha)) {
7279 			ql_log(ql_log_info, vha, 0x803f,
7280 			       "ISP Abort - ISP reg disconnect post nvmram config, exiting.\n");
7281 			return status;
7282 		}
7283 		if (!qla2x00_restart_isp(vha)) {
7284 			clear_bit(RESET_MARKER_NEEDED, &vha->dpc_flags);
7285 
7286 			if (!atomic_read(&vha->loop_down_timer)) {
7287 				/*
7288 				 * Issue marker command only when we are going
7289 				 * to start the I/O .
7290 				 */
7291 				vha->marker_needed = 1;
7292 			}
7293 
7294 			vha->flags.online = 1;
7295 
7296 			ha->isp_ops->enable_intrs(ha);
7297 
7298 			ha->isp_abort_cnt = 0;
7299 			clear_bit(ISP_ABORT_RETRY, &vha->dpc_flags);
7300 
7301 			if (IS_QLA81XX(ha) || IS_QLA8031(ha))
7302 				qla2x00_get_fw_version(vha);
7303 			if (ha->fce) {
7304 				ha->flags.fce_enabled = 1;
7305 				memset(ha->fce, 0,
7306 				    fce_calc_size(ha->fce_bufs));
7307 				rval = qla2x00_enable_fce_trace(vha,
7308 				    ha->fce_dma, ha->fce_bufs, ha->fce_mb,
7309 				    &ha->fce_bufs);
7310 				if (rval) {
7311 					ql_log(ql_log_warn, vha, 0x8033,
7312 					    "Unable to reinitialize FCE "
7313 					    "(%d).\n", rval);
7314 					ha->flags.fce_enabled = 0;
7315 				}
7316 			}
7317 
7318 			if (ha->eft) {
7319 				memset(ha->eft, 0, EFT_SIZE);
7320 				rval = qla2x00_enable_eft_trace(vha,
7321 				    ha->eft_dma, EFT_NUM_BUFFERS);
7322 				if (rval) {
7323 					ql_log(ql_log_warn, vha, 0x8034,
7324 					    "Unable to reinitialize EFT "
7325 					    "(%d).\n", rval);
7326 				}
7327 			}
7328 		} else {	/* failed the ISP abort */
7329 			vha->flags.online = 1;
7330 			if (test_bit(ISP_ABORT_RETRY, &vha->dpc_flags)) {
7331 				if (ha->isp_abort_cnt == 0) {
7332 					ql_log(ql_log_fatal, vha, 0x8035,
7333 					    "ISP error recover failed - "
7334 					    "board disabled.\n");
7335 					/*
7336 					 * The next call disables the board
7337 					 * completely.
7338 					 */
7339 					qla2x00_abort_isp_cleanup(vha);
7340 					vha->flags.online = 0;
7341 					clear_bit(ISP_ABORT_RETRY,
7342 					    &vha->dpc_flags);
7343 					status = 0;
7344 				} else { /* schedule another ISP abort */
7345 					ha->isp_abort_cnt--;
7346 					ql_dbg(ql_dbg_taskm, vha, 0x8020,
7347 					    "ISP abort - retry remaining %d.\n",
7348 					    ha->isp_abort_cnt);
7349 					status = 1;
7350 				}
7351 			} else {
7352 				ha->isp_abort_cnt = MAX_RETRIES_OF_ISP_ABORT;
7353 				ql_dbg(ql_dbg_taskm, vha, 0x8021,
7354 				    "ISP error recovery - retrying (%d) "
7355 				    "more times.\n", ha->isp_abort_cnt);
7356 				set_bit(ISP_ABORT_RETRY, &vha->dpc_flags);
7357 				status = 1;
7358 			}
7359 		}
7360 
7361 	}
7362 
7363 	if (vha->hw->flags.port_isolated) {
7364 		qla2x00_abort_isp_cleanup(vha);
7365 		return status;
7366 	}
7367 
7368 	if (!status) {
7369 		ql_dbg(ql_dbg_taskm, vha, 0x8022, "%s succeeded.\n", __func__);
7370 		qla2x00_configure_hba(vha);
7371 		spin_lock_irqsave(&ha->vport_slock, flags);
7372 		list_for_each_entry_safe(vp, tvp, &ha->vp_list, list) {
7373 			if (vp->vp_idx) {
7374 				atomic_inc(&vp->vref_count);
7375 				spin_unlock_irqrestore(&ha->vport_slock, flags);
7376 
7377 				qla2x00_vp_abort_isp(vp);
7378 
7379 				spin_lock_irqsave(&ha->vport_slock, flags);
7380 				atomic_dec(&vp->vref_count);
7381 			}
7382 		}
7383 		spin_unlock_irqrestore(&ha->vport_slock, flags);
7384 
7385 		if (IS_QLA8031(ha)) {
7386 			ql_dbg(ql_dbg_p3p, vha, 0xb05d,
7387 			    "Setting back fcoe driver presence.\n");
7388 			if (qla83xx_set_drv_presence(vha) != QLA_SUCCESS)
7389 				ql_dbg(ql_dbg_p3p, vha, 0xb074,
7390 				    "Error while setting DRV-Presence.\n");
7391 		}
7392 	} else {
7393 		ql_log(ql_log_warn, vha, 0x8023, "%s **** FAILED ****.\n",
7394 		       __func__);
7395 	}
7396 
7397 	return(status);
7398 }
7399 
7400 /*
7401 *  qla2x00_restart_isp
7402 *      restarts the ISP after a reset
7403 *
7404 * Input:
7405 *      ha = adapter block pointer.
7406 *
7407 * Returns:
7408 *      0 = success
7409 */
7410 static int
7411 qla2x00_restart_isp(scsi_qla_host_t *vha)
7412 {
7413 	int status;
7414 	struct qla_hw_data *ha = vha->hw;
7415 
7416 	/* If firmware needs to be loaded */
7417 	if (qla2x00_isp_firmware(vha)) {
7418 		vha->flags.online = 0;
7419 		status = ha->isp_ops->chip_diag(vha);
7420 		if (status)
7421 			return status;
7422 		status = qla2x00_setup_chip(vha);
7423 		if (status)
7424 			return status;
7425 	}
7426 
7427 	status = qla2x00_init_rings(vha);
7428 	if (status)
7429 		return status;
7430 
7431 	clear_bit(RESET_MARKER_NEEDED, &vha->dpc_flags);
7432 	ha->flags.chip_reset_done = 1;
7433 
7434 	/* Initialize the queues in use */
7435 	qla25xx_init_queues(ha);
7436 
7437 	status = qla2x00_fw_ready(vha);
7438 	if (status) {
7439 		/* if no cable then assume it's good */
7440 		return vha->device_flags & DFLG_NO_CABLE ? 0 : status;
7441 	}
7442 
7443 	/* Issue a marker after FW becomes ready. */
7444 	qla2x00_marker(vha, ha->base_qpair, 0, 0, MK_SYNC_ALL);
7445 	set_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags);
7446 
7447 	return 0;
7448 }
7449 
7450 static int
7451 qla25xx_init_queues(struct qla_hw_data *ha)
7452 {
7453 	struct rsp_que *rsp = NULL;
7454 	struct req_que *req = NULL;
7455 	struct scsi_qla_host *base_vha = pci_get_drvdata(ha->pdev);
7456 	int ret = -1;
7457 	int i;
7458 
7459 	for (i = 1; i < ha->max_rsp_queues; i++) {
7460 		rsp = ha->rsp_q_map[i];
7461 		if (rsp && test_bit(i, ha->rsp_qid_map)) {
7462 			rsp->options &= ~BIT_0;
7463 			ret = qla25xx_init_rsp_que(base_vha, rsp);
7464 			if (ret != QLA_SUCCESS)
7465 				ql_dbg(ql_dbg_init, base_vha, 0x00ff,
7466 				    "%s Rsp que: %d init failed.\n",
7467 				    __func__, rsp->id);
7468 			else
7469 				ql_dbg(ql_dbg_init, base_vha, 0x0100,
7470 				    "%s Rsp que: %d inited.\n",
7471 				    __func__, rsp->id);
7472 		}
7473 	}
7474 	for (i = 1; i < ha->max_req_queues; i++) {
7475 		req = ha->req_q_map[i];
7476 		if (req && test_bit(i, ha->req_qid_map)) {
7477 			/* Clear outstanding commands array. */
7478 			req->options &= ~BIT_0;
7479 			ret = qla25xx_init_req_que(base_vha, req);
7480 			if (ret != QLA_SUCCESS)
7481 				ql_dbg(ql_dbg_init, base_vha, 0x0101,
7482 				    "%s Req que: %d init failed.\n",
7483 				    __func__, req->id);
7484 			else
7485 				ql_dbg(ql_dbg_init, base_vha, 0x0102,
7486 				    "%s Req que: %d inited.\n",
7487 				    __func__, req->id);
7488 		}
7489 	}
7490 	return ret;
7491 }
7492 
7493 /*
7494 * qla2x00_reset_adapter
7495 *      Reset adapter.
7496 *
7497 * Input:
7498 *      ha = adapter block pointer.
7499 */
7500 int
7501 qla2x00_reset_adapter(scsi_qla_host_t *vha)
7502 {
7503 	unsigned long flags = 0;
7504 	struct qla_hw_data *ha = vha->hw;
7505 	struct device_reg_2xxx __iomem *reg = &ha->iobase->isp;
7506 
7507 	vha->flags.online = 0;
7508 	ha->isp_ops->disable_intrs(ha);
7509 
7510 	spin_lock_irqsave(&ha->hardware_lock, flags);
7511 	wrt_reg_word(&reg->hccr, HCCR_RESET_RISC);
7512 	rd_reg_word(&reg->hccr);			/* PCI Posting. */
7513 	wrt_reg_word(&reg->hccr, HCCR_RELEASE_RISC);
7514 	rd_reg_word(&reg->hccr);			/* PCI Posting. */
7515 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
7516 
7517 	return QLA_SUCCESS;
7518 }
7519 
7520 int
7521 qla24xx_reset_adapter(scsi_qla_host_t *vha)
7522 {
7523 	unsigned long flags = 0;
7524 	struct qla_hw_data *ha = vha->hw;
7525 	struct device_reg_24xx __iomem *reg = &ha->iobase->isp24;
7526 
7527 	if (IS_P3P_TYPE(ha))
7528 		return QLA_SUCCESS;
7529 
7530 	vha->flags.online = 0;
7531 	ha->isp_ops->disable_intrs(ha);
7532 
7533 	spin_lock_irqsave(&ha->hardware_lock, flags);
7534 	wrt_reg_dword(&reg->hccr, HCCRX_SET_RISC_RESET);
7535 	rd_reg_dword(&reg->hccr);
7536 	wrt_reg_dword(&reg->hccr, HCCRX_REL_RISC_PAUSE);
7537 	rd_reg_dword(&reg->hccr);
7538 	spin_unlock_irqrestore(&ha->hardware_lock, flags);
7539 
7540 	if (IS_NOPOLLING_TYPE(ha))
7541 		ha->isp_ops->enable_intrs(ha);
7542 
7543 	return QLA_SUCCESS;
7544 }
7545 
7546 /* On sparc systems, obtain port and node WWN from firmware
7547  * properties.
7548  */
7549 static void qla24xx_nvram_wwn_from_ofw(scsi_qla_host_t *vha,
7550 	struct nvram_24xx *nv)
7551 {
7552 #ifdef CONFIG_SPARC
7553 	struct qla_hw_data *ha = vha->hw;
7554 	struct pci_dev *pdev = ha->pdev;
7555 	struct device_node *dp = pci_device_to_OF_node(pdev);
7556 	const u8 *val;
7557 	int len;
7558 
7559 	val = of_get_property(dp, "port-wwn", &len);
7560 	if (val && len >= WWN_SIZE)
7561 		memcpy(nv->port_name, val, WWN_SIZE);
7562 
7563 	val = of_get_property(dp, "node-wwn", &len);
7564 	if (val && len >= WWN_SIZE)
7565 		memcpy(nv->node_name, val, WWN_SIZE);
7566 #endif
7567 }
7568 
7569 int
7570 qla24xx_nvram_config(scsi_qla_host_t *vha)
7571 {
7572 	int   rval;
7573 	struct init_cb_24xx *icb;
7574 	struct nvram_24xx *nv;
7575 	__le32 *dptr;
7576 	uint8_t  *dptr1, *dptr2;
7577 	uint32_t chksum;
7578 	uint16_t cnt;
7579 	struct qla_hw_data *ha = vha->hw;
7580 
7581 	rval = QLA_SUCCESS;
7582 	icb = (struct init_cb_24xx *)ha->init_cb;
7583 	nv = ha->nvram;
7584 
7585 	/* Determine NVRAM starting address. */
7586 	if (ha->port_no == 0) {
7587 		ha->nvram_base = FA_NVRAM_FUNC0_ADDR;
7588 		ha->vpd_base = FA_NVRAM_VPD0_ADDR;
7589 	} else {
7590 		ha->nvram_base = FA_NVRAM_FUNC1_ADDR;
7591 		ha->vpd_base = FA_NVRAM_VPD1_ADDR;
7592 	}
7593 
7594 	ha->nvram_size = sizeof(*nv);
7595 	ha->vpd_size = FA_NVRAM_VPD_SIZE;
7596 
7597 	/* Get VPD data into cache */
7598 	ha->vpd = ha->nvram + VPD_OFFSET;
7599 	ha->isp_ops->read_nvram(vha, ha->vpd,
7600 	    ha->nvram_base - FA_NVRAM_FUNC0_ADDR, FA_NVRAM_VPD_SIZE * 4);
7601 
7602 	/* Get NVRAM data into cache and calculate checksum. */
7603 	dptr = (__force __le32 *)nv;
7604 	ha->isp_ops->read_nvram(vha, dptr, ha->nvram_base, ha->nvram_size);
7605 	for (cnt = 0, chksum = 0; cnt < ha->nvram_size >> 2; cnt++, dptr++)
7606 		chksum += le32_to_cpu(*dptr);
7607 
7608 	ql_dbg(ql_dbg_init + ql_dbg_buffer, vha, 0x006a,
7609 	    "Contents of NVRAM\n");
7610 	ql_dump_buffer(ql_dbg_init + ql_dbg_buffer, vha, 0x010d,
7611 	    nv, ha->nvram_size);
7612 
7613 	/* Bad NVRAM data, set defaults parameters. */
7614 	if (chksum || memcmp("ISP ", nv->id, sizeof(nv->id)) ||
7615 	    le16_to_cpu(nv->nvram_version) < ICB_VERSION) {
7616 		/* Reset NVRAM data. */
7617 		ql_log(ql_log_warn, vha, 0x006b,
7618 		    "Inconsistent NVRAM checksum=%#x id=%.4s version=%#x.\n",
7619 		    chksum, nv->id, nv->nvram_version);
7620 		ql_dump_buffer(ql_dbg_init, vha, 0x006b, nv, sizeof(*nv));
7621 		ql_log(ql_log_warn, vha, 0x006c,
7622 		    "Falling back to functioning (yet invalid -- WWPN) "
7623 		    "defaults.\n");
7624 
7625 		/*
7626 		 * Set default initialization control block.
7627 		 */
7628 		memset(nv, 0, ha->nvram_size);
7629 		nv->nvram_version = cpu_to_le16(ICB_VERSION);
7630 		nv->version = cpu_to_le16(ICB_VERSION);
7631 		nv->frame_payload_size = cpu_to_le16(2048);
7632 		nv->execution_throttle = cpu_to_le16(0xFFFF);
7633 		nv->exchange_count = cpu_to_le16(0);
7634 		nv->hard_address = cpu_to_le16(124);
7635 		nv->port_name[0] = 0x21;
7636 		nv->port_name[1] = 0x00 + ha->port_no + 1;
7637 		nv->port_name[2] = 0x00;
7638 		nv->port_name[3] = 0xe0;
7639 		nv->port_name[4] = 0x8b;
7640 		nv->port_name[5] = 0x1c;
7641 		nv->port_name[6] = 0x55;
7642 		nv->port_name[7] = 0x86;
7643 		nv->node_name[0] = 0x20;
7644 		nv->node_name[1] = 0x00;
7645 		nv->node_name[2] = 0x00;
7646 		nv->node_name[3] = 0xe0;
7647 		nv->node_name[4] = 0x8b;
7648 		nv->node_name[5] = 0x1c;
7649 		nv->node_name[6] = 0x55;
7650 		nv->node_name[7] = 0x86;
7651 		qla24xx_nvram_wwn_from_ofw(vha, nv);
7652 		nv->login_retry_count = cpu_to_le16(8);
7653 		nv->interrupt_delay_timer = cpu_to_le16(0);
7654 		nv->login_timeout = cpu_to_le16(0);
7655 		nv->firmware_options_1 =
7656 		    cpu_to_le32(BIT_14|BIT_13|BIT_2|BIT_1);
7657 		nv->firmware_options_2 = cpu_to_le32(2 << 4);
7658 		nv->firmware_options_2 |= cpu_to_le32(BIT_12);
7659 		nv->firmware_options_3 = cpu_to_le32(2 << 13);
7660 		nv->host_p = cpu_to_le32(BIT_11|BIT_10);
7661 		nv->efi_parameters = cpu_to_le32(0);
7662 		nv->reset_delay = 5;
7663 		nv->max_luns_per_target = cpu_to_le16(128);
7664 		nv->port_down_retry_count = cpu_to_le16(30);
7665 		nv->link_down_timeout = cpu_to_le16(30);
7666 
7667 		rval = 1;
7668 	}
7669 
7670 	if (qla_tgt_mode_enabled(vha)) {
7671 		/* Don't enable full login after initial LIP */
7672 		nv->firmware_options_1 &= cpu_to_le32(~BIT_13);
7673 		/* Don't enable LIP full login for initiator */
7674 		nv->host_p &= cpu_to_le32(~BIT_10);
7675 	}
7676 
7677 	qlt_24xx_config_nvram_stage1(vha, nv);
7678 
7679 	/* Reset Initialization control block */
7680 	memset(icb, 0, ha->init_cb_size);
7681 
7682 	/* Copy 1st segment. */
7683 	dptr1 = (uint8_t *)icb;
7684 	dptr2 = (uint8_t *)&nv->version;
7685 	cnt = (uint8_t *)&icb->response_q_inpointer - (uint8_t *)&icb->version;
7686 	while (cnt--)
7687 		*dptr1++ = *dptr2++;
7688 
7689 	icb->login_retry_count = nv->login_retry_count;
7690 	icb->link_down_on_nos = nv->link_down_on_nos;
7691 
7692 	/* Copy 2nd segment. */
7693 	dptr1 = (uint8_t *)&icb->interrupt_delay_timer;
7694 	dptr2 = (uint8_t *)&nv->interrupt_delay_timer;
7695 	cnt = (uint8_t *)&icb->reserved_3 -
7696 	    (uint8_t *)&icb->interrupt_delay_timer;
7697 	while (cnt--)
7698 		*dptr1++ = *dptr2++;
7699 	ha->frame_payload_size = le16_to_cpu(icb->frame_payload_size);
7700 	/*
7701 	 * Setup driver NVRAM options.
7702 	 */
7703 	qla2x00_set_model_info(vha, nv->model_name, sizeof(nv->model_name),
7704 	    "QLA2462");
7705 
7706 	qlt_24xx_config_nvram_stage2(vha, icb);
7707 
7708 	if (nv->host_p & cpu_to_le32(BIT_15)) {
7709 		/* Use alternate WWN? */
7710 		memcpy(icb->node_name, nv->alternate_node_name, WWN_SIZE);
7711 		memcpy(icb->port_name, nv->alternate_port_name, WWN_SIZE);
7712 	}
7713 
7714 	/* Prepare nodename */
7715 	if ((icb->firmware_options_1 & cpu_to_le32(BIT_14)) == 0) {
7716 		/*
7717 		 * Firmware will apply the following mask if the nodename was
7718 		 * not provided.
7719 		 */
7720 		memcpy(icb->node_name, icb->port_name, WWN_SIZE);
7721 		icb->node_name[0] &= 0xF0;
7722 	}
7723 
7724 	/* Set host adapter parameters. */
7725 	ha->flags.disable_risc_code_load = 0;
7726 	ha->flags.enable_lip_reset = 0;
7727 	ha->flags.enable_lip_full_login =
7728 	    le32_to_cpu(nv->host_p) & BIT_10 ? 1 : 0;
7729 	ha->flags.enable_target_reset =
7730 	    le32_to_cpu(nv->host_p) & BIT_11 ? 1 : 0;
7731 	ha->flags.enable_led_scheme = 0;
7732 	ha->flags.disable_serdes = le32_to_cpu(nv->host_p) & BIT_5 ? 1 : 0;
7733 
7734 	ha->operating_mode = (le32_to_cpu(icb->firmware_options_2) &
7735 	    (BIT_6 | BIT_5 | BIT_4)) >> 4;
7736 
7737 	memcpy(ha->fw_seriallink_options24, nv->seriallink_options,
7738 	    sizeof(ha->fw_seriallink_options24));
7739 
7740 	/* save HBA serial number */
7741 	ha->serial0 = icb->port_name[5];
7742 	ha->serial1 = icb->port_name[6];
7743 	ha->serial2 = icb->port_name[7];
7744 	memcpy(vha->node_name, icb->node_name, WWN_SIZE);
7745 	memcpy(vha->port_name, icb->port_name, WWN_SIZE);
7746 
7747 	icb->execution_throttle = cpu_to_le16(0xFFFF);
7748 
7749 	ha->retry_count = le16_to_cpu(nv->login_retry_count);
7750 
7751 	/* Set minimum login_timeout to 4 seconds. */
7752 	if (le16_to_cpu(nv->login_timeout) < ql2xlogintimeout)
7753 		nv->login_timeout = cpu_to_le16(ql2xlogintimeout);
7754 	if (le16_to_cpu(nv->login_timeout) < 4)
7755 		nv->login_timeout = cpu_to_le16(4);
7756 	ha->login_timeout = le16_to_cpu(nv->login_timeout);
7757 
7758 	/* Set minimum RATOV to 100 tenths of a second. */
7759 	ha->r_a_tov = 100;
7760 
7761 	ha->loop_reset_delay = nv->reset_delay;
7762 
7763 	/* Link Down Timeout = 0:
7764 	 *
7765 	 * 	When Port Down timer expires we will start returning
7766 	 *	I/O's to OS with "DID_NO_CONNECT".
7767 	 *
7768 	 * Link Down Timeout != 0:
7769 	 *
7770 	 *	 The driver waits for the link to come up after link down
7771 	 *	 before returning I/Os to OS with "DID_NO_CONNECT".
7772 	 */
7773 	if (le16_to_cpu(nv->link_down_timeout) == 0) {
7774 		ha->loop_down_abort_time =
7775 		    (LOOP_DOWN_TIME - LOOP_DOWN_TIMEOUT);
7776 	} else {
7777 		ha->link_down_timeout =	le16_to_cpu(nv->link_down_timeout);
7778 		ha->loop_down_abort_time =
7779 		    (LOOP_DOWN_TIME - ha->link_down_timeout);
7780 	}
7781 
7782 	/* Need enough time to try and get the port back. */
7783 	ha->port_down_retry_count = le16_to_cpu(nv->port_down_retry_count);
7784 	if (qlport_down_retry)
7785 		ha->port_down_retry_count = qlport_down_retry;
7786 
7787 	/* Set login_retry_count */
7788 	ha->login_retry_count  = le16_to_cpu(nv->login_retry_count);
7789 	if (ha->port_down_retry_count ==
7790 	    le16_to_cpu(nv->port_down_retry_count) &&
7791 	    ha->port_down_retry_count > 3)
7792 		ha->login_retry_count = ha->port_down_retry_count;
7793 	else if (ha->port_down_retry_count > (int)ha->login_retry_count)
7794 		ha->login_retry_count = ha->port_down_retry_count;
7795 	if (ql2xloginretrycount)
7796 		ha->login_retry_count = ql2xloginretrycount;
7797 
7798 	/* N2N: driver will initiate Login instead of FW */
7799 	icb->firmware_options_3 |= cpu_to_le32(BIT_8);
7800 
7801 	/* Enable ZIO. */
7802 	if (!vha->flags.init_done) {
7803 		ha->zio_mode = le32_to_cpu(icb->firmware_options_2) &
7804 		    (BIT_3 | BIT_2 | BIT_1 | BIT_0);
7805 		ha->zio_timer = le16_to_cpu(icb->interrupt_delay_timer) ?
7806 		    le16_to_cpu(icb->interrupt_delay_timer) : 2;
7807 	}
7808 	icb->firmware_options_2 &= cpu_to_le32(
7809 	    ~(BIT_3 | BIT_2 | BIT_1 | BIT_0));
7810 	if (ha->zio_mode != QLA_ZIO_DISABLED) {
7811 		ha->zio_mode = QLA_ZIO_MODE_6;
7812 
7813 		ql_log(ql_log_info, vha, 0x006f,
7814 		    "ZIO mode %d enabled; timer delay (%d us).\n",
7815 		    ha->zio_mode, ha->zio_timer * 100);
7816 
7817 		icb->firmware_options_2 |= cpu_to_le32(
7818 		    (uint32_t)ha->zio_mode);
7819 		icb->interrupt_delay_timer = cpu_to_le16(ha->zio_timer);
7820 	}
7821 
7822 	if (rval) {
7823 		ql_log(ql_log_warn, vha, 0x0070,
7824 		    "NVRAM configuration failed.\n");
7825 	}
7826 	return (rval);
7827 }
7828 
7829 static void
7830 qla27xx_print_image(struct scsi_qla_host *vha, char *name,
7831     struct qla27xx_image_status *image_status)
7832 {
7833 	ql_dbg(ql_dbg_init, vha, 0x018b,
7834 	    "%s %s: mask=%#02x gen=%#04x ver=%u.%u map=%#01x sum=%#08x sig=%#08x\n",
7835 	    name, "status",
7836 	    image_status->image_status_mask,
7837 	    le16_to_cpu(image_status->generation),
7838 	    image_status->ver_major,
7839 	    image_status->ver_minor,
7840 	    image_status->bitmap,
7841 	    le32_to_cpu(image_status->checksum),
7842 	    le32_to_cpu(image_status->signature));
7843 }
7844 
7845 static bool
7846 qla28xx_check_aux_image_status_signature(
7847     struct qla27xx_image_status *image_status)
7848 {
7849 	ulong signature = le32_to_cpu(image_status->signature);
7850 
7851 	return signature != QLA28XX_AUX_IMG_STATUS_SIGN;
7852 }
7853 
7854 static bool
7855 qla27xx_check_image_status_signature(struct qla27xx_image_status *image_status)
7856 {
7857 	ulong signature = le32_to_cpu(image_status->signature);
7858 
7859 	return
7860 	    signature != QLA27XX_IMG_STATUS_SIGN &&
7861 	    signature != QLA28XX_IMG_STATUS_SIGN;
7862 }
7863 
7864 static ulong
7865 qla27xx_image_status_checksum(struct qla27xx_image_status *image_status)
7866 {
7867 	__le32 *p = (__force __le32 *)image_status;
7868 	uint n = sizeof(*image_status) / sizeof(*p);
7869 	uint32_t sum = 0;
7870 
7871 	for ( ; n--; p++)
7872 		sum += le32_to_cpup(p);
7873 
7874 	return sum;
7875 }
7876 
7877 static inline uint
7878 qla28xx_component_bitmask(struct qla27xx_image_status *aux, uint bitmask)
7879 {
7880 	return aux->bitmap & bitmask ?
7881 	    QLA27XX_SECONDARY_IMAGE : QLA27XX_PRIMARY_IMAGE;
7882 }
7883 
7884 static void
7885 qla28xx_component_status(
7886     struct active_regions *active_regions, struct qla27xx_image_status *aux)
7887 {
7888 	active_regions->aux.board_config =
7889 	    qla28xx_component_bitmask(aux, QLA28XX_AUX_IMG_BOARD_CONFIG);
7890 
7891 	active_regions->aux.vpd_nvram =
7892 	    qla28xx_component_bitmask(aux, QLA28XX_AUX_IMG_VPD_NVRAM);
7893 
7894 	active_regions->aux.npiv_config_0_1 =
7895 	    qla28xx_component_bitmask(aux, QLA28XX_AUX_IMG_NPIV_CONFIG_0_1);
7896 
7897 	active_regions->aux.npiv_config_2_3 =
7898 	    qla28xx_component_bitmask(aux, QLA28XX_AUX_IMG_NPIV_CONFIG_2_3);
7899 
7900 	active_regions->aux.nvme_params =
7901 	    qla28xx_component_bitmask(aux, QLA28XX_AUX_IMG_NVME_PARAMS);
7902 }
7903 
7904 static int
7905 qla27xx_compare_image_generation(
7906     struct qla27xx_image_status *pri_image_status,
7907     struct qla27xx_image_status *sec_image_status)
7908 {
7909 	/* calculate generation delta as uint16 (this accounts for wrap) */
7910 	int16_t delta =
7911 	    le16_to_cpu(pri_image_status->generation) -
7912 	    le16_to_cpu(sec_image_status->generation);
7913 
7914 	ql_dbg(ql_dbg_init, NULL, 0x0180, "generation delta = %d\n", delta);
7915 
7916 	return delta;
7917 }
7918 
7919 void
7920 qla28xx_get_aux_images(
7921 	struct scsi_qla_host *vha, struct active_regions *active_regions)
7922 {
7923 	struct qla_hw_data *ha = vha->hw;
7924 	struct qla27xx_image_status pri_aux_image_status, sec_aux_image_status;
7925 	bool valid_pri_image = false, valid_sec_image = false;
7926 	bool active_pri_image = false, active_sec_image = false;
7927 
7928 	if (!ha->flt_region_aux_img_status_pri) {
7929 		ql_dbg(ql_dbg_init, vha, 0x018a, "Primary aux image not addressed\n");
7930 		goto check_sec_image;
7931 	}
7932 
7933 	qla24xx_read_flash_data(vha, (uint32_t *)&pri_aux_image_status,
7934 	    ha->flt_region_aux_img_status_pri,
7935 	    sizeof(pri_aux_image_status) >> 2);
7936 	qla27xx_print_image(vha, "Primary aux image", &pri_aux_image_status);
7937 
7938 	if (qla28xx_check_aux_image_status_signature(&pri_aux_image_status)) {
7939 		ql_dbg(ql_dbg_init, vha, 0x018b,
7940 		    "Primary aux image signature (%#x) not valid\n",
7941 		    le32_to_cpu(pri_aux_image_status.signature));
7942 		goto check_sec_image;
7943 	}
7944 
7945 	if (qla27xx_image_status_checksum(&pri_aux_image_status)) {
7946 		ql_dbg(ql_dbg_init, vha, 0x018c,
7947 		    "Primary aux image checksum failed\n");
7948 		goto check_sec_image;
7949 	}
7950 
7951 	valid_pri_image = true;
7952 
7953 	if (pri_aux_image_status.image_status_mask & 1) {
7954 		ql_dbg(ql_dbg_init, vha, 0x018d,
7955 		    "Primary aux image is active\n");
7956 		active_pri_image = true;
7957 	}
7958 
7959 check_sec_image:
7960 	if (!ha->flt_region_aux_img_status_sec) {
7961 		ql_dbg(ql_dbg_init, vha, 0x018a,
7962 		    "Secondary aux image not addressed\n");
7963 		goto check_valid_image;
7964 	}
7965 
7966 	qla24xx_read_flash_data(vha, (uint32_t *)&sec_aux_image_status,
7967 	    ha->flt_region_aux_img_status_sec,
7968 	    sizeof(sec_aux_image_status) >> 2);
7969 	qla27xx_print_image(vha, "Secondary aux image", &sec_aux_image_status);
7970 
7971 	if (qla28xx_check_aux_image_status_signature(&sec_aux_image_status)) {
7972 		ql_dbg(ql_dbg_init, vha, 0x018b,
7973 		    "Secondary aux image signature (%#x) not valid\n",
7974 		    le32_to_cpu(sec_aux_image_status.signature));
7975 		goto check_valid_image;
7976 	}
7977 
7978 	if (qla27xx_image_status_checksum(&sec_aux_image_status)) {
7979 		ql_dbg(ql_dbg_init, vha, 0x018c,
7980 		    "Secondary aux image checksum failed\n");
7981 		goto check_valid_image;
7982 	}
7983 
7984 	valid_sec_image = true;
7985 
7986 	if (sec_aux_image_status.image_status_mask & 1) {
7987 		ql_dbg(ql_dbg_init, vha, 0x018d,
7988 		    "Secondary aux image is active\n");
7989 		active_sec_image = true;
7990 	}
7991 
7992 check_valid_image:
7993 	if (valid_pri_image && active_pri_image &&
7994 	    valid_sec_image && active_sec_image) {
7995 		if (qla27xx_compare_image_generation(&pri_aux_image_status,
7996 		    &sec_aux_image_status) >= 0) {
7997 			qla28xx_component_status(active_regions,
7998 			    &pri_aux_image_status);
7999 		} else {
8000 			qla28xx_component_status(active_regions,
8001 			    &sec_aux_image_status);
8002 		}
8003 	} else if (valid_pri_image && active_pri_image) {
8004 		qla28xx_component_status(active_regions, &pri_aux_image_status);
8005 	} else if (valid_sec_image && active_sec_image) {
8006 		qla28xx_component_status(active_regions, &sec_aux_image_status);
8007 	}
8008 
8009 	ql_dbg(ql_dbg_init, vha, 0x018f,
8010 	    "aux images active: BCFG=%u VPD/NVR=%u NPIV0/1=%u NPIV2/3=%u, NVME=%u\n",
8011 	    active_regions->aux.board_config,
8012 	    active_regions->aux.vpd_nvram,
8013 	    active_regions->aux.npiv_config_0_1,
8014 	    active_regions->aux.npiv_config_2_3,
8015 	    active_regions->aux.nvme_params);
8016 }
8017 
8018 void
8019 qla27xx_get_active_image(struct scsi_qla_host *vha,
8020     struct active_regions *active_regions)
8021 {
8022 	struct qla_hw_data *ha = vha->hw;
8023 	struct qla27xx_image_status pri_image_status, sec_image_status;
8024 	bool valid_pri_image = false, valid_sec_image = false;
8025 	bool active_pri_image = false, active_sec_image = false;
8026 
8027 	if (!ha->flt_region_img_status_pri) {
8028 		ql_dbg(ql_dbg_init, vha, 0x018a, "Primary image not addressed\n");
8029 		goto check_sec_image;
8030 	}
8031 
8032 	if (qla24xx_read_flash_data(vha, (uint32_t *)&pri_image_status,
8033 	    ha->flt_region_img_status_pri, sizeof(pri_image_status) >> 2) !=
8034 	    QLA_SUCCESS) {
8035 		WARN_ON_ONCE(true);
8036 		goto check_sec_image;
8037 	}
8038 	qla27xx_print_image(vha, "Primary image", &pri_image_status);
8039 
8040 	if (qla27xx_check_image_status_signature(&pri_image_status)) {
8041 		ql_dbg(ql_dbg_init, vha, 0x018b,
8042 		    "Primary image signature (%#x) not valid\n",
8043 		    le32_to_cpu(pri_image_status.signature));
8044 		goto check_sec_image;
8045 	}
8046 
8047 	if (qla27xx_image_status_checksum(&pri_image_status)) {
8048 		ql_dbg(ql_dbg_init, vha, 0x018c,
8049 		    "Primary image checksum failed\n");
8050 		goto check_sec_image;
8051 	}
8052 
8053 	valid_pri_image = true;
8054 
8055 	if (pri_image_status.image_status_mask & 1) {
8056 		ql_dbg(ql_dbg_init, vha, 0x018d,
8057 		    "Primary image is active\n");
8058 		active_pri_image = true;
8059 	}
8060 
8061 check_sec_image:
8062 	if (!ha->flt_region_img_status_sec) {
8063 		ql_dbg(ql_dbg_init, vha, 0x018a, "Secondary image not addressed\n");
8064 		goto check_valid_image;
8065 	}
8066 
8067 	qla24xx_read_flash_data(vha, (uint32_t *)(&sec_image_status),
8068 	    ha->flt_region_img_status_sec, sizeof(sec_image_status) >> 2);
8069 	qla27xx_print_image(vha, "Secondary image", &sec_image_status);
8070 
8071 	if (qla27xx_check_image_status_signature(&sec_image_status)) {
8072 		ql_dbg(ql_dbg_init, vha, 0x018b,
8073 		    "Secondary image signature (%#x) not valid\n",
8074 		    le32_to_cpu(sec_image_status.signature));
8075 		goto check_valid_image;
8076 	}
8077 
8078 	if (qla27xx_image_status_checksum(&sec_image_status)) {
8079 		ql_dbg(ql_dbg_init, vha, 0x018c,
8080 		    "Secondary image checksum failed\n");
8081 		goto check_valid_image;
8082 	}
8083 
8084 	valid_sec_image = true;
8085 
8086 	if (sec_image_status.image_status_mask & 1) {
8087 		ql_dbg(ql_dbg_init, vha, 0x018d,
8088 		    "Secondary image is active\n");
8089 		active_sec_image = true;
8090 	}
8091 
8092 check_valid_image:
8093 	if (valid_pri_image && active_pri_image)
8094 		active_regions->global = QLA27XX_PRIMARY_IMAGE;
8095 
8096 	if (valid_sec_image && active_sec_image) {
8097 		if (!active_regions->global ||
8098 		    qla27xx_compare_image_generation(
8099 			&pri_image_status, &sec_image_status) < 0) {
8100 			active_regions->global = QLA27XX_SECONDARY_IMAGE;
8101 		}
8102 	}
8103 
8104 	ql_dbg(ql_dbg_init, vha, 0x018f, "active image %s (%u)\n",
8105 	    active_regions->global == QLA27XX_DEFAULT_IMAGE ?
8106 		"default (boot/fw)" :
8107 	    active_regions->global == QLA27XX_PRIMARY_IMAGE ?
8108 		"primary" :
8109 	    active_regions->global == QLA27XX_SECONDARY_IMAGE ?
8110 		"secondary" : "invalid",
8111 	    active_regions->global);
8112 }
8113 
8114 bool qla24xx_risc_firmware_invalid(uint32_t *dword)
8115 {
8116 	return
8117 	    !(dword[4] | dword[5] | dword[6] | dword[7]) ||
8118 	    !(~dword[4] | ~dword[5] | ~dword[6] | ~dword[7]);
8119 }
8120 
8121 static int
8122 qla24xx_load_risc_flash(scsi_qla_host_t *vha, uint32_t *srisc_addr,
8123     uint32_t faddr)
8124 {
8125 	int rval;
8126 	uint templates, segments, fragment;
8127 	ulong i;
8128 	uint j;
8129 	ulong dlen;
8130 	uint32_t *dcode;
8131 	uint32_t risc_addr, risc_size, risc_attr = 0;
8132 	struct qla_hw_data *ha = vha->hw;
8133 	struct req_que *req = ha->req_q_map[0];
8134 	struct fwdt *fwdt = ha->fwdt;
8135 
8136 	ql_dbg(ql_dbg_init, vha, 0x008b,
8137 	    "FW: Loading firmware from flash (%x).\n", faddr);
8138 
8139 	dcode = (uint32_t *)req->ring;
8140 	qla24xx_read_flash_data(vha, dcode, faddr, 8);
8141 	if (qla24xx_risc_firmware_invalid(dcode)) {
8142 		ql_log(ql_log_fatal, vha, 0x008c,
8143 		    "Unable to verify the integrity of flash firmware "
8144 		    "image.\n");
8145 		ql_log(ql_log_fatal, vha, 0x008d,
8146 		    "Firmware data: %08x %08x %08x %08x.\n",
8147 		    dcode[0], dcode[1], dcode[2], dcode[3]);
8148 
8149 		return QLA_FUNCTION_FAILED;
8150 	}
8151 
8152 	dcode = (uint32_t *)req->ring;
8153 	*srisc_addr = 0;
8154 	segments = FA_RISC_CODE_SEGMENTS;
8155 	for (j = 0; j < segments; j++) {
8156 		ql_dbg(ql_dbg_init, vha, 0x008d,
8157 		    "-> Loading segment %u...\n", j);
8158 		qla24xx_read_flash_data(vha, dcode, faddr, 10);
8159 		risc_addr = be32_to_cpu((__force __be32)dcode[2]);
8160 		risc_size = be32_to_cpu((__force __be32)dcode[3]);
8161 		if (!*srisc_addr) {
8162 			*srisc_addr = risc_addr;
8163 			risc_attr = be32_to_cpu((__force __be32)dcode[9]);
8164 		}
8165 
8166 		dlen = ha->fw_transfer_size >> 2;
8167 		for (fragment = 0; risc_size; fragment++) {
8168 			if (dlen > risc_size)
8169 				dlen = risc_size;
8170 
8171 			ql_dbg(ql_dbg_init, vha, 0x008e,
8172 			    "-> Loading fragment %u: %#x <- %#x (%#lx dwords)...\n",
8173 			    fragment, risc_addr, faddr, dlen);
8174 			qla24xx_read_flash_data(vha, dcode, faddr, dlen);
8175 			for (i = 0; i < dlen; i++)
8176 				dcode[i] = swab32(dcode[i]);
8177 
8178 			rval = qla2x00_load_ram(vha, req->dma, risc_addr, dlen);
8179 			if (rval) {
8180 				ql_log(ql_log_fatal, vha, 0x008f,
8181 				    "-> Failed load firmware fragment %u.\n",
8182 				    fragment);
8183 				return QLA_FUNCTION_FAILED;
8184 			}
8185 
8186 			faddr += dlen;
8187 			risc_addr += dlen;
8188 			risc_size -= dlen;
8189 		}
8190 	}
8191 
8192 	if (!IS_QLA27XX(ha) && !IS_QLA28XX(ha))
8193 		return QLA_SUCCESS;
8194 
8195 	templates = (risc_attr & BIT_9) ? 2 : 1;
8196 	ql_dbg(ql_dbg_init, vha, 0x0160, "-> templates = %u\n", templates);
8197 	for (j = 0; j < templates; j++, fwdt++) {
8198 		vfree(fwdt->template);
8199 		fwdt->template = NULL;
8200 		fwdt->length = 0;
8201 
8202 		dcode = (uint32_t *)req->ring;
8203 		qla24xx_read_flash_data(vha, dcode, faddr, 7);
8204 		risc_size = be32_to_cpu((__force __be32)dcode[2]);
8205 		ql_dbg(ql_dbg_init, vha, 0x0161,
8206 		    "-> fwdt%u template array at %#x (%#x dwords)\n",
8207 		    j, faddr, risc_size);
8208 		if (!risc_size || !~risc_size) {
8209 			ql_dbg(ql_dbg_init, vha, 0x0162,
8210 			    "-> fwdt%u failed to read array\n", j);
8211 			goto failed;
8212 		}
8213 
8214 		/* skip header and ignore checksum */
8215 		faddr += 7;
8216 		risc_size -= 8;
8217 
8218 		ql_dbg(ql_dbg_init, vha, 0x0163,
8219 		    "-> fwdt%u template allocate template %#x words...\n",
8220 		    j, risc_size);
8221 		fwdt->template = vmalloc(risc_size * sizeof(*dcode));
8222 		if (!fwdt->template) {
8223 			ql_log(ql_log_warn, vha, 0x0164,
8224 			    "-> fwdt%u failed allocate template.\n", j);
8225 			goto failed;
8226 		}
8227 
8228 		dcode = fwdt->template;
8229 		qla24xx_read_flash_data(vha, dcode, faddr, risc_size);
8230 
8231 		if (!qla27xx_fwdt_template_valid(dcode)) {
8232 			ql_log(ql_log_warn, vha, 0x0165,
8233 			    "-> fwdt%u failed template validate\n", j);
8234 			goto failed;
8235 		}
8236 
8237 		dlen = qla27xx_fwdt_template_size(dcode);
8238 		ql_dbg(ql_dbg_init, vha, 0x0166,
8239 		    "-> fwdt%u template size %#lx bytes (%#lx words)\n",
8240 		    j, dlen, dlen / sizeof(*dcode));
8241 		if (dlen > risc_size * sizeof(*dcode)) {
8242 			ql_log(ql_log_warn, vha, 0x0167,
8243 			    "-> fwdt%u template exceeds array (%-lu bytes)\n",
8244 			    j, dlen - risc_size * sizeof(*dcode));
8245 			goto failed;
8246 		}
8247 
8248 		fwdt->length = dlen;
8249 		ql_dbg(ql_dbg_init, vha, 0x0168,
8250 		    "-> fwdt%u loaded template ok\n", j);
8251 
8252 		faddr += risc_size + 1;
8253 	}
8254 
8255 	return QLA_SUCCESS;
8256 
8257 failed:
8258 	vfree(fwdt->template);
8259 	fwdt->template = NULL;
8260 	fwdt->length = 0;
8261 
8262 	return QLA_SUCCESS;
8263 }
8264 
8265 #define QLA_FW_URL "http://ldriver.qlogic.com/firmware/"
8266 
8267 int
8268 qla2x00_load_risc(scsi_qla_host_t *vha, uint32_t *srisc_addr)
8269 {
8270 	int	rval;
8271 	int	i, fragment;
8272 	uint16_t *wcode;
8273 	__be16	 *fwcode;
8274 	uint32_t risc_addr, risc_size, fwclen, wlen, *seg;
8275 	struct fw_blob *blob;
8276 	struct qla_hw_data *ha = vha->hw;
8277 	struct req_que *req = ha->req_q_map[0];
8278 
8279 	/* Load firmware blob. */
8280 	blob = qla2x00_request_firmware(vha);
8281 	if (!blob) {
8282 		ql_log(ql_log_info, vha, 0x0083,
8283 		    "Firmware image unavailable.\n");
8284 		ql_log(ql_log_info, vha, 0x0084,
8285 		    "Firmware images can be retrieved from: "QLA_FW_URL ".\n");
8286 		return QLA_FUNCTION_FAILED;
8287 	}
8288 
8289 	rval = QLA_SUCCESS;
8290 
8291 	wcode = (uint16_t *)req->ring;
8292 	*srisc_addr = 0;
8293 	fwcode = (__force __be16 *)blob->fw->data;
8294 	fwclen = 0;
8295 
8296 	/* Validate firmware image by checking version. */
8297 	if (blob->fw->size < 8 * sizeof(uint16_t)) {
8298 		ql_log(ql_log_fatal, vha, 0x0085,
8299 		    "Unable to verify integrity of firmware image (%zd).\n",
8300 		    blob->fw->size);
8301 		goto fail_fw_integrity;
8302 	}
8303 	for (i = 0; i < 4; i++)
8304 		wcode[i] = be16_to_cpu(fwcode[i + 4]);
8305 	if ((wcode[0] == 0xffff && wcode[1] == 0xffff && wcode[2] == 0xffff &&
8306 	    wcode[3] == 0xffff) || (wcode[0] == 0 && wcode[1] == 0 &&
8307 		wcode[2] == 0 && wcode[3] == 0)) {
8308 		ql_log(ql_log_fatal, vha, 0x0086,
8309 		    "Unable to verify integrity of firmware image.\n");
8310 		ql_log(ql_log_fatal, vha, 0x0087,
8311 		    "Firmware data: %04x %04x %04x %04x.\n",
8312 		    wcode[0], wcode[1], wcode[2], wcode[3]);
8313 		goto fail_fw_integrity;
8314 	}
8315 
8316 	seg = blob->segs;
8317 	while (*seg && rval == QLA_SUCCESS) {
8318 		risc_addr = *seg;
8319 		*srisc_addr = *srisc_addr == 0 ? *seg : *srisc_addr;
8320 		risc_size = be16_to_cpu(fwcode[3]);
8321 
8322 		/* Validate firmware image size. */
8323 		fwclen += risc_size * sizeof(uint16_t);
8324 		if (blob->fw->size < fwclen) {
8325 			ql_log(ql_log_fatal, vha, 0x0088,
8326 			    "Unable to verify integrity of firmware image "
8327 			    "(%zd).\n", blob->fw->size);
8328 			goto fail_fw_integrity;
8329 		}
8330 
8331 		fragment = 0;
8332 		while (risc_size > 0 && rval == QLA_SUCCESS) {
8333 			wlen = (uint16_t)(ha->fw_transfer_size >> 1);
8334 			if (wlen > risc_size)
8335 				wlen = risc_size;
8336 			ql_dbg(ql_dbg_init, vha, 0x0089,
8337 			    "Loading risc segment@ risc addr %x number of "
8338 			    "words 0x%x.\n", risc_addr, wlen);
8339 
8340 			for (i = 0; i < wlen; i++)
8341 				wcode[i] = swab16((__force u32)fwcode[i]);
8342 
8343 			rval = qla2x00_load_ram(vha, req->dma, risc_addr,
8344 			    wlen);
8345 			if (rval) {
8346 				ql_log(ql_log_fatal, vha, 0x008a,
8347 				    "Failed to load segment %d of firmware.\n",
8348 				    fragment);
8349 				break;
8350 			}
8351 
8352 			fwcode += wlen;
8353 			risc_addr += wlen;
8354 			risc_size -= wlen;
8355 			fragment++;
8356 		}
8357 
8358 		/* Next segment. */
8359 		seg++;
8360 	}
8361 	return rval;
8362 
8363 fail_fw_integrity:
8364 	return QLA_FUNCTION_FAILED;
8365 }
8366 
8367 static int
8368 qla24xx_load_risc_blob(scsi_qla_host_t *vha, uint32_t *srisc_addr)
8369 {
8370 	int	rval;
8371 	uint templates, segments, fragment;
8372 	uint32_t *dcode;
8373 	ulong dlen;
8374 	uint32_t risc_addr, risc_size, risc_attr = 0;
8375 	ulong i;
8376 	uint j;
8377 	struct fw_blob *blob;
8378 	__be32 *fwcode;
8379 	struct qla_hw_data *ha = vha->hw;
8380 	struct req_que *req = ha->req_q_map[0];
8381 	struct fwdt *fwdt = ha->fwdt;
8382 
8383 	ql_dbg(ql_dbg_init, vha, 0x0090,
8384 	    "-> FW: Loading via request-firmware.\n");
8385 
8386 	blob = qla2x00_request_firmware(vha);
8387 	if (!blob) {
8388 		ql_log(ql_log_warn, vha, 0x0092,
8389 		    "-> Firmware file not found.\n");
8390 
8391 		return QLA_FUNCTION_FAILED;
8392 	}
8393 
8394 	fwcode = (__force __be32 *)blob->fw->data;
8395 	dcode = (__force uint32_t *)fwcode;
8396 	if (qla24xx_risc_firmware_invalid(dcode)) {
8397 		ql_log(ql_log_fatal, vha, 0x0093,
8398 		    "Unable to verify integrity of firmware image (%zd).\n",
8399 		    blob->fw->size);
8400 		ql_log(ql_log_fatal, vha, 0x0095,
8401 		    "Firmware data: %08x %08x %08x %08x.\n",
8402 		    dcode[0], dcode[1], dcode[2], dcode[3]);
8403 		return QLA_FUNCTION_FAILED;
8404 	}
8405 
8406 	dcode = (uint32_t *)req->ring;
8407 	*srisc_addr = 0;
8408 	segments = FA_RISC_CODE_SEGMENTS;
8409 	for (j = 0; j < segments; j++) {
8410 		ql_dbg(ql_dbg_init, vha, 0x0096,
8411 		    "-> Loading segment %u...\n", j);
8412 		risc_addr = be32_to_cpu(fwcode[2]);
8413 		risc_size = be32_to_cpu(fwcode[3]);
8414 
8415 		if (!*srisc_addr) {
8416 			*srisc_addr = risc_addr;
8417 			risc_attr = be32_to_cpu(fwcode[9]);
8418 		}
8419 
8420 		dlen = ha->fw_transfer_size >> 2;
8421 		for (fragment = 0; risc_size; fragment++) {
8422 			if (dlen > risc_size)
8423 				dlen = risc_size;
8424 
8425 			ql_dbg(ql_dbg_init, vha, 0x0097,
8426 			    "-> Loading fragment %u: %#x <- %#x (%#lx words)...\n",
8427 			    fragment, risc_addr,
8428 			    (uint32_t)(fwcode - (typeof(fwcode))blob->fw->data),
8429 			    dlen);
8430 
8431 			for (i = 0; i < dlen; i++)
8432 				dcode[i] = swab32((__force u32)fwcode[i]);
8433 
8434 			rval = qla2x00_load_ram(vha, req->dma, risc_addr, dlen);
8435 			if (rval) {
8436 				ql_log(ql_log_fatal, vha, 0x0098,
8437 				    "-> Failed load firmware fragment %u.\n",
8438 				    fragment);
8439 				return QLA_FUNCTION_FAILED;
8440 			}
8441 
8442 			fwcode += dlen;
8443 			risc_addr += dlen;
8444 			risc_size -= dlen;
8445 		}
8446 	}
8447 
8448 	if (!IS_QLA27XX(ha) && !IS_QLA28XX(ha))
8449 		return QLA_SUCCESS;
8450 
8451 	templates = (risc_attr & BIT_9) ? 2 : 1;
8452 	ql_dbg(ql_dbg_init, vha, 0x0170, "-> templates = %u\n", templates);
8453 	for (j = 0; j < templates; j++, fwdt++) {
8454 		vfree(fwdt->template);
8455 		fwdt->template = NULL;
8456 		fwdt->length = 0;
8457 
8458 		risc_size = be32_to_cpu(fwcode[2]);
8459 		ql_dbg(ql_dbg_init, vha, 0x0171,
8460 		    "-> fwdt%u template array at %#x (%#x dwords)\n",
8461 		    j, (uint32_t)((void *)fwcode - (void *)blob->fw->data),
8462 		    risc_size);
8463 		if (!risc_size || !~risc_size) {
8464 			ql_dbg(ql_dbg_init, vha, 0x0172,
8465 			    "-> fwdt%u failed to read array\n", j);
8466 			goto failed;
8467 		}
8468 
8469 		/* skip header and ignore checksum */
8470 		fwcode += 7;
8471 		risc_size -= 8;
8472 
8473 		ql_dbg(ql_dbg_init, vha, 0x0173,
8474 		    "-> fwdt%u template allocate template %#x words...\n",
8475 		    j, risc_size);
8476 		fwdt->template = vmalloc(risc_size * sizeof(*dcode));
8477 		if (!fwdt->template) {
8478 			ql_log(ql_log_warn, vha, 0x0174,
8479 			    "-> fwdt%u failed allocate template.\n", j);
8480 			goto failed;
8481 		}
8482 
8483 		dcode = fwdt->template;
8484 		for (i = 0; i < risc_size; i++)
8485 			dcode[i] = (__force u32)fwcode[i];
8486 
8487 		if (!qla27xx_fwdt_template_valid(dcode)) {
8488 			ql_log(ql_log_warn, vha, 0x0175,
8489 			    "-> fwdt%u failed template validate\n", j);
8490 			goto failed;
8491 		}
8492 
8493 		dlen = qla27xx_fwdt_template_size(dcode);
8494 		ql_dbg(ql_dbg_init, vha, 0x0176,
8495 		    "-> fwdt%u template size %#lx bytes (%#lx words)\n",
8496 		    j, dlen, dlen / sizeof(*dcode));
8497 		if (dlen > risc_size * sizeof(*dcode)) {
8498 			ql_log(ql_log_warn, vha, 0x0177,
8499 			    "-> fwdt%u template exceeds array (%-lu bytes)\n",
8500 			    j, dlen - risc_size * sizeof(*dcode));
8501 			goto failed;
8502 		}
8503 
8504 		fwdt->length = dlen;
8505 		ql_dbg(ql_dbg_init, vha, 0x0178,
8506 		    "-> fwdt%u loaded template ok\n", j);
8507 
8508 		fwcode += risc_size + 1;
8509 	}
8510 
8511 	return QLA_SUCCESS;
8512 
8513 failed:
8514 	vfree(fwdt->template);
8515 	fwdt->template = NULL;
8516 	fwdt->length = 0;
8517 
8518 	return QLA_SUCCESS;
8519 }
8520 
8521 int
8522 qla24xx_load_risc(scsi_qla_host_t *vha, uint32_t *srisc_addr)
8523 {
8524 	int rval;
8525 
8526 	if (ql2xfwloadbin == 1)
8527 		return qla81xx_load_risc(vha, srisc_addr);
8528 
8529 	/*
8530 	 * FW Load priority:
8531 	 * 1) Firmware via request-firmware interface (.bin file).
8532 	 * 2) Firmware residing in flash.
8533 	 */
8534 	rval = qla24xx_load_risc_blob(vha, srisc_addr);
8535 	if (rval == QLA_SUCCESS)
8536 		return rval;
8537 
8538 	return qla24xx_load_risc_flash(vha, srisc_addr,
8539 	    vha->hw->flt_region_fw);
8540 }
8541 
8542 int
8543 qla81xx_load_risc(scsi_qla_host_t *vha, uint32_t *srisc_addr)
8544 {
8545 	int rval;
8546 	struct qla_hw_data *ha = vha->hw;
8547 	struct active_regions active_regions = { };
8548 
8549 	if (ql2xfwloadbin == 2)
8550 		goto try_blob_fw;
8551 
8552 	/* FW Load priority:
8553 	 * 1) Firmware residing in flash.
8554 	 * 2) Firmware via request-firmware interface (.bin file).
8555 	 * 3) Golden-Firmware residing in flash -- (limited operation).
8556 	 */
8557 
8558 	if (!IS_QLA27XX(ha) && !IS_QLA28XX(ha))
8559 		goto try_primary_fw;
8560 
8561 	qla27xx_get_active_image(vha, &active_regions);
8562 
8563 	if (active_regions.global != QLA27XX_SECONDARY_IMAGE)
8564 		goto try_primary_fw;
8565 
8566 	ql_dbg(ql_dbg_init, vha, 0x008b,
8567 	    "Loading secondary firmware image.\n");
8568 	rval = qla24xx_load_risc_flash(vha, srisc_addr, ha->flt_region_fw_sec);
8569 	if (!rval)
8570 		return rval;
8571 
8572 try_primary_fw:
8573 	ql_dbg(ql_dbg_init, vha, 0x008b,
8574 	    "Loading primary firmware image.\n");
8575 	rval = qla24xx_load_risc_flash(vha, srisc_addr, ha->flt_region_fw);
8576 	if (!rval)
8577 		return rval;
8578 
8579 try_blob_fw:
8580 	rval = qla24xx_load_risc_blob(vha, srisc_addr);
8581 	if (!rval || !ha->flt_region_gold_fw)
8582 		return rval;
8583 
8584 	ql_log(ql_log_info, vha, 0x0099,
8585 	    "Attempting to fallback to golden firmware.\n");
8586 	rval = qla24xx_load_risc_flash(vha, srisc_addr, ha->flt_region_gold_fw);
8587 	if (rval)
8588 		return rval;
8589 
8590 	ql_log(ql_log_info, vha, 0x009a, "Need firmware flash update.\n");
8591 	ha->flags.running_gold_fw = 1;
8592 	return rval;
8593 }
8594 
8595 void
8596 qla2x00_try_to_stop_firmware(scsi_qla_host_t *vha)
8597 {
8598 	int ret, retries;
8599 	struct qla_hw_data *ha = vha->hw;
8600 
8601 	if (ha->flags.pci_channel_io_perm_failure)
8602 		return;
8603 	if (!IS_FWI2_CAPABLE(ha))
8604 		return;
8605 	if (!ha->fw_major_version)
8606 		return;
8607 	if (!ha->flags.fw_started)
8608 		return;
8609 
8610 	ret = qla2x00_stop_firmware(vha);
8611 	for (retries = 5; ret != QLA_SUCCESS && ret != QLA_FUNCTION_TIMEOUT &&
8612 	    ret != QLA_INVALID_COMMAND && retries ; retries--) {
8613 		ha->isp_ops->reset_chip(vha);
8614 		if (ha->isp_ops->chip_diag(vha) != QLA_SUCCESS)
8615 			continue;
8616 		if (qla2x00_setup_chip(vha) != QLA_SUCCESS)
8617 			continue;
8618 		ql_log(ql_log_info, vha, 0x8015,
8619 		    "Attempting retry of stop-firmware command.\n");
8620 		ret = qla2x00_stop_firmware(vha);
8621 	}
8622 
8623 	QLA_FW_STOPPED(ha);
8624 	ha->flags.fw_init_done = 0;
8625 }
8626 
8627 int
8628 qla24xx_configure_vhba(scsi_qla_host_t *vha)
8629 {
8630 	int rval = QLA_SUCCESS;
8631 	int rval2;
8632 	uint16_t mb[MAILBOX_REGISTER_COUNT];
8633 	struct qla_hw_data *ha = vha->hw;
8634 	struct scsi_qla_host *base_vha = pci_get_drvdata(ha->pdev);
8635 
8636 	if (!vha->vp_idx)
8637 		return -EINVAL;
8638 
8639 	rval = qla2x00_fw_ready(base_vha);
8640 
8641 	if (rval == QLA_SUCCESS) {
8642 		clear_bit(RESET_MARKER_NEEDED, &vha->dpc_flags);
8643 		qla2x00_marker(vha, ha->base_qpair, 0, 0, MK_SYNC_ALL);
8644 	}
8645 
8646 	vha->flags.management_server_logged_in = 0;
8647 
8648 	/* Login to SNS first */
8649 	rval2 = ha->isp_ops->fabric_login(vha, NPH_SNS, 0xff, 0xff, 0xfc, mb,
8650 	    BIT_1);
8651 	if (rval2 != QLA_SUCCESS || mb[0] != MBS_COMMAND_COMPLETE) {
8652 		if (rval2 == QLA_MEMORY_ALLOC_FAILED)
8653 			ql_dbg(ql_dbg_init, vha, 0x0120,
8654 			    "Failed SNS login: loop_id=%x, rval2=%d\n",
8655 			    NPH_SNS, rval2);
8656 		else
8657 			ql_dbg(ql_dbg_init, vha, 0x0103,
8658 			    "Failed SNS login: loop_id=%x mb[0]=%x mb[1]=%x "
8659 			    "mb[2]=%x mb[6]=%x mb[7]=%x.\n",
8660 			    NPH_SNS, mb[0], mb[1], mb[2], mb[6], mb[7]);
8661 		return (QLA_FUNCTION_FAILED);
8662 	}
8663 
8664 	atomic_set(&vha->loop_down_timer, 0);
8665 	atomic_set(&vha->loop_state, LOOP_UP);
8666 	set_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags);
8667 	set_bit(LOCAL_LOOP_UPDATE, &vha->dpc_flags);
8668 	rval = qla2x00_loop_resync(base_vha);
8669 
8670 	return rval;
8671 }
8672 
8673 /* 84XX Support **************************************************************/
8674 
8675 static LIST_HEAD(qla_cs84xx_list);
8676 static DEFINE_MUTEX(qla_cs84xx_mutex);
8677 
8678 static struct qla_chip_state_84xx *
8679 qla84xx_get_chip(struct scsi_qla_host *vha)
8680 {
8681 	struct qla_chip_state_84xx *cs84xx;
8682 	struct qla_hw_data *ha = vha->hw;
8683 
8684 	mutex_lock(&qla_cs84xx_mutex);
8685 
8686 	/* Find any shared 84xx chip. */
8687 	list_for_each_entry(cs84xx, &qla_cs84xx_list, list) {
8688 		if (cs84xx->bus == ha->pdev->bus) {
8689 			kref_get(&cs84xx->kref);
8690 			goto done;
8691 		}
8692 	}
8693 
8694 	cs84xx = kzalloc(sizeof(*cs84xx), GFP_KERNEL);
8695 	if (!cs84xx)
8696 		goto done;
8697 
8698 	kref_init(&cs84xx->kref);
8699 	spin_lock_init(&cs84xx->access_lock);
8700 	mutex_init(&cs84xx->fw_update_mutex);
8701 	cs84xx->bus = ha->pdev->bus;
8702 
8703 	list_add_tail(&cs84xx->list, &qla_cs84xx_list);
8704 done:
8705 	mutex_unlock(&qla_cs84xx_mutex);
8706 	return cs84xx;
8707 }
8708 
8709 static void
8710 __qla84xx_chip_release(struct kref *kref)
8711 {
8712 	struct qla_chip_state_84xx *cs84xx =
8713 	    container_of(kref, struct qla_chip_state_84xx, kref);
8714 
8715 	mutex_lock(&qla_cs84xx_mutex);
8716 	list_del(&cs84xx->list);
8717 	mutex_unlock(&qla_cs84xx_mutex);
8718 	kfree(cs84xx);
8719 }
8720 
8721 void
8722 qla84xx_put_chip(struct scsi_qla_host *vha)
8723 {
8724 	struct qla_hw_data *ha = vha->hw;
8725 
8726 	if (ha->cs84xx)
8727 		kref_put(&ha->cs84xx->kref, __qla84xx_chip_release);
8728 }
8729 
8730 static int
8731 qla84xx_init_chip(scsi_qla_host_t *vha)
8732 {
8733 	int rval;
8734 	uint16_t status[2];
8735 	struct qla_hw_data *ha = vha->hw;
8736 
8737 	mutex_lock(&ha->cs84xx->fw_update_mutex);
8738 
8739 	rval = qla84xx_verify_chip(vha, status);
8740 
8741 	mutex_unlock(&ha->cs84xx->fw_update_mutex);
8742 
8743 	return rval != QLA_SUCCESS || status[0] ? QLA_FUNCTION_FAILED :
8744 	    QLA_SUCCESS;
8745 }
8746 
8747 /* 81XX Support **************************************************************/
8748 
8749 int
8750 qla81xx_nvram_config(scsi_qla_host_t *vha)
8751 {
8752 	int   rval;
8753 	struct init_cb_81xx *icb;
8754 	struct nvram_81xx *nv;
8755 	__le32 *dptr;
8756 	uint8_t  *dptr1, *dptr2;
8757 	uint32_t chksum;
8758 	uint16_t cnt;
8759 	struct qla_hw_data *ha = vha->hw;
8760 	uint32_t faddr;
8761 	struct active_regions active_regions = { };
8762 
8763 	rval = QLA_SUCCESS;
8764 	icb = (struct init_cb_81xx *)ha->init_cb;
8765 	nv = ha->nvram;
8766 
8767 	/* Determine NVRAM starting address. */
8768 	ha->nvram_size = sizeof(*nv);
8769 	ha->vpd_size = FA_NVRAM_VPD_SIZE;
8770 	if (IS_P3P_TYPE(ha) || IS_QLA8031(ha))
8771 		ha->vpd_size = FA_VPD_SIZE_82XX;
8772 
8773 	if (IS_QLA28XX(ha) || IS_QLA27XX(ha))
8774 		qla28xx_get_aux_images(vha, &active_regions);
8775 
8776 	/* Get VPD data into cache */
8777 	ha->vpd = ha->nvram + VPD_OFFSET;
8778 
8779 	faddr = ha->flt_region_vpd;
8780 	if (IS_QLA28XX(ha)) {
8781 		if (active_regions.aux.vpd_nvram == QLA27XX_SECONDARY_IMAGE)
8782 			faddr = ha->flt_region_vpd_sec;
8783 		ql_dbg(ql_dbg_init, vha, 0x0110,
8784 		    "Loading %s nvram image.\n",
8785 		    active_regions.aux.vpd_nvram == QLA27XX_PRIMARY_IMAGE ?
8786 		    "primary" : "secondary");
8787 	}
8788 	ha->isp_ops->read_optrom(vha, ha->vpd, faddr << 2, ha->vpd_size);
8789 
8790 	/* Get NVRAM data into cache and calculate checksum. */
8791 	faddr = ha->flt_region_nvram;
8792 	if (IS_QLA28XX(ha)) {
8793 		if (active_regions.aux.vpd_nvram == QLA27XX_SECONDARY_IMAGE)
8794 			faddr = ha->flt_region_nvram_sec;
8795 	}
8796 	ql_dbg(ql_dbg_init, vha, 0x0110,
8797 	    "Loading %s nvram image.\n",
8798 	    active_regions.aux.vpd_nvram == QLA27XX_PRIMARY_IMAGE ?
8799 	    "primary" : "secondary");
8800 	ha->isp_ops->read_optrom(vha, ha->nvram, faddr << 2, ha->nvram_size);
8801 
8802 	dptr = (__force __le32 *)nv;
8803 	for (cnt = 0, chksum = 0; cnt < ha->nvram_size >> 2; cnt++, dptr++)
8804 		chksum += le32_to_cpu(*dptr);
8805 
8806 	ql_dbg(ql_dbg_init + ql_dbg_buffer, vha, 0x0111,
8807 	    "Contents of NVRAM:\n");
8808 	ql_dump_buffer(ql_dbg_init + ql_dbg_buffer, vha, 0x0112,
8809 	    nv, ha->nvram_size);
8810 
8811 	/* Bad NVRAM data, set defaults parameters. */
8812 	if (chksum || memcmp("ISP ", nv->id, sizeof(nv->id)) ||
8813 	    le16_to_cpu(nv->nvram_version) < ICB_VERSION) {
8814 		/* Reset NVRAM data. */
8815 		ql_log(ql_log_info, vha, 0x0073,
8816 		    "Inconsistent NVRAM checksum=%#x id=%.4s version=%#x.\n",
8817 		    chksum, nv->id, le16_to_cpu(nv->nvram_version));
8818 		ql_dump_buffer(ql_dbg_init, vha, 0x0073, nv, sizeof(*nv));
8819 		ql_log(ql_log_info, vha, 0x0074,
8820 		    "Falling back to functioning (yet invalid -- WWPN) "
8821 		    "defaults.\n");
8822 
8823 		/*
8824 		 * Set default initialization control block.
8825 		 */
8826 		memset(nv, 0, ha->nvram_size);
8827 		nv->nvram_version = cpu_to_le16(ICB_VERSION);
8828 		nv->version = cpu_to_le16(ICB_VERSION);
8829 		nv->frame_payload_size = cpu_to_le16(2048);
8830 		nv->execution_throttle = cpu_to_le16(0xFFFF);
8831 		nv->exchange_count = cpu_to_le16(0);
8832 		nv->port_name[0] = 0x21;
8833 		nv->port_name[1] = 0x00 + ha->port_no + 1;
8834 		nv->port_name[2] = 0x00;
8835 		nv->port_name[3] = 0xe0;
8836 		nv->port_name[4] = 0x8b;
8837 		nv->port_name[5] = 0x1c;
8838 		nv->port_name[6] = 0x55;
8839 		nv->port_name[7] = 0x86;
8840 		nv->node_name[0] = 0x20;
8841 		nv->node_name[1] = 0x00;
8842 		nv->node_name[2] = 0x00;
8843 		nv->node_name[3] = 0xe0;
8844 		nv->node_name[4] = 0x8b;
8845 		nv->node_name[5] = 0x1c;
8846 		nv->node_name[6] = 0x55;
8847 		nv->node_name[7] = 0x86;
8848 		nv->login_retry_count = cpu_to_le16(8);
8849 		nv->interrupt_delay_timer = cpu_to_le16(0);
8850 		nv->login_timeout = cpu_to_le16(0);
8851 		nv->firmware_options_1 =
8852 		    cpu_to_le32(BIT_14|BIT_13|BIT_2|BIT_1);
8853 		nv->firmware_options_2 = cpu_to_le32(2 << 4);
8854 		nv->firmware_options_2 |= cpu_to_le32(BIT_12);
8855 		nv->firmware_options_3 = cpu_to_le32(2 << 13);
8856 		nv->host_p = cpu_to_le32(BIT_11|BIT_10);
8857 		nv->efi_parameters = cpu_to_le32(0);
8858 		nv->reset_delay = 5;
8859 		nv->max_luns_per_target = cpu_to_le16(128);
8860 		nv->port_down_retry_count = cpu_to_le16(30);
8861 		nv->link_down_timeout = cpu_to_le16(180);
8862 		nv->enode_mac[0] = 0x00;
8863 		nv->enode_mac[1] = 0xC0;
8864 		nv->enode_mac[2] = 0xDD;
8865 		nv->enode_mac[3] = 0x04;
8866 		nv->enode_mac[4] = 0x05;
8867 		nv->enode_mac[5] = 0x06 + ha->port_no + 1;
8868 
8869 		rval = 1;
8870 	}
8871 
8872 	if (IS_T10_PI_CAPABLE(ha))
8873 		nv->frame_payload_size &= cpu_to_le16(~7);
8874 
8875 	qlt_81xx_config_nvram_stage1(vha, nv);
8876 
8877 	/* Reset Initialization control block */
8878 	memset(icb, 0, ha->init_cb_size);
8879 
8880 	/* Copy 1st segment. */
8881 	dptr1 = (uint8_t *)icb;
8882 	dptr2 = (uint8_t *)&nv->version;
8883 	cnt = (uint8_t *)&icb->response_q_inpointer - (uint8_t *)&icb->version;
8884 	while (cnt--)
8885 		*dptr1++ = *dptr2++;
8886 
8887 	icb->login_retry_count = nv->login_retry_count;
8888 
8889 	/* Copy 2nd segment. */
8890 	dptr1 = (uint8_t *)&icb->interrupt_delay_timer;
8891 	dptr2 = (uint8_t *)&nv->interrupt_delay_timer;
8892 	cnt = (uint8_t *)&icb->reserved_5 -
8893 	    (uint8_t *)&icb->interrupt_delay_timer;
8894 	while (cnt--)
8895 		*dptr1++ = *dptr2++;
8896 
8897 	memcpy(icb->enode_mac, nv->enode_mac, sizeof(icb->enode_mac));
8898 	/* Some boards (with valid NVRAMs) still have NULL enode_mac!! */
8899 	if (!memcmp(icb->enode_mac, "\0\0\0\0\0\0", sizeof(icb->enode_mac))) {
8900 		icb->enode_mac[0] = 0x00;
8901 		icb->enode_mac[1] = 0xC0;
8902 		icb->enode_mac[2] = 0xDD;
8903 		icb->enode_mac[3] = 0x04;
8904 		icb->enode_mac[4] = 0x05;
8905 		icb->enode_mac[5] = 0x06 + ha->port_no + 1;
8906 	}
8907 
8908 	/* Use extended-initialization control block. */
8909 	memcpy(ha->ex_init_cb, &nv->ex_version, sizeof(*ha->ex_init_cb));
8910 	ha->frame_payload_size = le16_to_cpu(icb->frame_payload_size);
8911 	/*
8912 	 * Setup driver NVRAM options.
8913 	 */
8914 	qla2x00_set_model_info(vha, nv->model_name, sizeof(nv->model_name),
8915 	    "QLE8XXX");
8916 
8917 	qlt_81xx_config_nvram_stage2(vha, icb);
8918 
8919 	/* Use alternate WWN? */
8920 	if (nv->host_p & cpu_to_le32(BIT_15)) {
8921 		memcpy(icb->node_name, nv->alternate_node_name, WWN_SIZE);
8922 		memcpy(icb->port_name, nv->alternate_port_name, WWN_SIZE);
8923 	}
8924 
8925 	/* Prepare nodename */
8926 	if ((icb->firmware_options_1 & cpu_to_le32(BIT_14)) == 0) {
8927 		/*
8928 		 * Firmware will apply the following mask if the nodename was
8929 		 * not provided.
8930 		 */
8931 		memcpy(icb->node_name, icb->port_name, WWN_SIZE);
8932 		icb->node_name[0] &= 0xF0;
8933 	}
8934 
8935 	if (IS_QLA28XX(ha) || IS_QLA27XX(ha)) {
8936 		if ((nv->enhanced_features & BIT_7) == 0)
8937 			ha->flags.scm_supported_a = 1;
8938 	}
8939 
8940 	/* Set host adapter parameters. */
8941 	ha->flags.disable_risc_code_load = 0;
8942 	ha->flags.enable_lip_reset = 0;
8943 	ha->flags.enable_lip_full_login =
8944 	    le32_to_cpu(nv->host_p) & BIT_10 ? 1 : 0;
8945 	ha->flags.enable_target_reset =
8946 	    le32_to_cpu(nv->host_p) & BIT_11 ? 1 : 0;
8947 	ha->flags.enable_led_scheme = 0;
8948 	ha->flags.disable_serdes = le32_to_cpu(nv->host_p) & BIT_5 ? 1 : 0;
8949 
8950 	ha->operating_mode = (le32_to_cpu(icb->firmware_options_2) &
8951 	    (BIT_6 | BIT_5 | BIT_4)) >> 4;
8952 
8953 	/* save HBA serial number */
8954 	ha->serial0 = icb->port_name[5];
8955 	ha->serial1 = icb->port_name[6];
8956 	ha->serial2 = icb->port_name[7];
8957 	memcpy(vha->node_name, icb->node_name, WWN_SIZE);
8958 	memcpy(vha->port_name, icb->port_name, WWN_SIZE);
8959 
8960 	icb->execution_throttle = cpu_to_le16(0xFFFF);
8961 
8962 	ha->retry_count = le16_to_cpu(nv->login_retry_count);
8963 
8964 	/* Set minimum login_timeout to 4 seconds. */
8965 	if (le16_to_cpu(nv->login_timeout) < ql2xlogintimeout)
8966 		nv->login_timeout = cpu_to_le16(ql2xlogintimeout);
8967 	if (le16_to_cpu(nv->login_timeout) < 4)
8968 		nv->login_timeout = cpu_to_le16(4);
8969 	ha->login_timeout = le16_to_cpu(nv->login_timeout);
8970 
8971 	/* Set minimum RATOV to 100 tenths of a second. */
8972 	ha->r_a_tov = 100;
8973 
8974 	ha->loop_reset_delay = nv->reset_delay;
8975 
8976 	/* Link Down Timeout = 0:
8977 	 *
8978 	 *	When Port Down timer expires we will start returning
8979 	 *	I/O's to OS with "DID_NO_CONNECT".
8980 	 *
8981 	 * Link Down Timeout != 0:
8982 	 *
8983 	 *	 The driver waits for the link to come up after link down
8984 	 *	 before returning I/Os to OS with "DID_NO_CONNECT".
8985 	 */
8986 	if (le16_to_cpu(nv->link_down_timeout) == 0) {
8987 		ha->loop_down_abort_time =
8988 		    (LOOP_DOWN_TIME - LOOP_DOWN_TIMEOUT);
8989 	} else {
8990 		ha->link_down_timeout =	le16_to_cpu(nv->link_down_timeout);
8991 		ha->loop_down_abort_time =
8992 		    (LOOP_DOWN_TIME - ha->link_down_timeout);
8993 	}
8994 
8995 	/* Need enough time to try and get the port back. */
8996 	ha->port_down_retry_count = le16_to_cpu(nv->port_down_retry_count);
8997 	if (qlport_down_retry)
8998 		ha->port_down_retry_count = qlport_down_retry;
8999 
9000 	/* Set login_retry_count */
9001 	ha->login_retry_count  = le16_to_cpu(nv->login_retry_count);
9002 	if (ha->port_down_retry_count ==
9003 	    le16_to_cpu(nv->port_down_retry_count) &&
9004 	    ha->port_down_retry_count > 3)
9005 		ha->login_retry_count = ha->port_down_retry_count;
9006 	else if (ha->port_down_retry_count > (int)ha->login_retry_count)
9007 		ha->login_retry_count = ha->port_down_retry_count;
9008 	if (ql2xloginretrycount)
9009 		ha->login_retry_count = ql2xloginretrycount;
9010 
9011 	/* if not running MSI-X we need handshaking on interrupts */
9012 	if (!vha->hw->flags.msix_enabled &&
9013 	    (IS_QLA83XX(ha) || IS_QLA27XX(ha) || IS_QLA28XX(ha)))
9014 		icb->firmware_options_2 |= cpu_to_le32(BIT_22);
9015 
9016 	/* Enable ZIO. */
9017 	if (!vha->flags.init_done) {
9018 		ha->zio_mode = le32_to_cpu(icb->firmware_options_2) &
9019 		    (BIT_3 | BIT_2 | BIT_1 | BIT_0);
9020 		ha->zio_timer = le16_to_cpu(icb->interrupt_delay_timer) ?
9021 		    le16_to_cpu(icb->interrupt_delay_timer) : 2;
9022 	}
9023 	icb->firmware_options_2 &= cpu_to_le32(
9024 	    ~(BIT_3 | BIT_2 | BIT_1 | BIT_0));
9025 	vha->flags.process_response_queue = 0;
9026 	if (ha->zio_mode != QLA_ZIO_DISABLED) {
9027 		ha->zio_mode = QLA_ZIO_MODE_6;
9028 
9029 		ql_log(ql_log_info, vha, 0x0075,
9030 		    "ZIO mode %d enabled; timer delay (%d us).\n",
9031 		    ha->zio_mode,
9032 		    ha->zio_timer * 100);
9033 
9034 		icb->firmware_options_2 |= cpu_to_le32(
9035 		    (uint32_t)ha->zio_mode);
9036 		icb->interrupt_delay_timer = cpu_to_le16(ha->zio_timer);
9037 		vha->flags.process_response_queue = 1;
9038 	}
9039 
9040 	 /* enable RIDA Format2 */
9041 	icb->firmware_options_3 |= cpu_to_le32(BIT_0);
9042 
9043 	/* N2N: driver will initiate Login instead of FW */
9044 	icb->firmware_options_3 |= cpu_to_le32(BIT_8);
9045 
9046 	/* Determine NVMe/FCP priority for target ports */
9047 	ha->fc4_type_priority = qla2xxx_get_fc4_priority(vha);
9048 
9049 	if (rval) {
9050 		ql_log(ql_log_warn, vha, 0x0076,
9051 		    "NVRAM configuration failed.\n");
9052 	}
9053 	return (rval);
9054 }
9055 
9056 int
9057 qla82xx_restart_isp(scsi_qla_host_t *vha)
9058 {
9059 	int status, rval;
9060 	struct qla_hw_data *ha = vha->hw;
9061 	struct scsi_qla_host *vp, *tvp;
9062 	unsigned long flags;
9063 
9064 	status = qla2x00_init_rings(vha);
9065 	if (!status) {
9066 		clear_bit(RESET_MARKER_NEEDED, &vha->dpc_flags);
9067 		ha->flags.chip_reset_done = 1;
9068 
9069 		status = qla2x00_fw_ready(vha);
9070 		if (!status) {
9071 			/* Issue a marker after FW becomes ready. */
9072 			qla2x00_marker(vha, ha->base_qpair, 0, 0, MK_SYNC_ALL);
9073 			vha->flags.online = 1;
9074 			set_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags);
9075 		}
9076 
9077 		/* if no cable then assume it's good */
9078 		if ((vha->device_flags & DFLG_NO_CABLE))
9079 			status = 0;
9080 	}
9081 
9082 	if (!status) {
9083 		clear_bit(RESET_MARKER_NEEDED, &vha->dpc_flags);
9084 
9085 		if (!atomic_read(&vha->loop_down_timer)) {
9086 			/*
9087 			 * Issue marker command only when we are going
9088 			 * to start the I/O .
9089 			 */
9090 			vha->marker_needed = 1;
9091 		}
9092 
9093 		ha->isp_ops->enable_intrs(ha);
9094 
9095 		ha->isp_abort_cnt = 0;
9096 		clear_bit(ISP_ABORT_RETRY, &vha->dpc_flags);
9097 
9098 		/* Update the firmware version */
9099 		status = qla82xx_check_md_needed(vha);
9100 
9101 		if (ha->fce) {
9102 			ha->flags.fce_enabled = 1;
9103 			memset(ha->fce, 0,
9104 			    fce_calc_size(ha->fce_bufs));
9105 			rval = qla2x00_enable_fce_trace(vha,
9106 			    ha->fce_dma, ha->fce_bufs, ha->fce_mb,
9107 			    &ha->fce_bufs);
9108 			if (rval) {
9109 				ql_log(ql_log_warn, vha, 0x8001,
9110 				    "Unable to reinitialize FCE (%d).\n",
9111 				    rval);
9112 				ha->flags.fce_enabled = 0;
9113 			}
9114 		}
9115 
9116 		if (ha->eft) {
9117 			memset(ha->eft, 0, EFT_SIZE);
9118 			rval = qla2x00_enable_eft_trace(vha,
9119 			    ha->eft_dma, EFT_NUM_BUFFERS);
9120 			if (rval) {
9121 				ql_log(ql_log_warn, vha, 0x8010,
9122 				    "Unable to reinitialize EFT (%d).\n",
9123 				    rval);
9124 			}
9125 		}
9126 	}
9127 
9128 	if (!status) {
9129 		ql_dbg(ql_dbg_taskm, vha, 0x8011,
9130 		    "qla82xx_restart_isp succeeded.\n");
9131 
9132 		spin_lock_irqsave(&ha->vport_slock, flags);
9133 		list_for_each_entry_safe(vp, tvp, &ha->vp_list, list) {
9134 			if (vp->vp_idx) {
9135 				atomic_inc(&vp->vref_count);
9136 				spin_unlock_irqrestore(&ha->vport_slock, flags);
9137 
9138 				qla2x00_vp_abort_isp(vp);
9139 
9140 				spin_lock_irqsave(&ha->vport_slock, flags);
9141 				atomic_dec(&vp->vref_count);
9142 			}
9143 		}
9144 		spin_unlock_irqrestore(&ha->vport_slock, flags);
9145 
9146 	} else {
9147 		ql_log(ql_log_warn, vha, 0x8016,
9148 		    "qla82xx_restart_isp **** FAILED ****.\n");
9149 	}
9150 
9151 	return status;
9152 }
9153 
9154 /*
9155  * qla24xx_get_fcp_prio
9156  *	Gets the fcp cmd priority value for the logged in port.
9157  *	Looks for a match of the port descriptors within
9158  *	each of the fcp prio config entries. If a match is found,
9159  *	the tag (priority) value is returned.
9160  *
9161  * Input:
9162  *	vha = scsi host structure pointer.
9163  *	fcport = port structure pointer.
9164  *
9165  * Return:
9166  *	non-zero (if found)
9167  *	-1 (if not found)
9168  *
9169  * Context:
9170  * 	Kernel context
9171  */
9172 static int
9173 qla24xx_get_fcp_prio(scsi_qla_host_t *vha, fc_port_t *fcport)
9174 {
9175 	int i, entries;
9176 	uint8_t pid_match, wwn_match;
9177 	int priority;
9178 	uint32_t pid1, pid2;
9179 	uint64_t wwn1, wwn2;
9180 	struct qla_fcp_prio_entry *pri_entry;
9181 	struct qla_hw_data *ha = vha->hw;
9182 
9183 	if (!ha->fcp_prio_cfg || !ha->flags.fcp_prio_enabled)
9184 		return -1;
9185 
9186 	priority = -1;
9187 	entries = ha->fcp_prio_cfg->num_entries;
9188 	pri_entry = &ha->fcp_prio_cfg->entry[0];
9189 
9190 	for (i = 0; i < entries; i++) {
9191 		pid_match = wwn_match = 0;
9192 
9193 		if (!(pri_entry->flags & FCP_PRIO_ENTRY_VALID)) {
9194 			pri_entry++;
9195 			continue;
9196 		}
9197 
9198 		/* check source pid for a match */
9199 		if (pri_entry->flags & FCP_PRIO_ENTRY_SPID_VALID) {
9200 			pid1 = pri_entry->src_pid & INVALID_PORT_ID;
9201 			pid2 = vha->d_id.b24 & INVALID_PORT_ID;
9202 			if (pid1 == INVALID_PORT_ID)
9203 				pid_match++;
9204 			else if (pid1 == pid2)
9205 				pid_match++;
9206 		}
9207 
9208 		/* check destination pid for a match */
9209 		if (pri_entry->flags & FCP_PRIO_ENTRY_DPID_VALID) {
9210 			pid1 = pri_entry->dst_pid & INVALID_PORT_ID;
9211 			pid2 = fcport->d_id.b24 & INVALID_PORT_ID;
9212 			if (pid1 == INVALID_PORT_ID)
9213 				pid_match++;
9214 			else if (pid1 == pid2)
9215 				pid_match++;
9216 		}
9217 
9218 		/* check source WWN for a match */
9219 		if (pri_entry->flags & FCP_PRIO_ENTRY_SWWN_VALID) {
9220 			wwn1 = wwn_to_u64(vha->port_name);
9221 			wwn2 = wwn_to_u64(pri_entry->src_wwpn);
9222 			if (wwn2 == (uint64_t)-1)
9223 				wwn_match++;
9224 			else if (wwn1 == wwn2)
9225 				wwn_match++;
9226 		}
9227 
9228 		/* check destination WWN for a match */
9229 		if (pri_entry->flags & FCP_PRIO_ENTRY_DWWN_VALID) {
9230 			wwn1 = wwn_to_u64(fcport->port_name);
9231 			wwn2 = wwn_to_u64(pri_entry->dst_wwpn);
9232 			if (wwn2 == (uint64_t)-1)
9233 				wwn_match++;
9234 			else if (wwn1 == wwn2)
9235 				wwn_match++;
9236 		}
9237 
9238 		if (pid_match == 2 || wwn_match == 2) {
9239 			/* Found a matching entry */
9240 			if (pri_entry->flags & FCP_PRIO_ENTRY_TAG_VALID)
9241 				priority = pri_entry->tag;
9242 			break;
9243 		}
9244 
9245 		pri_entry++;
9246 	}
9247 
9248 	return priority;
9249 }
9250 
9251 /*
9252  * qla24xx_update_fcport_fcp_prio
9253  *	Activates fcp priority for the logged in fc port
9254  *
9255  * Input:
9256  *	vha = scsi host structure pointer.
9257  *	fcp = port structure pointer.
9258  *
9259  * Return:
9260  *	QLA_SUCCESS or QLA_FUNCTION_FAILED
9261  *
9262  * Context:
9263  *	Kernel context.
9264  */
9265 int
9266 qla24xx_update_fcport_fcp_prio(scsi_qla_host_t *vha, fc_port_t *fcport)
9267 {
9268 	int ret;
9269 	int priority;
9270 	uint16_t mb[5];
9271 
9272 	if (fcport->port_type != FCT_TARGET ||
9273 	    fcport->loop_id == FC_NO_LOOP_ID)
9274 		return QLA_FUNCTION_FAILED;
9275 
9276 	priority = qla24xx_get_fcp_prio(vha, fcport);
9277 	if (priority < 0)
9278 		return QLA_FUNCTION_FAILED;
9279 
9280 	if (IS_P3P_TYPE(vha->hw)) {
9281 		fcport->fcp_prio = priority & 0xf;
9282 		return QLA_SUCCESS;
9283 	}
9284 
9285 	ret = qla24xx_set_fcp_prio(vha, fcport->loop_id, priority, mb);
9286 	if (ret == QLA_SUCCESS) {
9287 		if (fcport->fcp_prio != priority)
9288 			ql_dbg(ql_dbg_user, vha, 0x709e,
9289 			    "Updated FCP_CMND priority - value=%d loop_id=%d "
9290 			    "port_id=%02x%02x%02x.\n", priority,
9291 			    fcport->loop_id, fcport->d_id.b.domain,
9292 			    fcport->d_id.b.area, fcport->d_id.b.al_pa);
9293 		fcport->fcp_prio = priority & 0xf;
9294 	} else
9295 		ql_dbg(ql_dbg_user, vha, 0x704f,
9296 		    "Unable to update FCP_CMND priority - ret=0x%x for "
9297 		    "loop_id=%d port_id=%02x%02x%02x.\n", ret, fcport->loop_id,
9298 		    fcport->d_id.b.domain, fcport->d_id.b.area,
9299 		    fcport->d_id.b.al_pa);
9300 	return  ret;
9301 }
9302 
9303 /*
9304  * qla24xx_update_all_fcp_prio
9305  *	Activates fcp priority for all the logged in ports
9306  *
9307  * Input:
9308  *	ha = adapter block pointer.
9309  *
9310  * Return:
9311  *	QLA_SUCCESS or QLA_FUNCTION_FAILED
9312  *
9313  * Context:
9314  *	Kernel context.
9315  */
9316 int
9317 qla24xx_update_all_fcp_prio(scsi_qla_host_t *vha)
9318 {
9319 	int ret;
9320 	fc_port_t *fcport;
9321 
9322 	ret = QLA_FUNCTION_FAILED;
9323 	/* We need to set priority for all logged in ports */
9324 	list_for_each_entry(fcport, &vha->vp_fcports, list)
9325 		ret = qla24xx_update_fcport_fcp_prio(vha, fcport);
9326 
9327 	return ret;
9328 }
9329 
9330 struct qla_qpair *qla2xxx_create_qpair(struct scsi_qla_host *vha, int qos,
9331 	int vp_idx, bool startqp)
9332 {
9333 	int rsp_id = 0;
9334 	int  req_id = 0;
9335 	int i;
9336 	struct qla_hw_data *ha = vha->hw;
9337 	uint16_t qpair_id = 0;
9338 	struct qla_qpair *qpair = NULL;
9339 	struct qla_msix_entry *msix;
9340 
9341 	if (!(ha->fw_attributes & BIT_6) || !ha->flags.msix_enabled) {
9342 		ql_log(ql_log_warn, vha, 0x00181,
9343 		    "FW/Driver is not multi-queue capable.\n");
9344 		return NULL;
9345 	}
9346 
9347 	if (ql2xmqsupport || ql2xnvmeenable) {
9348 		qpair = kzalloc(sizeof(struct qla_qpair), GFP_KERNEL);
9349 		if (qpair == NULL) {
9350 			ql_log(ql_log_warn, vha, 0x0182,
9351 			    "Failed to allocate memory for queue pair.\n");
9352 			return NULL;
9353 		}
9354 
9355 		qpair->hw = vha->hw;
9356 		qpair->vha = vha;
9357 		qpair->qp_lock_ptr = &qpair->qp_lock;
9358 		spin_lock_init(&qpair->qp_lock);
9359 		qpair->use_shadow_reg = IS_SHADOW_REG_CAPABLE(ha) ? 1 : 0;
9360 
9361 		/* Assign available que pair id */
9362 		mutex_lock(&ha->mq_lock);
9363 		qpair_id = find_first_zero_bit(ha->qpair_qid_map, ha->max_qpairs);
9364 		if (ha->num_qpairs >= ha->max_qpairs) {
9365 			mutex_unlock(&ha->mq_lock);
9366 			ql_log(ql_log_warn, vha, 0x0183,
9367 			    "No resources to create additional q pair.\n");
9368 			goto fail_qid_map;
9369 		}
9370 		ha->num_qpairs++;
9371 		set_bit(qpair_id, ha->qpair_qid_map);
9372 		ha->queue_pair_map[qpair_id] = qpair;
9373 		qpair->id = qpair_id;
9374 		qpair->vp_idx = vp_idx;
9375 		qpair->fw_started = ha->flags.fw_started;
9376 		INIT_LIST_HEAD(&qpair->hints_list);
9377 		qpair->chip_reset = ha->base_qpair->chip_reset;
9378 		qpair->enable_class_2 = ha->base_qpair->enable_class_2;
9379 		qpair->enable_explicit_conf =
9380 		    ha->base_qpair->enable_explicit_conf;
9381 
9382 		for (i = 0; i < ha->msix_count; i++) {
9383 			msix = &ha->msix_entries[i];
9384 			if (msix->in_use)
9385 				continue;
9386 			qpair->msix = msix;
9387 			ql_dbg(ql_dbg_multiq, vha, 0xc00f,
9388 			    "Vector %x selected for qpair\n", msix->vector);
9389 			break;
9390 		}
9391 		if (!qpair->msix) {
9392 			ql_log(ql_log_warn, vha, 0x0184,
9393 			    "Out of MSI-X vectors!.\n");
9394 			goto fail_msix;
9395 		}
9396 
9397 		qpair->msix->in_use = 1;
9398 		list_add_tail(&qpair->qp_list_elem, &vha->qp_list);
9399 		qpair->pdev = ha->pdev;
9400 		if (IS_QLA27XX(ha) || IS_QLA83XX(ha) || IS_QLA28XX(ha))
9401 			qpair->reqq_start_iocbs = qla_83xx_start_iocbs;
9402 
9403 		mutex_unlock(&ha->mq_lock);
9404 
9405 		/* Create response queue first */
9406 		rsp_id = qla25xx_create_rsp_que(ha, 0, 0, 0, qpair, startqp);
9407 		if (!rsp_id) {
9408 			ql_log(ql_log_warn, vha, 0x0185,
9409 			    "Failed to create response queue.\n");
9410 			goto fail_rsp;
9411 		}
9412 
9413 		qpair->rsp = ha->rsp_q_map[rsp_id];
9414 
9415 		/* Create request queue */
9416 		req_id = qla25xx_create_req_que(ha, 0, vp_idx, 0, rsp_id, qos,
9417 		    startqp);
9418 		if (!req_id) {
9419 			ql_log(ql_log_warn, vha, 0x0186,
9420 			    "Failed to create request queue.\n");
9421 			goto fail_req;
9422 		}
9423 
9424 		qpair->req = ha->req_q_map[req_id];
9425 		qpair->rsp->req = qpair->req;
9426 		qpair->rsp->qpair = qpair;
9427 
9428 		if (IS_T10_PI_CAPABLE(ha) && ql2xenabledif) {
9429 			if (ha->fw_attributes & BIT_4)
9430 				qpair->difdix_supported = 1;
9431 		}
9432 
9433 		qpair->srb_mempool = mempool_create_slab_pool(SRB_MIN_REQ, srb_cachep);
9434 		if (!qpair->srb_mempool) {
9435 			ql_log(ql_log_warn, vha, 0xd036,
9436 			    "Failed to create srb mempool for qpair %d\n",
9437 			    qpair->id);
9438 			goto fail_mempool;
9439 		}
9440 
9441 		if (qla_create_buf_pool(vha, qpair)) {
9442 			ql_log(ql_log_warn, vha, 0xd036,
9443 			    "Failed to initialize buf pool for qpair %d\n",
9444 			    qpair->id);
9445 			goto fail_bufpool;
9446 		}
9447 
9448 		/* Mark as online */
9449 		qpair->online = 1;
9450 
9451 		if (!vha->flags.qpairs_available)
9452 			vha->flags.qpairs_available = 1;
9453 
9454 		ql_dbg(ql_dbg_multiq, vha, 0xc00d,
9455 		    "Request/Response queue pair created, id %d\n",
9456 		    qpair->id);
9457 		ql_dbg(ql_dbg_init, vha, 0x0187,
9458 		    "Request/Response queue pair created, id %d\n",
9459 		    qpair->id);
9460 	}
9461 	return qpair;
9462 
9463 fail_bufpool:
9464 	mempool_destroy(qpair->srb_mempool);
9465 fail_mempool:
9466 	qla25xx_delete_req_que(vha, qpair->req);
9467 fail_req:
9468 	qla25xx_delete_rsp_que(vha, qpair->rsp);
9469 fail_rsp:
9470 	mutex_lock(&ha->mq_lock);
9471 	qpair->msix->in_use = 0;
9472 	list_del(&qpair->qp_list_elem);
9473 	if (list_empty(&vha->qp_list))
9474 		vha->flags.qpairs_available = 0;
9475 fail_msix:
9476 	ha->queue_pair_map[qpair_id] = NULL;
9477 	clear_bit(qpair_id, ha->qpair_qid_map);
9478 	ha->num_qpairs--;
9479 	mutex_unlock(&ha->mq_lock);
9480 fail_qid_map:
9481 	kfree(qpair);
9482 	return NULL;
9483 }
9484 
9485 int qla2xxx_delete_qpair(struct scsi_qla_host *vha, struct qla_qpair *qpair)
9486 {
9487 	int ret = QLA_FUNCTION_FAILED;
9488 	struct qla_hw_data *ha = qpair->hw;
9489 
9490 	qpair->delete_in_progress = 1;
9491 
9492 	qla_free_buf_pool(qpair);
9493 
9494 	ret = qla25xx_delete_req_que(vha, qpair->req);
9495 	if (ret != QLA_SUCCESS)
9496 		goto fail;
9497 
9498 	ret = qla25xx_delete_rsp_que(vha, qpair->rsp);
9499 	if (ret != QLA_SUCCESS)
9500 		goto fail;
9501 
9502 	mutex_lock(&ha->mq_lock);
9503 	ha->queue_pair_map[qpair->id] = NULL;
9504 	clear_bit(qpair->id, ha->qpair_qid_map);
9505 	ha->num_qpairs--;
9506 	list_del(&qpair->qp_list_elem);
9507 	if (list_empty(&vha->qp_list)) {
9508 		vha->flags.qpairs_available = 0;
9509 		vha->flags.qpairs_req_created = 0;
9510 		vha->flags.qpairs_rsp_created = 0;
9511 	}
9512 	mempool_destroy(qpair->srb_mempool);
9513 	kfree(qpair);
9514 	mutex_unlock(&ha->mq_lock);
9515 
9516 	return QLA_SUCCESS;
9517 fail:
9518 	return ret;
9519 }
9520 
9521 uint64_t
9522 qla2x00_count_set_bits(uint32_t num)
9523 {
9524 	/* Brian Kernighan's Algorithm */
9525 	u64 count = 0;
9526 
9527 	while (num) {
9528 		num &= (num - 1);
9529 		count++;
9530 	}
9531 	return count;
9532 }
9533 
9534 uint64_t
9535 qla2x00_get_num_tgts(scsi_qla_host_t *vha)
9536 {
9537 	fc_port_t *f, *tf;
9538 	u64 count = 0;
9539 
9540 	f = NULL;
9541 	tf = NULL;
9542 
9543 	list_for_each_entry_safe(f, tf, &vha->vp_fcports, list) {
9544 		if (f->port_type != FCT_TARGET)
9545 			continue;
9546 		count++;
9547 	}
9548 	return count;
9549 }
9550 
9551 int qla2xxx_reset_stats(struct Scsi_Host *host, u32 flags)
9552 {
9553 	scsi_qla_host_t *vha = shost_priv(host);
9554 	fc_port_t *fcport = NULL;
9555 	unsigned long int_flags;
9556 
9557 	if (flags & QLA2XX_HW_ERROR)
9558 		vha->hw_err_cnt = 0;
9559 	if (flags & QLA2XX_SHT_LNK_DWN)
9560 		vha->short_link_down_cnt = 0;
9561 	if (flags & QLA2XX_INT_ERR)
9562 		vha->interface_err_cnt = 0;
9563 	if (flags & QLA2XX_CMD_TIMEOUT)
9564 		vha->cmd_timeout_cnt = 0;
9565 	if (flags & QLA2XX_RESET_CMD_ERR)
9566 		vha->reset_cmd_err_cnt = 0;
9567 	if (flags & QLA2XX_TGT_SHT_LNK_DOWN) {
9568 		spin_lock_irqsave(&vha->hw->tgt.sess_lock, int_flags);
9569 		list_for_each_entry(fcport, &vha->vp_fcports, list) {
9570 			fcport->tgt_short_link_down_cnt = 0;
9571 			fcport->tgt_link_down_time = QLA2XX_MAX_LINK_DOWN_TIME;
9572 		}
9573 		spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, int_flags);
9574 	}
9575 	vha->link_down_time = QLA2XX_MAX_LINK_DOWN_TIME;
9576 	return 0;
9577 }
9578 
9579 int qla2xxx_start_stats(struct Scsi_Host *host, u32 flags)
9580 {
9581 	return qla2xxx_reset_stats(host, flags);
9582 }
9583 
9584 int qla2xxx_stop_stats(struct Scsi_Host *host, u32 flags)
9585 {
9586 	return qla2xxx_reset_stats(host, flags);
9587 }
9588 
9589 int qla2xxx_get_ini_stats(struct Scsi_Host *host, u32 flags,
9590 			  void *data, u64 size)
9591 {
9592 	scsi_qla_host_t *vha = shost_priv(host);
9593 	struct ql_vnd_host_stats_resp *resp = (struct ql_vnd_host_stats_resp *)data;
9594 	struct ql_vnd_stats *rsp_data = &resp->stats;
9595 	u64 ini_entry_count = 0;
9596 	u64 i = 0;
9597 	u64 entry_count = 0;
9598 	u64 num_tgt = 0;
9599 	u32 tmp_stat_type = 0;
9600 	fc_port_t *fcport = NULL;
9601 	unsigned long int_flags;
9602 
9603 	/* Copy stat type to work on it */
9604 	tmp_stat_type = flags;
9605 
9606 	if (tmp_stat_type & BIT_17) {
9607 		num_tgt = qla2x00_get_num_tgts(vha);
9608 		/* unset BIT_17 */
9609 		tmp_stat_type &= ~(1 << 17);
9610 	}
9611 	ini_entry_count = qla2x00_count_set_bits(tmp_stat_type);
9612 
9613 	entry_count = ini_entry_count + num_tgt;
9614 
9615 	rsp_data->entry_count = entry_count;
9616 
9617 	i = 0;
9618 	if (flags & QLA2XX_HW_ERROR) {
9619 		rsp_data->entry[i].stat_type = QLA2XX_HW_ERROR;
9620 		rsp_data->entry[i].tgt_num = 0x0;
9621 		rsp_data->entry[i].cnt = vha->hw_err_cnt;
9622 		i++;
9623 	}
9624 
9625 	if (flags & QLA2XX_SHT_LNK_DWN) {
9626 		rsp_data->entry[i].stat_type = QLA2XX_SHT_LNK_DWN;
9627 		rsp_data->entry[i].tgt_num = 0x0;
9628 		rsp_data->entry[i].cnt = vha->short_link_down_cnt;
9629 		i++;
9630 	}
9631 
9632 	if (flags & QLA2XX_INT_ERR) {
9633 		rsp_data->entry[i].stat_type = QLA2XX_INT_ERR;
9634 		rsp_data->entry[i].tgt_num = 0x0;
9635 		rsp_data->entry[i].cnt = vha->interface_err_cnt;
9636 		i++;
9637 	}
9638 
9639 	if (flags & QLA2XX_CMD_TIMEOUT) {
9640 		rsp_data->entry[i].stat_type = QLA2XX_CMD_TIMEOUT;
9641 		rsp_data->entry[i].tgt_num = 0x0;
9642 		rsp_data->entry[i].cnt = vha->cmd_timeout_cnt;
9643 		i++;
9644 	}
9645 
9646 	if (flags & QLA2XX_RESET_CMD_ERR) {
9647 		rsp_data->entry[i].stat_type = QLA2XX_RESET_CMD_ERR;
9648 		rsp_data->entry[i].tgt_num = 0x0;
9649 		rsp_data->entry[i].cnt = vha->reset_cmd_err_cnt;
9650 		i++;
9651 	}
9652 
9653 	/* i will continue from previous loop, as target
9654 	 * entries are after initiator
9655 	 */
9656 	if (flags & QLA2XX_TGT_SHT_LNK_DOWN) {
9657 		spin_lock_irqsave(&vha->hw->tgt.sess_lock, int_flags);
9658 		list_for_each_entry(fcport, &vha->vp_fcports, list) {
9659 			if (fcport->port_type != FCT_TARGET)
9660 				continue;
9661 			if (!fcport->rport)
9662 				continue;
9663 			rsp_data->entry[i].stat_type = QLA2XX_TGT_SHT_LNK_DOWN;
9664 			rsp_data->entry[i].tgt_num = fcport->rport->number;
9665 			rsp_data->entry[i].cnt = fcport->tgt_short_link_down_cnt;
9666 			i++;
9667 		}
9668 		spin_unlock_irqrestore(&vha->hw->tgt.sess_lock, int_flags);
9669 	}
9670 	resp->status = EXT_STATUS_OK;
9671 
9672 	return 0;
9673 }
9674 
9675 int qla2xxx_get_tgt_stats(struct Scsi_Host *host, u32 flags,
9676 			  struct fc_rport *rport, void *data, u64 size)
9677 {
9678 	struct ql_vnd_tgt_stats_resp *tgt_data = data;
9679 	fc_port_t *fcport = *(fc_port_t **)rport->dd_data;
9680 
9681 	tgt_data->status = 0;
9682 	tgt_data->stats.entry_count = 1;
9683 	tgt_data->stats.entry[0].stat_type = flags;
9684 	tgt_data->stats.entry[0].tgt_num = rport->number;
9685 	tgt_data->stats.entry[0].cnt = fcport->tgt_short_link_down_cnt;
9686 
9687 	return 0;
9688 }
9689 
9690 int qla2xxx_disable_port(struct Scsi_Host *host)
9691 {
9692 	scsi_qla_host_t *vha = shost_priv(host);
9693 
9694 	vha->hw->flags.port_isolated = 1;
9695 
9696 	if (qla2x00_isp_reg_stat(vha->hw)) {
9697 		ql_log(ql_log_info, vha, 0x9006,
9698 		    "PCI/Register disconnect, exiting.\n");
9699 		qla_pci_set_eeh_busy(vha);
9700 		return FAILED;
9701 	}
9702 	if (qla2x00_chip_is_down(vha))
9703 		return 0;
9704 
9705 	if (vha->flags.online) {
9706 		qla2x00_abort_isp_cleanup(vha);
9707 		qla2x00_wait_for_sess_deletion(vha);
9708 	}
9709 
9710 	return 0;
9711 }
9712 
9713 int qla2xxx_enable_port(struct Scsi_Host *host)
9714 {
9715 	scsi_qla_host_t *vha = shost_priv(host);
9716 
9717 	if (qla2x00_isp_reg_stat(vha->hw)) {
9718 		ql_log(ql_log_info, vha, 0x9001,
9719 		    "PCI/Register disconnect, exiting.\n");
9720 		qla_pci_set_eeh_busy(vha);
9721 		return FAILED;
9722 	}
9723 
9724 	vha->hw->flags.port_isolated = 0;
9725 	/* Set the flag to 1, so that isp_abort can proceed */
9726 	vha->flags.online = 1;
9727 	set_bit(ISP_ABORT_NEEDED, &vha->dpc_flags);
9728 	qla2xxx_wake_dpc(vha);
9729 
9730 	return 0;
9731 }
9732