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