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