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