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