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