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