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