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