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 
2264 	/* If Datalenth is <= 16K and number of SGE’s entries are <= 2
2265 	 * we built IEEE SGL
2266 	 */
2267 	if ((data_length <= NVME_PRP_PAGE_SIZE*4) && (sge_count <= 2))
2268 		build_prp = false;
2269 
2270 	return build_prp;
2271 }
2272 
2273 /**
2274  * _base_check_pcie_native_sgl - This function is called for PCIe end devices to
2275  * determine if the driver needs to build a native SGL.  If so, that native
2276  * SGL is built in the special contiguous buffers allocated especially for
2277  * PCIe SGL creation.  If the driver will not build a native SGL, return
2278  * TRUE and a normal IEEE SGL will be built.  Currently this routine
2279  * supports NVMe.
2280  * @ioc: per adapter object
2281  * @mpi_request: mf request pointer
2282  * @smid: system request message index
2283  * @scmd: scsi command
2284  * @pcie_device: points to the PCIe device's info
2285  *
2286  * Return: 0 if native SGL was built, 1 if no SGL was built
2287  */
2288 static int
2289 _base_check_pcie_native_sgl(struct MPT3SAS_ADAPTER *ioc,
2290 	Mpi25SCSIIORequest_t *mpi_request, u16 smid, struct scsi_cmnd *scmd,
2291 	struct _pcie_device *pcie_device)
2292 {
2293 	int sges_left;
2294 
2295 	/* Get the SG list pointer and info. */
2296 	sges_left = scsi_dma_map(scmd);
2297 	if (sges_left < 0) {
2298 		sdev_printk(KERN_ERR, scmd->device,
2299 			"scsi_dma_map failed: request for %d bytes!\n",
2300 			scsi_bufflen(scmd));
2301 		return 1;
2302 	}
2303 
2304 	/* Check if we need to build a native SG list. */
2305 	if (base_is_prp_possible(ioc, pcie_device,
2306 				scmd, sges_left) == 0) {
2307 		/* We built a native SG list, just return. */
2308 		goto out;
2309 	}
2310 
2311 	/*
2312 	 * Build native NVMe PRP.
2313 	 */
2314 	base_make_prp_nvme(ioc, scmd, mpi_request,
2315 			smid, sges_left);
2316 
2317 	return 0;
2318 out:
2319 	scsi_dma_unmap(scmd);
2320 	return 1;
2321 }
2322 
2323 /**
2324  * _base_add_sg_single_ieee - add sg element for IEEE format
2325  * @paddr: virtual address for SGE
2326  * @flags: SGE flags
2327  * @chain_offset: number of 128 byte elements from start of segment
2328  * @length: data transfer length
2329  * @dma_addr: Physical address
2330  */
2331 static void
2332 _base_add_sg_single_ieee(void *paddr, u8 flags, u8 chain_offset, u32 length,
2333 	dma_addr_t dma_addr)
2334 {
2335 	Mpi25IeeeSgeChain64_t *sgel = paddr;
2336 
2337 	sgel->Flags = flags;
2338 	sgel->NextChainOffset = chain_offset;
2339 	sgel->Length = cpu_to_le32(length);
2340 	sgel->Address = cpu_to_le64(dma_addr);
2341 }
2342 
2343 /**
2344  * _base_build_zero_len_sge_ieee - build zero length sg entry for IEEE format
2345  * @ioc: per adapter object
2346  * @paddr: virtual address for SGE
2347  *
2348  * Create a zero length scatter gather entry to insure the IOCs hardware has
2349  * something to use if the target device goes brain dead and tries
2350  * to send data even when none is asked for.
2351  */
2352 static void
2353 _base_build_zero_len_sge_ieee(struct MPT3SAS_ADAPTER *ioc, void *paddr)
2354 {
2355 	u8 sgl_flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2356 		MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
2357 		MPI25_IEEE_SGE_FLAGS_END_OF_LIST);
2358 
2359 	_base_add_sg_single_ieee(paddr, sgl_flags, 0, 0, -1);
2360 }
2361 
2362 /**
2363  * _base_build_sg_scmd - main sg creation routine
2364  *		pcie_device is unused here!
2365  * @ioc: per adapter object
2366  * @scmd: scsi command
2367  * @smid: system request message index
2368  * @unused: unused pcie_device pointer
2369  * Context: none.
2370  *
2371  * The main routine that builds scatter gather table from a given
2372  * scsi request sent via the .queuecommand main handler.
2373  *
2374  * Return: 0 success, anything else error
2375  */
2376 static int
2377 _base_build_sg_scmd(struct MPT3SAS_ADAPTER *ioc,
2378 	struct scsi_cmnd *scmd, u16 smid, struct _pcie_device *unused)
2379 {
2380 	Mpi2SCSIIORequest_t *mpi_request;
2381 	dma_addr_t chain_dma;
2382 	struct scatterlist *sg_scmd;
2383 	void *sg_local, *chain;
2384 	u32 chain_offset;
2385 	u32 chain_length;
2386 	u32 chain_flags;
2387 	int sges_left;
2388 	u32 sges_in_segment;
2389 	u32 sgl_flags;
2390 	u32 sgl_flags_last_element;
2391 	u32 sgl_flags_end_buffer;
2392 	struct chain_tracker *chain_req;
2393 
2394 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
2395 
2396 	/* init scatter gather flags */
2397 	sgl_flags = MPI2_SGE_FLAGS_SIMPLE_ELEMENT;
2398 	if (scmd->sc_data_direction == DMA_TO_DEVICE)
2399 		sgl_flags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
2400 	sgl_flags_last_element = (sgl_flags | MPI2_SGE_FLAGS_LAST_ELEMENT)
2401 	    << MPI2_SGE_FLAGS_SHIFT;
2402 	sgl_flags_end_buffer = (sgl_flags | MPI2_SGE_FLAGS_LAST_ELEMENT |
2403 	    MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_END_OF_LIST)
2404 	    << MPI2_SGE_FLAGS_SHIFT;
2405 	sgl_flags = sgl_flags << MPI2_SGE_FLAGS_SHIFT;
2406 
2407 	sg_scmd = scsi_sglist(scmd);
2408 	sges_left = scsi_dma_map(scmd);
2409 	if (sges_left < 0) {
2410 		sdev_printk(KERN_ERR, scmd->device,
2411 		 "scsi_dma_map failed: request for %d bytes!\n",
2412 		 scsi_bufflen(scmd));
2413 		return -ENOMEM;
2414 	}
2415 
2416 	sg_local = &mpi_request->SGL;
2417 	sges_in_segment = ioc->max_sges_in_main_message;
2418 	if (sges_left <= sges_in_segment)
2419 		goto fill_in_last_segment;
2420 
2421 	mpi_request->ChainOffset = (offsetof(Mpi2SCSIIORequest_t, SGL) +
2422 	    (sges_in_segment * ioc->sge_size))/4;
2423 
2424 	/* fill in main message segment when there is a chain following */
2425 	while (sges_in_segment) {
2426 		if (sges_in_segment == 1)
2427 			ioc->base_add_sg_single(sg_local,
2428 			    sgl_flags_last_element | sg_dma_len(sg_scmd),
2429 			    sg_dma_address(sg_scmd));
2430 		else
2431 			ioc->base_add_sg_single(sg_local, sgl_flags |
2432 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2433 		sg_scmd = sg_next(sg_scmd);
2434 		sg_local += ioc->sge_size;
2435 		sges_left--;
2436 		sges_in_segment--;
2437 	}
2438 
2439 	/* initializing the chain flags and pointers */
2440 	chain_flags = MPI2_SGE_FLAGS_CHAIN_ELEMENT << MPI2_SGE_FLAGS_SHIFT;
2441 	chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2442 	if (!chain_req)
2443 		return -1;
2444 	chain = chain_req->chain_buffer;
2445 	chain_dma = chain_req->chain_buffer_dma;
2446 	do {
2447 		sges_in_segment = (sges_left <=
2448 		    ioc->max_sges_in_chain_message) ? sges_left :
2449 		    ioc->max_sges_in_chain_message;
2450 		chain_offset = (sges_left == sges_in_segment) ?
2451 		    0 : (sges_in_segment * ioc->sge_size)/4;
2452 		chain_length = sges_in_segment * ioc->sge_size;
2453 		if (chain_offset) {
2454 			chain_offset = chain_offset <<
2455 			    MPI2_SGE_CHAIN_OFFSET_SHIFT;
2456 			chain_length += ioc->sge_size;
2457 		}
2458 		ioc->base_add_sg_single(sg_local, chain_flags | chain_offset |
2459 		    chain_length, chain_dma);
2460 		sg_local = chain;
2461 		if (!chain_offset)
2462 			goto fill_in_last_segment;
2463 
2464 		/* fill in chain segments */
2465 		while (sges_in_segment) {
2466 			if (sges_in_segment == 1)
2467 				ioc->base_add_sg_single(sg_local,
2468 				    sgl_flags_last_element |
2469 				    sg_dma_len(sg_scmd),
2470 				    sg_dma_address(sg_scmd));
2471 			else
2472 				ioc->base_add_sg_single(sg_local, sgl_flags |
2473 				    sg_dma_len(sg_scmd),
2474 				    sg_dma_address(sg_scmd));
2475 			sg_scmd = sg_next(sg_scmd);
2476 			sg_local += ioc->sge_size;
2477 			sges_left--;
2478 			sges_in_segment--;
2479 		}
2480 
2481 		chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2482 		if (!chain_req)
2483 			return -1;
2484 		chain = chain_req->chain_buffer;
2485 		chain_dma = chain_req->chain_buffer_dma;
2486 	} while (1);
2487 
2488 
2489  fill_in_last_segment:
2490 
2491 	/* fill the last segment */
2492 	while (sges_left) {
2493 		if (sges_left == 1)
2494 			ioc->base_add_sg_single(sg_local, sgl_flags_end_buffer |
2495 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2496 		else
2497 			ioc->base_add_sg_single(sg_local, sgl_flags |
2498 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2499 		sg_scmd = sg_next(sg_scmd);
2500 		sg_local += ioc->sge_size;
2501 		sges_left--;
2502 	}
2503 
2504 	return 0;
2505 }
2506 
2507 /**
2508  * _base_build_sg_scmd_ieee - main sg creation routine for IEEE format
2509  * @ioc: per adapter object
2510  * @scmd: scsi command
2511  * @smid: system request message index
2512  * @pcie_device: Pointer to pcie_device. If set, the pcie native sgl will be
2513  * constructed on need.
2514  * Context: none.
2515  *
2516  * The main routine that builds scatter gather table from a given
2517  * scsi request sent via the .queuecommand main handler.
2518  *
2519  * Return: 0 success, anything else error
2520  */
2521 static int
2522 _base_build_sg_scmd_ieee(struct MPT3SAS_ADAPTER *ioc,
2523 	struct scsi_cmnd *scmd, u16 smid, struct _pcie_device *pcie_device)
2524 {
2525 	Mpi25SCSIIORequest_t *mpi_request;
2526 	dma_addr_t chain_dma;
2527 	struct scatterlist *sg_scmd;
2528 	void *sg_local, *chain;
2529 	u32 chain_offset;
2530 	u32 chain_length;
2531 	int sges_left;
2532 	u32 sges_in_segment;
2533 	u8 simple_sgl_flags;
2534 	u8 simple_sgl_flags_last;
2535 	u8 chain_sgl_flags;
2536 	struct chain_tracker *chain_req;
2537 
2538 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
2539 
2540 	/* init scatter gather flags */
2541 	simple_sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2542 	    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2543 	simple_sgl_flags_last = simple_sgl_flags |
2544 	    MPI25_IEEE_SGE_FLAGS_END_OF_LIST;
2545 	chain_sgl_flags = MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
2546 	    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2547 
2548 	/* Check if we need to build a native SG list. */
2549 	if ((pcie_device) && (_base_check_pcie_native_sgl(ioc, mpi_request,
2550 			smid, scmd, pcie_device) == 0)) {
2551 		/* We built a native SG list, just return. */
2552 		return 0;
2553 	}
2554 
2555 	sg_scmd = scsi_sglist(scmd);
2556 	sges_left = scsi_dma_map(scmd);
2557 	if (sges_left < 0) {
2558 		sdev_printk(KERN_ERR, scmd->device,
2559 			"scsi_dma_map failed: request for %d bytes!\n",
2560 			scsi_bufflen(scmd));
2561 		return -ENOMEM;
2562 	}
2563 
2564 	sg_local = &mpi_request->SGL;
2565 	sges_in_segment = (ioc->request_sz -
2566 		   offsetof(Mpi25SCSIIORequest_t, SGL))/ioc->sge_size_ieee;
2567 	if (sges_left <= sges_in_segment)
2568 		goto fill_in_last_segment;
2569 
2570 	mpi_request->ChainOffset = (sges_in_segment - 1 /* chain element */) +
2571 	    (offsetof(Mpi25SCSIIORequest_t, SGL)/ioc->sge_size_ieee);
2572 
2573 	/* fill in main message segment when there is a chain following */
2574 	while (sges_in_segment > 1) {
2575 		_base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
2576 		    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2577 		sg_scmd = sg_next(sg_scmd);
2578 		sg_local += ioc->sge_size_ieee;
2579 		sges_left--;
2580 		sges_in_segment--;
2581 	}
2582 
2583 	/* initializing the pointers */
2584 	chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2585 	if (!chain_req)
2586 		return -1;
2587 	chain = chain_req->chain_buffer;
2588 	chain_dma = chain_req->chain_buffer_dma;
2589 	do {
2590 		sges_in_segment = (sges_left <=
2591 		    ioc->max_sges_in_chain_message) ? sges_left :
2592 		    ioc->max_sges_in_chain_message;
2593 		chain_offset = (sges_left == sges_in_segment) ?
2594 		    0 : sges_in_segment;
2595 		chain_length = sges_in_segment * ioc->sge_size_ieee;
2596 		if (chain_offset)
2597 			chain_length += ioc->sge_size_ieee;
2598 		_base_add_sg_single_ieee(sg_local, chain_sgl_flags,
2599 		    chain_offset, chain_length, chain_dma);
2600 
2601 		sg_local = chain;
2602 		if (!chain_offset)
2603 			goto fill_in_last_segment;
2604 
2605 		/* fill in chain segments */
2606 		while (sges_in_segment) {
2607 			_base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
2608 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2609 			sg_scmd = sg_next(sg_scmd);
2610 			sg_local += ioc->sge_size_ieee;
2611 			sges_left--;
2612 			sges_in_segment--;
2613 		}
2614 
2615 		chain_req = _base_get_chain_buffer_tracker(ioc, scmd);
2616 		if (!chain_req)
2617 			return -1;
2618 		chain = chain_req->chain_buffer;
2619 		chain_dma = chain_req->chain_buffer_dma;
2620 	} while (1);
2621 
2622 
2623  fill_in_last_segment:
2624 
2625 	/* fill the last segment */
2626 	while (sges_left > 0) {
2627 		if (sges_left == 1)
2628 			_base_add_sg_single_ieee(sg_local,
2629 			    simple_sgl_flags_last, 0, sg_dma_len(sg_scmd),
2630 			    sg_dma_address(sg_scmd));
2631 		else
2632 			_base_add_sg_single_ieee(sg_local, simple_sgl_flags, 0,
2633 			    sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2634 		sg_scmd = sg_next(sg_scmd);
2635 		sg_local += ioc->sge_size_ieee;
2636 		sges_left--;
2637 	}
2638 
2639 	return 0;
2640 }
2641 
2642 /**
2643  * _base_build_sg_ieee - build generic sg for IEEE format
2644  * @ioc: per adapter object
2645  * @psge: virtual address for SGE
2646  * @data_out_dma: physical address for WRITES
2647  * @data_out_sz: data xfer size for WRITES
2648  * @data_in_dma: physical address for READS
2649  * @data_in_sz: data xfer size for READS
2650  */
2651 static void
2652 _base_build_sg_ieee(struct MPT3SAS_ADAPTER *ioc, void *psge,
2653 	dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
2654 	size_t data_in_sz)
2655 {
2656 	u8 sgl_flags;
2657 
2658 	if (!data_out_sz && !data_in_sz) {
2659 		_base_build_zero_len_sge_ieee(ioc, psge);
2660 		return;
2661 	}
2662 
2663 	if (data_out_sz && data_in_sz) {
2664 		/* WRITE sgel first */
2665 		sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2666 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2667 		_base_add_sg_single_ieee(psge, sgl_flags, 0, data_out_sz,
2668 		    data_out_dma);
2669 
2670 		/* incr sgel */
2671 		psge += ioc->sge_size_ieee;
2672 
2673 		/* READ sgel last */
2674 		sgl_flags |= MPI25_IEEE_SGE_FLAGS_END_OF_LIST;
2675 		_base_add_sg_single_ieee(psge, sgl_flags, 0, data_in_sz,
2676 		    data_in_dma);
2677 	} else if (data_out_sz) /* WRITE */ {
2678 		sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2679 		    MPI25_IEEE_SGE_FLAGS_END_OF_LIST |
2680 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2681 		_base_add_sg_single_ieee(psge, sgl_flags, 0, data_out_sz,
2682 		    data_out_dma);
2683 	} else if (data_in_sz) /* READ */ {
2684 		sgl_flags = MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
2685 		    MPI25_IEEE_SGE_FLAGS_END_OF_LIST |
2686 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR;
2687 		_base_add_sg_single_ieee(psge, sgl_flags, 0, data_in_sz,
2688 		    data_in_dma);
2689 	}
2690 }
2691 
2692 #define convert_to_kb(x) ((x) << (PAGE_SHIFT - 10))
2693 
2694 /**
2695  * _base_config_dma_addressing - set dma addressing
2696  * @ioc: per adapter object
2697  * @pdev: PCI device struct
2698  *
2699  * Return: 0 for success, non-zero for failure.
2700  */
2701 static int
2702 _base_config_dma_addressing(struct MPT3SAS_ADAPTER *ioc, struct pci_dev *pdev)
2703 {
2704 	u64 required_mask, coherent_mask;
2705 	struct sysinfo s;
2706 
2707 	if (ioc->is_mcpu_endpoint)
2708 		goto try_32bit;
2709 
2710 	required_mask = dma_get_required_mask(&pdev->dev);
2711 	if (sizeof(dma_addr_t) == 4 || required_mask == 32)
2712 		goto try_32bit;
2713 
2714 	if (ioc->dma_mask)
2715 		coherent_mask = DMA_BIT_MASK(64);
2716 	else
2717 		coherent_mask = DMA_BIT_MASK(32);
2718 
2719 	if (dma_set_mask(&pdev->dev, DMA_BIT_MASK(64)) ||
2720 	    dma_set_coherent_mask(&pdev->dev, coherent_mask))
2721 		goto try_32bit;
2722 
2723 	ioc->base_add_sg_single = &_base_add_sg_single_64;
2724 	ioc->sge_size = sizeof(Mpi2SGESimple64_t);
2725 	ioc->dma_mask = 64;
2726 	goto out;
2727 
2728  try_32bit:
2729 	if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
2730 		return -ENODEV;
2731 
2732 	ioc->base_add_sg_single = &_base_add_sg_single_32;
2733 	ioc->sge_size = sizeof(Mpi2SGESimple32_t);
2734 	ioc->dma_mask = 32;
2735  out:
2736 	si_meminfo(&s);
2737 	ioc_info(ioc, "%d BIT PCI BUS DMA ADDRESSING SUPPORTED, total mem (%ld kB)\n",
2738 		 ioc->dma_mask, convert_to_kb(s.totalram));
2739 
2740 	return 0;
2741 }
2742 
2743 static int
2744 _base_change_consistent_dma_mask(struct MPT3SAS_ADAPTER *ioc,
2745 				      struct pci_dev *pdev)
2746 {
2747 	if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64))) {
2748 		if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)))
2749 			return -ENODEV;
2750 	}
2751 	return 0;
2752 }
2753 
2754 /**
2755  * _base_check_enable_msix - checks MSIX capabable.
2756  * @ioc: per adapter object
2757  *
2758  * Check to see if card is capable of MSIX, and set number
2759  * of available msix vectors
2760  */
2761 static int
2762 _base_check_enable_msix(struct MPT3SAS_ADAPTER *ioc)
2763 {
2764 	int base;
2765 	u16 message_control;
2766 
2767 	/* Check whether controller SAS2008 B0 controller,
2768 	 * if it is SAS2008 B0 controller use IO-APIC instead of MSIX
2769 	 */
2770 	if (ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2008 &&
2771 	    ioc->pdev->revision == SAS2_PCI_DEVICE_B0_REVISION) {
2772 		return -EINVAL;
2773 	}
2774 
2775 	base = pci_find_capability(ioc->pdev, PCI_CAP_ID_MSIX);
2776 	if (!base) {
2777 		dfailprintk(ioc, ioc_info(ioc, "msix not supported\n"));
2778 		return -EINVAL;
2779 	}
2780 
2781 	/* get msix vector count */
2782 	/* NUMA_IO not supported for older controllers */
2783 	if (ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2004 ||
2784 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2008 ||
2785 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_1 ||
2786 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_2 ||
2787 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2108_3 ||
2788 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2116_1 ||
2789 	    ioc->pdev->device == MPI2_MFGPAGE_DEVID_SAS2116_2)
2790 		ioc->msix_vector_count = 1;
2791 	else {
2792 		pci_read_config_word(ioc->pdev, base + 2, &message_control);
2793 		ioc->msix_vector_count = (message_control & 0x3FF) + 1;
2794 	}
2795 	dinitprintk(ioc, ioc_info(ioc, "msix is supported, vector_count(%d)\n",
2796 				  ioc->msix_vector_count));
2797 	return 0;
2798 }
2799 
2800 /**
2801  * _base_free_irq - free irq
2802  * @ioc: per adapter object
2803  *
2804  * Freeing respective reply_queue from the list.
2805  */
2806 static void
2807 _base_free_irq(struct MPT3SAS_ADAPTER *ioc)
2808 {
2809 	struct adapter_reply_queue *reply_q, *next;
2810 
2811 	if (list_empty(&ioc->reply_queue_list))
2812 		return;
2813 
2814 	list_for_each_entry_safe(reply_q, next, &ioc->reply_queue_list, list) {
2815 		list_del(&reply_q->list);
2816 		if (ioc->smp_affinity_enable)
2817 			irq_set_affinity_hint(pci_irq_vector(ioc->pdev,
2818 			    reply_q->msix_index), NULL);
2819 		free_irq(pci_irq_vector(ioc->pdev, reply_q->msix_index),
2820 			 reply_q);
2821 		kfree(reply_q);
2822 	}
2823 }
2824 
2825 /**
2826  * _base_request_irq - request irq
2827  * @ioc: per adapter object
2828  * @index: msix index into vector table
2829  *
2830  * Inserting respective reply_queue into the list.
2831  */
2832 static int
2833 _base_request_irq(struct MPT3SAS_ADAPTER *ioc, u8 index)
2834 {
2835 	struct pci_dev *pdev = ioc->pdev;
2836 	struct adapter_reply_queue *reply_q;
2837 	int r;
2838 
2839 	reply_q =  kzalloc(sizeof(struct adapter_reply_queue), GFP_KERNEL);
2840 	if (!reply_q) {
2841 		ioc_err(ioc, "unable to allocate memory %zu!\n",
2842 			sizeof(struct adapter_reply_queue));
2843 		return -ENOMEM;
2844 	}
2845 	reply_q->ioc = ioc;
2846 	reply_q->msix_index = index;
2847 
2848 	atomic_set(&reply_q->busy, 0);
2849 	if (ioc->msix_enable)
2850 		snprintf(reply_q->name, MPT_NAME_LENGTH, "%s%d-msix%d",
2851 		    ioc->driver_name, ioc->id, index);
2852 	else
2853 		snprintf(reply_q->name, MPT_NAME_LENGTH, "%s%d",
2854 		    ioc->driver_name, ioc->id);
2855 	r = request_irq(pci_irq_vector(pdev, index), _base_interrupt,
2856 			IRQF_SHARED, reply_q->name, reply_q);
2857 	if (r) {
2858 		pr_err("%s: unable to allocate interrupt %d!\n",
2859 		       reply_q->name, pci_irq_vector(pdev, index));
2860 		kfree(reply_q);
2861 		return -EBUSY;
2862 	}
2863 
2864 	INIT_LIST_HEAD(&reply_q->list);
2865 	list_add_tail(&reply_q->list, &ioc->reply_queue_list);
2866 	return 0;
2867 }
2868 
2869 /**
2870  * _base_assign_reply_queues - assigning msix index for each cpu
2871  * @ioc: per adapter object
2872  *
2873  * The enduser would need to set the affinity via /proc/irq/#/smp_affinity
2874  *
2875  * It would nice if we could call irq_set_affinity, however it is not
2876  * an exported symbol
2877  */
2878 static void
2879 _base_assign_reply_queues(struct MPT3SAS_ADAPTER *ioc)
2880 {
2881 	unsigned int cpu, nr_cpus, nr_msix, index = 0;
2882 	struct adapter_reply_queue *reply_q;
2883 	int local_numa_node;
2884 
2885 	if (!_base_is_controller_msix_enabled(ioc))
2886 		return;
2887 
2888 	if (ioc->msix_load_balance)
2889 		return;
2890 
2891 	memset(ioc->cpu_msix_table, 0, ioc->cpu_msix_table_sz);
2892 
2893 	nr_cpus = num_online_cpus();
2894 	nr_msix = ioc->reply_queue_count = min(ioc->reply_queue_count,
2895 					       ioc->facts.MaxMSIxVectors);
2896 	if (!nr_msix)
2897 		return;
2898 
2899 	if (ioc->smp_affinity_enable) {
2900 
2901 		/*
2902 		 * set irq affinity to local numa node for those irqs
2903 		 * corresponding to high iops queues.
2904 		 */
2905 		if (ioc->high_iops_queues) {
2906 			local_numa_node = dev_to_node(&ioc->pdev->dev);
2907 			for (index = 0; index < ioc->high_iops_queues;
2908 			    index++) {
2909 				irq_set_affinity_hint(pci_irq_vector(ioc->pdev,
2910 				    index), cpumask_of_node(local_numa_node));
2911 			}
2912 		}
2913 
2914 		list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
2915 			const cpumask_t *mask;
2916 
2917 			if (reply_q->msix_index < ioc->high_iops_queues)
2918 				continue;
2919 
2920 			mask = pci_irq_get_affinity(ioc->pdev,
2921 			    reply_q->msix_index);
2922 			if (!mask) {
2923 				ioc_warn(ioc, "no affinity for msi %x\n",
2924 					 reply_q->msix_index);
2925 				goto fall_back;
2926 			}
2927 
2928 			for_each_cpu_and(cpu, mask, cpu_online_mask) {
2929 				if (cpu >= ioc->cpu_msix_table_sz)
2930 					break;
2931 				ioc->cpu_msix_table[cpu] = reply_q->msix_index;
2932 			}
2933 		}
2934 		return;
2935 	}
2936 
2937 fall_back:
2938 	cpu = cpumask_first(cpu_online_mask);
2939 	nr_msix -= ioc->high_iops_queues;
2940 	index = 0;
2941 
2942 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
2943 		unsigned int i, group = nr_cpus / nr_msix;
2944 
2945 		if (reply_q->msix_index < ioc->high_iops_queues)
2946 			continue;
2947 
2948 		if (cpu >= nr_cpus)
2949 			break;
2950 
2951 		if (index < nr_cpus % nr_msix)
2952 			group++;
2953 
2954 		for (i = 0 ; i < group ; i++) {
2955 			ioc->cpu_msix_table[cpu] = reply_q->msix_index;
2956 			cpu = cpumask_next(cpu, cpu_online_mask);
2957 		}
2958 		index++;
2959 	}
2960 }
2961 
2962 /**
2963  * _base_check_and_enable_high_iops_queues - enable high iops mode
2964  * @ ioc - per adapter object
2965  * @ hba_msix_vector_count - msix vectors supported by HBA
2966  *
2967  * Enable high iops queues only if
2968  *  - HBA is a SEA/AERO controller and
2969  *  - MSI-Xs vector supported by the HBA is 128 and
2970  *  - total CPU count in the system >=16 and
2971  *  - loaded driver with default max_msix_vectors module parameter and
2972  *  - system booted in non kdump mode
2973  *
2974  * returns nothing.
2975  */
2976 static void
2977 _base_check_and_enable_high_iops_queues(struct MPT3SAS_ADAPTER *ioc,
2978 		int hba_msix_vector_count)
2979 {
2980 	u16 lnksta, speed;
2981 
2982 	if (perf_mode == MPT_PERF_MODE_IOPS ||
2983 	    perf_mode == MPT_PERF_MODE_LATENCY) {
2984 		ioc->high_iops_queues = 0;
2985 		return;
2986 	}
2987 
2988 	if (perf_mode == MPT_PERF_MODE_DEFAULT) {
2989 
2990 		pcie_capability_read_word(ioc->pdev, PCI_EXP_LNKSTA, &lnksta);
2991 		speed = lnksta & PCI_EXP_LNKSTA_CLS;
2992 
2993 		if (speed < 0x4) {
2994 			ioc->high_iops_queues = 0;
2995 			return;
2996 		}
2997 	}
2998 
2999 	if (!reset_devices && ioc->is_aero_ioc &&
3000 	    hba_msix_vector_count == MPT3SAS_GEN35_MAX_MSIX_QUEUES &&
3001 	    num_online_cpus() >= MPT3SAS_HIGH_IOPS_REPLY_QUEUES &&
3002 	    max_msix_vectors == -1)
3003 		ioc->high_iops_queues = MPT3SAS_HIGH_IOPS_REPLY_QUEUES;
3004 	else
3005 		ioc->high_iops_queues = 0;
3006 }
3007 
3008 /**
3009  * _base_disable_msix - disables msix
3010  * @ioc: per adapter object
3011  *
3012  */
3013 static void
3014 _base_disable_msix(struct MPT3SAS_ADAPTER *ioc)
3015 {
3016 	if (!ioc->msix_enable)
3017 		return;
3018 	pci_free_irq_vectors(ioc->pdev);
3019 	ioc->msix_enable = 0;
3020 }
3021 
3022 /**
3023  * _base_alloc_irq_vectors - allocate msix vectors
3024  * @ioc: per adapter object
3025  *
3026  */
3027 static int
3028 _base_alloc_irq_vectors(struct MPT3SAS_ADAPTER *ioc)
3029 {
3030 	int i, irq_flags = PCI_IRQ_MSIX;
3031 	struct irq_affinity desc = { .pre_vectors = ioc->high_iops_queues };
3032 	struct irq_affinity *descp = &desc;
3033 
3034 	if (ioc->smp_affinity_enable)
3035 		irq_flags |= PCI_IRQ_AFFINITY;
3036 	else
3037 		descp = NULL;
3038 
3039 	ioc_info(ioc, " %d %d\n", ioc->high_iops_queues,
3040 	    ioc->msix_vector_count);
3041 
3042 	i = pci_alloc_irq_vectors_affinity(ioc->pdev,
3043 	    ioc->high_iops_queues,
3044 	    ioc->msix_vector_count, irq_flags, descp);
3045 
3046 	return i;
3047 }
3048 
3049 /**
3050  * _base_enable_msix - enables msix, failback to io_apic
3051  * @ioc: per adapter object
3052  *
3053  */
3054 static int
3055 _base_enable_msix(struct MPT3SAS_ADAPTER *ioc)
3056 {
3057 	int r;
3058 	int i, local_max_msix_vectors;
3059 	u8 try_msix = 0;
3060 
3061 	ioc->msix_load_balance = false;
3062 
3063 	if (msix_disable == -1 || msix_disable == 0)
3064 		try_msix = 1;
3065 
3066 	if (!try_msix)
3067 		goto try_ioapic;
3068 
3069 	if (_base_check_enable_msix(ioc) != 0)
3070 		goto try_ioapic;
3071 
3072 	ioc_info(ioc, "MSI-X vectors supported: %d\n", ioc->msix_vector_count);
3073 	pr_info("\t no of cores: %d, max_msix_vectors: %d\n",
3074 		ioc->cpu_count, max_msix_vectors);
3075 	if (ioc->is_aero_ioc)
3076 		_base_check_and_enable_high_iops_queues(ioc,
3077 			ioc->msix_vector_count);
3078 	ioc->reply_queue_count =
3079 		min_t(int, ioc->cpu_count + ioc->high_iops_queues,
3080 		ioc->msix_vector_count);
3081 
3082 	if (!ioc->rdpq_array_enable && max_msix_vectors == -1)
3083 		local_max_msix_vectors = (reset_devices) ? 1 : 8;
3084 	else
3085 		local_max_msix_vectors = max_msix_vectors;
3086 
3087 	if (local_max_msix_vectors > 0)
3088 		ioc->reply_queue_count = min_t(int, local_max_msix_vectors,
3089 			ioc->reply_queue_count);
3090 	else if (local_max_msix_vectors == 0)
3091 		goto try_ioapic;
3092 
3093 	/*
3094 	 * Enable msix_load_balance only if combined reply queue mode is
3095 	 * disabled on SAS3 & above generation HBA devices.
3096 	 */
3097 	if (!ioc->combined_reply_queue &&
3098 	    ioc->hba_mpi_version_belonged != MPI2_VERSION) {
3099 		ioc->msix_load_balance = true;
3100 	}
3101 
3102 	/*
3103 	 * smp affinity setting is not need when msix load balance
3104 	 * is enabled.
3105 	 */
3106 	if (ioc->msix_load_balance)
3107 		ioc->smp_affinity_enable = 0;
3108 
3109 	r = _base_alloc_irq_vectors(ioc);
3110 	if (r < 0) {
3111 		dfailprintk(ioc,
3112 			    ioc_info(ioc, "pci_alloc_irq_vectors failed (r=%d) !!!\n",
3113 				     r));
3114 		goto try_ioapic;
3115 	}
3116 
3117 	ioc->msix_enable = 1;
3118 	ioc->reply_queue_count = r;
3119 	for (i = 0; i < ioc->reply_queue_count; i++) {
3120 		r = _base_request_irq(ioc, i);
3121 		if (r) {
3122 			_base_free_irq(ioc);
3123 			_base_disable_msix(ioc);
3124 			goto try_ioapic;
3125 		}
3126 	}
3127 
3128 	ioc_info(ioc, "High IOPs queues : %s\n",
3129 			ioc->high_iops_queues ? "enabled" : "disabled");
3130 
3131 	return 0;
3132 
3133 /* failback to io_apic interrupt routing */
3134  try_ioapic:
3135 	ioc->high_iops_queues = 0;
3136 	ioc_info(ioc, "High IOPs queues : disabled\n");
3137 	ioc->reply_queue_count = 1;
3138 	r = pci_alloc_irq_vectors(ioc->pdev, 1, 1, PCI_IRQ_LEGACY);
3139 	if (r < 0) {
3140 		dfailprintk(ioc,
3141 			    ioc_info(ioc, "pci_alloc_irq_vector(legacy) failed (r=%d) !!!\n",
3142 				     r));
3143 	} else
3144 		r = _base_request_irq(ioc, 0);
3145 
3146 	return r;
3147 }
3148 
3149 /**
3150  * mpt3sas_base_unmap_resources - free controller resources
3151  * @ioc: per adapter object
3152  */
3153 static void
3154 mpt3sas_base_unmap_resources(struct MPT3SAS_ADAPTER *ioc)
3155 {
3156 	struct pci_dev *pdev = ioc->pdev;
3157 
3158 	dexitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
3159 
3160 	_base_free_irq(ioc);
3161 	_base_disable_msix(ioc);
3162 
3163 	kfree(ioc->replyPostRegisterIndex);
3164 	ioc->replyPostRegisterIndex = NULL;
3165 
3166 
3167 	if (ioc->chip_phys) {
3168 		iounmap(ioc->chip);
3169 		ioc->chip_phys = 0;
3170 	}
3171 
3172 	if (pci_is_enabled(pdev)) {
3173 		pci_release_selected_regions(ioc->pdev, ioc->bars);
3174 		pci_disable_pcie_error_reporting(pdev);
3175 		pci_disable_device(pdev);
3176 	}
3177 }
3178 
3179 /**
3180  * mpt3sas_base_map_resources - map in controller resources (io/irq/memap)
3181  * @ioc: per adapter object
3182  *
3183  * Return: 0 for success, non-zero for failure.
3184  */
3185 int
3186 mpt3sas_base_map_resources(struct MPT3SAS_ADAPTER *ioc)
3187 {
3188 	struct pci_dev *pdev = ioc->pdev;
3189 	u32 memap_sz;
3190 	u32 pio_sz;
3191 	int i, r = 0;
3192 	u64 pio_chip = 0;
3193 	phys_addr_t chip_phys = 0;
3194 	struct adapter_reply_queue *reply_q;
3195 
3196 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
3197 
3198 	ioc->bars = pci_select_bars(pdev, IORESOURCE_MEM);
3199 	if (pci_enable_device_mem(pdev)) {
3200 		ioc_warn(ioc, "pci_enable_device_mem: failed\n");
3201 		ioc->bars = 0;
3202 		return -ENODEV;
3203 	}
3204 
3205 
3206 	if (pci_request_selected_regions(pdev, ioc->bars,
3207 	    ioc->driver_name)) {
3208 		ioc_warn(ioc, "pci_request_selected_regions: failed\n");
3209 		ioc->bars = 0;
3210 		r = -ENODEV;
3211 		goto out_fail;
3212 	}
3213 
3214 /* AER (Advanced Error Reporting) hooks */
3215 	pci_enable_pcie_error_reporting(pdev);
3216 
3217 	pci_set_master(pdev);
3218 
3219 
3220 	if (_base_config_dma_addressing(ioc, pdev) != 0) {
3221 		ioc_warn(ioc, "no suitable DMA mask for %s\n", pci_name(pdev));
3222 		r = -ENODEV;
3223 		goto out_fail;
3224 	}
3225 
3226 	for (i = 0, memap_sz = 0, pio_sz = 0; (i < DEVICE_COUNT_RESOURCE) &&
3227 	     (!memap_sz || !pio_sz); i++) {
3228 		if (pci_resource_flags(pdev, i) & IORESOURCE_IO) {
3229 			if (pio_sz)
3230 				continue;
3231 			pio_chip = (u64)pci_resource_start(pdev, i);
3232 			pio_sz = pci_resource_len(pdev, i);
3233 		} else if (pci_resource_flags(pdev, i) & IORESOURCE_MEM) {
3234 			if (memap_sz)
3235 				continue;
3236 			ioc->chip_phys = pci_resource_start(pdev, i);
3237 			chip_phys = ioc->chip_phys;
3238 			memap_sz = pci_resource_len(pdev, i);
3239 			ioc->chip = ioremap(ioc->chip_phys, memap_sz);
3240 		}
3241 	}
3242 
3243 	if (ioc->chip == NULL) {
3244 		ioc_err(ioc, "unable to map adapter memory! or resource not found\n");
3245 		r = -EINVAL;
3246 		goto out_fail;
3247 	}
3248 
3249 	_base_mask_interrupts(ioc);
3250 
3251 	r = _base_get_ioc_facts(ioc);
3252 	if (r)
3253 		goto out_fail;
3254 
3255 	if (!ioc->rdpq_array_enable_assigned) {
3256 		ioc->rdpq_array_enable = ioc->rdpq_array_capable;
3257 		ioc->rdpq_array_enable_assigned = 1;
3258 	}
3259 
3260 	r = _base_enable_msix(ioc);
3261 	if (r)
3262 		goto out_fail;
3263 
3264 	if (!ioc->is_driver_loading)
3265 		_base_init_irqpolls(ioc);
3266 	/* Use the Combined reply queue feature only for SAS3 C0 & higher
3267 	 * revision HBAs and also only when reply queue count is greater than 8
3268 	 */
3269 	if (ioc->combined_reply_queue) {
3270 		/* Determine the Supplemental Reply Post Host Index Registers
3271 		 * Addresse. Supplemental Reply Post Host Index Registers
3272 		 * starts at offset MPI25_SUP_REPLY_POST_HOST_INDEX_OFFSET and
3273 		 * each register is at offset bytes of
3274 		 * MPT3_SUP_REPLY_POST_HOST_INDEX_REG_OFFSET from previous one.
3275 		 */
3276 		ioc->replyPostRegisterIndex = kcalloc(
3277 		     ioc->combined_reply_index_count,
3278 		     sizeof(resource_size_t *), GFP_KERNEL);
3279 		if (!ioc->replyPostRegisterIndex) {
3280 			dfailprintk(ioc,
3281 				    ioc_warn(ioc, "allocation for reply Post Register Index failed!!!\n"));
3282 			r = -ENOMEM;
3283 			goto out_fail;
3284 		}
3285 
3286 		for (i = 0; i < ioc->combined_reply_index_count; i++) {
3287 			ioc->replyPostRegisterIndex[i] = (resource_size_t *)
3288 			     ((u8 __force *)&ioc->chip->Doorbell +
3289 			     MPI25_SUP_REPLY_POST_HOST_INDEX_OFFSET +
3290 			     (i * MPT3_SUP_REPLY_POST_HOST_INDEX_REG_OFFSET));
3291 		}
3292 	}
3293 
3294 	if (ioc->is_warpdrive) {
3295 		ioc->reply_post_host_index[0] = (resource_size_t __iomem *)
3296 		    &ioc->chip->ReplyPostHostIndex;
3297 
3298 		for (i = 1; i < ioc->cpu_msix_table_sz; i++)
3299 			ioc->reply_post_host_index[i] =
3300 			(resource_size_t __iomem *)
3301 			((u8 __iomem *)&ioc->chip->Doorbell + (0x4000 + ((i - 1)
3302 			* 4)));
3303 	}
3304 
3305 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list)
3306 		pr_info("%s: %s enabled: IRQ %d\n",
3307 			reply_q->name,
3308 			ioc->msix_enable ? "PCI-MSI-X" : "IO-APIC",
3309 			pci_irq_vector(ioc->pdev, reply_q->msix_index));
3310 
3311 	ioc_info(ioc, "iomem(%pap), mapped(0x%p), size(%d)\n",
3312 		 &chip_phys, ioc->chip, memap_sz);
3313 	ioc_info(ioc, "ioport(0x%016llx), size(%d)\n",
3314 		 (unsigned long long)pio_chip, pio_sz);
3315 
3316 	/* Save PCI configuration state for recovery from PCI AER/EEH errors */
3317 	pci_save_state(pdev);
3318 	return 0;
3319 
3320  out_fail:
3321 	mpt3sas_base_unmap_resources(ioc);
3322 	return r;
3323 }
3324 
3325 /**
3326  * mpt3sas_base_get_msg_frame - obtain request mf pointer
3327  * @ioc: per adapter object
3328  * @smid: system request message index(smid zero is invalid)
3329  *
3330  * Return: virt pointer to message frame.
3331  */
3332 void *
3333 mpt3sas_base_get_msg_frame(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3334 {
3335 	return (void *)(ioc->request + (smid * ioc->request_sz));
3336 }
3337 
3338 /**
3339  * mpt3sas_base_get_sense_buffer - obtain a sense buffer virt addr
3340  * @ioc: per adapter object
3341  * @smid: system request message index
3342  *
3343  * Return: virt pointer to sense buffer.
3344  */
3345 void *
3346 mpt3sas_base_get_sense_buffer(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3347 {
3348 	return (void *)(ioc->sense + ((smid - 1) * SCSI_SENSE_BUFFERSIZE));
3349 }
3350 
3351 /**
3352  * mpt3sas_base_get_sense_buffer_dma - obtain a sense buffer dma addr
3353  * @ioc: per adapter object
3354  * @smid: system request message index
3355  *
3356  * Return: phys pointer to the low 32bit address of the sense buffer.
3357  */
3358 __le32
3359 mpt3sas_base_get_sense_buffer_dma(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3360 {
3361 	return cpu_to_le32(ioc->sense_dma + ((smid - 1) *
3362 	    SCSI_SENSE_BUFFERSIZE));
3363 }
3364 
3365 /**
3366  * mpt3sas_base_get_pcie_sgl - obtain a PCIe SGL virt addr
3367  * @ioc: per adapter object
3368  * @smid: system request message index
3369  *
3370  * Return: virt pointer to a PCIe SGL.
3371  */
3372 void *
3373 mpt3sas_base_get_pcie_sgl(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3374 {
3375 	return (void *)(ioc->pcie_sg_lookup[smid - 1].pcie_sgl);
3376 }
3377 
3378 /**
3379  * mpt3sas_base_get_pcie_sgl_dma - obtain a PCIe SGL dma addr
3380  * @ioc: per adapter object
3381  * @smid: system request message index
3382  *
3383  * Return: phys pointer to the address of the PCIe buffer.
3384  */
3385 dma_addr_t
3386 mpt3sas_base_get_pcie_sgl_dma(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3387 {
3388 	return ioc->pcie_sg_lookup[smid - 1].pcie_sgl_dma;
3389 }
3390 
3391 /**
3392  * mpt3sas_base_get_reply_virt_addr - obtain reply frames virt address
3393  * @ioc: per adapter object
3394  * @phys_addr: lower 32 physical addr of the reply
3395  *
3396  * Converts 32bit lower physical addr into a virt address.
3397  */
3398 void *
3399 mpt3sas_base_get_reply_virt_addr(struct MPT3SAS_ADAPTER *ioc, u32 phys_addr)
3400 {
3401 	if (!phys_addr)
3402 		return NULL;
3403 	return ioc->reply + (phys_addr - (u32)ioc->reply_dma);
3404 }
3405 
3406 /**
3407  * _base_get_msix_index - get the msix index
3408  * @ioc: per adapter object
3409  * @scmd: scsi_cmnd object
3410  *
3411  * returns msix index of general reply queues,
3412  * i.e. reply queue on which IO request's reply
3413  * should be posted by the HBA firmware.
3414  */
3415 static inline u8
3416 _base_get_msix_index(struct MPT3SAS_ADAPTER *ioc,
3417 	struct scsi_cmnd *scmd)
3418 {
3419 	/* Enables reply_queue load balancing */
3420 	if (ioc->msix_load_balance)
3421 		return ioc->reply_queue_count ?
3422 		    base_mod64(atomic64_add_return(1,
3423 		    &ioc->total_io_cnt), ioc->reply_queue_count) : 0;
3424 
3425 	return ioc->cpu_msix_table[raw_smp_processor_id()];
3426 }
3427 
3428 /**
3429  * _base_get_high_iops_msix_index - get the msix index of
3430  *				high iops queues
3431  * @ioc: per adapter object
3432  * @scmd: scsi_cmnd object
3433  *
3434  * Returns: msix index of high iops reply queues.
3435  * i.e. high iops reply queue on which IO request's
3436  * reply should be posted by the HBA firmware.
3437  */
3438 static inline u8
3439 _base_get_high_iops_msix_index(struct MPT3SAS_ADAPTER *ioc,
3440 	struct scsi_cmnd *scmd)
3441 {
3442 	/**
3443 	 * Round robin the IO interrupts among the high iops
3444 	 * reply queues in terms of batch count 16 when outstanding
3445 	 * IOs on the target device is >=8.
3446 	 */
3447 	if (atomic_read(&scmd->device->device_busy) >
3448 	    MPT3SAS_DEVICE_HIGH_IOPS_DEPTH)
3449 		return base_mod64((
3450 		    atomic64_add_return(1, &ioc->high_iops_outstanding) /
3451 		    MPT3SAS_HIGH_IOPS_BATCH_COUNT),
3452 		    MPT3SAS_HIGH_IOPS_REPLY_QUEUES);
3453 
3454 	return _base_get_msix_index(ioc, scmd);
3455 }
3456 
3457 /**
3458  * mpt3sas_base_get_smid - obtain a free smid from internal queue
3459  * @ioc: per adapter object
3460  * @cb_idx: callback index
3461  *
3462  * Return: smid (zero is invalid)
3463  */
3464 u16
3465 mpt3sas_base_get_smid(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx)
3466 {
3467 	unsigned long flags;
3468 	struct request_tracker *request;
3469 	u16 smid;
3470 
3471 	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3472 	if (list_empty(&ioc->internal_free_list)) {
3473 		spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3474 		ioc_err(ioc, "%s: smid not available\n", __func__);
3475 		return 0;
3476 	}
3477 
3478 	request = list_entry(ioc->internal_free_list.next,
3479 	    struct request_tracker, tracker_list);
3480 	request->cb_idx = cb_idx;
3481 	smid = request->smid;
3482 	list_del(&request->tracker_list);
3483 	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3484 	return smid;
3485 }
3486 
3487 /**
3488  * mpt3sas_base_get_smid_scsiio - obtain a free smid from scsiio queue
3489  * @ioc: per adapter object
3490  * @cb_idx: callback index
3491  * @scmd: pointer to scsi command object
3492  *
3493  * Return: smid (zero is invalid)
3494  */
3495 u16
3496 mpt3sas_base_get_smid_scsiio(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx,
3497 	struct scsi_cmnd *scmd)
3498 {
3499 	struct scsiio_tracker *request = scsi_cmd_priv(scmd);
3500 	unsigned int tag = scmd->request->tag;
3501 	u16 smid;
3502 
3503 	smid = tag + 1;
3504 	request->cb_idx = cb_idx;
3505 	request->smid = smid;
3506 	request->scmd = scmd;
3507 	INIT_LIST_HEAD(&request->chain_list);
3508 	return smid;
3509 }
3510 
3511 /**
3512  * mpt3sas_base_get_smid_hpr - obtain a free smid from hi-priority queue
3513  * @ioc: per adapter object
3514  * @cb_idx: callback index
3515  *
3516  * Return: smid (zero is invalid)
3517  */
3518 u16
3519 mpt3sas_base_get_smid_hpr(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx)
3520 {
3521 	unsigned long flags;
3522 	struct request_tracker *request;
3523 	u16 smid;
3524 
3525 	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3526 	if (list_empty(&ioc->hpr_free_list)) {
3527 		spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3528 		return 0;
3529 	}
3530 
3531 	request = list_entry(ioc->hpr_free_list.next,
3532 	    struct request_tracker, tracker_list);
3533 	request->cb_idx = cb_idx;
3534 	smid = request->smid;
3535 	list_del(&request->tracker_list);
3536 	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3537 	return smid;
3538 }
3539 
3540 static void
3541 _base_recovery_check(struct MPT3SAS_ADAPTER *ioc)
3542 {
3543 	/*
3544 	 * See _wait_for_commands_to_complete() call with regards to this code.
3545 	 */
3546 	if (ioc->shost_recovery && ioc->pending_io_count) {
3547 		ioc->pending_io_count = scsi_host_busy(ioc->shost);
3548 		if (ioc->pending_io_count == 0)
3549 			wake_up(&ioc->reset_wq);
3550 	}
3551 }
3552 
3553 void mpt3sas_base_clear_st(struct MPT3SAS_ADAPTER *ioc,
3554 			   struct scsiio_tracker *st)
3555 {
3556 	if (WARN_ON(st->smid == 0))
3557 		return;
3558 	st->cb_idx = 0xFF;
3559 	st->direct_io = 0;
3560 	st->scmd = NULL;
3561 	atomic_set(&ioc->chain_lookup[st->smid - 1].chain_offset, 0);
3562 	st->smid = 0;
3563 }
3564 
3565 /**
3566  * mpt3sas_base_free_smid - put smid back on free_list
3567  * @ioc: per adapter object
3568  * @smid: system request message index
3569  */
3570 void
3571 mpt3sas_base_free_smid(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3572 {
3573 	unsigned long flags;
3574 	int i;
3575 
3576 	if (smid < ioc->hi_priority_smid) {
3577 		struct scsiio_tracker *st;
3578 		void *request;
3579 
3580 		st = _get_st_from_smid(ioc, smid);
3581 		if (!st) {
3582 			_base_recovery_check(ioc);
3583 			return;
3584 		}
3585 
3586 		/* Clear MPI request frame */
3587 		request = mpt3sas_base_get_msg_frame(ioc, smid);
3588 		memset(request, 0, ioc->request_sz);
3589 
3590 		mpt3sas_base_clear_st(ioc, st);
3591 		_base_recovery_check(ioc);
3592 		return;
3593 	}
3594 
3595 	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
3596 	if (smid < ioc->internal_smid) {
3597 		/* hi-priority */
3598 		i = smid - ioc->hi_priority_smid;
3599 		ioc->hpr_lookup[i].cb_idx = 0xFF;
3600 		list_add(&ioc->hpr_lookup[i].tracker_list, &ioc->hpr_free_list);
3601 	} else if (smid <= ioc->hba_queue_depth) {
3602 		/* internal queue */
3603 		i = smid - ioc->internal_smid;
3604 		ioc->internal_lookup[i].cb_idx = 0xFF;
3605 		list_add(&ioc->internal_lookup[i].tracker_list,
3606 		    &ioc->internal_free_list);
3607 	}
3608 	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
3609 }
3610 
3611 /**
3612  * _base_mpi_ep_writeq - 32 bit write to MMIO
3613  * @b: data payload
3614  * @addr: address in MMIO space
3615  * @writeq_lock: spin lock
3616  *
3617  * This special handling for MPI EP to take care of 32 bit
3618  * environment where its not quarenteed to send the entire word
3619  * in one transfer.
3620  */
3621 static inline void
3622 _base_mpi_ep_writeq(__u64 b, volatile void __iomem *addr,
3623 					spinlock_t *writeq_lock)
3624 {
3625 	unsigned long flags;
3626 
3627 	spin_lock_irqsave(writeq_lock, flags);
3628 	__raw_writel((u32)(b), addr);
3629 	__raw_writel((u32)(b >> 32), (addr + 4));
3630 	spin_unlock_irqrestore(writeq_lock, flags);
3631 }
3632 
3633 /**
3634  * _base_writeq - 64 bit write to MMIO
3635  * @b: data payload
3636  * @addr: address in MMIO space
3637  * @writeq_lock: spin lock
3638  *
3639  * Glue for handling an atomic 64 bit word to MMIO. This special handling takes
3640  * care of 32 bit environment where its not quarenteed to send the entire word
3641  * in one transfer.
3642  */
3643 #if defined(writeq) && defined(CONFIG_64BIT)
3644 static inline void
3645 _base_writeq(__u64 b, volatile void __iomem *addr, spinlock_t *writeq_lock)
3646 {
3647 	wmb();
3648 	__raw_writeq(b, addr);
3649 	barrier();
3650 }
3651 #else
3652 static inline void
3653 _base_writeq(__u64 b, volatile void __iomem *addr, spinlock_t *writeq_lock)
3654 {
3655 	_base_mpi_ep_writeq(b, addr, writeq_lock);
3656 }
3657 #endif
3658 
3659 /**
3660  * _base_set_and_get_msix_index - get the msix index and assign to msix_io
3661  *                                variable of scsi tracker
3662  * @ioc: per adapter object
3663  * @smid: system request message index
3664  *
3665  * returns msix index.
3666  */
3667 static u8
3668 _base_set_and_get_msix_index(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3669 {
3670 	struct scsiio_tracker *st = NULL;
3671 
3672 	if (smid < ioc->hi_priority_smid)
3673 		st = _get_st_from_smid(ioc, smid);
3674 
3675 	if (st == NULL)
3676 		return  _base_get_msix_index(ioc, NULL);
3677 
3678 	st->msix_io = ioc->get_msix_index_for_smlio(ioc, st->scmd);
3679 	return st->msix_io;
3680 }
3681 
3682 /**
3683  * _base_put_smid_mpi_ep_scsi_io - send SCSI_IO request to firmware
3684  * @ioc: per adapter object
3685  * @smid: system request message index
3686  * @handle: device handle
3687  */
3688 static void
3689 _base_put_smid_mpi_ep_scsi_io(struct MPT3SAS_ADAPTER *ioc,
3690 	u16 smid, u16 handle)
3691 {
3692 	Mpi2RequestDescriptorUnion_t descriptor;
3693 	u64 *request = (u64 *)&descriptor;
3694 	void *mpi_req_iomem;
3695 	__le32 *mfp = (__le32 *)mpt3sas_base_get_msg_frame(ioc, smid);
3696 
3697 	_clone_sg_entries(ioc, (void *) mfp, smid);
3698 	mpi_req_iomem = (void __force *)ioc->chip +
3699 			MPI_FRAME_START_OFFSET + (smid * ioc->request_sz);
3700 	_base_clone_mpi_to_sys_mem(mpi_req_iomem, (void *)mfp,
3701 					ioc->request_sz);
3702 	descriptor.SCSIIO.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
3703 	descriptor.SCSIIO.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
3704 	descriptor.SCSIIO.SMID = cpu_to_le16(smid);
3705 	descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
3706 	descriptor.SCSIIO.LMID = 0;
3707 	_base_mpi_ep_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3708 	    &ioc->scsi_lookup_lock);
3709 }
3710 
3711 /**
3712  * _base_put_smid_scsi_io - send SCSI_IO request to firmware
3713  * @ioc: per adapter object
3714  * @smid: system request message index
3715  * @handle: device handle
3716  */
3717 static void
3718 _base_put_smid_scsi_io(struct MPT3SAS_ADAPTER *ioc, u16 smid, u16 handle)
3719 {
3720 	Mpi2RequestDescriptorUnion_t descriptor;
3721 	u64 *request = (u64 *)&descriptor;
3722 
3723 
3724 	descriptor.SCSIIO.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
3725 	descriptor.SCSIIO.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
3726 	descriptor.SCSIIO.SMID = cpu_to_le16(smid);
3727 	descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
3728 	descriptor.SCSIIO.LMID = 0;
3729 	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3730 	    &ioc->scsi_lookup_lock);
3731 }
3732 
3733 /**
3734  * _base_put_smid_fast_path - send fast path request to firmware
3735  * @ioc: per adapter object
3736  * @smid: system request message index
3737  * @handle: device handle
3738  */
3739 static void
3740 _base_put_smid_fast_path(struct MPT3SAS_ADAPTER *ioc, u16 smid,
3741 	u16 handle)
3742 {
3743 	Mpi2RequestDescriptorUnion_t descriptor;
3744 	u64 *request = (u64 *)&descriptor;
3745 
3746 	descriptor.SCSIIO.RequestFlags =
3747 	    MPI25_REQ_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO;
3748 	descriptor.SCSIIO.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
3749 	descriptor.SCSIIO.SMID = cpu_to_le16(smid);
3750 	descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
3751 	descriptor.SCSIIO.LMID = 0;
3752 	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3753 	    &ioc->scsi_lookup_lock);
3754 }
3755 
3756 /**
3757  * _base_put_smid_hi_priority - send Task Management request to firmware
3758  * @ioc: per adapter object
3759  * @smid: system request message index
3760  * @msix_task: msix_task will be same as msix of IO incase of task abort else 0.
3761  */
3762 static void
3763 _base_put_smid_hi_priority(struct MPT3SAS_ADAPTER *ioc, u16 smid,
3764 	u16 msix_task)
3765 {
3766 	Mpi2RequestDescriptorUnion_t descriptor;
3767 	void *mpi_req_iomem;
3768 	u64 *request;
3769 
3770 	if (ioc->is_mcpu_endpoint) {
3771 		__le32 *mfp = (__le32 *)mpt3sas_base_get_msg_frame(ioc, smid);
3772 
3773 		/* TBD 256 is offset within sys register. */
3774 		mpi_req_iomem = (void __force *)ioc->chip
3775 					+ MPI_FRAME_START_OFFSET
3776 					+ (smid * ioc->request_sz);
3777 		_base_clone_mpi_to_sys_mem(mpi_req_iomem, (void *)mfp,
3778 							ioc->request_sz);
3779 	}
3780 
3781 	request = (u64 *)&descriptor;
3782 
3783 	descriptor.HighPriority.RequestFlags =
3784 	    MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY;
3785 	descriptor.HighPriority.MSIxIndex =  msix_task;
3786 	descriptor.HighPriority.SMID = cpu_to_le16(smid);
3787 	descriptor.HighPriority.LMID = 0;
3788 	descriptor.HighPriority.Reserved1 = 0;
3789 	if (ioc->is_mcpu_endpoint)
3790 		_base_mpi_ep_writeq(*request,
3791 				&ioc->chip->RequestDescriptorPostLow,
3792 				&ioc->scsi_lookup_lock);
3793 	else
3794 		_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3795 		    &ioc->scsi_lookup_lock);
3796 }
3797 
3798 /**
3799  * mpt3sas_base_put_smid_nvme_encap - send NVMe encapsulated request to
3800  *  firmware
3801  * @ioc: per adapter object
3802  * @smid: system request message index
3803  */
3804 void
3805 mpt3sas_base_put_smid_nvme_encap(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3806 {
3807 	Mpi2RequestDescriptorUnion_t descriptor;
3808 	u64 *request = (u64 *)&descriptor;
3809 
3810 	descriptor.Default.RequestFlags =
3811 		MPI26_REQ_DESCRIPT_FLAGS_PCIE_ENCAPSULATED;
3812 	descriptor.Default.MSIxIndex =  _base_set_and_get_msix_index(ioc, smid);
3813 	descriptor.Default.SMID = cpu_to_le16(smid);
3814 	descriptor.Default.LMID = 0;
3815 	descriptor.Default.DescriptorTypeDependent = 0;
3816 	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3817 	    &ioc->scsi_lookup_lock);
3818 }
3819 
3820 /**
3821  * _base_put_smid_default - Default, primarily used for config pages
3822  * @ioc: per adapter object
3823  * @smid: system request message index
3824  */
3825 static void
3826 _base_put_smid_default(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3827 {
3828 	Mpi2RequestDescriptorUnion_t descriptor;
3829 	void *mpi_req_iomem;
3830 	u64 *request;
3831 
3832 	if (ioc->is_mcpu_endpoint) {
3833 		__le32 *mfp = (__le32 *)mpt3sas_base_get_msg_frame(ioc, smid);
3834 
3835 		_clone_sg_entries(ioc, (void *) mfp, smid);
3836 		/* TBD 256 is offset within sys register */
3837 		mpi_req_iomem = (void __force *)ioc->chip +
3838 			MPI_FRAME_START_OFFSET + (smid * ioc->request_sz);
3839 		_base_clone_mpi_to_sys_mem(mpi_req_iomem, (void *)mfp,
3840 							ioc->request_sz);
3841 	}
3842 	request = (u64 *)&descriptor;
3843 	descriptor.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
3844 	descriptor.Default.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
3845 	descriptor.Default.SMID = cpu_to_le16(smid);
3846 	descriptor.Default.LMID = 0;
3847 	descriptor.Default.DescriptorTypeDependent = 0;
3848 	if (ioc->is_mcpu_endpoint)
3849 		_base_mpi_ep_writeq(*request,
3850 				&ioc->chip->RequestDescriptorPostLow,
3851 				&ioc->scsi_lookup_lock);
3852 	else
3853 		_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
3854 				&ioc->scsi_lookup_lock);
3855 }
3856 
3857 /**
3858  * _base_put_smid_scsi_io_atomic - send SCSI_IO request to firmware using
3859  *   Atomic Request Descriptor
3860  * @ioc: per adapter object
3861  * @smid: system request message index
3862  * @handle: device handle, unused in this function, for function type match
3863  *
3864  * Return nothing.
3865  */
3866 static void
3867 _base_put_smid_scsi_io_atomic(struct MPT3SAS_ADAPTER *ioc, u16 smid,
3868 	u16 handle)
3869 {
3870 	Mpi26AtomicRequestDescriptor_t descriptor;
3871 	u32 *request = (u32 *)&descriptor;
3872 
3873 	descriptor.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
3874 	descriptor.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
3875 	descriptor.SMID = cpu_to_le16(smid);
3876 
3877 	writel(cpu_to_le32(*request), &ioc->chip->AtomicRequestDescriptorPost);
3878 }
3879 
3880 /**
3881  * _base_put_smid_fast_path_atomic - send fast path request to firmware
3882  * using Atomic Request Descriptor
3883  * @ioc: per adapter object
3884  * @smid: system request message index
3885  * @handle: device handle, unused in this function, for function type match
3886  * Return nothing
3887  */
3888 static void
3889 _base_put_smid_fast_path_atomic(struct MPT3SAS_ADAPTER *ioc, u16 smid,
3890 	u16 handle)
3891 {
3892 	Mpi26AtomicRequestDescriptor_t descriptor;
3893 	u32 *request = (u32 *)&descriptor;
3894 
3895 	descriptor.RequestFlags = MPI25_REQ_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO;
3896 	descriptor.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
3897 	descriptor.SMID = cpu_to_le16(smid);
3898 
3899 	writel(cpu_to_le32(*request), &ioc->chip->AtomicRequestDescriptorPost);
3900 }
3901 
3902 /**
3903  * _base_put_smid_hi_priority_atomic - send Task Management request to
3904  * firmware using Atomic Request Descriptor
3905  * @ioc: per adapter object
3906  * @smid: system request message index
3907  * @msix_task: msix_task will be same as msix of IO incase of task abort else 0
3908  *
3909  * Return nothing.
3910  */
3911 static void
3912 _base_put_smid_hi_priority_atomic(struct MPT3SAS_ADAPTER *ioc, u16 smid,
3913 	u16 msix_task)
3914 {
3915 	Mpi26AtomicRequestDescriptor_t descriptor;
3916 	u32 *request = (u32 *)&descriptor;
3917 
3918 	descriptor.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY;
3919 	descriptor.MSIxIndex = msix_task;
3920 	descriptor.SMID = cpu_to_le16(smid);
3921 
3922 	writel(cpu_to_le32(*request), &ioc->chip->AtomicRequestDescriptorPost);
3923 }
3924 
3925 /**
3926  * _base_put_smid_default - Default, primarily used for config pages
3927  * use Atomic Request Descriptor
3928  * @ioc: per adapter object
3929  * @smid: system request message index
3930  *
3931  * Return nothing.
3932  */
3933 static void
3934 _base_put_smid_default_atomic(struct MPT3SAS_ADAPTER *ioc, u16 smid)
3935 {
3936 	Mpi26AtomicRequestDescriptor_t descriptor;
3937 	u32 *request = (u32 *)&descriptor;
3938 
3939 	descriptor.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
3940 	descriptor.MSIxIndex = _base_set_and_get_msix_index(ioc, smid);
3941 	descriptor.SMID = cpu_to_le16(smid);
3942 
3943 	writel(cpu_to_le32(*request), &ioc->chip->AtomicRequestDescriptorPost);
3944 }
3945 
3946 /**
3947  * _base_display_OEMs_branding - Display branding string
3948  * @ioc: per adapter object
3949  */
3950 static void
3951 _base_display_OEMs_branding(struct MPT3SAS_ADAPTER *ioc)
3952 {
3953 	if (ioc->pdev->subsystem_vendor != PCI_VENDOR_ID_INTEL)
3954 		return;
3955 
3956 	switch (ioc->pdev->subsystem_vendor) {
3957 	case PCI_VENDOR_ID_INTEL:
3958 		switch (ioc->pdev->device) {
3959 		case MPI2_MFGPAGE_DEVID_SAS2008:
3960 			switch (ioc->pdev->subsystem_device) {
3961 			case MPT2SAS_INTEL_RMS2LL080_SSDID:
3962 				ioc_info(ioc, "%s\n",
3963 					 MPT2SAS_INTEL_RMS2LL080_BRANDING);
3964 				break;
3965 			case MPT2SAS_INTEL_RMS2LL040_SSDID:
3966 				ioc_info(ioc, "%s\n",
3967 					 MPT2SAS_INTEL_RMS2LL040_BRANDING);
3968 				break;
3969 			case MPT2SAS_INTEL_SSD910_SSDID:
3970 				ioc_info(ioc, "%s\n",
3971 					 MPT2SAS_INTEL_SSD910_BRANDING);
3972 				break;
3973 			default:
3974 				ioc_info(ioc, "Intel(R) Controller: Subsystem ID: 0x%X\n",
3975 					 ioc->pdev->subsystem_device);
3976 				break;
3977 			}
3978 			break;
3979 		case MPI2_MFGPAGE_DEVID_SAS2308_2:
3980 			switch (ioc->pdev->subsystem_device) {
3981 			case MPT2SAS_INTEL_RS25GB008_SSDID:
3982 				ioc_info(ioc, "%s\n",
3983 					 MPT2SAS_INTEL_RS25GB008_BRANDING);
3984 				break;
3985 			case MPT2SAS_INTEL_RMS25JB080_SSDID:
3986 				ioc_info(ioc, "%s\n",
3987 					 MPT2SAS_INTEL_RMS25JB080_BRANDING);
3988 				break;
3989 			case MPT2SAS_INTEL_RMS25JB040_SSDID:
3990 				ioc_info(ioc, "%s\n",
3991 					 MPT2SAS_INTEL_RMS25JB040_BRANDING);
3992 				break;
3993 			case MPT2SAS_INTEL_RMS25KB080_SSDID:
3994 				ioc_info(ioc, "%s\n",
3995 					 MPT2SAS_INTEL_RMS25KB080_BRANDING);
3996 				break;
3997 			case MPT2SAS_INTEL_RMS25KB040_SSDID:
3998 				ioc_info(ioc, "%s\n",
3999 					 MPT2SAS_INTEL_RMS25KB040_BRANDING);
4000 				break;
4001 			case MPT2SAS_INTEL_RMS25LB040_SSDID:
4002 				ioc_info(ioc, "%s\n",
4003 					 MPT2SAS_INTEL_RMS25LB040_BRANDING);
4004 				break;
4005 			case MPT2SAS_INTEL_RMS25LB080_SSDID:
4006 				ioc_info(ioc, "%s\n",
4007 					 MPT2SAS_INTEL_RMS25LB080_BRANDING);
4008 				break;
4009 			default:
4010 				ioc_info(ioc, "Intel(R) Controller: Subsystem ID: 0x%X\n",
4011 					 ioc->pdev->subsystem_device);
4012 				break;
4013 			}
4014 			break;
4015 		case MPI25_MFGPAGE_DEVID_SAS3008:
4016 			switch (ioc->pdev->subsystem_device) {
4017 			case MPT3SAS_INTEL_RMS3JC080_SSDID:
4018 				ioc_info(ioc, "%s\n",
4019 					 MPT3SAS_INTEL_RMS3JC080_BRANDING);
4020 				break;
4021 
4022 			case MPT3SAS_INTEL_RS3GC008_SSDID:
4023 				ioc_info(ioc, "%s\n",
4024 					 MPT3SAS_INTEL_RS3GC008_BRANDING);
4025 				break;
4026 			case MPT3SAS_INTEL_RS3FC044_SSDID:
4027 				ioc_info(ioc, "%s\n",
4028 					 MPT3SAS_INTEL_RS3FC044_BRANDING);
4029 				break;
4030 			case MPT3SAS_INTEL_RS3UC080_SSDID:
4031 				ioc_info(ioc, "%s\n",
4032 					 MPT3SAS_INTEL_RS3UC080_BRANDING);
4033 				break;
4034 			default:
4035 				ioc_info(ioc, "Intel(R) Controller: Subsystem ID: 0x%X\n",
4036 					 ioc->pdev->subsystem_device);
4037 				break;
4038 			}
4039 			break;
4040 		default:
4041 			ioc_info(ioc, "Intel(R) Controller: Subsystem ID: 0x%X\n",
4042 				 ioc->pdev->subsystem_device);
4043 			break;
4044 		}
4045 		break;
4046 	case PCI_VENDOR_ID_DELL:
4047 		switch (ioc->pdev->device) {
4048 		case MPI2_MFGPAGE_DEVID_SAS2008:
4049 			switch (ioc->pdev->subsystem_device) {
4050 			case MPT2SAS_DELL_6GBPS_SAS_HBA_SSDID:
4051 				ioc_info(ioc, "%s\n",
4052 					 MPT2SAS_DELL_6GBPS_SAS_HBA_BRANDING);
4053 				break;
4054 			case MPT2SAS_DELL_PERC_H200_ADAPTER_SSDID:
4055 				ioc_info(ioc, "%s\n",
4056 					 MPT2SAS_DELL_PERC_H200_ADAPTER_BRANDING);
4057 				break;
4058 			case MPT2SAS_DELL_PERC_H200_INTEGRATED_SSDID:
4059 				ioc_info(ioc, "%s\n",
4060 					 MPT2SAS_DELL_PERC_H200_INTEGRATED_BRANDING);
4061 				break;
4062 			case MPT2SAS_DELL_PERC_H200_MODULAR_SSDID:
4063 				ioc_info(ioc, "%s\n",
4064 					 MPT2SAS_DELL_PERC_H200_MODULAR_BRANDING);
4065 				break;
4066 			case MPT2SAS_DELL_PERC_H200_EMBEDDED_SSDID:
4067 				ioc_info(ioc, "%s\n",
4068 					 MPT2SAS_DELL_PERC_H200_EMBEDDED_BRANDING);
4069 				break;
4070 			case MPT2SAS_DELL_PERC_H200_SSDID:
4071 				ioc_info(ioc, "%s\n",
4072 					 MPT2SAS_DELL_PERC_H200_BRANDING);
4073 				break;
4074 			case MPT2SAS_DELL_6GBPS_SAS_SSDID:
4075 				ioc_info(ioc, "%s\n",
4076 					 MPT2SAS_DELL_6GBPS_SAS_BRANDING);
4077 				break;
4078 			default:
4079 				ioc_info(ioc, "Dell 6Gbps HBA: Subsystem ID: 0x%X\n",
4080 					 ioc->pdev->subsystem_device);
4081 				break;
4082 			}
4083 			break;
4084 		case MPI25_MFGPAGE_DEVID_SAS3008:
4085 			switch (ioc->pdev->subsystem_device) {
4086 			case MPT3SAS_DELL_12G_HBA_SSDID:
4087 				ioc_info(ioc, "%s\n",
4088 					 MPT3SAS_DELL_12G_HBA_BRANDING);
4089 				break;
4090 			default:
4091 				ioc_info(ioc, "Dell 12Gbps HBA: Subsystem ID: 0x%X\n",
4092 					 ioc->pdev->subsystem_device);
4093 				break;
4094 			}
4095 			break;
4096 		default:
4097 			ioc_info(ioc, "Dell HBA: Subsystem ID: 0x%X\n",
4098 				 ioc->pdev->subsystem_device);
4099 			break;
4100 		}
4101 		break;
4102 	case PCI_VENDOR_ID_CISCO:
4103 		switch (ioc->pdev->device) {
4104 		case MPI25_MFGPAGE_DEVID_SAS3008:
4105 			switch (ioc->pdev->subsystem_device) {
4106 			case MPT3SAS_CISCO_12G_8E_HBA_SSDID:
4107 				ioc_info(ioc, "%s\n",
4108 					 MPT3SAS_CISCO_12G_8E_HBA_BRANDING);
4109 				break;
4110 			case MPT3SAS_CISCO_12G_8I_HBA_SSDID:
4111 				ioc_info(ioc, "%s\n",
4112 					 MPT3SAS_CISCO_12G_8I_HBA_BRANDING);
4113 				break;
4114 			case MPT3SAS_CISCO_12G_AVILA_HBA_SSDID:
4115 				ioc_info(ioc, "%s\n",
4116 					 MPT3SAS_CISCO_12G_AVILA_HBA_BRANDING);
4117 				break;
4118 			default:
4119 				ioc_info(ioc, "Cisco 12Gbps SAS HBA: Subsystem ID: 0x%X\n",
4120 					 ioc->pdev->subsystem_device);
4121 				break;
4122 			}
4123 			break;
4124 		case MPI25_MFGPAGE_DEVID_SAS3108_1:
4125 			switch (ioc->pdev->subsystem_device) {
4126 			case MPT3SAS_CISCO_12G_AVILA_HBA_SSDID:
4127 				ioc_info(ioc, "%s\n",
4128 					 MPT3SAS_CISCO_12G_AVILA_HBA_BRANDING);
4129 				break;
4130 			case MPT3SAS_CISCO_12G_COLUSA_MEZZANINE_HBA_SSDID:
4131 				ioc_info(ioc, "%s\n",
4132 					 MPT3SAS_CISCO_12G_COLUSA_MEZZANINE_HBA_BRANDING);
4133 				break;
4134 			default:
4135 				ioc_info(ioc, "Cisco 12Gbps SAS HBA: Subsystem ID: 0x%X\n",
4136 					 ioc->pdev->subsystem_device);
4137 				break;
4138 			}
4139 			break;
4140 		default:
4141 			ioc_info(ioc, "Cisco SAS HBA: Subsystem ID: 0x%X\n",
4142 				 ioc->pdev->subsystem_device);
4143 			break;
4144 		}
4145 		break;
4146 	case MPT2SAS_HP_3PAR_SSVID:
4147 		switch (ioc->pdev->device) {
4148 		case MPI2_MFGPAGE_DEVID_SAS2004:
4149 			switch (ioc->pdev->subsystem_device) {
4150 			case MPT2SAS_HP_DAUGHTER_2_4_INTERNAL_SSDID:
4151 				ioc_info(ioc, "%s\n",
4152 					 MPT2SAS_HP_DAUGHTER_2_4_INTERNAL_BRANDING);
4153 				break;
4154 			default:
4155 				ioc_info(ioc, "HP 6Gbps SAS HBA: Subsystem ID: 0x%X\n",
4156 					 ioc->pdev->subsystem_device);
4157 				break;
4158 			}
4159 			break;
4160 		case MPI2_MFGPAGE_DEVID_SAS2308_2:
4161 			switch (ioc->pdev->subsystem_device) {
4162 			case MPT2SAS_HP_2_4_INTERNAL_SSDID:
4163 				ioc_info(ioc, "%s\n",
4164 					 MPT2SAS_HP_2_4_INTERNAL_BRANDING);
4165 				break;
4166 			case MPT2SAS_HP_2_4_EXTERNAL_SSDID:
4167 				ioc_info(ioc, "%s\n",
4168 					 MPT2SAS_HP_2_4_EXTERNAL_BRANDING);
4169 				break;
4170 			case MPT2SAS_HP_1_4_INTERNAL_1_4_EXTERNAL_SSDID:
4171 				ioc_info(ioc, "%s\n",
4172 					 MPT2SAS_HP_1_4_INTERNAL_1_4_EXTERNAL_BRANDING);
4173 				break;
4174 			case MPT2SAS_HP_EMBEDDED_2_4_INTERNAL_SSDID:
4175 				ioc_info(ioc, "%s\n",
4176 					 MPT2SAS_HP_EMBEDDED_2_4_INTERNAL_BRANDING);
4177 				break;
4178 			default:
4179 				ioc_info(ioc, "HP 6Gbps SAS HBA: Subsystem ID: 0x%X\n",
4180 					 ioc->pdev->subsystem_device);
4181 				break;
4182 			}
4183 			break;
4184 		default:
4185 			ioc_info(ioc, "HP SAS HBA: Subsystem ID: 0x%X\n",
4186 				 ioc->pdev->subsystem_device);
4187 			break;
4188 		}
4189 	default:
4190 		break;
4191 	}
4192 }
4193 
4194 /**
4195  * _base_display_fwpkg_version - sends FWUpload request to pull FWPkg
4196  *				version from FW Image Header.
4197  * @ioc: per adapter object
4198  *
4199  * Return: 0 for success, non-zero for failure.
4200  */
4201 	static int
4202 _base_display_fwpkg_version(struct MPT3SAS_ADAPTER *ioc)
4203 {
4204 	Mpi2FWImageHeader_t *FWImgHdr;
4205 	Mpi25FWUploadRequest_t *mpi_request;
4206 	Mpi2FWUploadReply_t mpi_reply;
4207 	int r = 0;
4208 	void *fwpkg_data = NULL;
4209 	dma_addr_t fwpkg_data_dma;
4210 	u16 smid, ioc_status;
4211 	size_t data_length;
4212 
4213 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
4214 
4215 	if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
4216 		ioc_err(ioc, "%s: internal command already in use\n", __func__);
4217 		return -EAGAIN;
4218 	}
4219 
4220 	data_length = sizeof(Mpi2FWImageHeader_t);
4221 	fwpkg_data = dma_alloc_coherent(&ioc->pdev->dev, data_length,
4222 			&fwpkg_data_dma, GFP_KERNEL);
4223 	if (!fwpkg_data) {
4224 		ioc_err(ioc, "failure at %s:%d/%s()!\n",
4225 			__FILE__, __LINE__, __func__);
4226 		return -ENOMEM;
4227 	}
4228 
4229 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
4230 	if (!smid) {
4231 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
4232 		r = -EAGAIN;
4233 		goto out;
4234 	}
4235 
4236 	ioc->base_cmds.status = MPT3_CMD_PENDING;
4237 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
4238 	ioc->base_cmds.smid = smid;
4239 	memset(mpi_request, 0, sizeof(Mpi25FWUploadRequest_t));
4240 	mpi_request->Function = MPI2_FUNCTION_FW_UPLOAD;
4241 	mpi_request->ImageType = MPI2_FW_UPLOAD_ITYPE_FW_FLASH;
4242 	mpi_request->ImageSize = cpu_to_le32(data_length);
4243 	ioc->build_sg(ioc, &mpi_request->SGL, 0, 0, fwpkg_data_dma,
4244 			data_length);
4245 	init_completion(&ioc->base_cmds.done);
4246 	ioc->put_smid_default(ioc, smid);
4247 	/* Wait for 15 seconds */
4248 	wait_for_completion_timeout(&ioc->base_cmds.done,
4249 			FW_IMG_HDR_READ_TIMEOUT*HZ);
4250 	ioc_info(ioc, "%s: complete\n", __func__);
4251 	if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
4252 		ioc_err(ioc, "%s: timeout\n", __func__);
4253 		_debug_dump_mf(mpi_request,
4254 				sizeof(Mpi25FWUploadRequest_t)/4);
4255 		r = -ETIME;
4256 	} else {
4257 		memset(&mpi_reply, 0, sizeof(Mpi2FWUploadReply_t));
4258 		if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID) {
4259 			memcpy(&mpi_reply, ioc->base_cmds.reply,
4260 					sizeof(Mpi2FWUploadReply_t));
4261 			ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
4262 						MPI2_IOCSTATUS_MASK;
4263 			if (ioc_status == MPI2_IOCSTATUS_SUCCESS) {
4264 				FWImgHdr = (Mpi2FWImageHeader_t *)fwpkg_data;
4265 				if (FWImgHdr->PackageVersion.Word) {
4266 					ioc_info(ioc, "FW Package Version (%02d.%02d.%02d.%02d)\n",
4267 						 FWImgHdr->PackageVersion.Struct.Major,
4268 						 FWImgHdr->PackageVersion.Struct.Minor,
4269 						 FWImgHdr->PackageVersion.Struct.Unit,
4270 						 FWImgHdr->PackageVersion.Struct.Dev);
4271 				}
4272 			} else {
4273 				_debug_dump_mf(&mpi_reply,
4274 						sizeof(Mpi2FWUploadReply_t)/4);
4275 			}
4276 		}
4277 	}
4278 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
4279 out:
4280 	if (fwpkg_data)
4281 		dma_free_coherent(&ioc->pdev->dev, data_length, fwpkg_data,
4282 				fwpkg_data_dma);
4283 	return r;
4284 }
4285 
4286 /**
4287  * _base_display_ioc_capabilities - Disply IOC's capabilities.
4288  * @ioc: per adapter object
4289  */
4290 static void
4291 _base_display_ioc_capabilities(struct MPT3SAS_ADAPTER *ioc)
4292 {
4293 	int i = 0;
4294 	char desc[16];
4295 	u32 iounit_pg1_flags;
4296 	u32 bios_version;
4297 
4298 	bios_version = le32_to_cpu(ioc->bios_pg3.BiosVersion);
4299 	strncpy(desc, ioc->manu_pg0.ChipName, 16);
4300 	ioc_info(ioc, "%s: FWVersion(%02d.%02d.%02d.%02d), ChipRevision(0x%02x), BiosVersion(%02d.%02d.%02d.%02d)\n",
4301 		 desc,
4302 		 (ioc->facts.FWVersion.Word & 0xFF000000) >> 24,
4303 		 (ioc->facts.FWVersion.Word & 0x00FF0000) >> 16,
4304 		 (ioc->facts.FWVersion.Word & 0x0000FF00) >> 8,
4305 		 ioc->facts.FWVersion.Word & 0x000000FF,
4306 		 ioc->pdev->revision,
4307 		 (bios_version & 0xFF000000) >> 24,
4308 		 (bios_version & 0x00FF0000) >> 16,
4309 		 (bios_version & 0x0000FF00) >> 8,
4310 		 bios_version & 0x000000FF);
4311 
4312 	_base_display_OEMs_branding(ioc);
4313 
4314 	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_NVME_DEVICES) {
4315 		pr_info("%sNVMe", i ? "," : "");
4316 		i++;
4317 	}
4318 
4319 	ioc_info(ioc, "Protocol=(");
4320 
4321 	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_INITIATOR) {
4322 		pr_cont("Initiator");
4323 		i++;
4324 	}
4325 
4326 	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_TARGET) {
4327 		pr_cont("%sTarget", i ? "," : "");
4328 		i++;
4329 	}
4330 
4331 	i = 0;
4332 	pr_cont("), Capabilities=(");
4333 
4334 	if (!ioc->hide_ir_msg) {
4335 		if (ioc->facts.IOCCapabilities &
4336 		    MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID) {
4337 			pr_cont("Raid");
4338 			i++;
4339 		}
4340 	}
4341 
4342 	if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR) {
4343 		pr_cont("%sTLR", i ? "," : "");
4344 		i++;
4345 	}
4346 
4347 	if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_MULTICAST) {
4348 		pr_cont("%sMulticast", i ? "," : "");
4349 		i++;
4350 	}
4351 
4352 	if (ioc->facts.IOCCapabilities &
4353 	    MPI2_IOCFACTS_CAPABILITY_BIDIRECTIONAL_TARGET) {
4354 		pr_cont("%sBIDI Target", i ? "," : "");
4355 		i++;
4356 	}
4357 
4358 	if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP) {
4359 		pr_cont("%sEEDP", i ? "," : "");
4360 		i++;
4361 	}
4362 
4363 	if (ioc->facts.IOCCapabilities &
4364 	    MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER) {
4365 		pr_cont("%sSnapshot Buffer", i ? "," : "");
4366 		i++;
4367 	}
4368 
4369 	if (ioc->facts.IOCCapabilities &
4370 	    MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER) {
4371 		pr_cont("%sDiag Trace Buffer", i ? "," : "");
4372 		i++;
4373 	}
4374 
4375 	if (ioc->facts.IOCCapabilities &
4376 	    MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER) {
4377 		pr_cont("%sDiag Extended Buffer", i ? "," : "");
4378 		i++;
4379 	}
4380 
4381 	if (ioc->facts.IOCCapabilities &
4382 	    MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING) {
4383 		pr_cont("%sTask Set Full", i ? "," : "");
4384 		i++;
4385 	}
4386 
4387 	iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
4388 	if (!(iounit_pg1_flags & MPI2_IOUNITPAGE1_NATIVE_COMMAND_Q_DISABLE)) {
4389 		pr_cont("%sNCQ", i ? "," : "");
4390 		i++;
4391 	}
4392 
4393 	pr_cont(")\n");
4394 }
4395 
4396 /**
4397  * mpt3sas_base_update_missing_delay - change the missing delay timers
4398  * @ioc: per adapter object
4399  * @device_missing_delay: amount of time till device is reported missing
4400  * @io_missing_delay: interval IO is returned when there is a missing device
4401  *
4402  * Passed on the command line, this function will modify the device missing
4403  * delay, as well as the io missing delay. This should be called at driver
4404  * load time.
4405  */
4406 void
4407 mpt3sas_base_update_missing_delay(struct MPT3SAS_ADAPTER *ioc,
4408 	u16 device_missing_delay, u8 io_missing_delay)
4409 {
4410 	u16 dmd, dmd_new, dmd_orignal;
4411 	u8 io_missing_delay_original;
4412 	u16 sz;
4413 	Mpi2SasIOUnitPage1_t *sas_iounit_pg1 = NULL;
4414 	Mpi2ConfigReply_t mpi_reply;
4415 	u8 num_phys = 0;
4416 	u16 ioc_status;
4417 
4418 	mpt3sas_config_get_number_hba_phys(ioc, &num_phys);
4419 	if (!num_phys)
4420 		return;
4421 
4422 	sz = offsetof(Mpi2SasIOUnitPage1_t, PhyData) + (num_phys *
4423 	    sizeof(Mpi2SasIOUnit1PhyData_t));
4424 	sas_iounit_pg1 = kzalloc(sz, GFP_KERNEL);
4425 	if (!sas_iounit_pg1) {
4426 		ioc_err(ioc, "failure at %s:%d/%s()!\n",
4427 			__FILE__, __LINE__, __func__);
4428 		goto out;
4429 	}
4430 	if ((mpt3sas_config_get_sas_iounit_pg1(ioc, &mpi_reply,
4431 	    sas_iounit_pg1, sz))) {
4432 		ioc_err(ioc, "failure at %s:%d/%s()!\n",
4433 			__FILE__, __LINE__, __func__);
4434 		goto out;
4435 	}
4436 	ioc_status = le16_to_cpu(mpi_reply.IOCStatus) &
4437 	    MPI2_IOCSTATUS_MASK;
4438 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
4439 		ioc_err(ioc, "failure at %s:%d/%s()!\n",
4440 			__FILE__, __LINE__, __func__);
4441 		goto out;
4442 	}
4443 
4444 	/* device missing delay */
4445 	dmd = sas_iounit_pg1->ReportDeviceMissingDelay;
4446 	if (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16)
4447 		dmd = (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK) * 16;
4448 	else
4449 		dmd = dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK;
4450 	dmd_orignal = dmd;
4451 	if (device_missing_delay > 0x7F) {
4452 		dmd = (device_missing_delay > 0x7F0) ? 0x7F0 :
4453 		    device_missing_delay;
4454 		dmd = dmd / 16;
4455 		dmd |= MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16;
4456 	} else
4457 		dmd = device_missing_delay;
4458 	sas_iounit_pg1->ReportDeviceMissingDelay = dmd;
4459 
4460 	/* io missing delay */
4461 	io_missing_delay_original = sas_iounit_pg1->IODeviceMissingDelay;
4462 	sas_iounit_pg1->IODeviceMissingDelay = io_missing_delay;
4463 
4464 	if (!mpt3sas_config_set_sas_iounit_pg1(ioc, &mpi_reply, sas_iounit_pg1,
4465 	    sz)) {
4466 		if (dmd & MPI2_SASIOUNIT1_REPORT_MISSING_UNIT_16)
4467 			dmd_new = (dmd &
4468 			    MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK) * 16;
4469 		else
4470 			dmd_new =
4471 		    dmd & MPI2_SASIOUNIT1_REPORT_MISSING_TIMEOUT_MASK;
4472 		ioc_info(ioc, "device_missing_delay: old(%d), new(%d)\n",
4473 			 dmd_orignal, dmd_new);
4474 		ioc_info(ioc, "ioc_missing_delay: old(%d), new(%d)\n",
4475 			 io_missing_delay_original,
4476 			 io_missing_delay);
4477 		ioc->device_missing_delay = dmd_new;
4478 		ioc->io_missing_delay = io_missing_delay;
4479 	}
4480 
4481 out:
4482 	kfree(sas_iounit_pg1);
4483 }
4484 
4485 /**
4486  * _base_update_ioc_page1_inlinewith_perf_mode - Update IOC Page1 fields
4487  *    according to performance mode.
4488  * @ioc : per adapter object
4489  *
4490  * Return nothing.
4491  */
4492 static void
4493 _base_update_ioc_page1_inlinewith_perf_mode(struct MPT3SAS_ADAPTER *ioc)
4494 {
4495 	Mpi2IOCPage1_t ioc_pg1;
4496 	Mpi2ConfigReply_t mpi_reply;
4497 
4498 	mpt3sas_config_get_ioc_pg1(ioc, &mpi_reply, &ioc->ioc_pg1_copy);
4499 	memcpy(&ioc_pg1, &ioc->ioc_pg1_copy, sizeof(Mpi2IOCPage1_t));
4500 
4501 	switch (perf_mode) {
4502 	case MPT_PERF_MODE_DEFAULT:
4503 	case MPT_PERF_MODE_BALANCED:
4504 		if (ioc->high_iops_queues) {
4505 			ioc_info(ioc,
4506 				"Enable interrupt coalescing only for first\t"
4507 				"%d reply queues\n",
4508 				MPT3SAS_HIGH_IOPS_REPLY_QUEUES);
4509 			/*
4510 			 * If 31st bit is zero then interrupt coalescing is
4511 			 * enabled for all reply descriptor post queues.
4512 			 * If 31st bit is set to one then user can
4513 			 * enable/disable interrupt coalescing on per reply
4514 			 * descriptor post queue group(8) basis. So to enable
4515 			 * interrupt coalescing only on first reply descriptor
4516 			 * post queue group 31st bit and zero th bit is enabled.
4517 			 */
4518 			ioc_pg1.ProductSpecific = cpu_to_le32(0x80000000 |
4519 			    ((1 << MPT3SAS_HIGH_IOPS_REPLY_QUEUES/8) - 1));
4520 			mpt3sas_config_set_ioc_pg1(ioc, &mpi_reply, &ioc_pg1);
4521 			ioc_info(ioc, "performance mode: balanced\n");
4522 			return;
4523 		}
4524 		/* Fall through */
4525 	case MPT_PERF_MODE_LATENCY:
4526 		/*
4527 		 * Enable interrupt coalescing on all reply queues
4528 		 * with timeout value 0xA
4529 		 */
4530 		ioc_pg1.CoalescingTimeout = cpu_to_le32(0xa);
4531 		ioc_pg1.Flags |= cpu_to_le32(MPI2_IOCPAGE1_REPLY_COALESCING);
4532 		ioc_pg1.ProductSpecific = 0;
4533 		mpt3sas_config_set_ioc_pg1(ioc, &mpi_reply, &ioc_pg1);
4534 		ioc_info(ioc, "performance mode: latency\n");
4535 		break;
4536 	case MPT_PERF_MODE_IOPS:
4537 		/*
4538 		 * Enable interrupt coalescing on all reply queues.
4539 		 */
4540 		ioc_info(ioc,
4541 		    "performance mode: iops with coalescing timeout: 0x%x\n",
4542 		    le32_to_cpu(ioc_pg1.CoalescingTimeout));
4543 		ioc_pg1.Flags |= cpu_to_le32(MPI2_IOCPAGE1_REPLY_COALESCING);
4544 		ioc_pg1.ProductSpecific = 0;
4545 		mpt3sas_config_set_ioc_pg1(ioc, &mpi_reply, &ioc_pg1);
4546 		break;
4547 	}
4548 }
4549 
4550 /**
4551  * _base_static_config_pages - static start of day config pages
4552  * @ioc: per adapter object
4553  */
4554 static void
4555 _base_static_config_pages(struct MPT3SAS_ADAPTER *ioc)
4556 {
4557 	Mpi2ConfigReply_t mpi_reply;
4558 	u32 iounit_pg1_flags;
4559 
4560 	ioc->nvme_abort_timeout = 30;
4561 	mpt3sas_config_get_manufacturing_pg0(ioc, &mpi_reply, &ioc->manu_pg0);
4562 	if (ioc->ir_firmware)
4563 		mpt3sas_config_get_manufacturing_pg10(ioc, &mpi_reply,
4564 		    &ioc->manu_pg10);
4565 
4566 	/*
4567 	 * Ensure correct T10 PI operation if vendor left EEDPTagMode
4568 	 * flag unset in NVDATA.
4569 	 */
4570 	mpt3sas_config_get_manufacturing_pg11(ioc, &mpi_reply, &ioc->manu_pg11);
4571 	if (!ioc->is_gen35_ioc && ioc->manu_pg11.EEDPTagMode == 0) {
4572 		pr_err("%s: overriding NVDATA EEDPTagMode setting\n",
4573 		    ioc->name);
4574 		ioc->manu_pg11.EEDPTagMode &= ~0x3;
4575 		ioc->manu_pg11.EEDPTagMode |= 0x1;
4576 		mpt3sas_config_set_manufacturing_pg11(ioc, &mpi_reply,
4577 		    &ioc->manu_pg11);
4578 	}
4579 	if (ioc->manu_pg11.AddlFlags2 & NVME_TASK_MNGT_CUSTOM_MASK)
4580 		ioc->tm_custom_handling = 1;
4581 	else {
4582 		ioc->tm_custom_handling = 0;
4583 		if (ioc->manu_pg11.NVMeAbortTO < NVME_TASK_ABORT_MIN_TIMEOUT)
4584 			ioc->nvme_abort_timeout = NVME_TASK_ABORT_MIN_TIMEOUT;
4585 		else if (ioc->manu_pg11.NVMeAbortTO >
4586 					NVME_TASK_ABORT_MAX_TIMEOUT)
4587 			ioc->nvme_abort_timeout = NVME_TASK_ABORT_MAX_TIMEOUT;
4588 		else
4589 			ioc->nvme_abort_timeout = ioc->manu_pg11.NVMeAbortTO;
4590 	}
4591 
4592 	mpt3sas_config_get_bios_pg2(ioc, &mpi_reply, &ioc->bios_pg2);
4593 	mpt3sas_config_get_bios_pg3(ioc, &mpi_reply, &ioc->bios_pg3);
4594 	mpt3sas_config_get_ioc_pg8(ioc, &mpi_reply, &ioc->ioc_pg8);
4595 	mpt3sas_config_get_iounit_pg0(ioc, &mpi_reply, &ioc->iounit_pg0);
4596 	mpt3sas_config_get_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
4597 	mpt3sas_config_get_iounit_pg8(ioc, &mpi_reply, &ioc->iounit_pg8);
4598 	_base_display_ioc_capabilities(ioc);
4599 
4600 	/*
4601 	 * Enable task_set_full handling in iounit_pg1 when the
4602 	 * facts capabilities indicate that its supported.
4603 	 */
4604 	iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
4605 	if ((ioc->facts.IOCCapabilities &
4606 	    MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING))
4607 		iounit_pg1_flags &=
4608 		    ~MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
4609 	else
4610 		iounit_pg1_flags |=
4611 		    MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
4612 	ioc->iounit_pg1.Flags = cpu_to_le32(iounit_pg1_flags);
4613 	mpt3sas_config_set_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
4614 
4615 	if (ioc->iounit_pg8.NumSensors)
4616 		ioc->temp_sensors_count = ioc->iounit_pg8.NumSensors;
4617 	if (ioc->is_aero_ioc)
4618 		_base_update_ioc_page1_inlinewith_perf_mode(ioc);
4619 }
4620 
4621 /**
4622  * mpt3sas_free_enclosure_list - release memory
4623  * @ioc: per adapter object
4624  *
4625  * Free memory allocated during encloure add.
4626  */
4627 void
4628 mpt3sas_free_enclosure_list(struct MPT3SAS_ADAPTER *ioc)
4629 {
4630 	struct _enclosure_node *enclosure_dev, *enclosure_dev_next;
4631 
4632 	/* Free enclosure list */
4633 	list_for_each_entry_safe(enclosure_dev,
4634 			enclosure_dev_next, &ioc->enclosure_list, list) {
4635 		list_del(&enclosure_dev->list);
4636 		kfree(enclosure_dev);
4637 	}
4638 }
4639 
4640 /**
4641  * _base_release_memory_pools - release memory
4642  * @ioc: per adapter object
4643  *
4644  * Free memory allocated from _base_allocate_memory_pools.
4645  */
4646 static void
4647 _base_release_memory_pools(struct MPT3SAS_ADAPTER *ioc)
4648 {
4649 	int i = 0;
4650 	int j = 0;
4651 	struct chain_tracker *ct;
4652 	struct reply_post_struct *rps;
4653 
4654 	dexitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
4655 
4656 	if (ioc->request) {
4657 		dma_free_coherent(&ioc->pdev->dev, ioc->request_dma_sz,
4658 		    ioc->request,  ioc->request_dma);
4659 		dexitprintk(ioc,
4660 			    ioc_info(ioc, "request_pool(0x%p): free\n",
4661 				     ioc->request));
4662 		ioc->request = NULL;
4663 	}
4664 
4665 	if (ioc->sense) {
4666 		dma_pool_free(ioc->sense_dma_pool, ioc->sense, ioc->sense_dma);
4667 		dma_pool_destroy(ioc->sense_dma_pool);
4668 		dexitprintk(ioc,
4669 			    ioc_info(ioc, "sense_pool(0x%p): free\n",
4670 				     ioc->sense));
4671 		ioc->sense = NULL;
4672 	}
4673 
4674 	if (ioc->reply) {
4675 		dma_pool_free(ioc->reply_dma_pool, ioc->reply, ioc->reply_dma);
4676 		dma_pool_destroy(ioc->reply_dma_pool);
4677 		dexitprintk(ioc,
4678 			    ioc_info(ioc, "reply_pool(0x%p): free\n",
4679 				     ioc->reply));
4680 		ioc->reply = NULL;
4681 	}
4682 
4683 	if (ioc->reply_free) {
4684 		dma_pool_free(ioc->reply_free_dma_pool, ioc->reply_free,
4685 		    ioc->reply_free_dma);
4686 		dma_pool_destroy(ioc->reply_free_dma_pool);
4687 		dexitprintk(ioc,
4688 			    ioc_info(ioc, "reply_free_pool(0x%p): free\n",
4689 				     ioc->reply_free));
4690 		ioc->reply_free = NULL;
4691 	}
4692 
4693 	if (ioc->reply_post) {
4694 		do {
4695 			rps = &ioc->reply_post[i];
4696 			if (rps->reply_post_free) {
4697 				dma_pool_free(
4698 				    ioc->reply_post_free_dma_pool,
4699 				    rps->reply_post_free,
4700 				    rps->reply_post_free_dma);
4701 				dexitprintk(ioc,
4702 					    ioc_info(ioc, "reply_post_free_pool(0x%p): free\n",
4703 						     rps->reply_post_free));
4704 				rps->reply_post_free = NULL;
4705 			}
4706 		} while (ioc->rdpq_array_enable &&
4707 			   (++i < ioc->reply_queue_count));
4708 		if (ioc->reply_post_free_array &&
4709 			ioc->rdpq_array_enable) {
4710 			dma_pool_free(ioc->reply_post_free_array_dma_pool,
4711 				ioc->reply_post_free_array,
4712 				ioc->reply_post_free_array_dma);
4713 			ioc->reply_post_free_array = NULL;
4714 		}
4715 		dma_pool_destroy(ioc->reply_post_free_array_dma_pool);
4716 		dma_pool_destroy(ioc->reply_post_free_dma_pool);
4717 		kfree(ioc->reply_post);
4718 	}
4719 
4720 	if (ioc->pcie_sgl_dma_pool) {
4721 		for (i = 0; i < ioc->scsiio_depth; i++) {
4722 			dma_pool_free(ioc->pcie_sgl_dma_pool,
4723 					ioc->pcie_sg_lookup[i].pcie_sgl,
4724 					ioc->pcie_sg_lookup[i].pcie_sgl_dma);
4725 		}
4726 		if (ioc->pcie_sgl_dma_pool)
4727 			dma_pool_destroy(ioc->pcie_sgl_dma_pool);
4728 	}
4729 
4730 	if (ioc->config_page) {
4731 		dexitprintk(ioc,
4732 			    ioc_info(ioc, "config_page(0x%p): free\n",
4733 				     ioc->config_page));
4734 		dma_free_coherent(&ioc->pdev->dev, ioc->config_page_sz,
4735 		    ioc->config_page, ioc->config_page_dma);
4736 	}
4737 
4738 	kfree(ioc->hpr_lookup);
4739 	kfree(ioc->internal_lookup);
4740 	if (ioc->chain_lookup) {
4741 		for (i = 0; i < ioc->scsiio_depth; i++) {
4742 			for (j = ioc->chains_per_prp_buffer;
4743 			    j < ioc->chains_needed_per_io; j++) {
4744 				ct = &ioc->chain_lookup[i].chains_per_smid[j];
4745 				if (ct && ct->chain_buffer)
4746 					dma_pool_free(ioc->chain_dma_pool,
4747 						ct->chain_buffer,
4748 						ct->chain_buffer_dma);
4749 			}
4750 			kfree(ioc->chain_lookup[i].chains_per_smid);
4751 		}
4752 		dma_pool_destroy(ioc->chain_dma_pool);
4753 		kfree(ioc->chain_lookup);
4754 		ioc->chain_lookup = NULL;
4755 	}
4756 }
4757 
4758 /**
4759  * is_MSB_are_same - checks whether all reply queues in a set are
4760  *	having same upper 32bits in their base memory address.
4761  * @reply_pool_start_address: Base address of a reply queue set
4762  * @pool_sz: Size of single Reply Descriptor Post Queues pool size
4763  *
4764  * Return: 1 if reply queues in a set have a same upper 32bits in their base
4765  * memory address, else 0.
4766  */
4767 
4768 static int
4769 is_MSB_are_same(long reply_pool_start_address, u32 pool_sz)
4770 {
4771 	long reply_pool_end_address;
4772 
4773 	reply_pool_end_address = reply_pool_start_address + pool_sz;
4774 
4775 	if (upper_32_bits(reply_pool_start_address) ==
4776 		upper_32_bits(reply_pool_end_address))
4777 		return 1;
4778 	else
4779 		return 0;
4780 }
4781 
4782 /**
4783  * _base_allocate_memory_pools - allocate start of day memory pools
4784  * @ioc: per adapter object
4785  *
4786  * Return: 0 success, anything else error.
4787  */
4788 static int
4789 _base_allocate_memory_pools(struct MPT3SAS_ADAPTER *ioc)
4790 {
4791 	struct mpt3sas_facts *facts;
4792 	u16 max_sge_elements;
4793 	u16 chains_needed_per_io;
4794 	u32 sz, total_sz, reply_post_free_sz, reply_post_free_array_sz;
4795 	u32 retry_sz;
4796 	u16 max_request_credit, nvme_blocks_needed;
4797 	unsigned short sg_tablesize;
4798 	u16 sge_size;
4799 	int i, j;
4800 	struct chain_tracker *ct;
4801 
4802 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
4803 
4804 
4805 	retry_sz = 0;
4806 	facts = &ioc->facts;
4807 
4808 	/* command line tunables for max sgl entries */
4809 	if (max_sgl_entries != -1)
4810 		sg_tablesize = max_sgl_entries;
4811 	else {
4812 		if (ioc->hba_mpi_version_belonged == MPI2_VERSION)
4813 			sg_tablesize = MPT2SAS_SG_DEPTH;
4814 		else
4815 			sg_tablesize = MPT3SAS_SG_DEPTH;
4816 	}
4817 
4818 	/* max sgl entries <= MPT_KDUMP_MIN_PHYS_SEGMENTS in KDUMP mode */
4819 	if (reset_devices)
4820 		sg_tablesize = min_t(unsigned short, sg_tablesize,
4821 		   MPT_KDUMP_MIN_PHYS_SEGMENTS);
4822 
4823 	if (ioc->is_mcpu_endpoint)
4824 		ioc->shost->sg_tablesize = MPT_MIN_PHYS_SEGMENTS;
4825 	else {
4826 		if (sg_tablesize < MPT_MIN_PHYS_SEGMENTS)
4827 			sg_tablesize = MPT_MIN_PHYS_SEGMENTS;
4828 		else if (sg_tablesize > MPT_MAX_PHYS_SEGMENTS) {
4829 			sg_tablesize = min_t(unsigned short, sg_tablesize,
4830 					SG_MAX_SEGMENTS);
4831 			ioc_warn(ioc, "sg_tablesize(%u) is bigger than kernel defined SG_CHUNK_SIZE(%u)\n",
4832 				 sg_tablesize, MPT_MAX_PHYS_SEGMENTS);
4833 		}
4834 		ioc->shost->sg_tablesize = sg_tablesize;
4835 	}
4836 
4837 	ioc->internal_depth = min_t(int, (facts->HighPriorityCredit + (5)),
4838 		(facts->RequestCredit / 4));
4839 	if (ioc->internal_depth < INTERNAL_CMDS_COUNT) {
4840 		if (facts->RequestCredit <= (INTERNAL_CMDS_COUNT +
4841 				INTERNAL_SCSIIO_CMDS_COUNT)) {
4842 			ioc_err(ioc, "IOC doesn't have enough Request Credits, it has just %d number of credits\n",
4843 				facts->RequestCredit);
4844 			return -ENOMEM;
4845 		}
4846 		ioc->internal_depth = 10;
4847 	}
4848 
4849 	ioc->hi_priority_depth = ioc->internal_depth - (5);
4850 	/* command line tunables  for max controller queue depth */
4851 	if (max_queue_depth != -1 && max_queue_depth != 0) {
4852 		max_request_credit = min_t(u16, max_queue_depth +
4853 			ioc->internal_depth, facts->RequestCredit);
4854 		if (max_request_credit > MAX_HBA_QUEUE_DEPTH)
4855 			max_request_credit =  MAX_HBA_QUEUE_DEPTH;
4856 	} else if (reset_devices)
4857 		max_request_credit = min_t(u16, facts->RequestCredit,
4858 		    (MPT3SAS_KDUMP_SCSI_IO_DEPTH + ioc->internal_depth));
4859 	else
4860 		max_request_credit = min_t(u16, facts->RequestCredit,
4861 		    MAX_HBA_QUEUE_DEPTH);
4862 
4863 	/* Firmware maintains additional facts->HighPriorityCredit number of
4864 	 * credits for HiPriprity Request messages, so hba queue depth will be
4865 	 * sum of max_request_credit and high priority queue depth.
4866 	 */
4867 	ioc->hba_queue_depth = max_request_credit + ioc->hi_priority_depth;
4868 
4869 	/* request frame size */
4870 	ioc->request_sz = facts->IOCRequestFrameSize * 4;
4871 
4872 	/* reply frame size */
4873 	ioc->reply_sz = facts->ReplyFrameSize * 4;
4874 
4875 	/* chain segment size */
4876 	if (ioc->hba_mpi_version_belonged != MPI2_VERSION) {
4877 		if (facts->IOCMaxChainSegmentSize)
4878 			ioc->chain_segment_sz =
4879 					facts->IOCMaxChainSegmentSize *
4880 					MAX_CHAIN_ELEMT_SZ;
4881 		else
4882 		/* set to 128 bytes size if IOCMaxChainSegmentSize is zero */
4883 			ioc->chain_segment_sz = DEFAULT_NUM_FWCHAIN_ELEMTS *
4884 						    MAX_CHAIN_ELEMT_SZ;
4885 	} else
4886 		ioc->chain_segment_sz = ioc->request_sz;
4887 
4888 	/* calculate the max scatter element size */
4889 	sge_size = max_t(u16, ioc->sge_size, ioc->sge_size_ieee);
4890 
4891  retry_allocation:
4892 	total_sz = 0;
4893 	/* calculate number of sg elements left over in the 1st frame */
4894 	max_sge_elements = ioc->request_sz - ((sizeof(Mpi2SCSIIORequest_t) -
4895 	    sizeof(Mpi2SGEIOUnion_t)) + sge_size);
4896 	ioc->max_sges_in_main_message = max_sge_elements/sge_size;
4897 
4898 	/* now do the same for a chain buffer */
4899 	max_sge_elements = ioc->chain_segment_sz - sge_size;
4900 	ioc->max_sges_in_chain_message = max_sge_elements/sge_size;
4901 
4902 	/*
4903 	 *  MPT3SAS_SG_DEPTH = CONFIG_FUSION_MAX_SGE
4904 	 */
4905 	chains_needed_per_io = ((ioc->shost->sg_tablesize -
4906 	   ioc->max_sges_in_main_message)/ioc->max_sges_in_chain_message)
4907 	    + 1;
4908 	if (chains_needed_per_io > facts->MaxChainDepth) {
4909 		chains_needed_per_io = facts->MaxChainDepth;
4910 		ioc->shost->sg_tablesize = min_t(u16,
4911 		ioc->max_sges_in_main_message + (ioc->max_sges_in_chain_message
4912 		* chains_needed_per_io), ioc->shost->sg_tablesize);
4913 	}
4914 	ioc->chains_needed_per_io = chains_needed_per_io;
4915 
4916 	/* reply free queue sizing - taking into account for 64 FW events */
4917 	ioc->reply_free_queue_depth = ioc->hba_queue_depth + 64;
4918 
4919 	/* mCPU manage single counters for simplicity */
4920 	if (ioc->is_mcpu_endpoint)
4921 		ioc->reply_post_queue_depth = ioc->reply_free_queue_depth;
4922 	else {
4923 		/* calculate reply descriptor post queue depth */
4924 		ioc->reply_post_queue_depth = ioc->hba_queue_depth +
4925 			ioc->reply_free_queue_depth +  1;
4926 		/* align the reply post queue on the next 16 count boundary */
4927 		if (ioc->reply_post_queue_depth % 16)
4928 			ioc->reply_post_queue_depth += 16 -
4929 				(ioc->reply_post_queue_depth % 16);
4930 	}
4931 
4932 	if (ioc->reply_post_queue_depth >
4933 	    facts->MaxReplyDescriptorPostQueueDepth) {
4934 		ioc->reply_post_queue_depth =
4935 				facts->MaxReplyDescriptorPostQueueDepth -
4936 		    (facts->MaxReplyDescriptorPostQueueDepth % 16);
4937 		ioc->hba_queue_depth =
4938 				((ioc->reply_post_queue_depth - 64) / 2) - 1;
4939 		ioc->reply_free_queue_depth = ioc->hba_queue_depth + 64;
4940 	}
4941 
4942 	dinitprintk(ioc,
4943 		    ioc_info(ioc, "scatter gather: sge_in_main_msg(%d), sge_per_chain(%d), sge_per_io(%d), chains_per_io(%d)\n",
4944 			     ioc->max_sges_in_main_message,
4945 			     ioc->max_sges_in_chain_message,
4946 			     ioc->shost->sg_tablesize,
4947 			     ioc->chains_needed_per_io));
4948 
4949 	/* reply post queue, 16 byte align */
4950 	reply_post_free_sz = ioc->reply_post_queue_depth *
4951 	    sizeof(Mpi2DefaultReplyDescriptor_t);
4952 
4953 	sz = reply_post_free_sz;
4954 	if (_base_is_controller_msix_enabled(ioc) && !ioc->rdpq_array_enable)
4955 		sz *= ioc->reply_queue_count;
4956 
4957 	ioc->reply_post = kcalloc((ioc->rdpq_array_enable) ?
4958 	    (ioc->reply_queue_count):1,
4959 	    sizeof(struct reply_post_struct), GFP_KERNEL);
4960 
4961 	if (!ioc->reply_post) {
4962 		ioc_err(ioc, "reply_post_free pool: kcalloc failed\n");
4963 		goto out;
4964 	}
4965 	ioc->reply_post_free_dma_pool = dma_pool_create("reply_post_free pool",
4966 	    &ioc->pdev->dev, sz, 16, 0);
4967 	if (!ioc->reply_post_free_dma_pool) {
4968 		ioc_err(ioc, "reply_post_free pool: dma_pool_create failed\n");
4969 		goto out;
4970 	}
4971 	i = 0;
4972 	do {
4973 		ioc->reply_post[i].reply_post_free =
4974 		    dma_pool_zalloc(ioc->reply_post_free_dma_pool,
4975 		    GFP_KERNEL,
4976 		    &ioc->reply_post[i].reply_post_free_dma);
4977 		if (!ioc->reply_post[i].reply_post_free) {
4978 			ioc_err(ioc, "reply_post_free pool: dma_pool_alloc failed\n");
4979 			goto out;
4980 		}
4981 		dinitprintk(ioc,
4982 			    ioc_info(ioc, "reply post free pool (0x%p): depth(%d), element_size(%d), pool_size(%d kB)\n",
4983 				     ioc->reply_post[i].reply_post_free,
4984 				     ioc->reply_post_queue_depth,
4985 				     8, sz / 1024));
4986 		dinitprintk(ioc,
4987 			    ioc_info(ioc, "reply_post_free_dma = (0x%llx)\n",
4988 				     (u64)ioc->reply_post[i].reply_post_free_dma));
4989 		total_sz += sz;
4990 	} while (ioc->rdpq_array_enable && (++i < ioc->reply_queue_count));
4991 
4992 	if (ioc->dma_mask == 64) {
4993 		if (_base_change_consistent_dma_mask(ioc, ioc->pdev) != 0) {
4994 			ioc_warn(ioc, "no suitable consistent DMA mask for %s\n",
4995 				 pci_name(ioc->pdev));
4996 			goto out;
4997 		}
4998 	}
4999 
5000 	ioc->scsiio_depth = ioc->hba_queue_depth -
5001 	    ioc->hi_priority_depth - ioc->internal_depth;
5002 
5003 	/* set the scsi host can_queue depth
5004 	 * with some internal commands that could be outstanding
5005 	 */
5006 	ioc->shost->can_queue = ioc->scsiio_depth - INTERNAL_SCSIIO_CMDS_COUNT;
5007 	dinitprintk(ioc,
5008 		    ioc_info(ioc, "scsi host: can_queue depth (%d)\n",
5009 			     ioc->shost->can_queue));
5010 
5011 
5012 	/* contiguous pool for request and chains, 16 byte align, one extra "
5013 	 * "frame for smid=0
5014 	 */
5015 	ioc->chain_depth = ioc->chains_needed_per_io * ioc->scsiio_depth;
5016 	sz = ((ioc->scsiio_depth + 1) * ioc->request_sz);
5017 
5018 	/* hi-priority queue */
5019 	sz += (ioc->hi_priority_depth * ioc->request_sz);
5020 
5021 	/* internal queue */
5022 	sz += (ioc->internal_depth * ioc->request_sz);
5023 
5024 	ioc->request_dma_sz = sz;
5025 	ioc->request = dma_alloc_coherent(&ioc->pdev->dev, sz,
5026 			&ioc->request_dma, GFP_KERNEL);
5027 	if (!ioc->request) {
5028 		ioc_err(ioc, "request pool: dma_alloc_coherent failed: hba_depth(%d), chains_per_io(%d), frame_sz(%d), total(%d kB)\n",
5029 			ioc->hba_queue_depth, ioc->chains_needed_per_io,
5030 			ioc->request_sz, sz / 1024);
5031 		if (ioc->scsiio_depth < MPT3SAS_SAS_QUEUE_DEPTH)
5032 			goto out;
5033 		retry_sz = 64;
5034 		ioc->hba_queue_depth -= retry_sz;
5035 		_base_release_memory_pools(ioc);
5036 		goto retry_allocation;
5037 	}
5038 
5039 	if (retry_sz)
5040 		ioc_err(ioc, "request pool: dma_alloc_coherent succeed: hba_depth(%d), chains_per_io(%d), frame_sz(%d), total(%d kb)\n",
5041 			ioc->hba_queue_depth, ioc->chains_needed_per_io,
5042 			ioc->request_sz, sz / 1024);
5043 
5044 	/* hi-priority queue */
5045 	ioc->hi_priority = ioc->request + ((ioc->scsiio_depth + 1) *
5046 	    ioc->request_sz);
5047 	ioc->hi_priority_dma = ioc->request_dma + ((ioc->scsiio_depth + 1) *
5048 	    ioc->request_sz);
5049 
5050 	/* internal queue */
5051 	ioc->internal = ioc->hi_priority + (ioc->hi_priority_depth *
5052 	    ioc->request_sz);
5053 	ioc->internal_dma = ioc->hi_priority_dma + (ioc->hi_priority_depth *
5054 	    ioc->request_sz);
5055 
5056 	dinitprintk(ioc,
5057 		    ioc_info(ioc, "request pool(0x%p): depth(%d), frame_size(%d), pool_size(%d kB)\n",
5058 			     ioc->request, ioc->hba_queue_depth,
5059 			     ioc->request_sz,
5060 			     (ioc->hba_queue_depth * ioc->request_sz) / 1024));
5061 
5062 	dinitprintk(ioc,
5063 		    ioc_info(ioc, "request pool: dma(0x%llx)\n",
5064 			     (unsigned long long)ioc->request_dma));
5065 	total_sz += sz;
5066 
5067 	dinitprintk(ioc,
5068 		    ioc_info(ioc, "scsiio(0x%p): depth(%d)\n",
5069 			     ioc->request, ioc->scsiio_depth));
5070 
5071 	ioc->chain_depth = min_t(u32, ioc->chain_depth, MAX_CHAIN_DEPTH);
5072 	sz = ioc->scsiio_depth * sizeof(struct chain_lookup);
5073 	ioc->chain_lookup = kzalloc(sz, GFP_KERNEL);
5074 	if (!ioc->chain_lookup) {
5075 		ioc_err(ioc, "chain_lookup: __get_free_pages failed\n");
5076 		goto out;
5077 	}
5078 
5079 	sz = ioc->chains_needed_per_io * sizeof(struct chain_tracker);
5080 	for (i = 0; i < ioc->scsiio_depth; i++) {
5081 		ioc->chain_lookup[i].chains_per_smid = kzalloc(sz, GFP_KERNEL);
5082 		if (!ioc->chain_lookup[i].chains_per_smid) {
5083 			ioc_err(ioc, "chain_lookup: kzalloc failed\n");
5084 			goto out;
5085 		}
5086 	}
5087 
5088 	/* initialize hi-priority queue smid's */
5089 	ioc->hpr_lookup = kcalloc(ioc->hi_priority_depth,
5090 	    sizeof(struct request_tracker), GFP_KERNEL);
5091 	if (!ioc->hpr_lookup) {
5092 		ioc_err(ioc, "hpr_lookup: kcalloc failed\n");
5093 		goto out;
5094 	}
5095 	ioc->hi_priority_smid = ioc->scsiio_depth + 1;
5096 	dinitprintk(ioc,
5097 		    ioc_info(ioc, "hi_priority(0x%p): depth(%d), start smid(%d)\n",
5098 			     ioc->hi_priority,
5099 			     ioc->hi_priority_depth, ioc->hi_priority_smid));
5100 
5101 	/* initialize internal queue smid's */
5102 	ioc->internal_lookup = kcalloc(ioc->internal_depth,
5103 	    sizeof(struct request_tracker), GFP_KERNEL);
5104 	if (!ioc->internal_lookup) {
5105 		ioc_err(ioc, "internal_lookup: kcalloc failed\n");
5106 		goto out;
5107 	}
5108 	ioc->internal_smid = ioc->hi_priority_smid + ioc->hi_priority_depth;
5109 	dinitprintk(ioc,
5110 		    ioc_info(ioc, "internal(0x%p): depth(%d), start smid(%d)\n",
5111 			     ioc->internal,
5112 			     ioc->internal_depth, ioc->internal_smid));
5113 	/*
5114 	 * The number of NVMe page sized blocks needed is:
5115 	 *     (((sg_tablesize * 8) - 1) / (page_size - 8)) + 1
5116 	 * ((sg_tablesize * 8) - 1) is the max PRP's minus the first PRP entry
5117 	 * that is placed in the main message frame.  8 is the size of each PRP
5118 	 * entry or PRP list pointer entry.  8 is subtracted from page_size
5119 	 * because of the PRP list pointer entry at the end of a page, so this
5120 	 * is not counted as a PRP entry.  The 1 added page is a round up.
5121 	 *
5122 	 * To avoid allocation failures due to the amount of memory that could
5123 	 * be required for NVMe PRP's, only each set of NVMe blocks will be
5124 	 * contiguous, so a new set is allocated for each possible I/O.
5125 	 */
5126 	ioc->chains_per_prp_buffer = 0;
5127 	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_NVME_DEVICES) {
5128 		nvme_blocks_needed =
5129 			(ioc->shost->sg_tablesize * NVME_PRP_SIZE) - 1;
5130 		nvme_blocks_needed /= (ioc->page_size - NVME_PRP_SIZE);
5131 		nvme_blocks_needed++;
5132 
5133 		sz = sizeof(struct pcie_sg_list) * ioc->scsiio_depth;
5134 		ioc->pcie_sg_lookup = kzalloc(sz, GFP_KERNEL);
5135 		if (!ioc->pcie_sg_lookup) {
5136 			ioc_info(ioc, "PCIe SGL lookup: kzalloc failed\n");
5137 			goto out;
5138 		}
5139 		sz = nvme_blocks_needed * ioc->page_size;
5140 		ioc->pcie_sgl_dma_pool =
5141 			dma_pool_create("PCIe SGL pool", &ioc->pdev->dev, sz, 16, 0);
5142 		if (!ioc->pcie_sgl_dma_pool) {
5143 			ioc_info(ioc, "PCIe SGL pool: dma_pool_create failed\n");
5144 			goto out;
5145 		}
5146 
5147 		ioc->chains_per_prp_buffer = sz/ioc->chain_segment_sz;
5148 		ioc->chains_per_prp_buffer = min(ioc->chains_per_prp_buffer,
5149 						ioc->chains_needed_per_io);
5150 
5151 		for (i = 0; i < ioc->scsiio_depth; i++) {
5152 			ioc->pcie_sg_lookup[i].pcie_sgl = dma_pool_alloc(
5153 				ioc->pcie_sgl_dma_pool, GFP_KERNEL,
5154 				&ioc->pcie_sg_lookup[i].pcie_sgl_dma);
5155 			if (!ioc->pcie_sg_lookup[i].pcie_sgl) {
5156 				ioc_info(ioc, "PCIe SGL pool: dma_pool_alloc failed\n");
5157 				goto out;
5158 			}
5159 			for (j = 0; j < ioc->chains_per_prp_buffer; j++) {
5160 				ct = &ioc->chain_lookup[i].chains_per_smid[j];
5161 				ct->chain_buffer =
5162 				    ioc->pcie_sg_lookup[i].pcie_sgl +
5163 				    (j * ioc->chain_segment_sz);
5164 				ct->chain_buffer_dma =
5165 				    ioc->pcie_sg_lookup[i].pcie_sgl_dma +
5166 				    (j * ioc->chain_segment_sz);
5167 			}
5168 		}
5169 
5170 		dinitprintk(ioc,
5171 			    ioc_info(ioc, "PCIe sgl pool depth(%d), element_size(%d), pool_size(%d kB)\n",
5172 				     ioc->scsiio_depth, sz,
5173 				     (sz * ioc->scsiio_depth) / 1024));
5174 		dinitprintk(ioc,
5175 			    ioc_info(ioc, "Number of chains can fit in a PRP page(%d)\n",
5176 				     ioc->chains_per_prp_buffer));
5177 		total_sz += sz * ioc->scsiio_depth;
5178 	}
5179 
5180 	ioc->chain_dma_pool = dma_pool_create("chain pool", &ioc->pdev->dev,
5181 	    ioc->chain_segment_sz, 16, 0);
5182 	if (!ioc->chain_dma_pool) {
5183 		ioc_err(ioc, "chain_dma_pool: dma_pool_create failed\n");
5184 		goto out;
5185 	}
5186 	for (i = 0; i < ioc->scsiio_depth; i++) {
5187 		for (j = ioc->chains_per_prp_buffer;
5188 				j < ioc->chains_needed_per_io; j++) {
5189 			ct = &ioc->chain_lookup[i].chains_per_smid[j];
5190 			ct->chain_buffer = dma_pool_alloc(
5191 					ioc->chain_dma_pool, GFP_KERNEL,
5192 					&ct->chain_buffer_dma);
5193 			if (!ct->chain_buffer) {
5194 				ioc_err(ioc, "chain_lookup: pci_pool_alloc failed\n");
5195 				_base_release_memory_pools(ioc);
5196 				goto out;
5197 			}
5198 		}
5199 		total_sz += ioc->chain_segment_sz;
5200 	}
5201 
5202 	dinitprintk(ioc,
5203 		    ioc_info(ioc, "chain pool depth(%d), frame_size(%d), pool_size(%d kB)\n",
5204 			     ioc->chain_depth, ioc->chain_segment_sz,
5205 			     (ioc->chain_depth * ioc->chain_segment_sz) / 1024));
5206 
5207 	/* sense buffers, 4 byte align */
5208 	sz = ioc->scsiio_depth * SCSI_SENSE_BUFFERSIZE;
5209 	ioc->sense_dma_pool = dma_pool_create("sense pool", &ioc->pdev->dev, sz,
5210 					      4, 0);
5211 	if (!ioc->sense_dma_pool) {
5212 		ioc_err(ioc, "sense pool: dma_pool_create failed\n");
5213 		goto out;
5214 	}
5215 	ioc->sense = dma_pool_alloc(ioc->sense_dma_pool, GFP_KERNEL,
5216 	    &ioc->sense_dma);
5217 	if (!ioc->sense) {
5218 		ioc_err(ioc, "sense pool: dma_pool_alloc failed\n");
5219 		goto out;
5220 	}
5221 	/* sense buffer requires to be in same 4 gb region.
5222 	 * Below function will check the same.
5223 	 * In case of failure, new pci pool will be created with updated
5224 	 * alignment. Older allocation and pool will be destroyed.
5225 	 * Alignment will be used such a way that next allocation if
5226 	 * success, will always meet same 4gb region requirement.
5227 	 * Actual requirement is not alignment, but we need start and end of
5228 	 * DMA address must have same upper 32 bit address.
5229 	 */
5230 	if (!is_MSB_are_same((long)ioc->sense, sz)) {
5231 		//Release Sense pool & Reallocate
5232 		dma_pool_free(ioc->sense_dma_pool, ioc->sense, ioc->sense_dma);
5233 		dma_pool_destroy(ioc->sense_dma_pool);
5234 		ioc->sense = NULL;
5235 
5236 		ioc->sense_dma_pool =
5237 			dma_pool_create("sense pool", &ioc->pdev->dev, sz,
5238 						roundup_pow_of_two(sz), 0);
5239 		if (!ioc->sense_dma_pool) {
5240 			ioc_err(ioc, "sense pool: pci_pool_create failed\n");
5241 			goto out;
5242 		}
5243 		ioc->sense = dma_pool_alloc(ioc->sense_dma_pool, GFP_KERNEL,
5244 				&ioc->sense_dma);
5245 		if (!ioc->sense) {
5246 			ioc_err(ioc, "sense pool: pci_pool_alloc failed\n");
5247 			goto out;
5248 		}
5249 	}
5250 	dinitprintk(ioc,
5251 		    ioc_info(ioc, "sense pool(0x%p): depth(%d), element_size(%d), pool_size(%d kB)\n",
5252 			     ioc->sense, ioc->scsiio_depth,
5253 			     SCSI_SENSE_BUFFERSIZE, sz / 1024));
5254 	dinitprintk(ioc,
5255 		    ioc_info(ioc, "sense_dma(0x%llx)\n",
5256 			     (unsigned long long)ioc->sense_dma));
5257 	total_sz += sz;
5258 
5259 	/* reply pool, 4 byte align */
5260 	sz = ioc->reply_free_queue_depth * ioc->reply_sz;
5261 	ioc->reply_dma_pool = dma_pool_create("reply pool", &ioc->pdev->dev, sz,
5262 					      4, 0);
5263 	if (!ioc->reply_dma_pool) {
5264 		ioc_err(ioc, "reply pool: dma_pool_create failed\n");
5265 		goto out;
5266 	}
5267 	ioc->reply = dma_pool_alloc(ioc->reply_dma_pool, GFP_KERNEL,
5268 	    &ioc->reply_dma);
5269 	if (!ioc->reply) {
5270 		ioc_err(ioc, "reply pool: dma_pool_alloc failed\n");
5271 		goto out;
5272 	}
5273 	ioc->reply_dma_min_address = (u32)(ioc->reply_dma);
5274 	ioc->reply_dma_max_address = (u32)(ioc->reply_dma) + sz;
5275 	dinitprintk(ioc,
5276 		    ioc_info(ioc, "reply pool(0x%p): depth(%d), frame_size(%d), pool_size(%d kB)\n",
5277 			     ioc->reply, ioc->reply_free_queue_depth,
5278 			     ioc->reply_sz, sz / 1024));
5279 	dinitprintk(ioc,
5280 		    ioc_info(ioc, "reply_dma(0x%llx)\n",
5281 			     (unsigned long long)ioc->reply_dma));
5282 	total_sz += sz;
5283 
5284 	/* reply free queue, 16 byte align */
5285 	sz = ioc->reply_free_queue_depth * 4;
5286 	ioc->reply_free_dma_pool = dma_pool_create("reply_free pool",
5287 	    &ioc->pdev->dev, sz, 16, 0);
5288 	if (!ioc->reply_free_dma_pool) {
5289 		ioc_err(ioc, "reply_free pool: dma_pool_create failed\n");
5290 		goto out;
5291 	}
5292 	ioc->reply_free = dma_pool_zalloc(ioc->reply_free_dma_pool, GFP_KERNEL,
5293 	    &ioc->reply_free_dma);
5294 	if (!ioc->reply_free) {
5295 		ioc_err(ioc, "reply_free pool: dma_pool_alloc failed\n");
5296 		goto out;
5297 	}
5298 	dinitprintk(ioc,
5299 		    ioc_info(ioc, "reply_free pool(0x%p): depth(%d), element_size(%d), pool_size(%d kB)\n",
5300 			     ioc->reply_free, ioc->reply_free_queue_depth,
5301 			     4, sz / 1024));
5302 	dinitprintk(ioc,
5303 		    ioc_info(ioc, "reply_free_dma (0x%llx)\n",
5304 			     (unsigned long long)ioc->reply_free_dma));
5305 	total_sz += sz;
5306 
5307 	if (ioc->rdpq_array_enable) {
5308 		reply_post_free_array_sz = ioc->reply_queue_count *
5309 		    sizeof(Mpi2IOCInitRDPQArrayEntry);
5310 		ioc->reply_post_free_array_dma_pool =
5311 		    dma_pool_create("reply_post_free_array pool",
5312 		    &ioc->pdev->dev, reply_post_free_array_sz, 16, 0);
5313 		if (!ioc->reply_post_free_array_dma_pool) {
5314 			dinitprintk(ioc,
5315 				    ioc_info(ioc, "reply_post_free_array pool: dma_pool_create failed\n"));
5316 			goto out;
5317 		}
5318 		ioc->reply_post_free_array =
5319 		    dma_pool_alloc(ioc->reply_post_free_array_dma_pool,
5320 		    GFP_KERNEL, &ioc->reply_post_free_array_dma);
5321 		if (!ioc->reply_post_free_array) {
5322 			dinitprintk(ioc,
5323 				    ioc_info(ioc, "reply_post_free_array pool: dma_pool_alloc failed\n"));
5324 			goto out;
5325 		}
5326 	}
5327 	ioc->config_page_sz = 512;
5328 	ioc->config_page = dma_alloc_coherent(&ioc->pdev->dev,
5329 			ioc->config_page_sz, &ioc->config_page_dma, GFP_KERNEL);
5330 	if (!ioc->config_page) {
5331 		ioc_err(ioc, "config page: dma_pool_alloc failed\n");
5332 		goto out;
5333 	}
5334 	dinitprintk(ioc,
5335 		    ioc_info(ioc, "config page(0x%p): size(%d)\n",
5336 			     ioc->config_page, ioc->config_page_sz));
5337 	dinitprintk(ioc,
5338 		    ioc_info(ioc, "config_page_dma(0x%llx)\n",
5339 			     (unsigned long long)ioc->config_page_dma));
5340 	total_sz += ioc->config_page_sz;
5341 
5342 	ioc_info(ioc, "Allocated physical memory: size(%d kB)\n",
5343 		 total_sz / 1024);
5344 	ioc_info(ioc, "Current Controller Queue Depth(%d),Max Controller Queue Depth(%d)\n",
5345 		 ioc->shost->can_queue, facts->RequestCredit);
5346 	ioc_info(ioc, "Scatter Gather Elements per IO(%d)\n",
5347 		 ioc->shost->sg_tablesize);
5348 	return 0;
5349 
5350  out:
5351 	return -ENOMEM;
5352 }
5353 
5354 /**
5355  * mpt3sas_base_get_iocstate - Get the current state of a MPT adapter.
5356  * @ioc: Pointer to MPT_ADAPTER structure
5357  * @cooked: Request raw or cooked IOC state
5358  *
5359  * Return: all IOC Doorbell register bits if cooked==0, else just the
5360  * Doorbell bits in MPI_IOC_STATE_MASK.
5361  */
5362 u32
5363 mpt3sas_base_get_iocstate(struct MPT3SAS_ADAPTER *ioc, int cooked)
5364 {
5365 	u32 s, sc;
5366 
5367 	s = ioc->base_readl(&ioc->chip->Doorbell);
5368 	sc = s & MPI2_IOC_STATE_MASK;
5369 	return cooked ? sc : s;
5370 }
5371 
5372 /**
5373  * _base_wait_on_iocstate - waiting on a particular ioc state
5374  * @ioc: ?
5375  * @ioc_state: controller state { READY, OPERATIONAL, or RESET }
5376  * @timeout: timeout in second
5377  *
5378  * Return: 0 for success, non-zero for failure.
5379  */
5380 static int
5381 _base_wait_on_iocstate(struct MPT3SAS_ADAPTER *ioc, u32 ioc_state, int timeout)
5382 {
5383 	u32 count, cntdn;
5384 	u32 current_state;
5385 
5386 	count = 0;
5387 	cntdn = 1000 * timeout;
5388 	do {
5389 		current_state = mpt3sas_base_get_iocstate(ioc, 1);
5390 		if (current_state == ioc_state)
5391 			return 0;
5392 		if (count && current_state == MPI2_IOC_STATE_FAULT)
5393 			break;
5394 
5395 		usleep_range(1000, 1500);
5396 		count++;
5397 	} while (--cntdn);
5398 
5399 	return current_state;
5400 }
5401 
5402 /**
5403  * _base_wait_for_doorbell_int - waiting for controller interrupt(generated by
5404  * a write to the doorbell)
5405  * @ioc: per adapter object
5406  *
5407  * Return: 0 for success, non-zero for failure.
5408  *
5409  * Notes: MPI2_HIS_IOC2SYS_DB_STATUS - set to one when IOC writes to doorbell.
5410  */
5411 static int
5412 _base_diag_reset(struct MPT3SAS_ADAPTER *ioc);
5413 
5414 static int
5415 _base_wait_for_doorbell_int(struct MPT3SAS_ADAPTER *ioc, int timeout)
5416 {
5417 	u32 cntdn, count;
5418 	u32 int_status;
5419 
5420 	count = 0;
5421 	cntdn = 1000 * timeout;
5422 	do {
5423 		int_status = ioc->base_readl(&ioc->chip->HostInterruptStatus);
5424 		if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
5425 			dhsprintk(ioc,
5426 				  ioc_info(ioc, "%s: successful count(%d), timeout(%d)\n",
5427 					   __func__, count, timeout));
5428 			return 0;
5429 		}
5430 
5431 		usleep_range(1000, 1500);
5432 		count++;
5433 	} while (--cntdn);
5434 
5435 	ioc_err(ioc, "%s: failed due to timeout count(%d), int_status(%x)!\n",
5436 		__func__, count, int_status);
5437 	return -EFAULT;
5438 }
5439 
5440 static int
5441 _base_spin_on_doorbell_int(struct MPT3SAS_ADAPTER *ioc, int timeout)
5442 {
5443 	u32 cntdn, count;
5444 	u32 int_status;
5445 
5446 	count = 0;
5447 	cntdn = 2000 * timeout;
5448 	do {
5449 		int_status = ioc->base_readl(&ioc->chip->HostInterruptStatus);
5450 		if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
5451 			dhsprintk(ioc,
5452 				  ioc_info(ioc, "%s: successful count(%d), timeout(%d)\n",
5453 					   __func__, count, timeout));
5454 			return 0;
5455 		}
5456 
5457 		udelay(500);
5458 		count++;
5459 	} while (--cntdn);
5460 
5461 	ioc_err(ioc, "%s: failed due to timeout count(%d), int_status(%x)!\n",
5462 		__func__, count, int_status);
5463 	return -EFAULT;
5464 
5465 }
5466 
5467 /**
5468  * _base_wait_for_doorbell_ack - waiting for controller to read the doorbell.
5469  * @ioc: per adapter object
5470  * @timeout: timeout in second
5471  *
5472  * Return: 0 for success, non-zero for failure.
5473  *
5474  * Notes: MPI2_HIS_SYS2IOC_DB_STATUS - set to one when host writes to
5475  * doorbell.
5476  */
5477 static int
5478 _base_wait_for_doorbell_ack(struct MPT3SAS_ADAPTER *ioc, int timeout)
5479 {
5480 	u32 cntdn, count;
5481 	u32 int_status;
5482 	u32 doorbell;
5483 
5484 	count = 0;
5485 	cntdn = 1000 * timeout;
5486 	do {
5487 		int_status = ioc->base_readl(&ioc->chip->HostInterruptStatus);
5488 		if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
5489 			dhsprintk(ioc,
5490 				  ioc_info(ioc, "%s: successful count(%d), timeout(%d)\n",
5491 					   __func__, count, timeout));
5492 			return 0;
5493 		} else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
5494 			doorbell = ioc->base_readl(&ioc->chip->Doorbell);
5495 			if ((doorbell & MPI2_IOC_STATE_MASK) ==
5496 			    MPI2_IOC_STATE_FAULT) {
5497 				mpt3sas_base_fault_info(ioc , doorbell);
5498 				return -EFAULT;
5499 			}
5500 		} else if (int_status == 0xFFFFFFFF)
5501 			goto out;
5502 
5503 		usleep_range(1000, 1500);
5504 		count++;
5505 	} while (--cntdn);
5506 
5507  out:
5508 	ioc_err(ioc, "%s: failed due to timeout count(%d), int_status(%x)!\n",
5509 		__func__, count, int_status);
5510 	return -EFAULT;
5511 }
5512 
5513 /**
5514  * _base_wait_for_doorbell_not_used - waiting for doorbell to not be in use
5515  * @ioc: per adapter object
5516  * @timeout: timeout in second
5517  *
5518  * Return: 0 for success, non-zero for failure.
5519  */
5520 static int
5521 _base_wait_for_doorbell_not_used(struct MPT3SAS_ADAPTER *ioc, int timeout)
5522 {
5523 	u32 cntdn, count;
5524 	u32 doorbell_reg;
5525 
5526 	count = 0;
5527 	cntdn = 1000 * timeout;
5528 	do {
5529 		doorbell_reg = ioc->base_readl(&ioc->chip->Doorbell);
5530 		if (!(doorbell_reg & MPI2_DOORBELL_USED)) {
5531 			dhsprintk(ioc,
5532 				  ioc_info(ioc, "%s: successful count(%d), timeout(%d)\n",
5533 					   __func__, count, timeout));
5534 			return 0;
5535 		}
5536 
5537 		usleep_range(1000, 1500);
5538 		count++;
5539 	} while (--cntdn);
5540 
5541 	ioc_err(ioc, "%s: failed due to timeout count(%d), doorbell_reg(%x)!\n",
5542 		__func__, count, doorbell_reg);
5543 	return -EFAULT;
5544 }
5545 
5546 /**
5547  * _base_send_ioc_reset - send doorbell reset
5548  * @ioc: per adapter object
5549  * @reset_type: currently only supports: MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET
5550  * @timeout: timeout in second
5551  *
5552  * Return: 0 for success, non-zero for failure.
5553  */
5554 static int
5555 _base_send_ioc_reset(struct MPT3SAS_ADAPTER *ioc, u8 reset_type, int timeout)
5556 {
5557 	u32 ioc_state;
5558 	int r = 0;
5559 
5560 	if (reset_type != MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET) {
5561 		ioc_err(ioc, "%s: unknown reset_type\n", __func__);
5562 		return -EFAULT;
5563 	}
5564 
5565 	if (!(ioc->facts.IOCCapabilities &
5566 	   MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY))
5567 		return -EFAULT;
5568 
5569 	ioc_info(ioc, "sending message unit reset !!\n");
5570 
5571 	writel(reset_type << MPI2_DOORBELL_FUNCTION_SHIFT,
5572 	    &ioc->chip->Doorbell);
5573 	if ((_base_wait_for_doorbell_ack(ioc, 15))) {
5574 		r = -EFAULT;
5575 		goto out;
5576 	}
5577 	ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, timeout);
5578 	if (ioc_state) {
5579 		ioc_err(ioc, "%s: failed going to ready state (ioc_state=0x%x)\n",
5580 			__func__, ioc_state);
5581 		r = -EFAULT;
5582 		goto out;
5583 	}
5584  out:
5585 	ioc_info(ioc, "message unit reset: %s\n",
5586 		 r == 0 ? "SUCCESS" : "FAILED");
5587 	return r;
5588 }
5589 
5590 /**
5591  * mpt3sas_wait_for_ioc - IOC's operational state is checked here.
5592  * @ioc: per adapter object
5593  * @wait_count: timeout in seconds
5594  *
5595  * Return: Waits up to timeout seconds for the IOC to
5596  * become operational. Returns 0 if IOC is present
5597  * and operational; otherwise returns -EFAULT.
5598  */
5599 
5600 int
5601 mpt3sas_wait_for_ioc(struct MPT3SAS_ADAPTER *ioc, int timeout)
5602 {
5603 	int wait_state_count = 0;
5604 	u32 ioc_state;
5605 
5606 	do {
5607 		ioc_state = mpt3sas_base_get_iocstate(ioc, 1);
5608 		if (ioc_state == MPI2_IOC_STATE_OPERATIONAL)
5609 			break;
5610 		ssleep(1);
5611 		ioc_info(ioc, "%s: waiting for operational state(count=%d)\n",
5612 				__func__, ++wait_state_count);
5613 	} while (--timeout);
5614 	if (!timeout) {
5615 		ioc_err(ioc, "%s: failed due to ioc not operational\n", __func__);
5616 		return -EFAULT;
5617 	}
5618 	if (wait_state_count)
5619 		ioc_info(ioc, "ioc is operational\n");
5620 	return 0;
5621 }
5622 
5623 /**
5624  * _base_handshake_req_reply_wait - send request thru doorbell interface
5625  * @ioc: per adapter object
5626  * @request_bytes: request length
5627  * @request: pointer having request payload
5628  * @reply_bytes: reply length
5629  * @reply: pointer to reply payload
5630  * @timeout: timeout in second
5631  *
5632  * Return: 0 for success, non-zero for failure.
5633  */
5634 static int
5635 _base_handshake_req_reply_wait(struct MPT3SAS_ADAPTER *ioc, int request_bytes,
5636 	u32 *request, int reply_bytes, u16 *reply, int timeout)
5637 {
5638 	MPI2DefaultReply_t *default_reply = (MPI2DefaultReply_t *)reply;
5639 	int i;
5640 	u8 failed;
5641 	__le32 *mfp;
5642 
5643 	/* make sure doorbell is not in use */
5644 	if ((ioc->base_readl(&ioc->chip->Doorbell) & MPI2_DOORBELL_USED)) {
5645 		ioc_err(ioc, "doorbell is in use (line=%d)\n", __LINE__);
5646 		return -EFAULT;
5647 	}
5648 
5649 	/* clear pending doorbell interrupts from previous state changes */
5650 	if (ioc->base_readl(&ioc->chip->HostInterruptStatus) &
5651 	    MPI2_HIS_IOC2SYS_DB_STATUS)
5652 		writel(0, &ioc->chip->HostInterruptStatus);
5653 
5654 	/* send message to ioc */
5655 	writel(((MPI2_FUNCTION_HANDSHAKE<<MPI2_DOORBELL_FUNCTION_SHIFT) |
5656 	    ((request_bytes/4)<<MPI2_DOORBELL_ADD_DWORDS_SHIFT)),
5657 	    &ioc->chip->Doorbell);
5658 
5659 	if ((_base_spin_on_doorbell_int(ioc, 5))) {
5660 		ioc_err(ioc, "doorbell handshake int failed (line=%d)\n",
5661 			__LINE__);
5662 		return -EFAULT;
5663 	}
5664 	writel(0, &ioc->chip->HostInterruptStatus);
5665 
5666 	if ((_base_wait_for_doorbell_ack(ioc, 5))) {
5667 		ioc_err(ioc, "doorbell handshake ack failed (line=%d)\n",
5668 			__LINE__);
5669 		return -EFAULT;
5670 	}
5671 
5672 	/* send message 32-bits at a time */
5673 	for (i = 0, failed = 0; i < request_bytes/4 && !failed; i++) {
5674 		writel(cpu_to_le32(request[i]), &ioc->chip->Doorbell);
5675 		if ((_base_wait_for_doorbell_ack(ioc, 5)))
5676 			failed = 1;
5677 	}
5678 
5679 	if (failed) {
5680 		ioc_err(ioc, "doorbell handshake sending request failed (line=%d)\n",
5681 			__LINE__);
5682 		return -EFAULT;
5683 	}
5684 
5685 	/* now wait for the reply */
5686 	if ((_base_wait_for_doorbell_int(ioc, timeout))) {
5687 		ioc_err(ioc, "doorbell handshake int failed (line=%d)\n",
5688 			__LINE__);
5689 		return -EFAULT;
5690 	}
5691 
5692 	/* read the first two 16-bits, it gives the total length of the reply */
5693 	reply[0] = le16_to_cpu(ioc->base_readl(&ioc->chip->Doorbell)
5694 	    & MPI2_DOORBELL_DATA_MASK);
5695 	writel(0, &ioc->chip->HostInterruptStatus);
5696 	if ((_base_wait_for_doorbell_int(ioc, 5))) {
5697 		ioc_err(ioc, "doorbell handshake int failed (line=%d)\n",
5698 			__LINE__);
5699 		return -EFAULT;
5700 	}
5701 	reply[1] = le16_to_cpu(ioc->base_readl(&ioc->chip->Doorbell)
5702 	    & MPI2_DOORBELL_DATA_MASK);
5703 	writel(0, &ioc->chip->HostInterruptStatus);
5704 
5705 	for (i = 2; i < default_reply->MsgLength * 2; i++)  {
5706 		if ((_base_wait_for_doorbell_int(ioc, 5))) {
5707 			ioc_err(ioc, "doorbell handshake int failed (line=%d)\n",
5708 				__LINE__);
5709 			return -EFAULT;
5710 		}
5711 		if (i >=  reply_bytes/2) /* overflow case */
5712 			ioc->base_readl(&ioc->chip->Doorbell);
5713 		else
5714 			reply[i] = le16_to_cpu(
5715 			    ioc->base_readl(&ioc->chip->Doorbell)
5716 			    & MPI2_DOORBELL_DATA_MASK);
5717 		writel(0, &ioc->chip->HostInterruptStatus);
5718 	}
5719 
5720 	_base_wait_for_doorbell_int(ioc, 5);
5721 	if (_base_wait_for_doorbell_not_used(ioc, 5) != 0) {
5722 		dhsprintk(ioc,
5723 			  ioc_info(ioc, "doorbell is in use (line=%d)\n",
5724 				   __LINE__));
5725 	}
5726 	writel(0, &ioc->chip->HostInterruptStatus);
5727 
5728 	if (ioc->logging_level & MPT_DEBUG_INIT) {
5729 		mfp = (__le32 *)reply;
5730 		pr_info("\toffset:data\n");
5731 		for (i = 0; i < reply_bytes/4; i++)
5732 			pr_info("\t[0x%02x]:%08x\n", i*4,
5733 			    le32_to_cpu(mfp[i]));
5734 	}
5735 	return 0;
5736 }
5737 
5738 /**
5739  * mpt3sas_base_sas_iounit_control - send sas iounit control to FW
5740  * @ioc: per adapter object
5741  * @mpi_reply: the reply payload from FW
5742  * @mpi_request: the request payload sent to FW
5743  *
5744  * The SAS IO Unit Control Request message allows the host to perform low-level
5745  * operations, such as resets on the PHYs of the IO Unit, also allows the host
5746  * to obtain the IOC assigned device handles for a device if it has other
5747  * identifying information about the device, in addition allows the host to
5748  * remove IOC resources associated with the device.
5749  *
5750  * Return: 0 for success, non-zero for failure.
5751  */
5752 int
5753 mpt3sas_base_sas_iounit_control(struct MPT3SAS_ADAPTER *ioc,
5754 	Mpi2SasIoUnitControlReply_t *mpi_reply,
5755 	Mpi2SasIoUnitControlRequest_t *mpi_request)
5756 {
5757 	u16 smid;
5758 	u8 issue_reset = 0;
5759 	int rc;
5760 	void *request;
5761 
5762 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
5763 
5764 	mutex_lock(&ioc->base_cmds.mutex);
5765 
5766 	if (ioc->base_cmds.status != MPT3_CMD_NOT_USED) {
5767 		ioc_err(ioc, "%s: base_cmd in use\n", __func__);
5768 		rc = -EAGAIN;
5769 		goto out;
5770 	}
5771 
5772 	rc = mpt3sas_wait_for_ioc(ioc, IOC_OPERATIONAL_WAIT_COUNT);
5773 	if (rc)
5774 		goto out;
5775 
5776 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
5777 	if (!smid) {
5778 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
5779 		rc = -EAGAIN;
5780 		goto out;
5781 	}
5782 
5783 	rc = 0;
5784 	ioc->base_cmds.status = MPT3_CMD_PENDING;
5785 	request = mpt3sas_base_get_msg_frame(ioc, smid);
5786 	ioc->base_cmds.smid = smid;
5787 	memcpy(request, mpi_request, sizeof(Mpi2SasIoUnitControlRequest_t));
5788 	if (mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
5789 	    mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET)
5790 		ioc->ioc_link_reset_in_progress = 1;
5791 	init_completion(&ioc->base_cmds.done);
5792 	ioc->put_smid_default(ioc, smid);
5793 	wait_for_completion_timeout(&ioc->base_cmds.done,
5794 	    msecs_to_jiffies(10000));
5795 	if ((mpi_request->Operation == MPI2_SAS_OP_PHY_HARD_RESET ||
5796 	    mpi_request->Operation == MPI2_SAS_OP_PHY_LINK_RESET) &&
5797 	    ioc->ioc_link_reset_in_progress)
5798 		ioc->ioc_link_reset_in_progress = 0;
5799 	if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
5800 		issue_reset =
5801 			mpt3sas_base_check_cmd_timeout(ioc,
5802 				ioc->base_cmds.status, mpi_request,
5803 				sizeof(Mpi2SasIoUnitControlRequest_t)/4);
5804 		goto issue_host_reset;
5805 	}
5806 	if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID)
5807 		memcpy(mpi_reply, ioc->base_cmds.reply,
5808 		    sizeof(Mpi2SasIoUnitControlReply_t));
5809 	else
5810 		memset(mpi_reply, 0, sizeof(Mpi2SasIoUnitControlReply_t));
5811 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5812 	goto out;
5813 
5814  issue_host_reset:
5815 	if (issue_reset)
5816 		mpt3sas_base_hard_reset_handler(ioc, FORCE_BIG_HAMMER);
5817 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5818 	rc = -EFAULT;
5819  out:
5820 	mutex_unlock(&ioc->base_cmds.mutex);
5821 	return rc;
5822 }
5823 
5824 /**
5825  * mpt3sas_base_scsi_enclosure_processor - sending request to sep device
5826  * @ioc: per adapter object
5827  * @mpi_reply: the reply payload from FW
5828  * @mpi_request: the request payload sent to FW
5829  *
5830  * The SCSI Enclosure Processor request message causes the IOC to
5831  * communicate with SES devices to control LED status signals.
5832  *
5833  * Return: 0 for success, non-zero for failure.
5834  */
5835 int
5836 mpt3sas_base_scsi_enclosure_processor(struct MPT3SAS_ADAPTER *ioc,
5837 	Mpi2SepReply_t *mpi_reply, Mpi2SepRequest_t *mpi_request)
5838 {
5839 	u16 smid;
5840 	u8 issue_reset = 0;
5841 	int rc;
5842 	void *request;
5843 
5844 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
5845 
5846 	mutex_lock(&ioc->base_cmds.mutex);
5847 
5848 	if (ioc->base_cmds.status != MPT3_CMD_NOT_USED) {
5849 		ioc_err(ioc, "%s: base_cmd in use\n", __func__);
5850 		rc = -EAGAIN;
5851 		goto out;
5852 	}
5853 
5854 	rc = mpt3sas_wait_for_ioc(ioc, IOC_OPERATIONAL_WAIT_COUNT);
5855 	if (rc)
5856 		goto out;
5857 
5858 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
5859 	if (!smid) {
5860 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
5861 		rc = -EAGAIN;
5862 		goto out;
5863 	}
5864 
5865 	rc = 0;
5866 	ioc->base_cmds.status = MPT3_CMD_PENDING;
5867 	request = mpt3sas_base_get_msg_frame(ioc, smid);
5868 	ioc->base_cmds.smid = smid;
5869 	memcpy(request, mpi_request, sizeof(Mpi2SepReply_t));
5870 	init_completion(&ioc->base_cmds.done);
5871 	ioc->put_smid_default(ioc, smid);
5872 	wait_for_completion_timeout(&ioc->base_cmds.done,
5873 	    msecs_to_jiffies(10000));
5874 	if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
5875 		issue_reset =
5876 			mpt3sas_base_check_cmd_timeout(ioc,
5877 				ioc->base_cmds.status, mpi_request,
5878 				sizeof(Mpi2SepRequest_t)/4);
5879 		goto issue_host_reset;
5880 	}
5881 	if (ioc->base_cmds.status & MPT3_CMD_REPLY_VALID)
5882 		memcpy(mpi_reply, ioc->base_cmds.reply,
5883 		    sizeof(Mpi2SepReply_t));
5884 	else
5885 		memset(mpi_reply, 0, sizeof(Mpi2SepReply_t));
5886 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5887 	goto out;
5888 
5889  issue_host_reset:
5890 	if (issue_reset)
5891 		mpt3sas_base_hard_reset_handler(ioc, FORCE_BIG_HAMMER);
5892 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
5893 	rc = -EFAULT;
5894  out:
5895 	mutex_unlock(&ioc->base_cmds.mutex);
5896 	return rc;
5897 }
5898 
5899 /**
5900  * _base_get_port_facts - obtain port facts reply and save in ioc
5901  * @ioc: per adapter object
5902  * @port: ?
5903  *
5904  * Return: 0 for success, non-zero for failure.
5905  */
5906 static int
5907 _base_get_port_facts(struct MPT3SAS_ADAPTER *ioc, int port)
5908 {
5909 	Mpi2PortFactsRequest_t mpi_request;
5910 	Mpi2PortFactsReply_t mpi_reply;
5911 	struct mpt3sas_port_facts *pfacts;
5912 	int mpi_reply_sz, mpi_request_sz, r;
5913 
5914 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
5915 
5916 	mpi_reply_sz = sizeof(Mpi2PortFactsReply_t);
5917 	mpi_request_sz = sizeof(Mpi2PortFactsRequest_t);
5918 	memset(&mpi_request, 0, mpi_request_sz);
5919 	mpi_request.Function = MPI2_FUNCTION_PORT_FACTS;
5920 	mpi_request.PortNumber = port;
5921 	r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
5922 	    (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5);
5923 
5924 	if (r != 0) {
5925 		ioc_err(ioc, "%s: handshake failed (r=%d)\n", __func__, r);
5926 		return r;
5927 	}
5928 
5929 	pfacts = &ioc->pfacts[port];
5930 	memset(pfacts, 0, sizeof(struct mpt3sas_port_facts));
5931 	pfacts->PortNumber = mpi_reply.PortNumber;
5932 	pfacts->VP_ID = mpi_reply.VP_ID;
5933 	pfacts->VF_ID = mpi_reply.VF_ID;
5934 	pfacts->MaxPostedCmdBuffers =
5935 	    le16_to_cpu(mpi_reply.MaxPostedCmdBuffers);
5936 
5937 	return 0;
5938 }
5939 
5940 /**
5941  * _base_wait_for_iocstate - Wait until the card is in READY or OPERATIONAL
5942  * @ioc: per adapter object
5943  * @timeout:
5944  *
5945  * Return: 0 for success, non-zero for failure.
5946  */
5947 static int
5948 _base_wait_for_iocstate(struct MPT3SAS_ADAPTER *ioc, int timeout)
5949 {
5950 	u32 ioc_state;
5951 	int rc;
5952 
5953 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
5954 
5955 	if (ioc->pci_error_recovery) {
5956 		dfailprintk(ioc,
5957 			    ioc_info(ioc, "%s: host in pci error recovery\n",
5958 				     __func__));
5959 		return -EFAULT;
5960 	}
5961 
5962 	ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
5963 	dhsprintk(ioc,
5964 		  ioc_info(ioc, "%s: ioc_state(0x%08x)\n",
5965 			   __func__, ioc_state));
5966 
5967 	if (((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_READY) ||
5968 	    (ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_OPERATIONAL)
5969 		return 0;
5970 
5971 	if (ioc_state & MPI2_DOORBELL_USED) {
5972 		dhsprintk(ioc, ioc_info(ioc, "unexpected doorbell active!\n"));
5973 		goto issue_diag_reset;
5974 	}
5975 
5976 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
5977 		mpt3sas_base_fault_info(ioc, ioc_state &
5978 		    MPI2_DOORBELL_DATA_MASK);
5979 		goto issue_diag_reset;
5980 	}
5981 
5982 	ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, timeout);
5983 	if (ioc_state) {
5984 		dfailprintk(ioc,
5985 			    ioc_info(ioc, "%s: failed going to ready state (ioc_state=0x%x)\n",
5986 				     __func__, ioc_state));
5987 		return -EFAULT;
5988 	}
5989 
5990  issue_diag_reset:
5991 	rc = _base_diag_reset(ioc);
5992 	return rc;
5993 }
5994 
5995 /**
5996  * _base_get_ioc_facts - obtain ioc facts reply and save in ioc
5997  * @ioc: per adapter object
5998  *
5999  * Return: 0 for success, non-zero for failure.
6000  */
6001 static int
6002 _base_get_ioc_facts(struct MPT3SAS_ADAPTER *ioc)
6003 {
6004 	Mpi2IOCFactsRequest_t mpi_request;
6005 	Mpi2IOCFactsReply_t mpi_reply;
6006 	struct mpt3sas_facts *facts;
6007 	int mpi_reply_sz, mpi_request_sz, r;
6008 
6009 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6010 
6011 	r = _base_wait_for_iocstate(ioc, 10);
6012 	if (r) {
6013 		dfailprintk(ioc,
6014 			    ioc_info(ioc, "%s: failed getting to correct state\n",
6015 				     __func__));
6016 		return r;
6017 	}
6018 	mpi_reply_sz = sizeof(Mpi2IOCFactsReply_t);
6019 	mpi_request_sz = sizeof(Mpi2IOCFactsRequest_t);
6020 	memset(&mpi_request, 0, mpi_request_sz);
6021 	mpi_request.Function = MPI2_FUNCTION_IOC_FACTS;
6022 	r = _base_handshake_req_reply_wait(ioc, mpi_request_sz,
6023 	    (u32 *)&mpi_request, mpi_reply_sz, (u16 *)&mpi_reply, 5);
6024 
6025 	if (r != 0) {
6026 		ioc_err(ioc, "%s: handshake failed (r=%d)\n", __func__, r);
6027 		return r;
6028 	}
6029 
6030 	facts = &ioc->facts;
6031 	memset(facts, 0, sizeof(struct mpt3sas_facts));
6032 	facts->MsgVersion = le16_to_cpu(mpi_reply.MsgVersion);
6033 	facts->HeaderVersion = le16_to_cpu(mpi_reply.HeaderVersion);
6034 	facts->VP_ID = mpi_reply.VP_ID;
6035 	facts->VF_ID = mpi_reply.VF_ID;
6036 	facts->IOCExceptions = le16_to_cpu(mpi_reply.IOCExceptions);
6037 	facts->MaxChainDepth = mpi_reply.MaxChainDepth;
6038 	facts->WhoInit = mpi_reply.WhoInit;
6039 	facts->NumberOfPorts = mpi_reply.NumberOfPorts;
6040 	facts->MaxMSIxVectors = mpi_reply.MaxMSIxVectors;
6041 	if (ioc->msix_enable && (facts->MaxMSIxVectors <=
6042 	    MAX_COMBINED_MSIX_VECTORS(ioc->is_gen35_ioc)))
6043 		ioc->combined_reply_queue = 0;
6044 	facts->RequestCredit = le16_to_cpu(mpi_reply.RequestCredit);
6045 	facts->MaxReplyDescriptorPostQueueDepth =
6046 	    le16_to_cpu(mpi_reply.MaxReplyDescriptorPostQueueDepth);
6047 	facts->ProductID = le16_to_cpu(mpi_reply.ProductID);
6048 	facts->IOCCapabilities = le32_to_cpu(mpi_reply.IOCCapabilities);
6049 	if ((facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID))
6050 		ioc->ir_firmware = 1;
6051 	if ((facts->IOCCapabilities &
6052 	      MPI2_IOCFACTS_CAPABILITY_RDPQ_ARRAY_CAPABLE) && (!reset_devices))
6053 		ioc->rdpq_array_capable = 1;
6054 	if ((facts->IOCCapabilities & MPI26_IOCFACTS_CAPABILITY_ATOMIC_REQ)
6055 	    && ioc->is_aero_ioc)
6056 		ioc->atomic_desc_capable = 1;
6057 	facts->FWVersion.Word = le32_to_cpu(mpi_reply.FWVersion.Word);
6058 	facts->IOCRequestFrameSize =
6059 	    le16_to_cpu(mpi_reply.IOCRequestFrameSize);
6060 	if (ioc->hba_mpi_version_belonged != MPI2_VERSION) {
6061 		facts->IOCMaxChainSegmentSize =
6062 			le16_to_cpu(mpi_reply.IOCMaxChainSegmentSize);
6063 	}
6064 	facts->MaxInitiators = le16_to_cpu(mpi_reply.MaxInitiators);
6065 	facts->MaxTargets = le16_to_cpu(mpi_reply.MaxTargets);
6066 	ioc->shost->max_id = -1;
6067 	facts->MaxSasExpanders = le16_to_cpu(mpi_reply.MaxSasExpanders);
6068 	facts->MaxEnclosures = le16_to_cpu(mpi_reply.MaxEnclosures);
6069 	facts->ProtocolFlags = le16_to_cpu(mpi_reply.ProtocolFlags);
6070 	facts->HighPriorityCredit =
6071 	    le16_to_cpu(mpi_reply.HighPriorityCredit);
6072 	facts->ReplyFrameSize = mpi_reply.ReplyFrameSize;
6073 	facts->MaxDevHandle = le16_to_cpu(mpi_reply.MaxDevHandle);
6074 	facts->CurrentHostPageSize = mpi_reply.CurrentHostPageSize;
6075 
6076 	/*
6077 	 * Get the Page Size from IOC Facts. If it's 0, default to 4k.
6078 	 */
6079 	ioc->page_size = 1 << facts->CurrentHostPageSize;
6080 	if (ioc->page_size == 1) {
6081 		ioc_info(ioc, "CurrentHostPageSize is 0: Setting default host page size to 4k\n");
6082 		ioc->page_size = 1 << MPT3SAS_HOST_PAGE_SIZE_4K;
6083 	}
6084 	dinitprintk(ioc,
6085 		    ioc_info(ioc, "CurrentHostPageSize(%d)\n",
6086 			     facts->CurrentHostPageSize));
6087 
6088 	dinitprintk(ioc,
6089 		    ioc_info(ioc, "hba queue depth(%d), max chains per io(%d)\n",
6090 			     facts->RequestCredit, facts->MaxChainDepth));
6091 	dinitprintk(ioc,
6092 		    ioc_info(ioc, "request frame size(%d), reply frame size(%d)\n",
6093 			     facts->IOCRequestFrameSize * 4,
6094 			     facts->ReplyFrameSize * 4));
6095 	return 0;
6096 }
6097 
6098 /**
6099  * _base_send_ioc_init - send ioc_init to firmware
6100  * @ioc: per adapter object
6101  *
6102  * Return: 0 for success, non-zero for failure.
6103  */
6104 static int
6105 _base_send_ioc_init(struct MPT3SAS_ADAPTER *ioc)
6106 {
6107 	Mpi2IOCInitRequest_t mpi_request;
6108 	Mpi2IOCInitReply_t mpi_reply;
6109 	int i, r = 0;
6110 	ktime_t current_time;
6111 	u16 ioc_status;
6112 	u32 reply_post_free_array_sz = 0;
6113 
6114 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6115 
6116 	memset(&mpi_request, 0, sizeof(Mpi2IOCInitRequest_t));
6117 	mpi_request.Function = MPI2_FUNCTION_IOC_INIT;
6118 	mpi_request.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
6119 	mpi_request.VF_ID = 0; /* TODO */
6120 	mpi_request.VP_ID = 0;
6121 	mpi_request.MsgVersion = cpu_to_le16(ioc->hba_mpi_version_belonged);
6122 	mpi_request.HeaderVersion = cpu_to_le16(MPI2_HEADER_VERSION);
6123 	mpi_request.HostPageSize = MPT3SAS_HOST_PAGE_SIZE_4K;
6124 
6125 	if (_base_is_controller_msix_enabled(ioc))
6126 		mpi_request.HostMSIxVectors = ioc->reply_queue_count;
6127 	mpi_request.SystemRequestFrameSize = cpu_to_le16(ioc->request_sz/4);
6128 	mpi_request.ReplyDescriptorPostQueueDepth =
6129 	    cpu_to_le16(ioc->reply_post_queue_depth);
6130 	mpi_request.ReplyFreeQueueDepth =
6131 	    cpu_to_le16(ioc->reply_free_queue_depth);
6132 
6133 	mpi_request.SenseBufferAddressHigh =
6134 	    cpu_to_le32((u64)ioc->sense_dma >> 32);
6135 	mpi_request.SystemReplyAddressHigh =
6136 	    cpu_to_le32((u64)ioc->reply_dma >> 32);
6137 	mpi_request.SystemRequestFrameBaseAddress =
6138 	    cpu_to_le64((u64)ioc->request_dma);
6139 	mpi_request.ReplyFreeQueueAddress =
6140 	    cpu_to_le64((u64)ioc->reply_free_dma);
6141 
6142 	if (ioc->rdpq_array_enable) {
6143 		reply_post_free_array_sz = ioc->reply_queue_count *
6144 		    sizeof(Mpi2IOCInitRDPQArrayEntry);
6145 		memset(ioc->reply_post_free_array, 0, reply_post_free_array_sz);
6146 		for (i = 0; i < ioc->reply_queue_count; i++)
6147 			ioc->reply_post_free_array[i].RDPQBaseAddress =
6148 			    cpu_to_le64(
6149 				(u64)ioc->reply_post[i].reply_post_free_dma);
6150 		mpi_request.MsgFlags = MPI2_IOCINIT_MSGFLAG_RDPQ_ARRAY_MODE;
6151 		mpi_request.ReplyDescriptorPostQueueAddress =
6152 		    cpu_to_le64((u64)ioc->reply_post_free_array_dma);
6153 	} else {
6154 		mpi_request.ReplyDescriptorPostQueueAddress =
6155 		    cpu_to_le64((u64)ioc->reply_post[0].reply_post_free_dma);
6156 	}
6157 
6158 	/* This time stamp specifies number of milliseconds
6159 	 * since epoch ~ midnight January 1, 1970.
6160 	 */
6161 	current_time = ktime_get_real();
6162 	mpi_request.TimeStamp = cpu_to_le64(ktime_to_ms(current_time));
6163 
6164 	if (ioc->logging_level & MPT_DEBUG_INIT) {
6165 		__le32 *mfp;
6166 		int i;
6167 
6168 		mfp = (__le32 *)&mpi_request;
6169 		pr_info("\toffset:data\n");
6170 		for (i = 0; i < sizeof(Mpi2IOCInitRequest_t)/4; i++)
6171 			pr_info("\t[0x%02x]:%08x\n", i*4,
6172 			    le32_to_cpu(mfp[i]));
6173 	}
6174 
6175 	r = _base_handshake_req_reply_wait(ioc,
6176 	    sizeof(Mpi2IOCInitRequest_t), (u32 *)&mpi_request,
6177 	    sizeof(Mpi2IOCInitReply_t), (u16 *)&mpi_reply, 10);
6178 
6179 	if (r != 0) {
6180 		ioc_err(ioc, "%s: handshake failed (r=%d)\n", __func__, r);
6181 		return r;
6182 	}
6183 
6184 	ioc_status = le16_to_cpu(mpi_reply.IOCStatus) & MPI2_IOCSTATUS_MASK;
6185 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS ||
6186 	    mpi_reply.IOCLogInfo) {
6187 		ioc_err(ioc, "%s: failed\n", __func__);
6188 		r = -EIO;
6189 	}
6190 
6191 	return r;
6192 }
6193 
6194 /**
6195  * mpt3sas_port_enable_done - command completion routine for port enable
6196  * @ioc: per adapter object
6197  * @smid: system request message index
6198  * @msix_index: MSIX table index supplied by the OS
6199  * @reply: reply message frame(lower 32bit addr)
6200  *
6201  * Return: 1 meaning mf should be freed from _base_interrupt
6202  *          0 means the mf is freed from this function.
6203  */
6204 u8
6205 mpt3sas_port_enable_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
6206 	u32 reply)
6207 {
6208 	MPI2DefaultReply_t *mpi_reply;
6209 	u16 ioc_status;
6210 
6211 	if (ioc->port_enable_cmds.status == MPT3_CMD_NOT_USED)
6212 		return 1;
6213 
6214 	mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply);
6215 	if (!mpi_reply)
6216 		return 1;
6217 
6218 	if (mpi_reply->Function != MPI2_FUNCTION_PORT_ENABLE)
6219 		return 1;
6220 
6221 	ioc->port_enable_cmds.status &= ~MPT3_CMD_PENDING;
6222 	ioc->port_enable_cmds.status |= MPT3_CMD_COMPLETE;
6223 	ioc->port_enable_cmds.status |= MPT3_CMD_REPLY_VALID;
6224 	memcpy(ioc->port_enable_cmds.reply, mpi_reply, mpi_reply->MsgLength*4);
6225 	ioc_status = le16_to_cpu(mpi_reply->IOCStatus) & MPI2_IOCSTATUS_MASK;
6226 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS)
6227 		ioc->port_enable_failed = 1;
6228 
6229 	if (ioc->is_driver_loading) {
6230 		if (ioc_status == MPI2_IOCSTATUS_SUCCESS) {
6231 			mpt3sas_port_enable_complete(ioc);
6232 			return 1;
6233 		} else {
6234 			ioc->start_scan_failed = ioc_status;
6235 			ioc->start_scan = 0;
6236 			return 1;
6237 		}
6238 	}
6239 	complete(&ioc->port_enable_cmds.done);
6240 	return 1;
6241 }
6242 
6243 /**
6244  * _base_send_port_enable - send port_enable(discovery stuff) to firmware
6245  * @ioc: per adapter object
6246  *
6247  * Return: 0 for success, non-zero for failure.
6248  */
6249 static int
6250 _base_send_port_enable(struct MPT3SAS_ADAPTER *ioc)
6251 {
6252 	Mpi2PortEnableRequest_t *mpi_request;
6253 	Mpi2PortEnableReply_t *mpi_reply;
6254 	int r = 0;
6255 	u16 smid;
6256 	u16 ioc_status;
6257 
6258 	ioc_info(ioc, "sending port enable !!\n");
6259 
6260 	if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
6261 		ioc_err(ioc, "%s: internal command already in use\n", __func__);
6262 		return -EAGAIN;
6263 	}
6264 
6265 	smid = mpt3sas_base_get_smid(ioc, ioc->port_enable_cb_idx);
6266 	if (!smid) {
6267 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
6268 		return -EAGAIN;
6269 	}
6270 
6271 	ioc->port_enable_cmds.status = MPT3_CMD_PENDING;
6272 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
6273 	ioc->port_enable_cmds.smid = smid;
6274 	memset(mpi_request, 0, sizeof(Mpi2PortEnableRequest_t));
6275 	mpi_request->Function = MPI2_FUNCTION_PORT_ENABLE;
6276 
6277 	init_completion(&ioc->port_enable_cmds.done);
6278 	ioc->put_smid_default(ioc, smid);
6279 	wait_for_completion_timeout(&ioc->port_enable_cmds.done, 300*HZ);
6280 	if (!(ioc->port_enable_cmds.status & MPT3_CMD_COMPLETE)) {
6281 		ioc_err(ioc, "%s: timeout\n", __func__);
6282 		_debug_dump_mf(mpi_request,
6283 		    sizeof(Mpi2PortEnableRequest_t)/4);
6284 		if (ioc->port_enable_cmds.status & MPT3_CMD_RESET)
6285 			r = -EFAULT;
6286 		else
6287 			r = -ETIME;
6288 		goto out;
6289 	}
6290 
6291 	mpi_reply = ioc->port_enable_cmds.reply;
6292 	ioc_status = le16_to_cpu(mpi_reply->IOCStatus) & MPI2_IOCSTATUS_MASK;
6293 	if (ioc_status != MPI2_IOCSTATUS_SUCCESS) {
6294 		ioc_err(ioc, "%s: failed with (ioc_status=0x%08x)\n",
6295 			__func__, ioc_status);
6296 		r = -EFAULT;
6297 		goto out;
6298 	}
6299 
6300  out:
6301 	ioc->port_enable_cmds.status = MPT3_CMD_NOT_USED;
6302 	ioc_info(ioc, "port enable: %s\n", r == 0 ? "SUCCESS" : "FAILED");
6303 	return r;
6304 }
6305 
6306 /**
6307  * mpt3sas_port_enable - initiate firmware discovery (don't wait for reply)
6308  * @ioc: per adapter object
6309  *
6310  * Return: 0 for success, non-zero for failure.
6311  */
6312 int
6313 mpt3sas_port_enable(struct MPT3SAS_ADAPTER *ioc)
6314 {
6315 	Mpi2PortEnableRequest_t *mpi_request;
6316 	u16 smid;
6317 
6318 	ioc_info(ioc, "sending port enable !!\n");
6319 
6320 	if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
6321 		ioc_err(ioc, "%s: internal command already in use\n", __func__);
6322 		return -EAGAIN;
6323 	}
6324 
6325 	smid = mpt3sas_base_get_smid(ioc, ioc->port_enable_cb_idx);
6326 	if (!smid) {
6327 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
6328 		return -EAGAIN;
6329 	}
6330 
6331 	ioc->port_enable_cmds.status = MPT3_CMD_PENDING;
6332 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
6333 	ioc->port_enable_cmds.smid = smid;
6334 	memset(mpi_request, 0, sizeof(Mpi2PortEnableRequest_t));
6335 	mpi_request->Function = MPI2_FUNCTION_PORT_ENABLE;
6336 
6337 	ioc->put_smid_default(ioc, smid);
6338 	return 0;
6339 }
6340 
6341 /**
6342  * _base_determine_wait_on_discovery - desposition
6343  * @ioc: per adapter object
6344  *
6345  * Decide whether to wait on discovery to complete. Used to either
6346  * locate boot device, or report volumes ahead of physical devices.
6347  *
6348  * Return: 1 for wait, 0 for don't wait.
6349  */
6350 static int
6351 _base_determine_wait_on_discovery(struct MPT3SAS_ADAPTER *ioc)
6352 {
6353 	/* We wait for discovery to complete if IR firmware is loaded.
6354 	 * The sas topology events arrive before PD events, so we need time to
6355 	 * turn on the bit in ioc->pd_handles to indicate PD
6356 	 * Also, it maybe required to report Volumes ahead of physical
6357 	 * devices when MPI2_IOCPAGE8_IRFLAGS_LOW_VOLUME_MAPPING is set.
6358 	 */
6359 	if (ioc->ir_firmware)
6360 		return 1;
6361 
6362 	/* if no Bios, then we don't need to wait */
6363 	if (!ioc->bios_pg3.BiosVersion)
6364 		return 0;
6365 
6366 	/* Bios is present, then we drop down here.
6367 	 *
6368 	 * If there any entries in the Bios Page 2, then we wait
6369 	 * for discovery to complete.
6370 	 */
6371 
6372 	/* Current Boot Device */
6373 	if ((ioc->bios_pg2.CurrentBootDeviceForm &
6374 	    MPI2_BIOSPAGE2_FORM_MASK) ==
6375 	    MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED &&
6376 	/* Request Boot Device */
6377 	   (ioc->bios_pg2.ReqBootDeviceForm &
6378 	    MPI2_BIOSPAGE2_FORM_MASK) ==
6379 	    MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED &&
6380 	/* Alternate Request Boot Device */
6381 	   (ioc->bios_pg2.ReqAltBootDeviceForm &
6382 	    MPI2_BIOSPAGE2_FORM_MASK) ==
6383 	    MPI2_BIOSPAGE2_FORM_NO_DEVICE_SPECIFIED)
6384 		return 0;
6385 
6386 	return 1;
6387 }
6388 
6389 /**
6390  * _base_unmask_events - turn on notification for this event
6391  * @ioc: per adapter object
6392  * @event: firmware event
6393  *
6394  * The mask is stored in ioc->event_masks.
6395  */
6396 static void
6397 _base_unmask_events(struct MPT3SAS_ADAPTER *ioc, u16 event)
6398 {
6399 	u32 desired_event;
6400 
6401 	if (event >= 128)
6402 		return;
6403 
6404 	desired_event = (1 << (event % 32));
6405 
6406 	if (event < 32)
6407 		ioc->event_masks[0] &= ~desired_event;
6408 	else if (event < 64)
6409 		ioc->event_masks[1] &= ~desired_event;
6410 	else if (event < 96)
6411 		ioc->event_masks[2] &= ~desired_event;
6412 	else if (event < 128)
6413 		ioc->event_masks[3] &= ~desired_event;
6414 }
6415 
6416 /**
6417  * _base_event_notification - send event notification
6418  * @ioc: per adapter object
6419  *
6420  * Return: 0 for success, non-zero for failure.
6421  */
6422 static int
6423 _base_event_notification(struct MPT3SAS_ADAPTER *ioc)
6424 {
6425 	Mpi2EventNotificationRequest_t *mpi_request;
6426 	u16 smid;
6427 	int r = 0;
6428 	int i;
6429 
6430 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6431 
6432 	if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
6433 		ioc_err(ioc, "%s: internal command already in use\n", __func__);
6434 		return -EAGAIN;
6435 	}
6436 
6437 	smid = mpt3sas_base_get_smid(ioc, ioc->base_cb_idx);
6438 	if (!smid) {
6439 		ioc_err(ioc, "%s: failed obtaining a smid\n", __func__);
6440 		return -EAGAIN;
6441 	}
6442 	ioc->base_cmds.status = MPT3_CMD_PENDING;
6443 	mpi_request = mpt3sas_base_get_msg_frame(ioc, smid);
6444 	ioc->base_cmds.smid = smid;
6445 	memset(mpi_request, 0, sizeof(Mpi2EventNotificationRequest_t));
6446 	mpi_request->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
6447 	mpi_request->VF_ID = 0; /* TODO */
6448 	mpi_request->VP_ID = 0;
6449 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
6450 		mpi_request->EventMasks[i] =
6451 		    cpu_to_le32(ioc->event_masks[i]);
6452 	init_completion(&ioc->base_cmds.done);
6453 	ioc->put_smid_default(ioc, smid);
6454 	wait_for_completion_timeout(&ioc->base_cmds.done, 30*HZ);
6455 	if (!(ioc->base_cmds.status & MPT3_CMD_COMPLETE)) {
6456 		ioc_err(ioc, "%s: timeout\n", __func__);
6457 		_debug_dump_mf(mpi_request,
6458 		    sizeof(Mpi2EventNotificationRequest_t)/4);
6459 		if (ioc->base_cmds.status & MPT3_CMD_RESET)
6460 			r = -EFAULT;
6461 		else
6462 			r = -ETIME;
6463 	} else
6464 		dinitprintk(ioc, ioc_info(ioc, "%s: complete\n", __func__));
6465 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
6466 	return r;
6467 }
6468 
6469 /**
6470  * mpt3sas_base_validate_event_type - validating event types
6471  * @ioc: per adapter object
6472  * @event_type: firmware event
6473  *
6474  * This will turn on firmware event notification when application
6475  * ask for that event. We don't mask events that are already enabled.
6476  */
6477 void
6478 mpt3sas_base_validate_event_type(struct MPT3SAS_ADAPTER *ioc, u32 *event_type)
6479 {
6480 	int i, j;
6481 	u32 event_mask, desired_event;
6482 	u8 send_update_to_fw;
6483 
6484 	for (i = 0, send_update_to_fw = 0; i <
6485 	    MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++) {
6486 		event_mask = ~event_type[i];
6487 		desired_event = 1;
6488 		for (j = 0; j < 32; j++) {
6489 			if (!(event_mask & desired_event) &&
6490 			    (ioc->event_masks[i] & desired_event)) {
6491 				ioc->event_masks[i] &= ~desired_event;
6492 				send_update_to_fw = 1;
6493 			}
6494 			desired_event = (desired_event << 1);
6495 		}
6496 	}
6497 
6498 	if (!send_update_to_fw)
6499 		return;
6500 
6501 	mutex_lock(&ioc->base_cmds.mutex);
6502 	_base_event_notification(ioc);
6503 	mutex_unlock(&ioc->base_cmds.mutex);
6504 }
6505 
6506 /**
6507  * _base_diag_reset - the "big hammer" start of day reset
6508  * @ioc: per adapter object
6509  *
6510  * Return: 0 for success, non-zero for failure.
6511  */
6512 static int
6513 _base_diag_reset(struct MPT3SAS_ADAPTER *ioc)
6514 {
6515 	u32 host_diagnostic;
6516 	u32 ioc_state;
6517 	u32 count;
6518 	u32 hcb_size;
6519 
6520 	ioc_info(ioc, "sending diag reset !!\n");
6521 
6522 	drsprintk(ioc, ioc_info(ioc, "clear interrupts\n"));
6523 
6524 	count = 0;
6525 	do {
6526 		/* Write magic sequence to WriteSequence register
6527 		 * Loop until in diagnostic mode
6528 		 */
6529 		drsprintk(ioc, ioc_info(ioc, "write magic sequence\n"));
6530 		writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
6531 		writel(MPI2_WRSEQ_1ST_KEY_VALUE, &ioc->chip->WriteSequence);
6532 		writel(MPI2_WRSEQ_2ND_KEY_VALUE, &ioc->chip->WriteSequence);
6533 		writel(MPI2_WRSEQ_3RD_KEY_VALUE, &ioc->chip->WriteSequence);
6534 		writel(MPI2_WRSEQ_4TH_KEY_VALUE, &ioc->chip->WriteSequence);
6535 		writel(MPI2_WRSEQ_5TH_KEY_VALUE, &ioc->chip->WriteSequence);
6536 		writel(MPI2_WRSEQ_6TH_KEY_VALUE, &ioc->chip->WriteSequence);
6537 
6538 		/* wait 100 msec */
6539 		msleep(100);
6540 
6541 		if (count++ > 20)
6542 			goto out;
6543 
6544 		host_diagnostic = ioc->base_readl(&ioc->chip->HostDiagnostic);
6545 		drsprintk(ioc,
6546 			  ioc_info(ioc, "wrote magic sequence: count(%d), host_diagnostic(0x%08x)\n",
6547 				   count, host_diagnostic));
6548 
6549 	} while ((host_diagnostic & MPI2_DIAG_DIAG_WRITE_ENABLE) == 0);
6550 
6551 	hcb_size = ioc->base_readl(&ioc->chip->HCBSize);
6552 
6553 	drsprintk(ioc, ioc_info(ioc, "diag reset: issued\n"));
6554 	writel(host_diagnostic | MPI2_DIAG_RESET_ADAPTER,
6555 	     &ioc->chip->HostDiagnostic);
6556 
6557 	/*This delay allows the chip PCIe hardware time to finish reset tasks*/
6558 	msleep(MPI2_HARD_RESET_PCIE_FIRST_READ_DELAY_MICRO_SEC/1000);
6559 
6560 	/* Approximately 300 second max wait */
6561 	for (count = 0; count < (300000000 /
6562 		MPI2_HARD_RESET_PCIE_SECOND_READ_DELAY_MICRO_SEC); count++) {
6563 
6564 		host_diagnostic = ioc->base_readl(&ioc->chip->HostDiagnostic);
6565 
6566 		if (host_diagnostic == 0xFFFFFFFF)
6567 			goto out;
6568 		if (!(host_diagnostic & MPI2_DIAG_RESET_ADAPTER))
6569 			break;
6570 
6571 		msleep(MPI2_HARD_RESET_PCIE_SECOND_READ_DELAY_MICRO_SEC / 1000);
6572 	}
6573 
6574 	if (host_diagnostic & MPI2_DIAG_HCB_MODE) {
6575 
6576 		drsprintk(ioc,
6577 			  ioc_info(ioc, "restart the adapter assuming the HCB Address points to good F/W\n"));
6578 		host_diagnostic &= ~MPI2_DIAG_BOOT_DEVICE_SELECT_MASK;
6579 		host_diagnostic |= MPI2_DIAG_BOOT_DEVICE_SELECT_HCDW;
6580 		writel(host_diagnostic, &ioc->chip->HostDiagnostic);
6581 
6582 		drsprintk(ioc, ioc_info(ioc, "re-enable the HCDW\n"));
6583 		writel(hcb_size | MPI2_HCB_SIZE_HCB_ENABLE,
6584 		    &ioc->chip->HCBSize);
6585 	}
6586 
6587 	drsprintk(ioc, ioc_info(ioc, "restart the adapter\n"));
6588 	writel(host_diagnostic & ~MPI2_DIAG_HOLD_IOC_RESET,
6589 	    &ioc->chip->HostDiagnostic);
6590 
6591 	drsprintk(ioc,
6592 		  ioc_info(ioc, "disable writes to the diagnostic register\n"));
6593 	writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &ioc->chip->WriteSequence);
6594 
6595 	drsprintk(ioc, ioc_info(ioc, "Wait for FW to go to the READY state\n"));
6596 	ioc_state = _base_wait_on_iocstate(ioc, MPI2_IOC_STATE_READY, 20);
6597 	if (ioc_state) {
6598 		ioc_err(ioc, "%s: failed going to ready state (ioc_state=0x%x)\n",
6599 			__func__, ioc_state);
6600 		goto out;
6601 	}
6602 
6603 	ioc_info(ioc, "diag reset: SUCCESS\n");
6604 	return 0;
6605 
6606  out:
6607 	ioc_err(ioc, "diag reset: FAILED\n");
6608 	return -EFAULT;
6609 }
6610 
6611 /**
6612  * _base_make_ioc_ready - put controller in READY state
6613  * @ioc: per adapter object
6614  * @type: FORCE_BIG_HAMMER or SOFT_RESET
6615  *
6616  * Return: 0 for success, non-zero for failure.
6617  */
6618 static int
6619 _base_make_ioc_ready(struct MPT3SAS_ADAPTER *ioc, enum reset_type type)
6620 {
6621 	u32 ioc_state;
6622 	int rc;
6623 	int count;
6624 
6625 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6626 
6627 	if (ioc->pci_error_recovery)
6628 		return 0;
6629 
6630 	ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
6631 	dhsprintk(ioc,
6632 		  ioc_info(ioc, "%s: ioc_state(0x%08x)\n",
6633 			   __func__, ioc_state));
6634 
6635 	/* if in RESET state, it should move to READY state shortly */
6636 	count = 0;
6637 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_RESET) {
6638 		while ((ioc_state & MPI2_IOC_STATE_MASK) !=
6639 		    MPI2_IOC_STATE_READY) {
6640 			if (count++ == 10) {
6641 				ioc_err(ioc, "%s: failed going to ready state (ioc_state=0x%x)\n",
6642 					__func__, ioc_state);
6643 				return -EFAULT;
6644 			}
6645 			ssleep(1);
6646 			ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
6647 		}
6648 	}
6649 
6650 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_READY)
6651 		return 0;
6652 
6653 	if (ioc_state & MPI2_DOORBELL_USED) {
6654 		dhsprintk(ioc, ioc_info(ioc, "unexpected doorbell active!\n"));
6655 		goto issue_diag_reset;
6656 	}
6657 
6658 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
6659 		mpt3sas_base_fault_info(ioc, ioc_state &
6660 		    MPI2_DOORBELL_DATA_MASK);
6661 		goto issue_diag_reset;
6662 	}
6663 
6664 	if (type == FORCE_BIG_HAMMER)
6665 		goto issue_diag_reset;
6666 
6667 	if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_OPERATIONAL)
6668 		if (!(_base_send_ioc_reset(ioc,
6669 		    MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET, 15))) {
6670 			return 0;
6671 	}
6672 
6673  issue_diag_reset:
6674 	rc = _base_diag_reset(ioc);
6675 	return rc;
6676 }
6677 
6678 /**
6679  * _base_make_ioc_operational - put controller in OPERATIONAL state
6680  * @ioc: per adapter object
6681  *
6682  * Return: 0 for success, non-zero for failure.
6683  */
6684 static int
6685 _base_make_ioc_operational(struct MPT3SAS_ADAPTER *ioc)
6686 {
6687 	int r, i, index;
6688 	unsigned long	flags;
6689 	u32 reply_address;
6690 	u16 smid;
6691 	struct _tr_list *delayed_tr, *delayed_tr_next;
6692 	struct _sc_list *delayed_sc, *delayed_sc_next;
6693 	struct _event_ack_list *delayed_event_ack, *delayed_event_ack_next;
6694 	u8 hide_flag;
6695 	struct adapter_reply_queue *reply_q;
6696 	Mpi2ReplyDescriptorsUnion_t *reply_post_free_contig;
6697 
6698 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6699 
6700 	/* clean the delayed target reset list */
6701 	list_for_each_entry_safe(delayed_tr, delayed_tr_next,
6702 	    &ioc->delayed_tr_list, list) {
6703 		list_del(&delayed_tr->list);
6704 		kfree(delayed_tr);
6705 	}
6706 
6707 
6708 	list_for_each_entry_safe(delayed_tr, delayed_tr_next,
6709 	    &ioc->delayed_tr_volume_list, list) {
6710 		list_del(&delayed_tr->list);
6711 		kfree(delayed_tr);
6712 	}
6713 
6714 	list_for_each_entry_safe(delayed_sc, delayed_sc_next,
6715 	    &ioc->delayed_sc_list, list) {
6716 		list_del(&delayed_sc->list);
6717 		kfree(delayed_sc);
6718 	}
6719 
6720 	list_for_each_entry_safe(delayed_event_ack, delayed_event_ack_next,
6721 	    &ioc->delayed_event_ack_list, list) {
6722 		list_del(&delayed_event_ack->list);
6723 		kfree(delayed_event_ack);
6724 	}
6725 
6726 	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
6727 
6728 	/* hi-priority queue */
6729 	INIT_LIST_HEAD(&ioc->hpr_free_list);
6730 	smid = ioc->hi_priority_smid;
6731 	for (i = 0; i < ioc->hi_priority_depth; i++, smid++) {
6732 		ioc->hpr_lookup[i].cb_idx = 0xFF;
6733 		ioc->hpr_lookup[i].smid = smid;
6734 		list_add_tail(&ioc->hpr_lookup[i].tracker_list,
6735 		    &ioc->hpr_free_list);
6736 	}
6737 
6738 	/* internal queue */
6739 	INIT_LIST_HEAD(&ioc->internal_free_list);
6740 	smid = ioc->internal_smid;
6741 	for (i = 0; i < ioc->internal_depth; i++, smid++) {
6742 		ioc->internal_lookup[i].cb_idx = 0xFF;
6743 		ioc->internal_lookup[i].smid = smid;
6744 		list_add_tail(&ioc->internal_lookup[i].tracker_list,
6745 		    &ioc->internal_free_list);
6746 	}
6747 
6748 	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
6749 
6750 	/* initialize Reply Free Queue */
6751 	for (i = 0, reply_address = (u32)ioc->reply_dma ;
6752 	    i < ioc->reply_free_queue_depth ; i++, reply_address +=
6753 	    ioc->reply_sz) {
6754 		ioc->reply_free[i] = cpu_to_le32(reply_address);
6755 		if (ioc->is_mcpu_endpoint)
6756 			_base_clone_reply_to_sys_mem(ioc,
6757 					reply_address, i);
6758 	}
6759 
6760 	/* initialize reply queues */
6761 	if (ioc->is_driver_loading)
6762 		_base_assign_reply_queues(ioc);
6763 
6764 	/* initialize Reply Post Free Queue */
6765 	index = 0;
6766 	reply_post_free_contig = ioc->reply_post[0].reply_post_free;
6767 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
6768 		/*
6769 		 * If RDPQ is enabled, switch to the next allocation.
6770 		 * Otherwise advance within the contiguous region.
6771 		 */
6772 		if (ioc->rdpq_array_enable) {
6773 			reply_q->reply_post_free =
6774 				ioc->reply_post[index++].reply_post_free;
6775 		} else {
6776 			reply_q->reply_post_free = reply_post_free_contig;
6777 			reply_post_free_contig += ioc->reply_post_queue_depth;
6778 		}
6779 
6780 		reply_q->reply_post_host_index = 0;
6781 		for (i = 0; i < ioc->reply_post_queue_depth; i++)
6782 			reply_q->reply_post_free[i].Words =
6783 			    cpu_to_le64(ULLONG_MAX);
6784 		if (!_base_is_controller_msix_enabled(ioc))
6785 			goto skip_init_reply_post_free_queue;
6786 	}
6787  skip_init_reply_post_free_queue:
6788 
6789 	r = _base_send_ioc_init(ioc);
6790 	if (r)
6791 		return r;
6792 
6793 	/* initialize reply free host index */
6794 	ioc->reply_free_host_index = ioc->reply_free_queue_depth - 1;
6795 	writel(ioc->reply_free_host_index, &ioc->chip->ReplyFreeHostIndex);
6796 
6797 	/* initialize reply post host index */
6798 	list_for_each_entry(reply_q, &ioc->reply_queue_list, list) {
6799 		if (ioc->combined_reply_queue)
6800 			writel((reply_q->msix_index & 7)<<
6801 			   MPI2_RPHI_MSIX_INDEX_SHIFT,
6802 			   ioc->replyPostRegisterIndex[reply_q->msix_index/8]);
6803 		else
6804 			writel(reply_q->msix_index <<
6805 				MPI2_RPHI_MSIX_INDEX_SHIFT,
6806 				&ioc->chip->ReplyPostHostIndex);
6807 
6808 		if (!_base_is_controller_msix_enabled(ioc))
6809 			goto skip_init_reply_post_host_index;
6810 	}
6811 
6812  skip_init_reply_post_host_index:
6813 
6814 	_base_unmask_interrupts(ioc);
6815 
6816 	if (ioc->hba_mpi_version_belonged != MPI2_VERSION) {
6817 		r = _base_display_fwpkg_version(ioc);
6818 		if (r)
6819 			return r;
6820 	}
6821 
6822 	_base_static_config_pages(ioc);
6823 	r = _base_event_notification(ioc);
6824 	if (r)
6825 		return r;
6826 
6827 	if (ioc->is_driver_loading) {
6828 
6829 		if (ioc->is_warpdrive && ioc->manu_pg10.OEMIdentifier
6830 		    == 0x80) {
6831 			hide_flag = (u8) (
6832 			    le32_to_cpu(ioc->manu_pg10.OEMSpecificFlags0) &
6833 			    MFG_PAGE10_HIDE_SSDS_MASK);
6834 			if (hide_flag != MFG_PAGE10_HIDE_SSDS_MASK)
6835 				ioc->mfg_pg10_hide_flag = hide_flag;
6836 		}
6837 
6838 		ioc->wait_for_discovery_to_complete =
6839 		    _base_determine_wait_on_discovery(ioc);
6840 
6841 		return r; /* scan_start and scan_finished support */
6842 	}
6843 
6844 	r = _base_send_port_enable(ioc);
6845 	if (r)
6846 		return r;
6847 
6848 	return r;
6849 }
6850 
6851 /**
6852  * mpt3sas_base_free_resources - free resources controller resources
6853  * @ioc: per adapter object
6854  */
6855 void
6856 mpt3sas_base_free_resources(struct MPT3SAS_ADAPTER *ioc)
6857 {
6858 	dexitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6859 
6860 	/* synchronizing freeing resource with pci_access_mutex lock */
6861 	mutex_lock(&ioc->pci_access_mutex);
6862 	if (ioc->chip_phys && ioc->chip) {
6863 		_base_mask_interrupts(ioc);
6864 		ioc->shost_recovery = 1;
6865 		_base_make_ioc_ready(ioc, SOFT_RESET);
6866 		ioc->shost_recovery = 0;
6867 	}
6868 
6869 	mpt3sas_base_unmap_resources(ioc);
6870 	mutex_unlock(&ioc->pci_access_mutex);
6871 	return;
6872 }
6873 
6874 /**
6875  * mpt3sas_base_attach - attach controller instance
6876  * @ioc: per adapter object
6877  *
6878  * Return: 0 for success, non-zero for failure.
6879  */
6880 int
6881 mpt3sas_base_attach(struct MPT3SAS_ADAPTER *ioc)
6882 {
6883 	int r, i;
6884 	int cpu_id, last_cpu_id = 0;
6885 
6886 	dinitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
6887 
6888 	/* setup cpu_msix_table */
6889 	ioc->cpu_count = num_online_cpus();
6890 	for_each_online_cpu(cpu_id)
6891 		last_cpu_id = cpu_id;
6892 	ioc->cpu_msix_table_sz = last_cpu_id + 1;
6893 	ioc->cpu_msix_table = kzalloc(ioc->cpu_msix_table_sz, GFP_KERNEL);
6894 	ioc->reply_queue_count = 1;
6895 	if (!ioc->cpu_msix_table) {
6896 		dfailprintk(ioc,
6897 			    ioc_info(ioc, "allocation for cpu_msix_table failed!!!\n"));
6898 		r = -ENOMEM;
6899 		goto out_free_resources;
6900 	}
6901 
6902 	if (ioc->is_warpdrive) {
6903 		ioc->reply_post_host_index = kcalloc(ioc->cpu_msix_table_sz,
6904 		    sizeof(resource_size_t *), GFP_KERNEL);
6905 		if (!ioc->reply_post_host_index) {
6906 			dfailprintk(ioc,
6907 				    ioc_info(ioc, "allocation for reply_post_host_index failed!!!\n"));
6908 			r = -ENOMEM;
6909 			goto out_free_resources;
6910 		}
6911 	}
6912 
6913 	ioc->smp_affinity_enable = smp_affinity_enable;
6914 
6915 	ioc->rdpq_array_enable_assigned = 0;
6916 	ioc->dma_mask = 0;
6917 	if (ioc->is_aero_ioc)
6918 		ioc->base_readl = &_base_readl_aero;
6919 	else
6920 		ioc->base_readl = &_base_readl;
6921 	r = mpt3sas_base_map_resources(ioc);
6922 	if (r)
6923 		goto out_free_resources;
6924 
6925 	pci_set_drvdata(ioc->pdev, ioc->shost);
6926 	r = _base_get_ioc_facts(ioc);
6927 	if (r)
6928 		goto out_free_resources;
6929 
6930 	switch (ioc->hba_mpi_version_belonged) {
6931 	case MPI2_VERSION:
6932 		ioc->build_sg_scmd = &_base_build_sg_scmd;
6933 		ioc->build_sg = &_base_build_sg;
6934 		ioc->build_zero_len_sge = &_base_build_zero_len_sge;
6935 		ioc->get_msix_index_for_smlio = &_base_get_msix_index;
6936 		break;
6937 	case MPI25_VERSION:
6938 	case MPI26_VERSION:
6939 		/*
6940 		 * In SAS3.0,
6941 		 * SCSI_IO, SMP_PASSTHRU, SATA_PASSTHRU, Target Assist, and
6942 		 * Target Status - all require the IEEE formated scatter gather
6943 		 * elements.
6944 		 */
6945 		ioc->build_sg_scmd = &_base_build_sg_scmd_ieee;
6946 		ioc->build_sg = &_base_build_sg_ieee;
6947 		ioc->build_nvme_prp = &_base_build_nvme_prp;
6948 		ioc->build_zero_len_sge = &_base_build_zero_len_sge_ieee;
6949 		ioc->sge_size_ieee = sizeof(Mpi2IeeeSgeSimple64_t);
6950 		if (ioc->high_iops_queues)
6951 			ioc->get_msix_index_for_smlio =
6952 					&_base_get_high_iops_msix_index;
6953 		else
6954 			ioc->get_msix_index_for_smlio = &_base_get_msix_index;
6955 		break;
6956 	}
6957 	if (ioc->atomic_desc_capable) {
6958 		ioc->put_smid_default = &_base_put_smid_default_atomic;
6959 		ioc->put_smid_scsi_io = &_base_put_smid_scsi_io_atomic;
6960 		ioc->put_smid_fast_path =
6961 				&_base_put_smid_fast_path_atomic;
6962 		ioc->put_smid_hi_priority =
6963 				&_base_put_smid_hi_priority_atomic;
6964 	} else {
6965 		ioc->put_smid_default = &_base_put_smid_default;
6966 		ioc->put_smid_fast_path = &_base_put_smid_fast_path;
6967 		ioc->put_smid_hi_priority = &_base_put_smid_hi_priority;
6968 		if (ioc->is_mcpu_endpoint)
6969 			ioc->put_smid_scsi_io =
6970 				&_base_put_smid_mpi_ep_scsi_io;
6971 		else
6972 			ioc->put_smid_scsi_io = &_base_put_smid_scsi_io;
6973 	}
6974 	/*
6975 	 * These function pointers for other requests that don't
6976 	 * the require IEEE scatter gather elements.
6977 	 *
6978 	 * For example Configuration Pages and SAS IOUNIT Control don't.
6979 	 */
6980 	ioc->build_sg_mpi = &_base_build_sg;
6981 	ioc->build_zero_len_sge_mpi = &_base_build_zero_len_sge;
6982 
6983 	r = _base_make_ioc_ready(ioc, SOFT_RESET);
6984 	if (r)
6985 		goto out_free_resources;
6986 
6987 	ioc->pfacts = kcalloc(ioc->facts.NumberOfPorts,
6988 	    sizeof(struct mpt3sas_port_facts), GFP_KERNEL);
6989 	if (!ioc->pfacts) {
6990 		r = -ENOMEM;
6991 		goto out_free_resources;
6992 	}
6993 
6994 	for (i = 0 ; i < ioc->facts.NumberOfPorts; i++) {
6995 		r = _base_get_port_facts(ioc, i);
6996 		if (r)
6997 			goto out_free_resources;
6998 	}
6999 
7000 	r = _base_allocate_memory_pools(ioc);
7001 	if (r)
7002 		goto out_free_resources;
7003 
7004 	if (irqpoll_weight > 0)
7005 		ioc->thresh_hold = irqpoll_weight;
7006 	else
7007 		ioc->thresh_hold = ioc->hba_queue_depth/4;
7008 
7009 	_base_init_irqpolls(ioc);
7010 	init_waitqueue_head(&ioc->reset_wq);
7011 
7012 	/* allocate memory pd handle bitmask list */
7013 	ioc->pd_handles_sz = (ioc->facts.MaxDevHandle / 8);
7014 	if (ioc->facts.MaxDevHandle % 8)
7015 		ioc->pd_handles_sz++;
7016 	ioc->pd_handles = kzalloc(ioc->pd_handles_sz,
7017 	    GFP_KERNEL);
7018 	if (!ioc->pd_handles) {
7019 		r = -ENOMEM;
7020 		goto out_free_resources;
7021 	}
7022 	ioc->blocking_handles = kzalloc(ioc->pd_handles_sz,
7023 	    GFP_KERNEL);
7024 	if (!ioc->blocking_handles) {
7025 		r = -ENOMEM;
7026 		goto out_free_resources;
7027 	}
7028 
7029 	/* allocate memory for pending OS device add list */
7030 	ioc->pend_os_device_add_sz = (ioc->facts.MaxDevHandle / 8);
7031 	if (ioc->facts.MaxDevHandle % 8)
7032 		ioc->pend_os_device_add_sz++;
7033 	ioc->pend_os_device_add = kzalloc(ioc->pend_os_device_add_sz,
7034 	    GFP_KERNEL);
7035 	if (!ioc->pend_os_device_add)
7036 		goto out_free_resources;
7037 
7038 	ioc->device_remove_in_progress_sz = ioc->pend_os_device_add_sz;
7039 	ioc->device_remove_in_progress =
7040 		kzalloc(ioc->device_remove_in_progress_sz, GFP_KERNEL);
7041 	if (!ioc->device_remove_in_progress)
7042 		goto out_free_resources;
7043 
7044 	ioc->fwfault_debug = mpt3sas_fwfault_debug;
7045 
7046 	/* base internal command bits */
7047 	mutex_init(&ioc->base_cmds.mutex);
7048 	ioc->base_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
7049 	ioc->base_cmds.status = MPT3_CMD_NOT_USED;
7050 
7051 	/* port_enable command bits */
7052 	ioc->port_enable_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
7053 	ioc->port_enable_cmds.status = MPT3_CMD_NOT_USED;
7054 
7055 	/* transport internal command bits */
7056 	ioc->transport_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
7057 	ioc->transport_cmds.status = MPT3_CMD_NOT_USED;
7058 	mutex_init(&ioc->transport_cmds.mutex);
7059 
7060 	/* scsih internal command bits */
7061 	ioc->scsih_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
7062 	ioc->scsih_cmds.status = MPT3_CMD_NOT_USED;
7063 	mutex_init(&ioc->scsih_cmds.mutex);
7064 
7065 	/* task management internal command bits */
7066 	ioc->tm_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
7067 	ioc->tm_cmds.status = MPT3_CMD_NOT_USED;
7068 	mutex_init(&ioc->tm_cmds.mutex);
7069 
7070 	/* config page internal command bits */
7071 	ioc->config_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
7072 	ioc->config_cmds.status = MPT3_CMD_NOT_USED;
7073 	mutex_init(&ioc->config_cmds.mutex);
7074 
7075 	/* ctl module internal command bits */
7076 	ioc->ctl_cmds.reply = kzalloc(ioc->reply_sz, GFP_KERNEL);
7077 	ioc->ctl_cmds.sense = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
7078 	ioc->ctl_cmds.status = MPT3_CMD_NOT_USED;
7079 	mutex_init(&ioc->ctl_cmds.mutex);
7080 
7081 	if (!ioc->base_cmds.reply || !ioc->port_enable_cmds.reply ||
7082 	    !ioc->transport_cmds.reply || !ioc->scsih_cmds.reply ||
7083 	    !ioc->tm_cmds.reply || !ioc->config_cmds.reply ||
7084 	    !ioc->ctl_cmds.reply || !ioc->ctl_cmds.sense) {
7085 		r = -ENOMEM;
7086 		goto out_free_resources;
7087 	}
7088 
7089 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
7090 		ioc->event_masks[i] = -1;
7091 
7092 	/* here we enable the events we care about */
7093 	_base_unmask_events(ioc, MPI2_EVENT_SAS_DISCOVERY);
7094 	_base_unmask_events(ioc, MPI2_EVENT_SAS_BROADCAST_PRIMITIVE);
7095 	_base_unmask_events(ioc, MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST);
7096 	_base_unmask_events(ioc, MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE);
7097 	_base_unmask_events(ioc, MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE);
7098 	_base_unmask_events(ioc, MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST);
7099 	_base_unmask_events(ioc, MPI2_EVENT_IR_VOLUME);
7100 	_base_unmask_events(ioc, MPI2_EVENT_IR_PHYSICAL_DISK);
7101 	_base_unmask_events(ioc, MPI2_EVENT_IR_OPERATION_STATUS);
7102 	_base_unmask_events(ioc, MPI2_EVENT_LOG_ENTRY_ADDED);
7103 	_base_unmask_events(ioc, MPI2_EVENT_TEMP_THRESHOLD);
7104 	_base_unmask_events(ioc, MPI2_EVENT_ACTIVE_CABLE_EXCEPTION);
7105 	_base_unmask_events(ioc, MPI2_EVENT_SAS_DEVICE_DISCOVERY_ERROR);
7106 	if (ioc->hba_mpi_version_belonged == MPI26_VERSION) {
7107 		if (ioc->is_gen35_ioc) {
7108 			_base_unmask_events(ioc,
7109 				MPI2_EVENT_PCIE_DEVICE_STATUS_CHANGE);
7110 			_base_unmask_events(ioc, MPI2_EVENT_PCIE_ENUMERATION);
7111 			_base_unmask_events(ioc,
7112 				MPI2_EVENT_PCIE_TOPOLOGY_CHANGE_LIST);
7113 		}
7114 	}
7115 	r = _base_make_ioc_operational(ioc);
7116 	if (r)
7117 		goto out_free_resources;
7118 
7119 	ioc->non_operational_loop = 0;
7120 	ioc->got_task_abort_from_ioctl = 0;
7121 	return 0;
7122 
7123  out_free_resources:
7124 
7125 	ioc->remove_host = 1;
7126 
7127 	mpt3sas_base_free_resources(ioc);
7128 	_base_release_memory_pools(ioc);
7129 	pci_set_drvdata(ioc->pdev, NULL);
7130 	kfree(ioc->cpu_msix_table);
7131 	if (ioc->is_warpdrive)
7132 		kfree(ioc->reply_post_host_index);
7133 	kfree(ioc->pd_handles);
7134 	kfree(ioc->blocking_handles);
7135 	kfree(ioc->device_remove_in_progress);
7136 	kfree(ioc->pend_os_device_add);
7137 	kfree(ioc->tm_cmds.reply);
7138 	kfree(ioc->transport_cmds.reply);
7139 	kfree(ioc->scsih_cmds.reply);
7140 	kfree(ioc->config_cmds.reply);
7141 	kfree(ioc->base_cmds.reply);
7142 	kfree(ioc->port_enable_cmds.reply);
7143 	kfree(ioc->ctl_cmds.reply);
7144 	kfree(ioc->ctl_cmds.sense);
7145 	kfree(ioc->pfacts);
7146 	ioc->ctl_cmds.reply = NULL;
7147 	ioc->base_cmds.reply = NULL;
7148 	ioc->tm_cmds.reply = NULL;
7149 	ioc->scsih_cmds.reply = NULL;
7150 	ioc->transport_cmds.reply = NULL;
7151 	ioc->config_cmds.reply = NULL;
7152 	ioc->pfacts = NULL;
7153 	return r;
7154 }
7155 
7156 
7157 /**
7158  * mpt3sas_base_detach - remove controller instance
7159  * @ioc: per adapter object
7160  */
7161 void
7162 mpt3sas_base_detach(struct MPT3SAS_ADAPTER *ioc)
7163 {
7164 	dexitprintk(ioc, ioc_info(ioc, "%s\n", __func__));
7165 
7166 	mpt3sas_base_stop_watchdog(ioc);
7167 	mpt3sas_base_free_resources(ioc);
7168 	_base_release_memory_pools(ioc);
7169 	mpt3sas_free_enclosure_list(ioc);
7170 	pci_set_drvdata(ioc->pdev, NULL);
7171 	kfree(ioc->cpu_msix_table);
7172 	if (ioc->is_warpdrive)
7173 		kfree(ioc->reply_post_host_index);
7174 	kfree(ioc->pd_handles);
7175 	kfree(ioc->blocking_handles);
7176 	kfree(ioc->device_remove_in_progress);
7177 	kfree(ioc->pend_os_device_add);
7178 	kfree(ioc->pfacts);
7179 	kfree(ioc->ctl_cmds.reply);
7180 	kfree(ioc->ctl_cmds.sense);
7181 	kfree(ioc->base_cmds.reply);
7182 	kfree(ioc->port_enable_cmds.reply);
7183 	kfree(ioc->tm_cmds.reply);
7184 	kfree(ioc->transport_cmds.reply);
7185 	kfree(ioc->scsih_cmds.reply);
7186 	kfree(ioc->config_cmds.reply);
7187 }
7188 
7189 /**
7190  * _base_pre_reset_handler - pre reset handler
7191  * @ioc: per adapter object
7192  */
7193 static void _base_pre_reset_handler(struct MPT3SAS_ADAPTER *ioc)
7194 {
7195 	mpt3sas_scsih_pre_reset_handler(ioc);
7196 	mpt3sas_ctl_pre_reset_handler(ioc);
7197 	dtmprintk(ioc, ioc_info(ioc, "%s: MPT3_IOC_PRE_RESET\n", __func__));
7198 }
7199 
7200 /**
7201  * _base_after_reset_handler - after reset handler
7202  * @ioc: per adapter object
7203  */
7204 static void _base_after_reset_handler(struct MPT3SAS_ADAPTER *ioc)
7205 {
7206 	mpt3sas_scsih_after_reset_handler(ioc);
7207 	mpt3sas_ctl_after_reset_handler(ioc);
7208 	dtmprintk(ioc, ioc_info(ioc, "%s: MPT3_IOC_AFTER_RESET\n", __func__));
7209 	if (ioc->transport_cmds.status & MPT3_CMD_PENDING) {
7210 		ioc->transport_cmds.status |= MPT3_CMD_RESET;
7211 		mpt3sas_base_free_smid(ioc, ioc->transport_cmds.smid);
7212 		complete(&ioc->transport_cmds.done);
7213 	}
7214 	if (ioc->base_cmds.status & MPT3_CMD_PENDING) {
7215 		ioc->base_cmds.status |= MPT3_CMD_RESET;
7216 		mpt3sas_base_free_smid(ioc, ioc->base_cmds.smid);
7217 		complete(&ioc->base_cmds.done);
7218 	}
7219 	if (ioc->port_enable_cmds.status & MPT3_CMD_PENDING) {
7220 		ioc->port_enable_failed = 1;
7221 		ioc->port_enable_cmds.status |= MPT3_CMD_RESET;
7222 		mpt3sas_base_free_smid(ioc, ioc->port_enable_cmds.smid);
7223 		if (ioc->is_driver_loading) {
7224 			ioc->start_scan_failed =
7225 				MPI2_IOCSTATUS_INTERNAL_ERROR;
7226 			ioc->start_scan = 0;
7227 			ioc->port_enable_cmds.status =
7228 				MPT3_CMD_NOT_USED;
7229 		} else {
7230 			complete(&ioc->port_enable_cmds.done);
7231 		}
7232 	}
7233 	if (ioc->config_cmds.status & MPT3_CMD_PENDING) {
7234 		ioc->config_cmds.status |= MPT3_CMD_RESET;
7235 		mpt3sas_base_free_smid(ioc, ioc->config_cmds.smid);
7236 		ioc->config_cmds.smid = USHRT_MAX;
7237 		complete(&ioc->config_cmds.done);
7238 	}
7239 }
7240 
7241 /**
7242  * _base_reset_done_handler - reset done handler
7243  * @ioc: per adapter object
7244  */
7245 static void _base_reset_done_handler(struct MPT3SAS_ADAPTER *ioc)
7246 {
7247 	mpt3sas_scsih_reset_done_handler(ioc);
7248 	mpt3sas_ctl_reset_done_handler(ioc);
7249 	dtmprintk(ioc, ioc_info(ioc, "%s: MPT3_IOC_DONE_RESET\n", __func__));
7250 }
7251 
7252 /**
7253  * mpt3sas_wait_for_commands_to_complete - reset controller
7254  * @ioc: Pointer to MPT_ADAPTER structure
7255  *
7256  * This function is waiting 10s for all pending commands to complete
7257  * prior to putting controller in reset.
7258  */
7259 void
7260 mpt3sas_wait_for_commands_to_complete(struct MPT3SAS_ADAPTER *ioc)
7261 {
7262 	u32 ioc_state;
7263 
7264 	ioc->pending_io_count = 0;
7265 
7266 	ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
7267 	if ((ioc_state & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_OPERATIONAL)
7268 		return;
7269 
7270 	/* pending command count */
7271 	ioc->pending_io_count = scsi_host_busy(ioc->shost);
7272 
7273 	if (!ioc->pending_io_count)
7274 		return;
7275 
7276 	/* wait for pending commands to complete */
7277 	wait_event_timeout(ioc->reset_wq, ioc->pending_io_count == 0, 10 * HZ);
7278 }
7279 
7280 /**
7281  * mpt3sas_base_hard_reset_handler - reset controller
7282  * @ioc: Pointer to MPT_ADAPTER structure
7283  * @type: FORCE_BIG_HAMMER or SOFT_RESET
7284  *
7285  * Return: 0 for success, non-zero for failure.
7286  */
7287 int
7288 mpt3sas_base_hard_reset_handler(struct MPT3SAS_ADAPTER *ioc,
7289 	enum reset_type type)
7290 {
7291 	int r;
7292 	unsigned long flags;
7293 	u32 ioc_state;
7294 	u8 is_fault = 0, is_trigger = 0;
7295 
7296 	dtmprintk(ioc, ioc_info(ioc, "%s: enter\n", __func__));
7297 
7298 	if (ioc->pci_error_recovery) {
7299 		ioc_err(ioc, "%s: pci error recovery reset\n", __func__);
7300 		r = 0;
7301 		goto out_unlocked;
7302 	}
7303 
7304 	if (mpt3sas_fwfault_debug)
7305 		mpt3sas_halt_firmware(ioc);
7306 
7307 	/* wait for an active reset in progress to complete */
7308 	mutex_lock(&ioc->reset_in_progress_mutex);
7309 
7310 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
7311 	ioc->shost_recovery = 1;
7312 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
7313 
7314 	if ((ioc->diag_buffer_status[MPI2_DIAG_BUF_TYPE_TRACE] &
7315 	    MPT3_DIAG_BUFFER_IS_REGISTERED) &&
7316 	    (!(ioc->diag_buffer_status[MPI2_DIAG_BUF_TYPE_TRACE] &
7317 	    MPT3_DIAG_BUFFER_IS_RELEASED))) {
7318 		is_trigger = 1;
7319 		ioc_state = mpt3sas_base_get_iocstate(ioc, 0);
7320 		if ((ioc_state & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT)
7321 			is_fault = 1;
7322 	}
7323 	_base_pre_reset_handler(ioc);
7324 	mpt3sas_wait_for_commands_to_complete(ioc);
7325 	_base_mask_interrupts(ioc);
7326 	r = _base_make_ioc_ready(ioc, type);
7327 	if (r)
7328 		goto out;
7329 	_base_after_reset_handler(ioc);
7330 
7331 	/* If this hard reset is called while port enable is active, then
7332 	 * there is no reason to call make_ioc_operational
7333 	 */
7334 	if (ioc->is_driver_loading && ioc->port_enable_failed) {
7335 		ioc->remove_host = 1;
7336 		r = -EFAULT;
7337 		goto out;
7338 	}
7339 	r = _base_get_ioc_facts(ioc);
7340 	if (r)
7341 		goto out;
7342 
7343 	if (ioc->rdpq_array_enable && !ioc->rdpq_array_capable)
7344 		panic("%s: Issue occurred with flashing controller firmware."
7345 		      "Please reboot the system and ensure that the correct"
7346 		      " firmware version is running\n", ioc->name);
7347 
7348 	r = _base_make_ioc_operational(ioc);
7349 	if (!r)
7350 		_base_reset_done_handler(ioc);
7351 
7352  out:
7353 	dtmprintk(ioc,
7354 		  ioc_info(ioc, "%s: %s\n",
7355 			   __func__, r == 0 ? "SUCCESS" : "FAILED"));
7356 
7357 	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
7358 	ioc->shost_recovery = 0;
7359 	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
7360 	ioc->ioc_reset_count++;
7361 	mutex_unlock(&ioc->reset_in_progress_mutex);
7362 
7363  out_unlocked:
7364 	if ((r == 0) && is_trigger) {
7365 		if (is_fault)
7366 			mpt3sas_trigger_master(ioc, MASTER_TRIGGER_FW_FAULT);
7367 		else
7368 			mpt3sas_trigger_master(ioc,
7369 			    MASTER_TRIGGER_ADAPTER_RESET);
7370 	}
7371 	dtmprintk(ioc, ioc_info(ioc, "%s: exit\n", __func__));
7372 	return r;
7373 }
7374