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