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