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