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