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