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