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