xref: /freebsd/sys/geom/raid3/g_raid3.c (revision 73577bf01de5c4677dc54d97f93310286c254780)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2004-2006 Pawel Jakub Dawidek <pjd@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/raid3/g_raid3.h>
51 
52 FEATURE(geom_raid3, "GEOM RAID-3 functionality");
53 
54 static MALLOC_DEFINE(M_RAID3, "raid3_data", "GEOM_RAID3 Data");
55 
56 SYSCTL_DECL(_kern_geom);
57 static SYSCTL_NODE(_kern_geom, OID_AUTO, raid3, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
58     "GEOM_RAID3 stuff");
59 u_int g_raid3_debug = 0;
60 SYSCTL_UINT(_kern_geom_raid3, OID_AUTO, debug, CTLFLAG_RWTUN, &g_raid3_debug, 0,
61     "Debug level");
62 static u_int g_raid3_timeout = 4;
63 SYSCTL_UINT(_kern_geom_raid3, OID_AUTO, timeout, CTLFLAG_RWTUN, &g_raid3_timeout,
64     0, "Time to wait on all raid3 components");
65 static u_int g_raid3_idletime = 5;
66 SYSCTL_UINT(_kern_geom_raid3, OID_AUTO, idletime, CTLFLAG_RWTUN,
67     &g_raid3_idletime, 0, "Mark components as clean when idling");
68 static u_int g_raid3_disconnect_on_failure = 1;
69 SYSCTL_UINT(_kern_geom_raid3, OID_AUTO, disconnect_on_failure, CTLFLAG_RWTUN,
70     &g_raid3_disconnect_on_failure, 0, "Disconnect component on I/O failure.");
71 static u_int g_raid3_syncreqs = 2;
72 SYSCTL_UINT(_kern_geom_raid3, OID_AUTO, sync_requests, CTLFLAG_RDTUN,
73     &g_raid3_syncreqs, 0, "Parallel synchronization I/O requests.");
74 static u_int g_raid3_use_malloc = 0;
75 SYSCTL_UINT(_kern_geom_raid3, OID_AUTO, use_malloc, CTLFLAG_RDTUN,
76     &g_raid3_use_malloc, 0, "Use malloc(9) instead of uma(9).");
77 
78 static u_int g_raid3_n64k = 50;
79 SYSCTL_UINT(_kern_geom_raid3, OID_AUTO, n64k, CTLFLAG_RDTUN, &g_raid3_n64k, 0,
80     "Maximum number of 64kB allocations");
81 static u_int g_raid3_n16k = 200;
82 SYSCTL_UINT(_kern_geom_raid3, OID_AUTO, n16k, CTLFLAG_RDTUN, &g_raid3_n16k, 0,
83     "Maximum number of 16kB allocations");
84 static u_int g_raid3_n4k = 1200;
85 SYSCTL_UINT(_kern_geom_raid3, OID_AUTO, n4k, CTLFLAG_RDTUN, &g_raid3_n4k, 0,
86     "Maximum number of 4kB allocations");
87 
88 static SYSCTL_NODE(_kern_geom_raid3, OID_AUTO, stat,
89     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
90     "GEOM_RAID3 statistics");
91 static u_int g_raid3_parity_mismatch = 0;
92 SYSCTL_UINT(_kern_geom_raid3_stat, OID_AUTO, parity_mismatch, CTLFLAG_RD,
93     &g_raid3_parity_mismatch, 0, "Number of failures in VERIFY mode");
94 
95 #define	MSLEEP(ident, mtx, priority, wmesg, timeout)	do {		\
96 	G_RAID3_DEBUG(4, "%s: Sleeping %p.", __func__, (ident));	\
97 	msleep((ident), (mtx), (priority), (wmesg), (timeout));		\
98 	G_RAID3_DEBUG(4, "%s: Woken up %p.", __func__, (ident));	\
99 } while (0)
100 
101 static eventhandler_tag g_raid3_post_sync = NULL;
102 static int g_raid3_shutdown = 0;
103 
104 static int g_raid3_destroy_geom(struct gctl_req *req, struct g_class *mp,
105     struct g_geom *gp);
106 static g_taste_t g_raid3_taste;
107 static void g_raid3_init(struct g_class *mp);
108 static void g_raid3_fini(struct g_class *mp);
109 
110 struct g_class g_raid3_class = {
111 	.name = G_RAID3_CLASS_NAME,
112 	.version = G_VERSION,
113 	.ctlreq = g_raid3_config,
114 	.taste = g_raid3_taste,
115 	.destroy_geom = g_raid3_destroy_geom,
116 	.init = g_raid3_init,
117 	.fini = g_raid3_fini
118 };
119 
120 static void g_raid3_destroy_provider(struct g_raid3_softc *sc);
121 static int g_raid3_update_disk(struct g_raid3_disk *disk, u_int state);
122 static void g_raid3_update_device(struct g_raid3_softc *sc, boolean_t force);
123 static void g_raid3_dumpconf(struct sbuf *sb, const char *indent,
124     struct g_geom *gp, struct g_consumer *cp, struct g_provider *pp);
125 static void g_raid3_sync_stop(struct g_raid3_softc *sc, int type);
126 static int g_raid3_register_request(struct bio *pbp);
127 static void g_raid3_sync_release(struct g_raid3_softc *sc);
128 
129 static const char *
130 g_raid3_disk_state2str(int state)
131 {
132 
133 	switch (state) {
134 	case G_RAID3_DISK_STATE_NODISK:
135 		return ("NODISK");
136 	case G_RAID3_DISK_STATE_NONE:
137 		return ("NONE");
138 	case G_RAID3_DISK_STATE_NEW:
139 		return ("NEW");
140 	case G_RAID3_DISK_STATE_ACTIVE:
141 		return ("ACTIVE");
142 	case G_RAID3_DISK_STATE_STALE:
143 		return ("STALE");
144 	case G_RAID3_DISK_STATE_SYNCHRONIZING:
145 		return ("SYNCHRONIZING");
146 	case G_RAID3_DISK_STATE_DISCONNECTED:
147 		return ("DISCONNECTED");
148 	default:
149 		return ("INVALID");
150 	}
151 }
152 
153 static const char *
154 g_raid3_device_state2str(int state)
155 {
156 
157 	switch (state) {
158 	case G_RAID3_DEVICE_STATE_STARTING:
159 		return ("STARTING");
160 	case G_RAID3_DEVICE_STATE_DEGRADED:
161 		return ("DEGRADED");
162 	case G_RAID3_DEVICE_STATE_COMPLETE:
163 		return ("COMPLETE");
164 	default:
165 		return ("INVALID");
166 	}
167 }
168 
169 const char *
170 g_raid3_get_diskname(struct g_raid3_disk *disk)
171 {
172 
173 	if (disk->d_consumer == NULL || disk->d_consumer->provider == NULL)
174 		return ("[unknown]");
175 	return (disk->d_name);
176 }
177 
178 static void *
179 g_raid3_alloc(struct g_raid3_softc *sc, size_t size, int flags)
180 {
181 	void *ptr;
182 	enum g_raid3_zones zone;
183 
184 	if (g_raid3_use_malloc ||
185 	    (zone = g_raid3_zone(size)) == G_RAID3_NUM_ZONES)
186 		ptr = malloc(size, M_RAID3, flags);
187 	else {
188 		ptr = uma_zalloc_arg(sc->sc_zones[zone].sz_zone,
189 		   &sc->sc_zones[zone], flags);
190 		sc->sc_zones[zone].sz_requested++;
191 		if (ptr == NULL)
192 			sc->sc_zones[zone].sz_failed++;
193 	}
194 	return (ptr);
195 }
196 
197 static void
198 g_raid3_free(struct g_raid3_softc *sc, void *ptr, size_t size)
199 {
200 	enum g_raid3_zones zone;
201 
202 	if (g_raid3_use_malloc ||
203 	    (zone = g_raid3_zone(size)) == G_RAID3_NUM_ZONES)
204 		free(ptr, M_RAID3);
205 	else {
206 		uma_zfree_arg(sc->sc_zones[zone].sz_zone,
207 		    ptr, &sc->sc_zones[zone]);
208 	}
209 }
210 
211 static int
212 g_raid3_uma_ctor(void *mem, int size, void *arg, int flags)
213 {
214 	struct g_raid3_zone *sz = arg;
215 
216 	if (sz->sz_max > 0 && sz->sz_inuse == sz->sz_max)
217 		return (ENOMEM);
218 	sz->sz_inuse++;
219 	return (0);
220 }
221 
222 static void
223 g_raid3_uma_dtor(void *mem, int size, void *arg)
224 {
225 	struct g_raid3_zone *sz = arg;
226 
227 	sz->sz_inuse--;
228 }
229 
230 #define	g_raid3_xor(src, dst, size)					\
231 	_g_raid3_xor((uint64_t *)(src),					\
232 	    (uint64_t *)(dst), (size_t)size)
233 static void
234 _g_raid3_xor(uint64_t *src, uint64_t *dst, size_t size)
235 {
236 
237 	KASSERT((size % 128) == 0, ("Invalid size: %zu.", size));
238 	for (; size > 0; size -= 128) {
239 		*dst++ ^= (*src++);
240 		*dst++ ^= (*src++);
241 		*dst++ ^= (*src++);
242 		*dst++ ^= (*src++);
243 		*dst++ ^= (*src++);
244 		*dst++ ^= (*src++);
245 		*dst++ ^= (*src++);
246 		*dst++ ^= (*src++);
247 		*dst++ ^= (*src++);
248 		*dst++ ^= (*src++);
249 		*dst++ ^= (*src++);
250 		*dst++ ^= (*src++);
251 		*dst++ ^= (*src++);
252 		*dst++ ^= (*src++);
253 		*dst++ ^= (*src++);
254 		*dst++ ^= (*src++);
255 	}
256 }
257 
258 static int
259 g_raid3_is_zero(struct bio *bp)
260 {
261 	static const uint64_t zeros[] = {
262 	    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
263 	};
264 	u_char *addr;
265 	ssize_t size;
266 
267 	size = bp->bio_length;
268 	addr = (u_char *)bp->bio_data;
269 	for (; size > 0; size -= sizeof(zeros), addr += sizeof(zeros)) {
270 		if (bcmp(addr, zeros, sizeof(zeros)) != 0)
271 			return (0);
272 	}
273 	return (1);
274 }
275 
276 /*
277  * --- Events handling functions ---
278  * Events in geom_raid3 are used to maintain disks and device status
279  * from one thread to simplify locking.
280  */
281 static void
282 g_raid3_event_free(struct g_raid3_event *ep)
283 {
284 
285 	free(ep, M_RAID3);
286 }
287 
288 int
289 g_raid3_event_send(void *arg, int state, int flags)
290 {
291 	struct g_raid3_softc *sc;
292 	struct g_raid3_disk *disk;
293 	struct g_raid3_event *ep;
294 	int error;
295 
296 	ep = malloc(sizeof(*ep), M_RAID3, M_WAITOK);
297 	G_RAID3_DEBUG(4, "%s: Sending event %p.", __func__, ep);
298 	if ((flags & G_RAID3_EVENT_DEVICE) != 0) {
299 		disk = NULL;
300 		sc = arg;
301 	} else {
302 		disk = arg;
303 		sc = disk->d_softc;
304 	}
305 	ep->e_disk = disk;
306 	ep->e_state = state;
307 	ep->e_flags = flags;
308 	ep->e_error = 0;
309 	mtx_lock(&sc->sc_events_mtx);
310 	TAILQ_INSERT_TAIL(&sc->sc_events, ep, e_next);
311 	mtx_unlock(&sc->sc_events_mtx);
312 	G_RAID3_DEBUG(4, "%s: Waking up %p.", __func__, sc);
313 	mtx_lock(&sc->sc_queue_mtx);
314 	wakeup(sc);
315 	wakeup(&sc->sc_queue);
316 	mtx_unlock(&sc->sc_queue_mtx);
317 	if ((flags & G_RAID3_EVENT_DONTWAIT) != 0)
318 		return (0);
319 	sx_assert(&sc->sc_lock, SX_XLOCKED);
320 	G_RAID3_DEBUG(4, "%s: Sleeping %p.", __func__, ep);
321 	sx_xunlock(&sc->sc_lock);
322 	while ((ep->e_flags & G_RAID3_EVENT_DONE) == 0) {
323 		mtx_lock(&sc->sc_events_mtx);
324 		MSLEEP(ep, &sc->sc_events_mtx, PRIBIO | PDROP, "r3:event",
325 		    hz * 5);
326 	}
327 	error = ep->e_error;
328 	g_raid3_event_free(ep);
329 	sx_xlock(&sc->sc_lock);
330 	return (error);
331 }
332 
333 static struct g_raid3_event *
334 g_raid3_event_get(struct g_raid3_softc *sc)
335 {
336 	struct g_raid3_event *ep;
337 
338 	mtx_lock(&sc->sc_events_mtx);
339 	ep = TAILQ_FIRST(&sc->sc_events);
340 	mtx_unlock(&sc->sc_events_mtx);
341 	return (ep);
342 }
343 
344 static void
345 g_raid3_event_remove(struct g_raid3_softc *sc, struct g_raid3_event *ep)
346 {
347 
348 	mtx_lock(&sc->sc_events_mtx);
349 	TAILQ_REMOVE(&sc->sc_events, ep, e_next);
350 	mtx_unlock(&sc->sc_events_mtx);
351 }
352 
353 static void
354 g_raid3_event_cancel(struct g_raid3_disk *disk)
355 {
356 	struct g_raid3_softc *sc;
357 	struct g_raid3_event *ep, *tmpep;
358 
359 	sc = disk->d_softc;
360 	sx_assert(&sc->sc_lock, SX_XLOCKED);
361 
362 	mtx_lock(&sc->sc_events_mtx);
363 	TAILQ_FOREACH_SAFE(ep, &sc->sc_events, e_next, tmpep) {
364 		if ((ep->e_flags & G_RAID3_EVENT_DEVICE) != 0)
365 			continue;
366 		if (ep->e_disk != disk)
367 			continue;
368 		TAILQ_REMOVE(&sc->sc_events, ep, e_next);
369 		if ((ep->e_flags & G_RAID3_EVENT_DONTWAIT) != 0)
370 			g_raid3_event_free(ep);
371 		else {
372 			ep->e_error = ECANCELED;
373 			wakeup(ep);
374 		}
375 	}
376 	mtx_unlock(&sc->sc_events_mtx);
377 }
378 
379 /*
380  * Return the number of disks in the given state.
381  * If state is equal to -1, count all connected disks.
382  */
383 u_int
384 g_raid3_ndisks(struct g_raid3_softc *sc, int state)
385 {
386 	struct g_raid3_disk *disk;
387 	u_int n, ndisks;
388 
389 	sx_assert(&sc->sc_lock, SX_LOCKED);
390 
391 	for (n = ndisks = 0; n < sc->sc_ndisks; n++) {
392 		disk = &sc->sc_disks[n];
393 		if (disk->d_state == G_RAID3_DISK_STATE_NODISK)
394 			continue;
395 		if (state == -1 || disk->d_state == state)
396 			ndisks++;
397 	}
398 	return (ndisks);
399 }
400 
401 static u_int
402 g_raid3_nrequests(struct g_raid3_softc *sc, struct g_consumer *cp)
403 {
404 	struct bio *bp;
405 	u_int nreqs = 0;
406 
407 	mtx_lock(&sc->sc_queue_mtx);
408 	TAILQ_FOREACH(bp, &sc->sc_queue.queue, bio_queue) {
409 		if (bp->bio_from == cp)
410 			nreqs++;
411 	}
412 	mtx_unlock(&sc->sc_queue_mtx);
413 	return (nreqs);
414 }
415 
416 static int
417 g_raid3_is_busy(struct g_raid3_softc *sc, struct g_consumer *cp)
418 {
419 
420 	if (cp->index > 0) {
421 		G_RAID3_DEBUG(2,
422 		    "I/O requests for %s exist, can't destroy it now.",
423 		    cp->provider->name);
424 		return (1);
425 	}
426 	if (g_raid3_nrequests(sc, cp) > 0) {
427 		G_RAID3_DEBUG(2,
428 		    "I/O requests for %s in queue, can't destroy it now.",
429 		    cp->provider->name);
430 		return (1);
431 	}
432 	return (0);
433 }
434 
435 static void
436 g_raid3_destroy_consumer(void *arg, int flags __unused)
437 {
438 	struct g_consumer *cp;
439 
440 	g_topology_assert();
441 
442 	cp = arg;
443 	G_RAID3_DEBUG(1, "Consumer %s destroyed.", cp->provider->name);
444 	g_detach(cp);
445 	g_destroy_consumer(cp);
446 }
447 
448 static void
449 g_raid3_kill_consumer(struct g_raid3_softc *sc, struct g_consumer *cp)
450 {
451 	struct g_provider *pp;
452 	int retaste_wait;
453 
454 	g_topology_assert();
455 
456 	cp->private = NULL;
457 	if (g_raid3_is_busy(sc, cp))
458 		return;
459 	G_RAID3_DEBUG(2, "Consumer %s destroyed.", cp->provider->name);
460 	pp = cp->provider;
461 	retaste_wait = 0;
462 	if (cp->acw == 1) {
463 		if ((pp->geom->flags & G_GEOM_WITHER) == 0)
464 			retaste_wait = 1;
465 	}
466 	G_RAID3_DEBUG(2, "Access %s r%dw%de%d = %d", pp->name, -cp->acr,
467 	    -cp->acw, -cp->ace, 0);
468 	if (cp->acr > 0 || cp->acw > 0 || cp->ace > 0)
469 		g_access(cp, -cp->acr, -cp->acw, -cp->ace);
470 	if (retaste_wait) {
471 		/*
472 		 * After retaste event was send (inside g_access()), we can send
473 		 * event to detach and destroy consumer.
474 		 * A class, which has consumer to the given provider connected
475 		 * will not receive retaste event for the provider.
476 		 * This is the way how I ignore retaste events when I close
477 		 * consumers opened for write: I detach and destroy consumer
478 		 * after retaste event is sent.
479 		 */
480 		g_post_event(g_raid3_destroy_consumer, cp, M_WAITOK, NULL);
481 		return;
482 	}
483 	G_RAID3_DEBUG(1, "Consumer %s destroyed.", pp->name);
484 	g_detach(cp);
485 	g_destroy_consumer(cp);
486 }
487 
488 static int
489 g_raid3_connect_disk(struct g_raid3_disk *disk, struct g_provider *pp)
490 {
491 	struct g_consumer *cp;
492 	int error;
493 
494 	g_topology_assert_not();
495 	KASSERT(disk->d_consumer == NULL,
496 	    ("Disk already connected (device %s).", disk->d_softc->sc_name));
497 
498 	g_topology_lock();
499 	cp = g_new_consumer(disk->d_softc->sc_geom);
500 	error = g_attach(cp, pp);
501 	if (error != 0) {
502 		g_destroy_consumer(cp);
503 		g_topology_unlock();
504 		return (error);
505 	}
506 	error = g_access(cp, 1, 1, 1);
507 		g_topology_unlock();
508 	if (error != 0) {
509 		g_detach(cp);
510 		g_destroy_consumer(cp);
511 		G_RAID3_DEBUG(0, "Cannot open consumer %s (error=%d).",
512 		    pp->name, error);
513 		return (error);
514 	}
515 	disk->d_consumer = cp;
516 	disk->d_consumer->private = disk;
517 	disk->d_consumer->index = 0;
518 	G_RAID3_DEBUG(2, "Disk %s connected.", g_raid3_get_diskname(disk));
519 	return (0);
520 }
521 
522 static void
523 g_raid3_disconnect_consumer(struct g_raid3_softc *sc, struct g_consumer *cp)
524 {
525 
526 	g_topology_assert();
527 
528 	if (cp == NULL)
529 		return;
530 	if (cp->provider != NULL)
531 		g_raid3_kill_consumer(sc, cp);
532 	else
533 		g_destroy_consumer(cp);
534 }
535 
536 /*
537  * Initialize disk. This means allocate memory, create consumer, attach it
538  * to the provider and open access (r1w1e1) to it.
539  */
540 static struct g_raid3_disk *
541 g_raid3_init_disk(struct g_raid3_softc *sc, struct g_provider *pp,
542     struct g_raid3_metadata *md, int *errorp)
543 {
544 	struct g_raid3_disk *disk;
545 	int error;
546 
547 	disk = &sc->sc_disks[md->md_no];
548 	error = g_raid3_connect_disk(disk, pp);
549 	if (error != 0) {
550 		if (errorp != NULL)
551 			*errorp = error;
552 		return (NULL);
553 	}
554 	disk->d_state = G_RAID3_DISK_STATE_NONE;
555 	disk->d_flags = md->md_dflags;
556 	if (md->md_provider[0] != '\0')
557 		disk->d_flags |= G_RAID3_DISK_FLAG_HARDCODED;
558 	disk->d_sync.ds_consumer = NULL;
559 	disk->d_sync.ds_offset = md->md_sync_offset;
560 	disk->d_sync.ds_offset_done = md->md_sync_offset;
561 	disk->d_genid = md->md_genid;
562 	disk->d_sync.ds_syncid = md->md_syncid;
563 	if (errorp != NULL)
564 		*errorp = 0;
565 	return (disk);
566 }
567 
568 static void
569 g_raid3_destroy_disk(struct g_raid3_disk *disk)
570 {
571 	struct g_raid3_softc *sc;
572 
573 	g_topology_assert_not();
574 	sc = disk->d_softc;
575 	sx_assert(&sc->sc_lock, SX_XLOCKED);
576 
577 	if (disk->d_state == G_RAID3_DISK_STATE_NODISK)
578 		return;
579 	g_raid3_event_cancel(disk);
580 	switch (disk->d_state) {
581 	case G_RAID3_DISK_STATE_SYNCHRONIZING:
582 		if (sc->sc_syncdisk != NULL)
583 			g_raid3_sync_stop(sc, 1);
584 		/* FALLTHROUGH */
585 	case G_RAID3_DISK_STATE_NEW:
586 	case G_RAID3_DISK_STATE_STALE:
587 	case G_RAID3_DISK_STATE_ACTIVE:
588 		g_topology_lock();
589 		g_raid3_disconnect_consumer(sc, disk->d_consumer);
590 		g_topology_unlock();
591 		disk->d_consumer = NULL;
592 		break;
593 	default:
594 		KASSERT(0 == 1, ("Wrong disk state (%s, %s).",
595 		    g_raid3_get_diskname(disk),
596 		    g_raid3_disk_state2str(disk->d_state)));
597 	}
598 	disk->d_state = G_RAID3_DISK_STATE_NODISK;
599 }
600 
601 static void
602 g_raid3_destroy_device(struct g_raid3_softc *sc)
603 {
604 	struct g_raid3_event *ep;
605 	struct g_raid3_disk *disk;
606 	struct g_geom *gp;
607 	struct g_consumer *cp;
608 	u_int n;
609 
610 	g_topology_assert_not();
611 	sx_assert(&sc->sc_lock, SX_XLOCKED);
612 
613 	gp = sc->sc_geom;
614 	if (sc->sc_provider != NULL)
615 		g_raid3_destroy_provider(sc);
616 	for (n = 0; n < sc->sc_ndisks; n++) {
617 		disk = &sc->sc_disks[n];
618 		if (disk->d_state != G_RAID3_DISK_STATE_NODISK) {
619 			disk->d_flags &= ~G_RAID3_DISK_FLAG_DIRTY;
620 			g_raid3_update_metadata(disk);
621 			g_raid3_destroy_disk(disk);
622 		}
623 	}
624 	while ((ep = g_raid3_event_get(sc)) != NULL) {
625 		g_raid3_event_remove(sc, ep);
626 		if ((ep->e_flags & G_RAID3_EVENT_DONTWAIT) != 0)
627 			g_raid3_event_free(ep);
628 		else {
629 			ep->e_error = ECANCELED;
630 			ep->e_flags |= G_RAID3_EVENT_DONE;
631 			G_RAID3_DEBUG(4, "%s: Waking up %p.", __func__, ep);
632 			mtx_lock(&sc->sc_events_mtx);
633 			wakeup(ep);
634 			mtx_unlock(&sc->sc_events_mtx);
635 		}
636 	}
637 	callout_drain(&sc->sc_callout);
638 	cp = LIST_FIRST(&sc->sc_sync.ds_geom->consumer);
639 	g_topology_lock();
640 	if (cp != NULL)
641 		g_raid3_disconnect_consumer(sc, cp);
642 	g_wither_geom(sc->sc_sync.ds_geom, ENXIO);
643 	G_RAID3_DEBUG(0, "Device %s destroyed.", gp->name);
644 	g_wither_geom(gp, ENXIO);
645 	g_topology_unlock();
646 	if (!g_raid3_use_malloc) {
647 		uma_zdestroy(sc->sc_zones[G_RAID3_ZONE_64K].sz_zone);
648 		uma_zdestroy(sc->sc_zones[G_RAID3_ZONE_16K].sz_zone);
649 		uma_zdestroy(sc->sc_zones[G_RAID3_ZONE_4K].sz_zone);
650 	}
651 	mtx_destroy(&sc->sc_queue_mtx);
652 	mtx_destroy(&sc->sc_events_mtx);
653 	sx_xunlock(&sc->sc_lock);
654 	sx_destroy(&sc->sc_lock);
655 }
656 
657 static void
658 g_raid3_orphan(struct g_consumer *cp)
659 {
660 	struct g_raid3_disk *disk;
661 
662 	g_topology_assert();
663 
664 	disk = cp->private;
665 	if (disk == NULL)
666 		return;
667 	disk->d_softc->sc_bump_id = G_RAID3_BUMP_SYNCID;
668 	g_raid3_event_send(disk, G_RAID3_DISK_STATE_DISCONNECTED,
669 	    G_RAID3_EVENT_DONTWAIT);
670 }
671 
672 static int
673 g_raid3_write_metadata(struct g_raid3_disk *disk, struct g_raid3_metadata *md)
674 {
675 	struct g_raid3_softc *sc;
676 	struct g_consumer *cp;
677 	off_t offset, length;
678 	u_char *sector;
679 	int error = 0;
680 
681 	g_topology_assert_not();
682 	sc = disk->d_softc;
683 	sx_assert(&sc->sc_lock, SX_LOCKED);
684 
685 	cp = disk->d_consumer;
686 	KASSERT(cp != NULL, ("NULL consumer (%s).", sc->sc_name));
687 	KASSERT(cp->provider != NULL, ("NULL provider (%s).", sc->sc_name));
688 	KASSERT(cp->acr >= 1 && cp->acw >= 1 && cp->ace >= 1,
689 	    ("Consumer %s closed? (r%dw%de%d).", cp->provider->name, cp->acr,
690 	    cp->acw, cp->ace));
691 	length = cp->provider->sectorsize;
692 	offset = cp->provider->mediasize - length;
693 	sector = malloc((size_t)length, M_RAID3, M_WAITOK | M_ZERO);
694 	if (md != NULL)
695 		raid3_metadata_encode(md, sector);
696 	error = g_write_data(cp, offset, sector, length);
697 	free(sector, M_RAID3);
698 	if (error != 0) {
699 		if ((disk->d_flags & G_RAID3_DISK_FLAG_BROKEN) == 0) {
700 			G_RAID3_DEBUG(0, "Cannot write metadata on %s "
701 			    "(device=%s, error=%d).",
702 			    g_raid3_get_diskname(disk), sc->sc_name, error);
703 			disk->d_flags |= G_RAID3_DISK_FLAG_BROKEN;
704 		} else {
705 			G_RAID3_DEBUG(1, "Cannot write metadata on %s "
706 			    "(device=%s, error=%d).",
707 			    g_raid3_get_diskname(disk), sc->sc_name, error);
708 		}
709 		if (g_raid3_disconnect_on_failure &&
710 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE) {
711 			sc->sc_bump_id |= G_RAID3_BUMP_GENID;
712 			g_raid3_event_send(disk,
713 			    G_RAID3_DISK_STATE_DISCONNECTED,
714 			    G_RAID3_EVENT_DONTWAIT);
715 		}
716 	}
717 	return (error);
718 }
719 
720 int
721 g_raid3_clear_metadata(struct g_raid3_disk *disk)
722 {
723 	int error;
724 
725 	g_topology_assert_not();
726 	sx_assert(&disk->d_softc->sc_lock, SX_LOCKED);
727 
728 	error = g_raid3_write_metadata(disk, NULL);
729 	if (error == 0) {
730 		G_RAID3_DEBUG(2, "Metadata on %s cleared.",
731 		    g_raid3_get_diskname(disk));
732 	} else {
733 		G_RAID3_DEBUG(0,
734 		    "Cannot clear metadata on disk %s (error=%d).",
735 		    g_raid3_get_diskname(disk), error);
736 	}
737 	return (error);
738 }
739 
740 void
741 g_raid3_fill_metadata(struct g_raid3_disk *disk, struct g_raid3_metadata *md)
742 {
743 	struct g_raid3_softc *sc;
744 	struct g_provider *pp;
745 
746 	sc = disk->d_softc;
747 	strlcpy(md->md_magic, G_RAID3_MAGIC, sizeof(md->md_magic));
748 	md->md_version = G_RAID3_VERSION;
749 	strlcpy(md->md_name, sc->sc_name, sizeof(md->md_name));
750 	md->md_id = sc->sc_id;
751 	md->md_all = sc->sc_ndisks;
752 	md->md_genid = sc->sc_genid;
753 	md->md_mediasize = sc->sc_mediasize;
754 	md->md_sectorsize = sc->sc_sectorsize;
755 	md->md_mflags = (sc->sc_flags & G_RAID3_DEVICE_FLAG_MASK);
756 	md->md_no = disk->d_no;
757 	md->md_syncid = disk->d_sync.ds_syncid;
758 	md->md_dflags = (disk->d_flags & G_RAID3_DISK_FLAG_MASK);
759 	if (disk->d_state != G_RAID3_DISK_STATE_SYNCHRONIZING)
760 		md->md_sync_offset = 0;
761 	else {
762 		md->md_sync_offset =
763 		    disk->d_sync.ds_offset_done / (sc->sc_ndisks - 1);
764 	}
765 	if (disk->d_consumer != NULL && disk->d_consumer->provider != NULL)
766 		pp = disk->d_consumer->provider;
767 	else
768 		pp = NULL;
769 	if ((disk->d_flags & G_RAID3_DISK_FLAG_HARDCODED) != 0 && pp != NULL)
770 		strlcpy(md->md_provider, pp->name, sizeof(md->md_provider));
771 	else
772 		bzero(md->md_provider, sizeof(md->md_provider));
773 	if (pp != NULL)
774 		md->md_provsize = pp->mediasize;
775 	else
776 		md->md_provsize = 0;
777 }
778 
779 void
780 g_raid3_update_metadata(struct g_raid3_disk *disk)
781 {
782 	struct g_raid3_softc *sc;
783 	struct g_raid3_metadata md;
784 	int error;
785 
786 	g_topology_assert_not();
787 	sc = disk->d_softc;
788 	sx_assert(&sc->sc_lock, SX_LOCKED);
789 
790 	g_raid3_fill_metadata(disk, &md);
791 	error = g_raid3_write_metadata(disk, &md);
792 	if (error == 0) {
793 		G_RAID3_DEBUG(2, "Metadata on %s updated.",
794 		    g_raid3_get_diskname(disk));
795 	} else {
796 		G_RAID3_DEBUG(0,
797 		    "Cannot update metadata on disk %s (error=%d).",
798 		    g_raid3_get_diskname(disk), error);
799 	}
800 }
801 
802 static void
803 g_raid3_bump_syncid(struct g_raid3_softc *sc)
804 {
805 	struct g_raid3_disk *disk;
806 	u_int n;
807 
808 	g_topology_assert_not();
809 	sx_assert(&sc->sc_lock, SX_XLOCKED);
810 	KASSERT(g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE) > 0,
811 	    ("%s called with no active disks (device=%s).", __func__,
812 	    sc->sc_name));
813 
814 	sc->sc_syncid++;
815 	G_RAID3_DEBUG(1, "Device %s: syncid bumped to %u.", sc->sc_name,
816 	    sc->sc_syncid);
817 	for (n = 0; n < sc->sc_ndisks; n++) {
818 		disk = &sc->sc_disks[n];
819 		if (disk->d_state == G_RAID3_DISK_STATE_ACTIVE ||
820 		    disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING) {
821 			disk->d_sync.ds_syncid = sc->sc_syncid;
822 			g_raid3_update_metadata(disk);
823 		}
824 	}
825 }
826 
827 static void
828 g_raid3_bump_genid(struct g_raid3_softc *sc)
829 {
830 	struct g_raid3_disk *disk;
831 	u_int n;
832 
833 	g_topology_assert_not();
834 	sx_assert(&sc->sc_lock, SX_XLOCKED);
835 	KASSERT(g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE) > 0,
836 	    ("%s called with no active disks (device=%s).", __func__,
837 	    sc->sc_name));
838 
839 	sc->sc_genid++;
840 	G_RAID3_DEBUG(1, "Device %s: genid bumped to %u.", sc->sc_name,
841 	    sc->sc_genid);
842 	for (n = 0; n < sc->sc_ndisks; n++) {
843 		disk = &sc->sc_disks[n];
844 		if (disk->d_state == G_RAID3_DISK_STATE_ACTIVE ||
845 		    disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING) {
846 			disk->d_genid = sc->sc_genid;
847 			g_raid3_update_metadata(disk);
848 		}
849 	}
850 }
851 
852 static int
853 g_raid3_idle(struct g_raid3_softc *sc, int acw)
854 {
855 	struct g_raid3_disk *disk;
856 	u_int i;
857 	int timeout;
858 
859 	g_topology_assert_not();
860 	sx_assert(&sc->sc_lock, SX_XLOCKED);
861 
862 	if (sc->sc_provider == NULL)
863 		return (0);
864 	if ((sc->sc_flags & G_RAID3_DEVICE_FLAG_NOFAILSYNC) != 0)
865 		return (0);
866 	if (sc->sc_idle)
867 		return (0);
868 	if (sc->sc_writes > 0)
869 		return (0);
870 	if (acw > 0 || (acw == -1 && sc->sc_provider->acw > 0)) {
871 		timeout = g_raid3_idletime - (time_uptime - sc->sc_last_write);
872 		if (!g_raid3_shutdown && timeout > 0)
873 			return (timeout);
874 	}
875 	sc->sc_idle = 1;
876 	for (i = 0; i < sc->sc_ndisks; i++) {
877 		disk = &sc->sc_disks[i];
878 		if (disk->d_state != G_RAID3_DISK_STATE_ACTIVE)
879 			continue;
880 		G_RAID3_DEBUG(1, "Disk %s (device %s) marked as clean.",
881 		    g_raid3_get_diskname(disk), sc->sc_name);
882 		disk->d_flags &= ~G_RAID3_DISK_FLAG_DIRTY;
883 		g_raid3_update_metadata(disk);
884 	}
885 	return (0);
886 }
887 
888 static void
889 g_raid3_unidle(struct g_raid3_softc *sc)
890 {
891 	struct g_raid3_disk *disk;
892 	u_int i;
893 
894 	g_topology_assert_not();
895 	sx_assert(&sc->sc_lock, SX_XLOCKED);
896 
897 	if ((sc->sc_flags & G_RAID3_DEVICE_FLAG_NOFAILSYNC) != 0)
898 		return;
899 	sc->sc_idle = 0;
900 	sc->sc_last_write = time_uptime;
901 	for (i = 0; i < sc->sc_ndisks; i++) {
902 		disk = &sc->sc_disks[i];
903 		if (disk->d_state != G_RAID3_DISK_STATE_ACTIVE)
904 			continue;
905 		G_RAID3_DEBUG(1, "Disk %s (device %s) marked as dirty.",
906 		    g_raid3_get_diskname(disk), sc->sc_name);
907 		disk->d_flags |= G_RAID3_DISK_FLAG_DIRTY;
908 		g_raid3_update_metadata(disk);
909 	}
910 }
911 
912 /*
913  * Treat bio_driver1 field in parent bio as list head and field bio_caller1
914  * in child bio as pointer to the next element on the list.
915  */
916 #define	G_RAID3_HEAD_BIO(pbp)	(pbp)->bio_driver1
917 
918 #define	G_RAID3_NEXT_BIO(cbp)	(cbp)->bio_caller1
919 
920 #define	G_RAID3_FOREACH_BIO(pbp, bp)					\
921 	for ((bp) = G_RAID3_HEAD_BIO(pbp); (bp) != NULL;		\
922 	    (bp) = G_RAID3_NEXT_BIO(bp))
923 
924 #define	G_RAID3_FOREACH_SAFE_BIO(pbp, bp, tmpbp)			\
925 	for ((bp) = G_RAID3_HEAD_BIO(pbp);				\
926 	    (bp) != NULL && ((tmpbp) = G_RAID3_NEXT_BIO(bp), 1);	\
927 	    (bp) = (tmpbp))
928 
929 static void
930 g_raid3_init_bio(struct bio *pbp)
931 {
932 
933 	G_RAID3_HEAD_BIO(pbp) = NULL;
934 }
935 
936 static void
937 g_raid3_remove_bio(struct bio *cbp)
938 {
939 	struct bio *pbp, *bp;
940 
941 	pbp = cbp->bio_parent;
942 	if (G_RAID3_HEAD_BIO(pbp) == cbp)
943 		G_RAID3_HEAD_BIO(pbp) = G_RAID3_NEXT_BIO(cbp);
944 	else {
945 		G_RAID3_FOREACH_BIO(pbp, bp) {
946 			if (G_RAID3_NEXT_BIO(bp) == cbp) {
947 				G_RAID3_NEXT_BIO(bp) = G_RAID3_NEXT_BIO(cbp);
948 				break;
949 			}
950 		}
951 	}
952 	G_RAID3_NEXT_BIO(cbp) = NULL;
953 }
954 
955 static void
956 g_raid3_replace_bio(struct bio *sbp, struct bio *dbp)
957 {
958 	struct bio *pbp, *bp;
959 
960 	g_raid3_remove_bio(sbp);
961 	pbp = dbp->bio_parent;
962 	G_RAID3_NEXT_BIO(sbp) = G_RAID3_NEXT_BIO(dbp);
963 	if (G_RAID3_HEAD_BIO(pbp) == dbp)
964 		G_RAID3_HEAD_BIO(pbp) = sbp;
965 	else {
966 		G_RAID3_FOREACH_BIO(pbp, bp) {
967 			if (G_RAID3_NEXT_BIO(bp) == dbp) {
968 				G_RAID3_NEXT_BIO(bp) = sbp;
969 				break;
970 			}
971 		}
972 	}
973 	G_RAID3_NEXT_BIO(dbp) = NULL;
974 }
975 
976 static void
977 g_raid3_destroy_bio(struct g_raid3_softc *sc, struct bio *cbp)
978 {
979 	struct bio *bp, *pbp;
980 	size_t size;
981 
982 	pbp = cbp->bio_parent;
983 	pbp->bio_children--;
984 	KASSERT(cbp->bio_data != NULL, ("NULL bio_data"));
985 	size = pbp->bio_length / (sc->sc_ndisks - 1);
986 	g_raid3_free(sc, cbp->bio_data, size);
987 	if (G_RAID3_HEAD_BIO(pbp) == cbp) {
988 		G_RAID3_HEAD_BIO(pbp) = G_RAID3_NEXT_BIO(cbp);
989 		G_RAID3_NEXT_BIO(cbp) = NULL;
990 		g_destroy_bio(cbp);
991 	} else {
992 		G_RAID3_FOREACH_BIO(pbp, bp) {
993 			if (G_RAID3_NEXT_BIO(bp) == cbp)
994 				break;
995 		}
996 		if (bp != NULL) {
997 			KASSERT(G_RAID3_NEXT_BIO(bp) != NULL,
998 			    ("NULL bp->bio_driver1"));
999 			G_RAID3_NEXT_BIO(bp) = G_RAID3_NEXT_BIO(cbp);
1000 			G_RAID3_NEXT_BIO(cbp) = NULL;
1001 		}
1002 		g_destroy_bio(cbp);
1003 	}
1004 }
1005 
1006 static struct bio *
1007 g_raid3_clone_bio(struct g_raid3_softc *sc, struct bio *pbp)
1008 {
1009 	struct bio *bp, *cbp;
1010 	size_t size;
1011 	int memflag;
1012 
1013 	cbp = g_clone_bio(pbp);
1014 	if (cbp == NULL)
1015 		return (NULL);
1016 	size = pbp->bio_length / (sc->sc_ndisks - 1);
1017 	if ((pbp->bio_cflags & G_RAID3_BIO_CFLAG_REGULAR) != 0)
1018 		memflag = M_WAITOK;
1019 	else
1020 		memflag = M_NOWAIT;
1021 	cbp->bio_data = g_raid3_alloc(sc, size, memflag);
1022 	if (cbp->bio_data == NULL) {
1023 		pbp->bio_children--;
1024 		g_destroy_bio(cbp);
1025 		return (NULL);
1026 	}
1027 	G_RAID3_NEXT_BIO(cbp) = NULL;
1028 	if (G_RAID3_HEAD_BIO(pbp) == NULL)
1029 		G_RAID3_HEAD_BIO(pbp) = cbp;
1030 	else {
1031 		G_RAID3_FOREACH_BIO(pbp, bp) {
1032 			if (G_RAID3_NEXT_BIO(bp) == NULL) {
1033 				G_RAID3_NEXT_BIO(bp) = cbp;
1034 				break;
1035 			}
1036 		}
1037 	}
1038 	return (cbp);
1039 }
1040 
1041 static void
1042 g_raid3_scatter(struct bio *pbp)
1043 {
1044 	struct g_raid3_softc *sc;
1045 	struct g_raid3_disk *disk;
1046 	struct bio *bp, *cbp, *tmpbp;
1047 	off_t atom, cadd, padd, left;
1048 	int first;
1049 
1050 	sc = pbp->bio_to->geom->softc;
1051 	bp = NULL;
1052 	if ((pbp->bio_pflags & G_RAID3_BIO_PFLAG_NOPARITY) == 0) {
1053 		/*
1054 		 * Find bio for which we should calculate data.
1055 		 */
1056 		G_RAID3_FOREACH_BIO(pbp, cbp) {
1057 			if ((cbp->bio_cflags & G_RAID3_BIO_CFLAG_PARITY) != 0) {
1058 				bp = cbp;
1059 				break;
1060 			}
1061 		}
1062 		KASSERT(bp != NULL, ("NULL parity bio."));
1063 	}
1064 	atom = sc->sc_sectorsize / (sc->sc_ndisks - 1);
1065 	cadd = padd = 0;
1066 	for (left = pbp->bio_length; left > 0; left -= sc->sc_sectorsize) {
1067 		G_RAID3_FOREACH_BIO(pbp, cbp) {
1068 			if (cbp == bp)
1069 				continue;
1070 			bcopy(pbp->bio_data + padd, cbp->bio_data + cadd, atom);
1071 			padd += atom;
1072 		}
1073 		cadd += atom;
1074 	}
1075 	if ((pbp->bio_pflags & G_RAID3_BIO_PFLAG_NOPARITY) == 0) {
1076 		/*
1077 		 * Calculate parity.
1078 		 */
1079 		first = 1;
1080 		G_RAID3_FOREACH_SAFE_BIO(pbp, cbp, tmpbp) {
1081 			if (cbp == bp)
1082 				continue;
1083 			if (first) {
1084 				bcopy(cbp->bio_data, bp->bio_data,
1085 				    bp->bio_length);
1086 				first = 0;
1087 			} else {
1088 				g_raid3_xor(cbp->bio_data, bp->bio_data,
1089 				    bp->bio_length);
1090 			}
1091 			if ((cbp->bio_cflags & G_RAID3_BIO_CFLAG_NODISK) != 0)
1092 				g_raid3_destroy_bio(sc, cbp);
1093 		}
1094 	}
1095 	G_RAID3_FOREACH_SAFE_BIO(pbp, cbp, tmpbp) {
1096 		struct g_consumer *cp;
1097 
1098 		disk = cbp->bio_caller2;
1099 		cp = disk->d_consumer;
1100 		cbp->bio_to = cp->provider;
1101 		G_RAID3_LOGREQ(3, cbp, "Sending request.");
1102 		KASSERT(cp->acr >= 1 && cp->acw >= 1 && cp->ace >= 1,
1103 		    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name,
1104 		    cp->acr, cp->acw, cp->ace));
1105 		cp->index++;
1106 		sc->sc_writes++;
1107 		g_io_request(cbp, cp);
1108 	}
1109 }
1110 
1111 static void
1112 g_raid3_gather(struct bio *pbp)
1113 {
1114 	struct g_raid3_softc *sc;
1115 	struct g_raid3_disk *disk;
1116 	struct bio *xbp, *fbp, *cbp;
1117 	off_t atom, cadd, padd, left;
1118 
1119 	sc = pbp->bio_to->geom->softc;
1120 	/*
1121 	 * Find bio for which we have to calculate data.
1122 	 * While going through this path, check if all requests
1123 	 * succeeded, if not, deny whole request.
1124 	 * If we're in COMPLETE mode, we allow one request to fail,
1125 	 * so if we find one, we're sending it to the parity consumer.
1126 	 * If there are more failed requests, we deny whole request.
1127 	 */
1128 	xbp = fbp = NULL;
1129 	G_RAID3_FOREACH_BIO(pbp, cbp) {
1130 		if ((cbp->bio_cflags & G_RAID3_BIO_CFLAG_PARITY) != 0) {
1131 			KASSERT(xbp == NULL, ("More than one parity bio."));
1132 			xbp = cbp;
1133 		}
1134 		if (cbp->bio_error == 0)
1135 			continue;
1136 		/*
1137 		 * Found failed request.
1138 		 */
1139 		if (fbp == NULL) {
1140 			if ((pbp->bio_pflags & G_RAID3_BIO_PFLAG_DEGRADED) != 0) {
1141 				/*
1142 				 * We are already in degraded mode, so we can't
1143 				 * accept any failures.
1144 				 */
1145 				if (pbp->bio_error == 0)
1146 					pbp->bio_error = cbp->bio_error;
1147 			} else {
1148 				fbp = cbp;
1149 			}
1150 		} else {
1151 			/*
1152 			 * Next failed request, that's too many.
1153 			 */
1154 			if (pbp->bio_error == 0)
1155 				pbp->bio_error = fbp->bio_error;
1156 		}
1157 		disk = cbp->bio_caller2;
1158 		if (disk == NULL)
1159 			continue;
1160 		if ((disk->d_flags & G_RAID3_DISK_FLAG_BROKEN) == 0) {
1161 			disk->d_flags |= G_RAID3_DISK_FLAG_BROKEN;
1162 			G_RAID3_LOGREQ(0, cbp, "Request failed (error=%d).",
1163 			    cbp->bio_error);
1164 		} else {
1165 			G_RAID3_LOGREQ(1, cbp, "Request failed (error=%d).",
1166 			    cbp->bio_error);
1167 		}
1168 		if (g_raid3_disconnect_on_failure &&
1169 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE) {
1170 			sc->sc_bump_id |= G_RAID3_BUMP_GENID;
1171 			g_raid3_event_send(disk,
1172 			    G_RAID3_DISK_STATE_DISCONNECTED,
1173 			    G_RAID3_EVENT_DONTWAIT);
1174 		}
1175 	}
1176 	if (pbp->bio_error != 0)
1177 		goto finish;
1178 	if (fbp != NULL && (pbp->bio_pflags & G_RAID3_BIO_PFLAG_VERIFY) != 0) {
1179 		pbp->bio_pflags &= ~G_RAID3_BIO_PFLAG_VERIFY;
1180 		if (xbp != fbp)
1181 			g_raid3_replace_bio(xbp, fbp);
1182 		g_raid3_destroy_bio(sc, fbp);
1183 	} else if (fbp != NULL) {
1184 		struct g_consumer *cp;
1185 
1186 		/*
1187 		 * One request failed, so send the same request to
1188 		 * the parity consumer.
1189 		 */
1190 		disk = pbp->bio_driver2;
1191 		if (disk->d_state != G_RAID3_DISK_STATE_ACTIVE) {
1192 			pbp->bio_error = fbp->bio_error;
1193 			goto finish;
1194 		}
1195 		pbp->bio_pflags |= G_RAID3_BIO_PFLAG_DEGRADED;
1196 		pbp->bio_inbed--;
1197 		fbp->bio_flags &= ~(BIO_DONE | BIO_ERROR);
1198 		if (disk->d_no == sc->sc_ndisks - 1)
1199 			fbp->bio_cflags |= G_RAID3_BIO_CFLAG_PARITY;
1200 		fbp->bio_error = 0;
1201 		fbp->bio_completed = 0;
1202 		fbp->bio_children = 0;
1203 		fbp->bio_inbed = 0;
1204 		cp = disk->d_consumer;
1205 		fbp->bio_caller2 = disk;
1206 		fbp->bio_to = cp->provider;
1207 		G_RAID3_LOGREQ(3, fbp, "Sending request (recover).");
1208 		KASSERT(cp->acr >= 1 && cp->acw >= 1 && cp->ace >= 1,
1209 		    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name,
1210 		    cp->acr, cp->acw, cp->ace));
1211 		cp->index++;
1212 		g_io_request(fbp, cp);
1213 		return;
1214 	}
1215 	if (xbp != NULL) {
1216 		/*
1217 		 * Calculate parity.
1218 		 */
1219 		G_RAID3_FOREACH_BIO(pbp, cbp) {
1220 			if ((cbp->bio_cflags & G_RAID3_BIO_CFLAG_PARITY) != 0)
1221 				continue;
1222 			g_raid3_xor(cbp->bio_data, xbp->bio_data,
1223 			    xbp->bio_length);
1224 		}
1225 		xbp->bio_cflags &= ~G_RAID3_BIO_CFLAG_PARITY;
1226 		if ((pbp->bio_pflags & G_RAID3_BIO_PFLAG_VERIFY) != 0) {
1227 			if (!g_raid3_is_zero(xbp)) {
1228 				g_raid3_parity_mismatch++;
1229 				pbp->bio_error = EIO;
1230 				goto finish;
1231 			}
1232 			g_raid3_destroy_bio(sc, xbp);
1233 		}
1234 	}
1235 	atom = sc->sc_sectorsize / (sc->sc_ndisks - 1);
1236 	cadd = padd = 0;
1237 	for (left = pbp->bio_length; left > 0; left -= sc->sc_sectorsize) {
1238 		G_RAID3_FOREACH_BIO(pbp, cbp) {
1239 			bcopy(cbp->bio_data + cadd, pbp->bio_data + padd, atom);
1240 			pbp->bio_completed += atom;
1241 			padd += atom;
1242 		}
1243 		cadd += atom;
1244 	}
1245 finish:
1246 	if (pbp->bio_error == 0)
1247 		G_RAID3_LOGREQ(3, pbp, "Request finished.");
1248 	else {
1249 		if ((pbp->bio_pflags & G_RAID3_BIO_PFLAG_VERIFY) != 0)
1250 			G_RAID3_LOGREQ(1, pbp, "Verification error.");
1251 		else
1252 			G_RAID3_LOGREQ(0, pbp, "Request failed.");
1253 	}
1254 	pbp->bio_pflags &= ~G_RAID3_BIO_PFLAG_MASK;
1255 	while ((cbp = G_RAID3_HEAD_BIO(pbp)) != NULL)
1256 		g_raid3_destroy_bio(sc, cbp);
1257 	g_io_deliver(pbp, pbp->bio_error);
1258 }
1259 
1260 static void
1261 g_raid3_done(struct bio *bp)
1262 {
1263 	struct g_raid3_softc *sc;
1264 
1265 	sc = bp->bio_from->geom->softc;
1266 	bp->bio_cflags |= G_RAID3_BIO_CFLAG_REGULAR;
1267 	G_RAID3_LOGREQ(3, bp, "Regular request done (error=%d).", bp->bio_error);
1268 	mtx_lock(&sc->sc_queue_mtx);
1269 	bioq_insert_head(&sc->sc_queue, bp);
1270 	mtx_unlock(&sc->sc_queue_mtx);
1271 	wakeup(sc);
1272 	wakeup(&sc->sc_queue);
1273 }
1274 
1275 static void
1276 g_raid3_regular_request(struct bio *cbp)
1277 {
1278 	struct g_raid3_softc *sc;
1279 	struct g_raid3_disk *disk;
1280 	struct bio *pbp;
1281 
1282 	g_topology_assert_not();
1283 
1284 	pbp = cbp->bio_parent;
1285 	sc = pbp->bio_to->geom->softc;
1286 	cbp->bio_from->index--;
1287 	if (cbp->bio_cmd == BIO_WRITE)
1288 		sc->sc_writes--;
1289 	disk = cbp->bio_from->private;
1290 	if (disk == NULL) {
1291 		g_topology_lock();
1292 		g_raid3_kill_consumer(sc, cbp->bio_from);
1293 		g_topology_unlock();
1294 	}
1295 
1296 	G_RAID3_LOGREQ(3, cbp, "Request finished.");
1297 	pbp->bio_inbed++;
1298 	KASSERT(pbp->bio_inbed <= pbp->bio_children,
1299 	    ("bio_inbed (%u) is bigger than bio_children (%u).", pbp->bio_inbed,
1300 	    pbp->bio_children));
1301 	if (pbp->bio_inbed != pbp->bio_children)
1302 		return;
1303 	switch (pbp->bio_cmd) {
1304 	case BIO_READ:
1305 		g_raid3_gather(pbp);
1306 		break;
1307 	case BIO_WRITE:
1308 	case BIO_DELETE:
1309 	    {
1310 		int error = 0;
1311 
1312 		pbp->bio_completed = pbp->bio_length;
1313 		while ((cbp = G_RAID3_HEAD_BIO(pbp)) != NULL) {
1314 			if (cbp->bio_error == 0) {
1315 				g_raid3_destroy_bio(sc, cbp);
1316 				continue;
1317 			}
1318 
1319 			if (error == 0)
1320 				error = cbp->bio_error;
1321 			else if (pbp->bio_error == 0) {
1322 				/*
1323 				 * Next failed request, that's too many.
1324 				 */
1325 				pbp->bio_error = error;
1326 			}
1327 
1328 			disk = cbp->bio_caller2;
1329 			if (disk == NULL) {
1330 				g_raid3_destroy_bio(sc, cbp);
1331 				continue;
1332 			}
1333 
1334 			if ((disk->d_flags & G_RAID3_DISK_FLAG_BROKEN) == 0) {
1335 				disk->d_flags |= G_RAID3_DISK_FLAG_BROKEN;
1336 				G_RAID3_LOGREQ(0, cbp,
1337 				    "Request failed (error=%d).",
1338 				    cbp->bio_error);
1339 			} else {
1340 				G_RAID3_LOGREQ(1, cbp,
1341 				    "Request failed (error=%d).",
1342 				    cbp->bio_error);
1343 			}
1344 			if (g_raid3_disconnect_on_failure &&
1345 			    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE) {
1346 				sc->sc_bump_id |= G_RAID3_BUMP_GENID;
1347 				g_raid3_event_send(disk,
1348 				    G_RAID3_DISK_STATE_DISCONNECTED,
1349 				    G_RAID3_EVENT_DONTWAIT);
1350 			}
1351 			g_raid3_destroy_bio(sc, cbp);
1352 		}
1353 		if (pbp->bio_error == 0)
1354 			G_RAID3_LOGREQ(3, pbp, "Request finished.");
1355 		else
1356 			G_RAID3_LOGREQ(0, pbp, "Request failed.");
1357 		pbp->bio_pflags &= ~G_RAID3_BIO_PFLAG_DEGRADED;
1358 		pbp->bio_pflags &= ~G_RAID3_BIO_PFLAG_NOPARITY;
1359 		bioq_remove(&sc->sc_inflight, pbp);
1360 		/* Release delayed sync requests if possible. */
1361 		g_raid3_sync_release(sc);
1362 		g_io_deliver(pbp, pbp->bio_error);
1363 		break;
1364 	    }
1365 	}
1366 }
1367 
1368 static void
1369 g_raid3_sync_done(struct bio *bp)
1370 {
1371 	struct g_raid3_softc *sc;
1372 
1373 	G_RAID3_LOGREQ(3, bp, "Synchronization request delivered.");
1374 	sc = bp->bio_from->geom->softc;
1375 	bp->bio_cflags |= G_RAID3_BIO_CFLAG_SYNC;
1376 	mtx_lock(&sc->sc_queue_mtx);
1377 	bioq_insert_head(&sc->sc_queue, bp);
1378 	mtx_unlock(&sc->sc_queue_mtx);
1379 	wakeup(sc);
1380 	wakeup(&sc->sc_queue);
1381 }
1382 
1383 static void
1384 g_raid3_flush(struct g_raid3_softc *sc, struct bio *bp)
1385 {
1386 	struct bio_queue_head queue;
1387 	struct g_raid3_disk *disk;
1388 	struct g_consumer *cp;
1389 	struct bio *cbp;
1390 	u_int i;
1391 
1392 	bioq_init(&queue);
1393 	for (i = 0; i < sc->sc_ndisks; i++) {
1394 		disk = &sc->sc_disks[i];
1395 		if (disk->d_state != G_RAID3_DISK_STATE_ACTIVE)
1396 			continue;
1397 		cbp = g_clone_bio(bp);
1398 		if (cbp == NULL) {
1399 			for (cbp = bioq_first(&queue); cbp != NULL;
1400 			    cbp = bioq_first(&queue)) {
1401 				bioq_remove(&queue, cbp);
1402 				g_destroy_bio(cbp);
1403 			}
1404 			if (bp->bio_error == 0)
1405 				bp->bio_error = ENOMEM;
1406 			g_io_deliver(bp, bp->bio_error);
1407 			return;
1408 		}
1409 		bioq_insert_tail(&queue, cbp);
1410 		cbp->bio_done = g_std_done;
1411 		cbp->bio_caller1 = disk;
1412 		cbp->bio_to = disk->d_consumer->provider;
1413 	}
1414 	for (cbp = bioq_first(&queue); cbp != NULL; cbp = bioq_first(&queue)) {
1415 		bioq_remove(&queue, cbp);
1416 		G_RAID3_LOGREQ(3, cbp, "Sending request.");
1417 		disk = cbp->bio_caller1;
1418 		cbp->bio_caller1 = NULL;
1419 		cp = disk->d_consumer;
1420 		KASSERT(cp->acr >= 1 && cp->acw >= 1 && cp->ace >= 1,
1421 		    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name,
1422 		    cp->acr, cp->acw, cp->ace));
1423 		g_io_request(cbp, disk->d_consumer);
1424 	}
1425 }
1426 
1427 static void
1428 g_raid3_start(struct bio *bp)
1429 {
1430 	struct g_raid3_softc *sc;
1431 
1432 	sc = bp->bio_to->geom->softc;
1433 	/*
1434 	 * If sc == NULL or there are no valid disks, provider's error
1435 	 * should be set and g_raid3_start() should not be called at all.
1436 	 */
1437 	KASSERT(sc != NULL && (sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED ||
1438 	    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE),
1439 	    ("Provider's error should be set (error=%d)(device=%s).",
1440 	    bp->bio_to->error, bp->bio_to->name));
1441 	G_RAID3_LOGREQ(3, bp, "Request received.");
1442 
1443 	switch (bp->bio_cmd) {
1444 	case BIO_READ:
1445 	case BIO_WRITE:
1446 	case BIO_DELETE:
1447 		break;
1448 	case BIO_SPEEDUP:
1449 	case BIO_FLUSH:
1450 		g_raid3_flush(sc, bp);
1451 		return;
1452 	case BIO_GETATTR:
1453 	default:
1454 		g_io_deliver(bp, EOPNOTSUPP);
1455 		return;
1456 	}
1457 	mtx_lock(&sc->sc_queue_mtx);
1458 	bioq_insert_tail(&sc->sc_queue, bp);
1459 	mtx_unlock(&sc->sc_queue_mtx);
1460 	G_RAID3_DEBUG(4, "%s: Waking up %p.", __func__, sc);
1461 	wakeup(sc);
1462 }
1463 
1464 /*
1465  * Return TRUE if the given request is colliding with a in-progress
1466  * synchronization request.
1467  */
1468 static int
1469 g_raid3_sync_collision(struct g_raid3_softc *sc, struct bio *bp)
1470 {
1471 	struct g_raid3_disk *disk;
1472 	struct bio *sbp;
1473 	off_t rstart, rend, sstart, send;
1474 	int i;
1475 
1476 	disk = sc->sc_syncdisk;
1477 	if (disk == NULL)
1478 		return (0);
1479 	rstart = bp->bio_offset;
1480 	rend = bp->bio_offset + bp->bio_length;
1481 	for (i = 0; i < g_raid3_syncreqs; i++) {
1482 		sbp = disk->d_sync.ds_bios[i];
1483 		if (sbp == NULL)
1484 			continue;
1485 		sstart = sbp->bio_offset;
1486 		send = sbp->bio_length;
1487 		if (sbp->bio_cmd == BIO_WRITE) {
1488 			sstart *= sc->sc_ndisks - 1;
1489 			send *= sc->sc_ndisks - 1;
1490 		}
1491 		send += sstart;
1492 		if (rend > sstart && rstart < send)
1493 			return (1);
1494 	}
1495 	return (0);
1496 }
1497 
1498 /*
1499  * Return TRUE if the given sync request is colliding with a in-progress regular
1500  * request.
1501  */
1502 static int
1503 g_raid3_regular_collision(struct g_raid3_softc *sc, struct bio *sbp)
1504 {
1505 	off_t rstart, rend, sstart, send;
1506 	struct bio *bp;
1507 
1508 	if (sc->sc_syncdisk == NULL)
1509 		return (0);
1510 	sstart = sbp->bio_offset;
1511 	send = sstart + sbp->bio_length;
1512 	TAILQ_FOREACH(bp, &sc->sc_inflight.queue, bio_queue) {
1513 		rstart = bp->bio_offset;
1514 		rend = bp->bio_offset + bp->bio_length;
1515 		if (rend > sstart && rstart < send)
1516 			return (1);
1517 	}
1518 	return (0);
1519 }
1520 
1521 /*
1522  * Puts request onto delayed queue.
1523  */
1524 static void
1525 g_raid3_regular_delay(struct g_raid3_softc *sc, struct bio *bp)
1526 {
1527 
1528 	G_RAID3_LOGREQ(2, bp, "Delaying request.");
1529 	bioq_insert_head(&sc->sc_regular_delayed, bp);
1530 }
1531 
1532 /*
1533  * Puts synchronization request onto delayed queue.
1534  */
1535 static void
1536 g_raid3_sync_delay(struct g_raid3_softc *sc, struct bio *bp)
1537 {
1538 
1539 	G_RAID3_LOGREQ(2, bp, "Delaying synchronization request.");
1540 	bioq_insert_tail(&sc->sc_sync_delayed, bp);
1541 }
1542 
1543 /*
1544  * Releases delayed regular requests which don't collide anymore with sync
1545  * requests.
1546  */
1547 static void
1548 g_raid3_regular_release(struct g_raid3_softc *sc)
1549 {
1550 	struct bio *bp, *bp2;
1551 
1552 	TAILQ_FOREACH_SAFE(bp, &sc->sc_regular_delayed.queue, bio_queue, bp2) {
1553 		if (g_raid3_sync_collision(sc, bp))
1554 			continue;
1555 		bioq_remove(&sc->sc_regular_delayed, bp);
1556 		G_RAID3_LOGREQ(2, bp, "Releasing delayed request (%p).", bp);
1557 		mtx_lock(&sc->sc_queue_mtx);
1558 		bioq_insert_head(&sc->sc_queue, bp);
1559 #if 0
1560 		/*
1561 		 * wakeup() is not needed, because this function is called from
1562 		 * the worker thread.
1563 		 */
1564 		wakeup(&sc->sc_queue);
1565 #endif
1566 		mtx_unlock(&sc->sc_queue_mtx);
1567 	}
1568 }
1569 
1570 /*
1571  * Releases delayed sync requests which don't collide anymore with regular
1572  * requests.
1573  */
1574 static void
1575 g_raid3_sync_release(struct g_raid3_softc *sc)
1576 {
1577 	struct bio *bp, *bp2;
1578 
1579 	TAILQ_FOREACH_SAFE(bp, &sc->sc_sync_delayed.queue, bio_queue, bp2) {
1580 		if (g_raid3_regular_collision(sc, bp))
1581 			continue;
1582 		bioq_remove(&sc->sc_sync_delayed, bp);
1583 		G_RAID3_LOGREQ(2, bp,
1584 		    "Releasing delayed synchronization request.");
1585 		g_io_request(bp, bp->bio_from);
1586 	}
1587 }
1588 
1589 /*
1590  * Handle synchronization requests.
1591  * Every synchronization request is two-steps process: first, READ request is
1592  * send to active provider and then WRITE request (with read data) to the provider
1593  * being synchronized. When WRITE is finished, new synchronization request is
1594  * send.
1595  */
1596 static void
1597 g_raid3_sync_request(struct bio *bp)
1598 {
1599 	struct g_raid3_softc *sc;
1600 	struct g_raid3_disk *disk;
1601 
1602 	bp->bio_from->index--;
1603 	sc = bp->bio_from->geom->softc;
1604 	disk = bp->bio_from->private;
1605 	if (disk == NULL) {
1606 		sx_xunlock(&sc->sc_lock); /* Avoid recursion on sc_lock. */
1607 		g_topology_lock();
1608 		g_raid3_kill_consumer(sc, bp->bio_from);
1609 		g_topology_unlock();
1610 		free(bp->bio_data, M_RAID3);
1611 		g_destroy_bio(bp);
1612 		sx_xlock(&sc->sc_lock);
1613 		return;
1614 	}
1615 
1616 	/*
1617 	 * Synchronization request.
1618 	 */
1619 	switch (bp->bio_cmd) {
1620 	case BIO_READ:
1621 	    {
1622 		struct g_consumer *cp;
1623 		u_char *dst, *src;
1624 		off_t left;
1625 		u_int atom;
1626 
1627 		if (bp->bio_error != 0) {
1628 			G_RAID3_LOGREQ(0, bp,
1629 			    "Synchronization request failed (error=%d).",
1630 			    bp->bio_error);
1631 			g_destroy_bio(bp);
1632 			return;
1633 		}
1634 		G_RAID3_LOGREQ(3, bp, "Synchronization request finished.");
1635 		atom = sc->sc_sectorsize / (sc->sc_ndisks - 1);
1636 		dst = src = bp->bio_data;
1637 		if (disk->d_no == sc->sc_ndisks - 1) {
1638 			u_int n;
1639 
1640 			/* Parity component. */
1641 			for (left = bp->bio_length; left > 0;
1642 			    left -= sc->sc_sectorsize) {
1643 				bcopy(src, dst, atom);
1644 				src += atom;
1645 				for (n = 1; n < sc->sc_ndisks - 1; n++) {
1646 					g_raid3_xor(src, dst, atom);
1647 					src += atom;
1648 				}
1649 				dst += atom;
1650 			}
1651 		} else {
1652 			/* Regular component. */
1653 			src += atom * disk->d_no;
1654 			for (left = bp->bio_length; left > 0;
1655 			    left -= sc->sc_sectorsize) {
1656 				bcopy(src, dst, atom);
1657 				src += sc->sc_sectorsize;
1658 				dst += atom;
1659 			}
1660 		}
1661 		bp->bio_driver1 = bp->bio_driver2 = NULL;
1662 		bp->bio_pflags = 0;
1663 		bp->bio_offset /= sc->sc_ndisks - 1;
1664 		bp->bio_length /= sc->sc_ndisks - 1;
1665 		bp->bio_cmd = BIO_WRITE;
1666 		bp->bio_cflags = 0;
1667 		bp->bio_children = bp->bio_inbed = 0;
1668 		cp = disk->d_consumer;
1669 		KASSERT(cp->acr >= 1 && cp->acw >= 1 && cp->ace >= 1,
1670 		    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name,
1671 		    cp->acr, cp->acw, cp->ace));
1672 		cp->index++;
1673 		g_io_request(bp, cp);
1674 		return;
1675 	    }
1676 	case BIO_WRITE:
1677 	    {
1678 		struct g_raid3_disk_sync *sync;
1679 		off_t boffset, moffset;
1680 		void *data;
1681 		int i;
1682 
1683 		if (bp->bio_error != 0) {
1684 			G_RAID3_LOGREQ(0, bp,
1685 			    "Synchronization request failed (error=%d).",
1686 			    bp->bio_error);
1687 			g_destroy_bio(bp);
1688 			sc->sc_bump_id |= G_RAID3_BUMP_GENID;
1689 			g_raid3_event_send(disk,
1690 			    G_RAID3_DISK_STATE_DISCONNECTED,
1691 			    G_RAID3_EVENT_DONTWAIT);
1692 			return;
1693 		}
1694 		G_RAID3_LOGREQ(3, bp, "Synchronization request finished.");
1695 		sync = &disk->d_sync;
1696 		if (sync->ds_offset == sc->sc_mediasize / (sc->sc_ndisks - 1) ||
1697 		    sync->ds_consumer == NULL ||
1698 		    (sc->sc_flags & G_RAID3_DEVICE_FLAG_DESTROY) != 0) {
1699 			/* Don't send more synchronization requests. */
1700 			sync->ds_inflight--;
1701 			if (sync->ds_bios != NULL) {
1702 				i = (int)(uintptr_t)bp->bio_caller1;
1703 				sync->ds_bios[i] = NULL;
1704 			}
1705 			free(bp->bio_data, M_RAID3);
1706 			g_destroy_bio(bp);
1707 			if (sync->ds_inflight > 0)
1708 				return;
1709 			if (sync->ds_consumer == NULL ||
1710 			    (sc->sc_flags & G_RAID3_DEVICE_FLAG_DESTROY) != 0) {
1711 				return;
1712 			}
1713 			/*
1714 			 * Disk up-to-date, activate it.
1715 			 */
1716 			g_raid3_event_send(disk, G_RAID3_DISK_STATE_ACTIVE,
1717 			    G_RAID3_EVENT_DONTWAIT);
1718 			return;
1719 		}
1720 
1721 		/* Send next synchronization request. */
1722 		data = bp->bio_data;
1723 		g_reset_bio(bp);
1724 		bp->bio_cmd = BIO_READ;
1725 		bp->bio_offset = sync->ds_offset * (sc->sc_ndisks - 1);
1726 		bp->bio_length = MIN(MAXPHYS, sc->sc_mediasize - bp->bio_offset);
1727 		sync->ds_offset += bp->bio_length / (sc->sc_ndisks - 1);
1728 		bp->bio_done = g_raid3_sync_done;
1729 		bp->bio_data = data;
1730 		bp->bio_from = sync->ds_consumer;
1731 		bp->bio_to = sc->sc_provider;
1732 		G_RAID3_LOGREQ(3, bp, "Sending synchronization request.");
1733 		sync->ds_consumer->index++;
1734 		/*
1735 		 * Delay the request if it is colliding with a regular request.
1736 		 */
1737 		if (g_raid3_regular_collision(sc, bp))
1738 			g_raid3_sync_delay(sc, bp);
1739 		else
1740 			g_io_request(bp, sync->ds_consumer);
1741 
1742 		/* Release delayed requests if possible. */
1743 		g_raid3_regular_release(sc);
1744 
1745 		/* Find the smallest offset. */
1746 		moffset = sc->sc_mediasize;
1747 		for (i = 0; i < g_raid3_syncreqs; i++) {
1748 			bp = sync->ds_bios[i];
1749 			boffset = bp->bio_offset;
1750 			if (bp->bio_cmd == BIO_WRITE)
1751 				boffset *= sc->sc_ndisks - 1;
1752 			if (boffset < moffset)
1753 				moffset = boffset;
1754 		}
1755 		if (sync->ds_offset_done + (MAXPHYS * 100) < moffset) {
1756 			/* Update offset_done on every 100 blocks. */
1757 			sync->ds_offset_done = moffset;
1758 			g_raid3_update_metadata(disk);
1759 		}
1760 		return;
1761 	    }
1762 	default:
1763 		KASSERT(1 == 0, ("Invalid command here: %u (device=%s)",
1764 		    bp->bio_cmd, sc->sc_name));
1765 		break;
1766 	}
1767 }
1768 
1769 static int
1770 g_raid3_register_request(struct bio *pbp)
1771 {
1772 	struct g_raid3_softc *sc;
1773 	struct g_raid3_disk *disk;
1774 	struct g_consumer *cp;
1775 	struct bio *cbp, *tmpbp;
1776 	off_t offset, length;
1777 	u_int n, ndisks;
1778 	int round_robin, verify;
1779 
1780 	ndisks = 0;
1781 	sc = pbp->bio_to->geom->softc;
1782 	if ((pbp->bio_cflags & G_RAID3_BIO_CFLAG_REGSYNC) != 0 &&
1783 	    sc->sc_syncdisk == NULL) {
1784 		g_io_deliver(pbp, EIO);
1785 		return (0);
1786 	}
1787 	g_raid3_init_bio(pbp);
1788 	length = pbp->bio_length / (sc->sc_ndisks - 1);
1789 	offset = pbp->bio_offset / (sc->sc_ndisks - 1);
1790 	round_robin = verify = 0;
1791 	switch (pbp->bio_cmd) {
1792 	case BIO_READ:
1793 		if ((sc->sc_flags & G_RAID3_DEVICE_FLAG_VERIFY) != 0 &&
1794 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE) {
1795 			pbp->bio_pflags |= G_RAID3_BIO_PFLAG_VERIFY;
1796 			verify = 1;
1797 			ndisks = sc->sc_ndisks;
1798 		} else {
1799 			verify = 0;
1800 			ndisks = sc->sc_ndisks - 1;
1801 		}
1802 		if ((sc->sc_flags & G_RAID3_DEVICE_FLAG_ROUND_ROBIN) != 0 &&
1803 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE) {
1804 			round_robin = 1;
1805 		} else {
1806 			round_robin = 0;
1807 		}
1808 		KASSERT(!round_robin || !verify,
1809 		    ("ROUND-ROBIN and VERIFY are mutually exclusive."));
1810 		pbp->bio_driver2 = &sc->sc_disks[sc->sc_ndisks - 1];
1811 		break;
1812 	case BIO_WRITE:
1813 	case BIO_DELETE:
1814 		/*
1815 		 * Delay the request if it is colliding with a synchronization
1816 		 * request.
1817 		 */
1818 		if (g_raid3_sync_collision(sc, pbp)) {
1819 			g_raid3_regular_delay(sc, pbp);
1820 			return (0);
1821 		}
1822 
1823 		if (sc->sc_idle)
1824 			g_raid3_unidle(sc);
1825 		else
1826 			sc->sc_last_write = time_uptime;
1827 
1828 		ndisks = sc->sc_ndisks;
1829 		break;
1830 	}
1831 	for (n = 0; n < ndisks; n++) {
1832 		disk = &sc->sc_disks[n];
1833 		cbp = g_raid3_clone_bio(sc, pbp);
1834 		if (cbp == NULL) {
1835 			while ((cbp = G_RAID3_HEAD_BIO(pbp)) != NULL)
1836 				g_raid3_destroy_bio(sc, cbp);
1837 			/*
1838 			 * To prevent deadlock, we must run back up
1839 			 * with the ENOMEM for failed requests of any
1840 			 * of our consumers.  Our own sync requests
1841 			 * can stick around, as they are finite.
1842 			 */
1843 			if ((pbp->bio_cflags &
1844 			    G_RAID3_BIO_CFLAG_REGULAR) != 0) {
1845 				g_io_deliver(pbp, ENOMEM);
1846 				return (0);
1847 			}
1848 			return (ENOMEM);
1849 		}
1850 		cbp->bio_offset = offset;
1851 		cbp->bio_length = length;
1852 		cbp->bio_done = g_raid3_done;
1853 		switch (pbp->bio_cmd) {
1854 		case BIO_READ:
1855 			if (disk->d_state != G_RAID3_DISK_STATE_ACTIVE) {
1856 				/*
1857 				 * Replace invalid component with the parity
1858 				 * component.
1859 				 */
1860 				disk = &sc->sc_disks[sc->sc_ndisks - 1];
1861 				cbp->bio_cflags |= G_RAID3_BIO_CFLAG_PARITY;
1862 				pbp->bio_pflags |= G_RAID3_BIO_PFLAG_DEGRADED;
1863 			} else if (round_robin &&
1864 			    disk->d_no == sc->sc_round_robin) {
1865 				/*
1866 				 * In round-robin mode skip one data component
1867 				 * and use parity component when reading.
1868 				 */
1869 				pbp->bio_driver2 = disk;
1870 				disk = &sc->sc_disks[sc->sc_ndisks - 1];
1871 				cbp->bio_cflags |= G_RAID3_BIO_CFLAG_PARITY;
1872 				sc->sc_round_robin++;
1873 				round_robin = 0;
1874 			} else if (verify && disk->d_no == sc->sc_ndisks - 1) {
1875 				cbp->bio_cflags |= G_RAID3_BIO_CFLAG_PARITY;
1876 			}
1877 			break;
1878 		case BIO_WRITE:
1879 		case BIO_DELETE:
1880 			if (disk->d_state == G_RAID3_DISK_STATE_ACTIVE ||
1881 			    disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING) {
1882 				if (n == ndisks - 1) {
1883 					/*
1884 					 * Active parity component, mark it as such.
1885 					 */
1886 					cbp->bio_cflags |=
1887 					    G_RAID3_BIO_CFLAG_PARITY;
1888 				}
1889 			} else {
1890 				pbp->bio_pflags |= G_RAID3_BIO_PFLAG_DEGRADED;
1891 				if (n == ndisks - 1) {
1892 					/*
1893 					 * Parity component is not connected,
1894 					 * so destroy its request.
1895 					 */
1896 					pbp->bio_pflags |=
1897 					    G_RAID3_BIO_PFLAG_NOPARITY;
1898 					g_raid3_destroy_bio(sc, cbp);
1899 					cbp = NULL;
1900 				} else {
1901 					cbp->bio_cflags |=
1902 					    G_RAID3_BIO_CFLAG_NODISK;
1903 					disk = NULL;
1904 				}
1905 			}
1906 			break;
1907 		}
1908 		if (cbp != NULL)
1909 			cbp->bio_caller2 = disk;
1910 	}
1911 	switch (pbp->bio_cmd) {
1912 	case BIO_READ:
1913 		if (round_robin) {
1914 			/*
1915 			 * If we are in round-robin mode and 'round_robin' is
1916 			 * still 1, it means, that we skipped parity component
1917 			 * for this read and must reset sc_round_robin field.
1918 			 */
1919 			sc->sc_round_robin = 0;
1920 		}
1921 		G_RAID3_FOREACH_SAFE_BIO(pbp, cbp, tmpbp) {
1922 			disk = cbp->bio_caller2;
1923 			cp = disk->d_consumer;
1924 			cbp->bio_to = cp->provider;
1925 			G_RAID3_LOGREQ(3, cbp, "Sending request.");
1926 			KASSERT(cp->acr >= 1 && cp->acw >= 1 && cp->ace >= 1,
1927 			    ("Consumer %s not opened (r%dw%de%d).",
1928 			    cp->provider->name, cp->acr, cp->acw, cp->ace));
1929 			cp->index++;
1930 			g_io_request(cbp, cp);
1931 		}
1932 		break;
1933 	case BIO_WRITE:
1934 	case BIO_DELETE:
1935 		/*
1936 		 * Put request onto inflight queue, so we can check if new
1937 		 * synchronization requests don't collide with it.
1938 		 */
1939 		bioq_insert_tail(&sc->sc_inflight, pbp);
1940 
1941 		/*
1942 		 * Bump syncid on first write.
1943 		 */
1944 		if ((sc->sc_bump_id & G_RAID3_BUMP_SYNCID) != 0) {
1945 			sc->sc_bump_id &= ~G_RAID3_BUMP_SYNCID;
1946 			g_raid3_bump_syncid(sc);
1947 		}
1948 		g_raid3_scatter(pbp);
1949 		break;
1950 	}
1951 	return (0);
1952 }
1953 
1954 static int
1955 g_raid3_can_destroy(struct g_raid3_softc *sc)
1956 {
1957 	struct g_geom *gp;
1958 	struct g_consumer *cp;
1959 
1960 	g_topology_assert();
1961 	gp = sc->sc_geom;
1962 	if (gp->softc == NULL)
1963 		return (1);
1964 	LIST_FOREACH(cp, &gp->consumer, consumer) {
1965 		if (g_raid3_is_busy(sc, cp))
1966 			return (0);
1967 	}
1968 	gp = sc->sc_sync.ds_geom;
1969 	LIST_FOREACH(cp, &gp->consumer, consumer) {
1970 		if (g_raid3_is_busy(sc, cp))
1971 			return (0);
1972 	}
1973 	G_RAID3_DEBUG(2, "No I/O requests for %s, it can be destroyed.",
1974 	    sc->sc_name);
1975 	return (1);
1976 }
1977 
1978 static int
1979 g_raid3_try_destroy(struct g_raid3_softc *sc)
1980 {
1981 
1982 	g_topology_assert_not();
1983 	sx_assert(&sc->sc_lock, SX_XLOCKED);
1984 
1985 	if (sc->sc_rootmount != NULL) {
1986 		G_RAID3_DEBUG(1, "root_mount_rel[%u] %p", __LINE__,
1987 		    sc->sc_rootmount);
1988 		root_mount_rel(sc->sc_rootmount);
1989 		sc->sc_rootmount = NULL;
1990 	}
1991 
1992 	g_topology_lock();
1993 	if (!g_raid3_can_destroy(sc)) {
1994 		g_topology_unlock();
1995 		return (0);
1996 	}
1997 	sc->sc_geom->softc = NULL;
1998 	sc->sc_sync.ds_geom->softc = NULL;
1999 	if ((sc->sc_flags & G_RAID3_DEVICE_FLAG_WAIT) != 0) {
2000 		g_topology_unlock();
2001 		G_RAID3_DEBUG(4, "%s: Waking up %p.", __func__,
2002 		    &sc->sc_worker);
2003 		/* Unlock sc_lock here, as it can be destroyed after wakeup. */
2004 		sx_xunlock(&sc->sc_lock);
2005 		wakeup(&sc->sc_worker);
2006 		sc->sc_worker = NULL;
2007 	} else {
2008 		g_topology_unlock();
2009 		g_raid3_destroy_device(sc);
2010 		free(sc->sc_disks, M_RAID3);
2011 		free(sc, M_RAID3);
2012 	}
2013 	return (1);
2014 }
2015 
2016 /*
2017  * Worker thread.
2018  */
2019 static void
2020 g_raid3_worker(void *arg)
2021 {
2022 	struct g_raid3_softc *sc;
2023 	struct g_raid3_event *ep;
2024 	struct bio *bp;
2025 	int timeout;
2026 
2027 	sc = arg;
2028 	thread_lock(curthread);
2029 	sched_prio(curthread, PRIBIO);
2030 	thread_unlock(curthread);
2031 
2032 	sx_xlock(&sc->sc_lock);
2033 	for (;;) {
2034 		G_RAID3_DEBUG(5, "%s: Let's see...", __func__);
2035 		/*
2036 		 * First take a look at events.
2037 		 * This is important to handle events before any I/O requests.
2038 		 */
2039 		ep = g_raid3_event_get(sc);
2040 		if (ep != NULL) {
2041 			g_raid3_event_remove(sc, ep);
2042 			if ((ep->e_flags & G_RAID3_EVENT_DEVICE) != 0) {
2043 				/* Update only device status. */
2044 				G_RAID3_DEBUG(3,
2045 				    "Running event for device %s.",
2046 				    sc->sc_name);
2047 				ep->e_error = 0;
2048 				g_raid3_update_device(sc, 1);
2049 			} else {
2050 				/* Update disk status. */
2051 				G_RAID3_DEBUG(3, "Running event for disk %s.",
2052 				     g_raid3_get_diskname(ep->e_disk));
2053 				ep->e_error = g_raid3_update_disk(ep->e_disk,
2054 				    ep->e_state);
2055 				if (ep->e_error == 0)
2056 					g_raid3_update_device(sc, 0);
2057 			}
2058 			if ((ep->e_flags & G_RAID3_EVENT_DONTWAIT) != 0) {
2059 				KASSERT(ep->e_error == 0,
2060 				    ("Error cannot be handled."));
2061 				g_raid3_event_free(ep);
2062 			} else {
2063 				ep->e_flags |= G_RAID3_EVENT_DONE;
2064 				G_RAID3_DEBUG(4, "%s: Waking up %p.", __func__,
2065 				    ep);
2066 				mtx_lock(&sc->sc_events_mtx);
2067 				wakeup(ep);
2068 				mtx_unlock(&sc->sc_events_mtx);
2069 			}
2070 			if ((sc->sc_flags &
2071 			    G_RAID3_DEVICE_FLAG_DESTROY) != 0) {
2072 				if (g_raid3_try_destroy(sc)) {
2073 					curthread->td_pflags &= ~TDP_GEOM;
2074 					G_RAID3_DEBUG(1, "Thread exiting.");
2075 					kproc_exit(0);
2076 				}
2077 			}
2078 			G_RAID3_DEBUG(5, "%s: I'm here 1.", __func__);
2079 			continue;
2080 		}
2081 		/*
2082 		 * Check if we can mark array as CLEAN and if we can't take
2083 		 * how much seconds should we wait.
2084 		 */
2085 		timeout = g_raid3_idle(sc, -1);
2086 		/*
2087 		 * Now I/O requests.
2088 		 */
2089 		/* Get first request from the queue. */
2090 		mtx_lock(&sc->sc_queue_mtx);
2091 		bp = bioq_first(&sc->sc_queue);
2092 		if (bp == NULL) {
2093 			if ((sc->sc_flags &
2094 			    G_RAID3_DEVICE_FLAG_DESTROY) != 0) {
2095 				mtx_unlock(&sc->sc_queue_mtx);
2096 				if (g_raid3_try_destroy(sc)) {
2097 					curthread->td_pflags &= ~TDP_GEOM;
2098 					G_RAID3_DEBUG(1, "Thread exiting.");
2099 					kproc_exit(0);
2100 				}
2101 				mtx_lock(&sc->sc_queue_mtx);
2102 			}
2103 			sx_xunlock(&sc->sc_lock);
2104 			/*
2105 			 * XXX: We can miss an event here, because an event
2106 			 *      can be added without sx-device-lock and without
2107 			 *      mtx-queue-lock. Maybe I should just stop using
2108 			 *      dedicated mutex for events synchronization and
2109 			 *      stick with the queue lock?
2110 			 *      The event will hang here until next I/O request
2111 			 *      or next event is received.
2112 			 */
2113 			MSLEEP(sc, &sc->sc_queue_mtx, PRIBIO | PDROP, "r3:w1",
2114 			    timeout * hz);
2115 			sx_xlock(&sc->sc_lock);
2116 			G_RAID3_DEBUG(5, "%s: I'm here 4.", __func__);
2117 			continue;
2118 		}
2119 process:
2120 		bioq_remove(&sc->sc_queue, bp);
2121 		mtx_unlock(&sc->sc_queue_mtx);
2122 
2123 		if (bp->bio_from->geom == sc->sc_sync.ds_geom &&
2124 		    (bp->bio_cflags & G_RAID3_BIO_CFLAG_SYNC) != 0) {
2125 			g_raid3_sync_request(bp);	/* READ */
2126 		} else if (bp->bio_to != sc->sc_provider) {
2127 			if ((bp->bio_cflags & G_RAID3_BIO_CFLAG_REGULAR) != 0)
2128 				g_raid3_regular_request(bp);
2129 			else if ((bp->bio_cflags & G_RAID3_BIO_CFLAG_SYNC) != 0)
2130 				g_raid3_sync_request(bp);	/* WRITE */
2131 			else {
2132 				KASSERT(0,
2133 				    ("Invalid request cflags=0x%hx to=%s.",
2134 				    bp->bio_cflags, bp->bio_to->name));
2135 			}
2136 		} else if (g_raid3_register_request(bp) != 0) {
2137 			mtx_lock(&sc->sc_queue_mtx);
2138 			bioq_insert_head(&sc->sc_queue, bp);
2139 			/*
2140 			 * We are short in memory, let see if there are finished
2141 			 * request we can free.
2142 			 */
2143 			TAILQ_FOREACH(bp, &sc->sc_queue.queue, bio_queue) {
2144 				if (bp->bio_cflags & G_RAID3_BIO_CFLAG_REGULAR)
2145 					goto process;
2146 			}
2147 			/*
2148 			 * No finished regular request, so at least keep
2149 			 * synchronization running.
2150 			 */
2151 			TAILQ_FOREACH(bp, &sc->sc_queue.queue, bio_queue) {
2152 				if (bp->bio_cflags & G_RAID3_BIO_CFLAG_SYNC)
2153 					goto process;
2154 			}
2155 			sx_xunlock(&sc->sc_lock);
2156 			MSLEEP(&sc->sc_queue, &sc->sc_queue_mtx, PRIBIO | PDROP,
2157 			    "r3:lowmem", hz / 10);
2158 			sx_xlock(&sc->sc_lock);
2159 		}
2160 		G_RAID3_DEBUG(5, "%s: I'm here 9.", __func__);
2161 	}
2162 }
2163 
2164 static void
2165 g_raid3_update_idle(struct g_raid3_softc *sc, struct g_raid3_disk *disk)
2166 {
2167 
2168 	sx_assert(&sc->sc_lock, SX_LOCKED);
2169 	if ((sc->sc_flags & G_RAID3_DEVICE_FLAG_NOFAILSYNC) != 0)
2170 		return;
2171 	if (!sc->sc_idle && (disk->d_flags & G_RAID3_DISK_FLAG_DIRTY) == 0) {
2172 		G_RAID3_DEBUG(1, "Disk %s (device %s) marked as dirty.",
2173 		    g_raid3_get_diskname(disk), sc->sc_name);
2174 		disk->d_flags |= G_RAID3_DISK_FLAG_DIRTY;
2175 	} else if (sc->sc_idle &&
2176 	    (disk->d_flags & G_RAID3_DISK_FLAG_DIRTY) != 0) {
2177 		G_RAID3_DEBUG(1, "Disk %s (device %s) marked as clean.",
2178 		    g_raid3_get_diskname(disk), sc->sc_name);
2179 		disk->d_flags &= ~G_RAID3_DISK_FLAG_DIRTY;
2180 	}
2181 }
2182 
2183 static void
2184 g_raid3_sync_start(struct g_raid3_softc *sc)
2185 {
2186 	struct g_raid3_disk *disk;
2187 	struct g_consumer *cp;
2188 	struct bio *bp;
2189 	int error;
2190 	u_int n;
2191 
2192 	g_topology_assert_not();
2193 	sx_assert(&sc->sc_lock, SX_XLOCKED);
2194 
2195 	KASSERT(sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED,
2196 	    ("Device not in DEGRADED state (%s, %u).", sc->sc_name,
2197 	    sc->sc_state));
2198 	KASSERT(sc->sc_syncdisk == NULL, ("Syncdisk is not NULL (%s, %u).",
2199 	    sc->sc_name, sc->sc_state));
2200 	disk = NULL;
2201 	for (n = 0; n < sc->sc_ndisks; n++) {
2202 		if (sc->sc_disks[n].d_state != G_RAID3_DISK_STATE_SYNCHRONIZING)
2203 			continue;
2204 		disk = &sc->sc_disks[n];
2205 		break;
2206 	}
2207 	if (disk == NULL)
2208 		return;
2209 
2210 	sx_xunlock(&sc->sc_lock);
2211 	g_topology_lock();
2212 	cp = g_new_consumer(sc->sc_sync.ds_geom);
2213 	error = g_attach(cp, sc->sc_provider);
2214 	KASSERT(error == 0,
2215 	    ("Cannot attach to %s (error=%d).", sc->sc_name, error));
2216 	error = g_access(cp, 1, 0, 0);
2217 	KASSERT(error == 0, ("Cannot open %s (error=%d).", sc->sc_name, error));
2218 	g_topology_unlock();
2219 	sx_xlock(&sc->sc_lock);
2220 
2221 	G_RAID3_DEBUG(0, "Device %s: rebuilding provider %s.", sc->sc_name,
2222 	    g_raid3_get_diskname(disk));
2223 	if ((sc->sc_flags & G_RAID3_DEVICE_FLAG_NOFAILSYNC) == 0)
2224 		disk->d_flags |= G_RAID3_DISK_FLAG_DIRTY;
2225 	KASSERT(disk->d_sync.ds_consumer == NULL,
2226 	    ("Sync consumer already exists (device=%s, disk=%s).",
2227 	    sc->sc_name, g_raid3_get_diskname(disk)));
2228 
2229 	disk->d_sync.ds_consumer = cp;
2230 	disk->d_sync.ds_consumer->private = disk;
2231 	disk->d_sync.ds_consumer->index = 0;
2232 	sc->sc_syncdisk = disk;
2233 
2234 	/*
2235 	 * Allocate memory for synchronization bios and initialize them.
2236 	 */
2237 	disk->d_sync.ds_bios = malloc(sizeof(struct bio *) * g_raid3_syncreqs,
2238 	    M_RAID3, M_WAITOK);
2239 	for (n = 0; n < g_raid3_syncreqs; n++) {
2240 		bp = g_alloc_bio();
2241 		disk->d_sync.ds_bios[n] = bp;
2242 		bp->bio_parent = NULL;
2243 		bp->bio_cmd = BIO_READ;
2244 		bp->bio_data = malloc(MAXPHYS, M_RAID3, M_WAITOK);
2245 		bp->bio_cflags = 0;
2246 		bp->bio_offset = disk->d_sync.ds_offset * (sc->sc_ndisks - 1);
2247 		bp->bio_length = MIN(MAXPHYS, sc->sc_mediasize - bp->bio_offset);
2248 		disk->d_sync.ds_offset += bp->bio_length / (sc->sc_ndisks - 1);
2249 		bp->bio_done = g_raid3_sync_done;
2250 		bp->bio_from = disk->d_sync.ds_consumer;
2251 		bp->bio_to = sc->sc_provider;
2252 		bp->bio_caller1 = (void *)(uintptr_t)n;
2253 	}
2254 
2255 	/* Set the number of in-flight synchronization requests. */
2256 	disk->d_sync.ds_inflight = g_raid3_syncreqs;
2257 
2258 	/*
2259 	 * Fire off first synchronization requests.
2260 	 */
2261 	for (n = 0; n < g_raid3_syncreqs; n++) {
2262 		bp = disk->d_sync.ds_bios[n];
2263 		G_RAID3_LOGREQ(3, bp, "Sending synchronization request.");
2264 		disk->d_sync.ds_consumer->index++;
2265 		/*
2266 		 * Delay the request if it is colliding with a regular request.
2267 		 */
2268 		if (g_raid3_regular_collision(sc, bp))
2269 			g_raid3_sync_delay(sc, bp);
2270 		else
2271 			g_io_request(bp, disk->d_sync.ds_consumer);
2272 	}
2273 }
2274 
2275 /*
2276  * Stop synchronization process.
2277  * type: 0 - synchronization finished
2278  *       1 - synchronization stopped
2279  */
2280 static void
2281 g_raid3_sync_stop(struct g_raid3_softc *sc, int type)
2282 {
2283 	struct g_raid3_disk *disk;
2284 	struct g_consumer *cp;
2285 
2286 	g_topology_assert_not();
2287 	sx_assert(&sc->sc_lock, SX_LOCKED);
2288 
2289 	KASSERT(sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED,
2290 	    ("Device not in DEGRADED state (%s, %u).", sc->sc_name,
2291 	    sc->sc_state));
2292 	disk = sc->sc_syncdisk;
2293 	sc->sc_syncdisk = NULL;
2294 	KASSERT(disk != NULL, ("No disk was synchronized (%s).", sc->sc_name));
2295 	KASSERT(disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING,
2296 	    ("Wrong disk state (%s, %s).", g_raid3_get_diskname(disk),
2297 	    g_raid3_disk_state2str(disk->d_state)));
2298 	if (disk->d_sync.ds_consumer == NULL)
2299 		return;
2300 
2301 	if (type == 0) {
2302 		G_RAID3_DEBUG(0, "Device %s: rebuilding provider %s finished.",
2303 		    sc->sc_name, g_raid3_get_diskname(disk));
2304 	} else /* if (type == 1) */ {
2305 		G_RAID3_DEBUG(0, "Device %s: rebuilding provider %s stopped.",
2306 		    sc->sc_name, g_raid3_get_diskname(disk));
2307 	}
2308 	free(disk->d_sync.ds_bios, M_RAID3);
2309 	disk->d_sync.ds_bios = NULL;
2310 	cp = disk->d_sync.ds_consumer;
2311 	disk->d_sync.ds_consumer = NULL;
2312 	disk->d_flags &= ~G_RAID3_DISK_FLAG_DIRTY;
2313 	sx_xunlock(&sc->sc_lock); /* Avoid recursion on sc_lock. */
2314 	g_topology_lock();
2315 	g_raid3_kill_consumer(sc, cp);
2316 	g_topology_unlock();
2317 	sx_xlock(&sc->sc_lock);
2318 }
2319 
2320 static void
2321 g_raid3_launch_provider(struct g_raid3_softc *sc)
2322 {
2323 	struct g_provider *pp;
2324 	struct g_raid3_disk *disk;
2325 	int n;
2326 
2327 	sx_assert(&sc->sc_lock, SX_LOCKED);
2328 
2329 	g_topology_lock();
2330 	pp = g_new_providerf(sc->sc_geom, "raid3/%s", sc->sc_name);
2331 	pp->mediasize = sc->sc_mediasize;
2332 	pp->sectorsize = sc->sc_sectorsize;
2333 	pp->stripesize = 0;
2334 	pp->stripeoffset = 0;
2335 	for (n = 0; n < sc->sc_ndisks; n++) {
2336 		disk = &sc->sc_disks[n];
2337 		if (disk->d_consumer && disk->d_consumer->provider &&
2338 		    disk->d_consumer->provider->stripesize > pp->stripesize) {
2339 			pp->stripesize = disk->d_consumer->provider->stripesize;
2340 			pp->stripeoffset = disk->d_consumer->provider->stripeoffset;
2341 		}
2342 	}
2343 	pp->stripesize *= sc->sc_ndisks - 1;
2344 	pp->stripeoffset *= sc->sc_ndisks - 1;
2345 	sc->sc_provider = pp;
2346 	g_error_provider(pp, 0);
2347 	g_topology_unlock();
2348 	G_RAID3_DEBUG(0, "Device %s launched (%u/%u).", pp->name,
2349 	    g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE), sc->sc_ndisks);
2350 
2351 	if (sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED)
2352 		g_raid3_sync_start(sc);
2353 }
2354 
2355 static void
2356 g_raid3_destroy_provider(struct g_raid3_softc *sc)
2357 {
2358 	struct bio *bp;
2359 
2360 	g_topology_assert_not();
2361 	KASSERT(sc->sc_provider != NULL, ("NULL provider (device=%s).",
2362 	    sc->sc_name));
2363 
2364 	g_topology_lock();
2365 	g_error_provider(sc->sc_provider, ENXIO);
2366 	mtx_lock(&sc->sc_queue_mtx);
2367 	while ((bp = bioq_first(&sc->sc_queue)) != NULL) {
2368 		bioq_remove(&sc->sc_queue, bp);
2369 		g_io_deliver(bp, ENXIO);
2370 	}
2371 	mtx_unlock(&sc->sc_queue_mtx);
2372 	G_RAID3_DEBUG(0, "Device %s: provider %s destroyed.", sc->sc_name,
2373 	    sc->sc_provider->name);
2374 	g_wither_provider(sc->sc_provider, ENXIO);
2375 	g_topology_unlock();
2376 	sc->sc_provider = NULL;
2377 	if (sc->sc_syncdisk != NULL)
2378 		g_raid3_sync_stop(sc, 1);
2379 }
2380 
2381 static void
2382 g_raid3_go(void *arg)
2383 {
2384 	struct g_raid3_softc *sc;
2385 
2386 	sc = arg;
2387 	G_RAID3_DEBUG(0, "Force device %s start due to timeout.", sc->sc_name);
2388 	g_raid3_event_send(sc, 0,
2389 	    G_RAID3_EVENT_DONTWAIT | G_RAID3_EVENT_DEVICE);
2390 }
2391 
2392 static u_int
2393 g_raid3_determine_state(struct g_raid3_disk *disk)
2394 {
2395 	struct g_raid3_softc *sc;
2396 	u_int state;
2397 
2398 	sc = disk->d_softc;
2399 	if (sc->sc_syncid == disk->d_sync.ds_syncid) {
2400 		if ((disk->d_flags &
2401 		    G_RAID3_DISK_FLAG_SYNCHRONIZING) == 0) {
2402 			/* Disk does not need synchronization. */
2403 			state = G_RAID3_DISK_STATE_ACTIVE;
2404 		} else {
2405 			if ((sc->sc_flags &
2406 			     G_RAID3_DEVICE_FLAG_NOAUTOSYNC) == 0 ||
2407 			    (disk->d_flags &
2408 			     G_RAID3_DISK_FLAG_FORCE_SYNC) != 0) {
2409 				/*
2410 				 * We can start synchronization from
2411 				 * the stored offset.
2412 				 */
2413 				state = G_RAID3_DISK_STATE_SYNCHRONIZING;
2414 			} else {
2415 				state = G_RAID3_DISK_STATE_STALE;
2416 			}
2417 		}
2418 	} else if (disk->d_sync.ds_syncid < sc->sc_syncid) {
2419 		/*
2420 		 * Reset all synchronization data for this disk,
2421 		 * because if it even was synchronized, it was
2422 		 * synchronized to disks with different syncid.
2423 		 */
2424 		disk->d_flags |= G_RAID3_DISK_FLAG_SYNCHRONIZING;
2425 		disk->d_sync.ds_offset = 0;
2426 		disk->d_sync.ds_offset_done = 0;
2427 		disk->d_sync.ds_syncid = sc->sc_syncid;
2428 		if ((sc->sc_flags & G_RAID3_DEVICE_FLAG_NOAUTOSYNC) == 0 ||
2429 		    (disk->d_flags & G_RAID3_DISK_FLAG_FORCE_SYNC) != 0) {
2430 			state = G_RAID3_DISK_STATE_SYNCHRONIZING;
2431 		} else {
2432 			state = G_RAID3_DISK_STATE_STALE;
2433 		}
2434 	} else /* if (sc->sc_syncid < disk->d_sync.ds_syncid) */ {
2435 		/*
2436 		 * Not good, NOT GOOD!
2437 		 * It means that device was started on stale disks
2438 		 * and more fresh disk just arrive.
2439 		 * If there were writes, device is broken, sorry.
2440 		 * I think the best choice here is don't touch
2441 		 * this disk and inform the user loudly.
2442 		 */
2443 		G_RAID3_DEBUG(0, "Device %s was started before the freshest "
2444 		    "disk (%s) arrives!! It will not be connected to the "
2445 		    "running device.", sc->sc_name,
2446 		    g_raid3_get_diskname(disk));
2447 		g_raid3_destroy_disk(disk);
2448 		state = G_RAID3_DISK_STATE_NONE;
2449 		/* Return immediately, because disk was destroyed. */
2450 		return (state);
2451 	}
2452 	G_RAID3_DEBUG(3, "State for %s disk: %s.",
2453 	    g_raid3_get_diskname(disk), g_raid3_disk_state2str(state));
2454 	return (state);
2455 }
2456 
2457 /*
2458  * Update device state.
2459  */
2460 static void
2461 g_raid3_update_device(struct g_raid3_softc *sc, boolean_t force)
2462 {
2463 	struct g_raid3_disk *disk;
2464 	u_int state;
2465 
2466 	sx_assert(&sc->sc_lock, SX_XLOCKED);
2467 
2468 	switch (sc->sc_state) {
2469 	case G_RAID3_DEVICE_STATE_STARTING:
2470 	    {
2471 		u_int n, ndirty, ndisks, genid, syncid;
2472 
2473 		KASSERT(sc->sc_provider == NULL,
2474 		    ("Non-NULL provider in STARTING state (%s).", sc->sc_name));
2475 		/*
2476 		 * Are we ready? We are, if all disks are connected or
2477 		 * one disk is missing and 'force' is true.
2478 		 */
2479 		if (g_raid3_ndisks(sc, -1) + force == sc->sc_ndisks) {
2480 			if (!force)
2481 				callout_drain(&sc->sc_callout);
2482 		} else {
2483 			if (force) {
2484 				/*
2485 				 * Timeout expired, so destroy device.
2486 				 */
2487 				sc->sc_flags |= G_RAID3_DEVICE_FLAG_DESTROY;
2488 				G_RAID3_DEBUG(1, "root_mount_rel[%u] %p",
2489 				    __LINE__, sc->sc_rootmount);
2490 				root_mount_rel(sc->sc_rootmount);
2491 				sc->sc_rootmount = NULL;
2492 			}
2493 			return;
2494 		}
2495 
2496 		/*
2497 		 * Find the biggest genid.
2498 		 */
2499 		genid = 0;
2500 		for (n = 0; n < sc->sc_ndisks; n++) {
2501 			disk = &sc->sc_disks[n];
2502 			if (disk->d_state == G_RAID3_DISK_STATE_NODISK)
2503 				continue;
2504 			if (disk->d_genid > genid)
2505 				genid = disk->d_genid;
2506 		}
2507 		sc->sc_genid = genid;
2508 		/*
2509 		 * Remove all disks without the biggest genid.
2510 		 */
2511 		for (n = 0; n < sc->sc_ndisks; n++) {
2512 			disk = &sc->sc_disks[n];
2513 			if (disk->d_state == G_RAID3_DISK_STATE_NODISK)
2514 				continue;
2515 			if (disk->d_genid < genid) {
2516 				G_RAID3_DEBUG(0,
2517 				    "Component %s (device %s) broken, skipping.",
2518 				    g_raid3_get_diskname(disk), sc->sc_name);
2519 				g_raid3_destroy_disk(disk);
2520 			}
2521 		}
2522 
2523 		/*
2524 		 * There must be at least 'sc->sc_ndisks - 1' components
2525 		 * with the same syncid and without SYNCHRONIZING flag.
2526 		 */
2527 
2528 		/*
2529 		 * Find the biggest syncid, number of valid components and
2530 		 * number of dirty components.
2531 		 */
2532 		ndirty = ndisks = syncid = 0;
2533 		for (n = 0; n < sc->sc_ndisks; n++) {
2534 			disk = &sc->sc_disks[n];
2535 			if (disk->d_state == G_RAID3_DISK_STATE_NODISK)
2536 				continue;
2537 			if ((disk->d_flags & G_RAID3_DISK_FLAG_DIRTY) != 0)
2538 				ndirty++;
2539 			if (disk->d_sync.ds_syncid > syncid) {
2540 				syncid = disk->d_sync.ds_syncid;
2541 				ndisks = 0;
2542 			} else if (disk->d_sync.ds_syncid < syncid) {
2543 				continue;
2544 			}
2545 			if ((disk->d_flags &
2546 			    G_RAID3_DISK_FLAG_SYNCHRONIZING) != 0) {
2547 				continue;
2548 			}
2549 			ndisks++;
2550 		}
2551 		/*
2552 		 * Do we have enough valid components?
2553 		 */
2554 		if (ndisks + 1 < sc->sc_ndisks) {
2555 			G_RAID3_DEBUG(0,
2556 			    "Device %s is broken, too few valid components.",
2557 			    sc->sc_name);
2558 			sc->sc_flags |= G_RAID3_DEVICE_FLAG_DESTROY;
2559 			return;
2560 		}
2561 		/*
2562 		 * If there is one DIRTY component and all disks are present,
2563 		 * mark it for synchronization. If there is more than one DIRTY
2564 		 * component, mark parity component for synchronization.
2565 		 */
2566 		if (ndisks == sc->sc_ndisks && ndirty == 1) {
2567 			for (n = 0; n < sc->sc_ndisks; n++) {
2568 				disk = &sc->sc_disks[n];
2569 				if ((disk->d_flags &
2570 				    G_RAID3_DISK_FLAG_DIRTY) == 0) {
2571 					continue;
2572 				}
2573 				disk->d_flags |=
2574 				    G_RAID3_DISK_FLAG_SYNCHRONIZING;
2575 			}
2576 		} else if (ndisks == sc->sc_ndisks && ndirty > 1) {
2577 			disk = &sc->sc_disks[sc->sc_ndisks - 1];
2578 			disk->d_flags |= G_RAID3_DISK_FLAG_SYNCHRONIZING;
2579 		}
2580 
2581 		sc->sc_syncid = syncid;
2582 		if (force) {
2583 			/* Remember to bump syncid on first write. */
2584 			sc->sc_bump_id |= G_RAID3_BUMP_SYNCID;
2585 		}
2586 		if (ndisks == sc->sc_ndisks)
2587 			state = G_RAID3_DEVICE_STATE_COMPLETE;
2588 		else /* if (ndisks == sc->sc_ndisks - 1) */
2589 			state = G_RAID3_DEVICE_STATE_DEGRADED;
2590 		G_RAID3_DEBUG(1, "Device %s state changed from %s to %s.",
2591 		    sc->sc_name, g_raid3_device_state2str(sc->sc_state),
2592 		    g_raid3_device_state2str(state));
2593 		sc->sc_state = state;
2594 		for (n = 0; n < sc->sc_ndisks; n++) {
2595 			disk = &sc->sc_disks[n];
2596 			if (disk->d_state == G_RAID3_DISK_STATE_NODISK)
2597 				continue;
2598 			state = g_raid3_determine_state(disk);
2599 			g_raid3_event_send(disk, state, G_RAID3_EVENT_DONTWAIT);
2600 			if (state == G_RAID3_DISK_STATE_STALE)
2601 				sc->sc_bump_id |= G_RAID3_BUMP_SYNCID;
2602 		}
2603 		break;
2604 	    }
2605 	case G_RAID3_DEVICE_STATE_DEGRADED:
2606 		/*
2607 		 * Genid need to be bumped immediately, so do it here.
2608 		 */
2609 		if ((sc->sc_bump_id & G_RAID3_BUMP_GENID) != 0) {
2610 			sc->sc_bump_id &= ~G_RAID3_BUMP_GENID;
2611 			g_raid3_bump_genid(sc);
2612 		}
2613 
2614 		if (g_raid3_ndisks(sc, G_RAID3_DISK_STATE_NEW) > 0)
2615 			return;
2616 		if (g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE) <
2617 		    sc->sc_ndisks - 1) {
2618 			if (sc->sc_provider != NULL)
2619 				g_raid3_destroy_provider(sc);
2620 			sc->sc_flags |= G_RAID3_DEVICE_FLAG_DESTROY;
2621 			return;
2622 		}
2623 		if (g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE) ==
2624 		    sc->sc_ndisks) {
2625 			state = G_RAID3_DEVICE_STATE_COMPLETE;
2626 			G_RAID3_DEBUG(1,
2627 			    "Device %s state changed from %s to %s.",
2628 			    sc->sc_name, g_raid3_device_state2str(sc->sc_state),
2629 			    g_raid3_device_state2str(state));
2630 			sc->sc_state = state;
2631 		}
2632 		if (sc->sc_provider == NULL)
2633 			g_raid3_launch_provider(sc);
2634 		if (sc->sc_rootmount != NULL) {
2635 			G_RAID3_DEBUG(1, "root_mount_rel[%u] %p", __LINE__,
2636 			    sc->sc_rootmount);
2637 			root_mount_rel(sc->sc_rootmount);
2638 			sc->sc_rootmount = NULL;
2639 		}
2640 		break;
2641 	case G_RAID3_DEVICE_STATE_COMPLETE:
2642 		/*
2643 		 * Genid need to be bumped immediately, so do it here.
2644 		 */
2645 		if ((sc->sc_bump_id & G_RAID3_BUMP_GENID) != 0) {
2646 			sc->sc_bump_id &= ~G_RAID3_BUMP_GENID;
2647 			g_raid3_bump_genid(sc);
2648 		}
2649 
2650 		if (g_raid3_ndisks(sc, G_RAID3_DISK_STATE_NEW) > 0)
2651 			return;
2652 		KASSERT(g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE) >=
2653 		    sc->sc_ndisks - 1,
2654 		    ("Too few ACTIVE components in COMPLETE state (device %s).",
2655 		    sc->sc_name));
2656 		if (g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE) ==
2657 		    sc->sc_ndisks - 1) {
2658 			state = G_RAID3_DEVICE_STATE_DEGRADED;
2659 			G_RAID3_DEBUG(1,
2660 			    "Device %s state changed from %s to %s.",
2661 			    sc->sc_name, g_raid3_device_state2str(sc->sc_state),
2662 			    g_raid3_device_state2str(state));
2663 			sc->sc_state = state;
2664 		}
2665 		if (sc->sc_provider == NULL)
2666 			g_raid3_launch_provider(sc);
2667 		if (sc->sc_rootmount != NULL) {
2668 			G_RAID3_DEBUG(1, "root_mount_rel[%u] %p", __LINE__,
2669 			    sc->sc_rootmount);
2670 			root_mount_rel(sc->sc_rootmount);
2671 			sc->sc_rootmount = NULL;
2672 		}
2673 		break;
2674 	default:
2675 		KASSERT(1 == 0, ("Wrong device state (%s, %s).", sc->sc_name,
2676 		    g_raid3_device_state2str(sc->sc_state)));
2677 		break;
2678 	}
2679 }
2680 
2681 /*
2682  * Update disk state and device state if needed.
2683  */
2684 #define	DISK_STATE_CHANGED()	G_RAID3_DEBUG(1,			\
2685 	"Disk %s state changed from %s to %s (device %s).",		\
2686 	g_raid3_get_diskname(disk),					\
2687 	g_raid3_disk_state2str(disk->d_state),				\
2688 	g_raid3_disk_state2str(state), sc->sc_name)
2689 static int
2690 g_raid3_update_disk(struct g_raid3_disk *disk, u_int state)
2691 {
2692 	struct g_raid3_softc *sc;
2693 
2694 	sc = disk->d_softc;
2695 	sx_assert(&sc->sc_lock, SX_XLOCKED);
2696 
2697 again:
2698 	G_RAID3_DEBUG(3, "Changing disk %s state from %s to %s.",
2699 	    g_raid3_get_diskname(disk), g_raid3_disk_state2str(disk->d_state),
2700 	    g_raid3_disk_state2str(state));
2701 	switch (state) {
2702 	case G_RAID3_DISK_STATE_NEW:
2703 		/*
2704 		 * Possible scenarios:
2705 		 * 1. New disk arrive.
2706 		 */
2707 		/* Previous state should be NONE. */
2708 		KASSERT(disk->d_state == G_RAID3_DISK_STATE_NONE,
2709 		    ("Wrong disk state (%s, %s).", g_raid3_get_diskname(disk),
2710 		    g_raid3_disk_state2str(disk->d_state)));
2711 		DISK_STATE_CHANGED();
2712 
2713 		disk->d_state = state;
2714 		G_RAID3_DEBUG(1, "Device %s: provider %s detected.",
2715 		    sc->sc_name, g_raid3_get_diskname(disk));
2716 		if (sc->sc_state == G_RAID3_DEVICE_STATE_STARTING)
2717 			break;
2718 		KASSERT(sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED ||
2719 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE,
2720 		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2721 		    g_raid3_device_state2str(sc->sc_state),
2722 		    g_raid3_get_diskname(disk),
2723 		    g_raid3_disk_state2str(disk->d_state)));
2724 		state = g_raid3_determine_state(disk);
2725 		if (state != G_RAID3_DISK_STATE_NONE)
2726 			goto again;
2727 		break;
2728 	case G_RAID3_DISK_STATE_ACTIVE:
2729 		/*
2730 		 * Possible scenarios:
2731 		 * 1. New disk does not need synchronization.
2732 		 * 2. Synchronization process finished successfully.
2733 		 */
2734 		KASSERT(sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED ||
2735 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE,
2736 		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2737 		    g_raid3_device_state2str(sc->sc_state),
2738 		    g_raid3_get_diskname(disk),
2739 		    g_raid3_disk_state2str(disk->d_state)));
2740 		/* Previous state should be NEW or SYNCHRONIZING. */
2741 		KASSERT(disk->d_state == G_RAID3_DISK_STATE_NEW ||
2742 		    disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING,
2743 		    ("Wrong disk state (%s, %s).", g_raid3_get_diskname(disk),
2744 		    g_raid3_disk_state2str(disk->d_state)));
2745 		DISK_STATE_CHANGED();
2746 
2747 		if (disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING) {
2748 			disk->d_flags &= ~G_RAID3_DISK_FLAG_SYNCHRONIZING;
2749 			disk->d_flags &= ~G_RAID3_DISK_FLAG_FORCE_SYNC;
2750 			g_raid3_sync_stop(sc, 0);
2751 		}
2752 		disk->d_state = state;
2753 		disk->d_sync.ds_offset = 0;
2754 		disk->d_sync.ds_offset_done = 0;
2755 		g_raid3_update_idle(sc, disk);
2756 		g_raid3_update_metadata(disk);
2757 		G_RAID3_DEBUG(1, "Device %s: provider %s activated.",
2758 		    sc->sc_name, g_raid3_get_diskname(disk));
2759 		break;
2760 	case G_RAID3_DISK_STATE_STALE:
2761 		/*
2762 		 * Possible scenarios:
2763 		 * 1. Stale disk was connected.
2764 		 */
2765 		/* Previous state should be NEW. */
2766 		KASSERT(disk->d_state == G_RAID3_DISK_STATE_NEW,
2767 		    ("Wrong disk state (%s, %s).", g_raid3_get_diskname(disk),
2768 		    g_raid3_disk_state2str(disk->d_state)));
2769 		KASSERT(sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED ||
2770 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE,
2771 		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2772 		    g_raid3_device_state2str(sc->sc_state),
2773 		    g_raid3_get_diskname(disk),
2774 		    g_raid3_disk_state2str(disk->d_state)));
2775 		/*
2776 		 * STALE state is only possible if device is marked
2777 		 * NOAUTOSYNC.
2778 		 */
2779 		KASSERT((sc->sc_flags & G_RAID3_DEVICE_FLAG_NOAUTOSYNC) != 0,
2780 		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2781 		    g_raid3_device_state2str(sc->sc_state),
2782 		    g_raid3_get_diskname(disk),
2783 		    g_raid3_disk_state2str(disk->d_state)));
2784 		DISK_STATE_CHANGED();
2785 
2786 		disk->d_flags &= ~G_RAID3_DISK_FLAG_DIRTY;
2787 		disk->d_state = state;
2788 		g_raid3_update_metadata(disk);
2789 		G_RAID3_DEBUG(0, "Device %s: provider %s is stale.",
2790 		    sc->sc_name, g_raid3_get_diskname(disk));
2791 		break;
2792 	case G_RAID3_DISK_STATE_SYNCHRONIZING:
2793 		/*
2794 		 * Possible scenarios:
2795 		 * 1. Disk which needs synchronization was connected.
2796 		 */
2797 		/* Previous state should be NEW. */
2798 		KASSERT(disk->d_state == G_RAID3_DISK_STATE_NEW,
2799 		    ("Wrong disk state (%s, %s).", g_raid3_get_diskname(disk),
2800 		    g_raid3_disk_state2str(disk->d_state)));
2801 		KASSERT(sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED ||
2802 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE,
2803 		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2804 		    g_raid3_device_state2str(sc->sc_state),
2805 		    g_raid3_get_diskname(disk),
2806 		    g_raid3_disk_state2str(disk->d_state)));
2807 		DISK_STATE_CHANGED();
2808 
2809 		if (disk->d_state == G_RAID3_DISK_STATE_NEW)
2810 			disk->d_flags &= ~G_RAID3_DISK_FLAG_DIRTY;
2811 		disk->d_state = state;
2812 		if (sc->sc_provider != NULL) {
2813 			g_raid3_sync_start(sc);
2814 			g_raid3_update_metadata(disk);
2815 		}
2816 		break;
2817 	case G_RAID3_DISK_STATE_DISCONNECTED:
2818 		/*
2819 		 * Possible scenarios:
2820 		 * 1. Device wasn't running yet, but disk disappear.
2821 		 * 2. Disk was active and disapppear.
2822 		 * 3. Disk disappear during synchronization process.
2823 		 */
2824 		if (sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED ||
2825 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE) {
2826 			/*
2827 			 * Previous state should be ACTIVE, STALE or
2828 			 * SYNCHRONIZING.
2829 			 */
2830 			KASSERT(disk->d_state == G_RAID3_DISK_STATE_ACTIVE ||
2831 			    disk->d_state == G_RAID3_DISK_STATE_STALE ||
2832 			    disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING,
2833 			    ("Wrong disk state (%s, %s).",
2834 			    g_raid3_get_diskname(disk),
2835 			    g_raid3_disk_state2str(disk->d_state)));
2836 		} else if (sc->sc_state == G_RAID3_DEVICE_STATE_STARTING) {
2837 			/* Previous state should be NEW. */
2838 			KASSERT(disk->d_state == G_RAID3_DISK_STATE_NEW,
2839 			    ("Wrong disk state (%s, %s).",
2840 			    g_raid3_get_diskname(disk),
2841 			    g_raid3_disk_state2str(disk->d_state)));
2842 			/*
2843 			 * Reset bumping syncid if disk disappeared in STARTING
2844 			 * state.
2845 			 */
2846 			if ((sc->sc_bump_id & G_RAID3_BUMP_SYNCID) != 0)
2847 				sc->sc_bump_id &= ~G_RAID3_BUMP_SYNCID;
2848 #ifdef	INVARIANTS
2849 		} else {
2850 			KASSERT(1 == 0, ("Wrong device state (%s, %s, %s, %s).",
2851 			    sc->sc_name,
2852 			    g_raid3_device_state2str(sc->sc_state),
2853 			    g_raid3_get_diskname(disk),
2854 			    g_raid3_disk_state2str(disk->d_state)));
2855 #endif
2856 		}
2857 		DISK_STATE_CHANGED();
2858 		G_RAID3_DEBUG(0, "Device %s: provider %s disconnected.",
2859 		    sc->sc_name, g_raid3_get_diskname(disk));
2860 
2861 		g_raid3_destroy_disk(disk);
2862 		break;
2863 	default:
2864 		KASSERT(1 == 0, ("Unknown state (%u).", state));
2865 		break;
2866 	}
2867 	return (0);
2868 }
2869 #undef	DISK_STATE_CHANGED
2870 
2871 int
2872 g_raid3_read_metadata(struct g_consumer *cp, struct g_raid3_metadata *md)
2873 {
2874 	struct g_provider *pp;
2875 	u_char *buf;
2876 	int error;
2877 
2878 	g_topology_assert();
2879 
2880 	error = g_access(cp, 1, 0, 0);
2881 	if (error != 0)
2882 		return (error);
2883 	pp = cp->provider;
2884 	g_topology_unlock();
2885 	/* Metadata are stored on last sector. */
2886 	buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
2887 	    &error);
2888 	g_topology_lock();
2889 	g_access(cp, -1, 0, 0);
2890 	if (buf == NULL) {
2891 		G_RAID3_DEBUG(1, "Cannot read metadata from %s (error=%d).",
2892 		    cp->provider->name, error);
2893 		return (error);
2894 	}
2895 
2896 	/* Decode metadata. */
2897 	error = raid3_metadata_decode(buf, md);
2898 	g_free(buf);
2899 	if (strcmp(md->md_magic, G_RAID3_MAGIC) != 0)
2900 		return (EINVAL);
2901 	if (md->md_version > G_RAID3_VERSION) {
2902 		G_RAID3_DEBUG(0,
2903 		    "Kernel module is too old to handle metadata from %s.",
2904 		    cp->provider->name);
2905 		return (EINVAL);
2906 	}
2907 	if (error != 0) {
2908 		G_RAID3_DEBUG(1, "MD5 metadata hash mismatch for provider %s.",
2909 		    cp->provider->name);
2910 		return (error);
2911 	}
2912 	if (md->md_sectorsize > MAXPHYS) {
2913 		G_RAID3_DEBUG(0, "The blocksize is too big.");
2914 		return (EINVAL);
2915 	}
2916 
2917 	return (0);
2918 }
2919 
2920 static int
2921 g_raid3_check_metadata(struct g_raid3_softc *sc, struct g_provider *pp,
2922     struct g_raid3_metadata *md)
2923 {
2924 
2925 	if (md->md_no >= sc->sc_ndisks) {
2926 		G_RAID3_DEBUG(1, "Invalid disk %s number (no=%u), skipping.",
2927 		    pp->name, md->md_no);
2928 		return (EINVAL);
2929 	}
2930 	if (sc->sc_disks[md->md_no].d_state != G_RAID3_DISK_STATE_NODISK) {
2931 		G_RAID3_DEBUG(1, "Disk %s (no=%u) already exists, skipping.",
2932 		    pp->name, md->md_no);
2933 		return (EEXIST);
2934 	}
2935 	if (md->md_all != sc->sc_ndisks) {
2936 		G_RAID3_DEBUG(1,
2937 		    "Invalid '%s' field on disk %s (device %s), skipping.",
2938 		    "md_all", pp->name, sc->sc_name);
2939 		return (EINVAL);
2940 	}
2941 	if ((md->md_mediasize % md->md_sectorsize) != 0) {
2942 		G_RAID3_DEBUG(1, "Invalid metadata (mediasize %% sectorsize != "
2943 		    "0) on disk %s (device %s), skipping.", pp->name,
2944 		    sc->sc_name);
2945 		return (EINVAL);
2946 	}
2947 	if (md->md_mediasize != sc->sc_mediasize) {
2948 		G_RAID3_DEBUG(1,
2949 		    "Invalid '%s' field on disk %s (device %s), skipping.",
2950 		    "md_mediasize", pp->name, sc->sc_name);
2951 		return (EINVAL);
2952 	}
2953 	if ((md->md_mediasize % (sc->sc_ndisks - 1)) != 0) {
2954 		G_RAID3_DEBUG(1,
2955 		    "Invalid '%s' field on disk %s (device %s), skipping.",
2956 		    "md_mediasize", pp->name, sc->sc_name);
2957 		return (EINVAL);
2958 	}
2959 	if ((sc->sc_mediasize / (sc->sc_ndisks - 1)) > pp->mediasize) {
2960 		G_RAID3_DEBUG(1,
2961 		    "Invalid size of disk %s (device %s), skipping.", pp->name,
2962 		    sc->sc_name);
2963 		return (EINVAL);
2964 	}
2965 	if ((md->md_sectorsize / pp->sectorsize) < sc->sc_ndisks - 1) {
2966 		G_RAID3_DEBUG(1,
2967 		    "Invalid '%s' field on disk %s (device %s), skipping.",
2968 		    "md_sectorsize", pp->name, sc->sc_name);
2969 		return (EINVAL);
2970 	}
2971 	if (md->md_sectorsize != sc->sc_sectorsize) {
2972 		G_RAID3_DEBUG(1,
2973 		    "Invalid '%s' field on disk %s (device %s), skipping.",
2974 		    "md_sectorsize", pp->name, sc->sc_name);
2975 		return (EINVAL);
2976 	}
2977 	if ((sc->sc_sectorsize % pp->sectorsize) != 0) {
2978 		G_RAID3_DEBUG(1,
2979 		    "Invalid sector size of disk %s (device %s), skipping.",
2980 		    pp->name, sc->sc_name);
2981 		return (EINVAL);
2982 	}
2983 	if ((md->md_mflags & ~G_RAID3_DEVICE_FLAG_MASK) != 0) {
2984 		G_RAID3_DEBUG(1,
2985 		    "Invalid device flags on disk %s (device %s), skipping.",
2986 		    pp->name, sc->sc_name);
2987 		return (EINVAL);
2988 	}
2989 	if ((md->md_mflags & G_RAID3_DEVICE_FLAG_VERIFY) != 0 &&
2990 	    (md->md_mflags & G_RAID3_DEVICE_FLAG_ROUND_ROBIN) != 0) {
2991 		/*
2992 		 * VERIFY and ROUND-ROBIN options are mutally exclusive.
2993 		 */
2994 		G_RAID3_DEBUG(1, "Both VERIFY and ROUND-ROBIN flags exist on "
2995 		    "disk %s (device %s), skipping.", pp->name, sc->sc_name);
2996 		return (EINVAL);
2997 	}
2998 	if ((md->md_dflags & ~G_RAID3_DISK_FLAG_MASK) != 0) {
2999 		G_RAID3_DEBUG(1,
3000 		    "Invalid disk flags on disk %s (device %s), skipping.",
3001 		    pp->name, sc->sc_name);
3002 		return (EINVAL);
3003 	}
3004 	return (0);
3005 }
3006 
3007 int
3008 g_raid3_add_disk(struct g_raid3_softc *sc, struct g_provider *pp,
3009     struct g_raid3_metadata *md)
3010 {
3011 	struct g_raid3_disk *disk;
3012 	int error;
3013 
3014 	g_topology_assert_not();
3015 	G_RAID3_DEBUG(2, "Adding disk %s.", pp->name);
3016 
3017 	error = g_raid3_check_metadata(sc, pp, md);
3018 	if (error != 0)
3019 		return (error);
3020 	if (sc->sc_state != G_RAID3_DEVICE_STATE_STARTING &&
3021 	    md->md_genid < sc->sc_genid) {
3022 		G_RAID3_DEBUG(0, "Component %s (device %s) broken, skipping.",
3023 		    pp->name, sc->sc_name);
3024 		return (EINVAL);
3025 	}
3026 	disk = g_raid3_init_disk(sc, pp, md, &error);
3027 	if (disk == NULL)
3028 		return (error);
3029 	error = g_raid3_event_send(disk, G_RAID3_DISK_STATE_NEW,
3030 	    G_RAID3_EVENT_WAIT);
3031 	if (error != 0)
3032 		return (error);
3033 	if (md->md_version < G_RAID3_VERSION) {
3034 		G_RAID3_DEBUG(0, "Upgrading metadata on %s (v%d->v%d).",
3035 		    pp->name, md->md_version, G_RAID3_VERSION);
3036 		g_raid3_update_metadata(disk);
3037 	}
3038 	return (0);
3039 }
3040 
3041 static void
3042 g_raid3_destroy_delayed(void *arg, int flag)
3043 {
3044 	struct g_raid3_softc *sc;
3045 	int error;
3046 
3047 	if (flag == EV_CANCEL) {
3048 		G_RAID3_DEBUG(1, "Destroying canceled.");
3049 		return;
3050 	}
3051 	sc = arg;
3052 	g_topology_unlock();
3053 	sx_xlock(&sc->sc_lock);
3054 	KASSERT((sc->sc_flags & G_RAID3_DEVICE_FLAG_DESTROY) == 0,
3055 	    ("DESTROY flag set on %s.", sc->sc_name));
3056 	KASSERT((sc->sc_flags & G_RAID3_DEVICE_FLAG_DESTROYING) != 0,
3057 	    ("DESTROYING flag not set on %s.", sc->sc_name));
3058 	G_RAID3_DEBUG(0, "Destroying %s (delayed).", sc->sc_name);
3059 	error = g_raid3_destroy(sc, G_RAID3_DESTROY_SOFT);
3060 	if (error != 0) {
3061 		G_RAID3_DEBUG(0, "Cannot destroy %s.", sc->sc_name);
3062 		sx_xunlock(&sc->sc_lock);
3063 	}
3064 	g_topology_lock();
3065 }
3066 
3067 static int
3068 g_raid3_access(struct g_provider *pp, int acr, int acw, int ace)
3069 {
3070 	struct g_raid3_softc *sc;
3071 	int dcr, dcw, dce, error = 0;
3072 
3073 	g_topology_assert();
3074 	G_RAID3_DEBUG(2, "Access request for %s: r%dw%de%d.", pp->name, acr,
3075 	    acw, ace);
3076 
3077 	sc = pp->geom->softc;
3078 	if (sc == NULL && acr <= 0 && acw <= 0 && ace <= 0)
3079 		return (0);
3080 	KASSERT(sc != NULL, ("NULL softc (provider=%s).", pp->name));
3081 
3082 	dcr = pp->acr + acr;
3083 	dcw = pp->acw + acw;
3084 	dce = pp->ace + ace;
3085 
3086 	g_topology_unlock();
3087 	sx_xlock(&sc->sc_lock);
3088 	if ((sc->sc_flags & G_RAID3_DEVICE_FLAG_DESTROY) != 0 ||
3089 	    g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE) < sc->sc_ndisks - 1) {
3090 		if (acr > 0 || acw > 0 || ace > 0)
3091 			error = ENXIO;
3092 		goto end;
3093 	}
3094 	if (dcw == 0)
3095 		g_raid3_idle(sc, dcw);
3096 	if ((sc->sc_flags & G_RAID3_DEVICE_FLAG_DESTROYING) != 0) {
3097 		if (acr > 0 || acw > 0 || ace > 0) {
3098 			error = ENXIO;
3099 			goto end;
3100 		}
3101 		if (dcr == 0 && dcw == 0 && dce == 0) {
3102 			g_post_event(g_raid3_destroy_delayed, sc, M_WAITOK,
3103 			    sc, NULL);
3104 		}
3105 	}
3106 end:
3107 	sx_xunlock(&sc->sc_lock);
3108 	g_topology_lock();
3109 	return (error);
3110 }
3111 
3112 static struct g_geom *
3113 g_raid3_create(struct g_class *mp, const struct g_raid3_metadata *md)
3114 {
3115 	struct g_raid3_softc *sc;
3116 	struct g_geom *gp;
3117 	int error, timeout;
3118 	u_int n;
3119 
3120 	g_topology_assert();
3121 	G_RAID3_DEBUG(1, "Creating device %s (id=%u).", md->md_name, md->md_id);
3122 
3123 	/* One disk is minimum. */
3124 	if (md->md_all < 1)
3125 		return (NULL);
3126 	/*
3127 	 * Action geom.
3128 	 */
3129 	gp = g_new_geomf(mp, "%s", md->md_name);
3130 	sc = malloc(sizeof(*sc), M_RAID3, M_WAITOK | M_ZERO);
3131 	sc->sc_disks = malloc(sizeof(struct g_raid3_disk) * md->md_all, M_RAID3,
3132 	    M_WAITOK | M_ZERO);
3133 	gp->start = g_raid3_start;
3134 	gp->orphan = g_raid3_orphan;
3135 	gp->access = g_raid3_access;
3136 	gp->dumpconf = g_raid3_dumpconf;
3137 
3138 	sc->sc_id = md->md_id;
3139 	sc->sc_mediasize = md->md_mediasize;
3140 	sc->sc_sectorsize = md->md_sectorsize;
3141 	sc->sc_ndisks = md->md_all;
3142 	sc->sc_round_robin = 0;
3143 	sc->sc_flags = md->md_mflags;
3144 	sc->sc_bump_id = 0;
3145 	sc->sc_idle = 1;
3146 	sc->sc_last_write = time_uptime;
3147 	sc->sc_writes = 0;
3148 	for (n = 0; n < sc->sc_ndisks; n++) {
3149 		sc->sc_disks[n].d_softc = sc;
3150 		sc->sc_disks[n].d_no = n;
3151 		sc->sc_disks[n].d_state = G_RAID3_DISK_STATE_NODISK;
3152 	}
3153 	sx_init(&sc->sc_lock, "graid3:lock");
3154 	bioq_init(&sc->sc_queue);
3155 	mtx_init(&sc->sc_queue_mtx, "graid3:queue", NULL, MTX_DEF);
3156 	bioq_init(&sc->sc_regular_delayed);
3157 	bioq_init(&sc->sc_inflight);
3158 	bioq_init(&sc->sc_sync_delayed);
3159 	TAILQ_INIT(&sc->sc_events);
3160 	mtx_init(&sc->sc_events_mtx, "graid3:events", NULL, MTX_DEF);
3161 	callout_init(&sc->sc_callout, 1);
3162 	sc->sc_state = G_RAID3_DEVICE_STATE_STARTING;
3163 	gp->softc = sc;
3164 	sc->sc_geom = gp;
3165 	sc->sc_provider = NULL;
3166 	/*
3167 	 * Synchronization geom.
3168 	 */
3169 	gp = g_new_geomf(mp, "%s.sync", md->md_name);
3170 	gp->softc = sc;
3171 	gp->orphan = g_raid3_orphan;
3172 	sc->sc_sync.ds_geom = gp;
3173 
3174 	if (!g_raid3_use_malloc) {
3175 		sc->sc_zones[G_RAID3_ZONE_64K].sz_zone = uma_zcreate("gr3:64k",
3176 		    65536, g_raid3_uma_ctor, g_raid3_uma_dtor, NULL, NULL,
3177 		    UMA_ALIGN_PTR, 0);
3178 		sc->sc_zones[G_RAID3_ZONE_64K].sz_inuse = 0;
3179 		sc->sc_zones[G_RAID3_ZONE_64K].sz_max = g_raid3_n64k;
3180 		sc->sc_zones[G_RAID3_ZONE_64K].sz_requested =
3181 		    sc->sc_zones[G_RAID3_ZONE_64K].sz_failed = 0;
3182 		sc->sc_zones[G_RAID3_ZONE_16K].sz_zone = uma_zcreate("gr3:16k",
3183 		    16384, g_raid3_uma_ctor, g_raid3_uma_dtor, NULL, NULL,
3184 		    UMA_ALIGN_PTR, 0);
3185 		sc->sc_zones[G_RAID3_ZONE_16K].sz_inuse = 0;
3186 		sc->sc_zones[G_RAID3_ZONE_16K].sz_max = g_raid3_n16k;
3187 		sc->sc_zones[G_RAID3_ZONE_16K].sz_requested =
3188 		    sc->sc_zones[G_RAID3_ZONE_16K].sz_failed = 0;
3189 		sc->sc_zones[G_RAID3_ZONE_4K].sz_zone = uma_zcreate("gr3:4k",
3190 		    4096, g_raid3_uma_ctor, g_raid3_uma_dtor, NULL, NULL,
3191 		    UMA_ALIGN_PTR, 0);
3192 		sc->sc_zones[G_RAID3_ZONE_4K].sz_inuse = 0;
3193 		sc->sc_zones[G_RAID3_ZONE_4K].sz_max = g_raid3_n4k;
3194 		sc->sc_zones[G_RAID3_ZONE_4K].sz_requested =
3195 		    sc->sc_zones[G_RAID3_ZONE_4K].sz_failed = 0;
3196 	}
3197 
3198 	error = kproc_create(g_raid3_worker, sc, &sc->sc_worker, 0, 0,
3199 	    "g_raid3 %s", md->md_name);
3200 	if (error != 0) {
3201 		G_RAID3_DEBUG(1, "Cannot create kernel thread for %s.",
3202 		    sc->sc_name);
3203 		if (!g_raid3_use_malloc) {
3204 			uma_zdestroy(sc->sc_zones[G_RAID3_ZONE_64K].sz_zone);
3205 			uma_zdestroy(sc->sc_zones[G_RAID3_ZONE_16K].sz_zone);
3206 			uma_zdestroy(sc->sc_zones[G_RAID3_ZONE_4K].sz_zone);
3207 		}
3208 		g_destroy_geom(sc->sc_sync.ds_geom);
3209 		mtx_destroy(&sc->sc_events_mtx);
3210 		mtx_destroy(&sc->sc_queue_mtx);
3211 		sx_destroy(&sc->sc_lock);
3212 		g_destroy_geom(sc->sc_geom);
3213 		free(sc->sc_disks, M_RAID3);
3214 		free(sc, M_RAID3);
3215 		return (NULL);
3216 	}
3217 
3218 	G_RAID3_DEBUG(1, "Device %s created (%u components, id=%u).",
3219 	    sc->sc_name, sc->sc_ndisks, sc->sc_id);
3220 
3221 	sc->sc_rootmount = root_mount_hold("GRAID3");
3222 	G_RAID3_DEBUG(1, "root_mount_hold %p", sc->sc_rootmount);
3223 
3224 	/*
3225 	 * Run timeout.
3226 	 */
3227 	timeout = atomic_load_acq_int(&g_raid3_timeout);
3228 	callout_reset(&sc->sc_callout, timeout * hz, g_raid3_go, sc);
3229 	return (sc->sc_geom);
3230 }
3231 
3232 int
3233 g_raid3_destroy(struct g_raid3_softc *sc, int how)
3234 {
3235 	struct g_provider *pp;
3236 
3237 	g_topology_assert_not();
3238 	if (sc == NULL)
3239 		return (ENXIO);
3240 	sx_assert(&sc->sc_lock, SX_XLOCKED);
3241 
3242 	pp = sc->sc_provider;
3243 	if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
3244 		switch (how) {
3245 		case G_RAID3_DESTROY_SOFT:
3246 			G_RAID3_DEBUG(1,
3247 			    "Device %s is still open (r%dw%de%d).", pp->name,
3248 			    pp->acr, pp->acw, pp->ace);
3249 			return (EBUSY);
3250 		case G_RAID3_DESTROY_DELAYED:
3251 			G_RAID3_DEBUG(1,
3252 			    "Device %s will be destroyed on last close.",
3253 			    pp->name);
3254 			if (sc->sc_syncdisk != NULL)
3255 				g_raid3_sync_stop(sc, 1);
3256 			sc->sc_flags |= G_RAID3_DEVICE_FLAG_DESTROYING;
3257 			return (EBUSY);
3258 		case G_RAID3_DESTROY_HARD:
3259 			G_RAID3_DEBUG(1, "Device %s is still open, so it "
3260 			    "can't be definitely removed.", pp->name);
3261 			break;
3262 		}
3263 	}
3264 
3265 	g_topology_lock();
3266 	if (sc->sc_geom->softc == NULL) {
3267 		g_topology_unlock();
3268 		return (0);
3269 	}
3270 	sc->sc_geom->softc = NULL;
3271 	sc->sc_sync.ds_geom->softc = NULL;
3272 	g_topology_unlock();
3273 
3274 	sc->sc_flags |= G_RAID3_DEVICE_FLAG_DESTROY;
3275 	sc->sc_flags |= G_RAID3_DEVICE_FLAG_WAIT;
3276 	G_RAID3_DEBUG(4, "%s: Waking up %p.", __func__, sc);
3277 	sx_xunlock(&sc->sc_lock);
3278 	mtx_lock(&sc->sc_queue_mtx);
3279 	wakeup(sc);
3280 	wakeup(&sc->sc_queue);
3281 	mtx_unlock(&sc->sc_queue_mtx);
3282 	G_RAID3_DEBUG(4, "%s: Sleeping %p.", __func__, &sc->sc_worker);
3283 	while (sc->sc_worker != NULL)
3284 		tsleep(&sc->sc_worker, PRIBIO, "r3:destroy", hz / 5);
3285 	G_RAID3_DEBUG(4, "%s: Woken up %p.", __func__, &sc->sc_worker);
3286 	sx_xlock(&sc->sc_lock);
3287 	g_raid3_destroy_device(sc);
3288 	free(sc->sc_disks, M_RAID3);
3289 	free(sc, M_RAID3);
3290 	return (0);
3291 }
3292 
3293 static void
3294 g_raid3_taste_orphan(struct g_consumer *cp)
3295 {
3296 
3297 	KASSERT(1 == 0, ("%s called while tasting %s.", __func__,
3298 	    cp->provider->name));
3299 }
3300 
3301 static struct g_geom *
3302 g_raid3_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
3303 {
3304 	struct g_raid3_metadata md;
3305 	struct g_raid3_softc *sc;
3306 	struct g_consumer *cp;
3307 	struct g_geom *gp;
3308 	int error;
3309 
3310 	g_topology_assert();
3311 	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
3312 	G_RAID3_DEBUG(2, "Tasting %s.", pp->name);
3313 
3314 	gp = g_new_geomf(mp, "raid3:taste");
3315 	/* This orphan function should be never called. */
3316 	gp->orphan = g_raid3_taste_orphan;
3317 	cp = g_new_consumer(gp);
3318 	error = g_attach(cp, pp);
3319 	if (error == 0) {
3320 		error = g_raid3_read_metadata(cp, &md);
3321 		g_detach(cp);
3322 	}
3323 	g_destroy_consumer(cp);
3324 	g_destroy_geom(gp);
3325 	if (error != 0)
3326 		return (NULL);
3327 	gp = NULL;
3328 
3329 	if (md.md_provider[0] != '\0' &&
3330 	    !g_compare_names(md.md_provider, pp->name))
3331 		return (NULL);
3332 	if (md.md_provsize != 0 && md.md_provsize != pp->mediasize)
3333 		return (NULL);
3334 	if (g_raid3_debug >= 2)
3335 		raid3_metadata_dump(&md);
3336 
3337 	/*
3338 	 * Let's check if device already exists.
3339 	 */
3340 	sc = NULL;
3341 	LIST_FOREACH(gp, &mp->geom, geom) {
3342 		sc = gp->softc;
3343 		if (sc == NULL)
3344 			continue;
3345 		if (sc->sc_sync.ds_geom == gp)
3346 			continue;
3347 		if (strcmp(md.md_name, sc->sc_name) != 0)
3348 			continue;
3349 		if (md.md_id != sc->sc_id) {
3350 			G_RAID3_DEBUG(0, "Device %s already configured.",
3351 			    sc->sc_name);
3352 			return (NULL);
3353 		}
3354 		break;
3355 	}
3356 	if (gp == NULL) {
3357 		gp = g_raid3_create(mp, &md);
3358 		if (gp == NULL) {
3359 			G_RAID3_DEBUG(0, "Cannot create device %s.",
3360 			    md.md_name);
3361 			return (NULL);
3362 		}
3363 		sc = gp->softc;
3364 	}
3365 	G_RAID3_DEBUG(1, "Adding disk %s to %s.", pp->name, gp->name);
3366 	g_topology_unlock();
3367 	sx_xlock(&sc->sc_lock);
3368 	error = g_raid3_add_disk(sc, pp, &md);
3369 	if (error != 0) {
3370 		G_RAID3_DEBUG(0, "Cannot add disk %s to %s (error=%d).",
3371 		    pp->name, gp->name, error);
3372 		if (g_raid3_ndisks(sc, G_RAID3_DISK_STATE_NODISK) ==
3373 		    sc->sc_ndisks) {
3374 			g_cancel_event(sc);
3375 			g_raid3_destroy(sc, G_RAID3_DESTROY_HARD);
3376 			g_topology_lock();
3377 			return (NULL);
3378 		}
3379 		gp = NULL;
3380 	}
3381 	sx_xunlock(&sc->sc_lock);
3382 	g_topology_lock();
3383 	return (gp);
3384 }
3385 
3386 static int
3387 g_raid3_destroy_geom(struct gctl_req *req __unused, struct g_class *mp __unused,
3388     struct g_geom *gp)
3389 {
3390 	struct g_raid3_softc *sc;
3391 	int error;
3392 
3393 	g_topology_unlock();
3394 	sc = gp->softc;
3395 	sx_xlock(&sc->sc_lock);
3396 	g_cancel_event(sc);
3397 	error = g_raid3_destroy(gp->softc, G_RAID3_DESTROY_SOFT);
3398 	if (error != 0)
3399 		sx_xunlock(&sc->sc_lock);
3400 	g_topology_lock();
3401 	return (error);
3402 }
3403 
3404 static void
3405 g_raid3_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
3406     struct g_consumer *cp, struct g_provider *pp)
3407 {
3408 	struct g_raid3_softc *sc;
3409 
3410 	g_topology_assert();
3411 
3412 	sc = gp->softc;
3413 	if (sc == NULL)
3414 		return;
3415 	/* Skip synchronization geom. */
3416 	if (gp == sc->sc_sync.ds_geom)
3417 		return;
3418 	if (pp != NULL) {
3419 		/* Nothing here. */
3420 	} else if (cp != NULL) {
3421 		struct g_raid3_disk *disk;
3422 
3423 		disk = cp->private;
3424 		if (disk == NULL)
3425 			return;
3426 		g_topology_unlock();
3427 		sx_xlock(&sc->sc_lock);
3428 		sbuf_printf(sb, "%s<Type>", indent);
3429 		if (disk->d_no == sc->sc_ndisks - 1)
3430 			sbuf_cat(sb, "PARITY");
3431 		else
3432 			sbuf_cat(sb, "DATA");
3433 		sbuf_cat(sb, "</Type>\n");
3434 		sbuf_printf(sb, "%s<Number>%u</Number>\n", indent,
3435 		    (u_int)disk->d_no);
3436 		if (disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING) {
3437 			sbuf_printf(sb, "%s<Synchronized>", indent);
3438 			if (disk->d_sync.ds_offset == 0)
3439 				sbuf_cat(sb, "0%");
3440 			else {
3441 				sbuf_printf(sb, "%u%%",
3442 				    (u_int)((disk->d_sync.ds_offset * 100) /
3443 				    (sc->sc_mediasize / (sc->sc_ndisks - 1))));
3444 			}
3445 			sbuf_cat(sb, "</Synchronized>\n");
3446 			if (disk->d_sync.ds_offset > 0) {
3447 				sbuf_printf(sb, "%s<BytesSynced>%jd"
3448 				    "</BytesSynced>\n", indent,
3449 				    (intmax_t)disk->d_sync.ds_offset);
3450 			}
3451 		}
3452 		sbuf_printf(sb, "%s<SyncID>%u</SyncID>\n", indent,
3453 		    disk->d_sync.ds_syncid);
3454 		sbuf_printf(sb, "%s<GenID>%u</GenID>\n", indent, disk->d_genid);
3455 		sbuf_printf(sb, "%s<Flags>", indent);
3456 		if (disk->d_flags == 0)
3457 			sbuf_cat(sb, "NONE");
3458 		else {
3459 			int first = 1;
3460 
3461 #define	ADD_FLAG(flag, name)	do {					\
3462 	if ((disk->d_flags & (flag)) != 0) {				\
3463 		if (!first)						\
3464 			sbuf_cat(sb, ", ");				\
3465 		else							\
3466 			first = 0;					\
3467 		sbuf_cat(sb, name);					\
3468 	}								\
3469 } while (0)
3470 			ADD_FLAG(G_RAID3_DISK_FLAG_DIRTY, "DIRTY");
3471 			ADD_FLAG(G_RAID3_DISK_FLAG_HARDCODED, "HARDCODED");
3472 			ADD_FLAG(G_RAID3_DISK_FLAG_SYNCHRONIZING,
3473 			    "SYNCHRONIZING");
3474 			ADD_FLAG(G_RAID3_DISK_FLAG_FORCE_SYNC, "FORCE_SYNC");
3475 			ADD_FLAG(G_RAID3_DISK_FLAG_BROKEN, "BROKEN");
3476 #undef	ADD_FLAG
3477 		}
3478 		sbuf_cat(sb, "</Flags>\n");
3479 		sbuf_printf(sb, "%s<State>%s</State>\n", indent,
3480 		    g_raid3_disk_state2str(disk->d_state));
3481 		sx_xunlock(&sc->sc_lock);
3482 		g_topology_lock();
3483 	} else {
3484 		g_topology_unlock();
3485 		sx_xlock(&sc->sc_lock);
3486 		if (!g_raid3_use_malloc) {
3487 			sbuf_printf(sb,
3488 			    "%s<Zone4kRequested>%u</Zone4kRequested>\n", indent,
3489 			    sc->sc_zones[G_RAID3_ZONE_4K].sz_requested);
3490 			sbuf_printf(sb,
3491 			    "%s<Zone4kFailed>%u</Zone4kFailed>\n", indent,
3492 			    sc->sc_zones[G_RAID3_ZONE_4K].sz_failed);
3493 			sbuf_printf(sb,
3494 			    "%s<Zone16kRequested>%u</Zone16kRequested>\n", indent,
3495 			    sc->sc_zones[G_RAID3_ZONE_16K].sz_requested);
3496 			sbuf_printf(sb,
3497 			    "%s<Zone16kFailed>%u</Zone16kFailed>\n", indent,
3498 			    sc->sc_zones[G_RAID3_ZONE_16K].sz_failed);
3499 			sbuf_printf(sb,
3500 			    "%s<Zone64kRequested>%u</Zone64kRequested>\n", indent,
3501 			    sc->sc_zones[G_RAID3_ZONE_64K].sz_requested);
3502 			sbuf_printf(sb,
3503 			    "%s<Zone64kFailed>%u</Zone64kFailed>\n", indent,
3504 			    sc->sc_zones[G_RAID3_ZONE_64K].sz_failed);
3505 		}
3506 		sbuf_printf(sb, "%s<ID>%u</ID>\n", indent, (u_int)sc->sc_id);
3507 		sbuf_printf(sb, "%s<SyncID>%u</SyncID>\n", indent, sc->sc_syncid);
3508 		sbuf_printf(sb, "%s<GenID>%u</GenID>\n", indent, sc->sc_genid);
3509 		sbuf_printf(sb, "%s<Flags>", indent);
3510 		if (sc->sc_flags == 0)
3511 			sbuf_cat(sb, "NONE");
3512 		else {
3513 			int first = 1;
3514 
3515 #define	ADD_FLAG(flag, name)	do {					\
3516 	if ((sc->sc_flags & (flag)) != 0) {				\
3517 		if (!first)						\
3518 			sbuf_cat(sb, ", ");				\
3519 		else							\
3520 			first = 0;					\
3521 		sbuf_cat(sb, name);					\
3522 	}								\
3523 } while (0)
3524 			ADD_FLAG(G_RAID3_DEVICE_FLAG_NOFAILSYNC, "NOFAILSYNC");
3525 			ADD_FLAG(G_RAID3_DEVICE_FLAG_NOAUTOSYNC, "NOAUTOSYNC");
3526 			ADD_FLAG(G_RAID3_DEVICE_FLAG_ROUND_ROBIN,
3527 			    "ROUND-ROBIN");
3528 			ADD_FLAG(G_RAID3_DEVICE_FLAG_VERIFY, "VERIFY");
3529 #undef	ADD_FLAG
3530 		}
3531 		sbuf_cat(sb, "</Flags>\n");
3532 		sbuf_printf(sb, "%s<Components>%u</Components>\n", indent,
3533 		    sc->sc_ndisks);
3534 		sbuf_printf(sb, "%s<State>%s</State>\n", indent,
3535 		    g_raid3_device_state2str(sc->sc_state));
3536 		sx_xunlock(&sc->sc_lock);
3537 		g_topology_lock();
3538 	}
3539 }
3540 
3541 static void
3542 g_raid3_shutdown_post_sync(void *arg, int howto)
3543 {
3544 	struct g_class *mp;
3545 	struct g_geom *gp, *gp2;
3546 	struct g_raid3_softc *sc;
3547 	int error;
3548 
3549 	mp = arg;
3550 	g_topology_lock();
3551 	g_raid3_shutdown = 1;
3552 	LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
3553 		if ((sc = gp->softc) == NULL)
3554 			continue;
3555 		/* Skip synchronization geom. */
3556 		if (gp == sc->sc_sync.ds_geom)
3557 			continue;
3558 		g_topology_unlock();
3559 		sx_xlock(&sc->sc_lock);
3560 		g_raid3_idle(sc, -1);
3561 		g_cancel_event(sc);
3562 		error = g_raid3_destroy(sc, G_RAID3_DESTROY_DELAYED);
3563 		if (error != 0)
3564 			sx_xunlock(&sc->sc_lock);
3565 		g_topology_lock();
3566 	}
3567 	g_topology_unlock();
3568 }
3569 
3570 static void
3571 g_raid3_init(struct g_class *mp)
3572 {
3573 
3574 	g_raid3_post_sync = EVENTHANDLER_REGISTER(shutdown_post_sync,
3575 	    g_raid3_shutdown_post_sync, mp, SHUTDOWN_PRI_FIRST);
3576 	if (g_raid3_post_sync == NULL)
3577 		G_RAID3_DEBUG(0, "Warning! Cannot register shutdown event.");
3578 }
3579 
3580 static void
3581 g_raid3_fini(struct g_class *mp)
3582 {
3583 
3584 	if (g_raid3_post_sync != NULL)
3585 		EVENTHANDLER_DEREGISTER(shutdown_post_sync, g_raid3_post_sync);
3586 }
3587 
3588 DECLARE_GEOM_CLASS(g_raid3_class, g_raid3);
3589 MODULE_VERSION(geom_raid3, 0);
3590