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