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