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