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