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