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