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