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