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