xref: /linux/block/partitions/ldm.c (revision afeea2758b4f1210361ce2a91d8fa3e7df606ad2)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * ldm - Support for Windows Logical Disk Manager (Dynamic Disks)
4  *
5  * Copyright (C) 2001,2002 Richard Russon <ldm@flatcap.org>
6  * Copyright (c) 2001-2012 Anton Altaparmakov
7  * Copyright (C) 2001,2002 Jakob Kemi <jakob.kemi@telia.com>
8  *
9  * Documentation is available at http://www.linux-ntfs.org/doku.php?id=downloads
10  */
11 
12 #include <linux/slab.h>
13 #include <linux/pagemap.h>
14 #include <linux/stringify.h>
15 #include <linux/kernel.h>
16 #include <linux/uuid.h>
17 #include <linux/msdos_partition.h>
18 
19 #include "ldm.h"
20 #include "check.h"
21 
22 /*
23  * ldm_debug/info/error/crit - Output an error message
24  * @f:    A printf format string containing the message
25  * @...:  Variables to substitute into @f
26  *
27  * ldm_debug() writes a DEBUG level message to the syslog but only if the
28  * driver was compiled with debug enabled. Otherwise, the call turns into a NOP.
29  */
30 #ifndef CONFIG_LDM_DEBUG
31 #define ldm_debug(...)	do {} while (0)
32 #else
33 #define ldm_debug(f, a...) _ldm_printk (KERN_DEBUG, __func__, f, ##a)
34 #endif
35 
36 #define ldm_crit(f, a...)  _ldm_printk (KERN_CRIT,  __func__, f, ##a)
37 #define ldm_error(f, a...) _ldm_printk (KERN_ERR,   __func__, f, ##a)
38 #define ldm_info(f, a...)  _ldm_printk (KERN_INFO,  __func__, f, ##a)
39 
40 static __printf(3, 4)
41 void _ldm_printk(const char *level, const char *function, const char *fmt, ...)
42 {
43 	struct va_format vaf;
44 	va_list args;
45 
46 	va_start (args, fmt);
47 
48 	vaf.fmt = fmt;
49 	vaf.va = &args;
50 
51 	printk("%s%s(): %pV\n", level, function, &vaf);
52 
53 	va_end(args);
54 }
55 
56 /**
57  * ldm_parse_privhead - Read the LDM Database PRIVHEAD structure
58  * @data:  Raw database PRIVHEAD structure loaded from the device
59  * @ph:    In-memory privhead structure in which to return parsed information
60  *
61  * This parses the LDM database PRIVHEAD structure supplied in @data and
62  * sets up the in-memory privhead structure @ph with the obtained information.
63  *
64  * Return:  'true'   @ph contains the PRIVHEAD data
65  *          'false'  @ph contents are undefined
66  */
67 static bool ldm_parse_privhead(const u8 *data, struct privhead *ph)
68 {
69 	bool is_vista = false;
70 
71 	BUG_ON(!data || !ph);
72 	if (MAGIC_PRIVHEAD != get_unaligned_be64(data)) {
73 		ldm_error("Cannot find PRIVHEAD structure. LDM database is"
74 			" corrupt. Aborting.");
75 		return false;
76 	}
77 	ph->ver_major = get_unaligned_be16(data + 0x000C);
78 	ph->ver_minor = get_unaligned_be16(data + 0x000E);
79 	ph->logical_disk_start = get_unaligned_be64(data + 0x011B);
80 	ph->logical_disk_size = get_unaligned_be64(data + 0x0123);
81 	ph->config_start = get_unaligned_be64(data + 0x012B);
82 	ph->config_size = get_unaligned_be64(data + 0x0133);
83 	/* Version 2.11 is Win2k/XP and version 2.12 is Vista. */
84 	if (ph->ver_major == 2 && ph->ver_minor == 12)
85 		is_vista = true;
86 	if (!is_vista && (ph->ver_major != 2 || ph->ver_minor != 11)) {
87 		ldm_error("Expected PRIVHEAD version 2.11 or 2.12, got %d.%d."
88 			" Aborting.", ph->ver_major, ph->ver_minor);
89 		return false;
90 	}
91 	ldm_debug("PRIVHEAD version %d.%d (Windows %s).", ph->ver_major,
92 			ph->ver_minor, is_vista ? "Vista" : "2000/XP");
93 	if (ph->config_size != LDM_DB_SIZE) {	/* 1 MiB in sectors. */
94 		/* Warn the user and continue, carefully. */
95 		ldm_info("Database is normally %u bytes, it claims to "
96 			"be %llu bytes.", LDM_DB_SIZE,
97 			(unsigned long long)ph->config_size);
98 	}
99 	if ((ph->logical_disk_size == 0) || (ph->logical_disk_start +
100 			ph->logical_disk_size > ph->config_start)) {
101 		ldm_error("PRIVHEAD disk size doesn't match real disk size");
102 		return false;
103 	}
104 	if (uuid_parse(data + 0x0030, &ph->disk_id)) {
105 		ldm_error("PRIVHEAD contains an invalid GUID.");
106 		return false;
107 	}
108 	ldm_debug("Parsed PRIVHEAD successfully.");
109 	return true;
110 }
111 
112 /**
113  * ldm_parse_tocblock - Read the LDM Database TOCBLOCK structure
114  * @data:  Raw database TOCBLOCK structure loaded from the device
115  * @toc:   In-memory toc structure in which to return parsed information
116  *
117  * This parses the LDM Database TOCBLOCK (table of contents) structure supplied
118  * in @data and sets up the in-memory tocblock structure @toc with the obtained
119  * information.
120  *
121  * N.B.  The *_start and *_size values returned in @toc are not range-checked.
122  *
123  * Return:  'true'   @toc contains the TOCBLOCK data
124  *          'false'  @toc contents are undefined
125  */
126 static bool ldm_parse_tocblock (const u8 *data, struct tocblock *toc)
127 {
128 	BUG_ON (!data || !toc);
129 
130 	if (MAGIC_TOCBLOCK != get_unaligned_be64(data)) {
131 		ldm_crit ("Cannot find TOCBLOCK, database may be corrupt.");
132 		return false;
133 	}
134 	strscpy_pad(toc->bitmap1_name, data + 0x24, sizeof(toc->bitmap1_name));
135 	toc->bitmap1_start = get_unaligned_be64(data + 0x2E);
136 	toc->bitmap1_size  = get_unaligned_be64(data + 0x36);
137 
138 	if (strncmp (toc->bitmap1_name, TOC_BITMAP1,
139 			sizeof (toc->bitmap1_name)) != 0) {
140 		ldm_crit ("TOCBLOCK's first bitmap is '%s', should be '%s'.",
141 				TOC_BITMAP1, toc->bitmap1_name);
142 		return false;
143 	}
144 	strscpy_pad(toc->bitmap2_name, data + 0x46, sizeof(toc->bitmap2_name));
145 	toc->bitmap2_start = get_unaligned_be64(data + 0x50);
146 	toc->bitmap2_size  = get_unaligned_be64(data + 0x58);
147 	if (strncmp (toc->bitmap2_name, TOC_BITMAP2,
148 			sizeof (toc->bitmap2_name)) != 0) {
149 		ldm_crit ("TOCBLOCK's second bitmap is '%s', should be '%s'.",
150 				TOC_BITMAP2, toc->bitmap2_name);
151 		return false;
152 	}
153 	ldm_debug ("Parsed TOCBLOCK successfully.");
154 	return true;
155 }
156 
157 /**
158  * ldm_parse_vmdb - Read the LDM Database VMDB structure
159  * @data:  Raw database VMDB structure loaded from the device
160  * @vm:    In-memory vmdb structure in which to return parsed information
161  *
162  * This parses the LDM Database VMDB structure supplied in @data and sets up
163  * the in-memory vmdb structure @vm with the obtained information.
164  *
165  * N.B.  The *_start, *_size and *_seq values will be range-checked later.
166  *
167  * Return:  'true'   @vm contains VMDB info
168  *          'false'  @vm contents are undefined
169  */
170 static bool ldm_parse_vmdb (const u8 *data, struct vmdb *vm)
171 {
172 	BUG_ON (!data || !vm);
173 
174 	if (MAGIC_VMDB != get_unaligned_be32(data)) {
175 		ldm_crit ("Cannot find the VMDB, database may be corrupt.");
176 		return false;
177 	}
178 
179 	vm->ver_major = get_unaligned_be16(data + 0x12);
180 	vm->ver_minor = get_unaligned_be16(data + 0x14);
181 	if ((vm->ver_major != 4) || (vm->ver_minor != 10)) {
182 		ldm_error ("Expected VMDB version %d.%d, got %d.%d. "
183 			"Aborting.", 4, 10, vm->ver_major, vm->ver_minor);
184 		return false;
185 	}
186 
187 	vm->vblk_size     = get_unaligned_be32(data + 0x08);
188 	if (vm->vblk_size == 0) {
189 		ldm_error ("Illegal VBLK size");
190 		return false;
191 	}
192 
193 	vm->vblk_offset   = get_unaligned_be32(data + 0x0C);
194 	vm->last_vblk_seq = get_unaligned_be32(data + 0x04);
195 
196 	ldm_debug ("Parsed VMDB successfully.");
197 	return true;
198 }
199 
200 /**
201  * ldm_compare_privheads - Compare two privhead objects
202  * @ph1:  First privhead
203  * @ph2:  Second privhead
204  *
205  * This compares the two privhead structures @ph1 and @ph2.
206  *
207  * Return:  'true'   Identical
208  *          'false'  Different
209  */
210 static bool ldm_compare_privheads (const struct privhead *ph1,
211 				   const struct privhead *ph2)
212 {
213 	BUG_ON (!ph1 || !ph2);
214 
215 	return ((ph1->ver_major          == ph2->ver_major)		&&
216 		(ph1->ver_minor          == ph2->ver_minor)		&&
217 		(ph1->logical_disk_start == ph2->logical_disk_start)	&&
218 		(ph1->logical_disk_size  == ph2->logical_disk_size)	&&
219 		(ph1->config_start       == ph2->config_start)		&&
220 		(ph1->config_size        == ph2->config_size)		&&
221 		uuid_equal(&ph1->disk_id, &ph2->disk_id));
222 }
223 
224 /**
225  * ldm_compare_tocblocks - Compare two tocblock objects
226  * @toc1:  First toc
227  * @toc2:  Second toc
228  *
229  * This compares the two tocblock structures @toc1 and @toc2.
230  *
231  * Return:  'true'   Identical
232  *          'false'  Different
233  */
234 static bool ldm_compare_tocblocks (const struct tocblock *toc1,
235 				   const struct tocblock *toc2)
236 {
237 	BUG_ON (!toc1 || !toc2);
238 
239 	return ((toc1->bitmap1_start == toc2->bitmap1_start)	&&
240 		(toc1->bitmap1_size  == toc2->bitmap1_size)	&&
241 		(toc1->bitmap2_start == toc2->bitmap2_start)	&&
242 		(toc1->bitmap2_size  == toc2->bitmap2_size)	&&
243 		!strncmp (toc1->bitmap1_name, toc2->bitmap1_name,
244 			sizeof (toc1->bitmap1_name))		&&
245 		!strncmp (toc1->bitmap2_name, toc2->bitmap2_name,
246 			sizeof (toc1->bitmap2_name)));
247 }
248 
249 /**
250  * ldm_validate_privheads - Compare the primary privhead with its backups
251  * @state: Partition check state including device holding the LDM Database
252  * @ph1:   Memory struct to fill with ph contents
253  *
254  * Read and compare all three privheads from disk.
255  *
256  * The privheads on disk show the size and location of the main disk area and
257  * the configuration area (the database).  The values are range-checked against
258  * @hd, which contains the real size of the disk.
259  *
260  * Return:  'true'   Success
261  *          'false'  Error
262  */
263 static bool ldm_validate_privheads(struct parsed_partitions *state,
264 				   struct privhead *ph1)
265 {
266 	static const int off[3] = { OFF_PRIV1, OFF_PRIV2, OFF_PRIV3 };
267 	struct privhead *ph[3] = { ph1 };
268 	Sector sect;
269 	u8 *data;
270 	bool result = false;
271 	long num_sects;
272 	int i;
273 
274 	BUG_ON (!state || !ph1);
275 
276 	ph[1] = kmalloc (sizeof (*ph[1]), GFP_KERNEL);
277 	ph[2] = kmalloc (sizeof (*ph[2]), GFP_KERNEL);
278 	if (!ph[1] || !ph[2]) {
279 		ldm_crit ("Out of memory.");
280 		goto out;
281 	}
282 
283 	/* off[1 & 2] are relative to ph[0]->config_start */
284 	ph[0]->config_start = 0;
285 
286 	/* Read and parse privheads */
287 	for (i = 0; i < 3; i++) {
288 		data = read_part_sector(state, ph[0]->config_start + off[i],
289 					&sect);
290 		if (!data) {
291 			ldm_crit ("Disk read failed.");
292 			goto out;
293 		}
294 		result = ldm_parse_privhead (data, ph[i]);
295 		put_dev_sector (sect);
296 		if (!result) {
297 			ldm_error ("Cannot find PRIVHEAD %d.", i+1); /* Log again */
298 			if (i < 2)
299 				goto out;	/* Already logged */
300 			else
301 				break;	/* FIXME ignore for now, 3rd PH can fail on odd-sized disks */
302 		}
303 	}
304 
305 	num_sects = get_capacity(state->disk);
306 
307 	if ((ph[0]->config_start > num_sects) ||
308 	   ((ph[0]->config_start + ph[0]->config_size) > num_sects)) {
309 		ldm_crit ("Database extends beyond the end of the disk.");
310 		goto out;
311 	}
312 
313 	if ((ph[0]->logical_disk_start > ph[0]->config_start) ||
314 	   ((ph[0]->logical_disk_start + ph[0]->logical_disk_size)
315 		    > ph[0]->config_start)) {
316 		ldm_crit ("Disk and database overlap.");
317 		goto out;
318 	}
319 
320 	if (!ldm_compare_privheads (ph[0], ph[1])) {
321 		ldm_crit ("Primary and backup PRIVHEADs don't match.");
322 		goto out;
323 	}
324 	/* FIXME ignore this for now
325 	if (!ldm_compare_privheads (ph[0], ph[2])) {
326 		ldm_crit ("Primary and backup PRIVHEADs don't match.");
327 		goto out;
328 	}*/
329 	ldm_debug ("Validated PRIVHEADs successfully.");
330 	result = true;
331 out:
332 	kfree (ph[1]);
333 	kfree (ph[2]);
334 	return result;
335 }
336 
337 /**
338  * ldm_validate_tocblocks - Validate the table of contents and its backups
339  * @state: Partition check state including device holding the LDM Database
340  * @base:  Offset, into @state->disk, of the database
341  * @ldb:   Cache of the database structures
342  *
343  * Find and compare the four tables of contents of the LDM Database stored on
344  * @state->disk and return the parsed information into @toc1.
345  *
346  * The offsets and sizes of the configs are range-checked against a privhead.
347  *
348  * Return:  'true'   @toc1 contains validated TOCBLOCK info
349  *          'false'  @toc1 contents are undefined
350  */
351 static bool ldm_validate_tocblocks(struct parsed_partitions *state,
352 				   unsigned long base, struct ldmdb *ldb)
353 {
354 	static const int off[4] = { OFF_TOCB1, OFF_TOCB2, OFF_TOCB3, OFF_TOCB4};
355 	struct tocblock *tb[4];
356 	struct privhead *ph;
357 	Sector sect;
358 	u8 *data;
359 	int i, nr_tbs;
360 	bool result = false;
361 
362 	BUG_ON(!state || !ldb);
363 	ph = &ldb->ph;
364 	tb[0] = &ldb->toc;
365 	tb[1] = kmalloc_array(3, sizeof(*tb[1]), GFP_KERNEL);
366 	if (!tb[1]) {
367 		ldm_crit("Out of memory.");
368 		goto err;
369 	}
370 	tb[2] = (struct tocblock*)((u8*)tb[1] + sizeof(*tb[1]));
371 	tb[3] = (struct tocblock*)((u8*)tb[2] + sizeof(*tb[2]));
372 	/*
373 	 * Try to read and parse all four TOCBLOCKs.
374 	 *
375 	 * Windows Vista LDM v2.12 does not always have all four TOCBLOCKs so
376 	 * skip any that fail as long as we get at least one valid TOCBLOCK.
377 	 */
378 	for (nr_tbs = i = 0; i < 4; i++) {
379 		data = read_part_sector(state, base + off[i], &sect);
380 		if (!data) {
381 			ldm_error("Disk read failed for TOCBLOCK %d.", i);
382 			continue;
383 		}
384 		if (ldm_parse_tocblock(data, tb[nr_tbs]))
385 			nr_tbs++;
386 		put_dev_sector(sect);
387 	}
388 	if (!nr_tbs) {
389 		ldm_crit("Failed to find a valid TOCBLOCK.");
390 		goto err;
391 	}
392 	/* Range check the TOCBLOCK against a privhead. */
393 	if (((tb[0]->bitmap1_start + tb[0]->bitmap1_size) > ph->config_size) ||
394 			((tb[0]->bitmap2_start + tb[0]->bitmap2_size) >
395 			ph->config_size)) {
396 		ldm_crit("The bitmaps are out of range.  Giving up.");
397 		goto err;
398 	}
399 	/* Compare all loaded TOCBLOCKs. */
400 	for (i = 1; i < nr_tbs; i++) {
401 		if (!ldm_compare_tocblocks(tb[0], tb[i])) {
402 			ldm_crit("TOCBLOCKs 0 and %d do not match.", i);
403 			goto err;
404 		}
405 	}
406 	ldm_debug("Validated %d TOCBLOCKs successfully.", nr_tbs);
407 	result = true;
408 err:
409 	kfree(tb[1]);
410 	return result;
411 }
412 
413 /**
414  * ldm_validate_vmdb - Read the VMDB and validate it
415  * @state: Partition check state including device holding the LDM Database
416  * @base:  Offset, into @bdev, of the database
417  * @ldb:   Cache of the database structures
418  *
419  * Find the vmdb of the LDM Database stored on @bdev and return the parsed
420  * information in @ldb.
421  *
422  * Return:  'true'   @ldb contains validated VBDB info
423  *          'false'  @ldb contents are undefined
424  */
425 static bool ldm_validate_vmdb(struct parsed_partitions *state,
426 			      unsigned long base, struct ldmdb *ldb)
427 {
428 	Sector sect;
429 	u8 *data;
430 	bool result = false;
431 	struct vmdb *vm;
432 	struct tocblock *toc;
433 
434 	BUG_ON (!state || !ldb);
435 
436 	vm  = &ldb->vm;
437 	toc = &ldb->toc;
438 
439 	data = read_part_sector(state, base + OFF_VMDB, &sect);
440 	if (!data) {
441 		ldm_crit ("Disk read failed.");
442 		return false;
443 	}
444 
445 	if (!ldm_parse_vmdb (data, vm))
446 		goto out;				/* Already logged */
447 
448 	/* Are there uncommitted transactions? */
449 	if (get_unaligned_be16(data + 0x10) != 0x01) {
450 		ldm_crit ("Database is not in a consistent state.  Aborting.");
451 		goto out;
452 	}
453 
454 	if (vm->vblk_offset != 512)
455 		ldm_info ("VBLKs start at offset 0x%04x.", vm->vblk_offset);
456 
457 	/*
458 	 * The last_vblkd_seq can be before the end of the vmdb, just make sure
459 	 * it is not out of bounds.
460 	 */
461 	if ((vm->vblk_size * vm->last_vblk_seq) > (toc->bitmap1_size << 9)) {
462 		ldm_crit ("VMDB exceeds allowed size specified by TOCBLOCK.  "
463 				"Database is corrupt.  Aborting.");
464 		goto out;
465 	}
466 
467 	result = true;
468 out:
469 	put_dev_sector (sect);
470 	return result;
471 }
472 
473 
474 /**
475  * ldm_validate_partition_table - Determine whether bdev might be a dynamic disk
476  * @state: Partition check state including device holding the LDM Database
477  *
478  * This function provides a weak test to decide whether the device is a dynamic
479  * disk or not.  It looks for an MS-DOS-style partition table containing at
480  * least one partition of type 0x42 (formerly SFS, now used by Windows for
481  * dynamic disks).
482  *
483  * N.B.  The only possible error can come from the read_part_sector and that is
484  *       only likely to happen if the underlying device is strange.  If that IS
485  *       the case we should return zero to let someone else try.
486  *
487  * Return:  'true'   @state->disk is a dynamic disk
488  *          'false'  @state->disk is not a dynamic disk, or an error occurred
489  */
490 static bool ldm_validate_partition_table(struct parsed_partitions *state)
491 {
492 	Sector sect;
493 	u8 *data;
494 	struct msdos_partition *p;
495 	int i;
496 	bool result = false;
497 
498 	BUG_ON(!state);
499 
500 	data = read_part_sector(state, 0, &sect);
501 	if (!data) {
502 		ldm_info ("Disk read failed.");
503 		return false;
504 	}
505 
506 	if (*(__le16*) (data + 0x01FE) != cpu_to_le16 (MSDOS_LABEL_MAGIC))
507 		goto out;
508 
509 	p = (struct msdos_partition *)(data + 0x01BE);
510 	for (i = 0; i < 4; i++, p++)
511 		if (p->sys_ind == LDM_PARTITION) {
512 			result = true;
513 			break;
514 		}
515 
516 	if (result)
517 		ldm_debug ("Found W2K dynamic disk partition type.");
518 
519 out:
520 	put_dev_sector (sect);
521 	return result;
522 }
523 
524 /**
525  * ldm_get_disk_objid - Search a linked list of vblk's for a given Disk Id
526  * @ldb:  Cache of the database structures
527  *
528  * The LDM Database contains a list of all partitions on all dynamic disks.
529  * The primary PRIVHEAD, at the beginning of the physical disk, tells us
530  * the GUID of this disk.  This function searches for the GUID in a linked
531  * list of vblk's.
532  *
533  * Return:  Pointer, A matching vblk was found
534  *          NULL,    No match, or an error
535  */
536 static struct vblk * ldm_get_disk_objid (const struct ldmdb *ldb)
537 {
538 	struct list_head *item;
539 
540 	BUG_ON (!ldb);
541 
542 	list_for_each (item, &ldb->v_disk) {
543 		struct vblk *v = list_entry (item, struct vblk, list);
544 		if (uuid_equal(&v->vblk.disk.disk_id, &ldb->ph.disk_id))
545 			return v;
546 	}
547 
548 	return NULL;
549 }
550 
551 /**
552  * ldm_create_data_partitions - Create data partitions for this device
553  * @pp:   List of the partitions parsed so far
554  * @ldb:  Cache of the database structures
555  *
556  * The database contains ALL the partitions for ALL disk groups, so we need to
557  * filter out this specific disk. Using the disk's object id, we can find all
558  * the partitions in the database that belong to this disk.
559  *
560  * Add each partition in our database, to the parsed_partitions structure.
561  *
562  * N.B.  This function creates the partitions in the order it finds partition
563  *       objects in the linked list.
564  *
565  * Return:  'true'   Partition created
566  *          'false'  Error, probably a range checking problem
567  */
568 static bool ldm_create_data_partitions (struct parsed_partitions *pp,
569 					const struct ldmdb *ldb)
570 {
571 	struct list_head *item;
572 	struct vblk *vb;
573 	struct vblk *disk;
574 	struct vblk_part *part;
575 	int part_num = 1;
576 
577 	BUG_ON (!pp || !ldb);
578 
579 	disk = ldm_get_disk_objid (ldb);
580 	if (!disk) {
581 		ldm_crit ("Can't find the ID of this disk in the database.");
582 		return false;
583 	}
584 
585 	strlcat(pp->pp_buf, " [LDM]", PAGE_SIZE);
586 
587 	/* Create the data partitions */
588 	list_for_each (item, &ldb->v_part) {
589 		vb = list_entry (item, struct vblk, list);
590 		part = &vb->vblk.part;
591 
592 		if (part->disk_id != disk->obj_id)
593 			continue;
594 
595 		put_partition (pp, part_num, ldb->ph.logical_disk_start +
596 				part->start, part->size);
597 		part_num++;
598 	}
599 
600 	strlcat(pp->pp_buf, "\n", PAGE_SIZE);
601 	return true;
602 }
603 
604 
605 /**
606  * ldm_relative - Calculate the next relative offset
607  * @buffer:  Block of data being worked on
608  * @buflen:  Size of the block of data
609  * @base:    Size of the previous fixed width fields
610  * @offset:  Cumulative size of the previous variable-width fields
611  *
612  * Because many of the VBLK fields are variable-width, it's necessary
613  * to calculate each offset based on the previous one and the length
614  * of the field it pointed to.
615  *
616  * Return:  -1 Error, the calculated offset exceeded the size of the buffer
617  *           n OK, a range-checked offset into buffer
618  */
619 static int ldm_relative(const u8 *buffer, int buflen, int base, int offset)
620 {
621 
622 	base += offset;
623 	if (!buffer || offset < 0 || base > buflen) {
624 		if (!buffer)
625 			ldm_error("!buffer");
626 		if (offset < 0)
627 			ldm_error("offset (%d) < 0", offset);
628 		if (base > buflen)
629 			ldm_error("base (%d) > buflen (%d)", base, buflen);
630 		return -1;
631 	}
632 	if (base + buffer[base] >= buflen) {
633 		ldm_error("base (%d) + buffer[base] (%d) >= buflen (%d)", base,
634 				buffer[base], buflen);
635 		return -1;
636 	}
637 	return buffer[base] + offset + 1;
638 }
639 
640 /**
641  * ldm_get_vnum - Convert a variable-width, big endian number, into cpu order
642  * @block:  Pointer to the variable-width number to convert
643  *
644  * Large numbers in the LDM Database are often stored in a packed format.  Each
645  * number is prefixed by a one byte width marker.  All numbers in the database
646  * are stored in big-endian byte order.  This function reads one of these
647  * numbers and returns the result
648  *
649  * N.B.  This function DOES NOT perform any range checking, though the most
650  *       it will read is eight bytes.
651  *
652  * Return:  n A number
653  *          0 Zero, or an error occurred
654  */
655 static u64 ldm_get_vnum (const u8 *block)
656 {
657 	u64 tmp = 0;
658 	u8 length;
659 
660 	BUG_ON (!block);
661 
662 	length = *block++;
663 
664 	if (length && length <= 8)
665 		while (length--)
666 			tmp = (tmp << 8) | *block++;
667 	else
668 		ldm_error ("Illegal length %d.", length);
669 
670 	return tmp;
671 }
672 
673 /**
674  * ldm_get_vstr - Read a length-prefixed string into a buffer
675  * @block:   Pointer to the length marker
676  * @buffer:  Location to copy string to
677  * @buflen:  Size of the output buffer
678  *
679  * Many of the strings in the LDM Database are not NULL terminated.  Instead
680  * they are prefixed by a one byte length marker.  This function copies one of
681  * these strings into a buffer.
682  *
683  * N.B.  This function DOES NOT perform any range checking on the input.
684  *       If the buffer is too small, the output will be truncated.
685  *
686  * Return:  0, Error and @buffer contents are undefined
687  *          n, String length in characters (excluding NULL)
688  *          buflen-1, String was truncated.
689  */
690 static int ldm_get_vstr (const u8 *block, u8 *buffer, int buflen)
691 {
692 	int length;
693 
694 	BUG_ON (!block || !buffer);
695 
696 	length = block[0];
697 	if (length >= buflen) {
698 		ldm_error ("Truncating string %d -> %d.", length, buflen);
699 		length = buflen - 1;
700 	}
701 	memcpy (buffer, block + 1, length);
702 	buffer[length] = 0;
703 	return length;
704 }
705 
706 
707 /**
708  * ldm_parse_cmp3 - Read a raw VBLK Component object into a vblk structure
709  * @buffer:  Block of data being worked on
710  * @buflen:  Size of the block of data
711  * @vb:      In-memory vblk in which to return information
712  *
713  * Read a raw VBLK Component object (version 3) into a vblk structure.
714  *
715  * Return:  'true'   @vb contains a Component VBLK
716  *          'false'  @vb contents are not defined
717  */
718 static bool ldm_parse_cmp3 (const u8 *buffer, int buflen, struct vblk *vb)
719 {
720 	int r_objid, r_name, r_vstate, r_child, r_parent, r_stripe, r_cols, len;
721 	struct vblk_comp *comp;
722 
723 	BUG_ON (!buffer || !vb);
724 
725 	r_objid  = ldm_relative (buffer, buflen, 0x18, 0);
726 	r_name   = ldm_relative (buffer, buflen, 0x18, r_objid);
727 	r_vstate = ldm_relative (buffer, buflen, 0x18, r_name);
728 	r_child  = ldm_relative (buffer, buflen, 0x1D, r_vstate);
729 	r_parent = ldm_relative (buffer, buflen, 0x2D, r_child);
730 
731 	if (buffer[0x12] & VBLK_FLAG_COMP_STRIPE) {
732 		r_stripe = ldm_relative (buffer, buflen, 0x2E, r_parent);
733 		r_cols   = ldm_relative (buffer, buflen, 0x2E, r_stripe);
734 		len = r_cols;
735 	} else {
736 		r_stripe = 0;
737 		len = r_parent;
738 	}
739 	if (len < 0)
740 		return false;
741 
742 	len += VBLK_SIZE_CMP3;
743 	if (len != get_unaligned_be32(buffer + 0x14))
744 		return false;
745 
746 	comp = &vb->vblk.comp;
747 	ldm_get_vstr (buffer + 0x18 + r_name, comp->state,
748 		sizeof (comp->state));
749 	comp->type      = buffer[0x18 + r_vstate];
750 	comp->children  = ldm_get_vnum (buffer + 0x1D + r_vstate);
751 	comp->parent_id = ldm_get_vnum (buffer + 0x2D + r_child);
752 	comp->chunksize = r_stripe ? ldm_get_vnum (buffer+r_parent+0x2E) : 0;
753 
754 	return true;
755 }
756 
757 /**
758  * ldm_parse_dgr3 - Read a raw VBLK Disk Group object into a vblk structure
759  * @buffer:  Block of data being worked on
760  * @buflen:  Size of the block of data
761  * @vb:      In-memory vblk in which to return information
762  *
763  * Read a raw VBLK Disk Group object (version 3) into a vblk structure.
764  *
765  * Return:  'true'   @vb contains a Disk Group VBLK
766  *          'false'  @vb contents are not defined
767  */
768 static int ldm_parse_dgr3 (const u8 *buffer, int buflen, struct vblk *vb)
769 {
770 	int r_objid, r_name, r_diskid, r_id1, r_id2, len;
771 	struct vblk_dgrp *dgrp;
772 
773 	BUG_ON (!buffer || !vb);
774 
775 	r_objid  = ldm_relative (buffer, buflen, 0x18, 0);
776 	r_name   = ldm_relative (buffer, buflen, 0x18, r_objid);
777 	r_diskid = ldm_relative (buffer, buflen, 0x18, r_name);
778 
779 	if (buffer[0x12] & VBLK_FLAG_DGR3_IDS) {
780 		r_id1 = ldm_relative (buffer, buflen, 0x24, r_diskid);
781 		r_id2 = ldm_relative (buffer, buflen, 0x24, r_id1);
782 		len = r_id2;
783 	} else
784 		len = r_diskid;
785 	if (len < 0)
786 		return false;
787 
788 	len += VBLK_SIZE_DGR3;
789 	if (len != get_unaligned_be32(buffer + 0x14))
790 		return false;
791 
792 	dgrp = &vb->vblk.dgrp;
793 	ldm_get_vstr (buffer + 0x18 + r_name, dgrp->disk_id,
794 		sizeof (dgrp->disk_id));
795 	return true;
796 }
797 
798 /**
799  * ldm_parse_dgr4 - Read a raw VBLK Disk Group object into a vblk structure
800  * @buffer:  Block of data being worked on
801  * @buflen:  Size of the block of data
802  * @vb:      In-memory vblk in which to return information
803  *
804  * Read a raw VBLK Disk Group object (version 4) into a vblk structure.
805  *
806  * Return:  'true'   @vb contains a Disk Group VBLK
807  *          'false'  @vb contents are not defined
808  */
809 static bool ldm_parse_dgr4 (const u8 *buffer, int buflen, struct vblk *vb)
810 {
811 	char buf[64];
812 	int r_objid, r_name, r_id1, r_id2, len;
813 
814 	BUG_ON (!buffer || !vb);
815 
816 	r_objid  = ldm_relative (buffer, buflen, 0x18, 0);
817 	r_name   = ldm_relative (buffer, buflen, 0x18, r_objid);
818 
819 	if (buffer[0x12] & VBLK_FLAG_DGR4_IDS) {
820 		r_id1 = ldm_relative (buffer, buflen, 0x44, r_name);
821 		r_id2 = ldm_relative (buffer, buflen, 0x44, r_id1);
822 		len = r_id2;
823 	} else
824 		len = r_name;
825 	if (len < 0)
826 		return false;
827 
828 	len += VBLK_SIZE_DGR4;
829 	if (len != get_unaligned_be32(buffer + 0x14))
830 		return false;
831 
832 	ldm_get_vstr (buffer + 0x18 + r_objid, buf, sizeof (buf));
833 	return true;
834 }
835 
836 /**
837  * ldm_parse_dsk3 - Read a raw VBLK Disk object into a vblk structure
838  * @buffer:  Block of data being worked on
839  * @buflen:  Size of the block of data
840  * @vb:      In-memory vblk in which to return information
841  *
842  * Read a raw VBLK Disk object (version 3) into a vblk structure.
843  *
844  * Return:  'true'   @vb contains a Disk VBLK
845  *          'false'  @vb contents are not defined
846  */
847 static bool ldm_parse_dsk3 (const u8 *buffer, int buflen, struct vblk *vb)
848 {
849 	int r_objid, r_name, r_diskid, r_altname, len;
850 	struct vblk_disk *disk;
851 
852 	BUG_ON (!buffer || !vb);
853 
854 	r_objid   = ldm_relative (buffer, buflen, 0x18, 0);
855 	r_name    = ldm_relative (buffer, buflen, 0x18, r_objid);
856 	r_diskid  = ldm_relative (buffer, buflen, 0x18, r_name);
857 	r_altname = ldm_relative (buffer, buflen, 0x18, r_diskid);
858 	len = r_altname;
859 	if (len < 0)
860 		return false;
861 
862 	len += VBLK_SIZE_DSK3;
863 	if (len != get_unaligned_be32(buffer + 0x14))
864 		return false;
865 
866 	disk = &vb->vblk.disk;
867 	ldm_get_vstr (buffer + 0x18 + r_diskid, disk->alt_name,
868 		sizeof (disk->alt_name));
869 	if (uuid_parse(buffer + 0x19 + r_name, &disk->disk_id))
870 		return false;
871 
872 	return true;
873 }
874 
875 /**
876  * ldm_parse_dsk4 - Read a raw VBLK Disk object into a vblk structure
877  * @buffer:  Block of data being worked on
878  * @buflen:  Size of the block of data
879  * @vb:      In-memory vblk in which to return information
880  *
881  * Read a raw VBLK Disk object (version 4) into a vblk structure.
882  *
883  * Return:  'true'   @vb contains a Disk VBLK
884  *          'false'  @vb contents are not defined
885  */
886 static bool ldm_parse_dsk4 (const u8 *buffer, int buflen, struct vblk *vb)
887 {
888 	int r_objid, r_name, len;
889 	struct vblk_disk *disk;
890 
891 	BUG_ON (!buffer || !vb);
892 
893 	r_objid = ldm_relative (buffer, buflen, 0x18, 0);
894 	r_name  = ldm_relative (buffer, buflen, 0x18, r_objid);
895 	len     = r_name;
896 	if (len < 0)
897 		return false;
898 
899 	len += VBLK_SIZE_DSK4;
900 	if (len != get_unaligned_be32(buffer + 0x14))
901 		return false;
902 
903 	disk = &vb->vblk.disk;
904 	import_uuid(&disk->disk_id, buffer + 0x18 + r_name);
905 	return true;
906 }
907 
908 /**
909  * ldm_parse_prt3 - Read a raw VBLK Partition object into a vblk structure
910  * @buffer:  Block of data being worked on
911  * @buflen:  Size of the block of data
912  * @vb:      In-memory vblk in which to return information
913  *
914  * Read a raw VBLK Partition object (version 3) into a vblk structure.
915  *
916  * Return:  'true'   @vb contains a Partition VBLK
917  *          'false'  @vb contents are not defined
918  */
919 static bool ldm_parse_prt3(const u8 *buffer, int buflen, struct vblk *vb)
920 {
921 	int r_objid, r_name, r_size, r_parent, r_diskid, r_index, len;
922 	struct vblk_part *part;
923 
924 	BUG_ON(!buffer || !vb);
925 	r_objid = ldm_relative(buffer, buflen, 0x18, 0);
926 	if (r_objid < 0) {
927 		ldm_error("r_objid %d < 0", r_objid);
928 		return false;
929 	}
930 	r_name = ldm_relative(buffer, buflen, 0x18, r_objid);
931 	if (r_name < 0) {
932 		ldm_error("r_name %d < 0", r_name);
933 		return false;
934 	}
935 	r_size = ldm_relative(buffer, buflen, 0x34, r_name);
936 	if (r_size < 0) {
937 		ldm_error("r_size %d < 0", r_size);
938 		return false;
939 	}
940 	r_parent = ldm_relative(buffer, buflen, 0x34, r_size);
941 	if (r_parent < 0) {
942 		ldm_error("r_parent %d < 0", r_parent);
943 		return false;
944 	}
945 	r_diskid = ldm_relative(buffer, buflen, 0x34, r_parent);
946 	if (r_diskid < 0) {
947 		ldm_error("r_diskid %d < 0", r_diskid);
948 		return false;
949 	}
950 	if (buffer[0x12] & VBLK_FLAG_PART_INDEX) {
951 		r_index = ldm_relative(buffer, buflen, 0x34, r_diskid);
952 		if (r_index < 0) {
953 			ldm_error("r_index %d < 0", r_index);
954 			return false;
955 		}
956 		len = r_index;
957 	} else
958 		len = r_diskid;
959 	if (len < 0) {
960 		ldm_error("len %d < 0", len);
961 		return false;
962 	}
963 	len += VBLK_SIZE_PRT3;
964 	if (len > get_unaligned_be32(buffer + 0x14)) {
965 		ldm_error("len %d > BE32(buffer + 0x14) %d", len,
966 				get_unaligned_be32(buffer + 0x14));
967 		return false;
968 	}
969 	part = &vb->vblk.part;
970 	part->start = get_unaligned_be64(buffer + 0x24 + r_name);
971 	part->volume_offset = get_unaligned_be64(buffer + 0x2C + r_name);
972 	part->size = ldm_get_vnum(buffer + 0x34 + r_name);
973 	part->parent_id = ldm_get_vnum(buffer + 0x34 + r_size);
974 	part->disk_id = ldm_get_vnum(buffer + 0x34 + r_parent);
975 	if (vb->flags & VBLK_FLAG_PART_INDEX)
976 		part->partnum = buffer[0x35 + r_diskid];
977 	else
978 		part->partnum = 0;
979 	return true;
980 }
981 
982 /**
983  * ldm_parse_vol5 - Read a raw VBLK Volume object into a vblk structure
984  * @buffer:  Block of data being worked on
985  * @buflen:  Size of the block of data
986  * @vb:      In-memory vblk in which to return information
987  *
988  * Read a raw VBLK Volume object (version 5) into a vblk structure.
989  *
990  * Return:  'true'   @vb contains a Volume VBLK
991  *          'false'  @vb contents are not defined
992  */
993 static bool ldm_parse_vol5(const u8 *buffer, int buflen, struct vblk *vb)
994 {
995 	int r_objid, r_name, r_vtype, r_disable_drive_letter, r_child, r_size;
996 	int r_id1, r_id2, r_size2, r_drive, len;
997 	struct vblk_volu *volu;
998 
999 	BUG_ON(!buffer || !vb);
1000 	r_objid = ldm_relative(buffer, buflen, 0x18, 0);
1001 	if (r_objid < 0) {
1002 		ldm_error("r_objid %d < 0", r_objid);
1003 		return false;
1004 	}
1005 	r_name = ldm_relative(buffer, buflen, 0x18, r_objid);
1006 	if (r_name < 0) {
1007 		ldm_error("r_name %d < 0", r_name);
1008 		return false;
1009 	}
1010 	r_vtype = ldm_relative(buffer, buflen, 0x18, r_name);
1011 	if (r_vtype < 0) {
1012 		ldm_error("r_vtype %d < 0", r_vtype);
1013 		return false;
1014 	}
1015 	r_disable_drive_letter = ldm_relative(buffer, buflen, 0x18, r_vtype);
1016 	if (r_disable_drive_letter < 0) {
1017 		ldm_error("r_disable_drive_letter %d < 0",
1018 				r_disable_drive_letter);
1019 		return false;
1020 	}
1021 	r_child = ldm_relative(buffer, buflen, 0x2D, r_disable_drive_letter);
1022 	if (r_child < 0) {
1023 		ldm_error("r_child %d < 0", r_child);
1024 		return false;
1025 	}
1026 	r_size = ldm_relative(buffer, buflen, 0x3D, r_child);
1027 	if (r_size < 0) {
1028 		ldm_error("r_size %d < 0", r_size);
1029 		return false;
1030 	}
1031 	if (buffer[0x12] & VBLK_FLAG_VOLU_ID1) {
1032 		r_id1 = ldm_relative(buffer, buflen, 0x52, r_size);
1033 		if (r_id1 < 0) {
1034 			ldm_error("r_id1 %d < 0", r_id1);
1035 			return false;
1036 		}
1037 	} else
1038 		r_id1 = r_size;
1039 	if (buffer[0x12] & VBLK_FLAG_VOLU_ID2) {
1040 		r_id2 = ldm_relative(buffer, buflen, 0x52, r_id1);
1041 		if (r_id2 < 0) {
1042 			ldm_error("r_id2 %d < 0", r_id2);
1043 			return false;
1044 		}
1045 	} else
1046 		r_id2 = r_id1;
1047 	if (buffer[0x12] & VBLK_FLAG_VOLU_SIZE) {
1048 		r_size2 = ldm_relative(buffer, buflen, 0x52, r_id2);
1049 		if (r_size2 < 0) {
1050 			ldm_error("r_size2 %d < 0", r_size2);
1051 			return false;
1052 		}
1053 	} else
1054 		r_size2 = r_id2;
1055 	if (buffer[0x12] & VBLK_FLAG_VOLU_DRIVE) {
1056 		r_drive = ldm_relative(buffer, buflen, 0x52, r_size2);
1057 		if (r_drive < 0) {
1058 			ldm_error("r_drive %d < 0", r_drive);
1059 			return false;
1060 		}
1061 	} else
1062 		r_drive = r_size2;
1063 	len = r_drive;
1064 	if (len < 0) {
1065 		ldm_error("len %d < 0", len);
1066 		return false;
1067 	}
1068 	len += VBLK_SIZE_VOL5;
1069 	if (len > get_unaligned_be32(buffer + 0x14)) {
1070 		ldm_error("len %d > BE32(buffer + 0x14) %d", len,
1071 				get_unaligned_be32(buffer + 0x14));
1072 		return false;
1073 	}
1074 	volu = &vb->vblk.volu;
1075 	ldm_get_vstr(buffer + 0x18 + r_name, volu->volume_type,
1076 			sizeof(volu->volume_type));
1077 	memcpy(volu->volume_state, buffer + 0x18 + r_disable_drive_letter,
1078 			sizeof(volu->volume_state));
1079 	volu->size = ldm_get_vnum(buffer + 0x3D + r_child);
1080 	volu->partition_type = buffer[0x41 + r_size];
1081 	memcpy(volu->guid, buffer + 0x42 + r_size, sizeof(volu->guid));
1082 	if (buffer[0x12] & VBLK_FLAG_VOLU_DRIVE) {
1083 		ldm_get_vstr(buffer + 0x52 + r_size, volu->drive_hint,
1084 				sizeof(volu->drive_hint));
1085 	}
1086 	return true;
1087 }
1088 
1089 /**
1090  * ldm_parse_vblk - Read a raw VBLK object into a vblk structure
1091  * @buf:  Block of data being worked on
1092  * @len:  Size of the block of data
1093  * @vb:   In-memory vblk in which to return information
1094  *
1095  * Read a raw VBLK object into a vblk structure.  This function just reads the
1096  * information common to all VBLK types, then delegates the rest of the work to
1097  * helper functions: ldm_parse_*.
1098  *
1099  * Return:  'true'   @vb contains a VBLK
1100  *          'false'  @vb contents are not defined
1101  */
1102 static bool ldm_parse_vblk (const u8 *buf, int len, struct vblk *vb)
1103 {
1104 	bool result = false;
1105 	int r_objid;
1106 
1107 	BUG_ON (!buf || !vb);
1108 
1109 	r_objid = ldm_relative (buf, len, 0x18, 0);
1110 	if (r_objid < 0) {
1111 		ldm_error ("VBLK header is corrupt.");
1112 		return false;
1113 	}
1114 
1115 	vb->flags  = buf[0x12];
1116 	vb->type   = buf[0x13];
1117 	vb->obj_id = ldm_get_vnum (buf + 0x18);
1118 	ldm_get_vstr (buf+0x18+r_objid, vb->name, sizeof (vb->name));
1119 
1120 	switch (vb->type) {
1121 		case VBLK_CMP3:  result = ldm_parse_cmp3 (buf, len, vb); break;
1122 		case VBLK_DSK3:  result = ldm_parse_dsk3 (buf, len, vb); break;
1123 		case VBLK_DSK4:  result = ldm_parse_dsk4 (buf, len, vb); break;
1124 		case VBLK_DGR3:  result = ldm_parse_dgr3 (buf, len, vb); break;
1125 		case VBLK_DGR4:  result = ldm_parse_dgr4 (buf, len, vb); break;
1126 		case VBLK_PRT3:  result = ldm_parse_prt3 (buf, len, vb); break;
1127 		case VBLK_VOL5:  result = ldm_parse_vol5 (buf, len, vb); break;
1128 	}
1129 
1130 	if (result)
1131 		ldm_debug ("Parsed VBLK 0x%llx (type: 0x%02x) ok.",
1132 			 (unsigned long long) vb->obj_id, vb->type);
1133 	else
1134 		ldm_error ("Failed to parse VBLK 0x%llx (type: 0x%02x).",
1135 			(unsigned long long) vb->obj_id, vb->type);
1136 
1137 	return result;
1138 }
1139 
1140 
1141 /**
1142  * ldm_ldmdb_add - Adds a raw VBLK entry to the ldmdb database
1143  * @data:  Raw VBLK to add to the database
1144  * @len:   Size of the raw VBLK
1145  * @ldb:   Cache of the database structures
1146  *
1147  * The VBLKs are sorted into categories.  Partitions are also sorted by offset.
1148  *
1149  * N.B.  This function does not check the validity of the VBLKs.
1150  *
1151  * Return:  'true'   The VBLK was added
1152  *          'false'  An error occurred
1153  */
1154 static bool ldm_ldmdb_add (u8 *data, int len, struct ldmdb *ldb)
1155 {
1156 	struct vblk *vb;
1157 	struct list_head *item;
1158 
1159 	BUG_ON (!data || !ldb);
1160 
1161 	vb = kmalloc (sizeof (*vb), GFP_KERNEL);
1162 	if (!vb) {
1163 		ldm_crit ("Out of memory.");
1164 		return false;
1165 	}
1166 
1167 	if (!ldm_parse_vblk (data, len, vb)) {
1168 		kfree(vb);
1169 		return false;			/* Already logged */
1170 	}
1171 
1172 	/* Put vblk into the correct list. */
1173 	switch (vb->type) {
1174 	case VBLK_DGR3:
1175 	case VBLK_DGR4:
1176 		list_add (&vb->list, &ldb->v_dgrp);
1177 		break;
1178 	case VBLK_DSK3:
1179 	case VBLK_DSK4:
1180 		list_add (&vb->list, &ldb->v_disk);
1181 		break;
1182 	case VBLK_VOL5:
1183 		list_add (&vb->list, &ldb->v_volu);
1184 		break;
1185 	case VBLK_CMP3:
1186 		list_add (&vb->list, &ldb->v_comp);
1187 		break;
1188 	case VBLK_PRT3:
1189 		/* Sort by the partition's start sector. */
1190 		list_for_each (item, &ldb->v_part) {
1191 			struct vblk *v = list_entry (item, struct vblk, list);
1192 			if ((v->vblk.part.disk_id == vb->vblk.part.disk_id) &&
1193 			    (v->vblk.part.start > vb->vblk.part.start)) {
1194 				list_add_tail (&vb->list, &v->list);
1195 				return true;
1196 			}
1197 		}
1198 		list_add_tail (&vb->list, &ldb->v_part);
1199 		break;
1200 	}
1201 	return true;
1202 }
1203 
1204 /**
1205  * ldm_frag_add - Add a VBLK fragment to a list
1206  * @data:   Raw fragment to be added to the list
1207  * @size:   Size of the raw fragment
1208  * @frags:  Linked list of VBLK fragments
1209  *
1210  * Fragmented VBLKs may not be consecutive in the database, so they are placed
1211  * in a list so they can be pieced together later.
1212  *
1213  * Return:  'true'   Success, the VBLK was added to the list
1214  *          'false'  Error, a problem occurred
1215  */
1216 static bool ldm_frag_add (const u8 *data, int size, struct list_head *frags)
1217 {
1218 	struct frag *f;
1219 	struct list_head *item;
1220 	int rec, num, group;
1221 
1222 	BUG_ON (!data || !frags);
1223 
1224 	if (size < 2 * VBLK_SIZE_HEAD) {
1225 		ldm_error("Value of size is too small.");
1226 		return false;
1227 	}
1228 
1229 	group = get_unaligned_be32(data + 0x08);
1230 	rec   = get_unaligned_be16(data + 0x0C);
1231 	num   = get_unaligned_be16(data + 0x0E);
1232 	if ((num < 1) || (num > 4)) {
1233 		ldm_error ("A VBLK claims to have %d parts.", num);
1234 		return false;
1235 	}
1236 	if (rec >= num) {
1237 		ldm_error("REC value (%d) exceeds NUM value (%d)", rec, num);
1238 		return false;
1239 	}
1240 
1241 	list_for_each (item, frags) {
1242 		f = list_entry (item, struct frag, list);
1243 		if (f->group == group)
1244 			goto found;
1245 	}
1246 
1247 	f = kmalloc (sizeof (*f) + size*num, GFP_KERNEL);
1248 	if (!f) {
1249 		ldm_crit ("Out of memory.");
1250 		return false;
1251 	}
1252 
1253 	f->group = group;
1254 	f->num   = num;
1255 	f->rec   = rec;
1256 	f->map   = 0xFF << num;
1257 
1258 	list_add_tail (&f->list, frags);
1259 found:
1260 	if (rec >= f->num) {
1261 		ldm_error("REC value (%d) exceeds NUM value (%d)", rec, f->num);
1262 		return false;
1263 	}
1264 	if (f->map & (1 << rec)) {
1265 		ldm_error ("Duplicate VBLK, part %d.", rec);
1266 		f->map &= 0x7F;			/* Mark the group as broken */
1267 		return false;
1268 	}
1269 	f->map |= (1 << rec);
1270 	if (!rec)
1271 		memcpy(f->data, data, VBLK_SIZE_HEAD);
1272 	data += VBLK_SIZE_HEAD;
1273 	size -= VBLK_SIZE_HEAD;
1274 	memcpy(f->data + VBLK_SIZE_HEAD + rec * size, data, size);
1275 	return true;
1276 }
1277 
1278 /**
1279  * ldm_frag_free - Free a linked list of VBLK fragments
1280  * @list:  Linked list of fragments
1281  *
1282  * Free a linked list of VBLK fragments
1283  *
1284  * Return:  none
1285  */
1286 static void ldm_frag_free (struct list_head *list)
1287 {
1288 	struct list_head *item, *tmp;
1289 
1290 	BUG_ON (!list);
1291 
1292 	list_for_each_safe (item, tmp, list)
1293 		kfree (list_entry (item, struct frag, list));
1294 }
1295 
1296 /**
1297  * ldm_frag_commit - Validate fragmented VBLKs and add them to the database
1298  * @frags:  Linked list of VBLK fragments
1299  * @ldb:    Cache of the database structures
1300  *
1301  * Now that all the fragmented VBLKs have been collected, they must be added to
1302  * the database for later use.
1303  *
1304  * Return:  'true'   All the fragments we added successfully
1305  *          'false'  One or more of the fragments we invalid
1306  */
1307 static bool ldm_frag_commit (struct list_head *frags, struct ldmdb *ldb)
1308 {
1309 	struct frag *f;
1310 	struct list_head *item;
1311 
1312 	BUG_ON (!frags || !ldb);
1313 
1314 	list_for_each (item, frags) {
1315 		f = list_entry (item, struct frag, list);
1316 
1317 		if (f->map != 0xFF) {
1318 			ldm_error ("VBLK group %d is incomplete (0x%02x).",
1319 				f->group, f->map);
1320 			return false;
1321 		}
1322 
1323 		if (!ldm_ldmdb_add (f->data, f->num*ldb->vm.vblk_size, ldb))
1324 			return false;		/* Already logged */
1325 	}
1326 	return true;
1327 }
1328 
1329 /**
1330  * ldm_get_vblks - Read the on-disk database of VBLKs into memory
1331  * @state: Partition check state including device holding the LDM Database
1332  * @base:  Offset, into @state->disk, of the database
1333  * @ldb:   Cache of the database structures
1334  *
1335  * To use the information from the VBLKs, they need to be read from the disk,
1336  * unpacked and validated.  We cache them in @ldb according to their type.
1337  *
1338  * Return:  'true'   All the VBLKs were read successfully
1339  *          'false'  An error occurred
1340  */
1341 static bool ldm_get_vblks(struct parsed_partitions *state, unsigned long base,
1342 			  struct ldmdb *ldb)
1343 {
1344 	int size, perbuf, skip, finish, s, v, recs;
1345 	u8 *data = NULL;
1346 	Sector sect;
1347 	bool result = false;
1348 	LIST_HEAD (frags);
1349 
1350 	BUG_ON(!state || !ldb);
1351 
1352 	size   = ldb->vm.vblk_size;
1353 	perbuf = 512 / size;
1354 	skip   = ldb->vm.vblk_offset >> 9;		/* Bytes to sectors */
1355 	finish = (size * ldb->vm.last_vblk_seq) >> 9;
1356 
1357 	for (s = skip; s < finish; s++) {		/* For each sector */
1358 		data = read_part_sector(state, base + OFF_VMDB + s, &sect);
1359 		if (!data) {
1360 			ldm_crit ("Disk read failed.");
1361 			goto out;
1362 		}
1363 
1364 		for (v = 0; v < perbuf; v++, data+=size) {  /* For each vblk */
1365 			if (MAGIC_VBLK != get_unaligned_be32(data)) {
1366 				ldm_error ("Expected to find a VBLK.");
1367 				goto out;
1368 			}
1369 
1370 			recs = get_unaligned_be16(data + 0x0E);	/* Number of records */
1371 			if (recs == 1) {
1372 				if (!ldm_ldmdb_add (data, size, ldb))
1373 					goto out;	/* Already logged */
1374 			} else if (recs > 1) {
1375 				if (!ldm_frag_add (data, size, &frags))
1376 					goto out;	/* Already logged */
1377 			}
1378 			/* else Record is not in use, ignore it. */
1379 		}
1380 		put_dev_sector (sect);
1381 		data = NULL;
1382 	}
1383 
1384 	result = ldm_frag_commit (&frags, ldb);	/* Failures, already logged */
1385 out:
1386 	if (data)
1387 		put_dev_sector (sect);
1388 	ldm_frag_free (&frags);
1389 
1390 	return result;
1391 }
1392 
1393 /**
1394  * ldm_free_vblks - Free a linked list of vblk's
1395  * @lh:  Head of a linked list of struct vblk
1396  *
1397  * Free a list of vblk's and free the memory used to maintain the list.
1398  *
1399  * Return:  none
1400  */
1401 static void ldm_free_vblks (struct list_head *lh)
1402 {
1403 	struct list_head *item, *tmp;
1404 
1405 	BUG_ON (!lh);
1406 
1407 	list_for_each_safe (item, tmp, lh)
1408 		kfree (list_entry (item, struct vblk, list));
1409 }
1410 
1411 
1412 /**
1413  * ldm_partition - Find out whether a device is a dynamic disk and handle it
1414  * @state: Partition check state including device holding the LDM Database
1415  *
1416  * This determines whether the device @bdev is a dynamic disk and if so creates
1417  * the partitions necessary in the gendisk structure pointed to by @hd.
1418  *
1419  * We create a dummy device 1, which contains the LDM database, and then create
1420  * each partition described by the LDM database in sequence as devices 2+. For
1421  * example, if the device is hda, we would have: hda1: LDM database, hda2, hda3,
1422  * and so on: the actual data containing partitions.
1423  *
1424  * Return:  1 Success, @state->disk is a dynamic disk and we handled it
1425  *          0 Success, @state->disk is not a dynamic disk
1426  *         -1 An error occurred before enough information had been read
1427  *            Or @state->disk is a dynamic disk, but it may be corrupted
1428  */
1429 int ldm_partition(struct parsed_partitions *state)
1430 {
1431 	struct ldmdb  *ldb;
1432 	unsigned long base;
1433 	int result = -1;
1434 
1435 	BUG_ON(!state);
1436 
1437 	/* Look for signs of a Dynamic Disk */
1438 	if (!ldm_validate_partition_table(state))
1439 		return 0;
1440 
1441 	ldb = kmalloc (sizeof (*ldb), GFP_KERNEL);
1442 	if (!ldb) {
1443 		ldm_crit ("Out of memory.");
1444 		goto out;
1445 	}
1446 
1447 	/* Parse and check privheads. */
1448 	if (!ldm_validate_privheads(state, &ldb->ph))
1449 		goto out;		/* Already logged */
1450 
1451 	/* All further references are relative to base (database start). */
1452 	base = ldb->ph.config_start;
1453 
1454 	/* Parse and check tocs and vmdb. */
1455 	if (!ldm_validate_tocblocks(state, base, ldb) ||
1456 	    !ldm_validate_vmdb(state, base, ldb))
1457 	    	goto out;		/* Already logged */
1458 
1459 	/* Initialize vblk lists in ldmdb struct */
1460 	INIT_LIST_HEAD (&ldb->v_dgrp);
1461 	INIT_LIST_HEAD (&ldb->v_disk);
1462 	INIT_LIST_HEAD (&ldb->v_volu);
1463 	INIT_LIST_HEAD (&ldb->v_comp);
1464 	INIT_LIST_HEAD (&ldb->v_part);
1465 
1466 	if (!ldm_get_vblks(state, base, ldb)) {
1467 		ldm_crit ("Failed to read the VBLKs from the database.");
1468 		goto cleanup;
1469 	}
1470 
1471 	/* Finally, create the data partition devices. */
1472 	if (ldm_create_data_partitions(state, ldb)) {
1473 		ldm_debug ("Parsed LDM database successfully.");
1474 		result = 1;
1475 	}
1476 	/* else Already logged */
1477 
1478 cleanup:
1479 	ldm_free_vblks (&ldb->v_dgrp);
1480 	ldm_free_vblks (&ldb->v_disk);
1481 	ldm_free_vblks (&ldb->v_volu);
1482 	ldm_free_vblks (&ldb->v_comp);
1483 	ldm_free_vblks (&ldb->v_part);
1484 out:
1485 	kfree (ldb);
1486 	return result;
1487 }
1488