xref: /freebsd/sys/geom/raid/md_ddf.c (revision 4c9e27bd0a5f7fda85b0c0bf750575aee300a172)
1 /*-
2  * Copyright (c) 2012 Alexander Motin <mav@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
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/time.h>
41 #include <sys/clock.h>
42 #include <geom/geom.h>
43 #include "geom/raid/g_raid.h"
44 #include "geom/raid/md_ddf.h"
45 #include "g_raid_md_if.h"
46 
47 static MALLOC_DEFINE(M_MD_DDF, "md_ddf_data", "GEOM_RAID DDF metadata");
48 
49 #define	DDF_MAX_DISKS_HARD	128
50 
51 #define	DDF_MAX_DISKS	16
52 #define	DDF_MAX_VDISKS	7
53 #define	DDF_MAX_PARTITIONS	1
54 
55 #define DECADE (3600*24*(365*10+2))	/* 10 years in seconds. */
56 
57 struct ddf_meta {
58 	u_int	sectorsize;
59 	u_int	bigendian;
60 	struct ddf_header *hdr;
61 	struct ddf_cd_record *cdr;
62 	struct ddf_pd_record *pdr;
63 	struct ddf_vd_record *vdr;
64 	void *cr;
65 	struct ddf_pdd_record *pdd;
66 	struct ddf_bbm_log *bbm;
67 };
68 
69 struct ddf_vol_meta {
70 	u_int	sectorsize;
71 	u_int	bigendian;
72 	struct ddf_header *hdr;
73 	struct ddf_cd_record *cdr;
74 	struct ddf_vd_entry *vde;
75 	struct ddf_vdc_record *vdc;
76 	struct ddf_vdc_record *bvdc[DDF_MAX_DISKS_HARD];
77 };
78 
79 struct g_raid_md_ddf_perdisk {
80 	struct ddf_meta	 pd_meta;
81 };
82 
83 struct g_raid_md_ddf_pervolume {
84 	struct ddf_vol_meta		 pv_meta;
85 	int				 pv_started;
86 	struct callout			 pv_start_co;	/* STARTING state timer. */
87 };
88 
89 struct g_raid_md_ddf_object {
90 	struct g_raid_md_object	 mdio_base;
91 	u_int			 mdio_bigendian;
92 	struct ddf_meta		 mdio_meta;
93 	int			 mdio_starting;
94 	struct callout		 mdio_start_co;	/* STARTING state timer. */
95 	int			 mdio_started;
96 	struct root_hold_token	*mdio_rootmount; /* Root mount delay token. */
97 };
98 
99 static g_raid_md_create_req_t g_raid_md_create_req_ddf;
100 static g_raid_md_taste_t g_raid_md_taste_ddf;
101 static g_raid_md_event_t g_raid_md_event_ddf;
102 static g_raid_md_volume_event_t g_raid_md_volume_event_ddf;
103 static g_raid_md_ctl_t g_raid_md_ctl_ddf;
104 static g_raid_md_write_t g_raid_md_write_ddf;
105 static g_raid_md_fail_disk_t g_raid_md_fail_disk_ddf;
106 static g_raid_md_free_disk_t g_raid_md_free_disk_ddf;
107 static g_raid_md_free_volume_t g_raid_md_free_volume_ddf;
108 static g_raid_md_free_t g_raid_md_free_ddf;
109 
110 static kobj_method_t g_raid_md_ddf_methods[] = {
111 	KOBJMETHOD(g_raid_md_create_req,	g_raid_md_create_req_ddf),
112 	KOBJMETHOD(g_raid_md_taste,	g_raid_md_taste_ddf),
113 	KOBJMETHOD(g_raid_md_event,	g_raid_md_event_ddf),
114 	KOBJMETHOD(g_raid_md_volume_event,	g_raid_md_volume_event_ddf),
115 	KOBJMETHOD(g_raid_md_ctl,	g_raid_md_ctl_ddf),
116 	KOBJMETHOD(g_raid_md_write,	g_raid_md_write_ddf),
117 	KOBJMETHOD(g_raid_md_fail_disk,	g_raid_md_fail_disk_ddf),
118 	KOBJMETHOD(g_raid_md_free_disk,	g_raid_md_free_disk_ddf),
119 	KOBJMETHOD(g_raid_md_free_volume,	g_raid_md_free_volume_ddf),
120 	KOBJMETHOD(g_raid_md_free,	g_raid_md_free_ddf),
121 	{ 0, 0 }
122 };
123 
124 static struct g_raid_md_class g_raid_md_ddf_class = {
125 	"DDF",
126 	g_raid_md_ddf_methods,
127 	sizeof(struct g_raid_md_ddf_object),
128 	.mdc_enable = 1,
129 	.mdc_priority = 100
130 };
131 
132 #define GET8(m, f)	((m)->f)
133 #define GET16(m, f)	((m)->bigendian ? be16dec(&(m)->f) : le16dec(&(m)->f))
134 #define GET32(m, f)	((m)->bigendian ? be32dec(&(m)->f) : le32dec(&(m)->f))
135 #define GET64(m, f)	((m)->bigendian ? be64dec(&(m)->f) : le64dec(&(m)->f))
136 #define GET8D(m, f)	(f)
137 #define GET16D(m, f)	((m)->bigendian ? be16dec(&f) : le16dec(&f))
138 #define GET32D(m, f)	((m)->bigendian ? be32dec(&f) : le32dec(&f))
139 #define GET64D(m, f)	((m)->bigendian ? be64dec(&f) : le64dec(&f))
140 #define GET8P(m, f)	(*(f))
141 #define GET16P(m, f)	((m)->bigendian ? be16dec(f) : le16dec(f))
142 #define GET32P(m, f)	((m)->bigendian ? be32dec(f) : le32dec(f))
143 #define GET64P(m, f)	((m)->bigendian ? be64dec(f) : le64dec(f))
144 
145 #define SET8P(m, f, v)							\
146 	(*(f) = (v))
147 #define SET16P(m, f, v)							\
148 	do {								\
149 		if ((m)->bigendian)					\
150 			be16enc((f), (v));				\
151 		else							\
152 			le16enc((f), (v));				\
153 	} while (0)
154 #define SET32P(m, f, v)							\
155 	do {								\
156 		if ((m)->bigendian)					\
157 			be32enc((f), (v));				\
158 		else							\
159 			le32enc((f), (v));				\
160 	} while (0)
161 #define SET64P(m, f, v)							\
162 	do {								\
163 		if ((m)->bigendian)					\
164 			be64enc((f), (v));				\
165 		else							\
166 			le64enc((f), (v));				\
167 	} while (0)
168 #define SET8(m, f, v)	SET8P((m), &((m)->f), (v))
169 #define SET16(m, f, v)	SET16P((m), &((m)->f), (v))
170 #define SET32(m, f, v)	SET32P((m), &((m)->f), (v))
171 #define SET64(m, f, v)	SET64P((m), &((m)->f), (v))
172 #define SET8D(m, f, v)	SET8P((m), &(f), (v))
173 #define SET16D(m, f, v)	SET16P((m), &(f), (v))
174 #define SET32D(m, f, v)	SET32P((m), &(f), (v))
175 #define SET64D(m, f, v)	SET64P((m), &(f), (v))
176 
177 #define GETCRNUM(m)	(GET32((m), hdr->cr_length) /			\
178 	GET16((m), hdr->Configuration_Record_Length))
179 
180 #define GETVDCPTR(m, n)	((struct ddf_vdc_record *)((uint8_t *)(m)->cr +	\
181 	(n) * GET16((m), hdr->Configuration_Record_Length) *		\
182 	(m)->sectorsize))
183 
184 #define GETSAPTR(m, n)	((struct ddf_sa_record *)((uint8_t *)(m)->cr +	\
185 	(n) * GET16((m), hdr->Configuration_Record_Length) *		\
186 	(m)->sectorsize))
187 
188 static int
189 isff(uint8_t *buf, int size)
190 {
191 	int i;
192 
193 	for (i = 0; i < size; i++)
194 		if (buf[i] != 0xff)
195 			return (0);
196 	return (1);
197 }
198 
199 static void
200 print_guid(uint8_t *buf)
201 {
202 	int i, ascii;
203 
204 	ascii = 1;
205 	for (i = 0; i < 24; i++) {
206 		if (buf[i] != 0 && (buf[i] < ' ' || buf[i] > 127)) {
207 			ascii = 0;
208 			break;
209 		}
210 	}
211 	if (ascii) {
212 		printf("'%.24s'", buf);
213 	} else {
214 		for (i = 0; i < 24; i++)
215 			printf("%02x", buf[i]);
216 	}
217 }
218 
219 static void
220 g_raid_md_ddf_print(struct ddf_meta *meta)
221 {
222 	struct ddf_vdc_record *vdc;
223 	struct ddf_vuc_record *vuc;
224 	struct ddf_sa_record *sa;
225 	uint64_t *val2;
226 	uint32_t val;
227 	int i, j, k, num, num2;
228 
229 	if (g_raid_debug < 1)
230 		return;
231 
232 	printf("********* DDF Metadata *********\n");
233 	printf("**** Header ****\n");
234 	printf("DDF_Header_GUID      ");
235 	print_guid(meta->hdr->DDF_Header_GUID);
236 	printf("\n");
237 	printf("DDF_rev              %8.8s\n", (char *)&meta->hdr->DDF_rev[0]);
238 	printf("Sequence_Number      0x%08x\n", GET32(meta, hdr->Sequence_Number));
239 	printf("TimeStamp            0x%08x\n", GET32(meta, hdr->TimeStamp));
240 	printf("Open_Flag            0x%02x\n", GET16(meta, hdr->Open_Flag));
241 	printf("Foreign_Flag         0x%02x\n", GET16(meta, hdr->Foreign_Flag));
242 	printf("Diskgrouping         0x%02x\n", GET16(meta, hdr->Diskgrouping));
243 	printf("Primary_Header_LBA   %ju\n", GET64(meta, hdr->Primary_Header_LBA));
244 	printf("Secondary_Header_LBA %ju\n", GET64(meta, hdr->Secondary_Header_LBA));
245 	printf("WorkSpace_Length     %u\n", GET32(meta, hdr->WorkSpace_Length));
246 	printf("WorkSpace_LBA        %ju\n", GET64(meta, hdr->WorkSpace_LBA));
247 	printf("Max_PD_Entries       %u\n", GET16(meta, hdr->Max_PD_Entries));
248 	printf("Max_VD_Entries       %u\n", GET16(meta, hdr->Max_VD_Entries));
249 	printf("Max_Partitions       %u\n", GET16(meta, hdr->Max_Partitions));
250 	printf("Configuration_Record_Length %u\n", GET16(meta, hdr->Configuration_Record_Length));
251 	printf("Max_Primary_Element_Entries %u\n", GET16(meta, hdr->Max_Primary_Element_Entries));
252 	printf("Controller Data      %u:%u\n", GET32(meta, hdr->cd_section), GET32(meta, hdr->cd_length));
253 	printf("Physical Disk        %u:%u\n", GET32(meta, hdr->pdr_section), GET32(meta, hdr->pdr_length));
254 	printf("Virtual Disk         %u:%u\n", GET32(meta, hdr->vdr_section), GET32(meta, hdr->vdr_length));
255 	printf("Configuration Recs   %u:%u\n", GET32(meta, hdr->cr_section), GET32(meta, hdr->cr_length));
256 	printf("Physical Disk Recs   %u:%u\n", GET32(meta, hdr->pdd_section), GET32(meta, hdr->pdd_length));
257 	printf("BBM Log              %u:%u\n", GET32(meta, hdr->bbmlog_section), GET32(meta, hdr->bbmlog_length));
258 	printf("Diagnostic Space     %u:%u\n", GET32(meta, hdr->Diagnostic_Space), GET32(meta, hdr->Diagnostic_Space_Length));
259 	printf("Vendor_Specific_Logs %u:%u\n", GET32(meta, hdr->Vendor_Specific_Logs), GET32(meta, hdr->Vendor_Specific_Logs_Length));
260 	printf("**** Controler Data ****\n");
261 	printf("Controller_GUID      ");
262 	print_guid(meta->cdr->Controller_GUID);
263 	printf("\n");
264 	printf("Controller_Type      0x%04x%04x 0x%04x%04x\n",
265 	    GET16(meta, cdr->Controller_Type.Vendor_ID),
266 	    GET16(meta, cdr->Controller_Type.Device_ID),
267 	    GET16(meta, cdr->Controller_Type.SubVendor_ID),
268 	    GET16(meta, cdr->Controller_Type.SubDevice_ID));
269 	printf("Product_ID           '%.16s'\n", (char *)&meta->cdr->Product_ID[0]);
270 	printf("**** Physical Disk Records ****\n");
271 	printf("Populated_PDEs       %u\n", GET16(meta, pdr->Populated_PDEs));
272 	printf("Max_PDE_Supported    %u\n", GET16(meta, pdr->Max_PDE_Supported));
273 	for (j = 0; j < GET16(meta, pdr->Populated_PDEs); j++) {
274 		if (isff(meta->pdr->entry[j].PD_GUID, 24))
275 			continue;
276 		if (GET32(meta, pdr->entry[j].PD_Reference) == 0xffffffff)
277 			continue;
278 		printf("PD_GUID              ");
279 		print_guid(meta->pdr->entry[j].PD_GUID);
280 		printf("\n");
281 		printf("PD_Reference         0x%08x\n",
282 		    GET32(meta, pdr->entry[j].PD_Reference));
283 		printf("PD_Type              0x%04x\n",
284 		    GET16(meta, pdr->entry[j].PD_Type));
285 		printf("PD_State             0x%04x\n",
286 		    GET16(meta, pdr->entry[j].PD_State));
287 		printf("Configured_Size      %ju\n",
288 		    GET64(meta, pdr->entry[j].Configured_Size));
289 		printf("Block_Size           %u\n",
290 		    GET16(meta, pdr->entry[j].Block_Size));
291 	}
292 	printf("**** Virtual Disk Records ****\n");
293 	printf("Populated_VDEs       %u\n", GET16(meta, vdr->Populated_VDEs));
294 	printf("Max_VDE_Supported    %u\n", GET16(meta, vdr->Max_VDE_Supported));
295 	for (j = 0; j < GET16(meta, vdr->Populated_VDEs); j++) {
296 		if (isff(meta->vdr->entry[j].VD_GUID, 24))
297 			continue;
298 		printf("VD_GUID              ");
299 		print_guid(meta->vdr->entry[j].VD_GUID);
300 		printf("\n");
301 		printf("VD_Number            0x%04x\n",
302 		    GET16(meta, vdr->entry[j].VD_Number));
303 		printf("VD_Type              0x%04x\n",
304 		    GET16(meta, vdr->entry[j].VD_Type));
305 		printf("VD_State             0x%02x\n",
306 		    GET8(meta, vdr->entry[j].VD_State));
307 		printf("Init_State           0x%02x\n",
308 		    GET8(meta, vdr->entry[j].Init_State));
309 		printf("Drive_Failures_Remaining %u\n",
310 		    GET8(meta, vdr->entry[j].Drive_Failures_Remaining));
311 		printf("VD_Name              '%.16s'\n",
312 		    (char *)&meta->vdr->entry[j].VD_Name);
313 	}
314 	printf("**** Configuration Records ****\n");
315 	num = GETCRNUM(meta);
316 	for (j = 0; j < num; j++) {
317 		vdc = GETVDCPTR(meta, j);
318 		val = GET32D(meta, vdc->Signature);
319 		switch (val) {
320 		case DDF_VDCR_SIGNATURE:
321 			printf("** Virtual Disk Configuration **\n");
322 			printf("VD_GUID              ");
323 			print_guid(vdc->VD_GUID);
324 			printf("\n");
325 			printf("Timestamp            0x%08x\n",
326 			    GET32D(meta, vdc->Timestamp));
327 			printf("Sequence_Number      0x%08x\n",
328 			    GET32D(meta, vdc->Sequence_Number));
329 			printf("Primary_Element_Count %u\n",
330 			    GET16D(meta, vdc->Primary_Element_Count));
331 			printf("Stripe_Size          %u\n",
332 			    GET8D(meta, vdc->Stripe_Size));
333 			printf("Primary_RAID_Level   0x%02x\n",
334 			    GET8D(meta, vdc->Primary_RAID_Level));
335 			printf("RLQ                  0x%02x\n",
336 			    GET8D(meta, vdc->RLQ));
337 			printf("Secondary_Element_Count %u\n",
338 			    GET8D(meta, vdc->Secondary_Element_Count));
339 			printf("Secondary_Element_Seq %u\n",
340 			    GET8D(meta, vdc->Secondary_Element_Seq));
341 			printf("Secondary_RAID_Level 0x%02x\n",
342 			    GET8D(meta, vdc->Secondary_RAID_Level));
343 			printf("Block_Count          %ju\n",
344 			    GET64D(meta, vdc->Block_Count));
345 			printf("VD_Size              %ju\n",
346 			    GET64D(meta, vdc->VD_Size));
347 			printf("Block_Size           %u\n",
348 			    GET16D(meta, vdc->Block_Size));
349 			printf("Rotate_Parity_count  %u\n",
350 			    GET8D(meta, vdc->Rotate_Parity_count));
351 			printf("Associated_Spare_Disks");
352 			for (i = 0; i < 8; i++) {
353 				if (GET32D(meta, vdc->Associated_Spares[i]) != 0xffffffff)
354 					printf(" 0x%08x", GET32D(meta, vdc->Associated_Spares[i]));
355 			}
356 			printf("\n");
357 			printf("Cache_Flags          %016jx\n",
358 			    GET64D(meta, vdc->Cache_Flags));
359 			printf("BG_Rate              %u\n",
360 			    GET8D(meta, vdc->BG_Rate));
361 			printf("MDF_Parity_Disks     %u\n",
362 			    GET8D(meta, vdc->MDF_Parity_Disks));
363 			printf("MDF_Parity_Generator_Polynomial 0x%04x\n",
364 			    GET16D(meta, vdc->MDF_Parity_Generator_Polynomial));
365 			printf("MDF_Constant_Generation_Method 0x%02x\n",
366 			    GET8D(meta, vdc->MDF_Constant_Generation_Method));
367 			printf("Physical_Disks      ");
368 			num2 = GET16D(meta, vdc->Primary_Element_Count);
369 			val2 = (uint64_t *)&(vdc->Physical_Disk_Sequence[GET16(meta, hdr->Max_Primary_Element_Entries)]);
370 			for (i = 0; i < num2; i++)
371 				printf(" 0x%08x @ %ju",
372 				    GET32D(meta, vdc->Physical_Disk_Sequence[i]),
373 				    GET64P(meta, val2 + i));
374 			printf("\n");
375 			break;
376 		case DDF_VUCR_SIGNATURE:
377 			printf("** Vendor Unique Configuration **\n");
378 			vuc = (struct ddf_vuc_record *)vdc;
379 			printf("VD_GUID              ");
380 			print_guid(vuc->VD_GUID);
381 			printf("\n");
382 			break;
383 		case DDF_SA_SIGNATURE:
384 			printf("** Spare Assignment Configuration **\n");
385 			sa = (struct ddf_sa_record *)vdc;
386 			printf("Timestamp            0x%08x\n",
387 			    GET32D(meta, sa->Timestamp));
388 			printf("Spare_Type           0x%02x\n",
389 			    GET8D(meta, sa->Spare_Type));
390 			printf("Populated_SAEs       %u\n",
391 			    GET16D(meta, sa->Populated_SAEs));
392 			printf("MAX_SAE_Supported    %u\n",
393 			    GET16D(meta, sa->MAX_SAE_Supported));
394 			for (i = 0; i < GET16D(meta, sa->Populated_SAEs); i++) {
395 				if (isff(sa->entry[i].VD_GUID, 24))
396 					continue;
397 				printf("VD_GUID             ");
398 				for (k = 0; k < 24; k++)
399 					printf("%02x", sa->entry[i].VD_GUID[k]);
400 				printf("\n");
401 				printf("Secondary_Element   %u\n",
402 				    GET16D(meta, sa->entry[i].Secondary_Element));
403 			}
404 			break;
405 		case 0x00000000:
406 		case 0xFFFFFFFF:
407 			break;
408 		default:
409 			printf("Unknown configuration signature %08x\n", val);
410 			break;
411 		}
412 	}
413 	printf("**** Physical Disk Data ****\n");
414 	printf("PD_GUID              ");
415 	print_guid(meta->pdd->PD_GUID);
416 	printf("\n");
417 	printf("PD_Reference         0x%08x\n",
418 	    GET32(meta, pdd->PD_Reference));
419 	printf("Forced_Ref_Flag      0x%02x\n",
420 	    GET8(meta, pdd->Forced_Ref_Flag));
421 	printf("Forced_PD_GUID_Flag  0x%02x\n",
422 	    GET8(meta, pdd->Forced_PD_GUID_Flag));
423 }
424 
425 static int
426 ddf_meta_find_pd(struct ddf_meta *meta, uint8_t *GUID, uint32_t PD_Reference)
427 {
428 	int i;
429 
430 	for (i = 0; i < GET16(meta, pdr->Populated_PDEs); i++) {
431 		if (GUID != NULL) {
432 			if (memcmp(meta->pdr->entry[i].PD_GUID, GUID, 24) == 0)
433 				return (i);
434 		} else if (PD_Reference != 0xffffffff) {
435 			if (GET32(meta, pdr->entry[i].PD_Reference) == PD_Reference)
436 				return (i);
437 		} else
438 			if (isff(meta->pdr->entry[i].PD_GUID, 24))
439 				return (i);
440 	}
441 	if (GUID == NULL && PD_Reference == 0xffffffff) {
442 		if (i >= GET16(meta, pdr->Max_PDE_Supported))
443 			return (-1);
444 		SET16(meta, pdr->Populated_PDEs, i + 1);
445 		return (i);
446 	}
447 	return (-1);
448 }
449 
450 static int
451 ddf_meta_find_vd(struct ddf_meta *meta, uint8_t *GUID)
452 {
453 	int i;
454 
455 	for (i = 0; i < GET16(meta, vdr->Populated_VDEs); i++) {
456 		if (GUID != NULL) {
457 			if (memcmp(meta->vdr->entry[i].VD_GUID, GUID, 24) == 0)
458 				return (i);
459 		} else
460 			if (isff(meta->vdr->entry[i].VD_GUID, 24))
461 				return (i);
462 	}
463 	if (GUID == NULL) {
464 		if (i >= GET16(meta, vdr->Max_VDE_Supported))
465 			return (-1);
466 		SET16(meta, vdr->Populated_VDEs, i + 1);
467 		return (i);
468 	}
469 	return (-1);
470 }
471 
472 static struct ddf_vdc_record *
473 ddf_meta_find_vdc(struct ddf_meta *meta, uint8_t *GUID)
474 {
475 	struct ddf_vdc_record *vdc;
476 	int i, num;
477 
478 	num = GETCRNUM(meta);
479 	for (i = 0; i < num; i++) {
480 		vdc = GETVDCPTR(meta, i);
481 		if (GUID != NULL) {
482 			if (GET32D(meta, vdc->Signature) == DDF_VDCR_SIGNATURE &&
483 			    memcmp(vdc->VD_GUID, GUID, 24) == 0)
484 				return (vdc);
485 		} else
486 			if (GET32D(meta, vdc->Signature) == 0xffffffff ||
487 			    GET32D(meta, vdc->Signature) == 0)
488 				return (vdc);
489 	}
490 	return (NULL);
491 }
492 
493 static int
494 ddf_meta_count_vdc(struct ddf_meta *meta, uint8_t *GUID)
495 {
496 	struct ddf_vdc_record *vdc;
497 	int i, num, cnt;
498 
499 	cnt = 0;
500 	num = GETCRNUM(meta);
501 	for (i = 0; i < num; i++) {
502 		vdc = GETVDCPTR(meta, i);
503 		if (GET32D(meta, vdc->Signature) != DDF_VDCR_SIGNATURE)
504 			continue;
505 		if (GUID == NULL || memcmp(vdc->VD_GUID, GUID, 24) == 0)
506 			cnt++;
507 	}
508 	return (cnt);
509 }
510 
511 static int
512 ddf_meta_find_disk(struct ddf_vol_meta *vmeta, uint32_t PD_Reference,
513     int *bvdp, int *posp)
514 {
515 	int i, bvd, pos;
516 
517 	i = 0;
518 	for (bvd = 0; bvd < GET8(vmeta, vdc->Secondary_Element_Count); bvd++) {
519 		if (vmeta->bvdc[bvd] == NULL) {
520 			i += GET16(vmeta, vdc->Primary_Element_Count); // XXX
521 			continue;
522 		}
523 		for (pos = 0; pos < GET16(vmeta, bvdc[bvd]->Primary_Element_Count);
524 		    pos++, i++) {
525 			if (GET32(vmeta, bvdc[bvd]->Physical_Disk_Sequence[pos]) ==
526 			    PD_Reference) {
527 				if (bvdp != NULL)
528 					*bvdp = bvd;
529 				if (posp != NULL)
530 					*posp = pos;
531 				return (i);
532 			}
533 		}
534 	}
535 	return (-1);
536 }
537 
538 static struct ddf_sa_record *
539 ddf_meta_find_sa(struct ddf_meta *meta, int create)
540 {
541 	struct ddf_sa_record *sa;
542 	int i, num;
543 
544 	num = GETCRNUM(meta);
545 	for (i = 0; i < num; i++) {
546 		sa = GETSAPTR(meta, i);
547 		if (GET32D(meta, sa->Signature) == DDF_SA_SIGNATURE)
548 			return (sa);
549 	}
550 	if (create) {
551 		for (i = 0; i < num; i++) {
552 			sa = GETSAPTR(meta, i);
553 			if (GET32D(meta, sa->Signature) == 0xffffffff ||
554 			    GET32D(meta, sa->Signature) == 0)
555 				return (sa);
556 		}
557 	}
558 	return (NULL);
559 }
560 
561 static void
562 ddf_meta_create(struct g_raid_disk *disk, struct ddf_meta *sample)
563 {
564 	struct timespec ts;
565 	struct clocktime ct;
566 	struct g_raid_md_ddf_perdisk *pd;
567 	struct g_raid_md_ddf_object *mdi;
568 	struct ddf_meta *meta;
569 	struct ddf_pd_entry *pde;
570 	off_t anchorlba;
571 	u_int ss, pos, size;
572 	int len, error;
573 	char serial_buffer[24];
574 
575 	if (sample->hdr == NULL)
576 		sample = NULL;
577 
578 	mdi = (struct g_raid_md_ddf_object *)disk->d_softc->sc_md;
579 	pd = (struct g_raid_md_ddf_perdisk *)disk->d_md_data;
580 	meta = &pd->pd_meta;
581 	ss = disk->d_consumer->provider->sectorsize;
582 	anchorlba = disk->d_consumer->provider->mediasize / ss - 1;
583 
584 	meta->sectorsize = ss;
585 	meta->bigendian = sample ? sample->bigendian : mdi->mdio_bigendian;
586 	getnanotime(&ts);
587 	clock_ts_to_ct(&ts, &ct);
588 
589 	/* Header */
590 	meta->hdr = malloc(ss, M_MD_DDF, M_WAITOK);
591 	memset(meta->hdr, 0xff, ss);
592 	if (sample) {
593 		memcpy(meta->hdr, sample->hdr, sizeof(struct ddf_header));
594 		if (ss != sample->sectorsize) {
595 			SET32(meta, hdr->WorkSpace_Length,
596 			    (GET32(sample, hdr->WorkSpace_Length) *
597 			    sample->sectorsize + ss - 1) / ss);
598 			SET16(meta, hdr->Configuration_Record_Length,
599 			    (GET16(sample, hdr->Configuration_Record_Length) *
600 			    sample->sectorsize + ss - 1) / ss);
601 			SET32(meta, hdr->cd_length,
602 			    (GET32(sample, hdr->cd_length) *
603 			    sample->sectorsize + ss - 1) / ss);
604 			SET32(meta, hdr->pdr_length,
605 			    (GET32(sample, hdr->pdr_length) *
606 			    sample->sectorsize + ss - 1) / ss);
607 			SET32(meta, hdr->vdr_length,
608 			    (GET32(sample, hdr->vdr_length) *
609 			    sample->sectorsize + ss - 1) / ss);
610 			SET32(meta, hdr->cr_length,
611 			    (GET32(sample, hdr->cr_length) *
612 			    sample->sectorsize + ss - 1) / ss);
613 			SET32(meta, hdr->pdd_length,
614 			    (GET32(sample, hdr->pdd_length) *
615 			    sample->sectorsize + ss - 1) / ss);
616 			SET32(meta, hdr->bbmlog_length,
617 			    (GET32(sample, hdr->bbmlog_length) *
618 			    sample->sectorsize + ss - 1) / ss);
619 			SET32(meta, hdr->Diagnostic_Space,
620 			    (GET32(sample, hdr->bbmlog_length) *
621 			    sample->sectorsize + ss - 1) / ss);
622 			SET32(meta, hdr->Vendor_Specific_Logs,
623 			    (GET32(sample, hdr->bbmlog_length) *
624 			    sample->sectorsize + ss - 1) / ss);
625 		}
626 	} else {
627 		SET32(meta, hdr->Signature, DDF_HEADER_SIGNATURE);
628 		snprintf(meta->hdr->DDF_Header_GUID, 25, "FreeBSD %08x%08x",
629 		    (u_int)(ts.tv_sec - DECADE), arc4random());
630 		memcpy(meta->hdr->DDF_rev, "02.00.00", 8);
631 		SET32(meta, hdr->TimeStamp, (ts.tv_sec - DECADE));
632 		SET32(meta, hdr->WorkSpace_Length, 16 * 1024 * 1024 / ss);
633 		SET16(meta, hdr->Max_PD_Entries, DDF_MAX_DISKS - 1);
634 		SET16(meta, hdr->Max_VD_Entries, DDF_MAX_VDISKS);
635 		SET16(meta, hdr->Max_Partitions, DDF_MAX_PARTITIONS);
636 		SET16(meta, hdr->Max_Primary_Element_Entries, DDF_MAX_DISKS);
637 		SET16(meta, hdr->Configuration_Record_Length,
638 		    (sizeof(struct ddf_vdc_record) +
639 		     (4 + 8) * GET16(meta, hdr->Max_Primary_Element_Entries) +
640 		     ss - 1) / ss);
641 		SET32(meta, hdr->cd_length,
642 		    (sizeof(struct ddf_cd_record) + ss - 1) / ss);
643 		SET32(meta, hdr->pdr_length,
644 		    (sizeof(struct ddf_pd_record) +
645 		     sizeof(struct ddf_pd_entry) *
646 		     GET16(meta, hdr->Max_PD_Entries) + ss - 1) / ss);
647 		SET32(meta, hdr->vdr_length,
648 		    (sizeof(struct ddf_vd_record) +
649 		     sizeof(struct ddf_vd_entry) *
650 		     GET16(meta, hdr->Max_VD_Entries) + ss - 1) / ss);
651 		SET32(meta, hdr->cr_length,
652 		    GET16(meta, hdr->Configuration_Record_Length) *
653 		    (GET16(meta, hdr->Max_Partitions) + 1));
654 		SET32(meta, hdr->pdd_length,
655 		    (sizeof(struct ddf_pdd_record) + ss - 1) / ss);
656 		SET32(meta, hdr->bbmlog_length, 0);
657 		SET32(meta, hdr->Diagnostic_Space_Length, 0);
658 		SET32(meta, hdr->Vendor_Specific_Logs_Length, 0);
659 	}
660 	pos = 1;
661 	SET32(meta, hdr->cd_section, pos);
662 	pos += GET32(meta, hdr->cd_length);
663 	SET32(meta, hdr->pdr_section, pos);
664 	pos += GET32(meta, hdr->pdr_length);
665 	SET32(meta, hdr->vdr_section, pos);
666 	pos += GET32(meta, hdr->vdr_length);
667 	SET32(meta, hdr->cr_section, pos);
668 	pos += GET32(meta, hdr->cr_length);
669 	SET32(meta, hdr->pdd_section, pos);
670 	pos += GET32(meta, hdr->pdd_length);
671 	SET32(meta, hdr->bbmlog_section,
672 	    GET32(meta, hdr->bbmlog_length) != 0 ? pos : 0xffffffff);
673 	pos += GET32(meta, hdr->bbmlog_length);
674 	SET32(meta, hdr->Diagnostic_Space,
675 	    GET32(meta, hdr->Diagnostic_Space_Length) != 0 ? pos : 0xffffffff);
676 	pos += GET32(meta, hdr->Diagnostic_Space_Length);
677 	SET32(meta, hdr->Vendor_Specific_Logs,
678 	    GET32(meta, hdr->Vendor_Specific_Logs_Length) != 0 ? pos : 0xffffffff);
679 	pos += min(GET32(meta, hdr->Vendor_Specific_Logs_Length), 1);
680 	SET64(meta, hdr->Primary_Header_LBA,
681 	    anchorlba - pos);
682 	SET64(meta, hdr->Secondary_Header_LBA,
683 	    0xffffffffffffffffULL);
684 	SET64(meta, hdr->WorkSpace_LBA,
685 	    anchorlba + 1 - 32 * 1024 * 1024 / ss);
686 
687 	/* Controller Data */
688 	size = GET32(meta, hdr->cd_length) * ss;
689 	meta->cdr = malloc(size, M_MD_DDF, M_WAITOK);
690 	memset(meta->cdr, 0xff, size);
691 	SET32(meta, cdr->Signature, DDF_CONTROLLER_DATA_SIGNATURE);
692 	memcpy(meta->cdr->Controller_GUID, "FreeBSD GEOM RAID SERIAL", 24);
693 	memcpy(meta->cdr->Product_ID, "FreeBSD GEOMRAID", 16);
694 
695 	/* Physical Drive Records. */
696 	size = GET32(meta, hdr->pdr_length) * ss;
697 	meta->pdr = malloc(size, M_MD_DDF, M_WAITOK);
698 	memset(meta->pdr, 0xff, size);
699 	SET32(meta, pdr->Signature, DDF_PDR_SIGNATURE);
700 	SET16(meta, pdr->Populated_PDEs, 1);
701 	SET16(meta, pdr->Max_PDE_Supported,
702 	    GET16(meta, hdr->Max_PD_Entries));
703 
704 	pde = &meta->pdr->entry[0];
705 	len = sizeof(serial_buffer);
706 	error = g_io_getattr("GEOM::ident", disk->d_consumer, &len, serial_buffer);
707 	if (error == 0 && (len = strlen (serial_buffer)) >= 6 && len <= 20)
708 		snprintf(pde->PD_GUID, 25, "DISK%20s", serial_buffer);
709 	else
710 		snprintf(pde->PD_GUID, 25, "DISK%04d%02d%02d%08x%04x",
711 		    ct.year, ct.mon, ct.day,
712 		    arc4random(), arc4random() & 0xffff);
713 	SET32D(meta, pde->PD_Reference, arc4random());
714 	SET16D(meta, pde->PD_Type, DDF_PDE_GUID_FORCE);
715 	SET16D(meta, pde->PD_State, 0);
716 	SET64D(meta, pde->Configured_Size,
717 	    anchorlba + 1 - 32 * 1024 * 1024 / ss);
718 	SET16D(meta, pde->Block_Size, ss);
719 
720 	/* Virtual Drive Records. */
721 	size = GET32(meta, hdr->vdr_length) * ss;
722 	meta->vdr = malloc(size, M_MD_DDF, M_WAITOK);
723 	memset(meta->vdr, 0xff, size);
724 	SET32(meta, vdr->Signature, DDF_VD_RECORD_SIGNATURE);
725 	SET32(meta, vdr->Populated_VDEs, 0);
726 	SET16(meta, vdr->Max_VDE_Supported,
727 	    GET16(meta, hdr->Max_VD_Entries));
728 
729 	/* Configuration Records. */
730 	size = GET32(meta, hdr->cr_length) * ss;
731 	meta->cr = malloc(size, M_MD_DDF, M_WAITOK);
732 	memset(meta->cr, 0xff, size);
733 
734 	/* Physical Disk Data. */
735 	size = GET32(meta, hdr->pdd_length) * ss;
736 	meta->pdd = malloc(size, M_MD_DDF, M_WAITOK);
737 	memset(meta->pdd, 0xff, size);
738 	SET32(meta, pdd->Signature, DDF_PDD_SIGNATURE);
739 	memcpy(meta->pdd->PD_GUID, pde->PD_GUID, 24);
740 	SET32(meta, pdd->PD_Reference, GET32D(meta, pde->PD_Reference));
741 	SET8(meta, pdd->Forced_Ref_Flag, DDF_PDD_FORCED_REF);
742 	SET8(meta, pdd->Forced_PD_GUID_Flag, DDF_PDD_FORCED_GUID);
743 
744 	/* Bad Block Management Log. */
745 	if (GET32(meta, hdr->bbmlog_length) != 0) {
746 		size = GET32(meta, hdr->bbmlog_length) * ss;
747 		meta->bbm = malloc(size, M_MD_DDF, M_WAITOK);
748 		memset(meta->bbm, 0xff, size);
749 		SET32(meta, bbm->Signature, DDF_BBML_SIGNATURE);
750 		SET32(meta, bbm->Entry_Count, 0);
751 		SET32(meta, bbm->Spare_Block_Count, 0);
752 	}
753 }
754 
755 static void
756 ddf_meta_copy(struct ddf_meta *dst, struct ddf_meta *src)
757 {
758 	struct ddf_header *hdr;
759 	u_int ss;
760 
761 	hdr = src->hdr;
762 	dst->bigendian = src->bigendian;
763 	ss = dst->sectorsize = src->sectorsize;
764 	dst->hdr = malloc(ss, M_MD_DDF, M_WAITOK);
765 	memcpy(dst->hdr, src->hdr, ss);
766 	dst->cdr = malloc(GET32(src, hdr->cd_length) * ss, M_MD_DDF, M_WAITOK);
767 	memcpy(dst->cdr, src->cdr, GET32(src, hdr->cd_length) * ss);
768 	dst->pdr = malloc(GET32(src, hdr->pdr_length) * ss, M_MD_DDF, M_WAITOK);
769 	memcpy(dst->pdr, src->pdr, GET32(src, hdr->pdr_length) * ss);
770 	dst->vdr = malloc(GET32(src, hdr->vdr_length) * ss, M_MD_DDF, M_WAITOK);
771 	memcpy(dst->vdr, src->vdr, GET32(src, hdr->vdr_length) * ss);
772 	dst->cr = malloc(GET32(src, hdr->cr_length) * ss, M_MD_DDF, M_WAITOK);
773 	memcpy(dst->cr, src->cr, GET32(src, hdr->cr_length) * ss);
774 	dst->pdd = malloc(GET32(src, hdr->pdd_length) * ss, M_MD_DDF, M_WAITOK);
775 	memcpy(dst->pdd, src->pdd, GET32(src, hdr->pdd_length) * ss);
776 	if (src->bbm != NULL) {
777 		dst->bbm = malloc(GET32(src, hdr->bbmlog_length) * ss, M_MD_DDF, M_WAITOK);
778 		memcpy(dst->bbm, src->bbm, GET32(src, hdr->bbmlog_length) * ss);
779 	}
780 }
781 
782 static void
783 ddf_meta_update(struct ddf_meta *meta, struct ddf_meta *src)
784 {
785 	struct ddf_pd_entry *pde, *spde;
786 	int i, j;
787 
788 	for (i = 0; i < GET16(src, pdr->Populated_PDEs); i++) {
789 		spde = &src->pdr->entry[i];
790 		if (isff(spde->PD_GUID, 24))
791 			continue;
792 		j = ddf_meta_find_pd(meta, NULL,
793 		    GET32(src, pdr->entry[i].PD_Reference));
794 		if (j < 0) {
795 			j = ddf_meta_find_pd(meta, NULL, 0xffffffff);
796 			pde = &meta->pdr->entry[j];
797 			memcpy(pde, spde, sizeof(*pde));
798 		} else {
799 			pde = &meta->pdr->entry[j];
800 			SET16D(meta, pde->PD_State,
801 			    GET16D(meta, pde->PD_State) |
802 			    GET16D(src, pde->PD_State));
803 		}
804 	}
805 }
806 
807 static void
808 ddf_meta_free(struct ddf_meta *meta)
809 {
810 
811 	if (meta->hdr != NULL) {
812 		free(meta->hdr, M_MD_DDF);
813 		meta->hdr = NULL;
814 	}
815 	if (meta->cdr != NULL) {
816 		free(meta->cdr, M_MD_DDF);
817 		meta->cdr = NULL;
818 	}
819 	if (meta->pdr != NULL) {
820 		free(meta->pdr, M_MD_DDF);
821 		meta->pdr = NULL;
822 	}
823 	if (meta->vdr != NULL) {
824 		free(meta->vdr, M_MD_DDF);
825 		meta->vdr = NULL;
826 	}
827 	if (meta->cr != NULL) {
828 		free(meta->cr, M_MD_DDF);
829 		meta->cr = NULL;
830 	}
831 	if (meta->pdd != NULL) {
832 		free(meta->pdd, M_MD_DDF);
833 		meta->pdd = NULL;
834 	}
835 	if (meta->bbm != NULL) {
836 		free(meta->bbm, M_MD_DDF);
837 		meta->bbm = NULL;
838 	}
839 }
840 
841 static void
842 ddf_vol_meta_create(struct ddf_vol_meta *meta, struct ddf_meta *sample)
843 {
844 	struct timespec ts;
845 	struct clocktime ct;
846 	struct ddf_header *hdr;
847 	u_int ss, size;
848 
849 	hdr = sample->hdr;
850 	meta->bigendian = sample->bigendian;
851 	ss = meta->sectorsize = sample->sectorsize;
852 	meta->hdr = malloc(ss, M_MD_DDF, M_WAITOK);
853 	memcpy(meta->hdr, sample->hdr, ss);
854 	meta->cdr = malloc(GET32(sample, hdr->cd_length) * ss, M_MD_DDF, M_WAITOK);
855 	memcpy(meta->cdr, sample->cdr, GET32(sample, hdr->cd_length) * ss);
856 	meta->vde = malloc(sizeof(struct ddf_vd_entry), M_MD_DDF, M_WAITOK);
857 	memset(meta->vde, 0xff, sizeof(struct ddf_vd_entry));
858 	getnanotime(&ts);
859 	clock_ts_to_ct(&ts, &ct);
860 	snprintf(meta->vde->VD_GUID, 25, "FreeBSD%04d%02d%02d%08x%01x",
861 	    ct.year, ct.mon, ct.day,
862 	    arc4random(), arc4random() & 0xf);
863 	size = GET16(sample, hdr->Configuration_Record_Length) * ss;
864 	meta->vdc = malloc(size, M_MD_DDF, M_WAITOK);
865 	memset(meta->vdc, 0xff, size);
866 	SET32(meta, vdc->Signature, DDF_VDCR_SIGNATURE);
867 	memcpy(meta->vdc->VD_GUID, meta->vde->VD_GUID, 24);
868 	SET32(meta, vdc->Sequence_Number, 0);
869 }
870 
871 static void
872 ddf_vol_meta_update(struct ddf_vol_meta *dst, struct ddf_meta *src,
873     uint8_t *GUID, int started)
874 {
875 	struct ddf_header *hdr;
876 	struct ddf_vd_entry *vde;
877 	struct ddf_vdc_record *vdc;
878 	int vnew, bvnew, bvd, size;
879 	u_int ss;
880 
881 	hdr = src->hdr;
882 	vde = &src->vdr->entry[ddf_meta_find_vd(src, GUID)];
883 	vdc = ddf_meta_find_vdc(src, GUID);
884 	if (GET8D(src, vdc->Secondary_Element_Count) == 1)
885 		bvd = 0;
886 	else
887 		bvd = GET8D(src, vdc->Secondary_Element_Seq);
888 	size = GET16(src, hdr->Configuration_Record_Length) * src->sectorsize;
889 
890 	if (dst->vdc == NULL ||
891 	    (!started && ((int32_t)(GET32D(src, vdc->Sequence_Number) -
892 	    GET32(dst, vdc->Sequence_Number))) > 0))
893 		vnew = 1;
894 	else
895 		vnew = 0;
896 
897 	if (dst->bvdc[bvd] == NULL ||
898 	    (!started && ((int32_t)(GET32D(src, vdc->Sequence_Number) -
899 	    GET32(dst, bvdc[bvd]->Sequence_Number))) > 0))
900 		bvnew = 1;
901 	else
902 		bvnew = 0;
903 
904 	if (vnew) {
905 		dst->bigendian = src->bigendian;
906 		ss = dst->sectorsize = src->sectorsize;
907 		if (dst->hdr != NULL)
908 			free(dst->hdr, M_MD_DDF);
909 		dst->hdr = malloc(ss, M_MD_DDF, M_WAITOK);
910 		memcpy(dst->hdr, src->hdr, ss);
911 		if (dst->cdr != NULL)
912 			free(dst->cdr, M_MD_DDF);
913 		dst->cdr = malloc(GET32(src, hdr->cd_length) * ss, M_MD_DDF, M_WAITOK);
914 		memcpy(dst->cdr, src->cdr, GET32(src, hdr->cd_length) * ss);
915 		if (dst->vde != NULL)
916 			free(dst->vde, M_MD_DDF);
917 		dst->vde = malloc(sizeof(struct ddf_vd_entry), M_MD_DDF, M_WAITOK);
918 		memcpy(dst->vde, vde, sizeof(struct ddf_vd_entry));
919 		if (dst->vdc != NULL)
920 			free(dst->vdc, M_MD_DDF);
921 		dst->vdc = malloc(size, M_MD_DDF, M_WAITOK);
922 		memcpy(dst->vdc, vdc, size);
923 	}
924 	if (bvnew) {
925 		if (dst->bvdc[bvd] != NULL)
926 			free(dst->bvdc[bvd], M_MD_DDF);
927 		dst->bvdc[bvd] = malloc(size, M_MD_DDF, M_WAITOK);
928 		memcpy(dst->bvdc[bvd], vdc, size);
929 	}
930 }
931 
932 static void
933 ddf_vol_meta_free(struct ddf_vol_meta *meta)
934 {
935 	int i;
936 
937 	if (meta->hdr != NULL) {
938 		free(meta->hdr, M_MD_DDF);
939 		meta->hdr = NULL;
940 	}
941 	if (meta->cdr != NULL) {
942 		free(meta->cdr, M_MD_DDF);
943 		meta->cdr = NULL;
944 	}
945 	if (meta->vde != NULL) {
946 		free(meta->vde, M_MD_DDF);
947 		meta->vde = NULL;
948 	}
949 	if (meta->vdc != NULL) {
950 		free(meta->vdc, M_MD_DDF);
951 		meta->vdc = NULL;
952 	}
953 	for (i = 0; i < DDF_MAX_DISKS_HARD; i++) {
954 		if (meta->bvdc[i] != NULL) {
955 			free(meta->bvdc[i], M_MD_DDF);
956 			meta->bvdc[i] = NULL;
957 		}
958 	}
959 }
960 
961 static int
962 ddf_meta_unused_range(struct ddf_meta *meta, off_t *off, off_t *size)
963 {
964 	struct ddf_vdc_record *vdc;
965 	off_t beg[32], end[32], beg1, end1;
966 	uint64_t *offp;
967 	int i, j, n, num, pos;
968 	uint32_t ref;
969 
970 	*off = 0;
971 	*size = 0;
972 	ref = GET32(meta, pdd->PD_Reference);
973 	pos = ddf_meta_find_pd(meta, NULL, ref);
974 	beg[0] = 0;
975 	end[0] = GET64(meta, pdr->entry[pos].Configured_Size);
976 	n = 1;
977 	num = GETCRNUM(meta);
978 	for (i = 0; i < num; i++) {
979 		vdc = GETVDCPTR(meta, i);
980 		if (GET32D(meta, vdc->Signature) != DDF_VDCR_SIGNATURE)
981 			continue;
982 		for (pos = 0; pos < GET16D(meta, vdc->Primary_Element_Count); pos++)
983 			if (GET32D(meta, vdc->Physical_Disk_Sequence[pos]) == ref)
984 				break;
985 		if (pos == GET16D(meta, vdc->Primary_Element_Count))
986 			continue;
987 		offp = (uint64_t *)&(vdc->Physical_Disk_Sequence[
988 		    GET16(meta, hdr->Max_Primary_Element_Entries)]);
989 		beg1 = GET64P(meta, offp + pos);
990 		end1 = beg1 + GET64D(meta, vdc->Block_Count);
991 		for (j = 0; j < n; j++) {
992 			if (beg[j] >= end1 || end[j] <= beg1 )
993 				continue;
994 			if (beg[j] < beg1 && end[j] > end1) {
995 				beg[n] = end1;
996 				end[n] = end[j];
997 				end[j] = beg1;
998 				n++;
999 			} else if (beg[j] < beg1)
1000 				end[j] = beg1;
1001 			else
1002 				beg[j] = end1;
1003 		}
1004 	}
1005 	for (j = 0; j < n; j++) {
1006 		if (end[j] - beg[j] > *size) {
1007 			*off = beg[j];
1008 			*size = end[j] - beg[j];
1009 		}
1010 	}
1011 	return ((*size > 0) ? 1 : 0);
1012 }
1013 
1014 static void
1015 ddf_meta_get_name(struct ddf_meta *meta, int num, char *buf)
1016 {
1017 	const char *b;
1018 	int i;
1019 
1020 	b = meta->vdr->entry[num].VD_Name;
1021 	for (i = 15; i >= 0; i--)
1022 		if (b[i] != 0x20)
1023 			break;
1024 	memcpy(buf, b, i + 1);
1025 	buf[i + 1] = 0;
1026 }
1027 
1028 static void
1029 ddf_meta_put_name(struct ddf_vol_meta *meta, char *buf)
1030 {
1031 	int len;
1032 
1033 	len = min(strlen(buf), 16);
1034 	memset(meta->vde->VD_Name, 0x20, 16);
1035 	memcpy(meta->vde->VD_Name, buf, len);
1036 }
1037 
1038 static int
1039 ddf_meta_read(struct g_consumer *cp, struct ddf_meta *meta)
1040 {
1041 	struct g_provider *pp;
1042 	struct ddf_header *ahdr, *hdr;
1043 	char *abuf, *buf;
1044 	off_t plba, slba, lba;
1045 	int error, len, i;
1046 	u_int ss;
1047 	uint32_t val;
1048 
1049 	ddf_meta_free(meta);
1050 	pp = cp->provider;
1051 	ss = meta->sectorsize = pp->sectorsize;
1052 	/* Read anchor block. */
1053 	abuf = g_read_data(cp, pp->mediasize - ss, ss, &error);
1054 	if (abuf == NULL) {
1055 		G_RAID_DEBUG(1, "Cannot read metadata from %s (error=%d).",
1056 		    pp->name, error);
1057 		return (error);
1058 	}
1059 	ahdr = (struct ddf_header *)abuf;
1060 
1061 	/* Check if this is an DDF RAID struct */
1062 	if (be32dec(&ahdr->Signature) == DDF_HEADER_SIGNATURE)
1063 		meta->bigendian = 1;
1064 	else if (le32dec(&ahdr->Signature) == DDF_HEADER_SIGNATURE)
1065 		meta->bigendian = 0;
1066 	else {
1067 		G_RAID_DEBUG(1, "DDF signature check failed on %s", pp->name);
1068 		error = EINVAL;
1069 		goto done;
1070 	}
1071 	if (ahdr->Header_Type != DDF_HEADER_ANCHOR) {
1072 		G_RAID_DEBUG(1, "DDF header type check failed on %s", pp->name);
1073 		error = EINVAL;
1074 		goto done;
1075 	}
1076 	meta->hdr = ahdr;
1077 	plba = GET64(meta, hdr->Primary_Header_LBA);
1078 	slba = GET64(meta, hdr->Secondary_Header_LBA);
1079 	val = GET32(meta, hdr->CRC);
1080 	SET32(meta, hdr->CRC, 0xffffffff);
1081 	meta->hdr = NULL;
1082 	if (crc32(ahdr, ss) != val) {
1083 		G_RAID_DEBUG(1, "DDF CRC mismatch on %s", pp->name);
1084 		error = EINVAL;
1085 		goto done;
1086 	}
1087 	if ((plba + 6) * ss >= pp->mediasize) {
1088 		G_RAID_DEBUG(1, "DDF primary header LBA is wrong on %s", pp->name);
1089 		error = EINVAL;
1090 		goto done;
1091 	}
1092 	if (slba != -1 && (slba + 6) * ss >= pp->mediasize) {
1093 		G_RAID_DEBUG(1, "DDF secondary header LBA is wrong on %s", pp->name);
1094 		error = EINVAL;
1095 		goto done;
1096 	}
1097 	lba = plba;
1098 
1099 doread:
1100 	error = 0;
1101 	ddf_meta_free(meta);
1102 
1103 	/* Read header block. */
1104 	buf = g_read_data(cp, lba * ss, ss, &error);
1105 	if (buf == NULL) {
1106 readerror:
1107 		G_RAID_DEBUG(1, "DDF %s metadata read error on %s (error=%d).",
1108 		    (lba == plba) ? "primary" : "secondary", pp->name, error);
1109 		if (lba == plba && slba != -1) {
1110 			lba = slba;
1111 			goto doread;
1112 		}
1113 		G_RAID_DEBUG(1, "DDF metadata read error on %s.", pp->name);
1114 		goto done;
1115 	}
1116 	meta->hdr = malloc(ss, M_MD_DDF, M_WAITOK);
1117 	memcpy(meta->hdr, buf, ss);
1118 	g_free(buf);
1119 	hdr = meta->hdr;
1120 	val = GET32(meta, hdr->CRC);
1121 	SET32(meta, hdr->CRC, 0xffffffff);
1122 	if (hdr->Signature != ahdr->Signature ||
1123 	    crc32(meta->hdr, ss) != val ||
1124 	    memcmp(hdr->DDF_Header_GUID, ahdr->DDF_Header_GUID, 24) ||
1125 	    GET64(meta, hdr->Primary_Header_LBA) != plba ||
1126 	    GET64(meta, hdr->Secondary_Header_LBA) != slba) {
1127 hdrerror:
1128 		G_RAID_DEBUG(1, "DDF %s metadata check failed on %s",
1129 		    (lba == plba) ? "primary" : "secondary", pp->name);
1130 		if (lba == plba && slba != -1) {
1131 			lba = slba;
1132 			goto doread;
1133 		}
1134 		G_RAID_DEBUG(1, "DDF metadata check failed on %s", pp->name);
1135 		error = EINVAL;
1136 		goto done;
1137 	}
1138 	if ((lba == plba && hdr->Header_Type != DDF_HEADER_PRIMARY) ||
1139 	    (lba == slba && hdr->Header_Type != DDF_HEADER_SECONDARY))
1140 		goto hdrerror;
1141 	len = 1;
1142 	len = max(len, GET32(meta, hdr->cd_section) + GET32(meta, hdr->cd_length));
1143 	len = max(len, GET32(meta, hdr->pdr_section) + GET32(meta, hdr->pdr_length));
1144 	len = max(len, GET32(meta, hdr->vdr_section) + GET32(meta, hdr->vdr_length));
1145 	len = max(len, GET32(meta, hdr->cr_section) + GET32(meta, hdr->cr_length));
1146 	len = max(len, GET32(meta, hdr->pdd_section) + GET32(meta, hdr->pdd_length));
1147 	if ((val = GET32(meta, hdr->bbmlog_section)) != 0xffffffff)
1148 		len = max(len, val + GET32(meta, hdr->bbmlog_length));
1149 	if ((val = GET32(meta, hdr->Diagnostic_Space)) != 0xffffffff)
1150 		len = max(len, val + GET32(meta, hdr->Diagnostic_Space_Length));
1151 	if ((val = GET32(meta, hdr->Vendor_Specific_Logs)) != 0xffffffff)
1152 		len = max(len, val + GET32(meta, hdr->Vendor_Specific_Logs_Length));
1153 	if ((plba + len) * ss >= pp->mediasize)
1154 		goto hdrerror;
1155 	if (slba != -1 && (slba + len) * ss >= pp->mediasize)
1156 		goto hdrerror;
1157 	/* Workaround for Adaptec implementation. */
1158 	if (GET16(meta, hdr->Max_Primary_Element_Entries) == 0xffff) {
1159 		SET16(meta, hdr->Max_Primary_Element_Entries,
1160 		    min(GET16(meta, hdr->Max_PD_Entries),
1161 		    (GET16(meta, hdr->Configuration_Record_Length) * ss - 512) / 12));
1162 	}
1163 
1164 	/* Read controller data. */
1165 	buf = g_read_data(cp, (lba + GET32(meta, hdr->cd_section)) * ss,
1166 	    GET32(meta, hdr->cd_length) * ss, &error);
1167 	if (buf == NULL)
1168 		goto readerror;
1169 	meta->cdr = malloc(GET32(meta, hdr->cd_length) * ss, M_MD_DDF, M_WAITOK);
1170 	memcpy(meta->cdr, buf, GET32(meta, hdr->cd_length) * ss);
1171 	g_free(buf);
1172 	if (GET32(meta, cdr->Signature) != DDF_CONTROLLER_DATA_SIGNATURE)
1173 		goto hdrerror;
1174 
1175 	/* Read physical disk records. */
1176 	buf = g_read_data(cp, (lba + GET32(meta, hdr->pdr_section)) * ss,
1177 	    GET32(meta, hdr->pdr_length) * ss, &error);
1178 	if (buf == NULL)
1179 		goto readerror;
1180 	meta->pdr = malloc(GET32(meta, hdr->pdr_length) * ss, M_MD_DDF, M_WAITOK);
1181 	memcpy(meta->pdr, buf, GET32(meta, hdr->pdr_length) * ss);
1182 	g_free(buf);
1183 	if (GET32(meta, pdr->Signature) != DDF_PDR_SIGNATURE)
1184 		goto hdrerror;
1185 
1186 	/* Read virtual disk records. */
1187 	buf = g_read_data(cp, (lba + GET32(meta, hdr->vdr_section)) * ss,
1188 	    GET32(meta, hdr->vdr_length) * ss, &error);
1189 	if (buf == NULL)
1190 		goto readerror;
1191 	meta->vdr = malloc(GET32(meta, hdr->vdr_length) * ss, M_MD_DDF, M_WAITOK);
1192 	memcpy(meta->vdr, buf, GET32(meta, hdr->vdr_length) * ss);
1193 	g_free(buf);
1194 	if (GET32(meta, vdr->Signature) != DDF_VD_RECORD_SIGNATURE)
1195 		goto hdrerror;
1196 
1197 	/* Read configuration records. */
1198 	buf = g_read_data(cp, (lba + GET32(meta, hdr->cr_section)) * ss,
1199 	    GET32(meta, hdr->cr_length) * ss, &error);
1200 	if (buf == NULL)
1201 		goto readerror;
1202 	meta->cr = malloc(GET32(meta, hdr->cr_length) * ss, M_MD_DDF, M_WAITOK);
1203 	memcpy(meta->cr, buf, GET32(meta, hdr->cr_length) * ss);
1204 	g_free(buf);
1205 
1206 	/* Read physical disk data. */
1207 	buf = g_read_data(cp, (lba + GET32(meta, hdr->pdd_section)) * ss,
1208 	    GET32(meta, hdr->pdd_length) * ss, &error);
1209 	if (buf == NULL)
1210 		goto readerror;
1211 	meta->pdd = malloc(GET32(meta, hdr->pdd_length) * ss, M_MD_DDF, M_WAITOK);
1212 	memcpy(meta->pdd, buf, GET32(meta, hdr->pdd_length) * ss);
1213 	g_free(buf);
1214 	if (GET32(meta, pdd->Signature) != DDF_PDD_SIGNATURE)
1215 		goto hdrerror;
1216 	i = ddf_meta_find_pd(meta, NULL, GET32(meta, pdd->PD_Reference));
1217 	if (i < 0)
1218 		goto hdrerror;
1219 
1220 	/* Read BBM Log. */
1221 	if (GET32(meta, hdr->bbmlog_section) != 0xffffffff &&
1222 	    GET32(meta, hdr->bbmlog_length) != 0) {
1223 		buf = g_read_data(cp, (lba + GET32(meta, hdr->bbmlog_section)) * ss,
1224 		    GET32(meta, hdr->bbmlog_length) * ss, &error);
1225 		if (buf == NULL)
1226 			goto readerror;
1227 		meta->bbm = malloc(GET32(meta, hdr->bbmlog_length) * ss, M_MD_DDF, M_WAITOK);
1228 		memcpy(meta->bbm, buf, GET32(meta, hdr->bbmlog_length) * ss);
1229 		g_free(buf);
1230 		if (GET32(meta, bbm->Signature) != DDF_BBML_SIGNATURE)
1231 			goto hdrerror;
1232 	}
1233 
1234 done:
1235 	g_free(abuf);
1236 	if (error != 0)
1237 		ddf_meta_free(meta);
1238 	return (error);
1239 }
1240 
1241 static int
1242 ddf_meta_write(struct g_consumer *cp, struct ddf_meta *meta)
1243 {
1244 	struct g_provider *pp;
1245 	struct ddf_vdc_record *vdc;
1246 	off_t alba, plba, slba, lba;
1247 	u_int ss, size;
1248 	int error, i, num;
1249 
1250 	pp = cp->provider;
1251 	ss = pp->sectorsize;
1252 	lba = alba = pp->mediasize / ss - 1;
1253 	plba = GET64(meta, hdr->Primary_Header_LBA);
1254 	slba = GET64(meta, hdr->Secondary_Header_LBA);
1255 
1256 next:
1257 	SET8(meta, hdr->Header_Type, (lba == alba) ? DDF_HEADER_ANCHOR :
1258 	    (lba == plba) ? DDF_HEADER_PRIMARY : DDF_HEADER_SECONDARY);
1259 	SET32(meta, hdr->CRC, 0xffffffff);
1260 	SET32(meta, hdr->CRC, crc32(meta->hdr, ss));
1261 	error = g_write_data(cp, lba * ss, meta->hdr, ss);
1262 	if (error != 0) {
1263 err:
1264 		G_RAID_DEBUG(1, "Cannot write metadata to %s (error=%d).",
1265 		    pp->name, error);
1266 		if (lba != alba)
1267 			goto done;
1268 	}
1269 	if (lba == alba) {
1270 		lba = plba;
1271 		goto next;
1272 	}
1273 
1274 	size = GET32(meta, hdr->cd_length) * ss;
1275 	SET32(meta, cdr->CRC, 0xffffffff);
1276 	SET32(meta, cdr->CRC, crc32(meta->cdr, size));
1277 	error = g_write_data(cp, (lba + GET32(meta, hdr->cd_section)) * ss,
1278 	    meta->cdr, size);
1279 	if (error != 0)
1280 		goto err;
1281 
1282 	size = GET32(meta, hdr->pdr_length) * ss;
1283 	SET32(meta, pdr->CRC, 0xffffffff);
1284 	SET32(meta, pdr->CRC, crc32(meta->pdr, size));
1285 	error = g_write_data(cp, (lba + GET32(meta, hdr->pdr_section)) * ss,
1286 	    meta->pdr, size);
1287 	if (error != 0)
1288 		goto err;
1289 
1290 	size = GET32(meta, hdr->vdr_length) * ss;
1291 	SET32(meta, vdr->CRC, 0xffffffff);
1292 	SET32(meta, vdr->CRC, crc32(meta->vdr, size));
1293 	error = g_write_data(cp, (lba + GET32(meta, hdr->vdr_section)) * ss,
1294 	    meta->vdr, size);
1295 	if (error != 0)
1296 		goto err;
1297 
1298 	size = GET16(meta, hdr->Configuration_Record_Length) * ss;
1299 	num = GETCRNUM(meta);
1300 	for (i = 0; i < num; i++) {
1301 		vdc = GETVDCPTR(meta, i);
1302 		SET32D(meta, vdc->CRC, 0xffffffff);
1303 		SET32D(meta, vdc->CRC, crc32(vdc, size));
1304 	}
1305 	error = g_write_data(cp, (lba + GET32(meta, hdr->cr_section)) * ss,
1306 	    meta->cr, size * num);
1307 	if (error != 0)
1308 		goto err;
1309 
1310 	size = GET32(meta, hdr->pdd_length) * ss;
1311 	SET32(meta, pdd->CRC, 0xffffffff);
1312 	SET32(meta, pdd->CRC, crc32(meta->pdd, size));
1313 	error = g_write_data(cp, (lba + GET32(meta, hdr->pdd_section)) * ss,
1314 	    meta->pdd, size);
1315 	if (error != 0)
1316 		goto err;
1317 
1318 	if (GET32(meta, hdr->bbmlog_length) != 0) {
1319 		size = GET32(meta, hdr->bbmlog_length) * ss;
1320 		SET32(meta, bbm->CRC, 0xffffffff);
1321 		SET32(meta, bbm->CRC, crc32(meta->bbm, size));
1322 		error = g_write_data(cp,
1323 		    (lba + GET32(meta, hdr->bbmlog_section)) * ss,
1324 		    meta->bbm, size);
1325 		if (error != 0)
1326 			goto err;
1327 	}
1328 
1329 done:
1330 	if (lba == plba && slba != -1) {
1331 		lba = slba;
1332 		goto next;
1333 	}
1334 
1335 	return (error);
1336 }
1337 
1338 static int
1339 ddf_meta_erase(struct g_consumer *cp)
1340 {
1341 	struct g_provider *pp;
1342 	char *buf;
1343 	int error;
1344 
1345 	pp = cp->provider;
1346 	buf = malloc(pp->sectorsize, M_MD_DDF, M_WAITOK | M_ZERO);
1347 	error = g_write_data(cp, pp->mediasize - pp->sectorsize,
1348 	    buf, pp->sectorsize);
1349 	if (error != 0) {
1350 		G_RAID_DEBUG(1, "Cannot erase metadata on %s (error=%d).",
1351 		    pp->name, error);
1352 	}
1353 	free(buf, M_MD_DDF);
1354 	return (error);
1355 }
1356 
1357 static struct g_raid_volume *
1358 g_raid_md_ddf_get_volume(struct g_raid_softc *sc, uint8_t *GUID)
1359 {
1360 	struct g_raid_volume	*vol;
1361 	struct g_raid_md_ddf_pervolume *pv;
1362 
1363 	TAILQ_FOREACH(vol, &sc->sc_volumes, v_next) {
1364 		pv = vol->v_md_data;
1365 		if (memcmp(pv->pv_meta.vde->VD_GUID, GUID, 24) == 0)
1366 			break;
1367 	}
1368 	return (vol);
1369 }
1370 
1371 static struct g_raid_disk *
1372 g_raid_md_ddf_get_disk(struct g_raid_softc *sc, uint8_t *GUID, uint32_t id)
1373 {
1374 	struct g_raid_disk	*disk;
1375 	struct g_raid_md_ddf_perdisk *pd;
1376 	struct ddf_meta *meta;
1377 
1378 	TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
1379 		pd = (struct g_raid_md_ddf_perdisk *)disk->d_md_data;
1380 		meta = &pd->pd_meta;
1381 		if (GUID != NULL) {
1382 			if (memcmp(meta->pdd->PD_GUID, GUID, 24) == 0)
1383 				break;
1384 		} else {
1385 			if (GET32(meta, pdd->PD_Reference) == id)
1386 				break;
1387 		}
1388 	}
1389 	return (disk);
1390 }
1391 
1392 static int
1393 g_raid_md_ddf_purge_volumes(struct g_raid_softc *sc)
1394 {
1395 	struct g_raid_volume	*vol, *tvol;
1396 	struct g_raid_md_ddf_pervolume *pv;
1397 	int i, res;
1398 
1399 	res = 0;
1400 	TAILQ_FOREACH_SAFE(vol, &sc->sc_volumes, v_next, tvol) {
1401 		pv = vol->v_md_data;
1402 		if (vol->v_stopping)
1403 			continue;
1404 		for (i = 0; i < vol->v_disks_count; i++) {
1405 			if (vol->v_subdisks[i].sd_state != G_RAID_SUBDISK_S_NONE)
1406 				break;
1407 		}
1408 		if (i >= vol->v_disks_count) {
1409 			g_raid_destroy_volume(vol);
1410 			res = 1;
1411 		}
1412 	}
1413 	return (res);
1414 }
1415 
1416 static int
1417 g_raid_md_ddf_purge_disks(struct g_raid_softc *sc)
1418 {
1419 #if 0
1420 	struct g_raid_disk	*disk, *tdisk;
1421 	struct g_raid_volume	*vol;
1422 	struct g_raid_md_ddf_perdisk *pd;
1423 	int i, j, res;
1424 
1425 	res = 0;
1426 	TAILQ_FOREACH_SAFE(disk, &sc->sc_disks, d_next, tdisk) {
1427 		if (disk->d_state == G_RAID_DISK_S_SPARE)
1428 			continue;
1429 		pd = (struct g_raid_md_ddf_perdisk *)disk->d_md_data;
1430 
1431 		/* Scan for deleted volumes. */
1432 		for (i = 0; i < pd->pd_subdisks; ) {
1433 			vol = g_raid_md_ddf_get_volume(sc,
1434 			    pd->pd_meta[i]->volume_id);
1435 			if (vol != NULL && !vol->v_stopping) {
1436 				i++;
1437 				continue;
1438 			}
1439 			free(pd->pd_meta[i], M_MD_DDF);
1440 			for (j = i; j < pd->pd_subdisks - 1; j++)
1441 				pd->pd_meta[j] = pd->pd_meta[j + 1];
1442 			pd->pd_meta[DDF_MAX_SUBDISKS - 1] = NULL;
1443 			pd->pd_subdisks--;
1444 			pd->pd_updated = 1;
1445 		}
1446 
1447 		/* If there is no metadata left - erase and delete disk. */
1448 		if (pd->pd_subdisks == 0) {
1449 			ddf_meta_erase(disk->d_consumer);
1450 			g_raid_destroy_disk(disk);
1451 			res = 1;
1452 		}
1453 	}
1454 	return (res);
1455 #endif
1456 	return (0);
1457 }
1458 
1459 static int
1460 g_raid_md_ddf_supported(int level, int qual, int disks, int force)
1461 {
1462 
1463 	if (disks > DDF_MAX_DISKS_HARD)
1464 		return (0);
1465 	switch (level) {
1466 	case G_RAID_VOLUME_RL_RAID0:
1467 		if (qual != G_RAID_VOLUME_RLQ_NONE)
1468 			return (0);
1469 		if (disks < 1)
1470 			return (0);
1471 		if (!force && disks < 2)
1472 			return (0);
1473 		break;
1474 	case G_RAID_VOLUME_RL_RAID1:
1475 		if (disks < 1)
1476 			return (0);
1477 		if (qual == G_RAID_VOLUME_RLQ_R1SM) {
1478 			if (!force && disks != 2)
1479 				return (0);
1480 		} else if (qual == G_RAID_VOLUME_RLQ_R1MM) {
1481 			if (!force && disks != 3)
1482 				return (0);
1483 		} else
1484 			return (0);
1485 		break;
1486 	case G_RAID_VOLUME_RL_RAID3:
1487 		if (qual != G_RAID_VOLUME_RLQ_R3P0 &&
1488 		    qual != G_RAID_VOLUME_RLQ_R3PN)
1489 			return (0);
1490 		if (disks < 3)
1491 			return (0);
1492 		break;
1493 	case G_RAID_VOLUME_RL_RAID4:
1494 		if (qual != G_RAID_VOLUME_RLQ_R4P0 &&
1495 		    qual != G_RAID_VOLUME_RLQ_R4PN)
1496 			return (0);
1497 		if (disks < 3)
1498 			return (0);
1499 		break;
1500 	case G_RAID_VOLUME_RL_RAID5:
1501 		if (qual != G_RAID_VOLUME_RLQ_R5RA &&
1502 		    qual != G_RAID_VOLUME_RLQ_R5RS &&
1503 		    qual != G_RAID_VOLUME_RLQ_R5LA &&
1504 		    qual != G_RAID_VOLUME_RLQ_R5LS)
1505 			return (0);
1506 		if (disks < 3)
1507 			return (0);
1508 		break;
1509 	case G_RAID_VOLUME_RL_RAID6:
1510 		if (qual != G_RAID_VOLUME_RLQ_R6RA &&
1511 		    qual != G_RAID_VOLUME_RLQ_R6RS &&
1512 		    qual != G_RAID_VOLUME_RLQ_R6LA &&
1513 		    qual != G_RAID_VOLUME_RLQ_R6LS)
1514 			return (0);
1515 		if (disks < 4)
1516 			return (0);
1517 		break;
1518 	case G_RAID_VOLUME_RL_RAIDMDF:
1519 		if (qual != G_RAID_VOLUME_RLQ_RMDFRA &&
1520 		    qual != G_RAID_VOLUME_RLQ_RMDFRS &&
1521 		    qual != G_RAID_VOLUME_RLQ_RMDFLA &&
1522 		    qual != G_RAID_VOLUME_RLQ_RMDFLS)
1523 			return (0);
1524 		if (disks < 4)
1525 			return (0);
1526 		break;
1527 	case G_RAID_VOLUME_RL_RAID1E:
1528 		if (qual != G_RAID_VOLUME_RLQ_R1EA &&
1529 		    qual != G_RAID_VOLUME_RLQ_R1EO)
1530 			return (0);
1531 		if (disks < 3)
1532 			return (0);
1533 		break;
1534 	case G_RAID_VOLUME_RL_SINGLE:
1535 		if (qual != G_RAID_VOLUME_RLQ_NONE)
1536 			return (0);
1537 		if (disks != 1)
1538 			return (0);
1539 		break;
1540 	case G_RAID_VOLUME_RL_CONCAT:
1541 		if (qual != G_RAID_VOLUME_RLQ_NONE)
1542 			return (0);
1543 		if (disks < 2)
1544 			return (0);
1545 		break;
1546 	case G_RAID_VOLUME_RL_RAID5E:
1547 		if (qual != G_RAID_VOLUME_RLQ_R5ERA &&
1548 		    qual != G_RAID_VOLUME_RLQ_R5ERS &&
1549 		    qual != G_RAID_VOLUME_RLQ_R5ELA &&
1550 		    qual != G_RAID_VOLUME_RLQ_R5ELS)
1551 			return (0);
1552 		if (disks < 4)
1553 			return (0);
1554 		break;
1555 	case G_RAID_VOLUME_RL_RAID5EE:
1556 		if (qual != G_RAID_VOLUME_RLQ_R5EERA &&
1557 		    qual != G_RAID_VOLUME_RLQ_R5EERS &&
1558 		    qual != G_RAID_VOLUME_RLQ_R5EELA &&
1559 		    qual != G_RAID_VOLUME_RLQ_R5EELS)
1560 			return (0);
1561 		if (disks < 4)
1562 			return (0);
1563 		break;
1564 	case G_RAID_VOLUME_RL_RAID5R:
1565 		if (qual != G_RAID_VOLUME_RLQ_R5RRA &&
1566 		    qual != G_RAID_VOLUME_RLQ_R5RRS &&
1567 		    qual != G_RAID_VOLUME_RLQ_R5RLA &&
1568 		    qual != G_RAID_VOLUME_RLQ_R5RLS)
1569 			return (0);
1570 		if (disks < 3)
1571 			return (0);
1572 		break;
1573 	default:
1574 		return (0);
1575 	}
1576 	return (1);
1577 }
1578 
1579 static int
1580 g_raid_md_ddf_start_disk(struct g_raid_disk *disk, struct g_raid_volume *vol)
1581 {
1582 	struct g_raid_softc *sc;
1583 	struct g_raid_subdisk *sd;
1584 	struct g_raid_md_ddf_perdisk *pd;
1585 	struct g_raid_md_ddf_pervolume *pv;
1586 	struct g_raid_md_ddf_object *mdi;
1587 	struct ddf_vol_meta *vmeta;
1588 	struct ddf_meta *pdmeta, *gmeta;
1589 	struct ddf_vdc_record *vdc1;
1590 	struct ddf_sa_record *sa;
1591 	off_t size, eoff = 0, esize = 0;
1592 	uint64_t *val2;
1593 	int disk_pos, md_disk_bvd = -1, md_disk_pos = -1, md_pde_pos;
1594 	int i, resurrection = 0;
1595 	uint32_t reference;
1596 
1597 	sc = disk->d_softc;
1598 	mdi = (struct g_raid_md_ddf_object *)sc->sc_md;
1599 	pd = (struct g_raid_md_ddf_perdisk *)disk->d_md_data;
1600 	pdmeta = &pd->pd_meta;
1601 	reference = GET32(&pd->pd_meta, pdd->PD_Reference);
1602 
1603 	pv = vol->v_md_data;
1604 	vmeta = &pv->pv_meta;
1605 	gmeta = &mdi->mdio_meta;
1606 
1607 	/* Find disk position in metadata by it's reference. */
1608 	disk_pos = ddf_meta_find_disk(vmeta, reference,
1609 	    &md_disk_bvd, &md_disk_pos);
1610 	md_pde_pos = ddf_meta_find_pd(gmeta, NULL, reference);
1611 
1612 	if (disk_pos < 0) {
1613 		G_RAID_DEBUG1(1, sc,
1614 		    "Disk %s is not a present part of the volume %s",
1615 		    g_raid_get_diskname(disk), vol->v_name);
1616 
1617 		/* Failed stale disk is useless for us. */
1618 		if ((GET16(gmeta, pdr->entry[md_pde_pos].PD_State) & DDF_PDE_PFA) != 0) {
1619 			g_raid_change_disk_state(disk, G_RAID_DISK_S_STALE_FAILED);
1620 			return (0);
1621 		}
1622 
1623 		/* If disk has some metadata for this volume - erase. */
1624 		if ((vdc1 = ddf_meta_find_vdc(pdmeta, vmeta->vdc->VD_GUID)) != NULL)
1625 			SET32D(pdmeta, vdc1->Signature, 0xffffffff);
1626 
1627 		/* If we are in the start process, that's all for now. */
1628 		if (!pv->pv_started)
1629 			goto nofit;
1630 		/*
1631 		 * If we have already started - try to get use of the disk.
1632 		 * Try to replace OFFLINE disks first, then FAILED.
1633 		 */
1634 		if (ddf_meta_count_vdc(&pd->pd_meta, NULL) >=
1635 			GET16(&pd->pd_meta, hdr->Max_Partitions)) {
1636 			G_RAID_DEBUG1(1, sc, "No free partitions on disk %s",
1637 			    g_raid_get_diskname(disk));
1638 			goto nofit;
1639 		}
1640 		ddf_meta_unused_range(&pd->pd_meta, &eoff, &esize);
1641 		if (esize == 0) {
1642 			G_RAID_DEBUG1(1, sc, "No free space on disk %s",
1643 			    g_raid_get_diskname(disk));
1644 			goto nofit;
1645 		}
1646 		eoff *= pd->pd_meta.sectorsize;
1647 		esize *= pd->pd_meta.sectorsize;
1648 		size = INT64_MAX;
1649 		for (i = 0; i < vol->v_disks_count; i++) {
1650 			sd = &vol->v_subdisks[i];
1651 			if (sd->sd_state != G_RAID_SUBDISK_S_NONE)
1652 				size = sd->sd_size;
1653 			if (sd->sd_state <= G_RAID_SUBDISK_S_FAILED &&
1654 			    (disk_pos < 0 ||
1655 			     vol->v_subdisks[i].sd_state < sd->sd_state))
1656 				disk_pos = i;
1657 		}
1658 		if (disk_pos >= 0 &&
1659 		    vol->v_raid_level != G_RAID_VOLUME_RL_CONCAT &&
1660 		    esize < size) {
1661 			G_RAID_DEBUG1(1, sc, "Disk %s free space "
1662 			    "is too small (%ju < %ju)",
1663 			    g_raid_get_diskname(disk), esize, size);
1664 			disk_pos = -1;
1665 		}
1666 		if (disk_pos >= 0) {
1667 			if (vol->v_raid_level != G_RAID_VOLUME_RL_CONCAT)
1668 				esize = size;
1669 			md_disk_bvd = disk_pos / GET16(vmeta, vdc->Primary_Element_Count); // XXX
1670 			md_disk_pos = disk_pos % GET16(vmeta, vdc->Primary_Element_Count); // XXX
1671 		} else {
1672 nofit:
1673 			if (disk->d_state == G_RAID_DISK_S_NONE)
1674 				g_raid_change_disk_state(disk,
1675 				    G_RAID_DISK_S_STALE);
1676 			return (0);
1677 		}
1678 
1679 		/*
1680 		 * If spare is committable, delete spare record.
1681 		 * Othersize, mark it active and leave there.
1682 		 */
1683 		sa = ddf_meta_find_sa(&pd->pd_meta, 0);
1684 		if (sa != NULL) {
1685 			if ((GET8D(&pd->pd_meta, sa->Spare_Type) &
1686 			    DDF_SAR_TYPE_REVERTIBLE) == 0) {
1687 				SET32D(&pd->pd_meta, sa->Signature, 0xffffffff);
1688 			} else {
1689 				SET8D(&pd->pd_meta, sa->Spare_Type,
1690 				    GET8D(&pd->pd_meta, sa->Spare_Type) |
1691 				    DDF_SAR_TYPE_ACTIVE);
1692 			}
1693 		}
1694 
1695 		G_RAID_DEBUG1(1, sc, "Disk %s takes pos %d in the volume %s",
1696 		    g_raid_get_diskname(disk), disk_pos, vol->v_name);
1697 		resurrection = 1;
1698 	}
1699 
1700 	sd = &vol->v_subdisks[disk_pos];
1701 
1702 	if (resurrection && sd->sd_disk != NULL) {
1703 		g_raid_change_disk_state(sd->sd_disk,
1704 		    G_RAID_DISK_S_STALE_FAILED);
1705 		TAILQ_REMOVE(&sd->sd_disk->d_subdisks,
1706 		    sd, sd_next);
1707 	}
1708 	vol->v_subdisks[disk_pos].sd_disk = disk;
1709 	TAILQ_INSERT_TAIL(&disk->d_subdisks, sd, sd_next);
1710 
1711 	/* Welcome the new disk. */
1712 	if (resurrection)
1713 		g_raid_change_disk_state(disk, G_RAID_DISK_S_ACTIVE);
1714 	else if (GET8(gmeta, pdr->entry[md_pde_pos].PD_State) & DDF_PDE_PFA)
1715 		g_raid_change_disk_state(disk, G_RAID_DISK_S_FAILED);
1716 	else
1717 		g_raid_change_disk_state(disk, G_RAID_DISK_S_ACTIVE);
1718 
1719 	if (resurrection) {
1720 		sd->sd_offset = eoff;
1721 		sd->sd_size = esize;
1722 	} else if (pdmeta->cr != NULL &&
1723 	    (vdc1 = ddf_meta_find_vdc(pdmeta, vmeta->vdc->VD_GUID)) != NULL) {
1724 		val2 = (uint64_t *)&(vdc1->Physical_Disk_Sequence[GET16(vmeta, hdr->Max_Primary_Element_Entries)]);
1725 		sd->sd_offset = (off_t)GET64P(pdmeta, val2 + md_disk_pos) * 512;
1726 		sd->sd_size = (off_t)GET64D(pdmeta, vdc1->Block_Count) * 512;
1727 	}
1728 
1729 	if (resurrection) {
1730 		/* Stale disk, almost same as new. */
1731 		g_raid_change_subdisk_state(sd,
1732 		    G_RAID_SUBDISK_S_NEW);
1733 	} else if (GET8(gmeta, pdr->entry[md_pde_pos].PD_State) & DDF_PDE_PFA) {
1734 		/* Failed disk. */
1735 		g_raid_change_subdisk_state(sd,
1736 		    G_RAID_SUBDISK_S_FAILED);
1737 	} else if ((GET8(gmeta, pdr->entry[md_pde_pos].PD_State) &
1738 	     (DDF_PDE_FAILED | DDF_PDE_REBUILD)) != 0) {
1739 		/* Rebuilding disk. */
1740 		g_raid_change_subdisk_state(sd,
1741 		    G_RAID_SUBDISK_S_REBUILD);
1742 		sd->sd_rebuild_pos = 0;
1743 	} else if ((GET8(vmeta, vde->VD_State) & DDF_VDE_DIRTY) != 0 ||
1744 	    (GET8(vmeta, vde->Init_State) & DDF_VDE_INIT_MASK) !=
1745 	     DDF_VDE_INIT_FULL) {
1746 		/* Stale disk or dirty volume (unclean shutdown). */
1747 		g_raid_change_subdisk_state(sd,
1748 		    G_RAID_SUBDISK_S_STALE);
1749 	} else {
1750 		/* Up to date disk. */
1751 		g_raid_change_subdisk_state(sd,
1752 		    G_RAID_SUBDISK_S_ACTIVE);
1753 	}
1754 	g_raid_event_send(sd, G_RAID_SUBDISK_E_NEW,
1755 	    G_RAID_EVENT_SUBDISK);
1756 
1757 	return (resurrection);
1758 }
1759 
1760 static void
1761 g_raid_md_ddf_refill(struct g_raid_softc *sc)
1762 {
1763 	struct g_raid_volume *vol;
1764 	struct g_raid_subdisk *sd;
1765 	struct g_raid_disk *disk;
1766 	struct g_raid_md_object *md;
1767 	struct g_raid_md_ddf_perdisk *pd;
1768 	struct g_raid_md_ddf_pervolume *pv;
1769 	int update, updated, i, bad;
1770 
1771 	md = sc->sc_md;
1772 restart:
1773 	updated = 0;
1774 	TAILQ_FOREACH(vol, &sc->sc_volumes, v_next) {
1775 		pv = vol->v_md_data;
1776 		if (!pv->pv_started || vol->v_stopping)
1777 			continue;
1778 
1779 		/* Search for subdisk that needs replacement. */
1780 		bad = 0;
1781 		for (i = 0; i < vol->v_disks_count; i++) {
1782 			sd = &vol->v_subdisks[i];
1783 			if (sd->sd_state == G_RAID_SUBDISK_S_NONE ||
1784 			    sd->sd_state == G_RAID_SUBDISK_S_FAILED)
1785 			        bad = 1;
1786 		}
1787 		if (!bad)
1788 			continue;
1789 
1790 		G_RAID_DEBUG1(1, sc, "Volume %s is not complete, "
1791 		    "trying to refill.", vol->v_name);
1792 
1793 		TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
1794 			/* Skip failed. */
1795 			if (disk->d_state < G_RAID_DISK_S_SPARE)
1796 				continue;
1797 			/* Skip already used by this volume. */
1798 			for (i = 0; i < vol->v_disks_count; i++) {
1799 				sd = &vol->v_subdisks[i];
1800 				if (sd->sd_disk == disk)
1801 					break;
1802 			}
1803 			if (i < vol->v_disks_count)
1804 				continue;
1805 
1806 			/* Try to use disk if it has empty extents. */
1807 			pd = disk->d_md_data;
1808 			if (ddf_meta_count_vdc(&pd->pd_meta, NULL) <
1809 			    GET16(&pd->pd_meta, hdr->Max_Partitions)) {
1810 				update = g_raid_md_ddf_start_disk(disk, vol);
1811 			} else
1812 				update = 0;
1813 			if (update) {
1814 				updated = 1;
1815 				g_raid_md_write_ddf(md, vol, NULL, disk);
1816 				break;
1817 			}
1818 		}
1819 	}
1820 	if (updated)
1821 		goto restart;
1822 }
1823 
1824 static void
1825 g_raid_md_ddf_start(struct g_raid_volume *vol)
1826 {
1827 	struct g_raid_softc *sc;
1828 	struct g_raid_subdisk *sd;
1829 	struct g_raid_disk *disk;
1830 	struct g_raid_md_object *md;
1831 	struct g_raid_md_ddf_perdisk *pd;
1832 	struct g_raid_md_ddf_pervolume *pv;
1833 	struct g_raid_md_ddf_object *mdi;
1834 	struct ddf_vol_meta *vmeta;
1835 	struct ddf_vdc_record *vdc;
1836 	uint64_t *val2;
1837 	int i, j, bvd;
1838 
1839 	sc = vol->v_softc;
1840 	md = sc->sc_md;
1841 	mdi = (struct g_raid_md_ddf_object *)md;
1842 	pv = vol->v_md_data;
1843 	vmeta = &pv->pv_meta;
1844 	vdc = vmeta->vdc;
1845 
1846 	vol->v_raid_level = GET8(vmeta, vdc->Primary_RAID_Level);
1847 	vol->v_raid_level_qualifier = GET8(vmeta, vdc->RLQ);
1848 	if (GET8(vmeta, vdc->Secondary_Element_Count) > 1 &&
1849 	    vol->v_raid_level == G_RAID_VOLUME_RL_RAID1 &&
1850 	    GET8(vmeta, vdc->Secondary_RAID_Level) == 0)
1851 		vol->v_raid_level = G_RAID_VOLUME_RL_RAID1E;
1852 	vol->v_sectorsize = GET16(vmeta, vdc->Block_Size);
1853 	if (vol->v_sectorsize == 0xffff)
1854 		vol->v_sectorsize = vmeta->sectorsize;
1855 	vol->v_strip_size = vol->v_sectorsize << GET8(vmeta, vdc->Stripe_Size);
1856 	vol->v_disks_count = GET16(vmeta, vdc->Primary_Element_Count) *
1857 	    GET8(vmeta, vdc->Secondary_Element_Count);
1858 	vol->v_mdf_pdisks = GET8(vmeta, vdc->MDF_Parity_Disks);
1859 	vol->v_mdf_polynomial = GET16(vmeta, vdc->MDF_Parity_Generator_Polynomial);
1860 	vol->v_mdf_method = GET8(vmeta, vdc->MDF_Constant_Generation_Method);
1861 	if (GET8(vmeta, vdc->Rotate_Parity_count) > 31)
1862 		vol->v_rotate_parity = 1;
1863 	else
1864 		vol->v_rotate_parity = 1 << GET8(vmeta, vdc->Rotate_Parity_count);
1865 	vol->v_mediasize = GET64(vmeta, vdc->VD_Size) * vol->v_sectorsize;
1866 	for (i = 0, j = 0, bvd = 0; i < vol->v_disks_count; i++, j++) {
1867 		if (j == GET16(vmeta, vdc->Primary_Element_Count)) {
1868 			j = 0;
1869 			bvd++;
1870 		}
1871 		sd = &vol->v_subdisks[i];
1872 		if (vmeta->bvdc[bvd] == NULL) {
1873 			sd->sd_offset = 0;
1874 			sd->sd_size = GET64(vmeta, vdc->Block_Count) *
1875 			    vol->v_sectorsize;
1876 			continue;
1877 		}
1878 		val2 = (uint64_t *)&(vmeta->bvdc[bvd]->Physical_Disk_Sequence[
1879 		    GET16(vmeta, hdr->Max_Primary_Element_Entries)]);
1880 		sd->sd_offset = GET64P(vmeta, val2 + j) * vol->v_sectorsize;
1881 		sd->sd_size = GET64(vmeta, bvdc[bvd]->Block_Count) *
1882 		    vol->v_sectorsize;
1883 	}
1884 	g_raid_start_volume(vol);
1885 
1886 	/* Make all disks found till the moment take their places. */
1887 	TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
1888 		pd = (struct g_raid_md_ddf_perdisk *)disk->d_md_data;
1889 		if (ddf_meta_find_vdc(&pd->pd_meta, vmeta->vdc->VD_GUID) != NULL)
1890 			g_raid_md_ddf_start_disk(disk, vol);
1891 	}
1892 
1893 	pv->pv_started = 1;
1894 	mdi->mdio_starting--;
1895 	callout_stop(&pv->pv_start_co);
1896 	G_RAID_DEBUG1(0, sc, "Volume started.");
1897 	g_raid_md_write_ddf(md, vol, NULL, NULL);
1898 
1899 	/* Pickup any STALE/SPARE disks to refill array if needed. */
1900 	g_raid_md_ddf_refill(sc);
1901 
1902 	g_raid_event_send(vol, G_RAID_VOLUME_E_START, G_RAID_EVENT_VOLUME);
1903 }
1904 
1905 static void
1906 g_raid_ddf_go(void *arg)
1907 {
1908 	struct g_raid_volume *vol;
1909 	struct g_raid_softc *sc;
1910 	struct g_raid_md_ddf_pervolume *pv;
1911 
1912 	vol = arg;
1913 	pv = vol->v_md_data;
1914 	sc = vol->v_softc;
1915 	if (!pv->pv_started) {
1916 		G_RAID_DEBUG1(0, sc, "Force volume start due to timeout.");
1917 		g_raid_event_send(vol, G_RAID_VOLUME_E_STARTMD,
1918 		    G_RAID_EVENT_VOLUME);
1919 	}
1920 }
1921 
1922 static void
1923 g_raid_md_ddf_new_disk(struct g_raid_disk *disk)
1924 {
1925 	struct g_raid_softc *sc;
1926 	struct g_raid_md_object *md;
1927 	struct g_raid_md_ddf_perdisk *pd;
1928 	struct g_raid_md_ddf_pervolume *pv;
1929 	struct g_raid_md_ddf_object *mdi;
1930 	struct g_raid_volume *vol;
1931 	struct ddf_meta *pdmeta;
1932 	struct ddf_vol_meta *vmeta;
1933 	struct ddf_vdc_record *vdc;
1934 	struct ddf_vd_entry *vde;
1935 	int i, j, k, num, have, need, cnt, spare;
1936 	uint32_t val;
1937 	char buf[17];
1938 
1939 	sc = disk->d_softc;
1940 	md = sc->sc_md;
1941 	mdi = (struct g_raid_md_ddf_object *)md;
1942 	pd = (struct g_raid_md_ddf_perdisk *)disk->d_md_data;
1943 	pdmeta = &pd->pd_meta;
1944 	spare = -1;
1945 
1946 	if (mdi->mdio_meta.hdr == NULL)
1947 		ddf_meta_copy(&mdi->mdio_meta, pdmeta);
1948 	else
1949 		ddf_meta_update(&mdi->mdio_meta, pdmeta);
1950 
1951 	num = GETCRNUM(pdmeta);
1952 	for (j = 0; j < num; j++) {
1953 		vdc = GETVDCPTR(pdmeta, j);
1954 		val = GET32D(pdmeta, vdc->Signature);
1955 
1956 		if (val == DDF_SA_SIGNATURE && spare == -1)
1957 			spare = 1;
1958 
1959 		if (val != DDF_VDCR_SIGNATURE)
1960 			continue;
1961 		spare = 0;
1962 		k = ddf_meta_find_vd(pdmeta, vdc->VD_GUID);
1963 		if (k < 0)
1964 			continue;
1965 		vde = &pdmeta->vdr->entry[k];
1966 
1967 		/* Look for volume with matching ID. */
1968 		vol = g_raid_md_ddf_get_volume(sc, vdc->VD_GUID);
1969 		if (vol == NULL) {
1970 			ddf_meta_get_name(pdmeta, k, buf);
1971 			vol = g_raid_create_volume(sc, buf,
1972 			    GET16D(pdmeta, vde->VD_Number));
1973 			pv = malloc(sizeof(*pv), M_MD_DDF, M_WAITOK | M_ZERO);
1974 			vol->v_md_data = pv;
1975 			callout_init(&pv->pv_start_co, 1);
1976 			callout_reset(&pv->pv_start_co,
1977 			    g_raid_start_timeout * hz,
1978 			    g_raid_ddf_go, vol);
1979 			mdi->mdio_starting++;
1980 		} else
1981 			pv = vol->v_md_data;
1982 
1983 		/* If we haven't started yet - check metadata freshness. */
1984 		vmeta = &pv->pv_meta;
1985 		ddf_vol_meta_update(vmeta, pdmeta, vdc->VD_GUID, pv->pv_started);
1986 	}
1987 
1988 	if (spare == 1) {
1989 		g_raid_change_disk_state(disk, G_RAID_DISK_S_SPARE);
1990 		g_raid_md_ddf_refill(sc);
1991 	}
1992 
1993 	TAILQ_FOREACH(vol, &sc->sc_volumes, v_next) {
1994 		pv = vol->v_md_data;
1995 		vmeta = &pv->pv_meta;
1996 
1997 		if (ddf_meta_find_vdc(pdmeta, vmeta->vdc->VD_GUID) == NULL)
1998 			continue;
1999 
2000 		if (pv->pv_started) {
2001 			if (g_raid_md_ddf_start_disk(disk, vol))
2002 				g_raid_md_write_ddf(md, vol, NULL, NULL);
2003 			continue;
2004 		}
2005 
2006 		/* If we collected all needed disks - start array. */
2007 		need = 0;
2008 		have = 0;
2009 		for (k = 0; k < GET8(vmeta, vdc->Secondary_Element_Count); k++) {
2010 			if (vmeta->bvdc[k] == NULL) {
2011 				need += GET16(vmeta, vdc->Primary_Element_Count);
2012 				continue;
2013 			}
2014 			cnt = GET16(vmeta, bvdc[k]->Primary_Element_Count);
2015 			need += cnt;
2016 			for (i = 0; i < cnt; i++) {
2017 				val = GET32(vmeta, bvdc[k]->Physical_Disk_Sequence[i]);
2018 				if (g_raid_md_ddf_get_disk(sc, NULL, val) != NULL)
2019 					have++;
2020 			}
2021 		}
2022 		G_RAID_DEBUG1(1, sc, "Volume %s now has %d of %d disks",
2023 		    vol->v_name, have, need);
2024 		if (have == need)
2025 			g_raid_md_ddf_start(vol);
2026 	}
2027 }
2028 
2029 static int
2030 g_raid_md_create_req_ddf(struct g_raid_md_object *md, struct g_class *mp,
2031     struct gctl_req *req, struct g_geom **gp)
2032 {
2033 	struct g_geom *geom;
2034 	struct g_raid_softc *sc;
2035 	struct g_raid_md_ddf_object *mdi, *mdi1;
2036 	char name[16];
2037 	const char *fmtopt;
2038 	int be = 1;
2039 
2040 	mdi = (struct g_raid_md_ddf_object *)md;
2041 	fmtopt = gctl_get_asciiparam(req, "fmtopt");
2042 	if (fmtopt == NULL || strcasecmp(fmtopt, "BE") == 0)
2043 		be = 1;
2044 	else if (strcasecmp(fmtopt, "LE") == 0)
2045 		be = 0;
2046 	else {
2047 		gctl_error(req, "Incorrect fmtopt argument.");
2048 		return (G_RAID_MD_TASTE_FAIL);
2049 	}
2050 
2051 	/* Search for existing node. */
2052 	LIST_FOREACH(geom, &mp->geom, geom) {
2053 		sc = geom->softc;
2054 		if (sc == NULL)
2055 			continue;
2056 		if (sc->sc_stopping != 0)
2057 			continue;
2058 		if (sc->sc_md->mdo_class != md->mdo_class)
2059 			continue;
2060 		mdi1 = (struct g_raid_md_ddf_object *)sc->sc_md;
2061 		if (mdi1->mdio_bigendian != be)
2062 			continue;
2063 		break;
2064 	}
2065 	if (geom != NULL) {
2066 		*gp = geom;
2067 		return (G_RAID_MD_TASTE_EXISTING);
2068 	}
2069 
2070 	/* Create new one if not found. */
2071 	mdi->mdio_bigendian = be;
2072 	snprintf(name, sizeof(name), "DDF%s", be ? "" : "-LE");
2073 	sc = g_raid_create_node(mp, name, md);
2074 	if (sc == NULL)
2075 		return (G_RAID_MD_TASTE_FAIL);
2076 	md->mdo_softc = sc;
2077 	*gp = sc->sc_geom;
2078 	return (G_RAID_MD_TASTE_NEW);
2079 }
2080 
2081 static int
2082 g_raid_md_taste_ddf(struct g_raid_md_object *md, struct g_class *mp,
2083                               struct g_consumer *cp, struct g_geom **gp)
2084 {
2085 	struct g_consumer *rcp;
2086 	struct g_provider *pp;
2087 	struct g_raid_softc *sc;
2088 	struct g_raid_disk *disk;
2089 	struct ddf_meta meta;
2090 	struct g_raid_md_ddf_perdisk *pd;
2091 	struct g_raid_md_ddf_object *mdi;
2092 	struct g_geom *geom;
2093 	int error, result, be;
2094 	char name[16];
2095 
2096 	G_RAID_DEBUG(1, "Tasting DDF on %s", cp->provider->name);
2097 	mdi = (struct g_raid_md_ddf_object *)md;
2098 	pp = cp->provider;
2099 
2100 	/* Read metadata from device. */
2101 	if (g_access(cp, 1, 0, 0) != 0)
2102 		return (G_RAID_MD_TASTE_FAIL);
2103 	g_topology_unlock();
2104 	bzero(&meta, sizeof(meta));
2105 	error = ddf_meta_read(cp, &meta);
2106 	g_topology_lock();
2107 	g_access(cp, -1, 0, 0);
2108 	if (error != 0)
2109 		return (G_RAID_MD_TASTE_FAIL);
2110 	be = meta.bigendian;
2111 
2112 	/* Metadata valid. Print it. */
2113 	g_raid_md_ddf_print(&meta);
2114 
2115 	/* Search for matching node. */
2116 	sc = NULL;
2117 	LIST_FOREACH(geom, &mp->geom, geom) {
2118 		sc = geom->softc;
2119 		if (sc == NULL)
2120 			continue;
2121 		if (sc->sc_stopping != 0)
2122 			continue;
2123 		if (sc->sc_md->mdo_class != md->mdo_class)
2124 			continue;
2125 		mdi = (struct g_raid_md_ddf_object *)sc->sc_md;
2126 		if (mdi->mdio_bigendian != be)
2127 			continue;
2128 		break;
2129 	}
2130 
2131 	/* Found matching node. */
2132 	if (geom != NULL) {
2133 		G_RAID_DEBUG(1, "Found matching array %s", sc->sc_name);
2134 		result = G_RAID_MD_TASTE_EXISTING;
2135 
2136 	} else { /* Not found matching node -- create one. */
2137 		result = G_RAID_MD_TASTE_NEW;
2138 		mdi->mdio_bigendian = be;
2139 		snprintf(name, sizeof(name), "DDF%s", be ? "" : "-LE");
2140 		sc = g_raid_create_node(mp, name, md);
2141 		md->mdo_softc = sc;
2142 		geom = sc->sc_geom;
2143 	}
2144 
2145 	rcp = g_new_consumer(geom);
2146 	rcp->flags |= G_CF_DIRECT_RECEIVE;
2147 	g_attach(rcp, pp);
2148 	if (g_access(rcp, 1, 1, 1) != 0)
2149 		; //goto fail1;
2150 
2151 	g_topology_unlock();
2152 	sx_xlock(&sc->sc_lock);
2153 
2154 	pd = malloc(sizeof(*pd), M_MD_DDF, M_WAITOK | M_ZERO);
2155 	pd->pd_meta = meta;
2156 	disk = g_raid_create_disk(sc);
2157 	disk->d_md_data = (void *)pd;
2158 	disk->d_consumer = rcp;
2159 	rcp->private = disk;
2160 
2161 	g_raid_get_disk_info(disk);
2162 
2163 	g_raid_md_ddf_new_disk(disk);
2164 
2165 	sx_xunlock(&sc->sc_lock);
2166 	g_topology_lock();
2167 	*gp = geom;
2168 	return (result);
2169 }
2170 
2171 static int
2172 g_raid_md_event_ddf(struct g_raid_md_object *md,
2173     struct g_raid_disk *disk, u_int event)
2174 {
2175 	struct g_raid_softc *sc;
2176 
2177 	sc = md->mdo_softc;
2178 	if (disk == NULL)
2179 		return (-1);
2180 	switch (event) {
2181 	case G_RAID_DISK_E_DISCONNECTED:
2182 		/* Delete disk. */
2183 		g_raid_change_disk_state(disk, G_RAID_DISK_S_NONE);
2184 		g_raid_destroy_disk(disk);
2185 		g_raid_md_ddf_purge_volumes(sc);
2186 
2187 		/* Write updated metadata to all disks. */
2188 		g_raid_md_write_ddf(md, NULL, NULL, NULL);
2189 
2190 		/* Check if anything left. */
2191 		if (g_raid_ndisks(sc, -1) == 0)
2192 			g_raid_destroy_node(sc, 0);
2193 		else
2194 			g_raid_md_ddf_refill(sc);
2195 		return (0);
2196 	}
2197 	return (-2);
2198 }
2199 
2200 static int
2201 g_raid_md_volume_event_ddf(struct g_raid_md_object *md,
2202     struct g_raid_volume *vol, u_int event)
2203 {
2204 	struct g_raid_md_ddf_pervolume *pv;
2205 
2206 	pv = (struct g_raid_md_ddf_pervolume *)vol->v_md_data;
2207 	switch (event) {
2208 	case G_RAID_VOLUME_E_STARTMD:
2209 		if (!pv->pv_started)
2210 			g_raid_md_ddf_start(vol);
2211 		return (0);
2212 	}
2213 	return (-2);
2214 }
2215 
2216 static int
2217 g_raid_md_ctl_ddf(struct g_raid_md_object *md,
2218     struct gctl_req *req)
2219 {
2220 	struct g_raid_softc *sc;
2221 	struct g_raid_volume *vol, *vol1;
2222 	struct g_raid_subdisk *sd;
2223 	struct g_raid_disk *disk, *disks[DDF_MAX_DISKS_HARD];
2224 	struct g_raid_md_ddf_perdisk *pd;
2225 	struct g_raid_md_ddf_pervolume *pv;
2226 	struct g_raid_md_ddf_object *mdi;
2227 	struct ddf_sa_record *sa;
2228 	struct g_consumer *cp;
2229 	struct g_provider *pp;
2230 	char arg[16];
2231 	const char *nodename, *verb, *volname, *levelname, *diskname;
2232 	char *tmp;
2233 	int *nargs, *force;
2234 	off_t size, sectorsize, strip, offs[DDF_MAX_DISKS_HARD], esize;
2235 	intmax_t *sizearg, *striparg;
2236 	int i, numdisks, len, level, qual;
2237 	int error;
2238 
2239 	sc = md->mdo_softc;
2240 	mdi = (struct g_raid_md_ddf_object *)md;
2241 	verb = gctl_get_param(req, "verb", NULL);
2242 	nargs = gctl_get_paraml(req, "nargs", sizeof(*nargs));
2243 	error = 0;
2244 
2245 	if (strcmp(verb, "label") == 0) {
2246 
2247 		if (*nargs < 4) {
2248 			gctl_error(req, "Invalid number of arguments.");
2249 			return (-1);
2250 		}
2251 		volname = gctl_get_asciiparam(req, "arg1");
2252 		if (volname == NULL) {
2253 			gctl_error(req, "No volume name.");
2254 			return (-2);
2255 		}
2256 		levelname = gctl_get_asciiparam(req, "arg2");
2257 		if (levelname == NULL) {
2258 			gctl_error(req, "No RAID level.");
2259 			return (-3);
2260 		}
2261 		if (g_raid_volume_str2level(levelname, &level, &qual)) {
2262 			gctl_error(req, "Unknown RAID level '%s'.", levelname);
2263 			return (-4);
2264 		}
2265 		numdisks = *nargs - 3;
2266 		force = gctl_get_paraml(req, "force", sizeof(*force));
2267 		if (!g_raid_md_ddf_supported(level, qual, numdisks,
2268 		    force ? *force : 0)) {
2269 			gctl_error(req, "Unsupported RAID level "
2270 			    "(0x%02x/0x%02x), or number of disks (%d).",
2271 			    level, qual, numdisks);
2272 			return (-5);
2273 		}
2274 
2275 		/* Search for disks, connect them and probe. */
2276 		size = INT64_MAX;
2277 		sectorsize = 0;
2278 		bzero(disks, sizeof(disks));
2279 		bzero(offs, sizeof(offs));
2280 		for (i = 0; i < numdisks; i++) {
2281 			snprintf(arg, sizeof(arg), "arg%d", i + 3);
2282 			diskname = gctl_get_asciiparam(req, arg);
2283 			if (diskname == NULL) {
2284 				gctl_error(req, "No disk name (%s).", arg);
2285 				error = -6;
2286 				break;
2287 			}
2288 			if (strcmp(diskname, "NONE") == 0)
2289 				continue;
2290 
2291 			TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
2292 				if (disk->d_consumer != NULL &&
2293 				    disk->d_consumer->provider != NULL &&
2294 				    strcmp(disk->d_consumer->provider->name,
2295 				     diskname) == 0)
2296 					break;
2297 			}
2298 			if (disk != NULL) {
2299 				if (disk->d_state != G_RAID_DISK_S_ACTIVE) {
2300 					gctl_error(req, "Disk '%s' is in a "
2301 					    "wrong state (%s).", diskname,
2302 					    g_raid_disk_state2str(disk->d_state));
2303 					error = -7;
2304 					break;
2305 				}
2306 				pd = disk->d_md_data;
2307 				if (ddf_meta_count_vdc(&pd->pd_meta, NULL) >=
2308 				    GET16(&pd->pd_meta, hdr->Max_Partitions)) {
2309 					gctl_error(req, "No free partitions "
2310 					    "on disk '%s'.",
2311 					    diskname);
2312 					error = -7;
2313 					break;
2314 				}
2315 				pp = disk->d_consumer->provider;
2316 				disks[i] = disk;
2317 				ddf_meta_unused_range(&pd->pd_meta,
2318 				    &offs[i], &esize);
2319 				offs[i] *= pp->sectorsize;
2320 				size = MIN(size, (off_t)esize * pp->sectorsize);
2321 				sectorsize = MAX(sectorsize, pp->sectorsize);
2322 				continue;
2323 			}
2324 
2325 			g_topology_lock();
2326 			cp = g_raid_open_consumer(sc, diskname);
2327 			if (cp == NULL) {
2328 				gctl_error(req, "Can't open disk '%s'.",
2329 				    diskname);
2330 				g_topology_unlock();
2331 				error = -8;
2332 				break;
2333 			}
2334 			pp = cp->provider;
2335 			pd = malloc(sizeof(*pd), M_MD_DDF, M_WAITOK | M_ZERO);
2336 			disk = g_raid_create_disk(sc);
2337 			disk->d_md_data = (void *)pd;
2338 			disk->d_consumer = cp;
2339 			disks[i] = disk;
2340 			cp->private = disk;
2341 			ddf_meta_create(disk, &mdi->mdio_meta);
2342 			if (mdi->mdio_meta.hdr == NULL)
2343 				ddf_meta_copy(&mdi->mdio_meta, &pd->pd_meta);
2344 			else
2345 				ddf_meta_update(&mdi->mdio_meta, &pd->pd_meta);
2346 			g_topology_unlock();
2347 
2348 			g_raid_get_disk_info(disk);
2349 
2350 			/* Reserve some space for metadata. */
2351 			size = MIN(size, GET64(&pd->pd_meta,
2352 			    pdr->entry[0].Configured_Size) * pp->sectorsize);
2353 			sectorsize = MAX(sectorsize, pp->sectorsize);
2354 		}
2355 		if (error != 0) {
2356 			for (i = 0; i < numdisks; i++) {
2357 				if (disks[i] != NULL &&
2358 				    disks[i]->d_state == G_RAID_DISK_S_NONE)
2359 					g_raid_destroy_disk(disks[i]);
2360 			}
2361 			return (error);
2362 		}
2363 
2364 		if (sectorsize <= 0) {
2365 			gctl_error(req, "Can't get sector size.");
2366 			return (-8);
2367 		}
2368 
2369 		/* Handle size argument. */
2370 		len = sizeof(*sizearg);
2371 		sizearg = gctl_get_param(req, "size", &len);
2372 		if (sizearg != NULL && len == sizeof(*sizearg) &&
2373 		    *sizearg > 0) {
2374 			if (*sizearg > size) {
2375 				gctl_error(req, "Size too big %lld > %lld.",
2376 				    (long long)*sizearg, (long long)size);
2377 				return (-9);
2378 			}
2379 			size = *sizearg;
2380 		}
2381 
2382 		/* Handle strip argument. */
2383 		strip = 131072;
2384 		len = sizeof(*striparg);
2385 		striparg = gctl_get_param(req, "strip", &len);
2386 		if (striparg != NULL && len == sizeof(*striparg) &&
2387 		    *striparg > 0) {
2388 			if (*striparg < sectorsize) {
2389 				gctl_error(req, "Strip size too small.");
2390 				return (-10);
2391 			}
2392 			if (*striparg % sectorsize != 0) {
2393 				gctl_error(req, "Incorrect strip size.");
2394 				return (-11);
2395 			}
2396 			strip = *striparg;
2397 		}
2398 
2399 		/* Round size down to strip or sector. */
2400 		if (level == G_RAID_VOLUME_RL_RAID1 ||
2401 		    level == G_RAID_VOLUME_RL_RAID3 ||
2402 		    level == G_RAID_VOLUME_RL_SINGLE ||
2403 		    level == G_RAID_VOLUME_RL_CONCAT)
2404 			size -= (size % sectorsize);
2405 		else if (level == G_RAID_VOLUME_RL_RAID1E &&
2406 		    (numdisks & 1) != 0)
2407 			size -= (size % (2 * strip));
2408 		else
2409 			size -= (size % strip);
2410 		if (size <= 0) {
2411 			gctl_error(req, "Size too small.");
2412 			return (-13);
2413 		}
2414 
2415 		/* We have all we need, create things: volume, ... */
2416 		pv = malloc(sizeof(*pv), M_MD_DDF, M_WAITOK | M_ZERO);
2417 		ddf_vol_meta_create(&pv->pv_meta, &mdi->mdio_meta);
2418 		pv->pv_started = 1;
2419 		vol = g_raid_create_volume(sc, volname, -1);
2420 		vol->v_md_data = pv;
2421 		vol->v_raid_level = level;
2422 		vol->v_raid_level_qualifier = qual;
2423 		vol->v_strip_size = strip;
2424 		vol->v_disks_count = numdisks;
2425 		if (level == G_RAID_VOLUME_RL_RAID0 ||
2426 		    level == G_RAID_VOLUME_RL_CONCAT ||
2427 		    level == G_RAID_VOLUME_RL_SINGLE)
2428 			vol->v_mediasize = size * numdisks;
2429 		else if (level == G_RAID_VOLUME_RL_RAID1)
2430 			vol->v_mediasize = size;
2431 		else if (level == G_RAID_VOLUME_RL_RAID3 ||
2432 		    level == G_RAID_VOLUME_RL_RAID4 ||
2433 		    level == G_RAID_VOLUME_RL_RAID5)
2434 			vol->v_mediasize = size * (numdisks - 1);
2435 		else if (level == G_RAID_VOLUME_RL_RAID5R) {
2436 			vol->v_mediasize = size * (numdisks - 1);
2437 			vol->v_rotate_parity = 1024;
2438 		} else if (level == G_RAID_VOLUME_RL_RAID6 ||
2439 		    level == G_RAID_VOLUME_RL_RAID5E ||
2440 		    level == G_RAID_VOLUME_RL_RAID5EE)
2441 			vol->v_mediasize = size * (numdisks - 2);
2442 		else if (level == G_RAID_VOLUME_RL_RAIDMDF) {
2443 			if (numdisks < 5)
2444 				vol->v_mdf_pdisks = 2;
2445 			else
2446 				vol->v_mdf_pdisks = 3;
2447 			vol->v_mdf_polynomial = 0x11d;
2448 			vol->v_mdf_method = 0x00;
2449 			vol->v_mediasize = size * (numdisks - vol->v_mdf_pdisks);
2450 		} else { /* RAID1E */
2451 			vol->v_mediasize = ((size * numdisks) / strip / 2) *
2452 			    strip;
2453 		}
2454 		vol->v_sectorsize = sectorsize;
2455 		g_raid_start_volume(vol);
2456 
2457 		/* , and subdisks. */
2458 		for (i = 0; i < numdisks; i++) {
2459 			disk = disks[i];
2460 			sd = &vol->v_subdisks[i];
2461 			sd->sd_disk = disk;
2462 			sd->sd_offset = offs[i];
2463 			sd->sd_size = size;
2464 			if (disk == NULL)
2465 				continue;
2466 			TAILQ_INSERT_TAIL(&disk->d_subdisks, sd, sd_next);
2467 			g_raid_change_disk_state(disk,
2468 			    G_RAID_DISK_S_ACTIVE);
2469 			g_raid_change_subdisk_state(sd,
2470 			    G_RAID_SUBDISK_S_ACTIVE);
2471 			g_raid_event_send(sd, G_RAID_SUBDISK_E_NEW,
2472 			    G_RAID_EVENT_SUBDISK);
2473 		}
2474 
2475 		/* Write metadata based on created entities. */
2476 		G_RAID_DEBUG1(0, sc, "Array started.");
2477 		g_raid_md_write_ddf(md, vol, NULL, NULL);
2478 
2479 		/* Pickup any STALE/SPARE disks to refill array if needed. */
2480 		g_raid_md_ddf_refill(sc);
2481 
2482 		g_raid_event_send(vol, G_RAID_VOLUME_E_START,
2483 		    G_RAID_EVENT_VOLUME);
2484 		return (0);
2485 	}
2486 	if (strcmp(verb, "add") == 0) {
2487 
2488 		gctl_error(req, "`add` command is not applicable, "
2489 		    "use `label` instead.");
2490 		return (-99);
2491 	}
2492 	if (strcmp(verb, "delete") == 0) {
2493 
2494 		nodename = gctl_get_asciiparam(req, "arg0");
2495 		if (nodename != NULL && strcasecmp(sc->sc_name, nodename) != 0)
2496 			nodename = NULL;
2497 
2498 		/* Full node destruction. */
2499 		if (*nargs == 1 && nodename != NULL) {
2500 			/* Check if some volume is still open. */
2501 			force = gctl_get_paraml(req, "force", sizeof(*force));
2502 			if (force != NULL && *force == 0 &&
2503 			    g_raid_nopens(sc) != 0) {
2504 				gctl_error(req, "Some volume is still open.");
2505 				return (-4);
2506 			}
2507 
2508 			TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
2509 				if (disk->d_consumer)
2510 					ddf_meta_erase(disk->d_consumer);
2511 			}
2512 			g_raid_destroy_node(sc, 0);
2513 			return (0);
2514 		}
2515 
2516 		/* Destroy specified volume. If it was last - all node. */
2517 		if (*nargs > 2) {
2518 			gctl_error(req, "Invalid number of arguments.");
2519 			return (-1);
2520 		}
2521 		volname = gctl_get_asciiparam(req,
2522 		    nodename != NULL ? "arg1" : "arg0");
2523 		if (volname == NULL) {
2524 			gctl_error(req, "No volume name.");
2525 			return (-2);
2526 		}
2527 
2528 		/* Search for volume. */
2529 		TAILQ_FOREACH(vol, &sc->sc_volumes, v_next) {
2530 			if (strcmp(vol->v_name, volname) == 0)
2531 				break;
2532 			pp = vol->v_provider;
2533 			if (pp == NULL)
2534 				continue;
2535 			if (strcmp(pp->name, volname) == 0)
2536 				break;
2537 			if (strncmp(pp->name, "raid/", 5) == 0 &&
2538 			    strcmp(pp->name + 5, volname) == 0)
2539 				break;
2540 		}
2541 		if (vol == NULL) {
2542 			i = strtol(volname, &tmp, 10);
2543 			if (verb != volname && tmp[0] == 0) {
2544 				TAILQ_FOREACH(vol, &sc->sc_volumes, v_next) {
2545 					if (vol->v_global_id == i)
2546 						break;
2547 				}
2548 			}
2549 		}
2550 		if (vol == NULL) {
2551 			gctl_error(req, "Volume '%s' not found.", volname);
2552 			return (-3);
2553 		}
2554 
2555 		/* Check if volume is still open. */
2556 		force = gctl_get_paraml(req, "force", sizeof(*force));
2557 		if (force != NULL && *force == 0 &&
2558 		    vol->v_provider_open != 0) {
2559 			gctl_error(req, "Volume is still open.");
2560 			return (-4);
2561 		}
2562 
2563 		/* Destroy volume and potentially node. */
2564 		i = 0;
2565 		TAILQ_FOREACH(vol1, &sc->sc_volumes, v_next)
2566 			i++;
2567 		if (i >= 2) {
2568 			g_raid_destroy_volume(vol);
2569 			g_raid_md_ddf_purge_disks(sc);
2570 			g_raid_md_write_ddf(md, NULL, NULL, NULL);
2571 		} else {
2572 			TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
2573 				if (disk->d_consumer)
2574 					ddf_meta_erase(disk->d_consumer);
2575 			}
2576 			g_raid_destroy_node(sc, 0);
2577 		}
2578 		return (0);
2579 	}
2580 	if (strcmp(verb, "remove") == 0 ||
2581 	    strcmp(verb, "fail") == 0) {
2582 		if (*nargs < 2) {
2583 			gctl_error(req, "Invalid number of arguments.");
2584 			return (-1);
2585 		}
2586 		for (i = 1; i < *nargs; i++) {
2587 			snprintf(arg, sizeof(arg), "arg%d", i);
2588 			diskname = gctl_get_asciiparam(req, arg);
2589 			if (diskname == NULL) {
2590 				gctl_error(req, "No disk name (%s).", arg);
2591 				error = -2;
2592 				break;
2593 			}
2594 			if (strncmp(diskname, "/dev/", 5) == 0)
2595 				diskname += 5;
2596 
2597 			TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
2598 				if (disk->d_consumer != NULL &&
2599 				    disk->d_consumer->provider != NULL &&
2600 				    strcmp(disk->d_consumer->provider->name,
2601 				     diskname) == 0)
2602 					break;
2603 			}
2604 			if (disk == NULL) {
2605 				gctl_error(req, "Disk '%s' not found.",
2606 				    diskname);
2607 				error = -3;
2608 				break;
2609 			}
2610 
2611 			if (strcmp(verb, "fail") == 0) {
2612 				g_raid_md_fail_disk_ddf(md, NULL, disk);
2613 				continue;
2614 			}
2615 
2616 			/* Erase metadata on deleting disk and destroy it. */
2617 			ddf_meta_erase(disk->d_consumer);
2618 			g_raid_destroy_disk(disk);
2619 		}
2620 		g_raid_md_ddf_purge_volumes(sc);
2621 
2622 		/* Write updated metadata to remaining disks. */
2623 		g_raid_md_write_ddf(md, NULL, NULL, NULL);
2624 
2625 		/* Check if anything left. */
2626 		if (g_raid_ndisks(sc, -1) == 0)
2627 			g_raid_destroy_node(sc, 0);
2628 		else
2629 			g_raid_md_ddf_refill(sc);
2630 		return (error);
2631 	}
2632 	if (strcmp(verb, "insert") == 0) {
2633 		if (*nargs < 2) {
2634 			gctl_error(req, "Invalid number of arguments.");
2635 			return (-1);
2636 		}
2637 		for (i = 1; i < *nargs; i++) {
2638 			/* Get disk name. */
2639 			snprintf(arg, sizeof(arg), "arg%d", i);
2640 			diskname = gctl_get_asciiparam(req, arg);
2641 			if (diskname == NULL) {
2642 				gctl_error(req, "No disk name (%s).", arg);
2643 				error = -3;
2644 				break;
2645 			}
2646 
2647 			/* Try to find provider with specified name. */
2648 			g_topology_lock();
2649 			cp = g_raid_open_consumer(sc, diskname);
2650 			if (cp == NULL) {
2651 				gctl_error(req, "Can't open disk '%s'.",
2652 				    diskname);
2653 				g_topology_unlock();
2654 				error = -4;
2655 				break;
2656 			}
2657 			pp = cp->provider;
2658 			g_topology_unlock();
2659 
2660 			pd = malloc(sizeof(*pd), M_MD_DDF, M_WAITOK | M_ZERO);
2661 
2662 			disk = g_raid_create_disk(sc);
2663 			disk->d_consumer = cp;
2664 			disk->d_md_data = (void *)pd;
2665 			cp->private = disk;
2666 
2667 			g_raid_get_disk_info(disk);
2668 
2669 			/* Welcome the "new" disk. */
2670 			g_raid_change_disk_state(disk, G_RAID_DISK_S_SPARE);
2671 			ddf_meta_create(disk, &mdi->mdio_meta);
2672 			sa = ddf_meta_find_sa(&pd->pd_meta, 1);
2673 			if (sa != NULL) {
2674 				SET32D(&pd->pd_meta, sa->Signature,
2675 				    DDF_SA_SIGNATURE);
2676 				SET8D(&pd->pd_meta, sa->Spare_Type, 0);
2677 				SET16D(&pd->pd_meta, sa->Populated_SAEs, 0);
2678 				SET16D(&pd->pd_meta, sa->MAX_SAE_Supported,
2679 				    (GET16(&pd->pd_meta, hdr->Configuration_Record_Length) *
2680 				     pd->pd_meta.sectorsize -
2681 				     sizeof(struct ddf_sa_record)) /
2682 				    sizeof(struct ddf_sa_entry));
2683 			}
2684 			if (mdi->mdio_meta.hdr == NULL)
2685 				ddf_meta_copy(&mdi->mdio_meta, &pd->pd_meta);
2686 			else
2687 				ddf_meta_update(&mdi->mdio_meta, &pd->pd_meta);
2688 			g_raid_md_write_ddf(md, NULL, NULL, NULL);
2689 			g_raid_md_ddf_refill(sc);
2690 		}
2691 		return (error);
2692 	}
2693 	return (-100);
2694 }
2695 
2696 static int
2697 g_raid_md_write_ddf(struct g_raid_md_object *md, struct g_raid_volume *tvol,
2698     struct g_raid_subdisk *tsd, struct g_raid_disk *tdisk)
2699 {
2700 	struct g_raid_softc *sc;
2701 	struct g_raid_volume *vol;
2702 	struct g_raid_subdisk *sd;
2703 	struct g_raid_disk *disk;
2704 	struct g_raid_md_ddf_perdisk *pd;
2705 	struct g_raid_md_ddf_pervolume *pv;
2706 	struct g_raid_md_ddf_object *mdi;
2707 	struct ddf_meta *gmeta;
2708 	struct ddf_vol_meta *vmeta;
2709 	struct ddf_vdc_record *vdc;
2710 	struct ddf_sa_record *sa;
2711 	uint64_t *val2;
2712 	int i, j, pos, bvd, size;
2713 
2714 	sc = md->mdo_softc;
2715 	mdi = (struct g_raid_md_ddf_object *)md;
2716 	gmeta = &mdi->mdio_meta;
2717 
2718 	if (sc->sc_stopping == G_RAID_DESTROY_HARD)
2719 		return (0);
2720 
2721 	/*
2722 	 * Clear disk flags to let only really needed ones to be reset.
2723 	 * Do it only if there are no volumes in starting state now,
2724 	 * as they can update disk statuses yet and we may kill innocent.
2725 	 */
2726 	if (mdi->mdio_starting == 0) {
2727 		for (i = 0; i < GET16(gmeta, pdr->Populated_PDEs); i++) {
2728 			if (isff(gmeta->pdr->entry[i].PD_GUID, 24))
2729 				continue;
2730 			SET16(gmeta, pdr->entry[i].PD_Type,
2731 			    GET16(gmeta, pdr->entry[i].PD_Type) &
2732 			    ~(DDF_PDE_PARTICIPATING |
2733 			      DDF_PDE_GLOBAL_SPARE | DDF_PDE_CONFIG_SPARE));
2734 			if ((GET16(gmeta, pdr->entry[i].PD_State) &
2735 			    DDF_PDE_PFA) == 0)
2736 				SET16(gmeta, pdr->entry[i].PD_State, 0);
2737 		}
2738 	}
2739 
2740 	/* Generate/update new per-volume metadata. */
2741 	TAILQ_FOREACH(vol, &sc->sc_volumes, v_next) {
2742 		pv = (struct g_raid_md_ddf_pervolume *)vol->v_md_data;
2743 		if (vol->v_stopping || !pv->pv_started)
2744 			continue;
2745 		vmeta = &pv->pv_meta;
2746 
2747 		SET32(vmeta, vdc->Sequence_Number,
2748 		    GET32(vmeta, vdc->Sequence_Number) + 1);
2749 		if (vol->v_raid_level == G_RAID_VOLUME_RL_RAID1E &&
2750 		    vol->v_disks_count % 2 == 0)
2751 			SET16(vmeta, vdc->Primary_Element_Count, 2);
2752 		else
2753 			SET16(vmeta, vdc->Primary_Element_Count,
2754 			    vol->v_disks_count);
2755 		SET8(vmeta, vdc->Stripe_Size,
2756 		    ffs(vol->v_strip_size / vol->v_sectorsize) - 1);
2757 		if (vol->v_raid_level == G_RAID_VOLUME_RL_RAID1E &&
2758 		    vol->v_disks_count % 2 == 0) {
2759 			SET8(vmeta, vdc->Primary_RAID_Level,
2760 			    DDF_VDCR_RAID1);
2761 			SET8(vmeta, vdc->RLQ, 0);
2762 			SET8(vmeta, vdc->Secondary_Element_Count,
2763 			    vol->v_disks_count / 2);
2764 			SET8(vmeta, vdc->Secondary_RAID_Level, 0);
2765 		} else {
2766 			SET8(vmeta, vdc->Primary_RAID_Level,
2767 			    vol->v_raid_level);
2768 			SET8(vmeta, vdc->RLQ,
2769 			    vol->v_raid_level_qualifier);
2770 			SET8(vmeta, vdc->Secondary_Element_Count, 1);
2771 			SET8(vmeta, vdc->Secondary_RAID_Level, 0);
2772 		}
2773 		SET8(vmeta, vdc->Secondary_Element_Seq, 0);
2774 		SET64(vmeta, vdc->Block_Count, 0);
2775 		SET64(vmeta, vdc->VD_Size, vol->v_mediasize / vol->v_sectorsize);
2776 		SET16(vmeta, vdc->Block_Size, vol->v_sectorsize);
2777 		SET8(vmeta, vdc->Rotate_Parity_count,
2778 		    fls(vol->v_rotate_parity) - 1);
2779 		SET8(vmeta, vdc->MDF_Parity_Disks, vol->v_mdf_pdisks);
2780 		SET16(vmeta, vdc->MDF_Parity_Generator_Polynomial,
2781 		    vol->v_mdf_polynomial);
2782 		SET8(vmeta, vdc->MDF_Constant_Generation_Method,
2783 		    vol->v_mdf_method);
2784 
2785 		SET16(vmeta, vde->VD_Number, vol->v_global_id);
2786 		if (vol->v_state <= G_RAID_VOLUME_S_BROKEN)
2787 			SET8(vmeta, vde->VD_State, DDF_VDE_FAILED);
2788 		else if (vol->v_state <= G_RAID_VOLUME_S_DEGRADED)
2789 			SET8(vmeta, vde->VD_State, DDF_VDE_DEGRADED);
2790 		else if (vol->v_state <= G_RAID_VOLUME_S_SUBOPTIMAL)
2791 			SET8(vmeta, vde->VD_State, DDF_VDE_PARTIAL);
2792 		else
2793 			SET8(vmeta, vde->VD_State, DDF_VDE_OPTIMAL);
2794 		if (vol->v_dirty ||
2795 		    g_raid_nsubdisks(vol, G_RAID_SUBDISK_S_STALE) > 0 ||
2796 		    g_raid_nsubdisks(vol, G_RAID_SUBDISK_S_RESYNC) > 0)
2797 			SET8(vmeta, vde->VD_State,
2798 			    GET8(vmeta, vde->VD_State) | DDF_VDE_DIRTY);
2799 		SET8(vmeta, vde->Init_State, DDF_VDE_INIT_FULL); // XXX
2800 		ddf_meta_put_name(vmeta, vol->v_name);
2801 
2802 		for (i = 0; i < vol->v_disks_count; i++) {
2803 			sd = &vol->v_subdisks[i];
2804 			bvd = i / GET16(vmeta, vdc->Primary_Element_Count);
2805 			pos = i % GET16(vmeta, vdc->Primary_Element_Count);
2806 			disk = sd->sd_disk;
2807 			if (disk != NULL) {
2808 				pd = (struct g_raid_md_ddf_perdisk *)disk->d_md_data;
2809 				if (vmeta->bvdc[bvd] == NULL) {
2810 					size = GET16(vmeta,
2811 					    hdr->Configuration_Record_Length) *
2812 					    vmeta->sectorsize;
2813 					vmeta->bvdc[bvd] = malloc(size,
2814 					    M_MD_DDF, M_WAITOK);
2815 					memset(vmeta->bvdc[bvd], 0xff, size);
2816 				}
2817 				memcpy(vmeta->bvdc[bvd], vmeta->vdc,
2818 				    sizeof(struct ddf_vdc_record));
2819 				SET8(vmeta, bvdc[bvd]->Secondary_Element_Seq, bvd);
2820 				SET64(vmeta, bvdc[bvd]->Block_Count,
2821 				    sd->sd_size / vol->v_sectorsize);
2822 				SET32(vmeta, bvdc[bvd]->Physical_Disk_Sequence[pos],
2823 				    GET32(&pd->pd_meta, pdd->PD_Reference));
2824 				val2 = (uint64_t *)&(vmeta->bvdc[bvd]->Physical_Disk_Sequence[
2825 				    GET16(vmeta, hdr->Max_Primary_Element_Entries)]);
2826 				SET64P(vmeta, val2 + pos,
2827 				    sd->sd_offset / vol->v_sectorsize);
2828 			}
2829 			if (vmeta->bvdc[bvd] == NULL)
2830 				continue;
2831 
2832 			j = ddf_meta_find_pd(gmeta, NULL,
2833 			    GET32(vmeta, bvdc[bvd]->Physical_Disk_Sequence[pos]));
2834 			if (j < 0)
2835 				continue;
2836 			SET32(gmeta, pdr->entry[j].PD_Type,
2837 			    GET32(gmeta, pdr->entry[j].PD_Type) |
2838 			    DDF_PDE_PARTICIPATING);
2839 			if (sd->sd_state == G_RAID_SUBDISK_S_NONE)
2840 				SET32(gmeta, pdr->entry[j].PD_State,
2841 				    GET32(gmeta, pdr->entry[j].PD_State) |
2842 				    (DDF_PDE_FAILED | DDF_PDE_MISSING));
2843 			else if (sd->sd_state == G_RAID_SUBDISK_S_FAILED)
2844 				SET32(gmeta, pdr->entry[j].PD_State,
2845 				    GET32(gmeta, pdr->entry[j].PD_State) |
2846 				    (DDF_PDE_FAILED | DDF_PDE_PFA));
2847 			else if (sd->sd_state <= G_RAID_SUBDISK_S_REBUILD)
2848 				SET32(gmeta, pdr->entry[j].PD_State,
2849 				    GET32(gmeta, pdr->entry[j].PD_State) |
2850 				    DDF_PDE_REBUILD);
2851 			else
2852 				SET32(gmeta, pdr->entry[j].PD_State,
2853 				    GET32(gmeta, pdr->entry[j].PD_State) |
2854 				    DDF_PDE_ONLINE);
2855 		}
2856 	}
2857 
2858 	/* Mark spare and failed disks as such. */
2859 	TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
2860 		pd = (struct g_raid_md_ddf_perdisk *)disk->d_md_data;
2861 		i = ddf_meta_find_pd(gmeta, NULL,
2862 		    GET32(&pd->pd_meta, pdd->PD_Reference));
2863 		if (i < 0)
2864 			continue;
2865 		if (disk->d_state == G_RAID_DISK_S_FAILED) {
2866 			SET32(gmeta, pdr->entry[i].PD_State,
2867 			    GET32(gmeta, pdr->entry[i].PD_State) |
2868 			    (DDF_PDE_FAILED | DDF_PDE_PFA));
2869 		}
2870 		if (disk->d_state != G_RAID_DISK_S_SPARE)
2871 			continue;
2872 		sa = ddf_meta_find_sa(&pd->pd_meta, 0);
2873 		if (sa == NULL ||
2874 		    (GET8D(&pd->pd_meta, sa->Spare_Type) &
2875 		     DDF_SAR_TYPE_DEDICATED) == 0) {
2876 			SET16(gmeta, pdr->entry[i].PD_Type,
2877 			    GET16(gmeta, pdr->entry[i].PD_Type) |
2878 			    DDF_PDE_GLOBAL_SPARE);
2879 		} else {
2880 			SET16(gmeta, pdr->entry[i].PD_Type,
2881 			    GET16(gmeta, pdr->entry[i].PD_Type) |
2882 			    DDF_PDE_CONFIG_SPARE);
2883 		}
2884 		SET32(gmeta, pdr->entry[i].PD_State,
2885 		    GET32(gmeta, pdr->entry[i].PD_State) |
2886 		    DDF_PDE_ONLINE);
2887 	}
2888 
2889 	/* Remove disks without "participating" flag (unused). */
2890 	for (i = 0, j = -1; i < GET16(gmeta, pdr->Populated_PDEs); i++) {
2891 		if (isff(gmeta->pdr->entry[i].PD_GUID, 24))
2892 			continue;
2893 		if ((GET16(gmeta, pdr->entry[i].PD_Type) &
2894 		    (DDF_PDE_PARTICIPATING |
2895 		     DDF_PDE_GLOBAL_SPARE | DDF_PDE_CONFIG_SPARE)) != 0 ||
2896 		    g_raid_md_ddf_get_disk(sc,
2897 		     NULL, GET32(gmeta, pdr->entry[i].PD_Reference)) != NULL)
2898 			j = i;
2899 		else
2900 			memset(&gmeta->pdr->entry[i], 0xff,
2901 			    sizeof(struct ddf_pd_entry));
2902 	}
2903 	SET16(gmeta, pdr->Populated_PDEs, j + 1);
2904 
2905 	/* Update per-disk metadata and write them. */
2906 	TAILQ_FOREACH(disk, &sc->sc_disks, d_next) {
2907 		pd = (struct g_raid_md_ddf_perdisk *)disk->d_md_data;
2908 		if (disk->d_state != G_RAID_DISK_S_ACTIVE &&
2909 		    disk->d_state != G_RAID_DISK_S_SPARE)
2910 			continue;
2911 		/* Update PDR. */
2912 		memcpy(pd->pd_meta.pdr, gmeta->pdr,
2913 		    GET32(&pd->pd_meta, hdr->pdr_length) *
2914 		    pd->pd_meta.sectorsize);
2915 		/* Update VDR. */
2916 		SET16(&pd->pd_meta, vdr->Populated_VDEs, 0);
2917 		TAILQ_FOREACH(vol, &sc->sc_volumes, v_next) {
2918 			if (vol->v_stopping)
2919 				continue;
2920 			pv = (struct g_raid_md_ddf_pervolume *)vol->v_md_data;
2921 			i = ddf_meta_find_vd(&pd->pd_meta,
2922 			    pv->pv_meta.vde->VD_GUID);
2923 			if (i < 0)
2924 				i = ddf_meta_find_vd(&pd->pd_meta, NULL);
2925 			if (i >= 0)
2926 				memcpy(&pd->pd_meta.vdr->entry[i],
2927 				    pv->pv_meta.vde,
2928 				    sizeof(struct ddf_vd_entry));
2929 		}
2930 		/* Update VDC. */
2931 		if (mdi->mdio_starting == 0) {
2932 			/* Remove all VDCs to restore needed later. */
2933 			j = GETCRNUM(&pd->pd_meta);
2934 			for (i = 0; i < j; i++) {
2935 				vdc = GETVDCPTR(&pd->pd_meta, i);
2936 				if (GET32D(&pd->pd_meta, vdc->Signature) !=
2937 				    DDF_VDCR_SIGNATURE)
2938 					continue;
2939 				SET32D(&pd->pd_meta, vdc->Signature, 0xffffffff);
2940 			}
2941 		}
2942 		TAILQ_FOREACH(sd, &disk->d_subdisks, sd_next) {
2943 			vol = sd->sd_volume;
2944 			if (vol->v_stopping)
2945 				continue;
2946 			pv = (struct g_raid_md_ddf_pervolume *)vol->v_md_data;
2947 			vmeta = &pv->pv_meta;
2948 			vdc = ddf_meta_find_vdc(&pd->pd_meta,
2949 			    vmeta->vde->VD_GUID);
2950 			if (vdc == NULL)
2951 				vdc = ddf_meta_find_vdc(&pd->pd_meta, NULL);
2952 			if (vdc != NULL) {
2953 				bvd = sd->sd_pos / GET16(vmeta,
2954 				    vdc->Primary_Element_Count);
2955 				memcpy(vdc, vmeta->bvdc[bvd],
2956 				    GET16(&pd->pd_meta,
2957 				    hdr->Configuration_Record_Length) *
2958 				    pd->pd_meta.sectorsize);
2959 			}
2960 		}
2961 		G_RAID_DEBUG(1, "Writing DDF metadata to %s",
2962 		    g_raid_get_diskname(disk));
2963 		g_raid_md_ddf_print(&pd->pd_meta);
2964 		ddf_meta_write(disk->d_consumer, &pd->pd_meta);
2965 	}
2966 	return (0);
2967 }
2968 
2969 static int
2970 g_raid_md_fail_disk_ddf(struct g_raid_md_object *md,
2971     struct g_raid_subdisk *tsd, struct g_raid_disk *tdisk)
2972 {
2973 	struct g_raid_softc *sc;
2974 	struct g_raid_md_ddf_perdisk *pd;
2975 	struct g_raid_subdisk *sd;
2976 	int i;
2977 
2978 	sc = md->mdo_softc;
2979 	pd = (struct g_raid_md_ddf_perdisk *)tdisk->d_md_data;
2980 
2981 	/* We can't fail disk that is not a part of array now. */
2982 	if (tdisk->d_state != G_RAID_DISK_S_ACTIVE)
2983 		return (-1);
2984 
2985 	/*
2986 	 * Mark disk as failed in metadata and try to write that metadata
2987 	 * to the disk itself to prevent it's later resurrection as STALE.
2988 	 */
2989 	G_RAID_DEBUG(1, "Writing DDF metadata to %s",
2990 	    g_raid_get_diskname(tdisk));
2991 	i = ddf_meta_find_pd(&pd->pd_meta, NULL, GET32(&pd->pd_meta, pdd->PD_Reference));
2992 	SET16(&pd->pd_meta, pdr->entry[i].PD_State, DDF_PDE_FAILED | DDF_PDE_PFA);
2993 	if (tdisk->d_consumer != NULL)
2994 		ddf_meta_write(tdisk->d_consumer, &pd->pd_meta);
2995 
2996 	/* Change states. */
2997 	g_raid_change_disk_state(tdisk, G_RAID_DISK_S_FAILED);
2998 	TAILQ_FOREACH(sd, &tdisk->d_subdisks, sd_next) {
2999 		g_raid_change_subdisk_state(sd,
3000 		    G_RAID_SUBDISK_S_FAILED);
3001 		g_raid_event_send(sd, G_RAID_SUBDISK_E_FAILED,
3002 		    G_RAID_EVENT_SUBDISK);
3003 	}
3004 
3005 	/* Write updated metadata to remaining disks. */
3006 	g_raid_md_write_ddf(md, NULL, NULL, tdisk);
3007 
3008 	g_raid_md_ddf_refill(sc);
3009 	return (0);
3010 }
3011 
3012 static int
3013 g_raid_md_free_disk_ddf(struct g_raid_md_object *md,
3014     struct g_raid_disk *disk)
3015 {
3016 	struct g_raid_md_ddf_perdisk *pd;
3017 
3018 	pd = (struct g_raid_md_ddf_perdisk *)disk->d_md_data;
3019 	ddf_meta_free(&pd->pd_meta);
3020 	free(pd, M_MD_DDF);
3021 	disk->d_md_data = NULL;
3022 	return (0);
3023 }
3024 
3025 static int
3026 g_raid_md_free_volume_ddf(struct g_raid_md_object *md,
3027     struct g_raid_volume *vol)
3028 {
3029 	struct g_raid_md_ddf_object *mdi;
3030 	struct g_raid_md_ddf_pervolume *pv;
3031 
3032 	mdi = (struct g_raid_md_ddf_object *)md;
3033 	pv = (struct g_raid_md_ddf_pervolume *)vol->v_md_data;
3034 	ddf_vol_meta_free(&pv->pv_meta);
3035 	if (!pv->pv_started) {
3036 		pv->pv_started = 1;
3037 		mdi->mdio_starting--;
3038 		callout_stop(&pv->pv_start_co);
3039 	}
3040 	free(pv, M_MD_DDF);
3041 	vol->v_md_data = NULL;
3042 	return (0);
3043 }
3044 
3045 static int
3046 g_raid_md_free_ddf(struct g_raid_md_object *md)
3047 {
3048 	struct g_raid_md_ddf_object *mdi;
3049 
3050 	mdi = (struct g_raid_md_ddf_object *)md;
3051 	if (!mdi->mdio_started) {
3052 		mdi->mdio_started = 0;
3053 		callout_stop(&mdi->mdio_start_co);
3054 		G_RAID_DEBUG1(1, md->mdo_softc,
3055 		    "root_mount_rel %p", mdi->mdio_rootmount);
3056 		root_mount_rel(mdi->mdio_rootmount);
3057 		mdi->mdio_rootmount = NULL;
3058 	}
3059 	ddf_meta_free(&mdi->mdio_meta);
3060 	return (0);
3061 }
3062 
3063 G_RAID_MD_DECLARE(ddf, "DDF");
3064