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