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