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