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