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