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