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