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