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