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