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