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