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