[SCSI] lpfc 8.3.24: Miscellaneous Fixes and Corrections
[firefly-linux-kernel-4.4.55.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-2011 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/delay.h>
25 #include <asm/unaligned.h>
26
27 #include <scsi/scsi.h>
28 #include <scsi/scsi_device.h>
29 #include <scsi/scsi_eh.h>
30 #include <scsi/scsi_host.h>
31 #include <scsi/scsi_tcq.h>
32 #include <scsi/scsi_transport_fc.h>
33
34 #include "lpfc_version.h"
35 #include "lpfc_hw4.h"
36 #include "lpfc_hw.h"
37 #include "lpfc_sli.h"
38 #include "lpfc_sli4.h"
39 #include "lpfc_nl.h"
40 #include "lpfc_disc.h"
41 #include "lpfc_scsi.h"
42 #include "lpfc.h"
43 #include "lpfc_logmsg.h"
44 #include "lpfc_crtn.h"
45 #include "lpfc_vport.h"
46
47 #define LPFC_RESET_WAIT  2
48 #define LPFC_ABORT_WAIT  2
49
50 int _dump_buf_done;
51
52 static char *dif_op_str[] = {
53         "SCSI_PROT_NORMAL",
54         "SCSI_PROT_READ_INSERT",
55         "SCSI_PROT_WRITE_STRIP",
56         "SCSI_PROT_READ_STRIP",
57         "SCSI_PROT_WRITE_INSERT",
58         "SCSI_PROT_READ_PASS",
59         "SCSI_PROT_WRITE_PASS",
60 };
61 static void
62 lpfc_release_scsi_buf_s4(struct lpfc_hba *phba, struct lpfc_scsi_buf *psb);
63 static void
64 lpfc_release_scsi_buf_s3(struct lpfc_hba *phba, struct lpfc_scsi_buf *psb);
65
66 static void
67 lpfc_debug_save_data(struct lpfc_hba *phba, struct scsi_cmnd *cmnd)
68 {
69         void *src, *dst;
70         struct scatterlist *sgde = scsi_sglist(cmnd);
71
72         if (!_dump_buf_data) {
73                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
74                         "9050 BLKGRD: ERROR %s _dump_buf_data is NULL\n",
75                                 __func__);
76                 return;
77         }
78
79
80         if (!sgde) {
81                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
82                         "9051 BLKGRD: ERROR: data scatterlist is null\n");
83                 return;
84         }
85
86         dst = (void *) _dump_buf_data;
87         while (sgde) {
88                 src = sg_virt(sgde);
89                 memcpy(dst, src, sgde->length);
90                 dst += sgde->length;
91                 sgde = sg_next(sgde);
92         }
93 }
94
95 static void
96 lpfc_debug_save_dif(struct lpfc_hba *phba, struct scsi_cmnd *cmnd)
97 {
98         void *src, *dst;
99         struct scatterlist *sgde = scsi_prot_sglist(cmnd);
100
101         if (!_dump_buf_dif) {
102                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
103                         "9052 BLKGRD: ERROR %s _dump_buf_data is NULL\n",
104                                 __func__);
105                 return;
106         }
107
108         if (!sgde) {
109                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
110                         "9053 BLKGRD: ERROR: prot scatterlist is null\n");
111                 return;
112         }
113
114         dst = _dump_buf_dif;
115         while (sgde) {
116                 src = sg_virt(sgde);
117                 memcpy(dst, src, sgde->length);
118                 dst += sgde->length;
119                 sgde = sg_next(sgde);
120         }
121 }
122
123 /**
124  * lpfc_sli4_set_rsp_sgl_last - Set the last bit in the response sge.
125  * @phba: Pointer to HBA object.
126  * @lpfc_cmd: lpfc scsi command object pointer.
127  *
128  * This function is called from the lpfc_prep_task_mgmt_cmd function to
129  * set the last bit in the response sge entry.
130  **/
131 static void
132 lpfc_sli4_set_rsp_sgl_last(struct lpfc_hba *phba,
133                                 struct lpfc_scsi_buf *lpfc_cmd)
134 {
135         struct sli4_sge *sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
136         if (sgl) {
137                 sgl += 1;
138                 sgl->word2 = le32_to_cpu(sgl->word2);
139                 bf_set(lpfc_sli4_sge_last, sgl, 1);
140                 sgl->word2 = cpu_to_le32(sgl->word2);
141         }
142 }
143
144 /**
145  * lpfc_update_stats - Update statistical data for the command completion
146  * @phba: Pointer to HBA object.
147  * @lpfc_cmd: lpfc scsi command object pointer.
148  *
149  * This function is called when there is a command completion and this
150  * function updates the statistical data for the command completion.
151  **/
152 static void
153 lpfc_update_stats(struct lpfc_hba *phba, struct  lpfc_scsi_buf *lpfc_cmd)
154 {
155         struct lpfc_rport_data *rdata = lpfc_cmd->rdata;
156         struct lpfc_nodelist *pnode = rdata->pnode;
157         struct scsi_cmnd *cmd = lpfc_cmd->pCmd;
158         unsigned long flags;
159         struct Scsi_Host  *shost = cmd->device->host;
160         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
161         unsigned long latency;
162         int i;
163
164         if (cmd->result)
165                 return;
166
167         latency = jiffies_to_msecs((long)jiffies - (long)lpfc_cmd->start_time);
168
169         spin_lock_irqsave(shost->host_lock, flags);
170         if (!vport->stat_data_enabled ||
171                 vport->stat_data_blocked ||
172                 !pnode ||
173                 !pnode->lat_data ||
174                 (phba->bucket_type == LPFC_NO_BUCKET)) {
175                 spin_unlock_irqrestore(shost->host_lock, flags);
176                 return;
177         }
178
179         if (phba->bucket_type == LPFC_LINEAR_BUCKET) {
180                 i = (latency + phba->bucket_step - 1 - phba->bucket_base)/
181                         phba->bucket_step;
182                 /* check array subscript bounds */
183                 if (i < 0)
184                         i = 0;
185                 else if (i >= LPFC_MAX_BUCKET_COUNT)
186                         i = LPFC_MAX_BUCKET_COUNT - 1;
187         } else {
188                 for (i = 0; i < LPFC_MAX_BUCKET_COUNT-1; i++)
189                         if (latency <= (phba->bucket_base +
190                                 ((1<<i)*phba->bucket_step)))
191                                 break;
192         }
193
194         pnode->lat_data[i].cmd_count++;
195         spin_unlock_irqrestore(shost->host_lock, flags);
196 }
197
198 /**
199  * lpfc_send_sdev_queuedepth_change_event - Posts a queuedepth change event
200  * @phba: Pointer to HBA context object.
201  * @vport: Pointer to vport object.
202  * @ndlp: Pointer to FC node associated with the target.
203  * @lun: Lun number of the scsi device.
204  * @old_val: Old value of the queue depth.
205  * @new_val: New value of the queue depth.
206  *
207  * This function sends an event to the mgmt application indicating
208  * there is a change in the scsi device queue depth.
209  **/
210 static void
211 lpfc_send_sdev_queuedepth_change_event(struct lpfc_hba *phba,
212                 struct lpfc_vport  *vport,
213                 struct lpfc_nodelist *ndlp,
214                 uint32_t lun,
215                 uint32_t old_val,
216                 uint32_t new_val)
217 {
218         struct lpfc_fast_path_event *fast_path_evt;
219         unsigned long flags;
220
221         fast_path_evt = lpfc_alloc_fast_evt(phba);
222         if (!fast_path_evt)
223                 return;
224
225         fast_path_evt->un.queue_depth_evt.scsi_event.event_type =
226                 FC_REG_SCSI_EVENT;
227         fast_path_evt->un.queue_depth_evt.scsi_event.subcategory =
228                 LPFC_EVENT_VARQUEDEPTH;
229
230         /* Report all luns with change in queue depth */
231         fast_path_evt->un.queue_depth_evt.scsi_event.lun = lun;
232         if (ndlp && NLP_CHK_NODE_ACT(ndlp)) {
233                 memcpy(&fast_path_evt->un.queue_depth_evt.scsi_event.wwpn,
234                         &ndlp->nlp_portname, sizeof(struct lpfc_name));
235                 memcpy(&fast_path_evt->un.queue_depth_evt.scsi_event.wwnn,
236                         &ndlp->nlp_nodename, sizeof(struct lpfc_name));
237         }
238
239         fast_path_evt->un.queue_depth_evt.oldval = old_val;
240         fast_path_evt->un.queue_depth_evt.newval = new_val;
241         fast_path_evt->vport = vport;
242
243         fast_path_evt->work_evt.evt = LPFC_EVT_FASTPATH_MGMT_EVT;
244         spin_lock_irqsave(&phba->hbalock, flags);
245         list_add_tail(&fast_path_evt->work_evt.evt_listp, &phba->work_list);
246         spin_unlock_irqrestore(&phba->hbalock, flags);
247         lpfc_worker_wake_up(phba);
248
249         return;
250 }
251
252 /**
253  * lpfc_change_queue_depth - Alter scsi device queue depth
254  * @sdev: Pointer the scsi device on which to change the queue depth.
255  * @qdepth: New queue depth to set the sdev to.
256  * @reason: The reason for the queue depth change.
257  *
258  * This function is called by the midlayer and the LLD to alter the queue
259  * depth for a scsi device. This function sets the queue depth to the new
260  * value and sends an event out to log the queue depth change.
261  **/
262 int
263 lpfc_change_queue_depth(struct scsi_device *sdev, int qdepth, int reason)
264 {
265         struct lpfc_vport *vport = (struct lpfc_vport *) sdev->host->hostdata;
266         struct lpfc_hba   *phba = vport->phba;
267         struct lpfc_rport_data *rdata;
268         unsigned long new_queue_depth, old_queue_depth;
269
270         old_queue_depth = sdev->queue_depth;
271         scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), qdepth);
272         new_queue_depth = sdev->queue_depth;
273         rdata = sdev->hostdata;
274         if (rdata)
275                 lpfc_send_sdev_queuedepth_change_event(phba, vport,
276                                                        rdata->pnode, sdev->lun,
277                                                        old_queue_depth,
278                                                        new_queue_depth);
279         return sdev->queue_depth;
280 }
281
282 /**
283  * lpfc_rampdown_queue_depth - Post RAMP_DOWN_QUEUE event to worker thread
284  * @phba: The Hba for which this call is being executed.
285  *
286  * This routine is called when there is resource error in driver or firmware.
287  * This routine posts WORKER_RAMP_DOWN_QUEUE event for @phba. This routine
288  * posts at most 1 event each second. This routine wakes up worker thread of
289  * @phba to process WORKER_RAM_DOWN_EVENT event.
290  *
291  * This routine should be called with no lock held.
292  **/
293 void
294 lpfc_rampdown_queue_depth(struct lpfc_hba *phba)
295 {
296         unsigned long flags;
297         uint32_t evt_posted;
298
299         spin_lock_irqsave(&phba->hbalock, flags);
300         atomic_inc(&phba->num_rsrc_err);
301         phba->last_rsrc_error_time = jiffies;
302
303         if ((phba->last_ramp_down_time + QUEUE_RAMP_DOWN_INTERVAL) > jiffies) {
304                 spin_unlock_irqrestore(&phba->hbalock, flags);
305                 return;
306         }
307
308         phba->last_ramp_down_time = jiffies;
309
310         spin_unlock_irqrestore(&phba->hbalock, flags);
311
312         spin_lock_irqsave(&phba->pport->work_port_lock, flags);
313         evt_posted = phba->pport->work_port_events & WORKER_RAMP_DOWN_QUEUE;
314         if (!evt_posted)
315                 phba->pport->work_port_events |= WORKER_RAMP_DOWN_QUEUE;
316         spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
317
318         if (!evt_posted)
319                 lpfc_worker_wake_up(phba);
320         return;
321 }
322
323 /**
324  * lpfc_rampup_queue_depth - Post RAMP_UP_QUEUE event for worker thread
325  * @phba: The Hba for which this call is being executed.
326  *
327  * This routine post WORKER_RAMP_UP_QUEUE event for @phba vport. This routine
328  * post at most 1 event every 5 minute after last_ramp_up_time or
329  * last_rsrc_error_time.  This routine wakes up worker thread of @phba
330  * to process WORKER_RAM_DOWN_EVENT event.
331  *
332  * This routine should be called with no lock held.
333  **/
334 static inline void
335 lpfc_rampup_queue_depth(struct lpfc_vport  *vport,
336                         uint32_t queue_depth)
337 {
338         unsigned long flags;
339         struct lpfc_hba *phba = vport->phba;
340         uint32_t evt_posted;
341         atomic_inc(&phba->num_cmd_success);
342
343         if (vport->cfg_lun_queue_depth <= queue_depth)
344                 return;
345         spin_lock_irqsave(&phba->hbalock, flags);
346         if (time_before(jiffies,
347                         phba->last_ramp_up_time + QUEUE_RAMP_UP_INTERVAL) ||
348             time_before(jiffies,
349                         phba->last_rsrc_error_time + QUEUE_RAMP_UP_INTERVAL)) {
350                 spin_unlock_irqrestore(&phba->hbalock, flags);
351                 return;
352         }
353         phba->last_ramp_up_time = jiffies;
354         spin_unlock_irqrestore(&phba->hbalock, flags);
355
356         spin_lock_irqsave(&phba->pport->work_port_lock, flags);
357         evt_posted = phba->pport->work_port_events & WORKER_RAMP_UP_QUEUE;
358         if (!evt_posted)
359                 phba->pport->work_port_events |= WORKER_RAMP_UP_QUEUE;
360         spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
361
362         if (!evt_posted)
363                 lpfc_worker_wake_up(phba);
364         return;
365 }
366
367 /**
368  * lpfc_ramp_down_queue_handler - WORKER_RAMP_DOWN_QUEUE event handler
369  * @phba: The Hba for which this call is being executed.
370  *
371  * This routine is called to  process WORKER_RAMP_DOWN_QUEUE event for worker
372  * thread.This routine reduces queue depth for all scsi device on each vport
373  * associated with @phba.
374  **/
375 void
376 lpfc_ramp_down_queue_handler(struct lpfc_hba *phba)
377 {
378         struct lpfc_vport **vports;
379         struct Scsi_Host  *shost;
380         struct scsi_device *sdev;
381         unsigned long new_queue_depth;
382         unsigned long num_rsrc_err, num_cmd_success;
383         int i;
384
385         num_rsrc_err = atomic_read(&phba->num_rsrc_err);
386         num_cmd_success = atomic_read(&phba->num_cmd_success);
387
388         vports = lpfc_create_vport_work_array(phba);
389         if (vports != NULL)
390                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
391                         shost = lpfc_shost_from_vport(vports[i]);
392                         shost_for_each_device(sdev, shost) {
393                                 new_queue_depth =
394                                         sdev->queue_depth * num_rsrc_err /
395                                         (num_rsrc_err + num_cmd_success);
396                                 if (!new_queue_depth)
397                                         new_queue_depth = sdev->queue_depth - 1;
398                                 else
399                                         new_queue_depth = sdev->queue_depth -
400                                                                 new_queue_depth;
401                                 lpfc_change_queue_depth(sdev, new_queue_depth,
402                                                         SCSI_QDEPTH_DEFAULT);
403                         }
404                 }
405         lpfc_destroy_vport_work_array(phba, vports);
406         atomic_set(&phba->num_rsrc_err, 0);
407         atomic_set(&phba->num_cmd_success, 0);
408 }
409
410 /**
411  * lpfc_ramp_up_queue_handler - WORKER_RAMP_UP_QUEUE event handler
412  * @phba: The Hba for which this call is being executed.
413  *
414  * This routine is called to  process WORKER_RAMP_UP_QUEUE event for worker
415  * thread.This routine increases queue depth for all scsi device on each vport
416  * associated with @phba by 1. This routine also sets @phba num_rsrc_err and
417  * num_cmd_success to zero.
418  **/
419 void
420 lpfc_ramp_up_queue_handler(struct lpfc_hba *phba)
421 {
422         struct lpfc_vport **vports;
423         struct Scsi_Host  *shost;
424         struct scsi_device *sdev;
425         int i;
426
427         vports = lpfc_create_vport_work_array(phba);
428         if (vports != NULL)
429                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
430                         shost = lpfc_shost_from_vport(vports[i]);
431                         shost_for_each_device(sdev, shost) {
432                                 if (vports[i]->cfg_lun_queue_depth <=
433                                     sdev->queue_depth)
434                                         continue;
435                                 lpfc_change_queue_depth(sdev,
436                                                         sdev->queue_depth+1,
437                                                         SCSI_QDEPTH_RAMP_UP);
438                         }
439                 }
440         lpfc_destroy_vport_work_array(phba, vports);
441         atomic_set(&phba->num_rsrc_err, 0);
442         atomic_set(&phba->num_cmd_success, 0);
443 }
444
445 /**
446  * lpfc_scsi_dev_block - set all scsi hosts to block state
447  * @phba: Pointer to HBA context object.
448  *
449  * This function walks vport list and set each SCSI host to block state
450  * by invoking fc_remote_port_delete() routine. This function is invoked
451  * with EEH when device's PCI slot has been permanently disabled.
452  **/
453 void
454 lpfc_scsi_dev_block(struct lpfc_hba *phba)
455 {
456         struct lpfc_vport **vports;
457         struct Scsi_Host  *shost;
458         struct scsi_device *sdev;
459         struct fc_rport *rport;
460         int i;
461
462         vports = lpfc_create_vport_work_array(phba);
463         if (vports != NULL)
464                 for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++) {
465                         shost = lpfc_shost_from_vport(vports[i]);
466                         shost_for_each_device(sdev, shost) {
467                                 rport = starget_to_rport(scsi_target(sdev));
468                                 fc_remote_port_delete(rport);
469                         }
470                 }
471         lpfc_destroy_vport_work_array(phba, vports);
472 }
473
474 /**
475  * lpfc_new_scsi_buf_s3 - Scsi buffer allocator for HBA with SLI3 IF spec
476  * @vport: The virtual port for which this call being executed.
477  * @num_to_allocate: The requested number of buffers to allocate.
478  *
479  * This routine allocates a scsi buffer for device with SLI-3 interface spec,
480  * the scsi buffer contains all the necessary information needed to initiate
481  * a SCSI I/O. The non-DMAable buffer region contains information to build
482  * the IOCB. The DMAable region contains memory for the FCP CMND, FCP RSP,
483  * and the initial BPL. In addition to allocating memory, the FCP CMND and
484  * FCP RSP BDEs are setup in the BPL and the BPL BDE is setup in the IOCB.
485  *
486  * Return codes:
487  *   int - number of scsi buffers that were allocated.
488  *   0 = failure, less than num_to_alloc is a partial failure.
489  **/
490 static int
491 lpfc_new_scsi_buf_s3(struct lpfc_vport *vport, int num_to_alloc)
492 {
493         struct lpfc_hba *phba = vport->phba;
494         struct lpfc_scsi_buf *psb;
495         struct ulp_bde64 *bpl;
496         IOCB_t *iocb;
497         dma_addr_t pdma_phys_fcp_cmd;
498         dma_addr_t pdma_phys_fcp_rsp;
499         dma_addr_t pdma_phys_bpl;
500         uint16_t iotag;
501         int bcnt;
502
503         for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
504                 psb = kzalloc(sizeof(struct lpfc_scsi_buf), GFP_KERNEL);
505                 if (!psb)
506                         break;
507
508                 /*
509                  * Get memory from the pci pool to map the virt space to pci
510                  * bus space for an I/O.  The DMA buffer includes space for the
511                  * struct fcp_cmnd, struct fcp_rsp and the number of bde's
512                  * necessary to support the sg_tablesize.
513                  */
514                 psb->data = pci_pool_alloc(phba->lpfc_scsi_dma_buf_pool,
515                                         GFP_KERNEL, &psb->dma_handle);
516                 if (!psb->data) {
517                         kfree(psb);
518                         break;
519                 }
520
521                 /* Initialize virtual ptrs to dma_buf region. */
522                 memset(psb->data, 0, phba->cfg_sg_dma_buf_size);
523
524                 /* Allocate iotag for psb->cur_iocbq. */
525                 iotag = lpfc_sli_next_iotag(phba, &psb->cur_iocbq);
526                 if (iotag == 0) {
527                         pci_pool_free(phba->lpfc_scsi_dma_buf_pool,
528                                         psb->data, psb->dma_handle);
529                         kfree(psb);
530                         break;
531                 }
532                 psb->cur_iocbq.iocb_flag |= LPFC_IO_FCP;
533
534                 psb->fcp_cmnd = psb->data;
535                 psb->fcp_rsp = psb->data + sizeof(struct fcp_cmnd);
536                 psb->fcp_bpl = psb->data + sizeof(struct fcp_cmnd) +
537                         sizeof(struct fcp_rsp);
538
539                 /* Initialize local short-hand pointers. */
540                 bpl = psb->fcp_bpl;
541                 pdma_phys_fcp_cmd = psb->dma_handle;
542                 pdma_phys_fcp_rsp = psb->dma_handle + sizeof(struct fcp_cmnd);
543                 pdma_phys_bpl = psb->dma_handle + sizeof(struct fcp_cmnd) +
544                         sizeof(struct fcp_rsp);
545
546                 /*
547                  * The first two bdes are the FCP_CMD and FCP_RSP. The balance
548                  * are sg list bdes.  Initialize the first two and leave the
549                  * rest for queuecommand.
550                  */
551                 bpl[0].addrHigh = le32_to_cpu(putPaddrHigh(pdma_phys_fcp_cmd));
552                 bpl[0].addrLow = le32_to_cpu(putPaddrLow(pdma_phys_fcp_cmd));
553                 bpl[0].tus.f.bdeSize = sizeof(struct fcp_cmnd);
554                 bpl[0].tus.f.bdeFlags = BUFF_TYPE_BDE_64;
555                 bpl[0].tus.w = le32_to_cpu(bpl[0].tus.w);
556
557                 /* Setup the physical region for the FCP RSP */
558                 bpl[1].addrHigh = le32_to_cpu(putPaddrHigh(pdma_phys_fcp_rsp));
559                 bpl[1].addrLow = le32_to_cpu(putPaddrLow(pdma_phys_fcp_rsp));
560                 bpl[1].tus.f.bdeSize = sizeof(struct fcp_rsp);
561                 bpl[1].tus.f.bdeFlags = BUFF_TYPE_BDE_64;
562                 bpl[1].tus.w = le32_to_cpu(bpl[1].tus.w);
563
564                 /*
565                  * Since the IOCB for the FCP I/O is built into this
566                  * lpfc_scsi_buf, initialize it with all known data now.
567                  */
568                 iocb = &psb->cur_iocbq.iocb;
569                 iocb->un.fcpi64.bdl.ulpIoTag32 = 0;
570                 if ((phba->sli_rev == 3) &&
571                                 !(phba->sli3_options & LPFC_SLI3_BG_ENABLED)) {
572                         /* fill in immediate fcp command BDE */
573                         iocb->un.fcpi64.bdl.bdeFlags = BUFF_TYPE_BDE_IMMED;
574                         iocb->un.fcpi64.bdl.bdeSize = sizeof(struct fcp_cmnd);
575                         iocb->un.fcpi64.bdl.addrLow = offsetof(IOCB_t,
576                                         unsli3.fcp_ext.icd);
577                         iocb->un.fcpi64.bdl.addrHigh = 0;
578                         iocb->ulpBdeCount = 0;
579                         iocb->ulpLe = 0;
580                         /* fill in response BDE */
581                         iocb->unsli3.fcp_ext.rbde.tus.f.bdeFlags =
582                                                         BUFF_TYPE_BDE_64;
583                         iocb->unsli3.fcp_ext.rbde.tus.f.bdeSize =
584                                 sizeof(struct fcp_rsp);
585                         iocb->unsli3.fcp_ext.rbde.addrLow =
586                                 putPaddrLow(pdma_phys_fcp_rsp);
587                         iocb->unsli3.fcp_ext.rbde.addrHigh =
588                                 putPaddrHigh(pdma_phys_fcp_rsp);
589                 } else {
590                         iocb->un.fcpi64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
591                         iocb->un.fcpi64.bdl.bdeSize =
592                                         (2 * sizeof(struct ulp_bde64));
593                         iocb->un.fcpi64.bdl.addrLow =
594                                         putPaddrLow(pdma_phys_bpl);
595                         iocb->un.fcpi64.bdl.addrHigh =
596                                         putPaddrHigh(pdma_phys_bpl);
597                         iocb->ulpBdeCount = 1;
598                         iocb->ulpLe = 1;
599                 }
600                 iocb->ulpClass = CLASS3;
601                 psb->status = IOSTAT_SUCCESS;
602                 /* Put it back into the SCSI buffer list */
603                 psb->cur_iocbq.context1  = psb;
604                 lpfc_release_scsi_buf_s3(phba, psb);
605
606         }
607
608         return bcnt;
609 }
610
611 /**
612  * lpfc_sli4_vport_delete_fcp_xri_aborted -Remove all ndlp references for vport
613  * @vport: pointer to lpfc vport data structure.
614  *
615  * This routine is invoked by the vport cleanup for deletions and the cleanup
616  * for an ndlp on removal.
617  **/
618 void
619 lpfc_sli4_vport_delete_fcp_xri_aborted(struct lpfc_vport *vport)
620 {
621         struct lpfc_hba *phba = vport->phba;
622         struct lpfc_scsi_buf *psb, *next_psb;
623         unsigned long iflag = 0;
624
625         spin_lock_irqsave(&phba->hbalock, iflag);
626         spin_lock(&phba->sli4_hba.abts_scsi_buf_list_lock);
627         list_for_each_entry_safe(psb, next_psb,
628                                 &phba->sli4_hba.lpfc_abts_scsi_buf_list, list) {
629                 if (psb->rdata && psb->rdata->pnode
630                         && psb->rdata->pnode->vport == vport)
631                         psb->rdata = NULL;
632         }
633         spin_unlock(&phba->sli4_hba.abts_scsi_buf_list_lock);
634         spin_unlock_irqrestore(&phba->hbalock, iflag);
635 }
636
637 /**
638  * lpfc_sli4_fcp_xri_aborted - Fast-path process of fcp xri abort
639  * @phba: pointer to lpfc hba data structure.
640  * @axri: pointer to the fcp xri abort wcqe structure.
641  *
642  * This routine is invoked by the worker thread to process a SLI4 fast-path
643  * FCP aborted xri.
644  **/
645 void
646 lpfc_sli4_fcp_xri_aborted(struct lpfc_hba *phba,
647                           struct sli4_wcqe_xri_aborted *axri)
648 {
649         uint16_t xri = bf_get(lpfc_wcqe_xa_xri, axri);
650         uint16_t rxid = bf_get(lpfc_wcqe_xa_remote_xid, axri);
651         struct lpfc_scsi_buf *psb, *next_psb;
652         unsigned long iflag = 0;
653         struct lpfc_iocbq *iocbq;
654         int i;
655         struct lpfc_nodelist *ndlp;
656         int rrq_empty = 0;
657         struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
658
659         spin_lock_irqsave(&phba->hbalock, iflag);
660         spin_lock(&phba->sli4_hba.abts_scsi_buf_list_lock);
661         list_for_each_entry_safe(psb, next_psb,
662                 &phba->sli4_hba.lpfc_abts_scsi_buf_list, list) {
663                 if (psb->cur_iocbq.sli4_xritag == xri) {
664                         list_del(&psb->list);
665                         psb->exch_busy = 0;
666                         psb->status = IOSTAT_SUCCESS;
667                         spin_unlock(
668                                 &phba->sli4_hba.abts_scsi_buf_list_lock);
669                         if (psb->rdata && psb->rdata->pnode)
670                                 ndlp = psb->rdata->pnode;
671                         else
672                                 ndlp = NULL;
673
674                         rrq_empty = list_empty(&phba->active_rrq_list);
675                         spin_unlock_irqrestore(&phba->hbalock, iflag);
676                         if (ndlp)
677                                 lpfc_set_rrq_active(phba, ndlp, xri, rxid, 1);
678                         lpfc_release_scsi_buf_s4(phba, psb);
679                         if (rrq_empty)
680                                 lpfc_worker_wake_up(phba);
681                         return;
682                 }
683         }
684         spin_unlock(&phba->sli4_hba.abts_scsi_buf_list_lock);
685         for (i = 1; i <= phba->sli.last_iotag; i++) {
686                 iocbq = phba->sli.iocbq_lookup[i];
687
688                 if (!(iocbq->iocb_flag &  LPFC_IO_FCP) ||
689                         (iocbq->iocb_flag & LPFC_IO_LIBDFC))
690                         continue;
691                 if (iocbq->sli4_xritag != xri)
692                         continue;
693                 psb = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
694                 psb->exch_busy = 0;
695                 spin_unlock_irqrestore(&phba->hbalock, iflag);
696                 if (pring->txq_cnt)
697                         lpfc_worker_wake_up(phba);
698                 return;
699
700         }
701         spin_unlock_irqrestore(&phba->hbalock, iflag);
702 }
703
704 /**
705  * lpfc_sli4_repost_scsi_sgl_list - Repsot the Scsi buffers sgl pages as block
706  * @phba: pointer to lpfc hba data structure.
707  *
708  * This routine walks the list of scsi buffers that have been allocated and
709  * repost them to the HBA by using SGL block post. This is needed after a
710  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
711  * is responsible for moving all scsi buffers on the lpfc_abts_scsi_sgl_list
712  * to the lpfc_scsi_buf_list. If the repost fails, reject all scsi buffers.
713  *
714  * Returns: 0 = success, non-zero failure.
715  **/
716 int
717 lpfc_sli4_repost_scsi_sgl_list(struct lpfc_hba *phba)
718 {
719         struct lpfc_scsi_buf *psb;
720         int index, status, bcnt = 0, rcnt = 0, rc = 0;
721         LIST_HEAD(sblist);
722
723         for (index = 0; index < phba->sli4_hba.scsi_xri_cnt; index++) {
724                 psb = phba->sli4_hba.lpfc_scsi_psb_array[index];
725                 if (psb) {
726                         /* Remove from SCSI buffer list */
727                         list_del(&psb->list);
728                         /* Add it to a local SCSI buffer list */
729                         list_add_tail(&psb->list, &sblist);
730                         if (++rcnt == LPFC_NEMBED_MBOX_SGL_CNT) {
731                                 bcnt = rcnt;
732                                 rcnt = 0;
733                         }
734                 } else
735                         /* A hole present in the XRI array, need to skip */
736                         bcnt = rcnt;
737
738                 if (index == phba->sli4_hba.scsi_xri_cnt - 1)
739                         /* End of XRI array for SCSI buffer, complete */
740                         bcnt = rcnt;
741
742                 /* Continue until collect up to a nembed page worth of sgls */
743                 if (bcnt == 0)
744                         continue;
745                 /* Now, post the SCSI buffer list sgls as a block */
746                 status = lpfc_sli4_post_scsi_sgl_block(phba, &sblist, bcnt);
747                 /* Reset SCSI buffer count for next round of posting */
748                 bcnt = 0;
749                 while (!list_empty(&sblist)) {
750                         list_remove_head(&sblist, psb, struct lpfc_scsi_buf,
751                                          list);
752                         if (status) {
753                                 /* Put this back on the abort scsi list */
754                                 psb->exch_busy = 1;
755                                 rc++;
756                         } else {
757                                 psb->exch_busy = 0;
758                                 psb->status = IOSTAT_SUCCESS;
759                         }
760                         /* Put it back into the SCSI buffer list */
761                         lpfc_release_scsi_buf_s4(phba, psb);
762                 }
763         }
764         return rc;
765 }
766
767 /**
768  * lpfc_new_scsi_buf_s4 - Scsi buffer allocator for HBA with SLI4 IF spec
769  * @vport: The virtual port for which this call being executed.
770  * @num_to_allocate: The requested number of buffers to allocate.
771  *
772  * This routine allocates a scsi buffer for device with SLI-4 interface spec,
773  * the scsi buffer contains all the necessary information needed to initiate
774  * a SCSI I/O.
775  *
776  * Return codes:
777  *   int - number of scsi buffers that were allocated.
778  *   0 = failure, less than num_to_alloc is a partial failure.
779  **/
780 static int
781 lpfc_new_scsi_buf_s4(struct lpfc_vport *vport, int num_to_alloc)
782 {
783         struct lpfc_hba *phba = vport->phba;
784         struct lpfc_scsi_buf *psb;
785         struct sli4_sge *sgl;
786         IOCB_t *iocb;
787         dma_addr_t pdma_phys_fcp_cmd;
788         dma_addr_t pdma_phys_fcp_rsp;
789         dma_addr_t pdma_phys_bpl, pdma_phys_bpl1;
790         uint16_t iotag, last_xritag = NO_XRI;
791         int status = 0, index;
792         int bcnt;
793         int non_sequential_xri = 0;
794         LIST_HEAD(sblist);
795
796         for (bcnt = 0; bcnt < num_to_alloc; bcnt++) {
797                 psb = kzalloc(sizeof(struct lpfc_scsi_buf), GFP_KERNEL);
798                 if (!psb)
799                         break;
800
801                 /*
802                  * Get memory from the pci pool to map the virt space to pci bus
803                  * space for an I/O.  The DMA buffer includes space for the
804                  * struct fcp_cmnd, struct fcp_rsp and the number of bde's
805                  * necessary to support the sg_tablesize.
806                  */
807                 psb->data = pci_pool_alloc(phba->lpfc_scsi_dma_buf_pool,
808                                                 GFP_KERNEL, &psb->dma_handle);
809                 if (!psb->data) {
810                         kfree(psb);
811                         break;
812                 }
813
814                 /* Initialize virtual ptrs to dma_buf region. */
815                 memset(psb->data, 0, phba->cfg_sg_dma_buf_size);
816
817                 /* Allocate iotag for psb->cur_iocbq. */
818                 iotag = lpfc_sli_next_iotag(phba, &psb->cur_iocbq);
819                 if (iotag == 0) {
820                         pci_pool_free(phba->lpfc_scsi_dma_buf_pool,
821                                 psb->data, psb->dma_handle);
822                         kfree(psb);
823                         break;
824                 }
825
826                 psb->cur_iocbq.sli4_xritag = lpfc_sli4_next_xritag(phba);
827                 if (psb->cur_iocbq.sli4_xritag == NO_XRI) {
828                         pci_pool_free(phba->lpfc_scsi_dma_buf_pool,
829                               psb->data, psb->dma_handle);
830                         kfree(psb);
831                         break;
832                 }
833                 if (last_xritag != NO_XRI
834                         && psb->cur_iocbq.sli4_xritag != (last_xritag+1)) {
835                         non_sequential_xri = 1;
836                 } else
837                         list_add_tail(&psb->list, &sblist);
838                 last_xritag = psb->cur_iocbq.sli4_xritag;
839
840                 index = phba->sli4_hba.scsi_xri_cnt++;
841                 psb->cur_iocbq.iocb_flag |= LPFC_IO_FCP;
842
843                 psb->fcp_bpl = psb->data;
844                 psb->fcp_cmnd = (psb->data + phba->cfg_sg_dma_buf_size)
845                         - (sizeof(struct fcp_cmnd) + sizeof(struct fcp_rsp));
846                 psb->fcp_rsp = (struct fcp_rsp *)((uint8_t *)psb->fcp_cmnd +
847                                         sizeof(struct fcp_cmnd));
848
849                 /* Initialize local short-hand pointers. */
850                 sgl = (struct sli4_sge *)psb->fcp_bpl;
851                 pdma_phys_bpl = psb->dma_handle;
852                 pdma_phys_fcp_cmd =
853                         (psb->dma_handle + phba->cfg_sg_dma_buf_size)
854                          - (sizeof(struct fcp_cmnd) + sizeof(struct fcp_rsp));
855                 pdma_phys_fcp_rsp = pdma_phys_fcp_cmd + sizeof(struct fcp_cmnd);
856
857                 /*
858                  * The first two bdes are the FCP_CMD and FCP_RSP.  The balance
859                  * are sg list bdes.  Initialize the first two and leave the
860                  * rest for queuecommand.
861                  */
862                 sgl->addr_hi = cpu_to_le32(putPaddrHigh(pdma_phys_fcp_cmd));
863                 sgl->addr_lo = cpu_to_le32(putPaddrLow(pdma_phys_fcp_cmd));
864                 sgl->word2 = le32_to_cpu(sgl->word2);
865                 bf_set(lpfc_sli4_sge_last, sgl, 0);
866                 sgl->word2 = cpu_to_le32(sgl->word2);
867                 sgl->sge_len = cpu_to_le32(sizeof(struct fcp_cmnd));
868                 sgl++;
869
870                 /* Setup the physical region for the FCP RSP */
871                 sgl->addr_hi = cpu_to_le32(putPaddrHigh(pdma_phys_fcp_rsp));
872                 sgl->addr_lo = cpu_to_le32(putPaddrLow(pdma_phys_fcp_rsp));
873                 sgl->word2 = le32_to_cpu(sgl->word2);
874                 bf_set(lpfc_sli4_sge_last, sgl, 1);
875                 sgl->word2 = cpu_to_le32(sgl->word2);
876                 sgl->sge_len = cpu_to_le32(sizeof(struct fcp_rsp));
877
878                 /*
879                  * Since the IOCB for the FCP I/O is built into this
880                  * lpfc_scsi_buf, initialize it with all known data now.
881                  */
882                 iocb = &psb->cur_iocbq.iocb;
883                 iocb->un.fcpi64.bdl.ulpIoTag32 = 0;
884                 iocb->un.fcpi64.bdl.bdeFlags = BUFF_TYPE_BDE_64;
885                 /* setting the BLP size to 2 * sizeof BDE may not be correct.
886                  * We are setting the bpl to point to out sgl. An sgl's
887                  * entries are 16 bytes, a bpl entries are 12 bytes.
888                  */
889                 iocb->un.fcpi64.bdl.bdeSize = sizeof(struct fcp_cmnd);
890                 iocb->un.fcpi64.bdl.addrLow = putPaddrLow(pdma_phys_fcp_cmd);
891                 iocb->un.fcpi64.bdl.addrHigh = putPaddrHigh(pdma_phys_fcp_cmd);
892                 iocb->ulpBdeCount = 1;
893                 iocb->ulpLe = 1;
894                 iocb->ulpClass = CLASS3;
895                 psb->cur_iocbq.context1  = psb;
896                 if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
897                         pdma_phys_bpl1 = pdma_phys_bpl + SGL_PAGE_SIZE;
898                 else
899                         pdma_phys_bpl1 = 0;
900                 psb->dma_phys_bpl = pdma_phys_bpl;
901                 phba->sli4_hba.lpfc_scsi_psb_array[index] = psb;
902                 if (non_sequential_xri) {
903                         status = lpfc_sli4_post_sgl(phba, pdma_phys_bpl,
904                                                 pdma_phys_bpl1,
905                                                 psb->cur_iocbq.sli4_xritag);
906                         if (status) {
907                                 /* Put this back on the abort scsi list */
908                                 psb->exch_busy = 1;
909                         } else {
910                                 psb->exch_busy = 0;
911                                 psb->status = IOSTAT_SUCCESS;
912                         }
913                         /* Put it back into the SCSI buffer list */
914                         lpfc_release_scsi_buf_s4(phba, psb);
915                         break;
916                 }
917         }
918         if (bcnt) {
919                 status = lpfc_sli4_post_scsi_sgl_block(phba, &sblist, bcnt);
920                 /* Reset SCSI buffer count for next round of posting */
921                 while (!list_empty(&sblist)) {
922                         list_remove_head(&sblist, psb, struct lpfc_scsi_buf,
923                                  list);
924                         if (status) {
925                                 /* Put this back on the abort scsi list */
926                                 psb->exch_busy = 1;
927                         } else {
928                                 psb->exch_busy = 0;
929                                 psb->status = IOSTAT_SUCCESS;
930                         }
931                         /* Put it back into the SCSI buffer list */
932                         lpfc_release_scsi_buf_s4(phba, psb);
933                 }
934         }
935
936         return bcnt + non_sequential_xri;
937 }
938
939 /**
940  * lpfc_new_scsi_buf - Wrapper funciton for scsi buffer allocator
941  * @vport: The virtual port for which this call being executed.
942  * @num_to_allocate: The requested number of buffers to allocate.
943  *
944  * This routine wraps the actual SCSI buffer allocator function pointer from
945  * the lpfc_hba struct.
946  *
947  * Return codes:
948  *   int - number of scsi buffers that were allocated.
949  *   0 = failure, less than num_to_alloc is a partial failure.
950  **/
951 static inline int
952 lpfc_new_scsi_buf(struct lpfc_vport *vport, int num_to_alloc)
953 {
954         return vport->phba->lpfc_new_scsi_buf(vport, num_to_alloc);
955 }
956
957 /**
958  * lpfc_get_scsi_buf_s3 - Get a scsi buffer from lpfc_scsi_buf_list of the HBA
959  * @phba: The HBA for which this call is being executed.
960  *
961  * This routine removes a scsi buffer from head of @phba lpfc_scsi_buf_list list
962  * and returns to caller.
963  *
964  * Return codes:
965  *   NULL - Error
966  *   Pointer to lpfc_scsi_buf - Success
967  **/
968 static struct lpfc_scsi_buf*
969 lpfc_get_scsi_buf_s3(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp)
970 {
971         struct  lpfc_scsi_buf * lpfc_cmd = NULL;
972         struct list_head *scsi_buf_list = &phba->lpfc_scsi_buf_list;
973         unsigned long iflag = 0;
974
975         spin_lock_irqsave(&phba->scsi_buf_list_lock, iflag);
976         list_remove_head(scsi_buf_list, lpfc_cmd, struct lpfc_scsi_buf, list);
977         if (lpfc_cmd) {
978                 lpfc_cmd->seg_cnt = 0;
979                 lpfc_cmd->nonsg_phys = 0;
980                 lpfc_cmd->prot_seg_cnt = 0;
981         }
982         spin_unlock_irqrestore(&phba->scsi_buf_list_lock, iflag);
983         return  lpfc_cmd;
984 }
985 /**
986  * lpfc_get_scsi_buf_s4 - Get a scsi buffer from lpfc_scsi_buf_list of the HBA
987  * @phba: The HBA for which this call is being executed.
988  *
989  * This routine removes a scsi buffer from head of @phba lpfc_scsi_buf_list list
990  * and returns to caller.
991  *
992  * Return codes:
993  *   NULL - Error
994  *   Pointer to lpfc_scsi_buf - Success
995  **/
996 static struct lpfc_scsi_buf*
997 lpfc_get_scsi_buf_s4(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp)
998 {
999         struct lpfc_scsi_buf *lpfc_cmd ;
1000         unsigned long iflag = 0;
1001         int found = 0;
1002
1003         spin_lock_irqsave(&phba->scsi_buf_list_lock, iflag);
1004         list_for_each_entry(lpfc_cmd, &phba->lpfc_scsi_buf_list,
1005                                                         list) {
1006                 if (lpfc_test_rrq_active(phba, ndlp,
1007                                          lpfc_cmd->cur_iocbq.sli4_xritag))
1008                         continue;
1009                 list_del(&lpfc_cmd->list);
1010                 found = 1;
1011                 lpfc_cmd->seg_cnt = 0;
1012                 lpfc_cmd->nonsg_phys = 0;
1013                 lpfc_cmd->prot_seg_cnt = 0;
1014                 break;
1015         }
1016         spin_unlock_irqrestore(&phba->scsi_buf_list_lock,
1017                                                  iflag);
1018         if (!found)
1019                 return NULL;
1020         else
1021                 return  lpfc_cmd;
1022 }
1023 /**
1024  * lpfc_get_scsi_buf - Get a scsi buffer from lpfc_scsi_buf_list of the HBA
1025  * @phba: The HBA for which this call is being executed.
1026  *
1027  * This routine removes a scsi buffer from head of @phba lpfc_scsi_buf_list list
1028  * and returns to caller.
1029  *
1030  * Return codes:
1031  *   NULL - Error
1032  *   Pointer to lpfc_scsi_buf - Success
1033  **/
1034 static struct lpfc_scsi_buf*
1035 lpfc_get_scsi_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp)
1036 {
1037         return  phba->lpfc_get_scsi_buf(phba, ndlp);
1038 }
1039
1040 /**
1041  * lpfc_release_scsi_buf - Return a scsi buffer back to hba scsi buf list
1042  * @phba: The Hba for which this call is being executed.
1043  * @psb: The scsi buffer which is being released.
1044  *
1045  * This routine releases @psb scsi buffer by adding it to tail of @phba
1046  * lpfc_scsi_buf_list list.
1047  **/
1048 static void
1049 lpfc_release_scsi_buf_s3(struct lpfc_hba *phba, struct lpfc_scsi_buf *psb)
1050 {
1051         unsigned long iflag = 0;
1052
1053         spin_lock_irqsave(&phba->scsi_buf_list_lock, iflag);
1054         psb->pCmd = NULL;
1055         list_add_tail(&psb->list, &phba->lpfc_scsi_buf_list);
1056         spin_unlock_irqrestore(&phba->scsi_buf_list_lock, iflag);
1057 }
1058
1059 /**
1060  * lpfc_release_scsi_buf_s4: Return a scsi buffer back to hba scsi buf list.
1061  * @phba: The Hba for which this call is being executed.
1062  * @psb: The scsi buffer which is being released.
1063  *
1064  * This routine releases @psb scsi buffer by adding it to tail of @phba
1065  * lpfc_scsi_buf_list list. For SLI4 XRI's are tied to the scsi buffer
1066  * and cannot be reused for at least RA_TOV amount of time if it was
1067  * aborted.
1068  **/
1069 static void
1070 lpfc_release_scsi_buf_s4(struct lpfc_hba *phba, struct lpfc_scsi_buf *psb)
1071 {
1072         unsigned long iflag = 0;
1073
1074         if (psb->exch_busy) {
1075                 spin_lock_irqsave(&phba->sli4_hba.abts_scsi_buf_list_lock,
1076                                         iflag);
1077                 psb->pCmd = NULL;
1078                 list_add_tail(&psb->list,
1079                         &phba->sli4_hba.lpfc_abts_scsi_buf_list);
1080                 spin_unlock_irqrestore(&phba->sli4_hba.abts_scsi_buf_list_lock,
1081                                         iflag);
1082         } else {
1083
1084                 spin_lock_irqsave(&phba->scsi_buf_list_lock, iflag);
1085                 psb->pCmd = NULL;
1086                 list_add_tail(&psb->list, &phba->lpfc_scsi_buf_list);
1087                 spin_unlock_irqrestore(&phba->scsi_buf_list_lock, iflag);
1088         }
1089 }
1090
1091 /**
1092  * lpfc_release_scsi_buf: Return a scsi buffer back to hba scsi buf list.
1093  * @phba: The Hba for which this call is being executed.
1094  * @psb: The scsi buffer which is being released.
1095  *
1096  * This routine releases @psb scsi buffer by adding it to tail of @phba
1097  * lpfc_scsi_buf_list list.
1098  **/
1099 static void
1100 lpfc_release_scsi_buf(struct lpfc_hba *phba, struct lpfc_scsi_buf *psb)
1101 {
1102
1103         phba->lpfc_release_scsi_buf(phba, psb);
1104 }
1105
1106 /**
1107  * lpfc_scsi_prep_dma_buf_s3 - DMA mapping for scsi buffer to SLI3 IF spec
1108  * @phba: The Hba for which this call is being executed.
1109  * @lpfc_cmd: The scsi buffer which is going to be mapped.
1110  *
1111  * This routine does the pci dma mapping for scatter-gather list of scsi cmnd
1112  * field of @lpfc_cmd for device with SLI-3 interface spec. This routine scans
1113  * through sg elements and format the bdea. This routine also initializes all
1114  * IOCB fields which are dependent on scsi command request buffer.
1115  *
1116  * Return codes:
1117  *   1 - Error
1118  *   0 - Success
1119  **/
1120 static int
1121 lpfc_scsi_prep_dma_buf_s3(struct lpfc_hba *phba, struct lpfc_scsi_buf *lpfc_cmd)
1122 {
1123         struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
1124         struct scatterlist *sgel = NULL;
1125         struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
1126         struct ulp_bde64 *bpl = lpfc_cmd->fcp_bpl;
1127         struct lpfc_iocbq *iocbq = &lpfc_cmd->cur_iocbq;
1128         IOCB_t *iocb_cmd = &lpfc_cmd->cur_iocbq.iocb;
1129         struct ulp_bde64 *data_bde = iocb_cmd->unsli3.fcp_ext.dbde;
1130         dma_addr_t physaddr;
1131         uint32_t num_bde = 0;
1132         int nseg, datadir = scsi_cmnd->sc_data_direction;
1133
1134         /*
1135          * There are three possibilities here - use scatter-gather segment, use
1136          * the single mapping, or neither.  Start the lpfc command prep by
1137          * bumping the bpl beyond the fcp_cmnd and fcp_rsp regions to the first
1138          * data bde entry.
1139          */
1140         bpl += 2;
1141         if (scsi_sg_count(scsi_cmnd)) {
1142                 /*
1143                  * The driver stores the segment count returned from pci_map_sg
1144                  * because this a count of dma-mappings used to map the use_sg
1145                  * pages.  They are not guaranteed to be the same for those
1146                  * architectures that implement an IOMMU.
1147                  */
1148
1149                 nseg = dma_map_sg(&phba->pcidev->dev, scsi_sglist(scsi_cmnd),
1150                                   scsi_sg_count(scsi_cmnd), datadir);
1151                 if (unlikely(!nseg))
1152                         return 1;
1153
1154                 lpfc_cmd->seg_cnt = nseg;
1155                 if (lpfc_cmd->seg_cnt > phba->cfg_sg_seg_cnt) {
1156                         lpfc_printf_log(phba, KERN_ERR, LOG_BG,
1157                                 "9064 BLKGRD: %s: Too many sg segments from "
1158                                "dma_map_sg.  Config %d, seg_cnt %d\n",
1159                                __func__, phba->cfg_sg_seg_cnt,
1160                                lpfc_cmd->seg_cnt);
1161                         scsi_dma_unmap(scsi_cmnd);
1162                         return 1;
1163                 }
1164
1165                 /*
1166                  * The driver established a maximum scatter-gather segment count
1167                  * during probe that limits the number of sg elements in any
1168                  * single scsi command.  Just run through the seg_cnt and format
1169                  * the bde's.
1170                  * When using SLI-3 the driver will try to fit all the BDEs into
1171                  * the IOCB. If it can't then the BDEs get added to a BPL as it
1172                  * does for SLI-2 mode.
1173                  */
1174                 scsi_for_each_sg(scsi_cmnd, sgel, nseg, num_bde) {
1175                         physaddr = sg_dma_address(sgel);
1176                         if (phba->sli_rev == 3 &&
1177                             !(phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
1178                             !(iocbq->iocb_flag & DSS_SECURITY_OP) &&
1179                             nseg <= LPFC_EXT_DATA_BDE_COUNT) {
1180                                 data_bde->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
1181                                 data_bde->tus.f.bdeSize = sg_dma_len(sgel);
1182                                 data_bde->addrLow = putPaddrLow(physaddr);
1183                                 data_bde->addrHigh = putPaddrHigh(physaddr);
1184                                 data_bde++;
1185                         } else {
1186                                 bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
1187                                 bpl->tus.f.bdeSize = sg_dma_len(sgel);
1188                                 bpl->tus.w = le32_to_cpu(bpl->tus.w);
1189                                 bpl->addrLow =
1190                                         le32_to_cpu(putPaddrLow(physaddr));
1191                                 bpl->addrHigh =
1192                                         le32_to_cpu(putPaddrHigh(physaddr));
1193                                 bpl++;
1194                         }
1195                 }
1196         }
1197
1198         /*
1199          * Finish initializing those IOCB fields that are dependent on the
1200          * scsi_cmnd request_buffer.  Note that for SLI-2 the bdeSize is
1201          * explicitly reinitialized and for SLI-3 the extended bde count is
1202          * explicitly reinitialized since all iocb memory resources are reused.
1203          */
1204         if (phba->sli_rev == 3 &&
1205             !(phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
1206             !(iocbq->iocb_flag & DSS_SECURITY_OP)) {
1207                 if (num_bde > LPFC_EXT_DATA_BDE_COUNT) {
1208                         /*
1209                          * The extended IOCB format can only fit 3 BDE or a BPL.
1210                          * This I/O has more than 3 BDE so the 1st data bde will
1211                          * be a BPL that is filled in here.
1212                          */
1213                         physaddr = lpfc_cmd->dma_handle;
1214                         data_bde->tus.f.bdeFlags = BUFF_TYPE_BLP_64;
1215                         data_bde->tus.f.bdeSize = (num_bde *
1216                                                    sizeof(struct ulp_bde64));
1217                         physaddr += (sizeof(struct fcp_cmnd) +
1218                                      sizeof(struct fcp_rsp) +
1219                                      (2 * sizeof(struct ulp_bde64)));
1220                         data_bde->addrHigh = putPaddrHigh(physaddr);
1221                         data_bde->addrLow = putPaddrLow(physaddr);
1222                         /* ebde count includes the response bde and data bpl */
1223                         iocb_cmd->unsli3.fcp_ext.ebde_count = 2;
1224                 } else {
1225                         /* ebde count includes the response bde and data bdes */
1226                         iocb_cmd->unsli3.fcp_ext.ebde_count = (num_bde + 1);
1227                 }
1228         } else {
1229                 iocb_cmd->un.fcpi64.bdl.bdeSize =
1230                         ((num_bde + 2) * sizeof(struct ulp_bde64));
1231                 iocb_cmd->unsli3.fcp_ext.ebde_count = (num_bde + 1);
1232         }
1233         fcp_cmnd->fcpDl = cpu_to_be32(scsi_bufflen(scsi_cmnd));
1234
1235         /*
1236          * Due to difference in data length between DIF/non-DIF paths,
1237          * we need to set word 4 of IOCB here
1238          */
1239         iocb_cmd->un.fcpi.fcpi_parm = scsi_bufflen(scsi_cmnd);
1240         return 0;
1241 }
1242
1243 /*
1244  * Given a scsi cmnd, determine the BlockGuard opcodes to be used with it
1245  * @sc: The SCSI command to examine
1246  * @txopt: (out) BlockGuard operation for transmitted data
1247  * @rxopt: (out) BlockGuard operation for received data
1248  *
1249  * Returns: zero on success; non-zero if tx and/or rx op cannot be determined
1250  *
1251  */
1252 static int
1253 lpfc_sc_to_bg_opcodes(struct lpfc_hba *phba, struct scsi_cmnd *sc,
1254                 uint8_t *txop, uint8_t *rxop)
1255 {
1256         uint8_t guard_type = scsi_host_get_guard(sc->device->host);
1257         uint8_t ret = 0;
1258
1259         if (guard_type == SHOST_DIX_GUARD_IP) {
1260                 switch (scsi_get_prot_op(sc)) {
1261                 case SCSI_PROT_READ_INSERT:
1262                 case SCSI_PROT_WRITE_STRIP:
1263                         *txop = BG_OP_IN_CSUM_OUT_NODIF;
1264                         *rxop = BG_OP_IN_NODIF_OUT_CSUM;
1265                         break;
1266
1267                 case SCSI_PROT_READ_STRIP:
1268                 case SCSI_PROT_WRITE_INSERT:
1269                         *txop = BG_OP_IN_NODIF_OUT_CRC;
1270                         *rxop = BG_OP_IN_CRC_OUT_NODIF;
1271                         break;
1272
1273                 case SCSI_PROT_READ_PASS:
1274                 case SCSI_PROT_WRITE_PASS:
1275                         *txop = BG_OP_IN_CSUM_OUT_CRC;
1276                         *rxop = BG_OP_IN_CRC_OUT_CSUM;
1277                         break;
1278
1279                 case SCSI_PROT_NORMAL:
1280                 default:
1281                         lpfc_printf_log(phba, KERN_ERR, LOG_BG,
1282                                 "9063 BLKGRD: Bad op/guard:%d/%d combination\n",
1283                                         scsi_get_prot_op(sc), guard_type);
1284                         ret = 1;
1285                         break;
1286
1287                 }
1288         } else if (guard_type == SHOST_DIX_GUARD_CRC) {
1289                 switch (scsi_get_prot_op(sc)) {
1290                 case SCSI_PROT_READ_STRIP:
1291                 case SCSI_PROT_WRITE_INSERT:
1292                         *txop = BG_OP_IN_NODIF_OUT_CRC;
1293                         *rxop = BG_OP_IN_CRC_OUT_NODIF;
1294                         break;
1295
1296                 case SCSI_PROT_READ_PASS:
1297                 case SCSI_PROT_WRITE_PASS:
1298                         *txop = BG_OP_IN_CRC_OUT_CRC;
1299                         *rxop = BG_OP_IN_CRC_OUT_CRC;
1300                         break;
1301
1302                 case SCSI_PROT_READ_INSERT:
1303                 case SCSI_PROT_WRITE_STRIP:
1304                 case SCSI_PROT_NORMAL:
1305                 default:
1306                         lpfc_printf_log(phba, KERN_ERR, LOG_BG,
1307                                 "9075 BLKGRD: Bad op/guard:%d/%d combination\n",
1308                                         scsi_get_prot_op(sc), guard_type);
1309                         ret = 1;
1310                         break;
1311                 }
1312         } else {
1313                 /* unsupported format */
1314                 BUG();
1315         }
1316
1317         return ret;
1318 }
1319
1320 struct scsi_dif_tuple {
1321         __be16 guard_tag;       /* Checksum */
1322         __be16 app_tag;         /* Opaque storage */
1323         __be32 ref_tag;         /* Target LBA or indirect LBA */
1324 };
1325
1326 static inline unsigned
1327 lpfc_cmd_blksize(struct scsi_cmnd *sc)
1328 {
1329         return sc->device->sector_size;
1330 }
1331
1332 /**
1333  * lpfc_get_cmd_dif_parms - Extract DIF parameters from SCSI command
1334  * @sc:             in: SCSI command
1335  * @apptagmask:     out: app tag mask
1336  * @apptagval:      out: app tag value
1337  * @reftag:         out: ref tag (reference tag)
1338  *
1339  * Description:
1340  *   Extract DIF parameters from the command if possible.  Otherwise,
1341  *   use default parameters.
1342  *
1343  **/
1344 static inline void
1345 lpfc_get_cmd_dif_parms(struct scsi_cmnd *sc, uint16_t *apptagmask,
1346                 uint16_t *apptagval, uint32_t *reftag)
1347 {
1348         struct  scsi_dif_tuple *spt;
1349         unsigned char op = scsi_get_prot_op(sc);
1350         unsigned int protcnt = scsi_prot_sg_count(sc);
1351         static int cnt;
1352
1353         if (protcnt && (op == SCSI_PROT_WRITE_STRIP ||
1354                                 op == SCSI_PROT_WRITE_PASS)) {
1355
1356                 cnt++;
1357                 spt = page_address(sg_page(scsi_prot_sglist(sc))) +
1358                         scsi_prot_sglist(sc)[0].offset;
1359                 *apptagmask = 0;
1360                 *apptagval = 0;
1361                 *reftag = cpu_to_be32(spt->ref_tag);
1362
1363         } else {
1364                 /* SBC defines ref tag to be lower 32bits of LBA */
1365                 *reftag = (uint32_t) (0xffffffff & scsi_get_lba(sc));
1366                 *apptagmask = 0;
1367                 *apptagval = 0;
1368         }
1369 }
1370
1371 /*
1372  * This function sets up buffer list for protection groups of
1373  * type LPFC_PG_TYPE_NO_DIF
1374  *
1375  * This is usually used when the HBA is instructed to generate
1376  * DIFs and insert them into data stream (or strip DIF from
1377  * incoming data stream)
1378  *
1379  * The buffer list consists of just one protection group described
1380  * below:
1381  *                                +-------------------------+
1382  *   start of prot group  -->     |          PDE_5          |
1383  *                                +-------------------------+
1384  *                                |          PDE_6          |
1385  *                                +-------------------------+
1386  *                                |         Data BDE        |
1387  *                                +-------------------------+
1388  *                                |more Data BDE's ... (opt)|
1389  *                                +-------------------------+
1390  *
1391  * @sc: pointer to scsi command we're working on
1392  * @bpl: pointer to buffer list for protection groups
1393  * @datacnt: number of segments of data that have been dma mapped
1394  *
1395  * Note: Data s/g buffers have been dma mapped
1396  */
1397 static int
1398 lpfc_bg_setup_bpl(struct lpfc_hba *phba, struct scsi_cmnd *sc,
1399                 struct ulp_bde64 *bpl, int datasegcnt)
1400 {
1401         struct scatterlist *sgde = NULL; /* s/g data entry */
1402         struct lpfc_pde5 *pde5 = NULL;
1403         struct lpfc_pde6 *pde6 = NULL;
1404         dma_addr_t physaddr;
1405         int i = 0, num_bde = 0, status;
1406         int datadir = sc->sc_data_direction;
1407         unsigned blksize;
1408         uint32_t reftag;
1409         uint16_t apptagmask, apptagval;
1410         uint8_t txop, rxop;
1411
1412         status  = lpfc_sc_to_bg_opcodes(phba, sc, &txop, &rxop);
1413         if (status)
1414                 goto out;
1415
1416         /* extract some info from the scsi command for pde*/
1417         blksize = lpfc_cmd_blksize(sc);
1418         lpfc_get_cmd_dif_parms(sc, &apptagmask, &apptagval, &reftag);
1419
1420         /* setup PDE5 with what we have */
1421         pde5 = (struct lpfc_pde5 *) bpl;
1422         memset(pde5, 0, sizeof(struct lpfc_pde5));
1423         bf_set(pde5_type, pde5, LPFC_PDE5_DESCRIPTOR);
1424         pde5->reftag = reftag;
1425
1426         /* Endianness conversion if necessary for PDE5 */
1427         pde5->word0 = cpu_to_le32(pde5->word0);
1428         pde5->reftag = cpu_to_le32(pde5->reftag);
1429
1430         /* advance bpl and increment bde count */
1431         num_bde++;
1432         bpl++;
1433         pde6 = (struct lpfc_pde6 *) bpl;
1434
1435         /* setup PDE6 with the rest of the info */
1436         memset(pde6, 0, sizeof(struct lpfc_pde6));
1437         bf_set(pde6_type, pde6, LPFC_PDE6_DESCRIPTOR);
1438         bf_set(pde6_optx, pde6, txop);
1439         bf_set(pde6_oprx, pde6, rxop);
1440         if (datadir == DMA_FROM_DEVICE) {
1441                 bf_set(pde6_ce, pde6, 1);
1442                 bf_set(pde6_re, pde6, 1);
1443                 bf_set(pde6_ae, pde6, 1);
1444         }
1445         bf_set(pde6_ai, pde6, 1);
1446         bf_set(pde6_apptagval, pde6, apptagval);
1447
1448         /* Endianness conversion if necessary for PDE6 */
1449         pde6->word0 = cpu_to_le32(pde6->word0);
1450         pde6->word1 = cpu_to_le32(pde6->word1);
1451         pde6->word2 = cpu_to_le32(pde6->word2);
1452
1453         /* advance bpl and increment bde count */
1454         num_bde++;
1455         bpl++;
1456
1457         /* assumption: caller has already run dma_map_sg on command data */
1458         scsi_for_each_sg(sc, sgde, datasegcnt, i) {
1459                 physaddr = sg_dma_address(sgde);
1460                 bpl->addrLow = le32_to_cpu(putPaddrLow(physaddr));
1461                 bpl->addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
1462                 bpl->tus.f.bdeSize = sg_dma_len(sgde);
1463                 if (datadir == DMA_TO_DEVICE)
1464                         bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
1465                 else
1466                         bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
1467                 bpl->tus.w = le32_to_cpu(bpl->tus.w);
1468                 bpl++;
1469                 num_bde++;
1470         }
1471
1472 out:
1473         return num_bde;
1474 }
1475
1476 /*
1477  * This function sets up buffer list for protection groups of
1478  * type LPFC_PG_TYPE_DIF_BUF
1479  *
1480  * This is usually used when DIFs are in their own buffers,
1481  * separate from the data. The HBA can then by instructed
1482  * to place the DIFs in the outgoing stream.  For read operations,
1483  * The HBA could extract the DIFs and place it in DIF buffers.
1484  *
1485  * The buffer list for this type consists of one or more of the
1486  * protection groups described below:
1487  *                                    +-------------------------+
1488  *   start of first prot group  -->   |          PDE_5          |
1489  *                                    +-------------------------+
1490  *                                    |          PDE_6          |
1491  *                                    +-------------------------+
1492  *                                    |      PDE_7 (Prot BDE)   |
1493  *                                    +-------------------------+
1494  *                                    |        Data BDE         |
1495  *                                    +-------------------------+
1496  *                                    |more Data BDE's ... (opt)|
1497  *                                    +-------------------------+
1498  *   start of new  prot group  -->    |          PDE_5          |
1499  *                                    +-------------------------+
1500  *                                    |          ...            |
1501  *                                    +-------------------------+
1502  *
1503  * @sc: pointer to scsi command we're working on
1504  * @bpl: pointer to buffer list for protection groups
1505  * @datacnt: number of segments of data that have been dma mapped
1506  * @protcnt: number of segment of protection data that have been dma mapped
1507  *
1508  * Note: It is assumed that both data and protection s/g buffers have been
1509  *       mapped for DMA
1510  */
1511 static int
1512 lpfc_bg_setup_bpl_prot(struct lpfc_hba *phba, struct scsi_cmnd *sc,
1513                 struct ulp_bde64 *bpl, int datacnt, int protcnt)
1514 {
1515         struct scatterlist *sgde = NULL; /* s/g data entry */
1516         struct scatterlist *sgpe = NULL; /* s/g prot entry */
1517         struct lpfc_pde5 *pde5 = NULL;
1518         struct lpfc_pde6 *pde6 = NULL;
1519         struct lpfc_pde7 *pde7 = NULL;
1520         dma_addr_t dataphysaddr, protphysaddr;
1521         unsigned short curr_data = 0, curr_prot = 0;
1522         unsigned int split_offset;
1523         unsigned int protgroup_len, protgroup_offset = 0, protgroup_remainder;
1524         unsigned int protgrp_blks, protgrp_bytes;
1525         unsigned int remainder, subtotal;
1526         int status;
1527         int datadir = sc->sc_data_direction;
1528         unsigned char pgdone = 0, alldone = 0;
1529         unsigned blksize;
1530         uint32_t reftag;
1531         uint16_t apptagmask, apptagval;
1532         uint8_t txop, rxop;
1533         int num_bde = 0;
1534
1535         sgpe = scsi_prot_sglist(sc);
1536         sgde = scsi_sglist(sc);
1537
1538         if (!sgpe || !sgde) {
1539                 lpfc_printf_log(phba, KERN_ERR, LOG_FCP,
1540                                 "9020 Invalid s/g entry: data=0x%p prot=0x%p\n",
1541                                 sgpe, sgde);
1542                 return 0;
1543         }
1544
1545         status = lpfc_sc_to_bg_opcodes(phba, sc, &txop, &rxop);
1546         if (status)
1547                 goto out;
1548
1549         /* extract some info from the scsi command */
1550         blksize = lpfc_cmd_blksize(sc);
1551         lpfc_get_cmd_dif_parms(sc, &apptagmask, &apptagval, &reftag);
1552
1553         split_offset = 0;
1554         do {
1555                 /* setup PDE5 with what we have */
1556                 pde5 = (struct lpfc_pde5 *) bpl;
1557                 memset(pde5, 0, sizeof(struct lpfc_pde5));
1558                 bf_set(pde5_type, pde5, LPFC_PDE5_DESCRIPTOR);
1559                 pde5->reftag = reftag;
1560
1561                 /* Endianness conversion if necessary for PDE5 */
1562                 pde5->word0 = cpu_to_le32(pde5->word0);
1563                 pde5->reftag = cpu_to_le32(pde5->reftag);
1564
1565                 /* advance bpl and increment bde count */
1566                 num_bde++;
1567                 bpl++;
1568                 pde6 = (struct lpfc_pde6 *) bpl;
1569
1570                 /* setup PDE6 with the rest of the info */
1571                 memset(pde6, 0, sizeof(struct lpfc_pde6));
1572                 bf_set(pde6_type, pde6, LPFC_PDE6_DESCRIPTOR);
1573                 bf_set(pde6_optx, pde6, txop);
1574                 bf_set(pde6_oprx, pde6, rxop);
1575                 bf_set(pde6_ce, pde6, 1);
1576                 bf_set(pde6_re, pde6, 1);
1577                 bf_set(pde6_ae, pde6, 1);
1578                 bf_set(pde6_ai, pde6, 1);
1579                 bf_set(pde6_apptagval, pde6, apptagval);
1580
1581                 /* Endianness conversion if necessary for PDE6 */
1582                 pde6->word0 = cpu_to_le32(pde6->word0);
1583                 pde6->word1 = cpu_to_le32(pde6->word1);
1584                 pde6->word2 = cpu_to_le32(pde6->word2);
1585
1586                 /* advance bpl and increment bde count */
1587                 num_bde++;
1588                 bpl++;
1589
1590                 /* setup the first BDE that points to protection buffer */
1591                 protphysaddr = sg_dma_address(sgpe) + protgroup_offset;
1592                 protgroup_len = sg_dma_len(sgpe) - protgroup_offset;
1593
1594                 /* must be integer multiple of the DIF block length */
1595                 BUG_ON(protgroup_len % 8);
1596
1597                 pde7 = (struct lpfc_pde7 *) bpl;
1598                 memset(pde7, 0, sizeof(struct lpfc_pde7));
1599                 bf_set(pde7_type, pde7, LPFC_PDE7_DESCRIPTOR);
1600
1601                 pde7->addrHigh = le32_to_cpu(putPaddrLow(protphysaddr));
1602                 pde7->addrLow = le32_to_cpu(putPaddrHigh(protphysaddr));
1603
1604                 protgrp_blks = protgroup_len / 8;
1605                 protgrp_bytes = protgrp_blks * blksize;
1606
1607                 /* check if this pde is crossing the 4K boundary; if so split */
1608                 if ((pde7->addrLow & 0xfff) + protgroup_len > 0x1000) {
1609                         protgroup_remainder = 0x1000 - (pde7->addrLow & 0xfff);
1610                         protgroup_offset += protgroup_remainder;
1611                         protgrp_blks = protgroup_remainder / 8;
1612                         protgrp_bytes = protgroup_remainder * blksize;
1613                 } else {
1614                         protgroup_offset = 0;
1615                         curr_prot++;
1616                 }
1617
1618                 num_bde++;
1619
1620                 /* setup BDE's for data blocks associated with DIF data */
1621                 pgdone = 0;
1622                 subtotal = 0; /* total bytes processed for current prot grp */
1623                 while (!pgdone) {
1624                         if (!sgde) {
1625                                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
1626                                         "9065 BLKGRD:%s Invalid data segment\n",
1627                                                 __func__);
1628                                 return 0;
1629                         }
1630                         bpl++;
1631                         dataphysaddr = sg_dma_address(sgde) + split_offset;
1632                         bpl->addrLow = le32_to_cpu(putPaddrLow(dataphysaddr));
1633                         bpl->addrHigh = le32_to_cpu(putPaddrHigh(dataphysaddr));
1634
1635                         remainder = sg_dma_len(sgde) - split_offset;
1636
1637                         if ((subtotal + remainder) <= protgrp_bytes) {
1638                                 /* we can use this whole buffer */
1639                                 bpl->tus.f.bdeSize = remainder;
1640                                 split_offset = 0;
1641
1642                                 if ((subtotal + remainder) == protgrp_bytes)
1643                                         pgdone = 1;
1644                         } else {
1645                                 /* must split this buffer with next prot grp */
1646                                 bpl->tus.f.bdeSize = protgrp_bytes - subtotal;
1647                                 split_offset += bpl->tus.f.bdeSize;
1648                         }
1649
1650                         subtotal += bpl->tus.f.bdeSize;
1651
1652                         if (datadir == DMA_TO_DEVICE)
1653                                 bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
1654                         else
1655                                 bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
1656                         bpl->tus.w = le32_to_cpu(bpl->tus.w);
1657
1658                         num_bde++;
1659                         curr_data++;
1660
1661                         if (split_offset)
1662                                 break;
1663
1664                         /* Move to the next s/g segment if possible */
1665                         sgde = sg_next(sgde);
1666
1667                 }
1668
1669                 if (protgroup_offset) {
1670                         /* update the reference tag */
1671                         reftag += protgrp_blks;
1672                         bpl++;
1673                         continue;
1674                 }
1675
1676                 /* are we done ? */
1677                 if (curr_prot == protcnt) {
1678                         alldone = 1;
1679                 } else if (curr_prot < protcnt) {
1680                         /* advance to next prot buffer */
1681                         sgpe = sg_next(sgpe);
1682                         bpl++;
1683
1684                         /* update the reference tag */
1685                         reftag += protgrp_blks;
1686                 } else {
1687                         /* if we're here, we have a bug */
1688                         lpfc_printf_log(phba, KERN_ERR, LOG_BG,
1689                                 "9054 BLKGRD: bug in %s\n", __func__);
1690                 }
1691
1692         } while (!alldone);
1693
1694 out:
1695
1696         return num_bde;
1697 }
1698
1699 /*
1700  * Given a SCSI command that supports DIF, determine composition of protection
1701  * groups involved in setting up buffer lists
1702  *
1703  * Returns:
1704  *                            for DIF (for both read and write)
1705  * */
1706 static int
1707 lpfc_prot_group_type(struct lpfc_hba *phba, struct scsi_cmnd *sc)
1708 {
1709         int ret = LPFC_PG_TYPE_INVALID;
1710         unsigned char op = scsi_get_prot_op(sc);
1711
1712         switch (op) {
1713         case SCSI_PROT_READ_STRIP:
1714         case SCSI_PROT_WRITE_INSERT:
1715                 ret = LPFC_PG_TYPE_NO_DIF;
1716                 break;
1717         case SCSI_PROT_READ_INSERT:
1718         case SCSI_PROT_WRITE_STRIP:
1719         case SCSI_PROT_READ_PASS:
1720         case SCSI_PROT_WRITE_PASS:
1721                 ret = LPFC_PG_TYPE_DIF_BUF;
1722                 break;
1723         default:
1724                 lpfc_printf_log(phba, KERN_ERR, LOG_FCP,
1725                                 "9021 Unsupported protection op:%d\n", op);
1726                 break;
1727         }
1728
1729         return ret;
1730 }
1731
1732 /*
1733  * This is the protection/DIF aware version of
1734  * lpfc_scsi_prep_dma_buf(). It may be a good idea to combine the
1735  * two functions eventually, but for now, it's here
1736  */
1737 static int
1738 lpfc_bg_scsi_prep_dma_buf(struct lpfc_hba *phba,
1739                 struct lpfc_scsi_buf *lpfc_cmd)
1740 {
1741         struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
1742         struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
1743         struct ulp_bde64 *bpl = lpfc_cmd->fcp_bpl;
1744         IOCB_t *iocb_cmd = &lpfc_cmd->cur_iocbq.iocb;
1745         uint32_t num_bde = 0;
1746         int datasegcnt, protsegcnt, datadir = scsi_cmnd->sc_data_direction;
1747         int prot_group_type = 0;
1748         int diflen, fcpdl;
1749         unsigned blksize;
1750
1751         /*
1752          * Start the lpfc command prep by bumping the bpl beyond fcp_cmnd
1753          *  fcp_rsp regions to the first data bde entry
1754          */
1755         bpl += 2;
1756         if (scsi_sg_count(scsi_cmnd)) {
1757                 /*
1758                  * The driver stores the segment count returned from pci_map_sg
1759                  * because this a count of dma-mappings used to map the use_sg
1760                  * pages.  They are not guaranteed to be the same for those
1761                  * architectures that implement an IOMMU.
1762                  */
1763                 datasegcnt = dma_map_sg(&phba->pcidev->dev,
1764                                         scsi_sglist(scsi_cmnd),
1765                                         scsi_sg_count(scsi_cmnd), datadir);
1766                 if (unlikely(!datasegcnt))
1767                         return 1;
1768
1769                 lpfc_cmd->seg_cnt = datasegcnt;
1770                 if (lpfc_cmd->seg_cnt > phba->cfg_sg_seg_cnt) {
1771                         lpfc_printf_log(phba, KERN_ERR, LOG_BG,
1772                                         "9067 BLKGRD: %s: Too many sg segments"
1773                                         " from dma_map_sg.  Config %d, seg_cnt"
1774                                         " %d\n",
1775                                         __func__, phba->cfg_sg_seg_cnt,
1776                                         lpfc_cmd->seg_cnt);
1777                         scsi_dma_unmap(scsi_cmnd);
1778                         return 1;
1779                 }
1780
1781                 prot_group_type = lpfc_prot_group_type(phba, scsi_cmnd);
1782
1783                 switch (prot_group_type) {
1784                 case LPFC_PG_TYPE_NO_DIF:
1785                         num_bde = lpfc_bg_setup_bpl(phba, scsi_cmnd, bpl,
1786                                         datasegcnt);
1787                         /* we should have 2 or more entries in buffer list */
1788                         if (num_bde < 2)
1789                                 goto err;
1790                         break;
1791                 case LPFC_PG_TYPE_DIF_BUF:{
1792                         /*
1793                          * This type indicates that protection buffers are
1794                          * passed to the driver, so that needs to be prepared
1795                          * for DMA
1796                          */
1797                         protsegcnt = dma_map_sg(&phba->pcidev->dev,
1798                                         scsi_prot_sglist(scsi_cmnd),
1799                                         scsi_prot_sg_count(scsi_cmnd), datadir);
1800                         if (unlikely(!protsegcnt)) {
1801                                 scsi_dma_unmap(scsi_cmnd);
1802                                 return 1;
1803                         }
1804
1805                         lpfc_cmd->prot_seg_cnt = protsegcnt;
1806                         if (lpfc_cmd->prot_seg_cnt
1807                             > phba->cfg_prot_sg_seg_cnt) {
1808                                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
1809                                         "9068 BLKGRD: %s: Too many prot sg "
1810                                         "segments from dma_map_sg.  Config %d,"
1811                                                 "prot_seg_cnt %d\n", __func__,
1812                                                 phba->cfg_prot_sg_seg_cnt,
1813                                                 lpfc_cmd->prot_seg_cnt);
1814                                 dma_unmap_sg(&phba->pcidev->dev,
1815                                              scsi_prot_sglist(scsi_cmnd),
1816                                              scsi_prot_sg_count(scsi_cmnd),
1817                                              datadir);
1818                                 scsi_dma_unmap(scsi_cmnd);
1819                                 return 1;
1820                         }
1821
1822                         num_bde = lpfc_bg_setup_bpl_prot(phba, scsi_cmnd, bpl,
1823                                         datasegcnt, protsegcnt);
1824                         /* we should have 3 or more entries in buffer list */
1825                         if (num_bde < 3)
1826                                 goto err;
1827                         break;
1828                 }
1829                 case LPFC_PG_TYPE_INVALID:
1830                 default:
1831                         lpfc_printf_log(phba, KERN_ERR, LOG_FCP,
1832                                         "9022 Unexpected protection group %i\n",
1833                                         prot_group_type);
1834                         return 1;
1835                 }
1836         }
1837
1838         /*
1839          * Finish initializing those IOCB fields that are dependent on the
1840          * scsi_cmnd request_buffer.  Note that the bdeSize is explicitly
1841          * reinitialized since all iocb memory resources are used many times
1842          * for transmit, receive, and continuation bpl's.
1843          */
1844         iocb_cmd->un.fcpi64.bdl.bdeSize = (2 * sizeof(struct ulp_bde64));
1845         iocb_cmd->un.fcpi64.bdl.bdeSize += (num_bde * sizeof(struct ulp_bde64));
1846         iocb_cmd->ulpBdeCount = 1;
1847         iocb_cmd->ulpLe = 1;
1848
1849         fcpdl = scsi_bufflen(scsi_cmnd);
1850
1851         if (scsi_get_prot_type(scsi_cmnd) == SCSI_PROT_DIF_TYPE1) {
1852                 /*
1853                  * We are in DIF Type 1 mode
1854                  * Every data block has a 8 byte DIF (trailer)
1855                  * attached to it.  Must ajust FCP data length
1856                  */
1857                 blksize = lpfc_cmd_blksize(scsi_cmnd);
1858                 diflen = (fcpdl / blksize) * 8;
1859                 fcpdl += diflen;
1860         }
1861         fcp_cmnd->fcpDl = be32_to_cpu(fcpdl);
1862
1863         /*
1864          * Due to difference in data length between DIF/non-DIF paths,
1865          * we need to set word 4 of IOCB here
1866          */
1867         iocb_cmd->un.fcpi.fcpi_parm = fcpdl;
1868
1869         return 0;
1870 err:
1871         lpfc_printf_log(phba, KERN_ERR, LOG_FCP,
1872                         "9023 Could not setup all needed BDE's"
1873                         "prot_group_type=%d, num_bde=%d\n",
1874                         prot_group_type, num_bde);
1875         return 1;
1876 }
1877
1878 /*
1879  * This function checks for BlockGuard errors detected by
1880  * the HBA.  In case of errors, the ASC/ASCQ fields in the
1881  * sense buffer will be set accordingly, paired with
1882  * ILLEGAL_REQUEST to signal to the kernel that the HBA
1883  * detected corruption.
1884  *
1885  * Returns:
1886  *  0 - No error found
1887  *  1 - BlockGuard error found
1888  * -1 - Internal error (bad profile, ...etc)
1889  */
1890 static int
1891 lpfc_parse_bg_err(struct lpfc_hba *phba, struct lpfc_scsi_buf *lpfc_cmd,
1892                         struct lpfc_iocbq *pIocbOut)
1893 {
1894         struct scsi_cmnd *cmd = lpfc_cmd->pCmd;
1895         struct sli3_bg_fields *bgf = &pIocbOut->iocb.unsli3.sli3_bg;
1896         int ret = 0;
1897         uint32_t bghm = bgf->bghm;
1898         uint32_t bgstat = bgf->bgstat;
1899         uint64_t failing_sector = 0;
1900
1901         lpfc_printf_log(phba, KERN_ERR, LOG_BG, "9069 BLKGRD: BG ERROR in cmd"
1902                         " 0x%x lba 0x%llx blk cnt 0x%x "
1903                         "bgstat=0x%x bghm=0x%x\n",
1904                         cmd->cmnd[0], (unsigned long long)scsi_get_lba(cmd),
1905                         blk_rq_sectors(cmd->request), bgstat, bghm);
1906
1907         spin_lock(&_dump_buf_lock);
1908         if (!_dump_buf_done) {
1909                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,  "9070 BLKGRD: Saving"
1910                         " Data for %u blocks to debugfs\n",
1911                                 (cmd->cmnd[7] << 8 | cmd->cmnd[8]));
1912                 lpfc_debug_save_data(phba, cmd);
1913
1914                 /* If we have a prot sgl, save the DIF buffer */
1915                 if (lpfc_prot_group_type(phba, cmd) ==
1916                                 LPFC_PG_TYPE_DIF_BUF) {
1917                         lpfc_printf_log(phba, KERN_ERR, LOG_BG, "9071 BLKGRD: "
1918                                 "Saving DIF for %u blocks to debugfs\n",
1919                                 (cmd->cmnd[7] << 8 | cmd->cmnd[8]));
1920                         lpfc_debug_save_dif(phba, cmd);
1921                 }
1922
1923                 _dump_buf_done = 1;
1924         }
1925         spin_unlock(&_dump_buf_lock);
1926
1927         if (lpfc_bgs_get_invalid_prof(bgstat)) {
1928                 cmd->result = ScsiResult(DID_ERROR, 0);
1929                 lpfc_printf_log(phba, KERN_ERR, LOG_BG, "9072 BLKGRD: Invalid"
1930                         " BlockGuard profile. bgstat:0x%x\n",
1931                         bgstat);
1932                 ret = (-1);
1933                 goto out;
1934         }
1935
1936         if (lpfc_bgs_get_uninit_dif_block(bgstat)) {
1937                 cmd->result = ScsiResult(DID_ERROR, 0);
1938                 lpfc_printf_log(phba, KERN_ERR, LOG_BG, "9073 BLKGRD: "
1939                                 "Invalid BlockGuard DIF Block. bgstat:0x%x\n",
1940                                 bgstat);
1941                 ret = (-1);
1942                 goto out;
1943         }
1944
1945         if (lpfc_bgs_get_guard_err(bgstat)) {
1946                 ret = 1;
1947
1948                 scsi_build_sense_buffer(1, cmd->sense_buffer, ILLEGAL_REQUEST,
1949                                 0x10, 0x1);
1950                 cmd->result = DRIVER_SENSE << 24
1951                         | ScsiResult(DID_ABORT, SAM_STAT_CHECK_CONDITION);
1952                 phba->bg_guard_err_cnt++;
1953                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
1954                         "9055 BLKGRD: guard_tag error\n");
1955         }
1956
1957         if (lpfc_bgs_get_reftag_err(bgstat)) {
1958                 ret = 1;
1959
1960                 scsi_build_sense_buffer(1, cmd->sense_buffer, ILLEGAL_REQUEST,
1961                                 0x10, 0x3);
1962                 cmd->result = DRIVER_SENSE << 24
1963                         | ScsiResult(DID_ABORT, SAM_STAT_CHECK_CONDITION);
1964
1965                 phba->bg_reftag_err_cnt++;
1966                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
1967                         "9056 BLKGRD: ref_tag error\n");
1968         }
1969
1970         if (lpfc_bgs_get_apptag_err(bgstat)) {
1971                 ret = 1;
1972
1973                 scsi_build_sense_buffer(1, cmd->sense_buffer, ILLEGAL_REQUEST,
1974                                 0x10, 0x2);
1975                 cmd->result = DRIVER_SENSE << 24
1976                         | ScsiResult(DID_ABORT, SAM_STAT_CHECK_CONDITION);
1977
1978                 phba->bg_apptag_err_cnt++;
1979                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
1980                         "9061 BLKGRD: app_tag error\n");
1981         }
1982
1983         if (lpfc_bgs_get_hi_water_mark_present(bgstat)) {
1984                 /*
1985                  * setup sense data descriptor 0 per SPC-4 as an information
1986                  * field, and put the failing LBA in it
1987                  */
1988                 cmd->sense_buffer[8] = 0;     /* Information */
1989                 cmd->sense_buffer[9] = 0xa;   /* Add. length */
1990                 bghm /= cmd->device->sector_size;
1991
1992                 failing_sector = scsi_get_lba(cmd);
1993                 failing_sector += bghm;
1994
1995                 put_unaligned_be64(failing_sector, &cmd->sense_buffer[10]);
1996         }
1997
1998         if (!ret) {
1999                 /* No error was reported - problem in FW? */
2000                 cmd->result = ScsiResult(DID_ERROR, 0);
2001                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
2002                         "9057 BLKGRD: no errors reported!\n");
2003         }
2004
2005 out:
2006         return ret;
2007 }
2008
2009 /**
2010  * lpfc_scsi_prep_dma_buf_s4 - DMA mapping for scsi buffer to SLI4 IF spec
2011  * @phba: The Hba for which this call is being executed.
2012  * @lpfc_cmd: The scsi buffer which is going to be mapped.
2013  *
2014  * This routine does the pci dma mapping for scatter-gather list of scsi cmnd
2015  * field of @lpfc_cmd for device with SLI-4 interface spec.
2016  *
2017  * Return codes:
2018  *      1 - Error
2019  *      0 - Success
2020  **/
2021 static int
2022 lpfc_scsi_prep_dma_buf_s4(struct lpfc_hba *phba, struct lpfc_scsi_buf *lpfc_cmd)
2023 {
2024         struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
2025         struct scatterlist *sgel = NULL;
2026         struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
2027         struct sli4_sge *sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
2028         struct sli4_sge *first_data_sgl;
2029         IOCB_t *iocb_cmd = &lpfc_cmd->cur_iocbq.iocb;
2030         dma_addr_t physaddr;
2031         uint32_t num_bde = 0;
2032         uint32_t dma_len;
2033         uint32_t dma_offset = 0;
2034         int nseg;
2035         struct ulp_bde64 *bde;
2036
2037         /*
2038          * There are three possibilities here - use scatter-gather segment, use
2039          * the single mapping, or neither.  Start the lpfc command prep by
2040          * bumping the bpl beyond the fcp_cmnd and fcp_rsp regions to the first
2041          * data bde entry.
2042          */
2043         if (scsi_sg_count(scsi_cmnd)) {
2044                 /*
2045                  * The driver stores the segment count returned from pci_map_sg
2046                  * because this a count of dma-mappings used to map the use_sg
2047                  * pages.  They are not guaranteed to be the same for those
2048                  * architectures that implement an IOMMU.
2049                  */
2050
2051                 nseg = scsi_dma_map(scsi_cmnd);
2052                 if (unlikely(!nseg))
2053                         return 1;
2054                 sgl += 1;
2055                 /* clear the last flag in the fcp_rsp map entry */
2056                 sgl->word2 = le32_to_cpu(sgl->word2);
2057                 bf_set(lpfc_sli4_sge_last, sgl, 0);
2058                 sgl->word2 = cpu_to_le32(sgl->word2);
2059                 sgl += 1;
2060                 first_data_sgl = sgl;
2061                 lpfc_cmd->seg_cnt = nseg;
2062                 if (lpfc_cmd->seg_cnt > phba->cfg_sg_seg_cnt) {
2063                         lpfc_printf_log(phba, KERN_ERR, LOG_BG, "9074 BLKGRD:"
2064                                 " %s: Too many sg segments from "
2065                                 "dma_map_sg.  Config %d, seg_cnt %d\n",
2066                                 __func__, phba->cfg_sg_seg_cnt,
2067                                lpfc_cmd->seg_cnt);
2068                         scsi_dma_unmap(scsi_cmnd);
2069                         return 1;
2070                 }
2071
2072                 /*
2073                  * The driver established a maximum scatter-gather segment count
2074                  * during probe that limits the number of sg elements in any
2075                  * single scsi command.  Just run through the seg_cnt and format
2076                  * the sge's.
2077                  * When using SLI-3 the driver will try to fit all the BDEs into
2078                  * the IOCB. If it can't then the BDEs get added to a BPL as it
2079                  * does for SLI-2 mode.
2080                  */
2081                 scsi_for_each_sg(scsi_cmnd, sgel, nseg, num_bde) {
2082                         physaddr = sg_dma_address(sgel);
2083                         dma_len = sg_dma_len(sgel);
2084                         sgl->addr_lo = cpu_to_le32(putPaddrLow(physaddr));
2085                         sgl->addr_hi = cpu_to_le32(putPaddrHigh(physaddr));
2086                         sgl->word2 = le32_to_cpu(sgl->word2);
2087                         if ((num_bde + 1) == nseg)
2088                                 bf_set(lpfc_sli4_sge_last, sgl, 1);
2089                         else
2090                                 bf_set(lpfc_sli4_sge_last, sgl, 0);
2091                         bf_set(lpfc_sli4_sge_offset, sgl, dma_offset);
2092                         sgl->word2 = cpu_to_le32(sgl->word2);
2093                         sgl->sge_len = cpu_to_le32(dma_len);
2094                         dma_offset += dma_len;
2095                         sgl++;
2096                 }
2097                 /* setup the performance hint (first data BDE) if enabled */
2098                 if (phba->sli3_options & LPFC_SLI4_PERFH_ENABLED) {
2099                         bde = (struct ulp_bde64 *)
2100                                         &(iocb_cmd->unsli3.sli3Words[5]);
2101                         bde->addrLow = first_data_sgl->addr_lo;
2102                         bde->addrHigh = first_data_sgl->addr_hi;
2103                         bde->tus.f.bdeSize =
2104                                         le32_to_cpu(first_data_sgl->sge_len);
2105                         bde->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
2106                         bde->tus.w = cpu_to_le32(bde->tus.w);
2107                 }
2108         } else {
2109                 sgl += 1;
2110                 /* clear the last flag in the fcp_rsp map entry */
2111                 sgl->word2 = le32_to_cpu(sgl->word2);
2112                 bf_set(lpfc_sli4_sge_last, sgl, 1);
2113                 sgl->word2 = cpu_to_le32(sgl->word2);
2114         }
2115
2116         /*
2117          * Finish initializing those IOCB fields that are dependent on the
2118          * scsi_cmnd request_buffer.  Note that for SLI-2 the bdeSize is
2119          * explicitly reinitialized.
2120          * all iocb memory resources are reused.
2121          */
2122         fcp_cmnd->fcpDl = cpu_to_be32(scsi_bufflen(scsi_cmnd));
2123
2124         /*
2125          * Due to difference in data length between DIF/non-DIF paths,
2126          * we need to set word 4 of IOCB here
2127          */
2128         iocb_cmd->un.fcpi.fcpi_parm = scsi_bufflen(scsi_cmnd);
2129         return 0;
2130 }
2131
2132 /**
2133  * lpfc_scsi_prep_dma_buf - Wrapper function for DMA mapping of scsi buffer
2134  * @phba: The Hba for which this call is being executed.
2135  * @lpfc_cmd: The scsi buffer which is going to be mapped.
2136  *
2137  * This routine wraps the actual DMA mapping function pointer from the
2138  * lpfc_hba struct.
2139  *
2140  * Return codes:
2141  *      1 - Error
2142  *      0 - Success
2143  **/
2144 static inline int
2145 lpfc_scsi_prep_dma_buf(struct lpfc_hba *phba, struct lpfc_scsi_buf *lpfc_cmd)
2146 {
2147         return phba->lpfc_scsi_prep_dma_buf(phba, lpfc_cmd);
2148 }
2149
2150 /**
2151  * lpfc_send_scsi_error_event - Posts an event when there is SCSI error
2152  * @phba: Pointer to hba context object.
2153  * @vport: Pointer to vport object.
2154  * @lpfc_cmd: Pointer to lpfc scsi command which reported the error.
2155  * @rsp_iocb: Pointer to response iocb object which reported error.
2156  *
2157  * This function posts an event when there is a SCSI command reporting
2158  * error from the scsi device.
2159  **/
2160 static void
2161 lpfc_send_scsi_error_event(struct lpfc_hba *phba, struct lpfc_vport *vport,
2162                 struct lpfc_scsi_buf *lpfc_cmd, struct lpfc_iocbq *rsp_iocb) {
2163         struct scsi_cmnd *cmnd = lpfc_cmd->pCmd;
2164         struct fcp_rsp *fcprsp = lpfc_cmd->fcp_rsp;
2165         uint32_t resp_info = fcprsp->rspStatus2;
2166         uint32_t scsi_status = fcprsp->rspStatus3;
2167         uint32_t fcpi_parm = rsp_iocb->iocb.un.fcpi.fcpi_parm;
2168         struct lpfc_fast_path_event *fast_path_evt = NULL;
2169         struct lpfc_nodelist *pnode = lpfc_cmd->rdata->pnode;
2170         unsigned long flags;
2171
2172         if (!pnode || !NLP_CHK_NODE_ACT(pnode))
2173                 return;
2174
2175         /* If there is queuefull or busy condition send a scsi event */
2176         if ((cmnd->result == SAM_STAT_TASK_SET_FULL) ||
2177                 (cmnd->result == SAM_STAT_BUSY)) {
2178                 fast_path_evt = lpfc_alloc_fast_evt(phba);
2179                 if (!fast_path_evt)
2180                         return;
2181                 fast_path_evt->un.scsi_evt.event_type =
2182                         FC_REG_SCSI_EVENT;
2183                 fast_path_evt->un.scsi_evt.subcategory =
2184                 (cmnd->result == SAM_STAT_TASK_SET_FULL) ?
2185                 LPFC_EVENT_QFULL : LPFC_EVENT_DEVBSY;
2186                 fast_path_evt->un.scsi_evt.lun = cmnd->device->lun;
2187                 memcpy(&fast_path_evt->un.scsi_evt.wwpn,
2188                         &pnode->nlp_portname, sizeof(struct lpfc_name));
2189                 memcpy(&fast_path_evt->un.scsi_evt.wwnn,
2190                         &pnode->nlp_nodename, sizeof(struct lpfc_name));
2191         } else if ((resp_info & SNS_LEN_VALID) && fcprsp->rspSnsLen &&
2192                 ((cmnd->cmnd[0] == READ_10) || (cmnd->cmnd[0] == WRITE_10))) {
2193                 fast_path_evt = lpfc_alloc_fast_evt(phba);
2194                 if (!fast_path_evt)
2195                         return;
2196                 fast_path_evt->un.check_cond_evt.scsi_event.event_type =
2197                         FC_REG_SCSI_EVENT;
2198                 fast_path_evt->un.check_cond_evt.scsi_event.subcategory =
2199                         LPFC_EVENT_CHECK_COND;
2200                 fast_path_evt->un.check_cond_evt.scsi_event.lun =
2201                         cmnd->device->lun;
2202                 memcpy(&fast_path_evt->un.check_cond_evt.scsi_event.wwpn,
2203                         &pnode->nlp_portname, sizeof(struct lpfc_name));
2204                 memcpy(&fast_path_evt->un.check_cond_evt.scsi_event.wwnn,
2205                         &pnode->nlp_nodename, sizeof(struct lpfc_name));
2206                 fast_path_evt->un.check_cond_evt.sense_key =
2207                         cmnd->sense_buffer[2] & 0xf;
2208                 fast_path_evt->un.check_cond_evt.asc = cmnd->sense_buffer[12];
2209                 fast_path_evt->un.check_cond_evt.ascq = cmnd->sense_buffer[13];
2210         } else if ((cmnd->sc_data_direction == DMA_FROM_DEVICE) &&
2211                      fcpi_parm &&
2212                      ((be32_to_cpu(fcprsp->rspResId) != fcpi_parm) ||
2213                         ((scsi_status == SAM_STAT_GOOD) &&
2214                         !(resp_info & (RESID_UNDER | RESID_OVER))))) {
2215                 /*
2216                  * If status is good or resid does not match with fcp_param and
2217                  * there is valid fcpi_parm, then there is a read_check error
2218                  */
2219                 fast_path_evt = lpfc_alloc_fast_evt(phba);
2220                 if (!fast_path_evt)
2221                         return;
2222                 fast_path_evt->un.read_check_error.header.event_type =
2223                         FC_REG_FABRIC_EVENT;
2224                 fast_path_evt->un.read_check_error.header.subcategory =
2225                         LPFC_EVENT_FCPRDCHKERR;
2226                 memcpy(&fast_path_evt->un.read_check_error.header.wwpn,
2227                         &pnode->nlp_portname, sizeof(struct lpfc_name));
2228                 memcpy(&fast_path_evt->un.read_check_error.header.wwnn,
2229                         &pnode->nlp_nodename, sizeof(struct lpfc_name));
2230                 fast_path_evt->un.read_check_error.lun = cmnd->device->lun;
2231                 fast_path_evt->un.read_check_error.opcode = cmnd->cmnd[0];
2232                 fast_path_evt->un.read_check_error.fcpiparam =
2233                         fcpi_parm;
2234         } else
2235                 return;
2236
2237         fast_path_evt->vport = vport;
2238         spin_lock_irqsave(&phba->hbalock, flags);
2239         list_add_tail(&fast_path_evt->work_evt.evt_listp, &phba->work_list);
2240         spin_unlock_irqrestore(&phba->hbalock, flags);
2241         lpfc_worker_wake_up(phba);
2242         return;
2243 }
2244
2245 /**
2246  * lpfc_scsi_unprep_dma_buf - Un-map DMA mapping of SG-list for dev
2247  * @phba: The HBA for which this call is being executed.
2248  * @psb: The scsi buffer which is going to be un-mapped.
2249  *
2250  * This routine does DMA un-mapping of scatter gather list of scsi command
2251  * field of @lpfc_cmd for device with SLI-3 interface spec.
2252  **/
2253 static void
2254 lpfc_scsi_unprep_dma_buf(struct lpfc_hba *phba, struct lpfc_scsi_buf *psb)
2255 {
2256         /*
2257          * There are only two special cases to consider.  (1) the scsi command
2258          * requested scatter-gather usage or (2) the scsi command allocated
2259          * a request buffer, but did not request use_sg.  There is a third
2260          * case, but it does not require resource deallocation.
2261          */
2262         if (psb->seg_cnt > 0)
2263                 scsi_dma_unmap(psb->pCmd);
2264         if (psb->prot_seg_cnt > 0)
2265                 dma_unmap_sg(&phba->pcidev->dev, scsi_prot_sglist(psb->pCmd),
2266                                 scsi_prot_sg_count(psb->pCmd),
2267                                 psb->pCmd->sc_data_direction);
2268 }
2269
2270 /**
2271  * lpfc_handler_fcp_err - FCP response handler
2272  * @vport: The virtual port for which this call is being executed.
2273  * @lpfc_cmd: Pointer to lpfc_scsi_buf data structure.
2274  * @rsp_iocb: The response IOCB which contains FCP error.
2275  *
2276  * This routine is called to process response IOCB with status field
2277  * IOSTAT_FCP_RSP_ERROR. This routine sets result field of scsi command
2278  * based upon SCSI and FCP error.
2279  **/
2280 static void
2281 lpfc_handle_fcp_err(struct lpfc_vport *vport, struct lpfc_scsi_buf *lpfc_cmd,
2282                     struct lpfc_iocbq *rsp_iocb)
2283 {
2284         struct scsi_cmnd *cmnd = lpfc_cmd->pCmd;
2285         struct fcp_cmnd *fcpcmd = lpfc_cmd->fcp_cmnd;
2286         struct fcp_rsp *fcprsp = lpfc_cmd->fcp_rsp;
2287         uint32_t fcpi_parm = rsp_iocb->iocb.un.fcpi.fcpi_parm;
2288         uint32_t resp_info = fcprsp->rspStatus2;
2289         uint32_t scsi_status = fcprsp->rspStatus3;
2290         uint32_t *lp;
2291         uint32_t host_status = DID_OK;
2292         uint32_t rsplen = 0;
2293         uint32_t logit = LOG_FCP | LOG_FCP_ERROR;
2294
2295
2296         /*
2297          *  If this is a task management command, there is no
2298          *  scsi packet associated with this lpfc_cmd.  The driver
2299          *  consumes it.
2300          */
2301         if (fcpcmd->fcpCntl2) {
2302                 scsi_status = 0;
2303                 goto out;
2304         }
2305
2306         if (resp_info & RSP_LEN_VALID) {
2307                 rsplen = be32_to_cpu(fcprsp->rspRspLen);
2308                 if (rsplen != 0 && rsplen != 4 && rsplen != 8) {
2309                         lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
2310                                  "2719 Invalid response length: "
2311                                  "tgt x%x lun x%x cmnd x%x rsplen x%x\n",
2312                                  cmnd->device->id,
2313                                  cmnd->device->lun, cmnd->cmnd[0],
2314                                  rsplen);
2315                         host_status = DID_ERROR;
2316                         goto out;
2317                 }
2318                 if (fcprsp->rspInfo3 != RSP_NO_FAILURE) {
2319                         lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
2320                                  "2757 Protocol failure detected during "
2321                                  "processing of FCP I/O op: "
2322                                  "tgt x%x lun x%x cmnd x%x rspInfo3 x%x\n",
2323                                  cmnd->device->id,
2324                                  cmnd->device->lun, cmnd->cmnd[0],
2325                                  fcprsp->rspInfo3);
2326                         host_status = DID_ERROR;
2327                         goto out;
2328                 }
2329         }
2330
2331         if ((resp_info & SNS_LEN_VALID) && fcprsp->rspSnsLen) {
2332                 uint32_t snslen = be32_to_cpu(fcprsp->rspSnsLen);
2333                 if (snslen > SCSI_SENSE_BUFFERSIZE)
2334                         snslen = SCSI_SENSE_BUFFERSIZE;
2335
2336                 if (resp_info & RSP_LEN_VALID)
2337                   rsplen = be32_to_cpu(fcprsp->rspRspLen);
2338                 memcpy(cmnd->sense_buffer, &fcprsp->rspInfo0 + rsplen, snslen);
2339         }
2340         lp = (uint32_t *)cmnd->sense_buffer;
2341
2342         if (!scsi_status && (resp_info & RESID_UNDER))
2343                 logit = LOG_FCP;
2344
2345         lpfc_printf_vlog(vport, KERN_WARNING, logit,
2346                          "9024 FCP command x%x failed: x%x SNS x%x x%x "
2347                          "Data: x%x x%x x%x x%x x%x\n",
2348                          cmnd->cmnd[0], scsi_status,
2349                          be32_to_cpu(*lp), be32_to_cpu(*(lp + 3)), resp_info,
2350                          be32_to_cpu(fcprsp->rspResId),
2351                          be32_to_cpu(fcprsp->rspSnsLen),
2352                          be32_to_cpu(fcprsp->rspRspLen),
2353                          fcprsp->rspInfo3);
2354
2355         scsi_set_resid(cmnd, 0);
2356         if (resp_info & RESID_UNDER) {
2357                 scsi_set_resid(cmnd, be32_to_cpu(fcprsp->rspResId));
2358
2359                 lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
2360                                  "9025 FCP Read Underrun, expected %d, "
2361                                  "residual %d Data: x%x x%x x%x\n",
2362                                  be32_to_cpu(fcpcmd->fcpDl),
2363                                  scsi_get_resid(cmnd), fcpi_parm, cmnd->cmnd[0],
2364                                  cmnd->underflow);
2365
2366                 /*
2367                  * If there is an under run check if under run reported by
2368                  * storage array is same as the under run reported by HBA.
2369                  * If this is not same, there is a dropped frame.
2370                  */
2371                 if ((cmnd->sc_data_direction == DMA_FROM_DEVICE) &&
2372                         fcpi_parm &&
2373                         (scsi_get_resid(cmnd) != fcpi_parm)) {
2374                         lpfc_printf_vlog(vport, KERN_WARNING,
2375                                          LOG_FCP | LOG_FCP_ERROR,
2376                                          "9026 FCP Read Check Error "
2377                                          "and Underrun Data: x%x x%x x%x x%x\n",
2378                                          be32_to_cpu(fcpcmd->fcpDl),
2379                                          scsi_get_resid(cmnd), fcpi_parm,
2380                                          cmnd->cmnd[0]);
2381                         scsi_set_resid(cmnd, scsi_bufflen(cmnd));
2382                         host_status = DID_ERROR;
2383                 }
2384                 /*
2385                  * The cmnd->underflow is the minimum number of bytes that must
2386                  * be transferred for this command.  Provided a sense condition
2387                  * is not present, make sure the actual amount transferred is at
2388                  * least the underflow value or fail.
2389                  */
2390                 if (!(resp_info & SNS_LEN_VALID) &&
2391                     (scsi_status == SAM_STAT_GOOD) &&
2392                     (scsi_bufflen(cmnd) - scsi_get_resid(cmnd)
2393                      < cmnd->underflow)) {
2394                         lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
2395                                          "9027 FCP command x%x residual "
2396                                          "underrun converted to error "
2397                                          "Data: x%x x%x x%x\n",
2398                                          cmnd->cmnd[0], scsi_bufflen(cmnd),
2399                                          scsi_get_resid(cmnd), cmnd->underflow);
2400                         host_status = DID_ERROR;
2401                 }
2402         } else if (resp_info & RESID_OVER) {
2403                 lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
2404                                  "9028 FCP command x%x residual overrun error. "
2405                                  "Data: x%x x%x\n", cmnd->cmnd[0],
2406                                  scsi_bufflen(cmnd), scsi_get_resid(cmnd));
2407                 host_status = DID_ERROR;
2408
2409         /*
2410          * Check SLI validation that all the transfer was actually done
2411          * (fcpi_parm should be zero). Apply check only to reads.
2412          */
2413         } else if (fcpi_parm && (cmnd->sc_data_direction == DMA_FROM_DEVICE)) {
2414                 lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP | LOG_FCP_ERROR,
2415                                  "9029 FCP Read Check Error Data: "
2416                                  "x%x x%x x%x x%x x%x\n",
2417                                  be32_to_cpu(fcpcmd->fcpDl),
2418                                  be32_to_cpu(fcprsp->rspResId),
2419                                  fcpi_parm, cmnd->cmnd[0], scsi_status);
2420                 switch (scsi_status) {
2421                 case SAM_STAT_GOOD:
2422                 case SAM_STAT_CHECK_CONDITION:
2423                         /* Fabric dropped a data frame. Fail any successful
2424                          * command in which we detected dropped frames.
2425                          * A status of good or some check conditions could
2426                          * be considered a successful command.
2427                          */
2428                         host_status = DID_ERROR;
2429                         break;
2430                 }
2431                 scsi_set_resid(cmnd, scsi_bufflen(cmnd));
2432         }
2433
2434  out:
2435         cmnd->result = ScsiResult(host_status, scsi_status);
2436         lpfc_send_scsi_error_event(vport->phba, vport, lpfc_cmd, rsp_iocb);
2437 }
2438
2439 /**
2440  * lpfc_scsi_cmd_iocb_cmpl - Scsi cmnd IOCB completion routine
2441  * @phba: The Hba for which this call is being executed.
2442  * @pIocbIn: The command IOCBQ for the scsi cmnd.
2443  * @pIocbOut: The response IOCBQ for the scsi cmnd.
2444  *
2445  * This routine assigns scsi command result by looking into response IOCB
2446  * status field appropriately. This routine handles QUEUE FULL condition as
2447  * well by ramping down device queue depth.
2448  **/
2449 static void
2450 lpfc_scsi_cmd_iocb_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *pIocbIn,
2451                         struct lpfc_iocbq *pIocbOut)
2452 {
2453         struct lpfc_scsi_buf *lpfc_cmd =
2454                 (struct lpfc_scsi_buf *) pIocbIn->context1;
2455         struct lpfc_vport      *vport = pIocbIn->vport;
2456         struct lpfc_rport_data *rdata = lpfc_cmd->rdata;
2457         struct lpfc_nodelist *pnode = rdata->pnode;
2458         struct scsi_cmnd *cmd;
2459         int result;
2460         struct scsi_device *tmp_sdev;
2461         int depth;
2462         unsigned long flags;
2463         struct lpfc_fast_path_event *fast_path_evt;
2464         struct Scsi_Host *shost;
2465         uint32_t queue_depth, scsi_id;
2466
2467         /* Sanity check on return of outstanding command */
2468         if (!(lpfc_cmd->pCmd))
2469                 return;
2470         cmd = lpfc_cmd->pCmd;
2471         shost = cmd->device->host;
2472
2473         lpfc_cmd->result = pIocbOut->iocb.un.ulpWord[4];
2474         lpfc_cmd->status = pIocbOut->iocb.ulpStatus;
2475         /* pick up SLI4 exhange busy status from HBA */
2476         lpfc_cmd->exch_busy = pIocbOut->iocb_flag & LPFC_EXCHANGE_BUSY;
2477
2478         if (pnode && NLP_CHK_NODE_ACT(pnode))
2479                 atomic_dec(&pnode->cmd_pending);
2480
2481         if (lpfc_cmd->status) {
2482                 if (lpfc_cmd->status == IOSTAT_LOCAL_REJECT &&
2483                     (lpfc_cmd->result & IOERR_DRVR_MASK))
2484                         lpfc_cmd->status = IOSTAT_DRIVER_REJECT;
2485                 else if (lpfc_cmd->status >= IOSTAT_CNT)
2486                         lpfc_cmd->status = IOSTAT_DEFAULT;
2487
2488                 lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
2489                                  "9030 FCP cmd x%x failed <%d/%d> "
2490                                  "status: x%x result: x%x Data: x%x x%x\n",
2491                                  cmd->cmnd[0],
2492                                  cmd->device ? cmd->device->id : 0xffff,
2493                                  cmd->device ? cmd->device->lun : 0xffff,
2494                                  lpfc_cmd->status, lpfc_cmd->result,
2495                                  pIocbOut->iocb.ulpContext,
2496                                  lpfc_cmd->cur_iocbq.iocb.ulpIoTag);
2497
2498                 switch (lpfc_cmd->status) {
2499                 case IOSTAT_FCP_RSP_ERROR:
2500                         /* Call FCP RSP handler to determine result */
2501                         lpfc_handle_fcp_err(vport, lpfc_cmd, pIocbOut);
2502                         break;
2503                 case IOSTAT_NPORT_BSY:
2504                 case IOSTAT_FABRIC_BSY:
2505                         cmd->result = ScsiResult(DID_TRANSPORT_DISRUPTED, 0);
2506                         fast_path_evt = lpfc_alloc_fast_evt(phba);
2507                         if (!fast_path_evt)
2508                                 break;
2509                         fast_path_evt->un.fabric_evt.event_type =
2510                                 FC_REG_FABRIC_EVENT;
2511                         fast_path_evt->un.fabric_evt.subcategory =
2512                                 (lpfc_cmd->status == IOSTAT_NPORT_BSY) ?
2513                                 LPFC_EVENT_PORT_BUSY : LPFC_EVENT_FABRIC_BUSY;
2514                         if (pnode && NLP_CHK_NODE_ACT(pnode)) {
2515                                 memcpy(&fast_path_evt->un.fabric_evt.wwpn,
2516                                         &pnode->nlp_portname,
2517                                         sizeof(struct lpfc_name));
2518                                 memcpy(&fast_path_evt->un.fabric_evt.wwnn,
2519                                         &pnode->nlp_nodename,
2520                                         sizeof(struct lpfc_name));
2521                         }
2522                         fast_path_evt->vport = vport;
2523                         fast_path_evt->work_evt.evt =
2524                                 LPFC_EVT_FASTPATH_MGMT_EVT;
2525                         spin_lock_irqsave(&phba->hbalock, flags);
2526                         list_add_tail(&fast_path_evt->work_evt.evt_listp,
2527                                 &phba->work_list);
2528                         spin_unlock_irqrestore(&phba->hbalock, flags);
2529                         lpfc_worker_wake_up(phba);
2530                         break;
2531                 case IOSTAT_LOCAL_REJECT:
2532                 case IOSTAT_REMOTE_STOP:
2533                         if (lpfc_cmd->result == IOERR_ELXSEC_KEY_UNWRAP_ERROR ||
2534                             lpfc_cmd->result ==
2535                                         IOERR_ELXSEC_KEY_UNWRAP_COMPARE_ERROR ||
2536                             lpfc_cmd->result == IOERR_ELXSEC_CRYPTO_ERROR ||
2537                             lpfc_cmd->result ==
2538                                         IOERR_ELXSEC_CRYPTO_COMPARE_ERROR) {
2539                                 cmd->result = ScsiResult(DID_NO_CONNECT, 0);
2540                                 break;
2541                         }
2542                         if (lpfc_cmd->result == IOERR_INVALID_RPI ||
2543                             lpfc_cmd->result == IOERR_NO_RESOURCES ||
2544                             lpfc_cmd->result == IOERR_ABORT_REQUESTED ||
2545                             lpfc_cmd->result == IOERR_SLER_CMD_RCV_FAILURE) {
2546                                 cmd->result = ScsiResult(DID_REQUEUE, 0);
2547                                 break;
2548                         }
2549                         if ((lpfc_cmd->result == IOERR_RX_DMA_FAILED ||
2550                              lpfc_cmd->result == IOERR_TX_DMA_FAILED) &&
2551                              pIocbOut->iocb.unsli3.sli3_bg.bgstat) {
2552                                 if (scsi_get_prot_op(cmd) != SCSI_PROT_NORMAL) {
2553                                         /*
2554                                          * This is a response for a BG enabled
2555                                          * cmd. Parse BG error
2556                                          */
2557                                         lpfc_parse_bg_err(phba, lpfc_cmd,
2558                                                         pIocbOut);
2559                                         break;
2560                                 } else {
2561                                         lpfc_printf_vlog(vport, KERN_WARNING,
2562                                                         LOG_BG,
2563                                                         "9031 non-zero BGSTAT "
2564                                                         "on unprotected cmd\n");
2565                                 }
2566                         }
2567                         if ((lpfc_cmd->status == IOSTAT_REMOTE_STOP)
2568                                 && (phba->sli_rev == LPFC_SLI_REV4)
2569                                 && (pnode && NLP_CHK_NODE_ACT(pnode))) {
2570                                 /* This IO was aborted by the target, we don't
2571                                  * know the rxid and because we did not send the
2572                                  * ABTS we cannot generate and RRQ.
2573                                  */
2574                                 lpfc_set_rrq_active(phba, pnode,
2575                                                 lpfc_cmd->cur_iocbq.sli4_xritag,
2576                                                 0, 0);
2577                         }
2578                 /* else: fall through */
2579                 default:
2580                         cmd->result = ScsiResult(DID_ERROR, 0);
2581                         break;
2582                 }
2583
2584                 if (!pnode || !NLP_CHK_NODE_ACT(pnode)
2585                     || (pnode->nlp_state != NLP_STE_MAPPED_NODE))
2586                         cmd->result = ScsiResult(DID_TRANSPORT_DISRUPTED,
2587                                                  SAM_STAT_BUSY);
2588         } else
2589                 cmd->result = ScsiResult(DID_OK, 0);
2590
2591         if (cmd->result || lpfc_cmd->fcp_rsp->rspSnsLen) {
2592                 uint32_t *lp = (uint32_t *)cmd->sense_buffer;
2593
2594                 lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
2595                                  "0710 Iodone <%d/%d> cmd %p, error "
2596                                  "x%x SNS x%x x%x Data: x%x x%x\n",
2597                                  cmd->device->id, cmd->device->lun, cmd,
2598                                  cmd->result, *lp, *(lp + 3), cmd->retries,
2599                                  scsi_get_resid(cmd));
2600         }
2601
2602         lpfc_update_stats(phba, lpfc_cmd);
2603         result = cmd->result;
2604         if (vport->cfg_max_scsicmpl_time &&
2605            time_after(jiffies, lpfc_cmd->start_time +
2606                 msecs_to_jiffies(vport->cfg_max_scsicmpl_time))) {
2607                 spin_lock_irqsave(shost->host_lock, flags);
2608                 if (pnode && NLP_CHK_NODE_ACT(pnode)) {
2609                         if (pnode->cmd_qdepth >
2610                                 atomic_read(&pnode->cmd_pending) &&
2611                                 (atomic_read(&pnode->cmd_pending) >
2612                                 LPFC_MIN_TGT_QDEPTH) &&
2613                                 ((cmd->cmnd[0] == READ_10) ||
2614                                 (cmd->cmnd[0] == WRITE_10)))
2615                                 pnode->cmd_qdepth =
2616                                         atomic_read(&pnode->cmd_pending);
2617
2618                         pnode->last_change_time = jiffies;
2619                 }
2620                 spin_unlock_irqrestore(shost->host_lock, flags);
2621         } else if (pnode && NLP_CHK_NODE_ACT(pnode)) {
2622                 if ((pnode->cmd_qdepth < vport->cfg_tgt_queue_depth) &&
2623                    time_after(jiffies, pnode->last_change_time +
2624                               msecs_to_jiffies(LPFC_TGTQ_INTERVAL))) {
2625                         spin_lock_irqsave(shost->host_lock, flags);
2626                         depth = pnode->cmd_qdepth * LPFC_TGTQ_RAMPUP_PCENT
2627                                 / 100;
2628                         depth = depth ? depth : 1;
2629                         pnode->cmd_qdepth += depth;
2630                         if (pnode->cmd_qdepth > vport->cfg_tgt_queue_depth)
2631                                 pnode->cmd_qdepth = vport->cfg_tgt_queue_depth;
2632                         pnode->last_change_time = jiffies;
2633                         spin_unlock_irqrestore(shost->host_lock, flags);
2634                 }
2635         }
2636
2637         lpfc_scsi_unprep_dma_buf(phba, lpfc_cmd);
2638
2639         /* The sdev is not guaranteed to be valid post scsi_done upcall. */
2640         queue_depth = cmd->device->queue_depth;
2641         scsi_id = cmd->device->id;
2642         cmd->scsi_done(cmd);
2643
2644         if (phba->cfg_poll & ENABLE_FCP_RING_POLLING) {
2645                 /*
2646                  * If there is a thread waiting for command completion
2647                  * wake up the thread.
2648                  */
2649                 spin_lock_irqsave(shost->host_lock, flags);
2650                 lpfc_cmd->pCmd = NULL;
2651                 if (lpfc_cmd->waitq)
2652                         wake_up(lpfc_cmd->waitq);
2653                 spin_unlock_irqrestore(shost->host_lock, flags);
2654                 lpfc_release_scsi_buf(phba, lpfc_cmd);
2655                 return;
2656         }
2657
2658         if (!result)
2659                 lpfc_rampup_queue_depth(vport, queue_depth);
2660
2661         /*
2662          * Check for queue full.  If the lun is reporting queue full, then
2663          * back off the lun queue depth to prevent target overloads.
2664          */
2665         if (result == SAM_STAT_TASK_SET_FULL && pnode &&
2666             NLP_CHK_NODE_ACT(pnode)) {
2667                 shost_for_each_device(tmp_sdev, shost) {
2668                         if (tmp_sdev->id != scsi_id)
2669                                 continue;
2670                         depth = scsi_track_queue_full(tmp_sdev,
2671                                                       tmp_sdev->queue_depth-1);
2672                         if (depth <= 0)
2673                                 continue;
2674                         lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
2675                                          "0711 detected queue full - lun queue "
2676                                          "depth adjusted to %d.\n", depth);
2677                         lpfc_send_sdev_queuedepth_change_event(phba, vport,
2678                                                                pnode,
2679                                                                tmp_sdev->lun,
2680                                                                depth+1, depth);
2681                 }
2682         }
2683
2684         /*
2685          * If there is a thread waiting for command completion
2686          * wake up the thread.
2687          */
2688         spin_lock_irqsave(shost->host_lock, flags);
2689         lpfc_cmd->pCmd = NULL;
2690         if (lpfc_cmd->waitq)
2691                 wake_up(lpfc_cmd->waitq);
2692         spin_unlock_irqrestore(shost->host_lock, flags);
2693
2694         lpfc_release_scsi_buf(phba, lpfc_cmd);
2695 }
2696
2697 /**
2698  * lpfc_fcpcmd_to_iocb - copy the fcp_cmd data into the IOCB
2699  * @data: A pointer to the immediate command data portion of the IOCB.
2700  * @fcp_cmnd: The FCP Command that is provided by the SCSI layer.
2701  *
2702  * The routine copies the entire FCP command from @fcp_cmnd to @data while
2703  * byte swapping the data to big endian format for transmission on the wire.
2704  **/
2705 static void
2706 lpfc_fcpcmd_to_iocb(uint8_t *data, struct fcp_cmnd *fcp_cmnd)
2707 {
2708         int i, j;
2709         for (i = 0, j = 0; i < sizeof(struct fcp_cmnd);
2710              i += sizeof(uint32_t), j++) {
2711                 ((uint32_t *)data)[j] = cpu_to_be32(((uint32_t *)fcp_cmnd)[j]);
2712         }
2713 }
2714
2715 /**
2716  * lpfc_scsi_prep_cmnd - Wrapper func for convert scsi cmnd to FCP info unit
2717  * @vport: The virtual port for which this call is being executed.
2718  * @lpfc_cmd: The scsi command which needs to send.
2719  * @pnode: Pointer to lpfc_nodelist.
2720  *
2721  * This routine initializes fcp_cmnd and iocb data structure from scsi command
2722  * to transfer for device with SLI3 interface spec.
2723  **/
2724 static void
2725 lpfc_scsi_prep_cmnd(struct lpfc_vport *vport, struct lpfc_scsi_buf *lpfc_cmd,
2726                     struct lpfc_nodelist *pnode)
2727 {
2728         struct lpfc_hba *phba = vport->phba;
2729         struct scsi_cmnd *scsi_cmnd = lpfc_cmd->pCmd;
2730         struct fcp_cmnd *fcp_cmnd = lpfc_cmd->fcp_cmnd;
2731         IOCB_t *iocb_cmd = &lpfc_cmd->cur_iocbq.iocb;
2732         struct lpfc_iocbq *piocbq = &(lpfc_cmd->cur_iocbq);
2733         int datadir = scsi_cmnd->sc_data_direction;
2734         char tag[2];
2735
2736         if (!pnode || !NLP_CHK_NODE_ACT(pnode))
2737                 return;
2738
2739         lpfc_cmd->fcp_rsp->rspSnsLen = 0;
2740         /* clear task management bits */
2741         lpfc_cmd->fcp_cmnd->fcpCntl2 = 0;
2742
2743         int_to_scsilun(lpfc_cmd->pCmd->device->lun,
2744                         &lpfc_cmd->fcp_cmnd->fcp_lun);
2745
2746         memcpy(&fcp_cmnd->fcpCdb[0], scsi_cmnd->cmnd, 16);
2747
2748         if (scsi_populate_tag_msg(scsi_cmnd, tag)) {
2749                 switch (tag[0]) {
2750                 case HEAD_OF_QUEUE_TAG:
2751                         fcp_cmnd->fcpCntl1 = HEAD_OF_Q;
2752                         break;
2753                 case ORDERED_QUEUE_TAG:
2754                         fcp_cmnd->fcpCntl1 = ORDERED_Q;
2755                         break;
2756                 default:
2757                         fcp_cmnd->fcpCntl1 = SIMPLE_Q;
2758                         break;
2759                 }
2760         } else
2761                 fcp_cmnd->fcpCntl1 = 0;
2762
2763         /*
2764          * There are three possibilities here - use scatter-gather segment, use
2765          * the single mapping, or neither.  Start the lpfc command prep by
2766          * bumping the bpl beyond the fcp_cmnd and fcp_rsp regions to the first
2767          * data bde entry.
2768          */
2769         if (scsi_sg_count(scsi_cmnd)) {
2770                 if (datadir == DMA_TO_DEVICE) {
2771                         iocb_cmd->ulpCommand = CMD_FCP_IWRITE64_CR;
2772                         if (phba->sli_rev < LPFC_SLI_REV4) {
2773                                 iocb_cmd->un.fcpi.fcpi_parm = 0;
2774                                 iocb_cmd->ulpPU = 0;
2775                         } else
2776                                 iocb_cmd->ulpPU = PARM_READ_CHECK;
2777                         fcp_cmnd->fcpCntl3 = WRITE_DATA;
2778                         phba->fc4OutputRequests++;
2779                 } else {
2780                         iocb_cmd->ulpCommand = CMD_FCP_IREAD64_CR;
2781                         iocb_cmd->ulpPU = PARM_READ_CHECK;
2782                         fcp_cmnd->fcpCntl3 = READ_DATA;
2783                         phba->fc4InputRequests++;
2784                 }
2785         } else {
2786                 iocb_cmd->ulpCommand = CMD_FCP_ICMND64_CR;
2787                 iocb_cmd->un.fcpi.fcpi_parm = 0;
2788                 iocb_cmd->ulpPU = 0;
2789                 fcp_cmnd->fcpCntl3 = 0;
2790                 phba->fc4ControlRequests++;
2791         }
2792         if (phba->sli_rev == 3 &&
2793             !(phba->sli3_options & LPFC_SLI3_BG_ENABLED))
2794                 lpfc_fcpcmd_to_iocb(iocb_cmd->unsli3.fcp_ext.icd, fcp_cmnd);
2795         /*
2796          * Finish initializing those IOCB fields that are independent
2797          * of the scsi_cmnd request_buffer
2798          */
2799         piocbq->iocb.ulpContext = pnode->nlp_rpi;
2800         if (pnode->nlp_fcp_info & NLP_FCP_2_DEVICE)
2801                 piocbq->iocb.ulpFCP2Rcvy = 1;
2802         else
2803                 piocbq->iocb.ulpFCP2Rcvy = 0;
2804
2805         piocbq->iocb.ulpClass = (pnode->nlp_fcp_info & 0x0f);
2806         piocbq->context1  = lpfc_cmd;
2807         piocbq->iocb_cmpl = lpfc_scsi_cmd_iocb_cmpl;
2808         piocbq->iocb.ulpTimeout = lpfc_cmd->timeout;
2809         piocbq->vport = vport;
2810 }
2811
2812 /**
2813  * lpfc_scsi_prep_task_mgmt_cmnd - Convert SLI3 scsi TM cmd to FCP info unit
2814  * @vport: The virtual port for which this call is being executed.
2815  * @lpfc_cmd: Pointer to lpfc_scsi_buf data structure.
2816  * @lun: Logical unit number.
2817  * @task_mgmt_cmd: SCSI task management command.
2818  *
2819  * This routine creates FCP information unit corresponding to @task_mgmt_cmd
2820  * for device with SLI-3 interface spec.
2821  *
2822  * Return codes:
2823  *   0 - Error
2824  *   1 - Success
2825  **/
2826 static int
2827 lpfc_scsi_prep_task_mgmt_cmd(struct lpfc_vport *vport,
2828                              struct lpfc_scsi_buf *lpfc_cmd,
2829                              unsigned int lun,
2830                              uint8_t task_mgmt_cmd)
2831 {
2832         struct lpfc_iocbq *piocbq;
2833         IOCB_t *piocb;
2834         struct fcp_cmnd *fcp_cmnd;
2835         struct lpfc_rport_data *rdata = lpfc_cmd->rdata;
2836         struct lpfc_nodelist *ndlp = rdata->pnode;
2837
2838         if (!ndlp || !NLP_CHK_NODE_ACT(ndlp) ||
2839             ndlp->nlp_state != NLP_STE_MAPPED_NODE)
2840                 return 0;
2841
2842         piocbq = &(lpfc_cmd->cur_iocbq);
2843         piocbq->vport = vport;
2844
2845         piocb = &piocbq->iocb;
2846
2847         fcp_cmnd = lpfc_cmd->fcp_cmnd;
2848         /* Clear out any old data in the FCP command area */
2849         memset(fcp_cmnd, 0, sizeof(struct fcp_cmnd));
2850         int_to_scsilun(lun, &fcp_cmnd->fcp_lun);
2851         fcp_cmnd->fcpCntl2 = task_mgmt_cmd;
2852         if (vport->phba->sli_rev == 3 &&
2853             !(vport->phba->sli3_options & LPFC_SLI3_BG_ENABLED))
2854                 lpfc_fcpcmd_to_iocb(piocb->unsli3.fcp_ext.icd, fcp_cmnd);
2855         piocb->ulpCommand = CMD_FCP_ICMND64_CR;
2856         piocb->ulpContext = ndlp->nlp_rpi;
2857         if (ndlp->nlp_fcp_info & NLP_FCP_2_DEVICE) {
2858                 piocb->ulpFCP2Rcvy = 1;
2859         }
2860         piocb->ulpClass = (ndlp->nlp_fcp_info & 0x0f);
2861
2862         /* ulpTimeout is only one byte */
2863         if (lpfc_cmd->timeout > 0xff) {
2864                 /*
2865                  * Do not timeout the command at the firmware level.
2866                  * The driver will provide the timeout mechanism.
2867                  */
2868                 piocb->ulpTimeout = 0;
2869         } else
2870                 piocb->ulpTimeout = lpfc_cmd->timeout;
2871
2872         if (vport->phba->sli_rev == LPFC_SLI_REV4)
2873                 lpfc_sli4_set_rsp_sgl_last(vport->phba, lpfc_cmd);
2874
2875         return 1;
2876 }
2877
2878 /**
2879  * lpfc_scsi_api_table_setup - Set up scsi api function jump table
2880  * @phba: The hba struct for which this call is being executed.
2881  * @dev_grp: The HBA PCI-Device group number.
2882  *
2883  * This routine sets up the SCSI interface API function jump table in @phba
2884  * struct.
2885  * Returns: 0 - success, -ENODEV - failure.
2886  **/
2887 int
2888 lpfc_scsi_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
2889 {
2890
2891         phba->lpfc_scsi_unprep_dma_buf = lpfc_scsi_unprep_dma_buf;
2892         phba->lpfc_scsi_prep_cmnd = lpfc_scsi_prep_cmnd;
2893
2894         switch (dev_grp) {
2895         case LPFC_PCI_DEV_LP:
2896                 phba->lpfc_new_scsi_buf = lpfc_new_scsi_buf_s3;
2897                 phba->lpfc_scsi_prep_dma_buf = lpfc_scsi_prep_dma_buf_s3;
2898                 phba->lpfc_release_scsi_buf = lpfc_release_scsi_buf_s3;
2899                 phba->lpfc_get_scsi_buf = lpfc_get_scsi_buf_s3;
2900                 break;
2901         case LPFC_PCI_DEV_OC:
2902                 phba->lpfc_new_scsi_buf = lpfc_new_scsi_buf_s4;
2903                 phba->lpfc_scsi_prep_dma_buf = lpfc_scsi_prep_dma_buf_s4;
2904                 phba->lpfc_release_scsi_buf = lpfc_release_scsi_buf_s4;
2905                 phba->lpfc_get_scsi_buf = lpfc_get_scsi_buf_s4;
2906                 break;
2907         default:
2908                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
2909                                 "1418 Invalid HBA PCI-device group: 0x%x\n",
2910                                 dev_grp);
2911                 return -ENODEV;
2912                 break;
2913         }
2914         phba->lpfc_rampdown_queue_depth = lpfc_rampdown_queue_depth;
2915         phba->lpfc_scsi_cmd_iocb_cmpl = lpfc_scsi_cmd_iocb_cmpl;
2916         return 0;
2917 }
2918
2919 /**
2920  * lpfc_taskmgmt_def_cmpl - IOCB completion routine for task management command
2921  * @phba: The Hba for which this call is being executed.
2922  * @cmdiocbq: Pointer to lpfc_iocbq data structure.
2923  * @rspiocbq: Pointer to lpfc_iocbq data structure.
2924  *
2925  * This routine is IOCB completion routine for device reset and target reset
2926  * routine. This routine release scsi buffer associated with lpfc_cmd.
2927  **/
2928 static void
2929 lpfc_tskmgmt_def_cmpl(struct lpfc_hba *phba,
2930                         struct lpfc_iocbq *cmdiocbq,
2931                         struct lpfc_iocbq *rspiocbq)
2932 {
2933         struct lpfc_scsi_buf *lpfc_cmd =
2934                 (struct lpfc_scsi_buf *) cmdiocbq->context1;
2935         if (lpfc_cmd)
2936                 lpfc_release_scsi_buf(phba, lpfc_cmd);
2937         return;
2938 }
2939
2940 /**
2941  * lpfc_info - Info entry point of scsi_host_template data structure
2942  * @host: The scsi host for which this call is being executed.
2943  *
2944  * This routine provides module information about hba.
2945  *
2946  * Reutrn code:
2947  *   Pointer to char - Success.
2948  **/
2949 const char *
2950 lpfc_info(struct Scsi_Host *host)
2951 {
2952         struct lpfc_vport *vport = (struct lpfc_vport *) host->hostdata;
2953         struct lpfc_hba   *phba = vport->phba;
2954         int len;
2955         static char  lpfcinfobuf[384];
2956
2957         memset(lpfcinfobuf,0,384);
2958         if (phba && phba->pcidev){
2959                 strncpy(lpfcinfobuf, phba->ModelDesc, 256);
2960                 len = strlen(lpfcinfobuf);
2961                 snprintf(lpfcinfobuf + len,
2962                         384-len,
2963                         " on PCI bus %02x device %02x irq %d",
2964                         phba->pcidev->bus->number,
2965                         phba->pcidev->devfn,
2966                         phba->pcidev->irq);
2967                 len = strlen(lpfcinfobuf);
2968                 if (phba->Port[0]) {
2969                         snprintf(lpfcinfobuf + len,
2970                                  384-len,
2971                                  " port %s",
2972                                  phba->Port);
2973                 }
2974                 len = strlen(lpfcinfobuf);
2975                 if (phba->sli4_hba.link_state.logical_speed) {
2976                         snprintf(lpfcinfobuf + len,
2977                                  384-len,
2978                                  " Logical Link Speed: %d Mbps",
2979                                  phba->sli4_hba.link_state.logical_speed * 10);
2980                 }
2981         }
2982         return lpfcinfobuf;
2983 }
2984
2985 /**
2986  * lpfc_poll_rearm_time - Routine to modify fcp_poll timer of hba
2987  * @phba: The Hba for which this call is being executed.
2988  *
2989  * This routine modifies fcp_poll_timer  field of @phba by cfg_poll_tmo.
2990  * The default value of cfg_poll_tmo is 10 milliseconds.
2991  **/
2992 static __inline__ void lpfc_poll_rearm_timer(struct lpfc_hba * phba)
2993 {
2994         unsigned long  poll_tmo_expires =
2995                 (jiffies + msecs_to_jiffies(phba->cfg_poll_tmo));
2996
2997         if (phba->sli.ring[LPFC_FCP_RING].txcmplq_cnt)
2998                 mod_timer(&phba->fcp_poll_timer,
2999                           poll_tmo_expires);
3000 }
3001
3002 /**
3003  * lpfc_poll_start_timer - Routine to start fcp_poll_timer of HBA
3004  * @phba: The Hba for which this call is being executed.
3005  *
3006  * This routine starts the fcp_poll_timer of @phba.
3007  **/
3008 void lpfc_poll_start_timer(struct lpfc_hba * phba)
3009 {
3010         lpfc_poll_rearm_timer(phba);
3011 }
3012
3013 /**
3014  * lpfc_poll_timeout - Restart polling timer
3015  * @ptr: Map to lpfc_hba data structure pointer.
3016  *
3017  * This routine restarts fcp_poll timer, when FCP ring  polling is enable
3018  * and FCP Ring interrupt is disable.
3019  **/
3020
3021 void lpfc_poll_timeout(unsigned long ptr)
3022 {
3023         struct lpfc_hba *phba = (struct lpfc_hba *) ptr;
3024
3025         if (phba->cfg_poll & ENABLE_FCP_RING_POLLING) {
3026                 lpfc_sli_handle_fast_ring_event(phba,
3027                         &phba->sli.ring[LPFC_FCP_RING], HA_R0RE_REQ);
3028
3029                 if (phba->cfg_poll & DISABLE_FCP_RING_INT)
3030                         lpfc_poll_rearm_timer(phba);
3031         }
3032 }
3033
3034 /**
3035  * lpfc_queuecommand - scsi_host_template queuecommand entry point
3036  * @cmnd: Pointer to scsi_cmnd data structure.
3037  * @done: Pointer to done routine.
3038  *
3039  * Driver registers this routine to scsi midlayer to submit a @cmd to process.
3040  * This routine prepares an IOCB from scsi command and provides to firmware.
3041  * The @done callback is invoked after driver finished processing the command.
3042  *
3043  * Return value :
3044  *   0 - Success
3045  *   SCSI_MLQUEUE_HOST_BUSY - Block all devices served by this host temporarily.
3046  **/
3047 static int
3048 lpfc_queuecommand_lck(struct scsi_cmnd *cmnd, void (*done) (struct scsi_cmnd *))
3049 {
3050         struct Scsi_Host  *shost = cmnd->device->host;
3051         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
3052         struct lpfc_hba   *phba = vport->phba;
3053         struct lpfc_rport_data *rdata = cmnd->device->hostdata;
3054         struct lpfc_nodelist *ndlp;
3055         struct lpfc_scsi_buf *lpfc_cmd;
3056         struct fc_rport *rport = starget_to_rport(scsi_target(cmnd->device));
3057         int err;
3058
3059         err = fc_remote_port_chkready(rport);
3060         if (err) {
3061                 cmnd->result = err;
3062                 goto out_fail_command;
3063         }
3064         ndlp = rdata->pnode;
3065
3066         if (!(phba->sli3_options & LPFC_SLI3_BG_ENABLED) &&
3067                 scsi_get_prot_op(cmnd) != SCSI_PROT_NORMAL) {
3068
3069                 lpfc_printf_log(phba, KERN_ERR, LOG_BG,
3070                                 "9058 BLKGRD: ERROR: rcvd protected cmd:%02x"
3071                                 " op:%02x str=%s without registering for"
3072                                 " BlockGuard - Rejecting command\n",
3073                                 cmnd->cmnd[0], scsi_get_prot_op(cmnd),
3074                                 dif_op_str[scsi_get_prot_op(cmnd)]);
3075                 goto out_fail_command;
3076         }
3077
3078         /*
3079          * Catch race where our node has transitioned, but the
3080          * transport is still transitioning.
3081          */
3082         if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
3083                 cmnd->result = ScsiResult(DID_IMM_RETRY, 0);
3084                 goto out_fail_command;
3085         }
3086         if (atomic_read(&ndlp->cmd_pending) >= ndlp->cmd_qdepth)
3087                 goto out_tgt_busy;
3088
3089         lpfc_cmd = lpfc_get_scsi_buf(phba, ndlp);
3090         if (lpfc_cmd == NULL) {
3091                 lpfc_rampdown_queue_depth(phba);
3092
3093                 lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
3094                                  "0707 driver's buffer pool is empty, "
3095                                  "IO busied\n");
3096                 goto out_host_busy;
3097         }
3098
3099         /*
3100          * Store the midlayer's command structure for the completion phase
3101          * and complete the command initialization.
3102          */
3103         lpfc_cmd->pCmd  = cmnd;
3104         lpfc_cmd->rdata = rdata;
3105         lpfc_cmd->timeout = 0;
3106         lpfc_cmd->start_time = jiffies;
3107         cmnd->host_scribble = (unsigned char *)lpfc_cmd;
3108         cmnd->scsi_done = done;
3109
3110         if (scsi_get_prot_op(cmnd) != SCSI_PROT_NORMAL) {
3111                 if (vport->phba->cfg_enable_bg) {
3112                         lpfc_printf_vlog(vport, KERN_WARNING, LOG_BG,
3113                                 "9033 BLKGRD: rcvd protected cmd:%02x op:%02x "
3114                                 "str=%s\n",
3115                                 cmnd->cmnd[0], scsi_get_prot_op(cmnd),
3116                                 dif_op_str[scsi_get_prot_op(cmnd)]);
3117                         lpfc_printf_vlog(vport, KERN_WARNING, LOG_BG,
3118                                 "9034 BLKGRD: CDB: %02x %02x %02x %02x %02x "
3119                                 "%02x %02x %02x %02x %02x\n",
3120                                 cmnd->cmnd[0], cmnd->cmnd[1], cmnd->cmnd[2],
3121                                 cmnd->cmnd[3], cmnd->cmnd[4], cmnd->cmnd[5],
3122                                 cmnd->cmnd[6], cmnd->cmnd[7], cmnd->cmnd[8],
3123                                 cmnd->cmnd[9]);
3124                         if (cmnd->cmnd[0] == READ_10)
3125                                 lpfc_printf_vlog(vport, KERN_WARNING, LOG_BG,
3126                                         "9035 BLKGRD: READ @ sector %llu, "
3127                                         "count %u\n",
3128                                         (unsigned long long)scsi_get_lba(cmnd),
3129                                         blk_rq_sectors(cmnd->request));
3130                         else if (cmnd->cmnd[0] == WRITE_10)
3131                                 lpfc_printf_vlog(vport, KERN_WARNING, LOG_BG,
3132                                         "9036 BLKGRD: WRITE @ sector %llu, "
3133                                         "count %u cmd=%p\n",
3134                                         (unsigned long long)scsi_get_lba(cmnd),
3135                                         blk_rq_sectors(cmnd->request),
3136                                         cmnd);
3137                 }
3138
3139                 err = lpfc_bg_scsi_prep_dma_buf(phba, lpfc_cmd);
3140         } else {
3141                 if (vport->phba->cfg_enable_bg) {
3142                         lpfc_printf_vlog(vport, KERN_WARNING, LOG_BG,
3143                                         "9038 BLKGRD: rcvd unprotected cmd:"
3144                                         "%02x op:%02x str=%s\n",
3145                                         cmnd->cmnd[0], scsi_get_prot_op(cmnd),
3146                                         dif_op_str[scsi_get_prot_op(cmnd)]);
3147                                 lpfc_printf_vlog(vport, KERN_WARNING, LOG_BG,
3148                                         "9039 BLKGRD: CDB: %02x %02x %02x "
3149                                         "%02x %02x %02x %02x %02x %02x %02x\n",
3150                                         cmnd->cmnd[0], cmnd->cmnd[1],
3151                                         cmnd->cmnd[2], cmnd->cmnd[3],
3152                                         cmnd->cmnd[4], cmnd->cmnd[5],
3153                                         cmnd->cmnd[6], cmnd->cmnd[7],
3154                                         cmnd->cmnd[8], cmnd->cmnd[9]);
3155                         if (cmnd->cmnd[0] == READ_10)
3156                                 lpfc_printf_vlog(vport, KERN_WARNING, LOG_BG,
3157                                         "9040 dbg: READ @ sector %llu, "
3158                                         "count %u\n",
3159                                         (unsigned long long)scsi_get_lba(cmnd),
3160                                          blk_rq_sectors(cmnd->request));
3161                         else if (cmnd->cmnd[0] == WRITE_10)
3162                                 lpfc_printf_vlog(vport, KERN_WARNING, LOG_BG,
3163                                          "9041 dbg: WRITE @ sector %llu, "
3164                                          "count %u cmd=%p\n",
3165                                          (unsigned long long)scsi_get_lba(cmnd),
3166                                          blk_rq_sectors(cmnd->request), cmnd);
3167                         else
3168                                 lpfc_printf_vlog(vport, KERN_WARNING, LOG_BG,
3169                                          "9042 dbg: parser not implemented\n");
3170                 }
3171                 err = lpfc_scsi_prep_dma_buf(phba, lpfc_cmd);
3172         }
3173
3174         if (err)
3175                 goto out_host_busy_free_buf;
3176
3177         lpfc_scsi_prep_cmnd(vport, lpfc_cmd, ndlp);
3178
3179         atomic_inc(&ndlp->cmd_pending);
3180         err = lpfc_sli_issue_iocb(phba, LPFC_FCP_RING,
3181                                   &lpfc_cmd->cur_iocbq, SLI_IOCB_RET_IOCB);
3182         if (err) {
3183                 atomic_dec(&ndlp->cmd_pending);
3184                 goto out_host_busy_free_buf;
3185         }
3186         if (phba->cfg_poll & ENABLE_FCP_RING_POLLING) {
3187                 spin_unlock(shost->host_lock);
3188                 lpfc_sli_handle_fast_ring_event(phba,
3189                         &phba->sli.ring[LPFC_FCP_RING], HA_R0RE_REQ);
3190
3191                 spin_lock(shost->host_lock);
3192                 if (phba->cfg_poll & DISABLE_FCP_RING_INT)
3193                         lpfc_poll_rearm_timer(phba);
3194         }
3195
3196         return 0;
3197
3198  out_host_busy_free_buf:
3199         lpfc_scsi_unprep_dma_buf(phba, lpfc_cmd);
3200         lpfc_release_scsi_buf(phba, lpfc_cmd);
3201  out_host_busy:
3202         return SCSI_MLQUEUE_HOST_BUSY;
3203
3204  out_tgt_busy:
3205         return SCSI_MLQUEUE_TARGET_BUSY;
3206
3207  out_fail_command:
3208         done(cmnd);
3209         return 0;
3210 }
3211
3212 static DEF_SCSI_QCMD(lpfc_queuecommand)
3213
3214 /**
3215  * lpfc_abort_handler - scsi_host_template eh_abort_handler entry point
3216  * @cmnd: Pointer to scsi_cmnd data structure.
3217  *
3218  * This routine aborts @cmnd pending in base driver.
3219  *
3220  * Return code :
3221  *   0x2003 - Error
3222  *   0x2002 - Success
3223  **/
3224 static int
3225 lpfc_abort_handler(struct scsi_cmnd *cmnd)
3226 {
3227         struct Scsi_Host  *shost = cmnd->device->host;
3228         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
3229         struct lpfc_hba   *phba = vport->phba;
3230         struct lpfc_iocbq *iocb;
3231         struct lpfc_iocbq *abtsiocb;
3232         struct lpfc_scsi_buf *lpfc_cmd;
3233         IOCB_t *cmd, *icmd;
3234         int ret = SUCCESS;
3235         DECLARE_WAIT_QUEUE_HEAD_ONSTACK(waitq);
3236
3237         ret = fc_block_scsi_eh(cmnd);
3238         if (ret)
3239                 return ret;
3240         lpfc_cmd = (struct lpfc_scsi_buf *)cmnd->host_scribble;
3241         if (!lpfc_cmd) {
3242                 lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
3243                          "2873 SCSI Layer I/O Abort Request IO CMPL Status "
3244                          "x%x ID %d LUN %d\n",
3245                          ret, cmnd->device->id, cmnd->device->lun);
3246                 return SUCCESS;
3247         }
3248
3249         /*
3250          * If pCmd field of the corresponding lpfc_scsi_buf structure
3251          * points to a different SCSI command, then the driver has
3252          * already completed this command, but the midlayer did not
3253          * see the completion before the eh fired.  Just return
3254          * SUCCESS.
3255          */
3256         iocb = &lpfc_cmd->cur_iocbq;
3257         if (lpfc_cmd->pCmd != cmnd)
3258                 goto out;
3259
3260         BUG_ON(iocb->context1 != lpfc_cmd);
3261
3262         abtsiocb = lpfc_sli_get_iocbq(phba);
3263         if (abtsiocb == NULL) {
3264                 ret = FAILED;
3265                 goto out;
3266         }
3267
3268         /*
3269          * The scsi command can not be in txq and it is in flight because the
3270          * pCmd is still pointig at the SCSI command we have to abort. There
3271          * is no need to search the txcmplq. Just send an abort to the FW.
3272          */
3273
3274         cmd = &iocb->iocb;
3275         icmd = &abtsiocb->iocb;
3276         icmd->un.acxri.abortType = ABORT_TYPE_ABTS;
3277         icmd->un.acxri.abortContextTag = cmd->ulpContext;
3278         if (phba->sli_rev == LPFC_SLI_REV4)
3279                 icmd->un.acxri.abortIoTag = iocb->sli4_xritag;
3280         else
3281                 icmd->un.acxri.abortIoTag = cmd->ulpIoTag;
3282
3283         icmd->ulpLe = 1;
3284         icmd->ulpClass = cmd->ulpClass;
3285
3286         /* ABTS WQE must go to the same WQ as the WQE to be aborted */
3287         abtsiocb->fcp_wqidx = iocb->fcp_wqidx;
3288         abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
3289
3290         if (lpfc_is_link_up(phba))
3291                 icmd->ulpCommand = CMD_ABORT_XRI_CN;
3292         else
3293                 icmd->ulpCommand = CMD_CLOSE_XRI_CN;
3294
3295         abtsiocb->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
3296         abtsiocb->vport = vport;
3297         if (lpfc_sli_issue_iocb(phba, LPFC_FCP_RING, abtsiocb, 0) ==
3298             IOCB_ERROR) {
3299                 lpfc_sli_release_iocbq(phba, abtsiocb);
3300                 ret = FAILED;
3301                 goto out;
3302         }
3303
3304         if (phba->cfg_poll & DISABLE_FCP_RING_INT)
3305                 lpfc_sli_handle_fast_ring_event(phba,
3306                         &phba->sli.ring[LPFC_FCP_RING], HA_R0RE_REQ);
3307
3308         lpfc_cmd->waitq = &waitq;
3309         /* Wait for abort to complete */
3310         wait_event_timeout(waitq,
3311                           (lpfc_cmd->pCmd != cmnd),
3312                            (2*vport->cfg_devloss_tmo*HZ));
3313
3314         spin_lock_irq(shost->host_lock);
3315         lpfc_cmd->waitq = NULL;
3316         spin_unlock_irq(shost->host_lock);
3317
3318         if (lpfc_cmd->pCmd == cmnd) {
3319                 ret = FAILED;
3320                 lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
3321                                  "0748 abort handler timed out waiting "
3322                                  "for abort to complete: ret %#x, ID %d, "
3323                                  "LUN %d\n",
3324                                  ret, cmnd->device->id, cmnd->device->lun);
3325         }
3326
3327  out:
3328         lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
3329                          "0749 SCSI Layer I/O Abort Request Status x%x ID %d "
3330                          "LUN %d\n", ret, cmnd->device->id,
3331                          cmnd->device->lun);
3332         return ret;
3333 }
3334
3335 static char *
3336 lpfc_taskmgmt_name(uint8_t task_mgmt_cmd)
3337 {
3338         switch (task_mgmt_cmd) {
3339         case FCP_ABORT_TASK_SET:
3340                 return "ABORT_TASK_SET";
3341         case FCP_CLEAR_TASK_SET:
3342                 return "FCP_CLEAR_TASK_SET";
3343         case FCP_BUS_RESET:
3344                 return "FCP_BUS_RESET";
3345         case FCP_LUN_RESET:
3346                 return "FCP_LUN_RESET";
3347         case FCP_TARGET_RESET:
3348                 return "FCP_TARGET_RESET";
3349         case FCP_CLEAR_ACA:
3350                 return "FCP_CLEAR_ACA";
3351         case FCP_TERMINATE_TASK:
3352                 return "FCP_TERMINATE_TASK";
3353         default:
3354                 return "unknown";
3355         }
3356 }
3357
3358 /**
3359  * lpfc_send_taskmgmt - Generic SCSI Task Mgmt Handler
3360  * @vport: The virtual port for which this call is being executed.
3361  * @rdata: Pointer to remote port local data
3362  * @tgt_id: Target ID of remote device.
3363  * @lun_id: Lun number for the TMF
3364  * @task_mgmt_cmd: type of TMF to send
3365  *
3366  * This routine builds and sends a TMF (SCSI Task Mgmt Function) to
3367  * a remote port.
3368  *
3369  * Return Code:
3370  *   0x2003 - Error
3371  *   0x2002 - Success.
3372  **/
3373 static int
3374 lpfc_send_taskmgmt(struct lpfc_vport *vport, struct lpfc_rport_data *rdata,
3375                     unsigned  tgt_id, unsigned int lun_id,
3376                     uint8_t task_mgmt_cmd)
3377 {
3378         struct lpfc_hba   *phba = vport->phba;
3379         struct lpfc_scsi_buf *lpfc_cmd;
3380         struct lpfc_iocbq *iocbq;
3381         struct lpfc_iocbq *iocbqrsp;
3382         struct lpfc_nodelist *pnode = rdata->pnode;
3383         int ret;
3384         int status;
3385
3386         if (!pnode || !NLP_CHK_NODE_ACT(pnode))
3387                 return FAILED;
3388
3389         lpfc_cmd = lpfc_get_scsi_buf(phba, rdata->pnode);
3390         if (lpfc_cmd == NULL)
3391                 return FAILED;
3392         lpfc_cmd->timeout = 60;
3393         lpfc_cmd->rdata = rdata;
3394
3395         status = lpfc_scsi_prep_task_mgmt_cmd(vport, lpfc_cmd, lun_id,
3396                                            task_mgmt_cmd);
3397         if (!status) {
3398                 lpfc_release_scsi_buf(phba, lpfc_cmd);
3399                 return FAILED;
3400         }
3401
3402         iocbq = &lpfc_cmd->cur_iocbq;
3403         iocbqrsp = lpfc_sli_get_iocbq(phba);
3404         if (iocbqrsp == NULL) {
3405                 lpfc_release_scsi_buf(phba, lpfc_cmd);
3406                 return FAILED;
3407         }
3408
3409         lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
3410                          "0702 Issue %s to TGT %d LUN %d "
3411                          "rpi x%x nlp_flag x%x\n",
3412                          lpfc_taskmgmt_name(task_mgmt_cmd), tgt_id, lun_id,
3413                          pnode->nlp_rpi, pnode->nlp_flag);
3414
3415         status = lpfc_sli_issue_iocb_wait(phba, LPFC_FCP_RING,
3416                                           iocbq, iocbqrsp, lpfc_cmd->timeout);
3417         if (status != IOCB_SUCCESS) {
3418                 if (status == IOCB_TIMEDOUT) {
3419                         iocbq->iocb_cmpl = lpfc_tskmgmt_def_cmpl;
3420                         ret = TIMEOUT_ERROR;
3421                 } else
3422                         ret = FAILED;
3423                 lpfc_cmd->status = IOSTAT_DRIVER_REJECT;
3424                 lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
3425                          "0727 TMF %s to TGT %d LUN %d failed (%d, %d)\n",
3426                          lpfc_taskmgmt_name(task_mgmt_cmd),
3427                          tgt_id, lun_id, iocbqrsp->iocb.ulpStatus,
3428                          iocbqrsp->iocb.un.ulpWord[4]);
3429         } else if (status == IOCB_BUSY)
3430                 ret = FAILED;
3431         else
3432                 ret = SUCCESS;
3433
3434         lpfc_sli_release_iocbq(phba, iocbqrsp);
3435
3436         if (ret != TIMEOUT_ERROR)
3437                 lpfc_release_scsi_buf(phba, lpfc_cmd);
3438
3439         return ret;
3440 }
3441
3442 /**
3443  * lpfc_chk_tgt_mapped -
3444  * @vport: The virtual port to check on
3445  * @cmnd: Pointer to scsi_cmnd data structure.
3446  *
3447  * This routine delays until the scsi target (aka rport) for the
3448  * command exists (is present and logged in) or we declare it non-existent.
3449  *
3450  * Return code :
3451  *  0x2003 - Error
3452  *  0x2002 - Success
3453  **/
3454 static int
3455 lpfc_chk_tgt_mapped(struct lpfc_vport *vport, struct scsi_cmnd *cmnd)
3456 {
3457         struct lpfc_rport_data *rdata = cmnd->device->hostdata;
3458         struct lpfc_nodelist *pnode;
3459         unsigned long later;
3460
3461         if (!rdata) {
3462                 lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
3463                         "0797 Tgt Map rport failure: rdata x%p\n", rdata);
3464                 return FAILED;
3465         }
3466         pnode = rdata->pnode;
3467         /*
3468          * If target is not in a MAPPED state, delay until
3469          * target is rediscovered or devloss timeout expires.
3470          */
3471         later = msecs_to_jiffies(2 * vport->cfg_devloss_tmo * 1000) + jiffies;
3472         while (time_after(later, jiffies)) {
3473                 if (!pnode || !NLP_CHK_NODE_ACT(pnode))
3474                         return FAILED;
3475                 if (pnode->nlp_state == NLP_STE_MAPPED_NODE)
3476                         return SUCCESS;
3477                 schedule_timeout_uninterruptible(msecs_to_jiffies(500));
3478                 rdata = cmnd->device->hostdata;
3479                 if (!rdata)
3480                         return FAILED;
3481                 pnode = rdata->pnode;
3482         }
3483         if (!pnode || !NLP_CHK_NODE_ACT(pnode) ||
3484             (pnode->nlp_state != NLP_STE_MAPPED_NODE))
3485                 return FAILED;
3486         return SUCCESS;
3487 }
3488
3489 /**
3490  * lpfc_reset_flush_io_context -
3491  * @vport: The virtual port (scsi_host) for the flush context
3492  * @tgt_id: If aborting by Target contect - specifies the target id
3493  * @lun_id: If aborting by Lun context - specifies the lun id
3494  * @context: specifies the context level to flush at.
3495  *
3496  * After a reset condition via TMF, we need to flush orphaned i/o
3497  * contexts from the adapter. This routine aborts any contexts
3498  * outstanding, then waits for their completions. The wait is
3499  * bounded by devloss_tmo though.
3500  *
3501  * Return code :
3502  *  0x2003 - Error
3503  *  0x2002 - Success
3504  **/
3505 static int
3506 lpfc_reset_flush_io_context(struct lpfc_vport *vport, uint16_t tgt_id,
3507                         uint64_t lun_id, lpfc_ctx_cmd context)
3508 {
3509         struct lpfc_hba   *phba = vport->phba;
3510         unsigned long later;
3511         int cnt;
3512
3513         cnt = lpfc_sli_sum_iocb(vport, tgt_id, lun_id, context);
3514         if (cnt)
3515                 lpfc_sli_abort_iocb(vport, &phba->sli.ring[phba->sli.fcp_ring],
3516                                     tgt_id, lun_id, context);
3517         later = msecs_to_jiffies(2 * vport->cfg_devloss_tmo * 1000) + jiffies;
3518         while (time_after(later, jiffies) && cnt) {
3519                 schedule_timeout_uninterruptible(msecs_to_jiffies(20));
3520                 cnt = lpfc_sli_sum_iocb(vport, tgt_id, lun_id, context);
3521         }
3522         if (cnt) {
3523                 lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
3524                         "0724 I/O flush failure for context %s : cnt x%x\n",
3525                         ((context == LPFC_CTX_LUN) ? "LUN" :
3526                          ((context == LPFC_CTX_TGT) ? "TGT" :
3527                           ((context == LPFC_CTX_HOST) ? "HOST" : "Unknown"))),
3528                         cnt);
3529                 return FAILED;
3530         }
3531         return SUCCESS;
3532 }
3533
3534 /**
3535  * lpfc_device_reset_handler - scsi_host_template eh_device_reset entry point
3536  * @cmnd: Pointer to scsi_cmnd data structure.
3537  *
3538  * This routine does a device reset by sending a LUN_RESET task management
3539  * command.
3540  *
3541  * Return code :
3542  *  0x2003 - Error
3543  *  0x2002 - Success
3544  **/
3545 static int
3546 lpfc_device_reset_handler(struct scsi_cmnd *cmnd)
3547 {
3548         struct Scsi_Host  *shost = cmnd->device->host;
3549         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
3550         struct lpfc_rport_data *rdata = cmnd->device->hostdata;
3551         struct lpfc_nodelist *pnode;
3552         unsigned tgt_id = cmnd->device->id;
3553         unsigned int lun_id = cmnd->device->lun;
3554         struct lpfc_scsi_event_header scsi_event;
3555         int status;
3556
3557         if (!rdata) {
3558                 lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
3559                         "0798 Device Reset rport failure: rdata x%p\n", rdata);
3560                 return FAILED;
3561         }
3562         pnode = rdata->pnode;
3563         status = fc_block_scsi_eh(cmnd);
3564         if (status)
3565                 return status;
3566
3567         status = lpfc_chk_tgt_mapped(vport, cmnd);
3568         if (status == FAILED) {
3569                 lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
3570                         "0721 Device Reset rport failure: rdata x%p\n", rdata);
3571                 return FAILED;
3572         }
3573
3574         scsi_event.event_type = FC_REG_SCSI_EVENT;
3575         scsi_event.subcategory = LPFC_EVENT_LUNRESET;
3576         scsi_event.lun = lun_id;
3577         memcpy(scsi_event.wwpn, &pnode->nlp_portname, sizeof(struct lpfc_name));
3578         memcpy(scsi_event.wwnn, &pnode->nlp_nodename, sizeof(struct lpfc_name));
3579
3580         fc_host_post_vendor_event(shost, fc_get_event_number(),
3581                 sizeof(scsi_event), (char *)&scsi_event, LPFC_NL_VENDOR_ID);
3582
3583         status = lpfc_send_taskmgmt(vport, rdata, tgt_id, lun_id,
3584                                                 FCP_LUN_RESET);
3585
3586         lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
3587                          "0713 SCSI layer issued Device Reset (%d, %d) "
3588                          "return x%x\n", tgt_id, lun_id, status);
3589
3590         /*
3591          * We have to clean up i/o as : they may be orphaned by the TMF;
3592          * or if the TMF failed, they may be in an indeterminate state.
3593          * So, continue on.
3594          * We will report success if all the i/o aborts successfully.
3595          */
3596         status = lpfc_reset_flush_io_context(vport, tgt_id, lun_id,
3597                                                 LPFC_CTX_LUN);
3598         return status;
3599 }
3600
3601 /**
3602  * lpfc_target_reset_handler - scsi_host_template eh_target_reset entry point
3603  * @cmnd: Pointer to scsi_cmnd data structure.
3604  *
3605  * This routine does a target reset by sending a TARGET_RESET task management
3606  * command.
3607  *
3608  * Return code :
3609  *  0x2003 - Error
3610  *  0x2002 - Success
3611  **/
3612 static int
3613 lpfc_target_reset_handler(struct scsi_cmnd *cmnd)
3614 {
3615         struct Scsi_Host  *shost = cmnd->device->host;
3616         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
3617         struct lpfc_rport_data *rdata = cmnd->device->hostdata;
3618         struct lpfc_nodelist *pnode;
3619         unsigned tgt_id = cmnd->device->id;
3620         unsigned int lun_id = cmnd->device->lun;
3621         struct lpfc_scsi_event_header scsi_event;
3622         int status;
3623
3624         if (!rdata) {
3625                 lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
3626                         "0799 Target Reset rport failure: rdata x%p\n", rdata);
3627                 return FAILED;
3628         }
3629         pnode = rdata->pnode;
3630         status = fc_block_scsi_eh(cmnd);
3631         if (status)
3632                 return status;
3633
3634         status = lpfc_chk_tgt_mapped(vport, cmnd);
3635         if (status == FAILED) {
3636                 lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
3637                         "0722 Target Reset rport failure: rdata x%p\n", rdata);
3638                 return FAILED;
3639         }
3640
3641         scsi_event.event_type = FC_REG_SCSI_EVENT;
3642         scsi_event.subcategory = LPFC_EVENT_TGTRESET;
3643         scsi_event.lun = 0;
3644         memcpy(scsi_event.wwpn, &pnode->nlp_portname, sizeof(struct lpfc_name));
3645         memcpy(scsi_event.wwnn, &pnode->nlp_nodename, sizeof(struct lpfc_name));
3646
3647         fc_host_post_vendor_event(shost, fc_get_event_number(),
3648                 sizeof(scsi_event), (char *)&scsi_event, LPFC_NL_VENDOR_ID);
3649
3650         status = lpfc_send_taskmgmt(vport, rdata, tgt_id, lun_id,
3651                                         FCP_TARGET_RESET);
3652
3653         lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
3654                          "0723 SCSI layer issued Target Reset (%d, %d) "
3655                          "return x%x\n", tgt_id, lun_id, status);
3656
3657         /*
3658          * We have to clean up i/o as : they may be orphaned by the TMF;
3659          * or if the TMF failed, they may be in an indeterminate state.
3660          * So, continue on.
3661          * We will report success if all the i/o aborts successfully.
3662          */
3663         status = lpfc_reset_flush_io_context(vport, tgt_id, lun_id,
3664                                         LPFC_CTX_TGT);
3665         return status;
3666 }
3667
3668 /**
3669  * lpfc_bus_reset_handler - scsi_host_template eh_bus_reset_handler entry point
3670  * @cmnd: Pointer to scsi_cmnd data structure.
3671  *
3672  * This routine does target reset to all targets on @cmnd->device->host.
3673  * This emulates Parallel SCSI Bus Reset Semantics.
3674  *
3675  * Return code :
3676  *  0x2003 - Error
3677  *  0x2002 - Success
3678  **/
3679 static int
3680 lpfc_bus_reset_handler(struct scsi_cmnd *cmnd)
3681 {
3682         struct Scsi_Host  *shost = cmnd->device->host;
3683         struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
3684         struct lpfc_nodelist *ndlp = NULL;
3685         struct lpfc_scsi_event_header scsi_event;
3686         int match;
3687         int ret = SUCCESS, status, i;
3688
3689         scsi_event.event_type = FC_REG_SCSI_EVENT;
3690         scsi_event.subcategory = LPFC_EVENT_BUSRESET;
3691         scsi_event.lun = 0;
3692         memcpy(scsi_event.wwpn, &vport->fc_portname, sizeof(struct lpfc_name));
3693         memcpy(scsi_event.wwnn, &vport->fc_nodename, sizeof(struct lpfc_name));
3694
3695         fc_host_post_vendor_event(shost, fc_get_event_number(),
3696                 sizeof(scsi_event), (char *)&scsi_event, LPFC_NL_VENDOR_ID);
3697
3698         ret = fc_block_scsi_eh(cmnd);
3699         if (ret)
3700                 return ret;
3701
3702         /*
3703          * Since the driver manages a single bus device, reset all
3704          * targets known to the driver.  Should any target reset
3705          * fail, this routine returns failure to the midlayer.
3706          */
3707         for (i = 0; i < LPFC_MAX_TARGET; i++) {
3708                 /* Search for mapped node by target ID */
3709                 match = 0;
3710                 spin_lock_irq(shost->host_lock);
3711                 list_for_each_entry(ndlp, &vport->fc_nodes, nlp_listp) {
3712                         if (!NLP_CHK_NODE_ACT(ndlp))
3713                                 continue;
3714                         if (ndlp->nlp_state == NLP_STE_MAPPED_NODE &&
3715                             ndlp->nlp_sid == i &&
3716                             ndlp->rport) {
3717                                 match = 1;
3718                                 break;
3719                         }
3720                 }
3721                 spin_unlock_irq(shost->host_lock);
3722                 if (!match)
3723                         continue;
3724
3725                 status = lpfc_send_taskmgmt(vport, ndlp->rport->dd_data,
3726                                         i, 0, FCP_TARGET_RESET);
3727
3728                 if (status != SUCCESS) {
3729                         lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
3730                                          "0700 Bus Reset on target %d failed\n",
3731                                          i);
3732                         ret = FAILED;
3733                 }
3734         }
3735         /*
3736          * We have to clean up i/o as : they may be orphaned by the TMFs
3737          * above; or if any of the TMFs failed, they may be in an
3738          * indeterminate state.
3739          * We will report success if all the i/o aborts successfully.
3740          */
3741
3742         status = lpfc_reset_flush_io_context(vport, 0, 0, LPFC_CTX_HOST);
3743         if (status != SUCCESS)
3744                 ret = FAILED;
3745
3746         lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
3747                          "0714 SCSI layer issued Bus Reset Data: x%x\n", ret);
3748         return ret;
3749 }
3750
3751 /**
3752  * lpfc_slave_alloc - scsi_host_template slave_alloc entry point
3753  * @sdev: Pointer to scsi_device.
3754  *
3755  * This routine populates the cmds_per_lun count + 2 scsi_bufs into  this host's
3756  * globally available list of scsi buffers. This routine also makes sure scsi
3757  * buffer is not allocated more than HBA limit conveyed to midlayer. This list
3758  * of scsi buffer exists for the lifetime of the driver.
3759  *
3760  * Return codes:
3761  *   non-0 - Error
3762  *   0 - Success
3763  **/
3764 static int
3765 lpfc_slave_alloc(struct scsi_device *sdev)
3766 {
3767         struct lpfc_vport *vport = (struct lpfc_vport *) sdev->host->hostdata;
3768         struct lpfc_hba   *phba = vport->phba;
3769         struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
3770         uint32_t total = 0;
3771         uint32_t num_to_alloc = 0;
3772         int num_allocated = 0;
3773         uint32_t sdev_cnt;
3774
3775         if (!rport || fc_remote_port_chkready(rport))
3776                 return -ENXIO;
3777
3778         sdev->hostdata = rport->dd_data;
3779         sdev_cnt = atomic_inc_return(&phba->sdev_cnt);
3780
3781         /*
3782          * Populate the cmds_per_lun count scsi_bufs into this host's globally
3783          * available list of scsi buffers.  Don't allocate more than the
3784          * HBA limit conveyed to the midlayer via the host structure.  The
3785          * formula accounts for the lun_queue_depth + error handlers + 1
3786          * extra.  This list of scsi bufs exists for the lifetime of the driver.
3787          */
3788         total = phba->total_scsi_bufs;
3789         num_to_alloc = vport->cfg_lun_queue_depth + 2;
3790
3791         /* If allocated buffers are enough do nothing */
3792         if ((sdev_cnt * (vport->cfg_lun_queue_depth + 2)) < total)
3793                 return 0;
3794
3795         /* Allow some exchanges to be available always to complete discovery */
3796         if (total >= phba->cfg_hba_queue_depth - LPFC_DISC_IOCB_BUFF_COUNT ) {
3797                 lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
3798                                  "0704 At limitation of %d preallocated "
3799                                  "command buffers\n", total);
3800                 return 0;
3801         /* Allow some exchanges to be available always to complete discovery */
3802         } else if (total + num_to_alloc >
3803                 phba->cfg_hba_queue_depth - LPFC_DISC_IOCB_BUFF_COUNT ) {
3804                 lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
3805                                  "0705 Allocation request of %d "
3806                                  "command buffers will exceed max of %d.  "
3807                                  "Reducing allocation request to %d.\n",
3808                                  num_to_alloc, phba->cfg_hba_queue_depth,
3809                                  (phba->cfg_hba_queue_depth - total));
3810                 num_to_alloc = phba->cfg_hba_queue_depth - total;
3811         }
3812         num_allocated = lpfc_new_scsi_buf(vport, num_to_alloc);
3813         if (num_to_alloc != num_allocated) {
3814                         lpfc_printf_vlog(vport, KERN_WARNING, LOG_FCP,
3815                                  "0708 Allocation request of %d "
3816                                  "command buffers did not succeed.  "
3817                                  "Allocated %d buffers.\n",
3818                                  num_to_alloc, num_allocated);
3819         }
3820         if (num_allocated > 0)
3821                 phba->total_scsi_bufs += num_allocated;
3822         return 0;
3823 }
3824
3825 /**
3826  * lpfc_slave_configure - scsi_host_template slave_configure entry point
3827  * @sdev: Pointer to scsi_device.
3828  *
3829  * This routine configures following items
3830  *   - Tag command queuing support for @sdev if supported.
3831  *   - Enable SLI polling for fcp ring if ENABLE_FCP_RING_POLLING flag is set.
3832  *
3833  * Return codes:
3834  *   0 - Success
3835  **/
3836 static int
3837 lpfc_slave_configure(struct scsi_device *sdev)
3838 {
3839         struct lpfc_vport *vport = (struct lpfc_vport *) sdev->host->hostdata;
3840         struct lpfc_hba   *phba = vport->phba;
3841
3842         if (sdev->tagged_supported)
3843                 scsi_activate_tcq(sdev, vport->cfg_lun_queue_depth);
3844         else
3845                 scsi_deactivate_tcq(sdev, vport->cfg_lun_queue_depth);
3846
3847         if (phba->cfg_poll & ENABLE_FCP_RING_POLLING) {
3848                 lpfc_sli_handle_fast_ring_event(phba,
3849                         &phba->sli.ring[LPFC_FCP_RING], HA_R0RE_REQ);
3850                 if (phba->cfg_poll & DISABLE_FCP_RING_INT)
3851                         lpfc_poll_rearm_timer(phba);
3852         }
3853
3854         return 0;
3855 }
3856
3857 /**
3858  * lpfc_slave_destroy - slave_destroy entry point of SHT data structure
3859  * @sdev: Pointer to scsi_device.
3860  *
3861  * This routine sets @sdev hostatdata filed to null.
3862  **/
3863 static void
3864 lpfc_slave_destroy(struct scsi_device *sdev)
3865 {
3866         struct lpfc_vport *vport = (struct lpfc_vport *) sdev->host->hostdata;
3867         struct lpfc_hba   *phba = vport->phba;
3868         atomic_dec(&phba->sdev_cnt);
3869         sdev->hostdata = NULL;
3870         return;
3871 }
3872
3873
3874 struct scsi_host_template lpfc_template = {
3875         .module                 = THIS_MODULE,
3876         .name                   = LPFC_DRIVER_NAME,
3877         .info                   = lpfc_info,
3878         .queuecommand           = lpfc_queuecommand,
3879         .eh_abort_handler       = lpfc_abort_handler,
3880         .eh_device_reset_handler = lpfc_device_reset_handler,
3881         .eh_target_reset_handler = lpfc_target_reset_handler,
3882         .eh_bus_reset_handler   = lpfc_bus_reset_handler,
3883         .slave_alloc            = lpfc_slave_alloc,
3884         .slave_configure        = lpfc_slave_configure,
3885         .slave_destroy          = lpfc_slave_destroy,
3886         .scan_finished          = lpfc_scan_finished,
3887         .this_id                = -1,
3888         .sg_tablesize           = LPFC_DEFAULT_SG_SEG_CNT,
3889         .cmd_per_lun            = LPFC_CMD_PER_LUN,
3890         .use_clustering         = ENABLE_CLUSTERING,
3891         .shost_attrs            = lpfc_hba_attrs,
3892         .max_sectors            = 0xFFFF,
3893         .vendor_id              = LPFC_NL_VENDOR_ID,
3894         .change_queue_depth     = lpfc_change_queue_depth,
3895 };
3896
3897 struct scsi_host_template lpfc_vport_template = {
3898         .module                 = THIS_MODULE,
3899         .name                   = LPFC_DRIVER_NAME,
3900         .info                   = lpfc_info,
3901         .queuecommand           = lpfc_queuecommand,
3902         .eh_abort_handler       = lpfc_abort_handler,
3903         .eh_device_reset_handler = lpfc_device_reset_handler,
3904         .eh_target_reset_handler = lpfc_target_reset_handler,
3905         .eh_bus_reset_handler   = lpfc_bus_reset_handler,
3906         .slave_alloc            = lpfc_slave_alloc,
3907         .slave_configure        = lpfc_slave_configure,
3908         .slave_destroy          = lpfc_slave_destroy,
3909         .scan_finished          = lpfc_scan_finished,
3910         .this_id                = -1,
3911         .sg_tablesize           = LPFC_DEFAULT_SG_SEG_CNT,
3912         .cmd_per_lun            = LPFC_CMD_PER_LUN,
3913         .use_clustering         = ENABLE_CLUSTERING,
3914         .shost_attrs            = lpfc_vport_attrs,
3915         .max_sectors            = 0xFFFF,
3916         .change_queue_depth     = lpfc_change_queue_depth,
3917 };