]> Git Repo - linux.git/blob - drivers/scsi/mpt3sas/mpt3sas_base.c
scsi: mpt3sas: Split _base_reset_handler(), mpt3sas_scsih_reset_handler() and mpt3sas...
[linux.git] / drivers / scsi / mpt3sas / mpt3sas_base.c
1 /*
2  * This is the Fusion MPT base driver providing common API layer interface
3  * for access to MPT (Message Passing Technology) firmware.
4  *
5  * This code is based on drivers/scsi/mpt3sas/mpt3sas_base.c
6  * Copyright (C) 2012-2014  LSI Corporation
7  * Copyright (C) 2013-2014 Avago Technologies
8  *  (mailto: [email protected])
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * NO WARRANTY
21  * THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
22  * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
23  * LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
24  * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
25  * solely responsible for determining the appropriateness of using and
26  * distributing the Program and assumes all risks associated with its
27  * exercise of rights under this Agreement, including but not limited to
28  * the risks and costs of program errors, damage to or loss of data,
29  * programs or equipment, and unavailability or interruption of operations.
30
31  * DISCLAIMER OF LIABILITY
32  * NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
33  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
38  * HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
39
40  * You should have received a copy of the GNU General Public License
41  * along with this program; if not, write to the Free Software
42  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
43  * USA.
44  */
45
46 #include <linux/kernel.h>
47 #include <linux/module.h>
48 #include <linux/errno.h>
49 #include <linux/init.h>
50 #include <linux/slab.h>
51 #include <linux/types.h>
52 #include <linux/pci.h>
53 #include <linux/kdev_t.h>
54 #include <linux/blkdev.h>
55 #include <linux/delay.h>
56 #include <linux/interrupt.h>
57 #include <linux/dma-mapping.h>
58 #include <linux/io.h>
59 #include <linux/time.h>
60 #include <linux/ktime.h>
61 #include <linux/kthread.h>
62 #include <asm/page.h>        /* To get host page size per arch */
63 #include <linux/aer.h>
64
65
66 #include "mpt3sas_base.h"
67
68 static MPT_CALLBACK     mpt_callbacks[MPT_MAX_CALLBACKS];
69
70
71 #define FAULT_POLLING_INTERVAL 1000 /* in milliseconds */
72
73  /* maximum controller queue depth */
74 #define MAX_HBA_QUEUE_DEPTH     30000
75 #define MAX_CHAIN_DEPTH         100000
76 static int max_queue_depth = -1;
77 module_param(max_queue_depth, int, 0);
78 MODULE_PARM_DESC(max_queue_depth, " max controller queue depth ");
79
80 static int max_sgl_entries = -1;
81 module_param(max_sgl_entries, int, 0);
82 MODULE_PARM_DESC(max_sgl_entries, " max sg entries ");
83
84 static int msix_disable = -1;
85 module_param(msix_disable, int, 0);
86 MODULE_PARM_DESC(msix_disable, " disable msix routed interrupts (default=0)");
87
88 static int smp_affinity_enable = 1;
89 module_param(smp_affinity_enable, int, S_IRUGO);
90 MODULE_PARM_DESC(smp_affinity_enable, "SMP affinity feature enable/disable Default: enable(1)");
91
92 static int max_msix_vectors = -1;
93 module_param(max_msix_vectors, int, 0);
94 MODULE_PARM_DESC(max_msix_vectors,
95         " max msix vectors");
96
97 static int mpt3sas_fwfault_debug;
98 MODULE_PARM_DESC(mpt3sas_fwfault_debug,
99         " enable detection of firmware fault and halt firmware - (default=0)");
100
101 static int
102 _base_get_ioc_facts(struct MPT3SAS_ADAPTER *ioc);
103
104 /**
105  * mpt3sas_base_check_cmd_timeout - Function
106  *              to check timeout and command termination due
107  *              to Host reset.
108  *
109  * @ioc:        per adapter object.
110  * @status:     Status of issued command.
111  * @mpi_request:mf request pointer.
112  * @sz:         size of buffer.
113  *
114  * @Returns - 1/0 Reset to be done or Not
115  */
116 u8
117 mpt3sas_base_check_cmd_timeout(struct MPT3SAS_ADAPTER *ioc,
118                 u8 status, void *mpi_request, int sz)
119 {
120         u8 issue_reset = 0;
121
122         if (!(status & MPT3_CMD_RESET))
123                 issue_reset = 1;
124
125         pr_err(MPT3SAS_FMT "Command %s\n", ioc->name,
126             ((issue_reset == 0) ? "terminated due to Host Reset" : "Timeout"));
127         _debug_dump_mf(mpi_request, sz);
128
129         return issue_reset;
130 }
131
132 /**
133  * _scsih_set_fwfault_debug - global setting of ioc->fwfault_debug.
134  *
135  */
136 static int
137 _scsih_set_fwfault_debug(const char *val, const struct kernel_param *kp)
138 {
139         int ret = param_set_int(val, kp);
140         struct MPT3SAS_ADAPTER *ioc;
141
142         if (ret)
143                 return ret;
144
145         /* global ioc spinlock to protect controller list on list operations */
146         pr_info("setting fwfault_debug(%d)\n", mpt3sas_fwfault_debug);
147         spin_lock(&gioc_lock);
148         list_for_each_entry(ioc, &mpt3sas_ioc_list, list)
149                 ioc->fwfault_debug = mpt3sas_fwfault_debug;
150         spin_unlock(&gioc_lock);
151         return 0;
152 }
153 module_param_call(mpt3sas_fwfault_debug, _scsih_set_fwfault_debug,
154         param_get_int, &mpt3sas_fwfault_debug, 0644);
155
156 /**
157  * _base_clone_reply_to_sys_mem - copies reply to reply free iomem
158  *                                in BAR0 space.
159  *
160  * @ioc: per adapter object
161  * @reply: reply message frame(lower 32bit addr)
162  * @index: System request message index.
163  *
164  * @Returns - Nothing
165  */
166 static void
167 _base_clone_reply_to_sys_mem(struct MPT3SAS_ADAPTER *ioc, u32 reply,
168                 u32 index)
169 {
170         /*
171          * 256 is offset within sys register.
172          * 256 offset MPI frame starts. Max MPI frame supported is 32.
173          * 32 * 128 = 4K. From here, Clone of reply free for mcpu starts
174          */
175         u16 cmd_credit = ioc->facts.RequestCredit + 1;
176         void __iomem *reply_free_iomem = (void __iomem *)ioc->chip +
177                         MPI_FRAME_START_OFFSET +
178                         (cmd_credit * ioc->request_sz) + (index * sizeof(u32));
179
180         writel(reply, reply_free_iomem);
181 }
182
183 /**
184  * _base_clone_mpi_to_sys_mem - Writes/copies MPI frames
185  *                              to system/BAR0 region.
186  *
187  * @dst_iomem: Pointer to the destinaltion location in BAR0 space.
188  * @src: Pointer to the Source data.
189  * @size: Size of data to be copied.
190  */
191 static void
192 _base_clone_mpi_to_sys_mem(void *dst_iomem, void *src, u32 size)
193 {
194         int i;
195         u32 *src_virt_mem = (u32 *)src;
196
197         for (i = 0; i < size/4; i++)
198                 writel((u32)src_virt_mem[i],
199                                 (void __iomem *)dst_iomem + (i * 4));
200 }
201
202 /**
203  * _base_clone_to_sys_mem - Writes/copies data to system/BAR0 region
204  *
205  * @dst_iomem: Pointer to the destination location in BAR0 space.
206  * @src: Pointer to the Source data.
207  * @size: Size of data to be copied.
208  */
209 static void
210 _base_clone_to_sys_mem(void __iomem *dst_iomem, void *src, u32 size)
211 {
212         int i;
213         u32 *src_virt_mem = (u32 *)(src);
214
215         for (i = 0; i < size/4; i++)
216                 writel((u32)src_virt_mem[i],
217                         (void __iomem *)dst_iomem + (i * 4));
218 }
219
220 /**
221  * _base_get_chain - Calculates and Returns virtual chain address
222  *                       for the provided smid in BAR0 space.
223  *
224  * @ioc: per adapter object
225  * @smid: system request message index
226  * @sge_chain_count: Scatter gather chain count.
227  *
228  * @Return: chain address.
229  */
230 static inline void __iomem*
231 _base_get_chain(struct MPT3SAS_ADAPTER *ioc, u16 smid,
232                 u8 sge_chain_count)
233 {
234         void __iomem *base_chain, *chain_virt;
235         u16 cmd_credit = ioc->facts.RequestCredit + 1;
236
237         base_chain  = (void __iomem *)ioc->chip + MPI_FRAME_START_OFFSET +
238                 (cmd_credit * ioc->request_sz) +
239                 REPLY_FREE_POOL_SIZE;
240         chain_virt = base_chain + (smid * ioc->facts.MaxChainDepth *
241                         ioc->request_sz) + (sge_chain_count * ioc->request_sz);
242         return chain_virt;
243 }
244
245 /**
246  * _base_get_chain_phys - Calculates and Returns physical address
247  *                      in BAR0 for scatter gather chains, for
248  *                      the provided smid.
249  *
250  * @ioc: per adapter object
251  * @smid: system request message index
252  * @sge_chain_count: Scatter gather chain count.
253  *
254  * @Return - Physical chain address.
255  */
256 static inline phys_addr_t
257 _base_get_chain_phys(struct MPT3SAS_ADAPTER *ioc, u16 smid,
258                 u8 sge_chain_count)
259 {
260         phys_addr_t base_chain_phys, chain_phys;
261         u16 cmd_credit = ioc->facts.RequestCredit + 1;
262
263         base_chain_phys  = ioc->chip_phys + MPI_FRAME_START_OFFSET +
264                 (cmd_credit * ioc->request_sz) +
265                 REPLY_FREE_POOL_SIZE;
266         chain_phys = base_chain_phys + (smid * ioc->facts.MaxChainDepth *
267                         ioc->request_sz) + (sge_chain_count * ioc->request_sz);
268         return chain_phys;
269 }
270
271 /**
272  * _base_get_buffer_bar0 - Calculates and Returns BAR0 mapped Host
273  *                      buffer address for the provided smid.
274  *                      (Each smid can have 64K starts from 17024)
275  *
276  * @ioc: per adapter object
277  * @smid: system request message index
278  *
279  * @Returns - Pointer to buffer location in BAR0.
280  */
281
282 static void __iomem *
283 _base_get_buffer_bar0(struct MPT3SAS_ADAPTER *ioc, u16 smid)
284 {
285         u16 cmd_credit = ioc->facts.RequestCredit + 1;
286         // Added extra 1 to reach end of chain.
287         void __iomem *chain_end = _base_get_chain(ioc,
288                         cmd_credit + 1,
289                         ioc->facts.MaxChainDepth);
290         return chain_end + (smid * 64 * 1024);
291 }
292
293 /**
294  * _base_get_buffer_phys_bar0 - Calculates and Returns BAR0 mapped
295  *              Host buffer Physical address for the provided smid.
296  *              (Each smid can have 64K starts from 17024)
297  *
298  * @ioc: per adapter object
299  * @smid: system request message index
300  *
301  * @Returns - Pointer to buffer location in BAR0.
302  */
303 static phys_addr_t
304 _base_get_buffer_phys_bar0(struct MPT3SAS_ADAPTER *ioc, u16 smid)
305 {
306         u16 cmd_credit = ioc->facts.RequestCredit + 1;
307         phys_addr_t chain_end_phys = _base_get_chain_phys(ioc,
308                         cmd_credit + 1,
309                         ioc->facts.MaxChainDepth);
310         return chain_end_phys + (smid * 64 * 1024);
311 }
312
313 /**
314  * _base_get_chain_buffer_dma_to_chain_buffer - Iterates chain
315  *                      lookup list and Provides chain_buffer
316  *                      address for the matching dma address.
317  *                      (Each smid can have 64K starts from 17024)
318  *
319  * @ioc: per adapter object
320  * @chain_buffer_dma: Chain buffer dma address.
321  *
322  * @Returns - Pointer to chain buffer. Or Null on Failure.
323  */
324 static void *
325 _base_get_chain_buffer_dma_to_chain_buffer(struct MPT3SAS_ADAPTER *ioc,
326                 dma_addr_t chain_buffer_dma)
327 {
328         u16 index, j;
329         struct chain_tracker *ct;
330
331         for (index = 0; index < ioc->scsiio_depth; index++) {
332                 for (j = 0; j < ioc->chains_needed_per_io; j++) {
333                         ct = &ioc->chain_lookup[index].chains_per_smid[j];
334                         if (ct && ct->chain_buffer_dma == chain_buffer_dma)
335                                 return ct->chain_buffer;
336                 }
337         }
338         pr_info(MPT3SAS_FMT
339             "Provided chain_buffer_dma address is not in the lookup list\n",
340             ioc->name);
341         return NULL;
342 }
343
344 /**
345  * _clone_sg_entries -  MPI EP's scsiio and config requests
346  *                      are handled here. Base function for
347  *                      double buffering, before submitting
348  *                      the requests.
349  *
350  * @ioc: per adapter object.
351  * @mpi_request: mf request pointer.
352  * @smid: system request message index.
353  *
354  * @Returns: Nothing.
355  */
356 static void _clone_sg_entries(struct MPT3SAS_ADAPTER *ioc,
357                 void *mpi_request, u16 smid)
358 {
359         Mpi2SGESimple32_t *sgel, *sgel_next;
360         u32  sgl_flags, sge_chain_count = 0;
361         bool is_write = 0;
362         u16 i = 0;
363         void __iomem *buffer_iomem;
364         phys_addr_t buffer_iomem_phys;
365         void __iomem *buff_ptr;
366         phys_addr_t buff_ptr_phys;
367         void __iomem *dst_chain_addr[MCPU_MAX_CHAINS_PER_IO];
368         void *src_chain_addr[MCPU_MAX_CHAINS_PER_IO];
369         phys_addr_t dst_addr_phys;
370         MPI2RequestHeader_t *request_hdr;
371         struct scsi_cmnd *scmd;
372         struct scatterlist *sg_scmd = NULL;
373         int is_scsiio_req = 0;
374
375         request_hdr = (MPI2RequestHeader_t *) mpi_request;
376
377         if (request_hdr->Function == MPI2_FUNCTION_SCSI_IO_REQUEST) {
378                 Mpi25SCSIIORequest_t *scsiio_request =
379                         (Mpi25SCSIIORequest_t *)mpi_request;
380                 sgel = (Mpi2SGESimple32_t *) &scsiio_request->SGL;
381                 is_scsiio_req = 1;
382         } else if (request_hdr->Function == MPI2_FUNCTION_CONFIG) {
383                 Mpi2ConfigRequest_t  *config_req =
384                         (Mpi2ConfigRequest_t *)mpi_request;
385                 sgel = (Mpi2SGESimple32_t *) &config_req->PageBufferSGE;
386         } else
387                 return;
388
389         /* From smid we can get scsi_cmd, once we have sg_scmd,
390          * we just need to get sg_virt and sg_next to get virual
391          * address associated with sgel->Address.
392          */
393
394         if (is_scsiio_req) {
395                 /* Get scsi_cmd using smid */
396                 scmd = mpt3sas_scsih_scsi_lookup_get(ioc, smid);
397                 if (scmd == NULL) {
398                         pr_err(MPT3SAS_FMT "scmd is NULL\n", ioc->name);
399                         return;
400                 }
401
402                 /* Get sg_scmd from scmd provided */
403                 sg_scmd = scsi_sglist(scmd);
404         }
405
406         /*
407          * 0 - 255      System register
408          * 256 - 4352   MPI Frame. (This is based on maxCredit 32)
409          * 4352 - 4864  Reply_free pool (512 byte is reserved
410          *              considering maxCredit 32. Reply need extra
411          *              room, for mCPU case kept four times of
412          *              maxCredit).
413          * 4864 - 17152 SGE chain element. (32cmd * 3 chain of
414          *              128 byte size = 12288)
415          * 17152 - x    Host buffer mapped with smid.
416          *              (Each smid can have 64K Max IO.)
417          * BAR0+Last 1K MSIX Addr and Data
418          * Total size in use 2113664 bytes of 4MB BAR0
419          */
420
421         buffer_iomem = _base_get_buffer_bar0(ioc, smid);
422         buffer_iomem_phys = _base_get_buffer_phys_bar0(ioc, smid);
423
424         buff_ptr = buffer_iomem;
425         buff_ptr_phys = buffer_iomem_phys;
426         WARN_ON(buff_ptr_phys > U32_MAX);
427
428         if (le32_to_cpu(sgel->FlagsLength) &
429                         (MPI2_SGE_FLAGS_HOST_TO_IOC << MPI2_SGE_FLAGS_SHIFT))
430                 is_write = 1;
431
432         for (i = 0; i < MPT_MIN_PHYS_SEGMENTS + ioc->facts.MaxChainDepth; i++) {
433
434                 sgl_flags =
435                     (le32_to_cpu(sgel->FlagsLength) >> MPI2_SGE_FLAGS_SHIFT);
436
437                 switch (sgl_flags & MPI2_SGE_FLAGS_ELEMENT_MASK) {
438                 case MPI2_SGE_FLAGS_CHAIN_ELEMENT:
439                         /*
440                          * Helper function which on passing
441                          * chain_buffer_dma returns chain_buffer. Get
442                          * the virtual address for sgel->Address
443                          */
444                         sgel_next =
445                                 _base_get_chain_buffer_dma_to_chain_buffer(ioc,
446                                                 le32_to_cpu(sgel->Address));
447                         if (sgel_next == NULL)
448                                 return;
449                         /*
450                          * This is coping 128 byte chain
451                          * frame (not a host buffer)
452                          */
453                         dst_chain_addr[sge_chain_count] =
454                                 _base_get_chain(ioc,
455                                         smid, sge_chain_count);
456                         src_chain_addr[sge_chain_count] =
457                                                 (void *) sgel_next;
458                         dst_addr_phys = _base_get_chain_phys(ioc,
459                                                 smid, sge_chain_count);
460                         WARN_ON(dst_addr_phys > U32_MAX);
461                         sgel->Address =
462                                 cpu_to_le32(lower_32_bits(dst_addr_phys));
463                         sgel = sgel_next;
464                         sge_chain_count++;
465                         break;
466                 case MPI2_SGE_FLAGS_SIMPLE_ELEMENT:
467                         if (is_write) {
468                                 if (is_scsiio_req) {
469                                         _base_clone_to_sys_mem(buff_ptr,
470                                             sg_virt(sg_scmd),
471                                             (le32_to_cpu(sgel->FlagsLength) &
472                                             0x00ffffff));
473                                         /*
474                                          * FIXME: this relies on a a zero
475                                          * PCI mem_offset.
476                                          */
477                                         sgel->Address =
478                                             cpu_to_le32((u32)buff_ptr_phys);
479                                 } else {
480                                         _base_clone_to_sys_mem(buff_ptr,
481                                             ioc->config_vaddr,
482                                             (le32_to_cpu(sgel->FlagsLength) &
483                                             0x00ffffff));
484                                         sgel->Address =
485                                             cpu_to_le32((u32)buff_ptr_phys);
486                                 }
487                         }
488                         buff_ptr += (le32_to_cpu(sgel->FlagsLength) &
489                             0x00ffffff);
490                         buff_ptr_phys += (le32_to_cpu(sgel->FlagsLength) &
491                             0x00ffffff);
492                         if ((le32_to_cpu(sgel->FlagsLength) &
493                             (MPI2_SGE_FLAGS_END_OF_BUFFER
494                                         << MPI2_SGE_FLAGS_SHIFT)))
495                                 goto eob_clone_chain;
496                         else {
497                                 /*
498                                  * Every single element in MPT will have
499                                  * associated sg_next. Better to sanity that
500                                  * sg_next is not NULL, but it will be a bug
501                                  * if it is null.
502                                  */
503                                 if (is_scsiio_req) {
504                                         sg_scmd = sg_next(sg_scmd);
505                                         if (sg_scmd)
506                                                 sgel++;
507                                         else
508                                                 goto eob_clone_chain;
509                                 }
510                         }
511                         break;
512                 }
513         }
514
515 eob_clone_chain:
516         for (i = 0; i < sge_chain_count; i++) {
517                 if (is_scsiio_req)
518                         _base_clone_to_sys_mem(dst_chain_addr[i],
519                                 src_chain_addr[i], ioc->request_sz);
520         }
521 }
522
523 /**
524  *  mpt3sas_remove_dead_ioc_func - kthread context to remove dead ioc
525  * @arg: input argument, used to derive ioc
526  *
527  * Return 0 if controller is removed from pci subsystem.
528  * Return -1 for other case.
529  */
530 static int mpt3sas_remove_dead_ioc_func(void *arg)
531 {
532         struct MPT3SAS_ADAPTER *ioc = (struct MPT3SAS_ADAPTER *)arg;
533         struct pci_dev *pdev;
534
535         if ((ioc == NULL))
536                 return -1;
537
538         pdev = ioc->pdev;
539         if ((pdev == NULL))
540                 return -1;
541         pci_stop_and_remove_bus_device_locked(pdev);
542         return 0;
543 }
544
545 /**
546  * _base_fault_reset_work - workq handling ioc fault conditions
547  * @work: input argument, used to derive ioc
548  * Context: sleep.
549  *
550  * Return nothing.
551  */
552 static void
553 _base_fault_reset_work(struct work_struct *work)
554 {
555         struct MPT3SAS_ADAPTER *ioc =
556             container_of(work, struct MPT3SAS_ADAPTER, fault_reset_work.work);
557         unsigned long    flags;
558         u32 doorbell;
559         int rc;
560         struct task_struct *p;
561
562
563         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
564         if (ioc->shost_recovery || ioc->pci_error_recovery)
565                 goto rearm_timer;
566         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
567
568         doorbell = mpt3sas_base_get_iocstate(ioc, 0);
569         if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_MASK) {
570                 pr_err(MPT3SAS_FMT "SAS host is non-operational !!!!\n",
571                     ioc->name);
572
573                 /* It may be possible that EEH recovery can resolve some of
574                  * pci bus failure issues rather removing the dead ioc function
575                  * by considering controller is in a non-operational state. So
576                  * here priority is given to the EEH recovery. If it doesn't
577                  * not resolve this issue, mpt3sas driver will consider this
578                  * controller to non-operational state and remove the dead ioc
579                  * function.
580                  */
581                 if (ioc->non_operational_loop++ < 5) {
582                         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock,
583                                                          flags);
584                         goto rearm_timer;
585                 }
586
587                 /*
588                  * Call _scsih_flush_pending_cmds callback so that we flush all
589                  * pending commands back to OS. This call is required to aovid
590                  * deadlock at block layer. Dead IOC will fail to do diag reset,
591                  * and this call is safe since dead ioc will never return any
592                  * command back from HW.
593                  */
594                 ioc->schedule_dead_ioc_flush_running_cmds(ioc);
595                 /*
596                  * Set remove_host flag early since kernel thread will
597                  * take some time to execute.
598                  */
599                 ioc->remove_host = 1;
600                 /*Remove the Dead Host */
601                 p = kthread_run(mpt3sas_remove_dead_ioc_func, ioc,
602                     "%s_dead_ioc_%d", ioc->driver_name, ioc->id);
603                 if (IS_ERR(p))
604                         pr_err(MPT3SAS_FMT
605                         "%s: Running mpt3sas_dead_ioc thread failed !!!!\n",
606                         ioc->name, __func__);
607                 else
608                         pr_err(MPT3SAS_FMT
609                         "%s: Running mpt3sas_dead_ioc thread success !!!!\n",
610                         ioc->name, __func__);
611                 return; /* don't rearm timer */
612         }
613
614         ioc->non_operational_loop = 0;
615
616         if ((doorbell & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_OPERATIONAL) {
617                 rc = mpt3sas_base_hard_reset_handler(ioc, FORCE_BIG_HAMMER);
618                 pr_warn(MPT3SAS_FMT "%s: hard reset: %s\n", ioc->name,
619                     __func__, (rc == 0) ? "success" : "failed");
620                 doorbell = mpt3sas_base_get_iocstate(ioc, 0);
621                 if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT)
622                         mpt3sas_base_fault_info(ioc, doorbell &
623                             MPI2_DOORBELL_DATA_MASK);
624                 if (rc && (doorbell & MPI2_IOC_STATE_MASK) !=
625                     MPI2_IOC_STATE_OPERATIONAL)
626                         return; /* don't rearm timer */
627         }
628
629         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
630  rearm_timer:
631         if (ioc->fault_reset_work_q)
632                 queue_delayed_work(ioc->fault_reset_work_q,
633                     &ioc->fault_reset_work,
634                     msecs_to_jiffies(FAULT_POLLING_INTERVAL));
635         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
636 }
637
638 /**
639  * mpt3sas_base_start_watchdog - start the fault_reset_work_q
640  * @ioc: per adapter object
641  * Context: sleep.
642  *
643  * Return nothing.
644  */
645 void
646 mpt3sas_base_start_watchdog(struct MPT3SAS_ADAPTER *ioc)
647 {
648         unsigned long    flags;
649
650         if (ioc->fault_reset_work_q)
651                 return;
652
653         /* initialize fault polling */
654
655         INIT_DELAYED_WORK(&ioc->fault_reset_work, _base_fault_reset_work);
656         snprintf(ioc->fault_reset_work_q_name,
657             sizeof(ioc->fault_reset_work_q_name), "poll_%s%d_status",
658             ioc->driver_name, ioc->id);
659         ioc->fault_reset_work_q =
660                 create_singlethread_workqueue(ioc->fault_reset_work_q_name);
661         if (!ioc->fault_reset_work_q) {
662                 pr_err(MPT3SAS_FMT "%s: failed (line=%d)\n",
663                     ioc->name, __func__, __LINE__);
664                 return;
665         }
666         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
667         if (ioc->fault_reset_work_q)
668                 queue_delayed_work(ioc->fault_reset_work_q,
669                     &ioc->fault_reset_work,
670                     msecs_to_jiffies(FAULT_POLLING_INTERVAL));
671         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
672 }
673
674 /**
675  * mpt3sas_base_stop_watchdog - stop the fault_reset_work_q
676  * @ioc: per adapter object
677  * Context: sleep.
678  *
679  * Return nothing.
680  */
681 void
682 mpt3sas_base_stop_watchdog(struct MPT3SAS_ADAPTER *ioc)
683 {
684         unsigned long flags;
685         struct workqueue_struct *wq;
686
687         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
688         wq = ioc->fault_reset_work_q;
689         ioc->fault_reset_work_q = NULL;
690         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
691         if (wq) {
692                 if (!cancel_delayed_work_sync(&ioc->fault_reset_work))
693                         flush_workqueue(wq);
694                 destroy_workqueue(wq);
695         }
696 }
697
698 /**
699  * mpt3sas_base_fault_info - verbose translation of firmware FAULT code
700  * @ioc: per adapter object
701  * @fault_code: fault code
702  *
703  * Return nothing.
704  */
705 void
706 mpt3sas_base_fault_info(struct MPT3SAS_ADAPTER *ioc , u16 fault_code)
707 {
708         pr_err(MPT3SAS_FMT "fault_state(0x%04x)!\n",
709             ioc->name, fault_code);
710 }
711
712 /**
713  * mpt3sas_halt_firmware - halt's mpt controller firmware
714  * @ioc: per adapter object
715  *
716  * For debugging timeout related issues.  Writing 0xCOFFEE00
717  * to the doorbell register will halt controller firmware. With
718  * the purpose to stop both driver and firmware, the enduser can
719  * obtain a ring buffer from controller UART.
720  */
721 void
722 mpt3sas_halt_firmware(struct MPT3SAS_ADAPTER *ioc)
723 {
724         u32 doorbell;
725
726         if (!ioc->fwfault_debug)
727                 return;
728
729         dump_stack();
730
731         doorbell = readl(&ioc->chip->Doorbell);
732         if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT)
733                 mpt3sas_base_fault_info(ioc , doorbell);
734         else {
735                 writel(0xC0FFEE00, &ioc->chip->Doorbell);
736                 pr_err(MPT3SAS_FMT "Firmware is halted due to command timeout\n",
737                         ioc->name);
738         }
739
740         if (ioc->fwfault_debug == 2)
741                 for (;;)
742                         ;
743         else
744                 panic("panic in %s\n", __func__);
745 }
746
747 /**
748  * _base_sas_ioc_info - verbose translation of the ioc status
749  * @ioc: per adapter object
750  * @mpi_reply: reply mf payload returned from firmware
751  * @request_hdr: request mf
752  *
753  * Return nothing.
754  */
755 static void
756 _base_sas_ioc_info(struct MPT3SAS_ADAPTER *ioc, MPI2DefaultReply_t *mpi_reply,
757         MPI2RequestHeader_t *request_hdr)
758 {
759         u16 ioc_status = le16_to_cpu(mpi_reply->IOCStatus) &
760             MPI2_IOCSTATUS_MASK;
761         char *desc = NULL;
762         u16 frame_sz;
763         char *func_str = NULL;
764
765         /* SCSI_IO, RAID_PASS are handled from _scsih_scsi_ioc_info */
766         if (request_hdr->Function == MPI2_FUNCTION_SCSI_IO_REQUEST ||
767             request_hdr->Function == MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH ||
768             request_hdr->Function == MPI2_FUNCTION_EVENT_NOTIFICATION)
769                 return;
770
771         if (ioc_status == MPI2_IOCSTATUS_CONFIG_INVALID_PAGE)
772                 return;
773
774         switch (ioc_status) {
775
776 /****************************************************************************
777 *  Common IOCStatus values for all replies
778 ****************************************************************************/
779
780         case MPI2_IOCSTATUS_INVALID_FUNCTION:
781                 desc = "invalid function";
782                 break;
783         case MPI2_IOCSTATUS_BUSY:
784                 desc = "busy";
785                 break;
786         case MPI2_IOCSTATUS_INVALID_SGL:
787                 desc = "invalid sgl";
788                 break;
789         case MPI2_IOCSTATUS_INTERNAL_ERROR:
790                 desc = "internal error";
791                 break;
792         case MPI2_IOCSTATUS_INVALID_VPID:
793                 desc = "invalid vpid";
794                 break;
795         case MPI2_IOCSTATUS_INSUFFICIENT_RESOURCES:
796                 desc = "insufficient resources";
797                 break;
798         case MPI2_IOCSTATUS_INSUFFICIENT_POWER:
799                 desc = "insufficient power";
800                 break;
801         case MPI2_IOCSTATUS_INVALID_FIELD:
802                 desc = "invalid field";
803                 break;
804         case MPI2_IOCSTATUS_INVALID_STATE:
805                 desc = "invalid state";
806                 break;
807         case MPI2_IOCSTATUS_OP_STATE_NOT_SUPPORTED:
808                 desc = "op state not supported";
809                 break;
810
811 /****************************************************************************
812 *  Config IOCStatus values
813 ****************************************************************************/
814
815         case MPI2_IOCSTATUS_CONFIG_INVALID_ACTION:
816                 desc = "config invalid action";
817                 break;
818         case MPI2_IOCSTATUS_CONFIG_INVALID_TYPE:
819                 desc = "config invalid type";
820                 break;
821         case MPI2_IOCSTATUS_CONFIG_INVALID_PAGE:
822                 desc = "config invalid page";
823                 break;
824         case MPI2_IOCSTATUS_CONFIG_INVALID_DATA:
825                 desc = "config invalid data";
826                 break;
827         case MPI2_IOCSTATUS_CONFIG_NO_DEFAULTS:
828                 desc = "config no defaults";
829                 break;
830         case MPI2_IOCSTATUS_CONFIG_CANT_COMMIT:
831                 desc = "config cant commit";
832                 break;
833
834 /****************************************************************************
835 *  SCSI IO Reply
836 ****************************************************************************/
837
838         case MPI2_IOCSTATUS_SCSI_RECOVERED_ERROR:
839         case MPI2_IOCSTATUS_SCSI_INVALID_DEVHANDLE:
840         case MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
841         case MPI2_IOCSTATUS_SCSI_DATA_OVERRUN:
842         case MPI2_IOCSTATUS_SCSI_DATA_UNDERRUN:
843         case MPI2_IOCSTATUS_SCSI_IO_DATA_ERROR:
844         case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
845         case MPI2_IOCSTATUS_SCSI_TASK_TERMINATED:
846         case MPI2_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
847         case MPI2_IOCSTATUS_SCSI_TASK_MGMT_FAILED:
848         case MPI2_IOCSTATUS_SCSI_IOC_TERMINATED:
849         case MPI2_IOCSTATUS_SCSI_EXT_TERMINATED:
850                 break;
851
852 /****************************************************************************
853 *  For use by SCSI Initiator and SCSI Target end-to-end data protection
854 ****************************************************************************/
855
856         case MPI2_IOCSTATUS_EEDP_GUARD_ERROR:
857                 desc = "eedp guard error";
858                 break;
859         case MPI2_IOCSTATUS_EEDP_REF_TAG_ERROR:
860                 desc = "eedp ref tag error";
861                 break;
862         case MPI2_IOCSTATUS_EEDP_APP_TAG_ERROR:
863                 desc = "eedp app tag error";
864                 break;
865
866 /****************************************************************************
867 *  SCSI Target values
868 ****************************************************************************/
869
870         case MPI2_IOCSTATUS_TARGET_INVALID_IO_INDEX:
871                 desc = "target invalid io index";
872                 break;
873         case MPI2_IOCSTATUS_TARGET_ABORTED:
874                 desc = "target aborted";
875                 break;
876         case MPI2_IOCSTATUS_TARGET_NO_CONN_RETRYABLE:
877                 desc = "target no conn retryable";
878                 break;
879         case MPI2_IOCSTATUS_TARGET_NO_CONNECTION:
880                 desc = "target no connection";
881                 break;
882         case MPI2_IOCSTATUS_TARGET_XFER_COUNT_MISMATCH:
883                 desc = "target xfer count mismatch";
884                 break;
885         case MPI2_IOCSTATUS_TARGET_DATA_OFFSET_ERROR:
886                 desc = "target data offset error";
887                 break;
888         case MPI2_IOCSTATUS_TARGET_TOO_MUCH_WRITE_DATA:
889                 desc = "target too much write data";
890                 break;
891         case MPI2_IOCSTATUS_TARGET_IU_TOO_SHORT:
892                 desc = "target iu too short";
893                 break;
894         case MPI2_IOCSTATUS_TARGET_ACK_NAK_TIMEOUT:
895                 desc = "target ack nak timeout";
896                 break;
897         case MPI2_IOCSTATUS_TARGET_NAK_RECEIVED:
898                 desc = "target nak received";
899                 break;
900
901 /****************************************************************************
902 *  Serial Attached SCSI values
903 ****************************************************************************/
904
905         case MPI2_IOCSTATUS_SAS_SMP_REQUEST_FAILED:
906                 desc = "smp request failed";
907                 break;
908         case MPI2_IOCSTATUS_SAS_SMP_DATA_OVERRUN:
909                 desc = "smp data overrun";
910                 break;
911
912 /****************************************************************************
913 *  Diagnostic Buffer Post / Diagnostic Release values
914 ****************************************************************************/
915
916         case MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED:
917                 desc = "diagnostic released";
918                 break;
919         default:
920                 break;
921         }
922
923         if (!desc)
924                 return;
925
926         switch (request_hdr->Function) {
927         case MPI2_FUNCTION_CONFIG:
928                 frame_sz = sizeof(Mpi2ConfigRequest_t) + ioc->sge_size;
929                 func_str = "config_page";
930                 break;
931         case MPI2_FUNCTION_SCSI_TASK_MGMT:
932                 frame_sz = sizeof(Mpi2SCSITaskManagementRequest_t);
933                 func_str = "task_mgmt";
934                 break;
935         case MPI2_FUNCTION_SAS_IO_UNIT_CONTROL:
936                 frame_sz = sizeof(Mpi2SasIoUnitControlRequest_t);
937                 func_str = "sas_iounit_ctl";
938                 break;
939         case MPI2_FUNCTION_SCSI_ENCLOSURE_PROCESSOR:
940                 frame_sz = sizeof(Mpi2SepRequest_t);
941                 func_str = "enclosure";
942                 break;
943         case MPI2_FUNCTION_IOC_INIT:
944                 frame_sz = sizeof(Mpi2IOCInitRequest_t);
945                 func_str = "ioc_init";
946                 break;
947         case MPI2_FUNCTION_PORT_ENABLE:
948                 frame_sz = sizeof(Mpi2PortEnableRequest_t);
949                 func_str = "port_enable";
950                 break;
951         case MPI2_FUNCTION_SMP_PASSTHROUGH:
952                 frame_sz = sizeof(Mpi2SmpPassthroughRequest_t) + ioc->sge_size;
953                 func_str = "smp_passthru";
954                 break;
955         case MPI2_FUNCTION_NVME_ENCAPSULATED:
956                 frame_sz = sizeof(Mpi26NVMeEncapsulatedRequest_t) +
957                     ioc->sge_size;
958                 func_str = "nvme_encapsulated";
959                 break;
960         default:
961                 frame_sz = 32;
962                 func_str = "unknown";
963                 break;
964         }
965
966         pr_warn(MPT3SAS_FMT "ioc_status: %s(0x%04x), request(0x%p),(%s)\n",
967                 ioc->name, desc, ioc_status, request_hdr, func_str);
968
969         _debug_dump_mf(request_hdr, frame_sz/4);
970 }
971
972 /**
973  * _base_display_event_data - verbose translation of firmware asyn events
974  * @ioc: per adapter object
975  * @mpi_reply: reply mf payload returned from firmware
976  *
977  * Return nothing.
978  */
979 static void
980 _base_display_event_data(struct MPT3SAS_ADAPTER *ioc,
981         Mpi2EventNotificationReply_t *mpi_reply)
982 {
983         char *desc = NULL;
984         u16 event;
985
986         if (!(ioc->logging_level & MPT_DEBUG_EVENTS))
987                 return;
988
989         event = le16_to_cpu(mpi_reply->Event);
990
991         switch (event) {
992         case MPI2_EVENT_LOG_DATA:
993                 desc = "Log Data";
994                 break;
995         case MPI2_EVENT_STATE_CHANGE:
996                 desc = "Status Change";
997                 break;
998         case MPI2_EVENT_HARD_RESET_RECEIVED:
999                 desc = "Hard Reset Received";
1000                 break;
1001         case MPI2_EVENT_EVENT_CHANGE:
1002                 desc = "Event Change";
1003                 break;
1004         case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
1005                 desc = "Device Status Change";
1006                 break;
1007         case MPI2_EVENT_IR_OPERATION_STATUS:
1008                 if (!ioc->hide_ir_msg)
1009                         desc = "IR Operation Status";
1010                 break;
1011         case MPI2_EVENT_SAS_DISCOVERY:
1012         {
1013                 Mpi2EventDataSasDiscovery_t *event_data =
1014                     (Mpi2EventDataSasDiscovery_t *)mpi_reply->EventData;
1015                 pr_info(MPT3SAS_FMT "Discovery: (%s)", ioc->name,
1016                     (event_data->ReasonCode == MPI2_EVENT_SAS_DISC_RC_STARTED) ?
1017                     "start" : "stop");
1018                 if (event_data->DiscoveryStatus)
1019                         pr_cont(" discovery_status(0x%08x)",
1020                             le32_to_cpu(event_data->DiscoveryStatus));
1021                 pr_cont("\n");
1022                 return;
1023         }
1024         case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
1025                 desc = "SAS Broadcast Primitive";
1026                 break;
1027         case MPI2_EVENT_SAS_INIT_DEVICE_STATUS_CHANGE:
1028                 desc = "SAS Init Device Status Change";
1029                 break;
1030         case MPI2_EVENT_SAS_INIT_TABLE_OVERFLOW:
1031                 desc = "SAS Init Table Overflow";
1032                 break;
1033         case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
1034                 desc = "SAS Topology Change List";
1035                 break;
1036         case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
1037                 desc = "SAS Enclosure Device Status Change";
1038                 break;
1039         case MPI2_EVENT_IR_VOLUME:
1040                 if (!ioc->hide_ir_msg)
1041                         desc = "IR Volume";
1042                 break;
1043         case MPI2_EVENT_IR_PHYSICAL_DISK:
1044                 if (!ioc->hide_ir_msg)
1045                         desc = "IR Physical Disk";
1046                 break;
1047         case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
1048                 if (!ioc->hide_ir_msg)
1049                         desc = "IR Configuration Change List";
1050                 break;
1051         case MPI2_EVENT_LOG_ENTRY_ADDED:
1052                 if (!ioc->hide_ir_msg)
1053                         desc = "Log Entry Added";
1054                 break;
1055         case MPI2_EVENT_TEMP_THRESHOLD:
1056                 desc = "Temperature Threshold";
1057                 break;
1058         case MPI2_EVENT_ACTIVE_CABLE_EXCEPTION:
1059                 desc = "Cable Event";
1060                 break;
1061         case MPI2_EVENT_SAS_DEVICE_DISCOVERY_ERROR:
1062                 desc = "SAS Device Discovery Error";
1063                 break;
1064         case MPI2_EVENT_PCIE_DEVICE_STATUS_CHANGE:
1065                 desc = "PCIE Device Status Change";
1066                 break;
1067         case MPI2_EVENT_PCIE_ENUMERATION:
1068         {
1069                 Mpi26EventDataPCIeEnumeration_t *event_data =
1070                         (Mpi26EventDataPCIeEnumeration_t *)mpi_reply->EventData;
1071                 pr_info(MPT3SAS_FMT "PCIE Enumeration: (%s)", ioc->name,
1072                            (event_data->ReasonCode ==
1073                                 MPI26_EVENT_PCIE_ENUM_RC_STARTED) ?
1074                                 "start" : "stop");
1075                 if (event_data->EnumerationStatus)
1076                         pr_info("enumeration_status(0x%08x)",
1077                                    le32_to_cpu(event_data->EnumerationStatus));
1078                 pr_info("\n");
1079                 return;
1080         }
1081         case MPI2_EVENT_PCIE_TOPOLOGY_CHANGE_LIST:
1082                 desc = "PCIE Topology Change List";
1083                 break;
1084         }
1085
1086         if (!desc)
1087                 return;
1088
1089         pr_info(MPT3SAS_FMT "%s\n", ioc->name, desc);
1090 }
1091
1092 /**
1093  * _base_sas_log_info - verbose translation of firmware log info
1094  * @ioc: per adapter object
1095  * @log_info: log info
1096  *
1097  * Return nothing.
1098  */
1099 static void
1100 _base_sas_log_info(struct MPT3SAS_ADAPTER *ioc , u32 log_info)
1101 {
1102         union loginfo_type {
1103                 u32     loginfo;
1104                 struct {
1105                         u32     subcode:16;
1106                         u32     code:8;
1107                         u32     originator:4;
1108                         u32     bus_type:4;
1109                 } dw;
1110         };
1111         union loginfo_type sas_loginfo;
1112         char *originator_str = NULL;
1113
1114         sas_loginfo.loginfo = log_info;
1115         if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
1116                 return;
1117
1118         /* each nexus loss loginfo */
1119         if (log_info == 0x31170000)
1120                 return;
1121
1122         /* eat the loginfos associated with task aborts */
1123         if (ioc->ignore_loginfos && (log_info == 0x30050000 || log_info ==
1124             0x31140000 || log_info == 0x31130000))
1125                 return;
1126
1127         switch (sas_loginfo.dw.originator) {
1128         case 0:
1129                 originator_str = "IOP";
1130                 break;
1131         case 1:
1132                 originator_str = "PL";
1133                 break;
1134         case 2:
1135                 if (!ioc->hide_ir_msg)
1136                         originator_str = "IR";
1137                 else
1138                         originator_str = "WarpDrive";
1139                 break;
1140         }
1141
1142         pr_warn(MPT3SAS_FMT
1143                 "log_info(0x%08x): originator(%s), code(0x%02x), sub_code(0x%04x)\n",
1144                 ioc->name, log_info,
1145              originator_str, sas_loginfo.dw.code,
1146              sas_loginfo.dw.subcode);
1147 }
1148
1149 /**
1150  * _base_display_reply_info -
1151  * @ioc: per adapter object
1152  * @smid: system request message index
1153  * @msix_index: MSIX table index supplied by the OS
1154  * @reply: reply message frame(lower 32bit addr)
1155  *
1156  * Return nothing.
1157  */
1158 static void
1159 _base_display_reply_info(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
1160         u32 reply)
1161 {
1162         MPI2DefaultReply_t *mpi_reply;
1163         u16 ioc_status;
1164         u32 loginfo = 0;
1165
1166         mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
1167         if (unlikely(!mpi_reply)) {
1168                 pr_err(MPT3SAS_FMT "mpi_reply not valid at %s:%d/%s()!\n",
1169                     ioc->name, __FILE__, __LINE__, __func__);
1170                 return;
1171         }
1172         ioc_status = le16_to_cpu(mpi_reply->IOCStatus);
1173
1174         if ((ioc_status & MPI2_IOCSTATUS_MASK) &&
1175             (ioc->logging_level & MPT_DEBUG_REPLY)) {
1176                 _base_sas_ioc_info(ioc , mpi_reply,
1177                    mpt3sas_base_get_msg_frame(ioc, smid));
1178         }
1179
1180         if (ioc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
1181                 loginfo = le32_to_cpu(mpi_reply->IOCLogInfo);
1182                 _base_sas_log_info(ioc, loginfo);
1183         }
1184
1185         if (ioc_status || loginfo) {
1186                 ioc_status &= MPI2_IOCSTATUS_MASK;
1187                 mpt3sas_trigger_mpi(ioc, ioc_status, loginfo);
1188         }
1189 }
1190
1191 /**
1192  * mpt3sas_base_done - base internal command completion routine
1193  * @ioc: per adapter object
1194  * @smid: system request message index
1195  * @msix_index: MSIX table index supplied by the OS
1196  * @reply: reply message frame(lower 32bit addr)
1197  *
1198  * Return 1 meaning mf should be freed from _base_interrupt
1199  *        0 means the mf is freed from this function.
1200  */
1201 u8
1202 mpt3sas_base_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
1203         u32 reply)
1204 {
1205         MPI2DefaultReply_t *mpi_reply;
1206
1207         mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
1208         if (mpi_reply && mpi_reply->Function == MPI2_FUNCTION_EVENT_ACK)
1209                 return mpt3sas_check_for_pending_internal_cmds(ioc, smid);
1210
1211         if (ioc->base_cmds.status == MPT3_CMD_NOT_USED)
1212                 return 1;
1213
1214         ioc->base_cmds.status |= MPT3_CMD_COMPLETE;
1215         if (mpi_reply) {
1216                 ioc->base_cmds.status |= MPT3_CMD_REPLY_VALID;
1217                 memcpy(ioc->base_cmds.reply, mpi_reply, mpi_reply->MsgLength*4);
1218         }
1219         ioc->base_cmds.status &= ~MPT3_CMD_PENDING;
1220
1221         complete(&ioc->base_cmds.done);
1222         return 1;
1223 }
1224
1225 /**
1226  * _base_async_event - main callback handler for firmware asyn events
1227  * @ioc: per adapter object
1228  * @msix_index: MSIX table index supplied by the OS
1229  * @reply: reply message frame(lower 32bit addr)
1230  *
1231  * Return 1 meaning mf should be freed from _base_interrupt
1232  *        0 means the mf is freed from this function.
1233  */
1234 static u8
1235 _base_async_event(struct MPT3SAS_ADAPTER *ioc, u8 msix_index, u32 reply)
1236 {
1237         Mpi2EventNotificationReply_t *mpi_reply;
1238         Mpi2EventAckRequest_t *ack_request;
1239         u16 smid;
1240         struct _event_ack_list *delayed_event_ack;
1241
1242         mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
1243         if (!mpi_reply)
1244                 return 1;
1245         if (mpi_reply->Function != MPI2_FUNCTION_EVENT_NOTIFICATION)
1246                 return 1;
1247
1248         _base_display_event_data(ioc, mpi_reply);
1249
1250         if (!(mpi_reply->AckRequired & MPI2_EVENT_NOTIFICATION_ACK_REQUIRED))
1251                 goto out;
1252         smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
1253         if (!smid) {
1254                 delayed_event_ack = kzalloc(sizeof(*delayed_event_ack),
1255                                         GFP_ATOMIC);
1256                 if (!delayed_event_ack)
1257                         goto out;
1258                 INIT_LIST_HEAD(&delayed_event_ack->list);
1259                 delayed_event_ack->Event = mpi_reply->Event;
1260                 delayed_event_ack->EventContext = mpi_reply->EventContext;
1261                 list_add_tail(&delayed_event_ack->list,
1262                                 &ioc->delayed_event_ack_list);
1263                 dewtprintk(ioc, pr_info(MPT3SAS_FMT
1264                                 "DELAYED: EVENT ACK: event (0x%04x)\n",
1265                                 ioc->name, le16_to_cpu(mpi_reply->Event)));
1266                 goto out;
1267         }
1268
1269         ack_request = mpt3sas_base_get_msg_frame(ioc, smid);
1270         memset(ack_request, 0, sizeof(Mpi2EventAckRequest_t));
1271         ack_request->Function = MPI2_FUNCTION_EVENT_ACK;
1272         ack_request->Event = mpi_reply->Event;
1273         ack_request->EventContext = mpi_reply->EventContext;
1274         ack_request->VF_ID = 0;  /* TODO */
1275         ack_request->VP_ID = 0;
1276         mpt3sas_base_put_smid_default(ioc, smid);
1277
1278  out:
1279
1280         /* scsih callback handler */
1281         mpt3sas_scsih_event_callback(ioc, msix_index, reply);
1282
1283         /* ctl callback handler */
1284         mpt3sas_ctl_event_callback(ioc, msix_index, reply);
1285
1286         return 1;
1287 }
1288
1289 static struct scsiio_tracker *
1290 _get_st_from_smid(struct MPT3SAS_ADAPTER *ioc, u16 smid)
1291 {
1292         struct scsi_cmnd *cmd;
1293
1294         if (WARN_ON(!smid) ||
1295             WARN_ON(smid >= ioc->hi_priority_smid))
1296                 return NULL;
1297
1298         cmd = mpt3sas_scsih_scsi_lookup_get(ioc, smid);
1299         if (cmd)
1300                 return scsi_cmd_priv(cmd);
1301
1302         return NULL;
1303 }
1304
1305 /**
1306  * _base_get_cb_idx - obtain the callback index
1307  * @ioc: per adapter object
1308  * @smid: system request message index
1309  *
1310  * Return callback index.
1311  */
1312 static u8
1313 _base_get_cb_idx(struct MPT3SAS_ADAPTER *ioc, u16 smid)
1314 {
1315         int i;
1316         u16 ctl_smid = ioc->scsiio_depth - INTERNAL_SCSIIO_CMDS_COUNT + 1;
1317         u8 cb_idx = 0xFF;
1318
1319         if (smid < ioc->hi_priority_smid) {
1320                 struct scsiio_tracker *st;
1321
1322                 if (smid < ctl_smid) {
1323                         st = _get_st_from_smid(ioc, smid);
1324                         if (st)
1325                                 cb_idx = st->cb_idx;
1326                 } else if (smid == ctl_smid)
1327                         cb_idx = ioc->ctl_cb_idx;
1328         } else if (smid < ioc->internal_smid) {
1329                 i = smid - ioc->hi_priority_smid;
1330                 cb_idx = ioc->hpr_lookup[i].cb_idx;
1331         } else if (smid <= ioc->hba_queue_depth) {
1332                 i = smid - ioc->internal_smid;
1333                 cb_idx = ioc->internal_lookup[i].cb_idx;
1334         }
1335         return cb_idx;
1336 }
1337
1338 /**
1339  * _base_mask_interrupts - disable interrupts
1340  * @ioc: per adapter object
1341  *
1342  * Disabling ResetIRQ, Reply and Doorbell Interrupts
1343  *
1344  * Return nothing.
1345  */
1346 static void
1347 _base_mask_interrupts(struct MPT3SAS_ADAPTER *ioc)
1348 {
1349         u32 him_register;
1350
1351         ioc->mask_interrupts = 1;
1352         him_register = readl(&ioc->chip->HostInterruptMask);
1353         him_register |= MPI2_HIM_DIM + MPI2_HIM_RIM + MPI2_HIM_RESET_IRQ_MASK;
1354         writel(him_register, &ioc->chip->HostInterruptMask);
1355         readl(&ioc->chip->HostInterruptMask);
1356 }
1357
1358 /**
1359  * _base_unmask_interrupts - enable interrupts
1360  * @ioc: per adapter object
1361  *
1362  * Enabling only Reply Interrupts
1363  *
1364  * Return nothing.
1365  */
1366 static void
1367 _base_unmask_interrupts(struct MPT3SAS_ADAPTER *ioc)
1368 {
1369         u32 him_register;
1370
1371         him_register = readl(&ioc->chip->HostInterruptMask);
1372         him_register &= ~MPI2_HIM_RIM;
1373         writel(him_register, &ioc->chip->HostInterruptMask);
1374         ioc->mask_interrupts = 0;
1375 }
1376
1377 union reply_descriptor {
1378         u64 word;
1379         struct {
1380                 u32 low;
1381                 u32 high;
1382         } u;
1383 };
1384
1385 /**
1386  * _base_interrupt - MPT adapter (IOC) specific interrupt handler.
1387  * @irq: irq number (not used)
1388  * @bus_id: bus identifier cookie == pointer to MPT_ADAPTER structure
1389  * @r: pt_regs pointer (not used)
1390  *
1391  * Return IRQ_HANDLE if processed, else IRQ_NONE.
1392  */
1393 static irqreturn_t
1394 _base_interrupt(int irq, void *bus_id)
1395 {
1396         struct adapter_reply_queue *reply_q = bus_id;
1397         union reply_descriptor rd;
1398         u32 completed_cmds;
1399         u8 request_desript_type;
1400         u16 smid;
1401         u8 cb_idx;
1402         u32 reply;
1403         u8 msix_index = reply_q->msix_index;
1404         struct MPT3SAS_ADAPTER *ioc = reply_q->ioc;
1405         Mpi2ReplyDescriptorsUnion_t *rpf;
1406         u8 rc;
1407
1408         if (ioc->mask_interrupts)
1409                 return IRQ_NONE;
1410
1411         if (!atomic_add_unless(&reply_q->busy, 1, 1))
1412                 return IRQ_NONE;
1413
1414         rpf = &reply_q->reply_post_free[reply_q->reply_post_host_index];
1415         request_desript_type = rpf->Default.ReplyFlags
1416              & MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
1417         if (request_desript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED) {
1418                 atomic_dec(&reply_q->busy);
1419                 return IRQ_NONE;
1420         }
1421
1422         completed_cmds = 0;
1423         cb_idx = 0xFF;
1424         do {
1425                 rd.word = le64_to_cpu(rpf->Words);
1426                 if (rd.u.low == UINT_MAX || rd.u.high == UINT_MAX)
1427                         goto out;
1428                 reply = 0;
1429                 smid = le16_to_cpu(rpf->Default.DescriptorTypeDependent1);
1430                 if (request_desript_type ==
1431                     MPI25_RPY_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO_SUCCESS ||
1432                     request_desript_type ==
1433                     MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS ||
1434                     request_desript_type ==
1435                     MPI26_RPY_DESCRIPT_FLAGS_PCIE_ENCAPSULATED_SUCCESS) {
1436                         cb_idx = _base_get_cb_idx(ioc, smid);
1437                         if ((likely(cb_idx < MPT_MAX_CALLBACKS)) &&
1438                             (likely(mpt_callbacks[cb_idx] != NULL))) {
1439                                 rc = mpt_callbacks[cb_idx](ioc, smid,
1440                                     msix_index, 0);
1441                                 if (rc)
1442                                         mpt3sas_base_free_smid(ioc, smid);
1443                         }
1444                 } else if (request_desript_type ==
1445                     MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY) {
1446                         reply = le32_to_cpu(
1447                             rpf->AddressReply.ReplyFrameAddress);
1448                         if (reply > ioc->reply_dma_max_address ||
1449                             reply < ioc->reply_dma_min_address)
1450                                 reply = 0;
1451                         if (smid) {
1452                                 cb_idx = _base_get_cb_idx(ioc, smid);
1453                                 if ((likely(cb_idx < MPT_MAX_CALLBACKS)) &&
1454                                     (likely(mpt_callbacks[cb_idx] != NULL))) {
1455                                         rc = mpt_callbacks[cb_idx](ioc, smid,
1456                                             msix_index, reply);
1457                                         if (reply)
1458                                                 _base_display_reply_info(ioc,
1459                                                     smid, msix_index, reply);
1460                                         if (rc)
1461                                                 mpt3sas_base_free_smid(ioc,
1462                                                     smid);
1463                                 }
1464                         } else {
1465                                 _base_async_event(ioc, msix_index, reply);
1466                         }
1467
1468                         /* reply free queue handling */
1469                         if (reply) {
1470                                 ioc->reply_free_host_index =
1471                                     (ioc->reply_free_host_index ==
1472                                     (ioc->reply_free_queue_depth - 1)) ?
1473                                     0 : ioc->reply_free_host_index + 1;
1474                                 ioc->reply_free[ioc->reply_free_host_index] =
1475                                     cpu_to_le32(reply);
1476                                 if (ioc->is_mcpu_endpoint)
1477                                         _base_clone_reply_to_sys_mem(ioc,
1478                                                 reply,
1479                                                 ioc->reply_free_host_index);
1480                                 writel(ioc->reply_free_host_index,
1481                                     &ioc->chip->ReplyFreeHostIndex);
1482                         }
1483                 }
1484
1485                 rpf->Words = cpu_to_le64(ULLONG_MAX);
1486                 reply_q->reply_post_host_index =
1487                     (reply_q->reply_post_host_index ==
1488                     (ioc->reply_post_queue_depth - 1)) ? 0 :
1489                     reply_q->reply_post_host_index + 1;
1490                 request_desript_type =
1491                     reply_q->reply_post_free[reply_q->reply_post_host_index].
1492                     Default.ReplyFlags & MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
1493                 completed_cmds++;
1494                 /* Update the reply post host index after continuously
1495                  * processing the threshold number of Reply Descriptors.
1496                  * So that FW can find enough entries to post the Reply
1497                  * Descriptors in the reply descriptor post queue.
1498                  */
1499                 if (completed_cmds > ioc->hba_queue_depth/3) {
1500                         if (ioc->combined_reply_queue) {
1501                                 writel(reply_q->reply_post_host_index |
1502                                                 ((msix_index  & 7) <<
1503                                                  MPI2_RPHI_MSIX_INDEX_SHIFT),
1504                                     ioc->replyPostRegisterIndex[msix_index/8]);
1505                         } else {
1506                                 writel(reply_q->reply_post_host_index |
1507                                                 (msix_index <<
1508                                                  MPI2_RPHI_MSIX_INDEX_SHIFT),
1509                                                 &ioc->chip->ReplyPostHostIndex);
1510                         }
1511                         completed_cmds = 1;
1512                 }
1513                 if (request_desript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
1514                         goto out;
1515                 if (!reply_q->reply_post_host_index)
1516                         rpf = reply_q->reply_post_free;
1517                 else
1518                         rpf++;
1519         } while (1);
1520
1521  out:
1522
1523         if (!completed_cmds) {
1524                 atomic_dec(&reply_q->busy);
1525                 return IRQ_NONE;
1526         }
1527
1528         if (ioc->is_warpdrive) {
1529                 writel(reply_q->reply_post_host_index,
1530                 ioc->reply_post_host_index[msix_index]);
1531                 atomic_dec(&reply_q->busy);
1532                 return IRQ_HANDLED;
1533         }
1534
1535         /* Update Reply Post Host Index.
1536          * For those HBA's which support combined reply queue feature
1537          * 1. Get the correct Supplemental Reply Post Host Index Register.
1538          *    i.e. (msix_index / 8)th entry from Supplemental Reply Post Host
1539          *    Index Register address bank i.e replyPostRegisterIndex[],
1540          * 2. Then update this register with new reply host index value
1541          *    in ReplyPostIndex field and the MSIxIndex field with
1542          *    msix_index value reduced to a value between 0 and 7,
1543          *    using a modulo 8 operation. Since each Supplemental Reply Post
1544          *    Host Index Register supports 8 MSI-X vectors.
1545          *
1546          * For other HBA's just update the Reply Post Host Index register with
1547          * new reply host index value in ReplyPostIndex Field and msix_index
1548          * value in MSIxIndex field.
1549          */
1550         if (ioc->combined_reply_queue)
1551                 writel(reply_q->reply_post_host_index | ((msix_index  & 7) <<
1552                         MPI2_RPHI_MSIX_INDEX_SHIFT),
1553                         ioc->replyPostRegisterIndex[msix_index/8]);
1554         else
1555                 writel(reply_q->reply_post_host_index | (msix_index <<
1556                         MPI2_RPHI_MSIX_INDEX_SHIFT),
1557                         &ioc->chip->ReplyPostHostIndex);
1558         atomic_dec(&reply_q->busy);
1559         return IRQ_HANDLED;
1560 }
1561
1562 /**
1563  * _base_is_controller_msix_enabled - is controller support muli-reply queues
1564  * @ioc: per adapter object
1565  *
1566  */
1567 static inline int
1568 _base_is_controller_msix_enabled(struct MPT3SAS_ADAPTER *ioc)
1569 {
1570         return (ioc->facts.IOCCapabilities &
1571             MPI2_IOCFACTS_CAPABILITY_MSI_X_INDEX) && ioc->msix_enable;
1572 }
1573
1574 /**
1575  * mpt3sas_base_sync_reply_irqs - flush pending MSIX interrupts
1576  * @ioc: per adapter object
1577  * Context: non ISR conext
1578  *
1579  * Called when a Task Management request has completed.
1580  *
1581  * Return nothing.
1582  */
1583 void
1584 mpt3sas_base_sync_reply_irqs(struct MPT3SAS_ADAPTER *ioc)
1585 {
1586         struct adapter_reply_queue *reply_q;
1587
1588         /* If MSIX capability is turned off
1589          * then multi-queues are not enabled
1590          */
1591         if (!_base_is_controller_msix_enabled(ioc))
1592                 return;
1593
1594         list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
1595                 if (ioc->shost_recovery || ioc->remove_host ||
1596                                 ioc->pci_error_recovery)
1597                         return;
1598                 /* TMs are on msix_index == 0 */
1599                 if (reply_q->msix_index == 0)
1600                         continue;
1601                 synchronize_irq(pci_irq_vector(ioc->pdev, reply_q->msix_index));
1602         }
1603 }
1604
1605 /**
1606  * mpt3sas_base_release_callback_handler - clear interrupt callback handler
1607  * @cb_idx: callback index
1608  *
1609  * Return nothing.
1610  */
1611 void
1612 mpt3sas_base_release_callback_handler(u8 cb_idx)
1613 {
1614         mpt_callbacks[cb_idx] = NULL;
1615 }
1616
1617 /**
1618  * mpt3sas_base_register_callback_handler - obtain index for the interrupt callback handler
1619  * @cb_func: callback function
1620  *
1621  * Returns cb_func.
1622  */
1623 u8
1624 mpt3sas_base_register_callback_handler(MPT_CALLBACK cb_func)
1625 {
1626         u8 cb_idx;
1627
1628         for (cb_idx = MPT_MAX_CALLBACKS-1; cb_idx; cb_idx--)
1629                 if (mpt_callbacks[cb_idx] == NULL)
1630                         break;
1631
1632         mpt_callbacks[cb_idx] = cb_func;
1633         return cb_idx;
1634 }
1635
1636 /**
1637  * mpt3sas_base_initialize_callback_handler - initialize the interrupt callback handler
1638  *
1639  * Return nothing.
1640  */
1641 void
1642 mpt3sas_base_initialize_callback_handler(void)
1643 {
1644         u8 cb_idx;
1645
1646         for (cb_idx = 0; cb_idx < MPT_MAX_CALLBACKS; cb_idx++)
1647                 mpt3sas_base_release_callback_handler(cb_idx);
1648 }
1649
1650
1651 /**
1652  * _base_build_zero_len_sge - build zero length sg entry
1653  * @ioc: per adapter object
1654  * @paddr: virtual address for SGE
1655  *
1656  * Create a zero length scatter gather entry to insure the IOCs hardware has
1657  * something to use if the target device goes brain dead and tries
1658  * to send data even when none is asked for.
1659  *
1660  * Return nothing.
1661  */
1662 static void
1663 _base_build_zero_len_sge(struct MPT3SAS_ADAPTER *ioc, void *paddr)
1664 {
1665         u32 flags_length = (u32)((MPI2_SGE_FLAGS_LAST_ELEMENT |
1666             MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_END_OF_LIST |
1667             MPI2_SGE_FLAGS_SIMPLE_ELEMENT) <<
1668             MPI2_SGE_FLAGS_SHIFT);
1669         ioc->base_add_sg_single(paddr, flags_length, -1);
1670 }
1671
1672 /**
1673  * _base_add_sg_single_32 - Place a simple 32 bit SGE at address pAddr.
1674  * @paddr: virtual address for SGE
1675  * @flags_length: SGE flags and data transfer length
1676  * @dma_addr: Physical address
1677  *
1678  * Return nothing.
1679  */
1680 static void
1681 _base_add_sg_single_32(void *paddr, u32 flags_length, dma_addr_t dma_addr)
1682 {
1683         Mpi2SGESimple32_t *sgel = paddr;
1684
1685         flags_length |= (MPI2_SGE_FLAGS_32_BIT_ADDRESSING |
1686             MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT;
1687         sgel->FlagsLength = cpu_to_le32(flags_length);
1688         sgel->Address = cpu_to_le32(dma_addr);
1689 }
1690
1691
1692 /**
1693  * _base_add_sg_single_64 - Place a simple 64 bit SGE at address pAddr.
1694  * @paddr: virtual address for SGE
1695  * @flags_length: SGE flags and data transfer length
1696  * @dma_addr: Physical address
1697  *
1698  * Return nothing.
1699  */
1700 static void
1701 _base_add_sg_single_64(void *paddr, u32 flags_length, dma_addr_t dma_addr)
1702 {
1703         Mpi2SGESimple64_t *sgel = paddr;
1704
1705         flags_length |= (MPI2_SGE_FLAGS_64_BIT_ADDRESSING |
1706             MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT;
1707         sgel->FlagsLength = cpu_to_le32(flags_length);
1708         sgel->Address = cpu_to_le64(dma_addr);
1709 }
1710
1711 /**
1712  * _base_get_chain_buffer_tracker - obtain chain tracker
1713  * @ioc: per adapter object
1714  * @scmd: SCSI commands of the IO request
1715  *
1716  * Returns chain tracker from chain_lookup table using key as
1717  * smid and smid's chain_offset.
1718  */
1719 static struct chain_tracker *
1720 _base_get_chain_buffer_tracker(struct MPT3SAS_ADAPTER *ioc,
1721                                struct scsi_cmnd *scmd)
1722 {
1723         struct chain_tracker *chain_req;
1724         struct scsiio_tracker *st = scsi_cmd_priv(scmd);
1725         u16 smid = st->smid;
1726         u8 chain_offset =
1727            atomic_read(&ioc->chain_lookup[smid - 1].chain_offset);
1728
1729         if (chain_offset == ioc->chains_needed_per_io)
1730                 return NULL;
1731
1732         chain_req = &ioc->chain_lookup[smid - 1].chains_per_smid[chain_offset];
1733         atomic_inc(&ioc->chain_lookup[smid - 1].chain_offset);
1734         return chain_req;
1735 }
1736
1737
1738 /**
1739  * _base_build_sg - build generic sg
1740  * @ioc: per adapter object
1741  * @psge: virtual address for SGE
1742  * @data_out_dma: physical address for WRITES
1743  * @data_out_sz: data xfer size for WRITES
1744  * @data_in_dma: physical address for READS
1745  * @data_in_sz: data xfer size for READS
1746  *
1747  * Return nothing.
1748  */
1749 static void
1750 _base_build_sg(struct MPT3SAS_ADAPTER *ioc, void *psge,
1751         dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
1752         size_t data_in_sz)
1753 {
1754         u32 sgl_flags;
1755
1756         if (!data_out_sz && !data_in_sz) {
1757                 _base_build_zero_len_sge(ioc, psge);
1758                 return;
1759         }
1760
1761         if (data_out_sz && data_in_sz) {
1762                 /* WRITE sgel first */
1763                 sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
1764                     MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_HOST_TO_IOC);
1765                 sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1766                 ioc->base_add_sg_single(psge, sgl_flags |
1767                     data_out_sz, data_out_dma);
1768
1769                 /* incr sgel */
1770                 psge += ioc->sge_size;
1771
1772                 /* READ sgel last */
1773                 sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
1774                     MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
1775                     MPI2_SGE_FLAGS_END_OF_LIST);
1776                 sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1777                 ioc->base_add_sg_single(psge, sgl_flags |
1778                     data_in_sz, data_in_dma);
1779         } else if (data_out_sz) /* WRITE */ {
1780                 sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
1781                     MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
1782                     MPI2_SGE_FLAGS_END_OF_LIST | MPI2_SGE_FLAGS_HOST_TO_IOC);
1783                 sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1784                 ioc->base_add_sg_single(psge, sgl_flags |
1785                     data_out_sz, data_out_dma);
1786         } else if (data_in_sz) /* READ */ {
1787                 sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
1788                     MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
1789                     MPI2_SGE_FLAGS_END_OF_LIST);
1790                 sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1791                 ioc->base_add_sg_single(psge, sgl_flags |
1792                     data_in_sz, data_in_dma);
1793         }
1794 }
1795
1796 /* IEEE format sgls */
1797
1798 /**
1799  * _base_build_nvme_prp - This function is called for NVMe end devices to build
1800  * a native SGL (NVMe PRP). The native SGL is built starting in the first PRP
1801  * entry of the NVMe message (PRP1).  If the data buffer is small enough to be
1802  * described entirely using PRP1, then PRP2 is not used.  If needed, PRP2 is
1803  * used to describe a larger data buffer.  If the data buffer is too large to
1804  * describe using the two PRP entriess inside the NVMe message, then PRP1
1805  * describes the first data memory segment, and PRP2 contains a pointer to a PRP
1806  * list located elsewhere in memory to describe the remaining data memory
1807  * segments.  The PRP list will be contiguous.
1808
1809  * The native SGL for NVMe devices is a Physical Region Page (PRP).  A PRP
1810  * consists of a list of PRP entries to describe a number of noncontigous
1811  * physical memory segments as a single memory buffer, just as a SGL does.  Note
1812  * however, that this function is only used by the IOCTL call, so the memory
1813  * given will be guaranteed to be contiguous.  There is no need to translate
1814  * non-contiguous SGL into a PRP in this case.  All PRPs will describe
1815  * contiguous space that is one page size each.
1816  *
1817  * Each NVMe message contains two PRP entries.  The first (PRP1) either contains
1818  * a PRP list pointer or a PRP element, depending upon the command.  PRP2
1819  * contains the second PRP element if the memory being described fits within 2
1820  * PRP entries, or a PRP list pointer if the PRP spans more than two entries.
1821  *
1822  * A PRP list pointer contains the address of a PRP list, structured as a linear
1823  * array of PRP entries.  Each PRP entry in this list describes a segment of
1824  * physical memory.
1825  *
1826  * Each 64-bit PRP entry comprises an address and an offset field.  The address
1827  * always points at the beginning of a 4KB physical memory page, and the offset
1828  * describes where within that 4KB page the memory segment begins.  Only the
1829  * first element in a PRP list may contain a non-zero offest, implying that all
1830  * memory segments following the first begin at the start of a 4KB page.
1831  *
1832  * Each PRP element normally describes 4KB of physical memory, with exceptions
1833  * for the first and last elements in the list.  If the memory being described
1834  * by the list begins at a non-zero offset within the first 4KB page, then the
1835  * first PRP element will contain a non-zero offset indicating where the region
1836  * begins within the 4KB page.  The last memory segment may end before the end
1837  * of the 4KB segment, depending upon the overall size of the memory being
1838  * described by the PRP list.
1839  *
1840  * Since PRP entries lack any indication of size, the overall data buffer length
1841  * is used to determine where the end of the data memory buffer is located, and
1842  * how many PRP entries are required to describe it.
1843  *
1844  * @ioc: per adapter object
1845  * @smid: system request message index for getting asscociated SGL
1846  * @nvme_encap_request: the NVMe request msg frame pointer
1847  * @data_out_dma: physical address for WRITES
1848  * @data_out_sz: data xfer size for WRITES
1849  * @data_in_dma: physical address for READS
1850  * @data_in_sz: data xfer size for READS
1851  *
1852  * Returns nothing.
1853  */
1854 static void
1855 _base_build_nvme_prp(struct MPT3SAS_ADAPTER *ioc, u16 smid,
1856         Mpi26NVMeEncapsulatedRequest_t *nvme_encap_request,
1857         dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
1858         size_t data_in_sz)
1859 {
1860         int             prp_size = NVME_PRP_SIZE;
1861         __le64          *prp_entry, *prp1_entry, *prp2_entry;
1862         __le64          *prp_page;
1863         dma_addr_t      prp_entry_dma, prp_page_dma, dma_addr;
1864         u32             offset, entry_len;
1865         u32             page_mask_result, page_mask;
1866         size_t          length;
1867         struct mpt3sas_nvme_cmd *nvme_cmd =
1868                 (void *)nvme_encap_request->NVMe_Command;
1869
1870         /*
1871          * Not all commands require a data transfer. If no data, just return
1872          * without constructing any PRP.
1873          */
1874         if (!data_in_sz && !data_out_sz)
1875                 return;
1876         prp1_entry = &nvme_cmd->prp1;
1877         prp2_entry = &nvme_cmd->prp2;
1878         prp_entry = prp1_entry;
1879         /*
1880          * For the PRP entries, use the specially allocated buffer of
1881          * contiguous memory.
1882          */
1883         prp_page = (__le64 *)mpt3sas_base_get_pcie_sgl(ioc, smid);
1884         prp_page_dma = mpt3sas_base_get_pcie_sgl_dma(ioc, smid);
1885
1886         /*
1887          * Check if we are within 1 entry of a page boundary we don't
1888          * want our first entry to be a PRP List entry.
1889          */
1890         page_mask = ioc->page_size - 1;
1891         page_mask_result = (uintptr_t)((u8 *)prp_page + prp_size) & page_mask;
1892         if (!page_mask_result) {
1893                 /* Bump up to next page boundary. */
1894                 prp_page = (__le64 *)((u8 *)prp_page + prp_size);
1895                 prp_page_dma = prp_page_dma + prp_size;
1896         }
1897
1898         /*
1899          * Set PRP physical pointer, which initially points to the current PRP
1900          * DMA memory page.
1901          */
1902         prp_entry_dma = prp_page_dma;
1903
1904         /* Get physical address and length of the data buffer. */
1905         if (data_in_sz) {
1906                 dma_addr = data_in_dma;
1907                 length = data_in_sz;
1908         } else {
1909                 dma_addr = data_out_dma;
1910                 length = data_out_sz;
1911         }
1912
1913         /* Loop while the length is not zero. */
1914         while (length) {
1915                 /*
1916                  * Check if we need to put a list pointer here if we are at
1917                  * page boundary - prp_size (8 bytes).
1918                  */
1919                 page_mask_result = (prp_entry_dma + prp_size) & page_mask;
1920                 if (!page_mask_result) {
1921                         /*
1922                          * This is the last entry in a PRP List, so we need to
1923                          * put a PRP list pointer here.  What this does is:
1924                          *   - bump the current memory pointer to the next
1925                          *     address, which will be the next full page.
1926                          *   - set the PRP Entry to point to that page.  This
1927                          *     is now the PRP List pointer.
1928                          *   - bump the PRP Entry pointer the start of the
1929                          *     next page.  Since all of this PRP memory is
1930                          *     contiguous, no need to get a new page - it's
1931                          *     just the next address.
1932                          */
1933                         prp_entry_dma++;
1934                         *prp_entry = cpu_to_le64(prp_entry_dma);
1935                         prp_entry++;
1936                 }
1937
1938                 /* Need to handle if entry will be part of a page. */
1939                 offset = dma_addr & page_mask;
1940                 entry_len = ioc->page_size - offset;
1941
1942                 if (prp_entry == prp1_entry) {
1943                         /*
1944                          * Must fill in the first PRP pointer (PRP1) before
1945                          * moving on.
1946                          */
1947                         *prp1_entry = cpu_to_le64(dma_addr);
1948
1949                         /*
1950                          * Now point to the second PRP entry within the
1951                          * command (PRP2).
1952                          */
1953                         prp_entry = prp2_entry;
1954                 } else if (prp_entry == prp2_entry) {
1955                         /*
1956                          * Should the PRP2 entry be a PRP List pointer or just
1957                          * a regular PRP pointer?  If there is more than one
1958                          * more page of data, must use a PRP List pointer.
1959                          */
1960                         if (length > ioc->page_size) {
1961                                 /*
1962                                  * PRP2 will contain a PRP List pointer because
1963                                  * more PRP's are needed with this command. The
1964                                  * list will start at the beginning of the
1965                                  * contiguous buffer.
1966                                  */
1967                                 *prp2_entry = cpu_to_le64(prp_entry_dma);
1968
1969                                 /*
1970                                  * The next PRP Entry will be the start of the
1971                                  * first PRP List.
1972                                  */
1973                                 prp_entry = prp_page;
1974                         } else {
1975                                 /*
1976                                  * After this, the PRP Entries are complete.
1977                                  * This command uses 2 PRP's and no PRP list.
1978                                  */
1979                                 *prp2_entry = cpu_to_le64(dma_addr);
1980                         }
1981                 } else {
1982                         /*
1983                          * Put entry in list and bump the addresses.
1984                          *
1985                          * After PRP1 and PRP2 are filled in, this will fill in
1986                          * all remaining PRP entries in a PRP List, one per
1987                          * each time through the loop.
1988                          */
1989                         *prp_entry = cpu_to_le64(dma_addr);
1990                         prp_entry++;
1991                         prp_entry_dma++;
1992                 }
1993
1994                 /*
1995                  * Bump the phys address of the command's data buffer by the
1996                  * entry_len.
1997                  */
1998                 dma_addr += entry_len;
1999
2000                 /* Decrement length accounting for last partial page. */
2001                 if (entry_len > length)
2002                         length = 0;
2003                 else
2004                         length -= entry_len;
2005         }
2006 }
2007
2008 /**
2009  * base_make_prp_nvme -
2010  * Prepare PRPs(Physical Region Page)- SGLs specific to NVMe drives only
2011  *
2012  * @ioc:                per adapter object
2013  * @scmd:               SCSI command from the mid-layer
2014  * @mpi_request:        mpi request
2015  * @smid:               msg Index
2016  * @sge_count:          scatter gather element count.
2017  *
2018  * Returns:             true: PRPs are built
2019  *                      false: IEEE SGLs needs to be built
2020  */
2021 static void
2022 base_make_prp_nvme(struct MPT3SAS_ADAPTER *ioc,
2023                 struct scsi_cmnd *scmd,
2024                 Mpi25SCSIIORequest_t *mpi_request,
2025                 u16 smid, int sge_count)
2026 {
2027         int sge_len, num_prp_in_chain = 0;
2028         Mpi25IeeeSgeChain64_t *main_chain_element, *ptr_first_sgl;
2029         __le64 *curr_buff;
2030         dma_addr_t msg_dma, sge_addr, offset;
2031         u32 page_mask, page_mask_result;
2032         struct scatterlist *sg_scmd;
2033         u32 first_prp_len;
2034         int data_len = scsi_bufflen(scmd);
2035         u32 nvme_pg_size;
2036
2037         nvme_pg_size = max_t(u32, ioc->page_size, NVME_PRP_PAGE_SIZE);
2038         /*
2039          * Nvme has a very convoluted prp format.  One prp is required
2040          * for each page or partial page. Driver need to split up OS sg_list
2041          * entries if it is longer than one page or cross a page
2042          * boundary.  Driver also have to insert a PRP list pointer entry as
2043          * the last entry in each physical page of the PRP list.
2044          *
2045          * NOTE: The first PRP "entry" is actually placed in the first
2046          * SGL entry in the main message as IEEE 64 format.  The 2nd
2047          * entry in the main message is the chain element, and the rest
2048          * of the PRP entries are built in the contiguous pcie buffer.
2049          */
2050         page_mask = nvme_pg_size - 1;
2051
2052         /*
2053          * Native SGL is needed.
2054          * Put a chain element in main message frame that points to the first
2055          * chain buffer.
2056          *
2057          * NOTE:  The ChainOffset field must be 0 when using a chain pointer to
2058          *        a native SGL.
2059          */
2060
2061         /* Set main message chain element pointer */
2062         main_chain_element = (pMpi25IeeeSgeChain64_t)&mpi_request->SGL;
2063         /*
2064          * For NVMe the chain element needs to be the 2nd SG entry in the main
2065          * message.
2066          */
2067         main_chain_element = (Mpi25IeeeSgeChain64_t *)
2068                 ((u8 *)main_chain_element + sizeof(MPI25_IEEE_SGE_CHAIN64));
2069
2070         /*
2071          * For the PRP entries, use the specially allocated buffer of
2072          * contiguous memory.  Normal chain buffers can't be used
2073          * because each chain buffer would need to be the size of an OS
2074          * page (4k).
2075          */
2076         curr_buff = mpt3sas_base_get_pcie_sgl(ioc, smid);
2077         msg_dma = mpt3sas_base_get_pcie_sgl_dma(ioc, smid);
2078
2079         main_chain_element->Address = cpu_to_le64(msg_dma);
2080         main_chain_element->NextChainOffset = 0;
2081         main_chain_element->Flags = MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
2082                         MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
2083                         MPI26_IEEE_SGE_FLAGS_NSF_NVME_PRP;
2084
2085         /* Build first prp, sge need not to be page aligned*/
2086         ptr_first_sgl = (pMpi25IeeeSgeChain64_t)&mpi_request->SGL;
2087         sg_scmd = scsi_sglist(scmd);
2088         sge_addr = sg_dma_address(sg_scmd);
2089         sge_len = sg_dma_len(sg_scmd);
2090
2091         offset = sge_addr & page_mask;
2092         first_prp_len = nvme_pg_size - offset;
2093
2094         ptr_first_sgl->Address = cpu_to_le64(sge_addr);
2095         ptr_first_sgl->Length = cpu_to_le32(first_prp_len);
2096
2097         data_len -= first_prp_len;
2098
2099         if (sge_len > first_prp_len) {
2100                 sge_addr += first_prp_len;
2101                 sge_len -= first_prp_len;
2102         } else if (data_len && (sge_len == first_prp_len)) {
2103                 sg_scmd = sg_next(sg_scmd);
2104                 sge_addr = sg_dma_address(sg_scmd);
2105                 sge_len = sg_dma_len(sg_scmd);
2106         }
2107
2108         for (;;) {
2109                 offset = sge_addr & page_mask;
2110
2111                 /* Put PRP pointer due to page boundary*/
2112                 page_mask_result = (uintptr_t)(curr_buff + 1) & page_mask;
2113                 if (unlikely(!page_mask_result)) {
2114                         scmd_printk(KERN_NOTICE,
2115                                 scmd, "page boundary curr_buff: 0x%p\n",
2116                                 curr_buff);
2117                         msg_dma += 8;
2118                         *curr_buff = cpu_to_le64(msg_dma);
2119                         curr_buff++;
2120                         num_prp_in_chain++;
2121                 }
2122
2123                 *curr_buff = cpu_to_le64(sge_addr);
2124                 curr_buff++;
2125                 msg_dma += 8;
2126                 num_prp_in_chain++;
2127
2128                 sge_addr += nvme_pg_size;
2129                 sge_len -= nvme_pg_size;
2130                 data_len -= nvme_pg_size;
2131
2132                 if (data_len <= 0)
2133                         break;
2134
2135                 if (sge_len > 0)
2136                         continue;
2137
2138                 sg_scmd = sg_next(sg_scmd);
2139                 sge_addr = sg_dma_address(sg_scmd);
2140                 sge_len = sg_dma_len(sg_scmd);
2141         }
2142
2143         main_chain_element->Length =
2144                 cpu_to_le32(num_prp_in_chain * sizeof(u64));
2145         return;
2146 }
2147
2148 static bool
2149 base_is_prp_possible(struct MPT3SAS_ADAPTER *ioc,
2150         struct _pcie_device *pcie_device, struct scsi_cmnd *scmd, int sge_count)
2151 {
2152         u32 data_length = 0;
2153         bool build_prp = true;
2154
2155         data_length = scsi_bufflen(scmd);
2156
2157         /* If Datalenth is <= 16K and number of SGE’s entries are <= 2
2158          * we built IEEE SGL
2159          */
2160         if ((data_length <= NVME_PRP_PAGE_SIZE*4) && (sge_count <= 2))
2161                 build_prp = false;
2162
2163         return build_prp;
2164 }
2165
2166 /**
2167  * _base_check_pcie_native_sgl - This function is called for PCIe end devices to
2168  * determine if the driver needs to build a native SGL.  If so, that native
2169  * SGL is built in the special contiguous buffers allocated especially for
2170  * PCIe SGL creation.  If the driver will not build a native SGL, return
2171  * TRUE and a normal IEEE SGL will be built.  Currently this routine
2172  * supports NVMe.
2173  * @ioc: per adapter object
2174  * @mpi_request: mf request pointer
2175  * @smid: system request message index
2176  * @scmd: scsi command
2177  * @pcie_device: points to the PCIe device's info
2178  *
2179  * Returns 0 if native SGL was built, 1 if no SGL was built
2180  */
2181 static int
2182 _base_check_pcie_native_sgl(struct MPT3SAS_ADAPTER *ioc,
2183         Mpi25SCSIIORequest_t *mpi_request, u16 smid, struct scsi_cmnd *scmd,
2184         struct _pcie_device *pcie_device)
2185 {
2186         int sges_left;
2187
2188         /* Get the SG list pointer and info. */
2189         sges_left = scsi_dma_map(scmd);
2190         if (sges_left < 0) {
2191                 sdev_printk(KERN_ERR, scmd->device,
2192                         "scsi_dma_map failed: request for %d bytes!\n",
2193                         scsi_bufflen(scmd));
2194                 return 1;
2195         }
2196
2197         /* Check if we need to build a native SG list. */
2198         if (base_is_prp_possible(ioc, pcie_device,
2199                                 scmd, sges_left) == 0) {
2200                 /* We built a native SG list, just return. */
2201                 goto out;
2202         }
2203
2204         /*
2205          * Build native NVMe PRP.
2206          */
2207         base_make_prp_nvme(ioc, scmd, mpi_request,
2208                         smid, sges_left);
2209
2210         return 0;
2211 out:
2212         scsi_dma_unmap(scmd);
2213         return 1;
2214 }
2215
2216 /**
2217  * _base_add_sg_single_ieee - add sg element for IEEE format
2218  * @paddr: virtual address for SGE
2219  * @flags: SGE flags
2220  * @chain_offset: number of 128 byte elements from start of segment
2221  * @length: data transfer length
2222  * @dma_addr: Physical address
2223  *
2224  * Return nothing.
2225  */
2226 static void
2227 _base_add_sg_single_ieee(void *paddr, u8 flags, u8 chain_offset, u32 length,
2228         dma_addr_t dma_addr)
2229 {
2230         Mpi25IeeeSgeChain64_t *sgel = paddr;
2231
2232         sgel->Flags = flags;
2233         sgel->NextChainOffset = chain_offset;
2234         sgel->Length = cpu_to_le32(length);
2235         sgel->Address = cpu_to_le64(dma_addr);
2236 }
2237
2238 /**
2239  * _base_build_zero_len_sge_ieee - build zero length sg entry for IEEE format
2240  * @ioc: per adapter object
2241  * @paddr: virtual address for SGE
2242  *
2243  * Create a zero length scatter gather entry to insure the IOCs hardware has
2244  * something to use if the target device goes brain dead and tries
2245  * to send data even when none is asked for.
2246  *
2247  * Return nothing.
2248  */
2249 static void
2250 _base_build_zero_len_sge_ieee(struct MPT3SAS_ADAPTER *ioc, void *paddr)
2251 {
2252         u8 sgl_flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2253                 MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
2254                 MPI25_IEEE_SGE_FLAGS_END_OF_LIST);
2255
2256         _base_add_sg_single_ieee(paddr, sgl_flags, 0, 0, -1);
2257 }
2258
2259 /**
2260  * _base_build_sg_scmd - main sg creation routine
2261  *              pcie_device is unused here!
2262  * @ioc: per adapter object
2263  * @scmd: scsi command
2264  * @smid: system request message index
2265  * @unused: unused pcie_device pointer
2266  * Context: none.
2267  *
2268  * The main routine that builds scatter gather table from a given
2269  * scsi request sent via the .queuecommand main handler.
2270  *
2271  * Returns 0 success, anything else error
2272  */
2273 static int
2274 _base_build_sg_scmd(struct MPT3SAS_ADAPTER *ioc,
2275         struct scsi_cmnd *scmd, u16 smid, struct _pcie_device *unused)
2276 {
2277         Mpi2SCSIIORequest_t *mpi_request;
2278         dma_addr_t chain_dma;
2279         struct scatterlist *sg_scmd;
2280         void *sg_local, *chain;
2281         u32 chain_offset;
2282         u32 chain_length;
2283         u32 chain_flags;
2284         int sges_left;
2285         u32 sges_in_segment;
2286         u32 sgl_flags;
2287         u32 sgl_flags_last_element;
2288         u32 sgl_flags_end_buffer;
2289         struct chain_tracker *chain_req;
2290
2291         mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
2292
2293         /* init scatter gather flags */
2294         sgl_flags = MPI2_SGE_FLAGS_SIMPLE_ELEMENT;
2295         if (scmd->sc_data_direction == DMA_TO_DEVICE)
2296                 sgl_flags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
2297         sgl_flags_last_element = (sgl_flags | MPI2_SGE_FLAGS_LAST_ELEMENT)
2298             << MPI2_SGE_FLAGS_SHIFT;
2299         sgl_flags_end_buffer = (sgl_flags | MPI2_SGE_FLAGS_LAST_ELEMENT |
2300             MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_END_OF_LIST)
2301             << MPI2_SGE_FLAGS_SHIFT;
2302         sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
2303
2304         sg_scmd = scsi_sglist(scmd);
2305         sges_left = scsi_dma_map(scmd);
2306         if (sges_left < 0) {
2307                 sdev_printk(KERN_ERR, scmd->device,
2308                  "pci_map_sg failed: request for %d bytes!\n",
2309                  scsi_bufflen(scmd));
2310                 return -ENOMEM;
2311         }
2312
2313         sg_local = &mpi_request->SGL;
2314         sges_in_segment = ioc->max_sges_in_main_message;
2315         if (sges_left <= sges_in_segment)
2316                 goto fill_in_last_segment;
2317
2318         mpi_request->ChainOffset = (offsetof(Mpi2SCSIIORequest_t, SGL) +
2319             (sges_in_segment * ioc->sge_size))/4;
2320
2321         /* fill in main message segment when there is a chain following */
2322         while (sges_in_segment) {
2323                 if (sges_in_segment == 1)
2324                         ioc->base_add_sg_single(sg_local,
2325                             sgl_flags_last_element | sg_dma_len(sg_scmd),
2326                             sg_dma_address(sg_scmd));
2327                 else
2328                         ioc->base_add_sg_single(sg_local, sgl_flags |
2329                             sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2330                 sg_scmd = sg_next(sg_scmd);
2331                 sg_local += ioc->sge_size;
2332                 sges_left--;
2333                 sges_in_segment--;
2334         }
2335
2336         /* initializing the chain flags and pointers */
2337         chain_flags = MPI2_SGE_FLAGS_CHAIN_ELEMENT << MPI2_SGE_FLAGS_SHIFT;
2338         chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2339         if (!chain_req)
2340                 return -1;
2341         chain = chain_req->chain_buffer;
2342         chain_dma = chain_req->chain_buffer_dma;
2343         do {
2344                 sges_in_segment = (sges_left <=
2345                     ioc->max_sges_in_chain_message) ? sges_left :
2346                     ioc->max_sges_in_chain_message;
2347                 chain_offset = (sges_left == sges_in_segment) ?
2348                     0 : (sges_in_segment * ioc->sge_size)/4;
2349                 chain_length = sges_in_segment * ioc->sge_size;
2350                 if (chain_offset) {
2351                         chain_offset = chain_offset <<
2352                             MPI2_SGE_CHAIN_OFFSET_SHIFT;
2353                         chain_length += ioc->sge_size;
2354                 }
2355                 ioc->base_add_sg_single(sg_local, chain_flags | chain_offset |
2356                     chain_length, chain_dma);
2357                 sg_local = chain;
2358                 if (!chain_offset)
2359                         goto fill_in_last_segment;
2360
2361                 /* fill in chain segments */
2362                 while (sges_in_segment) {
2363                         if (sges_in_segment == 1)
2364                                 ioc->base_add_sg_single(sg_local,
2365                                     sgl_flags_last_element |
2366                                     sg_dma_len(sg_scmd),
2367                                     sg_dma_address(sg_scmd));
2368                         else
2369                                 ioc->base_add_sg_single(sg_local, sgl_flags |
2370                                     sg_dma_len(sg_scmd),
2371                                     sg_dma_address(sg_scmd));
2372                         sg_scmd = sg_next(sg_scmd);
2373                         sg_local += ioc->sge_size;
2374                         sges_left--;
2375                         sges_in_segment--;
2376                 }
2377
2378                 chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2379                 if (!chain_req)
2380                         return -1;
2381                 chain = chain_req->chain_buffer;
2382                 chain_dma = chain_req->chain_buffer_dma;
2383         } while (1);
2384
2385
2386  fill_in_last_segment:
2387
2388         /* fill the last segment */
2389         while (sges_left) {
2390                 if (sges_left == 1)
2391                         ioc->base_add_sg_single(sg_local, sgl_flags_end_buffer |
2392                             sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2393                 else
2394                         ioc->base_add_sg_single(sg_local, sgl_flags |
2395                             sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2396                 sg_scmd = sg_next(sg_scmd);
2397                 sg_local += ioc->sge_size;
2398                 sges_left--;
2399         }
2400
2401         return 0;
2402 }
2403
2404 /**
2405  * _base_build_sg_scmd_ieee - main sg creation routine for IEEE format
2406  * @ioc: per adapter object
2407  * @scmd: scsi command
2408  * @smid: system request message index
2409  * @pcie_device: Pointer to pcie_device. If set, the pcie native sgl will be
2410  * constructed on need.
2411  * Context: none.
2412  *
2413  * The main routine that builds scatter gather table from a given
2414  * scsi request sent via the .queuecommand main handler.
2415  *
2416  * Returns 0 success, anything else error
2417  */
2418 static int
2419 _base_build_sg_scmd_ieee(struct MPT3SAS_ADAPTER *ioc,
2420         struct scsi_cmnd *scmd, u16 smid, struct _pcie_device *pcie_device)
2421 {
2422         Mpi25SCSIIORequest_t *mpi_request;
2423         dma_addr_t chain_dma;
2424         struct scatterlist *sg_scmd;
2425         void *sg_local, *chain;
2426         u32 chain_offset;
2427         u32 chain_length;
2428         int sges_left;
2429         u32 sges_in_segment;
2430         u8 simple_sgl_flags;
2431         u8 simple_sgl_flags_last;
2432         u8 chain_sgl_flags;
2433         struct chain_tracker *chain_req;
2434
2435         mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
2436
2437         /* init scatter gather flags */
2438         simple_sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2439             MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2440         simple_sgl_flags_last = simple_sgl_flags |
2441             MPI25_IEEE_SGE_FLAGS_END_OF_LIST;
2442         chain_sgl_flags = MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
2443             MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2444
2445         /* Check if we need to build a native SG list. */
2446         if ((pcie_device) && (_base_check_pcie_native_sgl(ioc, mpi_request,
2447                         smid, scmd, pcie_device) == 0)) {
2448                 /* We built a native SG list, just return. */
2449                 return 0;
2450         }
2451
2452         sg_scmd = scsi_sglist(scmd);
2453         sges_left = scsi_dma_map(scmd);
2454         if (sges_left < 0) {
2455                 sdev_printk(KERN_ERR, scmd->device,
2456                         "pci_map_sg failed: request for %d bytes!\n",
2457                         scsi_bufflen(scmd));
2458                 return -ENOMEM;
2459         }
2460
2461         sg_local = &mpi_request->SGL;
2462         sges_in_segment = (ioc->request_sz -
2463                    offsetof(Mpi25SCSIIORequest_t, SGL))/ioc->sge_size_ieee;
2464         if (sges_left <= sges_in_segment)
2465                 goto fill_in_last_segment;
2466
2467         mpi_request->ChainOffset = (sges_in_segment - 1 /* chain element */) +
2468             (offsetof(Mpi25SCSIIORequest_t, SGL)/ioc->sge_size_ieee);
2469
2470         /* fill in main message segment when there is a chain following */
2471         while (sges_in_segment > 1) {
2472                 _base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
2473                     sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2474                 sg_scmd = sg_next(sg_scmd);
2475                 sg_local += ioc->sge_size_ieee;
2476                 sges_left--;
2477                 sges_in_segment--;
2478         }
2479
2480         /* initializing the pointers */
2481         chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2482         if (!chain_req)
2483                 return -1;
2484         chain = chain_req->chain_buffer;
2485         chain_dma = chain_req->chain_buffer_dma;
2486         do {
2487                 sges_in_segment = (sges_left <=
2488                     ioc->max_sges_in_chain_message) ? sges_left :
2489                     ioc->max_sges_in_chain_message;
2490                 chain_offset = (sges_left == sges_in_segment) ?
2491                     0 : sges_in_segment;
2492                 chain_length = sges_in_segment * ioc->sge_size_ieee;
2493                 if (chain_offset)
2494                         chain_length += ioc->sge_size_ieee;
2495                 _base_add_sg_single_ieee(sg_local, chain_sgl_flags,
2496                     chain_offset, chain_length, chain_dma);
2497
2498                 sg_local = chain;
2499                 if (!chain_offset)
2500                         goto fill_in_last_segment;
2501
2502                 /* fill in chain segments */
2503                 while (sges_in_segment) {
2504                         _base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
2505                             sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2506                         sg_scmd = sg_next(sg_scmd);
2507                         sg_local += ioc->sge_size_ieee;
2508                         sges_left--;
2509                         sges_in_segment--;
2510                 }
2511
2512                 chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2513                 if (!chain_req)
2514                         return -1;
2515                 chain = chain_req->chain_buffer;
2516                 chain_dma = chain_req->chain_buffer_dma;
2517         } while (1);
2518
2519
2520  fill_in_last_segment:
2521
2522         /* fill the last segment */
2523         while (sges_left > 0) {
2524                 if (sges_left == 1)
2525                         _base_add_sg_single_ieee(sg_local,
2526                             simple_sgl_flags_last, 0, sg_dma_len(sg_scmd),
2527                             sg_dma_address(sg_scmd));
2528                 else
2529                         _base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
2530                             sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2531                 sg_scmd = sg_next(sg_scmd);
2532                 sg_local += ioc->sge_size_ieee;
2533                 sges_left--;
2534         }
2535
2536         return 0;
2537 }
2538
2539 /**
2540  * _base_build_sg_ieee - build generic sg for IEEE format
2541  * @ioc: per adapter object
2542  * @psge: virtual address for SGE
2543  * @data_out_dma: physical address for WRITES
2544  * @data_out_sz: data xfer size for WRITES
2545  * @data_in_dma: physical address for READS
2546  * @data_in_sz: data xfer size for READS
2547  *
2548  * Return nothing.
2549  */
2550 static void
2551 _base_build_sg_ieee(struct MPT3SAS_ADAPTER *ioc, void *psge,
2552         dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
2553         size_t data_in_sz)
2554 {
2555         u8 sgl_flags;
2556
2557         if (!data_out_sz && !data_in_sz) {
2558                 _base_build_zero_len_sge_ieee(ioc, psge);
2559                 return;
2560         }
2561
2562         if (data_out_sz && data_in_sz) {
2563                 /* WRITE sgel first */
2564                 sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2565                     MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2566                 _base_add_sg_single_ieee(psge, sgl_flags, 0, data_out_sz,
2567                     data_out_dma);
2568
2569                 /* incr sgel */
2570                 psge += ioc->sge_size_ieee;
2571
2572                 /* READ sgel last */
2573                 sgl_flags |= MPI25_IEEE_SGE_FLAGS_END_OF_LIST;
2574                 _base_add_sg_single_ieee(psge, sgl_flags, 0, data_in_sz,
2575                     data_in_dma);
2576         } else if (data_out_sz) /* WRITE */ {
2577                 sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2578                     MPI25_IEEE_SGE_FLAGS_END_OF_LIST |
2579                     MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2580                 _base_add_sg_single_ieee(psge, sgl_flags, 0, data_out_sz,
2581                     data_out_dma);
2582         } else if (data_in_sz) /* READ */ {
2583                 sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2584                     MPI25_IEEE_SGE_FLAGS_END_OF_LIST |
2585                     MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2586                 _base_add_sg_single_ieee(psge, sgl_flags, 0, data_in_sz,
2587                     data_in_dma);
2588         }
2589 }
2590
2591 #define convert_to_kb(x) ((x) << (PAGE_SHIFT - 10))
2592
2593 /**
2594  * _base_config_dma_addressing - set dma addressing
2595  * @ioc: per adapter object
2596  * @pdev: PCI device struct
2597  *
2598  * Returns 0 for success, non-zero for failure.
2599  */
2600 static int
2601 _base_config_dma_addressing(struct MPT3SAS_ADAPTER *ioc, struct pci_dev *pdev)
2602 {
2603         struct sysinfo s;
2604         u64 consistent_dma_mask;
2605
2606         if (ioc->is_mcpu_endpoint)
2607                 goto try_32bit;
2608
2609         if (ioc->dma_mask)
2610                 consistent_dma_mask = DMA_BIT_MASK(64);
2611         else
2612                 consistent_dma_mask = DMA_BIT_MASK(32);
2613
2614         if (sizeof(dma_addr_t) > 4) {
2615                 const uint64_t required_mask =
2616                     dma_get_required_mask(&pdev->dev);
2617                 if ((required_mask > DMA_BIT_MASK(32)) &&
2618                     !pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) &&
2619                     !pci_set_consistent_dma_mask(pdev, consistent_dma_mask)) {
2620                         ioc->base_add_sg_single = &_base_add_sg_single_64;
2621                         ioc->sge_size = sizeof(Mpi2SGESimple64_t);
2622                         ioc->dma_mask = 64;
2623                         goto out;
2624                 }
2625         }
2626
2627  try_32bit:
2628         if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(32))
2629             && !pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) {
2630                 ioc->base_add_sg_single = &_base_add_sg_single_32;
2631                 ioc->sge_size = sizeof(Mpi2SGESimple32_t);
2632                 ioc->dma_mask = 32;
2633         } else
2634                 return -ENODEV;
2635
2636  out:
2637         si_meminfo(&s);
2638         pr_info(MPT3SAS_FMT
2639                 "%d BIT PCI BUS DMA ADDRESSING SUPPORTED, total mem (%ld kB)\n",
2640                 ioc->name, ioc->dma_mask, convert_to_kb(s.totalram));
2641
2642         return 0;
2643 }
2644
2645 static int
2646 _base_change_consistent_dma_mask(struct MPT3SAS_ADAPTER *ioc,
2647                                       struct pci_dev *pdev)
2648 {
2649         if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64))) {
2650                 if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)))
2651                         return -ENODEV;
2652         }
2653         return 0;
2654 }
2655
2656 /**
2657  * _base_check_enable_msix - checks MSIX capabable.
2658  * @ioc: per adapter object
2659  *
2660  * Check to see if card is capable of MSIX, and set number
2661  * of available msix vectors
2662  */
2663 static int
2664 _base_check_enable_msix(struct MPT3SAS_ADAPTER *ioc)
2665 {
2666         int base;
2667         u16 message_control;
2668
2669         /* Check whether controller SAS2008 B0 controller,
2670          * if it is SAS2008 B0 controller use IO-APIC instead of MSIX
2671          */
2672         if (ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2008 &&
2673             ioc->pdev->revision == SAS2_PCI_DEVICE_B0_REVISION) {
2674                 return -EINVAL;
2675         }
2676
2677         base = pci_find_capability(ioc->pdev, PCI_CAP_ID_MSIX);
2678         if (!base) {
2679                 dfailprintk(ioc, pr_info(MPT3SAS_FMT "msix not supported\n",
2680                         ioc->name));
2681                 return -EINVAL;
2682         }
2683
2684         /* get msix vector count */
2685         /* NUMA_IO not supported for older controllers */
2686         if (ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2004 ||
2687             ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2008 ||
2688             ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_1 ||
2689             ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_2 ||
2690             ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_3 ||
2691             ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2116_1 ||
2692             ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2116_2)
2693                 ioc->msix_vector_count = 1;
2694         else {
2695                 pci_read_config_word(ioc->pdev, base + 2, &message_control);
2696                 ioc->msix_vector_count = (message_control & 0x3FF) + 1;
2697         }
2698         dinitprintk(ioc, pr_info(MPT3SAS_FMT
2699                 "msix is supported, vector_count(%d)\n",
2700                 ioc->name, ioc->msix_vector_count));
2701         return 0;
2702 }
2703
2704 /**
2705  * _base_free_irq - free irq
2706  * @ioc: per adapter object
2707  *
2708  * Freeing respective reply_queue from the list.
2709  */
2710 static void
2711 _base_free_irq(struct MPT3SAS_ADAPTER *ioc)
2712 {
2713         struct adapter_reply_queue *reply_q, *next;
2714
2715         if (list_empty(&ioc->reply_queue_list))
2716                 return;
2717
2718         list_for_each_entry_safe(reply_q, next, &ioc->reply_queue_list, list) {
2719                 list_del(&reply_q->list);
2720                 free_irq(pci_irq_vector(ioc->pdev, reply_q->msix_index),
2721                          reply_q);
2722                 kfree(reply_q);
2723         }
2724 }
2725
2726 /**
2727  * _base_request_irq - request irq
2728  * @ioc: per adapter object
2729  * @index: msix index into vector table
2730  *
2731  * Inserting respective reply_queue into the list.
2732  */
2733 static int
2734 _base_request_irq(struct MPT3SAS_ADAPTER *ioc, u8 index)
2735 {
2736         struct pci_dev *pdev = ioc->pdev;
2737         struct adapter_reply_queue *reply_q;
2738         int r;
2739
2740         reply_q =  kzalloc(sizeof(struct adapter_reply_queue), GFP_KERNEL);
2741         if (!reply_q) {
2742                 pr_err(MPT3SAS_FMT "unable to allocate memory %d!\n",
2743                     ioc->name, (int)sizeof(struct adapter_reply_queue));
2744                 return -ENOMEM;
2745         }
2746         reply_q->ioc = ioc;
2747         reply_q->msix_index = index;
2748
2749         atomic_set(&reply_q->busy, 0);
2750         if (ioc->msix_enable)
2751                 snprintf(reply_q->name, MPT_NAME_LENGTH, "%s%d-msix%d",
2752                     ioc->driver_name, ioc->id, index);
2753         else
2754                 snprintf(reply_q->name, MPT_NAME_LENGTH, "%s%d",
2755                     ioc->driver_name, ioc->id);
2756         r = request_irq(pci_irq_vector(pdev, index), _base_interrupt,
2757                         IRQF_SHARED, reply_q->name, reply_q);
2758         if (r) {
2759                 pr_err(MPT3SAS_FMT "unable to allocate interrupt %d!\n",
2760                        reply_q->name, pci_irq_vector(pdev, index));
2761                 kfree(reply_q);
2762                 return -EBUSY;
2763         }
2764
2765         INIT_LIST_HEAD(&reply_q->list);
2766         list_add_tail(&reply_q->list, &ioc->reply_queue_list);
2767         return 0;
2768 }
2769
2770 /**
2771  * _base_assign_reply_queues - assigning msix index for each cpu
2772  * @ioc: per adapter object
2773  *
2774  * The enduser would need to set the affinity via /proc/irq/#/smp_affinity
2775  *
2776  * It would nice if we could call irq_set_affinity, however it is not
2777  * an exported symbol
2778  */
2779 static void
2780 _base_assign_reply_queues(struct MPT3SAS_ADAPTER *ioc)
2781 {
2782         unsigned int cpu, nr_cpus, nr_msix, index = 0;
2783         struct adapter_reply_queue *reply_q;
2784
2785         if (!_base_is_controller_msix_enabled(ioc))
2786                 return;
2787
2788         memset(ioc->cpu_msix_table, 0, ioc->cpu_msix_table_sz);
2789
2790         nr_cpus = num_online_cpus();
2791         nr_msix = ioc->reply_queue_count = min(ioc->reply_queue_count,
2792                                                ioc->facts.MaxMSIxVectors);
2793         if (!nr_msix)
2794                 return;
2795
2796         if (smp_affinity_enable) {
2797                 list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
2798                         const cpumask_t *mask = pci_irq_get_affinity(ioc->pdev,
2799                                                         reply_q->msix_index);
2800                         if (!mask) {
2801                                 pr_warn(MPT3SAS_FMT "no affinity for msi %x\n",
2802                                         ioc->name, reply_q->msix_index);
2803                                 continue;
2804                         }
2805
2806                         for_each_cpu_and(cpu, mask, cpu_online_mask) {
2807                                 if (cpu >= ioc->cpu_msix_table_sz)
2808                                         break;
2809                                 ioc->cpu_msix_table[cpu] = reply_q->msix_index;
2810                         }
2811                 }
2812                 return;
2813         }
2814         cpu = cpumask_first(cpu_online_mask);
2815
2816         list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
2817
2818                 unsigned int i, group = nr_cpus / nr_msix;
2819
2820                 if (cpu >= nr_cpus)
2821                         break;
2822
2823                 if (index < nr_cpus % nr_msix)
2824                         group++;
2825
2826                 for (i = 0 ; i < group ; i++) {
2827                         ioc->cpu_msix_table[cpu] = reply_q->msix_index;
2828                         cpu = cpumask_next(cpu, cpu_online_mask);
2829                 }
2830                 index++;
2831         }
2832 }
2833
2834 /**
2835  * _base_disable_msix - disables msix
2836  * @ioc: per adapter object
2837  *
2838  */
2839 static void
2840 _base_disable_msix(struct MPT3SAS_ADAPTER *ioc)
2841 {
2842         if (!ioc->msix_enable)
2843                 return;
2844         pci_disable_msix(ioc->pdev);
2845         ioc->msix_enable = 0;
2846 }
2847
2848 /**
2849  * _base_enable_msix - enables msix, failback to io_apic
2850  * @ioc: per adapter object
2851  *
2852  */
2853 static int
2854 _base_enable_msix(struct MPT3SAS_ADAPTER *ioc)
2855 {
2856         int r;
2857         int i, local_max_msix_vectors;
2858         u8 try_msix = 0;
2859         unsigned int irq_flags = PCI_IRQ_MSIX;
2860
2861         if (msix_disable == -1 || msix_disable == 0)
2862                 try_msix = 1;
2863
2864         if (!try_msix)
2865                 goto try_ioapic;
2866
2867         if (_base_check_enable_msix(ioc) != 0)
2868                 goto try_ioapic;
2869
2870         ioc->reply_queue_count = min_t(int, ioc->cpu_count,
2871                 ioc->msix_vector_count);
2872
2873         printk(MPT3SAS_FMT "MSI-X vectors supported: %d, no of cores"
2874           ": %d, max_msix_vectors: %d\n", ioc->name, ioc->msix_vector_count,
2875           ioc->cpu_count, max_msix_vectors);
2876
2877         if (!ioc->rdpq_array_enable && max_msix_vectors == -1)
2878                 local_max_msix_vectors = (reset_devices) ? 1 : 8;
2879         else
2880                 local_max_msix_vectors = max_msix_vectors;
2881
2882         if (local_max_msix_vectors > 0)
2883                 ioc->reply_queue_count = min_t(int, local_max_msix_vectors,
2884                         ioc->reply_queue_count);
2885         else if (local_max_msix_vectors == 0)
2886                 goto try_ioapic;
2887
2888         if (ioc->msix_vector_count < ioc->cpu_count)
2889                 smp_affinity_enable = 0;
2890
2891         if (smp_affinity_enable)
2892                 irq_flags |= PCI_IRQ_AFFINITY;
2893
2894         r = pci_alloc_irq_vectors(ioc->pdev, 1, ioc->reply_queue_count,
2895                                   irq_flags);
2896         if (r < 0) {
2897                 dfailprintk(ioc, pr_info(MPT3SAS_FMT
2898                         "pci_alloc_irq_vectors failed (r=%d) !!!\n",
2899                         ioc->name, r));
2900                 goto try_ioapic;
2901         }
2902
2903         ioc->msix_enable = 1;
2904         ioc->reply_queue_count = r;
2905         for (i = 0; i < ioc->reply_queue_count; i++) {
2906                 r = _base_request_irq(ioc, i);
2907                 if (r) {
2908                         _base_free_irq(ioc);
2909                         _base_disable_msix(ioc);
2910                         goto try_ioapic;
2911                 }
2912         }
2913
2914         return 0;
2915
2916 /* failback to io_apic interrupt routing */
2917  try_ioapic:
2918
2919         ioc->reply_queue_count = 1;
2920         r = pci_alloc_irq_vectors(ioc->pdev, 1, 1, PCI_IRQ_LEGACY);
2921         if (r < 0) {
2922                 dfailprintk(ioc, pr_info(MPT3SAS_FMT
2923                         "pci_alloc_irq_vector(legacy) failed (r=%d) !!!\n",
2924                         ioc->name, r));
2925         } else
2926                 r = _base_request_irq(ioc, 0);
2927
2928         return r;
2929 }
2930
2931 /**
2932  * mpt3sas_base_unmap_resources - free controller resources
2933  * @ioc: per adapter object
2934  */
2935 static void
2936 mpt3sas_base_unmap_resources(struct MPT3SAS_ADAPTER *ioc)
2937 {
2938         struct pci_dev *pdev = ioc->pdev;
2939
2940         dexitprintk(ioc, printk(MPT3SAS_FMT "%s\n",
2941                 ioc->name, __func__));
2942
2943         _base_free_irq(ioc);
2944         _base_disable_msix(ioc);
2945
2946         kfree(ioc->replyPostRegisterIndex);
2947         ioc->replyPostRegisterIndex = NULL;
2948
2949
2950         if (ioc->chip_phys) {
2951                 iounmap(ioc->chip);
2952                 ioc->chip_phys = 0;
2953         }
2954
2955         if (pci_is_enabled(pdev)) {
2956                 pci_release_selected_regions(ioc->pdev, ioc->bars);
2957                 pci_disable_pcie_error_reporting(pdev);
2958                 pci_disable_device(pdev);
2959         }
2960 }
2961
2962 /**
2963  * mpt3sas_base_map_resources - map in controller resources (io/irq/memap)
2964  * @ioc: per adapter object
2965  *
2966  * Returns 0 for success, non-zero for failure.
2967  */
2968 int
2969 mpt3sas_base_map_resources(struct MPT3SAS_ADAPTER *ioc)
2970 {
2971         struct pci_dev *pdev = ioc->pdev;
2972         u32 memap_sz;
2973         u32 pio_sz;
2974         int i, r = 0;
2975         u64 pio_chip = 0;
2976         phys_addr_t chip_phys = 0;
2977         struct adapter_reply_queue *reply_q;
2978
2979         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n",
2980             ioc->name, __func__));
2981
2982         ioc->bars = pci_select_bars(pdev, IORESOURCE_MEM);
2983         if (pci_enable_device_mem(pdev)) {
2984                 pr_warn(MPT3SAS_FMT "pci_enable_device_mem: failed\n",
2985                         ioc->name);
2986                 ioc->bars = 0;
2987                 return -ENODEV;
2988         }
2989
2990
2991         if (pci_request_selected_regions(pdev, ioc->bars,
2992             ioc->driver_name)) {
2993                 pr_warn(MPT3SAS_FMT "pci_request_selected_regions: failed\n",
2994                         ioc->name);
2995                 ioc->bars = 0;
2996                 r = -ENODEV;
2997                 goto out_fail;
2998         }
2999
3000 /* AER (Advanced Error Reporting) hooks */
3001         pci_enable_pcie_error_reporting(pdev);
3002
3003         pci_set_master(pdev);
3004
3005
3006         if (_base_config_dma_addressing(ioc, pdev) != 0) {
3007                 pr_warn(MPT3SAS_FMT "no suitable DMA mask for %s\n",
3008                     ioc->name, pci_name(pdev));
3009                 r = -ENODEV;
3010                 goto out_fail;
3011         }
3012
3013         for (i = 0, memap_sz = 0, pio_sz = 0; (i < DEVICE_COUNT_RESOURCE) &&
3014              (!memap_sz || !pio_sz); i++) {
3015                 if (pci_resource_flags(pdev, i) & IORESOURCE_IO) {
3016                         if (pio_sz)
3017                                 continue;
3018                         pio_chip = (u64)pci_resource_start(pdev, i);
3019                         pio_sz = pci_resource_len(pdev, i);
3020                 } else if (pci_resource_flags(pdev, i) & IORESOURCE_MEM) {
3021                         if (memap_sz)
3022                                 continue;
3023                         ioc->chip_phys = pci_resource_start(pdev, i);
3024                         chip_phys = ioc->chip_phys;
3025                         memap_sz = pci_resource_len(pdev, i);
3026                         ioc->chip = ioremap(ioc->chip_phys, memap_sz);
3027                 }
3028         }
3029
3030         if (ioc->chip == NULL) {
3031                 pr_err(MPT3SAS_FMT "unable to map adapter memory! "
3032                         " or resource not found\n", ioc->name);
3033                 r = -EINVAL;
3034                 goto out_fail;
3035         }
3036
3037         _base_mask_interrupts(ioc);
3038
3039         r = _base_get_ioc_facts(ioc);
3040         if (r)
3041                 goto out_fail;
3042
3043         if (!ioc->rdpq_array_enable_assigned) {
3044                 ioc->rdpq_array_enable = ioc->rdpq_array_capable;
3045                 ioc->rdpq_array_enable_assigned = 1;
3046         }
3047
3048         r = _base_enable_msix(ioc);
3049         if (r)
3050                 goto out_fail;
3051
3052         /* Use the Combined reply queue feature only for SAS3 C0 & higher
3053          * revision HBAs and also only when reply queue count is greater than 8
3054          */
3055         if (ioc->combined_reply_queue) {
3056                 /* Determine the Supplemental Reply Post Host Index Registers
3057                  * Addresse. Supplemental Reply Post Host Index Registers
3058                  * starts at offset MPI25_SUP_REPLY_POST_HOST_INDEX_OFFSET and
3059                  * each register is at offset bytes of
3060                  * MPT3_SUP_REPLY_POST_HOST_INDEX_REG_OFFSET from previous one.
3061                  */
3062                 ioc->replyPostRegisterIndex = kcalloc(
3063                      ioc->combined_reply_index_count,
3064                      sizeof(resource_size_t *), GFP_KERNEL);
3065                 if (!ioc->replyPostRegisterIndex) {
3066                         dfailprintk(ioc, printk(MPT3SAS_FMT
3067                         "allocation for reply Post Register Index failed!!!\n",
3068                                                                    ioc->name));
3069                         r = -ENOMEM;
3070                         goto out_fail;
3071                 }
3072
3073                 for (i = 0; i < ioc->combined_reply_index_count; i++) {
3074                         ioc->replyPostRegisterIndex[i] = (resource_size_t *)
3075                              ((u8 __force *)&ioc->chip->Doorbell +
3076                              MPI25_SUP_REPLY_POST_HOST_INDEX_OFFSET +
3077                              (i * MPT3_SUP_REPLY_POST_HOST_INDEX_REG_OFFSET));
3078                 }
3079         }
3080
3081         if (ioc->is_warpdrive) {
3082                 ioc->reply_post_host_index[0] = (resource_size_t __iomem *)
3083                     &ioc->chip->ReplyPostHostIndex;
3084
3085                 for (i = 1; i < ioc->cpu_msix_table_sz; i++)
3086                         ioc->reply_post_host_index[i] =
3087                         (resource_size_t __iomem *)
3088                         ((u8 __iomem *)&ioc->chip->Doorbell + (0x4000 + ((i - 1)
3089                         * 4)));
3090         }
3091
3092         list_for_each_entry(reply_q, &ioc->reply_queue_list, list)
3093                 pr_info(MPT3SAS_FMT "%s: IRQ %d\n",
3094                     reply_q->name,  ((ioc->msix_enable) ? "PCI-MSI-X enabled" :
3095                     "IO-APIC enabled"),
3096                     pci_irq_vector(ioc->pdev, reply_q->msix_index));
3097
3098         pr_info(MPT3SAS_FMT "iomem(%pap), mapped(0x%p), size(%d)\n",
3099             ioc->name, &chip_phys, ioc->chip, memap_sz);
3100         pr_info(MPT3SAS_FMT "ioport(0x%016llx), size(%d)\n",
3101             ioc->name, (unsigned long long)pio_chip, pio_sz);
3102
3103         /* Save PCI configuration state for recovery from PCI AER/EEH errors */
3104         pci_save_state(pdev);
3105         return 0;
3106
3107  out_fail:
3108         mpt3sas_base_unmap_resources(ioc);
3109         return r;
3110 }
3111
3112 /**
3113  * mpt3sas_base_get_msg_frame - obtain request mf pointer
3114  * @ioc: per adapter object
3115  * @smid: system request message index(smid zero is invalid)
3116  *
3117  * Returns virt pointer to message frame.
3118  */
3119 void *
3120 mpt3sas_base_get_msg_frame(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3121 {
3122         return (void *)(ioc->request + (smid * ioc->request_sz));
3123 }
3124
3125 /**
3126  * mpt3sas_base_get_sense_buffer - obtain a sense buffer virt addr
3127  * @ioc: per adapter object
3128  * @smid: system request message index
3129  *
3130  * Returns virt pointer to sense buffer.
3131  */
3132 void *
3133 mpt3sas_base_get_sense_buffer(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3134 {
3135         return (void *)(ioc->sense + ((smid - 1) * SCSI_SENSE_BUFFERSIZE));
3136 }
3137
3138 /**
3139  * mpt3sas_base_get_sense_buffer_dma - obtain a sense buffer dma addr
3140  * @ioc: per adapter object
3141  * @smid: system request message index
3142  *
3143  * Returns phys pointer to the low 32bit address of the sense buffer.
3144  */
3145 __le32
3146 mpt3sas_base_get_sense_buffer_dma(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3147 {
3148         return cpu_to_le32(ioc->sense_dma + ((smid - 1) *
3149             SCSI_SENSE_BUFFERSIZE));
3150 }
3151
3152 /**
3153  * mpt3sas_base_get_pcie_sgl - obtain a PCIe SGL virt addr
3154  * @ioc: per adapter object
3155  * @smid: system request message index
3156  *
3157  * Returns virt pointer to a PCIe SGL.
3158  */
3159 void *
3160 mpt3sas_base_get_pcie_sgl(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3161 {
3162         return (void *)(ioc->pcie_sg_lookup[smid - 1].pcie_sgl);
3163 }
3164
3165 /**
3166  * mpt3sas_base_get_pcie_sgl_dma - obtain a PCIe SGL dma addr
3167  * @ioc: per adapter object
3168  * @smid: system request message index
3169  *
3170  * Returns phys pointer to the address of the PCIe buffer.
3171  */
3172 dma_addr_t
3173 mpt3sas_base_get_pcie_sgl_dma(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3174 {
3175         return ioc->pcie_sg_lookup[smid - 1].pcie_sgl_dma;
3176 }
3177
3178 /**
3179  * mpt3sas_base_get_reply_virt_addr - obtain reply frames virt address
3180  * @ioc: per adapter object
3181  * @phys_addr: lower 32 physical addr of the reply
3182  *
3183  * Converts 32bit lower physical addr into a virt address.
3184  */
3185 void *
3186 mpt3sas_base_get_reply_virt_addr(struct MPT3SAS_ADAPTER *ioc, u32 phys_addr)
3187 {
3188         if (!phys_addr)
3189                 return NULL;
3190         return ioc->reply + (phys_addr - (u32)ioc->reply_dma);
3191 }
3192
3193 static inline u8
3194 _base_get_msix_index(struct MPT3SAS_ADAPTER *ioc)
3195 {
3196         return ioc->cpu_msix_table[raw_smp_processor_id()];
3197 }
3198
3199 /**
3200  * mpt3sas_base_get_smid - obtain a free smid from internal queue
3201  * @ioc: per adapter object
3202  * @cb_idx: callback index
3203  *
3204  * Returns smid (zero is invalid)
3205  */
3206 u16
3207 mpt3sas_base_get_smid(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx)
3208 {
3209         unsigned long flags;
3210         struct request_tracker *request;
3211         u16 smid;
3212
3213         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3214         if (list_empty(&ioc->internal_free_list)) {
3215                 spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3216                 pr_err(MPT3SAS_FMT "%s: smid not available\n",
3217                     ioc->name, __func__);
3218                 return 0;
3219         }
3220
3221         request = list_entry(ioc->internal_free_list.next,
3222             struct request_tracker, tracker_list);
3223         request->cb_idx = cb_idx;
3224         smid = request->smid;
3225         list_del(&request->tracker_list);
3226         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3227         return smid;
3228 }
3229
3230 /**
3231  * mpt3sas_base_get_smid_scsiio - obtain a free smid from scsiio queue
3232  * @ioc: per adapter object
3233  * @cb_idx: callback index
3234  * @scmd: pointer to scsi command object
3235  *
3236  * Returns smid (zero is invalid)
3237  */
3238 u16
3239 mpt3sas_base_get_smid_scsiio(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx,
3240         struct scsi_cmnd *scmd)
3241 {
3242         struct scsiio_tracker *request = scsi_cmd_priv(scmd);
3243         unsigned int tag = scmd->request->tag;
3244         u16 smid;
3245
3246         smid = tag + 1;
3247         request->cb_idx = cb_idx;
3248         request->msix_io = _base_get_msix_index(ioc);
3249         request->smid = smid;
3250         INIT_LIST_HEAD(&request->chain_list);
3251         return smid;
3252 }
3253
3254 /**
3255  * mpt3sas_base_get_smid_hpr - obtain a free smid from hi-priority queue
3256  * @ioc: per adapter object
3257  * @cb_idx: callback index
3258  *
3259  * Returns smid (zero is invalid)
3260  */
3261 u16
3262 mpt3sas_base_get_smid_hpr(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx)
3263 {
3264         unsigned long flags;
3265         struct request_tracker *request;
3266         u16 smid;
3267
3268         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3269         if (list_empty(&ioc->hpr_free_list)) {
3270                 spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3271                 return 0;
3272         }
3273
3274         request = list_entry(ioc->hpr_free_list.next,
3275             struct request_tracker, tracker_list);
3276         request->cb_idx = cb_idx;
3277         smid = request->smid;
3278         list_del(&request->tracker_list);
3279         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3280         return smid;
3281 }
3282
3283 static void
3284 _base_recovery_check(struct MPT3SAS_ADAPTER *ioc)
3285 {
3286         /*
3287          * See _wait_for_commands_to_complete() call with regards to this code.
3288          */
3289         if (ioc->shost_recovery && ioc->pending_io_count) {
3290                 ioc->pending_io_count = atomic_read(&ioc->shost->host_busy);
3291                 if (ioc->pending_io_count == 0)
3292                         wake_up(&ioc->reset_wq);
3293         }
3294 }
3295
3296 void mpt3sas_base_clear_st(struct MPT3SAS_ADAPTER *ioc,
3297                            struct scsiio_tracker *st)
3298 {
3299         if (WARN_ON(st->smid == 0))
3300                 return;
3301         st->cb_idx = 0xFF;
3302         st->direct_io = 0;
3303         atomic_set(&ioc->chain_lookup[st->smid - 1].chain_offset, 0);
3304 }
3305
3306 /**
3307  * mpt3sas_base_free_smid - put smid back on free_list
3308  * @ioc: per adapter object
3309  * @smid: system request message index
3310  *
3311  * Return nothing.
3312  */
3313 void
3314 mpt3sas_base_free_smid(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3315 {
3316         unsigned long flags;
3317         int i;
3318
3319         if (smid < ioc->hi_priority_smid) {
3320                 struct scsiio_tracker *st;
3321
3322                 st = _get_st_from_smid(ioc, smid);
3323                 if (!st) {
3324                         _base_recovery_check(ioc);
3325                         return;
3326                 }
3327                 mpt3sas_base_clear_st(ioc, st);
3328                 _base_recovery_check(ioc);
3329                 return;
3330         }
3331
3332         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3333         if (smid < ioc->internal_smid) {
3334                 /* hi-priority */
3335                 i = smid - ioc->hi_priority_smid;
3336                 ioc->hpr_lookup[i].cb_idx = 0xFF;
3337                 list_add(&ioc->hpr_lookup[i].tracker_list, &ioc->hpr_free_list);
3338         } else if (smid <= ioc->hba_queue_depth) {
3339                 /* internal queue */
3340                 i = smid - ioc->internal_smid;
3341                 ioc->internal_lookup[i].cb_idx = 0xFF;
3342                 list_add(&ioc->internal_lookup[i].tracker_list,
3343                     &ioc->internal_free_list);
3344         }
3345         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3346 }
3347
3348 /**
3349  * _base_mpi_ep_writeq - 32 bit write to MMIO
3350  * @b: data payload
3351  * @addr: address in MMIO space
3352  * @writeq_lock: spin lock
3353  *
3354  * This special handling for MPI EP to take care of 32 bit
3355  * environment where its not quarenteed to send the entire word
3356  * in one transfer.
3357  */
3358 static inline void
3359 _base_mpi_ep_writeq(__u64 b, volatile void __iomem *addr,
3360                                         spinlock_t *writeq_lock)
3361 {
3362         unsigned long flags;
3363         __u64 data_out = b;
3364
3365         spin_lock_irqsave(writeq_lock, flags);
3366         writel((u32)(data_out), addr);
3367         writel((u32)(data_out >> 32), (addr + 4));
3368         mmiowb();
3369         spin_unlock_irqrestore(writeq_lock, flags);
3370 }
3371
3372 /**
3373  * _base_writeq - 64 bit write to MMIO
3374  * @ioc: per adapter object
3375  * @b: data payload
3376  * @addr: address in MMIO space
3377  * @writeq_lock: spin lock
3378  *
3379  * Glue for handling an atomic 64 bit word to MMIO. This special handling takes
3380  * care of 32 bit environment where its not quarenteed to send the entire word
3381  * in one transfer.
3382  */
3383 #if defined(writeq) && defined(CONFIG_64BIT)
3384 static inline void
3385 _base_writeq(__u64 b, volatile void __iomem *addr, spinlock_t *writeq_lock)
3386 {
3387         writeq(b, addr);
3388 }
3389 #else
3390 static inline void
3391 _base_writeq(__u64 b, volatile void __iomem *addr, spinlock_t *writeq_lock)
3392 {
3393         _base_mpi_ep_writeq(b, addr, writeq_lock);
3394 }
3395 #endif
3396
3397 /**
3398  * _base_put_smid_mpi_ep_scsi_io - send SCSI_IO request to firmware
3399  * @ioc: per adapter object
3400  * @smid: system request message index
3401  * @handle: device handle
3402  *
3403  * Return nothing.
3404  */
3405 static void
3406 _base_put_smid_mpi_ep_scsi_io(struct MPT3SAS_ADAPTER *ioc, u16 smid, u16 handle)
3407 {
3408         Mpi2RequestDescriptorUnion_t descriptor;
3409         u64 *request = (u64 *)&descriptor;
3410         void *mpi_req_iomem;
3411         __le32 *mfp = (__le32 *)mpt3sas_base_get_msg_frame(ioc, smid);
3412
3413         _clone_sg_entries(ioc, (void *) mfp, smid);
3414         mpi_req_iomem = (void __force *)ioc->chip +
3415                         MPI_FRAME_START_OFFSET + (smid * ioc->request_sz);
3416         _base_clone_mpi_to_sys_mem(mpi_req_iomem, (void *)mfp,
3417                                         ioc->request_sz);
3418         descriptor.SCSIIO.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
3419         descriptor.SCSIIO.MSIxIndex =  _base_get_msix_index(ioc);
3420         descriptor.SCSIIO.SMID = cpu_to_le16(smid);
3421         descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
3422         descriptor.SCSIIO.LMID = 0;
3423         _base_mpi_ep_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3424             &ioc->scsi_lookup_lock);
3425 }
3426
3427 /**
3428  * _base_put_smid_scsi_io - send SCSI_IO request to firmware
3429  * @ioc: per adapter object
3430  * @smid: system request message index
3431  * @handle: device handle
3432  *
3433  * Return nothing.
3434  */
3435 static void
3436 _base_put_smid_scsi_io(struct MPT3SAS_ADAPTER *ioc, u16 smid, u16 handle)
3437 {
3438         Mpi2RequestDescriptorUnion_t descriptor;
3439         u64 *request = (u64 *)&descriptor;
3440
3441
3442         descriptor.SCSIIO.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
3443         descriptor.SCSIIO.MSIxIndex =  _base_get_msix_index(ioc);
3444         descriptor.SCSIIO.SMID = cpu_to_le16(smid);
3445         descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
3446         descriptor.SCSIIO.LMID = 0;
3447         _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3448             &ioc->scsi_lookup_lock);
3449 }
3450
3451 /**
3452  * mpt3sas_base_put_smid_fast_path - send fast path request to firmware
3453  * @ioc: per adapter object
3454  * @smid: system request message index
3455  * @handle: device handle
3456  *
3457  * Return nothing.
3458  */
3459 void
3460 mpt3sas_base_put_smid_fast_path(struct MPT3SAS_ADAPTER *ioc, u16 smid,
3461         u16 handle)
3462 {
3463         Mpi2RequestDescriptorUnion_t descriptor;
3464         u64 *request = (u64 *)&descriptor;
3465
3466         descriptor.SCSIIO.RequestFlags =
3467             MPI25_REQ_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO;
3468         descriptor.SCSIIO.MSIxIndex = _base_get_msix_index(ioc);
3469         descriptor.SCSIIO.SMID = cpu_to_le16(smid);
3470         descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
3471         descriptor.SCSIIO.LMID = 0;
3472         _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3473             &ioc->scsi_lookup_lock);
3474 }
3475
3476 /**
3477  * mpt3sas_base_put_smid_hi_priority - send Task Management request to firmware
3478  * @ioc: per adapter object
3479  * @smid: system request message index
3480  * @msix_task: msix_task will be same as msix of IO incase of task abort else 0.
3481  * Return nothing.
3482  */
3483 void
3484 mpt3sas_base_put_smid_hi_priority(struct MPT3SAS_ADAPTER *ioc, u16 smid,
3485         u16 msix_task)
3486 {
3487         Mpi2RequestDescriptorUnion_t descriptor;
3488         void *mpi_req_iomem;
3489         u64 *request;
3490
3491         if (ioc->is_mcpu_endpoint) {
3492                 __le32 *mfp = (__le32 *)mpt3sas_base_get_msg_frame(ioc, smid);
3493
3494                 /* TBD 256 is offset within sys register. */
3495                 mpi_req_iomem = (void __force *)ioc->chip
3496                                         + MPI_FRAME_START_OFFSET
3497                                         + (smid * ioc->request_sz);
3498                 _base_clone_mpi_to_sys_mem(mpi_req_iomem, (void *)mfp,
3499                                                         ioc->request_sz);
3500         }
3501
3502         request = (u64 *)&descriptor;
3503
3504         descriptor.HighPriority.RequestFlags =
3505             MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY;
3506         descriptor.HighPriority.MSIxIndex =  msix_task;
3507         descriptor.HighPriority.SMID = cpu_to_le16(smid);
3508         descriptor.HighPriority.LMID = 0;
3509         descriptor.HighPriority.Reserved1 = 0;
3510         if (ioc->is_mcpu_endpoint)
3511                 _base_mpi_ep_writeq(*request,
3512                                 &ioc->chip->RequestDescriptorPostLow,
3513                                 &ioc->scsi_lookup_lock);
3514         else
3515                 _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3516                     &ioc->scsi_lookup_lock);
3517 }
3518
3519 /**
3520  * mpt3sas_base_put_smid_nvme_encap - send NVMe encapsulated request to
3521  *  firmware
3522  * @ioc: per adapter object
3523  * @smid: system request message index
3524  *
3525  * Return nothing.
3526  */
3527 void
3528 mpt3sas_base_put_smid_nvme_encap(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3529 {
3530         Mpi2RequestDescriptorUnion_t descriptor;
3531         u64 *request = (u64 *)&descriptor;
3532
3533         descriptor.Default.RequestFlags =
3534                 MPI26_REQ_DESCRIPT_FLAGS_PCIE_ENCAPSULATED;
3535         descriptor.Default.MSIxIndex =  _base_get_msix_index(ioc);
3536         descriptor.Default.SMID = cpu_to_le16(smid);
3537         descriptor.Default.LMID = 0;
3538         descriptor.Default.DescriptorTypeDependent = 0;
3539         _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3540             &ioc->scsi_lookup_lock);
3541 }
3542
3543 /**
3544  * mpt3sas_base_put_smid_default - Default, primarily used for config pages
3545  * @ioc: per adapter object
3546  * @smid: system request message index
3547  *
3548  * Return nothing.
3549  */
3550 void
3551 mpt3sas_base_put_smid_default(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3552 {
3553         Mpi2RequestDescriptorUnion_t descriptor;
3554         void *mpi_req_iomem;
3555         u64 *request;
3556
3557         if (ioc->is_mcpu_endpoint) {
3558                 __le32 *mfp = (__le32 *)mpt3sas_base_get_msg_frame(ioc, smid);
3559
3560                 _clone_sg_entries(ioc, (void *) mfp, smid);
3561                 /* TBD 256 is offset within sys register */
3562                 mpi_req_iomem = (void __force *)ioc->chip +
3563                         MPI_FRAME_START_OFFSET + (smid * ioc->request_sz);
3564                 _base_clone_mpi_to_sys_mem(mpi_req_iomem, (void *)mfp,
3565                                                         ioc->request_sz);
3566         }
3567         request = (u64 *)&descriptor;
3568         descriptor.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
3569         descriptor.Default.MSIxIndex =  _base_get_msix_index(ioc);
3570         descriptor.Default.SMID = cpu_to_le16(smid);
3571         descriptor.Default.LMID = 0;
3572         descriptor.Default.DescriptorTypeDependent = 0;
3573         if (ioc->is_mcpu_endpoint)
3574                 _base_mpi_ep_writeq(*request,
3575                                 &ioc->chip->RequestDescriptorPostLow,
3576                                 &ioc->scsi_lookup_lock);
3577         else
3578                 _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3579                                 &ioc->scsi_lookup_lock);
3580 }
3581
3582 /**
3583  * _base_display_OEMs_branding - Display branding string
3584  * @ioc: per adapter object
3585  *
3586  * Return nothing.
3587  */
3588 static void
3589 _base_display_OEMs_branding(struct MPT3SAS_ADAPTER *ioc)
3590 {
3591         if (ioc->pdev->subsystem_vendor != PCI_VENDOR_ID_INTEL)
3592                 return;
3593
3594         switch (ioc->pdev->subsystem_vendor) {
3595         case PCI_VENDOR_ID_INTEL:
3596                 switch (ioc->pdev->device) {
3597                 case MPI2_MFGPAGE_DEVID_SAS2008:
3598                         switch (ioc->pdev->subsystem_device) {
3599                         case MPT2SAS_INTEL_RMS2LL080_SSDID:
3600                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3601                                     MPT2SAS_INTEL_RMS2LL080_BRANDING);
3602                                 break;
3603                         case MPT2SAS_INTEL_RMS2LL040_SSDID:
3604                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3605                                     MPT2SAS_INTEL_RMS2LL040_BRANDING);
3606                                 break;
3607                         case MPT2SAS_INTEL_SSD910_SSDID:
3608                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3609                                     MPT2SAS_INTEL_SSD910_BRANDING);
3610                                 break;
3611                         default:
3612                                 pr_info(MPT3SAS_FMT
3613                                  "Intel(R) Controller: Subsystem ID: 0x%X\n",
3614                                  ioc->name, ioc->pdev->subsystem_device);
3615                                 break;
3616                         }
3617                 case MPI2_MFGPAGE_DEVID_SAS2308_2:
3618                         switch (ioc->pdev->subsystem_device) {
3619                         case MPT2SAS_INTEL_RS25GB008_SSDID:
3620                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3621                                     MPT2SAS_INTEL_RS25GB008_BRANDING);
3622                                 break;
3623                         case MPT2SAS_INTEL_RMS25JB080_SSDID:
3624                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3625                                     MPT2SAS_INTEL_RMS25JB080_BRANDING);
3626                                 break;
3627                         case MPT2SAS_INTEL_RMS25JB040_SSDID:
3628                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3629                                     MPT2SAS_INTEL_RMS25JB040_BRANDING);
3630                                 break;
3631                         case MPT2SAS_INTEL_RMS25KB080_SSDID:
3632                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3633                                     MPT2SAS_INTEL_RMS25KB080_BRANDING);
3634                                 break;
3635                         case MPT2SAS_INTEL_RMS25KB040_SSDID:
3636                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3637                                     MPT2SAS_INTEL_RMS25KB040_BRANDING);
3638                                 break;
3639                         case MPT2SAS_INTEL_RMS25LB040_SSDID:
3640                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3641                                     MPT2SAS_INTEL_RMS25LB040_BRANDING);
3642                                 break;
3643                         case MPT2SAS_INTEL_RMS25LB080_SSDID:
3644                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3645                                     MPT2SAS_INTEL_RMS25LB080_BRANDING);
3646                                 break;
3647                         default:
3648                                 pr_info(MPT3SAS_FMT
3649                                  "Intel(R) Controller: Subsystem ID: 0x%X\n",
3650                                  ioc->name, ioc->pdev->subsystem_device);
3651                                 break;
3652                         }
3653                 case MPI25_MFGPAGE_DEVID_SAS3008:
3654                         switch (ioc->pdev->subsystem_device) {
3655                         case MPT3SAS_INTEL_RMS3JC080_SSDID:
3656                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3657                                         MPT3SAS_INTEL_RMS3JC080_BRANDING);
3658                                 break;
3659
3660                         case MPT3SAS_INTEL_RS3GC008_SSDID:
3661                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3662                                         MPT3SAS_INTEL_RS3GC008_BRANDING);
3663                                 break;
3664                         case MPT3SAS_INTEL_RS3FC044_SSDID:
3665                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3666                                         MPT3SAS_INTEL_RS3FC044_BRANDING);
3667                                 break;
3668                         case MPT3SAS_INTEL_RS3UC080_SSDID:
3669                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3670                                         MPT3SAS_INTEL_RS3UC080_BRANDING);
3671                                 break;
3672                         default:
3673                                 pr_info(MPT3SAS_FMT
3674                                  "Intel(R) Controller: Subsystem ID: 0x%X\n",
3675                                  ioc->name, ioc->pdev->subsystem_device);
3676                                 break;
3677                         }
3678                         break;
3679                 default:
3680                         pr_info(MPT3SAS_FMT
3681                          "Intel(R) Controller: Subsystem ID: 0x%X\n",
3682                          ioc->name, ioc->pdev->subsystem_device);
3683                         break;
3684                 }
3685                 break;
3686         case PCI_VENDOR_ID_DELL:
3687                 switch (ioc->pdev->device) {
3688                 case MPI2_MFGPAGE_DEVID_SAS2008:
3689                         switch (ioc->pdev->subsystem_device) {
3690                         case MPT2SAS_DELL_6GBPS_SAS_HBA_SSDID:
3691                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3692                                  MPT2SAS_DELL_6GBPS_SAS_HBA_BRANDING);
3693                                 break;
3694                         case MPT2SAS_DELL_PERC_H200_ADAPTER_SSDID:
3695                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3696                                  MPT2SAS_DELL_PERC_H200_ADAPTER_BRANDING);
3697                                 break;
3698                         case MPT2SAS_DELL_PERC_H200_INTEGRATED_SSDID:
3699                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3700                                  MPT2SAS_DELL_PERC_H200_INTEGRATED_BRANDING);
3701                                 break;
3702                         case MPT2SAS_DELL_PERC_H200_MODULAR_SSDID:
3703                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3704                                  MPT2SAS_DELL_PERC_H200_MODULAR_BRANDING);
3705                                 break;
3706                         case MPT2SAS_DELL_PERC_H200_EMBEDDED_SSDID:
3707                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3708                                  MPT2SAS_DELL_PERC_H200_EMBEDDED_BRANDING);
3709                                 break;
3710                         case MPT2SAS_DELL_PERC_H200_SSDID:
3711                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3712                                  MPT2SAS_DELL_PERC_H200_BRANDING);
3713                                 break;
3714                         case MPT2SAS_DELL_6GBPS_SAS_SSDID:
3715                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3716                                  MPT2SAS_DELL_6GBPS_SAS_BRANDING);
3717                                 break;
3718                         default:
3719                                 pr_info(MPT3SAS_FMT
3720                                    "Dell 6Gbps HBA: Subsystem ID: 0x%X\n",
3721                                    ioc->name, ioc->pdev->subsystem_device);
3722                                 break;
3723                         }
3724                         break;
3725                 case MPI25_MFGPAGE_DEVID_SAS3008:
3726                         switch (ioc->pdev->subsystem_device) {
3727                         case MPT3SAS_DELL_12G_HBA_SSDID:
3728                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3729                                         MPT3SAS_DELL_12G_HBA_BRANDING);
3730                                 break;
3731                         default:
3732                                 pr_info(MPT3SAS_FMT
3733                                    "Dell 12Gbps HBA: Subsystem ID: 0x%X\n",
3734                                    ioc->name, ioc->pdev->subsystem_device);
3735                                 break;
3736                         }
3737                         break;
3738                 default:
3739                         pr_info(MPT3SAS_FMT
3740                            "Dell HBA: Subsystem ID: 0x%X\n", ioc->name,
3741                            ioc->pdev->subsystem_device);
3742                         break;
3743                 }
3744                 break;
3745         case PCI_VENDOR_ID_CISCO:
3746                 switch (ioc->pdev->device) {
3747                 case MPI25_MFGPAGE_DEVID_SAS3008:
3748                         switch (ioc->pdev->subsystem_device) {
3749                         case MPT3SAS_CISCO_12G_8E_HBA_SSDID:
3750                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3751                                         MPT3SAS_CISCO_12G_8E_HBA_BRANDING);
3752                                 break;
3753                         case MPT3SAS_CISCO_12G_8I_HBA_SSDID:
3754                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3755                                         MPT3SAS_CISCO_12G_8I_HBA_BRANDING);
3756                                 break;
3757                         case MPT3SAS_CISCO_12G_AVILA_HBA_SSDID:
3758                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3759                                         MPT3SAS_CISCO_12G_AVILA_HBA_BRANDING);
3760                                 break;
3761                         default:
3762                                 pr_info(MPT3SAS_FMT
3763                                   "Cisco 12Gbps SAS HBA: Subsystem ID: 0x%X\n",
3764                                   ioc->name, ioc->pdev->subsystem_device);
3765                                 break;
3766                         }
3767                         break;
3768                 case MPI25_MFGPAGE_DEVID_SAS3108_1:
3769                         switch (ioc->pdev->subsystem_device) {
3770                         case MPT3SAS_CISCO_12G_AVILA_HBA_SSDID:
3771                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3772                                 MPT3SAS_CISCO_12G_AVILA_HBA_BRANDING);
3773                                 break;
3774                         case MPT3SAS_CISCO_12G_COLUSA_MEZZANINE_HBA_SSDID:
3775                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3776                                 MPT3SAS_CISCO_12G_COLUSA_MEZZANINE_HBA_BRANDING
3777                                 );
3778                                 break;
3779                         default:
3780                                 pr_info(MPT3SAS_FMT
3781                                  "Cisco 12Gbps SAS HBA: Subsystem ID: 0x%X\n",
3782                                  ioc->name, ioc->pdev->subsystem_device);
3783                                 break;
3784                         }
3785                         break;
3786                 default:
3787                         pr_info(MPT3SAS_FMT
3788                            "Cisco SAS HBA: Subsystem ID: 0x%X\n",
3789                            ioc->name, ioc->pdev->subsystem_device);
3790                         break;
3791                 }
3792                 break;
3793         case MPT2SAS_HP_3PAR_SSVID:
3794                 switch (ioc->pdev->device) {
3795                 case MPI2_MFGPAGE_DEVID_SAS2004:
3796                         switch (ioc->pdev->subsystem_device) {
3797                         case MPT2SAS_HP_DAUGHTER_2_4_INTERNAL_SSDID:
3798                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3799                                     MPT2SAS_HP_DAUGHTER_2_4_INTERNAL_BRANDING);
3800                                 break;
3801                         default:
3802                                 pr_info(MPT3SAS_FMT
3803                                    "HP 6Gbps SAS HBA: Subsystem ID: 0x%X\n",
3804                                    ioc->name, ioc->pdev->subsystem_device);
3805                                 break;
3806                         }
3807                 case MPI2_MFGPAGE_DEVID_SAS2308_2:
3808                         switch (ioc->pdev->subsystem_device) {
3809                         case MPT2SAS_HP_2_4_INTERNAL_SSDID:
3810                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3811                                     MPT2SAS_HP_2_4_INTERNAL_BRANDING);
3812                                 break;
3813                         case MPT2SAS_HP_2_4_EXTERNAL_SSDID:
3814                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3815                                     MPT2SAS_HP_2_4_EXTERNAL_BRANDING);
3816                                 break;
3817                         case MPT2SAS_HP_1_4_INTERNAL_1_4_EXTERNAL_SSDID:
3818                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3819                                  MPT2SAS_HP_1_4_INTERNAL_1_4_EXTERNAL_BRANDING);
3820                                 break;
3821                         case MPT2SAS_HP_EMBEDDED_2_4_INTERNAL_SSDID:
3822                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3823                                     MPT2SAS_HP_EMBEDDED_2_4_INTERNAL_BRANDING);
3824                                 break;
3825                         default:
3826                                 pr_info(MPT3SAS_FMT
3827                                    "HP 6Gbps SAS HBA: Subsystem ID: 0x%X\n",
3828                                    ioc->name, ioc->pdev->subsystem_device);
3829                                 break;
3830                         }
3831                 default:
3832                         pr_info(MPT3SAS_FMT
3833                            "HP SAS HBA: Subsystem ID: 0x%X\n",
3834                            ioc->name, ioc->pdev->subsystem_device);
3835                         break;
3836                 }
3837         default:
3838                 break;
3839         }
3840 }
3841
3842 /**
3843  * _base_display_fwpkg_version - sends FWUpload request to pull FWPkg
3844  *                              version from FW Image Header.
3845  * @ioc: per adapter object
3846  *
3847  * Returns 0 for success, non-zero for failure.
3848  */
3849         static int
3850 _base_display_fwpkg_version(struct MPT3SAS_ADAPTER *ioc)
3851 {
3852         Mpi2FWImageHeader_t *FWImgHdr;
3853         Mpi25FWUploadRequest_t *mpi_request;
3854         Mpi2FWUploadReply_t mpi_reply;
3855         int r = 0;
3856         void *fwpkg_data = NULL;
3857         dma_addr_t fwpkg_data_dma;
3858         u16 smid, ioc_status;
3859         size_t data_length;
3860
3861         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3862                                 __func__));
3863
3864         if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
3865                 pr_err(MPT3SAS_FMT "%s: internal command already in use\n",
3866                                 ioc->name, __func__);
3867                 return -EAGAIN;
3868         }
3869
3870         data_length = sizeof(Mpi2FWImageHeader_t);
3871         fwpkg_data = pci_alloc_consistent(ioc->pdev, data_length,
3872                         &fwpkg_data_dma);
3873         if (!fwpkg_data) {
3874                 pr_err(MPT3SAS_FMT "failure at %s:%d/%s()!\n",
3875                                 ioc->name, __FILE__, __LINE__, __func__);
3876                 return -ENOMEM;
3877         }
3878
3879         smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
3880         if (!smid) {
3881                 pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n",
3882                                 ioc->name, __func__);
3883                 r = -EAGAIN;
3884                 goto out;
3885         }
3886
3887         ioc->base_cmds.status = MPT3_CMD_PENDING;
3888         mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
3889         ioc->base_cmds.smid = smid;
3890         memset(mpi_request, 0, sizeof(Mpi25FWUploadRequest_t));
3891         mpi_request->Function = MPI2_FUNCTION_FW_UPLOAD;
3892         mpi_request->ImageType = MPI2_FW_UPLOAD_ITYPE_FW_FLASH;
3893         mpi_request->ImageSize = cpu_to_le32(data_length);
3894         ioc->build_sg(ioc, &mpi_request->SGL, 0, 0, fwpkg_data_dma,
3895                         data_length);
3896         init_completion(&ioc->base_cmds.done);
3897         mpt3sas_base_put_smid_default(ioc, smid);
3898         /* Wait for 15 seconds */
3899         wait_for_completion_timeout(&ioc->base_cmds.done,
3900                         FW_IMG_HDR_READ_TIMEOUT*HZ);
3901         pr_info(MPT3SAS_FMT "%s: complete\n",
3902                         ioc->name, __func__);
3903         if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
3904                 pr_err(MPT3SAS_FMT "%s: timeout\n",
3905                                 ioc->name, __func__);
3906                 _debug_dump_mf(mpi_request,
3907                                 sizeof(Mpi25FWUploadRequest_t)/4);
3908                 r = -ETIME;
3909         } else {
3910                 memset(&mpi_reply, 0, sizeof(Mpi2FWUploadReply_t));
3911                 if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID) {
3912                         memcpy(&mpi_reply, ioc->base_cmds.reply,
3913                                         sizeof(Mpi2FWUploadReply_t));
3914                         ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
3915                                                 MPI2_IOCSTATUS_MASK;
3916                         if (ioc_status == MPI2_IOCSTATUS_SUCCESS) {
3917                                 FWImgHdr = (Mpi2FWImageHeader_t *)fwpkg_data;
3918                                 if (FWImgHdr->PackageVersion.Word) {
3919                                         pr_info(MPT3SAS_FMT "FW Package Version"
3920                                         "(%02d.%02d.%02d.%02d)\n",
3921                                         ioc->name,
3922                                         FWImgHdr->PackageVersion.Struct.Major,
3923                                         FWImgHdr->PackageVersion.Struct.Minor,
3924                                         FWImgHdr->PackageVersion.Struct.Unit,
3925                                         FWImgHdr->PackageVersion.Struct.Dev);
3926                                 }
3927                         } else {
3928                                 _debug_dump_mf(&mpi_reply,
3929                                                 sizeof(Mpi2FWUploadReply_t)/4);
3930                         }
3931                 }
3932         }
3933         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
3934 out:
3935         if (fwpkg_data)
3936                 pci_free_consistent(ioc->pdev, data_length, fwpkg_data,
3937                                 fwpkg_data_dma);
3938         return r;
3939 }
3940
3941 /**
3942  * _base_display_ioc_capabilities - Disply IOC's capabilities.
3943  * @ioc: per adapter object
3944  *
3945  * Return nothing.
3946  */
3947 static void
3948 _base_display_ioc_capabilities(struct MPT3SAS_ADAPTER *ioc)
3949 {
3950         int i = 0;
3951         char desc[16];
3952         u32 iounit_pg1_flags;
3953         u32 bios_version;
3954
3955         bios_version = le32_to_cpu(ioc->bios_pg3.BiosVersion);
3956         strncpy(desc, ioc->manu_pg0.ChipName, 16);
3957         pr_info(MPT3SAS_FMT "%s: FWVersion(%02d.%02d.%02d.%02d), "\
3958            "ChipRevision(0x%02x), BiosVersion(%02d.%02d.%02d.%02d)\n",
3959             ioc->name, desc,
3960            (ioc->facts.FWVersion.Word & 0xFF000000) >> 24,
3961            (ioc->facts.FWVersion.Word & 0x00FF0000) >> 16,
3962            (ioc->facts.FWVersion.Word & 0x0000FF00) >> 8,
3963            ioc->facts.FWVersion.Word & 0x000000FF,
3964            ioc->pdev->revision,
3965            (bios_version & 0xFF000000) >> 24,
3966            (bios_version & 0x00FF0000) >> 16,
3967            (bios_version & 0x0000FF00) >> 8,
3968             bios_version & 0x000000FF);
3969
3970         _base_display_OEMs_branding(ioc);
3971
3972         if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_NVME_DEVICES) {
3973                 pr_info("%sNVMe", i ? "," : "");
3974                 i++;
3975         }
3976
3977         pr_info(MPT3SAS_FMT "Protocol=(", ioc->name);
3978
3979         if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_INITIATOR) {
3980                 pr_info("Initiator");
3981                 i++;
3982         }
3983
3984         if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_TARGET) {
3985                 pr_info("%sTarget", i ? "," : "");
3986                 i++;
3987         }
3988
3989         i = 0;
3990         pr_info("), ");
3991         pr_info("Capabilities=(");
3992
3993         if (!ioc->hide_ir_msg) {
3994                 if (ioc->facts.IOCCapabilities &
3995                     MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID) {
3996                         pr_info("Raid");
3997                         i++;
3998                 }
3999         }
4000
4001         if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR) {
4002                 pr_info("%sTLR", i ? "," : "");
4003                 i++;
4004         }
4005
4006         if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_MULTICAST) {
4007                 pr_info("%sMulticast", i ? "," : "");
4008                 i++;
4009         }
4010
4011         if (ioc->facts.IOCCapabilities &
4012             MPI2_IOCFACTS_CAPABILITY_BIDIRECTIONAL_TARGET) {
4013                 pr_info("%sBIDI Target", i ? "," : "");
4014                 i++;
4015         }
4016
4017         if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP) {
4018                 pr_info("%sEEDP", i ? "," : "");
4019                 i++;
4020         }
4021
4022         if (ioc->facts.IOCCapabilities &
4023             MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER) {
4024                 pr_info("%sSnapshot Buffer", i ? "," : "");
4025                 i++;
4026         }
4027
4028         if (ioc->facts.IOCCapabilities &
4029             MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER) {
4030                 pr_info("%sDiag Trace Buffer", i ? "," : "");
4031                 i++;
4032         }
4033
4034         if (ioc->facts.IOCCapabilities &
4035             MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER) {
4036                 pr_info("%sDiag Extended Buffer", i ? "," : "");
4037                 i++;
4038         }
4039
4040         if (ioc->facts.IOCCapabilities &
4041             MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING) {
4042                 pr_info("%sTask Set Full", i ? "," : "");
4043                 i++;
4044         }
4045
4046         iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
4047         if (!(iounit_pg1_flags & MPI2_IOUNITPAGE1_NATIVE_COMMAND_Q_DISABLE)) {
4048                 pr_info("%sNCQ", i ? "," : "");
4049                 i++;
4050         }
4051
4052         pr_info(")\n");
4053 }
4054
4055 /**
4056  * mpt3sas_base_update_missing_delay - change the missing delay timers
4057  * @ioc: per adapter object
4058  * @device_missing_delay: amount of time till device is reported missing
4059  * @io_missing_delay: interval IO is returned when there is a missing device
4060  *
4061  * Return nothing.
4062  *
4063  * Passed on the command line, this function will modify the device missing
4064  * delay, as well as the io missing delay. This should be called at driver
4065  * load time.
4066  */
4067 void
4068 mpt3sas_base_update_missing_delay(struct MPT3SAS_ADAPTER *ioc,
4069         u16 device_missing_delay, u8 io_missing_delay)
4070 {
4071         u16 dmd, dmd_new, dmd_orignal;
4072         u8 io_missing_delay_original;
4073         u16 sz;
4074         Mpi2SasIOUnitPage1_t *sas_iounit_pg1 = NULL;
4075         Mpi2ConfigReply_t mpi_reply;
4076         u8 num_phys = 0;
4077         u16 ioc_status;
4078
4079         mpt3sas_config_get_number_hba_phys(ioc, &num_phys);
4080         if (!num_phys)
4081                 return;
4082
4083         sz = offsetof(Mpi2SasIOUnitPage1_t, PhyData) + (num_phys *
4084             sizeof(Mpi2SasIOUnit1PhyData_t));
4085         sas_iounit_pg1 = kzalloc(sz, GFP_KERNEL);
4086         if (!sas_iounit_pg1) {
4087                 pr_err(MPT3SAS_FMT "failure at %s:%d/%s()!\n",
4088                     ioc->name, __FILE__, __LINE__, __func__);
4089                 goto out;
4090         }
4091         if ((mpt3sas_config_get_sas_iounit_pg1(ioc, &mpi_reply,
4092             sas_iounit_pg1, sz))) {
4093                 pr_err(MPT3SAS_FMT "failure at %s:%d/%s()!\n",
4094                     ioc->name, __FILE__, __LINE__, __func__);
4095                 goto out;
4096         }
4097         ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
4098             MPI2_IOCSTATUS_MASK;
4099         if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
4100                 pr_err(MPT3SAS_FMT "failure at %s:%d/%s()!\n",
4101                     ioc->name, __FILE__, __LINE__, __func__);
4102                 goto out;
4103         }
4104
4105         /* device missing delay */
4106         dmd = sas_iounit_pg1->ReportDeviceMissingDelay;
4107         if (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16)
4108                 dmd = (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK) * 16;
4109         else
4110                 dmd = dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK;
4111         dmd_orignal = dmd;
4112         if (device_missing_delay > 0x7F) {
4113                 dmd = (device_missing_delay > 0x7F0) ? 0x7F0 :
4114                     device_missing_delay;
4115                 dmd = dmd / 16;
4116                 dmd |= MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16;
4117         } else
4118                 dmd = device_missing_delay;
4119         sas_iounit_pg1->ReportDeviceMissingDelay = dmd;
4120
4121         /* io missing delay */
4122         io_missing_delay_original = sas_iounit_pg1->IODeviceMissingDelay;
4123         sas_iounit_pg1->IODeviceMissingDelay = io_missing_delay;
4124
4125         if (!mpt3sas_config_set_sas_iounit_pg1(ioc, &mpi_reply, sas_iounit_pg1,
4126             sz)) {
4127                 if (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16)
4128                         dmd_new = (dmd &
4129                             MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK) * 16;
4130                 else
4131                         dmd_new =
4132                     dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK;
4133                 pr_info(MPT3SAS_FMT "device_missing_delay: old(%d), new(%d)\n",
4134                         ioc->name, dmd_orignal, dmd_new);
4135                 pr_info(MPT3SAS_FMT "ioc_missing_delay: old(%d), new(%d)\n",
4136                         ioc->name, io_missing_delay_original,
4137                     io_missing_delay);
4138                 ioc->device_missing_delay = dmd_new;
4139                 ioc->io_missing_delay = io_missing_delay;
4140         }
4141
4142 out:
4143         kfree(sas_iounit_pg1);
4144 }
4145 /**
4146  * _base_static_config_pages - static start of day config pages
4147  * @ioc: per adapter object
4148  *
4149  * Return nothing.
4150  */
4151 static void
4152 _base_static_config_pages(struct MPT3SAS_ADAPTER *ioc)
4153 {
4154         Mpi2ConfigReply_t mpi_reply;
4155         u32 iounit_pg1_flags;
4156
4157         ioc->nvme_abort_timeout = 30;
4158         mpt3sas_config_get_manufacturing_pg0(ioc, &mpi_reply, &ioc->manu_pg0);
4159         if (ioc->ir_firmware)
4160                 mpt3sas_config_get_manufacturing_pg10(ioc, &mpi_reply,
4161                     &ioc->manu_pg10);
4162
4163         /*
4164          * Ensure correct T10 PI operation if vendor left EEDPTagMode
4165          * flag unset in NVDATA.
4166          */
4167         mpt3sas_config_get_manufacturing_pg11(ioc, &mpi_reply, &ioc->manu_pg11);
4168         if (ioc->manu_pg11.EEDPTagMode == 0) {
4169                 pr_err("%s: overriding NVDATA EEDPTagMode setting\n",
4170                     ioc->name);
4171                 ioc->manu_pg11.EEDPTagMode &= ~0x3;
4172                 ioc->manu_pg11.EEDPTagMode |= 0x1;
4173                 mpt3sas_config_set_manufacturing_pg11(ioc, &mpi_reply,
4174                     &ioc->manu_pg11);
4175         }
4176         if (ioc->manu_pg11.AddlFlags2 & NVME_TASK_MNGT_CUSTOM_MASK)
4177                 ioc->tm_custom_handling = 1;
4178         else {
4179                 ioc->tm_custom_handling = 0;
4180                 if (ioc->manu_pg11.NVMeAbortTO < NVME_TASK_ABORT_MIN_TIMEOUT)
4181                         ioc->nvme_abort_timeout = NVME_TASK_ABORT_MIN_TIMEOUT;
4182                 else if (ioc->manu_pg11.NVMeAbortTO >
4183                                         NVME_TASK_ABORT_MAX_TIMEOUT)
4184                         ioc->nvme_abort_timeout = NVME_TASK_ABORT_MAX_TIMEOUT;
4185                 else
4186                         ioc->nvme_abort_timeout = ioc->manu_pg11.NVMeAbortTO;
4187         }
4188
4189         mpt3sas_config_get_bios_pg2(ioc, &mpi_reply, &ioc->bios_pg2);
4190         mpt3sas_config_get_bios_pg3(ioc, &mpi_reply, &ioc->bios_pg3);
4191         mpt3sas_config_get_ioc_pg8(ioc, &mpi_reply, &ioc->ioc_pg8);
4192         mpt3sas_config_get_iounit_pg0(ioc, &mpi_reply, &ioc->iounit_pg0);
4193         mpt3sas_config_get_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
4194         mpt3sas_config_get_iounit_pg8(ioc, &mpi_reply, &ioc->iounit_pg8);
4195         _base_display_ioc_capabilities(ioc);
4196
4197         /*
4198          * Enable task_set_full handling in iounit_pg1 when the
4199          * facts capabilities indicate that its supported.
4200          */
4201         iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
4202         if ((ioc->facts.IOCCapabilities &
4203             MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING))
4204                 iounit_pg1_flags &=
4205                     ~MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
4206         else
4207                 iounit_pg1_flags |=
4208                     MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
4209         ioc->iounit_pg1.Flags = cpu_to_le32(iounit_pg1_flags);
4210         mpt3sas_config_set_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
4211
4212         if (ioc->iounit_pg8.NumSensors)
4213                 ioc->temp_sensors_count = ioc->iounit_pg8.NumSensors;
4214 }
4215
4216 /**
4217  * mpt3sas_free_enclosure_list - release memory
4218  * @ioc: per adapter object
4219  *
4220  * Free memory allocated during encloure add.
4221  *
4222  * Return nothing.
4223  */
4224 void
4225 mpt3sas_free_enclosure_list(struct MPT3SAS_ADAPTER *ioc)
4226 {
4227         struct _enclosure_node *enclosure_dev, *enclosure_dev_next;
4228
4229         /* Free enclosure list */
4230         list_for_each_entry_safe(enclosure_dev,
4231                         enclosure_dev_next, &ioc->enclosure_list, list) {
4232                 list_del(&enclosure_dev->list);
4233                 kfree(enclosure_dev);
4234         }
4235 }
4236
4237 /**
4238  * _base_release_memory_pools - release memory
4239  * @ioc: per adapter object
4240  *
4241  * Free memory allocated from _base_allocate_memory_pools.
4242  *
4243  * Return nothing.
4244  */
4245 static void
4246 _base_release_memory_pools(struct MPT3SAS_ADAPTER *ioc)
4247 {
4248         int i = 0;
4249         int j = 0;
4250         struct chain_tracker *ct;
4251         struct reply_post_struct *rps;
4252
4253         dexitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
4254             __func__));
4255
4256         if (ioc->request) {
4257                 pci_free_consistent(ioc->pdev, ioc->request_dma_sz,
4258                     ioc->request,  ioc->request_dma);
4259                 dexitprintk(ioc, pr_info(MPT3SAS_FMT
4260                         "request_pool(0x%p): free\n",
4261                         ioc->name, ioc->request));
4262                 ioc->request = NULL;
4263         }
4264
4265         if (ioc->sense) {
4266                 dma_pool_free(ioc->sense_dma_pool, ioc->sense, ioc->sense_dma);
4267                 dma_pool_destroy(ioc->sense_dma_pool);
4268                 dexitprintk(ioc, pr_info(MPT3SAS_FMT
4269                         "sense_pool(0x%p): free\n",
4270                         ioc->name, ioc->sense));
4271                 ioc->sense = NULL;
4272         }
4273
4274         if (ioc->reply) {
4275                 dma_pool_free(ioc->reply_dma_pool, ioc->reply, ioc->reply_dma);
4276                 dma_pool_destroy(ioc->reply_dma_pool);
4277                 dexitprintk(ioc, pr_info(MPT3SAS_FMT
4278                         "reply_pool(0x%p): free\n",
4279                         ioc->name, ioc->reply));
4280                 ioc->reply = NULL;
4281         }
4282
4283         if (ioc->reply_free) {
4284                 dma_pool_free(ioc->reply_free_dma_pool, ioc->reply_free,
4285                     ioc->reply_free_dma);
4286                 dma_pool_destroy(ioc->reply_free_dma_pool);
4287                 dexitprintk(ioc, pr_info(MPT3SAS_FMT
4288                         "reply_free_pool(0x%p): free\n",
4289                         ioc->name, ioc->reply_free));
4290                 ioc->reply_free = NULL;
4291         }
4292
4293         if (ioc->reply_post) {
4294                 do {
4295                         rps = &ioc->reply_post[i];
4296                         if (rps->reply_post_free) {
4297                                 dma_pool_free(
4298                                     ioc->reply_post_free_dma_pool,
4299                                     rps->reply_post_free,
4300                                     rps->reply_post_free_dma);
4301                                 dexitprintk(ioc, pr_info(MPT3SAS_FMT
4302                                     "reply_post_free_pool(0x%p): free\n",
4303                                     ioc->name, rps->reply_post_free));
4304                                 rps->reply_post_free = NULL;
4305                         }
4306                 } while (ioc->rdpq_array_enable &&
4307                            (++i < ioc->reply_queue_count));
4308                 if (ioc->reply_post_free_array &&
4309                         ioc->rdpq_array_enable) {
4310                         dma_pool_free(ioc->reply_post_free_array_dma_pool,
4311                                 ioc->reply_post_free_array,
4312                                 ioc->reply_post_free_array_dma);
4313                         ioc->reply_post_free_array = NULL;
4314                 }
4315                 dma_pool_destroy(ioc->reply_post_free_array_dma_pool);
4316                 dma_pool_destroy(ioc->reply_post_free_dma_pool);
4317                 kfree(ioc->reply_post);
4318         }
4319
4320         if (ioc->pcie_sgl_dma_pool) {
4321                 for (i = 0; i < ioc->scsiio_depth; i++) {
4322                         dma_pool_free(ioc->pcie_sgl_dma_pool,
4323                                         ioc->pcie_sg_lookup[i].pcie_sgl,
4324                                         ioc->pcie_sg_lookup[i].pcie_sgl_dma);
4325                 }
4326                 if (ioc->pcie_sgl_dma_pool)
4327                         dma_pool_destroy(ioc->pcie_sgl_dma_pool);
4328         }
4329
4330         if (ioc->config_page) {
4331                 dexitprintk(ioc, pr_info(MPT3SAS_FMT
4332                     "config_page(0x%p): free\n", ioc->name,
4333                     ioc->config_page));
4334                 pci_free_consistent(ioc->pdev, ioc->config_page_sz,
4335                     ioc->config_page, ioc->config_page_dma);
4336         }
4337
4338         kfree(ioc->hpr_lookup);
4339         kfree(ioc->internal_lookup);
4340         if (ioc->chain_lookup) {
4341                 for (i = 0; i < ioc->scsiio_depth; i++) {
4342                         for (j = ioc->chains_per_prp_buffer;
4343                             j < ioc->chains_needed_per_io; j++) {
4344                                 ct = &ioc->chain_lookup[i].chains_per_smid[j];
4345                                 if (ct && ct->chain_buffer)
4346                                         dma_pool_free(ioc->chain_dma_pool,
4347                                                 ct->chain_buffer,
4348                                                 ct->chain_buffer_dma);
4349                         }
4350                         kfree(ioc->chain_lookup[i].chains_per_smid);
4351                 }
4352                 dma_pool_destroy(ioc->chain_dma_pool);
4353                 kfree(ioc->chain_lookup);
4354                 ioc->chain_lookup = NULL;
4355         }
4356 }
4357
4358 /**
4359  * is_MSB_are_same - checks whether all reply queues in a set are
4360  *      having same upper 32bits in their base memory address.
4361  * @reply_pool_start_address: Base address of a reply queue set
4362  * @pool_sz: Size of single Reply Descriptor Post Queues pool size
4363  *
4364  * Returns 1 if reply queues in a set have a same upper 32bits
4365  * in their base memory address,
4366  * else 0
4367  */
4368
4369 static int
4370 is_MSB_are_same(long reply_pool_start_address, u32 pool_sz)
4371 {
4372         long reply_pool_end_address;
4373
4374         reply_pool_end_address = reply_pool_start_address + pool_sz;
4375
4376         if (upper_32_bits(reply_pool_start_address) ==
4377                 upper_32_bits(reply_pool_end_address))
4378                 return 1;
4379         else
4380                 return 0;
4381 }
4382
4383 /**
4384  * _base_allocate_memory_pools - allocate start of day memory pools
4385  * @ioc: per adapter object
4386  *
4387  * Returns 0 success, anything else error
4388  */
4389 static int
4390 _base_allocate_memory_pools(struct MPT3SAS_ADAPTER *ioc)
4391 {
4392         struct mpt3sas_facts *facts;
4393         u16 max_sge_elements;
4394         u16 chains_needed_per_io;
4395         u32 sz, total_sz, reply_post_free_sz, reply_post_free_array_sz;
4396         u32 retry_sz;
4397         u16 max_request_credit, nvme_blocks_needed;
4398         unsigned short sg_tablesize;
4399         u16 sge_size;
4400         int i, j;
4401         struct chain_tracker *ct;
4402
4403         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
4404             __func__));
4405
4406
4407         retry_sz = 0;
4408         facts = &ioc->facts;
4409
4410         /* command line tunables for max sgl entries */
4411         if (max_sgl_entries != -1)
4412                 sg_tablesize = max_sgl_entries;
4413         else {
4414                 if (ioc->hba_mpi_version_belonged == MPI2_VERSION)
4415                         sg_tablesize = MPT2SAS_SG_DEPTH;
4416                 else
4417                         sg_tablesize = MPT3SAS_SG_DEPTH;
4418         }
4419
4420         /* max sgl entries <= MPT_KDUMP_MIN_PHYS_SEGMENTS in KDUMP mode */
4421         if (reset_devices)
4422                 sg_tablesize = min_t(unsigned short, sg_tablesize,
4423                    MPT_KDUMP_MIN_PHYS_SEGMENTS);
4424
4425         if (ioc->is_mcpu_endpoint)
4426                 ioc->shost->sg_tablesize = MPT_MIN_PHYS_SEGMENTS;
4427         else {
4428                 if (sg_tablesize < MPT_MIN_PHYS_SEGMENTS)
4429                         sg_tablesize = MPT_MIN_PHYS_SEGMENTS;
4430                 else if (sg_tablesize > MPT_MAX_PHYS_SEGMENTS) {
4431                         sg_tablesize = min_t(unsigned short, sg_tablesize,
4432                                         SG_MAX_SEGMENTS);
4433                         pr_warn(MPT3SAS_FMT
4434                                 "sg_tablesize(%u) is bigger than kernel "
4435                                 "defined SG_CHUNK_SIZE(%u)\n", ioc->name,
4436                                 sg_tablesize, MPT_MAX_PHYS_SEGMENTS);
4437                 }
4438                 ioc->shost->sg_tablesize = sg_tablesize;
4439         }
4440
4441         ioc->internal_depth = min_t(int, (facts->HighPriorityCredit + (5)),
4442                 (facts->RequestCredit / 4));
4443         if (ioc->internal_depth < INTERNAL_CMDS_COUNT) {
4444                 if (facts->RequestCredit <= (INTERNAL_CMDS_COUNT +
4445                                 INTERNAL_SCSIIO_CMDS_COUNT)) {
4446                         pr_err(MPT3SAS_FMT "IOC doesn't have enough Request \
4447                             Credits, it has just %d number of credits\n",
4448                             ioc->name, facts->RequestCredit);
4449                         return -ENOMEM;
4450                 }
4451                 ioc->internal_depth = 10;
4452         }
4453
4454         ioc->hi_priority_depth = ioc->internal_depth - (5);
4455         /* command line tunables  for max controller queue depth */
4456         if (max_queue_depth != -1 && max_queue_depth != 0) {
4457                 max_request_credit = min_t(u16, max_queue_depth +
4458                         ioc->internal_depth, facts->RequestCredit);
4459                 if (max_request_credit > MAX_HBA_QUEUE_DEPTH)
4460                         max_request_credit =  MAX_HBA_QUEUE_DEPTH;
4461         } else if (reset_devices)
4462                 max_request_credit = min_t(u16, facts->RequestCredit,
4463                     (MPT3SAS_KDUMP_SCSI_IO_DEPTH + ioc->internal_depth));
4464         else
4465                 max_request_credit = min_t(u16, facts->RequestCredit,
4466                     MAX_HBA_QUEUE_DEPTH);
4467
4468         /* Firmware maintains additional facts->HighPriorityCredit number of
4469          * credits for HiPriprity Request messages, so hba queue depth will be
4470          * sum of max_request_credit and high priority queue depth.
4471          */
4472         ioc->hba_queue_depth = max_request_credit + ioc->hi_priority_depth;
4473
4474         /* request frame size */
4475         ioc->request_sz = facts->IOCRequestFrameSize * 4;
4476
4477         /* reply frame size */
4478         ioc->reply_sz = facts->ReplyFrameSize * 4;
4479
4480         /* chain segment size */
4481         if (ioc->hba_mpi_version_belonged != MPI2_VERSION) {
4482                 if (facts->IOCMaxChainSegmentSize)
4483                         ioc->chain_segment_sz =
4484                                         facts->IOCMaxChainSegmentSize *
4485                                         MAX_CHAIN_ELEMT_SZ;
4486                 else
4487                 /* set to 128 bytes size if IOCMaxChainSegmentSize is zero */
4488                         ioc->chain_segment_sz = DEFAULT_NUM_FWCHAIN_ELEMTS *
4489                                                     MAX_CHAIN_ELEMT_SZ;
4490         } else
4491                 ioc->chain_segment_sz = ioc->request_sz;
4492
4493         /* calculate the max scatter element size */
4494         sge_size = max_t(u16, ioc->sge_size, ioc->sge_size_ieee);
4495
4496  retry_allocation:
4497         total_sz = 0;
4498         /* calculate number of sg elements left over in the 1st frame */
4499         max_sge_elements = ioc->request_sz - ((sizeof(Mpi2SCSIIORequest_t) -
4500             sizeof(Mpi2SGEIOUnion_t)) + sge_size);
4501         ioc->max_sges_in_main_message = max_sge_elements/sge_size;
4502
4503         /* now do the same for a chain buffer */
4504         max_sge_elements = ioc->chain_segment_sz - sge_size;
4505         ioc->max_sges_in_chain_message = max_sge_elements/sge_size;
4506
4507         /*
4508          *  MPT3SAS_SG_DEPTH = CONFIG_FUSION_MAX_SGE
4509          */
4510         chains_needed_per_io = ((ioc->shost->sg_tablesize -
4511            ioc->max_sges_in_main_message)/ioc->max_sges_in_chain_message)
4512             + 1;
4513         if (chains_needed_per_io > facts->MaxChainDepth) {
4514                 chains_needed_per_io = facts->MaxChainDepth;
4515                 ioc->shost->sg_tablesize = min_t(u16,
4516                 ioc->max_sges_in_main_message + (ioc->max_sges_in_chain_message
4517                 * chains_needed_per_io), ioc->shost->sg_tablesize);
4518         }
4519         ioc->chains_needed_per_io = chains_needed_per_io;
4520
4521         /* reply free queue sizing - taking into account for 64 FW events */
4522         ioc->reply_free_queue_depth = ioc->hba_queue_depth + 64;
4523
4524         /* mCPU manage single counters for simplicity */
4525         if (ioc->is_mcpu_endpoint)
4526                 ioc->reply_post_queue_depth = ioc->reply_free_queue_depth;
4527         else {
4528                 /* calculate reply descriptor post queue depth */
4529                 ioc->reply_post_queue_depth = ioc->hba_queue_depth +
4530                         ioc->reply_free_queue_depth +  1;
4531                 /* align the reply post queue on the next 16 count boundary */
4532                 if (ioc->reply_post_queue_depth % 16)
4533                         ioc->reply_post_queue_depth += 16 -
4534                                 (ioc->reply_post_queue_depth % 16);
4535         }
4536
4537         if (ioc->reply_post_queue_depth >
4538             facts->MaxReplyDescriptorPostQueueDepth) {
4539                 ioc->reply_post_queue_depth =
4540                                 facts->MaxReplyDescriptorPostQueueDepth -
4541                     (facts->MaxReplyDescriptorPostQueueDepth % 16);
4542                 ioc->hba_queue_depth =
4543                                 ((ioc->reply_post_queue_depth - 64) / 2) - 1;
4544                 ioc->reply_free_queue_depth = ioc->hba_queue_depth + 64;
4545         }
4546
4547         dinitprintk(ioc, pr_info(MPT3SAS_FMT "scatter gather: " \
4548             "sge_in_main_msg(%d), sge_per_chain(%d), sge_per_io(%d), "
4549             "chains_per_io(%d)\n", ioc->name, ioc->max_sges_in_main_message,
4550             ioc->max_sges_in_chain_message, ioc->shost->sg_tablesize,
4551             ioc->chains_needed_per_io));
4552
4553         /* reply post queue, 16 byte align */
4554         reply_post_free_sz = ioc->reply_post_queue_depth *
4555             sizeof(Mpi2DefaultReplyDescriptor_t);
4556
4557         sz = reply_post_free_sz;
4558         if (_base_is_controller_msix_enabled(ioc) && !ioc->rdpq_array_enable)
4559                 sz *= ioc->reply_queue_count;
4560
4561         ioc->reply_post = kcalloc((ioc->rdpq_array_enable) ?
4562             (ioc->reply_queue_count):1,
4563             sizeof(struct reply_post_struct), GFP_KERNEL);
4564
4565         if (!ioc->reply_post) {
4566                 pr_err(MPT3SAS_FMT "reply_post_free pool: kcalloc failed\n",
4567                         ioc->name);
4568                 goto out;
4569         }
4570         ioc->reply_post_free_dma_pool = dma_pool_create("reply_post_free pool",
4571             &ioc->pdev->dev, sz, 16, 0);
4572         if (!ioc->reply_post_free_dma_pool) {
4573                 pr_err(MPT3SAS_FMT
4574                  "reply_post_free pool: dma_pool_create failed\n",
4575                  ioc->name);
4576                 goto out;
4577         }
4578         i = 0;
4579         do {
4580                 ioc->reply_post[i].reply_post_free =
4581                     dma_pool_alloc(ioc->reply_post_free_dma_pool,
4582                     GFP_KERNEL,
4583                     &ioc->reply_post[i].reply_post_free_dma);
4584                 if (!ioc->reply_post[i].reply_post_free) {
4585                         pr_err(MPT3SAS_FMT
4586                         "reply_post_free pool: dma_pool_alloc failed\n",
4587                         ioc->name);
4588                         goto out;
4589                 }
4590                 memset(ioc->reply_post[i].reply_post_free, 0, sz);
4591                 dinitprintk(ioc, pr_info(MPT3SAS_FMT
4592                     "reply post free pool (0x%p): depth(%d),"
4593                     "element_size(%d), pool_size(%d kB)\n", ioc->name,
4594                     ioc->reply_post[i].reply_post_free,
4595                     ioc->reply_post_queue_depth, 8, sz/1024));
4596                 dinitprintk(ioc, pr_info(MPT3SAS_FMT
4597                     "reply_post_free_dma = (0x%llx)\n", ioc->name,
4598                     (unsigned long long)
4599                     ioc->reply_post[i].reply_post_free_dma));
4600                 total_sz += sz;
4601         } while (ioc->rdpq_array_enable && (++i < ioc->reply_queue_count));
4602
4603         if (ioc->dma_mask == 64) {
4604                 if (_base_change_consistent_dma_mask(ioc, ioc->pdev) != 0) {
4605                         pr_warn(MPT3SAS_FMT
4606                             "no suitable consistent DMA mask for %s\n",
4607                             ioc->name, pci_name(ioc->pdev));
4608                         goto out;
4609                 }
4610         }
4611
4612         ioc->scsiio_depth = ioc->hba_queue_depth -
4613             ioc->hi_priority_depth - ioc->internal_depth;
4614
4615         /* set the scsi host can_queue depth
4616          * with some internal commands that could be outstanding
4617          */
4618         ioc->shost->can_queue = ioc->scsiio_depth - INTERNAL_SCSIIO_CMDS_COUNT;
4619         dinitprintk(ioc, pr_info(MPT3SAS_FMT
4620                 "scsi host: can_queue depth (%d)\n",
4621                 ioc->name, ioc->shost->can_queue));
4622
4623
4624         /* contiguous pool for request and chains, 16 byte align, one extra "
4625          * "frame for smid=0
4626          */
4627         ioc->chain_depth = ioc->chains_needed_per_io * ioc->scsiio_depth;
4628         sz = ((ioc->scsiio_depth + 1) * ioc->request_sz);
4629
4630         /* hi-priority queue */
4631         sz += (ioc->hi_priority_depth * ioc->request_sz);
4632
4633         /* internal queue */
4634         sz += (ioc->internal_depth * ioc->request_sz);
4635
4636         ioc->request_dma_sz = sz;
4637         ioc->request = pci_alloc_consistent(ioc->pdev, sz, &ioc->request_dma);
4638         if (!ioc->request) {
4639                 pr_err(MPT3SAS_FMT "request pool: pci_alloc_consistent " \
4640                     "failed: hba_depth(%d), chains_per_io(%d), frame_sz(%d), "
4641                     "total(%d kB)\n", ioc->name, ioc->hba_queue_depth,
4642                     ioc->chains_needed_per_io, ioc->request_sz, sz/1024);
4643                 if (ioc->scsiio_depth < MPT3SAS_SAS_QUEUE_DEPTH)
4644                         goto out;
4645                 retry_sz = 64;
4646                 ioc->hba_queue_depth -= retry_sz;
4647                 _base_release_memory_pools(ioc);
4648                 goto retry_allocation;
4649         }
4650
4651         if (retry_sz)
4652                 pr_err(MPT3SAS_FMT "request pool: pci_alloc_consistent " \
4653                     "succeed: hba_depth(%d), chains_per_io(%d), frame_sz(%d), "
4654                     "total(%d kb)\n", ioc->name, ioc->hba_queue_depth,
4655                     ioc->chains_needed_per_io, ioc->request_sz, sz/1024);
4656
4657         /* hi-priority queue */
4658         ioc->hi_priority = ioc->request + ((ioc->scsiio_depth + 1) *
4659             ioc->request_sz);
4660         ioc->hi_priority_dma = ioc->request_dma + ((ioc->scsiio_depth + 1) *
4661             ioc->request_sz);
4662
4663         /* internal queue */
4664         ioc->internal = ioc->hi_priority + (ioc->hi_priority_depth *
4665             ioc->request_sz);
4666         ioc->internal_dma = ioc->hi_priority_dma + (ioc->hi_priority_depth *
4667             ioc->request_sz);
4668
4669         dinitprintk(ioc, pr_info(MPT3SAS_FMT
4670                 "request pool(0x%p): depth(%d), frame_size(%d), pool_size(%d kB)\n",
4671                 ioc->name, ioc->request, ioc->hba_queue_depth, ioc->request_sz,
4672             (ioc->hba_queue_depth * ioc->request_sz)/1024));
4673
4674         dinitprintk(ioc, pr_info(MPT3SAS_FMT "request pool: dma(0x%llx)\n",
4675             ioc->name, (unsigned long long) ioc->request_dma));
4676         total_sz += sz;
4677
4678         dinitprintk(ioc, pr_info(MPT3SAS_FMT "scsiio(0x%p): depth(%d)\n",
4679                 ioc->name, ioc->request, ioc->scsiio_depth));
4680
4681         ioc->chain_depth = min_t(u32, ioc->chain_depth, MAX_CHAIN_DEPTH);
4682         sz = ioc->scsiio_depth * sizeof(struct chain_lookup);
4683         ioc->chain_lookup = kzalloc(sz, GFP_KERNEL);
4684         if (!ioc->chain_lookup) {
4685                 pr_err(MPT3SAS_FMT "chain_lookup: __get_free_pages "
4686                                 "failed\n", ioc->name);
4687                 goto out;
4688         }
4689
4690         sz = ioc->chains_needed_per_io * sizeof(struct chain_tracker);
4691         for (i = 0; i < ioc->scsiio_depth; i++) {
4692                 ioc->chain_lookup[i].chains_per_smid = kzalloc(sz, GFP_KERNEL);
4693                 if (!ioc->chain_lookup[i].chains_per_smid) {
4694                         pr_err(MPT3SAS_FMT "chain_lookup: "
4695                                         " kzalloc failed\n", ioc->name);
4696                         goto out;
4697                 }
4698         }
4699
4700         /* initialize hi-priority queue smid's */
4701         ioc->hpr_lookup = kcalloc(ioc->hi_priority_depth,
4702             sizeof(struct request_tracker), GFP_KERNEL);
4703         if (!ioc->hpr_lookup) {
4704                 pr_err(MPT3SAS_FMT "hpr_lookup: kcalloc failed\n",
4705                     ioc->name);
4706                 goto out;
4707         }
4708         ioc->hi_priority_smid = ioc->scsiio_depth + 1;
4709         dinitprintk(ioc, pr_info(MPT3SAS_FMT
4710                 "hi_priority(0x%p): depth(%d), start smid(%d)\n",
4711                 ioc->name, ioc->hi_priority,
4712             ioc->hi_priority_depth, ioc->hi_priority_smid));
4713
4714         /* initialize internal queue smid's */
4715         ioc->internal_lookup = kcalloc(ioc->internal_depth,
4716             sizeof(struct request_tracker), GFP_KERNEL);
4717         if (!ioc->internal_lookup) {
4718                 pr_err(MPT3SAS_FMT "internal_lookup: kcalloc failed\n",
4719                     ioc->name);
4720                 goto out;
4721         }
4722         ioc->internal_smid = ioc->hi_priority_smid + ioc->hi_priority_depth;
4723         dinitprintk(ioc, pr_info(MPT3SAS_FMT
4724                 "internal(0x%p): depth(%d), start smid(%d)\n",
4725                 ioc->name, ioc->internal,
4726             ioc->internal_depth, ioc->internal_smid));
4727         /*
4728          * The number of NVMe page sized blocks needed is:
4729          *     (((sg_tablesize * 8) - 1) / (page_size - 8)) + 1
4730          * ((sg_tablesize * 8) - 1) is the max PRP's minus the first PRP entry
4731          * that is placed in the main message frame.  8 is the size of each PRP
4732          * entry or PRP list pointer entry.  8 is subtracted from page_size
4733          * because of the PRP list pointer entry at the end of a page, so this
4734          * is not counted as a PRP entry.  The 1 added page is a round up.
4735          *
4736          * To avoid allocation failures due to the amount of memory that could
4737          * be required for NVMe PRP's, only each set of NVMe blocks will be
4738          * contiguous, so a new set is allocated for each possible I/O.
4739          */
4740         ioc->chains_per_prp_buffer = 0;
4741         if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_NVME_DEVICES) {
4742                 nvme_blocks_needed =
4743                         (ioc->shost->sg_tablesize * NVME_PRP_SIZE) - 1;
4744                 nvme_blocks_needed /= (ioc->page_size - NVME_PRP_SIZE);
4745                 nvme_blocks_needed++;
4746
4747                 sz = sizeof(struct pcie_sg_list) * ioc->scsiio_depth;
4748                 ioc->pcie_sg_lookup = kzalloc(sz, GFP_KERNEL);
4749                 if (!ioc->pcie_sg_lookup) {
4750                         pr_info(MPT3SAS_FMT
4751                             "PCIe SGL lookup: kzalloc failed\n", ioc->name);
4752                         goto out;
4753                 }
4754                 sz = nvme_blocks_needed * ioc->page_size;
4755                 ioc->pcie_sgl_dma_pool =
4756                         dma_pool_create("PCIe SGL pool", &ioc->pdev->dev, sz, 16, 0);
4757                 if (!ioc->pcie_sgl_dma_pool) {
4758                         pr_info(MPT3SAS_FMT
4759                             "PCIe SGL pool: dma_pool_create failed\n",
4760                             ioc->name);
4761                         goto out;
4762                 }
4763
4764                 ioc->chains_per_prp_buffer = sz/ioc->chain_segment_sz;
4765                 ioc->chains_per_prp_buffer = min(ioc->chains_per_prp_buffer,
4766                                                 ioc->chains_needed_per_io);
4767
4768                 for (i = 0; i < ioc->scsiio_depth; i++) {
4769                         ioc->pcie_sg_lookup[i].pcie_sgl = dma_pool_alloc(
4770                                 ioc->pcie_sgl_dma_pool, GFP_KERNEL,
4771                                 &ioc->pcie_sg_lookup[i].pcie_sgl_dma);
4772                         if (!ioc->pcie_sg_lookup[i].pcie_sgl) {
4773                                 pr_info(MPT3SAS_FMT
4774                                     "PCIe SGL pool: dma_pool_alloc failed\n",
4775                                     ioc->name);
4776                                 goto out;
4777                         }
4778                         for (j = 0; j < ioc->chains_per_prp_buffer; j++) {
4779                                 ct = &ioc->chain_lookup[i].chains_per_smid[j];
4780                                 ct->chain_buffer =
4781                                     ioc->pcie_sg_lookup[i].pcie_sgl +
4782                                     (j * ioc->chain_segment_sz);
4783                                 ct->chain_buffer_dma =
4784                                     ioc->pcie_sg_lookup[i].pcie_sgl_dma +
4785                                     (j * ioc->chain_segment_sz);
4786                         }
4787                 }
4788
4789                 dinitprintk(ioc, pr_info(MPT3SAS_FMT "PCIe sgl pool depth(%d), "
4790                         "element_size(%d), pool_size(%d kB)\n", ioc->name,
4791                         ioc->scsiio_depth, sz, (sz * ioc->scsiio_depth)/1024));
4792                 dinitprintk(ioc, pr_info(MPT3SAS_FMT "Number of chains can "
4793                     "fit in a PRP page(%d)\n", ioc->name,
4794                     ioc->chains_per_prp_buffer));
4795                 total_sz += sz * ioc->scsiio_depth;
4796         }
4797
4798         ioc->chain_dma_pool = dma_pool_create("chain pool", &ioc->pdev->dev,
4799             ioc->chain_segment_sz, 16, 0);
4800         if (!ioc->chain_dma_pool) {
4801                 pr_err(MPT3SAS_FMT "chain_dma_pool: dma_pool_create failed\n",
4802                         ioc->name);
4803                 goto out;
4804         }
4805         for (i = 0; i < ioc->scsiio_depth; i++) {
4806                 for (j = ioc->chains_per_prp_buffer;
4807                                 j < ioc->chains_needed_per_io; j++) {
4808                         ct = &ioc->chain_lookup[i].chains_per_smid[j];
4809                         ct->chain_buffer = dma_pool_alloc(
4810                                         ioc->chain_dma_pool, GFP_KERNEL,
4811                                         &ct->chain_buffer_dma);
4812                         if (!ct->chain_buffer) {
4813                                 pr_err(MPT3SAS_FMT "chain_lookup: "
4814                                 " pci_pool_alloc failed\n", ioc->name);
4815                                 _base_release_memory_pools(ioc);
4816                                 goto out;
4817                         }
4818                 }
4819                 total_sz += ioc->chain_segment_sz;
4820         }
4821
4822         dinitprintk(ioc, pr_info(MPT3SAS_FMT
4823                 "chain pool depth(%d), frame_size(%d), pool_size(%d kB)\n",
4824                 ioc->name, ioc->chain_depth, ioc->chain_segment_sz,
4825                 ((ioc->chain_depth *  ioc->chain_segment_sz))/1024));
4826
4827         /* sense buffers, 4 byte align */
4828         sz = ioc->scsiio_depth * SCSI_SENSE_BUFFERSIZE;
4829         ioc->sense_dma_pool = dma_pool_create("sense pool", &ioc->pdev->dev, sz,
4830                                               4, 0);
4831         if (!ioc->sense_dma_pool) {
4832                 pr_err(MPT3SAS_FMT "sense pool: dma_pool_create failed\n",
4833                     ioc->name);
4834                 goto out;
4835         }
4836         ioc->sense = dma_pool_alloc(ioc->sense_dma_pool, GFP_KERNEL,
4837             &ioc->sense_dma);
4838         if (!ioc->sense) {
4839                 pr_err(MPT3SAS_FMT "sense pool: dma_pool_alloc failed\n",
4840                     ioc->name);
4841                 goto out;
4842         }
4843         /* sense buffer requires to be in same 4 gb region.
4844          * Below function will check the same.
4845          * In case of failure, new pci pool will be created with updated
4846          * alignment. Older allocation and pool will be destroyed.
4847          * Alignment will be used such a way that next allocation if
4848          * success, will always meet same 4gb region requirement.
4849          * Actual requirement is not alignment, but we need start and end of
4850          * DMA address must have same upper 32 bit address.
4851          */
4852         if (!is_MSB_are_same((long)ioc->sense, sz)) {
4853                 //Release Sense pool & Reallocate
4854                 dma_pool_free(ioc->sense_dma_pool, ioc->sense, ioc->sense_dma);
4855                 dma_pool_destroy(ioc->sense_dma_pool);
4856                 ioc->sense = NULL;
4857
4858                 ioc->sense_dma_pool =
4859                         dma_pool_create("sense pool", &ioc->pdev->dev, sz,
4860                                                 roundup_pow_of_two(sz), 0);
4861                 if (!ioc->sense_dma_pool) {
4862                         pr_err(MPT3SAS_FMT "sense pool: pci_pool_create failed\n",
4863                                         ioc->name);
4864                         goto out;
4865                 }
4866                 ioc->sense = dma_pool_alloc(ioc->sense_dma_pool, GFP_KERNEL,
4867                                 &ioc->sense_dma);
4868                 if (!ioc->sense) {
4869                         pr_err(MPT3SAS_FMT "sense pool: pci_pool_alloc failed\n",
4870                                         ioc->name);
4871                         goto out;
4872                 }
4873         }
4874         dinitprintk(ioc, pr_info(MPT3SAS_FMT
4875             "sense pool(0x%p): depth(%d), element_size(%d), pool_size"
4876             "(%d kB)\n", ioc->name, ioc->sense, ioc->scsiio_depth,
4877             SCSI_SENSE_BUFFERSIZE, sz/1024));
4878         dinitprintk(ioc, pr_info(MPT3SAS_FMT "sense_dma(0x%llx)\n",
4879             ioc->name, (unsigned long long)ioc->sense_dma));
4880         total_sz += sz;
4881
4882         /* reply pool, 4 byte align */
4883         sz = ioc->reply_free_queue_depth * ioc->reply_sz;
4884         ioc->reply_dma_pool = dma_pool_create("reply pool", &ioc->pdev->dev, sz,
4885                                               4, 0);
4886         if (!ioc->reply_dma_pool) {
4887                 pr_err(MPT3SAS_FMT "reply pool: dma_pool_create failed\n",
4888                     ioc->name);
4889                 goto out;
4890         }
4891         ioc->reply = dma_pool_alloc(ioc->reply_dma_pool, GFP_KERNEL,
4892             &ioc->reply_dma);
4893         if (!ioc->reply) {
4894                 pr_err(MPT3SAS_FMT "reply pool: dma_pool_alloc failed\n",
4895                     ioc->name);
4896                 goto out;
4897         }
4898         ioc->reply_dma_min_address = (u32)(ioc->reply_dma);
4899         ioc->reply_dma_max_address = (u32)(ioc->reply_dma) + sz;
4900         dinitprintk(ioc, pr_info(MPT3SAS_FMT
4901                 "reply pool(0x%p): depth(%d), frame_size(%d), pool_size(%d kB)\n",
4902                 ioc->name, ioc->reply,
4903             ioc->reply_free_queue_depth, ioc->reply_sz, sz/1024));
4904         dinitprintk(ioc, pr_info(MPT3SAS_FMT "reply_dma(0x%llx)\n",
4905             ioc->name, (unsigned long long)ioc->reply_dma));
4906         total_sz += sz;
4907
4908         /* reply free queue, 16 byte align */
4909         sz = ioc->reply_free_queue_depth * 4;
4910         ioc->reply_free_dma_pool = dma_pool_create("reply_free pool",
4911             &ioc->pdev->dev, sz, 16, 0);
4912         if (!ioc->reply_free_dma_pool) {
4913                 pr_err(MPT3SAS_FMT "reply_free pool: dma_pool_create failed\n",
4914                         ioc->name);
4915                 goto out;
4916         }
4917         ioc->reply_free = dma_pool_alloc(ioc->reply_free_dma_pool, GFP_KERNEL,
4918             &ioc->reply_free_dma);
4919         if (!ioc->reply_free) {
4920                 pr_err(MPT3SAS_FMT "reply_free pool: dma_pool_alloc failed\n",
4921                         ioc->name);
4922                 goto out;
4923         }
4924         memset(ioc->reply_free, 0, sz);
4925         dinitprintk(ioc, pr_info(MPT3SAS_FMT "reply_free pool(0x%p): " \
4926             "depth(%d), element_size(%d), pool_size(%d kB)\n", ioc->name,
4927             ioc->reply_free, ioc->reply_free_queue_depth, 4, sz/1024));
4928         dinitprintk(ioc, pr_info(MPT3SAS_FMT
4929                 "reply_free_dma (0x%llx)\n",
4930                 ioc->name, (unsigned long long)ioc->reply_free_dma));
4931         total_sz += sz;
4932
4933         if (ioc->rdpq_array_enable) {
4934                 reply_post_free_array_sz = ioc->reply_queue_count *
4935                     sizeof(Mpi2IOCInitRDPQArrayEntry);
4936                 ioc->reply_post_free_array_dma_pool =
4937                     dma_pool_create("reply_post_free_array pool",
4938                     &ioc->pdev->dev, reply_post_free_array_sz, 16, 0);
4939                 if (!ioc->reply_post_free_array_dma_pool) {
4940                         dinitprintk(ioc,
4941                             pr_info(MPT3SAS_FMT "reply_post_free_array pool: "
4942                             "dma_pool_create failed\n", ioc->name));
4943                         goto out;
4944                 }
4945                 ioc->reply_post_free_array =
4946                     dma_pool_alloc(ioc->reply_post_free_array_dma_pool,
4947                     GFP_KERNEL, &ioc->reply_post_free_array_dma);
4948                 if (!ioc->reply_post_free_array) {
4949                         dinitprintk(ioc,
4950                             pr_info(MPT3SAS_FMT "reply_post_free_array pool: "
4951                             "dma_pool_alloc failed\n", ioc->name));
4952                         goto out;
4953                 }
4954         }
4955         ioc->config_page_sz = 512;
4956         ioc->config_page = pci_alloc_consistent(ioc->pdev,
4957             ioc->config_page_sz, &ioc->config_page_dma);
4958         if (!ioc->config_page) {
4959                 pr_err(MPT3SAS_FMT
4960                         "config page: dma_pool_alloc failed\n",
4961                         ioc->name);
4962                 goto out;
4963         }
4964         dinitprintk(ioc, pr_info(MPT3SAS_FMT
4965                 "config page(0x%p): size(%d)\n",
4966                 ioc->name, ioc->config_page, ioc->config_page_sz));
4967         dinitprintk(ioc, pr_info(MPT3SAS_FMT "config_page_dma(0x%llx)\n",
4968                 ioc->name, (unsigned long long)ioc->config_page_dma));
4969         total_sz += ioc->config_page_sz;
4970
4971         pr_info(MPT3SAS_FMT "Allocated physical memory: size(%d kB)\n",
4972             ioc->name, total_sz/1024);
4973         pr_info(MPT3SAS_FMT
4974                 "Current Controller Queue Depth(%d),Max Controller Queue Depth(%d)\n",
4975             ioc->name, ioc->shost->can_queue, facts->RequestCredit);
4976         pr_info(MPT3SAS_FMT "Scatter Gather Elements per IO(%d)\n",
4977             ioc->name, ioc->shost->sg_tablesize);
4978         return 0;
4979
4980  out:
4981         return -ENOMEM;
4982 }
4983
4984 /**
4985  * mpt3sas_base_get_iocstate - Get the current state of a MPT adapter.
4986  * @ioc: Pointer to MPT_ADAPTER structure
4987  * @cooked: Request raw or cooked IOC state
4988  *
4989  * Returns all IOC Doorbell register bits if cooked==0, else just the
4990  * Doorbell bits in MPI_IOC_STATE_MASK.
4991  */
4992 u32
4993 mpt3sas_base_get_iocstate(struct MPT3SAS_ADAPTER *ioc, int cooked)
4994 {
4995         u32 s, sc;
4996
4997         s = readl(&ioc->chip->Doorbell);
4998         sc = s & MPI2_IOC_STATE_MASK;
4999         return cooked ? sc : s;
5000 }
5001
5002 /**
5003  * _base_wait_on_iocstate - waiting on a particular ioc state
5004  * @ioc_state: controller state { READY, OPERATIONAL, or RESET }
5005  * @timeout: timeout in second
5006  *
5007  * Returns 0 for success, non-zero for failure.
5008  */
5009 static int
5010 _base_wait_on_iocstate(struct MPT3SAS_ADAPTER *ioc, u32 ioc_state, int timeout)
5011 {
5012         u32 count, cntdn;
5013         u32 current_state;
5014
5015         count = 0;
5016         cntdn = 1000 * timeout;
5017         do {
5018                 current_state = mpt3sas_base_get_iocstate(ioc, 1);
5019                 if (current_state == ioc_state)
5020                         return 0;
5021                 if (count && current_state == MPI2_IOC_STATE_FAULT)
5022                         break;
5023
5024                 usleep_range(1000, 1500);
5025                 count++;
5026         } while (--cntdn);
5027
5028         return current_state;
5029 }
5030
5031 /**
5032  * _base_wait_for_doorbell_int - waiting for controller interrupt(generated by
5033  * a write to the doorbell)
5034  * @ioc: per adapter object
5035  * @timeout: timeout in second
5036  *
5037  * Returns 0 for success, non-zero for failure.
5038  *
5039  * Notes: MPI2_HIS_IOC2SYS_DB_STATUS - set to one when IOC writes to doorbell.
5040  */
5041 static int
5042 _base_diag_reset(struct MPT3SAS_ADAPTER *ioc);
5043
5044 static int
5045 _base_wait_for_doorbell_int(struct MPT3SAS_ADAPTER *ioc, int timeout)
5046 {
5047         u32 cntdn, count;
5048         u32 int_status;
5049
5050         count = 0;
5051         cntdn = 1000 * timeout;
5052         do {
5053                 int_status = readl(&ioc->chip->HostInterruptStatus);
5054                 if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
5055                         dhsprintk(ioc, pr_info(MPT3SAS_FMT
5056                                 "%s: successful count(%d), timeout(%d)\n",
5057                                 ioc->name, __func__, count, timeout));
5058                         return 0;
5059                 }
5060
5061                 usleep_range(1000, 1500);
5062                 count++;
5063         } while (--cntdn);
5064
5065         pr_err(MPT3SAS_FMT
5066                 "%s: failed due to timeout count(%d), int_status(%x)!\n",
5067                 ioc->name, __func__, count, int_status);
5068         return -EFAULT;
5069 }
5070
5071 static int
5072 _base_spin_on_doorbell_int(struct MPT3SAS_ADAPTER *ioc, int timeout)
5073 {
5074         u32 cntdn, count;
5075         u32 int_status;
5076
5077         count = 0;
5078         cntdn = 2000 * timeout;
5079         do {
5080                 int_status = readl(&ioc->chip->HostInterruptStatus);
5081                 if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
5082                         dhsprintk(ioc, pr_info(MPT3SAS_FMT
5083                                 "%s: successful count(%d), timeout(%d)\n",
5084                                 ioc->name, __func__, count, timeout));
5085                         return 0;
5086                 }
5087
5088                 udelay(500);
5089                 count++;
5090         } while (--cntdn);
5091
5092         pr_err(MPT3SAS_FMT
5093                 "%s: failed due to timeout count(%d), int_status(%x)!\n",
5094                 ioc->name, __func__, count, int_status);
5095         return -EFAULT;
5096
5097 }
5098
5099 /**
5100  * _base_wait_for_doorbell_ack - waiting for controller to read the doorbell.
5101  * @ioc: per adapter object
5102  * @timeout: timeout in second
5103  *
5104  * Returns 0 for success, non-zero for failure.
5105  *
5106  * Notes: MPI2_HIS_SYS2IOC_DB_STATUS - set to one when host writes to
5107  * doorbell.
5108  */
5109 static int
5110 _base_wait_for_doorbell_ack(struct MPT3SAS_ADAPTER *ioc, int timeout)
5111 {
5112         u32 cntdn, count;
5113         u32 int_status;
5114         u32 doorbell;
5115
5116         count = 0;
5117         cntdn = 1000 * timeout;
5118         do {
5119                 int_status = readl(&ioc->chip->HostInterruptStatus);
5120                 if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
5121                         dhsprintk(ioc, pr_info(MPT3SAS_FMT
5122                                 "%s: successful count(%d), timeout(%d)\n",
5123                                 ioc->name, __func__, count, timeout));
5124                         return 0;
5125                 } else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
5126                         doorbell = readl(&ioc->chip->Doorbell);
5127                         if ((doorbell & MPI2_IOC_STATE_MASK) ==
5128                             MPI2_IOC_STATE_FAULT) {
5129                                 mpt3sas_base_fault_info(ioc , doorbell);
5130                                 return -EFAULT;
5131                         }
5132                 } else if (int_status == 0xFFFFFFFF)
5133                         goto out;
5134
5135                 usleep_range(1000, 1500);
5136                 count++;
5137         } while (--cntdn);
5138
5139  out:
5140         pr_err(MPT3SAS_FMT
5141          "%s: failed due to timeout count(%d), int_status(%x)!\n",
5142          ioc->name, __func__, count, int_status);
5143         return -EFAULT;
5144 }
5145
5146 /**
5147  * _base_wait_for_doorbell_not_used - waiting for doorbell to not be in use
5148  * @ioc: per adapter object
5149  * @timeout: timeout in second
5150  *
5151  * Returns 0 for success, non-zero for failure.
5152  *
5153  */
5154 static int
5155 _base_wait_for_doorbell_not_used(struct MPT3SAS_ADAPTER *ioc, int timeout)
5156 {
5157         u32 cntdn, count;
5158         u32 doorbell_reg;
5159
5160         count = 0;
5161         cntdn = 1000 * timeout;
5162         do {
5163                 doorbell_reg = readl(&ioc->chip->Doorbell);
5164                 if (!(doorbell_reg & MPI2_DOORBELL_USED)) {
5165                         dhsprintk(ioc, pr_info(MPT3SAS_FMT
5166                                 "%s: successful count(%d), timeout(%d)\n",
5167                                 ioc->name, __func__, count, timeout));
5168                         return 0;
5169                 }
5170
5171                 usleep_range(1000, 1500);
5172                 count++;
5173         } while (--cntdn);
5174
5175         pr_err(MPT3SAS_FMT
5176                 "%s: failed due to timeout count(%d), doorbell_reg(%x)!\n",
5177                 ioc->name, __func__, count, doorbell_reg);
5178         return -EFAULT;
5179 }
5180
5181 /**
5182  * _base_send_ioc_reset - send doorbell reset
5183  * @ioc: per adapter object
5184  * @reset_type: currently only supports: MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET
5185  * @timeout: timeout in second
5186  *
5187  * Returns 0 for success, non-zero for failure.
5188  */
5189 static int
5190 _base_send_ioc_reset(struct MPT3SAS_ADAPTER *ioc, u8 reset_type, int timeout)
5191 {
5192         u32 ioc_state;
5193         int r = 0;
5194
5195         if (reset_type != MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET) {
5196                 pr_err(MPT3SAS_FMT "%s: unknown reset_type\n",
5197                     ioc->name, __func__);
5198                 return -EFAULT;
5199         }
5200
5201         if (!(ioc->facts.IOCCapabilities &
5202            MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY))
5203                 return -EFAULT;
5204
5205         pr_info(MPT3SAS_FMT "sending message unit reset !!\n", ioc->name);
5206
5207         writel(reset_type << MPI2_DOORBELL_FUNCTION_SHIFT,
5208             &ioc->chip->Doorbell);
5209         if ((_base_wait_for_doorbell_ack(ioc, 15))) {
5210                 r = -EFAULT;
5211                 goto out;
5212         }
5213         ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, timeout);
5214         if (ioc_state) {
5215                 pr_err(MPT3SAS_FMT
5216                         "%s: failed going to ready state (ioc_state=0x%x)\n",
5217                         ioc->name, __func__, ioc_state);
5218                 r = -EFAULT;
5219                 goto out;
5220         }
5221  out:
5222         pr_info(MPT3SAS_FMT "message unit reset: %s\n",
5223             ioc->name, ((r == 0) ? "SUCCESS" : "FAILED"));
5224         return r;
5225 }
5226
5227 /**
5228  * _base_handshake_req_reply_wait - send request thru doorbell interface
5229  * @ioc: per adapter object
5230  * @request_bytes: request length
5231  * @request: pointer having request payload
5232  * @reply_bytes: reply length
5233  * @reply: pointer to reply payload
5234  * @timeout: timeout in second
5235  *
5236  * Returns 0 for success, non-zero for failure.
5237  */
5238 static int
5239 _base_handshake_req_reply_wait(struct MPT3SAS_ADAPTER *ioc, int request_bytes,
5240         u32 *request, int reply_bytes, u16 *reply, int timeout)
5241 {
5242         MPI2DefaultReply_t *default_reply = (MPI2DefaultReply_t *)reply;
5243         int i;
5244         u8 failed;
5245         __le32 *mfp;
5246
5247         /* make sure doorbell is not in use */
5248         if ((readl(&ioc->chip->Doorbell) & MPI2_DOORBELL_USED)) {
5249                 pr_err(MPT3SAS_FMT
5250                         "doorbell is in use (line=%d)\n",
5251                         ioc->name, __LINE__);
5252                 return -EFAULT;
5253         }
5254
5255         /* clear pending doorbell interrupts from previous state changes */
5256         if (readl(&ioc->chip->HostInterruptStatus) &
5257             MPI2_HIS_IOC2SYS_DB_STATUS)
5258                 writel(0, &ioc->chip->HostInterruptStatus);
5259
5260         /* send message to ioc */
5261         writel(((MPI2_FUNCTION_HANDSHAKE<<MPI2_DOORBELL_FUNCTION_SHIFT) |
5262             ((request_bytes/4)<<MPI2_DOORBELL_ADD_DWORDS_SHIFT)),
5263             &ioc->chip->Doorbell);
5264
5265         if ((_base_spin_on_doorbell_int(ioc, 5))) {
5266                 pr_err(MPT3SAS_FMT
5267                         "doorbell handshake int failed (line=%d)\n",
5268                         ioc->name, __LINE__);
5269                 return -EFAULT;
5270         }
5271         writel(0, &ioc->chip->HostInterruptStatus);
5272
5273         if ((_base_wait_for_doorbell_ack(ioc, 5))) {
5274                 pr_err(MPT3SAS_FMT
5275                         "doorbell handshake ack failed (line=%d)\n",
5276                         ioc->name, __LINE__);
5277                 return -EFAULT;
5278         }
5279
5280         /* send message 32-bits at a time */
5281         for (i = 0, failed = 0; i < request_bytes/4 && !failed; i++) {
5282                 writel((u32)(request[i]), &ioc->chip->Doorbell);
5283                 if ((_base_wait_for_doorbell_ack(ioc, 5)))
5284                         failed = 1;
5285         }
5286
5287         if (failed) {
5288                 pr_err(MPT3SAS_FMT
5289                         "doorbell handshake sending request failed (line=%d)\n",
5290                         ioc->name, __LINE__);
5291                 return -EFAULT;
5292         }
5293
5294         /* now wait for the reply */
5295         if ((_base_wait_for_doorbell_int(ioc, timeout))) {
5296                 pr_err(MPT3SAS_FMT
5297                         "doorbell handshake int failed (line=%d)\n",
5298                         ioc->name, __LINE__);
5299                 return -EFAULT;
5300         }
5301
5302         /* read the first two 16-bits, it gives the total length of the reply */
5303         reply[0] = (u16)(readl(&ioc->chip->Doorbell)
5304             & MPI2_DOORBELL_DATA_MASK);
5305         writel(0, &ioc->chip->HostInterruptStatus);
5306         if ((_base_wait_for_doorbell_int(ioc, 5))) {
5307                 pr_err(MPT3SAS_FMT
5308                         "doorbell handshake int failed (line=%d)\n",
5309                         ioc->name, __LINE__);
5310                 return -EFAULT;
5311         }
5312         reply[1] = (u16)(readl(&ioc->chip->Doorbell)
5313             & MPI2_DOORBELL_DATA_MASK);
5314         writel(0, &ioc->chip->HostInterruptStatus);
5315
5316         for (i = 2; i < default_reply->MsgLength * 2; i++)  {
5317                 if ((_base_wait_for_doorbell_int(ioc, 5))) {
5318                         pr_err(MPT3SAS_FMT
5319                                 "doorbell handshake int failed (line=%d)\n",
5320                                 ioc->name, __LINE__);
5321                         return -EFAULT;
5322                 }
5323                 if (i >=  reply_bytes/2) /* overflow case */
5324                         readl(&ioc->chip->Doorbell);
5325                 else
5326                         reply[i] = (u16)(readl(&ioc->chip->Doorbell)
5327                             & MPI2_DOORBELL_DATA_MASK);
5328                 writel(0, &ioc->chip->HostInterruptStatus);
5329         }
5330
5331         _base_wait_for_doorbell_int(ioc, 5);
5332         if (_base_wait_for_doorbell_not_used(ioc, 5) != 0) {
5333                 dhsprintk(ioc, pr_info(MPT3SAS_FMT
5334                         "doorbell is in use (line=%d)\n", ioc->name, __LINE__));
5335         }
5336         writel(0, &ioc->chip->HostInterruptStatus);
5337
5338         if (ioc->logging_level & MPT_DEBUG_INIT) {
5339                 mfp = (__le32 *)reply;
5340                 pr_info("\toffset:data\n");
5341                 for (i = 0; i < reply_bytes/4; i++)
5342                         pr_info("\t[0x%02x]:%08x\n", i*4,
5343                             le32_to_cpu(mfp[i]));
5344         }
5345         return 0;
5346 }
5347
5348 /**
5349  * mpt3sas_base_sas_iounit_control - send sas iounit control to FW
5350  * @ioc: per adapter object
5351  * @mpi_reply: the reply payload from FW
5352  * @mpi_request: the request payload sent to FW
5353  *
5354  * The SAS IO Unit Control Request message allows the host to perform low-level
5355  * operations, such as resets on the PHYs of the IO Unit, also allows the host
5356  * to obtain the IOC assigned device handles for a device if it has other
5357  * identifying information about the device, in addition allows the host to
5358  * remove IOC resources associated with the device.
5359  *
5360  * Returns 0 for success, non-zero for failure.
5361  */
5362 int
5363 mpt3sas_base_sas_iounit_control(struct MPT3SAS_ADAPTER *ioc,
5364         Mpi2SasIoUnitControlReply_t *mpi_reply,
5365         Mpi2SasIoUnitControlRequest_t *mpi_request)
5366 {
5367         u16 smid;
5368         u32 ioc_state;
5369         u8 issue_reset = 0;
5370         int rc;
5371         void *request;
5372         u16 wait_state_count;
5373
5374         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
5375             __func__));
5376
5377         mutex_lock(&ioc->base_cmds.mutex);
5378
5379         if (ioc->base_cmds.status != MPT3_CMD_NOT_USED) {
5380                 pr_err(MPT3SAS_FMT "%s: base_cmd in use\n",
5381                     ioc->name, __func__);
5382                 rc = -EAGAIN;
5383                 goto out;
5384         }
5385
5386         wait_state_count = 0;
5387         ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
5388         while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
5389                 if (wait_state_count++ == 10) {
5390                         pr_err(MPT3SAS_FMT
5391                             "%s: failed due to ioc not operational\n",
5392                             ioc->name, __func__);
5393                         rc = -EFAULT;
5394                         goto out;
5395                 }
5396                 ssleep(1);
5397                 ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
5398                 pr_info(MPT3SAS_FMT
5399                         "%s: waiting for operational state(count=%d)\n",
5400                         ioc->name, __func__, wait_state_count);
5401         }
5402
5403         smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
5404         if (!smid) {
5405                 pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n",
5406                     ioc->name, __func__);
5407                 rc = -EAGAIN;
5408                 goto out;
5409         }
5410
5411         rc = 0;
5412         ioc->base_cmds.status = MPT3_CMD_PENDING;
5413         request = mpt3sas_base_get_msg_frame(ioc, smid);
5414         ioc->base_cmds.smid = smid;
5415         memcpy(request, mpi_request, sizeof(Mpi2SasIoUnitControlRequest_t));
5416         if (mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
5417             mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET)
5418                 ioc->ioc_link_reset_in_progress = 1;
5419         init_completion(&ioc->base_cmds.done);
5420         mpt3sas_base_put_smid_default(ioc, smid);
5421         wait_for_completion_timeout(&ioc->base_cmds.done,
5422             msecs_to_jiffies(10000));
5423         if ((mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
5424             mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET) &&
5425             ioc->ioc_link_reset_in_progress)
5426                 ioc->ioc_link_reset_in_progress = 0;
5427         if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
5428                 issue_reset =
5429                         mpt3sas_base_check_cmd_timeout(ioc,
5430                                 ioc->base_cmds.status, mpi_request,
5431                                 sizeof(Mpi2SasIoUnitControlRequest_t)/4);
5432                 goto issue_host_reset;
5433         }
5434         if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID)
5435                 memcpy(mpi_reply, ioc->base_cmds.reply,
5436                     sizeof(Mpi2SasIoUnitControlReply_t));
5437         else
5438                 memset(mpi_reply, 0, sizeof(Mpi2SasIoUnitControlReply_t));
5439         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5440         goto out;
5441
5442  issue_host_reset:
5443         if (issue_reset)
5444                 mpt3sas_base_hard_reset_handler(ioc, FORCE_BIG_HAMMER);
5445         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5446         rc = -EFAULT;
5447  out:
5448         mutex_unlock(&ioc->base_cmds.mutex);
5449         return rc;
5450 }
5451
5452 /**
5453  * mpt3sas_base_scsi_enclosure_processor - sending request to sep device
5454  * @ioc: per adapter object
5455  * @mpi_reply: the reply payload from FW
5456  * @mpi_request: the request payload sent to FW
5457  *
5458  * The SCSI Enclosure Processor request message causes the IOC to
5459  * communicate with SES devices to control LED status signals.
5460  *
5461  * Returns 0 for success, non-zero for failure.
5462  */
5463 int
5464 mpt3sas_base_scsi_enclosure_processor(struct MPT3SAS_ADAPTER *ioc,
5465         Mpi2SepReply_t *mpi_reply, Mpi2SepRequest_t *mpi_request)
5466 {
5467         u16 smid;
5468         u32 ioc_state;
5469         u8 issue_reset = 0;
5470         int rc;
5471         void *request;
5472         u16 wait_state_count;
5473
5474         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
5475             __func__));
5476
5477         mutex_lock(&ioc->base_cmds.mutex);
5478
5479         if (ioc->base_cmds.status != MPT3_CMD_NOT_USED) {
5480                 pr_err(MPT3SAS_FMT "%s: base_cmd in use\n",
5481                     ioc->name, __func__);
5482                 rc = -EAGAIN;
5483                 goto out;
5484         }
5485
5486         wait_state_count = 0;
5487         ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
5488         while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
5489                 if (wait_state_count++ == 10) {
5490                         pr_err(MPT3SAS_FMT
5491                             "%s: failed due to ioc not operational\n",
5492                             ioc->name, __func__);
5493                         rc = -EFAULT;
5494                         goto out;
5495                 }
5496                 ssleep(1);
5497                 ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
5498                 pr_info(MPT3SAS_FMT
5499                         "%s: waiting for operational state(count=%d)\n",
5500                         ioc->name,
5501                     __func__, wait_state_count);
5502         }
5503
5504         smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
5505         if (!smid) {
5506                 pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n",
5507                     ioc->name, __func__);
5508                 rc = -EAGAIN;
5509                 goto out;
5510         }
5511
5512         rc = 0;
5513         ioc->base_cmds.status = MPT3_CMD_PENDING;
5514         request = mpt3sas_base_get_msg_frame(ioc, smid);
5515         ioc->base_cmds.smid = smid;
5516         memcpy(request, mpi_request, sizeof(Mpi2SepReply_t));
5517         init_completion(&ioc->base_cmds.done);
5518         mpt3sas_base_put_smid_default(ioc, smid);
5519         wait_for_completion_timeout(&ioc->base_cmds.done,
5520             msecs_to_jiffies(10000));
5521         if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
5522                 issue_reset =
5523                         mpt3sas_base_check_cmd_timeout(ioc,
5524                                 ioc->base_cmds.status, mpi_request,
5525                                 sizeof(Mpi2SepRequest_t)/4);
5526                 goto issue_host_reset;
5527         }
5528         if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID)
5529                 memcpy(mpi_reply, ioc->base_cmds.reply,
5530                     sizeof(Mpi2SepReply_t));
5531         else
5532                 memset(mpi_reply, 0, sizeof(Mpi2SepReply_t));
5533         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5534         goto out;
5535
5536  issue_host_reset:
5537         if (issue_reset)
5538                 mpt3sas_base_hard_reset_handler(ioc, FORCE_BIG_HAMMER);
5539         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5540         rc = -EFAULT;
5541  out:
5542         mutex_unlock(&ioc->base_cmds.mutex);
5543         return rc;
5544 }
5545
5546 /**
5547  * _base_get_port_facts - obtain port facts reply and save in ioc
5548  * @ioc: per adapter object
5549  *
5550  * Returns 0 for success, non-zero for failure.
5551  */
5552 static int
5553 _base_get_port_facts(struct MPT3SAS_ADAPTER *ioc, int port)
5554 {
5555         Mpi2PortFactsRequest_t mpi_request;
5556         Mpi2PortFactsReply_t mpi_reply;
5557         struct mpt3sas_port_facts *pfacts;
5558         int mpi_reply_sz, mpi_request_sz, r;
5559
5560         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
5561             __func__));
5562
5563         mpi_reply_sz = sizeof(Mpi2PortFactsReply_t);
5564         mpi_request_sz = sizeof(Mpi2PortFactsRequest_t);
5565         memset(&mpi_request, 0, mpi_request_sz);
5566         mpi_request.Function = MPI2_FUNCTION_PORT_FACTS;
5567         mpi_request.PortNumber = port;
5568         r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
5569             (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5);
5570
5571         if (r != 0) {
5572                 pr_err(MPT3SAS_FMT "%s: handshake failed (r=%d)\n",
5573                     ioc->name, __func__, r);
5574                 return r;
5575         }
5576
5577         pfacts = &ioc->pfacts[port];
5578         memset(pfacts, 0, sizeof(struct mpt3sas_port_facts));
5579         pfacts->PortNumber = mpi_reply.PortNumber;
5580         pfacts->VP_ID = mpi_reply.VP_ID;
5581         pfacts->VF_ID = mpi_reply.VF_ID;
5582         pfacts->MaxPostedCmdBuffers =
5583             le16_to_cpu(mpi_reply.MaxPostedCmdBuffers);
5584
5585         return 0;
5586 }
5587
5588 /**
5589  * _base_wait_for_iocstate - Wait until the card is in READY or OPERATIONAL
5590  * @ioc: per adapter object
5591  * @timeout:
5592  *
5593  * Returns 0 for success, non-zero for failure.
5594  */
5595 static int
5596 _base_wait_for_iocstate(struct MPT3SAS_ADAPTER *ioc, int timeout)
5597 {
5598         u32 ioc_state;
5599         int rc;
5600
5601         dinitprintk(ioc, printk(MPT3SAS_FMT "%s\n", ioc->name,
5602             __func__));
5603
5604         if (ioc->pci_error_recovery) {
5605                 dfailprintk(ioc, printk(MPT3SAS_FMT
5606                     "%s: host in pci error recovery\n", ioc->name, __func__));
5607                 return -EFAULT;
5608         }
5609
5610         ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
5611         dhsprintk(ioc, printk(MPT3SAS_FMT "%s: ioc_state(0x%08x)\n",
5612             ioc->name, __func__, ioc_state));
5613
5614         if (((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_READY) ||
5615             (ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_OPERATIONAL)
5616                 return 0;
5617
5618         if (ioc_state & MPI2_DOORBELL_USED) {
5619                 dhsprintk(ioc, printk(MPT3SAS_FMT
5620                     "unexpected doorbell active!\n", ioc->name));
5621                 goto issue_diag_reset;
5622         }
5623
5624         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
5625                 mpt3sas_base_fault_info(ioc, ioc_state &
5626                     MPI2_DOORBELL_DATA_MASK);
5627                 goto issue_diag_reset;
5628         }
5629
5630         ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, timeout);
5631         if (ioc_state) {
5632                 dfailprintk(ioc, printk(MPT3SAS_FMT
5633                     "%s: failed going to ready state (ioc_state=0x%x)\n",
5634                     ioc->name, __func__, ioc_state));
5635                 return -EFAULT;
5636         }
5637
5638  issue_diag_reset:
5639         rc = _base_diag_reset(ioc);
5640         return rc;
5641 }
5642
5643 /**
5644  * _base_get_ioc_facts - obtain ioc facts reply and save in ioc
5645  * @ioc: per adapter object
5646  *
5647  * Returns 0 for success, non-zero for failure.
5648  */
5649 static int
5650 _base_get_ioc_facts(struct MPT3SAS_ADAPTER *ioc)
5651 {
5652         Mpi2IOCFactsRequest_t mpi_request;
5653         Mpi2IOCFactsReply_t mpi_reply;
5654         struct mpt3sas_facts *facts;
5655         int mpi_reply_sz, mpi_request_sz, r;
5656
5657         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
5658             __func__));
5659
5660         r = _base_wait_for_iocstate(ioc, 10);
5661         if (r) {
5662                 dfailprintk(ioc, printk(MPT3SAS_FMT
5663                     "%s: failed getting to correct state\n",
5664                     ioc->name, __func__));
5665                 return r;
5666         }
5667         mpi_reply_sz = sizeof(Mpi2IOCFactsReply_t);
5668         mpi_request_sz = sizeof(Mpi2IOCFactsRequest_t);
5669         memset(&mpi_request, 0, mpi_request_sz);
5670         mpi_request.Function = MPI2_FUNCTION_IOC_FACTS;
5671         r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
5672             (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5);
5673
5674         if (r != 0) {
5675                 pr_err(MPT3SAS_FMT "%s: handshake failed (r=%d)\n",
5676                     ioc->name, __func__, r);
5677                 return r;
5678         }
5679
5680         facts = &ioc->facts;
5681         memset(facts, 0, sizeof(struct mpt3sas_facts));
5682         facts->MsgVersion = le16_to_cpu(mpi_reply.MsgVersion);
5683         facts->HeaderVersion = le16_to_cpu(mpi_reply.HeaderVersion);
5684         facts->VP_ID = mpi_reply.VP_ID;
5685         facts->VF_ID = mpi_reply.VF_ID;
5686         facts->IOCExceptions = le16_to_cpu(mpi_reply.IOCExceptions);
5687         facts->MaxChainDepth = mpi_reply.MaxChainDepth;
5688         facts->WhoInit = mpi_reply.WhoInit;
5689         facts->NumberOfPorts = mpi_reply.NumberOfPorts;
5690         facts->MaxMSIxVectors = mpi_reply.MaxMSIxVectors;
5691         if (ioc->msix_enable && (facts->MaxMSIxVectors <=
5692             MAX_COMBINED_MSIX_VECTORS(ioc->is_gen35_ioc)))
5693                 ioc->combined_reply_queue = 0;
5694         facts->RequestCredit = le16_to_cpu(mpi_reply.RequestCredit);
5695         facts->MaxReplyDescriptorPostQueueDepth =
5696             le16_to_cpu(mpi_reply.MaxReplyDescriptorPostQueueDepth);
5697         facts->ProductID = le16_to_cpu(mpi_reply.ProductID);
5698         facts->IOCCapabilities = le32_to_cpu(mpi_reply.IOCCapabilities);
5699         if ((facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID))
5700                 ioc->ir_firmware = 1;
5701         if ((facts->IOCCapabilities &
5702               MPI2_IOCFACTS_CAPABILITY_RDPQ_ARRAY_CAPABLE) && (!reset_devices))
5703                 ioc->rdpq_array_capable = 1;
5704         facts->FWVersion.Word = le32_to_cpu(mpi_reply.FWVersion.Word);
5705         facts->IOCRequestFrameSize =
5706             le16_to_cpu(mpi_reply.IOCRequestFrameSize);
5707         if (ioc->hba_mpi_version_belonged != MPI2_VERSION) {
5708                 facts->IOCMaxChainSegmentSize =
5709                         le16_to_cpu(mpi_reply.IOCMaxChainSegmentSize);
5710         }
5711         facts->MaxInitiators = le16_to_cpu(mpi_reply.MaxInitiators);
5712         facts->MaxTargets = le16_to_cpu(mpi_reply.MaxTargets);
5713         ioc->shost->max_id = -1;
5714         facts->MaxSasExpanders = le16_to_cpu(mpi_reply.MaxSasExpanders);
5715         facts->MaxEnclosures = le16_to_cpu(mpi_reply.MaxEnclosures);
5716         facts->ProtocolFlags = le16_to_cpu(mpi_reply.ProtocolFlags);
5717         facts->HighPriorityCredit =
5718             le16_to_cpu(mpi_reply.HighPriorityCredit);
5719         facts->ReplyFrameSize = mpi_reply.ReplyFrameSize;
5720         facts->MaxDevHandle = le16_to_cpu(mpi_reply.MaxDevHandle);
5721         facts->CurrentHostPageSize = mpi_reply.CurrentHostPageSize;
5722
5723         /*
5724          * Get the Page Size from IOC Facts. If it's 0, default to 4k.
5725          */
5726         ioc->page_size = 1 << facts->CurrentHostPageSize;
5727         if (ioc->page_size == 1) {
5728                 pr_info(MPT3SAS_FMT "CurrentHostPageSize is 0: Setting "
5729                         "default host page size to 4k\n", ioc->name);
5730                 ioc->page_size = 1 << MPT3SAS_HOST_PAGE_SIZE_4K;
5731         }
5732         dinitprintk(ioc, pr_info(MPT3SAS_FMT "CurrentHostPageSize(%d)\n",
5733                 ioc->name, facts->CurrentHostPageSize));
5734
5735         dinitprintk(ioc, pr_info(MPT3SAS_FMT
5736                 "hba queue depth(%d), max chains per io(%d)\n",
5737                 ioc->name, facts->RequestCredit,
5738             facts->MaxChainDepth));
5739         dinitprintk(ioc, pr_info(MPT3SAS_FMT
5740                 "request frame size(%d), reply frame size(%d)\n", ioc->name,
5741             facts->IOCRequestFrameSize * 4, facts->ReplyFrameSize * 4));
5742         return 0;
5743 }
5744
5745 /**
5746  * _base_send_ioc_init - send ioc_init to firmware
5747  * @ioc: per adapter object
5748  *
5749  * Returns 0 for success, non-zero for failure.
5750  */
5751 static int
5752 _base_send_ioc_init(struct MPT3SAS_ADAPTER *ioc)
5753 {
5754         Mpi2IOCInitRequest_t mpi_request;
5755         Mpi2IOCInitReply_t mpi_reply;
5756         int i, r = 0;
5757         ktime_t current_time;
5758         u16 ioc_status;
5759         u32 reply_post_free_array_sz = 0;
5760
5761         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
5762             __func__));
5763
5764         memset(&mpi_request, 0, sizeof(Mpi2IOCInitRequest_t));
5765         mpi_request.Function = MPI2_FUNCTION_IOC_INIT;
5766         mpi_request.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
5767         mpi_request.VF_ID = 0; /* TODO */
5768         mpi_request.VP_ID = 0;
5769         mpi_request.MsgVersion = cpu_to_le16(ioc->hba_mpi_version_belonged);
5770         mpi_request.HeaderVersion = cpu_to_le16(MPI2_HEADER_VERSION);
5771         mpi_request.HostPageSize = MPT3SAS_HOST_PAGE_SIZE_4K;
5772
5773         if (_base_is_controller_msix_enabled(ioc))
5774                 mpi_request.HostMSIxVectors = ioc->reply_queue_count;
5775         mpi_request.SystemRequestFrameSize = cpu_to_le16(ioc->request_sz/4);
5776         mpi_request.ReplyDescriptorPostQueueDepth =
5777             cpu_to_le16(ioc->reply_post_queue_depth);
5778         mpi_request.ReplyFreeQueueDepth =
5779             cpu_to_le16(ioc->reply_free_queue_depth);
5780
5781         mpi_request.SenseBufferAddressHigh =
5782             cpu_to_le32((u64)ioc->sense_dma >> 32);
5783         mpi_request.SystemReplyAddressHigh =
5784             cpu_to_le32((u64)ioc->reply_dma >> 32);
5785         mpi_request.SystemRequestFrameBaseAddress =
5786             cpu_to_le64((u64)ioc->request_dma);
5787         mpi_request.ReplyFreeQueueAddress =
5788             cpu_to_le64((u64)ioc->reply_free_dma);
5789
5790         if (ioc->rdpq_array_enable) {
5791                 reply_post_free_array_sz = ioc->reply_queue_count *
5792                     sizeof(Mpi2IOCInitRDPQArrayEntry);
5793                 memset(ioc->reply_post_free_array, 0, reply_post_free_array_sz);
5794                 for (i = 0; i < ioc->reply_queue_count; i++)
5795                         ioc->reply_post_free_array[i].RDPQBaseAddress =
5796                             cpu_to_le64(
5797                                 (u64)ioc->reply_post[i].reply_post_free_dma);
5798                 mpi_request.MsgFlags = MPI2_IOCINIT_MSGFLAG_RDPQ_ARRAY_MODE;
5799                 mpi_request.ReplyDescriptorPostQueueAddress =
5800                     cpu_to_le64((u64)ioc->reply_post_free_array_dma);
5801         } else {
5802                 mpi_request.ReplyDescriptorPostQueueAddress =
5803                     cpu_to_le64((u64)ioc->reply_post[0].reply_post_free_dma);
5804         }
5805
5806         /* This time stamp specifies number of milliseconds
5807          * since epoch ~ midnight January 1, 1970.
5808          */
5809         current_time = ktime_get_real();
5810         mpi_request.TimeStamp = cpu_to_le64(ktime_to_ms(current_time));
5811
5812         if (ioc->logging_level & MPT_DEBUG_INIT) {
5813                 __le32 *mfp;
5814                 int i;
5815
5816                 mfp = (__le32 *)&mpi_request;
5817                 pr_info("\toffset:data\n");
5818                 for (i = 0; i < sizeof(Mpi2IOCInitRequest_t)/4; i++)
5819                         pr_info("\t[0x%02x]:%08x\n", i*4,
5820                             le32_to_cpu(mfp[i]));
5821         }
5822
5823         r = _base_handshake_req_reply_wait(ioc,
5824             sizeof(Mpi2IOCInitRequest_t), (u32 *)&mpi_request,
5825             sizeof(Mpi2IOCInitReply_t), (u16 *)&mpi_reply, 10);
5826
5827         if (r != 0) {
5828                 pr_err(MPT3SAS_FMT "%s: handshake failed (r=%d)\n",
5829                     ioc->name, __func__, r);
5830                 return r;
5831         }
5832
5833         ioc_status = le16_to_cpu(mpi_reply.IOCStatus) & MPI2_IOCSTATUS_MASK;
5834         if (ioc_status != MPI2_IOCSTATUS_SUCCESS ||
5835             mpi_reply.IOCLogInfo) {
5836                 pr_err(MPT3SAS_FMT "%s: failed\n", ioc->name, __func__);
5837                 r = -EIO;
5838         }
5839
5840         return r;
5841 }
5842
5843 /**
5844  * mpt3sas_port_enable_done - command completion routine for port enable
5845  * @ioc: per adapter object
5846  * @smid: system request message index
5847  * @msix_index: MSIX table index supplied by the OS
5848  * @reply: reply message frame(lower 32bit addr)
5849  *
5850  * Return 1 meaning mf should be freed from _base_interrupt
5851  *        0 means the mf is freed from this function.
5852  */
5853 u8
5854 mpt3sas_port_enable_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
5855         u32 reply)
5856 {
5857         MPI2DefaultReply_t *mpi_reply;
5858         u16 ioc_status;
5859
5860         if (ioc->port_enable_cmds.status == MPT3_CMD_NOT_USED)
5861                 return 1;
5862
5863         mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
5864         if (!mpi_reply)
5865                 return 1;
5866
5867         if (mpi_reply->Function != MPI2_FUNCTION_PORT_ENABLE)
5868                 return 1;
5869
5870         ioc->port_enable_cmds.status &= ~MPT3_CMD_PENDING;
5871         ioc->port_enable_cmds.status |= MPT3_CMD_COMPLETE;
5872         ioc->port_enable_cmds.status |= MPT3_CMD_REPLY_VALID;
5873         memcpy(ioc->port_enable_cmds.reply, mpi_reply, mpi_reply->MsgLength*4);
5874         ioc_status = le16_to_cpu(mpi_reply->IOCStatus) & MPI2_IOCSTATUS_MASK;
5875         if (ioc_status != MPI2_IOCSTATUS_SUCCESS)
5876                 ioc->port_enable_failed = 1;
5877
5878         if (ioc->is_driver_loading) {
5879                 if (ioc_status == MPI2_IOCSTATUS_SUCCESS) {
5880                         mpt3sas_port_enable_complete(ioc);
5881                         return 1;
5882                 } else {
5883                         ioc->start_scan_failed = ioc_status;
5884                         ioc->start_scan = 0;
5885                         return 1;
5886                 }
5887         }
5888         complete(&ioc->port_enable_cmds.done);
5889         return 1;
5890 }
5891
5892 /**
5893  * _base_send_port_enable - send port_enable(discovery stuff) to firmware
5894  * @ioc: per adapter object
5895  *
5896  * Returns 0 for success, non-zero for failure.
5897  */
5898 static int
5899 _base_send_port_enable(struct MPT3SAS_ADAPTER *ioc)
5900 {
5901         Mpi2PortEnableRequest_t *mpi_request;
5902         Mpi2PortEnableReply_t *mpi_reply;
5903         int r = 0;
5904         u16 smid;
5905         u16 ioc_status;
5906
5907         pr_info(MPT3SAS_FMT "sending port enable !!\n", ioc->name);
5908
5909         if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
5910                 pr_err(MPT3SAS_FMT "%s: internal command already in use\n",
5911                     ioc->name, __func__);
5912                 return -EAGAIN;
5913         }
5914
5915         smid = mpt3sas_base_get_smid(ioc, ioc->port_enable_cb_idx);
5916         if (!smid) {
5917                 pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n",
5918                     ioc->name, __func__);
5919                 return -EAGAIN;
5920         }
5921
5922         ioc->port_enable_cmds.status = MPT3_CMD_PENDING;
5923         mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
5924         ioc->port_enable_cmds.smid = smid;
5925         memset(mpi_request, 0, sizeof(Mpi2PortEnableRequest_t));
5926         mpi_request->Function = MPI2_FUNCTION_PORT_ENABLE;
5927
5928         init_completion(&ioc->port_enable_cmds.done);
5929         mpt3sas_base_put_smid_default(ioc, smid);
5930         wait_for_completion_timeout(&ioc->port_enable_cmds.done, 300*HZ);
5931         if (!(ioc->port_enable_cmds.status & MPT3_CMD_COMPLETE)) {
5932                 pr_err(MPT3SAS_FMT "%s: timeout\n",
5933                     ioc->name, __func__);
5934                 _debug_dump_mf(mpi_request,
5935                     sizeof(Mpi2PortEnableRequest_t)/4);
5936                 if (ioc->port_enable_cmds.status & MPT3_CMD_RESET)
5937                         r = -EFAULT;
5938                 else
5939                         r = -ETIME;
5940                 goto out;
5941         }
5942
5943         mpi_reply = ioc->port_enable_cmds.reply;
5944         ioc_status = le16_to_cpu(mpi_reply->IOCStatus) & MPI2_IOCSTATUS_MASK;
5945         if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
5946                 pr_err(MPT3SAS_FMT "%s: failed with (ioc_status=0x%08x)\n",
5947                     ioc->name, __func__, ioc_status);
5948                 r = -EFAULT;
5949                 goto out;
5950         }
5951
5952  out:
5953         ioc->port_enable_cmds.status = MPT3_CMD_NOT_USED;
5954         pr_info(MPT3SAS_FMT "port enable: %s\n", ioc->name, ((r == 0) ?
5955             "SUCCESS" : "FAILED"));
5956         return r;
5957 }
5958
5959 /**
5960  * mpt3sas_port_enable - initiate firmware discovery (don't wait for reply)
5961  * @ioc: per adapter object
5962  *
5963  * Returns 0 for success, non-zero for failure.
5964  */
5965 int
5966 mpt3sas_port_enable(struct MPT3SAS_ADAPTER *ioc)
5967 {
5968         Mpi2PortEnableRequest_t *mpi_request;
5969         u16 smid;
5970
5971         pr_info(MPT3SAS_FMT "sending port enable !!\n", ioc->name);
5972
5973         if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
5974                 pr_err(MPT3SAS_FMT "%s: internal command already in use\n",
5975                     ioc->name, __func__);
5976                 return -EAGAIN;
5977         }
5978
5979         smid = mpt3sas_base_get_smid(ioc, ioc->port_enable_cb_idx);
5980         if (!smid) {
5981                 pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n",
5982                     ioc->name, __func__);
5983                 return -EAGAIN;
5984         }
5985
5986         ioc->port_enable_cmds.status = MPT3_CMD_PENDING;
5987         mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
5988         ioc->port_enable_cmds.smid = smid;
5989         memset(mpi_request, 0, sizeof(Mpi2PortEnableRequest_t));
5990         mpi_request->Function = MPI2_FUNCTION_PORT_ENABLE;
5991
5992         mpt3sas_base_put_smid_default(ioc, smid);
5993         return 0;
5994 }
5995
5996 /**
5997  * _base_determine_wait_on_discovery - desposition
5998  * @ioc: per adapter object
5999  *
6000  * Decide whether to wait on discovery to complete. Used to either
6001  * locate boot device, or report volumes ahead of physical devices.
6002  *
6003  * Returns 1 for wait, 0 for don't wait
6004  */
6005 static int
6006 _base_determine_wait_on_discovery(struct MPT3SAS_ADAPTER *ioc)
6007 {
6008         /* We wait for discovery to complete if IR firmware is loaded.
6009          * The sas topology events arrive before PD events, so we need time to
6010          * turn on the bit in ioc->pd_handles to indicate PD
6011          * Also, it maybe required to report Volumes ahead of physical
6012          * devices when MPI2_IOCPAGE8_IRFLAGS_LOW_VOLUME_MAPPING is set.
6013          */
6014         if (ioc->ir_firmware)
6015                 return 1;
6016
6017         /* if no Bios, then we don't need to wait */
6018         if (!ioc->bios_pg3.BiosVersion)
6019                 return 0;
6020
6021         /* Bios is present, then we drop down here.
6022          *
6023          * If there any entries in the Bios Page 2, then we wait
6024          * for discovery to complete.
6025          */
6026
6027         /* Current Boot Device */
6028         if ((ioc->bios_pg2.CurrentBootDeviceForm &
6029             MPI2_BIOSPAGE2_FORM_MASK) ==
6030             MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED &&
6031         /* Request Boot Device */
6032            (ioc->bios_pg2.ReqBootDeviceForm &
6033             MPI2_BIOSPAGE2_FORM_MASK) ==
6034             MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED &&
6035         /* Alternate Request Boot Device */
6036            (ioc->bios_pg2.ReqAltBootDeviceForm &
6037             MPI2_BIOSPAGE2_FORM_MASK) ==
6038             MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED)
6039                 return 0;
6040
6041         return 1;
6042 }
6043
6044 /**
6045  * _base_unmask_events - turn on notification for this event
6046  * @ioc: per adapter object
6047  * @event: firmware event
6048  *
6049  * The mask is stored in ioc->event_masks.
6050  */
6051 static void
6052 _base_unmask_events(struct MPT3SAS_ADAPTER *ioc, u16 event)
6053 {
6054         u32 desired_event;
6055
6056         if (event >= 128)
6057                 return;
6058
6059         desired_event = (1 << (event % 32));
6060
6061         if (event < 32)
6062                 ioc->event_masks[0] &= ~desired_event;
6063         else if (event < 64)
6064                 ioc->event_masks[1] &= ~desired_event;
6065         else if (event < 96)
6066                 ioc->event_masks[2] &= ~desired_event;
6067         else if (event < 128)
6068                 ioc->event_masks[3] &= ~desired_event;
6069 }
6070
6071 /**
6072  * _base_event_notification - send event notification
6073  * @ioc: per adapter object
6074  *
6075  * Returns 0 for success, non-zero for failure.
6076  */
6077 static int
6078 _base_event_notification(struct MPT3SAS_ADAPTER *ioc)
6079 {
6080         Mpi2EventNotificationRequest_t *mpi_request;
6081         u16 smid;
6082         int r = 0;
6083         int i;
6084
6085         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
6086             __func__));
6087
6088         if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
6089                 pr_err(MPT3SAS_FMT "%s: internal command already in use\n",
6090                     ioc->name, __func__);
6091                 return -EAGAIN;
6092         }
6093
6094         smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
6095         if (!smid) {
6096                 pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n",
6097                     ioc->name, __func__);
6098                 return -EAGAIN;
6099         }
6100         ioc->base_cmds.status = MPT3_CMD_PENDING;
6101         mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
6102         ioc->base_cmds.smid = smid;
6103         memset(mpi_request, 0, sizeof(Mpi2EventNotificationRequest_t));
6104         mpi_request->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
6105         mpi_request->VF_ID = 0; /* TODO */
6106         mpi_request->VP_ID = 0;
6107         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
6108                 mpi_request->EventMasks[i] =
6109                     cpu_to_le32(ioc->event_masks[i]);
6110         init_completion(&ioc->base_cmds.done);
6111         mpt3sas_base_put_smid_default(ioc, smid);
6112         wait_for_completion_timeout(&ioc->base_cmds.done, 30*HZ);
6113         if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
6114                 pr_err(MPT3SAS_FMT "%s: timeout\n",
6115                     ioc->name, __func__);
6116                 _debug_dump_mf(mpi_request,
6117                     sizeof(Mpi2EventNotificationRequest_t)/4);
6118                 if (ioc->base_cmds.status & MPT3_CMD_RESET)
6119                         r = -EFAULT;
6120                 else
6121                         r = -ETIME;
6122         } else
6123                 dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s: complete\n",
6124                     ioc->name, __func__));
6125         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
6126         return r;
6127 }
6128
6129 /**
6130  * mpt3sas_base_validate_event_type - validating event types
6131  * @ioc: per adapter object
6132  * @event: firmware event
6133  *
6134  * This will turn on firmware event notification when application
6135  * ask for that event. We don't mask events that are already enabled.
6136  */
6137 void
6138 mpt3sas_base_validate_event_type(struct MPT3SAS_ADAPTER *ioc, u32 *event_type)
6139 {
6140         int i, j;
6141         u32 event_mask, desired_event;
6142         u8 send_update_to_fw;
6143
6144         for (i = 0, send_update_to_fw = 0; i <
6145             MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++) {
6146                 event_mask = ~event_type[i];
6147                 desired_event = 1;
6148                 for (j = 0; j < 32; j++) {
6149                         if (!(event_mask & desired_event) &&
6150                             (ioc->event_masks[i] & desired_event)) {
6151                                 ioc->event_masks[i] &= ~desired_event;
6152                                 send_update_to_fw = 1;
6153                         }
6154                         desired_event = (desired_event << 1);
6155                 }
6156         }
6157
6158         if (!send_update_to_fw)
6159                 return;
6160
6161         mutex_lock(&ioc->base_cmds.mutex);
6162         _base_event_notification(ioc);
6163         mutex_unlock(&ioc->base_cmds.mutex);
6164 }
6165
6166 /**
6167  * _base_diag_reset - the "big hammer" start of day reset
6168  * @ioc: per adapter object
6169  *
6170  * Returns 0 for success, non-zero for failure.
6171  */
6172 static int
6173 _base_diag_reset(struct MPT3SAS_ADAPTER *ioc)
6174 {
6175         u32 host_diagnostic;
6176         u32 ioc_state;
6177         u32 count;
6178         u32 hcb_size;
6179
6180         pr_info(MPT3SAS_FMT "sending diag reset !!\n", ioc->name);
6181
6182         drsprintk(ioc, pr_info(MPT3SAS_FMT "clear interrupts\n",
6183             ioc->name));
6184
6185         count = 0;
6186         do {
6187                 /* Write magic sequence to WriteSequence register
6188                  * Loop until in diagnostic mode
6189                  */
6190                 drsprintk(ioc, pr_info(MPT3SAS_FMT
6191                         "write magic sequence\n", ioc->name));
6192                 writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
6193                 writel(MPI2_WRSEQ_1ST_KEY_VALUE, &ioc->chip->WriteSequence);
6194                 writel(MPI2_WRSEQ_2ND_KEY_VALUE, &ioc->chip->WriteSequence);
6195                 writel(MPI2_WRSEQ_3RD_KEY_VALUE, &ioc->chip->WriteSequence);
6196                 writel(MPI2_WRSEQ_4TH_KEY_VALUE, &ioc->chip->WriteSequence);
6197                 writel(MPI2_WRSEQ_5TH_KEY_VALUE, &ioc->chip->WriteSequence);
6198                 writel(MPI2_WRSEQ_6TH_KEY_VALUE, &ioc->chip->WriteSequence);
6199
6200                 /* wait 100 msec */
6201                 msleep(100);
6202
6203                 if (count++ > 20)
6204                         goto out;
6205
6206                 host_diagnostic = readl(&ioc->chip->HostDiagnostic);
6207                 drsprintk(ioc, pr_info(MPT3SAS_FMT
6208                         "wrote magic sequence: count(%d), host_diagnostic(0x%08x)\n",
6209                     ioc->name, count, host_diagnostic));
6210
6211         } while ((host_diagnostic & MPI2_DIAG_DIAG_WRITE_ENABLE) == 0);
6212
6213         hcb_size = readl(&ioc->chip->HCBSize);
6214
6215         drsprintk(ioc, pr_info(MPT3SAS_FMT "diag reset: issued\n",
6216             ioc->name));
6217         writel(host_diagnostic | MPI2_DIAG_RESET_ADAPTER,
6218              &ioc->chip->HostDiagnostic);
6219
6220         /*This delay allows the chip PCIe hardware time to finish reset tasks*/
6221         msleep(MPI2_HARD_RESET_PCIE_FIRST_READ_DELAY_MICRO_SEC/1000);
6222
6223         /* Approximately 300 second max wait */
6224         for (count = 0; count < (300000000 /
6225                 MPI2_HARD_RESET_PCIE_SECOND_READ_DELAY_MICRO_SEC); count++) {
6226
6227                 host_diagnostic = readl(&ioc->chip->HostDiagnostic);
6228
6229                 if (host_diagnostic == 0xFFFFFFFF)
6230                         goto out;
6231                 if (!(host_diagnostic & MPI2_DIAG_RESET_ADAPTER))
6232                         break;
6233
6234                 msleep(MPI2_HARD_RESET_PCIE_SECOND_READ_DELAY_MICRO_SEC / 1000);
6235         }
6236
6237         if (host_diagnostic & MPI2_DIAG_HCB_MODE) {
6238
6239                 drsprintk(ioc, pr_info(MPT3SAS_FMT
6240                 "restart the adapter assuming the HCB Address points to good F/W\n",
6241                     ioc->name));
6242                 host_diagnostic &= ~MPI2_DIAG_BOOT_DEVICE_SELECT_MASK;
6243                 host_diagnostic |= MPI2_DIAG_BOOT_DEVICE_SELECT_HCDW;
6244                 writel(host_diagnostic, &ioc->chip->HostDiagnostic);
6245
6246                 drsprintk(ioc, pr_info(MPT3SAS_FMT
6247                     "re-enable the HCDW\n", ioc->name));
6248                 writel(hcb_size | MPI2_HCB_SIZE_HCB_ENABLE,
6249                     &ioc->chip->HCBSize);
6250         }
6251
6252         drsprintk(ioc, pr_info(MPT3SAS_FMT "restart the adapter\n",
6253             ioc->name));
6254         writel(host_diagnostic & ~MPI2_DIAG_HOLD_IOC_RESET,
6255             &ioc->chip->HostDiagnostic);
6256
6257         drsprintk(ioc, pr_info(MPT3SAS_FMT
6258                 "disable writes to the diagnostic register\n", ioc->name));
6259         writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
6260
6261         drsprintk(ioc, pr_info(MPT3SAS_FMT
6262                 "Wait for FW to go to the READY state\n", ioc->name));
6263         ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, 20);
6264         if (ioc_state) {
6265                 pr_err(MPT3SAS_FMT
6266                         "%s: failed going to ready state (ioc_state=0x%x)\n",
6267                         ioc->name, __func__, ioc_state);
6268                 goto out;
6269         }
6270
6271         pr_info(MPT3SAS_FMT "diag reset: SUCCESS\n", ioc->name);
6272         return 0;
6273
6274  out:
6275         pr_err(MPT3SAS_FMT "diag reset: FAILED\n", ioc->name);
6276         return -EFAULT;
6277 }
6278
6279 /**
6280  * _base_make_ioc_ready - put controller in READY state
6281  * @ioc: per adapter object
6282  * @type: FORCE_BIG_HAMMER or SOFT_RESET
6283  *
6284  * Returns 0 for success, non-zero for failure.
6285  */
6286 static int
6287 _base_make_ioc_ready(struct MPT3SAS_ADAPTER *ioc, enum reset_type type)
6288 {
6289         u32 ioc_state;
6290         int rc;
6291         int count;
6292
6293         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
6294             __func__));
6295
6296         if (ioc->pci_error_recovery)
6297                 return 0;
6298
6299         ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
6300         dhsprintk(ioc, pr_info(MPT3SAS_FMT "%s: ioc_state(0x%08x)\n",
6301             ioc->name, __func__, ioc_state));
6302
6303         /* if in RESET state, it should move to READY state shortly */
6304         count = 0;
6305         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_RESET) {
6306                 while ((ioc_state & MPI2_IOC_STATE_MASK) !=
6307                     MPI2_IOC_STATE_READY) {
6308                         if (count++ == 10) {
6309                                 pr_err(MPT3SAS_FMT
6310                                         "%s: failed going to ready state (ioc_state=0x%x)\n",
6311                                     ioc->name, __func__, ioc_state);
6312                                 return -EFAULT;
6313                         }
6314                         ssleep(1);
6315                         ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
6316                 }
6317         }
6318
6319         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_READY)
6320                 return 0;
6321
6322         if (ioc_state & MPI2_DOORBELL_USED) {
6323                 dhsprintk(ioc, pr_info(MPT3SAS_FMT
6324                         "unexpected doorbell active!\n",
6325                         ioc->name));
6326                 goto issue_diag_reset;
6327         }
6328
6329         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
6330                 mpt3sas_base_fault_info(ioc, ioc_state &
6331                     MPI2_DOORBELL_DATA_MASK);
6332                 goto issue_diag_reset;
6333         }
6334
6335         if (type == FORCE_BIG_HAMMER)
6336                 goto issue_diag_reset;
6337
6338         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_OPERATIONAL)
6339                 if (!(_base_send_ioc_reset(ioc,
6340                     MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET, 15))) {
6341                         return 0;
6342         }
6343
6344  issue_diag_reset:
6345         rc = _base_diag_reset(ioc);
6346         return rc;
6347 }
6348
6349 /**
6350  * _base_make_ioc_operational - put controller in OPERATIONAL state
6351  * @ioc: per adapter object
6352  *
6353  * Returns 0 for success, non-zero for failure.
6354  */
6355 static int
6356 _base_make_ioc_operational(struct MPT3SAS_ADAPTER *ioc)
6357 {
6358         int r, i, index;
6359         unsigned long   flags;
6360         u32 reply_address;
6361         u16 smid;
6362         struct _tr_list *delayed_tr, *delayed_tr_next;
6363         struct _sc_list *delayed_sc, *delayed_sc_next;
6364         struct _event_ack_list *delayed_event_ack, *delayed_event_ack_next;
6365         u8 hide_flag;
6366         struct adapter_reply_queue *reply_q;
6367         Mpi2ReplyDescriptorsUnion_t *reply_post_free_contig;
6368
6369         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
6370             __func__));
6371
6372         /* clean the delayed target reset list */
6373         list_for_each_entry_safe(delayed_tr, delayed_tr_next,
6374             &ioc->delayed_tr_list, list) {
6375                 list_del(&delayed_tr->list);
6376                 kfree(delayed_tr);
6377         }
6378
6379
6380         list_for_each_entry_safe(delayed_tr, delayed_tr_next,
6381             &ioc->delayed_tr_volume_list, list) {
6382                 list_del(&delayed_tr->list);
6383                 kfree(delayed_tr);
6384         }
6385
6386         list_for_each_entry_safe(delayed_sc, delayed_sc_next,
6387             &ioc->delayed_sc_list, list) {
6388                 list_del(&delayed_sc->list);
6389                 kfree(delayed_sc);
6390         }
6391
6392         list_for_each_entry_safe(delayed_event_ack, delayed_event_ack_next,
6393             &ioc->delayed_event_ack_list, list) {
6394                 list_del(&delayed_event_ack->list);
6395                 kfree(delayed_event_ack);
6396         }
6397
6398         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
6399
6400         /* hi-priority queue */
6401         INIT_LIST_HEAD(&ioc->hpr_free_list);
6402         smid = ioc->hi_priority_smid;
6403         for (i = 0; i < ioc->hi_priority_depth; i++, smid++) {
6404                 ioc->hpr_lookup[i].cb_idx = 0xFF;
6405                 ioc->hpr_lookup[i].smid = smid;
6406                 list_add_tail(&ioc->hpr_lookup[i].tracker_list,
6407                     &ioc->hpr_free_list);
6408         }
6409
6410         /* internal queue */
6411         INIT_LIST_HEAD(&ioc->internal_free_list);
6412         smid = ioc->internal_smid;
6413         for (i = 0; i < ioc->internal_depth; i++, smid++) {
6414                 ioc->internal_lookup[i].cb_idx = 0xFF;
6415                 ioc->internal_lookup[i].smid = smid;
6416                 list_add_tail(&ioc->internal_lookup[i].tracker_list,
6417                     &ioc->internal_free_list);
6418         }
6419
6420         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
6421
6422         /* initialize Reply Free Queue */
6423         for (i = 0, reply_address = (u32)ioc->reply_dma ;
6424             i < ioc->reply_free_queue_depth ; i++, reply_address +=
6425             ioc->reply_sz) {
6426                 ioc->reply_free[i] = cpu_to_le32(reply_address);
6427                 if (ioc->is_mcpu_endpoint)
6428                         _base_clone_reply_to_sys_mem(ioc,
6429                                         reply_address, i);
6430         }
6431
6432         /* initialize reply queues */
6433         if (ioc->is_driver_loading)
6434                 _base_assign_reply_queues(ioc);
6435
6436         /* initialize Reply Post Free Queue */
6437         index = 0;
6438         reply_post_free_contig = ioc->reply_post[0].reply_post_free;
6439         list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
6440                 /*
6441                  * If RDPQ is enabled, switch to the next allocation.
6442                  * Otherwise advance within the contiguous region.
6443                  */
6444                 if (ioc->rdpq_array_enable) {
6445                         reply_q->reply_post_free =
6446                                 ioc->reply_post[index++].reply_post_free;
6447                 } else {
6448                         reply_q->reply_post_free = reply_post_free_contig;
6449                         reply_post_free_contig += ioc->reply_post_queue_depth;
6450                 }
6451
6452                 reply_q->reply_post_host_index = 0;
6453                 for (i = 0; i < ioc->reply_post_queue_depth; i++)
6454                         reply_q->reply_post_free[i].Words =
6455                             cpu_to_le64(ULLONG_MAX);
6456                 if (!_base_is_controller_msix_enabled(ioc))
6457                         goto skip_init_reply_post_free_queue;
6458         }
6459  skip_init_reply_post_free_queue:
6460
6461         r = _base_send_ioc_init(ioc);
6462         if (r)
6463                 return r;
6464
6465         /* initialize reply free host index */
6466         ioc->reply_free_host_index = ioc->reply_free_queue_depth - 1;
6467         writel(ioc->reply_free_host_index, &ioc->chip->ReplyFreeHostIndex);
6468
6469         /* initialize reply post host index */
6470         list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
6471                 if (ioc->combined_reply_queue)
6472                         writel((reply_q->msix_index & 7)<<
6473                            MPI2_RPHI_MSIX_INDEX_SHIFT,
6474                            ioc->replyPostRegisterIndex[reply_q->msix_index/8]);
6475                 else
6476                         writel(reply_q->msix_index <<
6477                                 MPI2_RPHI_MSIX_INDEX_SHIFT,
6478                                 &ioc->chip->ReplyPostHostIndex);
6479
6480                 if (!_base_is_controller_msix_enabled(ioc))
6481                         goto skip_init_reply_post_host_index;
6482         }
6483
6484  skip_init_reply_post_host_index:
6485
6486         _base_unmask_interrupts(ioc);
6487
6488         if (ioc->hba_mpi_version_belonged != MPI2_VERSION) {
6489                 r = _base_display_fwpkg_version(ioc);
6490                 if (r)
6491                         return r;
6492         }
6493
6494         _base_static_config_pages(ioc);
6495         r = _base_event_notification(ioc);
6496         if (r)
6497                 return r;
6498
6499         if (ioc->is_driver_loading) {
6500
6501                 if (ioc->is_warpdrive && ioc->manu_pg10.OEMIdentifier
6502                     == 0x80) {
6503                         hide_flag = (u8) (
6504                             le32_to_cpu(ioc->manu_pg10.OEMSpecificFlags0) &
6505                             MFG_PAGE10_HIDE_SSDS_MASK);
6506                         if (hide_flag != MFG_PAGE10_HIDE_SSDS_MASK)
6507                                 ioc->mfg_pg10_hide_flag = hide_flag;
6508                 }
6509
6510                 ioc->wait_for_discovery_to_complete =
6511                     _base_determine_wait_on_discovery(ioc);
6512
6513                 return r; /* scan_start and scan_finished support */
6514         }
6515
6516         r = _base_send_port_enable(ioc);
6517         if (r)
6518                 return r;
6519
6520         return r;
6521 }
6522
6523 /**
6524  * mpt3sas_base_free_resources - free resources controller resources
6525  * @ioc: per adapter object
6526  *
6527  * Return nothing.
6528  */
6529 void
6530 mpt3sas_base_free_resources(struct MPT3SAS_ADAPTER *ioc)
6531 {
6532         dexitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
6533             __func__));
6534
6535         /* synchronizing freeing resource with pci_access_mutex lock */
6536         mutex_lock(&ioc->pci_access_mutex);
6537         if (ioc->chip_phys && ioc->chip) {
6538                 _base_mask_interrupts(ioc);
6539                 ioc->shost_recovery = 1;
6540                 _base_make_ioc_ready(ioc, SOFT_RESET);
6541                 ioc->shost_recovery = 0;
6542         }
6543
6544         mpt3sas_base_unmap_resources(ioc);
6545         mutex_unlock(&ioc->pci_access_mutex);
6546         return;
6547 }
6548
6549 /**
6550  * mpt3sas_base_attach - attach controller instance
6551  * @ioc: per adapter object
6552  *
6553  * Returns 0 for success, non-zero for failure.
6554  */
6555 int
6556 mpt3sas_base_attach(struct MPT3SAS_ADAPTER *ioc)
6557 {
6558         int r, i;
6559         int cpu_id, last_cpu_id = 0;
6560
6561         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
6562             __func__));
6563
6564         /* setup cpu_msix_table */
6565         ioc->cpu_count = num_online_cpus();
6566         for_each_online_cpu(cpu_id)
6567                 last_cpu_id = cpu_id;
6568         ioc->cpu_msix_table_sz = last_cpu_id + 1;
6569         ioc->cpu_msix_table = kzalloc(ioc->cpu_msix_table_sz, GFP_KERNEL);
6570         ioc->reply_queue_count = 1;
6571         if (!ioc->cpu_msix_table) {
6572                 dfailprintk(ioc, pr_info(MPT3SAS_FMT
6573                         "allocation for cpu_msix_table failed!!!\n",
6574                         ioc->name));
6575                 r = -ENOMEM;
6576                 goto out_free_resources;
6577         }
6578
6579         if (ioc->is_warpdrive) {
6580                 ioc->reply_post_host_index = kcalloc(ioc->cpu_msix_table_sz,
6581                     sizeof(resource_size_t *), GFP_KERNEL);
6582                 if (!ioc->reply_post_host_index) {
6583                         dfailprintk(ioc, pr_info(MPT3SAS_FMT "allocation "
6584                                 "for reply_post_host_index failed!!!\n",
6585                                 ioc->name));
6586                         r = -ENOMEM;
6587                         goto out_free_resources;
6588                 }
6589         }
6590
6591         ioc->rdpq_array_enable_assigned = 0;
6592         ioc->dma_mask = 0;
6593         r = mpt3sas_base_map_resources(ioc);
6594         if (r)
6595                 goto out_free_resources;
6596
6597         pci_set_drvdata(ioc->pdev, ioc->shost);
6598         r = _base_get_ioc_facts(ioc);
6599         if (r)
6600                 goto out_free_resources;
6601
6602         switch (ioc->hba_mpi_version_belonged) {
6603         case MPI2_VERSION:
6604                 ioc->build_sg_scmd = &_base_build_sg_scmd;
6605                 ioc->build_sg = &_base_build_sg;
6606                 ioc->build_zero_len_sge = &_base_build_zero_len_sge;
6607                 break;
6608         case MPI25_VERSION:
6609         case MPI26_VERSION:
6610                 /*
6611                  * In SAS3.0,
6612                  * SCSI_IO, SMP_PASSTHRU, SATA_PASSTHRU, Target Assist, and
6613                  * Target Status - all require the IEEE formated scatter gather
6614                  * elements.
6615                  */
6616                 ioc->build_sg_scmd = &_base_build_sg_scmd_ieee;
6617                 ioc->build_sg = &_base_build_sg_ieee;
6618                 ioc->build_nvme_prp = &_base_build_nvme_prp;
6619                 ioc->build_zero_len_sge = &_base_build_zero_len_sge_ieee;
6620                 ioc->sge_size_ieee = sizeof(Mpi2IeeeSgeSimple64_t);
6621
6622                 break;
6623         }
6624
6625         if (ioc->is_mcpu_endpoint)
6626                 ioc->put_smid_scsi_io = &_base_put_smid_mpi_ep_scsi_io;
6627         else
6628                 ioc->put_smid_scsi_io = &_base_put_smid_scsi_io;
6629
6630         /*
6631          * These function pointers for other requests that don't
6632          * the require IEEE scatter gather elements.
6633          *
6634          * For example Configuration Pages and SAS IOUNIT Control don't.
6635          */
6636         ioc->build_sg_mpi = &_base_build_sg;
6637         ioc->build_zero_len_sge_mpi = &_base_build_zero_len_sge;
6638
6639         r = _base_make_ioc_ready(ioc, SOFT_RESET);
6640         if (r)
6641                 goto out_free_resources;
6642
6643         ioc->pfacts = kcalloc(ioc->facts.NumberOfPorts,
6644             sizeof(struct mpt3sas_port_facts), GFP_KERNEL);
6645         if (!ioc->pfacts) {
6646                 r = -ENOMEM;
6647                 goto out_free_resources;
6648         }
6649
6650         for (i = 0 ; i < ioc->facts.NumberOfPorts; i++) {
6651                 r = _base_get_port_facts(ioc, i);
6652                 if (r)
6653                         goto out_free_resources;
6654         }
6655
6656         r = _base_allocate_memory_pools(ioc);
6657         if (r)
6658                 goto out_free_resources;
6659
6660         init_waitqueue_head(&ioc->reset_wq);
6661
6662         /* allocate memory pd handle bitmask list */
6663         ioc->pd_handles_sz = (ioc->facts.MaxDevHandle / 8);
6664         if (ioc->facts.MaxDevHandle % 8)
6665                 ioc->pd_handles_sz++;
6666         ioc->pd_handles = kzalloc(ioc->pd_handles_sz,
6667             GFP_KERNEL);
6668         if (!ioc->pd_handles) {
6669                 r = -ENOMEM;
6670                 goto out_free_resources;
6671         }
6672         ioc->blocking_handles = kzalloc(ioc->pd_handles_sz,
6673             GFP_KERNEL);
6674         if (!ioc->blocking_handles) {
6675                 r = -ENOMEM;
6676                 goto out_free_resources;
6677         }
6678
6679         /* allocate memory for pending OS device add list */
6680         ioc->pend_os_device_add_sz = (ioc->facts.MaxDevHandle / 8);
6681         if (ioc->facts.MaxDevHandle % 8)
6682                 ioc->pend_os_device_add_sz++;
6683         ioc->pend_os_device_add = kzalloc(ioc->pend_os_device_add_sz,
6684             GFP_KERNEL);
6685         if (!ioc->pend_os_device_add)
6686                 goto out_free_resources;
6687
6688         ioc->device_remove_in_progress_sz = ioc->pend_os_device_add_sz;
6689         ioc->device_remove_in_progress =
6690                 kzalloc(ioc->device_remove_in_progress_sz, GFP_KERNEL);
6691         if (!ioc->device_remove_in_progress)
6692                 goto out_free_resources;
6693
6694         ioc->fwfault_debug = mpt3sas_fwfault_debug;
6695
6696         /* base internal command bits */
6697         mutex_init(&ioc->base_cmds.mutex);
6698         ioc->base_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6699         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
6700
6701         /* port_enable command bits */
6702         ioc->port_enable_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6703         ioc->port_enable_cmds.status = MPT3_CMD_NOT_USED;
6704
6705         /* transport internal command bits */
6706         ioc->transport_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6707         ioc->transport_cmds.status = MPT3_CMD_NOT_USED;
6708         mutex_init(&ioc->transport_cmds.mutex);
6709
6710         /* scsih internal command bits */
6711         ioc->scsih_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6712         ioc->scsih_cmds.status = MPT3_CMD_NOT_USED;
6713         mutex_init(&ioc->scsih_cmds.mutex);
6714
6715         /* task management internal command bits */
6716         ioc->tm_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6717         ioc->tm_cmds.status = MPT3_CMD_NOT_USED;
6718         mutex_init(&ioc->tm_cmds.mutex);
6719
6720         /* config page internal command bits */
6721         ioc->config_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6722         ioc->config_cmds.status = MPT3_CMD_NOT_USED;
6723         mutex_init(&ioc->config_cmds.mutex);
6724
6725         /* ctl module internal command bits */
6726         ioc->ctl_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6727         ioc->ctl_cmds.sense = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
6728         ioc->ctl_cmds.status = MPT3_CMD_NOT_USED;
6729         mutex_init(&ioc->ctl_cmds.mutex);
6730
6731         if (!ioc->base_cmds.reply || !ioc->port_enable_cmds.reply ||
6732             !ioc->transport_cmds.reply || !ioc->scsih_cmds.reply ||
6733             !ioc->tm_cmds.reply || !ioc->config_cmds.reply ||
6734             !ioc->ctl_cmds.reply || !ioc->ctl_cmds.sense) {
6735                 r = -ENOMEM;
6736                 goto out_free_resources;
6737         }
6738
6739         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
6740                 ioc->event_masks[i] = -1;
6741
6742         /* here we enable the events we care about */
6743         _base_unmask_events(ioc, MPI2_EVENT_SAS_DISCOVERY);
6744         _base_unmask_events(ioc, MPI2_EVENT_SAS_BROADCAST_PRIMITIVE);
6745         _base_unmask_events(ioc, MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST);
6746         _base_unmask_events(ioc, MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE);
6747         _base_unmask_events(ioc, MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE);
6748         _base_unmask_events(ioc, MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST);
6749         _base_unmask_events(ioc, MPI2_EVENT_IR_VOLUME);
6750         _base_unmask_events(ioc, MPI2_EVENT_IR_PHYSICAL_DISK);
6751         _base_unmask_events(ioc, MPI2_EVENT_IR_OPERATION_STATUS);
6752         _base_unmask_events(ioc, MPI2_EVENT_LOG_ENTRY_ADDED);
6753         _base_unmask_events(ioc, MPI2_EVENT_TEMP_THRESHOLD);
6754         _base_unmask_events(ioc, MPI2_EVENT_ACTIVE_CABLE_EXCEPTION);
6755         _base_unmask_events(ioc, MPI2_EVENT_SAS_DEVICE_DISCOVERY_ERROR);
6756         if (ioc->hba_mpi_version_belonged == MPI26_VERSION) {
6757                 if (ioc->is_gen35_ioc) {
6758                         _base_unmask_events(ioc,
6759                                 MPI2_EVENT_PCIE_DEVICE_STATUS_CHANGE);
6760                         _base_unmask_events(ioc, MPI2_EVENT_PCIE_ENUMERATION);
6761                         _base_unmask_events(ioc,
6762                                 MPI2_EVENT_PCIE_TOPOLOGY_CHANGE_LIST);
6763                 }
6764         }
6765         r = _base_make_ioc_operational(ioc);
6766         if (r)
6767                 goto out_free_resources;
6768
6769         ioc->non_operational_loop = 0;
6770         ioc->got_task_abort_from_ioctl = 0;
6771         return 0;
6772
6773  out_free_resources:
6774
6775         ioc->remove_host = 1;
6776
6777         mpt3sas_base_free_resources(ioc);
6778         _base_release_memory_pools(ioc);
6779         pci_set_drvdata(ioc->pdev, NULL);
6780         kfree(ioc->cpu_msix_table);
6781         if (ioc->is_warpdrive)
6782                 kfree(ioc->reply_post_host_index);
6783         kfree(ioc->pd_handles);
6784         kfree(ioc->blocking_handles);
6785         kfree(ioc->device_remove_in_progress);
6786         kfree(ioc->pend_os_device_add);
6787         kfree(ioc->tm_cmds.reply);
6788         kfree(ioc->transport_cmds.reply);
6789         kfree(ioc->scsih_cmds.reply);
6790         kfree(ioc->config_cmds.reply);
6791         kfree(ioc->base_cmds.reply);
6792         kfree(ioc->port_enable_cmds.reply);
6793         kfree(ioc->ctl_cmds.reply);
6794         kfree(ioc->ctl_cmds.sense);
6795         kfree(ioc->pfacts);
6796         ioc->ctl_cmds.reply = NULL;
6797         ioc->base_cmds.reply = NULL;
6798         ioc->tm_cmds.reply = NULL;
6799         ioc->scsih_cmds.reply = NULL;
6800         ioc->transport_cmds.reply = NULL;
6801         ioc->config_cmds.reply = NULL;
6802         ioc->pfacts = NULL;
6803         return r;
6804 }
6805
6806
6807 /**
6808  * mpt3sas_base_detach - remove controller instance
6809  * @ioc: per adapter object
6810  *
6811  * Return nothing.
6812  */
6813 void
6814 mpt3sas_base_detach(struct MPT3SAS_ADAPTER *ioc)
6815 {
6816         dexitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
6817             __func__));
6818
6819         mpt3sas_base_stop_watchdog(ioc);
6820         mpt3sas_base_free_resources(ioc);
6821         _base_release_memory_pools(ioc);
6822         mpt3sas_free_enclosure_list(ioc);
6823         pci_set_drvdata(ioc->pdev, NULL);
6824         kfree(ioc->cpu_msix_table);
6825         if (ioc->is_warpdrive)
6826                 kfree(ioc->reply_post_host_index);
6827         kfree(ioc->pd_handles);
6828         kfree(ioc->blocking_handles);
6829         kfree(ioc->device_remove_in_progress);
6830         kfree(ioc->pend_os_device_add);
6831         kfree(ioc->pfacts);
6832         kfree(ioc->ctl_cmds.reply);
6833         kfree(ioc->ctl_cmds.sense);
6834         kfree(ioc->base_cmds.reply);
6835         kfree(ioc->port_enable_cmds.reply);
6836         kfree(ioc->tm_cmds.reply);
6837         kfree(ioc->transport_cmds.reply);
6838         kfree(ioc->scsih_cmds.reply);
6839         kfree(ioc->config_cmds.reply);
6840 }
6841
6842 /**
6843  * _base_pre_reset_handler - pre reset handler
6844  * @ioc: per adapter object
6845  */
6846 static void _base_pre_reset_handler(struct MPT3SAS_ADAPTER *ioc)
6847 {
6848         mpt3sas_scsih_pre_reset_handler(ioc);
6849         mpt3sas_ctl_pre_reset_handler(ioc);
6850         dtmprintk(ioc, pr_info(MPT3SAS_FMT
6851                         "%s: MPT3_IOC_PRE_RESET\n", ioc->name, __func__));
6852 }
6853
6854 /**
6855  * _base_after_reset_handler - after reset handler
6856  * @ioc: per adapter object
6857  */
6858 static void _base_after_reset_handler(struct MPT3SAS_ADAPTER *ioc)
6859 {
6860         mpt3sas_scsih_after_reset_handler(ioc);
6861         mpt3sas_ctl_after_reset_handler(ioc);
6862         dtmprintk(ioc, pr_info(MPT3SAS_FMT
6863                         "%s: MPT3_IOC_AFTER_RESET\n", ioc->name, __func__));
6864         if (ioc->transport_cmds.status & MPT3_CMD_PENDING) {
6865                 ioc->transport_cmds.status |= MPT3_CMD_RESET;
6866                 mpt3sas_base_free_smid(ioc, ioc->transport_cmds.smid);
6867                 complete(&ioc->transport_cmds.done);
6868         }
6869         if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
6870                 ioc->base_cmds.status |= MPT3_CMD_RESET;
6871                 mpt3sas_base_free_smid(ioc, ioc->base_cmds.smid);
6872                 complete(&ioc->base_cmds.done);
6873         }
6874         if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
6875                 ioc->port_enable_failed = 1;
6876                 ioc->port_enable_cmds.status |= MPT3_CMD_RESET;
6877                 mpt3sas_base_free_smid(ioc, ioc->port_enable_cmds.smid);
6878                 if (ioc->is_driver_loading) {
6879                         ioc->start_scan_failed =
6880                                 MPI2_IOCSTATUS_INTERNAL_ERROR;
6881                         ioc->start_scan = 0;
6882                         ioc->port_enable_cmds.status =
6883                                 MPT3_CMD_NOT_USED;
6884                 } else {
6885                         complete(&ioc->port_enable_cmds.done);
6886                 }
6887         }
6888         if (ioc->config_cmds.status & MPT3_CMD_PENDING) {
6889                 ioc->config_cmds.status |= MPT3_CMD_RESET;
6890                 mpt3sas_base_free_smid(ioc, ioc->config_cmds.smid);
6891                 ioc->config_cmds.smid = USHRT_MAX;
6892                 complete(&ioc->config_cmds.done);
6893         }
6894 }
6895
6896 /**
6897  * _base_reset_done_handler - reset done handler
6898  * @ioc: per adapter object
6899  */
6900 static void _base_reset_done_handler(struct MPT3SAS_ADAPTER *ioc)
6901 {
6902         mpt3sas_scsih_reset_done_handler(ioc);
6903         mpt3sas_ctl_reset_done_handler(ioc);
6904         dtmprintk(ioc, pr_info(MPT3SAS_FMT
6905                         "%s: MPT3_IOC_DONE_RESET\n", ioc->name, __func__));
6906 }
6907
6908 /**
6909  * mpt3sas_wait_for_commands_to_complete - reset controller
6910  * @ioc: Pointer to MPT_ADAPTER structure
6911  *
6912  * This function is waiting 10s for all pending commands to complete
6913  * prior to putting controller in reset.
6914  */
6915 void
6916 mpt3sas_wait_for_commands_to_complete(struct MPT3SAS_ADAPTER *ioc)
6917 {
6918         u32 ioc_state;
6919
6920         ioc->pending_io_count = 0;
6921
6922         ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
6923         if ((ioc_state & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_OPERATIONAL)
6924                 return;
6925
6926         /* pending command count */
6927         ioc->pending_io_count = atomic_read(&ioc->shost->host_busy);
6928
6929         if (!ioc->pending_io_count)
6930                 return;
6931
6932         /* wait for pending commands to complete */
6933         wait_event_timeout(ioc->reset_wq, ioc->pending_io_count == 0, 10 * HZ);
6934 }
6935
6936 /**
6937  * mpt3sas_base_hard_reset_handler - reset controller
6938  * @ioc: Pointer to MPT_ADAPTER structure
6939  * @type: FORCE_BIG_HAMMER or SOFT_RESET
6940  *
6941  * Returns 0 for success, non-zero for failure.
6942  */
6943 int
6944 mpt3sas_base_hard_reset_handler(struct MPT3SAS_ADAPTER *ioc,
6945         enum reset_type type)
6946 {
6947         int r;
6948         unsigned long flags;
6949         u32 ioc_state;
6950         u8 is_fault = 0, is_trigger = 0;
6951
6952         dtmprintk(ioc, pr_info(MPT3SAS_FMT "%s: enter\n", ioc->name,
6953             __func__));
6954
6955         if (ioc->pci_error_recovery) {
6956                 pr_err(MPT3SAS_FMT "%s: pci error recovery reset\n",
6957                     ioc->name, __func__);
6958                 r = 0;
6959                 goto out_unlocked;
6960         }
6961
6962         if (mpt3sas_fwfault_debug)
6963                 mpt3sas_halt_firmware(ioc);
6964
6965         /* wait for an active reset in progress to complete */
6966         mutex_lock(&ioc->reset_in_progress_mutex);
6967
6968         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
6969         ioc->shost_recovery = 1;
6970         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
6971
6972         if ((ioc->diag_buffer_status[MPI2_DIAG_BUF_TYPE_TRACE] &
6973             MPT3_DIAG_BUFFER_IS_REGISTERED) &&
6974             (!(ioc->diag_buffer_status[MPI2_DIAG_BUF_TYPE_TRACE] &
6975             MPT3_DIAG_BUFFER_IS_RELEASED))) {
6976                 is_trigger = 1;
6977                 ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
6978                 if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT)
6979                         is_fault = 1;
6980         }
6981         _base_pre_reset_handler(ioc);
6982         mpt3sas_wait_for_commands_to_complete(ioc);
6983         _base_mask_interrupts(ioc);
6984         r = _base_make_ioc_ready(ioc, type);
6985         if (r)
6986                 goto out;
6987         _base_after_reset_handler(ioc);
6988
6989         /* If this hard reset is called while port enable is active, then
6990          * there is no reason to call make_ioc_operational
6991          */
6992         if (ioc->is_driver_loading && ioc->port_enable_failed) {
6993                 ioc->remove_host = 1;
6994                 r = -EFAULT;
6995                 goto out;
6996         }
6997         r = _base_get_ioc_facts(ioc);
6998         if (r)
6999                 goto out;
7000
7001         if (ioc->rdpq_array_enable && !ioc->rdpq_array_capable)
7002                 panic("%s: Issue occurred with flashing controller firmware."
7003                       "Please reboot the system and ensure that the correct"
7004                       " firmware version is running\n", ioc->name);
7005
7006         r = _base_make_ioc_operational(ioc);
7007         if (!r)
7008                 _base_reset_done_handler(ioc);
7009
7010  out:
7011         dtmprintk(ioc, pr_info(MPT3SAS_FMT "%s: %s\n",
7012             ioc->name, __func__, ((r == 0) ? "SUCCESS" : "FAILED")));
7013
7014         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
7015         ioc->shost_recovery = 0;
7016         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
7017         ioc->ioc_reset_count++;
7018         mutex_unlock(&ioc->reset_in_progress_mutex);
7019
7020  out_unlocked:
7021         if ((r == 0) && is_trigger) {
7022                 if (is_fault)
7023                         mpt3sas_trigger_master(ioc, MASTER_TRIGGER_FW_FAULT);
7024                 else
7025                         mpt3sas_trigger_master(ioc,
7026                             MASTER_TRIGGER_ADAPTER_RESET);
7027         }
7028         dtmprintk(ioc, pr_info(MPT3SAS_FMT "%s: exit\n", ioc->name,
7029             __func__));
7030         return r;
7031 }
This page took 0.452376 seconds and 4 git commands to generate.