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