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