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