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