These changes are the raw update to linux-4.4.6-rt14. Kernel sources
[kvmfornfv.git] / kernel / drivers / scsi / mpt3sas / mpt3sas_base.c
1 /*
2  * This is the Fusion MPT base driver providing common API layer interface
3  * for access to MPT (Message Passing Technology) firmware.
4  *
5  * This code is based on drivers/scsi/mpt3sas/mpt3sas_base.c
6  * Copyright (C) 2012-2014  LSI Corporation
7  * Copyright (C) 2013-2014 Avago Technologies
8  *  (mailto: MPT-FusionLinux.pdl@avagotech.com)
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * NO WARRANTY
21  * THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
22  * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
23  * LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
24  * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
25  * solely responsible for determining the appropriateness of using and
26  * distributing the Program and assumes all risks associated with its
27  * exercise of rights under this Agreement, including but not limited to
28  * the risks and costs of program errors, damage to or loss of data,
29  * programs or equipment, and unavailability or interruption of operations.
30
31  * DISCLAIMER OF LIABILITY
32  * NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
33  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
38  * HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
39
40  * You should have received a copy of the GNU General Public License
41  * along with this program; if not, write to the Free Software
42  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
43  * USA.
44  */
45
46 #include <linux/kernel.h>
47 #include <linux/module.h>
48 #include <linux/errno.h>
49 #include <linux/init.h>
50 #include <linux/slab.h>
51 #include <linux/types.h>
52 #include <linux/pci.h>
53 #include <linux/kdev_t.h>
54 #include <linux/blkdev.h>
55 #include <linux/delay.h>
56 #include <linux/interrupt.h>
57 #include <linux/dma-mapping.h>
58 #include <linux/io.h>
59 #include <linux/time.h>
60 #include <linux/kthread.h>
61 #include <linux/aer.h>
62
63
64 #include "mpt3sas_base.h"
65
66 static MPT_CALLBACK     mpt_callbacks[MPT_MAX_CALLBACKS];
67
68
69 #define FAULT_POLLING_INTERVAL 1000 /* in milliseconds */
70
71  /* maximum controller queue depth */
72 #define MAX_HBA_QUEUE_DEPTH     30000
73 #define MAX_CHAIN_DEPTH         100000
74 static int max_queue_depth = -1;
75 module_param(max_queue_depth, int, 0);
76 MODULE_PARM_DESC(max_queue_depth, " max controller queue depth ");
77
78 static int max_sgl_entries = -1;
79 module_param(max_sgl_entries, int, 0);
80 MODULE_PARM_DESC(max_sgl_entries, " max sg entries ");
81
82 static int msix_disable = -1;
83 module_param(msix_disable, int, 0);
84 MODULE_PARM_DESC(msix_disable, " disable msix routed interrupts (default=0)");
85
86 static int max_msix_vectors = -1;
87 module_param(max_msix_vectors, int, 0);
88 MODULE_PARM_DESC(max_msix_vectors,
89         " max msix vectors");
90
91 static int mpt3sas_fwfault_debug;
92 MODULE_PARM_DESC(mpt3sas_fwfault_debug,
93         " enable detection of firmware fault and halt firmware - (default=0)");
94
95 static int
96 _base_get_ioc_facts(struct MPT3SAS_ADAPTER *ioc, int sleep_flag);
97
98 /**
99  * _scsih_set_fwfault_debug - global setting of ioc->fwfault_debug.
100  *
101  */
102 static int
103 _scsih_set_fwfault_debug(const char *val, struct kernel_param *kp)
104 {
105         int ret = param_set_int(val, kp);
106         struct MPT3SAS_ADAPTER *ioc;
107
108         if (ret)
109                 return ret;
110
111         /* global ioc spinlock to protect controller list on list operations */
112         pr_info("setting fwfault_debug(%d)\n", mpt3sas_fwfault_debug);
113         spin_lock(&gioc_lock);
114         list_for_each_entry(ioc, &mpt3sas_ioc_list, list)
115                 ioc->fwfault_debug = mpt3sas_fwfault_debug;
116         spin_unlock(&gioc_lock);
117         return 0;
118 }
119 module_param_call(mpt3sas_fwfault_debug, _scsih_set_fwfault_debug,
120         param_get_int, &mpt3sas_fwfault_debug, 0644);
121
122 /**
123  *  mpt3sas_remove_dead_ioc_func - kthread context to remove dead ioc
124  * @arg: input argument, used to derive ioc
125  *
126  * Return 0 if controller is removed from pci subsystem.
127  * Return -1 for other case.
128  */
129 static int mpt3sas_remove_dead_ioc_func(void *arg)
130 {
131         struct MPT3SAS_ADAPTER *ioc = (struct MPT3SAS_ADAPTER *)arg;
132         struct pci_dev *pdev;
133
134         if ((ioc == NULL))
135                 return -1;
136
137         pdev = ioc->pdev;
138         if ((pdev == NULL))
139                 return -1;
140         pci_stop_and_remove_bus_device_locked(pdev);
141         return 0;
142 }
143
144 /**
145  * _base_fault_reset_work - workq handling ioc fault conditions
146  * @work: input argument, used to derive ioc
147  * Context: sleep.
148  *
149  * Return nothing.
150  */
151 static void
152 _base_fault_reset_work(struct work_struct *work)
153 {
154         struct MPT3SAS_ADAPTER *ioc =
155             container_of(work, struct MPT3SAS_ADAPTER, fault_reset_work.work);
156         unsigned long    flags;
157         u32 doorbell;
158         int rc;
159         struct task_struct *p;
160
161
162         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
163         if (ioc->shost_recovery || ioc->pci_error_recovery)
164                 goto rearm_timer;
165         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
166
167         doorbell = mpt3sas_base_get_iocstate(ioc, 0);
168         if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_MASK) {
169                 pr_err(MPT3SAS_FMT "SAS host is non-operational !!!!\n",
170                     ioc->name);
171
172                 /* It may be possible that EEH recovery can resolve some of
173                  * pci bus failure issues rather removing the dead ioc function
174                  * by considering controller is in a non-operational state. So
175                  * here priority is given to the EEH recovery. If it doesn't
176                  * not resolve this issue, mpt3sas driver will consider this
177                  * controller to non-operational state and remove the dead ioc
178                  * function.
179                  */
180                 if (ioc->non_operational_loop++ < 5) {
181                         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock,
182                                                          flags);
183                         goto rearm_timer;
184                 }
185
186                 /*
187                  * Call _scsih_flush_pending_cmds callback so that we flush all
188                  * pending commands back to OS. This call is required to aovid
189                  * deadlock at block layer. Dead IOC will fail to do diag reset,
190                  * and this call is safe since dead ioc will never return any
191                  * command back from HW.
192                  */
193                 ioc->schedule_dead_ioc_flush_running_cmds(ioc);
194                 /*
195                  * Set remove_host flag early since kernel thread will
196                  * take some time to execute.
197                  */
198                 ioc->remove_host = 1;
199                 /*Remove the Dead Host */
200                 p = kthread_run(mpt3sas_remove_dead_ioc_func, ioc,
201                     "%s_dead_ioc_%d", ioc->driver_name, ioc->id);
202                 if (IS_ERR(p))
203                         pr_err(MPT3SAS_FMT
204                         "%s: Running mpt3sas_dead_ioc thread failed !!!!\n",
205                         ioc->name, __func__);
206                 else
207                         pr_err(MPT3SAS_FMT
208                         "%s: Running mpt3sas_dead_ioc thread success !!!!\n",
209                         ioc->name, __func__);
210                 return; /* don't rearm timer */
211         }
212
213         ioc->non_operational_loop = 0;
214
215         if ((doorbell & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_OPERATIONAL) {
216                 rc = mpt3sas_base_hard_reset_handler(ioc, CAN_SLEEP,
217                     FORCE_BIG_HAMMER);
218                 pr_warn(MPT3SAS_FMT "%s: hard reset: %s\n", ioc->name,
219                     __func__, (rc == 0) ? "success" : "failed");
220                 doorbell = mpt3sas_base_get_iocstate(ioc, 0);
221                 if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT)
222                         mpt3sas_base_fault_info(ioc, doorbell &
223                             MPI2_DOORBELL_DATA_MASK);
224                 if (rc && (doorbell & MPI2_IOC_STATE_MASK) !=
225                     MPI2_IOC_STATE_OPERATIONAL)
226                         return; /* don't rearm timer */
227         }
228
229         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
230  rearm_timer:
231         if (ioc->fault_reset_work_q)
232                 queue_delayed_work(ioc->fault_reset_work_q,
233                     &ioc->fault_reset_work,
234                     msecs_to_jiffies(FAULT_POLLING_INTERVAL));
235         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
236 }
237
238 /**
239  * mpt3sas_base_start_watchdog - start the fault_reset_work_q
240  * @ioc: per adapter object
241  * Context: sleep.
242  *
243  * Return nothing.
244  */
245 void
246 mpt3sas_base_start_watchdog(struct MPT3SAS_ADAPTER *ioc)
247 {
248         unsigned long    flags;
249
250         if (ioc->fault_reset_work_q)
251                 return;
252
253         /* initialize fault polling */
254
255         INIT_DELAYED_WORK(&ioc->fault_reset_work, _base_fault_reset_work);
256         snprintf(ioc->fault_reset_work_q_name,
257             sizeof(ioc->fault_reset_work_q_name), "poll_%s%d_status",
258             ioc->driver_name, ioc->id);
259         ioc->fault_reset_work_q =
260                 create_singlethread_workqueue(ioc->fault_reset_work_q_name);
261         if (!ioc->fault_reset_work_q) {
262                 pr_err(MPT3SAS_FMT "%s: failed (line=%d)\n",
263                     ioc->name, __func__, __LINE__);
264                         return;
265         }
266         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
267         if (ioc->fault_reset_work_q)
268                 queue_delayed_work(ioc->fault_reset_work_q,
269                     &ioc->fault_reset_work,
270                     msecs_to_jiffies(FAULT_POLLING_INTERVAL));
271         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
272 }
273
274 /**
275  * mpt3sas_base_stop_watchdog - stop the fault_reset_work_q
276  * @ioc: per adapter object
277  * Context: sleep.
278  *
279  * Return nothing.
280  */
281 void
282 mpt3sas_base_stop_watchdog(struct MPT3SAS_ADAPTER *ioc)
283 {
284         unsigned long flags;
285         struct workqueue_struct *wq;
286
287         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
288         wq = ioc->fault_reset_work_q;
289         ioc->fault_reset_work_q = NULL;
290         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
291         if (wq) {
292                 if (!cancel_delayed_work_sync(&ioc->fault_reset_work))
293                         flush_workqueue(wq);
294                 destroy_workqueue(wq);
295         }
296 }
297
298 /**
299  * mpt3sas_base_fault_info - verbose translation of firmware FAULT code
300  * @ioc: per adapter object
301  * @fault_code: fault code
302  *
303  * Return nothing.
304  */
305 void
306 mpt3sas_base_fault_info(struct MPT3SAS_ADAPTER *ioc , u16 fault_code)
307 {
308         pr_err(MPT3SAS_FMT "fault_state(0x%04x)!\n",
309             ioc->name, fault_code);
310 }
311
312 /**
313  * mpt3sas_halt_firmware - halt's mpt controller firmware
314  * @ioc: per adapter object
315  *
316  * For debugging timeout related issues.  Writing 0xCOFFEE00
317  * to the doorbell register will halt controller firmware. With
318  * the purpose to stop both driver and firmware, the enduser can
319  * obtain a ring buffer from controller UART.
320  */
321 void
322 mpt3sas_halt_firmware(struct MPT3SAS_ADAPTER *ioc)
323 {
324         u32 doorbell;
325
326         if (!ioc->fwfault_debug)
327                 return;
328
329         dump_stack();
330
331         doorbell = readl(&ioc->chip->Doorbell);
332         if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT)
333                 mpt3sas_base_fault_info(ioc , doorbell);
334         else {
335                 writel(0xC0FFEE00, &ioc->chip->Doorbell);
336                 pr_err(MPT3SAS_FMT "Firmware is halted due to command timeout\n",
337                         ioc->name);
338         }
339
340         if (ioc->fwfault_debug == 2)
341                 for (;;)
342                         ;
343         else
344                 panic("panic in %s\n", __func__);
345 }
346
347 /**
348  * _base_sas_ioc_info - verbose translation of the ioc status
349  * @ioc: per adapter object
350  * @mpi_reply: reply mf payload returned from firmware
351  * @request_hdr: request mf
352  *
353  * Return nothing.
354  */
355 static void
356 _base_sas_ioc_info(struct MPT3SAS_ADAPTER *ioc, MPI2DefaultReply_t *mpi_reply,
357         MPI2RequestHeader_t *request_hdr)
358 {
359         u16 ioc_status = le16_to_cpu(mpi_reply->IOCStatus) &
360             MPI2_IOCSTATUS_MASK;
361         char *desc = NULL;
362         u16 frame_sz;
363         char *func_str = NULL;
364
365         /* SCSI_IO, RAID_PASS are handled from _scsih_scsi_ioc_info */
366         if (request_hdr->Function == MPI2_FUNCTION_SCSI_IO_REQUEST ||
367             request_hdr->Function == MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH ||
368             request_hdr->Function == MPI2_FUNCTION_EVENT_NOTIFICATION)
369                 return;
370
371         if (ioc_status == MPI2_IOCSTATUS_CONFIG_INVALID_PAGE)
372                 return;
373
374         switch (ioc_status) {
375
376 /****************************************************************************
377 *  Common IOCStatus values for all replies
378 ****************************************************************************/
379
380         case MPI2_IOCSTATUS_INVALID_FUNCTION:
381                 desc = "invalid function";
382                 break;
383         case MPI2_IOCSTATUS_BUSY:
384                 desc = "busy";
385                 break;
386         case MPI2_IOCSTATUS_INVALID_SGL:
387                 desc = "invalid sgl";
388                 break;
389         case MPI2_IOCSTATUS_INTERNAL_ERROR:
390                 desc = "internal error";
391                 break;
392         case MPI2_IOCSTATUS_INVALID_VPID:
393                 desc = "invalid vpid";
394                 break;
395         case MPI2_IOCSTATUS_INSUFFICIENT_RESOURCES:
396                 desc = "insufficient resources";
397                 break;
398         case MPI2_IOCSTATUS_INVALID_FIELD:
399                 desc = "invalid field";
400                 break;
401         case MPI2_IOCSTATUS_INVALID_STATE:
402                 desc = "invalid state";
403                 break;
404         case MPI2_IOCSTATUS_OP_STATE_NOT_SUPPORTED:
405                 desc = "op state not supported";
406                 break;
407
408 /****************************************************************************
409 *  Config IOCStatus values
410 ****************************************************************************/
411
412         case MPI2_IOCSTATUS_CONFIG_INVALID_ACTION:
413                 desc = "config invalid action";
414                 break;
415         case MPI2_IOCSTATUS_CONFIG_INVALID_TYPE:
416                 desc = "config invalid type";
417                 break;
418         case MPI2_IOCSTATUS_CONFIG_INVALID_PAGE:
419                 desc = "config invalid page";
420                 break;
421         case MPI2_IOCSTATUS_CONFIG_INVALID_DATA:
422                 desc = "config invalid data";
423                 break;
424         case MPI2_IOCSTATUS_CONFIG_NO_DEFAULTS:
425                 desc = "config no defaults";
426                 break;
427         case MPI2_IOCSTATUS_CONFIG_CANT_COMMIT:
428                 desc = "config cant commit";
429                 break;
430
431 /****************************************************************************
432 *  SCSI IO Reply
433 ****************************************************************************/
434
435         case MPI2_IOCSTATUS_SCSI_RECOVERED_ERROR:
436         case MPI2_IOCSTATUS_SCSI_INVALID_DEVHANDLE:
437         case MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
438         case MPI2_IOCSTATUS_SCSI_DATA_OVERRUN:
439         case MPI2_IOCSTATUS_SCSI_DATA_UNDERRUN:
440         case MPI2_IOCSTATUS_SCSI_IO_DATA_ERROR:
441         case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
442         case MPI2_IOCSTATUS_SCSI_TASK_TERMINATED:
443         case MPI2_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
444         case MPI2_IOCSTATUS_SCSI_TASK_MGMT_FAILED:
445         case MPI2_IOCSTATUS_SCSI_IOC_TERMINATED:
446         case MPI2_IOCSTATUS_SCSI_EXT_TERMINATED:
447                 break;
448
449 /****************************************************************************
450 *  For use by SCSI Initiator and SCSI Target end-to-end data protection
451 ****************************************************************************/
452
453         case MPI2_IOCSTATUS_EEDP_GUARD_ERROR:
454                 desc = "eedp guard error";
455                 break;
456         case MPI2_IOCSTATUS_EEDP_REF_TAG_ERROR:
457                 desc = "eedp ref tag error";
458                 break;
459         case MPI2_IOCSTATUS_EEDP_APP_TAG_ERROR:
460                 desc = "eedp app tag error";
461                 break;
462
463 /****************************************************************************
464 *  SCSI Target values
465 ****************************************************************************/
466
467         case MPI2_IOCSTATUS_TARGET_INVALID_IO_INDEX:
468                 desc = "target invalid io index";
469                 break;
470         case MPI2_IOCSTATUS_TARGET_ABORTED:
471                 desc = "target aborted";
472                 break;
473         case MPI2_IOCSTATUS_TARGET_NO_CONN_RETRYABLE:
474                 desc = "target no conn retryable";
475                 break;
476         case MPI2_IOCSTATUS_TARGET_NO_CONNECTION:
477                 desc = "target no connection";
478                 break;
479         case MPI2_IOCSTATUS_TARGET_XFER_COUNT_MISMATCH:
480                 desc = "target xfer count mismatch";
481                 break;
482         case MPI2_IOCSTATUS_TARGET_DATA_OFFSET_ERROR:
483                 desc = "target data offset error";
484                 break;
485         case MPI2_IOCSTATUS_TARGET_TOO_MUCH_WRITE_DATA:
486                 desc = "target too much write data";
487                 break;
488         case MPI2_IOCSTATUS_TARGET_IU_TOO_SHORT:
489                 desc = "target iu too short";
490                 break;
491         case MPI2_IOCSTATUS_TARGET_ACK_NAK_TIMEOUT:
492                 desc = "target ack nak timeout";
493                 break;
494         case MPI2_IOCSTATUS_TARGET_NAK_RECEIVED:
495                 desc = "target nak received";
496                 break;
497
498 /****************************************************************************
499 *  Serial Attached SCSI values
500 ****************************************************************************/
501
502         case MPI2_IOCSTATUS_SAS_SMP_REQUEST_FAILED:
503                 desc = "smp request failed";
504                 break;
505         case MPI2_IOCSTATUS_SAS_SMP_DATA_OVERRUN:
506                 desc = "smp data overrun";
507                 break;
508
509 /****************************************************************************
510 *  Diagnostic Buffer Post / Diagnostic Release values
511 ****************************************************************************/
512
513         case MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED:
514                 desc = "diagnostic released";
515                 break;
516         default:
517                 break;
518         }
519
520         if (!desc)
521                 return;
522
523         switch (request_hdr->Function) {
524         case MPI2_FUNCTION_CONFIG:
525                 frame_sz = sizeof(Mpi2ConfigRequest_t) + ioc->sge_size;
526                 func_str = "config_page";
527                 break;
528         case MPI2_FUNCTION_SCSI_TASK_MGMT:
529                 frame_sz = sizeof(Mpi2SCSITaskManagementRequest_t);
530                 func_str = "task_mgmt";
531                 break;
532         case MPI2_FUNCTION_SAS_IO_UNIT_CONTROL:
533                 frame_sz = sizeof(Mpi2SasIoUnitControlRequest_t);
534                 func_str = "sas_iounit_ctl";
535                 break;
536         case MPI2_FUNCTION_SCSI_ENCLOSURE_PROCESSOR:
537                 frame_sz = sizeof(Mpi2SepRequest_t);
538                 func_str = "enclosure";
539                 break;
540         case MPI2_FUNCTION_IOC_INIT:
541                 frame_sz = sizeof(Mpi2IOCInitRequest_t);
542                 func_str = "ioc_init";
543                 break;
544         case MPI2_FUNCTION_PORT_ENABLE:
545                 frame_sz = sizeof(Mpi2PortEnableRequest_t);
546                 func_str = "port_enable";
547                 break;
548         case MPI2_FUNCTION_SMP_PASSTHROUGH:
549                 frame_sz = sizeof(Mpi2SmpPassthroughRequest_t) + ioc->sge_size;
550                 func_str = "smp_passthru";
551                 break;
552         default:
553                 frame_sz = 32;
554                 func_str = "unknown";
555                 break;
556         }
557
558         pr_warn(MPT3SAS_FMT "ioc_status: %s(0x%04x), request(0x%p),(%s)\n",
559                 ioc->name, desc, ioc_status, request_hdr, func_str);
560
561         _debug_dump_mf(request_hdr, frame_sz/4);
562 }
563
564 /**
565  * _base_display_event_data - verbose translation of firmware asyn events
566  * @ioc: per adapter object
567  * @mpi_reply: reply mf payload returned from firmware
568  *
569  * Return nothing.
570  */
571 static void
572 _base_display_event_data(struct MPT3SAS_ADAPTER *ioc,
573         Mpi2EventNotificationReply_t *mpi_reply)
574 {
575         char *desc = NULL;
576         u16 event;
577
578         if (!(ioc->logging_level & MPT_DEBUG_EVENTS))
579                 return;
580
581         event = le16_to_cpu(mpi_reply->Event);
582
583         switch (event) {
584         case MPI2_EVENT_LOG_DATA:
585                 desc = "Log Data";
586                 break;
587         case MPI2_EVENT_STATE_CHANGE:
588                 desc = "Status Change";
589                 break;
590         case MPI2_EVENT_HARD_RESET_RECEIVED:
591                 desc = "Hard Reset Received";
592                 break;
593         case MPI2_EVENT_EVENT_CHANGE:
594                 desc = "Event Change";
595                 break;
596         case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
597                 desc = "Device Status Change";
598                 break;
599         case MPI2_EVENT_IR_OPERATION_STATUS:
600                 if (!ioc->hide_ir_msg)
601                         desc = "IR Operation Status";
602                 break;
603         case MPI2_EVENT_SAS_DISCOVERY:
604         {
605                 Mpi2EventDataSasDiscovery_t *event_data =
606                     (Mpi2EventDataSasDiscovery_t *)mpi_reply->EventData;
607                 pr_info(MPT3SAS_FMT "Discovery: (%s)", ioc->name,
608                     (event_data->ReasonCode == MPI2_EVENT_SAS_DISC_RC_STARTED) ?
609                     "start" : "stop");
610                 if (event_data->DiscoveryStatus)
611                         pr_info("discovery_status(0x%08x)",
612                             le32_to_cpu(event_data->DiscoveryStatus));
613                         pr_info("\n");
614                 return;
615         }
616         case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
617                 desc = "SAS Broadcast Primitive";
618                 break;
619         case MPI2_EVENT_SAS_INIT_DEVICE_STATUS_CHANGE:
620                 desc = "SAS Init Device Status Change";
621                 break;
622         case MPI2_EVENT_SAS_INIT_TABLE_OVERFLOW:
623                 desc = "SAS Init Table Overflow";
624                 break;
625         case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
626                 desc = "SAS Topology Change List";
627                 break;
628         case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
629                 desc = "SAS Enclosure Device Status Change";
630                 break;
631         case MPI2_EVENT_IR_VOLUME:
632                 if (!ioc->hide_ir_msg)
633                         desc = "IR Volume";
634                 break;
635         case MPI2_EVENT_IR_PHYSICAL_DISK:
636                 if (!ioc->hide_ir_msg)
637                         desc = "IR Physical Disk";
638                 break;
639         case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
640                 if (!ioc->hide_ir_msg)
641                         desc = "IR Configuration Change List";
642                 break;
643         case MPI2_EVENT_LOG_ENTRY_ADDED:
644                 if (!ioc->hide_ir_msg)
645                         desc = "Log Entry Added";
646                 break;
647         case MPI2_EVENT_TEMP_THRESHOLD:
648                 desc = "Temperature Threshold";
649                 break;
650         }
651
652         if (!desc)
653                 return;
654
655         pr_info(MPT3SAS_FMT "%s\n", ioc->name, desc);
656 }
657
658 /**
659  * _base_sas_log_info - verbose translation of firmware log info
660  * @ioc: per adapter object
661  * @log_info: log info
662  *
663  * Return nothing.
664  */
665 static void
666 _base_sas_log_info(struct MPT3SAS_ADAPTER *ioc , u32 log_info)
667 {
668         union loginfo_type {
669                 u32     loginfo;
670                 struct {
671                         u32     subcode:16;
672                         u32     code:8;
673                         u32     originator:4;
674                         u32     bus_type:4;
675                 } dw;
676         };
677         union loginfo_type sas_loginfo;
678         char *originator_str = NULL;
679
680         sas_loginfo.loginfo = log_info;
681         if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
682                 return;
683
684         /* each nexus loss loginfo */
685         if (log_info == 0x31170000)
686                 return;
687
688         /* eat the loginfos associated with task aborts */
689         if (ioc->ignore_loginfos && (log_info == 0x30050000 || log_info ==
690             0x31140000 || log_info == 0x31130000))
691                 return;
692
693         switch (sas_loginfo.dw.originator) {
694         case 0:
695                 originator_str = "IOP";
696                 break;
697         case 1:
698                 originator_str = "PL";
699                 break;
700         case 2:
701                 if (!ioc->hide_ir_msg)
702                         originator_str = "IR";
703                 else
704                         originator_str = "WarpDrive";
705                 break;
706         }
707
708         pr_warn(MPT3SAS_FMT
709                 "log_info(0x%08x): originator(%s), code(0x%02x), sub_code(0x%04x)\n",
710                 ioc->name, log_info,
711              originator_str, sas_loginfo.dw.code,
712              sas_loginfo.dw.subcode);
713 }
714
715 /**
716  * _base_display_reply_info -
717  * @ioc: per adapter object
718  * @smid: system request message index
719  * @msix_index: MSIX table index supplied by the OS
720  * @reply: reply message frame(lower 32bit addr)
721  *
722  * Return nothing.
723  */
724 static void
725 _base_display_reply_info(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
726         u32 reply)
727 {
728         MPI2DefaultReply_t *mpi_reply;
729         u16 ioc_status;
730         u32 loginfo = 0;
731
732         mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
733         if (unlikely(!mpi_reply)) {
734                 pr_err(MPT3SAS_FMT "mpi_reply not valid at %s:%d/%s()!\n",
735                     ioc->name, __FILE__, __LINE__, __func__);
736                 return;
737         }
738         ioc_status = le16_to_cpu(mpi_reply->IOCStatus);
739
740         if ((ioc_status & MPI2_IOCSTATUS_MASK) &&
741             (ioc->logging_level & MPT_DEBUG_REPLY)) {
742                 _base_sas_ioc_info(ioc , mpi_reply,
743                    mpt3sas_base_get_msg_frame(ioc, smid));
744         }
745
746         if (ioc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
747                 loginfo = le32_to_cpu(mpi_reply->IOCLogInfo);
748                 _base_sas_log_info(ioc, loginfo);
749         }
750
751         if (ioc_status || loginfo) {
752                 ioc_status &= MPI2_IOCSTATUS_MASK;
753                 mpt3sas_trigger_mpi(ioc, ioc_status, loginfo);
754         }
755 }
756
757 /**
758  * mpt3sas_base_done - base internal command completion routine
759  * @ioc: per adapter object
760  * @smid: system request message index
761  * @msix_index: MSIX table index supplied by the OS
762  * @reply: reply message frame(lower 32bit addr)
763  *
764  * Return 1 meaning mf should be freed from _base_interrupt
765  *        0 means the mf is freed from this function.
766  */
767 u8
768 mpt3sas_base_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
769         u32 reply)
770 {
771         MPI2DefaultReply_t *mpi_reply;
772
773         mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
774         if (mpi_reply && mpi_reply->Function == MPI2_FUNCTION_EVENT_ACK)
775                 return 1;
776
777         if (ioc->base_cmds.status == MPT3_CMD_NOT_USED)
778                 return 1;
779
780         ioc->base_cmds.status |= MPT3_CMD_COMPLETE;
781         if (mpi_reply) {
782                 ioc->base_cmds.status |= MPT3_CMD_REPLY_VALID;
783                 memcpy(ioc->base_cmds.reply, mpi_reply, mpi_reply->MsgLength*4);
784         }
785         ioc->base_cmds.status &= ~MPT3_CMD_PENDING;
786
787         complete(&ioc->base_cmds.done);
788         return 1;
789 }
790
791 /**
792  * _base_async_event - main callback handler for firmware asyn events
793  * @ioc: per adapter object
794  * @msix_index: MSIX table index supplied by the OS
795  * @reply: reply message frame(lower 32bit addr)
796  *
797  * Return 1 meaning mf should be freed from _base_interrupt
798  *        0 means the mf is freed from this function.
799  */
800 static u8
801 _base_async_event(struct MPT3SAS_ADAPTER *ioc, u8 msix_index, u32 reply)
802 {
803         Mpi2EventNotificationReply_t *mpi_reply;
804         Mpi2EventAckRequest_t *ack_request;
805         u16 smid;
806
807         mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
808         if (!mpi_reply)
809                 return 1;
810         if (mpi_reply->Function != MPI2_FUNCTION_EVENT_NOTIFICATION)
811                 return 1;
812
813         _base_display_event_data(ioc, mpi_reply);
814
815         if (!(mpi_reply->AckRequired & MPI2_EVENT_NOTIFICATION_ACK_REQUIRED))
816                 goto out;
817         smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
818         if (!smid) {
819                 pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n",
820                     ioc->name, __func__);
821                 goto out;
822         }
823
824         ack_request = mpt3sas_base_get_msg_frame(ioc, smid);
825         memset(ack_request, 0, sizeof(Mpi2EventAckRequest_t));
826         ack_request->Function = MPI2_FUNCTION_EVENT_ACK;
827         ack_request->Event = mpi_reply->Event;
828         ack_request->EventContext = mpi_reply->EventContext;
829         ack_request->VF_ID = 0;  /* TODO */
830         ack_request->VP_ID = 0;
831         mpt3sas_base_put_smid_default(ioc, smid);
832
833  out:
834
835         /* scsih callback handler */
836         mpt3sas_scsih_event_callback(ioc, msix_index, reply);
837
838         /* ctl callback handler */
839         mpt3sas_ctl_event_callback(ioc, msix_index, reply);
840
841         return 1;
842 }
843
844 /**
845  * _base_get_cb_idx - obtain the callback index
846  * @ioc: per adapter object
847  * @smid: system request message index
848  *
849  * Return callback index.
850  */
851 static u8
852 _base_get_cb_idx(struct MPT3SAS_ADAPTER *ioc, u16 smid)
853 {
854         int i;
855         u8 cb_idx;
856
857         if (smid < ioc->hi_priority_smid) {
858                 i = smid - 1;
859                 cb_idx = ioc->scsi_lookup[i].cb_idx;
860         } else if (smid < ioc->internal_smid) {
861                 i = smid - ioc->hi_priority_smid;
862                 cb_idx = ioc->hpr_lookup[i].cb_idx;
863         } else if (smid <= ioc->hba_queue_depth) {
864                 i = smid - ioc->internal_smid;
865                 cb_idx = ioc->internal_lookup[i].cb_idx;
866         } else
867                 cb_idx = 0xFF;
868         return cb_idx;
869 }
870
871 /**
872  * _base_mask_interrupts - disable interrupts
873  * @ioc: per adapter object
874  *
875  * Disabling ResetIRQ, Reply and Doorbell Interrupts
876  *
877  * Return nothing.
878  */
879 static void
880 _base_mask_interrupts(struct MPT3SAS_ADAPTER *ioc)
881 {
882         u32 him_register;
883
884         ioc->mask_interrupts = 1;
885         him_register = readl(&ioc->chip->HostInterruptMask);
886         him_register |= MPI2_HIM_DIM + MPI2_HIM_RIM + MPI2_HIM_RESET_IRQ_MASK;
887         writel(him_register, &ioc->chip->HostInterruptMask);
888         readl(&ioc->chip->HostInterruptMask);
889 }
890
891 /**
892  * _base_unmask_interrupts - enable interrupts
893  * @ioc: per adapter object
894  *
895  * Enabling only Reply Interrupts
896  *
897  * Return nothing.
898  */
899 static void
900 _base_unmask_interrupts(struct MPT3SAS_ADAPTER *ioc)
901 {
902         u32 him_register;
903
904         him_register = readl(&ioc->chip->HostInterruptMask);
905         him_register &= ~MPI2_HIM_RIM;
906         writel(him_register, &ioc->chip->HostInterruptMask);
907         ioc->mask_interrupts = 0;
908 }
909
910 union reply_descriptor {
911         u64 word;
912         struct {
913                 u32 low;
914                 u32 high;
915         } u;
916 };
917
918 /**
919  * _base_interrupt - MPT adapter (IOC) specific interrupt handler.
920  * @irq: irq number (not used)
921  * @bus_id: bus identifier cookie == pointer to MPT_ADAPTER structure
922  * @r: pt_regs pointer (not used)
923  *
924  * Return IRQ_HANDLE if processed, else IRQ_NONE.
925  */
926 static irqreturn_t
927 _base_interrupt(int irq, void *bus_id)
928 {
929         struct adapter_reply_queue *reply_q = bus_id;
930         union reply_descriptor rd;
931         u32 completed_cmds;
932         u8 request_desript_type;
933         u16 smid;
934         u8 cb_idx;
935         u32 reply;
936         u8 msix_index = reply_q->msix_index;
937         struct MPT3SAS_ADAPTER *ioc = reply_q->ioc;
938         Mpi2ReplyDescriptorsUnion_t *rpf;
939         u8 rc;
940
941         if (ioc->mask_interrupts)
942                 return IRQ_NONE;
943
944         if (!atomic_add_unless(&reply_q->busy, 1, 1))
945                 return IRQ_NONE;
946
947         rpf = &reply_q->reply_post_free[reply_q->reply_post_host_index];
948         request_desript_type = rpf->Default.ReplyFlags
949              & MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
950         if (request_desript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED) {
951                 atomic_dec(&reply_q->busy);
952                 return IRQ_NONE;
953         }
954
955         completed_cmds = 0;
956         cb_idx = 0xFF;
957         do {
958                 rd.word = le64_to_cpu(rpf->Words);
959                 if (rd.u.low == UINT_MAX || rd.u.high == UINT_MAX)
960                         goto out;
961                 reply = 0;
962                 smid = le16_to_cpu(rpf->Default.DescriptorTypeDependent1);
963                 if (request_desript_type ==
964                     MPI25_RPY_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO_SUCCESS ||
965                     request_desript_type ==
966                     MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS) {
967                         cb_idx = _base_get_cb_idx(ioc, smid);
968                         if ((likely(cb_idx < MPT_MAX_CALLBACKS)) &&
969                             (likely(mpt_callbacks[cb_idx] != NULL))) {
970                                 rc = mpt_callbacks[cb_idx](ioc, smid,
971                                     msix_index, 0);
972                                 if (rc)
973                                         mpt3sas_base_free_smid(ioc, smid);
974                         }
975                 } else if (request_desript_type ==
976                     MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY) {
977                         reply = le32_to_cpu(
978                             rpf->AddressReply.ReplyFrameAddress);
979                         if (reply > ioc->reply_dma_max_address ||
980                             reply < ioc->reply_dma_min_address)
981                                 reply = 0;
982                         if (smid) {
983                                 cb_idx = _base_get_cb_idx(ioc, smid);
984                                 if ((likely(cb_idx < MPT_MAX_CALLBACKS)) &&
985                                     (likely(mpt_callbacks[cb_idx] != NULL))) {
986                                         rc = mpt_callbacks[cb_idx](ioc, smid,
987                                             msix_index, reply);
988                                         if (reply)
989                                                 _base_display_reply_info(ioc,
990                                                     smid, msix_index, reply);
991                                         if (rc)
992                                                 mpt3sas_base_free_smid(ioc,
993                                                     smid);
994                                 }
995                         } else {
996                                 _base_async_event(ioc, msix_index, reply);
997                         }
998
999                         /* reply free queue handling */
1000                         if (reply) {
1001                                 ioc->reply_free_host_index =
1002                                     (ioc->reply_free_host_index ==
1003                                     (ioc->reply_free_queue_depth - 1)) ?
1004                                     0 : ioc->reply_free_host_index + 1;
1005                                 ioc->reply_free[ioc->reply_free_host_index] =
1006                                     cpu_to_le32(reply);
1007                                 wmb();
1008                                 writel(ioc->reply_free_host_index,
1009                                     &ioc->chip->ReplyFreeHostIndex);
1010                         }
1011                 }
1012
1013                 rpf->Words = cpu_to_le64(ULLONG_MAX);
1014                 reply_q->reply_post_host_index =
1015                     (reply_q->reply_post_host_index ==
1016                     (ioc->reply_post_queue_depth - 1)) ? 0 :
1017                     reply_q->reply_post_host_index + 1;
1018                 request_desript_type =
1019                     reply_q->reply_post_free[reply_q->reply_post_host_index].
1020                     Default.ReplyFlags & MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
1021                 completed_cmds++;
1022                 if (request_desript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
1023                         goto out;
1024                 if (!reply_q->reply_post_host_index)
1025                         rpf = reply_q->reply_post_free;
1026                 else
1027                         rpf++;
1028         } while (1);
1029
1030  out:
1031
1032         if (!completed_cmds) {
1033                 atomic_dec(&reply_q->busy);
1034                 return IRQ_NONE;
1035         }
1036
1037         wmb();
1038         if (ioc->is_warpdrive) {
1039                 writel(reply_q->reply_post_host_index,
1040                 ioc->reply_post_host_index[msix_index]);
1041                 atomic_dec(&reply_q->busy);
1042                 return IRQ_HANDLED;
1043         }
1044
1045         /* Update Reply Post Host Index.
1046          * For those HBA's which support combined reply queue feature
1047          * 1. Get the correct Supplemental Reply Post Host Index Register.
1048          *    i.e. (msix_index / 8)th entry from Supplemental Reply Post Host
1049          *    Index Register address bank i.e replyPostRegisterIndex[],
1050          * 2. Then update this register with new reply host index value
1051          *    in ReplyPostIndex field and the MSIxIndex field with
1052          *    msix_index value reduced to a value between 0 and 7,
1053          *    using a modulo 8 operation. Since each Supplemental Reply Post
1054          *    Host Index Register supports 8 MSI-X vectors.
1055          *
1056          * For other HBA's just update the Reply Post Host Index register with
1057          * new reply host index value in ReplyPostIndex Field and msix_index
1058          * value in MSIxIndex field.
1059          */
1060         if (ioc->msix96_vector)
1061                 writel(reply_q->reply_post_host_index | ((msix_index  & 7) <<
1062                         MPI2_RPHI_MSIX_INDEX_SHIFT),
1063                         ioc->replyPostRegisterIndex[msix_index/8]);
1064         else
1065                 writel(reply_q->reply_post_host_index | (msix_index <<
1066                         MPI2_RPHI_MSIX_INDEX_SHIFT),
1067                         &ioc->chip->ReplyPostHostIndex);
1068         atomic_dec(&reply_q->busy);
1069         return IRQ_HANDLED;
1070 }
1071
1072 /**
1073  * _base_is_controller_msix_enabled - is controller support muli-reply queues
1074  * @ioc: per adapter object
1075  *
1076  */
1077 static inline int
1078 _base_is_controller_msix_enabled(struct MPT3SAS_ADAPTER *ioc)
1079 {
1080         return (ioc->facts.IOCCapabilities &
1081             MPI2_IOCFACTS_CAPABILITY_MSI_X_INDEX) && ioc->msix_enable;
1082 }
1083
1084 /**
1085  * mpt3sas_base_flush_reply_queues - flushing the MSIX reply queues
1086  * @ioc: per adapter object
1087  * Context: ISR conext
1088  *
1089  * Called when a Task Management request has completed. We want
1090  * to flush the other reply queues so all the outstanding IO has been
1091  * completed back to OS before we process the TM completetion.
1092  *
1093  * Return nothing.
1094  */
1095 void
1096 mpt3sas_base_flush_reply_queues(struct MPT3SAS_ADAPTER *ioc)
1097 {
1098         struct adapter_reply_queue *reply_q;
1099
1100         /* If MSIX capability is turned off
1101          * then multi-queues are not enabled
1102          */
1103         if (!_base_is_controller_msix_enabled(ioc))
1104                 return;
1105
1106         list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
1107                 if (ioc->shost_recovery)
1108                         return;
1109                 /* TMs are on msix_index == 0 */
1110                 if (reply_q->msix_index == 0)
1111                         continue;
1112                 _base_interrupt(reply_q->vector, (void *)reply_q);
1113         }
1114 }
1115
1116 /**
1117  * mpt3sas_base_release_callback_handler - clear interrupt callback handler
1118  * @cb_idx: callback index
1119  *
1120  * Return nothing.
1121  */
1122 void
1123 mpt3sas_base_release_callback_handler(u8 cb_idx)
1124 {
1125         mpt_callbacks[cb_idx] = NULL;
1126 }
1127
1128 /**
1129  * mpt3sas_base_register_callback_handler - obtain index for the interrupt callback handler
1130  * @cb_func: callback function
1131  *
1132  * Returns cb_func.
1133  */
1134 u8
1135 mpt3sas_base_register_callback_handler(MPT_CALLBACK cb_func)
1136 {
1137         u8 cb_idx;
1138
1139         for (cb_idx = MPT_MAX_CALLBACKS-1; cb_idx; cb_idx--)
1140                 if (mpt_callbacks[cb_idx] == NULL)
1141                         break;
1142
1143         mpt_callbacks[cb_idx] = cb_func;
1144         return cb_idx;
1145 }
1146
1147 /**
1148  * mpt3sas_base_initialize_callback_handler - initialize the interrupt callback handler
1149  *
1150  * Return nothing.
1151  */
1152 void
1153 mpt3sas_base_initialize_callback_handler(void)
1154 {
1155         u8 cb_idx;
1156
1157         for (cb_idx = 0; cb_idx < MPT_MAX_CALLBACKS; cb_idx++)
1158                 mpt3sas_base_release_callback_handler(cb_idx);
1159 }
1160
1161
1162 /**
1163  * _base_build_zero_len_sge - build zero length sg entry
1164  * @ioc: per adapter object
1165  * @paddr: virtual address for SGE
1166  *
1167  * Create a zero length scatter gather entry to insure the IOCs hardware has
1168  * something to use if the target device goes brain dead and tries
1169  * to send data even when none is asked for.
1170  *
1171  * Return nothing.
1172  */
1173 static void
1174 _base_build_zero_len_sge(struct MPT3SAS_ADAPTER *ioc, void *paddr)
1175 {
1176         u32 flags_length = (u32)((MPI2_SGE_FLAGS_LAST_ELEMENT |
1177             MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_END_OF_LIST |
1178             MPI2_SGE_FLAGS_SIMPLE_ELEMENT) <<
1179             MPI2_SGE_FLAGS_SHIFT);
1180         ioc->base_add_sg_single(paddr, flags_length, -1);
1181 }
1182
1183 /**
1184  * _base_add_sg_single_32 - Place a simple 32 bit SGE at address pAddr.
1185  * @paddr: virtual address for SGE
1186  * @flags_length: SGE flags and data transfer length
1187  * @dma_addr: Physical address
1188  *
1189  * Return nothing.
1190  */
1191 static void
1192 _base_add_sg_single_32(void *paddr, u32 flags_length, dma_addr_t dma_addr)
1193 {
1194         Mpi2SGESimple32_t *sgel = paddr;
1195
1196         flags_length |= (MPI2_SGE_FLAGS_32_BIT_ADDRESSING |
1197             MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT;
1198         sgel->FlagsLength = cpu_to_le32(flags_length);
1199         sgel->Address = cpu_to_le32(dma_addr);
1200 }
1201
1202
1203 /**
1204  * _base_add_sg_single_64 - Place a simple 64 bit SGE at address pAddr.
1205  * @paddr: virtual address for SGE
1206  * @flags_length: SGE flags and data transfer length
1207  * @dma_addr: Physical address
1208  *
1209  * Return nothing.
1210  */
1211 static void
1212 _base_add_sg_single_64(void *paddr, u32 flags_length, dma_addr_t dma_addr)
1213 {
1214         Mpi2SGESimple64_t *sgel = paddr;
1215
1216         flags_length |= (MPI2_SGE_FLAGS_64_BIT_ADDRESSING |
1217             MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT;
1218         sgel->FlagsLength = cpu_to_le32(flags_length);
1219         sgel->Address = cpu_to_le64(dma_addr);
1220 }
1221
1222 /**
1223  * _base_get_chain_buffer_tracker - obtain chain tracker
1224  * @ioc: per adapter object
1225  * @smid: smid associated to an IO request
1226  *
1227  * Returns chain tracker(from ioc->free_chain_list)
1228  */
1229 static struct chain_tracker *
1230 _base_get_chain_buffer_tracker(struct MPT3SAS_ADAPTER *ioc, u16 smid)
1231 {
1232         struct chain_tracker *chain_req;
1233         unsigned long flags;
1234
1235         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
1236         if (list_empty(&ioc->free_chain_list)) {
1237                 spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
1238                 dfailprintk(ioc, pr_warn(MPT3SAS_FMT
1239                         "chain buffers not available\n", ioc->name));
1240                 return NULL;
1241         }
1242         chain_req = list_entry(ioc->free_chain_list.next,
1243             struct chain_tracker, tracker_list);
1244         list_del_init(&chain_req->tracker_list);
1245         list_add_tail(&chain_req->tracker_list,
1246             &ioc->scsi_lookup[smid - 1].chain_list);
1247         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
1248         return chain_req;
1249 }
1250
1251
1252 /**
1253  * _base_build_sg - build generic sg
1254  * @ioc: per adapter object
1255  * @psge: virtual address for SGE
1256  * @data_out_dma: physical address for WRITES
1257  * @data_out_sz: data xfer size for WRITES
1258  * @data_in_dma: physical address for READS
1259  * @data_in_sz: data xfer size for READS
1260  *
1261  * Return nothing.
1262  */
1263 static void
1264 _base_build_sg(struct MPT3SAS_ADAPTER *ioc, void *psge,
1265         dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
1266         size_t data_in_sz)
1267 {
1268         u32 sgl_flags;
1269
1270         if (!data_out_sz && !data_in_sz) {
1271                 _base_build_zero_len_sge(ioc, psge);
1272                 return;
1273         }
1274
1275         if (data_out_sz && data_in_sz) {
1276                 /* WRITE sgel first */
1277                 sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
1278                     MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_HOST_TO_IOC);
1279                 sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1280                 ioc->base_add_sg_single(psge, sgl_flags |
1281                     data_out_sz, data_out_dma);
1282
1283                 /* incr sgel */
1284                 psge += ioc->sge_size;
1285
1286                 /* READ sgel last */
1287                 sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
1288                     MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
1289                     MPI2_SGE_FLAGS_END_OF_LIST);
1290                 sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1291                 ioc->base_add_sg_single(psge, sgl_flags |
1292                     data_in_sz, data_in_dma);
1293         } else if (data_out_sz) /* WRITE */ {
1294                 sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
1295                     MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
1296                     MPI2_SGE_FLAGS_END_OF_LIST | MPI2_SGE_FLAGS_HOST_TO_IOC);
1297                 sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1298                 ioc->base_add_sg_single(psge, sgl_flags |
1299                     data_out_sz, data_out_dma);
1300         } else if (data_in_sz) /* READ */ {
1301                 sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
1302                     MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
1303                     MPI2_SGE_FLAGS_END_OF_LIST);
1304                 sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1305                 ioc->base_add_sg_single(psge, sgl_flags |
1306                     data_in_sz, data_in_dma);
1307         }
1308 }
1309
1310 /* IEEE format sgls */
1311
1312 /**
1313  * _base_add_sg_single_ieee - add sg element for IEEE format
1314  * @paddr: virtual address for SGE
1315  * @flags: SGE flags
1316  * @chain_offset: number of 128 byte elements from start of segment
1317  * @length: data transfer length
1318  * @dma_addr: Physical address
1319  *
1320  * Return nothing.
1321  */
1322 static void
1323 _base_add_sg_single_ieee(void *paddr, u8 flags, u8 chain_offset, u32 length,
1324         dma_addr_t dma_addr)
1325 {
1326         Mpi25IeeeSgeChain64_t *sgel = paddr;
1327
1328         sgel->Flags = flags;
1329         sgel->NextChainOffset = chain_offset;
1330         sgel->Length = cpu_to_le32(length);
1331         sgel->Address = cpu_to_le64(dma_addr);
1332 }
1333
1334 /**
1335  * _base_build_zero_len_sge_ieee - build zero length sg entry for IEEE format
1336  * @ioc: per adapter object
1337  * @paddr: virtual address for SGE
1338  *
1339  * Create a zero length scatter gather entry to insure the IOCs hardware has
1340  * something to use if the target device goes brain dead and tries
1341  * to send data even when none is asked for.
1342  *
1343  * Return nothing.
1344  */
1345 static void
1346 _base_build_zero_len_sge_ieee(struct MPT3SAS_ADAPTER *ioc, void *paddr)
1347 {
1348         u8 sgl_flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
1349                 MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
1350                 MPI25_IEEE_SGE_FLAGS_END_OF_LIST);
1351         _base_add_sg_single_ieee(paddr, sgl_flags, 0, 0, -1);
1352 }
1353
1354 /**
1355  * _base_build_sg_scmd - main sg creation routine
1356  * @ioc: per adapter object
1357  * @scmd: scsi command
1358  * @smid: system request message index
1359  * Context: none.
1360  *
1361  * The main routine that builds scatter gather table from a given
1362  * scsi request sent via the .queuecommand main handler.
1363  *
1364  * Returns 0 success, anything else error
1365  */
1366 static int
1367 _base_build_sg_scmd(struct MPT3SAS_ADAPTER *ioc,
1368                 struct scsi_cmnd *scmd, u16 smid)
1369 {
1370         Mpi2SCSIIORequest_t *mpi_request;
1371         dma_addr_t chain_dma;
1372         struct scatterlist *sg_scmd;
1373         void *sg_local, *chain;
1374         u32 chain_offset;
1375         u32 chain_length;
1376         u32 chain_flags;
1377         int sges_left;
1378         u32 sges_in_segment;
1379         u32 sgl_flags;
1380         u32 sgl_flags_last_element;
1381         u32 sgl_flags_end_buffer;
1382         struct chain_tracker *chain_req;
1383
1384         mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
1385
1386         /* init scatter gather flags */
1387         sgl_flags = MPI2_SGE_FLAGS_SIMPLE_ELEMENT;
1388         if (scmd->sc_data_direction == DMA_TO_DEVICE)
1389                 sgl_flags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
1390         sgl_flags_last_element = (sgl_flags | MPI2_SGE_FLAGS_LAST_ELEMENT)
1391             << MPI2_SGE_FLAGS_SHIFT;
1392         sgl_flags_end_buffer = (sgl_flags | MPI2_SGE_FLAGS_LAST_ELEMENT |
1393             MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_END_OF_LIST)
1394             << MPI2_SGE_FLAGS_SHIFT;
1395         sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1396
1397         sg_scmd = scsi_sglist(scmd);
1398         sges_left = scsi_dma_map(scmd);
1399         if (sges_left < 0) {
1400                 sdev_printk(KERN_ERR, scmd->device,
1401                  "pci_map_sg failed: request for %d bytes!\n",
1402                  scsi_bufflen(scmd));
1403                 return -ENOMEM;
1404         }
1405
1406         sg_local = &mpi_request->SGL;
1407         sges_in_segment = ioc->max_sges_in_main_message;
1408         if (sges_left <= sges_in_segment)
1409                 goto fill_in_last_segment;
1410
1411         mpi_request->ChainOffset = (offsetof(Mpi2SCSIIORequest_t, SGL) +
1412             (sges_in_segment * ioc->sge_size))/4;
1413
1414         /* fill in main message segment when there is a chain following */
1415         while (sges_in_segment) {
1416                 if (sges_in_segment == 1)
1417                         ioc->base_add_sg_single(sg_local,
1418                             sgl_flags_last_element | sg_dma_len(sg_scmd),
1419                             sg_dma_address(sg_scmd));
1420                 else
1421                         ioc->base_add_sg_single(sg_local, sgl_flags |
1422                             sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
1423                 sg_scmd = sg_next(sg_scmd);
1424                 sg_local += ioc->sge_size;
1425                 sges_left--;
1426                 sges_in_segment--;
1427         }
1428
1429         /* initializing the chain flags and pointers */
1430         chain_flags = MPI2_SGE_FLAGS_CHAIN_ELEMENT << MPI2_SGE_FLAGS_SHIFT;
1431         chain_req = _base_get_chain_buffer_tracker(ioc, smid);
1432         if (!chain_req)
1433                 return -1;
1434         chain = chain_req->chain_buffer;
1435         chain_dma = chain_req->chain_buffer_dma;
1436         do {
1437                 sges_in_segment = (sges_left <=
1438                     ioc->max_sges_in_chain_message) ? sges_left :
1439                     ioc->max_sges_in_chain_message;
1440                 chain_offset = (sges_left == sges_in_segment) ?
1441                     0 : (sges_in_segment * ioc->sge_size)/4;
1442                 chain_length = sges_in_segment * ioc->sge_size;
1443                 if (chain_offset) {
1444                         chain_offset = chain_offset <<
1445                             MPI2_SGE_CHAIN_OFFSET_SHIFT;
1446                         chain_length += ioc->sge_size;
1447                 }
1448                 ioc->base_add_sg_single(sg_local, chain_flags | chain_offset |
1449                     chain_length, chain_dma);
1450                 sg_local = chain;
1451                 if (!chain_offset)
1452                         goto fill_in_last_segment;
1453
1454                 /* fill in chain segments */
1455                 while (sges_in_segment) {
1456                         if (sges_in_segment == 1)
1457                                 ioc->base_add_sg_single(sg_local,
1458                                     sgl_flags_last_element |
1459                                     sg_dma_len(sg_scmd),
1460                                     sg_dma_address(sg_scmd));
1461                         else
1462                                 ioc->base_add_sg_single(sg_local, sgl_flags |
1463                                     sg_dma_len(sg_scmd),
1464                                     sg_dma_address(sg_scmd));
1465                         sg_scmd = sg_next(sg_scmd);
1466                         sg_local += ioc->sge_size;
1467                         sges_left--;
1468                         sges_in_segment--;
1469                 }
1470
1471                 chain_req = _base_get_chain_buffer_tracker(ioc, smid);
1472                 if (!chain_req)
1473                         return -1;
1474                 chain = chain_req->chain_buffer;
1475                 chain_dma = chain_req->chain_buffer_dma;
1476         } while (1);
1477
1478
1479  fill_in_last_segment:
1480
1481         /* fill the last segment */
1482         while (sges_left) {
1483                 if (sges_left == 1)
1484                         ioc->base_add_sg_single(sg_local, sgl_flags_end_buffer |
1485                             sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
1486                 else
1487                         ioc->base_add_sg_single(sg_local, sgl_flags |
1488                             sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
1489                 sg_scmd = sg_next(sg_scmd);
1490                 sg_local += ioc->sge_size;
1491                 sges_left--;
1492         }
1493
1494         return 0;
1495 }
1496
1497 /**
1498  * _base_build_sg_scmd_ieee - main sg creation routine for IEEE format
1499  * @ioc: per adapter object
1500  * @scmd: scsi command
1501  * @smid: system request message index
1502  * Context: none.
1503  *
1504  * The main routine that builds scatter gather table from a given
1505  * scsi request sent via the .queuecommand main handler.
1506  *
1507  * Returns 0 success, anything else error
1508  */
1509 static int
1510 _base_build_sg_scmd_ieee(struct MPT3SAS_ADAPTER *ioc,
1511         struct scsi_cmnd *scmd, u16 smid)
1512 {
1513         Mpi2SCSIIORequest_t *mpi_request;
1514         dma_addr_t chain_dma;
1515         struct scatterlist *sg_scmd;
1516         void *sg_local, *chain;
1517         u32 chain_offset;
1518         u32 chain_length;
1519         int sges_left;
1520         u32 sges_in_segment;
1521         u8 simple_sgl_flags;
1522         u8 simple_sgl_flags_last;
1523         u8 chain_sgl_flags;
1524         struct chain_tracker *chain_req;
1525
1526         mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
1527
1528         /* init scatter gather flags */
1529         simple_sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
1530             MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
1531         simple_sgl_flags_last = simple_sgl_flags |
1532             MPI25_IEEE_SGE_FLAGS_END_OF_LIST;
1533         chain_sgl_flags = MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
1534             MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
1535
1536         sg_scmd = scsi_sglist(scmd);
1537         sges_left = scsi_dma_map(scmd);
1538         if (sges_left < 0) {
1539                 sdev_printk(KERN_ERR, scmd->device,
1540                         "pci_map_sg failed: request for %d bytes!\n",
1541                         scsi_bufflen(scmd));
1542                 return -ENOMEM;
1543         }
1544
1545         sg_local = &mpi_request->SGL;
1546         sges_in_segment = (ioc->request_sz -
1547             offsetof(Mpi2SCSIIORequest_t, SGL))/ioc->sge_size_ieee;
1548         if (sges_left <= sges_in_segment)
1549                 goto fill_in_last_segment;
1550
1551         mpi_request->ChainOffset = (sges_in_segment - 1 /* chain element */) +
1552             (offsetof(Mpi2SCSIIORequest_t, SGL)/ioc->sge_size_ieee);
1553
1554         /* fill in main message segment when there is a chain following */
1555         while (sges_in_segment > 1) {
1556                 _base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
1557                     sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
1558                 sg_scmd = sg_next(sg_scmd);
1559                 sg_local += ioc->sge_size_ieee;
1560                 sges_left--;
1561                 sges_in_segment--;
1562         }
1563
1564         /* initializing the pointers */
1565         chain_req = _base_get_chain_buffer_tracker(ioc, smid);
1566         if (!chain_req)
1567                 return -1;
1568         chain = chain_req->chain_buffer;
1569         chain_dma = chain_req->chain_buffer_dma;
1570         do {
1571                 sges_in_segment = (sges_left <=
1572                     ioc->max_sges_in_chain_message) ? sges_left :
1573                     ioc->max_sges_in_chain_message;
1574                 chain_offset = (sges_left == sges_in_segment) ?
1575                     0 : sges_in_segment;
1576                 chain_length = sges_in_segment * ioc->sge_size_ieee;
1577                 if (chain_offset)
1578                         chain_length += ioc->sge_size_ieee;
1579                 _base_add_sg_single_ieee(sg_local, chain_sgl_flags,
1580                     chain_offset, chain_length, chain_dma);
1581
1582                 sg_local = chain;
1583                 if (!chain_offset)
1584                         goto fill_in_last_segment;
1585
1586                 /* fill in chain segments */
1587                 while (sges_in_segment) {
1588                         _base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
1589                             sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
1590                         sg_scmd = sg_next(sg_scmd);
1591                         sg_local += ioc->sge_size_ieee;
1592                         sges_left--;
1593                         sges_in_segment--;
1594                 }
1595
1596                 chain_req = _base_get_chain_buffer_tracker(ioc, smid);
1597                 if (!chain_req)
1598                         return -1;
1599                 chain = chain_req->chain_buffer;
1600                 chain_dma = chain_req->chain_buffer_dma;
1601         } while (1);
1602
1603
1604  fill_in_last_segment:
1605
1606         /* fill the last segment */
1607         while (sges_left > 0) {
1608                 if (sges_left == 1)
1609                         _base_add_sg_single_ieee(sg_local,
1610                             simple_sgl_flags_last, 0, sg_dma_len(sg_scmd),
1611                             sg_dma_address(sg_scmd));
1612                 else
1613                         _base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
1614                             sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
1615                 sg_scmd = sg_next(sg_scmd);
1616                 sg_local += ioc->sge_size_ieee;
1617                 sges_left--;
1618         }
1619
1620         return 0;
1621 }
1622
1623 /**
1624  * _base_build_sg_ieee - build generic sg for IEEE format
1625  * @ioc: per adapter object
1626  * @psge: virtual address for SGE
1627  * @data_out_dma: physical address for WRITES
1628  * @data_out_sz: data xfer size for WRITES
1629  * @data_in_dma: physical address for READS
1630  * @data_in_sz: data xfer size for READS
1631  *
1632  * Return nothing.
1633  */
1634 static void
1635 _base_build_sg_ieee(struct MPT3SAS_ADAPTER *ioc, void *psge,
1636         dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
1637         size_t data_in_sz)
1638 {
1639         u8 sgl_flags;
1640
1641         if (!data_out_sz && !data_in_sz) {
1642                 _base_build_zero_len_sge_ieee(ioc, psge);
1643                 return;
1644         }
1645
1646         if (data_out_sz && data_in_sz) {
1647                 /* WRITE sgel first */
1648                 sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
1649                     MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
1650                 _base_add_sg_single_ieee(psge, sgl_flags, 0, data_out_sz,
1651                     data_out_dma);
1652
1653                 /* incr sgel */
1654                 psge += ioc->sge_size_ieee;
1655
1656                 /* READ sgel last */
1657                 sgl_flags |= MPI25_IEEE_SGE_FLAGS_END_OF_LIST;
1658                 _base_add_sg_single_ieee(psge, sgl_flags, 0, data_in_sz,
1659                     data_in_dma);
1660         } else if (data_out_sz) /* WRITE */ {
1661                 sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
1662                     MPI25_IEEE_SGE_FLAGS_END_OF_LIST |
1663                     MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
1664                 _base_add_sg_single_ieee(psge, sgl_flags, 0, data_out_sz,
1665                     data_out_dma);
1666         } else if (data_in_sz) /* READ */ {
1667                 sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
1668                     MPI25_IEEE_SGE_FLAGS_END_OF_LIST |
1669                     MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
1670                 _base_add_sg_single_ieee(psge, sgl_flags, 0, data_in_sz,
1671                     data_in_dma);
1672         }
1673 }
1674
1675 #define convert_to_kb(x) ((x) << (PAGE_SHIFT - 10))
1676
1677 /**
1678  * _base_config_dma_addressing - set dma addressing
1679  * @ioc: per adapter object
1680  * @pdev: PCI device struct
1681  *
1682  * Returns 0 for success, non-zero for failure.
1683  */
1684 static int
1685 _base_config_dma_addressing(struct MPT3SAS_ADAPTER *ioc, struct pci_dev *pdev)
1686 {
1687         struct sysinfo s;
1688         u64 consistent_dma_mask;
1689
1690         if (ioc->dma_mask)
1691                 consistent_dma_mask = DMA_BIT_MASK(64);
1692         else
1693                 consistent_dma_mask = DMA_BIT_MASK(32);
1694
1695         if (sizeof(dma_addr_t) > 4) {
1696                 const uint64_t required_mask =
1697                     dma_get_required_mask(&pdev->dev);
1698                 if ((required_mask > DMA_BIT_MASK(32)) &&
1699                     !pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) &&
1700                     !pci_set_consistent_dma_mask(pdev, consistent_dma_mask)) {
1701                         ioc->base_add_sg_single = &_base_add_sg_single_64;
1702                         ioc->sge_size = sizeof(Mpi2SGESimple64_t);
1703                         ioc->dma_mask = 64;
1704                         goto out;
1705                 }
1706         }
1707
1708         if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(32))
1709             && !pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) {
1710                 ioc->base_add_sg_single = &_base_add_sg_single_32;
1711                 ioc->sge_size = sizeof(Mpi2SGESimple32_t);
1712                 ioc->dma_mask = 32;
1713         } else
1714                 return -ENODEV;
1715
1716  out:
1717         si_meminfo(&s);
1718         pr_info(MPT3SAS_FMT
1719                 "%d BIT PCI BUS DMA ADDRESSING SUPPORTED, total mem (%ld kB)\n",
1720                 ioc->name, ioc->dma_mask, convert_to_kb(s.totalram));
1721
1722         return 0;
1723 }
1724
1725 static int
1726 _base_change_consistent_dma_mask(struct MPT3SAS_ADAPTER *ioc,
1727                                       struct pci_dev *pdev)
1728 {
1729         if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64))) {
1730                 if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)))
1731                         return -ENODEV;
1732         }
1733         return 0;
1734 }
1735
1736 /**
1737  * _base_check_enable_msix - checks MSIX capabable.
1738  * @ioc: per adapter object
1739  *
1740  * Check to see if card is capable of MSIX, and set number
1741  * of available msix vectors
1742  */
1743 static int
1744 _base_check_enable_msix(struct MPT3SAS_ADAPTER *ioc)
1745 {
1746         int base;
1747         u16 message_control;
1748
1749         /* Check whether controller SAS2008 B0 controller,
1750          * if it is SAS2008 B0 controller use IO-APIC instead of MSIX
1751          */
1752         if (ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2008 &&
1753             ioc->pdev->revision == SAS2_PCI_DEVICE_B0_REVISION) {
1754                 return -EINVAL;
1755         }
1756
1757         base = pci_find_capability(ioc->pdev, PCI_CAP_ID_MSIX);
1758         if (!base) {
1759                 dfailprintk(ioc, pr_info(MPT3SAS_FMT "msix not supported\n",
1760                         ioc->name));
1761                 return -EINVAL;
1762         }
1763
1764         /* get msix vector count */
1765         /* NUMA_IO not supported for older controllers */
1766         if (ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2004 ||
1767             ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2008 ||
1768             ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_1 ||
1769             ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_2 ||
1770             ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_3 ||
1771             ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2116_1 ||
1772             ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2116_2)
1773                 ioc->msix_vector_count = 1;
1774         else {
1775                 pci_read_config_word(ioc->pdev, base + 2, &message_control);
1776                 ioc->msix_vector_count = (message_control & 0x3FF) + 1;
1777         }
1778         dinitprintk(ioc, pr_info(MPT3SAS_FMT
1779                 "msix is supported, vector_count(%d)\n",
1780                 ioc->name, ioc->msix_vector_count));
1781         return 0;
1782 }
1783
1784 /**
1785  * _base_free_irq - free irq
1786  * @ioc: per adapter object
1787  *
1788  * Freeing respective reply_queue from the list.
1789  */
1790 static void
1791 _base_free_irq(struct MPT3SAS_ADAPTER *ioc)
1792 {
1793         struct adapter_reply_queue *reply_q, *next;
1794
1795         if (list_empty(&ioc->reply_queue_list))
1796                 return;
1797
1798         list_for_each_entry_safe(reply_q, next, &ioc->reply_queue_list, list) {
1799                 list_del(&reply_q->list);
1800                 irq_set_affinity_hint(reply_q->vector, NULL);
1801                 free_cpumask_var(reply_q->affinity_hint);
1802                 synchronize_irq(reply_q->vector);
1803                 free_irq(reply_q->vector, reply_q);
1804                 kfree(reply_q);
1805         }
1806 }
1807
1808 /**
1809  * _base_request_irq - request irq
1810  * @ioc: per adapter object
1811  * @index: msix index into vector table
1812  * @vector: irq vector
1813  *
1814  * Inserting respective reply_queue into the list.
1815  */
1816 static int
1817 _base_request_irq(struct MPT3SAS_ADAPTER *ioc, u8 index, u32 vector)
1818 {
1819         struct adapter_reply_queue *reply_q;
1820         int r;
1821
1822         reply_q =  kzalloc(sizeof(struct adapter_reply_queue), GFP_KERNEL);
1823         if (!reply_q) {
1824                 pr_err(MPT3SAS_FMT "unable to allocate memory %d!\n",
1825                     ioc->name, (int)sizeof(struct adapter_reply_queue));
1826                 return -ENOMEM;
1827         }
1828         reply_q->ioc = ioc;
1829         reply_q->msix_index = index;
1830         reply_q->vector = vector;
1831
1832         if (!alloc_cpumask_var(&reply_q->affinity_hint, GFP_KERNEL))
1833                 return -ENOMEM;
1834         cpumask_clear(reply_q->affinity_hint);
1835
1836         atomic_set(&reply_q->busy, 0);
1837         if (ioc->msix_enable)
1838                 snprintf(reply_q->name, MPT_NAME_LENGTH, "%s%d-msix%d",
1839                     ioc->driver_name, ioc->id, index);
1840         else
1841                 snprintf(reply_q->name, MPT_NAME_LENGTH, "%s%d",
1842                     ioc->driver_name, ioc->id);
1843         r = request_irq(vector, _base_interrupt, IRQF_SHARED, reply_q->name,
1844             reply_q);
1845         if (r) {
1846                 pr_err(MPT3SAS_FMT "unable to allocate interrupt %d!\n",
1847                     reply_q->name, vector);
1848                 kfree(reply_q);
1849                 return -EBUSY;
1850         }
1851
1852         INIT_LIST_HEAD(&reply_q->list);
1853         list_add_tail(&reply_q->list, &ioc->reply_queue_list);
1854         return 0;
1855 }
1856
1857 /**
1858  * _base_assign_reply_queues - assigning msix index for each cpu
1859  * @ioc: per adapter object
1860  *
1861  * The enduser would need to set the affinity via /proc/irq/#/smp_affinity
1862  *
1863  * It would nice if we could call irq_set_affinity, however it is not
1864  * an exported symbol
1865  */
1866 static void
1867 _base_assign_reply_queues(struct MPT3SAS_ADAPTER *ioc)
1868 {
1869         unsigned int cpu, nr_cpus, nr_msix, index = 0;
1870         struct adapter_reply_queue *reply_q;
1871
1872         if (!_base_is_controller_msix_enabled(ioc))
1873                 return;
1874
1875         memset(ioc->cpu_msix_table, 0, ioc->cpu_msix_table_sz);
1876
1877         nr_cpus = num_online_cpus();
1878         nr_msix = ioc->reply_queue_count = min(ioc->reply_queue_count,
1879                                                ioc->facts.MaxMSIxVectors);
1880         if (!nr_msix)
1881                 return;
1882
1883         cpu = cpumask_first(cpu_online_mask);
1884
1885         list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
1886
1887                 unsigned int i, group = nr_cpus / nr_msix;
1888
1889                 if (cpu >= nr_cpus)
1890                         break;
1891
1892                 if (index < nr_cpus % nr_msix)
1893                         group++;
1894
1895                 for (i = 0 ; i < group ; i++) {
1896                         ioc->cpu_msix_table[cpu] = index;
1897                         cpumask_or(reply_q->affinity_hint,
1898                                    reply_q->affinity_hint, get_cpu_mask(cpu));
1899                         cpu = cpumask_next(cpu, cpu_online_mask);
1900                 }
1901
1902                 if (irq_set_affinity_hint(reply_q->vector,
1903                                            reply_q->affinity_hint))
1904                         dinitprintk(ioc, pr_info(MPT3SAS_FMT
1905                             "error setting affinity hint for irq vector %d\n",
1906                             ioc->name, reply_q->vector));
1907                 index++;
1908         }
1909 }
1910
1911 /**
1912  * _base_disable_msix - disables msix
1913  * @ioc: per adapter object
1914  *
1915  */
1916 static void
1917 _base_disable_msix(struct MPT3SAS_ADAPTER *ioc)
1918 {
1919         if (!ioc->msix_enable)
1920                 return;
1921         pci_disable_msix(ioc->pdev);
1922         ioc->msix_enable = 0;
1923 }
1924
1925 /**
1926  * _base_enable_msix - enables msix, failback to io_apic
1927  * @ioc: per adapter object
1928  *
1929  */
1930 static int
1931 _base_enable_msix(struct MPT3SAS_ADAPTER *ioc)
1932 {
1933         struct msix_entry *entries, *a;
1934         int r;
1935         int i;
1936         u8 try_msix = 0;
1937
1938         if (msix_disable == -1 || msix_disable == 0)
1939                 try_msix = 1;
1940
1941         if (!try_msix)
1942                 goto try_ioapic;
1943
1944         if (_base_check_enable_msix(ioc) != 0)
1945                 goto try_ioapic;
1946
1947         ioc->reply_queue_count = min_t(int, ioc->cpu_count,
1948             ioc->msix_vector_count);
1949
1950         printk(MPT3SAS_FMT "MSI-X vectors supported: %d, no of cores"
1951           ": %d, max_msix_vectors: %d\n", ioc->name, ioc->msix_vector_count,
1952           ioc->cpu_count, max_msix_vectors);
1953
1954         if (!ioc->rdpq_array_enable && max_msix_vectors == -1)
1955                 max_msix_vectors = 8;
1956
1957         if (max_msix_vectors > 0) {
1958                 ioc->reply_queue_count = min_t(int, max_msix_vectors,
1959                         ioc->reply_queue_count);
1960                 ioc->msix_vector_count = ioc->reply_queue_count;
1961         } else if (max_msix_vectors == 0)
1962                 goto try_ioapic;
1963
1964         entries = kcalloc(ioc->reply_queue_count, sizeof(struct msix_entry),
1965             GFP_KERNEL);
1966         if (!entries) {
1967                 dfailprintk(ioc, pr_info(MPT3SAS_FMT
1968                         "kcalloc failed @ at %s:%d/%s() !!!\n",
1969                         ioc->name, __FILE__, __LINE__, __func__));
1970                 goto try_ioapic;
1971         }
1972
1973         for (i = 0, a = entries; i < ioc->reply_queue_count; i++, a++)
1974                 a->entry = i;
1975
1976         r = pci_enable_msix_exact(ioc->pdev, entries, ioc->reply_queue_count);
1977         if (r) {
1978                 dfailprintk(ioc, pr_info(MPT3SAS_FMT
1979                         "pci_enable_msix_exact failed (r=%d) !!!\n",
1980                         ioc->name, r));
1981                 kfree(entries);
1982                 goto try_ioapic;
1983         }
1984
1985         ioc->msix_enable = 1;
1986         for (i = 0, a = entries; i < ioc->reply_queue_count; i++, a++) {
1987                 r = _base_request_irq(ioc, i, a->vector);
1988                 if (r) {
1989                         _base_free_irq(ioc);
1990                         _base_disable_msix(ioc);
1991                         kfree(entries);
1992                         goto try_ioapic;
1993                 }
1994         }
1995
1996         kfree(entries);
1997         return 0;
1998
1999 /* failback to io_apic interrupt routing */
2000  try_ioapic:
2001
2002         ioc->reply_queue_count = 1;
2003         r = _base_request_irq(ioc, 0, ioc->pdev->irq);
2004
2005         return r;
2006 }
2007
2008 /**
2009  * mpt3sas_base_unmap_resources - free controller resources
2010  * @ioc: per adapter object
2011  */
2012 void
2013 mpt3sas_base_unmap_resources(struct MPT3SAS_ADAPTER *ioc)
2014 {
2015         struct pci_dev *pdev = ioc->pdev;
2016
2017         dexitprintk(ioc, printk(MPT3SAS_FMT "%s\n",
2018                 ioc->name, __func__));
2019
2020         _base_free_irq(ioc);
2021         _base_disable_msix(ioc);
2022
2023         if (ioc->msix96_vector)
2024                 kfree(ioc->replyPostRegisterIndex);
2025
2026         if (ioc->chip_phys) {
2027                 iounmap(ioc->chip);
2028                 ioc->chip_phys = 0;
2029         }
2030
2031         if (pci_is_enabled(pdev)) {
2032                 pci_release_selected_regions(ioc->pdev, ioc->bars);
2033                 pci_disable_pcie_error_reporting(pdev);
2034                 pci_disable_device(pdev);
2035         }
2036 }
2037
2038 /**
2039  * mpt3sas_base_map_resources - map in controller resources (io/irq/memap)
2040  * @ioc: per adapter object
2041  *
2042  * Returns 0 for success, non-zero for failure.
2043  */
2044 int
2045 mpt3sas_base_map_resources(struct MPT3SAS_ADAPTER *ioc)
2046 {
2047         struct pci_dev *pdev = ioc->pdev;
2048         u32 memap_sz;
2049         u32 pio_sz;
2050         int i, r = 0;
2051         u64 pio_chip = 0;
2052         u64 chip_phys = 0;
2053         struct adapter_reply_queue *reply_q;
2054
2055         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n",
2056             ioc->name, __func__));
2057
2058         ioc->bars = pci_select_bars(pdev, IORESOURCE_MEM);
2059         if (pci_enable_device_mem(pdev)) {
2060                 pr_warn(MPT3SAS_FMT "pci_enable_device_mem: failed\n",
2061                         ioc->name);
2062                 ioc->bars = 0;
2063                 return -ENODEV;
2064         }
2065
2066
2067         if (pci_request_selected_regions(pdev, ioc->bars,
2068             ioc->driver_name)) {
2069                 pr_warn(MPT3SAS_FMT "pci_request_selected_regions: failed\n",
2070                         ioc->name);
2071                 ioc->bars = 0;
2072                 r = -ENODEV;
2073                 goto out_fail;
2074         }
2075
2076 /* AER (Advanced Error Reporting) hooks */
2077         pci_enable_pcie_error_reporting(pdev);
2078
2079         pci_set_master(pdev);
2080
2081
2082         if (_base_config_dma_addressing(ioc, pdev) != 0) {
2083                 pr_warn(MPT3SAS_FMT "no suitable DMA mask for %s\n",
2084                     ioc->name, pci_name(pdev));
2085                 r = -ENODEV;
2086                 goto out_fail;
2087         }
2088
2089         for (i = 0, memap_sz = 0, pio_sz = 0; (i < DEVICE_COUNT_RESOURCE) &&
2090              (!memap_sz || !pio_sz); i++) {
2091                 if (pci_resource_flags(pdev, i) & IORESOURCE_IO) {
2092                         if (pio_sz)
2093                                 continue;
2094                         pio_chip = (u64)pci_resource_start(pdev, i);
2095                         pio_sz = pci_resource_len(pdev, i);
2096                 } else if (pci_resource_flags(pdev, i) & IORESOURCE_MEM) {
2097                         if (memap_sz)
2098                                 continue;
2099                         ioc->chip_phys = pci_resource_start(pdev, i);
2100                         chip_phys = (u64)ioc->chip_phys;
2101                         memap_sz = pci_resource_len(pdev, i);
2102                         ioc->chip = ioremap(ioc->chip_phys, memap_sz);
2103                 }
2104         }
2105
2106         if (ioc->chip == NULL) {
2107                 pr_err(MPT3SAS_FMT "unable to map adapter memory! "
2108                         " or resource not found\n", ioc->name);
2109                 r = -EINVAL;
2110                 goto out_fail;
2111         }
2112
2113         _base_mask_interrupts(ioc);
2114
2115         r = _base_get_ioc_facts(ioc, CAN_SLEEP);
2116         if (r)
2117                 goto out_fail;
2118
2119         if (!ioc->rdpq_array_enable_assigned) {
2120                 ioc->rdpq_array_enable = ioc->rdpq_array_capable;
2121                 ioc->rdpq_array_enable_assigned = 1;
2122         }
2123
2124         r = _base_enable_msix(ioc);
2125         if (r)
2126                 goto out_fail;
2127
2128         /* Use the Combined reply queue feature only for SAS3 C0 & higher
2129          * revision HBAs and also only when reply queue count is greater than 8
2130          */
2131         if (ioc->msix96_vector && ioc->reply_queue_count > 8) {
2132                 /* Determine the Supplemental Reply Post Host Index Registers
2133                  * Addresse. Supplemental Reply Post Host Index Registers
2134                  * starts at offset MPI25_SUP_REPLY_POST_HOST_INDEX_OFFSET and
2135                  * each register is at offset bytes of
2136                  * MPT3_SUP_REPLY_POST_HOST_INDEX_REG_OFFSET from previous one.
2137                  */
2138                 ioc->replyPostRegisterIndex = kcalloc(
2139                      MPT3_SUP_REPLY_POST_HOST_INDEX_REG_COUNT,
2140                      sizeof(resource_size_t *), GFP_KERNEL);
2141                 if (!ioc->replyPostRegisterIndex) {
2142                         dfailprintk(ioc, printk(MPT3SAS_FMT
2143                         "allocation for reply Post Register Index failed!!!\n",
2144                                                                    ioc->name));
2145                         r = -ENOMEM;
2146                         goto out_fail;
2147                 }
2148
2149                 for (i = 0; i < MPT3_SUP_REPLY_POST_HOST_INDEX_REG_COUNT; i++) {
2150                         ioc->replyPostRegisterIndex[i] = (resource_size_t *)
2151                              ((u8 *)&ioc->chip->Doorbell +
2152                              MPI25_SUP_REPLY_POST_HOST_INDEX_OFFSET +
2153                              (i * MPT3_SUP_REPLY_POST_HOST_INDEX_REG_OFFSET));
2154                 }
2155         } else
2156                 ioc->msix96_vector = 0;
2157
2158         list_for_each_entry(reply_q, &ioc->reply_queue_list, list)
2159                 pr_info(MPT3SAS_FMT "%s: IRQ %d\n",
2160                     reply_q->name,  ((ioc->msix_enable) ? "PCI-MSI-X enabled" :
2161                     "IO-APIC enabled"), reply_q->vector);
2162
2163         pr_info(MPT3SAS_FMT "iomem(0x%016llx), mapped(0x%p), size(%d)\n",
2164             ioc->name, (unsigned long long)chip_phys, ioc->chip, memap_sz);
2165         pr_info(MPT3SAS_FMT "ioport(0x%016llx), size(%d)\n",
2166             ioc->name, (unsigned long long)pio_chip, pio_sz);
2167
2168         /* Save PCI configuration state for recovery from PCI AER/EEH errors */
2169         pci_save_state(pdev);
2170         return 0;
2171
2172  out_fail:
2173         mpt3sas_base_unmap_resources(ioc);
2174         return r;
2175 }
2176
2177 /**
2178  * mpt3sas_base_get_msg_frame - obtain request mf pointer
2179  * @ioc: per adapter object
2180  * @smid: system request message index(smid zero is invalid)
2181  *
2182  * Returns virt pointer to message frame.
2183  */
2184 void *
2185 mpt3sas_base_get_msg_frame(struct MPT3SAS_ADAPTER *ioc, u16 smid)
2186 {
2187         return (void *)(ioc->request + (smid * ioc->request_sz));
2188 }
2189
2190 /**
2191  * mpt3sas_base_get_sense_buffer - obtain a sense buffer virt addr
2192  * @ioc: per adapter object
2193  * @smid: system request message index
2194  *
2195  * Returns virt pointer to sense buffer.
2196  */
2197 void *
2198 mpt3sas_base_get_sense_buffer(struct MPT3SAS_ADAPTER *ioc, u16 smid)
2199 {
2200         return (void *)(ioc->sense + ((smid - 1) * SCSI_SENSE_BUFFERSIZE));
2201 }
2202
2203 /**
2204  * mpt3sas_base_get_sense_buffer_dma - obtain a sense buffer dma addr
2205  * @ioc: per adapter object
2206  * @smid: system request message index
2207  *
2208  * Returns phys pointer to the low 32bit address of the sense buffer.
2209  */
2210 __le32
2211 mpt3sas_base_get_sense_buffer_dma(struct MPT3SAS_ADAPTER *ioc, u16 smid)
2212 {
2213         return cpu_to_le32(ioc->sense_dma + ((smid - 1) *
2214             SCSI_SENSE_BUFFERSIZE));
2215 }
2216
2217 /**
2218  * mpt3sas_base_get_reply_virt_addr - obtain reply frames virt address
2219  * @ioc: per adapter object
2220  * @phys_addr: lower 32 physical addr of the reply
2221  *
2222  * Converts 32bit lower physical addr into a virt address.
2223  */
2224 void *
2225 mpt3sas_base_get_reply_virt_addr(struct MPT3SAS_ADAPTER *ioc, u32 phys_addr)
2226 {
2227         if (!phys_addr)
2228                 return NULL;
2229         return ioc->reply + (phys_addr - (u32)ioc->reply_dma);
2230 }
2231
2232 /**
2233  * mpt3sas_base_get_smid - obtain a free smid from internal queue
2234  * @ioc: per adapter object
2235  * @cb_idx: callback index
2236  *
2237  * Returns smid (zero is invalid)
2238  */
2239 u16
2240 mpt3sas_base_get_smid(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx)
2241 {
2242         unsigned long flags;
2243         struct request_tracker *request;
2244         u16 smid;
2245
2246         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
2247         if (list_empty(&ioc->internal_free_list)) {
2248                 spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
2249                 pr_err(MPT3SAS_FMT "%s: smid not available\n",
2250                     ioc->name, __func__);
2251                 return 0;
2252         }
2253
2254         request = list_entry(ioc->internal_free_list.next,
2255             struct request_tracker, tracker_list);
2256         request->cb_idx = cb_idx;
2257         smid = request->smid;
2258         list_del(&request->tracker_list);
2259         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
2260         return smid;
2261 }
2262
2263 /**
2264  * mpt3sas_base_get_smid_scsiio - obtain a free smid from scsiio queue
2265  * @ioc: per adapter object
2266  * @cb_idx: callback index
2267  * @scmd: pointer to scsi command object
2268  *
2269  * Returns smid (zero is invalid)
2270  */
2271 u16
2272 mpt3sas_base_get_smid_scsiio(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx,
2273         struct scsi_cmnd *scmd)
2274 {
2275         unsigned long flags;
2276         struct scsiio_tracker *request;
2277         u16 smid;
2278
2279         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
2280         if (list_empty(&ioc->free_list)) {
2281                 spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
2282                 pr_err(MPT3SAS_FMT "%s: smid not available\n",
2283                     ioc->name, __func__);
2284                 return 0;
2285         }
2286
2287         request = list_entry(ioc->free_list.next,
2288             struct scsiio_tracker, tracker_list);
2289         request->scmd = scmd;
2290         request->cb_idx = cb_idx;
2291         smid = request->smid;
2292         list_del(&request->tracker_list);
2293         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
2294         return smid;
2295 }
2296
2297 /**
2298  * mpt3sas_base_get_smid_hpr - obtain a free smid from hi-priority queue
2299  * @ioc: per adapter object
2300  * @cb_idx: callback index
2301  *
2302  * Returns smid (zero is invalid)
2303  */
2304 u16
2305 mpt3sas_base_get_smid_hpr(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx)
2306 {
2307         unsigned long flags;
2308         struct request_tracker *request;
2309         u16 smid;
2310
2311         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
2312         if (list_empty(&ioc->hpr_free_list)) {
2313                 spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
2314                 return 0;
2315         }
2316
2317         request = list_entry(ioc->hpr_free_list.next,
2318             struct request_tracker, tracker_list);
2319         request->cb_idx = cb_idx;
2320         smid = request->smid;
2321         list_del(&request->tracker_list);
2322         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
2323         return smid;
2324 }
2325
2326 /**
2327  * mpt3sas_base_free_smid - put smid back on free_list
2328  * @ioc: per adapter object
2329  * @smid: system request message index
2330  *
2331  * Return nothing.
2332  */
2333 void
2334 mpt3sas_base_free_smid(struct MPT3SAS_ADAPTER *ioc, u16 smid)
2335 {
2336         unsigned long flags;
2337         int i;
2338         struct chain_tracker *chain_req, *next;
2339
2340         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
2341         if (smid < ioc->hi_priority_smid) {
2342                 /* scsiio queue */
2343                 i = smid - 1;
2344                 if (!list_empty(&ioc->scsi_lookup[i].chain_list)) {
2345                         list_for_each_entry_safe(chain_req, next,
2346                             &ioc->scsi_lookup[i].chain_list, tracker_list) {
2347                                 list_del_init(&chain_req->tracker_list);
2348                                 list_add(&chain_req->tracker_list,
2349                                     &ioc->free_chain_list);
2350                         }
2351                 }
2352                 ioc->scsi_lookup[i].cb_idx = 0xFF;
2353                 ioc->scsi_lookup[i].scmd = NULL;
2354                 ioc->scsi_lookup[i].direct_io = 0;
2355                 list_add(&ioc->scsi_lookup[i].tracker_list, &ioc->free_list);
2356                 spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
2357
2358                 /*
2359                  * See _wait_for_commands_to_complete() call with regards
2360                  * to this code.
2361                  */
2362                 if (ioc->shost_recovery && ioc->pending_io_count) {
2363                         if (ioc->pending_io_count == 1)
2364                                 wake_up(&ioc->reset_wq);
2365                         ioc->pending_io_count--;
2366                 }
2367                 return;
2368         } else if (smid < ioc->internal_smid) {
2369                 /* hi-priority */
2370                 i = smid - ioc->hi_priority_smid;
2371                 ioc->hpr_lookup[i].cb_idx = 0xFF;
2372                 list_add(&ioc->hpr_lookup[i].tracker_list, &ioc->hpr_free_list);
2373         } else if (smid <= ioc->hba_queue_depth) {
2374                 /* internal queue */
2375                 i = smid - ioc->internal_smid;
2376                 ioc->internal_lookup[i].cb_idx = 0xFF;
2377                 list_add(&ioc->internal_lookup[i].tracker_list,
2378                     &ioc->internal_free_list);
2379         }
2380         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
2381 }
2382
2383 /**
2384  * _base_writeq - 64 bit write to MMIO
2385  * @ioc: per adapter object
2386  * @b: data payload
2387  * @addr: address in MMIO space
2388  * @writeq_lock: spin lock
2389  *
2390  * Glue for handling an atomic 64 bit word to MMIO. This special handling takes
2391  * care of 32 bit environment where its not quarenteed to send the entire word
2392  * in one transfer.
2393  */
2394 #if defined(writeq) && defined(CONFIG_64BIT)
2395 static inline void
2396 _base_writeq(__u64 b, volatile void __iomem *addr, spinlock_t *writeq_lock)
2397 {
2398         writeq(cpu_to_le64(b), addr);
2399 }
2400 #else
2401 static inline void
2402 _base_writeq(__u64 b, volatile void __iomem *addr, spinlock_t *writeq_lock)
2403 {
2404         unsigned long flags;
2405         __u64 data_out = cpu_to_le64(b);
2406
2407         spin_lock_irqsave(writeq_lock, flags);
2408         writel((u32)(data_out), addr);
2409         writel((u32)(data_out >> 32), (addr + 4));
2410         spin_unlock_irqrestore(writeq_lock, flags);
2411 }
2412 #endif
2413
2414 static inline u8
2415 _base_get_msix_index(struct MPT3SAS_ADAPTER *ioc)
2416 {
2417         return ioc->cpu_msix_table[raw_smp_processor_id()];
2418 }
2419
2420 /**
2421  * mpt3sas_base_put_smid_scsi_io - send SCSI_IO request to firmware
2422  * @ioc: per adapter object
2423  * @smid: system request message index
2424  * @handle: device handle
2425  *
2426  * Return nothing.
2427  */
2428 void
2429 mpt3sas_base_put_smid_scsi_io(struct MPT3SAS_ADAPTER *ioc, u16 smid, u16 handle)
2430 {
2431         Mpi2RequestDescriptorUnion_t descriptor;
2432         u64 *request = (u64 *)&descriptor;
2433
2434
2435         descriptor.SCSIIO.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
2436         descriptor.SCSIIO.MSIxIndex =  _base_get_msix_index(ioc);
2437         descriptor.SCSIIO.SMID = cpu_to_le16(smid);
2438         descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
2439         descriptor.SCSIIO.LMID = 0;
2440         _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
2441             &ioc->scsi_lookup_lock);
2442 }
2443
2444 /**
2445  * mpt3sas_base_put_smid_fast_path - send fast path request to firmware
2446  * @ioc: per adapter object
2447  * @smid: system request message index
2448  * @handle: device handle
2449  *
2450  * Return nothing.
2451  */
2452 void
2453 mpt3sas_base_put_smid_fast_path(struct MPT3SAS_ADAPTER *ioc, u16 smid,
2454         u16 handle)
2455 {
2456         Mpi2RequestDescriptorUnion_t descriptor;
2457         u64 *request = (u64 *)&descriptor;
2458
2459         descriptor.SCSIIO.RequestFlags =
2460             MPI25_REQ_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO;
2461         descriptor.SCSIIO.MSIxIndex = _base_get_msix_index(ioc);
2462         descriptor.SCSIIO.SMID = cpu_to_le16(smid);
2463         descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
2464         descriptor.SCSIIO.LMID = 0;
2465         _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
2466             &ioc->scsi_lookup_lock);
2467 }
2468
2469 /**
2470  * mpt3sas_base_put_smid_hi_priority - send Task Managment request to firmware
2471  * @ioc: per adapter object
2472  * @smid: system request message index
2473  *
2474  * Return nothing.
2475  */
2476 void
2477 mpt3sas_base_put_smid_hi_priority(struct MPT3SAS_ADAPTER *ioc, u16 smid)
2478 {
2479         Mpi2RequestDescriptorUnion_t descriptor;
2480         u64 *request = (u64 *)&descriptor;
2481
2482         descriptor.HighPriority.RequestFlags =
2483             MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY;
2484         descriptor.HighPriority.MSIxIndex =  0;
2485         descriptor.HighPriority.SMID = cpu_to_le16(smid);
2486         descriptor.HighPriority.LMID = 0;
2487         descriptor.HighPriority.Reserved1 = 0;
2488         _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
2489             &ioc->scsi_lookup_lock);
2490 }
2491
2492 /**
2493  * mpt3sas_base_put_smid_default - Default, primarily used for config pages
2494  * @ioc: per adapter object
2495  * @smid: system request message index
2496  *
2497  * Return nothing.
2498  */
2499 void
2500 mpt3sas_base_put_smid_default(struct MPT3SAS_ADAPTER *ioc, u16 smid)
2501 {
2502         Mpi2RequestDescriptorUnion_t descriptor;
2503         u64 *request = (u64 *)&descriptor;
2504
2505         descriptor.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2506         descriptor.Default.MSIxIndex =  _base_get_msix_index(ioc);
2507         descriptor.Default.SMID = cpu_to_le16(smid);
2508         descriptor.Default.LMID = 0;
2509         descriptor.Default.DescriptorTypeDependent = 0;
2510         _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
2511             &ioc->scsi_lookup_lock);
2512 }
2513
2514 /**
2515  * _base_display_OEMs_branding - Display branding string
2516  * @ioc: per adapter object
2517  *
2518  * Return nothing.
2519  */
2520 static void
2521 _base_display_OEMs_branding(struct MPT3SAS_ADAPTER *ioc)
2522 {
2523         if (ioc->pdev->subsystem_vendor != PCI_VENDOR_ID_INTEL)
2524                 return;
2525
2526         switch (ioc->pdev->subsystem_vendor) {
2527         case PCI_VENDOR_ID_INTEL:
2528                 switch (ioc->pdev->device) {
2529                 case MPI2_MFGPAGE_DEVID_SAS2008:
2530                         switch (ioc->pdev->subsystem_device) {
2531                         case MPT2SAS_INTEL_RMS2LL080_SSDID:
2532                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2533                                     MPT2SAS_INTEL_RMS2LL080_BRANDING);
2534                                 break;
2535                         case MPT2SAS_INTEL_RMS2LL040_SSDID:
2536                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2537                                     MPT2SAS_INTEL_RMS2LL040_BRANDING);
2538                                 break;
2539                         case MPT2SAS_INTEL_SSD910_SSDID:
2540                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2541                                     MPT2SAS_INTEL_SSD910_BRANDING);
2542                                 break;
2543                         default:
2544                                 pr_info(MPT3SAS_FMT
2545                                  "Intel(R) Controller: Subsystem ID: 0x%X\n",
2546                                  ioc->name, ioc->pdev->subsystem_device);
2547                                 break;
2548                         }
2549                 case MPI2_MFGPAGE_DEVID_SAS2308_2:
2550                         switch (ioc->pdev->subsystem_device) {
2551                         case MPT2SAS_INTEL_RS25GB008_SSDID:
2552                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2553                                     MPT2SAS_INTEL_RS25GB008_BRANDING);
2554                                 break;
2555                         case MPT2SAS_INTEL_RMS25JB080_SSDID:
2556                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2557                                     MPT2SAS_INTEL_RMS25JB080_BRANDING);
2558                                 break;
2559                         case MPT2SAS_INTEL_RMS25JB040_SSDID:
2560                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2561                                     MPT2SAS_INTEL_RMS25JB040_BRANDING);
2562                                 break;
2563                         case MPT2SAS_INTEL_RMS25KB080_SSDID:
2564                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2565                                     MPT2SAS_INTEL_RMS25KB080_BRANDING);
2566                                 break;
2567                         case MPT2SAS_INTEL_RMS25KB040_SSDID:
2568                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2569                                     MPT2SAS_INTEL_RMS25KB040_BRANDING);
2570                                 break;
2571                         case MPT2SAS_INTEL_RMS25LB040_SSDID:
2572                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2573                                     MPT2SAS_INTEL_RMS25LB040_BRANDING);
2574                                 break;
2575                         case MPT2SAS_INTEL_RMS25LB080_SSDID:
2576                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2577                                     MPT2SAS_INTEL_RMS25LB080_BRANDING);
2578                                 break;
2579                         default:
2580                                 pr_info(MPT3SAS_FMT
2581                                  "Intel(R) Controller: Subsystem ID: 0x%X\n",
2582                                  ioc->name, ioc->pdev->subsystem_device);
2583                                 break;
2584                         }
2585                 case MPI25_MFGPAGE_DEVID_SAS3008:
2586                         switch (ioc->pdev->subsystem_device) {
2587                         case MPT3SAS_INTEL_RMS3JC080_SSDID:
2588                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2589                                         MPT3SAS_INTEL_RMS3JC080_BRANDING);
2590                                 break;
2591
2592                         case MPT3SAS_INTEL_RS3GC008_SSDID:
2593                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2594                                         MPT3SAS_INTEL_RS3GC008_BRANDING);
2595                                 break;
2596                         case MPT3SAS_INTEL_RS3FC044_SSDID:
2597                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2598                                         MPT3SAS_INTEL_RS3FC044_BRANDING);
2599                                 break;
2600                         case MPT3SAS_INTEL_RS3UC080_SSDID:
2601                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2602                                         MPT3SAS_INTEL_RS3UC080_BRANDING);
2603                                 break;
2604                         default:
2605                                 pr_info(MPT3SAS_FMT
2606                                  "Intel(R) Controller: Subsystem ID: 0x%X\n",
2607                                  ioc->name, ioc->pdev->subsystem_device);
2608                                 break;
2609                         }
2610                         break;
2611                 default:
2612                         pr_info(MPT3SAS_FMT
2613                          "Intel(R) Controller: Subsystem ID: 0x%X\n",
2614                          ioc->name, ioc->pdev->subsystem_device);
2615                         break;
2616                 }
2617                 break;
2618         case PCI_VENDOR_ID_DELL:
2619                 switch (ioc->pdev->device) {
2620                 case MPI2_MFGPAGE_DEVID_SAS2008:
2621                         switch (ioc->pdev->subsystem_device) {
2622                         case MPT2SAS_DELL_6GBPS_SAS_HBA_SSDID:
2623                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2624                                  MPT2SAS_DELL_6GBPS_SAS_HBA_BRANDING);
2625                                 break;
2626                         case MPT2SAS_DELL_PERC_H200_ADAPTER_SSDID:
2627                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2628                                  MPT2SAS_DELL_PERC_H200_ADAPTER_BRANDING);
2629                                 break;
2630                         case MPT2SAS_DELL_PERC_H200_INTEGRATED_SSDID:
2631                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2632                                  MPT2SAS_DELL_PERC_H200_INTEGRATED_BRANDING);
2633                                 break;
2634                         case MPT2SAS_DELL_PERC_H200_MODULAR_SSDID:
2635                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2636                                  MPT2SAS_DELL_PERC_H200_MODULAR_BRANDING);
2637                                 break;
2638                         case MPT2SAS_DELL_PERC_H200_EMBEDDED_SSDID:
2639                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2640                                  MPT2SAS_DELL_PERC_H200_EMBEDDED_BRANDING);
2641                                 break;
2642                         case MPT2SAS_DELL_PERC_H200_SSDID:
2643                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2644                                  MPT2SAS_DELL_PERC_H200_BRANDING);
2645                                 break;
2646                         case MPT2SAS_DELL_6GBPS_SAS_SSDID:
2647                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2648                                  MPT2SAS_DELL_6GBPS_SAS_BRANDING);
2649                                 break;
2650                         default:
2651                                 pr_info(MPT3SAS_FMT
2652                                    "Dell 6Gbps HBA: Subsystem ID: 0x%X\n",
2653                                    ioc->name, ioc->pdev->subsystem_device);
2654                                 break;
2655                         }
2656                         break;
2657                 case MPI25_MFGPAGE_DEVID_SAS3008:
2658                         switch (ioc->pdev->subsystem_device) {
2659                         case MPT3SAS_DELL_12G_HBA_SSDID:
2660                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2661                                         MPT3SAS_DELL_12G_HBA_BRANDING);
2662                                 break;
2663                         default:
2664                                 pr_info(MPT3SAS_FMT
2665                                    "Dell 12Gbps HBA: Subsystem ID: 0x%X\n",
2666                                    ioc->name, ioc->pdev->subsystem_device);
2667                                 break;
2668                         }
2669                         break;
2670                 default:
2671                         pr_info(MPT3SAS_FMT
2672                            "Dell HBA: Subsystem ID: 0x%X\n", ioc->name,
2673                            ioc->pdev->subsystem_device);
2674                         break;
2675                 }
2676                 break;
2677         case PCI_VENDOR_ID_CISCO:
2678                 switch (ioc->pdev->device) {
2679                 case MPI25_MFGPAGE_DEVID_SAS3008:
2680                         switch (ioc->pdev->subsystem_device) {
2681                         case MPT3SAS_CISCO_12G_8E_HBA_SSDID:
2682                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2683                                         MPT3SAS_CISCO_12G_8E_HBA_BRANDING);
2684                                 break;
2685                         case MPT3SAS_CISCO_12G_8I_HBA_SSDID:
2686                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2687                                         MPT3SAS_CISCO_12G_8I_HBA_BRANDING);
2688                                 break;
2689                         case MPT3SAS_CISCO_12G_AVILA_HBA_SSDID:
2690                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2691                                         MPT3SAS_CISCO_12G_AVILA_HBA_BRANDING);
2692                                 break;
2693                         default:
2694                                 pr_info(MPT3SAS_FMT
2695                                   "Cisco 12Gbps SAS HBA: Subsystem ID: 0x%X\n",
2696                                   ioc->name, ioc->pdev->subsystem_device);
2697                                 break;
2698                         }
2699                         break;
2700                 case MPI25_MFGPAGE_DEVID_SAS3108_1:
2701                         switch (ioc->pdev->subsystem_device) {
2702                         case MPT3SAS_CISCO_12G_AVILA_HBA_SSDID:
2703                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2704                                 MPT3SAS_CISCO_12G_AVILA_HBA_BRANDING);
2705                                 break;
2706                         case MPT3SAS_CISCO_12G_COLUSA_MEZZANINE_HBA_SSDID:
2707                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2708                                 MPT3SAS_CISCO_12G_COLUSA_MEZZANINE_HBA_BRANDING
2709                                 );
2710                                 break;
2711                         default:
2712                                 pr_info(MPT3SAS_FMT
2713                                  "Cisco 12Gbps SAS HBA: Subsystem ID: 0x%X\n",
2714                                  ioc->name, ioc->pdev->subsystem_device);
2715                                 break;
2716                         }
2717                         break;
2718                 default:
2719                         pr_info(MPT3SAS_FMT
2720                            "Cisco SAS HBA: Subsystem ID: 0x%X\n",
2721                            ioc->name, ioc->pdev->subsystem_device);
2722                         break;
2723                 }
2724                 break;
2725         case MPT2SAS_HP_3PAR_SSVID:
2726                 switch (ioc->pdev->device) {
2727                 case MPI2_MFGPAGE_DEVID_SAS2004:
2728                         switch (ioc->pdev->subsystem_device) {
2729                         case MPT2SAS_HP_DAUGHTER_2_4_INTERNAL_SSDID:
2730                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2731                                     MPT2SAS_HP_DAUGHTER_2_4_INTERNAL_BRANDING);
2732                                 break;
2733                         default:
2734                                 pr_info(MPT3SAS_FMT
2735                                    "HP 6Gbps SAS HBA: Subsystem ID: 0x%X\n",
2736                                    ioc->name, ioc->pdev->subsystem_device);
2737                                 break;
2738                         }
2739                 case MPI2_MFGPAGE_DEVID_SAS2308_2:
2740                         switch (ioc->pdev->subsystem_device) {
2741                         case MPT2SAS_HP_2_4_INTERNAL_SSDID:
2742                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2743                                     MPT2SAS_HP_2_4_INTERNAL_BRANDING);
2744                                 break;
2745                         case MPT2SAS_HP_2_4_EXTERNAL_SSDID:
2746                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2747                                     MPT2SAS_HP_2_4_EXTERNAL_BRANDING);
2748                                 break;
2749                         case MPT2SAS_HP_1_4_INTERNAL_1_4_EXTERNAL_SSDID:
2750                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2751                                  MPT2SAS_HP_1_4_INTERNAL_1_4_EXTERNAL_BRANDING);
2752                                 break;
2753                         case MPT2SAS_HP_EMBEDDED_2_4_INTERNAL_SSDID:
2754                                 pr_info(MPT3SAS_FMT "%s\n", ioc->name,
2755                                     MPT2SAS_HP_EMBEDDED_2_4_INTERNAL_BRANDING);
2756                                 break;
2757                         default:
2758                                 pr_info(MPT3SAS_FMT
2759                                    "HP 6Gbps SAS HBA: Subsystem ID: 0x%X\n",
2760                                    ioc->name, ioc->pdev->subsystem_device);
2761                                 break;
2762                         }
2763                 default:
2764                         pr_info(MPT3SAS_FMT
2765                            "HP SAS HBA: Subsystem ID: 0x%X\n",
2766                            ioc->name, ioc->pdev->subsystem_device);
2767                         break;
2768                 }
2769         default:
2770                 break;
2771         }
2772 }
2773
2774 /**
2775  * _base_display_ioc_capabilities - Disply IOC's capabilities.
2776  * @ioc: per adapter object
2777  *
2778  * Return nothing.
2779  */
2780 static void
2781 _base_display_ioc_capabilities(struct MPT3SAS_ADAPTER *ioc)
2782 {
2783         int i = 0;
2784         char desc[16];
2785         u32 iounit_pg1_flags;
2786         u32 bios_version;
2787
2788         bios_version = le32_to_cpu(ioc->bios_pg3.BiosVersion);
2789         strncpy(desc, ioc->manu_pg0.ChipName, 16);
2790         pr_info(MPT3SAS_FMT "%s: FWVersion(%02d.%02d.%02d.%02d), "\
2791            "ChipRevision(0x%02x), BiosVersion(%02d.%02d.%02d.%02d)\n",
2792             ioc->name, desc,
2793            (ioc->facts.FWVersion.Word & 0xFF000000) >> 24,
2794            (ioc->facts.FWVersion.Word & 0x00FF0000) >> 16,
2795            (ioc->facts.FWVersion.Word & 0x0000FF00) >> 8,
2796            ioc->facts.FWVersion.Word & 0x000000FF,
2797            ioc->pdev->revision,
2798            (bios_version & 0xFF000000) >> 24,
2799            (bios_version & 0x00FF0000) >> 16,
2800            (bios_version & 0x0000FF00) >> 8,
2801             bios_version & 0x000000FF);
2802
2803         _base_display_OEMs_branding(ioc);
2804
2805         pr_info(MPT3SAS_FMT "Protocol=(", ioc->name);
2806
2807         if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_INITIATOR) {
2808                 pr_info("Initiator");
2809                 i++;
2810         }
2811
2812         if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_TARGET) {
2813                 pr_info("%sTarget", i ? "," : "");
2814                 i++;
2815         }
2816
2817         i = 0;
2818         pr_info("), ");
2819         pr_info("Capabilities=(");
2820
2821         if (!ioc->hide_ir_msg) {
2822                 if (ioc->facts.IOCCapabilities &
2823                     MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID) {
2824                         pr_info("Raid");
2825                         i++;
2826                 }
2827         }
2828
2829         if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR) {
2830                 pr_info("%sTLR", i ? "," : "");
2831                 i++;
2832         }
2833
2834         if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_MULTICAST) {
2835                 pr_info("%sMulticast", i ? "," : "");
2836                 i++;
2837         }
2838
2839         if (ioc->facts.IOCCapabilities &
2840             MPI2_IOCFACTS_CAPABILITY_BIDIRECTIONAL_TARGET) {
2841                 pr_info("%sBIDI Target", i ? "," : "");
2842                 i++;
2843         }
2844
2845         if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP) {
2846                 pr_info("%sEEDP", i ? "," : "");
2847                 i++;
2848         }
2849
2850         if (ioc->facts.IOCCapabilities &
2851             MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER) {
2852                 pr_info("%sSnapshot Buffer", i ? "," : "");
2853                 i++;
2854         }
2855
2856         if (ioc->facts.IOCCapabilities &
2857             MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER) {
2858                 pr_info("%sDiag Trace Buffer", i ? "," : "");
2859                 i++;
2860         }
2861
2862         if (ioc->facts.IOCCapabilities &
2863             MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER) {
2864                 pr_info("%sDiag Extended Buffer", i ? "," : "");
2865                 i++;
2866         }
2867
2868         if (ioc->facts.IOCCapabilities &
2869             MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING) {
2870                 pr_info("%sTask Set Full", i ? "," : "");
2871                 i++;
2872         }
2873
2874         iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
2875         if (!(iounit_pg1_flags & MPI2_IOUNITPAGE1_NATIVE_COMMAND_Q_DISABLE)) {
2876                 pr_info("%sNCQ", i ? "," : "");
2877                 i++;
2878         }
2879
2880         pr_info(")\n");
2881 }
2882
2883 /**
2884  * mpt3sas_base_update_missing_delay - change the missing delay timers
2885  * @ioc: per adapter object
2886  * @device_missing_delay: amount of time till device is reported missing
2887  * @io_missing_delay: interval IO is returned when there is a missing device
2888  *
2889  * Return nothing.
2890  *
2891  * Passed on the command line, this function will modify the device missing
2892  * delay, as well as the io missing delay. This should be called at driver
2893  * load time.
2894  */
2895 void
2896 mpt3sas_base_update_missing_delay(struct MPT3SAS_ADAPTER *ioc,
2897         u16 device_missing_delay, u8 io_missing_delay)
2898 {
2899         u16 dmd, dmd_new, dmd_orignal;
2900         u8 io_missing_delay_original;
2901         u16 sz;
2902         Mpi2SasIOUnitPage1_t *sas_iounit_pg1 = NULL;
2903         Mpi2ConfigReply_t mpi_reply;
2904         u8 num_phys = 0;
2905         u16 ioc_status;
2906
2907         mpt3sas_config_get_number_hba_phys(ioc, &num_phys);
2908         if (!num_phys)
2909                 return;
2910
2911         sz = offsetof(Mpi2SasIOUnitPage1_t, PhyData) + (num_phys *
2912             sizeof(Mpi2SasIOUnit1PhyData_t));
2913         sas_iounit_pg1 = kzalloc(sz, GFP_KERNEL);
2914         if (!sas_iounit_pg1) {
2915                 pr_err(MPT3SAS_FMT "failure at %s:%d/%s()!\n",
2916                     ioc->name, __FILE__, __LINE__, __func__);
2917                 goto out;
2918         }
2919         if ((mpt3sas_config_get_sas_iounit_pg1(ioc, &mpi_reply,
2920             sas_iounit_pg1, sz))) {
2921                 pr_err(MPT3SAS_FMT "failure at %s:%d/%s()!\n",
2922                     ioc->name, __FILE__, __LINE__, __func__);
2923                 goto out;
2924         }
2925         ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
2926             MPI2_IOCSTATUS_MASK;
2927         if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
2928                 pr_err(MPT3SAS_FMT "failure at %s:%d/%s()!\n",
2929                     ioc->name, __FILE__, __LINE__, __func__);
2930                 goto out;
2931         }
2932
2933         /* device missing delay */
2934         dmd = sas_iounit_pg1->ReportDeviceMissingDelay;
2935         if (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16)
2936                 dmd = (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK) * 16;
2937         else
2938                 dmd = dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK;
2939         dmd_orignal = dmd;
2940         if (device_missing_delay > 0x7F) {
2941                 dmd = (device_missing_delay > 0x7F0) ? 0x7F0 :
2942                     device_missing_delay;
2943                 dmd = dmd / 16;
2944                 dmd |= MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16;
2945         } else
2946                 dmd = device_missing_delay;
2947         sas_iounit_pg1->ReportDeviceMissingDelay = dmd;
2948
2949         /* io missing delay */
2950         io_missing_delay_original = sas_iounit_pg1->IODeviceMissingDelay;
2951         sas_iounit_pg1->IODeviceMissingDelay = io_missing_delay;
2952
2953         if (!mpt3sas_config_set_sas_iounit_pg1(ioc, &mpi_reply, sas_iounit_pg1,
2954             sz)) {
2955                 if (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16)
2956                         dmd_new = (dmd &
2957                             MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK) * 16;
2958                 else
2959                         dmd_new =
2960                     dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK;
2961                 pr_info(MPT3SAS_FMT "device_missing_delay: old(%d), new(%d)\n",
2962                         ioc->name, dmd_orignal, dmd_new);
2963                 pr_info(MPT3SAS_FMT "ioc_missing_delay: old(%d), new(%d)\n",
2964                         ioc->name, io_missing_delay_original,
2965                     io_missing_delay);
2966                 ioc->device_missing_delay = dmd_new;
2967                 ioc->io_missing_delay = io_missing_delay;
2968         }
2969
2970 out:
2971         kfree(sas_iounit_pg1);
2972 }
2973 /**
2974  * _base_static_config_pages - static start of day config pages
2975  * @ioc: per adapter object
2976  *
2977  * Return nothing.
2978  */
2979 static void
2980 _base_static_config_pages(struct MPT3SAS_ADAPTER *ioc)
2981 {
2982         Mpi2ConfigReply_t mpi_reply;
2983         u32 iounit_pg1_flags;
2984
2985         mpt3sas_config_get_manufacturing_pg0(ioc, &mpi_reply, &ioc->manu_pg0);
2986         if (ioc->ir_firmware)
2987                 mpt3sas_config_get_manufacturing_pg10(ioc, &mpi_reply,
2988                     &ioc->manu_pg10);
2989
2990         /*
2991          * Ensure correct T10 PI operation if vendor left EEDPTagMode
2992          * flag unset in NVDATA.
2993          */
2994         mpt3sas_config_get_manufacturing_pg11(ioc, &mpi_reply, &ioc->manu_pg11);
2995         if (ioc->manu_pg11.EEDPTagMode == 0) {
2996                 pr_err("%s: overriding NVDATA EEDPTagMode setting\n",
2997                     ioc->name);
2998                 ioc->manu_pg11.EEDPTagMode &= ~0x3;
2999                 ioc->manu_pg11.EEDPTagMode |= 0x1;
3000                 mpt3sas_config_set_manufacturing_pg11(ioc, &mpi_reply,
3001                     &ioc->manu_pg11);
3002         }
3003
3004         mpt3sas_config_get_bios_pg2(ioc, &mpi_reply, &ioc->bios_pg2);
3005         mpt3sas_config_get_bios_pg3(ioc, &mpi_reply, &ioc->bios_pg3);
3006         mpt3sas_config_get_ioc_pg8(ioc, &mpi_reply, &ioc->ioc_pg8);
3007         mpt3sas_config_get_iounit_pg0(ioc, &mpi_reply, &ioc->iounit_pg0);
3008         mpt3sas_config_get_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
3009         mpt3sas_config_get_iounit_pg8(ioc, &mpi_reply, &ioc->iounit_pg8);
3010         _base_display_ioc_capabilities(ioc);
3011
3012         /*
3013          * Enable task_set_full handling in iounit_pg1 when the
3014          * facts capabilities indicate that its supported.
3015          */
3016         iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
3017         if ((ioc->facts.IOCCapabilities &
3018             MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING))
3019                 iounit_pg1_flags &=
3020                     ~MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
3021         else
3022                 iounit_pg1_flags |=
3023                     MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
3024         ioc->iounit_pg1.Flags = cpu_to_le32(iounit_pg1_flags);
3025         mpt3sas_config_set_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
3026
3027         if (ioc->iounit_pg8.NumSensors)
3028                 ioc->temp_sensors_count = ioc->iounit_pg8.NumSensors;
3029 }
3030
3031 /**
3032  * _base_release_memory_pools - release memory
3033  * @ioc: per adapter object
3034  *
3035  * Free memory allocated from _base_allocate_memory_pools.
3036  *
3037  * Return nothing.
3038  */
3039 static void
3040 _base_release_memory_pools(struct MPT3SAS_ADAPTER *ioc)
3041 {
3042         int i = 0;
3043         struct reply_post_struct *rps;
3044
3045         dexitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3046             __func__));
3047
3048         if (ioc->request) {
3049                 pci_free_consistent(ioc->pdev, ioc->request_dma_sz,
3050                     ioc->request,  ioc->request_dma);
3051                 dexitprintk(ioc, pr_info(MPT3SAS_FMT
3052                         "request_pool(0x%p): free\n",
3053                         ioc->name, ioc->request));
3054                 ioc->request = NULL;
3055         }
3056
3057         if (ioc->sense) {
3058                 pci_pool_free(ioc->sense_dma_pool, ioc->sense, ioc->sense_dma);
3059                 if (ioc->sense_dma_pool)
3060                         pci_pool_destroy(ioc->sense_dma_pool);
3061                 dexitprintk(ioc, pr_info(MPT3SAS_FMT
3062                         "sense_pool(0x%p): free\n",
3063                         ioc->name, ioc->sense));
3064                 ioc->sense = NULL;
3065         }
3066
3067         if (ioc->reply) {
3068                 pci_pool_free(ioc->reply_dma_pool, ioc->reply, ioc->reply_dma);
3069                 if (ioc->reply_dma_pool)
3070                         pci_pool_destroy(ioc->reply_dma_pool);
3071                 dexitprintk(ioc, pr_info(MPT3SAS_FMT
3072                         "reply_pool(0x%p): free\n",
3073                         ioc->name, ioc->reply));
3074                 ioc->reply = NULL;
3075         }
3076
3077         if (ioc->reply_free) {
3078                 pci_pool_free(ioc->reply_free_dma_pool, ioc->reply_free,
3079                     ioc->reply_free_dma);
3080                 if (ioc->reply_free_dma_pool)
3081                         pci_pool_destroy(ioc->reply_free_dma_pool);
3082                 dexitprintk(ioc, pr_info(MPT3SAS_FMT
3083                         "reply_free_pool(0x%p): free\n",
3084                         ioc->name, ioc->reply_free));
3085                 ioc->reply_free = NULL;
3086         }
3087
3088         if (ioc->reply_post) {
3089                 do {
3090                         rps = &ioc->reply_post[i];
3091                         if (rps->reply_post_free) {
3092                                 pci_pool_free(
3093                                     ioc->reply_post_free_dma_pool,
3094                                     rps->reply_post_free,
3095                                     rps->reply_post_free_dma);
3096                                 dexitprintk(ioc, pr_info(MPT3SAS_FMT
3097                                     "reply_post_free_pool(0x%p): free\n",
3098                                     ioc->name, rps->reply_post_free));
3099                                 rps->reply_post_free = NULL;
3100                         }
3101                 } while (ioc->rdpq_array_enable &&
3102                            (++i < ioc->reply_queue_count));
3103
3104                 if (ioc->reply_post_free_dma_pool)
3105                         pci_pool_destroy(ioc->reply_post_free_dma_pool);
3106                 kfree(ioc->reply_post);
3107         }
3108
3109         if (ioc->config_page) {
3110                 dexitprintk(ioc, pr_info(MPT3SAS_FMT
3111                     "config_page(0x%p): free\n", ioc->name,
3112                     ioc->config_page));
3113                 pci_free_consistent(ioc->pdev, ioc->config_page_sz,
3114                     ioc->config_page, ioc->config_page_dma);
3115         }
3116
3117         if (ioc->scsi_lookup) {
3118                 free_pages((ulong)ioc->scsi_lookup, ioc->scsi_lookup_pages);
3119                 ioc->scsi_lookup = NULL;
3120         }
3121         kfree(ioc->hpr_lookup);
3122         kfree(ioc->internal_lookup);
3123         if (ioc->chain_lookup) {
3124                 for (i = 0; i < ioc->chain_depth; i++) {
3125                         if (ioc->chain_lookup[i].chain_buffer)
3126                                 pci_pool_free(ioc->chain_dma_pool,
3127                                     ioc->chain_lookup[i].chain_buffer,
3128                                     ioc->chain_lookup[i].chain_buffer_dma);
3129                 }
3130                 if (ioc->chain_dma_pool)
3131                         pci_pool_destroy(ioc->chain_dma_pool);
3132                 free_pages((ulong)ioc->chain_lookup, ioc->chain_pages);
3133                 ioc->chain_lookup = NULL;
3134         }
3135 }
3136
3137 /**
3138  * _base_allocate_memory_pools - allocate start of day memory pools
3139  * @ioc: per adapter object
3140  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3141  *
3142  * Returns 0 success, anything else error
3143  */
3144 static int
3145 _base_allocate_memory_pools(struct MPT3SAS_ADAPTER *ioc,  int sleep_flag)
3146 {
3147         struct mpt3sas_facts *facts;
3148         u16 max_sge_elements;
3149         u16 chains_needed_per_io;
3150         u32 sz, total_sz, reply_post_free_sz;
3151         u32 retry_sz;
3152         u16 max_request_credit;
3153         unsigned short sg_tablesize;
3154         u16 sge_size;
3155         int i;
3156
3157         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3158             __func__));
3159
3160
3161         retry_sz = 0;
3162         facts = &ioc->facts;
3163
3164         /* command line tunables for max sgl entries */
3165         if (max_sgl_entries != -1)
3166                 sg_tablesize = max_sgl_entries;
3167         else {
3168                 if (ioc->hba_mpi_version_belonged == MPI2_VERSION)
3169                         sg_tablesize = MPT2SAS_SG_DEPTH;
3170                 else
3171                         sg_tablesize = MPT3SAS_SG_DEPTH;
3172         }
3173
3174         if (sg_tablesize < MPT_MIN_PHYS_SEGMENTS)
3175                 sg_tablesize = MPT_MIN_PHYS_SEGMENTS;
3176         else if (sg_tablesize > MPT_MAX_PHYS_SEGMENTS) {
3177                 sg_tablesize = min_t(unsigned short, sg_tablesize,
3178                                       SCSI_MAX_SG_CHAIN_SEGMENTS);
3179                 pr_warn(MPT3SAS_FMT
3180                  "sg_tablesize(%u) is bigger than kernel"
3181                  " defined SCSI_MAX_SG_SEGMENTS(%u)\n", ioc->name,
3182                  sg_tablesize, MPT_MAX_PHYS_SEGMENTS);
3183         }
3184         ioc->shost->sg_tablesize = sg_tablesize;
3185
3186         ioc->hi_priority_depth = facts->HighPriorityCredit;
3187         ioc->internal_depth = ioc->hi_priority_depth + (5);
3188         /* command line tunables  for max controller queue depth */
3189         if (max_queue_depth != -1 && max_queue_depth != 0) {
3190                 max_request_credit = min_t(u16, max_queue_depth +
3191                     ioc->hi_priority_depth + ioc->internal_depth,
3192                     facts->RequestCredit);
3193                 if (max_request_credit > MAX_HBA_QUEUE_DEPTH)
3194                         max_request_credit =  MAX_HBA_QUEUE_DEPTH;
3195         } else
3196                 max_request_credit = min_t(u16, facts->RequestCredit,
3197                     MAX_HBA_QUEUE_DEPTH);
3198
3199         ioc->hba_queue_depth = max_request_credit;
3200
3201         /* request frame size */
3202         ioc->request_sz = facts->IOCRequestFrameSize * 4;
3203
3204         /* reply frame size */
3205         ioc->reply_sz = facts->ReplyFrameSize * 4;
3206
3207         /* calculate the max scatter element size */
3208         sge_size = max_t(u16, ioc->sge_size, ioc->sge_size_ieee);
3209
3210  retry_allocation:
3211         total_sz = 0;
3212         /* calculate number of sg elements left over in the 1st frame */
3213         max_sge_elements = ioc->request_sz - ((sizeof(Mpi2SCSIIORequest_t) -
3214             sizeof(Mpi2SGEIOUnion_t)) + sge_size);
3215         ioc->max_sges_in_main_message = max_sge_elements/sge_size;
3216
3217         /* now do the same for a chain buffer */
3218         max_sge_elements = ioc->request_sz - sge_size;
3219         ioc->max_sges_in_chain_message = max_sge_elements/sge_size;
3220
3221         /*
3222          *  MPT3SAS_SG_DEPTH = CONFIG_FUSION_MAX_SGE
3223          */
3224         chains_needed_per_io = ((ioc->shost->sg_tablesize -
3225            ioc->max_sges_in_main_message)/ioc->max_sges_in_chain_message)
3226             + 1;
3227         if (chains_needed_per_io > facts->MaxChainDepth) {
3228                 chains_needed_per_io = facts->MaxChainDepth;
3229                 ioc->shost->sg_tablesize = min_t(u16,
3230                 ioc->max_sges_in_main_message + (ioc->max_sges_in_chain_message
3231                 * chains_needed_per_io), ioc->shost->sg_tablesize);
3232         }
3233         ioc->chains_needed_per_io = chains_needed_per_io;
3234
3235         /* reply free queue sizing - taking into account for 64 FW events */
3236         ioc->reply_free_queue_depth = ioc->hba_queue_depth + 64;
3237
3238         /* calculate reply descriptor post queue depth */
3239         ioc->reply_post_queue_depth = ioc->hba_queue_depth +
3240                                 ioc->reply_free_queue_depth +  1 ;
3241         /* align the reply post queue on the next 16 count boundary */
3242         if (ioc->reply_post_queue_depth % 16)
3243                 ioc->reply_post_queue_depth += 16 -
3244                 (ioc->reply_post_queue_depth % 16);
3245
3246
3247         if (ioc->reply_post_queue_depth >
3248             facts->MaxReplyDescriptorPostQueueDepth) {
3249                 ioc->reply_post_queue_depth =
3250                                 facts->MaxReplyDescriptorPostQueueDepth -
3251                     (facts->MaxReplyDescriptorPostQueueDepth % 16);
3252                 ioc->hba_queue_depth =
3253                                 ((ioc->reply_post_queue_depth - 64) / 2) - 1;
3254                 ioc->reply_free_queue_depth = ioc->hba_queue_depth + 64;
3255         }
3256
3257         dinitprintk(ioc, pr_info(MPT3SAS_FMT "scatter gather: " \
3258             "sge_in_main_msg(%d), sge_per_chain(%d), sge_per_io(%d), "
3259             "chains_per_io(%d)\n", ioc->name, ioc->max_sges_in_main_message,
3260             ioc->max_sges_in_chain_message, ioc->shost->sg_tablesize,
3261             ioc->chains_needed_per_io));
3262
3263         /* reply post queue, 16 byte align */
3264         reply_post_free_sz = ioc->reply_post_queue_depth *
3265             sizeof(Mpi2DefaultReplyDescriptor_t);
3266
3267         sz = reply_post_free_sz;
3268         if (_base_is_controller_msix_enabled(ioc) && !ioc->rdpq_array_enable)
3269                 sz *= ioc->reply_queue_count;
3270
3271         ioc->reply_post = kcalloc((ioc->rdpq_array_enable) ?
3272             (ioc->reply_queue_count):1,
3273             sizeof(struct reply_post_struct), GFP_KERNEL);
3274
3275         if (!ioc->reply_post) {
3276                 pr_err(MPT3SAS_FMT "reply_post_free pool: kcalloc failed\n",
3277                         ioc->name);
3278                 goto out;
3279         }
3280         ioc->reply_post_free_dma_pool = pci_pool_create("reply_post_free pool",
3281             ioc->pdev, sz, 16, 0);
3282         if (!ioc->reply_post_free_dma_pool) {
3283                 pr_err(MPT3SAS_FMT
3284                  "reply_post_free pool: pci_pool_create failed\n",
3285                  ioc->name);
3286                 goto out;
3287         }
3288         i = 0;
3289         do {
3290                 ioc->reply_post[i].reply_post_free =
3291                     pci_pool_alloc(ioc->reply_post_free_dma_pool,
3292                     GFP_KERNEL,
3293                     &ioc->reply_post[i].reply_post_free_dma);
3294                 if (!ioc->reply_post[i].reply_post_free) {
3295                         pr_err(MPT3SAS_FMT
3296                         "reply_post_free pool: pci_pool_alloc failed\n",
3297                         ioc->name);
3298                         goto out;
3299                 }
3300                 memset(ioc->reply_post[i].reply_post_free, 0, sz);
3301                 dinitprintk(ioc, pr_info(MPT3SAS_FMT
3302                     "reply post free pool (0x%p): depth(%d),"
3303                     "element_size(%d), pool_size(%d kB)\n", ioc->name,
3304                     ioc->reply_post[i].reply_post_free,
3305                     ioc->reply_post_queue_depth, 8, sz/1024));
3306                 dinitprintk(ioc, pr_info(MPT3SAS_FMT
3307                     "reply_post_free_dma = (0x%llx)\n", ioc->name,
3308                     (unsigned long long)
3309                     ioc->reply_post[i].reply_post_free_dma));
3310                 total_sz += sz;
3311         } while (ioc->rdpq_array_enable && (++i < ioc->reply_queue_count));
3312
3313         if (ioc->dma_mask == 64) {
3314                 if (_base_change_consistent_dma_mask(ioc, ioc->pdev) != 0) {
3315                         pr_warn(MPT3SAS_FMT
3316                             "no suitable consistent DMA mask for %s\n",
3317                             ioc->name, pci_name(ioc->pdev));
3318                         goto out;
3319                 }
3320         }
3321
3322         ioc->scsiio_depth = ioc->hba_queue_depth -
3323             ioc->hi_priority_depth - ioc->internal_depth;
3324
3325         /* set the scsi host can_queue depth
3326          * with some internal commands that could be outstanding
3327          */
3328         ioc->shost->can_queue = ioc->scsiio_depth;
3329         dinitprintk(ioc, pr_info(MPT3SAS_FMT
3330                 "scsi host: can_queue depth (%d)\n",
3331                 ioc->name, ioc->shost->can_queue));
3332
3333
3334         /* contiguous pool for request and chains, 16 byte align, one extra "
3335          * "frame for smid=0
3336          */
3337         ioc->chain_depth = ioc->chains_needed_per_io * ioc->scsiio_depth;
3338         sz = ((ioc->scsiio_depth + 1) * ioc->request_sz);
3339
3340         /* hi-priority queue */
3341         sz += (ioc->hi_priority_depth * ioc->request_sz);
3342
3343         /* internal queue */
3344         sz += (ioc->internal_depth * ioc->request_sz);
3345
3346         ioc->request_dma_sz = sz;
3347         ioc->request = pci_alloc_consistent(ioc->pdev, sz, &ioc->request_dma);
3348         if (!ioc->request) {
3349                 pr_err(MPT3SAS_FMT "request pool: pci_alloc_consistent " \
3350                     "failed: hba_depth(%d), chains_per_io(%d), frame_sz(%d), "
3351                     "total(%d kB)\n", ioc->name, ioc->hba_queue_depth,
3352                     ioc->chains_needed_per_io, ioc->request_sz, sz/1024);
3353                 if (ioc->scsiio_depth < MPT3SAS_SAS_QUEUE_DEPTH)
3354                         goto out;
3355                 retry_sz += 64;
3356                 ioc->hba_queue_depth = max_request_credit - retry_sz;
3357                 goto retry_allocation;
3358         }
3359
3360         if (retry_sz)
3361                 pr_err(MPT3SAS_FMT "request pool: pci_alloc_consistent " \
3362                     "succeed: hba_depth(%d), chains_per_io(%d), frame_sz(%d), "
3363                     "total(%d kb)\n", ioc->name, ioc->hba_queue_depth,
3364                     ioc->chains_needed_per_io, ioc->request_sz, sz/1024);
3365
3366         /* hi-priority queue */
3367         ioc->hi_priority = ioc->request + ((ioc->scsiio_depth + 1) *
3368             ioc->request_sz);
3369         ioc->hi_priority_dma = ioc->request_dma + ((ioc->scsiio_depth + 1) *
3370             ioc->request_sz);
3371
3372         /* internal queue */
3373         ioc->internal = ioc->hi_priority + (ioc->hi_priority_depth *
3374             ioc->request_sz);
3375         ioc->internal_dma = ioc->hi_priority_dma + (ioc->hi_priority_depth *
3376             ioc->request_sz);
3377
3378         dinitprintk(ioc, pr_info(MPT3SAS_FMT
3379                 "request pool(0x%p): depth(%d), frame_size(%d), pool_size(%d kB)\n",
3380                 ioc->name, ioc->request, ioc->hba_queue_depth, ioc->request_sz,
3381             (ioc->hba_queue_depth * ioc->request_sz)/1024));
3382
3383         dinitprintk(ioc, pr_info(MPT3SAS_FMT "request pool: dma(0x%llx)\n",
3384             ioc->name, (unsigned long long) ioc->request_dma));
3385         total_sz += sz;
3386
3387         sz = ioc->scsiio_depth * sizeof(struct scsiio_tracker);
3388         ioc->scsi_lookup_pages = get_order(sz);
3389         ioc->scsi_lookup = (struct scsiio_tracker *)__get_free_pages(
3390             GFP_KERNEL, ioc->scsi_lookup_pages);
3391         if (!ioc->scsi_lookup) {
3392                 pr_err(MPT3SAS_FMT "scsi_lookup: get_free_pages failed, sz(%d)\n",
3393                         ioc->name, (int)sz);
3394                 goto out;
3395         }
3396
3397         dinitprintk(ioc, pr_info(MPT3SAS_FMT "scsiio(0x%p): depth(%d)\n",
3398                 ioc->name, ioc->request, ioc->scsiio_depth));
3399
3400         ioc->chain_depth = min_t(u32, ioc->chain_depth, MAX_CHAIN_DEPTH);
3401         sz = ioc->chain_depth * sizeof(struct chain_tracker);
3402         ioc->chain_pages = get_order(sz);
3403         ioc->chain_lookup = (struct chain_tracker *)__get_free_pages(
3404             GFP_KERNEL, ioc->chain_pages);
3405         if (!ioc->chain_lookup) {
3406                 pr_err(MPT3SAS_FMT "chain_lookup: __get_free_pages failed\n",
3407                         ioc->name);
3408                 goto out;
3409         }
3410         ioc->chain_dma_pool = pci_pool_create("chain pool", ioc->pdev,
3411             ioc->request_sz, 16, 0);
3412         if (!ioc->chain_dma_pool) {
3413                 pr_err(MPT3SAS_FMT "chain_dma_pool: pci_pool_create failed\n",
3414                         ioc->name);
3415                 goto out;
3416         }
3417         for (i = 0; i < ioc->chain_depth; i++) {
3418                 ioc->chain_lookup[i].chain_buffer = pci_pool_alloc(
3419                     ioc->chain_dma_pool , GFP_KERNEL,
3420                     &ioc->chain_lookup[i].chain_buffer_dma);
3421                 if (!ioc->chain_lookup[i].chain_buffer) {
3422                         ioc->chain_depth = i;
3423                         goto chain_done;
3424                 }
3425                 total_sz += ioc->request_sz;
3426         }
3427  chain_done:
3428         dinitprintk(ioc, pr_info(MPT3SAS_FMT
3429                 "chain pool depth(%d), frame_size(%d), pool_size(%d kB)\n",
3430                 ioc->name, ioc->chain_depth, ioc->request_sz,
3431                 ((ioc->chain_depth *  ioc->request_sz))/1024));
3432
3433         /* initialize hi-priority queue smid's */
3434         ioc->hpr_lookup = kcalloc(ioc->hi_priority_depth,
3435             sizeof(struct request_tracker), GFP_KERNEL);
3436         if (!ioc->hpr_lookup) {
3437                 pr_err(MPT3SAS_FMT "hpr_lookup: kcalloc failed\n",
3438                     ioc->name);
3439                 goto out;
3440         }
3441         ioc->hi_priority_smid = ioc->scsiio_depth + 1;
3442         dinitprintk(ioc, pr_info(MPT3SAS_FMT
3443                 "hi_priority(0x%p): depth(%d), start smid(%d)\n",
3444                 ioc->name, ioc->hi_priority,
3445             ioc->hi_priority_depth, ioc->hi_priority_smid));
3446
3447         /* initialize internal queue smid's */
3448         ioc->internal_lookup = kcalloc(ioc->internal_depth,
3449             sizeof(struct request_tracker), GFP_KERNEL);
3450         if (!ioc->internal_lookup) {
3451                 pr_err(MPT3SAS_FMT "internal_lookup: kcalloc failed\n",
3452                     ioc->name);
3453                 goto out;
3454         }
3455         ioc->internal_smid = ioc->hi_priority_smid + ioc->hi_priority_depth;
3456         dinitprintk(ioc, pr_info(MPT3SAS_FMT
3457                 "internal(0x%p): depth(%d), start smid(%d)\n",
3458                 ioc->name, ioc->internal,
3459             ioc->internal_depth, ioc->internal_smid));
3460
3461         /* sense buffers, 4 byte align */
3462         sz = ioc->scsiio_depth * SCSI_SENSE_BUFFERSIZE;
3463         ioc->sense_dma_pool = pci_pool_create("sense pool", ioc->pdev, sz, 4,
3464             0);
3465         if (!ioc->sense_dma_pool) {
3466                 pr_err(MPT3SAS_FMT "sense pool: pci_pool_create failed\n",
3467                     ioc->name);
3468                 goto out;
3469         }
3470         ioc->sense = pci_pool_alloc(ioc->sense_dma_pool , GFP_KERNEL,
3471             &ioc->sense_dma);
3472         if (!ioc->sense) {
3473                 pr_err(MPT3SAS_FMT "sense pool: pci_pool_alloc failed\n",
3474                     ioc->name);
3475                 goto out;
3476         }
3477         dinitprintk(ioc, pr_info(MPT3SAS_FMT
3478             "sense pool(0x%p): depth(%d), element_size(%d), pool_size"
3479             "(%d kB)\n", ioc->name, ioc->sense, ioc->scsiio_depth,
3480             SCSI_SENSE_BUFFERSIZE, sz/1024));
3481         dinitprintk(ioc, pr_info(MPT3SAS_FMT "sense_dma(0x%llx)\n",
3482             ioc->name, (unsigned long long)ioc->sense_dma));
3483         total_sz += sz;
3484
3485         /* reply pool, 4 byte align */
3486         sz = ioc->reply_free_queue_depth * ioc->reply_sz;
3487         ioc->reply_dma_pool = pci_pool_create("reply pool", ioc->pdev, sz, 4,
3488             0);
3489         if (!ioc->reply_dma_pool) {
3490                 pr_err(MPT3SAS_FMT "reply pool: pci_pool_create failed\n",
3491                     ioc->name);
3492                 goto out;
3493         }
3494         ioc->reply = pci_pool_alloc(ioc->reply_dma_pool , GFP_KERNEL,
3495             &ioc->reply_dma);
3496         if (!ioc->reply) {
3497                 pr_err(MPT3SAS_FMT "reply pool: pci_pool_alloc failed\n",
3498                     ioc->name);
3499                 goto out;
3500         }
3501         ioc->reply_dma_min_address = (u32)(ioc->reply_dma);
3502         ioc->reply_dma_max_address = (u32)(ioc->reply_dma) + sz;
3503         dinitprintk(ioc, pr_info(MPT3SAS_FMT
3504                 "reply pool(0x%p): depth(%d), frame_size(%d), pool_size(%d kB)\n",
3505                 ioc->name, ioc->reply,
3506             ioc->reply_free_queue_depth, ioc->reply_sz, sz/1024));
3507         dinitprintk(ioc, pr_info(MPT3SAS_FMT "reply_dma(0x%llx)\n",
3508             ioc->name, (unsigned long long)ioc->reply_dma));
3509         total_sz += sz;
3510
3511         /* reply free queue, 16 byte align */
3512         sz = ioc->reply_free_queue_depth * 4;
3513         ioc->reply_free_dma_pool = pci_pool_create("reply_free pool",
3514             ioc->pdev, sz, 16, 0);
3515         if (!ioc->reply_free_dma_pool) {
3516                 pr_err(MPT3SAS_FMT "reply_free pool: pci_pool_create failed\n",
3517                         ioc->name);
3518                 goto out;
3519         }
3520         ioc->reply_free = pci_pool_alloc(ioc->reply_free_dma_pool , GFP_KERNEL,
3521             &ioc->reply_free_dma);
3522         if (!ioc->reply_free) {
3523                 pr_err(MPT3SAS_FMT "reply_free pool: pci_pool_alloc failed\n",
3524                         ioc->name);
3525                 goto out;
3526         }
3527         memset(ioc->reply_free, 0, sz);
3528         dinitprintk(ioc, pr_info(MPT3SAS_FMT "reply_free pool(0x%p): " \
3529             "depth(%d), element_size(%d), pool_size(%d kB)\n", ioc->name,
3530             ioc->reply_free, ioc->reply_free_queue_depth, 4, sz/1024));
3531         dinitprintk(ioc, pr_info(MPT3SAS_FMT
3532                 "reply_free_dma (0x%llx)\n",
3533                 ioc->name, (unsigned long long)ioc->reply_free_dma));
3534         total_sz += sz;
3535
3536         ioc->config_page_sz = 512;
3537         ioc->config_page = pci_alloc_consistent(ioc->pdev,
3538             ioc->config_page_sz, &ioc->config_page_dma);
3539         if (!ioc->config_page) {
3540                 pr_err(MPT3SAS_FMT
3541                         "config page: pci_pool_alloc failed\n",
3542                         ioc->name);
3543                 goto out;
3544         }
3545         dinitprintk(ioc, pr_info(MPT3SAS_FMT
3546                 "config page(0x%p): size(%d)\n",
3547                 ioc->name, ioc->config_page, ioc->config_page_sz));
3548         dinitprintk(ioc, pr_info(MPT3SAS_FMT "config_page_dma(0x%llx)\n",
3549                 ioc->name, (unsigned long long)ioc->config_page_dma));
3550         total_sz += ioc->config_page_sz;
3551
3552         pr_info(MPT3SAS_FMT "Allocated physical memory: size(%d kB)\n",
3553             ioc->name, total_sz/1024);
3554         pr_info(MPT3SAS_FMT
3555                 "Current Controller Queue Depth(%d),Max Controller Queue Depth(%d)\n",
3556             ioc->name, ioc->shost->can_queue, facts->RequestCredit);
3557         pr_info(MPT3SAS_FMT "Scatter Gather Elements per IO(%d)\n",
3558             ioc->name, ioc->shost->sg_tablesize);
3559         return 0;
3560
3561  out:
3562         return -ENOMEM;
3563 }
3564
3565 /**
3566  * mpt3sas_base_get_iocstate - Get the current state of a MPT adapter.
3567  * @ioc: Pointer to MPT_ADAPTER structure
3568  * @cooked: Request raw or cooked IOC state
3569  *
3570  * Returns all IOC Doorbell register bits if cooked==0, else just the
3571  * Doorbell bits in MPI_IOC_STATE_MASK.
3572  */
3573 u32
3574 mpt3sas_base_get_iocstate(struct MPT3SAS_ADAPTER *ioc, int cooked)
3575 {
3576         u32 s, sc;
3577
3578         s = readl(&ioc->chip->Doorbell);
3579         sc = s & MPI2_IOC_STATE_MASK;
3580         return cooked ? sc : s;
3581 }
3582
3583 /**
3584  * _base_wait_on_iocstate - waiting on a particular ioc state
3585  * @ioc_state: controller state { READY, OPERATIONAL, or RESET }
3586  * @timeout: timeout in second
3587  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3588  *
3589  * Returns 0 for success, non-zero for failure.
3590  */
3591 static int
3592 _base_wait_on_iocstate(struct MPT3SAS_ADAPTER *ioc, u32 ioc_state, int timeout,
3593         int sleep_flag)
3594 {
3595         u32 count, cntdn;
3596         u32 current_state;
3597
3598         count = 0;
3599         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
3600         do {
3601                 current_state = mpt3sas_base_get_iocstate(ioc, 1);
3602                 if (current_state == ioc_state)
3603                         return 0;
3604                 if (count && current_state == MPI2_IOC_STATE_FAULT)
3605                         break;
3606                 if (sleep_flag == CAN_SLEEP)
3607                         usleep_range(1000, 1500);
3608                 else
3609                         udelay(500);
3610                 count++;
3611         } while (--cntdn);
3612
3613         return current_state;
3614 }
3615
3616 /**
3617  * _base_wait_for_doorbell_int - waiting for controller interrupt(generated by
3618  * a write to the doorbell)
3619  * @ioc: per adapter object
3620  * @timeout: timeout in second
3621  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3622  *
3623  * Returns 0 for success, non-zero for failure.
3624  *
3625  * Notes: MPI2_HIS_IOC2SYS_DB_STATUS - set to one when IOC writes to doorbell.
3626  */
3627 static int
3628 _base_diag_reset(struct MPT3SAS_ADAPTER *ioc, int sleep_flag);
3629
3630 static int
3631 _base_wait_for_doorbell_int(struct MPT3SAS_ADAPTER *ioc, int timeout,
3632         int sleep_flag)
3633 {
3634         u32 cntdn, count;
3635         u32 int_status;
3636
3637         count = 0;
3638         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
3639         do {
3640                 int_status = readl(&ioc->chip->HostInterruptStatus);
3641                 if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
3642                         dhsprintk(ioc, pr_info(MPT3SAS_FMT
3643                                 "%s: successful count(%d), timeout(%d)\n",
3644                                 ioc->name, __func__, count, timeout));
3645                         return 0;
3646                 }
3647                 if (sleep_flag == CAN_SLEEP)
3648                         usleep_range(1000, 1500);
3649                 else
3650                         udelay(500);
3651                 count++;
3652         } while (--cntdn);
3653
3654         pr_err(MPT3SAS_FMT
3655                 "%s: failed due to timeout count(%d), int_status(%x)!\n",
3656                 ioc->name, __func__, count, int_status);
3657         return -EFAULT;
3658 }
3659
3660 /**
3661  * _base_wait_for_doorbell_ack - waiting for controller to read the doorbell.
3662  * @ioc: per adapter object
3663  * @timeout: timeout in second
3664  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3665  *
3666  * Returns 0 for success, non-zero for failure.
3667  *
3668  * Notes: MPI2_HIS_SYS2IOC_DB_STATUS - set to one when host writes to
3669  * doorbell.
3670  */
3671 static int
3672 _base_wait_for_doorbell_ack(struct MPT3SAS_ADAPTER *ioc, int timeout,
3673         int sleep_flag)
3674 {
3675         u32 cntdn, count;
3676         u32 int_status;
3677         u32 doorbell;
3678
3679         count = 0;
3680         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
3681         do {
3682                 int_status = readl(&ioc->chip->HostInterruptStatus);
3683                 if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
3684                         dhsprintk(ioc, pr_info(MPT3SAS_FMT
3685                                 "%s: successful count(%d), timeout(%d)\n",
3686                                 ioc->name, __func__, count, timeout));
3687                         return 0;
3688                 } else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
3689                         doorbell = readl(&ioc->chip->Doorbell);
3690                         if ((doorbell & MPI2_IOC_STATE_MASK) ==
3691                             MPI2_IOC_STATE_FAULT) {
3692                                 mpt3sas_base_fault_info(ioc , doorbell);
3693                                 return -EFAULT;
3694                         }
3695                 } else if (int_status == 0xFFFFFFFF)
3696                         goto out;
3697
3698                 if (sleep_flag == CAN_SLEEP)
3699                         usleep_range(1000, 1500);
3700                 else
3701                         udelay(500);
3702                 count++;
3703         } while (--cntdn);
3704
3705  out:
3706         pr_err(MPT3SAS_FMT
3707          "%s: failed due to timeout count(%d), int_status(%x)!\n",
3708          ioc->name, __func__, count, int_status);
3709         return -EFAULT;
3710 }
3711
3712 /**
3713  * _base_wait_for_doorbell_not_used - waiting for doorbell to not be in use
3714  * @ioc: per adapter object
3715  * @timeout: timeout in second
3716  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3717  *
3718  * Returns 0 for success, non-zero for failure.
3719  *
3720  */
3721 static int
3722 _base_wait_for_doorbell_not_used(struct MPT3SAS_ADAPTER *ioc, int timeout,
3723         int sleep_flag)
3724 {
3725         u32 cntdn, count;
3726         u32 doorbell_reg;
3727
3728         count = 0;
3729         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
3730         do {
3731                 doorbell_reg = readl(&ioc->chip->Doorbell);
3732                 if (!(doorbell_reg & MPI2_DOORBELL_USED)) {
3733                         dhsprintk(ioc, pr_info(MPT3SAS_FMT
3734                                 "%s: successful count(%d), timeout(%d)\n",
3735                                 ioc->name, __func__, count, timeout));
3736                         return 0;
3737                 }
3738                 if (sleep_flag == CAN_SLEEP)
3739                         usleep_range(1000, 1500);
3740                 else
3741                         udelay(500);
3742                 count++;
3743         } while (--cntdn);
3744
3745         pr_err(MPT3SAS_FMT
3746                 "%s: failed due to timeout count(%d), doorbell_reg(%x)!\n",
3747                 ioc->name, __func__, count, doorbell_reg);
3748         return -EFAULT;
3749 }
3750
3751 /**
3752  * _base_send_ioc_reset - send doorbell reset
3753  * @ioc: per adapter object
3754  * @reset_type: currently only supports: MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET
3755  * @timeout: timeout in second
3756  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3757  *
3758  * Returns 0 for success, non-zero for failure.
3759  */
3760 static int
3761 _base_send_ioc_reset(struct MPT3SAS_ADAPTER *ioc, u8 reset_type, int timeout,
3762         int sleep_flag)
3763 {
3764         u32 ioc_state;
3765         int r = 0;
3766
3767         if (reset_type != MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET) {
3768                 pr_err(MPT3SAS_FMT "%s: unknown reset_type\n",
3769                     ioc->name, __func__);
3770                 return -EFAULT;
3771         }
3772
3773         if (!(ioc->facts.IOCCapabilities &
3774            MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY))
3775                 return -EFAULT;
3776
3777         pr_info(MPT3SAS_FMT "sending message unit reset !!\n", ioc->name);
3778
3779         writel(reset_type << MPI2_DOORBELL_FUNCTION_SHIFT,
3780             &ioc->chip->Doorbell);
3781         if ((_base_wait_for_doorbell_ack(ioc, 15, sleep_flag))) {
3782                 r = -EFAULT;
3783                 goto out;
3784         }
3785         ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY,
3786             timeout, sleep_flag);
3787         if (ioc_state) {
3788                 pr_err(MPT3SAS_FMT
3789                         "%s: failed going to ready state (ioc_state=0x%x)\n",
3790                         ioc->name, __func__, ioc_state);
3791                 r = -EFAULT;
3792                 goto out;
3793         }
3794  out:
3795         pr_info(MPT3SAS_FMT "message unit reset: %s\n",
3796             ioc->name, ((r == 0) ? "SUCCESS" : "FAILED"));
3797         return r;
3798 }
3799
3800 /**
3801  * _base_handshake_req_reply_wait - send request thru doorbell interface
3802  * @ioc: per adapter object
3803  * @request_bytes: request length
3804  * @request: pointer having request payload
3805  * @reply_bytes: reply length
3806  * @reply: pointer to reply payload
3807  * @timeout: timeout in second
3808  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3809  *
3810  * Returns 0 for success, non-zero for failure.
3811  */
3812 static int
3813 _base_handshake_req_reply_wait(struct MPT3SAS_ADAPTER *ioc, int request_bytes,
3814         u32 *request, int reply_bytes, u16 *reply, int timeout, int sleep_flag)
3815 {
3816         MPI2DefaultReply_t *default_reply = (MPI2DefaultReply_t *)reply;
3817         int i;
3818         u8 failed;
3819         u16 dummy;
3820         __le32 *mfp;
3821
3822         /* make sure doorbell is not in use */
3823         if ((readl(&ioc->chip->Doorbell) & MPI2_DOORBELL_USED)) {
3824                 pr_err(MPT3SAS_FMT
3825                         "doorbell is in use (line=%d)\n",
3826                         ioc->name, __LINE__);
3827                 return -EFAULT;
3828         }
3829
3830         /* clear pending doorbell interrupts from previous state changes */
3831         if (readl(&ioc->chip->HostInterruptStatus) &
3832             MPI2_HIS_IOC2SYS_DB_STATUS)
3833                 writel(0, &ioc->chip->HostInterruptStatus);
3834
3835         /* send message to ioc */
3836         writel(((MPI2_FUNCTION_HANDSHAKE<<MPI2_DOORBELL_FUNCTION_SHIFT) |
3837             ((request_bytes/4)<<MPI2_DOORBELL_ADD_DWORDS_SHIFT)),
3838             &ioc->chip->Doorbell);
3839
3840         if ((_base_wait_for_doorbell_int(ioc, 5, NO_SLEEP))) {
3841                 pr_err(MPT3SAS_FMT
3842                         "doorbell handshake int failed (line=%d)\n",
3843                         ioc->name, __LINE__);
3844                 return -EFAULT;
3845         }
3846         writel(0, &ioc->chip->HostInterruptStatus);
3847
3848         if ((_base_wait_for_doorbell_ack(ioc, 5, sleep_flag))) {
3849                 pr_err(MPT3SAS_FMT
3850                         "doorbell handshake ack failed (line=%d)\n",
3851                         ioc->name, __LINE__);
3852                 return -EFAULT;
3853         }
3854
3855         /* send message 32-bits at a time */
3856         for (i = 0, failed = 0; i < request_bytes/4 && !failed; i++) {
3857                 writel(cpu_to_le32(request[i]), &ioc->chip->Doorbell);
3858                 if ((_base_wait_for_doorbell_ack(ioc, 5, sleep_flag)))
3859                         failed = 1;
3860         }
3861
3862         if (failed) {
3863                 pr_err(MPT3SAS_FMT
3864                         "doorbell handshake sending request failed (line=%d)\n",
3865                         ioc->name, __LINE__);
3866                 return -EFAULT;
3867         }
3868
3869         /* now wait for the reply */
3870         if ((_base_wait_for_doorbell_int(ioc, timeout, sleep_flag))) {
3871                 pr_err(MPT3SAS_FMT
3872                         "doorbell handshake int failed (line=%d)\n",
3873                         ioc->name, __LINE__);
3874                 return -EFAULT;
3875         }
3876
3877         /* read the first two 16-bits, it gives the total length of the reply */
3878         reply[0] = le16_to_cpu(readl(&ioc->chip->Doorbell)
3879             & MPI2_DOORBELL_DATA_MASK);
3880         writel(0, &ioc->chip->HostInterruptStatus);
3881         if ((_base_wait_for_doorbell_int(ioc, 5, sleep_flag))) {
3882                 pr_err(MPT3SAS_FMT
3883                         "doorbell handshake int failed (line=%d)\n",
3884                         ioc->name, __LINE__);
3885                 return -EFAULT;
3886         }
3887         reply[1] = le16_to_cpu(readl(&ioc->chip->Doorbell)
3888             & MPI2_DOORBELL_DATA_MASK);
3889         writel(0, &ioc->chip->HostInterruptStatus);
3890
3891         for (i = 2; i < default_reply->MsgLength * 2; i++)  {
3892                 if ((_base_wait_for_doorbell_int(ioc, 5, sleep_flag))) {
3893                         pr_err(MPT3SAS_FMT
3894                                 "doorbell handshake int failed (line=%d)\n",
3895                                 ioc->name, __LINE__);
3896                         return -EFAULT;
3897                 }
3898                 if (i >=  reply_bytes/2) /* overflow case */
3899                         dummy = readl(&ioc->chip->Doorbell);
3900                 else
3901                         reply[i] = le16_to_cpu(readl(&ioc->chip->Doorbell)
3902                             & MPI2_DOORBELL_DATA_MASK);
3903                 writel(0, &ioc->chip->HostInterruptStatus);
3904         }
3905
3906         _base_wait_for_doorbell_int(ioc, 5, sleep_flag);
3907         if (_base_wait_for_doorbell_not_used(ioc, 5, sleep_flag) != 0) {
3908                 dhsprintk(ioc, pr_info(MPT3SAS_FMT
3909                         "doorbell is in use (line=%d)\n", ioc->name, __LINE__));
3910         }
3911         writel(0, &ioc->chip->HostInterruptStatus);
3912
3913         if (ioc->logging_level & MPT_DEBUG_INIT) {
3914                 mfp = (__le32 *)reply;
3915                 pr_info("\toffset:data\n");
3916                 for (i = 0; i < reply_bytes/4; i++)
3917                         pr_info("\t[0x%02x]:%08x\n", i*4,
3918                             le32_to_cpu(mfp[i]));
3919         }
3920         return 0;
3921 }
3922
3923 /**
3924  * mpt3sas_base_sas_iounit_control - send sas iounit control to FW
3925  * @ioc: per adapter object
3926  * @mpi_reply: the reply payload from FW
3927  * @mpi_request: the request payload sent to FW
3928  *
3929  * The SAS IO Unit Control Request message allows the host to perform low-level
3930  * operations, such as resets on the PHYs of the IO Unit, also allows the host
3931  * to obtain the IOC assigned device handles for a device if it has other
3932  * identifying information about the device, in addition allows the host to
3933  * remove IOC resources associated with the device.
3934  *
3935  * Returns 0 for success, non-zero for failure.
3936  */
3937 int
3938 mpt3sas_base_sas_iounit_control(struct MPT3SAS_ADAPTER *ioc,
3939         Mpi2SasIoUnitControlReply_t *mpi_reply,
3940         Mpi2SasIoUnitControlRequest_t *mpi_request)
3941 {
3942         u16 smid;
3943         u32 ioc_state;
3944         unsigned long timeleft;
3945         bool issue_reset = false;
3946         int rc;
3947         void *request;
3948         u16 wait_state_count;
3949
3950         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
3951             __func__));
3952
3953         mutex_lock(&ioc->base_cmds.mutex);
3954
3955         if (ioc->base_cmds.status != MPT3_CMD_NOT_USED) {
3956                 pr_err(MPT3SAS_FMT "%s: base_cmd in use\n",
3957                     ioc->name, __func__);
3958                 rc = -EAGAIN;
3959                 goto out;
3960         }
3961
3962         wait_state_count = 0;
3963         ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
3964         while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
3965                 if (wait_state_count++ == 10) {
3966                         pr_err(MPT3SAS_FMT
3967                             "%s: failed due to ioc not operational\n",
3968                             ioc->name, __func__);
3969                         rc = -EFAULT;
3970                         goto out;
3971                 }
3972                 ssleep(1);
3973                 ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
3974                 pr_info(MPT3SAS_FMT
3975                         "%s: waiting for operational state(count=%d)\n",
3976                         ioc->name, __func__, wait_state_count);
3977         }
3978
3979         smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
3980         if (!smid) {
3981                 pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n",
3982                     ioc->name, __func__);
3983                 rc = -EAGAIN;
3984                 goto out;
3985         }
3986
3987         rc = 0;
3988         ioc->base_cmds.status = MPT3_CMD_PENDING;
3989         request = mpt3sas_base_get_msg_frame(ioc, smid);
3990         ioc->base_cmds.smid = smid;
3991         memcpy(request, mpi_request, sizeof(Mpi2SasIoUnitControlRequest_t));
3992         if (mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
3993             mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET)
3994                 ioc->ioc_link_reset_in_progress = 1;
3995         init_completion(&ioc->base_cmds.done);
3996         mpt3sas_base_put_smid_default(ioc, smid);
3997         timeleft = wait_for_completion_timeout(&ioc->base_cmds.done,
3998             msecs_to_jiffies(10000));
3999         if ((mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
4000             mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET) &&
4001             ioc->ioc_link_reset_in_progress)
4002                 ioc->ioc_link_reset_in_progress = 0;
4003         if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
4004                 pr_err(MPT3SAS_FMT "%s: timeout\n",
4005                     ioc->name, __func__);
4006                 _debug_dump_mf(mpi_request,
4007                     sizeof(Mpi2SasIoUnitControlRequest_t)/4);
4008                 if (!(ioc->base_cmds.status & MPT3_CMD_RESET))
4009                         issue_reset = true;
4010                 goto issue_host_reset;
4011         }
4012         if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID)
4013                 memcpy(mpi_reply, ioc->base_cmds.reply,
4014                     sizeof(Mpi2SasIoUnitControlReply_t));
4015         else
4016                 memset(mpi_reply, 0, sizeof(Mpi2SasIoUnitControlReply_t));
4017         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
4018         goto out;
4019
4020  issue_host_reset:
4021         if (issue_reset)
4022                 mpt3sas_base_hard_reset_handler(ioc, CAN_SLEEP,
4023                     FORCE_BIG_HAMMER);
4024         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
4025         rc = -EFAULT;
4026  out:
4027         mutex_unlock(&ioc->base_cmds.mutex);
4028         return rc;
4029 }
4030
4031 /**
4032  * mpt3sas_base_scsi_enclosure_processor - sending request to sep device
4033  * @ioc: per adapter object
4034  * @mpi_reply: the reply payload from FW
4035  * @mpi_request: the request payload sent to FW
4036  *
4037  * The SCSI Enclosure Processor request message causes the IOC to
4038  * communicate with SES devices to control LED status signals.
4039  *
4040  * Returns 0 for success, non-zero for failure.
4041  */
4042 int
4043 mpt3sas_base_scsi_enclosure_processor(struct MPT3SAS_ADAPTER *ioc,
4044         Mpi2SepReply_t *mpi_reply, Mpi2SepRequest_t *mpi_request)
4045 {
4046         u16 smid;
4047         u32 ioc_state;
4048         unsigned long timeleft;
4049         bool issue_reset = false;
4050         int rc;
4051         void *request;
4052         u16 wait_state_count;
4053
4054         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
4055             __func__));
4056
4057         mutex_lock(&ioc->base_cmds.mutex);
4058
4059         if (ioc->base_cmds.status != MPT3_CMD_NOT_USED) {
4060                 pr_err(MPT3SAS_FMT "%s: base_cmd in use\n",
4061                     ioc->name, __func__);
4062                 rc = -EAGAIN;
4063                 goto out;
4064         }
4065
4066         wait_state_count = 0;
4067         ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
4068         while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
4069                 if (wait_state_count++ == 10) {
4070                         pr_err(MPT3SAS_FMT
4071                             "%s: failed due to ioc not operational\n",
4072                             ioc->name, __func__);
4073                         rc = -EFAULT;
4074                         goto out;
4075                 }
4076                 ssleep(1);
4077                 ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
4078                 pr_info(MPT3SAS_FMT
4079                         "%s: waiting for operational state(count=%d)\n",
4080                         ioc->name,
4081                     __func__, wait_state_count);
4082         }
4083
4084         smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
4085         if (!smid) {
4086                 pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n",
4087                     ioc->name, __func__);
4088                 rc = -EAGAIN;
4089                 goto out;
4090         }
4091
4092         rc = 0;
4093         ioc->base_cmds.status = MPT3_CMD_PENDING;
4094         request = mpt3sas_base_get_msg_frame(ioc, smid);
4095         ioc->base_cmds.smid = smid;
4096         memcpy(request, mpi_request, sizeof(Mpi2SepReply_t));
4097         init_completion(&ioc->base_cmds.done);
4098         mpt3sas_base_put_smid_default(ioc, smid);
4099         timeleft = wait_for_completion_timeout(&ioc->base_cmds.done,
4100             msecs_to_jiffies(10000));
4101         if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
4102                 pr_err(MPT3SAS_FMT "%s: timeout\n",
4103                     ioc->name, __func__);
4104                 _debug_dump_mf(mpi_request,
4105                     sizeof(Mpi2SepRequest_t)/4);
4106                 if (!(ioc->base_cmds.status & MPT3_CMD_RESET))
4107                         issue_reset = false;
4108                 goto issue_host_reset;
4109         }
4110         if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID)
4111                 memcpy(mpi_reply, ioc->base_cmds.reply,
4112                     sizeof(Mpi2SepReply_t));
4113         else
4114                 memset(mpi_reply, 0, sizeof(Mpi2SepReply_t));
4115         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
4116         goto out;
4117
4118  issue_host_reset:
4119         if (issue_reset)
4120                 mpt3sas_base_hard_reset_handler(ioc, CAN_SLEEP,
4121                     FORCE_BIG_HAMMER);
4122         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
4123         rc = -EFAULT;
4124  out:
4125         mutex_unlock(&ioc->base_cmds.mutex);
4126         return rc;
4127 }
4128
4129 /**
4130  * _base_get_port_facts - obtain port facts reply and save in ioc
4131  * @ioc: per adapter object
4132  * @sleep_flag: CAN_SLEEP or NO_SLEEP
4133  *
4134  * Returns 0 for success, non-zero for failure.
4135  */
4136 static int
4137 _base_get_port_facts(struct MPT3SAS_ADAPTER *ioc, int port, int sleep_flag)
4138 {
4139         Mpi2PortFactsRequest_t mpi_request;
4140         Mpi2PortFactsReply_t mpi_reply;
4141         struct mpt3sas_port_facts *pfacts;
4142         int mpi_reply_sz, mpi_request_sz, r;
4143
4144         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
4145             __func__));
4146
4147         mpi_reply_sz = sizeof(Mpi2PortFactsReply_t);
4148         mpi_request_sz = sizeof(Mpi2PortFactsRequest_t);
4149         memset(&mpi_request, 0, mpi_request_sz);
4150         mpi_request.Function = MPI2_FUNCTION_PORT_FACTS;
4151         mpi_request.PortNumber = port;
4152         r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
4153             (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5, CAN_SLEEP);
4154
4155         if (r != 0) {
4156                 pr_err(MPT3SAS_FMT "%s: handshake failed (r=%d)\n",
4157                     ioc->name, __func__, r);
4158                 return r;
4159         }
4160
4161         pfacts = &ioc->pfacts[port];
4162         memset(pfacts, 0, sizeof(struct mpt3sas_port_facts));
4163         pfacts->PortNumber = mpi_reply.PortNumber;
4164         pfacts->VP_ID = mpi_reply.VP_ID;
4165         pfacts->VF_ID = mpi_reply.VF_ID;
4166         pfacts->MaxPostedCmdBuffers =
4167             le16_to_cpu(mpi_reply.MaxPostedCmdBuffers);
4168
4169         return 0;
4170 }
4171
4172 /**
4173  * _base_wait_for_iocstate - Wait until the card is in READY or OPERATIONAL
4174  * @ioc: per adapter object
4175  * @timeout:
4176  * @sleep_flag: CAN_SLEEP or NO_SLEEP
4177  *
4178  * Returns 0 for success, non-zero for failure.
4179  */
4180 static int
4181 _base_wait_for_iocstate(struct MPT3SAS_ADAPTER *ioc, int timeout,
4182         int sleep_flag)
4183 {
4184         u32 ioc_state;
4185         int rc;
4186
4187         dinitprintk(ioc, printk(MPT3SAS_FMT "%s\n", ioc->name,
4188             __func__));
4189
4190         if (ioc->pci_error_recovery) {
4191                 dfailprintk(ioc, printk(MPT3SAS_FMT
4192                     "%s: host in pci error recovery\n", ioc->name, __func__));
4193                 return -EFAULT;
4194         }
4195
4196         ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
4197         dhsprintk(ioc, printk(MPT3SAS_FMT "%s: ioc_state(0x%08x)\n",
4198             ioc->name, __func__, ioc_state));
4199
4200         if (((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_READY) ||
4201             (ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_OPERATIONAL)
4202                 return 0;
4203
4204         if (ioc_state & MPI2_DOORBELL_USED) {
4205                 dhsprintk(ioc, printk(MPT3SAS_FMT
4206                     "unexpected doorbell active!\n", ioc->name));
4207                 goto issue_diag_reset;
4208         }
4209
4210         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
4211                 mpt3sas_base_fault_info(ioc, ioc_state &
4212                     MPI2_DOORBELL_DATA_MASK);
4213                 goto issue_diag_reset;
4214         }
4215
4216         ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY,
4217             timeout, sleep_flag);
4218         if (ioc_state) {
4219                 dfailprintk(ioc, printk(MPT3SAS_FMT
4220                     "%s: failed going to ready state (ioc_state=0x%x)\n",
4221                     ioc->name, __func__, ioc_state));
4222                 return -EFAULT;
4223         }
4224
4225  issue_diag_reset:
4226         rc = _base_diag_reset(ioc, sleep_flag);
4227         return rc;
4228 }
4229
4230 /**
4231  * _base_get_ioc_facts - obtain ioc facts reply and save in ioc
4232  * @ioc: per adapter object
4233  * @sleep_flag: CAN_SLEEP or NO_SLEEP
4234  *
4235  * Returns 0 for success, non-zero for failure.
4236  */
4237 static int
4238 _base_get_ioc_facts(struct MPT3SAS_ADAPTER *ioc, int sleep_flag)
4239 {
4240         Mpi2IOCFactsRequest_t mpi_request;
4241         Mpi2IOCFactsReply_t mpi_reply;
4242         struct mpt3sas_facts *facts;
4243         int mpi_reply_sz, mpi_request_sz, r;
4244
4245         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
4246             __func__));
4247
4248         r = _base_wait_for_iocstate(ioc, 10, sleep_flag);
4249         if (r) {
4250                 dfailprintk(ioc, printk(MPT3SAS_FMT
4251                     "%s: failed getting to correct state\n",
4252                     ioc->name, __func__));
4253                 return r;
4254         }
4255         mpi_reply_sz = sizeof(Mpi2IOCFactsReply_t);
4256         mpi_request_sz = sizeof(Mpi2IOCFactsRequest_t);
4257         memset(&mpi_request, 0, mpi_request_sz);
4258         mpi_request.Function = MPI2_FUNCTION_IOC_FACTS;
4259         r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
4260             (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5, CAN_SLEEP);
4261
4262         if (r != 0) {
4263                 pr_err(MPT3SAS_FMT "%s: handshake failed (r=%d)\n",
4264                     ioc->name, __func__, r);
4265                 return r;
4266         }
4267
4268         facts = &ioc->facts;
4269         memset(facts, 0, sizeof(struct mpt3sas_facts));
4270         facts->MsgVersion = le16_to_cpu(mpi_reply.MsgVersion);
4271         facts->HeaderVersion = le16_to_cpu(mpi_reply.HeaderVersion);
4272         facts->VP_ID = mpi_reply.VP_ID;
4273         facts->VF_ID = mpi_reply.VF_ID;
4274         facts->IOCExceptions = le16_to_cpu(mpi_reply.IOCExceptions);
4275         facts->MaxChainDepth = mpi_reply.MaxChainDepth;
4276         facts->WhoInit = mpi_reply.WhoInit;
4277         facts->NumberOfPorts = mpi_reply.NumberOfPorts;
4278         facts->MaxMSIxVectors = mpi_reply.MaxMSIxVectors;
4279         facts->RequestCredit = le16_to_cpu(mpi_reply.RequestCredit);
4280         facts->MaxReplyDescriptorPostQueueDepth =
4281             le16_to_cpu(mpi_reply.MaxReplyDescriptorPostQueueDepth);
4282         facts->ProductID = le16_to_cpu(mpi_reply.ProductID);
4283         facts->IOCCapabilities = le32_to_cpu(mpi_reply.IOCCapabilities);
4284         if ((facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID))
4285                 ioc->ir_firmware = 1;
4286         if ((facts->IOCCapabilities &
4287               MPI2_IOCFACTS_CAPABILITY_RDPQ_ARRAY_CAPABLE))
4288                 ioc->rdpq_array_capable = 1;
4289         facts->FWVersion.Word = le32_to_cpu(mpi_reply.FWVersion.Word);
4290         facts->IOCRequestFrameSize =
4291             le16_to_cpu(mpi_reply.IOCRequestFrameSize);
4292         facts->MaxInitiators = le16_to_cpu(mpi_reply.MaxInitiators);
4293         facts->MaxTargets = le16_to_cpu(mpi_reply.MaxTargets);
4294         ioc->shost->max_id = -1;
4295         facts->MaxSasExpanders = le16_to_cpu(mpi_reply.MaxSasExpanders);
4296         facts->MaxEnclosures = le16_to_cpu(mpi_reply.MaxEnclosures);
4297         facts->ProtocolFlags = le16_to_cpu(mpi_reply.ProtocolFlags);
4298         facts->HighPriorityCredit =
4299             le16_to_cpu(mpi_reply.HighPriorityCredit);
4300         facts->ReplyFrameSize = mpi_reply.ReplyFrameSize;
4301         facts->MaxDevHandle = le16_to_cpu(mpi_reply.MaxDevHandle);
4302
4303         dinitprintk(ioc, pr_info(MPT3SAS_FMT
4304                 "hba queue depth(%d), max chains per io(%d)\n",
4305                 ioc->name, facts->RequestCredit,
4306             facts->MaxChainDepth));
4307         dinitprintk(ioc, pr_info(MPT3SAS_FMT
4308                 "request frame size(%d), reply frame size(%d)\n", ioc->name,
4309             facts->IOCRequestFrameSize * 4, facts->ReplyFrameSize * 4));
4310         return 0;
4311 }
4312
4313 /**
4314  * _base_send_ioc_init - send ioc_init to firmware
4315  * @ioc: per adapter object
4316  * @sleep_flag: CAN_SLEEP or NO_SLEEP
4317  *
4318  * Returns 0 for success, non-zero for failure.
4319  */
4320 static int
4321 _base_send_ioc_init(struct MPT3SAS_ADAPTER *ioc, int sleep_flag)
4322 {
4323         Mpi2IOCInitRequest_t mpi_request;
4324         Mpi2IOCInitReply_t mpi_reply;
4325         int i, r = 0;
4326         struct timeval current_time;
4327         u16 ioc_status;
4328         u32 reply_post_free_array_sz = 0;
4329         Mpi2IOCInitRDPQArrayEntry *reply_post_free_array = NULL;
4330         dma_addr_t reply_post_free_array_dma;
4331
4332         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
4333             __func__));
4334
4335         memset(&mpi_request, 0, sizeof(Mpi2IOCInitRequest_t));
4336         mpi_request.Function = MPI2_FUNCTION_IOC_INIT;
4337         mpi_request.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
4338         mpi_request.VF_ID = 0; /* TODO */
4339         mpi_request.VP_ID = 0;
4340         mpi_request.MsgVersion = cpu_to_le16(ioc->hba_mpi_version_belonged);
4341         mpi_request.HeaderVersion = cpu_to_le16(MPI2_HEADER_VERSION);
4342
4343         if (_base_is_controller_msix_enabled(ioc))
4344                 mpi_request.HostMSIxVectors = ioc->reply_queue_count;
4345         mpi_request.SystemRequestFrameSize = cpu_to_le16(ioc->request_sz/4);
4346         mpi_request.ReplyDescriptorPostQueueDepth =
4347             cpu_to_le16(ioc->reply_post_queue_depth);
4348         mpi_request.ReplyFreeQueueDepth =
4349             cpu_to_le16(ioc->reply_free_queue_depth);
4350
4351         mpi_request.SenseBufferAddressHigh =
4352             cpu_to_le32((u64)ioc->sense_dma >> 32);
4353         mpi_request.SystemReplyAddressHigh =
4354             cpu_to_le32((u64)ioc->reply_dma >> 32);
4355         mpi_request.SystemRequestFrameBaseAddress =
4356             cpu_to_le64((u64)ioc->request_dma);
4357         mpi_request.ReplyFreeQueueAddress =
4358             cpu_to_le64((u64)ioc->reply_free_dma);
4359
4360         if (ioc->rdpq_array_enable) {
4361                 reply_post_free_array_sz = ioc->reply_queue_count *
4362                     sizeof(Mpi2IOCInitRDPQArrayEntry);
4363                 reply_post_free_array = pci_alloc_consistent(ioc->pdev,
4364                         reply_post_free_array_sz, &reply_post_free_array_dma);
4365                 if (!reply_post_free_array) {
4366                         pr_err(MPT3SAS_FMT
4367                         "reply_post_free_array: pci_alloc_consistent failed\n",
4368                         ioc->name);
4369                         r = -ENOMEM;
4370                         goto out;
4371                 }
4372                 memset(reply_post_free_array, 0, reply_post_free_array_sz);
4373                 for (i = 0; i < ioc->reply_queue_count; i++)
4374                         reply_post_free_array[i].RDPQBaseAddress =
4375                             cpu_to_le64(
4376                                 (u64)ioc->reply_post[i].reply_post_free_dma);
4377                 mpi_request.MsgFlags = MPI2_IOCINIT_MSGFLAG_RDPQ_ARRAY_MODE;
4378                 mpi_request.ReplyDescriptorPostQueueAddress =
4379                     cpu_to_le64((u64)reply_post_free_array_dma);
4380         } else {
4381                 mpi_request.ReplyDescriptorPostQueueAddress =
4382                     cpu_to_le64((u64)ioc->reply_post[0].reply_post_free_dma);
4383         }
4384
4385         /* This time stamp specifies number of milliseconds
4386          * since epoch ~ midnight January 1, 1970.
4387          */
4388         do_gettimeofday(&current_time);
4389         mpi_request.TimeStamp = cpu_to_le64((u64)current_time.tv_sec * 1000 +
4390             (current_time.tv_usec / 1000));
4391
4392         if (ioc->logging_level & MPT_DEBUG_INIT) {
4393                 __le32 *mfp;
4394                 int i;
4395
4396                 mfp = (__le32 *)&mpi_request;
4397                 pr_info("\toffset:data\n");
4398                 for (i = 0; i < sizeof(Mpi2IOCInitRequest_t)/4; i++)
4399                         pr_info("\t[0x%02x]:%08x\n", i*4,
4400                             le32_to_cpu(mfp[i]));
4401         }
4402
4403         r = _base_handshake_req_reply_wait(ioc,
4404             sizeof(Mpi2IOCInitRequest_t), (u32 *)&mpi_request,
4405             sizeof(Mpi2IOCInitReply_t), (u16 *)&mpi_reply, 10,
4406             sleep_flag);
4407
4408         if (r != 0) {
4409                 pr_err(MPT3SAS_FMT "%s: handshake failed (r=%d)\n",
4410                     ioc->name, __func__, r);
4411                 goto out;
4412         }
4413
4414         ioc_status = le16_to_cpu(mpi_reply.IOCStatus) & MPI2_IOCSTATUS_MASK;
4415         if (ioc_status != MPI2_IOCSTATUS_SUCCESS ||
4416             mpi_reply.IOCLogInfo) {
4417                 pr_err(MPT3SAS_FMT "%s: failed\n", ioc->name, __func__);
4418                 r = -EIO;
4419         }
4420
4421 out:
4422         if (reply_post_free_array)
4423                 pci_free_consistent(ioc->pdev, reply_post_free_array_sz,
4424                                     reply_post_free_array,
4425                                     reply_post_free_array_dma);
4426         return r;
4427 }
4428
4429 /**
4430  * mpt3sas_port_enable_done - command completion routine for port enable
4431  * @ioc: per adapter object
4432  * @smid: system request message index
4433  * @msix_index: MSIX table index supplied by the OS
4434  * @reply: reply message frame(lower 32bit addr)
4435  *
4436  * Return 1 meaning mf should be freed from _base_interrupt
4437  *        0 means the mf is freed from this function.
4438  */
4439 u8
4440 mpt3sas_port_enable_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
4441         u32 reply)
4442 {
4443         MPI2DefaultReply_t *mpi_reply;
4444         u16 ioc_status;
4445
4446         if (ioc->port_enable_cmds.status == MPT3_CMD_NOT_USED)
4447                 return 1;
4448
4449         mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
4450         if (!mpi_reply)
4451                 return 1;
4452
4453         if (mpi_reply->Function != MPI2_FUNCTION_PORT_ENABLE)
4454                 return 1;
4455
4456         ioc->port_enable_cmds.status &= ~MPT3_CMD_PENDING;
4457         ioc->port_enable_cmds.status |= MPT3_CMD_COMPLETE;
4458         ioc->port_enable_cmds.status |= MPT3_CMD_REPLY_VALID;
4459         memcpy(ioc->port_enable_cmds.reply, mpi_reply, mpi_reply->MsgLength*4);
4460         ioc_status = le16_to_cpu(mpi_reply->IOCStatus) & MPI2_IOCSTATUS_MASK;
4461         if (ioc_status != MPI2_IOCSTATUS_SUCCESS)
4462                 ioc->port_enable_failed = 1;
4463
4464         if (ioc->is_driver_loading) {
4465                 if (ioc_status == MPI2_IOCSTATUS_SUCCESS) {
4466                         mpt3sas_port_enable_complete(ioc);
4467                         return 1;
4468                 } else {
4469                         ioc->start_scan_failed = ioc_status;
4470                         ioc->start_scan = 0;
4471                         return 1;
4472                 }
4473         }
4474         complete(&ioc->port_enable_cmds.done);
4475         return 1;
4476 }
4477
4478 /**
4479  * _base_send_port_enable - send port_enable(discovery stuff) to firmware
4480  * @ioc: per adapter object
4481  * @sleep_flag: CAN_SLEEP or NO_SLEEP
4482  *
4483  * Returns 0 for success, non-zero for failure.
4484  */
4485 static int
4486 _base_send_port_enable(struct MPT3SAS_ADAPTER *ioc, int sleep_flag)
4487 {
4488         Mpi2PortEnableRequest_t *mpi_request;
4489         Mpi2PortEnableReply_t *mpi_reply;
4490         unsigned long timeleft;
4491         int r = 0;
4492         u16 smid;
4493         u16 ioc_status;
4494
4495         pr_info(MPT3SAS_FMT "sending port enable !!\n", ioc->name);
4496
4497         if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
4498                 pr_err(MPT3SAS_FMT "%s: internal command already in use\n",
4499                     ioc->name, __func__);
4500                 return -EAGAIN;
4501         }
4502
4503         smid = mpt3sas_base_get_smid(ioc, ioc->port_enable_cb_idx);
4504         if (!smid) {
4505                 pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n",
4506                     ioc->name, __func__);
4507                 return -EAGAIN;
4508         }
4509
4510         ioc->port_enable_cmds.status = MPT3_CMD_PENDING;
4511         mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
4512         ioc->port_enable_cmds.smid = smid;
4513         memset(mpi_request, 0, sizeof(Mpi2PortEnableRequest_t));
4514         mpi_request->Function = MPI2_FUNCTION_PORT_ENABLE;
4515
4516         init_completion(&ioc->port_enable_cmds.done);
4517         mpt3sas_base_put_smid_default(ioc, smid);
4518         timeleft = wait_for_completion_timeout(&ioc->port_enable_cmds.done,
4519             300*HZ);
4520         if (!(ioc->port_enable_cmds.status & MPT3_CMD_COMPLETE)) {
4521                 pr_err(MPT3SAS_FMT "%s: timeout\n",
4522                     ioc->name, __func__);
4523                 _debug_dump_mf(mpi_request,
4524                     sizeof(Mpi2PortEnableRequest_t)/4);
4525                 if (ioc->port_enable_cmds.status & MPT3_CMD_RESET)
4526                         r = -EFAULT;
4527                 else
4528                         r = -ETIME;
4529                 goto out;
4530         }
4531
4532         mpi_reply = ioc->port_enable_cmds.reply;
4533         ioc_status = le16_to_cpu(mpi_reply->IOCStatus) & MPI2_IOCSTATUS_MASK;
4534         if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
4535                 pr_err(MPT3SAS_FMT "%s: failed with (ioc_status=0x%08x)\n",
4536                     ioc->name, __func__, ioc_status);
4537                 r = -EFAULT;
4538                 goto out;
4539         }
4540
4541  out:
4542         ioc->port_enable_cmds.status = MPT3_CMD_NOT_USED;
4543         pr_info(MPT3SAS_FMT "port enable: %s\n", ioc->name, ((r == 0) ?
4544             "SUCCESS" : "FAILED"));
4545         return r;
4546 }
4547
4548 /**
4549  * mpt3sas_port_enable - initiate firmware discovery (don't wait for reply)
4550  * @ioc: per adapter object
4551  *
4552  * Returns 0 for success, non-zero for failure.
4553  */
4554 int
4555 mpt3sas_port_enable(struct MPT3SAS_ADAPTER *ioc)
4556 {
4557         Mpi2PortEnableRequest_t *mpi_request;
4558         u16 smid;
4559
4560         pr_info(MPT3SAS_FMT "sending port enable !!\n", ioc->name);
4561
4562         if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
4563                 pr_err(MPT3SAS_FMT "%s: internal command already in use\n",
4564                     ioc->name, __func__);
4565                 return -EAGAIN;
4566         }
4567
4568         smid = mpt3sas_base_get_smid(ioc, ioc->port_enable_cb_idx);
4569         if (!smid) {
4570                 pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n",
4571                     ioc->name, __func__);
4572                 return -EAGAIN;
4573         }
4574
4575         ioc->port_enable_cmds.status = MPT3_CMD_PENDING;
4576         mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
4577         ioc->port_enable_cmds.smid = smid;
4578         memset(mpi_request, 0, sizeof(Mpi2PortEnableRequest_t));
4579         mpi_request->Function = MPI2_FUNCTION_PORT_ENABLE;
4580
4581         mpt3sas_base_put_smid_default(ioc, smid);
4582         return 0;
4583 }
4584
4585 /**
4586  * _base_determine_wait_on_discovery - desposition
4587  * @ioc: per adapter object
4588  *
4589  * Decide whether to wait on discovery to complete. Used to either
4590  * locate boot device, or report volumes ahead of physical devices.
4591  *
4592  * Returns 1 for wait, 0 for don't wait
4593  */
4594 static int
4595 _base_determine_wait_on_discovery(struct MPT3SAS_ADAPTER *ioc)
4596 {
4597         /* We wait for discovery to complete if IR firmware is loaded.
4598          * The sas topology events arrive before PD events, so we need time to
4599          * turn on the bit in ioc->pd_handles to indicate PD
4600          * Also, it maybe required to report Volumes ahead of physical
4601          * devices when MPI2_IOCPAGE8_IRFLAGS_LOW_VOLUME_MAPPING is set.
4602          */
4603         if (ioc->ir_firmware)
4604                 return 1;
4605
4606         /* if no Bios, then we don't need to wait */
4607         if (!ioc->bios_pg3.BiosVersion)
4608                 return 0;
4609
4610         /* Bios is present, then we drop down here.
4611          *
4612          * If there any entries in the Bios Page 2, then we wait
4613          * for discovery to complete.
4614          */
4615
4616         /* Current Boot Device */
4617         if ((ioc->bios_pg2.CurrentBootDeviceForm &
4618             MPI2_BIOSPAGE2_FORM_MASK) ==
4619             MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED &&
4620         /* Request Boot Device */
4621            (ioc->bios_pg2.ReqBootDeviceForm &
4622             MPI2_BIOSPAGE2_FORM_MASK) ==
4623             MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED &&
4624         /* Alternate Request Boot Device */
4625            (ioc->bios_pg2.ReqAltBootDeviceForm &
4626             MPI2_BIOSPAGE2_FORM_MASK) ==
4627             MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED)
4628                 return 0;
4629
4630         return 1;
4631 }
4632
4633 /**
4634  * _base_unmask_events - turn on notification for this event
4635  * @ioc: per adapter object
4636  * @event: firmware event
4637  *
4638  * The mask is stored in ioc->event_masks.
4639  */
4640 static void
4641 _base_unmask_events(struct MPT3SAS_ADAPTER *ioc, u16 event)
4642 {
4643         u32 desired_event;
4644
4645         if (event >= 128)
4646                 return;
4647
4648         desired_event = (1 << (event % 32));
4649
4650         if (event < 32)
4651                 ioc->event_masks[0] &= ~desired_event;
4652         else if (event < 64)
4653                 ioc->event_masks[1] &= ~desired_event;
4654         else if (event < 96)
4655                 ioc->event_masks[2] &= ~desired_event;
4656         else if (event < 128)
4657                 ioc->event_masks[3] &= ~desired_event;
4658 }
4659
4660 /**
4661  * _base_event_notification - send event notification
4662  * @ioc: per adapter object
4663  * @sleep_flag: CAN_SLEEP or NO_SLEEP
4664  *
4665  * Returns 0 for success, non-zero for failure.
4666  */
4667 static int
4668 _base_event_notification(struct MPT3SAS_ADAPTER *ioc, int sleep_flag)
4669 {
4670         Mpi2EventNotificationRequest_t *mpi_request;
4671         unsigned long timeleft;
4672         u16 smid;
4673         int r = 0;
4674         int i;
4675
4676         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
4677             __func__));
4678
4679         if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
4680                 pr_err(MPT3SAS_FMT "%s: internal command already in use\n",
4681                     ioc->name, __func__);
4682                 return -EAGAIN;
4683         }
4684
4685         smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
4686         if (!smid) {
4687                 pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n",
4688                     ioc->name, __func__);
4689                 return -EAGAIN;
4690         }
4691         ioc->base_cmds.status = MPT3_CMD_PENDING;
4692         mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
4693         ioc->base_cmds.smid = smid;
4694         memset(mpi_request, 0, sizeof(Mpi2EventNotificationRequest_t));
4695         mpi_request->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
4696         mpi_request->VF_ID = 0; /* TODO */
4697         mpi_request->VP_ID = 0;
4698         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
4699                 mpi_request->EventMasks[i] =
4700                     cpu_to_le32(ioc->event_masks[i]);
4701         init_completion(&ioc->base_cmds.done);
4702         mpt3sas_base_put_smid_default(ioc, smid);
4703         timeleft = wait_for_completion_timeout(&ioc->base_cmds.done, 30*HZ);
4704         if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
4705                 pr_err(MPT3SAS_FMT "%s: timeout\n",
4706                     ioc->name, __func__);
4707                 _debug_dump_mf(mpi_request,
4708                     sizeof(Mpi2EventNotificationRequest_t)/4);
4709                 if (ioc->base_cmds.status & MPT3_CMD_RESET)
4710                         r = -EFAULT;
4711                 else
4712                         r = -ETIME;
4713         } else
4714                 dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s: complete\n",
4715                     ioc->name, __func__));
4716         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
4717         return r;
4718 }
4719
4720 /**
4721  * mpt3sas_base_validate_event_type - validating event types
4722  * @ioc: per adapter object
4723  * @event: firmware event
4724  *
4725  * This will turn on firmware event notification when application
4726  * ask for that event. We don't mask events that are already enabled.
4727  */
4728 void
4729 mpt3sas_base_validate_event_type(struct MPT3SAS_ADAPTER *ioc, u32 *event_type)
4730 {
4731         int i, j;
4732         u32 event_mask, desired_event;
4733         u8 send_update_to_fw;
4734
4735         for (i = 0, send_update_to_fw = 0; i <
4736             MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++) {
4737                 event_mask = ~event_type[i];
4738                 desired_event = 1;
4739                 for (j = 0; j < 32; j++) {
4740                         if (!(event_mask & desired_event) &&
4741                             (ioc->event_masks[i] & desired_event)) {
4742                                 ioc->event_masks[i] &= ~desired_event;
4743                                 send_update_to_fw = 1;
4744                         }
4745                         desired_event = (desired_event << 1);
4746                 }
4747         }
4748
4749         if (!send_update_to_fw)
4750                 return;
4751
4752         mutex_lock(&ioc->base_cmds.mutex);
4753         _base_event_notification(ioc, CAN_SLEEP);
4754         mutex_unlock(&ioc->base_cmds.mutex);
4755 }
4756
4757 /**
4758  * _base_diag_reset - the "big hammer" start of day reset
4759  * @ioc: per adapter object
4760  * @sleep_flag: CAN_SLEEP or NO_SLEEP
4761  *
4762  * Returns 0 for success, non-zero for failure.
4763  */
4764 static int
4765 _base_diag_reset(struct MPT3SAS_ADAPTER *ioc, int sleep_flag)
4766 {
4767         u32 host_diagnostic;
4768         u32 ioc_state;
4769         u32 count;
4770         u32 hcb_size;
4771
4772         pr_info(MPT3SAS_FMT "sending diag reset !!\n", ioc->name);
4773
4774         drsprintk(ioc, pr_info(MPT3SAS_FMT "clear interrupts\n",
4775             ioc->name));
4776
4777         count = 0;
4778         do {
4779                 /* Write magic sequence to WriteSequence register
4780                  * Loop until in diagnostic mode
4781                  */
4782                 drsprintk(ioc, pr_info(MPT3SAS_FMT
4783                         "write magic sequence\n", ioc->name));
4784                 writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
4785                 writel(MPI2_WRSEQ_1ST_KEY_VALUE, &ioc->chip->WriteSequence);
4786                 writel(MPI2_WRSEQ_2ND_KEY_VALUE, &ioc->chip->WriteSequence);
4787                 writel(MPI2_WRSEQ_3RD_KEY_VALUE, &ioc->chip->WriteSequence);
4788                 writel(MPI2_WRSEQ_4TH_KEY_VALUE, &ioc->chip->WriteSequence);
4789                 writel(MPI2_WRSEQ_5TH_KEY_VALUE, &ioc->chip->WriteSequence);
4790                 writel(MPI2_WRSEQ_6TH_KEY_VALUE, &ioc->chip->WriteSequence);
4791
4792                 /* wait 100 msec */
4793                 if (sleep_flag == CAN_SLEEP)
4794                         msleep(100);
4795                 else
4796                         mdelay(100);
4797
4798                 if (count++ > 20)
4799                         goto out;
4800
4801                 host_diagnostic = readl(&ioc->chip->HostDiagnostic);
4802                 drsprintk(ioc, pr_info(MPT3SAS_FMT
4803                         "wrote magic sequence: count(%d), host_diagnostic(0x%08x)\n",
4804                     ioc->name, count, host_diagnostic));
4805
4806         } while ((host_diagnostic & MPI2_DIAG_DIAG_WRITE_ENABLE) == 0);
4807
4808         hcb_size = readl(&ioc->chip->HCBSize);
4809
4810         drsprintk(ioc, pr_info(MPT3SAS_FMT "diag reset: issued\n",
4811             ioc->name));
4812         writel(host_diagnostic | MPI2_DIAG_RESET_ADAPTER,
4813              &ioc->chip->HostDiagnostic);
4814
4815         /*This delay allows the chip PCIe hardware time to finish reset tasks*/
4816         if (sleep_flag == CAN_SLEEP)
4817                 msleep(MPI2_HARD_RESET_PCIE_FIRST_READ_DELAY_MICRO_SEC/1000);
4818         else
4819                 mdelay(MPI2_HARD_RESET_PCIE_FIRST_READ_DELAY_MICRO_SEC/1000);
4820
4821         /* Approximately 300 second max wait */
4822         for (count = 0; count < (300000000 /
4823                 MPI2_HARD_RESET_PCIE_SECOND_READ_DELAY_MICRO_SEC); count++) {
4824
4825                 host_diagnostic = readl(&ioc->chip->HostDiagnostic);
4826
4827                 if (host_diagnostic == 0xFFFFFFFF)
4828                         goto out;
4829                 if (!(host_diagnostic & MPI2_DIAG_RESET_ADAPTER))
4830                         break;
4831
4832                 /* Wait to pass the second read delay window */
4833                 if (sleep_flag == CAN_SLEEP)
4834                         msleep(MPI2_HARD_RESET_PCIE_SECOND_READ_DELAY_MICRO_SEC
4835                                                                 / 1000);
4836                 else
4837                         mdelay(MPI2_HARD_RESET_PCIE_SECOND_READ_DELAY_MICRO_SEC
4838                                                                 / 1000);
4839         }
4840
4841         if (host_diagnostic & MPI2_DIAG_HCB_MODE) {
4842
4843                 drsprintk(ioc, pr_info(MPT3SAS_FMT
4844                 "restart the adapter assuming the HCB Address points to good F/W\n",
4845                     ioc->name));
4846                 host_diagnostic &= ~MPI2_DIAG_BOOT_DEVICE_SELECT_MASK;
4847                 host_diagnostic |= MPI2_DIAG_BOOT_DEVICE_SELECT_HCDW;
4848                 writel(host_diagnostic, &ioc->chip->HostDiagnostic);
4849
4850                 drsprintk(ioc, pr_info(MPT3SAS_FMT
4851                     "re-enable the HCDW\n", ioc->name));
4852                 writel(hcb_size | MPI2_HCB_SIZE_HCB_ENABLE,
4853                     &ioc->chip->HCBSize);
4854         }
4855
4856         drsprintk(ioc, pr_info(MPT3SAS_FMT "restart the adapter\n",
4857             ioc->name));
4858         writel(host_diagnostic & ~MPI2_DIAG_HOLD_IOC_RESET,
4859             &ioc->chip->HostDiagnostic);
4860
4861         drsprintk(ioc, pr_info(MPT3SAS_FMT
4862                 "disable writes to the diagnostic register\n", ioc->name));
4863         writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
4864
4865         drsprintk(ioc, pr_info(MPT3SAS_FMT
4866                 "Wait for FW to go to the READY state\n", ioc->name));
4867         ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, 20,
4868             sleep_flag);
4869         if (ioc_state) {
4870                 pr_err(MPT3SAS_FMT
4871                         "%s: failed going to ready state (ioc_state=0x%x)\n",
4872                         ioc->name, __func__, ioc_state);
4873                 goto out;
4874         }
4875
4876         pr_info(MPT3SAS_FMT "diag reset: SUCCESS\n", ioc->name);
4877         return 0;
4878
4879  out:
4880         pr_err(MPT3SAS_FMT "diag reset: FAILED\n", ioc->name);
4881         return -EFAULT;
4882 }
4883
4884 /**
4885  * _base_make_ioc_ready - put controller in READY state
4886  * @ioc: per adapter object
4887  * @sleep_flag: CAN_SLEEP or NO_SLEEP
4888  * @type: FORCE_BIG_HAMMER or SOFT_RESET
4889  *
4890  * Returns 0 for success, non-zero for failure.
4891  */
4892 static int
4893 _base_make_ioc_ready(struct MPT3SAS_ADAPTER *ioc, int sleep_flag,
4894         enum reset_type type)
4895 {
4896         u32 ioc_state;
4897         int rc;
4898         int count;
4899
4900         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
4901             __func__));
4902
4903         if (ioc->pci_error_recovery)
4904                 return 0;
4905
4906         ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
4907         dhsprintk(ioc, pr_info(MPT3SAS_FMT "%s: ioc_state(0x%08x)\n",
4908             ioc->name, __func__, ioc_state));
4909
4910         /* if in RESET state, it should move to READY state shortly */
4911         count = 0;
4912         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_RESET) {
4913                 while ((ioc_state & MPI2_IOC_STATE_MASK) !=
4914                     MPI2_IOC_STATE_READY) {
4915                         if (count++ == 10) {
4916                                 pr_err(MPT3SAS_FMT
4917                                         "%s: failed going to ready state (ioc_state=0x%x)\n",
4918                                     ioc->name, __func__, ioc_state);
4919                                 return -EFAULT;
4920                         }
4921                         if (sleep_flag == CAN_SLEEP)
4922                                 ssleep(1);
4923                         else
4924                                 mdelay(1000);
4925                         ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
4926                 }
4927         }
4928
4929         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_READY)
4930                 return 0;
4931
4932         if (ioc_state & MPI2_DOORBELL_USED) {
4933                 dhsprintk(ioc, pr_info(MPT3SAS_FMT
4934                         "unexpected doorbell active!\n",
4935                         ioc->name));
4936                 goto issue_diag_reset;
4937         }
4938
4939         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
4940                 mpt3sas_base_fault_info(ioc, ioc_state &
4941                     MPI2_DOORBELL_DATA_MASK);
4942                 goto issue_diag_reset;
4943         }
4944
4945         if (type == FORCE_BIG_HAMMER)
4946                 goto issue_diag_reset;
4947
4948         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_OPERATIONAL)
4949                 if (!(_base_send_ioc_reset(ioc,
4950                     MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET, 15, CAN_SLEEP))) {
4951                         return 0;
4952         }
4953
4954  issue_diag_reset:
4955         rc = _base_diag_reset(ioc, CAN_SLEEP);
4956         return rc;
4957 }
4958
4959 /**
4960  * _base_make_ioc_operational - put controller in OPERATIONAL state
4961  * @ioc: per adapter object
4962  * @sleep_flag: CAN_SLEEP or NO_SLEEP
4963  *
4964  * Returns 0 for success, non-zero for failure.
4965  */
4966 static int
4967 _base_make_ioc_operational(struct MPT3SAS_ADAPTER *ioc, int sleep_flag)
4968 {
4969         int r, i;
4970         unsigned long   flags;
4971         u32 reply_address;
4972         u16 smid;
4973         struct _tr_list *delayed_tr, *delayed_tr_next;
4974         u8 hide_flag;
4975         struct adapter_reply_queue *reply_q;
4976         long reply_post_free;
4977         u32 reply_post_free_sz, index = 0;
4978
4979         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
4980             __func__));
4981
4982         /* clean the delayed target reset list */
4983         list_for_each_entry_safe(delayed_tr, delayed_tr_next,
4984             &ioc->delayed_tr_list, list) {
4985                 list_del(&delayed_tr->list);
4986                 kfree(delayed_tr);
4987         }
4988
4989
4990         list_for_each_entry_safe(delayed_tr, delayed_tr_next,
4991             &ioc->delayed_tr_volume_list, list) {
4992                 list_del(&delayed_tr->list);
4993                 kfree(delayed_tr);
4994         }
4995
4996         /* initialize the scsi lookup free list */
4997         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
4998         INIT_LIST_HEAD(&ioc->free_list);
4999         smid = 1;
5000         for (i = 0; i < ioc->scsiio_depth; i++, smid++) {
5001                 INIT_LIST_HEAD(&ioc->scsi_lookup[i].chain_list);
5002                 ioc->scsi_lookup[i].cb_idx = 0xFF;
5003                 ioc->scsi_lookup[i].smid = smid;
5004                 ioc->scsi_lookup[i].scmd = NULL;
5005                 ioc->scsi_lookup[i].direct_io = 0;
5006                 list_add_tail(&ioc->scsi_lookup[i].tracker_list,
5007                     &ioc->free_list);
5008         }
5009
5010         /* hi-priority queue */
5011         INIT_LIST_HEAD(&ioc->hpr_free_list);
5012         smid = ioc->hi_priority_smid;
5013         for (i = 0; i < ioc->hi_priority_depth; i++, smid++) {
5014                 ioc->hpr_lookup[i].cb_idx = 0xFF;
5015                 ioc->hpr_lookup[i].smid = smid;
5016                 list_add_tail(&ioc->hpr_lookup[i].tracker_list,
5017                     &ioc->hpr_free_list);
5018         }
5019
5020         /* internal queue */
5021         INIT_LIST_HEAD(&ioc->internal_free_list);
5022         smid = ioc->internal_smid;
5023         for (i = 0; i < ioc->internal_depth; i++, smid++) {
5024                 ioc->internal_lookup[i].cb_idx = 0xFF;
5025                 ioc->internal_lookup[i].smid = smid;
5026                 list_add_tail(&ioc->internal_lookup[i].tracker_list,
5027                     &ioc->internal_free_list);
5028         }
5029
5030         /* chain pool */
5031         INIT_LIST_HEAD(&ioc->free_chain_list);
5032         for (i = 0; i < ioc->chain_depth; i++)
5033                 list_add_tail(&ioc->chain_lookup[i].tracker_list,
5034                     &ioc->free_chain_list);
5035
5036         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
5037
5038         /* initialize Reply Free Queue */
5039         for (i = 0, reply_address = (u32)ioc->reply_dma ;
5040             i < ioc->reply_free_queue_depth ; i++, reply_address +=
5041             ioc->reply_sz)
5042                 ioc->reply_free[i] = cpu_to_le32(reply_address);
5043
5044         /* initialize reply queues */
5045         if (ioc->is_driver_loading)
5046                 _base_assign_reply_queues(ioc);
5047
5048         /* initialize Reply Post Free Queue */
5049         reply_post_free_sz = ioc->reply_post_queue_depth *
5050             sizeof(Mpi2DefaultReplyDescriptor_t);
5051         reply_post_free = (long)ioc->reply_post[index].reply_post_free;
5052         list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
5053                 reply_q->reply_post_host_index = 0;
5054                 reply_q->reply_post_free = (Mpi2ReplyDescriptorsUnion_t *)
5055                     reply_post_free;
5056                 for (i = 0; i < ioc->reply_post_queue_depth; i++)
5057                         reply_q->reply_post_free[i].Words =
5058                             cpu_to_le64(ULLONG_MAX);
5059                 if (!_base_is_controller_msix_enabled(ioc))
5060                         goto skip_init_reply_post_free_queue;
5061                 /*
5062                  * If RDPQ is enabled, switch to the next allocation.
5063                  * Otherwise advance within the contiguous region.
5064                  */
5065                 if (ioc->rdpq_array_enable)
5066                         reply_post_free = (long)
5067                             ioc->reply_post[++index].reply_post_free;
5068                 else
5069                         reply_post_free += reply_post_free_sz;
5070         }
5071  skip_init_reply_post_free_queue:
5072
5073         r = _base_send_ioc_init(ioc, sleep_flag);
5074         if (r)
5075                 return r;
5076
5077         /* initialize reply free host index */
5078         ioc->reply_free_host_index = ioc->reply_free_queue_depth - 1;
5079         writel(ioc->reply_free_host_index, &ioc->chip->ReplyFreeHostIndex);
5080
5081         /* initialize reply post host index */
5082         list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
5083                 if (ioc->msix96_vector)
5084                         writel((reply_q->msix_index & 7)<<
5085                            MPI2_RPHI_MSIX_INDEX_SHIFT,
5086                            ioc->replyPostRegisterIndex[reply_q->msix_index/8]);
5087                 else
5088                         writel(reply_q->msix_index <<
5089                                 MPI2_RPHI_MSIX_INDEX_SHIFT,
5090                                 &ioc->chip->ReplyPostHostIndex);
5091
5092                 if (!_base_is_controller_msix_enabled(ioc))
5093                         goto skip_init_reply_post_host_index;
5094         }
5095
5096  skip_init_reply_post_host_index:
5097
5098         _base_unmask_interrupts(ioc);
5099         r = _base_event_notification(ioc, sleep_flag);
5100         if (r)
5101                 return r;
5102
5103         if (sleep_flag == CAN_SLEEP)
5104                 _base_static_config_pages(ioc);
5105
5106
5107         if (ioc->is_driver_loading) {
5108
5109                 if (ioc->is_warpdrive && ioc->manu_pg10.OEMIdentifier
5110                     == 0x80) {
5111                         hide_flag = (u8) (
5112                             le32_to_cpu(ioc->manu_pg10.OEMSpecificFlags0) &
5113                             MFG_PAGE10_HIDE_SSDS_MASK);
5114                         if (hide_flag != MFG_PAGE10_HIDE_SSDS_MASK)
5115                                 ioc->mfg_pg10_hide_flag = hide_flag;
5116                 }
5117
5118                 ioc->wait_for_discovery_to_complete =
5119                     _base_determine_wait_on_discovery(ioc);
5120
5121                 return r; /* scan_start and scan_finished support */
5122         }
5123
5124         r = _base_send_port_enable(ioc, sleep_flag);
5125         if (r)
5126                 return r;
5127
5128         return r;
5129 }
5130
5131 /**
5132  * mpt3sas_base_free_resources - free resources controller resources
5133  * @ioc: per adapter object
5134  *
5135  * Return nothing.
5136  */
5137 void
5138 mpt3sas_base_free_resources(struct MPT3SAS_ADAPTER *ioc)
5139 {
5140         dexitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
5141             __func__));
5142
5143         /* synchronizing freeing resource with pci_access_mutex lock */
5144         mutex_lock(&ioc->pci_access_mutex);
5145         if (ioc->chip_phys && ioc->chip) {
5146                 _base_mask_interrupts(ioc);
5147                 ioc->shost_recovery = 1;
5148                 _base_make_ioc_ready(ioc, CAN_SLEEP, SOFT_RESET);
5149                 ioc->shost_recovery = 0;
5150         }
5151
5152         mpt3sas_base_unmap_resources(ioc);
5153         mutex_unlock(&ioc->pci_access_mutex);
5154         return;
5155 }
5156
5157 /**
5158  * mpt3sas_base_attach - attach controller instance
5159  * @ioc: per adapter object
5160  *
5161  * Returns 0 for success, non-zero for failure.
5162  */
5163 int
5164 mpt3sas_base_attach(struct MPT3SAS_ADAPTER *ioc)
5165 {
5166         int r, i;
5167         int cpu_id, last_cpu_id = 0;
5168
5169         dinitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
5170             __func__));
5171
5172         /* setup cpu_msix_table */
5173         ioc->cpu_count = num_online_cpus();
5174         for_each_online_cpu(cpu_id)
5175                 last_cpu_id = cpu_id;
5176         ioc->cpu_msix_table_sz = last_cpu_id + 1;
5177         ioc->cpu_msix_table = kzalloc(ioc->cpu_msix_table_sz, GFP_KERNEL);
5178         ioc->reply_queue_count = 1;
5179         if (!ioc->cpu_msix_table) {
5180                 dfailprintk(ioc, pr_info(MPT3SAS_FMT
5181                         "allocation for cpu_msix_table failed!!!\n",
5182                         ioc->name));
5183                 r = -ENOMEM;
5184                 goto out_free_resources;
5185         }
5186
5187         if (ioc->is_warpdrive) {
5188                 ioc->reply_post_host_index = kcalloc(ioc->cpu_msix_table_sz,
5189                     sizeof(resource_size_t *), GFP_KERNEL);
5190                 if (!ioc->reply_post_host_index) {
5191                         dfailprintk(ioc, pr_info(MPT3SAS_FMT "allocation "
5192                                 "for cpu_msix_table failed!!!\n", ioc->name));
5193                         r = -ENOMEM;
5194                         goto out_free_resources;
5195                 }
5196         }
5197
5198         ioc->rdpq_array_enable_assigned = 0;
5199         ioc->dma_mask = 0;
5200         r = mpt3sas_base_map_resources(ioc);
5201         if (r)
5202                 goto out_free_resources;
5203
5204         if (ioc->is_warpdrive) {
5205                 ioc->reply_post_host_index[0] = (resource_size_t __iomem *)
5206                     &ioc->chip->ReplyPostHostIndex;
5207
5208                 for (i = 1; i < ioc->cpu_msix_table_sz; i++)
5209                         ioc->reply_post_host_index[i] =
5210                         (resource_size_t __iomem *)
5211                         ((u8 __iomem *)&ioc->chip->Doorbell + (0x4000 + ((i - 1)
5212                         * 4)));
5213         }
5214
5215         pci_set_drvdata(ioc->pdev, ioc->shost);
5216         r = _base_get_ioc_facts(ioc, CAN_SLEEP);
5217         if (r)
5218                 goto out_free_resources;
5219
5220         switch (ioc->hba_mpi_version_belonged) {
5221         case MPI2_VERSION:
5222                 ioc->build_sg_scmd = &_base_build_sg_scmd;
5223                 ioc->build_sg = &_base_build_sg;
5224                 ioc->build_zero_len_sge = &_base_build_zero_len_sge;
5225                 break;
5226         case MPI25_VERSION:
5227                 /*
5228                  * In SAS3.0,
5229                  * SCSI_IO, SMP_PASSTHRU, SATA_PASSTHRU, Target Assist, and
5230                  * Target Status - all require the IEEE formated scatter gather
5231                  * elements.
5232                  */
5233                 ioc->build_sg_scmd = &_base_build_sg_scmd_ieee;
5234                 ioc->build_sg = &_base_build_sg_ieee;
5235                 ioc->build_zero_len_sge = &_base_build_zero_len_sge_ieee;
5236                 ioc->sge_size_ieee = sizeof(Mpi2IeeeSgeSimple64_t);
5237                 break;
5238         }
5239
5240         /*
5241          * These function pointers for other requests that don't
5242          * the require IEEE scatter gather elements.
5243          *
5244          * For example Configuration Pages and SAS IOUNIT Control don't.
5245          */
5246         ioc->build_sg_mpi = &_base_build_sg;
5247         ioc->build_zero_len_sge_mpi = &_base_build_zero_len_sge;
5248
5249         r = _base_make_ioc_ready(ioc, CAN_SLEEP, SOFT_RESET);
5250         if (r)
5251                 goto out_free_resources;
5252
5253         ioc->pfacts = kcalloc(ioc->facts.NumberOfPorts,
5254             sizeof(struct mpt3sas_port_facts), GFP_KERNEL);
5255         if (!ioc->pfacts) {
5256                 r = -ENOMEM;
5257                 goto out_free_resources;
5258         }
5259
5260         for (i = 0 ; i < ioc->facts.NumberOfPorts; i++) {
5261                 r = _base_get_port_facts(ioc, i, CAN_SLEEP);
5262                 if (r)
5263                         goto out_free_resources;
5264         }
5265
5266         r = _base_allocate_memory_pools(ioc, CAN_SLEEP);
5267         if (r)
5268                 goto out_free_resources;
5269
5270         init_waitqueue_head(&ioc->reset_wq);
5271
5272         /* allocate memory pd handle bitmask list */
5273         ioc->pd_handles_sz = (ioc->facts.MaxDevHandle / 8);
5274         if (ioc->facts.MaxDevHandle % 8)
5275                 ioc->pd_handles_sz++;
5276         ioc->pd_handles = kzalloc(ioc->pd_handles_sz,
5277             GFP_KERNEL);
5278         if (!ioc->pd_handles) {
5279                 r = -ENOMEM;
5280                 goto out_free_resources;
5281         }
5282         ioc->blocking_handles = kzalloc(ioc->pd_handles_sz,
5283             GFP_KERNEL);
5284         if (!ioc->blocking_handles) {
5285                 r = -ENOMEM;
5286                 goto out_free_resources;
5287         }
5288
5289         ioc->fwfault_debug = mpt3sas_fwfault_debug;
5290
5291         /* base internal command bits */
5292         mutex_init(&ioc->base_cmds.mutex);
5293         ioc->base_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
5294         ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5295
5296         /* port_enable command bits */
5297         ioc->port_enable_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
5298         ioc->port_enable_cmds.status = MPT3_CMD_NOT_USED;
5299
5300         /* transport internal command bits */
5301         ioc->transport_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
5302         ioc->transport_cmds.status = MPT3_CMD_NOT_USED;
5303         mutex_init(&ioc->transport_cmds.mutex);
5304
5305         /* scsih internal command bits */
5306         ioc->scsih_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
5307         ioc->scsih_cmds.status = MPT3_CMD_NOT_USED;
5308         mutex_init(&ioc->scsih_cmds.mutex);
5309
5310         /* task management internal command bits */
5311         ioc->tm_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
5312         ioc->tm_cmds.status = MPT3_CMD_NOT_USED;
5313         mutex_init(&ioc->tm_cmds.mutex);
5314
5315         /* config page internal command bits */
5316         ioc->config_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
5317         ioc->config_cmds.status = MPT3_CMD_NOT_USED;
5318         mutex_init(&ioc->config_cmds.mutex);
5319
5320         /* ctl module internal command bits */
5321         ioc->ctl_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
5322         ioc->ctl_cmds.sense = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
5323         ioc->ctl_cmds.status = MPT3_CMD_NOT_USED;
5324         mutex_init(&ioc->ctl_cmds.mutex);
5325
5326         if (!ioc->base_cmds.reply || !ioc->transport_cmds.reply ||
5327             !ioc->scsih_cmds.reply || !ioc->tm_cmds.reply ||
5328             !ioc->config_cmds.reply || !ioc->ctl_cmds.reply ||
5329             !ioc->ctl_cmds.sense) {
5330                 r = -ENOMEM;
5331                 goto out_free_resources;
5332         }
5333
5334         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
5335                 ioc->event_masks[i] = -1;
5336
5337         /* here we enable the events we care about */
5338         _base_unmask_events(ioc, MPI2_EVENT_SAS_DISCOVERY);
5339         _base_unmask_events(ioc, MPI2_EVENT_SAS_BROADCAST_PRIMITIVE);
5340         _base_unmask_events(ioc, MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST);
5341         _base_unmask_events(ioc, MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE);
5342         _base_unmask_events(ioc, MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE);
5343         _base_unmask_events(ioc, MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST);
5344         _base_unmask_events(ioc, MPI2_EVENT_IR_VOLUME);
5345         _base_unmask_events(ioc, MPI2_EVENT_IR_PHYSICAL_DISK);
5346         _base_unmask_events(ioc, MPI2_EVENT_IR_OPERATION_STATUS);
5347         _base_unmask_events(ioc, MPI2_EVENT_LOG_ENTRY_ADDED);
5348         _base_unmask_events(ioc, MPI2_EVENT_TEMP_THRESHOLD);
5349
5350         r = _base_make_ioc_operational(ioc, CAN_SLEEP);
5351         if (r)
5352                 goto out_free_resources;
5353
5354         ioc->non_operational_loop = 0;
5355         return 0;
5356
5357  out_free_resources:
5358
5359         ioc->remove_host = 1;
5360
5361         mpt3sas_base_free_resources(ioc);
5362         _base_release_memory_pools(ioc);
5363         pci_set_drvdata(ioc->pdev, NULL);
5364         kfree(ioc->cpu_msix_table);
5365         if (ioc->is_warpdrive)
5366                 kfree(ioc->reply_post_host_index);
5367         kfree(ioc->pd_handles);
5368         kfree(ioc->blocking_handles);
5369         kfree(ioc->tm_cmds.reply);
5370         kfree(ioc->transport_cmds.reply);
5371         kfree(ioc->scsih_cmds.reply);
5372         kfree(ioc->config_cmds.reply);
5373         kfree(ioc->base_cmds.reply);
5374         kfree(ioc->port_enable_cmds.reply);
5375         kfree(ioc->ctl_cmds.reply);
5376         kfree(ioc->ctl_cmds.sense);
5377         kfree(ioc->pfacts);
5378         ioc->ctl_cmds.reply = NULL;
5379         ioc->base_cmds.reply = NULL;
5380         ioc->tm_cmds.reply = NULL;
5381         ioc->scsih_cmds.reply = NULL;
5382         ioc->transport_cmds.reply = NULL;
5383         ioc->config_cmds.reply = NULL;
5384         ioc->pfacts = NULL;
5385         return r;
5386 }
5387
5388
5389 /**
5390  * mpt3sas_base_detach - remove controller instance
5391  * @ioc: per adapter object
5392  *
5393  * Return nothing.
5394  */
5395 void
5396 mpt3sas_base_detach(struct MPT3SAS_ADAPTER *ioc)
5397 {
5398         dexitprintk(ioc, pr_info(MPT3SAS_FMT "%s\n", ioc->name,
5399             __func__));
5400
5401         mpt3sas_base_stop_watchdog(ioc);
5402         mpt3sas_base_free_resources(ioc);
5403         _base_release_memory_pools(ioc);
5404         pci_set_drvdata(ioc->pdev, NULL);
5405         kfree(ioc->cpu_msix_table);
5406         if (ioc->is_warpdrive)
5407                 kfree(ioc->reply_post_host_index);
5408         kfree(ioc->pd_handles);
5409         kfree(ioc->blocking_handles);
5410         kfree(ioc->pfacts);
5411         kfree(ioc->ctl_cmds.reply);
5412         kfree(ioc->ctl_cmds.sense);
5413         kfree(ioc->base_cmds.reply);
5414         kfree(ioc->port_enable_cmds.reply);
5415         kfree(ioc->tm_cmds.reply);
5416         kfree(ioc->transport_cmds.reply);
5417         kfree(ioc->scsih_cmds.reply);
5418         kfree(ioc->config_cmds.reply);
5419 }
5420
5421 /**
5422  * _base_reset_handler - reset callback handler (for base)
5423  * @ioc: per adapter object
5424  * @reset_phase: phase
5425  *
5426  * The handler for doing any required cleanup or initialization.
5427  *
5428  * The reset phase can be MPT3_IOC_PRE_RESET, MPT3_IOC_AFTER_RESET,
5429  * MPT3_IOC_DONE_RESET
5430  *
5431  * Return nothing.
5432  */
5433 static void
5434 _base_reset_handler(struct MPT3SAS_ADAPTER *ioc, int reset_phase)
5435 {
5436         mpt3sas_scsih_reset_handler(ioc, reset_phase);
5437         mpt3sas_ctl_reset_handler(ioc, reset_phase);
5438         switch (reset_phase) {
5439         case MPT3_IOC_PRE_RESET:
5440                 dtmprintk(ioc, pr_info(MPT3SAS_FMT
5441                 "%s: MPT3_IOC_PRE_RESET\n", ioc->name, __func__));
5442                 break;
5443         case MPT3_IOC_AFTER_RESET:
5444                 dtmprintk(ioc, pr_info(MPT3SAS_FMT
5445                 "%s: MPT3_IOC_AFTER_RESET\n", ioc->name, __func__));
5446                 if (ioc->transport_cmds.status & MPT3_CMD_PENDING) {
5447                         ioc->transport_cmds.status |= MPT3_CMD_RESET;
5448                         mpt3sas_base_free_smid(ioc, ioc->transport_cmds.smid);
5449                         complete(&ioc->transport_cmds.done);
5450                 }
5451                 if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
5452                         ioc->base_cmds.status |= MPT3_CMD_RESET;
5453                         mpt3sas_base_free_smid(ioc, ioc->base_cmds.smid);
5454                         complete(&ioc->base_cmds.done);
5455                 }
5456                 if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
5457                         ioc->port_enable_failed = 1;
5458                         ioc->port_enable_cmds.status |= MPT3_CMD_RESET;
5459                         mpt3sas_base_free_smid(ioc, ioc->port_enable_cmds.smid);
5460                         if (ioc->is_driver_loading) {
5461                                 ioc->start_scan_failed =
5462                                     MPI2_IOCSTATUS_INTERNAL_ERROR;
5463                                 ioc->start_scan = 0;
5464                                 ioc->port_enable_cmds.status =
5465                                     MPT3_CMD_NOT_USED;
5466                         } else
5467                                 complete(&ioc->port_enable_cmds.done);
5468                 }
5469                 if (ioc->config_cmds.status & MPT3_CMD_PENDING) {
5470                         ioc->config_cmds.status |= MPT3_CMD_RESET;
5471                         mpt3sas_base_free_smid(ioc, ioc->config_cmds.smid);
5472                         ioc->config_cmds.smid = USHRT_MAX;
5473                         complete(&ioc->config_cmds.done);
5474                 }
5475                 break;
5476         case MPT3_IOC_DONE_RESET:
5477                 dtmprintk(ioc, pr_info(MPT3SAS_FMT
5478                         "%s: MPT3_IOC_DONE_RESET\n", ioc->name, __func__));
5479                 break;
5480         }
5481 }
5482
5483 /**
5484  * _wait_for_commands_to_complete - reset controller
5485  * @ioc: Pointer to MPT_ADAPTER structure
5486  * @sleep_flag: CAN_SLEEP or NO_SLEEP
5487  *
5488  * This function waiting(3s) for all pending commands to complete
5489  * prior to putting controller in reset.
5490  */
5491 static void
5492 _wait_for_commands_to_complete(struct MPT3SAS_ADAPTER *ioc, int sleep_flag)
5493 {
5494         u32 ioc_state;
5495         unsigned long flags;
5496         u16 i;
5497
5498         ioc->pending_io_count = 0;
5499         if (sleep_flag != CAN_SLEEP)
5500                 return;
5501
5502         ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
5503         if ((ioc_state & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_OPERATIONAL)
5504                 return;
5505
5506         /* pending command count */
5507         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
5508         for (i = 0; i < ioc->scsiio_depth; i++)
5509                 if (ioc->scsi_lookup[i].cb_idx != 0xFF)
5510                         ioc->pending_io_count++;
5511         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
5512
5513         if (!ioc->pending_io_count)
5514                 return;
5515
5516         /* wait for pending commands to complete */
5517         wait_event_timeout(ioc->reset_wq, ioc->pending_io_count == 0, 10 * HZ);
5518 }
5519
5520 /**
5521  * mpt3sas_base_hard_reset_handler - reset controller
5522  * @ioc: Pointer to MPT_ADAPTER structure
5523  * @sleep_flag: CAN_SLEEP or NO_SLEEP
5524  * @type: FORCE_BIG_HAMMER or SOFT_RESET
5525  *
5526  * Returns 0 for success, non-zero for failure.
5527  */
5528 int
5529 mpt3sas_base_hard_reset_handler(struct MPT3SAS_ADAPTER *ioc, int sleep_flag,
5530         enum reset_type type)
5531 {
5532         int r;
5533         unsigned long flags;
5534         u32 ioc_state;
5535         u8 is_fault = 0, is_trigger = 0;
5536
5537         dtmprintk(ioc, pr_info(MPT3SAS_FMT "%s: enter\n", ioc->name,
5538             __func__));
5539
5540         if (ioc->pci_error_recovery) {
5541                 pr_err(MPT3SAS_FMT "%s: pci error recovery reset\n",
5542                     ioc->name, __func__);
5543                 r = 0;
5544                 goto out_unlocked;
5545         }
5546
5547         if (mpt3sas_fwfault_debug)
5548                 mpt3sas_halt_firmware(ioc);
5549
5550         /* TODO - What we really should be doing is pulling
5551          * out all the code associated with NO_SLEEP; its never used.
5552          * That is legacy code from mpt fusion driver, ported over.
5553          * I will leave this BUG_ON here for now till its been resolved.
5554          */
5555         BUG_ON(sleep_flag == NO_SLEEP);
5556
5557         /* wait for an active reset in progress to complete */
5558         if (!mutex_trylock(&ioc->reset_in_progress_mutex)) {
5559                 do {
5560                         ssleep(1);
5561                 } while (ioc->shost_recovery == 1);
5562                 dtmprintk(ioc, pr_info(MPT3SAS_FMT "%s: exit\n", ioc->name,
5563                     __func__));
5564                 return ioc->ioc_reset_in_progress_status;
5565         }
5566
5567         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
5568         ioc->shost_recovery = 1;
5569         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
5570
5571         if ((ioc->diag_buffer_status[MPI2_DIAG_BUF_TYPE_TRACE] &
5572             MPT3_DIAG_BUFFER_IS_REGISTERED) &&
5573             (!(ioc->diag_buffer_status[MPI2_DIAG_BUF_TYPE_TRACE] &
5574             MPT3_DIAG_BUFFER_IS_RELEASED))) {
5575                 is_trigger = 1;
5576                 ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
5577                 if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT)
5578                         is_fault = 1;
5579         }
5580         _base_reset_handler(ioc, MPT3_IOC_PRE_RESET);
5581         _wait_for_commands_to_complete(ioc, sleep_flag);
5582         _base_mask_interrupts(ioc);
5583         r = _base_make_ioc_ready(ioc, sleep_flag, type);
5584         if (r)
5585                 goto out;
5586         _base_reset_handler(ioc, MPT3_IOC_AFTER_RESET);
5587
5588         /* If this hard reset is called while port enable is active, then
5589          * there is no reason to call make_ioc_operational
5590          */
5591         if (ioc->is_driver_loading && ioc->port_enable_failed) {
5592                 ioc->remove_host = 1;
5593                 r = -EFAULT;
5594                 goto out;
5595         }
5596         r = _base_get_ioc_facts(ioc, CAN_SLEEP);
5597         if (r)
5598                 goto out;
5599
5600         if (ioc->rdpq_array_enable && !ioc->rdpq_array_capable)
5601                 panic("%s: Issue occurred with flashing controller firmware."
5602                       "Please reboot the system and ensure that the correct"
5603                       " firmware version is running\n", ioc->name);
5604
5605         r = _base_make_ioc_operational(ioc, sleep_flag);
5606         if (!r)
5607                 _base_reset_handler(ioc, MPT3_IOC_DONE_RESET);
5608
5609  out:
5610         dtmprintk(ioc, pr_info(MPT3SAS_FMT "%s: %s\n",
5611             ioc->name, __func__, ((r == 0) ? "SUCCESS" : "FAILED")));
5612
5613         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
5614         ioc->ioc_reset_in_progress_status = r;
5615         ioc->shost_recovery = 0;
5616         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
5617         ioc->ioc_reset_count++;
5618         mutex_unlock(&ioc->reset_in_progress_mutex);
5619
5620  out_unlocked:
5621         if ((r == 0) && is_trigger) {
5622                 if (is_fault)
5623                         mpt3sas_trigger_master(ioc, MASTER_TRIGGER_FW_FAULT);
5624                 else
5625                         mpt3sas_trigger_master(ioc,
5626                             MASTER_TRIGGER_ADAPTER_RESET);
5627         }
5628         dtmprintk(ioc, pr_info(MPT3SAS_FMT "%s: exit\n", ioc->name,
5629             __func__));
5630         return r;
5631 }