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