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