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