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