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