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