xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_scsi.c (revision 144679df)
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 				 (cmd->device->sector_size) ?
4277 				 (u64)scsi_get_lba(cmd) : 0,
4278 				 cmd->retries, scsi_get_resid(cmd));
4279 	}
4280 
4281 	if (vport->cfg_max_scsicmpl_time &&
4282 	    time_after(jiffies, lpfc_cmd->start_time +
4283 	    msecs_to_jiffies(vport->cfg_max_scsicmpl_time))) {
4284 		spin_lock_irqsave(shost->host_lock, flags);
4285 		if (ndlp) {
4286 			if (ndlp->cmd_qdepth >
4287 				atomic_read(&ndlp->cmd_pending) &&
4288 				(atomic_read(&ndlp->cmd_pending) >
4289 				LPFC_MIN_TGT_QDEPTH) &&
4290 				(cmd->cmnd[0] == READ_10 ||
4291 				cmd->cmnd[0] == WRITE_10))
4292 				ndlp->cmd_qdepth =
4293 					atomic_read(&ndlp->cmd_pending);
4294 
4295 			ndlp->last_change_time = jiffies;
4296 		}
4297 		spin_unlock_irqrestore(shost->host_lock, flags);
4298 	}
4299 	lpfc_scsi_unprep_dma_buf(phba, lpfc_cmd);
4300 
4301 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
4302 	if (lpfc_cmd->ts_cmd_start) {
4303 		lpfc_cmd->ts_isr_cmpl = lpfc_cmd->cur_iocbq.isr_timestamp;
4304 		lpfc_cmd->ts_data_io = ktime_get_ns();
4305 		phba->ktime_last_cmd = lpfc_cmd->ts_data_io;
4306 		lpfc_io_ktime(phba, lpfc_cmd);
4307 	}
4308 #endif
4309 	if (likely(!wait_xb_clr))
4310 		lpfc_cmd->pCmd = NULL;
4311 	spin_unlock(&lpfc_cmd->buf_lock);
4312 
4313 	/* Check if IO qualified for CMF */
4314 	if (phba->cmf_active_mode != LPFC_CFG_OFF &&
4315 	    cmd->sc_data_direction == DMA_FROM_DEVICE &&
4316 	    (scsi_sg_count(cmd))) {
4317 		/* Used when calculating average latency */
4318 		lat = ktime_get_ns() - lpfc_cmd->rx_cmd_start;
4319 		lpfc_update_cmf_cmpl(phba, lat, scsi_bufflen(cmd), shost);
4320 	}
4321 
4322 	if (wait_xb_clr)
4323 		goto out;
4324 
4325 	/* The sdev is not guaranteed to be valid post scsi_done upcall. */
4326 	scsi_done(cmd);
4327 
4328 	/*
4329 	 * If there is an abort thread waiting for command completion
4330 	 * wake up the thread.
4331 	 */
4332 	spin_lock(&lpfc_cmd->buf_lock);
4333 	lpfc_cmd->cur_iocbq.cmd_flag &= ~LPFC_DRIVER_ABORTED;
4334 	if (lpfc_cmd->waitq)
4335 		wake_up(lpfc_cmd->waitq);
4336 	spin_unlock(&lpfc_cmd->buf_lock);
4337 out:
4338 	lpfc_release_scsi_buf(phba, lpfc_cmd);
4339 }
4340 
4341 /**
4342  * lpfc_scsi_cmd_iocb_cmpl - Scsi cmnd IOCB completion routine
4343  * @phba: The Hba for which this call is being executed.
4344  * @pIocbIn: The command IOCBQ for the scsi cmnd.
4345  * @pIocbOut: The response IOCBQ for the scsi cmnd.
4346  *
4347  * This routine assigns scsi command result by looking into response IOCB
4348  * status field appropriately. This routine handles QUEUE FULL condition as
4349  * well by ramping down device queue depth.
4350  **/
4351 static void
4352 lpfc_scsi_cmd_iocb_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *pIocbIn,
4353 			struct lpfc_iocbq *pIocbOut)
4354 {
4355 	struct lpfc_io_buf *lpfc_cmd =
4356 		(struct lpfc_io_buf *) pIocbIn->io_buf;
4357 	struct lpfc_vport      *vport = pIocbIn->vport;
4358 	struct lpfc_rport_data *rdata = lpfc_cmd->rdata;
4359 	struct lpfc_nodelist *pnode = rdata->pnode;
4360 	struct scsi_cmnd *cmd;
4361 	unsigned long flags;
4362 	struct lpfc_fast_path_event *fast_path_evt;
4363 	struct Scsi_Host *shost;
4364 	int idx;
4365 	uint32_t logit = LOG_FCP;
4366 
4367 	/* Guard against abort handler being called at same time */
4368 	spin_lock(&lpfc_cmd->buf_lock);
4369 
4370 	/* Sanity check on return of outstanding command */
4371 	cmd = lpfc_cmd->pCmd;
4372 	if (!cmd || !phba) {
4373 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
4374 				 "2621 IO completion: Not an active IO\n");
4375 		spin_unlock(&lpfc_cmd->buf_lock);
4376 		return;
4377 	}
4378 
4379 	idx = lpfc_cmd->cur_iocbq.hba_wqidx;
4380 	if (phba->sli4_hba.hdwq)
4381 		phba->sli4_hba.hdwq[idx].scsi_cstat.io_cmpls++;
4382 
4383 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
4384 	if (unlikely(phba->hdwqstat_on & LPFC_CHECK_SCSI_IO))
4385 		this_cpu_inc(phba->sli4_hba.c_stat->cmpl_io);
4386 #endif
4387 	shost = cmd->device->host;
4388 
4389 	lpfc_cmd->result = (pIocbOut->iocb.un.ulpWord[4] & IOERR_PARAM_MASK);
4390 	lpfc_cmd->status = pIocbOut->iocb.ulpStatus;
4391 	/* pick up SLI4 exchange busy status from HBA */
4392 	lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
4393 	if (pIocbOut->cmd_flag & LPFC_EXCHANGE_BUSY)
4394 		lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
4395 
4396 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
4397 	if (lpfc_cmd->prot_data_type) {
4398 		struct scsi_dif_tuple *src = NULL;
4399 
4400 		src =  (struct scsi_dif_tuple *)lpfc_cmd->prot_data_segment;
4401 		/*
4402 		 * Used to restore any changes to protection
4403 		 * data for error injection.
4404 		 */
4405 		switch (lpfc_cmd->prot_data_type) {
4406 		case LPFC_INJERR_REFTAG:
4407 			src->ref_tag =
4408 				lpfc_cmd->prot_data;
4409 			break;
4410 		case LPFC_INJERR_APPTAG:
4411 			src->app_tag =
4412 				(uint16_t)lpfc_cmd->prot_data;
4413 			break;
4414 		case LPFC_INJERR_GUARD:
4415 			src->guard_tag =
4416 				(uint16_t)lpfc_cmd->prot_data;
4417 			break;
4418 		default:
4419 			break;
4420 		}
4421 
4422 		lpfc_cmd->prot_data = 0;
4423 		lpfc_cmd->prot_data_type = 0;
4424 		lpfc_cmd->prot_data_segment = NULL;
4425 	}
4426 #endif
4427 
4428 	if (unlikely(lpfc_cmd->status)) {
4429 		if (lpfc_cmd->status == IOSTAT_LOCAL_REJECT &&
4430 		    (lpfc_cmd->result & IOERR_DRVR_MASK))
4431 			lpfc_cmd->status = IOSTAT_DRIVER_REJECT;
4432 		else if (lpfc_cmd->status >= IOSTAT_CNT)
4433 			lpfc_cmd->status = IOSTAT_DEFAULT;
4434 		if (lpfc_cmd->status == IOSTAT_FCP_RSP_ERROR &&
4435 		    !lpfc_cmd->fcp_rsp->rspStatus3 &&
4436 		    (lpfc_cmd->fcp_rsp->rspStatus2 & RESID_UNDER) &&
4437 		    !(vport->cfg_log_verbose & LOG_FCP_UNDER))
4438 			logit = 0;
4439 		else
4440 			logit = LOG_FCP | LOG_FCP_UNDER;
4441 		lpfc_printf_vlog(vport, KERN_WARNING, logit,
4442 			 "9030 FCP cmd x%x failed <%d/%lld> "
4443 			 "status: x%x result: x%x "
4444 			 "sid: x%x did: x%x oxid: x%x "
4445 			 "Data: x%x x%x\n",
4446 			 cmd->cmnd[0],
4447 			 cmd->device ? cmd->device->id : 0xffff,
4448 			 cmd->device ? cmd->device->lun : 0xffff,
4449 			 lpfc_cmd->status, lpfc_cmd->result,
4450 			 vport->fc_myDID,
4451 			 (pnode) ? pnode->nlp_DID : 0,
4452 			 phba->sli_rev == LPFC_SLI_REV4 ?
4453 			     lpfc_cmd->cur_iocbq.sli4_xritag : 0xffff,
4454 			 pIocbOut->iocb.ulpContext,
4455 			 lpfc_cmd->cur_iocbq.iocb.ulpIoTag);
4456 
4457 		switch (lpfc_cmd->status) {
4458 		case IOSTAT_FCP_RSP_ERROR:
4459 			/* Call FCP RSP handler to determine result */
4460 			lpfc_handle_fcp_err(vport, lpfc_cmd,
4461 					    pIocbOut->iocb.un.fcpi.fcpi_parm);
4462 			break;
4463 		case IOSTAT_NPORT_BSY:
4464 		case IOSTAT_FABRIC_BSY:
4465 			cmd->result = DID_TRANSPORT_DISRUPTED << 16;
4466 			fast_path_evt = lpfc_alloc_fast_evt(phba);
4467 			if (!fast_path_evt)
4468 				break;
4469 			fast_path_evt->un.fabric_evt.event_type =
4470 				FC_REG_FABRIC_EVENT;
4471 			fast_path_evt->un.fabric_evt.subcategory =
4472 				(lpfc_cmd->status == IOSTAT_NPORT_BSY) ?
4473 				LPFC_EVENT_PORT_BUSY : LPFC_EVENT_FABRIC_BUSY;
4474 			if (pnode) {
4475 				memcpy(&fast_path_evt->un.fabric_evt.wwpn,
4476 					&pnode->nlp_portname,
4477 					sizeof(struct lpfc_name));
4478 				memcpy(&fast_path_evt->un.fabric_evt.wwnn,
4479 					&pnode->nlp_nodename,
4480 					sizeof(struct lpfc_name));
4481 			}
4482 			fast_path_evt->vport = vport;
4483 			fast_path_evt->work_evt.evt =
4484 				LPFC_EVT_FASTPATH_MGMT_EVT;
4485 			spin_lock_irqsave(&phba->hbalock, flags);
4486 			list_add_tail(&fast_path_evt->work_evt.evt_listp,
4487 				&phba->work_list);
4488 			spin_unlock_irqrestore(&phba->hbalock, flags);
4489 			lpfc_worker_wake_up(phba);
4490 			break;
4491 		case IOSTAT_LOCAL_REJECT:
4492 		case IOSTAT_REMOTE_STOP:
4493 			if (lpfc_cmd->result == IOERR_ELXSEC_KEY_UNWRAP_ERROR ||
4494 			    lpfc_cmd->result ==
4495 					IOERR_ELXSEC_KEY_UNWRAP_COMPARE_ERROR ||
4496 			    lpfc_cmd->result == IOERR_ELXSEC_CRYPTO_ERROR ||
4497 			    lpfc_cmd->result ==
4498 					IOERR_ELXSEC_CRYPTO_COMPARE_ERROR) {
4499 				cmd->result = DID_NO_CONNECT << 16;
4500 				break;
4501 			}
4502 			if (lpfc_cmd->result == IOERR_INVALID_RPI ||
4503 			    lpfc_cmd->result == IOERR_NO_RESOURCES ||
4504 			    lpfc_cmd->result == IOERR_ABORT_REQUESTED ||
4505 			    lpfc_cmd->result == IOERR_SLER_CMD_RCV_FAILURE) {
4506 				cmd->result = DID_TRANSPORT_DISRUPTED << 16;
4507 				break;
4508 			}
4509 			if ((lpfc_cmd->result == IOERR_RX_DMA_FAILED ||
4510 			     lpfc_cmd->result == IOERR_TX_DMA_FAILED) &&
4511 			     pIocbOut->iocb.unsli3.sli3_bg.bgstat) {
4512 				if (scsi_get_prot_op(cmd) != SCSI_PROT_NORMAL) {
4513 					/*
4514 					 * This is a response for a BG enabled
4515 					 * cmd. Parse BG error
4516 					 */
4517 					lpfc_parse_bg_err(phba, lpfc_cmd,
4518 							pIocbOut);
4519 					break;
4520 				} else {
4521 					lpfc_printf_vlog(vport, KERN_WARNING,
4522 							LOG_BG,
4523 							"9031 non-zero BGSTAT "
4524 							"on unprotected cmd\n");
4525 				}
4526 			}
4527 			if ((lpfc_cmd->status == IOSTAT_REMOTE_STOP)
4528 				&& (phba->sli_rev == LPFC_SLI_REV4)
4529 				&& pnode) {
4530 				/* This IO was aborted by the target, we don't
4531 				 * know the rxid and because we did not send the
4532 				 * ABTS we cannot generate and RRQ.
4533 				 */
4534 				lpfc_set_rrq_active(phba, pnode,
4535 					lpfc_cmd->cur_iocbq.sli4_lxritag,
4536 					0, 0);
4537 			}
4538 			fallthrough;
4539 		default:
4540 			cmd->result = DID_ERROR << 16;
4541 			break;
4542 		}
4543 
4544 		if (!pnode || (pnode->nlp_state != NLP_STE_MAPPED_NODE))
4545 			cmd->result = DID_TRANSPORT_DISRUPTED << 16 |
4546 				      SAM_STAT_BUSY;
4547 	} else
4548 		cmd->result = DID_OK << 16;
4549 
4550 	if (cmd->result || lpfc_cmd->fcp_rsp->rspSnsLen) {
4551 		uint32_t *lp = (uint32_t *)cmd->sense_buffer;
4552 
4553 		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
4554 				 "0710 Iodone <%d/%llu> cmd x%px, error "
4555 				 "x%x SNS x%x x%x Data: x%x x%x\n",
4556 				 cmd->device->id, cmd->device->lun, cmd,
4557 				 cmd->result, *lp, *(lp + 3), cmd->retries,
4558 				 scsi_get_resid(cmd));
4559 	}
4560 
4561 	if (vport->cfg_max_scsicmpl_time &&
4562 	   time_after(jiffies, lpfc_cmd->start_time +
4563 		msecs_to_jiffies(vport->cfg_max_scsicmpl_time))) {
4564 		spin_lock_irqsave(shost->host_lock, flags);
4565 		if (pnode) {
4566 			if (pnode->cmd_qdepth >
4567 				atomic_read(&pnode->cmd_pending) &&
4568 				(atomic_read(&pnode->cmd_pending) >
4569 				LPFC_MIN_TGT_QDEPTH) &&
4570 				((cmd->cmnd[0] == READ_10) ||
4571 				(cmd->cmnd[0] == WRITE_10)))
4572 				pnode->cmd_qdepth =
4573 					atomic_read(&pnode->cmd_pending);
4574 
4575 			pnode->last_change_time = jiffies;
4576 		}
4577 		spin_unlock_irqrestore(shost->host_lock, flags);
4578 	}
4579 	lpfc_scsi_unprep_dma_buf(phba, lpfc_cmd);
4580 
4581 	lpfc_cmd->pCmd = NULL;
4582 	spin_unlock(&lpfc_cmd->buf_lock);
4583 
4584 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
4585 	if (lpfc_cmd->ts_cmd_start) {
4586 		lpfc_cmd->ts_isr_cmpl = pIocbIn->isr_timestamp;
4587 		lpfc_cmd->ts_data_io = ktime_get_ns();
4588 		phba->ktime_last_cmd = lpfc_cmd->ts_data_io;
4589 		lpfc_io_ktime(phba, lpfc_cmd);
4590 	}
4591 #endif
4592 
4593 	/* The sdev is not guaranteed to be valid post scsi_done upcall. */
4594 	scsi_done(cmd);
4595 
4596 	/*
4597 	 * If there is an abort thread waiting for command completion
4598 	 * wake up the thread.
4599 	 */
4600 	spin_lock(&lpfc_cmd->buf_lock);
4601 	lpfc_cmd->cur_iocbq.cmd_flag &= ~LPFC_DRIVER_ABORTED;
4602 	if (lpfc_cmd->waitq)
4603 		wake_up(lpfc_cmd->waitq);
4604 	spin_unlock(&lpfc_cmd->buf_lock);
4605 
4606 	lpfc_release_scsi_buf(phba, lpfc_cmd);
4607 }
4608 
4609 /**
4610  * lpfc_scsi_prep_cmnd_buf_s3 - SLI-3 IOCB init for the IO
4611  * @vport: Pointer to vport object.
4612  * @lpfc_cmd: The scsi buffer which is going to be prep'ed.
4613  * @tmo: timeout value for the IO
4614  *
4615  * Based on the data-direction of the command, initialize IOCB
4616  * in the I/O buffer. Fill in the IOCB fields which are independent
4617  * of the scsi buffer
4618  *
4619  * RETURNS 0 - SUCCESS,
4620  **/
4621 static int lpfc_scsi_prep_cmnd_buf_s3(struct lpfc_vport *vport,
4622 				      struct lpfc_io_buf *lpfc_cmd,
4623 				      uint8_t tmo)
4624 {
4625 	IOCB_t *iocb_cmd = &lpfc_cmd->cur_iocbq.iocb;
4626 	struct lpfc_iocbq *piocbq = &lpfc_cmd->cur_iocbq;
4627 	struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
4628 	struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
4629 	struct lpfc_nodelist *pnode = lpfc_cmd->ndlp;
4630 	int datadir = scsi_cmnd->sc_data_direction;
4631 	u32 fcpdl;
4632 
4633 	piocbq->iocb.un.fcpi.fcpi_XRdy = 0;
4634 
4635 	/*
4636 	 * There are three possibilities here - use scatter-gather segment, use
4637 	 * the single mapping, or neither.  Start the lpfc command prep by
4638 	 * bumping the bpl beyond the fcp_cmnd and fcp_rsp regions to the first
4639 	 * data bde entry.
4640 	 */
4641 	if (scsi_sg_count(scsi_cmnd)) {
4642 		if (datadir == DMA_TO_DEVICE) {
4643 			iocb_cmd->ulpCommand = CMD_FCP_IWRITE64_CR;
4644 			iocb_cmd->ulpPU = PARM_READ_CHECK;
4645 			if (vport->cfg_first_burst_size &&
4646 			    (pnode->nlp_flag & NLP_FIRSTBURST)) {
4647 				u32 xrdy_len;
4648 
4649 				fcpdl = scsi_bufflen(scsi_cmnd);
4650 				xrdy_len = min(fcpdl,
4651 					       vport->cfg_first_burst_size);
4652 				piocbq->iocb.un.fcpi.fcpi_XRdy = xrdy_len;
4653 			}
4654 			fcp_cmnd->fcpCntl3 = WRITE_DATA;
4655 		} else {
4656 			iocb_cmd->ulpCommand = CMD_FCP_IREAD64_CR;
4657 			iocb_cmd->ulpPU = PARM_READ_CHECK;
4658 			fcp_cmnd->fcpCntl3 = READ_DATA;
4659 		}
4660 	} else {
4661 		iocb_cmd->ulpCommand = CMD_FCP_ICMND64_CR;
4662 		iocb_cmd->un.fcpi.fcpi_parm = 0;
4663 		iocb_cmd->ulpPU = 0;
4664 		fcp_cmnd->fcpCntl3 = 0;
4665 	}
4666 
4667 	/*
4668 	 * Finish initializing those IOCB fields that are independent
4669 	 * of the scsi_cmnd request_buffer
4670 	 */
4671 	piocbq->iocb.ulpContext = pnode->nlp_rpi;
4672 	if (pnode->nlp_fcp_info & NLP_FCP_2_DEVICE)
4673 		piocbq->iocb.ulpFCP2Rcvy = 1;
4674 	else
4675 		piocbq->iocb.ulpFCP2Rcvy = 0;
4676 
4677 	piocbq->iocb.ulpClass = (pnode->nlp_fcp_info & 0x0f);
4678 	piocbq->io_buf  = lpfc_cmd;
4679 	if (!piocbq->cmd_cmpl)
4680 		piocbq->cmd_cmpl = lpfc_scsi_cmd_iocb_cmpl;
4681 	piocbq->iocb.ulpTimeout = tmo;
4682 	piocbq->vport = vport;
4683 	return 0;
4684 }
4685 
4686 /**
4687  * lpfc_scsi_prep_cmnd_buf_s4 - SLI-4 WQE init for the IO
4688  * @vport: Pointer to vport object.
4689  * @lpfc_cmd: The scsi buffer which is going to be prep'ed.
4690  * @tmo: timeout value for the IO
4691  *
4692  * Based on the data-direction of the command copy WQE template
4693  * to I/O buffer WQE. Fill in the WQE fields which are independent
4694  * of the scsi buffer
4695  *
4696  * RETURNS 0 - SUCCESS,
4697  **/
4698 static int lpfc_scsi_prep_cmnd_buf_s4(struct lpfc_vport *vport,
4699 				      struct lpfc_io_buf *lpfc_cmd,
4700 				      uint8_t tmo)
4701 {
4702 	struct lpfc_hba *phba = vport->phba;
4703 	struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
4704 	struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
4705 	struct lpfc_sli4_hdw_queue *hdwq = NULL;
4706 	struct lpfc_iocbq *pwqeq = &lpfc_cmd->cur_iocbq;
4707 	struct lpfc_nodelist *pnode = lpfc_cmd->ndlp;
4708 	union lpfc_wqe128 *wqe = &pwqeq->wqe;
4709 	u16 idx = lpfc_cmd->hdwq_no;
4710 	int datadir = scsi_cmnd->sc_data_direction;
4711 
4712 	hdwq = &phba->sli4_hba.hdwq[idx];
4713 
4714 	/* Initialize 64 bytes only */
4715 	memset(wqe, 0, sizeof(union lpfc_wqe128));
4716 
4717 	/*
4718 	 * There are three possibilities here - use scatter-gather segment, use
4719 	 * the single mapping, or neither.
4720 	 */
4721 	if (scsi_sg_count(scsi_cmnd)) {
4722 		if (datadir == DMA_TO_DEVICE) {
4723 			/* From the iwrite template, initialize words 7 -  11 */
4724 			memcpy(&wqe->words[7],
4725 			       &lpfc_iwrite_cmd_template.words[7],
4726 			       sizeof(uint32_t) * 5);
4727 
4728 			fcp_cmnd->fcpCntl3 = WRITE_DATA;
4729 			if (hdwq)
4730 				hdwq->scsi_cstat.output_requests++;
4731 		} else {
4732 			/* From the iread template, initialize words 7 - 11 */
4733 			memcpy(&wqe->words[7],
4734 			       &lpfc_iread_cmd_template.words[7],
4735 			       sizeof(uint32_t) * 5);
4736 
4737 			/* Word 7 */
4738 			bf_set(wqe_tmo, &wqe->fcp_iread.wqe_com, tmo);
4739 
4740 			fcp_cmnd->fcpCntl3 = READ_DATA;
4741 			if (hdwq)
4742 				hdwq->scsi_cstat.input_requests++;
4743 
4744 			/* For a CMF Managed port, iod must be zero'ed */
4745 			if (phba->cmf_active_mode == LPFC_CFG_MANAGED)
4746 				bf_set(wqe_iod, &wqe->fcp_iread.wqe_com,
4747 				       LPFC_WQE_IOD_NONE);
4748 		}
4749 	} else {
4750 		/* From the icmnd template, initialize words 4 - 11 */
4751 		memcpy(&wqe->words[4], &lpfc_icmnd_cmd_template.words[4],
4752 		       sizeof(uint32_t) * 8);
4753 
4754 		/* Word 7 */
4755 		bf_set(wqe_tmo, &wqe->fcp_icmd.wqe_com, tmo);
4756 
4757 		fcp_cmnd->fcpCntl3 = 0;
4758 		if (hdwq)
4759 			hdwq->scsi_cstat.control_requests++;
4760 	}
4761 
4762 	/*
4763 	 * Finish initializing those WQE fields that are independent
4764 	 * of the request_buffer
4765 	 */
4766 
4767 	 /* Word 3 */
4768 	bf_set(payload_offset_len, &wqe->fcp_icmd,
4769 	       sizeof(struct fcp_cmnd) + sizeof(struct fcp_rsp));
4770 
4771 	/* Word 6 */
4772 	bf_set(wqe_ctxt_tag, &wqe->generic.wqe_com,
4773 	       phba->sli4_hba.rpi_ids[pnode->nlp_rpi]);
4774 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, pwqeq->sli4_xritag);
4775 
4776 	/* Word 7*/
4777 	if (pnode->nlp_fcp_info & NLP_FCP_2_DEVICE)
4778 		bf_set(wqe_erp, &wqe->generic.wqe_com, 1);
4779 
4780 	bf_set(wqe_class, &wqe->generic.wqe_com,
4781 	       (pnode->nlp_fcp_info & 0x0f));
4782 
4783 	 /* Word 8 */
4784 	wqe->generic.wqe_com.abort_tag = pwqeq->iotag;
4785 
4786 	/* Word 9 */
4787 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, pwqeq->iotag);
4788 
4789 	pwqeq->vport = vport;
4790 	pwqeq->io_buf = lpfc_cmd;
4791 	pwqeq->hba_wqidx = lpfc_cmd->hdwq_no;
4792 	pwqeq->cmd_cmpl = lpfc_fcp_io_cmd_wqe_cmpl;
4793 
4794 	return 0;
4795 }
4796 
4797 /**
4798  * lpfc_scsi_prep_cmnd - Wrapper func for convert scsi cmnd to FCP info unit
4799  * @vport: The virtual port for which this call is being executed.
4800  * @lpfc_cmd: The scsi command which needs to send.
4801  * @pnode: Pointer to lpfc_nodelist.
4802  *
4803  * This routine initializes fcp_cmnd and iocb data structure from scsi command
4804  * to transfer for device with SLI3 interface spec.
4805  **/
4806 static int
4807 lpfc_scsi_prep_cmnd(struct lpfc_vport *vport, struct lpfc_io_buf *lpfc_cmd,
4808 		    struct lpfc_nodelist *pnode)
4809 {
4810 	struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
4811 	struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
4812 	u8 *ptr;
4813 
4814 	if (!pnode)
4815 		return 0;
4816 
4817 	lpfc_cmd->fcp_rsp->rspSnsLen = 0;
4818 	/* clear task management bits */
4819 	lpfc_cmd->fcp_cmnd->fcpCntl2 = 0;
4820 
4821 	int_to_scsilun(lpfc_cmd->pCmd->device->lun,
4822 		       &lpfc_cmd->fcp_cmnd->fcp_lun);
4823 
4824 	ptr = &fcp_cmnd->fcpCdb[0];
4825 	memcpy(ptr, scsi_cmnd->cmnd, scsi_cmnd->cmd_len);
4826 	if (scsi_cmnd->cmd_len < LPFC_FCP_CDB_LEN) {
4827 		ptr += scsi_cmnd->cmd_len;
4828 		memset(ptr, 0, (LPFC_FCP_CDB_LEN - scsi_cmnd->cmd_len));
4829 	}
4830 
4831 	fcp_cmnd->fcpCntl1 = SIMPLE_Q;
4832 
4833 	lpfc_scsi_prep_cmnd_buf(vport, lpfc_cmd, lpfc_cmd->timeout);
4834 
4835 	return 0;
4836 }
4837 
4838 /**
4839  * lpfc_scsi_prep_task_mgmt_cmd_s3 - Convert SLI3 scsi TM cmd to FCP info unit
4840  * @vport: The virtual port for which this call is being executed.
4841  * @lpfc_cmd: Pointer to lpfc_io_buf data structure.
4842  * @lun: Logical unit number.
4843  * @task_mgmt_cmd: SCSI task management command.
4844  *
4845  * This routine creates FCP information unit corresponding to @task_mgmt_cmd
4846  * for device with SLI-3 interface spec.
4847  *
4848  * Return codes:
4849  *   0 - Error
4850  *   1 - Success
4851  **/
4852 static int
4853 lpfc_scsi_prep_task_mgmt_cmd_s3(struct lpfc_vport *vport,
4854 				struct lpfc_io_buf *lpfc_cmd,
4855 				u64 lun, u8 task_mgmt_cmd)
4856 {
4857 	struct lpfc_iocbq *piocbq;
4858 	IOCB_t *piocb;
4859 	struct fcp_cmnd *fcp_cmnd;
4860 	struct lpfc_rport_data *rdata = lpfc_cmd->rdata;
4861 	struct lpfc_nodelist *ndlp = rdata->pnode;
4862 
4863 	if (!ndlp || ndlp->nlp_state != NLP_STE_MAPPED_NODE)
4864 		return 0;
4865 
4866 	piocbq = &(lpfc_cmd->cur_iocbq);
4867 	piocbq->vport = vport;
4868 
4869 	piocb = &piocbq->iocb;
4870 
4871 	fcp_cmnd = lpfc_cmd->fcp_cmnd;
4872 	/* Clear out any old data in the FCP command area */
4873 	memset(fcp_cmnd, 0, sizeof(struct fcp_cmnd));
4874 	int_to_scsilun(lun, &fcp_cmnd->fcp_lun);
4875 	fcp_cmnd->fcpCntl2 = task_mgmt_cmd;
4876 	if (!(vport->phba->sli3_options & LPFC_SLI3_BG_ENABLED))
4877 		lpfc_fcpcmd_to_iocb(piocb->unsli3.fcp_ext.icd, fcp_cmnd);
4878 	piocb->ulpCommand = CMD_FCP_ICMND64_CR;
4879 	piocb->ulpContext = ndlp->nlp_rpi;
4880 	piocb->ulpFCP2Rcvy = (ndlp->nlp_fcp_info & NLP_FCP_2_DEVICE) ? 1 : 0;
4881 	piocb->ulpClass = (ndlp->nlp_fcp_info & 0x0f);
4882 	piocb->ulpPU = 0;
4883 	piocb->un.fcpi.fcpi_parm = 0;
4884 
4885 	/* ulpTimeout is only one byte */
4886 	if (lpfc_cmd->timeout > 0xff) {
4887 		/*
4888 		 * Do not timeout the command at the firmware level.
4889 		 * The driver will provide the timeout mechanism.
4890 		 */
4891 		piocb->ulpTimeout = 0;
4892 	} else
4893 		piocb->ulpTimeout = lpfc_cmd->timeout;
4894 
4895 	return 1;
4896 }
4897 
4898 /**
4899  * lpfc_scsi_prep_task_mgmt_cmd_s4 - Convert SLI4 scsi TM cmd to FCP info unit
4900  * @vport: The virtual port for which this call is being executed.
4901  * @lpfc_cmd: Pointer to lpfc_io_buf data structure.
4902  * @lun: Logical unit number.
4903  * @task_mgmt_cmd: SCSI task management command.
4904  *
4905  * This routine creates FCP information unit corresponding to @task_mgmt_cmd
4906  * for device with SLI-4 interface spec.
4907  *
4908  * Return codes:
4909  *   0 - Error
4910  *   1 - Success
4911  **/
4912 static int
4913 lpfc_scsi_prep_task_mgmt_cmd_s4(struct lpfc_vport *vport,
4914 				struct lpfc_io_buf *lpfc_cmd,
4915 				u64 lun, u8 task_mgmt_cmd)
4916 {
4917 	struct lpfc_iocbq *pwqeq = &lpfc_cmd->cur_iocbq;
4918 	union lpfc_wqe128 *wqe = &pwqeq->wqe;
4919 	struct fcp_cmnd *fcp_cmnd;
4920 	struct lpfc_rport_data *rdata = lpfc_cmd->rdata;
4921 	struct lpfc_nodelist *ndlp = rdata->pnode;
4922 
4923 	if (!ndlp || ndlp->nlp_state != NLP_STE_MAPPED_NODE)
4924 		return 0;
4925 
4926 	pwqeq->vport = vport;
4927 	/* Initialize 64 bytes only */
4928 	memset(wqe, 0, sizeof(union lpfc_wqe128));
4929 
4930 	/* From the icmnd template, initialize words 4 - 11 */
4931 	memcpy(&wqe->words[4], &lpfc_icmnd_cmd_template.words[4],
4932 	       sizeof(uint32_t) * 8);
4933 
4934 	fcp_cmnd = lpfc_cmd->fcp_cmnd;
4935 	/* Clear out any old data in the FCP command area */
4936 	memset(fcp_cmnd, 0, sizeof(struct fcp_cmnd));
4937 	int_to_scsilun(lun, &fcp_cmnd->fcp_lun);
4938 	fcp_cmnd->fcpCntl3 = 0;
4939 	fcp_cmnd->fcpCntl2 = task_mgmt_cmd;
4940 
4941 	bf_set(payload_offset_len, &wqe->fcp_icmd,
4942 	       sizeof(struct fcp_cmnd) + sizeof(struct fcp_rsp));
4943 	bf_set(cmd_buff_len, &wqe->fcp_icmd, 0);
4944 	bf_set(wqe_ctxt_tag, &wqe->generic.wqe_com,  /* ulpContext */
4945 	       vport->phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
4946 	bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
4947 	       ((ndlp->nlp_fcp_info & NLP_FCP_2_DEVICE) ? 1 : 0));
4948 	bf_set(wqe_class, &wqe->fcp_icmd.wqe_com,
4949 	       (ndlp->nlp_fcp_info & 0x0f));
4950 
4951 	/* ulpTimeout is only one byte */
4952 	if (lpfc_cmd->timeout > 0xff) {
4953 		/*
4954 		 * Do not timeout the command at the firmware level.
4955 		 * The driver will provide the timeout mechanism.
4956 		 */
4957 		bf_set(wqe_tmo, &wqe->fcp_icmd.wqe_com, 0);
4958 	} else {
4959 		bf_set(wqe_tmo, &wqe->fcp_icmd.wqe_com, lpfc_cmd->timeout);
4960 	}
4961 
4962 	lpfc_prep_embed_io(vport->phba, lpfc_cmd);
4963 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, pwqeq->sli4_xritag);
4964 	wqe->generic.wqe_com.abort_tag = pwqeq->iotag;
4965 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, pwqeq->iotag);
4966 
4967 	lpfc_sli4_set_rsp_sgl_last(vport->phba, lpfc_cmd);
4968 
4969 	return 1;
4970 }
4971 
4972 /**
4973  * lpfc_scsi_api_table_setup - Set up scsi api function jump table
4974  * @phba: The hba struct for which this call is being executed.
4975  * @dev_grp: The HBA PCI-Device group number.
4976  *
4977  * This routine sets up the SCSI interface API function jump table in @phba
4978  * struct.
4979  * Returns: 0 - success, -ENODEV - failure.
4980  **/
4981 int
4982 lpfc_scsi_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
4983 {
4984 
4985 	phba->lpfc_scsi_unprep_dma_buf = lpfc_scsi_unprep_dma_buf;
4986 
4987 	switch (dev_grp) {
4988 	case LPFC_PCI_DEV_LP:
4989 		phba->lpfc_scsi_prep_dma_buf = lpfc_scsi_prep_dma_buf_s3;
4990 		phba->lpfc_bg_scsi_prep_dma_buf = lpfc_bg_scsi_prep_dma_buf_s3;
4991 		phba->lpfc_release_scsi_buf = lpfc_release_scsi_buf_s3;
4992 		phba->lpfc_get_scsi_buf = lpfc_get_scsi_buf_s3;
4993 		phba->lpfc_scsi_prep_cmnd_buf = lpfc_scsi_prep_cmnd_buf_s3;
4994 		phba->lpfc_scsi_prep_task_mgmt_cmd =
4995 					lpfc_scsi_prep_task_mgmt_cmd_s3;
4996 		break;
4997 	case LPFC_PCI_DEV_OC:
4998 		phba->lpfc_scsi_prep_dma_buf = lpfc_scsi_prep_dma_buf_s4;
4999 		phba->lpfc_bg_scsi_prep_dma_buf = lpfc_bg_scsi_prep_dma_buf_s4;
5000 		phba->lpfc_release_scsi_buf = lpfc_release_scsi_buf_s4;
5001 		phba->lpfc_get_scsi_buf = lpfc_get_scsi_buf_s4;
5002 		phba->lpfc_scsi_prep_cmnd_buf = lpfc_scsi_prep_cmnd_buf_s4;
5003 		phba->lpfc_scsi_prep_task_mgmt_cmd =
5004 					lpfc_scsi_prep_task_mgmt_cmd_s4;
5005 		break;
5006 	default:
5007 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5008 				"1418 Invalid HBA PCI-device group: 0x%x\n",
5009 				dev_grp);
5010 		return -ENODEV;
5011 	}
5012 	phba->lpfc_rampdown_queue_depth = lpfc_rampdown_queue_depth;
5013 	phba->lpfc_scsi_cmd_iocb_cmpl = lpfc_scsi_cmd_iocb_cmpl;
5014 	return 0;
5015 }
5016 
5017 /**
5018  * lpfc_tskmgmt_def_cmpl - IOCB completion routine for task management command
5019  * @phba: The Hba for which this call is being executed.
5020  * @cmdiocbq: Pointer to lpfc_iocbq data structure.
5021  * @rspiocbq: Pointer to lpfc_iocbq data structure.
5022  *
5023  * This routine is IOCB completion routine for device reset and target reset
5024  * routine. This routine release scsi buffer associated with lpfc_cmd.
5025  **/
5026 static void
5027 lpfc_tskmgmt_def_cmpl(struct lpfc_hba *phba,
5028 			struct lpfc_iocbq *cmdiocbq,
5029 			struct lpfc_iocbq *rspiocbq)
5030 {
5031 	struct lpfc_io_buf *lpfc_cmd = cmdiocbq->io_buf;
5032 	if (lpfc_cmd)
5033 		lpfc_release_scsi_buf(phba, lpfc_cmd);
5034 	return;
5035 }
5036 
5037 /**
5038  * lpfc_check_pci_resettable - Walks list of devices on pci_dev's bus to check
5039  *                             if issuing a pci_bus_reset is possibly unsafe
5040  * @phba: lpfc_hba pointer.
5041  *
5042  * Description:
5043  * Walks the bus_list to ensure only PCI devices with Emulex
5044  * vendor id, device ids that support hot reset, and only one occurrence
5045  * of function 0.
5046  *
5047  * Returns:
5048  * -EBADSLT,  detected invalid device
5049  *      0,    successful
5050  */
5051 int
5052 lpfc_check_pci_resettable(struct lpfc_hba *phba)
5053 {
5054 	const struct pci_dev *pdev = phba->pcidev;
5055 	struct pci_dev *ptr = NULL;
5056 	u8 counter = 0;
5057 
5058 	/* Walk the list of devices on the pci_dev's bus */
5059 	list_for_each_entry(ptr, &pdev->bus->devices, bus_list) {
5060 		/* Check for Emulex Vendor ID */
5061 		if (ptr->vendor != PCI_VENDOR_ID_EMULEX) {
5062 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5063 					"8346 Non-Emulex vendor found: "
5064 					"0x%04x\n", ptr->vendor);
5065 			return -EBADSLT;
5066 		}
5067 
5068 		/* Check for valid Emulex Device ID */
5069 		if (phba->sli_rev != LPFC_SLI_REV4 ||
5070 		    phba->hba_flag & HBA_FCOE_MODE) {
5071 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5072 					"8347 Incapable PCI reset device: "
5073 					"0x%04x\n", ptr->device);
5074 			return -EBADSLT;
5075 		}
5076 
5077 		/* Check for only one function 0 ID to ensure only one HBA on
5078 		 * secondary bus
5079 		 */
5080 		if (ptr->devfn == 0) {
5081 			if (++counter > 1) {
5082 				lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5083 						"8348 More than one device on "
5084 						"secondary bus found\n");
5085 				return -EBADSLT;
5086 			}
5087 		}
5088 	}
5089 
5090 	return 0;
5091 }
5092 
5093 /**
5094  * lpfc_info - Info entry point of scsi_host_template data structure
5095  * @host: The scsi host for which this call is being executed.
5096  *
5097  * This routine provides module information about hba.
5098  *
5099  * Reutrn code:
5100  *   Pointer to char - Success.
5101  **/
5102 const char *
5103 lpfc_info(struct Scsi_Host *host)
5104 {
5105 	struct lpfc_vport *vport = (struct lpfc_vport *) host->hostdata;
5106 	struct lpfc_hba   *phba = vport->phba;
5107 	int link_speed = 0;
5108 	static char lpfcinfobuf[384];
5109 	char tmp[384] = {0};
5110 
5111 	memset(lpfcinfobuf, 0, sizeof(lpfcinfobuf));
5112 	if (phba && phba->pcidev){
5113 		/* Model Description */
5114 		scnprintf(tmp, sizeof(tmp), phba->ModelDesc);
5115 		if (strlcat(lpfcinfobuf, tmp, sizeof(lpfcinfobuf)) >=
5116 		    sizeof(lpfcinfobuf))
5117 			goto buffer_done;
5118 
5119 		/* PCI Info */
5120 		scnprintf(tmp, sizeof(tmp),
5121 			  " on PCI bus %02x device %02x irq %d",
5122 			  phba->pcidev->bus->number, phba->pcidev->devfn,
5123 			  phba->pcidev->irq);
5124 		if (strlcat(lpfcinfobuf, tmp, sizeof(lpfcinfobuf)) >=
5125 		    sizeof(lpfcinfobuf))
5126 			goto buffer_done;
5127 
5128 		/* Port Number */
5129 		if (phba->Port[0]) {
5130 			scnprintf(tmp, sizeof(tmp), " port %s", phba->Port);
5131 			if (strlcat(lpfcinfobuf, tmp, sizeof(lpfcinfobuf)) >=
5132 			    sizeof(lpfcinfobuf))
5133 				goto buffer_done;
5134 		}
5135 
5136 		/* Link Speed */
5137 		link_speed = lpfc_sli_port_speed_get(phba);
5138 		if (link_speed != 0) {
5139 			scnprintf(tmp, sizeof(tmp),
5140 				  " Logical Link Speed: %d Mbps", link_speed);
5141 			if (strlcat(lpfcinfobuf, tmp, sizeof(lpfcinfobuf)) >=
5142 			    sizeof(lpfcinfobuf))
5143 				goto buffer_done;
5144 		}
5145 
5146 		/* PCI resettable */
5147 		if (!lpfc_check_pci_resettable(phba)) {
5148 			scnprintf(tmp, sizeof(tmp), " PCI resettable");
5149 			strlcat(lpfcinfobuf, tmp, sizeof(lpfcinfobuf));
5150 		}
5151 	}
5152 
5153 buffer_done:
5154 	return lpfcinfobuf;
5155 }
5156 
5157 /**
5158  * lpfc_poll_rearm_timer - Routine to modify fcp_poll timer of hba
5159  * @phba: The Hba for which this call is being executed.
5160  *
5161  * This routine modifies fcp_poll_timer  field of @phba by cfg_poll_tmo.
5162  * The default value of cfg_poll_tmo is 10 milliseconds.
5163  **/
5164 static __inline__ void lpfc_poll_rearm_timer(struct lpfc_hba * phba)
5165 {
5166 	unsigned long  poll_tmo_expires =
5167 		(jiffies + msecs_to_jiffies(phba->cfg_poll_tmo));
5168 
5169 	if (!list_empty(&phba->sli.sli3_ring[LPFC_FCP_RING].txcmplq))
5170 		mod_timer(&phba->fcp_poll_timer,
5171 			  poll_tmo_expires);
5172 }
5173 
5174 /**
5175  * lpfc_poll_start_timer - Routine to start fcp_poll_timer of HBA
5176  * @phba: The Hba for which this call is being executed.
5177  *
5178  * This routine starts the fcp_poll_timer of @phba.
5179  **/
5180 void lpfc_poll_start_timer(struct lpfc_hba * phba)
5181 {
5182 	lpfc_poll_rearm_timer(phba);
5183 }
5184 
5185 /**
5186  * lpfc_poll_timeout - Restart polling timer
5187  * @t: Timer construct where lpfc_hba data structure pointer is obtained.
5188  *
5189  * This routine restarts fcp_poll timer, when FCP ring  polling is enable
5190  * and FCP Ring interrupt is disable.
5191  **/
5192 void lpfc_poll_timeout(struct timer_list *t)
5193 {
5194 	struct lpfc_hba *phba = from_timer(phba, t, fcp_poll_timer);
5195 
5196 	if (phba->cfg_poll & ENABLE_FCP_RING_POLLING) {
5197 		lpfc_sli_handle_fast_ring_event(phba,
5198 			&phba->sli.sli3_ring[LPFC_FCP_RING], HA_R0RE_REQ);
5199 
5200 		if (phba->cfg_poll & DISABLE_FCP_RING_INT)
5201 			lpfc_poll_rearm_timer(phba);
5202 	}
5203 }
5204 
5205 /*
5206  * lpfc_is_command_vm_io - get the UUID from blk cgroup
5207  * @cmd: Pointer to scsi_cmnd data structure
5208  * Returns UUID if present, otherwise NULL
5209  */
5210 static char *lpfc_is_command_vm_io(struct scsi_cmnd *cmd)
5211 {
5212 	struct bio *bio = scsi_cmd_to_rq(cmd)->bio;
5213 
5214 	if (!IS_ENABLED(CONFIG_BLK_CGROUP_FC_APPID) || !bio)
5215 		return NULL;
5216 	return blkcg_get_fc_appid(bio);
5217 }
5218 
5219 /**
5220  * lpfc_queuecommand - scsi_host_template queuecommand entry point
5221  * @shost: kernel scsi host pointer.
5222  * @cmnd: Pointer to scsi_cmnd data structure.
5223  *
5224  * Driver registers this routine to scsi midlayer to submit a @cmd to process.
5225  * This routine prepares an IOCB from scsi command and provides to firmware.
5226  * The @done callback is invoked after driver finished processing the command.
5227  *
5228  * Return value :
5229  *   0 - Success
5230  *   SCSI_MLQUEUE_HOST_BUSY - Block all devices served by this host temporarily.
5231  **/
5232 static int
5233 lpfc_queuecommand(struct Scsi_Host *shost, struct scsi_cmnd *cmnd)
5234 {
5235 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
5236 	struct lpfc_hba   *phba = vport->phba;
5237 	struct lpfc_iocbq *cur_iocbq = NULL;
5238 	struct lpfc_rport_data *rdata;
5239 	struct lpfc_nodelist *ndlp;
5240 	struct lpfc_io_buf *lpfc_cmd;
5241 	struct fc_rport *rport = starget_to_rport(scsi_target(cmnd->device));
5242 	int err, idx;
5243 	u8 *uuid = NULL;
5244 	uint64_t start;
5245 
5246 	start = ktime_get_ns();
5247 	rdata = lpfc_rport_data_from_scsi_device(cmnd->device);
5248 
5249 	/* sanity check on references */
5250 	if (unlikely(!rdata) || unlikely(!rport))
5251 		goto out_fail_command;
5252 
5253 	err = fc_remote_port_chkready(rport);
5254 	if (err) {
5255 		cmnd->result = err;
5256 		goto out_fail_command;
5257 	}
5258 	ndlp = rdata->pnode;
5259 
5260 	if ((scsi_get_prot_op(cmnd) != SCSI_PROT_NORMAL) &&
5261 		(!(phba->sli3_options & LPFC_SLI3_BG_ENABLED))) {
5262 
5263 		lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5264 				"9058 BLKGRD: ERROR: rcvd protected cmd:%02x"
5265 				" op:%02x str=%s without registering for"
5266 				" BlockGuard - Rejecting command\n",
5267 				cmnd->cmnd[0], scsi_get_prot_op(cmnd),
5268 				dif_op_str[scsi_get_prot_op(cmnd)]);
5269 		goto out_fail_command;
5270 	}
5271 
5272 	/*
5273 	 * Catch race where our node has transitioned, but the
5274 	 * transport is still transitioning.
5275 	 */
5276 	if (!ndlp)
5277 		goto out_tgt_busy1;
5278 
5279 	/* Check if IO qualifies for CMF */
5280 	if (phba->cmf_active_mode != LPFC_CFG_OFF &&
5281 	    cmnd->sc_data_direction == DMA_FROM_DEVICE &&
5282 	    (scsi_sg_count(cmnd))) {
5283 		/* Latency start time saved in rx_cmd_start later in routine */
5284 		err = lpfc_update_cmf_cmd(phba, scsi_bufflen(cmnd));
5285 		if (err)
5286 			goto out_tgt_busy1;
5287 	}
5288 
5289 	if (lpfc_ndlp_check_qdepth(phba, ndlp)) {
5290 		if (atomic_read(&ndlp->cmd_pending) >= ndlp->cmd_qdepth) {
5291 			lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP_ERROR,
5292 					 "3377 Target Queue Full, scsi Id:%d "
5293 					 "Qdepth:%d Pending command:%d"
5294 					 " WWNN:%02x:%02x:%02x:%02x:"
5295 					 "%02x:%02x:%02x:%02x, "
5296 					 " WWPN:%02x:%02x:%02x:%02x:"
5297 					 "%02x:%02x:%02x:%02x",
5298 					 ndlp->nlp_sid, ndlp->cmd_qdepth,
5299 					 atomic_read(&ndlp->cmd_pending),
5300 					 ndlp->nlp_nodename.u.wwn[0],
5301 					 ndlp->nlp_nodename.u.wwn[1],
5302 					 ndlp->nlp_nodename.u.wwn[2],
5303 					 ndlp->nlp_nodename.u.wwn[3],
5304 					 ndlp->nlp_nodename.u.wwn[4],
5305 					 ndlp->nlp_nodename.u.wwn[5],
5306 					 ndlp->nlp_nodename.u.wwn[6],
5307 					 ndlp->nlp_nodename.u.wwn[7],
5308 					 ndlp->nlp_portname.u.wwn[0],
5309 					 ndlp->nlp_portname.u.wwn[1],
5310 					 ndlp->nlp_portname.u.wwn[2],
5311 					 ndlp->nlp_portname.u.wwn[3],
5312 					 ndlp->nlp_portname.u.wwn[4],
5313 					 ndlp->nlp_portname.u.wwn[5],
5314 					 ndlp->nlp_portname.u.wwn[6],
5315 					 ndlp->nlp_portname.u.wwn[7]);
5316 			goto out_tgt_busy2;
5317 		}
5318 	}
5319 
5320 	lpfc_cmd = lpfc_get_scsi_buf(phba, ndlp, cmnd);
5321 	if (lpfc_cmd == NULL) {
5322 		lpfc_rampdown_queue_depth(phba);
5323 
5324 		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP_ERROR,
5325 				 "0707 driver's buffer pool is empty, "
5326 				 "IO busied\n");
5327 		goto out_host_busy;
5328 	}
5329 	lpfc_cmd->rx_cmd_start = start;
5330 
5331 	cur_iocbq = &lpfc_cmd->cur_iocbq;
5332 	/*
5333 	 * Store the midlayer's command structure for the completion phase
5334 	 * and complete the command initialization.
5335 	 */
5336 	lpfc_cmd->pCmd  = cmnd;
5337 	lpfc_cmd->rdata = rdata;
5338 	lpfc_cmd->ndlp = ndlp;
5339 	cur_iocbq->cmd_cmpl = NULL;
5340 	cmnd->host_scribble = (unsigned char *)lpfc_cmd;
5341 
5342 	err = lpfc_scsi_prep_cmnd(vport, lpfc_cmd, ndlp);
5343 	if (err)
5344 		goto out_host_busy_release_buf;
5345 
5346 	if (scsi_get_prot_op(cmnd) != SCSI_PROT_NORMAL) {
5347 		if (vport->phba->cfg_enable_bg) {
5348 			lpfc_printf_vlog(vport,
5349 					 KERN_INFO, LOG_SCSI_CMD,
5350 					 "9033 BLKGRD: rcvd %s cmd:x%x "
5351 					 "reftag x%x cnt %u pt %x\n",
5352 					 dif_op_str[scsi_get_prot_op(cmnd)],
5353 					 cmnd->cmnd[0],
5354 					 scsi_prot_ref_tag(cmnd),
5355 					 scsi_logical_block_count(cmnd),
5356 					 (cmnd->cmnd[1]>>5));
5357 		}
5358 		err = lpfc_bg_scsi_prep_dma_buf(phba, lpfc_cmd);
5359 	} else {
5360 		if (vport->phba->cfg_enable_bg) {
5361 			lpfc_printf_vlog(vport,
5362 					 KERN_INFO, LOG_SCSI_CMD,
5363 					 "9038 BLKGRD: rcvd PROT_NORMAL cmd: "
5364 					 "x%x reftag x%x cnt %u pt %x\n",
5365 					 cmnd->cmnd[0],
5366 					 scsi_prot_ref_tag(cmnd),
5367 					 scsi_logical_block_count(cmnd),
5368 					 (cmnd->cmnd[1]>>5));
5369 		}
5370 		err = lpfc_scsi_prep_dma_buf(phba, lpfc_cmd);
5371 	}
5372 
5373 	if (unlikely(err)) {
5374 		if (err == 2) {
5375 			cmnd->result = DID_ERROR << 16;
5376 			goto out_fail_command_release_buf;
5377 		}
5378 		goto out_host_busy_free_buf;
5379 	}
5380 
5381 	/* check the necessary and sufficient condition to support VMID */
5382 	if (lpfc_is_vmid_enabled(phba) &&
5383 	    (ndlp->vmid_support ||
5384 	     phba->pport->vmid_priority_tagging ==
5385 	     LPFC_VMID_PRIO_TAG_ALL_TARGETS)) {
5386 		/* is the I/O generated by a VM, get the associated virtual */
5387 		/* entity id */
5388 		uuid = lpfc_is_command_vm_io(cmnd);
5389 
5390 		if (uuid) {
5391 			err = lpfc_vmid_get_appid(vport, uuid,
5392 					cmnd->sc_data_direction,
5393 					(union lpfc_vmid_io_tag *)
5394 						&cur_iocbq->vmid_tag);
5395 			if (!err)
5396 				cur_iocbq->cmd_flag |= LPFC_IO_VMID;
5397 		}
5398 	}
5399 
5400 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
5401 	if (unlikely(phba->hdwqstat_on & LPFC_CHECK_SCSI_IO))
5402 		this_cpu_inc(phba->sli4_hba.c_stat->xmt_io);
5403 #endif
5404 	/* Issue I/O to adapter */
5405 	err = lpfc_sli_issue_fcp_io(phba, LPFC_FCP_RING, cur_iocbq,
5406 				    SLI_IOCB_RET_IOCB);
5407 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
5408 	if (start) {
5409 		lpfc_cmd->ts_cmd_start = start;
5410 		lpfc_cmd->ts_last_cmd = phba->ktime_last_cmd;
5411 		lpfc_cmd->ts_cmd_wqput = ktime_get_ns();
5412 	} else {
5413 		lpfc_cmd->ts_cmd_start = 0;
5414 	}
5415 #endif
5416 	if (err) {
5417 		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5418 				 "3376 FCP could not issue iocb err %x "
5419 				 "FCP cmd x%x <%d/%llu> "
5420 				 "sid: x%x did: x%x oxid: x%x "
5421 				 "Data: x%x x%x x%x x%x\n",
5422 				 err, cmnd->cmnd[0],
5423 				 cmnd->device ? cmnd->device->id : 0xffff,
5424 				 cmnd->device ? cmnd->device->lun : (u64)-1,
5425 				 vport->fc_myDID, ndlp->nlp_DID,
5426 				 phba->sli_rev == LPFC_SLI_REV4 ?
5427 				 cur_iocbq->sli4_xritag : 0xffff,
5428 				 phba->sli_rev == LPFC_SLI_REV4 ?
5429 				 phba->sli4_hba.rpi_ids[ndlp->nlp_rpi] :
5430 				 cur_iocbq->iocb.ulpContext,
5431 				 cur_iocbq->iotag,
5432 				 phba->sli_rev == LPFC_SLI_REV4 ?
5433 				 bf_get(wqe_tmo,
5434 					&cur_iocbq->wqe.generic.wqe_com) :
5435 				 cur_iocbq->iocb.ulpTimeout,
5436 				 (uint32_t)(scsi_cmd_to_rq(cmnd)->timeout / 1000));
5437 
5438 		goto out_host_busy_free_buf;
5439 	}
5440 
5441 	if (phba->cfg_poll & ENABLE_FCP_RING_POLLING) {
5442 		lpfc_sli_handle_fast_ring_event(phba,
5443 			&phba->sli.sli3_ring[LPFC_FCP_RING], HA_R0RE_REQ);
5444 
5445 		if (phba->cfg_poll & DISABLE_FCP_RING_INT)
5446 			lpfc_poll_rearm_timer(phba);
5447 	}
5448 
5449 	if (phba->cfg_xri_rebalancing)
5450 		lpfc_keep_pvt_pool_above_lowwm(phba, lpfc_cmd->hdwq_no);
5451 
5452 	return 0;
5453 
5454  out_host_busy_free_buf:
5455 	idx = lpfc_cmd->hdwq_no;
5456 	lpfc_scsi_unprep_dma_buf(phba, lpfc_cmd);
5457 	if (phba->sli4_hba.hdwq) {
5458 		switch (lpfc_cmd->fcp_cmnd->fcpCntl3) {
5459 		case WRITE_DATA:
5460 			phba->sli4_hba.hdwq[idx].scsi_cstat.output_requests--;
5461 			break;
5462 		case READ_DATA:
5463 			phba->sli4_hba.hdwq[idx].scsi_cstat.input_requests--;
5464 			break;
5465 		default:
5466 			phba->sli4_hba.hdwq[idx].scsi_cstat.control_requests--;
5467 		}
5468 	}
5469  out_host_busy_release_buf:
5470 	lpfc_release_scsi_buf(phba, lpfc_cmd);
5471  out_host_busy:
5472 	lpfc_update_cmf_cmpl(phba, LPFC_CGN_NOT_SENT, scsi_bufflen(cmnd),
5473 			     shost);
5474 	return SCSI_MLQUEUE_HOST_BUSY;
5475 
5476  out_tgt_busy2:
5477 	lpfc_update_cmf_cmpl(phba, LPFC_CGN_NOT_SENT, scsi_bufflen(cmnd),
5478 			     shost);
5479  out_tgt_busy1:
5480 	return SCSI_MLQUEUE_TARGET_BUSY;
5481 
5482  out_fail_command_release_buf:
5483 	lpfc_release_scsi_buf(phba, lpfc_cmd);
5484 	lpfc_update_cmf_cmpl(phba, LPFC_CGN_NOT_SENT, scsi_bufflen(cmnd),
5485 			     shost);
5486 
5487  out_fail_command:
5488 	scsi_done(cmnd);
5489 	return 0;
5490 }
5491 
5492 /*
5493  * lpfc_vmid_vport_cleanup - cleans up the resources associated with a vport
5494  * @vport: The virtual port for which this call is being executed.
5495  */
5496 void lpfc_vmid_vport_cleanup(struct lpfc_vport *vport)
5497 {
5498 	u32 bucket;
5499 	struct lpfc_vmid *cur;
5500 
5501 	if (vport->port_type == LPFC_PHYSICAL_PORT)
5502 		del_timer_sync(&vport->phba->inactive_vmid_poll);
5503 
5504 	kfree(vport->qfpa_res);
5505 	kfree(vport->vmid_priority.vmid_range);
5506 	kfree(vport->vmid);
5507 
5508 	if (!hash_empty(vport->hash_table))
5509 		hash_for_each(vport->hash_table, bucket, cur, hnode)
5510 			hash_del(&cur->hnode);
5511 
5512 	vport->qfpa_res = NULL;
5513 	vport->vmid_priority.vmid_range = NULL;
5514 	vport->vmid = NULL;
5515 	vport->cur_vmid_cnt = 0;
5516 }
5517 
5518 /**
5519  * lpfc_abort_handler - scsi_host_template eh_abort_handler entry point
5520  * @cmnd: Pointer to scsi_cmnd data structure.
5521  *
5522  * This routine aborts @cmnd pending in base driver.
5523  *
5524  * Return code :
5525  *   0x2003 - Error
5526  *   0x2002 - Success
5527  **/
5528 static int
5529 lpfc_abort_handler(struct scsi_cmnd *cmnd)
5530 {
5531 	struct Scsi_Host  *shost = cmnd->device->host;
5532 	struct fc_rport *rport = starget_to_rport(scsi_target(cmnd->device));
5533 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
5534 	struct lpfc_hba   *phba = vport->phba;
5535 	struct lpfc_iocbq *iocb;
5536 	struct lpfc_io_buf *lpfc_cmd;
5537 	int ret = SUCCESS, status = 0;
5538 	struct lpfc_sli_ring *pring_s4 = NULL;
5539 	struct lpfc_sli_ring *pring = NULL;
5540 	int ret_val;
5541 	unsigned long flags;
5542 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(waitq);
5543 
5544 	status = fc_block_rport(rport);
5545 	if (status != 0 && status != SUCCESS)
5546 		return status;
5547 
5548 	lpfc_cmd = (struct lpfc_io_buf *)cmnd->host_scribble;
5549 	if (!lpfc_cmd)
5550 		return ret;
5551 
5552 	/* Guard against IO completion being called at same time */
5553 	spin_lock_irqsave(&lpfc_cmd->buf_lock, flags);
5554 
5555 	spin_lock(&phba->hbalock);
5556 	/* driver queued commands are in process of being flushed */
5557 	if (phba->hba_flag & HBA_IOQ_FLUSH) {
5558 		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5559 			"3168 SCSI Layer abort requested I/O has been "
5560 			"flushed by LLD.\n");
5561 		ret = FAILED;
5562 		goto out_unlock_hba;
5563 	}
5564 
5565 	if (!lpfc_cmd->pCmd) {
5566 		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5567 			 "2873 SCSI Layer I/O Abort Request IO CMPL Status "
5568 			 "x%x ID %d LUN %llu\n",
5569 			 SUCCESS, cmnd->device->id, cmnd->device->lun);
5570 		goto out_unlock_hba;
5571 	}
5572 
5573 	iocb = &lpfc_cmd->cur_iocbq;
5574 	if (phba->sli_rev == LPFC_SLI_REV4) {
5575 		pring_s4 = phba->sli4_hba.hdwq[iocb->hba_wqidx].io_wq->pring;
5576 		if (!pring_s4) {
5577 			ret = FAILED;
5578 			goto out_unlock_hba;
5579 		}
5580 		spin_lock(&pring_s4->ring_lock);
5581 	}
5582 	/* the command is in process of being cancelled */
5583 	if (!(iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ)) {
5584 		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5585 			"3169 SCSI Layer abort requested I/O has been "
5586 			"cancelled by LLD.\n");
5587 		ret = FAILED;
5588 		goto out_unlock_ring;
5589 	}
5590 	/*
5591 	 * If pCmd field of the corresponding lpfc_io_buf structure
5592 	 * points to a different SCSI command, then the driver has
5593 	 * already completed this command, but the midlayer did not
5594 	 * see the completion before the eh fired. Just return SUCCESS.
5595 	 */
5596 	if (lpfc_cmd->pCmd != cmnd) {
5597 		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5598 			"3170 SCSI Layer abort requested I/O has been "
5599 			"completed by LLD.\n");
5600 		goto out_unlock_ring;
5601 	}
5602 
5603 	WARN_ON(iocb->io_buf != lpfc_cmd);
5604 
5605 	/* abort issued in recovery is still in progress */
5606 	if (iocb->cmd_flag & LPFC_DRIVER_ABORTED) {
5607 		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5608 			 "3389 SCSI Layer I/O Abort Request is pending\n");
5609 		if (phba->sli_rev == LPFC_SLI_REV4)
5610 			spin_unlock(&pring_s4->ring_lock);
5611 		spin_unlock(&phba->hbalock);
5612 		spin_unlock_irqrestore(&lpfc_cmd->buf_lock, flags);
5613 		goto wait_for_cmpl;
5614 	}
5615 
5616 	lpfc_cmd->waitq = &waitq;
5617 	if (phba->sli_rev == LPFC_SLI_REV4) {
5618 		spin_unlock(&pring_s4->ring_lock);
5619 		ret_val = lpfc_sli4_issue_abort_iotag(phba, iocb,
5620 						      lpfc_sli_abort_fcp_cmpl);
5621 	} else {
5622 		pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
5623 		ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocb,
5624 						     lpfc_sli_abort_fcp_cmpl);
5625 	}
5626 
5627 	/* Make sure HBA is alive */
5628 	lpfc_issue_hb_tmo(phba);
5629 
5630 	if (ret_val != IOCB_SUCCESS) {
5631 		/* Indicate the IO is not being aborted by the driver. */
5632 		lpfc_cmd->waitq = NULL;
5633 		ret = FAILED;
5634 		goto out_unlock_hba;
5635 	}
5636 
5637 	/* no longer need the lock after this point */
5638 	spin_unlock(&phba->hbalock);
5639 	spin_unlock_irqrestore(&lpfc_cmd->buf_lock, flags);
5640 
5641 	if (phba->cfg_poll & DISABLE_FCP_RING_INT)
5642 		lpfc_sli_handle_fast_ring_event(phba,
5643 			&phba->sli.sli3_ring[LPFC_FCP_RING], HA_R0RE_REQ);
5644 
5645 wait_for_cmpl:
5646 	/*
5647 	 * cmd_flag is set to LPFC_DRIVER_ABORTED before we wait
5648 	 * for abort to complete.
5649 	 */
5650 	wait_event_timeout(waitq,
5651 			  (lpfc_cmd->pCmd != cmnd),
5652 			   msecs_to_jiffies(2*vport->cfg_devloss_tmo*1000));
5653 
5654 	spin_lock(&lpfc_cmd->buf_lock);
5655 
5656 	if (lpfc_cmd->pCmd == cmnd) {
5657 		ret = FAILED;
5658 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
5659 				 "0748 abort handler timed out waiting "
5660 				 "for aborting I/O (xri:x%x) to complete: "
5661 				 "ret %#x, ID %d, LUN %llu\n",
5662 				 iocb->sli4_xritag, ret,
5663 				 cmnd->device->id, cmnd->device->lun);
5664 	}
5665 
5666 	lpfc_cmd->waitq = NULL;
5667 
5668 	spin_unlock(&lpfc_cmd->buf_lock);
5669 	goto out;
5670 
5671 out_unlock_ring:
5672 	if (phba->sli_rev == LPFC_SLI_REV4)
5673 		spin_unlock(&pring_s4->ring_lock);
5674 out_unlock_hba:
5675 	spin_unlock(&phba->hbalock);
5676 	spin_unlock_irqrestore(&lpfc_cmd->buf_lock, flags);
5677 out:
5678 	lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
5679 			 "0749 SCSI Layer I/O Abort Request Status x%x ID %d "
5680 			 "LUN %llu\n", ret, cmnd->device->id,
5681 			 cmnd->device->lun);
5682 	return ret;
5683 }
5684 
5685 static char *
5686 lpfc_taskmgmt_name(uint8_t task_mgmt_cmd)
5687 {
5688 	switch (task_mgmt_cmd) {
5689 	case FCP_ABORT_TASK_SET:
5690 		return "ABORT_TASK_SET";
5691 	case FCP_CLEAR_TASK_SET:
5692 		return "FCP_CLEAR_TASK_SET";
5693 	case FCP_BUS_RESET:
5694 		return "FCP_BUS_RESET";
5695 	case FCP_LUN_RESET:
5696 		return "FCP_LUN_RESET";
5697 	case FCP_TARGET_RESET:
5698 		return "FCP_TARGET_RESET";
5699 	case FCP_CLEAR_ACA:
5700 		return "FCP_CLEAR_ACA";
5701 	case FCP_TERMINATE_TASK:
5702 		return "FCP_TERMINATE_TASK";
5703 	default:
5704 		return "unknown";
5705 	}
5706 }
5707 
5708 
5709 /**
5710  * lpfc_check_fcp_rsp - check the returned fcp_rsp to see if task failed
5711  * @vport: The virtual port for which this call is being executed.
5712  * @lpfc_cmd: Pointer to lpfc_io_buf data structure.
5713  *
5714  * This routine checks the FCP RSP INFO to see if the tsk mgmt command succeded
5715  *
5716  * Return code :
5717  *   0x2003 - Error
5718  *   0x2002 - Success
5719  **/
5720 static int
5721 lpfc_check_fcp_rsp(struct lpfc_vport *vport, struct lpfc_io_buf *lpfc_cmd)
5722 {
5723 	struct fcp_rsp *fcprsp = lpfc_cmd->fcp_rsp;
5724 	uint32_t rsp_info;
5725 	uint32_t rsp_len;
5726 	uint8_t  rsp_info_code;
5727 	int ret = FAILED;
5728 
5729 
5730 	if (fcprsp == NULL)
5731 		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5732 				 "0703 fcp_rsp is missing\n");
5733 	else {
5734 		rsp_info = fcprsp->rspStatus2;
5735 		rsp_len = be32_to_cpu(fcprsp->rspRspLen);
5736 		rsp_info_code = fcprsp->rspInfo3;
5737 
5738 
5739 		lpfc_printf_vlog(vport, KERN_INFO,
5740 				 LOG_FCP,
5741 				 "0706 fcp_rsp valid 0x%x,"
5742 				 " rsp len=%d code 0x%x\n",
5743 				 rsp_info,
5744 				 rsp_len, rsp_info_code);
5745 
5746 		/* If FCP_RSP_LEN_VALID bit is one, then the FCP_RSP_LEN
5747 		 * field specifies the number of valid bytes of FCP_RSP_INFO.
5748 		 * The FCP_RSP_LEN field shall be set to 0x04 or 0x08
5749 		 */
5750 		if ((fcprsp->rspStatus2 & RSP_LEN_VALID) &&
5751 		    ((rsp_len == 8) || (rsp_len == 4))) {
5752 			switch (rsp_info_code) {
5753 			case RSP_NO_FAILURE:
5754 				lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5755 						 "0715 Task Mgmt No Failure\n");
5756 				ret = SUCCESS;
5757 				break;
5758 			case RSP_TM_NOT_SUPPORTED: /* TM rejected */
5759 				lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5760 						 "0716 Task Mgmt Target "
5761 						"reject\n");
5762 				break;
5763 			case RSP_TM_NOT_COMPLETED: /* TM failed */
5764 				lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5765 						 "0717 Task Mgmt Target "
5766 						"failed TM\n");
5767 				break;
5768 			case RSP_TM_INVALID_LU: /* TM to invalid LU! */
5769 				lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5770 						 "0718 Task Mgmt to invalid "
5771 						"LUN\n");
5772 				break;
5773 			}
5774 		}
5775 	}
5776 	return ret;
5777 }
5778 
5779 
5780 /**
5781  * lpfc_send_taskmgmt - Generic SCSI Task Mgmt Handler
5782  * @vport: The virtual port for which this call is being executed.
5783  * @rport: Pointer to remote port
5784  * @tgt_id: Target ID of remote device.
5785  * @lun_id: Lun number for the TMF
5786  * @task_mgmt_cmd: type of TMF to send
5787  *
5788  * This routine builds and sends a TMF (SCSI Task Mgmt Function) to
5789  * a remote port.
5790  *
5791  * Return Code:
5792  *   0x2003 - Error
5793  *   0x2002 - Success.
5794  **/
5795 static int
5796 lpfc_send_taskmgmt(struct lpfc_vport *vport, struct fc_rport *rport,
5797 		   unsigned int tgt_id, uint64_t lun_id,
5798 		   uint8_t task_mgmt_cmd)
5799 {
5800 	struct lpfc_hba   *phba = vport->phba;
5801 	struct lpfc_io_buf *lpfc_cmd;
5802 	struct lpfc_iocbq *iocbq;
5803 	struct lpfc_iocbq *iocbqrsp;
5804 	struct lpfc_rport_data *rdata;
5805 	struct lpfc_nodelist *pnode;
5806 	int ret;
5807 	int status;
5808 
5809 	rdata = rport->dd_data;
5810 	if (!rdata || !rdata->pnode)
5811 		return FAILED;
5812 	pnode = rdata->pnode;
5813 
5814 	lpfc_cmd = lpfc_get_scsi_buf(phba, rdata->pnode, NULL);
5815 	if (lpfc_cmd == NULL)
5816 		return FAILED;
5817 	lpfc_cmd->timeout = phba->cfg_task_mgmt_tmo;
5818 	lpfc_cmd->rdata = rdata;
5819 	lpfc_cmd->pCmd = NULL;
5820 	lpfc_cmd->ndlp = pnode;
5821 
5822 	status = phba->lpfc_scsi_prep_task_mgmt_cmd(vport, lpfc_cmd, lun_id,
5823 						    task_mgmt_cmd);
5824 	if (!status) {
5825 		lpfc_release_scsi_buf(phba, lpfc_cmd);
5826 		return FAILED;
5827 	}
5828 
5829 	iocbq = &lpfc_cmd->cur_iocbq;
5830 	iocbqrsp = lpfc_sli_get_iocbq(phba);
5831 	if (iocbqrsp == NULL) {
5832 		lpfc_release_scsi_buf(phba, lpfc_cmd);
5833 		return FAILED;
5834 	}
5835 	iocbq->cmd_cmpl = lpfc_tskmgmt_def_cmpl;
5836 	iocbq->vport = vport;
5837 
5838 	lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5839 			 "0702 Issue %s to TGT %d LUN %llu "
5840 			 "rpi x%x nlp_flag x%x Data: x%x x%x\n",
5841 			 lpfc_taskmgmt_name(task_mgmt_cmd), tgt_id, lun_id,
5842 			 pnode->nlp_rpi, pnode->nlp_flag, iocbq->sli4_xritag,
5843 			 iocbq->cmd_flag);
5844 
5845 	status = lpfc_sli_issue_iocb_wait(phba, LPFC_FCP_RING,
5846 					  iocbq, iocbqrsp, lpfc_cmd->timeout);
5847 	if ((status != IOCB_SUCCESS) ||
5848 	    (get_job_ulpstatus(phba, iocbqrsp) != IOSTAT_SUCCESS)) {
5849 		if (status != IOCB_SUCCESS ||
5850 		    get_job_ulpstatus(phba, iocbqrsp) != IOSTAT_FCP_RSP_ERROR)
5851 			lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
5852 					 "0727 TMF %s to TGT %d LUN %llu "
5853 					 "failed (%d, %d) cmd_flag x%x\n",
5854 					 lpfc_taskmgmt_name(task_mgmt_cmd),
5855 					 tgt_id, lun_id,
5856 					 get_job_ulpstatus(phba, iocbqrsp),
5857 					 get_job_word4(phba, iocbqrsp),
5858 					 iocbq->cmd_flag);
5859 		/* if ulpStatus != IOCB_SUCCESS, then status == IOCB_SUCCESS */
5860 		if (status == IOCB_SUCCESS) {
5861 			if (get_job_ulpstatus(phba, iocbqrsp) ==
5862 			    IOSTAT_FCP_RSP_ERROR)
5863 				/* Something in the FCP_RSP was invalid.
5864 				 * Check conditions */
5865 				ret = lpfc_check_fcp_rsp(vport, lpfc_cmd);
5866 			else
5867 				ret = FAILED;
5868 		} else if ((status == IOCB_TIMEDOUT) ||
5869 			   (status == IOCB_ABORTED)) {
5870 			ret = TIMEOUT_ERROR;
5871 		} else {
5872 			ret = FAILED;
5873 		}
5874 	} else
5875 		ret = SUCCESS;
5876 
5877 	lpfc_sli_release_iocbq(phba, iocbqrsp);
5878 
5879 	if (status != IOCB_TIMEDOUT)
5880 		lpfc_release_scsi_buf(phba, lpfc_cmd);
5881 
5882 	return ret;
5883 }
5884 
5885 /**
5886  * lpfc_chk_tgt_mapped -
5887  * @vport: The virtual port to check on
5888  * @rport: Pointer to fc_rport data structure.
5889  *
5890  * This routine delays until the scsi target (aka rport) for the
5891  * command exists (is present and logged in) or we declare it non-existent.
5892  *
5893  * Return code :
5894  *  0x2003 - Error
5895  *  0x2002 - Success
5896  **/
5897 static int
5898 lpfc_chk_tgt_mapped(struct lpfc_vport *vport, struct fc_rport *rport)
5899 {
5900 	struct lpfc_rport_data *rdata;
5901 	struct lpfc_nodelist *pnode = NULL;
5902 	unsigned long later;
5903 
5904 	rdata = rport->dd_data;
5905 	if (!rdata) {
5906 		lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
5907 			"0797 Tgt Map rport failure: rdata x%px\n", rdata);
5908 		return FAILED;
5909 	}
5910 	pnode = rdata->pnode;
5911 
5912 	/*
5913 	 * If target is not in a MAPPED state, delay until
5914 	 * target is rediscovered or devloss timeout expires.
5915 	 */
5916 	later = msecs_to_jiffies(2 * vport->cfg_devloss_tmo * 1000) + jiffies;
5917 	while (time_after(later, jiffies)) {
5918 		if (!pnode)
5919 			return FAILED;
5920 		if (pnode->nlp_state == NLP_STE_MAPPED_NODE)
5921 			return SUCCESS;
5922 		schedule_timeout_uninterruptible(msecs_to_jiffies(500));
5923 		rdata = rport->dd_data;
5924 		if (!rdata)
5925 			return FAILED;
5926 		pnode = rdata->pnode;
5927 	}
5928 	if (!pnode || (pnode->nlp_state != NLP_STE_MAPPED_NODE))
5929 		return FAILED;
5930 	return SUCCESS;
5931 }
5932 
5933 /**
5934  * lpfc_reset_flush_io_context -
5935  * @vport: The virtual port (scsi_host) for the flush context
5936  * @tgt_id: If aborting by Target contect - specifies the target id
5937  * @lun_id: If aborting by Lun context - specifies the lun id
5938  * @context: specifies the context level to flush at.
5939  *
5940  * After a reset condition via TMF, we need to flush orphaned i/o
5941  * contexts from the adapter. This routine aborts any contexts
5942  * outstanding, then waits for their completions. The wait is
5943  * bounded by devloss_tmo though.
5944  *
5945  * Return code :
5946  *  0x2003 - Error
5947  *  0x2002 - Success
5948  **/
5949 static int
5950 lpfc_reset_flush_io_context(struct lpfc_vport *vport, uint16_t tgt_id,
5951 			uint64_t lun_id, lpfc_ctx_cmd context)
5952 {
5953 	struct lpfc_hba   *phba = vport->phba;
5954 	unsigned long later;
5955 	int cnt;
5956 
5957 	cnt = lpfc_sli_sum_iocb(vport, tgt_id, lun_id, context);
5958 	if (cnt)
5959 		lpfc_sli_abort_taskmgmt(vport,
5960 					&phba->sli.sli3_ring[LPFC_FCP_RING],
5961 					tgt_id, lun_id, context);
5962 	later = msecs_to_jiffies(2 * vport->cfg_devloss_tmo * 1000) + jiffies;
5963 	while (time_after(later, jiffies) && cnt) {
5964 		schedule_timeout_uninterruptible(msecs_to_jiffies(20));
5965 		cnt = lpfc_sli_sum_iocb(vport, tgt_id, lun_id, context);
5966 	}
5967 	if (cnt) {
5968 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
5969 			"0724 I/O flush failure for context %s : cnt x%x\n",
5970 			((context == LPFC_CTX_LUN) ? "LUN" :
5971 			 ((context == LPFC_CTX_TGT) ? "TGT" :
5972 			  ((context == LPFC_CTX_HOST) ? "HOST" : "Unknown"))),
5973 			cnt);
5974 		return FAILED;
5975 	}
5976 	return SUCCESS;
5977 }
5978 
5979 /**
5980  * lpfc_device_reset_handler - scsi_host_template eh_device_reset entry point
5981  * @cmnd: Pointer to scsi_cmnd data structure.
5982  *
5983  * This routine does a device reset by sending a LUN_RESET task management
5984  * command.
5985  *
5986  * Return code :
5987  *  0x2003 - Error
5988  *  0x2002 - Success
5989  **/
5990 static int
5991 lpfc_device_reset_handler(struct scsi_cmnd *cmnd)
5992 {
5993 	struct Scsi_Host  *shost = cmnd->device->host;
5994 	struct fc_rport *rport = starget_to_rport(scsi_target(cmnd->device));
5995 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
5996 	struct lpfc_rport_data *rdata;
5997 	struct lpfc_nodelist *pnode;
5998 	unsigned tgt_id = cmnd->device->id;
5999 	uint64_t lun_id = cmnd->device->lun;
6000 	struct lpfc_scsi_event_header scsi_event;
6001 	int status;
6002 	u32 logit = LOG_FCP;
6003 
6004 	if (!rport)
6005 		return FAILED;
6006 
6007 	rdata = rport->dd_data;
6008 	if (!rdata || !rdata->pnode) {
6009 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
6010 				 "0798 Device Reset rdata failure: rdata x%px\n",
6011 				 rdata);
6012 		return FAILED;
6013 	}
6014 	pnode = rdata->pnode;
6015 	status = fc_block_rport(rport);
6016 	if (status != 0 && status != SUCCESS)
6017 		return status;
6018 
6019 	status = lpfc_chk_tgt_mapped(vport, rport);
6020 	if (status == FAILED) {
6021 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
6022 			"0721 Device Reset rport failure: rdata x%px\n", rdata);
6023 		return FAILED;
6024 	}
6025 
6026 	scsi_event.event_type = FC_REG_SCSI_EVENT;
6027 	scsi_event.subcategory = LPFC_EVENT_LUNRESET;
6028 	scsi_event.lun = lun_id;
6029 	memcpy(scsi_event.wwpn, &pnode->nlp_portname, sizeof(struct lpfc_name));
6030 	memcpy(scsi_event.wwnn, &pnode->nlp_nodename, sizeof(struct lpfc_name));
6031 
6032 	fc_host_post_vendor_event(shost, fc_get_event_number(),
6033 		sizeof(scsi_event), (char *)&scsi_event, LPFC_NL_VENDOR_ID);
6034 
6035 	status = lpfc_send_taskmgmt(vport, rport, tgt_id, lun_id,
6036 						FCP_LUN_RESET);
6037 	if (status != SUCCESS)
6038 		logit =  LOG_TRACE_EVENT;
6039 
6040 	lpfc_printf_vlog(vport, KERN_ERR, logit,
6041 			 "0713 SCSI layer issued Device Reset (%d, %llu) "
6042 			 "return x%x\n", tgt_id, lun_id, status);
6043 
6044 	/*
6045 	 * We have to clean up i/o as : they may be orphaned by the TMF;
6046 	 * or if the TMF failed, they may be in an indeterminate state.
6047 	 * So, continue on.
6048 	 * We will report success if all the i/o aborts successfully.
6049 	 */
6050 	if (status == SUCCESS)
6051 		status = lpfc_reset_flush_io_context(vport, tgt_id, lun_id,
6052 						LPFC_CTX_LUN);
6053 
6054 	return status;
6055 }
6056 
6057 /**
6058  * lpfc_target_reset_handler - scsi_host_template eh_target_reset entry point
6059  * @cmnd: Pointer to scsi_cmnd data structure.
6060  *
6061  * This routine does a target reset by sending a TARGET_RESET task management
6062  * command.
6063  *
6064  * Return code :
6065  *  0x2003 - Error
6066  *  0x2002 - Success
6067  **/
6068 static int
6069 lpfc_target_reset_handler(struct scsi_cmnd *cmnd)
6070 {
6071 	struct Scsi_Host  *shost = cmnd->device->host;
6072 	struct fc_rport *rport = starget_to_rport(scsi_target(cmnd->device));
6073 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
6074 	struct lpfc_rport_data *rdata;
6075 	struct lpfc_nodelist *pnode;
6076 	unsigned tgt_id = cmnd->device->id;
6077 	uint64_t lun_id = cmnd->device->lun;
6078 	struct lpfc_scsi_event_header scsi_event;
6079 	int status;
6080 	u32 logit = LOG_FCP;
6081 	u32 dev_loss_tmo = vport->cfg_devloss_tmo;
6082 	unsigned long flags;
6083 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(waitq);
6084 
6085 	if (!rport)
6086 		return FAILED;
6087 
6088 	rdata = rport->dd_data;
6089 	if (!rdata || !rdata->pnode) {
6090 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
6091 				 "0799 Target Reset rdata failure: rdata x%px\n",
6092 				 rdata);
6093 		return FAILED;
6094 	}
6095 	pnode = rdata->pnode;
6096 	status = fc_block_rport(rport);
6097 	if (status != 0 && status != SUCCESS)
6098 		return status;
6099 
6100 	status = lpfc_chk_tgt_mapped(vport, rport);
6101 	if (status == FAILED) {
6102 		lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
6103 			"0722 Target Reset rport failure: rdata x%px\n", rdata);
6104 		if (pnode) {
6105 			spin_lock_irqsave(&pnode->lock, flags);
6106 			pnode->nlp_flag &= ~NLP_NPR_ADISC;
6107 			pnode->nlp_fcp_info &= ~NLP_FCP_2_DEVICE;
6108 			spin_unlock_irqrestore(&pnode->lock, flags);
6109 		}
6110 		lpfc_reset_flush_io_context(vport, tgt_id, lun_id,
6111 					  LPFC_CTX_TGT);
6112 		return FAST_IO_FAIL;
6113 	}
6114 
6115 	scsi_event.event_type = FC_REG_SCSI_EVENT;
6116 	scsi_event.subcategory = LPFC_EVENT_TGTRESET;
6117 	scsi_event.lun = 0;
6118 	memcpy(scsi_event.wwpn, &pnode->nlp_portname, sizeof(struct lpfc_name));
6119 	memcpy(scsi_event.wwnn, &pnode->nlp_nodename, sizeof(struct lpfc_name));
6120 
6121 	fc_host_post_vendor_event(shost, fc_get_event_number(),
6122 		sizeof(scsi_event), (char *)&scsi_event, LPFC_NL_VENDOR_ID);
6123 
6124 	status = lpfc_send_taskmgmt(vport, rport, tgt_id, lun_id,
6125 					FCP_TARGET_RESET);
6126 	if (status != SUCCESS) {
6127 		logit = LOG_TRACE_EVENT;
6128 
6129 		/* Issue LOGO, if no LOGO is outstanding */
6130 		spin_lock_irqsave(&pnode->lock, flags);
6131 		if (!(pnode->save_flags & NLP_WAIT_FOR_LOGO) &&
6132 		    !pnode->logo_waitq) {
6133 			pnode->logo_waitq = &waitq;
6134 			pnode->nlp_fcp_info &= ~NLP_FCP_2_DEVICE;
6135 			pnode->nlp_flag |= NLP_ISSUE_LOGO;
6136 			pnode->save_flags |= NLP_WAIT_FOR_LOGO;
6137 			spin_unlock_irqrestore(&pnode->lock, flags);
6138 			lpfc_unreg_rpi(vport, pnode);
6139 			wait_event_timeout(waitq,
6140 					   (!(pnode->save_flags &
6141 					      NLP_WAIT_FOR_LOGO)),
6142 					   msecs_to_jiffies(dev_loss_tmo *
6143 							    1000));
6144 
6145 			if (pnode->save_flags & NLP_WAIT_FOR_LOGO) {
6146 				lpfc_printf_vlog(vport, KERN_ERR, logit,
6147 						 "0725 SCSI layer TGTRST "
6148 						 "failed & LOGO TMO (%d, %llu) "
6149 						 "return x%x\n",
6150 						 tgt_id, lun_id, status);
6151 				spin_lock_irqsave(&pnode->lock, flags);
6152 				pnode->save_flags &= ~NLP_WAIT_FOR_LOGO;
6153 			} else {
6154 				spin_lock_irqsave(&pnode->lock, flags);
6155 			}
6156 			pnode->logo_waitq = NULL;
6157 			spin_unlock_irqrestore(&pnode->lock, flags);
6158 			status = SUCCESS;
6159 
6160 		} else {
6161 			spin_unlock_irqrestore(&pnode->lock, flags);
6162 			status = FAILED;
6163 		}
6164 	}
6165 
6166 	lpfc_printf_vlog(vport, KERN_ERR, logit,
6167 			 "0723 SCSI layer issued Target Reset (%d, %llu) "
6168 			 "return x%x\n", tgt_id, lun_id, status);
6169 
6170 	/*
6171 	 * We have to clean up i/o as : they may be orphaned by the TMF;
6172 	 * or if the TMF failed, they may be in an indeterminate state.
6173 	 * So, continue on.
6174 	 * We will report success if all the i/o aborts successfully.
6175 	 */
6176 	if (status == SUCCESS)
6177 		status = lpfc_reset_flush_io_context(vport, tgt_id, lun_id,
6178 					  LPFC_CTX_TGT);
6179 	return status;
6180 }
6181 
6182 /**
6183  * lpfc_host_reset_handler - scsi_host_template eh_host_reset_handler entry pt
6184  * @cmnd: Pointer to scsi_cmnd data structure.
6185  *
6186  * This routine does host reset to the adaptor port. It brings the HBA
6187  * offline, performs a board restart, and then brings the board back online.
6188  * The lpfc_offline calls lpfc_sli_hba_down which will abort and local
6189  * reject all outstanding SCSI commands to the host and error returned
6190  * back to SCSI mid-level. As this will be SCSI mid-level's last resort
6191  * of error handling, it will only return error if resetting of the adapter
6192  * is not successful; in all other cases, will return success.
6193  *
6194  * Return code :
6195  *  0x2003 - Error
6196  *  0x2002 - Success
6197  **/
6198 static int
6199 lpfc_host_reset_handler(struct scsi_cmnd *cmnd)
6200 {
6201 	struct Scsi_Host *shost = cmnd->device->host;
6202 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
6203 	struct lpfc_hba *phba = vport->phba;
6204 	int rc, ret = SUCCESS;
6205 
6206 	lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
6207 			 "3172 SCSI layer issued Host Reset Data:\n");
6208 
6209 	lpfc_offline_prep(phba, LPFC_MBX_WAIT);
6210 	lpfc_offline(phba);
6211 	rc = lpfc_sli_brdrestart(phba);
6212 	if (rc)
6213 		goto error;
6214 
6215 	/* Wait for successful restart of adapter */
6216 	if (phba->sli_rev < LPFC_SLI_REV4) {
6217 		rc = lpfc_sli_chipset_init(phba);
6218 		if (rc)
6219 			goto error;
6220 	}
6221 
6222 	rc = lpfc_online(phba);
6223 	if (rc)
6224 		goto error;
6225 
6226 	lpfc_unblock_mgmt_io(phba);
6227 
6228 	return ret;
6229 error:
6230 	lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
6231 			 "3323 Failed host reset\n");
6232 	lpfc_unblock_mgmt_io(phba);
6233 	return FAILED;
6234 }
6235 
6236 /**
6237  * lpfc_slave_alloc - scsi_host_template slave_alloc entry point
6238  * @sdev: Pointer to scsi_device.
6239  *
6240  * This routine populates the cmds_per_lun count + 2 scsi_bufs into  this host's
6241  * globally available list of scsi buffers. This routine also makes sure scsi
6242  * buffer is not allocated more than HBA limit conveyed to midlayer. This list
6243  * of scsi buffer exists for the lifetime of the driver.
6244  *
6245  * Return codes:
6246  *   non-0 - Error
6247  *   0 - Success
6248  **/
6249 static int
6250 lpfc_slave_alloc(struct scsi_device *sdev)
6251 {
6252 	struct lpfc_vport *vport = (struct lpfc_vport *) sdev->host->hostdata;
6253 	struct lpfc_hba   *phba = vport->phba;
6254 	struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
6255 	uint32_t total = 0;
6256 	uint32_t num_to_alloc = 0;
6257 	int num_allocated = 0;
6258 	uint32_t sdev_cnt;
6259 	struct lpfc_device_data *device_data;
6260 	unsigned long flags;
6261 	struct lpfc_name target_wwpn;
6262 
6263 	if (!rport || fc_remote_port_chkready(rport))
6264 		return -ENXIO;
6265 
6266 	if (phba->cfg_fof) {
6267 
6268 		/*
6269 		 * Check to see if the device data structure for the lun
6270 		 * exists.  If not, create one.
6271 		 */
6272 
6273 		u64_to_wwn(rport->port_name, target_wwpn.u.wwn);
6274 		spin_lock_irqsave(&phba->devicelock, flags);
6275 		device_data = __lpfc_get_device_data(phba,
6276 						     &phba->luns,
6277 						     &vport->fc_portname,
6278 						     &target_wwpn,
6279 						     sdev->lun);
6280 		if (!device_data) {
6281 			spin_unlock_irqrestore(&phba->devicelock, flags);
6282 			device_data = lpfc_create_device_data(phba,
6283 							&vport->fc_portname,
6284 							&target_wwpn,
6285 							sdev->lun,
6286 							phba->cfg_XLanePriority,
6287 							true);
6288 			if (!device_data)
6289 				return -ENOMEM;
6290 			spin_lock_irqsave(&phba->devicelock, flags);
6291 			list_add_tail(&device_data->listentry, &phba->luns);
6292 		}
6293 		device_data->rport_data = rport->dd_data;
6294 		device_data->available = true;
6295 		spin_unlock_irqrestore(&phba->devicelock, flags);
6296 		sdev->hostdata = device_data;
6297 	} else {
6298 		sdev->hostdata = rport->dd_data;
6299 	}
6300 	sdev_cnt = atomic_inc_return(&phba->sdev_cnt);
6301 
6302 	/* For SLI4, all IO buffers are pre-allocated */
6303 	if (phba->sli_rev == LPFC_SLI_REV4)
6304 		return 0;
6305 
6306 	/* This code path is now ONLY for SLI3 adapters */
6307 
6308 	/*
6309 	 * Populate the cmds_per_lun count scsi_bufs into this host's globally
6310 	 * available list of scsi buffers.  Don't allocate more than the
6311 	 * HBA limit conveyed to the midlayer via the host structure.  The
6312 	 * formula accounts for the lun_queue_depth + error handlers + 1
6313 	 * extra.  This list of scsi bufs exists for the lifetime of the driver.
6314 	 */
6315 	total = phba->total_scsi_bufs;
6316 	num_to_alloc = vport->cfg_lun_queue_depth + 2;
6317 
6318 	/* If allocated buffers are enough do nothing */
6319 	if ((sdev_cnt * (vport->cfg_lun_queue_depth + 2)) < total)
6320 		return 0;
6321 
6322 	/* Allow some exchanges to be available always to complete discovery */
6323 	if (total >= phba->cfg_hba_queue_depth - LPFC_DISC_IOCB_BUFF_COUNT ) {
6324 		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
6325 				 "0704 At limitation of %d preallocated "
6326 				 "command buffers\n", total);
6327 		return 0;
6328 	/* Allow some exchanges to be available always to complete discovery */
6329 	} else if (total + num_to_alloc >
6330 		phba->cfg_hba_queue_depth - LPFC_DISC_IOCB_BUFF_COUNT ) {
6331 		lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
6332 				 "0705 Allocation request of %d "
6333 				 "command buffers will exceed max of %d.  "
6334 				 "Reducing allocation request to %d.\n",
6335 				 num_to_alloc, phba->cfg_hba_queue_depth,
6336 				 (phba->cfg_hba_queue_depth - total));
6337 		num_to_alloc = phba->cfg_hba_queue_depth - total;
6338 	}
6339 	num_allocated = lpfc_new_scsi_buf_s3(vport, num_to_alloc);
6340 	if (num_to_alloc != num_allocated) {
6341 			lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
6342 					 "0708 Allocation request of %d "
6343 					 "command buffers did not succeed.  "
6344 					 "Allocated %d buffers.\n",
6345 					 num_to_alloc, num_allocated);
6346 	}
6347 	if (num_allocated > 0)
6348 		phba->total_scsi_bufs += num_allocated;
6349 	return 0;
6350 }
6351 
6352 /**
6353  * lpfc_slave_configure - scsi_host_template slave_configure entry point
6354  * @sdev: Pointer to scsi_device.
6355  *
6356  * This routine configures following items
6357  *   - Tag command queuing support for @sdev if supported.
6358  *   - Enable SLI polling for fcp ring if ENABLE_FCP_RING_POLLING flag is set.
6359  *
6360  * Return codes:
6361  *   0 - Success
6362  **/
6363 static int
6364 lpfc_slave_configure(struct scsi_device *sdev)
6365 {
6366 	struct lpfc_vport *vport = (struct lpfc_vport *) sdev->host->hostdata;
6367 	struct lpfc_hba   *phba = vport->phba;
6368 
6369 	scsi_change_queue_depth(sdev, vport->cfg_lun_queue_depth);
6370 
6371 	if (phba->cfg_poll & ENABLE_FCP_RING_POLLING) {
6372 		lpfc_sli_handle_fast_ring_event(phba,
6373 			&phba->sli.sli3_ring[LPFC_FCP_RING], HA_R0RE_REQ);
6374 		if (phba->cfg_poll & DISABLE_FCP_RING_INT)
6375 			lpfc_poll_rearm_timer(phba);
6376 	}
6377 
6378 	return 0;
6379 }
6380 
6381 /**
6382  * lpfc_slave_destroy - slave_destroy entry point of SHT data structure
6383  * @sdev: Pointer to scsi_device.
6384  *
6385  * This routine sets @sdev hostatdata filed to null.
6386  **/
6387 static void
6388 lpfc_slave_destroy(struct scsi_device *sdev)
6389 {
6390 	struct lpfc_vport *vport = (struct lpfc_vport *) sdev->host->hostdata;
6391 	struct lpfc_hba   *phba = vport->phba;
6392 	unsigned long flags;
6393 	struct lpfc_device_data *device_data = sdev->hostdata;
6394 
6395 	atomic_dec(&phba->sdev_cnt);
6396 	if ((phba->cfg_fof) && (device_data)) {
6397 		spin_lock_irqsave(&phba->devicelock, flags);
6398 		device_data->available = false;
6399 		if (!device_data->oas_enabled)
6400 			lpfc_delete_device_data(phba, device_data);
6401 		spin_unlock_irqrestore(&phba->devicelock, flags);
6402 	}
6403 	sdev->hostdata = NULL;
6404 	return;
6405 }
6406 
6407 /**
6408  * lpfc_create_device_data - creates and initializes device data structure for OAS
6409  * @phba: Pointer to host bus adapter structure.
6410  * @vport_wwpn: Pointer to vport's wwpn information
6411  * @target_wwpn: Pointer to target's wwpn information
6412  * @lun: Lun on target
6413  * @pri: Priority
6414  * @atomic_create: Flag to indicate if memory should be allocated using the
6415  *		  GFP_ATOMIC flag or not.
6416  *
6417  * This routine creates a device data structure which will contain identifying
6418  * information for the device (host wwpn, target wwpn, lun), state of OAS,
6419  * whether or not the corresponding lun is available by the system,
6420  * and pointer to the rport data.
6421  *
6422  * Return codes:
6423  *   NULL - Error
6424  *   Pointer to lpfc_device_data - Success
6425  **/
6426 struct lpfc_device_data*
6427 lpfc_create_device_data(struct lpfc_hba *phba, struct lpfc_name *vport_wwpn,
6428 			struct lpfc_name *target_wwpn, uint64_t lun,
6429 			uint32_t pri, bool atomic_create)
6430 {
6431 
6432 	struct lpfc_device_data *lun_info;
6433 	int memory_flags;
6434 
6435 	if (unlikely(!phba) || !vport_wwpn || !target_wwpn  ||
6436 	    !(phba->cfg_fof))
6437 		return NULL;
6438 
6439 	/* Attempt to create the device data to contain lun info */
6440 
6441 	if (atomic_create)
6442 		memory_flags = GFP_ATOMIC;
6443 	else
6444 		memory_flags = GFP_KERNEL;
6445 	lun_info = mempool_alloc(phba->device_data_mem_pool, memory_flags);
6446 	if (!lun_info)
6447 		return NULL;
6448 	INIT_LIST_HEAD(&lun_info->listentry);
6449 	lun_info->rport_data  = NULL;
6450 	memcpy(&lun_info->device_id.vport_wwpn, vport_wwpn,
6451 	       sizeof(struct lpfc_name));
6452 	memcpy(&lun_info->device_id.target_wwpn, target_wwpn,
6453 	       sizeof(struct lpfc_name));
6454 	lun_info->device_id.lun = lun;
6455 	lun_info->oas_enabled = false;
6456 	lun_info->priority = pri;
6457 	lun_info->available = false;
6458 	return lun_info;
6459 }
6460 
6461 /**
6462  * lpfc_delete_device_data - frees a device data structure for OAS
6463  * @phba: Pointer to host bus adapter structure.
6464  * @lun_info: Pointer to device data structure to free.
6465  *
6466  * This routine frees the previously allocated device data structure passed.
6467  *
6468  **/
6469 void
6470 lpfc_delete_device_data(struct lpfc_hba *phba,
6471 			struct lpfc_device_data *lun_info)
6472 {
6473 
6474 	if (unlikely(!phba) || !lun_info  ||
6475 	    !(phba->cfg_fof))
6476 		return;
6477 
6478 	if (!list_empty(&lun_info->listentry))
6479 		list_del(&lun_info->listentry);
6480 	mempool_free(lun_info, phba->device_data_mem_pool);
6481 	return;
6482 }
6483 
6484 /**
6485  * __lpfc_get_device_data - returns the device data for the specified lun
6486  * @phba: Pointer to host bus adapter structure.
6487  * @list: Point to list to search.
6488  * @vport_wwpn: Pointer to vport's wwpn information
6489  * @target_wwpn: Pointer to target's wwpn information
6490  * @lun: Lun on target
6491  *
6492  * This routine searches the list passed for the specified lun's device data.
6493  * This function does not hold locks, it is the responsibility of the caller
6494  * to ensure the proper lock is held before calling the function.
6495  *
6496  * Return codes:
6497  *   NULL - Error
6498  *   Pointer to lpfc_device_data - Success
6499  **/
6500 struct lpfc_device_data*
6501 __lpfc_get_device_data(struct lpfc_hba *phba, struct list_head *list,
6502 		       struct lpfc_name *vport_wwpn,
6503 		       struct lpfc_name *target_wwpn, uint64_t lun)
6504 {
6505 
6506 	struct lpfc_device_data *lun_info;
6507 
6508 	if (unlikely(!phba) || !list || !vport_wwpn || !target_wwpn ||
6509 	    !phba->cfg_fof)
6510 		return NULL;
6511 
6512 	/* Check to see if the lun is already enabled for OAS. */
6513 
6514 	list_for_each_entry(lun_info, list, listentry) {
6515 		if ((memcmp(&lun_info->device_id.vport_wwpn, vport_wwpn,
6516 			    sizeof(struct lpfc_name)) == 0) &&
6517 		    (memcmp(&lun_info->device_id.target_wwpn, target_wwpn,
6518 			    sizeof(struct lpfc_name)) == 0) &&
6519 		    (lun_info->device_id.lun == lun))
6520 			return lun_info;
6521 	}
6522 
6523 	return NULL;
6524 }
6525 
6526 /**
6527  * lpfc_find_next_oas_lun - searches for the next oas lun
6528  * @phba: Pointer to host bus adapter structure.
6529  * @vport_wwpn: Pointer to vport's wwpn information
6530  * @target_wwpn: Pointer to target's wwpn information
6531  * @starting_lun: Pointer to the lun to start searching for
6532  * @found_vport_wwpn: Pointer to the found lun's vport wwpn information
6533  * @found_target_wwpn: Pointer to the found lun's target wwpn information
6534  * @found_lun: Pointer to the found lun.
6535  * @found_lun_status: Pointer to status of the found lun.
6536  * @found_lun_pri: Pointer to priority of the found lun.
6537  *
6538  * This routine searches the luns list for the specified lun
6539  * or the first lun for the vport/target.  If the vport wwpn contains
6540  * a zero value then a specific vport is not specified. In this case
6541  * any vport which contains the lun will be considered a match.  If the
6542  * target wwpn contains a zero value then a specific target is not specified.
6543  * In this case any target which contains the lun will be considered a
6544  * match.  If the lun is found, the lun, vport wwpn, target wwpn and lun status
6545  * are returned.  The function will also return the next lun if available.
6546  * If the next lun is not found, starting_lun parameter will be set to
6547  * NO_MORE_OAS_LUN.
6548  *
6549  * Return codes:
6550  *   non-0 - Error
6551  *   0 - Success
6552  **/
6553 bool
6554 lpfc_find_next_oas_lun(struct lpfc_hba *phba, struct lpfc_name *vport_wwpn,
6555 		       struct lpfc_name *target_wwpn, uint64_t *starting_lun,
6556 		       struct lpfc_name *found_vport_wwpn,
6557 		       struct lpfc_name *found_target_wwpn,
6558 		       uint64_t *found_lun,
6559 		       uint32_t *found_lun_status,
6560 		       uint32_t *found_lun_pri)
6561 {
6562 
6563 	unsigned long flags;
6564 	struct lpfc_device_data *lun_info;
6565 	struct lpfc_device_id *device_id;
6566 	uint64_t lun;
6567 	bool found = false;
6568 
6569 	if (unlikely(!phba) || !vport_wwpn || !target_wwpn ||
6570 	    !starting_lun || !found_vport_wwpn ||
6571 	    !found_target_wwpn || !found_lun || !found_lun_status ||
6572 	    (*starting_lun == NO_MORE_OAS_LUN) ||
6573 	    !phba->cfg_fof)
6574 		return false;
6575 
6576 	lun = *starting_lun;
6577 	*found_lun = NO_MORE_OAS_LUN;
6578 	*starting_lun = NO_MORE_OAS_LUN;
6579 
6580 	/* Search for lun or the lun closet in value */
6581 
6582 	spin_lock_irqsave(&phba->devicelock, flags);
6583 	list_for_each_entry(lun_info, &phba->luns, listentry) {
6584 		if (((wwn_to_u64(vport_wwpn->u.wwn) == 0) ||
6585 		     (memcmp(&lun_info->device_id.vport_wwpn, vport_wwpn,
6586 			    sizeof(struct lpfc_name)) == 0)) &&
6587 		    ((wwn_to_u64(target_wwpn->u.wwn) == 0) ||
6588 		     (memcmp(&lun_info->device_id.target_wwpn, target_wwpn,
6589 			    sizeof(struct lpfc_name)) == 0)) &&
6590 		    (lun_info->oas_enabled)) {
6591 			device_id = &lun_info->device_id;
6592 			if ((!found) &&
6593 			    ((lun == FIND_FIRST_OAS_LUN) ||
6594 			     (device_id->lun == lun))) {
6595 				*found_lun = device_id->lun;
6596 				memcpy(found_vport_wwpn,
6597 				       &device_id->vport_wwpn,
6598 				       sizeof(struct lpfc_name));
6599 				memcpy(found_target_wwpn,
6600 				       &device_id->target_wwpn,
6601 				       sizeof(struct lpfc_name));
6602 				if (lun_info->available)
6603 					*found_lun_status =
6604 						OAS_LUN_STATUS_EXISTS;
6605 				else
6606 					*found_lun_status = 0;
6607 				*found_lun_pri = lun_info->priority;
6608 				if (phba->cfg_oas_flags & OAS_FIND_ANY_VPORT)
6609 					memset(vport_wwpn, 0x0,
6610 					       sizeof(struct lpfc_name));
6611 				if (phba->cfg_oas_flags & OAS_FIND_ANY_TARGET)
6612 					memset(target_wwpn, 0x0,
6613 					       sizeof(struct lpfc_name));
6614 				found = true;
6615 			} else if (found) {
6616 				*starting_lun = device_id->lun;
6617 				memcpy(vport_wwpn, &device_id->vport_wwpn,
6618 				       sizeof(struct lpfc_name));
6619 				memcpy(target_wwpn, &device_id->target_wwpn,
6620 				       sizeof(struct lpfc_name));
6621 				break;
6622 			}
6623 		}
6624 	}
6625 	spin_unlock_irqrestore(&phba->devicelock, flags);
6626 	return found;
6627 }
6628 
6629 /**
6630  * lpfc_enable_oas_lun - enables a lun for OAS operations
6631  * @phba: Pointer to host bus adapter structure.
6632  * @vport_wwpn: Pointer to vport's wwpn information
6633  * @target_wwpn: Pointer to target's wwpn information
6634  * @lun: Lun
6635  * @pri: Priority
6636  *
6637  * This routine enables a lun for oas operations.  The routines does so by
6638  * doing the following :
6639  *
6640  *   1) Checks to see if the device data for the lun has been created.
6641  *   2) If found, sets the OAS enabled flag if not set and returns.
6642  *   3) Otherwise, creates a device data structure.
6643  *   4) If successfully created, indicates the device data is for an OAS lun,
6644  *   indicates the lun is not available and add to the list of luns.
6645  *
6646  * Return codes:
6647  *   false - Error
6648  *   true - Success
6649  **/
6650 bool
6651 lpfc_enable_oas_lun(struct lpfc_hba *phba, struct lpfc_name *vport_wwpn,
6652 		    struct lpfc_name *target_wwpn, uint64_t lun, uint8_t pri)
6653 {
6654 
6655 	struct lpfc_device_data *lun_info;
6656 	unsigned long flags;
6657 
6658 	if (unlikely(!phba) || !vport_wwpn || !target_wwpn ||
6659 	    !phba->cfg_fof)
6660 		return false;
6661 
6662 	spin_lock_irqsave(&phba->devicelock, flags);
6663 
6664 	/* Check to see if the device data for the lun has been created */
6665 	lun_info = __lpfc_get_device_data(phba, &phba->luns, vport_wwpn,
6666 					  target_wwpn, lun);
6667 	if (lun_info) {
6668 		if (!lun_info->oas_enabled)
6669 			lun_info->oas_enabled = true;
6670 		lun_info->priority = pri;
6671 		spin_unlock_irqrestore(&phba->devicelock, flags);
6672 		return true;
6673 	}
6674 
6675 	/* Create an lun info structure and add to list of luns */
6676 	lun_info = lpfc_create_device_data(phba, vport_wwpn, target_wwpn, lun,
6677 					   pri, true);
6678 	if (lun_info) {
6679 		lun_info->oas_enabled = true;
6680 		lun_info->priority = pri;
6681 		lun_info->available = false;
6682 		list_add_tail(&lun_info->listentry, &phba->luns);
6683 		spin_unlock_irqrestore(&phba->devicelock, flags);
6684 		return true;
6685 	}
6686 	spin_unlock_irqrestore(&phba->devicelock, flags);
6687 	return false;
6688 }
6689 
6690 /**
6691  * lpfc_disable_oas_lun - disables a lun for OAS operations
6692  * @phba: Pointer to host bus adapter structure.
6693  * @vport_wwpn: Pointer to vport's wwpn information
6694  * @target_wwpn: Pointer to target's wwpn information
6695  * @lun: Lun
6696  * @pri: Priority
6697  *
6698  * This routine disables a lun for oas operations.  The routines does so by
6699  * doing the following :
6700  *
6701  *   1) Checks to see if the device data for the lun is created.
6702  *   2) If present, clears the flag indicating this lun is for OAS.
6703  *   3) If the lun is not available by the system, the device data is
6704  *   freed.
6705  *
6706  * Return codes:
6707  *   false - Error
6708  *   true - Success
6709  **/
6710 bool
6711 lpfc_disable_oas_lun(struct lpfc_hba *phba, struct lpfc_name *vport_wwpn,
6712 		     struct lpfc_name *target_wwpn, uint64_t lun, uint8_t pri)
6713 {
6714 
6715 	struct lpfc_device_data *lun_info;
6716 	unsigned long flags;
6717 
6718 	if (unlikely(!phba) || !vport_wwpn || !target_wwpn ||
6719 	    !phba->cfg_fof)
6720 		return false;
6721 
6722 	spin_lock_irqsave(&phba->devicelock, flags);
6723 
6724 	/* Check to see if the lun is available. */
6725 	lun_info = __lpfc_get_device_data(phba,
6726 					  &phba->luns, vport_wwpn,
6727 					  target_wwpn, lun);
6728 	if (lun_info) {
6729 		lun_info->oas_enabled = false;
6730 		lun_info->priority = pri;
6731 		if (!lun_info->available)
6732 			lpfc_delete_device_data(phba, lun_info);
6733 		spin_unlock_irqrestore(&phba->devicelock, flags);
6734 		return true;
6735 	}
6736 
6737 	spin_unlock_irqrestore(&phba->devicelock, flags);
6738 	return false;
6739 }
6740 
6741 static int
6742 lpfc_no_command(struct Scsi_Host *shost, struct scsi_cmnd *cmnd)
6743 {
6744 	return SCSI_MLQUEUE_HOST_BUSY;
6745 }
6746 
6747 static int
6748 lpfc_no_slave(struct scsi_device *sdev)
6749 {
6750 	return -ENODEV;
6751 }
6752 
6753 struct scsi_host_template lpfc_template_nvme = {
6754 	.module			= THIS_MODULE,
6755 	.name			= LPFC_DRIVER_NAME,
6756 	.proc_name		= LPFC_DRIVER_NAME,
6757 	.info			= lpfc_info,
6758 	.queuecommand		= lpfc_no_command,
6759 	.slave_alloc		= lpfc_no_slave,
6760 	.slave_configure	= lpfc_no_slave,
6761 	.scan_finished		= lpfc_scan_finished,
6762 	.this_id		= -1,
6763 	.sg_tablesize		= 1,
6764 	.cmd_per_lun		= 1,
6765 	.shost_groups		= lpfc_hba_groups,
6766 	.max_sectors		= 0xFFFFFFFF,
6767 	.vendor_id		= LPFC_NL_VENDOR_ID,
6768 	.track_queue_depth	= 0,
6769 };
6770 
6771 struct scsi_host_template lpfc_template = {
6772 	.module			= THIS_MODULE,
6773 	.name			= LPFC_DRIVER_NAME,
6774 	.proc_name		= LPFC_DRIVER_NAME,
6775 	.info			= lpfc_info,
6776 	.queuecommand		= lpfc_queuecommand,
6777 	.eh_timed_out		= fc_eh_timed_out,
6778 	.eh_should_retry_cmd    = fc_eh_should_retry_cmd,
6779 	.eh_abort_handler	= lpfc_abort_handler,
6780 	.eh_device_reset_handler = lpfc_device_reset_handler,
6781 	.eh_target_reset_handler = lpfc_target_reset_handler,
6782 	.eh_host_reset_handler  = lpfc_host_reset_handler,
6783 	.slave_alloc		= lpfc_slave_alloc,
6784 	.slave_configure	= lpfc_slave_configure,
6785 	.slave_destroy		= lpfc_slave_destroy,
6786 	.scan_finished		= lpfc_scan_finished,
6787 	.this_id		= -1,
6788 	.sg_tablesize		= LPFC_DEFAULT_SG_SEG_CNT,
6789 	.cmd_per_lun		= LPFC_CMD_PER_LUN,
6790 	.shost_groups		= lpfc_hba_groups,
6791 	.max_sectors		= 0xFFFFFFFF,
6792 	.vendor_id		= LPFC_NL_VENDOR_ID,
6793 	.change_queue_depth	= scsi_change_queue_depth,
6794 	.track_queue_depth	= 1,
6795 };
6796 
6797 struct scsi_host_template lpfc_vport_template = {
6798 	.module			= THIS_MODULE,
6799 	.name			= LPFC_DRIVER_NAME,
6800 	.proc_name		= LPFC_DRIVER_NAME,
6801 	.info			= lpfc_info,
6802 	.queuecommand		= lpfc_queuecommand,
6803 	.eh_timed_out		= fc_eh_timed_out,
6804 	.eh_should_retry_cmd    = fc_eh_should_retry_cmd,
6805 	.eh_abort_handler	= lpfc_abort_handler,
6806 	.eh_device_reset_handler = lpfc_device_reset_handler,
6807 	.eh_target_reset_handler = lpfc_target_reset_handler,
6808 	.eh_bus_reset_handler	= NULL,
6809 	.eh_host_reset_handler	= NULL,
6810 	.slave_alloc		= lpfc_slave_alloc,
6811 	.slave_configure	= lpfc_slave_configure,
6812 	.slave_destroy		= lpfc_slave_destroy,
6813 	.scan_finished		= lpfc_scan_finished,
6814 	.this_id		= -1,
6815 	.sg_tablesize		= LPFC_DEFAULT_SG_SEG_CNT,
6816 	.cmd_per_lun		= LPFC_CMD_PER_LUN,
6817 	.shost_groups		= lpfc_vport_groups,
6818 	.max_sectors		= 0xFFFFFFFF,
6819 	.vendor_id		= 0,
6820 	.change_queue_depth	= scsi_change_queue_depth,
6821 	.track_queue_depth	= 1,
6822 };
6823