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