• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /************************************************************
3  * EFI GUID Partition Table handling
4  *
5  * http://www.uefi.org/specs/
6  * http://www.intel.com/technology/efi/
7  *
8  * efi.[ch] by Matt Domsch <Matt_Domsch@dell.com>
9  *   Copyright 2000,2001,2002,2004 Dell Inc.
10  *
11  * TODO:
12  *
13  * Changelog:
14  * Mon August 5th, 2013 Davidlohr Bueso <davidlohr@hp.com>
15  * - detect hybrid MBRs, tighter pMBR checking & cleanups.
16  *
17  * Mon Nov 09 2004 Matt Domsch <Matt_Domsch@dell.com>
18  * - test for valid PMBR and valid PGPT before ever reading
19  *   AGPT, allow override with 'gpt' kernel command line option.
20  * - check for first/last_usable_lba outside of size of disk
21  *
22  * Tue  Mar 26 2002 Matt Domsch <Matt_Domsch@dell.com>
23  * - Ported to 2.5.7-pre1 and 2.5.7-dj2
24  * - Applied patch to avoid fault in alternate header handling
25  * - cleaned up find_valid_gpt
26  * - On-disk structure and copy in memory is *always* LE now -
27  *   swab fields as needed
28  * - remove print_gpt_header()
29  * - only use first max_p partition entries, to keep the kernel minor number
30  *   and partition numbers tied.
31  *
32  * Mon  Feb 04 2002 Matt Domsch <Matt_Domsch@dell.com>
33  * - Removed __PRIPTR_PREFIX - not being used
34  *
35  * Mon  Jan 14 2002 Matt Domsch <Matt_Domsch@dell.com>
36  * - Ported to 2.5.2-pre11 + library crc32 patch Linus applied
37  *
38  * Thu Dec 6 2001 Matt Domsch <Matt_Domsch@dell.com>
39  * - Added compare_gpts().
40  * - moved le_efi_guid_to_cpus() back into this file.  GPT is the only
41  *   thing that keeps EFI GUIDs on disk.
42  * - Changed gpt structure names and members to be simpler and more Linux-like.
43  *
44  * Wed Oct 17 2001 Matt Domsch <Matt_Domsch@dell.com>
45  * - Removed CONFIG_DEVFS_VOLUMES_UUID code entirely per Martin Wilck
46  *
47  * Wed Oct 10 2001 Matt Domsch <Matt_Domsch@dell.com>
48  * - Changed function comments to DocBook style per Andreas Dilger suggestion.
49  *
50  * Mon Oct 08 2001 Matt Domsch <Matt_Domsch@dell.com>
51  * - Change read_lba() to use the page cache per Al Viro's work.
52  * - print u64s properly on all architectures
53  * - fixed debug_printk(), now Dprintk()
54  *
55  * Mon Oct 01 2001 Matt Domsch <Matt_Domsch@dell.com>
56  * - Style cleanups
57  * - made most functions static
58  * - Endianness addition
59  * - remove test for second alternate header, as it's not per spec,
60  *   and is unnecessary.  There's now a method to read/write the last
61  *   sector of an odd-sized disk from user space.  No tools have ever
62  *   been released which used this code, so it's effectively dead.
63  * - Per Asit Mallick of Intel, added a test for a valid PMBR.
64  * - Added kernel command line option 'gpt' to override valid PMBR test.
65  *
66  * Wed Jun  6 2001 Martin Wilck <Martin.Wilck@Fujitsu-Siemens.com>
67  * - added devfs volume UUID support (/dev/volumes/uuids) for
68  *   mounting file systems by the partition GUID.
69  *
70  * Tue Dec  5 2000 Matt Domsch <Matt_Domsch@dell.com>
71  * - Moved crc32() to linux/lib, added efi_crc32().
72  *
73  * Thu Nov 30 2000 Matt Domsch <Matt_Domsch@dell.com>
74  * - Replaced Intel's CRC32 function with an equivalent
75  *   non-license-restricted version.
76  *
77  * Wed Oct 25 2000 Matt Domsch <Matt_Domsch@dell.com>
78  * - Fixed the last_lba() call to return the proper last block
79  *
80  * Thu Oct 12 2000 Matt Domsch <Matt_Domsch@dell.com>
81  * - Thanks to Andries Brouwer for his debugging assistance.
82  * - Code works, detects all the partitions.
83  *
84  ************************************************************/
85 #include <linux/kernel.h>
86 #include <linux/crc32.h>
87 #include <linux/ctype.h>
88 #include <linux/math64.h>
89 #include <linux/slab.h>
90 #include "check.h"
91 #include "efi.h"
92 
93 /* This allows a kernel command line option 'gpt' to override
94  * the test for invalid PMBR.  Not __initdata because reloading
95  * the partition tables happens after init too.
96  */
97 static int force_gpt;
98 static int __init
force_gpt_fn(char * str)99 force_gpt_fn(char *str)
100 {
101 	force_gpt = 1;
102 	return 1;
103 }
104 __setup("gpt", force_gpt_fn);
105 
106 
107 /**
108  * efi_crc32() - EFI version of crc32 function
109  * @buf: buffer to calculate crc32 of
110  * @len: length of buf
111  *
112  * Description: Returns EFI-style CRC32 value for @buf
113  *
114  * This function uses the little endian Ethernet polynomial
115  * but seeds the function with ~0, and xor's with ~0 at the end.
116  * Note, the EFI Specification, v1.02, has a reference to
117  * Dr. Dobbs Journal, May 1994 (actually it's in May 1992).
118  */
119 static inline u32
efi_crc32(const void * buf,unsigned long len)120 efi_crc32(const void *buf, unsigned long len)
121 {
122 	return (crc32(~0L, buf, len) ^ ~0L);
123 }
124 
125 /**
126  * last_lba(): return number of last logical block of device
127  * @disk: block device
128  *
129  * Description: Returns last LBA value on success, 0 on error.
130  * This is stored (by sd and ide-geometry) in
131  *  the part[0] entry for this disk, and is the number of
132  *  physical sectors available on the disk.
133  */
last_lba(struct gendisk * disk)134 static u64 last_lba(struct gendisk *disk)
135 {
136 	return div_u64(disk->part0->bd_inode->i_size,
137 		       queue_logical_block_size(disk->queue)) - 1ULL;
138 }
139 
pmbr_part_valid(gpt_mbr_record * part)140 static inline int pmbr_part_valid(gpt_mbr_record *part)
141 {
142 	if (part->os_type != EFI_PMBR_OSTYPE_EFI_GPT)
143 		goto invalid;
144 
145 	/* set to 0x00000001 (i.e., the LBA of the GPT Partition Header) */
146 	if (le32_to_cpu(part->starting_lba) != GPT_PRIMARY_PARTITION_TABLE_LBA)
147 		goto invalid;
148 
149 	return GPT_MBR_PROTECTIVE;
150 invalid:
151 	return 0;
152 }
153 
154 /**
155  * is_pmbr_valid(): test Protective MBR for validity
156  * @mbr: pointer to a legacy mbr structure
157  * @total_sectors: amount of sectors in the device
158  *
159  * Description: Checks for a valid protective or hybrid
160  * master boot record (MBR). The validity of a pMBR depends
161  * on all of the following properties:
162  *  1) MSDOS signature is in the last two bytes of the MBR
163  *  2) One partition of type 0xEE is found
164  *
165  * In addition, a hybrid MBR will have up to three additional
166  * primary partitions, which point to the same space that's
167  * marked out by up to three GPT partitions.
168  *
169  * Returns 0 upon invalid MBR, or GPT_MBR_PROTECTIVE or
170  * GPT_MBR_HYBRID depending on the device layout.
171  */
is_pmbr_valid(legacy_mbr * mbr,sector_t total_sectors)172 static int is_pmbr_valid(legacy_mbr *mbr, sector_t total_sectors)
173 {
174 	uint32_t sz = 0;
175 	int i, part = 0, ret = 0; /* invalid by default */
176 
177 	if (!mbr || le16_to_cpu(mbr->signature) != MSDOS_MBR_SIGNATURE)
178 		goto done;
179 
180 	for (i = 0; i < 4; i++) {
181 		ret = pmbr_part_valid(&mbr->partition_record[i]);
182 		if (ret == GPT_MBR_PROTECTIVE) {
183 			part = i;
184 			/*
185 			 * Ok, we at least know that there's a protective MBR,
186 			 * now check if there are other partition types for
187 			 * hybrid MBR.
188 			 */
189 			goto check_hybrid;
190 		}
191 	}
192 
193 	if (ret != GPT_MBR_PROTECTIVE)
194 		goto done;
195 check_hybrid:
196 	for (i = 0; i < 4; i++)
197 		if ((mbr->partition_record[i].os_type !=
198 			EFI_PMBR_OSTYPE_EFI_GPT) &&
199 		    (mbr->partition_record[i].os_type != 0x00))
200 			ret = GPT_MBR_HYBRID;
201 
202 	/*
203 	 * Protective MBRs take up the lesser of the whole disk
204 	 * or 2 TiB (32bit LBA), ignoring the rest of the disk.
205 	 * Some partitioning programs, nonetheless, choose to set
206 	 * the size to the maximum 32-bit limitation, disregarding
207 	 * the disk size.
208 	 *
209 	 * Hybrid MBRs do not necessarily comply with this.
210 	 *
211 	 * Consider a bad value here to be a warning to support dd'ing
212 	 * an image from a smaller disk to a larger disk.
213 	 */
214 	if (ret == GPT_MBR_PROTECTIVE) {
215 		sz = le32_to_cpu(mbr->partition_record[part].size_in_lba);
216 		if (sz != (uint32_t) total_sectors - 1 && sz != 0xFFFFFFFF)
217 			pr_debug("GPT: mbr size in lba (%u) different than whole disk (%u).\n",
218 				 sz, min_t(uint32_t,
219 					   total_sectors - 1, 0xFFFFFFFF));
220 	}
221 done:
222 	return ret;
223 }
224 
225 /**
226  * read_lba(): Read bytes from disk, starting at given LBA
227  * @state: disk parsed partitions
228  * @lba: the Logical Block Address of the partition table
229  * @buffer: destination buffer
230  * @count: bytes to read
231  *
232  * Description: Reads @count bytes from @state->disk into @buffer.
233  * Returns number of bytes read on success, 0 on error.
234  */
read_lba(struct parsed_partitions * state,u64 lba,u8 * buffer,size_t count)235 static size_t read_lba(struct parsed_partitions *state,
236 		       u64 lba, u8 *buffer, size_t count)
237 {
238 	size_t totalreadcount = 0;
239 	sector_t n = lba *
240 		(queue_logical_block_size(state->disk->queue) / 512);
241 
242 	if (!buffer || lba > last_lba(state->disk))
243                 return 0;
244 
245 	while (count) {
246 		int copied = 512;
247 		Sector sect;
248 		unsigned char *data = read_part_sector(state, n++, &sect);
249 		if (!data)
250 			break;
251 		if (copied > count)
252 			copied = count;
253 		memcpy(buffer, data, copied);
254 		put_dev_sector(sect);
255 		buffer += copied;
256 		totalreadcount +=copied;
257 		count -= copied;
258 	}
259 	return totalreadcount;
260 }
261 
262 /**
263  * alloc_read_gpt_entries(): reads partition entries from disk
264  * @state: disk parsed partitions
265  * @gpt: GPT header
266  *
267  * Description: Returns ptes on success,  NULL on error.
268  * Allocates space for PTEs based on information found in @gpt.
269  * Notes: remember to free pte when you're done!
270  */
alloc_read_gpt_entries(struct parsed_partitions * state,gpt_header * gpt)271 static gpt_entry *alloc_read_gpt_entries(struct parsed_partitions *state,
272 					 gpt_header *gpt)
273 {
274 	size_t count;
275 	gpt_entry *pte;
276 
277 	if (!gpt)
278 		return NULL;
279 
280 	count = (size_t)le32_to_cpu(gpt->num_partition_entries) *
281                 le32_to_cpu(gpt->sizeof_partition_entry);
282 	if (!count)
283 		return NULL;
284 	pte = kmalloc(count, GFP_KERNEL);
285 	if (!pte)
286 		return NULL;
287 
288 	if (read_lba(state, le64_to_cpu(gpt->partition_entry_lba),
289 			(u8 *) pte, count) < count) {
290 		kfree(pte);
291                 pte=NULL;
292 		return NULL;
293 	}
294 	return pte;
295 }
296 
297 /**
298  * alloc_read_gpt_header(): Allocates GPT header, reads into it from disk
299  * @state: disk parsed partitions
300  * @lba: the Logical Block Address of the partition table
301  *
302  * Description: returns GPT header on success, NULL on error.   Allocates
303  * and fills a GPT header starting at @ from @state->disk.
304  * Note: remember to free gpt when finished with it.
305  */
alloc_read_gpt_header(struct parsed_partitions * state,u64 lba)306 static gpt_header *alloc_read_gpt_header(struct parsed_partitions *state,
307 					 u64 lba)
308 {
309 	gpt_header *gpt;
310 	unsigned ssz = queue_logical_block_size(state->disk->queue);
311 
312 	gpt = kmalloc(ssz, GFP_KERNEL);
313 	if (!gpt)
314 		return NULL;
315 
316 	if (read_lba(state, lba, (u8 *) gpt, ssz) < ssz) {
317 		kfree(gpt);
318                 gpt=NULL;
319 		return NULL;
320 	}
321 
322 	return gpt;
323 }
324 
325 /**
326  * is_gpt_valid() - tests one GPT header and PTEs for validity
327  * @state: disk parsed partitions
328  * @lba: logical block address of the GPT header to test
329  * @gpt: GPT header ptr, filled on return.
330  * @ptes: PTEs ptr, filled on return.
331  *
332  * Description: returns 1 if valid,  0 on error.
333  * If valid, returns pointers to newly allocated GPT header and PTEs.
334  */
is_gpt_valid(struct parsed_partitions * state,u64 lba,gpt_header ** gpt,gpt_entry ** ptes)335 static int is_gpt_valid(struct parsed_partitions *state, u64 lba,
336 			gpt_header **gpt, gpt_entry **ptes)
337 {
338 	u32 crc, origcrc;
339 	u64 lastlba, pt_size;
340 
341 	if (!ptes)
342 		return 0;
343 	if (!(*gpt = alloc_read_gpt_header(state, lba)))
344 		return 0;
345 
346 	/* Check the GUID Partition Table signature */
347 	if (le64_to_cpu((*gpt)->signature) != GPT_HEADER_SIGNATURE) {
348 		pr_debug("GUID Partition Table Header signature is wrong:"
349 			 "%lld != %lld\n",
350 			 (unsigned long long)le64_to_cpu((*gpt)->signature),
351 			 (unsigned long long)GPT_HEADER_SIGNATURE);
352 		goto fail;
353 	}
354 
355 	/* Check the GUID Partition Table header size is too big */
356 	if (le32_to_cpu((*gpt)->header_size) >
357 			queue_logical_block_size(state->disk->queue)) {
358 		pr_debug("GUID Partition Table Header size is too large: %u > %u\n",
359 			le32_to_cpu((*gpt)->header_size),
360 			queue_logical_block_size(state->disk->queue));
361 		goto fail;
362 	}
363 
364 	/* Check the GUID Partition Table header size is too small */
365 	if (le32_to_cpu((*gpt)->header_size) < sizeof(gpt_header)) {
366 		pr_debug("GUID Partition Table Header size is too small: %u < %zu\n",
367 			le32_to_cpu((*gpt)->header_size),
368 			sizeof(gpt_header));
369 		goto fail;
370 	}
371 
372 	/* Check the GUID Partition Table CRC */
373 	origcrc = le32_to_cpu((*gpt)->header_crc32);
374 	(*gpt)->header_crc32 = 0;
375 	crc = efi_crc32((const unsigned char *) (*gpt), le32_to_cpu((*gpt)->header_size));
376 
377 	if (crc != origcrc) {
378 		pr_debug("GUID Partition Table Header CRC is wrong: %x != %x\n",
379 			 crc, origcrc);
380 		goto fail;
381 	}
382 	(*gpt)->header_crc32 = cpu_to_le32(origcrc);
383 
384 	/* Check that the my_lba entry points to the LBA that contains
385 	 * the GUID Partition Table */
386 	if (le64_to_cpu((*gpt)->my_lba) != lba) {
387 		pr_debug("GPT my_lba incorrect: %lld != %lld\n",
388 			 (unsigned long long)le64_to_cpu((*gpt)->my_lba),
389 			 (unsigned long long)lba);
390 		goto fail;
391 	}
392 
393 	/* Check the first_usable_lba and last_usable_lba are
394 	 * within the disk.
395 	 */
396 	lastlba = last_lba(state->disk);
397 	if (le64_to_cpu((*gpt)->first_usable_lba) > lastlba) {
398 		pr_debug("GPT: first_usable_lba incorrect: %lld > %lld\n",
399 			 (unsigned long long)le64_to_cpu((*gpt)->first_usable_lba),
400 			 (unsigned long long)lastlba);
401 		goto fail;
402 	}
403 	if (le64_to_cpu((*gpt)->last_usable_lba) > lastlba) {
404 		pr_debug("GPT: last_usable_lba incorrect: %lld > %lld\n",
405 			 (unsigned long long)le64_to_cpu((*gpt)->last_usable_lba),
406 			 (unsigned long long)lastlba);
407 		goto fail;
408 	}
409 	if (le64_to_cpu((*gpt)->last_usable_lba) < le64_to_cpu((*gpt)->first_usable_lba)) {
410 		pr_debug("GPT: last_usable_lba incorrect: %lld > %lld\n",
411 			 (unsigned long long)le64_to_cpu((*gpt)->last_usable_lba),
412 			 (unsigned long long)le64_to_cpu((*gpt)->first_usable_lba));
413 		goto fail;
414 	}
415 	/* Check that sizeof_partition_entry has the correct value */
416 	if (le32_to_cpu((*gpt)->sizeof_partition_entry) != sizeof(gpt_entry)) {
417 		pr_debug("GUID Partition Entry Size check failed.\n");
418 		goto fail;
419 	}
420 
421 	/* Sanity check partition table size */
422 	pt_size = (u64)le32_to_cpu((*gpt)->num_partition_entries) *
423 		le32_to_cpu((*gpt)->sizeof_partition_entry);
424 	if (pt_size > KMALLOC_MAX_SIZE) {
425 		pr_debug("GUID Partition Table is too large: %llu > %lu bytes\n",
426 			 (unsigned long long)pt_size, KMALLOC_MAX_SIZE);
427 		goto fail;
428 	}
429 
430 	if (!(*ptes = alloc_read_gpt_entries(state, *gpt)))
431 		goto fail;
432 
433 	/* Check the GUID Partition Entry Array CRC */
434 	crc = efi_crc32((const unsigned char *) (*ptes), pt_size);
435 
436 	if (crc != le32_to_cpu((*gpt)->partition_entry_array_crc32)) {
437 		pr_debug("GUID Partition Entry Array CRC check failed.\n");
438 		goto fail_ptes;
439 	}
440 
441 	/* We're done, all's well */
442 	return 1;
443 
444  fail_ptes:
445 	kfree(*ptes);
446 	*ptes = NULL;
447  fail:
448 	kfree(*gpt);
449 	*gpt = NULL;
450 	return 0;
451 }
452 
453 /**
454  * is_pte_valid() - tests one PTE for validity
455  * @pte:pte to check
456  * @lastlba: last lba of the disk
457  *
458  * Description: returns 1 if valid,  0 on error.
459  */
460 static inline int
is_pte_valid(const gpt_entry * pte,const u64 lastlba)461 is_pte_valid(const gpt_entry *pte, const u64 lastlba)
462 {
463 	if ((!efi_guidcmp(pte->partition_type_guid, NULL_GUID)) ||
464 	    le64_to_cpu(pte->starting_lba) > lastlba         ||
465 	    le64_to_cpu(pte->ending_lba)   > lastlba)
466 		return 0;
467 	return 1;
468 }
469 
470 /**
471  * compare_gpts() - Search disk for valid GPT headers and PTEs
472  * @pgpt: primary GPT header
473  * @agpt: alternate GPT header
474  * @lastlba: last LBA number
475  *
476  * Description: Returns nothing.  Sanity checks pgpt and agpt fields
477  * and prints warnings on discrepancies.
478  *
479  */
480 static void
compare_gpts(gpt_header * pgpt,gpt_header * agpt,u64 lastlba)481 compare_gpts(gpt_header *pgpt, gpt_header *agpt, u64 lastlba)
482 {
483 	int error_found = 0;
484 	if (!pgpt || !agpt)
485 		return;
486 	if (le64_to_cpu(pgpt->my_lba) != le64_to_cpu(agpt->alternate_lba)) {
487 		pr_warn("GPT:Primary header LBA != Alt. header alternate_lba\n");
488 		pr_warn("GPT:%lld != %lld\n",
489 		       (unsigned long long)le64_to_cpu(pgpt->my_lba),
490                        (unsigned long long)le64_to_cpu(agpt->alternate_lba));
491 		error_found++;
492 	}
493 	if (le64_to_cpu(pgpt->alternate_lba) != le64_to_cpu(agpt->my_lba)) {
494 		pr_warn("GPT:Primary header alternate_lba != Alt. header my_lba\n");
495 		pr_warn("GPT:%lld != %lld\n",
496 		       (unsigned long long)le64_to_cpu(pgpt->alternate_lba),
497                        (unsigned long long)le64_to_cpu(agpt->my_lba));
498 		error_found++;
499 	}
500 	if (le64_to_cpu(pgpt->first_usable_lba) !=
501             le64_to_cpu(agpt->first_usable_lba)) {
502 		pr_warn("GPT:first_usable_lbas don't match.\n");
503 		pr_warn("GPT:%lld != %lld\n",
504 		       (unsigned long long)le64_to_cpu(pgpt->first_usable_lba),
505                        (unsigned long long)le64_to_cpu(agpt->first_usable_lba));
506 		error_found++;
507 	}
508 	if (le64_to_cpu(pgpt->last_usable_lba) !=
509             le64_to_cpu(agpt->last_usable_lba)) {
510 		pr_warn("GPT:last_usable_lbas don't match.\n");
511 		pr_warn("GPT:%lld != %lld\n",
512 		       (unsigned long long)le64_to_cpu(pgpt->last_usable_lba),
513                        (unsigned long long)le64_to_cpu(agpt->last_usable_lba));
514 		error_found++;
515 	}
516 	if (efi_guidcmp(pgpt->disk_guid, agpt->disk_guid)) {
517 		pr_warn("GPT:disk_guids don't match.\n");
518 		error_found++;
519 	}
520 	if (le32_to_cpu(pgpt->num_partition_entries) !=
521             le32_to_cpu(agpt->num_partition_entries)) {
522 		pr_warn("GPT:num_partition_entries don't match: "
523 		       "0x%x != 0x%x\n",
524 		       le32_to_cpu(pgpt->num_partition_entries),
525 		       le32_to_cpu(agpt->num_partition_entries));
526 		error_found++;
527 	}
528 	if (le32_to_cpu(pgpt->sizeof_partition_entry) !=
529             le32_to_cpu(agpt->sizeof_partition_entry)) {
530 		pr_warn("GPT:sizeof_partition_entry values don't match: "
531 		       "0x%x != 0x%x\n",
532                        le32_to_cpu(pgpt->sizeof_partition_entry),
533 		       le32_to_cpu(agpt->sizeof_partition_entry));
534 		error_found++;
535 	}
536 	if (le32_to_cpu(pgpt->partition_entry_array_crc32) !=
537             le32_to_cpu(agpt->partition_entry_array_crc32)) {
538 		pr_warn("GPT:partition_entry_array_crc32 values don't match: "
539 		       "0x%x != 0x%x\n",
540                        le32_to_cpu(pgpt->partition_entry_array_crc32),
541 		       le32_to_cpu(agpt->partition_entry_array_crc32));
542 		error_found++;
543 	}
544 	if (le64_to_cpu(pgpt->alternate_lba) != lastlba) {
545 		pr_warn("GPT:Primary header thinks Alt. header is not at the end of the disk.\n");
546 		pr_warn("GPT:%lld != %lld\n",
547 			(unsigned long long)le64_to_cpu(pgpt->alternate_lba),
548 			(unsigned long long)lastlba);
549 		error_found++;
550 	}
551 
552 	if (le64_to_cpu(agpt->my_lba) != lastlba) {
553 		pr_warn("GPT:Alternate GPT header not at the end of the disk.\n");
554 		pr_warn("GPT:%lld != %lld\n",
555 			(unsigned long long)le64_to_cpu(agpt->my_lba),
556 			(unsigned long long)lastlba);
557 		error_found++;
558 	}
559 
560 	if (error_found)
561 		pr_warn("GPT: Use GNU Parted to correct GPT errors.\n");
562 	return;
563 }
564 
565 /**
566  * find_valid_gpt() - Search disk for valid GPT headers and PTEs
567  * @state: disk parsed partitions
568  * @gpt: GPT header ptr, filled on return.
569  * @ptes: PTEs ptr, filled on return.
570  *
571  * Description: Returns 1 if valid, 0 on error.
572  * If valid, returns pointers to newly allocated GPT header and PTEs.
573  * Validity depends on PMBR being valid (or being overridden by the
574  * 'gpt' kernel command line option) and finding either the Primary
575  * GPT header and PTEs valid, or the Alternate GPT header and PTEs
576  * valid.  If the Primary GPT header is not valid, the Alternate GPT header
577  * is not checked unless the 'gpt' kernel command line option is passed.
578  * This protects against devices which misreport their size, and forces
579  * the user to decide to use the Alternate GPT.
580  */
find_valid_gpt(struct parsed_partitions * state,gpt_header ** gpt,gpt_entry ** ptes)581 static int find_valid_gpt(struct parsed_partitions *state, gpt_header **gpt,
582 			  gpt_entry **ptes)
583 {
584 	int good_pgpt = 0, good_agpt = 0, good_pmbr = 0;
585 	gpt_header *pgpt = NULL, *agpt = NULL;
586 	gpt_entry *pptes = NULL, *aptes = NULL;
587 	legacy_mbr *legacymbr;
588 	struct gendisk *disk = state->disk;
589 	const struct block_device_operations *fops = disk->fops;
590 	sector_t total_sectors = get_capacity(state->disk);
591 	u64 lastlba;
592 
593 	if (!ptes)
594 		return 0;
595 
596 	lastlba = last_lba(state->disk);
597         if (!force_gpt) {
598 		/* This will be added to the EFI Spec. per Intel after v1.02. */
599 		legacymbr = kzalloc(sizeof(*legacymbr), GFP_KERNEL);
600 		if (!legacymbr)
601 			goto fail;
602 
603 		read_lba(state, 0, (u8 *)legacymbr, sizeof(*legacymbr));
604 		good_pmbr = is_pmbr_valid(legacymbr, total_sectors);
605 		kfree(legacymbr);
606 
607 		if (!good_pmbr)
608 			goto fail;
609 
610 		pr_debug("Device has a %s MBR\n",
611 			 good_pmbr == GPT_MBR_PROTECTIVE ?
612 						"protective" : "hybrid");
613 	}
614 
615 	good_pgpt = is_gpt_valid(state, GPT_PRIMARY_PARTITION_TABLE_LBA,
616 				 &pgpt, &pptes);
617         if (good_pgpt)
618 		good_agpt = is_gpt_valid(state,
619 					 le64_to_cpu(pgpt->alternate_lba),
620 					 &agpt, &aptes);
621         if (!good_agpt && force_gpt)
622                 good_agpt = is_gpt_valid(state, lastlba, &agpt, &aptes);
623 
624 	if (!good_agpt && force_gpt && fops->alternative_gpt_sector) {
625 		sector_t agpt_sector;
626 		int err;
627 
628 		err = fops->alternative_gpt_sector(disk, &agpt_sector);
629 		if (!err)
630 			good_agpt = is_gpt_valid(state, agpt_sector,
631 						 &agpt, &aptes);
632 	}
633 
634         /* The obviously unsuccessful case */
635         if (!good_pgpt && !good_agpt)
636                 goto fail;
637 
638         compare_gpts(pgpt, agpt, lastlba);
639 
640         /* The good cases */
641         if (good_pgpt) {
642                 *gpt  = pgpt;
643                 *ptes = pptes;
644                 kfree(agpt);
645                 kfree(aptes);
646 		if (!good_agpt)
647                         pr_warn("Alternate GPT is invalid, using primary GPT.\n");
648                 return 1;
649         }
650         else if (good_agpt) {
651                 *gpt  = agpt;
652                 *ptes = aptes;
653                 kfree(pgpt);
654                 kfree(pptes);
655 		pr_warn("Primary GPT is invalid, using alternate GPT.\n");
656                 return 1;
657         }
658 
659  fail:
660         kfree(pgpt);
661         kfree(agpt);
662         kfree(pptes);
663         kfree(aptes);
664         *gpt = NULL;
665         *ptes = NULL;
666         return 0;
667 }
668 
669 /**
670  * utf16_le_to_7bit(): Naively converts a UTF-16LE string to 7-bit ASCII characters
671  * @in: input UTF-16LE string
672  * @size: size of the input string
673  * @out: output string ptr, should be capable to store @size+1 characters
674  *
675  * Description: Converts @size UTF16-LE symbols from @in string to 7-bit
676  * ASCII characters and stores them to @out. Adds trailing zero to @out array.
677  */
utf16_le_to_7bit(const __le16 * in,unsigned int size,u8 * out)678 static void utf16_le_to_7bit(const __le16 *in, unsigned int size, u8 *out)
679 {
680 	unsigned int i = 0;
681 
682 	out[size] = 0;
683 
684 	while (i < size) {
685 		u8 c = le16_to_cpu(in[i]) & 0xff;
686 
687 		if (c && !isprint(c))
688 			c = '!';
689 		out[i] = c;
690 		i++;
691 	}
692 }
693 
694 /**
695  * efi_partition - scan for GPT partitions
696  * @state: disk parsed partitions
697  *
698  * Description: called from check.c, if the disk contains GPT
699  * partitions, sets up partition entries in the kernel.
700  *
701  * If the first block on the disk is a legacy MBR,
702  * it will get handled by msdos_partition().
703  * If it's a Protective MBR, we'll handle it here.
704  *
705  * We do not create a Linux partition for GPT, but
706  * only for the actual data partitions.
707  * Returns:
708  * -1 if unable to read the partition table
709  *  0 if this isn't our partition table
710  *  1 if successful
711  *
712  */
efi_partition(struct parsed_partitions * state)713 int efi_partition(struct parsed_partitions *state)
714 {
715 	gpt_header *gpt = NULL;
716 	gpt_entry *ptes = NULL;
717 	u32 i;
718 	unsigned ssz = queue_logical_block_size(state->disk->queue) / 512;
719 
720 	if (!find_valid_gpt(state, &gpt, &ptes) || !gpt || !ptes) {
721 		kfree(gpt);
722 		kfree(ptes);
723 		return 0;
724 	}
725 
726 	pr_debug("GUID Partition Table is valid!  Yea!\n");
727 
728 	for (i = 0; i < le32_to_cpu(gpt->num_partition_entries) && i < state->limit-1; i++) {
729 		struct partition_meta_info *info;
730 		unsigned label_max;
731 		u64 start = le64_to_cpu(ptes[i].starting_lba);
732 		u64 size = le64_to_cpu(ptes[i].ending_lba) -
733 			   le64_to_cpu(ptes[i].starting_lba) + 1ULL;
734 
735 		if (!is_pte_valid(&ptes[i], last_lba(state->disk)))
736 			continue;
737 
738 		put_partition(state, i+1, start * ssz, size * ssz);
739 
740 		/* If this is a RAID volume, tell md */
741 		if (!efi_guidcmp(ptes[i].partition_type_guid, PARTITION_LINUX_RAID_GUID))
742 			state->parts[i + 1].flags = ADDPART_FLAG_RAID;
743 
744 		info = &state->parts[i + 1].info;
745 		efi_guid_to_str(&ptes[i].unique_partition_guid, info->uuid);
746 
747 		/* Naively convert UTF16-LE to 7 bits. */
748 		label_max = min(ARRAY_SIZE(info->volname) - 1,
749 				ARRAY_SIZE(ptes[i].partition_name));
750 		utf16_le_to_7bit(ptes[i].partition_name, label_max, info->volname);
751 		state->parts[i + 1].has_info = true;
752 	}
753 	kfree(ptes);
754 	kfree(gpt);
755 	strlcat(state->pp_buf, "\n", PAGE_SIZE);
756 	return 1;
757 }
758