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