xref: /netbsd-src/sys/dev/raidframe/rf_driver.c (revision bada23909e740596d0a3785a73bd3583a9807fb8)
1 /*	$NetBSD: rf_driver.c,v 1.11 1999/03/14 21:53:31 oster Exp $	*/
2 /*-
3  * Copyright (c) 1999 The NetBSD Foundation, Inc.
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to The NetBSD Foundation
7  * by Greg Oster
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *        This product includes software developed by the NetBSD
20  *        Foundation, Inc. and its contributors.
21  * 4. Neither the name of The NetBSD Foundation nor the names of its
22  *    contributors may be used to endorse or promote products derived
23  *    from this software without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
26  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
29  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 /*
39  * Copyright (c) 1995 Carnegie-Mellon University.
40  * All rights reserved.
41  *
42  * Author: Mark Holland, Khalil Amiri, Claudson Bornstein, William V. Courtright II,
43  *         Robby Findler, Daniel Stodolsky, Rachad Youssef, Jim Zelenka
44  *
45  * Permission to use, copy, modify and distribute this software and
46  * its documentation is hereby granted, provided that both the copyright
47  * notice and this permission notice appear in all copies of the
48  * software, derivative works or modified versions, and any portions
49  * thereof, and that both notices appear in supporting documentation.
50  *
51  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
52  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
53  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
54  *
55  * Carnegie Mellon requests users of this software to return to
56  *
57  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
58  *  School of Computer Science
59  *  Carnegie Mellon University
60  *  Pittsburgh PA 15213-3890
61  *
62  * any improvements or extensions that they make and grant Carnegie the
63  * rights to redistribute these changes.
64  */
65 
66 /******************************************************************************
67  *
68  * rf_driver.c -- main setup, teardown, and access routines for the RAID driver
69  *
70  * all routines are prefixed with rf_ (raidframe), to avoid conficts.
71  *
72  ******************************************************************************/
73 
74 
75 #include <sys/types.h>
76 #include <sys/param.h>
77 #include <sys/systm.h>
78 #include <sys/ioctl.h>
79 #include <sys/fcntl.h>
80 #include <sys/vnode.h>
81 
82 
83 #include "rf_archs.h"
84 #include "rf_threadstuff.h"
85 
86 #include <sys/errno.h>
87 
88 #include "rf_raid.h"
89 #include "rf_dag.h"
90 #include "rf_aselect.h"
91 #include "rf_diskqueue.h"
92 #include "rf_parityscan.h"
93 #include "rf_alloclist.h"
94 #include "rf_threadid.h"
95 #include "rf_dagutils.h"
96 #include "rf_utils.h"
97 #include "rf_etimer.h"
98 #include "rf_acctrace.h"
99 #include "rf_configure.h"
100 #include "rf_general.h"
101 #include "rf_desc.h"
102 #include "rf_states.h"
103 #include "rf_freelist.h"
104 #include "rf_decluster.h"
105 #include "rf_map.h"
106 #include "rf_diskthreads.h"
107 #include "rf_revent.h"
108 #include "rf_callback.h"
109 #include "rf_engine.h"
110 #include "rf_memchunk.h"
111 #include "rf_mcpair.h"
112 #include "rf_nwayxor.h"
113 #include "rf_debugprint.h"
114 #include "rf_copyback.h"
115 #include "rf_driver.h"
116 #include "rf_options.h"
117 #include "rf_shutdown.h"
118 #include "rf_sys.h"
119 #include "rf_cpuutil.h"
120 
121 #include <sys/buf.h>
122 
123 #if DKUSAGE > 0
124 #include <sys/dkusage.h>
125 #include <io/common/iotypes.h>
126 #include <io/cam/dec_cam.h>
127 #include <io/cam/cam.h>
128 #include <io/cam/pdrv.h>
129 #endif				/* DKUSAGE > 0 */
130 
131 /* rad == RF_RaidAccessDesc_t */
132 static RF_FreeList_t *rf_rad_freelist;
133 #define RF_MAX_FREE_RAD 128
134 #define RF_RAD_INC       16
135 #define RF_RAD_INITIAL   32
136 
137 /* debug variables */
138 char    rf_panicbuf[2048];	/* a buffer to hold an error msg when we panic */
139 
140 /* main configuration routines */
141 static int raidframe_booted = 0;
142 
143 static void rf_ConfigureDebug(RF_Config_t * cfgPtr);
144 static void set_debug_option(char *name, long val);
145 static void rf_UnconfigureArray(void);
146 static int init_rad(RF_RaidAccessDesc_t *);
147 static void clean_rad(RF_RaidAccessDesc_t *);
148 static void rf_ShutdownRDFreeList(void *);
149 static int rf_ConfigureRDFreeList(RF_ShutdownList_t **);
150 void rf_UnconfigureVnodes( RF_Raid_t * );
151 
152 /* XXX move these to their own .h file! */
153 int raidwrite_component_label(dev_t, struct vnode *, RF_ComponentLabel_t *);
154 int raidread_component_label(dev_t, struct vnode *, RF_ComponentLabel_t *);
155 int raidmarkclean(dev_t dev, struct vnode *b_vp,int);
156 void rf_update_component_labels( RF_Raid_t *);
157 
158 RF_DECLARE_MUTEX(rf_printf_mutex)	/* debug only:  avoids interleaved
159 					 * printfs by different stripes */
160 RF_DECLARE_GLOBAL_THREADID	/* declarations for threadid.h */
161 
162 
163 #define SIGNAL_QUIESCENT_COND(_raid_)  wakeup(&((_raid_)->accesses_suspended))
164 #define WAIT_FOR_QUIESCENCE(_raid_) \
165 	tsleep(&((_raid_)->accesses_suspended),PRIBIO,"raidframe quiesce", 0);
166 
167 #if DKUSAGE > 0
168 #define IO_BUF_ERR(bp, err, unit) { \
169 	bp->b_flags |= B_ERROR; \
170 	bp->b_resid = bp->b_bcount; \
171 	bp->b_error = err; \
172 	RF_DKU_END_IO(unit, bp); \
173 	biodone(bp); \
174 }
175 #else
176 #define IO_BUF_ERR(bp, err, unit) { \
177 	bp->b_flags |= B_ERROR; \
178 	bp->b_resid = bp->b_bcount; \
179 	bp->b_error = err; \
180 	RF_DKU_END_IO(unit); \
181 	biodone(bp); \
182 }
183 #endif				/* DKUSAGE > 0 */
184 
185 static int configureCount = 0;	/* number of active configurations */
186 static int isconfigged = 0;	/* is basic raidframe (non per-array)
187 				 * stuff configged */
188 RF_DECLARE_STATIC_MUTEX(configureMutex)	/* used to lock the configuration
189 					 * stuff */
190 static RF_ShutdownList_t *globalShutdown;	/* non array-specific
191 						 * stuff */
192 
193 static int rf_ConfigureRDFreeList(RF_ShutdownList_t ** listp);
194 
195 /* called at system boot time */
196 int
197 rf_BootRaidframe()
198 {
199 	int     rc;
200 
201 	if (raidframe_booted)
202 		return (EBUSY);
203 	raidframe_booted = 1;
204 
205 #if RF_DEBUG_ATOMIC > 0
206 	rf_atent_init();
207 #endif				/* RF_DEBUG_ATOMIC > 0 */
208 
209 	rf_setup_threadid();
210 	rf_assign_threadid();
211 
212 	rc = rf_mutex_init(&configureMutex);
213 	if (rc) {
214 		RF_ERRORMSG3("Unable to init mutex file %s line %d rc=%d\n", __FILE__,
215 		    __LINE__, rc);
216 		RF_PANIC();
217 	}
218 	configureCount = 0;
219 	isconfigged = 0;
220 	globalShutdown = NULL;
221 	return (0);
222 }
223 /*
224  * This function is really just for debugging user-level stuff: it
225  * frees up all memory, other RAIDframe resources which might otherwise
226  * be kept around. This is used with systems like "sentinel" to detect
227  * memory leaks.
228  */
229 int
230 rf_UnbootRaidframe()
231 {
232 	int     rc;
233 
234 	RF_LOCK_MUTEX(configureMutex);
235 	if (configureCount) {
236 		RF_UNLOCK_MUTEX(configureMutex);
237 		return (EBUSY);
238 	}
239 	raidframe_booted = 0;
240 	RF_UNLOCK_MUTEX(configureMutex);
241 	rc = rf_mutex_destroy(&configureMutex);
242 	if (rc) {
243 		RF_ERRORMSG3("Unable to destroy mutex file %s line %d rc=%d\n", __FILE__,
244 		    __LINE__, rc);
245 		RF_PANIC();
246 	}
247 #if RF_DEBUG_ATOMIC > 0
248 	rf_atent_shutdown();
249 #endif				/* RF_DEBUG_ATOMIC > 0 */
250 	return (0);
251 }
252 /*
253  * Called whenever an array is shutdown
254  */
255 static void
256 rf_UnconfigureArray()
257 {
258 	int     rc;
259 
260 	RF_LOCK_MUTEX(configureMutex);
261 	if (--configureCount == 0) {	/* if no active configurations, shut
262 					 * everything down */
263 		isconfigged = 0;
264 
265 		rc = rf_ShutdownList(&globalShutdown);
266 		if (rc) {
267 			RF_ERRORMSG1("RAIDFRAME: unable to do global shutdown, rc=%d\n", rc);
268 		}
269 		rf_shutdown_threadid();
270 
271 		/*
272 	         * We must wait until now, because the AllocList module
273 	         * uses the DebugMem module.
274 	         */
275 		if (rf_memDebug)
276 			rf_print_unfreed();
277 	}
278 	RF_UNLOCK_MUTEX(configureMutex);
279 }
280 
281 /*
282  * Called to shut down an array.
283  */
284 int
285 rf_Shutdown(raidPtr)
286 	RF_Raid_t *raidPtr;
287 {
288 
289 	if (!raidPtr->valid) {
290 		RF_ERRORMSG("Attempt to shut down unconfigured RAIDframe driver.  Aborting shutdown\n");
291 		return (EINVAL);
292 	}
293 	/*
294          * wait for outstanding IOs to land
295          * As described in rf_raid.h, we use the rad_freelist lock
296          * to protect the per-array info about outstanding descs
297          * since we need to do freelist locking anyway, and this
298          * cuts down on the amount of serialization we've got going
299          * on.
300          */
301 	RF_FREELIST_DO_LOCK(rf_rad_freelist);
302 	if (raidPtr->waitShutdown) {
303 		RF_FREELIST_DO_UNLOCK(rf_rad_freelist);
304 		return (EBUSY);
305 	}
306 	raidPtr->waitShutdown = 1;
307 	while (raidPtr->nAccOutstanding) {
308 		RF_WAIT_COND(raidPtr->outstandingCond, RF_FREELIST_MUTEX_OF(rf_rad_freelist));
309 	}
310 	RF_FREELIST_DO_UNLOCK(rf_rad_freelist);
311 
312 	raidPtr->valid = 0;
313 
314 	rf_update_component_labels(raidPtr);
315 
316 	rf_UnconfigureVnodes(raidPtr);
317 
318 	rf_ShutdownList(&raidPtr->shutdownList);
319 
320 	rf_UnconfigureArray();
321 
322 	return (0);
323 }
324 
325 void
326 rf_UnconfigureVnodes( raidPtr )
327 	RF_Raid_t *raidPtr;
328 {
329 	int r,c;
330 	struct proc *p;
331 
332 
333 	/* We take this opportunity to close the vnodes like we should.. */
334 
335 	p = raidPtr->proc;	/* XXX */
336 
337 	for (r = 0; r < raidPtr->numRow; r++) {
338 		for (c = 0; c < raidPtr->numCol; c++) {
339 			printf("Closing vnode for row: %d col: %d\n", r, c);
340 			if (raidPtr->raid_cinfo[r][c].ci_vp) {
341 				VOP_UNLOCK(raidPtr->raid_cinfo[r][c].ci_vp, 0);
342 				(void) vn_close(raidPtr->raid_cinfo[r][c].ci_vp,
343 				    FREAD | FWRITE, p->p_ucred, p);
344 				raidPtr->raid_cinfo[r][c].ci_vp = NULL;
345 			} else {
346 				printf("vnode was NULL\n");
347 			}
348 
349 		}
350 	}
351 	for (r = 0; r < raidPtr->numSpare; r++) {
352 		printf("Closing vnode for spare: %d\n", r);
353 		if (raidPtr->raid_cinfo[0][raidPtr->numCol + r].ci_vp) {
354 			VOP_UNLOCK(raidPtr->raid_cinfo[0][raidPtr->numCol + r].ci_vp, 0);
355 			(void) vn_close(raidPtr->raid_cinfo[0][raidPtr->numCol + r].ci_vp,
356 			    FREAD | FWRITE, p->p_ucred, p);
357 			raidPtr->raid_cinfo[0][raidPtr->numCol + r].ci_vp = NULL;
358 		} else {
359 			printf("vnode was NULL\n");
360 		}
361 	}
362 
363 
364 }
365 
366 
367 #define DO_INIT_CONFIGURE(f) { \
368 	rc = f (&globalShutdown); \
369 	if (rc) { \
370 		RF_ERRORMSG2("RAIDFRAME: failed %s with %d\n", RF_STRING(f), rc); \
371 		rf_ShutdownList(&globalShutdown); \
372 		configureCount--; \
373 		RF_UNLOCK_MUTEX(configureMutex); \
374 		return(rc); \
375 	} \
376 }
377 
378 #define DO_RAID_FAIL() { \
379 	rf_ShutdownList(&raidPtr->shutdownList); \
380 	rf_UnconfigureArray(); \
381 }
382 
383 #define DO_RAID_INIT_CONFIGURE(f) { \
384 	rc = f (&raidPtr->shutdownList, raidPtr, cfgPtr); \
385 	if (rc) { \
386 		RF_ERRORMSG2("RAIDFRAME: failed %s with %d\n", RF_STRING(f), rc); \
387 		DO_RAID_FAIL(); \
388 		return(rc); \
389 	} \
390 }
391 
392 #define DO_RAID_MUTEX(_m_) { \
393 	rc = rf_create_managed_mutex(&raidPtr->shutdownList, (_m_)); \
394 	if (rc) { \
395 		RF_ERRORMSG3("Unable to init mutex file %s line %d rc=%d\n", \
396 			__FILE__, __LINE__, rc); \
397 		DO_RAID_FAIL(); \
398 		return(rc); \
399 	} \
400 }
401 
402 #define DO_RAID_COND(_c_) { \
403 	rc = rf_create_managed_cond(&raidPtr->shutdownList, (_c_)); \
404 	if (rc) { \
405 		RF_ERRORMSG3("Unable to init cond file %s line %d rc=%d\n", \
406 			__FILE__, __LINE__, rc); \
407 		DO_RAID_FAIL(); \
408 		return(rc); \
409 	} \
410 }
411 
412 int
413 rf_Configure(raidPtr, cfgPtr)
414 	RF_Raid_t *raidPtr;
415 	RF_Config_t *cfgPtr;
416 {
417 	RF_RowCol_t row, col;
418 	int     i, rc;
419 	int     unit;
420 	struct proc *p;
421 
422 	if (raidPtr->valid) {
423 		RF_ERRORMSG("RAIDframe configuration not shut down.  Aborting configure.\n");
424 		return (EINVAL);
425 	}
426 	RF_LOCK_MUTEX(configureMutex);
427 	configureCount++;
428 	if (isconfigged == 0) {
429 		rc = rf_create_managed_mutex(&globalShutdown, &rf_printf_mutex);
430 		if (rc) {
431 			RF_ERRORMSG3("Unable to init mutex file %s line %d rc=%d\n", __FILE__,
432 			    __LINE__, rc);
433 			rf_ShutdownList(&globalShutdown);
434 			return (rc);
435 		}
436 		/* initialize globals */
437 		printf("RAIDFRAME: protectedSectors is %ld\n", rf_protectedSectors);
438 
439 		rf_clear_debug_print_buffer();
440 
441 		DO_INIT_CONFIGURE(rf_ConfigureAllocList);
442 		DO_INIT_CONFIGURE(rf_ConfigureEtimer);
443 		/*
444 	         * Yes, this does make debugging general to the whole system instead
445 	         * of being array specific. Bummer, drag.
446 	         */
447 		rf_ConfigureDebug(cfgPtr);
448 		DO_INIT_CONFIGURE(rf_ConfigureDebugMem);
449 		DO_INIT_CONFIGURE(rf_ConfigureAccessTrace);
450 		DO_INIT_CONFIGURE(rf_ConfigureMapModule);
451 		DO_INIT_CONFIGURE(rf_ConfigureReconEvent);
452 		DO_INIT_CONFIGURE(rf_ConfigureCallback);
453 		DO_INIT_CONFIGURE(rf_ConfigureMemChunk);
454 		DO_INIT_CONFIGURE(rf_ConfigureRDFreeList);
455 		DO_INIT_CONFIGURE(rf_ConfigureNWayXor);
456 		DO_INIT_CONFIGURE(rf_ConfigureStripeLockFreeList);
457 		DO_INIT_CONFIGURE(rf_ConfigureMCPair);
458 #if !defined(__NetBSD__)
459 		DO_INIT_CONFIGURE(rf_ConfigureCamLayer);
460 #endif
461 		DO_INIT_CONFIGURE(rf_ConfigureDAGs);
462 		DO_INIT_CONFIGURE(rf_ConfigureDAGFuncs);
463 		DO_INIT_CONFIGURE(rf_ConfigureDebugPrint);
464 		DO_INIT_CONFIGURE(rf_ConfigureReconstruction);
465 		DO_INIT_CONFIGURE(rf_ConfigureCopyback);
466 		DO_INIT_CONFIGURE(rf_ConfigureDiskQueueSystem);
467 		DO_INIT_CONFIGURE(rf_ConfigureCpuMonitor);
468 		isconfigged = 1;
469 	}
470 	RF_UNLOCK_MUTEX(configureMutex);
471 
472 	/*
473          * Null out the entire raid descriptor to avoid problems when we reconfig.
474          * This also clears the valid bit.
475          */
476 	/* XXX this clearing should be moved UP to outside of here.... that,
477 	 * or rf_Configure() needs to take more arguments... XXX */
478 	unit = raidPtr->raidid;
479 	p = raidPtr->proc;	/* XXX save these... */
480 	bzero((char *) raidPtr, sizeof(RF_Raid_t));
481 	raidPtr->raidid = unit;
482 	raidPtr->proc = p;	/* XXX and then recover them.. */
483 	DO_RAID_MUTEX(&raidPtr->mutex);
484 	/* set up the cleanup list.  Do this after ConfigureDebug so that
485 	 * value of memDebug will be set */
486 
487 	rf_MakeAllocList(raidPtr->cleanupList);
488 	if (raidPtr->cleanupList == NULL) {
489 		DO_RAID_FAIL();
490 		return (ENOMEM);
491 	}
492 	rc = rf_ShutdownCreate(&raidPtr->shutdownList,
493 	    (void (*) (void *)) rf_FreeAllocList,
494 	    raidPtr->cleanupList);
495 	if (rc) {
496 		RF_ERRORMSG3("Unable to add to shutdown list file %s line %d rc=%d\n",
497 		    __FILE__, __LINE__, rc);
498 		DO_RAID_FAIL();
499 		return (rc);
500 	}
501 	raidPtr->numRow = cfgPtr->numRow;
502 	raidPtr->numCol = cfgPtr->numCol;
503 	raidPtr->numSpare = cfgPtr->numSpare;
504 
505 	/* XXX we don't even pretend to support more than one row in the
506 	 * kernel... */
507 	if (raidPtr->numRow != 1) {
508 		RF_ERRORMSG("Only one row supported in kernel.\n");
509 		DO_RAID_FAIL();
510 		return (EINVAL);
511 	}
512 	RF_CallocAndAdd(raidPtr->status, raidPtr->numRow, sizeof(RF_RowStatus_t),
513 	    (RF_RowStatus_t *), raidPtr->cleanupList);
514 	if (raidPtr->status == NULL) {
515 		DO_RAID_FAIL();
516 		return (ENOMEM);
517 	}
518 	RF_CallocAndAdd(raidPtr->reconControl, raidPtr->numRow,
519 	    sizeof(RF_ReconCtrl_t *), (RF_ReconCtrl_t **), raidPtr->cleanupList);
520 	if (raidPtr->reconControl == NULL) {
521 		DO_RAID_FAIL();
522 		return (ENOMEM);
523 	}
524 	for (i = 0; i < raidPtr->numRow; i++) {
525 		raidPtr->status[i] = rf_rs_optimal;
526 		raidPtr->reconControl[i] = NULL;
527 	}
528 
529 	DO_RAID_INIT_CONFIGURE(rf_ConfigureEngine);
530 	DO_RAID_INIT_CONFIGURE(rf_ConfigureStripeLocks);
531 
532 	DO_RAID_COND(&raidPtr->outstandingCond);
533 
534 	raidPtr->nAccOutstanding = 0;
535 	raidPtr->waitShutdown = 0;
536 
537 	DO_RAID_MUTEX(&raidPtr->access_suspend_mutex);
538 	DO_RAID_COND(&raidPtr->quiescent_cond);
539 
540 	DO_RAID_COND(&raidPtr->waitForReconCond);
541 
542 	DO_RAID_MUTEX(&raidPtr->recon_done_proc_mutex);
543 	DO_RAID_INIT_CONFIGURE(rf_ConfigureDisks);
544 	DO_RAID_INIT_CONFIGURE(rf_ConfigureSpareDisks);
545 	/* do this after ConfigureDisks & ConfigureSpareDisks to be sure dev
546 	 * no. is set */
547 	DO_RAID_INIT_CONFIGURE(rf_ConfigureDiskQueues);
548 
549 	DO_RAID_INIT_CONFIGURE(rf_ConfigureLayout);
550 
551 	DO_RAID_INIT_CONFIGURE(rf_ConfigurePSStatus);
552 
553 	for (row = 0; row < raidPtr->numRow; row++) {
554 		for (col = 0; col < raidPtr->numCol; col++) {
555 			/*
556 		         * XXX better distribution
557 		         */
558 			raidPtr->hist_diskreq[row][col] = 0;
559 		}
560 	}
561 
562 	if (rf_keepAccTotals) {
563 		raidPtr->keep_acc_totals = 1;
564 	}
565 	rf_StartUserStats(raidPtr);
566 
567 	raidPtr->valid = 1;
568 	return (0);
569 }
570 
571 static int
572 init_rad(desc)
573 	RF_RaidAccessDesc_t *desc;
574 {
575 	int     rc;
576 
577 	rc = rf_mutex_init(&desc->mutex);
578 	if (rc) {
579 		RF_ERRORMSG3("Unable to init mutex file %s line %d rc=%d\n", __FILE__,
580 		    __LINE__, rc);
581 		return (rc);
582 	}
583 	rc = rf_cond_init(&desc->cond);
584 	if (rc) {
585 		RF_ERRORMSG3("Unable to init cond file %s line %d rc=%d\n", __FILE__,
586 		    __LINE__, rc);
587 		rf_mutex_destroy(&desc->mutex);
588 		return (rc);
589 	}
590 	return (0);
591 }
592 
593 static void
594 clean_rad(desc)
595 	RF_RaidAccessDesc_t *desc;
596 {
597 	rf_mutex_destroy(&desc->mutex);
598 	rf_cond_destroy(&desc->cond);
599 }
600 
601 static void
602 rf_ShutdownRDFreeList(ignored)
603 	void   *ignored;
604 {
605 	RF_FREELIST_DESTROY_CLEAN(rf_rad_freelist, next, (RF_RaidAccessDesc_t *), clean_rad);
606 }
607 
608 static int
609 rf_ConfigureRDFreeList(listp)
610 	RF_ShutdownList_t **listp;
611 {
612 	int     rc;
613 
614 	RF_FREELIST_CREATE(rf_rad_freelist, RF_MAX_FREE_RAD,
615 	    RF_RAD_INC, sizeof(RF_RaidAccessDesc_t));
616 	if (rf_rad_freelist == NULL) {
617 		return (ENOMEM);
618 	}
619 	rc = rf_ShutdownCreate(listp, rf_ShutdownRDFreeList, NULL);
620 	if (rc) {
621 		RF_ERRORMSG3("Unable to add to shutdown list file %s line %d rc=%d\n", __FILE__,
622 		    __LINE__, rc);
623 		rf_ShutdownRDFreeList(NULL);
624 		return (rc);
625 	}
626 	RF_FREELIST_PRIME_INIT(rf_rad_freelist, RF_RAD_INITIAL, next,
627 	    (RF_RaidAccessDesc_t *), init_rad);
628 	return (0);
629 }
630 
631 RF_RaidAccessDesc_t *
632 rf_AllocRaidAccDesc(
633     RF_Raid_t * raidPtr,
634     RF_IoType_t type,
635     RF_RaidAddr_t raidAddress,
636     RF_SectorCount_t numBlocks,
637     caddr_t bufPtr,
638     void *bp,
639     RF_DagHeader_t ** paramDAG,
640     RF_AccessStripeMapHeader_t ** paramASM,
641     RF_RaidAccessFlags_t flags,
642     void (*cbF) (struct buf *),
643     void *cbA,
644     RF_AccessState_t * states)
645 {
646 	RF_RaidAccessDesc_t *desc;
647 
648 	RF_FREELIST_GET_INIT_NOUNLOCK(rf_rad_freelist, desc, next, (RF_RaidAccessDesc_t *), init_rad);
649 	if (raidPtr->waitShutdown) {
650 		/*
651 	         * Actually, we're shutting the array down. Free the desc
652 	         * and return NULL.
653 	         */
654 		RF_FREELIST_DO_UNLOCK(rf_rad_freelist);
655 		RF_FREELIST_FREE_CLEAN(rf_rad_freelist, desc, next, clean_rad);
656 		return (NULL);
657 	}
658 	raidPtr->nAccOutstanding++;
659 	RF_FREELIST_DO_UNLOCK(rf_rad_freelist);
660 
661 	desc->raidPtr = (void *) raidPtr;
662 	desc->type = type;
663 	desc->raidAddress = raidAddress;
664 	desc->numBlocks = numBlocks;
665 	desc->bufPtr = bufPtr;
666 	desc->bp = bp;
667 	desc->paramDAG = paramDAG;
668 	desc->paramASM = paramASM;
669 	desc->flags = flags;
670 	desc->states = states;
671 	desc->state = 0;
672 
673 	desc->status = 0;
674 	bzero((char *) &desc->tracerec, sizeof(RF_AccTraceEntry_t));
675 	desc->callbackFunc = (void (*) (RF_CBParam_t)) cbF;	/* XXX */
676 	desc->callbackArg = cbA;
677 	desc->next = NULL;
678 	desc->head = desc;
679 	desc->numPending = 0;
680 	desc->cleanupList = NULL;
681 	rf_MakeAllocList(desc->cleanupList);
682 	rf_get_threadid(desc->tid);
683 	return (desc);
684 }
685 
686 void
687 rf_FreeRaidAccDesc(RF_RaidAccessDesc_t * desc)
688 {
689 	RF_Raid_t *raidPtr = desc->raidPtr;
690 
691 	RF_ASSERT(desc);
692 
693 	rf_FreeAllocList(desc->cleanupList);
694 	RF_FREELIST_FREE_CLEAN_NOUNLOCK(rf_rad_freelist, desc, next, clean_rad);
695 	raidPtr->nAccOutstanding--;
696 	if (raidPtr->waitShutdown) {
697 		RF_SIGNAL_COND(raidPtr->outstandingCond);
698 	}
699 	RF_FREELIST_DO_UNLOCK(rf_rad_freelist);
700 }
701 /*********************************************************************
702  * Main routine for performing an access.
703  * Accesses are retried until a DAG can not be selected.  This occurs
704  * when either the DAG library is incomplete or there are too many
705  * failures in a parity group.
706  ********************************************************************/
707 int
708 rf_DoAccess(
709     RF_Raid_t * raidPtr,
710     RF_IoType_t type,
711     int async_flag,
712     RF_RaidAddr_t raidAddress,
713     RF_SectorCount_t numBlocks,
714     caddr_t bufPtr,
715     void *bp_in,
716     RF_DagHeader_t ** paramDAG,
717     RF_AccessStripeMapHeader_t ** paramASM,
718     RF_RaidAccessFlags_t flags,
719     RF_RaidAccessDesc_t ** paramDesc,
720     void (*cbF) (struct buf *),
721     void *cbA)
722 /*
723 type should be read or write
724 async_flag should be RF_TRUE or RF_FALSE
725 bp_in is a buf pointer.  void * to facilitate ignoring it outside the kernel
726 */
727 {
728 	int     tid;
729 	RF_RaidAccessDesc_t *desc;
730 	caddr_t lbufPtr = bufPtr;
731 	struct buf *bp = (struct buf *) bp_in;
732 #if DFSTRACE > 0
733 	struct {
734 		RF_uint64 raidAddr;
735 		int     numBlocks;
736 		char    type;
737 	}       dfsrecord;
738 #endif				/* DFSTRACE > 0 */
739 
740 	raidAddress += rf_raidSectorOffset;
741 
742 	if (!raidPtr->valid) {
743 		RF_ERRORMSG("RAIDframe driver not successfully configured.  Rejecting access.\n");
744 		IO_BUF_ERR(bp, EINVAL, raidPtr->raidid);
745 		return (EINVAL);
746 	}
747 #if defined(KERNEL) && DFSTRACE > 0
748 	if (rf_DFSTraceAccesses) {
749 		dfsrecord.raidAddr = raidAddress;
750 		dfsrecord.numBlocks = numBlocks;
751 		dfsrecord.type = type;
752 		dfs_log(DFS_NOTE, (char *) &dfsrecord, sizeof(dfsrecord), 0);
753 	}
754 #endif				/* KERNEL && DFSTRACE > 0 */
755 
756 	rf_get_threadid(tid);
757 	if (rf_accessDebug) {
758 
759 		printf("logBytes is: %d %d %d\n", raidPtr->raidid,
760 		    raidPtr->logBytesPerSector,
761 		    (int) rf_RaidAddressToByte(raidPtr, numBlocks));
762 		printf("[%d] %s raidAddr %d (stripeid %d-%d) numBlocks %d (%d bytes) buf 0x%lx\n", tid,
763 		    (type == RF_IO_TYPE_READ) ? "READ" : "WRITE", (int) raidAddress,
764 		    (int) rf_RaidAddressToStripeID(&raidPtr->Layout, raidAddress),
765 		    (int) rf_RaidAddressToStripeID(&raidPtr->Layout, raidAddress + numBlocks - 1),
766 		    (int) numBlocks,
767 		    (int) rf_RaidAddressToByte(raidPtr, numBlocks),
768 		    (long) bufPtr);
769 	}
770 	if (raidAddress + numBlocks > raidPtr->totalSectors) {
771 
772 		printf("DoAccess: raid addr %lu too large to access %lu sectors.  Max legal addr is %lu\n",
773 		    (u_long) raidAddress, (u_long) numBlocks, (u_long) raidPtr->totalSectors);
774 
775 		if (type == RF_IO_TYPE_READ) {
776 			IO_BUF_ERR(bp, ENOSPC, raidPtr->raidid);
777 			return (ENOSPC);
778 		} else {
779 			IO_BUF_ERR(bp, ENOSPC, raidPtr->raidid);
780 			return (ENOSPC);
781 		}
782 	}
783 	desc = rf_AllocRaidAccDesc(raidPtr, type, raidAddress,
784 	    numBlocks, lbufPtr, bp, paramDAG, paramASM,
785 	    flags, cbF, cbA, raidPtr->Layout.map->states);
786 
787 	if (desc == NULL) {
788 		return (ENOMEM);
789 	}
790 	RF_ETIMER_START(desc->tracerec.tot_timer);
791 
792 	desc->async_flag = async_flag;
793 
794 	rf_ContinueRaidAccess(desc);
795 
796 	return (0);
797 }
798 /* force the array into reconfigured mode without doing reconstruction */
799 int
800 rf_SetReconfiguredMode(raidPtr, row, col)
801 	RF_Raid_t *raidPtr;
802 	int     row;
803 	int     col;
804 {
805 	if (!(raidPtr->Layout.map->flags & RF_DISTRIBUTE_SPARE)) {
806 		printf("Can't set reconfigured mode in dedicated-spare array\n");
807 		RF_PANIC();
808 	}
809 	RF_LOCK_MUTEX(raidPtr->mutex);
810 	raidPtr->numFailures++;
811 	raidPtr->Disks[row][col].status = rf_ds_dist_spared;
812 	raidPtr->status[row] = rf_rs_reconfigured;
813 	/* install spare table only if declustering + distributed sparing
814 	 * architecture. */
815 	if (raidPtr->Layout.map->flags & RF_BD_DECLUSTERED)
816 		rf_InstallSpareTable(raidPtr, row, col);
817 	RF_UNLOCK_MUTEX(raidPtr->mutex);
818 	return (0);
819 }
820 
821 extern int fail_row, fail_col, fail_time;
822 extern int delayed_recon;
823 
824 int
825 rf_FailDisk(
826     RF_Raid_t * raidPtr,
827     int frow,
828     int fcol,
829     int initRecon)
830 {
831 	int     tid;
832 
833 	rf_get_threadid(tid);
834 	printf("[%d] Failing disk r%d c%d\n", tid, frow, fcol);
835 	RF_LOCK_MUTEX(raidPtr->mutex);
836 	raidPtr->numFailures++;
837 	raidPtr->Disks[frow][fcol].status = rf_ds_failed;
838 	raidPtr->status[frow] = rf_rs_degraded;
839 	RF_UNLOCK_MUTEX(raidPtr->mutex);
840 	if (initRecon)
841 		rf_ReconstructFailedDisk(raidPtr, frow, fcol);
842 	return (0);
843 }
844 /* releases a thread that is waiting for the array to become quiesced.
845  * access_suspend_mutex should be locked upon calling this
846  */
847 void
848 rf_SignalQuiescenceLock(raidPtr, reconDesc)
849 	RF_Raid_t *raidPtr;
850 	RF_RaidReconDesc_t *reconDesc;
851 {
852 	int     tid;
853 
854 	if (rf_quiesceDebug) {
855 		rf_get_threadid(tid);
856 		printf("[%d] Signalling quiescence lock\n", tid);
857 	}
858 	raidPtr->access_suspend_release = 1;
859 
860 	if (raidPtr->waiting_for_quiescence) {
861 		SIGNAL_QUIESCENT_COND(raidPtr);
862 	}
863 }
864 /* suspends all new requests to the array.  No effect on accesses that are in flight.  */
865 int
866 rf_SuspendNewRequestsAndWait(raidPtr)
867 	RF_Raid_t *raidPtr;
868 {
869 	if (rf_quiesceDebug)
870 		printf("Suspending new reqs\n");
871 
872 	RF_LOCK_MUTEX(raidPtr->access_suspend_mutex);
873 	raidPtr->accesses_suspended++;
874 	raidPtr->waiting_for_quiescence = (raidPtr->accs_in_flight == 0) ? 0 : 1;
875 
876 	if (raidPtr->waiting_for_quiescence) {
877 		raidPtr->access_suspend_release = 0;
878 		while (!raidPtr->access_suspend_release) {
879 			printf("Suspending: Waiting for Quiesence\n");
880 			WAIT_FOR_QUIESCENCE(raidPtr);
881 			raidPtr->waiting_for_quiescence = 0;
882 		}
883 	}
884 	printf("Quiesence reached..\n");
885 
886 	RF_UNLOCK_MUTEX(raidPtr->access_suspend_mutex);
887 	return (raidPtr->waiting_for_quiescence);
888 }
889 /* wake up everyone waiting for quiescence to be released */
890 void
891 rf_ResumeNewRequests(raidPtr)
892 	RF_Raid_t *raidPtr;
893 {
894 	RF_CallbackDesc_t *t, *cb;
895 
896 	if (rf_quiesceDebug)
897 		printf("Resuming new reqs\n");
898 
899 	RF_LOCK_MUTEX(raidPtr->access_suspend_mutex);
900 	raidPtr->accesses_suspended--;
901 	if (raidPtr->accesses_suspended == 0)
902 		cb = raidPtr->quiesce_wait_list;
903 	else
904 		cb = NULL;
905 	raidPtr->quiesce_wait_list = NULL;
906 	RF_UNLOCK_MUTEX(raidPtr->access_suspend_mutex);
907 
908 	while (cb) {
909 		t = cb;
910 		cb = cb->next;
911 		(t->callbackFunc) (t->callbackArg);
912 		rf_FreeCallbackDesc(t);
913 	}
914 }
915 /*****************************************************************************************
916  *
917  * debug routines
918  *
919  ****************************************************************************************/
920 
921 static void
922 set_debug_option(name, val)
923 	char   *name;
924 	long    val;
925 {
926 	RF_DebugName_t *p;
927 
928 	for (p = rf_debugNames; p->name; p++) {
929 		if (!strcmp(p->name, name)) {
930 			*(p->ptr) = val;
931 			printf("[Set debug variable %s to %ld]\n", name, val);
932 			return;
933 		}
934 	}
935 	RF_ERRORMSG1("Unknown debug string \"%s\"\n", name);
936 }
937 
938 
939 /* would like to use sscanf here, but apparently not available in kernel */
940 /*ARGSUSED*/
941 static void
942 rf_ConfigureDebug(cfgPtr)
943 	RF_Config_t *cfgPtr;
944 {
945 	char   *val_p, *name_p, *white_p;
946 	long    val;
947 	int     i;
948 
949 	rf_ResetDebugOptions();
950 	for (i = 0; cfgPtr->debugVars[i][0] && i < RF_MAXDBGV; i++) {
951 		name_p = rf_find_non_white(&cfgPtr->debugVars[i][0]);
952 		white_p = rf_find_white(name_p);	/* skip to start of 2nd
953 							 * word */
954 		val_p = rf_find_non_white(white_p);
955 		if (*val_p == '0' && *(val_p + 1) == 'x')
956 			val = rf_htoi(val_p + 2);
957 		else
958 			val = rf_atoi(val_p);
959 		*white_p = '\0';
960 		set_debug_option(name_p, val);
961 	}
962 }
963 /* performance monitoring stuff */
964 
965 #define TIMEVAL_TO_US(t) (((long) t.tv_sec) * 1000000L + (long) t.tv_usec)
966 
967 #if !defined(_KERNEL) && !defined(SIMULATE)
968 
969 /*
970  * Throughput stats currently only used in user-level RAIDframe
971  */
972 
973 static int
974 rf_InitThroughputStats(
975     RF_ShutdownList_t ** listp,
976     RF_Raid_t * raidPtr,
977     RF_Config_t * cfgPtr)
978 {
979 	int     rc;
980 
981 	/* these used by user-level raidframe only */
982 	rc = rf_create_managed_mutex(listp, &raidPtr->throughputstats.mutex);
983 	if (rc) {
984 		RF_ERRORMSG3("Unable to init mutex file %s line %d rc=%d\n", __FILE__,
985 		    __LINE__, rc);
986 		return (rc);
987 	}
988 	raidPtr->throughputstats.sum_io_us = 0;
989 	raidPtr->throughputstats.num_ios = 0;
990 	raidPtr->throughputstats.num_out_ios = 0;
991 	return (0);
992 }
993 
994 void
995 rf_StartThroughputStats(RF_Raid_t * raidPtr)
996 {
997 	RF_LOCK_MUTEX(raidPtr->throughputstats.mutex);
998 	raidPtr->throughputstats.num_ios++;
999 	raidPtr->throughputstats.num_out_ios++;
1000 	if (raidPtr->throughputstats.num_out_ios == 1)
1001 		RF_GETTIME(raidPtr->throughputstats.start);
1002 	RF_UNLOCK_MUTEX(raidPtr->throughputstats.mutex);
1003 }
1004 
1005 static void
1006 rf_StopThroughputStats(RF_Raid_t * raidPtr)
1007 {
1008 	struct timeval diff;
1009 
1010 	RF_LOCK_MUTEX(raidPtr->throughputstats.mutex);
1011 	raidPtr->throughputstats.num_out_ios--;
1012 	if (raidPtr->throughputstats.num_out_ios == 0) {
1013 		RF_GETTIME(raidPtr->throughputstats.stop);
1014 		RF_TIMEVAL_DIFF(&raidPtr->throughputstats.start, &raidPtr->throughputstats.stop, &diff);
1015 		raidPtr->throughputstats.sum_io_us += TIMEVAL_TO_US(diff);
1016 	}
1017 	RF_UNLOCK_MUTEX(raidPtr->throughputstats.mutex);
1018 }
1019 
1020 static void
1021 rf_PrintThroughputStats(RF_Raid_t * raidPtr)
1022 {
1023 	RF_ASSERT(raidPtr->throughputstats.num_out_ios == 0);
1024 	if (raidPtr->throughputstats.sum_io_us != 0) {
1025 		printf("[Througphut: %8.2f IOs/second]\n", raidPtr->throughputstats.num_ios
1026 		    / (raidPtr->throughputstats.sum_io_us / 1000000.0));
1027 	}
1028 }
1029 #endif				/* !KERNEL && !SIMULATE */
1030 
1031 void
1032 rf_StartUserStats(RF_Raid_t * raidPtr)
1033 {
1034 	RF_GETTIME(raidPtr->userstats.start);
1035 	raidPtr->userstats.sum_io_us = 0;
1036 	raidPtr->userstats.num_ios = 0;
1037 	raidPtr->userstats.num_sect_moved = 0;
1038 }
1039 
1040 void
1041 rf_StopUserStats(RF_Raid_t * raidPtr)
1042 {
1043 	RF_GETTIME(raidPtr->userstats.stop);
1044 }
1045 
1046 void
1047 rf_UpdateUserStats(raidPtr, rt, numsect)
1048 	RF_Raid_t *raidPtr;
1049 	int     rt;		/* resp time in us */
1050 	int     numsect;	/* number of sectors for this access */
1051 {
1052 	raidPtr->userstats.sum_io_us += rt;
1053 	raidPtr->userstats.num_ios++;
1054 	raidPtr->userstats.num_sect_moved += numsect;
1055 }
1056 
1057 void
1058 rf_PrintUserStats(RF_Raid_t * raidPtr)
1059 {
1060 	long    elapsed_us, mbs, mbs_frac;
1061 	struct timeval diff;
1062 
1063 	RF_TIMEVAL_DIFF(&raidPtr->userstats.start, &raidPtr->userstats.stop, &diff);
1064 	elapsed_us = TIMEVAL_TO_US(diff);
1065 
1066 	/* 2000 sectors per megabyte, 10000000 microseconds per second */
1067 	if (elapsed_us)
1068 		mbs = (raidPtr->userstats.num_sect_moved / 2000) / (elapsed_us / 1000000);
1069 	else
1070 		mbs = 0;
1071 
1072 	/* this computes only the first digit of the fractional mb/s moved */
1073 	if (elapsed_us) {
1074 		mbs_frac = ((raidPtr->userstats.num_sect_moved / 200) / (elapsed_us / 1000000))
1075 		    - (mbs * 10);
1076 	} else {
1077 		mbs_frac = 0;
1078 	}
1079 
1080 	printf("Number of I/Os:             %ld\n", raidPtr->userstats.num_ios);
1081 	printf("Elapsed time (us):          %ld\n", elapsed_us);
1082 	printf("User I/Os per second:       %ld\n", RF_DB0_CHECK(raidPtr->userstats.num_ios, (elapsed_us / 1000000)));
1083 	printf("Average user response time: %ld us\n", RF_DB0_CHECK(raidPtr->userstats.sum_io_us, raidPtr->userstats.num_ios));
1084 	printf("Total sectors moved:        %ld\n", raidPtr->userstats.num_sect_moved);
1085 	printf("Average access size (sect): %ld\n", RF_DB0_CHECK(raidPtr->userstats.num_sect_moved, raidPtr->userstats.num_ios));
1086 	printf("Achieved data rate:         %ld.%ld MB/sec\n", mbs, mbs_frac);
1087 }
1088