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