[SCSI] mpt2sas : the sanity check in base_interrupt needs to be on dword boundary
[linux-2.6] / 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-2008  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/version.h>
46 #include <linux/kernel.h>
47 #include <linux/module.h>
48 #include <linux/errno.h>
49 #include <linux/init.h>
50 #include <linux/slab.h>
51 #include <linux/types.h>
52 #include <linux/pci.h>
53 #include <linux/kdev_t.h>
54 #include <linux/blkdev.h>
55 #include <linux/delay.h>
56 #include <linux/interrupt.h>
57 #include <linux/dma-mapping.h>
58 #include <linux/sort.h>
59 #include <linux/io.h>
60
61 #include "mpt2sas_base.h"
62
63 static MPT_CALLBACK     mpt_callbacks[MPT_MAX_CALLBACKS];
64
65 #define FAULT_POLLING_INTERVAL 1000 /* in milliseconds */
66 #define MPT2SAS_MAX_REQUEST_QUEUE 500 /* maximum controller queue depth */
67
68 static int max_queue_depth = -1;
69 module_param(max_queue_depth, int, 0);
70 MODULE_PARM_DESC(max_queue_depth, " max controller queue depth ");
71
72 static int max_sgl_entries = -1;
73 module_param(max_sgl_entries, int, 0);
74 MODULE_PARM_DESC(max_sgl_entries, " max sg entries ");
75
76 static int msix_disable = -1;
77 module_param(msix_disable, int, 0);
78 MODULE_PARM_DESC(msix_disable, " disable msix routed interrupts (default=0)");
79
80 /**
81  * _base_fault_reset_work - workq handling ioc fault conditions
82  * @work: input argument, used to derive ioc
83  * Context: sleep.
84  *
85  * Return nothing.
86  */
87 static void
88 _base_fault_reset_work(struct work_struct *work)
89 {
90         struct MPT2SAS_ADAPTER *ioc =
91             container_of(work, struct MPT2SAS_ADAPTER, fault_reset_work.work);
92         unsigned long    flags;
93         u32 doorbell;
94         int rc;
95
96         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
97         if (ioc->ioc_reset_in_progress)
98                 goto rearm_timer;
99         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
100
101         doorbell = mpt2sas_base_get_iocstate(ioc, 0);
102         if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
103                 rc = mpt2sas_base_hard_reset_handler(ioc, CAN_SLEEP,
104                     FORCE_BIG_HAMMER);
105                 printk(MPT2SAS_WARN_FMT "%s: hard reset: %s\n", ioc->name,
106                     __func__, (rc == 0) ? "success" : "failed");
107                 doorbell = mpt2sas_base_get_iocstate(ioc, 0);
108                 if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT)
109                         mpt2sas_base_fault_info(ioc, doorbell &
110                             MPI2_DOORBELL_DATA_MASK);
111         }
112
113         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
114  rearm_timer:
115         if (ioc->fault_reset_work_q)
116                 queue_delayed_work(ioc->fault_reset_work_q,
117                     &ioc->fault_reset_work,
118                     msecs_to_jiffies(FAULT_POLLING_INTERVAL));
119         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
120 }
121
122 #ifdef CONFIG_SCSI_MPT2SAS_LOGGING
123 /**
124  * _base_sas_ioc_info - verbose translation of the ioc status
125  * @ioc: pointer to scsi command object
126  * @mpi_reply: reply mf payload returned from firmware
127  * @request_hdr: request mf
128  *
129  * Return nothing.
130  */
131 static void
132 _base_sas_ioc_info(struct MPT2SAS_ADAPTER *ioc, MPI2DefaultReply_t *mpi_reply,
133      MPI2RequestHeader_t *request_hdr)
134 {
135         u16 ioc_status = le16_to_cpu(mpi_reply->IOCStatus) &
136             MPI2_IOCSTATUS_MASK;
137         char *desc = NULL;
138         u16 frame_sz;
139         char *func_str = NULL;
140
141         /* SCSI_IO, RAID_PASS are handled from _scsih_scsi_ioc_info */
142         if (request_hdr->Function == MPI2_FUNCTION_SCSI_IO_REQUEST ||
143             request_hdr->Function == MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH ||
144             request_hdr->Function == MPI2_FUNCTION_EVENT_NOTIFICATION)
145                 return;
146
147         switch (ioc_status) {
148
149 /****************************************************************************
150 *  Common IOCStatus values for all replies
151 ****************************************************************************/
152
153         case MPI2_IOCSTATUS_INVALID_FUNCTION:
154                 desc = "invalid function";
155                 break;
156         case MPI2_IOCSTATUS_BUSY:
157                 desc = "busy";
158                 break;
159         case MPI2_IOCSTATUS_INVALID_SGL:
160                 desc = "invalid sgl";
161                 break;
162         case MPI2_IOCSTATUS_INTERNAL_ERROR:
163                 desc = "internal error";
164                 break;
165         case MPI2_IOCSTATUS_INVALID_VPID:
166                 desc = "invalid vpid";
167                 break;
168         case MPI2_IOCSTATUS_INSUFFICIENT_RESOURCES:
169                 desc = "insufficient resources";
170                 break;
171         case MPI2_IOCSTATUS_INVALID_FIELD:
172                 desc = "invalid field";
173                 break;
174         case MPI2_IOCSTATUS_INVALID_STATE:
175                 desc = "invalid state";
176                 break;
177         case MPI2_IOCSTATUS_OP_STATE_NOT_SUPPORTED:
178                 desc = "op state not supported";
179                 break;
180
181 /****************************************************************************
182 *  Config IOCStatus values
183 ****************************************************************************/
184
185         case MPI2_IOCSTATUS_CONFIG_INVALID_ACTION:
186                 desc = "config invalid action";
187                 break;
188         case MPI2_IOCSTATUS_CONFIG_INVALID_TYPE:
189                 desc = "config invalid type";
190                 break;
191         case MPI2_IOCSTATUS_CONFIG_INVALID_PAGE:
192                 desc = "config invalid page";
193                 break;
194         case MPI2_IOCSTATUS_CONFIG_INVALID_DATA:
195                 desc = "config invalid data";
196                 break;
197         case MPI2_IOCSTATUS_CONFIG_NO_DEFAULTS:
198                 desc = "config no defaults";
199                 break;
200         case MPI2_IOCSTATUS_CONFIG_CANT_COMMIT:
201                 desc = "config cant commit";
202                 break;
203
204 /****************************************************************************
205 *  SCSI IO Reply
206 ****************************************************************************/
207
208         case MPI2_IOCSTATUS_SCSI_RECOVERED_ERROR:
209         case MPI2_IOCSTATUS_SCSI_INVALID_DEVHANDLE:
210         case MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
211         case MPI2_IOCSTATUS_SCSI_DATA_OVERRUN:
212         case MPI2_IOCSTATUS_SCSI_DATA_UNDERRUN:
213         case MPI2_IOCSTATUS_SCSI_IO_DATA_ERROR:
214         case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
215         case MPI2_IOCSTATUS_SCSI_TASK_TERMINATED:
216         case MPI2_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
217         case MPI2_IOCSTATUS_SCSI_TASK_MGMT_FAILED:
218         case MPI2_IOCSTATUS_SCSI_IOC_TERMINATED:
219         case MPI2_IOCSTATUS_SCSI_EXT_TERMINATED:
220                 break;
221
222 /****************************************************************************
223 *  For use by SCSI Initiator and SCSI Target end-to-end data protection
224 ****************************************************************************/
225
226         case MPI2_IOCSTATUS_EEDP_GUARD_ERROR:
227                 desc = "eedp guard error";
228                 break;
229         case MPI2_IOCSTATUS_EEDP_REF_TAG_ERROR:
230                 desc = "eedp ref tag error";
231                 break;
232         case MPI2_IOCSTATUS_EEDP_APP_TAG_ERROR:
233                 desc = "eedp app tag error";
234                 break;
235
236 /****************************************************************************
237 *  SCSI Target values
238 ****************************************************************************/
239
240         case MPI2_IOCSTATUS_TARGET_INVALID_IO_INDEX:
241                 desc = "target invalid io index";
242                 break;
243         case MPI2_IOCSTATUS_TARGET_ABORTED:
244                 desc = "target aborted";
245                 break;
246         case MPI2_IOCSTATUS_TARGET_NO_CONN_RETRYABLE:
247                 desc = "target no conn retryable";
248                 break;
249         case MPI2_IOCSTATUS_TARGET_NO_CONNECTION:
250                 desc = "target no connection";
251                 break;
252         case MPI2_IOCSTATUS_TARGET_XFER_COUNT_MISMATCH:
253                 desc = "target xfer count mismatch";
254                 break;
255         case MPI2_IOCSTATUS_TARGET_DATA_OFFSET_ERROR:
256                 desc = "target data offset error";
257                 break;
258         case MPI2_IOCSTATUS_TARGET_TOO_MUCH_WRITE_DATA:
259                 desc = "target too much write data";
260                 break;
261         case MPI2_IOCSTATUS_TARGET_IU_TOO_SHORT:
262                 desc = "target iu too short";
263                 break;
264         case MPI2_IOCSTATUS_TARGET_ACK_NAK_TIMEOUT:
265                 desc = "target ack nak timeout";
266                 break;
267         case MPI2_IOCSTATUS_TARGET_NAK_RECEIVED:
268                 desc = "target nak received";
269                 break;
270
271 /****************************************************************************
272 *  Serial Attached SCSI values
273 ****************************************************************************/
274
275         case MPI2_IOCSTATUS_SAS_SMP_REQUEST_FAILED:
276                 desc = "smp request failed";
277                 break;
278         case MPI2_IOCSTATUS_SAS_SMP_DATA_OVERRUN:
279                 desc = "smp data overrun";
280                 break;
281
282 /****************************************************************************
283 *  Diagnostic Buffer Post / Diagnostic Release values
284 ****************************************************************************/
285
286         case MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED:
287                 desc = "diagnostic released";
288                 break;
289         default:
290                 break;
291         }
292
293         if (!desc)
294                 return;
295
296         switch (request_hdr->Function) {
297         case MPI2_FUNCTION_CONFIG:
298                 frame_sz = sizeof(Mpi2ConfigRequest_t) + ioc->sge_size;
299                 func_str = "config_page";
300                 break;
301         case MPI2_FUNCTION_SCSI_TASK_MGMT:
302                 frame_sz = sizeof(Mpi2SCSITaskManagementRequest_t);
303                 func_str = "task_mgmt";
304                 break;
305         case MPI2_FUNCTION_SAS_IO_UNIT_CONTROL:
306                 frame_sz = sizeof(Mpi2SasIoUnitControlRequest_t);
307                 func_str = "sas_iounit_ctl";
308                 break;
309         case MPI2_FUNCTION_SCSI_ENCLOSURE_PROCESSOR:
310                 frame_sz = sizeof(Mpi2SepRequest_t);
311                 func_str = "enclosure";
312                 break;
313         case MPI2_FUNCTION_IOC_INIT:
314                 frame_sz = sizeof(Mpi2IOCInitRequest_t);
315                 func_str = "ioc_init";
316                 break;
317         case MPI2_FUNCTION_PORT_ENABLE:
318                 frame_sz = sizeof(Mpi2PortEnableRequest_t);
319                 func_str = "port_enable";
320                 break;
321         case MPI2_FUNCTION_SMP_PASSTHROUGH:
322                 frame_sz = sizeof(Mpi2SmpPassthroughRequest_t) + ioc->sge_size;
323                 func_str = "smp_passthru";
324                 break;
325         default:
326                 frame_sz = 32;
327                 func_str = "unknown";
328                 break;
329         }
330
331         printk(MPT2SAS_WARN_FMT "ioc_status: %s(0x%04x), request(0x%p),"
332             " (%s)\n", ioc->name, desc, ioc_status, request_hdr, func_str);
333
334         _debug_dump_mf(request_hdr, frame_sz/4);
335 }
336
337 /**
338  * _base_display_event_data - verbose translation of firmware asyn events
339  * @ioc: pointer to scsi command object
340  * @mpi_reply: reply mf payload returned from firmware
341  *
342  * Return nothing.
343  */
344 static void
345 _base_display_event_data(struct MPT2SAS_ADAPTER *ioc,
346     Mpi2EventNotificationReply_t *mpi_reply)
347 {
348         char *desc = NULL;
349         u16 event;
350
351         if (!(ioc->logging_level & MPT_DEBUG_EVENTS))
352                 return;
353
354         event = le16_to_cpu(mpi_reply->Event);
355
356         switch (event) {
357         case MPI2_EVENT_LOG_DATA:
358                 desc = "Log Data";
359                 break;
360         case MPI2_EVENT_STATE_CHANGE:
361                 desc = "Status Change";
362                 break;
363         case MPI2_EVENT_HARD_RESET_RECEIVED:
364                 desc = "Hard Reset Received";
365                 break;
366         case MPI2_EVENT_EVENT_CHANGE:
367                 desc = "Event Change";
368                 break;
369         case MPI2_EVENT_TASK_SET_FULL:
370                 desc = "Task Set Full";
371                 break;
372         case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
373                 desc = "Device Status Change";
374                 break;
375         case MPI2_EVENT_IR_OPERATION_STATUS:
376                 desc = "IR Operation Status";
377                 break;
378         case MPI2_EVENT_SAS_DISCOVERY:
379                 desc =  "Discovery";
380                 break;
381         case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
382                 desc = "SAS Broadcast Primitive";
383                 break;
384         case MPI2_EVENT_SAS_INIT_DEVICE_STATUS_CHANGE:
385                 desc = "SAS Init Device Status Change";
386                 break;
387         case MPI2_EVENT_SAS_INIT_TABLE_OVERFLOW:
388                 desc = "SAS Init Table Overflow";
389                 break;
390         case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
391                 desc = "SAS Topology Change List";
392                 break;
393         case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
394                 desc = "SAS Enclosure Device Status Change";
395                 break;
396         case MPI2_EVENT_IR_VOLUME:
397                 desc = "IR Volume";
398                 break;
399         case MPI2_EVENT_IR_PHYSICAL_DISK:
400                 desc = "IR Physical Disk";
401                 break;
402         case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
403                 desc = "IR Configuration Change List";
404                 break;
405         case MPI2_EVENT_LOG_ENTRY_ADDED:
406                 desc = "Log Entry Added";
407                 break;
408         }
409
410         if (!desc)
411                 return;
412
413         printk(MPT2SAS_INFO_FMT "%s\n", ioc->name, desc);
414 }
415 #endif
416
417 /**
418  * _base_sas_log_info - verbose translation of firmware log info
419  * @ioc: pointer to scsi command object
420  * @log_info: log info
421  *
422  * Return nothing.
423  */
424 static void
425 _base_sas_log_info(struct MPT2SAS_ADAPTER *ioc , u32 log_info)
426 {
427         union loginfo_type {
428                 u32     loginfo;
429                 struct {
430                         u32     subcode:16;
431                         u32     code:8;
432                         u32     originator:4;
433                         u32     bus_type:4;
434                 } dw;
435         };
436         union loginfo_type sas_loginfo;
437         char *originator_str = NULL;
438
439         sas_loginfo.loginfo = log_info;
440         if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
441                 return;
442
443         /* eat the loginfos associated with task aborts */
444         if (ioc->ignore_loginfos && (log_info == 30050000 || log_info ==
445             0x31140000 || log_info == 0x31130000))
446                 return;
447
448         switch (sas_loginfo.dw.originator) {
449         case 0:
450                 originator_str = "IOP";
451                 break;
452         case 1:
453                 originator_str = "PL";
454                 break;
455         case 2:
456                 originator_str = "IR";
457                 break;
458         }
459
460         printk(MPT2SAS_WARN_FMT "log_info(0x%08x): originator(%s), "
461             "code(0x%02x), sub_code(0x%04x)\n", ioc->name, log_info,
462              originator_str, sas_loginfo.dw.code,
463              sas_loginfo.dw.subcode);
464 }
465
466 /**
467  * mpt2sas_base_fault_info - verbose translation of firmware FAULT code
468  * @ioc: pointer to scsi command object
469  * @fault_code: fault code
470  *
471  * Return nothing.
472  */
473 void
474 mpt2sas_base_fault_info(struct MPT2SAS_ADAPTER *ioc , u16 fault_code)
475 {
476         printk(MPT2SAS_ERR_FMT "fault_state(0x%04x)!\n",
477             ioc->name, fault_code);
478 }
479
480 /**
481  * _base_display_reply_info -
482  * @ioc: pointer to scsi command object
483  * @smid: system request message index
484  * @VF_ID: virtual function id
485  * @reply: reply message frame(lower 32bit addr)
486  *
487  * Return nothing.
488  */
489 static void
490 _base_display_reply_info(struct MPT2SAS_ADAPTER *ioc, u16 smid, u8 VF_ID,
491     u32 reply)
492 {
493         MPI2DefaultReply_t *mpi_reply;
494         u16 ioc_status;
495
496         mpi_reply = mpt2sas_base_get_reply_virt_addr(ioc, reply);
497         ioc_status = le16_to_cpu(mpi_reply->IOCStatus);
498 #ifdef CONFIG_SCSI_MPT2SAS_LOGGING
499         if ((ioc_status & MPI2_IOCSTATUS_MASK) &&
500             (ioc->logging_level & MPT_DEBUG_REPLY)) {
501                 _base_sas_ioc_info(ioc , mpi_reply,
502                    mpt2sas_base_get_msg_frame(ioc, smid));
503         }
504 #endif
505         if (ioc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE)
506                 _base_sas_log_info(ioc, le32_to_cpu(mpi_reply->IOCLogInfo));
507 }
508
509 /**
510  * mpt2sas_base_done - base internal command completion routine
511  * @ioc: pointer to scsi command object
512  * @smid: system request message index
513  * @VF_ID: virtual function id
514  * @reply: reply message frame(lower 32bit addr)
515  *
516  * Return nothing.
517  */
518 void
519 mpt2sas_base_done(struct MPT2SAS_ADAPTER *ioc, u16 smid, u8 VF_ID, u32 reply)
520 {
521         MPI2DefaultReply_t *mpi_reply;
522
523         mpi_reply = mpt2sas_base_get_reply_virt_addr(ioc, reply);
524         if (mpi_reply && mpi_reply->Function == MPI2_FUNCTION_EVENT_ACK)
525                 return;
526
527         if (ioc->base_cmds.status == MPT2_CMD_NOT_USED)
528                 return;
529
530         ioc->base_cmds.status |= MPT2_CMD_COMPLETE;
531         if (mpi_reply) {
532                 ioc->base_cmds.status |= MPT2_CMD_REPLY_VALID;
533                 memcpy(ioc->base_cmds.reply, mpi_reply, mpi_reply->MsgLength*4);
534         }
535         ioc->base_cmds.status &= ~MPT2_CMD_PENDING;
536         complete(&ioc->base_cmds.done);
537 }
538
539 /**
540  * _base_async_event - main callback handler for firmware asyn events
541  * @ioc: pointer to scsi command object
542  * @VF_ID: virtual function id
543  * @reply: reply message frame(lower 32bit addr)
544  *
545  * Return nothing.
546  */
547 static void
548 _base_async_event(struct MPT2SAS_ADAPTER *ioc, u8 VF_ID, u32 reply)
549 {
550         Mpi2EventNotificationReply_t *mpi_reply;
551         Mpi2EventAckRequest_t *ack_request;
552         u16 smid;
553
554         mpi_reply = mpt2sas_base_get_reply_virt_addr(ioc, reply);
555         if (!mpi_reply)
556                 return;
557         if (mpi_reply->Function != MPI2_FUNCTION_EVENT_NOTIFICATION)
558                 return;
559 #ifdef CONFIG_SCSI_MPT2SAS_LOGGING
560         _base_display_event_data(ioc, mpi_reply);
561 #endif
562         if (!(mpi_reply->AckRequired & MPI2_EVENT_NOTIFICATION_ACK_REQUIRED))
563                 goto out;
564         smid = mpt2sas_base_get_smid(ioc, ioc->base_cb_idx);
565         if (!smid) {
566                 printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
567                     ioc->name, __func__);
568                 goto out;
569         }
570
571         ack_request = mpt2sas_base_get_msg_frame(ioc, smid);
572         memset(ack_request, 0, sizeof(Mpi2EventAckRequest_t));
573         ack_request->Function = MPI2_FUNCTION_EVENT_ACK;
574         ack_request->Event = mpi_reply->Event;
575         ack_request->EventContext = mpi_reply->EventContext;
576         ack_request->VF_ID = VF_ID;
577         mpt2sas_base_put_smid_default(ioc, smid, VF_ID);
578
579  out:
580
581         /* scsih callback handler */
582         mpt2sas_scsih_event_callback(ioc, VF_ID, reply);
583
584         /* ctl callback handler */
585         mpt2sas_ctl_event_callback(ioc, VF_ID, reply);
586 }
587
588 /**
589  * _base_mask_interrupts - disable interrupts
590  * @ioc: pointer to scsi command object
591  *
592  * Disabling ResetIRQ, Reply and Doorbell Interrupts
593  *
594  * Return nothing.
595  */
596 static void
597 _base_mask_interrupts(struct MPT2SAS_ADAPTER *ioc)
598 {
599         u32 him_register;
600
601         ioc->mask_interrupts = 1;
602         him_register = readl(&ioc->chip->HostInterruptMask);
603         him_register |= MPI2_HIM_DIM + MPI2_HIM_RIM + MPI2_HIM_RESET_IRQ_MASK;
604         writel(him_register, &ioc->chip->HostInterruptMask);
605         readl(&ioc->chip->HostInterruptMask);
606 }
607
608 /**
609  * _base_unmask_interrupts - enable interrupts
610  * @ioc: pointer to scsi command object
611  *
612  * Enabling only Reply Interrupts
613  *
614  * Return nothing.
615  */
616 static void
617 _base_unmask_interrupts(struct MPT2SAS_ADAPTER *ioc)
618 {
619         u32 him_register;
620
621         writel(0, &ioc->chip->HostInterruptStatus);
622         him_register = readl(&ioc->chip->HostInterruptMask);
623         him_register &= ~MPI2_HIM_RIM;
624         writel(him_register, &ioc->chip->HostInterruptMask);
625         ioc->mask_interrupts = 0;
626 }
627
628 /**
629  * _base_interrupt - MPT adapter (IOC) specific interrupt handler.
630  * @irq: irq number (not used)
631  * @bus_id: bus identifier cookie == pointer to MPT_ADAPTER structure
632  * @r: pt_regs pointer (not used)
633  *
634  * Return IRQ_HANDLE if processed, else IRQ_NONE.
635  */
636 static irqreturn_t
637 _base_interrupt(int irq, void *bus_id)
638 {
639         union reply_descriptor {
640                 u64 word;
641                 struct {
642                         u32 low;
643                         u32 high;
644                 } u;
645         };
646         union reply_descriptor rd;
647         u32 post_index, post_index_next, completed_cmds;
648         u8 request_desript_type;
649         u16 smid;
650         u8 cb_idx;
651         u32 reply;
652         u8 VF_ID;
653         int i;
654         struct MPT2SAS_ADAPTER *ioc = bus_id;
655
656         if (ioc->mask_interrupts)
657                 return IRQ_NONE;
658
659         post_index = ioc->reply_post_host_index;
660         request_desript_type = ioc->reply_post_free[post_index].
661             Default.ReplyFlags & MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
662         if (request_desript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
663                 return IRQ_NONE;
664
665         completed_cmds = 0;
666         do {
667                 rd.word = ioc->reply_post_free[post_index].Words;
668                 if (rd.u.low == UINT_MAX || rd.u.high == UINT_MAX)
669                         goto out;
670                 reply = 0;
671                 cb_idx = 0xFF;
672                 smid = le16_to_cpu(ioc->reply_post_free[post_index].
673                     Default.DescriptorTypeDependent1);
674                 VF_ID = ioc->reply_post_free[post_index].
675                     Default.VF_ID;
676                 if (request_desript_type ==
677                     MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY) {
678                         reply = le32_to_cpu(ioc->reply_post_free[post_index].
679                             AddressReply.ReplyFrameAddress);
680                 } else if (request_desript_type ==
681                     MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER)
682                         goto next;
683                 else if (request_desript_type ==
684                     MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS)
685                         goto next;
686                 if (smid)
687                         cb_idx = ioc->scsi_lookup[smid - 1].cb_idx;
688                 if (smid && cb_idx != 0xFF) {
689                         mpt_callbacks[cb_idx](ioc, smid, VF_ID, reply);
690                         if (reply)
691                                 _base_display_reply_info(ioc, smid, VF_ID,
692                                     reply);
693                         mpt2sas_base_free_smid(ioc, smid);
694                 }
695                 if (!smid)
696                         _base_async_event(ioc, VF_ID, reply);
697
698                 /* reply free queue handling */
699                 if (reply) {
700                         ioc->reply_free_host_index =
701                             (ioc->reply_free_host_index ==
702                             (ioc->reply_free_queue_depth - 1)) ?
703                             0 : ioc->reply_free_host_index + 1;
704                         ioc->reply_free[ioc->reply_free_host_index] =
705                             cpu_to_le32(reply);
706                         writel(ioc->reply_free_host_index,
707                             &ioc->chip->ReplyFreeHostIndex);
708                         wmb();
709                 }
710
711  next:
712                 post_index_next = (post_index == (ioc->reply_post_queue_depth -
713                     1)) ? 0 : post_index + 1;
714                 request_desript_type =
715                     ioc->reply_post_free[post_index_next].Default.ReplyFlags
716                     & MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
717                 completed_cmds++;
718                 if (request_desript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
719                         goto out;
720                 post_index = post_index_next;
721         } while (1);
722
723  out:
724
725         if (!completed_cmds)
726                 return IRQ_NONE;
727
728         /* reply post descriptor handling */
729         post_index_next = ioc->reply_post_host_index;
730         for (i = 0 ; i < completed_cmds; i++) {
731                 post_index = post_index_next;
732                 /* poison the reply post descriptor */
733                 ioc->reply_post_free[post_index_next].Words = ULLONG_MAX;
734                 post_index_next = (post_index ==
735                     (ioc->reply_post_queue_depth - 1))
736                     ? 0 : post_index + 1;
737         }
738         ioc->reply_post_host_index = post_index_next;
739         writel(post_index_next, &ioc->chip->ReplyPostHostIndex);
740         wmb();
741         return IRQ_HANDLED;
742 }
743
744 /**
745  * mpt2sas_base_release_callback_handler - clear interupt callback handler
746  * @cb_idx: callback index
747  *
748  * Return nothing.
749  */
750 void
751 mpt2sas_base_release_callback_handler(u8 cb_idx)
752 {
753         mpt_callbacks[cb_idx] = NULL;
754 }
755
756 /**
757  * mpt2sas_base_register_callback_handler - obtain index for the interrupt callback handler
758  * @cb_func: callback function
759  *
760  * Returns cb_func.
761  */
762 u8
763 mpt2sas_base_register_callback_handler(MPT_CALLBACK cb_func)
764 {
765         u8 cb_idx;
766
767         for (cb_idx = MPT_MAX_CALLBACKS-1; cb_idx; cb_idx--)
768                 if (mpt_callbacks[cb_idx] == NULL)
769                         break;
770
771         mpt_callbacks[cb_idx] = cb_func;
772         return cb_idx;
773 }
774
775 /**
776  * mpt2sas_base_initialize_callback_handler - initialize the interrupt callback handler
777  *
778  * Return nothing.
779  */
780 void
781 mpt2sas_base_initialize_callback_handler(void)
782 {
783         u8 cb_idx;
784
785         for (cb_idx = 0; cb_idx < MPT_MAX_CALLBACKS; cb_idx++)
786                 mpt2sas_base_release_callback_handler(cb_idx);
787 }
788
789 /**
790  * mpt2sas_base_build_zero_len_sge - build zero length sg entry
791  * @ioc: per adapter object
792  * @paddr: virtual address for SGE
793  *
794  * Create a zero length scatter gather entry to insure the IOCs hardware has
795  * something to use if the target device goes brain dead and tries
796  * to send data even when none is asked for.
797  *
798  * Return nothing.
799  */
800 void
801 mpt2sas_base_build_zero_len_sge(struct MPT2SAS_ADAPTER *ioc, void *paddr)
802 {
803         u32 flags_length = (u32)((MPI2_SGE_FLAGS_LAST_ELEMENT |
804             MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_END_OF_LIST |
805             MPI2_SGE_FLAGS_SIMPLE_ELEMENT) <<
806             MPI2_SGE_FLAGS_SHIFT);
807         ioc->base_add_sg_single(paddr, flags_length, -1);
808 }
809
810 /**
811  * _base_add_sg_single_32 - Place a simple 32 bit SGE at address pAddr.
812  * @paddr: virtual address for SGE
813  * @flags_length: SGE flags and data transfer length
814  * @dma_addr: Physical address
815  *
816  * Return nothing.
817  */
818 static void
819 _base_add_sg_single_32(void *paddr, u32 flags_length, dma_addr_t dma_addr)
820 {
821         Mpi2SGESimple32_t *sgel = paddr;
822
823         flags_length |= (MPI2_SGE_FLAGS_32_BIT_ADDRESSING |
824             MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT;
825         sgel->FlagsLength = cpu_to_le32(flags_length);
826         sgel->Address = cpu_to_le32(dma_addr);
827 }
828
829
830 /**
831  * _base_add_sg_single_64 - Place a simple 64 bit SGE at address pAddr.
832  * @paddr: virtual address for SGE
833  * @flags_length: SGE flags and data transfer length
834  * @dma_addr: Physical address
835  *
836  * Return nothing.
837  */
838 static void
839 _base_add_sg_single_64(void *paddr, u32 flags_length, dma_addr_t dma_addr)
840 {
841         Mpi2SGESimple64_t *sgel = paddr;
842
843         flags_length |= (MPI2_SGE_FLAGS_64_BIT_ADDRESSING |
844             MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT;
845         sgel->FlagsLength = cpu_to_le32(flags_length);
846         sgel->Address = cpu_to_le64(dma_addr);
847 }
848
849 #define convert_to_kb(x) ((x) << (PAGE_SHIFT - 10))
850
851 /**
852  * _base_config_dma_addressing - set dma addressing
853  * @ioc: per adapter object
854  * @pdev: PCI device struct
855  *
856  * Returns 0 for success, non-zero for failure.
857  */
858 static int
859 _base_config_dma_addressing(struct MPT2SAS_ADAPTER *ioc, struct pci_dev *pdev)
860 {
861         struct sysinfo s;
862         char *desc = NULL;
863
864         if (sizeof(dma_addr_t) > 4) {
865                 const uint64_t required_mask =
866                     dma_get_required_mask(&pdev->dev);
867                 if ((required_mask > DMA_BIT_MASK(32)) && !pci_set_dma_mask(pdev,
868                     DMA_BIT_MASK(64)) && !pci_set_consistent_dma_mask(pdev,
869                     DMA_BIT_MASK(64))) {
870                         ioc->base_add_sg_single = &_base_add_sg_single_64;
871                         ioc->sge_size = sizeof(Mpi2SGESimple64_t);
872                         desc = "64";
873                         goto out;
874                 }
875         }
876
877         if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(32))
878             && !pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) {
879                 ioc->base_add_sg_single = &_base_add_sg_single_32;
880                 ioc->sge_size = sizeof(Mpi2SGESimple32_t);
881                 desc = "32";
882         } else
883                 return -ENODEV;
884
885  out:
886         si_meminfo(&s);
887         printk(MPT2SAS_INFO_FMT "%s BIT PCI BUS DMA ADDRESSING SUPPORTED, "
888             "total mem (%ld kB)\n", ioc->name, desc, convert_to_kb(s.totalram));
889
890         return 0;
891 }
892
893 /**
894  * _base_save_msix_table - backup msix vector table
895  * @ioc: per adapter object
896  *
897  * This address an errata where diag reset clears out the table
898  */
899 static void
900 _base_save_msix_table(struct MPT2SAS_ADAPTER *ioc)
901 {
902         int i;
903
904         if (!ioc->msix_enable || ioc->msix_table_backup == NULL)
905                 return;
906
907         for (i = 0; i < ioc->msix_vector_count; i++)
908                 ioc->msix_table_backup[i] = ioc->msix_table[i];
909 }
910
911 /**
912  * _base_restore_msix_table - this restores the msix vector table
913  * @ioc: per adapter object
914  *
915  */
916 static void
917 _base_restore_msix_table(struct MPT2SAS_ADAPTER *ioc)
918 {
919         int i;
920
921         if (!ioc->msix_enable || ioc->msix_table_backup == NULL)
922                 return;
923
924         for (i = 0; i < ioc->msix_vector_count; i++)
925                 ioc->msix_table[i] = ioc->msix_table_backup[i];
926 }
927
928 /**
929  * _base_check_enable_msix - checks MSIX capabable.
930  * @ioc: per adapter object
931  *
932  * Check to see if card is capable of MSIX, and set number
933  * of avaliable msix vectors
934  */
935 static int
936 _base_check_enable_msix(struct MPT2SAS_ADAPTER *ioc)
937 {
938         int base;
939         u16 message_control;
940         u32 msix_table_offset;
941
942         base = pci_find_capability(ioc->pdev, PCI_CAP_ID_MSIX);
943         if (!base) {
944                 dfailprintk(ioc, printk(MPT2SAS_INFO_FMT "msix not "
945                     "supported\n", ioc->name));
946                 return -EINVAL;
947         }
948
949         /* get msix vector count */
950         pci_read_config_word(ioc->pdev, base + 2, &message_control);
951         ioc->msix_vector_count = (message_control & 0x3FF) + 1;
952
953         /* get msix table  */
954         pci_read_config_dword(ioc->pdev, base + 4, &msix_table_offset);
955         msix_table_offset &= 0xFFFFFFF8;
956         ioc->msix_table = (u32 *)((void *)ioc->chip + msix_table_offset);
957
958         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "msix is supported, "
959             "vector_count(%d), table_offset(0x%08x), table(%p)\n", ioc->name,
960             ioc->msix_vector_count, msix_table_offset, ioc->msix_table));
961         return 0;
962 }
963
964 /**
965  * _base_disable_msix - disables msix
966  * @ioc: per adapter object
967  *
968  */
969 static void
970 _base_disable_msix(struct MPT2SAS_ADAPTER *ioc)
971 {
972         if (ioc->msix_enable) {
973                 pci_disable_msix(ioc->pdev);
974                 kfree(ioc->msix_table_backup);
975                 ioc->msix_table_backup = NULL;
976                 ioc->msix_enable = 0;
977         }
978 }
979
980 /**
981  * _base_enable_msix - enables msix, failback to io_apic
982  * @ioc: per adapter object
983  *
984  */
985 static int
986 _base_enable_msix(struct MPT2SAS_ADAPTER *ioc)
987 {
988         struct msix_entry entries;
989         int r;
990         u8 try_msix = 0;
991
992         if (msix_disable == -1 || msix_disable == 0)
993                 try_msix = 1;
994
995         if (!try_msix)
996                 goto try_ioapic;
997
998         if (_base_check_enable_msix(ioc) != 0)
999                 goto try_ioapic;
1000
1001         ioc->msix_table_backup = kcalloc(ioc->msix_vector_count,
1002             sizeof(u32), GFP_KERNEL);
1003         if (!ioc->msix_table_backup) {
1004                 dfailprintk(ioc, printk(MPT2SAS_INFO_FMT "allocation for "
1005                     "msix_table_backup failed!!!\n", ioc->name));
1006                 goto try_ioapic;
1007         }
1008
1009         memset(&entries, 0, sizeof(struct msix_entry));
1010         r = pci_enable_msix(ioc->pdev, &entries, 1);
1011         if (r) {
1012                 dfailprintk(ioc, printk(MPT2SAS_INFO_FMT "pci_enable_msix "
1013                     "failed (r=%d) !!!\n", ioc->name, r));
1014                 goto try_ioapic;
1015         }
1016
1017         r = request_irq(entries.vector, _base_interrupt, IRQF_SHARED,
1018             ioc->name, ioc);
1019         if (r) {
1020                 dfailprintk(ioc, printk(MPT2SAS_INFO_FMT "unable to allocate "
1021                     "interrupt %d !!!\n", ioc->name, entries.vector));
1022                 pci_disable_msix(ioc->pdev);
1023                 goto try_ioapic;
1024         }
1025
1026         ioc->pci_irq = entries.vector;
1027         ioc->msix_enable = 1;
1028         return 0;
1029
1030 /* failback to io_apic interrupt routing */
1031  try_ioapic:
1032
1033         r = request_irq(ioc->pdev->irq, _base_interrupt, IRQF_SHARED,
1034             ioc->name, ioc);
1035         if (r) {
1036                 printk(MPT2SAS_ERR_FMT "unable to allocate interrupt %d!\n",
1037                     ioc->name, ioc->pdev->irq);
1038                 r = -EBUSY;
1039                 goto out_fail;
1040         }
1041
1042         ioc->pci_irq = ioc->pdev->irq;
1043         return 0;
1044
1045  out_fail:
1046         return r;
1047 }
1048
1049 /**
1050  * mpt2sas_base_map_resources - map in controller resources (io/irq/memap)
1051  * @ioc: per adapter object
1052  *
1053  * Returns 0 for success, non-zero for failure.
1054  */
1055 int
1056 mpt2sas_base_map_resources(struct MPT2SAS_ADAPTER *ioc)
1057 {
1058         struct pci_dev *pdev = ioc->pdev;
1059         u32 memap_sz;
1060         u32 pio_sz;
1061         int i, r = 0;
1062
1063         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n",
1064             ioc->name, __func__));
1065
1066         ioc->bars = pci_select_bars(pdev, IORESOURCE_MEM);
1067         if (pci_enable_device_mem(pdev)) {
1068                 printk(MPT2SAS_WARN_FMT "pci_enable_device_mem: "
1069                     "failed\n", ioc->name);
1070                 return -ENODEV;
1071         }
1072
1073
1074         if (pci_request_selected_regions(pdev, ioc->bars,
1075             MPT2SAS_DRIVER_NAME)) {
1076                 printk(MPT2SAS_WARN_FMT "pci_request_selected_regions: "
1077                     "failed\n", ioc->name);
1078                 r = -ENODEV;
1079                 goto out_fail;
1080         }
1081
1082         pci_set_master(pdev);
1083
1084         if (_base_config_dma_addressing(ioc, pdev) != 0) {
1085                 printk(MPT2SAS_WARN_FMT "no suitable DMA mask for %s\n",
1086                     ioc->name, pci_name(pdev));
1087                 r = -ENODEV;
1088                 goto out_fail;
1089         }
1090
1091         for (i = 0, memap_sz = 0, pio_sz = 0 ; i < DEVICE_COUNT_RESOURCE; i++) {
1092                 if (pci_resource_flags(pdev, i) & PCI_BASE_ADDRESS_SPACE_IO) {
1093                         if (pio_sz)
1094                                 continue;
1095                         ioc->pio_chip = pci_resource_start(pdev, i);
1096                         pio_sz = pci_resource_len(pdev, i);
1097                 } else {
1098                         if (memap_sz)
1099                                 continue;
1100                         ioc->chip_phys = pci_resource_start(pdev, i);
1101                         memap_sz = pci_resource_len(pdev, i);
1102                         ioc->chip = ioremap(ioc->chip_phys, memap_sz);
1103                         if (ioc->chip == NULL) {
1104                                 printk(MPT2SAS_ERR_FMT "unable to map adapter "
1105                                     "memory!\n", ioc->name);
1106                                 r = -EINVAL;
1107                                 goto out_fail;
1108                         }
1109                 }
1110         }
1111
1112         pci_set_drvdata(pdev, ioc->shost);
1113         _base_mask_interrupts(ioc);
1114         r = _base_enable_msix(ioc);
1115         if (r)
1116                 goto out_fail;
1117
1118         printk(MPT2SAS_INFO_FMT "%s: IRQ %d\n",
1119             ioc->name,  ((ioc->msix_enable) ? "PCI-MSI-X enabled" :
1120             "IO-APIC enabled"), ioc->pci_irq);
1121         printk(MPT2SAS_INFO_FMT "iomem(0x%lx), mapped(0x%p), size(%d)\n",
1122             ioc->name, ioc->chip_phys, ioc->chip, memap_sz);
1123         printk(MPT2SAS_INFO_FMT "ioport(0x%lx), size(%d)\n",
1124             ioc->name, ioc->pio_chip, pio_sz);
1125
1126         return 0;
1127
1128  out_fail:
1129         if (ioc->chip_phys)
1130                 iounmap(ioc->chip);
1131         ioc->chip_phys = 0;
1132         ioc->pci_irq = -1;
1133         pci_release_selected_regions(ioc->pdev, ioc->bars);
1134         pci_disable_device(pdev);
1135         pci_set_drvdata(pdev, NULL);
1136         return r;
1137 }
1138
1139 /**
1140  * mpt2sas_base_get_msg_frame_dma - obtain request mf pointer phys addr
1141  * @ioc: per adapter object
1142  * @smid: system request message index(smid zero is invalid)
1143  *
1144  * Returns phys pointer to message frame.
1145  */
1146 dma_addr_t
1147 mpt2sas_base_get_msg_frame_dma(struct MPT2SAS_ADAPTER *ioc, u16 smid)
1148 {
1149         return ioc->request_dma + (smid * ioc->request_sz);
1150 }
1151
1152 /**
1153  * mpt2sas_base_get_msg_frame - obtain request mf pointer
1154  * @ioc: per adapter object
1155  * @smid: system request message index(smid zero is invalid)
1156  *
1157  * Returns virt pointer to message frame.
1158  */
1159 void *
1160 mpt2sas_base_get_msg_frame(struct MPT2SAS_ADAPTER *ioc, u16 smid)
1161 {
1162         return (void *)(ioc->request + (smid * ioc->request_sz));
1163 }
1164
1165 /**
1166  * mpt2sas_base_get_sense_buffer - obtain a sense buffer assigned to a mf request
1167  * @ioc: per adapter object
1168  * @smid: system request message index
1169  *
1170  * Returns virt pointer to sense buffer.
1171  */
1172 void *
1173 mpt2sas_base_get_sense_buffer(struct MPT2SAS_ADAPTER *ioc, u16 smid)
1174 {
1175         return (void *)(ioc->sense + ((smid - 1) * SCSI_SENSE_BUFFERSIZE));
1176 }
1177
1178 /**
1179  * mpt2sas_base_get_sense_buffer_dma - obtain a sense buffer assigned to a mf request
1180  * @ioc: per adapter object
1181  * @smid: system request message index
1182  *
1183  * Returns phys pointer to sense buffer.
1184  */
1185 dma_addr_t
1186 mpt2sas_base_get_sense_buffer_dma(struct MPT2SAS_ADAPTER *ioc, u16 smid)
1187 {
1188         return ioc->sense_dma + ((smid - 1) * SCSI_SENSE_BUFFERSIZE);
1189 }
1190
1191 /**
1192  * mpt2sas_base_get_reply_virt_addr - obtain reply frames virt address
1193  * @ioc: per adapter object
1194  * @phys_addr: lower 32 physical addr of the reply
1195  *
1196  * Converts 32bit lower physical addr into a virt address.
1197  */
1198 void *
1199 mpt2sas_base_get_reply_virt_addr(struct MPT2SAS_ADAPTER *ioc, u32 phys_addr)
1200 {
1201         if (!phys_addr)
1202                 return NULL;
1203         return ioc->reply + (phys_addr - (u32)ioc->reply_dma);
1204 }
1205
1206 /**
1207  * mpt2sas_base_get_smid - obtain a free smid
1208  * @ioc: per adapter object
1209  * @cb_idx: callback index
1210  *
1211  * Returns smid (zero is invalid)
1212  */
1213 u16
1214 mpt2sas_base_get_smid(struct MPT2SAS_ADAPTER *ioc, u8 cb_idx)
1215 {
1216         unsigned long flags;
1217         struct request_tracker *request;
1218         u16 smid;
1219
1220         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
1221         if (list_empty(&ioc->free_list)) {
1222                 spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
1223                 printk(MPT2SAS_ERR_FMT "%s: smid not available\n",
1224                     ioc->name, __func__);
1225                 return 0;
1226         }
1227
1228         request = list_entry(ioc->free_list.next,
1229             struct request_tracker, tracker_list);
1230         request->cb_idx = cb_idx;
1231         smid = request->smid;
1232         list_del(&request->tracker_list);
1233         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
1234         return smid;
1235 }
1236
1237
1238 /**
1239  * mpt2sas_base_free_smid - put smid back on free_list
1240  * @ioc: per adapter object
1241  * @smid: system request message index
1242  *
1243  * Return nothing.
1244  */
1245 void
1246 mpt2sas_base_free_smid(struct MPT2SAS_ADAPTER *ioc, u16 smid)
1247 {
1248         unsigned long flags;
1249
1250         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
1251         ioc->scsi_lookup[smid - 1].cb_idx = 0xFF;
1252         list_add_tail(&ioc->scsi_lookup[smid - 1].tracker_list,
1253             &ioc->free_list);
1254         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
1255
1256         /*
1257          * See _wait_for_commands_to_complete() call with regards to this code.
1258          */
1259         if (ioc->shost_recovery && ioc->pending_io_count) {
1260                 if (ioc->pending_io_count == 1)
1261                         wake_up(&ioc->reset_wq);
1262                 ioc->pending_io_count--;
1263         }
1264 }
1265
1266 /**
1267  * _base_writeq - 64 bit write to MMIO
1268  * @ioc: per adapter object
1269  * @b: data payload
1270  * @addr: address in MMIO space
1271  * @writeq_lock: spin lock
1272  *
1273  * Glue for handling an atomic 64 bit word to MMIO. This special handling takes
1274  * care of 32 bit environment where its not quarenteed to send the entire word
1275  * in one transfer.
1276  */
1277 #ifndef writeq
1278 static inline void _base_writeq(__u64 b, volatile void __iomem *addr,
1279     spinlock_t *writeq_lock)
1280 {
1281         unsigned long flags;
1282         __u64 data_out = cpu_to_le64(b);
1283
1284         spin_lock_irqsave(writeq_lock, flags);
1285         writel((u32)(data_out), addr);
1286         writel((u32)(data_out >> 32), (addr + 4));
1287         spin_unlock_irqrestore(writeq_lock, flags);
1288 }
1289 #else
1290 static inline void _base_writeq(__u64 b, volatile void __iomem *addr,
1291     spinlock_t *writeq_lock)
1292 {
1293         writeq(cpu_to_le64(b), addr);
1294 }
1295 #endif
1296
1297 /**
1298  * mpt2sas_base_put_smid_scsi_io - send SCSI_IO request to firmware
1299  * @ioc: per adapter object
1300  * @smid: system request message index
1301  * @vf_id: virtual function id
1302  * @handle: device handle
1303  *
1304  * Return nothing.
1305  */
1306 void
1307 mpt2sas_base_put_smid_scsi_io(struct MPT2SAS_ADAPTER *ioc, u16 smid, u8 vf_id,
1308     u16 handle)
1309 {
1310         Mpi2RequestDescriptorUnion_t descriptor;
1311         u64 *request = (u64 *)&descriptor;
1312
1313
1314         descriptor.SCSIIO.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
1315         descriptor.SCSIIO.VF_ID = vf_id;
1316         descriptor.SCSIIO.SMID = cpu_to_le16(smid);
1317         descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
1318         descriptor.SCSIIO.LMID = 0;
1319         _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
1320             &ioc->scsi_lookup_lock);
1321 }
1322
1323
1324 /**
1325  * mpt2sas_base_put_smid_hi_priority - send Task Managment request to firmware
1326  * @ioc: per adapter object
1327  * @smid: system request message index
1328  * @vf_id: virtual function id
1329  *
1330  * Return nothing.
1331  */
1332 void
1333 mpt2sas_base_put_smid_hi_priority(struct MPT2SAS_ADAPTER *ioc, u16 smid,
1334     u8 vf_id)
1335 {
1336         Mpi2RequestDescriptorUnion_t descriptor;
1337         u64 *request = (u64 *)&descriptor;
1338
1339         descriptor.HighPriority.RequestFlags =
1340             MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY;
1341         descriptor.HighPriority.VF_ID = vf_id;
1342         descriptor.HighPriority.SMID = cpu_to_le16(smid);
1343         descriptor.HighPriority.LMID = 0;
1344         descriptor.HighPriority.Reserved1 = 0;
1345         _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
1346             &ioc->scsi_lookup_lock);
1347 }
1348
1349 /**
1350  * mpt2sas_base_put_smid_default - Default, primarily used for config pages
1351  * @ioc: per adapter object
1352  * @smid: system request message index
1353  * @vf_id: virtual function id
1354  *
1355  * Return nothing.
1356  */
1357 void
1358 mpt2sas_base_put_smid_default(struct MPT2SAS_ADAPTER *ioc, u16 smid, u8 vf_id)
1359 {
1360         Mpi2RequestDescriptorUnion_t descriptor;
1361         u64 *request = (u64 *)&descriptor;
1362
1363         descriptor.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
1364         descriptor.Default.VF_ID = vf_id;
1365         descriptor.Default.SMID = cpu_to_le16(smid);
1366         descriptor.Default.LMID = 0;
1367         descriptor.Default.DescriptorTypeDependent = 0;
1368         _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
1369             &ioc->scsi_lookup_lock);
1370 }
1371
1372 /**
1373  * mpt2sas_base_put_smid_target_assist - send Target Assist/Status to firmware
1374  * @ioc: per adapter object
1375  * @smid: system request message index
1376  * @vf_id: virtual function id
1377  * @io_index: value used to track the IO
1378  *
1379  * Return nothing.
1380  */
1381 void
1382 mpt2sas_base_put_smid_target_assist(struct MPT2SAS_ADAPTER *ioc, u16 smid,
1383     u8 vf_id, u16 io_index)
1384 {
1385         Mpi2RequestDescriptorUnion_t descriptor;
1386         u64 *request = (u64 *)&descriptor;
1387
1388         descriptor.SCSITarget.RequestFlags =
1389             MPI2_REQ_DESCRIPT_FLAGS_SCSI_TARGET;
1390         descriptor.SCSITarget.VF_ID = vf_id;
1391         descriptor.SCSITarget.SMID = cpu_to_le16(smid);
1392         descriptor.SCSITarget.LMID = 0;
1393         descriptor.SCSITarget.IoIndex = cpu_to_le16(io_index);
1394         _base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
1395             &ioc->scsi_lookup_lock);
1396 }
1397
1398 /**
1399  * _base_display_ioc_capabilities - Disply IOC's capabilities.
1400  * @ioc: per adapter object
1401  *
1402  * Return nothing.
1403  */
1404 static void
1405 _base_display_ioc_capabilities(struct MPT2SAS_ADAPTER *ioc)
1406 {
1407         int i = 0;
1408         char desc[16];
1409         u8 revision;
1410         u32 iounit_pg1_flags;
1411
1412         pci_read_config_byte(ioc->pdev, PCI_CLASS_REVISION, &revision);
1413         strncpy(desc, ioc->manu_pg0.ChipName, 16);
1414         printk(MPT2SAS_INFO_FMT "%s: FWVersion(%02d.%02d.%02d.%02d), "
1415            "ChipRevision(0x%02x), BiosVersion(%02d.%02d.%02d.%02d)\n",
1416             ioc->name, desc,
1417            (ioc->facts.FWVersion.Word & 0xFF000000) >> 24,
1418            (ioc->facts.FWVersion.Word & 0x00FF0000) >> 16,
1419            (ioc->facts.FWVersion.Word & 0x0000FF00) >> 8,
1420            ioc->facts.FWVersion.Word & 0x000000FF,
1421            revision,
1422            (ioc->bios_pg3.BiosVersion & 0xFF000000) >> 24,
1423            (ioc->bios_pg3.BiosVersion & 0x00FF0000) >> 16,
1424            (ioc->bios_pg3.BiosVersion & 0x0000FF00) >> 8,
1425             ioc->bios_pg3.BiosVersion & 0x000000FF);
1426
1427         printk(MPT2SAS_INFO_FMT "Protocol=(", ioc->name);
1428
1429         if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_INITIATOR) {
1430                 printk("Initiator");
1431                 i++;
1432         }
1433
1434         if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_TARGET) {
1435                 printk("%sTarget", i ? "," : "");
1436                 i++;
1437         }
1438
1439         i = 0;
1440         printk("), ");
1441         printk("Capabilities=(");
1442
1443         if (ioc->facts.IOCCapabilities &
1444             MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID) {
1445                 printk("Raid");
1446                 i++;
1447         }
1448
1449         if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR) {
1450                 printk("%sTLR", i ? "," : "");
1451                 i++;
1452         }
1453
1454         if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_MULTICAST) {
1455                 printk("%sMulticast", i ? "," : "");
1456                 i++;
1457         }
1458
1459         if (ioc->facts.IOCCapabilities &
1460             MPI2_IOCFACTS_CAPABILITY_BIDIRECTIONAL_TARGET) {
1461                 printk("%sBIDI Target", i ? "," : "");
1462                 i++;
1463         }
1464
1465         if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP) {
1466                 printk("%sEEDP", i ? "," : "");
1467                 i++;
1468         }
1469
1470         if (ioc->facts.IOCCapabilities &
1471             MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER) {
1472                 printk("%sSnapshot Buffer", i ? "," : "");
1473                 i++;
1474         }
1475
1476         if (ioc->facts.IOCCapabilities &
1477             MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER) {
1478                 printk("%sDiag Trace Buffer", i ? "," : "");
1479                 i++;
1480         }
1481
1482         if (ioc->facts.IOCCapabilities &
1483             MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING) {
1484                 printk("%sTask Set Full", i ? "," : "");
1485                 i++;
1486         }
1487
1488         iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
1489         if (!(iounit_pg1_flags & MPI2_IOUNITPAGE1_NATIVE_COMMAND_Q_DISABLE)) {
1490                 printk("%sNCQ", i ? "," : "");
1491                 i++;
1492         }
1493
1494         printk(")\n");
1495 }
1496
1497 /**
1498  * _base_static_config_pages - static start of day config pages
1499  * @ioc: per adapter object
1500  *
1501  * Return nothing.
1502  */
1503 static void
1504 _base_static_config_pages(struct MPT2SAS_ADAPTER *ioc)
1505 {
1506         Mpi2ConfigReply_t mpi_reply;
1507         u32 iounit_pg1_flags;
1508
1509         mpt2sas_config_get_manufacturing_pg0(ioc, &mpi_reply, &ioc->manu_pg0);
1510         mpt2sas_config_get_bios_pg2(ioc, &mpi_reply, &ioc->bios_pg2);
1511         mpt2sas_config_get_bios_pg3(ioc, &mpi_reply, &ioc->bios_pg3);
1512         mpt2sas_config_get_ioc_pg8(ioc, &mpi_reply, &ioc->ioc_pg8);
1513         mpt2sas_config_get_iounit_pg0(ioc, &mpi_reply, &ioc->iounit_pg0);
1514         mpt2sas_config_get_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
1515         _base_display_ioc_capabilities(ioc);
1516
1517         /*
1518          * Enable task_set_full handling in iounit_pg1 when the
1519          * facts capabilities indicate that its supported.
1520          */
1521         iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
1522         if ((ioc->facts.IOCCapabilities &
1523             MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING))
1524                 iounit_pg1_flags &=
1525                     ~MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
1526         else
1527                 iounit_pg1_flags |=
1528                     MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
1529         ioc->iounit_pg1.Flags = cpu_to_le32(iounit_pg1_flags);
1530         mpt2sas_config_set_iounit_pg1(ioc, &mpi_reply, ioc->iounit_pg1);
1531 }
1532
1533 /**
1534  * _base_release_memory_pools - release memory
1535  * @ioc: per adapter object
1536  *
1537  * Free memory allocated from _base_allocate_memory_pools.
1538  *
1539  * Return nothing.
1540  */
1541 static void
1542 _base_release_memory_pools(struct MPT2SAS_ADAPTER *ioc)
1543 {
1544         dexitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
1545             __func__));
1546
1547         if (ioc->request) {
1548                 pci_free_consistent(ioc->pdev, ioc->request_dma_sz,
1549                     ioc->request,  ioc->request_dma);
1550                 dexitprintk(ioc, printk(MPT2SAS_INFO_FMT "request_pool(0x%p)"
1551                     ": free\n", ioc->name, ioc->request));
1552                 ioc->request = NULL;
1553         }
1554
1555         if (ioc->sense) {
1556                 pci_pool_free(ioc->sense_dma_pool, ioc->sense, ioc->sense_dma);
1557                 if (ioc->sense_dma_pool)
1558                         pci_pool_destroy(ioc->sense_dma_pool);
1559                 dexitprintk(ioc, printk(MPT2SAS_INFO_FMT "sense_pool(0x%p)"
1560                     ": free\n", ioc->name, ioc->sense));
1561                 ioc->sense = NULL;
1562         }
1563
1564         if (ioc->reply) {
1565                 pci_pool_free(ioc->reply_dma_pool, ioc->reply, ioc->reply_dma);
1566                 if (ioc->reply_dma_pool)
1567                         pci_pool_destroy(ioc->reply_dma_pool);
1568                 dexitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_pool(0x%p)"
1569                      ": free\n", ioc->name, ioc->reply));
1570                 ioc->reply = NULL;
1571         }
1572
1573         if (ioc->reply_free) {
1574                 pci_pool_free(ioc->reply_free_dma_pool, ioc->reply_free,
1575                     ioc->reply_free_dma);
1576                 if (ioc->reply_free_dma_pool)
1577                         pci_pool_destroy(ioc->reply_free_dma_pool);
1578                 dexitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_free_pool"
1579                     "(0x%p): free\n", ioc->name, ioc->reply_free));
1580                 ioc->reply_free = NULL;
1581         }
1582
1583         if (ioc->reply_post_free) {
1584                 pci_pool_free(ioc->reply_post_free_dma_pool,
1585                     ioc->reply_post_free, ioc->reply_post_free_dma);
1586                 if (ioc->reply_post_free_dma_pool)
1587                         pci_pool_destroy(ioc->reply_post_free_dma_pool);
1588                 dexitprintk(ioc, printk(MPT2SAS_INFO_FMT
1589                     "reply_post_free_pool(0x%p): free\n", ioc->name,
1590                     ioc->reply_post_free));
1591                 ioc->reply_post_free = NULL;
1592         }
1593
1594         if (ioc->config_page) {
1595                 dexitprintk(ioc, printk(MPT2SAS_INFO_FMT
1596                     "config_page(0x%p): free\n", ioc->name,
1597                     ioc->config_page));
1598                 pci_free_consistent(ioc->pdev, ioc->config_page_sz,
1599                     ioc->config_page, ioc->config_page_dma);
1600         }
1601
1602         kfree(ioc->scsi_lookup);
1603 }
1604
1605
1606 /**
1607  * _base_allocate_memory_pools - allocate start of day memory pools
1608  * @ioc: per adapter object
1609  * @sleep_flag: CAN_SLEEP or NO_SLEEP
1610  *
1611  * Returns 0 success, anything else error
1612  */
1613 static int
1614 _base_allocate_memory_pools(struct MPT2SAS_ADAPTER *ioc,  int sleep_flag)
1615 {
1616         Mpi2IOCFactsReply_t *facts;
1617         u32 queue_size, queue_diff;
1618         u16 max_sge_elements;
1619         u16 num_of_reply_frames;
1620         u16 chains_needed_per_io;
1621         u32 sz, total_sz;
1622         u16 i;
1623         u32 retry_sz;
1624         u16 max_request_credit;
1625
1626         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
1627             __func__));
1628
1629         retry_sz = 0;
1630         facts = &ioc->facts;
1631
1632         /* command line tunables  for max sgl entries */
1633         if (max_sgl_entries != -1) {
1634                 ioc->shost->sg_tablesize = (max_sgl_entries <
1635                     MPT2SAS_SG_DEPTH) ? max_sgl_entries :
1636                     MPT2SAS_SG_DEPTH;
1637         } else {
1638                 ioc->shost->sg_tablesize = MPT2SAS_SG_DEPTH;
1639         }
1640
1641         /* command line tunables  for max controller queue depth */
1642         if (max_queue_depth != -1) {
1643                 max_request_credit = (max_queue_depth < facts->RequestCredit)
1644                     ? max_queue_depth : facts->RequestCredit;
1645         } else {
1646                 max_request_credit = (facts->RequestCredit >
1647                     MPT2SAS_MAX_REQUEST_QUEUE) ? MPT2SAS_MAX_REQUEST_QUEUE :
1648                     facts->RequestCredit;
1649         }
1650         ioc->request_depth = max_request_credit;
1651
1652         /* request frame size */
1653         ioc->request_sz = facts->IOCRequestFrameSize * 4;
1654
1655         /* reply frame size */
1656         ioc->reply_sz = facts->ReplyFrameSize * 4;
1657
1658  retry_allocation:
1659         total_sz = 0;
1660         /* calculate number of sg elements left over in the 1st frame */
1661         max_sge_elements = ioc->request_sz - ((sizeof(Mpi2SCSIIORequest_t) -
1662             sizeof(Mpi2SGEIOUnion_t)) + ioc->sge_size);
1663         ioc->max_sges_in_main_message = max_sge_elements/ioc->sge_size;
1664
1665         /* now do the same for a chain buffer */
1666         max_sge_elements = ioc->request_sz - ioc->sge_size;
1667         ioc->max_sges_in_chain_message = max_sge_elements/ioc->sge_size;
1668
1669         ioc->chain_offset_value_for_main_message =
1670             ((sizeof(Mpi2SCSIIORequest_t) - sizeof(Mpi2SGEIOUnion_t)) +
1671              (ioc->max_sges_in_chain_message * ioc->sge_size)) / 4;
1672
1673         /*
1674          *  MPT2SAS_SG_DEPTH = CONFIG_FUSION_MAX_SGE
1675          */
1676         chains_needed_per_io = ((ioc->shost->sg_tablesize -
1677            ioc->max_sges_in_main_message)/ioc->max_sges_in_chain_message)
1678             + 1;
1679         if (chains_needed_per_io > facts->MaxChainDepth) {
1680                 chains_needed_per_io = facts->MaxChainDepth;
1681                 ioc->shost->sg_tablesize = min_t(u16,
1682                 ioc->max_sges_in_main_message + (ioc->max_sges_in_chain_message
1683                 * chains_needed_per_io), ioc->shost->sg_tablesize);
1684         }
1685         ioc->chains_needed_per_io = chains_needed_per_io;
1686
1687         /* reply free queue sizing - taking into account for events */
1688         num_of_reply_frames = ioc->request_depth + 32;
1689
1690         /* number of replies frames can't be a multiple of 16 */
1691         /* decrease number of reply frames by 1 */
1692         if (!(num_of_reply_frames % 16))
1693                 num_of_reply_frames--;
1694
1695         /* calculate number of reply free queue entries
1696          *  (must be multiple of 16)
1697          */
1698
1699         /* (we know reply_free_queue_depth is not a multiple of 16) */
1700         queue_size = num_of_reply_frames;
1701         queue_size += 16 - (queue_size % 16);
1702         ioc->reply_free_queue_depth = queue_size;
1703
1704         /* reply descriptor post queue sizing */
1705         /* this size should be the number of request frames + number of reply
1706          * frames
1707          */
1708
1709         queue_size = ioc->request_depth + num_of_reply_frames + 1;
1710         /* round up to 16 byte boundary */
1711         if (queue_size % 16)
1712                 queue_size += 16 - (queue_size % 16);
1713
1714         /* check against IOC maximum reply post queue depth */
1715         if (queue_size > facts->MaxReplyDescriptorPostQueueDepth) {
1716                 queue_diff = queue_size -
1717                     facts->MaxReplyDescriptorPostQueueDepth;
1718
1719                 /* round queue_diff up to multiple of 16 */
1720                 if (queue_diff % 16)
1721                         queue_diff += 16 - (queue_diff % 16);
1722
1723                 /* adjust request_depth, reply_free_queue_depth,
1724                  * and queue_size
1725                  */
1726                 ioc->request_depth -= queue_diff;
1727                 ioc->reply_free_queue_depth -= queue_diff;
1728                 queue_size -= queue_diff;
1729         }
1730         ioc->reply_post_queue_depth = queue_size;
1731
1732         /* max scsi host queue depth */
1733         ioc->shost->can_queue = ioc->request_depth - INTERNAL_CMDS_COUNT;
1734         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "scsi host queue: depth"
1735             "(%d)\n", ioc->name, ioc->shost->can_queue));
1736
1737         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "scatter gather: "
1738             "sge_in_main_msg(%d), sge_per_chain(%d), sge_per_io(%d), "
1739             "chains_per_io(%d)\n", ioc->name, ioc->max_sges_in_main_message,
1740             ioc->max_sges_in_chain_message, ioc->shost->sg_tablesize,
1741             ioc->chains_needed_per_io));
1742
1743         /* contiguous pool for request and chains, 16 byte align, one extra "
1744          * "frame for smid=0
1745          */
1746         ioc->chain_depth = ioc->chains_needed_per_io * ioc->request_depth;
1747         sz = ((ioc->request_depth + 1 + ioc->chain_depth) * ioc->request_sz);
1748
1749         ioc->request_dma_sz = sz;
1750         ioc->request = pci_alloc_consistent(ioc->pdev, sz, &ioc->request_dma);
1751         if (!ioc->request) {
1752                 printk(MPT2SAS_ERR_FMT "request pool: pci_alloc_consistent "
1753                     "failed: req_depth(%d), chains_per_io(%d), frame_sz(%d), "
1754                     "total(%d kB)\n", ioc->name, ioc->request_depth,
1755                     ioc->chains_needed_per_io, ioc->request_sz, sz/1024);
1756                 if (ioc->request_depth < MPT2SAS_SAS_QUEUE_DEPTH)
1757                         goto out;
1758                 retry_sz += 64;
1759                 ioc->request_depth = max_request_credit - retry_sz;
1760                 goto retry_allocation;
1761         }
1762
1763         if (retry_sz)
1764                 printk(MPT2SAS_ERR_FMT "request pool: pci_alloc_consistent "
1765                     "succeed: req_depth(%d), chains_per_io(%d), frame_sz(%d), "
1766                     "total(%d kb)\n", ioc->name, ioc->request_depth,
1767                     ioc->chains_needed_per_io, ioc->request_sz, sz/1024);
1768
1769         ioc->chain = ioc->request + ((ioc->request_depth + 1) *
1770             ioc->request_sz);
1771         ioc->chain_dma = ioc->request_dma + ((ioc->request_depth + 1) *
1772             ioc->request_sz);
1773         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "request pool(0x%p): "
1774             "depth(%d), frame_size(%d), pool_size(%d kB)\n", ioc->name,
1775             ioc->request, ioc->request_depth, ioc->request_sz,
1776             ((ioc->request_depth + 1) * ioc->request_sz)/1024));
1777         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "chain pool(0x%p): depth"
1778             "(%d), frame_size(%d), pool_size(%d kB)\n", ioc->name, ioc->chain,
1779             ioc->chain_depth, ioc->request_sz, ((ioc->chain_depth *
1780             ioc->request_sz))/1024));
1781         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "request pool: dma(0x%llx)\n",
1782             ioc->name, (unsigned long long) ioc->request_dma));
1783         total_sz += sz;
1784
1785         ioc->scsi_lookup = kcalloc(ioc->request_depth,
1786             sizeof(struct request_tracker), GFP_KERNEL);
1787         if (!ioc->scsi_lookup) {
1788                 printk(MPT2SAS_ERR_FMT "scsi_lookup: kcalloc failed\n",
1789                     ioc->name);
1790                 goto out;
1791         }
1792
1793          /* initialize some bits */
1794         for (i = 0; i < ioc->request_depth; i++)
1795                 ioc->scsi_lookup[i].smid = i + 1;
1796
1797         /* sense buffers, 4 byte align */
1798         sz = ioc->request_depth * SCSI_SENSE_BUFFERSIZE;
1799         ioc->sense_dma_pool = pci_pool_create("sense pool", ioc->pdev, sz, 4,
1800             0);
1801         if (!ioc->sense_dma_pool) {
1802                 printk(MPT2SAS_ERR_FMT "sense pool: pci_pool_create failed\n",
1803                     ioc->name);
1804                 goto out;
1805         }
1806         ioc->sense = pci_pool_alloc(ioc->sense_dma_pool , GFP_KERNEL,
1807             &ioc->sense_dma);
1808         if (!ioc->sense) {
1809                 printk(MPT2SAS_ERR_FMT "sense pool: pci_pool_alloc failed\n",
1810                     ioc->name);
1811                 goto out;
1812         }
1813         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT
1814             "sense pool(0x%p): depth(%d), element_size(%d), pool_size"
1815             "(%d kB)\n", ioc->name, ioc->sense, ioc->request_depth,
1816             SCSI_SENSE_BUFFERSIZE, sz/1024));
1817         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "sense_dma(0x%llx)\n",
1818             ioc->name, (unsigned long long)ioc->sense_dma));
1819         total_sz += sz;
1820
1821         /* reply pool, 4 byte align */
1822         sz = ioc->reply_free_queue_depth * ioc->reply_sz;
1823         ioc->reply_dma_pool = pci_pool_create("reply pool", ioc->pdev, sz, 4,
1824             0);
1825         if (!ioc->reply_dma_pool) {
1826                 printk(MPT2SAS_ERR_FMT "reply pool: pci_pool_create failed\n",
1827                     ioc->name);
1828                 goto out;
1829         }
1830         ioc->reply = pci_pool_alloc(ioc->reply_dma_pool , GFP_KERNEL,
1831             &ioc->reply_dma);
1832         if (!ioc->reply) {
1833                 printk(MPT2SAS_ERR_FMT "reply pool: pci_pool_alloc failed\n",
1834                     ioc->name);
1835                 goto out;
1836         }
1837         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply pool(0x%p): depth"
1838             "(%d), frame_size(%d), pool_size(%d kB)\n", ioc->name, ioc->reply,
1839             ioc->reply_free_queue_depth, ioc->reply_sz, sz/1024));
1840         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_dma(0x%llx)\n",
1841             ioc->name, (unsigned long long)ioc->reply_dma));
1842         total_sz += sz;
1843
1844         /* reply free queue, 16 byte align */
1845         sz = ioc->reply_free_queue_depth * 4;
1846         ioc->reply_free_dma_pool = pci_pool_create("reply_free pool",
1847             ioc->pdev, sz, 16, 0);
1848         if (!ioc->reply_free_dma_pool) {
1849                 printk(MPT2SAS_ERR_FMT "reply_free pool: pci_pool_create "
1850                     "failed\n", ioc->name);
1851                 goto out;
1852         }
1853         ioc->reply_free = pci_pool_alloc(ioc->reply_free_dma_pool , GFP_KERNEL,
1854             &ioc->reply_free_dma);
1855         if (!ioc->reply_free) {
1856                 printk(MPT2SAS_ERR_FMT "reply_free pool: pci_pool_alloc "
1857                     "failed\n", ioc->name);
1858                 goto out;
1859         }
1860         memset(ioc->reply_free, 0, sz);
1861         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_free pool(0x%p): "
1862             "depth(%d), element_size(%d), pool_size(%d kB)\n", ioc->name,
1863             ioc->reply_free, ioc->reply_free_queue_depth, 4, sz/1024));
1864         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_free_dma"
1865             "(0x%llx)\n", ioc->name, (unsigned long long)ioc->reply_free_dma));
1866         total_sz += sz;
1867
1868         /* reply post queue, 16 byte align */
1869         sz = ioc->reply_post_queue_depth * sizeof(Mpi2DefaultReplyDescriptor_t);
1870         ioc->reply_post_free_dma_pool = pci_pool_create("reply_post_free pool",
1871             ioc->pdev, sz, 16, 0);
1872         if (!ioc->reply_post_free_dma_pool) {
1873                 printk(MPT2SAS_ERR_FMT "reply_post_free pool: pci_pool_create "
1874                     "failed\n", ioc->name);
1875                 goto out;
1876         }
1877         ioc->reply_post_free = pci_pool_alloc(ioc->reply_post_free_dma_pool ,
1878             GFP_KERNEL, &ioc->reply_post_free_dma);
1879         if (!ioc->reply_post_free) {
1880                 printk(MPT2SAS_ERR_FMT "reply_post_free pool: pci_pool_alloc "
1881                     "failed\n", ioc->name);
1882                 goto out;
1883         }
1884         memset(ioc->reply_post_free, 0, sz);
1885         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply post free pool"
1886             "(0x%p): depth(%d), element_size(%d), pool_size(%d kB)\n",
1887             ioc->name, ioc->reply_post_free, ioc->reply_post_queue_depth, 8,
1888             sz/1024));
1889         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_post_free_dma = "
1890             "(0x%llx)\n", ioc->name, (unsigned long long)
1891             ioc->reply_post_free_dma));
1892         total_sz += sz;
1893
1894         ioc->config_page_sz = 512;
1895         ioc->config_page = pci_alloc_consistent(ioc->pdev,
1896             ioc->config_page_sz, &ioc->config_page_dma);
1897         if (!ioc->config_page) {
1898                 printk(MPT2SAS_ERR_FMT "config page: pci_pool_alloc "
1899                     "failed\n", ioc->name);
1900                 goto out;
1901         }
1902         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "config page(0x%p): size"
1903             "(%d)\n", ioc->name, ioc->config_page, ioc->config_page_sz));
1904         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "config_page_dma"
1905             "(0x%llx)\n", ioc->name, (unsigned long long)ioc->config_page_dma));
1906         total_sz += ioc->config_page_sz;
1907
1908         printk(MPT2SAS_INFO_FMT "Allocated physical memory: size(%d kB)\n",
1909             ioc->name, total_sz/1024);
1910         printk(MPT2SAS_INFO_FMT "Current Controller Queue Depth(%d), "
1911             "Max Controller Queue Depth(%d)\n",
1912             ioc->name, ioc->shost->can_queue, facts->RequestCredit);
1913         printk(MPT2SAS_INFO_FMT "Scatter Gather Elements per IO(%d)\n",
1914             ioc->name, ioc->shost->sg_tablesize);
1915         return 0;
1916
1917  out:
1918         _base_release_memory_pools(ioc);
1919         return -ENOMEM;
1920 }
1921
1922
1923 /**
1924  * mpt2sas_base_get_iocstate - Get the current state of a MPT adapter.
1925  * @ioc: Pointer to MPT_ADAPTER structure
1926  * @cooked: Request raw or cooked IOC state
1927  *
1928  * Returns all IOC Doorbell register bits if cooked==0, else just the
1929  * Doorbell bits in MPI_IOC_STATE_MASK.
1930  */
1931 u32
1932 mpt2sas_base_get_iocstate(struct MPT2SAS_ADAPTER *ioc, int cooked)
1933 {
1934         u32 s, sc;
1935
1936         s = readl(&ioc->chip->Doorbell);
1937         sc = s & MPI2_IOC_STATE_MASK;
1938         return cooked ? sc : s;
1939 }
1940
1941 /**
1942  * _base_wait_on_iocstate - waiting on a particular ioc state
1943  * @ioc_state: controller state { READY, OPERATIONAL, or RESET }
1944  * @timeout: timeout in second
1945  * @sleep_flag: CAN_SLEEP or NO_SLEEP
1946  *
1947  * Returns 0 for success, non-zero for failure.
1948  */
1949 static int
1950 _base_wait_on_iocstate(struct MPT2SAS_ADAPTER *ioc, u32 ioc_state, int timeout,
1951     int sleep_flag)
1952 {
1953         u32 count, cntdn;
1954         u32 current_state;
1955
1956         count = 0;
1957         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
1958         do {
1959                 current_state = mpt2sas_base_get_iocstate(ioc, 1);
1960                 if (current_state == ioc_state)
1961                         return 0;
1962                 if (count && current_state == MPI2_IOC_STATE_FAULT)
1963                         break;
1964                 if (sleep_flag == CAN_SLEEP)
1965                         msleep(1);
1966                 else
1967                         udelay(500);
1968                 count++;
1969         } while (--cntdn);
1970
1971         return current_state;
1972 }
1973
1974 /**
1975  * _base_wait_for_doorbell_int - waiting for controller interrupt(generated by
1976  * a write to the doorbell)
1977  * @ioc: per adapter object
1978  * @timeout: timeout in second
1979  * @sleep_flag: CAN_SLEEP or NO_SLEEP
1980  *
1981  * Returns 0 for success, non-zero for failure.
1982  *
1983  * Notes: MPI2_HIS_IOC2SYS_DB_STATUS - set to one when IOC writes to doorbell.
1984  */
1985 static int
1986 _base_wait_for_doorbell_int(struct MPT2SAS_ADAPTER *ioc, int timeout,
1987     int sleep_flag)
1988 {
1989         u32 cntdn, count;
1990         u32 int_status;
1991
1992         count = 0;
1993         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
1994         do {
1995                 int_status = readl(&ioc->chip->HostInterruptStatus);
1996                 if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
1997                         dhsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: "
1998                             "successfull count(%d), timeout(%d)\n", ioc->name,
1999                             __func__, count, timeout));
2000                         return 0;
2001                 }
2002                 if (sleep_flag == CAN_SLEEP)
2003                         msleep(1);
2004                 else
2005                         udelay(500);
2006                 count++;
2007         } while (--cntdn);
2008
2009         printk(MPT2SAS_ERR_FMT "%s: failed due to timeout count(%d), "
2010             "int_status(%x)!\n", ioc->name, __func__, count, int_status);
2011         return -EFAULT;
2012 }
2013
2014 /**
2015  * _base_wait_for_doorbell_ack - waiting for controller to read the doorbell.
2016  * @ioc: per adapter object
2017  * @timeout: timeout in second
2018  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2019  *
2020  * Returns 0 for success, non-zero for failure.
2021  *
2022  * Notes: MPI2_HIS_SYS2IOC_DB_STATUS - set to one when host writes to
2023  * doorbell.
2024  */
2025 static int
2026 _base_wait_for_doorbell_ack(struct MPT2SAS_ADAPTER *ioc, int timeout,
2027     int sleep_flag)
2028 {
2029         u32 cntdn, count;
2030         u32 int_status;
2031         u32 doorbell;
2032
2033         count = 0;
2034         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
2035         do {
2036                 int_status = readl(&ioc->chip->HostInterruptStatus);
2037                 if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
2038                         dhsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: "
2039                             "successfull count(%d), timeout(%d)\n", ioc->name,
2040                             __func__, count, timeout));
2041                         return 0;
2042                 } else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
2043                         doorbell = readl(&ioc->chip->Doorbell);
2044                         if ((doorbell & MPI2_IOC_STATE_MASK) ==
2045                             MPI2_IOC_STATE_FAULT) {
2046                                 mpt2sas_base_fault_info(ioc , doorbell);
2047                                 return -EFAULT;
2048                         }
2049                 } else if (int_status == 0xFFFFFFFF)
2050                         goto out;
2051
2052                 if (sleep_flag == CAN_SLEEP)
2053                         msleep(1);
2054                 else
2055                         udelay(500);
2056                 count++;
2057         } while (--cntdn);
2058
2059  out:
2060         printk(MPT2SAS_ERR_FMT "%s: failed due to timeout count(%d), "
2061             "int_status(%x)!\n", ioc->name, __func__, count, int_status);
2062         return -EFAULT;
2063 }
2064
2065 /**
2066  * _base_wait_for_doorbell_not_used - waiting for doorbell to not be in use
2067  * @ioc: per adapter object
2068  * @timeout: timeout in second
2069  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2070  *
2071  * Returns 0 for success, non-zero for failure.
2072  *
2073  */
2074 static int
2075 _base_wait_for_doorbell_not_used(struct MPT2SAS_ADAPTER *ioc, int timeout,
2076     int sleep_flag)
2077 {
2078         u32 cntdn, count;
2079         u32 doorbell_reg;
2080
2081         count = 0;
2082         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
2083         do {
2084                 doorbell_reg = readl(&ioc->chip->Doorbell);
2085                 if (!(doorbell_reg & MPI2_DOORBELL_USED)) {
2086                         dhsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: "
2087                             "successfull count(%d), timeout(%d)\n", ioc->name,
2088                             __func__, count, timeout));
2089                         return 0;
2090                 }
2091                 if (sleep_flag == CAN_SLEEP)
2092                         msleep(1);
2093                 else
2094                         udelay(500);
2095                 count++;
2096         } while (--cntdn);
2097
2098         printk(MPT2SAS_ERR_FMT "%s: failed due to timeout count(%d), "
2099             "doorbell_reg(%x)!\n", ioc->name, __func__, count, doorbell_reg);
2100         return -EFAULT;
2101 }
2102
2103 /**
2104  * _base_send_ioc_reset - send doorbell reset
2105  * @ioc: per adapter object
2106  * @reset_type: currently only supports: MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET
2107  * @timeout: timeout in second
2108  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2109  *
2110  * Returns 0 for success, non-zero for failure.
2111  */
2112 static int
2113 _base_send_ioc_reset(struct MPT2SAS_ADAPTER *ioc, u8 reset_type, int timeout,
2114     int sleep_flag)
2115 {
2116         u32 ioc_state;
2117         int r = 0;
2118
2119         if (reset_type != MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET) {
2120                 printk(MPT2SAS_ERR_FMT "%s: unknown reset_type\n",
2121                     ioc->name, __func__);
2122                 return -EFAULT;
2123         }
2124
2125         if (!(ioc->facts.IOCCapabilities &
2126            MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY))
2127                 return -EFAULT;
2128
2129         printk(MPT2SAS_INFO_FMT "sending message unit reset !!\n", ioc->name);
2130
2131         writel(reset_type << MPI2_DOORBELL_FUNCTION_SHIFT,
2132             &ioc->chip->Doorbell);
2133         if ((_base_wait_for_doorbell_ack(ioc, 15, sleep_flag))) {
2134                 r = -EFAULT;
2135                 goto out;
2136         }
2137         ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY,
2138             timeout, sleep_flag);
2139         if (ioc_state) {
2140                 printk(MPT2SAS_ERR_FMT "%s: failed going to ready state "
2141                     " (ioc_state=0x%x)\n", ioc->name, __func__, ioc_state);
2142                 r = -EFAULT;
2143                 goto out;
2144         }
2145  out:
2146         printk(MPT2SAS_INFO_FMT "message unit reset: %s\n",
2147             ioc->name, ((r == 0) ? "SUCCESS" : "FAILED"));
2148         return r;
2149 }
2150
2151 /**
2152  * _base_handshake_req_reply_wait - send request thru doorbell interface
2153  * @ioc: per adapter object
2154  * @request_bytes: request length
2155  * @request: pointer having request payload
2156  * @reply_bytes: reply length
2157  * @reply: pointer to reply payload
2158  * @timeout: timeout in second
2159  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2160  *
2161  * Returns 0 for success, non-zero for failure.
2162  */
2163 static int
2164 _base_handshake_req_reply_wait(struct MPT2SAS_ADAPTER *ioc, int request_bytes,
2165     u32 *request, int reply_bytes, u16 *reply, int timeout, int sleep_flag)
2166 {
2167         MPI2DefaultReply_t *default_reply = (MPI2DefaultReply_t *)reply;
2168         int i;
2169         u8 failed;
2170         u16 dummy;
2171         u32 *mfp;
2172
2173         /* make sure doorbell is not in use */
2174         if ((readl(&ioc->chip->Doorbell) & MPI2_DOORBELL_USED)) {
2175                 printk(MPT2SAS_ERR_FMT "doorbell is in use "
2176                     " (line=%d)\n", ioc->name, __LINE__);
2177                 return -EFAULT;
2178         }
2179
2180         /* clear pending doorbell interrupts from previous state changes */
2181         if (readl(&ioc->chip->HostInterruptStatus) &
2182             MPI2_HIS_IOC2SYS_DB_STATUS)
2183                 writel(0, &ioc->chip->HostInterruptStatus);
2184
2185         /* send message to ioc */
2186         writel(((MPI2_FUNCTION_HANDSHAKE<<MPI2_DOORBELL_FUNCTION_SHIFT) |
2187             ((request_bytes/4)<<MPI2_DOORBELL_ADD_DWORDS_SHIFT)),
2188             &ioc->chip->Doorbell);
2189
2190         if ((_base_wait_for_doorbell_int(ioc, 5, sleep_flag))) {
2191                 printk(MPT2SAS_ERR_FMT "doorbell handshake "
2192                    "int failed (line=%d)\n", ioc->name, __LINE__);
2193                 return -EFAULT;
2194         }
2195         writel(0, &ioc->chip->HostInterruptStatus);
2196
2197         if ((_base_wait_for_doorbell_ack(ioc, 5, sleep_flag))) {
2198                 printk(MPT2SAS_ERR_FMT "doorbell handshake "
2199                     "ack failed (line=%d)\n", ioc->name, __LINE__);
2200                 return -EFAULT;
2201         }
2202
2203         /* send message 32-bits at a time */
2204         for (i = 0, failed = 0; i < request_bytes/4 && !failed; i++) {
2205                 writel(cpu_to_le32(request[i]), &ioc->chip->Doorbell);
2206                 if ((_base_wait_for_doorbell_ack(ioc, 5, sleep_flag)))
2207                         failed = 1;
2208         }
2209
2210         if (failed) {
2211                 printk(MPT2SAS_ERR_FMT "doorbell handshake "
2212                     "sending request failed (line=%d)\n", ioc->name, __LINE__);
2213                 return -EFAULT;
2214         }
2215
2216         /* now wait for the reply */
2217         if ((_base_wait_for_doorbell_int(ioc, timeout, sleep_flag))) {
2218                 printk(MPT2SAS_ERR_FMT "doorbell handshake "
2219                    "int failed (line=%d)\n", ioc->name, __LINE__);
2220                 return -EFAULT;
2221         }
2222
2223         /* read the first two 16-bits, it gives the total length of the reply */
2224         reply[0] = le16_to_cpu(readl(&ioc->chip->Doorbell)
2225             & MPI2_DOORBELL_DATA_MASK);
2226         writel(0, &ioc->chip->HostInterruptStatus);
2227         if ((_base_wait_for_doorbell_int(ioc, 5, sleep_flag))) {
2228                 printk(MPT2SAS_ERR_FMT "doorbell handshake "
2229                    "int failed (line=%d)\n", ioc->name, __LINE__);
2230                 return -EFAULT;
2231         }
2232         reply[1] = le16_to_cpu(readl(&ioc->chip->Doorbell)
2233             & MPI2_DOORBELL_DATA_MASK);
2234         writel(0, &ioc->chip->HostInterruptStatus);
2235
2236         for (i = 2; i < default_reply->MsgLength * 2; i++)  {
2237                 if ((_base_wait_for_doorbell_int(ioc, 5, sleep_flag))) {
2238                         printk(MPT2SAS_ERR_FMT "doorbell "
2239                             "handshake int failed (line=%d)\n", ioc->name,
2240                             __LINE__);
2241                         return -EFAULT;
2242                 }
2243                 if (i >=  reply_bytes/2) /* overflow case */
2244                         dummy = readl(&ioc->chip->Doorbell);
2245                 else
2246                         reply[i] = le16_to_cpu(readl(&ioc->chip->Doorbell)
2247                             & MPI2_DOORBELL_DATA_MASK);
2248                 writel(0, &ioc->chip->HostInterruptStatus);
2249         }
2250
2251         _base_wait_for_doorbell_int(ioc, 5, sleep_flag);
2252         if (_base_wait_for_doorbell_not_used(ioc, 5, sleep_flag) != 0) {
2253                 dhsprintk(ioc, printk(MPT2SAS_INFO_FMT "doorbell is in use "
2254                     " (line=%d)\n", ioc->name, __LINE__));
2255         }
2256         writel(0, &ioc->chip->HostInterruptStatus);
2257
2258         if (ioc->logging_level & MPT_DEBUG_INIT) {
2259                 mfp = (u32 *)reply;
2260                 printk(KERN_DEBUG "\toffset:data\n");
2261                 for (i = 0; i < reply_bytes/4; i++)
2262                         printk(KERN_DEBUG "\t[0x%02x]:%08x\n", i*4,
2263                             le32_to_cpu(mfp[i]));
2264         }
2265         return 0;
2266 }
2267
2268 /**
2269  * mpt2sas_base_sas_iounit_control - send sas iounit control to FW
2270  * @ioc: per adapter object
2271  * @mpi_reply: the reply payload from FW
2272  * @mpi_request: the request payload sent to FW
2273  *
2274  * The SAS IO Unit Control Request message allows the host to perform low-level
2275  * operations, such as resets on the PHYs of the IO Unit, also allows the host
2276  * to obtain the IOC assigned device handles for a device if it has other
2277  * identifying information about the device, in addition allows the host to
2278  * remove IOC resources associated with the device.
2279  *
2280  * Returns 0 for success, non-zero for failure.
2281  */
2282 int
2283 mpt2sas_base_sas_iounit_control(struct MPT2SAS_ADAPTER *ioc,
2284     Mpi2SasIoUnitControlReply_t *mpi_reply,
2285     Mpi2SasIoUnitControlRequest_t *mpi_request)
2286 {
2287         u16 smid;
2288         u32 ioc_state;
2289         unsigned long timeleft;
2290         u8 issue_reset;
2291         int rc;
2292         void *request;
2293         u16 wait_state_count;
2294
2295         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
2296             __func__));
2297
2298         mutex_lock(&ioc->base_cmds.mutex);
2299
2300         if (ioc->base_cmds.status != MPT2_CMD_NOT_USED) {
2301                 printk(MPT2SAS_ERR_FMT "%s: base_cmd in use\n",
2302                     ioc->name, __func__);
2303                 rc = -EAGAIN;
2304                 goto out;
2305         }
2306
2307         wait_state_count = 0;
2308         ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
2309         while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
2310                 if (wait_state_count++ == 10) {
2311                         printk(MPT2SAS_ERR_FMT
2312                             "%s: failed due to ioc not operational\n",
2313                             ioc->name, __func__);
2314                         rc = -EFAULT;
2315                         goto out;
2316                 }
2317                 ssleep(1);
2318                 ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
2319                 printk(MPT2SAS_INFO_FMT "%s: waiting for "
2320                     "operational state(count=%d)\n", ioc->name,
2321                     __func__, wait_state_count);
2322         }
2323
2324         smid = mpt2sas_base_get_smid(ioc, ioc->base_cb_idx);
2325         if (!smid) {
2326                 printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
2327                     ioc->name, __func__);
2328                 rc = -EAGAIN;
2329                 goto out;
2330         }
2331
2332         rc = 0;
2333         ioc->base_cmds.status = MPT2_CMD_PENDING;
2334         request = mpt2sas_base_get_msg_frame(ioc, smid);
2335         ioc->base_cmds.smid = smid;
2336         memcpy(request, mpi_request, sizeof(Mpi2SasIoUnitControlRequest_t));
2337         if (mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
2338             mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET)
2339                 ioc->ioc_link_reset_in_progress = 1;
2340         mpt2sas_base_put_smid_default(ioc, smid, mpi_request->VF_ID);
2341         timeleft = wait_for_completion_timeout(&ioc->base_cmds.done,
2342             msecs_to_jiffies(10000));
2343         if ((mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
2344             mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET) &&
2345             ioc->ioc_link_reset_in_progress)
2346                 ioc->ioc_link_reset_in_progress = 0;
2347         if (!(ioc->base_cmds.status & MPT2_CMD_COMPLETE)) {
2348                 printk(MPT2SAS_ERR_FMT "%s: timeout\n",
2349                     ioc->name, __func__);
2350                 _debug_dump_mf(mpi_request,
2351                     sizeof(Mpi2SasIoUnitControlRequest_t)/4);
2352                 if (!(ioc->base_cmds.status & MPT2_CMD_RESET))
2353                         issue_reset = 1;
2354                 goto issue_host_reset;
2355         }
2356         if (ioc->base_cmds.status & MPT2_CMD_REPLY_VALID)
2357                 memcpy(mpi_reply, ioc->base_cmds.reply,
2358                     sizeof(Mpi2SasIoUnitControlReply_t));
2359         else
2360                 memset(mpi_reply, 0, sizeof(Mpi2SasIoUnitControlReply_t));
2361         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
2362         goto out;
2363
2364  issue_host_reset:
2365         if (issue_reset)
2366                 mpt2sas_base_hard_reset_handler(ioc, CAN_SLEEP,
2367                     FORCE_BIG_HAMMER);
2368         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
2369         rc = -EFAULT;
2370  out:
2371         mutex_unlock(&ioc->base_cmds.mutex);
2372         return rc;
2373 }
2374
2375
2376 /**
2377  * mpt2sas_base_scsi_enclosure_processor - sending request to sep device
2378  * @ioc: per adapter object
2379  * @mpi_reply: the reply payload from FW
2380  * @mpi_request: the request payload sent to FW
2381  *
2382  * The SCSI Enclosure Processor request message causes the IOC to
2383  * communicate with SES devices to control LED status signals.
2384  *
2385  * Returns 0 for success, non-zero for failure.
2386  */
2387 int
2388 mpt2sas_base_scsi_enclosure_processor(struct MPT2SAS_ADAPTER *ioc,
2389     Mpi2SepReply_t *mpi_reply, Mpi2SepRequest_t *mpi_request)
2390 {
2391         u16 smid;
2392         u32 ioc_state;
2393         unsigned long timeleft;
2394         u8 issue_reset;
2395         int rc;
2396         void *request;
2397         u16 wait_state_count;
2398
2399         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
2400             __func__));
2401
2402         mutex_lock(&ioc->base_cmds.mutex);
2403
2404         if (ioc->base_cmds.status != MPT2_CMD_NOT_USED) {
2405                 printk(MPT2SAS_ERR_FMT "%s: base_cmd in use\n",
2406                     ioc->name, __func__);
2407                 rc = -EAGAIN;
2408                 goto out;
2409         }
2410
2411         wait_state_count = 0;
2412         ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
2413         while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
2414                 if (wait_state_count++ == 10) {
2415                         printk(MPT2SAS_ERR_FMT
2416                             "%s: failed due to ioc not operational\n",
2417                             ioc->name, __func__);
2418                         rc = -EFAULT;
2419                         goto out;
2420                 }
2421                 ssleep(1);
2422                 ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
2423                 printk(MPT2SAS_INFO_FMT "%s: waiting for "
2424                     "operational state(count=%d)\n", ioc->name,
2425                     __func__, wait_state_count);
2426         }
2427
2428         smid = mpt2sas_base_get_smid(ioc, ioc->base_cb_idx);
2429         if (!smid) {
2430                 printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
2431                     ioc->name, __func__);
2432                 rc = -EAGAIN;
2433                 goto out;
2434         }
2435
2436         rc = 0;
2437         ioc->base_cmds.status = MPT2_CMD_PENDING;
2438         request = mpt2sas_base_get_msg_frame(ioc, smid);
2439         ioc->base_cmds.smid = smid;
2440         memcpy(request, mpi_request, sizeof(Mpi2SepReply_t));
2441         mpt2sas_base_put_smid_default(ioc, smid, mpi_request->VF_ID);
2442         timeleft = wait_for_completion_timeout(&ioc->base_cmds.done,
2443             msecs_to_jiffies(10000));
2444         if (!(ioc->base_cmds.status & MPT2_CMD_COMPLETE)) {
2445                 printk(MPT2SAS_ERR_FMT "%s: timeout\n",
2446                     ioc->name, __func__);
2447                 _debug_dump_mf(mpi_request,
2448                     sizeof(Mpi2SepRequest_t)/4);
2449                 if (!(ioc->base_cmds.status & MPT2_CMD_RESET))
2450                         issue_reset = 1;
2451                 goto issue_host_reset;
2452         }
2453         if (ioc->base_cmds.status & MPT2_CMD_REPLY_VALID)
2454                 memcpy(mpi_reply, ioc->base_cmds.reply,
2455                     sizeof(Mpi2SepReply_t));
2456         else
2457                 memset(mpi_reply, 0, sizeof(Mpi2SepReply_t));
2458         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
2459         goto out;
2460
2461  issue_host_reset:
2462         if (issue_reset)
2463                 mpt2sas_base_hard_reset_handler(ioc, CAN_SLEEP,
2464                     FORCE_BIG_HAMMER);
2465         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
2466         rc = -EFAULT;
2467  out:
2468         mutex_unlock(&ioc->base_cmds.mutex);
2469         return rc;
2470 }
2471
2472 /**
2473  * _base_get_port_facts - obtain port facts reply and save in ioc
2474  * @ioc: per adapter object
2475  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2476  *
2477  * Returns 0 for success, non-zero for failure.
2478  */
2479 static int
2480 _base_get_port_facts(struct MPT2SAS_ADAPTER *ioc, int port, int sleep_flag)
2481 {
2482         Mpi2PortFactsRequest_t mpi_request;
2483         Mpi2PortFactsReply_t mpi_reply, *pfacts;
2484         int mpi_reply_sz, mpi_request_sz, r;
2485
2486         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
2487             __func__));
2488
2489         mpi_reply_sz = sizeof(Mpi2PortFactsReply_t);
2490         mpi_request_sz = sizeof(Mpi2PortFactsRequest_t);
2491         memset(&mpi_request, 0, mpi_request_sz);
2492         mpi_request.Function = MPI2_FUNCTION_PORT_FACTS;
2493         mpi_request.PortNumber = port;
2494         r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
2495             (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5, CAN_SLEEP);
2496
2497         if (r != 0) {
2498                 printk(MPT2SAS_ERR_FMT "%s: handshake failed (r=%d)\n",
2499                     ioc->name, __func__, r);
2500                 return r;
2501         }
2502
2503         pfacts = &ioc->pfacts[port];
2504         memset(pfacts, 0, sizeof(Mpi2PortFactsReply_t));
2505         pfacts->PortNumber = mpi_reply.PortNumber;
2506         pfacts->VP_ID = mpi_reply.VP_ID;
2507         pfacts->VF_ID = mpi_reply.VF_ID;
2508         pfacts->MaxPostedCmdBuffers =
2509             le16_to_cpu(mpi_reply.MaxPostedCmdBuffers);
2510
2511         return 0;
2512 }
2513
2514 /**
2515  * _base_get_ioc_facts - obtain ioc facts reply and save in ioc
2516  * @ioc: per adapter object
2517  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2518  *
2519  * Returns 0 for success, non-zero for failure.
2520  */
2521 static int
2522 _base_get_ioc_facts(struct MPT2SAS_ADAPTER *ioc, int sleep_flag)
2523 {
2524         Mpi2IOCFactsRequest_t mpi_request;
2525         Mpi2IOCFactsReply_t mpi_reply, *facts;
2526         int mpi_reply_sz, mpi_request_sz, r;
2527
2528         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
2529             __func__));
2530
2531         mpi_reply_sz = sizeof(Mpi2IOCFactsReply_t);
2532         mpi_request_sz = sizeof(Mpi2IOCFactsRequest_t);
2533         memset(&mpi_request, 0, mpi_request_sz);
2534         mpi_request.Function = MPI2_FUNCTION_IOC_FACTS;
2535         r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
2536             (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5, CAN_SLEEP);
2537
2538         if (r != 0) {
2539                 printk(MPT2SAS_ERR_FMT "%s: handshake failed (r=%d)\n",
2540                     ioc->name, __func__, r);
2541                 return r;
2542         }
2543
2544         facts = &ioc->facts;
2545         memset(facts, 0, sizeof(Mpi2IOCFactsReply_t));
2546         facts->MsgVersion = le16_to_cpu(mpi_reply.MsgVersion);
2547         facts->HeaderVersion = le16_to_cpu(mpi_reply.HeaderVersion);
2548         facts->VP_ID = mpi_reply.VP_ID;
2549         facts->VF_ID = mpi_reply.VF_ID;
2550         facts->IOCExceptions = le16_to_cpu(mpi_reply.IOCExceptions);
2551         facts->MaxChainDepth = mpi_reply.MaxChainDepth;
2552         facts->WhoInit = mpi_reply.WhoInit;
2553         facts->NumberOfPorts = mpi_reply.NumberOfPorts;
2554         facts->RequestCredit = le16_to_cpu(mpi_reply.RequestCredit);
2555         facts->MaxReplyDescriptorPostQueueDepth =
2556             le16_to_cpu(mpi_reply.MaxReplyDescriptorPostQueueDepth);
2557         facts->ProductID = le16_to_cpu(mpi_reply.ProductID);
2558         facts->IOCCapabilities = le32_to_cpu(mpi_reply.IOCCapabilities);
2559         if ((facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID))
2560                 ioc->ir_firmware = 1;
2561         facts->FWVersion.Word = le32_to_cpu(mpi_reply.FWVersion.Word);
2562         facts->IOCRequestFrameSize =
2563             le16_to_cpu(mpi_reply.IOCRequestFrameSize);
2564         facts->MaxInitiators = le16_to_cpu(mpi_reply.MaxInitiators);
2565         facts->MaxTargets = le16_to_cpu(mpi_reply.MaxTargets);
2566         ioc->shost->max_id = -1;
2567         facts->MaxSasExpanders = le16_to_cpu(mpi_reply.MaxSasExpanders);
2568         facts->MaxEnclosures = le16_to_cpu(mpi_reply.MaxEnclosures);
2569         facts->ProtocolFlags = le16_to_cpu(mpi_reply.ProtocolFlags);
2570         facts->HighPriorityCredit =
2571             le16_to_cpu(mpi_reply.HighPriorityCredit);
2572         facts->ReplyFrameSize = mpi_reply.ReplyFrameSize;
2573         facts->MaxDevHandle = le16_to_cpu(mpi_reply.MaxDevHandle);
2574
2575         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "hba queue depth(%d), "
2576             "max chains per io(%d)\n", ioc->name, facts->RequestCredit,
2577             facts->MaxChainDepth));
2578         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "request frame size(%d), "
2579             "reply frame size(%d)\n", ioc->name,
2580             facts->IOCRequestFrameSize * 4, facts->ReplyFrameSize * 4));
2581         return 0;
2582 }
2583
2584 /**
2585  * _base_send_ioc_init - send ioc_init to firmware
2586  * @ioc: per adapter object
2587  * @VF_ID: virtual function id
2588  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2589  *
2590  * Returns 0 for success, non-zero for failure.
2591  */
2592 static int
2593 _base_send_ioc_init(struct MPT2SAS_ADAPTER *ioc, u8 VF_ID, int sleep_flag)
2594 {
2595         Mpi2IOCInitRequest_t mpi_request;
2596         Mpi2IOCInitReply_t mpi_reply;
2597         int r;
2598
2599         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
2600             __func__));
2601
2602         memset(&mpi_request, 0, sizeof(Mpi2IOCInitRequest_t));
2603         mpi_request.Function = MPI2_FUNCTION_IOC_INIT;
2604         mpi_request.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
2605         mpi_request.VF_ID = VF_ID;
2606         mpi_request.MsgVersion = cpu_to_le16(MPI2_VERSION);
2607         mpi_request.HeaderVersion = cpu_to_le16(MPI2_HEADER_VERSION);
2608
2609         /* In MPI Revision I (0xA), the SystemReplyFrameSize(offset 0x18) was
2610          * removed and made reserved.  For those with older firmware will need
2611          * this fix. It was decided that the Reply and Request frame sizes are
2612          * the same.
2613          */
2614         if ((ioc->facts.HeaderVersion >> 8) < 0xA) {
2615                 mpi_request.Reserved7 = cpu_to_le16(ioc->reply_sz);
2616 /*              mpi_request.SystemReplyFrameSize =
2617  *               cpu_to_le16(ioc->reply_sz);
2618  */
2619         }
2620
2621         mpi_request.SystemRequestFrameSize = cpu_to_le16(ioc->request_sz/4);
2622         mpi_request.ReplyDescriptorPostQueueDepth =
2623             cpu_to_le16(ioc->reply_post_queue_depth);
2624         mpi_request.ReplyFreeQueueDepth =
2625             cpu_to_le16(ioc->reply_free_queue_depth);
2626
2627 #if BITS_PER_LONG > 32
2628         mpi_request.SenseBufferAddressHigh =
2629             cpu_to_le32(ioc->sense_dma >> 32);
2630         mpi_request.SystemReplyAddressHigh =
2631             cpu_to_le32(ioc->reply_dma >> 32);
2632         mpi_request.SystemRequestFrameBaseAddress =
2633             cpu_to_le64(ioc->request_dma);
2634         mpi_request.ReplyFreeQueueAddress =
2635             cpu_to_le64(ioc->reply_free_dma);
2636         mpi_request.ReplyDescriptorPostQueueAddress =
2637             cpu_to_le64(ioc->reply_post_free_dma);
2638 #else
2639         mpi_request.SystemRequestFrameBaseAddress =
2640             cpu_to_le32(ioc->request_dma);
2641         mpi_request.ReplyFreeQueueAddress =
2642             cpu_to_le32(ioc->reply_free_dma);
2643         mpi_request.ReplyDescriptorPostQueueAddress =
2644             cpu_to_le32(ioc->reply_post_free_dma);
2645 #endif
2646
2647         if (ioc->logging_level & MPT_DEBUG_INIT) {
2648                 u32 *mfp;
2649                 int i;
2650
2651                 mfp = (u32 *)&mpi_request;
2652                 printk(KERN_DEBUG "\toffset:data\n");
2653                 for (i = 0; i < sizeof(Mpi2IOCInitRequest_t)/4; i++)
2654                         printk(KERN_DEBUG "\t[0x%02x]:%08x\n", i*4,
2655                             le32_to_cpu(mfp[i]));
2656         }
2657
2658         r = _base_handshake_req_reply_wait(ioc,
2659             sizeof(Mpi2IOCInitRequest_t), (u32 *)&mpi_request,
2660             sizeof(Mpi2IOCInitReply_t), (u16 *)&mpi_reply, 10,
2661             sleep_flag);
2662
2663         if (r != 0) {
2664                 printk(MPT2SAS_ERR_FMT "%s: handshake failed (r=%d)\n",
2665                     ioc->name, __func__, r);
2666                 return r;
2667         }
2668
2669         if (mpi_reply.IOCStatus != MPI2_IOCSTATUS_SUCCESS ||
2670             mpi_reply.IOCLogInfo) {
2671                 printk(MPT2SAS_ERR_FMT "%s: failed\n", ioc->name, __func__);
2672                 r = -EIO;
2673         }
2674
2675         return 0;
2676 }
2677
2678 /**
2679  * _base_send_port_enable - send port_enable(discovery stuff) to firmware
2680  * @ioc: per adapter object
2681  * @VF_ID: virtual function id
2682  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2683  *
2684  * Returns 0 for success, non-zero for failure.
2685  */
2686 static int
2687 _base_send_port_enable(struct MPT2SAS_ADAPTER *ioc, u8 VF_ID, int sleep_flag)
2688 {
2689         Mpi2PortEnableRequest_t *mpi_request;
2690         u32 ioc_state;
2691         unsigned long timeleft;
2692         int r = 0;
2693         u16 smid;
2694
2695         printk(MPT2SAS_INFO_FMT "sending port enable !!\n", ioc->name);
2696
2697         if (ioc->base_cmds.status & MPT2_CMD_PENDING) {
2698                 printk(MPT2SAS_ERR_FMT "%s: internal command already in use\n",
2699                     ioc->name, __func__);
2700                 return -EAGAIN;
2701         }
2702
2703         smid = mpt2sas_base_get_smid(ioc, ioc->base_cb_idx);
2704         if (!smid) {
2705                 printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
2706                     ioc->name, __func__);
2707                 return -EAGAIN;
2708         }
2709
2710         ioc->base_cmds.status = MPT2_CMD_PENDING;
2711         mpi_request = mpt2sas_base_get_msg_frame(ioc, smid);
2712         ioc->base_cmds.smid = smid;
2713         memset(mpi_request, 0, sizeof(Mpi2PortEnableRequest_t));
2714         mpi_request->Function = MPI2_FUNCTION_PORT_ENABLE;
2715         mpi_request->VF_ID = VF_ID;
2716
2717         mpt2sas_base_put_smid_default(ioc, smid, VF_ID);
2718         timeleft = wait_for_completion_timeout(&ioc->base_cmds.done,
2719             300*HZ);
2720         if (!(ioc->base_cmds.status & MPT2_CMD_COMPLETE)) {
2721                 printk(MPT2SAS_ERR_FMT "%s: timeout\n",
2722                     ioc->name, __func__);
2723                 _debug_dump_mf(mpi_request,
2724                     sizeof(Mpi2PortEnableRequest_t)/4);
2725                 if (ioc->base_cmds.status & MPT2_CMD_RESET)
2726                         r = -EFAULT;
2727                 else
2728                         r = -ETIME;
2729                 goto out;
2730         } else
2731                 dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: complete\n",
2732                     ioc->name, __func__));
2733
2734         ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_OPERATIONAL,
2735             60, sleep_flag);
2736         if (ioc_state) {
2737                 printk(MPT2SAS_ERR_FMT "%s: failed going to operational state "
2738                     " (ioc_state=0x%x)\n", ioc->name, __func__, ioc_state);
2739                 r = -EFAULT;
2740         }
2741  out:
2742         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
2743         printk(MPT2SAS_INFO_FMT "port enable: %s\n",
2744             ioc->name, ((r == 0) ? "SUCCESS" : "FAILED"));
2745         return r;
2746 }
2747
2748 /**
2749  * _base_unmask_events - turn on notification for this event
2750  * @ioc: per adapter object
2751  * @event: firmware event
2752  *
2753  * The mask is stored in ioc->event_masks.
2754  */
2755 static void
2756 _base_unmask_events(struct MPT2SAS_ADAPTER *ioc, u16 event)
2757 {
2758         u32 desired_event;
2759
2760         if (event >= 128)
2761                 return;
2762
2763         desired_event = (1 << (event % 32));
2764
2765         if (event < 32)
2766                 ioc->event_masks[0] &= ~desired_event;
2767         else if (event < 64)
2768                 ioc->event_masks[1] &= ~desired_event;
2769         else if (event < 96)
2770                 ioc->event_masks[2] &= ~desired_event;
2771         else if (event < 128)
2772                 ioc->event_masks[3] &= ~desired_event;
2773 }
2774
2775 /**
2776  * _base_event_notification - send event notification
2777  * @ioc: per adapter object
2778  * @VF_ID: virtual function id
2779  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2780  *
2781  * Returns 0 for success, non-zero for failure.
2782  */
2783 static int
2784 _base_event_notification(struct MPT2SAS_ADAPTER *ioc, u8 VF_ID, int sleep_flag)
2785 {
2786         Mpi2EventNotificationRequest_t *mpi_request;
2787         unsigned long timeleft;
2788         u16 smid;
2789         int r = 0;
2790         int i;
2791
2792         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
2793             __func__));
2794
2795         if (ioc->base_cmds.status & MPT2_CMD_PENDING) {
2796                 printk(MPT2SAS_ERR_FMT "%s: internal command already in use\n",
2797                     ioc->name, __func__);
2798                 return -EAGAIN;
2799         }
2800
2801         smid = mpt2sas_base_get_smid(ioc, ioc->base_cb_idx);
2802         if (!smid) {
2803                 printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
2804                     ioc->name, __func__);
2805                 return -EAGAIN;
2806         }
2807         ioc->base_cmds.status = MPT2_CMD_PENDING;
2808         mpi_request = mpt2sas_base_get_msg_frame(ioc, smid);
2809         ioc->base_cmds.smid = smid;
2810         memset(mpi_request, 0, sizeof(Mpi2EventNotificationRequest_t));
2811         mpi_request->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2812         mpi_request->VF_ID = VF_ID;
2813         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2814                 mpi_request->EventMasks[i] =
2815                     le32_to_cpu(ioc->event_masks[i]);
2816         mpt2sas_base_put_smid_default(ioc, smid, VF_ID);
2817         timeleft = wait_for_completion_timeout(&ioc->base_cmds.done, 30*HZ);
2818         if (!(ioc->base_cmds.status & MPT2_CMD_COMPLETE)) {
2819                 printk(MPT2SAS_ERR_FMT "%s: timeout\n",
2820                     ioc->name, __func__);
2821                 _debug_dump_mf(mpi_request,
2822                     sizeof(Mpi2EventNotificationRequest_t)/4);
2823                 if (ioc->base_cmds.status & MPT2_CMD_RESET)
2824                         r = -EFAULT;
2825                 else
2826                         r = -ETIME;
2827         } else
2828                 dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: complete\n",
2829                     ioc->name, __func__));
2830         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
2831         return r;
2832 }
2833
2834 /**
2835  * mpt2sas_base_validate_event_type - validating event types
2836  * @ioc: per adapter object
2837  * @event: firmware event
2838  *
2839  * This will turn on firmware event notification when application
2840  * ask for that event. We don't mask events that are already enabled.
2841  */
2842 void
2843 mpt2sas_base_validate_event_type(struct MPT2SAS_ADAPTER *ioc, u32 *event_type)
2844 {
2845         int i, j;
2846         u32 event_mask, desired_event;
2847         u8 send_update_to_fw;
2848
2849         for (i = 0, send_update_to_fw = 0; i <
2850             MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++) {
2851                 event_mask = ~event_type[i];
2852                 desired_event = 1;
2853                 for (j = 0; j < 32; j++) {
2854                         if (!(event_mask & desired_event) &&
2855                             (ioc->event_masks[i] & desired_event)) {
2856                                 ioc->event_masks[i] &= ~desired_event;
2857                                 send_update_to_fw = 1;
2858                         }
2859                         desired_event = (desired_event << 1);
2860                 }
2861         }
2862
2863         if (!send_update_to_fw)
2864                 return;
2865
2866         mutex_lock(&ioc->base_cmds.mutex);
2867         _base_event_notification(ioc, 0, CAN_SLEEP);
2868         mutex_unlock(&ioc->base_cmds.mutex);
2869 }
2870
2871 /**
2872  * _base_diag_reset - the "big hammer" start of day reset
2873  * @ioc: per adapter object
2874  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2875  *
2876  * Returns 0 for success, non-zero for failure.
2877  */
2878 static int
2879 _base_diag_reset(struct MPT2SAS_ADAPTER *ioc, int sleep_flag)
2880 {
2881         u32 host_diagnostic;
2882         u32 ioc_state;
2883         u32 count;
2884         u32 hcb_size;
2885
2886         printk(MPT2SAS_INFO_FMT "sending diag reset !!\n", ioc->name);
2887
2888         _base_save_msix_table(ioc);
2889
2890         drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "clear interrupts\n",
2891             ioc->name));
2892         writel(0, &ioc->chip->HostInterruptStatus);
2893
2894         count = 0;
2895         do {
2896                 /* Write magic sequence to WriteSequence register
2897                  * Loop until in diagnostic mode
2898                  */
2899                 drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "write magic "
2900                     "sequence\n", ioc->name));
2901                 writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
2902                 writel(MPI2_WRSEQ_1ST_KEY_VALUE, &ioc->chip->WriteSequence);
2903                 writel(MPI2_WRSEQ_2ND_KEY_VALUE, &ioc->chip->WriteSequence);
2904                 writel(MPI2_WRSEQ_3RD_KEY_VALUE, &ioc->chip->WriteSequence);
2905                 writel(MPI2_WRSEQ_4TH_KEY_VALUE, &ioc->chip->WriteSequence);
2906                 writel(MPI2_WRSEQ_5TH_KEY_VALUE, &ioc->chip->WriteSequence);
2907                 writel(MPI2_WRSEQ_6TH_KEY_VALUE, &ioc->chip->WriteSequence);
2908
2909                 /* wait 100 msec */
2910                 if (sleep_flag == CAN_SLEEP)
2911                         msleep(100);
2912                 else
2913                         mdelay(100);
2914
2915                 if (count++ > 20)
2916                         goto out;
2917
2918                 host_diagnostic = readl(&ioc->chip->HostDiagnostic);
2919                 drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "wrote magic "
2920                     "sequence: count(%d), host_diagnostic(0x%08x)\n",
2921                     ioc->name, count, host_diagnostic));
2922
2923         } while ((host_diagnostic & MPI2_DIAG_DIAG_WRITE_ENABLE) == 0);
2924
2925         hcb_size = readl(&ioc->chip->HCBSize);
2926
2927         drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "diag reset: issued\n",
2928             ioc->name));
2929         writel(host_diagnostic | MPI2_DIAG_RESET_ADAPTER,
2930              &ioc->chip->HostDiagnostic);
2931
2932         /* don't access any registers for 50 milliseconds */
2933         msleep(50);
2934
2935         /* 300 second max wait */
2936         for (count = 0; count < 3000000 ; count++) {
2937
2938                 host_diagnostic = readl(&ioc->chip->HostDiagnostic);
2939
2940                 if (host_diagnostic == 0xFFFFFFFF)
2941                         goto out;
2942                 if (!(host_diagnostic & MPI2_DIAG_RESET_ADAPTER))
2943                         break;
2944
2945                 /* wait 100 msec */
2946                 if (sleep_flag == CAN_SLEEP)
2947                         msleep(1);
2948                 else
2949                         mdelay(1);
2950         }
2951
2952         if (host_diagnostic & MPI2_DIAG_HCB_MODE) {
2953
2954                 drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "restart the adapter "
2955                     "assuming the HCB Address points to good F/W\n",
2956                     ioc->name));
2957                 host_diagnostic &= ~MPI2_DIAG_BOOT_DEVICE_SELECT_MASK;
2958                 host_diagnostic |= MPI2_DIAG_BOOT_DEVICE_SELECT_HCDW;
2959                 writel(host_diagnostic, &ioc->chip->HostDiagnostic);
2960
2961                 drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT
2962                     "re-enable the HCDW\n", ioc->name));
2963                 writel(hcb_size | MPI2_HCB_SIZE_HCB_ENABLE,
2964                     &ioc->chip->HCBSize);
2965         }
2966
2967         drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "restart the adapter\n",
2968             ioc->name));
2969         writel(host_diagnostic & ~MPI2_DIAG_HOLD_IOC_RESET,
2970             &ioc->chip->HostDiagnostic);
2971
2972         drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "disable writes to the "
2973             "diagnostic register\n", ioc->name));
2974         writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
2975
2976         drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "Wait for FW to go to the "
2977             "READY state\n", ioc->name));
2978         ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, 20,
2979             sleep_flag);
2980         if (ioc_state) {
2981                 printk(MPT2SAS_ERR_FMT "%s: failed going to ready state "
2982                     " (ioc_state=0x%x)\n", ioc->name, __func__, ioc_state);
2983                 goto out;
2984         }
2985
2986         _base_restore_msix_table(ioc);
2987         printk(MPT2SAS_INFO_FMT "diag reset: SUCCESS\n", ioc->name);
2988         return 0;
2989
2990  out:
2991         printk(MPT2SAS_ERR_FMT "diag reset: FAILED\n", ioc->name);
2992         return -EFAULT;
2993 }
2994
2995 /**
2996  * _base_make_ioc_ready - put controller in READY state
2997  * @ioc: per adapter object
2998  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2999  * @type: FORCE_BIG_HAMMER or SOFT_RESET
3000  *
3001  * Returns 0 for success, non-zero for failure.
3002  */
3003 static int
3004 _base_make_ioc_ready(struct MPT2SAS_ADAPTER *ioc, int sleep_flag,
3005     enum reset_type type)
3006 {
3007         u32 ioc_state;
3008
3009         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
3010             __func__));
3011
3012         ioc_state = mpt2sas_base_get_iocstate(ioc, 0);
3013         dhsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: ioc_state(0x%08x)\n",
3014             ioc->name, __func__, ioc_state));
3015
3016         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_READY)
3017                 return 0;
3018
3019         if (ioc_state & MPI2_DOORBELL_USED) {
3020                 dhsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "unexpected doorbell "
3021                     "active!\n", ioc->name));
3022                 goto issue_diag_reset;
3023         }
3024
3025         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
3026                 mpt2sas_base_fault_info(ioc, ioc_state &
3027                     MPI2_DOORBELL_DATA_MASK);
3028                 goto issue_diag_reset;
3029         }
3030
3031         if (type == FORCE_BIG_HAMMER)
3032                 goto issue_diag_reset;
3033
3034         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_OPERATIONAL)
3035                 if (!(_base_send_ioc_reset(ioc,
3036                     MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET, 15, CAN_SLEEP)))
3037                         return 0;
3038
3039  issue_diag_reset:
3040         return _base_diag_reset(ioc, CAN_SLEEP);
3041 }
3042
3043 /**
3044  * _base_make_ioc_operational - put controller in OPERATIONAL state
3045  * @ioc: per adapter object
3046  * @VF_ID: virtual function id
3047  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3048  *
3049  * Returns 0 for success, non-zero for failure.
3050  */
3051 static int
3052 _base_make_ioc_operational(struct MPT2SAS_ADAPTER *ioc, u8 VF_ID,
3053     int sleep_flag)
3054 {
3055         int r, i;
3056         unsigned long   flags;
3057         u32 reply_address;
3058
3059         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
3060             __func__));
3061
3062         /* initialize the scsi lookup free list */
3063         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3064         INIT_LIST_HEAD(&ioc->free_list);
3065         for (i = 0; i < ioc->request_depth; i++) {
3066                 ioc->scsi_lookup[i].cb_idx = 0xFF;
3067                 list_add_tail(&ioc->scsi_lookup[i].tracker_list,
3068                     &ioc->free_list);
3069         }
3070         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3071
3072         /* initialize Reply Free Queue */
3073         for (i = 0, reply_address = (u32)ioc->reply_dma ;
3074             i < ioc->reply_free_queue_depth ; i++, reply_address +=
3075             ioc->reply_sz)
3076                 ioc->reply_free[i] = cpu_to_le32(reply_address);
3077
3078         /* initialize Reply Post Free Queue */
3079         for (i = 0; i < ioc->reply_post_queue_depth; i++)
3080                 ioc->reply_post_free[i].Words = ULLONG_MAX;
3081
3082         r = _base_send_ioc_init(ioc, VF_ID, sleep_flag);
3083         if (r)
3084                 return r;
3085
3086         /* initialize the index's */
3087         ioc->reply_free_host_index = ioc->reply_free_queue_depth - 1;
3088         ioc->reply_post_host_index = 0;
3089         writel(ioc->reply_free_host_index, &ioc->chip->ReplyFreeHostIndex);
3090         writel(0, &ioc->chip->ReplyPostHostIndex);
3091
3092         _base_unmask_interrupts(ioc);
3093         r = _base_event_notification(ioc, VF_ID, sleep_flag);
3094         if (r)
3095                 return r;
3096
3097         if (sleep_flag == CAN_SLEEP)
3098                 _base_static_config_pages(ioc);
3099
3100         r = _base_send_port_enable(ioc, VF_ID, sleep_flag);
3101         if (r)
3102                 return r;
3103
3104         return r;
3105 }
3106
3107 /**
3108  * mpt2sas_base_free_resources - free resources controller resources (io/irq/memap)
3109  * @ioc: per adapter object
3110  *
3111  * Return nothing.
3112  */
3113 void
3114 mpt2sas_base_free_resources(struct MPT2SAS_ADAPTER *ioc)
3115 {
3116         struct pci_dev *pdev = ioc->pdev;
3117
3118         dexitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
3119             __func__));
3120
3121         _base_mask_interrupts(ioc);
3122         _base_make_ioc_ready(ioc, CAN_SLEEP, SOFT_RESET);
3123         if (ioc->pci_irq) {
3124                 synchronize_irq(pdev->irq);
3125                 free_irq(ioc->pci_irq, ioc);
3126         }
3127         _base_disable_msix(ioc);
3128         if (ioc->chip_phys)
3129                 iounmap(ioc->chip);
3130         ioc->pci_irq = -1;
3131         ioc->chip_phys = 0;
3132         pci_release_selected_regions(ioc->pdev, ioc->bars);
3133         pci_disable_device(pdev);
3134         pci_set_drvdata(pdev, NULL);
3135         return;
3136 }
3137
3138 /**
3139  * mpt2sas_base_attach - attach controller instance
3140  * @ioc: per adapter object
3141  *
3142  * Returns 0 for success, non-zero for failure.
3143  */
3144 int
3145 mpt2sas_base_attach(struct MPT2SAS_ADAPTER *ioc)
3146 {
3147         int r, i;
3148         unsigned long    flags;
3149
3150         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
3151             __func__));
3152
3153         r = mpt2sas_base_map_resources(ioc);
3154         if (r)
3155                 return r;
3156
3157         r = _base_make_ioc_ready(ioc, CAN_SLEEP, SOFT_RESET);
3158         if (r)
3159                 goto out_free_resources;
3160
3161         r = _base_get_ioc_facts(ioc, CAN_SLEEP);
3162         if (r)
3163                 goto out_free_resources;
3164
3165         r = _base_allocate_memory_pools(ioc, CAN_SLEEP);
3166         if (r)
3167                 goto out_free_resources;
3168
3169         init_waitqueue_head(&ioc->reset_wq);
3170
3171         /* base internal command bits */
3172         mutex_init(&ioc->base_cmds.mutex);
3173         init_completion(&ioc->base_cmds.done);
3174         ioc->base_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
3175         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
3176
3177         /* transport internal command bits */
3178         ioc->transport_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
3179         ioc->transport_cmds.status = MPT2_CMD_NOT_USED;
3180         mutex_init(&ioc->transport_cmds.mutex);
3181         init_completion(&ioc->transport_cmds.done);
3182
3183         /* task management internal command bits */
3184         ioc->tm_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
3185         ioc->tm_cmds.status = MPT2_CMD_NOT_USED;
3186         mutex_init(&ioc->tm_cmds.mutex);
3187         init_completion(&ioc->tm_cmds.done);
3188
3189         /* config page internal command bits */
3190         ioc->config_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
3191         ioc->config_cmds.status = MPT2_CMD_NOT_USED;
3192         mutex_init(&ioc->config_cmds.mutex);
3193         init_completion(&ioc->config_cmds.done);
3194
3195         /* ctl module internal command bits */
3196         ioc->ctl_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
3197         ioc->ctl_cmds.status = MPT2_CMD_NOT_USED;
3198         mutex_init(&ioc->ctl_cmds.mutex);
3199         init_completion(&ioc->ctl_cmds.done);
3200
3201         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
3202                 ioc->event_masks[i] = -1;
3203
3204         /* here we enable the events we care about */
3205         _base_unmask_events(ioc, MPI2_EVENT_SAS_DISCOVERY);
3206         _base_unmask_events(ioc, MPI2_EVENT_SAS_BROADCAST_PRIMITIVE);
3207         _base_unmask_events(ioc, MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST);
3208         _base_unmask_events(ioc, MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE);
3209         _base_unmask_events(ioc, MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE);
3210         _base_unmask_events(ioc, MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST);
3211         _base_unmask_events(ioc, MPI2_EVENT_IR_VOLUME);
3212         _base_unmask_events(ioc, MPI2_EVENT_IR_PHYSICAL_DISK);
3213         _base_unmask_events(ioc, MPI2_EVENT_IR_OPERATION_STATUS);
3214         _base_unmask_events(ioc, MPI2_EVENT_TASK_SET_FULL);
3215         _base_unmask_events(ioc, MPI2_EVENT_LOG_ENTRY_ADDED);
3216
3217         ioc->pfacts = kcalloc(ioc->facts.NumberOfPorts,
3218             sizeof(Mpi2PortFactsReply_t), GFP_KERNEL);
3219         if (!ioc->pfacts)
3220                 goto out_free_resources;
3221
3222         for (i = 0 ; i < ioc->facts.NumberOfPorts; i++) {
3223                 r = _base_get_port_facts(ioc, i, CAN_SLEEP);
3224                 if (r)
3225                         goto out_free_resources;
3226         }
3227         r = _base_make_ioc_operational(ioc, 0, CAN_SLEEP);
3228         if (r)
3229                 goto out_free_resources;
3230
3231         /* initialize fault polling */
3232         INIT_DELAYED_WORK(&ioc->fault_reset_work, _base_fault_reset_work);
3233         snprintf(ioc->fault_reset_work_q_name,
3234             sizeof(ioc->fault_reset_work_q_name), "poll_%d_status", ioc->id);
3235         ioc->fault_reset_work_q =
3236                 create_singlethread_workqueue(ioc->fault_reset_work_q_name);
3237         if (!ioc->fault_reset_work_q) {
3238                 printk(MPT2SAS_ERR_FMT "%s: failed (line=%d)\n",
3239                     ioc->name, __func__, __LINE__);
3240                         goto out_free_resources;
3241         }
3242         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
3243         if (ioc->fault_reset_work_q)
3244                 queue_delayed_work(ioc->fault_reset_work_q,
3245                     &ioc->fault_reset_work,
3246                     msecs_to_jiffies(FAULT_POLLING_INTERVAL));
3247         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
3248         return 0;
3249
3250  out_free_resources:
3251
3252         ioc->remove_host = 1;
3253         mpt2sas_base_free_resources(ioc);
3254         _base_release_memory_pools(ioc);
3255         kfree(ioc->tm_cmds.reply);
3256         kfree(ioc->transport_cmds.reply);
3257         kfree(ioc->config_cmds.reply);
3258         kfree(ioc->base_cmds.reply);
3259         kfree(ioc->ctl_cmds.reply);
3260         kfree(ioc->pfacts);
3261         ioc->ctl_cmds.reply = NULL;
3262         ioc->base_cmds.reply = NULL;
3263         ioc->tm_cmds.reply = NULL;
3264         ioc->transport_cmds.reply = NULL;
3265         ioc->config_cmds.reply = NULL;
3266         ioc->pfacts = NULL;
3267         return r;
3268 }
3269
3270
3271 /**
3272  * mpt2sas_base_detach - remove controller instance
3273  * @ioc: per adapter object
3274  *
3275  * Return nothing.
3276  */
3277 void
3278 mpt2sas_base_detach(struct MPT2SAS_ADAPTER *ioc)
3279 {
3280         unsigned long    flags;
3281         struct workqueue_struct *wq;
3282
3283         dexitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
3284             __func__));
3285
3286         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
3287         wq = ioc->fault_reset_work_q;
3288         ioc->fault_reset_work_q = NULL;
3289         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
3290         if (!cancel_delayed_work(&ioc->fault_reset_work))
3291                 flush_workqueue(wq);
3292         destroy_workqueue(wq);
3293
3294         mpt2sas_base_free_resources(ioc);
3295         _base_release_memory_pools(ioc);
3296         kfree(ioc->pfacts);
3297         kfree(ioc->ctl_cmds.reply);
3298         kfree(ioc->base_cmds.reply);
3299         kfree(ioc->tm_cmds.reply);
3300         kfree(ioc->transport_cmds.reply);
3301         kfree(ioc->config_cmds.reply);
3302 }
3303
3304 /**
3305  * _base_reset_handler - reset callback handler (for base)
3306  * @ioc: per adapter object
3307  * @reset_phase: phase
3308  *
3309  * The handler for doing any required cleanup or initialization.
3310  *
3311  * The reset phase can be MPT2_IOC_PRE_RESET, MPT2_IOC_AFTER_RESET,
3312  * MPT2_IOC_DONE_RESET
3313  *
3314  * Return nothing.
3315  */
3316 static void
3317 _base_reset_handler(struct MPT2SAS_ADAPTER *ioc, int reset_phase)
3318 {
3319         switch (reset_phase) {
3320         case MPT2_IOC_PRE_RESET:
3321                 dtmprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: "
3322                     "MPT2_IOC_PRE_RESET\n", ioc->name, __func__));
3323                 break;
3324         case MPT2_IOC_AFTER_RESET:
3325                 dtmprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: "
3326                     "MPT2_IOC_AFTER_RESET\n", ioc->name, __func__));
3327                 if (ioc->transport_cmds.status & MPT2_CMD_PENDING) {
3328                         ioc->transport_cmds.status |= MPT2_CMD_RESET;
3329                         mpt2sas_base_free_smid(ioc, ioc->transport_cmds.smid);
3330                         complete(&ioc->transport_cmds.done);
3331                 }
3332                 if (ioc->base_cmds.status & MPT2_CMD_PENDING) {
3333                         ioc->base_cmds.status |= MPT2_CMD_RESET;
3334                         mpt2sas_base_free_smid(ioc, ioc->base_cmds.smid);
3335                         complete(&ioc->base_cmds.done);
3336                 }
3337                 if (ioc->config_cmds.status & MPT2_CMD_PENDING) {
3338                         ioc->config_cmds.status |= MPT2_CMD_RESET;
3339                         mpt2sas_base_free_smid(ioc, ioc->config_cmds.smid);
3340                         complete(&ioc->config_cmds.done);
3341                 }
3342                 break;
3343         case MPT2_IOC_DONE_RESET:
3344                 dtmprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: "
3345                     "MPT2_IOC_DONE_RESET\n", ioc->name, __func__));
3346                 break;
3347         }
3348         mpt2sas_scsih_reset_handler(ioc, reset_phase);
3349         mpt2sas_ctl_reset_handler(ioc, reset_phase);
3350 }
3351
3352 /**
3353  * _wait_for_commands_to_complete - reset controller
3354  * @ioc: Pointer to MPT_ADAPTER structure
3355  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3356  *
3357  * This function waiting(3s) for all pending commands to complete
3358  * prior to putting controller in reset.
3359  */
3360 static void
3361 _wait_for_commands_to_complete(struct MPT2SAS_ADAPTER *ioc, int sleep_flag)
3362 {
3363         u32 ioc_state;
3364         unsigned long flags;
3365         u16 i;
3366
3367         ioc->pending_io_count = 0;
3368         if (sleep_flag != CAN_SLEEP)
3369                 return;
3370
3371         ioc_state = mpt2sas_base_get_iocstate(ioc, 0);
3372         if ((ioc_state & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_OPERATIONAL)
3373                 return;
3374
3375         /* pending command count */
3376         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3377         for (i = 0; i < ioc->request_depth; i++)
3378                 if (ioc->scsi_lookup[i].cb_idx != 0xFF)
3379                         ioc->pending_io_count++;
3380         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3381
3382         if (!ioc->pending_io_count)
3383                 return;
3384
3385         /* wait for pending commands to complete */
3386         wait_event_timeout(ioc->reset_wq, ioc->pending_io_count == 0, 3 * HZ);
3387 }
3388
3389 /**
3390  * mpt2sas_base_hard_reset_handler - reset controller
3391  * @ioc: Pointer to MPT_ADAPTER structure
3392  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3393  * @type: FORCE_BIG_HAMMER or SOFT_RESET
3394  *
3395  * Returns 0 for success, non-zero for failure.
3396  */
3397 int
3398 mpt2sas_base_hard_reset_handler(struct MPT2SAS_ADAPTER *ioc, int sleep_flag,
3399     enum reset_type type)
3400 {
3401         int r, i;
3402         unsigned long flags;
3403
3404         dtmprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: enter\n", ioc->name,
3405             __func__));
3406
3407         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
3408         if (ioc->ioc_reset_in_progress) {
3409                 spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
3410                 printk(MPT2SAS_ERR_FMT "%s: busy\n",
3411                     ioc->name, __func__);
3412                 return -EBUSY;
3413         }
3414         ioc->ioc_reset_in_progress = 1;
3415         ioc->shost_recovery = 1;
3416         if (ioc->shost->shost_state == SHOST_RUNNING) {
3417                 /* set back to SHOST_RUNNING in mpt2sas_scsih.c */
3418                 scsi_host_set_state(ioc->shost, SHOST_RECOVERY);
3419                 printk(MPT2SAS_INFO_FMT "putting controller into "
3420                     "SHOST_RECOVERY\n", ioc->name);
3421         }
3422         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
3423
3424         _base_reset_handler(ioc, MPT2_IOC_PRE_RESET);
3425         _wait_for_commands_to_complete(ioc, sleep_flag);
3426         _base_mask_interrupts(ioc);
3427         r = _base_make_ioc_ready(ioc, sleep_flag, type);
3428         if (r)
3429                 goto out;
3430         _base_reset_handler(ioc, MPT2_IOC_AFTER_RESET);
3431         for (i = 0 ; i < ioc->facts.NumberOfPorts; i++)
3432                 r = _base_make_ioc_operational(ioc, ioc->pfacts[i].VF_ID,
3433                     sleep_flag);
3434         if (!r)
3435                 _base_reset_handler(ioc, MPT2_IOC_DONE_RESET);
3436  out:
3437         dtmprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: %s\n",
3438             ioc->name, __func__, ((r == 0) ? "SUCCESS" : "FAILED")));
3439
3440         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
3441         ioc->ioc_reset_in_progress = 0;
3442         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
3443         return r;
3444 }