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