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