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