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