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