Home | History | Annotate | Line # | Download | only in raidframe
rf_reconstruct.c revision 1.72
      1 /*	$NetBSD: rf_reconstruct.c,v 1.72 2004/03/05 03:58:21 oster Exp $	*/
      2 /*
      3  * Copyright (c) 1995 Carnegie-Mellon University.
      4  * All rights reserved.
      5  *
      6  * Author: Mark Holland
      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_reconstruct.c -- code to perform on-line reconstruction
     32  *
     33  ************************************************************/
     34 
     35 #include <sys/cdefs.h>
     36 __KERNEL_RCSID(0, "$NetBSD: rf_reconstruct.c,v 1.72 2004/03/05 03:58:21 oster Exp $");
     37 
     38 #include <sys/time.h>
     39 #include <sys/buf.h>
     40 #include <sys/errno.h>
     41 
     42 #include <sys/param.h>
     43 #include <sys/systm.h>
     44 #include <sys/proc.h>
     45 #include <sys/ioctl.h>
     46 #include <sys/fcntl.h>
     47 #include <sys/vnode.h>
     48 #include <dev/raidframe/raidframevar.h>
     49 
     50 #include "rf_raid.h"
     51 #include "rf_reconutil.h"
     52 #include "rf_revent.h"
     53 #include "rf_reconbuffer.h"
     54 #include "rf_acctrace.h"
     55 #include "rf_etimer.h"
     56 #include "rf_dag.h"
     57 #include "rf_desc.h"
     58 #include "rf_debugprint.h"
     59 #include "rf_general.h"
     60 #include "rf_driver.h"
     61 #include "rf_utils.h"
     62 #include "rf_shutdown.h"
     63 
     64 #include "rf_kintf.h"
     65 
     66 /* setting these to -1 causes them to be set to their default values if not set by debug options */
     67 
     68 #if RF_DEBUG_RECON
     69 #define Dprintf(s)         if (rf_reconDebug) rf_debug_printf(s,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)
     70 #define Dprintf1(s,a)         if (rf_reconDebug) rf_debug_printf(s,(void *)((unsigned long)a),NULL,NULL,NULL,NULL,NULL,NULL,NULL)
     71 #define Dprintf2(s,a,b)       if (rf_reconDebug) rf_debug_printf(s,(void *)((unsigned long)a),(void *)((unsigned long)b),NULL,NULL,NULL,NULL,NULL,NULL)
     72 #define Dprintf3(s,a,b,c)     if (rf_reconDebug) rf_debug_printf(s,(void *)((unsigned long)a),(void *)((unsigned long)b),(void *)((unsigned long)c),NULL,NULL,NULL,NULL,NULL)
     73 #define Dprintf4(s,a,b,c,d)   if (rf_reconDebug) rf_debug_printf(s,(void *)((unsigned long)a),(void *)((unsigned long)b),(void *)((unsigned long)c),(void *)((unsigned long)d),NULL,NULL,NULL,NULL)
     74 #define Dprintf5(s,a,b,c,d,e) if (rf_reconDebug) rf_debug_printf(s,(void *)((unsigned long)a),(void *)((unsigned long)b),(void *)((unsigned long)c),(void *)((unsigned long)d),(void *)((unsigned long)e),NULL,NULL,NULL)
     75 #define Dprintf6(s,a,b,c,d,e,f) if (rf_reconDebug) rf_debug_printf(s,(void *)((unsigned long)a),(void *)((unsigned long)b),(void *)((unsigned long)c),(void *)((unsigned long)d),(void *)((unsigned long)e),(void *)((unsigned long)f),NULL,NULL)
     76 #define Dprintf7(s,a,b,c,d,e,f,g) if (rf_reconDebug) rf_debug_printf(s,(void *)((unsigned long)a),(void *)((unsigned long)b),(void *)((unsigned long)c),(void *)((unsigned long)d),(void *)((unsigned long)e),(void *)((unsigned long)f),(void *)((unsigned long)g),NULL)
     77 
     78 #define DDprintf1(s,a)         if (rf_reconDebug) rf_debug_printf(s,(void *)((unsigned long)a),NULL,NULL,NULL,NULL,NULL,NULL,NULL)
     79 #define DDprintf2(s,a,b)       if (rf_reconDebug) rf_debug_printf(s,(void *)((unsigned long)a),(void *)((unsigned long)b),NULL,NULL,NULL,NULL,NULL,NULL)
     80 
     81 #else /* RF_DEBUG_RECON */
     82 
     83 #define Dprintf(s) {}
     84 #define Dprintf1(s,a) {}
     85 #define Dprintf2(s,a,b) {}
     86 #define Dprintf3(s,a,b,c) {}
     87 #define Dprintf4(s,a,b,c,d) {}
     88 #define Dprintf5(s,a,b,c,d,e) {}
     89 #define Dprintf6(s,a,b,c,d,e,f) {}
     90 #define Dprintf7(s,a,b,c,d,e,f,g) {}
     91 
     92 #define DDprintf1(s,a) {}
     93 #define DDprintf2(s,a,b) {}
     94 
     95 #endif /* RF_DEBUG_RECON */
     96 
     97 
     98 static struct pool rf_recond_pool;
     99 #define RF_MAX_FREE_RECOND  4
    100 #define RF_RECOND_INC       1
    101 
    102 static RF_RaidReconDesc_t *AllocRaidReconDesc(RF_Raid_t *, RF_RowCol_t,
    103 					      RF_RaidDisk_t *, int, RF_RowCol_t);
    104 static void FreeReconDesc(RF_RaidReconDesc_t *);
    105 static int ProcessReconEvent(RF_Raid_t *, RF_ReconEvent_t *);
    106 static int IssueNextReadRequest(RF_Raid_t *, RF_RowCol_t);
    107 static int TryToRead(RF_Raid_t *, RF_RowCol_t);
    108 static int ComputePSDiskOffsets(RF_Raid_t *, RF_StripeNum_t, RF_RowCol_t,
    109 				RF_SectorNum_t *, RF_SectorNum_t *, RF_RowCol_t *,
    110 				RF_SectorNum_t *);
    111 static int IssueNextWriteRequest(RF_Raid_t *);
    112 static int ReconReadDoneProc(void *, int);
    113 static int ReconWriteDoneProc(void *, int);
    114 static void CheckForNewMinHeadSep(RF_Raid_t *, RF_HeadSepLimit_t);
    115 static int CheckHeadSeparation(RF_Raid_t *, RF_PerDiskReconCtrl_t *,
    116 			       RF_RowCol_t, RF_HeadSepLimit_t,
    117 			       RF_ReconUnitNum_t);
    118 static int CheckForcedOrBlockedReconstruction(RF_Raid_t *,
    119 					      RF_ReconParityStripeStatus_t *,
    120 					      RF_PerDiskReconCtrl_t *,
    121 					      RF_RowCol_t, RF_StripeNum_t,
    122 					      RF_ReconUnitNum_t);
    123 static void ForceReconReadDoneProc(void *, int);
    124 static void rf_ShutdownReconstruction(void *);
    125 
    126 struct RF_ReconDoneProc_s {
    127 	void    (*proc) (RF_Raid_t *, void *);
    128 	void   *arg;
    129 	RF_ReconDoneProc_t *next;
    130 };
    131 
    132 /**************************************************************************
    133  *
    134  * sets up the parameters that will be used by the reconstruction process
    135  * currently there are none, except for those that the layout-specific
    136  * configuration (e.g. rf_ConfigureDeclustered) routine sets up.
    137  *
    138  * in the kernel, we fire off the recon thread.
    139  *
    140  **************************************************************************/
    141 static void
    142 rf_ShutdownReconstruction(void *ignored)
    143 {
    144 	pool_destroy(&rf_recond_pool);
    145 }
    146 
    147 int
    148 rf_ConfigureReconstruction(RF_ShutdownList_t **listp)
    149 {
    150 
    151 	pool_init(&rf_recond_pool, sizeof(RF_RaidReconDesc_t), 0, 0, 0,
    152 		  "rf_recond_pl", NULL);
    153 	rf_ShutdownCreate(listp, rf_ShutdownReconstruction, NULL);
    154 
    155 	return (0);
    156 }
    157 
    158 static RF_RaidReconDesc_t *
    159 AllocRaidReconDesc(RF_Raid_t *raidPtr, RF_RowCol_t col,
    160 		   RF_RaidDisk_t *spareDiskPtr, int numDisksDone,
    161 		   RF_RowCol_t scol)
    162 {
    163 
    164 	RF_RaidReconDesc_t *reconDesc;
    165 
    166 	reconDesc = pool_get(&rf_recond_pool, PR_WAITOK); /* XXX WAITOK?? */
    167 
    168 	reconDesc->raidPtr = raidPtr;
    169 	reconDesc->col = col;
    170 	reconDesc->spareDiskPtr = spareDiskPtr;
    171 	reconDesc->numDisksDone = numDisksDone;
    172 	reconDesc->scol = scol;
    173 	reconDesc->state = 0;
    174 	reconDesc->next = NULL;
    175 
    176 	return (reconDesc);
    177 }
    178 
    179 static void
    180 FreeReconDesc(RF_RaidReconDesc_t *reconDesc)
    181 {
    182 #if RF_RECON_STATS > 0
    183 	printf("raid%d: %lu recon event waits, %lu recon delays\n",
    184 	       reconDesc->raidPtr->raidid,
    185 	       (long) reconDesc->numReconEventWaits,
    186 	       (long) reconDesc->numReconExecDelays);
    187 #endif				/* RF_RECON_STATS > 0 */
    188 	printf("raid%d: %lu max exec ticks\n",
    189 	       reconDesc->raidPtr->raidid,
    190 	       (long) reconDesc->maxReconExecTicks);
    191 #if (RF_RECON_STATS > 0) || defined(KERNEL)
    192 	printf("\n");
    193 #endif				/* (RF_RECON_STATS > 0) || KERNEL */
    194 	pool_put(&rf_recond_pool, reconDesc);
    195 }
    196 
    197 
    198 /*****************************************************************************
    199  *
    200  * primary routine to reconstruct a failed disk.  This should be called from
    201  * within its own thread.  It won't return until reconstruction completes,
    202  * fails, or is aborted.
    203  *****************************************************************************/
    204 int
    205 rf_ReconstructFailedDisk(RF_Raid_t *raidPtr, RF_RowCol_t col)
    206 {
    207 	const RF_LayoutSW_t *lp;
    208 	int     rc;
    209 
    210 	lp = raidPtr->Layout.map;
    211 	if (lp->SubmitReconBuffer) {
    212 		/*
    213 	         * The current infrastructure only supports reconstructing one
    214 	         * disk at a time for each array.
    215 	         */
    216 		RF_LOCK_MUTEX(raidPtr->mutex);
    217 		while (raidPtr->reconInProgress) {
    218 			RF_WAIT_COND(raidPtr->waitForReconCond, raidPtr->mutex);
    219 		}
    220 		raidPtr->reconInProgress++;
    221 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    222 		rc = rf_ReconstructFailedDiskBasic(raidPtr, col);
    223 		RF_LOCK_MUTEX(raidPtr->mutex);
    224 		raidPtr->reconInProgress--;
    225 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    226 	} else {
    227 		RF_ERRORMSG1("RECON: no way to reconstruct failed disk for arch %c\n",
    228 		    lp->parityConfig);
    229 		rc = EIO;
    230 	}
    231 	RF_SIGNAL_COND(raidPtr->waitForReconCond);
    232 	return (rc);
    233 }
    234 
    235 int
    236 rf_ReconstructFailedDiskBasic(RF_Raid_t *raidPtr, RF_RowCol_t col)
    237 {
    238 	RF_ComponentLabel_t c_label;
    239 	RF_RaidDisk_t *spareDiskPtr = NULL;
    240 	RF_RaidReconDesc_t *reconDesc;
    241 	RF_RowCol_t scol;
    242 	int     numDisksDone = 0, rc;
    243 
    244 	/* first look for a spare drive onto which to reconstruct the data */
    245 	/* spare disk descriptors are stored in row 0.  This may have to
    246 	 * change eventually */
    247 
    248 	RF_LOCK_MUTEX(raidPtr->mutex);
    249 	RF_ASSERT(raidPtr->Disks[col].status == rf_ds_failed);
    250 #if RF_INCLUDE_PARITY_DECLUSTERING_DS > 0
    251 	if (raidPtr->Layout.map->flags & RF_DISTRIBUTE_SPARE) {
    252 		if (raidPtr->status != rf_rs_degraded) {
    253 			RF_ERRORMSG1("Unable to reconstruct disk at col %d because status not degraded\n", col);
    254 			RF_UNLOCK_MUTEX(raidPtr->mutex);
    255 			return (EINVAL);
    256 		}
    257 		scol = (-1);
    258 	} else {
    259 #endif
    260 		for (scol = raidPtr->numCol; scol < raidPtr->numCol + raidPtr->numSpare; scol++) {
    261 			if (raidPtr->Disks[scol].status == rf_ds_spare) {
    262 				spareDiskPtr = &raidPtr->Disks[scol];
    263 				spareDiskPtr->status = rf_ds_used_spare;
    264 				break;
    265 			}
    266 		}
    267 		if (!spareDiskPtr) {
    268 			RF_ERRORMSG1("Unable to reconstruct disk at col %d because no spares are available\n", col);
    269 			RF_UNLOCK_MUTEX(raidPtr->mutex);
    270 			return (ENOSPC);
    271 		}
    272 		printf("RECON: initiating reconstruction on col %d -> spare at col %d\n", col, scol);
    273 #if RF_INCLUDE_PARITY_DECLUSTERING_DS > 0
    274 	}
    275 #endif
    276 	RF_UNLOCK_MUTEX(raidPtr->mutex);
    277 
    278 	reconDesc = AllocRaidReconDesc((void *) raidPtr, col, spareDiskPtr, numDisksDone, scol);
    279 	raidPtr->reconDesc = (void *) reconDesc;
    280 #if RF_RECON_STATS > 0
    281 	reconDesc->hsStallCount = 0;
    282 	reconDesc->numReconExecDelays = 0;
    283 	reconDesc->numReconEventWaits = 0;
    284 #endif				/* RF_RECON_STATS > 0 */
    285 	reconDesc->reconExecTimerRunning = 0;
    286 	reconDesc->reconExecTicks = 0;
    287 	reconDesc->maxReconExecTicks = 0;
    288 	rc = rf_ContinueReconstructFailedDisk(reconDesc);
    289 
    290 	if (!rc) {
    291 		/* fix up the component label */
    292 		/* Don't actually need the read here.. */
    293 		raidread_component_label(
    294                         raidPtr->raid_cinfo[scol].ci_dev,
    295 			raidPtr->raid_cinfo[scol].ci_vp,
    296 			&c_label);
    297 
    298 		raid_init_component_label( raidPtr, &c_label);
    299 		c_label.row = 0;
    300 		c_label.column = col;
    301 		c_label.clean = RF_RAID_DIRTY;
    302 		c_label.status = rf_ds_optimal;
    303 		c_label.partitionSize = raidPtr->Disks[scol].partitionSize;
    304 
    305 		/* We've just done a rebuild based on all the other
    306 		   disks, so at this point the parity is known to be
    307 		   clean, even if it wasn't before. */
    308 
    309 		/* XXX doesn't hold for RAID 6!!*/
    310 
    311 		RF_LOCK_MUTEX(raidPtr->mutex);
    312 		raidPtr->parity_good = RF_RAID_CLEAN;
    313 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    314 
    315 		/* XXXX MORE NEEDED HERE */
    316 
    317 		raidwrite_component_label(
    318                         raidPtr->raid_cinfo[scol].ci_dev,
    319 			raidPtr->raid_cinfo[scol].ci_vp,
    320 			&c_label);
    321 
    322 
    323 		rf_update_component_labels(raidPtr,
    324 					   RF_NORMAL_COMPONENT_UPDATE);
    325 
    326 	}
    327 	return (rc);
    328 }
    329 
    330 /*
    331 
    332    Allow reconstructing a disk in-place -- i.e. component /dev/sd2e goes AWOL,
    333    and you don't get a spare until the next Monday.  With this function
    334    (and hot-swappable drives) you can now put your new disk containing
    335    /dev/sd2e on the bus, scsictl it alive, and then use raidctl(8) to
    336    rebuild the data "on the spot".
    337 
    338 */
    339 
    340 int
    341 rf_ReconstructInPlace(RF_Raid_t *raidPtr, RF_RowCol_t col)
    342 {
    343 	RF_RaidDisk_t *spareDiskPtr = NULL;
    344 	RF_RaidReconDesc_t *reconDesc;
    345 	const RF_LayoutSW_t *lp;
    346 	RF_ComponentLabel_t c_label;
    347 	int     numDisksDone = 0, rc;
    348 	struct partinfo dpart;
    349 	struct vnode *vp;
    350 	struct vattr va;
    351 	struct proc *proc;
    352 	int retcode;
    353 	int ac;
    354 
    355 	lp = raidPtr->Layout.map;
    356 	if (!lp->SubmitReconBuffer) {
    357 		RF_ERRORMSG1("RECON: no way to reconstruct failed disk for arch %c\n",
    358 			     lp->parityConfig);
    359 		/* wakeup anyone who might be waiting to do a reconstruct */
    360 		RF_SIGNAL_COND(raidPtr->waitForReconCond);
    361 		return(EIO);
    362 	}
    363 
    364 	/*
    365 	 * The current infrastructure only supports reconstructing one
    366 	 * disk at a time for each array.
    367 	 */
    368 	RF_LOCK_MUTEX(raidPtr->mutex);
    369 
    370 	if (raidPtr->Disks[col].status != rf_ds_failed) {
    371 		/* "It's gone..." */
    372 		raidPtr->numFailures++;
    373 		raidPtr->Disks[col].status = rf_ds_failed;
    374 		raidPtr->status = rf_rs_degraded;
    375 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    376 		rf_update_component_labels(raidPtr,
    377 					   RF_NORMAL_COMPONENT_UPDATE);
    378 		RF_LOCK_MUTEX(raidPtr->mutex);
    379 	}
    380 
    381 	while (raidPtr->reconInProgress) {
    382 		RF_WAIT_COND(raidPtr->waitForReconCond, raidPtr->mutex);
    383 	}
    384 
    385 	raidPtr->reconInProgress++;
    386 
    387 	/* first look for a spare drive onto which to reconstruct the
    388 	   data.  spare disk descriptors are stored in row 0.  This
    389 	   may have to change eventually */
    390 
    391 	/* Actually, we don't care if it's failed or not...  On a RAID
    392 	   set with correct parity, this function should be callable
    393 	   on any component without ill affects. */
    394 	/* RF_ASSERT(raidPtr->Disks[col].status == rf_ds_failed); */
    395 
    396 #if RF_INCLUDE_PARITY_DECLUSTERING_DS > 0
    397 	if (raidPtr->Layout.map->flags & RF_DISTRIBUTE_SPARE) {
    398 		RF_ERRORMSG1("Unable to reconstruct to disk at col %d: operation not supported for RF_DISTRIBUTE_SPARE\n", col);
    399 
    400 		raidPtr->reconInProgress--;
    401 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    402 		RF_SIGNAL_COND(raidPtr->waitForReconCond);
    403 		return (EINVAL);
    404 	}
    405 #endif
    406 	proc = raidPtr->engine_thread;
    407 
    408 	/* This device may have been opened successfully the
    409 	   first time. Close it before trying to open it again.. */
    410 
    411 	if (raidPtr->raid_cinfo[col].ci_vp != NULL) {
    412 #if 0
    413 		printf("Closed the open device: %s\n",
    414 		       raidPtr->Disks[col].devname);
    415 #endif
    416 		vp = raidPtr->raid_cinfo[col].ci_vp;
    417 		ac = raidPtr->Disks[col].auto_configured;
    418 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    419 		rf_close_component(raidPtr, vp, ac);
    420 		RF_LOCK_MUTEX(raidPtr->mutex);
    421 		raidPtr->raid_cinfo[col].ci_vp = NULL;
    422 	}
    423 	/* note that this disk was *not* auto_configured (any longer)*/
    424 	raidPtr->Disks[col].auto_configured = 0;
    425 
    426 #if 0
    427 	printf("About to (re-)open the device for rebuilding: %s\n",
    428 	       raidPtr->Disks[col].devname);
    429 #endif
    430 	RF_UNLOCK_MUTEX(raidPtr->mutex);
    431 	retcode = raidlookup(raidPtr->Disks[col].devname, proc, &vp);
    432 
    433 	if (retcode) {
    434 		printf("raid%d: rebuilding: raidlookup on device: %s failed: %d!\n",raidPtr->raidid,
    435 		       raidPtr->Disks[col].devname, retcode);
    436 
    437 		/* the component isn't responding properly...
    438 		   must be still dead :-( */
    439 		RF_LOCK_MUTEX(raidPtr->mutex);
    440 		raidPtr->reconInProgress--;
    441 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    442 		RF_SIGNAL_COND(raidPtr->waitForReconCond);
    443 		return(retcode);
    444 	}
    445 
    446 	/* Ok, so we can at least do a lookup...
    447 	   How about actually getting a vp for it? */
    448 
    449 	if ((retcode = VOP_GETATTR(vp, &va, proc->p_ucred, proc)) != 0) {
    450 		RF_LOCK_MUTEX(raidPtr->mutex);
    451 		raidPtr->reconInProgress--;
    452 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    453 		RF_SIGNAL_COND(raidPtr->waitForReconCond);
    454 		return(retcode);
    455 	}
    456 
    457 	retcode = VOP_IOCTL(vp, DIOCGPART, &dpart, FREAD, proc->p_ucred, proc);
    458 	if (retcode) {
    459 		RF_LOCK_MUTEX(raidPtr->mutex);
    460 		raidPtr->reconInProgress--;
    461 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    462 		RF_SIGNAL_COND(raidPtr->waitForReconCond);
    463 		return(retcode);
    464 	}
    465 	RF_LOCK_MUTEX(raidPtr->mutex);
    466 	raidPtr->Disks[col].blockSize =	dpart.disklab->d_secsize;
    467 
    468 	raidPtr->Disks[col].numBlocks = dpart.part->p_size -
    469 		rf_protectedSectors;
    470 
    471 	raidPtr->raid_cinfo[col].ci_vp = vp;
    472 	raidPtr->raid_cinfo[col].ci_dev = va.va_rdev;
    473 
    474 	raidPtr->Disks[col].dev = va.va_rdev;
    475 
    476 	/* we allow the user to specify that only a fraction
    477 	   of the disks should be used this is just for debug:
    478 	   it speeds up * the parity scan */
    479 	raidPtr->Disks[col].numBlocks = raidPtr->Disks[col].numBlocks *
    480 		rf_sizePercentage / 100;
    481 	RF_UNLOCK_MUTEX(raidPtr->mutex);
    482 
    483 	spareDiskPtr = &raidPtr->Disks[col];
    484 	spareDiskPtr->status = rf_ds_used_spare;
    485 
    486 	printf("raid%d: initiating in-place reconstruction on column %d\n",
    487 	       raidPtr->raidid, col);
    488 
    489 	reconDesc = AllocRaidReconDesc((void *) raidPtr, col, spareDiskPtr,
    490 				       numDisksDone, col);
    491 	raidPtr->reconDesc = (void *) reconDesc;
    492 #if RF_RECON_STATS > 0
    493 	reconDesc->hsStallCount = 0;
    494 	reconDesc->numReconExecDelays = 0;
    495 	reconDesc->numReconEventWaits = 0;
    496 #endif				/* RF_RECON_STATS > 0 */
    497 	reconDesc->reconExecTimerRunning = 0;
    498 	reconDesc->reconExecTicks = 0;
    499 	reconDesc->maxReconExecTicks = 0;
    500 	rc = rf_ContinueReconstructFailedDisk(reconDesc);
    501 
    502 	RF_LOCK_MUTEX(raidPtr->mutex);
    503 	raidPtr->reconInProgress--;
    504 	RF_UNLOCK_MUTEX(raidPtr->mutex);
    505 
    506 	if (!rc) {
    507 		RF_LOCK_MUTEX(raidPtr->mutex);
    508 		/* Need to set these here, as at this point it'll be claiming
    509 		   that the disk is in rf_ds_spared!  But we know better :-) */
    510 
    511 		raidPtr->Disks[col].status = rf_ds_optimal;
    512 		raidPtr->status = rf_rs_optimal;
    513 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    514 
    515 		/* fix up the component label */
    516 		/* Don't actually need the read here.. */
    517 		raidread_component_label(raidPtr->raid_cinfo[col].ci_dev,
    518 					 raidPtr->raid_cinfo[col].ci_vp,
    519 					 &c_label);
    520 
    521 		RF_LOCK_MUTEX(raidPtr->mutex);
    522 		raid_init_component_label(raidPtr, &c_label);
    523 
    524 		c_label.row = 0;
    525 		c_label.column = col;
    526 
    527 		/* We've just done a rebuild based on all the other
    528 		   disks, so at this point the parity is known to be
    529 		   clean, even if it wasn't before. */
    530 
    531 		/* XXX doesn't hold for RAID 6!!*/
    532 
    533 		raidPtr->parity_good = RF_RAID_CLEAN;
    534 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    535 
    536 		raidwrite_component_label(raidPtr->raid_cinfo[col].ci_dev,
    537 					  raidPtr->raid_cinfo[col].ci_vp,
    538 					  &c_label);
    539 
    540 		rf_update_component_labels(raidPtr,
    541 					   RF_NORMAL_COMPONENT_UPDATE);
    542 
    543 	}
    544 	RF_SIGNAL_COND(raidPtr->waitForReconCond);
    545 	return (rc);
    546 }
    547 
    548 
    549 int
    550 rf_ContinueReconstructFailedDisk(RF_RaidReconDesc_t *reconDesc)
    551 {
    552 	RF_Raid_t *raidPtr = reconDesc->raidPtr;
    553 	RF_RowCol_t col = reconDesc->col;
    554 	RF_RowCol_t scol = reconDesc->scol;
    555 	RF_ReconMap_t *mapPtr;
    556 	RF_ReconCtrl_t *tmp_reconctrl;
    557 	RF_ReconEvent_t *event;
    558 	struct timeval etime, elpsd;
    559 	unsigned long xor_s, xor_resid_us;
    560 	int     i, ds;
    561 
    562 	switch (reconDesc->state) {
    563 
    564 
    565 	case 0:
    566 
    567 		raidPtr->accumXorTimeUs = 0;
    568 #if RF_ACC_TRACE > 0
    569 		/* create one trace record per physical disk */
    570 		RF_Malloc(raidPtr->recon_tracerecs, raidPtr->numCol * sizeof(RF_AccTraceEntry_t), (RF_AccTraceEntry_t *));
    571 #endif
    572 
    573 		/* quiesce the array prior to starting recon.  this is needed
    574 		 * to assure no nasty interactions with pending user writes.
    575 		 * We need to do this before we change the disk or row status. */
    576 		reconDesc->state = 1;
    577 
    578 		Dprintf("RECON: begin request suspend\n");
    579 		rf_SuspendNewRequestsAndWait(raidPtr);
    580 		Dprintf("RECON: end request suspend\n");
    581 		rf_StartUserStats(raidPtr);	/* zero out the stats kept on
    582 						 * user accs */
    583 
    584 		/* fall through to state 1 */
    585 
    586 	case 1:
    587 
    588 		/* allocate our RF_ReconCTRL_t before we protect raidPtr->reconControl[row] */
    589 		tmp_reconctrl = rf_MakeReconControl(reconDesc, col, scol);
    590 
    591 		RF_LOCK_MUTEX(raidPtr->mutex);
    592 
    593 		/* create the reconstruction control pointer and install it in
    594 		 * the right slot */
    595 		raidPtr->reconControl = tmp_reconctrl;
    596 		mapPtr = raidPtr->reconControl->reconMap;
    597 		raidPtr->status = rf_rs_reconstructing;
    598 		raidPtr->Disks[col].status = rf_ds_reconstructing;
    599 		raidPtr->Disks[col].spareCol = scol;
    600 
    601 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    602 
    603 		RF_GETTIME(raidPtr->reconControl->starttime);
    604 
    605 		/* now start up the actual reconstruction: issue a read for
    606 		 * each surviving disk */
    607 
    608 		reconDesc->numDisksDone = 0;
    609 		for (i = 0; i < raidPtr->numCol; i++) {
    610 			if (i != col) {
    611 				/* find and issue the next I/O on the
    612 				 * indicated disk */
    613 				if (IssueNextReadRequest(raidPtr, i)) {
    614 					Dprintf1("RECON: done issuing for c%d\n", i);
    615 					reconDesc->numDisksDone++;
    616 				}
    617 			}
    618 		}
    619 
    620 	case 2:
    621 		Dprintf("RECON: resume requests\n");
    622 		rf_ResumeNewRequests(raidPtr);
    623 
    624 
    625 		reconDesc->state = 3;
    626 
    627 	case 3:
    628 
    629 		/* process reconstruction events until all disks report that
    630 		 * they've completed all work */
    631 		mapPtr = raidPtr->reconControl->reconMap;
    632 
    633 
    634 
    635 		while (reconDesc->numDisksDone < raidPtr->numCol - 1) {
    636 
    637 			event = rf_GetNextReconEvent(reconDesc, (void (*) (void *)) rf_ContinueReconstructFailedDisk, reconDesc);
    638 			RF_ASSERT(event);
    639 
    640 			if (ProcessReconEvent(raidPtr, event))
    641 				reconDesc->numDisksDone++;
    642 			raidPtr->reconControl->numRUsTotal =
    643 				mapPtr->totalRUs;
    644 			raidPtr->reconControl->numRUsComplete =
    645 				mapPtr->totalRUs -
    646 				rf_UnitsLeftToReconstruct(mapPtr);
    647 #if RF_DEBUG_RECON
    648 			raidPtr->reconControl->percentComplete =
    649 				(raidPtr->reconControl->numRUsComplete * 100 / raidPtr->reconControl->numRUsTotal);
    650 			if (rf_prReconSched) {
    651 				rf_PrintReconSchedule(raidPtr->reconControl->reconMap, &(raidPtr->reconControl->starttime));
    652 			}
    653 #endif
    654 		}
    655 
    656 
    657 
    658 		reconDesc->state = 4;
    659 
    660 
    661 	case 4:
    662 		mapPtr = raidPtr->reconControl->reconMap;
    663 		if (rf_reconDebug) {
    664 			printf("RECON: all reads completed\n");
    665 		}
    666 		/* at this point all the reads have completed.  We now wait
    667 		 * for any pending writes to complete, and then we're done */
    668 
    669 		while (rf_UnitsLeftToReconstruct(raidPtr->reconControl->reconMap) > 0) {
    670 
    671 			event = rf_GetNextReconEvent(reconDesc, (void (*) (void *)) rf_ContinueReconstructFailedDisk, reconDesc);
    672 			RF_ASSERT(event);
    673 
    674 			(void) ProcessReconEvent(raidPtr, event);	/* ignore return code */
    675 #if RF_DEBUG_RECON
    676 			raidPtr->reconControl->percentComplete = 100 - (rf_UnitsLeftToReconstruct(mapPtr) * 100 / mapPtr->totalRUs);
    677 			if (rf_prReconSched) {
    678 				rf_PrintReconSchedule(raidPtr->reconControl->reconMap, &(raidPtr->reconControl->starttime));
    679 			}
    680 #endif
    681 		}
    682 		reconDesc->state = 5;
    683 
    684 	case 5:
    685 		/* Success:  mark the dead disk as reconstructed.  We quiesce
    686 		 * the array here to assure no nasty interactions with pending
    687 		 * user accesses when we free up the psstatus structure as
    688 		 * part of FreeReconControl() */
    689 
    690 		reconDesc->state = 6;
    691 
    692 		rf_SuspendNewRequestsAndWait(raidPtr);
    693 		rf_StopUserStats(raidPtr);
    694 		rf_PrintUserStats(raidPtr);	/* print out the stats on user
    695 						 * accs accumulated during
    696 						 * recon */
    697 
    698 		/* fall through to state 6 */
    699 	case 6:
    700 
    701 
    702 
    703 		RF_LOCK_MUTEX(raidPtr->mutex);
    704 		raidPtr->numFailures--;
    705 		ds = (raidPtr->Layout.map->flags & RF_DISTRIBUTE_SPARE);
    706 		raidPtr->Disks[col].status = (ds) ? rf_ds_dist_spared : rf_ds_spared;
    707 		raidPtr->status = (ds) ? rf_rs_reconfigured : rf_rs_optimal;
    708 		RF_UNLOCK_MUTEX(raidPtr->mutex);
    709 		RF_GETTIME(etime);
    710 		RF_TIMEVAL_DIFF(&(raidPtr->reconControl->starttime), &etime, &elpsd);
    711 
    712 		/* XXX -- why is state 7 different from state 6 if there is no
    713 		 * return() here? -- XXX Note that I set elpsd above & use it
    714 		 * below, so if you put a return here you'll have to fix this.
    715 		 * (also, FreeReconControl is called below) */
    716 
    717 	case 7:
    718 
    719 		rf_ResumeNewRequests(raidPtr);
    720 
    721 		printf("raid%d: Reconstruction of disk at col %d completed\n",
    722 		       raidPtr->raidid, col);
    723 		xor_s = raidPtr->accumXorTimeUs / 1000000;
    724 		xor_resid_us = raidPtr->accumXorTimeUs % 1000000;
    725 		printf("raid%d: Recon time was %d.%06d seconds, accumulated XOR time was %ld us (%ld.%06ld)\n",
    726 		       raidPtr->raidid,
    727 		       (int) elpsd.tv_sec, (int) elpsd.tv_usec,
    728 		       raidPtr->accumXorTimeUs, xor_s, xor_resid_us);
    729 		printf("raid%d:  (start time %d sec %d usec, end time %d sec %d usec)\n",
    730 		       raidPtr->raidid,
    731 		       (int) raidPtr->reconControl->starttime.tv_sec,
    732 		       (int) raidPtr->reconControl->starttime.tv_usec,
    733 		       (int) etime.tv_sec, (int) etime.tv_usec);
    734 
    735 #if RF_RECON_STATS > 0
    736 		printf("raid%d: Total head-sep stall count was %d\n",
    737 		       raidPtr->raidid, (int) reconDesc->hsStallCount);
    738 #endif				/* RF_RECON_STATS > 0 */
    739 		rf_FreeReconControl(raidPtr);
    740 #if RF_ACC_TRACE > 0
    741 		RF_Free(raidPtr->recon_tracerecs, raidPtr->numCol * sizeof(RF_AccTraceEntry_t));
    742 #endif
    743 		FreeReconDesc(reconDesc);
    744 
    745 	}
    746 
    747 	return (0);
    748 }
    749 /*****************************************************************************
    750  * do the right thing upon each reconstruction event.
    751  * returns nonzero if and only if there is nothing left unread on the
    752  * indicated disk
    753  *****************************************************************************/
    754 static int
    755 ProcessReconEvent(RF_Raid_t *raidPtr, RF_ReconEvent_t *event)
    756 {
    757 	int     retcode = 0, submitblocked;
    758 	RF_ReconBuffer_t *rbuf;
    759 	RF_SectorCount_t sectorsPerRU;
    760 
    761 	Dprintf1("RECON: ProcessReconEvent type %d\n", event->type);
    762 	switch (event->type) {
    763 
    764 		/* a read I/O has completed */
    765 	case RF_REVENT_READDONE:
    766 		rbuf = raidPtr->reconControl->perDiskInfo[event->col].rbuf;
    767 		Dprintf2("RECON: READDONE EVENT: col %d psid %ld\n",
    768 		    event->col, rbuf->parityStripeID);
    769 		Dprintf7("RECON: done read  psid %ld buf %lx  %02x %02x %02x %02x %02x\n",
    770 		    rbuf->parityStripeID, rbuf->buffer, rbuf->buffer[0] & 0xff, rbuf->buffer[1] & 0xff,
    771 		    rbuf->buffer[2] & 0xff, rbuf->buffer[3] & 0xff, rbuf->buffer[4] & 0xff);
    772 		rf_FreeDiskQueueData((RF_DiskQueueData_t *) rbuf->arg);
    773 		submitblocked = rf_SubmitReconBuffer(rbuf, 0, 0);
    774 		Dprintf1("RECON: submitblocked=%d\n", submitblocked);
    775 		if (!submitblocked)
    776 			retcode = IssueNextReadRequest(raidPtr, event->col);
    777 		break;
    778 
    779 		/* a write I/O has completed */
    780 	case RF_REVENT_WRITEDONE:
    781 #if RF_DEBUG_RECON
    782 		if (rf_floatingRbufDebug) {
    783 			rf_CheckFloatingRbufCount(raidPtr, 1);
    784 		}
    785 #endif
    786 		sectorsPerRU = raidPtr->Layout.sectorsPerStripeUnit * raidPtr->Layout.SUsPerRU;
    787 		rbuf = (RF_ReconBuffer_t *) event->arg;
    788 		rf_FreeDiskQueueData((RF_DiskQueueData_t *) rbuf->arg);
    789 		Dprintf3("RECON: WRITEDONE EVENT: psid %d ru %d (%d %% complete)\n",
    790 		    rbuf->parityStripeID, rbuf->which_ru, raidPtr->reconControl->percentComplete);
    791 		rf_ReconMapUpdate(raidPtr, raidPtr->reconControl->reconMap,
    792 		    rbuf->failedDiskSectorOffset, rbuf->failedDiskSectorOffset + sectorsPerRU - 1);
    793 		rf_RemoveFromActiveReconTable(raidPtr, rbuf->parityStripeID, rbuf->which_ru);
    794 
    795 		if (rbuf->type == RF_RBUF_TYPE_FLOATING) {
    796 			RF_LOCK_MUTEX(raidPtr->reconControl->rb_mutex);
    797 			raidPtr->numFullReconBuffers--;
    798 			rf_ReleaseFloatingReconBuffer(raidPtr, rbuf);
    799 			RF_UNLOCK_MUTEX(raidPtr->reconControl->rb_mutex);
    800 		} else
    801 			if (rbuf->type == RF_RBUF_TYPE_FORCED)
    802 				rf_FreeReconBuffer(rbuf);
    803 			else
    804 				RF_ASSERT(0);
    805 		break;
    806 
    807 	case RF_REVENT_BUFCLEAR:	/* A buffer-stall condition has been
    808 					 * cleared */
    809 		Dprintf1("RECON: BUFCLEAR EVENT: col %d\n", event->col);
    810 		submitblocked = rf_SubmitReconBuffer(raidPtr->reconControl->perDiskInfo[event->col].rbuf, 0, (int) (long) event->arg);
    811 		RF_ASSERT(!submitblocked);	/* we wouldn't have gotten the
    812 						 * BUFCLEAR event if we
    813 						 * couldn't submit */
    814 		retcode = IssueNextReadRequest(raidPtr, event->col);
    815 		break;
    816 
    817 	case RF_REVENT_BLOCKCLEAR:	/* A user-write reconstruction
    818 					 * blockage has been cleared */
    819 		DDprintf1("RECON: BLOCKCLEAR EVENT: col %d\n", event->col);
    820 		retcode = TryToRead(raidPtr, event->col);
    821 		break;
    822 
    823 	case RF_REVENT_HEADSEPCLEAR:	/* A max-head-separation
    824 					 * reconstruction blockage has been
    825 					 * cleared */
    826 		Dprintf1("RECON: HEADSEPCLEAR EVENT: col %d\n", event->col);
    827 		retcode = TryToRead(raidPtr, event->col);
    828 		break;
    829 
    830 		/* a buffer has become ready to write */
    831 	case RF_REVENT_BUFREADY:
    832 		Dprintf1("RECON: BUFREADY EVENT: col %d\n", event->col);
    833 		retcode = IssueNextWriteRequest(raidPtr);
    834 #if RF_DEBUG_RECON
    835 		if (rf_floatingRbufDebug) {
    836 			rf_CheckFloatingRbufCount(raidPtr, 1);
    837 		}
    838 #endif
    839 		break;
    840 
    841 		/* we need to skip the current RU entirely because it got
    842 		 * recon'd while we were waiting for something else to happen */
    843 	case RF_REVENT_SKIP:
    844 		DDprintf1("RECON: SKIP EVENT: col %d\n", event->col);
    845 		retcode = IssueNextReadRequest(raidPtr, event->col);
    846 		break;
    847 
    848 		/* a forced-reconstruction read access has completed.  Just
    849 		 * submit the buffer */
    850 	case RF_REVENT_FORCEDREADDONE:
    851 		rbuf = (RF_ReconBuffer_t *) event->arg;
    852 		rf_FreeDiskQueueData((RF_DiskQueueData_t *) rbuf->arg);
    853 		DDprintf1("RECON: FORCEDREADDONE EVENT: col %d\n", event->col);
    854 		submitblocked = rf_SubmitReconBuffer(rbuf, 1, 0);
    855 		RF_ASSERT(!submitblocked);
    856 		break;
    857 
    858 		/* A read I/O failed to complete */
    859 	case RF_REVENT_READ_FAILED:
    860 		/* fallthru to panic... */
    861 
    862 		/* A write I/O failed to complete */
    863 	case RF_REVENT_WRITE_FAILED:
    864 		/* fallthru to panic... */
    865 
    866 		/* a forced read I/O failed to complete */
    867 	case RF_REVENT_FORCEDREAD_FAILED:
    868 		/* fallthru to panic... */
    869 
    870 	default:
    871 		RF_PANIC();
    872 	}
    873 	rf_FreeReconEventDesc(event);
    874 	return (retcode);
    875 }
    876 /*****************************************************************************
    877  *
    878  * find the next thing that's needed on the indicated disk, and issue
    879  * a read request for it.  We assume that the reconstruction buffer
    880  * associated with this process is free to receive the data.  If
    881  * reconstruction is blocked on the indicated RU, we issue a
    882  * blockage-release request instead of a physical disk read request.
    883  * If the current disk gets too far ahead of the others, we issue a
    884  * head-separation wait request and return.
    885  *
    886  * ctrl->{ru_count, curPSID, diskOffset} and
    887  * rbuf->failedDiskSectorOffset are maintained to point to the unit
    888  * we're currently accessing.  Note that this deviates from the
    889  * standard C idiom of having counters point to the next thing to be
    890  * accessed.  This allows us to easily retry when we're blocked by
    891  * head separation or reconstruction-blockage events.
    892  *
    893  * returns nonzero if and only if there is nothing left unread on the
    894  * indicated disk
    895  *
    896  *****************************************************************************/
    897 static int
    898 IssueNextReadRequest(RF_Raid_t *raidPtr, RF_RowCol_t col)
    899 {
    900 	RF_PerDiskReconCtrl_t *ctrl = &raidPtr->reconControl->perDiskInfo[col];
    901 	RF_RaidLayout_t *layoutPtr = &raidPtr->Layout;
    902 	RF_ReconBuffer_t *rbuf = ctrl->rbuf;
    903 	RF_ReconUnitCount_t RUsPerPU = layoutPtr->SUsPerPU / layoutPtr->SUsPerRU;
    904 	RF_SectorCount_t sectorsPerRU = layoutPtr->sectorsPerStripeUnit * layoutPtr->SUsPerRU;
    905 	int     do_new_check = 0, retcode = 0, status;
    906 
    907 	/* if we are currently the slowest disk, mark that we have to do a new
    908 	 * check */
    909 	if (ctrl->headSepCounter <= raidPtr->reconControl->minHeadSepCounter)
    910 		do_new_check = 1;
    911 
    912 	while (1) {
    913 
    914 		ctrl->ru_count++;
    915 		if (ctrl->ru_count < RUsPerPU) {
    916 			ctrl->diskOffset += sectorsPerRU;
    917 			rbuf->failedDiskSectorOffset += sectorsPerRU;
    918 		} else {
    919 			ctrl->curPSID++;
    920 			ctrl->ru_count = 0;
    921 			/* code left over from when head-sep was based on
    922 			 * parity stripe id */
    923 			if (ctrl->curPSID >= raidPtr->reconControl->lastPSID) {
    924 				CheckForNewMinHeadSep(raidPtr, ++(ctrl->headSepCounter));
    925 				return (1);	/* finito! */
    926 			}
    927 			/* find the disk offsets of the start of the parity
    928 			 * stripe on both the current disk and the failed
    929 			 * disk. skip this entire parity stripe if either disk
    930 			 * does not appear in the indicated PS */
    931 			status = ComputePSDiskOffsets(raidPtr, ctrl->curPSID, col, &ctrl->diskOffset, &rbuf->failedDiskSectorOffset,
    932 			    &rbuf->spCol, &rbuf->spOffset);
    933 			if (status) {
    934 				ctrl->ru_count = RUsPerPU - 1;
    935 				continue;
    936 			}
    937 		}
    938 		rbuf->which_ru = ctrl->ru_count;
    939 
    940 		/* skip this RU if it's already been reconstructed */
    941 		if (rf_CheckRUReconstructed(raidPtr->reconControl->reconMap, rbuf->failedDiskSectorOffset)) {
    942 			Dprintf2("Skipping psid %ld ru %d: already reconstructed\n", ctrl->curPSID, ctrl->ru_count);
    943 			continue;
    944 		}
    945 		break;
    946 	}
    947 	ctrl->headSepCounter++;
    948 	if (do_new_check)
    949 		CheckForNewMinHeadSep(raidPtr, ctrl->headSepCounter);	/* update min if needed */
    950 
    951 
    952 	/* at this point, we have definitely decided what to do, and we have
    953 	 * only to see if we can actually do it now */
    954 	rbuf->parityStripeID = ctrl->curPSID;
    955 	rbuf->which_ru = ctrl->ru_count;
    956 #if RF_ACC_TRACE > 0
    957 	memset((char *) &raidPtr->recon_tracerecs[col], 0,
    958 	    sizeof(raidPtr->recon_tracerecs[col]));
    959 	raidPtr->recon_tracerecs[col].reconacc = 1;
    960 	RF_ETIMER_START(raidPtr->recon_tracerecs[col].recon_timer);
    961 #endif
    962 	retcode = TryToRead(raidPtr, col);
    963 	return (retcode);
    964 }
    965 
    966 /*
    967  * tries to issue the next read on the indicated disk.  We may be
    968  * blocked by (a) the heads being too far apart, or (b) recon on the
    969  * indicated RU being blocked due to a write by a user thread.  In
    970  * this case, we issue a head-sep or blockage wait request, which will
    971  * cause this same routine to be invoked again later when the blockage
    972  * has cleared.
    973  */
    974 
    975 static int
    976 TryToRead(RF_Raid_t *raidPtr, RF_RowCol_t col)
    977 {
    978 	RF_PerDiskReconCtrl_t *ctrl = &raidPtr->reconControl->perDiskInfo[col];
    979 	RF_SectorCount_t sectorsPerRU = raidPtr->Layout.sectorsPerStripeUnit * raidPtr->Layout.SUsPerRU;
    980 	RF_StripeNum_t psid = ctrl->curPSID;
    981 	RF_ReconUnitNum_t which_ru = ctrl->ru_count;
    982 	RF_DiskQueueData_t *req;
    983 	int     status;
    984 	RF_ReconParityStripeStatus_t *pssPtr, *newpssPtr;
    985 
    986 	/* if the current disk is too far ahead of the others, issue a
    987 	 * head-separation wait and return */
    988 	if (CheckHeadSeparation(raidPtr, ctrl, col, ctrl->headSepCounter, which_ru))
    989 		return (0);
    990 
    991 	/* allocate a new PSS in case we need it */
    992 	newpssPtr = rf_AllocPSStatus(raidPtr);
    993 
    994 	RF_LOCK_PSS_MUTEX(raidPtr, psid);
    995 	pssPtr = rf_LookupRUStatus(raidPtr, raidPtr->reconControl->pssTable, psid, which_ru, RF_PSS_CREATE, newpssPtr);
    996 
    997 	if (pssPtr != newpssPtr) {
    998 		rf_FreePSStatus(raidPtr, newpssPtr);
    999 	}
   1000 
   1001 	/* if recon is blocked on the indicated parity stripe, issue a
   1002 	 * block-wait request and return. this also must mark the indicated RU
   1003 	 * in the stripe as under reconstruction if not blocked. */
   1004 	status = CheckForcedOrBlockedReconstruction(raidPtr, pssPtr, ctrl, col, psid, which_ru);
   1005 	if (status == RF_PSS_RECON_BLOCKED) {
   1006 		Dprintf2("RECON: Stalling psid %ld ru %d: recon blocked\n", psid, which_ru);
   1007 		goto out;
   1008 	} else
   1009 		if (status == RF_PSS_FORCED_ON_WRITE) {
   1010 			rf_CauseReconEvent(raidPtr, col, NULL, RF_REVENT_SKIP);
   1011 			goto out;
   1012 		}
   1013 	/* make one last check to be sure that the indicated RU didn't get
   1014 	 * reconstructed while we were waiting for something else to happen.
   1015 	 * This is unfortunate in that it causes us to make this check twice
   1016 	 * in the normal case.  Might want to make some attempt to re-work
   1017 	 * this so that we only do this check if we've definitely blocked on
   1018 	 * one of the above checks.  When this condition is detected, we may
   1019 	 * have just created a bogus status entry, which we need to delete. */
   1020 	if (rf_CheckRUReconstructed(raidPtr->reconControl->reconMap, ctrl->rbuf->failedDiskSectorOffset)) {
   1021 		Dprintf2("RECON: Skipping psid %ld ru %d: prior recon after stall\n", psid, which_ru);
   1022 		if (pssPtr == newpssPtr)
   1023 			rf_PSStatusDelete(raidPtr, raidPtr->reconControl->pssTable, pssPtr);
   1024 		rf_CauseReconEvent(raidPtr, col, NULL, RF_REVENT_SKIP);
   1025 		goto out;
   1026 	}
   1027 	/* found something to read.  issue the I/O */
   1028 	Dprintf4("RECON: Read for psid %ld on col %d offset %ld buf %lx\n",
   1029 	    psid, col, ctrl->diskOffset, ctrl->rbuf->buffer);
   1030 #if RF_ACC_TRACE > 0
   1031 	RF_ETIMER_STOP(raidPtr->recon_tracerecs[col].recon_timer);
   1032 	RF_ETIMER_EVAL(raidPtr->recon_tracerecs[col].recon_timer);
   1033 	raidPtr->recon_tracerecs[col].specific.recon.recon_start_to_fetch_us =
   1034 	    RF_ETIMER_VAL_US(raidPtr->recon_tracerecs[col].recon_timer);
   1035 	RF_ETIMER_START(raidPtr->recon_tracerecs[col].recon_timer);
   1036 #endif
   1037 	/* should be ok to use a NULL proc pointer here, all the bufs we use
   1038 	 * should be in kernel space */
   1039 	req = rf_CreateDiskQueueData(RF_IO_TYPE_READ, ctrl->diskOffset, sectorsPerRU, ctrl->rbuf->buffer, psid, which_ru,
   1040 	    ReconReadDoneProc, (void *) ctrl, NULL,
   1041 #if RF_ACC_TRACE > 0
   1042 				     &raidPtr->recon_tracerecs[col],
   1043 #else
   1044 				     NULL,
   1045 #endif
   1046 				     (void *) raidPtr, 0, NULL);
   1047 
   1048 	RF_ASSERT(req);		/* XXX -- fix this -- XXX */
   1049 
   1050 	ctrl->rbuf->arg = (void *) req;
   1051 	rf_DiskIOEnqueue(&raidPtr->Queues[col], req, RF_IO_RECON_PRIORITY);
   1052 	pssPtr->issued[col] = 1;
   1053 
   1054 out:
   1055 	RF_UNLOCK_PSS_MUTEX(raidPtr, psid);
   1056 	return (0);
   1057 }
   1058 
   1059 
   1060 /*
   1061  * given a parity stripe ID, we want to find out whether both the
   1062  * current disk and the failed disk exist in that parity stripe.  If
   1063  * not, we want to skip this whole PS.  If so, we want to find the
   1064  * disk offset of the start of the PS on both the current disk and the
   1065  * failed disk.
   1066  *
   1067  * this works by getting a list of disks comprising the indicated
   1068  * parity stripe, and searching the list for the current and failed
   1069  * disks.  Once we've decided they both exist in the parity stripe, we
   1070  * need to decide whether each is data or parity, so that we'll know
   1071  * which mapping function to call to get the corresponding disk
   1072  * offsets.
   1073  *
   1074  * this is kind of unpleasant, but doing it this way allows the
   1075  * reconstruction code to use parity stripe IDs rather than physical
   1076  * disks address to march through the failed disk, which greatly
   1077  * simplifies a lot of code, as well as eliminating the need for a
   1078  * reverse-mapping function.  I also think it will execute faster,
   1079  * since the calls to the mapping module are kept to a minimum.
   1080  *
   1081  * ASSUMES THAT THE STRIPE IDENTIFIER IDENTIFIES THE DISKS COMPRISING
   1082  * THE STRIPE IN THE CORRECT ORDER
   1083  *
   1084  * raidPtr          - raid descriptor
   1085  * psid             - parity stripe identifier
   1086  * col              - column of disk to find the offsets for
   1087  * spCol            - out: col of spare unit for failed unit
   1088  * spOffset         - out: offset into disk containing spare unit
   1089  *
   1090  */
   1091 
   1092 
   1093 static int
   1094 ComputePSDiskOffsets(RF_Raid_t *raidPtr, RF_StripeNum_t psid,
   1095 		     RF_RowCol_t col, RF_SectorNum_t *outDiskOffset,
   1096 		     RF_SectorNum_t *outFailedDiskSectorOffset,
   1097 		     RF_RowCol_t *spCol, RF_SectorNum_t *spOffset)
   1098 {
   1099 	RF_RaidLayout_t *layoutPtr = &raidPtr->Layout;
   1100 	RF_RowCol_t fcol = raidPtr->reconControl->fcol;
   1101 	RF_RaidAddr_t sosRaidAddress;	/* start-of-stripe */
   1102 	RF_RowCol_t *diskids;
   1103 	u_int   i, j, k, i_offset, j_offset;
   1104 	RF_RowCol_t pcol;
   1105 	int     testcol;
   1106 	RF_SectorNum_t poffset;
   1107 	char    i_is_parity = 0, j_is_parity = 0;
   1108 	RF_RowCol_t stripeWidth = layoutPtr->numDataCol + layoutPtr->numParityCol;
   1109 
   1110 	/* get a listing of the disks comprising that stripe */
   1111 	sosRaidAddress = rf_ParityStripeIDToRaidAddress(layoutPtr, psid);
   1112 	(layoutPtr->map->IdentifyStripe) (raidPtr, sosRaidAddress, &diskids);
   1113 	RF_ASSERT(diskids);
   1114 
   1115 	/* reject this entire parity stripe if it does not contain the
   1116 	 * indicated disk or it does not contain the failed disk */
   1117 
   1118 	for (i = 0; i < stripeWidth; i++) {
   1119 		if (col == diskids[i])
   1120 			break;
   1121 	}
   1122 	if (i == stripeWidth)
   1123 		goto skipit;
   1124 	for (j = 0; j < stripeWidth; j++) {
   1125 		if (fcol == diskids[j])
   1126 			break;
   1127 	}
   1128 	if (j == stripeWidth) {
   1129 		goto skipit;
   1130 	}
   1131 	/* find out which disk the parity is on */
   1132 	(layoutPtr->map->MapParity) (raidPtr, sosRaidAddress, &pcol, &poffset, RF_DONT_REMAP);
   1133 
   1134 	/* find out if either the current RU or the failed RU is parity */
   1135 	/* also, if the parity occurs in this stripe prior to the data and/or
   1136 	 * failed col, we need to decrement i and/or j */
   1137 	for (k = 0; k < stripeWidth; k++)
   1138 		if (diskids[k] == pcol)
   1139 			break;
   1140 	RF_ASSERT(k < stripeWidth);
   1141 	i_offset = i;
   1142 	j_offset = j;
   1143 	if (k < i)
   1144 		i_offset--;
   1145 	else
   1146 		if (k == i) {
   1147 			i_is_parity = 1;
   1148 			i_offset = 0;
   1149 		}		/* set offsets to zero to disable multiply
   1150 				 * below */
   1151 	if (k < j)
   1152 		j_offset--;
   1153 	else
   1154 		if (k == j) {
   1155 			j_is_parity = 1;
   1156 			j_offset = 0;
   1157 		}
   1158 	/* at this point, [ij]_is_parity tells us whether the [current,failed]
   1159 	 * disk is parity at the start of this RU, and, if data, "[ij]_offset"
   1160 	 * tells us how far into the stripe the [current,failed] disk is. */
   1161 
   1162 	/* call the mapping routine to get the offset into the current disk,
   1163 	 * repeat for failed disk. */
   1164 	if (i_is_parity)
   1165 		layoutPtr->map->MapParity(raidPtr, sosRaidAddress + i_offset * layoutPtr->sectorsPerStripeUnit, &testcol, outDiskOffset, RF_DONT_REMAP);
   1166 	else
   1167 		layoutPtr->map->MapSector(raidPtr, sosRaidAddress + i_offset * layoutPtr->sectorsPerStripeUnit, &testcol, outDiskOffset, RF_DONT_REMAP);
   1168 
   1169 	RF_ASSERT(col == testcol);
   1170 
   1171 	if (j_is_parity)
   1172 		layoutPtr->map->MapParity(raidPtr, sosRaidAddress + j_offset * layoutPtr->sectorsPerStripeUnit, &testcol, outFailedDiskSectorOffset, RF_DONT_REMAP);
   1173 	else
   1174 		layoutPtr->map->MapSector(raidPtr, sosRaidAddress + j_offset * layoutPtr->sectorsPerStripeUnit, &testcol, outFailedDiskSectorOffset, RF_DONT_REMAP);
   1175 	RF_ASSERT(fcol == testcol);
   1176 
   1177 	/* now locate the spare unit for the failed unit */
   1178 #if RF_INCLUDE_PARITY_DECLUSTERING_DS > 0
   1179 	if (layoutPtr->map->flags & RF_DISTRIBUTE_SPARE) {
   1180 		if (j_is_parity)
   1181 			layoutPtr->map->MapParity(raidPtr, sosRaidAddress + j_offset * layoutPtr->sectorsPerStripeUnit, spCol, spOffset, RF_REMAP);
   1182 		else
   1183 			layoutPtr->map->MapSector(raidPtr, sosRaidAddress + j_offset * layoutPtr->sectorsPerStripeUnit, spCol, spOffset, RF_REMAP);
   1184 	} else {
   1185 #endif
   1186 		*spCol = raidPtr->reconControl->spareCol;
   1187 		*spOffset = *outFailedDiskSectorOffset;
   1188 #if RF_INCLUDE_PARITY_DECLUSTERING_DS > 0
   1189 	}
   1190 #endif
   1191 	return (0);
   1192 
   1193 skipit:
   1194 	Dprintf2("RECON: Skipping psid %ld: nothing needed from r%d c%d\n",
   1195 	    psid, col);
   1196 	return (1);
   1197 }
   1198 /* this is called when a buffer has become ready to write to the replacement disk */
   1199 static int
   1200 IssueNextWriteRequest(RF_Raid_t *raidPtr)
   1201 {
   1202 	RF_RaidLayout_t *layoutPtr = &raidPtr->Layout;
   1203 	RF_SectorCount_t sectorsPerRU = layoutPtr->sectorsPerStripeUnit * layoutPtr->SUsPerRU;
   1204 #if RF_ACC_TRACE > 0
   1205 	RF_RowCol_t fcol = raidPtr->reconControl->fcol;
   1206 #endif
   1207 	RF_ReconBuffer_t *rbuf;
   1208 	RF_DiskQueueData_t *req;
   1209 
   1210 	rbuf = rf_GetFullReconBuffer(raidPtr->reconControl);
   1211 	RF_ASSERT(rbuf);	/* there must be one available, or we wouldn't
   1212 				 * have gotten the event that sent us here */
   1213 	RF_ASSERT(rbuf->pssPtr);
   1214 
   1215 	rbuf->pssPtr->writeRbuf = rbuf;
   1216 	rbuf->pssPtr = NULL;
   1217 
   1218 	Dprintf6("RECON: New write (c %d offs %d) for psid %ld ru %d (failed disk offset %ld) buf %lx\n",
   1219 	    rbuf->spCol, rbuf->spOffset, rbuf->parityStripeID,
   1220 	    rbuf->which_ru, rbuf->failedDiskSectorOffset, rbuf->buffer);
   1221 	Dprintf6("RECON: new write psid %ld   %02x %02x %02x %02x %02x\n",
   1222 	    rbuf->parityStripeID, rbuf->buffer[0] & 0xff, rbuf->buffer[1] & 0xff,
   1223 	    rbuf->buffer[2] & 0xff, rbuf->buffer[3] & 0xff, rbuf->buffer[4] & 0xff);
   1224 
   1225 	/* should be ok to use a NULL b_proc here b/c all addrs should be in
   1226 	 * kernel space */
   1227 	req = rf_CreateDiskQueueData(RF_IO_TYPE_WRITE, rbuf->spOffset,
   1228 	    sectorsPerRU, rbuf->buffer,
   1229 	    rbuf->parityStripeID, rbuf->which_ru,
   1230 	    ReconWriteDoneProc, (void *) rbuf, NULL,
   1231 #if RF_ACC_TRACE > 0
   1232 	    &raidPtr->recon_tracerecs[fcol],
   1233 #else
   1234 				     NULL,
   1235 #endif
   1236 	    (void *) raidPtr, 0, NULL);
   1237 
   1238 	RF_ASSERT(req);		/* XXX -- fix this -- XXX */
   1239 
   1240 	rbuf->arg = (void *) req;
   1241 	rf_DiskIOEnqueue(&raidPtr->Queues[rbuf->spCol], req, RF_IO_RECON_PRIORITY);
   1242 
   1243 	return (0);
   1244 }
   1245 
   1246 /*
   1247  * this gets called upon the completion of a reconstruction read
   1248  * operation the arg is a pointer to the per-disk reconstruction
   1249  * control structure for the process that just finished a read.
   1250  *
   1251  * called at interrupt context in the kernel, so don't do anything
   1252  * illegal here.
   1253  */
   1254 static int
   1255 ReconReadDoneProc(void *arg, int status)
   1256 {
   1257 	RF_PerDiskReconCtrl_t *ctrl = (RF_PerDiskReconCtrl_t *) arg;
   1258 	RF_Raid_t *raidPtr = ctrl->reconCtrl->reconDesc->raidPtr;
   1259 
   1260 	if (status) {
   1261 		printf("raid%d: Recon read failed!\n", raidPtr->raidid);
   1262 		rf_CauseReconEvent(raidPtr, ctrl->col, NULL, RF_REVENT_READ_FAILED);
   1263 		return(0);
   1264 	}
   1265 #if RF_ACC_TRACE > 0
   1266 	RF_ETIMER_STOP(raidPtr->recon_tracerecs[ctrl->col].recon_timer);
   1267 	RF_ETIMER_EVAL(raidPtr->recon_tracerecs[ctrl->col].recon_timer);
   1268 	raidPtr->recon_tracerecs[ctrl->col].specific.recon.recon_fetch_to_return_us =
   1269 	    RF_ETIMER_VAL_US(raidPtr->recon_tracerecs[ctrl->col].recon_timer);
   1270 	RF_ETIMER_START(raidPtr->recon_tracerecs[ctrl->col].recon_timer);
   1271 #endif
   1272 	rf_CauseReconEvent(raidPtr, ctrl->col, NULL, RF_REVENT_READDONE);
   1273 	return (0);
   1274 }
   1275 /* this gets called upon the completion of a reconstruction write operation.
   1276  * the arg is a pointer to the rbuf that was just written
   1277  *
   1278  * called at interrupt context in the kernel, so don't do anything illegal here.
   1279  */
   1280 static int
   1281 ReconWriteDoneProc(void *arg, int status)
   1282 {
   1283 	RF_ReconBuffer_t *rbuf = (RF_ReconBuffer_t *) arg;
   1284 
   1285 	Dprintf2("Reconstruction completed on psid %ld ru %d\n", rbuf->parityStripeID, rbuf->which_ru);
   1286 	if (status) {
   1287 		printf("raid%d: Recon write failed!\n", rbuf->raidPtr->raidid);
   1288 		rf_CauseReconEvent(rbuf->raidPtr, rbuf->col, arg, RF_REVENT_WRITE_FAILED);
   1289 		return(0);
   1290 	}
   1291 	rf_CauseReconEvent(rbuf->raidPtr, rbuf->col, arg, RF_REVENT_WRITEDONE);
   1292 	return (0);
   1293 }
   1294 
   1295 
   1296 /*
   1297  * computes a new minimum head sep, and wakes up anyone who needs to
   1298  * be woken as a result
   1299  */
   1300 static void
   1301 CheckForNewMinHeadSep(RF_Raid_t *raidPtr, RF_HeadSepLimit_t hsCtr)
   1302 {
   1303 	RF_ReconCtrl_t *reconCtrlPtr = raidPtr->reconControl;
   1304 	RF_HeadSepLimit_t new_min;
   1305 	RF_RowCol_t i;
   1306 	RF_CallbackDesc_t *p;
   1307 	RF_ASSERT(hsCtr >= reconCtrlPtr->minHeadSepCounter);	/* from the definition
   1308 								 * of a minimum */
   1309 
   1310 
   1311 	RF_LOCK_MUTEX(reconCtrlPtr->rb_mutex);
   1312 
   1313 	new_min = ~(1L << (8 * sizeof(long) - 1));	/* 0x7FFF....FFF */
   1314 	for (i = 0; i < raidPtr->numCol; i++)
   1315 		if (i != reconCtrlPtr->fcol) {
   1316 			if (reconCtrlPtr->perDiskInfo[i].headSepCounter < new_min)
   1317 				new_min = reconCtrlPtr->perDiskInfo[i].headSepCounter;
   1318 		}
   1319 	/* set the new minimum and wake up anyone who can now run again */
   1320 	if (new_min != reconCtrlPtr->minHeadSepCounter) {
   1321 		reconCtrlPtr->minHeadSepCounter = new_min;
   1322 		Dprintf1("RECON:  new min head pos counter val is %ld\n", new_min);
   1323 		while (reconCtrlPtr->headSepCBList) {
   1324 			if (reconCtrlPtr->headSepCBList->callbackArg.v > new_min)
   1325 				break;
   1326 			p = reconCtrlPtr->headSepCBList;
   1327 			reconCtrlPtr->headSepCBList = p->next;
   1328 			p->next = NULL;
   1329 			rf_CauseReconEvent(raidPtr, p->col, NULL, RF_REVENT_HEADSEPCLEAR);
   1330 			rf_FreeCallbackDesc(p);
   1331 		}
   1332 
   1333 	}
   1334 	RF_UNLOCK_MUTEX(reconCtrlPtr->rb_mutex);
   1335 }
   1336 
   1337 /*
   1338  * checks to see that the maximum head separation will not be violated
   1339  * if we initiate a reconstruction I/O on the indicated disk.
   1340  * Limiting the maximum head separation between two disks eliminates
   1341  * the nasty buffer-stall conditions that occur when one disk races
   1342  * ahead of the others and consumes all of the floating recon buffers.
   1343  * This code is complex and unpleasant but it's necessary to avoid
   1344  * some very nasty, albeit fairly rare, reconstruction behavior.
   1345  *
   1346  * returns non-zero if and only if we have to stop working on the
   1347  * indicated disk due to a head-separation delay.
   1348  */
   1349 static int
   1350 CheckHeadSeparation(RF_Raid_t *raidPtr, RF_PerDiskReconCtrl_t *ctrl,
   1351 		    RF_RowCol_t col, RF_HeadSepLimit_t hsCtr,
   1352 		    RF_ReconUnitNum_t which_ru)
   1353 {
   1354 	RF_ReconCtrl_t *reconCtrlPtr = raidPtr->reconControl;
   1355 	RF_CallbackDesc_t *cb, *p, *pt;
   1356 	int     retval = 0;
   1357 
   1358 	/* if we're too far ahead of the slowest disk, stop working on this
   1359 	 * disk until the slower ones catch up.  We do this by scheduling a
   1360 	 * wakeup callback for the time when the slowest disk has caught up.
   1361 	 * We define "caught up" with 20% hysteresis, i.e. the head separation
   1362 	 * must have fallen to at most 80% of the max allowable head
   1363 	 * separation before we'll wake up.
   1364 	 *
   1365 	 */
   1366 	RF_LOCK_MUTEX(reconCtrlPtr->rb_mutex);
   1367 	if ((raidPtr->headSepLimit >= 0) &&
   1368 	    ((ctrl->headSepCounter - reconCtrlPtr->minHeadSepCounter) > raidPtr->headSepLimit)) {
   1369 		Dprintf5("raid%d: RECON: head sep stall: col %d hsCtr %ld minHSCtr %ld limit %ld\n",
   1370 			 raidPtr->raidid, col, ctrl->headSepCounter,
   1371 			 reconCtrlPtr->minHeadSepCounter,
   1372 			 raidPtr->headSepLimit);
   1373 		cb = rf_AllocCallbackDesc();
   1374 		/* the minHeadSepCounter value we have to get to before we'll
   1375 		 * wake up.  build in 20% hysteresis. */
   1376 		cb->callbackArg.v = (ctrl->headSepCounter - raidPtr->headSepLimit + raidPtr->headSepLimit / 5);
   1377 		cb->col = col;
   1378 		cb->next = NULL;
   1379 
   1380 		/* insert this callback descriptor into the sorted list of
   1381 		 * pending head-sep callbacks */
   1382 		p = reconCtrlPtr->headSepCBList;
   1383 		if (!p)
   1384 			reconCtrlPtr->headSepCBList = cb;
   1385 		else
   1386 			if (cb->callbackArg.v < p->callbackArg.v) {
   1387 				cb->next = reconCtrlPtr->headSepCBList;
   1388 				reconCtrlPtr->headSepCBList = cb;
   1389 			} else {
   1390 				for (pt = p, p = p->next; p && (p->callbackArg.v < cb->callbackArg.v); pt = p, p = p->next);
   1391 				cb->next = p;
   1392 				pt->next = cb;
   1393 			}
   1394 		retval = 1;
   1395 #if RF_RECON_STATS > 0
   1396 		ctrl->reconCtrl->reconDesc->hsStallCount++;
   1397 #endif				/* RF_RECON_STATS > 0 */
   1398 	}
   1399 	RF_UNLOCK_MUTEX(reconCtrlPtr->rb_mutex);
   1400 
   1401 	return (retval);
   1402 }
   1403 /*
   1404  * checks to see if reconstruction has been either forced or blocked
   1405  * by a user operation.  if forced, we skip this RU entirely.  else if
   1406  * blocked, put ourselves on the wait list.  else return 0.
   1407  *
   1408  * ASSUMES THE PSS MUTEX IS LOCKED UPON ENTRY
   1409  */
   1410 static int
   1411 CheckForcedOrBlockedReconstruction(RF_Raid_t *raidPtr,
   1412 				   RF_ReconParityStripeStatus_t *pssPtr,
   1413 				   RF_PerDiskReconCtrl_t *ctrl,
   1414 				   RF_RowCol_t col, RF_StripeNum_t psid,
   1415 				   RF_ReconUnitNum_t which_ru)
   1416 {
   1417 	RF_CallbackDesc_t *cb;
   1418 	int     retcode = 0;
   1419 
   1420 	if ((pssPtr->flags & RF_PSS_FORCED_ON_READ) || (pssPtr->flags & RF_PSS_FORCED_ON_WRITE))
   1421 		retcode = RF_PSS_FORCED_ON_WRITE;
   1422 	else
   1423 		if (pssPtr->flags & RF_PSS_RECON_BLOCKED) {
   1424 			Dprintf3("RECON: col %d blocked at psid %ld ru %d\n", col, psid, which_ru);
   1425 			cb = rf_AllocCallbackDesc();	/* append ourselves to
   1426 							 * the blockage-wait
   1427 							 * list */
   1428 			cb->col = col;
   1429 			cb->next = pssPtr->blockWaitList;
   1430 			pssPtr->blockWaitList = cb;
   1431 			retcode = RF_PSS_RECON_BLOCKED;
   1432 		}
   1433 	if (!retcode)
   1434 		pssPtr->flags |= RF_PSS_UNDER_RECON;	/* mark this RU as under
   1435 							 * reconstruction */
   1436 
   1437 	return (retcode);
   1438 }
   1439 /*
   1440  * if reconstruction is currently ongoing for the indicated stripeID,
   1441  * reconstruction is forced to completion and we return non-zero to
   1442  * indicate that the caller must wait.  If not, then reconstruction is
   1443  * blocked on the indicated stripe and the routine returns zero.  If
   1444  * and only if we return non-zero, we'll cause the cbFunc to get
   1445  * invoked with the cbArg when the reconstruction has completed.
   1446  */
   1447 int
   1448 rf_ForceOrBlockRecon(RF_Raid_t *raidPtr, RF_AccessStripeMap_t *asmap,
   1449 		     void (*cbFunc)(RF_Raid_t *, void *), void *cbArg)
   1450 {
   1451 	RF_StripeNum_t stripeID = asmap->stripeID;	/* the stripe ID we're
   1452 							 * forcing recon on */
   1453 	RF_SectorCount_t sectorsPerRU = raidPtr->Layout.sectorsPerStripeUnit * raidPtr->Layout.SUsPerRU;	/* num sects in one RU */
   1454 	RF_ReconParityStripeStatus_t *pssPtr, *newpssPtr;	/* a pointer to the parity
   1455 						 * stripe status structure */
   1456 	RF_StripeNum_t psid;	/* parity stripe id */
   1457 	RF_SectorNum_t offset, fd_offset;	/* disk offset, failed-disk
   1458 						 * offset */
   1459 	RF_RowCol_t *diskids;
   1460 	RF_ReconUnitNum_t which_ru;	/* RU within parity stripe */
   1461 	RF_RowCol_t fcol, diskno, i;
   1462 	RF_ReconBuffer_t *new_rbuf;	/* ptr to newly allocated rbufs */
   1463 	RF_DiskQueueData_t *req;/* disk I/O req to be enqueued */
   1464 	RF_CallbackDesc_t *cb;
   1465 	int     nPromoted;
   1466 
   1467 	psid = rf_MapStripeIDToParityStripeID(&raidPtr->Layout, stripeID, &which_ru);
   1468 
   1469 	/* allocate a new PSS in case we need it */
   1470         newpssPtr = rf_AllocPSStatus(raidPtr);
   1471 
   1472 	RF_LOCK_PSS_MUTEX(raidPtr, psid);
   1473 
   1474 	pssPtr = rf_LookupRUStatus(raidPtr, raidPtr->reconControl->pssTable, psid, which_ru, RF_PSS_CREATE | RF_PSS_RECON_BLOCKED, newpssPtr);
   1475 
   1476         if (pssPtr != newpssPtr) {
   1477                 rf_FreePSStatus(raidPtr, newpssPtr);
   1478         }
   1479 
   1480 	/* if recon is not ongoing on this PS, just return */
   1481 	if (!(pssPtr->flags & RF_PSS_UNDER_RECON)) {
   1482 		RF_UNLOCK_PSS_MUTEX(raidPtr, psid);
   1483 		return (0);
   1484 	}
   1485 	/* otherwise, we have to wait for reconstruction to complete on this
   1486 	 * RU. */
   1487 	/* In order to avoid waiting for a potentially large number of
   1488 	 * low-priority accesses to complete, we force a normal-priority (i.e.
   1489 	 * not low-priority) reconstruction on this RU. */
   1490 	if (!(pssPtr->flags & RF_PSS_FORCED_ON_WRITE) && !(pssPtr->flags & RF_PSS_FORCED_ON_READ)) {
   1491 		DDprintf1("Forcing recon on psid %ld\n", psid);
   1492 		pssPtr->flags |= RF_PSS_FORCED_ON_WRITE;	/* mark this RU as under
   1493 								 * forced recon */
   1494 		pssPtr->flags &= ~RF_PSS_RECON_BLOCKED;	/* clear the blockage
   1495 							 * that we just set */
   1496 		fcol = raidPtr->reconControl->fcol;
   1497 
   1498 		/* get a listing of the disks comprising the indicated stripe */
   1499 		(raidPtr->Layout.map->IdentifyStripe) (raidPtr, asmap->raidAddress, &diskids);
   1500 
   1501 		/* For previously issued reads, elevate them to normal
   1502 		 * priority.  If the I/O has already completed, it won't be
   1503 		 * found in the queue, and hence this will be a no-op. For
   1504 		 * unissued reads, allocate buffers and issue new reads.  The
   1505 		 * fact that we've set the FORCED bit means that the regular
   1506 		 * recon procs will not re-issue these reqs */
   1507 		for (i = 0; i < raidPtr->Layout.numDataCol + raidPtr->Layout.numParityCol; i++)
   1508 			if ((diskno = diskids[i]) != fcol) {
   1509 				if (pssPtr->issued[diskno]) {
   1510 					nPromoted = rf_DiskIOPromote(&raidPtr->Queues[diskno], psid, which_ru);
   1511 					if (rf_reconDebug && nPromoted)
   1512 						printf("raid%d: promoted read from col %d\n", raidPtr->raidid, diskno);
   1513 				} else {
   1514 					new_rbuf = rf_MakeReconBuffer(raidPtr, diskno, RF_RBUF_TYPE_FORCED);	/* create new buf */
   1515 					ComputePSDiskOffsets(raidPtr, psid, diskno, &offset, &fd_offset,
   1516 					    &new_rbuf->spCol, &new_rbuf->spOffset);	/* find offsets & spare
   1517 													 * location */
   1518 					new_rbuf->parityStripeID = psid;	/* fill in the buffer */
   1519 					new_rbuf->which_ru = which_ru;
   1520 					new_rbuf->failedDiskSectorOffset = fd_offset;
   1521 					new_rbuf->priority = RF_IO_NORMAL_PRIORITY;
   1522 
   1523 					/* use NULL b_proc b/c all addrs
   1524 					 * should be in kernel space */
   1525 					req = rf_CreateDiskQueueData(RF_IO_TYPE_READ, offset + which_ru * sectorsPerRU, sectorsPerRU, new_rbuf->buffer,
   1526 					    psid, which_ru, (int (*) (void *, int)) ForceReconReadDoneProc, (void *) new_rbuf, NULL,
   1527 					    NULL, (void *) raidPtr, 0, NULL);
   1528 
   1529 					RF_ASSERT(req);	/* XXX -- fix this --
   1530 							 * XXX */
   1531 
   1532 					new_rbuf->arg = req;
   1533 					rf_DiskIOEnqueue(&raidPtr->Queues[diskno], req, RF_IO_NORMAL_PRIORITY);	/* enqueue the I/O */
   1534 					Dprintf2("raid%d: Issued new read req on col %d\n", raidPtr->raidid, diskno);
   1535 				}
   1536 			}
   1537 		/* if the write is sitting in the disk queue, elevate its
   1538 		 * priority */
   1539 		if (rf_DiskIOPromote(&raidPtr->Queues[fcol], psid, which_ru))
   1540 			printf("raid%d: promoted write to col %d\n",
   1541 			       raidPtr->raidid, fcol);
   1542 	}
   1543 	/* install a callback descriptor to be invoked when recon completes on
   1544 	 * this parity stripe. */
   1545 	cb = rf_AllocCallbackDesc();
   1546 	/* XXX the following is bogus.. These functions don't really match!!
   1547 	 * GO */
   1548 	cb->callbackFunc = (void (*) (RF_CBParam_t)) cbFunc;
   1549 	cb->callbackArg.p = (void *) cbArg;
   1550 	cb->next = pssPtr->procWaitList;
   1551 	pssPtr->procWaitList = cb;
   1552 	DDprintf2("raid%d: Waiting for forced recon on psid %ld\n",
   1553 		  raidPtr->raidid, psid);
   1554 
   1555 	RF_UNLOCK_PSS_MUTEX(raidPtr, psid);
   1556 	return (1);
   1557 }
   1558 /* called upon the completion of a forced reconstruction read.
   1559  * all we do is schedule the FORCEDREADONE event.
   1560  * called at interrupt context in the kernel, so don't do anything illegal here.
   1561  */
   1562 static void
   1563 ForceReconReadDoneProc(void *arg, int status)
   1564 {
   1565 	RF_ReconBuffer_t *rbuf = arg;
   1566 
   1567 	if (status) {
   1568 		printf("raid%d: Forced recon read failed!\n", rbuf->raidPtr->raidid);
   1569 		rf_CauseReconEvent(rbuf->raidPtr, rbuf->col, (void *) rbuf, RF_REVENT_FORCEDREAD_FAILED);
   1570 	}
   1571 	rf_CauseReconEvent(rbuf->raidPtr, rbuf->col, (void *) rbuf, RF_REVENT_FORCEDREADDONE);
   1572 }
   1573 /* releases a block on the reconstruction of the indicated stripe */
   1574 int
   1575 rf_UnblockRecon(RF_Raid_t *raidPtr, RF_AccessStripeMap_t *asmap)
   1576 {
   1577 	RF_StripeNum_t stripeID = asmap->stripeID;
   1578 	RF_ReconParityStripeStatus_t *pssPtr;
   1579 	RF_ReconUnitNum_t which_ru;
   1580 	RF_StripeNum_t psid;
   1581 	RF_CallbackDesc_t *cb;
   1582 
   1583 	psid = rf_MapStripeIDToParityStripeID(&raidPtr->Layout, stripeID, &which_ru);
   1584 	RF_LOCK_PSS_MUTEX(raidPtr, psid);
   1585 	pssPtr = rf_LookupRUStatus(raidPtr, raidPtr->reconControl->pssTable, psid, which_ru, RF_PSS_NONE, NULL);
   1586 
   1587 	/* When recon is forced, the pss desc can get deleted before we get
   1588 	 * back to unblock recon. But, this can _only_ happen when recon is
   1589 	 * forced. It would be good to put some kind of sanity check here, but
   1590 	 * how to decide if recon was just forced or not? */
   1591 	if (!pssPtr) {
   1592 		/* printf("Warning: no pss descriptor upon unblock on psid %ld
   1593 		 * RU %d\n",psid,which_ru); */
   1594 #if (RF_DEBUG_RECON > 0) || (RF_DEBUG_PSS > 0)
   1595 		if (rf_reconDebug || rf_pssDebug)
   1596 			printf("Warning: no pss descriptor upon unblock on psid %ld RU %d\n", (long) psid, which_ru);
   1597 #endif
   1598 		goto out;
   1599 	}
   1600 	pssPtr->blockCount--;
   1601 	Dprintf3("raid%d: unblocking recon on psid %ld: blockcount is %d\n",
   1602 		 raidPtr->raidid, psid, pssPtr->blockCount);
   1603 	if (pssPtr->blockCount == 0) {	/* if recon blockage has been released */
   1604 
   1605 		/* unblock recon before calling CauseReconEvent in case
   1606 		 * CauseReconEvent causes us to try to issue a new read before
   1607 		 * returning here. */
   1608 		pssPtr->flags &= ~RF_PSS_RECON_BLOCKED;
   1609 
   1610 
   1611 		while (pssPtr->blockWaitList) {
   1612 			/* spin through the block-wait list and
   1613 			   release all the waiters */
   1614 			cb = pssPtr->blockWaitList;
   1615 			pssPtr->blockWaitList = cb->next;
   1616 			cb->next = NULL;
   1617 			rf_CauseReconEvent(raidPtr, cb->col, NULL, RF_REVENT_BLOCKCLEAR);
   1618 			rf_FreeCallbackDesc(cb);
   1619 		}
   1620 		if (!(pssPtr->flags & RF_PSS_UNDER_RECON)) {
   1621 			/* if no recon was requested while recon was blocked */
   1622 			rf_PSStatusDelete(raidPtr, raidPtr->reconControl->pssTable, pssPtr);
   1623 		}
   1624 	}
   1625 out:
   1626 	RF_UNLOCK_PSS_MUTEX(raidPtr, psid);
   1627 	return (0);
   1628 }
   1629