xref: /freebsd/sys/geom/raid/g_raid.c (revision 036d2e814bf0f5d88ffb4b24c159320894541757)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2010 Alexander Motin <mav@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/kernel.h>
35 #include <sys/module.h>
36 #include <sys/limits.h>
37 #include <sys/lock.h>
38 #include <sys/mutex.h>
39 #include <sys/bio.h>
40 #include <sys/sbuf.h>
41 #include <sys/sysctl.h>
42 #include <sys/malloc.h>
43 #include <sys/eventhandler.h>
44 #include <vm/uma.h>
45 #include <geom/geom.h>
46 #include <geom/geom_dbg.h>
47 #include <sys/proc.h>
48 #include <sys/kthread.h>
49 #include <sys/sched.h>
50 #include <geom/raid/g_raid.h>
51 #include "g_raid_md_if.h"
52 #include "g_raid_tr_if.h"
53 
54 static MALLOC_DEFINE(M_RAID, "raid_data", "GEOM_RAID Data");
55 
56 SYSCTL_DECL(_kern_geom);
57 SYSCTL_NODE(_kern_geom, OID_AUTO, raid, CTLFLAG_RW, 0, "GEOM_RAID stuff");
58 int g_raid_enable = 1;
59 SYSCTL_INT(_kern_geom_raid, OID_AUTO, enable, CTLFLAG_RWTUN,
60     &g_raid_enable, 0, "Enable on-disk metadata taste");
61 u_int g_raid_aggressive_spare = 0;
62 SYSCTL_UINT(_kern_geom_raid, OID_AUTO, aggressive_spare, CTLFLAG_RWTUN,
63     &g_raid_aggressive_spare, 0, "Use disks without metadata as spare");
64 u_int g_raid_debug = 0;
65 SYSCTL_UINT(_kern_geom_raid, OID_AUTO, debug, CTLFLAG_RWTUN, &g_raid_debug, 0,
66     "Debug level");
67 int g_raid_read_err_thresh = 10;
68 SYSCTL_UINT(_kern_geom_raid, OID_AUTO, read_err_thresh, CTLFLAG_RWTUN,
69     &g_raid_read_err_thresh, 0,
70     "Number of read errors equated to disk failure");
71 u_int g_raid_start_timeout = 30;
72 SYSCTL_UINT(_kern_geom_raid, OID_AUTO, start_timeout, CTLFLAG_RWTUN,
73     &g_raid_start_timeout, 0,
74     "Time to wait for all array components");
75 static u_int g_raid_clean_time = 5;
76 SYSCTL_UINT(_kern_geom_raid, OID_AUTO, clean_time, CTLFLAG_RWTUN,
77     &g_raid_clean_time, 0, "Mark volume as clean when idling");
78 static u_int g_raid_disconnect_on_failure = 1;
79 SYSCTL_UINT(_kern_geom_raid, OID_AUTO, disconnect_on_failure, CTLFLAG_RWTUN,
80     &g_raid_disconnect_on_failure, 0, "Disconnect component on I/O failure.");
81 static u_int g_raid_name_format = 0;
82 SYSCTL_UINT(_kern_geom_raid, OID_AUTO, name_format, CTLFLAG_RWTUN,
83     &g_raid_name_format, 0, "Providers name format.");
84 static u_int g_raid_idle_threshold = 1000000;
85 SYSCTL_UINT(_kern_geom_raid, OID_AUTO, idle_threshold, CTLFLAG_RWTUN,
86     &g_raid_idle_threshold, 1000000,
87     "Time in microseconds to consider a volume idle.");
88 
89 #define	MSLEEP(rv, ident, mtx, priority, wmesg, timeout)	do {	\
90 	G_RAID_DEBUG(4, "%s: Sleeping %p.", __func__, (ident));		\
91 	rv = msleep((ident), (mtx), (priority), (wmesg), (timeout));	\
92 	G_RAID_DEBUG(4, "%s: Woken up %p.", __func__, (ident));		\
93 } while (0)
94 
95 LIST_HEAD(, g_raid_md_class) g_raid_md_classes =
96     LIST_HEAD_INITIALIZER(g_raid_md_classes);
97 
98 LIST_HEAD(, g_raid_tr_class) g_raid_tr_classes =
99     LIST_HEAD_INITIALIZER(g_raid_tr_classes);
100 
101 LIST_HEAD(, g_raid_volume) g_raid_volumes =
102     LIST_HEAD_INITIALIZER(g_raid_volumes);
103 
104 static eventhandler_tag g_raid_post_sync = NULL;
105 static int g_raid_started = 0;
106 static int g_raid_shutdown = 0;
107 
108 static int g_raid_destroy_geom(struct gctl_req *req, struct g_class *mp,
109     struct g_geom *gp);
110 static g_taste_t g_raid_taste;
111 static void g_raid_init(struct g_class *mp);
112 static void g_raid_fini(struct g_class *mp);
113 
114 struct g_class g_raid_class = {
115 	.name = G_RAID_CLASS_NAME,
116 	.version = G_VERSION,
117 	.ctlreq = g_raid_ctl,
118 	.taste = g_raid_taste,
119 	.destroy_geom = g_raid_destroy_geom,
120 	.init = g_raid_init,
121 	.fini = g_raid_fini
122 };
123 
124 static void g_raid_destroy_provider(struct g_raid_volume *vol);
125 static int g_raid_update_disk(struct g_raid_disk *disk, u_int event);
126 static int g_raid_update_subdisk(struct g_raid_subdisk *subdisk, u_int event);
127 static int g_raid_update_volume(struct g_raid_volume *vol, u_int event);
128 static int g_raid_update_node(struct g_raid_softc *sc, u_int event);
129 static void g_raid_dumpconf(struct sbuf *sb, const char *indent,
130     struct g_geom *gp, struct g_consumer *cp, struct g_provider *pp);
131 static void g_raid_start(struct bio *bp);
132 static void g_raid_start_request(struct bio *bp);
133 static void g_raid_disk_done(struct bio *bp);
134 static void g_raid_poll(struct g_raid_softc *sc);
135 
136 static const char *
137 g_raid_node_event2str(int event)
138 {
139 
140 	switch (event) {
141 	case G_RAID_NODE_E_WAKE:
142 		return ("WAKE");
143 	case G_RAID_NODE_E_START:
144 		return ("START");
145 	default:
146 		return ("INVALID");
147 	}
148 }
149 
150 const char *
151 g_raid_disk_state2str(int state)
152 {
153 
154 	switch (state) {
155 	case G_RAID_DISK_S_NONE:
156 		return ("NONE");
157 	case G_RAID_DISK_S_OFFLINE:
158 		return ("OFFLINE");
159 	case G_RAID_DISK_S_DISABLED:
160 		return ("DISABLED");
161 	case G_RAID_DISK_S_FAILED:
162 		return ("FAILED");
163 	case G_RAID_DISK_S_STALE_FAILED:
164 		return ("STALE_FAILED");
165 	case G_RAID_DISK_S_SPARE:
166 		return ("SPARE");
167 	case G_RAID_DISK_S_STALE:
168 		return ("STALE");
169 	case G_RAID_DISK_S_ACTIVE:
170 		return ("ACTIVE");
171 	default:
172 		return ("INVALID");
173 	}
174 }
175 
176 static const char *
177 g_raid_disk_event2str(int event)
178 {
179 
180 	switch (event) {
181 	case G_RAID_DISK_E_DISCONNECTED:
182 		return ("DISCONNECTED");
183 	default:
184 		return ("INVALID");
185 	}
186 }
187 
188 const char *
189 g_raid_subdisk_state2str(int state)
190 {
191 
192 	switch (state) {
193 	case G_RAID_SUBDISK_S_NONE:
194 		return ("NONE");
195 	case G_RAID_SUBDISK_S_FAILED:
196 		return ("FAILED");
197 	case G_RAID_SUBDISK_S_NEW:
198 		return ("NEW");
199 	case G_RAID_SUBDISK_S_REBUILD:
200 		return ("REBUILD");
201 	case G_RAID_SUBDISK_S_UNINITIALIZED:
202 		return ("UNINITIALIZED");
203 	case G_RAID_SUBDISK_S_STALE:
204 		return ("STALE");
205 	case G_RAID_SUBDISK_S_RESYNC:
206 		return ("RESYNC");
207 	case G_RAID_SUBDISK_S_ACTIVE:
208 		return ("ACTIVE");
209 	default:
210 		return ("INVALID");
211 	}
212 }
213 
214 static const char *
215 g_raid_subdisk_event2str(int event)
216 {
217 
218 	switch (event) {
219 	case G_RAID_SUBDISK_E_NEW:
220 		return ("NEW");
221 	case G_RAID_SUBDISK_E_FAILED:
222 		return ("FAILED");
223 	case G_RAID_SUBDISK_E_DISCONNECTED:
224 		return ("DISCONNECTED");
225 	default:
226 		return ("INVALID");
227 	}
228 }
229 
230 const char *
231 g_raid_volume_state2str(int state)
232 {
233 
234 	switch (state) {
235 	case G_RAID_VOLUME_S_STARTING:
236 		return ("STARTING");
237 	case G_RAID_VOLUME_S_BROKEN:
238 		return ("BROKEN");
239 	case G_RAID_VOLUME_S_DEGRADED:
240 		return ("DEGRADED");
241 	case G_RAID_VOLUME_S_SUBOPTIMAL:
242 		return ("SUBOPTIMAL");
243 	case G_RAID_VOLUME_S_OPTIMAL:
244 		return ("OPTIMAL");
245 	case G_RAID_VOLUME_S_UNSUPPORTED:
246 		return ("UNSUPPORTED");
247 	case G_RAID_VOLUME_S_STOPPED:
248 		return ("STOPPED");
249 	default:
250 		return ("INVALID");
251 	}
252 }
253 
254 static const char *
255 g_raid_volume_event2str(int event)
256 {
257 
258 	switch (event) {
259 	case G_RAID_VOLUME_E_UP:
260 		return ("UP");
261 	case G_RAID_VOLUME_E_DOWN:
262 		return ("DOWN");
263 	case G_RAID_VOLUME_E_START:
264 		return ("START");
265 	case G_RAID_VOLUME_E_STARTMD:
266 		return ("STARTMD");
267 	default:
268 		return ("INVALID");
269 	}
270 }
271 
272 const char *
273 g_raid_volume_level2str(int level, int qual)
274 {
275 
276 	switch (level) {
277 	case G_RAID_VOLUME_RL_RAID0:
278 		return ("RAID0");
279 	case G_RAID_VOLUME_RL_RAID1:
280 		return ("RAID1");
281 	case G_RAID_VOLUME_RL_RAID3:
282 		if (qual == G_RAID_VOLUME_RLQ_R3P0)
283 			return ("RAID3-P0");
284 		if (qual == G_RAID_VOLUME_RLQ_R3PN)
285 			return ("RAID3-PN");
286 		return ("RAID3");
287 	case G_RAID_VOLUME_RL_RAID4:
288 		if (qual == G_RAID_VOLUME_RLQ_R4P0)
289 			return ("RAID4-P0");
290 		if (qual == G_RAID_VOLUME_RLQ_R4PN)
291 			return ("RAID4-PN");
292 		return ("RAID4");
293 	case G_RAID_VOLUME_RL_RAID5:
294 		if (qual == G_RAID_VOLUME_RLQ_R5RA)
295 			return ("RAID5-RA");
296 		if (qual == G_RAID_VOLUME_RLQ_R5RS)
297 			return ("RAID5-RS");
298 		if (qual == G_RAID_VOLUME_RLQ_R5LA)
299 			return ("RAID5-LA");
300 		if (qual == G_RAID_VOLUME_RLQ_R5LS)
301 			return ("RAID5-LS");
302 		return ("RAID5");
303 	case G_RAID_VOLUME_RL_RAID6:
304 		if (qual == G_RAID_VOLUME_RLQ_R6RA)
305 			return ("RAID6-RA");
306 		if (qual == G_RAID_VOLUME_RLQ_R6RS)
307 			return ("RAID6-RS");
308 		if (qual == G_RAID_VOLUME_RLQ_R6LA)
309 			return ("RAID6-LA");
310 		if (qual == G_RAID_VOLUME_RLQ_R6LS)
311 			return ("RAID6-LS");
312 		return ("RAID6");
313 	case G_RAID_VOLUME_RL_RAIDMDF:
314 		if (qual == G_RAID_VOLUME_RLQ_RMDFRA)
315 			return ("RAIDMDF-RA");
316 		if (qual == G_RAID_VOLUME_RLQ_RMDFRS)
317 			return ("RAIDMDF-RS");
318 		if (qual == G_RAID_VOLUME_RLQ_RMDFLA)
319 			return ("RAIDMDF-LA");
320 		if (qual == G_RAID_VOLUME_RLQ_RMDFLS)
321 			return ("RAIDMDF-LS");
322 		return ("RAIDMDF");
323 	case G_RAID_VOLUME_RL_RAID1E:
324 		if (qual == G_RAID_VOLUME_RLQ_R1EA)
325 			return ("RAID1E-A");
326 		if (qual == G_RAID_VOLUME_RLQ_R1EO)
327 			return ("RAID1E-O");
328 		return ("RAID1E");
329 	case G_RAID_VOLUME_RL_SINGLE:
330 		return ("SINGLE");
331 	case G_RAID_VOLUME_RL_CONCAT:
332 		return ("CONCAT");
333 	case G_RAID_VOLUME_RL_RAID5E:
334 		if (qual == G_RAID_VOLUME_RLQ_R5ERA)
335 			return ("RAID5E-RA");
336 		if (qual == G_RAID_VOLUME_RLQ_R5ERS)
337 			return ("RAID5E-RS");
338 		if (qual == G_RAID_VOLUME_RLQ_R5ELA)
339 			return ("RAID5E-LA");
340 		if (qual == G_RAID_VOLUME_RLQ_R5ELS)
341 			return ("RAID5E-LS");
342 		return ("RAID5E");
343 	case G_RAID_VOLUME_RL_RAID5EE:
344 		if (qual == G_RAID_VOLUME_RLQ_R5EERA)
345 			return ("RAID5EE-RA");
346 		if (qual == G_RAID_VOLUME_RLQ_R5EERS)
347 			return ("RAID5EE-RS");
348 		if (qual == G_RAID_VOLUME_RLQ_R5EELA)
349 			return ("RAID5EE-LA");
350 		if (qual == G_RAID_VOLUME_RLQ_R5EELS)
351 			return ("RAID5EE-LS");
352 		return ("RAID5EE");
353 	case G_RAID_VOLUME_RL_RAID5R:
354 		if (qual == G_RAID_VOLUME_RLQ_R5RRA)
355 			return ("RAID5R-RA");
356 		if (qual == G_RAID_VOLUME_RLQ_R5RRS)
357 			return ("RAID5R-RS");
358 		if (qual == G_RAID_VOLUME_RLQ_R5RLA)
359 			return ("RAID5R-LA");
360 		if (qual == G_RAID_VOLUME_RLQ_R5RLS)
361 			return ("RAID5R-LS");
362 		return ("RAID5E");
363 	default:
364 		return ("UNKNOWN");
365 	}
366 }
367 
368 int
369 g_raid_volume_str2level(const char *str, int *level, int *qual)
370 {
371 
372 	*level = G_RAID_VOLUME_RL_UNKNOWN;
373 	*qual = G_RAID_VOLUME_RLQ_NONE;
374 	if (strcasecmp(str, "RAID0") == 0)
375 		*level = G_RAID_VOLUME_RL_RAID0;
376 	else if (strcasecmp(str, "RAID1") == 0)
377 		*level = G_RAID_VOLUME_RL_RAID1;
378 	else if (strcasecmp(str, "RAID3-P0") == 0) {
379 		*level = G_RAID_VOLUME_RL_RAID3;
380 		*qual = G_RAID_VOLUME_RLQ_R3P0;
381 	} else if (strcasecmp(str, "RAID3-PN") == 0 ||
382 		   strcasecmp(str, "RAID3") == 0) {
383 		*level = G_RAID_VOLUME_RL_RAID3;
384 		*qual = G_RAID_VOLUME_RLQ_R3PN;
385 	} else if (strcasecmp(str, "RAID4-P0") == 0) {
386 		*level = G_RAID_VOLUME_RL_RAID4;
387 		*qual = G_RAID_VOLUME_RLQ_R4P0;
388 	} else if (strcasecmp(str, "RAID4-PN") == 0 ||
389 		   strcasecmp(str, "RAID4") == 0) {
390 		*level = G_RAID_VOLUME_RL_RAID4;
391 		*qual = G_RAID_VOLUME_RLQ_R4PN;
392 	} else if (strcasecmp(str, "RAID5-RA") == 0) {
393 		*level = G_RAID_VOLUME_RL_RAID5;
394 		*qual = G_RAID_VOLUME_RLQ_R5RA;
395 	} else if (strcasecmp(str, "RAID5-RS") == 0) {
396 		*level = G_RAID_VOLUME_RL_RAID5;
397 		*qual = G_RAID_VOLUME_RLQ_R5RS;
398 	} else if (strcasecmp(str, "RAID5") == 0 ||
399 		   strcasecmp(str, "RAID5-LA") == 0) {
400 		*level = G_RAID_VOLUME_RL_RAID5;
401 		*qual = G_RAID_VOLUME_RLQ_R5LA;
402 	} else if (strcasecmp(str, "RAID5-LS") == 0) {
403 		*level = G_RAID_VOLUME_RL_RAID5;
404 		*qual = G_RAID_VOLUME_RLQ_R5LS;
405 	} else if (strcasecmp(str, "RAID6-RA") == 0) {
406 		*level = G_RAID_VOLUME_RL_RAID6;
407 		*qual = G_RAID_VOLUME_RLQ_R6RA;
408 	} else if (strcasecmp(str, "RAID6-RS") == 0) {
409 		*level = G_RAID_VOLUME_RL_RAID6;
410 		*qual = G_RAID_VOLUME_RLQ_R6RS;
411 	} else if (strcasecmp(str, "RAID6") == 0 ||
412 		   strcasecmp(str, "RAID6-LA") == 0) {
413 		*level = G_RAID_VOLUME_RL_RAID6;
414 		*qual = G_RAID_VOLUME_RLQ_R6LA;
415 	} else if (strcasecmp(str, "RAID6-LS") == 0) {
416 		*level = G_RAID_VOLUME_RL_RAID6;
417 		*qual = G_RAID_VOLUME_RLQ_R6LS;
418 	} else if (strcasecmp(str, "RAIDMDF-RA") == 0) {
419 		*level = G_RAID_VOLUME_RL_RAIDMDF;
420 		*qual = G_RAID_VOLUME_RLQ_RMDFRA;
421 	} else if (strcasecmp(str, "RAIDMDF-RS") == 0) {
422 		*level = G_RAID_VOLUME_RL_RAIDMDF;
423 		*qual = G_RAID_VOLUME_RLQ_RMDFRS;
424 	} else if (strcasecmp(str, "RAIDMDF") == 0 ||
425 		   strcasecmp(str, "RAIDMDF-LA") == 0) {
426 		*level = G_RAID_VOLUME_RL_RAIDMDF;
427 		*qual = G_RAID_VOLUME_RLQ_RMDFLA;
428 	} else if (strcasecmp(str, "RAIDMDF-LS") == 0) {
429 		*level = G_RAID_VOLUME_RL_RAIDMDF;
430 		*qual = G_RAID_VOLUME_RLQ_RMDFLS;
431 	} else if (strcasecmp(str, "RAID10") == 0 ||
432 		   strcasecmp(str, "RAID1E") == 0 ||
433 		   strcasecmp(str, "RAID1E-A") == 0) {
434 		*level = G_RAID_VOLUME_RL_RAID1E;
435 		*qual = G_RAID_VOLUME_RLQ_R1EA;
436 	} else if (strcasecmp(str, "RAID1E-O") == 0) {
437 		*level = G_RAID_VOLUME_RL_RAID1E;
438 		*qual = G_RAID_VOLUME_RLQ_R1EO;
439 	} else if (strcasecmp(str, "SINGLE") == 0)
440 		*level = G_RAID_VOLUME_RL_SINGLE;
441 	else if (strcasecmp(str, "CONCAT") == 0)
442 		*level = G_RAID_VOLUME_RL_CONCAT;
443 	else if (strcasecmp(str, "RAID5E-RA") == 0) {
444 		*level = G_RAID_VOLUME_RL_RAID5E;
445 		*qual = G_RAID_VOLUME_RLQ_R5ERA;
446 	} else if (strcasecmp(str, "RAID5E-RS") == 0) {
447 		*level = G_RAID_VOLUME_RL_RAID5E;
448 		*qual = G_RAID_VOLUME_RLQ_R5ERS;
449 	} else if (strcasecmp(str, "RAID5E") == 0 ||
450 		   strcasecmp(str, "RAID5E-LA") == 0) {
451 		*level = G_RAID_VOLUME_RL_RAID5E;
452 		*qual = G_RAID_VOLUME_RLQ_R5ELA;
453 	} else if (strcasecmp(str, "RAID5E-LS") == 0) {
454 		*level = G_RAID_VOLUME_RL_RAID5E;
455 		*qual = G_RAID_VOLUME_RLQ_R5ELS;
456 	} else if (strcasecmp(str, "RAID5EE-RA") == 0) {
457 		*level = G_RAID_VOLUME_RL_RAID5EE;
458 		*qual = G_RAID_VOLUME_RLQ_R5EERA;
459 	} else if (strcasecmp(str, "RAID5EE-RS") == 0) {
460 		*level = G_RAID_VOLUME_RL_RAID5EE;
461 		*qual = G_RAID_VOLUME_RLQ_R5EERS;
462 	} else if (strcasecmp(str, "RAID5EE") == 0 ||
463 		   strcasecmp(str, "RAID5EE-LA") == 0) {
464 		*level = G_RAID_VOLUME_RL_RAID5EE;
465 		*qual = G_RAID_VOLUME_RLQ_R5EELA;
466 	} else if (strcasecmp(str, "RAID5EE-LS") == 0) {
467 		*level = G_RAID_VOLUME_RL_RAID5EE;
468 		*qual = G_RAID_VOLUME_RLQ_R5EELS;
469 	} else if (strcasecmp(str, "RAID5R-RA") == 0) {
470 		*level = G_RAID_VOLUME_RL_RAID5R;
471 		*qual = G_RAID_VOLUME_RLQ_R5RRA;
472 	} else if (strcasecmp(str, "RAID5R-RS") == 0) {
473 		*level = G_RAID_VOLUME_RL_RAID5R;
474 		*qual = G_RAID_VOLUME_RLQ_R5RRS;
475 	} else if (strcasecmp(str, "RAID5R") == 0 ||
476 		   strcasecmp(str, "RAID5R-LA") == 0) {
477 		*level = G_RAID_VOLUME_RL_RAID5R;
478 		*qual = G_RAID_VOLUME_RLQ_R5RLA;
479 	} else if (strcasecmp(str, "RAID5R-LS") == 0) {
480 		*level = G_RAID_VOLUME_RL_RAID5R;
481 		*qual = G_RAID_VOLUME_RLQ_R5RLS;
482 	} else
483 		return (-1);
484 	return (0);
485 }
486 
487 const char *
488 g_raid_get_diskname(struct g_raid_disk *disk)
489 {
490 
491 	if (disk->d_consumer == NULL || disk->d_consumer->provider == NULL)
492 		return ("[unknown]");
493 	return (disk->d_consumer->provider->name);
494 }
495 
496 void
497 g_raid_get_disk_info(struct g_raid_disk *disk)
498 {
499 	struct g_consumer *cp = disk->d_consumer;
500 	int error, len;
501 
502 	/* Read kernel dumping information. */
503 	disk->d_kd.offset = 0;
504 	disk->d_kd.length = OFF_MAX;
505 	len = sizeof(disk->d_kd);
506 	error = g_io_getattr("GEOM::kerneldump", cp, &len, &disk->d_kd);
507 	if (error)
508 		disk->d_kd.di.dumper = NULL;
509 	if (disk->d_kd.di.dumper == NULL)
510 		G_RAID_DEBUG1(2, disk->d_softc,
511 		    "Dumping not supported by %s: %d.",
512 		    cp->provider->name, error);
513 
514 	/* Read BIO_DELETE support. */
515 	error = g_getattr("GEOM::candelete", cp, &disk->d_candelete);
516 	if (error)
517 		disk->d_candelete = 0;
518 	if (!disk->d_candelete)
519 		G_RAID_DEBUG1(2, disk->d_softc,
520 		    "BIO_DELETE not supported by %s: %d.",
521 		    cp->provider->name, error);
522 }
523 
524 void
525 g_raid_report_disk_state(struct g_raid_disk *disk)
526 {
527 	struct g_raid_subdisk *sd;
528 	int len, state;
529 	uint32_t s;
530 
531 	if (disk->d_consumer == NULL)
532 		return;
533 	if (disk->d_state == G_RAID_DISK_S_DISABLED) {
534 		s = G_STATE_ACTIVE; /* XXX */
535 	} else if (disk->d_state == G_RAID_DISK_S_FAILED ||
536 	    disk->d_state == G_RAID_DISK_S_STALE_FAILED) {
537 		s = G_STATE_FAILED;
538 	} else {
539 		state = G_RAID_SUBDISK_S_ACTIVE;
540 		TAILQ_FOREACH(sd, &disk->d_subdisks, sd_next) {
541 			if (sd->sd_state < state)
542 				state = sd->sd_state;
543 		}
544 		if (state == G_RAID_SUBDISK_S_FAILED)
545 			s = G_STATE_FAILED;
546 		else if (state == G_RAID_SUBDISK_S_NEW ||
547 		    state == G_RAID_SUBDISK_S_REBUILD)
548 			s = G_STATE_REBUILD;
549 		else if (state == G_RAID_SUBDISK_S_STALE ||
550 		    state == G_RAID_SUBDISK_S_RESYNC)
551 			s = G_STATE_RESYNC;
552 		else
553 			s = G_STATE_ACTIVE;
554 	}
555 	len = sizeof(s);
556 	g_io_getattr("GEOM::setstate", disk->d_consumer, &len, &s);
557 	G_RAID_DEBUG1(2, disk->d_softc, "Disk %s state reported as %d.",
558 	    g_raid_get_diskname(disk), s);
559 }
560 
561 void
562 g_raid_change_disk_state(struct g_raid_disk *disk, int state)
563 {
564 
565 	G_RAID_DEBUG1(0, disk->d_softc, "Disk %s state changed from %s to %s.",
566 	    g_raid_get_diskname(disk),
567 	    g_raid_disk_state2str(disk->d_state),
568 	    g_raid_disk_state2str(state));
569 	disk->d_state = state;
570 	g_raid_report_disk_state(disk);
571 }
572 
573 void
574 g_raid_change_subdisk_state(struct g_raid_subdisk *sd, int state)
575 {
576 
577 	G_RAID_DEBUG1(0, sd->sd_softc,
578 	    "Subdisk %s:%d-%s state changed from %s to %s.",
579 	    sd->sd_volume->v_name, sd->sd_pos,
580 	    sd->sd_disk ? g_raid_get_diskname(sd->sd_disk) : "[none]",
581 	    g_raid_subdisk_state2str(sd->sd_state),
582 	    g_raid_subdisk_state2str(state));
583 	sd->sd_state = state;
584 	if (sd->sd_disk)
585 		g_raid_report_disk_state(sd->sd_disk);
586 }
587 
588 void
589 g_raid_change_volume_state(struct g_raid_volume *vol, int state)
590 {
591 
592 	G_RAID_DEBUG1(0, vol->v_softc,
593 	    "Volume %s state changed from %s to %s.",
594 	    vol->v_name,
595 	    g_raid_volume_state2str(vol->v_state),
596 	    g_raid_volume_state2str(state));
597 	vol->v_state = state;
598 }
599 
600 /*
601  * --- Events handling functions ---
602  * Events in geom_raid are used to maintain subdisks and volumes status
603  * from one thread to simplify locking.
604  */
605 static void
606 g_raid_event_free(struct g_raid_event *ep)
607 {
608 
609 	free(ep, M_RAID);
610 }
611 
612 int
613 g_raid_event_send(void *arg, int event, int flags)
614 {
615 	struct g_raid_softc *sc;
616 	struct g_raid_event *ep;
617 	int error;
618 
619 	if ((flags & G_RAID_EVENT_VOLUME) != 0) {
620 		sc = ((struct g_raid_volume *)arg)->v_softc;
621 	} else if ((flags & G_RAID_EVENT_DISK) != 0) {
622 		sc = ((struct g_raid_disk *)arg)->d_softc;
623 	} else if ((flags & G_RAID_EVENT_SUBDISK) != 0) {
624 		sc = ((struct g_raid_subdisk *)arg)->sd_softc;
625 	} else {
626 		sc = arg;
627 	}
628 	ep = malloc(sizeof(*ep), M_RAID,
629 	    sx_xlocked(&sc->sc_lock) ? M_WAITOK : M_NOWAIT);
630 	if (ep == NULL)
631 		return (ENOMEM);
632 	ep->e_tgt = arg;
633 	ep->e_event = event;
634 	ep->e_flags = flags;
635 	ep->e_error = 0;
636 	G_RAID_DEBUG1(4, sc, "Sending event %p. Waking up %p.", ep, sc);
637 	mtx_lock(&sc->sc_queue_mtx);
638 	TAILQ_INSERT_TAIL(&sc->sc_events, ep, e_next);
639 	mtx_unlock(&sc->sc_queue_mtx);
640 	wakeup(sc);
641 
642 	if ((flags & G_RAID_EVENT_WAIT) == 0)
643 		return (0);
644 
645 	sx_assert(&sc->sc_lock, SX_XLOCKED);
646 	G_RAID_DEBUG1(4, sc, "Sleeping on %p.", ep);
647 	sx_xunlock(&sc->sc_lock);
648 	while ((ep->e_flags & G_RAID_EVENT_DONE) == 0) {
649 		mtx_lock(&sc->sc_queue_mtx);
650 		MSLEEP(error, ep, &sc->sc_queue_mtx, PRIBIO | PDROP, "m:event",
651 		    hz * 5);
652 	}
653 	error = ep->e_error;
654 	g_raid_event_free(ep);
655 	sx_xlock(&sc->sc_lock);
656 	return (error);
657 }
658 
659 static void
660 g_raid_event_cancel(struct g_raid_softc *sc, void *tgt)
661 {
662 	struct g_raid_event *ep, *tmpep;
663 
664 	sx_assert(&sc->sc_lock, SX_XLOCKED);
665 
666 	mtx_lock(&sc->sc_queue_mtx);
667 	TAILQ_FOREACH_SAFE(ep, &sc->sc_events, e_next, tmpep) {
668 		if (ep->e_tgt != tgt)
669 			continue;
670 		TAILQ_REMOVE(&sc->sc_events, ep, e_next);
671 		if ((ep->e_flags & G_RAID_EVENT_WAIT) == 0)
672 			g_raid_event_free(ep);
673 		else {
674 			ep->e_error = ECANCELED;
675 			wakeup(ep);
676 		}
677 	}
678 	mtx_unlock(&sc->sc_queue_mtx);
679 }
680 
681 static int
682 g_raid_event_check(struct g_raid_softc *sc, void *tgt)
683 {
684 	struct g_raid_event *ep;
685 	int	res = 0;
686 
687 	sx_assert(&sc->sc_lock, SX_XLOCKED);
688 
689 	mtx_lock(&sc->sc_queue_mtx);
690 	TAILQ_FOREACH(ep, &sc->sc_events, e_next) {
691 		if (ep->e_tgt != tgt)
692 			continue;
693 		res = 1;
694 		break;
695 	}
696 	mtx_unlock(&sc->sc_queue_mtx);
697 	return (res);
698 }
699 
700 /*
701  * Return the number of disks in given state.
702  * If state is equal to -1, count all connected disks.
703  */
704 u_int
705 g_raid_ndisks(struct g_raid_softc *sc, int state)
706 {
707 	struct g_raid_disk *disk;
708 	u_int n;
709 
710 	sx_assert(&sc->sc_lock, SX_LOCKED);
711 
712 	n = 0;
713 	TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
714 		if (disk->d_state == state || state == -1)
715 			n++;
716 	}
717 	return (n);
718 }
719 
720 /*
721  * Return the number of subdisks in given state.
722  * If state is equal to -1, count all connected disks.
723  */
724 u_int
725 g_raid_nsubdisks(struct g_raid_volume *vol, int state)
726 {
727 	struct g_raid_subdisk *subdisk;
728 	struct g_raid_softc *sc;
729 	u_int i, n ;
730 
731 	sc = vol->v_softc;
732 	sx_assert(&sc->sc_lock, SX_LOCKED);
733 
734 	n = 0;
735 	for (i = 0; i < vol->v_disks_count; i++) {
736 		subdisk = &vol->v_subdisks[i];
737 		if ((state == -1 &&
738 		     subdisk->sd_state != G_RAID_SUBDISK_S_NONE) ||
739 		    subdisk->sd_state == state)
740 			n++;
741 	}
742 	return (n);
743 }
744 
745 /*
746  * Return the first subdisk in given state.
747  * If state is equal to -1, then the first connected disks.
748  */
749 struct g_raid_subdisk *
750 g_raid_get_subdisk(struct g_raid_volume *vol, int state)
751 {
752 	struct g_raid_subdisk *sd;
753 	struct g_raid_softc *sc;
754 	u_int i;
755 
756 	sc = vol->v_softc;
757 	sx_assert(&sc->sc_lock, SX_LOCKED);
758 
759 	for (i = 0; i < vol->v_disks_count; i++) {
760 		sd = &vol->v_subdisks[i];
761 		if ((state == -1 &&
762 		     sd->sd_state != G_RAID_SUBDISK_S_NONE) ||
763 		    sd->sd_state == state)
764 			return (sd);
765 	}
766 	return (NULL);
767 }
768 
769 struct g_consumer *
770 g_raid_open_consumer(struct g_raid_softc *sc, const char *name)
771 {
772 	struct g_consumer *cp;
773 	struct g_provider *pp;
774 
775 	g_topology_assert();
776 
777 	if (strncmp(name, "/dev/", 5) == 0)
778 		name += 5;
779 	pp = g_provider_by_name(name);
780 	if (pp == NULL)
781 		return (NULL);
782 	cp = g_new_consumer(sc->sc_geom);
783 	cp->flags |= G_CF_DIRECT_RECEIVE;
784 	if (g_attach(cp, pp) != 0) {
785 		g_destroy_consumer(cp);
786 		return (NULL);
787 	}
788 	if (g_access(cp, 1, 1, 1) != 0) {
789 		g_detach(cp);
790 		g_destroy_consumer(cp);
791 		return (NULL);
792 	}
793 	return (cp);
794 }
795 
796 static u_int
797 g_raid_nrequests(struct g_raid_softc *sc, struct g_consumer *cp)
798 {
799 	struct bio *bp;
800 	u_int nreqs = 0;
801 
802 	mtx_lock(&sc->sc_queue_mtx);
803 	TAILQ_FOREACH(bp, &sc->sc_queue.queue, bio_queue) {
804 		if (bp->bio_from == cp)
805 			nreqs++;
806 	}
807 	mtx_unlock(&sc->sc_queue_mtx);
808 	return (nreqs);
809 }
810 
811 u_int
812 g_raid_nopens(struct g_raid_softc *sc)
813 {
814 	struct g_raid_volume *vol;
815 	u_int opens;
816 
817 	opens = 0;
818 	TAILQ_FOREACH(vol, &sc->sc_volumes, v_next) {
819 		if (vol->v_provider_open != 0)
820 			opens++;
821 	}
822 	return (opens);
823 }
824 
825 static int
826 g_raid_consumer_is_busy(struct g_raid_softc *sc, struct g_consumer *cp)
827 {
828 
829 	if (cp->index > 0) {
830 		G_RAID_DEBUG1(2, sc,
831 		    "I/O requests for %s exist, can't destroy it now.",
832 		    cp->provider->name);
833 		return (1);
834 	}
835 	if (g_raid_nrequests(sc, cp) > 0) {
836 		G_RAID_DEBUG1(2, sc,
837 		    "I/O requests for %s in queue, can't destroy it now.",
838 		    cp->provider->name);
839 		return (1);
840 	}
841 	return (0);
842 }
843 
844 static void
845 g_raid_destroy_consumer(void *arg, int flags __unused)
846 {
847 	struct g_consumer *cp;
848 
849 	g_topology_assert();
850 
851 	cp = arg;
852 	G_RAID_DEBUG(1, "Consumer %s destroyed.", cp->provider->name);
853 	g_detach(cp);
854 	g_destroy_consumer(cp);
855 }
856 
857 void
858 g_raid_kill_consumer(struct g_raid_softc *sc, struct g_consumer *cp)
859 {
860 	struct g_provider *pp;
861 	int retaste_wait;
862 
863 	g_topology_assert_not();
864 
865 	g_topology_lock();
866 	cp->private = NULL;
867 	if (g_raid_consumer_is_busy(sc, cp))
868 		goto out;
869 	pp = cp->provider;
870 	retaste_wait = 0;
871 	if (cp->acw == 1) {
872 		if ((pp->geom->flags & G_GEOM_WITHER) == 0)
873 			retaste_wait = 1;
874 	}
875 	if (cp->acr > 0 || cp->acw > 0 || cp->ace > 0)
876 		g_access(cp, -cp->acr, -cp->acw, -cp->ace);
877 	if (retaste_wait) {
878 		/*
879 		 * After retaste event was send (inside g_access()), we can send
880 		 * event to detach and destroy consumer.
881 		 * A class, which has consumer to the given provider connected
882 		 * will not receive retaste event for the provider.
883 		 * This is the way how I ignore retaste events when I close
884 		 * consumers opened for write: I detach and destroy consumer
885 		 * after retaste event is sent.
886 		 */
887 		g_post_event(g_raid_destroy_consumer, cp, M_WAITOK, NULL);
888 		goto out;
889 	}
890 	G_RAID_DEBUG(1, "Consumer %s destroyed.", pp->name);
891 	g_detach(cp);
892 	g_destroy_consumer(cp);
893 out:
894 	g_topology_unlock();
895 }
896 
897 static void
898 g_raid_orphan(struct g_consumer *cp)
899 {
900 	struct g_raid_disk *disk;
901 
902 	g_topology_assert();
903 
904 	disk = cp->private;
905 	if (disk == NULL)
906 		return;
907 	g_raid_event_send(disk, G_RAID_DISK_E_DISCONNECTED,
908 	    G_RAID_EVENT_DISK);
909 }
910 
911 static void
912 g_raid_clean(struct g_raid_volume *vol, int acw)
913 {
914 	struct g_raid_softc *sc;
915 	int timeout;
916 
917 	sc = vol->v_softc;
918 	g_topology_assert_not();
919 	sx_assert(&sc->sc_lock, SX_XLOCKED);
920 
921 //	if ((sc->sc_flags & G_RAID_DEVICE_FLAG_NOFAILSYNC) != 0)
922 //		return;
923 	if (!vol->v_dirty)
924 		return;
925 	if (vol->v_writes > 0)
926 		return;
927 	if (acw > 0 || (acw == -1 &&
928 	    vol->v_provider != NULL && vol->v_provider->acw > 0)) {
929 		timeout = g_raid_clean_time - (time_uptime - vol->v_last_write);
930 		if (!g_raid_shutdown && timeout > 0)
931 			return;
932 	}
933 	vol->v_dirty = 0;
934 	G_RAID_DEBUG1(1, sc, "Volume %s marked as clean.",
935 	    vol->v_name);
936 	g_raid_write_metadata(sc, vol, NULL, NULL);
937 }
938 
939 static void
940 g_raid_dirty(struct g_raid_volume *vol)
941 {
942 	struct g_raid_softc *sc;
943 
944 	sc = vol->v_softc;
945 	g_topology_assert_not();
946 	sx_assert(&sc->sc_lock, SX_XLOCKED);
947 
948 //	if ((sc->sc_flags & G_RAID_DEVICE_FLAG_NOFAILSYNC) != 0)
949 //		return;
950 	vol->v_dirty = 1;
951 	G_RAID_DEBUG1(1, sc, "Volume %s marked as dirty.",
952 	    vol->v_name);
953 	g_raid_write_metadata(sc, vol, NULL, NULL);
954 }
955 
956 void
957 g_raid_tr_flush_common(struct g_raid_tr_object *tr, struct bio *bp)
958 {
959 	struct g_raid_volume *vol;
960 	struct g_raid_subdisk *sd;
961 	struct bio_queue_head queue;
962 	struct bio *cbp;
963 	int i;
964 
965 	vol = tr->tro_volume;
966 
967 	/*
968 	 * Allocate all bios before sending any request, so we can return
969 	 * ENOMEM in nice and clean way.
970 	 */
971 	bioq_init(&queue);
972 	for (i = 0; i < vol->v_disks_count; i++) {
973 		sd = &vol->v_subdisks[i];
974 		if (sd->sd_state == G_RAID_SUBDISK_S_NONE ||
975 		    sd->sd_state == G_RAID_SUBDISK_S_FAILED)
976 			continue;
977 		cbp = g_clone_bio(bp);
978 		if (cbp == NULL)
979 			goto failure;
980 		cbp->bio_caller1 = sd;
981 		bioq_insert_tail(&queue, cbp);
982 	}
983 	while ((cbp = bioq_takefirst(&queue)) != NULL) {
984 		sd = cbp->bio_caller1;
985 		cbp->bio_caller1 = NULL;
986 		g_raid_subdisk_iostart(sd, cbp);
987 	}
988 	return;
989 failure:
990 	while ((cbp = bioq_takefirst(&queue)) != NULL)
991 		g_destroy_bio(cbp);
992 	if (bp->bio_error == 0)
993 		bp->bio_error = ENOMEM;
994 	g_raid_iodone(bp, bp->bio_error);
995 }
996 
997 static void
998 g_raid_tr_kerneldump_common_done(struct bio *bp)
999 {
1000 
1001 	bp->bio_flags |= BIO_DONE;
1002 }
1003 
1004 int
1005 g_raid_tr_kerneldump_common(struct g_raid_tr_object *tr,
1006     void *virtual, vm_offset_t physical, off_t offset, size_t length)
1007 {
1008 	struct g_raid_softc *sc;
1009 	struct g_raid_volume *vol;
1010 	struct bio bp;
1011 
1012 	vol = tr->tro_volume;
1013 	sc = vol->v_softc;
1014 
1015 	g_reset_bio(&bp);
1016 	bp.bio_cmd = BIO_WRITE;
1017 	bp.bio_done = g_raid_tr_kerneldump_common_done;
1018 	bp.bio_attribute = NULL;
1019 	bp.bio_offset = offset;
1020 	bp.bio_length = length;
1021 	bp.bio_data = virtual;
1022 	bp.bio_to = vol->v_provider;
1023 
1024 	g_raid_start(&bp);
1025 	while (!(bp.bio_flags & BIO_DONE)) {
1026 		G_RAID_DEBUG1(4, sc, "Poll...");
1027 		g_raid_poll(sc);
1028 		DELAY(10);
1029 	}
1030 
1031 	return (bp.bio_error != 0 ? EIO : 0);
1032 }
1033 
1034 static int
1035 g_raid_dump(void *arg,
1036     void *virtual, vm_offset_t physical, off_t offset, size_t length)
1037 {
1038 	struct g_raid_volume *vol;
1039 	int error;
1040 
1041 	vol = (struct g_raid_volume *)arg;
1042 	G_RAID_DEBUG1(3, vol->v_softc, "Dumping at off %llu len %llu.",
1043 	    (long long unsigned)offset, (long long unsigned)length);
1044 
1045 	error = G_RAID_TR_KERNELDUMP(vol->v_tr,
1046 	    virtual, physical, offset, length);
1047 	return (error);
1048 }
1049 
1050 static void
1051 g_raid_kerneldump(struct g_raid_softc *sc, struct bio *bp)
1052 {
1053 	struct g_kerneldump *gkd;
1054 	struct g_provider *pp;
1055 	struct g_raid_volume *vol;
1056 
1057 	gkd = (struct g_kerneldump*)bp->bio_data;
1058 	pp = bp->bio_to;
1059 	vol = pp->private;
1060 	g_trace(G_T_TOPOLOGY, "g_raid_kerneldump(%s, %jd, %jd)",
1061 		pp->name, (intmax_t)gkd->offset, (intmax_t)gkd->length);
1062 	gkd->di.dumper = g_raid_dump;
1063 	gkd->di.priv = vol;
1064 	gkd->di.blocksize = vol->v_sectorsize;
1065 	gkd->di.maxiosize = DFLTPHYS;
1066 	gkd->di.mediaoffset = gkd->offset;
1067 	if ((gkd->offset + gkd->length) > vol->v_mediasize)
1068 		gkd->length = vol->v_mediasize - gkd->offset;
1069 	gkd->di.mediasize = gkd->length;
1070 	g_io_deliver(bp, 0);
1071 }
1072 
1073 static void
1074 g_raid_candelete(struct g_raid_softc *sc, struct bio *bp)
1075 {
1076 	struct g_provider *pp;
1077 	struct g_raid_volume *vol;
1078 	struct g_raid_subdisk *sd;
1079 	int i, val;
1080 
1081 	pp = bp->bio_to;
1082 	vol = pp->private;
1083 	for (i = 0; i < vol->v_disks_count; i++) {
1084 		sd = &vol->v_subdisks[i];
1085 		if (sd->sd_state == G_RAID_SUBDISK_S_NONE)
1086 			continue;
1087 		if (sd->sd_disk->d_candelete)
1088 			break;
1089 	}
1090 	val = i < vol->v_disks_count;
1091 	g_handleattr(bp, "GEOM::candelete", &val, sizeof(val));
1092 }
1093 
1094 static void
1095 g_raid_start(struct bio *bp)
1096 {
1097 	struct g_raid_softc *sc;
1098 
1099 	sc = bp->bio_to->geom->softc;
1100 	/*
1101 	 * If sc == NULL or there are no valid disks, provider's error
1102 	 * should be set and g_raid_start() should not be called at all.
1103 	 */
1104 //	KASSERT(sc != NULL && sc->sc_state == G_RAID_VOLUME_S_RUNNING,
1105 //	    ("Provider's error should be set (error=%d)(mirror=%s).",
1106 //	    bp->bio_to->error, bp->bio_to->name));
1107 	G_RAID_LOGREQ(3, bp, "Request received.");
1108 
1109 	switch (bp->bio_cmd) {
1110 	case BIO_READ:
1111 	case BIO_WRITE:
1112 	case BIO_DELETE:
1113 	case BIO_FLUSH:
1114 		break;
1115 	case BIO_GETATTR:
1116 		if (!strcmp(bp->bio_attribute, "GEOM::candelete"))
1117 			g_raid_candelete(sc, bp);
1118 		else if (!strcmp(bp->bio_attribute, "GEOM::kerneldump"))
1119 			g_raid_kerneldump(sc, bp);
1120 		else
1121 			g_io_deliver(bp, EOPNOTSUPP);
1122 		return;
1123 	default:
1124 		g_io_deliver(bp, EOPNOTSUPP);
1125 		return;
1126 	}
1127 	mtx_lock(&sc->sc_queue_mtx);
1128 	bioq_insert_tail(&sc->sc_queue, bp);
1129 	mtx_unlock(&sc->sc_queue_mtx);
1130 	if (!dumping) {
1131 		G_RAID_DEBUG1(4, sc, "Waking up %p.", sc);
1132 		wakeup(sc);
1133 	}
1134 }
1135 
1136 static int
1137 g_raid_bio_overlaps(const struct bio *bp, off_t lstart, off_t len)
1138 {
1139 	/*
1140 	 * 5 cases:
1141 	 * (1) bp entirely below NO
1142 	 * (2) bp entirely above NO
1143 	 * (3) bp start below, but end in range YES
1144 	 * (4) bp entirely within YES
1145 	 * (5) bp starts within, ends above YES
1146 	 *
1147 	 * lock range 10-19 (offset 10 length 10)
1148 	 * (1) 1-5: first if kicks it out
1149 	 * (2) 30-35: second if kicks it out
1150 	 * (3) 5-15: passes both ifs
1151 	 * (4) 12-14: passes both ifs
1152 	 * (5) 19-20: passes both
1153 	 */
1154 	off_t lend = lstart + len - 1;
1155 	off_t bstart = bp->bio_offset;
1156 	off_t bend = bp->bio_offset + bp->bio_length - 1;
1157 
1158 	if (bend < lstart)
1159 		return (0);
1160 	if (lend < bstart)
1161 		return (0);
1162 	return (1);
1163 }
1164 
1165 static int
1166 g_raid_is_in_locked_range(struct g_raid_volume *vol, const struct bio *bp)
1167 {
1168 	struct g_raid_lock *lp;
1169 
1170 	sx_assert(&vol->v_softc->sc_lock, SX_LOCKED);
1171 
1172 	LIST_FOREACH(lp, &vol->v_locks, l_next) {
1173 		if (g_raid_bio_overlaps(bp, lp->l_offset, lp->l_length))
1174 			return (1);
1175 	}
1176 	return (0);
1177 }
1178 
1179 static void
1180 g_raid_start_request(struct bio *bp)
1181 {
1182 	struct g_raid_softc *sc;
1183 	struct g_raid_volume *vol;
1184 
1185 	sc = bp->bio_to->geom->softc;
1186 	sx_assert(&sc->sc_lock, SX_LOCKED);
1187 	vol = bp->bio_to->private;
1188 
1189 	/*
1190 	 * Check to see if this item is in a locked range.  If so,
1191 	 * queue it to our locked queue and return.  We'll requeue
1192 	 * it when the range is unlocked.  Internal I/O for the
1193 	 * rebuild/rescan/recovery process is excluded from this
1194 	 * check so we can actually do the recovery.
1195 	 */
1196 	if (!(bp->bio_cflags & G_RAID_BIO_FLAG_SPECIAL) &&
1197 	    g_raid_is_in_locked_range(vol, bp)) {
1198 		G_RAID_LOGREQ(3, bp, "Defer request.");
1199 		bioq_insert_tail(&vol->v_locked, bp);
1200 		return;
1201 	}
1202 
1203 	/*
1204 	 * If we're actually going to do the write/delete, then
1205 	 * update the idle stats for the volume.
1206 	 */
1207 	if (bp->bio_cmd == BIO_WRITE || bp->bio_cmd == BIO_DELETE) {
1208 		if (!vol->v_dirty)
1209 			g_raid_dirty(vol);
1210 		vol->v_writes++;
1211 	}
1212 
1213 	/*
1214 	 * Put request onto inflight queue, so we can check if new
1215 	 * synchronization requests don't collide with it.  Then tell
1216 	 * the transformation layer to start the I/O.
1217 	 */
1218 	bioq_insert_tail(&vol->v_inflight, bp);
1219 	G_RAID_LOGREQ(4, bp, "Request started");
1220 	G_RAID_TR_IOSTART(vol->v_tr, bp);
1221 }
1222 
1223 static void
1224 g_raid_finish_with_locked_ranges(struct g_raid_volume *vol, struct bio *bp)
1225 {
1226 	off_t off, len;
1227 	struct bio *nbp;
1228 	struct g_raid_lock *lp;
1229 
1230 	vol->v_pending_lock = 0;
1231 	LIST_FOREACH(lp, &vol->v_locks, l_next) {
1232 		if (lp->l_pending) {
1233 			off = lp->l_offset;
1234 			len = lp->l_length;
1235 			lp->l_pending = 0;
1236 			TAILQ_FOREACH(nbp, &vol->v_inflight.queue, bio_queue) {
1237 				if (g_raid_bio_overlaps(nbp, off, len))
1238 					lp->l_pending++;
1239 			}
1240 			if (lp->l_pending) {
1241 				vol->v_pending_lock = 1;
1242 				G_RAID_DEBUG1(4, vol->v_softc,
1243 				    "Deferred lock(%jd, %jd) has %d pending",
1244 				    (intmax_t)off, (intmax_t)(off + len),
1245 				    lp->l_pending);
1246 				continue;
1247 			}
1248 			G_RAID_DEBUG1(4, vol->v_softc,
1249 			    "Deferred lock of %jd to %jd completed",
1250 			    (intmax_t)off, (intmax_t)(off + len));
1251 			G_RAID_TR_LOCKED(vol->v_tr, lp->l_callback_arg);
1252 		}
1253 	}
1254 }
1255 
1256 void
1257 g_raid_iodone(struct bio *bp, int error)
1258 {
1259 	struct g_raid_softc *sc;
1260 	struct g_raid_volume *vol;
1261 
1262 	sc = bp->bio_to->geom->softc;
1263 	sx_assert(&sc->sc_lock, SX_LOCKED);
1264 	vol = bp->bio_to->private;
1265 	G_RAID_LOGREQ(3, bp, "Request done: %d.", error);
1266 
1267 	/* Update stats if we done write/delete. */
1268 	if (bp->bio_cmd == BIO_WRITE || bp->bio_cmd == BIO_DELETE) {
1269 		vol->v_writes--;
1270 		vol->v_last_write = time_uptime;
1271 	}
1272 
1273 	bioq_remove(&vol->v_inflight, bp);
1274 	if (vol->v_pending_lock && g_raid_is_in_locked_range(vol, bp))
1275 		g_raid_finish_with_locked_ranges(vol, bp);
1276 	getmicrouptime(&vol->v_last_done);
1277 	g_io_deliver(bp, error);
1278 }
1279 
1280 int
1281 g_raid_lock_range(struct g_raid_volume *vol, off_t off, off_t len,
1282     struct bio *ignore, void *argp)
1283 {
1284 	struct g_raid_softc *sc;
1285 	struct g_raid_lock *lp;
1286 	struct bio *bp;
1287 
1288 	sc = vol->v_softc;
1289 	lp = malloc(sizeof(*lp), M_RAID, M_WAITOK | M_ZERO);
1290 	LIST_INSERT_HEAD(&vol->v_locks, lp, l_next);
1291 	lp->l_offset = off;
1292 	lp->l_length = len;
1293 	lp->l_callback_arg = argp;
1294 
1295 	lp->l_pending = 0;
1296 	TAILQ_FOREACH(bp, &vol->v_inflight.queue, bio_queue) {
1297 		if (bp != ignore && g_raid_bio_overlaps(bp, off, len))
1298 			lp->l_pending++;
1299 	}
1300 
1301 	/*
1302 	 * If there are any writes that are pending, we return EBUSY.  All
1303 	 * callers will have to wait until all pending writes clear.
1304 	 */
1305 	if (lp->l_pending > 0) {
1306 		vol->v_pending_lock = 1;
1307 		G_RAID_DEBUG1(4, sc, "Locking range %jd to %jd deferred %d pend",
1308 		    (intmax_t)off, (intmax_t)(off+len), lp->l_pending);
1309 		return (EBUSY);
1310 	}
1311 	G_RAID_DEBUG1(4, sc, "Locking range %jd to %jd",
1312 	    (intmax_t)off, (intmax_t)(off+len));
1313 	G_RAID_TR_LOCKED(vol->v_tr, lp->l_callback_arg);
1314 	return (0);
1315 }
1316 
1317 int
1318 g_raid_unlock_range(struct g_raid_volume *vol, off_t off, off_t len)
1319 {
1320 	struct g_raid_lock *lp;
1321 	struct g_raid_softc *sc;
1322 	struct bio *bp;
1323 
1324 	sc = vol->v_softc;
1325 	LIST_FOREACH(lp, &vol->v_locks, l_next) {
1326 		if (lp->l_offset == off && lp->l_length == len) {
1327 			LIST_REMOVE(lp, l_next);
1328 			/* XXX
1329 			 * Right now we just put them all back on the queue
1330 			 * and hope for the best.  We hope this because any
1331 			 * locked ranges will go right back on this list
1332 			 * when the worker thread runs.
1333 			 * XXX
1334 			 */
1335 			G_RAID_DEBUG1(4, sc, "Unlocked %jd to %jd",
1336 			    (intmax_t)lp->l_offset,
1337 			    (intmax_t)(lp->l_offset+lp->l_length));
1338 			mtx_lock(&sc->sc_queue_mtx);
1339 			while ((bp = bioq_takefirst(&vol->v_locked)) != NULL)
1340 				bioq_insert_tail(&sc->sc_queue, bp);
1341 			mtx_unlock(&sc->sc_queue_mtx);
1342 			free(lp, M_RAID);
1343 			return (0);
1344 		}
1345 	}
1346 	return (EINVAL);
1347 }
1348 
1349 void
1350 g_raid_subdisk_iostart(struct g_raid_subdisk *sd, struct bio *bp)
1351 {
1352 	struct g_consumer *cp;
1353 	struct g_raid_disk *disk, *tdisk;
1354 
1355 	bp->bio_caller1 = sd;
1356 
1357 	/*
1358 	 * Make sure that the disk is present. Generally it is a task of
1359 	 * transformation layers to not send requests to absent disks, but
1360 	 * it is better to be safe and report situation then sorry.
1361 	 */
1362 	if (sd->sd_disk == NULL) {
1363 		G_RAID_LOGREQ(0, bp, "Warning! I/O request to an absent disk!");
1364 nodisk:
1365 		bp->bio_from = NULL;
1366 		bp->bio_to = NULL;
1367 		bp->bio_error = ENXIO;
1368 		g_raid_disk_done(bp);
1369 		return;
1370 	}
1371 	disk = sd->sd_disk;
1372 	if (disk->d_state != G_RAID_DISK_S_ACTIVE &&
1373 	    disk->d_state != G_RAID_DISK_S_FAILED) {
1374 		G_RAID_LOGREQ(0, bp, "Warning! I/O request to a disk in a "
1375 		    "wrong state (%s)!", g_raid_disk_state2str(disk->d_state));
1376 		goto nodisk;
1377 	}
1378 
1379 	cp = disk->d_consumer;
1380 	bp->bio_from = cp;
1381 	bp->bio_to = cp->provider;
1382 	cp->index++;
1383 
1384 	/* Update average disks load. */
1385 	TAILQ_FOREACH(tdisk, &sd->sd_softc->sc_disks, d_next) {
1386 		if (tdisk->d_consumer == NULL)
1387 			tdisk->d_load = 0;
1388 		else
1389 			tdisk->d_load = (tdisk->d_consumer->index *
1390 			    G_RAID_SUBDISK_LOAD_SCALE + tdisk->d_load * 7) / 8;
1391 	}
1392 
1393 	disk->d_last_offset = bp->bio_offset + bp->bio_length;
1394 	if (dumping) {
1395 		G_RAID_LOGREQ(3, bp, "Sending dumping request.");
1396 		if (bp->bio_cmd == BIO_WRITE) {
1397 			bp->bio_error = g_raid_subdisk_kerneldump(sd,
1398 			    bp->bio_data, 0, bp->bio_offset, bp->bio_length);
1399 		} else
1400 			bp->bio_error = EOPNOTSUPP;
1401 		g_raid_disk_done(bp);
1402 	} else {
1403 		bp->bio_done = g_raid_disk_done;
1404 		bp->bio_offset += sd->sd_offset;
1405 		G_RAID_LOGREQ(3, bp, "Sending request.");
1406 		g_io_request(bp, cp);
1407 	}
1408 }
1409 
1410 int
1411 g_raid_subdisk_kerneldump(struct g_raid_subdisk *sd,
1412     void *virtual, vm_offset_t physical, off_t offset, size_t length)
1413 {
1414 
1415 	if (sd->sd_disk == NULL)
1416 		return (ENXIO);
1417 	if (sd->sd_disk->d_kd.di.dumper == NULL)
1418 		return (EOPNOTSUPP);
1419 	return (dump_write(&sd->sd_disk->d_kd.di,
1420 	    virtual, physical,
1421 	    sd->sd_disk->d_kd.di.mediaoffset + sd->sd_offset + offset,
1422 	    length));
1423 }
1424 
1425 static void
1426 g_raid_disk_done(struct bio *bp)
1427 {
1428 	struct g_raid_softc *sc;
1429 	struct g_raid_subdisk *sd;
1430 
1431 	sd = bp->bio_caller1;
1432 	sc = sd->sd_softc;
1433 	mtx_lock(&sc->sc_queue_mtx);
1434 	bioq_insert_tail(&sc->sc_queue, bp);
1435 	mtx_unlock(&sc->sc_queue_mtx);
1436 	if (!dumping)
1437 		wakeup(sc);
1438 }
1439 
1440 static void
1441 g_raid_disk_done_request(struct bio *bp)
1442 {
1443 	struct g_raid_softc *sc;
1444 	struct g_raid_disk *disk;
1445 	struct g_raid_subdisk *sd;
1446 	struct g_raid_volume *vol;
1447 
1448 	g_topology_assert_not();
1449 
1450 	G_RAID_LOGREQ(3, bp, "Disk request done: %d.", bp->bio_error);
1451 	sd = bp->bio_caller1;
1452 	sc = sd->sd_softc;
1453 	vol = sd->sd_volume;
1454 	if (bp->bio_from != NULL) {
1455 		bp->bio_from->index--;
1456 		disk = bp->bio_from->private;
1457 		if (disk == NULL)
1458 			g_raid_kill_consumer(sc, bp->bio_from);
1459 	}
1460 	bp->bio_offset -= sd->sd_offset;
1461 
1462 	G_RAID_TR_IODONE(vol->v_tr, sd, bp);
1463 }
1464 
1465 static void
1466 g_raid_handle_event(struct g_raid_softc *sc, struct g_raid_event *ep)
1467 {
1468 
1469 	if ((ep->e_flags & G_RAID_EVENT_VOLUME) != 0)
1470 		ep->e_error = g_raid_update_volume(ep->e_tgt, ep->e_event);
1471 	else if ((ep->e_flags & G_RAID_EVENT_DISK) != 0)
1472 		ep->e_error = g_raid_update_disk(ep->e_tgt, ep->e_event);
1473 	else if ((ep->e_flags & G_RAID_EVENT_SUBDISK) != 0)
1474 		ep->e_error = g_raid_update_subdisk(ep->e_tgt, ep->e_event);
1475 	else
1476 		ep->e_error = g_raid_update_node(ep->e_tgt, ep->e_event);
1477 	if ((ep->e_flags & G_RAID_EVENT_WAIT) == 0) {
1478 		KASSERT(ep->e_error == 0,
1479 		    ("Error cannot be handled."));
1480 		g_raid_event_free(ep);
1481 	} else {
1482 		ep->e_flags |= G_RAID_EVENT_DONE;
1483 		G_RAID_DEBUG1(4, sc, "Waking up %p.", ep);
1484 		mtx_lock(&sc->sc_queue_mtx);
1485 		wakeup(ep);
1486 		mtx_unlock(&sc->sc_queue_mtx);
1487 	}
1488 }
1489 
1490 /*
1491  * Worker thread.
1492  */
1493 static void
1494 g_raid_worker(void *arg)
1495 {
1496 	struct g_raid_softc *sc;
1497 	struct g_raid_event *ep;
1498 	struct g_raid_volume *vol;
1499 	struct bio *bp;
1500 	struct timeval now, t;
1501 	int timeout, rv;
1502 
1503 	sc = arg;
1504 	thread_lock(curthread);
1505 	sched_prio(curthread, PRIBIO);
1506 	thread_unlock(curthread);
1507 
1508 	sx_xlock(&sc->sc_lock);
1509 	for (;;) {
1510 		mtx_lock(&sc->sc_queue_mtx);
1511 		/*
1512 		 * First take a look at events.
1513 		 * This is important to handle events before any I/O requests.
1514 		 */
1515 		bp = NULL;
1516 		vol = NULL;
1517 		rv = 0;
1518 		ep = TAILQ_FIRST(&sc->sc_events);
1519 		if (ep != NULL)
1520 			TAILQ_REMOVE(&sc->sc_events, ep, e_next);
1521 		else if ((bp = bioq_takefirst(&sc->sc_queue)) != NULL)
1522 			;
1523 		else {
1524 			getmicrouptime(&now);
1525 			t = now;
1526 			TAILQ_FOREACH(vol, &sc->sc_volumes, v_next) {
1527 				if (bioq_first(&vol->v_inflight) == NULL &&
1528 				    vol->v_tr &&
1529 				    timevalcmp(&vol->v_last_done, &t, < ))
1530 					t = vol->v_last_done;
1531 			}
1532 			timevalsub(&t, &now);
1533 			timeout = g_raid_idle_threshold +
1534 			    t.tv_sec * 1000000 + t.tv_usec;
1535 			if (timeout > 0) {
1536 				/*
1537 				 * Two steps to avoid overflows at HZ=1000
1538 				 * and idle timeouts > 2.1s.  Some rounding
1539 				 * errors can occur, but they are < 1tick,
1540 				 * which is deemed to be close enough for
1541 				 * this purpose.
1542 				 */
1543 				int micpertic = 1000000 / hz;
1544 				timeout = (timeout + micpertic - 1) / micpertic;
1545 				sx_xunlock(&sc->sc_lock);
1546 				MSLEEP(rv, sc, &sc->sc_queue_mtx,
1547 				    PRIBIO | PDROP, "-", timeout);
1548 				sx_xlock(&sc->sc_lock);
1549 				goto process;
1550 			} else
1551 				rv = EWOULDBLOCK;
1552 		}
1553 		mtx_unlock(&sc->sc_queue_mtx);
1554 process:
1555 		if (ep != NULL) {
1556 			g_raid_handle_event(sc, ep);
1557 		} else if (bp != NULL) {
1558 			if (bp->bio_to != NULL &&
1559 			    bp->bio_to->geom == sc->sc_geom)
1560 				g_raid_start_request(bp);
1561 			else
1562 				g_raid_disk_done_request(bp);
1563 		} else if (rv == EWOULDBLOCK) {
1564 			TAILQ_FOREACH(vol, &sc->sc_volumes, v_next) {
1565 				g_raid_clean(vol, -1);
1566 				if (bioq_first(&vol->v_inflight) == NULL &&
1567 				    vol->v_tr) {
1568 					t.tv_sec = g_raid_idle_threshold / 1000000;
1569 					t.tv_usec = g_raid_idle_threshold % 1000000;
1570 					timevaladd(&t, &vol->v_last_done);
1571 					getmicrouptime(&now);
1572 					if (timevalcmp(&t, &now, <= )) {
1573 						G_RAID_TR_IDLE(vol->v_tr);
1574 						vol->v_last_done = now;
1575 					}
1576 				}
1577 			}
1578 		}
1579 		if (sc->sc_stopping == G_RAID_DESTROY_HARD)
1580 			g_raid_destroy_node(sc, 1);	/* May not return. */
1581 	}
1582 }
1583 
1584 static void
1585 g_raid_poll(struct g_raid_softc *sc)
1586 {
1587 	struct g_raid_event *ep;
1588 	struct bio *bp;
1589 
1590 	sx_xlock(&sc->sc_lock);
1591 	mtx_lock(&sc->sc_queue_mtx);
1592 	/*
1593 	 * First take a look at events.
1594 	 * This is important to handle events before any I/O requests.
1595 	 */
1596 	ep = TAILQ_FIRST(&sc->sc_events);
1597 	if (ep != NULL) {
1598 		TAILQ_REMOVE(&sc->sc_events, ep, e_next);
1599 		mtx_unlock(&sc->sc_queue_mtx);
1600 		g_raid_handle_event(sc, ep);
1601 		goto out;
1602 	}
1603 	bp = bioq_takefirst(&sc->sc_queue);
1604 	if (bp != NULL) {
1605 		mtx_unlock(&sc->sc_queue_mtx);
1606 		if (bp->bio_from == NULL ||
1607 		    bp->bio_from->geom != sc->sc_geom)
1608 			g_raid_start_request(bp);
1609 		else
1610 			g_raid_disk_done_request(bp);
1611 	}
1612 out:
1613 	sx_xunlock(&sc->sc_lock);
1614 }
1615 
1616 static void
1617 g_raid_launch_provider(struct g_raid_volume *vol)
1618 {
1619 	struct g_raid_disk *disk;
1620 	struct g_raid_subdisk *sd;
1621 	struct g_raid_softc *sc;
1622 	struct g_provider *pp;
1623 	char name[G_RAID_MAX_VOLUMENAME];
1624 	off_t off;
1625 	int i;
1626 
1627 	sc = vol->v_softc;
1628 	sx_assert(&sc->sc_lock, SX_LOCKED);
1629 
1630 	g_topology_lock();
1631 	/* Try to name provider with volume name. */
1632 	snprintf(name, sizeof(name), "raid/%s", vol->v_name);
1633 	if (g_raid_name_format == 0 || vol->v_name[0] == 0 ||
1634 	    g_provider_by_name(name) != NULL) {
1635 		/* Otherwise use sequential volume number. */
1636 		snprintf(name, sizeof(name), "raid/r%d", vol->v_global_id);
1637 	}
1638 
1639 	pp = g_new_providerf(sc->sc_geom, "%s", name);
1640 	pp->flags |= G_PF_DIRECT_RECEIVE;
1641 	if (vol->v_tr->tro_class->trc_accept_unmapped) {
1642 		pp->flags |= G_PF_ACCEPT_UNMAPPED;
1643 		for (i = 0; i < vol->v_disks_count; i++) {
1644 			sd = &vol->v_subdisks[i];
1645 			if (sd->sd_state == G_RAID_SUBDISK_S_NONE)
1646 				continue;
1647 			if ((sd->sd_disk->d_consumer->provider->flags &
1648 			    G_PF_ACCEPT_UNMAPPED) == 0)
1649 				pp->flags &= ~G_PF_ACCEPT_UNMAPPED;
1650 		}
1651 	}
1652 	pp->private = vol;
1653 	pp->mediasize = vol->v_mediasize;
1654 	pp->sectorsize = vol->v_sectorsize;
1655 	pp->stripesize = 0;
1656 	pp->stripeoffset = 0;
1657 	if (vol->v_raid_level == G_RAID_VOLUME_RL_RAID1 ||
1658 	    vol->v_raid_level == G_RAID_VOLUME_RL_RAID3 ||
1659 	    vol->v_raid_level == G_RAID_VOLUME_RL_SINGLE ||
1660 	    vol->v_raid_level == G_RAID_VOLUME_RL_CONCAT) {
1661 		if ((disk = vol->v_subdisks[0].sd_disk) != NULL &&
1662 		    disk->d_consumer != NULL &&
1663 		    disk->d_consumer->provider != NULL) {
1664 			pp->stripesize = disk->d_consumer->provider->stripesize;
1665 			off = disk->d_consumer->provider->stripeoffset;
1666 			pp->stripeoffset = off + vol->v_subdisks[0].sd_offset;
1667 			if (off > 0)
1668 				pp->stripeoffset %= off;
1669 		}
1670 		if (vol->v_raid_level == G_RAID_VOLUME_RL_RAID3) {
1671 			pp->stripesize *= (vol->v_disks_count - 1);
1672 			pp->stripeoffset *= (vol->v_disks_count - 1);
1673 		}
1674 	} else
1675 		pp->stripesize = vol->v_strip_size;
1676 	vol->v_provider = pp;
1677 	g_error_provider(pp, 0);
1678 	g_topology_unlock();
1679 	G_RAID_DEBUG1(0, sc, "Provider %s for volume %s created.",
1680 	    pp->name, vol->v_name);
1681 }
1682 
1683 static void
1684 g_raid_destroy_provider(struct g_raid_volume *vol)
1685 {
1686 	struct g_raid_softc *sc;
1687 	struct g_provider *pp;
1688 	struct bio *bp, *tmp;
1689 
1690 	g_topology_assert_not();
1691 	sc = vol->v_softc;
1692 	pp = vol->v_provider;
1693 	KASSERT(pp != NULL, ("NULL provider (volume=%s).", vol->v_name));
1694 
1695 	g_topology_lock();
1696 	g_error_provider(pp, ENXIO);
1697 	mtx_lock(&sc->sc_queue_mtx);
1698 	TAILQ_FOREACH_SAFE(bp, &sc->sc_queue.queue, bio_queue, tmp) {
1699 		if (bp->bio_to != pp)
1700 			continue;
1701 		bioq_remove(&sc->sc_queue, bp);
1702 		g_io_deliver(bp, ENXIO);
1703 	}
1704 	mtx_unlock(&sc->sc_queue_mtx);
1705 	G_RAID_DEBUG1(0, sc, "Provider %s for volume %s destroyed.",
1706 	    pp->name, vol->v_name);
1707 	g_wither_provider(pp, ENXIO);
1708 	g_topology_unlock();
1709 	vol->v_provider = NULL;
1710 }
1711 
1712 /*
1713  * Update device state.
1714  */
1715 static int
1716 g_raid_update_volume(struct g_raid_volume *vol, u_int event)
1717 {
1718 	struct g_raid_softc *sc;
1719 
1720 	sc = vol->v_softc;
1721 	sx_assert(&sc->sc_lock, SX_XLOCKED);
1722 
1723 	G_RAID_DEBUG1(2, sc, "Event %s for volume %s.",
1724 	    g_raid_volume_event2str(event),
1725 	    vol->v_name);
1726 	switch (event) {
1727 	case G_RAID_VOLUME_E_DOWN:
1728 		if (vol->v_provider != NULL)
1729 			g_raid_destroy_provider(vol);
1730 		break;
1731 	case G_RAID_VOLUME_E_UP:
1732 		if (vol->v_provider == NULL)
1733 			g_raid_launch_provider(vol);
1734 		break;
1735 	case G_RAID_VOLUME_E_START:
1736 		if (vol->v_tr)
1737 			G_RAID_TR_START(vol->v_tr);
1738 		return (0);
1739 	default:
1740 		if (sc->sc_md)
1741 			G_RAID_MD_VOLUME_EVENT(sc->sc_md, vol, event);
1742 		return (0);
1743 	}
1744 
1745 	/* Manage root mount release. */
1746 	if (vol->v_starting) {
1747 		vol->v_starting = 0;
1748 		G_RAID_DEBUG1(1, sc, "root_mount_rel %p", vol->v_rootmount);
1749 		root_mount_rel(vol->v_rootmount);
1750 		vol->v_rootmount = NULL;
1751 	}
1752 	if (vol->v_stopping && vol->v_provider_open == 0)
1753 		g_raid_destroy_volume(vol);
1754 	return (0);
1755 }
1756 
1757 /*
1758  * Update subdisk state.
1759  */
1760 static int
1761 g_raid_update_subdisk(struct g_raid_subdisk *sd, u_int event)
1762 {
1763 	struct g_raid_softc *sc;
1764 	struct g_raid_volume *vol;
1765 
1766 	sc = sd->sd_softc;
1767 	vol = sd->sd_volume;
1768 	sx_assert(&sc->sc_lock, SX_XLOCKED);
1769 
1770 	G_RAID_DEBUG1(2, sc, "Event %s for subdisk %s:%d-%s.",
1771 	    g_raid_subdisk_event2str(event),
1772 	    vol->v_name, sd->sd_pos,
1773 	    sd->sd_disk ? g_raid_get_diskname(sd->sd_disk) : "[none]");
1774 	if (vol->v_tr)
1775 		G_RAID_TR_EVENT(vol->v_tr, sd, event);
1776 
1777 	return (0);
1778 }
1779 
1780 /*
1781  * Update disk state.
1782  */
1783 static int
1784 g_raid_update_disk(struct g_raid_disk *disk, u_int event)
1785 {
1786 	struct g_raid_softc *sc;
1787 
1788 	sc = disk->d_softc;
1789 	sx_assert(&sc->sc_lock, SX_XLOCKED);
1790 
1791 	G_RAID_DEBUG1(2, sc, "Event %s for disk %s.",
1792 	    g_raid_disk_event2str(event),
1793 	    g_raid_get_diskname(disk));
1794 
1795 	if (sc->sc_md)
1796 		G_RAID_MD_EVENT(sc->sc_md, disk, event);
1797 	return (0);
1798 }
1799 
1800 /*
1801  * Node event.
1802  */
1803 static int
1804 g_raid_update_node(struct g_raid_softc *sc, u_int event)
1805 {
1806 	sx_assert(&sc->sc_lock, SX_XLOCKED);
1807 
1808 	G_RAID_DEBUG1(2, sc, "Event %s for the array.",
1809 	    g_raid_node_event2str(event));
1810 
1811 	if (event == G_RAID_NODE_E_WAKE)
1812 		return (0);
1813 	if (sc->sc_md)
1814 		G_RAID_MD_EVENT(sc->sc_md, NULL, event);
1815 	return (0);
1816 }
1817 
1818 static int
1819 g_raid_access(struct g_provider *pp, int acr, int acw, int ace)
1820 {
1821 	struct g_raid_volume *vol;
1822 	struct g_raid_softc *sc;
1823 	int dcw, opens, error = 0;
1824 
1825 	g_topology_assert();
1826 	sc = pp->geom->softc;
1827 	vol = pp->private;
1828 	KASSERT(sc != NULL, ("NULL softc (provider=%s).", pp->name));
1829 	KASSERT(vol != NULL, ("NULL volume (provider=%s).", pp->name));
1830 
1831 	G_RAID_DEBUG1(2, sc, "Access request for %s: r%dw%de%d.", pp->name,
1832 	    acr, acw, ace);
1833 	dcw = pp->acw + acw;
1834 
1835 	g_topology_unlock();
1836 	sx_xlock(&sc->sc_lock);
1837 	/* Deny new opens while dying. */
1838 	if (sc->sc_stopping != 0 && (acr > 0 || acw > 0 || ace > 0)) {
1839 		error = ENXIO;
1840 		goto out;
1841 	}
1842 	/* Deny write opens for read-only volumes. */
1843 	if (vol->v_read_only && acw > 0) {
1844 		error = EROFS;
1845 		goto out;
1846 	}
1847 	if (dcw == 0)
1848 		g_raid_clean(vol, dcw);
1849 	vol->v_provider_open += acr + acw + ace;
1850 	/* Handle delayed node destruction. */
1851 	if (sc->sc_stopping == G_RAID_DESTROY_DELAYED &&
1852 	    vol->v_provider_open == 0) {
1853 		/* Count open volumes. */
1854 		opens = g_raid_nopens(sc);
1855 		if (opens == 0) {
1856 			sc->sc_stopping = G_RAID_DESTROY_HARD;
1857 			/* Wake up worker to make it selfdestruct. */
1858 			g_raid_event_send(sc, G_RAID_NODE_E_WAKE, 0);
1859 		}
1860 	}
1861 	/* Handle open volume destruction. */
1862 	if (vol->v_stopping && vol->v_provider_open == 0)
1863 		g_raid_destroy_volume(vol);
1864 out:
1865 	sx_xunlock(&sc->sc_lock);
1866 	g_topology_lock();
1867 	return (error);
1868 }
1869 
1870 struct g_raid_softc *
1871 g_raid_create_node(struct g_class *mp,
1872     const char *name, struct g_raid_md_object *md)
1873 {
1874 	struct g_raid_softc *sc;
1875 	struct g_geom *gp;
1876 	int error;
1877 
1878 	g_topology_assert();
1879 	G_RAID_DEBUG(1, "Creating array %s.", name);
1880 
1881 	gp = g_new_geomf(mp, "%s", name);
1882 	sc = malloc(sizeof(*sc), M_RAID, M_WAITOK | M_ZERO);
1883 	gp->start = g_raid_start;
1884 	gp->orphan = g_raid_orphan;
1885 	gp->access = g_raid_access;
1886 	gp->dumpconf = g_raid_dumpconf;
1887 
1888 	sc->sc_md = md;
1889 	sc->sc_geom = gp;
1890 	sc->sc_flags = 0;
1891 	TAILQ_INIT(&sc->sc_volumes);
1892 	TAILQ_INIT(&sc->sc_disks);
1893 	sx_init(&sc->sc_lock, "graid:lock");
1894 	mtx_init(&sc->sc_queue_mtx, "graid:queue", NULL, MTX_DEF);
1895 	TAILQ_INIT(&sc->sc_events);
1896 	bioq_init(&sc->sc_queue);
1897 	gp->softc = sc;
1898 	error = kproc_create(g_raid_worker, sc, &sc->sc_worker, 0, 0,
1899 	    "g_raid %s", name);
1900 	if (error != 0) {
1901 		G_RAID_DEBUG(0, "Cannot create kernel thread for %s.", name);
1902 		mtx_destroy(&sc->sc_queue_mtx);
1903 		sx_destroy(&sc->sc_lock);
1904 		g_destroy_geom(sc->sc_geom);
1905 		free(sc, M_RAID);
1906 		return (NULL);
1907 	}
1908 
1909 	G_RAID_DEBUG1(0, sc, "Array %s created.", name);
1910 	return (sc);
1911 }
1912 
1913 struct g_raid_volume *
1914 g_raid_create_volume(struct g_raid_softc *sc, const char *name, int id)
1915 {
1916 	struct g_raid_volume	*vol, *vol1;
1917 	int i;
1918 
1919 	G_RAID_DEBUG1(1, sc, "Creating volume %s.", name);
1920 	vol = malloc(sizeof(*vol), M_RAID, M_WAITOK | M_ZERO);
1921 	vol->v_softc = sc;
1922 	strlcpy(vol->v_name, name, G_RAID_MAX_VOLUMENAME);
1923 	vol->v_state = G_RAID_VOLUME_S_STARTING;
1924 	vol->v_raid_level = G_RAID_VOLUME_RL_UNKNOWN;
1925 	vol->v_raid_level_qualifier = G_RAID_VOLUME_RLQ_UNKNOWN;
1926 	vol->v_rotate_parity = 1;
1927 	bioq_init(&vol->v_inflight);
1928 	bioq_init(&vol->v_locked);
1929 	LIST_INIT(&vol->v_locks);
1930 	for (i = 0; i < G_RAID_MAX_SUBDISKS; i++) {
1931 		vol->v_subdisks[i].sd_softc = sc;
1932 		vol->v_subdisks[i].sd_volume = vol;
1933 		vol->v_subdisks[i].sd_pos = i;
1934 		vol->v_subdisks[i].sd_state = G_RAID_DISK_S_NONE;
1935 	}
1936 
1937 	/* Find free ID for this volume. */
1938 	g_topology_lock();
1939 	vol1 = vol;
1940 	if (id >= 0) {
1941 		LIST_FOREACH(vol1, &g_raid_volumes, v_global_next) {
1942 			if (vol1->v_global_id == id)
1943 				break;
1944 		}
1945 	}
1946 	if (vol1 != NULL) {
1947 		for (id = 0; ; id++) {
1948 			LIST_FOREACH(vol1, &g_raid_volumes, v_global_next) {
1949 				if (vol1->v_global_id == id)
1950 					break;
1951 			}
1952 			if (vol1 == NULL)
1953 				break;
1954 		}
1955 	}
1956 	vol->v_global_id = id;
1957 	LIST_INSERT_HEAD(&g_raid_volumes, vol, v_global_next);
1958 	g_topology_unlock();
1959 
1960 	/* Delay root mounting. */
1961 	vol->v_rootmount = root_mount_hold("GRAID");
1962 	G_RAID_DEBUG1(1, sc, "root_mount_hold %p", vol->v_rootmount);
1963 	vol->v_starting = 1;
1964 	TAILQ_INSERT_TAIL(&sc->sc_volumes, vol, v_next);
1965 	return (vol);
1966 }
1967 
1968 struct g_raid_disk *
1969 g_raid_create_disk(struct g_raid_softc *sc)
1970 {
1971 	struct g_raid_disk	*disk;
1972 
1973 	G_RAID_DEBUG1(1, sc, "Creating disk.");
1974 	disk = malloc(sizeof(*disk), M_RAID, M_WAITOK | M_ZERO);
1975 	disk->d_softc = sc;
1976 	disk->d_state = G_RAID_DISK_S_NONE;
1977 	TAILQ_INIT(&disk->d_subdisks);
1978 	TAILQ_INSERT_TAIL(&sc->sc_disks, disk, d_next);
1979 	return (disk);
1980 }
1981 
1982 int g_raid_start_volume(struct g_raid_volume *vol)
1983 {
1984 	struct g_raid_tr_class *class;
1985 	struct g_raid_tr_object *obj;
1986 	int status;
1987 
1988 	G_RAID_DEBUG1(2, vol->v_softc, "Starting volume %s.", vol->v_name);
1989 	LIST_FOREACH(class, &g_raid_tr_classes, trc_list) {
1990 		if (!class->trc_enable)
1991 			continue;
1992 		G_RAID_DEBUG1(2, vol->v_softc,
1993 		    "Tasting volume %s for %s transformation.",
1994 		    vol->v_name, class->name);
1995 		obj = (void *)kobj_create((kobj_class_t)class, M_RAID,
1996 		    M_WAITOK);
1997 		obj->tro_class = class;
1998 		obj->tro_volume = vol;
1999 		status = G_RAID_TR_TASTE(obj, vol);
2000 		if (status != G_RAID_TR_TASTE_FAIL)
2001 			break;
2002 		kobj_delete((kobj_t)obj, M_RAID);
2003 	}
2004 	if (class == NULL) {
2005 		G_RAID_DEBUG1(0, vol->v_softc,
2006 		    "No transformation module found for %s.",
2007 		    vol->v_name);
2008 		vol->v_tr = NULL;
2009 		g_raid_change_volume_state(vol, G_RAID_VOLUME_S_UNSUPPORTED);
2010 		g_raid_event_send(vol, G_RAID_VOLUME_E_DOWN,
2011 		    G_RAID_EVENT_VOLUME);
2012 		return (-1);
2013 	}
2014 	G_RAID_DEBUG1(2, vol->v_softc,
2015 	    "Transformation module %s chosen for %s.",
2016 	    class->name, vol->v_name);
2017 	vol->v_tr = obj;
2018 	return (0);
2019 }
2020 
2021 int
2022 g_raid_destroy_node(struct g_raid_softc *sc, int worker)
2023 {
2024 	struct g_raid_volume *vol, *tmpv;
2025 	struct g_raid_disk *disk, *tmpd;
2026 	int error = 0;
2027 
2028 	sc->sc_stopping = G_RAID_DESTROY_HARD;
2029 	TAILQ_FOREACH_SAFE(vol, &sc->sc_volumes, v_next, tmpv) {
2030 		if (g_raid_destroy_volume(vol))
2031 			error = EBUSY;
2032 	}
2033 	if (error)
2034 		return (error);
2035 	TAILQ_FOREACH_SAFE(disk, &sc->sc_disks, d_next, tmpd) {
2036 		if (g_raid_destroy_disk(disk))
2037 			error = EBUSY;
2038 	}
2039 	if (error)
2040 		return (error);
2041 	if (sc->sc_md) {
2042 		G_RAID_MD_FREE(sc->sc_md);
2043 		kobj_delete((kobj_t)sc->sc_md, M_RAID);
2044 		sc->sc_md = NULL;
2045 	}
2046 	if (sc->sc_geom != NULL) {
2047 		G_RAID_DEBUG1(0, sc, "Array %s destroyed.", sc->sc_name);
2048 		g_topology_lock();
2049 		sc->sc_geom->softc = NULL;
2050 		g_wither_geom(sc->sc_geom, ENXIO);
2051 		g_topology_unlock();
2052 		sc->sc_geom = NULL;
2053 	} else
2054 		G_RAID_DEBUG(1, "Array destroyed.");
2055 	if (worker) {
2056 		g_raid_event_cancel(sc, sc);
2057 		mtx_destroy(&sc->sc_queue_mtx);
2058 		sx_xunlock(&sc->sc_lock);
2059 		sx_destroy(&sc->sc_lock);
2060 		wakeup(&sc->sc_stopping);
2061 		free(sc, M_RAID);
2062 		curthread->td_pflags &= ~TDP_GEOM;
2063 		G_RAID_DEBUG(1, "Thread exiting.");
2064 		kproc_exit(0);
2065 	} else {
2066 		/* Wake up worker to make it selfdestruct. */
2067 		g_raid_event_send(sc, G_RAID_NODE_E_WAKE, 0);
2068 	}
2069 	return (0);
2070 }
2071 
2072 int
2073 g_raid_destroy_volume(struct g_raid_volume *vol)
2074 {
2075 	struct g_raid_softc *sc;
2076 	struct g_raid_disk *disk;
2077 	int i;
2078 
2079 	sc = vol->v_softc;
2080 	G_RAID_DEBUG1(2, sc, "Destroying volume %s.", vol->v_name);
2081 	vol->v_stopping = 1;
2082 	if (vol->v_state != G_RAID_VOLUME_S_STOPPED) {
2083 		if (vol->v_tr) {
2084 			G_RAID_TR_STOP(vol->v_tr);
2085 			return (EBUSY);
2086 		} else
2087 			vol->v_state = G_RAID_VOLUME_S_STOPPED;
2088 	}
2089 	if (g_raid_event_check(sc, vol) != 0)
2090 		return (EBUSY);
2091 	if (vol->v_provider != NULL)
2092 		return (EBUSY);
2093 	if (vol->v_provider_open != 0)
2094 		return (EBUSY);
2095 	if (vol->v_tr) {
2096 		G_RAID_TR_FREE(vol->v_tr);
2097 		kobj_delete((kobj_t)vol->v_tr, M_RAID);
2098 		vol->v_tr = NULL;
2099 	}
2100 	if (vol->v_rootmount)
2101 		root_mount_rel(vol->v_rootmount);
2102 	g_topology_lock();
2103 	LIST_REMOVE(vol, v_global_next);
2104 	g_topology_unlock();
2105 	TAILQ_REMOVE(&sc->sc_volumes, vol, v_next);
2106 	for (i = 0; i < G_RAID_MAX_SUBDISKS; i++) {
2107 		g_raid_event_cancel(sc, &vol->v_subdisks[i]);
2108 		disk = vol->v_subdisks[i].sd_disk;
2109 		if (disk == NULL)
2110 			continue;
2111 		TAILQ_REMOVE(&disk->d_subdisks, &vol->v_subdisks[i], sd_next);
2112 	}
2113 	G_RAID_DEBUG1(2, sc, "Volume %s destroyed.", vol->v_name);
2114 	if (sc->sc_md)
2115 		G_RAID_MD_FREE_VOLUME(sc->sc_md, vol);
2116 	g_raid_event_cancel(sc, vol);
2117 	free(vol, M_RAID);
2118 	if (sc->sc_stopping == G_RAID_DESTROY_HARD) {
2119 		/* Wake up worker to let it selfdestruct. */
2120 		g_raid_event_send(sc, G_RAID_NODE_E_WAKE, 0);
2121 	}
2122 	return (0);
2123 }
2124 
2125 int
2126 g_raid_destroy_disk(struct g_raid_disk *disk)
2127 {
2128 	struct g_raid_softc *sc;
2129 	struct g_raid_subdisk *sd, *tmp;
2130 
2131 	sc = disk->d_softc;
2132 	G_RAID_DEBUG1(2, sc, "Destroying disk.");
2133 	if (disk->d_consumer) {
2134 		g_raid_kill_consumer(sc, disk->d_consumer);
2135 		disk->d_consumer = NULL;
2136 	}
2137 	TAILQ_FOREACH_SAFE(sd, &disk->d_subdisks, sd_next, tmp) {
2138 		g_raid_change_subdisk_state(sd, G_RAID_SUBDISK_S_NONE);
2139 		g_raid_event_send(sd, G_RAID_SUBDISK_E_DISCONNECTED,
2140 		    G_RAID_EVENT_SUBDISK);
2141 		TAILQ_REMOVE(&disk->d_subdisks, sd, sd_next);
2142 		sd->sd_disk = NULL;
2143 	}
2144 	TAILQ_REMOVE(&sc->sc_disks, disk, d_next);
2145 	if (sc->sc_md)
2146 		G_RAID_MD_FREE_DISK(sc->sc_md, disk);
2147 	g_raid_event_cancel(sc, disk);
2148 	free(disk, M_RAID);
2149 	return (0);
2150 }
2151 
2152 int
2153 g_raid_destroy(struct g_raid_softc *sc, int how)
2154 {
2155 	int error, opens;
2156 
2157 	g_topology_assert_not();
2158 	if (sc == NULL)
2159 		return (ENXIO);
2160 	sx_assert(&sc->sc_lock, SX_XLOCKED);
2161 
2162 	/* Count open volumes. */
2163 	opens = g_raid_nopens(sc);
2164 
2165 	/* React on some opened volumes. */
2166 	if (opens > 0) {
2167 		switch (how) {
2168 		case G_RAID_DESTROY_SOFT:
2169 			G_RAID_DEBUG1(1, sc,
2170 			    "%d volumes are still open.",
2171 			    opens);
2172 			sx_xunlock(&sc->sc_lock);
2173 			return (EBUSY);
2174 		case G_RAID_DESTROY_DELAYED:
2175 			G_RAID_DEBUG1(1, sc,
2176 			    "Array will be destroyed on last close.");
2177 			sc->sc_stopping = G_RAID_DESTROY_DELAYED;
2178 			sx_xunlock(&sc->sc_lock);
2179 			return (EBUSY);
2180 		case G_RAID_DESTROY_HARD:
2181 			G_RAID_DEBUG1(1, sc,
2182 			    "%d volumes are still open.",
2183 			    opens);
2184 		}
2185 	}
2186 
2187 	/* Mark node for destruction. */
2188 	sc->sc_stopping = G_RAID_DESTROY_HARD;
2189 	/* Wake up worker to let it selfdestruct. */
2190 	g_raid_event_send(sc, G_RAID_NODE_E_WAKE, 0);
2191 	/* Sleep until node destroyed. */
2192 	error = sx_sleep(&sc->sc_stopping, &sc->sc_lock,
2193 	    PRIBIO | PDROP, "r:destroy", hz * 3);
2194 	return (error == EWOULDBLOCK ? EBUSY : 0);
2195 }
2196 
2197 static void
2198 g_raid_taste_orphan(struct g_consumer *cp)
2199 {
2200 
2201 	KASSERT(1 == 0, ("%s called while tasting %s.", __func__,
2202 	    cp->provider->name));
2203 }
2204 
2205 static struct g_geom *
2206 g_raid_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
2207 {
2208 	struct g_consumer *cp;
2209 	struct g_geom *gp, *geom;
2210 	struct g_raid_md_class *class;
2211 	struct g_raid_md_object *obj;
2212 	int status;
2213 
2214 	g_topology_assert();
2215 	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
2216 	if (!g_raid_enable)
2217 		return (NULL);
2218 	G_RAID_DEBUG(2, "Tasting provider %s.", pp->name);
2219 
2220 	geom = NULL;
2221 	status = G_RAID_MD_TASTE_FAIL;
2222 	gp = g_new_geomf(mp, "raid:taste");
2223 	/*
2224 	 * This orphan function should be never called.
2225 	 */
2226 	gp->orphan = g_raid_taste_orphan;
2227 	cp = g_new_consumer(gp);
2228 	cp->flags |= G_CF_DIRECT_RECEIVE;
2229 	g_attach(cp, pp);
2230 	if (g_access(cp, 1, 0, 0) != 0)
2231 		goto ofail;
2232 
2233 	LIST_FOREACH(class, &g_raid_md_classes, mdc_list) {
2234 		if (!class->mdc_enable)
2235 			continue;
2236 		G_RAID_DEBUG(2, "Tasting provider %s for %s metadata.",
2237 		    pp->name, class->name);
2238 		obj = (void *)kobj_create((kobj_class_t)class, M_RAID,
2239 		    M_WAITOK);
2240 		obj->mdo_class = class;
2241 		status = G_RAID_MD_TASTE(obj, mp, cp, &geom);
2242 		if (status != G_RAID_MD_TASTE_NEW)
2243 			kobj_delete((kobj_t)obj, M_RAID);
2244 		if (status != G_RAID_MD_TASTE_FAIL)
2245 			break;
2246 	}
2247 
2248 	if (status == G_RAID_MD_TASTE_FAIL)
2249 		(void)g_access(cp, -1, 0, 0);
2250 ofail:
2251 	g_detach(cp);
2252 	g_destroy_consumer(cp);
2253 	g_destroy_geom(gp);
2254 	G_RAID_DEBUG(2, "Tasting provider %s done.", pp->name);
2255 	return (geom);
2256 }
2257 
2258 int
2259 g_raid_create_node_format(const char *format, struct gctl_req *req,
2260     struct g_geom **gp)
2261 {
2262 	struct g_raid_md_class *class;
2263 	struct g_raid_md_object *obj;
2264 	int status;
2265 
2266 	G_RAID_DEBUG(2, "Creating array for %s metadata.", format);
2267 	LIST_FOREACH(class, &g_raid_md_classes, mdc_list) {
2268 		if (strcasecmp(class->name, format) == 0)
2269 			break;
2270 	}
2271 	if (class == NULL) {
2272 		G_RAID_DEBUG(1, "No support for %s metadata.", format);
2273 		return (G_RAID_MD_TASTE_FAIL);
2274 	}
2275 	obj = (void *)kobj_create((kobj_class_t)class, M_RAID,
2276 	    M_WAITOK);
2277 	obj->mdo_class = class;
2278 	status = G_RAID_MD_CREATE_REQ(obj, &g_raid_class, req, gp);
2279 	if (status != G_RAID_MD_TASTE_NEW)
2280 		kobj_delete((kobj_t)obj, M_RAID);
2281 	return (status);
2282 }
2283 
2284 static int
2285 g_raid_destroy_geom(struct gctl_req *req __unused,
2286     struct g_class *mp __unused, struct g_geom *gp)
2287 {
2288 	struct g_raid_softc *sc;
2289 	int error;
2290 
2291 	g_topology_unlock();
2292 	sc = gp->softc;
2293 	sx_xlock(&sc->sc_lock);
2294 	g_cancel_event(sc);
2295 	error = g_raid_destroy(gp->softc, G_RAID_DESTROY_SOFT);
2296 	g_topology_lock();
2297 	return (error);
2298 }
2299 
2300 void g_raid_write_metadata(struct g_raid_softc *sc, struct g_raid_volume *vol,
2301     struct g_raid_subdisk *sd, struct g_raid_disk *disk)
2302 {
2303 
2304 	if (sc->sc_stopping == G_RAID_DESTROY_HARD)
2305 		return;
2306 	if (sc->sc_md)
2307 		G_RAID_MD_WRITE(sc->sc_md, vol, sd, disk);
2308 }
2309 
2310 void g_raid_fail_disk(struct g_raid_softc *sc,
2311     struct g_raid_subdisk *sd, struct g_raid_disk *disk)
2312 {
2313 
2314 	if (disk == NULL)
2315 		disk = sd->sd_disk;
2316 	if (disk == NULL) {
2317 		G_RAID_DEBUG1(0, sc, "Warning! Fail request to an absent disk!");
2318 		return;
2319 	}
2320 	if (disk->d_state != G_RAID_DISK_S_ACTIVE) {
2321 		G_RAID_DEBUG1(0, sc, "Warning! Fail request to a disk in a "
2322 		    "wrong state (%s)!", g_raid_disk_state2str(disk->d_state));
2323 		return;
2324 	}
2325 	if (sc->sc_md)
2326 		G_RAID_MD_FAIL_DISK(sc->sc_md, sd, disk);
2327 }
2328 
2329 static void
2330 g_raid_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
2331     struct g_consumer *cp, struct g_provider *pp)
2332 {
2333 	struct g_raid_softc *sc;
2334 	struct g_raid_volume *vol;
2335 	struct g_raid_subdisk *sd;
2336 	struct g_raid_disk *disk;
2337 	int i, s;
2338 
2339 	g_topology_assert();
2340 
2341 	sc = gp->softc;
2342 	if (sc == NULL)
2343 		return;
2344 	if (pp != NULL) {
2345 		vol = pp->private;
2346 		g_topology_unlock();
2347 		sx_xlock(&sc->sc_lock);
2348 		sbuf_printf(sb, "%s<descr>%s %s volume</descr>\n", indent,
2349 		    sc->sc_md->mdo_class->name,
2350 		    g_raid_volume_level2str(vol->v_raid_level,
2351 		    vol->v_raid_level_qualifier));
2352 		sbuf_printf(sb, "%s<Label>%s</Label>\n", indent,
2353 		    vol->v_name);
2354 		sbuf_printf(sb, "%s<RAIDLevel>%s</RAIDLevel>\n", indent,
2355 		    g_raid_volume_level2str(vol->v_raid_level,
2356 		    vol->v_raid_level_qualifier));
2357 		sbuf_printf(sb,
2358 		    "%s<Transformation>%s</Transformation>\n", indent,
2359 		    vol->v_tr ? vol->v_tr->tro_class->name : "NONE");
2360 		sbuf_printf(sb, "%s<Components>%u</Components>\n", indent,
2361 		    vol->v_disks_count);
2362 		sbuf_printf(sb, "%s<Strip>%u</Strip>\n", indent,
2363 		    vol->v_strip_size);
2364 		sbuf_printf(sb, "%s<State>%s</State>\n", indent,
2365 		    g_raid_volume_state2str(vol->v_state));
2366 		sbuf_printf(sb, "%s<Dirty>%s</Dirty>\n", indent,
2367 		    vol->v_dirty ? "Yes" : "No");
2368 		sbuf_printf(sb, "%s<Subdisks>", indent);
2369 		for (i = 0; i < vol->v_disks_count; i++) {
2370 			sd = &vol->v_subdisks[i];
2371 			if (sd->sd_disk != NULL &&
2372 			    sd->sd_disk->d_consumer != NULL) {
2373 				sbuf_printf(sb, "%s ",
2374 				    g_raid_get_diskname(sd->sd_disk));
2375 			} else {
2376 				sbuf_cat(sb, "NONE ");
2377 			}
2378 			sbuf_printf(sb, "(%s",
2379 			    g_raid_subdisk_state2str(sd->sd_state));
2380 			if (sd->sd_state == G_RAID_SUBDISK_S_REBUILD ||
2381 			    sd->sd_state == G_RAID_SUBDISK_S_RESYNC) {
2382 				sbuf_printf(sb, " %d%%",
2383 				    (int)(sd->sd_rebuild_pos * 100 /
2384 				     sd->sd_size));
2385 			}
2386 			sbuf_cat(sb, ")");
2387 			if (i + 1 < vol->v_disks_count)
2388 				sbuf_cat(sb, ", ");
2389 		}
2390 		sbuf_cat(sb, "</Subdisks>\n");
2391 		sx_xunlock(&sc->sc_lock);
2392 		g_topology_lock();
2393 	} else if (cp != NULL) {
2394 		disk = cp->private;
2395 		if (disk == NULL)
2396 			return;
2397 		g_topology_unlock();
2398 		sx_xlock(&sc->sc_lock);
2399 		sbuf_printf(sb, "%s<State>%s", indent,
2400 		    g_raid_disk_state2str(disk->d_state));
2401 		if (!TAILQ_EMPTY(&disk->d_subdisks)) {
2402 			sbuf_cat(sb, " (");
2403 			TAILQ_FOREACH(sd, &disk->d_subdisks, sd_next) {
2404 				sbuf_printf(sb, "%s",
2405 				    g_raid_subdisk_state2str(sd->sd_state));
2406 				if (sd->sd_state == G_RAID_SUBDISK_S_REBUILD ||
2407 				    sd->sd_state == G_RAID_SUBDISK_S_RESYNC) {
2408 					sbuf_printf(sb, " %d%%",
2409 					    (int)(sd->sd_rebuild_pos * 100 /
2410 					     sd->sd_size));
2411 				}
2412 				if (TAILQ_NEXT(sd, sd_next))
2413 					sbuf_cat(sb, ", ");
2414 			}
2415 			sbuf_cat(sb, ")");
2416 		}
2417 		sbuf_cat(sb, "</State>\n");
2418 		sbuf_printf(sb, "%s<Subdisks>", indent);
2419 		TAILQ_FOREACH(sd, &disk->d_subdisks, sd_next) {
2420 			sbuf_printf(sb, "r%d(%s):%d@%ju",
2421 			    sd->sd_volume->v_global_id,
2422 			    sd->sd_volume->v_name,
2423 			    sd->sd_pos, (uintmax_t)sd->sd_offset);
2424 			if (TAILQ_NEXT(sd, sd_next))
2425 				sbuf_cat(sb, ", ");
2426 		}
2427 		sbuf_cat(sb, "</Subdisks>\n");
2428 		sbuf_printf(sb, "%s<ReadErrors>%d</ReadErrors>\n", indent,
2429 		    disk->d_read_errs);
2430 		sx_xunlock(&sc->sc_lock);
2431 		g_topology_lock();
2432 	} else {
2433 		g_topology_unlock();
2434 		sx_xlock(&sc->sc_lock);
2435 		if (sc->sc_md) {
2436 			sbuf_printf(sb, "%s<Metadata>%s</Metadata>\n", indent,
2437 			    sc->sc_md->mdo_class->name);
2438 		}
2439 		if (!TAILQ_EMPTY(&sc->sc_volumes)) {
2440 			s = 0xff;
2441 			TAILQ_FOREACH(vol, &sc->sc_volumes, v_next) {
2442 				if (vol->v_state < s)
2443 					s = vol->v_state;
2444 			}
2445 			sbuf_printf(sb, "%s<State>%s</State>\n", indent,
2446 			    g_raid_volume_state2str(s));
2447 		}
2448 		sx_xunlock(&sc->sc_lock);
2449 		g_topology_lock();
2450 	}
2451 }
2452 
2453 static void
2454 g_raid_shutdown_post_sync(void *arg, int howto)
2455 {
2456 	struct g_class *mp;
2457 	struct g_geom *gp, *gp2;
2458 	struct g_raid_softc *sc;
2459 	struct g_raid_volume *vol;
2460 
2461 	mp = arg;
2462 	g_topology_lock();
2463 	g_raid_shutdown = 1;
2464 	LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
2465 		if ((sc = gp->softc) == NULL)
2466 			continue;
2467 		g_topology_unlock();
2468 		sx_xlock(&sc->sc_lock);
2469 		TAILQ_FOREACH(vol, &sc->sc_volumes, v_next)
2470 			g_raid_clean(vol, -1);
2471 		g_cancel_event(sc);
2472 		g_raid_destroy(sc, G_RAID_DESTROY_DELAYED);
2473 		g_topology_lock();
2474 	}
2475 	g_topology_unlock();
2476 }
2477 
2478 static void
2479 g_raid_init(struct g_class *mp)
2480 {
2481 
2482 	g_raid_post_sync = EVENTHANDLER_REGISTER(shutdown_post_sync,
2483 	    g_raid_shutdown_post_sync, mp, SHUTDOWN_PRI_FIRST);
2484 	if (g_raid_post_sync == NULL)
2485 		G_RAID_DEBUG(0, "Warning! Cannot register shutdown event.");
2486 	g_raid_started = 1;
2487 }
2488 
2489 static void
2490 g_raid_fini(struct g_class *mp)
2491 {
2492 
2493 	if (g_raid_post_sync != NULL)
2494 		EVENTHANDLER_DEREGISTER(shutdown_post_sync, g_raid_post_sync);
2495 	g_raid_started = 0;
2496 }
2497 
2498 int
2499 g_raid_md_modevent(module_t mod, int type, void *arg)
2500 {
2501 	struct g_raid_md_class *class, *c, *nc;
2502 	int error;
2503 
2504 	error = 0;
2505 	class = arg;
2506 	switch (type) {
2507 	case MOD_LOAD:
2508 		c = LIST_FIRST(&g_raid_md_classes);
2509 		if (c == NULL || c->mdc_priority > class->mdc_priority)
2510 			LIST_INSERT_HEAD(&g_raid_md_classes, class, mdc_list);
2511 		else {
2512 			while ((nc = LIST_NEXT(c, mdc_list)) != NULL &&
2513 			    nc->mdc_priority < class->mdc_priority)
2514 				c = nc;
2515 			LIST_INSERT_AFTER(c, class, mdc_list);
2516 		}
2517 		if (g_raid_started)
2518 			g_retaste(&g_raid_class);
2519 		break;
2520 	case MOD_UNLOAD:
2521 		LIST_REMOVE(class, mdc_list);
2522 		break;
2523 	default:
2524 		error = EOPNOTSUPP;
2525 		break;
2526 	}
2527 
2528 	return (error);
2529 }
2530 
2531 int
2532 g_raid_tr_modevent(module_t mod, int type, void *arg)
2533 {
2534 	struct g_raid_tr_class *class, *c, *nc;
2535 	int error;
2536 
2537 	error = 0;
2538 	class = arg;
2539 	switch (type) {
2540 	case MOD_LOAD:
2541 		c = LIST_FIRST(&g_raid_tr_classes);
2542 		if (c == NULL || c->trc_priority > class->trc_priority)
2543 			LIST_INSERT_HEAD(&g_raid_tr_classes, class, trc_list);
2544 		else {
2545 			while ((nc = LIST_NEXT(c, trc_list)) != NULL &&
2546 			    nc->trc_priority < class->trc_priority)
2547 				c = nc;
2548 			LIST_INSERT_AFTER(c, class, trc_list);
2549 		}
2550 		break;
2551 	case MOD_UNLOAD:
2552 		LIST_REMOVE(class, trc_list);
2553 		break;
2554 	default:
2555 		error = EOPNOTSUPP;
2556 		break;
2557 	}
2558 
2559 	return (error);
2560 }
2561 
2562 /*
2563  * Use local implementation of DECLARE_GEOM_CLASS(g_raid_class, g_raid)
2564  * to reduce module priority, allowing submodules to register them first.
2565  */
2566 static moduledata_t g_raid_mod = {
2567 	"g_raid",
2568 	g_modevent,
2569 	&g_raid_class
2570 };
2571 DECLARE_MODULE(g_raid, g_raid_mod, SI_SUB_DRIVERS, SI_ORDER_THIRD);
2572 MODULE_VERSION(geom_raid, 0);
2573