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