Home | History | Annotate | Line # | Download | only in raidframe
rf_dagutils.c revision 1.38
      1 /*	$NetBSD: rf_dagutils.c,v 1.38 2004/03/18 16:40:05 oster Exp $	*/
      2 /*
      3  * Copyright (c) 1995 Carnegie-Mellon University.
      4  * All rights reserved.
      5  *
      6  * Authors: Mark Holland, William V. Courtright II, Jim Zelenka
      7  *
      8  * Permission to use, copy, modify and distribute this software and
      9  * its documentation is hereby granted, provided that both the copyright
     10  * notice and this permission notice appear in all copies of the
     11  * software, derivative works or modified versions, and any portions
     12  * thereof, and that both notices appear in supporting documentation.
     13  *
     14  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
     15  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
     16  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
     17  *
     18  * Carnegie Mellon requests users of this software to return to
     19  *
     20  *  Software Distribution Coordinator  or  Software.Distribution (at) CS.CMU.EDU
     21  *  School of Computer Science
     22  *  Carnegie Mellon University
     23  *  Pittsburgh PA 15213-3890
     24  *
     25  * any improvements or extensions that they make and grant Carnegie the
     26  * rights to redistribute these changes.
     27  */
     28 
     29 /******************************************************************************
     30  *
     31  * rf_dagutils.c -- utility routines for manipulating dags
     32  *
     33  *****************************************************************************/
     34 
     35 #include <sys/cdefs.h>
     36 __KERNEL_RCSID(0, "$NetBSD: rf_dagutils.c,v 1.38 2004/03/18 16:40:05 oster Exp $");
     37 
     38 #include <dev/raidframe/raidframevar.h>
     39 
     40 #include "rf_archs.h"
     41 #include "rf_threadstuff.h"
     42 #include "rf_raid.h"
     43 #include "rf_dag.h"
     44 #include "rf_dagutils.h"
     45 #include "rf_dagfuncs.h"
     46 #include "rf_general.h"
     47 #include "rf_map.h"
     48 #include "rf_shutdown.h"
     49 
     50 #define SNUM_DIFF(_a_,_b_) (((_a_)>(_b_))?((_a_)-(_b_)):((_b_)-(_a_)))
     51 
     52 const RF_RedFuncs_t rf_xorFuncs = {
     53 	rf_RegularXorFunc, "Reg Xr",
     54 	rf_SimpleXorFunc, "Simple Xr"};
     55 
     56 const RF_RedFuncs_t rf_xorRecoveryFuncs = {
     57 	rf_RecoveryXorFunc, "Recovery Xr",
     58 	rf_RecoveryXorFunc, "Recovery Xr"};
     59 
     60 #if RF_DEBUG_VALIDATE_DAG
     61 static void rf_RecurPrintDAG(RF_DagNode_t *, int, int);
     62 static void rf_PrintDAG(RF_DagHeader_t *);
     63 static int rf_ValidateBranch(RF_DagNode_t *, int *, int *,
     64 			     RF_DagNode_t **, int);
     65 static void rf_ValidateBranchVisitedBits(RF_DagNode_t *, int, int);
     66 static void rf_ValidateVisitedBits(RF_DagHeader_t *);
     67 #endif /* RF_DEBUG_VALIDATE_DAG */
     68 
     69 /******************************************************************************
     70  *
     71  * InitNode - initialize a dag node
     72  *
     73  * the size of the propList array is always the same as that of the
     74  * successors array.
     75  *
     76  *****************************************************************************/
     77 void
     78 rf_InitNode(RF_DagNode_t *node, RF_NodeStatus_t initstatus, int commit,
     79     int (*doFunc) (RF_DagNode_t *node),
     80     int (*undoFunc) (RF_DagNode_t *node),
     81     int (*wakeFunc) (RF_DagNode_t *node, int status),
     82     int nSucc, int nAnte, int nParam, int nResult,
     83     RF_DagHeader_t *hdr, char *name, RF_AllocListElem_t *alist)
     84 {
     85 	void  **ptrs;
     86 	int     nptrs;
     87 
     88 	if (nAnte > RF_MAX_ANTECEDENTS)
     89 		RF_PANIC();
     90 	node->status = initstatus;
     91 	node->commitNode = commit;
     92 	node->doFunc = doFunc;
     93 	node->undoFunc = undoFunc;
     94 	node->wakeFunc = wakeFunc;
     95 	node->numParams = nParam;
     96 	node->numResults = nResult;
     97 	node->numAntecedents = nAnte;
     98 	node->numAntDone = 0;
     99 	node->next = NULL;
    100 	/* node->list_next = NULL */  /* Don't touch this here!
    101 	                                 It may already be
    102 					 in use by the caller! */
    103 	node->numSuccedents = nSucc;
    104 	node->name = name;
    105 	node->dagHdr = hdr;
    106 	node->visited = 0;
    107 
    108 	/* allocate all the pointers with one call to malloc */
    109 	nptrs = nSucc + nAnte + nResult + nSucc;
    110 
    111 	if (nptrs <= RF_DAG_PTRCACHESIZE) {
    112 		/*
    113 	         * The dag_ptrs field of the node is basically some scribble
    114 	         * space to be used here. We could get rid of it, and always
    115 	         * allocate the range of pointers, but that's expensive. So,
    116 	         * we pick a "common case" size for the pointer cache. Hopefully,
    117 	         * we'll find that:
    118 	         * (1) Generally, nptrs doesn't exceed RF_DAG_PTRCACHESIZE by
    119 	         *     only a little bit (least efficient case)
    120 	         * (2) Generally, ntprs isn't a lot less than RF_DAG_PTRCACHESIZE
    121 	         *     (wasted memory)
    122 	         */
    123 		ptrs = (void **) node->dag_ptrs;
    124 	} else {
    125 		RF_MallocAndAdd(ptrs, nptrs * sizeof(void *),
    126 				(void **), alist);
    127 	}
    128 	node->succedents = (nSucc) ? (RF_DagNode_t **) ptrs : NULL;
    129 	node->antecedents = (nAnte) ? (RF_DagNode_t **) (ptrs + nSucc) : NULL;
    130 	node->results = (nResult) ? (void **) (ptrs + nSucc + nAnte) : NULL;
    131 	node->propList = (nSucc) ? (RF_PropHeader_t **) (ptrs + nSucc + nAnte + nResult) : NULL;
    132 
    133 	if (nParam) {
    134 		if (nParam <= RF_DAG_PARAMCACHESIZE) {
    135 			node->params = (RF_DagParam_t *) node->dag_params;
    136 		} else {
    137 			RF_MallocAndAdd(node->params,
    138 					nParam * sizeof(RF_DagParam_t),
    139 					(RF_DagParam_t *), alist);
    140 		}
    141 	} else {
    142 		node->params = NULL;
    143 	}
    144 }
    145 
    146 
    147 
    148 /******************************************************************************
    149  *
    150  * allocation and deallocation routines
    151  *
    152  *****************************************************************************/
    153 
    154 void
    155 rf_FreeDAG(RF_DagHeader_t *dag_h)
    156 {
    157 	RF_AccessStripeMapHeader_t *asmap, *t_asmap;
    158 	RF_DagNode_t *tmpnode;
    159 	RF_DagHeader_t *nextDag;
    160 
    161 	while (dag_h) {
    162 		nextDag = dag_h->next;
    163 		rf_FreeAllocList(dag_h->allocList);
    164 		for (asmap = dag_h->asmList; asmap;) {
    165 			t_asmap = asmap;
    166 			asmap = asmap->next;
    167 			rf_FreeAccessStripeMap(t_asmap);
    168 		}
    169 		while(dag_h->nodes) {
    170 			tmpnode = dag_h->nodes;
    171 			dag_h->nodes = dag_h->nodes->list_next;
    172 			rf_FreeDAGNode(tmpnode);
    173 		}
    174 		rf_FreeDAGHeader(dag_h);
    175 		dag_h = nextDag;
    176 	}
    177 }
    178 
    179 #define RF_MAX_FREE_DAGH 128
    180 #define RF_MIN_FREE_DAGH  32
    181 
    182 #define RF_MAX_FREE_DAGNODE 512 /* XXX Tune this... */
    183 #define RF_MIN_FREE_DAGNODE 128 /* XXX Tune this... */
    184 
    185 #define RF_MAX_FREE_DAGLIST 128
    186 #define RF_MIN_FREE_DAGLIST  32
    187 
    188 #define RF_MAX_FREE_FUNCLIST 128
    189 #define RF_MIN_FREE_FUNCLIST  32
    190 
    191 static void rf_ShutdownDAGs(void *);
    192 static void
    193 rf_ShutdownDAGs(void *ignored)
    194 {
    195 	pool_destroy(&rf_pools.dagh);
    196 	pool_destroy(&rf_pools.dagnode);
    197 	pool_destroy(&rf_pools.daglist);
    198 	pool_destroy(&rf_pools.funclist);
    199 }
    200 
    201 int
    202 rf_ConfigureDAGs(RF_ShutdownList_t **listp)
    203 {
    204 
    205 	rf_pool_init(&rf_pools.dagnode, sizeof(RF_DagNode_t),
    206 		     "rf_dagnode_pl", RF_MIN_FREE_DAGNODE, RF_MAX_FREE_DAGNODE);
    207 	rf_pool_init(&rf_pools.dagh, sizeof(RF_DagHeader_t),
    208 		     "rf_dagh_pl", RF_MIN_FREE_DAGH, RF_MAX_FREE_DAGH);
    209 	rf_pool_init(&rf_pools.daglist, sizeof(RF_DagList_t),
    210 		     "rf_daglist_pl", RF_MIN_FREE_DAGLIST, RF_MAX_FREE_DAGLIST);
    211 	rf_pool_init(&rf_pools.funclist, sizeof(RF_FuncList_t),
    212 		     "rf_funclist_pl", RF_MIN_FREE_FUNCLIST, RF_MAX_FREE_FUNCLIST);
    213 	rf_ShutdownCreate(listp, rf_ShutdownDAGs, NULL);
    214 
    215 	return (0);
    216 }
    217 
    218 RF_DagHeader_t *
    219 rf_AllocDAGHeader()
    220 {
    221 	RF_DagHeader_t *dh;
    222 
    223 	dh = pool_get(&rf_pools.dagh, PR_WAITOK);
    224 	memset((char *) dh, 0, sizeof(RF_DagHeader_t));
    225 	return (dh);
    226 }
    227 
    228 void
    229 rf_FreeDAGHeader(RF_DagHeader_t * dh)
    230 {
    231 	pool_put(&rf_pools.dagh, dh);
    232 }
    233 
    234 RF_DagNode_t *
    235 rf_AllocDAGNode()
    236 {
    237 	RF_DagNode_t *node;
    238 
    239 	node = pool_get(&rf_pools.dagnode, PR_WAITOK);
    240 	memset(node, 0, sizeof(RF_DagNode_t));
    241 	return (node);
    242 }
    243 
    244 void
    245 rf_FreeDAGNode(RF_DagNode_t *node)
    246 {
    247 	pool_put(&rf_pools.dagnode, node);
    248 }
    249 
    250 RF_DagList_t *
    251 rf_AllocDAGList()
    252 {
    253 	RF_DagList_t *dagList;
    254 
    255 	dagList = pool_get(&rf_pools.daglist, PR_WAITOK);
    256 	memset(dagList, 0, sizeof(RF_DagList_t));
    257 
    258 	return (dagList);
    259 }
    260 
    261 void
    262 rf_FreeDAGList(RF_DagList_t *dagList)
    263 {
    264 	pool_put(&rf_pools.daglist, dagList);
    265 }
    266 
    267 RF_FuncList_t *
    268 rf_AllocFuncList()
    269 {
    270 	RF_FuncList_t *funcList;
    271 
    272 	funcList = pool_get(&rf_pools.funclist, PR_WAITOK);
    273 	memset(funcList, 0, sizeof(RF_FuncList_t));
    274 
    275 	return (funcList);
    276 }
    277 
    278 void
    279 rf_FreeFuncList(RF_FuncList_t *funcList)
    280 {
    281 	pool_put(&rf_pools.funclist, funcList);
    282 }
    283 
    284 
    285 
    286 /* allocates a buffer big enough to hold the data described by pda */
    287 void   *
    288 rf_AllocBuffer(RF_Raid_t *raidPtr, RF_PhysDiskAddr_t *pda,
    289 	       RF_AllocListElem_t *allocList)
    290 {
    291 	char   *p;
    292 
    293 	RF_MallocAndAdd(p, pda->numSector << raidPtr->logBytesPerSector,
    294 	    (char *), allocList);
    295 	return ((void *) p);
    296 }
    297 #if RF_DEBUG_VALIDATE_DAG
    298 /******************************************************************************
    299  *
    300  * debug routines
    301  *
    302  *****************************************************************************/
    303 
    304 char   *
    305 rf_NodeStatusString(RF_DagNode_t *node)
    306 {
    307 	switch (node->status) {
    308 	case rf_wait:
    309 		return ("wait");
    310 	case rf_fired:
    311 		return ("fired");
    312 	case rf_good:
    313 		return ("good");
    314 	case rf_bad:
    315 		return ("bad");
    316 	default:
    317 		return ("?");
    318 	}
    319 }
    320 
    321 void
    322 rf_PrintNodeInfoString(RF_DagNode_t *node)
    323 {
    324 	RF_PhysDiskAddr_t *pda;
    325 	int     (*df) (RF_DagNode_t *) = node->doFunc;
    326 	int     i, lk, unlk;
    327 	void   *bufPtr;
    328 
    329 	if ((df == rf_DiskReadFunc) || (df == rf_DiskWriteFunc)
    330 	    || (df == rf_DiskReadMirrorIdleFunc)
    331 	    || (df == rf_DiskReadMirrorPartitionFunc)) {
    332 		pda = (RF_PhysDiskAddr_t *) node->params[0].p;
    333 		bufPtr = (void *) node->params[1].p;
    334 		lk = 0;
    335 		unlk = 0;
    336 		RF_ASSERT(!(lk && unlk));
    337 		printf("c %d offs %ld nsect %d buf 0x%lx %s\n", pda->col,
    338 		    (long) pda->startSector, (int) pda->numSector, (long) bufPtr,
    339 		    (lk) ? "LOCK" : ((unlk) ? "UNLK" : " "));
    340 		return;
    341 	}
    342 	if (df == rf_DiskUnlockFunc) {
    343 		pda = (RF_PhysDiskAddr_t *) node->params[0].p;
    344 		lk = 0;
    345 		unlk = 0;
    346 		RF_ASSERT(!(lk && unlk));
    347 		printf("c %d %s\n", pda->col,
    348 		    (lk) ? "LOCK" : ((unlk) ? "UNLK" : "nop"));
    349 		return;
    350 	}
    351 	if ((df == rf_SimpleXorFunc) || (df == rf_RegularXorFunc)
    352 	    || (df == rf_RecoveryXorFunc)) {
    353 		printf("result buf 0x%lx\n", (long) node->results[0]);
    354 		for (i = 0; i < node->numParams - 1; i += 2) {
    355 			pda = (RF_PhysDiskAddr_t *) node->params[i].p;
    356 			bufPtr = (RF_PhysDiskAddr_t *) node->params[i + 1].p;
    357 			printf("    buf 0x%lx c%d offs %ld nsect %d\n",
    358 			    (long) bufPtr, pda->col,
    359 			    (long) pda->startSector, (int) pda->numSector);
    360 		}
    361 		return;
    362 	}
    363 #if RF_INCLUDE_PARITYLOGGING > 0
    364 	if (df == rf_ParityLogOverwriteFunc || df == rf_ParityLogUpdateFunc) {
    365 		for (i = 0; i < node->numParams - 1; i += 2) {
    366 			pda = (RF_PhysDiskAddr_t *) node->params[i].p;
    367 			bufPtr = (RF_PhysDiskAddr_t *) node->params[i + 1].p;
    368 			printf(" c%d offs %ld nsect %d buf 0x%lx\n",
    369 			    pda->col, (long) pda->startSector,
    370 			    (int) pda->numSector, (long) bufPtr);
    371 		}
    372 		return;
    373 	}
    374 #endif				/* RF_INCLUDE_PARITYLOGGING > 0 */
    375 
    376 	if ((df == rf_TerminateFunc) || (df == rf_NullNodeFunc)) {
    377 		printf("\n");
    378 		return;
    379 	}
    380 	printf("?\n");
    381 }
    382 #ifdef DEBUG
    383 static void
    384 rf_RecurPrintDAG(RF_DagNode_t *node, int depth, int unvisited)
    385 {
    386 	char   *anttype;
    387 	int     i;
    388 
    389 	node->visited = (unvisited) ? 0 : 1;
    390 	printf("(%d) %d C%d %s: %s,s%d %d/%d,a%d/%d,p%d,r%d S{", depth,
    391 	    node->nodeNum, node->commitNode, node->name, rf_NodeStatusString(node),
    392 	    node->numSuccedents, node->numSuccFired, node->numSuccDone,
    393 	    node->numAntecedents, node->numAntDone, node->numParams, node->numResults);
    394 	for (i = 0; i < node->numSuccedents; i++) {
    395 		printf("%d%s", node->succedents[i]->nodeNum,
    396 		    ((i == node->numSuccedents - 1) ? "\0" : " "));
    397 	}
    398 	printf("} A{");
    399 	for (i = 0; i < node->numAntecedents; i++) {
    400 		switch (node->antType[i]) {
    401 		case rf_trueData:
    402 			anttype = "T";
    403 			break;
    404 		case rf_antiData:
    405 			anttype = "A";
    406 			break;
    407 		case rf_outputData:
    408 			anttype = "O";
    409 			break;
    410 		case rf_control:
    411 			anttype = "C";
    412 			break;
    413 		default:
    414 			anttype = "?";
    415 			break;
    416 		}
    417 		printf("%d(%s)%s", node->antecedents[i]->nodeNum, anttype, (i == node->numAntecedents - 1) ? "\0" : " ");
    418 	}
    419 	printf("}; ");
    420 	rf_PrintNodeInfoString(node);
    421 	for (i = 0; i < node->numSuccedents; i++) {
    422 		if (node->succedents[i]->visited == unvisited)
    423 			rf_RecurPrintDAG(node->succedents[i], depth + 1, unvisited);
    424 	}
    425 }
    426 
    427 static void
    428 rf_PrintDAG(RF_DagHeader_t *dag_h)
    429 {
    430 	int     unvisited, i;
    431 	char   *status;
    432 
    433 	/* set dag status */
    434 	switch (dag_h->status) {
    435 	case rf_enable:
    436 		status = "enable";
    437 		break;
    438 	case rf_rollForward:
    439 		status = "rollForward";
    440 		break;
    441 	case rf_rollBackward:
    442 		status = "rollBackward";
    443 		break;
    444 	default:
    445 		status = "illegal!";
    446 		break;
    447 	}
    448 	/* find out if visited bits are currently set or clear */
    449 	unvisited = dag_h->succedents[0]->visited;
    450 
    451 	printf("DAG type:  %s\n", dag_h->creator);
    452 	printf("format is (depth) num commit type: status,nSucc nSuccFired/nSuccDone,nAnte/nAnteDone,nParam,nResult S{x} A{x(type)};  info\n");
    453 	printf("(0) %d Hdr: %s, s%d, (commit %d/%d) S{", dag_h->nodeNum,
    454 	    status, dag_h->numSuccedents, dag_h->numCommitNodes, dag_h->numCommits);
    455 	for (i = 0; i < dag_h->numSuccedents; i++) {
    456 		printf("%d%s", dag_h->succedents[i]->nodeNum,
    457 		    ((i == dag_h->numSuccedents - 1) ? "\0" : " "));
    458 	}
    459 	printf("};\n");
    460 	for (i = 0; i < dag_h->numSuccedents; i++) {
    461 		if (dag_h->succedents[i]->visited == unvisited)
    462 			rf_RecurPrintDAG(dag_h->succedents[i], 1, unvisited);
    463 	}
    464 }
    465 #endif
    466 /* assigns node numbers */
    467 int
    468 rf_AssignNodeNums(RF_DagHeader_t * dag_h)
    469 {
    470 	int     unvisited, i, nnum;
    471 	RF_DagNode_t *node;
    472 
    473 	nnum = 0;
    474 	unvisited = dag_h->succedents[0]->visited;
    475 
    476 	dag_h->nodeNum = nnum++;
    477 	for (i = 0; i < dag_h->numSuccedents; i++) {
    478 		node = dag_h->succedents[i];
    479 		if (node->visited == unvisited) {
    480 			nnum = rf_RecurAssignNodeNums(dag_h->succedents[i], nnum, unvisited);
    481 		}
    482 	}
    483 	return (nnum);
    484 }
    485 
    486 int
    487 rf_RecurAssignNodeNums(RF_DagNode_t *node, int num, int unvisited)
    488 {
    489 	int     i;
    490 
    491 	node->visited = (unvisited) ? 0 : 1;
    492 
    493 	node->nodeNum = num++;
    494 	for (i = 0; i < node->numSuccedents; i++) {
    495 		if (node->succedents[i]->visited == unvisited) {
    496 			num = rf_RecurAssignNodeNums(node->succedents[i], num, unvisited);
    497 		}
    498 	}
    499 	return (num);
    500 }
    501 /* set the header pointers in each node to "newptr" */
    502 void
    503 rf_ResetDAGHeaderPointers(RF_DagHeader_t *dag_h, RF_DagHeader_t *newptr)
    504 {
    505 	int     i;
    506 	for (i = 0; i < dag_h->numSuccedents; i++)
    507 		if (dag_h->succedents[i]->dagHdr != newptr)
    508 			rf_RecurResetDAGHeaderPointers(dag_h->succedents[i], newptr);
    509 }
    510 
    511 void
    512 rf_RecurResetDAGHeaderPointers(RF_DagNode_t *node, RF_DagHeader_t *newptr)
    513 {
    514 	int     i;
    515 	node->dagHdr = newptr;
    516 	for (i = 0; i < node->numSuccedents; i++)
    517 		if (node->succedents[i]->dagHdr != newptr)
    518 			rf_RecurResetDAGHeaderPointers(node->succedents[i], newptr);
    519 }
    520 
    521 
    522 void
    523 rf_PrintDAGList(RF_DagHeader_t * dag_h)
    524 {
    525 	int     i = 0;
    526 
    527 	for (; dag_h; dag_h = dag_h->next) {
    528 		rf_AssignNodeNums(dag_h);
    529 		printf("\n\nDAG %d IN LIST:\n", i++);
    530 		rf_PrintDAG(dag_h);
    531 	}
    532 }
    533 
    534 static int
    535 rf_ValidateBranch(RF_DagNode_t *node, int *scount, int *acount,
    536 		  RF_DagNode_t **nodes, int unvisited)
    537 {
    538 	int     i, retcode = 0;
    539 
    540 	/* construct an array of node pointers indexed by node num */
    541 	node->visited = (unvisited) ? 0 : 1;
    542 	nodes[node->nodeNum] = node;
    543 
    544 	if (node->next != NULL) {
    545 		printf("INVALID DAG: next pointer in node is not NULL\n");
    546 		retcode = 1;
    547 	}
    548 	if (node->status != rf_wait) {
    549 		printf("INVALID DAG: Node status is not wait\n");
    550 		retcode = 1;
    551 	}
    552 	if (node->numAntDone != 0) {
    553 		printf("INVALID DAG: numAntDone is not zero\n");
    554 		retcode = 1;
    555 	}
    556 	if (node->doFunc == rf_TerminateFunc) {
    557 		if (node->numSuccedents != 0) {
    558 			printf("INVALID DAG: Terminator node has succedents\n");
    559 			retcode = 1;
    560 		}
    561 	} else {
    562 		if (node->numSuccedents == 0) {
    563 			printf("INVALID DAG: Non-terminator node has no succedents\n");
    564 			retcode = 1;
    565 		}
    566 	}
    567 	for (i = 0; i < node->numSuccedents; i++) {
    568 		if (!node->succedents[i]) {
    569 			printf("INVALID DAG: succedent %d of node %s is NULL\n", i, node->name);
    570 			retcode = 1;
    571 		}
    572 		scount[node->succedents[i]->nodeNum]++;
    573 	}
    574 	for (i = 0; i < node->numAntecedents; i++) {
    575 		if (!node->antecedents[i]) {
    576 			printf("INVALID DAG: antecedent %d of node %s is NULL\n", i, node->name);
    577 			retcode = 1;
    578 		}
    579 		acount[node->antecedents[i]->nodeNum]++;
    580 	}
    581 	for (i = 0; i < node->numSuccedents; i++) {
    582 		if (node->succedents[i]->visited == unvisited) {
    583 			if (rf_ValidateBranch(node->succedents[i], scount,
    584 				acount, nodes, unvisited)) {
    585 				retcode = 1;
    586 			}
    587 		}
    588 	}
    589 	return (retcode);
    590 }
    591 
    592 static void
    593 rf_ValidateBranchVisitedBits(RF_DagNode_t *node, int unvisited, int rl)
    594 {
    595 	int     i;
    596 
    597 	RF_ASSERT(node->visited == unvisited);
    598 	for (i = 0; i < node->numSuccedents; i++) {
    599 		if (node->succedents[i] == NULL) {
    600 			printf("node=%lx node->succedents[%d] is NULL\n", (long) node, i);
    601 			RF_ASSERT(0);
    602 		}
    603 		rf_ValidateBranchVisitedBits(node->succedents[i], unvisited, rl + 1);
    604 	}
    605 }
    606 /* NOTE:  never call this on a big dag, because it is exponential
    607  * in execution time
    608  */
    609 static void
    610 rf_ValidateVisitedBits(RF_DagHeader_t *dag)
    611 {
    612 	int     i, unvisited;
    613 
    614 	unvisited = dag->succedents[0]->visited;
    615 
    616 	for (i = 0; i < dag->numSuccedents; i++) {
    617 		if (dag->succedents[i] == NULL) {
    618 			printf("dag=%lx dag->succedents[%d] is NULL\n", (long) dag, i);
    619 			RF_ASSERT(0);
    620 		}
    621 		rf_ValidateBranchVisitedBits(dag->succedents[i], unvisited, 0);
    622 	}
    623 }
    624 /* validate a DAG.  _at entry_ verify that:
    625  *   -- numNodesCompleted is zero
    626  *   -- node queue is null
    627  *   -- dag status is rf_enable
    628  *   -- next pointer is null on every node
    629  *   -- all nodes have status wait
    630  *   -- numAntDone is zero in all nodes
    631  *   -- terminator node has zero successors
    632  *   -- no other node besides terminator has zero successors
    633  *   -- no successor or antecedent pointer in a node is NULL
    634  *   -- number of times that each node appears as a successor of another node
    635  *      is equal to the antecedent count on that node
    636  *   -- number of times that each node appears as an antecedent of another node
    637  *      is equal to the succedent count on that node
    638  *   -- what else?
    639  */
    640 int
    641 rf_ValidateDAG(RF_DagHeader_t *dag_h)
    642 {
    643 	int     i, nodecount;
    644 	int    *scount, *acount;/* per-node successor and antecedent counts */
    645 	RF_DagNode_t **nodes;	/* array of ptrs to nodes in dag */
    646 	int     retcode = 0;
    647 	int     unvisited;
    648 	int     commitNodeCount = 0;
    649 
    650 	if (rf_validateVisitedDebug)
    651 		rf_ValidateVisitedBits(dag_h);
    652 
    653 	if (dag_h->numNodesCompleted != 0) {
    654 		printf("INVALID DAG: num nodes completed is %d, should be 0\n", dag_h->numNodesCompleted);
    655 		retcode = 1;
    656 		goto validate_dag_bad;
    657 	}
    658 	if (dag_h->status != rf_enable) {
    659 		printf("INVALID DAG: not enabled\n");
    660 		retcode = 1;
    661 		goto validate_dag_bad;
    662 	}
    663 	if (dag_h->numCommits != 0) {
    664 		printf("INVALID DAG: numCommits != 0 (%d)\n", dag_h->numCommits);
    665 		retcode = 1;
    666 		goto validate_dag_bad;
    667 	}
    668 	if (dag_h->numSuccedents != 1) {
    669 		/* currently, all dags must have only one succedent */
    670 		printf("INVALID DAG: numSuccedents !1 (%d)\n", dag_h->numSuccedents);
    671 		retcode = 1;
    672 		goto validate_dag_bad;
    673 	}
    674 	nodecount = rf_AssignNodeNums(dag_h);
    675 
    676 	unvisited = dag_h->succedents[0]->visited;
    677 
    678 	RF_Malloc(scount, nodecount * sizeof(int), (int *));
    679 	RF_Malloc(acount, nodecount * sizeof(int), (int *));
    680 	RF_Malloc(nodes, nodecount * sizeof(RF_DagNode_t *),
    681 		  (RF_DagNode_t **));
    682 	for (i = 0; i < dag_h->numSuccedents; i++) {
    683 		if ((dag_h->succedents[i]->visited == unvisited)
    684 		    && rf_ValidateBranch(dag_h->succedents[i], scount,
    685 			acount, nodes, unvisited)) {
    686 			retcode = 1;
    687 		}
    688 	}
    689 	/* start at 1 to skip the header node */
    690 	for (i = 1; i < nodecount; i++) {
    691 		if (nodes[i]->commitNode)
    692 			commitNodeCount++;
    693 		if (nodes[i]->doFunc == NULL) {
    694 			printf("INVALID DAG: node %s has an undefined doFunc\n", nodes[i]->name);
    695 			retcode = 1;
    696 			goto validate_dag_out;
    697 		}
    698 		if (nodes[i]->undoFunc == NULL) {
    699 			printf("INVALID DAG: node %s has an undefined doFunc\n", nodes[i]->name);
    700 			retcode = 1;
    701 			goto validate_dag_out;
    702 		}
    703 		if (nodes[i]->numAntecedents != scount[nodes[i]->nodeNum]) {
    704 			printf("INVALID DAG: node %s has %d antecedents but appears as a succedent %d times\n",
    705 			    nodes[i]->name, nodes[i]->numAntecedents, scount[nodes[i]->nodeNum]);
    706 			retcode = 1;
    707 			goto validate_dag_out;
    708 		}
    709 		if (nodes[i]->numSuccedents != acount[nodes[i]->nodeNum]) {
    710 			printf("INVALID DAG: node %s has %d succedents but appears as an antecedent %d times\n",
    711 			    nodes[i]->name, nodes[i]->numSuccedents, acount[nodes[i]->nodeNum]);
    712 			retcode = 1;
    713 			goto validate_dag_out;
    714 		}
    715 	}
    716 
    717 	if (dag_h->numCommitNodes != commitNodeCount) {
    718 		printf("INVALID DAG: incorrect commit node count.  hdr->numCommitNodes (%d) found (%d) commit nodes in graph\n",
    719 		    dag_h->numCommitNodes, commitNodeCount);
    720 		retcode = 1;
    721 		goto validate_dag_out;
    722 	}
    723 validate_dag_out:
    724 	RF_Free(scount, nodecount * sizeof(int));
    725 	RF_Free(acount, nodecount * sizeof(int));
    726 	RF_Free(nodes, nodecount * sizeof(RF_DagNode_t *));
    727 	if (retcode)
    728 		rf_PrintDAGList(dag_h);
    729 
    730 	if (rf_validateVisitedDebug)
    731 		rf_ValidateVisitedBits(dag_h);
    732 
    733 	return (retcode);
    734 
    735 validate_dag_bad:
    736 	rf_PrintDAGList(dag_h);
    737 	return (retcode);
    738 }
    739 
    740 #endif /* RF_DEBUG_VALIDATE_DAG */
    741 
    742 /******************************************************************************
    743  *
    744  * misc construction routines
    745  *
    746  *****************************************************************************/
    747 
    748 void
    749 rf_redirect_asm(RF_Raid_t *raidPtr, RF_AccessStripeMap_t *asmap)
    750 {
    751 	int     ds = (raidPtr->Layout.map->flags & RF_DISTRIBUTE_SPARE) ? 1 : 0;
    752 	int     fcol = raidPtr->reconControl->fcol;
    753 	int     scol = raidPtr->reconControl->spareCol;
    754 	RF_PhysDiskAddr_t *pda;
    755 
    756 	RF_ASSERT(raidPtr->status == rf_rs_reconstructing);
    757 	for (pda = asmap->physInfo; pda; pda = pda->next) {
    758 		if (pda->col == fcol) {
    759 #if RF_DEBUG_DAG
    760 			if (rf_dagDebug) {
    761 				if (!rf_CheckRUReconstructed(raidPtr->reconControl->reconMap,
    762 					pda->startSector)) {
    763 					RF_PANIC();
    764 				}
    765 			}
    766 #endif
    767 			/* printf("Remapped data for large write\n"); */
    768 			if (ds) {
    769 				raidPtr->Layout.map->MapSector(raidPtr, pda->raidAddress,
    770 				    &pda->col, &pda->startSector, RF_REMAP);
    771 			} else {
    772 				pda->col = scol;
    773 			}
    774 		}
    775 	}
    776 	for (pda = asmap->parityInfo; pda; pda = pda->next) {
    777 		if (pda->col == fcol) {
    778 #if RF_DEBUG_DAG
    779 			if (rf_dagDebug) {
    780 				if (!rf_CheckRUReconstructed(raidPtr->reconControl->reconMap, pda->startSector)) {
    781 					RF_PANIC();
    782 				}
    783 			}
    784 #endif
    785 		}
    786 		if (ds) {
    787 			(raidPtr->Layout.map->MapParity) (raidPtr, pda->raidAddress, &pda->col, &pda->startSector, RF_REMAP);
    788 		} else {
    789 			pda->col = scol;
    790 		}
    791 	}
    792 }
    793 
    794 
    795 /* this routine allocates read buffers and generates stripe maps for the
    796  * regions of the array from the start of the stripe to the start of the
    797  * access, and from the end of the access to the end of the stripe.  It also
    798  * computes and returns the number of DAG nodes needed to read all this data.
    799  * Note that this routine does the wrong thing if the access is fully
    800  * contained within one stripe unit, so we RF_ASSERT against this case at the
    801  * start.
    802  *
    803  * layoutPtr - in: layout information
    804  * asmap     - in: access stripe map
    805  * dag_h     - in: header of the dag to create
    806  * new_asm_h - in: ptr to array of 2 headers.  to be filled in
    807  * nRodNodes - out: num nodes to be generated to read unaccessed data
    808  * sosBuffer, eosBuffer - out: pointers to newly allocated buffer
    809  */
    810 void
    811 rf_MapUnaccessedPortionOfStripe(RF_Raid_t *raidPtr,
    812 				RF_RaidLayout_t *layoutPtr,
    813 				RF_AccessStripeMap_t *asmap,
    814 				RF_DagHeader_t *dag_h,
    815 				RF_AccessStripeMapHeader_t **new_asm_h,
    816 				int *nRodNodes,
    817 				char **sosBuffer, char **eosBuffer,
    818 				RF_AllocListElem_t *allocList)
    819 {
    820 	RF_RaidAddr_t sosRaidAddress, eosRaidAddress;
    821 	RF_SectorNum_t sosNumSector, eosNumSector;
    822 
    823 	RF_ASSERT(asmap->numStripeUnitsAccessed > (layoutPtr->numDataCol / 2));
    824 	/* generate an access map for the region of the array from start of
    825 	 * stripe to start of access */
    826 	new_asm_h[0] = new_asm_h[1] = NULL;
    827 	*nRodNodes = 0;
    828 	if (!rf_RaidAddressStripeAligned(layoutPtr, asmap->raidAddress)) {
    829 		sosRaidAddress = rf_RaidAddressOfPrevStripeBoundary(layoutPtr, asmap->raidAddress);
    830 		sosNumSector = asmap->raidAddress - sosRaidAddress;
    831 		RF_MallocAndAdd(*sosBuffer, rf_RaidAddressToByte(raidPtr, sosNumSector), (char *), allocList);
    832 		new_asm_h[0] = rf_MapAccess(raidPtr, sosRaidAddress, sosNumSector, *sosBuffer, RF_DONT_REMAP);
    833 		new_asm_h[0]->next = dag_h->asmList;
    834 		dag_h->asmList = new_asm_h[0];
    835 		*nRodNodes += new_asm_h[0]->stripeMap->numStripeUnitsAccessed;
    836 
    837 		RF_ASSERT(new_asm_h[0]->stripeMap->next == NULL);
    838 		/* we're totally within one stripe here */
    839 		if (asmap->flags & RF_ASM_REDIR_LARGE_WRITE)
    840 			rf_redirect_asm(raidPtr, new_asm_h[0]->stripeMap);
    841 	}
    842 	/* generate an access map for the region of the array from end of
    843 	 * access to end of stripe */
    844 	if (!rf_RaidAddressStripeAligned(layoutPtr, asmap->endRaidAddress)) {
    845 		eosRaidAddress = asmap->endRaidAddress;
    846 		eosNumSector = rf_RaidAddressOfNextStripeBoundary(layoutPtr, eosRaidAddress) - eosRaidAddress;
    847 		RF_MallocAndAdd(*eosBuffer, rf_RaidAddressToByte(raidPtr, eosNumSector), (char *), allocList);
    848 		new_asm_h[1] = rf_MapAccess(raidPtr, eosRaidAddress, eosNumSector, *eosBuffer, RF_DONT_REMAP);
    849 		new_asm_h[1]->next = dag_h->asmList;
    850 		dag_h->asmList = new_asm_h[1];
    851 		*nRodNodes += new_asm_h[1]->stripeMap->numStripeUnitsAccessed;
    852 
    853 		RF_ASSERT(new_asm_h[1]->stripeMap->next == NULL);
    854 		/* we're totally within one stripe here */
    855 		if (asmap->flags & RF_ASM_REDIR_LARGE_WRITE)
    856 			rf_redirect_asm(raidPtr, new_asm_h[1]->stripeMap);
    857 	}
    858 }
    859 
    860 
    861 
    862 /* returns non-zero if the indicated ranges of stripe unit offsets overlap */
    863 int
    864 rf_PDAOverlap(RF_RaidLayout_t *layoutPtr,
    865 	      RF_PhysDiskAddr_t *src, RF_PhysDiskAddr_t *dest)
    866 {
    867 	RF_SectorNum_t soffs = rf_StripeUnitOffset(layoutPtr, src->startSector);
    868 	RF_SectorNum_t doffs = rf_StripeUnitOffset(layoutPtr, dest->startSector);
    869 	/* use -1 to be sure we stay within SU */
    870 	RF_SectorNum_t send = rf_StripeUnitOffset(layoutPtr, src->startSector + src->numSector - 1);
    871 	RF_SectorNum_t dend = rf_StripeUnitOffset(layoutPtr, dest->startSector + dest->numSector - 1);
    872 	return ((RF_MAX(soffs, doffs) <= RF_MIN(send, dend)) ? 1 : 0);
    873 }
    874 
    875 
    876 /* GenerateFailedAccessASMs
    877  *
    878  * this routine figures out what portion of the stripe needs to be read
    879  * to effect the degraded read or write operation.  It's primary function
    880  * is to identify everything required to recover the data, and then
    881  * eliminate anything that is already being accessed by the user.
    882  *
    883  * The main result is two new ASMs, one for the region from the start of the
    884  * stripe to the start of the access, and one for the region from the end of
    885  * the access to the end of the stripe.  These ASMs describe everything that
    886  * needs to be read to effect the degraded access.  Other results are:
    887  *    nXorBufs -- the total number of buffers that need to be XORed together to
    888  *                recover the lost data,
    889  *    rpBufPtr -- ptr to a newly-allocated buffer to hold the parity.  If NULL
    890  *                at entry, not allocated.
    891  *    overlappingPDAs --
    892  *                describes which of the non-failed PDAs in the user access
    893  *                overlap data that needs to be read to effect recovery.
    894  *                overlappingPDAs[i]==1 if and only if, neglecting the failed
    895  *                PDA, the ith pda in the input asm overlaps data that needs
    896  *                to be read for recovery.
    897  */
    898  /* in: asm - ASM for the actual access, one stripe only */
    899  /* in: failedPDA - which component of the access has failed */
    900  /* in: dag_h - header of the DAG we're going to create */
    901  /* out: new_asm_h - the two new ASMs */
    902  /* out: nXorBufs - the total number of xor bufs required */
    903  /* out: rpBufPtr - a buffer for the parity read */
    904 void
    905 rf_GenerateFailedAccessASMs(RF_Raid_t *raidPtr, RF_AccessStripeMap_t *asmap,
    906 			    RF_PhysDiskAddr_t *failedPDA,
    907 			    RF_DagHeader_t *dag_h,
    908 			    RF_AccessStripeMapHeader_t **new_asm_h,
    909 			    int *nXorBufs, char **rpBufPtr,
    910 			    char *overlappingPDAs,
    911 			    RF_AllocListElem_t *allocList)
    912 {
    913 	RF_RaidLayout_t *layoutPtr = &(raidPtr->Layout);
    914 
    915 	/* s=start, e=end, s=stripe, a=access, f=failed, su=stripe unit */
    916 	RF_RaidAddr_t sosAddr, sosEndAddr, eosStartAddr, eosAddr;
    917 	RF_PhysDiskAddr_t *pda;
    918 	int     foundit, i;
    919 
    920 	foundit = 0;
    921 	/* first compute the following raid addresses: start of stripe,
    922 	 * (sosAddr) MIN(start of access, start of failed SU),   (sosEndAddr)
    923 	 * MAX(end of access, end of failed SU),       (eosStartAddr) end of
    924 	 * stripe (i.e. start of next stripe)   (eosAddr) */
    925 	sosAddr = rf_RaidAddressOfPrevStripeBoundary(layoutPtr, asmap->raidAddress);
    926 	sosEndAddr = RF_MIN(asmap->raidAddress, rf_RaidAddressOfPrevStripeUnitBoundary(layoutPtr, failedPDA->raidAddress));
    927 	eosStartAddr = RF_MAX(asmap->endRaidAddress, rf_RaidAddressOfNextStripeUnitBoundary(layoutPtr, failedPDA->raidAddress));
    928 	eosAddr = rf_RaidAddressOfNextStripeBoundary(layoutPtr, asmap->raidAddress);
    929 
    930 	/* now generate access stripe maps for each of the above regions of
    931 	 * the stripe.  Use a dummy (NULL) buf ptr for now */
    932 
    933 	new_asm_h[0] = (sosAddr != sosEndAddr) ? rf_MapAccess(raidPtr, sosAddr, sosEndAddr - sosAddr, NULL, RF_DONT_REMAP) : NULL;
    934 	new_asm_h[1] = (eosStartAddr != eosAddr) ? rf_MapAccess(raidPtr, eosStartAddr, eosAddr - eosStartAddr, NULL, RF_DONT_REMAP) : NULL;
    935 
    936 	/* walk through the PDAs and range-restrict each SU to the region of
    937 	 * the SU touched on the failed PDA.  also compute total data buffer
    938 	 * space requirements in this step.  Ignore the parity for now. */
    939 	/* Also count nodes to find out how many bufs need to be xored together */
    940 	(*nXorBufs) = 1;	/* in read case, 1 is for parity.  In write
    941 				 * case, 1 is for failed data */
    942 
    943 	if (new_asm_h[0]) {
    944 		new_asm_h[0]->next = dag_h->asmList;
    945 		dag_h->asmList = new_asm_h[0];
    946 		for (pda = new_asm_h[0]->stripeMap->physInfo; pda; pda = pda->next) {
    947 			rf_RangeRestrictPDA(raidPtr, failedPDA, pda, RF_RESTRICT_NOBUFFER, 0);
    948 			pda->bufPtr = rf_AllocBuffer(raidPtr, pda, allocList);
    949 		}
    950 		(*nXorBufs) += new_asm_h[0]->stripeMap->numStripeUnitsAccessed;
    951 	}
    952 	if (new_asm_h[1]) {
    953 		new_asm_h[1]->next = dag_h->asmList;
    954 		dag_h->asmList = new_asm_h[1];
    955 		for (pda = new_asm_h[1]->stripeMap->physInfo; pda; pda = pda->next) {
    956 			rf_RangeRestrictPDA(raidPtr, failedPDA, pda, RF_RESTRICT_NOBUFFER, 0);
    957 			pda->bufPtr = rf_AllocBuffer(raidPtr, pda, allocList);
    958 		}
    959 		(*nXorBufs) += new_asm_h[1]->stripeMap->numStripeUnitsAccessed;
    960 	}
    961 
    962 	/* allocate a buffer for parity */
    963 	if (rpBufPtr)
    964 		*rpBufPtr = rf_AllocBuffer(raidPtr, failedPDA, allocList);
    965 
    966 	/* the last step is to figure out how many more distinct buffers need
    967 	 * to get xor'd to produce the missing unit.  there's one for each
    968 	 * user-data read node that overlaps the portion of the failed unit
    969 	 * being accessed */
    970 
    971 	for (foundit = i = 0, pda = asmap->physInfo; pda; i++, pda = pda->next) {
    972 		if (pda == failedPDA) {
    973 			i--;
    974 			foundit = 1;
    975 			continue;
    976 		}
    977 		if (rf_PDAOverlap(layoutPtr, pda, failedPDA)) {
    978 			overlappingPDAs[i] = 1;
    979 			(*nXorBufs)++;
    980 		}
    981 	}
    982 	if (!foundit) {
    983 		RF_ERRORMSG("GenerateFailedAccessASMs: did not find failedPDA in asm list\n");
    984 		RF_ASSERT(0);
    985 	}
    986 #if RF_DEBUG_DAG
    987 	if (rf_degDagDebug) {
    988 		if (new_asm_h[0]) {
    989 			printf("First asm:\n");
    990 			rf_PrintFullAccessStripeMap(new_asm_h[0], 1);
    991 		}
    992 		if (new_asm_h[1]) {
    993 			printf("Second asm:\n");
    994 			rf_PrintFullAccessStripeMap(new_asm_h[1], 1);
    995 		}
    996 	}
    997 #endif
    998 }
    999 
   1000 
   1001 /* adjusts the offset and number of sectors in the destination pda so that
   1002  * it covers at most the region of the SU covered by the source PDA.  This
   1003  * is exclusively a restriction:  the number of sectors indicated by the
   1004  * target PDA can only shrink.
   1005  *
   1006  * For example:  s = sectors within SU indicated by source PDA
   1007  *               d = sectors within SU indicated by dest PDA
   1008  *               r = results, stored in dest PDA
   1009  *
   1010  * |--------------- one stripe unit ---------------------|
   1011  * |           sssssssssssssssssssssssssssssssss         |
   1012  * |    ddddddddddddddddddddddddddddddddddddddddddddd    |
   1013  * |           rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr         |
   1014  *
   1015  * Another example:
   1016  *
   1017  * |--------------- one stripe unit ---------------------|
   1018  * |           sssssssssssssssssssssssssssssssss         |
   1019  * |    ddddddddddddddddddddddd                          |
   1020  * |           rrrrrrrrrrrrrrrr                          |
   1021  *
   1022  */
   1023 void
   1024 rf_RangeRestrictPDA(RF_Raid_t *raidPtr, RF_PhysDiskAddr_t *src,
   1025 		    RF_PhysDiskAddr_t *dest, int dobuffer, int doraidaddr)
   1026 {
   1027 	RF_RaidLayout_t *layoutPtr = &raidPtr->Layout;
   1028 	RF_SectorNum_t soffs = rf_StripeUnitOffset(layoutPtr, src->startSector);
   1029 	RF_SectorNum_t doffs = rf_StripeUnitOffset(layoutPtr, dest->startSector);
   1030 	RF_SectorNum_t send = rf_StripeUnitOffset(layoutPtr, src->startSector + src->numSector - 1);	/* use -1 to be sure we
   1031 													 * stay within SU */
   1032 	RF_SectorNum_t dend = rf_StripeUnitOffset(layoutPtr, dest->startSector + dest->numSector - 1);
   1033 	RF_SectorNum_t subAddr = rf_RaidAddressOfPrevStripeUnitBoundary(layoutPtr, dest->startSector);	/* stripe unit boundary */
   1034 
   1035 	dest->startSector = subAddr + RF_MAX(soffs, doffs);
   1036 	dest->numSector = subAddr + RF_MIN(send, dend) + 1 - dest->startSector;
   1037 
   1038 	if (dobuffer)
   1039 		dest->bufPtr += (soffs > doffs) ? rf_RaidAddressToByte(raidPtr, soffs - doffs) : 0;
   1040 	if (doraidaddr) {
   1041 		dest->raidAddress = rf_RaidAddressOfPrevStripeUnitBoundary(layoutPtr, dest->raidAddress) +
   1042 		    rf_StripeUnitOffset(layoutPtr, dest->startSector);
   1043 	}
   1044 }
   1045 
   1046 #if (RF_INCLUDE_CHAINDECLUSTER > 0)
   1047 
   1048 /*
   1049  * Want the highest of these primes to be the largest one
   1050  * less than the max expected number of columns (won't hurt
   1051  * to be too small or too large, but won't be optimal, either)
   1052  * --jimz
   1053  */
   1054 #define NLOWPRIMES 8
   1055 static int lowprimes[NLOWPRIMES] = {2, 3, 5, 7, 11, 13, 17, 19};
   1056 /*****************************************************************************
   1057  * compute the workload shift factor.  (chained declustering)
   1058  *
   1059  * return nonzero if access should shift to secondary, otherwise,
   1060  * access is to primary
   1061  *****************************************************************************/
   1062 int
   1063 rf_compute_workload_shift(RF_Raid_t *raidPtr, RF_PhysDiskAddr_t *pda)
   1064 {
   1065 	/*
   1066          * variables:
   1067          *  d   = column of disk containing primary
   1068          *  f   = column of failed disk
   1069          *  n   = number of disks in array
   1070          *  sd  = "shift distance" (number of columns that d is to the right of f)
   1071          *  v   = numerator of redirection ratio
   1072          *  k   = denominator of redirection ratio
   1073          */
   1074 	RF_RowCol_t d, f, sd, n;
   1075 	int     k, v, ret, i;
   1076 
   1077 	n = raidPtr->numCol;
   1078 
   1079 	/* assign column of primary copy to d */
   1080 	d = pda->col;
   1081 
   1082 	/* assign column of dead disk to f */
   1083 	for (f = 0; ((!RF_DEAD_DISK(raidPtr->Disks[f].status)) && (f < n)); f++);
   1084 
   1085 	RF_ASSERT(f < n);
   1086 	RF_ASSERT(f != d);
   1087 
   1088 	sd = (f > d) ? (n + d - f) : (d - f);
   1089 	RF_ASSERT(sd < n);
   1090 
   1091 	/*
   1092          * v of every k accesses should be redirected
   1093          *
   1094          * v/k := (n-1-sd)/(n-1)
   1095          */
   1096 	v = (n - 1 - sd);
   1097 	k = (n - 1);
   1098 
   1099 #if 1
   1100 	/*
   1101          * XXX
   1102          * Is this worth it?
   1103          *
   1104          * Now reduce the fraction, by repeatedly factoring
   1105          * out primes (just like they teach in elementary school!)
   1106          */
   1107 	for (i = 0; i < NLOWPRIMES; i++) {
   1108 		if (lowprimes[i] > v)
   1109 			break;
   1110 		while (((v % lowprimes[i]) == 0) && ((k % lowprimes[i]) == 0)) {
   1111 			v /= lowprimes[i];
   1112 			k /= lowprimes[i];
   1113 		}
   1114 	}
   1115 #endif
   1116 
   1117 	raidPtr->hist_diskreq[d]++;
   1118 	if (raidPtr->hist_diskreq[d] > v) {
   1119 		ret = 0;	/* do not redirect */
   1120 	} else {
   1121 		ret = 1;	/* redirect */
   1122 	}
   1123 
   1124 #if 0
   1125 	printf("d=%d f=%d sd=%d v=%d k=%d ret=%d h=%d\n", d, f, sd, v, k, ret,
   1126 	    raidPtr->hist_diskreq[d]);
   1127 #endif
   1128 
   1129 	if (raidPtr->hist_diskreq[d] >= k) {
   1130 		/* reset counter */
   1131 		raidPtr->hist_diskreq[d] = 0;
   1132 	}
   1133 	return (ret);
   1134 }
   1135 #endif /* (RF_INCLUDE_CHAINDECLUSTER > 0) */
   1136 
   1137 /*
   1138  * Disk selection routines
   1139  */
   1140 
   1141 /*
   1142  * Selects the disk with the shortest queue from a mirror pair.
   1143  * Both the disk I/Os queued in RAIDframe as well as those at the physical
   1144  * disk are counted as members of the "queue"
   1145  */
   1146 void
   1147 rf_SelectMirrorDiskIdle(RF_DagNode_t * node)
   1148 {
   1149 	RF_Raid_t *raidPtr = (RF_Raid_t *) node->dagHdr->raidPtr;
   1150 	RF_RowCol_t colData, colMirror;
   1151 	int     dataQueueLength, mirrorQueueLength, usemirror;
   1152 	RF_PhysDiskAddr_t *data_pda = (RF_PhysDiskAddr_t *) node->params[0].p;
   1153 	RF_PhysDiskAddr_t *mirror_pda = (RF_PhysDiskAddr_t *) node->params[4].p;
   1154 	RF_PhysDiskAddr_t *tmp_pda;
   1155 	RF_RaidDisk_t *disks = raidPtr->Disks;
   1156 	RF_DiskQueue_t *dqs = raidPtr->Queues, *dataQueue, *mirrorQueue;
   1157 
   1158 	/* return the [row col] of the disk with the shortest queue */
   1159 	colData = data_pda->col;
   1160 	colMirror = mirror_pda->col;
   1161 	dataQueue = &(dqs[colData]);
   1162 	mirrorQueue = &(dqs[colMirror]);
   1163 
   1164 #ifdef RF_LOCK_QUEUES_TO_READ_LEN
   1165 	RF_LOCK_QUEUE_MUTEX(dataQueue, "SelectMirrorDiskIdle");
   1166 #endif				/* RF_LOCK_QUEUES_TO_READ_LEN */
   1167 	dataQueueLength = dataQueue->queueLength + dataQueue->numOutstanding;
   1168 #ifdef RF_LOCK_QUEUES_TO_READ_LEN
   1169 	RF_UNLOCK_QUEUE_MUTEX(dataQueue, "SelectMirrorDiskIdle");
   1170 	RF_LOCK_QUEUE_MUTEX(mirrorQueue, "SelectMirrorDiskIdle");
   1171 #endif				/* RF_LOCK_QUEUES_TO_READ_LEN */
   1172 	mirrorQueueLength = mirrorQueue->queueLength + mirrorQueue->numOutstanding;
   1173 #ifdef RF_LOCK_QUEUES_TO_READ_LEN
   1174 	RF_UNLOCK_QUEUE_MUTEX(mirrorQueue, "SelectMirrorDiskIdle");
   1175 #endif				/* RF_LOCK_QUEUES_TO_READ_LEN */
   1176 
   1177 	usemirror = 0;
   1178 	if (RF_DEAD_DISK(disks[colMirror].status)) {
   1179 		usemirror = 0;
   1180 	} else
   1181 		if (RF_DEAD_DISK(disks[colData].status)) {
   1182 			usemirror = 1;
   1183 		} else
   1184 			if (raidPtr->parity_good == RF_RAID_DIRTY) {
   1185 				/* Trust only the main disk */
   1186 				usemirror = 0;
   1187 			} else
   1188 				if (dataQueueLength < mirrorQueueLength) {
   1189 					usemirror = 0;
   1190 				} else
   1191 					if (mirrorQueueLength < dataQueueLength) {
   1192 						usemirror = 1;
   1193 					} else {
   1194 						/* queues are equal length. attempt
   1195 						 * cleverness. */
   1196 						if (SNUM_DIFF(dataQueue->last_deq_sector, data_pda->startSector)
   1197 						    <= SNUM_DIFF(mirrorQueue->last_deq_sector, mirror_pda->startSector)) {
   1198 							usemirror = 0;
   1199 						} else {
   1200 							usemirror = 1;
   1201 						}
   1202 					}
   1203 
   1204 	if (usemirror) {
   1205 		/* use mirror (parity) disk, swap params 0 & 4 */
   1206 		tmp_pda = data_pda;
   1207 		node->params[0].p = mirror_pda;
   1208 		node->params[4].p = tmp_pda;
   1209 	} else {
   1210 		/* use data disk, leave param 0 unchanged */
   1211 	}
   1212 	/* printf("dataQueueLength %d, mirrorQueueLength
   1213 	 * %d\n",dataQueueLength, mirrorQueueLength); */
   1214 }
   1215 #if (RF_INCLUDE_CHAINDECLUSTER > 0) || (RF_INCLUDE_INTERDECLUSTER > 0) || (RF_DEBUG_VALIDATE_DAG > 0)
   1216 /*
   1217  * Do simple partitioning. This assumes that
   1218  * the data and parity disks are laid out identically.
   1219  */
   1220 void
   1221 rf_SelectMirrorDiskPartition(RF_DagNode_t * node)
   1222 {
   1223 	RF_Raid_t *raidPtr = (RF_Raid_t *) node->dagHdr->raidPtr;
   1224 	RF_RowCol_t colData, colMirror;
   1225 	RF_PhysDiskAddr_t *data_pda = (RF_PhysDiskAddr_t *) node->params[0].p;
   1226 	RF_PhysDiskAddr_t *mirror_pda = (RF_PhysDiskAddr_t *) node->params[4].p;
   1227 	RF_PhysDiskAddr_t *tmp_pda;
   1228 	RF_RaidDisk_t *disks = raidPtr->Disks;
   1229 	int     usemirror;
   1230 
   1231 	/* return the [row col] of the disk with the shortest queue */
   1232 	colData = data_pda->col;
   1233 	colMirror = mirror_pda->col;
   1234 
   1235 	usemirror = 0;
   1236 	if (RF_DEAD_DISK(disks[colMirror].status)) {
   1237 		usemirror = 0;
   1238 	} else
   1239 		if (RF_DEAD_DISK(disks[colData].status)) {
   1240 			usemirror = 1;
   1241 		} else
   1242 			if (raidPtr->parity_good == RF_RAID_DIRTY) {
   1243 				/* Trust only the main disk */
   1244 				usemirror = 0;
   1245 			} else
   1246 				if (data_pda->startSector <
   1247 				    (disks[colData].numBlocks / 2)) {
   1248 					usemirror = 0;
   1249 				} else {
   1250 					usemirror = 1;
   1251 				}
   1252 
   1253 	if (usemirror) {
   1254 		/* use mirror (parity) disk, swap params 0 & 4 */
   1255 		tmp_pda = data_pda;
   1256 		node->params[0].p = mirror_pda;
   1257 		node->params[4].p = tmp_pda;
   1258 	} else {
   1259 		/* use data disk, leave param 0 unchanged */
   1260 	}
   1261 }
   1262 #endif
   1263