g_mirror.c revision 133114
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 133114 2004-08-04 10:02:06Z 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
401static void
402g_mirror_destroy_disk(struct g_mirror_disk *disk)
403{
404	struct g_mirror_softc *sc;
405
406	g_topology_assert();
407
408	LIST_REMOVE(disk, d_next);
409	g_mirror_event_cancel(disk);
410	sc = disk->d_softc;
411	if (sc->sc_hint == disk)
412		sc->sc_hint = NULL;
413	switch (disk->d_state) {
414	case G_MIRROR_DISK_STATE_SYNCHRONIZING:
415		g_mirror_sync_stop(disk, 1);
416		/* FALLTHROUGH */
417	case G_MIRROR_DISK_STATE_NEW:
418	case G_MIRROR_DISK_STATE_STALE:
419	case G_MIRROR_DISK_STATE_ACTIVE:
420		g_mirror_disconnect_disk(disk);
421		free(disk, M_MIRROR);
422		break;
423	default:
424		KASSERT(0 == 1, ("Wrong disk state (%s, %s).",
425		    g_mirror_get_diskname(disk),
426		    g_mirror_disk_state2str(disk->d_state)));
427	}
428}
429
430static void
431g_mirror_destroy_device(struct g_mirror_softc *sc)
432{
433	struct g_mirror_disk *disk;
434	struct g_mirror_event *ep;
435	struct g_geom *gp;
436	struct g_consumer *cp;
437
438	g_topology_assert();
439
440	gp = sc->sc_geom;
441	if (sc->sc_provider != NULL)
442		g_mirror_destroy_provider(sc);
443	for (disk = LIST_FIRST(&sc->sc_disks); disk != NULL;
444	    disk = LIST_FIRST(&sc->sc_disks)) {
445		g_mirror_destroy_disk(disk);
446	}
447	while ((ep = g_mirror_event_get(sc)) != NULL) {
448		if ((ep->e_flags & G_MIRROR_EVENT_DONTWAIT) != 0)
449			g_mirror_event_free(ep);
450		else {
451			ep->e_error = ECANCELED;
452			ep->e_flags |= G_MIRROR_EVENT_DONE;
453			G_MIRROR_DEBUG(4, "%s: Waking up %p.", __func__, ep);
454			mtx_lock(&sc->sc_events_mtx);
455			wakeup(ep);
456			mtx_unlock(&sc->sc_events_mtx);
457		}
458	}
459	callout_drain(&sc->sc_callout);
460	gp->softc = NULL;
461	uma_zdestroy(sc->sc_sync.ds_zone);
462	while ((cp = LIST_FIRST(&sc->sc_sync.ds_geom->consumer)) != NULL) {
463		if (cp->provider != NULL) {
464			if (cp->acr > 0 || cp->acw > 0 || cp->ace > 0)
465				g_access(cp, -cp->acr, -cp->acw, -cp->ace);
466			g_detach(cp);
467		}
468		g_destroy_consumer(cp);
469	}
470	sc->sc_sync.ds_geom->softc = NULL;
471	g_destroy_geom(sc->sc_sync.ds_geom);
472	mtx_destroy(&sc->sc_queue_mtx);
473	mtx_destroy(&sc->sc_events_mtx);
474	G_MIRROR_DEBUG(0, "Device %s destroyed.", gp->name);
475	g_wither_geom(gp, ENXIO);
476}
477
478static void
479g_mirror_orphan(struct g_consumer *cp)
480{
481	struct g_mirror_disk *disk;
482
483	g_topology_assert();
484
485	disk = cp->private;
486	if (disk == NULL)
487		return;
488	disk->d_softc->sc_bump_syncid = G_MIRROR_BUMP_ON_FIRST_WRITE;
489	g_mirror_event_send(disk, G_MIRROR_DISK_STATE_DISCONNECTED,
490	    G_MIRROR_EVENT_DONTWAIT);
491}
492
493static void
494g_mirror_spoiled(struct g_consumer *cp)
495{
496	struct g_mirror_disk *disk;
497
498	g_topology_assert();
499
500	disk = cp->private;
501	if (disk == NULL)
502		return;
503	disk->d_softc->sc_bump_syncid = G_MIRROR_BUMP_IMMEDIATELY;
504	g_mirror_event_send(disk, G_MIRROR_DISK_STATE_DISCONNECTED,
505	    G_MIRROR_EVENT_DONTWAIT);
506}
507
508/*
509 * Function should return the next active disk on the list.
510 * It is possible that it will be the same disk as given.
511 * If there are no active disks on list, NULL is returned.
512 */
513static __inline struct g_mirror_disk *
514g_mirror_find_next(struct g_mirror_softc *sc, struct g_mirror_disk *disk)
515{
516	struct g_mirror_disk *dp;
517
518	for (dp = LIST_NEXT(disk, d_next); dp != disk;
519	    dp = LIST_NEXT(dp, d_next)) {
520		if (dp == NULL)
521			dp = LIST_FIRST(&sc->sc_disks);
522		if (dp->d_state == G_MIRROR_DISK_STATE_ACTIVE)
523			break;
524	}
525	if (dp->d_state != G_MIRROR_DISK_STATE_ACTIVE)
526		return (NULL);
527	return (dp);
528}
529
530static struct g_mirror_disk *
531g_mirror_get_disk(struct g_mirror_softc *sc)
532{
533	struct g_mirror_disk *disk;
534
535	if (sc->sc_hint == NULL) {
536		sc->sc_hint = LIST_FIRST(&sc->sc_disks);
537		if (sc->sc_hint == NULL)
538			return (NULL);
539	}
540	disk = sc->sc_hint;
541	if (disk->d_state != G_MIRROR_DISK_STATE_ACTIVE) {
542		disk = g_mirror_find_next(sc, disk);
543		if (disk == NULL)
544			return (NULL);
545	}
546	sc->sc_hint = g_mirror_find_next(sc, disk);
547	return (disk);
548}
549
550static int
551g_mirror_clear_metadata(struct g_mirror_disk *disk)
552{
553	struct g_mirror_softc *sc;
554	struct g_consumer *cp;
555	off_t offset, length;
556	u_char *sector;
557	int close = 0, error = 0;
558
559	g_topology_assert();
560
561	sc = disk->d_softc;
562	cp = disk->d_consumer;
563	KASSERT(cp != NULL, ("NULL consumer (%s).", sc->sc_name));
564	KASSERT(cp->provider != NULL, ("NULL provider (%s).", sc->sc_name));
565	length = cp->provider->sectorsize;
566	offset = cp->provider->mediasize - length;
567	sector = malloc((size_t)length, M_MIRROR, M_WAITOK | M_ZERO);
568	/*
569	 * Open consumer if it wasn't opened and remember to close it.
570	 */
571	if ((disk->d_flags & G_MIRROR_DISK_FLAG_DIRTY) == 0) {
572		error = g_access(cp, 0, 1, 1);
573		G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d",
574		    cp->provider->name, 0, 1, 1, error);
575		if (error == 0)
576			close = 1;
577#ifdef	INVARIANTS
578	} else {
579		KASSERT(cp->acw > 0 && cp->ace > 0,
580		    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name,
581		    cp->acr, cp->acw, cp->ace));
582#endif
583	}
584	if (error == 0) {
585		g_topology_unlock();
586		error = g_write_data(cp, offset, sector, length);
587		g_topology_lock();
588	}
589	free(sector, M_MIRROR);
590	if (close) {
591		g_access(cp, 0, -1, -1);
592		G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d",
593		    cp->provider->name, 0, -1, -1, 0);
594	}
595	if (error != 0) {
596		G_MIRROR_DEBUG(0, "Cannot clear metadata on disk %s.",
597		    g_mirror_get_diskname(disk));
598		disk->d_softc->sc_bump_syncid = G_MIRROR_BUMP_IMMEDIATELY;
599		g_mirror_event_send(disk, G_MIRROR_DISK_STATE_DISCONNECTED,
600		    G_MIRROR_EVENT_DONTWAIT);
601		return (error);
602	}
603	G_MIRROR_DEBUG(2, "Metadata on %s cleared.",
604	    g_mirror_get_diskname(disk));
605	return (0);
606}
607
608void
609g_mirror_fill_metadata(struct g_mirror_softc *sc, struct g_mirror_disk *disk,
610    struct g_mirror_metadata *md)
611{
612
613	strlcpy(md->md_magic, G_MIRROR_MAGIC, sizeof(md->md_magic));
614	md->md_version = G_MIRROR_VERSION;
615	strlcpy(md->md_name, sc->sc_name, sizeof(md->md_name));
616	md->md_mid = sc->sc_id;
617	md->md_all = sc->sc_ndisks;
618	md->md_slice = sc->sc_slice;
619	md->md_balance = sc->sc_balance;
620	md->md_mediasize = sc->sc_mediasize;
621	md->md_sectorsize = sc->sc_sectorsize;
622	md->md_mflags = (sc->sc_flags & G_MIRROR_DEVICE_FLAG_MASK);
623	if (disk == NULL) {
624		md->md_did = arc4random();
625		md->md_priority = 0;
626		md->md_syncid = 0;
627		md->md_dflags = 0;
628		md->md_sync_offset = 0;
629	} else {
630		md->md_did = disk->d_id;
631		md->md_priority = disk->d_priority;
632		md->md_syncid = disk->d_sync.ds_syncid;
633		md->md_dflags = (disk->d_flags & G_MIRROR_DISK_FLAG_MASK);
634		if (disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING)
635			md->md_sync_offset = disk->d_sync.ds_offset_done;
636		else
637			md->md_sync_offset = 0;
638	}
639}
640
641void
642g_mirror_update_metadata(struct g_mirror_disk *disk)
643{
644	struct g_mirror_softc *sc;
645	struct g_mirror_metadata md;
646	struct g_consumer *cp;
647	off_t offset, length;
648	u_char *sector;
649	int close = 0, error = 0;
650
651	g_topology_assert();
652
653	sc = disk->d_softc;
654	cp = disk->d_consumer;
655	KASSERT(cp != NULL, ("NULL consumer (%s).", sc->sc_name));
656	KASSERT(cp->provider != NULL, ("NULL provider (%s).", sc->sc_name));
657	length = cp->provider->sectorsize;
658	offset = cp->provider->mediasize - length;
659	sector = malloc((size_t)length, M_MIRROR, M_WAITOK);
660	/*
661	 * Open consumer if it wasn't opened and remember to close it.
662	 */
663	if ((disk->d_flags & G_MIRROR_DISK_FLAG_DIRTY) == 0) {
664		error = g_access(cp, 0, 1, 1);
665		G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d",
666		    cp->provider->name, 0, 1, 1, error);
667		if (error == 0)
668			close = 1;
669#ifdef	INVARIANTS
670	} else {
671		KASSERT(cp->acw > 0 && cp->ace > 0,
672		    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name,
673		    cp->acr, cp->acw, cp->ace));
674#endif
675	}
676	if (error == 0) {
677		g_mirror_fill_metadata(sc, disk, &md);
678		mirror_metadata_encode(&md, sector);
679		g_topology_unlock();
680		error = g_write_data(cp, offset, sector, length);
681		g_topology_lock();
682	}
683	free(sector, M_MIRROR);
684	if (close) {
685		g_access(cp, 0, -1, -1);
686		G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d",
687		    cp->provider->name, 0, -1, -1, 0);
688	}
689	if (error != 0) {
690		G_MIRROR_DEBUG(0,
691		    "Cannot update metadata on disk %s (error=%d).",
692		    g_mirror_get_diskname(disk), error);
693		disk->d_softc->sc_bump_syncid = G_MIRROR_BUMP_IMMEDIATELY;
694		g_mirror_event_send(disk, G_MIRROR_DISK_STATE_DISCONNECTED,
695		    G_MIRROR_EVENT_DONTWAIT);
696		return;
697	}
698	G_MIRROR_DEBUG(2, "Metadata on %s updated.",
699	    g_mirror_get_diskname(disk));
700}
701
702static void
703g_mirror_bump_syncid(struct g_mirror_softc *sc)
704{
705	struct g_mirror_disk *disk;
706
707	g_topology_assert();
708	KASSERT(g_mirror_ndisks(sc, G_MIRROR_DISK_STATE_ACTIVE) > 0,
709	    ("%s called with no active disks (device=%s).", __func__,
710	    sc->sc_name));
711
712	sc->sc_syncid++;
713	G_MIRROR_DEBUG(1, "Device %s: syncid bumped to %u.", sc->sc_name,
714	    sc->sc_syncid);
715	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
716		if (disk->d_state == G_MIRROR_DISK_STATE_ACTIVE ||
717		    disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING) {
718			disk->d_sync.ds_syncid = sc->sc_syncid;
719			g_mirror_update_metadata(disk);
720		}
721	}
722}
723
724static __inline int
725bintime_cmp(struct bintime *bt1, struct bintime *bt2)
726{
727
728	if (bt1->sec < bt2->sec)
729		return (-1);
730	else if (bt1->sec > bt2->sec)
731		return (1);
732	if (bt1->frac < bt2->frac)
733		return (-1);
734	else if (bt1->frac > bt2->frac)
735		return (1);
736	return (0);
737}
738
739static void
740g_mirror_update_delay(struct g_mirror_disk *disk, struct bio *bp)
741{
742
743	if (disk->d_softc->sc_balance != G_MIRROR_BALANCE_LOAD)
744		return;
745	binuptime(&disk->d_delay);
746	bintime_sub(&disk->d_delay, &bp->bio_t0);
747}
748
749static void
750g_mirror_done(struct bio *bp)
751{
752	struct g_mirror_softc *sc;
753
754	sc = bp->bio_from->geom->softc;
755	bp->bio_flags = BIO_FLAG1;
756	mtx_lock(&sc->sc_queue_mtx);
757	bioq_disksort(&sc->sc_queue, bp);
758	wakeup(sc);
759	mtx_unlock(&sc->sc_queue_mtx);
760}
761
762static void
763g_mirror_regular_request(struct bio *bp)
764{
765	struct g_mirror_softc *sc;
766	struct g_mirror_disk *disk;
767	struct bio *pbp;
768
769	g_topology_assert_not();
770
771	pbp = bp->bio_parent;
772	sc = pbp->bio_to->geom->softc;
773	disk = bp->bio_from->private;
774	if (disk == NULL) {
775		g_topology_lock();
776		g_mirror_kill_consumer(sc, bp->bio_from);
777		g_topology_unlock();
778	} else {
779		g_mirror_update_delay(disk, bp);
780	}
781
782	pbp->bio_inbed++;
783	KASSERT(pbp->bio_inbed <= pbp->bio_children,
784	    ("bio_inbed (%u) is bigger than bio_children (%u).", pbp->bio_inbed,
785	    pbp->bio_children));
786	if (bp->bio_error == 0 && pbp->bio_error == 0) {
787		G_MIRROR_LOGREQ(3, bp, "Request delivered.");
788		g_destroy_bio(bp);
789		if (pbp->bio_children == pbp->bio_inbed) {
790			G_MIRROR_LOGREQ(3, pbp, "Request delivered.");
791			pbp->bio_completed = pbp->bio_length;
792			g_io_deliver(pbp, pbp->bio_error);
793		}
794		return;
795	} else if (bp->bio_error != 0) {
796		if (pbp->bio_error == 0)
797			pbp->bio_error = bp->bio_error;
798		G_MIRROR_LOGREQ(0, bp, "Request failed (error=%d).",
799		    bp->bio_error);
800		if (disk != NULL) {
801			sc->sc_bump_syncid = G_MIRROR_BUMP_IMMEDIATELY;
802			g_mirror_event_send(disk,
803			    G_MIRROR_DISK_STATE_DISCONNECTED,
804			    G_MIRROR_EVENT_DONTWAIT);
805		}
806		switch (pbp->bio_cmd) {
807		case BIO_DELETE:
808		case BIO_WRITE:
809			pbp->bio_inbed--;
810			pbp->bio_children--;
811			break;
812		}
813	}
814	g_destroy_bio(bp);
815
816	switch (pbp->bio_cmd) {
817	case BIO_READ:
818		if (pbp->bio_children == pbp->bio_inbed) {
819			pbp->bio_error = 0;
820			mtx_lock(&sc->sc_queue_mtx);
821			bioq_disksort(&sc->sc_queue, pbp);
822			G_MIRROR_DEBUG(4, "%s: Waking up %p.", __func__, sc);
823			wakeup(sc);
824			mtx_unlock(&sc->sc_queue_mtx);
825		}
826		break;
827	case BIO_DELETE:
828	case BIO_WRITE:
829		if (pbp->bio_children == 0) {
830			/*
831			 * All requests failed.
832			 */
833		} else if (pbp->bio_inbed < pbp->bio_children) {
834			/* Do nothing. */
835			break;
836		} else if (pbp->bio_children == pbp->bio_inbed) {
837			/* Some requests succeeded. */
838			pbp->bio_error = 0;
839			pbp->bio_completed = pbp->bio_length;
840		}
841		g_io_deliver(pbp, pbp->bio_error);
842		break;
843	default:
844		KASSERT(1 == 0, ("Invalid request: %u.", pbp->bio_cmd));
845		break;
846	}
847}
848
849static void
850g_mirror_sync_done(struct bio *bp)
851{
852	struct g_mirror_softc *sc;
853
854	G_MIRROR_LOGREQ(3, bp, "Synchronization request delivered.");
855	sc = bp->bio_from->geom->softc;
856	bp->bio_flags = BIO_FLAG2;
857	mtx_lock(&sc->sc_queue_mtx);
858	bioq_disksort(&sc->sc_queue, bp);
859	wakeup(sc);
860	mtx_unlock(&sc->sc_queue_mtx);
861}
862
863static void
864g_mirror_start(struct bio *bp)
865{
866	struct g_mirror_softc *sc;
867
868	sc = bp->bio_to->geom->softc;
869	/*
870	 * If sc == NULL or there are no valid disks, provider's error
871	 * should be set and g_mirror_start() should not be called at all.
872	 */
873	KASSERT(sc != NULL && sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
874	    ("Provider's error should be set (error=%d)(mirror=%s).",
875	    bp->bio_to->error, bp->bio_to->name));
876	G_MIRROR_LOGREQ(3, bp, "Request received.");
877
878	switch (bp->bio_cmd) {
879	case BIO_READ:
880	case BIO_WRITE:
881	case BIO_DELETE:
882		break;
883	case BIO_GETATTR:
884	default:
885		g_io_deliver(bp, EOPNOTSUPP);
886		return;
887	}
888	mtx_lock(&sc->sc_queue_mtx);
889	bioq_disksort(&sc->sc_queue, bp);
890	G_MIRROR_DEBUG(4, "%s: Waking up %p.", __func__, sc);
891	wakeup(sc);
892	mtx_unlock(&sc->sc_queue_mtx);
893}
894
895/*
896 * Send one synchronization request.
897 */
898static void
899g_mirror_sync_one(struct g_mirror_disk *disk)
900{
901	struct g_mirror_softc *sc;
902	struct bio *bp;
903
904	sc = disk->d_softc;
905	KASSERT(disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING,
906	    ("Disk %s is not marked for synchronization.",
907	    g_mirror_get_diskname(disk)));
908
909	bp = g_new_bio();
910	if (bp == NULL)
911		return;
912	bp->bio_parent = NULL;
913	bp->bio_cmd = BIO_READ;
914	bp->bio_offset = disk->d_sync.ds_offset;
915	bp->bio_length = MIN(sc->sc_sync.ds_block,
916	    sc->sc_mediasize - bp->bio_offset);
917	bp->bio_flags = 0;
918	bp->bio_done = g_mirror_sync_done;
919	bp->bio_data = uma_zalloc(sc->sc_sync.ds_zone, M_NOWAIT | M_ZERO);
920	if (bp->bio_data == NULL) {
921		g_destroy_bio(bp);
922		return;
923	}
924	disk->d_sync.ds_offset += bp->bio_length;
925	bp->bio_to = sc->sc_provider;
926	G_MIRROR_LOGREQ(3, bp, "Sending synchronization request.");
927	g_io_request(bp, disk->d_sync.ds_consumer);
928}
929
930static void
931g_mirror_sync_request(struct bio *bp)
932{
933	struct g_mirror_softc *sc;
934	struct g_mirror_disk *disk;
935
936	sc = bp->bio_from->geom->softc;
937	disk = bp->bio_from->private;
938	if (disk == NULL) {
939		g_topology_lock();
940		g_mirror_kill_consumer(sc, bp->bio_from);
941		g_topology_unlock();
942		uma_zfree(sc->sc_sync.ds_zone, bp->bio_data);
943		g_destroy_bio(bp);
944		return;
945	}
946
947	/*
948	 * Synchronization request.
949	 */
950	switch (bp->bio_cmd) {
951	case BIO_READ:
952	    {
953		struct g_consumer *cp;
954
955		if (bp->bio_error != 0) {
956			G_MIRROR_LOGREQ(0, bp,
957			    "Synchronization request failed (error=%d).",
958			    bp->bio_error);
959			uma_zfree(sc->sc_sync.ds_zone, bp->bio_data);
960			g_destroy_bio(bp);
961			return;
962		}
963		bp->bio_cmd = BIO_WRITE;
964		bp->bio_flags = 0;
965		G_MIRROR_LOGREQ(3, bp, "Synchronization request finished.");
966		cp = disk->d_consumer;
967		KASSERT(cp->acr == 0 && cp->acw == 1 && cp->ace == 1,
968		    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name,
969		    cp->acr, cp->acw, cp->ace));
970		g_io_request(bp, cp);
971		return;
972	    }
973	case BIO_WRITE:
974		uma_zfree(sc->sc_sync.ds_zone, bp->bio_data);
975		if (bp->bio_error != 0) {
976			G_MIRROR_LOGREQ(0, bp,
977			    "Synchronization request failed (error=%d).",
978			    bp->bio_error);
979			g_destroy_bio(bp);
980			disk->d_softc->sc_bump_syncid = G_MIRROR_BUMP_IMMEDIATELY;
981			g_mirror_event_send(disk,
982			    G_MIRROR_DISK_STATE_DISCONNECTED,
983			    G_MIRROR_EVENT_DONTWAIT);
984			return;
985		}
986		G_MIRROR_LOGREQ(3, bp, "Synchronization request finished.");
987		g_destroy_bio(bp);
988		disk->d_sync.ds_offset_done = bp->bio_offset + bp->bio_length;
989		if (bp->bio_offset + bp->bio_length ==
990		    sc->sc_provider->mediasize) {
991			/*
992			 * Disk up-to-date, activate it.
993			 */
994			g_mirror_event_send(disk, G_MIRROR_DISK_STATE_ACTIVE,
995			    G_MIRROR_EVENT_DONTWAIT);
996			return;
997		} else if ((disk->d_sync.ds_offset_done %
998		    (sc->sc_sync.ds_block * 100)) == 0) {
999			/*
1000			 * Update offset_done on every 100 blocks.
1001			 * XXX: This should be configurable.
1002			 */
1003			g_topology_lock();
1004			g_mirror_update_metadata(disk);
1005			g_topology_unlock();
1006		}
1007		return;
1008	default:
1009		KASSERT(1 == 0, ("Invalid command here: %u (device=%s)",
1010		    bp->bio_cmd, sc->sc_name));
1011		break;
1012	}
1013}
1014
1015static void
1016g_mirror_request_round_robin(struct g_mirror_softc *sc, struct bio *bp)
1017{
1018	struct g_mirror_disk *disk;
1019	struct g_consumer *cp;
1020	struct bio *cbp;
1021
1022	disk = g_mirror_get_disk(sc);
1023	if (disk == NULL) {
1024		if (bp->bio_error == 0)
1025			bp->bio_error = ENXIO;
1026		g_io_deliver(bp, bp->bio_error);
1027		return;
1028	}
1029	cbp = g_clone_bio(bp);
1030	if (cbp == NULL) {
1031		if (bp->bio_error == 0)
1032			bp->bio_error = ENOMEM;
1033		g_io_deliver(bp, bp->bio_error);
1034		return;
1035	}
1036	/*
1037	 * Fill in the component buf structure.
1038	 */
1039	cp = disk->d_consumer;
1040	cbp->bio_done = g_mirror_done;
1041	cbp->bio_to = cp->provider;
1042	G_MIRROR_LOGREQ(3, cbp, "Sending request.");
1043	KASSERT(cp->acr > 0 && cp->ace > 0,
1044	    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name, cp->acr,
1045	    cp->acw, cp->ace));
1046	g_io_request(cbp, cp);
1047}
1048
1049static void
1050g_mirror_request_load(struct g_mirror_softc *sc, struct bio *bp)
1051{
1052	struct g_mirror_disk *disk, *dp;
1053	struct g_consumer *cp;
1054	struct bio *cbp;
1055	struct bintime curtime;
1056
1057	binuptime(&curtime);
1058	/*
1059	 * Find a disk which the smallest load.
1060	 */
1061	disk = NULL;
1062	LIST_FOREACH(dp, &sc->sc_disks, d_next) {
1063		if (dp->d_state != G_MIRROR_DISK_STATE_ACTIVE)
1064			continue;
1065		/* If disk wasn't used for more than 2 sec, use it. */
1066		if (curtime.sec - dp->d_last_used.sec >= 2) {
1067			disk = dp;
1068			break;
1069		}
1070		if (disk == NULL ||
1071		    bintime_cmp(&dp->d_delay, &disk->d_delay) < 0) {
1072			disk = dp;
1073		}
1074	}
1075	cbp = g_clone_bio(bp);
1076	if (cbp == NULL) {
1077		if (bp->bio_error == 0)
1078			bp->bio_error = ENOMEM;
1079		g_io_deliver(bp, bp->bio_error);
1080		return;
1081	}
1082	/*
1083	 * Fill in the component buf structure.
1084	 */
1085	cp = disk->d_consumer;
1086	cbp->bio_done = g_mirror_done;
1087	cbp->bio_to = cp->provider;
1088	binuptime(&disk->d_last_used);
1089	G_MIRROR_LOGREQ(3, cbp, "Sending request.");
1090	KASSERT(cp->acr > 0 && cp->ace > 0,
1091	    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name, cp->acr,
1092	    cp->acw, cp->ace));
1093	g_io_request(cbp, cp);
1094}
1095
1096static void
1097g_mirror_request_split(struct g_mirror_softc *sc, struct bio *bp)
1098{
1099	struct bio_queue_head queue;
1100	struct g_mirror_disk *disk;
1101	struct g_consumer *cp;
1102	struct bio *cbp;
1103	off_t left, mod, offset, slice;
1104	u_char *data;
1105	u_int ndisks;
1106
1107	if (bp->bio_length <= sc->sc_slice) {
1108		g_mirror_request_round_robin(sc, bp);
1109		return;
1110	}
1111	ndisks = g_mirror_ndisks(sc, G_MIRROR_DISK_STATE_ACTIVE);
1112	slice = bp->bio_length / ndisks;
1113	mod = slice % sc->sc_provider->sectorsize;
1114	if (mod != 0)
1115		slice += sc->sc_provider->sectorsize - mod;
1116	/*
1117	 * Allocate all bios before sending any request, so we can
1118	 * return ENOMEM in nice and clean way.
1119	 */
1120	left = bp->bio_length;
1121	offset = bp->bio_offset;
1122	data = bp->bio_data;
1123	bioq_init(&queue);
1124	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1125		if (disk->d_state != G_MIRROR_DISK_STATE_ACTIVE)
1126			continue;
1127		cbp = g_clone_bio(bp);
1128		if (cbp == NULL) {
1129			for (cbp = bioq_first(&queue); cbp != NULL;
1130			    cbp = bioq_first(&queue)) {
1131				bioq_remove(&queue, cbp);
1132				g_destroy_bio(cbp);
1133			}
1134			if (bp->bio_error == 0)
1135				bp->bio_error = ENOMEM;
1136			g_io_deliver(bp, bp->bio_error);
1137			return;
1138		}
1139		bioq_insert_tail(&queue, cbp);
1140		cbp->bio_done = g_mirror_done;
1141		cbp->bio_caller1 = disk;
1142		cbp->bio_to = disk->d_consumer->provider;
1143		cbp->bio_offset = offset;
1144		cbp->bio_data = data;
1145		cbp->bio_length = MIN(left, slice);
1146		left -= cbp->bio_length;
1147		if (left == 0)
1148			break;
1149		offset += cbp->bio_length;
1150		data += cbp->bio_length;
1151	}
1152	for (cbp = bioq_first(&queue); cbp != NULL; cbp = bioq_first(&queue)) {
1153		bioq_remove(&queue, cbp);
1154		G_MIRROR_LOGREQ(3, cbp, "Sending request.");
1155		disk = cbp->bio_caller1;
1156		cbp->bio_caller1 = NULL;
1157		cp = disk->d_consumer;
1158		KASSERT(cp->acr > 0 && cp->ace > 0,
1159		    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name,
1160		    cp->acr, cp->acw, cp->ace));
1161		g_io_request(cbp, disk->d_consumer);
1162	}
1163}
1164
1165static void
1166g_mirror_register_request(struct bio *bp)
1167{
1168	struct g_mirror_softc *sc;
1169
1170	sc = bp->bio_to->geom->softc;
1171	switch (bp->bio_cmd) {
1172	case BIO_READ:
1173		switch (sc->sc_balance) {
1174		case G_MIRROR_BALANCE_ROUND_ROBIN:
1175			g_mirror_request_round_robin(sc, bp);
1176			break;
1177		case G_MIRROR_BALANCE_LOAD:
1178			g_mirror_request_load(sc, bp);
1179			break;
1180		case G_MIRROR_BALANCE_SPLIT:
1181			g_mirror_request_split(sc, bp);
1182			break;
1183		}
1184		return;
1185	case BIO_WRITE:
1186	case BIO_DELETE:
1187	    {
1188		struct g_mirror_disk *disk;
1189		struct bio_queue_head queue;
1190		struct g_consumer *cp;
1191		struct bio *cbp;
1192
1193		/*
1194		 * Allocate all bios before sending any request, so we can
1195		 * return ENOMEM in nice and clean way.
1196		 */
1197		bioq_init(&queue);
1198		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1199			switch (disk->d_state) {
1200			case G_MIRROR_DISK_STATE_ACTIVE:
1201				break;
1202			case G_MIRROR_DISK_STATE_SYNCHRONIZING:
1203				if (bp->bio_offset >= disk->d_sync.ds_offset)
1204					continue;
1205				break;
1206			default:
1207				continue;
1208			}
1209			cbp = g_clone_bio(bp);
1210			if (cbp == NULL) {
1211				for (cbp = bioq_first(&queue); cbp != NULL;
1212				    cbp = bioq_first(&queue)) {
1213					bioq_remove(&queue, cbp);
1214					g_destroy_bio(cbp);
1215				}
1216				if (bp->bio_error == 0)
1217					bp->bio_error = ENOMEM;
1218				g_io_deliver(bp, bp->bio_error);
1219				return;
1220			}
1221			bioq_insert_tail(&queue, cbp);
1222		}
1223		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1224			switch (disk->d_state) {
1225			case G_MIRROR_DISK_STATE_ACTIVE:
1226				break;
1227			case G_MIRROR_DISK_STATE_SYNCHRONIZING:
1228				if (bp->bio_offset >= disk->d_sync.ds_offset)
1229					continue;
1230				break;
1231			default:
1232				continue;
1233			}
1234			cbp = bioq_first(&queue);
1235			KASSERT(cbp != NULL, ("NULL cbp! (device %s).",
1236			    sc->sc_name));
1237			bioq_remove(&queue, cbp);
1238			cp = disk->d_consumer;
1239			cbp->bio_done = g_mirror_done;
1240			cbp->bio_to = cp->provider;
1241			G_MIRROR_LOGREQ(3, cbp, "Sending request.");
1242			KASSERT(cp->acw > 0 && cp->ace > 0,
1243			    ("Consumer %s not opened (r%dw%de%d).",
1244			    cp->provider->name, cp->acr, cp->acw, cp->ace));
1245			g_io_request(cbp, cp);
1246		}
1247		/*
1248		 * Bump syncid on first write.
1249		 */
1250		if (sc->sc_bump_syncid == G_MIRROR_BUMP_ON_FIRST_WRITE) {
1251			sc->sc_bump_syncid = 0;
1252			g_topology_lock();
1253			g_mirror_bump_syncid(sc);
1254			g_topology_unlock();
1255		}
1256		return;
1257	    }
1258	default:
1259		KASSERT(1 == 0, ("Invalid command here: %u (device=%s)",
1260		    bp->bio_cmd, sc->sc_name));
1261		break;
1262	}
1263}
1264
1265/*
1266 * Worker thread.
1267 */
1268static void
1269g_mirror_worker(void *arg)
1270{
1271	struct g_mirror_softc *sc;
1272	struct g_mirror_disk *disk;
1273	struct g_mirror_event *ep;
1274	struct bio *bp;
1275	u_int nreqs;
1276
1277	sc = arg;
1278	curthread->td_base_pri = PRIBIO;
1279
1280	nreqs = 0;
1281	for (;;) {
1282		G_MIRROR_DEBUG(5, "%s: Let's see...", __func__);
1283		/*
1284		 * First take a look at events.
1285		 * This is important to handle events before any I/O requests.
1286		 */
1287		ep = g_mirror_event_get(sc);
1288		if (ep != NULL) {
1289			g_topology_lock();
1290			if ((ep->e_flags & G_MIRROR_EVENT_DEVICE) != 0) {
1291				/* Update only device status. */
1292				G_MIRROR_DEBUG(3,
1293				    "Running event for device %s.",
1294				    sc->sc_name);
1295				ep->e_error = 0;
1296				g_mirror_update_device(sc, 1);
1297			} else {
1298				/* Update disk status. */
1299				G_MIRROR_DEBUG(3, "Running event for disk %s.",
1300				     g_mirror_get_diskname(ep->e_disk));
1301				ep->e_error = g_mirror_update_disk(ep->e_disk,
1302				    ep->e_state);
1303				if (ep->e_error == 0)
1304					g_mirror_update_device(sc, 0);
1305			}
1306			g_topology_unlock();
1307			if ((ep->e_flags & G_MIRROR_EVENT_DONTWAIT) != 0) {
1308				KASSERT(ep->e_error == 0,
1309				    ("Error cannot be handled."));
1310				g_mirror_event_free(ep);
1311			} else {
1312				ep->e_flags |= G_MIRROR_EVENT_DONE;
1313				G_MIRROR_DEBUG(4, "%s: Waking up %p.", __func__,
1314				    ep);
1315				mtx_lock(&sc->sc_events_mtx);
1316				wakeup(ep);
1317				mtx_unlock(&sc->sc_events_mtx);
1318			}
1319			if ((sc->sc_flags &
1320			    G_MIRROR_DEVICE_FLAG_DESTROY) != 0) {
1321end:
1322				if ((sc->sc_flags &
1323				    G_MIRROR_DEVICE_FLAG_WAIT) != 0) {
1324					G_MIRROR_DEBUG(4, "%s: Waking up %p.",
1325					    __func__, &sc->sc_worker);
1326					wakeup(&sc->sc_worker);
1327					sc->sc_worker = NULL;
1328				} else {
1329					g_topology_lock();
1330					g_mirror_destroy_device(sc);
1331					g_topology_unlock();
1332					free(sc, M_MIRROR);
1333				}
1334				kthread_exit(0);
1335			}
1336			G_MIRROR_DEBUG(5, "%s: I'm here 1.", __func__);
1337			continue;
1338		}
1339		/*
1340		 * Now I/O requests.
1341		 */
1342		/* Get first request from the queue. */
1343		mtx_lock(&sc->sc_queue_mtx);
1344		bp = bioq_first(&sc->sc_queue);
1345		if (bp == NULL) {
1346			if ((sc->sc_flags &
1347			    G_MIRROR_DEVICE_FLAG_DESTROY) != 0) {
1348				mtx_unlock(&sc->sc_queue_mtx);
1349				goto end;
1350			}
1351		}
1352		if (sc->sc_sync.ds_ndisks > 0 &&
1353		    (bp == NULL || nreqs > g_mirror_reqs_per_sync)) {
1354			mtx_unlock(&sc->sc_queue_mtx);
1355			/*
1356			 * It is time for synchronization...
1357			 */
1358			nreqs = 0;
1359			LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1360				if (disk->d_state !=
1361				    G_MIRROR_DISK_STATE_SYNCHRONIZING) {
1362					continue;
1363				}
1364				if (disk->d_sync.ds_offset >=
1365				    sc->sc_provider->mediasize) {
1366					continue;
1367				}
1368				if (disk->d_sync.ds_offset >
1369				    disk->d_sync.ds_offset_done) {
1370					continue;
1371				}
1372				g_mirror_sync_one(disk);
1373			}
1374			G_MIRROR_DEBUG(5, "%s: I'm here 2.", __func__);
1375			goto sleep;
1376		}
1377		if (bp == NULL) {
1378			MSLEEP(sc, &sc->sc_queue_mtx, PRIBIO | PDROP, "m:w1", 0);
1379			G_MIRROR_DEBUG(5, "%s: I'm here 3.", __func__);
1380			continue;
1381		}
1382		nreqs++;
1383		bioq_remove(&sc->sc_queue, bp);
1384		mtx_unlock(&sc->sc_queue_mtx);
1385
1386		if ((bp->bio_flags & BIO_FLAG1) != 0) {
1387			g_mirror_regular_request(bp);
1388		} else if ((bp->bio_flags & BIO_FLAG2) != 0) {
1389			u_int timeout, sps;
1390
1391			g_mirror_sync_request(bp);
1392sleep:
1393			sps = atomic_load_acq_int(&g_mirror_syncs_per_sec);
1394			if (sps == 0) {
1395				G_MIRROR_DEBUG(5, "%s: I'm here 5.", __func__);
1396				continue;
1397			}
1398			mtx_lock(&sc->sc_queue_mtx);
1399			if (bioq_first(&sc->sc_queue) != NULL) {
1400				mtx_unlock(&sc->sc_queue_mtx);
1401				G_MIRROR_DEBUG(5, "%s: I'm here 4.", __func__);
1402				continue;
1403			}
1404			timeout = hz / sps;
1405			if (timeout == 0)
1406				timeout = 1;
1407			MSLEEP(sc, &sc->sc_queue_mtx, PRIBIO | PDROP, "m:w2",
1408			    timeout);
1409		} else {
1410			g_mirror_register_request(bp);
1411		}
1412		G_MIRROR_DEBUG(5, "%s: I'm here 6.", __func__);
1413	}
1414}
1415
1416/*
1417 * Open disk's consumer if needed.
1418 */
1419static void
1420g_mirror_update_access(struct g_mirror_disk *disk)
1421{
1422	struct g_provider *pp;
1423	struct g_consumer *cp;
1424	int acr, acw, ace, cpw, error;
1425
1426	g_topology_assert();
1427
1428	cp = disk->d_consumer;
1429	pp = disk->d_softc->sc_provider;
1430	if (pp == NULL) {
1431		acr = -cp->acr;
1432		acw = -cp->acw;
1433		ace = -cp->ace;
1434	} else {
1435		acr = pp->acr - cp->acr;
1436		acw = pp->acw - cp->acw;
1437		ace = pp->ace - cp->ace;
1438		/* Grab an extra "exclusive" bit. */
1439		if (pp->acr > 0 || pp->acw > 0 || pp->ace > 0)
1440			ace++;
1441	}
1442	if (acr == 0 && acw == 0 && ace == 0)
1443		return;
1444	cpw = cp->acw;
1445	error = g_access(cp, acr, acw, ace);
1446	G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d", cp->provider->name, acr,
1447	    acw, ace, error);
1448	if (error != 0) {
1449		disk->d_softc->sc_bump_syncid = G_MIRROR_BUMP_ON_FIRST_WRITE;
1450		g_mirror_event_send(disk, G_MIRROR_DISK_STATE_DISCONNECTED,
1451		    G_MIRROR_EVENT_DONTWAIT);
1452		return;
1453	}
1454	if (cpw == 0 && cp->acw > 0) {
1455		G_MIRROR_DEBUG(1, "Disk %s (device %s) marked as dirty.",
1456		    g_mirror_get_diskname(disk), disk->d_softc->sc_name);
1457		disk->d_flags |= G_MIRROR_DISK_FLAG_DIRTY;
1458	} else if (cpw > 0 && cp->acw == 0) {
1459		G_MIRROR_DEBUG(1, "Disk %s (device %s) marked as clean.",
1460		    g_mirror_get_diskname(disk), disk->d_softc->sc_name);
1461		disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
1462	}
1463}
1464
1465static void
1466g_mirror_sync_start(struct g_mirror_disk *disk)
1467{
1468	struct g_mirror_softc *sc;
1469	struct g_consumer *cp;
1470	int error;
1471
1472	g_topology_assert();
1473
1474	sc = disk->d_softc;
1475	KASSERT(sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
1476	    ("Device not in RUNNING state (%s, %u).", sc->sc_name,
1477	    sc->sc_state));
1478	cp = disk->d_consumer;
1479	KASSERT(cp->acr == 0 && cp->acw == 0 && cp->ace == 0,
1480	    ("Consumer %s already opened.", cp->provider->name));
1481
1482	G_MIRROR_DEBUG(0, "Device %s: rebuilding provider %s.", sc->sc_name,
1483	    g_mirror_get_diskname(disk));
1484	error = g_access(cp, 0, 1, 1);
1485	G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d", cp->provider->name, 0, 1,
1486	    1, error);
1487	if (error != 0) {
1488		g_mirror_event_send(disk, G_MIRROR_DISK_STATE_DISCONNECTED,
1489		    G_MIRROR_EVENT_DONTWAIT);
1490		return;
1491	}
1492	disk->d_flags |= G_MIRROR_DISK_FLAG_DIRTY;
1493	KASSERT(disk->d_sync.ds_consumer == NULL,
1494	    ("Sync consumer already exists (device=%s, disk=%s).",
1495	    sc->sc_name, g_mirror_get_diskname(disk)));
1496	disk->d_sync.ds_consumer = g_new_consumer(sc->sc_sync.ds_geom);
1497	disk->d_sync.ds_consumer->private = disk;
1498	error = g_attach(disk->d_sync.ds_consumer, disk->d_softc->sc_provider);
1499	KASSERT(error == 0, ("Cannot attach to %s (error=%d).",
1500	    disk->d_softc->sc_name, error));
1501	error = g_access(disk->d_sync.ds_consumer, 1, 0, 0);
1502	KASSERT(error == 0, ("Cannot open %s (error=%d).",
1503	    disk->d_softc->sc_name, error));
1504	sc->sc_sync.ds_ndisks++;
1505}
1506
1507/*
1508 * Stop synchronization process.
1509 * type: 0 - synchronization finished
1510 *       1 - synchronization stopped
1511 */
1512static void
1513g_mirror_sync_stop(struct g_mirror_disk *disk, int type)
1514{
1515	struct g_consumer *cp;
1516
1517	g_topology_assert();
1518	KASSERT(disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING,
1519	    ("Wrong disk state (%s, %s).", g_mirror_get_diskname(disk),
1520	    g_mirror_disk_state2str(disk->d_state)));
1521	if (disk->d_sync.ds_consumer == NULL)
1522		return;
1523
1524	if (type == 0) {
1525		G_MIRROR_DEBUG(0, "Device %s: rebuilding provider %s finished.",
1526		    disk->d_softc->sc_name, g_mirror_get_diskname(disk));
1527	} else /* if (type == 1) */ {
1528		G_MIRROR_DEBUG(0, "Device %s: rebuilding provider %s stopped.",
1529		    disk->d_softc->sc_name, g_mirror_get_diskname(disk));
1530	}
1531	cp = disk->d_sync.ds_consumer;
1532	g_access(cp, -1, 0, 0);
1533	g_mirror_kill_consumer(disk->d_softc, cp);
1534	disk->d_sync.ds_consumer = NULL;
1535	disk->d_softc->sc_sync.ds_ndisks--;
1536	cp = disk->d_consumer;
1537	KASSERT(cp->acr == 0 && cp->acw == 1 && cp->ace == 1,
1538	    ("Consumer %s not opened.", cp->provider->name));
1539	g_access(cp, 0, -1, -1);
1540	G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d", cp->provider->name, 0, -1,
1541	    -1, 0);
1542	disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
1543}
1544
1545static void
1546g_mirror_launch_provider(struct g_mirror_softc *sc)
1547{
1548	struct g_mirror_disk *disk;
1549	struct g_provider *pp;
1550
1551	g_topology_assert();
1552
1553	pp = g_new_providerf(sc->sc_geom, "mirror/%s", sc->sc_name);
1554	pp->mediasize = sc->sc_mediasize;
1555	pp->sectorsize = sc->sc_sectorsize;
1556	sc->sc_provider = pp;
1557	g_error_provider(pp, 0);
1558	G_MIRROR_DEBUG(0, "Device %s: provider %s launched.", sc->sc_name,
1559	    pp->name);
1560	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1561		if (disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING)
1562			g_mirror_sync_start(disk);
1563	}
1564}
1565
1566static void
1567g_mirror_destroy_provider(struct g_mirror_softc *sc)
1568{
1569	struct g_mirror_disk *disk;
1570	struct bio *bp;
1571
1572	g_topology_assert();
1573	KASSERT(sc->sc_provider != NULL, ("NULL provider (device=%s).",
1574	    sc->sc_name));
1575
1576	g_error_provider(sc->sc_provider, ENXIO);
1577	mtx_lock(&sc->sc_queue_mtx);
1578	while ((bp = bioq_first(&sc->sc_queue)) != NULL) {
1579		bioq_remove(&sc->sc_queue, bp);
1580		g_io_deliver(bp, ENXIO);
1581	}
1582	mtx_unlock(&sc->sc_queue_mtx);
1583	G_MIRROR_DEBUG(0, "Device %s: provider %s destroyed.", sc->sc_name,
1584	    sc->sc_provider->name);
1585	sc->sc_provider->flags |= G_PF_WITHER;
1586	g_orphan_provider(sc->sc_provider, ENXIO);
1587	sc->sc_provider = NULL;
1588	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1589		if (disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING)
1590			g_mirror_sync_stop(disk, 1);
1591	}
1592}
1593
1594static void
1595g_mirror_go(void *arg)
1596{
1597	struct g_mirror_softc *sc;
1598
1599	sc = arg;
1600	G_MIRROR_DEBUG(0, "Force device %s start due to timeout.", sc->sc_name);
1601	g_mirror_event_send(sc, 0,
1602	    G_MIRROR_EVENT_DONTWAIT | G_MIRROR_EVENT_DEVICE);
1603}
1604
1605static u_int
1606g_mirror_determine_state(struct g_mirror_disk *disk)
1607{
1608	struct g_mirror_softc *sc;
1609	u_int state;
1610
1611	sc = disk->d_softc;
1612	if (sc->sc_syncid == disk->d_sync.ds_syncid) {
1613		if ((disk->d_flags &
1614		    G_MIRROR_DISK_FLAG_SYNCHRONIZING) == 0) {
1615			/* Disk does not need synchronization. */
1616			state = G_MIRROR_DISK_STATE_ACTIVE;
1617		} else {
1618			if ((sc->sc_flags &
1619			     G_MIRROR_DEVICE_FLAG_NOAUTOSYNC) == 0  ||
1620			    (disk->d_flags &
1621			     G_MIRROR_DISK_FLAG_FORCE_SYNC) != 0) {
1622				/*
1623				 * We can start synchronization from
1624				 * the stored offset.
1625				 */
1626				state = G_MIRROR_DISK_STATE_SYNCHRONIZING;
1627			} else {
1628				state = G_MIRROR_DISK_STATE_STALE;
1629			}
1630		}
1631	} else if (disk->d_sync.ds_syncid < sc->sc_syncid) {
1632		/*
1633		 * Reset all synchronization data for this disk,
1634		 * because if it even was synchronized, it was
1635		 * synchronized to disks with different syncid.
1636		 */
1637		disk->d_flags |= G_MIRROR_DISK_FLAG_SYNCHRONIZING;
1638		disk->d_sync.ds_offset = 0;
1639		disk->d_sync.ds_offset_done = 0;
1640		disk->d_sync.ds_syncid = sc->sc_syncid;
1641		if ((sc->sc_flags & G_MIRROR_DEVICE_FLAG_NOAUTOSYNC) == 0 ||
1642		    (disk->d_flags & G_MIRROR_DISK_FLAG_FORCE_SYNC) != 0) {
1643			state = G_MIRROR_DISK_STATE_SYNCHRONIZING;
1644		} else {
1645			state = G_MIRROR_DISK_STATE_STALE;
1646		}
1647	} else /* if (sc->sc_syncid < disk->d_sync.ds_syncid) */ {
1648		/*
1649		 * Not good, NOT GOOD!
1650		 * It means that mirror was started on stale disks
1651		 * and more fresh disk just arrive.
1652		 * If there were writes, mirror is fucked up, sorry.
1653		 * I think the best choice here is don't touch
1654		 * this disk and inform the user laudly.
1655		 */
1656		G_MIRROR_DEBUG(0, "Device %s was started before the freshest "
1657		    "disk (%s) arrives!! It will not be connected to the "
1658		    "running device.", sc->sc_name,
1659		    g_mirror_get_diskname(disk));
1660		g_mirror_destroy_disk(disk);
1661		state = G_MIRROR_DISK_STATE_NONE;
1662		/* Return immediately, because disk was destroyed. */
1663		return (state);
1664	}
1665	G_MIRROR_DEBUG(3, "State for %s disk: %s.",
1666	    g_mirror_get_diskname(disk), g_mirror_disk_state2str(state));
1667	return (state);
1668}
1669
1670/*
1671 * Update device state.
1672 */
1673static void
1674g_mirror_update_device(struct g_mirror_softc *sc, boolean_t force)
1675{
1676	struct g_mirror_disk *disk;
1677	u_int state;
1678
1679	g_topology_assert();
1680
1681	switch (sc->sc_state) {
1682	case G_MIRROR_DEVICE_STATE_STARTING:
1683	    {
1684		struct g_mirror_disk *pdisk;
1685		u_int dirty, ndisks, syncid;
1686
1687		KASSERT(sc->sc_provider == NULL,
1688		    ("Non-NULL provider in STARTING state (%s).", sc->sc_name));
1689		/*
1690		 * Are we ready? We are, if all disks are connected or
1691		 * if we have any disks and 'force' is true.
1692		 */
1693		if ((force && g_mirror_ndisks(sc, -1) > 0) ||
1694		    sc->sc_ndisks == g_mirror_ndisks(sc, -1)) {
1695			;
1696		} else if (g_mirror_ndisks(sc, -1) == 0) {
1697			/*
1698			 * Disks went down in starting phase, so destroy
1699			 * device.
1700			 */
1701			callout_drain(&sc->sc_callout);
1702			sc->sc_flags |= G_MIRROR_DEVICE_FLAG_DESTROY;
1703			return;
1704		} else {
1705			return;
1706		}
1707
1708		/*
1709		 * Activate all disks with the biggest syncid.
1710		 */
1711		if (force) {
1712			/*
1713			 * If 'force' is true, we have been called due to
1714			 * timeout, so don't bother canceling timeout.
1715			 */
1716			ndisks = 0;
1717			LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1718				if ((disk->d_flags &
1719				    G_MIRROR_DISK_FLAG_SYNCHRONIZING) == 0) {
1720					ndisks++;
1721				}
1722			}
1723			if (ndisks == 0) {
1724				/* No valid disks found, destroy device. */
1725				sc->sc_flags |= G_MIRROR_DEVICE_FLAG_DESTROY;
1726				return;
1727			}
1728		} else {
1729			/* Cancel timeout. */
1730			callout_drain(&sc->sc_callout);
1731		}
1732
1733		/*
1734		 * Find disk with the biggest syncid.
1735		 */
1736		syncid = 0;
1737		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1738			if (disk->d_sync.ds_syncid > syncid)
1739				syncid = disk->d_sync.ds_syncid;
1740		}
1741
1742		/*
1743		 * Here we need to look for dirty disks and if all disks
1744		 * with the biggest syncid are dirty, we have to choose
1745		 * one with the biggest priority and rebuild the rest.
1746		 */
1747		/*
1748		 * Find the number of dirty disks with the biggest syncid.
1749		 * Find the number of disks with the biggest syncid.
1750		 * While here, find a disk with the biggest priority.
1751		 */
1752		dirty = ndisks = 0;
1753		pdisk = NULL;
1754		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1755			if (disk->d_sync.ds_syncid != syncid)
1756				continue;
1757			if ((disk->d_flags &
1758			    G_MIRROR_DISK_FLAG_SYNCHRONIZING) != 0) {
1759				continue;
1760			}
1761			ndisks++;
1762			if ((disk->d_flags & G_MIRROR_DISK_FLAG_DIRTY) != 0) {
1763				dirty++;
1764				if (pdisk == NULL ||
1765				    pdisk->d_priority < disk->d_priority) {
1766					pdisk = disk;
1767				}
1768			}
1769		}
1770		if (dirty == 0) {
1771			/* No dirty disks at all, great. */
1772		} else if (dirty == ndisks) {
1773			/*
1774			 * Force synchronization for all dirty disks except one
1775			 * with the biggest priority.
1776			 */
1777			KASSERT(pdisk != NULL, ("pdisk == NULL"));
1778			G_MIRROR_DEBUG(1, "Using disk %s (device %s) as a "
1779			    "master disk for synchronization.",
1780			    g_mirror_get_diskname(pdisk), sc->sc_name);
1781			LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1782				if (disk->d_sync.ds_syncid != syncid)
1783					continue;
1784				if ((disk->d_flags &
1785				    G_MIRROR_DISK_FLAG_SYNCHRONIZING) != 0) {
1786					continue;
1787				}
1788				KASSERT((disk->d_flags &
1789				    G_MIRROR_DISK_FLAG_DIRTY) != 0,
1790				    ("Disk %s isn't marked as dirty.",
1791				    g_mirror_get_diskname(disk)));
1792				/* Skip the disk with the biggest priority. */
1793				if (disk == pdisk)
1794					continue;
1795				disk->d_sync.ds_syncid = 0;
1796			}
1797		} else if (dirty < ndisks) {
1798			/*
1799			 * Force synchronization for all dirty disks.
1800			 * We have some non-dirty disks.
1801			 */
1802			LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1803				if (disk->d_sync.ds_syncid != syncid)
1804					continue;
1805				if ((disk->d_flags &
1806				    G_MIRROR_DISK_FLAG_SYNCHRONIZING) != 0) {
1807					continue;
1808				}
1809				if ((disk->d_flags &
1810				    G_MIRROR_DISK_FLAG_DIRTY) == 0) {
1811					continue;
1812				}
1813				disk->d_sync.ds_syncid = 0;
1814			}
1815		}
1816
1817		/* Reset hint. */
1818		sc->sc_hint = NULL;
1819		sc->sc_syncid = syncid;
1820		if (force) {
1821			/* Remember to bump syncid on first write. */
1822			sc->sc_bump_syncid = G_MIRROR_BUMP_ON_FIRST_WRITE;
1823		}
1824		state = G_MIRROR_DEVICE_STATE_RUNNING;
1825		G_MIRROR_DEBUG(1, "Device %s state changed from %s to %s.",
1826		    sc->sc_name, g_mirror_device_state2str(sc->sc_state),
1827		    g_mirror_device_state2str(state));
1828		sc->sc_state = state;
1829		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1830			state = g_mirror_determine_state(disk);
1831			g_mirror_event_send(disk, state,
1832			    G_MIRROR_EVENT_DONTWAIT);
1833			if (state == G_MIRROR_DISK_STATE_STALE) {
1834				sc->sc_bump_syncid =
1835				    G_MIRROR_BUMP_ON_FIRST_WRITE;
1836			}
1837		}
1838		break;
1839	    }
1840	case G_MIRROR_DEVICE_STATE_RUNNING:
1841		/*
1842		 * Bump syncid here, if we need to do it immediately.
1843		 */
1844		if (sc->sc_bump_syncid == G_MIRROR_BUMP_IMMEDIATELY) {
1845			sc->sc_bump_syncid = 0;
1846			g_mirror_bump_syncid(sc);
1847		}
1848		if (g_mirror_ndisks(sc, -1) == 0) {
1849			/*
1850			 * No disks at all, we need to destroy device.
1851			 */
1852			sc->sc_flags |= G_MIRROR_DEVICE_FLAG_DESTROY;
1853		} else if (g_mirror_ndisks(sc,
1854		    G_MIRROR_DISK_STATE_ACTIVE) == 0 &&
1855		    g_mirror_ndisks(sc, G_MIRROR_DISK_STATE_NEW) == 0) {
1856			/*
1857			 * No active disks, destroy provider.
1858			 */
1859			if (sc->sc_provider != NULL)
1860				g_mirror_destroy_provider(sc);
1861		} else if (g_mirror_ndisks(sc,
1862		    G_MIRROR_DISK_STATE_ACTIVE) > 0 &&
1863		    g_mirror_ndisks(sc, G_MIRROR_DISK_STATE_NEW) == 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_spoiled;
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_spoiled;
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.",
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