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