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