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