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, 0444);
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, 0444);
82 MODULE_PARM_DESC(max_sgl_entries, " max sg entries ");
83 
84 static int msix_disable = -1;
85 module_param(msix_disable, int, 0444);
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, 0444);
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, 0444);
94 MODULE_PARM_DESC(max_msix_vectors,
95 	" max msix vectors");
96 
97 static int irqpoll_weight = -1;
98 module_param(irqpoll_weight, int, 0444);
99 MODULE_PARM_DESC(irqpoll_weight,
100 	"irq poll weight (default= one fourth of HBA queue depth)");
101 
102 static int mpt3sas_fwfault_debug;
103 MODULE_PARM_DESC(mpt3sas_fwfault_debug,
104 	" enable detection of firmware fault and halt firmware - (default=0)");
105 
106 static int perf_mode = -1;
107 module_param(perf_mode, int, 0444);
108 MODULE_PARM_DESC(perf_mode,
109 	"Performance mode (only for Aero/Sea Generation), options:\n\t\t"
110 	"0 - balanced: high iops mode is enabled &\n\t\t"
111 	"interrupt coalescing is enabled only on high iops queues,\n\t\t"
112 	"1 - iops: high iops mode is disabled &\n\t\t"
113 	"interrupt coalescing is enabled on all queues,\n\t\t"
114 	"2 - latency: high iops mode is disabled &\n\t\t"
115 	"interrupt coalescing is enabled on all queues with timeout value 0xA,\n"
116 	"\t\tdefault - default perf_mode is 'balanced'"
117 	);
118 
119 static int poll_queues;
120 module_param(poll_queues, int, 0444);
121 MODULE_PARM_DESC(poll_queues, "Number of queues to be use for io_uring poll mode.\n\t\t"
122 	"This parameter is effective only if host_tagset_enable=1. &\n\t\t"
123 	"when poll_queues are enabled then &\n\t\t"
124 	"perf_mode is set to latency mode. &\n\t\t"
125 	);
126 
127 enum mpt3sas_perf_mode {
128 	MPT_PERF_MODE_DEFAULT	= -1,
129 	MPT_PERF_MODE_BALANCED	= 0,
130 	MPT_PERF_MODE_IOPS	= 1,
131 	MPT_PERF_MODE_LATENCY	= 2,
132 };
133 
134 static int
135 _base_wait_on_iocstate(struct MPT3SAS_ADAPTER *ioc,
136 		u32 ioc_state, int timeout);
137 static int
138 _base_get_ioc_facts(struct MPT3SAS_ADAPTER *ioc);
139 static void
140 _base_clear_outstanding_commands(struct MPT3SAS_ADAPTER *ioc);
141 
142 /**
143  * mpt3sas_base_check_cmd_timeout - Function
144  *		to check timeout and command termination due
145  *		to Host reset.
146  *
147  * @ioc:	per adapter object.
148  * @status:	Status of issued command.
149  * @mpi_request:mf request pointer.
150  * @sz:		size of buffer.
151  *
152  * Return: 1/0 Reset to be done or Not
153  */
154 u8
155 mpt3sas_base_check_cmd_timeout(struct MPT3SAS_ADAPTER *ioc,
156 		u8 status, void *mpi_request, int sz)
157 {
158 	u8 issue_reset = 0;
159 
160 	if (!(status & MPT3_CMD_RESET))
161 		issue_reset = 1;
162 
163 	ioc_err(ioc, "Command %s\n",
164 		issue_reset == 0 ? "terminated due to Host Reset" : "Timeout");
165 	_debug_dump_mf(mpi_request, sz);
166 
167 	return issue_reset;
168 }
169 
170 /**
171  * _scsih_set_fwfault_debug - global setting of ioc->fwfault_debug.
172  * @val: ?
173  * @kp: ?
174  *
175  * Return: ?
176  */
177 static int
178 _scsih_set_fwfault_debug(const char *val, const struct kernel_param *kp)
179 {
180 	int ret = param_set_int(val, kp);
181 	struct MPT3SAS_ADAPTER *ioc;
182 
183 	if (ret)
184 		return ret;
185 
186 	/* global ioc spinlock to protect controller list on list operations */
187 	pr_info("setting fwfault_debug(%d)\n", mpt3sas_fwfault_debug);
188 	spin_lock(&gioc_lock);
189 	list_for_each_entry(ioc, &mpt3sas_ioc_list, list)
190 		ioc->fwfault_debug = mpt3sas_fwfault_debug;
191 	spin_unlock(&gioc_lock);
192 	return 0;
193 }
194 module_param_call(mpt3sas_fwfault_debug, _scsih_set_fwfault_debug,
195 	param_get_int, &mpt3sas_fwfault_debug, 0644);
196 
197 /**
198  * _base_readl_aero - retry readl for max three times.
199  * @addr: MPT Fusion system interface register address
200  *
201  * Retry the readl() for max three times if it gets zero value
202  * while reading the system interface register.
203  */
204 static inline u32
205 _base_readl_aero(const volatile void __iomem *addr)
206 {
207 	u32 i = 0, ret_val;
208 
209 	do {
210 		ret_val = readl(addr);
211 		i++;
212 	} while (ret_val == 0 && i < 3);
213 
214 	return ret_val;
215 }
216 
217 static inline u32
218 _base_readl(const volatile void __iomem *addr)
219 {
220 	return readl(addr);
221 }
222 
223 /**
224  * _base_clone_reply_to_sys_mem - copies reply to reply free iomem
225  *				  in BAR0 space.
226  *
227  * @ioc: per adapter object
228  * @reply: reply message frame(lower 32bit addr)
229  * @index: System request message index.
230  */
231 static void
232 _base_clone_reply_to_sys_mem(struct MPT3SAS_ADAPTER *ioc, u32 reply,
233 		u32 index)
234 {
235 	/*
236 	 * 256 is offset within sys register.
237 	 * 256 offset MPI frame starts. Max MPI frame supported is 32.
238 	 * 32 * 128 = 4K. From here, Clone of reply free for mcpu starts
239 	 */
240 	u16 cmd_credit = ioc->facts.RequestCredit + 1;
241 	void __iomem *reply_free_iomem = (void __iomem *)ioc->chip +
242 			MPI_FRAME_START_OFFSET +
243 			(cmd_credit * ioc->request_sz) + (index * sizeof(u32));
244 
245 	writel(reply, reply_free_iomem);
246 }
247 
248 /**
249  * _base_clone_mpi_to_sys_mem - Writes/copies MPI frames
250  *				to system/BAR0 region.
251  *
252  * @dst_iomem: Pointer to the destination location in BAR0 space.
253  * @src: Pointer to the Source data.
254  * @size: Size of data to be copied.
255  */
256 static void
257 _base_clone_mpi_to_sys_mem(void *dst_iomem, void *src, u32 size)
258 {
259 	int i;
260 	u32 *src_virt_mem = (u32 *)src;
261 
262 	for (i = 0; i < size/4; i++)
263 		writel((u32)src_virt_mem[i],
264 				(void __iomem *)dst_iomem + (i * 4));
265 }
266 
267 /**
268  * _base_clone_to_sys_mem - Writes/copies data to system/BAR0 region
269  *
270  * @dst_iomem: Pointer to the destination location in BAR0 space.
271  * @src: Pointer to the Source data.
272  * @size: Size of data to be copied.
273  */
274 static void
275 _base_clone_to_sys_mem(void __iomem *dst_iomem, void *src, u32 size)
276 {
277 	int i;
278 	u32 *src_virt_mem = (u32 *)(src);
279 
280 	for (i = 0; i < size/4; i++)
281 		writel((u32)src_virt_mem[i],
282 			(void __iomem *)dst_iomem + (i * 4));
283 }
284 
285 /**
286  * _base_get_chain - Calculates and Returns virtual chain address
287  *			 for the provided smid in BAR0 space.
288  *
289  * @ioc: per adapter object
290  * @smid: system request message index
291  * @sge_chain_count: Scatter gather chain count.
292  *
293  * Return: the chain address.
294  */
295 static inline void __iomem*
296 _base_get_chain(struct MPT3SAS_ADAPTER *ioc, u16 smid,
297 		u8 sge_chain_count)
298 {
299 	void __iomem *base_chain, *chain_virt;
300 	u16 cmd_credit = ioc->facts.RequestCredit + 1;
301 
302 	base_chain  = (void __iomem *)ioc->chip + MPI_FRAME_START_OFFSET +
303 		(cmd_credit * ioc->request_sz) +
304 		REPLY_FREE_POOL_SIZE;
305 	chain_virt = base_chain + (smid * ioc->facts.MaxChainDepth *
306 			ioc->request_sz) + (sge_chain_count * ioc->request_sz);
307 	return chain_virt;
308 }
309 
310 /**
311  * _base_get_chain_phys - Calculates and Returns physical address
312  *			in BAR0 for scatter gather chains, for
313  *			the provided smid.
314  *
315  * @ioc: per adapter object
316  * @smid: system request message index
317  * @sge_chain_count: Scatter gather chain count.
318  *
319  * Return: Physical chain address.
320  */
321 static inline phys_addr_t
322 _base_get_chain_phys(struct MPT3SAS_ADAPTER *ioc, u16 smid,
323 		u8 sge_chain_count)
324 {
325 	phys_addr_t base_chain_phys, chain_phys;
326 	u16 cmd_credit = ioc->facts.RequestCredit + 1;
327 
328 	base_chain_phys  = ioc->chip_phys + MPI_FRAME_START_OFFSET +
329 		(cmd_credit * ioc->request_sz) +
330 		REPLY_FREE_POOL_SIZE;
331 	chain_phys = base_chain_phys + (smid * ioc->facts.MaxChainDepth *
332 			ioc->request_sz) + (sge_chain_count * ioc->request_sz);
333 	return chain_phys;
334 }
335 
336 /**
337  * _base_get_buffer_bar0 - Calculates and Returns BAR0 mapped Host
338  *			buffer address for the provided smid.
339  *			(Each smid can have 64K starts from 17024)
340  *
341  * @ioc: per adapter object
342  * @smid: system request message index
343  *
344  * Return: Pointer to buffer location in BAR0.
345  */
346 
347 static void __iomem *
348 _base_get_buffer_bar0(struct MPT3SAS_ADAPTER *ioc, u16 smid)
349 {
350 	u16 cmd_credit = ioc->facts.RequestCredit + 1;
351 	// Added extra 1 to reach end of chain.
352 	void __iomem *chain_end = _base_get_chain(ioc,
353 			cmd_credit + 1,
354 			ioc->facts.MaxChainDepth);
355 	return chain_end + (smid * 64 * 1024);
356 }
357 
358 /**
359  * _base_get_buffer_phys_bar0 - Calculates and Returns BAR0 mapped
360  *		Host buffer Physical address for the provided smid.
361  *		(Each smid can have 64K starts from 17024)
362  *
363  * @ioc: per adapter object
364  * @smid: system request message index
365  *
366  * Return: Pointer to buffer location in BAR0.
367  */
368 static phys_addr_t
369 _base_get_buffer_phys_bar0(struct MPT3SAS_ADAPTER *ioc, u16 smid)
370 {
371 	u16 cmd_credit = ioc->facts.RequestCredit + 1;
372 	phys_addr_t chain_end_phys = _base_get_chain_phys(ioc,
373 			cmd_credit + 1,
374 			ioc->facts.MaxChainDepth);
375 	return chain_end_phys + (smid * 64 * 1024);
376 }
377 
378 /**
379  * _base_get_chain_buffer_dma_to_chain_buffer - Iterates chain
380  *			lookup list and Provides chain_buffer
381  *			address for the matching dma address.
382  *			(Each smid can have 64K starts from 17024)
383  *
384  * @ioc: per adapter object
385  * @chain_buffer_dma: Chain buffer dma address.
386  *
387  * Return: Pointer to chain buffer. Or Null on Failure.
388  */
389 static void *
390 _base_get_chain_buffer_dma_to_chain_buffer(struct MPT3SAS_ADAPTER *ioc,
391 		dma_addr_t chain_buffer_dma)
392 {
393 	u16 index, j;
394 	struct chain_tracker *ct;
395 
396 	for (index = 0; index < ioc->scsiio_depth; index++) {
397 		for (j = 0; j < ioc->chains_needed_per_io; j++) {
398 			ct = &ioc->chain_lookup[index].chains_per_smid[j];
399 			if (ct && ct->chain_buffer_dma == chain_buffer_dma)
400 				return ct->chain_buffer;
401 		}
402 	}
403 	ioc_info(ioc, "Provided chain_buffer_dma address is not in the lookup list\n");
404 	return NULL;
405 }
406 
407 /**
408  * _clone_sg_entries -	MPI EP's scsiio and config requests
409  *			are handled here. Base function for
410  *			double buffering, before submitting
411  *			the requests.
412  *
413  * @ioc: per adapter object.
414  * @mpi_request: mf request pointer.
415  * @smid: system request message index.
416  */
417 static void _clone_sg_entries(struct MPT3SAS_ADAPTER *ioc,
418 		void *mpi_request, u16 smid)
419 {
420 	Mpi2SGESimple32_t *sgel, *sgel_next;
421 	u32  sgl_flags, sge_chain_count = 0;
422 	bool is_write = false;
423 	u16 i = 0;
424 	void __iomem *buffer_iomem;
425 	phys_addr_t buffer_iomem_phys;
426 	void __iomem *buff_ptr;
427 	phys_addr_t buff_ptr_phys;
428 	void __iomem *dst_chain_addr[MCPU_MAX_CHAINS_PER_IO];
429 	void *src_chain_addr[MCPU_MAX_CHAINS_PER_IO];
430 	phys_addr_t dst_addr_phys;
431 	MPI2RequestHeader_t *request_hdr;
432 	struct scsi_cmnd *scmd;
433 	struct scatterlist *sg_scmd = NULL;
434 	int is_scsiio_req = 0;
435 
436 	request_hdr = (MPI2RequestHeader_t *) mpi_request;
437 
438 	if (request_hdr->Function == MPI2_FUNCTION_SCSI_IO_REQUEST) {
439 		Mpi25SCSIIORequest_t *scsiio_request =
440 			(Mpi25SCSIIORequest_t *)mpi_request;
441 		sgel = (Mpi2SGESimple32_t *) &scsiio_request->SGL;
442 		is_scsiio_req = 1;
443 	} else if (request_hdr->Function == MPI2_FUNCTION_CONFIG) {
444 		Mpi2ConfigRequest_t  *config_req =
445 			(Mpi2ConfigRequest_t *)mpi_request;
446 		sgel = (Mpi2SGESimple32_t *) &config_req->PageBufferSGE;
447 	} else
448 		return;
449 
450 	/* From smid we can get scsi_cmd, once we have sg_scmd,
451 	 * we just need to get sg_virt and sg_next to get virtual
452 	 * address associated with sgel->Address.
453 	 */
454 
455 	if (is_scsiio_req) {
456 		/* Get scsi_cmd using smid */
457 		scmd = mpt3sas_scsih_scsi_lookup_get(ioc, smid);
458 		if (scmd == NULL) {
459 			ioc_err(ioc, "scmd is NULL\n");
460 			return;
461 		}
462 
463 		/* Get sg_scmd from scmd provided */
464 		sg_scmd = scsi_sglist(scmd);
465 	}
466 
467 	/*
468 	 * 0 - 255	System register
469 	 * 256 - 4352	MPI Frame. (This is based on maxCredit 32)
470 	 * 4352 - 4864	Reply_free pool (512 byte is reserved
471 	 *		considering maxCredit 32. Reply need extra
472 	 *		room, for mCPU case kept four times of
473 	 *		maxCredit).
474 	 * 4864 - 17152	SGE chain element. (32cmd * 3 chain of
475 	 *		128 byte size = 12288)
476 	 * 17152 - x	Host buffer mapped with smid.
477 	 *		(Each smid can have 64K Max IO.)
478 	 * BAR0+Last 1K MSIX Addr and Data
479 	 * Total size in use 2113664 bytes of 4MB BAR0
480 	 */
481 
482 	buffer_iomem = _base_get_buffer_bar0(ioc, smid);
483 	buffer_iomem_phys = _base_get_buffer_phys_bar0(ioc, smid);
484 
485 	buff_ptr = buffer_iomem;
486 	buff_ptr_phys = buffer_iomem_phys;
487 	WARN_ON(buff_ptr_phys > U32_MAX);
488 
489 	if (le32_to_cpu(sgel->FlagsLength) &
490 			(MPI2_SGE_FLAGS_HOST_TO_IOC << MPI2_SGE_FLAGS_SHIFT))
491 		is_write = true;
492 
493 	for (i = 0; i < MPT_MIN_PHYS_SEGMENTS + ioc->facts.MaxChainDepth; i++) {
494 
495 		sgl_flags =
496 		    (le32_to_cpu(sgel->FlagsLength) >> MPI2_SGE_FLAGS_SHIFT);
497 
498 		switch (sgl_flags & MPI2_SGE_FLAGS_ELEMENT_MASK) {
499 		case MPI2_SGE_FLAGS_CHAIN_ELEMENT:
500 			/*
501 			 * Helper function which on passing
502 			 * chain_buffer_dma returns chain_buffer. Get
503 			 * the virtual address for sgel->Address
504 			 */
505 			sgel_next =
506 				_base_get_chain_buffer_dma_to_chain_buffer(ioc,
507 						le32_to_cpu(sgel->Address));
508 			if (sgel_next == NULL)
509 				return;
510 			/*
511 			 * This is coping 128 byte chain
512 			 * frame (not a host buffer)
513 			 */
514 			dst_chain_addr[sge_chain_count] =
515 				_base_get_chain(ioc,
516 					smid, sge_chain_count);
517 			src_chain_addr[sge_chain_count] =
518 						(void *) sgel_next;
519 			dst_addr_phys = _base_get_chain_phys(ioc,
520 						smid, sge_chain_count);
521 			WARN_ON(dst_addr_phys > U32_MAX);
522 			sgel->Address =
523 				cpu_to_le32(lower_32_bits(dst_addr_phys));
524 			sgel = sgel_next;
525 			sge_chain_count++;
526 			break;
527 		case MPI2_SGE_FLAGS_SIMPLE_ELEMENT:
528 			if (is_write) {
529 				if (is_scsiio_req) {
530 					_base_clone_to_sys_mem(buff_ptr,
531 					    sg_virt(sg_scmd),
532 					    (le32_to_cpu(sgel->FlagsLength) &
533 					    0x00ffffff));
534 					/*
535 					 * FIXME: this relies on a a zero
536 					 * PCI mem_offset.
537 					 */
538 					sgel->Address =
539 					    cpu_to_le32((u32)buff_ptr_phys);
540 				} else {
541 					_base_clone_to_sys_mem(buff_ptr,
542 					    ioc->config_vaddr,
543 					    (le32_to_cpu(sgel->FlagsLength) &
544 					    0x00ffffff));
545 					sgel->Address =
546 					    cpu_to_le32((u32)buff_ptr_phys);
547 				}
548 			}
549 			buff_ptr += (le32_to_cpu(sgel->FlagsLength) &
550 			    0x00ffffff);
551 			buff_ptr_phys += (le32_to_cpu(sgel->FlagsLength) &
552 			    0x00ffffff);
553 			if ((le32_to_cpu(sgel->FlagsLength) &
554 			    (MPI2_SGE_FLAGS_END_OF_BUFFER
555 					<< MPI2_SGE_FLAGS_SHIFT)))
556 				goto eob_clone_chain;
557 			else {
558 				/*
559 				 * Every single element in MPT will have
560 				 * associated sg_next. Better to sanity that
561 				 * sg_next is not NULL, but it will be a bug
562 				 * if it is null.
563 				 */
564 				if (is_scsiio_req) {
565 					sg_scmd = sg_next(sg_scmd);
566 					if (sg_scmd)
567 						sgel++;
568 					else
569 						goto eob_clone_chain;
570 				}
571 			}
572 			break;
573 		}
574 	}
575 
576 eob_clone_chain:
577 	for (i = 0; i < sge_chain_count; i++) {
578 		if (is_scsiio_req)
579 			_base_clone_to_sys_mem(dst_chain_addr[i],
580 				src_chain_addr[i], ioc->request_sz);
581 	}
582 }
583 
584 /**
585  *  mpt3sas_remove_dead_ioc_func - kthread context to remove dead ioc
586  * @arg: input argument, used to derive ioc
587  *
588  * Return:
589  * 0 if controller is removed from pci subsystem.
590  * -1 for other case.
591  */
592 static int mpt3sas_remove_dead_ioc_func(void *arg)
593 {
594 	struct MPT3SAS_ADAPTER *ioc = (struct MPT3SAS_ADAPTER *)arg;
595 	struct pci_dev *pdev;
596 
597 	if (!ioc)
598 		return -1;
599 
600 	pdev = ioc->pdev;
601 	if (!pdev)
602 		return -1;
603 	pci_stop_and_remove_bus_device_locked(pdev);
604 	return 0;
605 }
606 
607 /**
608  * _base_sync_drv_fw_timestamp - Sync Drive-Fw TimeStamp.
609  * @ioc: Per Adapter Object
610  *
611  * Return: nothing.
612  */
613 static void _base_sync_drv_fw_timestamp(struct MPT3SAS_ADAPTER *ioc)
614 {
615 	Mpi26IoUnitControlRequest_t *mpi_request;
616 	Mpi26IoUnitControlReply_t *mpi_reply;
617 	u16 smid;
618 	ktime_t current_time;
619 	u64 TimeStamp = 0;
620 	u8 issue_reset = 0;
621 
622 	mutex_lock(&ioc->scsih_cmds.mutex);
623 	if (ioc->scsih_cmds.status != MPT3_CMD_NOT_USED) {
624 		ioc_err(ioc, "scsih_cmd in use %s\n", __func__);
625 		goto out;
626 	}
627 	ioc->scsih_cmds.status = MPT3_CMD_PENDING;
628 	smid = mpt3sas_base_get_smid(ioc, ioc->scsih_cb_idx);
629 	if (!smid) {
630 		ioc_err(ioc, "Failed obtaining a smid %s\n", __func__);
631 		ioc->scsih_cmds.status = MPT3_CMD_NOT_USED;
632 		goto out;
633 	}
634 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
635 	ioc->scsih_cmds.smid = smid;
636 	memset(mpi_request, 0, sizeof(Mpi26IoUnitControlRequest_t));
637 	mpi_request->Function = MPI2_FUNCTION_IO_UNIT_CONTROL;
638 	mpi_request->Operation = MPI26_CTRL_OP_SET_IOC_PARAMETER;
639 	mpi_request->IOCParameter = MPI26_SET_IOC_PARAMETER_SYNC_TIMESTAMP;
640 	current_time = ktime_get_real();
641 	TimeStamp = ktime_to_ms(current_time);
642 	mpi_request->Reserved7 = cpu_to_le32(TimeStamp >> 32);
643 	mpi_request->IOCParameterValue = cpu_to_le32(TimeStamp & 0xFFFFFFFF);
644 	init_completion(&ioc->scsih_cmds.done);
645 	ioc->put_smid_default(ioc, smid);
646 	dinitprintk(ioc, ioc_info(ioc,
647 	    "Io Unit Control Sync TimeStamp (sending), @time %lld ms\n",
648 	    TimeStamp));
649 	wait_for_completion_timeout(&ioc->scsih_cmds.done,
650 		MPT3SAS_TIMESYNC_TIMEOUT_SECONDS*HZ);
651 	if (!(ioc->scsih_cmds.status & MPT3_CMD_COMPLETE)) {
652 		mpt3sas_check_cmd_timeout(ioc,
653 		    ioc->scsih_cmds.status, mpi_request,
654 		    sizeof(Mpi2SasIoUnitControlRequest_t)/4, issue_reset);
655 		goto issue_host_reset;
656 	}
657 	if (ioc->scsih_cmds.status & MPT3_CMD_REPLY_VALID) {
658 		mpi_reply = ioc->scsih_cmds.reply;
659 		dinitprintk(ioc, ioc_info(ioc,
660 		    "Io Unit Control sync timestamp (complete): ioc_status(0x%04x), loginfo(0x%08x)\n",
661 		    le16_to_cpu(mpi_reply->IOCStatus),
662 		    le32_to_cpu(mpi_reply->IOCLogInfo)));
663 	}
664 issue_host_reset:
665 	if (issue_reset)
666 		mpt3sas_base_hard_reset_handler(ioc, FORCE_BIG_HAMMER);
667 	ioc->scsih_cmds.status = MPT3_CMD_NOT_USED;
668 out:
669 	mutex_unlock(&ioc->scsih_cmds.mutex);
670 }
671 
672 /**
673  * _base_fault_reset_work - workq handling ioc fault conditions
674  * @work: input argument, used to derive ioc
675  *
676  * Context: sleep.
677  */
678 static void
679 _base_fault_reset_work(struct work_struct *work)
680 {
681 	struct MPT3SAS_ADAPTER *ioc =
682 	    container_of(work, struct MPT3SAS_ADAPTER, fault_reset_work.work);
683 	unsigned long	 flags;
684 	u32 doorbell;
685 	int rc;
686 	struct task_struct *p;
687 
688 
689 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
690 	if ((ioc->shost_recovery && (ioc->ioc_coredump_loop == 0)) ||
691 			ioc->pci_error_recovery)
692 		goto rearm_timer;
693 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
694 
695 	doorbell = mpt3sas_base_get_iocstate(ioc, 0);
696 	if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_MASK) {
697 		ioc_err(ioc, "SAS host is non-operational !!!!\n");
698 
699 		/* It may be possible that EEH recovery can resolve some of
700 		 * pci bus failure issues rather removing the dead ioc function
701 		 * by considering controller is in a non-operational state. So
702 		 * here priority is given to the EEH recovery. If it doesn't
703 		 * not resolve this issue, mpt3sas driver will consider this
704 		 * controller to non-operational state and remove the dead ioc
705 		 * function.
706 		 */
707 		if (ioc->non_operational_loop++ < 5) {
708 			spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock,
709 							 flags);
710 			goto rearm_timer;
711 		}
712 
713 		/*
714 		 * Call _scsih_flush_pending_cmds callback so that we flush all
715 		 * pending commands back to OS. This call is required to avoid
716 		 * deadlock at block layer. Dead IOC will fail to do diag reset,
717 		 * and this call is safe since dead ioc will never return any
718 		 * command back from HW.
719 		 */
720 		mpt3sas_base_pause_mq_polling(ioc);
721 		ioc->schedule_dead_ioc_flush_running_cmds(ioc);
722 		/*
723 		 * Set remove_host flag early since kernel thread will
724 		 * take some time to execute.
725 		 */
726 		ioc->remove_host = 1;
727 		/*Remove the Dead Host */
728 		p = kthread_run(mpt3sas_remove_dead_ioc_func, ioc,
729 		    "%s_dead_ioc_%d", ioc->driver_name, ioc->id);
730 		if (IS_ERR(p))
731 			ioc_err(ioc, "%s: Running mpt3sas_dead_ioc thread failed !!!!\n",
732 				__func__);
733 		else
734 			ioc_err(ioc, "%s: Running mpt3sas_dead_ioc thread success !!!!\n",
735 				__func__);
736 		return; /* don't rearm timer */
737 	}
738 
739 	if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_COREDUMP) {
740 		u8 timeout = (ioc->manu_pg11.CoreDumpTOSec) ?
741 		    ioc->manu_pg11.CoreDumpTOSec :
742 		    MPT3SAS_DEFAULT_COREDUMP_TIMEOUT_SECONDS;
743 
744 		timeout /= (FAULT_POLLING_INTERVAL/1000);
745 
746 		if (ioc->ioc_coredump_loop == 0) {
747 			mpt3sas_print_coredump_info(ioc,
748 			    doorbell & MPI2_DOORBELL_DATA_MASK);
749 			/* do not accept any IOs and disable the interrupts */
750 			spin_lock_irqsave(
751 			    &ioc->ioc_reset_in_progress_lock, flags);
752 			ioc->shost_recovery = 1;
753 			spin_unlock_irqrestore(
754 			    &ioc->ioc_reset_in_progress_lock, flags);
755 			mpt3sas_base_mask_interrupts(ioc);
756 			mpt3sas_base_pause_mq_polling(ioc);
757 			_base_clear_outstanding_commands(ioc);
758 		}
759 
760 		ioc_info(ioc, "%s: CoreDump loop %d.",
761 		    __func__, ioc->ioc_coredump_loop);
762 
763 		/* Wait until CoreDump completes or times out */
764 		if (ioc->ioc_coredump_loop++ < timeout) {
765 			spin_lock_irqsave(
766 			    &ioc->ioc_reset_in_progress_lock, flags);
767 			goto rearm_timer;
768 		}
769 	}
770 
771 	if (ioc->ioc_coredump_loop) {
772 		if ((doorbell & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_COREDUMP)
773 			ioc_err(ioc, "%s: CoreDump completed. LoopCount: %d",
774 			    __func__, ioc->ioc_coredump_loop);
775 		else
776 			ioc_err(ioc, "%s: CoreDump Timed out. LoopCount: %d",
777 			    __func__, ioc->ioc_coredump_loop);
778 		ioc->ioc_coredump_loop = MPT3SAS_COREDUMP_LOOP_DONE;
779 	}
780 	ioc->non_operational_loop = 0;
781 	if ((doorbell & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_OPERATIONAL) {
782 		rc = mpt3sas_base_hard_reset_handler(ioc, FORCE_BIG_HAMMER);
783 		ioc_warn(ioc, "%s: hard reset: %s\n",
784 			 __func__, rc == 0 ? "success" : "failed");
785 		doorbell = mpt3sas_base_get_iocstate(ioc, 0);
786 		if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
787 			mpt3sas_print_fault_code(ioc, doorbell &
788 			    MPI2_DOORBELL_DATA_MASK);
789 		} else if ((doorbell & MPI2_IOC_STATE_MASK) ==
790 		    MPI2_IOC_STATE_COREDUMP)
791 			mpt3sas_print_coredump_info(ioc, doorbell &
792 			    MPI2_DOORBELL_DATA_MASK);
793 		if (rc && (doorbell & MPI2_IOC_STATE_MASK) !=
794 		    MPI2_IOC_STATE_OPERATIONAL)
795 			return; /* don't rearm timer */
796 	}
797 	ioc->ioc_coredump_loop = 0;
798 	if (ioc->time_sync_interval &&
799 	    ++ioc->timestamp_update_count >= ioc->time_sync_interval) {
800 		ioc->timestamp_update_count = 0;
801 		_base_sync_drv_fw_timestamp(ioc);
802 	}
803 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
804  rearm_timer:
805 	if (ioc->fault_reset_work_q)
806 		queue_delayed_work(ioc->fault_reset_work_q,
807 		    &ioc->fault_reset_work,
808 		    msecs_to_jiffies(FAULT_POLLING_INTERVAL));
809 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
810 }
811 
812 /**
813  * mpt3sas_base_start_watchdog - start the fault_reset_work_q
814  * @ioc: per adapter object
815  *
816  * Context: sleep.
817  */
818 void
819 mpt3sas_base_start_watchdog(struct MPT3SAS_ADAPTER *ioc)
820 {
821 	unsigned long	 flags;
822 
823 	if (ioc->fault_reset_work_q)
824 		return;
825 
826 	ioc->timestamp_update_count = 0;
827 	/* initialize fault polling */
828 
829 	INIT_DELAYED_WORK(&ioc->fault_reset_work, _base_fault_reset_work);
830 	snprintf(ioc->fault_reset_work_q_name,
831 	    sizeof(ioc->fault_reset_work_q_name), "poll_%s%d_status",
832 	    ioc->driver_name, ioc->id);
833 	ioc->fault_reset_work_q =
834 		create_singlethread_workqueue(ioc->fault_reset_work_q_name);
835 	if (!ioc->fault_reset_work_q) {
836 		ioc_err(ioc, "%s: failed (line=%d)\n", __func__, __LINE__);
837 		return;
838 	}
839 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
840 	if (ioc->fault_reset_work_q)
841 		queue_delayed_work(ioc->fault_reset_work_q,
842 		    &ioc->fault_reset_work,
843 		    msecs_to_jiffies(FAULT_POLLING_INTERVAL));
844 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
845 }
846 
847 /**
848  * mpt3sas_base_stop_watchdog - stop the fault_reset_work_q
849  * @ioc: per adapter object
850  *
851  * Context: sleep.
852  */
853 void
854 mpt3sas_base_stop_watchdog(struct MPT3SAS_ADAPTER *ioc)
855 {
856 	unsigned long flags;
857 	struct workqueue_struct *wq;
858 
859 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
860 	wq = ioc->fault_reset_work_q;
861 	ioc->fault_reset_work_q = NULL;
862 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
863 	if (wq) {
864 		if (!cancel_delayed_work_sync(&ioc->fault_reset_work))
865 			flush_workqueue(wq);
866 		destroy_workqueue(wq);
867 	}
868 }
869 
870 /**
871  * mpt3sas_base_fault_info - verbose translation of firmware FAULT code
872  * @ioc: per adapter object
873  * @fault_code: fault code
874  */
875 void
876 mpt3sas_base_fault_info(struct MPT3SAS_ADAPTER *ioc, u16 fault_code)
877 {
878 	ioc_err(ioc, "fault_state(0x%04x)!\n", fault_code);
879 }
880 
881 /**
882  * mpt3sas_base_coredump_info - verbose translation of firmware CoreDump state
883  * @ioc: per adapter object
884  * @fault_code: fault code
885  *
886  * Return: nothing.
887  */
888 void
889 mpt3sas_base_coredump_info(struct MPT3SAS_ADAPTER *ioc, u16 fault_code)
890 {
891 	ioc_err(ioc, "coredump_state(0x%04x)!\n", fault_code);
892 }
893 
894 /**
895  * mpt3sas_base_wait_for_coredump_completion - Wait until coredump
896  * completes or times out
897  * @ioc: per adapter object
898  * @caller: caller function name
899  *
900  * Return: 0 for success, non-zero for failure.
901  */
902 int
903 mpt3sas_base_wait_for_coredump_completion(struct MPT3SAS_ADAPTER *ioc,
904 		const char *caller)
905 {
906 	u8 timeout = (ioc->manu_pg11.CoreDumpTOSec) ?
907 			ioc->manu_pg11.CoreDumpTOSec :
908 			MPT3SAS_DEFAULT_COREDUMP_TIMEOUT_SECONDS;
909 
910 	int ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_FAULT,
911 					timeout);
912 
913 	if (ioc_state)
914 		ioc_err(ioc,
915 		    "%s: CoreDump timed out. (ioc_state=0x%x)\n",
916 		    caller, ioc_state);
917 	else
918 		ioc_info(ioc,
919 		    "%s: CoreDump completed. (ioc_state=0x%x)\n",
920 		    caller, ioc_state);
921 
922 	return ioc_state;
923 }
924 
925 /**
926  * mpt3sas_halt_firmware - halt's mpt controller firmware
927  * @ioc: per adapter object
928  *
929  * For debugging timeout related issues.  Writing 0xCOFFEE00
930  * to the doorbell register will halt controller firmware. With
931  * the purpose to stop both driver and firmware, the enduser can
932  * obtain a ring buffer from controller UART.
933  */
934 void
935 mpt3sas_halt_firmware(struct MPT3SAS_ADAPTER *ioc)
936 {
937 	u32 doorbell;
938 
939 	if (!ioc->fwfault_debug)
940 		return;
941 
942 	dump_stack();
943 
944 	doorbell = ioc->base_readl(&ioc->chip->Doorbell);
945 	if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
946 		mpt3sas_print_fault_code(ioc, doorbell &
947 		    MPI2_DOORBELL_DATA_MASK);
948 	} else if ((doorbell & MPI2_IOC_STATE_MASK) ==
949 	    MPI2_IOC_STATE_COREDUMP) {
950 		mpt3sas_print_coredump_info(ioc, doorbell &
951 		    MPI2_DOORBELL_DATA_MASK);
952 	} else {
953 		writel(0xC0FFEE00, &ioc->chip->Doorbell);
954 		ioc_err(ioc, "Firmware is halted due to command timeout\n");
955 	}
956 
957 	if (ioc->fwfault_debug == 2)
958 		for (;;)
959 			;
960 	else
961 		panic("panic in %s\n", __func__);
962 }
963 
964 /**
965  * _base_sas_ioc_info - verbose translation of the ioc status
966  * @ioc: per adapter object
967  * @mpi_reply: reply mf payload returned from firmware
968  * @request_hdr: request mf
969  */
970 static void
971 _base_sas_ioc_info(struct MPT3SAS_ADAPTER *ioc, MPI2DefaultReply_t *mpi_reply,
972 	MPI2RequestHeader_t *request_hdr)
973 {
974 	u16 ioc_status = le16_to_cpu(mpi_reply->IOCStatus) &
975 	    MPI2_IOCSTATUS_MASK;
976 	char *desc = NULL;
977 	u16 frame_sz;
978 	char *func_str = NULL;
979 
980 	/* SCSI_IO, RAID_PASS are handled from _scsih_scsi_ioc_info */
981 	if (request_hdr->Function == MPI2_FUNCTION_SCSI_IO_REQUEST ||
982 	    request_hdr->Function == MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH ||
983 	    request_hdr->Function == MPI2_FUNCTION_EVENT_NOTIFICATION)
984 		return;
985 
986 	if (ioc_status == MPI2_IOCSTATUS_CONFIG_INVALID_PAGE)
987 		return;
988 	/*
989 	 * Older Firmware version doesn't support driver trigger pages.
990 	 * So, skip displaying 'config invalid type' type
991 	 * of error message.
992 	 */
993 	if (request_hdr->Function == MPI2_FUNCTION_CONFIG) {
994 		Mpi2ConfigRequest_t *rqst = (Mpi2ConfigRequest_t *)request_hdr;
995 
996 		if ((rqst->ExtPageType ==
997 		    MPI2_CONFIG_EXTPAGETYPE_DRIVER_PERSISTENT_TRIGGER) &&
998 		    !(ioc->logging_level & MPT_DEBUG_CONFIG)) {
999 			return;
1000 		}
1001 	}
1002 
1003 	switch (ioc_status) {
1004 
1005 /****************************************************************************
1006 *  Common IOCStatus values for all replies
1007 ****************************************************************************/
1008 
1009 	case MPI2_IOCSTATUS_INVALID_FUNCTION:
1010 		desc = "invalid function";
1011 		break;
1012 	case MPI2_IOCSTATUS_BUSY:
1013 		desc = "busy";
1014 		break;
1015 	case MPI2_IOCSTATUS_INVALID_SGL:
1016 		desc = "invalid sgl";
1017 		break;
1018 	case MPI2_IOCSTATUS_INTERNAL_ERROR:
1019 		desc = "internal error";
1020 		break;
1021 	case MPI2_IOCSTATUS_INVALID_VPID:
1022 		desc = "invalid vpid";
1023 		break;
1024 	case MPI2_IOCSTATUS_INSUFFICIENT_RESOURCES:
1025 		desc = "insufficient resources";
1026 		break;
1027 	case MPI2_IOCSTATUS_INSUFFICIENT_POWER:
1028 		desc = "insufficient power";
1029 		break;
1030 	case MPI2_IOCSTATUS_INVALID_FIELD:
1031 		desc = "invalid field";
1032 		break;
1033 	case MPI2_IOCSTATUS_INVALID_STATE:
1034 		desc = "invalid state";
1035 		break;
1036 	case MPI2_IOCSTATUS_OP_STATE_NOT_SUPPORTED:
1037 		desc = "op state not supported";
1038 		break;
1039 
1040 /****************************************************************************
1041 *  Config IOCStatus values
1042 ****************************************************************************/
1043 
1044 	case MPI2_IOCSTATUS_CONFIG_INVALID_ACTION:
1045 		desc = "config invalid action";
1046 		break;
1047 	case MPI2_IOCSTATUS_CONFIG_INVALID_TYPE:
1048 		desc = "config invalid type";
1049 		break;
1050 	case MPI2_IOCSTATUS_CONFIG_INVALID_PAGE:
1051 		desc = "config invalid page";
1052 		break;
1053 	case MPI2_IOCSTATUS_CONFIG_INVALID_DATA:
1054 		desc = "config invalid data";
1055 		break;
1056 	case MPI2_IOCSTATUS_CONFIG_NO_DEFAULTS:
1057 		desc = "config no defaults";
1058 		break;
1059 	case MPI2_IOCSTATUS_CONFIG_CANT_COMMIT:
1060 		desc = "config can't commit";
1061 		break;
1062 
1063 /****************************************************************************
1064 *  SCSI IO Reply
1065 ****************************************************************************/
1066 
1067 	case MPI2_IOCSTATUS_SCSI_RECOVERED_ERROR:
1068 	case MPI2_IOCSTATUS_SCSI_INVALID_DEVHANDLE:
1069 	case MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
1070 	case MPI2_IOCSTATUS_SCSI_DATA_OVERRUN:
1071 	case MPI2_IOCSTATUS_SCSI_DATA_UNDERRUN:
1072 	case MPI2_IOCSTATUS_SCSI_IO_DATA_ERROR:
1073 	case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
1074 	case MPI2_IOCSTATUS_SCSI_TASK_TERMINATED:
1075 	case MPI2_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
1076 	case MPI2_IOCSTATUS_SCSI_TASK_MGMT_FAILED:
1077 	case MPI2_IOCSTATUS_SCSI_IOC_TERMINATED:
1078 	case MPI2_IOCSTATUS_SCSI_EXT_TERMINATED:
1079 		break;
1080 
1081 /****************************************************************************
1082 *  For use by SCSI Initiator and SCSI Target end-to-end data protection
1083 ****************************************************************************/
1084 
1085 	case MPI2_IOCSTATUS_EEDP_GUARD_ERROR:
1086 		desc = "eedp guard error";
1087 		break;
1088 	case MPI2_IOCSTATUS_EEDP_REF_TAG_ERROR:
1089 		desc = "eedp ref tag error";
1090 		break;
1091 	case MPI2_IOCSTATUS_EEDP_APP_TAG_ERROR:
1092 		desc = "eedp app tag error";
1093 		break;
1094 
1095 /****************************************************************************
1096 *  SCSI Target values
1097 ****************************************************************************/
1098 
1099 	case MPI2_IOCSTATUS_TARGET_INVALID_IO_INDEX:
1100 		desc = "target invalid io index";
1101 		break;
1102 	case MPI2_IOCSTATUS_TARGET_ABORTED:
1103 		desc = "target aborted";
1104 		break;
1105 	case MPI2_IOCSTATUS_TARGET_NO_CONN_RETRYABLE:
1106 		desc = "target no conn retryable";
1107 		break;
1108 	case MPI2_IOCSTATUS_TARGET_NO_CONNECTION:
1109 		desc = "target no connection";
1110 		break;
1111 	case MPI2_IOCSTATUS_TARGET_XFER_COUNT_MISMATCH:
1112 		desc = "target xfer count mismatch";
1113 		break;
1114 	case MPI2_IOCSTATUS_TARGET_DATA_OFFSET_ERROR:
1115 		desc = "target data offset error";
1116 		break;
1117 	case MPI2_IOCSTATUS_TARGET_TOO_MUCH_WRITE_DATA:
1118 		desc = "target too much write data";
1119 		break;
1120 	case MPI2_IOCSTATUS_TARGET_IU_TOO_SHORT:
1121 		desc = "target iu too short";
1122 		break;
1123 	case MPI2_IOCSTATUS_TARGET_ACK_NAK_TIMEOUT:
1124 		desc = "target ack nak timeout";
1125 		break;
1126 	case MPI2_IOCSTATUS_TARGET_NAK_RECEIVED:
1127 		desc = "target nak received";
1128 		break;
1129 
1130 /****************************************************************************
1131 *  Serial Attached SCSI values
1132 ****************************************************************************/
1133 
1134 	case MPI2_IOCSTATUS_SAS_SMP_REQUEST_FAILED:
1135 		desc = "smp request failed";
1136 		break;
1137 	case MPI2_IOCSTATUS_SAS_SMP_DATA_OVERRUN:
1138 		desc = "smp data overrun";
1139 		break;
1140 
1141 /****************************************************************************
1142 *  Diagnostic Buffer Post / Diagnostic Release values
1143 ****************************************************************************/
1144 
1145 	case MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED:
1146 		desc = "diagnostic released";
1147 		break;
1148 	default:
1149 		break;
1150 	}
1151 
1152 	if (!desc)
1153 		return;
1154 
1155 	switch (request_hdr->Function) {
1156 	case MPI2_FUNCTION_CONFIG:
1157 		frame_sz = sizeof(Mpi2ConfigRequest_t) + ioc->sge_size;
1158 		func_str = "config_page";
1159 		break;
1160 	case MPI2_FUNCTION_SCSI_TASK_MGMT:
1161 		frame_sz = sizeof(Mpi2SCSITaskManagementRequest_t);
1162 		func_str = "task_mgmt";
1163 		break;
1164 	case MPI2_FUNCTION_SAS_IO_UNIT_CONTROL:
1165 		frame_sz = sizeof(Mpi2SasIoUnitControlRequest_t);
1166 		func_str = "sas_iounit_ctl";
1167 		break;
1168 	case MPI2_FUNCTION_SCSI_ENCLOSURE_PROCESSOR:
1169 		frame_sz = sizeof(Mpi2SepRequest_t);
1170 		func_str = "enclosure";
1171 		break;
1172 	case MPI2_FUNCTION_IOC_INIT:
1173 		frame_sz = sizeof(Mpi2IOCInitRequest_t);
1174 		func_str = "ioc_init";
1175 		break;
1176 	case MPI2_FUNCTION_PORT_ENABLE:
1177 		frame_sz = sizeof(Mpi2PortEnableRequest_t);
1178 		func_str = "port_enable";
1179 		break;
1180 	case MPI2_FUNCTION_SMP_PASSTHROUGH:
1181 		frame_sz = sizeof(Mpi2SmpPassthroughRequest_t) + ioc->sge_size;
1182 		func_str = "smp_passthru";
1183 		break;
1184 	case MPI2_FUNCTION_NVME_ENCAPSULATED:
1185 		frame_sz = sizeof(Mpi26NVMeEncapsulatedRequest_t) +
1186 		    ioc->sge_size;
1187 		func_str = "nvme_encapsulated";
1188 		break;
1189 	default:
1190 		frame_sz = 32;
1191 		func_str = "unknown";
1192 		break;
1193 	}
1194 
1195 	ioc_warn(ioc, "ioc_status: %s(0x%04x), request(0x%p),(%s)\n",
1196 		 desc, ioc_status, request_hdr, func_str);
1197 
1198 	_debug_dump_mf(request_hdr, frame_sz/4);
1199 }
1200 
1201 /**
1202  * _base_display_event_data - verbose translation of firmware asyn events
1203  * @ioc: per adapter object
1204  * @mpi_reply: reply mf payload returned from firmware
1205  */
1206 static void
1207 _base_display_event_data(struct MPT3SAS_ADAPTER *ioc,
1208 	Mpi2EventNotificationReply_t *mpi_reply)
1209 {
1210 	char *desc = NULL;
1211 	u16 event;
1212 
1213 	if (!(ioc->logging_level & MPT_DEBUG_EVENTS))
1214 		return;
1215 
1216 	event = le16_to_cpu(mpi_reply->Event);
1217 
1218 	switch (event) {
1219 	case MPI2_EVENT_LOG_DATA:
1220 		desc = "Log Data";
1221 		break;
1222 	case MPI2_EVENT_STATE_CHANGE:
1223 		desc = "Status Change";
1224 		break;
1225 	case MPI2_EVENT_HARD_RESET_RECEIVED:
1226 		desc = "Hard Reset Received";
1227 		break;
1228 	case MPI2_EVENT_EVENT_CHANGE:
1229 		desc = "Event Change";
1230 		break;
1231 	case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
1232 		desc = "Device Status Change";
1233 		break;
1234 	case MPI2_EVENT_IR_OPERATION_STATUS:
1235 		if (!ioc->hide_ir_msg)
1236 			desc = "IR Operation Status";
1237 		break;
1238 	case MPI2_EVENT_SAS_DISCOVERY:
1239 	{
1240 		Mpi2EventDataSasDiscovery_t *event_data =
1241 		    (Mpi2EventDataSasDiscovery_t *)mpi_reply->EventData;
1242 		ioc_info(ioc, "Discovery: (%s)",
1243 			 event_data->ReasonCode == MPI2_EVENT_SAS_DISC_RC_STARTED ?
1244 			 "start" : "stop");
1245 		if (event_data->DiscoveryStatus)
1246 			pr_cont(" discovery_status(0x%08x)",
1247 			    le32_to_cpu(event_data->DiscoveryStatus));
1248 		pr_cont("\n");
1249 		return;
1250 	}
1251 	case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
1252 		desc = "SAS Broadcast Primitive";
1253 		break;
1254 	case MPI2_EVENT_SAS_INIT_DEVICE_STATUS_CHANGE:
1255 		desc = "SAS Init Device Status Change";
1256 		break;
1257 	case MPI2_EVENT_SAS_INIT_TABLE_OVERFLOW:
1258 		desc = "SAS Init Table Overflow";
1259 		break;
1260 	case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
1261 		desc = "SAS Topology Change List";
1262 		break;
1263 	case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
1264 		desc = "SAS Enclosure Device Status Change";
1265 		break;
1266 	case MPI2_EVENT_IR_VOLUME:
1267 		if (!ioc->hide_ir_msg)
1268 			desc = "IR Volume";
1269 		break;
1270 	case MPI2_EVENT_IR_PHYSICAL_DISK:
1271 		if (!ioc->hide_ir_msg)
1272 			desc = "IR Physical Disk";
1273 		break;
1274 	case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
1275 		if (!ioc->hide_ir_msg)
1276 			desc = "IR Configuration Change List";
1277 		break;
1278 	case MPI2_EVENT_LOG_ENTRY_ADDED:
1279 		if (!ioc->hide_ir_msg)
1280 			desc = "Log Entry Added";
1281 		break;
1282 	case MPI2_EVENT_TEMP_THRESHOLD:
1283 		desc = "Temperature Threshold";
1284 		break;
1285 	case MPI2_EVENT_ACTIVE_CABLE_EXCEPTION:
1286 		desc = "Cable Event";
1287 		break;
1288 	case MPI2_EVENT_SAS_DEVICE_DISCOVERY_ERROR:
1289 		desc = "SAS Device Discovery Error";
1290 		break;
1291 	case MPI2_EVENT_PCIE_DEVICE_STATUS_CHANGE:
1292 		desc = "PCIE Device Status Change";
1293 		break;
1294 	case MPI2_EVENT_PCIE_ENUMERATION:
1295 	{
1296 		Mpi26EventDataPCIeEnumeration_t *event_data =
1297 			(Mpi26EventDataPCIeEnumeration_t *)mpi_reply->EventData;
1298 		ioc_info(ioc, "PCIE Enumeration: (%s)",
1299 			 event_data->ReasonCode == MPI26_EVENT_PCIE_ENUM_RC_STARTED ?
1300 			 "start" : "stop");
1301 		if (event_data->EnumerationStatus)
1302 			pr_cont("enumeration_status(0x%08x)",
1303 				le32_to_cpu(event_data->EnumerationStatus));
1304 		pr_cont("\n");
1305 		return;
1306 	}
1307 	case MPI2_EVENT_PCIE_TOPOLOGY_CHANGE_LIST:
1308 		desc = "PCIE Topology Change List";
1309 		break;
1310 	}
1311 
1312 	if (!desc)
1313 		return;
1314 
1315 	ioc_info(ioc, "%s\n", desc);
1316 }
1317 
1318 /**
1319  * _base_sas_log_info - verbose translation of firmware log info
1320  * @ioc: per adapter object
1321  * @log_info: log info
1322  */
1323 static void
1324 _base_sas_log_info(struct MPT3SAS_ADAPTER *ioc, u32 log_info)
1325 {
1326 	union loginfo_type {
1327 		u32	loginfo;
1328 		struct {
1329 			u32	subcode:16;
1330 			u32	code:8;
1331 			u32	originator:4;
1332 			u32	bus_type:4;
1333 		} dw;
1334 	};
1335 	union loginfo_type sas_loginfo;
1336 	char *originator_str = NULL;
1337 
1338 	sas_loginfo.loginfo = log_info;
1339 	if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
1340 		return;
1341 
1342 	/* each nexus loss loginfo */
1343 	if (log_info == 0x31170000)
1344 		return;
1345 
1346 	/* eat the loginfos associated with task aborts */
1347 	if (ioc->ignore_loginfos && (log_info == 0x30050000 || log_info ==
1348 	    0x31140000 || log_info == 0x31130000))
1349 		return;
1350 
1351 	switch (sas_loginfo.dw.originator) {
1352 	case 0:
1353 		originator_str = "IOP";
1354 		break;
1355 	case 1:
1356 		originator_str = "PL";
1357 		break;
1358 	case 2:
1359 		if (!ioc->hide_ir_msg)
1360 			originator_str = "IR";
1361 		else
1362 			originator_str = "WarpDrive";
1363 		break;
1364 	}
1365 
1366 	ioc_warn(ioc, "log_info(0x%08x): originator(%s), code(0x%02x), sub_code(0x%04x)\n",
1367 		 log_info,
1368 		 originator_str, sas_loginfo.dw.code, sas_loginfo.dw.subcode);
1369 }
1370 
1371 /**
1372  * _base_display_reply_info - handle reply descriptors depending on IOC Status
1373  * @ioc: per adapter object
1374  * @smid: system request message index
1375  * @msix_index: MSIX table index supplied by the OS
1376  * @reply: reply message frame (lower 32bit addr)
1377  */
1378 static void
1379 _base_display_reply_info(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
1380 	u32 reply)
1381 {
1382 	MPI2DefaultReply_t *mpi_reply;
1383 	u16 ioc_status;
1384 	u32 loginfo = 0;
1385 
1386 	mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
1387 	if (unlikely(!mpi_reply)) {
1388 		ioc_err(ioc, "mpi_reply not valid at %s:%d/%s()!\n",
1389 			__FILE__, __LINE__, __func__);
1390 		return;
1391 	}
1392 	ioc_status = le16_to_cpu(mpi_reply->IOCStatus);
1393 
1394 	if ((ioc_status & MPI2_IOCSTATUS_MASK) &&
1395 	    (ioc->logging_level & MPT_DEBUG_REPLY)) {
1396 		_base_sas_ioc_info(ioc, mpi_reply,
1397 		   mpt3sas_base_get_msg_frame(ioc, smid));
1398 	}
1399 
1400 	if (ioc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE) {
1401 		loginfo = le32_to_cpu(mpi_reply->IOCLogInfo);
1402 		_base_sas_log_info(ioc, loginfo);
1403 	}
1404 
1405 	if (ioc_status || loginfo) {
1406 		ioc_status &= MPI2_IOCSTATUS_MASK;
1407 		mpt3sas_trigger_mpi(ioc, ioc_status, loginfo);
1408 	}
1409 }
1410 
1411 /**
1412  * mpt3sas_base_done - base internal command completion routine
1413  * @ioc: per adapter object
1414  * @smid: system request message index
1415  * @msix_index: MSIX table index supplied by the OS
1416  * @reply: reply message frame(lower 32bit addr)
1417  *
1418  * Return:
1419  * 1 meaning mf should be freed from _base_interrupt
1420  * 0 means the mf is freed from this function.
1421  */
1422 u8
1423 mpt3sas_base_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
1424 	u32 reply)
1425 {
1426 	MPI2DefaultReply_t *mpi_reply;
1427 
1428 	mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
1429 	if (mpi_reply && mpi_reply->Function == MPI2_FUNCTION_EVENT_ACK)
1430 		return mpt3sas_check_for_pending_internal_cmds(ioc, smid);
1431 
1432 	if (ioc->base_cmds.status == MPT3_CMD_NOT_USED)
1433 		return 1;
1434 
1435 	ioc->base_cmds.status |= MPT3_CMD_COMPLETE;
1436 	if (mpi_reply) {
1437 		ioc->base_cmds.status |= MPT3_CMD_REPLY_VALID;
1438 		memcpy(ioc->base_cmds.reply, mpi_reply, mpi_reply->MsgLength*4);
1439 	}
1440 	ioc->base_cmds.status &= ~MPT3_CMD_PENDING;
1441 
1442 	complete(&ioc->base_cmds.done);
1443 	return 1;
1444 }
1445 
1446 /**
1447  * _base_async_event - main callback handler for firmware asyn events
1448  * @ioc: per adapter object
1449  * @msix_index: MSIX table index supplied by the OS
1450  * @reply: reply message frame(lower 32bit addr)
1451  *
1452  * Return:
1453  * 1 meaning mf should be freed from _base_interrupt
1454  * 0 means the mf is freed from this function.
1455  */
1456 static u8
1457 _base_async_event(struct MPT3SAS_ADAPTER *ioc, u8 msix_index, u32 reply)
1458 {
1459 	Mpi2EventNotificationReply_t *mpi_reply;
1460 	Mpi2EventAckRequest_t *ack_request;
1461 	u16 smid;
1462 	struct _event_ack_list *delayed_event_ack;
1463 
1464 	mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
1465 	if (!mpi_reply)
1466 		return 1;
1467 	if (mpi_reply->Function != MPI2_FUNCTION_EVENT_NOTIFICATION)
1468 		return 1;
1469 
1470 	_base_display_event_data(ioc, mpi_reply);
1471 
1472 	if (!(mpi_reply->AckRequired & MPI2_EVENT_NOTIFICATION_ACK_REQUIRED))
1473 		goto out;
1474 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
1475 	if (!smid) {
1476 		delayed_event_ack = kzalloc(sizeof(*delayed_event_ack),
1477 					GFP_ATOMIC);
1478 		if (!delayed_event_ack)
1479 			goto out;
1480 		INIT_LIST_HEAD(&delayed_event_ack->list);
1481 		delayed_event_ack->Event = mpi_reply->Event;
1482 		delayed_event_ack->EventContext = mpi_reply->EventContext;
1483 		list_add_tail(&delayed_event_ack->list,
1484 				&ioc->delayed_event_ack_list);
1485 		dewtprintk(ioc,
1486 			   ioc_info(ioc, "DELAYED: EVENT ACK: event (0x%04x)\n",
1487 				    le16_to_cpu(mpi_reply->Event)));
1488 		goto out;
1489 	}
1490 
1491 	ack_request = mpt3sas_base_get_msg_frame(ioc, smid);
1492 	memset(ack_request, 0, sizeof(Mpi2EventAckRequest_t));
1493 	ack_request->Function = MPI2_FUNCTION_EVENT_ACK;
1494 	ack_request->Event = mpi_reply->Event;
1495 	ack_request->EventContext = mpi_reply->EventContext;
1496 	ack_request->VF_ID = 0;  /* TODO */
1497 	ack_request->VP_ID = 0;
1498 	ioc->put_smid_default(ioc, smid);
1499 
1500  out:
1501 
1502 	/* scsih callback handler */
1503 	mpt3sas_scsih_event_callback(ioc, msix_index, reply);
1504 
1505 	/* ctl callback handler */
1506 	mpt3sas_ctl_event_callback(ioc, msix_index, reply);
1507 
1508 	return 1;
1509 }
1510 
1511 static struct scsiio_tracker *
1512 _get_st_from_smid(struct MPT3SAS_ADAPTER *ioc, u16 smid)
1513 {
1514 	struct scsi_cmnd *cmd;
1515 
1516 	if (WARN_ON(!smid) ||
1517 	    WARN_ON(smid >= ioc->hi_priority_smid))
1518 		return NULL;
1519 
1520 	cmd = mpt3sas_scsih_scsi_lookup_get(ioc, smid);
1521 	if (cmd)
1522 		return scsi_cmd_priv(cmd);
1523 
1524 	return NULL;
1525 }
1526 
1527 /**
1528  * _base_get_cb_idx - obtain the callback index
1529  * @ioc: per adapter object
1530  * @smid: system request message index
1531  *
1532  * Return: callback index.
1533  */
1534 static u8
1535 _base_get_cb_idx(struct MPT3SAS_ADAPTER *ioc, u16 smid)
1536 {
1537 	int i;
1538 	u16 ctl_smid = ioc->scsiio_depth - INTERNAL_SCSIIO_CMDS_COUNT + 1;
1539 	u8 cb_idx = 0xFF;
1540 
1541 	if (smid < ioc->hi_priority_smid) {
1542 		struct scsiio_tracker *st;
1543 
1544 		if (smid < ctl_smid) {
1545 			st = _get_st_from_smid(ioc, smid);
1546 			if (st)
1547 				cb_idx = st->cb_idx;
1548 		} else if (smid == ctl_smid)
1549 			cb_idx = ioc->ctl_cb_idx;
1550 	} else if (smid < ioc->internal_smid) {
1551 		i = smid - ioc->hi_priority_smid;
1552 		cb_idx = ioc->hpr_lookup[i].cb_idx;
1553 	} else if (smid <= ioc->hba_queue_depth) {
1554 		i = smid - ioc->internal_smid;
1555 		cb_idx = ioc->internal_lookup[i].cb_idx;
1556 	}
1557 	return cb_idx;
1558 }
1559 
1560 /**
1561  * mpt3sas_base_pause_mq_polling - pause polling on the mq poll queues
1562  *				when driver is flushing out the IOs.
1563  * @ioc: per adapter object
1564  *
1565  * Pause polling on the mq poll (io uring) queues when driver is flushing
1566  * out the IOs. Otherwise we may see the race condition of completing the same
1567  * IO from two paths.
1568  *
1569  * Returns nothing.
1570  */
1571 void
1572 mpt3sas_base_pause_mq_polling(struct MPT3SAS_ADAPTER *ioc)
1573 {
1574 	int iopoll_q_count =
1575 	    ioc->reply_queue_count - ioc->iopoll_q_start_index;
1576 	int qid;
1577 
1578 	for (qid = 0; qid < iopoll_q_count; qid++)
1579 		atomic_set(&ioc->io_uring_poll_queues[qid].pause, 1);
1580 
1581 	/*
1582 	 * wait for current poll to complete.
1583 	 */
1584 	for (qid = 0; qid < iopoll_q_count; qid++) {
1585 		while (atomic_read(&ioc->io_uring_poll_queues[qid].busy)) {
1586 			cpu_relax();
1587 			udelay(500);
1588 		}
1589 	}
1590 }
1591 
1592 /**
1593  * mpt3sas_base_resume_mq_polling - Resume polling on mq poll queues.
1594  * @ioc: per adapter object
1595  *
1596  * Returns nothing.
1597  */
1598 void
1599 mpt3sas_base_resume_mq_polling(struct MPT3SAS_ADAPTER *ioc)
1600 {
1601 	int iopoll_q_count =
1602 	    ioc->reply_queue_count - ioc->iopoll_q_start_index;
1603 	int qid;
1604 
1605 	for (qid = 0; qid < iopoll_q_count; qid++)
1606 		atomic_set(&ioc->io_uring_poll_queues[qid].pause, 0);
1607 }
1608 
1609 /**
1610  * mpt3sas_base_mask_interrupts - disable interrupts
1611  * @ioc: per adapter object
1612  *
1613  * Disabling ResetIRQ, Reply and Doorbell Interrupts
1614  */
1615 void
1616 mpt3sas_base_mask_interrupts(struct MPT3SAS_ADAPTER *ioc)
1617 {
1618 	u32 him_register;
1619 
1620 	ioc->mask_interrupts = 1;
1621 	him_register = ioc->base_readl(&ioc->chip->HostInterruptMask);
1622 	him_register |= MPI2_HIM_DIM + MPI2_HIM_RIM + MPI2_HIM_RESET_IRQ_MASK;
1623 	writel(him_register, &ioc->chip->HostInterruptMask);
1624 	ioc->base_readl(&ioc->chip->HostInterruptMask);
1625 }
1626 
1627 /**
1628  * mpt3sas_base_unmask_interrupts - enable interrupts
1629  * @ioc: per adapter object
1630  *
1631  * Enabling only Reply Interrupts
1632  */
1633 void
1634 mpt3sas_base_unmask_interrupts(struct MPT3SAS_ADAPTER *ioc)
1635 {
1636 	u32 him_register;
1637 
1638 	him_register = ioc->base_readl(&ioc->chip->HostInterruptMask);
1639 	him_register &= ~MPI2_HIM_RIM;
1640 	writel(him_register, &ioc->chip->HostInterruptMask);
1641 	ioc->mask_interrupts = 0;
1642 }
1643 
1644 union reply_descriptor {
1645 	u64 word;
1646 	struct {
1647 		u32 low;
1648 		u32 high;
1649 	} u;
1650 };
1651 
1652 static u32 base_mod64(u64 dividend, u32 divisor)
1653 {
1654 	u32 remainder;
1655 
1656 	if (!divisor)
1657 		pr_err("mpt3sas: DIVISOR is zero, in div fn\n");
1658 	remainder = do_div(dividend, divisor);
1659 	return remainder;
1660 }
1661 
1662 /**
1663  * _base_process_reply_queue - Process reply descriptors from reply
1664  *		descriptor post queue.
1665  * @reply_q: per IRQ's reply queue object.
1666  *
1667  * Return: number of reply descriptors processed from reply
1668  *		descriptor queue.
1669  */
1670 static int
1671 _base_process_reply_queue(struct adapter_reply_queue *reply_q)
1672 {
1673 	union reply_descriptor rd;
1674 	u64 completed_cmds;
1675 	u8 request_descript_type;
1676 	u16 smid;
1677 	u8 cb_idx;
1678 	u32 reply;
1679 	u8 msix_index = reply_q->msix_index;
1680 	struct MPT3SAS_ADAPTER *ioc = reply_q->ioc;
1681 	Mpi2ReplyDescriptorsUnion_t *rpf;
1682 	u8 rc;
1683 
1684 	completed_cmds = 0;
1685 	if (!atomic_add_unless(&reply_q->busy, 1, 1))
1686 		return completed_cmds;
1687 
1688 	rpf = &reply_q->reply_post_free[reply_q->reply_post_host_index];
1689 	request_descript_type = rpf->Default.ReplyFlags
1690 	     & MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
1691 	if (request_descript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED) {
1692 		atomic_dec(&reply_q->busy);
1693 		return completed_cmds;
1694 	}
1695 
1696 	cb_idx = 0xFF;
1697 	do {
1698 		rd.word = le64_to_cpu(rpf->Words);
1699 		if (rd.u.low == UINT_MAX || rd.u.high == UINT_MAX)
1700 			goto out;
1701 		reply = 0;
1702 		smid = le16_to_cpu(rpf->Default.DescriptorTypeDependent1);
1703 		if (request_descript_type ==
1704 		    MPI25_RPY_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO_SUCCESS ||
1705 		    request_descript_type ==
1706 		    MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS ||
1707 		    request_descript_type ==
1708 		    MPI26_RPY_DESCRIPT_FLAGS_PCIE_ENCAPSULATED_SUCCESS) {
1709 			cb_idx = _base_get_cb_idx(ioc, smid);
1710 			if ((likely(cb_idx < MPT_MAX_CALLBACKS)) &&
1711 			    (likely(mpt_callbacks[cb_idx] != NULL))) {
1712 				rc = mpt_callbacks[cb_idx](ioc, smid,
1713 				    msix_index, 0);
1714 				if (rc)
1715 					mpt3sas_base_free_smid(ioc, smid);
1716 			}
1717 		} else if (request_descript_type ==
1718 		    MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY) {
1719 			reply = le32_to_cpu(
1720 			    rpf->AddressReply.ReplyFrameAddress);
1721 			if (reply > ioc->reply_dma_max_address ||
1722 			    reply < ioc->reply_dma_min_address)
1723 				reply = 0;
1724 			if (smid) {
1725 				cb_idx = _base_get_cb_idx(ioc, smid);
1726 				if ((likely(cb_idx < MPT_MAX_CALLBACKS)) &&
1727 				    (likely(mpt_callbacks[cb_idx] != NULL))) {
1728 					rc = mpt_callbacks[cb_idx](ioc, smid,
1729 					    msix_index, reply);
1730 					if (reply)
1731 						_base_display_reply_info(ioc,
1732 						    smid, msix_index, reply);
1733 					if (rc)
1734 						mpt3sas_base_free_smid(ioc,
1735 						    smid);
1736 				}
1737 			} else {
1738 				_base_async_event(ioc, msix_index, reply);
1739 			}
1740 
1741 			/* reply free queue handling */
1742 			if (reply) {
1743 				ioc->reply_free_host_index =
1744 				    (ioc->reply_free_host_index ==
1745 				    (ioc->reply_free_queue_depth - 1)) ?
1746 				    0 : ioc->reply_free_host_index + 1;
1747 				ioc->reply_free[ioc->reply_free_host_index] =
1748 				    cpu_to_le32(reply);
1749 				if (ioc->is_mcpu_endpoint)
1750 					_base_clone_reply_to_sys_mem(ioc,
1751 						reply,
1752 						ioc->reply_free_host_index);
1753 				writel(ioc->reply_free_host_index,
1754 				    &ioc->chip->ReplyFreeHostIndex);
1755 			}
1756 		}
1757 
1758 		rpf->Words = cpu_to_le64(ULLONG_MAX);
1759 		reply_q->reply_post_host_index =
1760 		    (reply_q->reply_post_host_index ==
1761 		    (ioc->reply_post_queue_depth - 1)) ? 0 :
1762 		    reply_q->reply_post_host_index + 1;
1763 		request_descript_type =
1764 		    reply_q->reply_post_free[reply_q->reply_post_host_index].
1765 		    Default.ReplyFlags & MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
1766 		completed_cmds++;
1767 		/* Update the reply post host index after continuously
1768 		 * processing the threshold number of Reply Descriptors.
1769 		 * So that FW can find enough entries to post the Reply
1770 		 * Descriptors in the reply descriptor post queue.
1771 		 */
1772 		if (completed_cmds >= ioc->thresh_hold) {
1773 			if (ioc->combined_reply_queue) {
1774 				writel(reply_q->reply_post_host_index |
1775 						((msix_index  & 7) <<
1776 						 MPI2_RPHI_MSIX_INDEX_SHIFT),
1777 				    ioc->replyPostRegisterIndex[msix_index/8]);
1778 			} else {
1779 				writel(reply_q->reply_post_host_index |
1780 						(msix_index <<
1781 						 MPI2_RPHI_MSIX_INDEX_SHIFT),
1782 						&ioc->chip->ReplyPostHostIndex);
1783 			}
1784 			if (!reply_q->is_iouring_poll_q &&
1785 			    !reply_q->irq_poll_scheduled) {
1786 				reply_q->irq_poll_scheduled = true;
1787 				irq_poll_sched(&reply_q->irqpoll);
1788 			}
1789 			atomic_dec(&reply_q->busy);
1790 			return completed_cmds;
1791 		}
1792 		if (request_descript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
1793 			goto out;
1794 		if (!reply_q->reply_post_host_index)
1795 			rpf = reply_q->reply_post_free;
1796 		else
1797 			rpf++;
1798 	} while (1);
1799 
1800  out:
1801 
1802 	if (!completed_cmds) {
1803 		atomic_dec(&reply_q->busy);
1804 		return completed_cmds;
1805 	}
1806 
1807 	if (ioc->is_warpdrive) {
1808 		writel(reply_q->reply_post_host_index,
1809 		ioc->reply_post_host_index[msix_index]);
1810 		atomic_dec(&reply_q->busy);
1811 		return completed_cmds;
1812 	}
1813 
1814 	/* Update Reply Post Host Index.
1815 	 * For those HBA's which support combined reply queue feature
1816 	 * 1. Get the correct Supplemental Reply Post Host Index Register.
1817 	 *    i.e. (msix_index / 8)th entry from Supplemental Reply Post Host
1818 	 *    Index Register address bank i.e replyPostRegisterIndex[],
1819 	 * 2. Then update this register with new reply host index value
1820 	 *    in ReplyPostIndex field and the MSIxIndex field with
1821 	 *    msix_index value reduced to a value between 0 and 7,
1822 	 *    using a modulo 8 operation. Since each Supplemental Reply Post
1823 	 *    Host Index Register supports 8 MSI-X vectors.
1824 	 *
1825 	 * For other HBA's just update the Reply Post Host Index register with
1826 	 * new reply host index value in ReplyPostIndex Field and msix_index
1827 	 * value in MSIxIndex field.
1828 	 */
1829 	if (ioc->combined_reply_queue)
1830 		writel(reply_q->reply_post_host_index | ((msix_index  & 7) <<
1831 			MPI2_RPHI_MSIX_INDEX_SHIFT),
1832 			ioc->replyPostRegisterIndex[msix_index/8]);
1833 	else
1834 		writel(reply_q->reply_post_host_index | (msix_index <<
1835 			MPI2_RPHI_MSIX_INDEX_SHIFT),
1836 			&ioc->chip->ReplyPostHostIndex);
1837 	atomic_dec(&reply_q->busy);
1838 	return completed_cmds;
1839 }
1840 
1841 /**
1842  * mpt3sas_blk_mq_poll - poll the blk mq poll queue
1843  * @shost: Scsi_Host object
1844  * @queue_num: hw ctx queue number
1845  *
1846  * Return number of entries that has been processed from poll queue.
1847  */
1848 int mpt3sas_blk_mq_poll(struct Scsi_Host *shost, unsigned int queue_num)
1849 {
1850 	struct MPT3SAS_ADAPTER *ioc =
1851 	    (struct MPT3SAS_ADAPTER *)shost->hostdata;
1852 	struct adapter_reply_queue *reply_q;
1853 	int num_entries = 0;
1854 	int qid = queue_num - ioc->iopoll_q_start_index;
1855 
1856 	if (atomic_read(&ioc->io_uring_poll_queues[qid].pause) ||
1857 	    !atomic_add_unless(&ioc->io_uring_poll_queues[qid].busy, 1, 1))
1858 		return 0;
1859 
1860 	reply_q = ioc->io_uring_poll_queues[qid].reply_q;
1861 
1862 	num_entries = _base_process_reply_queue(reply_q);
1863 	atomic_dec(&ioc->io_uring_poll_queues[qid].busy);
1864 
1865 	return num_entries;
1866 }
1867 
1868 /**
1869  * _base_interrupt - MPT adapter (IOC) specific interrupt handler.
1870  * @irq: irq number (not used)
1871  * @bus_id: bus identifier cookie == pointer to MPT_ADAPTER structure
1872  *
1873  * Return: IRQ_HANDLED if processed, else IRQ_NONE.
1874  */
1875 static irqreturn_t
1876 _base_interrupt(int irq, void *bus_id)
1877 {
1878 	struct adapter_reply_queue *reply_q = bus_id;
1879 	struct MPT3SAS_ADAPTER *ioc = reply_q->ioc;
1880 
1881 	if (ioc->mask_interrupts)
1882 		return IRQ_NONE;
1883 	if (reply_q->irq_poll_scheduled)
1884 		return IRQ_HANDLED;
1885 	return ((_base_process_reply_queue(reply_q) > 0) ?
1886 			IRQ_HANDLED : IRQ_NONE);
1887 }
1888 
1889 /**
1890  * _base_irqpoll - IRQ poll callback handler
1891  * @irqpoll: irq_poll object
1892  * @budget: irq poll weight
1893  *
1894  * Return: number of reply descriptors processed
1895  */
1896 static int
1897 _base_irqpoll(struct irq_poll *irqpoll, int budget)
1898 {
1899 	struct adapter_reply_queue *reply_q;
1900 	int num_entries = 0;
1901 
1902 	reply_q = container_of(irqpoll, struct adapter_reply_queue,
1903 			irqpoll);
1904 	if (reply_q->irq_line_enable) {
1905 		disable_irq_nosync(reply_q->os_irq);
1906 		reply_q->irq_line_enable = false;
1907 	}
1908 	num_entries = _base_process_reply_queue(reply_q);
1909 	if (num_entries < budget) {
1910 		irq_poll_complete(irqpoll);
1911 		reply_q->irq_poll_scheduled = false;
1912 		reply_q->irq_line_enable = true;
1913 		enable_irq(reply_q->os_irq);
1914 		/*
1915 		 * Go for one more round of processing the
1916 		 * reply descriptor post queue in case the HBA
1917 		 * Firmware has posted some reply descriptors
1918 		 * while reenabling the IRQ.
1919 		 */
1920 		_base_process_reply_queue(reply_q);
1921 	}
1922 
1923 	return num_entries;
1924 }
1925 
1926 /**
1927  * _base_init_irqpolls - initliaze IRQ polls
1928  * @ioc: per adapter object
1929  *
1930  * Return: nothing
1931  */
1932 static void
1933 _base_init_irqpolls(struct MPT3SAS_ADAPTER *ioc)
1934 {
1935 	struct adapter_reply_queue *reply_q, *next;
1936 
1937 	if (list_empty(&ioc->reply_queue_list))
1938 		return;
1939 
1940 	list_for_each_entry_safe(reply_q, next, &ioc->reply_queue_list, list) {
1941 		if (reply_q->is_iouring_poll_q)
1942 			continue;
1943 		irq_poll_init(&reply_q->irqpoll,
1944 			ioc->hba_queue_depth/4, _base_irqpoll);
1945 		reply_q->irq_poll_scheduled = false;
1946 		reply_q->irq_line_enable = true;
1947 		reply_q->os_irq = pci_irq_vector(ioc->pdev,
1948 		    reply_q->msix_index);
1949 	}
1950 }
1951 
1952 /**
1953  * _base_is_controller_msix_enabled - is controller support muli-reply queues
1954  * @ioc: per adapter object
1955  *
1956  * Return: Whether or not MSI/X is enabled.
1957  */
1958 static inline int
1959 _base_is_controller_msix_enabled(struct MPT3SAS_ADAPTER *ioc)
1960 {
1961 	return (ioc->facts.IOCCapabilities &
1962 	    MPI2_IOCFACTS_CAPABILITY_MSI_X_INDEX) && ioc->msix_enable;
1963 }
1964 
1965 /**
1966  * mpt3sas_base_sync_reply_irqs - flush pending MSIX interrupts
1967  * @ioc: per adapter object
1968  * @poll: poll over reply descriptor pools incase interrupt for
1969  *		timed-out SCSI command got delayed
1970  * Context: non-ISR context
1971  *
1972  * Called when a Task Management request has completed.
1973  */
1974 void
1975 mpt3sas_base_sync_reply_irqs(struct MPT3SAS_ADAPTER *ioc, u8 poll)
1976 {
1977 	struct adapter_reply_queue *reply_q;
1978 
1979 	/* If MSIX capability is turned off
1980 	 * then multi-queues are not enabled
1981 	 */
1982 	if (!_base_is_controller_msix_enabled(ioc))
1983 		return;
1984 
1985 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
1986 		if (ioc->shost_recovery || ioc->remove_host ||
1987 				ioc->pci_error_recovery)
1988 			return;
1989 		/* TMs are on msix_index == 0 */
1990 		if (reply_q->msix_index == 0)
1991 			continue;
1992 
1993 		if (reply_q->is_iouring_poll_q) {
1994 			_base_process_reply_queue(reply_q);
1995 			continue;
1996 		}
1997 
1998 		synchronize_irq(pci_irq_vector(ioc->pdev, reply_q->msix_index));
1999 		if (reply_q->irq_poll_scheduled) {
2000 			/* Calling irq_poll_disable will wait for any pending
2001 			 * callbacks to have completed.
2002 			 */
2003 			irq_poll_disable(&reply_q->irqpoll);
2004 			irq_poll_enable(&reply_q->irqpoll);
2005 			/* check how the scheduled poll has ended,
2006 			 * clean up only if necessary
2007 			 */
2008 			if (reply_q->irq_poll_scheduled) {
2009 				reply_q->irq_poll_scheduled = false;
2010 				reply_q->irq_line_enable = true;
2011 				enable_irq(reply_q->os_irq);
2012 			}
2013 		}
2014 
2015 		if (poll)
2016 			_base_process_reply_queue(reply_q);
2017 	}
2018 }
2019 
2020 /**
2021  * mpt3sas_base_release_callback_handler - clear interrupt callback handler
2022  * @cb_idx: callback index
2023  */
2024 void
2025 mpt3sas_base_release_callback_handler(u8 cb_idx)
2026 {
2027 	mpt_callbacks[cb_idx] = NULL;
2028 }
2029 
2030 /**
2031  * mpt3sas_base_register_callback_handler - obtain index for the interrupt callback handler
2032  * @cb_func: callback function
2033  *
2034  * Return: Index of @cb_func.
2035  */
2036 u8
2037 mpt3sas_base_register_callback_handler(MPT_CALLBACK cb_func)
2038 {
2039 	u8 cb_idx;
2040 
2041 	for (cb_idx = MPT_MAX_CALLBACKS-1; cb_idx; cb_idx--)
2042 		if (mpt_callbacks[cb_idx] == NULL)
2043 			break;
2044 
2045 	mpt_callbacks[cb_idx] = cb_func;
2046 	return cb_idx;
2047 }
2048 
2049 /**
2050  * mpt3sas_base_initialize_callback_handler - initialize the interrupt callback handler
2051  */
2052 void
2053 mpt3sas_base_initialize_callback_handler(void)
2054 {
2055 	u8 cb_idx;
2056 
2057 	for (cb_idx = 0; cb_idx < MPT_MAX_CALLBACKS; cb_idx++)
2058 		mpt3sas_base_release_callback_handler(cb_idx);
2059 }
2060 
2061 
2062 /**
2063  * _base_build_zero_len_sge - build zero length sg entry
2064  * @ioc: per adapter object
2065  * @paddr: virtual address for SGE
2066  *
2067  * Create a zero length scatter gather entry to insure the IOCs hardware has
2068  * something to use if the target device goes brain dead and tries
2069  * to send data even when none is asked for.
2070  */
2071 static void
2072 _base_build_zero_len_sge(struct MPT3SAS_ADAPTER *ioc, void *paddr)
2073 {
2074 	u32 flags_length = (u32)((MPI2_SGE_FLAGS_LAST_ELEMENT |
2075 	    MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_END_OF_LIST |
2076 	    MPI2_SGE_FLAGS_SIMPLE_ELEMENT) <<
2077 	    MPI2_SGE_FLAGS_SHIFT);
2078 	ioc->base_add_sg_single(paddr, flags_length, -1);
2079 }
2080 
2081 /**
2082  * _base_add_sg_single_32 - Place a simple 32 bit SGE at address pAddr.
2083  * @paddr: virtual address for SGE
2084  * @flags_length: SGE flags and data transfer length
2085  * @dma_addr: Physical address
2086  */
2087 static void
2088 _base_add_sg_single_32(void *paddr, u32 flags_length, dma_addr_t dma_addr)
2089 {
2090 	Mpi2SGESimple32_t *sgel = paddr;
2091 
2092 	flags_length |= (MPI2_SGE_FLAGS_32_BIT_ADDRESSING |
2093 	    MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT;
2094 	sgel->FlagsLength = cpu_to_le32(flags_length);
2095 	sgel->Address = cpu_to_le32(dma_addr);
2096 }
2097 
2098 
2099 /**
2100  * _base_add_sg_single_64 - Place a simple 64 bit SGE at address pAddr.
2101  * @paddr: virtual address for SGE
2102  * @flags_length: SGE flags and data transfer length
2103  * @dma_addr: Physical address
2104  */
2105 static void
2106 _base_add_sg_single_64(void *paddr, u32 flags_length, dma_addr_t dma_addr)
2107 {
2108 	Mpi2SGESimple64_t *sgel = paddr;
2109 
2110 	flags_length |= (MPI2_SGE_FLAGS_64_BIT_ADDRESSING |
2111 	    MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT;
2112 	sgel->FlagsLength = cpu_to_le32(flags_length);
2113 	sgel->Address = cpu_to_le64(dma_addr);
2114 }
2115 
2116 /**
2117  * _base_get_chain_buffer_tracker - obtain chain tracker
2118  * @ioc: per adapter object
2119  * @scmd: SCSI commands of the IO request
2120  *
2121  * Return: chain tracker from chain_lookup table using key as
2122  * smid and smid's chain_offset.
2123  */
2124 static struct chain_tracker *
2125 _base_get_chain_buffer_tracker(struct MPT3SAS_ADAPTER *ioc,
2126 			       struct scsi_cmnd *scmd)
2127 {
2128 	struct chain_tracker *chain_req;
2129 	struct scsiio_tracker *st = scsi_cmd_priv(scmd);
2130 	u16 smid = st->smid;
2131 	u8 chain_offset =
2132 	   atomic_read(&ioc->chain_lookup[smid - 1].chain_offset);
2133 
2134 	if (chain_offset == ioc->chains_needed_per_io)
2135 		return NULL;
2136 
2137 	chain_req = &ioc->chain_lookup[smid - 1].chains_per_smid[chain_offset];
2138 	atomic_inc(&ioc->chain_lookup[smid - 1].chain_offset);
2139 	return chain_req;
2140 }
2141 
2142 
2143 /**
2144  * _base_build_sg - build generic sg
2145  * @ioc: per adapter object
2146  * @psge: virtual address for SGE
2147  * @data_out_dma: physical address for WRITES
2148  * @data_out_sz: data xfer size for WRITES
2149  * @data_in_dma: physical address for READS
2150  * @data_in_sz: data xfer size for READS
2151  */
2152 static void
2153 _base_build_sg(struct MPT3SAS_ADAPTER *ioc, void *psge,
2154 	dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
2155 	size_t data_in_sz)
2156 {
2157 	u32 sgl_flags;
2158 
2159 	if (!data_out_sz && !data_in_sz) {
2160 		_base_build_zero_len_sge(ioc, psge);
2161 		return;
2162 	}
2163 
2164 	if (data_out_sz && data_in_sz) {
2165 		/* WRITE sgel first */
2166 		sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2167 		    MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_HOST_TO_IOC);
2168 		sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
2169 		ioc->base_add_sg_single(psge, sgl_flags |
2170 		    data_out_sz, data_out_dma);
2171 
2172 		/* incr sgel */
2173 		psge += ioc->sge_size;
2174 
2175 		/* READ sgel last */
2176 		sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2177 		    MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
2178 		    MPI2_SGE_FLAGS_END_OF_LIST);
2179 		sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
2180 		ioc->base_add_sg_single(psge, sgl_flags |
2181 		    data_in_sz, data_in_dma);
2182 	} else if (data_out_sz) /* WRITE */ {
2183 		sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2184 		    MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
2185 		    MPI2_SGE_FLAGS_END_OF_LIST | MPI2_SGE_FLAGS_HOST_TO_IOC);
2186 		sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
2187 		ioc->base_add_sg_single(psge, sgl_flags |
2188 		    data_out_sz, data_out_dma);
2189 	} else if (data_in_sz) /* READ */ {
2190 		sgl_flags = (MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2191 		    MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER |
2192 		    MPI2_SGE_FLAGS_END_OF_LIST);
2193 		sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
2194 		ioc->base_add_sg_single(psge, sgl_flags |
2195 		    data_in_sz, data_in_dma);
2196 	}
2197 }
2198 
2199 /* IEEE format sgls */
2200 
2201 /**
2202  * _base_build_nvme_prp - This function is called for NVMe end devices to build
2203  *                        a native SGL (NVMe PRP).
2204  * @ioc: per adapter object
2205  * @smid: system request message index for getting asscociated SGL
2206  * @nvme_encap_request: the NVMe request msg frame pointer
2207  * @data_out_dma: physical address for WRITES
2208  * @data_out_sz: data xfer size for WRITES
2209  * @data_in_dma: physical address for READS
2210  * @data_in_sz: data xfer size for READS
2211  *
2212  * The native SGL is built starting in the first PRP
2213  * entry of the NVMe message (PRP1).  If the data buffer is small enough to be
2214  * described entirely using PRP1, then PRP2 is not used.  If needed, PRP2 is
2215  * used to describe a larger data buffer.  If the data buffer is too large to
2216  * describe using the two PRP entriess inside the NVMe message, then PRP1
2217  * describes the first data memory segment, and PRP2 contains a pointer to a PRP
2218  * list located elsewhere in memory to describe the remaining data memory
2219  * segments.  The PRP list will be contiguous.
2220  *
2221  * The native SGL for NVMe devices is a Physical Region Page (PRP).  A PRP
2222  * consists of a list of PRP entries to describe a number of noncontigous
2223  * physical memory segments as a single memory buffer, just as a SGL does.  Note
2224  * however, that this function is only used by the IOCTL call, so the memory
2225  * given will be guaranteed to be contiguous.  There is no need to translate
2226  * non-contiguous SGL into a PRP in this case.  All PRPs will describe
2227  * contiguous space that is one page size each.
2228  *
2229  * Each NVMe message contains two PRP entries.  The first (PRP1) either contains
2230  * a PRP list pointer or a PRP element, depending upon the command.  PRP2
2231  * contains the second PRP element if the memory being described fits within 2
2232  * PRP entries, or a PRP list pointer if the PRP spans more than two entries.
2233  *
2234  * A PRP list pointer contains the address of a PRP list, structured as a linear
2235  * array of PRP entries.  Each PRP entry in this list describes a segment of
2236  * physical memory.
2237  *
2238  * Each 64-bit PRP entry comprises an address and an offset field.  The address
2239  * always points at the beginning of a 4KB physical memory page, and the offset
2240  * describes where within that 4KB page the memory segment begins.  Only the
2241  * first element in a PRP list may contain a non-zero offset, implying that all
2242  * memory segments following the first begin at the start of a 4KB page.
2243  *
2244  * Each PRP element normally describes 4KB of physical memory, with exceptions
2245  * for the first and last elements in the list.  If the memory being described
2246  * by the list begins at a non-zero offset within the first 4KB page, then the
2247  * first PRP element will contain a non-zero offset indicating where the region
2248  * begins within the 4KB page.  The last memory segment may end before the end
2249  * of the 4KB segment, depending upon the overall size of the memory being
2250  * described by the PRP list.
2251  *
2252  * Since PRP entries lack any indication of size, the overall data buffer length
2253  * is used to determine where the end of the data memory buffer is located, and
2254  * how many PRP entries are required to describe it.
2255  */
2256 static void
2257 _base_build_nvme_prp(struct MPT3SAS_ADAPTER *ioc, u16 smid,
2258 	Mpi26NVMeEncapsulatedRequest_t *nvme_encap_request,
2259 	dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
2260 	size_t data_in_sz)
2261 {
2262 	int		prp_size = NVME_PRP_SIZE;
2263 	__le64		*prp_entry, *prp1_entry, *prp2_entry;
2264 	__le64		*prp_page;
2265 	dma_addr_t	prp_entry_dma, prp_page_dma, dma_addr;
2266 	u32		offset, entry_len;
2267 	u32		page_mask_result, page_mask;
2268 	size_t		length;
2269 	struct mpt3sas_nvme_cmd *nvme_cmd =
2270 		(void *)nvme_encap_request->NVMe_Command;
2271 
2272 	/*
2273 	 * Not all commands require a data transfer. If no data, just return
2274 	 * without constructing any PRP.
2275 	 */
2276 	if (!data_in_sz && !data_out_sz)
2277 		return;
2278 	prp1_entry = &nvme_cmd->prp1;
2279 	prp2_entry = &nvme_cmd->prp2;
2280 	prp_entry = prp1_entry;
2281 	/*
2282 	 * For the PRP entries, use the specially allocated buffer of
2283 	 * contiguous memory.
2284 	 */
2285 	prp_page = (__le64 *)mpt3sas_base_get_pcie_sgl(ioc, smid);
2286 	prp_page_dma = mpt3sas_base_get_pcie_sgl_dma(ioc, smid);
2287 
2288 	/*
2289 	 * Check if we are within 1 entry of a page boundary we don't
2290 	 * want our first entry to be a PRP List entry.
2291 	 */
2292 	page_mask = ioc->page_size - 1;
2293 	page_mask_result = (uintptr_t)((u8 *)prp_page + prp_size) & page_mask;
2294 	if (!page_mask_result) {
2295 		/* Bump up to next page boundary. */
2296 		prp_page = (__le64 *)((u8 *)prp_page + prp_size);
2297 		prp_page_dma = prp_page_dma + prp_size;
2298 	}
2299 
2300 	/*
2301 	 * Set PRP physical pointer, which initially points to the current PRP
2302 	 * DMA memory page.
2303 	 */
2304 	prp_entry_dma = prp_page_dma;
2305 
2306 	/* Get physical address and length of the data buffer. */
2307 	if (data_in_sz) {
2308 		dma_addr = data_in_dma;
2309 		length = data_in_sz;
2310 	} else {
2311 		dma_addr = data_out_dma;
2312 		length = data_out_sz;
2313 	}
2314 
2315 	/* Loop while the length is not zero. */
2316 	while (length) {
2317 		/*
2318 		 * Check if we need to put a list pointer here if we are at
2319 		 * page boundary - prp_size (8 bytes).
2320 		 */
2321 		page_mask_result = (prp_entry_dma + prp_size) & page_mask;
2322 		if (!page_mask_result) {
2323 			/*
2324 			 * This is the last entry in a PRP List, so we need to
2325 			 * put a PRP list pointer here.  What this does is:
2326 			 *   - bump the current memory pointer to the next
2327 			 *     address, which will be the next full page.
2328 			 *   - set the PRP Entry to point to that page.  This
2329 			 *     is now the PRP List pointer.
2330 			 *   - bump the PRP Entry pointer the start of the
2331 			 *     next page.  Since all of this PRP memory is
2332 			 *     contiguous, no need to get a new page - it's
2333 			 *     just the next address.
2334 			 */
2335 			prp_entry_dma++;
2336 			*prp_entry = cpu_to_le64(prp_entry_dma);
2337 			prp_entry++;
2338 		}
2339 
2340 		/* Need to handle if entry will be part of a page. */
2341 		offset = dma_addr & page_mask;
2342 		entry_len = ioc->page_size - offset;
2343 
2344 		if (prp_entry == prp1_entry) {
2345 			/*
2346 			 * Must fill in the first PRP pointer (PRP1) before
2347 			 * moving on.
2348 			 */
2349 			*prp1_entry = cpu_to_le64(dma_addr);
2350 
2351 			/*
2352 			 * Now point to the second PRP entry within the
2353 			 * command (PRP2).
2354 			 */
2355 			prp_entry = prp2_entry;
2356 		} else if (prp_entry == prp2_entry) {
2357 			/*
2358 			 * Should the PRP2 entry be a PRP List pointer or just
2359 			 * a regular PRP pointer?  If there is more than one
2360 			 * more page of data, must use a PRP List pointer.
2361 			 */
2362 			if (length > ioc->page_size) {
2363 				/*
2364 				 * PRP2 will contain a PRP List pointer because
2365 				 * more PRP's are needed with this command. The
2366 				 * list will start at the beginning of the
2367 				 * contiguous buffer.
2368 				 */
2369 				*prp2_entry = cpu_to_le64(prp_entry_dma);
2370 
2371 				/*
2372 				 * The next PRP Entry will be the start of the
2373 				 * first PRP List.
2374 				 */
2375 				prp_entry = prp_page;
2376 			} else {
2377 				/*
2378 				 * After this, the PRP Entries are complete.
2379 				 * This command uses 2 PRP's and no PRP list.
2380 				 */
2381 				*prp2_entry = cpu_to_le64(dma_addr);
2382 			}
2383 		} else {
2384 			/*
2385 			 * Put entry in list and bump the addresses.
2386 			 *
2387 			 * After PRP1 and PRP2 are filled in, this will fill in
2388 			 * all remaining PRP entries in a PRP List, one per
2389 			 * each time through the loop.
2390 			 */
2391 			*prp_entry = cpu_to_le64(dma_addr);
2392 			prp_entry++;
2393 			prp_entry_dma++;
2394 		}
2395 
2396 		/*
2397 		 * Bump the phys address of the command's data buffer by the
2398 		 * entry_len.
2399 		 */
2400 		dma_addr += entry_len;
2401 
2402 		/* Decrement length accounting for last partial page. */
2403 		if (entry_len > length)
2404 			length = 0;
2405 		else
2406 			length -= entry_len;
2407 	}
2408 }
2409 
2410 /**
2411  * base_make_prp_nvme - Prepare PRPs (Physical Region Page) -
2412  *			SGLs specific to NVMe drives only
2413  *
2414  * @ioc:		per adapter object
2415  * @scmd:		SCSI command from the mid-layer
2416  * @mpi_request:	mpi request
2417  * @smid:		msg Index
2418  * @sge_count:		scatter gather element count.
2419  *
2420  * Return:		true: PRPs are built
2421  *			false: IEEE SGLs needs to be built
2422  */
2423 static void
2424 base_make_prp_nvme(struct MPT3SAS_ADAPTER *ioc,
2425 		struct scsi_cmnd *scmd,
2426 		Mpi25SCSIIORequest_t *mpi_request,
2427 		u16 smid, int sge_count)
2428 {
2429 	int sge_len, num_prp_in_chain = 0;
2430 	Mpi25IeeeSgeChain64_t *main_chain_element, *ptr_first_sgl;
2431 	__le64 *curr_buff;
2432 	dma_addr_t msg_dma, sge_addr, offset;
2433 	u32 page_mask, page_mask_result;
2434 	struct scatterlist *sg_scmd;
2435 	u32 first_prp_len;
2436 	int data_len = scsi_bufflen(scmd);
2437 	u32 nvme_pg_size;
2438 
2439 	nvme_pg_size = max_t(u32, ioc->page_size, NVME_PRP_PAGE_SIZE);
2440 	/*
2441 	 * Nvme has a very convoluted prp format.  One prp is required
2442 	 * for each page or partial page. Driver need to split up OS sg_list
2443 	 * entries if it is longer than one page or cross a page
2444 	 * boundary.  Driver also have to insert a PRP list pointer entry as
2445 	 * the last entry in each physical page of the PRP list.
2446 	 *
2447 	 * NOTE: The first PRP "entry" is actually placed in the first
2448 	 * SGL entry in the main message as IEEE 64 format.  The 2nd
2449 	 * entry in the main message is the chain element, and the rest
2450 	 * of the PRP entries are built in the contiguous pcie buffer.
2451 	 */
2452 	page_mask = nvme_pg_size - 1;
2453 
2454 	/*
2455 	 * Native SGL is needed.
2456 	 * Put a chain element in main message frame that points to the first
2457 	 * chain buffer.
2458 	 *
2459 	 * NOTE:  The ChainOffset field must be 0 when using a chain pointer to
2460 	 *        a native SGL.
2461 	 */
2462 
2463 	/* Set main message chain element pointer */
2464 	main_chain_element = (pMpi25IeeeSgeChain64_t)&mpi_request->SGL;
2465 	/*
2466 	 * For NVMe the chain element needs to be the 2nd SG entry in the main
2467 	 * message.
2468 	 */
2469 	main_chain_element = (Mpi25IeeeSgeChain64_t *)
2470 		((u8 *)main_chain_element + sizeof(MPI25_IEEE_SGE_CHAIN64));
2471 
2472 	/*
2473 	 * For the PRP entries, use the specially allocated buffer of
2474 	 * contiguous memory.  Normal chain buffers can't be used
2475 	 * because each chain buffer would need to be the size of an OS
2476 	 * page (4k).
2477 	 */
2478 	curr_buff = mpt3sas_base_get_pcie_sgl(ioc, smid);
2479 	msg_dma = mpt3sas_base_get_pcie_sgl_dma(ioc, smid);
2480 
2481 	main_chain_element->Address = cpu_to_le64(msg_dma);
2482 	main_chain_element->NextChainOffset = 0;
2483 	main_chain_element->Flags = MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
2484 			MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
2485 			MPI26_IEEE_SGE_FLAGS_NSF_NVME_PRP;
2486 
2487 	/* Build first prp, sge need not to be page aligned*/
2488 	ptr_first_sgl = (pMpi25IeeeSgeChain64_t)&mpi_request->SGL;
2489 	sg_scmd = scsi_sglist(scmd);
2490 	sge_addr = sg_dma_address(sg_scmd);
2491 	sge_len = sg_dma_len(sg_scmd);
2492 
2493 	offset = sge_addr & page_mask;
2494 	first_prp_len = nvme_pg_size - offset;
2495 
2496 	ptr_first_sgl->Address = cpu_to_le64(sge_addr);
2497 	ptr_first_sgl->Length = cpu_to_le32(first_prp_len);
2498 
2499 	data_len -= first_prp_len;
2500 
2501 	if (sge_len > first_prp_len) {
2502 		sge_addr += first_prp_len;
2503 		sge_len -= first_prp_len;
2504 	} else if (data_len && (sge_len == first_prp_len)) {
2505 		sg_scmd = sg_next(sg_scmd);
2506 		sge_addr = sg_dma_address(sg_scmd);
2507 		sge_len = sg_dma_len(sg_scmd);
2508 	}
2509 
2510 	for (;;) {
2511 		offset = sge_addr & page_mask;
2512 
2513 		/* Put PRP pointer due to page boundary*/
2514 		page_mask_result = (uintptr_t)(curr_buff + 1) & page_mask;
2515 		if (unlikely(!page_mask_result)) {
2516 			scmd_printk(KERN_NOTICE,
2517 				scmd, "page boundary curr_buff: 0x%p\n",
2518 				curr_buff);
2519 			msg_dma += 8;
2520 			*curr_buff = cpu_to_le64(msg_dma);
2521 			curr_buff++;
2522 			num_prp_in_chain++;
2523 		}
2524 
2525 		*curr_buff = cpu_to_le64(sge_addr);
2526 		curr_buff++;
2527 		msg_dma += 8;
2528 		num_prp_in_chain++;
2529 
2530 		sge_addr += nvme_pg_size;
2531 		sge_len -= nvme_pg_size;
2532 		data_len -= nvme_pg_size;
2533 
2534 		if (data_len <= 0)
2535 			break;
2536 
2537 		if (sge_len > 0)
2538 			continue;
2539 
2540 		sg_scmd = sg_next(sg_scmd);
2541 		sge_addr = sg_dma_address(sg_scmd);
2542 		sge_len = sg_dma_len(sg_scmd);
2543 	}
2544 
2545 	main_chain_element->Length =
2546 		cpu_to_le32(num_prp_in_chain * sizeof(u64));
2547 	return;
2548 }
2549 
2550 static bool
2551 base_is_prp_possible(struct MPT3SAS_ADAPTER *ioc,
2552 	struct _pcie_device *pcie_device, struct scsi_cmnd *scmd, int sge_count)
2553 {
2554 	u32 data_length = 0;
2555 	bool build_prp = true;
2556 
2557 	data_length = scsi_bufflen(scmd);
2558 	if (pcie_device &&
2559 	    (mpt3sas_scsih_is_pcie_scsi_device(pcie_device->device_info))) {
2560 		build_prp = false;
2561 		return build_prp;
2562 	}
2563 
2564 	/* If Datalenth is <= 16K and number of SGE’s entries are <= 2
2565 	 * we built IEEE SGL
2566 	 */
2567 	if ((data_length <= NVME_PRP_PAGE_SIZE*4) && (sge_count <= 2))
2568 		build_prp = false;
2569 
2570 	return build_prp;
2571 }
2572 
2573 /**
2574  * _base_check_pcie_native_sgl - This function is called for PCIe end devices to
2575  * determine if the driver needs to build a native SGL.  If so, that native
2576  * SGL is built in the special contiguous buffers allocated especially for
2577  * PCIe SGL creation.  If the driver will not build a native SGL, return
2578  * TRUE and a normal IEEE SGL will be built.  Currently this routine
2579  * supports NVMe.
2580  * @ioc: per adapter object
2581  * @mpi_request: mf request pointer
2582  * @smid: system request message index
2583  * @scmd: scsi command
2584  * @pcie_device: points to the PCIe device's info
2585  *
2586  * Return: 0 if native SGL was built, 1 if no SGL was built
2587  */
2588 static int
2589 _base_check_pcie_native_sgl(struct MPT3SAS_ADAPTER *ioc,
2590 	Mpi25SCSIIORequest_t *mpi_request, u16 smid, struct scsi_cmnd *scmd,
2591 	struct _pcie_device *pcie_device)
2592 {
2593 	int sges_left;
2594 
2595 	/* Get the SG list pointer and info. */
2596 	sges_left = scsi_dma_map(scmd);
2597 	if (sges_left < 0)
2598 		return 1;
2599 
2600 	/* Check if we need to build a native SG list. */
2601 	if (!base_is_prp_possible(ioc, pcie_device,
2602 				scmd, sges_left)) {
2603 		/* We built a native SG list, just return. */
2604 		goto out;
2605 	}
2606 
2607 	/*
2608 	 * Build native NVMe PRP.
2609 	 */
2610 	base_make_prp_nvme(ioc, scmd, mpi_request,
2611 			smid, sges_left);
2612 
2613 	return 0;
2614 out:
2615 	scsi_dma_unmap(scmd);
2616 	return 1;
2617 }
2618 
2619 /**
2620  * _base_add_sg_single_ieee - add sg element for IEEE format
2621  * @paddr: virtual address for SGE
2622  * @flags: SGE flags
2623  * @chain_offset: number of 128 byte elements from start of segment
2624  * @length: data transfer length
2625  * @dma_addr: Physical address
2626  */
2627 static void
2628 _base_add_sg_single_ieee(void *paddr, u8 flags, u8 chain_offset, u32 length,
2629 	dma_addr_t dma_addr)
2630 {
2631 	Mpi25IeeeSgeChain64_t *sgel = paddr;
2632 
2633 	sgel->Flags = flags;
2634 	sgel->NextChainOffset = chain_offset;
2635 	sgel->Length = cpu_to_le32(length);
2636 	sgel->Address = cpu_to_le64(dma_addr);
2637 }
2638 
2639 /**
2640  * _base_build_zero_len_sge_ieee - build zero length sg entry for IEEE format
2641  * @ioc: per adapter object
2642  * @paddr: virtual address for SGE
2643  *
2644  * Create a zero length scatter gather entry to insure the IOCs hardware has
2645  * something to use if the target device goes brain dead and tries
2646  * to send data even when none is asked for.
2647  */
2648 static void
2649 _base_build_zero_len_sge_ieee(struct MPT3SAS_ADAPTER *ioc, void *paddr)
2650 {
2651 	u8 sgl_flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2652 		MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
2653 		MPI25_IEEE_SGE_FLAGS_END_OF_LIST);
2654 
2655 	_base_add_sg_single_ieee(paddr, sgl_flags, 0, 0, -1);
2656 }
2657 
2658 /**
2659  * _base_build_sg_scmd - main sg creation routine
2660  *		pcie_device is unused here!
2661  * @ioc: per adapter object
2662  * @scmd: scsi command
2663  * @smid: system request message index
2664  * @unused: unused pcie_device pointer
2665  * Context: none.
2666  *
2667  * The main routine that builds scatter gather table from a given
2668  * scsi request sent via the .queuecommand main handler.
2669  *
2670  * Return: 0 success, anything else error
2671  */
2672 static int
2673 _base_build_sg_scmd(struct MPT3SAS_ADAPTER *ioc,
2674 	struct scsi_cmnd *scmd, u16 smid, struct _pcie_device *unused)
2675 {
2676 	Mpi2SCSIIORequest_t *mpi_request;
2677 	dma_addr_t chain_dma;
2678 	struct scatterlist *sg_scmd;
2679 	void *sg_local, *chain;
2680 	u32 chain_offset;
2681 	u32 chain_length;
2682 	u32 chain_flags;
2683 	int sges_left;
2684 	u32 sges_in_segment;
2685 	u32 sgl_flags;
2686 	u32 sgl_flags_last_element;
2687 	u32 sgl_flags_end_buffer;
2688 	struct chain_tracker *chain_req;
2689 
2690 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
2691 
2692 	/* init scatter gather flags */
2693 	sgl_flags = MPI2_SGE_FLAGS_SIMPLE_ELEMENT;
2694 	if (scmd->sc_data_direction == DMA_TO_DEVICE)
2695 		sgl_flags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
2696 	sgl_flags_last_element = (sgl_flags | MPI2_SGE_FLAGS_LAST_ELEMENT)
2697 	    << MPI2_SGE_FLAGS_SHIFT;
2698 	sgl_flags_end_buffer = (sgl_flags | MPI2_SGE_FLAGS_LAST_ELEMENT |
2699 	    MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_END_OF_LIST)
2700 	    << MPI2_SGE_FLAGS_SHIFT;
2701 	sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
2702 
2703 	sg_scmd = scsi_sglist(scmd);
2704 	sges_left = scsi_dma_map(scmd);
2705 	if (sges_left < 0)
2706 		return -ENOMEM;
2707 
2708 	sg_local = &mpi_request->SGL;
2709 	sges_in_segment = ioc->max_sges_in_main_message;
2710 	if (sges_left <= sges_in_segment)
2711 		goto fill_in_last_segment;
2712 
2713 	mpi_request->ChainOffset = (offsetof(Mpi2SCSIIORequest_t, SGL) +
2714 	    (sges_in_segment * ioc->sge_size))/4;
2715 
2716 	/* fill in main message segment when there is a chain following */
2717 	while (sges_in_segment) {
2718 		if (sges_in_segment == 1)
2719 			ioc->base_add_sg_single(sg_local,
2720 			    sgl_flags_last_element | sg_dma_len(sg_scmd),
2721 			    sg_dma_address(sg_scmd));
2722 		else
2723 			ioc->base_add_sg_single(sg_local, sgl_flags |
2724 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2725 		sg_scmd = sg_next(sg_scmd);
2726 		sg_local += ioc->sge_size;
2727 		sges_left--;
2728 		sges_in_segment--;
2729 	}
2730 
2731 	/* initializing the chain flags and pointers */
2732 	chain_flags = MPI2_SGE_FLAGS_CHAIN_ELEMENT << MPI2_SGE_FLAGS_SHIFT;
2733 	chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2734 	if (!chain_req)
2735 		return -1;
2736 	chain = chain_req->chain_buffer;
2737 	chain_dma = chain_req->chain_buffer_dma;
2738 	do {
2739 		sges_in_segment = (sges_left <=
2740 		    ioc->max_sges_in_chain_message) ? sges_left :
2741 		    ioc->max_sges_in_chain_message;
2742 		chain_offset = (sges_left == sges_in_segment) ?
2743 		    0 : (sges_in_segment * ioc->sge_size)/4;
2744 		chain_length = sges_in_segment * ioc->sge_size;
2745 		if (chain_offset) {
2746 			chain_offset = chain_offset <<
2747 			    MPI2_SGE_CHAIN_OFFSET_SHIFT;
2748 			chain_length += ioc->sge_size;
2749 		}
2750 		ioc->base_add_sg_single(sg_local, chain_flags | chain_offset |
2751 		    chain_length, chain_dma);
2752 		sg_local = chain;
2753 		if (!chain_offset)
2754 			goto fill_in_last_segment;
2755 
2756 		/* fill in chain segments */
2757 		while (sges_in_segment) {
2758 			if (sges_in_segment == 1)
2759 				ioc->base_add_sg_single(sg_local,
2760 				    sgl_flags_last_element |
2761 				    sg_dma_len(sg_scmd),
2762 				    sg_dma_address(sg_scmd));
2763 			else
2764 				ioc->base_add_sg_single(sg_local, sgl_flags |
2765 				    sg_dma_len(sg_scmd),
2766 				    sg_dma_address(sg_scmd));
2767 			sg_scmd = sg_next(sg_scmd);
2768 			sg_local += ioc->sge_size;
2769 			sges_left--;
2770 			sges_in_segment--;
2771 		}
2772 
2773 		chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2774 		if (!chain_req)
2775 			return -1;
2776 		chain = chain_req->chain_buffer;
2777 		chain_dma = chain_req->chain_buffer_dma;
2778 	} while (1);
2779 
2780 
2781  fill_in_last_segment:
2782 
2783 	/* fill the last segment */
2784 	while (sges_left) {
2785 		if (sges_left == 1)
2786 			ioc->base_add_sg_single(sg_local, sgl_flags_end_buffer |
2787 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2788 		else
2789 			ioc->base_add_sg_single(sg_local, sgl_flags |
2790 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2791 		sg_scmd = sg_next(sg_scmd);
2792 		sg_local += ioc->sge_size;
2793 		sges_left--;
2794 	}
2795 
2796 	return 0;
2797 }
2798 
2799 /**
2800  * _base_build_sg_scmd_ieee - main sg creation routine for IEEE format
2801  * @ioc: per adapter object
2802  * @scmd: scsi command
2803  * @smid: system request message index
2804  * @pcie_device: Pointer to pcie_device. If set, the pcie native sgl will be
2805  * constructed on need.
2806  * Context: none.
2807  *
2808  * The main routine that builds scatter gather table from a given
2809  * scsi request sent via the .queuecommand main handler.
2810  *
2811  * Return: 0 success, anything else error
2812  */
2813 static int
2814 _base_build_sg_scmd_ieee(struct MPT3SAS_ADAPTER *ioc,
2815 	struct scsi_cmnd *scmd, u16 smid, struct _pcie_device *pcie_device)
2816 {
2817 	Mpi25SCSIIORequest_t *mpi_request;
2818 	dma_addr_t chain_dma;
2819 	struct scatterlist *sg_scmd;
2820 	void *sg_local, *chain;
2821 	u32 chain_offset;
2822 	u32 chain_length;
2823 	int sges_left;
2824 	u32 sges_in_segment;
2825 	u8 simple_sgl_flags;
2826 	u8 simple_sgl_flags_last;
2827 	u8 chain_sgl_flags;
2828 	struct chain_tracker *chain_req;
2829 
2830 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
2831 
2832 	/* init scatter gather flags */
2833 	simple_sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2834 	    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2835 	simple_sgl_flags_last = simple_sgl_flags |
2836 	    MPI25_IEEE_SGE_FLAGS_END_OF_LIST;
2837 	chain_sgl_flags = MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
2838 	    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2839 
2840 	/* Check if we need to build a native SG list. */
2841 	if ((pcie_device) && (_base_check_pcie_native_sgl(ioc, mpi_request,
2842 			smid, scmd, pcie_device) == 0)) {
2843 		/* We built a native SG list, just return. */
2844 		return 0;
2845 	}
2846 
2847 	sg_scmd = scsi_sglist(scmd);
2848 	sges_left = scsi_dma_map(scmd);
2849 	if (sges_left < 0)
2850 		return -ENOMEM;
2851 
2852 	sg_local = &mpi_request->SGL;
2853 	sges_in_segment = (ioc->request_sz -
2854 		   offsetof(Mpi25SCSIIORequest_t, SGL))/ioc->sge_size_ieee;
2855 	if (sges_left <= sges_in_segment)
2856 		goto fill_in_last_segment;
2857 
2858 	mpi_request->ChainOffset = (sges_in_segment - 1 /* chain element */) +
2859 	    (offsetof(Mpi25SCSIIORequest_t, SGL)/ioc->sge_size_ieee);
2860 
2861 	/* fill in main message segment when there is a chain following */
2862 	while (sges_in_segment > 1) {
2863 		_base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
2864 		    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2865 		sg_scmd = sg_next(sg_scmd);
2866 		sg_local += ioc->sge_size_ieee;
2867 		sges_left--;
2868 		sges_in_segment--;
2869 	}
2870 
2871 	/* initializing the pointers */
2872 	chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2873 	if (!chain_req)
2874 		return -1;
2875 	chain = chain_req->chain_buffer;
2876 	chain_dma = chain_req->chain_buffer_dma;
2877 	do {
2878 		sges_in_segment = (sges_left <=
2879 		    ioc->max_sges_in_chain_message) ? sges_left :
2880 		    ioc->max_sges_in_chain_message;
2881 		chain_offset = (sges_left == sges_in_segment) ?
2882 		    0 : sges_in_segment;
2883 		chain_length = sges_in_segment * ioc->sge_size_ieee;
2884 		if (chain_offset)
2885 			chain_length += ioc->sge_size_ieee;
2886 		_base_add_sg_single_ieee(sg_local, chain_sgl_flags,
2887 		    chain_offset, chain_length, chain_dma);
2888 
2889 		sg_local = chain;
2890 		if (!chain_offset)
2891 			goto fill_in_last_segment;
2892 
2893 		/* fill in chain segments */
2894 		while (sges_in_segment) {
2895 			_base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
2896 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2897 			sg_scmd = sg_next(sg_scmd);
2898 			sg_local += ioc->sge_size_ieee;
2899 			sges_left--;
2900 			sges_in_segment--;
2901 		}
2902 
2903 		chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2904 		if (!chain_req)
2905 			return -1;
2906 		chain = chain_req->chain_buffer;
2907 		chain_dma = chain_req->chain_buffer_dma;
2908 	} while (1);
2909 
2910 
2911  fill_in_last_segment:
2912 
2913 	/* fill the last segment */
2914 	while (sges_left > 0) {
2915 		if (sges_left == 1)
2916 			_base_add_sg_single_ieee(sg_local,
2917 			    simple_sgl_flags_last, 0, sg_dma_len(sg_scmd),
2918 			    sg_dma_address(sg_scmd));
2919 		else
2920 			_base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
2921 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2922 		sg_scmd = sg_next(sg_scmd);
2923 		sg_local += ioc->sge_size_ieee;
2924 		sges_left--;
2925 	}
2926 
2927 	return 0;
2928 }
2929 
2930 /**
2931  * _base_build_sg_ieee - build generic sg for IEEE format
2932  * @ioc: per adapter object
2933  * @psge: virtual address for SGE
2934  * @data_out_dma: physical address for WRITES
2935  * @data_out_sz: data xfer size for WRITES
2936  * @data_in_dma: physical address for READS
2937  * @data_in_sz: data xfer size for READS
2938  */
2939 static void
2940 _base_build_sg_ieee(struct MPT3SAS_ADAPTER *ioc, void *psge,
2941 	dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
2942 	size_t data_in_sz)
2943 {
2944 	u8 sgl_flags;
2945 
2946 	if (!data_out_sz && !data_in_sz) {
2947 		_base_build_zero_len_sge_ieee(ioc, psge);
2948 		return;
2949 	}
2950 
2951 	if (data_out_sz && data_in_sz) {
2952 		/* WRITE sgel first */
2953 		sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2954 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2955 		_base_add_sg_single_ieee(psge, sgl_flags, 0, data_out_sz,
2956 		    data_out_dma);
2957 
2958 		/* incr sgel */
2959 		psge += ioc->sge_size_ieee;
2960 
2961 		/* READ sgel last */
2962 		sgl_flags |= MPI25_IEEE_SGE_FLAGS_END_OF_LIST;
2963 		_base_add_sg_single_ieee(psge, sgl_flags, 0, data_in_sz,
2964 		    data_in_dma);
2965 	} else if (data_out_sz) /* WRITE */ {
2966 		sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2967 		    MPI25_IEEE_SGE_FLAGS_END_OF_LIST |
2968 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2969 		_base_add_sg_single_ieee(psge, sgl_flags, 0, data_out_sz,
2970 		    data_out_dma);
2971 	} else if (data_in_sz) /* READ */ {
2972 		sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2973 		    MPI25_IEEE_SGE_FLAGS_END_OF_LIST |
2974 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2975 		_base_add_sg_single_ieee(psge, sgl_flags, 0, data_in_sz,
2976 		    data_in_dma);
2977 	}
2978 }
2979 
2980 #define convert_to_kb(x) ((x) << (PAGE_SHIFT - 10))
2981 
2982 /**
2983  * _base_config_dma_addressing - set dma addressing
2984  * @ioc: per adapter object
2985  * @pdev: PCI device struct
2986  *
2987  * Return: 0 for success, non-zero for failure.
2988  */
2989 static int
2990 _base_config_dma_addressing(struct MPT3SAS_ADAPTER *ioc, struct pci_dev *pdev)
2991 {
2992 	struct sysinfo s;
2993 	u64 coherent_dma_mask, dma_mask;
2994 
2995 	if (ioc->is_mcpu_endpoint || sizeof(dma_addr_t) == 4 ||
2996 	    dma_get_required_mask(&pdev->dev) <= DMA_BIT_MASK(32)) {
2997 		ioc->dma_mask = 32;
2998 		coherent_dma_mask = dma_mask = DMA_BIT_MASK(32);
2999 	/* Set 63 bit DMA mask for all SAS3 and SAS35 controllers */
3000 	} else if (ioc->hba_mpi_version_belonged > MPI2_VERSION) {
3001 		ioc->dma_mask = 63;
3002 		coherent_dma_mask = dma_mask = DMA_BIT_MASK(63);
3003 	} else {
3004 		ioc->dma_mask = 64;
3005 		coherent_dma_mask = dma_mask = DMA_BIT_MASK(64);
3006 	}
3007 
3008 	if (ioc->use_32bit_dma)
3009 		coherent_dma_mask = DMA_BIT_MASK(32);
3010 
3011 	if (dma_set_mask(&pdev->dev, dma_mask) ||
3012 	    dma_set_coherent_mask(&pdev->dev, coherent_dma_mask))
3013 		return -ENODEV;
3014 
3015 	if (ioc->dma_mask > 32) {
3016 		ioc->base_add_sg_single = &_base_add_sg_single_64;
3017 		ioc->sge_size = sizeof(Mpi2SGESimple64_t);
3018 	} else {
3019 		ioc->base_add_sg_single = &_base_add_sg_single_32;
3020 		ioc->sge_size = sizeof(Mpi2SGESimple32_t);
3021 	}
3022 
3023 	si_meminfo(&s);
3024 	ioc_info(ioc, "%d BIT PCI BUS DMA ADDRESSING SUPPORTED, total mem (%ld kB)\n",
3025 		ioc->dma_mask, convert_to_kb(s.totalram));
3026 
3027 	return 0;
3028 }
3029 
3030 /**
3031  * _base_check_enable_msix - checks MSIX capabable.
3032  * @ioc: per adapter object
3033  *
3034  * Check to see if card is capable of MSIX, and set number
3035  * of available msix vectors
3036  */
3037 static int
3038 _base_check_enable_msix(struct MPT3SAS_ADAPTER *ioc)
3039 {
3040 	int base;
3041 	u16 message_control;
3042 
3043 	/* Check whether controller SAS2008 B0 controller,
3044 	 * if it is SAS2008 B0 controller use IO-APIC instead of MSIX
3045 	 */
3046 	if (ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2008 &&
3047 	    ioc->pdev->revision == SAS2_PCI_DEVICE_B0_REVISION) {
3048 		return -EINVAL;
3049 	}
3050 
3051 	base = pci_find_capability(ioc->pdev, PCI_CAP_ID_MSIX);
3052 	if (!base) {
3053 		dfailprintk(ioc, ioc_info(ioc, "msix not supported\n"));
3054 		return -EINVAL;
3055 	}
3056 
3057 	/* get msix vector count */
3058 	/* NUMA_IO not supported for older controllers */
3059 	if (ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2004 ||
3060 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2008 ||
3061 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_1 ||
3062 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_2 ||
3063 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_3 ||
3064 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2116_1 ||
3065 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2116_2)
3066 		ioc->msix_vector_count = 1;
3067 	else {
3068 		pci_read_config_word(ioc->pdev, base + 2, &message_control);
3069 		ioc->msix_vector_count = (message_control & 0x3FF) + 1;
3070 	}
3071 	dinitprintk(ioc, ioc_info(ioc, "msix is supported, vector_count(%d)\n",
3072 				  ioc->msix_vector_count));
3073 	return 0;
3074 }
3075 
3076 /**
3077  * mpt3sas_base_free_irq - free irq
3078  * @ioc: per adapter object
3079  *
3080  * Freeing respective reply_queue from the list.
3081  */
3082 void
3083 mpt3sas_base_free_irq(struct MPT3SAS_ADAPTER *ioc)
3084 {
3085 	unsigned int irq;
3086 	struct adapter_reply_queue *reply_q, *next;
3087 
3088 	if (list_empty(&ioc->reply_queue_list))
3089 		return;
3090 
3091 	list_for_each_entry_safe(reply_q, next, &ioc->reply_queue_list, list) {
3092 		list_del(&reply_q->list);
3093 		if (reply_q->is_iouring_poll_q) {
3094 			kfree(reply_q);
3095 			continue;
3096 		}
3097 
3098 		if (ioc->smp_affinity_enable) {
3099 			irq = pci_irq_vector(ioc->pdev, reply_q->msix_index);
3100 			irq_update_affinity_hint(irq, NULL);
3101 		}
3102 		free_irq(pci_irq_vector(ioc->pdev, reply_q->msix_index),
3103 			 reply_q);
3104 		kfree(reply_q);
3105 	}
3106 }
3107 
3108 /**
3109  * _base_request_irq - request irq
3110  * @ioc: per adapter object
3111  * @index: msix index into vector table
3112  *
3113  * Inserting respective reply_queue into the list.
3114  */
3115 static int
3116 _base_request_irq(struct MPT3SAS_ADAPTER *ioc, u8 index)
3117 {
3118 	struct pci_dev *pdev = ioc->pdev;
3119 	struct adapter_reply_queue *reply_q;
3120 	int r, qid;
3121 
3122 	reply_q =  kzalloc(sizeof(struct adapter_reply_queue), GFP_KERNEL);
3123 	if (!reply_q) {
3124 		ioc_err(ioc, "unable to allocate memory %zu!\n",
3125 			sizeof(struct adapter_reply_queue));
3126 		return -ENOMEM;
3127 	}
3128 	reply_q->ioc = ioc;
3129 	reply_q->msix_index = index;
3130 
3131 	atomic_set(&reply_q->busy, 0);
3132 
3133 	if (index >= ioc->iopoll_q_start_index) {
3134 		qid = index - ioc->iopoll_q_start_index;
3135 		snprintf(reply_q->name, MPT_NAME_LENGTH, "%s%d-mq-poll%d",
3136 		    ioc->driver_name, ioc->id, qid);
3137 		reply_q->is_iouring_poll_q = 1;
3138 		ioc->io_uring_poll_queues[qid].reply_q = reply_q;
3139 		goto out;
3140 	}
3141 
3142 
3143 	if (ioc->msix_enable)
3144 		snprintf(reply_q->name, MPT_NAME_LENGTH, "%s%d-msix%d",
3145 		    ioc->driver_name, ioc->id, index);
3146 	else
3147 		snprintf(reply_q->name, MPT_NAME_LENGTH, "%s%d",
3148 		    ioc->driver_name, ioc->id);
3149 	r = request_irq(pci_irq_vector(pdev, index), _base_interrupt,
3150 			IRQF_SHARED, reply_q->name, reply_q);
3151 	if (r) {
3152 		pr_err("%s: unable to allocate interrupt %d!\n",
3153 		       reply_q->name, pci_irq_vector(pdev, index));
3154 		kfree(reply_q);
3155 		return -EBUSY;
3156 	}
3157 out:
3158 	INIT_LIST_HEAD(&reply_q->list);
3159 	list_add_tail(&reply_q->list, &ioc->reply_queue_list);
3160 	return 0;
3161 }
3162 
3163 /**
3164  * _base_assign_reply_queues - assigning msix index for each cpu
3165  * @ioc: per adapter object
3166  *
3167  * The enduser would need to set the affinity via /proc/irq/#/smp_affinity
3168  */
3169 static void
3170 _base_assign_reply_queues(struct MPT3SAS_ADAPTER *ioc)
3171 {
3172 	unsigned int cpu, nr_cpus, nr_msix, index = 0, irq;
3173 	struct adapter_reply_queue *reply_q;
3174 	int iopoll_q_count = ioc->reply_queue_count -
3175 	    ioc->iopoll_q_start_index;
3176 	const struct cpumask *mask;
3177 
3178 	if (!_base_is_controller_msix_enabled(ioc))
3179 		return;
3180 
3181 	if (ioc->msix_load_balance)
3182 		return;
3183 
3184 	memset(ioc->cpu_msix_table, 0, ioc->cpu_msix_table_sz);
3185 
3186 	nr_cpus = num_online_cpus();
3187 	nr_msix = ioc->reply_queue_count = min(ioc->reply_queue_count,
3188 					       ioc->facts.MaxMSIxVectors);
3189 	if (!nr_msix)
3190 		return;
3191 
3192 	if (ioc->smp_affinity_enable) {
3193 
3194 		/*
3195 		 * set irq affinity to local numa node for those irqs
3196 		 * corresponding to high iops queues.
3197 		 */
3198 		if (ioc->high_iops_queues) {
3199 			mask = cpumask_of_node(dev_to_node(&ioc->pdev->dev));
3200 			for (index = 0; index < ioc->high_iops_queues;
3201 			    index++) {
3202 				irq = pci_irq_vector(ioc->pdev, index);
3203 				irq_set_affinity_and_hint(irq, mask);
3204 			}
3205 		}
3206 
3207 		list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
3208 			const cpumask_t *mask;
3209 
3210 			if (reply_q->msix_index < ioc->high_iops_queues ||
3211 			    reply_q->msix_index >= ioc->iopoll_q_start_index)
3212 				continue;
3213 
3214 			mask = pci_irq_get_affinity(ioc->pdev,
3215 			    reply_q->msix_index);
3216 			if (!mask) {
3217 				ioc_warn(ioc, "no affinity for msi %x\n",
3218 					 reply_q->msix_index);
3219 				goto fall_back;
3220 			}
3221 
3222 			for_each_cpu_and(cpu, mask, cpu_online_mask) {
3223 				if (cpu >= ioc->cpu_msix_table_sz)
3224 					break;
3225 				ioc->cpu_msix_table[cpu] = reply_q->msix_index;
3226 			}
3227 		}
3228 		return;
3229 	}
3230 
3231 fall_back:
3232 	cpu = cpumask_first(cpu_online_mask);
3233 	nr_msix -= (ioc->high_iops_queues - iopoll_q_count);
3234 	index = 0;
3235 
3236 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
3237 		unsigned int i, group = nr_cpus / nr_msix;
3238 
3239 		if (reply_q->msix_index < ioc->high_iops_queues ||
3240 		    reply_q->msix_index >= ioc->iopoll_q_start_index)
3241 			continue;
3242 
3243 		if (cpu >= nr_cpus)
3244 			break;
3245 
3246 		if (index < nr_cpus % nr_msix)
3247 			group++;
3248 
3249 		for (i = 0 ; i < group ; i++) {
3250 			ioc->cpu_msix_table[cpu] = reply_q->msix_index;
3251 			cpu = cpumask_next(cpu, cpu_online_mask);
3252 		}
3253 		index++;
3254 	}
3255 }
3256 
3257 /**
3258  * _base_check_and_enable_high_iops_queues - enable high iops mode
3259  * @ioc: per adapter object
3260  * @hba_msix_vector_count: msix vectors supported by HBA
3261  *
3262  * Enable high iops queues only if
3263  *  - HBA is a SEA/AERO controller and
3264  *  - MSI-Xs vector supported by the HBA is 128 and
3265  *  - total CPU count in the system >=16 and
3266  *  - loaded driver with default max_msix_vectors module parameter and
3267  *  - system booted in non kdump mode
3268  *
3269  * Return: nothing.
3270  */
3271 static void
3272 _base_check_and_enable_high_iops_queues(struct MPT3SAS_ADAPTER *ioc,
3273 		int hba_msix_vector_count)
3274 {
3275 	u16 lnksta, speed;
3276 
3277 	/*
3278 	 * Disable high iops queues if io uring poll queues are enabled.
3279 	 */
3280 	if (perf_mode == MPT_PERF_MODE_IOPS ||
3281 	    perf_mode == MPT_PERF_MODE_LATENCY ||
3282 	    ioc->io_uring_poll_queues) {
3283 		ioc->high_iops_queues = 0;
3284 		return;
3285 	}
3286 
3287 	if (perf_mode == MPT_PERF_MODE_DEFAULT) {
3288 
3289 		pcie_capability_read_word(ioc->pdev, PCI_EXP_LNKSTA, &lnksta);
3290 		speed = lnksta & PCI_EXP_LNKSTA_CLS;
3291 
3292 		if (speed < 0x4) {
3293 			ioc->high_iops_queues = 0;
3294 			return;
3295 		}
3296 	}
3297 
3298 	if (!reset_devices && ioc->is_aero_ioc &&
3299 	    hba_msix_vector_count == MPT3SAS_GEN35_MAX_MSIX_QUEUES &&
3300 	    num_online_cpus() >= MPT3SAS_HIGH_IOPS_REPLY_QUEUES &&
3301 	    max_msix_vectors == -1)
3302 		ioc->high_iops_queues = MPT3SAS_HIGH_IOPS_REPLY_QUEUES;
3303 	else
3304 		ioc->high_iops_queues = 0;
3305 }
3306 
3307 /**
3308  * mpt3sas_base_disable_msix - disables msix
3309  * @ioc: per adapter object
3310  *
3311  */
3312 void
3313 mpt3sas_base_disable_msix(struct MPT3SAS_ADAPTER *ioc)
3314 {
3315 	if (!ioc->msix_enable)
3316 		return;
3317 	pci_free_irq_vectors(ioc->pdev);
3318 	ioc->msix_enable = 0;
3319 	kfree(ioc->io_uring_poll_queues);
3320 }
3321 
3322 /**
3323  * _base_alloc_irq_vectors - allocate msix vectors
3324  * @ioc: per adapter object
3325  *
3326  */
3327 static int
3328 _base_alloc_irq_vectors(struct MPT3SAS_ADAPTER *ioc)
3329 {
3330 	int i, irq_flags = PCI_IRQ_MSIX;
3331 	struct irq_affinity desc = { .pre_vectors = ioc->high_iops_queues };
3332 	struct irq_affinity *descp = &desc;
3333 	/*
3334 	 * Don't allocate msix vectors for poll_queues.
3335 	 * msix_vectors is always within a range of FW supported reply queue.
3336 	 */
3337 	int nr_msix_vectors = ioc->iopoll_q_start_index;
3338 
3339 
3340 	if (ioc->smp_affinity_enable)
3341 		irq_flags |= PCI_IRQ_AFFINITY | PCI_IRQ_ALL_TYPES;
3342 	else
3343 		descp = NULL;
3344 
3345 	ioc_info(ioc, " %d %d %d\n", ioc->high_iops_queues,
3346 	    ioc->reply_queue_count, nr_msix_vectors);
3347 
3348 	i = pci_alloc_irq_vectors_affinity(ioc->pdev,
3349 	    ioc->high_iops_queues,
3350 	    nr_msix_vectors, irq_flags, descp);
3351 
3352 	return i;
3353 }
3354 
3355 /**
3356  * _base_enable_msix - enables msix, failback to io_apic
3357  * @ioc: per adapter object
3358  *
3359  */
3360 static int
3361 _base_enable_msix(struct MPT3SAS_ADAPTER *ioc)
3362 {
3363 	int r;
3364 	int i, local_max_msix_vectors;
3365 	u8 try_msix = 0;
3366 	int iopoll_q_count = 0;
3367 
3368 	ioc->msix_load_balance = false;
3369 
3370 	if (msix_disable == -1 || msix_disable == 0)
3371 		try_msix = 1;
3372 
3373 	if (!try_msix)
3374 		goto try_ioapic;
3375 
3376 	if (_base_check_enable_msix(ioc) != 0)
3377 		goto try_ioapic;
3378 
3379 	ioc_info(ioc, "MSI-X vectors supported: %d\n", ioc->msix_vector_count);
3380 	pr_info("\t no of cores: %d, max_msix_vectors: %d\n",
3381 		ioc->cpu_count, max_msix_vectors);
3382 
3383 	ioc->reply_queue_count =
3384 		min_t(int, ioc->cpu_count, ioc->msix_vector_count);
3385 
3386 	if (!ioc->rdpq_array_enable && max_msix_vectors == -1)
3387 		local_max_msix_vectors = (reset_devices) ? 1 : 8;
3388 	else
3389 		local_max_msix_vectors = max_msix_vectors;
3390 
3391 	if (local_max_msix_vectors == 0)
3392 		goto try_ioapic;
3393 
3394 	/*
3395 	 * Enable msix_load_balance only if combined reply queue mode is
3396 	 * disabled on SAS3 & above generation HBA devices.
3397 	 */
3398 	if (!ioc->combined_reply_queue &&
3399 	    ioc->hba_mpi_version_belonged != MPI2_VERSION) {
3400 		ioc_info(ioc,
3401 		    "combined ReplyQueue is off, Enabling msix load balance\n");
3402 		ioc->msix_load_balance = true;
3403 	}
3404 
3405 	/*
3406 	 * smp affinity setting is not need when msix load balance
3407 	 * is enabled.
3408 	 */
3409 	if (ioc->msix_load_balance)
3410 		ioc->smp_affinity_enable = 0;
3411 
3412 	if (!ioc->smp_affinity_enable || ioc->reply_queue_count <= 1)
3413 		ioc->shost->host_tagset = 0;
3414 
3415 	/*
3416 	 * Enable io uring poll queues only if host_tagset is enabled.
3417 	 */
3418 	if (ioc->shost->host_tagset)
3419 		iopoll_q_count = poll_queues;
3420 
3421 	if (iopoll_q_count) {
3422 		ioc->io_uring_poll_queues = kcalloc(iopoll_q_count,
3423 		    sizeof(struct io_uring_poll_queue), GFP_KERNEL);
3424 		if (!ioc->io_uring_poll_queues)
3425 			iopoll_q_count = 0;
3426 	}
3427 
3428 	if (ioc->is_aero_ioc)
3429 		_base_check_and_enable_high_iops_queues(ioc,
3430 		    ioc->msix_vector_count);
3431 
3432 	/*
3433 	 * Add high iops queues count to reply queue count if high iops queues
3434 	 * are enabled.
3435 	 */
3436 	ioc->reply_queue_count = min_t(int,
3437 	    ioc->reply_queue_count + ioc->high_iops_queues,
3438 	    ioc->msix_vector_count);
3439 
3440 	/*
3441 	 * Adjust the reply queue count incase reply queue count
3442 	 * exceeds the user provided MSIx vectors count.
3443 	 */
3444 	if (local_max_msix_vectors > 0)
3445 		ioc->reply_queue_count = min_t(int, local_max_msix_vectors,
3446 		    ioc->reply_queue_count);
3447 	/*
3448 	 * Add io uring poll queues count to reply queues count
3449 	 * if io uring is enabled in driver.
3450 	 */
3451 	if (iopoll_q_count) {
3452 		if (ioc->reply_queue_count < (iopoll_q_count + MPT3_MIN_IRQS))
3453 			iopoll_q_count = 0;
3454 		ioc->reply_queue_count = min_t(int,
3455 		    ioc->reply_queue_count + iopoll_q_count,
3456 		    ioc->msix_vector_count);
3457 	}
3458 
3459 	/*
3460 	 * Starting index of io uring poll queues in reply queue list.
3461 	 */
3462 	ioc->iopoll_q_start_index =
3463 	    ioc->reply_queue_count - iopoll_q_count;
3464 
3465 	r = _base_alloc_irq_vectors(ioc);
3466 	if (r < 0) {
3467 		ioc_info(ioc, "pci_alloc_irq_vectors failed (r=%d) !!!\n", r);
3468 		goto try_ioapic;
3469 	}
3470 
3471 	/*
3472 	 * Adjust the reply queue count if the allocated
3473 	 * MSIx vectors is less then the requested number
3474 	 * of MSIx vectors.
3475 	 */
3476 	if (r < ioc->iopoll_q_start_index) {
3477 		ioc->reply_queue_count = r + iopoll_q_count;
3478 		ioc->iopoll_q_start_index =
3479 		    ioc->reply_queue_count - iopoll_q_count;
3480 	}
3481 
3482 	ioc->msix_enable = 1;
3483 	for (i = 0; i < ioc->reply_queue_count; i++) {
3484 		r = _base_request_irq(ioc, i);
3485 		if (r) {
3486 			mpt3sas_base_free_irq(ioc);
3487 			mpt3sas_base_disable_msix(ioc);
3488 			goto try_ioapic;
3489 		}
3490 	}
3491 
3492 	ioc_info(ioc, "High IOPs queues : %s\n",
3493 			ioc->high_iops_queues ? "enabled" : "disabled");
3494 
3495 	return 0;
3496 
3497 /* failback to io_apic interrupt routing */
3498  try_ioapic:
3499 	ioc->high_iops_queues = 0;
3500 	ioc_info(ioc, "High IOPs queues : disabled\n");
3501 	ioc->reply_queue_count = 1;
3502 	ioc->iopoll_q_start_index = ioc->reply_queue_count - 0;
3503 	r = pci_alloc_irq_vectors(ioc->pdev, 1, 1, PCI_IRQ_LEGACY);
3504 	if (r < 0) {
3505 		dfailprintk(ioc,
3506 			    ioc_info(ioc, "pci_alloc_irq_vector(legacy) failed (r=%d) !!!\n",
3507 				     r));
3508 	} else
3509 		r = _base_request_irq(ioc, 0);
3510 
3511 	return r;
3512 }
3513 
3514 /**
3515  * mpt3sas_base_unmap_resources - free controller resources
3516  * @ioc: per adapter object
3517  */
3518 static void
3519 mpt3sas_base_unmap_resources(struct MPT3SAS_ADAPTER *ioc)
3520 {
3521 	struct pci_dev *pdev = ioc->pdev;
3522 
3523 	dexitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
3524 
3525 	mpt3sas_base_free_irq(ioc);
3526 	mpt3sas_base_disable_msix(ioc);
3527 
3528 	kfree(ioc->replyPostRegisterIndex);
3529 	ioc->replyPostRegisterIndex = NULL;
3530 
3531 
3532 	if (ioc->chip_phys) {
3533 		iounmap(ioc->chip);
3534 		ioc->chip_phys = 0;
3535 	}
3536 
3537 	if (pci_is_enabled(pdev)) {
3538 		pci_release_selected_regions(ioc->pdev, ioc->bars);
3539 		pci_disable_pcie_error_reporting(pdev);
3540 		pci_disable_device(pdev);
3541 	}
3542 }
3543 
3544 static int
3545 _base_diag_reset(struct MPT3SAS_ADAPTER *ioc);
3546 
3547 /**
3548  * mpt3sas_base_check_for_fault_and_issue_reset - check if IOC is in fault state
3549  *     and if it is in fault state then issue diag reset.
3550  * @ioc: per adapter object
3551  *
3552  * Return: 0 for success, non-zero for failure.
3553  */
3554 int
3555 mpt3sas_base_check_for_fault_and_issue_reset(struct MPT3SAS_ADAPTER *ioc)
3556 {
3557 	u32 ioc_state;
3558 	int rc = -EFAULT;
3559 
3560 	dinitprintk(ioc, pr_info("%s\n", __func__));
3561 	if (ioc->pci_error_recovery)
3562 		return 0;
3563 	ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
3564 	dhsprintk(ioc, pr_info("%s: ioc_state(0x%08x)\n", __func__, ioc_state));
3565 
3566 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
3567 		mpt3sas_print_fault_code(ioc, ioc_state &
3568 		    MPI2_DOORBELL_DATA_MASK);
3569 		mpt3sas_base_mask_interrupts(ioc);
3570 		rc = _base_diag_reset(ioc);
3571 	} else if ((ioc_state & MPI2_IOC_STATE_MASK) ==
3572 	    MPI2_IOC_STATE_COREDUMP) {
3573 		mpt3sas_print_coredump_info(ioc, ioc_state &
3574 		     MPI2_DOORBELL_DATA_MASK);
3575 		mpt3sas_base_wait_for_coredump_completion(ioc, __func__);
3576 		mpt3sas_base_mask_interrupts(ioc);
3577 		rc = _base_diag_reset(ioc);
3578 	}
3579 
3580 	return rc;
3581 }
3582 
3583 /**
3584  * mpt3sas_base_map_resources - map in controller resources (io/irq/memap)
3585  * @ioc: per adapter object
3586  *
3587  * Return: 0 for success, non-zero for failure.
3588  */
3589 int
3590 mpt3sas_base_map_resources(struct MPT3SAS_ADAPTER *ioc)
3591 {
3592 	struct pci_dev *pdev = ioc->pdev;
3593 	u32 memap_sz;
3594 	u32 pio_sz;
3595 	int i, r = 0, rc;
3596 	u64 pio_chip = 0;
3597 	phys_addr_t chip_phys = 0;
3598 	struct adapter_reply_queue *reply_q;
3599 	int iopoll_q_count = 0;
3600 
3601 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
3602 
3603 	ioc->bars = pci_select_bars(pdev, IORESOURCE_MEM);
3604 	if (pci_enable_device_mem(pdev)) {
3605 		ioc_warn(ioc, "pci_enable_device_mem: failed\n");
3606 		ioc->bars = 0;
3607 		return -ENODEV;
3608 	}
3609 
3610 
3611 	if (pci_request_selected_regions(pdev, ioc->bars,
3612 	    ioc->driver_name)) {
3613 		ioc_warn(ioc, "pci_request_selected_regions: failed\n");
3614 		ioc->bars = 0;
3615 		r = -ENODEV;
3616 		goto out_fail;
3617 	}
3618 
3619 /* AER (Advanced Error Reporting) hooks */
3620 	pci_enable_pcie_error_reporting(pdev);
3621 
3622 	pci_set_master(pdev);
3623 
3624 
3625 	if (_base_config_dma_addressing(ioc, pdev) != 0) {
3626 		ioc_warn(ioc, "no suitable DMA mask for %s\n", pci_name(pdev));
3627 		r = -ENODEV;
3628 		goto out_fail;
3629 	}
3630 
3631 	for (i = 0, memap_sz = 0, pio_sz = 0; (i < DEVICE_COUNT_RESOURCE) &&
3632 	     (!memap_sz || !pio_sz); i++) {
3633 		if (pci_resource_flags(pdev, i) & IORESOURCE_IO) {
3634 			if (pio_sz)
3635 				continue;
3636 			pio_chip = (u64)pci_resource_start(pdev, i);
3637 			pio_sz = pci_resource_len(pdev, i);
3638 		} else if (pci_resource_flags(pdev, i) & IORESOURCE_MEM) {
3639 			if (memap_sz)
3640 				continue;
3641 			ioc->chip_phys = pci_resource_start(pdev, i);
3642 			chip_phys = ioc->chip_phys;
3643 			memap_sz = pci_resource_len(pdev, i);
3644 			ioc->chip = ioremap(ioc->chip_phys, memap_sz);
3645 		}
3646 	}
3647 
3648 	if (ioc->chip == NULL) {
3649 		ioc_err(ioc,
3650 		    "unable to map adapter memory! or resource not found\n");
3651 		r = -EINVAL;
3652 		goto out_fail;
3653 	}
3654 
3655 	mpt3sas_base_mask_interrupts(ioc);
3656 
3657 	r = _base_get_ioc_facts(ioc);
3658 	if (r) {
3659 		rc = mpt3sas_base_check_for_fault_and_issue_reset(ioc);
3660 		if (rc || (_base_get_ioc_facts(ioc)))
3661 			goto out_fail;
3662 	}
3663 
3664 	if (!ioc->rdpq_array_enable_assigned) {
3665 		ioc->rdpq_array_enable = ioc->rdpq_array_capable;
3666 		ioc->rdpq_array_enable_assigned = 1;
3667 	}
3668 
3669 	r = _base_enable_msix(ioc);
3670 	if (r)
3671 		goto out_fail;
3672 
3673 	iopoll_q_count = ioc->reply_queue_count - ioc->iopoll_q_start_index;
3674 	for (i = 0; i < iopoll_q_count; i++) {
3675 		atomic_set(&ioc->io_uring_poll_queues[i].busy, 0);
3676 		atomic_set(&ioc->io_uring_poll_queues[i].pause, 0);
3677 	}
3678 
3679 	if (!ioc->is_driver_loading)
3680 		_base_init_irqpolls(ioc);
3681 	/* Use the Combined reply queue feature only for SAS3 C0 & higher
3682 	 * revision HBAs and also only when reply queue count is greater than 8
3683 	 */
3684 	if (ioc->combined_reply_queue) {
3685 		/* Determine the Supplemental Reply Post Host Index Registers
3686 		 * Addresse. Supplemental Reply Post Host Index Registers
3687 		 * starts at offset MPI25_SUP_REPLY_POST_HOST_INDEX_OFFSET and
3688 		 * each register is at offset bytes of
3689 		 * MPT3_SUP_REPLY_POST_HOST_INDEX_REG_OFFSET from previous one.
3690 		 */
3691 		ioc->replyPostRegisterIndex = kcalloc(
3692 		     ioc->combined_reply_index_count,
3693 		     sizeof(resource_size_t *), GFP_KERNEL);
3694 		if (!ioc->replyPostRegisterIndex) {
3695 			ioc_err(ioc,
3696 			    "allocation for replyPostRegisterIndex failed!\n");
3697 			r = -ENOMEM;
3698 			goto out_fail;
3699 		}
3700 
3701 		for (i = 0; i < ioc->combined_reply_index_count; i++) {
3702 			ioc->replyPostRegisterIndex[i] =
3703 				(resource_size_t __iomem *)
3704 				((u8 __force *)&ioc->chip->Doorbell +
3705 				 MPI25_SUP_REPLY_POST_HOST_INDEX_OFFSET +
3706 				 (i * MPT3_SUP_REPLY_POST_HOST_INDEX_REG_OFFSET));
3707 		}
3708 	}
3709 
3710 	if (ioc->is_warpdrive) {
3711 		ioc->reply_post_host_index[0] = (resource_size_t __iomem *)
3712 		    &ioc->chip->ReplyPostHostIndex;
3713 
3714 		for (i = 1; i < ioc->cpu_msix_table_sz; i++)
3715 			ioc->reply_post_host_index[i] =
3716 			(resource_size_t __iomem *)
3717 			((u8 __iomem *)&ioc->chip->Doorbell + (0x4000 + ((i - 1)
3718 			* 4)));
3719 	}
3720 
3721 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
3722 		if (reply_q->msix_index >= ioc->iopoll_q_start_index) {
3723 			pr_info("%s: enabled: index: %d\n",
3724 			    reply_q->name, reply_q->msix_index);
3725 			continue;
3726 		}
3727 
3728 		pr_info("%s: %s enabled: IRQ %d\n",
3729 			reply_q->name,
3730 			ioc->msix_enable ? "PCI-MSI-X" : "IO-APIC",
3731 			pci_irq_vector(ioc->pdev, reply_q->msix_index));
3732 	}
3733 
3734 	ioc_info(ioc, "iomem(%pap), mapped(0x%p), size(%d)\n",
3735 		 &chip_phys, ioc->chip, memap_sz);
3736 	ioc_info(ioc, "ioport(0x%016llx), size(%d)\n",
3737 		 (unsigned long long)pio_chip, pio_sz);
3738 
3739 	/* Save PCI configuration state for recovery from PCI AER/EEH errors */
3740 	pci_save_state(pdev);
3741 	return 0;
3742 
3743  out_fail:
3744 	mpt3sas_base_unmap_resources(ioc);
3745 	return r;
3746 }
3747 
3748 /**
3749  * mpt3sas_base_get_msg_frame - obtain request mf pointer
3750  * @ioc: per adapter object
3751  * @smid: system request message index(smid zero is invalid)
3752  *
3753  * Return: virt pointer to message frame.
3754  */
3755 void *
3756 mpt3sas_base_get_msg_frame(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3757 {
3758 	return (void *)(ioc->request + (smid * ioc->request_sz));
3759 }
3760 
3761 /**
3762  * mpt3sas_base_get_sense_buffer - obtain a sense buffer virt addr
3763  * @ioc: per adapter object
3764  * @smid: system request message index
3765  *
3766  * Return: virt pointer to sense buffer.
3767  */
3768 void *
3769 mpt3sas_base_get_sense_buffer(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3770 {
3771 	return (void *)(ioc->sense + ((smid - 1) * SCSI_SENSE_BUFFERSIZE));
3772 }
3773 
3774 /**
3775  * mpt3sas_base_get_sense_buffer_dma - obtain a sense buffer dma addr
3776  * @ioc: per adapter object
3777  * @smid: system request message index
3778  *
3779  * Return: phys pointer to the low 32bit address of the sense buffer.
3780  */
3781 __le32
3782 mpt3sas_base_get_sense_buffer_dma(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3783 {
3784 	return cpu_to_le32(ioc->sense_dma + ((smid - 1) *
3785 	    SCSI_SENSE_BUFFERSIZE));
3786 }
3787 
3788 /**
3789  * mpt3sas_base_get_pcie_sgl - obtain a PCIe SGL virt addr
3790  * @ioc: per adapter object
3791  * @smid: system request message index
3792  *
3793  * Return: virt pointer to a PCIe SGL.
3794  */
3795 void *
3796 mpt3sas_base_get_pcie_sgl(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3797 {
3798 	return (void *)(ioc->pcie_sg_lookup[smid - 1].pcie_sgl);
3799 }
3800 
3801 /**
3802  * mpt3sas_base_get_pcie_sgl_dma - obtain a PCIe SGL dma addr
3803  * @ioc: per adapter object
3804  * @smid: system request message index
3805  *
3806  * Return: phys pointer to the address of the PCIe buffer.
3807  */
3808 dma_addr_t
3809 mpt3sas_base_get_pcie_sgl_dma(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3810 {
3811 	return ioc->pcie_sg_lookup[smid - 1].pcie_sgl_dma;
3812 }
3813 
3814 /**
3815  * mpt3sas_base_get_reply_virt_addr - obtain reply frames virt address
3816  * @ioc: per adapter object
3817  * @phys_addr: lower 32 physical addr of the reply
3818  *
3819  * Converts 32bit lower physical addr into a virt address.
3820  */
3821 void *
3822 mpt3sas_base_get_reply_virt_addr(struct MPT3SAS_ADAPTER *ioc, u32 phys_addr)
3823 {
3824 	if (!phys_addr)
3825 		return NULL;
3826 	return ioc->reply + (phys_addr - (u32)ioc->reply_dma);
3827 }
3828 
3829 /**
3830  * _base_get_msix_index - get the msix index
3831  * @ioc: per adapter object
3832  * @scmd: scsi_cmnd object
3833  *
3834  * Return: msix index of general reply queues,
3835  * i.e. reply queue on which IO request's reply
3836  * should be posted by the HBA firmware.
3837  */
3838 static inline u8
3839 _base_get_msix_index(struct MPT3SAS_ADAPTER *ioc,
3840 	struct scsi_cmnd *scmd)
3841 {
3842 	/* Enables reply_queue load balancing */
3843 	if (ioc->msix_load_balance)
3844 		return ioc->reply_queue_count ?
3845 		    base_mod64(atomic64_add_return(1,
3846 		    &ioc->total_io_cnt), ioc->reply_queue_count) : 0;
3847 
3848 	if (scmd && ioc->shost->nr_hw_queues > 1) {
3849 		u32 tag = blk_mq_unique_tag(scsi_cmd_to_rq(scmd));
3850 
3851 		return blk_mq_unique_tag_to_hwq(tag) +
3852 			ioc->high_iops_queues;
3853 	}
3854 
3855 	return ioc->cpu_msix_table[raw_smp_processor_id()];
3856 }
3857 
3858 /**
3859  * _base_get_high_iops_msix_index - get the msix index of
3860  *				high iops queues
3861  * @ioc: per adapter object
3862  * @scmd: scsi_cmnd object
3863  *
3864  * Return: msix index of high iops reply queues.
3865  * i.e. high iops reply queue on which IO request's
3866  * reply should be posted by the HBA firmware.
3867  */
3868 static inline u8
3869 _base_get_high_iops_msix_index(struct MPT3SAS_ADAPTER *ioc,
3870 	struct scsi_cmnd *scmd)
3871 {
3872 	/**
3873 	 * Round robin the IO interrupts among the high iops
3874 	 * reply queues in terms of batch count 16 when outstanding
3875 	 * IOs on the target device is >=8.
3876 	 */
3877 
3878 	if (scsi_device_busy(scmd->device) > MPT3SAS_DEVICE_HIGH_IOPS_DEPTH)
3879 		return base_mod64((
3880 		    atomic64_add_return(1, &ioc->high_iops_outstanding) /
3881 		    MPT3SAS_HIGH_IOPS_BATCH_COUNT),
3882 		    MPT3SAS_HIGH_IOPS_REPLY_QUEUES);
3883 
3884 	return _base_get_msix_index(ioc, scmd);
3885 }
3886 
3887 /**
3888  * mpt3sas_base_get_smid - obtain a free smid from internal queue
3889  * @ioc: per adapter object
3890  * @cb_idx: callback index
3891  *
3892  * Return: smid (zero is invalid)
3893  */
3894 u16
3895 mpt3sas_base_get_smid(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx)
3896 {
3897 	unsigned long flags;
3898 	struct request_tracker *request;
3899 	u16 smid;
3900 
3901 	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3902 	if (list_empty(&ioc->internal_free_list)) {
3903 		spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3904 		ioc_err(ioc, "%s: smid not available\n", __func__);
3905 		return 0;
3906 	}
3907 
3908 	request = list_entry(ioc->internal_free_list.next,
3909 	    struct request_tracker, tracker_list);
3910 	request->cb_idx = cb_idx;
3911 	smid = request->smid;
3912 	list_del(&request->tracker_list);
3913 	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3914 	return smid;
3915 }
3916 
3917 /**
3918  * mpt3sas_base_get_smid_scsiio - obtain a free smid from scsiio queue
3919  * @ioc: per adapter object
3920  * @cb_idx: callback index
3921  * @scmd: pointer to scsi command object
3922  *
3923  * Return: smid (zero is invalid)
3924  */
3925 u16
3926 mpt3sas_base_get_smid_scsiio(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx,
3927 	struct scsi_cmnd *scmd)
3928 {
3929 	struct scsiio_tracker *request = scsi_cmd_priv(scmd);
3930 	u16 smid;
3931 	u32 tag, unique_tag;
3932 
3933 	unique_tag = blk_mq_unique_tag(scsi_cmd_to_rq(scmd));
3934 	tag = blk_mq_unique_tag_to_tag(unique_tag);
3935 
3936 	/*
3937 	 * Store hw queue number corresponding to the tag.
3938 	 * This hw queue number is used later to determine
3939 	 * the unique_tag using the logic below. This unique_tag
3940 	 * is used to retrieve the scmd pointer corresponding
3941 	 * to tag using scsi_host_find_tag() API.
3942 	 *
3943 	 * tag = smid - 1;
3944 	 * unique_tag = ioc->io_queue_num[tag] << BLK_MQ_UNIQUE_TAG_BITS | tag;
3945 	 */
3946 	ioc->io_queue_num[tag] = blk_mq_unique_tag_to_hwq(unique_tag);
3947 
3948 	smid = tag + 1;
3949 	request->cb_idx = cb_idx;
3950 	request->smid = smid;
3951 	request->scmd = scmd;
3952 	INIT_LIST_HEAD(&request->chain_list);
3953 	return smid;
3954 }
3955 
3956 /**
3957  * mpt3sas_base_get_smid_hpr - obtain a free smid from hi-priority queue
3958  * @ioc: per adapter object
3959  * @cb_idx: callback index
3960  *
3961  * Return: smid (zero is invalid)
3962  */
3963 u16
3964 mpt3sas_base_get_smid_hpr(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx)
3965 {
3966 	unsigned long flags;
3967 	struct request_tracker *request;
3968 	u16 smid;
3969 
3970 	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3971 	if (list_empty(&ioc->hpr_free_list)) {
3972 		spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3973 		return 0;
3974 	}
3975 
3976 	request = list_entry(ioc->hpr_free_list.next,
3977 	    struct request_tracker, tracker_list);
3978 	request->cb_idx = cb_idx;
3979 	smid = request->smid;
3980 	list_del(&request->tracker_list);
3981 	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3982 	return smid;
3983 }
3984 
3985 static void
3986 _base_recovery_check(struct MPT3SAS_ADAPTER *ioc)
3987 {
3988 	/*
3989 	 * See _wait_for_commands_to_complete() call with regards to this code.
3990 	 */
3991 	if (ioc->shost_recovery && ioc->pending_io_count) {
3992 		ioc->pending_io_count = scsi_host_busy(ioc->shost);
3993 		if (ioc->pending_io_count == 0)
3994 			wake_up(&ioc->reset_wq);
3995 	}
3996 }
3997 
3998 void mpt3sas_base_clear_st(struct MPT3SAS_ADAPTER *ioc,
3999 			   struct scsiio_tracker *st)
4000 {
4001 	if (WARN_ON(st->smid == 0))
4002 		return;
4003 	st->cb_idx = 0xFF;
4004 	st->direct_io = 0;
4005 	st->scmd = NULL;
4006 	atomic_set(&ioc->chain_lookup[st->smid - 1].chain_offset, 0);
4007 	st->smid = 0;
4008 }
4009 
4010 /**
4011  * mpt3sas_base_free_smid - put smid back on free_list
4012  * @ioc: per adapter object
4013  * @smid: system request message index
4014  */
4015 void
4016 mpt3sas_base_free_smid(struct MPT3SAS_ADAPTER *ioc, u16 smid)
4017 {
4018 	unsigned long flags;
4019 	int i;
4020 
4021 	if (smid < ioc->hi_priority_smid) {
4022 		struct scsiio_tracker *st;
4023 		void *request;
4024 
4025 		st = _get_st_from_smid(ioc, smid);
4026 		if (!st) {
4027 			_base_recovery_check(ioc);
4028 			return;
4029 		}
4030 
4031 		/* Clear MPI request frame */
4032 		request = mpt3sas_base_get_msg_frame(ioc, smid);
4033 		memset(request, 0, ioc->request_sz);
4034 
4035 		mpt3sas_base_clear_st(ioc, st);
4036 		_base_recovery_check(ioc);
4037 		ioc->io_queue_num[smid - 1] = 0;
4038 		return;
4039 	}
4040 
4041 	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
4042 	if (smid < ioc->internal_smid) {
4043 		/* hi-priority */
4044 		i = smid - ioc->hi_priority_smid;
4045 		ioc->hpr_lookup[i].cb_idx = 0xFF;
4046 		list_add(&ioc->hpr_lookup[i].tracker_list, &ioc->hpr_free_list);
4047 	} else if (smid <= ioc->hba_queue_depth) {
4048 		/* internal queue */
4049 		i = smid - ioc->internal_smid;
4050 		ioc->internal_lookup[i].cb_idx = 0xFF;
4051 		list_add(&ioc->internal_lookup[i].tracker_list,
4052 		    &ioc->internal_free_list);
4053 	}
4054 	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
4055 }
4056 
4057 /**
4058  * _base_mpi_ep_writeq - 32 bit write to MMIO
4059  * @b: data payload
4060  * @addr: address in MMIO space
4061  * @writeq_lock: spin lock
4062  *
4063  * This special handling for MPI EP to take care of 32 bit
4064  * environment where its not quarenteed to send the entire word
4065  * in one transfer.
4066  */
4067 static inline void
4068 _base_mpi_ep_writeq(__u64 b, volatile void __iomem *addr,
4069 					spinlock_t *writeq_lock)
4070 {
4071 	unsigned long flags;
4072 
4073 	spin_lock_irqsave(writeq_lock, flags);
4074 	__raw_writel((u32)(b), addr);
4075 	__raw_writel((u32)(b >> 32), (addr + 4));
4076 	spin_unlock_irqrestore(writeq_lock, flags);
4077 }
4078 
4079 /**
4080  * _base_writeq - 64 bit write to MMIO
4081  * @b: data payload
4082  * @addr: address in MMIO space
4083  * @writeq_lock: spin lock
4084  *
4085  * Glue for handling an atomic 64 bit word to MMIO. This special handling takes
4086  * care of 32 bit environment where its not quarenteed to send the entire word
4087  * in one transfer.
4088  */
4089 #if defined(writeq) && defined(CONFIG_64BIT)
4090 static inline void
4091 _base_writeq(__u64 b, volatile void __iomem *addr, spinlock_t *writeq_lock)
4092 {
4093 	wmb();
4094 	__raw_writeq(b, addr);
4095 	barrier();
4096 }
4097 #else
4098 static inline void
4099 _base_writeq(__u64 b, volatile void __iomem *addr, spinlock_t *writeq_lock)
4100 {
4101 	_base_mpi_ep_writeq(b, addr, writeq_lock);
4102 }
4103 #endif
4104 
4105 /**
4106  * _base_set_and_get_msix_index - get the msix index and assign to msix_io
4107  *                                variable of scsi tracker
4108  * @ioc: per adapter object
4109  * @smid: system request message index
4110  *
4111  * Return: msix index.
4112  */
4113 static u8
4114 _base_set_and_get_msix_index(struct MPT3SAS_ADAPTER *ioc, u16 smid)
4115 {
4116 	struct scsiio_tracker *st = NULL;
4117 
4118 	if (smid < ioc->hi_priority_smid)
4119 		st = _get_st_from_smid(ioc, smid);
4120 
4121 	if (st == NULL)
4122 		return  _base_get_msix_index(ioc, NULL);
4123 
4124 	st->msix_io = ioc->get_msix_index_for_smlio(ioc, st->scmd);
4125 	return st->msix_io;
4126 }
4127 
4128 /**
4129  * _base_put_smid_mpi_ep_scsi_io - send SCSI_IO request to firmware
4130  * @ioc: per adapter object
4131  * @smid: system request message index
4132  * @handle: device handle
4133  */
4134 static void
4135 _base_put_smid_mpi_ep_scsi_io(struct MPT3SAS_ADAPTER *ioc,
4136 	u16 smid, u16 handle)
4137 {
4138 	Mpi2RequestDescriptorUnion_t descriptor;
4139 	u64 *request = (u64 *)&descriptor;
4140 	void *mpi_req_iomem;
4141 	__le32 *mfp = (__le32 *)mpt3sas_base_get_msg_frame(ioc, smid);
4142 
4143 	_clone_sg_entries(ioc, (void *) mfp, smid);
4144 	mpi_req_iomem = (void __force *)ioc->chip +
4145 			MPI_FRAME_START_OFFSET + (smid * ioc->request_sz);
4146 	_base_clone_mpi_to_sys_mem(mpi_req_iomem, (void *)mfp,
4147 					ioc->request_sz);
4148 	descriptor.SCSIIO.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
4149 	descriptor.SCSIIO.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
4150 	descriptor.SCSIIO.SMID = cpu_to_le16(smid);
4151 	descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
4152 	descriptor.SCSIIO.LMID = 0;
4153 	_base_mpi_ep_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
4154 	    &ioc->scsi_lookup_lock);
4155 }
4156 
4157 /**
4158  * _base_put_smid_scsi_io - send SCSI_IO request to firmware
4159  * @ioc: per adapter object
4160  * @smid: system request message index
4161  * @handle: device handle
4162  */
4163 static void
4164 _base_put_smid_scsi_io(struct MPT3SAS_ADAPTER *ioc, u16 smid, u16 handle)
4165 {
4166 	Mpi2RequestDescriptorUnion_t descriptor;
4167 	u64 *request = (u64 *)&descriptor;
4168 
4169 
4170 	descriptor.SCSIIO.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
4171 	descriptor.SCSIIO.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
4172 	descriptor.SCSIIO.SMID = cpu_to_le16(smid);
4173 	descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
4174 	descriptor.SCSIIO.LMID = 0;
4175 	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
4176 	    &ioc->scsi_lookup_lock);
4177 }
4178 
4179 /**
4180  * _base_put_smid_fast_path - send fast path request to firmware
4181  * @ioc: per adapter object
4182  * @smid: system request message index
4183  * @handle: device handle
4184  */
4185 static void
4186 _base_put_smid_fast_path(struct MPT3SAS_ADAPTER *ioc, u16 smid,
4187 	u16 handle)
4188 {
4189 	Mpi2RequestDescriptorUnion_t descriptor;
4190 	u64 *request = (u64 *)&descriptor;
4191 
4192 	descriptor.SCSIIO.RequestFlags =
4193 	    MPI25_REQ_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO;
4194 	descriptor.SCSIIO.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
4195 	descriptor.SCSIIO.SMID = cpu_to_le16(smid);
4196 	descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
4197 	descriptor.SCSIIO.LMID = 0;
4198 	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
4199 	    &ioc->scsi_lookup_lock);
4200 }
4201 
4202 /**
4203  * _base_put_smid_hi_priority - send Task Management request to firmware
4204  * @ioc: per adapter object
4205  * @smid: system request message index
4206  * @msix_task: msix_task will be same as msix of IO in case of task abort else 0
4207  */
4208 static void
4209 _base_put_smid_hi_priority(struct MPT3SAS_ADAPTER *ioc, u16 smid,
4210 	u16 msix_task)
4211 {
4212 	Mpi2RequestDescriptorUnion_t descriptor;
4213 	void *mpi_req_iomem;
4214 	u64 *request;
4215 
4216 	if (ioc->is_mcpu_endpoint) {
4217 		__le32 *mfp = (__le32 *)mpt3sas_base_get_msg_frame(ioc, smid);
4218 
4219 		/* TBD 256 is offset within sys register. */
4220 		mpi_req_iomem = (void __force *)ioc->chip
4221 					+ MPI_FRAME_START_OFFSET
4222 					+ (smid * ioc->request_sz);
4223 		_base_clone_mpi_to_sys_mem(mpi_req_iomem, (void *)mfp,
4224 							ioc->request_sz);
4225 	}
4226 
4227 	request = (u64 *)&descriptor;
4228 
4229 	descriptor.HighPriority.RequestFlags =
4230 	    MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY;
4231 	descriptor.HighPriority.MSIxIndex =  msix_task;
4232 	descriptor.HighPriority.SMID = cpu_to_le16(smid);
4233 	descriptor.HighPriority.LMID = 0;
4234 	descriptor.HighPriority.Reserved1 = 0;
4235 	if (ioc->is_mcpu_endpoint)
4236 		_base_mpi_ep_writeq(*request,
4237 				&ioc->chip->RequestDescriptorPostLow,
4238 				&ioc->scsi_lookup_lock);
4239 	else
4240 		_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
4241 		    &ioc->scsi_lookup_lock);
4242 }
4243 
4244 /**
4245  * mpt3sas_base_put_smid_nvme_encap - send NVMe encapsulated request to
4246  *  firmware
4247  * @ioc: per adapter object
4248  * @smid: system request message index
4249  */
4250 void
4251 mpt3sas_base_put_smid_nvme_encap(struct MPT3SAS_ADAPTER *ioc, u16 smid)
4252 {
4253 	Mpi2RequestDescriptorUnion_t descriptor;
4254 	u64 *request = (u64 *)&descriptor;
4255 
4256 	descriptor.Default.RequestFlags =
4257 		MPI26_REQ_DESCRIPT_FLAGS_PCIE_ENCAPSULATED;
4258 	descriptor.Default.MSIxIndex =  _base_set_and_get_msix_index(ioc, smid);
4259 	descriptor.Default.SMID = cpu_to_le16(smid);
4260 	descriptor.Default.LMID = 0;
4261 	descriptor.Default.DescriptorTypeDependent = 0;
4262 	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
4263 	    &ioc->scsi_lookup_lock);
4264 }
4265 
4266 /**
4267  * _base_put_smid_default - Default, primarily used for config pages
4268  * @ioc: per adapter object
4269  * @smid: system request message index
4270  */
4271 static void
4272 _base_put_smid_default(struct MPT3SAS_ADAPTER *ioc, u16 smid)
4273 {
4274 	Mpi2RequestDescriptorUnion_t descriptor;
4275 	void *mpi_req_iomem;
4276 	u64 *request;
4277 
4278 	if (ioc->is_mcpu_endpoint) {
4279 		__le32 *mfp = (__le32 *)mpt3sas_base_get_msg_frame(ioc, smid);
4280 
4281 		_clone_sg_entries(ioc, (void *) mfp, smid);
4282 		/* TBD 256 is offset within sys register */
4283 		mpi_req_iomem = (void __force *)ioc->chip +
4284 			MPI_FRAME_START_OFFSET + (smid * ioc->request_sz);
4285 		_base_clone_mpi_to_sys_mem(mpi_req_iomem, (void *)mfp,
4286 							ioc->request_sz);
4287 	}
4288 	request = (u64 *)&descriptor;
4289 	descriptor.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
4290 	descriptor.Default.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
4291 	descriptor.Default.SMID = cpu_to_le16(smid);
4292 	descriptor.Default.LMID = 0;
4293 	descriptor.Default.DescriptorTypeDependent = 0;
4294 	if (ioc->is_mcpu_endpoint)
4295 		_base_mpi_ep_writeq(*request,
4296 				&ioc->chip->RequestDescriptorPostLow,
4297 				&ioc->scsi_lookup_lock);
4298 	else
4299 		_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
4300 				&ioc->scsi_lookup_lock);
4301 }
4302 
4303 /**
4304  * _base_put_smid_scsi_io_atomic - send SCSI_IO request to firmware using
4305  *   Atomic Request Descriptor
4306  * @ioc: per adapter object
4307  * @smid: system request message index
4308  * @handle: device handle, unused in this function, for function type match
4309  *
4310  * Return: nothing.
4311  */
4312 static void
4313 _base_put_smid_scsi_io_atomic(struct MPT3SAS_ADAPTER *ioc, u16 smid,
4314 	u16 handle)
4315 {
4316 	Mpi26AtomicRequestDescriptor_t descriptor;
4317 	u32 *request = (u32 *)&descriptor;
4318 
4319 	descriptor.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
4320 	descriptor.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
4321 	descriptor.SMID = cpu_to_le16(smid);
4322 
4323 	writel(cpu_to_le32(*request), &ioc->chip->AtomicRequestDescriptorPost);
4324 }
4325 
4326 /**
4327  * _base_put_smid_fast_path_atomic - send fast path request to firmware
4328  * using Atomic Request Descriptor
4329  * @ioc: per adapter object
4330  * @smid: system request message index
4331  * @handle: device handle, unused in this function, for function type match
4332  * Return: nothing
4333  */
4334 static void
4335 _base_put_smid_fast_path_atomic(struct MPT3SAS_ADAPTER *ioc, u16 smid,
4336 	u16 handle)
4337 {
4338 	Mpi26AtomicRequestDescriptor_t descriptor;
4339 	u32 *request = (u32 *)&descriptor;
4340 
4341 	descriptor.RequestFlags = MPI25_REQ_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO;
4342 	descriptor.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
4343 	descriptor.SMID = cpu_to_le16(smid);
4344 
4345 	writel(cpu_to_le32(*request), &ioc->chip->AtomicRequestDescriptorPost);
4346 }
4347 
4348 /**
4349  * _base_put_smid_hi_priority_atomic - send Task Management request to
4350  * firmware using Atomic Request Descriptor
4351  * @ioc: per adapter object
4352  * @smid: system request message index
4353  * @msix_task: msix_task will be same as msix of IO in case of task abort else 0
4354  *
4355  * Return: nothing.
4356  */
4357 static void
4358 _base_put_smid_hi_priority_atomic(struct MPT3SAS_ADAPTER *ioc, u16 smid,
4359 	u16 msix_task)
4360 {
4361 	Mpi26AtomicRequestDescriptor_t descriptor;
4362 	u32 *request = (u32 *)&descriptor;
4363 
4364 	descriptor.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY;
4365 	descriptor.MSIxIndex = msix_task;
4366 	descriptor.SMID = cpu_to_le16(smid);
4367 
4368 	writel(cpu_to_le32(*request), &ioc->chip->AtomicRequestDescriptorPost);
4369 }
4370 
4371 /**
4372  * _base_put_smid_default_atomic - Default, primarily used for config pages
4373  * use Atomic Request Descriptor
4374  * @ioc: per adapter object
4375  * @smid: system request message index
4376  *
4377  * Return: nothing.
4378  */
4379 static void
4380 _base_put_smid_default_atomic(struct MPT3SAS_ADAPTER *ioc, u16 smid)
4381 {
4382 	Mpi26AtomicRequestDescriptor_t descriptor;
4383 	u32 *request = (u32 *)&descriptor;
4384 
4385 	descriptor.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
4386 	descriptor.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
4387 	descriptor.SMID = cpu_to_le16(smid);
4388 
4389 	writel(cpu_to_le32(*request), &ioc->chip->AtomicRequestDescriptorPost);
4390 }
4391 
4392 /**
4393  * _base_display_OEMs_branding - Display branding string
4394  * @ioc: per adapter object
4395  */
4396 static void
4397 _base_display_OEMs_branding(struct MPT3SAS_ADAPTER *ioc)
4398 {
4399 	if (ioc->pdev->subsystem_vendor != PCI_VENDOR_ID_INTEL)
4400 		return;
4401 
4402 	switch (ioc->pdev->subsystem_vendor) {
4403 	case PCI_VENDOR_ID_INTEL:
4404 		switch (ioc->pdev->device) {
4405 		case MPI2_MFGPAGE_DEVID_SAS2008:
4406 			switch (ioc->pdev->subsystem_device) {
4407 			case MPT2SAS_INTEL_RMS2LL080_SSDID:
4408 				ioc_info(ioc, "%s\n",
4409 					 MPT2SAS_INTEL_RMS2LL080_BRANDING);
4410 				break;
4411 			case MPT2SAS_INTEL_RMS2LL040_SSDID:
4412 				ioc_info(ioc, "%s\n",
4413 					 MPT2SAS_INTEL_RMS2LL040_BRANDING);
4414 				break;
4415 			case MPT2SAS_INTEL_SSD910_SSDID:
4416 				ioc_info(ioc, "%s\n",
4417 					 MPT2SAS_INTEL_SSD910_BRANDING);
4418 				break;
4419 			default:
4420 				ioc_info(ioc, "Intel(R) Controller: Subsystem ID: 0x%X\n",
4421 					 ioc->pdev->subsystem_device);
4422 				break;
4423 			}
4424 			break;
4425 		case MPI2_MFGPAGE_DEVID_SAS2308_2:
4426 			switch (ioc->pdev->subsystem_device) {
4427 			case MPT2SAS_INTEL_RS25GB008_SSDID:
4428 				ioc_info(ioc, "%s\n",
4429 					 MPT2SAS_INTEL_RS25GB008_BRANDING);
4430 				break;
4431 			case MPT2SAS_INTEL_RMS25JB080_SSDID:
4432 				ioc_info(ioc, "%s\n",
4433 					 MPT2SAS_INTEL_RMS25JB080_BRANDING);
4434 				break;
4435 			case MPT2SAS_INTEL_RMS25JB040_SSDID:
4436 				ioc_info(ioc, "%s\n",
4437 					 MPT2SAS_INTEL_RMS25JB040_BRANDING);
4438 				break;
4439 			case MPT2SAS_INTEL_RMS25KB080_SSDID:
4440 				ioc_info(ioc, "%s\n",
4441 					 MPT2SAS_INTEL_RMS25KB080_BRANDING);
4442 				break;
4443 			case MPT2SAS_INTEL_RMS25KB040_SSDID:
4444 				ioc_info(ioc, "%s\n",
4445 					 MPT2SAS_INTEL_RMS25KB040_BRANDING);
4446 				break;
4447 			case MPT2SAS_INTEL_RMS25LB040_SSDID:
4448 				ioc_info(ioc, "%s\n",
4449 					 MPT2SAS_INTEL_RMS25LB040_BRANDING);
4450 				break;
4451 			case MPT2SAS_INTEL_RMS25LB080_SSDID:
4452 				ioc_info(ioc, "%s\n",
4453 					 MPT2SAS_INTEL_RMS25LB080_BRANDING);
4454 				break;
4455 			default:
4456 				ioc_info(ioc, "Intel(R) Controller: Subsystem ID: 0x%X\n",
4457 					 ioc->pdev->subsystem_device);
4458 				break;
4459 			}
4460 			break;
4461 		case MPI25_MFGPAGE_DEVID_SAS3008:
4462 			switch (ioc->pdev->subsystem_device) {
4463 			case MPT3SAS_INTEL_RMS3JC080_SSDID:
4464 				ioc_info(ioc, "%s\n",
4465 					 MPT3SAS_INTEL_RMS3JC080_BRANDING);
4466 				break;
4467 
4468 			case MPT3SAS_INTEL_RS3GC008_SSDID:
4469 				ioc_info(ioc, "%s\n",
4470 					 MPT3SAS_INTEL_RS3GC008_BRANDING);
4471 				break;
4472 			case MPT3SAS_INTEL_RS3FC044_SSDID:
4473 				ioc_info(ioc, "%s\n",
4474 					 MPT3SAS_INTEL_RS3FC044_BRANDING);
4475 				break;
4476 			case MPT3SAS_INTEL_RS3UC080_SSDID:
4477 				ioc_info(ioc, "%s\n",
4478 					 MPT3SAS_INTEL_RS3UC080_BRANDING);
4479 				break;
4480 			default:
4481 				ioc_info(ioc, "Intel(R) Controller: Subsystem ID: 0x%X\n",
4482 					 ioc->pdev->subsystem_device);
4483 				break;
4484 			}
4485 			break;
4486 		default:
4487 			ioc_info(ioc, "Intel(R) Controller: Subsystem ID: 0x%X\n",
4488 				 ioc->pdev->subsystem_device);
4489 			break;
4490 		}
4491 		break;
4492 	case PCI_VENDOR_ID_DELL:
4493 		switch (ioc->pdev->device) {
4494 		case MPI2_MFGPAGE_DEVID_SAS2008:
4495 			switch (ioc->pdev->subsystem_device) {
4496 			case MPT2SAS_DELL_6GBPS_SAS_HBA_SSDID:
4497 				ioc_info(ioc, "%s\n",
4498 					 MPT2SAS_DELL_6GBPS_SAS_HBA_BRANDING);
4499 				break;
4500 			case MPT2SAS_DELL_PERC_H200_ADAPTER_SSDID:
4501 				ioc_info(ioc, "%s\n",
4502 					 MPT2SAS_DELL_PERC_H200_ADAPTER_BRANDING);
4503 				break;
4504 			case MPT2SAS_DELL_PERC_H200_INTEGRATED_SSDID:
4505 				ioc_info(ioc, "%s\n",
4506 					 MPT2SAS_DELL_PERC_H200_INTEGRATED_BRANDING);
4507 				break;
4508 			case MPT2SAS_DELL_PERC_H200_MODULAR_SSDID:
4509 				ioc_info(ioc, "%s\n",
4510 					 MPT2SAS_DELL_PERC_H200_MODULAR_BRANDING);
4511 				break;
4512 			case MPT2SAS_DELL_PERC_H200_EMBEDDED_SSDID:
4513 				ioc_info(ioc, "%s\n",
4514 					 MPT2SAS_DELL_PERC_H200_EMBEDDED_BRANDING);
4515 				break;
4516 			case MPT2SAS_DELL_PERC_H200_SSDID:
4517 				ioc_info(ioc, "%s\n",
4518 					 MPT2SAS_DELL_PERC_H200_BRANDING);
4519 				break;
4520 			case MPT2SAS_DELL_6GBPS_SAS_SSDID:
4521 				ioc_info(ioc, "%s\n",
4522 					 MPT2SAS_DELL_6GBPS_SAS_BRANDING);
4523 				break;
4524 			default:
4525 				ioc_info(ioc, "Dell 6Gbps HBA: Subsystem ID: 0x%X\n",
4526 					 ioc->pdev->subsystem_device);
4527 				break;
4528 			}
4529 			break;
4530 		case MPI25_MFGPAGE_DEVID_SAS3008:
4531 			switch (ioc->pdev->subsystem_device) {
4532 			case MPT3SAS_DELL_12G_HBA_SSDID:
4533 				ioc_info(ioc, "%s\n",
4534 					 MPT3SAS_DELL_12G_HBA_BRANDING);
4535 				break;
4536 			default:
4537 				ioc_info(ioc, "Dell 12Gbps HBA: Subsystem ID: 0x%X\n",
4538 					 ioc->pdev->subsystem_device);
4539 				break;
4540 			}
4541 			break;
4542 		default:
4543 			ioc_info(ioc, "Dell HBA: Subsystem ID: 0x%X\n",
4544 				 ioc->pdev->subsystem_device);
4545 			break;
4546 		}
4547 		break;
4548 	case PCI_VENDOR_ID_CISCO:
4549 		switch (ioc->pdev->device) {
4550 		case MPI25_MFGPAGE_DEVID_SAS3008:
4551 			switch (ioc->pdev->subsystem_device) {
4552 			case MPT3SAS_CISCO_12G_8E_HBA_SSDID:
4553 				ioc_info(ioc, "%s\n",
4554 					 MPT3SAS_CISCO_12G_8E_HBA_BRANDING);
4555 				break;
4556 			case MPT3SAS_CISCO_12G_8I_HBA_SSDID:
4557 				ioc_info(ioc, "%s\n",
4558 					 MPT3SAS_CISCO_12G_8I_HBA_BRANDING);
4559 				break;
4560 			case MPT3SAS_CISCO_12G_AVILA_HBA_SSDID:
4561 				ioc_info(ioc, "%s\n",
4562 					 MPT3SAS_CISCO_12G_AVILA_HBA_BRANDING);
4563 				break;
4564 			default:
4565 				ioc_info(ioc, "Cisco 12Gbps SAS HBA: Subsystem ID: 0x%X\n",
4566 					 ioc->pdev->subsystem_device);
4567 				break;
4568 			}
4569 			break;
4570 		case MPI25_MFGPAGE_DEVID_SAS3108_1:
4571 			switch (ioc->pdev->subsystem_device) {
4572 			case MPT3SAS_CISCO_12G_AVILA_HBA_SSDID:
4573 				ioc_info(ioc, "%s\n",
4574 					 MPT3SAS_CISCO_12G_AVILA_HBA_BRANDING);
4575 				break;
4576 			case MPT3SAS_CISCO_12G_COLUSA_MEZZANINE_HBA_SSDID:
4577 				ioc_info(ioc, "%s\n",
4578 					 MPT3SAS_CISCO_12G_COLUSA_MEZZANINE_HBA_BRANDING);
4579 				break;
4580 			default:
4581 				ioc_info(ioc, "Cisco 12Gbps SAS HBA: Subsystem ID: 0x%X\n",
4582 					 ioc->pdev->subsystem_device);
4583 				break;
4584 			}
4585 			break;
4586 		default:
4587 			ioc_info(ioc, "Cisco SAS HBA: Subsystem ID: 0x%X\n",
4588 				 ioc->pdev->subsystem_device);
4589 			break;
4590 		}
4591 		break;
4592 	case MPT2SAS_HP_3PAR_SSVID:
4593 		switch (ioc->pdev->device) {
4594 		case MPI2_MFGPAGE_DEVID_SAS2004:
4595 			switch (ioc->pdev->subsystem_device) {
4596 			case MPT2SAS_HP_DAUGHTER_2_4_INTERNAL_SSDID:
4597 				ioc_info(ioc, "%s\n",
4598 					 MPT2SAS_HP_DAUGHTER_2_4_INTERNAL_BRANDING);
4599 				break;
4600 			default:
4601 				ioc_info(ioc, "HP 6Gbps SAS HBA: Subsystem ID: 0x%X\n",
4602 					 ioc->pdev->subsystem_device);
4603 				break;
4604 			}
4605 			break;
4606 		case MPI2_MFGPAGE_DEVID_SAS2308_2:
4607 			switch (ioc->pdev->subsystem_device) {
4608 			case MPT2SAS_HP_2_4_INTERNAL_SSDID:
4609 				ioc_info(ioc, "%s\n",
4610 					 MPT2SAS_HP_2_4_INTERNAL_BRANDING);
4611 				break;
4612 			case MPT2SAS_HP_2_4_EXTERNAL_SSDID:
4613 				ioc_info(ioc, "%s\n",
4614 					 MPT2SAS_HP_2_4_EXTERNAL_BRANDING);
4615 				break;
4616 			case MPT2SAS_HP_1_4_INTERNAL_1_4_EXTERNAL_SSDID:
4617 				ioc_info(ioc, "%s\n",
4618 					 MPT2SAS_HP_1_4_INTERNAL_1_4_EXTERNAL_BRANDING);
4619 				break;
4620 			case MPT2SAS_HP_EMBEDDED_2_4_INTERNAL_SSDID:
4621 				ioc_info(ioc, "%s\n",
4622 					 MPT2SAS_HP_EMBEDDED_2_4_INTERNAL_BRANDING);
4623 				break;
4624 			default:
4625 				ioc_info(ioc, "HP 6Gbps SAS HBA: Subsystem ID: 0x%X\n",
4626 					 ioc->pdev->subsystem_device);
4627 				break;
4628 			}
4629 			break;
4630 		default:
4631 			ioc_info(ioc, "HP SAS HBA: Subsystem ID: 0x%X\n",
4632 				 ioc->pdev->subsystem_device);
4633 			break;
4634 		}
4635 		break;
4636 	default:
4637 		break;
4638 	}
4639 }
4640 
4641 /**
4642  * _base_display_fwpkg_version - sends FWUpload request to pull FWPkg
4643  *				version from FW Image Header.
4644  * @ioc: per adapter object
4645  *
4646  * Return: 0 for success, non-zero for failure.
4647  */
4648 	static int
4649 _base_display_fwpkg_version(struct MPT3SAS_ADAPTER *ioc)
4650 {
4651 	Mpi2FWImageHeader_t *fw_img_hdr;
4652 	Mpi26ComponentImageHeader_t *cmp_img_hdr;
4653 	Mpi25FWUploadRequest_t *mpi_request;
4654 	Mpi2FWUploadReply_t mpi_reply;
4655 	int r = 0, issue_diag_reset = 0;
4656 	u32  package_version = 0;
4657 	void *fwpkg_data = NULL;
4658 	dma_addr_t fwpkg_data_dma;
4659 	u16 smid, ioc_status;
4660 	size_t data_length;
4661 
4662 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
4663 
4664 	if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
4665 		ioc_err(ioc, "%s: internal command already in use\n", __func__);
4666 		return -EAGAIN;
4667 	}
4668 
4669 	data_length = sizeof(Mpi2FWImageHeader_t);
4670 	fwpkg_data = dma_alloc_coherent(&ioc->pdev->dev, data_length,
4671 			&fwpkg_data_dma, GFP_KERNEL);
4672 	if (!fwpkg_data) {
4673 		ioc_err(ioc,
4674 		    "Memory allocation for fwpkg data failed at %s:%d/%s()!\n",
4675 			__FILE__, __LINE__, __func__);
4676 		return -ENOMEM;
4677 	}
4678 
4679 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
4680 	if (!smid) {
4681 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
4682 		r = -EAGAIN;
4683 		goto out;
4684 	}
4685 
4686 	ioc->base_cmds.status = MPT3_CMD_PENDING;
4687 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
4688 	ioc->base_cmds.smid = smid;
4689 	memset(mpi_request, 0, sizeof(Mpi25FWUploadRequest_t));
4690 	mpi_request->Function = MPI2_FUNCTION_FW_UPLOAD;
4691 	mpi_request->ImageType = MPI2_FW_UPLOAD_ITYPE_FW_FLASH;
4692 	mpi_request->ImageSize = cpu_to_le32(data_length);
4693 	ioc->build_sg(ioc, &mpi_request->SGL, 0, 0, fwpkg_data_dma,
4694 			data_length);
4695 	init_completion(&ioc->base_cmds.done);
4696 	ioc->put_smid_default(ioc, smid);
4697 	/* Wait for 15 seconds */
4698 	wait_for_completion_timeout(&ioc->base_cmds.done,
4699 			FW_IMG_HDR_READ_TIMEOUT*HZ);
4700 	ioc_info(ioc, "%s: complete\n", __func__);
4701 	if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
4702 		ioc_err(ioc, "%s: timeout\n", __func__);
4703 		_debug_dump_mf(mpi_request,
4704 				sizeof(Mpi25FWUploadRequest_t)/4);
4705 		issue_diag_reset = 1;
4706 	} else {
4707 		memset(&mpi_reply, 0, sizeof(Mpi2FWUploadReply_t));
4708 		if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID) {
4709 			memcpy(&mpi_reply, ioc->base_cmds.reply,
4710 					sizeof(Mpi2FWUploadReply_t));
4711 			ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
4712 						MPI2_IOCSTATUS_MASK;
4713 			if (ioc_status == MPI2_IOCSTATUS_SUCCESS) {
4714 				fw_img_hdr = (Mpi2FWImageHeader_t *)fwpkg_data;
4715 				if (le32_to_cpu(fw_img_hdr->Signature) ==
4716 				    MPI26_IMAGE_HEADER_SIGNATURE0_MPI26) {
4717 					cmp_img_hdr =
4718 					    (Mpi26ComponentImageHeader_t *)
4719 					    (fwpkg_data);
4720 					package_version =
4721 					    le32_to_cpu(
4722 					    cmp_img_hdr->ApplicationSpecific);
4723 				} else
4724 					package_version =
4725 					    le32_to_cpu(
4726 					    fw_img_hdr->PackageVersion.Word);
4727 				if (package_version)
4728 					ioc_info(ioc,
4729 					"FW Package Ver(%02d.%02d.%02d.%02d)\n",
4730 					((package_version) & 0xFF000000) >> 24,
4731 					((package_version) & 0x00FF0000) >> 16,
4732 					((package_version) & 0x0000FF00) >> 8,
4733 					(package_version) & 0x000000FF);
4734 			} else {
4735 				_debug_dump_mf(&mpi_reply,
4736 						sizeof(Mpi2FWUploadReply_t)/4);
4737 			}
4738 		}
4739 	}
4740 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
4741 out:
4742 	if (fwpkg_data)
4743 		dma_free_coherent(&ioc->pdev->dev, data_length, fwpkg_data,
4744 				fwpkg_data_dma);
4745 	if (issue_diag_reset) {
4746 		if (ioc->drv_internal_flags & MPT_DRV_INTERNAL_FIRST_PE_ISSUED)
4747 			return -EFAULT;
4748 		if (mpt3sas_base_check_for_fault_and_issue_reset(ioc))
4749 			return -EFAULT;
4750 		r = -EAGAIN;
4751 	}
4752 	return r;
4753 }
4754 
4755 /**
4756  * _base_display_ioc_capabilities - Display IOC's capabilities.
4757  * @ioc: per adapter object
4758  */
4759 static void
4760 _base_display_ioc_capabilities(struct MPT3SAS_ADAPTER *ioc)
4761 {
4762 	int i = 0;
4763 	char desc[17] = {0};
4764 	u32 iounit_pg1_flags;
4765 	u32 bios_version;
4766 
4767 	bios_version = le32_to_cpu(ioc->bios_pg3.BiosVersion);
4768 	strncpy(desc, ioc->manu_pg0.ChipName, 16);
4769 	ioc_info(ioc, "%s: FWVersion(%02d.%02d.%02d.%02d), ChipRevision(0x%02x), BiosVersion(%02d.%02d.%02d.%02d)\n",
4770 		 desc,
4771 		 (ioc->facts.FWVersion.Word & 0xFF000000) >> 24,
4772 		 (ioc->facts.FWVersion.Word & 0x00FF0000) >> 16,
4773 		 (ioc->facts.FWVersion.Word & 0x0000FF00) >> 8,
4774 		 ioc->facts.FWVersion.Word & 0x000000FF,
4775 		 ioc->pdev->revision,
4776 		 (bios_version & 0xFF000000) >> 24,
4777 		 (bios_version & 0x00FF0000) >> 16,
4778 		 (bios_version & 0x0000FF00) >> 8,
4779 		 bios_version & 0x000000FF);
4780 
4781 	_base_display_OEMs_branding(ioc);
4782 
4783 	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_NVME_DEVICES) {
4784 		pr_info("%sNVMe", i ? "," : "");
4785 		i++;
4786 	}
4787 
4788 	ioc_info(ioc, "Protocol=(");
4789 
4790 	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_INITIATOR) {
4791 		pr_cont("Initiator");
4792 		i++;
4793 	}
4794 
4795 	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_TARGET) {
4796 		pr_cont("%sTarget", i ? "," : "");
4797 		i++;
4798 	}
4799 
4800 	i = 0;
4801 	pr_cont("), Capabilities=(");
4802 
4803 	if (!ioc->hide_ir_msg) {
4804 		if (ioc->facts.IOCCapabilities &
4805 		    MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID) {
4806 			pr_cont("Raid");
4807 			i++;
4808 		}
4809 	}
4810 
4811 	if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR) {
4812 		pr_cont("%sTLR", i ? "," : "");
4813 		i++;
4814 	}
4815 
4816 	if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_MULTICAST) {
4817 		pr_cont("%sMulticast", i ? "," : "");
4818 		i++;
4819 	}
4820 
4821 	if (ioc->facts.IOCCapabilities &
4822 	    MPI2_IOCFACTS_CAPABILITY_BIDIRECTIONAL_TARGET) {
4823 		pr_cont("%sBIDI Target", i ? "," : "");
4824 		i++;
4825 	}
4826 
4827 	if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP) {
4828 		pr_cont("%sEEDP", i ? "," : "");
4829 		i++;
4830 	}
4831 
4832 	if (ioc->facts.IOCCapabilities &
4833 	    MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER) {
4834 		pr_cont("%sSnapshot Buffer", i ? "," : "");
4835 		i++;
4836 	}
4837 
4838 	if (ioc->facts.IOCCapabilities &
4839 	    MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER) {
4840 		pr_cont("%sDiag Trace Buffer", i ? "," : "");
4841 		i++;
4842 	}
4843 
4844 	if (ioc->facts.IOCCapabilities &
4845 	    MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER) {
4846 		pr_cont("%sDiag Extended Buffer", i ? "," : "");
4847 		i++;
4848 	}
4849 
4850 	if (ioc->facts.IOCCapabilities &
4851 	    MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING) {
4852 		pr_cont("%sTask Set Full", i ? "," : "");
4853 		i++;
4854 	}
4855 
4856 	iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
4857 	if (!(iounit_pg1_flags & MPI2_IOUNITPAGE1_NATIVE_COMMAND_Q_DISABLE)) {
4858 		pr_cont("%sNCQ", i ? "," : "");
4859 		i++;
4860 	}
4861 
4862 	pr_cont(")\n");
4863 }
4864 
4865 /**
4866  * mpt3sas_base_update_missing_delay - change the missing delay timers
4867  * @ioc: per adapter object
4868  * @device_missing_delay: amount of time till device is reported missing
4869  * @io_missing_delay: interval IO is returned when there is a missing device
4870  *
4871  * Passed on the command line, this function will modify the device missing
4872  * delay, as well as the io missing delay. This should be called at driver
4873  * load time.
4874  */
4875 void
4876 mpt3sas_base_update_missing_delay(struct MPT3SAS_ADAPTER *ioc,
4877 	u16 device_missing_delay, u8 io_missing_delay)
4878 {
4879 	u16 dmd, dmd_new, dmd_orignal;
4880 	u8 io_missing_delay_original;
4881 	u16 sz;
4882 	Mpi2SasIOUnitPage1_t *sas_iounit_pg1 = NULL;
4883 	Mpi2ConfigReply_t mpi_reply;
4884 	u8 num_phys = 0;
4885 	u16 ioc_status;
4886 
4887 	mpt3sas_config_get_number_hba_phys(ioc, &num_phys);
4888 	if (!num_phys)
4889 		return;
4890 
4891 	sz = offsetof(Mpi2SasIOUnitPage1_t, PhyData) + (num_phys *
4892 	    sizeof(Mpi2SasIOUnit1PhyData_t));
4893 	sas_iounit_pg1 = kzalloc(sz, GFP_KERNEL);
4894 	if (!sas_iounit_pg1) {
4895 		ioc_err(ioc, "failure at %s:%d/%s()!\n",
4896 			__FILE__, __LINE__, __func__);
4897 		goto out;
4898 	}
4899 	if ((mpt3sas_config_get_sas_iounit_pg1(ioc, &mpi_reply,
4900 	    sas_iounit_pg1, sz))) {
4901 		ioc_err(ioc, "failure at %s:%d/%s()!\n",
4902 			__FILE__, __LINE__, __func__);
4903 		goto out;
4904 	}
4905 	ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
4906 	    MPI2_IOCSTATUS_MASK;
4907 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
4908 		ioc_err(ioc, "failure at %s:%d/%s()!\n",
4909 			__FILE__, __LINE__, __func__);
4910 		goto out;
4911 	}
4912 
4913 	/* device missing delay */
4914 	dmd = sas_iounit_pg1->ReportDeviceMissingDelay;
4915 	if (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16)
4916 		dmd = (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK) * 16;
4917 	else
4918 		dmd = dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK;
4919 	dmd_orignal = dmd;
4920 	if (device_missing_delay > 0x7F) {
4921 		dmd = (device_missing_delay > 0x7F0) ? 0x7F0 :
4922 		    device_missing_delay;
4923 		dmd = dmd / 16;
4924 		dmd |= MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16;
4925 	} else
4926 		dmd = device_missing_delay;
4927 	sas_iounit_pg1->ReportDeviceMissingDelay = dmd;
4928 
4929 	/* io missing delay */
4930 	io_missing_delay_original = sas_iounit_pg1->IODeviceMissingDelay;
4931 	sas_iounit_pg1->IODeviceMissingDelay = io_missing_delay;
4932 
4933 	if (!mpt3sas_config_set_sas_iounit_pg1(ioc, &mpi_reply, sas_iounit_pg1,
4934 	    sz)) {
4935 		if (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16)
4936 			dmd_new = (dmd &
4937 			    MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK) * 16;
4938 		else
4939 			dmd_new =
4940 		    dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK;
4941 		ioc_info(ioc, "device_missing_delay: old(%d), new(%d)\n",
4942 			 dmd_orignal, dmd_new);
4943 		ioc_info(ioc, "ioc_missing_delay: old(%d), new(%d)\n",
4944 			 io_missing_delay_original,
4945 			 io_missing_delay);
4946 		ioc->device_missing_delay = dmd_new;
4947 		ioc->io_missing_delay = io_missing_delay;
4948 	}
4949 
4950 out:
4951 	kfree(sas_iounit_pg1);
4952 }
4953 
4954 /**
4955  * _base_update_ioc_page1_inlinewith_perf_mode - Update IOC Page1 fields
4956  *    according to performance mode.
4957  * @ioc : per adapter object
4958  *
4959  * Return: zero on success; otherwise return EAGAIN error code asking the
4960  * caller to retry.
4961  */
4962 static int
4963 _base_update_ioc_page1_inlinewith_perf_mode(struct MPT3SAS_ADAPTER *ioc)
4964 {
4965 	Mpi2IOCPage1_t ioc_pg1;
4966 	Mpi2ConfigReply_t mpi_reply;
4967 	int rc;
4968 
4969 	rc = mpt3sas_config_get_ioc_pg1(ioc, &mpi_reply, &ioc->ioc_pg1_copy);
4970 	if (rc)
4971 		return rc;
4972 	memcpy(&ioc_pg1, &ioc->ioc_pg1_copy, sizeof(Mpi2IOCPage1_t));
4973 
4974 	switch (perf_mode) {
4975 	case MPT_PERF_MODE_DEFAULT:
4976 	case MPT_PERF_MODE_BALANCED:
4977 		if (ioc->high_iops_queues) {
4978 			ioc_info(ioc,
4979 				"Enable interrupt coalescing only for first\t"
4980 				"%d reply queues\n",
4981 				MPT3SAS_HIGH_IOPS_REPLY_QUEUES);
4982 			/*
4983 			 * If 31st bit is zero then interrupt coalescing is
4984 			 * enabled for all reply descriptor post queues.
4985 			 * If 31st bit is set to one then user can
4986 			 * enable/disable interrupt coalescing on per reply
4987 			 * descriptor post queue group(8) basis. So to enable
4988 			 * interrupt coalescing only on first reply descriptor
4989 			 * post queue group 31st bit and zero th bit is enabled.
4990 			 */
4991 			ioc_pg1.ProductSpecific = cpu_to_le32(0x80000000 |
4992 			    ((1 << MPT3SAS_HIGH_IOPS_REPLY_QUEUES/8) - 1));
4993 			rc = mpt3sas_config_set_ioc_pg1(ioc, &mpi_reply, &ioc_pg1);
4994 			if (rc)
4995 				return rc;
4996 			ioc_info(ioc, "performance mode: balanced\n");
4997 			return 0;
4998 		}
4999 		fallthrough;
5000 	case MPT_PERF_MODE_LATENCY:
5001 		/*
5002 		 * Enable interrupt coalescing on all reply queues
5003 		 * with timeout value 0xA
5004 		 */
5005 		ioc_pg1.CoalescingTimeout = cpu_to_le32(0xa);
5006 		ioc_pg1.Flags |= cpu_to_le32(MPI2_IOCPAGE1_REPLY_COALESCING);
5007 		ioc_pg1.ProductSpecific = 0;
5008 		rc = mpt3sas_config_set_ioc_pg1(ioc, &mpi_reply, &ioc_pg1);
5009 		if (rc)
5010 			return rc;
5011 		ioc_info(ioc, "performance mode: latency\n");
5012 		break;
5013 	case MPT_PERF_MODE_IOPS:
5014 		/*
5015 		 * Enable interrupt coalescing on all reply queues.
5016 		 */
5017 		ioc_info(ioc,
5018 		    "performance mode: iops with coalescing timeout: 0x%x\n",
5019 		    le32_to_cpu(ioc_pg1.CoalescingTimeout));
5020 		ioc_pg1.Flags |= cpu_to_le32(MPI2_IOCPAGE1_REPLY_COALESCING);
5021 		ioc_pg1.ProductSpecific = 0;
5022 		rc = mpt3sas_config_set_ioc_pg1(ioc, &mpi_reply, &ioc_pg1);
5023 		if (rc)
5024 			return rc;
5025 		break;
5026 	}
5027 	return 0;
5028 }
5029 
5030 /**
5031  * _base_get_event_diag_triggers - get event diag trigger values from
5032  *				persistent pages
5033  * @ioc : per adapter object
5034  *
5035  * Return: nothing.
5036  */
5037 static int
5038 _base_get_event_diag_triggers(struct MPT3SAS_ADAPTER *ioc)
5039 {
5040 	Mpi26DriverTriggerPage2_t trigger_pg2;
5041 	struct SL_WH_EVENT_TRIGGER_T *event_tg;
5042 	MPI26_DRIVER_MPI_EVENT_TIGGER_ENTRY *mpi_event_tg;
5043 	Mpi2ConfigReply_t mpi_reply;
5044 	int r = 0, i = 0;
5045 	u16 count = 0;
5046 	u16 ioc_status;
5047 
5048 	r = mpt3sas_config_get_driver_trigger_pg2(ioc, &mpi_reply,
5049 	    &trigger_pg2);
5050 	if (r)
5051 		return r;
5052 
5053 	ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
5054 	    MPI2_IOCSTATUS_MASK;
5055 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
5056 		dinitprintk(ioc,
5057 		    ioc_err(ioc,
5058 		    "%s: Failed to get trigger pg2, ioc_status(0x%04x)\n",
5059 		   __func__, ioc_status));
5060 		return 0;
5061 	}
5062 
5063 	if (le16_to_cpu(trigger_pg2.NumMPIEventTrigger)) {
5064 		count = le16_to_cpu(trigger_pg2.NumMPIEventTrigger);
5065 		count = min_t(u16, NUM_VALID_ENTRIES, count);
5066 		ioc->diag_trigger_event.ValidEntries = count;
5067 
5068 		event_tg = &ioc->diag_trigger_event.EventTriggerEntry[0];
5069 		mpi_event_tg = &trigger_pg2.MPIEventTriggers[0];
5070 		for (i = 0; i < count; i++) {
5071 			event_tg->EventValue = le16_to_cpu(
5072 			    mpi_event_tg->MPIEventCode);
5073 			event_tg->LogEntryQualifier = le16_to_cpu(
5074 			    mpi_event_tg->MPIEventCodeSpecific);
5075 			event_tg++;
5076 			mpi_event_tg++;
5077 		}
5078 	}
5079 	return 0;
5080 }
5081 
5082 /**
5083  * _base_get_scsi_diag_triggers - get scsi diag trigger values from
5084  *				persistent pages
5085  * @ioc : per adapter object
5086  *
5087  * Return: 0 on success; otherwise return failure status.
5088  */
5089 static int
5090 _base_get_scsi_diag_triggers(struct MPT3SAS_ADAPTER *ioc)
5091 {
5092 	Mpi26DriverTriggerPage3_t trigger_pg3;
5093 	struct SL_WH_SCSI_TRIGGER_T *scsi_tg;
5094 	MPI26_DRIVER_SCSI_SENSE_TIGGER_ENTRY *mpi_scsi_tg;
5095 	Mpi2ConfigReply_t mpi_reply;
5096 	int r = 0, i = 0;
5097 	u16 count = 0;
5098 	u16 ioc_status;
5099 
5100 	r = mpt3sas_config_get_driver_trigger_pg3(ioc, &mpi_reply,
5101 	    &trigger_pg3);
5102 	if (r)
5103 		return r;
5104 
5105 	ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
5106 	    MPI2_IOCSTATUS_MASK;
5107 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
5108 		dinitprintk(ioc,
5109 		    ioc_err(ioc,
5110 		    "%s: Failed to get trigger pg3, ioc_status(0x%04x)\n",
5111 		    __func__, ioc_status));
5112 		return 0;
5113 	}
5114 
5115 	if (le16_to_cpu(trigger_pg3.NumSCSISenseTrigger)) {
5116 		count = le16_to_cpu(trigger_pg3.NumSCSISenseTrigger);
5117 		count = min_t(u16, NUM_VALID_ENTRIES, count);
5118 		ioc->diag_trigger_scsi.ValidEntries = count;
5119 
5120 		scsi_tg = &ioc->diag_trigger_scsi.SCSITriggerEntry[0];
5121 		mpi_scsi_tg = &trigger_pg3.SCSISenseTriggers[0];
5122 		for (i = 0; i < count; i++) {
5123 			scsi_tg->ASCQ = mpi_scsi_tg->ASCQ;
5124 			scsi_tg->ASC = mpi_scsi_tg->ASC;
5125 			scsi_tg->SenseKey = mpi_scsi_tg->SenseKey;
5126 
5127 			scsi_tg++;
5128 			mpi_scsi_tg++;
5129 		}
5130 	}
5131 	return 0;
5132 }
5133 
5134 /**
5135  * _base_get_mpi_diag_triggers - get mpi diag trigger values from
5136  *				persistent pages
5137  * @ioc : per adapter object
5138  *
5139  * Return: 0 on success; otherwise return failure status.
5140  */
5141 static int
5142 _base_get_mpi_diag_triggers(struct MPT3SAS_ADAPTER *ioc)
5143 {
5144 	Mpi26DriverTriggerPage4_t trigger_pg4;
5145 	struct SL_WH_MPI_TRIGGER_T *status_tg;
5146 	MPI26_DRIVER_IOCSTATUS_LOGINFO_TIGGER_ENTRY *mpi_status_tg;
5147 	Mpi2ConfigReply_t mpi_reply;
5148 	int r = 0, i = 0;
5149 	u16 count = 0;
5150 	u16 ioc_status;
5151 
5152 	r = mpt3sas_config_get_driver_trigger_pg4(ioc, &mpi_reply,
5153 	    &trigger_pg4);
5154 	if (r)
5155 		return r;
5156 
5157 	ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
5158 	    MPI2_IOCSTATUS_MASK;
5159 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
5160 		dinitprintk(ioc,
5161 		    ioc_err(ioc,
5162 		    "%s: Failed to get trigger pg4, ioc_status(0x%04x)\n",
5163 		    __func__, ioc_status));
5164 		return 0;
5165 	}
5166 
5167 	if (le16_to_cpu(trigger_pg4.NumIOCStatusLogInfoTrigger)) {
5168 		count = le16_to_cpu(trigger_pg4.NumIOCStatusLogInfoTrigger);
5169 		count = min_t(u16, NUM_VALID_ENTRIES, count);
5170 		ioc->diag_trigger_mpi.ValidEntries = count;
5171 
5172 		status_tg = &ioc->diag_trigger_mpi.MPITriggerEntry[0];
5173 		mpi_status_tg = &trigger_pg4.IOCStatusLoginfoTriggers[0];
5174 
5175 		for (i = 0; i < count; i++) {
5176 			status_tg->IOCStatus = le16_to_cpu(
5177 			    mpi_status_tg->IOCStatus);
5178 			status_tg->IocLogInfo = le32_to_cpu(
5179 			    mpi_status_tg->LogInfo);
5180 
5181 			status_tg++;
5182 			mpi_status_tg++;
5183 		}
5184 	}
5185 	return 0;
5186 }
5187 
5188 /**
5189  * _base_get_master_diag_triggers - get master diag trigger values from
5190  *				persistent pages
5191  * @ioc : per adapter object
5192  *
5193  * Return: nothing.
5194  */
5195 static int
5196 _base_get_master_diag_triggers(struct MPT3SAS_ADAPTER *ioc)
5197 {
5198 	Mpi26DriverTriggerPage1_t trigger_pg1;
5199 	Mpi2ConfigReply_t mpi_reply;
5200 	int r;
5201 	u16 ioc_status;
5202 
5203 	r = mpt3sas_config_get_driver_trigger_pg1(ioc, &mpi_reply,
5204 	    &trigger_pg1);
5205 	if (r)
5206 		return r;
5207 
5208 	ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
5209 	    MPI2_IOCSTATUS_MASK;
5210 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
5211 		dinitprintk(ioc,
5212 		    ioc_err(ioc,
5213 		    "%s: Failed to get trigger pg1, ioc_status(0x%04x)\n",
5214 		   __func__, ioc_status));
5215 		return 0;
5216 	}
5217 
5218 	if (le16_to_cpu(trigger_pg1.NumMasterTrigger))
5219 		ioc->diag_trigger_master.MasterData |=
5220 		    le32_to_cpu(
5221 		    trigger_pg1.MasterTriggers[0].MasterTriggerFlags);
5222 	return 0;
5223 }
5224 
5225 /**
5226  * _base_check_for_trigger_pages_support - checks whether HBA FW supports
5227  *					driver trigger pages or not
5228  * @ioc : per adapter object
5229  * @trigger_flags : address where trigger page0's TriggerFlags value is copied
5230  *
5231  * Return: trigger flags mask if HBA FW supports driver trigger pages;
5232  * otherwise returns %-EFAULT if driver trigger pages are not supported by FW or
5233  * return EAGAIN if diag reset occurred due to FW fault and asking the
5234  * caller to retry the command.
5235  *
5236  */
5237 static int
5238 _base_check_for_trigger_pages_support(struct MPT3SAS_ADAPTER *ioc, u32 *trigger_flags)
5239 {
5240 	Mpi26DriverTriggerPage0_t trigger_pg0;
5241 	int r = 0;
5242 	Mpi2ConfigReply_t mpi_reply;
5243 	u16 ioc_status;
5244 
5245 	r = mpt3sas_config_get_driver_trigger_pg0(ioc, &mpi_reply,
5246 	    &trigger_pg0);
5247 	if (r)
5248 		return r;
5249 
5250 	ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
5251 	    MPI2_IOCSTATUS_MASK;
5252 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS)
5253 		return -EFAULT;
5254 
5255 	*trigger_flags = le16_to_cpu(trigger_pg0.TriggerFlags);
5256 	return 0;
5257 }
5258 
5259 /**
5260  * _base_get_diag_triggers - Retrieve diag trigger values from
5261  *				persistent pages.
5262  * @ioc : per adapter object
5263  *
5264  * Return: zero on success; otherwise return EAGAIN error codes
5265  * asking the caller to retry.
5266  */
5267 static int
5268 _base_get_diag_triggers(struct MPT3SAS_ADAPTER *ioc)
5269 {
5270 	int trigger_flags;
5271 	int r;
5272 
5273 	/*
5274 	 * Default setting of master trigger.
5275 	 */
5276 	ioc->diag_trigger_master.MasterData =
5277 	    (MASTER_TRIGGER_FW_FAULT + MASTER_TRIGGER_ADAPTER_RESET);
5278 
5279 	r = _base_check_for_trigger_pages_support(ioc, &trigger_flags);
5280 	if (r) {
5281 		if (r == -EAGAIN)
5282 			return r;
5283 		/*
5284 		 * Don't go for error handling when FW doesn't support
5285 		 * driver trigger pages.
5286 		 */
5287 		return 0;
5288 	}
5289 
5290 	ioc->supports_trigger_pages = 1;
5291 
5292 	/*
5293 	 * Retrieve master diag trigger values from driver trigger pg1
5294 	 * if master trigger bit enabled in TriggerFlags.
5295 	 */
5296 	if ((u16)trigger_flags &
5297 	    MPI26_DRIVER_TRIGGER0_FLAG_MASTER_TRIGGER_VALID) {
5298 		r = _base_get_master_diag_triggers(ioc);
5299 		if (r)
5300 			return r;
5301 	}
5302 
5303 	/*
5304 	 * Retrieve event diag trigger values from driver trigger pg2
5305 	 * if event trigger bit enabled in TriggerFlags.
5306 	 */
5307 	if ((u16)trigger_flags &
5308 	    MPI26_DRIVER_TRIGGER0_FLAG_MPI_EVENT_TRIGGER_VALID) {
5309 		r = _base_get_event_diag_triggers(ioc);
5310 		if (r)
5311 			return r;
5312 	}
5313 
5314 	/*
5315 	 * Retrieve scsi diag trigger values from driver trigger pg3
5316 	 * if scsi trigger bit enabled in TriggerFlags.
5317 	 */
5318 	if ((u16)trigger_flags &
5319 	    MPI26_DRIVER_TRIGGER0_FLAG_SCSI_SENSE_TRIGGER_VALID) {
5320 		r = _base_get_scsi_diag_triggers(ioc);
5321 		if (r)
5322 			return r;
5323 	}
5324 	/*
5325 	 * Retrieve mpi error diag trigger values from driver trigger pg4
5326 	 * if loginfo trigger bit enabled in TriggerFlags.
5327 	 */
5328 	if ((u16)trigger_flags &
5329 	    MPI26_DRIVER_TRIGGER0_FLAG_LOGINFO_TRIGGER_VALID) {
5330 		r = _base_get_mpi_diag_triggers(ioc);
5331 		if (r)
5332 			return r;
5333 	}
5334 	return 0;
5335 }
5336 
5337 /**
5338  * _base_update_diag_trigger_pages - Update the driver trigger pages after
5339  *			online FW update, in case updated FW supports driver
5340  *			trigger pages.
5341  * @ioc : per adapter object
5342  *
5343  * Return: nothing.
5344  */
5345 static void
5346 _base_update_diag_trigger_pages(struct MPT3SAS_ADAPTER *ioc)
5347 {
5348 
5349 	if (ioc->diag_trigger_master.MasterData)
5350 		mpt3sas_config_update_driver_trigger_pg1(ioc,
5351 		    &ioc->diag_trigger_master, 1);
5352 
5353 	if (ioc->diag_trigger_event.ValidEntries)
5354 		mpt3sas_config_update_driver_trigger_pg2(ioc,
5355 		    &ioc->diag_trigger_event, 1);
5356 
5357 	if (ioc->diag_trigger_scsi.ValidEntries)
5358 		mpt3sas_config_update_driver_trigger_pg3(ioc,
5359 		    &ioc->diag_trigger_scsi, 1);
5360 
5361 	if (ioc->diag_trigger_mpi.ValidEntries)
5362 		mpt3sas_config_update_driver_trigger_pg4(ioc,
5363 		    &ioc->diag_trigger_mpi, 1);
5364 }
5365 
5366 /**
5367  * _base_assign_fw_reported_qd	- Get FW reported QD for SAS/SATA devices.
5368  *				- On failure set default QD values.
5369  * @ioc : per adapter object
5370  *
5371  * Returns 0 for success, non-zero for failure.
5372  *
5373  */
5374 static int _base_assign_fw_reported_qd(struct MPT3SAS_ADAPTER *ioc)
5375 {
5376 	Mpi2ConfigReply_t mpi_reply;
5377 	Mpi2SasIOUnitPage1_t *sas_iounit_pg1 = NULL;
5378 	Mpi26PCIeIOUnitPage1_t pcie_iounit_pg1;
5379 	u16 depth;
5380 	int sz;
5381 	int rc = 0;
5382 
5383 	ioc->max_wideport_qd = MPT3SAS_SAS_QUEUE_DEPTH;
5384 	ioc->max_narrowport_qd = MPT3SAS_SAS_QUEUE_DEPTH;
5385 	ioc->max_sata_qd = MPT3SAS_SATA_QUEUE_DEPTH;
5386 	ioc->max_nvme_qd = MPT3SAS_NVME_QUEUE_DEPTH;
5387 	if (!ioc->is_gen35_ioc)
5388 		goto out;
5389 	/* sas iounit page 1 */
5390 	sz = offsetof(Mpi2SasIOUnitPage1_t, PhyData);
5391 	sas_iounit_pg1 = kzalloc(sizeof(Mpi2SasIOUnitPage1_t), GFP_KERNEL);
5392 	if (!sas_iounit_pg1) {
5393 		pr_err("%s: failure at %s:%d/%s()!\n",
5394 		    ioc->name, __FILE__, __LINE__, __func__);
5395 		return rc;
5396 	}
5397 	rc = mpt3sas_config_get_sas_iounit_pg1(ioc, &mpi_reply,
5398 	    sas_iounit_pg1, sz);
5399 	if (rc) {
5400 		pr_err("%s: failure at %s:%d/%s()!\n",
5401 		    ioc->name, __FILE__, __LINE__, __func__);
5402 		goto out;
5403 	}
5404 
5405 	depth = le16_to_cpu(sas_iounit_pg1->SASWideMaxQueueDepth);
5406 	ioc->max_wideport_qd = (depth ? depth : MPT3SAS_SAS_QUEUE_DEPTH);
5407 
5408 	depth = le16_to_cpu(sas_iounit_pg1->SASNarrowMaxQueueDepth);
5409 	ioc->max_narrowport_qd = (depth ? depth : MPT3SAS_SAS_QUEUE_DEPTH);
5410 
5411 	depth = sas_iounit_pg1->SATAMaxQDepth;
5412 	ioc->max_sata_qd = (depth ? depth : MPT3SAS_SATA_QUEUE_DEPTH);
5413 
5414 	/* pcie iounit page 1 */
5415 	rc = mpt3sas_config_get_pcie_iounit_pg1(ioc, &mpi_reply,
5416 	    &pcie_iounit_pg1, sizeof(Mpi26PCIeIOUnitPage1_t));
5417 	if (rc) {
5418 		pr_err("%s: failure at %s:%d/%s()!\n",
5419 		    ioc->name, __FILE__, __LINE__, __func__);
5420 		goto out;
5421 	}
5422 	ioc->max_nvme_qd = (le16_to_cpu(pcie_iounit_pg1.NVMeMaxQueueDepth)) ?
5423 	    (le16_to_cpu(pcie_iounit_pg1.NVMeMaxQueueDepth)) :
5424 	    MPT3SAS_NVME_QUEUE_DEPTH;
5425 out:
5426 	dinitprintk(ioc, pr_err(
5427 	    "MaxWidePortQD: 0x%x MaxNarrowPortQD: 0x%x MaxSataQD: 0x%x MaxNvmeQD: 0x%x\n",
5428 	    ioc->max_wideport_qd, ioc->max_narrowport_qd,
5429 	    ioc->max_sata_qd, ioc->max_nvme_qd));
5430 	kfree(sas_iounit_pg1);
5431 	return rc;
5432 }
5433 
5434 /**
5435  * mpt3sas_atto_validate_nvram - validate the ATTO nvram read from mfg pg1
5436  *
5437  * @ioc : per adapter object
5438  * @n   : ptr to the ATTO nvram structure
5439  * Return: 0 for success, non-zero for failure.
5440  */
5441 static int
5442 mpt3sas_atto_validate_nvram(struct MPT3SAS_ADAPTER *ioc,
5443 			    struct ATTO_SAS_NVRAM *n)
5444 {
5445 	int r = -EINVAL;
5446 	union ATTO_SAS_ADDRESS *s1;
5447 	u32 len;
5448 	u8 *pb;
5449 	u8 ckSum;
5450 
5451 	/* validate nvram checksum */
5452 	pb = (u8 *) n;
5453 	ckSum = ATTO_SASNVR_CKSUM_SEED;
5454 	len = sizeof(struct ATTO_SAS_NVRAM);
5455 
5456 	while (len--)
5457 		ckSum = ckSum + pb[len];
5458 
5459 	if (ckSum) {
5460 		ioc_err(ioc, "Invalid ATTO NVRAM checksum\n");
5461 		return r;
5462 	}
5463 
5464 	s1 = (union ATTO_SAS_ADDRESS *) n->SasAddr;
5465 
5466 	if (n->Signature[0] != 'E'
5467 	|| n->Signature[1] != 'S'
5468 	|| n->Signature[2] != 'A'
5469 	|| n->Signature[3] != 'S')
5470 		ioc_err(ioc, "Invalid ATTO NVRAM signature\n");
5471 	else if (n->Version > ATTO_SASNVR_VERSION)
5472 		ioc_info(ioc, "Invalid ATTO NVRAM version");
5473 	else if ((n->SasAddr[7] & (ATTO_SAS_ADDR_ALIGN - 1))
5474 			|| s1->b[0] != 0x50
5475 			|| s1->b[1] != 0x01
5476 			|| s1->b[2] != 0x08
5477 			|| (s1->b[3] & 0xF0) != 0x60
5478 			|| ((s1->b[3] & 0x0F) | le32_to_cpu(s1->d[1])) == 0) {
5479 		ioc_err(ioc, "Invalid ATTO SAS address\n");
5480 	} else
5481 		r = 0;
5482 	return r;
5483 }
5484 
5485 /**
5486  * mpt3sas_atto_get_sas_addr - get the ATTO SAS address from mfg page 1
5487  *
5488  * @ioc : per adapter object
5489  * @*sas_addr : return sas address
5490  * Return: 0 for success, non-zero for failure.
5491  */
5492 static int
5493 mpt3sas_atto_get_sas_addr(struct MPT3SAS_ADAPTER *ioc, union ATTO_SAS_ADDRESS *sas_addr)
5494 {
5495 	Mpi2ManufacturingPage1_t mfg_pg1;
5496 	Mpi2ConfigReply_t mpi_reply;
5497 	struct ATTO_SAS_NVRAM *nvram;
5498 	int r;
5499 	__be64 addr;
5500 
5501 	r = mpt3sas_config_get_manufacturing_pg1(ioc, &mpi_reply, &mfg_pg1);
5502 	if (r) {
5503 		ioc_err(ioc, "Failed to read manufacturing page 1\n");
5504 		return r;
5505 	}
5506 
5507 	/* validate nvram */
5508 	nvram = (struct ATTO_SAS_NVRAM *) mfg_pg1.VPD;
5509 	r = mpt3sas_atto_validate_nvram(ioc, nvram);
5510 	if (r)
5511 		return r;
5512 
5513 	addr = *((__be64 *) nvram->SasAddr);
5514 	sas_addr->q = cpu_to_le64(be64_to_cpu(addr));
5515 	return r;
5516 }
5517 
5518 /**
5519  * mpt3sas_atto_init - perform initializaion for ATTO branded
5520  *					adapter.
5521  * @ioc : per adapter object
5522  *5
5523  * Return: 0 for success, non-zero for failure.
5524  */
5525 static int
5526 mpt3sas_atto_init(struct MPT3SAS_ADAPTER *ioc)
5527 {
5528 	int sz = 0;
5529 	Mpi2BiosPage4_t *bios_pg4 = NULL;
5530 	Mpi2ConfigReply_t mpi_reply;
5531 	int r;
5532 	int ix;
5533 	union ATTO_SAS_ADDRESS sas_addr;
5534 	union ATTO_SAS_ADDRESS temp;
5535 	union ATTO_SAS_ADDRESS bias;
5536 
5537 	r = mpt3sas_atto_get_sas_addr(ioc, &sas_addr);
5538 	if (r)
5539 		return r;
5540 
5541 	/* get header first to get size */
5542 	r = mpt3sas_config_get_bios_pg4(ioc, &mpi_reply, NULL, 0);
5543 	if (r) {
5544 		ioc_err(ioc, "Failed to read ATTO bios page 4 header.\n");
5545 		return r;
5546 	}
5547 
5548 	sz = mpi_reply.Header.PageLength * sizeof(u32);
5549 	bios_pg4 = kzalloc(sz, GFP_KERNEL);
5550 	if (!bios_pg4) {
5551 		ioc_err(ioc, "Failed to allocate memory for ATTO bios page.\n");
5552 		return -ENOMEM;
5553 	}
5554 
5555 	/* read bios page 4 */
5556 	r = mpt3sas_config_get_bios_pg4(ioc, &mpi_reply, bios_pg4, sz);
5557 	if (r) {
5558 		ioc_err(ioc, "Failed to read ATTO bios page 4\n");
5559 		goto out;
5560 	}
5561 
5562 	/* Update bios page 4 with the ATTO WWID */
5563 	bias.q = sas_addr.q;
5564 	bias.b[7] += ATTO_SAS_ADDR_DEVNAME_BIAS;
5565 
5566 	for (ix = 0; ix < bios_pg4->NumPhys; ix++) {
5567 		temp.q = sas_addr.q;
5568 		temp.b[7] += ix;
5569 		bios_pg4->Phy[ix].ReassignmentWWID = temp.q;
5570 		bios_pg4->Phy[ix].ReassignmentDeviceName = bias.q;
5571 	}
5572 	r = mpt3sas_config_set_bios_pg4(ioc, &mpi_reply, bios_pg4, sz);
5573 
5574 out:
5575 	kfree(bios_pg4);
5576 	return r;
5577 }
5578 
5579 /**
5580  * _base_static_config_pages - static start of day config pages
5581  * @ioc: per adapter object
5582  */
5583 static int
5584 _base_static_config_pages(struct MPT3SAS_ADAPTER *ioc)
5585 {
5586 	Mpi2ConfigReply_t mpi_reply;
5587 	u32 iounit_pg1_flags;
5588 	int tg_flags = 0;
5589 	int rc;
5590 	ioc->nvme_abort_timeout = 30;
5591 
5592 	rc = mpt3sas_config_get_manufacturing_pg0(ioc, &mpi_reply,
5593 	    &ioc->manu_pg0);
5594 	if (rc)
5595 		return rc;
5596 	if (ioc->ir_firmware) {
5597 		rc = mpt3sas_config_get_manufacturing_pg10(ioc, &mpi_reply,
5598 		    &ioc->manu_pg10);
5599 		if (rc)
5600 			return rc;
5601 	}
5602 
5603 	if (ioc->pdev->vendor == MPI2_MFGPAGE_VENDORID_ATTO) {
5604 		rc = mpt3sas_atto_init(ioc);
5605 		if (rc)
5606 			return rc;
5607 	}
5608 
5609 	/*
5610 	 * Ensure correct T10 PI operation if vendor left EEDPTagMode
5611 	 * flag unset in NVDATA.
5612 	 */
5613 	rc = mpt3sas_config_get_manufacturing_pg11(ioc, &mpi_reply,
5614 	    &ioc->manu_pg11);
5615 	if (rc)
5616 		return rc;
5617 	if (!ioc->is_gen35_ioc && ioc->manu_pg11.EEDPTagMode == 0) {
5618 		pr_err("%s: overriding NVDATA EEDPTagMode setting\n",
5619 		    ioc->name);
5620 		ioc->manu_pg11.EEDPTagMode &= ~0x3;
5621 		ioc->manu_pg11.EEDPTagMode |= 0x1;
5622 		mpt3sas_config_set_manufacturing_pg11(ioc, &mpi_reply,
5623 		    &ioc->manu_pg11);
5624 	}
5625 	if (ioc->manu_pg11.AddlFlags2 & NVME_TASK_MNGT_CUSTOM_MASK)
5626 		ioc->tm_custom_handling = 1;
5627 	else {
5628 		ioc->tm_custom_handling = 0;
5629 		if (ioc->manu_pg11.NVMeAbortTO < NVME_TASK_ABORT_MIN_TIMEOUT)
5630 			ioc->nvme_abort_timeout = NVME_TASK_ABORT_MIN_TIMEOUT;
5631 		else if (ioc->manu_pg11.NVMeAbortTO >
5632 					NVME_TASK_ABORT_MAX_TIMEOUT)
5633 			ioc->nvme_abort_timeout = NVME_TASK_ABORT_MAX_TIMEOUT;
5634 		else
5635 			ioc->nvme_abort_timeout = ioc->manu_pg11.NVMeAbortTO;
5636 	}
5637 	ioc->time_sync_interval =
5638 	    ioc->manu_pg11.TimeSyncInterval & MPT3SAS_TIMESYNC_MASK;
5639 	if (ioc->time_sync_interval) {
5640 		if (ioc->manu_pg11.TimeSyncInterval & MPT3SAS_TIMESYNC_UNIT_MASK)
5641 			ioc->time_sync_interval =
5642 			    ioc->time_sync_interval * SECONDS_PER_HOUR;
5643 		else
5644 			ioc->time_sync_interval =
5645 			    ioc->time_sync_interval * SECONDS_PER_MIN;
5646 		dinitprintk(ioc, ioc_info(ioc,
5647 		    "Driver-FW TimeSync interval is %d seconds. ManuPg11 TimeSync Unit is in %s\n",
5648 		    ioc->time_sync_interval, (ioc->manu_pg11.TimeSyncInterval &
5649 		    MPT3SAS_TIMESYNC_UNIT_MASK) ? "Hour" : "Minute"));
5650 	} else {
5651 		if (ioc->is_gen35_ioc)
5652 			ioc_warn(ioc,
5653 			    "TimeSync Interval in Manuf page-11 is not enabled. Periodic Time-Sync will be disabled\n");
5654 	}
5655 	rc = _base_assign_fw_reported_qd(ioc);
5656 	if (rc)
5657 		return rc;
5658 
5659 	/*
5660 	 * ATTO doesn't use bios page 2 and 3 for bios settings.
5661 	 */
5662 	if (ioc->pdev->vendor ==  MPI2_MFGPAGE_VENDORID_ATTO)
5663 		ioc->bios_pg3.BiosVersion = 0;
5664 	else {
5665 		rc = mpt3sas_config_get_bios_pg2(ioc, &mpi_reply, &ioc->bios_pg2);
5666 		if (rc)
5667 			return rc;
5668 		rc = mpt3sas_config_get_bios_pg3(ioc, &mpi_reply, &ioc->bios_pg3);
5669 		if (rc)
5670 			return rc;
5671 	}
5672 
5673 	rc = mpt3sas_config_get_ioc_pg8(ioc, &mpi_reply, &ioc->ioc_pg8);
5674 	if (rc)
5675 		return rc;
5676 	rc = mpt3sas_config_get_iounit_pg0(ioc, &mpi_reply, &ioc->iounit_pg0);
5677 	if (rc)
5678 		return rc;
5679 	rc = mpt3sas_config_get_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
5680 	if (rc)
5681 		return rc;
5682 	rc = mpt3sas_config_get_iounit_pg8(ioc, &mpi_reply, &ioc->iounit_pg8);
5683 	if (rc)
5684 		return rc;
5685 	_base_display_ioc_capabilities(ioc);
5686 
5687 	/*
5688 	 * Enable task_set_full handling in iounit_pg1 when the
5689 	 * facts capabilities indicate that its supported.
5690 	 */
5691 	iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
5692 	if ((ioc->facts.IOCCapabilities &
5693 	    MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING))
5694 		iounit_pg1_flags &=
5695 		    ~MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
5696 	else
5697 		iounit_pg1_flags |=
5698 		    MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
5699 	ioc->iounit_pg1.Flags = cpu_to_le32(iounit_pg1_flags);
5700 	rc = mpt3sas_config_set_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
5701 	if (rc)
5702 		return rc;
5703 
5704 	if (ioc->iounit_pg8.NumSensors)
5705 		ioc->temp_sensors_count = ioc->iounit_pg8.NumSensors;
5706 	if (ioc->is_aero_ioc) {
5707 		rc = _base_update_ioc_page1_inlinewith_perf_mode(ioc);
5708 		if (rc)
5709 			return rc;
5710 	}
5711 	if (ioc->is_gen35_ioc) {
5712 		if (ioc->is_driver_loading) {
5713 			rc = _base_get_diag_triggers(ioc);
5714 			if (rc)
5715 				return rc;
5716 		} else {
5717 			/*
5718 			 * In case of online HBA FW update operation,
5719 			 * check whether updated FW supports the driver trigger
5720 			 * pages or not.
5721 			 * - If previous FW has not supported driver trigger
5722 			 *   pages and newer FW supports them then update these
5723 			 *   pages with current diag trigger values.
5724 			 * - If previous FW has supported driver trigger pages
5725 			 *   and new FW doesn't support them then disable
5726 			 *   support_trigger_pages flag.
5727 			 */
5728 			_base_check_for_trigger_pages_support(ioc, &tg_flags);
5729 			if (!ioc->supports_trigger_pages && tg_flags != -EFAULT)
5730 				_base_update_diag_trigger_pages(ioc);
5731 			else if (ioc->supports_trigger_pages &&
5732 			    tg_flags == -EFAULT)
5733 				ioc->supports_trigger_pages = 0;
5734 		}
5735 	}
5736 	return 0;
5737 }
5738 
5739 /**
5740  * mpt3sas_free_enclosure_list - release memory
5741  * @ioc: per adapter object
5742  *
5743  * Free memory allocated during enclosure add.
5744  */
5745 void
5746 mpt3sas_free_enclosure_list(struct MPT3SAS_ADAPTER *ioc)
5747 {
5748 	struct _enclosure_node *enclosure_dev, *enclosure_dev_next;
5749 
5750 	/* Free enclosure list */
5751 	list_for_each_entry_safe(enclosure_dev,
5752 			enclosure_dev_next, &ioc->enclosure_list, list) {
5753 		list_del(&enclosure_dev->list);
5754 		kfree(enclosure_dev);
5755 	}
5756 }
5757 
5758 /**
5759  * _base_release_memory_pools - release memory
5760  * @ioc: per adapter object
5761  *
5762  * Free memory allocated from _base_allocate_memory_pools.
5763  */
5764 static void
5765 _base_release_memory_pools(struct MPT3SAS_ADAPTER *ioc)
5766 {
5767 	int i = 0;
5768 	int j = 0;
5769 	int dma_alloc_count = 0;
5770 	struct chain_tracker *ct;
5771 	int count = ioc->rdpq_array_enable ? ioc->reply_queue_count : 1;
5772 
5773 	dexitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
5774 
5775 	if (ioc->request) {
5776 		dma_free_coherent(&ioc->pdev->dev, ioc->request_dma_sz,
5777 		    ioc->request,  ioc->request_dma);
5778 		dexitprintk(ioc,
5779 			    ioc_info(ioc, "request_pool(0x%p): free\n",
5780 				     ioc->request));
5781 		ioc->request = NULL;
5782 	}
5783 
5784 	if (ioc->sense) {
5785 		dma_pool_free(ioc->sense_dma_pool, ioc->sense, ioc->sense_dma);
5786 		dma_pool_destroy(ioc->sense_dma_pool);
5787 		dexitprintk(ioc,
5788 			    ioc_info(ioc, "sense_pool(0x%p): free\n",
5789 				     ioc->sense));
5790 		ioc->sense = NULL;
5791 	}
5792 
5793 	if (ioc->reply) {
5794 		dma_pool_free(ioc->reply_dma_pool, ioc->reply, ioc->reply_dma);
5795 		dma_pool_destroy(ioc->reply_dma_pool);
5796 		dexitprintk(ioc,
5797 			    ioc_info(ioc, "reply_pool(0x%p): free\n",
5798 				     ioc->reply));
5799 		ioc->reply = NULL;
5800 	}
5801 
5802 	if (ioc->reply_free) {
5803 		dma_pool_free(ioc->reply_free_dma_pool, ioc->reply_free,
5804 		    ioc->reply_free_dma);
5805 		dma_pool_destroy(ioc->reply_free_dma_pool);
5806 		dexitprintk(ioc,
5807 			    ioc_info(ioc, "reply_free_pool(0x%p): free\n",
5808 				     ioc->reply_free));
5809 		ioc->reply_free = NULL;
5810 	}
5811 
5812 	if (ioc->reply_post) {
5813 		dma_alloc_count = DIV_ROUND_UP(count,
5814 				RDPQ_MAX_INDEX_IN_ONE_CHUNK);
5815 		for (i = 0; i < count; i++) {
5816 			if (i % RDPQ_MAX_INDEX_IN_ONE_CHUNK == 0
5817 			    && dma_alloc_count) {
5818 				if (ioc->reply_post[i].reply_post_free) {
5819 					dma_pool_free(
5820 					    ioc->reply_post_free_dma_pool,
5821 					    ioc->reply_post[i].reply_post_free,
5822 					ioc->reply_post[i].reply_post_free_dma);
5823 					dexitprintk(ioc, ioc_info(ioc,
5824 					   "reply_post_free_pool(0x%p): free\n",
5825 					   ioc->reply_post[i].reply_post_free));
5826 					ioc->reply_post[i].reply_post_free =
5827 									NULL;
5828 				}
5829 				--dma_alloc_count;
5830 			}
5831 		}
5832 		dma_pool_destroy(ioc->reply_post_free_dma_pool);
5833 		if (ioc->reply_post_free_array &&
5834 			ioc->rdpq_array_enable) {
5835 			dma_pool_free(ioc->reply_post_free_array_dma_pool,
5836 			    ioc->reply_post_free_array,
5837 			    ioc->reply_post_free_array_dma);
5838 			ioc->reply_post_free_array = NULL;
5839 		}
5840 		dma_pool_destroy(ioc->reply_post_free_array_dma_pool);
5841 		kfree(ioc->reply_post);
5842 	}
5843 
5844 	if (ioc->pcie_sgl_dma_pool) {
5845 		for (i = 0; i < ioc->scsiio_depth; i++) {
5846 			dma_pool_free(ioc->pcie_sgl_dma_pool,
5847 					ioc->pcie_sg_lookup[i].pcie_sgl,
5848 					ioc->pcie_sg_lookup[i].pcie_sgl_dma);
5849 			ioc->pcie_sg_lookup[i].pcie_sgl = NULL;
5850 		}
5851 		dma_pool_destroy(ioc->pcie_sgl_dma_pool);
5852 	}
5853 	if (ioc->config_page) {
5854 		dexitprintk(ioc,
5855 			    ioc_info(ioc, "config_page(0x%p): free\n",
5856 				     ioc->config_page));
5857 		dma_free_coherent(&ioc->pdev->dev, ioc->config_page_sz,
5858 		    ioc->config_page, ioc->config_page_dma);
5859 	}
5860 
5861 	kfree(ioc->hpr_lookup);
5862 	ioc->hpr_lookup = NULL;
5863 	kfree(ioc->internal_lookup);
5864 	ioc->internal_lookup = NULL;
5865 	if (ioc->chain_lookup) {
5866 		for (i = 0; i < ioc->scsiio_depth; i++) {
5867 			for (j = ioc->chains_per_prp_buffer;
5868 			    j < ioc->chains_needed_per_io; j++) {
5869 				ct = &ioc->chain_lookup[i].chains_per_smid[j];
5870 				if (ct && ct->chain_buffer)
5871 					dma_pool_free(ioc->chain_dma_pool,
5872 						ct->chain_buffer,
5873 						ct->chain_buffer_dma);
5874 			}
5875 			kfree(ioc->chain_lookup[i].chains_per_smid);
5876 		}
5877 		dma_pool_destroy(ioc->chain_dma_pool);
5878 		kfree(ioc->chain_lookup);
5879 		ioc->chain_lookup = NULL;
5880 	}
5881 
5882 	kfree(ioc->io_queue_num);
5883 	ioc->io_queue_num = NULL;
5884 }
5885 
5886 /**
5887  * mpt3sas_check_same_4gb_region - checks whether all reply queues in a set are
5888  *	having same upper 32bits in their base memory address.
5889  * @start_address: Base address of a reply queue set
5890  * @pool_sz: Size of single Reply Descriptor Post Queues pool size
5891  *
5892  * Return: 1 if reply queues in a set have a same upper 32bits in their base
5893  * memory address, else 0.
5894  */
5895 static int
5896 mpt3sas_check_same_4gb_region(dma_addr_t start_address, u32 pool_sz)
5897 {
5898 	dma_addr_t end_address;
5899 
5900 	end_address = start_address + pool_sz - 1;
5901 
5902 	if (upper_32_bits(start_address) == upper_32_bits(end_address))
5903 		return 1;
5904 	else
5905 		return 0;
5906 }
5907 
5908 /**
5909  * _base_reduce_hba_queue_depth- Retry with reduced queue depth
5910  * @ioc: Adapter object
5911  *
5912  * Return: 0 for success, non-zero for failure.
5913  **/
5914 static inline int
5915 _base_reduce_hba_queue_depth(struct MPT3SAS_ADAPTER *ioc)
5916 {
5917 	int reduce_sz = 64;
5918 
5919 	if ((ioc->hba_queue_depth - reduce_sz) >
5920 	    (ioc->internal_depth + INTERNAL_SCSIIO_CMDS_COUNT)) {
5921 		ioc->hba_queue_depth -= reduce_sz;
5922 		return 0;
5923 	} else
5924 		return -ENOMEM;
5925 }
5926 
5927 /**
5928  * _base_allocate_pcie_sgl_pool - Allocating DMA'able memory
5929  *			for pcie sgl pools.
5930  * @ioc: Adapter object
5931  * @sz: DMA Pool size
5932  *
5933  * Return: 0 for success, non-zero for failure.
5934  */
5935 
5936 static int
5937 _base_allocate_pcie_sgl_pool(struct MPT3SAS_ADAPTER *ioc, u32 sz)
5938 {
5939 	int i = 0, j = 0;
5940 	struct chain_tracker *ct;
5941 
5942 	ioc->pcie_sgl_dma_pool =
5943 	    dma_pool_create("PCIe SGL pool", &ioc->pdev->dev, sz,
5944 	    ioc->page_size, 0);
5945 	if (!ioc->pcie_sgl_dma_pool) {
5946 		ioc_err(ioc, "PCIe SGL pool: dma_pool_create failed\n");
5947 		return -ENOMEM;
5948 	}
5949 
5950 	ioc->chains_per_prp_buffer = sz/ioc->chain_segment_sz;
5951 	ioc->chains_per_prp_buffer =
5952 	    min(ioc->chains_per_prp_buffer, ioc->chains_needed_per_io);
5953 	for (i = 0; i < ioc->scsiio_depth; i++) {
5954 		ioc->pcie_sg_lookup[i].pcie_sgl =
5955 		    dma_pool_alloc(ioc->pcie_sgl_dma_pool, GFP_KERNEL,
5956 		    &ioc->pcie_sg_lookup[i].pcie_sgl_dma);
5957 		if (!ioc->pcie_sg_lookup[i].pcie_sgl) {
5958 			ioc_err(ioc, "PCIe SGL pool: dma_pool_alloc failed\n");
5959 			return -EAGAIN;
5960 		}
5961 
5962 		if (!mpt3sas_check_same_4gb_region(
5963 		    ioc->pcie_sg_lookup[i].pcie_sgl_dma, sz)) {
5964 			ioc_err(ioc, "PCIE SGLs are not in same 4G !! pcie sgl (0x%p) dma = (0x%llx)\n",
5965 			    ioc->pcie_sg_lookup[i].pcie_sgl,
5966 			    (unsigned long long)
5967 			    ioc->pcie_sg_lookup[i].pcie_sgl_dma);
5968 			ioc->use_32bit_dma = true;
5969 			return -EAGAIN;
5970 		}
5971 
5972 		for (j = 0; j < ioc->chains_per_prp_buffer; j++) {
5973 			ct = &ioc->chain_lookup[i].chains_per_smid[j];
5974 			ct->chain_buffer =
5975 			    ioc->pcie_sg_lookup[i].pcie_sgl +
5976 			    (j * ioc->chain_segment_sz);
5977 			ct->chain_buffer_dma =
5978 			    ioc->pcie_sg_lookup[i].pcie_sgl_dma +
5979 			    (j * ioc->chain_segment_sz);
5980 		}
5981 	}
5982 	dinitprintk(ioc, ioc_info(ioc,
5983 	    "PCIe sgl pool depth(%d), element_size(%d), pool_size(%d kB)\n",
5984 	    ioc->scsiio_depth, sz, (sz * ioc->scsiio_depth)/1024));
5985 	dinitprintk(ioc, ioc_info(ioc,
5986 	    "Number of chains can fit in a PRP page(%d)\n",
5987 	    ioc->chains_per_prp_buffer));
5988 	return 0;
5989 }
5990 
5991 /**
5992  * _base_allocate_chain_dma_pool - Allocating DMA'able memory
5993  *			for chain dma pool.
5994  * @ioc: Adapter object
5995  * @sz: DMA Pool size
5996  *
5997  * Return: 0 for success, non-zero for failure.
5998  */
5999 static int
6000 _base_allocate_chain_dma_pool(struct MPT3SAS_ADAPTER *ioc, u32 sz)
6001 {
6002 	int i = 0, j = 0;
6003 	struct chain_tracker *ctr;
6004 
6005 	ioc->chain_dma_pool = dma_pool_create("chain pool", &ioc->pdev->dev,
6006 	    ioc->chain_segment_sz, 16, 0);
6007 	if (!ioc->chain_dma_pool)
6008 		return -ENOMEM;
6009 
6010 	for (i = 0; i < ioc->scsiio_depth; i++) {
6011 		for (j = ioc->chains_per_prp_buffer;
6012 		    j < ioc->chains_needed_per_io; j++) {
6013 			ctr = &ioc->chain_lookup[i].chains_per_smid[j];
6014 			ctr->chain_buffer = dma_pool_alloc(ioc->chain_dma_pool,
6015 			    GFP_KERNEL, &ctr->chain_buffer_dma);
6016 			if (!ctr->chain_buffer)
6017 				return -EAGAIN;
6018 			if (!mpt3sas_check_same_4gb_region(
6019 			    ctr->chain_buffer_dma, ioc->chain_segment_sz)) {
6020 				ioc_err(ioc,
6021 				    "Chain buffers are not in same 4G !!! Chain buff (0x%p) dma = (0x%llx)\n",
6022 				    ctr->chain_buffer,
6023 				    (unsigned long long)ctr->chain_buffer_dma);
6024 				ioc->use_32bit_dma = true;
6025 				return -EAGAIN;
6026 			}
6027 		}
6028 	}
6029 	dinitprintk(ioc, ioc_info(ioc,
6030 	    "chain_lookup depth (%d), frame_size(%d), pool_size(%d kB)\n",
6031 	    ioc->scsiio_depth, ioc->chain_segment_sz, ((ioc->scsiio_depth *
6032 	    (ioc->chains_needed_per_io - ioc->chains_per_prp_buffer) *
6033 	    ioc->chain_segment_sz))/1024));
6034 	return 0;
6035 }
6036 
6037 /**
6038  * _base_allocate_sense_dma_pool - Allocating DMA'able memory
6039  *			for sense dma pool.
6040  * @ioc: Adapter object
6041  * @sz: DMA Pool size
6042  * Return: 0 for success, non-zero for failure.
6043  */
6044 static int
6045 _base_allocate_sense_dma_pool(struct MPT3SAS_ADAPTER *ioc, u32 sz)
6046 {
6047 	ioc->sense_dma_pool =
6048 	    dma_pool_create("sense pool", &ioc->pdev->dev, sz, 4, 0);
6049 	if (!ioc->sense_dma_pool)
6050 		return -ENOMEM;
6051 	ioc->sense = dma_pool_alloc(ioc->sense_dma_pool,
6052 	    GFP_KERNEL, &ioc->sense_dma);
6053 	if (!ioc->sense)
6054 		return -EAGAIN;
6055 	if (!mpt3sas_check_same_4gb_region(ioc->sense_dma, sz)) {
6056 		dinitprintk(ioc, pr_err(
6057 		    "Bad Sense Pool! sense (0x%p) sense_dma = (0x%llx)\n",
6058 		    ioc->sense, (unsigned long long) ioc->sense_dma));
6059 		ioc->use_32bit_dma = true;
6060 		return -EAGAIN;
6061 	}
6062 	ioc_info(ioc,
6063 	    "sense pool(0x%p) - dma(0x%llx): depth(%d), element_size(%d), pool_size (%d kB)\n",
6064 	    ioc->sense, (unsigned long long)ioc->sense_dma,
6065 	    ioc->scsiio_depth, SCSI_SENSE_BUFFERSIZE, sz/1024);
6066 	return 0;
6067 }
6068 
6069 /**
6070  * _base_allocate_reply_pool - Allocating DMA'able memory
6071  *			for reply pool.
6072  * @ioc: Adapter object
6073  * @sz: DMA Pool size
6074  * Return: 0 for success, non-zero for failure.
6075  */
6076 static int
6077 _base_allocate_reply_pool(struct MPT3SAS_ADAPTER *ioc, u32 sz)
6078 {
6079 	/* reply pool, 4 byte align */
6080 	ioc->reply_dma_pool = dma_pool_create("reply pool",
6081 	    &ioc->pdev->dev, sz, 4, 0);
6082 	if (!ioc->reply_dma_pool)
6083 		return -ENOMEM;
6084 	ioc->reply = dma_pool_alloc(ioc->reply_dma_pool, GFP_KERNEL,
6085 	    &ioc->reply_dma);
6086 	if (!ioc->reply)
6087 		return -EAGAIN;
6088 	if (!mpt3sas_check_same_4gb_region(ioc->reply_dma, sz)) {
6089 		dinitprintk(ioc, pr_err(
6090 		    "Bad Reply Pool! Reply (0x%p) Reply dma = (0x%llx)\n",
6091 		    ioc->reply, (unsigned long long) ioc->reply_dma));
6092 		ioc->use_32bit_dma = true;
6093 		return -EAGAIN;
6094 	}
6095 	ioc->reply_dma_min_address = (u32)(ioc->reply_dma);
6096 	ioc->reply_dma_max_address = (u32)(ioc->reply_dma) + sz;
6097 	ioc_info(ioc,
6098 	    "reply pool(0x%p) - dma(0x%llx): depth(%d), frame_size(%d), pool_size(%d kB)\n",
6099 	    ioc->reply, (unsigned long long)ioc->reply_dma,
6100 	    ioc->reply_free_queue_depth, ioc->reply_sz, sz/1024);
6101 	return 0;
6102 }
6103 
6104 /**
6105  * _base_allocate_reply_free_dma_pool - Allocating DMA'able memory
6106  *			for reply free dma pool.
6107  * @ioc: Adapter object
6108  * @sz: DMA Pool size
6109  * Return: 0 for success, non-zero for failure.
6110  */
6111 static int
6112 _base_allocate_reply_free_dma_pool(struct MPT3SAS_ADAPTER *ioc, u32 sz)
6113 {
6114 	/* reply free queue, 16 byte align */
6115 	ioc->reply_free_dma_pool = dma_pool_create(
6116 	    "reply_free pool", &ioc->pdev->dev, sz, 16, 0);
6117 	if (!ioc->reply_free_dma_pool)
6118 		return -ENOMEM;
6119 	ioc->reply_free = dma_pool_alloc(ioc->reply_free_dma_pool,
6120 	    GFP_KERNEL, &ioc->reply_free_dma);
6121 	if (!ioc->reply_free)
6122 		return -EAGAIN;
6123 	if (!mpt3sas_check_same_4gb_region(ioc->reply_free_dma, sz)) {
6124 		dinitprintk(ioc,
6125 		    pr_err("Bad Reply Free Pool! Reply Free (0x%p) Reply Free dma = (0x%llx)\n",
6126 		    ioc->reply_free, (unsigned long long) ioc->reply_free_dma));
6127 		ioc->use_32bit_dma = true;
6128 		return -EAGAIN;
6129 	}
6130 	memset(ioc->reply_free, 0, sz);
6131 	dinitprintk(ioc, ioc_info(ioc,
6132 	    "reply_free pool(0x%p): depth(%d), element_size(%d), pool_size(%d kB)\n",
6133 	    ioc->reply_free, ioc->reply_free_queue_depth, 4, sz/1024));
6134 	dinitprintk(ioc, ioc_info(ioc,
6135 	    "reply_free_dma (0x%llx)\n",
6136 	    (unsigned long long)ioc->reply_free_dma));
6137 	return 0;
6138 }
6139 
6140 /**
6141  * _base_allocate_reply_post_free_array - Allocating DMA'able memory
6142  *			for reply post free array.
6143  * @ioc: Adapter object
6144  * @reply_post_free_array_sz: DMA Pool size
6145  * Return: 0 for success, non-zero for failure.
6146  */
6147 
6148 static int
6149 _base_allocate_reply_post_free_array(struct MPT3SAS_ADAPTER *ioc,
6150 	u32 reply_post_free_array_sz)
6151 {
6152 	ioc->reply_post_free_array_dma_pool =
6153 	    dma_pool_create("reply_post_free_array pool",
6154 	    &ioc->pdev->dev, reply_post_free_array_sz, 16, 0);
6155 	if (!ioc->reply_post_free_array_dma_pool)
6156 		return -ENOMEM;
6157 	ioc->reply_post_free_array =
6158 	    dma_pool_alloc(ioc->reply_post_free_array_dma_pool,
6159 	    GFP_KERNEL, &ioc->reply_post_free_array_dma);
6160 	if (!ioc->reply_post_free_array)
6161 		return -EAGAIN;
6162 	if (!mpt3sas_check_same_4gb_region(ioc->reply_post_free_array_dma,
6163 	    reply_post_free_array_sz)) {
6164 		dinitprintk(ioc, pr_err(
6165 		    "Bad Reply Free Pool! Reply Free (0x%p) Reply Free dma = (0x%llx)\n",
6166 		    ioc->reply_free,
6167 		    (unsigned long long) ioc->reply_free_dma));
6168 		ioc->use_32bit_dma = true;
6169 		return -EAGAIN;
6170 	}
6171 	return 0;
6172 }
6173 /**
6174  * base_alloc_rdpq_dma_pool - Allocating DMA'able memory
6175  *                     for reply queues.
6176  * @ioc: per adapter object
6177  * @sz: DMA Pool size
6178  * Return: 0 for success, non-zero for failure.
6179  */
6180 static int
6181 base_alloc_rdpq_dma_pool(struct MPT3SAS_ADAPTER *ioc, int sz)
6182 {
6183 	int i = 0;
6184 	u32 dma_alloc_count = 0;
6185 	int reply_post_free_sz = ioc->reply_post_queue_depth *
6186 		sizeof(Mpi2DefaultReplyDescriptor_t);
6187 	int count = ioc->rdpq_array_enable ? ioc->reply_queue_count : 1;
6188 
6189 	ioc->reply_post = kcalloc(count, sizeof(struct reply_post_struct),
6190 			GFP_KERNEL);
6191 	if (!ioc->reply_post)
6192 		return -ENOMEM;
6193 	/*
6194 	 *  For INVADER_SERIES each set of 8 reply queues(0-7, 8-15, ..) and
6195 	 *  VENTURA_SERIES each set of 16 reply queues(0-15, 16-31, ..) should
6196 	 *  be within 4GB boundary i.e reply queues in a set must have same
6197 	 *  upper 32-bits in their memory address. so here driver is allocating
6198 	 *  the DMA'able memory for reply queues according.
6199 	 *  Driver uses limitation of
6200 	 *  VENTURA_SERIES to manage INVADER_SERIES as well.
6201 	 */
6202 	dma_alloc_count = DIV_ROUND_UP(count,
6203 				RDPQ_MAX_INDEX_IN_ONE_CHUNK);
6204 	ioc->reply_post_free_dma_pool =
6205 		dma_pool_create("reply_post_free pool",
6206 		    &ioc->pdev->dev, sz, 16, 0);
6207 	if (!ioc->reply_post_free_dma_pool)
6208 		return -ENOMEM;
6209 	for (i = 0; i < count; i++) {
6210 		if ((i % RDPQ_MAX_INDEX_IN_ONE_CHUNK == 0) && dma_alloc_count) {
6211 			ioc->reply_post[i].reply_post_free =
6212 			    dma_pool_zalloc(ioc->reply_post_free_dma_pool,
6213 				GFP_KERNEL,
6214 				&ioc->reply_post[i].reply_post_free_dma);
6215 			if (!ioc->reply_post[i].reply_post_free)
6216 				return -ENOMEM;
6217 			/*
6218 			 * Each set of RDPQ pool must satisfy 4gb boundary
6219 			 * restriction.
6220 			 * 1) Check if allocated resources for RDPQ pool are in
6221 			 *	the same 4GB range.
6222 			 * 2) If #1 is true, continue with 64 bit DMA.
6223 			 * 3) If #1 is false, return 1. which means free all the
6224 			 * resources and set DMA mask to 32 and allocate.
6225 			 */
6226 			if (!mpt3sas_check_same_4gb_region(
6227 				ioc->reply_post[i].reply_post_free_dma, sz)) {
6228 				dinitprintk(ioc,
6229 				    ioc_err(ioc, "bad Replypost free pool(0x%p)"
6230 				    "reply_post_free_dma = (0x%llx)\n",
6231 				    ioc->reply_post[i].reply_post_free,
6232 				    (unsigned long long)
6233 				    ioc->reply_post[i].reply_post_free_dma));
6234 				return -EAGAIN;
6235 			}
6236 			dma_alloc_count--;
6237 
6238 		} else {
6239 			ioc->reply_post[i].reply_post_free =
6240 			    (Mpi2ReplyDescriptorsUnion_t *)
6241 			    ((long)ioc->reply_post[i-1].reply_post_free
6242 			    + reply_post_free_sz);
6243 			ioc->reply_post[i].reply_post_free_dma =
6244 			    (dma_addr_t)
6245 			    (ioc->reply_post[i-1].reply_post_free_dma +
6246 			    reply_post_free_sz);
6247 		}
6248 	}
6249 	return 0;
6250 }
6251 
6252 /**
6253  * _base_allocate_memory_pools - allocate start of day memory pools
6254  * @ioc: per adapter object
6255  *
6256  * Return: 0 success, anything else error.
6257  */
6258 static int
6259 _base_allocate_memory_pools(struct MPT3SAS_ADAPTER *ioc)
6260 {
6261 	struct mpt3sas_facts *facts;
6262 	u16 max_sge_elements;
6263 	u16 chains_needed_per_io;
6264 	u32 sz, total_sz, reply_post_free_sz, reply_post_free_array_sz;
6265 	u32 retry_sz;
6266 	u32 rdpq_sz = 0, sense_sz = 0;
6267 	u16 max_request_credit, nvme_blocks_needed;
6268 	unsigned short sg_tablesize;
6269 	u16 sge_size;
6270 	int i;
6271 	int ret = 0, rc = 0;
6272 
6273 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6274 
6275 
6276 	retry_sz = 0;
6277 	facts = &ioc->facts;
6278 
6279 	/* command line tunables for max sgl entries */
6280 	if (max_sgl_entries != -1)
6281 		sg_tablesize = max_sgl_entries;
6282 	else {
6283 		if (ioc->hba_mpi_version_belonged == MPI2_VERSION)
6284 			sg_tablesize = MPT2SAS_SG_DEPTH;
6285 		else
6286 			sg_tablesize = MPT3SAS_SG_DEPTH;
6287 	}
6288 
6289 	/* max sgl entries <= MPT_KDUMP_MIN_PHYS_SEGMENTS in KDUMP mode */
6290 	if (reset_devices)
6291 		sg_tablesize = min_t(unsigned short, sg_tablesize,
6292 		   MPT_KDUMP_MIN_PHYS_SEGMENTS);
6293 
6294 	if (ioc->is_mcpu_endpoint)
6295 		ioc->shost->sg_tablesize = MPT_MIN_PHYS_SEGMENTS;
6296 	else {
6297 		if (sg_tablesize < MPT_MIN_PHYS_SEGMENTS)
6298 			sg_tablesize = MPT_MIN_PHYS_SEGMENTS;
6299 		else if (sg_tablesize > MPT_MAX_PHYS_SEGMENTS) {
6300 			sg_tablesize = min_t(unsigned short, sg_tablesize,
6301 					SG_MAX_SEGMENTS);
6302 			ioc_warn(ioc, "sg_tablesize(%u) is bigger than kernel defined SG_CHUNK_SIZE(%u)\n",
6303 				 sg_tablesize, MPT_MAX_PHYS_SEGMENTS);
6304 		}
6305 		ioc->shost->sg_tablesize = sg_tablesize;
6306 	}
6307 
6308 	ioc->internal_depth = min_t(int, (facts->HighPriorityCredit + (5)),
6309 		(facts->RequestCredit / 4));
6310 	if (ioc->internal_depth < INTERNAL_CMDS_COUNT) {
6311 		if (facts->RequestCredit <= (INTERNAL_CMDS_COUNT +
6312 				INTERNAL_SCSIIO_CMDS_COUNT)) {
6313 			ioc_err(ioc, "IOC doesn't have enough Request Credits, it has just %d number of credits\n",
6314 				facts->RequestCredit);
6315 			return -ENOMEM;
6316 		}
6317 		ioc->internal_depth = 10;
6318 	}
6319 
6320 	ioc->hi_priority_depth = ioc->internal_depth - (5);
6321 	/* command line tunables  for max controller queue depth */
6322 	if (max_queue_depth != -1 && max_queue_depth != 0) {
6323 		max_request_credit = min_t(u16, max_queue_depth +
6324 			ioc->internal_depth, facts->RequestCredit);
6325 		if (max_request_credit > MAX_HBA_QUEUE_DEPTH)
6326 			max_request_credit =  MAX_HBA_QUEUE_DEPTH;
6327 	} else if (reset_devices)
6328 		max_request_credit = min_t(u16, facts->RequestCredit,
6329 		    (MPT3SAS_KDUMP_SCSI_IO_DEPTH + ioc->internal_depth));
6330 	else
6331 		max_request_credit = min_t(u16, facts->RequestCredit,
6332 		    MAX_HBA_QUEUE_DEPTH);
6333 
6334 	/* Firmware maintains additional facts->HighPriorityCredit number of
6335 	 * credits for HiPriprity Request messages, so hba queue depth will be
6336 	 * sum of max_request_credit and high priority queue depth.
6337 	 */
6338 	ioc->hba_queue_depth = max_request_credit + ioc->hi_priority_depth;
6339 
6340 	/* request frame size */
6341 	ioc->request_sz = facts->IOCRequestFrameSize * 4;
6342 
6343 	/* reply frame size */
6344 	ioc->reply_sz = facts->ReplyFrameSize * 4;
6345 
6346 	/* chain segment size */
6347 	if (ioc->hba_mpi_version_belonged != MPI2_VERSION) {
6348 		if (facts->IOCMaxChainSegmentSize)
6349 			ioc->chain_segment_sz =
6350 					facts->IOCMaxChainSegmentSize *
6351 					MAX_CHAIN_ELEMT_SZ;
6352 		else
6353 		/* set to 128 bytes size if IOCMaxChainSegmentSize is zero */
6354 			ioc->chain_segment_sz = DEFAULT_NUM_FWCHAIN_ELEMTS *
6355 						    MAX_CHAIN_ELEMT_SZ;
6356 	} else
6357 		ioc->chain_segment_sz = ioc->request_sz;
6358 
6359 	/* calculate the max scatter element size */
6360 	sge_size = max_t(u16, ioc->sge_size, ioc->sge_size_ieee);
6361 
6362  retry_allocation:
6363 	total_sz = 0;
6364 	/* calculate number of sg elements left over in the 1st frame */
6365 	max_sge_elements = ioc->request_sz - ((sizeof(Mpi2SCSIIORequest_t) -
6366 	    sizeof(Mpi2SGEIOUnion_t)) + sge_size);
6367 	ioc->max_sges_in_main_message = max_sge_elements/sge_size;
6368 
6369 	/* now do the same for a chain buffer */
6370 	max_sge_elements = ioc->chain_segment_sz - sge_size;
6371 	ioc->max_sges_in_chain_message = max_sge_elements/sge_size;
6372 
6373 	/*
6374 	 *  MPT3SAS_SG_DEPTH = CONFIG_FUSION_MAX_SGE
6375 	 */
6376 	chains_needed_per_io = ((ioc->shost->sg_tablesize -
6377 	   ioc->max_sges_in_main_message)/ioc->max_sges_in_chain_message)
6378 	    + 1;
6379 	if (chains_needed_per_io > facts->MaxChainDepth) {
6380 		chains_needed_per_io = facts->MaxChainDepth;
6381 		ioc->shost->sg_tablesize = min_t(u16,
6382 		ioc->max_sges_in_main_message + (ioc->max_sges_in_chain_message
6383 		* chains_needed_per_io), ioc->shost->sg_tablesize);
6384 	}
6385 	ioc->chains_needed_per_io = chains_needed_per_io;
6386 
6387 	/* reply free queue sizing - taking into account for 64 FW events */
6388 	ioc->reply_free_queue_depth = ioc->hba_queue_depth + 64;
6389 
6390 	/* mCPU manage single counters for simplicity */
6391 	if (ioc->is_mcpu_endpoint)
6392 		ioc->reply_post_queue_depth = ioc->reply_free_queue_depth;
6393 	else {
6394 		/* calculate reply descriptor post queue depth */
6395 		ioc->reply_post_queue_depth = ioc->hba_queue_depth +
6396 			ioc->reply_free_queue_depth +  1;
6397 		/* align the reply post queue on the next 16 count boundary */
6398 		if (ioc->reply_post_queue_depth % 16)
6399 			ioc->reply_post_queue_depth += 16 -
6400 				(ioc->reply_post_queue_depth % 16);
6401 	}
6402 
6403 	if (ioc->reply_post_queue_depth >
6404 	    facts->MaxReplyDescriptorPostQueueDepth) {
6405 		ioc->reply_post_queue_depth =
6406 				facts->MaxReplyDescriptorPostQueueDepth -
6407 		    (facts->MaxReplyDescriptorPostQueueDepth % 16);
6408 		ioc->hba_queue_depth =
6409 				((ioc->reply_post_queue_depth - 64) / 2) - 1;
6410 		ioc->reply_free_queue_depth = ioc->hba_queue_depth + 64;
6411 	}
6412 
6413 	ioc_info(ioc,
6414 	    "scatter gather: sge_in_main_msg(%d), sge_per_chain(%d), "
6415 	    "sge_per_io(%d), chains_per_io(%d)\n",
6416 	    ioc->max_sges_in_main_message,
6417 	    ioc->max_sges_in_chain_message,
6418 	    ioc->shost->sg_tablesize,
6419 	    ioc->chains_needed_per_io);
6420 
6421 	/* reply post queue, 16 byte align */
6422 	reply_post_free_sz = ioc->reply_post_queue_depth *
6423 	    sizeof(Mpi2DefaultReplyDescriptor_t);
6424 	rdpq_sz = reply_post_free_sz * RDPQ_MAX_INDEX_IN_ONE_CHUNK;
6425 	if ((_base_is_controller_msix_enabled(ioc) && !ioc->rdpq_array_enable)
6426 	    || (ioc->reply_queue_count < RDPQ_MAX_INDEX_IN_ONE_CHUNK))
6427 		rdpq_sz = reply_post_free_sz * ioc->reply_queue_count;
6428 	ret = base_alloc_rdpq_dma_pool(ioc, rdpq_sz);
6429 	if (ret == -EAGAIN) {
6430 		/*
6431 		 * Free allocated bad RDPQ memory pools.
6432 		 * Change dma coherent mask to 32 bit and reallocate RDPQ
6433 		 */
6434 		_base_release_memory_pools(ioc);
6435 		ioc->use_32bit_dma = true;
6436 		if (_base_config_dma_addressing(ioc, ioc->pdev) != 0) {
6437 			ioc_err(ioc,
6438 			    "32 DMA mask failed %s\n", pci_name(ioc->pdev));
6439 			return -ENODEV;
6440 		}
6441 		if (base_alloc_rdpq_dma_pool(ioc, rdpq_sz))
6442 			return -ENOMEM;
6443 	} else if (ret == -ENOMEM)
6444 		return -ENOMEM;
6445 	total_sz = rdpq_sz * (!ioc->rdpq_array_enable ? 1 :
6446 	    DIV_ROUND_UP(ioc->reply_queue_count, RDPQ_MAX_INDEX_IN_ONE_CHUNK));
6447 	ioc->scsiio_depth = ioc->hba_queue_depth -
6448 	    ioc->hi_priority_depth - ioc->internal_depth;
6449 
6450 	/* set the scsi host can_queue depth
6451 	 * with some internal commands that could be outstanding
6452 	 */
6453 	ioc->shost->can_queue = ioc->scsiio_depth - INTERNAL_SCSIIO_CMDS_COUNT;
6454 	dinitprintk(ioc,
6455 		    ioc_info(ioc, "scsi host: can_queue depth (%d)\n",
6456 			     ioc->shost->can_queue));
6457 
6458 	/* contiguous pool for request and chains, 16 byte align, one extra "
6459 	 * "frame for smid=0
6460 	 */
6461 	ioc->chain_depth = ioc->chains_needed_per_io * ioc->scsiio_depth;
6462 	sz = ((ioc->scsiio_depth + 1) * ioc->request_sz);
6463 
6464 	/* hi-priority queue */
6465 	sz += (ioc->hi_priority_depth * ioc->request_sz);
6466 
6467 	/* internal queue */
6468 	sz += (ioc->internal_depth * ioc->request_sz);
6469 
6470 	ioc->request_dma_sz = sz;
6471 	ioc->request = dma_alloc_coherent(&ioc->pdev->dev, sz,
6472 			&ioc->request_dma, GFP_KERNEL);
6473 	if (!ioc->request) {
6474 		ioc_err(ioc, "request pool: dma_alloc_coherent failed: hba_depth(%d), chains_per_io(%d), frame_sz(%d), total(%d kB)\n",
6475 			ioc->hba_queue_depth, ioc->chains_needed_per_io,
6476 			ioc->request_sz, sz / 1024);
6477 		if (ioc->scsiio_depth < MPT3SAS_SAS_QUEUE_DEPTH)
6478 			goto out;
6479 		retry_sz = 64;
6480 		ioc->hba_queue_depth -= retry_sz;
6481 		_base_release_memory_pools(ioc);
6482 		goto retry_allocation;
6483 	}
6484 
6485 	if (retry_sz)
6486 		ioc_err(ioc, "request pool: dma_alloc_coherent succeed: hba_depth(%d), chains_per_io(%d), frame_sz(%d), total(%d kb)\n",
6487 			ioc->hba_queue_depth, ioc->chains_needed_per_io,
6488 			ioc->request_sz, sz / 1024);
6489 
6490 	/* hi-priority queue */
6491 	ioc->hi_priority = ioc->request + ((ioc->scsiio_depth + 1) *
6492 	    ioc->request_sz);
6493 	ioc->hi_priority_dma = ioc->request_dma + ((ioc->scsiio_depth + 1) *
6494 	    ioc->request_sz);
6495 
6496 	/* internal queue */
6497 	ioc->internal = ioc->hi_priority + (ioc->hi_priority_depth *
6498 	    ioc->request_sz);
6499 	ioc->internal_dma = ioc->hi_priority_dma + (ioc->hi_priority_depth *
6500 	    ioc->request_sz);
6501 
6502 	ioc_info(ioc,
6503 	    "request pool(0x%p) - dma(0x%llx): "
6504 	    "depth(%d), frame_size(%d), pool_size(%d kB)\n",
6505 	    ioc->request, (unsigned long long) ioc->request_dma,
6506 	    ioc->hba_queue_depth, ioc->request_sz,
6507 	    (ioc->hba_queue_depth * ioc->request_sz) / 1024);
6508 
6509 	total_sz += sz;
6510 
6511 	dinitprintk(ioc,
6512 		    ioc_info(ioc, "scsiio(0x%p): depth(%d)\n",
6513 			     ioc->request, ioc->scsiio_depth));
6514 
6515 	ioc->chain_depth = min_t(u32, ioc->chain_depth, MAX_CHAIN_DEPTH);
6516 	sz = ioc->scsiio_depth * sizeof(struct chain_lookup);
6517 	ioc->chain_lookup = kzalloc(sz, GFP_KERNEL);
6518 	if (!ioc->chain_lookup) {
6519 		ioc_err(ioc, "chain_lookup: __get_free_pages failed\n");
6520 		goto out;
6521 	}
6522 
6523 	sz = ioc->chains_needed_per_io * sizeof(struct chain_tracker);
6524 	for (i = 0; i < ioc->scsiio_depth; i++) {
6525 		ioc->chain_lookup[i].chains_per_smid = kzalloc(sz, GFP_KERNEL);
6526 		if (!ioc->chain_lookup[i].chains_per_smid) {
6527 			ioc_err(ioc, "chain_lookup: kzalloc failed\n");
6528 			goto out;
6529 		}
6530 	}
6531 
6532 	/* initialize hi-priority queue smid's */
6533 	ioc->hpr_lookup = kcalloc(ioc->hi_priority_depth,
6534 	    sizeof(struct request_tracker), GFP_KERNEL);
6535 	if (!ioc->hpr_lookup) {
6536 		ioc_err(ioc, "hpr_lookup: kcalloc failed\n");
6537 		goto out;
6538 	}
6539 	ioc->hi_priority_smid = ioc->scsiio_depth + 1;
6540 	dinitprintk(ioc,
6541 		    ioc_info(ioc, "hi_priority(0x%p): depth(%d), start smid(%d)\n",
6542 			     ioc->hi_priority,
6543 			     ioc->hi_priority_depth, ioc->hi_priority_smid));
6544 
6545 	/* initialize internal queue smid's */
6546 	ioc->internal_lookup = kcalloc(ioc->internal_depth,
6547 	    sizeof(struct request_tracker), GFP_KERNEL);
6548 	if (!ioc->internal_lookup) {
6549 		ioc_err(ioc, "internal_lookup: kcalloc failed\n");
6550 		goto out;
6551 	}
6552 	ioc->internal_smid = ioc->hi_priority_smid + ioc->hi_priority_depth;
6553 	dinitprintk(ioc,
6554 		    ioc_info(ioc, "internal(0x%p): depth(%d), start smid(%d)\n",
6555 			     ioc->internal,
6556 			     ioc->internal_depth, ioc->internal_smid));
6557 
6558 	ioc->io_queue_num = kcalloc(ioc->scsiio_depth,
6559 	    sizeof(u16), GFP_KERNEL);
6560 	if (!ioc->io_queue_num)
6561 		goto out;
6562 	/*
6563 	 * The number of NVMe page sized blocks needed is:
6564 	 *     (((sg_tablesize * 8) - 1) / (page_size - 8)) + 1
6565 	 * ((sg_tablesize * 8) - 1) is the max PRP's minus the first PRP entry
6566 	 * that is placed in the main message frame.  8 is the size of each PRP
6567 	 * entry or PRP list pointer entry.  8 is subtracted from page_size
6568 	 * because of the PRP list pointer entry at the end of a page, so this
6569 	 * is not counted as a PRP entry.  The 1 added page is a round up.
6570 	 *
6571 	 * To avoid allocation failures due to the amount of memory that could
6572 	 * be required for NVMe PRP's, only each set of NVMe blocks will be
6573 	 * contiguous, so a new set is allocated for each possible I/O.
6574 	 */
6575 
6576 	ioc->chains_per_prp_buffer = 0;
6577 	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_NVME_DEVICES) {
6578 		nvme_blocks_needed =
6579 			(ioc->shost->sg_tablesize * NVME_PRP_SIZE) - 1;
6580 		nvme_blocks_needed /= (ioc->page_size - NVME_PRP_SIZE);
6581 		nvme_blocks_needed++;
6582 
6583 		sz = sizeof(struct pcie_sg_list) * ioc->scsiio_depth;
6584 		ioc->pcie_sg_lookup = kzalloc(sz, GFP_KERNEL);
6585 		if (!ioc->pcie_sg_lookup) {
6586 			ioc_info(ioc, "PCIe SGL lookup: kzalloc failed\n");
6587 			goto out;
6588 		}
6589 		sz = nvme_blocks_needed * ioc->page_size;
6590 		rc = _base_allocate_pcie_sgl_pool(ioc, sz);
6591 		if (rc == -ENOMEM)
6592 			return -ENOMEM;
6593 		else if (rc == -EAGAIN)
6594 			goto try_32bit_dma;
6595 		total_sz += sz * ioc->scsiio_depth;
6596 	}
6597 
6598 	rc = _base_allocate_chain_dma_pool(ioc, ioc->chain_segment_sz);
6599 	if (rc == -ENOMEM)
6600 		return -ENOMEM;
6601 	else if (rc == -EAGAIN)
6602 		goto try_32bit_dma;
6603 	total_sz += ioc->chain_segment_sz * ((ioc->chains_needed_per_io -
6604 		ioc->chains_per_prp_buffer) * ioc->scsiio_depth);
6605 	dinitprintk(ioc,
6606 	    ioc_info(ioc, "chain pool depth(%d), frame_size(%d), pool_size(%d kB)\n",
6607 	    ioc->chain_depth, ioc->chain_segment_sz,
6608 	    (ioc->chain_depth * ioc->chain_segment_sz) / 1024));
6609 	/* sense buffers, 4 byte align */
6610 	sense_sz = ioc->scsiio_depth * SCSI_SENSE_BUFFERSIZE;
6611 	rc = _base_allocate_sense_dma_pool(ioc, sense_sz);
6612 	if (rc  == -ENOMEM)
6613 		return -ENOMEM;
6614 	else if (rc == -EAGAIN)
6615 		goto try_32bit_dma;
6616 	total_sz += sense_sz;
6617 	ioc_info(ioc,
6618 	    "sense pool(0x%p)- dma(0x%llx): depth(%d),"
6619 	    "element_size(%d), pool_size(%d kB)\n",
6620 	    ioc->sense, (unsigned long long)ioc->sense_dma, ioc->scsiio_depth,
6621 	    SCSI_SENSE_BUFFERSIZE, sz / 1024);
6622 	/* reply pool, 4 byte align */
6623 	sz = ioc->reply_free_queue_depth * ioc->reply_sz;
6624 	rc = _base_allocate_reply_pool(ioc, sz);
6625 	if (rc == -ENOMEM)
6626 		return -ENOMEM;
6627 	else if (rc == -EAGAIN)
6628 		goto try_32bit_dma;
6629 	total_sz += sz;
6630 
6631 	/* reply free queue, 16 byte align */
6632 	sz = ioc->reply_free_queue_depth * 4;
6633 	rc = _base_allocate_reply_free_dma_pool(ioc, sz);
6634 	if (rc  == -ENOMEM)
6635 		return -ENOMEM;
6636 	else if (rc == -EAGAIN)
6637 		goto try_32bit_dma;
6638 	dinitprintk(ioc,
6639 		    ioc_info(ioc, "reply_free_dma (0x%llx)\n",
6640 			     (unsigned long long)ioc->reply_free_dma));
6641 	total_sz += sz;
6642 	if (ioc->rdpq_array_enable) {
6643 		reply_post_free_array_sz = ioc->reply_queue_count *
6644 		    sizeof(Mpi2IOCInitRDPQArrayEntry);
6645 		rc = _base_allocate_reply_post_free_array(ioc,
6646 		    reply_post_free_array_sz);
6647 		if (rc == -ENOMEM)
6648 			return -ENOMEM;
6649 		else if (rc == -EAGAIN)
6650 			goto try_32bit_dma;
6651 	}
6652 	ioc->config_page_sz = 512;
6653 	ioc->config_page = dma_alloc_coherent(&ioc->pdev->dev,
6654 			ioc->config_page_sz, &ioc->config_page_dma, GFP_KERNEL);
6655 	if (!ioc->config_page) {
6656 		ioc_err(ioc, "config page: dma_pool_alloc failed\n");
6657 		goto out;
6658 	}
6659 
6660 	ioc_info(ioc, "config page(0x%p) - dma(0x%llx): size(%d)\n",
6661 	    ioc->config_page, (unsigned long long)ioc->config_page_dma,
6662 	    ioc->config_page_sz);
6663 	total_sz += ioc->config_page_sz;
6664 
6665 	ioc_info(ioc, "Allocated physical memory: size(%d kB)\n",
6666 		 total_sz / 1024);
6667 	ioc_info(ioc, "Current Controller Queue Depth(%d),Max Controller Queue Depth(%d)\n",
6668 		 ioc->shost->can_queue, facts->RequestCredit);
6669 	ioc_info(ioc, "Scatter Gather Elements per IO(%d)\n",
6670 		 ioc->shost->sg_tablesize);
6671 	return 0;
6672 
6673 try_32bit_dma:
6674 	_base_release_memory_pools(ioc);
6675 	if (ioc->use_32bit_dma && (ioc->dma_mask > 32)) {
6676 		/* Change dma coherent mask to 32 bit and reallocate */
6677 		if (_base_config_dma_addressing(ioc, ioc->pdev) != 0) {
6678 			pr_err("Setting 32 bit coherent DMA mask Failed %s\n",
6679 			    pci_name(ioc->pdev));
6680 			return -ENODEV;
6681 		}
6682 	} else if (_base_reduce_hba_queue_depth(ioc) != 0)
6683 		return -ENOMEM;
6684 	goto retry_allocation;
6685 
6686  out:
6687 	return -ENOMEM;
6688 }
6689 
6690 /**
6691  * mpt3sas_base_get_iocstate - Get the current state of a MPT adapter.
6692  * @ioc: Pointer to MPT_ADAPTER structure
6693  * @cooked: Request raw or cooked IOC state
6694  *
6695  * Return: all IOC Doorbell register bits if cooked==0, else just the
6696  * Doorbell bits in MPI_IOC_STATE_MASK.
6697  */
6698 u32
6699 mpt3sas_base_get_iocstate(struct MPT3SAS_ADAPTER *ioc, int cooked)
6700 {
6701 	u32 s, sc;
6702 
6703 	s = ioc->base_readl(&ioc->chip->Doorbell);
6704 	sc = s & MPI2_IOC_STATE_MASK;
6705 	return cooked ? sc : s;
6706 }
6707 
6708 /**
6709  * _base_wait_on_iocstate - waiting on a particular ioc state
6710  * @ioc: ?
6711  * @ioc_state: controller state { READY, OPERATIONAL, or RESET }
6712  * @timeout: timeout in second
6713  *
6714  * Return: 0 for success, non-zero for failure.
6715  */
6716 static int
6717 _base_wait_on_iocstate(struct MPT3SAS_ADAPTER *ioc, u32 ioc_state, int timeout)
6718 {
6719 	u32 count, cntdn;
6720 	u32 current_state;
6721 
6722 	count = 0;
6723 	cntdn = 1000 * timeout;
6724 	do {
6725 		current_state = mpt3sas_base_get_iocstate(ioc, 1);
6726 		if (current_state == ioc_state)
6727 			return 0;
6728 		if (count && current_state == MPI2_IOC_STATE_FAULT)
6729 			break;
6730 		if (count && current_state == MPI2_IOC_STATE_COREDUMP)
6731 			break;
6732 
6733 		usleep_range(1000, 1500);
6734 		count++;
6735 	} while (--cntdn);
6736 
6737 	return current_state;
6738 }
6739 
6740 /**
6741  * _base_dump_reg_set -	This function will print hexdump of register set.
6742  * @ioc: per adapter object
6743  *
6744  * Return: nothing.
6745  */
6746 static inline void
6747 _base_dump_reg_set(struct MPT3SAS_ADAPTER *ioc)
6748 {
6749 	unsigned int i, sz = 256;
6750 	u32 __iomem *reg = (u32 __iomem *)ioc->chip;
6751 
6752 	ioc_info(ioc, "System Register set:\n");
6753 	for (i = 0; i < (sz / sizeof(u32)); i++)
6754 		pr_info("%08x: %08x\n", (i * 4), readl(&reg[i]));
6755 }
6756 
6757 /**
6758  * _base_wait_for_doorbell_int - waiting for controller interrupt(generated by
6759  * a write to the doorbell)
6760  * @ioc: per adapter object
6761  * @timeout: timeout in seconds
6762  *
6763  * Return: 0 for success, non-zero for failure.
6764  *
6765  * Notes: MPI2_HIS_IOC2SYS_DB_STATUS - set to one when IOC writes to doorbell.
6766  */
6767 
6768 static int
6769 _base_wait_for_doorbell_int(struct MPT3SAS_ADAPTER *ioc, int timeout)
6770 {
6771 	u32 cntdn, count;
6772 	u32 int_status;
6773 
6774 	count = 0;
6775 	cntdn = 1000 * timeout;
6776 	do {
6777 		int_status = ioc->base_readl(&ioc->chip->HostInterruptStatus);
6778 		if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
6779 			dhsprintk(ioc,
6780 				  ioc_info(ioc, "%s: successful count(%d), timeout(%d)\n",
6781 					   __func__, count, timeout));
6782 			return 0;
6783 		}
6784 
6785 		usleep_range(1000, 1500);
6786 		count++;
6787 	} while (--cntdn);
6788 
6789 	ioc_err(ioc, "%s: failed due to timeout count(%d), int_status(%x)!\n",
6790 		__func__, count, int_status);
6791 	return -EFAULT;
6792 }
6793 
6794 static int
6795 _base_spin_on_doorbell_int(struct MPT3SAS_ADAPTER *ioc, int timeout)
6796 {
6797 	u32 cntdn, count;
6798 	u32 int_status;
6799 
6800 	count = 0;
6801 	cntdn = 2000 * timeout;
6802 	do {
6803 		int_status = ioc->base_readl(&ioc->chip->HostInterruptStatus);
6804 		if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
6805 			dhsprintk(ioc,
6806 				  ioc_info(ioc, "%s: successful count(%d), timeout(%d)\n",
6807 					   __func__, count, timeout));
6808 			return 0;
6809 		}
6810 
6811 		udelay(500);
6812 		count++;
6813 	} while (--cntdn);
6814 
6815 	ioc_err(ioc, "%s: failed due to timeout count(%d), int_status(%x)!\n",
6816 		__func__, count, int_status);
6817 	return -EFAULT;
6818 
6819 }
6820 
6821 /**
6822  * _base_wait_for_doorbell_ack - waiting for controller to read the doorbell.
6823  * @ioc: per adapter object
6824  * @timeout: timeout in second
6825  *
6826  * Return: 0 for success, non-zero for failure.
6827  *
6828  * Notes: MPI2_HIS_SYS2IOC_DB_STATUS - set to one when host writes to
6829  * doorbell.
6830  */
6831 static int
6832 _base_wait_for_doorbell_ack(struct MPT3SAS_ADAPTER *ioc, int timeout)
6833 {
6834 	u32 cntdn, count;
6835 	u32 int_status;
6836 	u32 doorbell;
6837 
6838 	count = 0;
6839 	cntdn = 1000 * timeout;
6840 	do {
6841 		int_status = ioc->base_readl(&ioc->chip->HostInterruptStatus);
6842 		if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
6843 			dhsprintk(ioc,
6844 				  ioc_info(ioc, "%s: successful count(%d), timeout(%d)\n",
6845 					   __func__, count, timeout));
6846 			return 0;
6847 		} else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
6848 			doorbell = ioc->base_readl(&ioc->chip->Doorbell);
6849 			if ((doorbell & MPI2_IOC_STATE_MASK) ==
6850 			    MPI2_IOC_STATE_FAULT) {
6851 				mpt3sas_print_fault_code(ioc, doorbell);
6852 				return -EFAULT;
6853 			}
6854 			if ((doorbell & MPI2_IOC_STATE_MASK) ==
6855 			    MPI2_IOC_STATE_COREDUMP) {
6856 				mpt3sas_print_coredump_info(ioc, doorbell);
6857 				return -EFAULT;
6858 			}
6859 		} else if (int_status == 0xFFFFFFFF)
6860 			goto out;
6861 
6862 		usleep_range(1000, 1500);
6863 		count++;
6864 	} while (--cntdn);
6865 
6866  out:
6867 	ioc_err(ioc, "%s: failed due to timeout count(%d), int_status(%x)!\n",
6868 		__func__, count, int_status);
6869 	return -EFAULT;
6870 }
6871 
6872 /**
6873  * _base_wait_for_doorbell_not_used - waiting for doorbell to not be in use
6874  * @ioc: per adapter object
6875  * @timeout: timeout in second
6876  *
6877  * Return: 0 for success, non-zero for failure.
6878  */
6879 static int
6880 _base_wait_for_doorbell_not_used(struct MPT3SAS_ADAPTER *ioc, int timeout)
6881 {
6882 	u32 cntdn, count;
6883 	u32 doorbell_reg;
6884 
6885 	count = 0;
6886 	cntdn = 1000 * timeout;
6887 	do {
6888 		doorbell_reg = ioc->base_readl(&ioc->chip->Doorbell);
6889 		if (!(doorbell_reg & MPI2_DOORBELL_USED)) {
6890 			dhsprintk(ioc,
6891 				  ioc_info(ioc, "%s: successful count(%d), timeout(%d)\n",
6892 					   __func__, count, timeout));
6893 			return 0;
6894 		}
6895 
6896 		usleep_range(1000, 1500);
6897 		count++;
6898 	} while (--cntdn);
6899 
6900 	ioc_err(ioc, "%s: failed due to timeout count(%d), doorbell_reg(%x)!\n",
6901 		__func__, count, doorbell_reg);
6902 	return -EFAULT;
6903 }
6904 
6905 /**
6906  * _base_send_ioc_reset - send doorbell reset
6907  * @ioc: per adapter object
6908  * @reset_type: currently only supports: MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET
6909  * @timeout: timeout in second
6910  *
6911  * Return: 0 for success, non-zero for failure.
6912  */
6913 static int
6914 _base_send_ioc_reset(struct MPT3SAS_ADAPTER *ioc, u8 reset_type, int timeout)
6915 {
6916 	u32 ioc_state;
6917 	int r = 0;
6918 	unsigned long flags;
6919 
6920 	if (reset_type != MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET) {
6921 		ioc_err(ioc, "%s: unknown reset_type\n", __func__);
6922 		return -EFAULT;
6923 	}
6924 
6925 	if (!(ioc->facts.IOCCapabilities &
6926 	   MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY))
6927 		return -EFAULT;
6928 
6929 	ioc_info(ioc, "sending message unit reset !!\n");
6930 
6931 	writel(reset_type << MPI2_DOORBELL_FUNCTION_SHIFT,
6932 	    &ioc->chip->Doorbell);
6933 	if ((_base_wait_for_doorbell_ack(ioc, 15))) {
6934 		r = -EFAULT;
6935 		goto out;
6936 	}
6937 
6938 	ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, timeout);
6939 	if (ioc_state) {
6940 		ioc_err(ioc, "%s: failed going to ready state (ioc_state=0x%x)\n",
6941 			__func__, ioc_state);
6942 		r = -EFAULT;
6943 		goto out;
6944 	}
6945  out:
6946 	if (r != 0) {
6947 		ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
6948 		spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
6949 		/*
6950 		 * Wait for IOC state CoreDump to clear only during
6951 		 * HBA initialization & release time.
6952 		 */
6953 		if ((ioc_state & MPI2_IOC_STATE_MASK) ==
6954 		    MPI2_IOC_STATE_COREDUMP && (ioc->is_driver_loading == 1 ||
6955 		    ioc->fault_reset_work_q == NULL)) {
6956 			spin_unlock_irqrestore(
6957 			    &ioc->ioc_reset_in_progress_lock, flags);
6958 			mpt3sas_print_coredump_info(ioc, ioc_state);
6959 			mpt3sas_base_wait_for_coredump_completion(ioc,
6960 			    __func__);
6961 			spin_lock_irqsave(
6962 			    &ioc->ioc_reset_in_progress_lock, flags);
6963 		}
6964 		spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
6965 	}
6966 	ioc_info(ioc, "message unit reset: %s\n",
6967 		 r == 0 ? "SUCCESS" : "FAILED");
6968 	return r;
6969 }
6970 
6971 /**
6972  * mpt3sas_wait_for_ioc - IOC's operational state is checked here.
6973  * @ioc: per adapter object
6974  * @timeout: timeout in seconds
6975  *
6976  * Return: Waits up to timeout seconds for the IOC to
6977  * become operational. Returns 0 if IOC is present
6978  * and operational; otherwise returns %-EFAULT.
6979  */
6980 
6981 int
6982 mpt3sas_wait_for_ioc(struct MPT3SAS_ADAPTER *ioc, int timeout)
6983 {
6984 	int wait_state_count = 0;
6985 	u32 ioc_state;
6986 
6987 	do {
6988 		ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
6989 		if (ioc_state == MPI2_IOC_STATE_OPERATIONAL)
6990 			break;
6991 
6992 		/*
6993 		 * Watchdog thread will be started after IOC Initialization, so
6994 		 * no need to wait here for IOC state to become operational
6995 		 * when IOC Initialization is on. Instead the driver will
6996 		 * return ETIME status, so that calling function can issue
6997 		 * diag reset operation and retry the command.
6998 		 */
6999 		if (ioc->is_driver_loading)
7000 			return -ETIME;
7001 
7002 		ssleep(1);
7003 		ioc_info(ioc, "%s: waiting for operational state(count=%d)\n",
7004 				__func__, ++wait_state_count);
7005 	} while (--timeout);
7006 	if (!timeout) {
7007 		ioc_err(ioc, "%s: failed due to ioc not operational\n", __func__);
7008 		return -EFAULT;
7009 	}
7010 	if (wait_state_count)
7011 		ioc_info(ioc, "ioc is operational\n");
7012 	return 0;
7013 }
7014 
7015 /**
7016  * _base_handshake_req_reply_wait - send request thru doorbell interface
7017  * @ioc: per adapter object
7018  * @request_bytes: request length
7019  * @request: pointer having request payload
7020  * @reply_bytes: reply length
7021  * @reply: pointer to reply payload
7022  * @timeout: timeout in second
7023  *
7024  * Return: 0 for success, non-zero for failure.
7025  */
7026 static int
7027 _base_handshake_req_reply_wait(struct MPT3SAS_ADAPTER *ioc, int request_bytes,
7028 	u32 *request, int reply_bytes, u16 *reply, int timeout)
7029 {
7030 	MPI2DefaultReply_t *default_reply = (MPI2DefaultReply_t *)reply;
7031 	int i;
7032 	u8 failed;
7033 	__le32 *mfp;
7034 
7035 	/* make sure doorbell is not in use */
7036 	if ((ioc->base_readl(&ioc->chip->Doorbell) & MPI2_DOORBELL_USED)) {
7037 		ioc_err(ioc, "doorbell is in use (line=%d)\n", __LINE__);
7038 		return -EFAULT;
7039 	}
7040 
7041 	/* clear pending doorbell interrupts from previous state changes */
7042 	if (ioc->base_readl(&ioc->chip->HostInterruptStatus) &
7043 	    MPI2_HIS_IOC2SYS_DB_STATUS)
7044 		writel(0, &ioc->chip->HostInterruptStatus);
7045 
7046 	/* send message to ioc */
7047 	writel(((MPI2_FUNCTION_HANDSHAKE<<MPI2_DOORBELL_FUNCTION_SHIFT) |
7048 	    ((request_bytes/4)<<MPI2_DOORBELL_ADD_DWORDS_SHIFT)),
7049 	    &ioc->chip->Doorbell);
7050 
7051 	if ((_base_spin_on_doorbell_int(ioc, 5))) {
7052 		ioc_err(ioc, "doorbell handshake int failed (line=%d)\n",
7053 			__LINE__);
7054 		return -EFAULT;
7055 	}
7056 	writel(0, &ioc->chip->HostInterruptStatus);
7057 
7058 	if ((_base_wait_for_doorbell_ack(ioc, 5))) {
7059 		ioc_err(ioc, "doorbell handshake ack failed (line=%d)\n",
7060 			__LINE__);
7061 		return -EFAULT;
7062 	}
7063 
7064 	/* send message 32-bits at a time */
7065 	for (i = 0, failed = 0; i < request_bytes/4 && !failed; i++) {
7066 		writel(cpu_to_le32(request[i]), &ioc->chip->Doorbell);
7067 		if ((_base_wait_for_doorbell_ack(ioc, 5)))
7068 			failed = 1;
7069 	}
7070 
7071 	if (failed) {
7072 		ioc_err(ioc, "doorbell handshake sending request failed (line=%d)\n",
7073 			__LINE__);
7074 		return -EFAULT;
7075 	}
7076 
7077 	/* now wait for the reply */
7078 	if ((_base_wait_for_doorbell_int(ioc, timeout))) {
7079 		ioc_err(ioc, "doorbell handshake int failed (line=%d)\n",
7080 			__LINE__);
7081 		return -EFAULT;
7082 	}
7083 
7084 	/* read the first two 16-bits, it gives the total length of the reply */
7085 	reply[0] = le16_to_cpu(ioc->base_readl(&ioc->chip->Doorbell)
7086 	    & MPI2_DOORBELL_DATA_MASK);
7087 	writel(0, &ioc->chip->HostInterruptStatus);
7088 	if ((_base_wait_for_doorbell_int(ioc, 5))) {
7089 		ioc_err(ioc, "doorbell handshake int failed (line=%d)\n",
7090 			__LINE__);
7091 		return -EFAULT;
7092 	}
7093 	reply[1] = le16_to_cpu(ioc->base_readl(&ioc->chip->Doorbell)
7094 	    & MPI2_DOORBELL_DATA_MASK);
7095 	writel(0, &ioc->chip->HostInterruptStatus);
7096 
7097 	for (i = 2; i < default_reply->MsgLength * 2; i++)  {
7098 		if ((_base_wait_for_doorbell_int(ioc, 5))) {
7099 			ioc_err(ioc, "doorbell handshake int failed (line=%d)\n",
7100 				__LINE__);
7101 			return -EFAULT;
7102 		}
7103 		if (i >=  reply_bytes/2) /* overflow case */
7104 			ioc->base_readl(&ioc->chip->Doorbell);
7105 		else
7106 			reply[i] = le16_to_cpu(
7107 			    ioc->base_readl(&ioc->chip->Doorbell)
7108 			    & MPI2_DOORBELL_DATA_MASK);
7109 		writel(0, &ioc->chip->HostInterruptStatus);
7110 	}
7111 
7112 	_base_wait_for_doorbell_int(ioc, 5);
7113 	if (_base_wait_for_doorbell_not_used(ioc, 5) != 0) {
7114 		dhsprintk(ioc,
7115 			  ioc_info(ioc, "doorbell is in use (line=%d)\n",
7116 				   __LINE__));
7117 	}
7118 	writel(0, &ioc->chip->HostInterruptStatus);
7119 
7120 	if (ioc->logging_level & MPT_DEBUG_INIT) {
7121 		mfp = (__le32 *)reply;
7122 		pr_info("\toffset:data\n");
7123 		for (i = 0; i < reply_bytes/4; i++)
7124 			ioc_info(ioc, "\t[0x%02x]:%08x\n", i*4,
7125 			    le32_to_cpu(mfp[i]));
7126 	}
7127 	return 0;
7128 }
7129 
7130 /**
7131  * mpt3sas_base_sas_iounit_control - send sas iounit control to FW
7132  * @ioc: per adapter object
7133  * @mpi_reply: the reply payload from FW
7134  * @mpi_request: the request payload sent to FW
7135  *
7136  * The SAS IO Unit Control Request message allows the host to perform low-level
7137  * operations, such as resets on the PHYs of the IO Unit, also allows the host
7138  * to obtain the IOC assigned device handles for a device if it has other
7139  * identifying information about the device, in addition allows the host to
7140  * remove IOC resources associated with the device.
7141  *
7142  * Return: 0 for success, non-zero for failure.
7143  */
7144 int
7145 mpt3sas_base_sas_iounit_control(struct MPT3SAS_ADAPTER *ioc,
7146 	Mpi2SasIoUnitControlReply_t *mpi_reply,
7147 	Mpi2SasIoUnitControlRequest_t *mpi_request)
7148 {
7149 	u16 smid;
7150 	u8 issue_reset = 0;
7151 	int rc;
7152 	void *request;
7153 
7154 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
7155 
7156 	mutex_lock(&ioc->base_cmds.mutex);
7157 
7158 	if (ioc->base_cmds.status != MPT3_CMD_NOT_USED) {
7159 		ioc_err(ioc, "%s: base_cmd in use\n", __func__);
7160 		rc = -EAGAIN;
7161 		goto out;
7162 	}
7163 
7164 	rc = mpt3sas_wait_for_ioc(ioc, IOC_OPERATIONAL_WAIT_COUNT);
7165 	if (rc)
7166 		goto out;
7167 
7168 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
7169 	if (!smid) {
7170 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
7171 		rc = -EAGAIN;
7172 		goto out;
7173 	}
7174 
7175 	rc = 0;
7176 	ioc->base_cmds.status = MPT3_CMD_PENDING;
7177 	request = mpt3sas_base_get_msg_frame(ioc, smid);
7178 	ioc->base_cmds.smid = smid;
7179 	memcpy(request, mpi_request, sizeof(Mpi2SasIoUnitControlRequest_t));
7180 	if (mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
7181 	    mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET)
7182 		ioc->ioc_link_reset_in_progress = 1;
7183 	init_completion(&ioc->base_cmds.done);
7184 	ioc->put_smid_default(ioc, smid);
7185 	wait_for_completion_timeout(&ioc->base_cmds.done,
7186 	    msecs_to_jiffies(10000));
7187 	if ((mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
7188 	    mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET) &&
7189 	    ioc->ioc_link_reset_in_progress)
7190 		ioc->ioc_link_reset_in_progress = 0;
7191 	if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
7192 		mpt3sas_check_cmd_timeout(ioc, ioc->base_cmds.status,
7193 		    mpi_request, sizeof(Mpi2SasIoUnitControlRequest_t)/4,
7194 		    issue_reset);
7195 		goto issue_host_reset;
7196 	}
7197 	if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID)
7198 		memcpy(mpi_reply, ioc->base_cmds.reply,
7199 		    sizeof(Mpi2SasIoUnitControlReply_t));
7200 	else
7201 		memset(mpi_reply, 0, sizeof(Mpi2SasIoUnitControlReply_t));
7202 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
7203 	goto out;
7204 
7205  issue_host_reset:
7206 	if (issue_reset)
7207 		mpt3sas_base_hard_reset_handler(ioc, FORCE_BIG_HAMMER);
7208 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
7209 	rc = -EFAULT;
7210  out:
7211 	mutex_unlock(&ioc->base_cmds.mutex);
7212 	return rc;
7213 }
7214 
7215 /**
7216  * mpt3sas_base_scsi_enclosure_processor - sending request to sep device
7217  * @ioc: per adapter object
7218  * @mpi_reply: the reply payload from FW
7219  * @mpi_request: the request payload sent to FW
7220  *
7221  * The SCSI Enclosure Processor request message causes the IOC to
7222  * communicate with SES devices to control LED status signals.
7223  *
7224  * Return: 0 for success, non-zero for failure.
7225  */
7226 int
7227 mpt3sas_base_scsi_enclosure_processor(struct MPT3SAS_ADAPTER *ioc,
7228 	Mpi2SepReply_t *mpi_reply, Mpi2SepRequest_t *mpi_request)
7229 {
7230 	u16 smid;
7231 	u8 issue_reset = 0;
7232 	int rc;
7233 	void *request;
7234 
7235 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
7236 
7237 	mutex_lock(&ioc->base_cmds.mutex);
7238 
7239 	if (ioc->base_cmds.status != MPT3_CMD_NOT_USED) {
7240 		ioc_err(ioc, "%s: base_cmd in use\n", __func__);
7241 		rc = -EAGAIN;
7242 		goto out;
7243 	}
7244 
7245 	rc = mpt3sas_wait_for_ioc(ioc, IOC_OPERATIONAL_WAIT_COUNT);
7246 	if (rc)
7247 		goto out;
7248 
7249 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
7250 	if (!smid) {
7251 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
7252 		rc = -EAGAIN;
7253 		goto out;
7254 	}
7255 
7256 	rc = 0;
7257 	ioc->base_cmds.status = MPT3_CMD_PENDING;
7258 	request = mpt3sas_base_get_msg_frame(ioc, smid);
7259 	ioc->base_cmds.smid = smid;
7260 	memset(request, 0, ioc->request_sz);
7261 	memcpy(request, mpi_request, sizeof(Mpi2SepReply_t));
7262 	init_completion(&ioc->base_cmds.done);
7263 	ioc->put_smid_default(ioc, smid);
7264 	wait_for_completion_timeout(&ioc->base_cmds.done,
7265 	    msecs_to_jiffies(10000));
7266 	if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
7267 		mpt3sas_check_cmd_timeout(ioc,
7268 		    ioc->base_cmds.status, mpi_request,
7269 		    sizeof(Mpi2SepRequest_t)/4, issue_reset);
7270 		goto issue_host_reset;
7271 	}
7272 	if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID)
7273 		memcpy(mpi_reply, ioc->base_cmds.reply,
7274 		    sizeof(Mpi2SepReply_t));
7275 	else
7276 		memset(mpi_reply, 0, sizeof(Mpi2SepReply_t));
7277 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
7278 	goto out;
7279 
7280  issue_host_reset:
7281 	if (issue_reset)
7282 		mpt3sas_base_hard_reset_handler(ioc, FORCE_BIG_HAMMER);
7283 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
7284 	rc = -EFAULT;
7285  out:
7286 	mutex_unlock(&ioc->base_cmds.mutex);
7287 	return rc;
7288 }
7289 
7290 /**
7291  * _base_get_port_facts - obtain port facts reply and save in ioc
7292  * @ioc: per adapter object
7293  * @port: ?
7294  *
7295  * Return: 0 for success, non-zero for failure.
7296  */
7297 static int
7298 _base_get_port_facts(struct MPT3SAS_ADAPTER *ioc, int port)
7299 {
7300 	Mpi2PortFactsRequest_t mpi_request;
7301 	Mpi2PortFactsReply_t mpi_reply;
7302 	struct mpt3sas_port_facts *pfacts;
7303 	int mpi_reply_sz, mpi_request_sz, r;
7304 
7305 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
7306 
7307 	mpi_reply_sz = sizeof(Mpi2PortFactsReply_t);
7308 	mpi_request_sz = sizeof(Mpi2PortFactsRequest_t);
7309 	memset(&mpi_request, 0, mpi_request_sz);
7310 	mpi_request.Function = MPI2_FUNCTION_PORT_FACTS;
7311 	mpi_request.PortNumber = port;
7312 	r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
7313 	    (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5);
7314 
7315 	if (r != 0) {
7316 		ioc_err(ioc, "%s: handshake failed (r=%d)\n", __func__, r);
7317 		return r;
7318 	}
7319 
7320 	pfacts = &ioc->pfacts[port];
7321 	memset(pfacts, 0, sizeof(struct mpt3sas_port_facts));
7322 	pfacts->PortNumber = mpi_reply.PortNumber;
7323 	pfacts->VP_ID = mpi_reply.VP_ID;
7324 	pfacts->VF_ID = mpi_reply.VF_ID;
7325 	pfacts->MaxPostedCmdBuffers =
7326 	    le16_to_cpu(mpi_reply.MaxPostedCmdBuffers);
7327 
7328 	return 0;
7329 }
7330 
7331 /**
7332  * _base_wait_for_iocstate - Wait until the card is in READY or OPERATIONAL
7333  * @ioc: per adapter object
7334  * @timeout:
7335  *
7336  * Return: 0 for success, non-zero for failure.
7337  */
7338 static int
7339 _base_wait_for_iocstate(struct MPT3SAS_ADAPTER *ioc, int timeout)
7340 {
7341 	u32 ioc_state;
7342 	int rc;
7343 
7344 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
7345 
7346 	if (ioc->pci_error_recovery) {
7347 		dfailprintk(ioc,
7348 			    ioc_info(ioc, "%s: host in pci error recovery\n",
7349 				     __func__));
7350 		return -EFAULT;
7351 	}
7352 
7353 	ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
7354 	dhsprintk(ioc,
7355 		  ioc_info(ioc, "%s: ioc_state(0x%08x)\n",
7356 			   __func__, ioc_state));
7357 
7358 	if (((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_READY) ||
7359 	    (ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_OPERATIONAL)
7360 		return 0;
7361 
7362 	if (ioc_state & MPI2_DOORBELL_USED) {
7363 		dhsprintk(ioc, ioc_info(ioc, "unexpected doorbell active!\n"));
7364 		goto issue_diag_reset;
7365 	}
7366 
7367 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
7368 		mpt3sas_print_fault_code(ioc, ioc_state &
7369 		    MPI2_DOORBELL_DATA_MASK);
7370 		goto issue_diag_reset;
7371 	} else if ((ioc_state & MPI2_IOC_STATE_MASK) ==
7372 	    MPI2_IOC_STATE_COREDUMP) {
7373 		ioc_info(ioc,
7374 		    "%s: Skipping the diag reset here. (ioc_state=0x%x)\n",
7375 		    __func__, ioc_state);
7376 		return -EFAULT;
7377 	}
7378 
7379 	ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, timeout);
7380 	if (ioc_state) {
7381 		dfailprintk(ioc,
7382 			    ioc_info(ioc, "%s: failed going to ready state (ioc_state=0x%x)\n",
7383 				     __func__, ioc_state));
7384 		return -EFAULT;
7385 	}
7386 
7387  issue_diag_reset:
7388 	rc = _base_diag_reset(ioc);
7389 	return rc;
7390 }
7391 
7392 /**
7393  * _base_get_ioc_facts - obtain ioc facts reply and save in ioc
7394  * @ioc: per adapter object
7395  *
7396  * Return: 0 for success, non-zero for failure.
7397  */
7398 static int
7399 _base_get_ioc_facts(struct MPT3SAS_ADAPTER *ioc)
7400 {
7401 	Mpi2IOCFactsRequest_t mpi_request;
7402 	Mpi2IOCFactsReply_t mpi_reply;
7403 	struct mpt3sas_facts *facts;
7404 	int mpi_reply_sz, mpi_request_sz, r;
7405 
7406 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
7407 
7408 	r = _base_wait_for_iocstate(ioc, 10);
7409 	if (r) {
7410 		dfailprintk(ioc,
7411 			    ioc_info(ioc, "%s: failed getting to correct state\n",
7412 				     __func__));
7413 		return r;
7414 	}
7415 	mpi_reply_sz = sizeof(Mpi2IOCFactsReply_t);
7416 	mpi_request_sz = sizeof(Mpi2IOCFactsRequest_t);
7417 	memset(&mpi_request, 0, mpi_request_sz);
7418 	mpi_request.Function = MPI2_FUNCTION_IOC_FACTS;
7419 	r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
7420 	    (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5);
7421 
7422 	if (r != 0) {
7423 		ioc_err(ioc, "%s: handshake failed (r=%d)\n", __func__, r);
7424 		return r;
7425 	}
7426 
7427 	facts = &ioc->facts;
7428 	memset(facts, 0, sizeof(struct mpt3sas_facts));
7429 	facts->MsgVersion = le16_to_cpu(mpi_reply.MsgVersion);
7430 	facts->HeaderVersion = le16_to_cpu(mpi_reply.HeaderVersion);
7431 	facts->VP_ID = mpi_reply.VP_ID;
7432 	facts->VF_ID = mpi_reply.VF_ID;
7433 	facts->IOCExceptions = le16_to_cpu(mpi_reply.IOCExceptions);
7434 	facts->MaxChainDepth = mpi_reply.MaxChainDepth;
7435 	facts->WhoInit = mpi_reply.WhoInit;
7436 	facts->NumberOfPorts = mpi_reply.NumberOfPorts;
7437 	facts->MaxMSIxVectors = mpi_reply.MaxMSIxVectors;
7438 	if (ioc->msix_enable && (facts->MaxMSIxVectors <=
7439 	    MAX_COMBINED_MSIX_VECTORS(ioc->is_gen35_ioc)))
7440 		ioc->combined_reply_queue = 0;
7441 	facts->RequestCredit = le16_to_cpu(mpi_reply.RequestCredit);
7442 	facts->MaxReplyDescriptorPostQueueDepth =
7443 	    le16_to_cpu(mpi_reply.MaxReplyDescriptorPostQueueDepth);
7444 	facts->ProductID = le16_to_cpu(mpi_reply.ProductID);
7445 	facts->IOCCapabilities = le32_to_cpu(mpi_reply.IOCCapabilities);
7446 	if ((facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID))
7447 		ioc->ir_firmware = 1;
7448 	if ((facts->IOCCapabilities &
7449 	      MPI2_IOCFACTS_CAPABILITY_RDPQ_ARRAY_CAPABLE) && (!reset_devices))
7450 		ioc->rdpq_array_capable = 1;
7451 	if ((facts->IOCCapabilities & MPI26_IOCFACTS_CAPABILITY_ATOMIC_REQ)
7452 	    && ioc->is_aero_ioc)
7453 		ioc->atomic_desc_capable = 1;
7454 	facts->FWVersion.Word = le32_to_cpu(mpi_reply.FWVersion.Word);
7455 	facts->IOCRequestFrameSize =
7456 	    le16_to_cpu(mpi_reply.IOCRequestFrameSize);
7457 	if (ioc->hba_mpi_version_belonged != MPI2_VERSION) {
7458 		facts->IOCMaxChainSegmentSize =
7459 			le16_to_cpu(mpi_reply.IOCMaxChainSegmentSize);
7460 	}
7461 	facts->MaxInitiators = le16_to_cpu(mpi_reply.MaxInitiators);
7462 	facts->MaxTargets = le16_to_cpu(mpi_reply.MaxTargets);
7463 	ioc->shost->max_id = -1;
7464 	facts->MaxSasExpanders = le16_to_cpu(mpi_reply.MaxSasExpanders);
7465 	facts->MaxEnclosures = le16_to_cpu(mpi_reply.MaxEnclosures);
7466 	facts->ProtocolFlags = le16_to_cpu(mpi_reply.ProtocolFlags);
7467 	facts->HighPriorityCredit =
7468 	    le16_to_cpu(mpi_reply.HighPriorityCredit);
7469 	facts->ReplyFrameSize = mpi_reply.ReplyFrameSize;
7470 	facts->MaxDevHandle = le16_to_cpu(mpi_reply.MaxDevHandle);
7471 	facts->CurrentHostPageSize = mpi_reply.CurrentHostPageSize;
7472 
7473 	/*
7474 	 * Get the Page Size from IOC Facts. If it's 0, default to 4k.
7475 	 */
7476 	ioc->page_size = 1 << facts->CurrentHostPageSize;
7477 	if (ioc->page_size == 1) {
7478 		ioc_info(ioc, "CurrentHostPageSize is 0: Setting default host page size to 4k\n");
7479 		ioc->page_size = 1 << MPT3SAS_HOST_PAGE_SIZE_4K;
7480 	}
7481 	dinitprintk(ioc,
7482 		    ioc_info(ioc, "CurrentHostPageSize(%d)\n",
7483 			     facts->CurrentHostPageSize));
7484 
7485 	dinitprintk(ioc,
7486 		    ioc_info(ioc, "hba queue depth(%d), max chains per io(%d)\n",
7487 			     facts->RequestCredit, facts->MaxChainDepth));
7488 	dinitprintk(ioc,
7489 		    ioc_info(ioc, "request frame size(%d), reply frame size(%d)\n",
7490 			     facts->IOCRequestFrameSize * 4,
7491 			     facts->ReplyFrameSize * 4));
7492 	return 0;
7493 }
7494 
7495 /**
7496  * _base_send_ioc_init - send ioc_init to firmware
7497  * @ioc: per adapter object
7498  *
7499  * Return: 0 for success, non-zero for failure.
7500  */
7501 static int
7502 _base_send_ioc_init(struct MPT3SAS_ADAPTER *ioc)
7503 {
7504 	Mpi2IOCInitRequest_t mpi_request;
7505 	Mpi2IOCInitReply_t mpi_reply;
7506 	int i, r = 0;
7507 	ktime_t current_time;
7508 	u16 ioc_status;
7509 	u32 reply_post_free_array_sz = 0;
7510 
7511 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
7512 
7513 	memset(&mpi_request, 0, sizeof(Mpi2IOCInitRequest_t));
7514 	mpi_request.Function = MPI2_FUNCTION_IOC_INIT;
7515 	mpi_request.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
7516 	mpi_request.VF_ID = 0; /* TODO */
7517 	mpi_request.VP_ID = 0;
7518 	mpi_request.MsgVersion = cpu_to_le16(ioc->hba_mpi_version_belonged);
7519 	mpi_request.HeaderVersion = cpu_to_le16(MPI2_HEADER_VERSION);
7520 	mpi_request.HostPageSize = MPT3SAS_HOST_PAGE_SIZE_4K;
7521 
7522 	if (_base_is_controller_msix_enabled(ioc))
7523 		mpi_request.HostMSIxVectors = ioc->reply_queue_count;
7524 	mpi_request.SystemRequestFrameSize = cpu_to_le16(ioc->request_sz/4);
7525 	mpi_request.ReplyDescriptorPostQueueDepth =
7526 	    cpu_to_le16(ioc->reply_post_queue_depth);
7527 	mpi_request.ReplyFreeQueueDepth =
7528 	    cpu_to_le16(ioc->reply_free_queue_depth);
7529 
7530 	mpi_request.SenseBufferAddressHigh =
7531 	    cpu_to_le32((u64)ioc->sense_dma >> 32);
7532 	mpi_request.SystemReplyAddressHigh =
7533 	    cpu_to_le32((u64)ioc->reply_dma >> 32);
7534 	mpi_request.SystemRequestFrameBaseAddress =
7535 	    cpu_to_le64((u64)ioc->request_dma);
7536 	mpi_request.ReplyFreeQueueAddress =
7537 	    cpu_to_le64((u64)ioc->reply_free_dma);
7538 
7539 	if (ioc->rdpq_array_enable) {
7540 		reply_post_free_array_sz = ioc->reply_queue_count *
7541 		    sizeof(Mpi2IOCInitRDPQArrayEntry);
7542 		memset(ioc->reply_post_free_array, 0, reply_post_free_array_sz);
7543 		for (i = 0; i < ioc->reply_queue_count; i++)
7544 			ioc->reply_post_free_array[i].RDPQBaseAddress =
7545 			    cpu_to_le64(
7546 				(u64)ioc->reply_post[i].reply_post_free_dma);
7547 		mpi_request.MsgFlags = MPI2_IOCINIT_MSGFLAG_RDPQ_ARRAY_MODE;
7548 		mpi_request.ReplyDescriptorPostQueueAddress =
7549 		    cpu_to_le64((u64)ioc->reply_post_free_array_dma);
7550 	} else {
7551 		mpi_request.ReplyDescriptorPostQueueAddress =
7552 		    cpu_to_le64((u64)ioc->reply_post[0].reply_post_free_dma);
7553 	}
7554 
7555 	/*
7556 	 * Set the flag to enable CoreDump state feature in IOC firmware.
7557 	 */
7558 	mpi_request.ConfigurationFlags |=
7559 	    cpu_to_le16(MPI26_IOCINIT_CFGFLAGS_COREDUMP_ENABLE);
7560 
7561 	/* This time stamp specifies number of milliseconds
7562 	 * since epoch ~ midnight January 1, 1970.
7563 	 */
7564 	current_time = ktime_get_real();
7565 	mpi_request.TimeStamp = cpu_to_le64(ktime_to_ms(current_time));
7566 
7567 	if (ioc->logging_level & MPT_DEBUG_INIT) {
7568 		__le32 *mfp;
7569 		int i;
7570 
7571 		mfp = (__le32 *)&mpi_request;
7572 		ioc_info(ioc, "\toffset:data\n");
7573 		for (i = 0; i < sizeof(Mpi2IOCInitRequest_t)/4; i++)
7574 			ioc_info(ioc, "\t[0x%02x]:%08x\n", i*4,
7575 			    le32_to_cpu(mfp[i]));
7576 	}
7577 
7578 	r = _base_handshake_req_reply_wait(ioc,
7579 	    sizeof(Mpi2IOCInitRequest_t), (u32 *)&mpi_request,
7580 	    sizeof(Mpi2IOCInitReply_t), (u16 *)&mpi_reply, 30);
7581 
7582 	if (r != 0) {
7583 		ioc_err(ioc, "%s: handshake failed (r=%d)\n", __func__, r);
7584 		return r;
7585 	}
7586 
7587 	ioc_status = le16_to_cpu(mpi_reply.IOCStatus) & MPI2_IOCSTATUS_MASK;
7588 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS ||
7589 	    mpi_reply.IOCLogInfo) {
7590 		ioc_err(ioc, "%s: failed\n", __func__);
7591 		r = -EIO;
7592 	}
7593 
7594 	/* Reset TimeSync Counter*/
7595 	ioc->timestamp_update_count = 0;
7596 	return r;
7597 }
7598 
7599 /**
7600  * mpt3sas_port_enable_done - command completion routine for port enable
7601  * @ioc: per adapter object
7602  * @smid: system request message index
7603  * @msix_index: MSIX table index supplied by the OS
7604  * @reply: reply message frame(lower 32bit addr)
7605  *
7606  * Return: 1 meaning mf should be freed from _base_interrupt
7607  *          0 means the mf is freed from this function.
7608  */
7609 u8
7610 mpt3sas_port_enable_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
7611 	u32 reply)
7612 {
7613 	MPI2DefaultReply_t *mpi_reply;
7614 	u16 ioc_status;
7615 
7616 	if (ioc->port_enable_cmds.status == MPT3_CMD_NOT_USED)
7617 		return 1;
7618 
7619 	mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
7620 	if (!mpi_reply)
7621 		return 1;
7622 
7623 	if (mpi_reply->Function != MPI2_FUNCTION_PORT_ENABLE)
7624 		return 1;
7625 
7626 	ioc->port_enable_cmds.status &= ~MPT3_CMD_PENDING;
7627 	ioc->port_enable_cmds.status |= MPT3_CMD_COMPLETE;
7628 	ioc->port_enable_cmds.status |= MPT3_CMD_REPLY_VALID;
7629 	memcpy(ioc->port_enable_cmds.reply, mpi_reply, mpi_reply->MsgLength*4);
7630 	ioc_status = le16_to_cpu(mpi_reply->IOCStatus) & MPI2_IOCSTATUS_MASK;
7631 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS)
7632 		ioc->port_enable_failed = 1;
7633 
7634 	if (ioc->port_enable_cmds.status & MPT3_CMD_COMPLETE_ASYNC) {
7635 		ioc->port_enable_cmds.status &= ~MPT3_CMD_COMPLETE_ASYNC;
7636 		if (ioc_status == MPI2_IOCSTATUS_SUCCESS) {
7637 			mpt3sas_port_enable_complete(ioc);
7638 			return 1;
7639 		} else {
7640 			ioc->start_scan_failed = ioc_status;
7641 			ioc->start_scan = 0;
7642 			return 1;
7643 		}
7644 	}
7645 	complete(&ioc->port_enable_cmds.done);
7646 	return 1;
7647 }
7648 
7649 /**
7650  * _base_send_port_enable - send port_enable(discovery stuff) to firmware
7651  * @ioc: per adapter object
7652  *
7653  * Return: 0 for success, non-zero for failure.
7654  */
7655 static int
7656 _base_send_port_enable(struct MPT3SAS_ADAPTER *ioc)
7657 {
7658 	Mpi2PortEnableRequest_t *mpi_request;
7659 	Mpi2PortEnableReply_t *mpi_reply;
7660 	int r = 0;
7661 	u16 smid;
7662 	u16 ioc_status;
7663 
7664 	ioc_info(ioc, "sending port enable !!\n");
7665 
7666 	if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
7667 		ioc_err(ioc, "%s: internal command already in use\n", __func__);
7668 		return -EAGAIN;
7669 	}
7670 
7671 	smid = mpt3sas_base_get_smid(ioc, ioc->port_enable_cb_idx);
7672 	if (!smid) {
7673 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
7674 		return -EAGAIN;
7675 	}
7676 
7677 	ioc->port_enable_cmds.status = MPT3_CMD_PENDING;
7678 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
7679 	ioc->port_enable_cmds.smid = smid;
7680 	memset(mpi_request, 0, sizeof(Mpi2PortEnableRequest_t));
7681 	mpi_request->Function = MPI2_FUNCTION_PORT_ENABLE;
7682 
7683 	init_completion(&ioc->port_enable_cmds.done);
7684 	ioc->put_smid_default(ioc, smid);
7685 	wait_for_completion_timeout(&ioc->port_enable_cmds.done, 300*HZ);
7686 	if (!(ioc->port_enable_cmds.status & MPT3_CMD_COMPLETE)) {
7687 		ioc_err(ioc, "%s: timeout\n", __func__);
7688 		_debug_dump_mf(mpi_request,
7689 		    sizeof(Mpi2PortEnableRequest_t)/4);
7690 		if (ioc->port_enable_cmds.status & MPT3_CMD_RESET)
7691 			r = -EFAULT;
7692 		else
7693 			r = -ETIME;
7694 		goto out;
7695 	}
7696 
7697 	mpi_reply = ioc->port_enable_cmds.reply;
7698 	ioc_status = le16_to_cpu(mpi_reply->IOCStatus) & MPI2_IOCSTATUS_MASK;
7699 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
7700 		ioc_err(ioc, "%s: failed with (ioc_status=0x%08x)\n",
7701 			__func__, ioc_status);
7702 		r = -EFAULT;
7703 		goto out;
7704 	}
7705 
7706  out:
7707 	ioc->port_enable_cmds.status = MPT3_CMD_NOT_USED;
7708 	ioc_info(ioc, "port enable: %s\n", r == 0 ? "SUCCESS" : "FAILED");
7709 	return r;
7710 }
7711 
7712 /**
7713  * mpt3sas_port_enable - initiate firmware discovery (don't wait for reply)
7714  * @ioc: per adapter object
7715  *
7716  * Return: 0 for success, non-zero for failure.
7717  */
7718 int
7719 mpt3sas_port_enable(struct MPT3SAS_ADAPTER *ioc)
7720 {
7721 	Mpi2PortEnableRequest_t *mpi_request;
7722 	u16 smid;
7723 
7724 	ioc_info(ioc, "sending port enable !!\n");
7725 
7726 	if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
7727 		ioc_err(ioc, "%s: internal command already in use\n", __func__);
7728 		return -EAGAIN;
7729 	}
7730 
7731 	smid = mpt3sas_base_get_smid(ioc, ioc->port_enable_cb_idx);
7732 	if (!smid) {
7733 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
7734 		return -EAGAIN;
7735 	}
7736 	ioc->drv_internal_flags |= MPT_DRV_INTERNAL_FIRST_PE_ISSUED;
7737 	ioc->port_enable_cmds.status = MPT3_CMD_PENDING;
7738 	ioc->port_enable_cmds.status |= MPT3_CMD_COMPLETE_ASYNC;
7739 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
7740 	ioc->port_enable_cmds.smid = smid;
7741 	memset(mpi_request, 0, sizeof(Mpi2PortEnableRequest_t));
7742 	mpi_request->Function = MPI2_FUNCTION_PORT_ENABLE;
7743 
7744 	ioc->put_smid_default(ioc, smid);
7745 	return 0;
7746 }
7747 
7748 /**
7749  * _base_determine_wait_on_discovery - desposition
7750  * @ioc: per adapter object
7751  *
7752  * Decide whether to wait on discovery to complete. Used to either
7753  * locate boot device, or report volumes ahead of physical devices.
7754  *
7755  * Return: 1 for wait, 0 for don't wait.
7756  */
7757 static int
7758 _base_determine_wait_on_discovery(struct MPT3SAS_ADAPTER *ioc)
7759 {
7760 	/* We wait for discovery to complete if IR firmware is loaded.
7761 	 * The sas topology events arrive before PD events, so we need time to
7762 	 * turn on the bit in ioc->pd_handles to indicate PD
7763 	 * Also, it maybe required to report Volumes ahead of physical
7764 	 * devices when MPI2_IOCPAGE8_IRFLAGS_LOW_VOLUME_MAPPING is set.
7765 	 */
7766 	if (ioc->ir_firmware)
7767 		return 1;
7768 
7769 	/* if no Bios, then we don't need to wait */
7770 	if (!ioc->bios_pg3.BiosVersion)
7771 		return 0;
7772 
7773 	/* Bios is present, then we drop down here.
7774 	 *
7775 	 * If there any entries in the Bios Page 2, then we wait
7776 	 * for discovery to complete.
7777 	 */
7778 
7779 	/* Current Boot Device */
7780 	if ((ioc->bios_pg2.CurrentBootDeviceForm &
7781 	    MPI2_BIOSPAGE2_FORM_MASK) ==
7782 	    MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED &&
7783 	/* Request Boot Device */
7784 	   (ioc->bios_pg2.ReqBootDeviceForm &
7785 	    MPI2_BIOSPAGE2_FORM_MASK) ==
7786 	    MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED &&
7787 	/* Alternate Request Boot Device */
7788 	   (ioc->bios_pg2.ReqAltBootDeviceForm &
7789 	    MPI2_BIOSPAGE2_FORM_MASK) ==
7790 	    MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED)
7791 		return 0;
7792 
7793 	return 1;
7794 }
7795 
7796 /**
7797  * _base_unmask_events - turn on notification for this event
7798  * @ioc: per adapter object
7799  * @event: firmware event
7800  *
7801  * The mask is stored in ioc->event_masks.
7802  */
7803 static void
7804 _base_unmask_events(struct MPT3SAS_ADAPTER *ioc, u16 event)
7805 {
7806 	u32 desired_event;
7807 
7808 	if (event >= 128)
7809 		return;
7810 
7811 	desired_event = (1 << (event % 32));
7812 
7813 	if (event < 32)
7814 		ioc->event_masks[0] &= ~desired_event;
7815 	else if (event < 64)
7816 		ioc->event_masks[1] &= ~desired_event;
7817 	else if (event < 96)
7818 		ioc->event_masks[2] &= ~desired_event;
7819 	else if (event < 128)
7820 		ioc->event_masks[3] &= ~desired_event;
7821 }
7822 
7823 /**
7824  * _base_event_notification - send event notification
7825  * @ioc: per adapter object
7826  *
7827  * Return: 0 for success, non-zero for failure.
7828  */
7829 static int
7830 _base_event_notification(struct MPT3SAS_ADAPTER *ioc)
7831 {
7832 	Mpi2EventNotificationRequest_t *mpi_request;
7833 	u16 smid;
7834 	int r = 0;
7835 	int i, issue_diag_reset = 0;
7836 
7837 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
7838 
7839 	if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
7840 		ioc_err(ioc, "%s: internal command already in use\n", __func__);
7841 		return -EAGAIN;
7842 	}
7843 
7844 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
7845 	if (!smid) {
7846 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
7847 		return -EAGAIN;
7848 	}
7849 	ioc->base_cmds.status = MPT3_CMD_PENDING;
7850 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
7851 	ioc->base_cmds.smid = smid;
7852 	memset(mpi_request, 0, sizeof(Mpi2EventNotificationRequest_t));
7853 	mpi_request->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
7854 	mpi_request->VF_ID = 0; /* TODO */
7855 	mpi_request->VP_ID = 0;
7856 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
7857 		mpi_request->EventMasks[i] =
7858 		    cpu_to_le32(ioc->event_masks[i]);
7859 	init_completion(&ioc->base_cmds.done);
7860 	ioc->put_smid_default(ioc, smid);
7861 	wait_for_completion_timeout(&ioc->base_cmds.done, 30*HZ);
7862 	if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
7863 		ioc_err(ioc, "%s: timeout\n", __func__);
7864 		_debug_dump_mf(mpi_request,
7865 		    sizeof(Mpi2EventNotificationRequest_t)/4);
7866 		if (ioc->base_cmds.status & MPT3_CMD_RESET)
7867 			r = -EFAULT;
7868 		else
7869 			issue_diag_reset = 1;
7870 
7871 	} else
7872 		dinitprintk(ioc, ioc_info(ioc, "%s: complete\n", __func__));
7873 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
7874 
7875 	if (issue_diag_reset) {
7876 		if (ioc->drv_internal_flags & MPT_DRV_INTERNAL_FIRST_PE_ISSUED)
7877 			return -EFAULT;
7878 		if (mpt3sas_base_check_for_fault_and_issue_reset(ioc))
7879 			return -EFAULT;
7880 		r = -EAGAIN;
7881 	}
7882 	return r;
7883 }
7884 
7885 /**
7886  * mpt3sas_base_validate_event_type - validating event types
7887  * @ioc: per adapter object
7888  * @event_type: firmware event
7889  *
7890  * This will turn on firmware event notification when application
7891  * ask for that event. We don't mask events that are already enabled.
7892  */
7893 void
7894 mpt3sas_base_validate_event_type(struct MPT3SAS_ADAPTER *ioc, u32 *event_type)
7895 {
7896 	int i, j;
7897 	u32 event_mask, desired_event;
7898 	u8 send_update_to_fw;
7899 
7900 	for (i = 0, send_update_to_fw = 0; i <
7901 	    MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++) {
7902 		event_mask = ~event_type[i];
7903 		desired_event = 1;
7904 		for (j = 0; j < 32; j++) {
7905 			if (!(event_mask & desired_event) &&
7906 			    (ioc->event_masks[i] & desired_event)) {
7907 				ioc->event_masks[i] &= ~desired_event;
7908 				send_update_to_fw = 1;
7909 			}
7910 			desired_event = (desired_event << 1);
7911 		}
7912 	}
7913 
7914 	if (!send_update_to_fw)
7915 		return;
7916 
7917 	mutex_lock(&ioc->base_cmds.mutex);
7918 	_base_event_notification(ioc);
7919 	mutex_unlock(&ioc->base_cmds.mutex);
7920 }
7921 
7922 /**
7923  * _base_diag_reset - the "big hammer" start of day reset
7924  * @ioc: per adapter object
7925  *
7926  * Return: 0 for success, non-zero for failure.
7927  */
7928 static int
7929 _base_diag_reset(struct MPT3SAS_ADAPTER *ioc)
7930 {
7931 	u32 host_diagnostic;
7932 	u32 ioc_state;
7933 	u32 count;
7934 	u32 hcb_size;
7935 
7936 	ioc_info(ioc, "sending diag reset !!\n");
7937 
7938 	pci_cfg_access_lock(ioc->pdev);
7939 
7940 	drsprintk(ioc, ioc_info(ioc, "clear interrupts\n"));
7941 
7942 	count = 0;
7943 	do {
7944 		/* Write magic sequence to WriteSequence register
7945 		 * Loop until in diagnostic mode
7946 		 */
7947 		drsprintk(ioc, ioc_info(ioc, "write magic sequence\n"));
7948 		writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
7949 		writel(MPI2_WRSEQ_1ST_KEY_VALUE, &ioc->chip->WriteSequence);
7950 		writel(MPI2_WRSEQ_2ND_KEY_VALUE, &ioc->chip->WriteSequence);
7951 		writel(MPI2_WRSEQ_3RD_KEY_VALUE, &ioc->chip->WriteSequence);
7952 		writel(MPI2_WRSEQ_4TH_KEY_VALUE, &ioc->chip->WriteSequence);
7953 		writel(MPI2_WRSEQ_5TH_KEY_VALUE, &ioc->chip->WriteSequence);
7954 		writel(MPI2_WRSEQ_6TH_KEY_VALUE, &ioc->chip->WriteSequence);
7955 
7956 		/* wait 100 msec */
7957 		msleep(100);
7958 
7959 		if (count++ > 20) {
7960 			ioc_info(ioc,
7961 			    "Stop writing magic sequence after 20 retries\n");
7962 			_base_dump_reg_set(ioc);
7963 			goto out;
7964 		}
7965 
7966 		host_diagnostic = ioc->base_readl(&ioc->chip->HostDiagnostic);
7967 		drsprintk(ioc,
7968 			  ioc_info(ioc, "wrote magic sequence: count(%d), host_diagnostic(0x%08x)\n",
7969 				   count, host_diagnostic));
7970 
7971 	} while ((host_diagnostic & MPI2_DIAG_DIAG_WRITE_ENABLE) == 0);
7972 
7973 	hcb_size = ioc->base_readl(&ioc->chip->HCBSize);
7974 
7975 	drsprintk(ioc, ioc_info(ioc, "diag reset: issued\n"));
7976 	writel(host_diagnostic | MPI2_DIAG_RESET_ADAPTER,
7977 	     &ioc->chip->HostDiagnostic);
7978 
7979 	/*This delay allows the chip PCIe hardware time to finish reset tasks*/
7980 	msleep(MPI2_HARD_RESET_PCIE_FIRST_READ_DELAY_MICRO_SEC/1000);
7981 
7982 	/* Approximately 300 second max wait */
7983 	for (count = 0; count < (300000000 /
7984 		MPI2_HARD_RESET_PCIE_SECOND_READ_DELAY_MICRO_SEC); count++) {
7985 
7986 		host_diagnostic = ioc->base_readl(&ioc->chip->HostDiagnostic);
7987 
7988 		if (host_diagnostic == 0xFFFFFFFF) {
7989 			ioc_info(ioc,
7990 			    "Invalid host diagnostic register value\n");
7991 			_base_dump_reg_set(ioc);
7992 			goto out;
7993 		}
7994 		if (!(host_diagnostic & MPI2_DIAG_RESET_ADAPTER))
7995 			break;
7996 
7997 		msleep(MPI2_HARD_RESET_PCIE_SECOND_READ_DELAY_MICRO_SEC / 1000);
7998 	}
7999 
8000 	if (host_diagnostic & MPI2_DIAG_HCB_MODE) {
8001 
8002 		drsprintk(ioc,
8003 			  ioc_info(ioc, "restart the adapter assuming the HCB Address points to good F/W\n"));
8004 		host_diagnostic &= ~MPI2_DIAG_BOOT_DEVICE_SELECT_MASK;
8005 		host_diagnostic |= MPI2_DIAG_BOOT_DEVICE_SELECT_HCDW;
8006 		writel(host_diagnostic, &ioc->chip->HostDiagnostic);
8007 
8008 		drsprintk(ioc, ioc_info(ioc, "re-enable the HCDW\n"));
8009 		writel(hcb_size | MPI2_HCB_SIZE_HCB_ENABLE,
8010 		    &ioc->chip->HCBSize);
8011 	}
8012 
8013 	drsprintk(ioc, ioc_info(ioc, "restart the adapter\n"));
8014 	writel(host_diagnostic & ~MPI2_DIAG_HOLD_IOC_RESET,
8015 	    &ioc->chip->HostDiagnostic);
8016 
8017 	drsprintk(ioc,
8018 		  ioc_info(ioc, "disable writes to the diagnostic register\n"));
8019 	writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
8020 
8021 	drsprintk(ioc, ioc_info(ioc, "Wait for FW to go to the READY state\n"));
8022 	ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, 20);
8023 	if (ioc_state) {
8024 		ioc_err(ioc, "%s: failed going to ready state (ioc_state=0x%x)\n",
8025 			__func__, ioc_state);
8026 		_base_dump_reg_set(ioc);
8027 		goto out;
8028 	}
8029 
8030 	pci_cfg_access_unlock(ioc->pdev);
8031 	ioc_info(ioc, "diag reset: SUCCESS\n");
8032 	return 0;
8033 
8034  out:
8035 	pci_cfg_access_unlock(ioc->pdev);
8036 	ioc_err(ioc, "diag reset: FAILED\n");
8037 	return -EFAULT;
8038 }
8039 
8040 /**
8041  * mpt3sas_base_make_ioc_ready - put controller in READY state
8042  * @ioc: per adapter object
8043  * @type: FORCE_BIG_HAMMER or SOFT_RESET
8044  *
8045  * Return: 0 for success, non-zero for failure.
8046  */
8047 int
8048 mpt3sas_base_make_ioc_ready(struct MPT3SAS_ADAPTER *ioc, enum reset_type type)
8049 {
8050 	u32 ioc_state;
8051 	int rc;
8052 	int count;
8053 
8054 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
8055 
8056 	if (ioc->pci_error_recovery)
8057 		return 0;
8058 
8059 	ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
8060 	dhsprintk(ioc,
8061 		  ioc_info(ioc, "%s: ioc_state(0x%08x)\n",
8062 			   __func__, ioc_state));
8063 
8064 	/* if in RESET state, it should move to READY state shortly */
8065 	count = 0;
8066 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_RESET) {
8067 		while ((ioc_state & MPI2_IOC_STATE_MASK) !=
8068 		    MPI2_IOC_STATE_READY) {
8069 			if (count++ == 10) {
8070 				ioc_err(ioc, "%s: failed going to ready state (ioc_state=0x%x)\n",
8071 					__func__, ioc_state);
8072 				return -EFAULT;
8073 			}
8074 			ssleep(1);
8075 			ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
8076 		}
8077 	}
8078 
8079 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_READY)
8080 		return 0;
8081 
8082 	if (ioc_state & MPI2_DOORBELL_USED) {
8083 		ioc_info(ioc, "unexpected doorbell active!\n");
8084 		goto issue_diag_reset;
8085 	}
8086 
8087 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
8088 		mpt3sas_print_fault_code(ioc, ioc_state &
8089 		    MPI2_DOORBELL_DATA_MASK);
8090 		goto issue_diag_reset;
8091 	}
8092 
8093 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_COREDUMP) {
8094 		/*
8095 		 * if host reset is invoked while watch dog thread is waiting
8096 		 * for IOC state to be changed to Fault state then driver has
8097 		 * to wait here for CoreDump state to clear otherwise reset
8098 		 * will be issued to the FW and FW move the IOC state to
8099 		 * reset state without copying the FW logs to coredump region.
8100 		 */
8101 		if (ioc->ioc_coredump_loop != MPT3SAS_COREDUMP_LOOP_DONE) {
8102 			mpt3sas_print_coredump_info(ioc, ioc_state &
8103 			    MPI2_DOORBELL_DATA_MASK);
8104 			mpt3sas_base_wait_for_coredump_completion(ioc,
8105 			    __func__);
8106 		}
8107 		goto issue_diag_reset;
8108 	}
8109 
8110 	if (type == FORCE_BIG_HAMMER)
8111 		goto issue_diag_reset;
8112 
8113 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_OPERATIONAL)
8114 		if (!(_base_send_ioc_reset(ioc,
8115 		    MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET, 15))) {
8116 			return 0;
8117 	}
8118 
8119  issue_diag_reset:
8120 	rc = _base_diag_reset(ioc);
8121 	return rc;
8122 }
8123 
8124 /**
8125  * _base_make_ioc_operational - put controller in OPERATIONAL state
8126  * @ioc: per adapter object
8127  *
8128  * Return: 0 for success, non-zero for failure.
8129  */
8130 static int
8131 _base_make_ioc_operational(struct MPT3SAS_ADAPTER *ioc)
8132 {
8133 	int r, i, index, rc;
8134 	unsigned long	flags;
8135 	u32 reply_address;
8136 	u16 smid;
8137 	struct _tr_list *delayed_tr, *delayed_tr_next;
8138 	struct _sc_list *delayed_sc, *delayed_sc_next;
8139 	struct _event_ack_list *delayed_event_ack, *delayed_event_ack_next;
8140 	u8 hide_flag;
8141 	struct adapter_reply_queue *reply_q;
8142 	Mpi2ReplyDescriptorsUnion_t *reply_post_free_contig;
8143 
8144 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
8145 
8146 	/* clean the delayed target reset list */
8147 	list_for_each_entry_safe(delayed_tr, delayed_tr_next,
8148 	    &ioc->delayed_tr_list, list) {
8149 		list_del(&delayed_tr->list);
8150 		kfree(delayed_tr);
8151 	}
8152 
8153 
8154 	list_for_each_entry_safe(delayed_tr, delayed_tr_next,
8155 	    &ioc->delayed_tr_volume_list, list) {
8156 		list_del(&delayed_tr->list);
8157 		kfree(delayed_tr);
8158 	}
8159 
8160 	list_for_each_entry_safe(delayed_sc, delayed_sc_next,
8161 	    &ioc->delayed_sc_list, list) {
8162 		list_del(&delayed_sc->list);
8163 		kfree(delayed_sc);
8164 	}
8165 
8166 	list_for_each_entry_safe(delayed_event_ack, delayed_event_ack_next,
8167 	    &ioc->delayed_event_ack_list, list) {
8168 		list_del(&delayed_event_ack->list);
8169 		kfree(delayed_event_ack);
8170 	}
8171 
8172 	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
8173 
8174 	/* hi-priority queue */
8175 	INIT_LIST_HEAD(&ioc->hpr_free_list);
8176 	smid = ioc->hi_priority_smid;
8177 	for (i = 0; i < ioc->hi_priority_depth; i++, smid++) {
8178 		ioc->hpr_lookup[i].cb_idx = 0xFF;
8179 		ioc->hpr_lookup[i].smid = smid;
8180 		list_add_tail(&ioc->hpr_lookup[i].tracker_list,
8181 		    &ioc->hpr_free_list);
8182 	}
8183 
8184 	/* internal queue */
8185 	INIT_LIST_HEAD(&ioc->internal_free_list);
8186 	smid = ioc->internal_smid;
8187 	for (i = 0; i < ioc->internal_depth; i++, smid++) {
8188 		ioc->internal_lookup[i].cb_idx = 0xFF;
8189 		ioc->internal_lookup[i].smid = smid;
8190 		list_add_tail(&ioc->internal_lookup[i].tracker_list,
8191 		    &ioc->internal_free_list);
8192 	}
8193 
8194 	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
8195 
8196 	/* initialize Reply Free Queue */
8197 	for (i = 0, reply_address = (u32)ioc->reply_dma ;
8198 	    i < ioc->reply_free_queue_depth ; i++, reply_address +=
8199 	    ioc->reply_sz) {
8200 		ioc->reply_free[i] = cpu_to_le32(reply_address);
8201 		if (ioc->is_mcpu_endpoint)
8202 			_base_clone_reply_to_sys_mem(ioc,
8203 					reply_address, i);
8204 	}
8205 
8206 	/* initialize reply queues */
8207 	if (ioc->is_driver_loading)
8208 		_base_assign_reply_queues(ioc);
8209 
8210 	/* initialize Reply Post Free Queue */
8211 	index = 0;
8212 	reply_post_free_contig = ioc->reply_post[0].reply_post_free;
8213 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
8214 		/*
8215 		 * If RDPQ is enabled, switch to the next allocation.
8216 		 * Otherwise advance within the contiguous region.
8217 		 */
8218 		if (ioc->rdpq_array_enable) {
8219 			reply_q->reply_post_free =
8220 				ioc->reply_post[index++].reply_post_free;
8221 		} else {
8222 			reply_q->reply_post_free = reply_post_free_contig;
8223 			reply_post_free_contig += ioc->reply_post_queue_depth;
8224 		}
8225 
8226 		reply_q->reply_post_host_index = 0;
8227 		for (i = 0; i < ioc->reply_post_queue_depth; i++)
8228 			reply_q->reply_post_free[i].Words =
8229 			    cpu_to_le64(ULLONG_MAX);
8230 		if (!_base_is_controller_msix_enabled(ioc))
8231 			goto skip_init_reply_post_free_queue;
8232 	}
8233  skip_init_reply_post_free_queue:
8234 
8235 	r = _base_send_ioc_init(ioc);
8236 	if (r) {
8237 		/*
8238 		 * No need to check IOC state for fault state & issue
8239 		 * diag reset during host reset. This check is need
8240 		 * only during driver load time.
8241 		 */
8242 		if (!ioc->is_driver_loading)
8243 			return r;
8244 
8245 		rc = mpt3sas_base_check_for_fault_and_issue_reset(ioc);
8246 		if (rc || (_base_send_ioc_init(ioc)))
8247 			return r;
8248 	}
8249 
8250 	/* initialize reply free host index */
8251 	ioc->reply_free_host_index = ioc->reply_free_queue_depth - 1;
8252 	writel(ioc->reply_free_host_index, &ioc->chip->ReplyFreeHostIndex);
8253 
8254 	/* initialize reply post host index */
8255 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
8256 		if (ioc->combined_reply_queue)
8257 			writel((reply_q->msix_index & 7)<<
8258 			   MPI2_RPHI_MSIX_INDEX_SHIFT,
8259 			   ioc->replyPostRegisterIndex[reply_q->msix_index/8]);
8260 		else
8261 			writel(reply_q->msix_index <<
8262 				MPI2_RPHI_MSIX_INDEX_SHIFT,
8263 				&ioc->chip->ReplyPostHostIndex);
8264 
8265 		if (!_base_is_controller_msix_enabled(ioc))
8266 			goto skip_init_reply_post_host_index;
8267 	}
8268 
8269  skip_init_reply_post_host_index:
8270 
8271 	mpt3sas_base_unmask_interrupts(ioc);
8272 
8273 	if (ioc->hba_mpi_version_belonged != MPI2_VERSION) {
8274 		r = _base_display_fwpkg_version(ioc);
8275 		if (r)
8276 			return r;
8277 	}
8278 
8279 	r = _base_static_config_pages(ioc);
8280 	if (r)
8281 		return r;
8282 
8283 	r = _base_event_notification(ioc);
8284 	if (r)
8285 		return r;
8286 
8287 	if (!ioc->shost_recovery) {
8288 
8289 		if (ioc->is_warpdrive && ioc->manu_pg10.OEMIdentifier
8290 		    == 0x80) {
8291 			hide_flag = (u8) (
8292 			    le32_to_cpu(ioc->manu_pg10.OEMSpecificFlags0) &
8293 			    MFG_PAGE10_HIDE_SSDS_MASK);
8294 			if (hide_flag != MFG_PAGE10_HIDE_SSDS_MASK)
8295 				ioc->mfg_pg10_hide_flag = hide_flag;
8296 		}
8297 
8298 		ioc->wait_for_discovery_to_complete =
8299 		    _base_determine_wait_on_discovery(ioc);
8300 
8301 		return r; /* scan_start and scan_finished support */
8302 	}
8303 
8304 	r = _base_send_port_enable(ioc);
8305 	if (r)
8306 		return r;
8307 
8308 	return r;
8309 }
8310 
8311 /**
8312  * mpt3sas_base_free_resources - free resources controller resources
8313  * @ioc: per adapter object
8314  */
8315 void
8316 mpt3sas_base_free_resources(struct MPT3SAS_ADAPTER *ioc)
8317 {
8318 	dexitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
8319 
8320 	/* synchronizing freeing resource with pci_access_mutex lock */
8321 	mutex_lock(&ioc->pci_access_mutex);
8322 	if (ioc->chip_phys && ioc->chip) {
8323 		mpt3sas_base_mask_interrupts(ioc);
8324 		ioc->shost_recovery = 1;
8325 		mpt3sas_base_make_ioc_ready(ioc, SOFT_RESET);
8326 		ioc->shost_recovery = 0;
8327 	}
8328 
8329 	mpt3sas_base_unmap_resources(ioc);
8330 	mutex_unlock(&ioc->pci_access_mutex);
8331 	return;
8332 }
8333 
8334 /**
8335  * mpt3sas_base_attach - attach controller instance
8336  * @ioc: per adapter object
8337  *
8338  * Return: 0 for success, non-zero for failure.
8339  */
8340 int
8341 mpt3sas_base_attach(struct MPT3SAS_ADAPTER *ioc)
8342 {
8343 	int r, i, rc;
8344 	int cpu_id, last_cpu_id = 0;
8345 
8346 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
8347 
8348 	/* setup cpu_msix_table */
8349 	ioc->cpu_count = num_online_cpus();
8350 	for_each_online_cpu(cpu_id)
8351 		last_cpu_id = cpu_id;
8352 	ioc->cpu_msix_table_sz = last_cpu_id + 1;
8353 	ioc->cpu_msix_table = kzalloc(ioc->cpu_msix_table_sz, GFP_KERNEL);
8354 	ioc->reply_queue_count = 1;
8355 	if (!ioc->cpu_msix_table) {
8356 		ioc_info(ioc, "Allocation for cpu_msix_table failed!!!\n");
8357 		r = -ENOMEM;
8358 		goto out_free_resources;
8359 	}
8360 
8361 	if (ioc->is_warpdrive) {
8362 		ioc->reply_post_host_index = kcalloc(ioc->cpu_msix_table_sz,
8363 		    sizeof(resource_size_t *), GFP_KERNEL);
8364 		if (!ioc->reply_post_host_index) {
8365 			ioc_info(ioc, "Allocation for reply_post_host_index failed!!!\n");
8366 			r = -ENOMEM;
8367 			goto out_free_resources;
8368 		}
8369 	}
8370 
8371 	ioc->smp_affinity_enable = smp_affinity_enable;
8372 
8373 	ioc->rdpq_array_enable_assigned = 0;
8374 	ioc->use_32bit_dma = false;
8375 	ioc->dma_mask = 64;
8376 	if (ioc->is_aero_ioc)
8377 		ioc->base_readl = &_base_readl_aero;
8378 	else
8379 		ioc->base_readl = &_base_readl;
8380 	r = mpt3sas_base_map_resources(ioc);
8381 	if (r)
8382 		goto out_free_resources;
8383 
8384 	pci_set_drvdata(ioc->pdev, ioc->shost);
8385 	r = _base_get_ioc_facts(ioc);
8386 	if (r) {
8387 		rc = mpt3sas_base_check_for_fault_and_issue_reset(ioc);
8388 		if (rc || (_base_get_ioc_facts(ioc)))
8389 			goto out_free_resources;
8390 	}
8391 
8392 	switch (ioc->hba_mpi_version_belonged) {
8393 	case MPI2_VERSION:
8394 		ioc->build_sg_scmd = &_base_build_sg_scmd;
8395 		ioc->build_sg = &_base_build_sg;
8396 		ioc->build_zero_len_sge = &_base_build_zero_len_sge;
8397 		ioc->get_msix_index_for_smlio = &_base_get_msix_index;
8398 		break;
8399 	case MPI25_VERSION:
8400 	case MPI26_VERSION:
8401 		/*
8402 		 * In SAS3.0,
8403 		 * SCSI_IO, SMP_PASSTHRU, SATA_PASSTHRU, Target Assist, and
8404 		 * Target Status - all require the IEEE formatted scatter gather
8405 		 * elements.
8406 		 */
8407 		ioc->build_sg_scmd = &_base_build_sg_scmd_ieee;
8408 		ioc->build_sg = &_base_build_sg_ieee;
8409 		ioc->build_nvme_prp = &_base_build_nvme_prp;
8410 		ioc->build_zero_len_sge = &_base_build_zero_len_sge_ieee;
8411 		ioc->sge_size_ieee = sizeof(Mpi2IeeeSgeSimple64_t);
8412 		if (ioc->high_iops_queues)
8413 			ioc->get_msix_index_for_smlio =
8414 					&_base_get_high_iops_msix_index;
8415 		else
8416 			ioc->get_msix_index_for_smlio = &_base_get_msix_index;
8417 		break;
8418 	}
8419 	if (ioc->atomic_desc_capable) {
8420 		ioc->put_smid_default = &_base_put_smid_default_atomic;
8421 		ioc->put_smid_scsi_io = &_base_put_smid_scsi_io_atomic;
8422 		ioc->put_smid_fast_path =
8423 				&_base_put_smid_fast_path_atomic;
8424 		ioc->put_smid_hi_priority =
8425 				&_base_put_smid_hi_priority_atomic;
8426 	} else {
8427 		ioc->put_smid_default = &_base_put_smid_default;
8428 		ioc->put_smid_fast_path = &_base_put_smid_fast_path;
8429 		ioc->put_smid_hi_priority = &_base_put_smid_hi_priority;
8430 		if (ioc->is_mcpu_endpoint)
8431 			ioc->put_smid_scsi_io =
8432 				&_base_put_smid_mpi_ep_scsi_io;
8433 		else
8434 			ioc->put_smid_scsi_io = &_base_put_smid_scsi_io;
8435 	}
8436 	/*
8437 	 * These function pointers for other requests that don't
8438 	 * the require IEEE scatter gather elements.
8439 	 *
8440 	 * For example Configuration Pages and SAS IOUNIT Control don't.
8441 	 */
8442 	ioc->build_sg_mpi = &_base_build_sg;
8443 	ioc->build_zero_len_sge_mpi = &_base_build_zero_len_sge;
8444 
8445 	r = mpt3sas_base_make_ioc_ready(ioc, SOFT_RESET);
8446 	if (r)
8447 		goto out_free_resources;
8448 
8449 	ioc->pfacts = kcalloc(ioc->facts.NumberOfPorts,
8450 	    sizeof(struct mpt3sas_port_facts), GFP_KERNEL);
8451 	if (!ioc->pfacts) {
8452 		r = -ENOMEM;
8453 		goto out_free_resources;
8454 	}
8455 
8456 	for (i = 0 ; i < ioc->facts.NumberOfPorts; i++) {
8457 		r = _base_get_port_facts(ioc, i);
8458 		if (r) {
8459 			rc = mpt3sas_base_check_for_fault_and_issue_reset(ioc);
8460 			if (rc || (_base_get_port_facts(ioc, i)))
8461 				goto out_free_resources;
8462 		}
8463 	}
8464 
8465 	r = _base_allocate_memory_pools(ioc);
8466 	if (r)
8467 		goto out_free_resources;
8468 
8469 	if (irqpoll_weight > 0)
8470 		ioc->thresh_hold = irqpoll_weight;
8471 	else
8472 		ioc->thresh_hold = ioc->hba_queue_depth/4;
8473 
8474 	_base_init_irqpolls(ioc);
8475 	init_waitqueue_head(&ioc->reset_wq);
8476 
8477 	/* allocate memory pd handle bitmask list */
8478 	ioc->pd_handles_sz = (ioc->facts.MaxDevHandle / 8);
8479 	if (ioc->facts.MaxDevHandle % 8)
8480 		ioc->pd_handles_sz++;
8481 	ioc->pd_handles = kzalloc(ioc->pd_handles_sz,
8482 	    GFP_KERNEL);
8483 	if (!ioc->pd_handles) {
8484 		r = -ENOMEM;
8485 		goto out_free_resources;
8486 	}
8487 	ioc->blocking_handles = kzalloc(ioc->pd_handles_sz,
8488 	    GFP_KERNEL);
8489 	if (!ioc->blocking_handles) {
8490 		r = -ENOMEM;
8491 		goto out_free_resources;
8492 	}
8493 
8494 	/* allocate memory for pending OS device add list */
8495 	ioc->pend_os_device_add_sz = (ioc->facts.MaxDevHandle / 8);
8496 	if (ioc->facts.MaxDevHandle % 8)
8497 		ioc->pend_os_device_add_sz++;
8498 	ioc->pend_os_device_add = kzalloc(ioc->pend_os_device_add_sz,
8499 	    GFP_KERNEL);
8500 	if (!ioc->pend_os_device_add) {
8501 		r = -ENOMEM;
8502 		goto out_free_resources;
8503 	}
8504 
8505 	ioc->device_remove_in_progress_sz = ioc->pend_os_device_add_sz;
8506 	ioc->device_remove_in_progress =
8507 		kzalloc(ioc->device_remove_in_progress_sz, GFP_KERNEL);
8508 	if (!ioc->device_remove_in_progress) {
8509 		r = -ENOMEM;
8510 		goto out_free_resources;
8511 	}
8512 
8513 	ioc->fwfault_debug = mpt3sas_fwfault_debug;
8514 
8515 	/* base internal command bits */
8516 	mutex_init(&ioc->base_cmds.mutex);
8517 	ioc->base_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
8518 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
8519 
8520 	/* port_enable command bits */
8521 	ioc->port_enable_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
8522 	ioc->port_enable_cmds.status = MPT3_CMD_NOT_USED;
8523 
8524 	/* transport internal command bits */
8525 	ioc->transport_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
8526 	ioc->transport_cmds.status = MPT3_CMD_NOT_USED;
8527 	mutex_init(&ioc->transport_cmds.mutex);
8528 
8529 	/* scsih internal command bits */
8530 	ioc->scsih_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
8531 	ioc->scsih_cmds.status = MPT3_CMD_NOT_USED;
8532 	mutex_init(&ioc->scsih_cmds.mutex);
8533 
8534 	/* task management internal command bits */
8535 	ioc->tm_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
8536 	ioc->tm_cmds.status = MPT3_CMD_NOT_USED;
8537 	mutex_init(&ioc->tm_cmds.mutex);
8538 
8539 	/* config page internal command bits */
8540 	ioc->config_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
8541 	ioc->config_cmds.status = MPT3_CMD_NOT_USED;
8542 	mutex_init(&ioc->config_cmds.mutex);
8543 
8544 	/* ctl module internal command bits */
8545 	ioc->ctl_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
8546 	ioc->ctl_cmds.sense = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
8547 	ioc->ctl_cmds.status = MPT3_CMD_NOT_USED;
8548 	mutex_init(&ioc->ctl_cmds.mutex);
8549 
8550 	if (!ioc->base_cmds.reply || !ioc->port_enable_cmds.reply ||
8551 	    !ioc->transport_cmds.reply || !ioc->scsih_cmds.reply ||
8552 	    !ioc->tm_cmds.reply || !ioc->config_cmds.reply ||
8553 	    !ioc->ctl_cmds.reply || !ioc->ctl_cmds.sense) {
8554 		r = -ENOMEM;
8555 		goto out_free_resources;
8556 	}
8557 
8558 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
8559 		ioc->event_masks[i] = -1;
8560 
8561 	/* here we enable the events we care about */
8562 	_base_unmask_events(ioc, MPI2_EVENT_SAS_DISCOVERY);
8563 	_base_unmask_events(ioc, MPI2_EVENT_SAS_BROADCAST_PRIMITIVE);
8564 	_base_unmask_events(ioc, MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST);
8565 	_base_unmask_events(ioc, MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE);
8566 	_base_unmask_events(ioc, MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE);
8567 	_base_unmask_events(ioc, MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST);
8568 	_base_unmask_events(ioc, MPI2_EVENT_IR_VOLUME);
8569 	_base_unmask_events(ioc, MPI2_EVENT_IR_PHYSICAL_DISK);
8570 	_base_unmask_events(ioc, MPI2_EVENT_IR_OPERATION_STATUS);
8571 	_base_unmask_events(ioc, MPI2_EVENT_LOG_ENTRY_ADDED);
8572 	_base_unmask_events(ioc, MPI2_EVENT_TEMP_THRESHOLD);
8573 	_base_unmask_events(ioc, MPI2_EVENT_ACTIVE_CABLE_EXCEPTION);
8574 	_base_unmask_events(ioc, MPI2_EVENT_SAS_DEVICE_DISCOVERY_ERROR);
8575 	if (ioc->hba_mpi_version_belonged == MPI26_VERSION) {
8576 		if (ioc->is_gen35_ioc) {
8577 			_base_unmask_events(ioc,
8578 				MPI2_EVENT_PCIE_DEVICE_STATUS_CHANGE);
8579 			_base_unmask_events(ioc, MPI2_EVENT_PCIE_ENUMERATION);
8580 			_base_unmask_events(ioc,
8581 				MPI2_EVENT_PCIE_TOPOLOGY_CHANGE_LIST);
8582 		}
8583 	}
8584 	r = _base_make_ioc_operational(ioc);
8585 	if (r == -EAGAIN) {
8586 		r = _base_make_ioc_operational(ioc);
8587 		if (r)
8588 			goto out_free_resources;
8589 	}
8590 
8591 	/*
8592 	 * Copy current copy of IOCFacts in prev_fw_facts
8593 	 * and it will be used during online firmware upgrade.
8594 	 */
8595 	memcpy(&ioc->prev_fw_facts, &ioc->facts,
8596 	    sizeof(struct mpt3sas_facts));
8597 
8598 	ioc->non_operational_loop = 0;
8599 	ioc->ioc_coredump_loop = 0;
8600 	ioc->got_task_abort_from_ioctl = 0;
8601 	return 0;
8602 
8603  out_free_resources:
8604 
8605 	ioc->remove_host = 1;
8606 
8607 	mpt3sas_base_free_resources(ioc);
8608 	_base_release_memory_pools(ioc);
8609 	pci_set_drvdata(ioc->pdev, NULL);
8610 	kfree(ioc->cpu_msix_table);
8611 	if (ioc->is_warpdrive)
8612 		kfree(ioc->reply_post_host_index);
8613 	kfree(ioc->pd_handles);
8614 	kfree(ioc->blocking_handles);
8615 	kfree(ioc->device_remove_in_progress);
8616 	kfree(ioc->pend_os_device_add);
8617 	kfree(ioc->tm_cmds.reply);
8618 	kfree(ioc->transport_cmds.reply);
8619 	kfree(ioc->scsih_cmds.reply);
8620 	kfree(ioc->config_cmds.reply);
8621 	kfree(ioc->base_cmds.reply);
8622 	kfree(ioc->port_enable_cmds.reply);
8623 	kfree(ioc->ctl_cmds.reply);
8624 	kfree(ioc->ctl_cmds.sense);
8625 	kfree(ioc->pfacts);
8626 	ioc->ctl_cmds.reply = NULL;
8627 	ioc->base_cmds.reply = NULL;
8628 	ioc->tm_cmds.reply = NULL;
8629 	ioc->scsih_cmds.reply = NULL;
8630 	ioc->transport_cmds.reply = NULL;
8631 	ioc->config_cmds.reply = NULL;
8632 	ioc->pfacts = NULL;
8633 	return r;
8634 }
8635 
8636 
8637 /**
8638  * mpt3sas_base_detach - remove controller instance
8639  * @ioc: per adapter object
8640  */
8641 void
8642 mpt3sas_base_detach(struct MPT3SAS_ADAPTER *ioc)
8643 {
8644 	dexitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
8645 
8646 	mpt3sas_base_stop_watchdog(ioc);
8647 	mpt3sas_base_free_resources(ioc);
8648 	_base_release_memory_pools(ioc);
8649 	mpt3sas_free_enclosure_list(ioc);
8650 	pci_set_drvdata(ioc->pdev, NULL);
8651 	kfree(ioc->cpu_msix_table);
8652 	if (ioc->is_warpdrive)
8653 		kfree(ioc->reply_post_host_index);
8654 	kfree(ioc->pd_handles);
8655 	kfree(ioc->blocking_handles);
8656 	kfree(ioc->device_remove_in_progress);
8657 	kfree(ioc->pend_os_device_add);
8658 	kfree(ioc->pfacts);
8659 	kfree(ioc->ctl_cmds.reply);
8660 	kfree(ioc->ctl_cmds.sense);
8661 	kfree(ioc->base_cmds.reply);
8662 	kfree(ioc->port_enable_cmds.reply);
8663 	kfree(ioc->tm_cmds.reply);
8664 	kfree(ioc->transport_cmds.reply);
8665 	kfree(ioc->scsih_cmds.reply);
8666 	kfree(ioc->config_cmds.reply);
8667 }
8668 
8669 /**
8670  * _base_pre_reset_handler - pre reset handler
8671  * @ioc: per adapter object
8672  */
8673 static void _base_pre_reset_handler(struct MPT3SAS_ADAPTER *ioc)
8674 {
8675 	mpt3sas_scsih_pre_reset_handler(ioc);
8676 	mpt3sas_ctl_pre_reset_handler(ioc);
8677 	dtmprintk(ioc, ioc_info(ioc, "%s: MPT3_IOC_PRE_RESET\n", __func__));
8678 }
8679 
8680 /**
8681  * _base_clear_outstanding_mpt_commands - clears outstanding mpt commands
8682  * @ioc: per adapter object
8683  */
8684 static void
8685 _base_clear_outstanding_mpt_commands(struct MPT3SAS_ADAPTER *ioc)
8686 {
8687 	dtmprintk(ioc,
8688 	    ioc_info(ioc, "%s: clear outstanding mpt cmds\n", __func__));
8689 	if (ioc->transport_cmds.status & MPT3_CMD_PENDING) {
8690 		ioc->transport_cmds.status |= MPT3_CMD_RESET;
8691 		mpt3sas_base_free_smid(ioc, ioc->transport_cmds.smid);
8692 		complete(&ioc->transport_cmds.done);
8693 	}
8694 	if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
8695 		ioc->base_cmds.status |= MPT3_CMD_RESET;
8696 		mpt3sas_base_free_smid(ioc, ioc->base_cmds.smid);
8697 		complete(&ioc->base_cmds.done);
8698 	}
8699 	if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
8700 		ioc->port_enable_failed = 1;
8701 		ioc->port_enable_cmds.status |= MPT3_CMD_RESET;
8702 		mpt3sas_base_free_smid(ioc, ioc->port_enable_cmds.smid);
8703 		if (ioc->is_driver_loading) {
8704 			ioc->start_scan_failed =
8705 				MPI2_IOCSTATUS_INTERNAL_ERROR;
8706 			ioc->start_scan = 0;
8707 		} else {
8708 			complete(&ioc->port_enable_cmds.done);
8709 		}
8710 	}
8711 	if (ioc->config_cmds.status & MPT3_CMD_PENDING) {
8712 		ioc->config_cmds.status |= MPT3_CMD_RESET;
8713 		mpt3sas_base_free_smid(ioc, ioc->config_cmds.smid);
8714 		ioc->config_cmds.smid = USHRT_MAX;
8715 		complete(&ioc->config_cmds.done);
8716 	}
8717 }
8718 
8719 /**
8720  * _base_clear_outstanding_commands - clear all outstanding commands
8721  * @ioc: per adapter object
8722  */
8723 static void _base_clear_outstanding_commands(struct MPT3SAS_ADAPTER *ioc)
8724 {
8725 	mpt3sas_scsih_clear_outstanding_scsi_tm_commands(ioc);
8726 	mpt3sas_ctl_clear_outstanding_ioctls(ioc);
8727 	_base_clear_outstanding_mpt_commands(ioc);
8728 }
8729 
8730 /**
8731  * _base_reset_done_handler - reset done handler
8732  * @ioc: per adapter object
8733  */
8734 static void _base_reset_done_handler(struct MPT3SAS_ADAPTER *ioc)
8735 {
8736 	mpt3sas_scsih_reset_done_handler(ioc);
8737 	mpt3sas_ctl_reset_done_handler(ioc);
8738 	dtmprintk(ioc, ioc_info(ioc, "%s: MPT3_IOC_DONE_RESET\n", __func__));
8739 }
8740 
8741 /**
8742  * mpt3sas_wait_for_commands_to_complete - reset controller
8743  * @ioc: Pointer to MPT_ADAPTER structure
8744  *
8745  * This function is waiting 10s for all pending commands to complete
8746  * prior to putting controller in reset.
8747  */
8748 void
8749 mpt3sas_wait_for_commands_to_complete(struct MPT3SAS_ADAPTER *ioc)
8750 {
8751 	u32 ioc_state;
8752 
8753 	ioc->pending_io_count = 0;
8754 
8755 	ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
8756 	if ((ioc_state & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_OPERATIONAL)
8757 		return;
8758 
8759 	/* pending command count */
8760 	ioc->pending_io_count = scsi_host_busy(ioc->shost);
8761 
8762 	if (!ioc->pending_io_count)
8763 		return;
8764 
8765 	/* wait for pending commands to complete */
8766 	wait_event_timeout(ioc->reset_wq, ioc->pending_io_count == 0, 10 * HZ);
8767 }
8768 
8769 /**
8770  * _base_check_ioc_facts_changes - Look for increase/decrease of IOCFacts
8771  *     attributes during online firmware upgrade and update the corresponding
8772  *     IOC variables accordingly.
8773  *
8774  * @ioc: Pointer to MPT_ADAPTER structure
8775  */
8776 static int
8777 _base_check_ioc_facts_changes(struct MPT3SAS_ADAPTER *ioc)
8778 {
8779 	u16 pd_handles_sz;
8780 	void *pd_handles = NULL, *blocking_handles = NULL;
8781 	void *pend_os_device_add = NULL, *device_remove_in_progress = NULL;
8782 	struct mpt3sas_facts *old_facts = &ioc->prev_fw_facts;
8783 
8784 	if (ioc->facts.MaxDevHandle > old_facts->MaxDevHandle) {
8785 		pd_handles_sz = (ioc->facts.MaxDevHandle / 8);
8786 		if (ioc->facts.MaxDevHandle % 8)
8787 			pd_handles_sz++;
8788 
8789 		pd_handles = krealloc(ioc->pd_handles, pd_handles_sz,
8790 		    GFP_KERNEL);
8791 		if (!pd_handles) {
8792 			ioc_info(ioc,
8793 			    "Unable to allocate the memory for pd_handles of sz: %d\n",
8794 			    pd_handles_sz);
8795 			return -ENOMEM;
8796 		}
8797 		memset(pd_handles + ioc->pd_handles_sz, 0,
8798 		    (pd_handles_sz - ioc->pd_handles_sz));
8799 		ioc->pd_handles = pd_handles;
8800 
8801 		blocking_handles = krealloc(ioc->blocking_handles,
8802 		    pd_handles_sz, GFP_KERNEL);
8803 		if (!blocking_handles) {
8804 			ioc_info(ioc,
8805 			    "Unable to allocate the memory for "
8806 			    "blocking_handles of sz: %d\n",
8807 			    pd_handles_sz);
8808 			return -ENOMEM;
8809 		}
8810 		memset(blocking_handles + ioc->pd_handles_sz, 0,
8811 		    (pd_handles_sz - ioc->pd_handles_sz));
8812 		ioc->blocking_handles = blocking_handles;
8813 		ioc->pd_handles_sz = pd_handles_sz;
8814 
8815 		pend_os_device_add = krealloc(ioc->pend_os_device_add,
8816 		    pd_handles_sz, GFP_KERNEL);
8817 		if (!pend_os_device_add) {
8818 			ioc_info(ioc,
8819 			    "Unable to allocate the memory for pend_os_device_add of sz: %d\n",
8820 			    pd_handles_sz);
8821 			return -ENOMEM;
8822 		}
8823 		memset(pend_os_device_add + ioc->pend_os_device_add_sz, 0,
8824 		    (pd_handles_sz - ioc->pend_os_device_add_sz));
8825 		ioc->pend_os_device_add = pend_os_device_add;
8826 		ioc->pend_os_device_add_sz = pd_handles_sz;
8827 
8828 		device_remove_in_progress = krealloc(
8829 		    ioc->device_remove_in_progress, pd_handles_sz, GFP_KERNEL);
8830 		if (!device_remove_in_progress) {
8831 			ioc_info(ioc,
8832 			    "Unable to allocate the memory for "
8833 			    "device_remove_in_progress of sz: %d\n "
8834 			    , pd_handles_sz);
8835 			return -ENOMEM;
8836 		}
8837 		memset(device_remove_in_progress +
8838 		    ioc->device_remove_in_progress_sz, 0,
8839 		    (pd_handles_sz - ioc->device_remove_in_progress_sz));
8840 		ioc->device_remove_in_progress = device_remove_in_progress;
8841 		ioc->device_remove_in_progress_sz = pd_handles_sz;
8842 	}
8843 
8844 	memcpy(&ioc->prev_fw_facts, &ioc->facts, sizeof(struct mpt3sas_facts));
8845 	return 0;
8846 }
8847 
8848 /**
8849  * mpt3sas_base_hard_reset_handler - reset controller
8850  * @ioc: Pointer to MPT_ADAPTER structure
8851  * @type: FORCE_BIG_HAMMER or SOFT_RESET
8852  *
8853  * Return: 0 for success, non-zero for failure.
8854  */
8855 int
8856 mpt3sas_base_hard_reset_handler(struct MPT3SAS_ADAPTER *ioc,
8857 	enum reset_type type)
8858 {
8859 	int r;
8860 	unsigned long flags;
8861 	u32 ioc_state;
8862 	u8 is_fault = 0, is_trigger = 0;
8863 
8864 	dtmprintk(ioc, ioc_info(ioc, "%s: enter\n", __func__));
8865 
8866 	if (ioc->pci_error_recovery) {
8867 		ioc_err(ioc, "%s: pci error recovery reset\n", __func__);
8868 		r = 0;
8869 		goto out_unlocked;
8870 	}
8871 
8872 	if (mpt3sas_fwfault_debug)
8873 		mpt3sas_halt_firmware(ioc);
8874 
8875 	/* wait for an active reset in progress to complete */
8876 	mutex_lock(&ioc->reset_in_progress_mutex);
8877 
8878 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
8879 	ioc->shost_recovery = 1;
8880 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
8881 
8882 	if ((ioc->diag_buffer_status[MPI2_DIAG_BUF_TYPE_TRACE] &
8883 	    MPT3_DIAG_BUFFER_IS_REGISTERED) &&
8884 	    (!(ioc->diag_buffer_status[MPI2_DIAG_BUF_TYPE_TRACE] &
8885 	    MPT3_DIAG_BUFFER_IS_RELEASED))) {
8886 		is_trigger = 1;
8887 		ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
8888 		if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT ||
8889 		    (ioc_state & MPI2_IOC_STATE_MASK) ==
8890 		    MPI2_IOC_STATE_COREDUMP) {
8891 			is_fault = 1;
8892 			ioc->htb_rel.trigger_info_dwords[1] =
8893 			    (ioc_state & MPI2_DOORBELL_DATA_MASK);
8894 		}
8895 	}
8896 	_base_pre_reset_handler(ioc);
8897 	mpt3sas_wait_for_commands_to_complete(ioc);
8898 	mpt3sas_base_mask_interrupts(ioc);
8899 	mpt3sas_base_pause_mq_polling(ioc);
8900 	r = mpt3sas_base_make_ioc_ready(ioc, type);
8901 	if (r)
8902 		goto out;
8903 	_base_clear_outstanding_commands(ioc);
8904 
8905 	/* If this hard reset is called while port enable is active, then
8906 	 * there is no reason to call make_ioc_operational
8907 	 */
8908 	if (ioc->is_driver_loading && ioc->port_enable_failed) {
8909 		ioc->remove_host = 1;
8910 		r = -EFAULT;
8911 		goto out;
8912 	}
8913 	r = _base_get_ioc_facts(ioc);
8914 	if (r)
8915 		goto out;
8916 
8917 	r = _base_check_ioc_facts_changes(ioc);
8918 	if (r) {
8919 		ioc_info(ioc,
8920 		    "Some of the parameters got changed in this new firmware"
8921 		    " image and it requires system reboot\n");
8922 		goto out;
8923 	}
8924 	if (ioc->rdpq_array_enable && !ioc->rdpq_array_capable)
8925 		panic("%s: Issue occurred with flashing controller firmware."
8926 		      "Please reboot the system and ensure that the correct"
8927 		      " firmware version is running\n", ioc->name);
8928 
8929 	r = _base_make_ioc_operational(ioc);
8930 	if (!r)
8931 		_base_reset_done_handler(ioc);
8932 
8933  out:
8934 	ioc_info(ioc, "%s: %s\n", __func__, r == 0 ? "SUCCESS" : "FAILED");
8935 
8936 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
8937 	ioc->shost_recovery = 0;
8938 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
8939 	ioc->ioc_reset_count++;
8940 	mutex_unlock(&ioc->reset_in_progress_mutex);
8941 	mpt3sas_base_resume_mq_polling(ioc);
8942 
8943  out_unlocked:
8944 	if ((r == 0) && is_trigger) {
8945 		if (is_fault)
8946 			mpt3sas_trigger_master(ioc, MASTER_TRIGGER_FW_FAULT);
8947 		else
8948 			mpt3sas_trigger_master(ioc,
8949 			    MASTER_TRIGGER_ADAPTER_RESET);
8950 	}
8951 	dtmprintk(ioc, ioc_info(ioc, "%s: exit\n", __func__));
8952 	return r;
8953 }
8954