xref: /freebsd/sys/geom/raid/md_sii.c (revision a7941b3326a38f203dab0b92a51e549499081a08)
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 		 * Different disks may have different sizes,
591 		 * in concat mode. Update from real disk size.
592 		 */
593 		if (meta->type == SII_T_CONCAT || meta->type == SII_T_JBOD)
594 			sd->sd_size = pd->pd_disk_size - 0x800 * 512;
595 
596 		if (resurrection) {
597 			/* New or ex-spare disk. */
598 			g_raid_change_subdisk_state(sd,
599 			    G_RAID_SUBDISK_S_NEW);
600 		} else if (pd->pd_meta->disk_status == SII_S_REBUILD) {
601 			/* Rebuilding disk. */
602 			g_raid_change_subdisk_state(sd,
603 			    G_RAID_SUBDISK_S_REBUILD);
604 			if (pd->pd_meta->generation == meta->generation)
605 				sd->sd_rebuild_pos = pd->pd_meta->rebuild_lba * 512;
606 			else
607 				sd->sd_rebuild_pos = 0;
608 		} else if (pd->pd_meta->disk_status == SII_S_CURRENT) {
609 			if (pd->pd_meta->raid_status == SII_S_ONLINE ||
610 			    pd->pd_meta->generation != meta->generation) {
611 				/* Dirty or resyncing disk. */
612 				g_raid_change_subdisk_state(sd,
613 				    G_RAID_SUBDISK_S_STALE);
614 			} else {
615 				/* Up to date disk. */
616 				g_raid_change_subdisk_state(sd,
617 				    G_RAID_SUBDISK_S_ACTIVE);
618 			}
619 		} else {
620 			g_raid_change_subdisk_state(sd,
621 			    G_RAID_SUBDISK_S_FAILED);
622 		}
623 		g_raid_event_send(sd, G_RAID_SUBDISK_E_NEW,
624 		    G_RAID_EVENT_SUBDISK);
625 	}
626 
627 	/* Update status of our need for spare. */
628 	if (mdi->mdio_started) {
629 		mdi->mdio_incomplete =
630 		    (g_raid_ndisks(sc, G_RAID_DISK_S_ACTIVE) <
631 		     mdi->mdio_total_disks);
632 	}
633 
634 	return (resurrection);
635 }
636 
637 static void
638 g_disk_md_sii_retaste(void *arg, int pending)
639 {
640 
641 	G_RAID_DEBUG(1, "Array is not complete, trying to retaste.");
642 	g_retaste(&g_raid_class);
643 	free(arg, M_MD_SII);
644 }
645 
646 static void
647 g_raid_md_sii_refill(struct g_raid_softc *sc)
648 {
649 	struct g_raid_md_object *md;
650 	struct g_raid_md_sii_object *mdi;
651 	struct g_raid_disk *disk;
652 	struct task *task;
653 	int update, na;
654 
655 	md = sc->sc_md;
656 	mdi = (struct g_raid_md_sii_object *)md;
657 	update = 0;
658 	do {
659 		/* Make sure we miss anything. */
660 		na = g_raid_ndisks(sc, G_RAID_DISK_S_ACTIVE);
661 		if (na == mdi->mdio_total_disks)
662 			break;
663 
664 		G_RAID_DEBUG1(1, md->mdo_softc,
665 		    "Array is not complete (%d of %d), "
666 		    "trying to refill.", na, mdi->mdio_total_disks);
667 
668 		/* Try to get use some of STALE disks. */
669 		TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
670 			if (disk->d_state == G_RAID_DISK_S_STALE) {
671 				update += g_raid_md_sii_start_disk(disk);
672 				if (disk->d_state == G_RAID_DISK_S_ACTIVE)
673 					break;
674 			}
675 		}
676 		if (disk != NULL)
677 			continue;
678 
679 		/* Try to get use some of SPARE disks. */
680 		TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
681 			if (disk->d_state == G_RAID_DISK_S_SPARE) {
682 				update += g_raid_md_sii_start_disk(disk);
683 				if (disk->d_state == G_RAID_DISK_S_ACTIVE)
684 					break;
685 			}
686 		}
687 	} while (disk != NULL);
688 
689 	/* Write new metadata if we changed something. */
690 	if (update)
691 		g_raid_md_write_sii(md, NULL, NULL, NULL);
692 
693 	/* Update status of our need for spare. */
694 	mdi->mdio_incomplete = (g_raid_ndisks(sc, G_RAID_DISK_S_ACTIVE) <
695 	    mdi->mdio_total_disks);
696 
697 	/* Request retaste hoping to find spare. */
698 	if (mdi->mdio_incomplete) {
699 		task = malloc(sizeof(struct task),
700 		    M_MD_SII, M_WAITOK | M_ZERO);
701 		TASK_INIT(task, 0, g_disk_md_sii_retaste, task);
702 		taskqueue_enqueue(taskqueue_swi, task);
703 	}
704 }
705 
706 static void
707 g_raid_md_sii_start(struct g_raid_softc *sc)
708 {
709 	struct g_raid_md_object *md;
710 	struct g_raid_md_sii_object *mdi;
711 	struct g_raid_md_sii_perdisk *pd;
712 	struct sii_raid_conf *meta;
713 	struct g_raid_volume *vol;
714 	struct g_raid_subdisk *sd;
715 	struct g_raid_disk *disk, *best;
716 	off_t size;
717 	int j, disk_pos;
718 	uint32_t gendiff, bestgendiff;
719 	char buf[17];
720 
721 	md = sc->sc_md;
722 	mdi = (struct g_raid_md_sii_object *)md;
723 	meta = mdi->mdio_meta;
724 
725 	/* Create volumes and subdisks. */
726 	sii_meta_get_name(meta, buf);
727 	vol = g_raid_create_volume(sc, buf, -1);
728 	vol->v_mediasize = (off_t)meta->total_sectors * 512;
729 	vol->v_raid_level_qualifier = G_RAID_VOLUME_RLQ_NONE;
730 	if (meta->type == SII_T_RAID0) {
731 		vol->v_raid_level = G_RAID_VOLUME_RL_RAID0;
732 		size = vol->v_mediasize / mdi->mdio_total_disks;
733 	} else if (meta->type == SII_T_RAID1) {
734 		vol->v_raid_level = G_RAID_VOLUME_RL_RAID1;
735 		size = vol->v_mediasize;
736 	} else if (meta->type == SII_T_RAID01) {
737 		vol->v_raid_level = G_RAID_VOLUME_RL_RAID1E;
738 		size = vol->v_mediasize / (mdi->mdio_total_disks / 2);
739 	} else if (meta->type == SII_T_CONCAT) {
740 		if (mdi->mdio_total_disks == 1)
741 			vol->v_raid_level = G_RAID_VOLUME_RL_SINGLE;
742 		else
743 			vol->v_raid_level = G_RAID_VOLUME_RL_CONCAT;
744 		size = 0;
745 	} else if (meta->type == SII_T_RAID5) {
746 		vol->v_raid_level = G_RAID_VOLUME_RL_RAID5;
747 		vol->v_raid_level_qualifier = G_RAID_VOLUME_RLQ_R5LS;
748 		size = vol->v_mediasize / (mdi->mdio_total_disks - 1);
749 	} else if (meta->type == SII_T_JBOD) {
750 		vol->v_raid_level = G_RAID_VOLUME_RL_SINGLE;
751 		size = 0;
752 	} else {
753 		vol->v_raid_level = G_RAID_VOLUME_RL_UNKNOWN;
754 		size = 0;
755 	}
756 	vol->v_strip_size = meta->strip_sectors * 512; //ZZZ
757 	vol->v_disks_count = mdi->mdio_total_disks;
758 	vol->v_sectorsize = 512; //ZZZ
759 	for (j = 0; j < vol->v_disks_count; j++) {
760 		sd = &vol->v_subdisks[j];
761 		sd->sd_offset = 0;
762 		sd->sd_size = size;
763 	}
764 	g_raid_start_volume(vol);
765 
766 	/* Create disk placeholders to store data for later writing. */
767 	for (disk_pos = 0; disk_pos < mdi->mdio_total_disks; disk_pos++) {
768 		pd = malloc(sizeof(*pd), M_MD_SII, M_WAITOK | M_ZERO);
769 		pd->pd_disk_pos = disk_pos;
770 		disk = g_raid_create_disk(sc);
771 		disk->d_md_data = (void *)pd;
772 		disk->d_state = G_RAID_DISK_S_OFFLINE;
773 		sd = &vol->v_subdisks[disk_pos];
774 		sd->sd_disk = disk;
775 		TAILQ_INSERT_TAIL(&disk->d_subdisks, sd, sd_next);
776 	}
777 
778 	/*
779 	 * Make all disks found till the moment take their places
780 	 * in order of their generation numbers.
781 	 */
782 	do {
783 		best = NULL;
784 		bestgendiff = 0xffffffff;
785 		TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
786 			if (disk->d_state != G_RAID_DISK_S_NONE)
787 				continue;
788 			pd = disk->d_md_data;
789 			if (pd->pd_meta == NULL)
790 				gendiff = 0xfffffffe;
791 			else
792 				gendiff = meta->generation -
793 				    pd->pd_meta->generation;
794 			if (gendiff < bestgendiff) {
795 				best = disk;
796 				bestgendiff = gendiff;
797 			}
798 		}
799 		if (best != NULL)
800 			g_raid_md_sii_start_disk(best);
801 	} while (best != NULL);
802 
803 	mdi->mdio_started = 1;
804 	G_RAID_DEBUG1(0, sc, "Array started.");
805 	g_raid_md_write_sii(md, NULL, NULL, NULL);
806 
807 	/* Pickup any STALE/SPARE disks to refill array if needed. */
808 	g_raid_md_sii_refill(sc);
809 
810 	g_raid_event_send(vol, G_RAID_VOLUME_E_START, G_RAID_EVENT_VOLUME);
811 
812 	callout_stop(&mdi->mdio_start_co);
813 	G_RAID_DEBUG1(1, sc, "root_mount_rel %p", mdi->mdio_rootmount);
814 	root_mount_rel(mdi->mdio_rootmount);
815 	mdi->mdio_rootmount = NULL;
816 }
817 
818 static void
819 g_raid_md_sii_new_disk(struct g_raid_disk *disk)
820 {
821 	struct g_raid_softc *sc;
822 	struct g_raid_md_object *md;
823 	struct g_raid_md_sii_object *mdi;
824 	struct sii_raid_conf *pdmeta;
825 	struct g_raid_md_sii_perdisk *pd;
826 
827 	sc = disk->d_softc;
828 	md = sc->sc_md;
829 	mdi = (struct g_raid_md_sii_object *)md;
830 	pd = (struct g_raid_md_sii_perdisk *)disk->d_md_data;
831 	pdmeta = pd->pd_meta;
832 
833 	if (mdi->mdio_started) {
834 		if (g_raid_md_sii_start_disk(disk))
835 			g_raid_md_write_sii(md, NULL, NULL, NULL);
836 	} else {
837 		if (mdi->mdio_meta == NULL ||
838 		    ((int32_t)(pdmeta->generation - mdi->mdio_generation)) > 0) {
839 			G_RAID_DEBUG1(1, sc, "Newer disk");
840 			if (mdi->mdio_meta != NULL)
841 				free(mdi->mdio_meta, M_MD_SII);
842 			mdi->mdio_meta = sii_meta_copy(pdmeta);
843 			mdi->mdio_generation = mdi->mdio_meta->generation;
844 			mdi->mdio_total_disks = sii_meta_total_disks(pdmeta);
845 			mdi->mdio_disks_present = 1;
846 		} else if (pdmeta->generation == mdi->mdio_generation) {
847 			mdi->mdio_disks_present++;
848 			G_RAID_DEBUG1(1, sc, "Matching disk (%d of %d up)",
849 			    mdi->mdio_disks_present,
850 			    mdi->mdio_total_disks);
851 		} else {
852 			G_RAID_DEBUG1(1, sc, "Older disk");
853 		}
854 
855 		/* If we collected all needed disks - start array. */
856 		if (mdi->mdio_disks_present == mdi->mdio_total_disks)
857 			g_raid_md_sii_start(sc);
858 	}
859 }
860 
861 static void
862 g_raid_sii_go(void *arg)
863 {
864 	struct g_raid_softc *sc;
865 	struct g_raid_md_object *md;
866 	struct g_raid_md_sii_object *mdi;
867 
868 	sc = arg;
869 	md = sc->sc_md;
870 	mdi = (struct g_raid_md_sii_object *)md;
871 	if (!mdi->mdio_started) {
872 		G_RAID_DEBUG1(0, sc, "Force array start due to timeout.");
873 		g_raid_event_send(sc, G_RAID_NODE_E_START, 0);
874 	}
875 }
876 
877 static int
878 g_raid_md_create_sii(struct g_raid_md_object *md, struct g_class *mp,
879     struct g_geom **gp)
880 {
881 	struct g_raid_softc *sc;
882 	struct g_raid_md_sii_object *mdi;
883 	char name[32];
884 
885 	mdi = (struct g_raid_md_sii_object *)md;
886 	mdi->mdio_timestamp[5] = arc4random();
887 	mdi->mdio_timestamp[4] = arc4random();
888 	mdi->mdio_timestamp[3] = arc4random();
889 	mdi->mdio_timestamp[2] = arc4random();
890 	mdi->mdio_timestamp[1] = arc4random();
891 	mdi->mdio_timestamp[0] = arc4random();
892 	mdi->mdio_location = arc4random();
893 	mdi->mdio_generation = 0;
894 	snprintf(name, sizeof(name), "SiI-%02x%02x%02x%02x%02x%02x",
895 	    mdi->mdio_timestamp[5], mdi->mdio_timestamp[4],
896 	    mdi->mdio_timestamp[3], mdi->mdio_timestamp[2],
897 	    mdi->mdio_timestamp[1], mdi->mdio_timestamp[0]);
898 	sc = g_raid_create_node(mp, name, md);
899 	if (sc == NULL)
900 		return (G_RAID_MD_TASTE_FAIL);
901 	md->mdo_softc = sc;
902 	*gp = sc->sc_geom;
903 	return (G_RAID_MD_TASTE_NEW);
904 }
905 
906 static int
907 g_raid_md_taste_sii(struct g_raid_md_object *md, struct g_class *mp,
908                               struct g_consumer *cp, struct g_geom **gp)
909 {
910 	struct g_consumer *rcp;
911 	struct g_provider *pp;
912 	struct g_raid_md_sii_object *mdi, *mdi1;
913 	struct g_raid_softc *sc;
914 	struct g_raid_disk *disk;
915 	struct sii_raid_conf *meta;
916 	struct g_raid_md_sii_perdisk *pd;
917 	struct g_geom *geom;
918 	int disk_pos, result, spare, len;
919 	char name[32];
920 	uint16_t vendor;
921 
922 	G_RAID_DEBUG(1, "Tasting SiI on %s", cp->provider->name);
923 	mdi = (struct g_raid_md_sii_object *)md;
924 	pp = cp->provider;
925 
926 	/* Read metadata from device. */
927 	meta = NULL;
928 	g_topology_unlock();
929 	vendor = 0xffff;
930 	len = sizeof(vendor);
931 	if (pp->geom->rank == 1)
932 		g_io_getattr("GEOM::hba_vendor", cp, &len, &vendor);
933 	meta = sii_meta_read(cp);
934 	g_topology_lock();
935 	if (meta == NULL) {
936 		if (g_raid_aggressive_spare) {
937 			if (vendor == 0x1095) {
938 				G_RAID_DEBUG(1,
939 				    "No SiI metadata, forcing spare.");
940 				spare = 2;
941 				goto search;
942 			} else {
943 				G_RAID_DEBUG(1,
944 				    "SiI vendor mismatch 0x%04x != 0x1095",
945 				    vendor);
946 			}
947 		}
948 		return (G_RAID_MD_TASTE_FAIL);
949 	}
950 
951 	/* Check this disk position in obtained metadata. */
952 	disk_pos = sii_meta_disk_pos(meta, meta);
953 	if (disk_pos == -1) {
954 		G_RAID_DEBUG(1, "SiI disk position not found");
955 		goto fail1;
956 	}
957 
958 	/* Metadata valid. Print it. */
959 	g_raid_md_sii_print(meta);
960 	G_RAID_DEBUG(1, "SiI disk position %d", disk_pos);
961 	spare = (meta->type == SII_T_SPARE) ? 1 : 0;
962 
963 search:
964 	/* Search for matching node. */
965 	sc = NULL;
966 	mdi1 = NULL;
967 	LIST_FOREACH(geom, &mp->geom, geom) {
968 		sc = geom->softc;
969 		if (sc == NULL)
970 			continue;
971 		if (sc->sc_stopping != 0)
972 			continue;
973 		if (sc->sc_md->mdo_class != md->mdo_class)
974 			continue;
975 		mdi1 = (struct g_raid_md_sii_object *)sc->sc_md;
976 		if (spare) {
977 			if (mdi1->mdio_incomplete)
978 				break;
979 		} else {
980 			if (mdi1->mdio_location == meta->raid_location &&
981 			    memcmp(&mdi1->mdio_timestamp,
982 			     &meta->timestamp, 6) == 0)
983 				break;
984 		}
985 	}
986 
987 	/* Found matching node. */
988 	if (geom != NULL) {
989 		G_RAID_DEBUG(1, "Found matching array %s", sc->sc_name);
990 		result = G_RAID_MD_TASTE_EXISTING;
991 
992 	} else if (spare) { /* Not found needy node -- left for later. */
993 		G_RAID_DEBUG(1, "Spare is not needed at this time");
994 		goto fail1;
995 
996 	} else { /* Not found matching node -- create one. */
997 		result = G_RAID_MD_TASTE_NEW;
998 		memcpy(&mdi->mdio_timestamp, &meta->timestamp, 6);
999 		mdi->mdio_location = meta->raid_location;
1000 		snprintf(name, sizeof(name), "SiI-%02x%02x%02x%02x%02x%02x",
1001 		    mdi->mdio_timestamp[5], mdi->mdio_timestamp[4],
1002 		    mdi->mdio_timestamp[3], mdi->mdio_timestamp[2],
1003 		    mdi->mdio_timestamp[1], mdi->mdio_timestamp[0]);
1004 		sc = g_raid_create_node(mp, name, md);
1005 		md->mdo_softc = sc;
1006 		geom = sc->sc_geom;
1007 		callout_init(&mdi->mdio_start_co, 1);
1008 		callout_reset(&mdi->mdio_start_co, g_raid_start_timeout * hz,
1009 		    g_raid_sii_go, sc);
1010 		mdi->mdio_rootmount = root_mount_hold("GRAID-SiI");
1011 		G_RAID_DEBUG1(1, sc, "root_mount_hold %p", mdi->mdio_rootmount);
1012 	}
1013 
1014 	/* There is no return after this point, so we close passed consumer. */
1015 	g_access(cp, -1, 0, 0);
1016 
1017 	rcp = g_new_consumer(geom);
1018 	rcp->flags |= G_CF_DIRECT_RECEIVE;
1019 	g_attach(rcp, pp);
1020 	if (g_access(rcp, 1, 1, 1) != 0)
1021 		; //goto fail1;
1022 
1023 	g_topology_unlock();
1024 	sx_xlock(&sc->sc_lock);
1025 
1026 	pd = malloc(sizeof(*pd), M_MD_SII, M_WAITOK | M_ZERO);
1027 	pd->pd_meta = meta;
1028 	if (spare == 2) {
1029 		pd->pd_disk_pos = -3;
1030 	} else {
1031 		pd->pd_disk_pos = -1;
1032 	}
1033 	pd->pd_disk_size = pp->mediasize;
1034 	disk = g_raid_create_disk(sc);
1035 	disk->d_md_data = (void *)pd;
1036 	disk->d_consumer = rcp;
1037 	rcp->private = disk;
1038 
1039 	g_raid_get_disk_info(disk);
1040 
1041 	g_raid_md_sii_new_disk(disk);
1042 
1043 	sx_xunlock(&sc->sc_lock);
1044 	g_topology_lock();
1045 	*gp = geom;
1046 	return (result);
1047 fail1:
1048 	free(meta, M_MD_SII);
1049 	return (G_RAID_MD_TASTE_FAIL);
1050 }
1051 
1052 static int
1053 g_raid_md_event_sii(struct g_raid_md_object *md,
1054     struct g_raid_disk *disk, u_int event)
1055 {
1056 	struct g_raid_softc *sc;
1057 	struct g_raid_subdisk *sd;
1058 	struct g_raid_md_sii_object *mdi;
1059 	struct g_raid_md_sii_perdisk *pd;
1060 
1061 	sc = md->mdo_softc;
1062 	mdi = (struct g_raid_md_sii_object *)md;
1063 	if (disk == NULL) {
1064 		switch (event) {
1065 		case G_RAID_NODE_E_START:
1066 			if (!mdi->mdio_started)
1067 				g_raid_md_sii_start(sc);
1068 			return (0);
1069 		}
1070 		return (-1);
1071 	}
1072 	pd = (struct g_raid_md_sii_perdisk *)disk->d_md_data;
1073 	switch (event) {
1074 	case G_RAID_DISK_E_DISCONNECTED:
1075 		/* If disk was assigned, just update statuses. */
1076 		if (pd->pd_disk_pos >= 0) {
1077 			g_raid_change_disk_state(disk, G_RAID_DISK_S_OFFLINE);
1078 			if (disk->d_consumer) {
1079 				g_raid_kill_consumer(sc, disk->d_consumer);
1080 				disk->d_consumer = NULL;
1081 			}
1082 			TAILQ_FOREACH(sd, &disk->d_subdisks, sd_next) {
1083 				g_raid_change_subdisk_state(sd,
1084 				    G_RAID_SUBDISK_S_NONE);
1085 				g_raid_event_send(sd, G_RAID_SUBDISK_E_DISCONNECTED,
1086 				    G_RAID_EVENT_SUBDISK);
1087 			}
1088 		} else {
1089 			/* Otherwise -- delete. */
1090 			g_raid_change_disk_state(disk, G_RAID_DISK_S_NONE);
1091 			g_raid_destroy_disk(disk);
1092 		}
1093 
1094 		/* Write updated metadata to all disks. */
1095 		g_raid_md_write_sii(md, NULL, NULL, NULL);
1096 
1097 		/* Check if anything left except placeholders. */
1098 		if (g_raid_ndisks(sc, -1) ==
1099 		    g_raid_ndisks(sc, G_RAID_DISK_S_OFFLINE))
1100 			g_raid_destroy_node(sc, 0);
1101 		else
1102 			g_raid_md_sii_refill(sc);
1103 		return (0);
1104 	}
1105 	return (-2);
1106 }
1107 
1108 static int
1109 g_raid_md_ctl_sii(struct g_raid_md_object *md,
1110     struct gctl_req *req)
1111 {
1112 	struct g_raid_softc *sc;
1113 	struct g_raid_volume *vol;
1114 	struct g_raid_subdisk *sd;
1115 	struct g_raid_disk *disk;
1116 	struct g_raid_md_sii_object *mdi;
1117 	struct g_raid_md_sii_perdisk *pd;
1118 	struct g_consumer *cp;
1119 	struct g_provider *pp;
1120 	char arg[16];
1121 	const char *verb, *volname, *levelname, *diskname;
1122 	int *nargs, *force;
1123 	off_t size, sectorsize, strip;
1124 	intmax_t *sizearg, *striparg;
1125 	int numdisks, i, len, level, qual, update;
1126 	int error;
1127 
1128 	sc = md->mdo_softc;
1129 	mdi = (struct g_raid_md_sii_object *)md;
1130 	verb = gctl_get_param(req, "verb", NULL);
1131 	nargs = gctl_get_paraml(req, "nargs", sizeof(*nargs));
1132 	error = 0;
1133 	if (strcmp(verb, "label") == 0) {
1134 		if (*nargs < 4) {
1135 			gctl_error(req, "Invalid number of arguments.");
1136 			return (-1);
1137 		}
1138 		volname = gctl_get_asciiparam(req, "arg1");
1139 		if (volname == NULL) {
1140 			gctl_error(req, "No volume name.");
1141 			return (-2);
1142 		}
1143 		levelname = gctl_get_asciiparam(req, "arg2");
1144 		if (levelname == NULL) {
1145 			gctl_error(req, "No RAID level.");
1146 			return (-3);
1147 		}
1148 		if (strcasecmp(levelname, "RAID5") == 0)
1149 			levelname = "RAID5-LS";
1150 		if (g_raid_volume_str2level(levelname, &level, &qual)) {
1151 			gctl_error(req, "Unknown RAID level '%s'.", levelname);
1152 			return (-4);
1153 		}
1154 		numdisks = *nargs - 3;
1155 		force = gctl_get_paraml(req, "force", sizeof(*force));
1156 		if (!g_raid_md_sii_supported(level, qual, numdisks,
1157 		    force ? *force : 0)) {
1158 			gctl_error(req, "Unsupported RAID level "
1159 			    "(0x%02x/0x%02x), or number of disks (%d).",
1160 			    level, qual, numdisks);
1161 			return (-5);
1162 		}
1163 
1164 		/* Search for disks, connect them and probe. */
1165 		size = 0x7fffffffffffffffllu;
1166 		sectorsize = 0;
1167 		for (i = 0; i < numdisks; i++) {
1168 			snprintf(arg, sizeof(arg), "arg%d", i + 3);
1169 			diskname = gctl_get_asciiparam(req, arg);
1170 			if (diskname == NULL) {
1171 				gctl_error(req, "No disk name (%s).", arg);
1172 				error = -6;
1173 				break;
1174 			}
1175 			if (strcmp(diskname, "NONE") == 0) {
1176 				cp = NULL;
1177 				pp = NULL;
1178 			} else {
1179 				g_topology_lock();
1180 				cp = g_raid_open_consumer(sc, diskname);
1181 				if (cp == NULL) {
1182 					gctl_error(req, "Can't open '%s'.",
1183 					    diskname);
1184 					g_topology_unlock();
1185 					error = -7;
1186 					break;
1187 				}
1188 				pp = cp->provider;
1189 			}
1190 			pd = malloc(sizeof(*pd), M_MD_SII, M_WAITOK | M_ZERO);
1191 			pd->pd_disk_pos = i;
1192 			disk = g_raid_create_disk(sc);
1193 			disk->d_md_data = (void *)pd;
1194 			disk->d_consumer = cp;
1195 			if (cp == NULL)
1196 				continue;
1197 			cp->private = disk;
1198 			g_topology_unlock();
1199 
1200 			g_raid_get_disk_info(disk);
1201 
1202 			pd->pd_disk_size = pp->mediasize;
1203 			if (size > pp->mediasize)
1204 				size = pp->mediasize;
1205 			if (sectorsize < pp->sectorsize)
1206 				sectorsize = pp->sectorsize;
1207 		}
1208 		if (error != 0)
1209 			return (error);
1210 
1211 		if (sectorsize <= 0) {
1212 			gctl_error(req, "Can't get sector size.");
1213 			return (-8);
1214 		}
1215 
1216 		/* Reserve space for metadata. */
1217 		size -= 0x800 * sectorsize;
1218 
1219 		/* Handle size argument. */
1220 		len = sizeof(*sizearg);
1221 		sizearg = gctl_get_param(req, "size", &len);
1222 		if (sizearg != NULL && len == sizeof(*sizearg) &&
1223 		    *sizearg > 0) {
1224 			if (*sizearg > size) {
1225 				gctl_error(req, "Size too big %lld > %lld.",
1226 				    (long long)*sizearg, (long long)size);
1227 				return (-9);
1228 			}
1229 			size = *sizearg;
1230 		}
1231 
1232 		/* Handle strip argument. */
1233 		strip = 131072;
1234 		len = sizeof(*striparg);
1235 		striparg = gctl_get_param(req, "strip", &len);
1236 		if (striparg != NULL && len == sizeof(*striparg) &&
1237 		    *striparg > 0) {
1238 			if (*striparg < sectorsize) {
1239 				gctl_error(req, "Strip size too small.");
1240 				return (-10);
1241 			}
1242 			if (*striparg % sectorsize != 0) {
1243 				gctl_error(req, "Incorrect strip size.");
1244 				return (-11);
1245 			}
1246 			if (strip > 65535 * sectorsize) {
1247 				gctl_error(req, "Strip size too big.");
1248 				return (-12);
1249 			}
1250 			strip = *striparg;
1251 		}
1252 
1253 		/* Round size down to strip or sector. */
1254 		if (level == G_RAID_VOLUME_RL_RAID1)
1255 			size -= (size % sectorsize);
1256 		else if (level == G_RAID_VOLUME_RL_RAID1E &&
1257 		    (numdisks & 1) != 0)
1258 			size -= (size % (2 * strip));
1259 		else
1260 			size -= (size % strip);
1261 		if (size <= 0) {
1262 			gctl_error(req, "Size too small.");
1263 			return (-13);
1264 		}
1265 		if (size > 0xffffffffffffllu * sectorsize) {
1266 			gctl_error(req, "Size too big.");
1267 			return (-14);
1268 		}
1269 
1270 		/* We have all we need, create things: volume, ... */
1271 		mdi->mdio_total_disks = numdisks;
1272 		mdi->mdio_started = 1;
1273 		vol = g_raid_create_volume(sc, volname, -1);
1274 		vol->v_md_data = (void *)(intptr_t)0;
1275 		vol->v_raid_level = level;
1276 		vol->v_raid_level_qualifier = qual;
1277 		vol->v_strip_size = strip;
1278 		vol->v_disks_count = numdisks;
1279 		if (level == G_RAID_VOLUME_RL_RAID0 ||
1280 		    level == G_RAID_VOLUME_RL_CONCAT ||
1281 		    level == G_RAID_VOLUME_RL_SINGLE)
1282 			vol->v_mediasize = size * numdisks;
1283 		else if (level == G_RAID_VOLUME_RL_RAID1)
1284 			vol->v_mediasize = size;
1285 		else if (level == G_RAID_VOLUME_RL_RAID5)
1286 			vol->v_mediasize = size * (numdisks - 1);
1287 		else { /* RAID1E */
1288 			vol->v_mediasize = ((size * numdisks) / strip / 2) *
1289 			    strip;
1290 		}
1291 		vol->v_sectorsize = sectorsize;
1292 		g_raid_start_volume(vol);
1293 
1294 		/* , and subdisks. */
1295 		TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
1296 			pd = (struct g_raid_md_sii_perdisk *)disk->d_md_data;
1297 			sd = &vol->v_subdisks[pd->pd_disk_pos];
1298 			sd->sd_disk = disk;
1299 			sd->sd_offset = 0;
1300 			sd->sd_size = size;
1301 			TAILQ_INSERT_TAIL(&disk->d_subdisks, sd, sd_next);
1302 			if (sd->sd_disk->d_consumer != NULL) {
1303 				g_raid_change_disk_state(disk,
1304 				    G_RAID_DISK_S_ACTIVE);
1305 				g_raid_change_subdisk_state(sd,
1306 				    G_RAID_SUBDISK_S_ACTIVE);
1307 				g_raid_event_send(sd, G_RAID_SUBDISK_E_NEW,
1308 				    G_RAID_EVENT_SUBDISK);
1309 			} else {
1310 				g_raid_change_disk_state(disk, G_RAID_DISK_S_OFFLINE);
1311 			}
1312 		}
1313 
1314 		/* Write metadata based on created entities. */
1315 		G_RAID_DEBUG1(0, sc, "Array started.");
1316 		g_raid_md_write_sii(md, NULL, NULL, NULL);
1317 
1318 		/* Pickup any STALE/SPARE disks to refill array if needed. */
1319 		g_raid_md_sii_refill(sc);
1320 
1321 		g_raid_event_send(vol, G_RAID_VOLUME_E_START,
1322 		    G_RAID_EVENT_VOLUME);
1323 		return (0);
1324 	}
1325 	if (strcmp(verb, "delete") == 0) {
1326 		/* Check if some volume is still open. */
1327 		force = gctl_get_paraml(req, "force", sizeof(*force));
1328 		if (force != NULL && *force == 0 &&
1329 		    g_raid_nopens(sc) != 0) {
1330 			gctl_error(req, "Some volume is still open.");
1331 			return (-4);
1332 		}
1333 
1334 		TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
1335 			if (disk->d_consumer)
1336 				sii_meta_erase(disk->d_consumer);
1337 		}
1338 		g_raid_destroy_node(sc, 0);
1339 		return (0);
1340 	}
1341 	if (strcmp(verb, "remove") == 0 ||
1342 	    strcmp(verb, "fail") == 0) {
1343 		if (*nargs < 2) {
1344 			gctl_error(req, "Invalid number of arguments.");
1345 			return (-1);
1346 		}
1347 		for (i = 1; i < *nargs; i++) {
1348 			snprintf(arg, sizeof(arg), "arg%d", i);
1349 			diskname = gctl_get_asciiparam(req, arg);
1350 			if (diskname == NULL) {
1351 				gctl_error(req, "No disk name (%s).", arg);
1352 				error = -2;
1353 				break;
1354 			}
1355 			if (strncmp(diskname, _PATH_DEV, 5) == 0)
1356 				diskname += 5;
1357 
1358 			TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
1359 				if (disk->d_consumer != NULL &&
1360 				    disk->d_consumer->provider != NULL &&
1361 				    strcmp(disk->d_consumer->provider->name,
1362 				     diskname) == 0)
1363 					break;
1364 			}
1365 			if (disk == NULL) {
1366 				gctl_error(req, "Disk '%s' not found.",
1367 				    diskname);
1368 				error = -3;
1369 				break;
1370 			}
1371 
1372 			if (strcmp(verb, "fail") == 0) {
1373 				g_raid_md_fail_disk_sii(md, NULL, disk);
1374 				continue;
1375 			}
1376 
1377 			pd = (struct g_raid_md_sii_perdisk *)disk->d_md_data;
1378 
1379 			/* Erase metadata on deleting disk. */
1380 			sii_meta_erase(disk->d_consumer);
1381 
1382 			/* If disk was assigned, just update statuses. */
1383 			if (pd->pd_disk_pos >= 0) {
1384 				g_raid_change_disk_state(disk, G_RAID_DISK_S_OFFLINE);
1385 				g_raid_kill_consumer(sc, disk->d_consumer);
1386 				disk->d_consumer = NULL;
1387 				TAILQ_FOREACH(sd, &disk->d_subdisks, sd_next) {
1388 					g_raid_change_subdisk_state(sd,
1389 					    G_RAID_SUBDISK_S_NONE);
1390 					g_raid_event_send(sd, G_RAID_SUBDISK_E_DISCONNECTED,
1391 					    G_RAID_EVENT_SUBDISK);
1392 				}
1393 			} else {
1394 				/* Otherwise -- delete. */
1395 				g_raid_change_disk_state(disk, G_RAID_DISK_S_NONE);
1396 				g_raid_destroy_disk(disk);
1397 			}
1398 		}
1399 
1400 		/* Write updated metadata to remaining disks. */
1401 		g_raid_md_write_sii(md, NULL, NULL, NULL);
1402 
1403 		/* Check if anything left except placeholders. */
1404 		if (g_raid_ndisks(sc, -1) ==
1405 		    g_raid_ndisks(sc, G_RAID_DISK_S_OFFLINE))
1406 			g_raid_destroy_node(sc, 0);
1407 		else
1408 			g_raid_md_sii_refill(sc);
1409 		return (error);
1410 	}
1411 	if (strcmp(verb, "insert") == 0) {
1412 		if (*nargs < 2) {
1413 			gctl_error(req, "Invalid number of arguments.");
1414 			return (-1);
1415 		}
1416 		update = 0;
1417 		for (i = 1; i < *nargs; i++) {
1418 			/* Get disk name. */
1419 			snprintf(arg, sizeof(arg), "arg%d", i);
1420 			diskname = gctl_get_asciiparam(req, arg);
1421 			if (diskname == NULL) {
1422 				gctl_error(req, "No disk name (%s).", arg);
1423 				error = -3;
1424 				break;
1425 			}
1426 
1427 			/* Try to find provider with specified name. */
1428 			g_topology_lock();
1429 			cp = g_raid_open_consumer(sc, diskname);
1430 			if (cp == NULL) {
1431 				gctl_error(req, "Can't open disk '%s'.",
1432 				    diskname);
1433 				g_topology_unlock();
1434 				error = -4;
1435 				break;
1436 			}
1437 			pp = cp->provider;
1438 
1439 			pd = malloc(sizeof(*pd), M_MD_SII, M_WAITOK | M_ZERO);
1440 			pd->pd_disk_pos = -3;
1441 			pd->pd_disk_size = pp->mediasize;
1442 
1443 			disk = g_raid_create_disk(sc);
1444 			disk->d_consumer = cp;
1445 			disk->d_md_data = (void *)pd;
1446 			cp->private = disk;
1447 			g_topology_unlock();
1448 
1449 			g_raid_get_disk_info(disk);
1450 
1451 			/* Welcome the "new" disk. */
1452 			update += g_raid_md_sii_start_disk(disk);
1453 			if (disk->d_state == G_RAID_DISK_S_SPARE) {
1454 				sii_meta_write_spare(cp);
1455 				g_raid_destroy_disk(disk);
1456 			} else if (disk->d_state != G_RAID_DISK_S_ACTIVE) {
1457 				gctl_error(req, "Disk '%s' doesn't fit.",
1458 				    diskname);
1459 				g_raid_destroy_disk(disk);
1460 				error = -8;
1461 				break;
1462 			}
1463 		}
1464 
1465 		/* Write new metadata if we changed something. */
1466 		if (update)
1467 			g_raid_md_write_sii(md, NULL, NULL, NULL);
1468 		return (error);
1469 	}
1470 	gctl_error(req, "Command '%s' is not supported.", verb);
1471 	return (-100);
1472 }
1473 
1474 static int
1475 g_raid_md_write_sii(struct g_raid_md_object *md, struct g_raid_volume *tvol,
1476     struct g_raid_subdisk *tsd, struct g_raid_disk *tdisk)
1477 {
1478 	struct g_raid_softc *sc;
1479 	struct g_raid_volume *vol;
1480 	struct g_raid_subdisk *sd;
1481 	struct g_raid_disk *disk;
1482 	struct g_raid_md_sii_object *mdi;
1483 	struct g_raid_md_sii_perdisk *pd;
1484 	struct sii_raid_conf *meta;
1485 	u_int i;
1486 
1487 	sc = md->mdo_softc;
1488 	mdi = (struct g_raid_md_sii_object *)md;
1489 
1490 	if (sc->sc_stopping == G_RAID_DESTROY_HARD)
1491 		return (0);
1492 
1493 	/* Bump generation. Newly written metadata may differ from previous. */
1494 	mdi->mdio_generation++;
1495 
1496 	/* There is only one volume. */
1497 	vol = TAILQ_FIRST(&sc->sc_volumes);
1498 
1499 	/* Fill global fields. */
1500 	meta = malloc(sizeof(*meta), M_MD_SII, M_WAITOK | M_ZERO);
1501 	if (mdi->mdio_meta)
1502 		memcpy(meta, mdi->mdio_meta, sizeof(*meta));
1503 	meta->total_sectors = vol->v_mediasize / vol->v_sectorsize;
1504 	meta->vendor_id = 0x1095;
1505 	meta->version_minor = 0;
1506 	meta->version_major = 2;
1507 	memcpy(&meta->timestamp, &mdi->mdio_timestamp, 6);
1508 	meta->strip_sectors = vol->v_strip_size / vol->v_sectorsize;
1509 	if (vol->v_raid_level == G_RAID_VOLUME_RL_RAID0) {
1510 		meta->type = SII_T_RAID0;
1511 		meta->raid0_disks = vol->v_disks_count;
1512 		meta->raid1_disks = 0xff;
1513 	} else if (vol->v_raid_level == G_RAID_VOLUME_RL_RAID1) {
1514 		meta->type = SII_T_RAID1;
1515 		meta->raid0_disks = 0xff;
1516 		meta->raid1_disks = vol->v_disks_count;
1517 	} else if (vol->v_raid_level == G_RAID_VOLUME_RL_RAID1E) {
1518 		meta->type = SII_T_RAID01;
1519 		meta->raid0_disks = vol->v_disks_count / 2;
1520 		meta->raid1_disks = 2;
1521 	} else if (vol->v_raid_level == G_RAID_VOLUME_RL_CONCAT ||
1522 	    vol->v_raid_level == G_RAID_VOLUME_RL_SINGLE) {
1523 		meta->type = SII_T_JBOD;
1524 		meta->raid0_disks = vol->v_disks_count;
1525 		meta->raid1_disks = 0xff;
1526 	} else {
1527 		meta->type = SII_T_RAID5;
1528 		meta->raid0_disks = vol->v_disks_count;
1529 		meta->raid1_disks = 0xff;
1530 	}
1531 	meta->generation = mdi->mdio_generation;
1532 	meta->raid_status = vol->v_dirty ? SII_S_ONLINE : SII_S_AVAILABLE;
1533 	for (i = 0; i < vol->v_disks_count; i++) {
1534 		sd = &vol->v_subdisks[i];
1535 		if (sd->sd_state == G_RAID_SUBDISK_S_STALE ||
1536 		    sd->sd_state == G_RAID_SUBDISK_S_RESYNC)
1537 			meta->raid_status = SII_S_ONLINE;
1538 	}
1539 	meta->raid_location = mdi->mdio_location;
1540 	sii_meta_put_name(meta, vol->v_name);
1541 
1542 	/* We are done. Print meta data and store them to disks. */
1543 	if (mdi->mdio_meta != NULL)
1544 		free(mdi->mdio_meta, M_MD_SII);
1545 	mdi->mdio_meta = meta;
1546 	TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
1547 		pd = (struct g_raid_md_sii_perdisk *)disk->d_md_data;
1548 		if (disk->d_state != G_RAID_DISK_S_ACTIVE)
1549 			continue;
1550 		if (pd->pd_meta != NULL) {
1551 			free(pd->pd_meta, M_MD_SII);
1552 			pd->pd_meta = NULL;
1553 		}
1554 		pd->pd_meta = sii_meta_copy(meta);
1555 		if ((sd = TAILQ_FIRST(&disk->d_subdisks)) != NULL) {
1556 			if (sd->sd_state < G_RAID_SUBDISK_S_NEW)
1557 				pd->pd_meta->disk_status = SII_S_DROPPED;
1558 			else if (sd->sd_state < G_RAID_SUBDISK_S_STALE) {
1559 				pd->pd_meta->disk_status = SII_S_REBUILD;
1560 				pd->pd_meta->rebuild_lba =
1561 				    sd->sd_rebuild_pos / vol->v_sectorsize;
1562 			} else
1563 				pd->pd_meta->disk_status = SII_S_CURRENT;
1564 			if (vol->v_raid_level == G_RAID_VOLUME_RL_RAID1) {
1565 				pd->pd_meta->disk_number = sd->sd_pos;
1566 				pd->pd_meta->raid0_ident = 0xff;
1567 				pd->pd_meta->raid1_ident = 0;
1568 			} else if (vol->v_raid_level == G_RAID_VOLUME_RL_RAID1E) {
1569 				pd->pd_meta->disk_number = sd->sd_pos / meta->raid1_disks;
1570 				pd->pd_meta->raid0_ident = sd->sd_pos % meta->raid1_disks;
1571 				pd->pd_meta->raid1_ident = sd->sd_pos / meta->raid1_disks;
1572 			} else {
1573 				pd->pd_meta->disk_number = sd->sd_pos;
1574 				pd->pd_meta->raid0_ident = 0;
1575 				pd->pd_meta->raid1_ident = 0xff;
1576 			}
1577 		}
1578 		G_RAID_DEBUG(1, "Writing SiI metadata to %s",
1579 		    g_raid_get_diskname(disk));
1580 		g_raid_md_sii_print(pd->pd_meta);
1581 		sii_meta_write(disk->d_consumer, pd->pd_meta);
1582 	}
1583 	return (0);
1584 }
1585 
1586 static int
1587 g_raid_md_fail_disk_sii(struct g_raid_md_object *md,
1588     struct g_raid_subdisk *tsd, struct g_raid_disk *tdisk)
1589 {
1590 	struct g_raid_softc *sc;
1591 	struct g_raid_md_sii_perdisk *pd;
1592 	struct g_raid_subdisk *sd;
1593 
1594 	sc = md->mdo_softc;
1595 	pd = (struct g_raid_md_sii_perdisk *)tdisk->d_md_data;
1596 
1597 	/* We can't fail disk that is not a part of array now. */
1598 	if (pd->pd_disk_pos < 0)
1599 		return (-1);
1600 
1601 	/*
1602 	 * Mark disk as failed in metadata and try to write that metadata
1603 	 * to the disk itself to prevent it's later resurrection as STALE.
1604 	 */
1605 	if (tdisk->d_consumer) {
1606 		if (pd->pd_meta) {
1607 			pd->pd_meta->disk_status = SII_S_REMOVED;
1608 			sii_meta_write(tdisk->d_consumer, pd->pd_meta);
1609 		} else
1610 			sii_meta_erase(tdisk->d_consumer);
1611 	}
1612 
1613 	/* Change states. */
1614 	g_raid_change_disk_state(tdisk, G_RAID_DISK_S_FAILED);
1615 	TAILQ_FOREACH(sd, &tdisk->d_subdisks, sd_next) {
1616 		g_raid_change_subdisk_state(sd,
1617 		    G_RAID_SUBDISK_S_FAILED);
1618 		g_raid_event_send(sd, G_RAID_SUBDISK_E_FAILED,
1619 		    G_RAID_EVENT_SUBDISK);
1620 	}
1621 
1622 	/* Write updated metadata to remaining disks. */
1623 	g_raid_md_write_sii(md, NULL, NULL, tdisk);
1624 
1625 	/* Check if anything left except placeholders. */
1626 	if (g_raid_ndisks(sc, -1) ==
1627 	    g_raid_ndisks(sc, G_RAID_DISK_S_OFFLINE))
1628 		g_raid_destroy_node(sc, 0);
1629 	else
1630 		g_raid_md_sii_refill(sc);
1631 	return (0);
1632 }
1633 
1634 static int
1635 g_raid_md_free_disk_sii(struct g_raid_md_object *md,
1636     struct g_raid_disk *disk)
1637 {
1638 	struct g_raid_md_sii_perdisk *pd;
1639 
1640 	pd = (struct g_raid_md_sii_perdisk *)disk->d_md_data;
1641 	if (pd->pd_meta != NULL) {
1642 		free(pd->pd_meta, M_MD_SII);
1643 		pd->pd_meta = NULL;
1644 	}
1645 	free(pd, M_MD_SII);
1646 	disk->d_md_data = NULL;
1647 	return (0);
1648 }
1649 
1650 static int
1651 g_raid_md_free_sii(struct g_raid_md_object *md)
1652 {
1653 	struct g_raid_md_sii_object *mdi;
1654 
1655 	mdi = (struct g_raid_md_sii_object *)md;
1656 	if (!mdi->mdio_started) {
1657 		mdi->mdio_started = 0;
1658 		callout_stop(&mdi->mdio_start_co);
1659 		G_RAID_DEBUG1(1, md->mdo_softc,
1660 		    "root_mount_rel %p", mdi->mdio_rootmount);
1661 		root_mount_rel(mdi->mdio_rootmount);
1662 		mdi->mdio_rootmount = NULL;
1663 	}
1664 	if (mdi->mdio_meta != NULL) {
1665 		free(mdi->mdio_meta, M_MD_SII);
1666 		mdi->mdio_meta = NULL;
1667 	}
1668 	return (0);
1669 }
1670 
1671 G_RAID_MD_DECLARE(sii, "SiI");
1672