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