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