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