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