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