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