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-2014  LSI Corporation
7  * Copyright (C) 2013-2014 Avago Technologies
8  *  (mailto: MPT-FusionLinux.pdl@avagotech.com)
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * NO WARRANTY
21  * THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
22  * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
23  * LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
24  * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
25  * solely responsible for determining the appropriateness of using and
26  * distributing the Program and assumes all risks associated with its
27  * exercise of rights under this Agreement, including but not limited to
28  * the risks and costs of program errors, damage to or loss of data,
29  * programs or equipment, and unavailability or interruption of operations.
30 
31  * DISCLAIMER OF LIABILITY
32  * NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
33  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
38  * HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
39 
40  * You should have received a copy of the GNU General Public License
41  * along with this program; if not, write to the Free Software
42  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
43  * USA.
44  */
45 
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/ktime.h>
61 #include <linux/kthread.h>
62 #include <asm/page.h>        /* To get host page size per arch */
63 #include <linux/aer.h>
64 
65 
66 #include "mpt3sas_base.h"
67 
68 static MPT_CALLBACK	mpt_callbacks[MPT_MAX_CALLBACKS];
69 
70 
71 #define FAULT_POLLING_INTERVAL 1000 /* in milliseconds */
72 
73  /* maximum controller queue depth */
74 #define MAX_HBA_QUEUE_DEPTH	30000
75 #define MAX_CHAIN_DEPTH		100000
76 static int max_queue_depth = -1;
77 module_param(max_queue_depth, int, 0);
78 MODULE_PARM_DESC(max_queue_depth, " max controller queue depth ");
79 
80 static int max_sgl_entries = -1;
81 module_param(max_sgl_entries, int, 0);
82 MODULE_PARM_DESC(max_sgl_entries, " max sg entries ");
83 
84 static int msix_disable = -1;
85 module_param(msix_disable, int, 0);
86 MODULE_PARM_DESC(msix_disable, " disable msix routed interrupts (default=0)");
87 
88 static int smp_affinity_enable = 1;
89 module_param(smp_affinity_enable, int, S_IRUGO);
90 MODULE_PARM_DESC(smp_affinity_enable, "SMP affinity feature enable/disable Default: enable(1)");
91 
92 static int max_msix_vectors = -1;
93 module_param(max_msix_vectors, int, 0);
94 MODULE_PARM_DESC(max_msix_vectors,
95 	" max msix vectors");
96 
97 static int mpt3sas_fwfault_debug;
98 MODULE_PARM_DESC(mpt3sas_fwfault_debug,
99 	" enable detection of firmware fault and halt firmware - (default=0)");
100 
101 static int
102 _base_get_ioc_facts(struct MPT3SAS_ADAPTER *ioc);
103 
104 /**
105  * mpt3sas_base_check_cmd_timeout - Function
106  *		to check timeout and command termination due
107  *		to Host reset.
108  *
109  * @ioc:	per adapter object.
110  * @status:	Status of issued command.
111  * @mpi_request:mf request pointer.
112  * @sz:		size of buffer.
113  *
114  * @Returns - 1/0 Reset to be done or Not
115  */
116 u8
117 mpt3sas_base_check_cmd_timeout(struct MPT3SAS_ADAPTER *ioc,
118 		u8 status, void *mpi_request, int sz)
119 {
120 	u8 issue_reset = 0;
121 
122 	if (!(status & MPT3_CMD_RESET))
123 		issue_reset = 1;
124 
125 	ioc_err(ioc, "Command %s\n",
126 		issue_reset == 0 ? "terminated due to Host Reset" : "Timeout");
127 	_debug_dump_mf(mpi_request, sz);
128 
129 	return issue_reset;
130 }
131 
132 /**
133  * _scsih_set_fwfault_debug - global setting of ioc->fwfault_debug.
134  * @val: ?
135  * @kp: ?
136  *
137  * Return: ?
138  */
139 static int
140 _scsih_set_fwfault_debug(const char *val, const struct kernel_param *kp)
141 {
142 	int ret = param_set_int(val, kp);
143 	struct MPT3SAS_ADAPTER *ioc;
144 
145 	if (ret)
146 		return ret;
147 
148 	/* global ioc spinlock to protect controller list on list operations */
149 	pr_info("setting fwfault_debug(%d)\n", mpt3sas_fwfault_debug);
150 	spin_lock(&gioc_lock);
151 	list_for_each_entry(ioc, &mpt3sas_ioc_list, list)
152 		ioc->fwfault_debug = mpt3sas_fwfault_debug;
153 	spin_unlock(&gioc_lock);
154 	return 0;
155 }
156 module_param_call(mpt3sas_fwfault_debug, _scsih_set_fwfault_debug,
157 	param_get_int, &mpt3sas_fwfault_debug, 0644);
158 
159 /**
160  * _base_clone_reply_to_sys_mem - copies reply to reply free iomem
161  *				  in BAR0 space.
162  *
163  * @ioc: per adapter object
164  * @reply: reply message frame(lower 32bit addr)
165  * @index: System request message index.
166  */
167 static void
168 _base_clone_reply_to_sys_mem(struct MPT3SAS_ADAPTER *ioc, u32 reply,
169 		u32 index)
170 {
171 	/*
172 	 * 256 is offset within sys register.
173 	 * 256 offset MPI frame starts. Max MPI frame supported is 32.
174 	 * 32 * 128 = 4K. From here, Clone of reply free for mcpu starts
175 	 */
176 	u16 cmd_credit = ioc->facts.RequestCredit + 1;
177 	void __iomem *reply_free_iomem = (void __iomem *)ioc->chip +
178 			MPI_FRAME_START_OFFSET +
179 			(cmd_credit * ioc->request_sz) + (index * sizeof(u32));
180 
181 	writel(reply, reply_free_iomem);
182 }
183 
184 /**
185  * _base_clone_mpi_to_sys_mem - Writes/copies MPI frames
186  *				to system/BAR0 region.
187  *
188  * @dst_iomem: Pointer to the destination location in BAR0 space.
189  * @src: Pointer to the Source data.
190  * @size: Size of data to be copied.
191  */
192 static void
193 _base_clone_mpi_to_sys_mem(void *dst_iomem, void *src, u32 size)
194 {
195 	int i;
196 	u32 *src_virt_mem = (u32 *)src;
197 
198 	for (i = 0; i < size/4; i++)
199 		writel((u32)src_virt_mem[i],
200 				(void __iomem *)dst_iomem + (i * 4));
201 }
202 
203 /**
204  * _base_clone_to_sys_mem - Writes/copies data to system/BAR0 region
205  *
206  * @dst_iomem: Pointer to the destination location in BAR0 space.
207  * @src: Pointer to the Source data.
208  * @size: Size of data to be copied.
209  */
210 static void
211 _base_clone_to_sys_mem(void __iomem *dst_iomem, void *src, u32 size)
212 {
213 	int i;
214 	u32 *src_virt_mem = (u32 *)(src);
215 
216 	for (i = 0; i < size/4; i++)
217 		writel((u32)src_virt_mem[i],
218 			(void __iomem *)dst_iomem + (i * 4));
219 }
220 
221 /**
222  * _base_get_chain - Calculates and Returns virtual chain address
223  *			 for the provided smid in BAR0 space.
224  *
225  * @ioc: per adapter object
226  * @smid: system request message index
227  * @sge_chain_count: Scatter gather chain count.
228  *
229  * Return: the chain address.
230  */
231 static inline void __iomem*
232 _base_get_chain(struct MPT3SAS_ADAPTER *ioc, u16 smid,
233 		u8 sge_chain_count)
234 {
235 	void __iomem *base_chain, *chain_virt;
236 	u16 cmd_credit = ioc->facts.RequestCredit + 1;
237 
238 	base_chain  = (void __iomem *)ioc->chip + MPI_FRAME_START_OFFSET +
239 		(cmd_credit * ioc->request_sz) +
240 		REPLY_FREE_POOL_SIZE;
241 	chain_virt = base_chain + (smid * ioc->facts.MaxChainDepth *
242 			ioc->request_sz) + (sge_chain_count * ioc->request_sz);
243 	return chain_virt;
244 }
245 
246 /**
247  * _base_get_chain_phys - Calculates and Returns physical address
248  *			in BAR0 for scatter gather chains, for
249  *			the provided smid.
250  *
251  * @ioc: per adapter object
252  * @smid: system request message index
253  * @sge_chain_count: Scatter gather chain count.
254  *
255  * Return: Physical chain address.
256  */
257 static inline phys_addr_t
258 _base_get_chain_phys(struct MPT3SAS_ADAPTER *ioc, u16 smid,
259 		u8 sge_chain_count)
260 {
261 	phys_addr_t base_chain_phys, chain_phys;
262 	u16 cmd_credit = ioc->facts.RequestCredit + 1;
263 
264 	base_chain_phys  = ioc->chip_phys + MPI_FRAME_START_OFFSET +
265 		(cmd_credit * ioc->request_sz) +
266 		REPLY_FREE_POOL_SIZE;
267 	chain_phys = base_chain_phys + (smid * ioc->facts.MaxChainDepth *
268 			ioc->request_sz) + (sge_chain_count * ioc->request_sz);
269 	return chain_phys;
270 }
271 
272 /**
273  * _base_get_buffer_bar0 - Calculates and Returns BAR0 mapped Host
274  *			buffer address for the provided smid.
275  *			(Each smid can have 64K starts from 17024)
276  *
277  * @ioc: per adapter object
278  * @smid: system request message index
279  *
280  * Return: Pointer to buffer location in BAR0.
281  */
282 
283 static void __iomem *
284 _base_get_buffer_bar0(struct MPT3SAS_ADAPTER *ioc, u16 smid)
285 {
286 	u16 cmd_credit = ioc->facts.RequestCredit + 1;
287 	// Added extra 1 to reach end of chain.
288 	void __iomem *chain_end = _base_get_chain(ioc,
289 			cmd_credit + 1,
290 			ioc->facts.MaxChainDepth);
291 	return chain_end + (smid * 64 * 1024);
292 }
293 
294 /**
295  * _base_get_buffer_phys_bar0 - Calculates and Returns BAR0 mapped
296  *		Host buffer Physical address for the provided smid.
297  *		(Each smid can have 64K starts from 17024)
298  *
299  * @ioc: per adapter object
300  * @smid: system request message index
301  *
302  * Return: Pointer to buffer location in BAR0.
303  */
304 static phys_addr_t
305 _base_get_buffer_phys_bar0(struct MPT3SAS_ADAPTER *ioc, u16 smid)
306 {
307 	u16 cmd_credit = ioc->facts.RequestCredit + 1;
308 	phys_addr_t chain_end_phys = _base_get_chain_phys(ioc,
309 			cmd_credit + 1,
310 			ioc->facts.MaxChainDepth);
311 	return chain_end_phys + (smid * 64 * 1024);
312 }
313 
314 /**
315  * _base_get_chain_buffer_dma_to_chain_buffer - Iterates chain
316  *			lookup list and Provides chain_buffer
317  *			address for the matching dma address.
318  *			(Each smid can have 64K starts from 17024)
319  *
320  * @ioc: per adapter object
321  * @chain_buffer_dma: Chain buffer dma address.
322  *
323  * Return: Pointer to chain buffer. Or Null on Failure.
324  */
325 static void *
326 _base_get_chain_buffer_dma_to_chain_buffer(struct MPT3SAS_ADAPTER *ioc,
327 		dma_addr_t chain_buffer_dma)
328 {
329 	u16 index, j;
330 	struct chain_tracker *ct;
331 
332 	for (index = 0; index < ioc->scsiio_depth; index++) {
333 		for (j = 0; j < ioc->chains_needed_per_io; j++) {
334 			ct = &ioc->chain_lookup[index].chains_per_smid[j];
335 			if (ct && ct->chain_buffer_dma == chain_buffer_dma)
336 				return ct->chain_buffer;
337 		}
338 	}
339 	ioc_info(ioc, "Provided chain_buffer_dma address is not in the lookup list\n");
340 	return NULL;
341 }
342 
343 /**
344  * _clone_sg_entries -	MPI EP's scsiio and config requests
345  *			are handled here. Base function for
346  *			double buffering, before submitting
347  *			the requests.
348  *
349  * @ioc: per adapter object.
350  * @mpi_request: mf request pointer.
351  * @smid: system request message index.
352  */
353 static void _clone_sg_entries(struct MPT3SAS_ADAPTER *ioc,
354 		void *mpi_request, u16 smid)
355 {
356 	Mpi2SGESimple32_t *sgel, *sgel_next;
357 	u32  sgl_flags, sge_chain_count = 0;
358 	bool is_write = 0;
359 	u16 i = 0;
360 	void __iomem *buffer_iomem;
361 	phys_addr_t buffer_iomem_phys;
362 	void __iomem *buff_ptr;
363 	phys_addr_t buff_ptr_phys;
364 	void __iomem *dst_chain_addr[MCPU_MAX_CHAINS_PER_IO];
365 	void *src_chain_addr[MCPU_MAX_CHAINS_PER_IO];
366 	phys_addr_t dst_addr_phys;
367 	MPI2RequestHeader_t *request_hdr;
368 	struct scsi_cmnd *scmd;
369 	struct scatterlist *sg_scmd = NULL;
370 	int is_scsiio_req = 0;
371 
372 	request_hdr = (MPI2RequestHeader_t *) mpi_request;
373 
374 	if (request_hdr->Function == MPI2_FUNCTION_SCSI_IO_REQUEST) {
375 		Mpi25SCSIIORequest_t *scsiio_request =
376 			(Mpi25SCSIIORequest_t *)mpi_request;
377 		sgel = (Mpi2SGESimple32_t *) &scsiio_request->SGL;
378 		is_scsiio_req = 1;
379 	} else if (request_hdr->Function == MPI2_FUNCTION_CONFIG) {
380 		Mpi2ConfigRequest_t  *config_req =
381 			(Mpi2ConfigRequest_t *)mpi_request;
382 		sgel = (Mpi2SGESimple32_t *) &config_req->PageBufferSGE;
383 	} else
384 		return;
385 
386 	/* From smid we can get scsi_cmd, once we have sg_scmd,
387 	 * we just need to get sg_virt and sg_next to get virual
388 	 * address associated with sgel->Address.
389 	 */
390 
391 	if (is_scsiio_req) {
392 		/* Get scsi_cmd using smid */
393 		scmd = mpt3sas_scsih_scsi_lookup_get(ioc, smid);
394 		if (scmd == NULL) {
395 			ioc_err(ioc, "scmd is NULL\n");
396 			return;
397 		}
398 
399 		/* Get sg_scmd from scmd provided */
400 		sg_scmd = scsi_sglist(scmd);
401 	}
402 
403 	/*
404 	 * 0 - 255	System register
405 	 * 256 - 4352	MPI Frame. (This is based on maxCredit 32)
406 	 * 4352 - 4864	Reply_free pool (512 byte is reserved
407 	 *		considering maxCredit 32. Reply need extra
408 	 *		room, for mCPU case kept four times of
409 	 *		maxCredit).
410 	 * 4864 - 17152	SGE chain element. (32cmd * 3 chain of
411 	 *		128 byte size = 12288)
412 	 * 17152 - x	Host buffer mapped with smid.
413 	 *		(Each smid can have 64K Max IO.)
414 	 * BAR0+Last 1K MSIX Addr and Data
415 	 * Total size in use 2113664 bytes of 4MB BAR0
416 	 */
417 
418 	buffer_iomem = _base_get_buffer_bar0(ioc, smid);
419 	buffer_iomem_phys = _base_get_buffer_phys_bar0(ioc, smid);
420 
421 	buff_ptr = buffer_iomem;
422 	buff_ptr_phys = buffer_iomem_phys;
423 	WARN_ON(buff_ptr_phys > U32_MAX);
424 
425 	if (le32_to_cpu(sgel->FlagsLength) &
426 			(MPI2_SGE_FLAGS_HOST_TO_IOC << MPI2_SGE_FLAGS_SHIFT))
427 		is_write = 1;
428 
429 	for (i = 0; i < MPT_MIN_PHYS_SEGMENTS + ioc->facts.MaxChainDepth; i++) {
430 
431 		sgl_flags =
432 		    (le32_to_cpu(sgel->FlagsLength) >> MPI2_SGE_FLAGS_SHIFT);
433 
434 		switch (sgl_flags & MPI2_SGE_FLAGS_ELEMENT_MASK) {
435 		case MPI2_SGE_FLAGS_CHAIN_ELEMENT:
436 			/*
437 			 * Helper function which on passing
438 			 * chain_buffer_dma returns chain_buffer. Get
439 			 * the virtual address for sgel->Address
440 			 */
441 			sgel_next =
442 				_base_get_chain_buffer_dma_to_chain_buffer(ioc,
443 						le32_to_cpu(sgel->Address));
444 			if (sgel_next == NULL)
445 				return;
446 			/*
447 			 * This is coping 128 byte chain
448 			 * frame (not a host buffer)
449 			 */
450 			dst_chain_addr[sge_chain_count] =
451 				_base_get_chain(ioc,
452 					smid, sge_chain_count);
453 			src_chain_addr[sge_chain_count] =
454 						(void *) sgel_next;
455 			dst_addr_phys = _base_get_chain_phys(ioc,
456 						smid, sge_chain_count);
457 			WARN_ON(dst_addr_phys > U32_MAX);
458 			sgel->Address =
459 				cpu_to_le32(lower_32_bits(dst_addr_phys));
460 			sgel = sgel_next;
461 			sge_chain_count++;
462 			break;
463 		case MPI2_SGE_FLAGS_SIMPLE_ELEMENT:
464 			if (is_write) {
465 				if (is_scsiio_req) {
466 					_base_clone_to_sys_mem(buff_ptr,
467 					    sg_virt(sg_scmd),
468 					    (le32_to_cpu(sgel->FlagsLength) &
469 					    0x00ffffff));
470 					/*
471 					 * FIXME: this relies on a a zero
472 					 * PCI mem_offset.
473 					 */
474 					sgel->Address =
475 					    cpu_to_le32((u32)buff_ptr_phys);
476 				} else {
477 					_base_clone_to_sys_mem(buff_ptr,
478 					    ioc->config_vaddr,
479 					    (le32_to_cpu(sgel->FlagsLength) &
480 					    0x00ffffff));
481 					sgel->Address =
482 					    cpu_to_le32((u32)buff_ptr_phys);
483 				}
484 			}
485 			buff_ptr += (le32_to_cpu(sgel->FlagsLength) &
486 			    0x00ffffff);
487 			buff_ptr_phys += (le32_to_cpu(sgel->FlagsLength) &
488 			    0x00ffffff);
489 			if ((le32_to_cpu(sgel->FlagsLength) &
490 			    (MPI2_SGE_FLAGS_END_OF_BUFFER
491 					<< MPI2_SGE_FLAGS_SHIFT)))
492 				goto eob_clone_chain;
493 			else {
494 				/*
495 				 * Every single element in MPT will have
496 				 * associated sg_next. Better to sanity that
497 				 * sg_next is not NULL, but it will be a bug
498 				 * if it is null.
499 				 */
500 				if (is_scsiio_req) {
501 					sg_scmd = sg_next(sg_scmd);
502 					if (sg_scmd)
503 						sgel++;
504 					else
505 						goto eob_clone_chain;
506 				}
507 			}
508 			break;
509 		}
510 	}
511 
512 eob_clone_chain:
513 	for (i = 0; i < sge_chain_count; i++) {
514 		if (is_scsiio_req)
515 			_base_clone_to_sys_mem(dst_chain_addr[i],
516 				src_chain_addr[i], ioc->request_sz);
517 	}
518 }
519 
520 /**
521  *  mpt3sas_remove_dead_ioc_func - kthread context to remove dead ioc
522  * @arg: input argument, used to derive ioc
523  *
524  * Return:
525  * 0 if controller is removed from pci subsystem.
526  * -1 for other case.
527  */
528 static int mpt3sas_remove_dead_ioc_func(void *arg)
529 {
530 	struct MPT3SAS_ADAPTER *ioc = (struct MPT3SAS_ADAPTER *)arg;
531 	struct pci_dev *pdev;
532 
533 	if (!ioc)
534 		return -1;
535 
536 	pdev = ioc->pdev;
537 	if (!pdev)
538 		return -1;
539 	pci_stop_and_remove_bus_device_locked(pdev);
540 	return 0;
541 }
542 
543 /**
544  * _base_fault_reset_work - workq handling ioc fault conditions
545  * @work: input argument, used to derive ioc
546  *
547  * Context: sleep.
548  */
549 static void
550 _base_fault_reset_work(struct work_struct *work)
551 {
552 	struct MPT3SAS_ADAPTER *ioc =
553 	    container_of(work, struct MPT3SAS_ADAPTER, fault_reset_work.work);
554 	unsigned long	 flags;
555 	u32 doorbell;
556 	int rc;
557 	struct task_struct *p;
558 
559 
560 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
561 	if (ioc->shost_recovery || ioc->pci_error_recovery)
562 		goto rearm_timer;
563 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
564 
565 	doorbell = mpt3sas_base_get_iocstate(ioc, 0);
566 	if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_MASK) {
567 		ioc_err(ioc, "SAS host is non-operational !!!!\n");
568 
569 		/* It may be possible that EEH recovery can resolve some of
570 		 * pci bus failure issues rather removing the dead ioc function
571 		 * by considering controller is in a non-operational state. So
572 		 * here priority is given to the EEH recovery. If it doesn't
573 		 * not resolve this issue, mpt3sas driver will consider this
574 		 * controller to non-operational state and remove the dead ioc
575 		 * function.
576 		 */
577 		if (ioc->non_operational_loop++ < 5) {
578 			spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock,
579 							 flags);
580 			goto rearm_timer;
581 		}
582 
583 		/*
584 		 * Call _scsih_flush_pending_cmds callback so that we flush all
585 		 * pending commands back to OS. This call is required to aovid
586 		 * deadlock at block layer. Dead IOC will fail to do diag reset,
587 		 * and this call is safe since dead ioc will never return any
588 		 * command back from HW.
589 		 */
590 		ioc->schedule_dead_ioc_flush_running_cmds(ioc);
591 		/*
592 		 * Set remove_host flag early since kernel thread will
593 		 * take some time to execute.
594 		 */
595 		ioc->remove_host = 1;
596 		/*Remove the Dead Host */
597 		p = kthread_run(mpt3sas_remove_dead_ioc_func, ioc,
598 		    "%s_dead_ioc_%d", ioc->driver_name, ioc->id);
599 		if (IS_ERR(p))
600 			ioc_err(ioc, "%s: Running mpt3sas_dead_ioc thread failed !!!!\n",
601 				__func__);
602 		else
603 			ioc_err(ioc, "%s: Running mpt3sas_dead_ioc thread success !!!!\n",
604 				__func__);
605 		return; /* don't rearm timer */
606 	}
607 
608 	ioc->non_operational_loop = 0;
609 
610 	if ((doorbell & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_OPERATIONAL) {
611 		rc = mpt3sas_base_hard_reset_handler(ioc, FORCE_BIG_HAMMER);
612 		ioc_warn(ioc, "%s: hard reset: %s\n",
613 			 __func__, rc == 0 ? "success" : "failed");
614 		doorbell = mpt3sas_base_get_iocstate(ioc, 0);
615 		if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT)
616 			mpt3sas_base_fault_info(ioc, doorbell &
617 			    MPI2_DOORBELL_DATA_MASK);
618 		if (rc && (doorbell & MPI2_IOC_STATE_MASK) !=
619 		    MPI2_IOC_STATE_OPERATIONAL)
620 			return; /* don't rearm timer */
621 	}
622 
623 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
624  rearm_timer:
625 	if (ioc->fault_reset_work_q)
626 		queue_delayed_work(ioc->fault_reset_work_q,
627 		    &ioc->fault_reset_work,
628 		    msecs_to_jiffies(FAULT_POLLING_INTERVAL));
629 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
630 }
631 
632 /**
633  * mpt3sas_base_start_watchdog - start the fault_reset_work_q
634  * @ioc: per adapter object
635  *
636  * Context: sleep.
637  */
638 void
639 mpt3sas_base_start_watchdog(struct MPT3SAS_ADAPTER *ioc)
640 {
641 	unsigned long	 flags;
642 
643 	if (ioc->fault_reset_work_q)
644 		return;
645 
646 	/* initialize fault polling */
647 
648 	INIT_DELAYED_WORK(&ioc->fault_reset_work, _base_fault_reset_work);
649 	snprintf(ioc->fault_reset_work_q_name,
650 	    sizeof(ioc->fault_reset_work_q_name), "poll_%s%d_status",
651 	    ioc->driver_name, ioc->id);
652 	ioc->fault_reset_work_q =
653 		create_singlethread_workqueue(ioc->fault_reset_work_q_name);
654 	if (!ioc->fault_reset_work_q) {
655 		ioc_err(ioc, "%s: failed (line=%d)\n", __func__, __LINE__);
656 		return;
657 	}
658 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
659 	if (ioc->fault_reset_work_q)
660 		queue_delayed_work(ioc->fault_reset_work_q,
661 		    &ioc->fault_reset_work,
662 		    msecs_to_jiffies(FAULT_POLLING_INTERVAL));
663 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
664 }
665 
666 /**
667  * mpt3sas_base_stop_watchdog - stop the fault_reset_work_q
668  * @ioc: per adapter object
669  *
670  * Context: sleep.
671  */
672 void
673 mpt3sas_base_stop_watchdog(struct MPT3SAS_ADAPTER *ioc)
674 {
675 	unsigned long flags;
676 	struct workqueue_struct *wq;
677 
678 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
679 	wq = ioc->fault_reset_work_q;
680 	ioc->fault_reset_work_q = NULL;
681 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
682 	if (wq) {
683 		if (!cancel_delayed_work_sync(&ioc->fault_reset_work))
684 			flush_workqueue(wq);
685 		destroy_workqueue(wq);
686 	}
687 }
688 
689 /**
690  * mpt3sas_base_fault_info - verbose translation of firmware FAULT code
691  * @ioc: per adapter object
692  * @fault_code: fault code
693  */
694 void
695 mpt3sas_base_fault_info(struct MPT3SAS_ADAPTER *ioc , u16 fault_code)
696 {
697 	ioc_err(ioc, "fault_state(0x%04x)!\n", fault_code);
698 }
699 
700 /**
701  * mpt3sas_halt_firmware - halt's mpt controller firmware
702  * @ioc: per adapter object
703  *
704  * For debugging timeout related issues.  Writing 0xCOFFEE00
705  * to the doorbell register will halt controller firmware. With
706  * the purpose to stop both driver and firmware, the enduser can
707  * obtain a ring buffer from controller UART.
708  */
709 void
710 mpt3sas_halt_firmware(struct MPT3SAS_ADAPTER *ioc)
711 {
712 	u32 doorbell;
713 
714 	if (!ioc->fwfault_debug)
715 		return;
716 
717 	dump_stack();
718 
719 	doorbell = readl(&ioc->chip->Doorbell);
720 	if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT)
721 		mpt3sas_base_fault_info(ioc , doorbell);
722 	else {
723 		writel(0xC0FFEE00, &ioc->chip->Doorbell);
724 		ioc_err(ioc, "Firmware is halted due to command timeout\n");
725 	}
726 
727 	if (ioc->fwfault_debug == 2)
728 		for (;;)
729 			;
730 	else
731 		panic("panic in %s\n", __func__);
732 }
733 
734 /**
735  * _base_sas_ioc_info - verbose translation of the ioc status
736  * @ioc: per adapter object
737  * @mpi_reply: reply mf payload returned from firmware
738  * @request_hdr: request mf
739  */
740 static void
741 _base_sas_ioc_info(struct MPT3SAS_ADAPTER *ioc, MPI2DefaultReply_t *mpi_reply,
742 	MPI2RequestHeader_t *request_hdr)
743 {
744 	u16 ioc_status = le16_to_cpu(mpi_reply->IOCStatus) &
745 	    MPI2_IOCSTATUS_MASK;
746 	char *desc = NULL;
747 	u16 frame_sz;
748 	char *func_str = NULL;
749 
750 	/* SCSI_IO, RAID_PASS are handled from _scsih_scsi_ioc_info */
751 	if (request_hdr->Function == MPI2_FUNCTION_SCSI_IO_REQUEST ||
752 	    request_hdr->Function == MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH ||
753 	    request_hdr->Function == MPI2_FUNCTION_EVENT_NOTIFICATION)
754 		return;
755 
756 	if (ioc_status == MPI2_IOCSTATUS_CONFIG_INVALID_PAGE)
757 		return;
758 
759 	switch (ioc_status) {
760 
761 /****************************************************************************
762 *  Common IOCStatus values for all replies
763 ****************************************************************************/
764 
765 	case MPI2_IOCSTATUS_INVALID_FUNCTION:
766 		desc = "invalid function";
767 		break;
768 	case MPI2_IOCSTATUS_BUSY:
769 		desc = "busy";
770 		break;
771 	case MPI2_IOCSTATUS_INVALID_SGL:
772 		desc = "invalid sgl";
773 		break;
774 	case MPI2_IOCSTATUS_INTERNAL_ERROR:
775 		desc = "internal error";
776 		break;
777 	case MPI2_IOCSTATUS_INVALID_VPID:
778 		desc = "invalid vpid";
779 		break;
780 	case MPI2_IOCSTATUS_INSUFFICIENT_RESOURCES:
781 		desc = "insufficient resources";
782 		break;
783 	case MPI2_IOCSTATUS_INSUFFICIENT_POWER:
784 		desc = "insufficient power";
785 		break;
786 	case MPI2_IOCSTATUS_INVALID_FIELD:
787 		desc = "invalid field";
788 		break;
789 	case MPI2_IOCSTATUS_INVALID_STATE:
790 		desc = "invalid state";
791 		break;
792 	case MPI2_IOCSTATUS_OP_STATE_NOT_SUPPORTED:
793 		desc = "op state not supported";
794 		break;
795 
796 /****************************************************************************
797 *  Config IOCStatus values
798 ****************************************************************************/
799 
800 	case MPI2_IOCSTATUS_CONFIG_INVALID_ACTION:
801 		desc = "config invalid action";
802 		break;
803 	case MPI2_IOCSTATUS_CONFIG_INVALID_TYPE:
804 		desc = "config invalid type";
805 		break;
806 	case MPI2_IOCSTATUS_CONFIG_INVALID_PAGE:
807 		desc = "config invalid page";
808 		break;
809 	case MPI2_IOCSTATUS_CONFIG_INVALID_DATA:
810 		desc = "config invalid data";
811 		break;
812 	case MPI2_IOCSTATUS_CONFIG_NO_DEFAULTS:
813 		desc = "config no defaults";
814 		break;
815 	case MPI2_IOCSTATUS_CONFIG_CANT_COMMIT:
816 		desc = "config cant commit";
817 		break;
818 
819 /****************************************************************************
820 *  SCSI IO Reply
821 ****************************************************************************/
822 
823 	case MPI2_IOCSTATUS_SCSI_RECOVERED_ERROR:
824 	case MPI2_IOCSTATUS_SCSI_INVALID_DEVHANDLE:
825 	case MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
826 	case MPI2_IOCSTATUS_SCSI_DATA_OVERRUN:
827 	case MPI2_IOCSTATUS_SCSI_DATA_UNDERRUN:
828 	case MPI2_IOCSTATUS_SCSI_IO_DATA_ERROR:
829 	case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
830 	case MPI2_IOCSTATUS_SCSI_TASK_TERMINATED:
831 	case MPI2_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
832 	case MPI2_IOCSTATUS_SCSI_TASK_MGMT_FAILED:
833 	case MPI2_IOCSTATUS_SCSI_IOC_TERMINATED:
834 	case MPI2_IOCSTATUS_SCSI_EXT_TERMINATED:
835 		break;
836 
837 /****************************************************************************
838 *  For use by SCSI Initiator and SCSI Target end-to-end data protection
839 ****************************************************************************/
840 
841 	case MPI2_IOCSTATUS_EEDP_GUARD_ERROR:
842 		desc = "eedp guard error";
843 		break;
844 	case MPI2_IOCSTATUS_EEDP_REF_TAG_ERROR:
845 		desc = "eedp ref tag error";
846 		break;
847 	case MPI2_IOCSTATUS_EEDP_APP_TAG_ERROR:
848 		desc = "eedp app tag error";
849 		break;
850 
851 /****************************************************************************
852 *  SCSI Target values
853 ****************************************************************************/
854 
855 	case MPI2_IOCSTATUS_TARGET_INVALID_IO_INDEX:
856 		desc = "target invalid io index";
857 		break;
858 	case MPI2_IOCSTATUS_TARGET_ABORTED:
859 		desc = "target aborted";
860 		break;
861 	case MPI2_IOCSTATUS_TARGET_NO_CONN_RETRYABLE:
862 		desc = "target no conn retryable";
863 		break;
864 	case MPI2_IOCSTATUS_TARGET_NO_CONNECTION:
865 		desc = "target no connection";
866 		break;
867 	case MPI2_IOCSTATUS_TARGET_XFER_COUNT_MISMATCH:
868 		desc = "target xfer count mismatch";
869 		break;
870 	case MPI2_IOCSTATUS_TARGET_DATA_OFFSET_ERROR:
871 		desc = "target data offset error";
872 		break;
873 	case MPI2_IOCSTATUS_TARGET_TOO_MUCH_WRITE_DATA:
874 		desc = "target too much write data";
875 		break;
876 	case MPI2_IOCSTATUS_TARGET_IU_TOO_SHORT:
877 		desc = "target iu too short";
878 		break;
879 	case MPI2_IOCSTATUS_TARGET_ACK_NAK_TIMEOUT:
880 		desc = "target ack nak timeout";
881 		break;
882 	case MPI2_IOCSTATUS_TARGET_NAK_RECEIVED:
883 		desc = "target nak received";
884 		break;
885 
886 /****************************************************************************
887 *  Serial Attached SCSI values
888 ****************************************************************************/
889 
890 	case MPI2_IOCSTATUS_SAS_SMP_REQUEST_FAILED:
891 		desc = "smp request failed";
892 		break;
893 	case MPI2_IOCSTATUS_SAS_SMP_DATA_OVERRUN:
894 		desc = "smp data overrun";
895 		break;
896 
897 /****************************************************************************
898 *  Diagnostic Buffer Post / Diagnostic Release values
899 ****************************************************************************/
900 
901 	case MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED:
902 		desc = "diagnostic released";
903 		break;
904 	default:
905 		break;
906 	}
907 
908 	if (!desc)
909 		return;
910 
911 	switch (request_hdr->Function) {
912 	case MPI2_FUNCTION_CONFIG:
913 		frame_sz = sizeof(Mpi2ConfigRequest_t) + ioc->sge_size;
914 		func_str = "config_page";
915 		break;
916 	case MPI2_FUNCTION_SCSI_TASK_MGMT:
917 		frame_sz = sizeof(Mpi2SCSITaskManagementRequest_t);
918 		func_str = "task_mgmt";
919 		break;
920 	case MPI2_FUNCTION_SAS_IO_UNIT_CONTROL:
921 		frame_sz = sizeof(Mpi2SasIoUnitControlRequest_t);
922 		func_str = "sas_iounit_ctl";
923 		break;
924 	case MPI2_FUNCTION_SCSI_ENCLOSURE_PROCESSOR:
925 		frame_sz = sizeof(Mpi2SepRequest_t);
926 		func_str = "enclosure";
927 		break;
928 	case MPI2_FUNCTION_IOC_INIT:
929 		frame_sz = sizeof(Mpi2IOCInitRequest_t);
930 		func_str = "ioc_init";
931 		break;
932 	case MPI2_FUNCTION_PORT_ENABLE:
933 		frame_sz = sizeof(Mpi2PortEnableRequest_t);
934 		func_str = "port_enable";
935 		break;
936 	case MPI2_FUNCTION_SMP_PASSTHROUGH:
937 		frame_sz = sizeof(Mpi2SmpPassthroughRequest_t) + ioc->sge_size;
938 		func_str = "smp_passthru";
939 		break;
940 	case MPI2_FUNCTION_NVME_ENCAPSULATED:
941 		frame_sz = sizeof(Mpi26NVMeEncapsulatedRequest_t) +
942 		    ioc->sge_size;
943 		func_str = "nvme_encapsulated";
944 		break;
945 	default:
946 		frame_sz = 32;
947 		func_str = "unknown";
948 		break;
949 	}
950 
951 	ioc_warn(ioc, "ioc_status: %s(0x%04x), request(0x%p),(%s)\n",
952 		 desc, ioc_status, request_hdr, func_str);
953 
954 	_debug_dump_mf(request_hdr, frame_sz/4);
955 }
956 
957 /**
958  * _base_display_event_data - verbose translation of firmware asyn events
959  * @ioc: per adapter object
960  * @mpi_reply: reply mf payload returned from firmware
961  */
962 static void
963 _base_display_event_data(struct MPT3SAS_ADAPTER *ioc,
964 	Mpi2EventNotificationReply_t *mpi_reply)
965 {
966 	char *desc = NULL;
967 	u16 event;
968 
969 	if (!(ioc->logging_level & MPT_DEBUG_EVENTS))
970 		return;
971 
972 	event = le16_to_cpu(mpi_reply->Event);
973 
974 	switch (event) {
975 	case MPI2_EVENT_LOG_DATA:
976 		desc = "Log Data";
977 		break;
978 	case MPI2_EVENT_STATE_CHANGE:
979 		desc = "Status Change";
980 		break;
981 	case MPI2_EVENT_HARD_RESET_RECEIVED:
982 		desc = "Hard Reset Received";
983 		break;
984 	case MPI2_EVENT_EVENT_CHANGE:
985 		desc = "Event Change";
986 		break;
987 	case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
988 		desc = "Device Status Change";
989 		break;
990 	case MPI2_EVENT_IR_OPERATION_STATUS:
991 		if (!ioc->hide_ir_msg)
992 			desc = "IR Operation Status";
993 		break;
994 	case MPI2_EVENT_SAS_DISCOVERY:
995 	{
996 		Mpi2EventDataSasDiscovery_t *event_data =
997 		    (Mpi2EventDataSasDiscovery_t *)mpi_reply->EventData;
998 		ioc_info(ioc, "Discovery: (%s)",
999 			 event_data->ReasonCode == MPI2_EVENT_SAS_DISC_RC_STARTED ?
1000 			 "start" : "stop");
1001 		if (event_data->DiscoveryStatus)
1002 			pr_cont(" discovery_status(0x%08x)",
1003 			    le32_to_cpu(event_data->DiscoveryStatus));
1004 		pr_cont("\n");
1005 		return;
1006 	}
1007 	case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
1008 		desc = "SAS Broadcast Primitive";
1009 		break;
1010 	case MPI2_EVENT_SAS_INIT_DEVICE_STATUS_CHANGE:
1011 		desc = "SAS Init Device Status Change";
1012 		break;
1013 	case MPI2_EVENT_SAS_INIT_TABLE_OVERFLOW:
1014 		desc = "SAS Init Table Overflow";
1015 		break;
1016 	case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
1017 		desc = "SAS Topology Change List";
1018 		break;
1019 	case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
1020 		desc = "SAS Enclosure Device Status Change";
1021 		break;
1022 	case MPI2_EVENT_IR_VOLUME:
1023 		if (!ioc->hide_ir_msg)
1024 			desc = "IR Volume";
1025 		break;
1026 	case MPI2_EVENT_IR_PHYSICAL_DISK:
1027 		if (!ioc->hide_ir_msg)
1028 			desc = "IR Physical Disk";
1029 		break;
1030 	case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
1031 		if (!ioc->hide_ir_msg)
1032 			desc = "IR Configuration Change List";
1033 		break;
1034 	case MPI2_EVENT_LOG_ENTRY_ADDED:
1035 		if (!ioc->hide_ir_msg)
1036 			desc = "Log Entry Added";
1037 		break;
1038 	case MPI2_EVENT_TEMP_THRESHOLD:
1039 		desc = "Temperature Threshold";
1040 		break;
1041 	case MPI2_EVENT_ACTIVE_CABLE_EXCEPTION:
1042 		desc = "Cable Event";
1043 		break;
1044 	case MPI2_EVENT_SAS_DEVICE_DISCOVERY_ERROR:
1045 		desc = "SAS Device Discovery Error";
1046 		break;
1047 	case MPI2_EVENT_PCIE_DEVICE_STATUS_CHANGE:
1048 		desc = "PCIE Device Status Change";
1049 		break;
1050 	case MPI2_EVENT_PCIE_ENUMERATION:
1051 	{
1052 		Mpi26EventDataPCIeEnumeration_t *event_data =
1053 			(Mpi26EventDataPCIeEnumeration_t *)mpi_reply->EventData;
1054 		ioc_info(ioc, "PCIE Enumeration: (%s)",
1055 			 event_data->ReasonCode == MPI26_EVENT_PCIE_ENUM_RC_STARTED ?
1056 			 "start" : "stop");
1057 		if (event_data->EnumerationStatus)
1058 			pr_cont("enumeration_status(0x%08x)",
1059 				le32_to_cpu(event_data->EnumerationStatus));
1060 		pr_cont("\n");
1061 		return;
1062 	}
1063 	case MPI2_EVENT_PCIE_TOPOLOGY_CHANGE_LIST:
1064 		desc = "PCIE Topology Change List";
1065 		break;
1066 	}
1067 
1068 	if (!desc)
1069 		return;
1070 
1071 	ioc_info(ioc, "%s\n", desc);
1072 }
1073 
1074 /**
1075  * _base_sas_log_info - verbose translation of firmware log info
1076  * @ioc: per adapter object
1077  * @log_info: log info
1078  */
1079 static void
1080 _base_sas_log_info(struct MPT3SAS_ADAPTER *ioc , u32 log_info)
1081 {
1082 	union loginfo_type {
1083 		u32	loginfo;
1084 		struct {
1085 			u32	subcode:16;
1086 			u32	code:8;
1087 			u32	originator:4;
1088 			u32	bus_type:4;
1089 		} dw;
1090 	};
1091 	union loginfo_type sas_loginfo;
1092 	char *originator_str = NULL;
1093 
1094 	sas_loginfo.loginfo = log_info;
1095 	if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
1096 		return;
1097 
1098 	/* each nexus loss loginfo */
1099 	if (log_info == 0x31170000)
1100 		return;
1101 
1102 	/* eat the loginfos associated with task aborts */
1103 	if (ioc->ignore_loginfos && (log_info == 0x30050000 || log_info ==
1104 	    0x31140000 || log_info == 0x31130000))
1105 		return;
1106 
1107 	switch (sas_loginfo.dw.originator) {
1108 	case 0:
1109 		originator_str = "IOP";
1110 		break;
1111 	case 1:
1112 		originator_str = "PL";
1113 		break;
1114 	case 2:
1115 		if (!ioc->hide_ir_msg)
1116 			originator_str = "IR";
1117 		else
1118 			originator_str = "WarpDrive";
1119 		break;
1120 	}
1121 
1122 	ioc_warn(ioc, "log_info(0x%08x): originator(%s), code(0x%02x), sub_code(0x%04x)\n",
1123 		 log_info,
1124 		 originator_str, sas_loginfo.dw.code, sas_loginfo.dw.subcode);
1125 }
1126 
1127 /**
1128  * _base_display_reply_info -
1129  * @ioc: per adapter object
1130  * @smid: system request message index
1131  * @msix_index: MSIX table index supplied by the OS
1132  * @reply: reply message frame(lower 32bit addr)
1133  */
1134 static void
1135 _base_display_reply_info(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
1136 	u32 reply)
1137 {
1138 	MPI2DefaultReply_t *mpi_reply;
1139 	u16 ioc_status;
1140 	u32 loginfo = 0;
1141 
1142 	mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
1143 	if (unlikely(!mpi_reply)) {
1144 		ioc_err(ioc, "mpi_reply not valid at %s:%d/%s()!\n",
1145 			__FILE__, __LINE__, __func__);
1146 		return;
1147 	}
1148 	ioc_status = le16_to_cpu(mpi_reply->IOCStatus);
1149 
1150 	if ((ioc_status & MPI2_IOCSTATUS_MASK) &&
1151 	    (ioc->logging_level & MPT_DEBUG_REPLY)) {
1152 		_base_sas_ioc_info(ioc , mpi_reply,
1153 		   mpt3sas_base_get_msg_frame(ioc, smid));
1154 	}
1155 
1156 	if (ioc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
1157 		loginfo = le32_to_cpu(mpi_reply->IOCLogInfo);
1158 		_base_sas_log_info(ioc, loginfo);
1159 	}
1160 
1161 	if (ioc_status || loginfo) {
1162 		ioc_status &= MPI2_IOCSTATUS_MASK;
1163 		mpt3sas_trigger_mpi(ioc, ioc_status, loginfo);
1164 	}
1165 }
1166 
1167 /**
1168  * mpt3sas_base_done - base internal command completion routine
1169  * @ioc: per adapter object
1170  * @smid: system request message index
1171  * @msix_index: MSIX table index supplied by the OS
1172  * @reply: reply message frame(lower 32bit addr)
1173  *
1174  * Return:
1175  * 1 meaning mf should be freed from _base_interrupt
1176  * 0 means the mf is freed from this function.
1177  */
1178 u8
1179 mpt3sas_base_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
1180 	u32 reply)
1181 {
1182 	MPI2DefaultReply_t *mpi_reply;
1183 
1184 	mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
1185 	if (mpi_reply && mpi_reply->Function == MPI2_FUNCTION_EVENT_ACK)
1186 		return mpt3sas_check_for_pending_internal_cmds(ioc, smid);
1187 
1188 	if (ioc->base_cmds.status == MPT3_CMD_NOT_USED)
1189 		return 1;
1190 
1191 	ioc->base_cmds.status |= MPT3_CMD_COMPLETE;
1192 	if (mpi_reply) {
1193 		ioc->base_cmds.status |= MPT3_CMD_REPLY_VALID;
1194 		memcpy(ioc->base_cmds.reply, mpi_reply, mpi_reply->MsgLength*4);
1195 	}
1196 	ioc->base_cmds.status &= ~MPT3_CMD_PENDING;
1197 
1198 	complete(&ioc->base_cmds.done);
1199 	return 1;
1200 }
1201 
1202 /**
1203  * _base_async_event - main callback handler for firmware asyn events
1204  * @ioc: per adapter object
1205  * @msix_index: MSIX table index supplied by the OS
1206  * @reply: reply message frame(lower 32bit addr)
1207  *
1208  * Return:
1209  * 1 meaning mf should be freed from _base_interrupt
1210  * 0 means the mf is freed from this function.
1211  */
1212 static u8
1213 _base_async_event(struct MPT3SAS_ADAPTER *ioc, u8 msix_index, u32 reply)
1214 {
1215 	Mpi2EventNotificationReply_t *mpi_reply;
1216 	Mpi2EventAckRequest_t *ack_request;
1217 	u16 smid;
1218 	struct _event_ack_list *delayed_event_ack;
1219 
1220 	mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
1221 	if (!mpi_reply)
1222 		return 1;
1223 	if (mpi_reply->Function != MPI2_FUNCTION_EVENT_NOTIFICATION)
1224 		return 1;
1225 
1226 	_base_display_event_data(ioc, mpi_reply);
1227 
1228 	if (!(mpi_reply->AckRequired & MPI2_EVENT_NOTIFICATION_ACK_REQUIRED))
1229 		goto out;
1230 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
1231 	if (!smid) {
1232 		delayed_event_ack = kzalloc(sizeof(*delayed_event_ack),
1233 					GFP_ATOMIC);
1234 		if (!delayed_event_ack)
1235 			goto out;
1236 		INIT_LIST_HEAD(&delayed_event_ack->list);
1237 		delayed_event_ack->Event = mpi_reply->Event;
1238 		delayed_event_ack->EventContext = mpi_reply->EventContext;
1239 		list_add_tail(&delayed_event_ack->list,
1240 				&ioc->delayed_event_ack_list);
1241 		dewtprintk(ioc,
1242 			   ioc_info(ioc, "DELAYED: EVENT ACK: event (0x%04x)\n",
1243 				    le16_to_cpu(mpi_reply->Event)));
1244 		goto out;
1245 	}
1246 
1247 	ack_request = mpt3sas_base_get_msg_frame(ioc, smid);
1248 	memset(ack_request, 0, sizeof(Mpi2EventAckRequest_t));
1249 	ack_request->Function = MPI2_FUNCTION_EVENT_ACK;
1250 	ack_request->Event = mpi_reply->Event;
1251 	ack_request->EventContext = mpi_reply->EventContext;
1252 	ack_request->VF_ID = 0;  /* TODO */
1253 	ack_request->VP_ID = 0;
1254 	mpt3sas_base_put_smid_default(ioc, smid);
1255 
1256  out:
1257 
1258 	/* scsih callback handler */
1259 	mpt3sas_scsih_event_callback(ioc, msix_index, reply);
1260 
1261 	/* ctl callback handler */
1262 	mpt3sas_ctl_event_callback(ioc, msix_index, reply);
1263 
1264 	return 1;
1265 }
1266 
1267 static struct scsiio_tracker *
1268 _get_st_from_smid(struct MPT3SAS_ADAPTER *ioc, u16 smid)
1269 {
1270 	struct scsi_cmnd *cmd;
1271 
1272 	if (WARN_ON(!smid) ||
1273 	    WARN_ON(smid >= ioc->hi_priority_smid))
1274 		return NULL;
1275 
1276 	cmd = mpt3sas_scsih_scsi_lookup_get(ioc, smid);
1277 	if (cmd)
1278 		return scsi_cmd_priv(cmd);
1279 
1280 	return NULL;
1281 }
1282 
1283 /**
1284  * _base_get_cb_idx - obtain the callback index
1285  * @ioc: per adapter object
1286  * @smid: system request message index
1287  *
1288  * Return: callback index.
1289  */
1290 static u8
1291 _base_get_cb_idx(struct MPT3SAS_ADAPTER *ioc, u16 smid)
1292 {
1293 	int i;
1294 	u16 ctl_smid = ioc->scsiio_depth - INTERNAL_SCSIIO_CMDS_COUNT + 1;
1295 	u8 cb_idx = 0xFF;
1296 
1297 	if (smid < ioc->hi_priority_smid) {
1298 		struct scsiio_tracker *st;
1299 
1300 		if (smid < ctl_smid) {
1301 			st = _get_st_from_smid(ioc, smid);
1302 			if (st)
1303 				cb_idx = st->cb_idx;
1304 		} else if (smid == ctl_smid)
1305 			cb_idx = ioc->ctl_cb_idx;
1306 	} else if (smid < ioc->internal_smid) {
1307 		i = smid - ioc->hi_priority_smid;
1308 		cb_idx = ioc->hpr_lookup[i].cb_idx;
1309 	} else if (smid <= ioc->hba_queue_depth) {
1310 		i = smid - ioc->internal_smid;
1311 		cb_idx = ioc->internal_lookup[i].cb_idx;
1312 	}
1313 	return cb_idx;
1314 }
1315 
1316 /**
1317  * _base_mask_interrupts - disable interrupts
1318  * @ioc: per adapter object
1319  *
1320  * Disabling ResetIRQ, Reply and Doorbell Interrupts
1321  */
1322 static void
1323 _base_mask_interrupts(struct MPT3SAS_ADAPTER *ioc)
1324 {
1325 	u32 him_register;
1326 
1327 	ioc->mask_interrupts = 1;
1328 	him_register = readl(&ioc->chip->HostInterruptMask);
1329 	him_register |= MPI2_HIM_DIM + MPI2_HIM_RIM + MPI2_HIM_RESET_IRQ_MASK;
1330 	writel(him_register, &ioc->chip->HostInterruptMask);
1331 	readl(&ioc->chip->HostInterruptMask);
1332 }
1333 
1334 /**
1335  * _base_unmask_interrupts - enable interrupts
1336  * @ioc: per adapter object
1337  *
1338  * Enabling only Reply Interrupts
1339  */
1340 static void
1341 _base_unmask_interrupts(struct MPT3SAS_ADAPTER *ioc)
1342 {
1343 	u32 him_register;
1344 
1345 	him_register = readl(&ioc->chip->HostInterruptMask);
1346 	him_register &= ~MPI2_HIM_RIM;
1347 	writel(him_register, &ioc->chip->HostInterruptMask);
1348 	ioc->mask_interrupts = 0;
1349 }
1350 
1351 union reply_descriptor {
1352 	u64 word;
1353 	struct {
1354 		u32 low;
1355 		u32 high;
1356 	} u;
1357 };
1358 
1359 /**
1360  * _base_interrupt - MPT adapter (IOC) specific interrupt handler.
1361  * @irq: irq number (not used)
1362  * @bus_id: bus identifier cookie == pointer to MPT_ADAPTER structure
1363  *
1364  * Return: IRQ_HANDLED if processed, else IRQ_NONE.
1365  */
1366 static irqreturn_t
1367 _base_interrupt(int irq, void *bus_id)
1368 {
1369 	struct adapter_reply_queue *reply_q = bus_id;
1370 	union reply_descriptor rd;
1371 	u32 completed_cmds;
1372 	u8 request_desript_type;
1373 	u16 smid;
1374 	u8 cb_idx;
1375 	u32 reply;
1376 	u8 msix_index = reply_q->msix_index;
1377 	struct MPT3SAS_ADAPTER *ioc = reply_q->ioc;
1378 	Mpi2ReplyDescriptorsUnion_t *rpf;
1379 	u8 rc;
1380 
1381 	if (ioc->mask_interrupts)
1382 		return IRQ_NONE;
1383 
1384 	if (!atomic_add_unless(&reply_q->busy, 1, 1))
1385 		return IRQ_NONE;
1386 
1387 	rpf = &reply_q->reply_post_free[reply_q->reply_post_host_index];
1388 	request_desript_type = rpf->Default.ReplyFlags
1389 	     & MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
1390 	if (request_desript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED) {
1391 		atomic_dec(&reply_q->busy);
1392 		return IRQ_NONE;
1393 	}
1394 
1395 	completed_cmds = 0;
1396 	cb_idx = 0xFF;
1397 	do {
1398 		rd.word = le64_to_cpu(rpf->Words);
1399 		if (rd.u.low == UINT_MAX || rd.u.high == UINT_MAX)
1400 			goto out;
1401 		reply = 0;
1402 		smid = le16_to_cpu(rpf->Default.DescriptorTypeDependent1);
1403 		if (request_desript_type ==
1404 		    MPI25_RPY_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO_SUCCESS ||
1405 		    request_desript_type ==
1406 		    MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS ||
1407 		    request_desript_type ==
1408 		    MPI26_RPY_DESCRIPT_FLAGS_PCIE_ENCAPSULATED_SUCCESS) {
1409 			cb_idx = _base_get_cb_idx(ioc, smid);
1410 			if ((likely(cb_idx < MPT_MAX_CALLBACKS)) &&
1411 			    (likely(mpt_callbacks[cb_idx] != NULL))) {
1412 				rc = mpt_callbacks[cb_idx](ioc, smid,
1413 				    msix_index, 0);
1414 				if (rc)
1415 					mpt3sas_base_free_smid(ioc, smid);
1416 			}
1417 		} else if (request_desript_type ==
1418 		    MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY) {
1419 			reply = le32_to_cpu(
1420 			    rpf->AddressReply.ReplyFrameAddress);
1421 			if (reply > ioc->reply_dma_max_address ||
1422 			    reply < ioc->reply_dma_min_address)
1423 				reply = 0;
1424 			if (smid) {
1425 				cb_idx = _base_get_cb_idx(ioc, smid);
1426 				if ((likely(cb_idx < MPT_MAX_CALLBACKS)) &&
1427 				    (likely(mpt_callbacks[cb_idx] != NULL))) {
1428 					rc = mpt_callbacks[cb_idx](ioc, smid,
1429 					    msix_index, reply);
1430 					if (reply)
1431 						_base_display_reply_info(ioc,
1432 						    smid, msix_index, reply);
1433 					if (rc)
1434 						mpt3sas_base_free_smid(ioc,
1435 						    smid);
1436 				}
1437 			} else {
1438 				_base_async_event(ioc, msix_index, reply);
1439 			}
1440 
1441 			/* reply free queue handling */
1442 			if (reply) {
1443 				ioc->reply_free_host_index =
1444 				    (ioc->reply_free_host_index ==
1445 				    (ioc->reply_free_queue_depth - 1)) ?
1446 				    0 : ioc->reply_free_host_index + 1;
1447 				ioc->reply_free[ioc->reply_free_host_index] =
1448 				    cpu_to_le32(reply);
1449 				if (ioc->is_mcpu_endpoint)
1450 					_base_clone_reply_to_sys_mem(ioc,
1451 						reply,
1452 						ioc->reply_free_host_index);
1453 				writel(ioc->reply_free_host_index,
1454 				    &ioc->chip->ReplyFreeHostIndex);
1455 			}
1456 		}
1457 
1458 		rpf->Words = cpu_to_le64(ULLONG_MAX);
1459 		reply_q->reply_post_host_index =
1460 		    (reply_q->reply_post_host_index ==
1461 		    (ioc->reply_post_queue_depth - 1)) ? 0 :
1462 		    reply_q->reply_post_host_index + 1;
1463 		request_desript_type =
1464 		    reply_q->reply_post_free[reply_q->reply_post_host_index].
1465 		    Default.ReplyFlags & MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
1466 		completed_cmds++;
1467 		/* Update the reply post host index after continuously
1468 		 * processing the threshold number of Reply Descriptors.
1469 		 * So that FW can find enough entries to post the Reply
1470 		 * Descriptors in the reply descriptor post queue.
1471 		 */
1472 		if (completed_cmds > ioc->hba_queue_depth/3) {
1473 			if (ioc->combined_reply_queue) {
1474 				writel(reply_q->reply_post_host_index |
1475 						((msix_index  & 7) <<
1476 						 MPI2_RPHI_MSIX_INDEX_SHIFT),
1477 				    ioc->replyPostRegisterIndex[msix_index/8]);
1478 			} else {
1479 				writel(reply_q->reply_post_host_index |
1480 						(msix_index <<
1481 						 MPI2_RPHI_MSIX_INDEX_SHIFT),
1482 						&ioc->chip->ReplyPostHostIndex);
1483 			}
1484 			completed_cmds = 1;
1485 		}
1486 		if (request_desript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
1487 			goto out;
1488 		if (!reply_q->reply_post_host_index)
1489 			rpf = reply_q->reply_post_free;
1490 		else
1491 			rpf++;
1492 	} while (1);
1493 
1494  out:
1495 
1496 	if (!completed_cmds) {
1497 		atomic_dec(&reply_q->busy);
1498 		return IRQ_NONE;
1499 	}
1500 
1501 	if (ioc->is_warpdrive) {
1502 		writel(reply_q->reply_post_host_index,
1503 		ioc->reply_post_host_index[msix_index]);
1504 		atomic_dec(&reply_q->busy);
1505 		return IRQ_HANDLED;
1506 	}
1507 
1508 	/* Update Reply Post Host Index.
1509 	 * For those HBA's which support combined reply queue feature
1510 	 * 1. Get the correct Supplemental Reply Post Host Index Register.
1511 	 *    i.e. (msix_index / 8)th entry from Supplemental Reply Post Host
1512 	 *    Index Register address bank i.e replyPostRegisterIndex[],
1513 	 * 2. Then update this register with new reply host index value
1514 	 *    in ReplyPostIndex field and the MSIxIndex field with
1515 	 *    msix_index value reduced to a value between 0 and 7,
1516 	 *    using a modulo 8 operation. Since each Supplemental Reply Post
1517 	 *    Host Index Register supports 8 MSI-X vectors.
1518 	 *
1519 	 * For other HBA's just update the Reply Post Host Index register with
1520 	 * new reply host index value in ReplyPostIndex Field and msix_index
1521 	 * value in MSIxIndex field.
1522 	 */
1523 	if (ioc->combined_reply_queue)
1524 		writel(reply_q->reply_post_host_index | ((msix_index  & 7) <<
1525 			MPI2_RPHI_MSIX_INDEX_SHIFT),
1526 			ioc->replyPostRegisterIndex[msix_index/8]);
1527 	else
1528 		writel(reply_q->reply_post_host_index | (msix_index <<
1529 			MPI2_RPHI_MSIX_INDEX_SHIFT),
1530 			&ioc->chip->ReplyPostHostIndex);
1531 	atomic_dec(&reply_q->busy);
1532 	return IRQ_HANDLED;
1533 }
1534 
1535 /**
1536  * _base_is_controller_msix_enabled - is controller support muli-reply queues
1537  * @ioc: per adapter object
1538  *
1539  * Return: Whether or not MSI/X is enabled.
1540  */
1541 static inline int
1542 _base_is_controller_msix_enabled(struct MPT3SAS_ADAPTER *ioc)
1543 {
1544 	return (ioc->facts.IOCCapabilities &
1545 	    MPI2_IOCFACTS_CAPABILITY_MSI_X_INDEX) && ioc->msix_enable;
1546 }
1547 
1548 /**
1549  * mpt3sas_base_sync_reply_irqs - flush pending MSIX interrupts
1550  * @ioc: per adapter object
1551  * Context: non ISR conext
1552  *
1553  * Called when a Task Management request has completed.
1554  */
1555 void
1556 mpt3sas_base_sync_reply_irqs(struct MPT3SAS_ADAPTER *ioc)
1557 {
1558 	struct adapter_reply_queue *reply_q;
1559 
1560 	/* If MSIX capability is turned off
1561 	 * then multi-queues are not enabled
1562 	 */
1563 	if (!_base_is_controller_msix_enabled(ioc))
1564 		return;
1565 
1566 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
1567 		if (ioc->shost_recovery || ioc->remove_host ||
1568 				ioc->pci_error_recovery)
1569 			return;
1570 		/* TMs are on msix_index == 0 */
1571 		if (reply_q->msix_index == 0)
1572 			continue;
1573 		synchronize_irq(pci_irq_vector(ioc->pdev, reply_q->msix_index));
1574 	}
1575 }
1576 
1577 /**
1578  * mpt3sas_base_release_callback_handler - clear interrupt callback handler
1579  * @cb_idx: callback index
1580  */
1581 void
1582 mpt3sas_base_release_callback_handler(u8 cb_idx)
1583 {
1584 	mpt_callbacks[cb_idx] = NULL;
1585 }
1586 
1587 /**
1588  * mpt3sas_base_register_callback_handler - obtain index for the interrupt callback handler
1589  * @cb_func: callback function
1590  *
1591  * Return: Index of @cb_func.
1592  */
1593 u8
1594 mpt3sas_base_register_callback_handler(MPT_CALLBACK cb_func)
1595 {
1596 	u8 cb_idx;
1597 
1598 	for (cb_idx = MPT_MAX_CALLBACKS-1; cb_idx; cb_idx--)
1599 		if (mpt_callbacks[cb_idx] == NULL)
1600 			break;
1601 
1602 	mpt_callbacks[cb_idx] = cb_func;
1603 	return cb_idx;
1604 }
1605 
1606 /**
1607  * mpt3sas_base_initialize_callback_handler - initialize the interrupt callback handler
1608  */
1609 void
1610 mpt3sas_base_initialize_callback_handler(void)
1611 {
1612 	u8 cb_idx;
1613 
1614 	for (cb_idx = 0; cb_idx < MPT_MAX_CALLBACKS; cb_idx++)
1615 		mpt3sas_base_release_callback_handler(cb_idx);
1616 }
1617 
1618 
1619 /**
1620  * _base_build_zero_len_sge - build zero length sg entry
1621  * @ioc: per adapter object
1622  * @paddr: virtual address for SGE
1623  *
1624  * Create a zero length scatter gather entry to insure the IOCs hardware has
1625  * something to use if the target device goes brain dead and tries
1626  * to send data even when none is asked for.
1627  */
1628 static void
1629 _base_build_zero_len_sge(struct MPT3SAS_ADAPTER *ioc, void *paddr)
1630 {
1631 	u32 flags_length = (u32)((MPI2_SGE_FLAGS_LAST_ELEMENT |
1632 	    MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_END_OF_LIST |
1633 	    MPI2_SGE_FLAGS_SIMPLE_ELEMENT) <<
1634 	    MPI2_SGE_FLAGS_SHIFT);
1635 	ioc->base_add_sg_single(paddr, flags_length, -1);
1636 }
1637 
1638 /**
1639  * _base_add_sg_single_32 - Place a simple 32 bit SGE at address pAddr.
1640  * @paddr: virtual address for SGE
1641  * @flags_length: SGE flags and data transfer length
1642  * @dma_addr: Physical address
1643  */
1644 static void
1645 _base_add_sg_single_32(void *paddr, u32 flags_length, dma_addr_t dma_addr)
1646 {
1647 	Mpi2SGESimple32_t *sgel = paddr;
1648 
1649 	flags_length |= (MPI2_SGE_FLAGS_32_BIT_ADDRESSING |
1650 	    MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT;
1651 	sgel->FlagsLength = cpu_to_le32(flags_length);
1652 	sgel->Address = cpu_to_le32(dma_addr);
1653 }
1654 
1655 
1656 /**
1657  * _base_add_sg_single_64 - Place a simple 64 bit SGE at address pAddr.
1658  * @paddr: virtual address for SGE
1659  * @flags_length: SGE flags and data transfer length
1660  * @dma_addr: Physical address
1661  */
1662 static void
1663 _base_add_sg_single_64(void *paddr, u32 flags_length, dma_addr_t dma_addr)
1664 {
1665 	Mpi2SGESimple64_t *sgel = paddr;
1666 
1667 	flags_length |= (MPI2_SGE_FLAGS_64_BIT_ADDRESSING |
1668 	    MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT;
1669 	sgel->FlagsLength = cpu_to_le32(flags_length);
1670 	sgel->Address = cpu_to_le64(dma_addr);
1671 }
1672 
1673 /**
1674  * _base_get_chain_buffer_tracker - obtain chain tracker
1675  * @ioc: per adapter object
1676  * @scmd: SCSI commands of the IO request
1677  *
1678  * Return: chain tracker from chain_lookup table using key as
1679  * smid and smid's chain_offset.
1680  */
1681 static struct chain_tracker *
1682 _base_get_chain_buffer_tracker(struct MPT3SAS_ADAPTER *ioc,
1683 			       struct scsi_cmnd *scmd)
1684 {
1685 	struct chain_tracker *chain_req;
1686 	struct scsiio_tracker *st = scsi_cmd_priv(scmd);
1687 	u16 smid = st->smid;
1688 	u8 chain_offset =
1689 	   atomic_read(&ioc->chain_lookup[smid - 1].chain_offset);
1690 
1691 	if (chain_offset == ioc->chains_needed_per_io)
1692 		return NULL;
1693 
1694 	chain_req = &ioc->chain_lookup[smid - 1].chains_per_smid[chain_offset];
1695 	atomic_inc(&ioc->chain_lookup[smid - 1].chain_offset);
1696 	return chain_req;
1697 }
1698 
1699 
1700 /**
1701  * _base_build_sg - build generic sg
1702  * @ioc: per adapter object
1703  * @psge: virtual address for SGE
1704  * @data_out_dma: physical address for WRITES
1705  * @data_out_sz: data xfer size for WRITES
1706  * @data_in_dma: physical address for READS
1707  * @data_in_sz: data xfer size for READS
1708  */
1709 static void
1710 _base_build_sg(struct MPT3SAS_ADAPTER *ioc, void *psge,
1711 	dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
1712 	size_t data_in_sz)
1713 {
1714 	u32 sgl_flags;
1715 
1716 	if (!data_out_sz && !data_in_sz) {
1717 		_base_build_zero_len_sge(ioc, psge);
1718 		return;
1719 	}
1720 
1721 	if (data_out_sz && data_in_sz) {
1722 		/* WRITE sgel first */
1723 		sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
1724 		    MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_HOST_TO_IOC);
1725 		sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1726 		ioc->base_add_sg_single(psge, sgl_flags |
1727 		    data_out_sz, data_out_dma);
1728 
1729 		/* incr sgel */
1730 		psge += ioc->sge_size;
1731 
1732 		/* READ sgel last */
1733 		sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
1734 		    MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
1735 		    MPI2_SGE_FLAGS_END_OF_LIST);
1736 		sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1737 		ioc->base_add_sg_single(psge, sgl_flags |
1738 		    data_in_sz, data_in_dma);
1739 	} else if (data_out_sz) /* WRITE */ {
1740 		sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
1741 		    MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
1742 		    MPI2_SGE_FLAGS_END_OF_LIST | MPI2_SGE_FLAGS_HOST_TO_IOC);
1743 		sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1744 		ioc->base_add_sg_single(psge, sgl_flags |
1745 		    data_out_sz, data_out_dma);
1746 	} else if (data_in_sz) /* READ */ {
1747 		sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
1748 		    MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
1749 		    MPI2_SGE_FLAGS_END_OF_LIST);
1750 		sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
1751 		ioc->base_add_sg_single(psge, sgl_flags |
1752 		    data_in_sz, data_in_dma);
1753 	}
1754 }
1755 
1756 /* IEEE format sgls */
1757 
1758 /**
1759  * _base_build_nvme_prp - This function is called for NVMe end devices to build
1760  * a native SGL (NVMe PRP). The native SGL is built starting in the first PRP
1761  * entry of the NVMe message (PRP1).  If the data buffer is small enough to be
1762  * described entirely using PRP1, then PRP2 is not used.  If needed, PRP2 is
1763  * used to describe a larger data buffer.  If the data buffer is too large to
1764  * describe using the two PRP entriess inside the NVMe message, then PRP1
1765  * describes the first data memory segment, and PRP2 contains a pointer to a PRP
1766  * list located elsewhere in memory to describe the remaining data memory
1767  * segments.  The PRP list will be contiguous.
1768  *
1769  * The native SGL for NVMe devices is a Physical Region Page (PRP).  A PRP
1770  * consists of a list of PRP entries to describe a number of noncontigous
1771  * physical memory segments as a single memory buffer, just as a SGL does.  Note
1772  * however, that this function is only used by the IOCTL call, so the memory
1773  * given will be guaranteed to be contiguous.  There is no need to translate
1774  * non-contiguous SGL into a PRP in this case.  All PRPs will describe
1775  * contiguous space that is one page size each.
1776  *
1777  * Each NVMe message contains two PRP entries.  The first (PRP1) either contains
1778  * a PRP list pointer or a PRP element, depending upon the command.  PRP2
1779  * contains the second PRP element if the memory being described fits within 2
1780  * PRP entries, or a PRP list pointer if the PRP spans more than two entries.
1781  *
1782  * A PRP list pointer contains the address of a PRP list, structured as a linear
1783  * array of PRP entries.  Each PRP entry in this list describes a segment of
1784  * physical memory.
1785  *
1786  * Each 64-bit PRP entry comprises an address and an offset field.  The address
1787  * always points at the beginning of a 4KB physical memory page, and the offset
1788  * describes where within that 4KB page the memory segment begins.  Only the
1789  * first element in a PRP list may contain a non-zero offest, implying that all
1790  * memory segments following the first begin at the start of a 4KB page.
1791  *
1792  * Each PRP element normally describes 4KB of physical memory, with exceptions
1793  * for the first and last elements in the list.  If the memory being described
1794  * by the list begins at a non-zero offset within the first 4KB page, then the
1795  * first PRP element will contain a non-zero offset indicating where the region
1796  * begins within the 4KB page.  The last memory segment may end before the end
1797  * of the 4KB segment, depending upon the overall size of the memory being
1798  * described by the PRP list.
1799  *
1800  * Since PRP entries lack any indication of size, the overall data buffer length
1801  * is used to determine where the end of the data memory buffer is located, and
1802  * how many PRP entries are required to describe it.
1803  *
1804  * @ioc: per adapter object
1805  * @smid: system request message index for getting asscociated SGL
1806  * @nvme_encap_request: the NVMe request msg frame pointer
1807  * @data_out_dma: physical address for WRITES
1808  * @data_out_sz: data xfer size for WRITES
1809  * @data_in_dma: physical address for READS
1810  * @data_in_sz: data xfer size for READS
1811  */
1812 static void
1813 _base_build_nvme_prp(struct MPT3SAS_ADAPTER *ioc, u16 smid,
1814 	Mpi26NVMeEncapsulatedRequest_t *nvme_encap_request,
1815 	dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
1816 	size_t data_in_sz)
1817 {
1818 	int		prp_size = NVME_PRP_SIZE;
1819 	__le64		*prp_entry, *prp1_entry, *prp2_entry;
1820 	__le64		*prp_page;
1821 	dma_addr_t	prp_entry_dma, prp_page_dma, dma_addr;
1822 	u32		offset, entry_len;
1823 	u32		page_mask_result, page_mask;
1824 	size_t		length;
1825 	struct mpt3sas_nvme_cmd *nvme_cmd =
1826 		(void *)nvme_encap_request->NVMe_Command;
1827 
1828 	/*
1829 	 * Not all commands require a data transfer. If no data, just return
1830 	 * without constructing any PRP.
1831 	 */
1832 	if (!data_in_sz && !data_out_sz)
1833 		return;
1834 	prp1_entry = &nvme_cmd->prp1;
1835 	prp2_entry = &nvme_cmd->prp2;
1836 	prp_entry = prp1_entry;
1837 	/*
1838 	 * For the PRP entries, use the specially allocated buffer of
1839 	 * contiguous memory.
1840 	 */
1841 	prp_page = (__le64 *)mpt3sas_base_get_pcie_sgl(ioc, smid);
1842 	prp_page_dma = mpt3sas_base_get_pcie_sgl_dma(ioc, smid);
1843 
1844 	/*
1845 	 * Check if we are within 1 entry of a page boundary we don't
1846 	 * want our first entry to be a PRP List entry.
1847 	 */
1848 	page_mask = ioc->page_size - 1;
1849 	page_mask_result = (uintptr_t)((u8 *)prp_page + prp_size) & page_mask;
1850 	if (!page_mask_result) {
1851 		/* Bump up to next page boundary. */
1852 		prp_page = (__le64 *)((u8 *)prp_page + prp_size);
1853 		prp_page_dma = prp_page_dma + prp_size;
1854 	}
1855 
1856 	/*
1857 	 * Set PRP physical pointer, which initially points to the current PRP
1858 	 * DMA memory page.
1859 	 */
1860 	prp_entry_dma = prp_page_dma;
1861 
1862 	/* Get physical address and length of the data buffer. */
1863 	if (data_in_sz) {
1864 		dma_addr = data_in_dma;
1865 		length = data_in_sz;
1866 	} else {
1867 		dma_addr = data_out_dma;
1868 		length = data_out_sz;
1869 	}
1870 
1871 	/* Loop while the length is not zero. */
1872 	while (length) {
1873 		/*
1874 		 * Check if we need to put a list pointer here if we are at
1875 		 * page boundary - prp_size (8 bytes).
1876 		 */
1877 		page_mask_result = (prp_entry_dma + prp_size) & page_mask;
1878 		if (!page_mask_result) {
1879 			/*
1880 			 * This is the last entry in a PRP List, so we need to
1881 			 * put a PRP list pointer here.  What this does is:
1882 			 *   - bump the current memory pointer to the next
1883 			 *     address, which will be the next full page.
1884 			 *   - set the PRP Entry to point to that page.  This
1885 			 *     is now the PRP List pointer.
1886 			 *   - bump the PRP Entry pointer the start of the
1887 			 *     next page.  Since all of this PRP memory is
1888 			 *     contiguous, no need to get a new page - it's
1889 			 *     just the next address.
1890 			 */
1891 			prp_entry_dma++;
1892 			*prp_entry = cpu_to_le64(prp_entry_dma);
1893 			prp_entry++;
1894 		}
1895 
1896 		/* Need to handle if entry will be part of a page. */
1897 		offset = dma_addr & page_mask;
1898 		entry_len = ioc->page_size - offset;
1899 
1900 		if (prp_entry == prp1_entry) {
1901 			/*
1902 			 * Must fill in the first PRP pointer (PRP1) before
1903 			 * moving on.
1904 			 */
1905 			*prp1_entry = cpu_to_le64(dma_addr);
1906 
1907 			/*
1908 			 * Now point to the second PRP entry within the
1909 			 * command (PRP2).
1910 			 */
1911 			prp_entry = prp2_entry;
1912 		} else if (prp_entry == prp2_entry) {
1913 			/*
1914 			 * Should the PRP2 entry be a PRP List pointer or just
1915 			 * a regular PRP pointer?  If there is more than one
1916 			 * more page of data, must use a PRP List pointer.
1917 			 */
1918 			if (length > ioc->page_size) {
1919 				/*
1920 				 * PRP2 will contain a PRP List pointer because
1921 				 * more PRP's are needed with this command. The
1922 				 * list will start at the beginning of the
1923 				 * contiguous buffer.
1924 				 */
1925 				*prp2_entry = cpu_to_le64(prp_entry_dma);
1926 
1927 				/*
1928 				 * The next PRP Entry will be the start of the
1929 				 * first PRP List.
1930 				 */
1931 				prp_entry = prp_page;
1932 			} else {
1933 				/*
1934 				 * After this, the PRP Entries are complete.
1935 				 * This command uses 2 PRP's and no PRP list.
1936 				 */
1937 				*prp2_entry = cpu_to_le64(dma_addr);
1938 			}
1939 		} else {
1940 			/*
1941 			 * Put entry in list and bump the addresses.
1942 			 *
1943 			 * After PRP1 and PRP2 are filled in, this will fill in
1944 			 * all remaining PRP entries in a PRP List, one per
1945 			 * each time through the loop.
1946 			 */
1947 			*prp_entry = cpu_to_le64(dma_addr);
1948 			prp_entry++;
1949 			prp_entry_dma++;
1950 		}
1951 
1952 		/*
1953 		 * Bump the phys address of the command's data buffer by the
1954 		 * entry_len.
1955 		 */
1956 		dma_addr += entry_len;
1957 
1958 		/* Decrement length accounting for last partial page. */
1959 		if (entry_len > length)
1960 			length = 0;
1961 		else
1962 			length -= entry_len;
1963 	}
1964 }
1965 
1966 /**
1967  * base_make_prp_nvme -
1968  * Prepare PRPs(Physical Region Page)- SGLs specific to NVMe drives only
1969  *
1970  * @ioc:		per adapter object
1971  * @scmd:		SCSI command from the mid-layer
1972  * @mpi_request:	mpi request
1973  * @smid:		msg Index
1974  * @sge_count:		scatter gather element count.
1975  *
1976  * Return:		true: PRPs are built
1977  *			false: IEEE SGLs needs to be built
1978  */
1979 static void
1980 base_make_prp_nvme(struct MPT3SAS_ADAPTER *ioc,
1981 		struct scsi_cmnd *scmd,
1982 		Mpi25SCSIIORequest_t *mpi_request,
1983 		u16 smid, int sge_count)
1984 {
1985 	int sge_len, num_prp_in_chain = 0;
1986 	Mpi25IeeeSgeChain64_t *main_chain_element, *ptr_first_sgl;
1987 	__le64 *curr_buff;
1988 	dma_addr_t msg_dma, sge_addr, offset;
1989 	u32 page_mask, page_mask_result;
1990 	struct scatterlist *sg_scmd;
1991 	u32 first_prp_len;
1992 	int data_len = scsi_bufflen(scmd);
1993 	u32 nvme_pg_size;
1994 
1995 	nvme_pg_size = max_t(u32, ioc->page_size, NVME_PRP_PAGE_SIZE);
1996 	/*
1997 	 * Nvme has a very convoluted prp format.  One prp is required
1998 	 * for each page or partial page. Driver need to split up OS sg_list
1999 	 * entries if it is longer than one page or cross a page
2000 	 * boundary.  Driver also have to insert a PRP list pointer entry as
2001 	 * the last entry in each physical page of the PRP list.
2002 	 *
2003 	 * NOTE: The first PRP "entry" is actually placed in the first
2004 	 * SGL entry in the main message as IEEE 64 format.  The 2nd
2005 	 * entry in the main message is the chain element, and the rest
2006 	 * of the PRP entries are built in the contiguous pcie buffer.
2007 	 */
2008 	page_mask = nvme_pg_size - 1;
2009 
2010 	/*
2011 	 * Native SGL is needed.
2012 	 * Put a chain element in main message frame that points to the first
2013 	 * chain buffer.
2014 	 *
2015 	 * NOTE:  The ChainOffset field must be 0 when using a chain pointer to
2016 	 *        a native SGL.
2017 	 */
2018 
2019 	/* Set main message chain element pointer */
2020 	main_chain_element = (pMpi25IeeeSgeChain64_t)&mpi_request->SGL;
2021 	/*
2022 	 * For NVMe the chain element needs to be the 2nd SG entry in the main
2023 	 * message.
2024 	 */
2025 	main_chain_element = (Mpi25IeeeSgeChain64_t *)
2026 		((u8 *)main_chain_element + sizeof(MPI25_IEEE_SGE_CHAIN64));
2027 
2028 	/*
2029 	 * For the PRP entries, use the specially allocated buffer of
2030 	 * contiguous memory.  Normal chain buffers can't be used
2031 	 * because each chain buffer would need to be the size of an OS
2032 	 * page (4k).
2033 	 */
2034 	curr_buff = mpt3sas_base_get_pcie_sgl(ioc, smid);
2035 	msg_dma = mpt3sas_base_get_pcie_sgl_dma(ioc, smid);
2036 
2037 	main_chain_element->Address = cpu_to_le64(msg_dma);
2038 	main_chain_element->NextChainOffset = 0;
2039 	main_chain_element->Flags = MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
2040 			MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
2041 			MPI26_IEEE_SGE_FLAGS_NSF_NVME_PRP;
2042 
2043 	/* Build first prp, sge need not to be page aligned*/
2044 	ptr_first_sgl = (pMpi25IeeeSgeChain64_t)&mpi_request->SGL;
2045 	sg_scmd = scsi_sglist(scmd);
2046 	sge_addr = sg_dma_address(sg_scmd);
2047 	sge_len = sg_dma_len(sg_scmd);
2048 
2049 	offset = sge_addr & page_mask;
2050 	first_prp_len = nvme_pg_size - offset;
2051 
2052 	ptr_first_sgl->Address = cpu_to_le64(sge_addr);
2053 	ptr_first_sgl->Length = cpu_to_le32(first_prp_len);
2054 
2055 	data_len -= first_prp_len;
2056 
2057 	if (sge_len > first_prp_len) {
2058 		sge_addr += first_prp_len;
2059 		sge_len -= first_prp_len;
2060 	} else if (data_len && (sge_len == first_prp_len)) {
2061 		sg_scmd = sg_next(sg_scmd);
2062 		sge_addr = sg_dma_address(sg_scmd);
2063 		sge_len = sg_dma_len(sg_scmd);
2064 	}
2065 
2066 	for (;;) {
2067 		offset = sge_addr & page_mask;
2068 
2069 		/* Put PRP pointer due to page boundary*/
2070 		page_mask_result = (uintptr_t)(curr_buff + 1) & page_mask;
2071 		if (unlikely(!page_mask_result)) {
2072 			scmd_printk(KERN_NOTICE,
2073 				scmd, "page boundary curr_buff: 0x%p\n",
2074 				curr_buff);
2075 			msg_dma += 8;
2076 			*curr_buff = cpu_to_le64(msg_dma);
2077 			curr_buff++;
2078 			num_prp_in_chain++;
2079 		}
2080 
2081 		*curr_buff = cpu_to_le64(sge_addr);
2082 		curr_buff++;
2083 		msg_dma += 8;
2084 		num_prp_in_chain++;
2085 
2086 		sge_addr += nvme_pg_size;
2087 		sge_len -= nvme_pg_size;
2088 		data_len -= nvme_pg_size;
2089 
2090 		if (data_len <= 0)
2091 			break;
2092 
2093 		if (sge_len > 0)
2094 			continue;
2095 
2096 		sg_scmd = sg_next(sg_scmd);
2097 		sge_addr = sg_dma_address(sg_scmd);
2098 		sge_len = sg_dma_len(sg_scmd);
2099 	}
2100 
2101 	main_chain_element->Length =
2102 		cpu_to_le32(num_prp_in_chain * sizeof(u64));
2103 	return;
2104 }
2105 
2106 static bool
2107 base_is_prp_possible(struct MPT3SAS_ADAPTER *ioc,
2108 	struct _pcie_device *pcie_device, struct scsi_cmnd *scmd, int sge_count)
2109 {
2110 	u32 data_length = 0;
2111 	bool build_prp = true;
2112 
2113 	data_length = scsi_bufflen(scmd);
2114 
2115 	/* If Datalenth is <= 16K and number of SGE’s entries are <= 2
2116 	 * we built IEEE SGL
2117 	 */
2118 	if ((data_length <= NVME_PRP_PAGE_SIZE*4) && (sge_count <= 2))
2119 		build_prp = false;
2120 
2121 	return build_prp;
2122 }
2123 
2124 /**
2125  * _base_check_pcie_native_sgl - This function is called for PCIe end devices to
2126  * determine if the driver needs to build a native SGL.  If so, that native
2127  * SGL is built in the special contiguous buffers allocated especially for
2128  * PCIe SGL creation.  If the driver will not build a native SGL, return
2129  * TRUE and a normal IEEE SGL will be built.  Currently this routine
2130  * supports NVMe.
2131  * @ioc: per adapter object
2132  * @mpi_request: mf request pointer
2133  * @smid: system request message index
2134  * @scmd: scsi command
2135  * @pcie_device: points to the PCIe device's info
2136  *
2137  * Return: 0 if native SGL was built, 1 if no SGL was built
2138  */
2139 static int
2140 _base_check_pcie_native_sgl(struct MPT3SAS_ADAPTER *ioc,
2141 	Mpi25SCSIIORequest_t *mpi_request, u16 smid, struct scsi_cmnd *scmd,
2142 	struct _pcie_device *pcie_device)
2143 {
2144 	int sges_left;
2145 
2146 	/* Get the SG list pointer and info. */
2147 	sges_left = scsi_dma_map(scmd);
2148 	if (sges_left < 0) {
2149 		sdev_printk(KERN_ERR, scmd->device,
2150 			"scsi_dma_map failed: request for %d bytes!\n",
2151 			scsi_bufflen(scmd));
2152 		return 1;
2153 	}
2154 
2155 	/* Check if we need to build a native SG list. */
2156 	if (base_is_prp_possible(ioc, pcie_device,
2157 				scmd, sges_left) == 0) {
2158 		/* We built a native SG list, just return. */
2159 		goto out;
2160 	}
2161 
2162 	/*
2163 	 * Build native NVMe PRP.
2164 	 */
2165 	base_make_prp_nvme(ioc, scmd, mpi_request,
2166 			smid, sges_left);
2167 
2168 	return 0;
2169 out:
2170 	scsi_dma_unmap(scmd);
2171 	return 1;
2172 }
2173 
2174 /**
2175  * _base_add_sg_single_ieee - add sg element for IEEE format
2176  * @paddr: virtual address for SGE
2177  * @flags: SGE flags
2178  * @chain_offset: number of 128 byte elements from start of segment
2179  * @length: data transfer length
2180  * @dma_addr: Physical address
2181  */
2182 static void
2183 _base_add_sg_single_ieee(void *paddr, u8 flags, u8 chain_offset, u32 length,
2184 	dma_addr_t dma_addr)
2185 {
2186 	Mpi25IeeeSgeChain64_t *sgel = paddr;
2187 
2188 	sgel->Flags = flags;
2189 	sgel->NextChainOffset = chain_offset;
2190 	sgel->Length = cpu_to_le32(length);
2191 	sgel->Address = cpu_to_le64(dma_addr);
2192 }
2193 
2194 /**
2195  * _base_build_zero_len_sge_ieee - build zero length sg entry for IEEE format
2196  * @ioc: per adapter object
2197  * @paddr: virtual address for SGE
2198  *
2199  * Create a zero length scatter gather entry to insure the IOCs hardware has
2200  * something to use if the target device goes brain dead and tries
2201  * to send data even when none is asked for.
2202  */
2203 static void
2204 _base_build_zero_len_sge_ieee(struct MPT3SAS_ADAPTER *ioc, void *paddr)
2205 {
2206 	u8 sgl_flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2207 		MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
2208 		MPI25_IEEE_SGE_FLAGS_END_OF_LIST);
2209 
2210 	_base_add_sg_single_ieee(paddr, sgl_flags, 0, 0, -1);
2211 }
2212 
2213 /**
2214  * _base_build_sg_scmd - main sg creation routine
2215  *		pcie_device is unused here!
2216  * @ioc: per adapter object
2217  * @scmd: scsi command
2218  * @smid: system request message index
2219  * @unused: unused pcie_device pointer
2220  * Context: none.
2221  *
2222  * The main routine that builds scatter gather table from a given
2223  * scsi request sent via the .queuecommand main handler.
2224  *
2225  * Return: 0 success, anything else error
2226  */
2227 static int
2228 _base_build_sg_scmd(struct MPT3SAS_ADAPTER *ioc,
2229 	struct scsi_cmnd *scmd, u16 smid, struct _pcie_device *unused)
2230 {
2231 	Mpi2SCSIIORequest_t *mpi_request;
2232 	dma_addr_t chain_dma;
2233 	struct scatterlist *sg_scmd;
2234 	void *sg_local, *chain;
2235 	u32 chain_offset;
2236 	u32 chain_length;
2237 	u32 chain_flags;
2238 	int sges_left;
2239 	u32 sges_in_segment;
2240 	u32 sgl_flags;
2241 	u32 sgl_flags_last_element;
2242 	u32 sgl_flags_end_buffer;
2243 	struct chain_tracker *chain_req;
2244 
2245 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
2246 
2247 	/* init scatter gather flags */
2248 	sgl_flags = MPI2_SGE_FLAGS_SIMPLE_ELEMENT;
2249 	if (scmd->sc_data_direction == DMA_TO_DEVICE)
2250 		sgl_flags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
2251 	sgl_flags_last_element = (sgl_flags | MPI2_SGE_FLAGS_LAST_ELEMENT)
2252 	    << MPI2_SGE_FLAGS_SHIFT;
2253 	sgl_flags_end_buffer = (sgl_flags | MPI2_SGE_FLAGS_LAST_ELEMENT |
2254 	    MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_END_OF_LIST)
2255 	    << MPI2_SGE_FLAGS_SHIFT;
2256 	sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
2257 
2258 	sg_scmd = scsi_sglist(scmd);
2259 	sges_left = scsi_dma_map(scmd);
2260 	if (sges_left < 0) {
2261 		sdev_printk(KERN_ERR, scmd->device,
2262 		 "scsi_dma_map failed: request for %d bytes!\n",
2263 		 scsi_bufflen(scmd));
2264 		return -ENOMEM;
2265 	}
2266 
2267 	sg_local = &mpi_request->SGL;
2268 	sges_in_segment = ioc->max_sges_in_main_message;
2269 	if (sges_left <= sges_in_segment)
2270 		goto fill_in_last_segment;
2271 
2272 	mpi_request->ChainOffset = (offsetof(Mpi2SCSIIORequest_t, SGL) +
2273 	    (sges_in_segment * ioc->sge_size))/4;
2274 
2275 	/* fill in main message segment when there is a chain following */
2276 	while (sges_in_segment) {
2277 		if (sges_in_segment == 1)
2278 			ioc->base_add_sg_single(sg_local,
2279 			    sgl_flags_last_element | sg_dma_len(sg_scmd),
2280 			    sg_dma_address(sg_scmd));
2281 		else
2282 			ioc->base_add_sg_single(sg_local, sgl_flags |
2283 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2284 		sg_scmd = sg_next(sg_scmd);
2285 		sg_local += ioc->sge_size;
2286 		sges_left--;
2287 		sges_in_segment--;
2288 	}
2289 
2290 	/* initializing the chain flags and pointers */
2291 	chain_flags = MPI2_SGE_FLAGS_CHAIN_ELEMENT << MPI2_SGE_FLAGS_SHIFT;
2292 	chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2293 	if (!chain_req)
2294 		return -1;
2295 	chain = chain_req->chain_buffer;
2296 	chain_dma = chain_req->chain_buffer_dma;
2297 	do {
2298 		sges_in_segment = (sges_left <=
2299 		    ioc->max_sges_in_chain_message) ? sges_left :
2300 		    ioc->max_sges_in_chain_message;
2301 		chain_offset = (sges_left == sges_in_segment) ?
2302 		    0 : (sges_in_segment * ioc->sge_size)/4;
2303 		chain_length = sges_in_segment * ioc->sge_size;
2304 		if (chain_offset) {
2305 			chain_offset = chain_offset <<
2306 			    MPI2_SGE_CHAIN_OFFSET_SHIFT;
2307 			chain_length += ioc->sge_size;
2308 		}
2309 		ioc->base_add_sg_single(sg_local, chain_flags | chain_offset |
2310 		    chain_length, chain_dma);
2311 		sg_local = chain;
2312 		if (!chain_offset)
2313 			goto fill_in_last_segment;
2314 
2315 		/* fill in chain segments */
2316 		while (sges_in_segment) {
2317 			if (sges_in_segment == 1)
2318 				ioc->base_add_sg_single(sg_local,
2319 				    sgl_flags_last_element |
2320 				    sg_dma_len(sg_scmd),
2321 				    sg_dma_address(sg_scmd));
2322 			else
2323 				ioc->base_add_sg_single(sg_local, sgl_flags |
2324 				    sg_dma_len(sg_scmd),
2325 				    sg_dma_address(sg_scmd));
2326 			sg_scmd = sg_next(sg_scmd);
2327 			sg_local += ioc->sge_size;
2328 			sges_left--;
2329 			sges_in_segment--;
2330 		}
2331 
2332 		chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2333 		if (!chain_req)
2334 			return -1;
2335 		chain = chain_req->chain_buffer;
2336 		chain_dma = chain_req->chain_buffer_dma;
2337 	} while (1);
2338 
2339 
2340  fill_in_last_segment:
2341 
2342 	/* fill the last segment */
2343 	while (sges_left) {
2344 		if (sges_left == 1)
2345 			ioc->base_add_sg_single(sg_local, sgl_flags_end_buffer |
2346 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2347 		else
2348 			ioc->base_add_sg_single(sg_local, sgl_flags |
2349 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2350 		sg_scmd = sg_next(sg_scmd);
2351 		sg_local += ioc->sge_size;
2352 		sges_left--;
2353 	}
2354 
2355 	return 0;
2356 }
2357 
2358 /**
2359  * _base_build_sg_scmd_ieee - main sg creation routine for IEEE format
2360  * @ioc: per adapter object
2361  * @scmd: scsi command
2362  * @smid: system request message index
2363  * @pcie_device: Pointer to pcie_device. If set, the pcie native sgl will be
2364  * constructed on need.
2365  * Context: none.
2366  *
2367  * The main routine that builds scatter gather table from a given
2368  * scsi request sent via the .queuecommand main handler.
2369  *
2370  * Return: 0 success, anything else error
2371  */
2372 static int
2373 _base_build_sg_scmd_ieee(struct MPT3SAS_ADAPTER *ioc,
2374 	struct scsi_cmnd *scmd, u16 smid, struct _pcie_device *pcie_device)
2375 {
2376 	Mpi25SCSIIORequest_t *mpi_request;
2377 	dma_addr_t chain_dma;
2378 	struct scatterlist *sg_scmd;
2379 	void *sg_local, *chain;
2380 	u32 chain_offset;
2381 	u32 chain_length;
2382 	int sges_left;
2383 	u32 sges_in_segment;
2384 	u8 simple_sgl_flags;
2385 	u8 simple_sgl_flags_last;
2386 	u8 chain_sgl_flags;
2387 	struct chain_tracker *chain_req;
2388 
2389 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
2390 
2391 	/* init scatter gather flags */
2392 	simple_sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2393 	    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2394 	simple_sgl_flags_last = simple_sgl_flags |
2395 	    MPI25_IEEE_SGE_FLAGS_END_OF_LIST;
2396 	chain_sgl_flags = MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
2397 	    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2398 
2399 	/* Check if we need to build a native SG list. */
2400 	if ((pcie_device) && (_base_check_pcie_native_sgl(ioc, mpi_request,
2401 			smid, scmd, pcie_device) == 0)) {
2402 		/* We built a native SG list, just return. */
2403 		return 0;
2404 	}
2405 
2406 	sg_scmd = scsi_sglist(scmd);
2407 	sges_left = scsi_dma_map(scmd);
2408 	if (sges_left < 0) {
2409 		sdev_printk(KERN_ERR, scmd->device,
2410 			"scsi_dma_map failed: request for %d bytes!\n",
2411 			scsi_bufflen(scmd));
2412 		return -ENOMEM;
2413 	}
2414 
2415 	sg_local = &mpi_request->SGL;
2416 	sges_in_segment = (ioc->request_sz -
2417 		   offsetof(Mpi25SCSIIORequest_t, SGL))/ioc->sge_size_ieee;
2418 	if (sges_left <= sges_in_segment)
2419 		goto fill_in_last_segment;
2420 
2421 	mpi_request->ChainOffset = (sges_in_segment - 1 /* chain element */) +
2422 	    (offsetof(Mpi25SCSIIORequest_t, SGL)/ioc->sge_size_ieee);
2423 
2424 	/* fill in main message segment when there is a chain following */
2425 	while (sges_in_segment > 1) {
2426 		_base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
2427 		    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2428 		sg_scmd = sg_next(sg_scmd);
2429 		sg_local += ioc->sge_size_ieee;
2430 		sges_left--;
2431 		sges_in_segment--;
2432 	}
2433 
2434 	/* initializing the pointers */
2435 	chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2436 	if (!chain_req)
2437 		return -1;
2438 	chain = chain_req->chain_buffer;
2439 	chain_dma = chain_req->chain_buffer_dma;
2440 	do {
2441 		sges_in_segment = (sges_left <=
2442 		    ioc->max_sges_in_chain_message) ? sges_left :
2443 		    ioc->max_sges_in_chain_message;
2444 		chain_offset = (sges_left == sges_in_segment) ?
2445 		    0 : sges_in_segment;
2446 		chain_length = sges_in_segment * ioc->sge_size_ieee;
2447 		if (chain_offset)
2448 			chain_length += ioc->sge_size_ieee;
2449 		_base_add_sg_single_ieee(sg_local, chain_sgl_flags,
2450 		    chain_offset, chain_length, chain_dma);
2451 
2452 		sg_local = chain;
2453 		if (!chain_offset)
2454 			goto fill_in_last_segment;
2455 
2456 		/* fill in chain segments */
2457 		while (sges_in_segment) {
2458 			_base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
2459 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2460 			sg_scmd = sg_next(sg_scmd);
2461 			sg_local += ioc->sge_size_ieee;
2462 			sges_left--;
2463 			sges_in_segment--;
2464 		}
2465 
2466 		chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2467 		if (!chain_req)
2468 			return -1;
2469 		chain = chain_req->chain_buffer;
2470 		chain_dma = chain_req->chain_buffer_dma;
2471 	} while (1);
2472 
2473 
2474  fill_in_last_segment:
2475 
2476 	/* fill the last segment */
2477 	while (sges_left > 0) {
2478 		if (sges_left == 1)
2479 			_base_add_sg_single_ieee(sg_local,
2480 			    simple_sgl_flags_last, 0, sg_dma_len(sg_scmd),
2481 			    sg_dma_address(sg_scmd));
2482 		else
2483 			_base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
2484 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2485 		sg_scmd = sg_next(sg_scmd);
2486 		sg_local += ioc->sge_size_ieee;
2487 		sges_left--;
2488 	}
2489 
2490 	return 0;
2491 }
2492 
2493 /**
2494  * _base_build_sg_ieee - build generic sg for IEEE format
2495  * @ioc: per adapter object
2496  * @psge: virtual address for SGE
2497  * @data_out_dma: physical address for WRITES
2498  * @data_out_sz: data xfer size for WRITES
2499  * @data_in_dma: physical address for READS
2500  * @data_in_sz: data xfer size for READS
2501  */
2502 static void
2503 _base_build_sg_ieee(struct MPT3SAS_ADAPTER *ioc, void *psge,
2504 	dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
2505 	size_t data_in_sz)
2506 {
2507 	u8 sgl_flags;
2508 
2509 	if (!data_out_sz && !data_in_sz) {
2510 		_base_build_zero_len_sge_ieee(ioc, psge);
2511 		return;
2512 	}
2513 
2514 	if (data_out_sz && data_in_sz) {
2515 		/* WRITE sgel first */
2516 		sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2517 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2518 		_base_add_sg_single_ieee(psge, sgl_flags, 0, data_out_sz,
2519 		    data_out_dma);
2520 
2521 		/* incr sgel */
2522 		psge += ioc->sge_size_ieee;
2523 
2524 		/* READ sgel last */
2525 		sgl_flags |= MPI25_IEEE_SGE_FLAGS_END_OF_LIST;
2526 		_base_add_sg_single_ieee(psge, sgl_flags, 0, data_in_sz,
2527 		    data_in_dma);
2528 	} else if (data_out_sz) /* WRITE */ {
2529 		sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2530 		    MPI25_IEEE_SGE_FLAGS_END_OF_LIST |
2531 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2532 		_base_add_sg_single_ieee(psge, sgl_flags, 0, data_out_sz,
2533 		    data_out_dma);
2534 	} else if (data_in_sz) /* READ */ {
2535 		sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2536 		    MPI25_IEEE_SGE_FLAGS_END_OF_LIST |
2537 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2538 		_base_add_sg_single_ieee(psge, sgl_flags, 0, data_in_sz,
2539 		    data_in_dma);
2540 	}
2541 }
2542 
2543 #define convert_to_kb(x) ((x) << (PAGE_SHIFT - 10))
2544 
2545 /**
2546  * _base_config_dma_addressing - set dma addressing
2547  * @ioc: per adapter object
2548  * @pdev: PCI device struct
2549  *
2550  * Return: 0 for success, non-zero for failure.
2551  */
2552 static int
2553 _base_config_dma_addressing(struct MPT3SAS_ADAPTER *ioc, struct pci_dev *pdev)
2554 {
2555 	u64 required_mask, coherent_mask;
2556 	struct sysinfo s;
2557 
2558 	if (ioc->is_mcpu_endpoint)
2559 		goto try_32bit;
2560 
2561 	required_mask = dma_get_required_mask(&pdev->dev);
2562 	if (sizeof(dma_addr_t) == 4 || required_mask == 32)
2563 		goto try_32bit;
2564 
2565 	if (ioc->dma_mask)
2566 		coherent_mask = DMA_BIT_MASK(64);
2567 	else
2568 		coherent_mask = DMA_BIT_MASK(32);
2569 
2570 	if (dma_set_mask(&pdev->dev, DMA_BIT_MASK(64)) ||
2571 	    dma_set_coherent_mask(&pdev->dev, coherent_mask))
2572 		goto try_32bit;
2573 
2574 	ioc->base_add_sg_single = &_base_add_sg_single_64;
2575 	ioc->sge_size = sizeof(Mpi2SGESimple64_t);
2576 	ioc->dma_mask = 64;
2577 	goto out;
2578 
2579  try_32bit:
2580 	if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
2581 		return -ENODEV;
2582 
2583 	ioc->base_add_sg_single = &_base_add_sg_single_32;
2584 	ioc->sge_size = sizeof(Mpi2SGESimple32_t);
2585 	ioc->dma_mask = 32;
2586  out:
2587 	si_meminfo(&s);
2588 	ioc_info(ioc, "%d BIT PCI BUS DMA ADDRESSING SUPPORTED, total mem (%ld kB)\n",
2589 		 ioc->dma_mask, convert_to_kb(s.totalram));
2590 
2591 	return 0;
2592 }
2593 
2594 static int
2595 _base_change_consistent_dma_mask(struct MPT3SAS_ADAPTER *ioc,
2596 				      struct pci_dev *pdev)
2597 {
2598 	if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64))) {
2599 		if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)))
2600 			return -ENODEV;
2601 	}
2602 	return 0;
2603 }
2604 
2605 /**
2606  * _base_check_enable_msix - checks MSIX capabable.
2607  * @ioc: per adapter object
2608  *
2609  * Check to see if card is capable of MSIX, and set number
2610  * of available msix vectors
2611  */
2612 static int
2613 _base_check_enable_msix(struct MPT3SAS_ADAPTER *ioc)
2614 {
2615 	int base;
2616 	u16 message_control;
2617 
2618 	/* Check whether controller SAS2008 B0 controller,
2619 	 * if it is SAS2008 B0 controller use IO-APIC instead of MSIX
2620 	 */
2621 	if (ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2008 &&
2622 	    ioc->pdev->revision == SAS2_PCI_DEVICE_B0_REVISION) {
2623 		return -EINVAL;
2624 	}
2625 
2626 	base = pci_find_capability(ioc->pdev, PCI_CAP_ID_MSIX);
2627 	if (!base) {
2628 		dfailprintk(ioc, ioc_info(ioc, "msix not supported\n"));
2629 		return -EINVAL;
2630 	}
2631 
2632 	/* get msix vector count */
2633 	/* NUMA_IO not supported for older controllers */
2634 	if (ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2004 ||
2635 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2008 ||
2636 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_1 ||
2637 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_2 ||
2638 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_3 ||
2639 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2116_1 ||
2640 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2116_2)
2641 		ioc->msix_vector_count = 1;
2642 	else {
2643 		pci_read_config_word(ioc->pdev, base + 2, &message_control);
2644 		ioc->msix_vector_count = (message_control & 0x3FF) + 1;
2645 	}
2646 	dinitprintk(ioc, ioc_info(ioc, "msix is supported, vector_count(%d)\n",
2647 				  ioc->msix_vector_count));
2648 	return 0;
2649 }
2650 
2651 /**
2652  * _base_free_irq - free irq
2653  * @ioc: per adapter object
2654  *
2655  * Freeing respective reply_queue from the list.
2656  */
2657 static void
2658 _base_free_irq(struct MPT3SAS_ADAPTER *ioc)
2659 {
2660 	struct adapter_reply_queue *reply_q, *next;
2661 
2662 	if (list_empty(&ioc->reply_queue_list))
2663 		return;
2664 
2665 	list_for_each_entry_safe(reply_q, next, &ioc->reply_queue_list, list) {
2666 		list_del(&reply_q->list);
2667 		free_irq(pci_irq_vector(ioc->pdev, reply_q->msix_index),
2668 			 reply_q);
2669 		kfree(reply_q);
2670 	}
2671 }
2672 
2673 /**
2674  * _base_request_irq - request irq
2675  * @ioc: per adapter object
2676  * @index: msix index into vector table
2677  *
2678  * Inserting respective reply_queue into the list.
2679  */
2680 static int
2681 _base_request_irq(struct MPT3SAS_ADAPTER *ioc, u8 index)
2682 {
2683 	struct pci_dev *pdev = ioc->pdev;
2684 	struct adapter_reply_queue *reply_q;
2685 	int r;
2686 
2687 	reply_q =  kzalloc(sizeof(struct adapter_reply_queue), GFP_KERNEL);
2688 	if (!reply_q) {
2689 		ioc_err(ioc, "unable to allocate memory %zu!\n",
2690 			sizeof(struct adapter_reply_queue));
2691 		return -ENOMEM;
2692 	}
2693 	reply_q->ioc = ioc;
2694 	reply_q->msix_index = index;
2695 
2696 	atomic_set(&reply_q->busy, 0);
2697 	if (ioc->msix_enable)
2698 		snprintf(reply_q->name, MPT_NAME_LENGTH, "%s%d-msix%d",
2699 		    ioc->driver_name, ioc->id, index);
2700 	else
2701 		snprintf(reply_q->name, MPT_NAME_LENGTH, "%s%d",
2702 		    ioc->driver_name, ioc->id);
2703 	r = request_irq(pci_irq_vector(pdev, index), _base_interrupt,
2704 			IRQF_SHARED, reply_q->name, reply_q);
2705 	if (r) {
2706 		pr_err("%s: unable to allocate interrupt %d!\n",
2707 		       reply_q->name, pci_irq_vector(pdev, index));
2708 		kfree(reply_q);
2709 		return -EBUSY;
2710 	}
2711 
2712 	INIT_LIST_HEAD(&reply_q->list);
2713 	list_add_tail(&reply_q->list, &ioc->reply_queue_list);
2714 	return 0;
2715 }
2716 
2717 /**
2718  * _base_assign_reply_queues - assigning msix index for each cpu
2719  * @ioc: per adapter object
2720  *
2721  * The enduser would need to set the affinity via /proc/irq/#/smp_affinity
2722  *
2723  * It would nice if we could call irq_set_affinity, however it is not
2724  * an exported symbol
2725  */
2726 static void
2727 _base_assign_reply_queues(struct MPT3SAS_ADAPTER *ioc)
2728 {
2729 	unsigned int cpu, nr_cpus, nr_msix, index = 0;
2730 	struct adapter_reply_queue *reply_q;
2731 
2732 	if (!_base_is_controller_msix_enabled(ioc))
2733 		return;
2734 
2735 	memset(ioc->cpu_msix_table, 0, ioc->cpu_msix_table_sz);
2736 
2737 	nr_cpus = num_online_cpus();
2738 	nr_msix = ioc->reply_queue_count = min(ioc->reply_queue_count,
2739 					       ioc->facts.MaxMSIxVectors);
2740 	if (!nr_msix)
2741 		return;
2742 
2743 	if (smp_affinity_enable) {
2744 		list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
2745 			const cpumask_t *mask = pci_irq_get_affinity(ioc->pdev,
2746 							reply_q->msix_index);
2747 			if (!mask) {
2748 				ioc_warn(ioc, "no affinity for msi %x\n",
2749 					 reply_q->msix_index);
2750 				continue;
2751 			}
2752 
2753 			for_each_cpu_and(cpu, mask, cpu_online_mask) {
2754 				if (cpu >= ioc->cpu_msix_table_sz)
2755 					break;
2756 				ioc->cpu_msix_table[cpu] = reply_q->msix_index;
2757 			}
2758 		}
2759 		return;
2760 	}
2761 	cpu = cpumask_first(cpu_online_mask);
2762 
2763 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
2764 
2765 		unsigned int i, group = nr_cpus / nr_msix;
2766 
2767 		if (cpu >= nr_cpus)
2768 			break;
2769 
2770 		if (index < nr_cpus % nr_msix)
2771 			group++;
2772 
2773 		for (i = 0 ; i < group ; i++) {
2774 			ioc->cpu_msix_table[cpu] = reply_q->msix_index;
2775 			cpu = cpumask_next(cpu, cpu_online_mask);
2776 		}
2777 		index++;
2778 	}
2779 }
2780 
2781 /**
2782  * _base_disable_msix - disables msix
2783  * @ioc: per adapter object
2784  *
2785  */
2786 static void
2787 _base_disable_msix(struct MPT3SAS_ADAPTER *ioc)
2788 {
2789 	if (!ioc->msix_enable)
2790 		return;
2791 	pci_disable_msix(ioc->pdev);
2792 	ioc->msix_enable = 0;
2793 }
2794 
2795 /**
2796  * _base_enable_msix - enables msix, failback to io_apic
2797  * @ioc: per adapter object
2798  *
2799  */
2800 static int
2801 _base_enable_msix(struct MPT3SAS_ADAPTER *ioc)
2802 {
2803 	int r;
2804 	int i, local_max_msix_vectors;
2805 	u8 try_msix = 0;
2806 	unsigned int irq_flags = PCI_IRQ_MSIX;
2807 
2808 	if (msix_disable == -1 || msix_disable == 0)
2809 		try_msix = 1;
2810 
2811 	if (!try_msix)
2812 		goto try_ioapic;
2813 
2814 	if (_base_check_enable_msix(ioc) != 0)
2815 		goto try_ioapic;
2816 
2817 	ioc->reply_queue_count = min_t(int, ioc->cpu_count,
2818 		ioc->msix_vector_count);
2819 
2820 	ioc_info(ioc, "MSI-X vectors supported: %d, no of cores: %d, max_msix_vectors: %d\n",
2821 		 ioc->msix_vector_count, ioc->cpu_count, max_msix_vectors);
2822 
2823 	if (!ioc->rdpq_array_enable && max_msix_vectors == -1)
2824 		local_max_msix_vectors = (reset_devices) ? 1 : 8;
2825 	else
2826 		local_max_msix_vectors = max_msix_vectors;
2827 
2828 	if (local_max_msix_vectors > 0)
2829 		ioc->reply_queue_count = min_t(int, local_max_msix_vectors,
2830 			ioc->reply_queue_count);
2831 	else if (local_max_msix_vectors == 0)
2832 		goto try_ioapic;
2833 
2834 	if (ioc->msix_vector_count < ioc->cpu_count)
2835 		smp_affinity_enable = 0;
2836 
2837 	if (smp_affinity_enable)
2838 		irq_flags |= PCI_IRQ_AFFINITY;
2839 
2840 	r = pci_alloc_irq_vectors(ioc->pdev, 1, ioc->reply_queue_count,
2841 				  irq_flags);
2842 	if (r < 0) {
2843 		dfailprintk(ioc,
2844 			    ioc_info(ioc, "pci_alloc_irq_vectors failed (r=%d) !!!\n",
2845 				     r));
2846 		goto try_ioapic;
2847 	}
2848 
2849 	ioc->msix_enable = 1;
2850 	ioc->reply_queue_count = r;
2851 	for (i = 0; i < ioc->reply_queue_count; i++) {
2852 		r = _base_request_irq(ioc, i);
2853 		if (r) {
2854 			_base_free_irq(ioc);
2855 			_base_disable_msix(ioc);
2856 			goto try_ioapic;
2857 		}
2858 	}
2859 
2860 	return 0;
2861 
2862 /* failback to io_apic interrupt routing */
2863  try_ioapic:
2864 
2865 	ioc->reply_queue_count = 1;
2866 	r = pci_alloc_irq_vectors(ioc->pdev, 1, 1, PCI_IRQ_LEGACY);
2867 	if (r < 0) {
2868 		dfailprintk(ioc,
2869 			    ioc_info(ioc, "pci_alloc_irq_vector(legacy) failed (r=%d) !!!\n",
2870 				     r));
2871 	} else
2872 		r = _base_request_irq(ioc, 0);
2873 
2874 	return r;
2875 }
2876 
2877 /**
2878  * mpt3sas_base_unmap_resources - free controller resources
2879  * @ioc: per adapter object
2880  */
2881 static void
2882 mpt3sas_base_unmap_resources(struct MPT3SAS_ADAPTER *ioc)
2883 {
2884 	struct pci_dev *pdev = ioc->pdev;
2885 
2886 	dexitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
2887 
2888 	_base_free_irq(ioc);
2889 	_base_disable_msix(ioc);
2890 
2891 	kfree(ioc->replyPostRegisterIndex);
2892 	ioc->replyPostRegisterIndex = NULL;
2893 
2894 
2895 	if (ioc->chip_phys) {
2896 		iounmap(ioc->chip);
2897 		ioc->chip_phys = 0;
2898 	}
2899 
2900 	if (pci_is_enabled(pdev)) {
2901 		pci_release_selected_regions(ioc->pdev, ioc->bars);
2902 		pci_disable_pcie_error_reporting(pdev);
2903 		pci_disable_device(pdev);
2904 	}
2905 }
2906 
2907 /**
2908  * mpt3sas_base_map_resources - map in controller resources (io/irq/memap)
2909  * @ioc: per adapter object
2910  *
2911  * Return: 0 for success, non-zero for failure.
2912  */
2913 int
2914 mpt3sas_base_map_resources(struct MPT3SAS_ADAPTER *ioc)
2915 {
2916 	struct pci_dev *pdev = ioc->pdev;
2917 	u32 memap_sz;
2918 	u32 pio_sz;
2919 	int i, r = 0;
2920 	u64 pio_chip = 0;
2921 	phys_addr_t chip_phys = 0;
2922 	struct adapter_reply_queue *reply_q;
2923 
2924 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
2925 
2926 	ioc->bars = pci_select_bars(pdev, IORESOURCE_MEM);
2927 	if (pci_enable_device_mem(pdev)) {
2928 		ioc_warn(ioc, "pci_enable_device_mem: failed\n");
2929 		ioc->bars = 0;
2930 		return -ENODEV;
2931 	}
2932 
2933 
2934 	if (pci_request_selected_regions(pdev, ioc->bars,
2935 	    ioc->driver_name)) {
2936 		ioc_warn(ioc, "pci_request_selected_regions: failed\n");
2937 		ioc->bars = 0;
2938 		r = -ENODEV;
2939 		goto out_fail;
2940 	}
2941 
2942 /* AER (Advanced Error Reporting) hooks */
2943 	pci_enable_pcie_error_reporting(pdev);
2944 
2945 	pci_set_master(pdev);
2946 
2947 
2948 	if (_base_config_dma_addressing(ioc, pdev) != 0) {
2949 		ioc_warn(ioc, "no suitable DMA mask for %s\n", pci_name(pdev));
2950 		r = -ENODEV;
2951 		goto out_fail;
2952 	}
2953 
2954 	for (i = 0, memap_sz = 0, pio_sz = 0; (i < DEVICE_COUNT_RESOURCE) &&
2955 	     (!memap_sz || !pio_sz); i++) {
2956 		if (pci_resource_flags(pdev, i) & IORESOURCE_IO) {
2957 			if (pio_sz)
2958 				continue;
2959 			pio_chip = (u64)pci_resource_start(pdev, i);
2960 			pio_sz = pci_resource_len(pdev, i);
2961 		} else if (pci_resource_flags(pdev, i) & IORESOURCE_MEM) {
2962 			if (memap_sz)
2963 				continue;
2964 			ioc->chip_phys = pci_resource_start(pdev, i);
2965 			chip_phys = ioc->chip_phys;
2966 			memap_sz = pci_resource_len(pdev, i);
2967 			ioc->chip = ioremap(ioc->chip_phys, memap_sz);
2968 		}
2969 	}
2970 
2971 	if (ioc->chip == NULL) {
2972 		ioc_err(ioc, "unable to map adapter memory! or resource not found\n");
2973 		r = -EINVAL;
2974 		goto out_fail;
2975 	}
2976 
2977 	_base_mask_interrupts(ioc);
2978 
2979 	r = _base_get_ioc_facts(ioc);
2980 	if (r)
2981 		goto out_fail;
2982 
2983 	if (!ioc->rdpq_array_enable_assigned) {
2984 		ioc->rdpq_array_enable = ioc->rdpq_array_capable;
2985 		ioc->rdpq_array_enable_assigned = 1;
2986 	}
2987 
2988 	r = _base_enable_msix(ioc);
2989 	if (r)
2990 		goto out_fail;
2991 
2992 	/* Use the Combined reply queue feature only for SAS3 C0 & higher
2993 	 * revision HBAs and also only when reply queue count is greater than 8
2994 	 */
2995 	if (ioc->combined_reply_queue) {
2996 		/* Determine the Supplemental Reply Post Host Index Registers
2997 		 * Addresse. Supplemental Reply Post Host Index Registers
2998 		 * starts at offset MPI25_SUP_REPLY_POST_HOST_INDEX_OFFSET and
2999 		 * each register is at offset bytes of
3000 		 * MPT3_SUP_REPLY_POST_HOST_INDEX_REG_OFFSET from previous one.
3001 		 */
3002 		ioc->replyPostRegisterIndex = kcalloc(
3003 		     ioc->combined_reply_index_count,
3004 		     sizeof(resource_size_t *), GFP_KERNEL);
3005 		if (!ioc->replyPostRegisterIndex) {
3006 			dfailprintk(ioc,
3007 				    ioc_warn(ioc, "allocation for reply Post Register Index failed!!!\n"));
3008 			r = -ENOMEM;
3009 			goto out_fail;
3010 		}
3011 
3012 		for (i = 0; i < ioc->combined_reply_index_count; i++) {
3013 			ioc->replyPostRegisterIndex[i] = (resource_size_t *)
3014 			     ((u8 __force *)&ioc->chip->Doorbell +
3015 			     MPI25_SUP_REPLY_POST_HOST_INDEX_OFFSET +
3016 			     (i * MPT3_SUP_REPLY_POST_HOST_INDEX_REG_OFFSET));
3017 		}
3018 	}
3019 
3020 	if (ioc->is_warpdrive) {
3021 		ioc->reply_post_host_index[0] = (resource_size_t __iomem *)
3022 		    &ioc->chip->ReplyPostHostIndex;
3023 
3024 		for (i = 1; i < ioc->cpu_msix_table_sz; i++)
3025 			ioc->reply_post_host_index[i] =
3026 			(resource_size_t __iomem *)
3027 			((u8 __iomem *)&ioc->chip->Doorbell + (0x4000 + ((i - 1)
3028 			* 4)));
3029 	}
3030 
3031 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list)
3032 		pr_info("%s: %s enabled: IRQ %d\n",
3033 			reply_q->name,
3034 			ioc->msix_enable ? "PCI-MSI-X" : "IO-APIC",
3035 			pci_irq_vector(ioc->pdev, reply_q->msix_index));
3036 
3037 	ioc_info(ioc, "iomem(%pap), mapped(0x%p), size(%d)\n",
3038 		 &chip_phys, ioc->chip, memap_sz);
3039 	ioc_info(ioc, "ioport(0x%016llx), size(%d)\n",
3040 		 (unsigned long long)pio_chip, pio_sz);
3041 
3042 	/* Save PCI configuration state for recovery from PCI AER/EEH errors */
3043 	pci_save_state(pdev);
3044 	return 0;
3045 
3046  out_fail:
3047 	mpt3sas_base_unmap_resources(ioc);
3048 	return r;
3049 }
3050 
3051 /**
3052  * mpt3sas_base_get_msg_frame - obtain request mf pointer
3053  * @ioc: per adapter object
3054  * @smid: system request message index(smid zero is invalid)
3055  *
3056  * Return: virt pointer to message frame.
3057  */
3058 void *
3059 mpt3sas_base_get_msg_frame(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3060 {
3061 	return (void *)(ioc->request + (smid * ioc->request_sz));
3062 }
3063 
3064 /**
3065  * mpt3sas_base_get_sense_buffer - obtain a sense buffer virt addr
3066  * @ioc: per adapter object
3067  * @smid: system request message index
3068  *
3069  * Return: virt pointer to sense buffer.
3070  */
3071 void *
3072 mpt3sas_base_get_sense_buffer(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3073 {
3074 	return (void *)(ioc->sense + ((smid - 1) * SCSI_SENSE_BUFFERSIZE));
3075 }
3076 
3077 /**
3078  * mpt3sas_base_get_sense_buffer_dma - obtain a sense buffer dma addr
3079  * @ioc: per adapter object
3080  * @smid: system request message index
3081  *
3082  * Return: phys pointer to the low 32bit address of the sense buffer.
3083  */
3084 __le32
3085 mpt3sas_base_get_sense_buffer_dma(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3086 {
3087 	return cpu_to_le32(ioc->sense_dma + ((smid - 1) *
3088 	    SCSI_SENSE_BUFFERSIZE));
3089 }
3090 
3091 /**
3092  * mpt3sas_base_get_pcie_sgl - obtain a PCIe SGL virt addr
3093  * @ioc: per adapter object
3094  * @smid: system request message index
3095  *
3096  * Return: virt pointer to a PCIe SGL.
3097  */
3098 void *
3099 mpt3sas_base_get_pcie_sgl(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3100 {
3101 	return (void *)(ioc->pcie_sg_lookup[smid - 1].pcie_sgl);
3102 }
3103 
3104 /**
3105  * mpt3sas_base_get_pcie_sgl_dma - obtain a PCIe SGL dma addr
3106  * @ioc: per adapter object
3107  * @smid: system request message index
3108  *
3109  * Return: phys pointer to the address of the PCIe buffer.
3110  */
3111 dma_addr_t
3112 mpt3sas_base_get_pcie_sgl_dma(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3113 {
3114 	return ioc->pcie_sg_lookup[smid - 1].pcie_sgl_dma;
3115 }
3116 
3117 /**
3118  * mpt3sas_base_get_reply_virt_addr - obtain reply frames virt address
3119  * @ioc: per adapter object
3120  * @phys_addr: lower 32 physical addr of the reply
3121  *
3122  * Converts 32bit lower physical addr into a virt address.
3123  */
3124 void *
3125 mpt3sas_base_get_reply_virt_addr(struct MPT3SAS_ADAPTER *ioc, u32 phys_addr)
3126 {
3127 	if (!phys_addr)
3128 		return NULL;
3129 	return ioc->reply + (phys_addr - (u32)ioc->reply_dma);
3130 }
3131 
3132 static inline u8
3133 _base_get_msix_index(struct MPT3SAS_ADAPTER *ioc)
3134 {
3135 	return ioc->cpu_msix_table[raw_smp_processor_id()];
3136 }
3137 
3138 /**
3139  * mpt3sas_base_get_smid - obtain a free smid from internal queue
3140  * @ioc: per adapter object
3141  * @cb_idx: callback index
3142  *
3143  * Return: smid (zero is invalid)
3144  */
3145 u16
3146 mpt3sas_base_get_smid(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx)
3147 {
3148 	unsigned long flags;
3149 	struct request_tracker *request;
3150 	u16 smid;
3151 
3152 	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3153 	if (list_empty(&ioc->internal_free_list)) {
3154 		spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3155 		ioc_err(ioc, "%s: smid not available\n", __func__);
3156 		return 0;
3157 	}
3158 
3159 	request = list_entry(ioc->internal_free_list.next,
3160 	    struct request_tracker, tracker_list);
3161 	request->cb_idx = cb_idx;
3162 	smid = request->smid;
3163 	list_del(&request->tracker_list);
3164 	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3165 	return smid;
3166 }
3167 
3168 /**
3169  * mpt3sas_base_get_smid_scsiio - obtain a free smid from scsiio queue
3170  * @ioc: per adapter object
3171  * @cb_idx: callback index
3172  * @scmd: pointer to scsi command object
3173  *
3174  * Return: smid (zero is invalid)
3175  */
3176 u16
3177 mpt3sas_base_get_smid_scsiio(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx,
3178 	struct scsi_cmnd *scmd)
3179 {
3180 	struct scsiio_tracker *request = scsi_cmd_priv(scmd);
3181 	unsigned int tag = scmd->request->tag;
3182 	u16 smid;
3183 
3184 	smid = tag + 1;
3185 	request->cb_idx = cb_idx;
3186 	request->msix_io = _base_get_msix_index(ioc);
3187 	request->smid = smid;
3188 	INIT_LIST_HEAD(&request->chain_list);
3189 	return smid;
3190 }
3191 
3192 /**
3193  * mpt3sas_base_get_smid_hpr - obtain a free smid from hi-priority queue
3194  * @ioc: per adapter object
3195  * @cb_idx: callback index
3196  *
3197  * Return: smid (zero is invalid)
3198  */
3199 u16
3200 mpt3sas_base_get_smid_hpr(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx)
3201 {
3202 	unsigned long flags;
3203 	struct request_tracker *request;
3204 	u16 smid;
3205 
3206 	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3207 	if (list_empty(&ioc->hpr_free_list)) {
3208 		spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3209 		return 0;
3210 	}
3211 
3212 	request = list_entry(ioc->hpr_free_list.next,
3213 	    struct request_tracker, tracker_list);
3214 	request->cb_idx = cb_idx;
3215 	smid = request->smid;
3216 	list_del(&request->tracker_list);
3217 	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3218 	return smid;
3219 }
3220 
3221 static void
3222 _base_recovery_check(struct MPT3SAS_ADAPTER *ioc)
3223 {
3224 	/*
3225 	 * See _wait_for_commands_to_complete() call with regards to this code.
3226 	 */
3227 	if (ioc->shost_recovery && ioc->pending_io_count) {
3228 		ioc->pending_io_count = scsi_host_busy(ioc->shost);
3229 		if (ioc->pending_io_count == 0)
3230 			wake_up(&ioc->reset_wq);
3231 	}
3232 }
3233 
3234 void mpt3sas_base_clear_st(struct MPT3SAS_ADAPTER *ioc,
3235 			   struct scsiio_tracker *st)
3236 {
3237 	if (WARN_ON(st->smid == 0))
3238 		return;
3239 	st->cb_idx = 0xFF;
3240 	st->direct_io = 0;
3241 	atomic_set(&ioc->chain_lookup[st->smid - 1].chain_offset, 0);
3242 	st->smid = 0;
3243 }
3244 
3245 /**
3246  * mpt3sas_base_free_smid - put smid back on free_list
3247  * @ioc: per adapter object
3248  * @smid: system request message index
3249  */
3250 void
3251 mpt3sas_base_free_smid(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3252 {
3253 	unsigned long flags;
3254 	int i;
3255 
3256 	if (smid < ioc->hi_priority_smid) {
3257 		struct scsiio_tracker *st;
3258 
3259 		st = _get_st_from_smid(ioc, smid);
3260 		if (!st) {
3261 			_base_recovery_check(ioc);
3262 			return;
3263 		}
3264 		mpt3sas_base_clear_st(ioc, st);
3265 		_base_recovery_check(ioc);
3266 		return;
3267 	}
3268 
3269 	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3270 	if (smid < ioc->internal_smid) {
3271 		/* hi-priority */
3272 		i = smid - ioc->hi_priority_smid;
3273 		ioc->hpr_lookup[i].cb_idx = 0xFF;
3274 		list_add(&ioc->hpr_lookup[i].tracker_list, &ioc->hpr_free_list);
3275 	} else if (smid <= ioc->hba_queue_depth) {
3276 		/* internal queue */
3277 		i = smid - ioc->internal_smid;
3278 		ioc->internal_lookup[i].cb_idx = 0xFF;
3279 		list_add(&ioc->internal_lookup[i].tracker_list,
3280 		    &ioc->internal_free_list);
3281 	}
3282 	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3283 }
3284 
3285 /**
3286  * _base_mpi_ep_writeq - 32 bit write to MMIO
3287  * @b: data payload
3288  * @addr: address in MMIO space
3289  * @writeq_lock: spin lock
3290  *
3291  * This special handling for MPI EP to take care of 32 bit
3292  * environment where its not quarenteed to send the entire word
3293  * in one transfer.
3294  */
3295 static inline void
3296 _base_mpi_ep_writeq(__u64 b, volatile void __iomem *addr,
3297 					spinlock_t *writeq_lock)
3298 {
3299 	unsigned long flags;
3300 
3301 	spin_lock_irqsave(writeq_lock, flags);
3302 	__raw_writel((u32)(b), addr);
3303 	__raw_writel((u32)(b >> 32), (addr + 4));
3304 	mmiowb();
3305 	spin_unlock_irqrestore(writeq_lock, flags);
3306 }
3307 
3308 /**
3309  * _base_writeq - 64 bit write to MMIO
3310  * @b: data payload
3311  * @addr: address in MMIO space
3312  * @writeq_lock: spin lock
3313  *
3314  * Glue for handling an atomic 64 bit word to MMIO. This special handling takes
3315  * care of 32 bit environment where its not quarenteed to send the entire word
3316  * in one transfer.
3317  */
3318 #if defined(writeq) && defined(CONFIG_64BIT)
3319 static inline void
3320 _base_writeq(__u64 b, volatile void __iomem *addr, spinlock_t *writeq_lock)
3321 {
3322 	__raw_writeq(b, addr);
3323 	mmiowb();
3324 }
3325 #else
3326 static inline void
3327 _base_writeq(__u64 b, volatile void __iomem *addr, spinlock_t *writeq_lock)
3328 {
3329 	_base_mpi_ep_writeq(b, addr, writeq_lock);
3330 }
3331 #endif
3332 
3333 /**
3334  * _base_put_smid_mpi_ep_scsi_io - send SCSI_IO request to firmware
3335  * @ioc: per adapter object
3336  * @smid: system request message index
3337  * @handle: device handle
3338  */
3339 static void
3340 _base_put_smid_mpi_ep_scsi_io(struct MPT3SAS_ADAPTER *ioc, u16 smid, u16 handle)
3341 {
3342 	Mpi2RequestDescriptorUnion_t descriptor;
3343 	u64 *request = (u64 *)&descriptor;
3344 	void *mpi_req_iomem;
3345 	__le32 *mfp = (__le32 *)mpt3sas_base_get_msg_frame(ioc, smid);
3346 
3347 	_clone_sg_entries(ioc, (void *) mfp, smid);
3348 	mpi_req_iomem = (void __force *)ioc->chip +
3349 			MPI_FRAME_START_OFFSET + (smid * ioc->request_sz);
3350 	_base_clone_mpi_to_sys_mem(mpi_req_iomem, (void *)mfp,
3351 					ioc->request_sz);
3352 	descriptor.SCSIIO.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
3353 	descriptor.SCSIIO.MSIxIndex =  _base_get_msix_index(ioc);
3354 	descriptor.SCSIIO.SMID = cpu_to_le16(smid);
3355 	descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
3356 	descriptor.SCSIIO.LMID = 0;
3357 	_base_mpi_ep_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3358 	    &ioc->scsi_lookup_lock);
3359 }
3360 
3361 /**
3362  * _base_put_smid_scsi_io - send SCSI_IO request to firmware
3363  * @ioc: per adapter object
3364  * @smid: system request message index
3365  * @handle: device handle
3366  */
3367 static void
3368 _base_put_smid_scsi_io(struct MPT3SAS_ADAPTER *ioc, u16 smid, u16 handle)
3369 {
3370 	Mpi2RequestDescriptorUnion_t descriptor;
3371 	u64 *request = (u64 *)&descriptor;
3372 
3373 
3374 	descriptor.SCSIIO.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
3375 	descriptor.SCSIIO.MSIxIndex =  _base_get_msix_index(ioc);
3376 	descriptor.SCSIIO.SMID = cpu_to_le16(smid);
3377 	descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
3378 	descriptor.SCSIIO.LMID = 0;
3379 	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3380 	    &ioc->scsi_lookup_lock);
3381 }
3382 
3383 /**
3384  * mpt3sas_base_put_smid_fast_path - send fast path request to firmware
3385  * @ioc: per adapter object
3386  * @smid: system request message index
3387  * @handle: device handle
3388  */
3389 void
3390 mpt3sas_base_put_smid_fast_path(struct MPT3SAS_ADAPTER *ioc, u16 smid,
3391 	u16 handle)
3392 {
3393 	Mpi2RequestDescriptorUnion_t descriptor;
3394 	u64 *request = (u64 *)&descriptor;
3395 
3396 	descriptor.SCSIIO.RequestFlags =
3397 	    MPI25_REQ_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO;
3398 	descriptor.SCSIIO.MSIxIndex = _base_get_msix_index(ioc);
3399 	descriptor.SCSIIO.SMID = cpu_to_le16(smid);
3400 	descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
3401 	descriptor.SCSIIO.LMID = 0;
3402 	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3403 	    &ioc->scsi_lookup_lock);
3404 }
3405 
3406 /**
3407  * mpt3sas_base_put_smid_hi_priority - send Task Management request to firmware
3408  * @ioc: per adapter object
3409  * @smid: system request message index
3410  * @msix_task: msix_task will be same as msix of IO incase of task abort else 0.
3411  */
3412 void
3413 mpt3sas_base_put_smid_hi_priority(struct MPT3SAS_ADAPTER *ioc, u16 smid,
3414 	u16 msix_task)
3415 {
3416 	Mpi2RequestDescriptorUnion_t descriptor;
3417 	void *mpi_req_iomem;
3418 	u64 *request;
3419 
3420 	if (ioc->is_mcpu_endpoint) {
3421 		__le32 *mfp = (__le32 *)mpt3sas_base_get_msg_frame(ioc, smid);
3422 
3423 		/* TBD 256 is offset within sys register. */
3424 		mpi_req_iomem = (void __force *)ioc->chip
3425 					+ MPI_FRAME_START_OFFSET
3426 					+ (smid * ioc->request_sz);
3427 		_base_clone_mpi_to_sys_mem(mpi_req_iomem, (void *)mfp,
3428 							ioc->request_sz);
3429 	}
3430 
3431 	request = (u64 *)&descriptor;
3432 
3433 	descriptor.HighPriority.RequestFlags =
3434 	    MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY;
3435 	descriptor.HighPriority.MSIxIndex =  msix_task;
3436 	descriptor.HighPriority.SMID = cpu_to_le16(smid);
3437 	descriptor.HighPriority.LMID = 0;
3438 	descriptor.HighPriority.Reserved1 = 0;
3439 	if (ioc->is_mcpu_endpoint)
3440 		_base_mpi_ep_writeq(*request,
3441 				&ioc->chip->RequestDescriptorPostLow,
3442 				&ioc->scsi_lookup_lock);
3443 	else
3444 		_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3445 		    &ioc->scsi_lookup_lock);
3446 }
3447 
3448 /**
3449  * mpt3sas_base_put_smid_nvme_encap - send NVMe encapsulated request to
3450  *  firmware
3451  * @ioc: per adapter object
3452  * @smid: system request message index
3453  */
3454 void
3455 mpt3sas_base_put_smid_nvme_encap(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3456 {
3457 	Mpi2RequestDescriptorUnion_t descriptor;
3458 	u64 *request = (u64 *)&descriptor;
3459 
3460 	descriptor.Default.RequestFlags =
3461 		MPI26_REQ_DESCRIPT_FLAGS_PCIE_ENCAPSULATED;
3462 	descriptor.Default.MSIxIndex =  _base_get_msix_index(ioc);
3463 	descriptor.Default.SMID = cpu_to_le16(smid);
3464 	descriptor.Default.LMID = 0;
3465 	descriptor.Default.DescriptorTypeDependent = 0;
3466 	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3467 	    &ioc->scsi_lookup_lock);
3468 }
3469 
3470 /**
3471  * mpt3sas_base_put_smid_default - Default, primarily used for config pages
3472  * @ioc: per adapter object
3473  * @smid: system request message index
3474  */
3475 void
3476 mpt3sas_base_put_smid_default(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3477 {
3478 	Mpi2RequestDescriptorUnion_t descriptor;
3479 	void *mpi_req_iomem;
3480 	u64 *request;
3481 
3482 	if (ioc->is_mcpu_endpoint) {
3483 		__le32 *mfp = (__le32 *)mpt3sas_base_get_msg_frame(ioc, smid);
3484 
3485 		_clone_sg_entries(ioc, (void *) mfp, smid);
3486 		/* TBD 256 is offset within sys register */
3487 		mpi_req_iomem = (void __force *)ioc->chip +
3488 			MPI_FRAME_START_OFFSET + (smid * ioc->request_sz);
3489 		_base_clone_mpi_to_sys_mem(mpi_req_iomem, (void *)mfp,
3490 							ioc->request_sz);
3491 	}
3492 	request = (u64 *)&descriptor;
3493 	descriptor.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
3494 	descriptor.Default.MSIxIndex =  _base_get_msix_index(ioc);
3495 	descriptor.Default.SMID = cpu_to_le16(smid);
3496 	descriptor.Default.LMID = 0;
3497 	descriptor.Default.DescriptorTypeDependent = 0;
3498 	if (ioc->is_mcpu_endpoint)
3499 		_base_mpi_ep_writeq(*request,
3500 				&ioc->chip->RequestDescriptorPostLow,
3501 				&ioc->scsi_lookup_lock);
3502 	else
3503 		_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3504 				&ioc->scsi_lookup_lock);
3505 }
3506 
3507 /**
3508  * _base_display_OEMs_branding - Display branding string
3509  * @ioc: per adapter object
3510  */
3511 static void
3512 _base_display_OEMs_branding(struct MPT3SAS_ADAPTER *ioc)
3513 {
3514 	if (ioc->pdev->subsystem_vendor != PCI_VENDOR_ID_INTEL)
3515 		return;
3516 
3517 	switch (ioc->pdev->subsystem_vendor) {
3518 	case PCI_VENDOR_ID_INTEL:
3519 		switch (ioc->pdev->device) {
3520 		case MPI2_MFGPAGE_DEVID_SAS2008:
3521 			switch (ioc->pdev->subsystem_device) {
3522 			case MPT2SAS_INTEL_RMS2LL080_SSDID:
3523 				ioc_info(ioc, "%s\n",
3524 					 MPT2SAS_INTEL_RMS2LL080_BRANDING);
3525 				break;
3526 			case MPT2SAS_INTEL_RMS2LL040_SSDID:
3527 				ioc_info(ioc, "%s\n",
3528 					 MPT2SAS_INTEL_RMS2LL040_BRANDING);
3529 				break;
3530 			case MPT2SAS_INTEL_SSD910_SSDID:
3531 				ioc_info(ioc, "%s\n",
3532 					 MPT2SAS_INTEL_SSD910_BRANDING);
3533 				break;
3534 			default:
3535 				ioc_info(ioc, "Intel(R) Controller: Subsystem ID: 0x%X\n",
3536 					 ioc->pdev->subsystem_device);
3537 				break;
3538 			}
3539 		case MPI2_MFGPAGE_DEVID_SAS2308_2:
3540 			switch (ioc->pdev->subsystem_device) {
3541 			case MPT2SAS_INTEL_RS25GB008_SSDID:
3542 				ioc_info(ioc, "%s\n",
3543 					 MPT2SAS_INTEL_RS25GB008_BRANDING);
3544 				break;
3545 			case MPT2SAS_INTEL_RMS25JB080_SSDID:
3546 				ioc_info(ioc, "%s\n",
3547 					 MPT2SAS_INTEL_RMS25JB080_BRANDING);
3548 				break;
3549 			case MPT2SAS_INTEL_RMS25JB040_SSDID:
3550 				ioc_info(ioc, "%s\n",
3551 					 MPT2SAS_INTEL_RMS25JB040_BRANDING);
3552 				break;
3553 			case MPT2SAS_INTEL_RMS25KB080_SSDID:
3554 				ioc_info(ioc, "%s\n",
3555 					 MPT2SAS_INTEL_RMS25KB080_BRANDING);
3556 				break;
3557 			case MPT2SAS_INTEL_RMS25KB040_SSDID:
3558 				ioc_info(ioc, "%s\n",
3559 					 MPT2SAS_INTEL_RMS25KB040_BRANDING);
3560 				break;
3561 			case MPT2SAS_INTEL_RMS25LB040_SSDID:
3562 				ioc_info(ioc, "%s\n",
3563 					 MPT2SAS_INTEL_RMS25LB040_BRANDING);
3564 				break;
3565 			case MPT2SAS_INTEL_RMS25LB080_SSDID:
3566 				ioc_info(ioc, "%s\n",
3567 					 MPT2SAS_INTEL_RMS25LB080_BRANDING);
3568 				break;
3569 			default:
3570 				ioc_info(ioc, "Intel(R) Controller: Subsystem ID: 0x%X\n",
3571 					 ioc->pdev->subsystem_device);
3572 				break;
3573 			}
3574 		case MPI25_MFGPAGE_DEVID_SAS3008:
3575 			switch (ioc->pdev->subsystem_device) {
3576 			case MPT3SAS_INTEL_RMS3JC080_SSDID:
3577 				ioc_info(ioc, "%s\n",
3578 					 MPT3SAS_INTEL_RMS3JC080_BRANDING);
3579 				break;
3580 
3581 			case MPT3SAS_INTEL_RS3GC008_SSDID:
3582 				ioc_info(ioc, "%s\n",
3583 					 MPT3SAS_INTEL_RS3GC008_BRANDING);
3584 				break;
3585 			case MPT3SAS_INTEL_RS3FC044_SSDID:
3586 				ioc_info(ioc, "%s\n",
3587 					 MPT3SAS_INTEL_RS3FC044_BRANDING);
3588 				break;
3589 			case MPT3SAS_INTEL_RS3UC080_SSDID:
3590 				ioc_info(ioc, "%s\n",
3591 					 MPT3SAS_INTEL_RS3UC080_BRANDING);
3592 				break;
3593 			default:
3594 				ioc_info(ioc, "Intel(R) Controller: Subsystem ID: 0x%X\n",
3595 					 ioc->pdev->subsystem_device);
3596 				break;
3597 			}
3598 			break;
3599 		default:
3600 			ioc_info(ioc, "Intel(R) Controller: Subsystem ID: 0x%X\n",
3601 				 ioc->pdev->subsystem_device);
3602 			break;
3603 		}
3604 		break;
3605 	case PCI_VENDOR_ID_DELL:
3606 		switch (ioc->pdev->device) {
3607 		case MPI2_MFGPAGE_DEVID_SAS2008:
3608 			switch (ioc->pdev->subsystem_device) {
3609 			case MPT2SAS_DELL_6GBPS_SAS_HBA_SSDID:
3610 				ioc_info(ioc, "%s\n",
3611 					 MPT2SAS_DELL_6GBPS_SAS_HBA_BRANDING);
3612 				break;
3613 			case MPT2SAS_DELL_PERC_H200_ADAPTER_SSDID:
3614 				ioc_info(ioc, "%s\n",
3615 					 MPT2SAS_DELL_PERC_H200_ADAPTER_BRANDING);
3616 				break;
3617 			case MPT2SAS_DELL_PERC_H200_INTEGRATED_SSDID:
3618 				ioc_info(ioc, "%s\n",
3619 					 MPT2SAS_DELL_PERC_H200_INTEGRATED_BRANDING);
3620 				break;
3621 			case MPT2SAS_DELL_PERC_H200_MODULAR_SSDID:
3622 				ioc_info(ioc, "%s\n",
3623 					 MPT2SAS_DELL_PERC_H200_MODULAR_BRANDING);
3624 				break;
3625 			case MPT2SAS_DELL_PERC_H200_EMBEDDED_SSDID:
3626 				ioc_info(ioc, "%s\n",
3627 					 MPT2SAS_DELL_PERC_H200_EMBEDDED_BRANDING);
3628 				break;
3629 			case MPT2SAS_DELL_PERC_H200_SSDID:
3630 				ioc_info(ioc, "%s\n",
3631 					 MPT2SAS_DELL_PERC_H200_BRANDING);
3632 				break;
3633 			case MPT2SAS_DELL_6GBPS_SAS_SSDID:
3634 				ioc_info(ioc, "%s\n",
3635 					 MPT2SAS_DELL_6GBPS_SAS_BRANDING);
3636 				break;
3637 			default:
3638 				ioc_info(ioc, "Dell 6Gbps HBA: Subsystem ID: 0x%X\n",
3639 					 ioc->pdev->subsystem_device);
3640 				break;
3641 			}
3642 			break;
3643 		case MPI25_MFGPAGE_DEVID_SAS3008:
3644 			switch (ioc->pdev->subsystem_device) {
3645 			case MPT3SAS_DELL_12G_HBA_SSDID:
3646 				ioc_info(ioc, "%s\n",
3647 					 MPT3SAS_DELL_12G_HBA_BRANDING);
3648 				break;
3649 			default:
3650 				ioc_info(ioc, "Dell 12Gbps HBA: Subsystem ID: 0x%X\n",
3651 					 ioc->pdev->subsystem_device);
3652 				break;
3653 			}
3654 			break;
3655 		default:
3656 			ioc_info(ioc, "Dell HBA: Subsystem ID: 0x%X\n",
3657 				 ioc->pdev->subsystem_device);
3658 			break;
3659 		}
3660 		break;
3661 	case PCI_VENDOR_ID_CISCO:
3662 		switch (ioc->pdev->device) {
3663 		case MPI25_MFGPAGE_DEVID_SAS3008:
3664 			switch (ioc->pdev->subsystem_device) {
3665 			case MPT3SAS_CISCO_12G_8E_HBA_SSDID:
3666 				ioc_info(ioc, "%s\n",
3667 					 MPT3SAS_CISCO_12G_8E_HBA_BRANDING);
3668 				break;
3669 			case MPT3SAS_CISCO_12G_8I_HBA_SSDID:
3670 				ioc_info(ioc, "%s\n",
3671 					 MPT3SAS_CISCO_12G_8I_HBA_BRANDING);
3672 				break;
3673 			case MPT3SAS_CISCO_12G_AVILA_HBA_SSDID:
3674 				ioc_info(ioc, "%s\n",
3675 					 MPT3SAS_CISCO_12G_AVILA_HBA_BRANDING);
3676 				break;
3677 			default:
3678 				ioc_info(ioc, "Cisco 12Gbps SAS HBA: Subsystem ID: 0x%X\n",
3679 					 ioc->pdev->subsystem_device);
3680 				break;
3681 			}
3682 			break;
3683 		case MPI25_MFGPAGE_DEVID_SAS3108_1:
3684 			switch (ioc->pdev->subsystem_device) {
3685 			case MPT3SAS_CISCO_12G_AVILA_HBA_SSDID:
3686 				ioc_info(ioc, "%s\n",
3687 					 MPT3SAS_CISCO_12G_AVILA_HBA_BRANDING);
3688 				break;
3689 			case MPT3SAS_CISCO_12G_COLUSA_MEZZANINE_HBA_SSDID:
3690 				ioc_info(ioc, "%s\n",
3691 					 MPT3SAS_CISCO_12G_COLUSA_MEZZANINE_HBA_BRANDING);
3692 				break;
3693 			default:
3694 				ioc_info(ioc, "Cisco 12Gbps SAS HBA: Subsystem ID: 0x%X\n",
3695 					 ioc->pdev->subsystem_device);
3696 				break;
3697 			}
3698 			break;
3699 		default:
3700 			ioc_info(ioc, "Cisco SAS HBA: Subsystem ID: 0x%X\n",
3701 				 ioc->pdev->subsystem_device);
3702 			break;
3703 		}
3704 		break;
3705 	case MPT2SAS_HP_3PAR_SSVID:
3706 		switch (ioc->pdev->device) {
3707 		case MPI2_MFGPAGE_DEVID_SAS2004:
3708 			switch (ioc->pdev->subsystem_device) {
3709 			case MPT2SAS_HP_DAUGHTER_2_4_INTERNAL_SSDID:
3710 				ioc_info(ioc, "%s\n",
3711 					 MPT2SAS_HP_DAUGHTER_2_4_INTERNAL_BRANDING);
3712 				break;
3713 			default:
3714 				ioc_info(ioc, "HP 6Gbps SAS HBA: Subsystem ID: 0x%X\n",
3715 					 ioc->pdev->subsystem_device);
3716 				break;
3717 			}
3718 		case MPI2_MFGPAGE_DEVID_SAS2308_2:
3719 			switch (ioc->pdev->subsystem_device) {
3720 			case MPT2SAS_HP_2_4_INTERNAL_SSDID:
3721 				ioc_info(ioc, "%s\n",
3722 					 MPT2SAS_HP_2_4_INTERNAL_BRANDING);
3723 				break;
3724 			case MPT2SAS_HP_2_4_EXTERNAL_SSDID:
3725 				ioc_info(ioc, "%s\n",
3726 					 MPT2SAS_HP_2_4_EXTERNAL_BRANDING);
3727 				break;
3728 			case MPT2SAS_HP_1_4_INTERNAL_1_4_EXTERNAL_SSDID:
3729 				ioc_info(ioc, "%s\n",
3730 					 MPT2SAS_HP_1_4_INTERNAL_1_4_EXTERNAL_BRANDING);
3731 				break;
3732 			case MPT2SAS_HP_EMBEDDED_2_4_INTERNAL_SSDID:
3733 				ioc_info(ioc, "%s\n",
3734 					 MPT2SAS_HP_EMBEDDED_2_4_INTERNAL_BRANDING);
3735 				break;
3736 			default:
3737 				ioc_info(ioc, "HP 6Gbps SAS HBA: Subsystem ID: 0x%X\n",
3738 					 ioc->pdev->subsystem_device);
3739 				break;
3740 			}
3741 		default:
3742 			ioc_info(ioc, "HP SAS HBA: Subsystem ID: 0x%X\n",
3743 				 ioc->pdev->subsystem_device);
3744 			break;
3745 		}
3746 	default:
3747 		break;
3748 	}
3749 }
3750 
3751 /**
3752  * _base_display_fwpkg_version - sends FWUpload request to pull FWPkg
3753  *				version from FW Image Header.
3754  * @ioc: per adapter object
3755  *
3756  * Return: 0 for success, non-zero for failure.
3757  */
3758 	static int
3759 _base_display_fwpkg_version(struct MPT3SAS_ADAPTER *ioc)
3760 {
3761 	Mpi2FWImageHeader_t *FWImgHdr;
3762 	Mpi25FWUploadRequest_t *mpi_request;
3763 	Mpi2FWUploadReply_t mpi_reply;
3764 	int r = 0;
3765 	void *fwpkg_data = NULL;
3766 	dma_addr_t fwpkg_data_dma;
3767 	u16 smid, ioc_status;
3768 	size_t data_length;
3769 
3770 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
3771 
3772 	if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
3773 		ioc_err(ioc, "%s: internal command already in use\n", __func__);
3774 		return -EAGAIN;
3775 	}
3776 
3777 	data_length = sizeof(Mpi2FWImageHeader_t);
3778 	fwpkg_data = dma_alloc_coherent(&ioc->pdev->dev, data_length,
3779 			&fwpkg_data_dma, GFP_KERNEL);
3780 	if (!fwpkg_data) {
3781 		ioc_err(ioc, "failure at %s:%d/%s()!\n",
3782 			__FILE__, __LINE__, __func__);
3783 		return -ENOMEM;
3784 	}
3785 
3786 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
3787 	if (!smid) {
3788 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
3789 		r = -EAGAIN;
3790 		goto out;
3791 	}
3792 
3793 	ioc->base_cmds.status = MPT3_CMD_PENDING;
3794 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
3795 	ioc->base_cmds.smid = smid;
3796 	memset(mpi_request, 0, sizeof(Mpi25FWUploadRequest_t));
3797 	mpi_request->Function = MPI2_FUNCTION_FW_UPLOAD;
3798 	mpi_request->ImageType = MPI2_FW_UPLOAD_ITYPE_FW_FLASH;
3799 	mpi_request->ImageSize = cpu_to_le32(data_length);
3800 	ioc->build_sg(ioc, &mpi_request->SGL, 0, 0, fwpkg_data_dma,
3801 			data_length);
3802 	init_completion(&ioc->base_cmds.done);
3803 	mpt3sas_base_put_smid_default(ioc, smid);
3804 	/* Wait for 15 seconds */
3805 	wait_for_completion_timeout(&ioc->base_cmds.done,
3806 			FW_IMG_HDR_READ_TIMEOUT*HZ);
3807 	ioc_info(ioc, "%s: complete\n", __func__);
3808 	if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
3809 		ioc_err(ioc, "%s: timeout\n", __func__);
3810 		_debug_dump_mf(mpi_request,
3811 				sizeof(Mpi25FWUploadRequest_t)/4);
3812 		r = -ETIME;
3813 	} else {
3814 		memset(&mpi_reply, 0, sizeof(Mpi2FWUploadReply_t));
3815 		if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID) {
3816 			memcpy(&mpi_reply, ioc->base_cmds.reply,
3817 					sizeof(Mpi2FWUploadReply_t));
3818 			ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
3819 						MPI2_IOCSTATUS_MASK;
3820 			if (ioc_status == MPI2_IOCSTATUS_SUCCESS) {
3821 				FWImgHdr = (Mpi2FWImageHeader_t *)fwpkg_data;
3822 				if (FWImgHdr->PackageVersion.Word) {
3823 					ioc_info(ioc, "FW Package Version (%02d.%02d.%02d.%02d)\n",
3824 						 FWImgHdr->PackageVersion.Struct.Major,
3825 						 FWImgHdr->PackageVersion.Struct.Minor,
3826 						 FWImgHdr->PackageVersion.Struct.Unit,
3827 						 FWImgHdr->PackageVersion.Struct.Dev);
3828 				}
3829 			} else {
3830 				_debug_dump_mf(&mpi_reply,
3831 						sizeof(Mpi2FWUploadReply_t)/4);
3832 			}
3833 		}
3834 	}
3835 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
3836 out:
3837 	if (fwpkg_data)
3838 		dma_free_coherent(&ioc->pdev->dev, data_length, fwpkg_data,
3839 				fwpkg_data_dma);
3840 	return r;
3841 }
3842 
3843 /**
3844  * _base_display_ioc_capabilities - Disply IOC's capabilities.
3845  * @ioc: per adapter object
3846  */
3847 static void
3848 _base_display_ioc_capabilities(struct MPT3SAS_ADAPTER *ioc)
3849 {
3850 	int i = 0;
3851 	char desc[16];
3852 	u32 iounit_pg1_flags;
3853 	u32 bios_version;
3854 
3855 	bios_version = le32_to_cpu(ioc->bios_pg3.BiosVersion);
3856 	strncpy(desc, ioc->manu_pg0.ChipName, 16);
3857 	ioc_info(ioc, "%s: FWVersion(%02d.%02d.%02d.%02d), ChipRevision(0x%02x), BiosVersion(%02d.%02d.%02d.%02d)\n",
3858 		 desc,
3859 		 (ioc->facts.FWVersion.Word & 0xFF000000) >> 24,
3860 		 (ioc->facts.FWVersion.Word & 0x00FF0000) >> 16,
3861 		 (ioc->facts.FWVersion.Word & 0x0000FF00) >> 8,
3862 		 ioc->facts.FWVersion.Word & 0x000000FF,
3863 		 ioc->pdev->revision,
3864 		 (bios_version & 0xFF000000) >> 24,
3865 		 (bios_version & 0x00FF0000) >> 16,
3866 		 (bios_version & 0x0000FF00) >> 8,
3867 		 bios_version & 0x000000FF);
3868 
3869 	_base_display_OEMs_branding(ioc);
3870 
3871 	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_NVME_DEVICES) {
3872 		pr_info("%sNVMe", i ? "," : "");
3873 		i++;
3874 	}
3875 
3876 	ioc_info(ioc, "Protocol=(");
3877 
3878 	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_INITIATOR) {
3879 		pr_cont("Initiator");
3880 		i++;
3881 	}
3882 
3883 	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_TARGET) {
3884 		pr_cont("%sTarget", i ? "," : "");
3885 		i++;
3886 	}
3887 
3888 	i = 0;
3889 	pr_cont("), Capabilities=(");
3890 
3891 	if (!ioc->hide_ir_msg) {
3892 		if (ioc->facts.IOCCapabilities &
3893 		    MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID) {
3894 			pr_cont("Raid");
3895 			i++;
3896 		}
3897 	}
3898 
3899 	if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR) {
3900 		pr_cont("%sTLR", i ? "," : "");
3901 		i++;
3902 	}
3903 
3904 	if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_MULTICAST) {
3905 		pr_cont("%sMulticast", i ? "," : "");
3906 		i++;
3907 	}
3908 
3909 	if (ioc->facts.IOCCapabilities &
3910 	    MPI2_IOCFACTS_CAPABILITY_BIDIRECTIONAL_TARGET) {
3911 		pr_cont("%sBIDI Target", i ? "," : "");
3912 		i++;
3913 	}
3914 
3915 	if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP) {
3916 		pr_cont("%sEEDP", i ? "," : "");
3917 		i++;
3918 	}
3919 
3920 	if (ioc->facts.IOCCapabilities &
3921 	    MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER) {
3922 		pr_cont("%sSnapshot Buffer", i ? "," : "");
3923 		i++;
3924 	}
3925 
3926 	if (ioc->facts.IOCCapabilities &
3927 	    MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER) {
3928 		pr_cont("%sDiag Trace Buffer", i ? "," : "");
3929 		i++;
3930 	}
3931 
3932 	if (ioc->facts.IOCCapabilities &
3933 	    MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER) {
3934 		pr_cont("%sDiag Extended Buffer", i ? "," : "");
3935 		i++;
3936 	}
3937 
3938 	if (ioc->facts.IOCCapabilities &
3939 	    MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING) {
3940 		pr_cont("%sTask Set Full", i ? "," : "");
3941 		i++;
3942 	}
3943 
3944 	iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
3945 	if (!(iounit_pg1_flags & MPI2_IOUNITPAGE1_NATIVE_COMMAND_Q_DISABLE)) {
3946 		pr_cont("%sNCQ", i ? "," : "");
3947 		i++;
3948 	}
3949 
3950 	pr_cont(")\n");
3951 }
3952 
3953 /**
3954  * mpt3sas_base_update_missing_delay - change the missing delay timers
3955  * @ioc: per adapter object
3956  * @device_missing_delay: amount of time till device is reported missing
3957  * @io_missing_delay: interval IO is returned when there is a missing device
3958  *
3959  * Passed on the command line, this function will modify the device missing
3960  * delay, as well as the io missing delay. This should be called at driver
3961  * load time.
3962  */
3963 void
3964 mpt3sas_base_update_missing_delay(struct MPT3SAS_ADAPTER *ioc,
3965 	u16 device_missing_delay, u8 io_missing_delay)
3966 {
3967 	u16 dmd, dmd_new, dmd_orignal;
3968 	u8 io_missing_delay_original;
3969 	u16 sz;
3970 	Mpi2SasIOUnitPage1_t *sas_iounit_pg1 = NULL;
3971 	Mpi2ConfigReply_t mpi_reply;
3972 	u8 num_phys = 0;
3973 	u16 ioc_status;
3974 
3975 	mpt3sas_config_get_number_hba_phys(ioc, &num_phys);
3976 	if (!num_phys)
3977 		return;
3978 
3979 	sz = offsetof(Mpi2SasIOUnitPage1_t, PhyData) + (num_phys *
3980 	    sizeof(Mpi2SasIOUnit1PhyData_t));
3981 	sas_iounit_pg1 = kzalloc(sz, GFP_KERNEL);
3982 	if (!sas_iounit_pg1) {
3983 		ioc_err(ioc, "failure at %s:%d/%s()!\n",
3984 			__FILE__, __LINE__, __func__);
3985 		goto out;
3986 	}
3987 	if ((mpt3sas_config_get_sas_iounit_pg1(ioc, &mpi_reply,
3988 	    sas_iounit_pg1, sz))) {
3989 		ioc_err(ioc, "failure at %s:%d/%s()!\n",
3990 			__FILE__, __LINE__, __func__);
3991 		goto out;
3992 	}
3993 	ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
3994 	    MPI2_IOCSTATUS_MASK;
3995 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
3996 		ioc_err(ioc, "failure at %s:%d/%s()!\n",
3997 			__FILE__, __LINE__, __func__);
3998 		goto out;
3999 	}
4000 
4001 	/* device missing delay */
4002 	dmd = sas_iounit_pg1->ReportDeviceMissingDelay;
4003 	if (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16)
4004 		dmd = (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK) * 16;
4005 	else
4006 		dmd = dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK;
4007 	dmd_orignal = dmd;
4008 	if (device_missing_delay > 0x7F) {
4009 		dmd = (device_missing_delay > 0x7F0) ? 0x7F0 :
4010 		    device_missing_delay;
4011 		dmd = dmd / 16;
4012 		dmd |= MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16;
4013 	} else
4014 		dmd = device_missing_delay;
4015 	sas_iounit_pg1->ReportDeviceMissingDelay = dmd;
4016 
4017 	/* io missing delay */
4018 	io_missing_delay_original = sas_iounit_pg1->IODeviceMissingDelay;
4019 	sas_iounit_pg1->IODeviceMissingDelay = io_missing_delay;
4020 
4021 	if (!mpt3sas_config_set_sas_iounit_pg1(ioc, &mpi_reply, sas_iounit_pg1,
4022 	    sz)) {
4023 		if (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16)
4024 			dmd_new = (dmd &
4025 			    MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK) * 16;
4026 		else
4027 			dmd_new =
4028 		    dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK;
4029 		ioc_info(ioc, "device_missing_delay: old(%d), new(%d)\n",
4030 			 dmd_orignal, dmd_new);
4031 		ioc_info(ioc, "ioc_missing_delay: old(%d), new(%d)\n",
4032 			 io_missing_delay_original,
4033 			 io_missing_delay);
4034 		ioc->device_missing_delay = dmd_new;
4035 		ioc->io_missing_delay = io_missing_delay;
4036 	}
4037 
4038 out:
4039 	kfree(sas_iounit_pg1);
4040 }
4041 
4042 /**
4043  * _base_static_config_pages - static start of day config pages
4044  * @ioc: per adapter object
4045  */
4046 static void
4047 _base_static_config_pages(struct MPT3SAS_ADAPTER *ioc)
4048 {
4049 	Mpi2ConfigReply_t mpi_reply;
4050 	u32 iounit_pg1_flags;
4051 
4052 	ioc->nvme_abort_timeout = 30;
4053 	mpt3sas_config_get_manufacturing_pg0(ioc, &mpi_reply, &ioc->manu_pg0);
4054 	if (ioc->ir_firmware)
4055 		mpt3sas_config_get_manufacturing_pg10(ioc, &mpi_reply,
4056 		    &ioc->manu_pg10);
4057 
4058 	/*
4059 	 * Ensure correct T10 PI operation if vendor left EEDPTagMode
4060 	 * flag unset in NVDATA.
4061 	 */
4062 	mpt3sas_config_get_manufacturing_pg11(ioc, &mpi_reply, &ioc->manu_pg11);
4063 	if (ioc->manu_pg11.EEDPTagMode == 0) {
4064 		pr_err("%s: overriding NVDATA EEDPTagMode setting\n",
4065 		    ioc->name);
4066 		ioc->manu_pg11.EEDPTagMode &= ~0x3;
4067 		ioc->manu_pg11.EEDPTagMode |= 0x1;
4068 		mpt3sas_config_set_manufacturing_pg11(ioc, &mpi_reply,
4069 		    &ioc->manu_pg11);
4070 	}
4071 	if (ioc->manu_pg11.AddlFlags2 & NVME_TASK_MNGT_CUSTOM_MASK)
4072 		ioc->tm_custom_handling = 1;
4073 	else {
4074 		ioc->tm_custom_handling = 0;
4075 		if (ioc->manu_pg11.NVMeAbortTO < NVME_TASK_ABORT_MIN_TIMEOUT)
4076 			ioc->nvme_abort_timeout = NVME_TASK_ABORT_MIN_TIMEOUT;
4077 		else if (ioc->manu_pg11.NVMeAbortTO >
4078 					NVME_TASK_ABORT_MAX_TIMEOUT)
4079 			ioc->nvme_abort_timeout = NVME_TASK_ABORT_MAX_TIMEOUT;
4080 		else
4081 			ioc->nvme_abort_timeout = ioc->manu_pg11.NVMeAbortTO;
4082 	}
4083 
4084 	mpt3sas_config_get_bios_pg2(ioc, &mpi_reply, &ioc->bios_pg2);
4085 	mpt3sas_config_get_bios_pg3(ioc, &mpi_reply, &ioc->bios_pg3);
4086 	mpt3sas_config_get_ioc_pg8(ioc, &mpi_reply, &ioc->ioc_pg8);
4087 	mpt3sas_config_get_iounit_pg0(ioc, &mpi_reply, &ioc->iounit_pg0);
4088 	mpt3sas_config_get_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
4089 	mpt3sas_config_get_iounit_pg8(ioc, &mpi_reply, &ioc->iounit_pg8);
4090 	_base_display_ioc_capabilities(ioc);
4091 
4092 	/*
4093 	 * Enable task_set_full handling in iounit_pg1 when the
4094 	 * facts capabilities indicate that its supported.
4095 	 */
4096 	iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
4097 	if ((ioc->facts.IOCCapabilities &
4098 	    MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING))
4099 		iounit_pg1_flags &=
4100 		    ~MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
4101 	else
4102 		iounit_pg1_flags |=
4103 		    MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
4104 	ioc->iounit_pg1.Flags = cpu_to_le32(iounit_pg1_flags);
4105 	mpt3sas_config_set_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
4106 
4107 	if (ioc->iounit_pg8.NumSensors)
4108 		ioc->temp_sensors_count = ioc->iounit_pg8.NumSensors;
4109 }
4110 
4111 /**
4112  * mpt3sas_free_enclosure_list - release memory
4113  * @ioc: per adapter object
4114  *
4115  * Free memory allocated during encloure add.
4116  */
4117 void
4118 mpt3sas_free_enclosure_list(struct MPT3SAS_ADAPTER *ioc)
4119 {
4120 	struct _enclosure_node *enclosure_dev, *enclosure_dev_next;
4121 
4122 	/* Free enclosure list */
4123 	list_for_each_entry_safe(enclosure_dev,
4124 			enclosure_dev_next, &ioc->enclosure_list, list) {
4125 		list_del(&enclosure_dev->list);
4126 		kfree(enclosure_dev);
4127 	}
4128 }
4129 
4130 /**
4131  * _base_release_memory_pools - release memory
4132  * @ioc: per adapter object
4133  *
4134  * Free memory allocated from _base_allocate_memory_pools.
4135  */
4136 static void
4137 _base_release_memory_pools(struct MPT3SAS_ADAPTER *ioc)
4138 {
4139 	int i = 0;
4140 	int j = 0;
4141 	struct chain_tracker *ct;
4142 	struct reply_post_struct *rps;
4143 
4144 	dexitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
4145 
4146 	if (ioc->request) {
4147 		dma_free_coherent(&ioc->pdev->dev, ioc->request_dma_sz,
4148 		    ioc->request,  ioc->request_dma);
4149 		dexitprintk(ioc,
4150 			    ioc_info(ioc, "request_pool(0x%p): free\n",
4151 				     ioc->request));
4152 		ioc->request = NULL;
4153 	}
4154 
4155 	if (ioc->sense) {
4156 		dma_pool_free(ioc->sense_dma_pool, ioc->sense, ioc->sense_dma);
4157 		dma_pool_destroy(ioc->sense_dma_pool);
4158 		dexitprintk(ioc,
4159 			    ioc_info(ioc, "sense_pool(0x%p): free\n",
4160 				     ioc->sense));
4161 		ioc->sense = NULL;
4162 	}
4163 
4164 	if (ioc->reply) {
4165 		dma_pool_free(ioc->reply_dma_pool, ioc->reply, ioc->reply_dma);
4166 		dma_pool_destroy(ioc->reply_dma_pool);
4167 		dexitprintk(ioc,
4168 			    ioc_info(ioc, "reply_pool(0x%p): free\n",
4169 				     ioc->reply));
4170 		ioc->reply = NULL;
4171 	}
4172 
4173 	if (ioc->reply_free) {
4174 		dma_pool_free(ioc->reply_free_dma_pool, ioc->reply_free,
4175 		    ioc->reply_free_dma);
4176 		dma_pool_destroy(ioc->reply_free_dma_pool);
4177 		dexitprintk(ioc,
4178 			    ioc_info(ioc, "reply_free_pool(0x%p): free\n",
4179 				     ioc->reply_free));
4180 		ioc->reply_free = NULL;
4181 	}
4182 
4183 	if (ioc->reply_post) {
4184 		do {
4185 			rps = &ioc->reply_post[i];
4186 			if (rps->reply_post_free) {
4187 				dma_pool_free(
4188 				    ioc->reply_post_free_dma_pool,
4189 				    rps->reply_post_free,
4190 				    rps->reply_post_free_dma);
4191 				dexitprintk(ioc,
4192 					    ioc_info(ioc, "reply_post_free_pool(0x%p): free\n",
4193 						     rps->reply_post_free));
4194 				rps->reply_post_free = NULL;
4195 			}
4196 		} while (ioc->rdpq_array_enable &&
4197 			   (++i < ioc->reply_queue_count));
4198 		if (ioc->reply_post_free_array &&
4199 			ioc->rdpq_array_enable) {
4200 			dma_pool_free(ioc->reply_post_free_array_dma_pool,
4201 				ioc->reply_post_free_array,
4202 				ioc->reply_post_free_array_dma);
4203 			ioc->reply_post_free_array = NULL;
4204 		}
4205 		dma_pool_destroy(ioc->reply_post_free_array_dma_pool);
4206 		dma_pool_destroy(ioc->reply_post_free_dma_pool);
4207 		kfree(ioc->reply_post);
4208 	}
4209 
4210 	if (ioc->pcie_sgl_dma_pool) {
4211 		for (i = 0; i < ioc->scsiio_depth; i++) {
4212 			dma_pool_free(ioc->pcie_sgl_dma_pool,
4213 					ioc->pcie_sg_lookup[i].pcie_sgl,
4214 					ioc->pcie_sg_lookup[i].pcie_sgl_dma);
4215 		}
4216 		if (ioc->pcie_sgl_dma_pool)
4217 			dma_pool_destroy(ioc->pcie_sgl_dma_pool);
4218 	}
4219 
4220 	if (ioc->config_page) {
4221 		dexitprintk(ioc,
4222 			    ioc_info(ioc, "config_page(0x%p): free\n",
4223 				     ioc->config_page));
4224 		dma_free_coherent(&ioc->pdev->dev, ioc->config_page_sz,
4225 		    ioc->config_page, ioc->config_page_dma);
4226 	}
4227 
4228 	kfree(ioc->hpr_lookup);
4229 	kfree(ioc->internal_lookup);
4230 	if (ioc->chain_lookup) {
4231 		for (i = 0; i < ioc->scsiio_depth; i++) {
4232 			for (j = ioc->chains_per_prp_buffer;
4233 			    j < ioc->chains_needed_per_io; j++) {
4234 				ct = &ioc->chain_lookup[i].chains_per_smid[j];
4235 				if (ct && ct->chain_buffer)
4236 					dma_pool_free(ioc->chain_dma_pool,
4237 						ct->chain_buffer,
4238 						ct->chain_buffer_dma);
4239 			}
4240 			kfree(ioc->chain_lookup[i].chains_per_smid);
4241 		}
4242 		dma_pool_destroy(ioc->chain_dma_pool);
4243 		kfree(ioc->chain_lookup);
4244 		ioc->chain_lookup = NULL;
4245 	}
4246 }
4247 
4248 /**
4249  * is_MSB_are_same - checks whether all reply queues in a set are
4250  *	having same upper 32bits in their base memory address.
4251  * @reply_pool_start_address: Base address of a reply queue set
4252  * @pool_sz: Size of single Reply Descriptor Post Queues pool size
4253  *
4254  * Return: 1 if reply queues in a set have a same upper 32bits in their base
4255  * memory address, else 0.
4256  */
4257 
4258 static int
4259 is_MSB_are_same(long reply_pool_start_address, u32 pool_sz)
4260 {
4261 	long reply_pool_end_address;
4262 
4263 	reply_pool_end_address = reply_pool_start_address + pool_sz;
4264 
4265 	if (upper_32_bits(reply_pool_start_address) ==
4266 		upper_32_bits(reply_pool_end_address))
4267 		return 1;
4268 	else
4269 		return 0;
4270 }
4271 
4272 /**
4273  * _base_allocate_memory_pools - allocate start of day memory pools
4274  * @ioc: per adapter object
4275  *
4276  * Return: 0 success, anything else error.
4277  */
4278 static int
4279 _base_allocate_memory_pools(struct MPT3SAS_ADAPTER *ioc)
4280 {
4281 	struct mpt3sas_facts *facts;
4282 	u16 max_sge_elements;
4283 	u16 chains_needed_per_io;
4284 	u32 sz, total_sz, reply_post_free_sz, reply_post_free_array_sz;
4285 	u32 retry_sz;
4286 	u16 max_request_credit, nvme_blocks_needed;
4287 	unsigned short sg_tablesize;
4288 	u16 sge_size;
4289 	int i, j;
4290 	struct chain_tracker *ct;
4291 
4292 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
4293 
4294 
4295 	retry_sz = 0;
4296 	facts = &ioc->facts;
4297 
4298 	/* command line tunables for max sgl entries */
4299 	if (max_sgl_entries != -1)
4300 		sg_tablesize = max_sgl_entries;
4301 	else {
4302 		if (ioc->hba_mpi_version_belonged == MPI2_VERSION)
4303 			sg_tablesize = MPT2SAS_SG_DEPTH;
4304 		else
4305 			sg_tablesize = MPT3SAS_SG_DEPTH;
4306 	}
4307 
4308 	/* max sgl entries <= MPT_KDUMP_MIN_PHYS_SEGMENTS in KDUMP mode */
4309 	if (reset_devices)
4310 		sg_tablesize = min_t(unsigned short, sg_tablesize,
4311 		   MPT_KDUMP_MIN_PHYS_SEGMENTS);
4312 
4313 	if (ioc->is_mcpu_endpoint)
4314 		ioc->shost->sg_tablesize = MPT_MIN_PHYS_SEGMENTS;
4315 	else {
4316 		if (sg_tablesize < MPT_MIN_PHYS_SEGMENTS)
4317 			sg_tablesize = MPT_MIN_PHYS_SEGMENTS;
4318 		else if (sg_tablesize > MPT_MAX_PHYS_SEGMENTS) {
4319 			sg_tablesize = min_t(unsigned short, sg_tablesize,
4320 					SG_MAX_SEGMENTS);
4321 			ioc_warn(ioc, "sg_tablesize(%u) is bigger than kernel defined SG_CHUNK_SIZE(%u)\n",
4322 				 sg_tablesize, MPT_MAX_PHYS_SEGMENTS);
4323 		}
4324 		ioc->shost->sg_tablesize = sg_tablesize;
4325 	}
4326 
4327 	ioc->internal_depth = min_t(int, (facts->HighPriorityCredit + (5)),
4328 		(facts->RequestCredit / 4));
4329 	if (ioc->internal_depth < INTERNAL_CMDS_COUNT) {
4330 		if (facts->RequestCredit <= (INTERNAL_CMDS_COUNT +
4331 				INTERNAL_SCSIIO_CMDS_COUNT)) {
4332 			ioc_err(ioc, "IOC doesn't have enough Request Credits, it has just %d number of credits\n",
4333 				facts->RequestCredit);
4334 			return -ENOMEM;
4335 		}
4336 		ioc->internal_depth = 10;
4337 	}
4338 
4339 	ioc->hi_priority_depth = ioc->internal_depth - (5);
4340 	/* command line tunables  for max controller queue depth */
4341 	if (max_queue_depth != -1 && max_queue_depth != 0) {
4342 		max_request_credit = min_t(u16, max_queue_depth +
4343 			ioc->internal_depth, facts->RequestCredit);
4344 		if (max_request_credit > MAX_HBA_QUEUE_DEPTH)
4345 			max_request_credit =  MAX_HBA_QUEUE_DEPTH;
4346 	} else if (reset_devices)
4347 		max_request_credit = min_t(u16, facts->RequestCredit,
4348 		    (MPT3SAS_KDUMP_SCSI_IO_DEPTH + ioc->internal_depth));
4349 	else
4350 		max_request_credit = min_t(u16, facts->RequestCredit,
4351 		    MAX_HBA_QUEUE_DEPTH);
4352 
4353 	/* Firmware maintains additional facts->HighPriorityCredit number of
4354 	 * credits for HiPriprity Request messages, so hba queue depth will be
4355 	 * sum of max_request_credit and high priority queue depth.
4356 	 */
4357 	ioc->hba_queue_depth = max_request_credit + ioc->hi_priority_depth;
4358 
4359 	/* request frame size */
4360 	ioc->request_sz = facts->IOCRequestFrameSize * 4;
4361 
4362 	/* reply frame size */
4363 	ioc->reply_sz = facts->ReplyFrameSize * 4;
4364 
4365 	/* chain segment size */
4366 	if (ioc->hba_mpi_version_belonged != MPI2_VERSION) {
4367 		if (facts->IOCMaxChainSegmentSize)
4368 			ioc->chain_segment_sz =
4369 					facts->IOCMaxChainSegmentSize *
4370 					MAX_CHAIN_ELEMT_SZ;
4371 		else
4372 		/* set to 128 bytes size if IOCMaxChainSegmentSize is zero */
4373 			ioc->chain_segment_sz = DEFAULT_NUM_FWCHAIN_ELEMTS *
4374 						    MAX_CHAIN_ELEMT_SZ;
4375 	} else
4376 		ioc->chain_segment_sz = ioc->request_sz;
4377 
4378 	/* calculate the max scatter element size */
4379 	sge_size = max_t(u16, ioc->sge_size, ioc->sge_size_ieee);
4380 
4381  retry_allocation:
4382 	total_sz = 0;
4383 	/* calculate number of sg elements left over in the 1st frame */
4384 	max_sge_elements = ioc->request_sz - ((sizeof(Mpi2SCSIIORequest_t) -
4385 	    sizeof(Mpi2SGEIOUnion_t)) + sge_size);
4386 	ioc->max_sges_in_main_message = max_sge_elements/sge_size;
4387 
4388 	/* now do the same for a chain buffer */
4389 	max_sge_elements = ioc->chain_segment_sz - sge_size;
4390 	ioc->max_sges_in_chain_message = max_sge_elements/sge_size;
4391 
4392 	/*
4393 	 *  MPT3SAS_SG_DEPTH = CONFIG_FUSION_MAX_SGE
4394 	 */
4395 	chains_needed_per_io = ((ioc->shost->sg_tablesize -
4396 	   ioc->max_sges_in_main_message)/ioc->max_sges_in_chain_message)
4397 	    + 1;
4398 	if (chains_needed_per_io > facts->MaxChainDepth) {
4399 		chains_needed_per_io = facts->MaxChainDepth;
4400 		ioc->shost->sg_tablesize = min_t(u16,
4401 		ioc->max_sges_in_main_message + (ioc->max_sges_in_chain_message
4402 		* chains_needed_per_io), ioc->shost->sg_tablesize);
4403 	}
4404 	ioc->chains_needed_per_io = chains_needed_per_io;
4405 
4406 	/* reply free queue sizing - taking into account for 64 FW events */
4407 	ioc->reply_free_queue_depth = ioc->hba_queue_depth + 64;
4408 
4409 	/* mCPU manage single counters for simplicity */
4410 	if (ioc->is_mcpu_endpoint)
4411 		ioc->reply_post_queue_depth = ioc->reply_free_queue_depth;
4412 	else {
4413 		/* calculate reply descriptor post queue depth */
4414 		ioc->reply_post_queue_depth = ioc->hba_queue_depth +
4415 			ioc->reply_free_queue_depth +  1;
4416 		/* align the reply post queue on the next 16 count boundary */
4417 		if (ioc->reply_post_queue_depth % 16)
4418 			ioc->reply_post_queue_depth += 16 -
4419 				(ioc->reply_post_queue_depth % 16);
4420 	}
4421 
4422 	if (ioc->reply_post_queue_depth >
4423 	    facts->MaxReplyDescriptorPostQueueDepth) {
4424 		ioc->reply_post_queue_depth =
4425 				facts->MaxReplyDescriptorPostQueueDepth -
4426 		    (facts->MaxReplyDescriptorPostQueueDepth % 16);
4427 		ioc->hba_queue_depth =
4428 				((ioc->reply_post_queue_depth - 64) / 2) - 1;
4429 		ioc->reply_free_queue_depth = ioc->hba_queue_depth + 64;
4430 	}
4431 
4432 	dinitprintk(ioc,
4433 		    ioc_info(ioc, "scatter gather: sge_in_main_msg(%d), sge_per_chain(%d), sge_per_io(%d), chains_per_io(%d)\n",
4434 			     ioc->max_sges_in_main_message,
4435 			     ioc->max_sges_in_chain_message,
4436 			     ioc->shost->sg_tablesize,
4437 			     ioc->chains_needed_per_io));
4438 
4439 	/* reply post queue, 16 byte align */
4440 	reply_post_free_sz = ioc->reply_post_queue_depth *
4441 	    sizeof(Mpi2DefaultReplyDescriptor_t);
4442 
4443 	sz = reply_post_free_sz;
4444 	if (_base_is_controller_msix_enabled(ioc) && !ioc->rdpq_array_enable)
4445 		sz *= ioc->reply_queue_count;
4446 
4447 	ioc->reply_post = kcalloc((ioc->rdpq_array_enable) ?
4448 	    (ioc->reply_queue_count):1,
4449 	    sizeof(struct reply_post_struct), GFP_KERNEL);
4450 
4451 	if (!ioc->reply_post) {
4452 		ioc_err(ioc, "reply_post_free pool: kcalloc failed\n");
4453 		goto out;
4454 	}
4455 	ioc->reply_post_free_dma_pool = dma_pool_create("reply_post_free pool",
4456 	    &ioc->pdev->dev, sz, 16, 0);
4457 	if (!ioc->reply_post_free_dma_pool) {
4458 		ioc_err(ioc, "reply_post_free pool: dma_pool_create failed\n");
4459 		goto out;
4460 	}
4461 	i = 0;
4462 	do {
4463 		ioc->reply_post[i].reply_post_free =
4464 		    dma_pool_zalloc(ioc->reply_post_free_dma_pool,
4465 		    GFP_KERNEL,
4466 		    &ioc->reply_post[i].reply_post_free_dma);
4467 		if (!ioc->reply_post[i].reply_post_free) {
4468 			ioc_err(ioc, "reply_post_free pool: dma_pool_alloc failed\n");
4469 			goto out;
4470 		}
4471 		dinitprintk(ioc,
4472 			    ioc_info(ioc, "reply post free pool (0x%p): depth(%d), element_size(%d), pool_size(%d kB)\n",
4473 				     ioc->reply_post[i].reply_post_free,
4474 				     ioc->reply_post_queue_depth,
4475 				     8, sz / 1024));
4476 		dinitprintk(ioc,
4477 			    ioc_info(ioc, "reply_post_free_dma = (0x%llx)\n",
4478 				     (u64)ioc->reply_post[i].reply_post_free_dma));
4479 		total_sz += sz;
4480 	} while (ioc->rdpq_array_enable && (++i < ioc->reply_queue_count));
4481 
4482 	if (ioc->dma_mask == 64) {
4483 		if (_base_change_consistent_dma_mask(ioc, ioc->pdev) != 0) {
4484 			ioc_warn(ioc, "no suitable consistent DMA mask for %s\n",
4485 				 pci_name(ioc->pdev));
4486 			goto out;
4487 		}
4488 	}
4489 
4490 	ioc->scsiio_depth = ioc->hba_queue_depth -
4491 	    ioc->hi_priority_depth - ioc->internal_depth;
4492 
4493 	/* set the scsi host can_queue depth
4494 	 * with some internal commands that could be outstanding
4495 	 */
4496 	ioc->shost->can_queue = ioc->scsiio_depth - INTERNAL_SCSIIO_CMDS_COUNT;
4497 	dinitprintk(ioc,
4498 		    ioc_info(ioc, "scsi host: can_queue depth (%d)\n",
4499 			     ioc->shost->can_queue));
4500 
4501 
4502 	/* contiguous pool for request and chains, 16 byte align, one extra "
4503 	 * "frame for smid=0
4504 	 */
4505 	ioc->chain_depth = ioc->chains_needed_per_io * ioc->scsiio_depth;
4506 	sz = ((ioc->scsiio_depth + 1) * ioc->request_sz);
4507 
4508 	/* hi-priority queue */
4509 	sz += (ioc->hi_priority_depth * ioc->request_sz);
4510 
4511 	/* internal queue */
4512 	sz += (ioc->internal_depth * ioc->request_sz);
4513 
4514 	ioc->request_dma_sz = sz;
4515 	ioc->request = dma_alloc_coherent(&ioc->pdev->dev, sz,
4516 			&ioc->request_dma, GFP_KERNEL);
4517 	if (!ioc->request) {
4518 		ioc_err(ioc, "request pool: dma_alloc_coherent failed: hba_depth(%d), chains_per_io(%d), frame_sz(%d), total(%d kB)\n",
4519 			ioc->hba_queue_depth, ioc->chains_needed_per_io,
4520 			ioc->request_sz, sz / 1024);
4521 		if (ioc->scsiio_depth < MPT3SAS_SAS_QUEUE_DEPTH)
4522 			goto out;
4523 		retry_sz = 64;
4524 		ioc->hba_queue_depth -= retry_sz;
4525 		_base_release_memory_pools(ioc);
4526 		goto retry_allocation;
4527 	}
4528 
4529 	if (retry_sz)
4530 		ioc_err(ioc, "request pool: dma_alloc_coherent succeed: hba_depth(%d), chains_per_io(%d), frame_sz(%d), total(%d kb)\n",
4531 			ioc->hba_queue_depth, ioc->chains_needed_per_io,
4532 			ioc->request_sz, sz / 1024);
4533 
4534 	/* hi-priority queue */
4535 	ioc->hi_priority = ioc->request + ((ioc->scsiio_depth + 1) *
4536 	    ioc->request_sz);
4537 	ioc->hi_priority_dma = ioc->request_dma + ((ioc->scsiio_depth + 1) *
4538 	    ioc->request_sz);
4539 
4540 	/* internal queue */
4541 	ioc->internal = ioc->hi_priority + (ioc->hi_priority_depth *
4542 	    ioc->request_sz);
4543 	ioc->internal_dma = ioc->hi_priority_dma + (ioc->hi_priority_depth *
4544 	    ioc->request_sz);
4545 
4546 	dinitprintk(ioc,
4547 		    ioc_info(ioc, "request pool(0x%p): depth(%d), frame_size(%d), pool_size(%d kB)\n",
4548 			     ioc->request, ioc->hba_queue_depth,
4549 			     ioc->request_sz,
4550 			     (ioc->hba_queue_depth * ioc->request_sz) / 1024));
4551 
4552 	dinitprintk(ioc,
4553 		    ioc_info(ioc, "request pool: dma(0x%llx)\n",
4554 			     (unsigned long long)ioc->request_dma));
4555 	total_sz += sz;
4556 
4557 	dinitprintk(ioc,
4558 		    ioc_info(ioc, "scsiio(0x%p): depth(%d)\n",
4559 			     ioc->request, ioc->scsiio_depth));
4560 
4561 	ioc->chain_depth = min_t(u32, ioc->chain_depth, MAX_CHAIN_DEPTH);
4562 	sz = ioc->scsiio_depth * sizeof(struct chain_lookup);
4563 	ioc->chain_lookup = kzalloc(sz, GFP_KERNEL);
4564 	if (!ioc->chain_lookup) {
4565 		ioc_err(ioc, "chain_lookup: __get_free_pages failed\n");
4566 		goto out;
4567 	}
4568 
4569 	sz = ioc->chains_needed_per_io * sizeof(struct chain_tracker);
4570 	for (i = 0; i < ioc->scsiio_depth; i++) {
4571 		ioc->chain_lookup[i].chains_per_smid = kzalloc(sz, GFP_KERNEL);
4572 		if (!ioc->chain_lookup[i].chains_per_smid) {
4573 			ioc_err(ioc, "chain_lookup: kzalloc failed\n");
4574 			goto out;
4575 		}
4576 	}
4577 
4578 	/* initialize hi-priority queue smid's */
4579 	ioc->hpr_lookup = kcalloc(ioc->hi_priority_depth,
4580 	    sizeof(struct request_tracker), GFP_KERNEL);
4581 	if (!ioc->hpr_lookup) {
4582 		ioc_err(ioc, "hpr_lookup: kcalloc failed\n");
4583 		goto out;
4584 	}
4585 	ioc->hi_priority_smid = ioc->scsiio_depth + 1;
4586 	dinitprintk(ioc,
4587 		    ioc_info(ioc, "hi_priority(0x%p): depth(%d), start smid(%d)\n",
4588 			     ioc->hi_priority,
4589 			     ioc->hi_priority_depth, ioc->hi_priority_smid));
4590 
4591 	/* initialize internal queue smid's */
4592 	ioc->internal_lookup = kcalloc(ioc->internal_depth,
4593 	    sizeof(struct request_tracker), GFP_KERNEL);
4594 	if (!ioc->internal_lookup) {
4595 		ioc_err(ioc, "internal_lookup: kcalloc failed\n");
4596 		goto out;
4597 	}
4598 	ioc->internal_smid = ioc->hi_priority_smid + ioc->hi_priority_depth;
4599 	dinitprintk(ioc,
4600 		    ioc_info(ioc, "internal(0x%p): depth(%d), start smid(%d)\n",
4601 			     ioc->internal,
4602 			     ioc->internal_depth, ioc->internal_smid));
4603 	/*
4604 	 * The number of NVMe page sized blocks needed is:
4605 	 *     (((sg_tablesize * 8) - 1) / (page_size - 8)) + 1
4606 	 * ((sg_tablesize * 8) - 1) is the max PRP's minus the first PRP entry
4607 	 * that is placed in the main message frame.  8 is the size of each PRP
4608 	 * entry or PRP list pointer entry.  8 is subtracted from page_size
4609 	 * because of the PRP list pointer entry at the end of a page, so this
4610 	 * is not counted as a PRP entry.  The 1 added page is a round up.
4611 	 *
4612 	 * To avoid allocation failures due to the amount of memory that could
4613 	 * be required for NVMe PRP's, only each set of NVMe blocks will be
4614 	 * contiguous, so a new set is allocated for each possible I/O.
4615 	 */
4616 	ioc->chains_per_prp_buffer = 0;
4617 	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_NVME_DEVICES) {
4618 		nvme_blocks_needed =
4619 			(ioc->shost->sg_tablesize * NVME_PRP_SIZE) - 1;
4620 		nvme_blocks_needed /= (ioc->page_size - NVME_PRP_SIZE);
4621 		nvme_blocks_needed++;
4622 
4623 		sz = sizeof(struct pcie_sg_list) * ioc->scsiio_depth;
4624 		ioc->pcie_sg_lookup = kzalloc(sz, GFP_KERNEL);
4625 		if (!ioc->pcie_sg_lookup) {
4626 			ioc_info(ioc, "PCIe SGL lookup: kzalloc failed\n");
4627 			goto out;
4628 		}
4629 		sz = nvme_blocks_needed * ioc->page_size;
4630 		ioc->pcie_sgl_dma_pool =
4631 			dma_pool_create("PCIe SGL pool", &ioc->pdev->dev, sz, 16, 0);
4632 		if (!ioc->pcie_sgl_dma_pool) {
4633 			ioc_info(ioc, "PCIe SGL pool: dma_pool_create failed\n");
4634 			goto out;
4635 		}
4636 
4637 		ioc->chains_per_prp_buffer = sz/ioc->chain_segment_sz;
4638 		ioc->chains_per_prp_buffer = min(ioc->chains_per_prp_buffer,
4639 						ioc->chains_needed_per_io);
4640 
4641 		for (i = 0; i < ioc->scsiio_depth; i++) {
4642 			ioc->pcie_sg_lookup[i].pcie_sgl = dma_pool_alloc(
4643 				ioc->pcie_sgl_dma_pool, GFP_KERNEL,
4644 				&ioc->pcie_sg_lookup[i].pcie_sgl_dma);
4645 			if (!ioc->pcie_sg_lookup[i].pcie_sgl) {
4646 				ioc_info(ioc, "PCIe SGL pool: dma_pool_alloc failed\n");
4647 				goto out;
4648 			}
4649 			for (j = 0; j < ioc->chains_per_prp_buffer; j++) {
4650 				ct = &ioc->chain_lookup[i].chains_per_smid[j];
4651 				ct->chain_buffer =
4652 				    ioc->pcie_sg_lookup[i].pcie_sgl +
4653 				    (j * ioc->chain_segment_sz);
4654 				ct->chain_buffer_dma =
4655 				    ioc->pcie_sg_lookup[i].pcie_sgl_dma +
4656 				    (j * ioc->chain_segment_sz);
4657 			}
4658 		}
4659 
4660 		dinitprintk(ioc,
4661 			    ioc_info(ioc, "PCIe sgl pool depth(%d), element_size(%d), pool_size(%d kB)\n",
4662 				     ioc->scsiio_depth, sz,
4663 				     (sz * ioc->scsiio_depth) / 1024));
4664 		dinitprintk(ioc,
4665 			    ioc_info(ioc, "Number of chains can fit in a PRP page(%d)\n",
4666 				     ioc->chains_per_prp_buffer));
4667 		total_sz += sz * ioc->scsiio_depth;
4668 	}
4669 
4670 	ioc->chain_dma_pool = dma_pool_create("chain pool", &ioc->pdev->dev,
4671 	    ioc->chain_segment_sz, 16, 0);
4672 	if (!ioc->chain_dma_pool) {
4673 		ioc_err(ioc, "chain_dma_pool: dma_pool_create failed\n");
4674 		goto out;
4675 	}
4676 	for (i = 0; i < ioc->scsiio_depth; i++) {
4677 		for (j = ioc->chains_per_prp_buffer;
4678 				j < ioc->chains_needed_per_io; j++) {
4679 			ct = &ioc->chain_lookup[i].chains_per_smid[j];
4680 			ct->chain_buffer = dma_pool_alloc(
4681 					ioc->chain_dma_pool, GFP_KERNEL,
4682 					&ct->chain_buffer_dma);
4683 			if (!ct->chain_buffer) {
4684 				ioc_err(ioc, "chain_lookup: pci_pool_alloc failed\n");
4685 				_base_release_memory_pools(ioc);
4686 				goto out;
4687 			}
4688 		}
4689 		total_sz += ioc->chain_segment_sz;
4690 	}
4691 
4692 	dinitprintk(ioc,
4693 		    ioc_info(ioc, "chain pool depth(%d), frame_size(%d), pool_size(%d kB)\n",
4694 			     ioc->chain_depth, ioc->chain_segment_sz,
4695 			     (ioc->chain_depth * ioc->chain_segment_sz) / 1024));
4696 
4697 	/* sense buffers, 4 byte align */
4698 	sz = ioc->scsiio_depth * SCSI_SENSE_BUFFERSIZE;
4699 	ioc->sense_dma_pool = dma_pool_create("sense pool", &ioc->pdev->dev, sz,
4700 					      4, 0);
4701 	if (!ioc->sense_dma_pool) {
4702 		ioc_err(ioc, "sense pool: dma_pool_create failed\n");
4703 		goto out;
4704 	}
4705 	ioc->sense = dma_pool_alloc(ioc->sense_dma_pool, GFP_KERNEL,
4706 	    &ioc->sense_dma);
4707 	if (!ioc->sense) {
4708 		ioc_err(ioc, "sense pool: dma_pool_alloc failed\n");
4709 		goto out;
4710 	}
4711 	/* sense buffer requires to be in same 4 gb region.
4712 	 * Below function will check the same.
4713 	 * In case of failure, new pci pool will be created with updated
4714 	 * alignment. Older allocation and pool will be destroyed.
4715 	 * Alignment will be used such a way that next allocation if
4716 	 * success, will always meet same 4gb region requirement.
4717 	 * Actual requirement is not alignment, but we need start and end of
4718 	 * DMA address must have same upper 32 bit address.
4719 	 */
4720 	if (!is_MSB_are_same((long)ioc->sense, sz)) {
4721 		//Release Sense pool & Reallocate
4722 		dma_pool_free(ioc->sense_dma_pool, ioc->sense, ioc->sense_dma);
4723 		dma_pool_destroy(ioc->sense_dma_pool);
4724 		ioc->sense = NULL;
4725 
4726 		ioc->sense_dma_pool =
4727 			dma_pool_create("sense pool", &ioc->pdev->dev, sz,
4728 						roundup_pow_of_two(sz), 0);
4729 		if (!ioc->sense_dma_pool) {
4730 			ioc_err(ioc, "sense pool: pci_pool_create failed\n");
4731 			goto out;
4732 		}
4733 		ioc->sense = dma_pool_alloc(ioc->sense_dma_pool, GFP_KERNEL,
4734 				&ioc->sense_dma);
4735 		if (!ioc->sense) {
4736 			ioc_err(ioc, "sense pool: pci_pool_alloc failed\n");
4737 			goto out;
4738 		}
4739 	}
4740 	dinitprintk(ioc,
4741 		    ioc_info(ioc, "sense pool(0x%p): depth(%d), element_size(%d), pool_size(%d kB)\n",
4742 			     ioc->sense, ioc->scsiio_depth,
4743 			     SCSI_SENSE_BUFFERSIZE, sz / 1024));
4744 	dinitprintk(ioc,
4745 		    ioc_info(ioc, "sense_dma(0x%llx)\n",
4746 			     (unsigned long long)ioc->sense_dma));
4747 	total_sz += sz;
4748 
4749 	/* reply pool, 4 byte align */
4750 	sz = ioc->reply_free_queue_depth * ioc->reply_sz;
4751 	ioc->reply_dma_pool = dma_pool_create("reply pool", &ioc->pdev->dev, sz,
4752 					      4, 0);
4753 	if (!ioc->reply_dma_pool) {
4754 		ioc_err(ioc, "reply pool: dma_pool_create failed\n");
4755 		goto out;
4756 	}
4757 	ioc->reply = dma_pool_alloc(ioc->reply_dma_pool, GFP_KERNEL,
4758 	    &ioc->reply_dma);
4759 	if (!ioc->reply) {
4760 		ioc_err(ioc, "reply pool: dma_pool_alloc failed\n");
4761 		goto out;
4762 	}
4763 	ioc->reply_dma_min_address = (u32)(ioc->reply_dma);
4764 	ioc->reply_dma_max_address = (u32)(ioc->reply_dma) + sz;
4765 	dinitprintk(ioc,
4766 		    ioc_info(ioc, "reply pool(0x%p): depth(%d), frame_size(%d), pool_size(%d kB)\n",
4767 			     ioc->reply, ioc->reply_free_queue_depth,
4768 			     ioc->reply_sz, sz / 1024));
4769 	dinitprintk(ioc,
4770 		    ioc_info(ioc, "reply_dma(0x%llx)\n",
4771 			     (unsigned long long)ioc->reply_dma));
4772 	total_sz += sz;
4773 
4774 	/* reply free queue, 16 byte align */
4775 	sz = ioc->reply_free_queue_depth * 4;
4776 	ioc->reply_free_dma_pool = dma_pool_create("reply_free pool",
4777 	    &ioc->pdev->dev, sz, 16, 0);
4778 	if (!ioc->reply_free_dma_pool) {
4779 		ioc_err(ioc, "reply_free pool: dma_pool_create failed\n");
4780 		goto out;
4781 	}
4782 	ioc->reply_free = dma_pool_zalloc(ioc->reply_free_dma_pool, GFP_KERNEL,
4783 	    &ioc->reply_free_dma);
4784 	if (!ioc->reply_free) {
4785 		ioc_err(ioc, "reply_free pool: dma_pool_alloc failed\n");
4786 		goto out;
4787 	}
4788 	dinitprintk(ioc,
4789 		    ioc_info(ioc, "reply_free pool(0x%p): depth(%d), element_size(%d), pool_size(%d kB)\n",
4790 			     ioc->reply_free, ioc->reply_free_queue_depth,
4791 			     4, sz / 1024));
4792 	dinitprintk(ioc,
4793 		    ioc_info(ioc, "reply_free_dma (0x%llx)\n",
4794 			     (unsigned long long)ioc->reply_free_dma));
4795 	total_sz += sz;
4796 
4797 	if (ioc->rdpq_array_enable) {
4798 		reply_post_free_array_sz = ioc->reply_queue_count *
4799 		    sizeof(Mpi2IOCInitRDPQArrayEntry);
4800 		ioc->reply_post_free_array_dma_pool =
4801 		    dma_pool_create("reply_post_free_array pool",
4802 		    &ioc->pdev->dev, reply_post_free_array_sz, 16, 0);
4803 		if (!ioc->reply_post_free_array_dma_pool) {
4804 			dinitprintk(ioc,
4805 				    ioc_info(ioc, "reply_post_free_array pool: dma_pool_create failed\n"));
4806 			goto out;
4807 		}
4808 		ioc->reply_post_free_array =
4809 		    dma_pool_alloc(ioc->reply_post_free_array_dma_pool,
4810 		    GFP_KERNEL, &ioc->reply_post_free_array_dma);
4811 		if (!ioc->reply_post_free_array) {
4812 			dinitprintk(ioc,
4813 				    ioc_info(ioc, "reply_post_free_array pool: dma_pool_alloc failed\n"));
4814 			goto out;
4815 		}
4816 	}
4817 	ioc->config_page_sz = 512;
4818 	ioc->config_page = dma_alloc_coherent(&ioc->pdev->dev,
4819 			ioc->config_page_sz, &ioc->config_page_dma, GFP_KERNEL);
4820 	if (!ioc->config_page) {
4821 		ioc_err(ioc, "config page: dma_pool_alloc failed\n");
4822 		goto out;
4823 	}
4824 	dinitprintk(ioc,
4825 		    ioc_info(ioc, "config page(0x%p): size(%d)\n",
4826 			     ioc->config_page, ioc->config_page_sz));
4827 	dinitprintk(ioc,
4828 		    ioc_info(ioc, "config_page_dma(0x%llx)\n",
4829 			     (unsigned long long)ioc->config_page_dma));
4830 	total_sz += ioc->config_page_sz;
4831 
4832 	ioc_info(ioc, "Allocated physical memory: size(%d kB)\n",
4833 		 total_sz / 1024);
4834 	ioc_info(ioc, "Current Controller Queue Depth(%d),Max Controller Queue Depth(%d)\n",
4835 		 ioc->shost->can_queue, facts->RequestCredit);
4836 	ioc_info(ioc, "Scatter Gather Elements per IO(%d)\n",
4837 		 ioc->shost->sg_tablesize);
4838 	return 0;
4839 
4840  out:
4841 	return -ENOMEM;
4842 }
4843 
4844 /**
4845  * mpt3sas_base_get_iocstate - Get the current state of a MPT adapter.
4846  * @ioc: Pointer to MPT_ADAPTER structure
4847  * @cooked: Request raw or cooked IOC state
4848  *
4849  * Return: all IOC Doorbell register bits if cooked==0, else just the
4850  * Doorbell bits in MPI_IOC_STATE_MASK.
4851  */
4852 u32
4853 mpt3sas_base_get_iocstate(struct MPT3SAS_ADAPTER *ioc, int cooked)
4854 {
4855 	u32 s, sc;
4856 
4857 	s = readl(&ioc->chip->Doorbell);
4858 	sc = s & MPI2_IOC_STATE_MASK;
4859 	return cooked ? sc : s;
4860 }
4861 
4862 /**
4863  * _base_wait_on_iocstate - waiting on a particular ioc state
4864  * @ioc: ?
4865  * @ioc_state: controller state { READY, OPERATIONAL, or RESET }
4866  * @timeout: timeout in second
4867  *
4868  * Return: 0 for success, non-zero for failure.
4869  */
4870 static int
4871 _base_wait_on_iocstate(struct MPT3SAS_ADAPTER *ioc, u32 ioc_state, int timeout)
4872 {
4873 	u32 count, cntdn;
4874 	u32 current_state;
4875 
4876 	count = 0;
4877 	cntdn = 1000 * timeout;
4878 	do {
4879 		current_state = mpt3sas_base_get_iocstate(ioc, 1);
4880 		if (current_state == ioc_state)
4881 			return 0;
4882 		if (count && current_state == MPI2_IOC_STATE_FAULT)
4883 			break;
4884 
4885 		usleep_range(1000, 1500);
4886 		count++;
4887 	} while (--cntdn);
4888 
4889 	return current_state;
4890 }
4891 
4892 /**
4893  * _base_wait_for_doorbell_int - waiting for controller interrupt(generated by
4894  * a write to the doorbell)
4895  * @ioc: per adapter object
4896  *
4897  * Return: 0 for success, non-zero for failure.
4898  *
4899  * Notes: MPI2_HIS_IOC2SYS_DB_STATUS - set to one when IOC writes to doorbell.
4900  */
4901 static int
4902 _base_diag_reset(struct MPT3SAS_ADAPTER *ioc);
4903 
4904 static int
4905 _base_wait_for_doorbell_int(struct MPT3SAS_ADAPTER *ioc, int timeout)
4906 {
4907 	u32 cntdn, count;
4908 	u32 int_status;
4909 
4910 	count = 0;
4911 	cntdn = 1000 * timeout;
4912 	do {
4913 		int_status = readl(&ioc->chip->HostInterruptStatus);
4914 		if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
4915 			dhsprintk(ioc,
4916 				  ioc_info(ioc, "%s: successful count(%d), timeout(%d)\n",
4917 					   __func__, count, timeout));
4918 			return 0;
4919 		}
4920 
4921 		usleep_range(1000, 1500);
4922 		count++;
4923 	} while (--cntdn);
4924 
4925 	ioc_err(ioc, "%s: failed due to timeout count(%d), int_status(%x)!\n",
4926 		__func__, count, int_status);
4927 	return -EFAULT;
4928 }
4929 
4930 static int
4931 _base_spin_on_doorbell_int(struct MPT3SAS_ADAPTER *ioc, int timeout)
4932 {
4933 	u32 cntdn, count;
4934 	u32 int_status;
4935 
4936 	count = 0;
4937 	cntdn = 2000 * timeout;
4938 	do {
4939 		int_status = readl(&ioc->chip->HostInterruptStatus);
4940 		if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
4941 			dhsprintk(ioc,
4942 				  ioc_info(ioc, "%s: successful count(%d), timeout(%d)\n",
4943 					   __func__, count, timeout));
4944 			return 0;
4945 		}
4946 
4947 		udelay(500);
4948 		count++;
4949 	} while (--cntdn);
4950 
4951 	ioc_err(ioc, "%s: failed due to timeout count(%d), int_status(%x)!\n",
4952 		__func__, count, int_status);
4953 	return -EFAULT;
4954 
4955 }
4956 
4957 /**
4958  * _base_wait_for_doorbell_ack - waiting for controller to read the doorbell.
4959  * @ioc: per adapter object
4960  * @timeout: timeout in second
4961  *
4962  * Return: 0 for success, non-zero for failure.
4963  *
4964  * Notes: MPI2_HIS_SYS2IOC_DB_STATUS - set to one when host writes to
4965  * doorbell.
4966  */
4967 static int
4968 _base_wait_for_doorbell_ack(struct MPT3SAS_ADAPTER *ioc, int timeout)
4969 {
4970 	u32 cntdn, count;
4971 	u32 int_status;
4972 	u32 doorbell;
4973 
4974 	count = 0;
4975 	cntdn = 1000 * timeout;
4976 	do {
4977 		int_status = readl(&ioc->chip->HostInterruptStatus);
4978 		if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
4979 			dhsprintk(ioc,
4980 				  ioc_info(ioc, "%s: successful count(%d), timeout(%d)\n",
4981 					   __func__, count, timeout));
4982 			return 0;
4983 		} else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
4984 			doorbell = readl(&ioc->chip->Doorbell);
4985 			if ((doorbell & MPI2_IOC_STATE_MASK) ==
4986 			    MPI2_IOC_STATE_FAULT) {
4987 				mpt3sas_base_fault_info(ioc , doorbell);
4988 				return -EFAULT;
4989 			}
4990 		} else if (int_status == 0xFFFFFFFF)
4991 			goto out;
4992 
4993 		usleep_range(1000, 1500);
4994 		count++;
4995 	} while (--cntdn);
4996 
4997  out:
4998 	ioc_err(ioc, "%s: failed due to timeout count(%d), int_status(%x)!\n",
4999 		__func__, count, int_status);
5000 	return -EFAULT;
5001 }
5002 
5003 /**
5004  * _base_wait_for_doorbell_not_used - waiting for doorbell to not be in use
5005  * @ioc: per adapter object
5006  * @timeout: timeout in second
5007  *
5008  * Return: 0 for success, non-zero for failure.
5009  */
5010 static int
5011 _base_wait_for_doorbell_not_used(struct MPT3SAS_ADAPTER *ioc, int timeout)
5012 {
5013 	u32 cntdn, count;
5014 	u32 doorbell_reg;
5015 
5016 	count = 0;
5017 	cntdn = 1000 * timeout;
5018 	do {
5019 		doorbell_reg = readl(&ioc->chip->Doorbell);
5020 		if (!(doorbell_reg & MPI2_DOORBELL_USED)) {
5021 			dhsprintk(ioc,
5022 				  ioc_info(ioc, "%s: successful count(%d), timeout(%d)\n",
5023 					   __func__, count, timeout));
5024 			return 0;
5025 		}
5026 
5027 		usleep_range(1000, 1500);
5028 		count++;
5029 	} while (--cntdn);
5030 
5031 	ioc_err(ioc, "%s: failed due to timeout count(%d), doorbell_reg(%x)!\n",
5032 		__func__, count, doorbell_reg);
5033 	return -EFAULT;
5034 }
5035 
5036 /**
5037  * _base_send_ioc_reset - send doorbell reset
5038  * @ioc: per adapter object
5039  * @reset_type: currently only supports: MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET
5040  * @timeout: timeout in second
5041  *
5042  * Return: 0 for success, non-zero for failure.
5043  */
5044 static int
5045 _base_send_ioc_reset(struct MPT3SAS_ADAPTER *ioc, u8 reset_type, int timeout)
5046 {
5047 	u32 ioc_state;
5048 	int r = 0;
5049 
5050 	if (reset_type != MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET) {
5051 		ioc_err(ioc, "%s: unknown reset_type\n", __func__);
5052 		return -EFAULT;
5053 	}
5054 
5055 	if (!(ioc->facts.IOCCapabilities &
5056 	   MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY))
5057 		return -EFAULT;
5058 
5059 	ioc_info(ioc, "sending message unit reset !!\n");
5060 
5061 	writel(reset_type << MPI2_DOORBELL_FUNCTION_SHIFT,
5062 	    &ioc->chip->Doorbell);
5063 	if ((_base_wait_for_doorbell_ack(ioc, 15))) {
5064 		r = -EFAULT;
5065 		goto out;
5066 	}
5067 	ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, timeout);
5068 	if (ioc_state) {
5069 		ioc_err(ioc, "%s: failed going to ready state (ioc_state=0x%x)\n",
5070 			__func__, ioc_state);
5071 		r = -EFAULT;
5072 		goto out;
5073 	}
5074  out:
5075 	ioc_info(ioc, "message unit reset: %s\n",
5076 		 r == 0 ? "SUCCESS" : "FAILED");
5077 	return r;
5078 }
5079 
5080 /**
5081  * _base_handshake_req_reply_wait - send request thru doorbell interface
5082  * @ioc: per adapter object
5083  * @request_bytes: request length
5084  * @request: pointer having request payload
5085  * @reply_bytes: reply length
5086  * @reply: pointer to reply payload
5087  * @timeout: timeout in second
5088  *
5089  * Return: 0 for success, non-zero for failure.
5090  */
5091 static int
5092 _base_handshake_req_reply_wait(struct MPT3SAS_ADAPTER *ioc, int request_bytes,
5093 	u32 *request, int reply_bytes, u16 *reply, int timeout)
5094 {
5095 	MPI2DefaultReply_t *default_reply = (MPI2DefaultReply_t *)reply;
5096 	int i;
5097 	u8 failed;
5098 	__le32 *mfp;
5099 
5100 	/* make sure doorbell is not in use */
5101 	if ((readl(&ioc->chip->Doorbell) & MPI2_DOORBELL_USED)) {
5102 		ioc_err(ioc, "doorbell is in use (line=%d)\n", __LINE__);
5103 		return -EFAULT;
5104 	}
5105 
5106 	/* clear pending doorbell interrupts from previous state changes */
5107 	if (readl(&ioc->chip->HostInterruptStatus) &
5108 	    MPI2_HIS_IOC2SYS_DB_STATUS)
5109 		writel(0, &ioc->chip->HostInterruptStatus);
5110 
5111 	/* send message to ioc */
5112 	writel(((MPI2_FUNCTION_HANDSHAKE<<MPI2_DOORBELL_FUNCTION_SHIFT) |
5113 	    ((request_bytes/4)<<MPI2_DOORBELL_ADD_DWORDS_SHIFT)),
5114 	    &ioc->chip->Doorbell);
5115 
5116 	if ((_base_spin_on_doorbell_int(ioc, 5))) {
5117 		ioc_err(ioc, "doorbell handshake int failed (line=%d)\n",
5118 			__LINE__);
5119 		return -EFAULT;
5120 	}
5121 	writel(0, &ioc->chip->HostInterruptStatus);
5122 
5123 	if ((_base_wait_for_doorbell_ack(ioc, 5))) {
5124 		ioc_err(ioc, "doorbell handshake ack failed (line=%d)\n",
5125 			__LINE__);
5126 		return -EFAULT;
5127 	}
5128 
5129 	/* send message 32-bits at a time */
5130 	for (i = 0, failed = 0; i < request_bytes/4 && !failed; i++) {
5131 		writel(cpu_to_le32(request[i]), &ioc->chip->Doorbell);
5132 		if ((_base_wait_for_doorbell_ack(ioc, 5)))
5133 			failed = 1;
5134 	}
5135 
5136 	if (failed) {
5137 		ioc_err(ioc, "doorbell handshake sending request failed (line=%d)\n",
5138 			__LINE__);
5139 		return -EFAULT;
5140 	}
5141 
5142 	/* now wait for the reply */
5143 	if ((_base_wait_for_doorbell_int(ioc, timeout))) {
5144 		ioc_err(ioc, "doorbell handshake int failed (line=%d)\n",
5145 			__LINE__);
5146 		return -EFAULT;
5147 	}
5148 
5149 	/* read the first two 16-bits, it gives the total length of the reply */
5150 	reply[0] = le16_to_cpu(readl(&ioc->chip->Doorbell)
5151 	    & MPI2_DOORBELL_DATA_MASK);
5152 	writel(0, &ioc->chip->HostInterruptStatus);
5153 	if ((_base_wait_for_doorbell_int(ioc, 5))) {
5154 		ioc_err(ioc, "doorbell handshake int failed (line=%d)\n",
5155 			__LINE__);
5156 		return -EFAULT;
5157 	}
5158 	reply[1] = le16_to_cpu(readl(&ioc->chip->Doorbell)
5159 	    & MPI2_DOORBELL_DATA_MASK);
5160 	writel(0, &ioc->chip->HostInterruptStatus);
5161 
5162 	for (i = 2; i < default_reply->MsgLength * 2; i++)  {
5163 		if ((_base_wait_for_doorbell_int(ioc, 5))) {
5164 			ioc_err(ioc, "doorbell handshake int failed (line=%d)\n",
5165 				__LINE__);
5166 			return -EFAULT;
5167 		}
5168 		if (i >=  reply_bytes/2) /* overflow case */
5169 			readl(&ioc->chip->Doorbell);
5170 		else
5171 			reply[i] = le16_to_cpu(readl(&ioc->chip->Doorbell)
5172 			    & MPI2_DOORBELL_DATA_MASK);
5173 		writel(0, &ioc->chip->HostInterruptStatus);
5174 	}
5175 
5176 	_base_wait_for_doorbell_int(ioc, 5);
5177 	if (_base_wait_for_doorbell_not_used(ioc, 5) != 0) {
5178 		dhsprintk(ioc,
5179 			  ioc_info(ioc, "doorbell is in use (line=%d)\n",
5180 				   __LINE__));
5181 	}
5182 	writel(0, &ioc->chip->HostInterruptStatus);
5183 
5184 	if (ioc->logging_level & MPT_DEBUG_INIT) {
5185 		mfp = (__le32 *)reply;
5186 		pr_info("\toffset:data\n");
5187 		for (i = 0; i < reply_bytes/4; i++)
5188 			pr_info("\t[0x%02x]:%08x\n", i*4,
5189 			    le32_to_cpu(mfp[i]));
5190 	}
5191 	return 0;
5192 }
5193 
5194 /**
5195  * mpt3sas_base_sas_iounit_control - send sas iounit control to FW
5196  * @ioc: per adapter object
5197  * @mpi_reply: the reply payload from FW
5198  * @mpi_request: the request payload sent to FW
5199  *
5200  * The SAS IO Unit Control Request message allows the host to perform low-level
5201  * operations, such as resets on the PHYs of the IO Unit, also allows the host
5202  * to obtain the IOC assigned device handles for a device if it has other
5203  * identifying information about the device, in addition allows the host to
5204  * remove IOC resources associated with the device.
5205  *
5206  * Return: 0 for success, non-zero for failure.
5207  */
5208 int
5209 mpt3sas_base_sas_iounit_control(struct MPT3SAS_ADAPTER *ioc,
5210 	Mpi2SasIoUnitControlReply_t *mpi_reply,
5211 	Mpi2SasIoUnitControlRequest_t *mpi_request)
5212 {
5213 	u16 smid;
5214 	u32 ioc_state;
5215 	u8 issue_reset = 0;
5216 	int rc;
5217 	void *request;
5218 	u16 wait_state_count;
5219 
5220 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
5221 
5222 	mutex_lock(&ioc->base_cmds.mutex);
5223 
5224 	if (ioc->base_cmds.status != MPT3_CMD_NOT_USED) {
5225 		ioc_err(ioc, "%s: base_cmd in use\n", __func__);
5226 		rc = -EAGAIN;
5227 		goto out;
5228 	}
5229 
5230 	wait_state_count = 0;
5231 	ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
5232 	while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
5233 		if (wait_state_count++ == 10) {
5234 			ioc_err(ioc, "%s: failed due to ioc not operational\n",
5235 				__func__);
5236 			rc = -EFAULT;
5237 			goto out;
5238 		}
5239 		ssleep(1);
5240 		ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
5241 		ioc_info(ioc, "%s: waiting for operational state(count=%d)\n",
5242 			 __func__, wait_state_count);
5243 	}
5244 
5245 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
5246 	if (!smid) {
5247 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
5248 		rc = -EAGAIN;
5249 		goto out;
5250 	}
5251 
5252 	rc = 0;
5253 	ioc->base_cmds.status = MPT3_CMD_PENDING;
5254 	request = mpt3sas_base_get_msg_frame(ioc, smid);
5255 	ioc->base_cmds.smid = smid;
5256 	memcpy(request, mpi_request, sizeof(Mpi2SasIoUnitControlRequest_t));
5257 	if (mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
5258 	    mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET)
5259 		ioc->ioc_link_reset_in_progress = 1;
5260 	init_completion(&ioc->base_cmds.done);
5261 	mpt3sas_base_put_smid_default(ioc, smid);
5262 	wait_for_completion_timeout(&ioc->base_cmds.done,
5263 	    msecs_to_jiffies(10000));
5264 	if ((mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
5265 	    mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET) &&
5266 	    ioc->ioc_link_reset_in_progress)
5267 		ioc->ioc_link_reset_in_progress = 0;
5268 	if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
5269 		issue_reset =
5270 			mpt3sas_base_check_cmd_timeout(ioc,
5271 				ioc->base_cmds.status, mpi_request,
5272 				sizeof(Mpi2SasIoUnitControlRequest_t)/4);
5273 		goto issue_host_reset;
5274 	}
5275 	if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID)
5276 		memcpy(mpi_reply, ioc->base_cmds.reply,
5277 		    sizeof(Mpi2SasIoUnitControlReply_t));
5278 	else
5279 		memset(mpi_reply, 0, sizeof(Mpi2SasIoUnitControlReply_t));
5280 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5281 	goto out;
5282 
5283  issue_host_reset:
5284 	if (issue_reset)
5285 		mpt3sas_base_hard_reset_handler(ioc, FORCE_BIG_HAMMER);
5286 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5287 	rc = -EFAULT;
5288  out:
5289 	mutex_unlock(&ioc->base_cmds.mutex);
5290 	return rc;
5291 }
5292 
5293 /**
5294  * mpt3sas_base_scsi_enclosure_processor - sending request to sep device
5295  * @ioc: per adapter object
5296  * @mpi_reply: the reply payload from FW
5297  * @mpi_request: the request payload sent to FW
5298  *
5299  * The SCSI Enclosure Processor request message causes the IOC to
5300  * communicate with SES devices to control LED status signals.
5301  *
5302  * Return: 0 for success, non-zero for failure.
5303  */
5304 int
5305 mpt3sas_base_scsi_enclosure_processor(struct MPT3SAS_ADAPTER *ioc,
5306 	Mpi2SepReply_t *mpi_reply, Mpi2SepRequest_t *mpi_request)
5307 {
5308 	u16 smid;
5309 	u32 ioc_state;
5310 	u8 issue_reset = 0;
5311 	int rc;
5312 	void *request;
5313 	u16 wait_state_count;
5314 
5315 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
5316 
5317 	mutex_lock(&ioc->base_cmds.mutex);
5318 
5319 	if (ioc->base_cmds.status != MPT3_CMD_NOT_USED) {
5320 		ioc_err(ioc, "%s: base_cmd in use\n", __func__);
5321 		rc = -EAGAIN;
5322 		goto out;
5323 	}
5324 
5325 	wait_state_count = 0;
5326 	ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
5327 	while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) {
5328 		if (wait_state_count++ == 10) {
5329 			ioc_err(ioc, "%s: failed due to ioc not operational\n",
5330 				__func__);
5331 			rc = -EFAULT;
5332 			goto out;
5333 		}
5334 		ssleep(1);
5335 		ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
5336 		ioc_info(ioc, "%s: waiting for operational state(count=%d)\n",
5337 			 __func__, wait_state_count);
5338 	}
5339 
5340 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
5341 	if (!smid) {
5342 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
5343 		rc = -EAGAIN;
5344 		goto out;
5345 	}
5346 
5347 	rc = 0;
5348 	ioc->base_cmds.status = MPT3_CMD_PENDING;
5349 	request = mpt3sas_base_get_msg_frame(ioc, smid);
5350 	ioc->base_cmds.smid = smid;
5351 	memcpy(request, mpi_request, sizeof(Mpi2SepReply_t));
5352 	init_completion(&ioc->base_cmds.done);
5353 	mpt3sas_base_put_smid_default(ioc, smid);
5354 	wait_for_completion_timeout(&ioc->base_cmds.done,
5355 	    msecs_to_jiffies(10000));
5356 	if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
5357 		issue_reset =
5358 			mpt3sas_base_check_cmd_timeout(ioc,
5359 				ioc->base_cmds.status, mpi_request,
5360 				sizeof(Mpi2SepRequest_t)/4);
5361 		goto issue_host_reset;
5362 	}
5363 	if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID)
5364 		memcpy(mpi_reply, ioc->base_cmds.reply,
5365 		    sizeof(Mpi2SepReply_t));
5366 	else
5367 		memset(mpi_reply, 0, sizeof(Mpi2SepReply_t));
5368 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5369 	goto out;
5370 
5371  issue_host_reset:
5372 	if (issue_reset)
5373 		mpt3sas_base_hard_reset_handler(ioc, FORCE_BIG_HAMMER);
5374 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5375 	rc = -EFAULT;
5376  out:
5377 	mutex_unlock(&ioc->base_cmds.mutex);
5378 	return rc;
5379 }
5380 
5381 /**
5382  * _base_get_port_facts - obtain port facts reply and save in ioc
5383  * @ioc: per adapter object
5384  * @port: ?
5385  *
5386  * Return: 0 for success, non-zero for failure.
5387  */
5388 static int
5389 _base_get_port_facts(struct MPT3SAS_ADAPTER *ioc, int port)
5390 {
5391 	Mpi2PortFactsRequest_t mpi_request;
5392 	Mpi2PortFactsReply_t mpi_reply;
5393 	struct mpt3sas_port_facts *pfacts;
5394 	int mpi_reply_sz, mpi_request_sz, r;
5395 
5396 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
5397 
5398 	mpi_reply_sz = sizeof(Mpi2PortFactsReply_t);
5399 	mpi_request_sz = sizeof(Mpi2PortFactsRequest_t);
5400 	memset(&mpi_request, 0, mpi_request_sz);
5401 	mpi_request.Function = MPI2_FUNCTION_PORT_FACTS;
5402 	mpi_request.PortNumber = port;
5403 	r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
5404 	    (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5);
5405 
5406 	if (r != 0) {
5407 		ioc_err(ioc, "%s: handshake failed (r=%d)\n", __func__, r);
5408 		return r;
5409 	}
5410 
5411 	pfacts = &ioc->pfacts[port];
5412 	memset(pfacts, 0, sizeof(struct mpt3sas_port_facts));
5413 	pfacts->PortNumber = mpi_reply.PortNumber;
5414 	pfacts->VP_ID = mpi_reply.VP_ID;
5415 	pfacts->VF_ID = mpi_reply.VF_ID;
5416 	pfacts->MaxPostedCmdBuffers =
5417 	    le16_to_cpu(mpi_reply.MaxPostedCmdBuffers);
5418 
5419 	return 0;
5420 }
5421 
5422 /**
5423  * _base_wait_for_iocstate - Wait until the card is in READY or OPERATIONAL
5424  * @ioc: per adapter object
5425  * @timeout:
5426  *
5427  * Return: 0 for success, non-zero for failure.
5428  */
5429 static int
5430 _base_wait_for_iocstate(struct MPT3SAS_ADAPTER *ioc, int timeout)
5431 {
5432 	u32 ioc_state;
5433 	int rc;
5434 
5435 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
5436 
5437 	if (ioc->pci_error_recovery) {
5438 		dfailprintk(ioc,
5439 			    ioc_info(ioc, "%s: host in pci error recovery\n",
5440 				     __func__));
5441 		return -EFAULT;
5442 	}
5443 
5444 	ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
5445 	dhsprintk(ioc,
5446 		  ioc_info(ioc, "%s: ioc_state(0x%08x)\n",
5447 			   __func__, ioc_state));
5448 
5449 	if (((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_READY) ||
5450 	    (ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_OPERATIONAL)
5451 		return 0;
5452 
5453 	if (ioc_state & MPI2_DOORBELL_USED) {
5454 		dhsprintk(ioc, ioc_info(ioc, "unexpected doorbell active!\n"));
5455 		goto issue_diag_reset;
5456 	}
5457 
5458 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
5459 		mpt3sas_base_fault_info(ioc, ioc_state &
5460 		    MPI2_DOORBELL_DATA_MASK);
5461 		goto issue_diag_reset;
5462 	}
5463 
5464 	ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, timeout);
5465 	if (ioc_state) {
5466 		dfailprintk(ioc,
5467 			    ioc_info(ioc, "%s: failed going to ready state (ioc_state=0x%x)\n",
5468 				     __func__, ioc_state));
5469 		return -EFAULT;
5470 	}
5471 
5472  issue_diag_reset:
5473 	rc = _base_diag_reset(ioc);
5474 	return rc;
5475 }
5476 
5477 /**
5478  * _base_get_ioc_facts - obtain ioc facts reply and save in ioc
5479  * @ioc: per adapter object
5480  *
5481  * Return: 0 for success, non-zero for failure.
5482  */
5483 static int
5484 _base_get_ioc_facts(struct MPT3SAS_ADAPTER *ioc)
5485 {
5486 	Mpi2IOCFactsRequest_t mpi_request;
5487 	Mpi2IOCFactsReply_t mpi_reply;
5488 	struct mpt3sas_facts *facts;
5489 	int mpi_reply_sz, mpi_request_sz, r;
5490 
5491 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
5492 
5493 	r = _base_wait_for_iocstate(ioc, 10);
5494 	if (r) {
5495 		dfailprintk(ioc,
5496 			    ioc_info(ioc, "%s: failed getting to correct state\n",
5497 				     __func__));
5498 		return r;
5499 	}
5500 	mpi_reply_sz = sizeof(Mpi2IOCFactsReply_t);
5501 	mpi_request_sz = sizeof(Mpi2IOCFactsRequest_t);
5502 	memset(&mpi_request, 0, mpi_request_sz);
5503 	mpi_request.Function = MPI2_FUNCTION_IOC_FACTS;
5504 	r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
5505 	    (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5);
5506 
5507 	if (r != 0) {
5508 		ioc_err(ioc, "%s: handshake failed (r=%d)\n", __func__, r);
5509 		return r;
5510 	}
5511 
5512 	facts = &ioc->facts;
5513 	memset(facts, 0, sizeof(struct mpt3sas_facts));
5514 	facts->MsgVersion = le16_to_cpu(mpi_reply.MsgVersion);
5515 	facts->HeaderVersion = le16_to_cpu(mpi_reply.HeaderVersion);
5516 	facts->VP_ID = mpi_reply.VP_ID;
5517 	facts->VF_ID = mpi_reply.VF_ID;
5518 	facts->IOCExceptions = le16_to_cpu(mpi_reply.IOCExceptions);
5519 	facts->MaxChainDepth = mpi_reply.MaxChainDepth;
5520 	facts->WhoInit = mpi_reply.WhoInit;
5521 	facts->NumberOfPorts = mpi_reply.NumberOfPorts;
5522 	facts->MaxMSIxVectors = mpi_reply.MaxMSIxVectors;
5523 	if (ioc->msix_enable && (facts->MaxMSIxVectors <=
5524 	    MAX_COMBINED_MSIX_VECTORS(ioc->is_gen35_ioc)))
5525 		ioc->combined_reply_queue = 0;
5526 	facts->RequestCredit = le16_to_cpu(mpi_reply.RequestCredit);
5527 	facts->MaxReplyDescriptorPostQueueDepth =
5528 	    le16_to_cpu(mpi_reply.MaxReplyDescriptorPostQueueDepth);
5529 	facts->ProductID = le16_to_cpu(mpi_reply.ProductID);
5530 	facts->IOCCapabilities = le32_to_cpu(mpi_reply.IOCCapabilities);
5531 	if ((facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID))
5532 		ioc->ir_firmware = 1;
5533 	if ((facts->IOCCapabilities &
5534 	      MPI2_IOCFACTS_CAPABILITY_RDPQ_ARRAY_CAPABLE) && (!reset_devices))
5535 		ioc->rdpq_array_capable = 1;
5536 	facts->FWVersion.Word = le32_to_cpu(mpi_reply.FWVersion.Word);
5537 	facts->IOCRequestFrameSize =
5538 	    le16_to_cpu(mpi_reply.IOCRequestFrameSize);
5539 	if (ioc->hba_mpi_version_belonged != MPI2_VERSION) {
5540 		facts->IOCMaxChainSegmentSize =
5541 			le16_to_cpu(mpi_reply.IOCMaxChainSegmentSize);
5542 	}
5543 	facts->MaxInitiators = le16_to_cpu(mpi_reply.MaxInitiators);
5544 	facts->MaxTargets = le16_to_cpu(mpi_reply.MaxTargets);
5545 	ioc->shost->max_id = -1;
5546 	facts->MaxSasExpanders = le16_to_cpu(mpi_reply.MaxSasExpanders);
5547 	facts->MaxEnclosures = le16_to_cpu(mpi_reply.MaxEnclosures);
5548 	facts->ProtocolFlags = le16_to_cpu(mpi_reply.ProtocolFlags);
5549 	facts->HighPriorityCredit =
5550 	    le16_to_cpu(mpi_reply.HighPriorityCredit);
5551 	facts->ReplyFrameSize = mpi_reply.ReplyFrameSize;
5552 	facts->MaxDevHandle = le16_to_cpu(mpi_reply.MaxDevHandle);
5553 	facts->CurrentHostPageSize = mpi_reply.CurrentHostPageSize;
5554 
5555 	/*
5556 	 * Get the Page Size from IOC Facts. If it's 0, default to 4k.
5557 	 */
5558 	ioc->page_size = 1 << facts->CurrentHostPageSize;
5559 	if (ioc->page_size == 1) {
5560 		ioc_info(ioc, "CurrentHostPageSize is 0: Setting default host page size to 4k\n");
5561 		ioc->page_size = 1 << MPT3SAS_HOST_PAGE_SIZE_4K;
5562 	}
5563 	dinitprintk(ioc,
5564 		    ioc_info(ioc, "CurrentHostPageSize(%d)\n",
5565 			     facts->CurrentHostPageSize));
5566 
5567 	dinitprintk(ioc,
5568 		    ioc_info(ioc, "hba queue depth(%d), max chains per io(%d)\n",
5569 			     facts->RequestCredit, facts->MaxChainDepth));
5570 	dinitprintk(ioc,
5571 		    ioc_info(ioc, "request frame size(%d), reply frame size(%d)\n",
5572 			     facts->IOCRequestFrameSize * 4,
5573 			     facts->ReplyFrameSize * 4));
5574 	return 0;
5575 }
5576 
5577 /**
5578  * _base_send_ioc_init - send ioc_init to firmware
5579  * @ioc: per adapter object
5580  *
5581  * Return: 0 for success, non-zero for failure.
5582  */
5583 static int
5584 _base_send_ioc_init(struct MPT3SAS_ADAPTER *ioc)
5585 {
5586 	Mpi2IOCInitRequest_t mpi_request;
5587 	Mpi2IOCInitReply_t mpi_reply;
5588 	int i, r = 0;
5589 	ktime_t current_time;
5590 	u16 ioc_status;
5591 	u32 reply_post_free_array_sz = 0;
5592 
5593 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
5594 
5595 	memset(&mpi_request, 0, sizeof(Mpi2IOCInitRequest_t));
5596 	mpi_request.Function = MPI2_FUNCTION_IOC_INIT;
5597 	mpi_request.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
5598 	mpi_request.VF_ID = 0; /* TODO */
5599 	mpi_request.VP_ID = 0;
5600 	mpi_request.MsgVersion = cpu_to_le16(ioc->hba_mpi_version_belonged);
5601 	mpi_request.HeaderVersion = cpu_to_le16(MPI2_HEADER_VERSION);
5602 	mpi_request.HostPageSize = MPT3SAS_HOST_PAGE_SIZE_4K;
5603 
5604 	if (_base_is_controller_msix_enabled(ioc))
5605 		mpi_request.HostMSIxVectors = ioc->reply_queue_count;
5606 	mpi_request.SystemRequestFrameSize = cpu_to_le16(ioc->request_sz/4);
5607 	mpi_request.ReplyDescriptorPostQueueDepth =
5608 	    cpu_to_le16(ioc->reply_post_queue_depth);
5609 	mpi_request.ReplyFreeQueueDepth =
5610 	    cpu_to_le16(ioc->reply_free_queue_depth);
5611 
5612 	mpi_request.SenseBufferAddressHigh =
5613 	    cpu_to_le32((u64)ioc->sense_dma >> 32);
5614 	mpi_request.SystemReplyAddressHigh =
5615 	    cpu_to_le32((u64)ioc->reply_dma >> 32);
5616 	mpi_request.SystemRequestFrameBaseAddress =
5617 	    cpu_to_le64((u64)ioc->request_dma);
5618 	mpi_request.ReplyFreeQueueAddress =
5619 	    cpu_to_le64((u64)ioc->reply_free_dma);
5620 
5621 	if (ioc->rdpq_array_enable) {
5622 		reply_post_free_array_sz = ioc->reply_queue_count *
5623 		    sizeof(Mpi2IOCInitRDPQArrayEntry);
5624 		memset(ioc->reply_post_free_array, 0, reply_post_free_array_sz);
5625 		for (i = 0; i < ioc->reply_queue_count; i++)
5626 			ioc->reply_post_free_array[i].RDPQBaseAddress =
5627 			    cpu_to_le64(
5628 				(u64)ioc->reply_post[i].reply_post_free_dma);
5629 		mpi_request.MsgFlags = MPI2_IOCINIT_MSGFLAG_RDPQ_ARRAY_MODE;
5630 		mpi_request.ReplyDescriptorPostQueueAddress =
5631 		    cpu_to_le64((u64)ioc->reply_post_free_array_dma);
5632 	} else {
5633 		mpi_request.ReplyDescriptorPostQueueAddress =
5634 		    cpu_to_le64((u64)ioc->reply_post[0].reply_post_free_dma);
5635 	}
5636 
5637 	/* This time stamp specifies number of milliseconds
5638 	 * since epoch ~ midnight January 1, 1970.
5639 	 */
5640 	current_time = ktime_get_real();
5641 	mpi_request.TimeStamp = cpu_to_le64(ktime_to_ms(current_time));
5642 
5643 	if (ioc->logging_level & MPT_DEBUG_INIT) {
5644 		__le32 *mfp;
5645 		int i;
5646 
5647 		mfp = (__le32 *)&mpi_request;
5648 		pr_info("\toffset:data\n");
5649 		for (i = 0; i < sizeof(Mpi2IOCInitRequest_t)/4; i++)
5650 			pr_info("\t[0x%02x]:%08x\n", i*4,
5651 			    le32_to_cpu(mfp[i]));
5652 	}
5653 
5654 	r = _base_handshake_req_reply_wait(ioc,
5655 	    sizeof(Mpi2IOCInitRequest_t), (u32 *)&mpi_request,
5656 	    sizeof(Mpi2IOCInitReply_t), (u16 *)&mpi_reply, 10);
5657 
5658 	if (r != 0) {
5659 		ioc_err(ioc, "%s: handshake failed (r=%d)\n", __func__, r);
5660 		return r;
5661 	}
5662 
5663 	ioc_status = le16_to_cpu(mpi_reply.IOCStatus) & MPI2_IOCSTATUS_MASK;
5664 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS ||
5665 	    mpi_reply.IOCLogInfo) {
5666 		ioc_err(ioc, "%s: failed\n", __func__);
5667 		r = -EIO;
5668 	}
5669 
5670 	return r;
5671 }
5672 
5673 /**
5674  * mpt3sas_port_enable_done - command completion routine for port enable
5675  * @ioc: per adapter object
5676  * @smid: system request message index
5677  * @msix_index: MSIX table index supplied by the OS
5678  * @reply: reply message frame(lower 32bit addr)
5679  *
5680  * Return: 1 meaning mf should be freed from _base_interrupt
5681  *          0 means the mf is freed from this function.
5682  */
5683 u8
5684 mpt3sas_port_enable_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
5685 	u32 reply)
5686 {
5687 	MPI2DefaultReply_t *mpi_reply;
5688 	u16 ioc_status;
5689 
5690 	if (ioc->port_enable_cmds.status == MPT3_CMD_NOT_USED)
5691 		return 1;
5692 
5693 	mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
5694 	if (!mpi_reply)
5695 		return 1;
5696 
5697 	if (mpi_reply->Function != MPI2_FUNCTION_PORT_ENABLE)
5698 		return 1;
5699 
5700 	ioc->port_enable_cmds.status &= ~MPT3_CMD_PENDING;
5701 	ioc->port_enable_cmds.status |= MPT3_CMD_COMPLETE;
5702 	ioc->port_enable_cmds.status |= MPT3_CMD_REPLY_VALID;
5703 	memcpy(ioc->port_enable_cmds.reply, mpi_reply, mpi_reply->MsgLength*4);
5704 	ioc_status = le16_to_cpu(mpi_reply->IOCStatus) & MPI2_IOCSTATUS_MASK;
5705 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS)
5706 		ioc->port_enable_failed = 1;
5707 
5708 	if (ioc->is_driver_loading) {
5709 		if (ioc_status == MPI2_IOCSTATUS_SUCCESS) {
5710 			mpt3sas_port_enable_complete(ioc);
5711 			return 1;
5712 		} else {
5713 			ioc->start_scan_failed = ioc_status;
5714 			ioc->start_scan = 0;
5715 			return 1;
5716 		}
5717 	}
5718 	complete(&ioc->port_enable_cmds.done);
5719 	return 1;
5720 }
5721 
5722 /**
5723  * _base_send_port_enable - send port_enable(discovery stuff) to firmware
5724  * @ioc: per adapter object
5725  *
5726  * Return: 0 for success, non-zero for failure.
5727  */
5728 static int
5729 _base_send_port_enable(struct MPT3SAS_ADAPTER *ioc)
5730 {
5731 	Mpi2PortEnableRequest_t *mpi_request;
5732 	Mpi2PortEnableReply_t *mpi_reply;
5733 	int r = 0;
5734 	u16 smid;
5735 	u16 ioc_status;
5736 
5737 	ioc_info(ioc, "sending port enable !!\n");
5738 
5739 	if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
5740 		ioc_err(ioc, "%s: internal command already in use\n", __func__);
5741 		return -EAGAIN;
5742 	}
5743 
5744 	smid = mpt3sas_base_get_smid(ioc, ioc->port_enable_cb_idx);
5745 	if (!smid) {
5746 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
5747 		return -EAGAIN;
5748 	}
5749 
5750 	ioc->port_enable_cmds.status = MPT3_CMD_PENDING;
5751 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
5752 	ioc->port_enable_cmds.smid = smid;
5753 	memset(mpi_request, 0, sizeof(Mpi2PortEnableRequest_t));
5754 	mpi_request->Function = MPI2_FUNCTION_PORT_ENABLE;
5755 
5756 	init_completion(&ioc->port_enable_cmds.done);
5757 	mpt3sas_base_put_smid_default(ioc, smid);
5758 	wait_for_completion_timeout(&ioc->port_enable_cmds.done, 300*HZ);
5759 	if (!(ioc->port_enable_cmds.status & MPT3_CMD_COMPLETE)) {
5760 		ioc_err(ioc, "%s: timeout\n", __func__);
5761 		_debug_dump_mf(mpi_request,
5762 		    sizeof(Mpi2PortEnableRequest_t)/4);
5763 		if (ioc->port_enable_cmds.status & MPT3_CMD_RESET)
5764 			r = -EFAULT;
5765 		else
5766 			r = -ETIME;
5767 		goto out;
5768 	}
5769 
5770 	mpi_reply = ioc->port_enable_cmds.reply;
5771 	ioc_status = le16_to_cpu(mpi_reply->IOCStatus) & MPI2_IOCSTATUS_MASK;
5772 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
5773 		ioc_err(ioc, "%s: failed with (ioc_status=0x%08x)\n",
5774 			__func__, ioc_status);
5775 		r = -EFAULT;
5776 		goto out;
5777 	}
5778 
5779  out:
5780 	ioc->port_enable_cmds.status = MPT3_CMD_NOT_USED;
5781 	ioc_info(ioc, "port enable: %s\n", r == 0 ? "SUCCESS" : "FAILED");
5782 	return r;
5783 }
5784 
5785 /**
5786  * mpt3sas_port_enable - initiate firmware discovery (don't wait for reply)
5787  * @ioc: per adapter object
5788  *
5789  * Return: 0 for success, non-zero for failure.
5790  */
5791 int
5792 mpt3sas_port_enable(struct MPT3SAS_ADAPTER *ioc)
5793 {
5794 	Mpi2PortEnableRequest_t *mpi_request;
5795 	u16 smid;
5796 
5797 	ioc_info(ioc, "sending port enable !!\n");
5798 
5799 	if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
5800 		ioc_err(ioc, "%s: internal command already in use\n", __func__);
5801 		return -EAGAIN;
5802 	}
5803 
5804 	smid = mpt3sas_base_get_smid(ioc, ioc->port_enable_cb_idx);
5805 	if (!smid) {
5806 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
5807 		return -EAGAIN;
5808 	}
5809 
5810 	ioc->port_enable_cmds.status = MPT3_CMD_PENDING;
5811 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
5812 	ioc->port_enable_cmds.smid = smid;
5813 	memset(mpi_request, 0, sizeof(Mpi2PortEnableRequest_t));
5814 	mpi_request->Function = MPI2_FUNCTION_PORT_ENABLE;
5815 
5816 	mpt3sas_base_put_smid_default(ioc, smid);
5817 	return 0;
5818 }
5819 
5820 /**
5821  * _base_determine_wait_on_discovery - desposition
5822  * @ioc: per adapter object
5823  *
5824  * Decide whether to wait on discovery to complete. Used to either
5825  * locate boot device, or report volumes ahead of physical devices.
5826  *
5827  * Return: 1 for wait, 0 for don't wait.
5828  */
5829 static int
5830 _base_determine_wait_on_discovery(struct MPT3SAS_ADAPTER *ioc)
5831 {
5832 	/* We wait for discovery to complete if IR firmware is loaded.
5833 	 * The sas topology events arrive before PD events, so we need time to
5834 	 * turn on the bit in ioc->pd_handles to indicate PD
5835 	 * Also, it maybe required to report Volumes ahead of physical
5836 	 * devices when MPI2_IOCPAGE8_IRFLAGS_LOW_VOLUME_MAPPING is set.
5837 	 */
5838 	if (ioc->ir_firmware)
5839 		return 1;
5840 
5841 	/* if no Bios, then we don't need to wait */
5842 	if (!ioc->bios_pg3.BiosVersion)
5843 		return 0;
5844 
5845 	/* Bios is present, then we drop down here.
5846 	 *
5847 	 * If there any entries in the Bios Page 2, then we wait
5848 	 * for discovery to complete.
5849 	 */
5850 
5851 	/* Current Boot Device */
5852 	if ((ioc->bios_pg2.CurrentBootDeviceForm &
5853 	    MPI2_BIOSPAGE2_FORM_MASK) ==
5854 	    MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED &&
5855 	/* Request Boot Device */
5856 	   (ioc->bios_pg2.ReqBootDeviceForm &
5857 	    MPI2_BIOSPAGE2_FORM_MASK) ==
5858 	    MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED &&
5859 	/* Alternate Request Boot Device */
5860 	   (ioc->bios_pg2.ReqAltBootDeviceForm &
5861 	    MPI2_BIOSPAGE2_FORM_MASK) ==
5862 	    MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED)
5863 		return 0;
5864 
5865 	return 1;
5866 }
5867 
5868 /**
5869  * _base_unmask_events - turn on notification for this event
5870  * @ioc: per adapter object
5871  * @event: firmware event
5872  *
5873  * The mask is stored in ioc->event_masks.
5874  */
5875 static void
5876 _base_unmask_events(struct MPT3SAS_ADAPTER *ioc, u16 event)
5877 {
5878 	u32 desired_event;
5879 
5880 	if (event >= 128)
5881 		return;
5882 
5883 	desired_event = (1 << (event % 32));
5884 
5885 	if (event < 32)
5886 		ioc->event_masks[0] &= ~desired_event;
5887 	else if (event < 64)
5888 		ioc->event_masks[1] &= ~desired_event;
5889 	else if (event < 96)
5890 		ioc->event_masks[2] &= ~desired_event;
5891 	else if (event < 128)
5892 		ioc->event_masks[3] &= ~desired_event;
5893 }
5894 
5895 /**
5896  * _base_event_notification - send event notification
5897  * @ioc: per adapter object
5898  *
5899  * Return: 0 for success, non-zero for failure.
5900  */
5901 static int
5902 _base_event_notification(struct MPT3SAS_ADAPTER *ioc)
5903 {
5904 	Mpi2EventNotificationRequest_t *mpi_request;
5905 	u16 smid;
5906 	int r = 0;
5907 	int i;
5908 
5909 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
5910 
5911 	if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
5912 		ioc_err(ioc, "%s: internal command already in use\n", __func__);
5913 		return -EAGAIN;
5914 	}
5915 
5916 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
5917 	if (!smid) {
5918 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
5919 		return -EAGAIN;
5920 	}
5921 	ioc->base_cmds.status = MPT3_CMD_PENDING;
5922 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
5923 	ioc->base_cmds.smid = smid;
5924 	memset(mpi_request, 0, sizeof(Mpi2EventNotificationRequest_t));
5925 	mpi_request->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
5926 	mpi_request->VF_ID = 0; /* TODO */
5927 	mpi_request->VP_ID = 0;
5928 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
5929 		mpi_request->EventMasks[i] =
5930 		    cpu_to_le32(ioc->event_masks[i]);
5931 	init_completion(&ioc->base_cmds.done);
5932 	mpt3sas_base_put_smid_default(ioc, smid);
5933 	wait_for_completion_timeout(&ioc->base_cmds.done, 30*HZ);
5934 	if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
5935 		ioc_err(ioc, "%s: timeout\n", __func__);
5936 		_debug_dump_mf(mpi_request,
5937 		    sizeof(Mpi2EventNotificationRequest_t)/4);
5938 		if (ioc->base_cmds.status & MPT3_CMD_RESET)
5939 			r = -EFAULT;
5940 		else
5941 			r = -ETIME;
5942 	} else
5943 		dinitprintk(ioc, ioc_info(ioc, "%s: complete\n", __func__));
5944 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5945 	return r;
5946 }
5947 
5948 /**
5949  * mpt3sas_base_validate_event_type - validating event types
5950  * @ioc: per adapter object
5951  * @event_type: firmware event
5952  *
5953  * This will turn on firmware event notification when application
5954  * ask for that event. We don't mask events that are already enabled.
5955  */
5956 void
5957 mpt3sas_base_validate_event_type(struct MPT3SAS_ADAPTER *ioc, u32 *event_type)
5958 {
5959 	int i, j;
5960 	u32 event_mask, desired_event;
5961 	u8 send_update_to_fw;
5962 
5963 	for (i = 0, send_update_to_fw = 0; i <
5964 	    MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++) {
5965 		event_mask = ~event_type[i];
5966 		desired_event = 1;
5967 		for (j = 0; j < 32; j++) {
5968 			if (!(event_mask & desired_event) &&
5969 			    (ioc->event_masks[i] & desired_event)) {
5970 				ioc->event_masks[i] &= ~desired_event;
5971 				send_update_to_fw = 1;
5972 			}
5973 			desired_event = (desired_event << 1);
5974 		}
5975 	}
5976 
5977 	if (!send_update_to_fw)
5978 		return;
5979 
5980 	mutex_lock(&ioc->base_cmds.mutex);
5981 	_base_event_notification(ioc);
5982 	mutex_unlock(&ioc->base_cmds.mutex);
5983 }
5984 
5985 /**
5986  * _base_diag_reset - the "big hammer" start of day reset
5987  * @ioc: per adapter object
5988  *
5989  * Return: 0 for success, non-zero for failure.
5990  */
5991 static int
5992 _base_diag_reset(struct MPT3SAS_ADAPTER *ioc)
5993 {
5994 	u32 host_diagnostic;
5995 	u32 ioc_state;
5996 	u32 count;
5997 	u32 hcb_size;
5998 
5999 	ioc_info(ioc, "sending diag reset !!\n");
6000 
6001 	drsprintk(ioc, ioc_info(ioc, "clear interrupts\n"));
6002 
6003 	count = 0;
6004 	do {
6005 		/* Write magic sequence to WriteSequence register
6006 		 * Loop until in diagnostic mode
6007 		 */
6008 		drsprintk(ioc, ioc_info(ioc, "write magic sequence\n"));
6009 		writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
6010 		writel(MPI2_WRSEQ_1ST_KEY_VALUE, &ioc->chip->WriteSequence);
6011 		writel(MPI2_WRSEQ_2ND_KEY_VALUE, &ioc->chip->WriteSequence);
6012 		writel(MPI2_WRSEQ_3RD_KEY_VALUE, &ioc->chip->WriteSequence);
6013 		writel(MPI2_WRSEQ_4TH_KEY_VALUE, &ioc->chip->WriteSequence);
6014 		writel(MPI2_WRSEQ_5TH_KEY_VALUE, &ioc->chip->WriteSequence);
6015 		writel(MPI2_WRSEQ_6TH_KEY_VALUE, &ioc->chip->WriteSequence);
6016 
6017 		/* wait 100 msec */
6018 		msleep(100);
6019 
6020 		if (count++ > 20)
6021 			goto out;
6022 
6023 		host_diagnostic = readl(&ioc->chip->HostDiagnostic);
6024 		drsprintk(ioc,
6025 			  ioc_info(ioc, "wrote magic sequence: count(%d), host_diagnostic(0x%08x)\n",
6026 				   count, host_diagnostic));
6027 
6028 	} while ((host_diagnostic & MPI2_DIAG_DIAG_WRITE_ENABLE) == 0);
6029 
6030 	hcb_size = readl(&ioc->chip->HCBSize);
6031 
6032 	drsprintk(ioc, ioc_info(ioc, "diag reset: issued\n"));
6033 	writel(host_diagnostic | MPI2_DIAG_RESET_ADAPTER,
6034 	     &ioc->chip->HostDiagnostic);
6035 
6036 	/*This delay allows the chip PCIe hardware time to finish reset tasks*/
6037 	msleep(MPI2_HARD_RESET_PCIE_FIRST_READ_DELAY_MICRO_SEC/1000);
6038 
6039 	/* Approximately 300 second max wait */
6040 	for (count = 0; count < (300000000 /
6041 		MPI2_HARD_RESET_PCIE_SECOND_READ_DELAY_MICRO_SEC); count++) {
6042 
6043 		host_diagnostic = readl(&ioc->chip->HostDiagnostic);
6044 
6045 		if (host_diagnostic == 0xFFFFFFFF)
6046 			goto out;
6047 		if (!(host_diagnostic & MPI2_DIAG_RESET_ADAPTER))
6048 			break;
6049 
6050 		msleep(MPI2_HARD_RESET_PCIE_SECOND_READ_DELAY_MICRO_SEC / 1000);
6051 	}
6052 
6053 	if (host_diagnostic & MPI2_DIAG_HCB_MODE) {
6054 
6055 		drsprintk(ioc,
6056 			  ioc_info(ioc, "restart the adapter assuming the HCB Address points to good F/W\n"));
6057 		host_diagnostic &= ~MPI2_DIAG_BOOT_DEVICE_SELECT_MASK;
6058 		host_diagnostic |= MPI2_DIAG_BOOT_DEVICE_SELECT_HCDW;
6059 		writel(host_diagnostic, &ioc->chip->HostDiagnostic);
6060 
6061 		drsprintk(ioc, ioc_info(ioc, "re-enable the HCDW\n"));
6062 		writel(hcb_size | MPI2_HCB_SIZE_HCB_ENABLE,
6063 		    &ioc->chip->HCBSize);
6064 	}
6065 
6066 	drsprintk(ioc, ioc_info(ioc, "restart the adapter\n"));
6067 	writel(host_diagnostic & ~MPI2_DIAG_HOLD_IOC_RESET,
6068 	    &ioc->chip->HostDiagnostic);
6069 
6070 	drsprintk(ioc,
6071 		  ioc_info(ioc, "disable writes to the diagnostic register\n"));
6072 	writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
6073 
6074 	drsprintk(ioc, ioc_info(ioc, "Wait for FW to go to the READY state\n"));
6075 	ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, 20);
6076 	if (ioc_state) {
6077 		ioc_err(ioc, "%s: failed going to ready state (ioc_state=0x%x)\n",
6078 			__func__, ioc_state);
6079 		goto out;
6080 	}
6081 
6082 	ioc_info(ioc, "diag reset: SUCCESS\n");
6083 	return 0;
6084 
6085  out:
6086 	ioc_err(ioc, "diag reset: FAILED\n");
6087 	return -EFAULT;
6088 }
6089 
6090 /**
6091  * _base_make_ioc_ready - put controller in READY state
6092  * @ioc: per adapter object
6093  * @type: FORCE_BIG_HAMMER or SOFT_RESET
6094  *
6095  * Return: 0 for success, non-zero for failure.
6096  */
6097 static int
6098 _base_make_ioc_ready(struct MPT3SAS_ADAPTER *ioc, enum reset_type type)
6099 {
6100 	u32 ioc_state;
6101 	int rc;
6102 	int count;
6103 
6104 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6105 
6106 	if (ioc->pci_error_recovery)
6107 		return 0;
6108 
6109 	ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
6110 	dhsprintk(ioc,
6111 		  ioc_info(ioc, "%s: ioc_state(0x%08x)\n",
6112 			   __func__, ioc_state));
6113 
6114 	/* if in RESET state, it should move to READY state shortly */
6115 	count = 0;
6116 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_RESET) {
6117 		while ((ioc_state & MPI2_IOC_STATE_MASK) !=
6118 		    MPI2_IOC_STATE_READY) {
6119 			if (count++ == 10) {
6120 				ioc_err(ioc, "%s: failed going to ready state (ioc_state=0x%x)\n",
6121 					__func__, ioc_state);
6122 				return -EFAULT;
6123 			}
6124 			ssleep(1);
6125 			ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
6126 		}
6127 	}
6128 
6129 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_READY)
6130 		return 0;
6131 
6132 	if (ioc_state & MPI2_DOORBELL_USED) {
6133 		dhsprintk(ioc, ioc_info(ioc, "unexpected doorbell active!\n"));
6134 		goto issue_diag_reset;
6135 	}
6136 
6137 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
6138 		mpt3sas_base_fault_info(ioc, ioc_state &
6139 		    MPI2_DOORBELL_DATA_MASK);
6140 		goto issue_diag_reset;
6141 	}
6142 
6143 	if (type == FORCE_BIG_HAMMER)
6144 		goto issue_diag_reset;
6145 
6146 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_OPERATIONAL)
6147 		if (!(_base_send_ioc_reset(ioc,
6148 		    MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET, 15))) {
6149 			return 0;
6150 	}
6151 
6152  issue_diag_reset:
6153 	rc = _base_diag_reset(ioc);
6154 	return rc;
6155 }
6156 
6157 /**
6158  * _base_make_ioc_operational - put controller in OPERATIONAL state
6159  * @ioc: per adapter object
6160  *
6161  * Return: 0 for success, non-zero for failure.
6162  */
6163 static int
6164 _base_make_ioc_operational(struct MPT3SAS_ADAPTER *ioc)
6165 {
6166 	int r, i, index;
6167 	unsigned long	flags;
6168 	u32 reply_address;
6169 	u16 smid;
6170 	struct _tr_list *delayed_tr, *delayed_tr_next;
6171 	struct _sc_list *delayed_sc, *delayed_sc_next;
6172 	struct _event_ack_list *delayed_event_ack, *delayed_event_ack_next;
6173 	u8 hide_flag;
6174 	struct adapter_reply_queue *reply_q;
6175 	Mpi2ReplyDescriptorsUnion_t *reply_post_free_contig;
6176 
6177 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6178 
6179 	/* clean the delayed target reset list */
6180 	list_for_each_entry_safe(delayed_tr, delayed_tr_next,
6181 	    &ioc->delayed_tr_list, list) {
6182 		list_del(&delayed_tr->list);
6183 		kfree(delayed_tr);
6184 	}
6185 
6186 
6187 	list_for_each_entry_safe(delayed_tr, delayed_tr_next,
6188 	    &ioc->delayed_tr_volume_list, list) {
6189 		list_del(&delayed_tr->list);
6190 		kfree(delayed_tr);
6191 	}
6192 
6193 	list_for_each_entry_safe(delayed_sc, delayed_sc_next,
6194 	    &ioc->delayed_sc_list, list) {
6195 		list_del(&delayed_sc->list);
6196 		kfree(delayed_sc);
6197 	}
6198 
6199 	list_for_each_entry_safe(delayed_event_ack, delayed_event_ack_next,
6200 	    &ioc->delayed_event_ack_list, list) {
6201 		list_del(&delayed_event_ack->list);
6202 		kfree(delayed_event_ack);
6203 	}
6204 
6205 	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
6206 
6207 	/* hi-priority queue */
6208 	INIT_LIST_HEAD(&ioc->hpr_free_list);
6209 	smid = ioc->hi_priority_smid;
6210 	for (i = 0; i < ioc->hi_priority_depth; i++, smid++) {
6211 		ioc->hpr_lookup[i].cb_idx = 0xFF;
6212 		ioc->hpr_lookup[i].smid = smid;
6213 		list_add_tail(&ioc->hpr_lookup[i].tracker_list,
6214 		    &ioc->hpr_free_list);
6215 	}
6216 
6217 	/* internal queue */
6218 	INIT_LIST_HEAD(&ioc->internal_free_list);
6219 	smid = ioc->internal_smid;
6220 	for (i = 0; i < ioc->internal_depth; i++, smid++) {
6221 		ioc->internal_lookup[i].cb_idx = 0xFF;
6222 		ioc->internal_lookup[i].smid = smid;
6223 		list_add_tail(&ioc->internal_lookup[i].tracker_list,
6224 		    &ioc->internal_free_list);
6225 	}
6226 
6227 	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
6228 
6229 	/* initialize Reply Free Queue */
6230 	for (i = 0, reply_address = (u32)ioc->reply_dma ;
6231 	    i < ioc->reply_free_queue_depth ; i++, reply_address +=
6232 	    ioc->reply_sz) {
6233 		ioc->reply_free[i] = cpu_to_le32(reply_address);
6234 		if (ioc->is_mcpu_endpoint)
6235 			_base_clone_reply_to_sys_mem(ioc,
6236 					reply_address, i);
6237 	}
6238 
6239 	/* initialize reply queues */
6240 	if (ioc->is_driver_loading)
6241 		_base_assign_reply_queues(ioc);
6242 
6243 	/* initialize Reply Post Free Queue */
6244 	index = 0;
6245 	reply_post_free_contig = ioc->reply_post[0].reply_post_free;
6246 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
6247 		/*
6248 		 * If RDPQ is enabled, switch to the next allocation.
6249 		 * Otherwise advance within the contiguous region.
6250 		 */
6251 		if (ioc->rdpq_array_enable) {
6252 			reply_q->reply_post_free =
6253 				ioc->reply_post[index++].reply_post_free;
6254 		} else {
6255 			reply_q->reply_post_free = reply_post_free_contig;
6256 			reply_post_free_contig += ioc->reply_post_queue_depth;
6257 		}
6258 
6259 		reply_q->reply_post_host_index = 0;
6260 		for (i = 0; i < ioc->reply_post_queue_depth; i++)
6261 			reply_q->reply_post_free[i].Words =
6262 			    cpu_to_le64(ULLONG_MAX);
6263 		if (!_base_is_controller_msix_enabled(ioc))
6264 			goto skip_init_reply_post_free_queue;
6265 	}
6266  skip_init_reply_post_free_queue:
6267 
6268 	r = _base_send_ioc_init(ioc);
6269 	if (r)
6270 		return r;
6271 
6272 	/* initialize reply free host index */
6273 	ioc->reply_free_host_index = ioc->reply_free_queue_depth - 1;
6274 	writel(ioc->reply_free_host_index, &ioc->chip->ReplyFreeHostIndex);
6275 
6276 	/* initialize reply post host index */
6277 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
6278 		if (ioc->combined_reply_queue)
6279 			writel((reply_q->msix_index & 7)<<
6280 			   MPI2_RPHI_MSIX_INDEX_SHIFT,
6281 			   ioc->replyPostRegisterIndex[reply_q->msix_index/8]);
6282 		else
6283 			writel(reply_q->msix_index <<
6284 				MPI2_RPHI_MSIX_INDEX_SHIFT,
6285 				&ioc->chip->ReplyPostHostIndex);
6286 
6287 		if (!_base_is_controller_msix_enabled(ioc))
6288 			goto skip_init_reply_post_host_index;
6289 	}
6290 
6291  skip_init_reply_post_host_index:
6292 
6293 	_base_unmask_interrupts(ioc);
6294 
6295 	if (ioc->hba_mpi_version_belonged != MPI2_VERSION) {
6296 		r = _base_display_fwpkg_version(ioc);
6297 		if (r)
6298 			return r;
6299 	}
6300 
6301 	_base_static_config_pages(ioc);
6302 	r = _base_event_notification(ioc);
6303 	if (r)
6304 		return r;
6305 
6306 	if (ioc->is_driver_loading) {
6307 
6308 		if (ioc->is_warpdrive && ioc->manu_pg10.OEMIdentifier
6309 		    == 0x80) {
6310 			hide_flag = (u8) (
6311 			    le32_to_cpu(ioc->manu_pg10.OEMSpecificFlags0) &
6312 			    MFG_PAGE10_HIDE_SSDS_MASK);
6313 			if (hide_flag != MFG_PAGE10_HIDE_SSDS_MASK)
6314 				ioc->mfg_pg10_hide_flag = hide_flag;
6315 		}
6316 
6317 		ioc->wait_for_discovery_to_complete =
6318 		    _base_determine_wait_on_discovery(ioc);
6319 
6320 		return r; /* scan_start and scan_finished support */
6321 	}
6322 
6323 	r = _base_send_port_enable(ioc);
6324 	if (r)
6325 		return r;
6326 
6327 	return r;
6328 }
6329 
6330 /**
6331  * mpt3sas_base_free_resources - free resources controller resources
6332  * @ioc: per adapter object
6333  */
6334 void
6335 mpt3sas_base_free_resources(struct MPT3SAS_ADAPTER *ioc)
6336 {
6337 	dexitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6338 
6339 	/* synchronizing freeing resource with pci_access_mutex lock */
6340 	mutex_lock(&ioc->pci_access_mutex);
6341 	if (ioc->chip_phys && ioc->chip) {
6342 		_base_mask_interrupts(ioc);
6343 		ioc->shost_recovery = 1;
6344 		_base_make_ioc_ready(ioc, SOFT_RESET);
6345 		ioc->shost_recovery = 0;
6346 	}
6347 
6348 	mpt3sas_base_unmap_resources(ioc);
6349 	mutex_unlock(&ioc->pci_access_mutex);
6350 	return;
6351 }
6352 
6353 /**
6354  * mpt3sas_base_attach - attach controller instance
6355  * @ioc: per adapter object
6356  *
6357  * Return: 0 for success, non-zero for failure.
6358  */
6359 int
6360 mpt3sas_base_attach(struct MPT3SAS_ADAPTER *ioc)
6361 {
6362 	int r, i;
6363 	int cpu_id, last_cpu_id = 0;
6364 
6365 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6366 
6367 	/* setup cpu_msix_table */
6368 	ioc->cpu_count = num_online_cpus();
6369 	for_each_online_cpu(cpu_id)
6370 		last_cpu_id = cpu_id;
6371 	ioc->cpu_msix_table_sz = last_cpu_id + 1;
6372 	ioc->cpu_msix_table = kzalloc(ioc->cpu_msix_table_sz, GFP_KERNEL);
6373 	ioc->reply_queue_count = 1;
6374 	if (!ioc->cpu_msix_table) {
6375 		dfailprintk(ioc,
6376 			    ioc_info(ioc, "allocation for cpu_msix_table failed!!!\n"));
6377 		r = -ENOMEM;
6378 		goto out_free_resources;
6379 	}
6380 
6381 	if (ioc->is_warpdrive) {
6382 		ioc->reply_post_host_index = kcalloc(ioc->cpu_msix_table_sz,
6383 		    sizeof(resource_size_t *), GFP_KERNEL);
6384 		if (!ioc->reply_post_host_index) {
6385 			dfailprintk(ioc,
6386 				    ioc_info(ioc, "allocation for reply_post_host_index failed!!!\n"));
6387 			r = -ENOMEM;
6388 			goto out_free_resources;
6389 		}
6390 	}
6391 
6392 	ioc->rdpq_array_enable_assigned = 0;
6393 	ioc->dma_mask = 0;
6394 	r = mpt3sas_base_map_resources(ioc);
6395 	if (r)
6396 		goto out_free_resources;
6397 
6398 	pci_set_drvdata(ioc->pdev, ioc->shost);
6399 	r = _base_get_ioc_facts(ioc);
6400 	if (r)
6401 		goto out_free_resources;
6402 
6403 	switch (ioc->hba_mpi_version_belonged) {
6404 	case MPI2_VERSION:
6405 		ioc->build_sg_scmd = &_base_build_sg_scmd;
6406 		ioc->build_sg = &_base_build_sg;
6407 		ioc->build_zero_len_sge = &_base_build_zero_len_sge;
6408 		break;
6409 	case MPI25_VERSION:
6410 	case MPI26_VERSION:
6411 		/*
6412 		 * In SAS3.0,
6413 		 * SCSI_IO, SMP_PASSTHRU, SATA_PASSTHRU, Target Assist, and
6414 		 * Target Status - all require the IEEE formated scatter gather
6415 		 * elements.
6416 		 */
6417 		ioc->build_sg_scmd = &_base_build_sg_scmd_ieee;
6418 		ioc->build_sg = &_base_build_sg_ieee;
6419 		ioc->build_nvme_prp = &_base_build_nvme_prp;
6420 		ioc->build_zero_len_sge = &_base_build_zero_len_sge_ieee;
6421 		ioc->sge_size_ieee = sizeof(Mpi2IeeeSgeSimple64_t);
6422 
6423 		break;
6424 	}
6425 
6426 	if (ioc->is_mcpu_endpoint)
6427 		ioc->put_smid_scsi_io = &_base_put_smid_mpi_ep_scsi_io;
6428 	else
6429 		ioc->put_smid_scsi_io = &_base_put_smid_scsi_io;
6430 
6431 	/*
6432 	 * These function pointers for other requests that don't
6433 	 * the require IEEE scatter gather elements.
6434 	 *
6435 	 * For example Configuration Pages and SAS IOUNIT Control don't.
6436 	 */
6437 	ioc->build_sg_mpi = &_base_build_sg;
6438 	ioc->build_zero_len_sge_mpi = &_base_build_zero_len_sge;
6439 
6440 	r = _base_make_ioc_ready(ioc, SOFT_RESET);
6441 	if (r)
6442 		goto out_free_resources;
6443 
6444 	ioc->pfacts = kcalloc(ioc->facts.NumberOfPorts,
6445 	    sizeof(struct mpt3sas_port_facts), GFP_KERNEL);
6446 	if (!ioc->pfacts) {
6447 		r = -ENOMEM;
6448 		goto out_free_resources;
6449 	}
6450 
6451 	for (i = 0 ; i < ioc->facts.NumberOfPorts; i++) {
6452 		r = _base_get_port_facts(ioc, i);
6453 		if (r)
6454 			goto out_free_resources;
6455 	}
6456 
6457 	r = _base_allocate_memory_pools(ioc);
6458 	if (r)
6459 		goto out_free_resources;
6460 
6461 	init_waitqueue_head(&ioc->reset_wq);
6462 
6463 	/* allocate memory pd handle bitmask list */
6464 	ioc->pd_handles_sz = (ioc->facts.MaxDevHandle / 8);
6465 	if (ioc->facts.MaxDevHandle % 8)
6466 		ioc->pd_handles_sz++;
6467 	ioc->pd_handles = kzalloc(ioc->pd_handles_sz,
6468 	    GFP_KERNEL);
6469 	if (!ioc->pd_handles) {
6470 		r = -ENOMEM;
6471 		goto out_free_resources;
6472 	}
6473 	ioc->blocking_handles = kzalloc(ioc->pd_handles_sz,
6474 	    GFP_KERNEL);
6475 	if (!ioc->blocking_handles) {
6476 		r = -ENOMEM;
6477 		goto out_free_resources;
6478 	}
6479 
6480 	/* allocate memory for pending OS device add list */
6481 	ioc->pend_os_device_add_sz = (ioc->facts.MaxDevHandle / 8);
6482 	if (ioc->facts.MaxDevHandle % 8)
6483 		ioc->pend_os_device_add_sz++;
6484 	ioc->pend_os_device_add = kzalloc(ioc->pend_os_device_add_sz,
6485 	    GFP_KERNEL);
6486 	if (!ioc->pend_os_device_add)
6487 		goto out_free_resources;
6488 
6489 	ioc->device_remove_in_progress_sz = ioc->pend_os_device_add_sz;
6490 	ioc->device_remove_in_progress =
6491 		kzalloc(ioc->device_remove_in_progress_sz, GFP_KERNEL);
6492 	if (!ioc->device_remove_in_progress)
6493 		goto out_free_resources;
6494 
6495 	ioc->fwfault_debug = mpt3sas_fwfault_debug;
6496 
6497 	/* base internal command bits */
6498 	mutex_init(&ioc->base_cmds.mutex);
6499 	ioc->base_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6500 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
6501 
6502 	/* port_enable command bits */
6503 	ioc->port_enable_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6504 	ioc->port_enable_cmds.status = MPT3_CMD_NOT_USED;
6505 
6506 	/* transport internal command bits */
6507 	ioc->transport_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6508 	ioc->transport_cmds.status = MPT3_CMD_NOT_USED;
6509 	mutex_init(&ioc->transport_cmds.mutex);
6510 
6511 	/* scsih internal command bits */
6512 	ioc->scsih_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6513 	ioc->scsih_cmds.status = MPT3_CMD_NOT_USED;
6514 	mutex_init(&ioc->scsih_cmds.mutex);
6515 
6516 	/* task management internal command bits */
6517 	ioc->tm_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6518 	ioc->tm_cmds.status = MPT3_CMD_NOT_USED;
6519 	mutex_init(&ioc->tm_cmds.mutex);
6520 
6521 	/* config page internal command bits */
6522 	ioc->config_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6523 	ioc->config_cmds.status = MPT3_CMD_NOT_USED;
6524 	mutex_init(&ioc->config_cmds.mutex);
6525 
6526 	/* ctl module internal command bits */
6527 	ioc->ctl_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
6528 	ioc->ctl_cmds.sense = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
6529 	ioc->ctl_cmds.status = MPT3_CMD_NOT_USED;
6530 	mutex_init(&ioc->ctl_cmds.mutex);
6531 
6532 	if (!ioc->base_cmds.reply || !ioc->port_enable_cmds.reply ||
6533 	    !ioc->transport_cmds.reply || !ioc->scsih_cmds.reply ||
6534 	    !ioc->tm_cmds.reply || !ioc->config_cmds.reply ||
6535 	    !ioc->ctl_cmds.reply || !ioc->ctl_cmds.sense) {
6536 		r = -ENOMEM;
6537 		goto out_free_resources;
6538 	}
6539 
6540 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
6541 		ioc->event_masks[i] = -1;
6542 
6543 	/* here we enable the events we care about */
6544 	_base_unmask_events(ioc, MPI2_EVENT_SAS_DISCOVERY);
6545 	_base_unmask_events(ioc, MPI2_EVENT_SAS_BROADCAST_PRIMITIVE);
6546 	_base_unmask_events(ioc, MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST);
6547 	_base_unmask_events(ioc, MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE);
6548 	_base_unmask_events(ioc, MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE);
6549 	_base_unmask_events(ioc, MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST);
6550 	_base_unmask_events(ioc, MPI2_EVENT_IR_VOLUME);
6551 	_base_unmask_events(ioc, MPI2_EVENT_IR_PHYSICAL_DISK);
6552 	_base_unmask_events(ioc, MPI2_EVENT_IR_OPERATION_STATUS);
6553 	_base_unmask_events(ioc, MPI2_EVENT_LOG_ENTRY_ADDED);
6554 	_base_unmask_events(ioc, MPI2_EVENT_TEMP_THRESHOLD);
6555 	_base_unmask_events(ioc, MPI2_EVENT_ACTIVE_CABLE_EXCEPTION);
6556 	_base_unmask_events(ioc, MPI2_EVENT_SAS_DEVICE_DISCOVERY_ERROR);
6557 	if (ioc->hba_mpi_version_belonged == MPI26_VERSION) {
6558 		if (ioc->is_gen35_ioc) {
6559 			_base_unmask_events(ioc,
6560 				MPI2_EVENT_PCIE_DEVICE_STATUS_CHANGE);
6561 			_base_unmask_events(ioc, MPI2_EVENT_PCIE_ENUMERATION);
6562 			_base_unmask_events(ioc,
6563 				MPI2_EVENT_PCIE_TOPOLOGY_CHANGE_LIST);
6564 		}
6565 	}
6566 	r = _base_make_ioc_operational(ioc);
6567 	if (r)
6568 		goto out_free_resources;
6569 
6570 	ioc->non_operational_loop = 0;
6571 	ioc->got_task_abort_from_ioctl = 0;
6572 	return 0;
6573 
6574  out_free_resources:
6575 
6576 	ioc->remove_host = 1;
6577 
6578 	mpt3sas_base_free_resources(ioc);
6579 	_base_release_memory_pools(ioc);
6580 	pci_set_drvdata(ioc->pdev, NULL);
6581 	kfree(ioc->cpu_msix_table);
6582 	if (ioc->is_warpdrive)
6583 		kfree(ioc->reply_post_host_index);
6584 	kfree(ioc->pd_handles);
6585 	kfree(ioc->blocking_handles);
6586 	kfree(ioc->device_remove_in_progress);
6587 	kfree(ioc->pend_os_device_add);
6588 	kfree(ioc->tm_cmds.reply);
6589 	kfree(ioc->transport_cmds.reply);
6590 	kfree(ioc->scsih_cmds.reply);
6591 	kfree(ioc->config_cmds.reply);
6592 	kfree(ioc->base_cmds.reply);
6593 	kfree(ioc->port_enable_cmds.reply);
6594 	kfree(ioc->ctl_cmds.reply);
6595 	kfree(ioc->ctl_cmds.sense);
6596 	kfree(ioc->pfacts);
6597 	ioc->ctl_cmds.reply = NULL;
6598 	ioc->base_cmds.reply = NULL;
6599 	ioc->tm_cmds.reply = NULL;
6600 	ioc->scsih_cmds.reply = NULL;
6601 	ioc->transport_cmds.reply = NULL;
6602 	ioc->config_cmds.reply = NULL;
6603 	ioc->pfacts = NULL;
6604 	return r;
6605 }
6606 
6607 
6608 /**
6609  * mpt3sas_base_detach - remove controller instance
6610  * @ioc: per adapter object
6611  */
6612 void
6613 mpt3sas_base_detach(struct MPT3SAS_ADAPTER *ioc)
6614 {
6615 	dexitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6616 
6617 	mpt3sas_base_stop_watchdog(ioc);
6618 	mpt3sas_base_free_resources(ioc);
6619 	_base_release_memory_pools(ioc);
6620 	mpt3sas_free_enclosure_list(ioc);
6621 	pci_set_drvdata(ioc->pdev, NULL);
6622 	kfree(ioc->cpu_msix_table);
6623 	if (ioc->is_warpdrive)
6624 		kfree(ioc->reply_post_host_index);
6625 	kfree(ioc->pd_handles);
6626 	kfree(ioc->blocking_handles);
6627 	kfree(ioc->device_remove_in_progress);
6628 	kfree(ioc->pend_os_device_add);
6629 	kfree(ioc->pfacts);
6630 	kfree(ioc->ctl_cmds.reply);
6631 	kfree(ioc->ctl_cmds.sense);
6632 	kfree(ioc->base_cmds.reply);
6633 	kfree(ioc->port_enable_cmds.reply);
6634 	kfree(ioc->tm_cmds.reply);
6635 	kfree(ioc->transport_cmds.reply);
6636 	kfree(ioc->scsih_cmds.reply);
6637 	kfree(ioc->config_cmds.reply);
6638 }
6639 
6640 /**
6641  * _base_pre_reset_handler - pre reset handler
6642  * @ioc: per adapter object
6643  */
6644 static void _base_pre_reset_handler(struct MPT3SAS_ADAPTER *ioc)
6645 {
6646 	mpt3sas_scsih_pre_reset_handler(ioc);
6647 	mpt3sas_ctl_pre_reset_handler(ioc);
6648 	dtmprintk(ioc, ioc_info(ioc, "%s: MPT3_IOC_PRE_RESET\n", __func__));
6649 }
6650 
6651 /**
6652  * _base_after_reset_handler - after reset handler
6653  * @ioc: per adapter object
6654  */
6655 static void _base_after_reset_handler(struct MPT3SAS_ADAPTER *ioc)
6656 {
6657 	mpt3sas_scsih_after_reset_handler(ioc);
6658 	mpt3sas_ctl_after_reset_handler(ioc);
6659 	dtmprintk(ioc, ioc_info(ioc, "%s: MPT3_IOC_AFTER_RESET\n", __func__));
6660 	if (ioc->transport_cmds.status & MPT3_CMD_PENDING) {
6661 		ioc->transport_cmds.status |= MPT3_CMD_RESET;
6662 		mpt3sas_base_free_smid(ioc, ioc->transport_cmds.smid);
6663 		complete(&ioc->transport_cmds.done);
6664 	}
6665 	if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
6666 		ioc->base_cmds.status |= MPT3_CMD_RESET;
6667 		mpt3sas_base_free_smid(ioc, ioc->base_cmds.smid);
6668 		complete(&ioc->base_cmds.done);
6669 	}
6670 	if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
6671 		ioc->port_enable_failed = 1;
6672 		ioc->port_enable_cmds.status |= MPT3_CMD_RESET;
6673 		mpt3sas_base_free_smid(ioc, ioc->port_enable_cmds.smid);
6674 		if (ioc->is_driver_loading) {
6675 			ioc->start_scan_failed =
6676 				MPI2_IOCSTATUS_INTERNAL_ERROR;
6677 			ioc->start_scan = 0;
6678 			ioc->port_enable_cmds.status =
6679 				MPT3_CMD_NOT_USED;
6680 		} else {
6681 			complete(&ioc->port_enable_cmds.done);
6682 		}
6683 	}
6684 	if (ioc->config_cmds.status & MPT3_CMD_PENDING) {
6685 		ioc->config_cmds.status |= MPT3_CMD_RESET;
6686 		mpt3sas_base_free_smid(ioc, ioc->config_cmds.smid);
6687 		ioc->config_cmds.smid = USHRT_MAX;
6688 		complete(&ioc->config_cmds.done);
6689 	}
6690 }
6691 
6692 /**
6693  * _base_reset_done_handler - reset done handler
6694  * @ioc: per adapter object
6695  */
6696 static void _base_reset_done_handler(struct MPT3SAS_ADAPTER *ioc)
6697 {
6698 	mpt3sas_scsih_reset_done_handler(ioc);
6699 	mpt3sas_ctl_reset_done_handler(ioc);
6700 	dtmprintk(ioc, ioc_info(ioc, "%s: MPT3_IOC_DONE_RESET\n", __func__));
6701 }
6702 
6703 /**
6704  * mpt3sas_wait_for_commands_to_complete - reset controller
6705  * @ioc: Pointer to MPT_ADAPTER structure
6706  *
6707  * This function is waiting 10s for all pending commands to complete
6708  * prior to putting controller in reset.
6709  */
6710 void
6711 mpt3sas_wait_for_commands_to_complete(struct MPT3SAS_ADAPTER *ioc)
6712 {
6713 	u32 ioc_state;
6714 
6715 	ioc->pending_io_count = 0;
6716 
6717 	ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
6718 	if ((ioc_state & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_OPERATIONAL)
6719 		return;
6720 
6721 	/* pending command count */
6722 	ioc->pending_io_count = scsi_host_busy(ioc->shost);
6723 
6724 	if (!ioc->pending_io_count)
6725 		return;
6726 
6727 	/* wait for pending commands to complete */
6728 	wait_event_timeout(ioc->reset_wq, ioc->pending_io_count == 0, 10 * HZ);
6729 }
6730 
6731 /**
6732  * mpt3sas_base_hard_reset_handler - reset controller
6733  * @ioc: Pointer to MPT_ADAPTER structure
6734  * @type: FORCE_BIG_HAMMER or SOFT_RESET
6735  *
6736  * Return: 0 for success, non-zero for failure.
6737  */
6738 int
6739 mpt3sas_base_hard_reset_handler(struct MPT3SAS_ADAPTER *ioc,
6740 	enum reset_type type)
6741 {
6742 	int r;
6743 	unsigned long flags;
6744 	u32 ioc_state;
6745 	u8 is_fault = 0, is_trigger = 0;
6746 
6747 	dtmprintk(ioc, ioc_info(ioc, "%s: enter\n", __func__));
6748 
6749 	if (ioc->pci_error_recovery) {
6750 		ioc_err(ioc, "%s: pci error recovery reset\n", __func__);
6751 		r = 0;
6752 		goto out_unlocked;
6753 	}
6754 
6755 	if (mpt3sas_fwfault_debug)
6756 		mpt3sas_halt_firmware(ioc);
6757 
6758 	/* wait for an active reset in progress to complete */
6759 	mutex_lock(&ioc->reset_in_progress_mutex);
6760 
6761 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
6762 	ioc->shost_recovery = 1;
6763 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
6764 
6765 	if ((ioc->diag_buffer_status[MPI2_DIAG_BUF_TYPE_TRACE] &
6766 	    MPT3_DIAG_BUFFER_IS_REGISTERED) &&
6767 	    (!(ioc->diag_buffer_status[MPI2_DIAG_BUF_TYPE_TRACE] &
6768 	    MPT3_DIAG_BUFFER_IS_RELEASED))) {
6769 		is_trigger = 1;
6770 		ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
6771 		if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT)
6772 			is_fault = 1;
6773 	}
6774 	_base_pre_reset_handler(ioc);
6775 	mpt3sas_wait_for_commands_to_complete(ioc);
6776 	_base_mask_interrupts(ioc);
6777 	r = _base_make_ioc_ready(ioc, type);
6778 	if (r)
6779 		goto out;
6780 	_base_after_reset_handler(ioc);
6781 
6782 	/* If this hard reset is called while port enable is active, then
6783 	 * there is no reason to call make_ioc_operational
6784 	 */
6785 	if (ioc->is_driver_loading && ioc->port_enable_failed) {
6786 		ioc->remove_host = 1;
6787 		r = -EFAULT;
6788 		goto out;
6789 	}
6790 	r = _base_get_ioc_facts(ioc);
6791 	if (r)
6792 		goto out;
6793 
6794 	if (ioc->rdpq_array_enable && !ioc->rdpq_array_capable)
6795 		panic("%s: Issue occurred with flashing controller firmware."
6796 		      "Please reboot the system and ensure that the correct"
6797 		      " firmware version is running\n", ioc->name);
6798 
6799 	r = _base_make_ioc_operational(ioc);
6800 	if (!r)
6801 		_base_reset_done_handler(ioc);
6802 
6803  out:
6804 	dtmprintk(ioc,
6805 		  ioc_info(ioc, "%s: %s\n",
6806 			   __func__, r == 0 ? "SUCCESS" : "FAILED"));
6807 
6808 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
6809 	ioc->shost_recovery = 0;
6810 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
6811 	ioc->ioc_reset_count++;
6812 	mutex_unlock(&ioc->reset_in_progress_mutex);
6813 
6814  out_unlocked:
6815 	if ((r == 0) && is_trigger) {
6816 		if (is_fault)
6817 			mpt3sas_trigger_master(ioc, MASTER_TRIGGER_FW_FAULT);
6818 		else
6819 			mpt3sas_trigger_master(ioc,
6820 			    MASTER_TRIGGER_ADAPTER_RESET);
6821 	}
6822 	dtmprintk(ioc, ioc_info(ioc, "%s: exit\n", __func__));
6823 	return r;
6824 }
6825