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