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