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