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