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