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