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