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