[kpartx] shut a build warning
[platform/upstream/multipath-tools.git] / kpartx / gpt.c.orig
1 /*
2     gpt.[ch]
3
4     Copyright (C) 2000-2001 Dell Computer Corporation <Matt_Domsch@dell.com> 
5
6     EFI GUID Partition Table handling
7     Per Intel EFI Specification v1.02
8     http://developer.intel.com/technology/efi/efi.htm
9
10     This program is free software; you can redistribute it and/or modify
11     it under the terms of the GNU General Public License as published by
12     the Free Software Foundation; either version 2 of the License, or
13     (at your option) any later version.
14
15     This program is distributed in the hope that it will be useful,
16     but WITHOUT ANY WARRANTY; without even the implied warranty of
17     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18     GNU General Public License for more details.
19
20     You should have received a copy of the GNU General Public License
21     along with this program; if not, write to the Free Software
22     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23 */
24
25 #define _FILE_OFFSET_BITS 64
26
27 #include "gpt.h"
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <inttypes.h>
32 #include <sys/stat.h>
33 #include <sys/ioctl.h>
34 #include <fcntl.h>
35 #include <unistd.h>
36 #include <errno.h>
37 #include <asm/byteorder.h>
38 #include "crc32.h"
39
40 #define BLKGETLASTSECT  _IO(0x12,108)   /* get last sector of block device */
41 #define BLKGETSIZE _IO(0x12,96)         /* return device size */
42 #define BLKSSZGET  _IO(0x12,104)        /* get block device sector size */
43 #define BLKGETSIZE64 _IOR(0x12,114,sizeof(uint64_t))    /* return device size in bytes (u64 *arg) */
44
45 struct blkdev_ioctl_param {
46         unsigned int block;
47         size_t content_length;
48         char * block_contents;
49 };
50
51 /**
52  * efi_crc32() - EFI version of crc32 function
53  * @buf: buffer to calculate crc32 of
54  * @len - length of buf
55  *
56  * Description: Returns EFI-style CRC32 value for @buf
57  * 
58  * This function uses the little endian Ethernet polynomial
59  * but seeds the function with ~0, and xor's with ~0 at the end.
60  * Note, the EFI Specification, v1.02, has a reference to
61  * Dr. Dobbs Journal, May 1994 (actually it's in May 1992).
62  */
63 static inline uint32_t
64 efi_crc32(const void *buf, unsigned long len)
65 {
66         return (crc32(~0L, buf, len) ^ ~0L);
67 }
68
69 /**
70  * is_pmbr_valid(): test Protective MBR for validity
71  * @mbr: pointer to a legacy mbr structure
72  *
73  * Description: Returns 1 if PMBR is valid, 0 otherwise.
74  * Validity depends on two things:
75  *  1) MSDOS signature is in the last two bytes of the MBR
76  *  2) One partition of type 0xEE is found
77  */
78 static int
79 is_pmbr_valid(legacy_mbr *mbr)
80 {
81         int i, found = 0, signature = 0;
82         if (!mbr)
83                 return 0;
84         signature = (__le16_to_cpu(mbr->signature) == MSDOS_MBR_SIGNATURE);
85         for (i = 0; signature && i < 4; i++) {
86                 if (mbr->partition[i].sys_type ==
87                     EFI_PMBR_OSTYPE_EFI_GPT) {
88                         found = 1;
89                         break;
90                 }
91         }
92         return (signature && found);
93 }
94
95
96 /************************************************************
97  * get_sector_size
98  * Requires:
99  *  - filedes is an open file descriptor, suitable for reading
100  * Modifies: nothing
101  * Returns:
102  *  sector size, or 512.
103  ************************************************************/
104 static int
105 get_sector_size(int filedes)
106 {
107         int rc, sector_size = 512;
108
109         rc = ioctl(filedes, BLKSSZGET, &sector_size);
110         if (rc)
111                 sector_size = 512;
112         return sector_size;
113 }
114
115 /************************************************************
116  * _get_num_sectors
117  * Requires:
118  *  - filedes is an open file descriptor, suitable for reading
119  * Modifies: nothing
120  * Returns:
121  *  Last LBA value on success 
122  *  0 on error
123  *
124  * Try getting BLKGETSIZE64 and BLKSSZGET first,
125  * then BLKGETSIZE if necessary.
126  *  Kernels 2.4.15-2.4.18 and 2.5.0-2.5.3 have a broken BLKGETSIZE64
127  *  which returns the number of 512-byte sectors, not the size of
128  *  the disk in bytes. Fixed in kernels 2.4.18-pre8 and 2.5.4-pre3.
129  ************************************************************/
130 static uint64_t
131 _get_num_sectors(int filedes)
132 {
133         unsigned long sectors=0;
134         int rc;
135 #if 0
136         uint64_t bytes=0;
137
138         rc = ioctl(filedes, BLKGETSIZE64, &bytes);
139         if (!rc)
140                 return bytes / get_sector_size(filedes);
141 #endif
142         rc = ioctl(filedes, BLKGETSIZE, &sectors);
143         if (rc)
144                 return 0;
145         
146         return sectors;
147 }
148
149 /************************************************************
150  * last_lba(): return number of last logical block of device
151  * 
152  * @fd
153  * 
154  * Description: returns Last LBA value on success, 0 on error.
155  * Notes: The value st_blocks gives the size of the file
156  *        in 512-byte blocks, which is OK if
157  *        EFI_BLOCK_SIZE_SHIFT == 9.
158  ************************************************************/
159
160 static uint64_t
161 last_lba(int filedes)
162 {
163         int rc;
164         uint64_t sectors = 0;
165         struct stat s;
166         memset(&s, 0, sizeof (s));
167         rc = fstat(filedes, &s);
168         if (rc == -1) {
169                 fprintf(stderr, "last_lba() could not stat: %s\n",
170                         strerror(errno));
171                 return 0;
172         }
173
174         if (S_ISBLK(s.st_mode)) {
175                 sectors = _get_num_sectors(filedes);
176         } else {
177                 fprintf(stderr,
178                         "last_lba(): I don't know how to handle files with mode %x\n",
179                         s.st_mode);
180                 sectors = 1;
181         }
182
183         return sectors - 1;
184 }
185
186
187 static ssize_t
188 read_lastoddsector(int fd, uint64_t lba, void *buffer, size_t count)
189 {
190         int rc;
191         struct blkdev_ioctl_param ioctl_param;
192
193         if (!buffer) return 0; 
194
195         ioctl_param.block = 0; /* read the last sector */
196         ioctl_param.content_length = count;
197         ioctl_param.block_contents = buffer;
198
199         rc = ioctl(fd, BLKGETLASTSECT, &ioctl_param);
200         if (rc == -1) perror("read failed");
201
202         return !rc;
203 }
204
205 static ssize_t
206 read_lba(int fd, uint64_t lba, void *buffer, size_t bytes)
207 {
208         int sector_size = get_sector_size(fd);
209         off_t offset = lba * sector_size;
210         ssize_t bytesread;
211
212         lseek(fd, offset, SEEK_SET);
213         bytesread = read(fd, buffer, bytes);
214
215         /* Kludge.  This is necessary to read/write the last
216            block of an odd-sized disk, until Linux 2.5.x kernel fixes.
217            This is only used by gpt.c, and only to read
218            one sector, so we don't have to be fancy.
219         */
220         if (!bytesread && !(last_lba(fd) & 1) && lba == last_lba(fd)) {
221                 bytesread = read_lastoddsector(fd, lba, buffer, bytes);
222         }
223         return bytesread;
224 }
225
226 /**
227  * alloc_read_gpt_entries(): reads partition entries from disk
228  * @fd  is an open file descriptor to the whole disk
229  * @gpt is a buffer into which the GPT will be put  
230  * Description: Returns ptes on success,  NULL on error.
231  * Allocates space for PTEs based on information found in @gpt.
232  * Notes: remember to free pte when you're done!
233  */
234 static gpt_entry *
235 alloc_read_gpt_entries(int fd, gpt_header * gpt)
236 {
237         gpt_entry *pte;
238         size_t count = __le32_to_cpu(gpt->num_partition_entries) *
239                 __le32_to_cpu(gpt->sizeof_partition_entry);
240
241         if (!count) return NULL;
242
243         pte = (gpt_entry *)malloc(count);
244         if (!pte)
245                 return NULL;
246         memset(pte, 0, count);
247
248         if (!read_lba(fd, __le64_to_cpu(gpt->partition_entry_lba), pte,
249                       count)) {
250                 free(pte);
251                 return NULL;
252         }
253         return pte;
254 }
255
256 /**
257  * alloc_read_gpt_header(): Allocates GPT header, reads into it from disk
258  * @fd  is an open file descriptor to the whole disk
259  * @lba is the Logical Block Address of the partition table
260  * 
261  * Description: returns GPT header on success, NULL on error.   Allocates
262  * and fills a GPT header starting at @ from @bdev.
263  * Note: remember to free gpt when finished with it.
264  */
265 static gpt_header *
266 alloc_read_gpt_header(int fd, uint64_t lba)
267 {
268         gpt_header *gpt;
269         gpt = (gpt_header *)
270             malloc(sizeof (gpt_header));
271         if (!gpt)
272                 return NULL;
273         memset(gpt, 0, sizeof (*gpt));
274         if (!read_lba(fd, lba, gpt, sizeof (gpt_header))) {
275                 free(gpt);
276                 return NULL;
277         }
278
279         return gpt;
280 }
281
282 /**
283  * is_gpt_valid() - tests one GPT header and PTEs for validity
284  * @fd  is an open file descriptor to the whole disk
285  * @lba is the logical block address of the GPT header to test
286  * @gpt is a GPT header ptr, filled on return.
287  * @ptes is a PTEs ptr, filled on return.
288  *
289  * Description: returns 1 if valid,  0 on error.
290  * If valid, returns pointers to newly allocated GPT header and PTEs.
291  */
292 static int
293 is_gpt_valid(int fd, uint64_t lba,
294              gpt_header ** gpt, gpt_entry ** ptes)
295 {
296         int rc = 0;             /* default to not valid */
297         uint32_t crc, origcrc;
298
299         if (!gpt || !ptes)
300                 return 0;
301         if (!(*gpt = alloc_read_gpt_header(fd, lba)))
302                 return 0;
303
304         /* Check the GUID Partition Table signature */
305         if (__le64_to_cpu((*gpt)->signature) != GPT_HEADER_SIGNATURE) {
306                 /* 
307                    printf("GUID Partition Table Header signature is wrong: %" PRIx64" != %" PRIx64 "\n",
308                    __le64_to_cpu((*gpt)->signature), GUID_PT_HEADER_SIGNATURE);
309                  */
310                 free(*gpt);
311                 *gpt = NULL;
312                 return rc;
313         }
314
315         /* Check the GUID Partition Table Header CRC */
316         origcrc = __le32_to_cpu((*gpt)->header_crc32);
317         (*gpt)->header_crc32 = 0;
318         crc = efi_crc32(*gpt, __le32_to_cpu((*gpt)->header_size));
319         if (crc != origcrc) {
320                 // printf( "GPTH CRC check failed, %x != %x.\n", origcrc, crc);
321                 (*gpt)->header_crc32 = __cpu_to_le32(origcrc);
322                 free(*gpt);
323                 *gpt = NULL;
324                 return 0;
325         }
326         (*gpt)->header_crc32 = __cpu_to_le32(origcrc);
327
328         /* Check that the my_lba entry points to the LBA
329          * that contains the GPT we read */
330         if (__le64_to_cpu((*gpt)->my_lba) != lba) {
331                 /*
332                 printf( "my_lba % PRIx64 "x != lba %"PRIx64 "x.\n",
333                                 __le64_to_cpu((*gpt)->my_lba), lba);
334                  */
335                 free(*gpt);
336                 *gpt = NULL;
337                 return 0;
338         }
339
340         if (!(*ptes = alloc_read_gpt_entries(fd, *gpt))) {
341                 free(*gpt);
342                 *gpt = NULL;
343                 return 0;
344         }
345
346         /* Check the GUID Partition Entry Array CRC */
347         crc = efi_crc32(*ptes,
348                         __le32_to_cpu((*gpt)->num_partition_entries) *
349                         __le32_to_cpu((*gpt)->sizeof_partition_entry));
350         if (crc != __le32_to_cpu((*gpt)->partition_entry_array_crc32)) {
351                 // printf("GUID Partitition Entry Array CRC check failed.\n");
352                 free(*gpt);
353                 *gpt = NULL;
354                 free(*ptes);
355                 *ptes = NULL;
356                 return 0;
357         }
358
359         /* We're done, all's well */
360         return 1;
361 }
362 /**
363  * compare_gpts() - Search disk for valid GPT headers and PTEs
364  * @pgpt is the primary GPT header
365  * @agpt is the alternate GPT header
366  * @lastlba is the last LBA number
367  * Description: Returns nothing.  Sanity checks pgpt and agpt fields
368  * and prints warnings on discrepancies.
369  * 
370  */
371 static void
372 compare_gpts(gpt_header *pgpt, gpt_header *agpt, uint64_t lastlba)
373 {
374         int error_found = 0;
375         if (!pgpt || !agpt)
376                 return;
377         if (__le64_to_cpu(pgpt->my_lba) != __le64_to_cpu(agpt->alternate_lba)) {
378                 error_found++;
379                 fprintf(stderr, 
380                        "GPT:Primary header LBA != Alt. header alternate_lba\n");
381 #ifdef DEBUG
382                 fprintf(stderr,  "GPT:%" PRIx64 " != %" PRIx64 "\n",
383                        __le64_to_cpu(pgpt->my_lba),
384                        __le64_to_cpu(agpt->alternate_lba));
385 #endif
386         }
387         if (__le64_to_cpu(pgpt->alternate_lba) != __le64_to_cpu(agpt->my_lba)) {
388                 error_found++;
389                 fprintf(stderr, 
390                        "GPT:Primary header alternate_lba != Alt. header my_lba\n");
391 #ifdef DEBUG
392                 fprintf(stderr,  "GPT:%" PRIx64 " != %" PRIx64 "\n",
393                        __le64_to_cpu(pgpt->alternate_lba),
394                        __le64_to_cpu(agpt->my_lba));
395 #endif
396         }
397         if (__le64_to_cpu(pgpt->first_usable_lba) !=
398             __le64_to_cpu(agpt->first_usable_lba)) {
399                 error_found++;
400                 fprintf(stderr,  "GPT:first_usable_lbas don't match.\n");
401 #ifdef DEBUG
402                 fprintf(stderr,  "GPT:%" PRIx64 " != %" PRIx64 "\n",
403                        __le64_to_cpu(pgpt->first_usable_lba),
404                        __le64_to_cpu(agpt->first_usable_lba));
405 #endif
406         }
407         if (__le64_to_cpu(pgpt->last_usable_lba) !=
408             __le64_to_cpu(agpt->last_usable_lba)) {
409                 error_found++;
410                 fprintf(stderr,  "GPT:last_usable_lbas don't match.\n");
411 #ifdef DEBUG
412                 fprintf(stderr,  "GPT:%" PRIx64 " != %" PRIx64 "\n",
413                        __le64_to_cpu(pgpt->last_usable_lba),
414                        __le64_to_cpu(agpt->last_usable_lba));
415 #endif
416         }
417         if (efi_guidcmp(pgpt->disk_guid, agpt->disk_guid)) {
418                 error_found++;
419                 fprintf(stderr,  "GPT:disk_guids don't match.\n");
420         }
421         if (__le32_to_cpu(pgpt->num_partition_entries) !=
422             __le32_to_cpu(agpt->num_partition_entries)) {
423                 error_found++;
424                 fprintf(stderr,  "GPT:num_partition_entries don't match: "
425                        "0x%x != 0x%x\n",
426                        __le32_to_cpu(pgpt->num_partition_entries),
427                        __le32_to_cpu(agpt->num_partition_entries));
428         }
429         if (__le32_to_cpu(pgpt->sizeof_partition_entry) !=
430             __le32_to_cpu(agpt->sizeof_partition_entry)) {
431                 error_found++;
432                 fprintf(stderr, 
433                        "GPT:sizeof_partition_entry values don't match: "
434                        "0x%x != 0x%x\n",
435                        __le32_to_cpu(pgpt->sizeof_partition_entry),
436                        __le32_to_cpu(agpt->sizeof_partition_entry));
437         }
438         if (__le32_to_cpu(pgpt->partition_entry_array_crc32) !=
439             __le32_to_cpu(agpt->partition_entry_array_crc32)) {
440                 error_found++;
441                 fprintf(stderr, 
442                        "GPT:partition_entry_array_crc32 values don't match: "
443                        "0x%x != 0x%x\n",
444                        __le32_to_cpu(pgpt->partition_entry_array_crc32),
445                        __le32_to_cpu(agpt->partition_entry_array_crc32));
446         }
447         if (__le64_to_cpu(pgpt->alternate_lba) != lastlba) {
448                 error_found++;
449                 fprintf(stderr, 
450                        "GPT:Primary header thinks Alt. header is not at the end of the disk.\n");
451 #ifdef DEBUG
452                 fprintf(stderr,  "GPT:%" PRIx64 " != %" PRIx64 "\n",
453                        __le64_to_cpu(pgpt->alternate_lba), lastlba);
454 #endif
455         }
456
457         if (__le64_to_cpu(agpt->my_lba) != lastlba) {
458                 error_found++;
459                 fprintf(stderr, 
460                        "GPT:Alternate GPT header not at the end of the disk.\n");
461 #ifdef DEBUG
462                 fprintf(stderr,  "GPT:%" PRIx64 " != %" PRIx64 "\n",
463                        __le64_to_cpu(agpt->my_lba), lastlba);
464 #endif
465         }
466
467         if (error_found)
468                 fprintf(stderr, 
469                        "GPT: Use GNU Parted to correct GPT errors.\n");
470         return;
471 }
472
473 /**
474  * find_valid_gpt() - Search disk for valid GPT headers and PTEs
475  * @fd  is an open file descriptor to the whole disk
476  * @gpt is a GPT header ptr, filled on return.
477  * @ptes is a PTEs ptr, filled on return.
478  * Description: Returns 1 if valid, 0 on error.
479  * If valid, returns pointers to newly allocated GPT header and PTEs.
480  * Validity depends on finding either the Primary GPT header and PTEs valid,
481  * or the Alternate GPT header and PTEs valid, and the PMBR valid.
482  */
483 static int
484 find_valid_gpt(int fd, gpt_header ** gpt, gpt_entry ** ptes)
485 {
486         extern int force_gpt;
487         int good_pgpt = 0, good_agpt = 0, good_pmbr = 0;
488         gpt_header *pgpt = NULL, *agpt = NULL;
489         gpt_entry *pptes = NULL, *aptes = NULL;
490         legacy_mbr *legacymbr = NULL;
491         uint64_t lastlba;
492         if (!gpt || !ptes)
493                 return 0;
494
495         lastlba = last_lba(fd);
496         good_pgpt = is_gpt_valid(fd, GPT_PRIMARY_PARTITION_TABLE_LBA,
497                                  &pgpt, &pptes);
498         if (good_pgpt) {
499                 good_agpt = is_gpt_valid(fd,
500                                          __le64_to_cpu(pgpt->alternate_lba),
501                                          &agpt, &aptes);
502                 if (!good_agpt) {
503                         good_agpt = is_gpt_valid(fd, lastlba,
504                                                  &agpt, &aptes);
505                 }
506         }
507         else {
508                 good_agpt = is_gpt_valid(fd, lastlba,
509                                          &agpt, &aptes);
510         }
511
512         /* The obviously unsuccessful case */
513         if (!good_pgpt && !good_agpt) {
514                 goto fail;
515         }
516
517         /* This will be added to the EFI Spec. per Intel after v1.02. */
518         legacymbr = malloc(sizeof (*legacymbr));
519         if (legacymbr) {
520                 memset(legacymbr, 0, sizeof (*legacymbr));
521                 read_lba(fd, 0, (uint8_t *) legacymbr,
522                          sizeof (*legacymbr));
523                 good_pmbr = is_pmbr_valid(legacymbr);
524                 free(legacymbr);
525                 legacymbr=NULL;
526         }
527
528         /* Failure due to bad PMBR */
529         if ((good_pgpt || good_agpt) && !good_pmbr && !force_gpt) {
530                 fprintf(stderr,
531                        "  Warning: Disk has a valid GPT signature "
532                        "but invalid PMBR.\n"
533                        "  Assuming this disk is *not* a GPT disk anymore.\n"
534                        "  Use gpt kernel option to override.  "
535                        "Use GNU Parted to correct disk.\n");
536                 goto fail;
537         }
538
539         /* Would fail due to bad PMBR, but force GPT anyhow */
540         if ((good_pgpt || good_agpt) && !good_pmbr && force_gpt) {
541                 fprintf(stderr, 
542                        "  Warning: Disk has a valid GPT signature but "
543                        "invalid PMBR.\n"
544                        "  Use GNU Parted to correct disk.\n"
545                        "  gpt option taken, disk treated as GPT.\n");
546         }
547
548         compare_gpts(pgpt, agpt, lastlba);
549
550         /* The good cases */
551         if (good_pgpt && (good_pmbr || force_gpt)) {
552                 *gpt  = pgpt;
553                 *ptes = pptes;
554                 if (agpt)  { free(agpt);   agpt = NULL; }
555                 if (aptes) { free(aptes); aptes = NULL; }
556                 if (!good_agpt) {
557                         fprintf(stderr, 
558                                "Alternate GPT is invalid, "
559                                "using primary GPT.\n");
560                 }
561                 return 1;
562         }
563         else if (good_agpt && (good_pmbr || force_gpt)) {
564                 *gpt  = agpt;
565                 *ptes = aptes;
566                 if (pgpt)  { free(pgpt);   pgpt = NULL; }
567                 if (pptes) { free(pptes); pptes = NULL; }
568                 fprintf(stderr, 
569                        "Primary GPT is invalid, using alternate GPT.\n");
570                 return 1;
571         }
572
573  fail:
574         if (pgpt)  { free(pgpt);   pgpt=NULL; }
575         if (agpt)  { free(agpt);   agpt=NULL; }
576         if (pptes) { free(pptes); pptes=NULL; }
577         if (aptes) { free(aptes); aptes=NULL; }
578         *gpt = NULL;
579         *ptes = NULL;
580         return 0;
581 }
582
583 /**
584  * read_gpt_pt() 
585  * @fd
586  * @all - slice with start/size of whole disk
587  *
588  *  0 if this isn't our partition table
589  *  number of partitions if successful
590  *
591  */
592 int
593 read_gpt_pt (int fd, struct slice all, struct slice *sp, int ns)
594 {
595         gpt_header *gpt = NULL;
596         gpt_entry *ptes = NULL;
597         uint32_t i;
598         int n = 0;
599         int last_used_index=-1;
600
601         if (!find_valid_gpt (fd, &gpt, &ptes) || !gpt || !ptes) {
602                 if (gpt)
603                         free (gpt);
604                 if (ptes)
605                         free (ptes);
606                 return 0;
607         }
608
609         for (i = 0; i < __le32_to_cpu(gpt->num_partition_entries) && i < ns; i++) {
610                 if (!efi_guidcmp (NULL_GUID, ptes[i].partition_type_guid)) {
611                         sp[n].start = 0;
612                         sp[n].size = 0;
613                         n++;
614                 } else {
615                         sp[n].start = __le64_to_cpu(ptes[i].starting_lba);
616                         sp[n].size  = __le64_to_cpu(ptes[i].ending_lba) -
617                                 __le64_to_cpu(ptes[i].starting_lba) + 1;
618                         last_used_index=n;
619                         n++;
620                 }
621         }
622         free (ptes);
623         free (gpt);
624         return last_used_index+1;
625 }