g_mirror.c revision 133318
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 133318 2004-08-08 07:57:53Z phk $");
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	.version = G_VERSION,
85	.ctlreq = g_mirror_config,
86	.taste = g_mirror_taste,
87	.destroy_geom = g_mirror_destroy_geom
88};
89
90
91static void g_mirror_destroy_provider(struct g_mirror_softc *sc);
92static int g_mirror_update_disk(struct g_mirror_disk *disk, u_int state);
93static void g_mirror_update_device(struct g_mirror_softc *sc, boolean_t force);
94static void g_mirror_dumpconf(struct sbuf *sb, const char *indent,
95    struct g_geom *gp, struct g_consumer *cp, struct g_provider *pp);
96static void g_mirror_sync_stop(struct g_mirror_disk *disk, int type);
97
98
99static const char *
100g_mirror_disk_state2str(int state)
101{
102
103	switch (state) {
104	case G_MIRROR_DISK_STATE_NONE:
105		return ("NONE");
106	case G_MIRROR_DISK_STATE_NEW:
107		return ("NEW");
108	case G_MIRROR_DISK_STATE_ACTIVE:
109		return ("ACTIVE");
110	case G_MIRROR_DISK_STATE_STALE:
111		return ("STALE");
112	case G_MIRROR_DISK_STATE_SYNCHRONIZING:
113		return ("SYNCHRONIZING");
114	case G_MIRROR_DISK_STATE_DISCONNECTED:
115		return ("DISCONNECTED");
116	case G_MIRROR_DISK_STATE_DESTROY:
117		return ("DESTROY");
118	default:
119		return ("INVALID");
120	}
121}
122
123static const char *
124g_mirror_device_state2str(int state)
125{
126
127	switch (state) {
128	case G_MIRROR_DEVICE_STATE_STARTING:
129		return ("STARTING");
130	case G_MIRROR_DEVICE_STATE_RUNNING:
131		return ("RUNNING");
132	default:
133		return ("INVALID");
134	}
135}
136
137static const char *
138g_mirror_get_diskname(struct g_mirror_disk *disk)
139{
140
141	if (disk->d_consumer == NULL || disk->d_consumer->provider == NULL)
142		return ("[unknown]");
143	return (disk->d_name);
144}
145
146/*
147 * --- Events handling functions ---
148 * Events in geom_mirror are used to maintain disks and device status
149 * from one thread to simplify locking.
150 */
151static void
152g_mirror_event_free(struct g_mirror_event *ep)
153{
154
155	free(ep, M_MIRROR);
156}
157
158int
159g_mirror_event_send(void *arg, int state, int flags)
160{
161	struct g_mirror_softc *sc;
162	struct g_mirror_disk *disk;
163	struct g_mirror_event *ep;
164	int error;
165
166	ep = malloc(sizeof(*ep), M_MIRROR, M_WAITOK);
167	G_MIRROR_DEBUG(4, "%s: Sending event %p.", __func__, ep);
168	if ((flags & G_MIRROR_EVENT_DEVICE) != 0) {
169		disk = NULL;
170		sc = arg;
171	} else {
172		disk = arg;
173		sc = disk->d_softc;
174	}
175	ep->e_disk = disk;
176	ep->e_state = state;
177	ep->e_flags = flags;
178	ep->e_error = 0;
179	mtx_lock(&sc->sc_events_mtx);
180	TAILQ_INSERT_TAIL(&sc->sc_events, ep, e_next);
181	mtx_unlock(&sc->sc_events_mtx);
182	G_MIRROR_DEBUG(4, "%s: Waking up %p.", __func__, sc);
183	mtx_lock(&sc->sc_queue_mtx);
184	wakeup(sc);
185	mtx_unlock(&sc->sc_queue_mtx);
186	if ((flags & G_MIRROR_EVENT_DONTWAIT) != 0)
187		return (0);
188	g_topology_assert();
189	G_MIRROR_DEBUG(4, "%s: Sleeping %p.", __func__, ep);
190	g_topology_unlock();
191	while ((ep->e_flags & G_MIRROR_EVENT_DONE) == 0) {
192		mtx_lock(&sc->sc_events_mtx);
193		MSLEEP(ep, &sc->sc_events_mtx, PRIBIO | PDROP, "m:event",
194		    hz * 5);
195	}
196	/* Don't even try to use 'sc' here, because it could be already dead. */
197	g_topology_lock();
198	error = ep->e_error;
199	g_mirror_event_free(ep);
200	return (error);
201}
202
203static struct g_mirror_event *
204g_mirror_event_get(struct g_mirror_softc *sc)
205{
206	struct g_mirror_event *ep;
207
208	mtx_lock(&sc->sc_events_mtx);
209	ep = TAILQ_FIRST(&sc->sc_events);
210	if (ep != NULL)
211		TAILQ_REMOVE(&sc->sc_events, ep, e_next);
212	mtx_unlock(&sc->sc_events_mtx);
213	return (ep);
214}
215
216static void
217g_mirror_event_cancel(struct g_mirror_disk *disk)
218{
219	struct g_mirror_softc *sc;
220	struct g_mirror_event *ep, *tmpep;
221
222	g_topology_assert();
223
224	sc = disk->d_softc;
225	mtx_lock(&sc->sc_events_mtx);
226	TAILQ_FOREACH_SAFE(ep, &sc->sc_events, e_next, tmpep) {
227		if ((ep->e_flags & G_MIRROR_EVENT_DEVICE) != 0)
228			continue;
229		if (ep->e_disk != disk)
230			continue;
231		TAILQ_REMOVE(&sc->sc_events, ep, e_next);
232		if ((ep->e_flags & G_MIRROR_EVENT_DONTWAIT) != 0)
233			g_mirror_event_free(ep);
234		else {
235			ep->e_error = ECANCELED;
236			wakeup(ep);
237		}
238	}
239	mtx_unlock(&sc->sc_events_mtx);
240}
241
242/*
243 * Return the number of disks in given state.
244 * If state is equal to -1, count all connected disks.
245 */
246u_int
247g_mirror_ndisks(struct g_mirror_softc *sc, int state)
248{
249	struct g_mirror_disk *disk;
250	u_int n = 0;
251
252	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
253		if (state == -1 || disk->d_state == state)
254			n++;
255	}
256	return (n);
257}
258
259/*
260 * Find a disk in mirror by its disk ID.
261 */
262static struct g_mirror_disk *
263g_mirror_id2disk(struct g_mirror_softc *sc, uint32_t id)
264{
265	struct g_mirror_disk *disk;
266
267	g_topology_assert();
268
269	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
270		if (disk->d_id == id)
271			return (disk);
272	}
273	return (NULL);
274}
275
276static u_int
277g_mirror_nrequests(struct g_mirror_softc *sc, struct g_consumer *cp)
278{
279	struct bio *bp;
280	u_int nreqs = 0;
281
282	mtx_lock(&sc->sc_queue_mtx);
283	TAILQ_FOREACH(bp, &sc->sc_queue.queue, bio_queue) {
284		if (bp->bio_from == cp)
285			nreqs++;
286	}
287	mtx_unlock(&sc->sc_queue_mtx);
288	return (nreqs);
289}
290
291static void
292g_mirror_kill_consumer(struct g_mirror_softc *sc, struct g_consumer *cp)
293{
294
295	g_topology_assert();
296
297	cp->private = NULL;
298	if (cp->nstart != cp->nend) {
299		G_MIRROR_DEBUG(2,
300		    "I/O requests for %s exist, can't destroy it now.",
301		    cp->provider->name);
302		return;
303	}
304	if (g_mirror_nrequests(sc, cp) > 0) {
305		G_MIRROR_DEBUG(2,
306		    "I/O requests for %s in queue, can't destroy it now.",
307		    cp->provider->name);
308		return;
309	}
310	G_MIRROR_DEBUG(2, "Consumer %s destroyed.", cp->provider->name);
311	g_detach(cp);
312	g_destroy_consumer(cp);
313}
314
315static int
316g_mirror_connect_disk(struct g_mirror_disk *disk, struct g_provider *pp)
317{
318	int error;
319
320	g_topology_assert();
321	KASSERT(disk->d_consumer == NULL,
322	    ("Disk already connected (device %s).", disk->d_softc->sc_name));
323
324	disk->d_consumer = g_new_consumer(disk->d_softc->sc_geom);
325	disk->d_consumer->private = disk;
326	error = g_attach(disk->d_consumer, pp);
327	if (error != 0)
328		return (error);
329	G_MIRROR_DEBUG(2, "Disk %s connected.", g_mirror_get_diskname(disk));
330	return (0);
331}
332
333static void
334g_mirror_disconnect_disk(struct g_mirror_disk *disk)
335{
336	struct g_consumer *cp;
337
338	g_topology_assert();
339
340	cp = disk->d_consumer;
341	if (cp == NULL)
342		return;
343	if (cp->provider != NULL) {
344		G_MIRROR_DEBUG(2, "Disk %s disconnected.",
345		    g_mirror_get_diskname(disk));
346		if (cp->acr > 0 || cp->acw > 0 || cp->ace > 0) {
347			G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d",
348			    cp->provider->name, -cp->acr, -cp->acw, -cp->ace,
349			    0);
350			g_access(cp, -cp->acr, -cp->acw, -cp->ace);
351		}
352		g_mirror_kill_consumer(disk->d_softc, cp);
353	} else {
354		g_destroy_consumer(cp);
355	}
356}
357
358/*
359 * Initialize disk. This means allocate memory, create consumer, attach it
360 * to the provider and open access (r1w1e1) to it.
361 */
362static struct g_mirror_disk *
363g_mirror_init_disk(struct g_mirror_softc *sc, struct g_provider *pp,
364    struct g_mirror_metadata *md, int *errorp)
365{
366	struct g_mirror_disk *disk;
367	int error;
368
369	disk = malloc(sizeof(*disk), M_MIRROR, M_NOWAIT | M_ZERO);
370	if (disk == NULL) {
371		error = ENOMEM;
372		goto fail;
373	}
374	disk->d_softc = sc;
375	error = g_mirror_connect_disk(disk, pp);
376	if (error != 0)
377		goto fail;
378	disk->d_id = md->md_did;
379	disk->d_state = G_MIRROR_DISK_STATE_NONE;
380	disk->d_priority = md->md_priority;
381	disk->d_delay.sec = 0;
382	disk->d_delay.frac = 0;
383	binuptime(&disk->d_last_used);
384	disk->d_flags = md->md_dflags;
385	disk->d_sync.ds_consumer = NULL;
386	disk->d_sync.ds_offset = md->md_sync_offset;
387	disk->d_sync.ds_offset_done = md->md_sync_offset;
388	disk->d_sync.ds_syncid = md->md_syncid;
389	if (errorp != NULL)
390		*errorp = 0;
391	return (disk);
392fail:
393	if (errorp != NULL)
394		*errorp = error;
395	if (disk != NULL) {
396		g_mirror_disconnect_disk(disk);
397		free(disk, M_MIRROR);
398	}
399	return (NULL);
400}
401
402static void
403g_mirror_destroy_disk(struct g_mirror_disk *disk)
404{
405	struct g_mirror_softc *sc;
406
407	g_topology_assert();
408
409	LIST_REMOVE(disk, d_next);
410	g_mirror_event_cancel(disk);
411	sc = disk->d_softc;
412	if (sc->sc_hint == disk)
413		sc->sc_hint = NULL;
414	switch (disk->d_state) {
415	case G_MIRROR_DISK_STATE_SYNCHRONIZING:
416		g_mirror_sync_stop(disk, 1);
417		/* FALLTHROUGH */
418	case G_MIRROR_DISK_STATE_NEW:
419	case G_MIRROR_DISK_STATE_STALE:
420	case G_MIRROR_DISK_STATE_ACTIVE:
421		g_mirror_disconnect_disk(disk);
422		free(disk, M_MIRROR);
423		break;
424	default:
425		KASSERT(0 == 1, ("Wrong disk state (%s, %s).",
426		    g_mirror_get_diskname(disk),
427		    g_mirror_disk_state2str(disk->d_state)));
428	}
429}
430
431static void
432g_mirror_destroy_device(struct g_mirror_softc *sc)
433{
434	struct g_mirror_disk *disk;
435	struct g_mirror_event *ep;
436	struct g_geom *gp;
437	struct g_consumer *cp;
438
439	g_topology_assert();
440
441	gp = sc->sc_geom;
442	if (sc->sc_provider != NULL)
443		g_mirror_destroy_provider(sc);
444	for (disk = LIST_FIRST(&sc->sc_disks); disk != NULL;
445	    disk = LIST_FIRST(&sc->sc_disks)) {
446		g_mirror_destroy_disk(disk);
447	}
448	while ((ep = g_mirror_event_get(sc)) != NULL) {
449		if ((ep->e_flags & G_MIRROR_EVENT_DONTWAIT) != 0)
450			g_mirror_event_free(ep);
451		else {
452			ep->e_error = ECANCELED;
453			ep->e_flags |= G_MIRROR_EVENT_DONE;
454			G_MIRROR_DEBUG(4, "%s: Waking up %p.", __func__, ep);
455			mtx_lock(&sc->sc_events_mtx);
456			wakeup(ep);
457			mtx_unlock(&sc->sc_events_mtx);
458		}
459	}
460	callout_drain(&sc->sc_callout);
461	gp->softc = NULL;
462	uma_zdestroy(sc->sc_sync.ds_zone);
463	while ((cp = LIST_FIRST(&sc->sc_sync.ds_geom->consumer)) != NULL) {
464		if (cp->provider != NULL) {
465			if (cp->acr > 0 || cp->acw > 0 || cp->ace > 0)
466				g_access(cp, -cp->acr, -cp->acw, -cp->ace);
467			g_detach(cp);
468		}
469		g_destroy_consumer(cp);
470	}
471	sc->sc_sync.ds_geom->softc = NULL;
472	g_destroy_geom(sc->sc_sync.ds_geom);
473	mtx_destroy(&sc->sc_queue_mtx);
474	mtx_destroy(&sc->sc_events_mtx);
475	G_MIRROR_DEBUG(0, "Device %s destroyed.", gp->name);
476	g_wither_geom(gp, ENXIO);
477}
478
479static void
480g_mirror_orphan(struct g_consumer *cp)
481{
482	struct g_mirror_disk *disk;
483
484	g_topology_assert();
485
486	disk = cp->private;
487	if (disk == NULL)
488		return;
489	disk->d_softc->sc_bump_syncid = G_MIRROR_BUMP_ON_FIRST_WRITE;
490	g_mirror_event_send(disk, G_MIRROR_DISK_STATE_DISCONNECTED,
491	    G_MIRROR_EVENT_DONTWAIT);
492}
493
494static void
495g_mirror_spoiled(struct g_consumer *cp)
496{
497	struct g_mirror_disk *disk;
498
499	g_topology_assert();
500
501	disk = cp->private;
502	if (disk == NULL)
503		return;
504	disk->d_softc->sc_bump_syncid = G_MIRROR_BUMP_IMMEDIATELY;
505	g_mirror_event_send(disk, G_MIRROR_DISK_STATE_DISCONNECTED,
506	    G_MIRROR_EVENT_DONTWAIT);
507}
508
509/*
510 * Function should return the next active disk on the list.
511 * It is possible that it will be the same disk as given.
512 * If there are no active disks on list, NULL is returned.
513 */
514static __inline struct g_mirror_disk *
515g_mirror_find_next(struct g_mirror_softc *sc, struct g_mirror_disk *disk)
516{
517	struct g_mirror_disk *dp;
518
519	for (dp = LIST_NEXT(disk, d_next); dp != disk;
520	    dp = LIST_NEXT(dp, d_next)) {
521		if (dp == NULL)
522			dp = LIST_FIRST(&sc->sc_disks);
523		if (dp->d_state == G_MIRROR_DISK_STATE_ACTIVE)
524			break;
525	}
526	if (dp->d_state != G_MIRROR_DISK_STATE_ACTIVE)
527		return (NULL);
528	return (dp);
529}
530
531static struct g_mirror_disk *
532g_mirror_get_disk(struct g_mirror_softc *sc)
533{
534	struct g_mirror_disk *disk;
535
536	if (sc->sc_hint == NULL) {
537		sc->sc_hint = LIST_FIRST(&sc->sc_disks);
538		if (sc->sc_hint == NULL)
539			return (NULL);
540	}
541	disk = sc->sc_hint;
542	if (disk->d_state != G_MIRROR_DISK_STATE_ACTIVE) {
543		disk = g_mirror_find_next(sc, disk);
544		if (disk == NULL)
545			return (NULL);
546	}
547	sc->sc_hint = g_mirror_find_next(sc, disk);
548	return (disk);
549}
550
551static int
552g_mirror_clear_metadata(struct g_mirror_disk *disk)
553{
554	struct g_mirror_softc *sc;
555	struct g_consumer *cp;
556	off_t offset, length;
557	u_char *sector;
558	int close = 0, error = 0;
559
560	g_topology_assert();
561
562	sc = disk->d_softc;
563	cp = disk->d_consumer;
564	KASSERT(cp != NULL, ("NULL consumer (%s).", sc->sc_name));
565	KASSERT(cp->provider != NULL, ("NULL provider (%s).", sc->sc_name));
566	length = cp->provider->sectorsize;
567	offset = cp->provider->mediasize - length;
568	sector = malloc((size_t)length, M_MIRROR, M_WAITOK | M_ZERO);
569	/*
570	 * Open consumer if it wasn't opened and remember to close it.
571	 */
572	if ((disk->d_flags & G_MIRROR_DISK_FLAG_DIRTY) == 0) {
573		error = g_access(cp, 0, 1, 1);
574		G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d",
575		    cp->provider->name, 0, 1, 1, error);
576		if (error == 0)
577			close = 1;
578#ifdef	INVARIANTS
579	} else {
580		KASSERT(cp->acw > 0 && cp->ace > 0,
581		    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name,
582		    cp->acr, cp->acw, cp->ace));
583#endif
584	}
585	if (error == 0) {
586		g_topology_unlock();
587		error = g_write_data(cp, offset, sector, length);
588		g_topology_lock();
589	}
590	free(sector, M_MIRROR);
591	if (close) {
592		g_access(cp, 0, -1, -1);
593		G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d",
594		    cp->provider->name, 0, -1, -1, 0);
595	}
596	if (error != 0) {
597		G_MIRROR_DEBUG(0, "Cannot clear metadata on disk %s.",
598		    g_mirror_get_diskname(disk));
599		disk->d_softc->sc_bump_syncid = G_MIRROR_BUMP_IMMEDIATELY;
600		g_mirror_event_send(disk, G_MIRROR_DISK_STATE_DISCONNECTED,
601		    G_MIRROR_EVENT_DONTWAIT);
602		return (error);
603	}
604	G_MIRROR_DEBUG(2, "Metadata on %s cleared.",
605	    g_mirror_get_diskname(disk));
606	return (0);
607}
608
609void
610g_mirror_fill_metadata(struct g_mirror_softc *sc, struct g_mirror_disk *disk,
611    struct g_mirror_metadata *md)
612{
613
614	strlcpy(md->md_magic, G_MIRROR_MAGIC, sizeof(md->md_magic));
615	md->md_version = G_MIRROR_VERSION;
616	strlcpy(md->md_name, sc->sc_name, sizeof(md->md_name));
617	md->md_mid = sc->sc_id;
618	md->md_all = sc->sc_ndisks;
619	md->md_slice = sc->sc_slice;
620	md->md_balance = sc->sc_balance;
621	md->md_mediasize = sc->sc_mediasize;
622	md->md_sectorsize = sc->sc_sectorsize;
623	md->md_mflags = (sc->sc_flags & G_MIRROR_DEVICE_FLAG_MASK);
624	if (disk == NULL) {
625		md->md_did = arc4random();
626		md->md_priority = 0;
627		md->md_syncid = 0;
628		md->md_dflags = 0;
629		md->md_sync_offset = 0;
630	} else {
631		md->md_did = disk->d_id;
632		md->md_priority = disk->d_priority;
633		md->md_syncid = disk->d_sync.ds_syncid;
634		md->md_dflags = (disk->d_flags & G_MIRROR_DISK_FLAG_MASK);
635		if (disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING)
636			md->md_sync_offset = disk->d_sync.ds_offset_done;
637		else
638			md->md_sync_offset = 0;
639	}
640}
641
642void
643g_mirror_update_metadata(struct g_mirror_disk *disk)
644{
645	struct g_mirror_softc *sc;
646	struct g_mirror_metadata md;
647	struct g_consumer *cp;
648	off_t offset, length;
649	u_char *sector;
650	int close = 0, error = 0;
651
652	g_topology_assert();
653
654	sc = disk->d_softc;
655	cp = disk->d_consumer;
656	KASSERT(cp != NULL, ("NULL consumer (%s).", sc->sc_name));
657	KASSERT(cp->provider != NULL, ("NULL provider (%s).", sc->sc_name));
658	length = cp->provider->sectorsize;
659	offset = cp->provider->mediasize - length;
660	sector = malloc((size_t)length, M_MIRROR, M_WAITOK);
661	/*
662	 * Open consumer if it wasn't opened and remember to close it.
663	 */
664	if ((disk->d_flags & G_MIRROR_DISK_FLAG_DIRTY) == 0) {
665		error = g_access(cp, 0, 1, 1);
666		G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d",
667		    cp->provider->name, 0, 1, 1, error);
668		if (error == 0)
669			close = 1;
670#ifdef	INVARIANTS
671	} else {
672		KASSERT(cp->acw > 0 && cp->ace > 0,
673		    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name,
674		    cp->acr, cp->acw, cp->ace));
675#endif
676	}
677	if (error == 0) {
678		g_mirror_fill_metadata(sc, disk, &md);
679		mirror_metadata_encode(&md, sector);
680		g_topology_unlock();
681		error = g_write_data(cp, offset, sector, length);
682		g_topology_lock();
683	}
684	free(sector, M_MIRROR);
685	if (close) {
686		g_access(cp, 0, -1, -1);
687		G_MIRROR_DEBUG(2, "Access %s r%dw%de%d = %d",
688		    cp->provider->name, 0, -1, -1, 0);
689	}
690	if (error != 0) {
691		G_MIRROR_DEBUG(0,
692		    "Cannot update metadata on disk %s (error=%d).",
693		    g_mirror_get_diskname(disk), error);
694		disk->d_softc->sc_bump_syncid = G_MIRROR_BUMP_IMMEDIATELY;
695		g_mirror_event_send(disk, G_MIRROR_DISK_STATE_DISCONNECTED,
696		    G_MIRROR_EVENT_DONTWAIT);
697		return;
698	}
699	G_MIRROR_DEBUG(2, "Metadata on %s updated.",
700	    g_mirror_get_diskname(disk));
701}
702
703static void
704g_mirror_bump_syncid(struct g_mirror_softc *sc)
705{
706	struct g_mirror_disk *disk;
707
708	g_topology_assert();
709	KASSERT(g_mirror_ndisks(sc, G_MIRROR_DISK_STATE_ACTIVE) > 0,
710	    ("%s called with no active disks (device=%s).", __func__,
711	    sc->sc_name));
712
713	sc->sc_syncid++;
714	G_MIRROR_DEBUG(1, "Device %s: syncid bumped to %u.", sc->sc_name,
715	    sc->sc_syncid);
716	LIST_FOREACH(disk, &sc->sc_disks, d_next) {
717		if (disk->d_state == G_MIRROR_DISK_STATE_ACTIVE ||
718		    disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING) {
719			disk->d_sync.ds_syncid = sc->sc_syncid;
720			g_mirror_update_metadata(disk);
721		}
722	}
723}
724
725static __inline int
726bintime_cmp(struct bintime *bt1, struct bintime *bt2)
727{
728
729	if (bt1->sec < bt2->sec)
730		return (-1);
731	else if (bt1->sec > bt2->sec)
732		return (1);
733	if (bt1->frac < bt2->frac)
734		return (-1);
735	else if (bt1->frac > bt2->frac)
736		return (1);
737	return (0);
738}
739
740static void
741g_mirror_update_delay(struct g_mirror_disk *disk, struct bio *bp)
742{
743
744	if (disk->d_softc->sc_balance != G_MIRROR_BALANCE_LOAD)
745		return;
746	binuptime(&disk->d_delay);
747	bintime_sub(&disk->d_delay, &bp->bio_t0);
748}
749
750static void
751g_mirror_done(struct bio *bp)
752{
753	struct g_mirror_softc *sc;
754
755	sc = bp->bio_from->geom->softc;
756	bp->bio_cflags |= G_MIRROR_BIO_FLAG_REGULAR;
757	mtx_lock(&sc->sc_queue_mtx);
758	bioq_disksort(&sc->sc_queue, bp);
759	wakeup(sc);
760	mtx_unlock(&sc->sc_queue_mtx);
761}
762
763static void
764g_mirror_regular_request(struct bio *bp)
765{
766	struct g_mirror_softc *sc;
767	struct g_mirror_disk *disk;
768	struct bio *pbp;
769
770	g_topology_assert_not();
771
772	pbp = bp->bio_parent;
773	sc = pbp->bio_to->geom->softc;
774	disk = bp->bio_from->private;
775	if (disk == NULL) {
776		g_topology_lock();
777		g_mirror_kill_consumer(sc, bp->bio_from);
778		g_topology_unlock();
779	} else {
780		g_mirror_update_delay(disk, bp);
781	}
782
783	pbp->bio_inbed++;
784	KASSERT(pbp->bio_inbed <= pbp->bio_children,
785	    ("bio_inbed (%u) is bigger than bio_children (%u).", pbp->bio_inbed,
786	    pbp->bio_children));
787	if (bp->bio_error == 0 && pbp->bio_error == 0) {
788		G_MIRROR_LOGREQ(3, bp, "Request delivered.");
789		g_destroy_bio(bp);
790		if (pbp->bio_children == pbp->bio_inbed) {
791			G_MIRROR_LOGREQ(3, pbp, "Request delivered.");
792			pbp->bio_completed = pbp->bio_length;
793			g_io_deliver(pbp, pbp->bio_error);
794		}
795		return;
796	} else if (bp->bio_error != 0) {
797		if (pbp->bio_error == 0)
798			pbp->bio_error = bp->bio_error;
799		G_MIRROR_LOGREQ(0, bp, "Request failed (error=%d).",
800		    bp->bio_error);
801		if (disk != NULL) {
802			sc->sc_bump_syncid = G_MIRROR_BUMP_IMMEDIATELY;
803			g_mirror_event_send(disk,
804			    G_MIRROR_DISK_STATE_DISCONNECTED,
805			    G_MIRROR_EVENT_DONTWAIT);
806		}
807		switch (pbp->bio_cmd) {
808		case BIO_DELETE:
809		case BIO_WRITE:
810			pbp->bio_inbed--;
811			pbp->bio_children--;
812			break;
813		}
814	}
815	g_destroy_bio(bp);
816
817	switch (pbp->bio_cmd) {
818	case BIO_READ:
819		if (pbp->bio_children == pbp->bio_inbed) {
820			pbp->bio_error = 0;
821			mtx_lock(&sc->sc_queue_mtx);
822			bioq_disksort(&sc->sc_queue, pbp);
823			G_MIRROR_DEBUG(4, "%s: Waking up %p.", __func__, sc);
824			wakeup(sc);
825			mtx_unlock(&sc->sc_queue_mtx);
826		}
827		break;
828	case BIO_DELETE:
829	case BIO_WRITE:
830		if (pbp->bio_children == 0) {
831			/*
832			 * All requests failed.
833			 */
834		} else if (pbp->bio_inbed < pbp->bio_children) {
835			/* Do nothing. */
836			break;
837		} else if (pbp->bio_children == pbp->bio_inbed) {
838			/* Some requests succeeded. */
839			pbp->bio_error = 0;
840			pbp->bio_completed = pbp->bio_length;
841		}
842		g_io_deliver(pbp, pbp->bio_error);
843		break;
844	default:
845		KASSERT(1 == 0, ("Invalid request: %u.", pbp->bio_cmd));
846		break;
847	}
848}
849
850static void
851g_mirror_sync_done(struct bio *bp)
852{
853	struct g_mirror_softc *sc;
854
855	G_MIRROR_LOGREQ(3, bp, "Synchronization request delivered.");
856	sc = bp->bio_from->geom->softc;
857	bp->bio_cflags |= G_MIRROR_BIO_FLAG_SYNC;
858	mtx_lock(&sc->sc_queue_mtx);
859	bioq_disksort(&sc->sc_queue, bp);
860	wakeup(sc);
861	mtx_unlock(&sc->sc_queue_mtx);
862}
863
864static void
865g_mirror_start(struct bio *bp)
866{
867	struct g_mirror_softc *sc;
868
869	sc = bp->bio_to->geom->softc;
870	/*
871	 * If sc == NULL or there are no valid disks, provider's error
872	 * should be set and g_mirror_start() should not be called at all.
873	 */
874	KASSERT(sc != NULL && sc->sc_state == G_MIRROR_DEVICE_STATE_RUNNING,
875	    ("Provider's error should be set (error=%d)(mirror=%s).",
876	    bp->bio_to->error, bp->bio_to->name));
877	G_MIRROR_LOGREQ(3, bp, "Request received.");
878
879	switch (bp->bio_cmd) {
880	case BIO_READ:
881	case BIO_WRITE:
882	case BIO_DELETE:
883		break;
884	case BIO_GETATTR:
885	default:
886		g_io_deliver(bp, EOPNOTSUPP);
887		return;
888	}
889	mtx_lock(&sc->sc_queue_mtx);
890	bioq_disksort(&sc->sc_queue, bp);
891	G_MIRROR_DEBUG(4, "%s: Waking up %p.", __func__, sc);
892	wakeup(sc);
893	mtx_unlock(&sc->sc_queue_mtx);
894}
895
896/*
897 * Send one synchronization request.
898 */
899static void
900g_mirror_sync_one(struct g_mirror_disk *disk)
901{
902	struct g_mirror_softc *sc;
903	struct bio *bp;
904
905	sc = disk->d_softc;
906	KASSERT(disk->d_state == G_MIRROR_DISK_STATE_SYNCHRONIZING,
907	    ("Disk %s is not marked for synchronization.",
908	    g_mirror_get_diskname(disk)));
909
910	bp = g_new_bio();
911	if (bp == NULL)
912		return;
913	bp->bio_parent = NULL;
914	bp->bio_cmd = BIO_READ;
915	bp->bio_offset = disk->d_sync.ds_offset;
916	bp->bio_length = MIN(sc->sc_sync.ds_block,
917	    sc->sc_mediasize - bp->bio_offset);
918	bp->bio_cflags = 0;
919	bp->bio_done = g_mirror_sync_done;
920	bp->bio_data = uma_zalloc(sc->sc_sync.ds_zone, M_NOWAIT | M_ZERO);
921	if (bp->bio_data == NULL) {
922		g_destroy_bio(bp);
923		return;
924	}
925	disk->d_sync.ds_offset += bp->bio_length;
926	bp->bio_to = sc->sc_provider;
927	G_MIRROR_LOGREQ(3, bp, "Sending synchronization request.");
928	g_io_request(bp, disk->d_sync.ds_consumer);
929}
930
931static void
932g_mirror_sync_request(struct bio *bp)
933{
934	struct g_mirror_softc *sc;
935	struct g_mirror_disk *disk;
936
937	sc = bp->bio_from->geom->softc;
938	disk = bp->bio_from->private;
939	if (disk == NULL) {
940		g_topology_lock();
941		g_mirror_kill_consumer(sc, bp->bio_from);
942		g_topology_unlock();
943		uma_zfree(sc->sc_sync.ds_zone, bp->bio_data);
944		g_destroy_bio(bp);
945		return;
946	}
947
948	/*
949	 * Synchronization request.
950	 */
951	switch (bp->bio_cmd) {
952	case BIO_READ:
953	    {
954		struct g_consumer *cp;
955
956		if (bp->bio_error != 0) {
957			G_MIRROR_LOGREQ(0, bp,
958			    "Synchronization request failed (error=%d).",
959			    bp->bio_error);
960			uma_zfree(sc->sc_sync.ds_zone, bp->bio_data);
961			g_destroy_bio(bp);
962			return;
963		}
964		bp->bio_cmd = BIO_WRITE;
965		bp->bio_cflags = 0;
966		G_MIRROR_LOGREQ(3, bp, "Synchronization request finished.");
967		cp = disk->d_consumer;
968		KASSERT(cp->acr == 0 && cp->acw == 1 && cp->ace == 1,
969		    ("Consumer %s not opened (r%dw%de%d).", cp->provider->name,
970		    cp->acr, cp->acw, cp->ace));
971		g_io_request(bp, cp);
972		return;
973	    }
974	case BIO_WRITE:
975		uma_zfree(sc->sc_sync.ds_zone, bp->bio_data);
976		if (bp->bio_error != 0) {
977			G_MIRROR_LOGREQ(0, bp,
978			    "Synchronization request failed (error=%d).",
979			    bp->bio_error);
980			g_destroy_bio(bp);
981			sc->sc_bump_syncid = G_MIRROR_BUMP_IMMEDIATELY;
982			g_mirror_event_send(disk,
983			    G_MIRROR_DISK_STATE_DISCONNECTED,
984			    G_MIRROR_EVENT_DONTWAIT);
985			return;
986		}
987		G_MIRROR_LOGREQ(3, bp, "Synchronization request finished.");
988		disk->d_sync.ds_offset_done = bp->bio_offset + bp->bio_length;
989		g_destroy_bio(bp);
990		if (disk->d_sync.ds_offset_done == 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