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