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