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