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