File Index
Files and directories
Sign in
FILE

lpfc_scsi.c

File preview with syntax highlighting.

linux-6.19.14/drivers/scsi/lpfc/lpfc_scsi.c C
   1/*******************************************************************
   2 * This file is part of the Emulex Linux Device Driver for         *
   3 * Fibre Channel Host Bus Adapters.                                *
   4 * Copyright (C) 2017-2025 Broadcom. All Rights Reserved. The term *
   5 * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.     *
   6 * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
   7 * EMULEX and SLI are trademarks of Emulex.                        *
   8 * www.broadcom.com                                                *
   9 * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
  10 *                                                                 *
  11 * This program is free software; you can redistribute it and/or   *
  12 * modify it under the terms of version 2 of the GNU General       *
  13 * Public License as published by the Free Software Foundation.    *
  14 * This program is distributed in the hope that it will be useful. *
  15 * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
  16 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
  17 * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
  18 * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
  19 * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
  20 * more details, a copy of which can be found in the file COPYING  *
  21 * included with this package.                                     *
  22 *******************************************************************/
  23#include <linux/pci.h>
  24#include <linux/slab.h>
  25#include <linux/interrupt.h>
  26#include <linux/export.h>
  27#include <linux/delay.h>
  28#include <linux/unaligned.h>
  29#include <linux/t10-pi.h>
  30#include <linux/crc-t10dif.h>
  31#include <linux/blk-cgroup.h>
  32#include <net/checksum.h>
  33
  34#include <scsi/scsi.h>
  35#include <scsi/scsi_device.h>
  36#include <scsi/scsi_eh.h>
  37#include <scsi/scsi_host.h>
  38#include <scsi/scsi_tcq.h>
  39#include <scsi/scsi_transport_fc.h>
  40
  41#include "lpfc_version.h"
  42#include "lpfc_hw4.h"
  43#include "lpfc_hw.h"
  44#include "lpfc_sli.h"
  45#include "lpfc_sli4.h"
  46#include "lpfc_nl.h"
  47#include "lpfc_disc.h"
  48#include "lpfc.h"
  49#include "lpfc_scsi.h"
  50#include "lpfc_logmsg.h"
  51#include "lpfc_crtn.h"
  52#include "lpfc_vport.h"
  53
  54#define LPFC_RESET_WAIT  2
  55#define LPFC_ABORT_WAIT  2
  56
  57static char *dif_op_str[] = {
  58	"PROT_NORMAL",
  59	"PROT_READ_INSERT",
  60	"PROT_WRITE_STRIP",
  61	"PROT_READ_STRIP",
  62	"PROT_WRITE_INSERT",
  63	"PROT_READ_PASS",
  64	"PROT_WRITE_PASS",
  65};
  66
  67struct scsi_dif_tuple {
  68	__be16 guard_tag;       /* Checksum */
  69	__be16 app_tag;         /* Opaque storage */
  70	__be32 ref_tag;         /* Target LBA or indirect LBA */
  71};
  72
  73static struct lpfc_rport_data *
  74lpfc_rport_data_from_scsi_device(struct scsi_device *sdev)
  75{
  76	struct lpfc_vport *vport = (struct lpfc_vport *)sdev->host->hostdata;
  77
  78	if (vport->phba->cfg_fof)
  79		return ((struct lpfc_device_data *)sdev->hostdata)->rport_data;
  80	else
  81		return (struct lpfc_rport_data *)sdev->hostdata;
  82}
  83
  84static void
  85lpfc_release_scsi_buf_s4(struct lpfc_hba *phba, struct lpfc_io_buf *psb);
  86static void
  87lpfc_release_scsi_buf_s3(struct lpfc_hba *phba, struct lpfc_io_buf *psb);
  88static int
  89lpfc_prot_group_type(struct lpfc_hba *phba, struct scsi_cmnd *sc);
  90
  91/**
  92 * lpfc_sli4_set_rsp_sgl_last - Set the last bit in the response sge.
  93 * @phba: Pointer to HBA object.
  94 * @lpfc_cmd: lpfc scsi command object pointer.
  95 *
  96 * This function is called from the lpfc_prep_task_mgmt_cmd function to
  97 * set the last bit in the response sge entry.
  98 **/
  99static void
 100lpfc_sli4_set_rsp_sgl_last(struct lpfc_hba *phba,
 101				struct lpfc_io_buf *lpfc_cmd)
 102{
 103	struct sli4_sge *sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
 104	if (sgl) {
 105		sgl += 1;
 106		sgl->word2 = le32_to_cpu(sgl->word2);
 107		bf_set(lpfc_sli4_sge_last, sgl, 1);
 108		sgl->word2 = cpu_to_le32(sgl->word2);
 109	}
 110}
 111
 112/**
 113 * lpfc_rampdown_queue_depth - Post RAMP_DOWN_QUEUE event to worker thread
 114 * @phba: The Hba for which this call is being executed.
 115 *
 116 * This routine is called when there is resource error in driver or firmware.
 117 * This routine posts WORKER_RAMP_DOWN_QUEUE event for @phba. This routine
 118 * posts at most 1 event each second. This routine wakes up worker thread of
 119 * @phba to process WORKER_RAM_DOWN_EVENT event.
 120 *
 121 * This routine should be called with no lock held.
 122 **/
 123void
 124lpfc_rampdown_queue_depth(struct lpfc_hba *phba)
 125{
 126	unsigned long flags;
 127	uint32_t evt_posted;
 128	unsigned long expires;
 129
 130	spin_lock_irqsave(&phba->hbalock, flags);
 131	atomic_inc(&phba->num_rsrc_err);
 132	phba->last_rsrc_error_time = jiffies;
 133
 134	expires = phba->last_ramp_down_time + QUEUE_RAMP_DOWN_INTERVAL;
 135	if (time_after(expires, jiffies)) {
 136		spin_unlock_irqrestore(&phba->hbalock, flags);
 137		return;
 138	}
 139
 140	phba->last_ramp_down_time = jiffies;
 141
 142	spin_unlock_irqrestore(&phba->hbalock, flags);
 143
 144	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
 145	evt_posted = phba->pport->work_port_events & WORKER_RAMP_DOWN_QUEUE;
 146	if (!evt_posted)
 147		phba->pport->work_port_events |= WORKER_RAMP_DOWN_QUEUE;
 148	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
 149
 150	if (!evt_posted)
 151		lpfc_worker_wake_up(phba);
 152	return;
 153}
 154
 155/**
 156 * lpfc_ramp_down_queue_handler - WORKER_RAMP_DOWN_QUEUE event handler
 157 * @phba: The Hba for which this call is being executed.
 158 *
 159 * This routine is called to  process WORKER_RAMP_DOWN_QUEUE event for worker
 160 * thread.This routine reduces queue depth for all scsi device on each vport
 161 * associated with @phba.
 162 **/
 163void
 164lpfc_ramp_down_queue_handler(struct lpfc_hba *phba)
 165{
 166	struct lpfc_vport **vports;
 167	struct Scsi_Host  *shost;
 168	struct scsi_device *sdev;
 169	unsigned long new_queue_depth;
 170	unsigned long num_rsrc_err;
 171	int i;
 172
 173	num_rsrc_err = atomic_read(&phba->num_rsrc_err);
 174
 175	/*
 176	 * The error and success command counters are global per
 177	 * driver instance.  If another handler has already
 178	 * operated on this error event, just exit.
 179	 */
 180	if (num_rsrc_err == 0)
 181		return;
 182
 183	vports = lpfc_create_vport_work_array(phba);
 184	if (vports != NULL)
 185		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
 186			shost = lpfc_shost_from_vport(vports[i]);
 187			shost_for_each_device(sdev, shost) {
 188				if (num_rsrc_err >= sdev->queue_depth)
 189					new_queue_depth = 1;
 190				else
 191					new_queue_depth = sdev->queue_depth -
 192						num_rsrc_err;
 193				scsi_change_queue_depth(sdev, new_queue_depth);
 194			}
 195		}
 196	lpfc_destroy_vport_work_array(phba, vports);
 197	atomic_set(&phba->num_rsrc_err, 0);
 198}
 199
 200/**
 201 * lpfc_scsi_dev_block - set all scsi hosts to block state
 202 * @phba: Pointer to HBA context object.
 203 *
 204 * This function walks vport list and set each SCSI host to block state
 205 * by invoking fc_remote_port_delete() routine. This function is invoked
 206 * with EEH when device's PCI slot has been permanently disabled.
 207 **/
 208void
 209lpfc_scsi_dev_block(struct lpfc_hba *phba)
 210{
 211	struct lpfc_vport **vports;
 212	struct Scsi_Host  *shost;
 213	struct scsi_device *sdev;
 214	struct fc_rport *rport;
 215	int i;
 216
 217	vports = lpfc_create_vport_work_array(phba);
 218	if (vports != NULL)
 219		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
 220			shost = lpfc_shost_from_vport(vports[i]);
 221			shost_for_each_device(sdev, shost) {
 222				rport = starget_to_rport(scsi_target(sdev));
 223				fc_remote_port_delete(rport);
 224			}
 225		}
 226	lpfc_destroy_vport_work_array(phba, vports);
 227}
 228
 229/**
 230 * lpfc_new_scsi_buf_s3 - Scsi buffer allocator for HBA with SLI3 IF spec
 231 * @vport: The virtual port for which this call being executed.
 232 * @num_to_alloc: The requested number of buffers to allocate.
 233 *
 234 * This routine allocates a scsi buffer for device with SLI-3 interface spec,
 235 * the scsi buffer contains all the necessary information needed to initiate
 236 * a SCSI I/O. The non-DMAable buffer region contains information to build
 237 * the IOCB. The DMAable region contains memory for the FCP CMND, FCP RSP,
 238 * and the initial BPL. In addition to allocating memory, the FCP CMND and
 239 * FCP RSP BDEs are setup in the BPL and the BPL BDE is setup in the IOCB.
 240 *
 241 * Return codes:
 242 *   int - number of scsi buffers that were allocated.
 243 *   0 = failure, less than num_to_alloc is a partial failure.
 244 **/
 245static int
 246lpfc_new_scsi_buf_s3(struct lpfc_vport *vport, int num_to_alloc)
 247{
 248	struct lpfc_hba *phba = vport->phba;
 249	struct lpfc_io_buf *psb;
 250	struct ulp_bde64 *bpl;
 251	IOCB_t *iocb;
 252	dma_addr_t pdma_phys_fcp_cmd;
 253	dma_addr_t pdma_phys_fcp_rsp;
 254	dma_addr_t pdma_phys_sgl;
 255	uint16_t iotag;
 256	int bcnt, bpl_size;
 257
 258	bpl_size = phba->cfg_sg_dma_buf_size -
 259		(sizeof(struct fcp_cmnd) + sizeof(struct fcp_rsp));
 260
 261	lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
 262			 "9067 ALLOC %d scsi_bufs: %d (%d + %d + %d)\n",
 263			 num_to_alloc, phba->cfg_sg_dma_buf_size,
 264			 (int)sizeof(struct fcp_cmnd),
 265			 (int)sizeof(struct fcp_rsp), bpl_size);
 266
 267	for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
 268		psb = kzalloc(sizeof(struct lpfc_io_buf), GFP_KERNEL);
 269		if (!psb)
 270			break;
 271
 272		/*
 273		 * Get memory from the pci pool to map the virt space to pci
 274		 * bus space for an I/O.  The DMA buffer includes space for the
 275		 * struct fcp_cmnd, struct fcp_rsp and the number of bde's
 276		 * necessary to support the sg_tablesize.
 277		 */
 278		psb->data = dma_pool_zalloc(phba->lpfc_sg_dma_buf_pool,
 279					GFP_KERNEL, &psb->dma_handle);
 280		if (!psb->data) {
 281			kfree(psb);
 282			break;
 283		}
 284
 285
 286		/* Allocate iotag for psb->cur_iocbq. */
 287		iotag = lpfc_sli_next_iotag(phba, &psb->cur_iocbq);
 288		if (iotag == 0) {
 289			dma_pool_free(phba->lpfc_sg_dma_buf_pool,
 290				      psb->data, psb->dma_handle);
 291			kfree(psb);
 292			break;
 293		}
 294		psb->cur_iocbq.cmd_flag |= LPFC_IO_FCP;
 295
 296		psb->fcp_cmnd = psb->data;
 297		psb->fcp_rsp = psb->data + sizeof(struct fcp_cmnd);
 298		psb->dma_sgl = psb->data + sizeof(struct fcp_cmnd) +
 299			sizeof(struct fcp_rsp);
 300
 301		/* Initialize local short-hand pointers. */
 302		bpl = (struct ulp_bde64 *)psb->dma_sgl;
 303		pdma_phys_fcp_cmd = psb->dma_handle;
 304		pdma_phys_fcp_rsp = psb->dma_handle + sizeof(struct fcp_cmnd);
 305		pdma_phys_sgl = psb->dma_handle + sizeof(struct fcp_cmnd) +
 306			sizeof(struct fcp_rsp);
 307
 308		/*
 309		 * The first two bdes are the FCP_CMD and FCP_RSP. The balance
 310		 * are sg list bdes.  Initialize the first two and leave the
 311		 * rest for queuecommand.
 312		 */
 313		bpl[0].addrHigh = le32_to_cpu(putPaddrHigh(pdma_phys_fcp_cmd));
 314		bpl[0].addrLow = le32_to_cpu(putPaddrLow(pdma_phys_fcp_cmd));
 315		bpl[0].tus.f.bdeSize = sizeof(struct fcp_cmnd);
 316		bpl[0].tus.f.bdeFlags = BUFF_TYPE_BDE_64;
 317		bpl[0].tus.w = le32_to_cpu(bpl[0].tus.w);
 318
 319		/* Setup the physical region for the FCP RSP */
 320		bpl[1].addrHigh = le32_to_cpu(putPaddrHigh(pdma_phys_fcp_rsp));
 321		bpl[1].addrLow = le32_to_cpu(putPaddrLow(pdma_phys_fcp_rsp));
 322		bpl[1].tus.f.bdeSize = sizeof(struct fcp_rsp);
 323		bpl[1].tus.f.bdeFlags = BUFF_TYPE_BDE_64;
 324		bpl[1].tus.w = le32_to_cpu(bpl[1].tus.w);
 325
 326		/*
 327		 * Since the IOCB for the FCP I/O is built into this
 328		 * lpfc_scsi_buf, initialize it with all known data now.
 329		 */
 330		iocb = &psb->cur_iocbq.iocb;
 331		iocb->un.fcpi64.bdl.ulpIoTag32 = 0;
 332		if ((phba->sli_rev == 3) &&
 333				!(phba->sli3_options & LPFC_SLI3_BG_ENABLED)) {
 334			/* fill in immediate fcp command BDE */
 335			iocb->un.fcpi64.bdl.bdeFlags = BUFF_TYPE_BDE_IMMED;
 336			iocb->un.fcpi64.bdl.bdeSize = sizeof(struct fcp_cmnd);
 337			iocb->un.fcpi64.bdl.addrLow = offsetof(IOCB_t,
 338					unsli3.fcp_ext.icd);
 339			iocb->un.fcpi64.bdl.addrHigh = 0;
 340			iocb->ulpBdeCount = 0;
 341			iocb->ulpLe = 0;
 342			/* fill in response BDE */
 343			iocb->unsli3.fcp_ext.rbde.tus.f.bdeFlags =
 344							BUFF_TYPE_BDE_64;
 345			iocb->unsli3.fcp_ext.rbde.tus.f.bdeSize =
 346				sizeof(struct fcp_rsp);
 347			iocb->unsli3.fcp_ext.rbde.addrLow =
 348				putPaddrLow(pdma_phys_fcp_rsp);
 349			iocb->unsli3.fcp_ext.rbde.addrHigh =
 350				putPaddrHigh(pdma_phys_fcp_rsp);
 351		} else {
 352			iocb->un.fcpi64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
 353			iocb->un.fcpi64.bdl.bdeSize =
 354					(2 * sizeof(struct ulp_bde64));
 355			iocb->un.fcpi64.bdl.addrLow =
 356					putPaddrLow(pdma_phys_sgl);
 357			iocb->un.fcpi64.bdl.addrHigh =
 358					putPaddrHigh(pdma_phys_sgl);
 359			iocb->ulpBdeCount = 1;
 360			iocb->ulpLe = 1;
 361		}
 362		iocb->ulpClass = CLASS3;
 363		psb->status = IOSTAT_SUCCESS;
 364		/* Put it back into the SCSI buffer list */
 365		psb->cur_iocbq.io_buf = psb;
 366		spin_lock_init(&psb->buf_lock);
 367		lpfc_release_scsi_buf_s3(phba, psb);
 368
 369	}
 370
 371	return bcnt;
 372}
 373
 374/**
 375 * lpfc_sli4_vport_delete_fcp_xri_aborted -Remove all ndlp references for vport
 376 * @vport: pointer to lpfc vport data structure.
 377 *
 378 * This routine is invoked by the vport cleanup for deletions and the cleanup
 379 * for an ndlp on removal.
 380 **/
 381void
 382lpfc_sli4_vport_delete_fcp_xri_aborted(struct lpfc_vport *vport)
 383{
 384	struct lpfc_hba *phba = vport->phba;
 385	struct lpfc_io_buf *psb, *next_psb;
 386	struct lpfc_sli4_hdw_queue *qp;
 387	unsigned long iflag = 0;
 388	int idx;
 389
 390	if (!(vport->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
 391		return;
 392
 393	/* may be called before queues established if hba_setup fails */
 394	if (!phba->sli4_hba.hdwq)
 395		return;
 396
 397	spin_lock_irqsave(&phba->hbalock, iflag);
 398	for (idx = 0; idx < phba->cfg_hdw_queue; idx++) {
 399		qp = &phba->sli4_hba.hdwq[idx];
 400
 401		spin_lock(&qp->abts_io_buf_list_lock);
 402		list_for_each_entry_safe(psb, next_psb,
 403					 &qp->lpfc_abts_io_buf_list, list) {
 404			if (psb->cur_iocbq.cmd_flag & LPFC_IO_NVME)
 405				continue;
 406
 407			if (psb->rdata && psb->rdata->pnode &&
 408			    psb->rdata->pnode->vport == vport)
 409				psb->rdata = NULL;
 410		}
 411		spin_unlock(&qp->abts_io_buf_list_lock);
 412	}
 413	spin_unlock_irqrestore(&phba->hbalock, iflag);
 414}
 415
 416/**
 417 * lpfc_sli4_io_xri_aborted - Fast-path process of fcp xri abort
 418 * @phba: pointer to lpfc hba data structure.
 419 * @axri: pointer to the fcp xri abort wcqe structure.
 420 * @idx: index into hdwq
 421 *
 422 * This routine is invoked by the worker thread to process a SLI4 fast-path
 423 * FCP or NVME aborted xri.
 424 **/
 425void
 426lpfc_sli4_io_xri_aborted(struct lpfc_hba *phba,
 427			 struct sli4_wcqe_xri_aborted *axri, int idx)
 428{
 429	u16 xri = 0;
 430	u16 rxid = 0;
 431	struct lpfc_io_buf *psb, *next_psb;
 432	struct lpfc_sli4_hdw_queue *qp;
 433	unsigned long iflag = 0;
 434	struct lpfc_iocbq *iocbq;
 435	int i;
 436	struct lpfc_nodelist *ndlp;
 437	int rrq_empty = 0;
 438	struct lpfc_sli_ring *pring = phba->sli4_hba.els_wq->pring;
 439	struct scsi_cmnd *cmd;
 440	int offline = 0;
 441
 442	if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP))
 443		return;
 444	offline = pci_channel_offline(phba->pcidev);
 445	if (!offline) {
 446		xri = bf_get(lpfc_wcqe_xa_xri, axri);
 447		rxid = bf_get(lpfc_wcqe_xa_remote_xid, axri);
 448	}
 449	qp = &phba->sli4_hba.hdwq[idx];
 450	spin_lock_irqsave(&phba->hbalock, iflag);
 451	spin_lock(&qp->abts_io_buf_list_lock);
 452	list_for_each_entry_safe(psb, next_psb,
 453		&qp->lpfc_abts_io_buf_list, list) {
 454		if (offline)
 455			xri = psb->cur_iocbq.sli4_xritag;
 456		if (psb->cur_iocbq.sli4_xritag == xri) {
 457			list_del_init(&psb->list);
 458			psb->flags &= ~LPFC_SBUF_XBUSY;
 459			psb->status = IOSTAT_SUCCESS;
 460			if (psb->cur_iocbq.cmd_flag & LPFC_IO_NVME) {
 461				qp->abts_nvme_io_bufs--;
 462				spin_unlock(&qp->abts_io_buf_list_lock);
 463				spin_unlock_irqrestore(&phba->hbalock, iflag);
 464				if (!offline) {
 465					lpfc_sli4_nvme_xri_aborted(phba, axri,
 466								   psb);
 467					return;
 468				}
 469				lpfc_sli4_nvme_pci_offline_aborted(phba, psb);
 470				spin_lock_irqsave(&phba->hbalock, iflag);
 471				spin_lock(&qp->abts_io_buf_list_lock);
 472				continue;
 473			}
 474			qp->abts_scsi_io_bufs--;
 475			spin_unlock(&qp->abts_io_buf_list_lock);
 476
 477			if (psb->rdata && psb->rdata->pnode)
 478				ndlp = psb->rdata->pnode;
 479			else
 480				ndlp = NULL;
 481			spin_unlock_irqrestore(&phba->hbalock, iflag);
 482
 483			spin_lock_irqsave(&phba->rrq_list_lock, iflag);
 484			rrq_empty = list_empty(&phba->active_rrq_list);
 485			spin_unlock_irqrestore(&phba->rrq_list_lock, iflag);
 486			if (ndlp && !offline) {
 487				lpfc_set_rrq_active(phba, ndlp,
 488					psb->cur_iocbq.sli4_lxritag, rxid, 1);
 489				lpfc_sli4_abts_err_handler(phba, ndlp, axri);
 490			}
 491
 492			if (phba->cfg_fcp_wait_abts_rsp || offline) {
 493				spin_lock_irqsave(&psb->buf_lock, iflag);
 494				cmd = psb->pCmd;
 495				psb->pCmd = NULL;
 496				spin_unlock_irqrestore(&psb->buf_lock, iflag);
 497
 498				/* The sdev is not guaranteed to be valid post
 499				 * scsi_done upcall.
 500				 */
 501				if (cmd)
 502					scsi_done(cmd);
 503
 504				/*
 505				 * We expect there is an abort thread waiting
 506				 * for command completion wake up the thread.
 507				 */
 508				spin_lock_irqsave(&psb->buf_lock, iflag);
 509				psb->cur_iocbq.cmd_flag &=
 510					~LPFC_DRIVER_ABORTED;
 511				if (psb->waitq)
 512					wake_up(psb->waitq);
 513				spin_unlock_irqrestore(&psb->buf_lock, iflag);
 514			}
 515
 516			lpfc_release_scsi_buf_s4(phba, psb);
 517			if (rrq_empty)
 518				lpfc_worker_wake_up(phba);
 519			if (!offline)
 520				return;
 521			spin_lock_irqsave(&phba->hbalock, iflag);
 522			spin_lock(&qp->abts_io_buf_list_lock);
 523			continue;
 524		}
 525	}
 526	spin_unlock(&qp->abts_io_buf_list_lock);
 527	if (!offline) {
 528		for (i = 1; i <= phba->sli.last_iotag; i++) {
 529			iocbq = phba->sli.iocbq_lookup[i];
 530
 531			if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
 532			    (iocbq->cmd_flag & LPFC_IO_LIBDFC))
 533				continue;
 534			if (iocbq->sli4_xritag != xri)
 535				continue;
 536			psb = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
 537			psb->flags &= ~LPFC_SBUF_XBUSY;
 538			spin_unlock_irqrestore(&phba->hbalock, iflag);
 539			if (test_bit(HBA_SETUP, &phba->hba_flag) &&
 540			    !list_empty(&pring->txq))
 541				lpfc_worker_wake_up(phba);
 542			return;
 543		}
 544	}
 545	spin_unlock_irqrestore(&phba->hbalock, iflag);
 546}
 547
 548/**
 549 * lpfc_get_scsi_buf_s3 - Get a scsi buffer from lpfc_scsi_buf_list of the HBA
 550 * @phba: The HBA for which this call is being executed.
 551 * @ndlp: pointer to a node-list data structure.
 552 * @cmnd: Pointer to scsi_cmnd data structure.
 553 *
 554 * This routine removes a scsi buffer from head of @phba lpfc_scsi_buf_list list
 555 * and returns to caller.
 556 *
 557 * Return codes:
 558 *   NULL - Error
 559 *   Pointer to lpfc_scsi_buf - Success
 560 **/
 561static struct lpfc_io_buf *
 562lpfc_get_scsi_buf_s3(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
 563		     struct scsi_cmnd *cmnd)
 564{
 565	struct lpfc_io_buf *lpfc_cmd = NULL;
 566	struct list_head *scsi_buf_list_get = &phba->lpfc_scsi_buf_list_get;
 567	unsigned long iflag = 0;
 568
 569	spin_lock_irqsave(&phba->scsi_buf_list_get_lock, iflag);
 570	list_remove_head(scsi_buf_list_get, lpfc_cmd, struct lpfc_io_buf,
 571			 list);
 572	if (!lpfc_cmd) {
 573		spin_lock(&phba->scsi_buf_list_put_lock);
 574		list_splice(&phba->lpfc_scsi_buf_list_put,
 575			    &phba->lpfc_scsi_buf_list_get);
 576		INIT_LIST_HEAD(&phba->lpfc_scsi_buf_list_put);
 577		list_remove_head(scsi_buf_list_get, lpfc_cmd,
 578				 struct lpfc_io_buf, list);
 579		spin_unlock(&phba->scsi_buf_list_put_lock);
 580	}
 581	spin_unlock_irqrestore(&phba->scsi_buf_list_get_lock, iflag);
 582
 583	if (lpfc_ndlp_check_qdepth(phba, ndlp) && lpfc_cmd) {
 584		atomic_inc(&ndlp->cmd_pending);
 585		lpfc_cmd->flags |= LPFC_SBUF_BUMP_QDEPTH;
 586	}
 587	return  lpfc_cmd;
 588}
 589/**
 590 * lpfc_get_scsi_buf_s4 - Get a scsi buffer from io_buf_list of the HBA
 591 * @phba: The HBA for which this call is being executed.
 592 * @ndlp: pointer to a node-list data structure.
 593 * @cmnd: Pointer to scsi_cmnd data structure.
 594 *
 595 * This routine removes a scsi buffer from head of @hdwq io_buf_list
 596 * and returns to caller.
 597 *
 598 * Return codes:
 599 *   NULL - Error
 600 *   Pointer to lpfc_scsi_buf - Success
 601 **/
 602static struct lpfc_io_buf *
 603lpfc_get_scsi_buf_s4(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
 604		     struct scsi_cmnd *cmnd)
 605{
 606	struct lpfc_io_buf *lpfc_cmd;
 607	struct lpfc_sli4_hdw_queue *qp;
 608	struct sli4_sge_le *sgl;
 609	dma_addr_t pdma_phys_fcp_rsp;
 610	dma_addr_t pdma_phys_fcp_cmd;
 611	uint32_t cpu, idx;
 612	int tag;
 613	struct fcp_cmd_rsp_buf *tmp = NULL;
 614
 615	cpu = raw_smp_processor_id();
 616	if (cmnd && phba->cfg_fcp_io_sched == LPFC_FCP_SCHED_BY_HDWQ) {
 617		tag = blk_mq_unique_tag(scsi_cmd_to_rq(cmnd));
 618		idx = blk_mq_unique_tag_to_hwq(tag);
 619	} else {
 620		idx = phba->sli4_hba.cpu_map[cpu].hdwq;
 621	}
 622
 623	lpfc_cmd = lpfc_get_io_buf(phba, ndlp, idx,
 624				   !phba->cfg_xri_rebalancing);
 625	if (!lpfc_cmd) {
 626		qp = &phba->sli4_hba.hdwq[idx];
 627		qp->empty_io_bufs++;
 628		return NULL;
 629	}
 630
 631	/* Setup key fields in buffer that may have been changed
 632	 * if other protocols used this buffer.
 633	 */
 634	lpfc_cmd->cur_iocbq.cmd_flag = LPFC_IO_FCP;
 635	lpfc_cmd->prot_seg_cnt = 0;
 636	lpfc_cmd->seg_cnt = 0;
 637	lpfc_cmd->timeout = 0;
 638	lpfc_cmd->flags = 0;
 639	lpfc_cmd->start_time = jiffies;
 640	lpfc_cmd->waitq = NULL;
 641	lpfc_cmd->cpu = cpu;
 642#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
 643	lpfc_cmd->prot_data_type = 0;
 644#endif
 645	tmp = lpfc_get_cmd_rsp_buf_per_hdwq(phba, lpfc_cmd);
 646	if (!tmp) {
 647		lpfc_release_io_buf(phba, lpfc_cmd, lpfc_cmd->hdwq);
 648		return NULL;
 649	}
 650
 651	lpfc_cmd->fcp_cmnd = tmp->fcp_cmnd;
 652	lpfc_cmd->fcp_rsp = tmp->fcp_rsp;
 653
 654	/*
 655	 * The first two SGEs are the FCP_CMD and FCP_RSP.
 656	 * The balance are sg list bdes. Initialize the
 657	 * first two and leave the rest for queuecommand.
 658	 */
 659	sgl = (struct sli4_sge_le *)lpfc_cmd->dma_sgl;
 660	pdma_phys_fcp_cmd = tmp->fcp_cmd_rsp_dma_handle;
 661	sgl->addr_hi = cpu_to_le32(putPaddrHigh(pdma_phys_fcp_cmd));
 662	sgl->addr_lo = cpu_to_le32(putPaddrLow(pdma_phys_fcp_cmd));
 663	bf_set_le32(lpfc_sli4_sge_last, sgl, 0);
 664	if (cmnd && cmnd->cmd_len > LPFC_FCP_CDB_LEN)
 665		sgl->sge_len = cpu_to_le32(sizeof(struct fcp_cmnd32));
 666	else
 667		sgl->sge_len = cpu_to_le32(sizeof(struct fcp_cmnd));
 668
 669	sgl++;
 670
 671	/* Setup the physical region for the FCP RSP */
 672	pdma_phys_fcp_rsp = pdma_phys_fcp_cmd + sizeof(struct fcp_cmnd32);
 673	sgl->addr_hi = cpu_to_le32(putPaddrHigh(pdma_phys_fcp_rsp));
 674	sgl->addr_lo = cpu_to_le32(putPaddrLow(pdma_phys_fcp_rsp));
 675	bf_set_le32(lpfc_sli4_sge_last, sgl, 1);
 676	sgl->sge_len = cpu_to_le32(sizeof(struct fcp_rsp));
 677
 678	if (lpfc_ndlp_check_qdepth(phba, ndlp)) {
 679		atomic_inc(&ndlp->cmd_pending);
 680		lpfc_cmd->flags |= LPFC_SBUF_BUMP_QDEPTH;
 681	}
 682	return  lpfc_cmd;
 683}
 684/**
 685 * lpfc_get_scsi_buf - Get a scsi buffer from lpfc_scsi_buf_list of the HBA
 686 * @phba: The HBA for which this call is being executed.
 687 * @ndlp: pointer to a node-list data structure.
 688 * @cmnd: Pointer to scsi_cmnd data structure.
 689 *
 690 * This routine removes a scsi buffer from head of @phba lpfc_scsi_buf_list list
 691 * and returns to caller.
 692 *
 693 * Return codes:
 694 *   NULL - Error
 695 *   Pointer to lpfc_scsi_buf - Success
 696 **/
 697static struct lpfc_io_buf*
 698lpfc_get_scsi_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
 699		  struct scsi_cmnd *cmnd)
 700{
 701	return  phba->lpfc_get_scsi_buf(phba, ndlp, cmnd);
 702}
 703
 704/**
 705 * lpfc_release_scsi_buf_s3 - Return a scsi buffer back to hba scsi buf list
 706 * @phba: The Hba for which this call is being executed.
 707 * @psb: The scsi buffer which is being released.
 708 *
 709 * This routine releases @psb scsi buffer by adding it to tail of @phba
 710 * lpfc_scsi_buf_list list.
 711 **/
 712static void
 713lpfc_release_scsi_buf_s3(struct lpfc_hba *phba, struct lpfc_io_buf *psb)
 714{
 715	unsigned long iflag = 0;
 716
 717	psb->seg_cnt = 0;
 718	psb->prot_seg_cnt = 0;
 719
 720	spin_lock_irqsave(&phba->scsi_buf_list_put_lock, iflag);
 721	psb->pCmd = NULL;
 722	psb->cur_iocbq.cmd_flag = LPFC_IO_FCP;
 723	list_add_tail(&psb->list, &phba->lpfc_scsi_buf_list_put);
 724	spin_unlock_irqrestore(&phba->scsi_buf_list_put_lock, iflag);
 725}
 726
 727/**
 728 * lpfc_release_scsi_buf_s4: Return a scsi buffer back to hba scsi buf list.
 729 * @phba: The Hba for which this call is being executed.
 730 * @psb: The scsi buffer which is being released.
 731 *
 732 * This routine releases @psb scsi buffer by adding it to tail of @hdwq
 733 * io_buf_list list. For SLI4 XRI's are tied to the scsi buffer
 734 * and cannot be reused for at least RA_TOV amount of time if it was
 735 * aborted.
 736 **/
 737static void
 738lpfc_release_scsi_buf_s4(struct lpfc_hba *phba, struct lpfc_io_buf *psb)
 739{
 740	struct lpfc_sli4_hdw_queue *qp;
 741	unsigned long iflag = 0;
 742
 743	psb->seg_cnt = 0;
 744	psb->prot_seg_cnt = 0;
 745
 746	qp = psb->hdwq;
 747	if (psb->flags & LPFC_SBUF_XBUSY) {
 748		spin_lock_irqsave(&qp->abts_io_buf_list_lock, iflag);
 749		if (!phba->cfg_fcp_wait_abts_rsp)
 750			psb->pCmd = NULL;
 751		list_add_tail(&psb->list, &qp->lpfc_abts_io_buf_list);
 752		qp->abts_scsi_io_bufs++;
 753		spin_unlock_irqrestore(&qp->abts_io_buf_list_lock, iflag);
 754	} else {
 755		lpfc_release_io_buf(phba, (struct lpfc_io_buf *)psb, qp);
 756	}
 757}
 758
 759/**
 760 * lpfc_release_scsi_buf: Return a scsi buffer back to hba scsi buf list.
 761 * @phba: The Hba for which this call is being executed.
 762 * @psb: The scsi buffer which is being released.
 763 *
 764 * This routine releases @psb scsi buffer by adding it to tail of @phba
 765 * lpfc_scsi_buf_list list.
 766 **/
 767static void
 768lpfc_release_scsi_buf(struct lpfc_hba *phba, struct lpfc_io_buf *psb)
 769{
 770	if ((psb->flags & LPFC_SBUF_BUMP_QDEPTH) && psb->ndlp)
 771		atomic_dec(&psb->ndlp->cmd_pending);
 772
 773	psb->flags &= ~LPFC_SBUF_BUMP_QDEPTH;
 774	phba->lpfc_release_scsi_buf(phba, psb);
 775}
 776
 777/**
 778 * lpfc_fcpcmd_to_iocb - copy the fcp_cmd data into the IOCB
 779 * @data: A pointer to the immediate command data portion of the IOCB.
 780 * @fcp_cmnd: The FCP Command that is provided by the SCSI layer.
 781 *
 782 * The routine copies the entire FCP command from @fcp_cmnd to @data while
 783 * byte swapping the data to big endian format for transmission on the wire.
 784 **/
 785static void
 786lpfc_fcpcmd_to_iocb(u8 *data, struct fcp_cmnd *fcp_cmnd)
 787{
 788	int i, j;
 789
 790	for (i = 0, j = 0; i < sizeof(struct fcp_cmnd);
 791	     i += sizeof(uint32_t), j++) {
 792		((uint32_t *)data)[j] = cpu_to_be32(((uint32_t *)fcp_cmnd)[j]);
 793	}
 794}
 795
 796/**
 797 * lpfc_scsi_prep_dma_buf_s3 - DMA mapping for scsi buffer to SLI3 IF spec
 798 * @phba: The Hba for which this call is being executed.
 799 * @lpfc_cmd: The scsi buffer which is going to be mapped.
 800 *
 801 * This routine does the pci dma mapping for scatter-gather list of scsi cmnd
 802 * field of @lpfc_cmd for device with SLI-3 interface spec. This routine scans
 803 * through sg elements and format the bde. This routine also initializes all
 804 * IOCB fields which are dependent on scsi command request buffer.
 805 *
 806 * Return codes:
 807 *   1 - Error
 808 *   0 - Success
 809 **/
 810static int
 811lpfc_scsi_prep_dma_buf_s3(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
 812{
 813	struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
 814	struct scatterlist *sgel = NULL;
 815	struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
 816	struct ulp_bde64 *bpl = (struct ulp_bde64 *)lpfc_cmd->dma_sgl;
 817	struct lpfc_iocbq *iocbq = &lpfc_cmd->cur_iocbq;
 818	IOCB_t *iocb_cmd = &lpfc_cmd->cur_iocbq.iocb;
 819	struct ulp_bde64 *data_bde = iocb_cmd->unsli3.fcp_ext.dbde;
 820	dma_addr_t physaddr;
 821	uint32_t num_bde = 0;
 822	int nseg, datadir = scsi_cmnd->sc_data_direction;
 823
 824	/*
 825	 * There are three possibilities here - use scatter-gather segment, use
 826	 * the single mapping, or neither.  Start the lpfc command prep by
 827	 * bumping the bpl beyond the fcp_cmnd and fcp_rsp regions to the first
 828	 * data bde entry.
 829	 */
 830	bpl += 2;
 831	if (scsi_sg_count(scsi_cmnd)) {
 832		/*
 833		 * The driver stores the segment count returned from dma_map_sg
 834		 * because this a count of dma-mappings used to map the use_sg
 835		 * pages.  They are not guaranteed to be the same for those
 836		 * architectures that implement an IOMMU.
 837		 */
 838
 839		nseg = dma_map_sg(&phba->pcidev->dev, scsi_sglist(scsi_cmnd),
 840				  scsi_sg_count(scsi_cmnd), datadir);
 841		if (unlikely(!nseg))
 842			return 1;
 843
 844		lpfc_cmd->seg_cnt = nseg;
 845		if (lpfc_cmd->seg_cnt > phba->cfg_sg_seg_cnt) {
 846			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
 847					"9064 BLKGRD: %s: Too many sg segments"
 848					" from dma_map_sg.  Config %d, seg_cnt"
 849					" %d\n", __func__, phba->cfg_sg_seg_cnt,
 850					lpfc_cmd->seg_cnt);
 851			WARN_ON_ONCE(lpfc_cmd->seg_cnt > phba->cfg_sg_seg_cnt);
 852			lpfc_cmd->seg_cnt = 0;
 853			scsi_dma_unmap(scsi_cmnd);
 854			return 2;
 855		}
 856
 857		/*
 858		 * The driver established a maximum scatter-gather segment count
 859		 * during probe that limits the number of sg elements in any
 860		 * single scsi command.  Just run through the seg_cnt and format
 861		 * the bde's.
 862		 * When using SLI-3 the driver will try to fit all the BDEs into
 863		 * the IOCB. If it can't then the BDEs get added to a BPL as it
 864		 * does for SLI-2 mode.
 865		 */
 866		scsi_for_each_sg(scsi_cmnd, sgel, nseg, num_bde) {
 867			physaddr = sg_dma_address(sgel);
 868			if (phba->sli_rev == 3 &&
 869			    !(phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
 870			    !(iocbq->cmd_flag & DSS_SECURITY_OP) &&
 871			    nseg <= LPFC_EXT_DATA_BDE_COUNT) {
 872				data_bde->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
 873				data_bde->tus.f.bdeSize = sg_dma_len(sgel);
 874				data_bde->addrLow = putPaddrLow(physaddr);
 875				data_bde->addrHigh = putPaddrHigh(physaddr);
 876				data_bde++;
 877			} else {
 878				bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
 879				bpl->tus.f.bdeSize = sg_dma_len(sgel);
 880				bpl->tus.w = le32_to_cpu(bpl->tus.w);
 881				bpl->addrLow =
 882					le32_to_cpu(putPaddrLow(physaddr));
 883				bpl->addrHigh =
 884					le32_to_cpu(putPaddrHigh(physaddr));
 885				bpl++;
 886			}
 887		}
 888	}
 889
 890	/*
 891	 * Finish initializing those IOCB fields that are dependent on the
 892	 * scsi_cmnd request_buffer.  Note that for SLI-2 the bdeSize is
 893	 * explicitly reinitialized and for SLI-3 the extended bde count is
 894	 * explicitly reinitialized since all iocb memory resources are reused.
 895	 */
 896	if (phba->sli_rev == 3 &&
 897	    !(phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
 898	    !(iocbq->cmd_flag & DSS_SECURITY_OP)) {
 899		if (num_bde > LPFC_EXT_DATA_BDE_COUNT) {
 900			/*
 901			 * The extended IOCB format can only fit 3 BDE or a BPL.
 902			 * This I/O has more than 3 BDE so the 1st data bde will
 903			 * be a BPL that is filled in here.
 904			 */
 905			physaddr = lpfc_cmd->dma_handle;
 906			data_bde->tus.f.bdeFlags = BUFF_TYPE_BLP_64;
 907			data_bde->tus.f.bdeSize = (num_bde *
 908						   sizeof(struct ulp_bde64));
 909			physaddr += (sizeof(struct fcp_cmnd) +
 910				     sizeof(struct fcp_rsp) +
 911				     (2 * sizeof(struct ulp_bde64)));
 912			data_bde->addrHigh = putPaddrHigh(physaddr);
 913			data_bde->addrLow = putPaddrLow(physaddr);
 914			/* ebde count includes the response bde and data bpl */
 915			iocb_cmd->unsli3.fcp_ext.ebde_count = 2;
 916		} else {
 917			/* ebde count includes the response bde and data bdes */
 918			iocb_cmd->unsli3.fcp_ext.ebde_count = (num_bde + 1);
 919		}
 920	} else {
 921		iocb_cmd->un.fcpi64.bdl.bdeSize =
 922			((num_bde + 2) * sizeof(struct ulp_bde64));
 923		iocb_cmd->unsli3.fcp_ext.ebde_count = (num_bde + 1);
 924	}
 925	fcp_cmnd->fcpDl = cpu_to_be32(scsi_bufflen(scsi_cmnd));
 926
 927	/*
 928	 * Due to difference in data length between DIF/non-DIF paths,
 929	 * we need to set word 4 of IOCB here
 930	 */
 931	iocb_cmd->un.fcpi.fcpi_parm = scsi_bufflen(scsi_cmnd);
 932	lpfc_fcpcmd_to_iocb(iocb_cmd->unsli3.fcp_ext.icd, fcp_cmnd);
 933	return 0;
 934}
 935
 936#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
 937
 938/* Return BG_ERR_INIT if error injection is detected by Initiator */
 939#define BG_ERR_INIT	0x1
 940/* Return BG_ERR_TGT if error injection is detected by Target */
 941#define BG_ERR_TGT	0x2
 942/* Return BG_ERR_SWAP if swapping CSUM<-->CRC is required for error injection */
 943#define BG_ERR_SWAP	0x10
 944/*
 945 * Return BG_ERR_CHECK if disabling Guard/Ref/App checking is required for
 946 * error injection
 947 */
 948#define BG_ERR_CHECK	0x20
 949
 950/**
 951 * lpfc_bg_err_inject - Determine if we should inject an error
 952 * @phba: The Hba for which this call is being executed.
 953 * @sc: The SCSI command to examine
 954 * @reftag: (out) BlockGuard reference tag for transmitted data
 955 * @apptag: (out) BlockGuard application tag for transmitted data
 956 * @new_guard: (in) Value to replace CRC with if needed
 957 *
 958 * Returns BG_ERR_* bit mask or 0 if request ignored
 959 **/
 960static int
 961lpfc_bg_err_inject(struct lpfc_hba *phba, struct scsi_cmnd *sc,
 962		uint32_t *reftag, uint16_t *apptag, uint32_t new_guard)
 963{
 964	struct scatterlist *sgpe; /* s/g prot entry */
 965	struct lpfc_io_buf *lpfc_cmd = NULL;
 966	struct scsi_dif_tuple *src = NULL;
 967	struct lpfc_nodelist *ndlp;
 968	struct lpfc_rport_data *rdata;
 969	uint32_t op = scsi_get_prot_op(sc);
 970	uint32_t blksize;
 971	uint32_t numblks;
 972	u32 lba;
 973	int rc = 0;
 974	int blockoff = 0;
 975
 976	if (op == SCSI_PROT_NORMAL)
 977		return 0;
 978
 979	sgpe = scsi_prot_sglist(sc);
 980	lba = scsi_prot_ref_tag(sc);
 981
 982	/* First check if we need to match the LBA */
 983	if (phba->lpfc_injerr_lba != LPFC_INJERR_LBA_OFF) {
 984		blksize = scsi_prot_interval(sc);
 985		numblks = (scsi_bufflen(sc) + blksize - 1) / blksize;
 986
 987		/* Make sure we have the right LBA if one is specified */
 988		if (phba->lpfc_injerr_lba < (u64)lba ||
 989		    (phba->lpfc_injerr_lba >= (u64)(lba + numblks)))
 990			return 0;
 991		if (sgpe) {
 992			blockoff = phba->lpfc_injerr_lba - (u64)lba;
 993			numblks = sg_dma_len(sgpe) /
 994				sizeof(struct scsi_dif_tuple);
 995			if (numblks < blockoff)
 996				blockoff = numblks;
 997		}
 998	}
 999
1000	/* Next check if we need to match the remote NPortID or WWPN */
1001	rdata = lpfc_rport_data_from_scsi_device(sc->device);
1002	if (rdata && rdata->pnode) {
1003		ndlp = rdata->pnode;
1004
1005		/* Make sure we have the right NPortID if one is specified */
1006		if (phba->lpfc_injerr_nportid  &&
1007			(phba->lpfc_injerr_nportid != ndlp->nlp_DID))
1008			return 0;
1009
1010		/*
1011		 * Make sure we have the right WWPN if one is specified.
1012		 * wwn[0] should be a non-zero NAA in a good WWPN.
1013		 */
1014		if (phba->lpfc_injerr_wwpn.u.wwn[0]  &&
1015			(memcmp(&ndlp->nlp_portname, &phba->lpfc_injerr_wwpn,
1016				sizeof(struct lpfc_name)) != 0))
1017			return 0;
1018	}
1019
1020	/* Setup a ptr to the protection data if the SCSI host provides it */
1021	if (sgpe) {
1022		src = (struct scsi_dif_tuple *)sg_virt(sgpe);
1023		src += blockoff;
1024		lpfc_cmd = (struct lpfc_io_buf *)sc->host_scribble;
1025	}
1026
1027	/* Should we change the Reference Tag */
1028	if (reftag) {
1029		if (phba->lpfc_injerr_wref_cnt) {
1030			switch (op) {
1031			case SCSI_PROT_WRITE_PASS:
1032				if (src) {
1033					/*
1034					 * For WRITE_PASS, force the error
1035					 * to be sent on the wire. It should
1036					 * be detected by the Target.
1037					 * If blockoff != 0 error will be
1038					 * inserted in middle of the IO.
1039					 */
1040
1041					lpfc_printf_log(phba, KERN_ERR,
1042							LOG_TRACE_EVENT,
1043					"9076 BLKGRD: Injecting reftag error: "
1044					"write lba x%lx + x%x oldrefTag x%x\n",
1045					(unsigned long)lba, blockoff,
1046					be32_to_cpu(src->ref_tag));
1047
1048					/*
1049					 * Save the old ref_tag so we can
1050					 * restore it on completion.
1051					 */
1052					if (lpfc_cmd) {
1053						lpfc_cmd->prot_data_type =
1054							LPFC_INJERR_REFTAG;
1055						lpfc_cmd->prot_data_segment =
1056							src;
1057						lpfc_cmd->prot_data =
1058							src->ref_tag;
1059					}
1060					src->ref_tag = cpu_to_be32(0xDEADBEEF);
1061					phba->lpfc_injerr_wref_cnt--;
1062					if (phba->lpfc_injerr_wref_cnt == 0) {
1063						phba->lpfc_injerr_nportid = 0;
1064						phba->lpfc_injerr_lba =
1065							LPFC_INJERR_LBA_OFF;
1066						memset(&phba->lpfc_injerr_wwpn,
1067						  0, sizeof(struct lpfc_name));
1068					}
1069					rc = BG_ERR_TGT | BG_ERR_CHECK;
1070
1071					break;
1072				}
1073				fallthrough;
1074			case SCSI_PROT_WRITE_INSERT:
1075				/*
1076				 * For WRITE_INSERT, force the error
1077				 * to be sent on the wire. It should be
1078				 * detected by the Target.
1079				 */
1080				/* DEADBEEF will be the reftag on the wire */
1081				*reftag = 0xDEADBEEF;
1082				phba->lpfc_injerr_wref_cnt--;
1083				if (phba->lpfc_injerr_wref_cnt == 0) {
1084					phba->lpfc_injerr_nportid = 0;
1085					phba->lpfc_injerr_lba =
1086					LPFC_INJERR_LBA_OFF;
1087					memset(&phba->lpfc_injerr_wwpn,
1088						0, sizeof(struct lpfc_name));
1089				}
1090				rc = BG_ERR_TGT | BG_ERR_CHECK;
1091
1092				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1093					"9078 BLKGRD: Injecting reftag error: "
1094					"write lba x%lx\n", (unsigned long)lba);
1095				break;
1096			case SCSI_PROT_WRITE_STRIP:
1097				/*
1098				 * For WRITE_STRIP and WRITE_PASS,
1099				 * force the error on data
1100				 * being copied from SLI-Host to SLI-Port.
1101				 */
1102				*reftag = 0xDEADBEEF;
1103				phba->lpfc_injerr_wref_cnt--;
1104				if (phba->lpfc_injerr_wref_cnt == 0) {
1105					phba->lpfc_injerr_nportid = 0;
1106					phba->lpfc_injerr_lba =
1107						LPFC_INJERR_LBA_OFF;
1108					memset(&phba->lpfc_injerr_wwpn,
1109						0, sizeof(struct lpfc_name));
1110				}
1111				rc = BG_ERR_INIT;
1112
1113				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1114					"9077 BLKGRD: Injecting reftag error: "
1115					"write lba x%lx\n", (unsigned long)lba);
1116				break;
1117			}
1118		}
1119		if (phba->lpfc_injerr_rref_cnt) {
1120			switch (op) {
1121			case SCSI_PROT_READ_INSERT:
1122			case SCSI_PROT_READ_STRIP:
1123			case SCSI_PROT_READ_PASS:
1124				/*
1125				 * For READ_STRIP and READ_PASS, force the
1126				 * error on data being read off the wire. It
1127				 * should force an IO error to the driver.
1128				 */
1129				*reftag = 0xDEADBEEF;
1130				phba->lpfc_injerr_rref_cnt--;
1131				if (phba->lpfc_injerr_rref_cnt == 0) {
1132					phba->lpfc_injerr_nportid = 0;
1133					phba->lpfc_injerr_lba =
1134						LPFC_INJERR_LBA_OFF;
1135					memset(&phba->lpfc_injerr_wwpn,
1136						0, sizeof(struct lpfc_name));
1137				}
1138				rc = BG_ERR_INIT;
1139
1140				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1141					"9079 BLKGRD: Injecting reftag error: "
1142					"read lba x%lx\n", (unsigned long)lba);
1143				break;
1144			}
1145		}
1146	}
1147
1148	/* Should we change the Application Tag */
1149	if (apptag) {
1150		if (phba->lpfc_injerr_wapp_cnt) {
1151			switch (op) {
1152			case SCSI_PROT_WRITE_PASS:
1153				if (src) {
1154					/*
1155					 * For WRITE_PASS, force the error
1156					 * to be sent on the wire. It should
1157					 * be detected by the Target.
1158					 * If blockoff != 0 error will be
1159					 * inserted in middle of the IO.
1160					 */
1161
1162					lpfc_printf_log(phba, KERN_ERR,
1163							LOG_TRACE_EVENT,
1164					"9080 BLKGRD: Injecting apptag error: "
1165					"write lba x%lx + x%x oldappTag x%x\n",
1166					(unsigned long)lba, blockoff,
1167					be16_to_cpu(src->app_tag));
1168
1169					/*
1170					 * Save the old app_tag so we can
1171					 * restore it on completion.
1172					 */
1173					if (lpfc_cmd) {
1174						lpfc_cmd->prot_data_type =
1175							LPFC_INJERR_APPTAG;
1176						lpfc_cmd->prot_data_segment =
1177							src;
1178						lpfc_cmd->prot_data =
1179							src->app_tag;
1180					}
1181					src->app_tag = cpu_to_be16(0xDEAD);
1182					phba->lpfc_injerr_wapp_cnt--;
1183					if (phba->lpfc_injerr_wapp_cnt == 0) {
1184						phba->lpfc_injerr_nportid = 0;
1185						phba->lpfc_injerr_lba =
1186							LPFC_INJERR_LBA_OFF;
1187						memset(&phba->lpfc_injerr_wwpn,
1188						  0, sizeof(struct lpfc_name));
1189					}
1190					rc = BG_ERR_TGT | BG_ERR_CHECK;
1191					break;
1192				}
1193				fallthrough;
1194			case SCSI_PROT_WRITE_INSERT:
1195				/*
1196				 * For WRITE_INSERT, force the
1197				 * error to be sent on the wire. It should be
1198				 * detected by the Target.
1199				 */
1200				/* DEAD will be the apptag on the wire */
1201				*apptag = 0xDEAD;
1202				phba->lpfc_injerr_wapp_cnt--;
1203				if (phba->lpfc_injerr_wapp_cnt == 0) {
1204					phba->lpfc_injerr_nportid = 0;
1205					phba->lpfc_injerr_lba =
1206						LPFC_INJERR_LBA_OFF;
1207					memset(&phba->lpfc_injerr_wwpn,
1208						0, sizeof(struct lpfc_name));
1209				}
1210				rc = BG_ERR_TGT | BG_ERR_CHECK;
1211
1212				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1213					"0813 BLKGRD: Injecting apptag error: "
1214					"write lba x%lx\n", (unsigned long)lba);
1215				break;
1216			case SCSI_PROT_WRITE_STRIP:
1217				/*
1218				 * For WRITE_STRIP and WRITE_PASS,
1219				 * force the error on data
1220				 * being copied from SLI-Host to SLI-Port.
1221				 */
1222				*apptag = 0xDEAD;
1223				phba->lpfc_injerr_wapp_cnt--;
1224				if (phba->lpfc_injerr_wapp_cnt == 0) {
1225					phba->lpfc_injerr_nportid = 0;
1226					phba->lpfc_injerr_lba =
1227						LPFC_INJERR_LBA_OFF;
1228					memset(&phba->lpfc_injerr_wwpn,
1229						0, sizeof(struct lpfc_name));
1230				}
1231				rc = BG_ERR_INIT;
1232
1233				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1234					"0812 BLKGRD: Injecting apptag error: "
1235					"write lba x%lx\n", (unsigned long)lba);
1236				break;
1237			}
1238		}
1239		if (phba->lpfc_injerr_rapp_cnt) {
1240			switch (op) {
1241			case SCSI_PROT_READ_INSERT:
1242			case SCSI_PROT_READ_STRIP:
1243			case SCSI_PROT_READ_PASS:
1244				/*
1245				 * For READ_STRIP and READ_PASS, force the
1246				 * error on data being read off the wire. It
1247				 * should force an IO error to the driver.
1248				 */
1249				*apptag = 0xDEAD;
1250				phba->lpfc_injerr_rapp_cnt--;
1251				if (phba->lpfc_injerr_rapp_cnt == 0) {
1252					phba->lpfc_injerr_nportid = 0;
1253					phba->lpfc_injerr_lba =
1254						LPFC_INJERR_LBA_OFF;
1255					memset(&phba->lpfc_injerr_wwpn,
1256						0, sizeof(struct lpfc_name));
1257				}
1258				rc = BG_ERR_INIT;
1259
1260				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1261					"0814 BLKGRD: Injecting apptag error: "
1262					"read lba x%lx\n", (unsigned long)lba);
1263				break;
1264			}
1265		}
1266	}
1267
1268
1269	/* Should we change the Guard Tag */
1270	if (new_guard) {
1271		if (phba->lpfc_injerr_wgrd_cnt) {
1272			switch (op) {
1273			case SCSI_PROT_WRITE_PASS:
1274				rc = BG_ERR_CHECK;
1275				fallthrough;
1276
1277			case SCSI_PROT_WRITE_INSERT:
1278				/*
1279				 * For WRITE_INSERT, force the
1280				 * error to be sent on the wire. It should be
1281				 * detected by the Target.
1282				 */
1283				phba->lpfc_injerr_wgrd_cnt--;
1284				if (phba->lpfc_injerr_wgrd_cnt == 0) {
1285					phba->lpfc_injerr_nportid = 0;
1286					phba->lpfc_injerr_lba =
1287						LPFC_INJERR_LBA_OFF;
1288					memset(&phba->lpfc_injerr_wwpn,
1289						0, sizeof(struct lpfc_name));
1290				}
1291
1292				rc |= BG_ERR_TGT | BG_ERR_SWAP;
1293				/* Signals the caller to swap CRC->CSUM */
1294
1295				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1296					"0817 BLKGRD: Injecting guard error: "
1297					"write lba x%lx\n", (unsigned long)lba);
1298				break;
1299			case SCSI_PROT_WRITE_STRIP:
1300				/*
1301				 * For WRITE_STRIP and WRITE_PASS,
1302				 * force the error on data
1303				 * being copied from SLI-Host to SLI-Port.
1304				 */
1305				phba->lpfc_injerr_wgrd_cnt--;
1306				if (phba->lpfc_injerr_wgrd_cnt == 0) {
1307					phba->lpfc_injerr_nportid = 0;
1308					phba->lpfc_injerr_lba =
1309						LPFC_INJERR_LBA_OFF;
1310					memset(&phba->lpfc_injerr_wwpn,
1311						0, sizeof(struct lpfc_name));
1312				}
1313
1314				rc = BG_ERR_INIT | BG_ERR_SWAP;
1315				/* Signals the caller to swap CRC->CSUM */
1316
1317				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1318					"0816 BLKGRD: Injecting guard error: "
1319					"write lba x%lx\n", (unsigned long)lba);
1320				break;
1321			}
1322		}
1323		if (phba->lpfc_injerr_rgrd_cnt) {
1324			switch (op) {
1325			case SCSI_PROT_READ_INSERT:
1326			case SCSI_PROT_READ_STRIP:
1327			case SCSI_PROT_READ_PASS:
1328				/*
1329				 * For READ_STRIP and READ_PASS, force the
1330				 * error on data being read off the wire. It
1331				 * should force an IO error to the driver.
1332				 */
1333				phba->lpfc_injerr_rgrd_cnt--;
1334				if (phba->lpfc_injerr_rgrd_cnt == 0) {
1335					phba->lpfc_injerr_nportid = 0;
1336					phba->lpfc_injerr_lba =
1337						LPFC_INJERR_LBA_OFF;
1338					memset(&phba->lpfc_injerr_wwpn,
1339						0, sizeof(struct lpfc_name));
1340				}
1341
1342				rc = BG_ERR_INIT | BG_ERR_SWAP;
1343				/* Signals the caller to swap CRC->CSUM */
1344
1345				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1346					"0818 BLKGRD: Injecting guard error: "
1347					"read lba x%lx\n", (unsigned long)lba);
1348			}
1349		}
1350	}
1351
1352	return rc;
1353}
1354#endif
1355
1356/**
1357 * lpfc_sc_to_bg_opcodes - Determine the BlockGuard opcodes to be used with
1358 * the specified SCSI command.
1359 * @phba: The Hba for which this call is being executed.
1360 * @sc: The SCSI command to examine
1361 * @txop: (out) BlockGuard operation for transmitted data
1362 * @rxop: (out) BlockGuard operation for received data
1363 *
1364 * Returns: zero on success; non-zero if tx and/or rx op cannot be determined
1365 *
1366 **/
1367static int
1368lpfc_sc_to_bg_opcodes(struct lpfc_hba *phba, struct scsi_cmnd *sc,
1369		uint8_t *txop, uint8_t *rxop)
1370{
1371	uint8_t ret = 0;
1372
1373	if (sc->prot_flags & SCSI_PROT_IP_CHECKSUM) {
1374		switch (scsi_get_prot_op(sc)) {
1375		case SCSI_PROT_READ_INSERT:
1376		case SCSI_PROT_WRITE_STRIP:
1377			*rxop = BG_OP_IN_NODIF_OUT_CSUM;
1378			*txop = BG_OP_IN_CSUM_OUT_NODIF;
1379			break;
1380
1381		case SCSI_PROT_READ_STRIP:
1382		case SCSI_PROT_WRITE_INSERT:
1383			*rxop = BG_OP_IN_CRC_OUT_NODIF;
1384			*txop = BG_OP_IN_NODIF_OUT_CRC;
1385			break;
1386
1387		case SCSI_PROT_READ_PASS:
1388		case SCSI_PROT_WRITE_PASS:
1389			*rxop = BG_OP_IN_CRC_OUT_CSUM;
1390			*txop = BG_OP_IN_CSUM_OUT_CRC;
1391			break;
1392
1393		case SCSI_PROT_NORMAL:
1394		default:
1395			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1396				"9063 BLKGRD: Bad op/guard:%d/IP combination\n",
1397					scsi_get_prot_op(sc));
1398			ret = 1;
1399			break;
1400
1401		}
1402	} else {
1403		switch (scsi_get_prot_op(sc)) {
1404		case SCSI_PROT_READ_STRIP:
1405		case SCSI_PROT_WRITE_INSERT:
1406			*rxop = BG_OP_IN_CRC_OUT_NODIF;
1407			*txop = BG_OP_IN_NODIF_OUT_CRC;
1408			break;
1409
1410		case SCSI_PROT_READ_PASS:
1411		case SCSI_PROT_WRITE_PASS:
1412			*rxop = BG_OP_IN_CRC_OUT_CRC;
1413			*txop = BG_OP_IN_CRC_OUT_CRC;
1414			break;
1415
1416		case SCSI_PROT_READ_INSERT:
1417		case SCSI_PROT_WRITE_STRIP:
1418			*rxop = BG_OP_IN_NODIF_OUT_CRC;
1419			*txop = BG_OP_IN_CRC_OUT_NODIF;
1420			break;
1421
1422		case SCSI_PROT_NORMAL:
1423		default:
1424			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1425				"9075 BLKGRD: Bad op/guard:%d/CRC combination\n",
1426					scsi_get_prot_op(sc));
1427			ret = 1;
1428			break;
1429		}
1430	}
1431
1432	return ret;
1433}
1434
1435#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
1436/**
1437 * lpfc_bg_err_opcodes - reDetermine the BlockGuard opcodes to be used with
1438 * the specified SCSI command in order to force a guard tag error.
1439 * @phba: The Hba for which this call is being executed.
1440 * @sc: The SCSI command to examine
1441 * @txop: (out) BlockGuard operation for transmitted data
1442 * @rxop: (out) BlockGuard operation for received data
1443 *
1444 * Returns: zero on success; non-zero if tx and/or rx op cannot be determined
1445 *
1446 **/
1447static int
1448lpfc_bg_err_opcodes(struct lpfc_hba *phba, struct scsi_cmnd *sc,
1449		uint8_t *txop, uint8_t *rxop)
1450{
1451
1452	if (sc->prot_flags & SCSI_PROT_IP_CHECKSUM) {
1453		switch (scsi_get_prot_op(sc)) {
1454		case SCSI_PROT_READ_INSERT:
1455		case SCSI_PROT_WRITE_STRIP:
1456			*rxop = BG_OP_IN_NODIF_OUT_CRC;
1457			*txop = BG_OP_IN_CRC_OUT_NODIF;
1458			break;
1459
1460		case SCSI_PROT_READ_STRIP:
1461		case SCSI_PROT_WRITE_INSERT:
1462			*rxop = BG_OP_IN_CSUM_OUT_NODIF;
1463			*txop = BG_OP_IN_NODIF_OUT_CSUM;
1464			break;
1465
1466		case SCSI_PROT_READ_PASS:
1467		case SCSI_PROT_WRITE_PASS:
1468			*rxop = BG_OP_IN_CSUM_OUT_CRC;
1469			*txop = BG_OP_IN_CRC_OUT_CSUM;
1470			break;
1471
1472		case SCSI_PROT_NORMAL:
1473		default:
1474			break;
1475
1476		}
1477	} else {
1478		switch (scsi_get_prot_op(sc)) {
1479		case SCSI_PROT_READ_STRIP:
1480		case SCSI_PROT_WRITE_INSERT:
1481			*rxop = BG_OP_IN_CSUM_OUT_NODIF;
1482			*txop = BG_OP_IN_NODIF_OUT_CSUM;
1483			break;
1484
1485		case SCSI_PROT_READ_PASS:
1486		case SCSI_PROT_WRITE_PASS:
1487			*rxop = BG_OP_IN_CSUM_OUT_CSUM;
1488			*txop = BG_OP_IN_CSUM_OUT_CSUM;
1489			break;
1490
1491		case SCSI_PROT_READ_INSERT:
1492		case SCSI_PROT_WRITE_STRIP:
1493			*rxop = BG_OP_IN_NODIF_OUT_CSUM;
1494			*txop = BG_OP_IN_CSUM_OUT_NODIF;
1495			break;
1496
1497		case SCSI_PROT_NORMAL:
1498		default:
1499			break;
1500		}
1501	}
1502
1503	return 0;
1504}
1505#endif
1506
1507/**
1508 * lpfc_bg_setup_bpl - Setup BlockGuard BPL with no protection data
1509 * @phba: The Hba for which this call is being executed.
1510 * @sc: pointer to scsi command we're working on
1511 * @bpl: pointer to buffer list for protection groups
1512 * @datasegcnt: number of segments of data that have been dma mapped
1513 *
1514 * This function sets up BPL buffer list for protection groups of
1515 * type LPFC_PG_TYPE_NO_DIF
1516 *
1517 * This is usually used when the HBA is instructed to generate
1518 * DIFs and insert them into data stream (or strip DIF from
1519 * incoming data stream)
1520 *
1521 * The buffer list consists of just one protection group described
1522 * below:
1523 *                                +-------------------------+
1524 *   start of prot group  -->     |          PDE_5          |
1525 *                                +-------------------------+
1526 *                                |          PDE_6          |
1527 *                                +-------------------------+
1528 *                                |         Data BDE        |
1529 *                                +-------------------------+
1530 *                                |more Data BDE's ... (opt)|
1531 *                                +-------------------------+
1532 *
1533 *
1534 * Note: Data s/g buffers have been dma mapped
1535 *
1536 * Returns the number of BDEs added to the BPL.
1537 **/
1538static int
1539lpfc_bg_setup_bpl(struct lpfc_hba *phba, struct scsi_cmnd *sc,
1540		struct ulp_bde64 *bpl, int datasegcnt)
1541{
1542	struct scatterlist *sgde = NULL; /* s/g data entry */
1543	struct lpfc_pde5 *pde5 = NULL;
1544	struct lpfc_pde6 *pde6 = NULL;
1545	dma_addr_t physaddr;
1546	int i = 0, num_bde = 0, status;
1547	int datadir = sc->sc_data_direction;
1548#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
1549	uint32_t rc;
1550#endif
1551	uint32_t checking = 1;
1552	uint32_t reftag;
1553	uint8_t txop, rxop;
1554
1555	status  = lpfc_sc_to_bg_opcodes(phba, sc, &txop, &rxop);
1556	if (status)
1557		goto out;
1558
1559	/* extract some info from the scsi command for pde*/
1560	reftag = scsi_prot_ref_tag(sc);
1561
1562#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
1563	rc = lpfc_bg_err_inject(phba, sc, &reftag, NULL, 1);
1564	if (rc) {
1565		if (rc & BG_ERR_SWAP)
1566			lpfc_bg_err_opcodes(phba, sc, &txop, &rxop);
1567		if (rc & BG_ERR_CHECK)
1568			checking = 0;
1569	}
1570#endif
1571
1572	/* setup PDE5 with what we have */
1573	pde5 = (struct lpfc_pde5 *) bpl;
1574	memset(pde5, 0, sizeof(struct lpfc_pde5));
1575	bf_set(pde5_type, pde5, LPFC_PDE5_DESCRIPTOR);
1576
1577	/* Endianness conversion if necessary for PDE5 */
1578	pde5->word0 = cpu_to_le32(pde5->word0);
1579	pde5->reftag = cpu_to_le32(reftag);
1580
1581	/* advance bpl and increment bde count */
1582	num_bde++;
1583	bpl++;
1584	pde6 = (struct lpfc_pde6 *) bpl;
1585
1586	/* setup PDE6 with the rest of the info */
1587	memset(pde6, 0, sizeof(struct lpfc_pde6));
1588	bf_set(pde6_type, pde6, LPFC_PDE6_DESCRIPTOR);
1589	bf_set(pde6_optx, pde6, txop);
1590	bf_set(pde6_oprx, pde6, rxop);
1591
1592	/*
1593	 * We only need to check the data on READs, for WRITEs
1594	 * protection data is automatically generated, not checked.
1595	 */
1596	if (datadir == DMA_FROM_DEVICE) {
1597		if (sc->prot_flags & SCSI_PROT_GUARD_CHECK)
1598			bf_set(pde6_ce, pde6, checking);
1599		else
1600			bf_set(pde6_ce, pde6, 0);
1601
1602		if (sc->prot_flags & SCSI_PROT_REF_CHECK)
1603			bf_set(pde6_re, pde6, checking);
1604		else
1605			bf_set(pde6_re, pde6, 0);
1606	}
1607	bf_set(pde6_ai, pde6, 1);
1608	bf_set(pde6_ae, pde6, 0);
1609	bf_set(pde6_apptagval, pde6, 0);
1610
1611	/* Endianness conversion if necessary for PDE6 */
1612	pde6->word0 = cpu_to_le32(pde6->word0);
1613	pde6->word1 = cpu_to_le32(pde6->word1);
1614	pde6->word2 = cpu_to_le32(pde6->word2);
1615
1616	/* advance bpl and increment bde count */
1617	num_bde++;
1618	bpl++;
1619
1620	/* assumption: caller has already run dma_map_sg on command data */
1621	scsi_for_each_sg(sc, sgde, datasegcnt, i) {
1622		physaddr = sg_dma_address(sgde);
1623		bpl->addrLow = le32_to_cpu(putPaddrLow(physaddr));
1624		bpl->addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
1625		bpl->tus.f.bdeSize = sg_dma_len(sgde);
1626		if (datadir == DMA_TO_DEVICE)
1627			bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
1628		else
1629			bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
1630		bpl->tus.w = le32_to_cpu(bpl->tus.w);
1631		bpl++;
1632		num_bde++;
1633	}
1634
1635out:
1636	return num_bde;
1637}
1638
1639/**
1640 * lpfc_bg_setup_bpl_prot - Setup BlockGuard BPL with protection data
1641 * @phba: The Hba for which this call is being executed.
1642 * @sc: pointer to scsi command we're working on
1643 * @bpl: pointer to buffer list for protection groups
1644 * @datacnt: number of segments of data that have been dma mapped
1645 * @protcnt: number of segment of protection data that have been dma mapped
1646 *
1647 * This function sets up BPL buffer list for protection groups of
1648 * type LPFC_PG_TYPE_DIF
1649 *
1650 * This is usually used when DIFs are in their own buffers,
1651 * separate from the data. The HBA can then by instructed
1652 * to place the DIFs in the outgoing stream.  For read operations,
1653 * The HBA could extract the DIFs and place it in DIF buffers.
1654 *
1655 * The buffer list for this type consists of one or more of the
1656 * protection groups described below:
1657 *                                    +-------------------------+
1658 *   start of first prot group  -->   |          PDE_5          |
1659 *                                    +-------------------------+
1660 *                                    |          PDE_6          |
1661 *                                    +-------------------------+
1662 *                                    |      PDE_7 (Prot BDE)   |
1663 *                                    +-------------------------+
1664 *                                    |        Data BDE         |
1665 *                                    +-------------------------+
1666 *                                    |more Data BDE's ... (opt)|
1667 *                                    +-------------------------+
1668 *   start of new  prot group  -->    |          PDE_5          |
1669 *                                    +-------------------------+
1670 *                                    |          ...            |
1671 *                                    +-------------------------+
1672 *
1673 * Note: It is assumed that both data and protection s/g buffers have been
1674 *       mapped for DMA
1675 *
1676 * Returns the number of BDEs added to the BPL.
1677 **/
1678static int
1679lpfc_bg_setup_bpl_prot(struct lpfc_hba *phba, struct scsi_cmnd *sc,
1680		struct ulp_bde64 *bpl, int datacnt, int protcnt)
1681{
1682	struct scatterlist *sgde = NULL; /* s/g data entry */
1683	struct scatterlist *sgpe = NULL; /* s/g prot entry */
1684	struct lpfc_pde5 *pde5 = NULL;
1685	struct lpfc_pde6 *pde6 = NULL;
1686	struct lpfc_pde7 *pde7 = NULL;
1687	dma_addr_t dataphysaddr, protphysaddr;
1688	unsigned short curr_prot = 0;
1689	unsigned int split_offset;
1690	unsigned int protgroup_len, protgroup_offset = 0, protgroup_remainder;
1691	unsigned int protgrp_blks, protgrp_bytes;
1692	unsigned int remainder, subtotal;
1693	int status;
1694	int datadir = sc->sc_data_direction;
1695	unsigned char pgdone = 0, alldone = 0;
1696	unsigned blksize;
1697#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
1698	uint32_t rc;
1699#endif
1700	uint32_t checking = 1;
1701	uint32_t reftag;
1702	uint8_t txop, rxop;
1703	int num_bde = 0;
1704
1705	sgpe = scsi_prot_sglist(sc);
1706	sgde = scsi_sglist(sc);
1707
1708	if (!sgpe || !sgde) {
1709		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1710				"9020 Invalid s/g entry: data=x%px prot=x%px\n",
1711				sgpe, sgde);
1712		return 0;
1713	}
1714
1715	status = lpfc_sc_to_bg_opcodes(phba, sc, &txop, &rxop);
1716	if (status)
1717		goto out;
1718
1719	/* extract some info from the scsi command */
1720	blksize = scsi_prot_interval(sc);
1721	reftag = scsi_prot_ref_tag(sc);
1722
1723#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
1724	rc = lpfc_bg_err_inject(phba, sc, &reftag, NULL, 1);
1725	if (rc) {
1726		if (rc & BG_ERR_SWAP)
1727			lpfc_bg_err_opcodes(phba, sc, &txop, &rxop);
1728		if (rc & BG_ERR_CHECK)
1729			checking = 0;
1730	}
1731#endif
1732
1733	split_offset = 0;
1734	do {
1735		/* Check to see if we ran out of space */
1736		if (num_bde >= (phba->cfg_total_seg_cnt - 2))
1737			return num_bde + 3;
1738
1739		/* setup PDE5 with what we have */
1740		pde5 = (struct lpfc_pde5 *) bpl;
1741		memset(pde5, 0, sizeof(struct lpfc_pde5));
1742		bf_set(pde5_type, pde5, LPFC_PDE5_DESCRIPTOR);
1743
1744		/* Endianness conversion if necessary for PDE5 */
1745		pde5->word0 = cpu_to_le32(pde5->word0);
1746		pde5->reftag = cpu_to_le32(reftag);
1747
1748		/* advance bpl and increment bde count */
1749		num_bde++;
1750		bpl++;
1751		pde6 = (struct lpfc_pde6 *) bpl;
1752
1753		/* setup PDE6 with the rest of the info */
1754		memset(pde6, 0, sizeof(struct lpfc_pde6));
1755		bf_set(pde6_type, pde6, LPFC_PDE6_DESCRIPTOR);
1756		bf_set(pde6_optx, pde6, txop);
1757		bf_set(pde6_oprx, pde6, rxop);
1758
1759		if (sc->prot_flags & SCSI_PROT_GUARD_CHECK)
1760			bf_set(pde6_ce, pde6, checking);
1761		else
1762			bf_set(pde6_ce, pde6, 0);
1763
1764		if (sc->prot_flags & SCSI_PROT_REF_CHECK)
1765			bf_set(pde6_re, pde6, checking);
1766		else
1767			bf_set(pde6_re, pde6, 0);
1768
1769		bf_set(pde6_ai, pde6, 1);
1770		bf_set(pde6_ae, pde6, 0);
1771		bf_set(pde6_apptagval, pde6, 0);
1772
1773		/* Endianness conversion if necessary for PDE6 */
1774		pde6->word0 = cpu_to_le32(pde6->word0);
1775		pde6->word1 = cpu_to_le32(pde6->word1);
1776		pde6->word2 = cpu_to_le32(pde6->word2);
1777
1778		/* advance bpl and increment bde count */
1779		num_bde++;
1780		bpl++;
1781
1782		/* setup the first BDE that points to protection buffer */
1783		protphysaddr = sg_dma_address(sgpe) + protgroup_offset;
1784		protgroup_len = sg_dma_len(sgpe) - protgroup_offset;
1785
1786		/* must be integer multiple of the DIF block length */
1787		BUG_ON(protgroup_len % 8);
1788
1789		pde7 = (struct lpfc_pde7 *) bpl;
1790		memset(pde7, 0, sizeof(struct lpfc_pde7));
1791		bf_set(pde7_type, pde7, LPFC_PDE7_DESCRIPTOR);
1792
1793		pde7->addrHigh = le32_to_cpu(putPaddrHigh(protphysaddr));
1794		pde7->addrLow = le32_to_cpu(putPaddrLow(protphysaddr));
1795
1796		protgrp_blks = protgroup_len / 8;
1797		protgrp_bytes = protgrp_blks * blksize;
1798
1799		/* check if this pde is crossing the 4K boundary; if so split */
1800		if ((pde7->addrLow & 0xfff) + protgroup_len > 0x1000) {
1801			protgroup_remainder = 0x1000 - (pde7->addrLow & 0xfff);
1802			protgroup_offset += protgroup_remainder;
1803			protgrp_blks = protgroup_remainder / 8;
1804			protgrp_bytes = protgrp_blks * blksize;
1805		} else {
1806			protgroup_offset = 0;
1807			curr_prot++;
1808		}
1809
1810		num_bde++;
1811
1812		/* setup BDE's for data blocks associated with DIF data */
1813		pgdone = 0;
1814		subtotal = 0; /* total bytes processed for current prot grp */
1815		while (!pgdone) {
1816			/* Check to see if we ran out of space */
1817			if (num_bde >= phba->cfg_total_seg_cnt)
1818				return num_bde + 1;
1819
1820			if (!sgde) {
1821				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1822					"9065 BLKGRD:%s Invalid data segment\n",
1823						__func__);
1824				return 0;
1825			}
1826			bpl++;
1827			dataphysaddr = sg_dma_address(sgde) + split_offset;
1828			bpl->addrLow = le32_to_cpu(putPaddrLow(dataphysaddr));
1829			bpl->addrHigh = le32_to_cpu(putPaddrHigh(dataphysaddr));
1830
1831			remainder = sg_dma_len(sgde) - split_offset;
1832
1833			if ((subtotal + remainder) <= protgrp_bytes) {
1834				/* we can use this whole buffer */
1835				bpl->tus.f.bdeSize = remainder;
1836				split_offset = 0;
1837
1838				if ((subtotal + remainder) == protgrp_bytes)
1839					pgdone = 1;
1840			} else {
1841				/* must split this buffer with next prot grp */
1842				bpl->tus.f.bdeSize = protgrp_bytes - subtotal;
1843				split_offset += bpl->tus.f.bdeSize;
1844			}
1845
1846			subtotal += bpl->tus.f.bdeSize;
1847
1848			if (datadir == DMA_TO_DEVICE)
1849				bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
1850			else
1851				bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
1852			bpl->tus.w = le32_to_cpu(bpl->tus.w);
1853
1854			num_bde++;
1855
1856			if (split_offset)
1857				break;
1858
1859			/* Move to the next s/g segment if possible */
1860			sgde = sg_next(sgde);
1861
1862		}
1863
1864		if (protgroup_offset) {
1865			/* update the reference tag */
1866			reftag += protgrp_blks;
1867			bpl++;
1868			continue;
1869		}
1870
1871		/* are we done ? */
1872		if (curr_prot == protcnt) {
1873			alldone = 1;
1874		} else if (curr_prot < protcnt) {
1875			/* advance to next prot buffer */
1876			sgpe = sg_next(sgpe);
1877			bpl++;
1878
1879			/* update the reference tag */
1880			reftag += protgrp_blks;
1881		} else {
1882			/* if we're here, we have a bug */
1883			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1884					"9054 BLKGRD: bug in %s\n", __func__);
1885		}
1886
1887	} while (!alldone);
1888out:
1889
1890	return num_bde;
1891}
1892
1893/**
1894 * lpfc_bg_setup_sgl - Setup BlockGuard SGL with no protection data
1895 * @phba: The Hba for which this call is being executed.
1896 * @sc: pointer to scsi command we're working on
1897 * @sgl: pointer to buffer list for protection groups
1898 * @datasegcnt: number of segments of data that have been dma mapped
1899 * @lpfc_cmd: lpfc scsi command object pointer.
1900 *
1901 * This function sets up SGL buffer list for protection groups of
1902 * type LPFC_PG_TYPE_NO_DIF
1903 *
1904 * This is usually used when the HBA is instructed to generate
1905 * DIFs and insert them into data stream (or strip DIF from
1906 * incoming data stream)
1907 *
1908 * The buffer list consists of just one protection group described
1909 * below:
1910 *                                +-------------------------+
1911 *   start of prot group  -->     |         DI_SEED         |
1912 *                                +-------------------------+
1913 *                                |         Data SGE        |
1914 *                                +-------------------------+
1915 *                                |more Data SGE's ... (opt)|
1916 *                                +-------------------------+
1917 *
1918 *
1919 * Note: Data s/g buffers have been dma mapped
1920 *
1921 * Returns the number of SGEs added to the SGL.
1922 **/
1923static uint32_t
1924lpfc_bg_setup_sgl(struct lpfc_hba *phba, struct scsi_cmnd *sc,
1925		struct sli4_sge *sgl, int datasegcnt,
1926		struct lpfc_io_buf *lpfc_cmd)
1927{
1928	struct scatterlist *sgde = NULL; /* s/g data entry */
1929	struct sli4_sge_diseed *diseed = NULL;
1930	dma_addr_t physaddr;
1931	int i = 0, status;
1932	uint32_t reftag, num_sge = 0;
1933	uint8_t txop, rxop;
1934#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
1935	uint32_t rc;
1936#endif
1937	uint32_t checking = 1;
1938	uint32_t dma_len;
1939	uint32_t dma_offset = 0;
1940	struct sli4_hybrid_sgl *sgl_xtra = NULL;
1941	int j;
1942	bool lsp_just_set = false;
1943
1944	status  = lpfc_sc_to_bg_opcodes(phba, sc, &txop, &rxop);
1945	if (status)
1946		goto out;
1947
1948	/* extract some info from the scsi command for pde*/
1949	reftag = scsi_prot_ref_tag(sc);
1950
1951#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
1952	rc = lpfc_bg_err_inject(phba, sc, &reftag, NULL, 1);
1953	if (rc) {
1954		if (rc & BG_ERR_SWAP)
1955			lpfc_bg_err_opcodes(phba, sc, &txop, &rxop);
1956		if (rc & BG_ERR_CHECK)
1957			checking = 0;
1958	}
1959#endif
1960
1961	/* setup DISEED with what we have */
1962	diseed = (struct sli4_sge_diseed *) sgl;
1963	memset(diseed, 0, sizeof(struct sli4_sge_diseed));
1964	bf_set(lpfc_sli4_sge_type, sgl, LPFC_SGE_TYPE_DISEED);
1965
1966	/* Endianness conversion if necessary */
1967	diseed->ref_tag = cpu_to_le32(reftag);
1968	diseed->ref_tag_tran = diseed->ref_tag;
1969
1970	/*
1971	 * We only need to check the data on READs, for WRITEs
1972	 * protection data is automatically generated, not checked.
1973	 */
1974	if (sc->sc_data_direction == DMA_FROM_DEVICE) {
1975		if (sc->prot_flags & SCSI_PROT_GUARD_CHECK)
1976			bf_set(lpfc_sli4_sge_dif_ce, diseed, checking);
1977		else
1978			bf_set(lpfc_sli4_sge_dif_ce, diseed, 0);
1979
1980		if (sc->prot_flags & SCSI_PROT_REF_CHECK)
1981			bf_set(lpfc_sli4_sge_dif_re, diseed, checking);
1982		else
1983			bf_set(lpfc_sli4_sge_dif_re, diseed, 0);
1984	}
1985
1986	/* setup DISEED with the rest of the info */
1987	bf_set(lpfc_sli4_sge_dif_optx, diseed, txop);
1988	bf_set(lpfc_sli4_sge_dif_oprx, diseed, rxop);
1989
1990	bf_set(lpfc_sli4_sge_dif_ai, diseed, 1);
1991	bf_set(lpfc_sli4_sge_dif_me, diseed, 0);
1992
1993	/* Endianness conversion if necessary for DISEED */
1994	diseed->word2 = cpu_to_le32(diseed->word2);
1995	diseed->word3 = cpu_to_le32(diseed->word3);
1996
1997	/* advance bpl and increment sge count */
1998	num_sge++;
1999	sgl++;
2000
2001	/* assumption: caller has already run dma_map_sg on command data */
2002	sgde = scsi_sglist(sc);
2003	j = 3;
2004	for (i = 0; i < datasegcnt; i++) {
2005		/* clear it */
2006		sgl->word2 = 0;
2007
2008		/* do we need to expand the segment */
2009		if (!lsp_just_set && !((j + 1) % phba->border_sge_num) &&
2010		    ((datasegcnt - 1) != i)) {
2011			/* set LSP type */
2012			bf_set(lpfc_sli4_sge_type, sgl, LPFC_SGE_TYPE_LSP);
2013
2014			sgl_xtra = lpfc_get_sgl_per_hdwq(phba, lpfc_cmd);
2015
2016			if (unlikely(!sgl_xtra)) {
2017				lpfc_cmd->seg_cnt = 0;
2018				return 0;
2019			}
2020			sgl->addr_lo = cpu_to_le32(putPaddrLow(
2021						sgl_xtra->dma_phys_sgl));
2022			sgl->addr_hi = cpu_to_le32(putPaddrHigh(
2023						sgl_xtra->dma_phys_sgl));
2024
2025		} else {
2026			bf_set(lpfc_sli4_sge_type, sgl, LPFC_SGE_TYPE_DATA);
2027		}
2028
2029		if (!(bf_get(lpfc_sli4_sge_type, sgl) & LPFC_SGE_TYPE_LSP)) {
2030			if ((datasegcnt - 1) == i)
2031				bf_set(lpfc_sli4_sge_last, sgl, 1);
2032			physaddr = sg_dma_address(sgde);
2033			dma_len = sg_dma_len(sgde);
2034			sgl->addr_lo = cpu_to_le32(putPaddrLow(physaddr));
2035			sgl->addr_hi = cpu_to_le32(putPaddrHigh(physaddr));
2036
2037			bf_set(lpfc_sli4_sge_offset, sgl, dma_offset);
2038			sgl->word2 = cpu_to_le32(sgl->word2);
2039			sgl->sge_len = cpu_to_le32(dma_len);
2040
2041			dma_offset += dma_len;
2042			sgde = sg_next(sgde);
2043
2044			sgl++;
2045			num_sge++;
2046			lsp_just_set = false;
2047
2048		} else {
2049			sgl->word2 = cpu_to_le32(sgl->word2);
2050			sgl->sge_len = cpu_to_le32(phba->cfg_sg_dma_buf_size);
2051
2052			sgl = (struct sli4_sge *)sgl_xtra->dma_sgl;
2053			i = i - 1;
2054
2055			lsp_just_set = true;
2056		}
2057
2058		j++;
2059
2060	}
2061
2062out:
2063	return num_sge;
2064}
2065
2066/**
2067 * lpfc_bg_setup_sgl_prot - Setup BlockGuard SGL with protection data
2068 * @phba: The Hba for which this call is being executed.
2069 * @sc: pointer to scsi command we're working on
2070 * @sgl: pointer to buffer list for protection groups
2071 * @datacnt: number of segments of data that have been dma mapped
2072 * @protcnt: number of segment of protection data that have been dma mapped
2073 * @lpfc_cmd: lpfc scsi command object pointer.
2074 *
2075 * This function sets up SGL buffer list for protection groups of
2076 * type LPFC_PG_TYPE_DIF
2077 *
2078 * This is usually used when DIFs are in their own buffers,
2079 * separate from the data. The HBA can then by instructed
2080 * to place the DIFs in the outgoing stream.  For read operations,
2081 * The HBA could extract the DIFs and place it in DIF buffers.
2082 *
2083 * The buffer list for this type consists of one or more of the
2084 * protection groups described below:
2085 *                                    +-------------------------+
2086 *   start of first prot group  -->   |         DISEED          |
2087 *                                    +-------------------------+
2088 *                                    |      DIF (Prot SGE)     |
2089 *                                    +-------------------------+
2090 *                                    |        Data SGE         |
2091 *                                    +-------------------------+
2092 *                                    |more Data SGE's ... (opt)|
2093 *                                    +-------------------------+
2094 *   start of new  prot group  -->    |         DISEED          |
2095 *                                    +-------------------------+
2096 *                                    |          ...            |
2097 *                                    +-------------------------+
2098 *
2099 * Note: It is assumed that both data and protection s/g buffers have been
2100 *       mapped for DMA
2101 *
2102 * Returns the number of SGEs added to the SGL.
2103 **/
2104static uint32_t
2105lpfc_bg_setup_sgl_prot(struct lpfc_hba *phba, struct scsi_cmnd *sc,
2106		struct sli4_sge *sgl, int datacnt, int protcnt,
2107		struct lpfc_io_buf *lpfc_cmd)
2108{
2109	struct scatterlist *sgde = NULL; /* s/g data entry */
2110	struct scatterlist *sgpe = NULL; /* s/g prot entry */
2111	struct sli4_sge_diseed *diseed = NULL;
2112	dma_addr_t dataphysaddr, protphysaddr;
2113	unsigned short curr_prot = 0;
2114	unsigned int split_offset;
2115	unsigned int protgroup_len, protgroup_offset = 0, protgroup_remainder;
2116	unsigned int protgrp_blks, protgrp_bytes;
2117	unsigned int remainder, subtotal;
2118	int status;
2119	unsigned char pgdone = 0, alldone = 0;
2120	unsigned blksize;
2121	uint32_t reftag;
2122	uint8_t txop, rxop;
2123	uint32_t dma_len;
2124#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
2125	uint32_t rc;
2126#endif
2127	uint32_t checking = 1;
2128	uint32_t dma_offset = 0, num_sge = 0;
2129	int j = 2;
2130	struct sli4_hybrid_sgl *sgl_xtra = NULL;
2131
2132	sgpe = scsi_prot_sglist(sc);
2133	sgde = scsi_sglist(sc);
2134
2135	if (!sgpe || !sgde) {
2136		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2137				"9082 Invalid s/g entry: data=x%px prot=x%px\n",
2138				sgpe, sgde);
2139		return 0;
2140	}
2141
2142	status = lpfc_sc_to_bg_opcodes(phba, sc, &txop, &rxop);
2143	if (status)
2144		goto out;
2145
2146	/* extract some info from the scsi command */
2147	blksize = scsi_prot_interval(sc);
2148	reftag = scsi_prot_ref_tag(sc);
2149
2150#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
2151	rc = lpfc_bg_err_inject(phba, sc, &reftag, NULL, 1);
2152	if (rc) {
2153		if (rc & BG_ERR_SWAP)
2154			lpfc_bg_err_opcodes(phba, sc, &txop, &rxop);
2155		if (rc & BG_ERR_CHECK)
2156			checking = 0;
2157	}
2158#endif
2159
2160	split_offset = 0;
2161	do {
2162		/* Check to see if we ran out of space */
2163		if ((num_sge >= (phba->cfg_total_seg_cnt - 2)) &&
2164		    !(phba->cfg_xpsgl))
2165			return num_sge + 3;
2166
2167		/* DISEED and DIF have to be together */
2168		if (!((j + 1) % phba->border_sge_num) ||
2169		    !((j + 2) % phba->border_sge_num) ||
2170		    !((j + 3) % phba->border_sge_num)) {
2171			sgl->word2 = 0;
2172
2173			/* set LSP type */
2174			bf_set(lpfc_sli4_sge_type, sgl, LPFC_SGE_TYPE_LSP);
2175
2176			sgl_xtra = lpfc_get_sgl_per_hdwq(phba, lpfc_cmd);
2177
2178			if (unlikely(!sgl_xtra)) {
2179				goto out;
2180			} else {
2181				sgl->addr_lo = cpu_to_le32(putPaddrLow(
2182						sgl_xtra->dma_phys_sgl));
2183				sgl->addr_hi = cpu_to_le32(putPaddrHigh(
2184						       sgl_xtra->dma_phys_sgl));
2185			}
2186
2187			sgl->word2 = cpu_to_le32(sgl->word2);
2188			sgl->sge_len = cpu_to_le32(phba->cfg_sg_dma_buf_size);
2189
2190			sgl = (struct sli4_sge *)sgl_xtra->dma_sgl;
2191			j = 0;
2192		}
2193
2194		/* setup DISEED with what we have */
2195		diseed = (struct sli4_sge_diseed *) sgl;
2196		memset(diseed, 0, sizeof(struct sli4_sge_diseed));
2197		bf_set(lpfc_sli4_sge_type, sgl, LPFC_SGE_TYPE_DISEED);
2198
2199		/* Endianness conversion if necessary */
2200		diseed->ref_tag = cpu_to_le32(reftag);
2201		diseed->ref_tag_tran = diseed->ref_tag;
2202
2203		if (sc->prot_flags & SCSI_PROT_GUARD_CHECK) {
2204			bf_set(lpfc_sli4_sge_dif_ce, diseed, checking);
2205		} else {
2206			bf_set(lpfc_sli4_sge_dif_ce, diseed, 0);
2207			/*
2208			 * When in this mode, the hardware will replace
2209			 * the guard tag from the host with a
2210			 * newly generated good CRC for the wire.
2211			 * Switch to raw mode here to avoid this
2212			 * behavior. What the host sends gets put on the wire.
2213			 */
2214			if (txop == BG_OP_IN_CRC_OUT_CRC) {
2215				txop = BG_OP_RAW_MODE;
2216				rxop = BG_OP_RAW_MODE;
2217			}
2218		}
2219
2220
2221		if (sc->prot_flags & SCSI_PROT_REF_CHECK)
2222			bf_set(lpfc_sli4_sge_dif_re, diseed, checking);
2223		else
2224			bf_set(lpfc_sli4_sge_dif_re, diseed, 0);
2225
2226		/* setup DISEED with the rest of the info */
2227		bf_set(lpfc_sli4_sge_dif_optx, diseed, txop);
2228		bf_set(lpfc_sli4_sge_dif_oprx, diseed, rxop);
2229
2230		bf_set(lpfc_sli4_sge_dif_ai, diseed, 1);
2231		bf_set(lpfc_sli4_sge_dif_me, diseed, 0);
2232
2233		/* Endianness conversion if necessary for DISEED */
2234		diseed->word2 = cpu_to_le32(diseed->word2);
2235		diseed->word3 = cpu_to_le32(diseed->word3);
2236
2237		/* advance sgl and increment bde count */
2238		num_sge++;
2239
2240		sgl++;
2241		j++;
2242
2243		/* setup the first BDE that points to protection buffer */
2244		protphysaddr = sg_dma_address(sgpe) + protgroup_offset;
2245		protgroup_len = sg_dma_len(sgpe) - protgroup_offset;
2246
2247		/* must be integer multiple of the DIF block length */
2248		BUG_ON(protgroup_len % 8);
2249
2250		/* Now setup DIF SGE */
2251		sgl->word2 = 0;
2252		bf_set(lpfc_sli4_sge_type, sgl, LPFC_SGE_TYPE_DIF);
2253		sgl->addr_hi = le32_to_cpu(putPaddrHigh(protphysaddr));
2254		sgl->addr_lo = le32_to_cpu(putPaddrLow(protphysaddr));
2255		sgl->word2 = cpu_to_le32(sgl->word2);
2256		sgl->sge_len = 0;
2257
2258		protgrp_blks = protgroup_len / 8;
2259		protgrp_bytes = protgrp_blks * blksize;
2260
2261		/* check if DIF SGE is crossing the 4K boundary; if so split */
2262		if ((sgl->addr_lo & 0xfff) + protgroup_len > 0x1000) {
2263			protgroup_remainder = 0x1000 - (sgl->addr_lo & 0xfff);
2264			protgroup_offset += protgroup_remainder;
2265			protgrp_blks = protgroup_remainder / 8;
2266			protgrp_bytes = protgrp_blks * blksize;
2267		} else {
2268			protgroup_offset = 0;
2269			curr_prot++;
2270		}
2271
2272		num_sge++;
2273
2274		/* setup SGE's for data blocks associated with DIF data */
2275		pgdone = 0;
2276		subtotal = 0; /* total bytes processed for current prot grp */
2277
2278		sgl++;
2279		j++;
2280
2281		while (!pgdone) {
2282			/* Check to see if we ran out of space */
2283			if ((num_sge >= phba->cfg_total_seg_cnt) &&
2284			    !phba->cfg_xpsgl)
2285				return num_sge + 1;
2286
2287			if (!sgde) {
2288				lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2289					"9086 BLKGRD:%s Invalid data segment\n",
2290						__func__);
2291				return 0;
2292			}
2293
2294			if (!((j + 1) % phba->border_sge_num)) {
2295				sgl->word2 = 0;
2296
2297				/* set LSP type */
2298				bf_set(lpfc_sli4_sge_type, sgl,
2299				       LPFC_SGE_TYPE_LSP);
2300
2301				sgl_xtra = lpfc_get_sgl_per_hdwq(phba,
2302								 lpfc_cmd);
2303
2304				if (unlikely(!sgl_xtra)) {
2305					goto out;
2306				} else {
2307					sgl->addr_lo = cpu_to_le32(
2308					  putPaddrLow(sgl_xtra->dma_phys_sgl));
2309					sgl->addr_hi = cpu_to_le32(
2310					  putPaddrHigh(sgl_xtra->dma_phys_sgl));
2311				}
2312
2313				sgl->word2 = cpu_to_le32(sgl->word2);
2314				sgl->sge_len = cpu_to_le32(
2315						     phba->cfg_sg_dma_buf_size);
2316
2317				sgl = (struct sli4_sge *)sgl_xtra->dma_sgl;
2318			} else {
2319				dataphysaddr = sg_dma_address(sgde) +
2320								   split_offset;
2321
2322				remainder = sg_dma_len(sgde) - split_offset;
2323
2324				if ((subtotal + remainder) <= protgrp_bytes) {
2325					/* we can use this whole buffer */
2326					dma_len = remainder;
2327					split_offset = 0;
2328
2329					if ((subtotal + remainder) ==
2330								  protgrp_bytes)
2331						pgdone = 1;
2332				} else {
2333					/* must split this buffer with next
2334					 * prot grp
2335					 */
2336					dma_len = protgrp_bytes - subtotal;
2337					split_offset += dma_len;
2338				}
2339
2340				subtotal += dma_len;
2341
2342				sgl->word2 = 0;
2343				sgl->addr_lo = cpu_to_le32(putPaddrLow(
2344								 dataphysaddr));
2345				sgl->addr_hi = cpu_to_le32(putPaddrHigh(
2346								 dataphysaddr));
2347				bf_set(lpfc_sli4_sge_last, sgl, 0);
2348				bf_set(lpfc_sli4_sge_offset, sgl, dma_offset);
2349				bf_set(lpfc_sli4_sge_type, sgl,
2350				       LPFC_SGE_TYPE_DATA);
2351
2352				sgl->sge_len = cpu_to_le32(dma_len);
2353				dma_offset += dma_len;
2354
2355				num_sge++;
2356
2357				if (split_offset) {
2358					sgl++;
2359					j++;
2360					break;
2361				}
2362
2363				/* Move to the next s/g segment if possible */
2364				sgde = sg_next(sgde);
2365
2366				sgl++;
2367			}
2368
2369			j++;
2370		}
2371
2372		if (protgroup_offset) {
2373			/* update the reference tag */
2374			reftag += protgrp_blks;
2375			continue;
2376		}
2377
2378		/* are we done ? */
2379		if (curr_prot == protcnt) {
2380			/* mark the last SGL */
2381			sgl--;
2382			bf_set(lpfc_sli4_sge_last, sgl, 1);
2383			alldone = 1;
2384		} else if (curr_prot < protcnt) {
2385			/* advance to next prot buffer */
2386			sgpe = sg_next(sgpe);
2387
2388			/* update the reference tag */
2389			reftag += protgrp_blks;
2390		} else {
2391			/* if we're here, we have a bug */
2392			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2393					"9085 BLKGRD: bug in %s\n", __func__);
2394		}
2395
2396	} while (!alldone);
2397
2398out:
2399
2400	return num_sge;
2401}
2402
2403/**
2404 * lpfc_prot_group_type - Get prtotection group type of SCSI command
2405 * @phba: The Hba for which this call is being executed.
2406 * @sc: pointer to scsi command we're working on
2407 *
2408 * Given a SCSI command that supports DIF, determine composition of protection
2409 * groups involved in setting up buffer lists
2410 *
2411 * Returns: Protection group type (with or without DIF)
2412 *
2413 **/
2414static int
2415lpfc_prot_group_type(struct lpfc_hba *phba, struct scsi_cmnd *sc)
2416{
2417	int ret = LPFC_PG_TYPE_INVALID;
2418	unsigned char op = scsi_get_prot_op(sc);
2419
2420	switch (op) {
2421	case SCSI_PROT_READ_STRIP:
2422	case SCSI_PROT_WRITE_INSERT:
2423		ret = LPFC_PG_TYPE_NO_DIF;
2424		break;
2425	case SCSI_PROT_READ_INSERT:
2426	case SCSI_PROT_WRITE_STRIP:
2427	case SCSI_PROT_READ_PASS:
2428	case SCSI_PROT_WRITE_PASS:
2429		ret = LPFC_PG_TYPE_DIF_BUF;
2430		break;
2431	default:
2432		if (phba)
2433			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2434					"9021 Unsupported protection op:%d\n",
2435					op);
2436		break;
2437	}
2438	return ret;
2439}
2440
2441/**
2442 * lpfc_bg_scsi_adjust_dl - Adjust SCSI data length for BlockGuard
2443 * @phba: The Hba for which this call is being executed.
2444 * @lpfc_cmd: The scsi buffer which is going to be adjusted.
2445 *
2446 * Adjust the data length to account for how much data
2447 * is actually on the wire.
2448 *
2449 * returns the adjusted data length
2450 **/
2451static int
2452lpfc_bg_scsi_adjust_dl(struct lpfc_hba *phba,
2453		       struct lpfc_io_buf *lpfc_cmd)
2454{
2455	struct scsi_cmnd *sc = lpfc_cmd->pCmd;
2456	int fcpdl;
2457
2458	fcpdl = scsi_bufflen(sc);
2459
2460	/* Check if there is protection data on the wire */
2461	if (sc->sc_data_direction == DMA_FROM_DEVICE) {
2462		/* Read check for protection data */
2463		if (scsi_get_prot_op(sc) ==  SCSI_PROT_READ_INSERT)
2464			return fcpdl;
2465
2466	} else {
2467		/* Write check for protection data */
2468		if (scsi_get_prot_op(sc) ==  SCSI_PROT_WRITE_STRIP)
2469			return fcpdl;
2470	}
2471
2472	/*
2473	 * If we are in DIF Type 1 mode every data block has a 8 byte
2474	 * DIF (trailer) attached to it. Must ajust FCP data length
2475	 * to account for the protection data.
2476	 */
2477	fcpdl += (fcpdl / scsi_prot_interval(sc)) * 8;
2478
2479	return fcpdl;
2480}
2481
2482/**
2483 * lpfc_bg_scsi_prep_dma_buf_s3 - DMA mapping for scsi buffer to SLI3 IF spec
2484 * @phba: The Hba for which this call is being executed.
2485 * @lpfc_cmd: The scsi buffer which is going to be prep'ed.
2486 *
2487 * This is the protection/DIF aware version of
2488 * lpfc_scsi_prep_dma_buf(). It may be a good idea to combine the
2489 * two functions eventually, but for now, it's here.
2490 * RETURNS 0 - SUCCESS,
2491 *         1 - Failed DMA map, retry.
2492 *         2 - Invalid scsi cmd or prot-type. Do not rety.
2493 **/
2494static int
2495lpfc_bg_scsi_prep_dma_buf_s3(struct lpfc_hba *phba,
2496		struct lpfc_io_buf *lpfc_cmd)
2497{
2498	struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
2499	struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
2500	struct ulp_bde64 *bpl = (struct ulp_bde64 *)lpfc_cmd->dma_sgl;
2501	IOCB_t *iocb_cmd = &lpfc_cmd->cur_iocbq.iocb;
2502	uint32_t num_bde = 0;
2503	int datasegcnt, protsegcnt, datadir = scsi_cmnd->sc_data_direction;
2504	int prot_group_type = 0;
2505	int fcpdl;
2506	int ret = 1;
2507	struct lpfc_vport *vport = phba->pport;
2508
2509	/*
2510	 * Start the lpfc command prep by bumping the bpl beyond fcp_cmnd
2511	 *  fcp_rsp regions to the first data bde entry
2512	 */
2513	bpl += 2;
2514	if (scsi_sg_count(scsi_cmnd)) {
2515		/*
2516		 * The driver stores the segment count returned from dma_map_sg
2517		 * because this a count of dma-mappings used to map the use_sg
2518		 * pages.  They are not guaranteed to be the same for those
2519		 * architectures that implement an IOMMU.
2520		 */
2521		datasegcnt = dma_map_sg(&phba->pcidev->dev,
2522					scsi_sglist(scsi_cmnd),
2523					scsi_sg_count(scsi_cmnd), datadir);
2524		if (unlikely(!datasegcnt))
2525			return 1;
2526
2527		lpfc_cmd->seg_cnt = datasegcnt;
2528
2529		/* First check if data segment count from SCSI Layer is good */
2530		if (lpfc_cmd->seg_cnt > phba->cfg_sg_seg_cnt) {
2531			WARN_ON_ONCE(lpfc_cmd->seg_cnt > phba->cfg_sg_seg_cnt);
2532			ret = 2;
2533			goto err;
2534		}
2535
2536		prot_group_type = lpfc_prot_group_type(phba, scsi_cmnd);
2537
2538		switch (prot_group_type) {
2539		case LPFC_PG_TYPE_NO_DIF:
2540
2541			/* Here we need to add a PDE5 and PDE6 to the count */
2542			if ((lpfc_cmd->seg_cnt + 2) > phba->cfg_total_seg_cnt) {
2543				ret = 2;
2544				goto err;
2545			}
2546
2547			num_bde = lpfc_bg_setup_bpl(phba, scsi_cmnd, bpl,
2548					datasegcnt);
2549			/* we should have 2 or more entries in buffer list */
2550			if (num_bde < 2) {
2551				ret = 2;
2552				goto err;
2553			}
2554			break;
2555
2556		case LPFC_PG_TYPE_DIF_BUF:
2557			/*
2558			 * This type indicates that protection buffers are
2559			 * passed to the driver, so that needs to be prepared
2560			 * for DMA
2561			 */
2562			protsegcnt = dma_map_sg(&phba->pcidev->dev,
2563					scsi_prot_sglist(scsi_cmnd),
2564					scsi_prot_sg_count(scsi_cmnd), datadir);
2565			if (unlikely(!protsegcnt)) {
2566				scsi_dma_unmap(scsi_cmnd);
2567				return 1;
2568			}
2569
2570			lpfc_cmd->prot_seg_cnt = protsegcnt;
2571
2572			/*
2573			 * There is a minimun of 4 BPLs used for every
2574			 * protection data segment.
2575			 */
2576			if ((lpfc_cmd->prot_seg_cnt * 4) >
2577			    (phba->cfg_total_seg_cnt - 2)) {
2578				ret = 2;
2579				goto err;
2580			}
2581
2582			num_bde = lpfc_bg_setup_bpl_prot(phba, scsi_cmnd, bpl,
2583					datasegcnt, protsegcnt);
2584			/* we should have 3 or more entries in buffer list */
2585			if ((num_bde < 3) ||
2586			    (num_bde > phba->cfg_total_seg_cnt)) {
2587				ret = 2;
2588				goto err;
2589			}
2590			break;
2591
2592		case LPFC_PG_TYPE_INVALID:
2593		default:
2594			scsi_dma_unmap(scsi_cmnd);
2595			lpfc_cmd->seg_cnt = 0;
2596
2597			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2598					"9022 Unexpected protection group %i\n",
2599					prot_group_type);
2600			return 2;
2601		}
2602	}
2603
2604	/*
2605	 * Finish initializing those IOCB fields that are dependent on the
2606	 * scsi_cmnd request_buffer.  Note that the bdeSize is explicitly
2607	 * reinitialized since all iocb memory resources are used many times
2608	 * for transmit, receive, and continuation bpl's.
2609	 */
2610	iocb_cmd->un.fcpi64.bdl.bdeSize = (2 * sizeof(struct ulp_bde64));
2611	iocb_cmd->un.fcpi64.bdl.bdeSize += (num_bde * sizeof(struct ulp_bde64));
2612	iocb_cmd->ulpBdeCount = 1;
2613	iocb_cmd->ulpLe = 1;
2614
2615	fcpdl = lpfc_bg_scsi_adjust_dl(phba, lpfc_cmd);
2616	fcp_cmnd->fcpDl = cpu_to_be32(fcpdl);
2617
2618	/*
2619	 * Due to difference in data length between DIF/non-DIF paths,
2620	 * we need to set word 4 of IOCB here
2621	 */
2622	iocb_cmd->un.fcpi.fcpi_parm = fcpdl;
2623
2624	/*
2625	 * For First burst, we may need to adjust the initial transfer
2626	 * length for DIF
2627	 */
2628	if (iocb_cmd->un.fcpi.fcpi_XRdy &&
2629	    (fcpdl < vport->cfg_first_burst_size))
2630		iocb_cmd->un.fcpi.fcpi_XRdy = fcpdl;
2631
2632	return 0;
2633err:
2634	if (lpfc_cmd->seg_cnt)
2635		scsi_dma_unmap(scsi_cmnd);
2636	if (lpfc_cmd->prot_seg_cnt)
2637		dma_unmap_sg(&phba->pcidev->dev, scsi_prot_sglist(scsi_cmnd),
2638			     scsi_prot_sg_count(scsi_cmnd),
2639			     scsi_cmnd->sc_data_direction);
2640
2641	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2642			"9023 Cannot setup S/G List for HBA"
2643			"IO segs %d/%d BPL %d SCSI %d: %d %d\n",
2644			lpfc_cmd->seg_cnt, lpfc_cmd->prot_seg_cnt,
2645			phba->cfg_total_seg_cnt, phba->cfg_sg_seg_cnt,
2646			prot_group_type, num_bde);
2647
2648	lpfc_cmd->seg_cnt = 0;
2649	lpfc_cmd->prot_seg_cnt = 0;
2650	return ret;
2651}
2652
2653/*
2654 * This function calcuates the T10 DIF guard tag
2655 * on the specified data using a CRC algorithmn
2656 * using crc_t10dif.
2657 */
2658static uint16_t
2659lpfc_bg_crc(uint8_t *data, int count)
2660{
2661	uint16_t crc = 0;
2662	uint16_t x;
2663
2664	crc = crc_t10dif(data, count);
2665	x = cpu_to_be16(crc);
2666	return x;
2667}
2668
2669/*
2670 * This function calcuates the T10 DIF guard tag
2671 * on the specified data using a CSUM algorithmn
2672 * using ip_compute_csum.
2673 */
2674static uint16_t
2675lpfc_bg_csum(uint8_t *data, int count)
2676{
2677	uint16_t ret;
2678
2679	ret = ip_compute_csum(data, count);
2680	return ret;
2681}
2682
2683/*
2684 * This function examines the protection data to try to determine
2685 * what type of T10-DIF error occurred.
2686 */
2687static void
2688lpfc_calc_bg_err(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
2689{
2690	struct scatterlist *sgpe; /* s/g prot entry */
2691	struct scatterlist *sgde; /* s/g data entry */
2692	struct scsi_cmnd *cmd = lpfc_cmd->pCmd;
2693	struct scsi_dif_tuple *src = NULL;
2694	uint8_t *data_src = NULL;
2695	uint16_t guard_tag;
2696	uint16_t start_app_tag, app_tag;
2697	uint32_t start_ref_tag, ref_tag;
2698	int prot, protsegcnt;
2699	int err_type, len, data_len;
2700	int chk_ref, chk_app, chk_guard;
2701	uint16_t sum;
2702	unsigned blksize;
2703
2704	err_type = BGS_GUARD_ERR_MASK;
2705	sum = 0;
2706	guard_tag = 0;
2707
2708	/* First check to see if there is protection data to examine */
2709	prot = scsi_get_prot_op(cmd);
2710	if ((prot == SCSI_PROT_READ_STRIP) ||
2711	    (prot == SCSI_PROT_WRITE_INSERT) ||
2712	    (prot == SCSI_PROT_NORMAL))
2713		goto out;
2714
2715	/* Currently the driver just supports ref_tag and guard_tag checking */
2716	chk_ref = 1;
2717	chk_app = 0;
2718	chk_guard = 0;
2719
2720	/* Setup a ptr to the protection data provided by the SCSI host */
2721	sgpe = scsi_prot_sglist(cmd);
2722	protsegcnt = lpfc_cmd->prot_seg_cnt;
2723
2724	if (sgpe && protsegcnt) {
2725
2726		/*
2727		 * We will only try to verify guard tag if the segment
2728		 * data length is a multiple of the blksize.
2729		 */
2730		sgde = scsi_sglist(cmd);
2731		blksize = scsi_prot_interval(cmd);
2732		data_src = (uint8_t *)sg_virt(sgde);
2733		data_len = sg_dma_len(sgde);
2734		if ((data_len & (blksize - 1)) == 0)
2735			chk_guard = 1;
2736
2737		src = (struct scsi_dif_tuple *)sg_virt(sgpe);
2738		start_ref_tag = scsi_prot_ref_tag(cmd);
2739		start_app_tag = src->app_tag;
2740		len = sg_dma_len(sgpe);
2741		while (src && protsegcnt) {
2742			while (len) {
2743
2744				/*
2745				 * First check to see if a protection data
2746				 * check is valid
2747				 */
2748				if ((src->ref_tag == T10_PI_REF_ESCAPE) ||
2749				    (src->app_tag == T10_PI_APP_ESCAPE)) {
2750					start_ref_tag++;
2751					goto skipit;
2752				}
2753
2754				/* First Guard Tag checking */
2755				if (chk_guard) {
2756					guard_tag = src->guard_tag;
2757					if (cmd->prot_flags
2758					    & SCSI_PROT_IP_CHECKSUM)
2759						sum = lpfc_bg_csum(data_src,
2760								   blksize);
2761					else
2762						sum = lpfc_bg_crc(data_src,
2763								  blksize);
2764					if ((guard_tag != sum)) {
2765						err_type = BGS_GUARD_ERR_MASK;
2766						goto out;
2767					}
2768				}
2769
2770				/* Reference Tag checking */
2771				ref_tag = be32_to_cpu(src->ref_tag);
2772				if (chk_ref && (ref_tag != start_ref_tag)) {
2773					err_type = BGS_REFTAG_ERR_MASK;
2774					goto out;
2775				}
2776				start_ref_tag++;
2777
2778				/* App Tag checking */
2779				app_tag = src->app_tag;
2780				if (chk_app && (app_tag != start_app_tag)) {
2781					err_type = BGS_APPTAG_ERR_MASK;
2782					goto out;
2783				}
2784skipit:
2785				len -= sizeof(struct scsi_dif_tuple);
2786				if (len < 0)
2787					len = 0;
2788				src++;
2789
2790				data_src += blksize;
2791				data_len -= blksize;
2792
2793				/*
2794				 * Are we at the end of the Data segment?
2795				 * The data segment is only used for Guard
2796				 * tag checking.
2797				 */
2798				if (chk_guard && (data_len == 0)) {
2799					chk_guard = 0;
2800					sgde = sg_next(sgde);
2801					if (!sgde)
2802						goto out;
2803
2804					data_src = (uint8_t *)sg_virt(sgde);
2805					data_len = sg_dma_len(sgde);
2806					if ((data_len & (blksize - 1)) == 0)
2807						chk_guard = 1;
2808				}
2809			}
2810
2811			/* Goto the next Protection data segment */
2812			sgpe = sg_next(sgpe);
2813			if (sgpe) {
2814				src = (struct scsi_dif_tuple *)sg_virt(sgpe);
2815				len = sg_dma_len(sgpe);
2816			} else {
2817				src = NULL;
2818			}
2819			protsegcnt--;
2820		}
2821	}
2822out:
2823	if (err_type == BGS_GUARD_ERR_MASK) {
2824		scsi_build_sense(cmd, 1, ILLEGAL_REQUEST, 0x10, 0x1);
2825		set_host_byte(cmd, DID_ABORT);
2826		phba->bg_guard_err_cnt++;
2827		lpfc_printf_log(phba, KERN_WARNING, LOG_FCP | LOG_BG,
2828				"9069 BLKGRD: reftag %x grd_tag err %x != %x\n",
2829				scsi_prot_ref_tag(cmd),
2830				sum, guard_tag);
2831
2832	} else if (err_type == BGS_REFTAG_ERR_MASK) {
2833		scsi_build_sense(cmd, 1, ILLEGAL_REQUEST, 0x10, 0x3);
2834		set_host_byte(cmd, DID_ABORT);
2835
2836		phba->bg_reftag_err_cnt++;
2837		lpfc_printf_log(phba, KERN_WARNING, LOG_FCP | LOG_BG,
2838				"9066 BLKGRD: reftag %x ref_tag err %x != %x\n",
2839				scsi_prot_ref_tag(cmd),
2840				ref_tag, start_ref_tag);
2841
2842	} else if (err_type == BGS_APPTAG_ERR_MASK) {
2843		scsi_build_sense(cmd, 1, ILLEGAL_REQUEST, 0x10, 0x2);
2844		set_host_byte(cmd, DID_ABORT);
2845
2846		phba->bg_apptag_err_cnt++;
2847		lpfc_printf_log(phba, KERN_WARNING, LOG_FCP | LOG_BG,
2848				"9041 BLKGRD: reftag %x app_tag err %x != %x\n",
2849				scsi_prot_ref_tag(cmd),
2850				app_tag, start_app_tag);
2851	}
2852}
2853
2854/*
2855 * This function checks for BlockGuard errors detected by
2856 * the HBA.  In case of errors, the ASC/ASCQ fields in the
2857 * sense buffer will be set accordingly, paired with
2858 * ILLEGAL_REQUEST to signal to the kernel that the HBA
2859 * detected corruption.
2860 *
2861 * Returns:
2862 *  0 - No error found
2863 *  1 - BlockGuard error found
2864 * -1 - Internal error (bad profile, ...etc)
2865 */
2866static int
2867lpfc_parse_bg_err(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd,
2868		  struct lpfc_iocbq *pIocbOut)
2869{
2870	struct scsi_cmnd *cmd = lpfc_cmd->pCmd;
2871	struct sli3_bg_fields *bgf;
2872	int ret = 0;
2873	struct lpfc_wcqe_complete *wcqe;
2874	u32 status;
2875	u32 bghm = 0;
2876	u32 bgstat = 0;
2877	u64 failing_sector = 0;
2878
2879	if (phba->sli_rev == LPFC_SLI_REV4) {
2880		wcqe = &pIocbOut->wcqe_cmpl;
2881		status = bf_get(lpfc_wcqe_c_status, wcqe);
2882
2883		if (status == CQE_STATUS_DI_ERROR) {
2884			/* Guard Check failed */
2885			if (bf_get(lpfc_wcqe_c_bg_ge, wcqe))
2886				bgstat |= BGS_GUARD_ERR_MASK;
2887
2888			/* AppTag Check failed */
2889			if (bf_get(lpfc_wcqe_c_bg_ae, wcqe))
2890				bgstat |= BGS_APPTAG_ERR_MASK;
2891
2892			/* RefTag Check failed */
2893			if (bf_get(lpfc_wcqe_c_bg_re, wcqe))
2894				bgstat |= BGS_REFTAG_ERR_MASK;
2895
2896			/* Check to see if there was any good data before the
2897			 * error
2898			 */
2899			if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
2900				bgstat |= BGS_HI_WATER_MARK_PRESENT_MASK;
2901				bghm = wcqe->total_data_placed;
2902			}
2903
2904			/*
2905			 * Set ALL the error bits to indicate we don't know what
2906			 * type of error it is.
2907			 */
2908			if (!bgstat)
2909				bgstat |= (BGS_REFTAG_ERR_MASK |
2910					   BGS_APPTAG_ERR_MASK |
2911					   BGS_GUARD_ERR_MASK);
2912		}
2913
2914	} else {
2915		bgf = &pIocbOut->iocb.unsli3.sli3_bg;
2916		bghm = bgf->bghm;
2917		bgstat = bgf->bgstat;
2918	}
2919
2920	if (lpfc_bgs_get_invalid_prof(bgstat)) {
2921		cmd->result = DID_ERROR << 16;
2922		lpfc_printf_log(phba, KERN_WARNING, LOG_FCP | LOG_BG,
2923				"9072 BLKGRD: Invalid BG Profile in cmd "
2924				"0x%x reftag 0x%x blk cnt 0x%x "
2925				"bgstat=x%x bghm=x%x\n", cmd->cmnd[0],
2926				scsi_prot_ref_tag(cmd),
2927				scsi_logical_block_count(cmd), bgstat, bghm);
2928		ret = (-1);
2929		goto out;
2930	}
2931
2932	if (lpfc_bgs_get_uninit_dif_block(bgstat)) {
2933		cmd->result = DID_ERROR << 16;
2934		lpfc_printf_log(phba, KERN_WARNING, LOG_FCP | LOG_BG,
2935				"9073 BLKGRD: Invalid BG PDIF Block in cmd "
2936				"0x%x reftag 0x%x blk cnt 0x%x "
2937				"bgstat=x%x bghm=x%x\n", cmd->cmnd[0],
2938				scsi_prot_ref_tag(cmd),
2939				scsi_logical_block_count(cmd), bgstat, bghm);
2940		ret = (-1);
2941		goto out;
2942	}
2943
2944	if (lpfc_bgs_get_guard_err(bgstat)) {
2945		ret = 1;
2946		scsi_build_sense(cmd, 1, ILLEGAL_REQUEST, 0x10, 0x1);
2947		set_host_byte(cmd, DID_ABORT);
2948		phba->bg_guard_err_cnt++;
2949		lpfc_printf_log(phba, KERN_WARNING, LOG_FCP | LOG_BG,
2950				"9055 BLKGRD: Guard Tag error in cmd "
2951				"0x%x reftag 0x%x blk cnt 0x%x "
2952				"bgstat=x%x bghm=x%x\n", cmd->cmnd[0],
2953				scsi_prot_ref_tag(cmd),
2954				scsi_logical_block_count(cmd), bgstat, bghm);
2955	}
2956
2957	if (lpfc_bgs_get_reftag_err(bgstat)) {
2958		ret = 1;
2959		scsi_build_sense(cmd, 1, ILLEGAL_REQUEST, 0x10, 0x3);
2960		set_host_byte(cmd, DID_ABORT);
2961		phba->bg_reftag_err_cnt++;
2962		lpfc_printf_log(phba, KERN_WARNING, LOG_FCP | LOG_BG,
2963				"9056 BLKGRD: Ref Tag error in cmd "
2964				"0x%x reftag 0x%x blk cnt 0x%x "
2965				"bgstat=x%x bghm=x%x\n", cmd->cmnd[0],
2966				scsi_prot_ref_tag(cmd),
2967				scsi_logical_block_count(cmd), bgstat, bghm);
2968	}
2969
2970	if (lpfc_bgs_get_apptag_err(bgstat)) {
2971		ret = 1;
2972		scsi_build_sense(cmd, 1, ILLEGAL_REQUEST, 0x10, 0x2);
2973		set_host_byte(cmd, DID_ABORT);
2974		phba->bg_apptag_err_cnt++;
2975		lpfc_printf_log(phba, KERN_WARNING, LOG_FCP | LOG_BG,
2976				"9061 BLKGRD: App Tag error in cmd "
2977				"0x%x reftag 0x%x blk cnt 0x%x "
2978				"bgstat=x%x bghm=x%x\n", cmd->cmnd[0],
2979				scsi_prot_ref_tag(cmd),
2980				scsi_logical_block_count(cmd), bgstat, bghm);
2981	}
2982
2983	if (lpfc_bgs_get_hi_water_mark_present(bgstat)) {
2984		/*
2985		 * setup sense data descriptor 0 per SPC-4 as an information
2986		 * field, and put the failing LBA in it.
2987		 * This code assumes there was also a guard/app/ref tag error
2988		 * indication.
2989		 */
2990		cmd->sense_buffer[7] = 0xc;   /* Additional sense length */
2991		cmd->sense_buffer[8] = 0;     /* Information descriptor type */
2992		cmd->sense_buffer[9] = 0xa;   /* Additional descriptor length */
2993		cmd->sense_buffer[10] = 0x80; /* Validity bit */
2994
2995		/* bghm is a "on the wire" FC frame based count */
2996		switch (scsi_get_prot_op(cmd)) {
2997		case SCSI_PROT_READ_INSERT:
2998		case SCSI_PROT_WRITE_STRIP:
2999			bghm /= cmd->device->sector_size;
3000			break;
3001		case SCSI_PROT_READ_STRIP:
3002		case SCSI_PROT_WRITE_INSERT:
3003		case SCSI_PROT_READ_PASS:
3004		case SCSI_PROT_WRITE_PASS:
3005			bghm /= (cmd->device->sector_size +
3006				sizeof(struct scsi_dif_tuple));
3007			break;
3008		}
3009
3010		failing_sector = scsi_get_lba(cmd);
3011		failing_sector += bghm;
3012
3013		/* Descriptor Information */
3014		put_unaligned_be64(failing_sector, &cmd->sense_buffer[12]);
3015	}
3016
3017	if (!ret) {
3018		/* No error was reported - problem in FW? */
3019		lpfc_printf_log(phba, KERN_WARNING, LOG_FCP | LOG_BG,
3020				"9057 BLKGRD: Unknown error in cmd "
3021				"0x%x reftag 0x%x blk cnt 0x%x "
3022				"bgstat=x%x bghm=x%x\n", cmd->cmnd[0],
3023				scsi_prot_ref_tag(cmd),
3024				scsi_logical_block_count(cmd), bgstat, bghm);
3025
3026		/* Calculate what type of error it was */
3027		lpfc_calc_bg_err(phba, lpfc_cmd);
3028	}
3029out:
3030	return ret;
3031}
3032
3033/**
3034 * lpfc_scsi_prep_dma_buf_s4 - DMA mapping for scsi buffer to SLI4 IF spec
3035 * @phba: The Hba for which this call is being executed.
3036 * @lpfc_cmd: The scsi buffer which is going to be mapped.
3037 *
3038 * This routine does the pci dma mapping for scatter-gather list of scsi cmnd
3039 * field of @lpfc_cmd for device with SLI-4 interface spec.
3040 *
3041 * Return codes:
3042 *	2 - Error - Do not retry
3043 *	1 - Error - Retry
3044 *	0 - Success
3045 **/
3046static int
3047lpfc_scsi_prep_dma_buf_s4(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
3048{
3049	struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
3050	struct scatterlist *sgel = NULL;
3051	struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
3052	struct sli4_sge *sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
3053	struct sli4_sge *first_data_sgl;
3054	struct lpfc_iocbq *pwqeq = &lpfc_cmd->cur_iocbq;
3055	struct lpfc_vport *vport = phba->pport;
3056	union lpfc_wqe128 *wqe = &pwqeq->wqe;
3057	dma_addr_t physaddr;
3058	uint32_t dma_len;
3059	uint32_t dma_offset = 0;
3060	int nseg, i, j;
3061	struct ulp_bde64 *bde;
3062	bool lsp_just_set = false;
3063	struct sli4_hybrid_sgl *sgl_xtra = NULL;
3064
3065	/*
3066	 * There are three possibilities here - use scatter-gather segment, use
3067	 * the single mapping, or neither.  Start the lpfc command prep by
3068	 * bumping the bpl beyond the fcp_cmnd and fcp_rsp regions to the first
3069	 * data bde entry.
3070	 */
3071	if (scsi_sg_count(scsi_cmnd)) {
3072		/*
3073		 * The driver stores the segment count returned from dma_map_sg
3074		 * because this a count of dma-mappings used to map the use_sg
3075		 * pages.  They are not guaranteed to be the same for those
3076		 * architectures that implement an IOMMU.
3077		 */
3078
3079		nseg = scsi_dma_map(scsi_cmnd);
3080		if (unlikely(nseg <= 0))
3081			return 1;
3082		sgl += 1;
3083		/* clear the last flag in the fcp_rsp map entry */
3084		sgl->word2 = le32_to_cpu(sgl->word2);
3085		bf_set(lpfc_sli4_sge_last, sgl, 0);
3086		sgl->word2 = cpu_to_le32(sgl->word2);
3087		sgl += 1;
3088		first_data_sgl = sgl;
3089		lpfc_cmd->seg_cnt = nseg;
3090		if (!phba->cfg_xpsgl &&
3091		    lpfc_cmd->seg_cnt > phba->cfg_sg_seg_cnt) {
3092			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3093					"9074 BLKGRD:"
3094					" %s: Too many sg segments from "
3095					"dma_map_sg.  Config %d, seg_cnt %d\n",
3096					__func__, phba->cfg_sg_seg_cnt,
3097					lpfc_cmd->seg_cnt);
3098			WARN_ON_ONCE(lpfc_cmd->seg_cnt > phba->cfg_sg_seg_cnt);
3099			lpfc_cmd->seg_cnt = 0;
3100			scsi_dma_unmap(scsi_cmnd);
3101			return 2;
3102		}
3103
3104		/*
3105		 * The driver established a maximum scatter-gather segment count
3106		 * during probe that limits the number of sg elements in any
3107		 * single scsi command.  Just run through the seg_cnt and format
3108		 * the sge's.
3109		 * When using SLI-3 the driver will try to fit all the BDEs into
3110		 * the IOCB. If it can't then the BDEs get added to a BPL as it
3111		 * does for SLI-2 mode.
3112		 */
3113
3114		/* for tracking segment boundaries */
3115		sgel = scsi_sglist(scsi_cmnd);
3116		j = 2;
3117		for (i = 0; i < nseg; i++) {
3118			sgl->word2 = 0;
3119			if (nseg == 1) {
3120				bf_set(lpfc_sli4_sge_last, sgl, 1);
3121				bf_set(lpfc_sli4_sge_type, sgl,
3122				       LPFC_SGE_TYPE_DATA);
3123			} else {
3124				bf_set(lpfc_sli4_sge_last, sgl, 0);
3125
3126				/* do we need to expand the segment */
3127				if (!lsp_just_set &&
3128				    !((j + 1) % phba->border_sge_num) &&
3129				    ((nseg - 1) != i)) {
3130					/* set LSP type */
3131					bf_set(lpfc_sli4_sge_type, sgl,
3132					       LPFC_SGE_TYPE_LSP);
3133
3134					sgl_xtra = lpfc_get_sgl_per_hdwq(
3135							phba, lpfc_cmd);
3136
3137					if (unlikely(!sgl_xtra)) {
3138						lpfc_cmd->seg_cnt = 0;
3139						scsi_dma_unmap(scsi_cmnd);
3140						return 1;
3141					}
3142					sgl->addr_lo = cpu_to_le32(putPaddrLow(
3143						       sgl_xtra->dma_phys_sgl));
3144					sgl->addr_hi = cpu_to_le32(putPaddrHigh(
3145						       sgl_xtra->dma_phys_sgl));
3146
3147				} else {
3148					bf_set(lpfc_sli4_sge_type, sgl,
3149					       LPFC_SGE_TYPE_DATA);
3150				}
3151			}
3152
3153			if (!(bf_get(lpfc_sli4_sge_type, sgl) &
3154				     LPFC_SGE_TYPE_LSP)) {
3155				if ((nseg - 1) == i)
3156					bf_set(lpfc_sli4_sge_last, sgl, 1);
3157
3158				physaddr = sg_dma_address(sgel);
3159				dma_len = sg_dma_len(sgel);
3160				sgl->addr_lo = cpu_to_le32(putPaddrLow(
3161							   physaddr));
3162				sgl->addr_hi = cpu_to_le32(putPaddrHigh(
3163							   physaddr));
3164
3165				bf_set(lpfc_sli4_sge_offset, sgl, dma_offset);
3166				sgl->word2 = cpu_to_le32(sgl->word2);
3167				sgl->sge_len = cpu_to_le32(dma_len);
3168
3169				dma_offset += dma_len;
3170				sgel = sg_next(sgel);
3171
3172				sgl++;
3173				lsp_just_set = false;
3174
3175			} else {
3176				sgl->word2 = cpu_to_le32(sgl->word2);
3177				sgl->sge_len = cpu_to_le32(
3178						     phba->cfg_sg_dma_buf_size);
3179
3180				sgl = (struct sli4_sge *)sgl_xtra->dma_sgl;
3181				i = i - 1;
3182
3183				lsp_just_set = true;
3184			}
3185
3186			j++;
3187		}
3188
3189		/* PBDE support for first data SGE only.
3190		 * For FCoE, we key off Performance Hints.
3191		 * For FC, we key off lpfc_enable_pbde.
3192		 */
3193		if (nseg == 1 &&
3194		    ((phba->sli3_options & LPFC_SLI4_PERFH_ENABLED) ||
3195		     phba->cfg_enable_pbde)) {
3196			/* Words 13-15 */
3197			bde = (struct ulp_bde64 *)
3198				&wqe->words[13];
3199			bde->addrLow = first_data_sgl->addr_lo;
3200			bde->addrHigh = first_data_sgl->addr_hi;
3201			bde->tus.f.bdeSize =
3202					le32_to_cpu(first_data_sgl->sge_len);
3203			bde->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
3204			bde->tus.w = cpu_to_le32(bde->tus.w);
3205
3206			/* Word 11 - set PBDE bit */
3207			bf_set(wqe_pbde, &wqe->generic.wqe_com, 1);
3208		} else {
3209			memset(&wqe->words[13], 0, (sizeof(uint32_t) * 3));
3210			/* Word 11 - PBDE bit disabled by default template */
3211		}
3212	} else {
3213		sgl += 1;
3214		/* set the last flag in the fcp_rsp map entry */
3215		sgl->word2 = le32_to_cpu(sgl->word2);
3216		bf_set(lpfc_sli4_sge_last, sgl, 1);
3217		sgl->word2 = cpu_to_le32(sgl->word2);
3218
3219		if ((phba->sli3_options & LPFC_SLI4_PERFH_ENABLED) ||
3220		    phba->cfg_enable_pbde) {
3221			bde = (struct ulp_bde64 *)
3222				&wqe->words[13];
3223			memset(bde, 0, (sizeof(uint32_t) * 3));
3224		}
3225	}
3226
3227	/*
3228	 * Finish initializing those IOCB fields that are dependent on the
3229	 * scsi_cmnd request_buffer.  Note that for SLI-2 the bdeSize is
3230	 * explicitly reinitialized.
3231	 * all iocb memory resources are reused.
3232	 */
3233	if (scsi_cmnd->cmd_len > LPFC_FCP_CDB_LEN)
3234		((struct fcp_cmnd32 *)fcp_cmnd)->fcpDl =
3235				cpu_to_be32(scsi_bufflen(scsi_cmnd));
3236	else
3237		fcp_cmnd->fcpDl = cpu_to_be32(scsi_bufflen(scsi_cmnd));
3238	/* Set first-burst provided it was successfully negotiated */
3239	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag) &&
3240	    vport->cfg_first_burst_size &&
3241	    scsi_cmnd->sc_data_direction == DMA_TO_DEVICE) {
3242		u32 init_len, total_len;
3243
3244		total_len = scsi_bufflen(scsi_cmnd);
3245		init_len = min(total_len, vport->cfg_first_burst_size);
3246
3247		/* Word 4 & 5 */
3248		wqe->fcp_iwrite.initial_xfer_len = init_len;
3249		wqe->fcp_iwrite.total_xfer_len = total_len;
3250	} else {
3251		/* Word 4 */
3252		wqe->fcp_iwrite.total_xfer_len =
3253			be32_to_cpu(fcp_cmnd->fcpDl);
3254	}
3255
3256	/*
3257	 * If the OAS driver feature is enabled and the lun is enabled for
3258	 * OAS, set the oas iocb related flags.
3259	 */
3260	if ((phba->cfg_fof) && ((struct lpfc_device_data *)
3261		scsi_cmnd->device->hostdata)->oas_enabled) {
3262		lpfc_cmd->cur_iocbq.cmd_flag |= (LPFC_IO_OAS | LPFC_IO_FOF);
3263		lpfc_cmd->cur_iocbq.priority = ((struct lpfc_device_data *)
3264			scsi_cmnd->device->hostdata)->priority;
3265
3266		/* Word 10 */
3267		bf_set(wqe_oas, &wqe->generic.wqe_com, 1);
3268		bf_set(wqe_ccpe, &wqe->generic.wqe_com, 1);
3269
3270		if (lpfc_cmd->cur_iocbq.priority)
3271			bf_set(wqe_ccp, &wqe->generic.wqe_com,
3272			       (lpfc_cmd->cur_iocbq.priority << 1));
3273		else
3274			bf_set(wqe_ccp, &wqe->generic.wqe_com,
3275			       (phba->cfg_XLanePriority << 1));
3276	}
3277
3278	return 0;
3279}
3280
3281/**
3282 * lpfc_bg_scsi_prep_dma_buf_s4 - DMA mapping for scsi buffer to SLI4 IF spec
3283 * @phba: The Hba for which this call is being executed.
3284 * @lpfc_cmd: The scsi buffer which is going to be mapped.
3285 *
3286 * This is the protection/DIF aware version of
3287 * lpfc_scsi_prep_dma_buf(). It may be a good idea to combine the
3288 * two functions eventually, but for now, it's here
3289 * Return codes:
3290 *	2 - Error - Do not retry
3291 *	1 - Error - Retry
3292 *	0 - Success
3293 **/
3294static int
3295lpfc_bg_scsi_prep_dma_buf_s4(struct lpfc_hba *phba,
3296		struct lpfc_io_buf *lpfc_cmd)
3297{
3298	struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
3299	struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
3300	struct sli4_sge *sgl = (struct sli4_sge *)(lpfc_cmd->dma_sgl);
3301	struct lpfc_iocbq *pwqeq = &lpfc_cmd->cur_iocbq;
3302	union lpfc_wqe128 *wqe = &pwqeq->wqe;
3303	uint32_t num_sge = 0;
3304	int datasegcnt, protsegcnt, datadir = scsi_cmnd->sc_data_direction;
3305	int prot_group_type = 0;
3306	int fcpdl;
3307	int ret = 1;
3308	struct lpfc_vport *vport = phba->pport;
3309
3310	/*
3311	 * Start the lpfc command prep by bumping the sgl beyond fcp_cmnd
3312	 *  fcp_rsp regions to the first data sge entry
3313	 */
3314	if (scsi_sg_count(scsi_cmnd)) {
3315		/*
3316		 * The driver stores the segment count returned from dma_map_sg
3317		 * because this a count of dma-mappings used to map the use_sg
3318		 * pages.  They are not guaranteed to be the same for those
3319		 * architectures that implement an IOMMU.
3320		 */
3321		datasegcnt = dma_map_sg(&phba->pcidev->dev,
3322					scsi_sglist(scsi_cmnd),
3323					scsi_sg_count(scsi_cmnd), datadir);
3324		if (unlikely(!datasegcnt))
3325			return 1;
3326
3327		sgl += 1;
3328		/* clear the last flag in the fcp_rsp map entry */
3329		sgl->word2 = le32_to_cpu(sgl->word2);
3330		bf_set(lpfc_sli4_sge_last, sgl, 0);
3331		sgl->word2 = cpu_to_le32(sgl->word2);
3332
3333		sgl += 1;
3334		lpfc_cmd->seg_cnt = datasegcnt;
3335
3336		/* First check if data segment count from SCSI Layer is good */
3337		if (lpfc_cmd->seg_cnt > phba->cfg_sg_seg_cnt &&
3338		    !phba->cfg_xpsgl) {
3339			WARN_ON_ONCE(lpfc_cmd->seg_cnt > phba->cfg_sg_seg_cnt);
3340			ret = 2;
3341			goto err;
3342		}
3343
3344		prot_group_type = lpfc_prot_group_type(phba, scsi_cmnd);
3345
3346		switch (prot_group_type) {
3347		case LPFC_PG_TYPE_NO_DIF:
3348			/* Here we need to add a DISEED to the count */
3349			if (((lpfc_cmd->seg_cnt + 1) >
3350					phba->cfg_total_seg_cnt) &&
3351			    !phba->cfg_xpsgl) {
3352				ret = 2;
3353				goto err;
3354			}
3355
3356			num_sge = lpfc_bg_setup_sgl(phba, scsi_cmnd, sgl,
3357					datasegcnt, lpfc_cmd);
3358
3359			/* we should have 2 or more entries in buffer list */
3360			if (num_sge < 2) {
3361				ret = 2;
3362				goto err;
3363			}
3364			break;
3365
3366		case LPFC_PG_TYPE_DIF_BUF:
3367			/*
3368			 * This type indicates that protection buffers are
3369			 * passed to the driver, so that needs to be prepared
3370			 * for DMA
3371			 */
3372			protsegcnt = dma_map_sg(&phba->pcidev->dev,
3373					scsi_prot_sglist(scsi_cmnd),
3374					scsi_prot_sg_count(scsi_cmnd), datadir);
3375			if (unlikely(!protsegcnt)) {
3376				scsi_dma_unmap(scsi_cmnd);
3377				return 1;
3378			}
3379
3380			lpfc_cmd->prot_seg_cnt = protsegcnt;
3381			/*
3382			 * There is a minimun of 3 SGEs used for every
3383			 * protection data segment.
3384			 */
3385			if (((lpfc_cmd->prot_seg_cnt * 3) >
3386					(phba->cfg_total_seg_cnt - 2)) &&
3387			    !phba->cfg_xpsgl) {
3388				ret = 2;
3389				goto err;
3390			}
3391
3392			num_sge = lpfc_bg_setup_sgl_prot(phba, scsi_cmnd, sgl,
3393					datasegcnt, protsegcnt, lpfc_cmd);
3394
3395			/* we should have 3 or more entries in buffer list */
3396			if (num_sge < 3 ||
3397			    (num_sge > phba->cfg_total_seg_cnt &&
3398			     !phba->cfg_xpsgl)) {
3399				ret = 2;
3400				goto err;
3401			}
3402			break;
3403
3404		case LPFC_PG_TYPE_INVALID:
3405		default:
3406			scsi_dma_unmap(scsi_cmnd);
3407			lpfc_cmd->seg_cnt = 0;
3408
3409			lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3410					"9083 Unexpected protection group %i\n",
3411					prot_group_type);
3412			return 2;
3413		}
3414	}
3415
3416	switch (scsi_get_prot_op(scsi_cmnd)) {
3417	case SCSI_PROT_WRITE_STRIP:
3418	case SCSI_PROT_READ_STRIP:
3419		lpfc_cmd->cur_iocbq.cmd_flag |= LPFC_IO_DIF_STRIP;
3420		break;
3421	case SCSI_PROT_WRITE_INSERT:
3422	case SCSI_PROT_READ_INSERT:
3423		lpfc_cmd->cur_iocbq.cmd_flag |= LPFC_IO_DIF_INSERT;
3424		break;
3425	case SCSI_PROT_WRITE_PASS:
3426	case SCSI_PROT_READ_PASS:
3427		lpfc_cmd->cur_iocbq.cmd_flag |= LPFC_IO_DIF_PASS;
3428		break;
3429	}
3430
3431	fcpdl = lpfc_bg_scsi_adjust_dl(phba, lpfc_cmd);
3432	if (lpfc_cmd->pCmd->cmd_len > LPFC_FCP_CDB_LEN)
3433		((struct fcp_cmnd32 *)fcp_cmnd)->fcpDl = cpu_to_be32(fcpdl);
3434	else
3435		fcp_cmnd->fcpDl = cpu_to_be32(fcpdl);
3436
3437	/* Set first-burst provided it was successfully negotiated */
3438	if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag) &&
3439	    vport->cfg_first_burst_size &&
3440	    scsi_cmnd->sc_data_direction == DMA_TO_DEVICE) {
3441		u32 init_len, total_len;
3442
3443		total_len = fcpdl;
3444		init_len = min(total_len, vport->cfg_first_burst_size);
3445
3446		/* Word 4 & 5 */
3447		wqe->fcp_iwrite.initial_xfer_len = init_len;
3448		wqe->fcp_iwrite.total_xfer_len = total_len;
3449	} else {
3450		/* Word 4 */
3451		wqe->fcp_iwrite.total_xfer_len = fcpdl;
3452	}
3453
3454	/*
3455	 * If the OAS driver feature is enabled and the lun is enabled for
3456	 * OAS, set the oas iocb related flags.
3457	 */
3458	if ((phba->cfg_fof) && ((struct lpfc_device_data *)
3459		scsi_cmnd->device->hostdata)->oas_enabled) {
3460		lpfc_cmd->cur_iocbq.cmd_flag |= (LPFC_IO_OAS | LPFC_IO_FOF);
3461
3462		/* Word 10 */
3463		bf_set(wqe_oas, &wqe->generic.wqe_com, 1);
3464		bf_set(wqe_ccpe, &wqe->generic.wqe_com, 1);
3465		bf_set(wqe_ccp, &wqe->generic.wqe_com,
3466		       (phba->cfg_XLanePriority << 1));
3467	}
3468
3469	/* Word 7. DIF Flags */
3470	if (lpfc_cmd->cur_iocbq.cmd_flag & LPFC_IO_DIF_PASS)
3471		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
3472	else if (lpfc_cmd->cur_iocbq.cmd_flag & LPFC_IO_DIF_STRIP)
3473		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
3474	else if (lpfc_cmd->cur_iocbq.cmd_flag & LPFC_IO_DIF_INSERT)
3475		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
3476
3477	lpfc_cmd->cur_iocbq.cmd_flag &= ~(LPFC_IO_DIF_PASS |
3478				 LPFC_IO_DIF_STRIP | LPFC_IO_DIF_INSERT);
3479
3480	return 0;
3481err:
3482	if (lpfc_cmd->seg_cnt)
3483		scsi_dma_unmap(scsi_cmnd);
3484	if (lpfc_cmd->prot_seg_cnt)
3485		dma_unmap_sg(&phba->pcidev->dev, scsi_prot_sglist(scsi_cmnd),
3486			     scsi_prot_sg_count(scsi_cmnd),
3487			     scsi_cmnd->sc_data_direction);
3488
3489	lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3490			"9084 Cannot setup S/G List for HBA "
3491			"IO segs %d/%d SGL %d SCSI %d: %d %d %d\n",
3492			lpfc_cmd->seg_cnt, lpfc_cmd->prot_seg_cnt,
3493			phba->cfg_total_seg_cnt, phba->cfg_sg_seg_cnt,
3494			prot_group_type, num_sge, ret);
3495
3496	lpfc_cmd->seg_cnt = 0;
3497	lpfc_cmd->prot_seg_cnt = 0;
3498	return ret;
3499}
3500
3501/**
3502 * lpfc_scsi_prep_dma_buf - Wrapper function for DMA mapping of scsi buffer
3503 * @phba: The Hba for which this call is being executed.
3504 * @lpfc_cmd: The scsi buffer which is going to be mapped.
3505 *
3506 * This routine wraps the actual DMA mapping function pointer from the
3507 * lpfc_hba struct.
3508 *
3509 * Return codes:
3510 *	1 - Error
3511 *	0 - Success
3512 **/
3513static inline int
3514lpfc_scsi_prep_dma_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
3515{
3516	return phba->lpfc_scsi_prep_dma_buf(phba, lpfc_cmd);
3517}
3518
3519/**
3520 * lpfc_bg_scsi_prep_dma_buf - Wrapper function for DMA mapping of scsi buffer
3521 * using BlockGuard.
3522 * @phba: The Hba for which this call is being executed.
3523 * @lpfc_cmd: The scsi buffer which is going to be mapped.
3524 *
3525 * This routine wraps the actual DMA mapping function pointer from the
3526 * lpfc_hba struct.
3527 *
3528 * Return codes:
3529 *	1 - Error
3530 *	0 - Success
3531 **/
3532static inline int
3533lpfc_bg_scsi_prep_dma_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
3534{
3535	return phba->lpfc_bg_scsi_prep_dma_buf(phba, lpfc_cmd);
3536}
3537
3538/**
3539 * lpfc_scsi_prep_cmnd_buf - Wrapper function for IOCB/WQE mapping of scsi
3540 * buffer
3541 * @vport: Pointer to vport object.
3542 * @lpfc_cmd: The scsi buffer which is going to be mapped.
3543 * @tmo: Timeout value for IO
3544 *
3545 * This routine initializes IOCB/WQE data structure from scsi command
3546 *
3547 * Return codes:
3548 *	1 - Error
3549 *	0 - Success
3550 **/
3551static inline int
3552lpfc_scsi_prep_cmnd_buf(struct lpfc_vport *vport, struct lpfc_io_buf *lpfc_cmd,
3553			uint8_t tmo)
3554{
3555	return vport->phba->lpfc_scsi_prep_cmnd_buf(vport, lpfc_cmd, tmo);
3556}
3557
3558/**
3559 * lpfc_send_scsi_error_event - Posts an event when there is SCSI error
3560 * @phba: Pointer to hba context object.
3561 * @vport: Pointer to vport object.
3562 * @lpfc_cmd: Pointer to lpfc scsi command which reported the error.
3563 * @fcpi_parm: FCP Initiator parameter.
3564 *
3565 * This function posts an event when there is a SCSI command reporting
3566 * error from the scsi device.
3567 **/
3568static void
3569lpfc_send_scsi_error_event(struct lpfc_hba *phba, struct lpfc_vport *vport,
3570		struct lpfc_io_buf *lpfc_cmd, uint32_t fcpi_parm) {
3571	struct scsi_cmnd *cmnd = lpfc_cmd->pCmd;
3572	struct fcp_rsp *fcprsp = lpfc_cmd->fcp_rsp;
3573	uint32_t resp_info = fcprsp->rspStatus2;
3574	uint32_t scsi_status = fcprsp->rspStatus3;
3575	struct lpfc_fast_path_event *fast_path_evt = NULL;
3576	struct lpfc_nodelist *pnode = lpfc_cmd->rdata->pnode;
3577	unsigned long flags;
3578
3579	if (!pnode)
3580		return;
3581
3582	/* If there is queuefull or busy condition send a scsi event */
3583	if ((cmnd->result == SAM_STAT_TASK_SET_FULL) ||
3584		(cmnd->result == SAM_STAT_BUSY)) {
3585		fast_path_evt = lpfc_alloc_fast_evt(phba);
3586		if (!fast_path_evt)
3587			return;
3588		fast_path_evt->un.scsi_evt.event_type =
3589			FC_REG_SCSI_EVENT;
3590		fast_path_evt->un.scsi_evt.subcategory =
3591		(cmnd->result == SAM_STAT_TASK_SET_FULL) ?
3592		LPFC_EVENT_QFULL : LPFC_EVENT_DEVBSY;
3593		fast_path_evt->un.scsi_evt.lun = cmnd->device->lun;
3594		memcpy(&fast_path_evt->un.scsi_evt.wwpn,
3595			&pnode->nlp_portname, sizeof(struct lpfc_name));
3596		memcpy(&fast_path_evt->un.scsi_evt.wwnn,
3597			&pnode->nlp_nodename, sizeof(struct lpfc_name));
3598	} else if ((resp_info & SNS_LEN_VALID) && fcprsp->rspSnsLen &&
3599		((cmnd->cmnd[0] == READ_10) || (cmnd->cmnd[0] == WRITE_10))) {
3600		fast_path_evt = lpfc_alloc_fast_evt(phba);
3601		if (!fast_path_evt)
3602			return;
3603		fast_path_evt->un.check_cond_evt.scsi_event.event_type =
3604			FC_REG_SCSI_EVENT;
3605		fast_path_evt->un.check_cond_evt.scsi_event.subcategory =
3606			LPFC_EVENT_CHECK_COND;
3607		fast_path_evt->un.check_cond_evt.scsi_event.lun =
3608			cmnd->device->lun;
3609		memcpy(&fast_path_evt->un.check_cond_evt.scsi_event.wwpn,
3610			&pnode->nlp_portname, sizeof(struct lpfc_name));
3611		memcpy(&fast_path_evt->un.check_cond_evt.scsi_event.wwnn,
3612			&pnode->nlp_nodename, sizeof(struct lpfc_name));
3613		fast_path_evt->un.check_cond_evt.sense_key =
3614			cmnd->sense_buffer[2] & 0xf;
3615		fast_path_evt->un.check_cond_evt.asc = cmnd->sense_buffer[12];
3616		fast_path_evt->un.check_cond_evt.ascq = cmnd->sense_buffer[13];
3617	} else if ((cmnd->sc_data_direction == DMA_FROM_DEVICE) &&
3618		     fcpi_parm &&
3619		     ((be32_to_cpu(fcprsp->rspResId) != fcpi_parm) ||
3620			((scsi_status == SAM_STAT_GOOD) &&
3621			!(resp_info & (RESID_UNDER | RESID_OVER))))) {
3622		/*
3623		 * If status is good or resid does not match with fcp_param and
3624		 * there is valid fcpi_parm, then there is a read_check error
3625		 */
3626		fast_path_evt = lpfc_alloc_fast_evt(phba);
3627		if (!fast_path_evt)
3628			return;
3629		fast_path_evt->un.read_check_error.header.event_type =
3630			FC_REG_FABRIC_EVENT;
3631		fast_path_evt->un.read_check_error.header.subcategory =
3632			LPFC_EVENT_FCPRDCHKERR;
3633		memcpy(&fast_path_evt->un.read_check_error.header.wwpn,
3634			&pnode->nlp_portname, sizeof(struct lpfc_name));
3635		memcpy(&fast_path_evt->un.read_check_error.header.wwnn,
3636			&pnode->nlp_nodename, sizeof(struct lpfc_name));
3637		fast_path_evt->un.read_check_error.lun = cmnd->device->lun;
3638		fast_path_evt->un.read_check_error.opcode = cmnd->cmnd[0];
3639		fast_path_evt->un.read_check_error.fcpiparam =
3640			fcpi_parm;
3641	} else
3642		return;
3643
3644	fast_path_evt->vport = vport;
3645	spin_lock_irqsave(&phba->hbalock, flags);
3646	list_add_tail(&fast_path_evt->work_evt.evt_listp, &phba->work_list);
3647	spin_unlock_irqrestore(&phba->hbalock, flags);
3648	lpfc_worker_wake_up(phba);
3649	return;
3650}
3651
3652/**
3653 * lpfc_scsi_unprep_dma_buf - Un-map DMA mapping of SG-list for dev
3654 * @phba: The HBA for which this call is being executed.
3655 * @psb: The scsi buffer which is going to be un-mapped.
3656 *
3657 * This routine does DMA un-mapping of scatter gather list of scsi command
3658 * field of @lpfc_cmd for device with SLI-3 interface spec.
3659 **/
3660static void
3661lpfc_scsi_unprep_dma_buf(struct lpfc_hba *phba, struct lpfc_io_buf *psb)
3662{
3663	/*
3664	 * There are only two special cases to consider.  (1) the scsi command
3665	 * requested scatter-gather usage or (2) the scsi command allocated
3666	 * a request buffer, but did not request use_sg.  There is a third
3667	 * case, but it does not require resource deallocation.
3668	 */
3669	if (psb->seg_cnt > 0)
3670		scsi_dma_unmap(psb->pCmd);
3671	if (psb->prot_seg_cnt > 0)
3672		dma_unmap_sg(&phba->pcidev->dev, scsi_prot_sglist(psb->pCmd),
3673				scsi_prot_sg_count(psb->pCmd),
3674				psb->pCmd->sc_data_direction);
3675}
3676
3677/**
3678 * lpfc_unblock_requests - allow further commands to be queued.
3679 * @phba: pointer to phba object
3680 *
3681 * For single vport, just call scsi_unblock_requests on physical port.
3682 * For multiple vports, send scsi_unblock_requests for all the vports.
3683 */
3684void
3685lpfc_unblock_requests(struct lpfc_hba *phba)
3686{
3687	struct lpfc_vport **vports;
3688	struct Scsi_Host  *shost;
3689	int i;
3690
3691	if (phba->sli_rev == LPFC_SLI_REV4 &&
3692	    !phba->sli4_hba.max_cfg_param.vpi_used) {
3693		shost = lpfc_shost_from_vport(phba->pport);
3694		scsi_unblock_requests(shost);
3695		return;
3696	}
3697
3698	vports = lpfc_create_vport_work_array(phba);
3699	if (vports != NULL)
3700		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3701			shost = lpfc_shost_from_vport(vports[i]);
3702			scsi_unblock_requests(shost);
3703		}
3704	lpfc_destroy_vport_work_array(phba, vports);
3705}
3706
3707/**
3708 * lpfc_block_requests - prevent further commands from being queued.
3709 * @phba: pointer to phba object
3710 *
3711 * For single vport, just call scsi_block_requests on physical port.
3712 * For multiple vports, send scsi_block_requests for all the vports.
3713 */
3714void
3715lpfc_block_requests(struct lpfc_hba *phba)
3716{
3717	struct lpfc_vport **vports;
3718	struct Scsi_Host  *shost;
3719	int i;
3720
3721	if (atomic_read(&phba->cmf_stop_io))
3722		return;
3723
3724	if (phba->sli_rev == LPFC_SLI_REV4 &&
3725	    !phba->sli4_hba.max_cfg_param.vpi_used) {
3726		shost = lpfc_shost_from_vport(phba->pport);
3727		scsi_block_requests(shost);
3728		return;
3729	}
3730
3731	vports = lpfc_create_vport_work_array(phba);
3732	if (vports != NULL)
3733		for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
3734			shost = lpfc_shost_from_vport(vports[i]);
3735			scsi_block_requests(shost);
3736		}
3737	lpfc_destroy_vport_work_array(phba, vports);
3738}
3739
3740/**
3741 * lpfc_update_cmf_cmpl - Adjust CMF counters for IO completion
3742 * @phba: The HBA for which this call is being executed.
3743 * @time: The latency of the IO that completed (in ns)
3744 * @size: The size of the IO that completed
3745 * @shost: SCSI host the IO completed on (NULL for a NVME IO)
3746 *
3747 * The routine adjusts the various Burst and Bandwidth counters used in
3748 * Congestion management and E2E. If time is set to LPFC_CGN_NOT_SENT,
3749 * that means the IO was never issued to the HBA, so this routine is
3750 * just being called to cleanup the counter from a previous
3751 * lpfc_update_cmf_cmd call.
3752 */
3753int
3754lpfc_update_cmf_cmpl(struct lpfc_hba *phba,
3755		     uint64_t time, uint32_t size, struct Scsi_Host *shost)
3756{
3757	struct lpfc_cgn_stat *cgs;
3758
3759	if (time != LPFC_CGN_NOT_SENT) {
3760		/* lat is ns coming in, save latency in us */
3761		if (time < 1000)
3762			time = 1;
3763		else
3764			time = div_u64(time + 500, 1000); /* round it */
3765
3766		cgs = per_cpu_ptr(phba->cmf_stat, raw_smp_processor_id());
3767		atomic64_add(size, &cgs->rcv_bytes);
3768		atomic64_add(time, &cgs->rx_latency);
3769		atomic_inc(&cgs->rx_io_cnt);
3770	}
3771	return 0;
3772}
3773
3774/**
3775 * lpfc_update_cmf_cmd - Adjust CMF counters for IO submission
3776 * @phba: The HBA for which this call is being executed.
3777 * @size: The size of the IO that will be issued
3778 *
3779 * The routine adjusts the various Burst and Bandwidth counters used in
3780 * Congestion management and E2E.
3781 */
3782int
3783lpfc_update_cmf_cmd(struct lpfc_hba *phba, uint32_t size)
3784{
3785	uint64_t total;
3786	struct lpfc_cgn_stat *cgs;
3787	int cpu;
3788
3789	/* At this point we are either LPFC_CFG_MANAGED or LPFC_CFG_MONITOR */
3790	if (phba->cmf_active_mode == LPFC_CFG_MANAGED &&
3791	    phba->cmf_max_bytes_per_interval) {
3792		total = 0;
3793		for_each_present_cpu(cpu) {
3794			cgs = per_cpu_ptr(phba->cmf_stat, cpu);
3795			total += atomic64_read(&cgs->total_bytes);
3796		}
3797		if (total >= phba->cmf_max_bytes_per_interval) {
3798			if (!atomic_xchg(&phba->cmf_bw_wait, 1)) {
3799				lpfc_block_requests(phba);
3800				phba->cmf_last_ts =
3801					lpfc_calc_cmf_latency(phba);
3802			}
3803			atomic_inc(&phba->cmf_busy);
3804			return -EBUSY;
3805		}
3806		if (size > atomic_read(&phba->rx_max_read_cnt))
3807			atomic_set(&phba->rx_max_read_cnt, size);
3808	}
3809
3810	cgs = per_cpu_ptr(phba->cmf_stat, raw_smp_processor_id());
3811	atomic64_add(size, &cgs->total_bytes);
3812	return 0;
3813}
3814
3815/**
3816 * lpfc_handle_fcp_err - FCP response handler
3817 * @vport: The virtual port for which this call is being executed.
3818 * @lpfc_cmd: Pointer to lpfc_io_buf data structure.
3819 * @fcpi_parm: FCP Initiator parameter.
3820 *
3821 * This routine is called to process response IOCB with status field
3822 * IOSTAT_FCP_RSP_ERROR. This routine sets result field of scsi command
3823 * based upon SCSI and FCP error.
3824 **/
3825static void
3826lpfc_handle_fcp_err(struct lpfc_vport *vport, struct lpfc_io_buf *lpfc_cmd,
3827		    uint32_t fcpi_parm)
3828{
3829	struct scsi_cmnd *cmnd = lpfc_cmd->pCmd;
3830	struct fcp_cmnd *fcpcmd = lpfc_cmd->fcp_cmnd;
3831	struct fcp_rsp *fcprsp = lpfc_cmd->fcp_rsp;
3832	uint32_t resp_info = fcprsp->rspStatus2;
3833	uint32_t scsi_status = fcprsp->rspStatus3;
3834	uint32_t *lp;
3835	uint32_t host_status = DID_OK;
3836	uint32_t rsplen = 0;
3837	uint32_t fcpDl;
3838	uint32_t logit = LOG_FCP | LOG_FCP_ERROR;
3839
3840
3841	/*
3842	 *  If this is a task management command, there is no
3843	 *  scsi packet associated with this lpfc_cmd.  The driver
3844	 *  consumes it.
3845	 */
3846	if (fcpcmd->fcpCntl2) {
3847		scsi_status = 0;
3848		goto out;
3849	}
3850
3851	if (resp_info & RSP_LEN_VALID) {
3852		rsplen = be32_to_cpu(fcprsp->rspRspLen);
3853		if (rsplen != 0 && rsplen != 4 && rsplen != 8) {
3854			lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
3855					 "2719 Invalid response length: "
3856					 "tgt x%x lun x%llx cmnd x%x rsplen "
3857					 "x%x\n", cmnd->device->id,
3858					 cmnd->device->lun, cmnd->cmnd[0],
3859					 rsplen);
3860			host_status = DID_ERROR;
3861			goto out;
3862		}
3863		if (fcprsp->rspInfo3 != RSP_NO_FAILURE) {
3864			lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
3865				 "2757 Protocol failure detected during "
3866				 "processing of FCP I/O op: "
3867				 "tgt x%x lun x%llx cmnd x%x rspInfo3 x%x\n",
3868				 cmnd->device->id,
3869				 cmnd->device->lun, cmnd->cmnd[0],
3870				 fcprsp->rspInfo3);
3871			host_status = DID_ERROR;
3872			goto out;
3873		}
3874	}
3875
3876	if ((resp_info & SNS_LEN_VALID) && fcprsp->rspSnsLen) {
3877		uint32_t snslen = be32_to_cpu(fcprsp->rspSnsLen);
3878		if (snslen > SCSI_SENSE_BUFFERSIZE)
3879			snslen = SCSI_SENSE_BUFFERSIZE;
3880
3881		if (resp_info & RSP_LEN_VALID)
3882		  rsplen = be32_to_cpu(fcprsp->rspRspLen);
3883		memcpy(cmnd->sense_buffer, &fcprsp->rspInfo0 + rsplen, snslen);
3884	}
3885	lp = (uint32_t *)cmnd->sense_buffer;
3886
3887	/* special handling for under run conditions */
3888	if (!scsi_status && (resp_info & RESID_UNDER)) {
3889		/* don't log under runs if fcp set... */
3890		if (vport->cfg_log_verbose & LOG_FCP)
3891			logit = LOG_FCP_ERROR;
3892		/* unless operator says so */
3893		if (vport->cfg_log_verbose & LOG_FCP_UNDER)
3894			logit = LOG_FCP_UNDER;
3895	}
3896
3897	lpfc_printf_vlog(vport, KERN_WARNING, logit,
3898			 "9024 FCP command x%x failed: x%x SNS x%x x%x "
3899			 "Data: x%x x%x x%x x%x x%x\n",
3900			 cmnd->cmnd[0], scsi_status,
3901			 be32_to_cpu(*lp), be32_to_cpu(*(lp + 3)), resp_info,
3902			 be32_to_cpu(fcprsp->rspResId),
3903			 be32_to_cpu(fcprsp->rspSnsLen),
3904			 be32_to_cpu(fcprsp->rspRspLen),
3905			 fcprsp->rspInfo3);
3906
3907	scsi_set_resid(cmnd, 0);
3908	if (cmnd->cmd_len > LPFC_FCP_CDB_LEN)
3909		fcpDl = be32_to_cpu(((struct fcp_cmnd32 *)fcpcmd)->fcpDl);
3910	else
3911		fcpDl = be32_to_cpu(fcpcmd->fcpDl);
3912	if (resp_info & RESID_UNDER) {
3913		scsi_set_resid(cmnd, be32_to_cpu(fcprsp->rspResId));
3914
3915		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP_UNDER,
3916				 "9025 FCP Underrun, expected %d, "
3917				 "residual %d Data: x%x x%x x%x\n",
3918				 fcpDl,
3919				 scsi_get_resid(cmnd), fcpi_parm, cmnd->cmnd[0],
3920				 cmnd->underflow);
3921
3922		/*
3923		 * If there is an under run, check if under run reported by
3924		 * storage array is same as the under run reported by HBA.
3925		 * If this is not same, there is a dropped frame.
3926		 */
3927		if (fcpi_parm && (scsi_get_resid(cmnd) != fcpi_parm)) {
3928			lpfc_printf_vlog(vport, KERN_WARNING,
3929					 LOG_FCP | LOG_FCP_ERROR,
3930					 "9026 FCP Read Check Error "
3931					 "and Underrun Data: x%x x%x x%x x%x\n",
3932					 fcpDl,
3933					 scsi_get_resid(cmnd), fcpi_parm,
3934					 cmnd->cmnd[0]);
3935			scsi_set_resid(cmnd, scsi_bufflen(cmnd));
3936			host_status = DID_ERROR;
3937		}
3938		/*
3939		 * The cmnd->underflow is the minimum number of bytes that must
3940		 * be transferred for this command.  Provided a sense condition
3941		 * is not present, make sure the actual amount transferred is at
3942		 * least the underflow value or fail.
3943		 */
3944		if (!(resp_info & SNS_LEN_VALID) &&
3945		    (scsi_status == SAM_STAT_GOOD) &&
3946		    (scsi_bufflen(cmnd) - scsi_get_resid(cmnd)
3947		     < cmnd->underflow)) {
3948			lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
3949					 "9027 FCP command x%x residual "
3950					 "underrun converted to error "
3951					 "Data: x%x x%x x%x\n",
3952					 cmnd->cmnd[0], scsi_bufflen(cmnd),
3953					 scsi_get_resid(cmnd), cmnd->underflow);
3954			host_status = DID_ERROR;
3955		}
3956	} else if (resp_info & RESID_OVER) {
3957		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
3958				 "9028 FCP command x%x residual overrun error. "
3959				 "Data: x%x x%x\n", cmnd->cmnd[0],
3960				 scsi_bufflen(cmnd), scsi_get_resid(cmnd));
3961		host_status = DID_ERROR;
3962
3963	/*
3964	 * Check SLI validation that all the transfer was actually done
3965	 * (fcpi_parm should be zero). Apply check only to reads.
3966	 */
3967	} else if (fcpi_parm) {
3968		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP | LOG_FCP_ERROR,
3969				 "9029 FCP %s Check Error Data: "
3970				 "x%x x%x x%x x%x x%x\n",
3971				 ((cmnd->sc_data_direction == DMA_FROM_DEVICE) ?
3972				 "Read" : "Write"),
3973				 fcpDl, be32_to_cpu(fcprsp->rspResId),
3974				 fcpi_parm, cmnd->cmnd[0], scsi_status);
3975
3976		/* There is some issue with the LPe12000 that causes it
3977		 * to miscalculate the fcpi_parm and falsely trip this
3978		 * recovery logic.  Detect this case and don't error when true.
3979		 */
3980		if (fcpi_parm > fcpDl)
3981			goto out;
3982
3983		switch (scsi_status) {
3984		case SAM_STAT_GOOD:
3985		case SAM_STAT_CHECK_CONDITION:
3986			/* Fabric dropped a data frame. Fail any successful
3987			 * command in which we detected dropped frames.
3988			 * A status of good or some check conditions could
3989			 * be considered a successful command.
3990			 */
3991			host_status = DID_ERROR;
3992			break;
3993		}
3994		scsi_set_resid(cmnd, scsi_bufflen(cmnd));
3995	}
3996
3997 out:
3998	cmnd->result = host_status << 16 | scsi_status;
3999	lpfc_send_scsi_error_event(vport->phba, vport, lpfc_cmd, fcpi_parm);
4000}
4001
4002/**
4003 * lpfc_fcp_io_cmd_wqe_cmpl - Complete a FCP IO
4004 * @phba: The hba for which this call is being executed.
4005 * @pwqeIn: The command WQE for the scsi cmnd.
4006 * @pwqeOut: Pointer to driver response WQE object.
4007 *
4008 * This routine assigns scsi command result by looking into response WQE
4009 * status field appropriately. This routine handles QUEUE FULL condition as
4010 * well by ramping down device queue depth.
4011 **/
4012static void
4013lpfc_fcp_io_cmd_wqe_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeIn,
4014			 struct lpfc_iocbq *pwqeOut)
4015{
4016	struct lpfc_io_buf *lpfc_cmd = pwqeIn->io_buf;
4017	struct lpfc_wcqe_complete *wcqe = &pwqeOut->wcqe_cmpl;
4018	struct lpfc_vport *vport = pwqeIn->vport;
4019	struct lpfc_rport_data *rdata;
4020	struct lpfc_nodelist *ndlp;
4021	struct scsi_cmnd *cmd;
4022	unsigned long flags;
4023	struct lpfc_fast_path_event *fast_path_evt;
4024	struct Scsi_Host *shost;
4025	u32 logit = LOG_FCP;
4026	u32 idx;
4027	u32 lat;
4028	u8 wait_xb_clr = 0;
4029
4030	/* Sanity check on return of outstanding command */
4031	if (!lpfc_cmd) {
4032		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
4033				 "9032 Null lpfc_cmd pointer. No "
4034				 "release, skip completion\n");
4035		return;
4036	}
4037
4038	rdata = lpfc_cmd->rdata;
4039	ndlp = rdata->pnode;
4040
4041	/* Sanity check on return of outstanding command */
4042	cmd = lpfc_cmd->pCmd;
4043	if (!cmd) {
4044		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
4045				 "9042 I/O completion: Not an active IO\n");
4046		lpfc_release_scsi_buf(phba, lpfc_cmd);
4047		return;
4048	}
4049	/* Guard against abort handler being called at same time */
4050	spin_lock(&lpfc_cmd->buf_lock);
4051	idx = lpfc_cmd->cur_iocbq.hba_wqidx;
4052	if (phba->sli4_hba.hdwq)
4053		phba->sli4_hba.hdwq[idx].scsi_cstat.io_cmpls++;
4054
4055#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
4056	if (unlikely(phba->hdwqstat_on & LPFC_CHECK_SCSI_IO))
4057		this_cpu_inc(phba->sli4_hba.c_stat->cmpl_io);
4058#endif
4059	shost = cmd->device->host;
4060
4061	lpfc_cmd->status = bf_get(lpfc_wcqe_c_status, wcqe);
4062	lpfc_cmd->result = (wcqe->parameter & IOERR_PARAM_MASK);
4063
4064	lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
4065	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
4066		lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
4067		if (phba->cfg_fcp_wait_abts_rsp)
4068			wait_xb_clr = 1;
4069	}
4070
4071#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
4072	if (lpfc_cmd->prot_data_type) {
4073		struct scsi_dif_tuple *src = NULL;
4074
4075		src =  (struct scsi_dif_tuple *)lpfc_cmd->prot_data_segment;
4076		/*
4077		 * Used to restore any changes to protection
4078		 * data for error injection.
4079		 */
4080		switch (lpfc_cmd->prot_data_type) {
4081		case LPFC_INJERR_REFTAG:
4082			src->ref_tag =
4083				lpfc_cmd->prot_data;
4084			break;
4085		case LPFC_INJERR_APPTAG:
4086			src->app_tag =
4087				(uint16_t)lpfc_cmd->prot_data;
4088			break;
4089		case LPFC_INJERR_GUARD:
4090			src->guard_tag =
4091				(uint16_t)lpfc_cmd->prot_data;
4092			break;
4093		default:
4094			break;
4095		}
4096
4097		lpfc_cmd->prot_data = 0;
4098		lpfc_cmd->prot_data_type = 0;
4099		lpfc_cmd->prot_data_segment = NULL;
4100	}
4101#endif
4102	if (unlikely(lpfc_cmd->status)) {
4103		if (lpfc_cmd->status == IOSTAT_FCP_RSP_ERROR &&
4104		    !lpfc_cmd->fcp_rsp->rspStatus3 &&
4105		    (lpfc_cmd->fcp_rsp->rspStatus2 & RESID_UNDER) &&
4106		    !(vport->cfg_log_verbose & LOG_FCP_UNDER))
4107			logit = 0;
4108		else
4109			logit = LOG_FCP | LOG_FCP_UNDER;
4110		lpfc_printf_vlog(vport, KERN_WARNING, logit,
4111				 "9034 FCP cmd x%x failed <%d/%lld> "
4112				 "status: x%x result: x%x "
4113				 "sid: x%x did: x%x oxid: x%x "
4114				 "Data: x%x x%x x%x\n",
4115				 cmd->cmnd[0],
4116				 cmd->device ? cmd->device->id : 0xffff,
4117				 cmd->device ? cmd->device->lun : 0xffff,
4118				 lpfc_cmd->status, lpfc_cmd->result,
4119				 vport->fc_myDID,
4120				 (ndlp) ? ndlp->nlp_DID : 0,
4121				 lpfc_cmd->cur_iocbq.sli4_xritag,
4122				 wcqe->parameter, wcqe->total_data_placed,
4123				 lpfc_cmd->cur_iocbq.iotag);
4124	}
4125
4126	switch (lpfc_cmd->status) {
4127	case CQE_STATUS_SUCCESS:
4128		cmd->result = DID_OK << 16;
4129		break;
4130	case CQE_STATUS_FCP_RSP_FAILURE:
4131		lpfc_handle_fcp_err(vport, lpfc_cmd,
4132				    pwqeIn->wqe.fcp_iread.total_xfer_len -
4133				    wcqe->total_data_placed);
4134		break;
4135	case CQE_STATUS_NPORT_BSY:
4136	case CQE_STATUS_FABRIC_BSY:
4137		cmd->result = DID_TRANSPORT_DISRUPTED << 16;
4138		fast_path_evt = lpfc_alloc_fast_evt(phba);
4139		if (!fast_path_evt)
4140			break;
4141		fast_path_evt->un.fabric_evt.event_type =
4142			FC_REG_FABRIC_EVENT;
4143		fast_path_evt->un.fabric_evt.subcategory =
4144			(lpfc_cmd->status == IOSTAT_NPORT_BSY) ?
4145			LPFC_EVENT_PORT_BUSY : LPFC_EVENT_FABRIC_BUSY;
4146		if (ndlp) {
4147			memcpy(&fast_path_evt->un.fabric_evt.wwpn,
4148			       &ndlp->nlp_portname,
4149				sizeof(struct lpfc_name));
4150			memcpy(&fast_path_evt->un.fabric_evt.wwnn,
4151			       &ndlp->nlp_nodename,
4152				sizeof(struct lpfc_name));
4153		}
4154		fast_path_evt->vport = vport;
4155		fast_path_evt->work_evt.evt =
4156			LPFC_EVT_FASTPATH_MGMT_EVT;
4157		spin_lock_irqsave(&phba->hbalock, flags);
4158		list_add_tail(&fast_path_evt->work_evt.evt_listp,
4159			      &phba->work_list);
4160		spin_unlock_irqrestore(&phba->hbalock, flags);
4161		lpfc_worker_wake_up(phba);
4162		lpfc_printf_vlog(vport, KERN_WARNING, logit,
4163				 "9035 Fabric/Node busy FCP cmd x%x failed"
4164				 " <%d/%lld> "
4165				 "status: x%x result: x%x "
4166				 "sid: x%x did: x%x oxid: x%x "
4167				 "Data: x%x x%x x%x\n",
4168				 cmd->cmnd[0],
4169				 cmd->device ? cmd->device->id : 0xffff,
4170				 cmd->device ? cmd->device->lun : 0xffff,
4171				 lpfc_cmd->status, lpfc_cmd->result,
4172				 vport->fc_myDID,
4173				 (ndlp) ? ndlp->nlp_DID : 0,
4174				 lpfc_cmd->cur_iocbq.sli4_xritag,
4175				 wcqe->parameter,
4176				 wcqe->total_data_placed,
4177				 lpfc_cmd->cur_iocbq.iocb.ulpIoTag);
4178		break;
4179	case CQE_STATUS_DI_ERROR:
4180		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
4181			lpfc_cmd->result = IOERR_RX_DMA_FAILED;
4182		else
4183			lpfc_cmd->result = IOERR_TX_DMA_FAILED;
4184		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP | LOG_BG,
4185				 "9048 DI Error xri x%x status x%x DI ext "
4186				 "status x%x data placed x%x\n",
4187				 lpfc_cmd->cur_iocbq.sli4_xritag,
4188				 lpfc_cmd->status, wcqe->parameter,
4189				 wcqe->total_data_placed);
4190		if (scsi_get_prot_op(cmd) != SCSI_PROT_NORMAL) {
4191			/* BG enabled cmd. Parse BG error */
4192			lpfc_parse_bg_err(phba, lpfc_cmd, pwqeOut);
4193			break;
4194		}
4195		cmd->result = DID_ERROR << 16;
4196		lpfc_printf_vlog(vport, KERN_WARNING, LOG_BG,
4197				 "9040 DI Error on unprotected cmd\n");
4198		break;
4199	case CQE_STATUS_REMOTE_STOP:
4200		if (ndlp) {
4201			/* This I/O was aborted by the target, we don't
4202			 * know the rxid and because we did not send the
4203			 * ABTS we cannot generate and RRQ.
4204			 */
4205			lpfc_set_rrq_active(phba, ndlp,
4206					    lpfc_cmd->cur_iocbq.sli4_lxritag,
4207					    0, 0);
4208		}
4209		fallthrough;
4210	case CQE_STATUS_LOCAL_REJECT:
4211		if (lpfc_cmd->result & IOERR_DRVR_MASK)
4212			lpfc_cmd->status = IOSTAT_DRIVER_REJECT;
4213		if (lpfc_cmd->result == IOERR_ELXSEC_KEY_UNWRAP_ERROR ||
4214		    lpfc_cmd->result ==
4215		    IOERR_ELXSEC_KEY_UNWRAP_COMPARE_ERROR ||
4216		    lpfc_cmd->result == IOERR_ELXSEC_CRYPTO_ERROR ||
4217		    lpfc_cmd->result ==
4218		    IOERR_ELXSEC_CRYPTO_COMPARE_ERROR) {
4219			cmd->result = DID_NO_CONNECT << 16;
4220			break;
4221		}
4222		if (lpfc_cmd->result == IOERR_INVALID_RPI ||
4223		    lpfc_cmd->result == IOERR_LINK_DOWN ||
4224		    lpfc_cmd->result == IOERR_NO_RESOURCES ||
4225		    lpfc_cmd->result == IOERR_ABORT_REQUESTED ||
4226		    lpfc_cmd->result == IOERR_RPI_SUSPENDED ||
4227		    lpfc_cmd->result == IOERR_SLER_CMD_RCV_FAILURE) {
4228			cmd->result = DID_TRANSPORT_DISRUPTED << 16;
4229			break;
4230		}
4231		lpfc_printf_vlog(vport, KERN_WARNING, logit,
4232				 "9036 Local Reject FCP cmd x%x failed"
4233				 " <%d/%lld> "
4234				 "status: x%x result: x%x "
4235				 "sid: x%x did: x%x oxid: x%x "
4236				 "Data: x%x x%x x%x\n",
4237				 cmd->cmnd[0],
4238				 cmd->device ? cmd->device->id : 0xffff,
4239				 cmd->device ? cmd->device->lun : 0xffff,
4240				 lpfc_cmd->status, lpfc_cmd->result,
4241				 vport->fc_myDID,
4242				 (ndlp) ? ndlp->nlp_DID : 0,
4243				 lpfc_cmd->cur_iocbq.sli4_xritag,
4244				 wcqe->parameter,
4245				 wcqe->total_data_placed,
4246				 lpfc_cmd->cur_iocbq.iocb.ulpIoTag);
4247		fallthrough;
4248	default:
4249		cmd->result = DID_ERROR << 16;
4250		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
4251				 "9037 FCP Completion Error: xri %x "
4252				 "status x%x result x%x [x%x] "
4253				 "placed x%x\n",
4254				 lpfc_cmd->cur_iocbq.sli4_xritag,
4255				 lpfc_cmd->status, lpfc_cmd->result,
4256				 wcqe->parameter,
4257				 wcqe->total_data_placed);
4258	}
4259	if (cmd->result || lpfc_cmd->fcp_rsp->rspSnsLen) {
4260		u32 *lp = (u32 *)cmd->sense_buffer;
4261
4262		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
4263				 "9039 Iodone <%d/%llu> cmd x%px, error "
4264				 "x%x SNS x%x x%x LBA x%llx Data: x%x x%x\n",
4265				 cmd->device->id, cmd->device->lun, cmd,
4266				 cmd->result, *lp, *(lp + 3),
4267				 (cmd->device->sector_size) ?
4268				 (u64)scsi_get_lba(cmd) : 0,
4269				 cmd->retries, scsi_get_resid(cmd));
4270	}
4271
4272	if (vport->cfg_max_scsicmpl_time &&
4273	    time_after(jiffies, lpfc_cmd->start_time +
4274	    msecs_to_jiffies(vport->cfg_max_scsicmpl_time))) {
4275		spin_lock_irqsave(shost->host_lock, flags);
4276		if (ndlp) {
4277			if (ndlp->cmd_qdepth >
4278				atomic_read(&ndlp->cmd_pending) &&
4279				(atomic_read(&ndlp->cmd_pending) >
4280				LPFC_MIN_TGT_QDEPTH) &&
4281				(cmd->cmnd[0] == READ_10 ||
4282				cmd->cmnd[0] == WRITE_10))
4283				ndlp->cmd_qdepth =
4284					atomic_read(&ndlp->cmd_pending);
4285
4286			ndlp->last_change_time = jiffies;
4287		}
4288		spin_unlock_irqrestore(shost->host_lock, flags);
4289	}
4290	lpfc_scsi_unprep_dma_buf(phba, lpfc_cmd);
4291
4292#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
4293	if (lpfc_cmd->ts_cmd_start) {
4294		lpfc_cmd->ts_isr_cmpl = lpfc_cmd->cur_iocbq.isr_timestamp;
4295		lpfc_cmd->ts_data_io = ktime_get_ns();
4296		phba->ktime_last_cmd = lpfc_cmd->ts_data_io;
4297		lpfc_io_ktime(phba, lpfc_cmd);
4298	}
4299#endif
4300	if (likely(!wait_xb_clr))
4301		lpfc_cmd->pCmd = NULL;
4302	spin_unlock(&lpfc_cmd->buf_lock);
4303
4304	/* Check if IO qualified for CMF */
4305	if (phba->cmf_active_mode != LPFC_CFG_OFF &&
4306	    cmd->sc_data_direction == DMA_FROM_DEVICE &&
4307	    (scsi_sg_count(cmd))) {
4308		/* Used when calculating average latency */
4309		lat = ktime_get_ns() - lpfc_cmd->rx_cmd_start;
4310		lpfc_update_cmf_cmpl(phba, lat, scsi_bufflen(cmd), shost);
4311	}
4312
4313	if (wait_xb_clr)
4314		goto out;
4315
4316	/* The sdev is not guaranteed to be valid post scsi_done upcall. */
4317	scsi_done(cmd);
4318
4319	/*
4320	 * If there is an abort thread waiting for command completion
4321	 * wake up the thread.
4322	 */
4323	spin_lock(&lpfc_cmd->buf_lock);
4324	lpfc_cmd->cur_iocbq.cmd_flag &= ~LPFC_DRIVER_ABORTED;
4325	if (lpfc_cmd->waitq)
4326		wake_up(lpfc_cmd->waitq);
4327	spin_unlock(&lpfc_cmd->buf_lock);
4328out:
4329	lpfc_release_scsi_buf(phba, lpfc_cmd);
4330}
4331
4332/**
4333 * lpfc_scsi_cmd_iocb_cmpl - Scsi cmnd IOCB completion routine
4334 * @phba: The Hba for which this call is being executed.
4335 * @pIocbIn: The command IOCBQ for the scsi cmnd.
4336 * @pIocbOut: The response IOCBQ for the scsi cmnd.
4337 *
4338 * This routine assigns scsi command result by looking into response IOCB
4339 * status field appropriately. This routine handles QUEUE FULL condition as
4340 * well by ramping down device queue depth.
4341 **/
4342static void
4343lpfc_scsi_cmd_iocb_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *pIocbIn,
4344			struct lpfc_iocbq *pIocbOut)
4345{
4346	struct lpfc_io_buf *lpfc_cmd =
4347		(struct lpfc_io_buf *) pIocbIn->io_buf;
4348	struct lpfc_vport      *vport = pIocbIn->vport;
4349	struct lpfc_rport_data *rdata = lpfc_cmd->rdata;
4350	struct lpfc_nodelist *pnode = rdata->pnode;
4351	struct scsi_cmnd *cmd;
4352	unsigned long flags;
4353	struct lpfc_fast_path_event *fast_path_evt;
4354	struct Scsi_Host *shost;
4355	int idx;
4356	uint32_t logit = LOG_FCP;
4357
4358	/* Guard against abort handler being called at same time */
4359	spin_lock(&lpfc_cmd->buf_lock);
4360
4361	/* Sanity check on return of outstanding command */
4362	cmd = lpfc_cmd->pCmd;
4363	if (!cmd || !phba) {
4364		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
4365				 "2621 IO completion: Not an active IO\n");
4366		spin_unlock(&lpfc_cmd->buf_lock);
4367		return;
4368	}
4369
4370	idx = lpfc_cmd->cur_iocbq.hba_wqidx;
4371	if (phba->sli4_hba.hdwq)
4372		phba->sli4_hba.hdwq[idx].scsi_cstat.io_cmpls++;
4373
4374#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
4375	if (unlikely(phba->hdwqstat_on & LPFC_CHECK_SCSI_IO))
4376		this_cpu_inc(phba->sli4_hba.c_stat->cmpl_io);
4377#endif
4378	shost = cmd->device->host;
4379
4380	lpfc_cmd->result = (pIocbOut->iocb.un.ulpWord[4] & IOERR_PARAM_MASK);
4381	lpfc_cmd->status = pIocbOut->iocb.ulpStatus;
4382	/* pick up SLI4 exchange busy status from HBA */
4383	lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
4384	if (pIocbOut->cmd_flag & LPFC_EXCHANGE_BUSY)
4385		lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
4386
4387#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
4388	if (lpfc_cmd->prot_data_type) {
4389		struct scsi_dif_tuple *src = NULL;
4390
4391		src =  (struct scsi_dif_tuple *)lpfc_cmd->prot_data_segment;
4392		/*
4393		 * Used to restore any changes to protection
4394		 * data for error injection.
4395		 */
4396		switch (lpfc_cmd->prot_data_type) {
4397		case LPFC_INJERR_REFTAG:
4398			src->ref_tag =
4399				lpfc_cmd->prot_data;
4400			break;
4401		case LPFC_INJERR_APPTAG:
4402			src->app_tag =
4403				(uint16_t)lpfc_cmd->prot_data;
4404			break;
4405		case LPFC_INJERR_GUARD:
4406			src->guard_tag =
4407				(uint16_t)lpfc_cmd->prot_data;
4408			break;
4409		default:
4410			break;
4411		}
4412
4413		lpfc_cmd->prot_data = 0;
4414		lpfc_cmd->prot_data_type = 0;
4415		lpfc_cmd->prot_data_segment = NULL;
4416	}
4417#endif
4418
4419	if (unlikely(lpfc_cmd->status)) {
4420		if (lpfc_cmd->status == IOSTAT_LOCAL_REJECT &&
4421		    (lpfc_cmd->result & IOERR_DRVR_MASK))
4422			lpfc_cmd->status = IOSTAT_DRIVER_REJECT;
4423		else if (lpfc_cmd->status >= IOSTAT_CNT)
4424			lpfc_cmd->status = IOSTAT_DEFAULT;
4425		if (lpfc_cmd->status == IOSTAT_FCP_RSP_ERROR &&
4426		    !lpfc_cmd->fcp_rsp->rspStatus3 &&
4427		    (lpfc_cmd->fcp_rsp->rspStatus2 & RESID_UNDER) &&
4428		    !(vport->cfg_log_verbose & LOG_FCP_UNDER))
4429			logit = 0;
4430		else
4431			logit = LOG_FCP | LOG_FCP_UNDER;
4432		lpfc_printf_vlog(vport, KERN_WARNING, logit,
4433			 "9030 FCP cmd x%x failed <%d/%lld> "
4434			 "status: x%x result: x%x "
4435			 "sid: x%x did: x%x oxid: x%x "
4436			 "Data: x%x x%x\n",
4437			 cmd->cmnd[0],
4438			 cmd->device ? cmd->device->id : 0xffff,
4439			 cmd->device ? cmd->device->lun : 0xffff,
4440			 lpfc_cmd->status, lpfc_cmd->result,
4441			 vport->fc_myDID,
4442			 (pnode) ? pnode->nlp_DID : 0,
4443			 phba->sli_rev == LPFC_SLI_REV4 ?
4444			     lpfc_cmd->cur_iocbq.sli4_xritag : 0xffff,
4445			 pIocbOut->iocb.ulpContext,
4446			 lpfc_cmd->cur_iocbq.iocb.ulpIoTag);
4447
4448		switch (lpfc_cmd->status) {
4449		case IOSTAT_FCP_RSP_ERROR:
4450			/* Call FCP RSP handler to determine result */
4451			lpfc_handle_fcp_err(vport, lpfc_cmd,
4452					    pIocbOut->iocb.un.fcpi.fcpi_parm);
4453			break;
4454		case IOSTAT_NPORT_BSY:
4455		case IOSTAT_FABRIC_BSY:
4456			cmd->result = DID_TRANSPORT_DISRUPTED << 16;
4457			fast_path_evt = lpfc_alloc_fast_evt(phba);
4458			if (!fast_path_evt)
4459				break;
4460			fast_path_evt->un.fabric_evt.event_type =
4461				FC_REG_FABRIC_EVENT;
4462			fast_path_evt->un.fabric_evt.subcategory =
4463				(lpfc_cmd->status == IOSTAT_NPORT_BSY) ?
4464				LPFC_EVENT_PORT_BUSY : LPFC_EVENT_FABRIC_BUSY;
4465			if (pnode) {
4466				memcpy(&fast_path_evt->un.fabric_evt.wwpn,
4467					&pnode->nlp_portname,
4468					sizeof(struct lpfc_name));
4469				memcpy(&fast_path_evt->un.fabric_evt.wwnn,
4470					&pnode->nlp_nodename,
4471					sizeof(struct lpfc_name));
4472			}
4473			fast_path_evt->vport = vport;
4474			fast_path_evt->work_evt.evt =
4475				LPFC_EVT_FASTPATH_MGMT_EVT;
4476			spin_lock_irqsave(&phba->hbalock, flags);
4477			list_add_tail(&fast_path_evt->work_evt.evt_listp,
4478				&phba->work_list);
4479			spin_unlock_irqrestore(&phba->hbalock, flags);
4480			lpfc_worker_wake_up(phba);
4481			break;
4482		case IOSTAT_LOCAL_REJECT:
4483		case IOSTAT_REMOTE_STOP:
4484			if (lpfc_cmd->result == IOERR_ELXSEC_KEY_UNWRAP_ERROR ||
4485			    lpfc_cmd->result ==
4486					IOERR_ELXSEC_KEY_UNWRAP_COMPARE_ERROR ||
4487			    lpfc_cmd->result == IOERR_ELXSEC_CRYPTO_ERROR ||
4488			    lpfc_cmd->result ==
4489					IOERR_ELXSEC_CRYPTO_COMPARE_ERROR) {
4490				cmd->result = DID_NO_CONNECT << 16;
4491				break;
4492			}
4493			if (lpfc_cmd->result == IOERR_INVALID_RPI ||
4494			    lpfc_cmd->result == IOERR_NO_RESOURCES ||
4495			    lpfc_cmd->result == IOERR_ABORT_REQUESTED ||
4496			    lpfc_cmd->result == IOERR_SLER_CMD_RCV_FAILURE) {
4497				cmd->result = DID_TRANSPORT_DISRUPTED << 16;
4498				break;
4499			}
4500			if ((lpfc_cmd->result == IOERR_RX_DMA_FAILED ||
4501			     lpfc_cmd->result == IOERR_TX_DMA_FAILED) &&
4502			     pIocbOut->iocb.unsli3.sli3_bg.bgstat) {
4503				if (scsi_get_prot_op(cmd) != SCSI_PROT_NORMAL) {
4504					/*
4505					 * This is a response for a BG enabled
4506					 * cmd. Parse BG error
4507					 */
4508					lpfc_parse_bg_err(phba, lpfc_cmd,
4509							pIocbOut);
4510					break;
4511				} else {
4512					lpfc_printf_vlog(vport, KERN_WARNING,
4513							LOG_BG,
4514							"9031 non-zero BGSTAT "
4515							"on unprotected cmd\n");
4516				}
4517			}
4518			if ((lpfc_cmd->status == IOSTAT_REMOTE_STOP)
4519				&& (phba->sli_rev == LPFC_SLI_REV4)
4520				&& pnode) {
4521				/* This IO was aborted by the target, we don't
4522				 * know the rxid and because we did not send the
4523				 * ABTS we cannot generate and RRQ.
4524				 */
4525				lpfc_set_rrq_active(phba, pnode,
4526					lpfc_cmd->cur_iocbq.sli4_lxritag,
4527					0, 0);
4528			}
4529			fallthrough;
4530		default:
4531			cmd->result = DID_ERROR << 16;
4532			break;
4533		}
4534
4535		if (!pnode || (pnode->nlp_state != NLP_STE_MAPPED_NODE))
4536			cmd->result = DID_TRANSPORT_DISRUPTED << 16 |
4537				      SAM_STAT_BUSY;
4538	} else
4539		cmd->result = DID_OK << 16;
4540
4541	if (cmd->result || lpfc_cmd->fcp_rsp->rspSnsLen) {
4542		uint32_t *lp = (uint32_t *)cmd->sense_buffer;
4543
4544		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
4545				 "0710 Iodone <%d/%llu> cmd x%px, error "
4546				 "x%x SNS x%x x%x Data: x%x x%x\n",
4547				 cmd->device->id, cmd->device->lun, cmd,
4548				 cmd->result, *lp, *(lp + 3), cmd->retries,
4549				 scsi_get_resid(cmd));
4550	}
4551
4552	if (vport->cfg_max_scsicmpl_time &&
4553	   time_after(jiffies, lpfc_cmd->start_time +
4554		msecs_to_jiffies(vport->cfg_max_scsicmpl_time))) {
4555		spin_lock_irqsave(shost->host_lock, flags);
4556		if (pnode) {
4557			if (pnode->cmd_qdepth >
4558				atomic_read(&pnode->cmd_pending) &&
4559				(atomic_read(&pnode->cmd_pending) >
4560				LPFC_MIN_TGT_QDEPTH) &&
4561				((cmd->cmnd[0] == READ_10) ||
4562				(cmd->cmnd[0] == WRITE_10)))
4563				pnode->cmd_qdepth =
4564					atomic_read(&pnode->cmd_pending);
4565
4566			pnode->last_change_time = jiffies;
4567		}
4568		spin_unlock_irqrestore(shost->host_lock, flags);
4569	}
4570	lpfc_scsi_unprep_dma_buf(phba, lpfc_cmd);
4571
4572	lpfc_cmd->pCmd = NULL;
4573	spin_unlock(&lpfc_cmd->buf_lock);
4574
4575#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
4576	if (lpfc_cmd->ts_cmd_start) {
4577		lpfc_cmd->ts_isr_cmpl = pIocbIn->isr_timestamp;
4578		lpfc_cmd->ts_data_io = ktime_get_ns();
4579		phba->ktime_last_cmd = lpfc_cmd->ts_data_io;
4580		lpfc_io_ktime(phba, lpfc_cmd);
4581	}
4582#endif
4583
4584	/* The sdev is not guaranteed to be valid post scsi_done upcall. */
4585	scsi_done(cmd);
4586
4587	/*
4588	 * If there is an abort thread waiting for command completion
4589	 * wake up the thread.
4590	 */
4591	spin_lock(&lpfc_cmd->buf_lock);
4592	lpfc_cmd->cur_iocbq.cmd_flag &= ~LPFC_DRIVER_ABORTED;
4593	if (lpfc_cmd->waitq)
4594		wake_up(lpfc_cmd->waitq);
4595	spin_unlock(&lpfc_cmd->buf_lock);
4596
4597	lpfc_release_scsi_buf(phba, lpfc_cmd);
4598}
4599
4600/**
4601 * lpfc_scsi_prep_cmnd_buf_s3 - SLI-3 IOCB init for the IO
4602 * @vport: Pointer to vport object.
4603 * @lpfc_cmd: The scsi buffer which is going to be prep'ed.
4604 * @tmo: timeout value for the IO
4605 *
4606 * Based on the data-direction of the command, initialize IOCB
4607 * in the I/O buffer. Fill in the IOCB fields which are independent
4608 * of the scsi buffer
4609 *
4610 * RETURNS 0 - SUCCESS,
4611 **/
4612static int lpfc_scsi_prep_cmnd_buf_s3(struct lpfc_vport *vport,
4613				      struct lpfc_io_buf *lpfc_cmd,
4614				      uint8_t tmo)
4615{
4616	IOCB_t *iocb_cmd = &lpfc_cmd->cur_iocbq.iocb;
4617	struct lpfc_iocbq *piocbq = &lpfc_cmd->cur_iocbq;
4618	struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
4619	struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
4620	struct lpfc_nodelist *pnode = lpfc_cmd->ndlp;
4621	int datadir = scsi_cmnd->sc_data_direction;
4622	u32 fcpdl;
4623
4624	piocbq->iocb.un.fcpi.fcpi_XRdy = 0;
4625
4626	/*
4627	 * There are three possibilities here - use scatter-gather segment, use
4628	 * the single mapping, or neither.  Start the lpfc command prep by
4629	 * bumping the bpl beyond the fcp_cmnd and fcp_rsp regions to the first
4630	 * data bde entry.
4631	 */
4632	if (scsi_sg_count(scsi_cmnd)) {
4633		if (datadir == DMA_TO_DEVICE) {
4634			iocb_cmd->ulpCommand = CMD_FCP_IWRITE64_CR;
4635			iocb_cmd->ulpPU = PARM_READ_CHECK;
4636			if (vport->cfg_first_burst_size &&
4637			    test_bit(NLP_FIRSTBURST, &pnode->nlp_flag)) {
4638				u32 xrdy_len;
4639
4640				fcpdl = scsi_bufflen(scsi_cmnd);
4641				xrdy_len = min(fcpdl,
4642					       vport->cfg_first_burst_size);
4643				piocbq->iocb.un.fcpi.fcpi_XRdy = xrdy_len;
4644			}
4645			fcp_cmnd->fcpCntl3 = WRITE_DATA;
4646		} else {
4647			iocb_cmd->ulpCommand = CMD_FCP_IREAD64_CR;
4648			iocb_cmd->ulpPU = PARM_READ_CHECK;
4649			fcp_cmnd->fcpCntl3 = READ_DATA;
4650		}
4651	} else {
4652		iocb_cmd->ulpCommand = CMD_FCP_ICMND64_CR;
4653		iocb_cmd->un.fcpi.fcpi_parm = 0;
4654		iocb_cmd->ulpPU = 0;
4655		fcp_cmnd->fcpCntl3 = 0;
4656	}
4657
4658	/*
4659	 * Finish initializing those IOCB fields that are independent
4660	 * of the scsi_cmnd request_buffer
4661	 */
4662	piocbq->iocb.ulpContext = pnode->nlp_rpi;
4663	if (pnode->nlp_fcp_info & NLP_FCP_2_DEVICE)
4664		piocbq->iocb.ulpFCP2Rcvy = 1;
4665	else
4666		piocbq->iocb.ulpFCP2Rcvy = 0;
4667
4668	piocbq->iocb.ulpClass = (pnode->nlp_fcp_info & 0x0f);
4669	piocbq->io_buf  = lpfc_cmd;
4670	if (!piocbq->cmd_cmpl)
4671		piocbq->cmd_cmpl = lpfc_scsi_cmd_iocb_cmpl;
4672	piocbq->iocb.ulpTimeout = tmo;
4673	piocbq->vport = vport;
4674	return 0;
4675}
4676
4677/**
4678 * lpfc_scsi_prep_cmnd_buf_s4 - SLI-4 WQE init for the IO
4679 * @vport: Pointer to vport object.
4680 * @lpfc_cmd: The scsi buffer which is going to be prep'ed.
4681 * @tmo: timeout value for the IO
4682 *
4683 * Based on the data-direction of the command copy WQE template
4684 * to I/O buffer WQE. Fill in the WQE fields which are independent
4685 * of the scsi buffer
4686 *
4687 * RETURNS 0 - SUCCESS,
4688 **/
4689static int lpfc_scsi_prep_cmnd_buf_s4(struct lpfc_vport *vport,
4690				      struct lpfc_io_buf *lpfc_cmd,
4691				      uint8_t tmo)
4692{
4693	struct lpfc_hba *phba = vport->phba;
4694	struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
4695	struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
4696	struct lpfc_sli4_hdw_queue *hdwq = NULL;
4697	struct lpfc_iocbq *pwqeq = &lpfc_cmd->cur_iocbq;
4698	struct lpfc_nodelist *pnode = lpfc_cmd->ndlp;
4699	union lpfc_wqe128 *wqe = &pwqeq->wqe;
4700	u16 idx = lpfc_cmd->hdwq_no;
4701	int datadir = scsi_cmnd->sc_data_direction;
4702
4703	hdwq = &phba->sli4_hba.hdwq[idx];
4704
4705	/* Initialize 64 bytes only */
4706	memset(wqe, 0, sizeof(union lpfc_wqe128));
4707
4708	/*
4709	 * There are three possibilities here - use scatter-gather segment, use
4710	 * the single mapping, or neither.
4711	 */
4712	if (scsi_sg_count(scsi_cmnd)) {
4713		if (datadir == DMA_TO_DEVICE) {
4714			/* From the iwrite template, initialize words 7 -  11 */
4715			memcpy(&wqe->words[7],
4716			       &lpfc_iwrite_cmd_template.words[7],
4717			       sizeof(uint32_t) * 5);
4718
4719			fcp_cmnd->fcpCntl3 = WRITE_DATA;
4720			if (hdwq)
4721				hdwq->scsi_cstat.output_requests++;
4722		} else {
4723			/* From the iread template, initialize words 7 - 11 */
4724			memcpy(&wqe->words[7],
4725			       &lpfc_iread_cmd_template.words[7],
4726			       sizeof(uint32_t) * 5);
4727
4728			/* Word 7 */
4729			bf_set(wqe_tmo, &wqe->fcp_iread.wqe_com, tmo);
4730
4731			fcp_cmnd->fcpCntl3 = READ_DATA;
4732			if (hdwq)
4733				hdwq->scsi_cstat.input_requests++;
4734
4735			/* For a CMF Managed port, iod must be zero'ed */
4736			if (phba->cmf_active_mode == LPFC_CFG_MANAGED)
4737				bf_set(wqe_iod, &wqe->fcp_iread.wqe_com,
4738				       LPFC_WQE_IOD_NONE);
4739		}
4740
4741		/* Additional fcp cdb length field calculation.
4742		 * LPFC_FCP_CDB_LEN_32 - normal 16 byte cdb length,
4743		 * then divide by 4 for the word count.
4744		 * shift 2 because of the RDDATA/WRDATA.
4745		 */
4746		if (scsi_cmnd->cmd_len > LPFC_FCP_CDB_LEN)
4747			fcp_cmnd->fcpCntl3 |= 4 << 2;
4748	} else {
4749		/* From the icmnd template, initialize words 4 - 11 */
4750		memcpy(&wqe->words[4], &lpfc_icmnd_cmd_template.words[4],
4751		       sizeof(uint32_t) * 8);
4752
4753		/* Word 7 */
4754		bf_set(wqe_tmo, &wqe->fcp_icmd.wqe_com, tmo);
4755
4756		fcp_cmnd->fcpCntl3 = 0;
4757		if (hdwq)
4758			hdwq->scsi_cstat.control_requests++;
4759	}
4760
4761	/*
4762	 * Finish initializing those WQE fields that are independent
4763	 * of the request_buffer
4764	 */
4765
4766	 /* Word 3 */
4767	bf_set(payload_offset_len, &wqe->fcp_icmd,
4768	       sizeof(struct fcp_cmnd) + sizeof(struct fcp_rsp));
4769
4770	/* Word 6 */
4771	bf_set(wqe_ctxt_tag, &wqe->generic.wqe_com,
4772	       phba->sli4_hba.rpi_ids[pnode->nlp_rpi]);
4773	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, pwqeq->sli4_xritag);
4774
4775	/* Word 7*/
4776	if (pnode->nlp_fcp_info & NLP_FCP_2_DEVICE)
4777		bf_set(wqe_erp, &wqe->generic.wqe_com, 1);
4778
4779	bf_set(wqe_class, &wqe->generic.wqe_com,
4780	       (pnode->nlp_fcp_info & 0x0f));
4781
4782	 /* Word 8 */
4783	wqe->generic.wqe_com.abort_tag = pwqeq->iotag;
4784
4785	/* Word 9 */
4786	bf_set(wqe_reqtag, &wqe->generic.wqe_com, pwqeq->iotag);
4787
4788	pwqeq->vport = vport;
4789	pwqeq->io_buf = lpfc_cmd;
4790	pwqeq->hba_wqidx = lpfc_cmd->hdwq_no;
4791	pwqeq->cmd_cmpl = lpfc_fcp_io_cmd_wqe_cmpl;
4792
4793	return 0;
4794}
4795
4796/**
4797 * lpfc_scsi_prep_cmnd - Wrapper func for convert scsi cmnd to FCP info unit
4798 * @vport: The virtual port for which this call is being executed.
4799 * @lpfc_cmd: The scsi command which needs to send.
4800 * @pnode: Pointer to lpfc_nodelist.
4801 *
4802 * This routine initializes fcp_cmnd and iocb data structure from scsi command
4803 * to transfer for device with SLI3 interface spec.
4804 **/
4805static int
4806lpfc_scsi_prep_cmnd(struct lpfc_vport *vport, struct lpfc_io_buf *lpfc_cmd,
4807		    struct lpfc_nodelist *pnode)
4808{
4809	struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
4810	struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
4811	u8 *ptr;
4812
4813	if (!pnode)
4814		return 0;
4815
4816	lpfc_cmd->fcp_rsp->rspSnsLen = 0;
4817	/* clear task management bits */
4818	lpfc_cmd->fcp_cmnd->fcpCntl2 = 0;
4819
4820	int_to_scsilun(lpfc_cmd->pCmd->device->lun,
4821		       &lpfc_cmd->fcp_cmnd->fcp_lun);
4822
4823	ptr = &((struct fcp_cmnd32 *)fcp_cmnd)->fcpCdb[0];
4824	memcpy(ptr, scsi_cmnd->cmnd, scsi_cmnd->cmd_len);
4825	if (scsi_cmnd->cmd_len < LPFC_FCP_CDB_LEN) {
4826		ptr += scsi_cmnd->cmd_len;
4827		memset(ptr, 0, (LPFC_FCP_CDB_LEN - scsi_cmnd->cmd_len));
4828	}
4829
4830	fcp_cmnd->fcpCntl1 = SIMPLE_Q;
4831
4832	lpfc_scsi_prep_cmnd_buf(vport, lpfc_cmd, lpfc_cmd->timeout);
4833
4834	return 0;
4835}
4836
4837/**
4838 * lpfc_scsi_prep_task_mgmt_cmd_s3 - Convert SLI3 scsi TM cmd to FCP info unit
4839 * @vport: The virtual port for which this call is being executed.
4840 * @lpfc_cmd: Pointer to lpfc_io_buf data structure.
4841 * @lun: Logical unit number.
4842 * @task_mgmt_cmd: SCSI task management command.
4843 *
4844 * This routine creates FCP information unit corresponding to @task_mgmt_cmd
4845 * for device with SLI-3 interface spec.
4846 *
4847 * Return codes:
4848 *   0 - Error
4849 *   1 - Success
4850 **/
4851static int
4852lpfc_scsi_prep_task_mgmt_cmd_s3(struct lpfc_vport *vport,
4853				struct lpfc_io_buf *lpfc_cmd,
4854				u64 lun, u8 task_mgmt_cmd)
4855{
4856	struct lpfc_iocbq *piocbq;
4857	IOCB_t *piocb;
4858	struct fcp_cmnd *fcp_cmnd;
4859	struct lpfc_rport_data *rdata = lpfc_cmd->rdata;
4860	struct lpfc_nodelist *ndlp = rdata->pnode;
4861
4862	if (!ndlp || ndlp->nlp_state != NLP_STE_MAPPED_NODE)
4863		return 0;
4864
4865	piocbq = &(lpfc_cmd->cur_iocbq);
4866	piocbq->vport = vport;
4867
4868	piocb = &piocbq->iocb;
4869
4870	fcp_cmnd = lpfc_cmd->fcp_cmnd;
4871	/* Clear out any old data in the FCP command area */
4872	memset(fcp_cmnd, 0, sizeof(struct fcp_cmnd));
4873	int_to_scsilun(lun, &fcp_cmnd->fcp_lun);
4874	fcp_cmnd->fcpCntl2 = task_mgmt_cmd;
4875	if (!(vport->phba->sli3_options & LPFC_SLI3_BG_ENABLED))
4876		lpfc_fcpcmd_to_iocb(piocb->unsli3.fcp_ext.icd, fcp_cmnd);
4877	piocb->ulpCommand = CMD_FCP_ICMND64_CR;
4878	piocb->ulpContext = ndlp->nlp_rpi;
4879	piocb->ulpFCP2Rcvy = (ndlp->nlp_fcp_info & NLP_FCP_2_DEVICE) ? 1 : 0;
4880	piocb->ulpClass = (ndlp->nlp_fcp_info & 0x0f);
4881	piocb->ulpPU = 0;
4882	piocb->un.fcpi.fcpi_parm = 0;
4883
4884	/* ulpTimeout is only one byte */
4885	if (lpfc_cmd->timeout > 0xff) {
4886		/*
4887		 * Do not timeout the command at the firmware level.
4888		 * The driver will provide the timeout mechanism.
4889		 */
4890		piocb->ulpTimeout = 0;
4891	} else
4892		piocb->ulpTimeout = lpfc_cmd->timeout;
4893
4894	return 1;
4895}
4896
4897/**
4898 * lpfc_scsi_prep_task_mgmt_cmd_s4 - Convert SLI4 scsi TM cmd to FCP info unit
4899 * @vport: The virtual port for which this call is being executed.
4900 * @lpfc_cmd: Pointer to lpfc_io_buf data structure.
4901 * @lun: Logical unit number.
4902 * @task_mgmt_cmd: SCSI task management command.
4903 *
4904 * This routine creates FCP information unit corresponding to @task_mgmt_cmd
4905 * for device with SLI-4 interface spec.
4906 *
4907 * Return codes:
4908 *   0 - Error
4909 *   1 - Success
4910 **/
4911static int
4912lpfc_scsi_prep_task_mgmt_cmd_s4(struct lpfc_vport *vport,
4913				struct lpfc_io_buf *lpfc_cmd,
4914				u64 lun, u8 task_mgmt_cmd)
4915{
4916	struct lpfc_iocbq *pwqeq = &lpfc_cmd->cur_iocbq;
4917	union lpfc_wqe128 *wqe = &pwqeq->wqe;
4918	struct fcp_cmnd *fcp_cmnd;
4919	struct lpfc_rport_data *rdata = lpfc_cmd->rdata;
4920	struct lpfc_nodelist *ndlp = rdata->pnode;
4921
4922	if (!ndlp || ndlp->nlp_state != NLP_STE_MAPPED_NODE)
4923		return 0;
4924
4925	pwqeq->vport = vport;
4926	/* Initialize 64 bytes only */
4927	memset(wqe, 0, sizeof(union lpfc_wqe128));
4928
4929	/* From the icmnd template, initialize words 4 - 11 */
4930	memcpy(&wqe->words[4], &lpfc_icmnd_cmd_template.words[4],
4931	       sizeof(uint32_t) * 8);
4932
4933	fcp_cmnd = lpfc_cmd->fcp_cmnd;
4934	/* Clear out any old data in the FCP command area */
4935	memset(fcp_cmnd, 0, sizeof(struct fcp_cmnd));
4936	int_to_scsilun(lun, &fcp_cmnd->fcp_lun);
4937	fcp_cmnd->fcpCntl3 = 0;
4938	fcp_cmnd->fcpCntl2 = task_mgmt_cmd;
4939
4940	bf_set(payload_offset_len, &wqe->fcp_icmd,
4941	       sizeof(struct fcp_cmnd) + sizeof(struct fcp_rsp));
4942	bf_set(cmd_buff_len, &wqe->fcp_icmd, 0);
4943	bf_set(wqe_ctxt_tag, &wqe->generic.wqe_com,  /* ulpContext */
4944	       vport->phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
4945	bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
4946	       ((ndlp->nlp_fcp_info & NLP_FCP_2_DEVICE) ? 1 : 0));
4947	bf_set(wqe_class, &wqe->fcp_icmd.wqe_com,
4948	       (ndlp->nlp_fcp_info & 0x0f));
4949
4950	/* ulpTimeout is only one byte */
4951	if (lpfc_cmd->timeout > 0xff) {
4952		/*
4953		 * Do not timeout the command at the firmware level.
4954		 * The driver will provide the timeout mechanism.
4955		 */
4956		bf_set(wqe_tmo, &wqe->fcp_icmd.wqe_com, 0);
4957	} else {
4958		bf_set(wqe_tmo, &wqe->fcp_icmd.wqe_com, lpfc_cmd->timeout);
4959	}
4960
4961	lpfc_prep_embed_io(vport->phba, lpfc_cmd);
4962	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, pwqeq->sli4_xritag);
4963	wqe->generic.wqe_com.abort_tag = pwqeq->iotag;
4964	bf_set(wqe_reqtag, &wqe->generic.wqe_com, pwqeq->iotag);
4965
4966	lpfc_sli4_set_rsp_sgl_last(vport->phba, lpfc_cmd);
4967
4968	return 1;
4969}
4970
4971/**
4972 * lpfc_scsi_api_table_setup - Set up scsi api function jump table
4973 * @phba: The hba struct for which this call is being executed.
4974 * @dev_grp: The HBA PCI-Device group number.
4975 *
4976 * This routine sets up the SCSI interface API function jump table in @phba
4977 * struct.
4978 * Returns: 0 - success, -ENODEV - failure.
4979 **/
4980int
4981lpfc_scsi_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
4982{
4983
4984	phba->lpfc_scsi_unprep_dma_buf = lpfc_scsi_unprep_dma_buf;
4985
4986	switch (dev_grp) {
4987	case LPFC_PCI_DEV_LP:
4988		phba->lpfc_scsi_prep_dma_buf = lpfc_scsi_prep_dma_buf_s3;
4989		phba->lpfc_bg_scsi_prep_dma_buf = lpfc_bg_scsi_prep_dma_buf_s3;
4990		phba->lpfc_release_scsi_buf = lpfc_release_scsi_buf_s3;
4991		phba->lpfc_get_scsi_buf = lpfc_get_scsi_buf_s3;
4992		phba->lpfc_scsi_prep_cmnd_buf = lpfc_scsi_prep_cmnd_buf_s3;
4993		phba->lpfc_scsi_prep_task_mgmt_cmd =
4994					lpfc_scsi_prep_task_mgmt_cmd_s3;
4995		break;
4996	case LPFC_PCI_DEV_OC:
4997		phba->lpfc_scsi_prep_dma_buf = lpfc_scsi_prep_dma_buf_s4;
4998		phba->lpfc_bg_scsi_prep_dma_buf = lpfc_bg_scsi_prep_dma_buf_s4;
4999		phba->lpfc_release_scsi_buf = lpfc_release_scsi_buf_s4;
5000		phba->lpfc_get_scsi_buf = lpfc_get_scsi_buf_s4;
5001		phba->lpfc_scsi_prep_cmnd_buf = lpfc_scsi_prep_cmnd_buf_s4;
5002		phba->lpfc_scsi_prep_task_mgmt_cmd =
5003					lpfc_scsi_prep_task_mgmt_cmd_s4;
5004		break;
5005	default:
5006		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5007				"1418 Invalid HBA PCI-device group: 0x%x\n",
5008				dev_grp);
5009		return -ENODEV;
5010	}
5011	phba->lpfc_rampdown_queue_depth = lpfc_rampdown_queue_depth;
5012	return 0;
5013}
5014
5015/**
5016 * lpfc_tskmgmt_def_cmpl - IOCB completion routine for task management command
5017 * @phba: The Hba for which this call is being executed.
5018 * @cmdiocbq: Pointer to lpfc_iocbq data structure.
5019 * @rspiocbq: Pointer to lpfc_iocbq data structure.
5020 *
5021 * This routine is IOCB completion routine for device reset and target reset
5022 * routine. This routine release scsi buffer associated with lpfc_cmd.
5023 **/
5024static void
5025lpfc_tskmgmt_def_cmpl(struct lpfc_hba *phba,
5026			struct lpfc_iocbq *cmdiocbq,
5027			struct lpfc_iocbq *rspiocbq)
5028{
5029	struct lpfc_io_buf *lpfc_cmd = cmdiocbq->io_buf;
5030	if (lpfc_cmd)
5031		lpfc_release_scsi_buf(phba, lpfc_cmd);
5032	return;
5033}
5034
5035/**
5036 * lpfc_check_pci_resettable - Walks list of devices on pci_dev's bus to check
5037 *                             if issuing a pci_bus_reset is possibly unsafe
5038 * @phba: lpfc_hba pointer.
5039 *
5040 * Description:
5041 * Walks the bus_list to ensure only PCI devices with Emulex
5042 * vendor id, device ids that support hot reset, and only one occurrence
5043 * of function 0.
5044 *
5045 * Returns:
5046 * -EBADSLT,  detected invalid device
5047 *      0,    successful
5048 */
5049int
5050lpfc_check_pci_resettable(struct lpfc_hba *phba)
5051{
5052	const struct pci_dev *pdev = phba->pcidev;
5053	struct pci_dev *ptr = NULL;
5054	u8 counter = 0;
5055
5056	/* Walk the list of devices on the pci_dev's bus */
5057	list_for_each_entry(ptr, &pdev->bus->devices, bus_list) {
5058		/* Check for Emulex Vendor ID */
5059		if (ptr->vendor != PCI_VENDOR_ID_EMULEX) {
5060			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5061					"8346 Non-Emulex vendor found: "
5062					"0x%04x\n", ptr->vendor);
5063			return -EBADSLT;
5064		}
5065
5066		/* Check for valid Emulex Device ID */
5067		if (phba->sli_rev != LPFC_SLI_REV4 ||
5068		    test_bit(HBA_FCOE_MODE, &phba->hba_flag)) {
5069			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5070					"8347 Incapable PCI reset device: "
5071					"0x%04x\n", ptr->device);
5072			return -EBADSLT;
5073		}
5074
5075		/* Check for only one function 0 ID to ensure only one HBA on
5076		 * secondary bus
5077		 */
5078		if (ptr->devfn == 0) {
5079			if (++counter > 1) {
5080				lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5081						"8348 More than one device on "
5082						"secondary bus found\n");
5083				return -EBADSLT;
5084			}
5085		}
5086	}
5087
5088	return 0;
5089}
5090
5091/**
5092 * lpfc_info - Info entry point of scsi_host_template data structure
5093 * @host: The scsi host for which this call is being executed.
5094 *
5095 * This routine provides module information about hba.
5096 *
5097 * Reutrn code:
5098 *   Pointer to char - Success.
5099 **/
5100const char *
5101lpfc_info(struct Scsi_Host *host)
5102{
5103	struct lpfc_vport *vport = (struct lpfc_vport *) host->hostdata;
5104	struct lpfc_hba   *phba = vport->phba;
5105	int link_speed = 0;
5106	static char lpfcinfobuf[384];
5107	char tmp[384] = {0};
5108
5109	memset(lpfcinfobuf, 0, sizeof(lpfcinfobuf));
5110	if (phba && phba->pcidev){
5111		/* Model Description */
5112		scnprintf(tmp, sizeof(tmp), phba->ModelDesc);
5113		if (strlcat(lpfcinfobuf, tmp, sizeof(lpfcinfobuf)) >=
5114		    sizeof(lpfcinfobuf))
5115			goto buffer_done;
5116
5117		/* PCI Info */
5118		scnprintf(tmp, sizeof(tmp),
5119			  " on PCI bus %02x device %02x irq %d",
5120			  phba->pcidev->bus->number, phba->pcidev->devfn,
5121			  phba->pcidev->irq);
5122		if (strlcat(lpfcinfobuf, tmp, sizeof(lpfcinfobuf)) >=
5123		    sizeof(lpfcinfobuf))
5124			goto buffer_done;
5125
5126		/* Port Number */
5127		if (phba->Port[0]) {
5128			scnprintf(tmp, sizeof(tmp), " port %s", phba->Port);
5129			if (strlcat(lpfcinfobuf, tmp, sizeof(lpfcinfobuf)) >=
5130			    sizeof(lpfcinfobuf))
5131				goto buffer_done;
5132		}
5133
5134		/* Link Speed */
5135		link_speed = lpfc_sli_port_speed_get(phba);
5136		if (link_speed != 0) {
5137			scnprintf(tmp, sizeof(tmp),
5138				  " Logical Link Speed: %d Mbps", link_speed);
5139			if (strlcat(lpfcinfobuf, tmp, sizeof(lpfcinfobuf)) >=
5140			    sizeof(lpfcinfobuf))
5141				goto buffer_done;
5142		}
5143
5144		/* Support for BSG ioctls */
5145		scnprintf(tmp, sizeof(tmp), " BSG");
5146		if (strlcat(lpfcinfobuf, tmp, sizeof(lpfcinfobuf)) >=
5147		    sizeof(lpfcinfobuf))
5148			goto buffer_done;
5149
5150		/* PCI resettable */
5151		if (!lpfc_check_pci_resettable(phba)) {
5152			scnprintf(tmp, sizeof(tmp), " PCI resettable");
5153			strlcat(lpfcinfobuf, tmp, sizeof(lpfcinfobuf));
5154		}
5155	}
5156
5157buffer_done:
5158	return lpfcinfobuf;
5159}
5160
5161/**
5162 * lpfc_poll_rearm_timer - Routine to modify fcp_poll timer of hba
5163 * @phba: The Hba for which this call is being executed.
5164 *
5165 * This routine modifies fcp_poll_timer  field of @phba by cfg_poll_tmo.
5166 * The default value of cfg_poll_tmo is 10 milliseconds.
5167 **/
5168static __inline__ void lpfc_poll_rearm_timer(struct lpfc_hba * phba)
5169{
5170	unsigned long  poll_tmo_expires =
5171		(jiffies + msecs_to_jiffies(phba->cfg_poll_tmo));
5172
5173	if (!list_empty(&phba->sli.sli3_ring[LPFC_FCP_RING].txcmplq))
5174		mod_timer(&phba->fcp_poll_timer,
5175			  poll_tmo_expires);
5176}
5177
5178/**
5179 * lpfc_poll_start_timer - Routine to start fcp_poll_timer of HBA
5180 * @phba: The Hba for which this call is being executed.
5181 *
5182 * This routine starts the fcp_poll_timer of @phba.
5183 **/
5184void lpfc_poll_start_timer(struct lpfc_hba * phba)
5185{
5186	lpfc_poll_rearm_timer(phba);
5187}
5188
5189/**
5190 * lpfc_poll_timeout - Restart polling timer
5191 * @t: Timer construct where lpfc_hba data structure pointer is obtained.
5192 *
5193 * This routine restarts fcp_poll timer, when FCP ring  polling is enable
5194 * and FCP Ring interrupt is disable.
5195 **/
5196void lpfc_poll_timeout(struct timer_list *t)
5197{
5198	struct lpfc_hba *phba = timer_container_of(phba, t, fcp_poll_timer);
5199
5200	if (phba->cfg_poll & ENABLE_FCP_RING_POLLING) {
5201		lpfc_sli_handle_fast_ring_event(phba,
5202			&phba->sli.sli3_ring[LPFC_FCP_RING], HA_R0RE_REQ);
5203
5204		if (phba->cfg_poll & DISABLE_FCP_RING_INT)
5205			lpfc_poll_rearm_timer(phba);
5206	}
5207}
5208
5209/*
5210 * lpfc_is_command_vm_io - get the UUID from blk cgroup
5211 * @cmd: Pointer to scsi_cmnd data structure
5212 * Returns UUID if present, otherwise NULL
5213 */
5214static char *lpfc_is_command_vm_io(struct scsi_cmnd *cmd)
5215{
5216	struct bio *bio = scsi_cmd_to_rq(cmd)->bio;
5217
5218	if (!IS_ENABLED(CONFIG_BLK_CGROUP_FC_APPID) || !bio)
5219		return NULL;
5220	return blkcg_get_fc_appid(bio);
5221}
5222
5223/**
5224 * lpfc_queuecommand - scsi_host_template queuecommand entry point
5225 * @shost: kernel scsi host pointer.
5226 * @cmnd: Pointer to scsi_cmnd data structure.
5227 *
5228 * Driver registers this routine to scsi midlayer to submit a @cmd to process.
5229 * This routine prepares an IOCB from scsi command and provides to firmware.
5230 * The @done callback is invoked after driver finished processing the command.
5231 *
5232 * Return value :
5233 *   0 - Success
5234 *   SCSI_MLQUEUE_HOST_BUSY - Block all devices served by this host temporarily.
5235 **/
5236static int
5237lpfc_queuecommand(struct Scsi_Host *shost, struct scsi_cmnd *cmnd)
5238{
5239	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
5240	struct lpfc_hba   *phba = vport->phba;
5241	struct lpfc_iocbq *cur_iocbq = NULL;
5242	struct lpfc_rport_data *rdata;
5243	struct lpfc_nodelist *ndlp;
5244	struct lpfc_io_buf *lpfc_cmd;
5245	struct fc_rport *rport = starget_to_rport(scsi_target(cmnd->device));
5246	int err, idx;
5247	u8 *uuid = NULL;
5248	uint64_t start;
5249
5250	start = ktime_get_ns();
5251	rdata = lpfc_rport_data_from_scsi_device(cmnd->device);
5252
5253	/* sanity check on references */
5254	if (unlikely(!rdata) || unlikely(!rport))
5255		goto out_fail_command;
5256
5257	err = fc_remote_port_chkready(rport);
5258	if (err) {
5259		cmnd->result = err;
5260		goto out_fail_command;
5261	}
5262	ndlp = rdata->pnode;
5263
5264	if ((scsi_get_prot_op(cmnd) != SCSI_PROT_NORMAL) &&
5265		(!(phba->sli3_options & LPFC_SLI3_BG_ENABLED))) {
5266
5267		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5268				"9058 BLKGRD: ERROR: rcvd protected cmd:%02x"
5269				" op:%02x str=%s without registering for"
5270				" BlockGuard - Rejecting command\n",
5271				cmnd->cmnd[0], scsi_get_prot_op(cmnd),
5272				dif_op_str[scsi_get_prot_op(cmnd)]);
5273		goto out_fail_command;
5274	}
5275
5276	/*
5277	 * Catch race where our node has transitioned, but the
5278	 * transport is still transitioning.
5279	 */
5280	if (!ndlp)
5281		goto out_tgt_busy1;
5282
5283	/* Check if IO qualifies for CMF */
5284	if (phba->cmf_active_mode != LPFC_CFG_OFF &&
5285	    cmnd->sc_data_direction == DMA_FROM_DEVICE &&
5286	    (scsi_sg_count(cmnd))) {
5287		/* Latency start time saved in rx_cmd_start later in routine */
5288		err = lpfc_update_cmf_cmd(phba, scsi_bufflen(cmnd));
5289		if (err)
5290			goto out_tgt_busy1;
5291	}
5292
5293	if (lpfc_ndlp_check_qdepth(phba, ndlp)) {
5294		if (atomic_read(&ndlp->cmd_pending) >= ndlp->cmd_qdepth) {
5295			lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP_ERROR,
5296					 "3377 Target Queue Full, scsi Id:%d "
5297					 "Qdepth:%d Pending command:%d"
5298					 " WWNN:%02x:%02x:%02x:%02x:"
5299					 "%02x:%02x:%02x:%02x, "
5300					 " WWPN:%02x:%02x:%02x:%02x:"
5301					 "%02x:%02x:%02x:%02x",
5302					 ndlp->nlp_sid, ndlp->cmd_qdepth,
5303					 atomic_read(&ndlp->cmd_pending),
5304					 ndlp->nlp_nodename.u.wwn[0],
5305					 ndlp->nlp_nodename.u.wwn[1],
5306					 ndlp->nlp_nodename.u.wwn[2],
5307					 ndlp->nlp_nodename.u.wwn[3],
5308					 ndlp->nlp_nodename.u.wwn[4],
5309					 ndlp->nlp_nodename.u.wwn[5],
5310					 ndlp->nlp_nodename.u.wwn[6],
5311					 ndlp->nlp_nodename.u.wwn[7],
5312					 ndlp->nlp_portname.u.wwn[0],
5313					 ndlp->nlp_portname.u.wwn[1],
5314					 ndlp->nlp_portname.u.wwn[2],
5315					 ndlp->nlp_portname.u.wwn[3],
5316					 ndlp->nlp_portname.u.wwn[4],
5317					 ndlp->nlp_portname.u.wwn[5],
5318					 ndlp->nlp_portname.u.wwn[6],
5319					 ndlp->nlp_portname.u.wwn[7]);
5320			goto out_tgt_busy2;
5321		}
5322	}
5323
5324	lpfc_cmd = lpfc_get_scsi_buf(phba, ndlp, cmnd);
5325	if (lpfc_cmd == NULL) {
5326		lpfc_rampdown_queue_depth(phba);
5327
5328		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP_ERROR,
5329				 "0707 driver's buffer pool is empty, "
5330				 "IO busied\n");
5331		goto out_host_busy;
5332	}
5333	lpfc_cmd->rx_cmd_start = start;
5334
5335	cur_iocbq = &lpfc_cmd->cur_iocbq;
5336	/*
5337	 * Store the midlayer's command structure for the completion phase
5338	 * and complete the command initialization.
5339	 */
5340	lpfc_cmd->pCmd  = cmnd;
5341	lpfc_cmd->rdata = rdata;
5342	lpfc_cmd->ndlp = ndlp;
5343	cur_iocbq->cmd_cmpl = NULL;
5344	cmnd->host_scribble = (unsigned char *)lpfc_cmd;
5345
5346	err = lpfc_scsi_prep_cmnd(vport, lpfc_cmd, ndlp);
5347	if (err)
5348		goto out_host_busy_release_buf;
5349
5350	if (scsi_get_prot_op(cmnd) != SCSI_PROT_NORMAL) {
5351		if (vport->phba->cfg_enable_bg) {
5352			lpfc_printf_vlog(vport,
5353					 KERN_INFO, LOG_SCSI_CMD,
5354					 "9033 BLKGRD: rcvd %s cmd:x%x "
5355					 "reftag x%x cnt %u pt %x\n",
5356					 dif_op_str[scsi_get_prot_op(cmnd)],
5357					 cmnd->cmnd[0],
5358					 scsi_prot_ref_tag(cmnd),
5359					 scsi_logical_block_count(cmnd),
5360					 scsi_get_prot_type(cmnd));
5361		}
5362		err = lpfc_bg_scsi_prep_dma_buf(phba, lpfc_cmd);
5363	} else {
5364		err = lpfc_scsi_prep_dma_buf(phba, lpfc_cmd);
5365	}
5366
5367	if (unlikely(err)) {
5368		if (err == 2) {
5369			cmnd->result = DID_ERROR << 16;
5370			goto out_fail_command_release_buf;
5371		}
5372		goto out_host_busy_free_buf;
5373	}
5374
5375	/* check the necessary and sufficient condition to support VMID */
5376	if (lpfc_is_vmid_enabled(phba) &&
5377	    (ndlp->vmid_support ||
5378	     phba->pport->vmid_priority_tagging ==
5379	     LPFC_VMID_PRIO_TAG_ALL_TARGETS)) {
5380		/* is the I/O generated by a VM, get the associated virtual */
5381		/* entity id */
5382		uuid = lpfc_is_command_vm_io(cmnd);
5383
5384		if (uuid) {
5385			err = lpfc_vmid_get_appid(vport, uuid,
5386					cmnd->sc_data_direction,
5387					(union lpfc_vmid_io_tag *)
5388						&cur_iocbq->vmid_tag);
5389			if (!err)
5390				cur_iocbq->cmd_flag |= LPFC_IO_VMID;
5391		}
5392	}
5393
5394#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
5395	if (unlikely(phba->hdwqstat_on & LPFC_CHECK_SCSI_IO))
5396		this_cpu_inc(phba->sli4_hba.c_stat->xmt_io);
5397#endif
5398	/* Issue I/O to adapter */
5399	err = lpfc_sli_issue_fcp_io(phba, LPFC_FCP_RING, cur_iocbq,
5400				    SLI_IOCB_RET_IOCB);
5401#ifdef CONFIG_SCSI_LPFC_DEBUG_FS
5402	if (start) {
5403		lpfc_cmd->ts_cmd_start = start;
5404		lpfc_cmd->ts_last_cmd = phba->ktime_last_cmd;
5405		lpfc_cmd->ts_cmd_wqput = ktime_get_ns();
5406	} else {
5407		lpfc_cmd->ts_cmd_start = 0;
5408	}
5409#endif
5410	if (err) {
5411		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5412				 "3376 FCP could not issue iocb err %x "
5413				 "FCP cmd x%x <%d/%llu> "
5414				 "sid: x%x did: x%x oxid: x%x "
5415				 "Data: x%x x%x x%x x%x\n",
5416				 err, cmnd->cmnd[0],
5417				 cmnd->device ? cmnd->device->id : 0xffff,
5418				 cmnd->device ? cmnd->device->lun : (u64)-1,
5419				 vport->fc_myDID, ndlp->nlp_DID,
5420				 phba->sli_rev == LPFC_SLI_REV4 ?
5421				 cur_iocbq->sli4_xritag : 0xffff,
5422				 phba->sli_rev == LPFC_SLI_REV4 ?
5423				 phba->sli4_hba.rpi_ids[ndlp->nlp_rpi] :
5424				 cur_iocbq->iocb.ulpContext,
5425				 cur_iocbq->iotag,
5426				 phba->sli_rev == LPFC_SLI_REV4 ?
5427				 bf_get(wqe_tmo,
5428					&cur_iocbq->wqe.generic.wqe_com) :
5429				 cur_iocbq->iocb.ulpTimeout,
5430				 (uint32_t)(scsi_cmd_to_rq(cmnd)->timeout / 1000));
5431
5432		goto out_host_busy_free_buf;
5433	}
5434
5435	if (phba->cfg_poll & ENABLE_FCP_RING_POLLING) {
5436		lpfc_sli_handle_fast_ring_event(phba,
5437			&phba->sli.sli3_ring[LPFC_FCP_RING], HA_R0RE_REQ);
5438
5439		if (phba->cfg_poll & DISABLE_FCP_RING_INT)
5440			lpfc_poll_rearm_timer(phba);
5441	}
5442
5443	if (phba->cfg_xri_rebalancing)
5444		lpfc_keep_pvt_pool_above_lowwm(phba, lpfc_cmd->hdwq_no);
5445
5446	return 0;
5447
5448 out_host_busy_free_buf:
5449	idx = lpfc_cmd->hdwq_no;
5450	lpfc_scsi_unprep_dma_buf(phba, lpfc_cmd);
5451	if (phba->sli4_hba.hdwq) {
5452		switch (lpfc_cmd->fcp_cmnd->fcpCntl3) {
5453		case WRITE_DATA:
5454			phba->sli4_hba.hdwq[idx].scsi_cstat.output_requests--;
5455			break;
5456		case READ_DATA:
5457			phba->sli4_hba.hdwq[idx].scsi_cstat.input_requests--;
5458			break;
5459		default:
5460			phba->sli4_hba.hdwq[idx].scsi_cstat.control_requests--;
5461		}
5462	}
5463 out_host_busy_release_buf:
5464	lpfc_release_scsi_buf(phba, lpfc_cmd);
5465 out_host_busy:
5466	lpfc_update_cmf_cmpl(phba, LPFC_CGN_NOT_SENT, scsi_bufflen(cmnd),
5467			     shost);
5468	return SCSI_MLQUEUE_HOST_BUSY;
5469
5470 out_tgt_busy2:
5471	lpfc_update_cmf_cmpl(phba, LPFC_CGN_NOT_SENT, scsi_bufflen(cmnd),
5472			     shost);
5473 out_tgt_busy1:
5474	return SCSI_MLQUEUE_TARGET_BUSY;
5475
5476 out_fail_command_release_buf:
5477	lpfc_release_scsi_buf(phba, lpfc_cmd);
5478	lpfc_update_cmf_cmpl(phba, LPFC_CGN_NOT_SENT, scsi_bufflen(cmnd),
5479			     shost);
5480
5481 out_fail_command:
5482	scsi_done(cmnd);
5483	return 0;
5484}
5485
5486/*
5487 * lpfc_vmid_vport_cleanup - cleans up the resources associated with a vport
5488 * @vport: The virtual port for which this call is being executed.
5489 */
5490void lpfc_vmid_vport_cleanup(struct lpfc_vport *vport)
5491{
5492	u32 bucket;
5493	struct lpfc_vmid *cur;
5494
5495	if (vport->port_type == LPFC_PHYSICAL_PORT)
5496		timer_delete_sync(&vport->phba->inactive_vmid_poll);
5497
5498	kfree(vport->qfpa_res);
5499	kfree(vport->vmid_priority.vmid_range);
5500	kfree(vport->vmid);
5501
5502	if (!hash_empty(vport->hash_table))
5503		hash_for_each(vport->hash_table, bucket, cur, hnode)
5504			hash_del(&cur->hnode);
5505
5506	vport->qfpa_res = NULL;
5507	vport->vmid_priority.vmid_range = NULL;
5508	vport->vmid = NULL;
5509	vport->cur_vmid_cnt = 0;
5510}
5511
5512/**
5513 * lpfc_abort_handler - scsi_host_template eh_abort_handler entry point
5514 * @cmnd: Pointer to scsi_cmnd data structure.
5515 *
5516 * This routine aborts @cmnd pending in base driver.
5517 *
5518 * Return code :
5519 *   0x2003 - Error
5520 *   0x2002 - Success
5521 **/
5522static int
5523lpfc_abort_handler(struct scsi_cmnd *cmnd)
5524{
5525	struct Scsi_Host  *shost = cmnd->device->host;
5526	struct fc_rport *rport = starget_to_rport(scsi_target(cmnd->device));
5527	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
5528	struct lpfc_hba   *phba = vport->phba;
5529	struct lpfc_iocbq *iocb;
5530	struct lpfc_io_buf *lpfc_cmd;
5531	int ret = SUCCESS, status = 0;
5532	struct lpfc_sli_ring *pring_s4 = NULL;
5533	struct lpfc_sli_ring *pring = NULL;
5534	int ret_val;
5535	unsigned long flags;
5536	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(waitq);
5537
5538	status = fc_block_rport(rport);
5539	if (status != 0 && status != SUCCESS)
5540		return status;
5541
5542	lpfc_cmd = (struct lpfc_io_buf *)cmnd->host_scribble;
5543	if (!lpfc_cmd)
5544		return ret;
5545
5546	/* Guard against IO completion being called at same time */
5547	spin_lock_irqsave(&lpfc_cmd->buf_lock, flags);
5548
5549	spin_lock(&phba->hbalock);
5550	/* driver queued commands are in process of being flushed */
5551	if (test_bit(HBA_IOQ_FLUSH, &phba->hba_flag)) {
5552		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5553			"3168 SCSI Layer abort requested I/O has been "
5554			"flushed by LLD.\n");
5555		ret = FAILED;
5556		goto out_unlock_hba;
5557	}
5558
5559	if (!lpfc_cmd->pCmd) {
5560		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5561			 "2873 SCSI Layer I/O Abort Request IO CMPL Status "
5562			 "x%x ID %d LUN %llu\n",
5563			 SUCCESS, cmnd->device->id, cmnd->device->lun);
5564		goto out_unlock_hba;
5565	}
5566
5567	iocb = &lpfc_cmd->cur_iocbq;
5568	if (phba->sli_rev == LPFC_SLI_REV4) {
5569		/* if the io_wq & pring are gone, the port was reset. */
5570		if (!phba->sli4_hba.hdwq[iocb->hba_wqidx].io_wq ||
5571		    !phba->sli4_hba.hdwq[iocb->hba_wqidx].io_wq->pring) {
5572			lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5573					 "2877 SCSI Layer I/O Abort Request "
5574					 "IO CMPL Status x%x ID %d LUN %llu "
5575					 "HBA_SETUP %d\n", FAILED,
5576					 cmnd->device->id,
5577					 (u64)cmnd->device->lun,
5578					 test_bit(HBA_SETUP, &phba->hba_flag));
5579			ret = FAILED;
5580			goto out_unlock_hba;
5581		}
5582		pring_s4 = phba->sli4_hba.hdwq[iocb->hba_wqidx].io_wq->pring;
5583		spin_lock(&pring_s4->ring_lock);
5584	}
5585	/* the command is in process of being cancelled */
5586	if (!(iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ)) {
5587		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5588			"3169 SCSI Layer abort requested I/O has been "
5589			"cancelled by LLD.\n");
5590		ret = FAILED;
5591		goto out_unlock_ring;
5592	}
5593	/*
5594	 * If pCmd field of the corresponding lpfc_io_buf structure
5595	 * points to a different SCSI command, then the driver has
5596	 * already completed this command, but the midlayer did not
5597	 * see the completion before the eh fired. Just return SUCCESS.
5598	 */
5599	if (lpfc_cmd->pCmd != cmnd) {
5600		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5601			"3170 SCSI Layer abort requested I/O has been "
5602			"completed by LLD.\n");
5603		goto out_unlock_ring;
5604	}
5605
5606	WARN_ON(iocb->io_buf != lpfc_cmd);
5607
5608	/* abort issued in recovery is still in progress */
5609	if (iocb->cmd_flag & LPFC_DRIVER_ABORTED) {
5610		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5611			 "3389 SCSI Layer I/O Abort Request is pending\n");
5612		if (phba->sli_rev == LPFC_SLI_REV4)
5613			spin_unlock(&pring_s4->ring_lock);
5614		spin_unlock(&phba->hbalock);
5615		spin_unlock_irqrestore(&lpfc_cmd->buf_lock, flags);
5616		goto wait_for_cmpl;
5617	}
5618
5619	lpfc_cmd->waitq = &waitq;
5620	if (phba->sli_rev == LPFC_SLI_REV4) {
5621		spin_unlock(&pring_s4->ring_lock);
5622		ret_val = lpfc_sli4_issue_abort_iotag(phba, iocb,
5623						      lpfc_sli_abort_fcp_cmpl);
5624	} else {
5625		pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
5626		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocb,
5627						     lpfc_sli_abort_fcp_cmpl);
5628	}
5629
5630	/* Make sure HBA is alive */
5631	lpfc_issue_hb_tmo(phba);
5632
5633	if (ret_val != IOCB_SUCCESS) {
5634		/* Indicate the IO is not being aborted by the driver. */
5635		lpfc_cmd->waitq = NULL;
5636		ret = FAILED;
5637		goto out_unlock_hba;
5638	}
5639
5640	/* no longer need the lock after this point */
5641	spin_unlock(&phba->hbalock);
5642	spin_unlock_irqrestore(&lpfc_cmd->buf_lock, flags);
5643
5644	if (phba->cfg_poll & DISABLE_FCP_RING_INT)
5645		lpfc_sli_handle_fast_ring_event(phba,
5646			&phba->sli.sli3_ring[LPFC_FCP_RING], HA_R0RE_REQ);
5647
5648wait_for_cmpl:
5649	/*
5650	 * cmd_flag is set to LPFC_DRIVER_ABORTED before we wait
5651	 * for abort to complete.
5652	 */
5653	wait_event_timeout(waitq, (lpfc_cmd->pCmd != cmnd),
5654			   secs_to_jiffies(2*vport->cfg_devloss_tmo));
5655
5656	spin_lock(&lpfc_cmd->buf_lock);
5657
5658	if (lpfc_cmd->pCmd == cmnd) {
5659		ret = FAILED;
5660		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
5661				 "0748 abort handler timed out waiting "
5662				 "for aborting I/O (xri:x%x) to complete: "
5663				 "ret %#x, ID %d, LUN %llu\n",
5664				 iocb->sli4_xritag, ret,
5665				 cmnd->device->id, cmnd->device->lun);
5666	}
5667
5668	lpfc_cmd->waitq = NULL;
5669
5670	spin_unlock(&lpfc_cmd->buf_lock);
5671	goto out;
5672
5673out_unlock_ring:
5674	if (phba->sli_rev == LPFC_SLI_REV4)
5675		spin_unlock(&pring_s4->ring_lock);
5676out_unlock_hba:
5677	spin_unlock(&phba->hbalock);
5678	spin_unlock_irqrestore(&lpfc_cmd->buf_lock, flags);
5679out:
5680	lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5681			 "0749 SCSI Layer I/O Abort Request Status x%x ID %d "
5682			 "LUN %llu\n", ret, cmnd->device->id,
5683			 cmnd->device->lun);
5684	return ret;
5685}
5686
5687static char *
5688lpfc_taskmgmt_name(uint8_t task_mgmt_cmd)
5689{
5690	switch (task_mgmt_cmd) {
5691	case FCP_ABORT_TASK_SET:
5692		return "ABORT_TASK_SET";
5693	case FCP_CLEAR_TASK_SET:
5694		return "FCP_CLEAR_TASK_SET";
5695	case FCP_BUS_RESET:
5696		return "FCP_BUS_RESET";
5697	case FCP_LUN_RESET:
5698		return "FCP_LUN_RESET";
5699	case FCP_TARGET_RESET:
5700		return "FCP_TARGET_RESET";
5701	case FCP_CLEAR_ACA:
5702		return "FCP_CLEAR_ACA";
5703	case FCP_TERMINATE_TASK:
5704		return "FCP_TERMINATE_TASK";
5705	default:
5706		return "unknown";
5707	}
5708}
5709
5710
5711/**
5712 * lpfc_check_fcp_rsp - check the returned fcp_rsp to see if task failed
5713 * @vport: The virtual port for which this call is being executed.
5714 * @lpfc_cmd: Pointer to lpfc_io_buf data structure.
5715 *
5716 * This routine checks the FCP RSP INFO to see if the tsk mgmt command succeded
5717 *
5718 * Return code :
5719 *   0x2003 - Error
5720 *   0x2002 - Success
5721 **/
5722static int
5723lpfc_check_fcp_rsp(struct lpfc_vport *vport, struct lpfc_io_buf *lpfc_cmd)
5724{
5725	struct fcp_rsp *fcprsp = lpfc_cmd->fcp_rsp;
5726	uint32_t rsp_info;
5727	uint32_t rsp_len;
5728	uint8_t  rsp_info_code;
5729	int ret = FAILED;
5730
5731
5732	if (fcprsp == NULL)
5733		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5734				 "0703 fcp_rsp is missing\n");
5735	else {
5736		rsp_info = fcprsp->rspStatus2;
5737		rsp_len = be32_to_cpu(fcprsp->rspRspLen);
5738		rsp_info_code = fcprsp->rspInfo3;
5739
5740
5741		lpfc_printf_vlog(vport, KERN_INFO,
5742				 LOG_FCP,
5743				 "0706 fcp_rsp valid 0x%x,"
5744				 " rsp len=%d code 0x%x\n",
5745				 rsp_info,
5746				 rsp_len, rsp_info_code);
5747
5748		/* If FCP_RSP_LEN_VALID bit is one, then the FCP_RSP_LEN
5749		 * field specifies the number of valid bytes of FCP_RSP_INFO.
5750		 * The FCP_RSP_LEN field shall be set to 0x04 or 0x08
5751		 */
5752		if ((fcprsp->rspStatus2 & RSP_LEN_VALID) &&
5753		    ((rsp_len == 8) || (rsp_len == 4))) {
5754			switch (rsp_info_code) {
5755			case RSP_NO_FAILURE:
5756				lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5757						 "0715 Task Mgmt No Failure\n");
5758				ret = SUCCESS;
5759				break;
5760			case RSP_TM_NOT_SUPPORTED: /* TM rejected */
5761				lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5762						 "0716 Task Mgmt Target "
5763						"reject\n");
5764				break;
5765			case RSP_TM_NOT_COMPLETED: /* TM failed */
5766				lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5767						 "0717 Task Mgmt Target "
5768						"failed TM\n");
5769				break;
5770			case RSP_TM_INVALID_LU: /* TM to invalid LU! */
5771				lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5772						 "0718 Task Mgmt to invalid "
5773						"LUN\n");
5774				break;
5775			}
5776		}
5777	}
5778	return ret;
5779}
5780
5781
5782/**
5783 * lpfc_send_taskmgmt - Generic SCSI Task Mgmt Handler
5784 * @vport: The virtual port for which this call is being executed.
5785 * @rport: Pointer to remote port
5786 * @tgt_id: Target ID of remote device.
5787 * @lun_id: Lun number for the TMF
5788 * @task_mgmt_cmd: type of TMF to send
5789 *
5790 * This routine builds and sends a TMF (SCSI Task Mgmt Function) to
5791 * a remote port.
5792 *
5793 * Return Code:
5794 *   0x2003 - Error
5795 *   0x2002 - Success.
5796 **/
5797static int
5798lpfc_send_taskmgmt(struct lpfc_vport *vport, struct fc_rport *rport,
5799		   unsigned int tgt_id, uint64_t lun_id,
5800		   uint8_t task_mgmt_cmd)
5801{
5802	struct lpfc_hba   *phba = vport->phba;
5803	struct lpfc_io_buf *lpfc_cmd;
5804	struct lpfc_iocbq *iocbq;
5805	struct lpfc_iocbq *iocbqrsp;
5806	struct lpfc_rport_data *rdata;
5807	struct lpfc_nodelist *pnode;
5808	int ret;
5809	int status;
5810
5811	rdata = rport->dd_data;
5812	if (!rdata || !rdata->pnode)
5813		return FAILED;
5814	pnode = rdata->pnode;
5815
5816	lpfc_cmd = lpfc_get_scsi_buf(phba, rdata->pnode, NULL);
5817	if (lpfc_cmd == NULL)
5818		return FAILED;
5819	lpfc_cmd->timeout = phba->cfg_task_mgmt_tmo;
5820	lpfc_cmd->rdata = rdata;
5821	lpfc_cmd->pCmd = NULL;
5822	lpfc_cmd->ndlp = pnode;
5823
5824	status = phba->lpfc_scsi_prep_task_mgmt_cmd(vport, lpfc_cmd, lun_id,
5825						    task_mgmt_cmd);
5826	if (!status) {
5827		lpfc_release_scsi_buf(phba, lpfc_cmd);
5828		return FAILED;
5829	}
5830
5831	iocbq = &lpfc_cmd->cur_iocbq;
5832	iocbqrsp = lpfc_sli_get_iocbq(phba);
5833	if (iocbqrsp == NULL) {
5834		lpfc_release_scsi_buf(phba, lpfc_cmd);
5835		return FAILED;
5836	}
5837	iocbq->cmd_cmpl = lpfc_tskmgmt_def_cmpl;
5838	iocbq->vport = vport;
5839
5840	lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5841			 "0702 Issue %s to TGT %d LUN %llu "
5842			 "rpi x%x nlp_flag x%lx Data: x%x x%x\n",
5843			 lpfc_taskmgmt_name(task_mgmt_cmd), tgt_id, lun_id,
5844			 pnode->nlp_rpi, pnode->nlp_flag, iocbq->sli4_xritag,
5845			 iocbq->cmd_flag);
5846
5847	status = lpfc_sli_issue_iocb_wait(phba, LPFC_FCP_RING,
5848					  iocbq, iocbqrsp, lpfc_cmd->timeout);
5849	if ((status != IOCB_SUCCESS) ||
5850	    (get_job_ulpstatus(phba, iocbqrsp) != IOSTAT_SUCCESS)) {
5851		if (status != IOCB_SUCCESS ||
5852		    get_job_ulpstatus(phba, iocbqrsp) != IOSTAT_FCP_RSP_ERROR)
5853			lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
5854					 "0727 TMF %s to TGT %d LUN %llu "
5855					 "failed (%d, %d) cmd_flag x%x\n",
5856					 lpfc_taskmgmt_name(task_mgmt_cmd),
5857					 tgt_id, lun_id,
5858					 get_job_ulpstatus(phba, iocbqrsp),
5859					 get_job_word4(phba, iocbqrsp),
5860					 iocbq->cmd_flag);
5861		/* if ulpStatus != IOCB_SUCCESS, then status == IOCB_SUCCESS */
5862		if (status == IOCB_SUCCESS) {
5863			if (get_job_ulpstatus(phba, iocbqrsp) ==
5864			    IOSTAT_FCP_RSP_ERROR)
5865				/* Something in the FCP_RSP was invalid.
5866				 * Check conditions */
5867				ret = lpfc_check_fcp_rsp(vport, lpfc_cmd);
5868			else
5869				ret = FAILED;
5870		} else if ((status == IOCB_TIMEDOUT) ||
5871			   (status == IOCB_ABORTED)) {
5872			ret = TIMEOUT_ERROR;
5873		} else {
5874			ret = FAILED;
5875		}
5876	} else
5877		ret = SUCCESS;
5878
5879	lpfc_sli_release_iocbq(phba, iocbqrsp);
5880
5881	if (status != IOCB_TIMEDOUT)
5882		lpfc_release_scsi_buf(phba, lpfc_cmd);
5883
5884	return ret;
5885}
5886
5887/**
5888 * lpfc_chk_tgt_mapped -
5889 * @vport: The virtual port to check on
5890 * @rport: Pointer to fc_rport data structure.
5891 *
5892 * This routine delays until the scsi target (aka rport) for the
5893 * command exists (is present and logged in) or we declare it non-existent.
5894 *
5895 * Return code :
5896 *  0x2003 - Error
5897 *  0x2002 - Success
5898 **/
5899static int
5900lpfc_chk_tgt_mapped(struct lpfc_vport *vport, struct fc_rport *rport)
5901{
5902	struct lpfc_rport_data *rdata;
5903	struct lpfc_nodelist *pnode = NULL;
5904	unsigned long later;
5905
5906	rdata = rport->dd_data;
5907	if (!rdata) {
5908		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5909			"0797 Tgt Map rport failure: rdata x%px\n", rdata);
5910		return FAILED;
5911	}
5912	pnode = rdata->pnode;
5913
5914	/*
5915	 * If target is not in a MAPPED state, delay until
5916	 * target is rediscovered or devloss timeout expires.
5917	 */
5918	later = secs_to_jiffies(2 * vport->cfg_devloss_tmo) + jiffies;
5919	while (time_after(later, jiffies)) {
5920		if (!pnode)
5921			return FAILED;
5922		if (pnode->nlp_state == NLP_STE_MAPPED_NODE)
5923			return SUCCESS;
5924		schedule_timeout_uninterruptible(msecs_to_jiffies(500));
5925		rdata = rport->dd_data;
5926		if (!rdata)
5927			return FAILED;
5928		pnode = rdata->pnode;
5929	}
5930	if (!pnode || (pnode->nlp_state != NLP_STE_MAPPED_NODE))
5931		return FAILED;
5932	return SUCCESS;
5933}
5934
5935/**
5936 * lpfc_reset_flush_io_context -
5937 * @vport: The virtual port (scsi_host) for the flush context
5938 * @tgt_id: If aborting by Target context - specifies the target id
5939 * @lun_id: If aborting by Lun context - specifies the lun id
5940 * @context: specifies the context level to flush at.
5941 *
5942 * After a reset condition via TMF, we need to flush orphaned i/o
5943 * contexts from the adapter. This routine aborts any contexts
5944 * outstanding, then waits for their completions. The wait is
5945 * bounded by devloss_tmo though.
5946 *
5947 * Return code :
5948 *  0x2003 - Error
5949 *  0x2002 - Success
5950 **/
5951static int
5952lpfc_reset_flush_io_context(struct lpfc_vport *vport, uint16_t tgt_id,
5953			uint64_t lun_id, lpfc_ctx_cmd context)
5954{
5955	struct lpfc_hba   *phba = vport->phba;
5956	unsigned long later;
5957	int cnt;
5958
5959	cnt = lpfc_sli_sum_iocb(vport, tgt_id, lun_id, context);
5960	if (cnt)
5961		lpfc_sli_abort_taskmgmt(vport,
5962					&phba->sli.sli3_ring[LPFC_FCP_RING],
5963					tgt_id, lun_id, context);
5964	later = secs_to_jiffies(2 * vport->cfg_devloss_tmo) + jiffies;
5965	while (time_after(later, jiffies) && cnt) {
5966		schedule_timeout_uninterruptible(msecs_to_jiffies(20));
5967		cnt = lpfc_sli_sum_iocb(vport, tgt_id, lun_id, context);
5968	}
5969	if (cnt) {
5970		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
5971			"0724 I/O flush failure for context %s : cnt x%x\n",
5972			((context == LPFC_CTX_LUN) ? "LUN" :
5973			 ((context == LPFC_CTX_TGT) ? "TGT" :
5974			  ((context == LPFC_CTX_HOST) ? "HOST" : "Unknown"))),
5975			cnt);
5976		return FAILED;
5977	}
5978	return SUCCESS;
5979}
5980
5981/**
5982 * lpfc_device_reset_handler - scsi_host_template eh_device_reset entry point
5983 * @cmnd: Pointer to scsi_cmnd data structure.
5984 *
5985 * This routine does a device reset by sending a LUN_RESET task management
5986 * command.
5987 *
5988 * Return code :
5989 *  0x2003 - Error
5990 *  0x2002 - Success
5991 **/
5992static int
5993lpfc_device_reset_handler(struct scsi_cmnd *cmnd)
5994{
5995	struct Scsi_Host  *shost = cmnd->device->host;
5996	struct fc_rport *rport = starget_to_rport(scsi_target(cmnd->device));
5997	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
5998	struct lpfc_rport_data *rdata;
5999	struct lpfc_nodelist *pnode;
6000	unsigned tgt_id = cmnd->device->id;
6001	uint64_t lun_id = cmnd->device->lun;
6002	struct lpfc_scsi_event_header scsi_event;
6003	int status;
6004	u32 logit = LOG_FCP;
6005
6006	if (!rport)
6007		return FAILED;
6008
6009	rdata = rport->dd_data;
6010	if (!rdata || !rdata->pnode) {
6011		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
6012				 "0798 Device Reset rdata failure: rdata x%px\n",
6013				 rdata);
6014		return FAILED;
6015	}
6016	pnode = rdata->pnode;
6017	status = fc_block_rport(rport);
6018	if (status != 0 && status != SUCCESS)
6019		return status;
6020
6021	status = lpfc_chk_tgt_mapped(vport, rport);
6022	if (status == FAILED) {
6023		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
6024			"0721 Device Reset rport failure: rdata x%px\n", rdata);
6025		return FAILED;
6026	}
6027
6028	scsi_event.event_type = FC_REG_SCSI_EVENT;
6029	scsi_event.subcategory = LPFC_EVENT_LUNRESET;
6030	scsi_event.lun = lun_id;
6031	memcpy(scsi_event.wwpn, &pnode->nlp_portname, sizeof(struct lpfc_name));
6032	memcpy(scsi_event.wwnn, &pnode->nlp_nodename, sizeof(struct lpfc_name));
6033
6034	fc_host_post_vendor_event(shost, fc_get_event_number(),
6035		sizeof(scsi_event), (char *)&scsi_event, LPFC_NL_VENDOR_ID);
6036
6037	status = lpfc_send_taskmgmt(vport, rport, tgt_id, lun_id,
6038						FCP_LUN_RESET);
6039	if (status != SUCCESS)
6040		logit =  LOG_TRACE_EVENT;
6041
6042	lpfc_printf_vlog(vport, KERN_ERR, logit,
6043			 "0713 SCSI layer issued Device Reset (%d, %llu) "
6044			 "return x%x\n", tgt_id, lun_id, status);
6045
6046	/*
6047	 * We have to clean up i/o as : they may be orphaned by the TMF;
6048	 * or if the TMF failed, they may be in an indeterminate state.
6049	 * So, continue on.
6050	 * We will report success if all the i/o aborts successfully.
6051	 */
6052	if (status == SUCCESS)
6053		status = lpfc_reset_flush_io_context(vport, tgt_id, lun_id,
6054						LPFC_CTX_LUN);
6055
6056	return status;
6057}
6058
6059/**
6060 * lpfc_target_reset_handler - scsi_host_template eh_target_reset entry point
6061 * @cmnd: Pointer to scsi_cmnd data structure.
6062 *
6063 * This routine does a target reset by sending a TARGET_RESET task management
6064 * command.
6065 *
6066 * Return code :
6067 *  0x2003 - Error
6068 *  0x2002 - Success
6069 **/
6070static int
6071lpfc_target_reset_handler(struct scsi_cmnd *cmnd)
6072{
6073	struct Scsi_Host  *shost = cmnd->device->host;
6074	struct fc_rport *rport = starget_to_rport(scsi_target(cmnd->device));
6075	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
6076	struct lpfc_rport_data *rdata;
6077	struct lpfc_nodelist *pnode;
6078	unsigned tgt_id = cmnd->device->id;
6079	uint64_t lun_id = cmnd->device->lun;
6080	struct lpfc_scsi_event_header scsi_event;
6081	int status;
6082	u32 logit = LOG_FCP;
6083	u32 dev_loss_tmo = vport->cfg_devloss_tmo;
6084	unsigned long flags;
6085	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(waitq);
6086
6087	if (!rport)
6088		return FAILED;
6089
6090	rdata = rport->dd_data;
6091	if (!rdata || !rdata->pnode) {
6092		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
6093				 "0799 Target Reset rdata failure: rdata x%px\n",
6094				 rdata);
6095		return FAILED;
6096	}
6097	pnode = rdata->pnode;
6098	status = fc_block_rport(rport);
6099	if (status != 0 && status != SUCCESS)
6100		return status;
6101
6102	status = lpfc_chk_tgt_mapped(vport, rport);
6103	if (status == FAILED) {
6104		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
6105			"0722 Target Reset rport failure: rdata x%px\n", rdata);
6106		if (pnode) {
6107			clear_bit(NLP_NPR_ADISC, &pnode->nlp_flag);
6108			spin_lock_irqsave(&pnode->lock, flags);
6109			pnode->nlp_fcp_info &= ~NLP_FCP_2_DEVICE;
6110			spin_unlock_irqrestore(&pnode->lock, flags);
6111		}
6112		status = lpfc_reset_flush_io_context(vport, tgt_id, lun_id,
6113						     LPFC_CTX_TGT);
6114		if (status != SUCCESS) {
6115			lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
6116					 "0726 Target Reset flush status x%x\n",
6117					 status);
6118			return status;
6119		}
6120		return FAST_IO_FAIL;
6121	}
6122
6123	scsi_event.event_type = FC_REG_SCSI_EVENT;
6124	scsi_event.subcategory = LPFC_EVENT_TGTRESET;
6125	scsi_event.lun = 0;
6126	memcpy(scsi_event.wwpn, &pnode->nlp_portname, sizeof(struct lpfc_name));
6127	memcpy(scsi_event.wwnn, &pnode->nlp_nodename, sizeof(struct lpfc_name));
6128
6129	fc_host_post_vendor_event(shost, fc_get_event_number(),
6130		sizeof(scsi_event), (char *)&scsi_event, LPFC_NL_VENDOR_ID);
6131
6132	status = lpfc_send_taskmgmt(vport, rport, tgt_id, lun_id,
6133					FCP_TARGET_RESET);
6134	if (status != SUCCESS) {
6135		logit = LOG_TRACE_EVENT;
6136
6137		/* Issue LOGO, if no LOGO is outstanding */
6138		spin_lock_irqsave(&pnode->lock, flags);
6139		if (!test_bit(NLP_WAIT_FOR_LOGO, &pnode->save_flags) &&
6140		    !pnode->logo_waitq) {
6141			pnode->logo_waitq = &waitq;
6142			pnode->nlp_fcp_info &= ~NLP_FCP_2_DEVICE;
6143			spin_unlock_irqrestore(&pnode->lock, flags);
6144			set_bit(NLP_ISSUE_LOGO, &pnode->nlp_flag);
6145			set_bit(NLP_WAIT_FOR_LOGO, &pnode->save_flags);
6146			lpfc_unreg_rpi(vport, pnode);
6147			wait_event_timeout(waitq,
6148					   !test_bit(NLP_WAIT_FOR_LOGO,
6149						     &pnode->save_flags),
6150					   secs_to_jiffies(dev_loss_tmo));
6151
6152			if (test_and_clear_bit(NLP_WAIT_FOR_LOGO,
6153					       &pnode->save_flags))
6154				lpfc_printf_vlog(vport, KERN_ERR, logit,
6155						 "0725 SCSI layer TGTRST "
6156						 "failed & LOGO TMO (%d, %llu) "
6157						 "return x%x\n",
6158						 tgt_id, lun_id, status);
6159			spin_lock_irqsave(&pnode->lock, flags);
6160			pnode->logo_waitq = NULL;
6161			spin_unlock_irqrestore(&pnode->lock, flags);
6162			status = SUCCESS;
6163
6164		} else {
6165			spin_unlock_irqrestore(&pnode->lock, flags);
6166			status = FAILED;
6167		}
6168	}
6169
6170	lpfc_printf_vlog(vport, KERN_ERR, logit,
6171			 "0723 SCSI layer issued Target Reset (%d, %llu) "
6172			 "return x%x\n", tgt_id, lun_id, status);
6173
6174	/*
6175	 * We have to clean up i/o as : they may be orphaned by the TMF;
6176	 * or if the TMF failed, they may be in an indeterminate state.
6177	 * So, continue on.
6178	 * We will report success if all the i/o aborts successfully.
6179	 */
6180	if (status == SUCCESS)
6181		status = lpfc_reset_flush_io_context(vport, tgt_id, lun_id,
6182					  LPFC_CTX_TGT);
6183	return status;
6184}
6185
6186/**
6187 * lpfc_host_reset_handler - scsi_host_template eh_host_reset_handler entry pt
6188 * @cmnd: Pointer to scsi_cmnd data structure.
6189 *
6190 * This routine does host reset to the adaptor port. It brings the HBA
6191 * offline, performs a board restart, and then brings the board back online.
6192 * The lpfc_offline calls lpfc_sli_hba_down which will abort and local
6193 * reject all outstanding SCSI commands to the host and error returned
6194 * back to SCSI mid-level. As this will be SCSI mid-level's last resort
6195 * of error handling, it will only return error if resetting of the adapter
6196 * is not successful; in all other cases, will return success.
6197 *
6198 * Return code :
6199 *  0x2003 - Error
6200 *  0x2002 - Success
6201 **/
6202static int
6203lpfc_host_reset_handler(struct scsi_cmnd *cmnd)
6204{
6205	struct Scsi_Host *shost = cmnd->device->host;
6206	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
6207	struct lpfc_hba *phba = vport->phba;
6208	int rc, ret = SUCCESS;
6209
6210	lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
6211			 "3172 SCSI layer issued Host Reset\n");
6212
6213	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
6214	lpfc_offline(phba);
6215	rc = lpfc_sli_brdrestart(phba);
6216	if (rc)
6217		goto error;
6218
6219	/* Wait for successful restart of adapter */
6220	if (phba->sli_rev < LPFC_SLI_REV4) {
6221		rc = lpfc_sli_chipset_init(phba);
6222		if (rc)
6223			goto error;
6224	}
6225
6226	rc = lpfc_online(phba);
6227	if (rc)
6228		goto error;
6229
6230	lpfc_unblock_mgmt_io(phba);
6231
6232	return ret;
6233error:
6234	lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
6235			 "3323 Failed host reset\n");
6236	lpfc_unblock_mgmt_io(phba);
6237	return FAILED;
6238}
6239
6240/**
6241 * lpfc_sdev_init - scsi_host_template sdev_init entry point
6242 * @sdev: Pointer to scsi_device.
6243 *
6244 * This routine populates the cmds_per_lun count + 2 scsi_bufs into  this host's
6245 * globally available list of scsi buffers. This routine also makes sure scsi
6246 * buffer is not allocated more than HBA limit conveyed to midlayer. This list
6247 * of scsi buffer exists for the lifetime of the driver.
6248 *
6249 * Return codes:
6250 *   non-0 - Error
6251 *   0 - Success
6252 **/
6253static int
6254lpfc_sdev_init(struct scsi_device *sdev)
6255{
6256	struct lpfc_vport *vport = (struct lpfc_vport *) sdev->host->hostdata;
6257	struct lpfc_hba   *phba = vport->phba;
6258	struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
6259	uint32_t total = 0;
6260	uint32_t num_to_alloc = 0;
6261	int num_allocated = 0;
6262	uint32_t sdev_cnt;
6263	struct lpfc_device_data *device_data;
6264	unsigned long flags;
6265	struct lpfc_name target_wwpn;
6266
6267	if (!rport || fc_remote_port_chkready(rport))
6268		return -ENXIO;
6269
6270	if (phba->cfg_fof) {
6271
6272		/*
6273		 * Check to see if the device data structure for the lun
6274		 * exists.  If not, create one.
6275		 */
6276
6277		u64_to_wwn(rport->port_name, target_wwpn.u.wwn);
6278		spin_lock_irqsave(&phba->devicelock, flags);
6279		device_data = __lpfc_get_device_data(phba,
6280						     &phba->luns,
6281						     &vport->fc_portname,
6282						     &target_wwpn,
6283						     sdev->lun);
6284		if (!device_data) {
6285			spin_unlock_irqrestore(&phba->devicelock, flags);
6286			device_data = lpfc_create_device_data(phba,
6287							&vport->fc_portname,
6288							&target_wwpn,
6289							sdev->lun,
6290							phba->cfg_XLanePriority,
6291							true);
6292			if (!device_data)
6293				return -ENOMEM;
6294			spin_lock_irqsave(&phba->devicelock, flags);
6295			list_add_tail(&device_data->listentry, &phba->luns);
6296		}
6297		device_data->rport_data = rport->dd_data;
6298		device_data->available = true;
6299		spin_unlock_irqrestore(&phba->devicelock, flags);
6300		sdev->hostdata = device_data;
6301	} else {
6302		sdev->hostdata = rport->dd_data;
6303	}
6304	sdev_cnt = atomic_inc_return(&phba->sdev_cnt);
6305
6306	/* For SLI4, all IO buffers are pre-allocated */
6307	if (phba->sli_rev == LPFC_SLI_REV4)
6308		return 0;
6309
6310	/* This code path is now ONLY for SLI3 adapters */
6311
6312	/*
6313	 * Populate the cmds_per_lun count scsi_bufs into this host's globally
6314	 * available list of scsi buffers.  Don't allocate more than the
6315	 * HBA limit conveyed to the midlayer via the host structure.  The
6316	 * formula accounts for the lun_queue_depth + error handlers + 1
6317	 * extra.  This list of scsi bufs exists for the lifetime of the driver.
6318	 */
6319	total = phba->total_scsi_bufs;
6320	num_to_alloc = vport->cfg_lun_queue_depth + 2;
6321
6322	/* If allocated buffers are enough do nothing */
6323	if ((sdev_cnt * (vport->cfg_lun_queue_depth + 2)) < total)
6324		return 0;
6325
6326	/* Allow some exchanges to be available always to complete discovery */
6327	if (total >= phba->cfg_hba_queue_depth - LPFC_DISC_IOCB_BUFF_COUNT ) {
6328		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
6329				 "0704 At limitation of %d preallocated "
6330				 "command buffers\n", total);
6331		return 0;
6332	/* Allow some exchanges to be available always to complete discovery */
6333	} else if (total + num_to_alloc >
6334		phba->cfg_hba_queue_depth - LPFC_DISC_IOCB_BUFF_COUNT ) {
6335		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
6336				 "0705 Allocation request of %d "
6337				 "command buffers will exceed max of %d.  "
6338				 "Reducing allocation request to %d.\n",
6339				 num_to_alloc, phba->cfg_hba_queue_depth,
6340				 (phba->cfg_hba_queue_depth - total));
6341		num_to_alloc = phba->cfg_hba_queue_depth - total;
6342	}
6343	num_allocated = lpfc_new_scsi_buf_s3(vport, num_to_alloc);
6344	if (num_to_alloc != num_allocated) {
6345			lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
6346					 "0708 Allocation request of %d "
6347					 "command buffers did not succeed.  "
6348					 "Allocated %d buffers.\n",
6349					 num_to_alloc, num_allocated);
6350	}
6351	if (num_allocated > 0)
6352		phba->total_scsi_bufs += num_allocated;
6353	return 0;
6354}
6355
6356/**
6357 * lpfc_sdev_configure - scsi_host_template sdev_configure entry point
6358 * @sdev: Pointer to scsi_device.
6359 * @lim: Request queue limits.
6360 *
6361 * This routine configures following items
6362 *   - Tag command queuing support for @sdev if supported.
6363 *   - Enable SLI polling for fcp ring if ENABLE_FCP_RING_POLLING flag is set.
6364 *
6365 * Return codes:
6366 *   0 - Success
6367 **/
6368static int
6369lpfc_sdev_configure(struct scsi_device *sdev, struct queue_limits *lim)
6370{
6371	struct lpfc_vport *vport = (struct lpfc_vport *) sdev->host->hostdata;
6372	struct lpfc_hba   *phba = vport->phba;
6373
6374	scsi_change_queue_depth(sdev, vport->cfg_lun_queue_depth);
6375
6376	if (phba->cfg_poll & ENABLE_FCP_RING_POLLING) {
6377		lpfc_sli_handle_fast_ring_event(phba,
6378			&phba->sli.sli3_ring[LPFC_FCP_RING], HA_R0RE_REQ);
6379		if (phba->cfg_poll & DISABLE_FCP_RING_INT)
6380			lpfc_poll_rearm_timer(phba);
6381	}
6382
6383	return 0;
6384}
6385
6386/**
6387 * lpfc_sdev_destroy - sdev_destroy entry point of SHT data structure
6388 * @sdev: Pointer to scsi_device.
6389 *
6390 * This routine sets @sdev hostatdata filed to null.
6391 **/
6392static void
6393lpfc_sdev_destroy(struct scsi_device *sdev)
6394{
6395	struct lpfc_vport *vport = (struct lpfc_vport *) sdev->host->hostdata;
6396	struct lpfc_hba   *phba = vport->phba;
6397	unsigned long flags;
6398	struct lpfc_device_data *device_data = sdev->hostdata;
6399
6400	atomic_dec(&phba->sdev_cnt);
6401	if ((phba->cfg_fof) && (device_data)) {
6402		spin_lock_irqsave(&phba->devicelock, flags);
6403		device_data->available = false;
6404		if (!device_data->oas_enabled)
6405			lpfc_delete_device_data(phba, device_data);
6406		spin_unlock_irqrestore(&phba->devicelock, flags);
6407	}
6408	sdev->hostdata = NULL;
6409	return;
6410}
6411
6412/**
6413 * lpfc_create_device_data - creates and initializes device data structure for OAS
6414 * @phba: Pointer to host bus adapter structure.
6415 * @vport_wwpn: Pointer to vport's wwpn information
6416 * @target_wwpn: Pointer to target's wwpn information
6417 * @lun: Lun on target
6418 * @pri: Priority
6419 * @atomic_create: Flag to indicate if memory should be allocated using the
6420 *		  GFP_ATOMIC flag or not.
6421 *
6422 * This routine creates a device data structure which will contain identifying
6423 * information for the device (host wwpn, target wwpn, lun), state of OAS,
6424 * whether or not the corresponding lun is available by the system,
6425 * and pointer to the rport data.
6426 *
6427 * Return codes:
6428 *   NULL - Error
6429 *   Pointer to lpfc_device_data - Success
6430 **/
6431struct lpfc_device_data*
6432lpfc_create_device_data(struct lpfc_hba *phba, struct lpfc_name *vport_wwpn,
6433			struct lpfc_name *target_wwpn, uint64_t lun,
6434			uint32_t pri, bool atomic_create)
6435{
6436
6437	struct lpfc_device_data *lun_info;
6438	gfp_t memory_flags;
6439
6440	if (unlikely(!phba) || !vport_wwpn || !target_wwpn  ||
6441	    !(phba->cfg_fof))
6442		return NULL;
6443
6444	/* Attempt to create the device data to contain lun info */
6445
6446	if (atomic_create)
6447		memory_flags = GFP_ATOMIC;
6448	else
6449		memory_flags = GFP_KERNEL;
6450	lun_info = mempool_alloc(phba->device_data_mem_pool, memory_flags);
6451	if (!lun_info)
6452		return NULL;
6453	INIT_LIST_HEAD(&lun_info->listentry);
6454	lun_info->rport_data  = NULL;
6455	memcpy(&lun_info->device_id.vport_wwpn, vport_wwpn,
6456	       sizeof(struct lpfc_name));
6457	memcpy(&lun_info->device_id.target_wwpn, target_wwpn,
6458	       sizeof(struct lpfc_name));
6459	lun_info->device_id.lun = lun;
6460	lun_info->oas_enabled = false;
6461	lun_info->priority = pri;
6462	lun_info->available = false;
6463	return lun_info;
6464}
6465
6466/**
6467 * lpfc_delete_device_data - frees a device data structure for OAS
6468 * @phba: Pointer to host bus adapter structure.
6469 * @lun_info: Pointer to device data structure to free.
6470 *
6471 * This routine frees the previously allocated device data structure passed.
6472 *
6473 **/
6474void
6475lpfc_delete_device_data(struct lpfc_hba *phba,
6476			struct lpfc_device_data *lun_info)
6477{
6478
6479	if (unlikely(!phba) || !lun_info  ||
6480	    !(phba->cfg_fof))
6481		return;
6482
6483	if (!list_empty(&lun_info->listentry))
6484		list_del(&lun_info->listentry);
6485	mempool_free(lun_info, phba->device_data_mem_pool);
6486	return;
6487}
6488
6489/**
6490 * __lpfc_get_device_data - returns the device data for the specified lun
6491 * @phba: Pointer to host bus adapter structure.
6492 * @list: Point to list to search.
6493 * @vport_wwpn: Pointer to vport's wwpn information
6494 * @target_wwpn: Pointer to target's wwpn information
6495 * @lun: Lun on target
6496 *
6497 * This routine searches the list passed for the specified lun's device data.
6498 * This function does not hold locks, it is the responsibility of the caller
6499 * to ensure the proper lock is held before calling the function.
6500 *
6501 * Return codes:
6502 *   NULL - Error
6503 *   Pointer to lpfc_device_data - Success
6504 **/
6505struct lpfc_device_data*
6506__lpfc_get_device_data(struct lpfc_hba *phba, struct list_head *list,
6507		       struct lpfc_name *vport_wwpn,
6508		       struct lpfc_name *target_wwpn, uint64_t lun)
6509{
6510
6511	struct lpfc_device_data *lun_info;
6512
6513	if (unlikely(!phba) || !list || !vport_wwpn || !target_wwpn ||
6514	    !phba->cfg_fof)
6515		return NULL;
6516
6517	/* Check to see if the lun is already enabled for OAS. */
6518
6519	list_for_each_entry(lun_info, list, listentry) {
6520		if ((memcmp(&lun_info->device_id.vport_wwpn, vport_wwpn,
6521			    sizeof(struct lpfc_name)) == 0) &&
6522		    (memcmp(&lun_info->device_id.target_wwpn, target_wwpn,
6523			    sizeof(struct lpfc_name)) == 0) &&
6524		    (lun_info->device_id.lun == lun))
6525			return lun_info;
6526	}
6527
6528	return NULL;
6529}
6530
6531/**
6532 * lpfc_find_next_oas_lun - searches for the next oas lun
6533 * @phba: Pointer to host bus adapter structure.
6534 * @vport_wwpn: Pointer to vport's wwpn information
6535 * @target_wwpn: Pointer to target's wwpn information
6536 * @starting_lun: Pointer to the lun to start searching for
6537 * @found_vport_wwpn: Pointer to the found lun's vport wwpn information
6538 * @found_target_wwpn: Pointer to the found lun's target wwpn information
6539 * @found_lun: Pointer to the found lun.
6540 * @found_lun_status: Pointer to status of the found lun.
6541 * @found_lun_pri: Pointer to priority of the found lun.
6542 *
6543 * This routine searches the luns list for the specified lun
6544 * or the first lun for the vport/target.  If the vport wwpn contains
6545 * a zero value then a specific vport is not specified. In this case
6546 * any vport which contains the lun will be considered a match.  If the
6547 * target wwpn contains a zero value then a specific target is not specified.
6548 * In this case any target which contains the lun will be considered a
6549 * match.  If the lun is found, the lun, vport wwpn, target wwpn and lun status
6550 * are returned.  The function will also return the next lun if available.
6551 * If the next lun is not found, starting_lun parameter will be set to
6552 * NO_MORE_OAS_LUN.
6553 *
6554 * Return codes:
6555 *   non-0 - Error
6556 *   0 - Success
6557 **/
6558bool
6559lpfc_find_next_oas_lun(struct lpfc_hba *phba, struct lpfc_name *vport_wwpn,
6560		       struct lpfc_name *target_wwpn, uint64_t *starting_lun,
6561		       struct lpfc_name *found_vport_wwpn,
6562		       struct lpfc_name *found_target_wwpn,
6563		       uint64_t *found_lun,
6564		       uint32_t *found_lun_status,
6565		       uint32_t *found_lun_pri)
6566{
6567
6568	unsigned long flags;
6569	struct lpfc_device_data *lun_info;
6570	struct lpfc_device_id *device_id;
6571	uint64_t lun;
6572	bool found = false;
6573
6574	if (unlikely(!phba) || !vport_wwpn || !target_wwpn ||
6575	    !starting_lun || !found_vport_wwpn ||
6576	    !found_target_wwpn || !found_lun || !found_lun_status ||
6577	    (*starting_lun == NO_MORE_OAS_LUN) ||
6578	    !phba->cfg_fof)
6579		return false;
6580
6581	lun = *starting_lun;
6582	*found_lun = NO_MORE_OAS_LUN;
6583	*starting_lun = NO_MORE_OAS_LUN;
6584
6585	/* Search for lun or the lun closet in value */
6586
6587	spin_lock_irqsave(&phba->devicelock, flags);
6588	list_for_each_entry(lun_info, &phba->luns, listentry) {
6589		if (((wwn_to_u64(vport_wwpn->u.wwn) == 0) ||
6590		     (memcmp(&lun_info->device_id.vport_wwpn, vport_wwpn,
6591			    sizeof(struct lpfc_name)) == 0)) &&
6592		    ((wwn_to_u64(target_wwpn->u.wwn) == 0) ||
6593		     (memcmp(&lun_info->device_id.target_wwpn, target_wwpn,
6594			    sizeof(struct lpfc_name)) == 0)) &&
6595		    (lun_info->oas_enabled)) {
6596			device_id = &lun_info->device_id;
6597			if ((!found) &&
6598			    ((lun == FIND_FIRST_OAS_LUN) ||
6599			     (device_id->lun == lun))) {
6600				*found_lun = device_id->lun;
6601				memcpy(found_vport_wwpn,
6602				       &device_id->vport_wwpn,
6603				       sizeof(struct lpfc_name));
6604				memcpy(found_target_wwpn,
6605				       &device_id->target_wwpn,
6606				       sizeof(struct lpfc_name));
6607				if (lun_info->available)
6608					*found_lun_status =
6609						OAS_LUN_STATUS_EXISTS;
6610				else
6611					*found_lun_status = 0;
6612				*found_lun_pri = lun_info->priority;
6613				if (phba->cfg_oas_flags & OAS_FIND_ANY_VPORT)
6614					memset(vport_wwpn, 0x0,
6615					       sizeof(struct lpfc_name));
6616				if (phba->cfg_oas_flags & OAS_FIND_ANY_TARGET)
6617					memset(target_wwpn, 0x0,
6618					       sizeof(struct lpfc_name));
6619				found = true;
6620			} else if (found) {
6621				*starting_lun = device_id->lun;
6622				memcpy(vport_wwpn, &device_id->vport_wwpn,
6623				       sizeof(struct lpfc_name));
6624				memcpy(target_wwpn, &device_id->target_wwpn,
6625				       sizeof(struct lpfc_name));
6626				break;
6627			}
6628		}
6629	}
6630	spin_unlock_irqrestore(&phba->devicelock, flags);
6631	return found;
6632}
6633
6634/**
6635 * lpfc_enable_oas_lun - enables a lun for OAS operations
6636 * @phba: Pointer to host bus adapter structure.
6637 * @vport_wwpn: Pointer to vport's wwpn information
6638 * @target_wwpn: Pointer to target's wwpn information
6639 * @lun: Lun
6640 * @pri: Priority
6641 *
6642 * This routine enables a lun for oas operations.  The routines does so by
6643 * doing the following :
6644 *
6645 *   1) Checks to see if the device data for the lun has been created.
6646 *   2) If found, sets the OAS enabled flag if not set and returns.
6647 *   3) Otherwise, creates a device data structure.
6648 *   4) If successfully created, indicates the device data is for an OAS lun,
6649 *   indicates the lun is not available and add to the list of luns.
6650 *
6651 * Return codes:
6652 *   false - Error
6653 *   true - Success
6654 **/
6655bool
6656lpfc_enable_oas_lun(struct lpfc_hba *phba, struct lpfc_name *vport_wwpn,
6657		    struct lpfc_name *target_wwpn, uint64_t lun, uint8_t pri)
6658{
6659
6660	struct lpfc_device_data *lun_info;
6661	unsigned long flags;
6662
6663	if (unlikely(!phba) || !vport_wwpn || !target_wwpn ||
6664	    !phba->cfg_fof)
6665		return false;
6666
6667	spin_lock_irqsave(&phba->devicelock, flags);
6668
6669	/* Check to see if the device data for the lun has been created */
6670	lun_info = __lpfc_get_device_data(phba, &phba->luns, vport_wwpn,
6671					  target_wwpn, lun);
6672	if (lun_info) {
6673		if (!lun_info->oas_enabled)
6674			lun_info->oas_enabled = true;
6675		lun_info->priority = pri;
6676		spin_unlock_irqrestore(&phba->devicelock, flags);
6677		return true;
6678	}
6679
6680	/* Create an lun info structure and add to list of luns */
6681	lun_info = lpfc_create_device_data(phba, vport_wwpn, target_wwpn, lun,
6682					   pri, true);
6683	if (lun_info) {
6684		lun_info->oas_enabled = true;
6685		lun_info->priority = pri;
6686		lun_info->available = false;
6687		list_add_tail(&lun_info->listentry, &phba->luns);
6688		spin_unlock_irqrestore(&phba->devicelock, flags);
6689		return true;
6690	}
6691	spin_unlock_irqrestore(&phba->devicelock, flags);
6692	return false;
6693}
6694
6695/**
6696 * lpfc_disable_oas_lun - disables a lun for OAS operations
6697 * @phba: Pointer to host bus adapter structure.
6698 * @vport_wwpn: Pointer to vport's wwpn information
6699 * @target_wwpn: Pointer to target's wwpn information
6700 * @lun: Lun
6701 * @pri: Priority
6702 *
6703 * This routine disables a lun for oas operations.  The routines does so by
6704 * doing the following :
6705 *
6706 *   1) Checks to see if the device data for the lun is created.
6707 *   2) If present, clears the flag indicating this lun is for OAS.
6708 *   3) If the lun is not available by the system, the device data is
6709 *   freed.
6710 *
6711 * Return codes:
6712 *   false - Error
6713 *   true - Success
6714 **/
6715bool
6716lpfc_disable_oas_lun(struct lpfc_hba *phba, struct lpfc_name *vport_wwpn,
6717		     struct lpfc_name *target_wwpn, uint64_t lun, uint8_t pri)
6718{
6719
6720	struct lpfc_device_data *lun_info;
6721	unsigned long flags;
6722
6723	if (unlikely(!phba) || !vport_wwpn || !target_wwpn ||
6724	    !phba->cfg_fof)
6725		return false;
6726
6727	spin_lock_irqsave(&phba->devicelock, flags);
6728
6729	/* Check to see if the lun is available. */
6730	lun_info = __lpfc_get_device_data(phba,
6731					  &phba->luns, vport_wwpn,
6732					  target_wwpn, lun);
6733	if (lun_info) {
6734		lun_info->oas_enabled = false;
6735		lun_info->priority = pri;
6736		if (!lun_info->available)
6737			lpfc_delete_device_data(phba, lun_info);
6738		spin_unlock_irqrestore(&phba->devicelock, flags);
6739		return true;
6740	}
6741
6742	spin_unlock_irqrestore(&phba->devicelock, flags);
6743	return false;
6744}
6745
6746static int
6747lpfc_no_command(struct Scsi_Host *shost, struct scsi_cmnd *cmnd)
6748{
6749	return SCSI_MLQUEUE_HOST_BUSY;
6750}
6751
6752static int
6753lpfc_init_no_sdev(struct scsi_device *sdev)
6754{
6755	return -ENODEV;
6756}
6757
6758static int
6759lpfc_config_no_sdev(struct scsi_device *sdev, struct queue_limits *lim)
6760{
6761	return -ENODEV;
6762}
6763
6764struct scsi_host_template lpfc_template_nvme = {
6765	.module			= THIS_MODULE,
6766	.name			= LPFC_DRIVER_NAME,
6767	.proc_name		= LPFC_DRIVER_NAME,
6768	.info			= lpfc_info,
6769	.queuecommand		= lpfc_no_command,
6770	.sdev_init		= lpfc_init_no_sdev,
6771	.sdev_configure		= lpfc_config_no_sdev,
6772	.scan_finished		= lpfc_scan_finished,
6773	.this_id		= -1,
6774	.sg_tablesize		= 1,
6775	.cmd_per_lun		= 1,
6776	.shost_groups		= lpfc_hba_groups,
6777	.max_sectors		= 0xFFFFFFFF,
6778	.vendor_id		= LPFC_NL_VENDOR_ID,
6779	.track_queue_depth	= 0,
6780};
6781
6782struct scsi_host_template lpfc_template = {
6783	.module			= THIS_MODULE,
6784	.name			= LPFC_DRIVER_NAME,
6785	.proc_name		= LPFC_DRIVER_NAME,
6786	.info			= lpfc_info,
6787	.queuecommand		= lpfc_queuecommand,
6788	.eh_timed_out		= fc_eh_timed_out,
6789	.eh_should_retry_cmd    = fc_eh_should_retry_cmd,
6790	.eh_abort_handler	= lpfc_abort_handler,
6791	.eh_device_reset_handler = lpfc_device_reset_handler,
6792	.eh_target_reset_handler = lpfc_target_reset_handler,
6793	.eh_host_reset_handler  = lpfc_host_reset_handler,
6794	.sdev_init		= lpfc_sdev_init,
6795	.sdev_configure		= lpfc_sdev_configure,
6796	.sdev_destroy		= lpfc_sdev_destroy,
6797	.scan_finished		= lpfc_scan_finished,
6798	.this_id		= -1,
6799	.sg_tablesize		= LPFC_DEFAULT_SG_SEG_CNT,
6800	.cmd_per_lun		= LPFC_CMD_PER_LUN,
6801	.shost_groups		= lpfc_hba_groups,
6802	.max_sectors		= 0xFFFFFFFF,
6803	.vendor_id		= LPFC_NL_VENDOR_ID,
6804	.change_queue_depth	= scsi_change_queue_depth,
6805	.track_queue_depth	= 1,
6806};
6807
6808struct scsi_host_template lpfc_vport_template = {
6809	.module			= THIS_MODULE,
6810	.name			= LPFC_DRIVER_NAME,
6811	.proc_name		= LPFC_DRIVER_NAME,
6812	.info			= lpfc_info,
6813	.queuecommand		= lpfc_queuecommand,
6814	.eh_timed_out		= fc_eh_timed_out,
6815	.eh_should_retry_cmd    = fc_eh_should_retry_cmd,
6816	.eh_abort_handler	= lpfc_abort_handler,
6817	.eh_device_reset_handler = lpfc_device_reset_handler,
6818	.eh_target_reset_handler = lpfc_target_reset_handler,
6819	.eh_bus_reset_handler	= NULL,
6820	.eh_host_reset_handler	= NULL,
6821	.sdev_init		= lpfc_sdev_init,
6822	.sdev_configure		= lpfc_sdev_configure,
6823	.sdev_destroy		= lpfc_sdev_destroy,
6824	.scan_finished		= lpfc_scan_finished,
6825	.this_id		= -1,
6826	.sg_tablesize		= LPFC_DEFAULT_SG_SEG_CNT,
6827	.cmd_per_lun		= LPFC_CMD_PER_LUN,
6828	.shost_groups		= lpfc_vport_groups,
6829	.max_sectors		= 0xFFFFFFFF,
6830	.vendor_id		= 0,
6831	.change_queue_depth	= scsi_change_queue_depth,
6832	.track_queue_depth	= 1,
6833};
~/ Read-only file preview.