xref: /freebsd/sys/geom/raid3/g_raid3.c (revision 263d6a7ece4f357d01b3152c39e5d36043f877bb)
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 	g_topology_lock();
1692 	if (!g_raid3_can_destroy(sc)) {
1693 		g_topology_unlock();
1694 		return (0);
1695 	}
1696 	if ((sc->sc_flags & G_RAID3_DEVICE_FLAG_WAIT) != 0) {
1697 		g_topology_unlock();
1698 		G_RAID3_DEBUG(4, "%s: Waking up %p.", __func__,
1699 		    &sc->sc_worker);
1700 		wakeup(&sc->sc_worker);
1701 		sc->sc_worker = NULL;
1702 	} else {
1703 		g_raid3_destroy_device(sc);
1704 		g_topology_unlock();
1705 		free(sc->sc_disks, M_RAID3);
1706 		free(sc, M_RAID3);
1707 	}
1708 	return (1);
1709 }
1710 
1711 /*
1712  * Worker thread.
1713  */
1714 static void
1715 g_raid3_worker(void *arg)
1716 {
1717 	struct g_raid3_softc *sc;
1718 	struct g_raid3_disk *disk;
1719 	struct g_raid3_disk_sync *sync;
1720 	struct g_raid3_event *ep;
1721 	struct bio *bp;
1722 	u_int nreqs;
1723 
1724 	sc = arg;
1725 	mtx_lock_spin(&sched_lock);
1726 	sched_prio(curthread, PRIBIO);
1727 	mtx_unlock_spin(&sched_lock);
1728 
1729 	nreqs = 0;
1730 	for (;;) {
1731 		G_RAID3_DEBUG(5, "%s: Let's see...", __func__);
1732 		/*
1733 		 * First take a look at events.
1734 		 * This is important to handle events before any I/O requests.
1735 		 */
1736 		ep = g_raid3_event_get(sc);
1737 		if (ep != NULL && g_topology_try_lock()) {
1738 			g_raid3_event_remove(sc, ep);
1739 			if ((ep->e_flags & G_RAID3_EVENT_DEVICE) != 0) {
1740 				/* Update only device status. */
1741 				G_RAID3_DEBUG(3,
1742 				    "Running event for device %s.",
1743 				    sc->sc_name);
1744 				ep->e_error = 0;
1745 				g_raid3_update_device(sc, 1);
1746 			} else {
1747 				/* Update disk status. */
1748 				G_RAID3_DEBUG(3, "Running event for disk %s.",
1749 				     g_raid3_get_diskname(ep->e_disk));
1750 				ep->e_error = g_raid3_update_disk(ep->e_disk,
1751 				    ep->e_state);
1752 				if (ep->e_error == 0)
1753 					g_raid3_update_device(sc, 0);
1754 			}
1755 			g_topology_unlock();
1756 			if ((ep->e_flags & G_RAID3_EVENT_DONTWAIT) != 0) {
1757 				KASSERT(ep->e_error == 0,
1758 				    ("Error cannot be handled."));
1759 				g_raid3_event_free(ep);
1760 			} else {
1761 				ep->e_flags |= G_RAID3_EVENT_DONE;
1762 				G_RAID3_DEBUG(4, "%s: Waking up %p.", __func__,
1763 				    ep);
1764 				mtx_lock(&sc->sc_events_mtx);
1765 				wakeup(ep);
1766 				mtx_unlock(&sc->sc_events_mtx);
1767 			}
1768 			if ((sc->sc_flags &
1769 			    G_RAID3_DEVICE_FLAG_DESTROY) != 0) {
1770 				if (g_raid3_try_destroy(sc))
1771 					kthread_exit(0);
1772 			}
1773 			G_RAID3_DEBUG(5, "%s: I'm here 1.", __func__);
1774 			continue;
1775 		}
1776 		/*
1777 		 * Now I/O requests.
1778 		 */
1779 		/* Get first request from the queue. */
1780 		mtx_lock(&sc->sc_queue_mtx);
1781 		bp = bioq_first(&sc->sc_queue);
1782 		if (bp == NULL) {
1783 			if (ep != NULL) {
1784 				/*
1785 				 * No I/O requests and topology lock was
1786 				 * already held? Try again.
1787 				 */
1788 				mtx_unlock(&sc->sc_queue_mtx);
1789 				tsleep(ep, PRIBIO, "r3:top1", hz / 5);
1790 				continue;
1791 			}
1792 			if ((sc->sc_flags &
1793 			    G_RAID3_DEVICE_FLAG_DESTROY) != 0) {
1794 				mtx_unlock(&sc->sc_queue_mtx);
1795 				if (g_raid3_try_destroy(sc))
1796 					kthread_exit(0);
1797 				mtx_lock(&sc->sc_queue_mtx);
1798 			}
1799 		}
1800 		if (sc->sc_syncdisk != NULL &&
1801 		    (bp == NULL || nreqs > g_raid3_reqs_per_sync)) {
1802 			mtx_unlock(&sc->sc_queue_mtx);
1803 			/*
1804 			 * It is time for synchronization...
1805 			 */
1806 			nreqs = 0;
1807 			disk = sc->sc_syncdisk;
1808 			sync = &disk->d_sync;
1809 			if (sync->ds_offset <
1810 			    sc->sc_mediasize / (sc->sc_ndisks - 1) &&
1811 			    sync->ds_offset == sync->ds_offset_done) {
1812 				if (sync->ds_resync != -1) {
1813 					sync->ds_offset = sync->ds_resync;
1814 					sync->ds_offset_done = sync->ds_resync;
1815 					sync->ds_resync = -1;
1816 				}
1817 				g_raid3_sync_one(sc);
1818 			}
1819 			G_RAID3_DEBUG(5, "%s: I'm here 2.", __func__);
1820 			goto sleep;
1821 		}
1822 		if (bp == NULL) {
1823 			if (g_raid3_check_idle(sc)) {
1824 				u_int idletime;
1825 
1826 				idletime = g_raid3_idletime;
1827 				if (idletime == 0)
1828 					idletime = 1;
1829 				idletime *= hz;
1830 				if (msleep(sc, &sc->sc_queue_mtx, PRIBIO | PDROP,
1831 				    "r3:w1", idletime) == EWOULDBLOCK) {
1832 					G_RAID3_DEBUG(5, "%s: I'm here 3.",
1833 					    __func__);
1834 					/*
1835 					 * No I/O requests in 'idletime'
1836 					 * seconds, so mark components as clean.
1837 					 */
1838 					g_raid3_idle(sc);
1839 				}
1840 				G_RAID3_DEBUG(5, "%s: I'm here 4.", __func__);
1841 			} else {
1842 				MSLEEP(sc, &sc->sc_queue_mtx, PRIBIO | PDROP,
1843 				    "r3:w2", 0);
1844 				G_RAID3_DEBUG(5, "%s: I'm here 5.", __func__);
1845 			}
1846 			continue;
1847 		}
1848 		nreqs++;
1849 		bioq_remove(&sc->sc_queue, bp);
1850 		mtx_unlock(&sc->sc_queue_mtx);
1851 
1852 		if ((bp->bio_cflags & G_RAID3_BIO_CFLAG_REGULAR) != 0) {
1853 			g_raid3_regular_request(bp);
1854 		} else if ((bp->bio_cflags & G_RAID3_BIO_CFLAG_SYNC) != 0) {
1855 			u_int timeout, sps;
1856 
1857 			g_raid3_sync_request(bp);
1858 sleep:
1859 			sps = atomic_load_acq_int(&g_raid3_syncs_per_sec);
1860 			if (sps == 0) {
1861 				G_RAID3_DEBUG(5, "%s: I'm here 6.", __func__);
1862 				continue;
1863 			}
1864 			if (ep != NULL) {
1865 				/*
1866 				 * We have some pending events, don't sleep now.
1867 				 */
1868 				G_RAID3_DEBUG(5, "%s: I'm here 7.", __func__);
1869 				tsleep(ep, PRIBIO, "r3:top2", hz / 5);
1870 				continue;
1871 			}
1872 			mtx_lock(&sc->sc_queue_mtx);
1873 			if (bioq_first(&sc->sc_queue) != NULL) {
1874 				mtx_unlock(&sc->sc_queue_mtx);
1875 				G_RAID3_DEBUG(5, "%s: I'm here 8.", __func__);
1876 				continue;
1877 			}
1878 			timeout = hz / sps;
1879 			if (timeout == 0)
1880 				timeout = 1;
1881 			MSLEEP(sc, &sc->sc_queue_mtx, PRIBIO | PDROP, "r3:w2",
1882 			    timeout);
1883 		} else {
1884 			if (g_raid3_register_request(bp) != 0) {
1885 				mtx_lock(&sc->sc_queue_mtx);
1886 				bioq_insert_tail(&sc->sc_queue, bp);
1887 				MSLEEP(&sc->sc_queue, &sc->sc_queue_mtx,
1888 				    PRIBIO | PDROP, "r3:lowmem", hz / 10);
1889 			}
1890 		}
1891 		G_RAID3_DEBUG(5, "%s: I'm here 9.", __func__);
1892 	}
1893 }
1894 
1895 /*
1896  * Open disk's consumer if needed.
1897  */
1898 static void
1899 g_raid3_update_access(struct g_raid3_disk *disk)
1900 {
1901 	struct g_provider *pp;
1902 
1903 	g_topology_assert();
1904 
1905 	pp = disk->d_softc->sc_provider;
1906 	if (pp == NULL)
1907 		return;
1908 	if (pp->acw > 0) {
1909 		if ((disk->d_flags & G_RAID3_DISK_FLAG_DIRTY) == 0) {
1910 			G_RAID3_DEBUG(1, "Disk %s (device %s) marked as dirty.",
1911 			    g_raid3_get_diskname(disk), disk->d_softc->sc_name);
1912 			disk->d_flags |= G_RAID3_DISK_FLAG_DIRTY;
1913 		}
1914 	} else if (pp->acw == 0) {
1915 		if ((disk->d_flags & G_RAID3_DISK_FLAG_DIRTY) != 0) {
1916 			G_RAID3_DEBUG(1, "Disk %s (device %s) marked as clean.",
1917 			    g_raid3_get_diskname(disk), disk->d_softc->sc_name);
1918 			disk->d_flags &= ~G_RAID3_DISK_FLAG_DIRTY;
1919 		}
1920 	}
1921 }
1922 
1923 static void
1924 g_raid3_sync_start(struct g_raid3_softc *sc)
1925 {
1926 	struct g_raid3_disk *disk;
1927 	int error;
1928 	u_int n;
1929 
1930 	g_topology_assert();
1931 
1932 	KASSERT(sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED,
1933 	    ("Device not in DEGRADED state (%s, %u).", sc->sc_name,
1934 	    sc->sc_state));
1935 	KASSERT(sc->sc_syncdisk == NULL, ("Syncdisk is not NULL (%s, %u).",
1936 	    sc->sc_name, sc->sc_state));
1937 	disk = NULL;
1938 	for (n = 0; n < sc->sc_ndisks; n++) {
1939 		if (sc->sc_disks[n].d_state != G_RAID3_DISK_STATE_SYNCHRONIZING)
1940 			continue;
1941 		disk = &sc->sc_disks[n];
1942 		break;
1943 	}
1944 	if (disk == NULL)
1945 		return;
1946 
1947 	G_RAID3_DEBUG(0, "Device %s: rebuilding provider %s.", sc->sc_name,
1948 	    g_raid3_get_diskname(disk));
1949 	disk->d_flags |= G_RAID3_DISK_FLAG_DIRTY;
1950 	KASSERT(disk->d_sync.ds_consumer == NULL,
1951 	    ("Sync consumer already exists (device=%s, disk=%s).",
1952 	    sc->sc_name, g_raid3_get_diskname(disk)));
1953 	disk->d_sync.ds_consumer = g_new_consumer(sc->sc_sync.ds_geom);
1954 	disk->d_sync.ds_consumer->private = disk;
1955 	disk->d_sync.ds_consumer->index = 0;
1956 	error = g_attach(disk->d_sync.ds_consumer, disk->d_softc->sc_provider);
1957 	KASSERT(error == 0, ("Cannot attach to %s (error=%d).",
1958 	    disk->d_softc->sc_name, error));
1959 	error = g_access(disk->d_sync.ds_consumer, 1, 0, 0);
1960 	KASSERT(error == 0, ("Cannot open %s (error=%d).",
1961 	    disk->d_softc->sc_name, error));
1962 	disk->d_sync.ds_data = malloc(MAXPHYS, M_RAID3, M_WAITOK);
1963 	sc->sc_syncdisk = disk;
1964 }
1965 
1966 /*
1967  * Stop synchronization process.
1968  * type: 0 - synchronization finished
1969  *       1 - synchronization stopped
1970  */
1971 static void
1972 g_raid3_sync_stop(struct g_raid3_softc *sc, int type)
1973 {
1974 	struct g_raid3_disk *disk;
1975 
1976 	g_topology_assert();
1977 	KASSERT(sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED,
1978 	    ("Device not in DEGRADED state (%s, %u).", sc->sc_name,
1979 	    sc->sc_state));
1980 	disk = sc->sc_syncdisk;
1981 	sc->sc_syncdisk = NULL;
1982 	KASSERT(disk != NULL, ("No disk was synchronized (%s).", sc->sc_name));
1983 	KASSERT(disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING,
1984 	    ("Wrong disk state (%s, %s).", g_raid3_get_diskname(disk),
1985 	    g_raid3_disk_state2str(disk->d_state)));
1986 	if (disk->d_sync.ds_consumer == NULL)
1987 		return;
1988 
1989 	if (type == 0) {
1990 		G_RAID3_DEBUG(0, "Device %s: rebuilding provider %s finished.",
1991 		    disk->d_softc->sc_name, g_raid3_get_diskname(disk));
1992 	} else /* if (type == 1) */ {
1993 		G_RAID3_DEBUG(0, "Device %s: rebuilding provider %s stopped.",
1994 		    disk->d_softc->sc_name, g_raid3_get_diskname(disk));
1995 	}
1996 	g_raid3_kill_consumer(disk->d_softc, disk->d_sync.ds_consumer);
1997 	free(disk->d_sync.ds_data, M_RAID3);
1998 	disk->d_sync.ds_consumer = NULL;
1999 	disk->d_flags &= ~G_RAID3_DISK_FLAG_DIRTY;
2000 }
2001 
2002 static void
2003 g_raid3_launch_provider(struct g_raid3_softc *sc)
2004 {
2005 	struct g_provider *pp;
2006 
2007 	g_topology_assert();
2008 
2009 	pp = g_new_providerf(sc->sc_geom, "raid3/%s", sc->sc_name);
2010 	pp->mediasize = sc->sc_mediasize;
2011 	pp->sectorsize = sc->sc_sectorsize;
2012 	sc->sc_provider = pp;
2013 	g_error_provider(pp, 0);
2014 	G_RAID3_DEBUG(0, "Device %s: provider %s launched.", sc->sc_name,
2015 	    pp->name);
2016 	if (sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED)
2017 		g_raid3_sync_start(sc);
2018 }
2019 
2020 static void
2021 g_raid3_destroy_provider(struct g_raid3_softc *sc)
2022 {
2023 	struct bio *bp;
2024 
2025 	g_topology_assert();
2026 	KASSERT(sc->sc_provider != NULL, ("NULL provider (device=%s).",
2027 	    sc->sc_name));
2028 
2029 	g_error_provider(sc->sc_provider, ENXIO);
2030 	mtx_lock(&sc->sc_queue_mtx);
2031 	while ((bp = bioq_first(&sc->sc_queue)) != NULL) {
2032 		bioq_remove(&sc->sc_queue, bp);
2033 		g_io_deliver(bp, ENXIO);
2034 	}
2035 	mtx_unlock(&sc->sc_queue_mtx);
2036 	G_RAID3_DEBUG(0, "Device %s: provider %s destroyed.", sc->sc_name,
2037 	    sc->sc_provider->name);
2038 	sc->sc_provider->flags |= G_PF_WITHER;
2039 	g_orphan_provider(sc->sc_provider, ENXIO);
2040 	sc->sc_provider = NULL;
2041 	if (sc->sc_syncdisk != NULL)
2042 		g_raid3_sync_stop(sc, 1);
2043 }
2044 
2045 static void
2046 g_raid3_go(void *arg)
2047 {
2048 	struct g_raid3_softc *sc;
2049 
2050 	sc = arg;
2051 	G_RAID3_DEBUG(0, "Force device %s start due to timeout.", sc->sc_name);
2052 	g_raid3_event_send(sc, 0,
2053 	    G_RAID3_EVENT_DONTWAIT | G_RAID3_EVENT_DEVICE);
2054 }
2055 
2056 static u_int
2057 g_raid3_determine_state(struct g_raid3_disk *disk)
2058 {
2059 	struct g_raid3_softc *sc;
2060 	u_int state;
2061 
2062 	sc = disk->d_softc;
2063 	if (sc->sc_syncid == disk->d_sync.ds_syncid) {
2064 		if ((disk->d_flags &
2065 		    G_RAID3_DISK_FLAG_SYNCHRONIZING) == 0) {
2066 			/* Disk does not need synchronization. */
2067 			state = G_RAID3_DISK_STATE_ACTIVE;
2068 		} else {
2069 			if ((sc->sc_flags &
2070 			     G_RAID3_DEVICE_FLAG_NOAUTOSYNC) == 0  ||
2071 			    (disk->d_flags &
2072 			     G_RAID3_DISK_FLAG_FORCE_SYNC) != 0) {
2073 				/*
2074 				 * We can start synchronization from
2075 				 * the stored offset.
2076 				 */
2077 				state = G_RAID3_DISK_STATE_SYNCHRONIZING;
2078 			} else {
2079 				state = G_RAID3_DISK_STATE_STALE;
2080 			}
2081 		}
2082 	} else if (disk->d_sync.ds_syncid < sc->sc_syncid) {
2083 		/*
2084 		 * Reset all synchronization data for this disk,
2085 		 * because if it even was synchronized, it was
2086 		 * synchronized to disks with different syncid.
2087 		 */
2088 		disk->d_flags |= G_RAID3_DISK_FLAG_SYNCHRONIZING;
2089 		disk->d_sync.ds_offset = 0;
2090 		disk->d_sync.ds_offset_done = 0;
2091 		disk->d_sync.ds_syncid = sc->sc_syncid;
2092 		if ((sc->sc_flags & G_RAID3_DEVICE_FLAG_NOAUTOSYNC) == 0 ||
2093 		    (disk->d_flags & G_RAID3_DISK_FLAG_FORCE_SYNC) != 0) {
2094 			state = G_RAID3_DISK_STATE_SYNCHRONIZING;
2095 		} else {
2096 			state = G_RAID3_DISK_STATE_STALE;
2097 		}
2098 	} else /* if (sc->sc_syncid < disk->d_sync.ds_syncid) */ {
2099 		/*
2100 		 * Not good, NOT GOOD!
2101 		 * It means that device was started on stale disks
2102 		 * and more fresh disk just arrive.
2103 		 * If there were writes, device is fucked up, sorry.
2104 		 * I think the best choice here is don't touch
2105 		 * this disk and inform the user laudly.
2106 		 */
2107 		G_RAID3_DEBUG(0, "Device %s was started before the freshest "
2108 		    "disk (%s) arrives!! It will not be connected to the "
2109 		    "running device.", sc->sc_name,
2110 		    g_raid3_get_diskname(disk));
2111 		g_raid3_destroy_disk(disk);
2112 		state = G_RAID3_DISK_STATE_NONE;
2113 		/* Return immediately, because disk was destroyed. */
2114 		return (state);
2115 	}
2116 	G_RAID3_DEBUG(3, "State for %s disk: %s.",
2117 	    g_raid3_get_diskname(disk), g_raid3_disk_state2str(state));
2118 	return (state);
2119 }
2120 
2121 /*
2122  * Update device state.
2123  */
2124 static void
2125 g_raid3_update_device(struct g_raid3_softc *sc, boolean_t force)
2126 {
2127 	struct g_raid3_disk *disk;
2128 	u_int state;
2129 
2130 	g_topology_assert();
2131 
2132 	switch (sc->sc_state) {
2133 	case G_RAID3_DEVICE_STATE_STARTING:
2134 	    {
2135 		u_int n, ndirty, ndisks, genid, syncid;
2136 
2137 		KASSERT(sc->sc_provider == NULL,
2138 		    ("Non-NULL provider in STARTING state (%s).", sc->sc_name));
2139 		/*
2140 		 * Are we ready? We are, if all disks are connected or
2141 		 * one disk is missing and 'force' is true.
2142 		 */
2143 		if (g_raid3_ndisks(sc, -1) + force == sc->sc_ndisks) {
2144 			if (!force)
2145 				callout_drain(&sc->sc_callout);
2146 		} else {
2147 			if (force) {
2148 				/*
2149 				 * Timeout expired, so destroy device.
2150 				 */
2151 				sc->sc_flags |= G_RAID3_DEVICE_FLAG_DESTROY;
2152 			}
2153 			return;
2154 		}
2155 
2156 		/*
2157 		 * Find the biggest genid.
2158 		 */
2159 		genid = 0;
2160 		for (n = 0; n < sc->sc_ndisks; n++) {
2161 			disk = &sc->sc_disks[n];
2162 			if (disk->d_state == G_RAID3_DISK_STATE_NODISK)
2163 				continue;
2164 			if (disk->d_genid > genid)
2165 				genid = disk->d_genid;
2166 		}
2167 		sc->sc_genid = genid;
2168 		/*
2169 		 * Remove all disks without the biggest genid.
2170 		 */
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 				G_RAID3_DEBUG(0,
2177 				    "Component %s (device %s) broken, skipping.",
2178 				    g_raid3_get_diskname(disk), sc->sc_name);
2179 				g_raid3_destroy_disk(disk);
2180 			}
2181 		}
2182 
2183 		/*
2184 		 * There must be at least 'sc->sc_ndisks - 1' components
2185 		 * with the same syncid and without SYNCHRONIZING flag.
2186 		 */
2187 
2188 		/*
2189 		 * Find the biggest syncid, number of valid components and
2190 		 * number of dirty components.
2191 		 */
2192 		ndirty = ndisks = syncid = 0;
2193 		for (n = 0; n < sc->sc_ndisks; n++) {
2194 			disk = &sc->sc_disks[n];
2195 			if (disk->d_state == G_RAID3_DISK_STATE_NODISK)
2196 				continue;
2197 			if ((disk->d_flags & G_RAID3_DISK_FLAG_DIRTY) != 0)
2198 				ndirty++;
2199 			if (disk->d_sync.ds_syncid > syncid) {
2200 				syncid = disk->d_sync.ds_syncid;
2201 				ndisks = 0;
2202 			} else if (disk->d_sync.ds_syncid < syncid) {
2203 				continue;
2204 			}
2205 			if ((disk->d_flags &
2206 			    G_RAID3_DISK_FLAG_SYNCHRONIZING) != 0) {
2207 				continue;
2208 			}
2209 			ndisks++;
2210 		}
2211 		/*
2212 		 * Do we have enough valid components?
2213 		 */
2214 		if (ndisks + 1 < sc->sc_ndisks) {
2215 			G_RAID3_DEBUG(0,
2216 			    "Device %s is broken, too few valid components.",
2217 			    sc->sc_name);
2218 			sc->sc_flags |= G_RAID3_DEVICE_FLAG_DESTROY;
2219 			return;
2220 		}
2221 		/*
2222 		 * If there is one DIRTY component and all disks are present,
2223 		 * mark it for synchronization. If there is more than one DIRTY
2224 		 * component, mark parity component for synchronization.
2225 		 */
2226 		if (ndisks == sc->sc_ndisks && ndirty == 1) {
2227 			for (n = 0; n < sc->sc_ndisks; n++) {
2228 				disk = &sc->sc_disks[n];
2229 				if ((disk->d_flags &
2230 				    G_RAID3_DISK_FLAG_DIRTY) == 0) {
2231 					continue;
2232 				}
2233 				disk->d_flags |=
2234 				    G_RAID3_DISK_FLAG_SYNCHRONIZING;
2235 			}
2236 		} else if (ndisks == sc->sc_ndisks && ndirty > 1) {
2237 			disk = &sc->sc_disks[sc->sc_ndisks - 1];
2238 			disk->d_flags |= G_RAID3_DISK_FLAG_SYNCHRONIZING;
2239 		}
2240 
2241 		sc->sc_syncid = syncid;
2242 		if (force) {
2243 			/* Remember to bump syncid on first write. */
2244 			sc->sc_bump_id |= G_RAID3_BUMP_SYNCID;
2245 		}
2246 		if (ndisks == sc->sc_ndisks)
2247 			state = G_RAID3_DEVICE_STATE_COMPLETE;
2248 		else /* if (ndisks == sc->sc_ndisks - 1) */
2249 			state = G_RAID3_DEVICE_STATE_DEGRADED;
2250 		G_RAID3_DEBUG(1, "Device %s state changed from %s to %s.",
2251 		    sc->sc_name, g_raid3_device_state2str(sc->sc_state),
2252 		    g_raid3_device_state2str(state));
2253 		sc->sc_state = state;
2254 		for (n = 0; n < sc->sc_ndisks; n++) {
2255 			disk = &sc->sc_disks[n];
2256 			if (disk->d_state == G_RAID3_DISK_STATE_NODISK)
2257 				continue;
2258 			state = g_raid3_determine_state(disk);
2259 			g_raid3_event_send(disk, state, G_RAID3_EVENT_DONTWAIT);
2260 			if (state == G_RAID3_DISK_STATE_STALE)
2261 				sc->sc_bump_id |= G_RAID3_BUMP_SYNCID;
2262 		}
2263 		break;
2264 	    }
2265 	case G_RAID3_DEVICE_STATE_DEGRADED:
2266 		/*
2267 		 * Genid need to be bumped immediately, so do it here.
2268 		 */
2269 		if ((sc->sc_bump_id & G_RAID3_BUMP_GENID) != 0) {
2270 			sc->sc_bump_id &= ~G_RAID3_BUMP_GENID;
2271 			g_raid3_bump_genid(sc);
2272 		}
2273 
2274 		if (g_raid3_ndisks(sc, G_RAID3_DISK_STATE_NEW) > 0)
2275 			return;
2276 		if (g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE) <
2277 		    sc->sc_ndisks - 1) {
2278 			if (sc->sc_provider != NULL)
2279 				g_raid3_destroy_provider(sc);
2280 			sc->sc_flags |= G_RAID3_DEVICE_FLAG_DESTROY;
2281 			return;
2282 		}
2283 		if (g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE) ==
2284 		    sc->sc_ndisks) {
2285 			state = G_RAID3_DEVICE_STATE_COMPLETE;
2286 			G_RAID3_DEBUG(1,
2287 			    "Device %s state changed from %s to %s.",
2288 			    sc->sc_name, g_raid3_device_state2str(sc->sc_state),
2289 			    g_raid3_device_state2str(state));
2290 			sc->sc_state = state;
2291 		}
2292 		if (sc->sc_provider == NULL)
2293 			g_raid3_launch_provider(sc);
2294 		break;
2295 	case G_RAID3_DEVICE_STATE_COMPLETE:
2296 		/*
2297 		 * Genid need to be bumped immediately, so do it here.
2298 		 */
2299 		if ((sc->sc_bump_id & G_RAID3_BUMP_GENID) != 0) {
2300 			sc->sc_bump_id &= ~G_RAID3_BUMP_GENID;
2301 			g_raid3_bump_genid(sc);
2302 		}
2303 
2304 		if (g_raid3_ndisks(sc, G_RAID3_DISK_STATE_NEW) > 0)
2305 			return;
2306 		KASSERT(g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE) >=
2307 		    sc->sc_ndisks - 1,
2308 		    ("Too few ACTIVE components in COMPLETE state (device %s).",
2309 		    sc->sc_name));
2310 		if (g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE) ==
2311 		    sc->sc_ndisks - 1) {
2312 			state = G_RAID3_DEVICE_STATE_DEGRADED;
2313 			G_RAID3_DEBUG(1,
2314 			    "Device %s state changed from %s to %s.",
2315 			    sc->sc_name, g_raid3_device_state2str(sc->sc_state),
2316 			    g_raid3_device_state2str(state));
2317 			sc->sc_state = state;
2318 		}
2319 		if (sc->sc_provider == NULL)
2320 			g_raid3_launch_provider(sc);
2321 		break;
2322 	default:
2323 		KASSERT(1 == 0, ("Wrong device state (%s, %s).", sc->sc_name,
2324 		    g_raid3_device_state2str(sc->sc_state)));
2325 		break;
2326 	}
2327 }
2328 
2329 /*
2330  * Update disk state and device state if needed.
2331  */
2332 #define	DISK_STATE_CHANGED()	G_RAID3_DEBUG(1,			\
2333 	"Disk %s state changed from %s to %s (device %s).",		\
2334 	g_raid3_get_diskname(disk),					\
2335 	g_raid3_disk_state2str(disk->d_state),				\
2336 	g_raid3_disk_state2str(state), sc->sc_name)
2337 static int
2338 g_raid3_update_disk(struct g_raid3_disk *disk, u_int state)
2339 {
2340 	struct g_raid3_softc *sc;
2341 
2342 	g_topology_assert();
2343 
2344 	sc = disk->d_softc;
2345 again:
2346 	G_RAID3_DEBUG(3, "Changing disk %s state from %s to %s.",
2347 	    g_raid3_get_diskname(disk), g_raid3_disk_state2str(disk->d_state),
2348 	    g_raid3_disk_state2str(state));
2349 	switch (state) {
2350 	case G_RAID3_DISK_STATE_NEW:
2351 		/*
2352 		 * Possible scenarios:
2353 		 * 1. New disk arrive.
2354 		 */
2355 		/* Previous state should be NONE. */
2356 		KASSERT(disk->d_state == G_RAID3_DISK_STATE_NONE,
2357 		    ("Wrong disk state (%s, %s).", g_raid3_get_diskname(disk),
2358 		    g_raid3_disk_state2str(disk->d_state)));
2359 		DISK_STATE_CHANGED();
2360 
2361 		disk->d_state = state;
2362 		G_RAID3_DEBUG(0, "Device %s: provider %s detected.",
2363 		    sc->sc_name, g_raid3_get_diskname(disk));
2364 		if (sc->sc_state == G_RAID3_DEVICE_STATE_STARTING)
2365 			break;
2366 		KASSERT(sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED ||
2367 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE,
2368 		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2369 		    g_raid3_device_state2str(sc->sc_state),
2370 		    g_raid3_get_diskname(disk),
2371 		    g_raid3_disk_state2str(disk->d_state)));
2372 		state = g_raid3_determine_state(disk);
2373 		if (state != G_RAID3_DISK_STATE_NONE)
2374 			goto again;
2375 		break;
2376 	case G_RAID3_DISK_STATE_ACTIVE:
2377 		/*
2378 		 * Possible scenarios:
2379 		 * 1. New disk does not need synchronization.
2380 		 * 2. Synchronization process finished successfully.
2381 		 */
2382 		KASSERT(sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED ||
2383 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE,
2384 		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2385 		    g_raid3_device_state2str(sc->sc_state),
2386 		    g_raid3_get_diskname(disk),
2387 		    g_raid3_disk_state2str(disk->d_state)));
2388 		/* Previous state should be NEW or SYNCHRONIZING. */
2389 		KASSERT(disk->d_state == G_RAID3_DISK_STATE_NEW ||
2390 		    disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING,
2391 		    ("Wrong disk state (%s, %s).", g_raid3_get_diskname(disk),
2392 		    g_raid3_disk_state2str(disk->d_state)));
2393 		DISK_STATE_CHANGED();
2394 
2395 		if (disk->d_state == G_RAID3_DISK_STATE_NEW)
2396 			disk->d_flags &= ~G_RAID3_DISK_FLAG_DIRTY;
2397 		else if (disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING) {
2398 			disk->d_flags &= ~G_RAID3_DISK_FLAG_SYNCHRONIZING;
2399 			disk->d_flags &= ~G_RAID3_DISK_FLAG_FORCE_SYNC;
2400 			g_raid3_sync_stop(sc, 0);
2401 		}
2402 		disk->d_state = state;
2403 		disk->d_sync.ds_offset = 0;
2404 		disk->d_sync.ds_offset_done = 0;
2405 		g_raid3_update_access(disk);
2406 		g_raid3_update_metadata(disk);
2407 		G_RAID3_DEBUG(0, "Device %s: provider %s activated.",
2408 		    sc->sc_name, g_raid3_get_diskname(disk));
2409 		break;
2410 	case G_RAID3_DISK_STATE_STALE:
2411 		/*
2412 		 * Possible scenarios:
2413 		 * 1. Stale disk was connected.
2414 		 */
2415 		/* Previous state should be NEW. */
2416 		KASSERT(disk->d_state == G_RAID3_DISK_STATE_NEW,
2417 		    ("Wrong disk state (%s, %s).", g_raid3_get_diskname(disk),
2418 		    g_raid3_disk_state2str(disk->d_state)));
2419 		KASSERT(sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED ||
2420 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE,
2421 		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2422 		    g_raid3_device_state2str(sc->sc_state),
2423 		    g_raid3_get_diskname(disk),
2424 		    g_raid3_disk_state2str(disk->d_state)));
2425 		/*
2426 		 * STALE state is only possible if device is marked
2427 		 * NOAUTOSYNC.
2428 		 */
2429 		KASSERT((sc->sc_flags & G_RAID3_DEVICE_FLAG_NOAUTOSYNC) != 0,
2430 		    ("Wrong device state (%s, %s, %s, %s).", sc->sc_name,
2431 		    g_raid3_device_state2str(sc->sc_state),
2432 		    g_raid3_get_diskname(disk),
2433 		    g_raid3_disk_state2str(disk->d_state)));
2434 		DISK_STATE_CHANGED();
2435 
2436 		disk->d_flags &= ~G_RAID3_DISK_FLAG_DIRTY;
2437 		disk->d_state = state;
2438 		g_raid3_update_metadata(disk);
2439 		G_RAID3_DEBUG(0, "Device %s: provider %s is stale.",
2440 		    sc->sc_name, g_raid3_get_diskname(disk));
2441 		break;
2442 	case G_RAID3_DISK_STATE_SYNCHRONIZING:
2443 		/*
2444 		 * Possible scenarios:
2445 		 * 1. Disk which needs synchronization was connected.
2446 		 */
2447 		/* Previous state should be NEW. */
2448 		KASSERT(disk->d_state == G_RAID3_DISK_STATE_NEW,
2449 		    ("Wrong disk state (%s, %s).", g_raid3_get_diskname(disk),
2450 		    g_raid3_disk_state2str(disk->d_state)));
2451 		KASSERT(sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED ||
2452 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE,
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 		if (disk->d_state == G_RAID3_DISK_STATE_NEW)
2460 			disk->d_flags &= ~G_RAID3_DISK_FLAG_DIRTY;
2461 		disk->d_state = state;
2462 		if (sc->sc_provider != NULL) {
2463 			g_raid3_sync_start(sc);
2464 			g_raid3_update_metadata(disk);
2465 		}
2466 		break;
2467 	case G_RAID3_DISK_STATE_DISCONNECTED:
2468 		/*
2469 		 * Possible scenarios:
2470 		 * 1. Device wasn't running yet, but disk disappear.
2471 		 * 2. Disk was active and disapppear.
2472 		 * 3. Disk disappear during synchronization process.
2473 		 */
2474 		if (sc->sc_state == G_RAID3_DEVICE_STATE_DEGRADED ||
2475 		    sc->sc_state == G_RAID3_DEVICE_STATE_COMPLETE) {
2476 			/*
2477 			 * Previous state should be ACTIVE, STALE or
2478 			 * SYNCHRONIZING.
2479 			 */
2480 			KASSERT(disk->d_state == G_RAID3_DISK_STATE_ACTIVE ||
2481 			    disk->d_state == G_RAID3_DISK_STATE_STALE ||
2482 			    disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING,
2483 			    ("Wrong disk state (%s, %s).",
2484 			    g_raid3_get_diskname(disk),
2485 			    g_raid3_disk_state2str(disk->d_state)));
2486 		} else if (sc->sc_state == G_RAID3_DEVICE_STATE_STARTING) {
2487 			/* Previous state should be NEW. */
2488 			KASSERT(disk->d_state == G_RAID3_DISK_STATE_NEW,
2489 			    ("Wrong disk state (%s, %s).",
2490 			    g_raid3_get_diskname(disk),
2491 			    g_raid3_disk_state2str(disk->d_state)));
2492 			/*
2493 			 * Reset bumping syncid if disk disappeared in STARTING
2494 			 * state.
2495 			 */
2496 			if ((sc->sc_bump_id & G_RAID3_BUMP_SYNCID) != 0)
2497 				sc->sc_bump_id &= ~G_RAID3_BUMP_SYNCID;
2498 #ifdef	INVARIANTS
2499 		} else {
2500 			KASSERT(1 == 0, ("Wrong device state (%s, %s, %s, %s).",
2501 			    sc->sc_name,
2502 			    g_raid3_device_state2str(sc->sc_state),
2503 			    g_raid3_get_diskname(disk),
2504 			    g_raid3_disk_state2str(disk->d_state)));
2505 #endif
2506 		}
2507 		DISK_STATE_CHANGED();
2508 		G_RAID3_DEBUG(0, "Device %s: provider %s disconnected.",
2509 		    sc->sc_name, g_raid3_get_diskname(disk));
2510 
2511 		g_raid3_destroy_disk(disk);
2512 		break;
2513 	default:
2514 		KASSERT(1 == 0, ("Unknown state (%u).", state));
2515 		break;
2516 	}
2517 	return (0);
2518 }
2519 #undef	DISK_STATE_CHANGED
2520 
2521 int
2522 g_raid3_read_metadata(struct g_consumer *cp, struct g_raid3_metadata *md)
2523 {
2524 	struct g_provider *pp;
2525 	u_char *buf;
2526 	int error;
2527 
2528 	g_topology_assert();
2529 
2530 	error = g_access(cp, 1, 0, 0);
2531 	if (error != 0)
2532 		return (error);
2533 	pp = cp->provider;
2534 	g_topology_unlock();
2535 	/* Metadata are stored on last sector. */
2536 	buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
2537 	    &error);
2538 	g_topology_lock();
2539 	g_access(cp, -1, 0, 0);
2540 	if (error != 0) {
2541 		G_RAID3_DEBUG(1, "Cannot read metadata from %s (error=%d).",
2542 		    cp->provider->name, error);
2543 		if (buf != NULL)
2544 			g_free(buf);
2545 		return (error);
2546 	}
2547 
2548 	/* Decode metadata. */
2549 	error = raid3_metadata_decode(buf, md);
2550 	g_free(buf);
2551 	if (strcmp(md->md_magic, G_RAID3_MAGIC) != 0)
2552 		return (EINVAL);
2553 	if (md->md_version > G_RAID3_VERSION) {
2554 		G_RAID3_DEBUG(0,
2555 		    "Kernel module is too old to handle metadata from %s.",
2556 		    cp->provider->name);
2557 		return (EINVAL);
2558 	}
2559 	if (error != 0) {
2560 		G_RAID3_DEBUG(1, "MD5 metadata hash mismatch for provider %s.",
2561 		    cp->provider->name);
2562 		return (error);
2563 	}
2564 
2565 	return (0);
2566 }
2567 
2568 static int
2569 g_raid3_check_metadata(struct g_raid3_softc *sc, struct g_provider *pp,
2570     struct g_raid3_metadata *md)
2571 {
2572 
2573 	if (md->md_no >= sc->sc_ndisks) {
2574 		G_RAID3_DEBUG(1, "Invalid disk %s number (no=%u), skipping.",
2575 		    pp->name, md->md_no);
2576 		return (EINVAL);
2577 	}
2578 	if (sc->sc_disks[md->md_no].d_state != G_RAID3_DISK_STATE_NODISK) {
2579 		G_RAID3_DEBUG(1, "Disk %s (no=%u) already exists, skipping.",
2580 		    pp->name, md->md_no);
2581 		return (EEXIST);
2582 	}
2583 	if (md->md_all != sc->sc_ndisks) {
2584 		G_RAID3_DEBUG(1,
2585 		    "Invalid '%s' field on disk %s (device %s), skipping.",
2586 		    "md_all", pp->name, sc->sc_name);
2587 		return (EINVAL);
2588 	}
2589 	if (md->md_mediasize != sc->sc_mediasize) {
2590 		G_RAID3_DEBUG(1,
2591 		    "Invalid '%s' field on disk %s (device %s), skipping.",
2592 		    "md_mediasize", pp->name, sc->sc_name);
2593 		return (EINVAL);
2594 	}
2595 	if ((md->md_mediasize % (sc->sc_ndisks - 1)) != 0) {
2596 		G_RAID3_DEBUG(1,
2597 		    "Invalid '%s' field on disk %s (device %s), skipping.",
2598 		    "md_mediasize", pp->name, sc->sc_name);
2599 		return (EINVAL);
2600 	}
2601 	if ((sc->sc_mediasize / (sc->sc_ndisks - 1)) > pp->mediasize) {
2602 		G_RAID3_DEBUG(1,
2603 		    "Invalid size of disk %s (device %s), skipping.", pp->name,
2604 		    sc->sc_name);
2605 		return (EINVAL);
2606 	}
2607 	if ((md->md_sectorsize / pp->sectorsize) < sc->sc_ndisks - 1) {
2608 		G_RAID3_DEBUG(1,
2609 		    "Invalid '%s' field on disk %s (device %s), skipping.",
2610 		    "md_sectorsize", pp->name, sc->sc_name);
2611 		return (EINVAL);
2612 	}
2613 	if (md->md_sectorsize != sc->sc_sectorsize) {
2614 		G_RAID3_DEBUG(1,
2615 		    "Invalid '%s' field on disk %s (device %s), skipping.",
2616 		    "md_sectorsize", pp->name, sc->sc_name);
2617 		return (EINVAL);
2618 	}
2619 	if ((sc->sc_sectorsize % pp->sectorsize) != 0) {
2620 		G_RAID3_DEBUG(1,
2621 		    "Invalid sector size of disk %s (device %s), skipping.",
2622 		    pp->name, sc->sc_name);
2623 		return (EINVAL);
2624 	}
2625 	if ((md->md_mflags & ~G_RAID3_DEVICE_FLAG_MASK) != 0) {
2626 		G_RAID3_DEBUG(1,
2627 		    "Invalid device flags on disk %s (device %s), skipping.",
2628 		    pp->name, sc->sc_name);
2629 		return (EINVAL);
2630 	}
2631 	if ((md->md_mflags & G_RAID3_DEVICE_FLAG_VERIFY) != 0 &&
2632 	    (md->md_mflags & G_RAID3_DEVICE_FLAG_ROUND_ROBIN) != 0) {
2633 		/*
2634 		 * VERIFY and ROUND-ROBIN options are mutally exclusive.
2635 		 */
2636 		G_RAID3_DEBUG(1, "Both VERIFY and ROUND-ROBIN flags exist on "
2637 		    "disk %s (device %s), skipping.", pp->name, sc->sc_name);
2638 		return (EINVAL);
2639 	}
2640 	if ((md->md_dflags & ~G_RAID3_DISK_FLAG_MASK) != 0) {
2641 		G_RAID3_DEBUG(1,
2642 		    "Invalid disk flags on disk %s (device %s), skipping.",
2643 		    pp->name, sc->sc_name);
2644 		return (EINVAL);
2645 	}
2646 	return (0);
2647 }
2648 
2649 int
2650 g_raid3_add_disk(struct g_raid3_softc *sc, struct g_provider *pp,
2651     struct g_raid3_metadata *md)
2652 {
2653 	struct g_raid3_disk *disk;
2654 	int error;
2655 
2656 	g_topology_assert();
2657 	G_RAID3_DEBUG(2, "Adding disk %s.", pp->name);
2658 
2659 	error = g_raid3_check_metadata(sc, pp, md);
2660 	if (error != 0)
2661 		return (error);
2662 	if (sc->sc_state != G_RAID3_DEVICE_STATE_STARTING &&
2663 	    md->md_genid < sc->sc_genid) {
2664 		G_RAID3_DEBUG(0, "Component %s (device %s) broken, skipping.",
2665 		    pp->name, sc->sc_name);
2666 		return (EINVAL);
2667 	}
2668 	disk = g_raid3_init_disk(sc, pp, md, &error);
2669 	if (disk == NULL)
2670 		return (error);
2671 	error = g_raid3_event_send(disk, G_RAID3_DISK_STATE_NEW,
2672 	    G_RAID3_EVENT_WAIT);
2673 	if (error != 0)
2674 		return (error);
2675 	if (md->md_version < G_RAID3_VERSION) {
2676 		G_RAID3_DEBUG(0, "Upgrading metadata on %s (v%d->v%d).",
2677 		    pp->name, md->md_version, G_RAID3_VERSION);
2678 		g_raid3_update_metadata(disk);
2679 	}
2680 	return (0);
2681 }
2682 
2683 static int
2684 g_raid3_access(struct g_provider *pp, int acr, int acw, int ace)
2685 {
2686 	struct g_raid3_softc *sc;
2687 	struct g_raid3_disk *disk;
2688 	int dcr, dcw, dce;
2689 	u_int n;
2690 
2691 	g_topology_assert();
2692 	G_RAID3_DEBUG(2, "Access request for %s: r%dw%de%d.", pp->name, acr,
2693 	    acw, ace);
2694 
2695 	dcr = pp->acr + acr;
2696 	dcw = pp->acw + acw;
2697 	dce = pp->ace + ace;
2698 
2699 	sc = pp->geom->softc;
2700 	if (sc == NULL ||
2701 	    g_raid3_ndisks(sc, G_RAID3_DISK_STATE_ACTIVE) < sc->sc_ndisks - 1 ||
2702 	    (sc->sc_flags & G_RAID3_DEVICE_FLAG_DESTROY) != 0) {
2703 		if (acr <= 0 && acw <= 0 && ace <= 0)
2704 			return (0);
2705 		else
2706 			return (ENXIO);
2707 	}
2708 	for (n = 0; n < sc->sc_ndisks; n++) {
2709 		disk = &sc->sc_disks[n];
2710 		if (disk->d_state != G_RAID3_DISK_STATE_ACTIVE)
2711 			continue;
2712 		/*
2713 		 * Mark disk as dirty on open and unmark on close.
2714 		 */
2715 		if (pp->acw == 0 && dcw > 0) {
2716 			G_RAID3_DEBUG(1, "Disk %s (device %s) marked as dirty.",
2717 			    g_raid3_get_diskname(disk), sc->sc_name);
2718 			disk->d_flags |= G_RAID3_DISK_FLAG_DIRTY;
2719 			g_raid3_update_metadata(disk);
2720 		} else if (pp->acw > 0 && dcw == 0) {
2721 			G_RAID3_DEBUG(1, "Disk %s (device %s) marked as clean.",
2722 			    g_raid3_get_diskname(disk), sc->sc_name);
2723 			disk->d_flags &= ~G_RAID3_DISK_FLAG_DIRTY;
2724 			g_raid3_update_metadata(disk);
2725 		}
2726 	}
2727 	return (0);
2728 }
2729 
2730 static struct g_geom *
2731 g_raid3_create(struct g_class *mp, const struct g_raid3_metadata *md)
2732 {
2733 	struct g_raid3_softc *sc;
2734 	struct g_geom *gp;
2735 	int error, timeout;
2736 	u_int n;
2737 
2738 	g_topology_assert();
2739 	G_RAID3_DEBUG(1, "Creating device %s (id=%u).", md->md_name, md->md_id);
2740 
2741 	/* One disk is minimum. */
2742 	if (md->md_all < 1)
2743 		return (NULL);
2744 	/*
2745 	 * Action geom.
2746 	 */
2747 	gp = g_new_geomf(mp, "%s", md->md_name);
2748 	sc = malloc(sizeof(*sc), M_RAID3, M_WAITOK | M_ZERO);
2749 	sc->sc_disks = malloc(sizeof(struct g_raid3_disk) * md->md_all, M_RAID3,
2750 	    M_WAITOK | M_ZERO);
2751 	gp->start = g_raid3_start;
2752 	gp->orphan = g_raid3_orphan;
2753 	gp->access = g_raid3_access;
2754 	gp->dumpconf = g_raid3_dumpconf;
2755 
2756 	sc->sc_id = md->md_id;
2757 	sc->sc_mediasize = md->md_mediasize;
2758 	sc->sc_sectorsize = md->md_sectorsize;
2759 	sc->sc_ndisks = md->md_all;
2760 	sc->sc_round_robin = 0;
2761 	sc->sc_flags = md->md_mflags;
2762 	sc->sc_bump_id = 0;
2763 	sc->sc_idle = 0;
2764 	for (n = 0; n < sc->sc_ndisks; n++) {
2765 		sc->sc_disks[n].d_softc = sc;
2766 		sc->sc_disks[n].d_no = n;
2767 		sc->sc_disks[n].d_state = G_RAID3_DISK_STATE_NODISK;
2768 	}
2769 	bioq_init(&sc->sc_queue);
2770 	mtx_init(&sc->sc_queue_mtx, "graid3:queue", NULL, MTX_DEF);
2771 	TAILQ_INIT(&sc->sc_events);
2772 	mtx_init(&sc->sc_events_mtx, "graid3:events", NULL, MTX_DEF);
2773 	callout_init(&sc->sc_callout, CALLOUT_MPSAFE);
2774 	sc->sc_state = G_RAID3_DEVICE_STATE_STARTING;
2775 	gp->softc = sc;
2776 	sc->sc_geom = gp;
2777 	sc->sc_provider = NULL;
2778 	/*
2779 	 * Synchronization geom.
2780 	 */
2781 	gp = g_new_geomf(mp, "%s.sync", md->md_name);
2782 	gp->softc = sc;
2783 	gp->orphan = g_raid3_orphan;
2784 	sc->sc_sync.ds_geom = gp;
2785 	sc->sc_zone_64k = uma_zcreate("gr3:64k", 65536, NULL, NULL, NULL, NULL,
2786 	    UMA_ALIGN_PTR, 0);
2787 	uma_zone_set_max(sc->sc_zone_64k, g_raid3_n64k);
2788 	sc->sc_zone_16k = uma_zcreate("gr3:16k", 16384, NULL, NULL, NULL, NULL,
2789 	    UMA_ALIGN_PTR, 0);
2790 	uma_zone_set_max(sc->sc_zone_64k, g_raid3_n16k);
2791 	sc->sc_zone_4k = uma_zcreate("gr3:4k", 4096, NULL, NULL, NULL, NULL,
2792 	    UMA_ALIGN_PTR, 0);
2793 	uma_zone_set_max(sc->sc_zone_4k, g_raid3_n4k);
2794 	error = kthread_create(g_raid3_worker, sc, &sc->sc_worker, 0, 0,
2795 	    "g_raid3 %s", md->md_name);
2796 	if (error != 0) {
2797 		G_RAID3_DEBUG(1, "Cannot create kernel thread for %s.",
2798 		    sc->sc_name);
2799 		uma_zdestroy(sc->sc_zone_64k);
2800 		uma_zdestroy(sc->sc_zone_16k);
2801 		uma_zdestroy(sc->sc_zone_4k);
2802 		g_destroy_geom(sc->sc_sync.ds_geom);
2803 		mtx_destroy(&sc->sc_events_mtx);
2804 		mtx_destroy(&sc->sc_queue_mtx);
2805 		g_destroy_geom(sc->sc_geom);
2806 		free(sc->sc_disks, M_RAID3);
2807 		free(sc, M_RAID3);
2808 		return (NULL);
2809 	}
2810 
2811 	G_RAID3_DEBUG(0, "Device %s created (id=%u).", sc->sc_name, sc->sc_id);
2812 
2813 	/*
2814 	 * Run timeout.
2815 	 */
2816 	timeout = atomic_load_acq_int(&g_raid3_timeout);
2817 	callout_reset(&sc->sc_callout, timeout * hz, g_raid3_go, sc);
2818 	return (sc->sc_geom);
2819 }
2820 
2821 int
2822 g_raid3_destroy(struct g_raid3_softc *sc, boolean_t force)
2823 {
2824 	struct g_provider *pp;
2825 
2826 	g_topology_assert();
2827 
2828 	if (sc == NULL)
2829 		return (ENXIO);
2830 	pp = sc->sc_provider;
2831 	if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
2832 		if (force) {
2833 			G_RAID3_DEBUG(1, "Device %s is still open, so it "
2834 			    "can't be definitely removed.", pp->name);
2835 		} else {
2836 			G_RAID3_DEBUG(1,
2837 			    "Device %s is still open (r%dw%de%d).", pp->name,
2838 			    pp->acr, pp->acw, pp->ace);
2839 			return (EBUSY);
2840 		}
2841 	}
2842 
2843 	sc->sc_flags |= G_RAID3_DEVICE_FLAG_DESTROY;
2844 	sc->sc_flags |= G_RAID3_DEVICE_FLAG_WAIT;
2845 	g_topology_unlock();
2846 	G_RAID3_DEBUG(4, "%s: Waking up %p.", __func__, sc);
2847 	mtx_lock(&sc->sc_queue_mtx);
2848 	wakeup(sc);
2849 	wakeup(&sc->sc_queue);
2850 	mtx_unlock(&sc->sc_queue_mtx);
2851 	G_RAID3_DEBUG(4, "%s: Sleeping %p.", __func__, &sc->sc_worker);
2852 	while (sc->sc_worker != NULL)
2853 		tsleep(&sc->sc_worker, PRIBIO, "r3:destroy", hz / 5);
2854 	G_RAID3_DEBUG(4, "%s: Woken up %p.", __func__, &sc->sc_worker);
2855 	g_topology_lock();
2856 	g_raid3_destroy_device(sc);
2857 	free(sc->sc_disks, M_RAID3);
2858 	free(sc, M_RAID3);
2859 	return (0);
2860 }
2861 
2862 static void
2863 g_raid3_taste_orphan(struct g_consumer *cp)
2864 {
2865 
2866 	KASSERT(1 == 0, ("%s called while tasting %s.", __func__,
2867 	    cp->provider->name));
2868 }
2869 
2870 static struct g_geom *
2871 g_raid3_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
2872 {
2873 	struct g_raid3_metadata md;
2874 	struct g_raid3_softc *sc;
2875 	struct g_consumer *cp;
2876 	struct g_geom *gp;
2877 	int error;
2878 
2879 	g_topology_assert();
2880 	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
2881 	G_RAID3_DEBUG(2, "Tasting %s.", pp->name);
2882 
2883 	gp = g_new_geomf(mp, "raid3:taste");
2884 	/* This orphan function should be never called. */
2885 	gp->orphan = g_raid3_taste_orphan;
2886 	cp = g_new_consumer(gp);
2887 	g_attach(cp, pp);
2888 	error = g_raid3_read_metadata(cp, &md);
2889 	g_detach(cp);
2890 	g_destroy_consumer(cp);
2891 	g_destroy_geom(gp);
2892 	if (error != 0)
2893 		return (NULL);
2894 	gp = NULL;
2895 
2896 	if (md.md_provider[0] != '\0' && strcmp(md.md_provider, pp->name) != 0)
2897 		return (NULL);
2898 	if (md.md_provsize != 0 && md.md_provsize != pp->mediasize)
2899 		return (NULL);
2900 	if (g_raid3_debug >= 2)
2901 		raid3_metadata_dump(&md);
2902 
2903 	/*
2904 	 * Let's check if device already exists.
2905 	 */
2906 	sc = NULL;
2907 	LIST_FOREACH(gp, &mp->geom, geom) {
2908 		sc = gp->softc;
2909 		if (sc == NULL)
2910 			continue;
2911 		if (sc->sc_sync.ds_geom == gp)
2912 			continue;
2913 		if (strcmp(md.md_name, sc->sc_name) != 0)
2914 			continue;
2915 		if (md.md_id != sc->sc_id) {
2916 			G_RAID3_DEBUG(0, "Device %s already configured.",
2917 			    sc->sc_name);
2918 			return (NULL);
2919 		}
2920 		break;
2921 	}
2922 	if (gp == NULL) {
2923 		gp = g_raid3_create(mp, &md);
2924 		if (gp == NULL) {
2925 			G_RAID3_DEBUG(0, "Cannot create device %s.",
2926 			    md.md_name);
2927 			return (NULL);
2928 		}
2929 		sc = gp->softc;
2930 	}
2931 	G_RAID3_DEBUG(1, "Adding disk %s to %s.", pp->name, gp->name);
2932 	error = g_raid3_add_disk(sc, pp, &md);
2933 	if (error != 0) {
2934 		G_RAID3_DEBUG(0, "Cannot add disk %s to %s (error=%d).",
2935 		    pp->name, gp->name, error);
2936 		if (g_raid3_ndisks(sc, G_RAID3_DISK_STATE_NODISK) ==
2937 		    sc->sc_ndisks) {
2938 			g_raid3_destroy(sc, 1);
2939 		}
2940 		return (NULL);
2941 	}
2942 	return (gp);
2943 }
2944 
2945 static int
2946 g_raid3_destroy_geom(struct gctl_req *req __unused, struct g_class *mp __unused,
2947     struct g_geom *gp)
2948 {
2949 
2950 	return (g_raid3_destroy(gp->softc, 0));
2951 }
2952 
2953 static void
2954 g_raid3_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
2955     struct g_consumer *cp, struct g_provider *pp)
2956 {
2957 	struct g_raid3_softc *sc;
2958 
2959 	g_topology_assert();
2960 
2961 	sc = gp->softc;
2962 	if (sc == NULL)
2963 		return;
2964 	/* Skip synchronization geom. */
2965 	if (gp == sc->sc_sync.ds_geom)
2966 		return;
2967 	if (pp != NULL) {
2968 		/* Nothing here. */
2969 	} else if (cp != NULL) {
2970 		struct g_raid3_disk *disk;
2971 
2972 		disk = cp->private;
2973 		if (disk == NULL)
2974 			return;
2975 		sbuf_printf(sb, "%s<Type>", indent);
2976 		if (disk->d_no == sc->sc_ndisks - 1)
2977 			sbuf_printf(sb, "PARITY");
2978 		else
2979 			sbuf_printf(sb, "DATA");
2980 		sbuf_printf(sb, "</Type>\n");
2981 		sbuf_printf(sb, "%s<Number>%u</Number>\n", indent,
2982 		    (u_int)disk->d_no);
2983 		if (disk->d_state == G_RAID3_DISK_STATE_SYNCHRONIZING) {
2984 			sbuf_printf(sb, "%s<Synchronized>", indent);
2985 			if (disk->d_sync.ds_offset_done == 0)
2986 				sbuf_printf(sb, "0%%");
2987 			else {
2988 				sbuf_printf(sb, "%u%%",
2989 				    (u_int)((disk->d_sync.ds_offset_done * 100) /
2990 				    (sc->sc_mediasize / (sc->sc_ndisks - 1))));
2991 			}
2992 			sbuf_printf(sb, "</Synchronized>\n");
2993 		}
2994 		sbuf_printf(sb, "%s<SyncID>%u</SyncID>\n", indent,
2995 		    disk->d_sync.ds_syncid);
2996 		sbuf_printf(sb, "%s<GenID>%u</GenID>\n", indent, disk->d_genid);
2997 		sbuf_printf(sb, "%s<Flags>", indent);
2998 		if (disk->d_flags == 0)
2999 			sbuf_printf(sb, "NONE");
3000 		else {
3001 			int first = 1;
3002 
3003 #define	ADD_FLAG(flag, name)	do {					\
3004 	if ((disk->d_flags & (flag)) != 0) {				\
3005 		if (!first)						\
3006 			sbuf_printf(sb, ", ");				\
3007 		else							\
3008 			first = 0;					\
3009 		sbuf_printf(sb, name);					\
3010 	}								\
3011 } while (0)
3012 			ADD_FLAG(G_RAID3_DISK_FLAG_DIRTY, "DIRTY");
3013 			ADD_FLAG(G_RAID3_DISK_FLAG_HARDCODED, "HARDCODED");
3014 			ADD_FLAG(G_RAID3_DISK_FLAG_SYNCHRONIZING,
3015 			    "SYNCHRONIZING");
3016 			ADD_FLAG(G_RAID3_DISK_FLAG_FORCE_SYNC, "FORCE_SYNC");
3017 #undef	ADD_FLAG
3018 		}
3019 		sbuf_printf(sb, "</Flags>\n");
3020 		sbuf_printf(sb, "%s<State>%s</State>\n", indent,
3021 		    g_raid3_disk_state2str(disk->d_state));
3022 	} else {
3023 		sbuf_printf(sb, "%s<ID>%u</ID>\n", indent, (u_int)sc->sc_id);
3024 		sbuf_printf(sb, "%s<SyncID>%u</SyncID>\n", indent, sc->sc_syncid);
3025 		sbuf_printf(sb, "%s<GenID>%u</GenID>\n", indent, sc->sc_genid);
3026 		sbuf_printf(sb, "%s<Flags>", indent);
3027 		if (sc->sc_flags == 0)
3028 			sbuf_printf(sb, "NONE");
3029 		else {
3030 			int first = 1;
3031 
3032 #define	ADD_FLAG(flag, name)	do {					\
3033 	if ((sc->sc_flags & (flag)) != 0) {				\
3034 		if (!first)						\
3035 			sbuf_printf(sb, ", ");				\
3036 		else							\
3037 			first = 0;					\
3038 		sbuf_printf(sb, name);					\
3039 	}								\
3040 } while (0)
3041 			ADD_FLAG(G_RAID3_DEVICE_FLAG_NOAUTOSYNC, "NOAUTOSYNC");
3042 			ADD_FLAG(G_RAID3_DEVICE_FLAG_ROUND_ROBIN,
3043 			    "ROUND-ROBIN");
3044 			ADD_FLAG(G_RAID3_DEVICE_FLAG_VERIFY, "VERIFY");
3045 #undef	ADD_FLAG
3046 		}
3047 		sbuf_printf(sb, "</Flags>\n");
3048 		sbuf_printf(sb, "%s<Components>%u</Components>\n", indent,
3049 		    sc->sc_ndisks);
3050 		sbuf_printf(sb, "%s<State>%s</State>\n", indent,
3051 		    g_raid3_device_state2str(sc->sc_state));
3052 	}
3053 }
3054 
3055 static void
3056 g_raid3_shutdown(void *arg, int howto)
3057 {
3058 	struct g_class *mp;
3059 	struct g_geom *gp, *gp2;
3060 
3061 	mp = arg;
3062 	DROP_GIANT();
3063 	g_topology_lock();
3064 	LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
3065 		if (gp->softc == NULL)
3066 			continue;
3067 		g_raid3_destroy(gp->softc, 1);
3068 	}
3069 	g_topology_unlock();
3070 	PICKUP_GIANT();
3071 #if 0
3072 	tsleep(&gp, PRIBIO, "r3:shutdown", hz * 20);
3073 #endif
3074 }
3075 
3076 static void
3077 g_raid3_init(struct g_class *mp)
3078 {
3079 
3080 	g_raid3_ehtag = EVENTHANDLER_REGISTER(shutdown_post_sync,
3081 	    g_raid3_shutdown, mp, SHUTDOWN_PRI_FIRST);
3082 	if (g_raid3_ehtag == NULL)
3083 		G_RAID3_DEBUG(0, "Warning! Cannot register shutdown event.");
3084 }
3085 
3086 static void
3087 g_raid3_fini(struct g_class *mp)
3088 {
3089 
3090 	if (g_raid3_ehtag == NULL)
3091 		return;
3092 	EVENTHANDLER_DEREGISTER(shutdown_post_sync, g_raid3_ehtag);
3093 }
3094 
3095 DECLARE_GEOM_CLASS(g_raid3_class, g_raid3);
3096