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