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