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