Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/tiwai/sound-2.6
[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_dell_branding - Disply branding string
1400  * @ioc: per adapter object
1401  *
1402  * Return nothing.
1403  */
1404 static void
1405 _base_display_dell_branding(struct MPT2SAS_ADAPTER *ioc)
1406 {
1407         char dell_branding[MPT2SAS_DELL_BRANDING_SIZE];
1408
1409         if (ioc->pdev->subsystem_vendor != PCI_VENDOR_ID_DELL)
1410                 return;
1411
1412         memset(dell_branding, 0, MPT2SAS_DELL_BRANDING_SIZE);
1413         switch (ioc->pdev->subsystem_device) {
1414         case MPT2SAS_DELL_6GBPS_SAS_HBA_SSDID:
1415                 strncpy(dell_branding, MPT2SAS_DELL_6GBPS_SAS_HBA_BRANDING,
1416                     MPT2SAS_DELL_BRANDING_SIZE - 1);
1417                 break;
1418         case MPT2SAS_DELL_PERC_H200_ADAPTER_SSDID:
1419                 strncpy(dell_branding, MPT2SAS_DELL_PERC_H200_ADAPTER_BRANDING,
1420                     MPT2SAS_DELL_BRANDING_SIZE - 1);
1421                 break;
1422         case MPT2SAS_DELL_PERC_H200_INTEGRATED_SSDID:
1423                 strncpy(dell_branding,
1424                     MPT2SAS_DELL_PERC_H200_INTEGRATED_BRANDING,
1425                     MPT2SAS_DELL_BRANDING_SIZE - 1);
1426                 break;
1427         case MPT2SAS_DELL_PERC_H200_MODULAR_SSDID:
1428                 strncpy(dell_branding,
1429                     MPT2SAS_DELL_PERC_H200_MODULAR_BRANDING,
1430                     MPT2SAS_DELL_BRANDING_SIZE - 1);
1431                 break;
1432         case MPT2SAS_DELL_PERC_H200_EMBEDDED_SSDID:
1433                 strncpy(dell_branding,
1434                     MPT2SAS_DELL_PERC_H200_EMBEDDED_BRANDING,
1435                     MPT2SAS_DELL_BRANDING_SIZE - 1);
1436                 break;
1437         case MPT2SAS_DELL_PERC_H200_SSDID:
1438                 strncpy(dell_branding, MPT2SAS_DELL_PERC_H200_BRANDING,
1439                     MPT2SAS_DELL_BRANDING_SIZE - 1);
1440                 break;
1441         case MPT2SAS_DELL_6GBPS_SAS_SSDID:
1442                 strncpy(dell_branding, MPT2SAS_DELL_6GBPS_SAS_BRANDING,
1443                     MPT2SAS_DELL_BRANDING_SIZE - 1);
1444                 break;
1445         default:
1446                 sprintf(dell_branding, "0x%4X", ioc->pdev->subsystem_device);
1447                 break;
1448         }
1449
1450         printk(MPT2SAS_INFO_FMT "%s: Vendor(0x%04X), Device(0x%04X),"
1451             " SSVID(0x%04X), SSDID(0x%04X)\n", ioc->name, dell_branding,
1452             ioc->pdev->vendor, ioc->pdev->device, ioc->pdev->subsystem_vendor,
1453             ioc->pdev->subsystem_device);
1454 }
1455
1456 /**
1457  * _base_display_ioc_capabilities - Disply IOC's capabilities.
1458  * @ioc: per adapter object
1459  *
1460  * Return nothing.
1461  */
1462 static void
1463 _base_display_ioc_capabilities(struct MPT2SAS_ADAPTER *ioc)
1464 {
1465         int i = 0;
1466         char desc[16];
1467         u8 revision;
1468         u32 iounit_pg1_flags;
1469
1470         pci_read_config_byte(ioc->pdev, PCI_CLASS_REVISION, &revision);
1471         strncpy(desc, ioc->manu_pg0.ChipName, 16);
1472         printk(MPT2SAS_INFO_FMT "%s: FWVersion(%02d.%02d.%02d.%02d), "
1473            "ChipRevision(0x%02x), BiosVersion(%02d.%02d.%02d.%02d)\n",
1474             ioc->name, desc,
1475            (ioc->facts.FWVersion.Word & 0xFF000000) >> 24,
1476            (ioc->facts.FWVersion.Word & 0x00FF0000) >> 16,
1477            (ioc->facts.FWVersion.Word & 0x0000FF00) >> 8,
1478            ioc->facts.FWVersion.Word & 0x000000FF,
1479            revision,
1480            (ioc->bios_pg3.BiosVersion & 0xFF000000) >> 24,
1481            (ioc->bios_pg3.BiosVersion & 0x00FF0000) >> 16,
1482            (ioc->bios_pg3.BiosVersion & 0x0000FF00) >> 8,
1483             ioc->bios_pg3.BiosVersion & 0x000000FF);
1484
1485         printk(MPT2SAS_INFO_FMT "Protocol=(", ioc->name);
1486
1487         if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_INITIATOR) {
1488                 printk("Initiator");
1489                 i++;
1490         }
1491
1492         if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_TARGET) {
1493                 printk("%sTarget", i ? "," : "");
1494                 i++;
1495         }
1496
1497         _base_display_dell_branding(ioc);
1498
1499         i = 0;
1500         printk("), ");
1501         printk("Capabilities=(");
1502
1503         if (ioc->facts.IOCCapabilities &
1504             MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID) {
1505                 printk("Raid");
1506                 i++;
1507         }
1508
1509         if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR) {
1510                 printk("%sTLR", i ? "," : "");
1511                 i++;
1512         }
1513
1514         if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_MULTICAST) {
1515                 printk("%sMulticast", i ? "," : "");
1516                 i++;
1517         }
1518
1519         if (ioc->facts.IOCCapabilities &
1520             MPI2_IOCFACTS_CAPABILITY_BIDIRECTIONAL_TARGET) {
1521                 printk("%sBIDI Target", i ? "," : "");
1522                 i++;
1523         }
1524
1525         if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP) {
1526                 printk("%sEEDP", i ? "," : "");
1527                 i++;
1528         }
1529
1530         if (ioc->facts.IOCCapabilities &
1531             MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER) {
1532                 printk("%sSnapshot Buffer", i ? "," : "");
1533                 i++;
1534         }
1535
1536         if (ioc->facts.IOCCapabilities &
1537             MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER) {
1538                 printk("%sDiag Trace Buffer", i ? "," : "");
1539                 i++;
1540         }
1541
1542         if (ioc->facts.IOCCapabilities &
1543             MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING) {
1544                 printk("%sTask Set Full", i ? "," : "");
1545                 i++;
1546         }
1547
1548         iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
1549         if (!(iounit_pg1_flags & MPI2_IOUNITPAGE1_NATIVE_COMMAND_Q_DISABLE)) {
1550                 printk("%sNCQ", i ? "," : "");
1551                 i++;
1552         }
1553
1554         printk(")\n");
1555 }
1556
1557 /**
1558  * _base_static_config_pages - static start of day config pages
1559  * @ioc: per adapter object
1560  *
1561  * Return nothing.
1562  */
1563 static void
1564 _base_static_config_pages(struct MPT2SAS_ADAPTER *ioc)
1565 {
1566         Mpi2ConfigReply_t mpi_reply;
1567         u32 iounit_pg1_flags;
1568
1569         mpt2sas_config_get_manufacturing_pg0(ioc, &mpi_reply, &ioc->manu_pg0);
1570         mpt2sas_config_get_bios_pg2(ioc, &mpi_reply, &ioc->bios_pg2);
1571         mpt2sas_config_get_bios_pg3(ioc, &mpi_reply, &ioc->bios_pg3);
1572         mpt2sas_config_get_ioc_pg8(ioc, &mpi_reply, &ioc->ioc_pg8);
1573         mpt2sas_config_get_iounit_pg0(ioc, &mpi_reply, &ioc->iounit_pg0);
1574         mpt2sas_config_get_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
1575         _base_display_ioc_capabilities(ioc);
1576
1577         /*
1578          * Enable task_set_full handling in iounit_pg1 when the
1579          * facts capabilities indicate that its supported.
1580          */
1581         iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
1582         if ((ioc->facts.IOCCapabilities &
1583             MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING))
1584                 iounit_pg1_flags &=
1585                     ~MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
1586         else
1587                 iounit_pg1_flags |=
1588                     MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
1589         ioc->iounit_pg1.Flags = cpu_to_le32(iounit_pg1_flags);
1590         mpt2sas_config_set_iounit_pg1(ioc, &mpi_reply, ioc->iounit_pg1);
1591 }
1592
1593 /**
1594  * _base_release_memory_pools - release memory
1595  * @ioc: per adapter object
1596  *
1597  * Free memory allocated from _base_allocate_memory_pools.
1598  *
1599  * Return nothing.
1600  */
1601 static void
1602 _base_release_memory_pools(struct MPT2SAS_ADAPTER *ioc)
1603 {
1604         dexitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
1605             __func__));
1606
1607         if (ioc->request) {
1608                 pci_free_consistent(ioc->pdev, ioc->request_dma_sz,
1609                     ioc->request,  ioc->request_dma);
1610                 dexitprintk(ioc, printk(MPT2SAS_INFO_FMT "request_pool(0x%p)"
1611                     ": free\n", ioc->name, ioc->request));
1612                 ioc->request = NULL;
1613         }
1614
1615         if (ioc->sense) {
1616                 pci_pool_free(ioc->sense_dma_pool, ioc->sense, ioc->sense_dma);
1617                 if (ioc->sense_dma_pool)
1618                         pci_pool_destroy(ioc->sense_dma_pool);
1619                 dexitprintk(ioc, printk(MPT2SAS_INFO_FMT "sense_pool(0x%p)"
1620                     ": free\n", ioc->name, ioc->sense));
1621                 ioc->sense = NULL;
1622         }
1623
1624         if (ioc->reply) {
1625                 pci_pool_free(ioc->reply_dma_pool, ioc->reply, ioc->reply_dma);
1626                 if (ioc->reply_dma_pool)
1627                         pci_pool_destroy(ioc->reply_dma_pool);
1628                 dexitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_pool(0x%p)"
1629                      ": free\n", ioc->name, ioc->reply));
1630                 ioc->reply = NULL;
1631         }
1632
1633         if (ioc->reply_free) {
1634                 pci_pool_free(ioc->reply_free_dma_pool, ioc->reply_free,
1635                     ioc->reply_free_dma);
1636                 if (ioc->reply_free_dma_pool)
1637                         pci_pool_destroy(ioc->reply_free_dma_pool);
1638                 dexitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_free_pool"
1639                     "(0x%p): free\n", ioc->name, ioc->reply_free));
1640                 ioc->reply_free = NULL;
1641         }
1642
1643         if (ioc->reply_post_free) {
1644                 pci_pool_free(ioc->reply_post_free_dma_pool,
1645                     ioc->reply_post_free, ioc->reply_post_free_dma);
1646                 if (ioc->reply_post_free_dma_pool)
1647                         pci_pool_destroy(ioc->reply_post_free_dma_pool);
1648                 dexitprintk(ioc, printk(MPT2SAS_INFO_FMT
1649                     "reply_post_free_pool(0x%p): free\n", ioc->name,
1650                     ioc->reply_post_free));
1651                 ioc->reply_post_free = NULL;
1652         }
1653
1654         if (ioc->config_page) {
1655                 dexitprintk(ioc, printk(MPT2SAS_INFO_FMT
1656                     "config_page(0x%p): free\n", ioc->name,
1657                     ioc->config_page));
1658                 pci_free_consistent(ioc->pdev, ioc->config_page_sz,
1659                     ioc->config_page, ioc->config_page_dma);
1660         }
1661
1662         kfree(ioc->scsi_lookup);
1663 }
1664
1665
1666 /**
1667  * _base_allocate_memory_pools - allocate start of day memory pools
1668  * @ioc: per adapter object
1669  * @sleep_flag: CAN_SLEEP or NO_SLEEP
1670  *
1671  * Returns 0 success, anything else error
1672  */
1673 static int
1674 _base_allocate_memory_pools(struct MPT2SAS_ADAPTER *ioc,  int sleep_flag)
1675 {
1676         Mpi2IOCFactsReply_t *facts;
1677         u32 queue_size, queue_diff;
1678         u16 max_sge_elements;
1679         u16 num_of_reply_frames;
1680         u16 chains_needed_per_io;
1681         u32 sz, total_sz;
1682         u16 i;
1683         u32 retry_sz;
1684         u16 max_request_credit;
1685
1686         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
1687             __func__));
1688
1689         retry_sz = 0;
1690         facts = &ioc->facts;
1691
1692         /* command line tunables  for max sgl entries */
1693         if (max_sgl_entries != -1) {
1694                 ioc->shost->sg_tablesize = (max_sgl_entries <
1695                     MPT2SAS_SG_DEPTH) ? max_sgl_entries :
1696                     MPT2SAS_SG_DEPTH;
1697         } else {
1698                 ioc->shost->sg_tablesize = MPT2SAS_SG_DEPTH;
1699         }
1700
1701         /* command line tunables  for max controller queue depth */
1702         if (max_queue_depth != -1) {
1703                 max_request_credit = (max_queue_depth < facts->RequestCredit)
1704                     ? max_queue_depth : facts->RequestCredit;
1705         } else {
1706                 max_request_credit = (facts->RequestCredit >
1707                     MPT2SAS_MAX_REQUEST_QUEUE) ? MPT2SAS_MAX_REQUEST_QUEUE :
1708                     facts->RequestCredit;
1709         }
1710         ioc->request_depth = max_request_credit;
1711
1712         /* request frame size */
1713         ioc->request_sz = facts->IOCRequestFrameSize * 4;
1714
1715         /* reply frame size */
1716         ioc->reply_sz = facts->ReplyFrameSize * 4;
1717
1718  retry_allocation:
1719         total_sz = 0;
1720         /* calculate number of sg elements left over in the 1st frame */
1721         max_sge_elements = ioc->request_sz - ((sizeof(Mpi2SCSIIORequest_t) -
1722             sizeof(Mpi2SGEIOUnion_t)) + ioc->sge_size);
1723         ioc->max_sges_in_main_message = max_sge_elements/ioc->sge_size;
1724
1725         /* now do the same for a chain buffer */
1726         max_sge_elements = ioc->request_sz - ioc->sge_size;
1727         ioc->max_sges_in_chain_message = max_sge_elements/ioc->sge_size;
1728
1729         ioc->chain_offset_value_for_main_message =
1730             ((sizeof(Mpi2SCSIIORequest_t) - sizeof(Mpi2SGEIOUnion_t)) +
1731              (ioc->max_sges_in_chain_message * ioc->sge_size)) / 4;
1732
1733         /*
1734          *  MPT2SAS_SG_DEPTH = CONFIG_FUSION_MAX_SGE
1735          */
1736         chains_needed_per_io = ((ioc->shost->sg_tablesize -
1737            ioc->max_sges_in_main_message)/ioc->max_sges_in_chain_message)
1738             + 1;
1739         if (chains_needed_per_io > facts->MaxChainDepth) {
1740                 chains_needed_per_io = facts->MaxChainDepth;
1741                 ioc->shost->sg_tablesize = min_t(u16,
1742                 ioc->max_sges_in_main_message + (ioc->max_sges_in_chain_message
1743                 * chains_needed_per_io), ioc->shost->sg_tablesize);
1744         }
1745         ioc->chains_needed_per_io = chains_needed_per_io;
1746
1747         /* reply free queue sizing - taking into account for events */
1748         num_of_reply_frames = ioc->request_depth + 32;
1749
1750         /* number of replies frames can't be a multiple of 16 */
1751         /* decrease number of reply frames by 1 */
1752         if (!(num_of_reply_frames % 16))
1753                 num_of_reply_frames--;
1754
1755         /* calculate number of reply free queue entries
1756          *  (must be multiple of 16)
1757          */
1758
1759         /* (we know reply_free_queue_depth is not a multiple of 16) */
1760         queue_size = num_of_reply_frames;
1761         queue_size += 16 - (queue_size % 16);
1762         ioc->reply_free_queue_depth = queue_size;
1763
1764         /* reply descriptor post queue sizing */
1765         /* this size should be the number of request frames + number of reply
1766          * frames
1767          */
1768
1769         queue_size = ioc->request_depth + num_of_reply_frames + 1;
1770         /* round up to 16 byte boundary */
1771         if (queue_size % 16)
1772                 queue_size += 16 - (queue_size % 16);
1773
1774         /* check against IOC maximum reply post queue depth */
1775         if (queue_size > facts->MaxReplyDescriptorPostQueueDepth) {
1776                 queue_diff = queue_size -
1777                     facts->MaxReplyDescriptorPostQueueDepth;
1778
1779                 /* round queue_diff up to multiple of 16 */
1780                 if (queue_diff % 16)
1781                         queue_diff += 16 - (queue_diff % 16);
1782
1783                 /* adjust request_depth, reply_free_queue_depth,
1784                  * and queue_size
1785                  */
1786                 ioc->request_depth -= queue_diff;
1787                 ioc->reply_free_queue_depth -= queue_diff;
1788                 queue_size -= queue_diff;
1789         }
1790         ioc->reply_post_queue_depth = queue_size;
1791
1792         /* max scsi host queue depth */
1793         ioc->shost->can_queue = ioc->request_depth - INTERNAL_CMDS_COUNT;
1794         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "scsi host queue: depth"
1795             "(%d)\n", ioc->name, ioc->shost->can_queue));
1796
1797         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "scatter gather: "
1798             "sge_in_main_msg(%d), sge_per_chain(%d), sge_per_io(%d), "
1799             "chains_per_io(%d)\n", ioc->name, ioc->max_sges_in_main_message,
1800             ioc->max_sges_in_chain_message, ioc->shost->sg_tablesize,
1801             ioc->chains_needed_per_io));
1802
1803         /* contiguous pool for request and chains, 16 byte align, one extra "
1804          * "frame for smid=0
1805          */
1806         ioc->chain_depth = ioc->chains_needed_per_io * ioc->request_depth;
1807         sz = ((ioc->request_depth + 1 + ioc->chain_depth) * ioc->request_sz);
1808
1809         ioc->request_dma_sz = sz;
1810         ioc->request = pci_alloc_consistent(ioc->pdev, sz, &ioc->request_dma);
1811         if (!ioc->request) {
1812                 printk(MPT2SAS_ERR_FMT "request pool: pci_alloc_consistent "
1813                     "failed: req_depth(%d), chains_per_io(%d), frame_sz(%d), "
1814                     "total(%d kB)\n", ioc->name, ioc->request_depth,
1815                     ioc->chains_needed_per_io, ioc->request_sz, sz/1024);
1816                 if (ioc->request_depth < MPT2SAS_SAS_QUEUE_DEPTH)
1817                         goto out;
1818                 retry_sz += 64;
1819                 ioc->request_depth = max_request_credit - retry_sz;
1820                 goto retry_allocation;
1821         }
1822
1823         if (retry_sz)
1824                 printk(MPT2SAS_ERR_FMT "request pool: pci_alloc_consistent "
1825                     "succeed: req_depth(%d), chains_per_io(%d), frame_sz(%d), "
1826                     "total(%d kb)\n", ioc->name, ioc->request_depth,
1827                     ioc->chains_needed_per_io, ioc->request_sz, sz/1024);
1828
1829         ioc->chain = ioc->request + ((ioc->request_depth + 1) *
1830             ioc->request_sz);
1831         ioc->chain_dma = ioc->request_dma + ((ioc->request_depth + 1) *
1832             ioc->request_sz);
1833         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "request pool(0x%p): "
1834             "depth(%d), frame_size(%d), pool_size(%d kB)\n", ioc->name,
1835             ioc->request, ioc->request_depth, ioc->request_sz,
1836             ((ioc->request_depth + 1) * ioc->request_sz)/1024));
1837         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "chain pool(0x%p): depth"
1838             "(%d), frame_size(%d), pool_size(%d kB)\n", ioc->name, ioc->chain,
1839             ioc->chain_depth, ioc->request_sz, ((ioc->chain_depth *
1840             ioc->request_sz))/1024));
1841         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "request pool: dma(0x%llx)\n",
1842             ioc->name, (unsigned long long) ioc->request_dma));
1843         total_sz += sz;
1844
1845         ioc->scsi_lookup = kcalloc(ioc->request_depth,
1846             sizeof(struct request_tracker), GFP_KERNEL);
1847         if (!ioc->scsi_lookup) {
1848                 printk(MPT2SAS_ERR_FMT "scsi_lookup: kcalloc failed\n",
1849                     ioc->name);
1850                 goto out;
1851         }
1852
1853          /* initialize some bits */
1854         for (i = 0; i < ioc->request_depth; i++)
1855                 ioc->scsi_lookup[i].smid = i + 1;
1856
1857         /* sense buffers, 4 byte align */
1858         sz = ioc->request_depth * SCSI_SENSE_BUFFERSIZE;
1859         ioc->sense_dma_pool = pci_pool_create("sense pool", ioc->pdev, sz, 4,
1860             0);
1861         if (!ioc->sense_dma_pool) {
1862                 printk(MPT2SAS_ERR_FMT "sense pool: pci_pool_create failed\n",
1863                     ioc->name);
1864                 goto out;
1865         }
1866         ioc->sense = pci_pool_alloc(ioc->sense_dma_pool , GFP_KERNEL,
1867             &ioc->sense_dma);
1868         if (!ioc->sense) {
1869                 printk(MPT2SAS_ERR_FMT "sense pool: pci_pool_alloc failed\n",
1870                     ioc->name);
1871                 goto out;
1872         }
1873         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT
1874             "sense pool(0x%p): depth(%d), element_size(%d), pool_size"
1875             "(%d kB)\n", ioc->name, ioc->sense, ioc->request_depth,
1876             SCSI_SENSE_BUFFERSIZE, sz/1024));
1877         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "sense_dma(0x%llx)\n",
1878             ioc->name, (unsigned long long)ioc->sense_dma));
1879         total_sz += sz;
1880
1881         /* reply pool, 4 byte align */
1882         sz = ioc->reply_free_queue_depth * ioc->reply_sz;
1883         ioc->reply_dma_pool = pci_pool_create("reply pool", ioc->pdev, sz, 4,
1884             0);
1885         if (!ioc->reply_dma_pool) {
1886                 printk(MPT2SAS_ERR_FMT "reply pool: pci_pool_create failed\n",
1887                     ioc->name);
1888                 goto out;
1889         }
1890         ioc->reply = pci_pool_alloc(ioc->reply_dma_pool , GFP_KERNEL,
1891             &ioc->reply_dma);
1892         if (!ioc->reply) {
1893                 printk(MPT2SAS_ERR_FMT "reply pool: pci_pool_alloc failed\n",
1894                     ioc->name);
1895                 goto out;
1896         }
1897         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply pool(0x%p): depth"
1898             "(%d), frame_size(%d), pool_size(%d kB)\n", ioc->name, ioc->reply,
1899             ioc->reply_free_queue_depth, ioc->reply_sz, sz/1024));
1900         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_dma(0x%llx)\n",
1901             ioc->name, (unsigned long long)ioc->reply_dma));
1902         total_sz += sz;
1903
1904         /* reply free queue, 16 byte align */
1905         sz = ioc->reply_free_queue_depth * 4;
1906         ioc->reply_free_dma_pool = pci_pool_create("reply_free pool",
1907             ioc->pdev, sz, 16, 0);
1908         if (!ioc->reply_free_dma_pool) {
1909                 printk(MPT2SAS_ERR_FMT "reply_free pool: pci_pool_create "
1910                     "failed\n", ioc->name);
1911                 goto out;
1912         }
1913         ioc->reply_free = pci_pool_alloc(ioc->reply_free_dma_pool , GFP_KERNEL,
1914             &ioc->reply_free_dma);
1915         if (!ioc->reply_free) {
1916                 printk(MPT2SAS_ERR_FMT "reply_free pool: pci_pool_alloc "
1917                     "failed\n", ioc->name);
1918                 goto out;
1919         }
1920         memset(ioc->reply_free, 0, sz);
1921         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_free pool(0x%p): "
1922             "depth(%d), element_size(%d), pool_size(%d kB)\n", ioc->name,
1923             ioc->reply_free, ioc->reply_free_queue_depth, 4, sz/1024));
1924         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_free_dma"
1925             "(0x%llx)\n", ioc->name, (unsigned long long)ioc->reply_free_dma));
1926         total_sz += sz;
1927
1928         /* reply post queue, 16 byte align */
1929         sz = ioc->reply_post_queue_depth * sizeof(Mpi2DefaultReplyDescriptor_t);
1930         ioc->reply_post_free_dma_pool = pci_pool_create("reply_post_free pool",
1931             ioc->pdev, sz, 16, 0);
1932         if (!ioc->reply_post_free_dma_pool) {
1933                 printk(MPT2SAS_ERR_FMT "reply_post_free pool: pci_pool_create "
1934                     "failed\n", ioc->name);
1935                 goto out;
1936         }
1937         ioc->reply_post_free = pci_pool_alloc(ioc->reply_post_free_dma_pool ,
1938             GFP_KERNEL, &ioc->reply_post_free_dma);
1939         if (!ioc->reply_post_free) {
1940                 printk(MPT2SAS_ERR_FMT "reply_post_free pool: pci_pool_alloc "
1941                     "failed\n", ioc->name);
1942                 goto out;
1943         }
1944         memset(ioc->reply_post_free, 0, sz);
1945         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply post free pool"
1946             "(0x%p): depth(%d), element_size(%d), pool_size(%d kB)\n",
1947             ioc->name, ioc->reply_post_free, ioc->reply_post_queue_depth, 8,
1948             sz/1024));
1949         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_post_free_dma = "
1950             "(0x%llx)\n", ioc->name, (unsigned long long)
1951             ioc->reply_post_free_dma));
1952         total_sz += sz;
1953
1954         ioc->config_page_sz = 512;
1955         ioc->config_page = pci_alloc_consistent(ioc->pdev,
1956             ioc->config_page_sz, &ioc->config_page_dma);
1957         if (!ioc->config_page) {
1958                 printk(MPT2SAS_ERR_FMT "config page: pci_pool_alloc "
1959                     "failed\n", ioc->name);
1960                 goto out;
1961         }
1962         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "config page(0x%p): size"
1963             "(%d)\n", ioc->name, ioc->config_page, ioc->config_page_sz));
1964         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "config_page_dma"
1965             "(0x%llx)\n", ioc->name, (unsigned long long)ioc->config_page_dma));
1966         total_sz += ioc->config_page_sz;
1967
1968         printk(MPT2SAS_INFO_FMT "Allocated physical memory: size(%d kB)\n",
1969             ioc->name, total_sz/1024);
1970         printk(MPT2SAS_INFO_FMT "Current Controller Queue Depth(%d), "
1971             "Max Controller Queue Depth(%d)\n",
1972             ioc->name, ioc->shost->can_queue, facts->RequestCredit);
1973         printk(MPT2SAS_INFO_FMT "Scatter Gather Elements per IO(%d)\n",
1974             ioc->name, ioc->shost->sg_tablesize);
1975         return 0;
1976
1977  out:
1978         _base_release_memory_pools(ioc);
1979         return -ENOMEM;
1980 }
1981
1982
1983 /**
1984  * mpt2sas_base_get_iocstate - Get the current state of a MPT adapter.
1985  * @ioc: Pointer to MPT_ADAPTER structure
1986  * @cooked: Request raw or cooked IOC state
1987  *
1988  * Returns all IOC Doorbell register bits if cooked==0, else just the
1989  * Doorbell bits in MPI_IOC_STATE_MASK.
1990  */
1991 u32
1992 mpt2sas_base_get_iocstate(struct MPT2SAS_ADAPTER *ioc, int cooked)
1993 {
1994         u32 s, sc;
1995
1996         s = readl(&ioc->chip->Doorbell);
1997         sc = s & MPI2_IOC_STATE_MASK;
1998         return cooked ? sc : s;
1999 }
2000
2001 /**
2002  * _base_wait_on_iocstate - waiting on a particular ioc state
2003  * @ioc_state: controller state { READY, OPERATIONAL, or RESET }
2004  * @timeout: timeout in second
2005  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2006  *
2007  * Returns 0 for success, non-zero for failure.
2008  */
2009 static int
2010 _base_wait_on_iocstate(struct MPT2SAS_ADAPTER *ioc, u32 ioc_state, int timeout,
2011     int sleep_flag)
2012 {
2013         u32 count, cntdn;
2014         u32 current_state;
2015
2016         count = 0;
2017         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
2018         do {
2019                 current_state = mpt2sas_base_get_iocstate(ioc, 1);
2020                 if (current_state == ioc_state)
2021                         return 0;
2022                 if (count && current_state == MPI2_IOC_STATE_FAULT)
2023                         break;
2024                 if (sleep_flag == CAN_SLEEP)
2025                         msleep(1);
2026                 else
2027                         udelay(500);
2028                 count++;
2029         } while (--cntdn);
2030
2031         return current_state;
2032 }
2033
2034 /**
2035  * _base_wait_for_doorbell_int - waiting for controller interrupt(generated by
2036  * a write to the doorbell)
2037  * @ioc: per adapter object
2038  * @timeout: timeout in second
2039  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2040  *
2041  * Returns 0 for success, non-zero for failure.
2042  *
2043  * Notes: MPI2_HIS_IOC2SYS_DB_STATUS - set to one when IOC writes to doorbell.
2044  */
2045 static int
2046 _base_wait_for_doorbell_int(struct MPT2SAS_ADAPTER *ioc, int timeout,
2047     int sleep_flag)
2048 {
2049         u32 cntdn, count;
2050         u32 int_status;
2051
2052         count = 0;
2053         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
2054         do {
2055                 int_status = readl(&ioc->chip->HostInterruptStatus);
2056                 if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
2057                         dhsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: "
2058                             "successfull count(%d), timeout(%d)\n", ioc->name,
2059                             __func__, count, timeout));
2060                         return 0;
2061                 }
2062                 if (sleep_flag == CAN_SLEEP)
2063                         msleep(1);
2064                 else
2065                         udelay(500);
2066                 count++;
2067         } while (--cntdn);
2068
2069         printk(MPT2SAS_ERR_FMT "%s: failed due to timeout count(%d), "
2070             "int_status(%x)!\n", ioc->name, __func__, count, int_status);
2071         return -EFAULT;
2072 }
2073
2074 /**
2075  * _base_wait_for_doorbell_ack - waiting for controller to read the doorbell.
2076  * @ioc: per adapter object
2077  * @timeout: timeout in second
2078  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2079  *
2080  * Returns 0 for success, non-zero for failure.
2081  *
2082  * Notes: MPI2_HIS_SYS2IOC_DB_STATUS - set to one when host writes to
2083  * doorbell.
2084  */
2085 static int
2086 _base_wait_for_doorbell_ack(struct MPT2SAS_ADAPTER *ioc, int timeout,
2087     int sleep_flag)
2088 {
2089         u32 cntdn, count;
2090         u32 int_status;
2091         u32 doorbell;
2092
2093         count = 0;
2094         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
2095         do {
2096                 int_status = readl(&ioc->chip->HostInterruptStatus);
2097                 if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
2098                         dhsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: "
2099                             "successfull count(%d), timeout(%d)\n", ioc->name,
2100                             __func__, count, timeout));
2101                         return 0;
2102                 } else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
2103                         doorbell = readl(&ioc->chip->Doorbell);
2104                         if ((doorbell & MPI2_IOC_STATE_MASK) ==
2105                             MPI2_IOC_STATE_FAULT) {
2106                                 mpt2sas_base_fault_info(ioc , doorbell);
2107                                 return -EFAULT;
2108                         }
2109                 } else if (int_status == 0xFFFFFFFF)
2110                         goto out;
2111
2112                 if (sleep_flag == CAN_SLEEP)
2113                         msleep(1);
2114                 else
2115                         udelay(500);
2116                 count++;
2117         } while (--cntdn);
2118
2119  out:
2120         printk(MPT2SAS_ERR_FMT "%s: failed due to timeout count(%d), "
2121             "int_status(%x)!\n", ioc->name, __func__, count, int_status);
2122         return -EFAULT;
2123 }
2124
2125 /**
2126  * _base_wait_for_doorbell_not_used - waiting for doorbell to not be in use
2127  * @ioc: per adapter object
2128  * @timeout: timeout in second
2129  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2130  *
2131  * Returns 0 for success, non-zero for failure.
2132  *
2133  */
2134 static int
2135 _base_wait_for_doorbell_not_used(struct MPT2SAS_ADAPTER *ioc, int timeout,
2136     int sleep_flag)
2137 {
2138         u32 cntdn, count;
2139         u32 doorbell_reg;
2140
2141         count = 0;
2142         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
2143         do {
2144                 doorbell_reg = readl(&ioc->chip->Doorbell);
2145                 if (!(doorbell_reg & MPI2_DOORBELL_USED)) {
2146                         dhsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: "
2147                             "successfull count(%d), timeout(%d)\n", ioc->name,
2148                             __func__, count, timeout));
2149                         return 0;
2150                 }
2151                 if (sleep_flag == CAN_SLEEP)
2152                         msleep(1);
2153                 else
2154                         udelay(500);
2155                 count++;
2156         } while (--cntdn);
2157
2158         printk(MPT2SAS_ERR_FMT "%s: failed due to timeout count(%d), "
2159             "doorbell_reg(%x)!\n", ioc->name, __func__, count, doorbell_reg);
2160         return -EFAULT;
2161 }
2162
2163 /**
2164  * _base_send_ioc_reset - send doorbell reset
2165  * @ioc: per adapter object
2166  * @reset_type: currently only supports: MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET
2167  * @timeout: timeout in second
2168  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2169  *
2170  * Returns 0 for success, non-zero for failure.
2171  */
2172 static int
2173 _base_send_ioc_reset(struct MPT2SAS_ADAPTER *ioc, u8 reset_type, int timeout,
2174     int sleep_flag)
2175 {
2176         u32 ioc_state;
2177         int r = 0;
2178
2179         if (reset_type != MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET) {
2180                 printk(MPT2SAS_ERR_FMT "%s: unknown reset_type\n",
2181                     ioc->name, __func__);
2182                 return -EFAULT;
2183         }
2184
2185         if (!(ioc->facts.IOCCapabilities &
2186            MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY))
2187                 return -EFAULT;
2188
2189         printk(MPT2SAS_INFO_FMT "sending message unit reset !!\n", ioc->name);
2190
2191         writel(reset_type << MPI2_DOORBELL_FUNCTION_SHIFT,
2192             &ioc->chip->Doorbell);
2193         if ((_base_wait_for_doorbell_ack(ioc, 15, sleep_flag))) {
2194                 r = -EFAULT;
2195                 goto out;
2196         }
2197         ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY,
2198             timeout, sleep_flag);
2199         if (ioc_state) {
2200                 printk(MPT2SAS_ERR_FMT "%s: failed going to ready state "
2201                     " (ioc_state=0x%x)\n", ioc->name, __func__, ioc_state);
2202                 r = -EFAULT;
2203                 goto out;
2204         }
2205  out:
2206         printk(MPT2SAS_INFO_FMT "message unit reset: %s\n",
2207             ioc->name, ((r == 0) ? "SUCCESS" : "FAILED"));
2208         return r;
2209 }
2210
2211 /**
2212  * _base_handshake_req_reply_wait - send request thru doorbell interface
2213  * @ioc: per adapter object
2214  * @request_bytes: request length
2215  * @request: pointer having request payload
2216  * @reply_bytes: reply length
2217  * @reply: pointer to reply payload
2218  * @timeout: timeout in second
2219  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2220  *
2221  * Returns 0 for success, non-zero for failure.
2222  */
2223 static int
2224 _base_handshake_req_reply_wait(struct MPT2SAS_ADAPTER *ioc, int request_bytes,
2225     u32 *request, int reply_bytes, u16 *reply, int timeout, int sleep_flag)
2226 {
2227         MPI2DefaultReply_t *default_reply = (MPI2DefaultReply_t *)reply;
2228         int i;
2229         u8 failed;
2230         u16 dummy;
2231         u32 *mfp;
2232
2233         /* make sure doorbell is not in use */
2234         if ((readl(&ioc->chip->Doorbell) & MPI2_DOORBELL_USED)) {
2235                 printk(MPT2SAS_ERR_FMT "doorbell is in use "
2236                     " (line=%d)\n", ioc->name, __LINE__);
2237                 return -EFAULT;
2238         }
2239
2240         /* clear pending doorbell interrupts from previous state changes */
2241         if (readl(&ioc->chip->HostInterruptStatus) &
2242             MPI2_HIS_IOC2SYS_DB_STATUS)
2243                 writel(0, &ioc->chip->HostInterruptStatus);
2244
2245         /* send message to ioc */
2246         writel(((MPI2_FUNCTION_HANDSHAKE<<MPI2_DOORBELL_FUNCTION_SHIFT) |
2247             ((request_bytes/4)<<MPI2_DOORBELL_ADD_DWORDS_SHIFT)),
2248             &ioc->chip->Doorbell);
2249
2250         if ((_base_wait_for_doorbell_int(ioc, 5, sleep_flag))) {
2251                 printk(MPT2SAS_ERR_FMT "doorbell handshake "
2252                    "int failed (line=%d)\n", ioc->name, __LINE__);
2253                 return -EFAULT;
2254         }
2255         writel(0, &ioc->chip->HostInterruptStatus);
2256
2257         if ((_base_wait_for_doorbell_ack(ioc, 5, sleep_flag))) {
2258                 printk(MPT2SAS_ERR_FMT "doorbell handshake "
2259                     "ack failed (line=%d)\n", ioc->name, __LINE__);
2260                 return -EFAULT;
2261         }
2262
2263         /* send message 32-bits at a time */
2264         for (i = 0, failed = 0; i < request_bytes/4 && !failed; i++) {
2265                 writel(cpu_to_le32(request[i]), &ioc->chip->Doorbell);
2266                 if ((_base_wait_for_doorbell_ack(ioc, 5, sleep_flag)))
2267                         failed = 1;
2268         }
2269
2270         if (failed) {
2271                 printk(MPT2SAS_ERR_FMT "doorbell handshake "
2272                     "sending request failed (line=%d)\n", ioc->name, __LINE__);
2273                 return -EFAULT;
2274         }
2275
2276         /* now wait for the reply */
2277         if ((_base_wait_for_doorbell_int(ioc, timeout, sleep_flag))) {
2278                 printk(MPT2SAS_ERR_FMT "doorbell handshake "
2279                    "int failed (line=%d)\n", ioc->name, __LINE__);
2280                 return -EFAULT;
2281         }
2282
2283         /* read the first two 16-bits, it gives the total length of the reply */
2284         reply[0] = le16_to_cpu(readl(&ioc->chip->Doorbell)
2285             & MPI2_DOORBELL_DATA_MASK);
2286         writel(0, &ioc->chip->HostInterruptStatus);
2287         if ((_base_wait_for_doorbell_int(ioc, 5, sleep_flag))) {
2288                 printk(MPT2SAS_ERR_FMT "doorbell handshake "
2289                    "int failed (line=%d)\n", ioc->name, __LINE__);
2290                 return -EFAULT;
2291         }
2292         reply[1] = le16_to_cpu(readl(&ioc->chip->Doorbell)
2293             & MPI2_DOORBELL_DATA_MASK);
2294         writel(0, &ioc->chip->HostInterruptStatus);
2295
2296         for (i = 2; i < default_reply->MsgLength * 2; i++)  {
2297                 if ((_base_wait_for_doorbell_int(ioc, 5, sleep_flag))) {
2298                         printk(MPT2SAS_ERR_FMT "doorbell "
2299                             "handshake int failed (line=%d)\n", ioc->name,
2300                             __LINE__);
2301                         return -EFAULT;
2302                 }
2303                 if (i >=  reply_bytes/2) /* overflow case */
2304                         dummy = readl(&ioc->chip->Doorbell);
2305                 else
2306                         reply[i] = le16_to_cpu(readl(&ioc->chip->Doorbell)
2307                             & MPI2_DOORBELL_DATA_MASK);
2308                 writel(0, &ioc->chip->HostInterruptStatus);
2309         }
2310
2311         _base_wait_for_doorbell_int(ioc, 5, sleep_flag);
2312         if (_base_wait_for_doorbell_not_used(ioc, 5, sleep_flag) != 0) {
2313                 dhsprintk(ioc, printk(MPT2SAS_INFO_FMT "doorbell is in use "
2314                     " (line=%d)\n", ioc->name, __LINE__));
2315         }
2316         writel(0, &ioc->chip->HostInterruptStatus);
2317
2318         if (ioc->logging_level & MPT_DEBUG_INIT) {
2319                 mfp = (u32 *)reply;
2320                 printk(KERN_DEBUG "\toffset:data\n");
2321                 for (i = 0; i < reply_bytes/4; i++)
2322                         printk(KERN_DEBUG "\t[0x%02x]:%08x\n", i*4,
2323                             le32_to_cpu(mfp[i]));
2324         }
2325         return 0;
2326 }
2327
2328 /**
2329  * mpt2sas_base_sas_iounit_control - send sas iounit control to FW
2330  * @ioc: per adapter object
2331  * @mpi_reply: the reply payload from FW
2332  * @mpi_request: the request payload sent to FW
2333  *
2334  * The SAS IO Unit Control Request message allows the host to perform low-level
2335  * operations, such as resets on the PHYs of the IO Unit, also allows the host
2336  * to obtain the IOC assigned device handles for a device if it has other
2337  * identifying information about the device, in addition allows the host to
2338  * remove IOC resources associated with the device.
2339  *
2340  * Returns 0 for success, non-zero for failure.
2341  */
2342 int
2343 mpt2sas_base_sas_iounit_control(struct MPT2SAS_ADAPTER *ioc,
2344     Mpi2SasIoUnitControlReply_t *mpi_reply,
2345     Mpi2SasIoUnitControlRequest_t *mpi_request)
2346 {
2347         u16 smid;
2348         u32 ioc_state;
2349         unsigned long timeleft;
2350         u8 issue_reset;
2351         int rc;
2352         void *request;
2353         u16 wait_state_count;
2354
2355         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
2356             __func__));
2357
2358         mutex_lock(&ioc->base_cmds.mutex);
2359
2360         if (ioc->base_cmds.status != MPT2_CMD_NOT_USED) {
2361                 printk(MPT2SAS_ERR_FMT "%s: base_cmd in use\n",
2362                     ioc->name, __func__);
2363                 rc = -EAGAIN;
2364                 goto out;
2365         }
2366
2367         wait_state_count = 0;
2368         ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
2369         while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
2370                 if (wait_state_count++ == 10) {
2371                         printk(MPT2SAS_ERR_FMT
2372                             "%s: failed due to ioc not operational\n",
2373                             ioc->name, __func__);
2374                         rc = -EFAULT;
2375                         goto out;
2376                 }
2377                 ssleep(1);
2378                 ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
2379                 printk(MPT2SAS_INFO_FMT "%s: waiting for "
2380                     "operational state(count=%d)\n", ioc->name,
2381                     __func__, wait_state_count);
2382         }
2383
2384         smid = mpt2sas_base_get_smid(ioc, ioc->base_cb_idx);
2385         if (!smid) {
2386                 printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
2387                     ioc->name, __func__);
2388                 rc = -EAGAIN;
2389                 goto out;
2390         }
2391
2392         rc = 0;
2393         ioc->base_cmds.status = MPT2_CMD_PENDING;
2394         request = mpt2sas_base_get_msg_frame(ioc, smid);
2395         ioc->base_cmds.smid = smid;
2396         memcpy(request, mpi_request, sizeof(Mpi2SasIoUnitControlRequest_t));
2397         if (mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
2398             mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET)
2399                 ioc->ioc_link_reset_in_progress = 1;
2400         mpt2sas_base_put_smid_default(ioc, smid, mpi_request->VF_ID);
2401         timeleft = wait_for_completion_timeout(&ioc->base_cmds.done,
2402             msecs_to_jiffies(10000));
2403         if ((mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
2404             mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET) &&
2405             ioc->ioc_link_reset_in_progress)
2406                 ioc->ioc_link_reset_in_progress = 0;
2407         if (!(ioc->base_cmds.status & MPT2_CMD_COMPLETE)) {
2408                 printk(MPT2SAS_ERR_FMT "%s: timeout\n",
2409                     ioc->name, __func__);
2410                 _debug_dump_mf(mpi_request,
2411                     sizeof(Mpi2SasIoUnitControlRequest_t)/4);
2412                 if (!(ioc->base_cmds.status & MPT2_CMD_RESET))
2413                         issue_reset = 1;
2414                 goto issue_host_reset;
2415         }
2416         if (ioc->base_cmds.status & MPT2_CMD_REPLY_VALID)
2417                 memcpy(mpi_reply, ioc->base_cmds.reply,
2418                     sizeof(Mpi2SasIoUnitControlReply_t));
2419         else
2420                 memset(mpi_reply, 0, sizeof(Mpi2SasIoUnitControlReply_t));
2421         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
2422         goto out;
2423
2424  issue_host_reset:
2425         if (issue_reset)
2426                 mpt2sas_base_hard_reset_handler(ioc, CAN_SLEEP,
2427                     FORCE_BIG_HAMMER);
2428         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
2429         rc = -EFAULT;
2430  out:
2431         mutex_unlock(&ioc->base_cmds.mutex);
2432         return rc;
2433 }
2434
2435
2436 /**
2437  * mpt2sas_base_scsi_enclosure_processor - sending request to sep device
2438  * @ioc: per adapter object
2439  * @mpi_reply: the reply payload from FW
2440  * @mpi_request: the request payload sent to FW
2441  *
2442  * The SCSI Enclosure Processor request message causes the IOC to
2443  * communicate with SES devices to control LED status signals.
2444  *
2445  * Returns 0 for success, non-zero for failure.
2446  */
2447 int
2448 mpt2sas_base_scsi_enclosure_processor(struct MPT2SAS_ADAPTER *ioc,
2449     Mpi2SepReply_t *mpi_reply, Mpi2SepRequest_t *mpi_request)
2450 {
2451         u16 smid;
2452         u32 ioc_state;
2453         unsigned long timeleft;
2454         u8 issue_reset;
2455         int rc;
2456         void *request;
2457         u16 wait_state_count;
2458
2459         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
2460             __func__));
2461
2462         mutex_lock(&ioc->base_cmds.mutex);
2463
2464         if (ioc->base_cmds.status != MPT2_CMD_NOT_USED) {
2465                 printk(MPT2SAS_ERR_FMT "%s: base_cmd in use\n",
2466                     ioc->name, __func__);
2467                 rc = -EAGAIN;
2468                 goto out;
2469         }
2470
2471         wait_state_count = 0;
2472         ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
2473         while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
2474                 if (wait_state_count++ == 10) {
2475                         printk(MPT2SAS_ERR_FMT
2476                             "%s: failed due to ioc not operational\n",
2477                             ioc->name, __func__);
2478                         rc = -EFAULT;
2479                         goto out;
2480                 }
2481                 ssleep(1);
2482                 ioc_state = mpt2sas_base_get_iocstate(ioc, 1);
2483                 printk(MPT2SAS_INFO_FMT "%s: waiting for "
2484                     "operational state(count=%d)\n", ioc->name,
2485                     __func__, wait_state_count);
2486         }
2487
2488         smid = mpt2sas_base_get_smid(ioc, ioc->base_cb_idx);
2489         if (!smid) {
2490                 printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
2491                     ioc->name, __func__);
2492                 rc = -EAGAIN;
2493                 goto out;
2494         }
2495
2496         rc = 0;
2497         ioc->base_cmds.status = MPT2_CMD_PENDING;
2498         request = mpt2sas_base_get_msg_frame(ioc, smid);
2499         ioc->base_cmds.smid = smid;
2500         memcpy(request, mpi_request, sizeof(Mpi2SepReply_t));
2501         mpt2sas_base_put_smid_default(ioc, smid, mpi_request->VF_ID);
2502         timeleft = wait_for_completion_timeout(&ioc->base_cmds.done,
2503             msecs_to_jiffies(10000));
2504         if (!(ioc->base_cmds.status & MPT2_CMD_COMPLETE)) {
2505                 printk(MPT2SAS_ERR_FMT "%s: timeout\n",
2506                     ioc->name, __func__);
2507                 _debug_dump_mf(mpi_request,
2508                     sizeof(Mpi2SepRequest_t)/4);
2509                 if (!(ioc->base_cmds.status & MPT2_CMD_RESET))
2510                         issue_reset = 1;
2511                 goto issue_host_reset;
2512         }
2513         if (ioc->base_cmds.status & MPT2_CMD_REPLY_VALID)
2514                 memcpy(mpi_reply, ioc->base_cmds.reply,
2515                     sizeof(Mpi2SepReply_t));
2516         else
2517                 memset(mpi_reply, 0, sizeof(Mpi2SepReply_t));
2518         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
2519         goto out;
2520
2521  issue_host_reset:
2522         if (issue_reset)
2523                 mpt2sas_base_hard_reset_handler(ioc, CAN_SLEEP,
2524                     FORCE_BIG_HAMMER);
2525         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
2526         rc = -EFAULT;
2527  out:
2528         mutex_unlock(&ioc->base_cmds.mutex);
2529         return rc;
2530 }
2531
2532 /**
2533  * _base_get_port_facts - obtain port facts reply and save in ioc
2534  * @ioc: per adapter object
2535  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2536  *
2537  * Returns 0 for success, non-zero for failure.
2538  */
2539 static int
2540 _base_get_port_facts(struct MPT2SAS_ADAPTER *ioc, int port, int sleep_flag)
2541 {
2542         Mpi2PortFactsRequest_t mpi_request;
2543         Mpi2PortFactsReply_t mpi_reply, *pfacts;
2544         int mpi_reply_sz, mpi_request_sz, r;
2545
2546         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
2547             __func__));
2548
2549         mpi_reply_sz = sizeof(Mpi2PortFactsReply_t);
2550         mpi_request_sz = sizeof(Mpi2PortFactsRequest_t);
2551         memset(&mpi_request, 0, mpi_request_sz);
2552         mpi_request.Function = MPI2_FUNCTION_PORT_FACTS;
2553         mpi_request.PortNumber = port;
2554         r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
2555             (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5, CAN_SLEEP);
2556
2557         if (r != 0) {
2558                 printk(MPT2SAS_ERR_FMT "%s: handshake failed (r=%d)\n",
2559                     ioc->name, __func__, r);
2560                 return r;
2561         }
2562
2563         pfacts = &ioc->pfacts[port];
2564         memset(pfacts, 0, sizeof(Mpi2PortFactsReply_t));
2565         pfacts->PortNumber = mpi_reply.PortNumber;
2566         pfacts->VP_ID = mpi_reply.VP_ID;
2567         pfacts->VF_ID = mpi_reply.VF_ID;
2568         pfacts->MaxPostedCmdBuffers =
2569             le16_to_cpu(mpi_reply.MaxPostedCmdBuffers);
2570
2571         return 0;
2572 }
2573
2574 /**
2575  * _base_get_ioc_facts - obtain ioc facts reply and save in ioc
2576  * @ioc: per adapter object
2577  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2578  *
2579  * Returns 0 for success, non-zero for failure.
2580  */
2581 static int
2582 _base_get_ioc_facts(struct MPT2SAS_ADAPTER *ioc, int sleep_flag)
2583 {
2584         Mpi2IOCFactsRequest_t mpi_request;
2585         Mpi2IOCFactsReply_t mpi_reply, *facts;
2586         int mpi_reply_sz, mpi_request_sz, r;
2587
2588         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
2589             __func__));
2590
2591         mpi_reply_sz = sizeof(Mpi2IOCFactsReply_t);
2592         mpi_request_sz = sizeof(Mpi2IOCFactsRequest_t);
2593         memset(&mpi_request, 0, mpi_request_sz);
2594         mpi_request.Function = MPI2_FUNCTION_IOC_FACTS;
2595         r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
2596             (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5, CAN_SLEEP);
2597
2598         if (r != 0) {
2599                 printk(MPT2SAS_ERR_FMT "%s: handshake failed (r=%d)\n",
2600                     ioc->name, __func__, r);
2601                 return r;
2602         }
2603
2604         facts = &ioc->facts;
2605         memset(facts, 0, sizeof(Mpi2IOCFactsReply_t));
2606         facts->MsgVersion = le16_to_cpu(mpi_reply.MsgVersion);
2607         facts->HeaderVersion = le16_to_cpu(mpi_reply.HeaderVersion);
2608         facts->VP_ID = mpi_reply.VP_ID;
2609         facts->VF_ID = mpi_reply.VF_ID;
2610         facts->IOCExceptions = le16_to_cpu(mpi_reply.IOCExceptions);
2611         facts->MaxChainDepth = mpi_reply.MaxChainDepth;
2612         facts->WhoInit = mpi_reply.WhoInit;
2613         facts->NumberOfPorts = mpi_reply.NumberOfPorts;
2614         facts->RequestCredit = le16_to_cpu(mpi_reply.RequestCredit);
2615         facts->MaxReplyDescriptorPostQueueDepth =
2616             le16_to_cpu(mpi_reply.MaxReplyDescriptorPostQueueDepth);
2617         facts->ProductID = le16_to_cpu(mpi_reply.ProductID);
2618         facts->IOCCapabilities = le32_to_cpu(mpi_reply.IOCCapabilities);
2619         if ((facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID))
2620                 ioc->ir_firmware = 1;
2621         facts->FWVersion.Word = le32_to_cpu(mpi_reply.FWVersion.Word);
2622         facts->IOCRequestFrameSize =
2623             le16_to_cpu(mpi_reply.IOCRequestFrameSize);
2624         facts->MaxInitiators = le16_to_cpu(mpi_reply.MaxInitiators);
2625         facts->MaxTargets = le16_to_cpu(mpi_reply.MaxTargets);
2626         ioc->shost->max_id = -1;
2627         facts->MaxSasExpanders = le16_to_cpu(mpi_reply.MaxSasExpanders);
2628         facts->MaxEnclosures = le16_to_cpu(mpi_reply.MaxEnclosures);
2629         facts->ProtocolFlags = le16_to_cpu(mpi_reply.ProtocolFlags);
2630         facts->HighPriorityCredit =
2631             le16_to_cpu(mpi_reply.HighPriorityCredit);
2632         facts->ReplyFrameSize = mpi_reply.ReplyFrameSize;
2633         facts->MaxDevHandle = le16_to_cpu(mpi_reply.MaxDevHandle);
2634
2635         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "hba queue depth(%d), "
2636             "max chains per io(%d)\n", ioc->name, facts->RequestCredit,
2637             facts->MaxChainDepth));
2638         dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "request frame size(%d), "
2639             "reply frame size(%d)\n", ioc->name,
2640             facts->IOCRequestFrameSize * 4, facts->ReplyFrameSize * 4));
2641         return 0;
2642 }
2643
2644 /**
2645  * _base_send_ioc_init - send ioc_init to firmware
2646  * @ioc: per adapter object
2647  * @VF_ID: virtual function id
2648  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2649  *
2650  * Returns 0 for success, non-zero for failure.
2651  */
2652 static int
2653 _base_send_ioc_init(struct MPT2SAS_ADAPTER *ioc, u8 VF_ID, int sleep_flag)
2654 {
2655         Mpi2IOCInitRequest_t mpi_request;
2656         Mpi2IOCInitReply_t mpi_reply;
2657         int r;
2658
2659         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
2660             __func__));
2661
2662         memset(&mpi_request, 0, sizeof(Mpi2IOCInitRequest_t));
2663         mpi_request.Function = MPI2_FUNCTION_IOC_INIT;
2664         mpi_request.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
2665         mpi_request.VF_ID = VF_ID;
2666         mpi_request.MsgVersion = cpu_to_le16(MPI2_VERSION);
2667         mpi_request.HeaderVersion = cpu_to_le16(MPI2_HEADER_VERSION);
2668
2669         /* In MPI Revision I (0xA), the SystemReplyFrameSize(offset 0x18) was
2670          * removed and made reserved.  For those with older firmware will need
2671          * this fix. It was decided that the Reply and Request frame sizes are
2672          * the same.
2673          */
2674         if ((ioc->facts.HeaderVersion >> 8) < 0xA) {
2675                 mpi_request.Reserved7 = cpu_to_le16(ioc->reply_sz);
2676 /*              mpi_request.SystemReplyFrameSize =
2677  *               cpu_to_le16(ioc->reply_sz);
2678  */
2679         }
2680
2681         mpi_request.SystemRequestFrameSize = cpu_to_le16(ioc->request_sz/4);
2682         mpi_request.ReplyDescriptorPostQueueDepth =
2683             cpu_to_le16(ioc->reply_post_queue_depth);
2684         mpi_request.ReplyFreeQueueDepth =
2685             cpu_to_le16(ioc->reply_free_queue_depth);
2686
2687 #if BITS_PER_LONG > 32
2688         mpi_request.SenseBufferAddressHigh =
2689             cpu_to_le32(ioc->sense_dma >> 32);
2690         mpi_request.SystemReplyAddressHigh =
2691             cpu_to_le32(ioc->reply_dma >> 32);
2692         mpi_request.SystemRequestFrameBaseAddress =
2693             cpu_to_le64(ioc->request_dma);
2694         mpi_request.ReplyFreeQueueAddress =
2695             cpu_to_le64(ioc->reply_free_dma);
2696         mpi_request.ReplyDescriptorPostQueueAddress =
2697             cpu_to_le64(ioc->reply_post_free_dma);
2698 #else
2699         mpi_request.SystemRequestFrameBaseAddress =
2700             cpu_to_le32(ioc->request_dma);
2701         mpi_request.ReplyFreeQueueAddress =
2702             cpu_to_le32(ioc->reply_free_dma);
2703         mpi_request.ReplyDescriptorPostQueueAddress =
2704             cpu_to_le32(ioc->reply_post_free_dma);
2705 #endif
2706
2707         if (ioc->logging_level & MPT_DEBUG_INIT) {
2708                 u32 *mfp;
2709                 int i;
2710
2711                 mfp = (u32 *)&mpi_request;
2712                 printk(KERN_DEBUG "\toffset:data\n");
2713                 for (i = 0; i < sizeof(Mpi2IOCInitRequest_t)/4; i++)
2714                         printk(KERN_DEBUG "\t[0x%02x]:%08x\n", i*4,
2715                             le32_to_cpu(mfp[i]));
2716         }
2717
2718         r = _base_handshake_req_reply_wait(ioc,
2719             sizeof(Mpi2IOCInitRequest_t), (u32 *)&mpi_request,
2720             sizeof(Mpi2IOCInitReply_t), (u16 *)&mpi_reply, 10,
2721             sleep_flag);
2722
2723         if (r != 0) {
2724                 printk(MPT2SAS_ERR_FMT "%s: handshake failed (r=%d)\n",
2725                     ioc->name, __func__, r);
2726                 return r;
2727         }
2728
2729         if (mpi_reply.IOCStatus != MPI2_IOCSTATUS_SUCCESS ||
2730             mpi_reply.IOCLogInfo) {
2731                 printk(MPT2SAS_ERR_FMT "%s: failed\n", ioc->name, __func__);
2732                 r = -EIO;
2733         }
2734
2735         return 0;
2736 }
2737
2738 /**
2739  * _base_send_port_enable - send port_enable(discovery stuff) to firmware
2740  * @ioc: per adapter object
2741  * @VF_ID: virtual function id
2742  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2743  *
2744  * Returns 0 for success, non-zero for failure.
2745  */
2746 static int
2747 _base_send_port_enable(struct MPT2SAS_ADAPTER *ioc, u8 VF_ID, int sleep_flag)
2748 {
2749         Mpi2PortEnableRequest_t *mpi_request;
2750         u32 ioc_state;
2751         unsigned long timeleft;
2752         int r = 0;
2753         u16 smid;
2754
2755         printk(MPT2SAS_INFO_FMT "sending port enable !!\n", ioc->name);
2756
2757         if (ioc->base_cmds.status & MPT2_CMD_PENDING) {
2758                 printk(MPT2SAS_ERR_FMT "%s: internal command already in use\n",
2759                     ioc->name, __func__);
2760                 return -EAGAIN;
2761         }
2762
2763         smid = mpt2sas_base_get_smid(ioc, ioc->base_cb_idx);
2764         if (!smid) {
2765                 printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
2766                     ioc->name, __func__);
2767                 return -EAGAIN;
2768         }
2769
2770         ioc->base_cmds.status = MPT2_CMD_PENDING;
2771         mpi_request = mpt2sas_base_get_msg_frame(ioc, smid);
2772         ioc->base_cmds.smid = smid;
2773         memset(mpi_request, 0, sizeof(Mpi2PortEnableRequest_t));
2774         mpi_request->Function = MPI2_FUNCTION_PORT_ENABLE;
2775         mpi_request->VF_ID = VF_ID;
2776
2777         mpt2sas_base_put_smid_default(ioc, smid, VF_ID);
2778         timeleft = wait_for_completion_timeout(&ioc->base_cmds.done,
2779             300*HZ);
2780         if (!(ioc->base_cmds.status & MPT2_CMD_COMPLETE)) {
2781                 printk(MPT2SAS_ERR_FMT "%s: timeout\n",
2782                     ioc->name, __func__);
2783                 _debug_dump_mf(mpi_request,
2784                     sizeof(Mpi2PortEnableRequest_t)/4);
2785                 if (ioc->base_cmds.status & MPT2_CMD_RESET)
2786                         r = -EFAULT;
2787                 else
2788                         r = -ETIME;
2789                 goto out;
2790         } else
2791                 dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: complete\n",
2792                     ioc->name, __func__));
2793
2794         ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_OPERATIONAL,
2795             60, sleep_flag);
2796         if (ioc_state) {
2797                 printk(MPT2SAS_ERR_FMT "%s: failed going to operational state "
2798                     " (ioc_state=0x%x)\n", ioc->name, __func__, ioc_state);
2799                 r = -EFAULT;
2800         }
2801  out:
2802         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
2803         printk(MPT2SAS_INFO_FMT "port enable: %s\n",
2804             ioc->name, ((r == 0) ? "SUCCESS" : "FAILED"));
2805         return r;
2806 }
2807
2808 /**
2809  * _base_unmask_events - turn on notification for this event
2810  * @ioc: per adapter object
2811  * @event: firmware event
2812  *
2813  * The mask is stored in ioc->event_masks.
2814  */
2815 static void
2816 _base_unmask_events(struct MPT2SAS_ADAPTER *ioc, u16 event)
2817 {
2818         u32 desired_event;
2819
2820         if (event >= 128)
2821                 return;
2822
2823         desired_event = (1 << (event % 32));
2824
2825         if (event < 32)
2826                 ioc->event_masks[0] &= ~desired_event;
2827         else if (event < 64)
2828                 ioc->event_masks[1] &= ~desired_event;
2829         else if (event < 96)
2830                 ioc->event_masks[2] &= ~desired_event;
2831         else if (event < 128)
2832                 ioc->event_masks[3] &= ~desired_event;
2833 }
2834
2835 /**
2836  * _base_event_notification - send event notification
2837  * @ioc: per adapter object
2838  * @VF_ID: virtual function id
2839  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2840  *
2841  * Returns 0 for success, non-zero for failure.
2842  */
2843 static int
2844 _base_event_notification(struct MPT2SAS_ADAPTER *ioc, u8 VF_ID, int sleep_flag)
2845 {
2846         Mpi2EventNotificationRequest_t *mpi_request;
2847         unsigned long timeleft;
2848         u16 smid;
2849         int r = 0;
2850         int i;
2851
2852         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
2853             __func__));
2854
2855         if (ioc->base_cmds.status & MPT2_CMD_PENDING) {
2856                 printk(MPT2SAS_ERR_FMT "%s: internal command already in use\n",
2857                     ioc->name, __func__);
2858                 return -EAGAIN;
2859         }
2860
2861         smid = mpt2sas_base_get_smid(ioc, ioc->base_cb_idx);
2862         if (!smid) {
2863                 printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
2864                     ioc->name, __func__);
2865                 return -EAGAIN;
2866         }
2867         ioc->base_cmds.status = MPT2_CMD_PENDING;
2868         mpi_request = mpt2sas_base_get_msg_frame(ioc, smid);
2869         ioc->base_cmds.smid = smid;
2870         memset(mpi_request, 0, sizeof(Mpi2EventNotificationRequest_t));
2871         mpi_request->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2872         mpi_request->VF_ID = VF_ID;
2873         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2874                 mpi_request->EventMasks[i] =
2875                     le32_to_cpu(ioc->event_masks[i]);
2876         mpt2sas_base_put_smid_default(ioc, smid, VF_ID);
2877         timeleft = wait_for_completion_timeout(&ioc->base_cmds.done, 30*HZ);
2878         if (!(ioc->base_cmds.status & MPT2_CMD_COMPLETE)) {
2879                 printk(MPT2SAS_ERR_FMT "%s: timeout\n",
2880                     ioc->name, __func__);
2881                 _debug_dump_mf(mpi_request,
2882                     sizeof(Mpi2EventNotificationRequest_t)/4);
2883                 if (ioc->base_cmds.status & MPT2_CMD_RESET)
2884                         r = -EFAULT;
2885                 else
2886                         r = -ETIME;
2887         } else
2888                 dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: complete\n",
2889                     ioc->name, __func__));
2890         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
2891         return r;
2892 }
2893
2894 /**
2895  * mpt2sas_base_validate_event_type - validating event types
2896  * @ioc: per adapter object
2897  * @event: firmware event
2898  *
2899  * This will turn on firmware event notification when application
2900  * ask for that event. We don't mask events that are already enabled.
2901  */
2902 void
2903 mpt2sas_base_validate_event_type(struct MPT2SAS_ADAPTER *ioc, u32 *event_type)
2904 {
2905         int i, j;
2906         u32 event_mask, desired_event;
2907         u8 send_update_to_fw;
2908
2909         for (i = 0, send_update_to_fw = 0; i <
2910             MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++) {
2911                 event_mask = ~event_type[i];
2912                 desired_event = 1;
2913                 for (j = 0; j < 32; j++) {
2914                         if (!(event_mask & desired_event) &&
2915                             (ioc->event_masks[i] & desired_event)) {
2916                                 ioc->event_masks[i] &= ~desired_event;
2917                                 send_update_to_fw = 1;
2918                         }
2919                         desired_event = (desired_event << 1);
2920                 }
2921         }
2922
2923         if (!send_update_to_fw)
2924                 return;
2925
2926         mutex_lock(&ioc->base_cmds.mutex);
2927         _base_event_notification(ioc, 0, CAN_SLEEP);
2928         mutex_unlock(&ioc->base_cmds.mutex);
2929 }
2930
2931 /**
2932  * _base_diag_reset - the "big hammer" start of day reset
2933  * @ioc: per adapter object
2934  * @sleep_flag: CAN_SLEEP or NO_SLEEP
2935  *
2936  * Returns 0 for success, non-zero for failure.
2937  */
2938 static int
2939 _base_diag_reset(struct MPT2SAS_ADAPTER *ioc, int sleep_flag)
2940 {
2941         u32 host_diagnostic;
2942         u32 ioc_state;
2943         u32 count;
2944         u32 hcb_size;
2945
2946         printk(MPT2SAS_INFO_FMT "sending diag reset !!\n", ioc->name);
2947
2948         _base_save_msix_table(ioc);
2949
2950         drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "clear interrupts\n",
2951             ioc->name));
2952         writel(0, &ioc->chip->HostInterruptStatus);
2953
2954         count = 0;
2955         do {
2956                 /* Write magic sequence to WriteSequence register
2957                  * Loop until in diagnostic mode
2958                  */
2959                 drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "write magic "
2960                     "sequence\n", ioc->name));
2961                 writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
2962                 writel(MPI2_WRSEQ_1ST_KEY_VALUE, &ioc->chip->WriteSequence);
2963                 writel(MPI2_WRSEQ_2ND_KEY_VALUE, &ioc->chip->WriteSequence);
2964                 writel(MPI2_WRSEQ_3RD_KEY_VALUE, &ioc->chip->WriteSequence);
2965                 writel(MPI2_WRSEQ_4TH_KEY_VALUE, &ioc->chip->WriteSequence);
2966                 writel(MPI2_WRSEQ_5TH_KEY_VALUE, &ioc->chip->WriteSequence);
2967                 writel(MPI2_WRSEQ_6TH_KEY_VALUE, &ioc->chip->WriteSequence);
2968
2969                 /* wait 100 msec */
2970                 if (sleep_flag == CAN_SLEEP)
2971                         msleep(100);
2972                 else
2973                         mdelay(100);
2974
2975                 if (count++ > 20)
2976                         goto out;
2977
2978                 host_diagnostic = readl(&ioc->chip->HostDiagnostic);
2979                 drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "wrote magic "
2980                     "sequence: count(%d), host_diagnostic(0x%08x)\n",
2981                     ioc->name, count, host_diagnostic));
2982
2983         } while ((host_diagnostic & MPI2_DIAG_DIAG_WRITE_ENABLE) == 0);
2984
2985         hcb_size = readl(&ioc->chip->HCBSize);
2986
2987         drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "diag reset: issued\n",
2988             ioc->name));
2989         writel(host_diagnostic | MPI2_DIAG_RESET_ADAPTER,
2990              &ioc->chip->HostDiagnostic);
2991
2992         /* don't access any registers for 50 milliseconds */
2993         msleep(50);
2994
2995         /* 300 second max wait */
2996         for (count = 0; count < 3000000 ; count++) {
2997
2998                 host_diagnostic = readl(&ioc->chip->HostDiagnostic);
2999
3000                 if (host_diagnostic == 0xFFFFFFFF)
3001                         goto out;
3002                 if (!(host_diagnostic & MPI2_DIAG_RESET_ADAPTER))
3003                         break;
3004
3005                 /* wait 100 msec */
3006                 if (sleep_flag == CAN_SLEEP)
3007                         msleep(1);
3008                 else
3009                         mdelay(1);
3010         }
3011
3012         if (host_diagnostic & MPI2_DIAG_HCB_MODE) {
3013
3014                 drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "restart the adapter "
3015                     "assuming the HCB Address points to good F/W\n",
3016                     ioc->name));
3017                 host_diagnostic &= ~MPI2_DIAG_BOOT_DEVICE_SELECT_MASK;
3018                 host_diagnostic |= MPI2_DIAG_BOOT_DEVICE_SELECT_HCDW;
3019                 writel(host_diagnostic, &ioc->chip->HostDiagnostic);
3020
3021                 drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT
3022                     "re-enable the HCDW\n", ioc->name));
3023                 writel(hcb_size | MPI2_HCB_SIZE_HCB_ENABLE,
3024                     &ioc->chip->HCBSize);
3025         }
3026
3027         drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "restart the adapter\n",
3028             ioc->name));
3029         writel(host_diagnostic & ~MPI2_DIAG_HOLD_IOC_RESET,
3030             &ioc->chip->HostDiagnostic);
3031
3032         drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "disable writes to the "
3033             "diagnostic register\n", ioc->name));
3034         writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
3035
3036         drsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "Wait for FW to go to the "
3037             "READY state\n", ioc->name));
3038         ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, 20,
3039             sleep_flag);
3040         if (ioc_state) {
3041                 printk(MPT2SAS_ERR_FMT "%s: failed going to ready state "
3042                     " (ioc_state=0x%x)\n", ioc->name, __func__, ioc_state);
3043                 goto out;
3044         }
3045
3046         _base_restore_msix_table(ioc);
3047         printk(MPT2SAS_INFO_FMT "diag reset: SUCCESS\n", ioc->name);
3048         return 0;
3049
3050  out:
3051         printk(MPT2SAS_ERR_FMT "diag reset: FAILED\n", ioc->name);
3052         return -EFAULT;
3053 }
3054
3055 /**
3056  * _base_make_ioc_ready - put controller in READY state
3057  * @ioc: per adapter object
3058  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3059  * @type: FORCE_BIG_HAMMER or SOFT_RESET
3060  *
3061  * Returns 0 for success, non-zero for failure.
3062  */
3063 static int
3064 _base_make_ioc_ready(struct MPT2SAS_ADAPTER *ioc, int sleep_flag,
3065     enum reset_type type)
3066 {
3067         u32 ioc_state;
3068
3069         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
3070             __func__));
3071
3072         ioc_state = mpt2sas_base_get_iocstate(ioc, 0);
3073         dhsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: ioc_state(0x%08x)\n",
3074             ioc->name, __func__, ioc_state));
3075
3076         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_READY)
3077                 return 0;
3078
3079         if (ioc_state & MPI2_DOORBELL_USED) {
3080                 dhsprintk(ioc, printk(MPT2SAS_DEBUG_FMT "unexpected doorbell "
3081                     "active!\n", ioc->name));
3082                 goto issue_diag_reset;
3083         }
3084
3085         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
3086                 mpt2sas_base_fault_info(ioc, ioc_state &
3087                     MPI2_DOORBELL_DATA_MASK);
3088                 goto issue_diag_reset;
3089         }
3090
3091         if (type == FORCE_BIG_HAMMER)
3092                 goto issue_diag_reset;
3093
3094         if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_OPERATIONAL)
3095                 if (!(_base_send_ioc_reset(ioc,
3096                     MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET, 15, CAN_SLEEP)))
3097                         return 0;
3098
3099  issue_diag_reset:
3100         return _base_diag_reset(ioc, CAN_SLEEP);
3101 }
3102
3103 /**
3104  * _base_make_ioc_operational - put controller in OPERATIONAL state
3105  * @ioc: per adapter object
3106  * @VF_ID: virtual function id
3107  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3108  *
3109  * Returns 0 for success, non-zero for failure.
3110  */
3111 static int
3112 _base_make_ioc_operational(struct MPT2SAS_ADAPTER *ioc, u8 VF_ID,
3113     int sleep_flag)
3114 {
3115         int r, i;
3116         unsigned long   flags;
3117         u32 reply_address;
3118
3119         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
3120             __func__));
3121
3122         /* initialize the scsi lookup free list */
3123         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3124         INIT_LIST_HEAD(&ioc->free_list);
3125         for (i = 0; i < ioc->request_depth; i++) {
3126                 ioc->scsi_lookup[i].cb_idx = 0xFF;
3127                 list_add_tail(&ioc->scsi_lookup[i].tracker_list,
3128                     &ioc->free_list);
3129         }
3130         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3131
3132         /* initialize Reply Free Queue */
3133         for (i = 0, reply_address = (u32)ioc->reply_dma ;
3134             i < ioc->reply_free_queue_depth ; i++, reply_address +=
3135             ioc->reply_sz)
3136                 ioc->reply_free[i] = cpu_to_le32(reply_address);
3137
3138         /* initialize Reply Post Free Queue */
3139         for (i = 0; i < ioc->reply_post_queue_depth; i++)
3140                 ioc->reply_post_free[i].Words = ULLONG_MAX;
3141
3142         r = _base_send_ioc_init(ioc, VF_ID, sleep_flag);
3143         if (r)
3144                 return r;
3145
3146         /* initialize the index's */
3147         ioc->reply_free_host_index = ioc->reply_free_queue_depth - 1;
3148         ioc->reply_post_host_index = 0;
3149         writel(ioc->reply_free_host_index, &ioc->chip->ReplyFreeHostIndex);
3150         writel(0, &ioc->chip->ReplyPostHostIndex);
3151
3152         _base_unmask_interrupts(ioc);
3153         r = _base_event_notification(ioc, VF_ID, sleep_flag);
3154         if (r)
3155                 return r;
3156
3157         if (sleep_flag == CAN_SLEEP)
3158                 _base_static_config_pages(ioc);
3159
3160         r = _base_send_port_enable(ioc, VF_ID, sleep_flag);
3161         if (r)
3162                 return r;
3163
3164         return r;
3165 }
3166
3167 /**
3168  * mpt2sas_base_free_resources - free resources controller resources (io/irq/memap)
3169  * @ioc: per adapter object
3170  *
3171  * Return nothing.
3172  */
3173 void
3174 mpt2sas_base_free_resources(struct MPT2SAS_ADAPTER *ioc)
3175 {
3176         struct pci_dev *pdev = ioc->pdev;
3177
3178         dexitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
3179             __func__));
3180
3181         _base_mask_interrupts(ioc);
3182         _base_make_ioc_ready(ioc, CAN_SLEEP, SOFT_RESET);
3183         if (ioc->pci_irq) {
3184                 synchronize_irq(pdev->irq);
3185                 free_irq(ioc->pci_irq, ioc);
3186         }
3187         _base_disable_msix(ioc);
3188         if (ioc->chip_phys)
3189                 iounmap(ioc->chip);
3190         ioc->pci_irq = -1;
3191         ioc->chip_phys = 0;
3192         pci_release_selected_regions(ioc->pdev, ioc->bars);
3193         pci_disable_device(pdev);
3194         pci_set_drvdata(pdev, NULL);
3195         return;
3196 }
3197
3198 /**
3199  * mpt2sas_base_attach - attach controller instance
3200  * @ioc: per adapter object
3201  *
3202  * Returns 0 for success, non-zero for failure.
3203  */
3204 int
3205 mpt2sas_base_attach(struct MPT2SAS_ADAPTER *ioc)
3206 {
3207         int r, i;
3208         unsigned long    flags;
3209
3210         dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
3211             __func__));
3212
3213         r = mpt2sas_base_map_resources(ioc);
3214         if (r)
3215                 return r;
3216
3217         r = _base_make_ioc_ready(ioc, CAN_SLEEP, SOFT_RESET);
3218         if (r)
3219                 goto out_free_resources;
3220
3221         r = _base_get_ioc_facts(ioc, CAN_SLEEP);
3222         if (r)
3223                 goto out_free_resources;
3224
3225         r = _base_allocate_memory_pools(ioc, CAN_SLEEP);
3226         if (r)
3227                 goto out_free_resources;
3228
3229         init_waitqueue_head(&ioc->reset_wq);
3230
3231         /* base internal command bits */
3232         mutex_init(&ioc->base_cmds.mutex);
3233         init_completion(&ioc->base_cmds.done);
3234         ioc->base_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
3235         ioc->base_cmds.status = MPT2_CMD_NOT_USED;
3236
3237         /* transport internal command bits */
3238         ioc->transport_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
3239         ioc->transport_cmds.status = MPT2_CMD_NOT_USED;
3240         mutex_init(&ioc->transport_cmds.mutex);
3241         init_completion(&ioc->transport_cmds.done);
3242
3243         /* task management internal command bits */
3244         ioc->tm_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
3245         ioc->tm_cmds.status = MPT2_CMD_NOT_USED;
3246         mutex_init(&ioc->tm_cmds.mutex);
3247         init_completion(&ioc->tm_cmds.done);
3248
3249         /* config page internal command bits */
3250         ioc->config_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
3251         ioc->config_cmds.status = MPT2_CMD_NOT_USED;
3252         mutex_init(&ioc->config_cmds.mutex);
3253         init_completion(&ioc->config_cmds.done);
3254
3255         /* ctl module internal command bits */
3256         ioc->ctl_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
3257         ioc->ctl_cmds.status = MPT2_CMD_NOT_USED;
3258         mutex_init(&ioc->ctl_cmds.mutex);
3259         init_completion(&ioc->ctl_cmds.done);
3260
3261         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
3262                 ioc->event_masks[i] = -1;
3263
3264         /* here we enable the events we care about */
3265         _base_unmask_events(ioc, MPI2_EVENT_SAS_DISCOVERY);
3266         _base_unmask_events(ioc, MPI2_EVENT_SAS_BROADCAST_PRIMITIVE);
3267         _base_unmask_events(ioc, MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST);
3268         _base_unmask_events(ioc, MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE);
3269         _base_unmask_events(ioc, MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE);
3270         _base_unmask_events(ioc, MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST);
3271         _base_unmask_events(ioc, MPI2_EVENT_IR_VOLUME);
3272         _base_unmask_events(ioc, MPI2_EVENT_IR_PHYSICAL_DISK);
3273         _base_unmask_events(ioc, MPI2_EVENT_IR_OPERATION_STATUS);
3274         _base_unmask_events(ioc, MPI2_EVENT_TASK_SET_FULL);
3275         _base_unmask_events(ioc, MPI2_EVENT_LOG_ENTRY_ADDED);
3276
3277         ioc->pfacts = kcalloc(ioc->facts.NumberOfPorts,
3278             sizeof(Mpi2PortFactsReply_t), GFP_KERNEL);
3279         if (!ioc->pfacts)
3280                 goto out_free_resources;
3281
3282         for (i = 0 ; i < ioc->facts.NumberOfPorts; i++) {
3283                 r = _base_get_port_facts(ioc, i, CAN_SLEEP);
3284                 if (r)
3285                         goto out_free_resources;
3286         }
3287         r = _base_make_ioc_operational(ioc, 0, CAN_SLEEP);
3288         if (r)
3289                 goto out_free_resources;
3290
3291         /* initialize fault polling */
3292         INIT_DELAYED_WORK(&ioc->fault_reset_work, _base_fault_reset_work);
3293         snprintf(ioc->fault_reset_work_q_name,
3294             sizeof(ioc->fault_reset_work_q_name), "poll_%d_status", ioc->id);
3295         ioc->fault_reset_work_q =
3296                 create_singlethread_workqueue(ioc->fault_reset_work_q_name);
3297         if (!ioc->fault_reset_work_q) {
3298                 printk(MPT2SAS_ERR_FMT "%s: failed (line=%d)\n",
3299                     ioc->name, __func__, __LINE__);
3300                         goto out_free_resources;
3301         }
3302         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
3303         if (ioc->fault_reset_work_q)
3304                 queue_delayed_work(ioc->fault_reset_work_q,
3305                     &ioc->fault_reset_work,
3306                     msecs_to_jiffies(FAULT_POLLING_INTERVAL));
3307         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
3308         return 0;
3309
3310  out_free_resources:
3311
3312         ioc->remove_host = 1;
3313         mpt2sas_base_free_resources(ioc);
3314         _base_release_memory_pools(ioc);
3315         kfree(ioc->tm_cmds.reply);
3316         kfree(ioc->transport_cmds.reply);
3317         kfree(ioc->config_cmds.reply);
3318         kfree(ioc->base_cmds.reply);
3319         kfree(ioc->ctl_cmds.reply);
3320         kfree(ioc->pfacts);
3321         ioc->ctl_cmds.reply = NULL;
3322         ioc->base_cmds.reply = NULL;
3323         ioc->tm_cmds.reply = NULL;
3324         ioc->transport_cmds.reply = NULL;
3325         ioc->config_cmds.reply = NULL;
3326         ioc->pfacts = NULL;
3327         return r;
3328 }
3329
3330
3331 /**
3332  * mpt2sas_base_detach - remove controller instance
3333  * @ioc: per adapter object
3334  *
3335  * Return nothing.
3336  */
3337 void
3338 mpt2sas_base_detach(struct MPT2SAS_ADAPTER *ioc)
3339 {
3340         unsigned long    flags;
3341         struct workqueue_struct *wq;
3342
3343         dexitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
3344             __func__));
3345
3346         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
3347         wq = ioc->fault_reset_work_q;
3348         ioc->fault_reset_work_q = NULL;
3349         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
3350         if (!cancel_delayed_work(&ioc->fault_reset_work))
3351                 flush_workqueue(wq);
3352         destroy_workqueue(wq);
3353
3354         mpt2sas_base_free_resources(ioc);
3355         _base_release_memory_pools(ioc);
3356         kfree(ioc->pfacts);
3357         kfree(ioc->ctl_cmds.reply);
3358         kfree(ioc->base_cmds.reply);
3359         kfree(ioc->tm_cmds.reply);
3360         kfree(ioc->transport_cmds.reply);
3361         kfree(ioc->config_cmds.reply);
3362 }
3363
3364 /**
3365  * _base_reset_handler - reset callback handler (for base)
3366  * @ioc: per adapter object
3367  * @reset_phase: phase
3368  *
3369  * The handler for doing any required cleanup or initialization.
3370  *
3371  * The reset phase can be MPT2_IOC_PRE_RESET, MPT2_IOC_AFTER_RESET,
3372  * MPT2_IOC_DONE_RESET
3373  *
3374  * Return nothing.
3375  */
3376 static void
3377 _base_reset_handler(struct MPT2SAS_ADAPTER *ioc, int reset_phase)
3378 {
3379         switch (reset_phase) {
3380         case MPT2_IOC_PRE_RESET:
3381                 dtmprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: "
3382                     "MPT2_IOC_PRE_RESET\n", ioc->name, __func__));
3383                 break;
3384         case MPT2_IOC_AFTER_RESET:
3385                 dtmprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: "
3386                     "MPT2_IOC_AFTER_RESET\n", ioc->name, __func__));
3387                 if (ioc->transport_cmds.status & MPT2_CMD_PENDING) {
3388                         ioc->transport_cmds.status |= MPT2_CMD_RESET;
3389                         mpt2sas_base_free_smid(ioc, ioc->transport_cmds.smid);
3390                         complete(&ioc->transport_cmds.done);
3391                 }
3392                 if (ioc->base_cmds.status & MPT2_CMD_PENDING) {
3393                         ioc->base_cmds.status |= MPT2_CMD_RESET;
3394                         mpt2sas_base_free_smid(ioc, ioc->base_cmds.smid);
3395                         complete(&ioc->base_cmds.done);
3396                 }
3397                 if (ioc->config_cmds.status & MPT2_CMD_PENDING) {
3398                         ioc->config_cmds.status |= MPT2_CMD_RESET;
3399                         mpt2sas_base_free_smid(ioc, ioc->config_cmds.smid);
3400                         complete(&ioc->config_cmds.done);
3401                 }
3402                 break;
3403         case MPT2_IOC_DONE_RESET:
3404                 dtmprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: "
3405                     "MPT2_IOC_DONE_RESET\n", ioc->name, __func__));
3406                 break;
3407         }
3408         mpt2sas_scsih_reset_handler(ioc, reset_phase);
3409         mpt2sas_ctl_reset_handler(ioc, reset_phase);
3410 }
3411
3412 /**
3413  * _wait_for_commands_to_complete - reset controller
3414  * @ioc: Pointer to MPT_ADAPTER structure
3415  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3416  *
3417  * This function waiting(3s) for all pending commands to complete
3418  * prior to putting controller in reset.
3419  */
3420 static void
3421 _wait_for_commands_to_complete(struct MPT2SAS_ADAPTER *ioc, int sleep_flag)
3422 {
3423         u32 ioc_state;
3424         unsigned long flags;
3425         u16 i;
3426
3427         ioc->pending_io_count = 0;
3428         if (sleep_flag != CAN_SLEEP)
3429                 return;
3430
3431         ioc_state = mpt2sas_base_get_iocstate(ioc, 0);
3432         if ((ioc_state & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_OPERATIONAL)
3433                 return;
3434
3435         /* pending command count */
3436         spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3437         for (i = 0; i < ioc->request_depth; i++)
3438                 if (ioc->scsi_lookup[i].cb_idx != 0xFF)
3439                         ioc->pending_io_count++;
3440         spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3441
3442         if (!ioc->pending_io_count)
3443                 return;
3444
3445         /* wait for pending commands to complete */
3446         wait_event_timeout(ioc->reset_wq, ioc->pending_io_count == 0, 3 * HZ);
3447 }
3448
3449 /**
3450  * mpt2sas_base_hard_reset_handler - reset controller
3451  * @ioc: Pointer to MPT_ADAPTER structure
3452  * @sleep_flag: CAN_SLEEP or NO_SLEEP
3453  * @type: FORCE_BIG_HAMMER or SOFT_RESET
3454  *
3455  * Returns 0 for success, non-zero for failure.
3456  */
3457 int
3458 mpt2sas_base_hard_reset_handler(struct MPT2SAS_ADAPTER *ioc, int sleep_flag,
3459     enum reset_type type)
3460 {
3461         int r, i;
3462         unsigned long flags;
3463
3464         dtmprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: enter\n", ioc->name,
3465             __func__));
3466
3467         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
3468         if (ioc->ioc_reset_in_progress) {
3469                 spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
3470                 printk(MPT2SAS_ERR_FMT "%s: busy\n",
3471                     ioc->name, __func__);
3472                 return -EBUSY;
3473         }
3474         ioc->ioc_reset_in_progress = 1;
3475         ioc->shost_recovery = 1;
3476         if (ioc->shost->shost_state == SHOST_RUNNING) {
3477                 /* set back to SHOST_RUNNING in mpt2sas_scsih.c */
3478                 scsi_host_set_state(ioc->shost, SHOST_RECOVERY);
3479                 printk(MPT2SAS_INFO_FMT "putting controller into "
3480                     "SHOST_RECOVERY\n", ioc->name);
3481         }
3482         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
3483
3484         _base_reset_handler(ioc, MPT2_IOC_PRE_RESET);
3485         _wait_for_commands_to_complete(ioc, sleep_flag);
3486         _base_mask_interrupts(ioc);
3487         r = _base_make_ioc_ready(ioc, sleep_flag, type);
3488         if (r)
3489                 goto out;
3490         _base_reset_handler(ioc, MPT2_IOC_AFTER_RESET);
3491         for (i = 0 ; i < ioc->facts.NumberOfPorts; i++)
3492                 r = _base_make_ioc_operational(ioc, ioc->pfacts[i].VF_ID,
3493                     sleep_flag);
3494         if (!r)
3495                 _base_reset_handler(ioc, MPT2_IOC_DONE_RESET);
3496  out:
3497         dtmprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s: %s\n",
3498             ioc->name, __func__, ((r == 0) ? "SUCCESS" : "FAILED")));
3499
3500         spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
3501         ioc->ioc_reset_in_progress = 0;
3502         spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
3503         return r;
3504 }