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