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