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