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