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