Home | History | Annotate | Line # | Download | only in raidframe
rf_dagutils.c revision 1.29
      1 /*	$NetBSD: rf_dagutils.c,v 1.29 2004/02/29 04:03:50 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.29 2004/02/29 04:03:50 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 static struct pool rf_dagh_pool;
    171 #define RF_MAX_FREE_DAGH 128
    172 #define RF_DAGH_INC       16
    173 #define RF_DAGH_INITIAL   32
    174 
    175 static struct pool rf_daglist_pool;
    176 #define RF_MAX_FREE_DAGLIST 128
    177 #define RF_DAGLIST_INITIAL   32
    178 
    179 static struct pool rf_funclist_pool;
    180 #define RF_MAX_FREE_FUNCLIST 128
    181 #define RF_FUNCLIST_INITIAL   32
    182 
    183 static void rf_ShutdownDAGs(void *);
    184 static void
    185 rf_ShutdownDAGs(void *ignored)
    186 {
    187 	pool_destroy(&rf_dagh_pool);
    188 	pool_destroy(&rf_daglist_pool);
    189 	pool_destroy(&rf_funclist_pool);
    190 }
    191 
    192 int
    193 rf_ConfigureDAGs(RF_ShutdownList_t **listp)
    194 {
    195 
    196 	pool_init(&rf_dagh_pool, sizeof(RF_DagHeader_t), 0, 0, 0,
    197 		  "rf_dagh_pl", NULL);
    198 	pool_sethiwat(&rf_dagh_pool, RF_MAX_FREE_DAGH);
    199 	pool_prime(&rf_dagh_pool, RF_DAGH_INITIAL);
    200 
    201 	pool_init(&rf_daglist_pool, sizeof(RF_DagList_t), 0, 0, 0,
    202 		  "rf_daglist_pl", NULL);
    203 	pool_sethiwat(&rf_daglist_pool, RF_MAX_FREE_DAGLIST);
    204 	pool_prime(&rf_daglist_pool, RF_DAGLIST_INITIAL);
    205 
    206 	pool_init(&rf_funclist_pool, sizeof(RF_FuncList_t), 0, 0, 0,
    207 		  "rf_funcist_pl", NULL);
    208 	pool_sethiwat(&rf_funclist_pool, RF_MAX_FREE_FUNCLIST);
    209 	pool_prime(&rf_funclist_pool, RF_FUNCLIST_INITIAL);
    210 
    211 	rf_ShutdownCreate(listp, rf_ShutdownDAGs, NULL);
    212 
    213 	return (0);
    214 }
    215 
    216 RF_DagHeader_t *
    217 rf_AllocDAGHeader()
    218 {
    219 	RF_DagHeader_t *dh;
    220 
    221 	dh = pool_get(&rf_dagh_pool, PR_WAITOK);
    222 	memset((char *) dh, 0, sizeof(RF_DagHeader_t));
    223 	return (dh);
    224 }
    225 
    226 void
    227 rf_FreeDAGHeader(RF_DagHeader_t * dh)
    228 {
    229 	pool_put(&rf_dagh_pool, dh);
    230 }
    231 
    232 RF_DagList_t *
    233 rf_AllocDAGList()
    234 {
    235 	RF_DagList_t *dagList;
    236 
    237 	dagList = pool_get(&rf_daglist_pool, PR_WAITOK);
    238 	memset(dagList, 0, sizeof(RF_DagList_t));
    239 
    240 	return (dagList);
    241 }
    242 
    243 void
    244 rf_FreeDAGList(RF_DagList_t *dagList)
    245 {
    246 	pool_put(&rf_daglist_pool, dagList);
    247 }
    248 
    249 RF_FuncList_t *
    250 rf_AllocFuncList()
    251 {
    252 	RF_FuncList_t *funcList;
    253 
    254 	funcList = pool_get(&rf_funclist_pool, PR_WAITOK);
    255 	memset(funcList, 0, sizeof(RF_FuncList_t));
    256 
    257 	return (funcList);
    258 }
    259 
    260 void
    261 rf_FreeFuncList(RF_FuncList_t *funcList)
    262 {
    263 	pool_put(&rf_funclist_pool, funcList);
    264 }
    265 
    266 
    267 
    268 /* allocates a buffer big enough to hold the data described by pda */
    269 void   *
    270 rf_AllocBuffer(RF_Raid_t *raidPtr, RF_DagHeader_t *dag_h,
    271 	       RF_PhysDiskAddr_t *pda, RF_AllocListElem_t *allocList)
    272 {
    273 	char   *p;
    274 
    275 	RF_MallocAndAdd(p, pda->numSector << raidPtr->logBytesPerSector,
    276 	    (char *), allocList);
    277 	return ((void *) p);
    278 }
    279 #if RF_DEBUG_VALIDATE_DAG
    280 /******************************************************************************
    281  *
    282  * debug routines
    283  *
    284  *****************************************************************************/
    285 
    286 char   *
    287 rf_NodeStatusString(RF_DagNode_t *node)
    288 {
    289 	switch (node->status) {
    290 		case rf_wait:return ("wait");
    291 	case rf_fired:
    292 		return ("fired");
    293 	case rf_good:
    294 		return ("good");
    295 	case rf_bad:
    296 		return ("bad");
    297 	default:
    298 		return ("?");
    299 	}
    300 }
    301 
    302 void
    303 rf_PrintNodeInfoString(RF_DagNode_t *node)
    304 {
    305 	RF_PhysDiskAddr_t *pda;
    306 	int     (*df) (RF_DagNode_t *) = node->doFunc;
    307 	int     i, lk, unlk;
    308 	void   *bufPtr;
    309 
    310 	if ((df == rf_DiskReadFunc) || (df == rf_DiskWriteFunc)
    311 	    || (df == rf_DiskReadMirrorIdleFunc)
    312 	    || (df == rf_DiskReadMirrorPartitionFunc)) {
    313 		pda = (RF_PhysDiskAddr_t *) node->params[0].p;
    314 		bufPtr = (void *) node->params[1].p;
    315 		lk = 0;
    316 		unlk = 0;
    317 		RF_ASSERT(!(lk && unlk));
    318 		printf("c %d offs %ld nsect %d buf 0x%lx %s\n", pda->col,
    319 		    (long) pda->startSector, (int) pda->numSector, (long) bufPtr,
    320 		    (lk) ? "LOCK" : ((unlk) ? "UNLK" : " "));
    321 		return;
    322 	}
    323 	if (df == rf_DiskUnlockFunc) {
    324 		pda = (RF_PhysDiskAddr_t *) node->params[0].p;
    325 		lk = 0;
    326 		unlk = 0;
    327 		RF_ASSERT(!(lk && unlk));
    328 		printf("c %d %s\n", pda->col,
    329 		    (lk) ? "LOCK" : ((unlk) ? "UNLK" : "nop"));
    330 		return;
    331 	}
    332 	if ((df == rf_SimpleXorFunc) || (df == rf_RegularXorFunc)
    333 	    || (df == rf_RecoveryXorFunc)) {
    334 		printf("result buf 0x%lx\n", (long) node->results[0]);
    335 		for (i = 0; i < node->numParams - 1; i += 2) {
    336 			pda = (RF_PhysDiskAddr_t *) node->params[i].p;
    337 			bufPtr = (RF_PhysDiskAddr_t *) node->params[i + 1].p;
    338 			printf("    buf 0x%lx c%d offs %ld nsect %d\n",
    339 			    (long) bufPtr, pda->col,
    340 			    (long) pda->startSector, (int) pda->numSector);
    341 		}
    342 		return;
    343 	}
    344 #if RF_INCLUDE_PARITYLOGGING > 0
    345 	if (df == rf_ParityLogOverwriteFunc || df == rf_ParityLogUpdateFunc) {
    346 		for (i = 0; i < node->numParams - 1; i += 2) {
    347 			pda = (RF_PhysDiskAddr_t *) node->params[i].p;
    348 			bufPtr = (RF_PhysDiskAddr_t *) node->params[i + 1].p;
    349 			printf(" c%d offs %ld nsect %d buf 0x%lx\n",
    350 			    pda->col, (long) pda->startSector,
    351 			    (int) pda->numSector, (long) bufPtr);
    352 		}
    353 		return;
    354 	}
    355 #endif				/* RF_INCLUDE_PARITYLOGGING > 0 */
    356 
    357 	if ((df == rf_TerminateFunc) || (df == rf_NullNodeFunc)) {
    358 		printf("\n");
    359 		return;
    360 	}
    361 	printf("?\n");
    362 }
    363 #ifdef DEBUG
    364 static void
    365 rf_RecurPrintDAG(RF_DagNode_t *node, int depth, int unvisited)
    366 {
    367 	char   *anttype;
    368 	int     i;
    369 
    370 	node->visited = (unvisited) ? 0 : 1;
    371 	printf("(%d) %d C%d %s: %s,s%d %d/%d,a%d/%d,p%d,r%d S{", depth,
    372 	    node->nodeNum, node->commitNode, node->name, rf_NodeStatusString(node),
    373 	    node->numSuccedents, node->numSuccFired, node->numSuccDone,
    374 	    node->numAntecedents, node->numAntDone, node->numParams, node->numResults);
    375 	for (i = 0; i < node->numSuccedents; i++) {
    376 		printf("%d%s", node->succedents[i]->nodeNum,
    377 		    ((i == node->numSuccedents - 1) ? "\0" : " "));
    378 	}
    379 	printf("} A{");
    380 	for (i = 0; i < node->numAntecedents; i++) {
    381 		switch (node->antType[i]) {
    382 		case rf_trueData:
    383 			anttype = "T";
    384 			break;
    385 		case rf_antiData:
    386 			anttype = "A";
    387 			break;
    388 		case rf_outputData:
    389 			anttype = "O";
    390 			break;
    391 		case rf_control:
    392 			anttype = "C";
    393 			break;
    394 		default:
    395 			anttype = "?";
    396 			break;
    397 		}
    398 		printf("%d(%s)%s", node->antecedents[i]->nodeNum, anttype, (i == node->numAntecedents - 1) ? "\0" : " ");
    399 	}
    400 	printf("}; ");
    401 	rf_PrintNodeInfoString(node);
    402 	for (i = 0; i < node->numSuccedents; i++) {
    403 		if (node->succedents[i]->visited == unvisited)
    404 			rf_RecurPrintDAG(node->succedents[i], depth + 1, unvisited);
    405 	}
    406 }
    407 
    408 static void
    409 rf_PrintDAG(RF_DagHeader_t *dag_h)
    410 {
    411 	int     unvisited, i;
    412 	char   *status;
    413 
    414 	/* set dag status */
    415 	switch (dag_h->status) {
    416 	case rf_enable:
    417 		status = "enable";
    418 		break;
    419 	case rf_rollForward:
    420 		status = "rollForward";
    421 		break;
    422 	case rf_rollBackward:
    423 		status = "rollBackward";
    424 		break;
    425 	default:
    426 		status = "illegal!";
    427 		break;
    428 	}
    429 	/* find out if visited bits are currently set or clear */
    430 	unvisited = dag_h->succedents[0]->visited;
    431 
    432 	printf("DAG type:  %s\n", dag_h->creator);
    433 	printf("format is (depth) num commit type: status,nSucc nSuccFired/nSuccDone,nAnte/nAnteDone,nParam,nResult S{x} A{x(type)};  info\n");
    434 	printf("(0) %d Hdr: %s, s%d, (commit %d/%d) S{", dag_h->nodeNum,
    435 	    status, dag_h->numSuccedents, dag_h->numCommitNodes, dag_h->numCommits);
    436 	for (i = 0; i < dag_h->numSuccedents; i++) {
    437 		printf("%d%s", dag_h->succedents[i]->nodeNum,
    438 		    ((i == dag_h->numSuccedents - 1) ? "\0" : " "));
    439 	}
    440 	printf("};\n");
    441 	for (i = 0; i < dag_h->numSuccedents; i++) {
    442 		if (dag_h->succedents[i]->visited == unvisited)
    443 			rf_RecurPrintDAG(dag_h->succedents[i], 1, unvisited);
    444 	}
    445 }
    446 #endif
    447 /* assigns node numbers */
    448 int
    449 rf_AssignNodeNums(RF_DagHeader_t * dag_h)
    450 {
    451 	int     unvisited, i, nnum;
    452 	RF_DagNode_t *node;
    453 
    454 	nnum = 0;
    455 	unvisited = dag_h->succedents[0]->visited;
    456 
    457 	dag_h->nodeNum = nnum++;
    458 	for (i = 0; i < dag_h->numSuccedents; i++) {
    459 		node = dag_h->succedents[i];
    460 		if (node->visited == unvisited) {
    461 			nnum = rf_RecurAssignNodeNums(dag_h->succedents[i], nnum, unvisited);
    462 		}
    463 	}
    464 	return (nnum);
    465 }
    466 
    467 int
    468 rf_RecurAssignNodeNums(RF_DagNode_t *node, int num, int unvisited)
    469 {
    470 	int     i;
    471 
    472 	node->visited = (unvisited) ? 0 : 1;
    473 
    474 	node->nodeNum = num++;
    475 	for (i = 0; i < node->numSuccedents; i++) {
    476 		if (node->succedents[i]->visited == unvisited) {
    477 			num = rf_RecurAssignNodeNums(node->succedents[i], num, unvisited);
    478 		}
    479 	}
    480 	return (num);
    481 }
    482 /* set the header pointers in each node to "newptr" */
    483 void
    484 rf_ResetDAGHeaderPointers(RF_DagHeader_t *dag_h, RF_DagHeader_t *newptr)
    485 {
    486 	int     i;
    487 	for (i = 0; i < dag_h->numSuccedents; i++)
    488 		if (dag_h->succedents[i]->dagHdr != newptr)
    489 			rf_RecurResetDAGHeaderPointers(dag_h->succedents[i], newptr);
    490 }
    491 
    492 void
    493 rf_RecurResetDAGHeaderPointers(RF_DagNode_t *node, RF_DagHeader_t *newptr)
    494 {
    495 	int     i;
    496 	node->dagHdr = newptr;
    497 	for (i = 0; i < node->numSuccedents; i++)
    498 		if (node->succedents[i]->dagHdr != newptr)
    499 			rf_RecurResetDAGHeaderPointers(node->succedents[i], newptr);
    500 }
    501 
    502 
    503 void
    504 rf_PrintDAGList(RF_DagHeader_t * dag_h)
    505 {
    506 	int     i = 0;
    507 
    508 	for (; dag_h; dag_h = dag_h->next) {
    509 		rf_AssignNodeNums(dag_h);
    510 		printf("\n\nDAG %d IN LIST:\n", i++);
    511 		rf_PrintDAG(dag_h);
    512 	}
    513 }
    514 
    515 static int
    516 rf_ValidateBranch(RF_DagNode_t *node, int *scount, int *acount,
    517 		  RF_DagNode_t **nodes, int unvisited)
    518 {
    519 	int     i, retcode = 0;
    520 
    521 	/* construct an array of node pointers indexed by node num */
    522 	node->visited = (unvisited) ? 0 : 1;
    523 	nodes[node->nodeNum] = node;
    524 
    525 	if (node->next != NULL) {
    526 		printf("INVALID DAG: next pointer in node is not NULL\n");
    527 		retcode = 1;
    528 	}
    529 	if (node->status != rf_wait) {
    530 		printf("INVALID DAG: Node status is not wait\n");
    531 		retcode = 1;
    532 	}
    533 	if (node->numAntDone != 0) {
    534 		printf("INVALID DAG: numAntDone is not zero\n");
    535 		retcode = 1;
    536 	}
    537 	if (node->doFunc == rf_TerminateFunc) {
    538 		if (node->numSuccedents != 0) {
    539 			printf("INVALID DAG: Terminator node has succedents\n");
    540 			retcode = 1;
    541 		}
    542 	} else {
    543 		if (node->numSuccedents == 0) {
    544 			printf("INVALID DAG: Non-terminator node has no succedents\n");
    545 			retcode = 1;
    546 		}
    547 	}
    548 	for (i = 0; i < node->numSuccedents; i++) {
    549 		if (!node->succedents[i]) {
    550 			printf("INVALID DAG: succedent %d of node %s is NULL\n", i, node->name);
    551 			retcode = 1;
    552 		}
    553 		scount[node->succedents[i]->nodeNum]++;
    554 	}
    555 	for (i = 0; i < node->numAntecedents; i++) {
    556 		if (!node->antecedents[i]) {
    557 			printf("INVALID DAG: antecedent %d of node %s is NULL\n", i, node->name);
    558 			retcode = 1;
    559 		}
    560 		acount[node->antecedents[i]->nodeNum]++;
    561 	}
    562 	for (i = 0; i < node->numSuccedents; i++) {
    563 		if (node->succedents[i]->visited == unvisited) {
    564 			if (rf_ValidateBranch(node->succedents[i], scount,
    565 				acount, nodes, unvisited)) {
    566 				retcode = 1;
    567 			}
    568 		}
    569 	}
    570 	return (retcode);
    571 }
    572 
    573 static void
    574 rf_ValidateBranchVisitedBits(RF_DagNode_t *node, int unvisited, int rl)
    575 {
    576 	int     i;
    577 
    578 	RF_ASSERT(node->visited == unvisited);
    579 	for (i = 0; i < node->numSuccedents; i++) {
    580 		if (node->succedents[i] == NULL) {
    581 			printf("node=%lx node->succedents[%d] is NULL\n", (long) node, i);
    582 			RF_ASSERT(0);
    583 		}
    584 		rf_ValidateBranchVisitedBits(node->succedents[i], unvisited, rl + 1);
    585 	}
    586 }
    587 /* NOTE:  never call this on a big dag, because it is exponential
    588  * in execution time
    589  */
    590 static void
    591 rf_ValidateVisitedBits(RF_DagHeader_t *dag)
    592 {
    593 	int     i, unvisited;
    594 
    595 	unvisited = dag->succedents[0]->visited;
    596 
    597 	for (i = 0; i < dag->numSuccedents; i++) {
    598 		if (dag->succedents[i] == NULL) {
    599 			printf("dag=%lx dag->succedents[%d] is NULL\n", (long) dag, i);
    600 			RF_ASSERT(0);
    601 		}
    602 		rf_ValidateBranchVisitedBits(dag->succedents[i], unvisited, 0);
    603 	}
    604 }
    605 /* validate a DAG.  _at entry_ verify that:
    606  *   -- numNodesCompleted is zero
    607  *   -- node queue is null
    608  *   -- dag status is rf_enable
    609  *   -- next pointer is null on every node
    610  *   -- all nodes have status wait
    611  *   -- numAntDone is zero in all nodes
    612  *   -- terminator node has zero successors
    613  *   -- no other node besides terminator has zero successors
    614  *   -- no successor or antecedent pointer in a node is NULL
    615  *   -- number of times that each node appears as a successor of another node
    616  *      is equal to the antecedent count on that node
    617  *   -- number of times that each node appears as an antecedent of another node
    618  *      is equal to the succedent count on that node
    619  *   -- what else?
    620  */
    621 int
    622 rf_ValidateDAG(RF_DagHeader_t *dag_h)
    623 {
    624 	int     i, nodecount;
    625 	int    *scount, *acount;/* per-node successor and antecedent counts */
    626 	RF_DagNode_t **nodes;	/* array of ptrs to nodes in dag */
    627 	int     retcode = 0;
    628 	int     unvisited;
    629 	int     commitNodeCount = 0;
    630 
    631 	if (rf_validateVisitedDebug)
    632 		rf_ValidateVisitedBits(dag_h);
    633 
    634 	if (dag_h->numNodesCompleted != 0) {
    635 		printf("INVALID DAG: num nodes completed is %d, should be 0\n", dag_h->numNodesCompleted);
    636 		retcode = 1;
    637 		goto validate_dag_bad;
    638 	}
    639 	if (dag_h->status != rf_enable) {
    640 		printf("INVALID DAG: not enabled\n");
    641 		retcode = 1;
    642 		goto validate_dag_bad;
    643 	}
    644 	if (dag_h->numCommits != 0) {
    645 		printf("INVALID DAG: numCommits != 0 (%d)\n", dag_h->numCommits);
    646 		retcode = 1;
    647 		goto validate_dag_bad;
    648 	}
    649 	if (dag_h->numSuccedents != 1) {
    650 		/* currently, all dags must have only one succedent */
    651 		printf("INVALID DAG: numSuccedents !1 (%d)\n", dag_h->numSuccedents);
    652 		retcode = 1;
    653 		goto validate_dag_bad;
    654 	}
    655 	nodecount = rf_AssignNodeNums(dag_h);
    656 
    657 	unvisited = dag_h->succedents[0]->visited;
    658 
    659 	RF_Malloc(scount, nodecount * sizeof(int), (int *));
    660 	RF_Malloc(acount, nodecount * sizeof(int), (int *));
    661 	RF_Malloc(nodes, nodecount * sizeof(RF_DagNode_t *),
    662 		  (RF_DagNode_t **));
    663 	for (i = 0; i < dag_h->numSuccedents; i++) {
    664 		if ((dag_h->succedents[i]->visited == unvisited)
    665 		    && rf_ValidateBranch(dag_h->succedents[i], scount,
    666 			acount, nodes, unvisited)) {
    667 			retcode = 1;
    668 		}
    669 	}
    670 	/* start at 1 to skip the header node */
    671 	for (i = 1; i < nodecount; i++) {
    672 		if (nodes[i]->commitNode)
    673 			commitNodeCount++;
    674 		if (nodes[i]->doFunc == NULL) {
    675 			printf("INVALID DAG: node %s has an undefined doFunc\n", nodes[i]->name);
    676 			retcode = 1;
    677 			goto validate_dag_out;
    678 		}
    679 		if (nodes[i]->undoFunc == NULL) {
    680 			printf("INVALID DAG: node %s has an undefined doFunc\n", nodes[i]->name);
    681 			retcode = 1;
    682 			goto validate_dag_out;
    683 		}
    684 		if (nodes[i]->numAntecedents != scount[nodes[i]->nodeNum]) {
    685 			printf("INVALID DAG: node %s has %d antecedents but appears as a succedent %d times\n",
    686 			    nodes[i]->name, nodes[i]->numAntecedents, scount[nodes[i]->nodeNum]);
    687 			retcode = 1;
    688 			goto validate_dag_out;
    689 		}
    690 		if (nodes[i]->numSuccedents != acount[nodes[i]->nodeNum]) {
    691 			printf("INVALID DAG: node %s has %d succedents but appears as an antecedent %d times\n",
    692 			    nodes[i]->name, nodes[i]->numSuccedents, acount[nodes[i]->nodeNum]);
    693 			retcode = 1;
    694 			goto validate_dag_out;
    695 		}
    696 	}
    697 
    698 	if (dag_h->numCommitNodes != commitNodeCount) {
    699 		printf("INVALID DAG: incorrect commit node count.  hdr->numCommitNodes (%d) found (%d) commit nodes in graph\n",
    700 		    dag_h->numCommitNodes, commitNodeCount);
    701 		retcode = 1;
    702 		goto validate_dag_out;
    703 	}
    704 validate_dag_out:
    705 	RF_Free(scount, nodecount * sizeof(int));
    706 	RF_Free(acount, nodecount * sizeof(int));
    707 	RF_Free(nodes, nodecount * sizeof(RF_DagNode_t *));
    708 	if (retcode)
    709 		rf_PrintDAGList(dag_h);
    710 
    711 	if (rf_validateVisitedDebug)
    712 		rf_ValidateVisitedBits(dag_h);
    713 
    714 	return (retcode);
    715 
    716 validate_dag_bad:
    717 	rf_PrintDAGList(dag_h);
    718 	return (retcode);
    719 }
    720 
    721 #endif /* RF_DEBUG_VALIDATE_DAG */
    722 
    723 /******************************************************************************
    724  *
    725  * misc construction routines
    726  *
    727  *****************************************************************************/
    728 
    729 void
    730 rf_redirect_asm(RF_Raid_t *raidPtr, RF_AccessStripeMap_t *asmap)
    731 {
    732 	int     ds = (raidPtr->Layout.map->flags & RF_DISTRIBUTE_SPARE) ? 1 : 0;
    733 	int     fcol = raidPtr->reconControl->fcol;
    734 	int     scol = raidPtr->reconControl->spareCol;
    735 	RF_PhysDiskAddr_t *pda;
    736 
    737 	RF_ASSERT(raidPtr->status == rf_rs_reconstructing);
    738 	for (pda = asmap->physInfo; pda; pda = pda->next) {
    739 		if (pda->col == fcol) {
    740 			if (rf_dagDebug) {
    741 				if (!rf_CheckRUReconstructed(raidPtr->reconControl->reconMap,
    742 					pda->startSector)) {
    743 					RF_PANIC();
    744 				}
    745 			}
    746 			/* printf("Remapped data for large write\n"); */
    747 			if (ds) {
    748 				raidPtr->Layout.map->MapSector(raidPtr, pda->raidAddress,
    749 				    &pda->col, &pda->startSector, RF_REMAP);
    750 			} else {
    751 				pda->col = scol;
    752 			}
    753 		}
    754 	}
    755 	for (pda = asmap->parityInfo; pda; pda = pda->next) {
    756 		if (pda->col == fcol) {
    757 			if (rf_dagDebug) {
    758 				if (!rf_CheckRUReconstructed(raidPtr->reconControl->reconMap, pda->startSector)) {
    759 					RF_PANIC();
    760 				}
    761 			}
    762 		}
    763 		if (ds) {
    764 			(raidPtr->Layout.map->MapParity) (raidPtr, pda->raidAddress, &pda->col, &pda->startSector, RF_REMAP);
    765 		} else {
    766 			pda->col = scol;
    767 		}
    768 	}
    769 }
    770 
    771 
    772 /* this routine allocates read buffers and generates stripe maps for the
    773  * regions of the array from the start of the stripe to the start of the
    774  * access, and from the end of the access to the end of the stripe.  It also
    775  * computes and returns the number of DAG nodes needed to read all this data.
    776  * Note that this routine does the wrong thing if the access is fully
    777  * contained within one stripe unit, so we RF_ASSERT against this case at the
    778  * start.
    779  *
    780  * layoutPtr - in: layout information
    781  * asmap     - in: access stripe map
    782  * dag_h     - in: header of the dag to create
    783  * new_asm_h - in: ptr to array of 2 headers.  to be filled in
    784  * nRodNodes - out: num nodes to be generated to read unaccessed data
    785  * sosBuffer, eosBuffer - out: pointers to newly allocated buffer
    786  */
    787 void
    788 rf_MapUnaccessedPortionOfStripe(RF_Raid_t *raidPtr,
    789 				RF_RaidLayout_t *layoutPtr,
    790 				RF_AccessStripeMap_t *asmap,
    791 				RF_DagHeader_t *dag_h,
    792 				RF_AccessStripeMapHeader_t **new_asm_h,
    793 				int *nRodNodes,
    794 				char **sosBuffer, char **eosBuffer,
    795 				RF_AllocListElem_t *allocList)
    796 {
    797 	RF_RaidAddr_t sosRaidAddress, eosRaidAddress;
    798 	RF_SectorNum_t sosNumSector, eosNumSector;
    799 
    800 	RF_ASSERT(asmap->numStripeUnitsAccessed > (layoutPtr->numDataCol / 2));
    801 	/* generate an access map for the region of the array from start of
    802 	 * stripe to start of access */
    803 	new_asm_h[0] = new_asm_h[1] = NULL;
    804 	*nRodNodes = 0;
    805 	if (!rf_RaidAddressStripeAligned(layoutPtr, asmap->raidAddress)) {
    806 		sosRaidAddress = rf_RaidAddressOfPrevStripeBoundary(layoutPtr, asmap->raidAddress);
    807 		sosNumSector = asmap->raidAddress - sosRaidAddress;
    808 		RF_MallocAndAdd(*sosBuffer, rf_RaidAddressToByte(raidPtr, sosNumSector), (char *), allocList);
    809 		new_asm_h[0] = rf_MapAccess(raidPtr, sosRaidAddress, sosNumSector, *sosBuffer, RF_DONT_REMAP);
    810 		new_asm_h[0]->next = dag_h->asmList;
    811 		dag_h->asmList = new_asm_h[0];
    812 		*nRodNodes += new_asm_h[0]->stripeMap->numStripeUnitsAccessed;
    813 
    814 		RF_ASSERT(new_asm_h[0]->stripeMap->next == NULL);
    815 		/* we're totally within one stripe here */
    816 		if (asmap->flags & RF_ASM_REDIR_LARGE_WRITE)
    817 			rf_redirect_asm(raidPtr, new_asm_h[0]->stripeMap);
    818 	}
    819 	/* generate an access map for the region of the array from end of
    820 	 * access to end of stripe */
    821 	if (!rf_RaidAddressStripeAligned(layoutPtr, asmap->endRaidAddress)) {
    822 		eosRaidAddress = asmap->endRaidAddress;
    823 		eosNumSector = rf_RaidAddressOfNextStripeBoundary(layoutPtr, eosRaidAddress) - eosRaidAddress;
    824 		RF_MallocAndAdd(*eosBuffer, rf_RaidAddressToByte(raidPtr, eosNumSector), (char *), allocList);
    825 		new_asm_h[1] = rf_MapAccess(raidPtr, eosRaidAddress, eosNumSector, *eosBuffer, RF_DONT_REMAP);
    826 		new_asm_h[1]->next = dag_h->asmList;
    827 		dag_h->asmList = new_asm_h[1];
    828 		*nRodNodes += new_asm_h[1]->stripeMap->numStripeUnitsAccessed;
    829 
    830 		RF_ASSERT(new_asm_h[1]->stripeMap->next == NULL);
    831 		/* we're totally within one stripe here */
    832 		if (asmap->flags & RF_ASM_REDIR_LARGE_WRITE)
    833 			rf_redirect_asm(raidPtr, new_asm_h[1]->stripeMap);
    834 	}
    835 }
    836 
    837 
    838 
    839 /* returns non-zero if the indicated ranges of stripe unit offsets overlap */
    840 int
    841 rf_PDAOverlap(RF_RaidLayout_t *layoutPtr,
    842 	      RF_PhysDiskAddr_t *src, RF_PhysDiskAddr_t *dest)
    843 {
    844 	RF_SectorNum_t soffs = rf_StripeUnitOffset(layoutPtr, src->startSector);
    845 	RF_SectorNum_t doffs = rf_StripeUnitOffset(layoutPtr, dest->startSector);
    846 	/* use -1 to be sure we stay within SU */
    847 	RF_SectorNum_t send = rf_StripeUnitOffset(layoutPtr, src->startSector + src->numSector - 1);
    848 	RF_SectorNum_t dend = rf_StripeUnitOffset(layoutPtr, dest->startSector + dest->numSector - 1);
    849 	return ((RF_MAX(soffs, doffs) <= RF_MIN(send, dend)) ? 1 : 0);
    850 }
    851 
    852 
    853 /* GenerateFailedAccessASMs
    854  *
    855  * this routine figures out what portion of the stripe needs to be read
    856  * to effect the degraded read or write operation.  It's primary function
    857  * is to identify everything required to recover the data, and then
    858  * eliminate anything that is already being accessed by the user.
    859  *
    860  * The main result is two new ASMs, one for the region from the start of the
    861  * stripe to the start of the access, and one for the region from the end of
    862  * the access to the end of the stripe.  These ASMs describe everything that
    863  * needs to be read to effect the degraded access.  Other results are:
    864  *    nXorBufs -- the total number of buffers that need to be XORed together to
    865  *                recover the lost data,
    866  *    rpBufPtr -- ptr to a newly-allocated buffer to hold the parity.  If NULL
    867  *                at entry, not allocated.
    868  *    overlappingPDAs --
    869  *                describes which of the non-failed PDAs in the user access
    870  *                overlap data that needs to be read to effect recovery.
    871  *                overlappingPDAs[i]==1 if and only if, neglecting the failed
    872  *                PDA, the ith pda in the input asm overlaps data that needs
    873  *                to be read for recovery.
    874  */
    875  /* in: asm - ASM for the actual access, one stripe only */
    876  /* in: failedPDA - which component of the access has failed */
    877  /* in: dag_h - header of the DAG we're going to create */
    878  /* out: new_asm_h - the two new ASMs */
    879  /* out: nXorBufs - the total number of xor bufs required */
    880  /* out: rpBufPtr - a buffer for the parity read */
    881 void
    882 rf_GenerateFailedAccessASMs(RF_Raid_t *raidPtr, RF_AccessStripeMap_t *asmap,
    883 			    RF_PhysDiskAddr_t *failedPDA,
    884 			    RF_DagHeader_t *dag_h,
    885 			    RF_AccessStripeMapHeader_t **new_asm_h,
    886 			    int *nXorBufs, char **rpBufPtr,
    887 			    char *overlappingPDAs,
    888 			    RF_AllocListElem_t *allocList)
    889 {
    890 	RF_RaidLayout_t *layoutPtr = &(raidPtr->Layout);
    891 
    892 	/* s=start, e=end, s=stripe, a=access, f=failed, su=stripe unit */
    893 	RF_RaidAddr_t sosAddr, sosEndAddr, eosStartAddr, eosAddr;
    894 
    895 	RF_SectorCount_t numSect[2], numParitySect;
    896 	RF_PhysDiskAddr_t *pda;
    897 	char   *rdBuf, *bufP;
    898 	int     foundit, i;
    899 
    900 	bufP = NULL;
    901 	foundit = 0;
    902 	/* first compute the following raid addresses: start of stripe,
    903 	 * (sosAddr) MIN(start of access, start of failed SU),   (sosEndAddr)
    904 	 * MAX(end of access, end of failed SU),       (eosStartAddr) end of
    905 	 * stripe (i.e. start of next stripe)   (eosAddr) */
    906 	sosAddr = rf_RaidAddressOfPrevStripeBoundary(layoutPtr, asmap->raidAddress);
    907 	sosEndAddr = RF_MIN(asmap->raidAddress, rf_RaidAddressOfPrevStripeUnitBoundary(layoutPtr, failedPDA->raidAddress));
    908 	eosStartAddr = RF_MAX(asmap->endRaidAddress, rf_RaidAddressOfNextStripeUnitBoundary(layoutPtr, failedPDA->raidAddress));
    909 	eosAddr = rf_RaidAddressOfNextStripeBoundary(layoutPtr, asmap->raidAddress);
    910 
    911 	/* now generate access stripe maps for each of the above regions of
    912 	 * the stripe.  Use a dummy (NULL) buf ptr for now */
    913 
    914 	new_asm_h[0] = (sosAddr != sosEndAddr) ? rf_MapAccess(raidPtr, sosAddr, sosEndAddr - sosAddr, NULL, RF_DONT_REMAP) : NULL;
    915 	new_asm_h[1] = (eosStartAddr != eosAddr) ? rf_MapAccess(raidPtr, eosStartAddr, eosAddr - eosStartAddr, NULL, RF_DONT_REMAP) : NULL;
    916 
    917 	/* walk through the PDAs and range-restrict each SU to the region of
    918 	 * the SU touched on the failed PDA.  also compute total data buffer
    919 	 * space requirements in this step.  Ignore the parity for now. */
    920 
    921 	numSect[0] = numSect[1] = 0;
    922 	if (new_asm_h[0]) {
    923 		new_asm_h[0]->next = dag_h->asmList;
    924 		dag_h->asmList = new_asm_h[0];
    925 		for (pda = new_asm_h[0]->stripeMap->physInfo; pda; pda = pda->next) {
    926 			rf_RangeRestrictPDA(raidPtr, failedPDA, pda, RF_RESTRICT_NOBUFFER, 0);
    927 			numSect[0] += pda->numSector;
    928 		}
    929 	}
    930 	if (new_asm_h[1]) {
    931 		new_asm_h[1]->next = dag_h->asmList;
    932 		dag_h->asmList = new_asm_h[1];
    933 		for (pda = new_asm_h[1]->stripeMap->physInfo; pda; pda = pda->next) {
    934 			rf_RangeRestrictPDA(raidPtr, failedPDA, pda, RF_RESTRICT_NOBUFFER, 0);
    935 			numSect[1] += pda->numSector;
    936 		}
    937 	}
    938 	numParitySect = failedPDA->numSector;
    939 
    940 	/* allocate buffer space for the data & parity we have to read to
    941 	 * recover from the failure */
    942 
    943 	if (numSect[0] + numSect[1] + ((rpBufPtr) ? numParitySect : 0)) {	/* don't allocate parity
    944 										 * buf if not needed */
    945 		RF_MallocAndAdd(rdBuf, rf_RaidAddressToByte(raidPtr, numSect[0] + numSect[1] + numParitySect), (char *), allocList);
    946 		bufP = rdBuf;
    947 		if (rf_degDagDebug)
    948 			printf("Newly allocated buffer (%d bytes) is 0x%lx\n",
    949 			    (int) rf_RaidAddressToByte(raidPtr, numSect[0] + numSect[1] + numParitySect), (unsigned long) bufP);
    950 	}
    951 	/* now walk through the pdas one last time and assign buffer pointers
    952 	 * (ugh!).  Again, ignore the parity.  also, count nodes to find out
    953 	 * how many bufs need to be xored together */
    954 	(*nXorBufs) = 1;	/* in read case, 1 is for parity.  In write
    955 				 * case, 1 is for failed data */
    956 	if (new_asm_h[0]) {
    957 		for (pda = new_asm_h[0]->stripeMap->physInfo; pda; pda = pda->next) {
    958 			pda->bufPtr = bufP;
    959 			bufP += rf_RaidAddressToByte(raidPtr, pda->numSector);
    960 		}
    961 		*nXorBufs += new_asm_h[0]->stripeMap->numStripeUnitsAccessed;
    962 	}
    963 	if (new_asm_h[1]) {
    964 		for (pda = new_asm_h[1]->stripeMap->physInfo; pda; pda = pda->next) {
    965 			pda->bufPtr = bufP;
    966 			bufP += rf_RaidAddressToByte(raidPtr, pda->numSector);
    967 		}
    968 		(*nXorBufs) += new_asm_h[1]->stripeMap->numStripeUnitsAccessed;
    969 	}
    970 	if (rpBufPtr)
    971 		*rpBufPtr = bufP;	/* the rest of the buffer is for
    972 					 * parity */
    973 
    974 	/* the last step is to figure out how many more distinct buffers need
    975 	 * to get xor'd to produce the missing unit.  there's one for each
    976 	 * user-data read node that overlaps the portion of the failed unit
    977 	 * being accessed */
    978 
    979 	for (foundit = i = 0, pda = asmap->physInfo; pda; i++, pda = pda->next) {
    980 		if (pda == failedPDA) {
    981 			i--;
    982 			foundit = 1;
    983 			continue;
    984 		}
    985 		if (rf_PDAOverlap(layoutPtr, pda, failedPDA)) {
    986 			overlappingPDAs[i] = 1;
    987 			(*nXorBufs)++;
    988 		}
    989 	}
    990 	if (!foundit) {
    991 		RF_ERRORMSG("GenerateFailedAccessASMs: did not find failedPDA in asm list\n");
    992 		RF_ASSERT(0);
    993 	}
    994 	if (rf_degDagDebug) {
    995 		if (new_asm_h[0]) {
    996 			printf("First asm:\n");
    997 			rf_PrintFullAccessStripeMap(new_asm_h[0], 1);
    998 		}
    999 		if (new_asm_h[1]) {
   1000 			printf("Second asm:\n");
   1001 			rf_PrintFullAccessStripeMap(new_asm_h[1], 1);
   1002 		}
   1003 	}
   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