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