xref: /freebsd/sys/geom/raid/md_jmicron.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2010 Alexander Motin <mav@FreeBSD.org>
5  * Copyright (c) 2000 - 2008 Søren Schmidt <sos@FreeBSD.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <sys/param.h>
34 #include <sys/bio.h>
35 #include <sys/endian.h>
36 #include <sys/kernel.h>
37 #include <sys/kobj.h>
38 #include <sys/limits.h>
39 #include <sys/lock.h>
40 #include <sys/malloc.h>
41 #include <sys/mutex.h>
42 #include <sys/systm.h>
43 #include <sys/taskqueue.h>
44 #include <geom/geom.h>
45 #include "geom/raid/g_raid.h"
46 #include "g_raid_md_if.h"
47 
48 static MALLOC_DEFINE(M_MD_JMICRON, "md_jmicron_data", "GEOM_RAID JMicron metadata");
49 
50 #define	JMICRON_MAX_DISKS	8
51 #define	JMICRON_MAX_SPARE	2
52 
53 struct jmicron_raid_conf {
54     u_int8_t		signature[2];
55 #define	JMICRON_MAGIC		"JM"
56 
57     u_int16_t		version;
58 #define	JMICRON_VERSION		0x0001
59 
60     u_int16_t		checksum;
61     u_int8_t		filler_1[10];
62     u_int32_t		disk_id;
63     u_int32_t		offset;
64     u_int32_t		disk_sectors_high;
65     u_int16_t		disk_sectors_low;
66     u_int8_t		filler_2[2];
67     u_int8_t		name[16];
68     u_int8_t		type;
69 #define	JMICRON_T_RAID0		0
70 #define	JMICRON_T_RAID1		1
71 #define	JMICRON_T_RAID01	2
72 #define	JMICRON_T_CONCAT	3
73 #define	JMICRON_T_RAID5		5
74 
75     u_int8_t		stripe_shift;
76     u_int16_t		flags;
77 #define	JMICRON_F_READY		0x0001
78 #define	JMICRON_F_BOOTABLE	0x0002
79 #define	JMICRON_F_BADSEC	0x0004
80 #define	JMICRON_F_ACTIVE	0x0010
81 #define	JMICRON_F_UNSYNC	0x0020
82 #define	JMICRON_F_NEWEST	0x0040
83 
84     u_int8_t		filler_3[4];
85     u_int32_t		spare[JMICRON_MAX_SPARE];
86     u_int32_t		disks[JMICRON_MAX_DISKS];
87 #define	JMICRON_DISK_MASK	0xFFFFFFF0
88 #define	JMICRON_SEG_MASK	0x0000000F
89     u_int8_t		filler_4[32];
90     u_int8_t		filler_5[384];
91 };
92 
93 struct g_raid_md_jmicron_perdisk {
94 	struct jmicron_raid_conf	*pd_meta;
95 	int				 pd_disk_pos;
96 	int				 pd_disk_id;
97 	off_t				 pd_disk_size;
98 };
99 
100 struct g_raid_md_jmicron_object {
101 	struct g_raid_md_object	 mdio_base;
102 	uint32_t		 mdio_config_id;
103 	struct jmicron_raid_conf	*mdio_meta;
104 	struct callout		 mdio_start_co;	/* STARTING state timer. */
105 	int			 mdio_total_disks;
106 	int			 mdio_disks_present;
107 	int			 mdio_started;
108 	int			 mdio_incomplete;
109 	struct root_hold_token	*mdio_rootmount; /* Root mount delay token. */
110 };
111 
112 static g_raid_md_create_t g_raid_md_create_jmicron;
113 static g_raid_md_taste_t g_raid_md_taste_jmicron;
114 static g_raid_md_event_t g_raid_md_event_jmicron;
115 static g_raid_md_ctl_t g_raid_md_ctl_jmicron;
116 static g_raid_md_write_t g_raid_md_write_jmicron;
117 static g_raid_md_fail_disk_t g_raid_md_fail_disk_jmicron;
118 static g_raid_md_free_disk_t g_raid_md_free_disk_jmicron;
119 static g_raid_md_free_t g_raid_md_free_jmicron;
120 
121 static kobj_method_t g_raid_md_jmicron_methods[] = {
122 	KOBJMETHOD(g_raid_md_create,	g_raid_md_create_jmicron),
123 	KOBJMETHOD(g_raid_md_taste,	g_raid_md_taste_jmicron),
124 	KOBJMETHOD(g_raid_md_event,	g_raid_md_event_jmicron),
125 	KOBJMETHOD(g_raid_md_ctl,	g_raid_md_ctl_jmicron),
126 	KOBJMETHOD(g_raid_md_write,	g_raid_md_write_jmicron),
127 	KOBJMETHOD(g_raid_md_fail_disk,	g_raid_md_fail_disk_jmicron),
128 	KOBJMETHOD(g_raid_md_free_disk,	g_raid_md_free_disk_jmicron),
129 	KOBJMETHOD(g_raid_md_free,	g_raid_md_free_jmicron),
130 	{ 0, 0 }
131 };
132 
133 static struct g_raid_md_class g_raid_md_jmicron_class = {
134 	"JMicron",
135 	g_raid_md_jmicron_methods,
136 	sizeof(struct g_raid_md_jmicron_object),
137 	.mdc_enable = 1,
138 	.mdc_priority = 100
139 };
140 
141 static void
142 g_raid_md_jmicron_print(struct jmicron_raid_conf *meta)
143 {
144 	int k;
145 
146 	if (g_raid_debug < 1)
147 		return;
148 
149 	printf("********* ATA JMicron RAID Metadata *********\n");
150 	printf("signature           <%c%c>\n", meta->signature[0], meta->signature[1]);
151 	printf("version             %04x\n", meta->version);
152 	printf("checksum            0x%04x\n", meta->checksum);
153 	printf("disk_id             0x%08x\n", meta->disk_id);
154 	printf("offset              0x%08x\n", meta->offset);
155 	printf("disk_sectors_high   0x%08x\n", meta->disk_sectors_high);
156 	printf("disk_sectors_low    0x%04x\n", meta->disk_sectors_low);
157 	printf("name                <%.16s>\n", meta->name);
158 	printf("type                %d\n", meta->type);
159 	printf("stripe_shift        %d\n", meta->stripe_shift);
160 	printf("flags               %04x\n", meta->flags);
161 	printf("spare              ");
162 	for (k = 0; k < JMICRON_MAX_SPARE; k++)
163 		printf(" 0x%08x", meta->spare[k]);
164 	printf("\n");
165 	printf("disks              ");
166 	for (k = 0; k < JMICRON_MAX_DISKS; k++)
167 		printf(" 0x%08x", meta->disks[k]);
168 	printf("\n");
169 	printf("=================================================\n");
170 }
171 
172 static struct jmicron_raid_conf *
173 jmicron_meta_copy(struct jmicron_raid_conf *meta)
174 {
175 	struct jmicron_raid_conf *nmeta;
176 
177 	nmeta = malloc(sizeof(*meta), M_MD_JMICRON, M_WAITOK);
178 	memcpy(nmeta, meta, sizeof(*meta));
179 	return (nmeta);
180 }
181 
182 static int
183 jmicron_meta_total_disks(struct jmicron_raid_conf *meta)
184 {
185 	int pos;
186 
187 	for (pos = 0; pos < JMICRON_MAX_DISKS; pos++) {
188 		if (meta->disks[pos] == 0)
189 			break;
190 	}
191 	return (pos);
192 }
193 
194 static int
195 jmicron_meta_total_spare(struct jmicron_raid_conf *meta)
196 {
197 	int pos, n;
198 
199 	n = 0;
200 	for (pos = 0; pos < JMICRON_MAX_SPARE; pos++) {
201 		if (meta->spare[pos] != 0)
202 			n++;
203 	}
204 	return (n);
205 }
206 
207 /*
208  * Generate fake Configuration ID based on disk IDs.
209  * Note: it will change after each disk set change.
210  */
211 static uint32_t
212 jmicron_meta_config_id(struct jmicron_raid_conf *meta)
213 {
214 	int pos;
215 	uint32_t config_id;
216 
217 	config_id = 0;
218 	for (pos = 0; pos < JMICRON_MAX_DISKS; pos++)
219 		config_id += meta->disks[pos] << pos;
220 	return (config_id);
221 }
222 
223 static void
224 jmicron_meta_get_name(struct jmicron_raid_conf *meta, char *buf)
225 {
226 	int i;
227 
228 	strncpy(buf, meta->name, 16);
229 	buf[16] = 0;
230 	for (i = 15; i >= 0; i--) {
231 		if (buf[i] > 0x20)
232 			break;
233 		buf[i] = 0;
234 	}
235 }
236 
237 static void
238 jmicron_meta_put_name(struct jmicron_raid_conf *meta, char *buf)
239 {
240 
241 	memset(meta->name, 0x20, 16);
242 	memcpy(meta->name, buf, MIN(strlen(buf), 16));
243 }
244 
245 static int
246 jmicron_meta_find_disk(struct jmicron_raid_conf *meta, uint32_t id)
247 {
248 	int pos;
249 
250 	id &= JMICRON_DISK_MASK;
251 	for (pos = 0; pos < JMICRON_MAX_DISKS; pos++) {
252 		if ((meta->disks[pos] & JMICRON_DISK_MASK) == id)
253 			return (pos);
254 	}
255 	for (pos = 0; pos < JMICRON_MAX_SPARE; pos++) {
256 		if ((meta->spare[pos] & JMICRON_DISK_MASK) == id)
257 			return (-3);
258 	}
259 	return (-1);
260 }
261 
262 static struct jmicron_raid_conf *
263 jmicron_meta_read(struct g_consumer *cp)
264 {
265 	struct g_provider *pp;
266 	struct jmicron_raid_conf *meta;
267 	char *buf;
268 	int error, i;
269 	uint16_t checksum, *ptr;
270 
271 	pp = cp->provider;
272 
273 	/* Read the anchor sector. */
274 	buf = g_read_data(cp,
275 	    pp->mediasize - pp->sectorsize, pp->sectorsize, &error);
276 	if (buf == NULL) {
277 		G_RAID_DEBUG(1, "Cannot read metadata from %s (error=%d).",
278 		    pp->name, error);
279 		return (NULL);
280 	}
281 	meta = (struct jmicron_raid_conf *)buf;
282 
283 	/* Check if this is an JMicron RAID struct */
284 	if (strncmp(meta->signature, JMICRON_MAGIC, strlen(JMICRON_MAGIC))) {
285 		G_RAID_DEBUG(1, "JMicron signature check failed on %s", pp->name);
286 		g_free(buf);
287 		return (NULL);
288 	}
289 	meta = malloc(sizeof(*meta), M_MD_JMICRON, M_WAITOK);
290 	memcpy(meta, buf, min(sizeof(*meta), pp->sectorsize));
291 	g_free(buf);
292 
293 	/* Check metadata checksum. */
294 	for (checksum = 0, ptr = (uint16_t *)meta, i = 0; i < 64; i++)
295 		checksum += *ptr++;
296 	if (checksum != 0) {
297 		G_RAID_DEBUG(1, "JMicron checksum check failed on %s", pp->name);
298 		free(meta, M_MD_JMICRON);
299 		return (NULL);
300 	}
301 
302 	return (meta);
303 }
304 
305 static int
306 jmicron_meta_write(struct g_consumer *cp, struct jmicron_raid_conf *meta)
307 {
308 	struct g_provider *pp;
309 	char *buf;
310 	int error, i;
311 	uint16_t checksum, *ptr;
312 
313 	pp = cp->provider;
314 
315 	/* Recalculate checksum for case if metadata were changed. */
316 	meta->checksum = 0;
317 	for (checksum = 0, ptr = (uint16_t *)meta, i = 0; i < 64; i++)
318 		checksum += *ptr++;
319 	meta->checksum -= checksum;
320 
321 	/* Create and fill buffer. */
322 	buf = malloc(pp->sectorsize, M_MD_JMICRON, M_WAITOK | M_ZERO);
323 	memcpy(buf, meta, sizeof(*meta));
324 
325 	error = g_write_data(cp,
326 	    pp->mediasize - pp->sectorsize, buf, pp->sectorsize);
327 	if (error != 0) {
328 		G_RAID_DEBUG(1, "Cannot write metadata to %s (error=%d).",
329 		    pp->name, error);
330 	}
331 
332 	free(buf, M_MD_JMICRON);
333 	return (error);
334 }
335 
336 static int
337 jmicron_meta_erase(struct g_consumer *cp)
338 {
339 	struct g_provider *pp;
340 	char *buf;
341 	int error;
342 
343 	pp = cp->provider;
344 	buf = malloc(pp->sectorsize, M_MD_JMICRON, M_WAITOK | M_ZERO);
345 	error = g_write_data(cp,
346 	    pp->mediasize - pp->sectorsize, buf, pp->sectorsize);
347 	if (error != 0) {
348 		G_RAID_DEBUG(1, "Cannot erase metadata on %s (error=%d).",
349 		    pp->name, error);
350 	}
351 	free(buf, M_MD_JMICRON);
352 	return (error);
353 }
354 
355 static struct g_raid_disk *
356 g_raid_md_jmicron_get_disk(struct g_raid_softc *sc, int id)
357 {
358 	struct g_raid_disk	*disk;
359 	struct g_raid_md_jmicron_perdisk *pd;
360 
361 	TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
362 		pd = (struct g_raid_md_jmicron_perdisk *)disk->d_md_data;
363 		if (pd->pd_disk_pos == id)
364 			break;
365 	}
366 	return (disk);
367 }
368 
369 static int
370 g_raid_md_jmicron_supported(int level, int qual, int disks, int force)
371 {
372 
373 	if (disks > 8)
374 		return (0);
375 	switch (level) {
376 	case G_RAID_VOLUME_RL_RAID0:
377 		if (disks < 1)
378 			return (0);
379 		if (!force && (disks < 2 || disks > 6))
380 			return (0);
381 		break;
382 	case G_RAID_VOLUME_RL_RAID1:
383 		if (disks < 1)
384 			return (0);
385 		if (!force && (disks != 2))
386 			return (0);
387 		break;
388 	case G_RAID_VOLUME_RL_RAID1E:
389 		if (disks < 2)
390 			return (0);
391 		if (!force && (disks != 4))
392 			return (0);
393 		break;
394 	case G_RAID_VOLUME_RL_SINGLE:
395 		if (disks != 1)
396 			return (0);
397 		if (!force)
398 			return (0);
399 		break;
400 	case G_RAID_VOLUME_RL_CONCAT:
401 		if (disks < 2)
402 			return (0);
403 		break;
404 	case G_RAID_VOLUME_RL_RAID5:
405 		if (disks < 3)
406 			return (0);
407 		if (qual != G_RAID_VOLUME_RLQ_R5LA)
408 			return (0);
409 		if (!force)
410 			return (0);
411 		break;
412 	default:
413 		return (0);
414 	}
415 	if (level != G_RAID_VOLUME_RL_RAID5 && qual != G_RAID_VOLUME_RLQ_NONE)
416 		return (0);
417 	return (1);
418 }
419 
420 static int
421 g_raid_md_jmicron_start_disk(struct g_raid_disk *disk)
422 {
423 	struct g_raid_softc *sc;
424 	struct g_raid_subdisk *sd, *tmpsd;
425 	struct g_raid_disk *olddisk, *tmpdisk;
426 	struct g_raid_md_object *md;
427 	struct g_raid_md_jmicron_object *mdi;
428 	struct g_raid_md_jmicron_perdisk *pd, *oldpd;
429 	struct jmicron_raid_conf *meta;
430 	int disk_pos, resurrection = 0;
431 
432 	sc = disk->d_softc;
433 	md = sc->sc_md;
434 	mdi = (struct g_raid_md_jmicron_object *)md;
435 	meta = mdi->mdio_meta;
436 	pd = (struct g_raid_md_jmicron_perdisk *)disk->d_md_data;
437 	olddisk = NULL;
438 
439 	/* Find disk position in metadata by its serial. */
440 	if (pd->pd_meta != NULL)
441 		disk_pos = jmicron_meta_find_disk(meta, pd->pd_disk_id);
442 	else
443 		disk_pos = -1;
444 	if (disk_pos < 0) {
445 		G_RAID_DEBUG1(1, sc, "Unknown, probably new or stale disk");
446 		/* If we are in the start process, that's all for now. */
447 		if (!mdi->mdio_started)
448 			goto nofit;
449 		/*
450 		 * If we have already started - try to get use of the disk.
451 		 * Try to replace OFFLINE disks first, then FAILED.
452 		 */
453 		TAILQ_FOREACH(tmpdisk, &sc->sc_disks, d_next) {
454 			if (tmpdisk->d_state != G_RAID_DISK_S_OFFLINE &&
455 			    tmpdisk->d_state != G_RAID_DISK_S_FAILED)
456 				continue;
457 			/* Make sure this disk is big enough. */
458 			TAILQ_FOREACH(sd, &tmpdisk->d_subdisks, sd_next) {
459 				if (sd->sd_offset + sd->sd_size + 512 >
460 				    pd->pd_disk_size) {
461 					G_RAID_DEBUG1(1, sc,
462 					    "Disk too small (%ju < %ju)",
463 					    pd->pd_disk_size,
464 					    sd->sd_offset + sd->sd_size + 512);
465 					break;
466 				}
467 			}
468 			if (sd != NULL)
469 				continue;
470 			if (tmpdisk->d_state == G_RAID_DISK_S_OFFLINE) {
471 				olddisk = tmpdisk;
472 				break;
473 			} else if (olddisk == NULL)
474 				olddisk = tmpdisk;
475 		}
476 		if (olddisk == NULL) {
477 nofit:
478 			if (disk_pos == -3 || pd->pd_disk_pos == -3) {
479 				g_raid_change_disk_state(disk,
480 				    G_RAID_DISK_S_SPARE);
481 				return (1);
482 			} else {
483 				g_raid_change_disk_state(disk,
484 				    G_RAID_DISK_S_STALE);
485 				return (0);
486 			}
487 		}
488 		oldpd = (struct g_raid_md_jmicron_perdisk *)olddisk->d_md_data;
489 		disk_pos = oldpd->pd_disk_pos;
490 		resurrection = 1;
491 	}
492 
493 	if (olddisk == NULL) {
494 		/* Find placeholder by position. */
495 		olddisk = g_raid_md_jmicron_get_disk(sc, disk_pos);
496 		if (olddisk == NULL)
497 			panic("No disk at position %d!", disk_pos);
498 		if (olddisk->d_state != G_RAID_DISK_S_OFFLINE) {
499 			G_RAID_DEBUG1(1, sc, "More than one disk for pos %d",
500 			    disk_pos);
501 			g_raid_change_disk_state(disk, G_RAID_DISK_S_STALE);
502 			return (0);
503 		}
504 		oldpd = (struct g_raid_md_jmicron_perdisk *)olddisk->d_md_data;
505 	}
506 
507 	/* Replace failed disk or placeholder with new disk. */
508 	TAILQ_FOREACH_SAFE(sd, &olddisk->d_subdisks, sd_next, tmpsd) {
509 		TAILQ_REMOVE(&olddisk->d_subdisks, sd, sd_next);
510 		TAILQ_INSERT_TAIL(&disk->d_subdisks, sd, sd_next);
511 		sd->sd_disk = disk;
512 	}
513 	oldpd->pd_disk_pos = -2;
514 	pd->pd_disk_pos = disk_pos;
515 	/* Update global metadata just in case. */
516 	meta->disks[disk_pos] = pd->pd_disk_id;
517 
518 	/* If it was placeholder -- destroy it. */
519 	if (olddisk->d_state == G_RAID_DISK_S_OFFLINE) {
520 		g_raid_destroy_disk(olddisk);
521 	} else {
522 		/* Otherwise, make it STALE_FAILED. */
523 		g_raid_change_disk_state(olddisk, G_RAID_DISK_S_STALE_FAILED);
524 	}
525 
526 	/* Welcome the new disk. */
527 	g_raid_change_disk_state(disk, G_RAID_DISK_S_ACTIVE);
528 	TAILQ_FOREACH(sd, &disk->d_subdisks, sd_next) {
529 
530 		/*
531 		 * Different disks may have different sizes/offsets,
532 		 * especially in concat mode. Update.
533 		 */
534 		if (!resurrection) {
535 			sd->sd_offset =
536 			    (off_t)pd->pd_meta->offset * 16 * 512; //ZZZ
537 			sd->sd_size =
538 			    (((off_t)pd->pd_meta->disk_sectors_high << 16) +
539 			      pd->pd_meta->disk_sectors_low) * 512;
540 		}
541 
542 		if (resurrection) {
543 			/* Stale disk, almost same as new. */
544 			g_raid_change_subdisk_state(sd,
545 			    G_RAID_SUBDISK_S_NEW);
546 		} else if ((meta->flags & JMICRON_F_BADSEC) != 0 &&
547 		    (pd->pd_meta->flags & JMICRON_F_BADSEC) == 0) {
548 			/* Cold-inserted or rebuilding disk. */
549 			g_raid_change_subdisk_state(sd,
550 			    G_RAID_SUBDISK_S_NEW);
551 		} else if (pd->pd_meta->flags & JMICRON_F_UNSYNC) {
552 			/* Dirty or resyncing disk.. */
553 			g_raid_change_subdisk_state(sd,
554 			    G_RAID_SUBDISK_S_STALE);
555 		} else {
556 			/* Up to date disk. */
557 			g_raid_change_subdisk_state(sd,
558 			    G_RAID_SUBDISK_S_ACTIVE);
559 		}
560 		g_raid_event_send(sd, G_RAID_SUBDISK_E_NEW,
561 		    G_RAID_EVENT_SUBDISK);
562 	}
563 
564 	/* Update status of our need for spare. */
565 	if (mdi->mdio_started) {
566 		mdi->mdio_incomplete =
567 		    (g_raid_ndisks(sc, G_RAID_DISK_S_ACTIVE) <
568 		     mdi->mdio_total_disks);
569 	}
570 
571 	return (resurrection);
572 }
573 
574 static void
575 g_disk_md_jmicron_retaste(void *arg, int pending)
576 {
577 
578 	G_RAID_DEBUG(1, "Array is not complete, trying to retaste.");
579 	g_retaste(&g_raid_class);
580 	free(arg, M_MD_JMICRON);
581 }
582 
583 static void
584 g_raid_md_jmicron_refill(struct g_raid_softc *sc)
585 {
586 	struct g_raid_md_object *md;
587 	struct g_raid_md_jmicron_object *mdi;
588 	struct g_raid_disk *disk;
589 	struct task *task;
590 	int update, na;
591 
592 	md = sc->sc_md;
593 	mdi = (struct g_raid_md_jmicron_object *)md;
594 	update = 0;
595 	do {
596 		/* Make sure we miss anything. */
597 		na = g_raid_ndisks(sc, G_RAID_DISK_S_ACTIVE);
598 		if (na == mdi->mdio_total_disks)
599 			break;
600 
601 		G_RAID_DEBUG1(1, md->mdo_softc,
602 		    "Array is not complete (%d of %d), "
603 		    "trying to refill.", na, mdi->mdio_total_disks);
604 
605 		/* Try to get use some of STALE disks. */
606 		TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
607 			if (disk->d_state == G_RAID_DISK_S_STALE) {
608 				update += g_raid_md_jmicron_start_disk(disk);
609 				if (disk->d_state == G_RAID_DISK_S_ACTIVE)
610 					break;
611 			}
612 		}
613 		if (disk != NULL)
614 			continue;
615 
616 		/* Try to get use some of SPARE disks. */
617 		TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
618 			if (disk->d_state == G_RAID_DISK_S_SPARE) {
619 				update += g_raid_md_jmicron_start_disk(disk);
620 				if (disk->d_state == G_RAID_DISK_S_ACTIVE)
621 					break;
622 			}
623 		}
624 	} while (disk != NULL);
625 
626 	/* Write new metadata if we changed something. */
627 	if (update)
628 		g_raid_md_write_jmicron(md, NULL, NULL, NULL);
629 
630 	/* Update status of our need for spare. */
631 	mdi->mdio_incomplete = (g_raid_ndisks(sc, G_RAID_DISK_S_ACTIVE) <
632 	    mdi->mdio_total_disks);
633 
634 	/* Request retaste hoping to find spare. */
635 	if (mdi->mdio_incomplete) {
636 		task = malloc(sizeof(struct task),
637 		    M_MD_JMICRON, M_WAITOK | M_ZERO);
638 		TASK_INIT(task, 0, g_disk_md_jmicron_retaste, task);
639 		taskqueue_enqueue(taskqueue_swi, task);
640 	}
641 }
642 
643 static void
644 g_raid_md_jmicron_start(struct g_raid_softc *sc)
645 {
646 	struct g_raid_md_object *md;
647 	struct g_raid_md_jmicron_object *mdi;
648 	struct g_raid_md_jmicron_perdisk *pd;
649 	struct jmicron_raid_conf *meta;
650 	struct g_raid_volume *vol;
651 	struct g_raid_subdisk *sd;
652 	struct g_raid_disk *disk;
653 	off_t size;
654 	int j, disk_pos;
655 	char buf[17];
656 
657 	md = sc->sc_md;
658 	mdi = (struct g_raid_md_jmicron_object *)md;
659 	meta = mdi->mdio_meta;
660 
661 	/* Create volumes and subdisks. */
662 	jmicron_meta_get_name(meta, buf);
663 	vol = g_raid_create_volume(sc, buf, -1);
664 	size = ((off_t)meta->disk_sectors_high << 16) + meta->disk_sectors_low;
665 	size *= 512; //ZZZ
666 	vol->v_raid_level_qualifier = G_RAID_VOLUME_RLQ_NONE;
667 	if (meta->type == JMICRON_T_RAID0) {
668 		vol->v_raid_level = G_RAID_VOLUME_RL_RAID0;
669 		vol->v_mediasize = size * mdi->mdio_total_disks;
670 	} else if (meta->type == JMICRON_T_RAID1) {
671 		vol->v_raid_level = G_RAID_VOLUME_RL_RAID1;
672 		vol->v_mediasize = size;
673 	} else if (meta->type == JMICRON_T_RAID01) {
674 		vol->v_raid_level = G_RAID_VOLUME_RL_RAID1E;
675 		vol->v_mediasize = size * mdi->mdio_total_disks / 2;
676 	} else if (meta->type == JMICRON_T_CONCAT) {
677 		if (mdi->mdio_total_disks == 1)
678 			vol->v_raid_level = G_RAID_VOLUME_RL_SINGLE;
679 		else
680 			vol->v_raid_level = G_RAID_VOLUME_RL_CONCAT;
681 		vol->v_mediasize = 0;
682 	} else if (meta->type == JMICRON_T_RAID5) {
683 		vol->v_raid_level = G_RAID_VOLUME_RL_RAID5;
684 		vol->v_raid_level_qualifier = G_RAID_VOLUME_RLQ_R5LA;
685 		vol->v_mediasize = size * (mdi->mdio_total_disks - 1);
686 	} else {
687 		vol->v_raid_level = G_RAID_VOLUME_RL_UNKNOWN;
688 		vol->v_mediasize = 0;
689 	}
690 	vol->v_strip_size = 1024 << meta->stripe_shift; //ZZZ
691 	vol->v_disks_count = mdi->mdio_total_disks;
692 	vol->v_sectorsize = 512; //ZZZ
693 	for (j = 0; j < vol->v_disks_count; j++) {
694 		sd = &vol->v_subdisks[j];
695 		sd->sd_offset = (off_t)meta->offset * 16 * 512; //ZZZ
696 		sd->sd_size = size;
697 	}
698 	g_raid_start_volume(vol);
699 
700 	/* Create disk placeholders to store data for later writing. */
701 	for (disk_pos = 0; disk_pos < mdi->mdio_total_disks; disk_pos++) {
702 		pd = malloc(sizeof(*pd), M_MD_JMICRON, M_WAITOK | M_ZERO);
703 		pd->pd_disk_pos = disk_pos;
704 		pd->pd_disk_id = meta->disks[disk_pos];
705 		disk = g_raid_create_disk(sc);
706 		disk->d_md_data = (void *)pd;
707 		disk->d_state = G_RAID_DISK_S_OFFLINE;
708 		sd = &vol->v_subdisks[disk_pos];
709 		sd->sd_disk = disk;
710 		TAILQ_INSERT_TAIL(&disk->d_subdisks, sd, sd_next);
711 	}
712 
713 	/* Make all disks found till the moment take their places. */
714 	do {
715 		TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
716 			if (disk->d_state == G_RAID_DISK_S_NONE) {
717 				g_raid_md_jmicron_start_disk(disk);
718 				break;
719 			}
720 		}
721 	} while (disk != NULL);
722 
723 	mdi->mdio_started = 1;
724 	G_RAID_DEBUG1(0, sc, "Array started.");
725 	g_raid_md_write_jmicron(md, NULL, NULL, NULL);
726 
727 	/* Pickup any STALE/SPARE disks to refill array if needed. */
728 	g_raid_md_jmicron_refill(sc);
729 
730 	g_raid_event_send(vol, G_RAID_VOLUME_E_START, G_RAID_EVENT_VOLUME);
731 
732 	callout_stop(&mdi->mdio_start_co);
733 	G_RAID_DEBUG1(1, sc, "root_mount_rel %p", mdi->mdio_rootmount);
734 	root_mount_rel(mdi->mdio_rootmount);
735 	mdi->mdio_rootmount = NULL;
736 }
737 
738 static void
739 g_raid_md_jmicron_new_disk(struct g_raid_disk *disk)
740 {
741 	struct g_raid_softc *sc;
742 	struct g_raid_md_object *md;
743 	struct g_raid_md_jmicron_object *mdi;
744 	struct jmicron_raid_conf *pdmeta;
745 	struct g_raid_md_jmicron_perdisk *pd;
746 
747 	sc = disk->d_softc;
748 	md = sc->sc_md;
749 	mdi = (struct g_raid_md_jmicron_object *)md;
750 	pd = (struct g_raid_md_jmicron_perdisk *)disk->d_md_data;
751 	pdmeta = pd->pd_meta;
752 
753 	if (mdi->mdio_started) {
754 		if (g_raid_md_jmicron_start_disk(disk))
755 			g_raid_md_write_jmicron(md, NULL, NULL, NULL);
756 	} else {
757 		/*
758 		 * If we haven't started yet - update common metadata
759 		 * to get subdisks details, avoiding data from spare disks.
760 		 */
761 		if (mdi->mdio_meta == NULL ||
762 		    jmicron_meta_find_disk(mdi->mdio_meta,
763 		     mdi->mdio_meta->disk_id) == -3) {
764 			if (mdi->mdio_meta != NULL)
765 				free(mdi->mdio_meta, M_MD_JMICRON);
766 			mdi->mdio_meta = jmicron_meta_copy(pdmeta);
767 			mdi->mdio_total_disks = jmicron_meta_total_disks(pdmeta);
768 		}
769 		mdi->mdio_meta->flags |= pdmeta->flags & JMICRON_F_BADSEC;
770 
771 		mdi->mdio_disks_present++;
772 		G_RAID_DEBUG1(1, sc, "Matching disk (%d of %d+%d up)",
773 		    mdi->mdio_disks_present,
774 		    mdi->mdio_total_disks,
775 		    jmicron_meta_total_spare(mdi->mdio_meta));
776 
777 		/* If we collected all needed disks - start array. */
778 		if (mdi->mdio_disks_present == mdi->mdio_total_disks +
779 		    jmicron_meta_total_spare(mdi->mdio_meta))
780 			g_raid_md_jmicron_start(sc);
781 	}
782 }
783 
784 static void
785 g_raid_jmicron_go(void *arg)
786 {
787 	struct g_raid_softc *sc;
788 	struct g_raid_md_object *md;
789 	struct g_raid_md_jmicron_object *mdi;
790 
791 	sc = arg;
792 	md = sc->sc_md;
793 	mdi = (struct g_raid_md_jmicron_object *)md;
794 	if (!mdi->mdio_started) {
795 		G_RAID_DEBUG1(0, sc, "Force array start due to timeout.");
796 		g_raid_event_send(sc, G_RAID_NODE_E_START, 0);
797 	}
798 }
799 
800 static int
801 g_raid_md_create_jmicron(struct g_raid_md_object *md, struct g_class *mp,
802     struct g_geom **gp)
803 {
804 	struct g_raid_softc *sc;
805 	struct g_raid_md_jmicron_object *mdi;
806 	char name[16];
807 
808 	mdi = (struct g_raid_md_jmicron_object *)md;
809 	mdi->mdio_config_id = arc4random();
810 	snprintf(name, sizeof(name), "JMicron-%08x", mdi->mdio_config_id);
811 	sc = g_raid_create_node(mp, name, md);
812 	if (sc == NULL)
813 		return (G_RAID_MD_TASTE_FAIL);
814 	md->mdo_softc = sc;
815 	*gp = sc->sc_geom;
816 	return (G_RAID_MD_TASTE_NEW);
817 }
818 
819 static int
820 g_raid_md_taste_jmicron(struct g_raid_md_object *md, struct g_class *mp,
821                               struct g_consumer *cp, struct g_geom **gp)
822 {
823 	struct g_consumer *rcp;
824 	struct g_provider *pp;
825 	struct g_raid_md_jmicron_object *mdi, *mdi1;
826 	struct g_raid_softc *sc;
827 	struct g_raid_disk *disk;
828 	struct jmicron_raid_conf *meta;
829 	struct g_raid_md_jmicron_perdisk *pd;
830 	struct g_geom *geom;
831 	int disk_pos, result, spare, len;
832 	char name[16];
833 	uint16_t vendor;
834 
835 	G_RAID_DEBUG(1, "Tasting JMicron on %s", cp->provider->name);
836 	mdi = (struct g_raid_md_jmicron_object *)md;
837 	pp = cp->provider;
838 
839 	/* Read metadata from device. */
840 	meta = NULL;
841 	g_topology_unlock();
842 	vendor = 0xffff;
843 	len = sizeof(vendor);
844 	if (pp->geom->rank == 1)
845 		g_io_getattr("GEOM::hba_vendor", cp, &len, &vendor);
846 	meta = jmicron_meta_read(cp);
847 	g_topology_lock();
848 	if (meta == NULL) {
849 		if (g_raid_aggressive_spare) {
850 			if (vendor == 0x197b) {
851 				G_RAID_DEBUG(1,
852 				    "No JMicron metadata, forcing spare.");
853 				spare = 2;
854 				goto search;
855 			} else {
856 				G_RAID_DEBUG(1,
857 				    "JMicron vendor mismatch 0x%04x != 0x197b",
858 				    vendor);
859 			}
860 		}
861 		return (G_RAID_MD_TASTE_FAIL);
862 	}
863 
864 	/* Check this disk position in obtained metadata. */
865 	disk_pos = jmicron_meta_find_disk(meta, meta->disk_id);
866 	if (disk_pos == -1) {
867 		G_RAID_DEBUG(1, "JMicron disk_id %08x not found",
868 		    meta->disk_id);
869 		goto fail1;
870 	}
871 
872 	/* Metadata valid. Print it. */
873 	g_raid_md_jmicron_print(meta);
874 	G_RAID_DEBUG(1, "JMicron disk position %d", disk_pos);
875 	spare = (disk_pos == -2) ? 1 : 0;
876 
877 search:
878 	/* Search for matching node. */
879 	sc = NULL;
880 	mdi1 = NULL;
881 	LIST_FOREACH(geom, &mp->geom, geom) {
882 		sc = geom->softc;
883 		if (sc == NULL)
884 			continue;
885 		if (sc->sc_stopping != 0)
886 			continue;
887 		if (sc->sc_md->mdo_class != md->mdo_class)
888 			continue;
889 		mdi1 = (struct g_raid_md_jmicron_object *)sc->sc_md;
890 		if (spare == 2) {
891 			if (mdi1->mdio_incomplete)
892 				break;
893 		} else {
894 			if (mdi1->mdio_config_id ==
895 			    jmicron_meta_config_id(meta))
896 				break;
897 		}
898 	}
899 
900 	/* Found matching node. */
901 	if (geom != NULL) {
902 		G_RAID_DEBUG(1, "Found matching array %s", sc->sc_name);
903 		result = G_RAID_MD_TASTE_EXISTING;
904 
905 	} else if (spare) { /* Not found needy node -- left for later. */
906 		G_RAID_DEBUG(1, "Spare is not needed at this time");
907 		goto fail1;
908 
909 	} else { /* Not found matching node -- create one. */
910 		result = G_RAID_MD_TASTE_NEW;
911 		mdi->mdio_config_id = jmicron_meta_config_id(meta);
912 		snprintf(name, sizeof(name), "JMicron-%08x",
913 		    mdi->mdio_config_id);
914 		sc = g_raid_create_node(mp, name, md);
915 		md->mdo_softc = sc;
916 		geom = sc->sc_geom;
917 		callout_init(&mdi->mdio_start_co, 1);
918 		callout_reset(&mdi->mdio_start_co, g_raid_start_timeout * hz,
919 		    g_raid_jmicron_go, sc);
920 		mdi->mdio_rootmount = root_mount_hold("GRAID-JMicron");
921 		G_RAID_DEBUG1(1, sc, "root_mount_hold %p", mdi->mdio_rootmount);
922 	}
923 
924 	/* There is no return after this point, so we close passed consumer. */
925 	g_access(cp, -1, 0, 0);
926 
927 	rcp = g_new_consumer(geom);
928 	rcp->flags |= G_CF_DIRECT_RECEIVE;
929 	g_attach(rcp, pp);
930 	if (g_access(rcp, 1, 1, 1) != 0)
931 		; //goto fail1;
932 
933 	g_topology_unlock();
934 	sx_xlock(&sc->sc_lock);
935 
936 	pd = malloc(sizeof(*pd), M_MD_JMICRON, M_WAITOK | M_ZERO);
937 	pd->pd_meta = meta;
938 	if (spare == 2) {
939 		pd->pd_disk_pos = -3;
940 		pd->pd_disk_id = arc4random() & JMICRON_DISK_MASK;
941 	} else {
942 		pd->pd_disk_pos = -1;
943 		pd->pd_disk_id = meta->disk_id;
944 	}
945 	pd->pd_disk_size = pp->mediasize;
946 	disk = g_raid_create_disk(sc);
947 	disk->d_md_data = (void *)pd;
948 	disk->d_consumer = rcp;
949 	rcp->private = disk;
950 
951 	g_raid_get_disk_info(disk);
952 
953 	g_raid_md_jmicron_new_disk(disk);
954 
955 	sx_xunlock(&sc->sc_lock);
956 	g_topology_lock();
957 	*gp = geom;
958 	return (result);
959 fail1:
960 	free(meta, M_MD_JMICRON);
961 	return (G_RAID_MD_TASTE_FAIL);
962 }
963 
964 static int
965 g_raid_md_event_jmicron(struct g_raid_md_object *md,
966     struct g_raid_disk *disk, u_int event)
967 {
968 	struct g_raid_softc *sc;
969 	struct g_raid_subdisk *sd;
970 	struct g_raid_md_jmicron_object *mdi;
971 	struct g_raid_md_jmicron_perdisk *pd;
972 
973 	sc = md->mdo_softc;
974 	mdi = (struct g_raid_md_jmicron_object *)md;
975 	if (disk == NULL) {
976 		switch (event) {
977 		case G_RAID_NODE_E_START:
978 			if (!mdi->mdio_started)
979 				g_raid_md_jmicron_start(sc);
980 			return (0);
981 		}
982 		return (-1);
983 	}
984 	pd = (struct g_raid_md_jmicron_perdisk *)disk->d_md_data;
985 	switch (event) {
986 	case G_RAID_DISK_E_DISCONNECTED:
987 		/* If disk was assigned, just update statuses. */
988 		if (pd->pd_disk_pos >= 0) {
989 			g_raid_change_disk_state(disk, G_RAID_DISK_S_OFFLINE);
990 			if (disk->d_consumer) {
991 				g_raid_kill_consumer(sc, disk->d_consumer);
992 				disk->d_consumer = NULL;
993 			}
994 			TAILQ_FOREACH(sd, &disk->d_subdisks, sd_next) {
995 				g_raid_change_subdisk_state(sd,
996 				    G_RAID_SUBDISK_S_NONE);
997 				g_raid_event_send(sd, G_RAID_SUBDISK_E_DISCONNECTED,
998 				    G_RAID_EVENT_SUBDISK);
999 			}
1000 		} else {
1001 			/* Otherwise -- delete. */
1002 			g_raid_change_disk_state(disk, G_RAID_DISK_S_NONE);
1003 			g_raid_destroy_disk(disk);
1004 		}
1005 
1006 		/* Write updated metadata to all disks. */
1007 		g_raid_md_write_jmicron(md, NULL, NULL, NULL);
1008 
1009 		/* Check if anything left except placeholders. */
1010 		if (g_raid_ndisks(sc, -1) ==
1011 		    g_raid_ndisks(sc, G_RAID_DISK_S_OFFLINE))
1012 			g_raid_destroy_node(sc, 0);
1013 		else
1014 			g_raid_md_jmicron_refill(sc);
1015 		return (0);
1016 	}
1017 	return (-2);
1018 }
1019 
1020 static int
1021 g_raid_md_ctl_jmicron(struct g_raid_md_object *md,
1022     struct gctl_req *req)
1023 {
1024 	struct g_raid_softc *sc;
1025 	struct g_raid_volume *vol;
1026 	struct g_raid_subdisk *sd;
1027 	struct g_raid_disk *disk;
1028 	struct g_raid_md_jmicron_object *mdi;
1029 	struct g_raid_md_jmicron_perdisk *pd;
1030 	struct g_consumer *cp;
1031 	struct g_provider *pp;
1032 	char arg[16];
1033 	const char *verb, *volname, *levelname, *diskname;
1034 	int *nargs, *force;
1035 	off_t size, sectorsize, strip;
1036 	intmax_t *sizearg, *striparg;
1037 	int numdisks, i, len, level, qual, update;
1038 	int error;
1039 
1040 	sc = md->mdo_softc;
1041 	mdi = (struct g_raid_md_jmicron_object *)md;
1042 	verb = gctl_get_param(req, "verb", NULL);
1043 	nargs = gctl_get_paraml(req, "nargs", sizeof(*nargs));
1044 	error = 0;
1045 	if (strcmp(verb, "label") == 0) {
1046 
1047 		if (*nargs < 4) {
1048 			gctl_error(req, "Invalid number of arguments.");
1049 			return (-1);
1050 		}
1051 		volname = gctl_get_asciiparam(req, "arg1");
1052 		if (volname == NULL) {
1053 			gctl_error(req, "No volume name.");
1054 			return (-2);
1055 		}
1056 		levelname = gctl_get_asciiparam(req, "arg2");
1057 		if (levelname == NULL) {
1058 			gctl_error(req, "No RAID level.");
1059 			return (-3);
1060 		}
1061 		if (strcasecmp(levelname, "RAID5") == 0)
1062 			levelname = "RAID5-LA";
1063 		if (g_raid_volume_str2level(levelname, &level, &qual)) {
1064 			gctl_error(req, "Unknown RAID level '%s'.", levelname);
1065 			return (-4);
1066 		}
1067 		numdisks = *nargs - 3;
1068 		force = gctl_get_paraml(req, "force", sizeof(*force));
1069 		if (!g_raid_md_jmicron_supported(level, qual, numdisks,
1070 		    force ? *force : 0)) {
1071 			gctl_error(req, "Unsupported RAID level "
1072 			    "(0x%02x/0x%02x), or number of disks (%d).",
1073 			    level, qual, numdisks);
1074 			return (-5);
1075 		}
1076 
1077 		/* Search for disks, connect them and probe. */
1078 		size = 0x7fffffffffffffffllu;
1079 		sectorsize = 0;
1080 		for (i = 0; i < numdisks; i++) {
1081 			snprintf(arg, sizeof(arg), "arg%d", i + 3);
1082 			diskname = gctl_get_asciiparam(req, arg);
1083 			if (diskname == NULL) {
1084 				gctl_error(req, "No disk name (%s).", arg);
1085 				error = -6;
1086 				break;
1087 			}
1088 			if (strcmp(diskname, "NONE") == 0) {
1089 				cp = NULL;
1090 				pp = NULL;
1091 			} else {
1092 				g_topology_lock();
1093 				cp = g_raid_open_consumer(sc, diskname);
1094 				if (cp == NULL) {
1095 					gctl_error(req, "Can't open '%s'.",
1096 					    diskname);
1097 					g_topology_unlock();
1098 					error = -7;
1099 					break;
1100 				}
1101 				pp = cp->provider;
1102 			}
1103 			pd = malloc(sizeof(*pd), M_MD_JMICRON, M_WAITOK | M_ZERO);
1104 			pd->pd_disk_pos = i;
1105 			pd->pd_disk_id = arc4random() & JMICRON_DISK_MASK;
1106 			disk = g_raid_create_disk(sc);
1107 			disk->d_md_data = (void *)pd;
1108 			disk->d_consumer = cp;
1109 			if (cp == NULL)
1110 				continue;
1111 			cp->private = disk;
1112 			g_topology_unlock();
1113 
1114 			g_raid_get_disk_info(disk);
1115 
1116 			pd->pd_disk_size = pp->mediasize;
1117 			if (size > pp->mediasize)
1118 				size = pp->mediasize;
1119 			if (sectorsize < pp->sectorsize)
1120 				sectorsize = pp->sectorsize;
1121 		}
1122 		if (error != 0)
1123 			return (error);
1124 
1125 		if (sectorsize <= 0) {
1126 			gctl_error(req, "Can't get sector size.");
1127 			return (-8);
1128 		}
1129 
1130 		/* Reserve space for metadata. */
1131 		size -= sectorsize;
1132 
1133 		/* Handle size argument. */
1134 		len = sizeof(*sizearg);
1135 		sizearg = gctl_get_param(req, "size", &len);
1136 		if (sizearg != NULL && len == sizeof(*sizearg) &&
1137 		    *sizearg > 0) {
1138 			if (*sizearg > size) {
1139 				gctl_error(req, "Size too big %lld > %lld.",
1140 				    (long long)*sizearg, (long long)size);
1141 				return (-9);
1142 			}
1143 			size = *sizearg;
1144 		}
1145 
1146 		/* Handle strip argument. */
1147 		strip = 131072;
1148 		len = sizeof(*striparg);
1149 		striparg = gctl_get_param(req, "strip", &len);
1150 		if (striparg != NULL && len == sizeof(*striparg) &&
1151 		    *striparg > 0) {
1152 			if (*striparg < sectorsize) {
1153 				gctl_error(req, "Strip size too small.");
1154 				return (-10);
1155 			}
1156 			if (*striparg % sectorsize != 0) {
1157 				gctl_error(req, "Incorrect strip size.");
1158 				return (-11);
1159 			}
1160 			if (strip > 65535 * sectorsize) {
1161 				gctl_error(req, "Strip size too big.");
1162 				return (-12);
1163 			}
1164 			strip = *striparg;
1165 		}
1166 
1167 		/* Round size down to strip or sector. */
1168 		if (level == G_RAID_VOLUME_RL_RAID1)
1169 			size -= (size % sectorsize);
1170 		else if (level == G_RAID_VOLUME_RL_RAID1E &&
1171 		    (numdisks & 1) != 0)
1172 			size -= (size % (2 * strip));
1173 		else
1174 			size -= (size % strip);
1175 		if (size <= 0) {
1176 			gctl_error(req, "Size too small.");
1177 			return (-13);
1178 		}
1179 		if (size > 0xffffffffffffllu * sectorsize) {
1180 			gctl_error(req, "Size too big.");
1181 			return (-14);
1182 		}
1183 
1184 		/* We have all we need, create things: volume, ... */
1185 		mdi->mdio_total_disks = numdisks;
1186 		mdi->mdio_started = 1;
1187 		vol = g_raid_create_volume(sc, volname, -1);
1188 		vol->v_md_data = (void *)(intptr_t)0;
1189 		vol->v_raid_level = level;
1190 		vol->v_raid_level_qualifier = qual;
1191 		vol->v_strip_size = strip;
1192 		vol->v_disks_count = numdisks;
1193 		if (level == G_RAID_VOLUME_RL_RAID0 ||
1194 		    level == G_RAID_VOLUME_RL_CONCAT ||
1195 		    level == G_RAID_VOLUME_RL_SINGLE)
1196 			vol->v_mediasize = size * numdisks;
1197 		else if (level == G_RAID_VOLUME_RL_RAID1)
1198 			vol->v_mediasize = size;
1199 		else if (level == G_RAID_VOLUME_RL_RAID5)
1200 			vol->v_mediasize = size * (numdisks - 1);
1201 		else { /* RAID1E */
1202 			vol->v_mediasize = ((size * numdisks) / strip / 2) *
1203 			    strip;
1204 		}
1205 		vol->v_sectorsize = sectorsize;
1206 		g_raid_start_volume(vol);
1207 
1208 		/* , and subdisks. */
1209 		TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
1210 			pd = (struct g_raid_md_jmicron_perdisk *)disk->d_md_data;
1211 			sd = &vol->v_subdisks[pd->pd_disk_pos];
1212 			sd->sd_disk = disk;
1213 			sd->sd_offset = 0;
1214 			sd->sd_size = size;
1215 			TAILQ_INSERT_TAIL(&disk->d_subdisks, sd, sd_next);
1216 			if (sd->sd_disk->d_consumer != NULL) {
1217 				g_raid_change_disk_state(disk,
1218 				    G_RAID_DISK_S_ACTIVE);
1219 				g_raid_change_subdisk_state(sd,
1220 				    G_RAID_SUBDISK_S_ACTIVE);
1221 				g_raid_event_send(sd, G_RAID_SUBDISK_E_NEW,
1222 				    G_RAID_EVENT_SUBDISK);
1223 			} else {
1224 				g_raid_change_disk_state(disk, G_RAID_DISK_S_OFFLINE);
1225 			}
1226 		}
1227 
1228 		/* Write metadata based on created entities. */
1229 		G_RAID_DEBUG1(0, sc, "Array started.");
1230 		g_raid_md_write_jmicron(md, NULL, NULL, NULL);
1231 
1232 		/* Pickup any STALE/SPARE disks to refill array if needed. */
1233 		g_raid_md_jmicron_refill(sc);
1234 
1235 		g_raid_event_send(vol, G_RAID_VOLUME_E_START,
1236 		    G_RAID_EVENT_VOLUME);
1237 		return (0);
1238 	}
1239 	if (strcmp(verb, "delete") == 0) {
1240 
1241 		/* Check if some volume is still open. */
1242 		force = gctl_get_paraml(req, "force", sizeof(*force));
1243 		if (force != NULL && *force == 0 &&
1244 		    g_raid_nopens(sc) != 0) {
1245 			gctl_error(req, "Some volume is still open.");
1246 			return (-4);
1247 		}
1248 
1249 		TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
1250 			if (disk->d_consumer)
1251 				jmicron_meta_erase(disk->d_consumer);
1252 		}
1253 		g_raid_destroy_node(sc, 0);
1254 		return (0);
1255 	}
1256 	if (strcmp(verb, "remove") == 0 ||
1257 	    strcmp(verb, "fail") == 0) {
1258 		if (*nargs < 2) {
1259 			gctl_error(req, "Invalid number of arguments.");
1260 			return (-1);
1261 		}
1262 		for (i = 1; i < *nargs; i++) {
1263 			snprintf(arg, sizeof(arg), "arg%d", i);
1264 			diskname = gctl_get_asciiparam(req, arg);
1265 			if (diskname == NULL) {
1266 				gctl_error(req, "No disk name (%s).", arg);
1267 				error = -2;
1268 				break;
1269 			}
1270 			if (strncmp(diskname, "/dev/", 5) == 0)
1271 				diskname += 5;
1272 
1273 			TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
1274 				if (disk->d_consumer != NULL &&
1275 				    disk->d_consumer->provider != NULL &&
1276 				    strcmp(disk->d_consumer->provider->name,
1277 				     diskname) == 0)
1278 					break;
1279 			}
1280 			if (disk == NULL) {
1281 				gctl_error(req, "Disk '%s' not found.",
1282 				    diskname);
1283 				error = -3;
1284 				break;
1285 			}
1286 
1287 			if (strcmp(verb, "fail") == 0) {
1288 				g_raid_md_fail_disk_jmicron(md, NULL, disk);
1289 				continue;
1290 			}
1291 
1292 			pd = (struct g_raid_md_jmicron_perdisk *)disk->d_md_data;
1293 
1294 			/* Erase metadata on deleting disk. */
1295 			jmicron_meta_erase(disk->d_consumer);
1296 
1297 			/* If disk was assigned, just update statuses. */
1298 			if (pd->pd_disk_pos >= 0) {
1299 				g_raid_change_disk_state(disk, G_RAID_DISK_S_OFFLINE);
1300 				g_raid_kill_consumer(sc, disk->d_consumer);
1301 				disk->d_consumer = NULL;
1302 				TAILQ_FOREACH(sd, &disk->d_subdisks, sd_next) {
1303 					g_raid_change_subdisk_state(sd,
1304 					    G_RAID_SUBDISK_S_NONE);
1305 					g_raid_event_send(sd, G_RAID_SUBDISK_E_DISCONNECTED,
1306 					    G_RAID_EVENT_SUBDISK);
1307 				}
1308 			} else {
1309 				/* Otherwise -- delete. */
1310 				g_raid_change_disk_state(disk, G_RAID_DISK_S_NONE);
1311 				g_raid_destroy_disk(disk);
1312 			}
1313 		}
1314 
1315 		/* Write updated metadata to remaining disks. */
1316 		g_raid_md_write_jmicron(md, NULL, NULL, NULL);
1317 
1318 		/* Check if anything left except placeholders. */
1319 		if (g_raid_ndisks(sc, -1) ==
1320 		    g_raid_ndisks(sc, G_RAID_DISK_S_OFFLINE))
1321 			g_raid_destroy_node(sc, 0);
1322 		else
1323 			g_raid_md_jmicron_refill(sc);
1324 		return (error);
1325 	}
1326 	if (strcmp(verb, "insert") == 0) {
1327 		if (*nargs < 2) {
1328 			gctl_error(req, "Invalid number of arguments.");
1329 			return (-1);
1330 		}
1331 		update = 0;
1332 		for (i = 1; i < *nargs; i++) {
1333 			/* Get disk name. */
1334 			snprintf(arg, sizeof(arg), "arg%d", i);
1335 			diskname = gctl_get_asciiparam(req, arg);
1336 			if (diskname == NULL) {
1337 				gctl_error(req, "No disk name (%s).", arg);
1338 				error = -3;
1339 				break;
1340 			}
1341 
1342 			/* Try to find provider with specified name. */
1343 			g_topology_lock();
1344 			cp = g_raid_open_consumer(sc, diskname);
1345 			if (cp == NULL) {
1346 				gctl_error(req, "Can't open disk '%s'.",
1347 				    diskname);
1348 				g_topology_unlock();
1349 				error = -4;
1350 				break;
1351 			}
1352 			pp = cp->provider;
1353 
1354 			pd = malloc(sizeof(*pd), M_MD_JMICRON, M_WAITOK | M_ZERO);
1355 			pd->pd_disk_pos = -3;
1356 			pd->pd_disk_id = arc4random() & JMICRON_DISK_MASK;
1357 			pd->pd_disk_size = pp->mediasize;
1358 
1359 			disk = g_raid_create_disk(sc);
1360 			disk->d_consumer = cp;
1361 			disk->d_md_data = (void *)pd;
1362 			cp->private = disk;
1363 			g_topology_unlock();
1364 
1365 			g_raid_get_disk_info(disk);
1366 
1367 			/* Welcome the "new" disk. */
1368 			update += g_raid_md_jmicron_start_disk(disk);
1369 			if (disk->d_state != G_RAID_DISK_S_ACTIVE &&
1370 			    disk->d_state != G_RAID_DISK_S_SPARE) {
1371 				gctl_error(req, "Disk '%s' doesn't fit.",
1372 				    diskname);
1373 				g_raid_destroy_disk(disk);
1374 				error = -8;
1375 				break;
1376 			}
1377 		}
1378 
1379 		/* Write new metadata if we changed something. */
1380 		if (update)
1381 			g_raid_md_write_jmicron(md, NULL, NULL, NULL);
1382 		return (error);
1383 	}
1384 	gctl_error(req, "Command '%s' is not supported.", verb);
1385 	return (-100);
1386 }
1387 
1388 static int
1389 g_raid_md_write_jmicron(struct g_raid_md_object *md, struct g_raid_volume *tvol,
1390     struct g_raid_subdisk *tsd, struct g_raid_disk *tdisk)
1391 {
1392 	struct g_raid_softc *sc;
1393 	struct g_raid_volume *vol;
1394 	struct g_raid_subdisk *sd;
1395 	struct g_raid_disk *disk;
1396 	struct g_raid_md_jmicron_object *mdi;
1397 	struct g_raid_md_jmicron_perdisk *pd;
1398 	struct jmicron_raid_conf *meta;
1399 	int i, spares;
1400 
1401 	sc = md->mdo_softc;
1402 	mdi = (struct g_raid_md_jmicron_object *)md;
1403 
1404 	if (sc->sc_stopping == G_RAID_DESTROY_HARD)
1405 		return (0);
1406 
1407 	/* There is only one volume. */
1408 	vol = TAILQ_FIRST(&sc->sc_volumes);
1409 
1410 	/* Fill global fields. */
1411 	meta = malloc(sizeof(*meta), M_MD_JMICRON, M_WAITOK | M_ZERO);
1412 	strncpy(meta->signature, JMICRON_MAGIC, 2);
1413 	meta->version = JMICRON_VERSION;
1414 	jmicron_meta_put_name(meta, vol->v_name);
1415 	if (vol->v_raid_level == G_RAID_VOLUME_RL_RAID0)
1416 		meta->type = JMICRON_T_RAID0;
1417 	else if (vol->v_raid_level == G_RAID_VOLUME_RL_RAID1)
1418 		meta->type = JMICRON_T_RAID1;
1419 	else if (vol->v_raid_level == G_RAID_VOLUME_RL_RAID1E)
1420 		meta->type = JMICRON_T_RAID01;
1421 	else if (vol->v_raid_level == G_RAID_VOLUME_RL_CONCAT ||
1422 	    vol->v_raid_level == G_RAID_VOLUME_RL_SINGLE)
1423 		meta->type = JMICRON_T_CONCAT;
1424 	else
1425 		meta->type = JMICRON_T_RAID5;
1426 	meta->stripe_shift = fls(vol->v_strip_size / 2048);
1427 	meta->flags = JMICRON_F_READY | JMICRON_F_BOOTABLE;
1428 	for (i = 0; i < vol->v_disks_count; i++) {
1429 		sd = &vol->v_subdisks[i];
1430 		if (sd->sd_disk == NULL || sd->sd_disk->d_md_data == NULL)
1431 			meta->disks[i] = 0xffffffff;
1432 		else {
1433 			pd = (struct g_raid_md_jmicron_perdisk *)
1434 			    sd->sd_disk->d_md_data;
1435 			meta->disks[i] = pd->pd_disk_id;
1436 		}
1437 		if (sd->sd_state < G_RAID_SUBDISK_S_STALE)
1438 			meta->flags |= JMICRON_F_BADSEC;
1439 		if (vol->v_dirty)
1440 			meta->flags |= JMICRON_F_UNSYNC;
1441 	}
1442 
1443 	/* Put spares to their slots. */
1444 	spares = 0;
1445 	TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
1446 		pd = (struct g_raid_md_jmicron_perdisk *)disk->d_md_data;
1447 		if (disk->d_state != G_RAID_DISK_S_SPARE)
1448 			continue;
1449 		meta->spare[spares] = pd->pd_disk_id;
1450 		if (++spares >= 2)
1451 			break;
1452 	}
1453 
1454 	/* We are done. Print meta data and store them to disks. */
1455 	if (mdi->mdio_meta != NULL)
1456 		free(mdi->mdio_meta, M_MD_JMICRON);
1457 	mdi->mdio_meta = meta;
1458 	TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
1459 		pd = (struct g_raid_md_jmicron_perdisk *)disk->d_md_data;
1460 		if (disk->d_state != G_RAID_DISK_S_ACTIVE &&
1461 		    disk->d_state != G_RAID_DISK_S_SPARE)
1462 			continue;
1463 		if (pd->pd_meta != NULL) {
1464 			free(pd->pd_meta, M_MD_JMICRON);
1465 			pd->pd_meta = NULL;
1466 		}
1467 		pd->pd_meta = jmicron_meta_copy(meta);
1468 		pd->pd_meta->disk_id = pd->pd_disk_id;
1469 		if ((sd = TAILQ_FIRST(&disk->d_subdisks)) != NULL) {
1470 			pd->pd_meta->offset =
1471 			    (sd->sd_offset / 512) / 16;
1472 			pd->pd_meta->disk_sectors_high =
1473 			    (sd->sd_size / 512) >> 16;
1474 			pd->pd_meta->disk_sectors_low =
1475 			    (sd->sd_size / 512) & 0xffff;
1476 			if (sd->sd_state < G_RAID_SUBDISK_S_STALE)
1477 				pd->pd_meta->flags &= ~JMICRON_F_BADSEC;
1478 			else if (sd->sd_state < G_RAID_SUBDISK_S_ACTIVE)
1479 				pd->pd_meta->flags |= JMICRON_F_UNSYNC;
1480 		}
1481 		G_RAID_DEBUG(1, "Writing JMicron metadata to %s",
1482 		    g_raid_get_diskname(disk));
1483 		g_raid_md_jmicron_print(pd->pd_meta);
1484 		jmicron_meta_write(disk->d_consumer, pd->pd_meta);
1485 	}
1486 	return (0);
1487 }
1488 
1489 static int
1490 g_raid_md_fail_disk_jmicron(struct g_raid_md_object *md,
1491     struct g_raid_subdisk *tsd, struct g_raid_disk *tdisk)
1492 {
1493 	struct g_raid_softc *sc;
1494 	struct g_raid_md_jmicron_perdisk *pd;
1495 	struct g_raid_subdisk *sd;
1496 
1497 	sc = md->mdo_softc;
1498 	pd = (struct g_raid_md_jmicron_perdisk *)tdisk->d_md_data;
1499 
1500 	/* We can't fail disk that is not a part of array now. */
1501 	if (pd->pd_disk_pos < 0)
1502 		return (-1);
1503 
1504 	if (tdisk->d_consumer)
1505 		jmicron_meta_erase(tdisk->d_consumer);
1506 
1507 	/* Change states. */
1508 	g_raid_change_disk_state(tdisk, G_RAID_DISK_S_FAILED);
1509 	TAILQ_FOREACH(sd, &tdisk->d_subdisks, sd_next) {
1510 		g_raid_change_subdisk_state(sd,
1511 		    G_RAID_SUBDISK_S_FAILED);
1512 		g_raid_event_send(sd, G_RAID_SUBDISK_E_FAILED,
1513 		    G_RAID_EVENT_SUBDISK);
1514 	}
1515 
1516 	/* Write updated metadata to remaining disks. */
1517 	g_raid_md_write_jmicron(md, NULL, NULL, tdisk);
1518 
1519 	/* Check if anything left except placeholders. */
1520 	if (g_raid_ndisks(sc, -1) ==
1521 	    g_raid_ndisks(sc, G_RAID_DISK_S_OFFLINE))
1522 		g_raid_destroy_node(sc, 0);
1523 	else
1524 		g_raid_md_jmicron_refill(sc);
1525 	return (0);
1526 }
1527 
1528 static int
1529 g_raid_md_free_disk_jmicron(struct g_raid_md_object *md,
1530     struct g_raid_disk *disk)
1531 {
1532 	struct g_raid_md_jmicron_perdisk *pd;
1533 
1534 	pd = (struct g_raid_md_jmicron_perdisk *)disk->d_md_data;
1535 	if (pd->pd_meta != NULL) {
1536 		free(pd->pd_meta, M_MD_JMICRON);
1537 		pd->pd_meta = NULL;
1538 	}
1539 	free(pd, M_MD_JMICRON);
1540 	disk->d_md_data = NULL;
1541 	return (0);
1542 }
1543 
1544 static int
1545 g_raid_md_free_jmicron(struct g_raid_md_object *md)
1546 {
1547 	struct g_raid_md_jmicron_object *mdi;
1548 
1549 	mdi = (struct g_raid_md_jmicron_object *)md;
1550 	if (!mdi->mdio_started) {
1551 		mdi->mdio_started = 0;
1552 		callout_stop(&mdi->mdio_start_co);
1553 		G_RAID_DEBUG1(1, md->mdo_softc,
1554 		    "root_mount_rel %p", mdi->mdio_rootmount);
1555 		root_mount_rel(mdi->mdio_rootmount);
1556 		mdi->mdio_rootmount = NULL;
1557 	}
1558 	if (mdi->mdio_meta != NULL) {
1559 		free(mdi->mdio_meta, M_MD_JMICRON);
1560 		mdi->mdio_meta = NULL;
1561 	}
1562 	return (0);
1563 }
1564 
1565 G_RAID_MD_DECLARE(jmicron, "JMicron");
1566