g_mirror.c revision 139054
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 139054 2004-12-19 23:55:49Z 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	int error;
1644
1645	g_topology_assert();
1646
1647	sc = disk->d_softc;
1648	KASSERT(sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
1649	    ("Device not in RUNNING state (%s, %u).", sc->sc_name,
1650	    sc->sc_state));
1651
1652	G_MIRROR_DEBUG(0, "Device %s: rebuilding provider %s.", sc->sc_name,
1653	    g_mirror_get_diskname(disk));
1654	disk->d_flags |= G_MIRROR_DISK_FLAG_DIRTY;
1655	KASSERT(disk->d_sync.ds_consumer == NULL,
1656	    ("Sync consumer already exists (device=%s, disk=%s).",
1657	    sc->sc_name, g_mirror_get_diskname(disk)));
1658	disk->d_sync.ds_consumer = g_new_consumer(sc->sc_sync.ds_geom);
1659	disk->d_sync.ds_consumer->private = disk;
1660	disk->d_sync.ds_consumer->index = 0;
1661	error = g_attach(disk->d_sync.ds_consumer, disk->d_softc->sc_provider);
1662	KASSERT(error == 0, ("Cannot attach to %s (error=%d).",
1663	    disk->d_softc->sc_name, error));
1664	error = g_access(disk->d_sync.ds_consumer, 1, 0, 0);
1665	KASSERT(error == 0, ("Cannot open %s (error=%d).",
1666	    disk->d_softc->sc_name, error));
1667	disk->d_sync.ds_data = malloc(MAXPHYS, M_MIRROR, M_WAITOK);
1668	sc->sc_sync.ds_ndisks++;
1669}
1670
1671/*
1672 * Stop synchronization process.
1673 * type: 0 - synchronization finished
1674 *       1 - synchronization stopped
1675 */
1676static void
1677g_mirror_sync_stop(struct g_mirror_disk *disk, int type)
1678{
1679
1680	g_topology_assert();
1681	KASSERT(disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING,
1682	    ("Wrong disk state (%s, %s).", g_mirror_get_diskname(disk),
1683	    g_mirror_disk_state2str(disk->d_state)));
1684	if (disk->d_sync.ds_consumer == NULL)
1685		return;
1686
1687	if (type == 0) {
1688		G_MIRROR_DEBUG(0, "Device %s: rebuilding provider %s finished.",
1689		    disk->d_softc->sc_name, g_mirror_get_diskname(disk));
1690	} else /* if (type == 1) */ {
1691		G_MIRROR_DEBUG(0, "Device %s: rebuilding provider %s stopped.",
1692		    disk->d_softc->sc_name, g_mirror_get_diskname(disk));
1693	}
1694	g_mirror_kill_consumer(disk->d_softc, disk->d_sync.ds_consumer);
1695	free(disk->d_sync.ds_data, M_MIRROR);
1696	disk->d_sync.ds_consumer = NULL;
1697	disk->d_softc->sc_sync.ds_ndisks--;
1698	disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
1699}
1700
1701static void
1702g_mirror_launch_provider(struct g_mirror_softc *sc)
1703{
1704	struct g_mirror_disk *disk;
1705	struct g_provider *pp;
1706
1707	g_topology_assert();
1708
1709	pp = g_new_providerf(sc->sc_geom, "mirror/%s", sc->sc_name);
1710	pp->mediasize = sc->sc_mediasize;
1711	pp->sectorsize = sc->sc_sectorsize;
1712	sc->sc_provider = pp;
1713	g_error_provider(pp, 0);
1714	G_MIRROR_DEBUG(0, "Device %s: provider %s launched.", sc->sc_name,
1715	    pp->name);
1716	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1717		if (disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING)
1718			g_mirror_sync_start(disk);
1719	}
1720}
1721
1722static void
1723g_mirror_destroy_provider(struct g_mirror_softc *sc)
1724{
1725	struct g_mirror_disk *disk;
1726	struct bio *bp;
1727
1728	g_topology_assert();
1729	KASSERT(sc->sc_provider != NULL, ("NULL provider (device=%s).",
1730	    sc->sc_name));
1731
1732	g_error_provider(sc->sc_provider, ENXIO);
1733	mtx_lock(&sc->sc_queue_mtx);
1734	while ((bp = bioq_first(&sc->sc_queue)) != NULL) {
1735		bioq_remove(&sc->sc_queue, bp);
1736		g_io_deliver(bp, ENXIO);
1737	}
1738	mtx_unlock(&sc->sc_queue_mtx);
1739	G_MIRROR_DEBUG(0, "Device %s: provider %s destroyed.", sc->sc_name,
1740	    sc->sc_provider->name);
1741	sc->sc_provider->flags |= G_PF_WITHER;
1742	g_orphan_provider(sc->sc_provider, ENXIO);
1743	sc->sc_provider = NULL;
1744	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1745		if (disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING)
1746			g_mirror_sync_stop(disk, 1);
1747	}
1748}
1749
1750static void
1751g_mirror_go(void *arg)
1752{
1753	struct g_mirror_softc *sc;
1754
1755	sc = arg;
1756	G_MIRROR_DEBUG(0, "Force device %s start due to timeout.", sc->sc_name);
1757	g_mirror_event_send(sc, 0,
1758	    G_MIRROR_EVENT_DONTWAIT | G_MIRROR_EVENT_DEVICE);
1759}
1760
1761static u_int
1762g_mirror_determine_state(struct g_mirror_disk *disk)
1763{
1764	struct g_mirror_softc *sc;
1765	u_int state;
1766
1767	sc = disk->d_softc;
1768	if (sc->sc_syncid == disk->d_sync.ds_syncid) {
1769		if ((disk->d_flags &
1770		    G_MIRROR_DISK_FLAG_SYNCHRONIZING) == 0) {
1771			/* Disk does not need synchronization. */
1772			state = G_MIRROR_DISK_STATE_ACTIVE;
1773		} else {
1774			if ((sc->sc_flags &
1775			     G_MIRROR_DEVICE_FLAG_NOAUTOSYNC) == 0  ||
1776			    (disk->d_flags &
1777			     G_MIRROR_DISK_FLAG_FORCE_SYNC) != 0) {
1778				/*
1779				 * We can start synchronization from
1780				 * the stored offset.
1781				 */
1782				state = G_MIRROR_DISK_STATE_SYNCHRONIZING;
1783			} else {
1784				state = G_MIRROR_DISK_STATE_STALE;
1785			}
1786		}
1787	} else if (disk->d_sync.ds_syncid < sc->sc_syncid) {
1788		/*
1789		 * Reset all synchronization data for this disk,
1790		 * because if it even was synchronized, it was
1791		 * synchronized to disks with different syncid.
1792		 */
1793		disk->d_flags |= G_MIRROR_DISK_FLAG_SYNCHRONIZING;
1794		disk->d_sync.ds_offset = 0;
1795		disk->d_sync.ds_offset_done = 0;
1796		disk->d_sync.ds_syncid = sc->sc_syncid;
1797		if ((sc->sc_flags & G_MIRROR_DEVICE_FLAG_NOAUTOSYNC) == 0 ||
1798		    (disk->d_flags & G_MIRROR_DISK_FLAG_FORCE_SYNC) != 0) {
1799			state = G_MIRROR_DISK_STATE_SYNCHRONIZING;
1800		} else {
1801			state = G_MIRROR_DISK_STATE_STALE;
1802		}
1803	} else /* if (sc->sc_syncid < disk->d_sync.ds_syncid) */ {
1804		/*
1805		 * Not good, NOT GOOD!
1806		 * It means that mirror was started on stale disks
1807		 * and more fresh disk just arrive.
1808		 * If there were writes, mirror is fucked up, sorry.
1809		 * I think the best choice here is don't touch
1810		 * this disk and inform the user laudly.
1811		 */
1812		G_MIRROR_DEBUG(0, "Device %s was started before the freshest "
1813		    "disk (%s) arrives!! It will not be connected to the "
1814		    "running device.", sc->sc_name,
1815		    g_mirror_get_diskname(disk));
1816		g_mirror_destroy_disk(disk);
1817		state = G_MIRROR_DISK_STATE_NONE;
1818		/* Return immediately, because disk was destroyed. */
1819		return (state);
1820	}
1821	G_MIRROR_DEBUG(3, "State for %s disk: %s.",
1822	    g_mirror_get_diskname(disk), g_mirror_disk_state2str(state));
1823	return (state);
1824}
1825
1826/*
1827 * Update device state.
1828 */
1829static void
1830g_mirror_update_device(struct g_mirror_softc *sc, boolean_t force)
1831{
1832	struct g_mirror_disk *disk;
1833	u_int state;
1834
1835	g_topology_assert();
1836
1837	switch (sc->sc_state) {
1838	case G_MIRROR_DEVICE_STATE_STARTING:
1839	    {
1840		struct g_mirror_disk *pdisk;
1841		u_int dirty, ndisks, syncid;
1842
1843		KASSERT(sc->sc_provider == NULL,
1844		    ("Non-NULL provider in STARTING state (%s).", sc->sc_name));
1845		/*
1846		 * Are we ready? We are, if all disks are connected or
1847		 * if we have any disks and 'force' is true.
1848		 */
1849		if ((force && g_mirror_ndisks(sc, -1) > 0) ||
1850		    sc->sc_ndisks == g_mirror_ndisks(sc, -1)) {
1851			;
1852		} else if (g_mirror_ndisks(sc, -1) == 0) {
1853			/*
1854			 * Disks went down in starting phase, so destroy
1855			 * device.
1856			 */
1857			callout_drain(&sc->sc_callout);
1858			sc->sc_flags |= G_MIRROR_DEVICE_FLAG_DESTROY;
1859			return;
1860		} else {
1861			return;
1862		}
1863
1864		/*
1865		 * Activate all disks with the biggest syncid.
1866		 */
1867		if (force) {
1868			/*
1869			 * If 'force' is true, we have been called due to
1870			 * timeout, so don't bother canceling timeout.
1871			 */
1872			ndisks = 0;
1873			LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1874				if ((disk->d_flags &
1875				    G_MIRROR_DISK_FLAG_SYNCHRONIZING) == 0) {
1876					ndisks++;
1877				}
1878			}
1879			if (ndisks == 0) {
1880				/* No valid disks found, destroy device. */
1881				sc->sc_flags |= G_MIRROR_DEVICE_FLAG_DESTROY;
1882				return;
1883			}
1884		} else {
1885			/* Cancel timeout. */
1886			callout_drain(&sc->sc_callout);
1887		}
1888
1889		/*
1890		 * Find disk with the biggest syncid.
1891		 */
1892		syncid = 0;
1893		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1894			if (disk->d_sync.ds_syncid > syncid)
1895				syncid = disk->d_sync.ds_syncid;
1896		}
1897
1898		/*
1899		 * Here we need to look for dirty disks and if all disks
1900		 * with the biggest syncid are dirty, we have to choose
1901		 * one with the biggest priority and rebuild the rest.
1902		 */
1903		/*
1904		 * Find the number of dirty disks with the biggest syncid.
1905		 * Find the number of disks with the biggest syncid.
1906		 * While here, find a disk with the biggest priority.
1907		 */
1908		dirty = ndisks = 0;
1909		pdisk = NULL;
1910		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1911			if (disk->d_sync.ds_syncid != syncid)
1912				continue;
1913			if ((disk->d_flags &
1914			    G_MIRROR_DISK_FLAG_SYNCHRONIZING) != 0) {
1915				continue;
1916			}
1917			ndisks++;
1918			if ((disk->d_flags & G_MIRROR_DISK_FLAG_DIRTY) != 0) {
1919				dirty++;
1920				if (pdisk == NULL ||
1921				    pdisk->d_priority < disk->d_priority) {
1922					pdisk = disk;
1923				}
1924			}
1925		}
1926		if (dirty == 0) {
1927			/* No dirty disks at all, great. */
1928		} else if (dirty == ndisks) {
1929			/*
1930			 * Force synchronization for all dirty disks except one
1931			 * with the biggest priority.
1932			 */
1933			KASSERT(pdisk != NULL, ("pdisk == NULL"));
1934			G_MIRROR_DEBUG(1, "Using disk %s (device %s) as a "
1935			    "master disk for synchronization.",
1936			    g_mirror_get_diskname(pdisk), sc->sc_name);
1937			LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1938				if (disk->d_sync.ds_syncid != syncid)
1939					continue;
1940				if ((disk->d_flags &
1941				    G_MIRROR_DISK_FLAG_SYNCHRONIZING) != 0) {
1942					continue;
1943				}
1944				KASSERT((disk->d_flags &
1945				    G_MIRROR_DISK_FLAG_DIRTY) != 0,
1946				    ("Disk %s isn't marked as dirty.",
1947				    g_mirror_get_diskname(disk)));
1948				/* Skip the disk with the biggest priority. */
1949				if (disk == pdisk)
1950					continue;
1951				disk->d_sync.ds_syncid = 0;
1952			}
1953		} else if (dirty < ndisks) {
1954			/*
1955			 * Force synchronization for all dirty disks.
1956			 * We have some non-dirty disks.
1957			 */
1958			LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1959				if (disk->d_sync.ds_syncid != syncid)
1960					continue;
1961				if ((disk->d_flags &
1962				    G_MIRROR_DISK_FLAG_SYNCHRONIZING) != 0) {
1963					continue;
1964				}
1965				if ((disk->d_flags &
1966				    G_MIRROR_DISK_FLAG_DIRTY) == 0) {
1967					continue;
1968				}
1969				disk->d_sync.ds_syncid = 0;
1970			}
1971		}
1972
1973		/* Reset hint. */
1974		sc->sc_hint = NULL;
1975		sc->sc_syncid = syncid;
1976		if (force) {
1977			/* Remember to bump syncid on first write. */
1978			sc->sc_bump_syncid = G_MIRROR_BUMP_ON_FIRST_WRITE;
1979		}
1980		state = G_MIRROR_DEVICE_STATE_RUNNING;
1981		G_MIRROR_DEBUG(1, "Device %s state changed from %s to %s.",
1982		    sc->sc_name, g_mirror_device_state2str(sc->sc_state),
1983		    g_mirror_device_state2str(state));
1984		sc->sc_state = state;
1985		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1986			state = g_mirror_determine_state(disk);
1987			g_mirror_event_send(disk, state,
1988			    G_MIRROR_EVENT_DONTWAIT);
1989			if (state == G_MIRROR_DISK_STATE_STALE) {
1990				sc->sc_bump_syncid =
1991				    G_MIRROR_BUMP_ON_FIRST_WRITE;
1992			}
1993		}
1994		wakeup(&g_mirror_class);
1995		break;
1996	    }
1997	case G_MIRROR_DEVICE_STATE_RUNNING:
1998		if (g_mirror_ndisks(sc, G_MIRROR_DISK_STATE_ACTIVE) == 0 &&
1999		    g_mirror_ndisks(sc, G_MIRROR_DISK_STATE_NEW) == 0) {
2000			/*
2001			 * No active disks or no disks at all,
2002			 * so destroy device.
2003			 */
2004			if (sc->sc_provider != NULL)
2005				g_mirror_destroy_provider(sc);
2006			sc->sc_flags |= G_MIRROR_DEVICE_FLAG_DESTROY;
2007			break;
2008		} else if (g_mirror_ndisks(sc,
2009		    G_MIRROR_DISK_STATE_ACTIVE) > 0 &&
2010		    g_mirror_ndisks(sc, G_MIRROR_DISK_STATE_NEW) == 0) {
2011			/*
2012			 * We have active disks, launch provider if it doesn't
2013			 * exist.
2014			 */
2015			if (sc->sc_provider == NULL)
2016				g_mirror_launch_provider(sc);
2017		}
2018		/*
2019		 * Bump syncid here, if we need to do it immediately.
2020		 */
2021		if (sc->sc_bump_syncid == G_MIRROR_BUMP_IMMEDIATELY) {
2022			sc->sc_bump_syncid = 0;
2023			g_mirror_bump_syncid(sc);
2024		}
2025		break;
2026	default:
2027		KASSERT(1 == 0, ("Wrong device state (%s, %s).",
2028		    sc->sc_name, g_mirror_device_state2str(sc->sc_state)));
2029		break;
2030	}
2031}
2032
2033/*
2034 * Update disk state and device state if needed.
2035 */
2036#define	DISK_STATE_CHANGED()	G_MIRROR_DEBUG(1,			\
2037	"Disk %s state changed from %s to %s (device %s).",		\
2038	g_mirror_get_diskname(disk),					\
2039	g_mirror_disk_state2str(disk->d_state),				\
2040	g_mirror_disk_state2str(state), sc->sc_name)
2041static int
2042g_mirror_update_disk(struct g_mirror_disk *disk, u_int state)
2043{
2044	struct g_mirror_softc *sc;
2045
2046	g_topology_assert();
2047
2048	sc = disk->d_softc;
2049again:
2050	G_MIRROR_DEBUG(3, "Changing disk %s state from %s to %s.",
2051	    g_mirror_get_diskname(disk), g_mirror_disk_state2str(disk->d_state),
2052	    g_mirror_disk_state2str(state));
2053	switch (state) {
2054	case G_MIRROR_DISK_STATE_NEW:
2055		/*
2056		 * Possible scenarios:
2057		 * 1. New disk arrive.
2058		 */
2059		/* Previous state should be NONE. */
2060		KASSERT(disk->d_state == G_MIRROR_DISK_STATE_NONE,
2061		    ("Wrong disk state (%s, %s).", g_mirror_get_diskname(disk),
2062		    g_mirror_disk_state2str(disk->d_state)));
2063		DISK_STATE_CHANGED();
2064
2065		disk->d_state = state;
2066		if (LIST_EMPTY(&sc->sc_disks))
2067			LIST_INSERT_HEAD(&sc->sc_disks, disk, d_next);
2068		else {
2069			struct g_mirror_disk *dp;
2070
2071			LIST_FOREACH(dp, &sc->sc_disks, d_next) {
2072				if (disk->d_priority >= dp->d_priority) {
2073					LIST_INSERT_BEFORE(dp, disk, d_next);
2074					dp = NULL;
2075					break;
2076				}
2077				if (LIST_NEXT(dp, d_next) == NULL)
2078					break;
2079			}
2080			if (dp != NULL)
2081				LIST_INSERT_AFTER(dp, disk, d_next);
2082		}
2083		G_MIRROR_DEBUG(0, "Device %s: provider %s detected.",
2084		    sc->sc_name, g_mirror_get_diskname(disk));
2085		if (sc->sc_state == G_MIRROR_DEVICE_STATE_STARTING)
2086			break;
2087		KASSERT(sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
2088		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2089		    g_mirror_device_state2str(sc->sc_state),
2090		    g_mirror_get_diskname(disk),
2091		    g_mirror_disk_state2str(disk->d_state)));
2092		state = g_mirror_determine_state(disk);
2093		if (state != G_MIRROR_DISK_STATE_NONE)
2094			goto again;
2095		break;
2096	case G_MIRROR_DISK_STATE_ACTIVE:
2097		/*
2098		 * Possible scenarios:
2099		 * 1. New disk does not need synchronization.
2100		 * 2. Synchronization process finished successfully.
2101		 */
2102		KASSERT(sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
2103		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2104		    g_mirror_device_state2str(sc->sc_state),
2105		    g_mirror_get_diskname(disk),
2106		    g_mirror_disk_state2str(disk->d_state)));
2107		/* Previous state should be NEW or SYNCHRONIZING. */
2108		KASSERT(disk->d_state == G_MIRROR_DISK_STATE_NEW ||
2109		    disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING,
2110		    ("Wrong disk state (%s, %s).", g_mirror_get_diskname(disk),
2111		    g_mirror_disk_state2str(disk->d_state)));
2112		DISK_STATE_CHANGED();
2113
2114		if (disk->d_state == G_MIRROR_DISK_STATE_NEW)
2115			disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
2116		else if (disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING) {
2117			disk->d_flags &= ~G_MIRROR_DISK_FLAG_SYNCHRONIZING;
2118			disk->d_flags &= ~G_MIRROR_DISK_FLAG_FORCE_SYNC;
2119			g_mirror_sync_stop(disk, 0);
2120		}
2121		disk->d_state = state;
2122		disk->d_sync.ds_offset = 0;
2123		disk->d_sync.ds_offset_done = 0;
2124		g_mirror_update_access(disk);
2125		g_mirror_update_metadata(disk);
2126		G_MIRROR_DEBUG(0, "Device %s: provider %s activated.",
2127		    sc->sc_name, g_mirror_get_diskname(disk));
2128		break;
2129	case G_MIRROR_DISK_STATE_STALE:
2130		/*
2131		 * Possible scenarios:
2132		 * 1. Stale disk was connected.
2133		 */
2134		/* Previous state should be NEW. */
2135		KASSERT(disk->d_state == G_MIRROR_DISK_STATE_NEW,
2136		    ("Wrong disk state (%s, %s).", g_mirror_get_diskname(disk),
2137		    g_mirror_disk_state2str(disk->d_state)));
2138		KASSERT(sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
2139		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2140		    g_mirror_device_state2str(sc->sc_state),
2141		    g_mirror_get_diskname(disk),
2142		    g_mirror_disk_state2str(disk->d_state)));
2143		/*
2144		 * STALE state is only possible if device is marked
2145		 * NOAUTOSYNC.
2146		 */
2147		KASSERT((sc->sc_flags & G_MIRROR_DEVICE_FLAG_NOAUTOSYNC) != 0,
2148		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2149		    g_mirror_device_state2str(sc->sc_state),
2150		    g_mirror_get_diskname(disk),
2151		    g_mirror_disk_state2str(disk->d_state)));
2152		DISK_STATE_CHANGED();
2153
2154		disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
2155		disk->d_state = state;
2156		g_mirror_update_metadata(disk);
2157		G_MIRROR_DEBUG(0, "Device %s: provider %s is stale.",
2158		    sc->sc_name, g_mirror_get_diskname(disk));
2159		break;
2160	case G_MIRROR_DISK_STATE_SYNCHRONIZING:
2161		/*
2162		 * Possible scenarios:
2163		 * 1. Disk which needs synchronization was connected.
2164		 */
2165		/* Previous state should be NEW. */
2166		KASSERT(disk->d_state == G_MIRROR_DISK_STATE_NEW,
2167		    ("Wrong disk state (%s, %s).", g_mirror_get_diskname(disk),
2168		    g_mirror_disk_state2str(disk->d_state)));
2169		KASSERT(sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
2170		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2171		    g_mirror_device_state2str(sc->sc_state),
2172		    g_mirror_get_diskname(disk),
2173		    g_mirror_disk_state2str(disk->d_state)));
2174		DISK_STATE_CHANGED();
2175
2176		if (disk->d_state == G_MIRROR_DISK_STATE_NEW)
2177			disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
2178		disk->d_state = state;
2179		if (sc->sc_provider != NULL) {
2180			g_mirror_sync_start(disk);
2181			g_mirror_update_metadata(disk);
2182		}
2183		break;
2184	case G_MIRROR_DISK_STATE_DISCONNECTED:
2185		/*
2186		 * Possible scenarios:
2187		 * 1. Device wasn't running yet, but disk disappear.
2188		 * 2. Disk was active and disapppear.
2189		 * 3. Disk disappear during synchronization process.
2190		 */
2191		if (sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING) {
2192			/*
2193			 * Previous state should be ACTIVE, STALE or
2194			 * SYNCHRONIZING.
2195			 */
2196			KASSERT(disk->d_state == G_MIRROR_DISK_STATE_ACTIVE ||
2197			    disk->d_state == G_MIRROR_DISK_STATE_STALE ||
2198			    disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING,
2199			    ("Wrong disk state (%s, %s).",
2200			    g_mirror_get_diskname(disk),
2201			    g_mirror_disk_state2str(disk->d_state)));
2202		} else if (sc->sc_state == G_MIRROR_DEVICE_STATE_STARTING) {
2203			/* Previous state should be NEW. */
2204			KASSERT(disk->d_state == G_MIRROR_DISK_STATE_NEW,
2205			    ("Wrong disk state (%s, %s).",
2206			    g_mirror_get_diskname(disk),
2207			    g_mirror_disk_state2str(disk->d_state)));
2208			/*
2209			 * Reset bumping syncid if disk disappeared in STARTING
2210			 * state.
2211			 */
2212			if (sc->sc_bump_syncid == G_MIRROR_BUMP_ON_FIRST_WRITE)
2213				sc->sc_bump_syncid = 0;
2214#ifdef	INVARIANTS
2215		} else {
2216			KASSERT(1 == 0, ("Wrong device state (%s, %s, %s, %s).",
2217			    sc->sc_name,
2218			    g_mirror_device_state2str(sc->sc_state),
2219			    g_mirror_get_diskname(disk),
2220			    g_mirror_disk_state2str(disk->d_state)));
2221#endif
2222		}
2223		DISK_STATE_CHANGED();
2224		G_MIRROR_DEBUG(0, "Device %s: provider %s disconnected.",
2225		    sc->sc_name, g_mirror_get_diskname(disk));
2226
2227		g_mirror_destroy_disk(disk);
2228		break;
2229	case G_MIRROR_DISK_STATE_DESTROY:
2230	    {
2231		int error;
2232
2233		error = g_mirror_clear_metadata(disk);
2234		if (error != 0)
2235			return (error);
2236		DISK_STATE_CHANGED();
2237		G_MIRROR_DEBUG(0, "Device %s: provider %s destroyed.",
2238		    sc->sc_name, g_mirror_get_diskname(disk));
2239
2240		g_mirror_destroy_disk(disk);
2241		sc->sc_ndisks--;
2242		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
2243			g_mirror_update_metadata(disk);
2244		}
2245		break;
2246	    }
2247	default:
2248		KASSERT(1 == 0, ("Unknown state (%u).", state));
2249		break;
2250	}
2251	return (0);
2252}
2253#undef	DISK_STATE_CHANGED
2254
2255static int
2256g_mirror_read_metadata(struct g_consumer *cp, struct g_mirror_metadata *md)
2257{
2258	struct g_provider *pp;
2259	u_char *buf;
2260	int error;
2261
2262	g_topology_assert();
2263
2264	error = g_access(cp, 1, 0, 0);
2265	if (error != 0)
2266		return (error);
2267	pp = cp->provider;
2268	g_topology_unlock();
2269	/* Metadata are stored on last sector. */
2270	buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
2271	    &error);
2272	g_topology_lock();
2273	g_access(cp, -1, 0, 0);
2274	if (error != 0) {
2275		if (buf != NULL)
2276			g_free(buf);
2277		return (error);
2278	}
2279
2280	/* Decode metadata. */
2281	error = mirror_metadata_decode(buf, md);
2282	g_free(buf);
2283	if (strcmp(md->md_magic, G_MIRROR_MAGIC) != 0)
2284		return (EINVAL);
2285	if (error != 0) {
2286		G_MIRROR_DEBUG(1, "MD5 metadata hash mismatch for provider %s.",
2287		    cp->provider->name);
2288		return (error);
2289	}
2290
2291	return (0);
2292}
2293
2294static int
2295g_mirror_check_metadata(struct g_mirror_softc *sc, struct g_provider *pp,
2296    struct g_mirror_metadata *md)
2297{
2298
2299	if (g_mirror_id2disk(sc, md->md_did) != NULL) {
2300		G_MIRROR_DEBUG(1, "Disk %s (id=%u) already exists, skipping.",
2301		    pp->name, md->md_did);
2302		return (EEXIST);
2303	}
2304	if (md->md_all != sc->sc_ndisks) {
2305		G_MIRROR_DEBUG(1,
2306		    "Invalid '%s' field on disk %s (device %s), skipping.",
2307		    "md_all", pp->name, sc->sc_name);
2308		return (EINVAL);
2309	}
2310	if (md->md_slice != sc->sc_slice) {
2311		G_MIRROR_DEBUG(1,
2312		    "Invalid '%s' field on disk %s (device %s), skipping.",
2313		    "md_slice", pp->name, sc->sc_name);
2314		return (EINVAL);
2315	}
2316	if (md->md_balance != sc->sc_balance) {
2317		G_MIRROR_DEBUG(1,
2318		    "Invalid '%s' field on disk %s (device %s), skipping.",
2319		    "md_balance", pp->name, sc->sc_name);
2320		return (EINVAL);
2321	}
2322	if (md->md_mediasize != sc->sc_mediasize) {
2323		G_MIRROR_DEBUG(1,
2324		    "Invalid '%s' field on disk %s (device %s), skipping.",
2325		    "md_mediasize", pp->name, sc->sc_name);
2326		return (EINVAL);
2327	}
2328	if (sc->sc_mediasize > pp->mediasize) {
2329		G_MIRROR_DEBUG(1,
2330		    "Invalid size of disk %s (device %s), skipping.", pp->name,
2331		    sc->sc_name);
2332		return (EINVAL);
2333	}
2334	if (md->md_sectorsize != sc->sc_sectorsize) {
2335		G_MIRROR_DEBUG(1,
2336		    "Invalid '%s' field on disk %s (device %s), skipping.",
2337		    "md_sectorsize", pp->name, sc->sc_name);
2338		return (EINVAL);
2339	}
2340	if ((sc->sc_sectorsize % pp->sectorsize) != 0) {
2341		G_MIRROR_DEBUG(1,
2342		    "Invalid sector size of disk %s (device %s), skipping.",
2343		    pp->name, sc->sc_name);
2344		return (EINVAL);
2345	}
2346	if ((md->md_mflags & ~G_MIRROR_DEVICE_FLAG_MASK) != 0) {
2347		G_MIRROR_DEBUG(1,
2348		    "Invalid device flags on disk %s (device %s), skipping.",
2349		    pp->name, sc->sc_name);
2350		return (EINVAL);
2351	}
2352	if ((md->md_dflags & ~G_MIRROR_DISK_FLAG_MASK) != 0) {
2353		G_MIRROR_DEBUG(1,
2354		    "Invalid disk flags on disk %s (device %s), skipping.",
2355		    pp->name, sc->sc_name);
2356		return (EINVAL);
2357	}
2358	return (0);
2359}
2360
2361static int
2362g_mirror_add_disk(struct g_mirror_softc *sc, struct g_provider *pp,
2363    struct g_mirror_metadata *md)
2364{
2365	struct g_mirror_disk *disk;
2366	int error;
2367
2368	g_topology_assert();
2369	G_MIRROR_DEBUG(2, "Adding disk %s.", pp->name);
2370
2371	error = g_mirror_check_metadata(sc, pp, md);
2372	if (error != 0)
2373		return (error);
2374	disk = g_mirror_init_disk(sc, pp, md, &error);
2375	if (disk == NULL)
2376		return (error);
2377	error = g_mirror_event_send(disk, G_MIRROR_DISK_STATE_NEW,
2378	    G_MIRROR_EVENT_WAIT);
2379	return (error);
2380}
2381
2382static int
2383g_mirror_access(struct g_provider *pp, int acr, int acw, int ace)
2384{
2385	struct g_mirror_softc *sc;
2386	struct g_mirror_disk *disk;
2387	int dcr, dcw, dce;
2388
2389	g_topology_assert();
2390	G_MIRROR_DEBUG(2, "Access request for %s: r%dw%de%d.", pp->name, acr,
2391	    acw, ace);
2392
2393	dcr = pp->acr + acr;
2394	dcw = pp->acw + acw;
2395	dce = pp->ace + ace;
2396
2397	sc = pp->geom->softc;
2398	if (sc == NULL || LIST_EMPTY(&sc->sc_disks) ||
2399	    (sc->sc_flags & G_MIRROR_DEVICE_FLAG_DESTROY) != 0) {
2400		if (acr <= 0 && acw <= 0 && ace <= 0)
2401			return (0);
2402		else
2403			return (ENXIO);
2404	}
2405	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
2406		if (disk->d_state != G_MIRROR_DISK_STATE_ACTIVE)
2407			continue;
2408		/*
2409		 * Mark disk as dirty on open and unmark on close.
2410		 */
2411		if (pp->acw == 0 && dcw > 0) {
2412			G_MIRROR_DEBUG(1,
2413			    "Disk %s (device %s) marked as dirty.",
2414			    g_mirror_get_diskname(disk), sc->sc_name);
2415			disk->d_flags |= G_MIRROR_DISK_FLAG_DIRTY;
2416			g_mirror_update_metadata(disk);
2417		} else if (pp->acw > 0 && dcw == 0) {
2418			G_MIRROR_DEBUG(1,
2419			    "Disk %s (device %s) marked as clean.",
2420			    g_mirror_get_diskname(disk), sc->sc_name);
2421			disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
2422			g_mirror_update_metadata(disk);
2423		}
2424	}
2425	return (0);
2426}
2427
2428static struct g_geom *
2429g_mirror_create(struct g_class *mp, const struct g_mirror_metadata *md)
2430{
2431	struct g_mirror_softc *sc;
2432	struct g_geom *gp;
2433	int error, timeout;
2434
2435	g_topology_assert();
2436	G_MIRROR_DEBUG(1, "Creating device %s (id=%u).", md->md_name,
2437	    md->md_mid);
2438
2439	/* One disk is minimum. */
2440	if (md->md_all < 1)
2441		return (NULL);
2442	/*
2443	 * Action geom.
2444	 */
2445	gp = g_new_geomf(mp, "%s", md->md_name);
2446	sc = malloc(sizeof(*sc), M_MIRROR, M_WAITOK | M_ZERO);
2447	gp->start = g_mirror_start;
2448	gp->spoiled = g_mirror_spoiled;
2449	gp->orphan = g_mirror_orphan;
2450	gp->access = g_mirror_access;
2451	gp->dumpconf = g_mirror_dumpconf;
2452
2453	sc->sc_id = md->md_mid;
2454	sc->sc_slice = md->md_slice;
2455	sc->sc_balance = md->md_balance;
2456	sc->sc_mediasize = md->md_mediasize;
2457	sc->sc_sectorsize = md->md_sectorsize;
2458	sc->sc_ndisks = md->md_all;
2459	sc->sc_flags = md->md_mflags;
2460	sc->sc_bump_syncid = 0;
2461	sc->sc_idle = 0;
2462	bioq_init(&sc->sc_queue);
2463	mtx_init(&sc->sc_queue_mtx, "gmirror:queue", NULL, MTX_DEF);
2464	LIST_INIT(&sc->sc_disks);
2465	TAILQ_INIT(&sc->sc_events);
2466	mtx_init(&sc->sc_events_mtx, "gmirror:events", NULL, MTX_DEF);
2467	callout_init(&sc->sc_callout, CALLOUT_MPSAFE);
2468	sc->sc_state = G_MIRROR_DEVICE_STATE_STARTING;
2469	gp->softc = sc;
2470	sc->sc_geom = gp;
2471	sc->sc_provider = NULL;
2472	/*
2473	 * Synchronization geom.
2474	 */
2475	gp = g_new_geomf(mp, "%s.sync", md->md_name);
2476	gp->softc = sc;
2477	gp->orphan = g_mirror_orphan;
2478	sc->sc_sync.ds_geom = gp;
2479	sc->sc_sync.ds_ndisks = 0;
2480	error = kthread_create(g_mirror_worker, sc, &sc->sc_worker, 0, 0,
2481	    "g_mirror %s", md->md_name);
2482	if (error != 0) {
2483		G_MIRROR_DEBUG(1, "Cannot create kernel thread for %s.",
2484		    sc->sc_name);
2485		g_destroy_geom(sc->sc_sync.ds_geom);
2486		mtx_destroy(&sc->sc_events_mtx);
2487		mtx_destroy(&sc->sc_queue_mtx);
2488		g_destroy_geom(sc->sc_geom);
2489		free(sc, M_MIRROR);
2490		return (NULL);
2491	}
2492
2493	G_MIRROR_DEBUG(0, "Device %s created (id=%u).", sc->sc_name, sc->sc_id);
2494
2495	/*
2496	 * Run timeout.
2497	 */
2498	timeout = g_mirror_timeout * hz;
2499	callout_reset(&sc->sc_callout, timeout, g_mirror_go, sc);
2500	return (sc->sc_geom);
2501}
2502
2503int
2504g_mirror_destroy(struct g_mirror_softc *sc, boolean_t force)
2505{
2506	struct g_provider *pp;
2507
2508	g_topology_assert();
2509
2510	if (sc == NULL)
2511		return (ENXIO);
2512	pp = sc->sc_provider;
2513	if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
2514		if (force) {
2515			G_MIRROR_DEBUG(0, "Device %s is still open, so it "
2516			    "can't be definitely removed.", pp->name);
2517		} else {
2518			G_MIRROR_DEBUG(1,
2519			    "Device %s is still open (r%dw%de%d).", pp->name,
2520			    pp->acr, pp->acw, pp->ace);
2521			return (EBUSY);
2522		}
2523	}
2524
2525	sc->sc_flags |= G_MIRROR_DEVICE_FLAG_DESTROY;
2526	sc->sc_flags |= G_MIRROR_DEVICE_FLAG_WAIT;
2527	g_topology_unlock();
2528	G_MIRROR_DEBUG(4, "%s: Waking up %p.", __func__, sc);
2529	mtx_lock(&sc->sc_queue_mtx);
2530	wakeup(sc);
2531	mtx_unlock(&sc->sc_queue_mtx);
2532	G_MIRROR_DEBUG(4, "%s: Sleeping %p.", __func__, &sc->sc_worker);
2533	while (sc->sc_worker != NULL)
2534		tsleep(&sc->sc_worker, PRIBIO, "m:destroy", hz / 5);
2535	G_MIRROR_DEBUG(4, "%s: Woken up %p.", __func__, &sc->sc_worker);
2536	g_topology_lock();
2537	g_mirror_destroy_device(sc);
2538	free(sc, M_MIRROR);
2539	return (0);
2540}
2541
2542static void
2543g_mirror_taste_orphan(struct g_consumer *cp)
2544{
2545
2546	KASSERT(1 == 0, ("%s called while tasting %s.", __func__,
2547	    cp->provider->name));
2548}
2549
2550static struct g_geom *
2551g_mirror_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
2552{
2553	struct g_mirror_metadata md;
2554	struct g_mirror_softc *sc;
2555	struct g_consumer *cp;
2556	struct g_geom *gp;
2557	int error;
2558
2559	g_topology_assert();
2560	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
2561	G_MIRROR_DEBUG(2, "Tasting %s.", pp->name);
2562
2563	gp = g_new_geomf(mp, "mirror:taste");
2564	/*
2565	 * This orphan function should be never called.
2566	 */
2567	gp->orphan = g_mirror_taste_orphan;
2568	cp = g_new_consumer(gp);
2569	g_attach(cp, pp);
2570	error = g_mirror_read_metadata(cp, &md);
2571	g_detach(cp);
2572	g_destroy_consumer(cp);
2573	g_destroy_geom(gp);
2574	if (error != 0)
2575		return (NULL);
2576	gp = NULL;
2577
2578	if (md.md_version > G_MIRROR_VERSION) {
2579		printf("geom_mirror.ko module is too old to handle %s.\n",
2580		    pp->name);
2581		return (NULL);
2582	}
2583	if (md.md_provider[0] != '\0' && strcmp(md.md_provider, pp->name) != 0)
2584		return (NULL);
2585	if ((md.md_dflags & G_MIRROR_DISK_FLAG_INACTIVE) != 0) {
2586		G_MIRROR_DEBUG(0,
2587		    "Device %s: provider %s marked as inactive, skipping.",
2588		    md.md_name, pp->name);
2589		return (NULL);
2590	}
2591	if (g_mirror_debug >= 2)
2592		mirror_metadata_dump(&md);
2593
2594	/*
2595	 * Let's check if device already exists.
2596	 */
2597	sc = NULL;
2598	LIST_FOREACH(gp, &mp->geom, geom) {
2599		sc = gp->softc;
2600		if (sc == NULL)
2601			continue;
2602		if (sc->sc_sync.ds_geom == gp)
2603			continue;
2604		if (strcmp(md.md_name, sc->sc_name) != 0)
2605			continue;
2606		if (md.md_mid != sc->sc_id) {
2607			G_MIRROR_DEBUG(0, "Device %s already configured.",
2608			    sc->sc_name);
2609			return (NULL);
2610		}
2611		break;
2612	}
2613	if (gp == NULL) {
2614		gp = g_mirror_create(mp, &md);
2615		if (gp == NULL) {
2616			G_MIRROR_DEBUG(0, "Cannot create device %s.",
2617			    md.md_name);
2618			return (NULL);
2619		}
2620		sc = gp->softc;
2621	}
2622	G_MIRROR_DEBUG(1, "Adding disk %s to %s.", pp->name, gp->name);
2623	error = g_mirror_add_disk(sc, pp, &md);
2624	if (error != 0) {
2625		G_MIRROR_DEBUG(0, "Cannot add disk %s to %s (error=%d).",
2626		    pp->name, gp->name, error);
2627		if (LIST_EMPTY(&sc->sc_disks))
2628			g_mirror_destroy(sc, 1);
2629		return (NULL);
2630	}
2631	return (gp);
2632}
2633
2634static int
2635g_mirror_destroy_geom(struct gctl_req *req __unused,
2636    struct g_class *mp __unused, struct g_geom *gp)
2637{
2638
2639	return (g_mirror_destroy(gp->softc, 0));
2640}
2641
2642static void
2643g_mirror_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
2644    struct g_consumer *cp, struct g_provider *pp)
2645{
2646	struct g_mirror_softc *sc;
2647
2648	g_topology_assert();
2649
2650	sc = gp->softc;
2651	if (sc == NULL)
2652		return;
2653	/* Skip synchronization geom. */
2654	if (gp == sc->sc_sync.ds_geom)
2655		return;
2656	if (pp != NULL) {
2657		/* Nothing here. */
2658	} else if (cp != NULL) {
2659		struct g_mirror_disk *disk;
2660
2661		disk = cp->private;
2662		if (disk == NULL)
2663			return;
2664		sbuf_printf(sb, "%s<ID>%u</ID>\n", indent, (u_int)disk->d_id);
2665		if (disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING) {
2666			sbuf_printf(sb, "%s<Synchronized>", indent);
2667			if (disk->d_sync.ds_offset_done == 0)
2668				sbuf_printf(sb, "0%%");
2669			else {
2670				sbuf_printf(sb, "%u%%",
2671				    (u_int)((disk->d_sync.ds_offset_done * 100) /
2672				    sc->sc_provider->mediasize));
2673			}
2674			sbuf_printf(sb, "</Synchronized>\n");
2675		}
2676		sbuf_printf(sb, "%s<SyncID>%u</SyncID>\n", indent,
2677		    disk->d_sync.ds_syncid);
2678		sbuf_printf(sb, "%s<Flags>", indent);
2679		if (disk->d_flags == 0)
2680			sbuf_printf(sb, "NONE");
2681		else {
2682			int first = 1;
2683
2684#define	ADD_FLAG(flag, name)	do {					\
2685	if ((disk->d_flags & (flag)) != 0) {				\
2686		if (!first)						\
2687			sbuf_printf(sb, ", ");				\
2688		else							\
2689			first = 0;					\
2690		sbuf_printf(sb, name);					\
2691	}								\
2692} while (0)
2693			ADD_FLAG(G_MIRROR_DISK_FLAG_DIRTY, "DIRTY");
2694			ADD_FLAG(G_MIRROR_DISK_FLAG_HARDCODED, "HARDCODED");
2695			ADD_FLAG(G_MIRROR_DISK_FLAG_INACTIVE, "INACTIVE");
2696			ADD_FLAG(G_MIRROR_DISK_FLAG_SYNCHRONIZING,
2697			    "SYNCHRONIZING");
2698			ADD_FLAG(G_MIRROR_DISK_FLAG_FORCE_SYNC, "FORCE_SYNC");
2699#undef	ADD_FLAG
2700		}
2701		sbuf_printf(sb, "</Flags>\n");
2702		sbuf_printf(sb, "%s<Priority>%u</Priority>\n", indent,
2703		    disk->d_priority);
2704		sbuf_printf(sb, "%s<State>%s</State>\n", indent,
2705		    g_mirror_disk_state2str(disk->d_state));
2706	} else {
2707		sbuf_printf(sb, "%s<ID>%u</ID>\n", indent, (u_int)sc->sc_id);
2708		sbuf_printf(sb, "%s<SyncID>%u</SyncID>\n", indent, sc->sc_syncid);
2709		sbuf_printf(sb, "%s<Flags>", indent);
2710		if (sc->sc_flags == 0)
2711			sbuf_printf(sb, "NONE");
2712		else {
2713			int first = 1;
2714
2715#define	ADD_FLAG(flag, name)	do {					\
2716	if ((sc->sc_flags & (flag)) != 0) {				\
2717		if (!first)						\
2718			sbuf_printf(sb, ", ");				\
2719		else							\
2720			first = 0;					\
2721		sbuf_printf(sb, name);					\
2722	}								\
2723} while (0)
2724			ADD_FLAG(G_MIRROR_DEVICE_FLAG_NOAUTOSYNC, "NOAUTOSYNC");
2725#undef	ADD_FLAG
2726		}
2727		sbuf_printf(sb, "</Flags>\n");
2728		sbuf_printf(sb, "%s<Slice>%u</Slice>\n", indent,
2729		    (u_int)sc->sc_slice);
2730		sbuf_printf(sb, "%s<Balance>%s</Balance>\n", indent,
2731		    balance_name(sc->sc_balance));
2732		sbuf_printf(sb, "%s<Components>%u</Components>\n", indent,
2733		    sc->sc_ndisks);
2734		sbuf_printf(sb, "%s<State>", indent);
2735		if (sc->sc_state == G_MIRROR_DEVICE_STATE_STARTING)
2736			sbuf_printf(sb, "%s", "STARTING");
2737		else if (sc->sc_ndisks ==
2738		    g_mirror_ndisks(sc, G_MIRROR_DISK_STATE_ACTIVE))
2739			sbuf_printf(sb, "%s", "COMPLETE");
2740		else
2741			sbuf_printf(sb, "%s", "DEGRADED");
2742		sbuf_printf(sb, "</State>\n");
2743	}
2744}
2745
2746static void
2747g_mirror_shutdown(void *arg, int howto)
2748{
2749	struct g_class *mp;
2750	struct g_geom *gp, *gp2;
2751
2752	mp = arg;
2753	DROP_GIANT();
2754	g_topology_lock();
2755	LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
2756		if (gp->softc == NULL)
2757			continue;
2758		g_mirror_destroy(gp->softc, 1);
2759	}
2760	g_topology_unlock();
2761	PICKUP_GIANT();
2762#if 0
2763	tsleep(&gp, PRIBIO, "m:shutdown", hz * 20);
2764#endif
2765}
2766
2767static void
2768g_mirror_init(struct g_class *mp)
2769{
2770
2771	g_mirror_ehtag = EVENTHANDLER_REGISTER(shutdown_post_sync,
2772	    g_mirror_shutdown, mp, SHUTDOWN_PRI_FIRST);
2773	if (g_mirror_ehtag == NULL)
2774		G_MIRROR_DEBUG(0, "Warning! Cannot register shutdown event.");
2775}
2776
2777static void
2778g_mirror_fini(struct g_class *mp)
2779{
2780
2781	if (g_mirror_ehtag == NULL)
2782		return;
2783	EVENTHANDLER_DEREGISTER(shutdown_post_sync, g_mirror_ehtag);
2784}
2785
2786static int
2787g_mirror_can_go(void)
2788{
2789	struct g_mirror_softc *sc;
2790	struct g_geom *gp;
2791	struct g_provider *pp;
2792	int can_go;
2793
2794	DROP_GIANT();
2795	can_go = 1;
2796	g_topology_lock();
2797	LIST_FOREACH(gp, &g_mirror_class.geom, geom) {
2798		sc = gp->softc;
2799		if (sc == NULL) {
2800			can_go = 0;
2801			break;
2802		}
2803		pp = sc->sc_provider;
2804		if (pp == NULL || pp->error != 0) {
2805			can_go = 0;
2806			break;
2807		}
2808	}
2809	g_topology_unlock();
2810	PICKUP_GIANT();
2811	return (can_go);
2812}
2813
2814static void
2815g_mirror_rootwait(void)
2816{
2817
2818	/*
2819	 * HACK: Wait for GEOM, because g_mirror_rootwait() can be called,
2820	 * HACK: before we get providers for tasting.
2821	 */
2822	tsleep(&g_mirror_class, PRIBIO, "mroot", hz * 3);
2823	/*
2824	 * Wait for mirrors in degraded state.
2825	 */
2826	for (;;) {
2827		if (g_mirror_can_go())
2828			break;
2829		tsleep(&g_mirror_class, PRIBIO, "mroot", hz);
2830	}
2831}
2832
2833SYSINIT(g_mirror_root, SI_SUB_RAID, SI_ORDER_FIRST, g_mirror_rootwait, NULL)
2834
2835DECLARE_GEOM_CLASS(g_mirror_class, g_mirror);
2836