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