g_mirror.c revision 133173
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 133173 2004-08-05 14:07:21Z 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		disk->d_sync.ds_offset_done = bp->bio_offset + bp->bio_length;
988		g_destroy_bio(bp);
989		if (disk->d_sync.ds_offset_done == sc->sc_provider->mediasize) {
990			/*
991			 * Disk up-to-date, activate it.
992			 */
993			g_mirror_event_send(disk, G_MIRROR_DISK_STATE_ACTIVE,
994			    G_MIRROR_EVENT_DONTWAIT);
995			return;
996		} else if ((disk->d_sync.ds_offset_done %
997		    (sc->sc_sync.ds_block * 100)) == 0) {
998			/*
999			 * Update offset_done on every 100 blocks.
1000			 * XXX: This should be configurable.
1001			 */
1002			g_topology_lock();
1003			g_mirror_update_metadata(disk);
1004			g_topology_unlock();
1005		}
1006		return;
1007	default:
1008		KASSERT(1 == 0, ("Invalid command here: %u (device=%s)",
1009		    bp->bio_cmd, sc->sc_name));
1010		break;
1011	}
1012}
1013
1014static void
1015g_mirror_request_prefer(struct g_mirror_softc *sc, struct bio *bp)
1016{
1017	struct g_mirror_disk *disk;
1018	struct g_consumer *cp;
1019	struct bio *cbp;
1020
1021	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1022		if (disk->d_state == G_MIRROR_DISK_STATE_ACTIVE)
1023			break;
1024	}
1025	if (disk == NULL) {
1026		if (bp->bio_error == 0)
1027			bp->bio_error = ENXIO;
1028		g_io_deliver(bp, bp->bio_error);
1029		return;
1030	}
1031	cbp = g_clone_bio(bp);
1032	if (cbp == NULL) {
1033		if (bp->bio_error == 0)
1034			bp->bio_error = ENOMEM;
1035		g_io_deliver(bp, bp->bio_error);
1036		return;
1037	}
1038	/*
1039	 * Fill in the component buf structure.
1040	 */
1041	cp = disk->d_consumer;
1042	cbp->bio_done = g_mirror_done;
1043	cbp->bio_to = cp->provider;
1044	G_MIRROR_LOGREQ(3, cbp, "Sending request.");
1045	KASSERT(cp->acr > 0 && cp->ace > 0,
1046	    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name, cp->acr,
1047	    cp->acw, cp->ace));
1048	g_io_request(cbp, cp);
1049}
1050
1051static void
1052g_mirror_request_round_robin(struct g_mirror_softc *sc, struct bio *bp)
1053{
1054	struct g_mirror_disk *disk;
1055	struct g_consumer *cp;
1056	struct bio *cbp;
1057
1058	disk = g_mirror_get_disk(sc);
1059	if (disk == NULL) {
1060		if (bp->bio_error == 0)
1061			bp->bio_error = ENXIO;
1062		g_io_deliver(bp, bp->bio_error);
1063		return;
1064	}
1065	cbp = g_clone_bio(bp);
1066	if (cbp == NULL) {
1067		if (bp->bio_error == 0)
1068			bp->bio_error = ENOMEM;
1069		g_io_deliver(bp, bp->bio_error);
1070		return;
1071	}
1072	/*
1073	 * Fill in the component buf structure.
1074	 */
1075	cp = disk->d_consumer;
1076	cbp->bio_done = g_mirror_done;
1077	cbp->bio_to = cp->provider;
1078	G_MIRROR_LOGREQ(3, cbp, "Sending request.");
1079	KASSERT(cp->acr > 0 && cp->ace > 0,
1080	    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name, cp->acr,
1081	    cp->acw, cp->ace));
1082	g_io_request(cbp, cp);
1083}
1084
1085static void
1086g_mirror_request_load(struct g_mirror_softc *sc, struct bio *bp)
1087{
1088	struct g_mirror_disk *disk, *dp;
1089	struct g_consumer *cp;
1090	struct bio *cbp;
1091	struct bintime curtime;
1092
1093	binuptime(&curtime);
1094	/*
1095	 * Find a disk which the smallest load.
1096	 */
1097	disk = NULL;
1098	LIST_FOREACH(dp, &sc->sc_disks, d_next) {
1099		if (dp->d_state != G_MIRROR_DISK_STATE_ACTIVE)
1100			continue;
1101		/* If disk wasn't used for more than 2 sec, use it. */
1102		if (curtime.sec - dp->d_last_used.sec >= 2) {
1103			disk = dp;
1104			break;
1105		}
1106		if (disk == NULL ||
1107		    bintime_cmp(&dp->d_delay, &disk->d_delay) < 0) {
1108			disk = dp;
1109		}
1110	}
1111	cbp = g_clone_bio(bp);
1112	if (cbp == NULL) {
1113		if (bp->bio_error == 0)
1114			bp->bio_error = ENOMEM;
1115		g_io_deliver(bp, bp->bio_error);
1116		return;
1117	}
1118	/*
1119	 * Fill in the component buf structure.
1120	 */
1121	cp = disk->d_consumer;
1122	cbp->bio_done = g_mirror_done;
1123	cbp->bio_to = cp->provider;
1124	binuptime(&disk->d_last_used);
1125	G_MIRROR_LOGREQ(3, cbp, "Sending request.");
1126	KASSERT(cp->acr > 0 && cp->ace > 0,
1127	    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name, cp->acr,
1128	    cp->acw, cp->ace));
1129	g_io_request(cbp, cp);
1130}
1131
1132static void
1133g_mirror_request_split(struct g_mirror_softc *sc, struct bio *bp)
1134{
1135	struct bio_queue_head queue;
1136	struct g_mirror_disk *disk;
1137	struct g_consumer *cp;
1138	struct bio *cbp;
1139	off_t left, mod, offset, slice;
1140	u_char *data;
1141	u_int ndisks;
1142
1143	if (bp->bio_length <= sc->sc_slice) {
1144		g_mirror_request_round_robin(sc, bp);
1145		return;
1146	}
1147	ndisks = g_mirror_ndisks(sc, G_MIRROR_DISK_STATE_ACTIVE);
1148	slice = bp->bio_length / ndisks;
1149	mod = slice % sc->sc_provider->sectorsize;
1150	if (mod != 0)
1151		slice += sc->sc_provider->sectorsize - mod;
1152	/*
1153	 * Allocate all bios before sending any request, so we can
1154	 * return ENOMEM in nice and clean way.
1155	 */
1156	left = bp->bio_length;
1157	offset = bp->bio_offset;
1158	data = bp->bio_data;
1159	bioq_init(&queue);
1160	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1161		if (disk->d_state != G_MIRROR_DISK_STATE_ACTIVE)
1162			continue;
1163		cbp = g_clone_bio(bp);
1164		if (cbp == NULL) {
1165			for (cbp = bioq_first(&queue); cbp != NULL;
1166			    cbp = bioq_first(&queue)) {
1167				bioq_remove(&queue, cbp);
1168				g_destroy_bio(cbp);
1169			}
1170			if (bp->bio_error == 0)
1171				bp->bio_error = ENOMEM;
1172			g_io_deliver(bp, bp->bio_error);
1173			return;
1174		}
1175		bioq_insert_tail(&queue, cbp);
1176		cbp->bio_done = g_mirror_done;
1177		cbp->bio_caller1 = disk;
1178		cbp->bio_to = disk->d_consumer->provider;
1179		cbp->bio_offset = offset;
1180		cbp->bio_data = data;
1181		cbp->bio_length = MIN(left, slice);
1182		left -= cbp->bio_length;
1183		if (left == 0)
1184			break;
1185		offset += cbp->bio_length;
1186		data += cbp->bio_length;
1187	}
1188	for (cbp = bioq_first(&queue); cbp != NULL; cbp = bioq_first(&queue)) {
1189		bioq_remove(&queue, cbp);
1190		G_MIRROR_LOGREQ(3, cbp, "Sending request.");
1191		disk = cbp->bio_caller1;
1192		cbp->bio_caller1 = NULL;
1193		cp = disk->d_consumer;
1194		KASSERT(cp->acr > 0 && cp->ace > 0,
1195		    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name,
1196		    cp->acr, cp->acw, cp->ace));
1197		g_io_request(cbp, disk->d_consumer);
1198	}
1199}
1200
1201static void
1202g_mirror_register_request(struct bio *bp)
1203{
1204	struct g_mirror_softc *sc;
1205
1206	sc = bp->bio_to->geom->softc;
1207	switch (bp->bio_cmd) {
1208	case BIO_READ:
1209		switch (sc->sc_balance) {
1210		case G_MIRROR_BALANCE_LOAD:
1211			g_mirror_request_load(sc, bp);
1212			break;
1213		case G_MIRROR_BALANCE_PREFER:
1214			g_mirror_request_prefer(sc, bp);
1215			break;
1216		case G_MIRROR_BALANCE_ROUND_ROBIN:
1217			g_mirror_request_round_robin(sc, bp);
1218			break;
1219		case G_MIRROR_BALANCE_SPLIT:
1220			g_mirror_request_split(sc, bp);
1221			break;
1222		}
1223		return;
1224	case BIO_WRITE:
1225	case BIO_DELETE:
1226	    {
1227		struct g_mirror_disk *disk;
1228		struct bio_queue_head queue;
1229		struct g_consumer *cp;
1230		struct bio *cbp;
1231
1232		/*
1233		 * Allocate all bios before sending any request, so we can
1234		 * return ENOMEM in nice and clean way.
1235		 */
1236		bioq_init(&queue);
1237		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1238			switch (disk->d_state) {
1239			case G_MIRROR_DISK_STATE_ACTIVE:
1240				break;
1241			case G_MIRROR_DISK_STATE_SYNCHRONIZING:
1242				if (bp->bio_offset >= disk->d_sync.ds_offset)
1243					continue;
1244				break;
1245			default:
1246				continue;
1247			}
1248			cbp = g_clone_bio(bp);
1249			if (cbp == NULL) {
1250				for (cbp = bioq_first(&queue); cbp != NULL;
1251				    cbp = bioq_first(&queue)) {
1252					bioq_remove(&queue, cbp);
1253					g_destroy_bio(cbp);
1254				}
1255				if (bp->bio_error == 0)
1256					bp->bio_error = ENOMEM;
1257				g_io_deliver(bp, bp->bio_error);
1258				return;
1259			}
1260			bioq_insert_tail(&queue, cbp);
1261		}
1262		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1263			switch (disk->d_state) {
1264			case G_MIRROR_DISK_STATE_ACTIVE:
1265				break;
1266			case G_MIRROR_DISK_STATE_SYNCHRONIZING:
1267				if (bp->bio_offset >= disk->d_sync.ds_offset)
1268					continue;
1269				break;
1270			default:
1271				continue;
1272			}
1273			cbp = bioq_first(&queue);
1274			KASSERT(cbp != NULL, ("NULL cbp! (device %s).",
1275			    sc->sc_name));
1276			bioq_remove(&queue, cbp);
1277			cp = disk->d_consumer;
1278			cbp->bio_done = g_mirror_done;
1279			cbp->bio_to = cp->provider;
1280			G_MIRROR_LOGREQ(3, cbp, "Sending request.");
1281			KASSERT(cp->acw > 0 && cp->ace > 0,
1282			    ("Consumer %s not opened (r%dw%de%d).",
1283			    cp->provider->name, cp->acr, cp->acw, cp->ace));
1284			g_io_request(cbp, cp);
1285		}
1286		/*
1287		 * Bump syncid on first write.
1288		 */
1289		if (sc->sc_bump_syncid == G_MIRROR_BUMP_ON_FIRST_WRITE) {
1290			sc->sc_bump_syncid = 0;
1291			g_topology_lock();
1292			g_mirror_bump_syncid(sc);
1293			g_topology_unlock();
1294		}
1295		return;
1296	    }
1297	default:
1298		KASSERT(1 == 0, ("Invalid command here: %u (device=%s)",
1299		    bp->bio_cmd, sc->sc_name));
1300		break;
1301	}
1302}
1303
1304/*
1305 * Worker thread.
1306 */
1307static void
1308g_mirror_worker(void *arg)
1309{
1310	struct g_mirror_softc *sc;
1311	struct g_mirror_disk *disk;
1312	struct g_mirror_event *ep;
1313	struct bio *bp;
1314	u_int nreqs;
1315
1316	sc = arg;
1317	curthread->td_base_pri = PRIBIO;
1318
1319	nreqs = 0;
1320	for (;;) {
1321		G_MIRROR_DEBUG(5, "%s: Let's see...", __func__);
1322		/*
1323		 * First take a look at events.
1324		 * This is important to handle events before any I/O requests.
1325		 */
1326		ep = g_mirror_event_get(sc);
1327		if (ep != NULL) {
1328			g_topology_lock();
1329			if ((ep->e_flags & G_MIRROR_EVENT_DEVICE) != 0) {
1330				/* Update only device status. */
1331				G_MIRROR_DEBUG(3,
1332				    "Running event for device %s.",
1333				    sc->sc_name);
1334				ep->e_error = 0;
1335				g_mirror_update_device(sc, 1);
1336			} else {
1337				/* Update disk status. */
1338				G_MIRROR_DEBUG(3, "Running event for disk %s.",
1339				     g_mirror_get_diskname(ep->e_disk));
1340				ep->e_error = g_mirror_update_disk(ep->e_disk,
1341				    ep->e_state);
1342				if (ep->e_error == 0)
1343					g_mirror_update_device(sc, 0);
1344			}
1345			g_topology_unlock();
1346			if ((ep->e_flags & G_MIRROR_EVENT_DONTWAIT) != 0) {
1347				KASSERT(ep->e_error == 0,
1348				    ("Error cannot be handled."));
1349				g_mirror_event_free(ep);
1350			} else {
1351				ep->e_flags |= G_MIRROR_EVENT_DONE;
1352				G_MIRROR_DEBUG(4, "%s: Waking up %p.", __func__,
1353				    ep);
1354				mtx_lock(&sc->sc_events_mtx);
1355				wakeup(ep);
1356				mtx_unlock(&sc->sc_events_mtx);
1357			}
1358			if ((sc->sc_flags &
1359			    G_MIRROR_DEVICE_FLAG_DESTROY) != 0) {
1360end:
1361				if ((sc->sc_flags &
1362				    G_MIRROR_DEVICE_FLAG_WAIT) != 0) {
1363					G_MIRROR_DEBUG(4, "%s: Waking up %p.",
1364					    __func__, &sc->sc_worker);
1365					wakeup(&sc->sc_worker);
1366					sc->sc_worker = NULL;
1367				} else {
1368					g_topology_lock();
1369					g_mirror_destroy_device(sc);
1370					g_topology_unlock();
1371					free(sc, M_MIRROR);
1372				}
1373				kthread_exit(0);
1374			}
1375			G_MIRROR_DEBUG(5, "%s: I'm here 1.", __func__);
1376			continue;
1377		}
1378		/*
1379		 * Now I/O requests.
1380		 */
1381		/* Get first request from the queue. */
1382		mtx_lock(&sc->sc_queue_mtx);
1383		bp = bioq_first(&sc->sc_queue);
1384		if (bp == NULL) {
1385			if ((sc->sc_flags &
1386			    G_MIRROR_DEVICE_FLAG_DESTROY) != 0) {
1387				mtx_unlock(&sc->sc_queue_mtx);
1388				goto end;
1389			}
1390		}
1391		if (sc->sc_sync.ds_ndisks > 0 &&
1392		    (bp == NULL || nreqs > g_mirror_reqs_per_sync)) {
1393			mtx_unlock(&sc->sc_queue_mtx);
1394			/*
1395			 * It is time for synchronization...
1396			 */
1397			nreqs = 0;
1398			LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1399				if (disk->d_state !=
1400				    G_MIRROR_DISK_STATE_SYNCHRONIZING) {
1401					continue;
1402				}
1403				if (disk->d_sync.ds_offset >=
1404				    sc->sc_provider->mediasize) {
1405					continue;
1406				}
1407				if (disk->d_sync.ds_offset >
1408				    disk->d_sync.ds_offset_done) {
1409					continue;
1410				}
1411				g_mirror_sync_one(disk);
1412			}
1413			G_MIRROR_DEBUG(5, "%s: I'm here 2.", __func__);
1414			goto sleep;
1415		}
1416		if (bp == NULL) {
1417			MSLEEP(sc, &sc->sc_queue_mtx, PRIBIO | PDROP, "m:w1", 0);
1418			G_MIRROR_DEBUG(5, "%s: I'm here 3.", __func__);
1419			continue;
1420		}
1421		nreqs++;
1422		bioq_remove(&sc->sc_queue, bp);
1423		mtx_unlock(&sc->sc_queue_mtx);
1424
1425		if ((bp->bio_cflags & G_MIRROR_BIO_FLAG_REGULAR) != 0) {
1426			g_mirror_regular_request(bp);
1427		} else if ((bp->bio_cflags & G_MIRROR_BIO_FLAG_SYNC) != 0) {
1428			u_int timeout, sps;
1429
1430			g_mirror_sync_request(bp);
1431sleep:
1432			sps = atomic_load_acq_int(&g_mirror_syncs_per_sec);
1433			if (sps == 0) {
1434				G_MIRROR_DEBUG(5, "%s: I'm here 5.", __func__);
1435				continue;
1436			}
1437			mtx_lock(&sc->sc_queue_mtx);
1438			if (bioq_first(&sc->sc_queue) != NULL) {
1439				mtx_unlock(&sc->sc_queue_mtx);
1440				G_MIRROR_DEBUG(5, "%s: I'm here 4.", __func__);
1441				continue;
1442			}
1443			timeout = hz / sps;
1444			if (timeout == 0)
1445				timeout = 1;
1446			MSLEEP(sc, &sc->sc_queue_mtx, PRIBIO | PDROP, "m:w2",
1447			    timeout);
1448		} else {
1449			g_mirror_register_request(bp);
1450		}
1451		G_MIRROR_DEBUG(5, "%s: I'm here 6.", __func__);
1452	}
1453}
1454
1455/*
1456 * Open disk's consumer if needed.
1457 */
1458static void
1459g_mirror_update_access(struct g_mirror_disk *disk)
1460{
1461	struct g_provider *pp;
1462	struct g_consumer *cp;
1463	int acr, acw, ace, cpw, error;
1464
1465	g_topology_assert();
1466
1467	cp = disk->d_consumer;
1468	pp = disk->d_softc->sc_provider;
1469	if (pp == NULL) {
1470		acr = -cp->acr;
1471		acw = -cp->acw;
1472		ace = -cp->ace;
1473	} else {
1474		acr = pp->acr - cp->acr;
1475		acw = pp->acw - cp->acw;
1476		ace = pp->ace - cp->ace;
1477		/* Grab an extra "exclusive" bit. */
1478		if (pp->acr > 0 || pp->acw > 0 || pp->ace > 0)
1479			ace++;
1480	}
1481	if (acr == 0 && acw == 0 && ace == 0)
1482		return;
1483	cpw = cp->acw;
1484	error = g_access(cp, acr, acw, ace);
1485	G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d", cp->provider->name, acr,
1486	    acw, ace, error);
1487	if (error != 0) {
1488		disk->d_softc->sc_bump_syncid = G_MIRROR_BUMP_ON_FIRST_WRITE;
1489		g_mirror_event_send(disk, G_MIRROR_DISK_STATE_DISCONNECTED,
1490		    G_MIRROR_EVENT_DONTWAIT);
1491		return;
1492	}
1493	if (cpw == 0 && cp->acw > 0) {
1494		G_MIRROR_DEBUG(1, "Disk %s (device %s) marked as dirty.",
1495		    g_mirror_get_diskname(disk), disk->d_softc->sc_name);
1496		disk->d_flags |= G_MIRROR_DISK_FLAG_DIRTY;
1497	} else if (cpw > 0 && cp->acw == 0) {
1498		G_MIRROR_DEBUG(1, "Disk %s (device %s) marked as clean.",
1499		    g_mirror_get_diskname(disk), disk->d_softc->sc_name);
1500		disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
1501	}
1502}
1503
1504static void
1505g_mirror_sync_start(struct g_mirror_disk *disk)
1506{
1507	struct g_mirror_softc *sc;
1508	struct g_consumer *cp;
1509	int error;
1510
1511	g_topology_assert();
1512
1513	sc = disk->d_softc;
1514	KASSERT(sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
1515	    ("Device not in RUNNING state (%s, %u).", sc->sc_name,
1516	    sc->sc_state));
1517	cp = disk->d_consumer;
1518	KASSERT(cp->acr == 0 && cp->acw == 0 && cp->ace == 0,
1519	    ("Consumer %s already opened.", cp->provider->name));
1520
1521	G_MIRROR_DEBUG(0, "Device %s: rebuilding provider %s.", sc->sc_name,
1522	    g_mirror_get_diskname(disk));
1523	error = g_access(cp, 0, 1, 1);
1524	G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d", cp->provider->name, 0, 1,
1525	    1, error);
1526	if (error != 0) {
1527		g_mirror_event_send(disk, G_MIRROR_DISK_STATE_DISCONNECTED,
1528		    G_MIRROR_EVENT_DONTWAIT);
1529		return;
1530	}
1531	disk->d_flags |= G_MIRROR_DISK_FLAG_DIRTY;
1532	KASSERT(disk->d_sync.ds_consumer == NULL,
1533	    ("Sync consumer already exists (device=%s, disk=%s).",
1534	    sc->sc_name, g_mirror_get_diskname(disk)));
1535	disk->d_sync.ds_consumer = g_new_consumer(sc->sc_sync.ds_geom);
1536	disk->d_sync.ds_consumer->private = disk;
1537	error = g_attach(disk->d_sync.ds_consumer, disk->d_softc->sc_provider);
1538	KASSERT(error == 0, ("Cannot attach to %s (error=%d).",
1539	    disk->d_softc->sc_name, error));
1540	error = g_access(disk->d_sync.ds_consumer, 1, 0, 0);
1541	KASSERT(error == 0, ("Cannot open %s (error=%d).",
1542	    disk->d_softc->sc_name, error));
1543	sc->sc_sync.ds_ndisks++;
1544}
1545
1546/*
1547 * Stop synchronization process.
1548 * type: 0 - synchronization finished
1549 *       1 - synchronization stopped
1550 */
1551static void
1552g_mirror_sync_stop(struct g_mirror_disk *disk, int type)
1553{
1554	struct g_consumer *cp;
1555
1556	g_topology_assert();
1557	KASSERT(disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING,
1558	    ("Wrong disk state (%s, %s).", g_mirror_get_diskname(disk),
1559	    g_mirror_disk_state2str(disk->d_state)));
1560	if (disk->d_sync.ds_consumer == NULL)
1561		return;
1562
1563	if (type == 0) {
1564		G_MIRROR_DEBUG(0, "Device %s: rebuilding provider %s finished.",
1565		    disk->d_softc->sc_name, g_mirror_get_diskname(disk));
1566	} else /* if (type == 1) */ {
1567		G_MIRROR_DEBUG(0, "Device %s: rebuilding provider %s stopped.",
1568		    disk->d_softc->sc_name, g_mirror_get_diskname(disk));
1569	}
1570	cp = disk->d_sync.ds_consumer;
1571	g_access(cp, -1, 0, 0);
1572	g_mirror_kill_consumer(disk->d_softc, cp);
1573	disk->d_sync.ds_consumer = NULL;
1574	disk->d_softc->sc_sync.ds_ndisks--;
1575	cp = disk->d_consumer;
1576	KASSERT(cp->acr == 0 && cp->acw == 1 && cp->ace == 1,
1577	    ("Consumer %s not opened.", cp->provider->name));
1578	g_access(cp, 0, -1, -1);
1579	G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d", cp->provider->name, 0, -1,
1580	    -1, 0);
1581	disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
1582}
1583
1584static void
1585g_mirror_launch_provider(struct g_mirror_softc *sc)
1586{
1587	struct g_mirror_disk *disk;
1588	struct g_provider *pp;
1589
1590	g_topology_assert();
1591
1592	pp = g_new_providerf(sc->sc_geom, "mirror/%s", sc->sc_name);
1593	pp->mediasize = sc->sc_mediasize;
1594	pp->sectorsize = sc->sc_sectorsize;
1595	sc->sc_provider = pp;
1596	g_error_provider(pp, 0);
1597	G_MIRROR_DEBUG(0, "Device %s: provider %s launched.", sc->sc_name,
1598	    pp->name);
1599	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1600		if (disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING)
1601			g_mirror_sync_start(disk);
1602	}
1603}
1604
1605static void
1606g_mirror_destroy_provider(struct g_mirror_softc *sc)
1607{
1608	struct g_mirror_disk *disk;
1609	struct bio *bp;
1610
1611	g_topology_assert();
1612	KASSERT(sc->sc_provider != NULL, ("NULL provider (device=%s).",
1613	    sc->sc_name));
1614
1615	g_error_provider(sc->sc_provider, ENXIO);
1616	mtx_lock(&sc->sc_queue_mtx);
1617	while ((bp = bioq_first(&sc->sc_queue)) != NULL) {
1618		bioq_remove(&sc->sc_queue, bp);
1619		g_io_deliver(bp, ENXIO);
1620	}
1621	mtx_unlock(&sc->sc_queue_mtx);
1622	G_MIRROR_DEBUG(0, "Device %s: provider %s destroyed.", sc->sc_name,
1623	    sc->sc_provider->name);
1624	sc->sc_provider->flags |= G_PF_WITHER;
1625	g_orphan_provider(sc->sc_provider, ENXIO);
1626	sc->sc_provider = NULL;
1627	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1628		if (disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING)
1629			g_mirror_sync_stop(disk, 1);
1630	}
1631}
1632
1633static void
1634g_mirror_go(void *arg)
1635{
1636	struct g_mirror_softc *sc;
1637
1638	sc = arg;
1639	G_MIRROR_DEBUG(0, "Force device %s start due to timeout.", sc->sc_name);
1640	g_mirror_event_send(sc, 0,
1641	    G_MIRROR_EVENT_DONTWAIT | G_MIRROR_EVENT_DEVICE);
1642}
1643
1644static u_int
1645g_mirror_determine_state(struct g_mirror_disk *disk)
1646{
1647	struct g_mirror_softc *sc;
1648	u_int state;
1649
1650	sc = disk->d_softc;
1651	if (sc->sc_syncid == disk->d_sync.ds_syncid) {
1652		if ((disk->d_flags &
1653		    G_MIRROR_DISK_FLAG_SYNCHRONIZING) == 0) {
1654			/* Disk does not need synchronization. */
1655			state = G_MIRROR_DISK_STATE_ACTIVE;
1656		} else {
1657			if ((sc->sc_flags &
1658			     G_MIRROR_DEVICE_FLAG_NOAUTOSYNC) == 0  ||
1659			    (disk->d_flags &
1660			     G_MIRROR_DISK_FLAG_FORCE_SYNC) != 0) {
1661				/*
1662				 * We can start synchronization from
1663				 * the stored offset.
1664				 */
1665				state = G_MIRROR_DISK_STATE_SYNCHRONIZING;
1666			} else {
1667				state = G_MIRROR_DISK_STATE_STALE;
1668			}
1669		}
1670	} else if (disk->d_sync.ds_syncid < sc->sc_syncid) {
1671		/*
1672		 * Reset all synchronization data for this disk,
1673		 * because if it even was synchronized, it was
1674		 * synchronized to disks with different syncid.
1675		 */
1676		disk->d_flags |= G_MIRROR_DISK_FLAG_SYNCHRONIZING;
1677		disk->d_sync.ds_offset = 0;
1678		disk->d_sync.ds_offset_done = 0;
1679		disk->d_sync.ds_syncid = sc->sc_syncid;
1680		if ((sc->sc_flags & G_MIRROR_DEVICE_FLAG_NOAUTOSYNC) == 0 ||
1681		    (disk->d_flags & G_MIRROR_DISK_FLAG_FORCE_SYNC) != 0) {
1682			state = G_MIRROR_DISK_STATE_SYNCHRONIZING;
1683		} else {
1684			state = G_MIRROR_DISK_STATE_STALE;
1685		}
1686	} else /* if (sc->sc_syncid < disk->d_sync.ds_syncid) */ {
1687		/*
1688		 * Not good, NOT GOOD!
1689		 * It means that mirror was started on stale disks
1690		 * and more fresh disk just arrive.
1691		 * If there were writes, mirror is fucked up, sorry.
1692		 * I think the best choice here is don't touch
1693		 * this disk and inform the user laudly.
1694		 */
1695		G_MIRROR_DEBUG(0, "Device %s was started before the freshest "
1696		    "disk (%s) arrives!! It will not be connected to the "
1697		    "running device.", sc->sc_name,
1698		    g_mirror_get_diskname(disk));
1699		g_mirror_destroy_disk(disk);
1700		state = G_MIRROR_DISK_STATE_NONE;
1701		/* Return immediately, because disk was destroyed. */
1702		return (state);
1703	}
1704	G_MIRROR_DEBUG(3, "State for %s disk: %s.",
1705	    g_mirror_get_diskname(disk), g_mirror_disk_state2str(state));
1706	return (state);
1707}
1708
1709/*
1710 * Update device state.
1711 */
1712static void
1713g_mirror_update_device(struct g_mirror_softc *sc, boolean_t force)
1714{
1715	struct g_mirror_disk *disk;
1716	u_int state;
1717
1718	g_topology_assert();
1719
1720	switch (sc->sc_state) {
1721	case G_MIRROR_DEVICE_STATE_STARTING:
1722	    {
1723		struct g_mirror_disk *pdisk;
1724		u_int dirty, ndisks, syncid;
1725
1726		KASSERT(sc->sc_provider == NULL,
1727		    ("Non-NULL provider in STARTING state (%s).", sc->sc_name));
1728		/*
1729		 * Are we ready? We are, if all disks are connected or
1730		 * if we have any disks and 'force' is true.
1731		 */
1732		if ((force && g_mirror_ndisks(sc, -1) > 0) ||
1733		    sc->sc_ndisks == g_mirror_ndisks(sc, -1)) {
1734			;
1735		} else if (g_mirror_ndisks(sc, -1) == 0) {
1736			/*
1737			 * Disks went down in starting phase, so destroy
1738			 * device.
1739			 */
1740			callout_drain(&sc->sc_callout);
1741			sc->sc_flags |= G_MIRROR_DEVICE_FLAG_DESTROY;
1742			return;
1743		} else {
1744			return;
1745		}
1746
1747		/*
1748		 * Activate all disks with the biggest syncid.
1749		 */
1750		if (force) {
1751			/*
1752			 * If 'force' is true, we have been called due to
1753			 * timeout, so don't bother canceling timeout.
1754			 */
1755			ndisks = 0;
1756			LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1757				if ((disk->d_flags &
1758				    G_MIRROR_DISK_FLAG_SYNCHRONIZING) == 0) {
1759					ndisks++;
1760				}
1761			}
1762			if (ndisks == 0) {
1763				/* No valid disks found, destroy device. */
1764				sc->sc_flags |= G_MIRROR_DEVICE_FLAG_DESTROY;
1765				return;
1766			}
1767		} else {
1768			/* Cancel timeout. */
1769			callout_drain(&sc->sc_callout);
1770		}
1771
1772		/*
1773		 * Find disk with the biggest syncid.
1774		 */
1775		syncid = 0;
1776		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1777			if (disk->d_sync.ds_syncid > syncid)
1778				syncid = disk->d_sync.ds_syncid;
1779		}
1780
1781		/*
1782		 * Here we need to look for dirty disks and if all disks
1783		 * with the biggest syncid are dirty, we have to choose
1784		 * one with the biggest priority and rebuild the rest.
1785		 */
1786		/*
1787		 * Find the number of dirty disks with the biggest syncid.
1788		 * Find the number of disks with the biggest syncid.
1789		 * While here, find a disk with the biggest priority.
1790		 */
1791		dirty = ndisks = 0;
1792		pdisk = NULL;
1793		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1794			if (disk->d_sync.ds_syncid != syncid)
1795				continue;
1796			if ((disk->d_flags &
1797			    G_MIRROR_DISK_FLAG_SYNCHRONIZING) != 0) {
1798				continue;
1799			}
1800			ndisks++;
1801			if ((disk->d_flags & G_MIRROR_DISK_FLAG_DIRTY) != 0) {
1802				dirty++;
1803				if (pdisk == NULL ||
1804				    pdisk->d_priority < disk->d_priority) {
1805					pdisk = disk;
1806				}
1807			}
1808		}
1809		if (dirty == 0) {
1810			/* No dirty disks at all, great. */
1811		} else if (dirty == ndisks) {
1812			/*
1813			 * Force synchronization for all dirty disks except one
1814			 * with the biggest priority.
1815			 */
1816			KASSERT(pdisk != NULL, ("pdisk == NULL"));
1817			G_MIRROR_DEBUG(1, "Using disk %s (device %s) as a "
1818			    "master disk for synchronization.",
1819			    g_mirror_get_diskname(pdisk), sc->sc_name);
1820			LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1821				if (disk->d_sync.ds_syncid != syncid)
1822					continue;
1823				if ((disk->d_flags &
1824				    G_MIRROR_DISK_FLAG_SYNCHRONIZING) != 0) {
1825					continue;
1826				}
1827				KASSERT((disk->d_flags &
1828				    G_MIRROR_DISK_FLAG_DIRTY) != 0,
1829				    ("Disk %s isn't marked as dirty.",
1830				    g_mirror_get_diskname(disk)));
1831				/* Skip the disk with the biggest priority. */
1832				if (disk == pdisk)
1833					continue;
1834				disk->d_sync.ds_syncid = 0;
1835			}
1836		} else if (dirty < ndisks) {
1837			/*
1838			 * Force synchronization for all dirty disks.
1839			 * We have some non-dirty disks.
1840			 */
1841			LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1842				if (disk->d_sync.ds_syncid != syncid)
1843					continue;
1844				if ((disk->d_flags &
1845				    G_MIRROR_DISK_FLAG_SYNCHRONIZING) != 0) {
1846					continue;
1847				}
1848				if ((disk->d_flags &
1849				    G_MIRROR_DISK_FLAG_DIRTY) == 0) {
1850					continue;
1851				}
1852				disk->d_sync.ds_syncid = 0;
1853			}
1854		}
1855
1856		/* Reset hint. */
1857		sc->sc_hint = NULL;
1858		sc->sc_syncid = syncid;
1859		if (force) {
1860			/* Remember to bump syncid on first write. */
1861			sc->sc_bump_syncid = G_MIRROR_BUMP_ON_FIRST_WRITE;
1862		}
1863		state = G_MIRROR_DEVICE_STATE_RUNNING;
1864		G_MIRROR_DEBUG(1, "Device %s state changed from %s to %s.",
1865		    sc->sc_name, g_mirror_device_state2str(sc->sc_state),
1866		    g_mirror_device_state2str(state));
1867		sc->sc_state = state;
1868		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
1869			state = g_mirror_determine_state(disk);
1870			g_mirror_event_send(disk, state,
1871			    G_MIRROR_EVENT_DONTWAIT);
1872			if (state == G_MIRROR_DISK_STATE_STALE) {
1873				sc->sc_bump_syncid =
1874				    G_MIRROR_BUMP_ON_FIRST_WRITE;
1875			}
1876		}
1877		break;
1878	    }
1879	case G_MIRROR_DEVICE_STATE_RUNNING:
1880		/*
1881		 * Bump syncid here, if we need to do it immediately.
1882		 */
1883		if (sc->sc_bump_syncid == G_MIRROR_BUMP_IMMEDIATELY) {
1884			sc->sc_bump_syncid = 0;
1885			g_mirror_bump_syncid(sc);
1886		}
1887		if (g_mirror_ndisks(sc, -1) == 0) {
1888			/*
1889			 * No disks at all, we need to destroy device.
1890			 */
1891			sc->sc_flags |= G_MIRROR_DEVICE_FLAG_DESTROY;
1892		} else if (g_mirror_ndisks(sc,
1893		    G_MIRROR_DISK_STATE_ACTIVE) == 0 &&
1894		    g_mirror_ndisks(sc, G_MIRROR_DISK_STATE_NEW) == 0) {
1895			/*
1896			 * No active disks, destroy provider.
1897			 */
1898			if (sc->sc_provider != NULL)
1899				g_mirror_destroy_provider(sc);
1900		} else if (g_mirror_ndisks(sc,
1901		    G_MIRROR_DISK_STATE_ACTIVE) > 0 &&
1902		    g_mirror_ndisks(sc, G_MIRROR_DISK_STATE_NEW) == 0) {
1903			/*
1904			 * We have active disks, launch provider if it doesn't
1905			 * exist.
1906			 */
1907			if (sc->sc_provider == NULL)
1908				g_mirror_launch_provider(sc);
1909		}
1910		break;
1911	default:
1912		KASSERT(1 == 0, ("Wrong device state (%s, %s).",
1913		    sc->sc_name, g_mirror_device_state2str(sc->sc_state)));
1914		break;
1915	}
1916}
1917
1918/*
1919 * Update disk state and device state if needed.
1920 */
1921#define	DISK_STATE_CHANGED()	G_MIRROR_DEBUG(1,			\
1922	"Disk %s state changed from %s to %s (device %s).",		\
1923	g_mirror_get_diskname(disk),					\
1924	g_mirror_disk_state2str(disk->d_state),				\
1925	g_mirror_disk_state2str(state), sc->sc_name)
1926static int
1927g_mirror_update_disk(struct g_mirror_disk *disk, u_int state)
1928{
1929	struct g_mirror_softc *sc;
1930
1931	g_topology_assert();
1932
1933	sc = disk->d_softc;
1934again:
1935	G_MIRROR_DEBUG(3, "Changing disk %s state from %s to %s.",
1936	    g_mirror_get_diskname(disk), g_mirror_disk_state2str(disk->d_state),
1937	    g_mirror_disk_state2str(state));
1938	switch (state) {
1939	case G_MIRROR_DISK_STATE_NEW:
1940		/*
1941		 * Possible scenarios:
1942		 * 1. New disk arrive.
1943		 */
1944		/* Previous state should be NONE. */
1945		KASSERT(disk->d_state == G_MIRROR_DISK_STATE_NONE,
1946		    ("Wrong disk state (%s, %s).", g_mirror_get_diskname(disk),
1947		    g_mirror_disk_state2str(disk->d_state)));
1948		DISK_STATE_CHANGED();
1949
1950		disk->d_state = state;
1951		if (LIST_EMPTY(&sc->sc_disks))
1952			LIST_INSERT_HEAD(&sc->sc_disks, disk, d_next);
1953		else {
1954			struct g_mirror_disk *dp;
1955
1956			LIST_FOREACH(dp, &sc->sc_disks, d_next) {
1957				if (disk->d_priority >= dp->d_priority) {
1958					LIST_INSERT_BEFORE(dp, disk, d_next);
1959					dp = NULL;
1960					break;
1961				}
1962				if (LIST_NEXT(dp, d_next) == NULL)
1963					break;
1964			}
1965			if (dp != NULL)
1966				LIST_INSERT_AFTER(dp, disk, d_next);
1967		}
1968		G_MIRROR_DEBUG(0, "Device %s: provider %s detected.",
1969		    sc->sc_name, g_mirror_get_diskname(disk));
1970		if (sc->sc_state == G_MIRROR_DEVICE_STATE_STARTING)
1971			break;
1972		KASSERT(sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
1973		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
1974		    g_mirror_device_state2str(sc->sc_state),
1975		    g_mirror_get_diskname(disk),
1976		    g_mirror_disk_state2str(disk->d_state)));
1977		state = g_mirror_determine_state(disk);
1978		if (state != G_MIRROR_DISK_STATE_NONE)
1979			goto again;
1980		break;
1981	case G_MIRROR_DISK_STATE_ACTIVE:
1982		/*
1983		 * Possible scenarios:
1984		 * 1. New disk does not need synchronization.
1985		 * 2. Synchronization process finished successfully.
1986		 */
1987		KASSERT(sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
1988		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
1989		    g_mirror_device_state2str(sc->sc_state),
1990		    g_mirror_get_diskname(disk),
1991		    g_mirror_disk_state2str(disk->d_state)));
1992		/* Previous state should be NEW or SYNCHRONIZING. */
1993		KASSERT(disk->d_state == G_MIRROR_DISK_STATE_NEW ||
1994		    disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING,
1995		    ("Wrong disk state (%s, %s).", g_mirror_get_diskname(disk),
1996		    g_mirror_disk_state2str(disk->d_state)));
1997		DISK_STATE_CHANGED();
1998
1999		if (disk->d_state == G_MIRROR_DISK_STATE_NEW)
2000			disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
2001		else if (disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING) {
2002			disk->d_flags &= ~G_MIRROR_DISK_FLAG_SYNCHRONIZING;
2003			disk->d_flags &= ~G_MIRROR_DISK_FLAG_FORCE_SYNC;
2004			g_mirror_sync_stop(disk, 0);
2005		}
2006		disk->d_state = state;
2007		disk->d_sync.ds_offset = 0;
2008		disk->d_sync.ds_offset_done = 0;
2009		g_mirror_update_access(disk);
2010		g_mirror_update_metadata(disk);
2011		G_MIRROR_DEBUG(0, "Device %s: provider %s activated.",
2012		    sc->sc_name, g_mirror_get_diskname(disk));
2013		break;
2014	case G_MIRROR_DISK_STATE_STALE:
2015		/*
2016		 * Possible scenarios:
2017		 * 1. Stale disk was connected.
2018		 */
2019		/* Previous state should be NEW. */
2020		KASSERT(disk->d_state == G_MIRROR_DISK_STATE_NEW,
2021		    ("Wrong disk state (%s, %s).", g_mirror_get_diskname(disk),
2022		    g_mirror_disk_state2str(disk->d_state)));
2023		KASSERT(sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
2024		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2025		    g_mirror_device_state2str(sc->sc_state),
2026		    g_mirror_get_diskname(disk),
2027		    g_mirror_disk_state2str(disk->d_state)));
2028		/*
2029		 * STALE state is only possible if device is marked
2030		 * NOAUTOSYNC.
2031		 */
2032		KASSERT((sc->sc_flags & G_MIRROR_DEVICE_FLAG_NOAUTOSYNC) != 0,
2033		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2034		    g_mirror_device_state2str(sc->sc_state),
2035		    g_mirror_get_diskname(disk),
2036		    g_mirror_disk_state2str(disk->d_state)));
2037		DISK_STATE_CHANGED();
2038
2039		disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
2040		disk->d_state = state;
2041		g_mirror_update_metadata(disk);
2042		G_MIRROR_DEBUG(0, "Device %s: provider %s is stale.",
2043		    sc->sc_name, g_mirror_get_diskname(disk));
2044		break;
2045	case G_MIRROR_DISK_STATE_SYNCHRONIZING:
2046		/*
2047		 * Possible scenarios:
2048		 * 1. Disk which needs synchronization was connected.
2049		 */
2050		/* Previous state should be NEW. */
2051		KASSERT(disk->d_state == G_MIRROR_DISK_STATE_NEW,
2052		    ("Wrong disk state (%s, %s).", g_mirror_get_diskname(disk),
2053		    g_mirror_disk_state2str(disk->d_state)));
2054		KASSERT(sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
2055		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2056		    g_mirror_device_state2str(sc->sc_state),
2057		    g_mirror_get_diskname(disk),
2058		    g_mirror_disk_state2str(disk->d_state)));
2059		DISK_STATE_CHANGED();
2060
2061		if (disk->d_state == G_MIRROR_DISK_STATE_NEW)
2062			disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
2063		disk->d_state = state;
2064		if (sc->sc_provider != NULL) {
2065			g_mirror_sync_start(disk);
2066			g_mirror_update_metadata(disk);
2067		}
2068		break;
2069	case G_MIRROR_DISK_STATE_DISCONNECTED:
2070		/*
2071		 * Possible scenarios:
2072		 * 1. Device wasn't running yet, but disk disappear.
2073		 * 2. Disk was active and disapppear.
2074		 * 3. Disk disappear during synchronization process.
2075		 */
2076		if (sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING) {
2077			/*
2078			 * Previous state should be ACTIVE, STALE or
2079			 * SYNCHRONIZING.
2080			 */
2081			KASSERT(disk->d_state == G_MIRROR_DISK_STATE_ACTIVE ||
2082			    disk->d_state == G_MIRROR_DISK_STATE_STALE ||
2083			    disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING,
2084			    ("Wrong disk state (%s, %s).",
2085			    g_mirror_get_diskname(disk),
2086			    g_mirror_disk_state2str(disk->d_state)));
2087		} else if (sc->sc_state == G_MIRROR_DEVICE_STATE_STARTING) {
2088			/* Previous state should be NEW. */
2089			KASSERT(disk->d_state == G_MIRROR_DISK_STATE_NEW,
2090			    ("Wrong disk state (%s, %s).",
2091			    g_mirror_get_diskname(disk),
2092			    g_mirror_disk_state2str(disk->d_state)));
2093			/*
2094			 * Reset bumping syncid if disk disappeared in STARTING
2095			 * state.
2096			 */
2097			if (sc->sc_bump_syncid == G_MIRROR_BUMP_ON_FIRST_WRITE)
2098				sc->sc_bump_syncid = 0;
2099#ifdef	INVARIANTS
2100		} else {
2101			KASSERT(1 == 0, ("Wrong device state (%s, %s, %s, %s).",
2102			    sc->sc_name,
2103			    g_mirror_device_state2str(sc->sc_state),
2104			    g_mirror_get_diskname(disk),
2105			    g_mirror_disk_state2str(disk->d_state)));
2106#endif
2107		}
2108		DISK_STATE_CHANGED();
2109		G_MIRROR_DEBUG(0, "Device %s: provider %s disconnected.",
2110		    sc->sc_name, g_mirror_get_diskname(disk));
2111
2112		g_mirror_destroy_disk(disk);
2113		break;
2114	case G_MIRROR_DISK_STATE_DESTROY:
2115	    {
2116		int error;
2117
2118		error = g_mirror_clear_metadata(disk);
2119		if (error != 0)
2120			return (error);
2121		DISK_STATE_CHANGED();
2122		G_MIRROR_DEBUG(0, "Device %s: provider %s destroyed.",
2123		    sc->sc_name, g_mirror_get_diskname(disk));
2124
2125		g_mirror_destroy_disk(disk);
2126		sc->sc_ndisks--;
2127		LIST_FOREACH(disk, &sc->sc_disks, d_next) {
2128			g_mirror_update_metadata(disk);
2129		}
2130		break;
2131	    }
2132	default:
2133		KASSERT(1 == 0, ("Unknown state (%u).", state));
2134		break;
2135	}
2136	return (0);
2137}
2138#undef	DISK_STATE_CHANGED
2139
2140static int
2141g_mirror_read_metadata(struct g_consumer *cp, struct g_mirror_metadata *md)
2142{
2143	struct g_provider *pp;
2144	u_char *buf;
2145	int error;
2146
2147	g_topology_assert();
2148
2149	error = g_access(cp, 1, 0, 0);
2150	if (error != 0)
2151		return (error);
2152	pp = cp->provider;
2153	g_topology_unlock();
2154	/* Metadata are stored on last sector. */
2155	buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
2156	    &error);
2157	g_topology_lock();
2158	if (buf == NULL) {
2159		g_access(cp, -1, 0, 0);
2160		return (error);
2161	}
2162	if (error != 0) {
2163		g_access(cp, -1, 0, 0);
2164		g_free(buf);
2165		return (error);
2166	}
2167	error = g_access(cp, -1, 0, 0);
2168	KASSERT(error == 0, ("Cannot decrease access count for %s.", pp->name));
2169
2170	/* Decode metadata. */
2171	error = mirror_metadata_decode(buf, md);
2172	g_free(buf);
2173	if (strcmp(md->md_magic, G_MIRROR_MAGIC) != 0)
2174		return (EINVAL);
2175	if (error != 0) {
2176		G_MIRROR_DEBUG(1, "MD5 metadata hash mismatch for provider %s.",
2177		    cp->provider->name);
2178		return (error);
2179	}
2180
2181	return (0);
2182}
2183
2184static int
2185g_mirror_check_metadata(struct g_mirror_softc *sc, struct g_provider *pp,
2186    struct g_mirror_metadata *md)
2187{
2188
2189	if (g_mirror_id2disk(sc, md->md_did) != NULL) {
2190		G_MIRROR_DEBUG(1, "Disk %s (id=%u) already exists, skipping.",
2191		    pp->name, md->md_did);
2192		return (EEXIST);
2193	}
2194	if (md->md_all != sc->sc_ndisks) {
2195		G_MIRROR_DEBUG(1,
2196		    "Invalid '%s' field on disk %s (device %s), skipping.",
2197		    "md_all", pp->name, sc->sc_name);
2198		return (EINVAL);
2199	}
2200	if (md->md_slice != sc->sc_slice) {
2201		G_MIRROR_DEBUG(1,
2202		    "Invalid '%s' field on disk %s (device %s), skipping.",
2203		    "md_slice", pp->name, sc->sc_name);
2204		return (EINVAL);
2205	}
2206	if (md->md_balance != sc->sc_balance) {
2207		G_MIRROR_DEBUG(1,
2208		    "Invalid '%s' field on disk %s (device %s), skipping.",
2209		    "md_balance", pp->name, sc->sc_name);
2210		return (EINVAL);
2211	}
2212	if (md->md_mediasize != sc->sc_mediasize) {
2213		G_MIRROR_DEBUG(1,
2214		    "Invalid '%s' field on disk %s (device %s), skipping.",
2215		    "md_mediasize", pp->name, sc->sc_name);
2216		return (EINVAL);
2217	}
2218	if (sc->sc_mediasize > pp->mediasize) {
2219		G_MIRROR_DEBUG(1,
2220		    "Invalid size of disk %s (device %s), skipping.", pp->name,
2221		    sc->sc_name);
2222		return (EINVAL);
2223	}
2224	if (md->md_sectorsize != sc->sc_sectorsize) {
2225		G_MIRROR_DEBUG(1,
2226		    "Invalid '%s' field on disk %s (device %s), skipping.",
2227		    "md_sectorsize", pp->name, sc->sc_name);
2228		return (EINVAL);
2229	}
2230	if ((sc->sc_sectorsize % pp->sectorsize) != 0) {
2231		G_MIRROR_DEBUG(1,
2232		    "Invalid sector size of disk %s (device %s), skipping.",
2233		    pp->name, sc->sc_name);
2234		return (EINVAL);
2235	}
2236	if ((md->md_mflags & ~G_MIRROR_DEVICE_FLAG_MASK) != 0) {
2237		G_MIRROR_DEBUG(1,
2238		    "Invalid device flags on disk %s (device %s), skipping.",
2239		    pp->name, sc->sc_name);
2240		return (EINVAL);
2241	}
2242	if ((md->md_dflags & ~G_MIRROR_DISK_FLAG_MASK) != 0) {
2243		G_MIRROR_DEBUG(1,
2244		    "Invalid disk flags on disk %s (device %s), skipping.",
2245		    pp->name, sc->sc_name);
2246		return (EINVAL);
2247	}
2248	return (0);
2249}
2250
2251static int
2252g_mirror_add_disk(struct g_mirror_softc *sc, struct g_provider *pp,
2253    struct g_mirror_metadata *md)
2254{
2255	struct g_mirror_disk *disk;
2256	int error;
2257
2258	g_topology_assert();
2259	G_MIRROR_DEBUG(2, "Adding disk %s.", pp->name);
2260
2261	error = g_mirror_check_metadata(sc, pp, md);
2262	if (error != 0)
2263		return (error);
2264	disk = g_mirror_init_disk(sc, pp, md, &error);
2265	if (disk == NULL)
2266		return (error);
2267	error = g_mirror_event_send(disk, G_MIRROR_DISK_STATE_NEW,
2268	    G_MIRROR_EVENT_WAIT);
2269	return (error);
2270}
2271
2272static int
2273g_mirror_access(struct g_provider *pp, int acr, int acw, int ace)
2274{
2275	struct g_mirror_softc *sc;
2276	struct g_mirror_disk *disk;
2277	int dcr, dcw, dce, err, error;
2278
2279	g_topology_assert();
2280	G_MIRROR_DEBUG(2, "Access request for %s: r%dw%de%d.", pp->name, acr,
2281	    acw, ace);
2282
2283	dcr = pp->acr + acr;
2284	dcw = pp->acw + acw;
2285	dce = pp->ace + ace;
2286
2287	/* On first open, grab an extra "exclusive" bit */
2288	if (pp->acr == 0 && pp->acw == 0 && pp->ace == 0)
2289		ace++;
2290	/* ... and let go of it on last close */
2291	if (dcr == 0 && dcw == 0 && dce == 0)
2292		ace--;
2293
2294	sc = pp->geom->softc;
2295	if (sc == NULL || LIST_EMPTY(&sc->sc_disks)) {
2296		if (acr <= 0 && acw <= 0 && ace <= 0)
2297			return (0);
2298		else
2299			return (ENXIO);
2300	}
2301	error = ENXIO;
2302	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
2303		if (disk->d_state != G_MIRROR_DISK_STATE_ACTIVE)
2304			continue;
2305		err = g_access(disk->d_consumer, acr, acw, ace);
2306		G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d",
2307		    g_mirror_get_diskname(disk), acr, acw, ace, err);
2308		if (err == 0) {
2309			/*
2310			 * Mark disk as dirty on open and unmark on close.
2311			 */
2312			if (pp->acw == 0 && dcw > 0) {
2313				G_MIRROR_DEBUG(1,
2314				    "Disk %s (device %s) marked as dirty.",
2315				    g_mirror_get_diskname(disk), sc->sc_name);
2316				disk->d_flags |= G_MIRROR_DISK_FLAG_DIRTY;
2317				g_mirror_update_metadata(disk);
2318			} else if (pp->acw > 0 && dcw == 0) {
2319				G_MIRROR_DEBUG(1,
2320				    "Disk %s (device %s) marked as clean.",
2321				    g_mirror_get_diskname(disk), sc->sc_name);
2322				disk->d_flags &= ~G_MIRROR_DISK_FLAG_DIRTY;
2323				g_mirror_update_metadata(disk);
2324			}
2325			error = 0;
2326		} else {
2327			sc->sc_bump_syncid = G_MIRROR_BUMP_ON_FIRST_WRITE;
2328			g_mirror_event_send(disk,
2329			    G_MIRROR_DISK_STATE_DISCONNECTED,
2330			    G_MIRROR_EVENT_DONTWAIT);
2331		}
2332	}
2333	return (error);
2334}
2335
2336static struct g_geom *
2337g_mirror_create(struct g_class *mp, const struct g_mirror_metadata *md)
2338{
2339	struct g_mirror_softc *sc;
2340	struct g_geom *gp;
2341	int error, timeout;
2342
2343	g_topology_assert();
2344	G_MIRROR_DEBUG(1, "Creating device %s (id=%u).", md->md_name,
2345	    md->md_mid);
2346
2347	/* One disk is minimum. */
2348	if (md->md_all < 1)
2349		return (NULL);
2350	/*
2351	 * Action geom.
2352	 */
2353	gp = g_new_geomf(mp, "%s", md->md_name);
2354	sc = malloc(sizeof(*sc), M_MIRROR, M_WAITOK | M_ZERO);
2355	gp->start = g_mirror_start;
2356	gp->spoiled = g_mirror_spoiled;
2357	gp->orphan = g_mirror_orphan;
2358	gp->access = g_mirror_access;
2359	gp->dumpconf = g_mirror_dumpconf;
2360
2361	sc->sc_id = md->md_mid;
2362	sc->sc_slice = md->md_slice;
2363	sc->sc_balance = md->md_balance;
2364	sc->sc_mediasize = md->md_mediasize;
2365	sc->sc_sectorsize = md->md_sectorsize;
2366	sc->sc_ndisks = md->md_all;
2367	sc->sc_flags = md->md_mflags;
2368	sc->sc_bump_syncid = 0;
2369	bioq_init(&sc->sc_queue);
2370	mtx_init(&sc->sc_queue_mtx, "gmirror:queue", NULL, MTX_DEF);
2371	LIST_INIT(&sc->sc_disks);
2372	TAILQ_INIT(&sc->sc_events);
2373	mtx_init(&sc->sc_events_mtx, "gmirror:events", NULL, MTX_DEF);
2374	callout_init(&sc->sc_callout, CALLOUT_MPSAFE);
2375	sc->sc_state = G_MIRROR_DEVICE_STATE_STARTING;
2376	gp->softc = sc;
2377	sc->sc_geom = gp;
2378	sc->sc_provider = NULL;
2379	/*
2380	 * Synchronization geom.
2381	 */
2382	gp = g_new_geomf(mp, "%s.sync", md->md_name);
2383	gp->softc = sc;
2384	gp->spoiled = g_mirror_spoiled;
2385	gp->orphan = g_mirror_orphan;
2386	sc->sc_sync.ds_geom = gp;
2387	sc->sc_sync.ds_block = atomic_load_acq_int(&g_mirror_sync_block_size);
2388	sc->sc_sync.ds_ndisks = 0;
2389	sc->sc_sync.ds_zone = uma_zcreate("gmirror:sync", sc->sc_sync.ds_block,
2390	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
2391	error = kthread_create(g_mirror_worker, sc, &sc->sc_worker, 0, 0,
2392	    "g_mirror %s", md->md_name);
2393	if (error != 0) {
2394		G_MIRROR_DEBUG(1, "Cannot create kernel thread for %s.",
2395		    sc->sc_name);
2396		uma_zdestroy(sc->sc_sync.ds_zone);
2397		g_destroy_geom(sc->sc_sync.ds_geom);
2398		mtx_destroy(&sc->sc_events_mtx);
2399		mtx_destroy(&sc->sc_queue_mtx);
2400		g_destroy_geom(sc->sc_geom);
2401		free(sc, M_MIRROR);
2402		return (NULL);
2403	}
2404
2405	G_MIRROR_DEBUG(0, "Device %s created (id=%u).", sc->sc_name, sc->sc_id);
2406
2407	/*
2408	 * Run timeout.
2409	 */
2410	timeout = atomic_load_acq_int(&g_mirror_timeout);
2411	callout_reset(&sc->sc_callout, timeout * hz, g_mirror_go, sc);
2412	return (sc->sc_geom);
2413}
2414
2415int
2416g_mirror_destroy(struct g_mirror_softc *sc, boolean_t force)
2417{
2418	struct g_provider *pp;
2419
2420	g_topology_assert();
2421
2422	if (sc == NULL)
2423		return (ENXIO);
2424	pp = sc->sc_provider;
2425	if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
2426		if (force) {
2427			G_MIRROR_DEBUG(0, "Device %s is still open, so it "
2428			    "can't be definitely removed.", pp->name);
2429		} else {
2430			G_MIRROR_DEBUG(1,
2431			    "Device %s is still open (r%dw%de%d).", pp->name,
2432			    pp->acr, pp->acw, pp->ace);
2433			return (EBUSY);
2434		}
2435	}
2436
2437	sc->sc_flags |= G_MIRROR_DEVICE_FLAG_DESTROY;
2438	sc->sc_flags |= G_MIRROR_DEVICE_FLAG_WAIT;
2439	G_MIRROR_DEBUG(4, "%s: Waking up %p.", __func__, sc);
2440	mtx_lock(&sc->sc_queue_mtx);
2441	wakeup(sc);
2442	mtx_unlock(&sc->sc_queue_mtx);
2443	G_MIRROR_DEBUG(4, "%s: Sleeping %p.", __func__, &sc->sc_worker);
2444	while (sc->sc_worker != NULL)
2445		tsleep(&sc->sc_worker, PRIBIO, "m:destroy", hz / 5);
2446	G_MIRROR_DEBUG(4, "%s: Woken up %p.", __func__, &sc->sc_worker);
2447	g_mirror_destroy_device(sc);
2448	free(sc, M_MIRROR);
2449	return (0);
2450}
2451
2452static void
2453g_mirror_taste_orphan(struct g_consumer *cp)
2454{
2455
2456	KASSERT(1 == 0, ("%s called while tasting %s.", __func__,
2457	    cp->provider->name));
2458}
2459
2460static struct g_geom *
2461g_mirror_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
2462{
2463	struct g_mirror_metadata md;
2464	struct g_mirror_softc *sc;
2465	struct g_consumer *cp;
2466	struct g_geom *gp;
2467	int error;
2468
2469	g_topology_assert();
2470	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
2471	G_MIRROR_DEBUG(2, "Tasting %s.", pp->name);
2472
2473	gp = g_new_geomf(mp, "mirror:taste");
2474	/*
2475	 * This orphan function should be never called.
2476	 */
2477	gp->orphan = g_mirror_taste_orphan;
2478	cp = g_new_consumer(gp);
2479	g_attach(cp, pp);
2480	error = g_mirror_read_metadata(cp, &md);
2481	g_detach(cp);
2482	g_destroy_consumer(cp);
2483	g_destroy_geom(gp);
2484	if (error != 0)
2485		return (NULL);
2486	gp = NULL;
2487
2488	if (md.md_version > G_MIRROR_VERSION) {
2489		printf("geom_mirror.ko module is too old to handle %s.\n",
2490		    pp->name);
2491		return (NULL);
2492	}
2493	if ((md.md_dflags & G_MIRROR_DISK_FLAG_INACTIVE) != 0) {
2494		G_MIRROR_DEBUG(0,
2495		    "Device %s: provider %s marked as inactive, skipping.",
2496		    md.md_name, pp->name);
2497		return (NULL);
2498	}
2499	if (g_mirror_debug >= 2)
2500		mirror_metadata_dump(&md);
2501
2502	/*
2503	 * Let's check if device already exists.
2504	 */
2505	LIST_FOREACH(gp, &mp->geom, geom) {
2506		sc = gp->softc;
2507		if (sc == NULL)
2508			continue;
2509		if (sc->sc_sync.ds_geom == gp)
2510			continue;
2511		if (strcmp(md.md_name, sc->sc_name) != 0)
2512			continue;
2513		if (md.md_mid != sc->sc_id) {
2514			G_MIRROR_DEBUG(0, "Device %s already configured.",
2515			    sc->sc_name);
2516			return (NULL);
2517		}
2518		break;
2519	}
2520	if (gp == NULL) {
2521		gp = g_mirror_create(mp, &md);
2522		if (gp == NULL) {
2523			G_MIRROR_DEBUG(0, "Cannot create device %s.",
2524			    md.md_name);
2525			return (NULL);
2526		}
2527		sc = gp->softc;
2528	}
2529	G_MIRROR_DEBUG(1, "Adding disk %s to %s.", pp->name, gp->name);
2530	error = g_mirror_add_disk(sc, pp, &md);
2531	if (error != 0) {
2532		G_MIRROR_DEBUG(0, "Cannot add disk %s to %s (error=%d).",
2533		    pp->name, gp->name, error);
2534		if (LIST_EMPTY(&sc->sc_disks))
2535			g_mirror_destroy(sc, 1);
2536		return (NULL);
2537	}
2538	return (gp);
2539}
2540
2541static int
2542g_mirror_destroy_geom(struct gctl_req *req __unused,
2543    struct g_class *mp __unused, struct g_geom *gp)
2544{
2545
2546	return (g_mirror_destroy(gp->softc, 0));
2547}
2548
2549static void
2550g_mirror_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
2551    struct g_consumer *cp, struct g_provider *pp)
2552{
2553	struct g_mirror_softc *sc;
2554
2555	g_topology_assert();
2556
2557	sc = gp->softc;
2558	if (sc == NULL)
2559		return;
2560	/* Skip synchronization geom. */
2561	if (gp == sc->sc_sync.ds_geom)
2562		return;
2563	if (pp != NULL) {
2564		/* Nothing here. */
2565	} else if (cp != NULL) {
2566		struct g_mirror_disk *disk;
2567
2568		disk = cp->private;
2569		if (disk == NULL)
2570			return;
2571		sbuf_printf(sb, "%s<ID>%u</ID>\n", indent, (u_int)disk->d_id);
2572		if (disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING) {
2573			sbuf_printf(sb, "%s<Synchronized>", indent);
2574			if (disk->d_sync.ds_offset_done == 0)
2575				sbuf_printf(sb, "0%%");
2576			else {
2577				sbuf_printf(sb, "%u%%",
2578				    (u_int)((disk->d_sync.ds_offset_done * 100) /
2579				    sc->sc_provider->mediasize));
2580			}
2581			sbuf_printf(sb, "</Synchronized>\n");
2582		}
2583		sbuf_printf(sb, "%s<SyncID>%u</SyncID>\n", indent,
2584		    disk->d_sync.ds_syncid);
2585		sbuf_printf(sb, "%s<Flags>", indent);
2586		if (disk->d_flags == 0)
2587			sbuf_printf(sb, "NONE");
2588		else {
2589			int first = 1;
2590
2591			if ((disk->d_flags & G_MIRROR_DISK_FLAG_DIRTY) != 0) {
2592				if (!first)
2593					sbuf_printf(sb, ", ");
2594				else
2595					first = 0;
2596				sbuf_printf(sb, "DIRTY");
2597			}
2598			if ((disk->d_flags &
2599			    G_MIRROR_DISK_FLAG_INACTIVE) != 0) {
2600				if (!first)
2601					sbuf_printf(sb, ", ");
2602				else
2603					first = 0;
2604				sbuf_printf(sb, "INACTIVE");
2605			}
2606			if ((disk->d_flags &
2607			    G_MIRROR_DISK_FLAG_SYNCHRONIZING) != 0) {
2608				if (!first)
2609					sbuf_printf(sb, ", ");
2610				else
2611					first = 0;
2612				sbuf_printf(sb, "SYNCHRONIZING");
2613			}
2614			if ((disk->d_flags &
2615			    G_MIRROR_DISK_FLAG_FORCE_SYNC) != 0) {
2616				if (!first)
2617					sbuf_printf(sb, ", ");
2618				else
2619					first = 0;
2620				sbuf_printf(sb, "FORCE_SYNC");
2621			}
2622		}
2623		sbuf_printf(sb, "</Flags>\n");
2624		sbuf_printf(sb, "%s<Priority>%u</Priority>\n", indent,
2625		    disk->d_priority);
2626		sbuf_printf(sb, "%s<State>%s</State>\n", indent,
2627		    g_mirror_disk_state2str(disk->d_state));
2628	} else {
2629		sbuf_printf(sb, "%s<ID>%u</ID>\n", indent, (u_int)sc->sc_id);
2630		sbuf_printf(sb, "%s<SyncID>%u</SyncID>\n", indent, sc->sc_syncid);
2631		sbuf_printf(sb, "%s<Flags>", indent);
2632		if (sc->sc_flags == 0)
2633			sbuf_printf(sb, "NONE");
2634		else {
2635			int first = 1;
2636
2637			if ((sc->sc_flags &
2638			    G_MIRROR_DEVICE_FLAG_NOAUTOSYNC) != 0) {
2639				if (!first)
2640					sbuf_printf(sb, ", ");
2641				else
2642					first = 0;
2643				sbuf_printf(sb, "NOAUTOSYNC");
2644			}
2645		}
2646		sbuf_printf(sb, "</Flags>\n");
2647		sbuf_printf(sb, "%s<Slice>%u</Slice>\n", indent,
2648		    (u_int)sc->sc_slice);
2649		sbuf_printf(sb, "%s<Balance>%s</Balance>\n", indent,
2650		    balance_name(sc->sc_balance));
2651		sbuf_printf(sb, "%s<Components>%u</Components>\n", indent,
2652		    sc->sc_ndisks);
2653	}
2654}
2655
2656DECLARE_GEOM_CLASS(g_mirror_class, g_mirror);
2657