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