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