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