1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Linux MegaRAID driver for SAS based RAID controllers
4  *
5  *  Copyright (c) 2009-2013  LSI Corporation
6  *  Copyright (c) 2013-2016  Avago Technologies
7  *  Copyright (c) 2016-2018  Broadcom Inc.
8  *
9  *  FILE: megaraid_sas_fp.c
10  *
11  *  Authors: Broadcom Inc.
12  *           Sumant Patro
13  *           Varad Talamacki
14  *           Manoj Jose
15  *           Kashyap Desai <kashyap.desai@broadcom.com>
16  *           Sumit Saxena <sumit.saxena@broadcom.com>
17  *
18  *  Send feedback to: megaraidlinux.pdl@broadcom.com
19  */
20 
21 #include <linux/kernel.h>
22 #include <linux/types.h>
23 #include <linux/pci.h>
24 #include <linux/list.h>
25 #include <linux/moduleparam.h>
26 #include <linux/module.h>
27 #include <linux/spinlock.h>
28 #include <linux/interrupt.h>
29 #include <linux/delay.h>
30 #include <linux/uio.h>
31 #include <linux/uaccess.h>
32 #include <linux/fs.h>
33 #include <linux/compat.h>
34 #include <linux/blkdev.h>
35 #include <linux/poll.h>
36 
37 #include <scsi/scsi.h>
38 #include <scsi/scsi_cmnd.h>
39 #include <scsi/scsi_device.h>
40 #include <scsi/scsi_host.h>
41 
42 #include "megaraid_sas_fusion.h"
43 #include "megaraid_sas.h"
44 #include <asm/div64.h>
45 
46 #define LB_PENDING_CMDS_DEFAULT 4
47 static unsigned int lb_pending_cmds = LB_PENDING_CMDS_DEFAULT;
48 module_param(lb_pending_cmds, int, S_IRUGO);
49 MODULE_PARM_DESC(lb_pending_cmds, "Change raid-1 load balancing outstanding "
50 	"threshold. Valid Values are 1-128. Default: 4");
51 
52 
53 #define ABS_DIFF(a, b)   (((a) > (b)) ? ((a) - (b)) : ((b) - (a)))
54 #define MR_LD_STATE_OPTIMAL 3
55 
56 #define SPAN_ROW_SIZE(map, ld, index_) (MR_LdSpanPtrGet(ld, index_, map)->spanRowSize)
57 #define SPAN_ROW_DATA_SIZE(map_, ld, index_)   (MR_LdSpanPtrGet(ld, index_, map)->spanRowDataSize)
58 #define SPAN_INVALID  0xff
59 
60 /* Prototypes */
61 static void mr_update_span_set(struct MR_DRV_RAID_MAP_ALL *map,
62 	PLD_SPAN_INFO ldSpanInfo);
63 static u8 mr_spanset_get_phy_params(struct megasas_instance *instance, u32 ld,
64 	u64 stripRow, u16 stripRef, struct IO_REQUEST_INFO *io_info,
65 	struct RAID_CONTEXT *pRAID_Context, struct MR_DRV_RAID_MAP_ALL *map);
66 static u64 get_row_from_strip(struct megasas_instance *instance, u32 ld,
67 	u64 strip, struct MR_DRV_RAID_MAP_ALL *map);
68 
69 u32 mega_mod64(u64 dividend, u32 divisor)
70 {
71 	u64 d;
72 	u32 remainder;
73 
74 	if (!divisor)
75 		printk(KERN_ERR "megasas : DIVISOR is zero, in div fn\n");
76 	d = dividend;
77 	remainder = do_div(d, divisor);
78 	return remainder;
79 }
80 
81 /**
82  * @param dividend    : Dividend
83  * @param divisor    : Divisor
84  *
85  * @return quotient
86  **/
87 u64 mega_div64_32(uint64_t dividend, uint32_t divisor)
88 {
89 	u32 remainder;
90 	u64 d;
91 
92 	if (!divisor)
93 		printk(KERN_ERR "megasas : DIVISOR is zero in mod fn\n");
94 
95 	d = dividend;
96 	remainder = do_div(d, divisor);
97 
98 	return d;
99 }
100 
101 struct MR_LD_RAID *MR_LdRaidGet(u32 ld, struct MR_DRV_RAID_MAP_ALL *map)
102 {
103 	return &map->raidMap.ldSpanMap[ld].ldRaid;
104 }
105 
106 static struct MR_SPAN_BLOCK_INFO *MR_LdSpanInfoGet(u32 ld,
107 						   struct MR_DRV_RAID_MAP_ALL
108 						   *map)
109 {
110 	return &map->raidMap.ldSpanMap[ld].spanBlock[0];
111 }
112 
113 static u8 MR_LdDataArmGet(u32 ld, u32 armIdx, struct MR_DRV_RAID_MAP_ALL *map)
114 {
115 	return map->raidMap.ldSpanMap[ld].dataArmMap[armIdx];
116 }
117 
118 u16 MR_ArPdGet(u32 ar, u32 arm, struct MR_DRV_RAID_MAP_ALL *map)
119 {
120 	return le16_to_cpu(map->raidMap.arMapInfo[ar].pd[arm]);
121 }
122 
123 u16 MR_LdSpanArrayGet(u32 ld, u32 span, struct MR_DRV_RAID_MAP_ALL *map)
124 {
125 	return le16_to_cpu(map->raidMap.ldSpanMap[ld].spanBlock[span].span.arrayRef);
126 }
127 
128 __le16 MR_PdDevHandleGet(u32 pd, struct MR_DRV_RAID_MAP_ALL *map)
129 {
130 	return map->raidMap.devHndlInfo[pd].curDevHdl;
131 }
132 
133 static u8 MR_PdInterfaceTypeGet(u32 pd, struct MR_DRV_RAID_MAP_ALL *map)
134 {
135 	return map->raidMap.devHndlInfo[pd].interfaceType;
136 }
137 
138 u16 MR_GetLDTgtId(u32 ld, struct MR_DRV_RAID_MAP_ALL *map)
139 {
140 	return le16_to_cpu(map->raidMap.ldSpanMap[ld].ldRaid.targetId);
141 }
142 
143 u16 MR_TargetIdToLdGet(u32 ldTgtId, struct MR_DRV_RAID_MAP_ALL *map)
144 {
145 	return map->raidMap.ldTgtIdToLd[ldTgtId];
146 }
147 
148 static struct MR_LD_SPAN *MR_LdSpanPtrGet(u32 ld, u32 span,
149 					  struct MR_DRV_RAID_MAP_ALL *map)
150 {
151 	return &map->raidMap.ldSpanMap[ld].spanBlock[span].span;
152 }
153 
154 /*
155  * This function will Populate Driver Map using firmware raid map
156  */
157 static int MR_PopulateDrvRaidMap(struct megasas_instance *instance, u64 map_id)
158 {
159 	struct fusion_context *fusion = instance->ctrl_context;
160 	struct MR_FW_RAID_MAP_ALL     *fw_map_old    = NULL;
161 	struct MR_FW_RAID_MAP         *pFwRaidMap    = NULL;
162 	int i, j;
163 	u16 ld_count;
164 	struct MR_FW_RAID_MAP_DYNAMIC *fw_map_dyn;
165 	struct MR_FW_RAID_MAP_EXT *fw_map_ext;
166 	struct MR_RAID_MAP_DESC_TABLE *desc_table;
167 
168 
169 	struct MR_DRV_RAID_MAP_ALL *drv_map =
170 			fusion->ld_drv_map[(map_id & 1)];
171 	struct MR_DRV_RAID_MAP *pDrvRaidMap = &drv_map->raidMap;
172 	void *raid_map_data = NULL;
173 
174 	memset(drv_map, 0, fusion->drv_map_sz);
175 	memset(pDrvRaidMap->ldTgtIdToLd,
176 	       0xff, (sizeof(u16) * MAX_LOGICAL_DRIVES_DYN));
177 
178 	if (instance->max_raid_mapsize) {
179 		fw_map_dyn = fusion->ld_map[(map_id & 1)];
180 		desc_table =
181 		(struct MR_RAID_MAP_DESC_TABLE *)((void *)fw_map_dyn + le32_to_cpu(fw_map_dyn->desc_table_offset));
182 		if (desc_table != fw_map_dyn->raid_map_desc_table)
183 			dev_dbg(&instance->pdev->dev, "offsets of desc table are not matching desc %p original %p\n",
184 				desc_table, fw_map_dyn->raid_map_desc_table);
185 
186 		ld_count = (u16)le16_to_cpu(fw_map_dyn->ld_count);
187 		pDrvRaidMap->ldCount = (__le16)cpu_to_le16(ld_count);
188 		pDrvRaidMap->fpPdIoTimeoutSec =
189 			fw_map_dyn->fp_pd_io_timeout_sec;
190 		pDrvRaidMap->totalSize =
191 			cpu_to_le32(sizeof(struct MR_DRV_RAID_MAP_ALL));
192 		/* point to actual data starting point*/
193 		raid_map_data = (void *)fw_map_dyn +
194 			le32_to_cpu(fw_map_dyn->desc_table_offset) +
195 			le32_to_cpu(fw_map_dyn->desc_table_size);
196 
197 		for (i = 0; i < le32_to_cpu(fw_map_dyn->desc_table_num_elements); ++i) {
198 			switch (le32_to_cpu(desc_table->raid_map_desc_type)) {
199 			case RAID_MAP_DESC_TYPE_DEVHDL_INFO:
200 				fw_map_dyn->dev_hndl_info =
201 				(struct MR_DEV_HANDLE_INFO *)(raid_map_data + le32_to_cpu(desc_table->raid_map_desc_offset));
202 				memcpy(pDrvRaidMap->devHndlInfo,
203 					fw_map_dyn->dev_hndl_info,
204 					sizeof(struct MR_DEV_HANDLE_INFO) *
205 					le32_to_cpu(desc_table->raid_map_desc_elements));
206 			break;
207 			case RAID_MAP_DESC_TYPE_TGTID_INFO:
208 				fw_map_dyn->ld_tgt_id_to_ld =
209 					(u16 *)(raid_map_data +
210 					le32_to_cpu(desc_table->raid_map_desc_offset));
211 				for (j = 0; j < le32_to_cpu(desc_table->raid_map_desc_elements); j++) {
212 					pDrvRaidMap->ldTgtIdToLd[j] =
213 						le16_to_cpu(fw_map_dyn->ld_tgt_id_to_ld[j]);
214 				}
215 			break;
216 			case RAID_MAP_DESC_TYPE_ARRAY_INFO:
217 				fw_map_dyn->ar_map_info =
218 					(struct MR_ARRAY_INFO *)
219 					(raid_map_data + le32_to_cpu(desc_table->raid_map_desc_offset));
220 				memcpy(pDrvRaidMap->arMapInfo,
221 				       fw_map_dyn->ar_map_info,
222 				       sizeof(struct MR_ARRAY_INFO) *
223 				       le32_to_cpu(desc_table->raid_map_desc_elements));
224 			break;
225 			case RAID_MAP_DESC_TYPE_SPAN_INFO:
226 				fw_map_dyn->ld_span_map =
227 					(struct MR_LD_SPAN_MAP *)
228 					(raid_map_data +
229 					le32_to_cpu(desc_table->raid_map_desc_offset));
230 				memcpy(pDrvRaidMap->ldSpanMap,
231 				       fw_map_dyn->ld_span_map,
232 				       sizeof(struct MR_LD_SPAN_MAP) *
233 				       le32_to_cpu(desc_table->raid_map_desc_elements));
234 			break;
235 			default:
236 				dev_dbg(&instance->pdev->dev, "wrong number of desctableElements %d\n",
237 					fw_map_dyn->desc_table_num_elements);
238 			}
239 			++desc_table;
240 		}
241 
242 	} else if (instance->supportmax256vd) {
243 		fw_map_ext =
244 			(struct MR_FW_RAID_MAP_EXT *)fusion->ld_map[(map_id & 1)];
245 		ld_count = (u16)le16_to_cpu(fw_map_ext->ldCount);
246 		if (ld_count > MAX_LOGICAL_DRIVES_EXT) {
247 			dev_dbg(&instance->pdev->dev, "megaraid_sas: LD count exposed in RAID map in not valid\n");
248 			return 1;
249 		}
250 
251 		pDrvRaidMap->ldCount = (__le16)cpu_to_le16(ld_count);
252 		pDrvRaidMap->fpPdIoTimeoutSec = fw_map_ext->fpPdIoTimeoutSec;
253 		for (i = 0; i < (MAX_LOGICAL_DRIVES_EXT); i++)
254 			pDrvRaidMap->ldTgtIdToLd[i] =
255 				(u16)fw_map_ext->ldTgtIdToLd[i];
256 		memcpy(pDrvRaidMap->ldSpanMap, fw_map_ext->ldSpanMap,
257 		       sizeof(struct MR_LD_SPAN_MAP) * ld_count);
258 		memcpy(pDrvRaidMap->arMapInfo, fw_map_ext->arMapInfo,
259 		       sizeof(struct MR_ARRAY_INFO) * MAX_API_ARRAYS_EXT);
260 		memcpy(pDrvRaidMap->devHndlInfo, fw_map_ext->devHndlInfo,
261 		       sizeof(struct MR_DEV_HANDLE_INFO) *
262 		       MAX_RAIDMAP_PHYSICAL_DEVICES);
263 
264 		/* New Raid map will not set totalSize, so keep expected value
265 		 * for legacy code in ValidateMapInfo
266 		 */
267 		pDrvRaidMap->totalSize =
268 			cpu_to_le32(sizeof(struct MR_FW_RAID_MAP_EXT));
269 	} else {
270 		fw_map_old = (struct MR_FW_RAID_MAP_ALL *)
271 				fusion->ld_map[(map_id & 1)];
272 		pFwRaidMap = &fw_map_old->raidMap;
273 		ld_count = (u16)le32_to_cpu(pFwRaidMap->ldCount);
274 		if (ld_count > MAX_LOGICAL_DRIVES) {
275 			dev_dbg(&instance->pdev->dev,
276 				"LD count exposed in RAID map in not valid\n");
277 			return 1;
278 		}
279 
280 		pDrvRaidMap->totalSize = pFwRaidMap->totalSize;
281 		pDrvRaidMap->ldCount = (__le16)cpu_to_le16(ld_count);
282 		pDrvRaidMap->fpPdIoTimeoutSec = pFwRaidMap->fpPdIoTimeoutSec;
283 		for (i = 0; i < MAX_RAIDMAP_LOGICAL_DRIVES + MAX_RAIDMAP_VIEWS; i++)
284 			pDrvRaidMap->ldTgtIdToLd[i] =
285 				(u8)pFwRaidMap->ldTgtIdToLd[i];
286 		for (i = 0; i < ld_count; i++) {
287 			pDrvRaidMap->ldSpanMap[i] = pFwRaidMap->ldSpanMap[i];
288 		}
289 		memcpy(pDrvRaidMap->arMapInfo, pFwRaidMap->arMapInfo,
290 			sizeof(struct MR_ARRAY_INFO) * MAX_RAIDMAP_ARRAYS);
291 		memcpy(pDrvRaidMap->devHndlInfo, pFwRaidMap->devHndlInfo,
292 			sizeof(struct MR_DEV_HANDLE_INFO) *
293 			MAX_RAIDMAP_PHYSICAL_DEVICES);
294 	}
295 
296 	return 0;
297 }
298 
299 /*
300  * This function will validate Map info data provided by FW
301  */
302 u8 MR_ValidateMapInfo(struct megasas_instance *instance, u64 map_id)
303 {
304 	struct fusion_context *fusion;
305 	struct MR_DRV_RAID_MAP_ALL *drv_map;
306 	struct MR_DRV_RAID_MAP *pDrvRaidMap;
307 	struct LD_LOAD_BALANCE_INFO *lbInfo;
308 	PLD_SPAN_INFO ldSpanInfo;
309 	struct MR_LD_RAID         *raid;
310 	u16 num_lds, i;
311 	u16 ld;
312 	u32 expected_size;
313 
314 	if (MR_PopulateDrvRaidMap(instance, map_id))
315 		return 0;
316 
317 	fusion = instance->ctrl_context;
318 	drv_map = fusion->ld_drv_map[(map_id & 1)];
319 	pDrvRaidMap = &drv_map->raidMap;
320 
321 	lbInfo = fusion->load_balance_info;
322 	ldSpanInfo = fusion->log_to_span;
323 
324 	if (instance->max_raid_mapsize)
325 		expected_size = sizeof(struct MR_DRV_RAID_MAP_ALL);
326 	else if (instance->supportmax256vd)
327 		expected_size = sizeof(struct MR_FW_RAID_MAP_EXT);
328 	else
329 		expected_size =
330 			(sizeof(struct MR_FW_RAID_MAP) - sizeof(struct MR_LD_SPAN_MAP) +
331 			(sizeof(struct MR_LD_SPAN_MAP) * le16_to_cpu(pDrvRaidMap->ldCount)));
332 
333 	if (le32_to_cpu(pDrvRaidMap->totalSize) != expected_size) {
334 		dev_dbg(&instance->pdev->dev, "megasas: map info structure size 0x%x",
335 			le32_to_cpu(pDrvRaidMap->totalSize));
336 		dev_dbg(&instance->pdev->dev, "is not matching expected size 0x%x\n",
337 			(unsigned int)expected_size);
338 		dev_err(&instance->pdev->dev, "megasas: span map %x, pDrvRaidMap->totalSize : %x\n",
339 			(unsigned int)sizeof(struct MR_LD_SPAN_MAP),
340 			le32_to_cpu(pDrvRaidMap->totalSize));
341 		return 0;
342 	}
343 
344 	if (instance->UnevenSpanSupport)
345 		mr_update_span_set(drv_map, ldSpanInfo);
346 
347 	if (lbInfo)
348 		mr_update_load_balance_params(drv_map, lbInfo);
349 
350 	num_lds = le16_to_cpu(drv_map->raidMap.ldCount);
351 
352 	/*Convert Raid capability values to CPU arch */
353 	for (i = 0; (num_lds > 0) && (i < MAX_LOGICAL_DRIVES_EXT); i++) {
354 		ld = MR_TargetIdToLdGet(i, drv_map);
355 
356 		/* For non existing VDs, iterate to next VD*/
357 		if (ld >= (MAX_LOGICAL_DRIVES_EXT - 1))
358 			continue;
359 
360 		raid = MR_LdRaidGet(ld, drv_map);
361 		le32_to_cpus((u32 *)&raid->capability);
362 
363 		num_lds--;
364 	}
365 
366 	return 1;
367 }
368 
369 u32 MR_GetSpanBlock(u32 ld, u64 row, u64 *span_blk,
370 		    struct MR_DRV_RAID_MAP_ALL *map)
371 {
372 	struct MR_SPAN_BLOCK_INFO *pSpanBlock = MR_LdSpanInfoGet(ld, map);
373 	struct MR_QUAD_ELEMENT    *quad;
374 	struct MR_LD_RAID         *raid = MR_LdRaidGet(ld, map);
375 	u32                span, j;
376 
377 	for (span = 0; span < raid->spanDepth; span++, pSpanBlock++) {
378 
379 		for (j = 0; j < le32_to_cpu(pSpanBlock->block_span_info.noElements); j++) {
380 			quad = &pSpanBlock->block_span_info.quad[j];
381 
382 			if (le32_to_cpu(quad->diff) == 0)
383 				return SPAN_INVALID;
384 			if (le64_to_cpu(quad->logStart) <= row && row <=
385 				le64_to_cpu(quad->logEnd) && (mega_mod64(row - le64_to_cpu(quad->logStart),
386 				le32_to_cpu(quad->diff))) == 0) {
387 				if (span_blk != NULL) {
388 					u64  blk, debugBlk;
389 					blk =  mega_div64_32((row-le64_to_cpu(quad->logStart)), le32_to_cpu(quad->diff));
390 					debugBlk = blk;
391 
392 					blk = (blk + le64_to_cpu(quad->offsetInSpan)) << raid->stripeShift;
393 					*span_blk = blk;
394 				}
395 				return span;
396 			}
397 		}
398 	}
399 	return SPAN_INVALID;
400 }
401 
402 /*
403 ******************************************************************************
404 *
405 * This routine calculates the Span block for given row using spanset.
406 *
407 * Inputs :
408 *    instance - HBA instance
409 *    ld   - Logical drive number
410 *    row        - Row number
411 *    map    - LD map
412 *
413 * Outputs :
414 *
415 *    span          - Span number
416 *    block         - Absolute Block number in the physical disk
417 *    div_error	   - Devide error code.
418 */
419 
420 u32 mr_spanset_get_span_block(struct megasas_instance *instance,
421 		u32 ld, u64 row, u64 *span_blk, struct MR_DRV_RAID_MAP_ALL *map)
422 {
423 	struct fusion_context *fusion = instance->ctrl_context;
424 	struct MR_LD_RAID         *raid = MR_LdRaidGet(ld, map);
425 	LD_SPAN_SET *span_set;
426 	struct MR_QUAD_ELEMENT    *quad;
427 	u32    span, info;
428 	PLD_SPAN_INFO ldSpanInfo = fusion->log_to_span;
429 
430 	for (info = 0; info < MAX_QUAD_DEPTH; info++) {
431 		span_set = &(ldSpanInfo[ld].span_set[info]);
432 
433 		if (span_set->span_row_data_width == 0)
434 			break;
435 
436 		if (row > span_set->data_row_end)
437 			continue;
438 
439 		for (span = 0; span < raid->spanDepth; span++)
440 			if (le32_to_cpu(map->raidMap.ldSpanMap[ld].spanBlock[span].
441 				block_span_info.noElements) >= info+1) {
442 				quad = &map->raidMap.ldSpanMap[ld].
443 					spanBlock[span].
444 					block_span_info.quad[info];
445 				if (le32_to_cpu(quad->diff) == 0)
446 					return SPAN_INVALID;
447 				if (le64_to_cpu(quad->logStart) <= row  &&
448 					row <= le64_to_cpu(quad->logEnd)  &&
449 					(mega_mod64(row - le64_to_cpu(quad->logStart),
450 						le32_to_cpu(quad->diff))) == 0) {
451 					if (span_blk != NULL) {
452 						u64  blk;
453 						blk = mega_div64_32
454 						    ((row - le64_to_cpu(quad->logStart)),
455 						    le32_to_cpu(quad->diff));
456 						blk = (blk + le64_to_cpu(quad->offsetInSpan))
457 							 << raid->stripeShift;
458 						*span_blk = blk;
459 					}
460 					return span;
461 				}
462 			}
463 	}
464 	return SPAN_INVALID;
465 }
466 
467 /*
468 ******************************************************************************
469 *
470 * This routine calculates the row for given strip using spanset.
471 *
472 * Inputs :
473 *    instance - HBA instance
474 *    ld   - Logical drive number
475 *    Strip        - Strip
476 *    map    - LD map
477 *
478 * Outputs :
479 *
480 *    row         - row associated with strip
481 */
482 
483 static u64  get_row_from_strip(struct megasas_instance *instance,
484 	u32 ld, u64 strip, struct MR_DRV_RAID_MAP_ALL *map)
485 {
486 	struct fusion_context *fusion = instance->ctrl_context;
487 	struct MR_LD_RAID	*raid = MR_LdRaidGet(ld, map);
488 	LD_SPAN_SET	*span_set;
489 	PLD_SPAN_INFO	ldSpanInfo = fusion->log_to_span;
490 	u32		info, strip_offset, span, span_offset;
491 	u64		span_set_Strip, span_set_Row, retval;
492 
493 	for (info = 0; info < MAX_QUAD_DEPTH; info++) {
494 		span_set = &(ldSpanInfo[ld].span_set[info]);
495 
496 		if (span_set->span_row_data_width == 0)
497 			break;
498 		if (strip > span_set->data_strip_end)
499 			continue;
500 
501 		span_set_Strip = strip - span_set->data_strip_start;
502 		strip_offset = mega_mod64(span_set_Strip,
503 				span_set->span_row_data_width);
504 		span_set_Row = mega_div64_32(span_set_Strip,
505 				span_set->span_row_data_width) * span_set->diff;
506 		for (span = 0, span_offset = 0; span < raid->spanDepth; span++)
507 			if (le32_to_cpu(map->raidMap.ldSpanMap[ld].spanBlock[span].
508 				block_span_info.noElements) >= info+1) {
509 				if (strip_offset >=
510 					span_set->strip_offset[span])
511 					span_offset++;
512 				else
513 					break;
514 			}
515 
516 		retval = (span_set->data_row_start + span_set_Row +
517 				(span_offset - 1));
518 		return retval;
519 	}
520 	return -1LLU;
521 }
522 
523 
524 /*
525 ******************************************************************************
526 *
527 * This routine calculates the Start Strip for given row using spanset.
528 *
529 * Inputs :
530 *    instance - HBA instance
531 *    ld   - Logical drive number
532 *    row        - Row number
533 *    map    - LD map
534 *
535 * Outputs :
536 *
537 *    Strip         - Start strip associated with row
538 */
539 
540 static u64 get_strip_from_row(struct megasas_instance *instance,
541 		u32 ld, u64 row, struct MR_DRV_RAID_MAP_ALL *map)
542 {
543 	struct fusion_context *fusion = instance->ctrl_context;
544 	struct MR_LD_RAID         *raid = MR_LdRaidGet(ld, map);
545 	LD_SPAN_SET *span_set;
546 	struct MR_QUAD_ELEMENT    *quad;
547 	PLD_SPAN_INFO ldSpanInfo = fusion->log_to_span;
548 	u32    span, info;
549 	u64  strip;
550 
551 	for (info = 0; info < MAX_QUAD_DEPTH; info++) {
552 		span_set = &(ldSpanInfo[ld].span_set[info]);
553 
554 		if (span_set->span_row_data_width == 0)
555 			break;
556 		if (row > span_set->data_row_end)
557 			continue;
558 
559 		for (span = 0; span < raid->spanDepth; span++)
560 			if (le32_to_cpu(map->raidMap.ldSpanMap[ld].spanBlock[span].
561 				block_span_info.noElements) >= info+1) {
562 				quad = &map->raidMap.ldSpanMap[ld].
563 					spanBlock[span].block_span_info.quad[info];
564 				if (le64_to_cpu(quad->logStart) <= row  &&
565 					row <= le64_to_cpu(quad->logEnd)  &&
566 					mega_mod64((row - le64_to_cpu(quad->logStart)),
567 					le32_to_cpu(quad->diff)) == 0) {
568 					strip = mega_div64_32
569 						(((row - span_set->data_row_start)
570 							- le64_to_cpu(quad->logStart)),
571 							le32_to_cpu(quad->diff));
572 					strip *= span_set->span_row_data_width;
573 					strip += span_set->data_strip_start;
574 					strip += span_set->strip_offset[span];
575 					return strip;
576 				}
577 			}
578 	}
579 	dev_err(&instance->pdev->dev, "get_strip_from_row"
580 		"returns invalid strip for ld=%x, row=%lx\n",
581 		ld, (long unsigned int)row);
582 	return -1;
583 }
584 
585 /*
586 ******************************************************************************
587 *
588 * This routine calculates the Physical Arm for given strip using spanset.
589 *
590 * Inputs :
591 *    instance - HBA instance
592 *    ld   - Logical drive number
593 *    strip      - Strip
594 *    map    - LD map
595 *
596 * Outputs :
597 *
598 *    Phys Arm         - Phys Arm associated with strip
599 */
600 
601 static u32 get_arm_from_strip(struct megasas_instance *instance,
602 	u32 ld, u64 strip, struct MR_DRV_RAID_MAP_ALL *map)
603 {
604 	struct fusion_context *fusion = instance->ctrl_context;
605 	struct MR_LD_RAID         *raid = MR_LdRaidGet(ld, map);
606 	LD_SPAN_SET *span_set;
607 	PLD_SPAN_INFO ldSpanInfo = fusion->log_to_span;
608 	u32    info, strip_offset, span, span_offset, retval;
609 
610 	for (info = 0 ; info < MAX_QUAD_DEPTH; info++) {
611 		span_set = &(ldSpanInfo[ld].span_set[info]);
612 
613 		if (span_set->span_row_data_width == 0)
614 			break;
615 		if (strip > span_set->data_strip_end)
616 			continue;
617 
618 		strip_offset = (uint)mega_mod64
619 				((strip - span_set->data_strip_start),
620 				span_set->span_row_data_width);
621 
622 		for (span = 0, span_offset = 0; span < raid->spanDepth; span++)
623 			if (le32_to_cpu(map->raidMap.ldSpanMap[ld].spanBlock[span].
624 				block_span_info.noElements) >= info+1) {
625 				if (strip_offset >=
626 					span_set->strip_offset[span])
627 					span_offset =
628 						span_set->strip_offset[span];
629 				else
630 					break;
631 			}
632 
633 		retval = (strip_offset - span_offset);
634 		return retval;
635 	}
636 
637 	dev_err(&instance->pdev->dev, "get_arm_from_strip"
638 		"returns invalid arm for ld=%x strip=%lx\n",
639 		ld, (long unsigned int)strip);
640 
641 	return -1;
642 }
643 
644 /* This Function will return Phys arm */
645 u8 get_arm(struct megasas_instance *instance, u32 ld, u8 span, u64 stripe,
646 		struct MR_DRV_RAID_MAP_ALL *map)
647 {
648 	struct MR_LD_RAID  *raid = MR_LdRaidGet(ld, map);
649 	/* Need to check correct default value */
650 	u32    arm = 0;
651 
652 	switch (raid->level) {
653 	case 0:
654 	case 5:
655 	case 6:
656 		arm = mega_mod64(stripe, SPAN_ROW_SIZE(map, ld, span));
657 		break;
658 	case 1:
659 		/* start with logical arm */
660 		arm = get_arm_from_strip(instance, ld, stripe, map);
661 		if (arm != -1U)
662 			arm *= 2;
663 		break;
664 	}
665 
666 	return arm;
667 }
668 
669 
670 /*
671 ******************************************************************************
672 *
673 * This routine calculates the arm, span and block for the specified stripe and
674 * reference in stripe using spanset
675 *
676 * Inputs :
677 *
678 *    ld   - Logical drive number
679 *    stripRow        - Stripe number
680 *    stripRef    - Reference in stripe
681 *
682 * Outputs :
683 *
684 *    span          - Span number
685 *    block         - Absolute Block number in the physical disk
686 */
687 static u8 mr_spanset_get_phy_params(struct megasas_instance *instance, u32 ld,
688 		u64 stripRow, u16 stripRef, struct IO_REQUEST_INFO *io_info,
689 		struct RAID_CONTEXT *pRAID_Context,
690 		struct MR_DRV_RAID_MAP_ALL *map)
691 {
692 	struct MR_LD_RAID  *raid = MR_LdRaidGet(ld, map);
693 	u32     pd, arRef, r1_alt_pd;
694 	u8      physArm, span;
695 	u64     row;
696 	u8	retval = true;
697 	u64	*pdBlock = &io_info->pdBlock;
698 	__le16	*pDevHandle = &io_info->devHandle;
699 	u8	*pPdInterface = &io_info->pd_interface;
700 	u32	logArm, rowMod, armQ, arm;
701 	struct fusion_context *fusion;
702 
703 	fusion = instance->ctrl_context;
704 	*pDevHandle = cpu_to_le16(MR_DEVHANDLE_INVALID);
705 
706 	/*Get row and span from io_info for Uneven Span IO.*/
707 	row	    = io_info->start_row;
708 	span	    = io_info->start_span;
709 
710 
711 	if (raid->level == 6) {
712 		logArm = get_arm_from_strip(instance, ld, stripRow, map);
713 		if (logArm == -1U)
714 			return false;
715 		rowMod = mega_mod64(row, SPAN_ROW_SIZE(map, ld, span));
716 		armQ = SPAN_ROW_SIZE(map, ld, span) - 1 - rowMod;
717 		arm = armQ + 1 + logArm;
718 		if (arm >= SPAN_ROW_SIZE(map, ld, span))
719 			arm -= SPAN_ROW_SIZE(map, ld, span);
720 		physArm = (u8)arm;
721 	} else
722 		/* Calculate the arm */
723 		physArm = get_arm(instance, ld, span, stripRow, map);
724 	if (physArm == 0xFF)
725 		return false;
726 
727 	arRef       = MR_LdSpanArrayGet(ld, span, map);
728 	pd          = MR_ArPdGet(arRef, physArm, map);
729 
730 	if (pd != MR_PD_INVALID) {
731 		*pDevHandle = MR_PdDevHandleGet(pd, map);
732 		*pPdInterface = MR_PdInterfaceTypeGet(pd, map);
733 		/* get second pd also for raid 1/10 fast path writes*/
734 		if ((instance->adapter_type >= VENTURA_SERIES) &&
735 		    (raid->level == 1) &&
736 		    !io_info->isRead) {
737 			r1_alt_pd = MR_ArPdGet(arRef, physArm + 1, map);
738 			if (r1_alt_pd != MR_PD_INVALID)
739 				io_info->r1_alt_dev_handle =
740 				MR_PdDevHandleGet(r1_alt_pd, map);
741 		}
742 	} else {
743 		if ((raid->level >= 5) &&
744 			((instance->adapter_type == THUNDERBOLT_SERIES)  ||
745 			((instance->adapter_type == INVADER_SERIES) &&
746 			(raid->regTypeReqOnRead != REGION_TYPE_UNUSED))))
747 			pRAID_Context->reg_lock_flags = REGION_TYPE_EXCLUSIVE;
748 		else if (raid->level == 1) {
749 			physArm = physArm + 1;
750 			pd = MR_ArPdGet(arRef, physArm, map);
751 			if (pd != MR_PD_INVALID) {
752 				*pDevHandle = MR_PdDevHandleGet(pd, map);
753 				*pPdInterface = MR_PdInterfaceTypeGet(pd, map);
754 			}
755 		}
756 	}
757 
758 	*pdBlock += stripRef + le64_to_cpu(MR_LdSpanPtrGet(ld, span, map)->startBlk);
759 	if (instance->adapter_type >= VENTURA_SERIES) {
760 		((struct RAID_CONTEXT_G35 *)pRAID_Context)->span_arm =
761 			(span << RAID_CTX_SPANARM_SPAN_SHIFT) | physArm;
762 		io_info->span_arm =
763 			(span << RAID_CTX_SPANARM_SPAN_SHIFT) | physArm;
764 	} else {
765 		pRAID_Context->span_arm =
766 			(span << RAID_CTX_SPANARM_SPAN_SHIFT) | physArm;
767 		io_info->span_arm = pRAID_Context->span_arm;
768 	}
769 	io_info->pd_after_lb = pd;
770 	return retval;
771 }
772 
773 /*
774 ******************************************************************************
775 *
776 * This routine calculates the arm, span and block for the specified stripe and
777 * reference in stripe.
778 *
779 * Inputs :
780 *
781 *    ld   - Logical drive number
782 *    stripRow        - Stripe number
783 *    stripRef    - Reference in stripe
784 *
785 * Outputs :
786 *
787 *    span          - Span number
788 *    block         - Absolute Block number in the physical disk
789 */
790 u8 MR_GetPhyParams(struct megasas_instance *instance, u32 ld, u64 stripRow,
791 		u16 stripRef, struct IO_REQUEST_INFO *io_info,
792 		struct RAID_CONTEXT *pRAID_Context,
793 		struct MR_DRV_RAID_MAP_ALL *map)
794 {
795 	struct MR_LD_RAID  *raid = MR_LdRaidGet(ld, map);
796 	u32         pd, arRef, r1_alt_pd;
797 	u8          physArm, span;
798 	u64         row;
799 	u8	    retval = true;
800 	u64	    *pdBlock = &io_info->pdBlock;
801 	__le16	    *pDevHandle = &io_info->devHandle;
802 	u8	    *pPdInterface = &io_info->pd_interface;
803 	struct fusion_context *fusion;
804 
805 	fusion = instance->ctrl_context;
806 	*pDevHandle = cpu_to_le16(MR_DEVHANDLE_INVALID);
807 
808 	row =  mega_div64_32(stripRow, raid->rowDataSize);
809 
810 	if (raid->level == 6) {
811 		/* logical arm within row */
812 		u32 logArm =  mega_mod64(stripRow, raid->rowDataSize);
813 		u32 rowMod, armQ, arm;
814 
815 		if (raid->rowSize == 0)
816 			return false;
817 		/* get logical row mod */
818 		rowMod = mega_mod64(row, raid->rowSize);
819 		armQ = raid->rowSize-1-rowMod; /* index of Q drive */
820 		arm = armQ+1+logArm; /* data always logically follows Q */
821 		if (arm >= raid->rowSize) /* handle wrap condition */
822 			arm -= raid->rowSize;
823 		physArm = (u8)arm;
824 	} else  {
825 		if (raid->modFactor == 0)
826 			return false;
827 		physArm = MR_LdDataArmGet(ld,  mega_mod64(stripRow,
828 							  raid->modFactor),
829 					  map);
830 	}
831 
832 	if (raid->spanDepth == 1) {
833 		span = 0;
834 		*pdBlock = row << raid->stripeShift;
835 	} else {
836 		span = (u8)MR_GetSpanBlock(ld, row, pdBlock, map);
837 		if (span == SPAN_INVALID)
838 			return false;
839 	}
840 
841 	/* Get the array on which this span is present */
842 	arRef       = MR_LdSpanArrayGet(ld, span, map);
843 	pd          = MR_ArPdGet(arRef, physArm, map); /* Get the pd */
844 
845 	if (pd != MR_PD_INVALID) {
846 		/* Get dev handle from Pd. */
847 		*pDevHandle = MR_PdDevHandleGet(pd, map);
848 		*pPdInterface = MR_PdInterfaceTypeGet(pd, map);
849 		/* get second pd also for raid 1/10 fast path writes*/
850 		if ((instance->adapter_type >= VENTURA_SERIES) &&
851 		    (raid->level == 1) &&
852 		    !io_info->isRead) {
853 			r1_alt_pd = MR_ArPdGet(arRef, physArm + 1, map);
854 			if (r1_alt_pd != MR_PD_INVALID)
855 				io_info->r1_alt_dev_handle =
856 					MR_PdDevHandleGet(r1_alt_pd, map);
857 		}
858 	} else {
859 		if ((raid->level >= 5) &&
860 			((instance->adapter_type == THUNDERBOLT_SERIES)  ||
861 			((instance->adapter_type == INVADER_SERIES) &&
862 			(raid->regTypeReqOnRead != REGION_TYPE_UNUSED))))
863 			pRAID_Context->reg_lock_flags = REGION_TYPE_EXCLUSIVE;
864 		else if (raid->level == 1) {
865 			/* Get alternate Pd. */
866 			physArm = physArm + 1;
867 			pd = MR_ArPdGet(arRef, physArm, map);
868 			if (pd != MR_PD_INVALID) {
869 				/* Get dev handle from Pd */
870 				*pDevHandle = MR_PdDevHandleGet(pd, map);
871 				*pPdInterface = MR_PdInterfaceTypeGet(pd, map);
872 			}
873 		}
874 	}
875 
876 	*pdBlock += stripRef + le64_to_cpu(MR_LdSpanPtrGet(ld, span, map)->startBlk);
877 	if (instance->adapter_type >= VENTURA_SERIES) {
878 		((struct RAID_CONTEXT_G35 *)pRAID_Context)->span_arm =
879 				(span << RAID_CTX_SPANARM_SPAN_SHIFT) | physArm;
880 		io_info->span_arm =
881 				(span << RAID_CTX_SPANARM_SPAN_SHIFT) | physArm;
882 	} else {
883 		pRAID_Context->span_arm =
884 			(span << RAID_CTX_SPANARM_SPAN_SHIFT) | physArm;
885 		io_info->span_arm = pRAID_Context->span_arm;
886 	}
887 	io_info->pd_after_lb = pd;
888 	return retval;
889 }
890 
891 /*
892 ******************************************************************************
893 *
894 * MR_BuildRaidContext function
895 *
896 * This function will initiate command processing.  The start/end row and strip
897 * information is calculated then the lock is acquired.
898 * This function will return 0 if region lock was acquired OR return num strips
899 */
900 u8
901 MR_BuildRaidContext(struct megasas_instance *instance,
902 		    struct IO_REQUEST_INFO *io_info,
903 		    struct RAID_CONTEXT *pRAID_Context,
904 		    struct MR_DRV_RAID_MAP_ALL *map, u8 **raidLUN)
905 {
906 	struct fusion_context *fusion;
907 	struct MR_LD_RAID  *raid;
908 	u32         stripSize, stripe_mask;
909 	u64         endLba, endStrip, endRow, start_row, start_strip;
910 	u64         regStart;
911 	u32         regSize;
912 	u8          num_strips, numRows;
913 	u16         ref_in_start_stripe, ref_in_end_stripe;
914 	u64         ldStartBlock;
915 	u32         numBlocks, ldTgtId;
916 	u8          isRead;
917 	u8	    retval = 0;
918 	u8	    startlba_span = SPAN_INVALID;
919 	u64 *pdBlock = &io_info->pdBlock;
920 	u16	    ld;
921 
922 	ldStartBlock = io_info->ldStartBlock;
923 	numBlocks = io_info->numBlocks;
924 	ldTgtId = io_info->ldTgtId;
925 	isRead = io_info->isRead;
926 	io_info->IoforUnevenSpan = 0;
927 	io_info->start_span	= SPAN_INVALID;
928 	fusion = instance->ctrl_context;
929 
930 	ld = MR_TargetIdToLdGet(ldTgtId, map);
931 	raid = MR_LdRaidGet(ld, map);
932 	/*check read ahead bit*/
933 	io_info->ra_capable = raid->capability.ra_capable;
934 
935 	/*
936 	 * if rowDataSize @RAID map and spanRowDataSize @SPAN INFO are zero
937 	 * return FALSE
938 	 */
939 	if (raid->rowDataSize == 0) {
940 		if (MR_LdSpanPtrGet(ld, 0, map)->spanRowDataSize == 0)
941 			return false;
942 		else if (instance->UnevenSpanSupport) {
943 			io_info->IoforUnevenSpan = 1;
944 		} else {
945 			dev_info(&instance->pdev->dev,
946 				"raid->rowDataSize is 0, but has SPAN[0]"
947 				"rowDataSize = 0x%0x,"
948 				"but there is _NO_ UnevenSpanSupport\n",
949 				MR_LdSpanPtrGet(ld, 0, map)->spanRowDataSize);
950 			return false;
951 		}
952 	}
953 
954 	stripSize = 1 << raid->stripeShift;
955 	stripe_mask = stripSize-1;
956 
957 
958 	/*
959 	 * calculate starting row and stripe, and number of strips and rows
960 	 */
961 	start_strip         = ldStartBlock >> raid->stripeShift;
962 	ref_in_start_stripe = (u16)(ldStartBlock & stripe_mask);
963 	endLba              = ldStartBlock + numBlocks - 1;
964 	ref_in_end_stripe   = (u16)(endLba & stripe_mask);
965 	endStrip            = endLba >> raid->stripeShift;
966 	num_strips          = (u8)(endStrip - start_strip + 1); /* End strip */
967 
968 	if (io_info->IoforUnevenSpan) {
969 		start_row = get_row_from_strip(instance, ld, start_strip, map);
970 		endRow	  = get_row_from_strip(instance, ld, endStrip, map);
971 		if (start_row == -1ULL || endRow == -1ULL) {
972 			dev_info(&instance->pdev->dev, "return from %s %d."
973 				"Send IO w/o region lock.\n",
974 				__func__, __LINE__);
975 			return false;
976 		}
977 
978 		if (raid->spanDepth == 1) {
979 			startlba_span = 0;
980 			*pdBlock = start_row << raid->stripeShift;
981 		} else
982 			startlba_span = (u8)mr_spanset_get_span_block(instance,
983 						ld, start_row, pdBlock, map);
984 		if (startlba_span == SPAN_INVALID) {
985 			dev_info(&instance->pdev->dev, "return from %s %d"
986 				"for row 0x%llx,start strip %llx"
987 				"endSrip %llx\n", __func__, __LINE__,
988 				(unsigned long long)start_row,
989 				(unsigned long long)start_strip,
990 				(unsigned long long)endStrip);
991 			return false;
992 		}
993 		io_info->start_span	= startlba_span;
994 		io_info->start_row	= start_row;
995 	} else {
996 		start_row = mega_div64_32(start_strip, raid->rowDataSize);
997 		endRow    = mega_div64_32(endStrip, raid->rowDataSize);
998 	}
999 	numRows = (u8)(endRow - start_row + 1);
1000 
1001 	/*
1002 	 * calculate region info.
1003 	 */
1004 
1005 	/* assume region is at the start of the first row */
1006 	regStart            = start_row << raid->stripeShift;
1007 	/* assume this IO needs the full row - we'll adjust if not true */
1008 	regSize             = stripSize;
1009 
1010 	io_info->do_fp_rlbypass = raid->capability.fpBypassRegionLock;
1011 
1012 	/* Check if we can send this I/O via FastPath */
1013 	if (raid->capability.fpCapable) {
1014 		if (isRead)
1015 			io_info->fpOkForIo = (raid->capability.fpReadCapable &&
1016 					      ((num_strips == 1) ||
1017 					       raid->capability.
1018 					       fpReadAcrossStripe));
1019 		else
1020 			io_info->fpOkForIo = (raid->capability.fpWriteCapable &&
1021 					      ((num_strips == 1) ||
1022 					       raid->capability.
1023 					       fpWriteAcrossStripe));
1024 	} else
1025 		io_info->fpOkForIo = false;
1026 
1027 	if (numRows == 1) {
1028 		/* single-strip IOs can always lock only the data needed */
1029 		if (num_strips == 1) {
1030 			regStart += ref_in_start_stripe;
1031 			regSize = numBlocks;
1032 		}
1033 		/* multi-strip IOs always need to full stripe locked */
1034 	} else if (io_info->IoforUnevenSpan == 0) {
1035 		/*
1036 		 * For Even span region lock optimization.
1037 		 * If the start strip is the last in the start row
1038 		 */
1039 		if (start_strip == (start_row + 1) * raid->rowDataSize - 1) {
1040 			regStart += ref_in_start_stripe;
1041 			/* initialize count to sectors from startref to end
1042 			   of strip */
1043 			regSize = stripSize - ref_in_start_stripe;
1044 		}
1045 
1046 		/* add complete rows in the middle of the transfer */
1047 		if (numRows > 2)
1048 			regSize += (numRows-2) << raid->stripeShift;
1049 
1050 		/* if IO ends within first strip of last row*/
1051 		if (endStrip == endRow*raid->rowDataSize)
1052 			regSize += ref_in_end_stripe+1;
1053 		else
1054 			regSize += stripSize;
1055 	} else {
1056 		/*
1057 		 * For Uneven span region lock optimization.
1058 		 * If the start strip is the last in the start row
1059 		 */
1060 		if (start_strip == (get_strip_from_row(instance, ld, start_row, map) +
1061 				SPAN_ROW_DATA_SIZE(map, ld, startlba_span) - 1)) {
1062 			regStart += ref_in_start_stripe;
1063 			/* initialize count to sectors from
1064 			 * startRef to end of strip
1065 			 */
1066 			regSize = stripSize - ref_in_start_stripe;
1067 		}
1068 		/* Add complete rows in the middle of the transfer*/
1069 
1070 		if (numRows > 2)
1071 			/* Add complete rows in the middle of the transfer*/
1072 			regSize += (numRows-2) << raid->stripeShift;
1073 
1074 		/* if IO ends within first strip of last row */
1075 		if (endStrip == get_strip_from_row(instance, ld, endRow, map))
1076 			regSize += ref_in_end_stripe + 1;
1077 		else
1078 			regSize += stripSize;
1079 	}
1080 
1081 	pRAID_Context->timeout_value =
1082 		cpu_to_le16(raid->fpIoTimeoutForLd ?
1083 			    raid->fpIoTimeoutForLd :
1084 			    map->raidMap.fpPdIoTimeoutSec);
1085 	if (instance->adapter_type == INVADER_SERIES)
1086 		pRAID_Context->reg_lock_flags = (isRead) ?
1087 			raid->regTypeReqOnRead : raid->regTypeReqOnWrite;
1088 	else if (instance->adapter_type == THUNDERBOLT_SERIES)
1089 		pRAID_Context->reg_lock_flags = (isRead) ?
1090 			REGION_TYPE_SHARED_READ : raid->regTypeReqOnWrite;
1091 	pRAID_Context->virtual_disk_tgt_id = raid->targetId;
1092 	pRAID_Context->reg_lock_row_lba    = cpu_to_le64(regStart);
1093 	pRAID_Context->reg_lock_length    = cpu_to_le32(regSize);
1094 	pRAID_Context->config_seq_num	= raid->seqNum;
1095 	/* save pointer to raid->LUN array */
1096 	*raidLUN = raid->LUN;
1097 
1098 
1099 	/*Get Phy Params only if FP capable, or else leave it to MR firmware
1100 	  to do the calculation.*/
1101 	if (io_info->fpOkForIo) {
1102 		retval = io_info->IoforUnevenSpan ?
1103 				mr_spanset_get_phy_params(instance, ld,
1104 					start_strip, ref_in_start_stripe,
1105 					io_info, pRAID_Context, map) :
1106 				MR_GetPhyParams(instance, ld, start_strip,
1107 					ref_in_start_stripe, io_info,
1108 					pRAID_Context, map);
1109 		/* If IO on an invalid Pd, then FP is not possible.*/
1110 		if (io_info->devHandle == MR_DEVHANDLE_INVALID)
1111 			io_info->fpOkForIo = false;
1112 		return retval;
1113 	} else if (isRead) {
1114 		uint stripIdx;
1115 		for (stripIdx = 0; stripIdx < num_strips; stripIdx++) {
1116 			retval = io_info->IoforUnevenSpan ?
1117 				mr_spanset_get_phy_params(instance, ld,
1118 				    start_strip + stripIdx,
1119 				    ref_in_start_stripe, io_info,
1120 				    pRAID_Context, map) :
1121 				MR_GetPhyParams(instance, ld,
1122 				    start_strip + stripIdx, ref_in_start_stripe,
1123 				    io_info, pRAID_Context, map);
1124 			if (!retval)
1125 				return true;
1126 		}
1127 	}
1128 	return true;
1129 }
1130 
1131 /*
1132 ******************************************************************************
1133 *
1134 * This routine pepare spanset info from Valid Raid map and store it into
1135 * local copy of ldSpanInfo per instance data structure.
1136 *
1137 * Inputs :
1138 * map    - LD map
1139 * ldSpanInfo - ldSpanInfo per HBA instance
1140 *
1141 */
1142 void mr_update_span_set(struct MR_DRV_RAID_MAP_ALL *map,
1143 	PLD_SPAN_INFO ldSpanInfo)
1144 {
1145 	u8   span, count;
1146 	u32  element, span_row_width;
1147 	u64  span_row;
1148 	struct MR_LD_RAID *raid;
1149 	LD_SPAN_SET *span_set, *span_set_prev;
1150 	struct MR_QUAD_ELEMENT    *quad;
1151 	int ldCount;
1152 	u16 ld;
1153 
1154 
1155 	for (ldCount = 0; ldCount < MAX_LOGICAL_DRIVES_EXT; ldCount++) {
1156 		ld = MR_TargetIdToLdGet(ldCount, map);
1157 		if (ld >= (MAX_LOGICAL_DRIVES_EXT - 1))
1158 			continue;
1159 		raid = MR_LdRaidGet(ld, map);
1160 		for (element = 0; element < MAX_QUAD_DEPTH; element++) {
1161 			for (span = 0; span < raid->spanDepth; span++) {
1162 				if (le32_to_cpu(map->raidMap.ldSpanMap[ld].spanBlock[span].
1163 					block_span_info.noElements) <
1164 					element + 1)
1165 					continue;
1166 				span_set = &(ldSpanInfo[ld].span_set[element]);
1167 				quad = &map->raidMap.ldSpanMap[ld].
1168 					spanBlock[span].block_span_info.
1169 					quad[element];
1170 
1171 				span_set->diff = le32_to_cpu(quad->diff);
1172 
1173 				for (count = 0, span_row_width = 0;
1174 					count < raid->spanDepth; count++) {
1175 					if (le32_to_cpu(map->raidMap.ldSpanMap[ld].
1176 						spanBlock[count].
1177 						block_span_info.
1178 						noElements) >= element + 1) {
1179 						span_set->strip_offset[count] =
1180 							span_row_width;
1181 						span_row_width +=
1182 							MR_LdSpanPtrGet
1183 							(ld, count, map)->spanRowDataSize;
1184 					}
1185 				}
1186 
1187 				span_set->span_row_data_width = span_row_width;
1188 				span_row = mega_div64_32(((le64_to_cpu(quad->logEnd) -
1189 					le64_to_cpu(quad->logStart)) + le32_to_cpu(quad->diff)),
1190 					le32_to_cpu(quad->diff));
1191 
1192 				if (element == 0) {
1193 					span_set->log_start_lba = 0;
1194 					span_set->log_end_lba =
1195 						((span_row << raid->stripeShift)
1196 						* span_row_width) - 1;
1197 
1198 					span_set->span_row_start = 0;
1199 					span_set->span_row_end = span_row - 1;
1200 
1201 					span_set->data_strip_start = 0;
1202 					span_set->data_strip_end =
1203 						(span_row * span_row_width) - 1;
1204 
1205 					span_set->data_row_start = 0;
1206 					span_set->data_row_end =
1207 						(span_row * le32_to_cpu(quad->diff)) - 1;
1208 				} else {
1209 					span_set_prev = &(ldSpanInfo[ld].
1210 							span_set[element - 1]);
1211 					span_set->log_start_lba =
1212 						span_set_prev->log_end_lba + 1;
1213 					span_set->log_end_lba =
1214 						span_set->log_start_lba +
1215 						((span_row << raid->stripeShift)
1216 						* span_row_width) - 1;
1217 
1218 					span_set->span_row_start =
1219 						span_set_prev->span_row_end + 1;
1220 					span_set->span_row_end =
1221 					span_set->span_row_start + span_row - 1;
1222 
1223 					span_set->data_strip_start =
1224 					span_set_prev->data_strip_end + 1;
1225 					span_set->data_strip_end =
1226 						span_set->data_strip_start +
1227 						(span_row * span_row_width) - 1;
1228 
1229 					span_set->data_row_start =
1230 						span_set_prev->data_row_end + 1;
1231 					span_set->data_row_end =
1232 						span_set->data_row_start +
1233 						(span_row * le32_to_cpu(quad->diff)) - 1;
1234 				}
1235 				break;
1236 		}
1237 		if (span == raid->spanDepth)
1238 			break;
1239 	    }
1240 	}
1241 }
1242 
1243 void mr_update_load_balance_params(struct MR_DRV_RAID_MAP_ALL *drv_map,
1244 	struct LD_LOAD_BALANCE_INFO *lbInfo)
1245 {
1246 	int ldCount;
1247 	u16 ld;
1248 	struct MR_LD_RAID *raid;
1249 
1250 	if (lb_pending_cmds > 128 || lb_pending_cmds < 1)
1251 		lb_pending_cmds = LB_PENDING_CMDS_DEFAULT;
1252 
1253 	for (ldCount = 0; ldCount < MAX_LOGICAL_DRIVES_EXT; ldCount++) {
1254 		ld = MR_TargetIdToLdGet(ldCount, drv_map);
1255 		if (ld >= MAX_LOGICAL_DRIVES_EXT - 1) {
1256 			lbInfo[ldCount].loadBalanceFlag = 0;
1257 			continue;
1258 		}
1259 
1260 		raid = MR_LdRaidGet(ld, drv_map);
1261 		if ((raid->level != 1) ||
1262 			(raid->ldState != MR_LD_STATE_OPTIMAL)) {
1263 			lbInfo[ldCount].loadBalanceFlag = 0;
1264 			continue;
1265 		}
1266 		lbInfo[ldCount].loadBalanceFlag = 1;
1267 	}
1268 }
1269 
1270 u8 megasas_get_best_arm_pd(struct megasas_instance *instance,
1271 			   struct LD_LOAD_BALANCE_INFO *lbInfo,
1272 			   struct IO_REQUEST_INFO *io_info,
1273 			   struct MR_DRV_RAID_MAP_ALL *drv_map)
1274 {
1275 	struct MR_LD_RAID  *raid;
1276 	u16	pd1_dev_handle;
1277 	u16     pend0, pend1, ld;
1278 	u64     diff0, diff1;
1279 	u8      bestArm, pd0, pd1, span, arm;
1280 	u32     arRef, span_row_size;
1281 
1282 	u64 block = io_info->ldStartBlock;
1283 	u32 count = io_info->numBlocks;
1284 
1285 	span = ((io_info->span_arm & RAID_CTX_SPANARM_SPAN_MASK)
1286 			>> RAID_CTX_SPANARM_SPAN_SHIFT);
1287 	arm = (io_info->span_arm & RAID_CTX_SPANARM_ARM_MASK);
1288 
1289 	ld = MR_TargetIdToLdGet(io_info->ldTgtId, drv_map);
1290 	raid = MR_LdRaidGet(ld, drv_map);
1291 	span_row_size = instance->UnevenSpanSupport ?
1292 			SPAN_ROW_SIZE(drv_map, ld, span) : raid->rowSize;
1293 
1294 	arRef = MR_LdSpanArrayGet(ld, span, drv_map);
1295 	pd0 = MR_ArPdGet(arRef, arm, drv_map);
1296 	pd1 = MR_ArPdGet(arRef, (arm + 1) >= span_row_size ?
1297 		(arm + 1 - span_row_size) : arm + 1, drv_map);
1298 
1299 	/* Get PD1 Dev Handle */
1300 
1301 	pd1_dev_handle = MR_PdDevHandleGet(pd1, drv_map);
1302 
1303 	if (pd1_dev_handle == MR_DEVHANDLE_INVALID) {
1304 		bestArm = arm;
1305 	} else {
1306 		/* get the pending cmds for the data and mirror arms */
1307 		pend0 = atomic_read(&lbInfo->scsi_pending_cmds[pd0]);
1308 		pend1 = atomic_read(&lbInfo->scsi_pending_cmds[pd1]);
1309 
1310 		/* Determine the disk whose head is nearer to the req. block */
1311 		diff0 = ABS_DIFF(block, lbInfo->last_accessed_block[pd0]);
1312 		diff1 = ABS_DIFF(block, lbInfo->last_accessed_block[pd1]);
1313 		bestArm = (diff0 <= diff1 ? arm : arm ^ 1);
1314 
1315 		/* Make balance count from 16 to 4 to
1316 		 *  keep driver in sync with Firmware
1317 		 */
1318 		if ((bestArm == arm && pend0 > pend1 + lb_pending_cmds)  ||
1319 		    (bestArm != arm && pend1 > pend0 + lb_pending_cmds))
1320 			bestArm ^= 1;
1321 
1322 		/* Update the last accessed block on the correct pd */
1323 		io_info->span_arm =
1324 			(span << RAID_CTX_SPANARM_SPAN_SHIFT) | bestArm;
1325 		io_info->pd_after_lb = (bestArm == arm) ? pd0 : pd1;
1326 	}
1327 
1328 	lbInfo->last_accessed_block[io_info->pd_after_lb] = block + count - 1;
1329 	return io_info->pd_after_lb;
1330 }
1331 
1332 __le16 get_updated_dev_handle(struct megasas_instance *instance,
1333 			      struct LD_LOAD_BALANCE_INFO *lbInfo,
1334 			      struct IO_REQUEST_INFO *io_info,
1335 			      struct MR_DRV_RAID_MAP_ALL *drv_map)
1336 {
1337 	u8 arm_pd;
1338 	__le16 devHandle;
1339 
1340 	/* get best new arm (PD ID) */
1341 	arm_pd  = megasas_get_best_arm_pd(instance, lbInfo, io_info, drv_map);
1342 	devHandle = MR_PdDevHandleGet(arm_pd, drv_map);
1343 	io_info->pd_interface = MR_PdInterfaceTypeGet(arm_pd, drv_map);
1344 	atomic_inc(&lbInfo->scsi_pending_cmds[arm_pd]);
1345 
1346 	return devHandle;
1347 }
1348