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