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