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