blob: 73a1968d8490d67c584bcd340853d29ef59d1c5c [file] [log] [blame]
micky387e96abca2019-06-11 02:35:20 +02001/*
2 * Copyright (c) 2013,2016, The Linux Foundation. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above
10 * copyright notice, this list of conditions and the following
11 * disclaimer in the documentation and/or other materials provided
12 * with the distribution.
13 * * Neither the name of The Linux Foundation nor the names of its
14 * contributors may be used to endorse or promote products derived
15 * from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
21 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
26 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
27 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30#define _LARGEFILE64_SOURCE /* enable lseek64() */
31
32/******************************************************************************
33 * INCLUDE SECTION
34 ******************************************************************************/
35#include <stdio.h>
36#include <fcntl.h>
37#include <string.h>
38#include <errno.h>
39#include <inttypes.h>
40#include <sys/stat.h>
41#include <sys/ioctl.h>
42#include <scsi/ufs/ioctl.h>
43#include <scsi/ufs/ufs.h>
44#include <unistd.h>
45#include <linux/fs.h>
46#include <limits.h>
47#include <dirent.h>
48#include <linux/kernel.h>
49#include <asm/byteorder.h>
50#include <map>
51#include <vector>
52#include <string>
53#define LOG_TAG "gpt-utils"
54#include <log/log.h>
55#include <cutils/properties.h>
56#include "gpt-utils.h"
57#include "sparse_crc32.h"
58#include <endian.h>
59
60
61/******************************************************************************
62 * DEFINE SECTION
63 ******************************************************************************/
64#define BLK_DEV_FILE "/dev/block/mmcblk0"
65/* list the names of the backed-up partitions to be swapped */
66/* extension used for the backup partitions - tzbak, abootbak, etc. */
67#define BAK_PTN_NAME_EXT "bak"
68#define XBL_PRIMARY "/dev/block/bootdevice/by-name/xbl"
69#define XBL_BACKUP "/dev/block/bootdevice/by-name/xblbak"
70#define XBL_AB_PRIMARY "/dev/block/bootdevice/by-name/xbl_a"
71#define XBL_AB_SECONDARY "/dev/block/bootdevice/by-name/xbl_b"
72/* GPT defines */
73#define MAX_LUNS 26
74//Size of the buffer that needs to be passed to the UFS ioctl
75#define UFS_ATTR_DATA_SIZE 32
76//This will allow us to get the root lun path from the path to the partition.
77//i.e: from /dev/block/sdaXXX get /dev/block/sda. The assumption here is that
78//the boot critical luns lie between sda to sdz which is acceptable because
79//only user added external disks,etc would lie beyond that limit which do not
80//contain partitions that interest us here.
81#define PATH_TRUNCATE_LOC (sizeof("/dev/block/sda") - 1)
82
83//From /dev/block/sda get just sda
84#define LUN_NAME_START_LOC (sizeof("/dev/block/") - 1)
85#define BOOT_LUN_A_ID 1
86#define BOOT_LUN_B_ID 2
87/******************************************************************************
88 * MACROS
89 ******************************************************************************/
90
91
92#define GET_4_BYTES(ptr) ((uint32_t) *((uint8_t *)(ptr)) | \
93 ((uint32_t) *((uint8_t *)(ptr) + 1) << 8) | \
94 ((uint32_t) *((uint8_t *)(ptr) + 2) << 16) | \
95 ((uint32_t) *((uint8_t *)(ptr) + 3) << 24))
96
97#define GET_8_BYTES(ptr) ((uint64_t) *((uint8_t *)(ptr)) | \
98 ((uint64_t) *((uint8_t *)(ptr) + 1) << 8) | \
99 ((uint64_t) *((uint8_t *)(ptr) + 2) << 16) | \
100 ((uint64_t) *((uint8_t *)(ptr) + 3) << 24) | \
101 ((uint64_t) *((uint8_t *)(ptr) + 4) << 32) | \
102 ((uint64_t) *((uint8_t *)(ptr) + 5) << 40) | \
103 ((uint64_t) *((uint8_t *)(ptr) + 6) << 48) | \
104 ((uint64_t) *((uint8_t *)(ptr) + 7) << 56))
105
106#define PUT_4_BYTES(ptr, y) *((uint8_t *)(ptr)) = (y) & 0xff; \
107 *((uint8_t *)(ptr) + 1) = ((y) >> 8) & 0xff; \
108 *((uint8_t *)(ptr) + 2) = ((y) >> 16) & 0xff; \
109 *((uint8_t *)(ptr) + 3) = ((y) >> 24) & 0xff;
110
111/******************************************************************************
112 * TYPES
113 ******************************************************************************/
114using namespace std;
115enum gpt_state {
116 GPT_OK = 0,
117 GPT_BAD_SIGNATURE,
118 GPT_BAD_CRC
119};
120//List of LUN's containing boot critical images.
121//Required in the case of UFS devices
122struct update_data {
123 char lun_list[MAX_LUNS][PATH_MAX];
124 uint32_t num_valid_entries;
125};
126
127/******************************************************************************
128 * FUNCTIONS
129 ******************************************************************************/
130/**
131 * ==========================================================================
132 *
133 * \brief Read/Write len bytes from/to block dev
134 *
135 * \param [in] fd block dev file descriptor (returned from open)
136 * \param [in] rw RW flag: 0 - read, != 0 - write
137 * \param [in] offset block dev offset [bytes] - RW start position
138 * \param [in] buf Pointer to the buffer containing the data
139 * \param [in] len RW size in bytes. Buf must be at least that big
140 *
141 * \return 0 on success
142 *
143 * ==========================================================================
144 */
145static int blk_rw(int fd, int rw, int64_t offset, uint8_t *buf, unsigned len)
146{
147 int r;
148
149 if (lseek64(fd, offset, SEEK_SET) < 0) {
150 fprintf(stderr, "block dev lseek64 %" PRId64 " failed: %s\n", offset,
151 strerror(errno));
152 return -1;
153 }
154
155 if (rw)
156 r = write(fd, buf, len);
157 else
158 r = read(fd, buf, len);
159
160 if (r < 0)
161 fprintf(stderr, "block dev %s failed: %s\n", rw ? "write" : "read",
162 strerror(errno));
163 else
164 r = 0;
165
166 return r;
167}
168
169
170
171/**
172 * ==========================================================================
173 *
174 * \brief Search within GPT for partition entry with the given name
175 * or it's backup twin (name-bak).
176 *
177 * \param [in] ptn_name Partition name to seek
178 * \param [in] pentries_start Partition entries array start pointer
179 * \param [in] pentries_end Partition entries array end pointer
180 * \param [in] pentry_size Single partition entry size [bytes]
181 *
182 * \return First partition entry pointer that matches the name or NULL
183 *
184 * ==========================================================================
185 */
186static uint8_t *gpt_pentry_seek(const char *ptn_name,
187 const uint8_t *pentries_start,
188 const uint8_t *pentries_end,
189 uint32_t pentry_size)
190{
191 char *pentry_name;
192 unsigned len = strlen(ptn_name);
193
194 for (pentry_name = (char *) (pentries_start + PARTITION_NAME_OFFSET);
195 pentry_name < (char *) pentries_end; pentry_name += pentry_size) {
196 char name8[MAX_GPT_NAME_SIZE] = {0}; // initialize with null
197 unsigned i;
198
199 /* Partition names in GPT are UTF-16 - ignoring UTF-16 2nd byte */
200 for (i = 0; i < sizeof(name8) / 2; i++)
201 name8[i] = pentry_name[i * 2];
202 if (!strncmp(ptn_name, name8, len))
203 if (name8[len] == 0 || !strcmp(&name8[len], BAK_PTN_NAME_EXT))
204 return (uint8_t *) (pentry_name - PARTITION_NAME_OFFSET);
205 }
206
207 return NULL;
208}
209
210
211
212/**
213 * ==========================================================================
214 *
215 * \brief Swaps boot chain in GPT partition entries array
216 *
217 * \param [in] pentries_start Partition entries array start
218 * \param [in] pentries_end Partition entries array end
219 * \param [in] pentry_size Single partition entry size
220 *
221 * \return 0 on success, 1 if no backup partitions found
222 *
223 * ==========================================================================
224 */
225static int gpt_boot_chain_swap(const uint8_t *pentries_start,
226 const uint8_t *pentries_end,
227 uint32_t pentry_size)
228{
229 const char ptn_swap_list[][MAX_GPT_NAME_SIZE] = { PTN_SWAP_LIST };
230
231 int backup_not_found = 1;
232 unsigned i;
233
234 for (i = 0; i < ARRAY_SIZE(ptn_swap_list); i++) {
235 uint8_t *ptn_entry;
236 uint8_t *ptn_bak_entry;
237 uint8_t ptn_swap[PTN_ENTRY_SIZE];
238 //Skip the xbl partition on UFS devices. That is handled
239 //seperately.
240 if (gpt_utils_is_ufs_device() && !strncmp(ptn_swap_list[i],
241 PTN_XBL,
242 strlen(PTN_XBL)))
243 continue;
244
245 ptn_entry = gpt_pentry_seek(ptn_swap_list[i], pentries_start,
246 pentries_end, pentry_size);
247 if (ptn_entry == NULL)
248 continue;
249
250 ptn_bak_entry = gpt_pentry_seek(ptn_swap_list[i],
251 ptn_entry + pentry_size, pentries_end, pentry_size);
252 if (ptn_bak_entry == NULL) {
253 fprintf(stderr, "'%s' partition not backup - skip safe update\n",
254 ptn_swap_list[i]);
255 continue;
256 }
257
258 /* swap primary <-> backup partition entries */
259 memcpy(ptn_swap, ptn_entry, PTN_ENTRY_SIZE);
260 memcpy(ptn_entry, ptn_bak_entry, PTN_ENTRY_SIZE);
261 memcpy(ptn_bak_entry, ptn_swap, PTN_ENTRY_SIZE);
262 backup_not_found = 0;
263 }
264
265 return backup_not_found;
266}
267
268
269
270/**
271 * ==========================================================================
272 *
273 * \brief Sets secondary GPT boot chain
274 *
275 * \param [in] fd block dev file descriptor
276 * \param [in] boot Boot chain to switch to
277 *
278 * \return 0 on success
279 *
280 * ==========================================================================
281 */
282static int gpt2_set_boot_chain(int fd, enum boot_chain boot)
283{
284 int64_t gpt2_header_offset;
285 uint64_t pentries_start_offset;
286 uint32_t gpt_header_size;
287 uint32_t pentry_size;
288 uint32_t pentries_array_size;
289
290 uint8_t *gpt_header = NULL;
291 uint8_t *pentries = NULL;
292 uint32_t crc;
293 uint32_t blk_size = 0;
294 int r;
295
296 if (ioctl(fd, BLKSSZGET, &blk_size) != 0) {
297 fprintf(stderr, "Failed to get GPT device block size: %s\n",
298 strerror(errno));
299 r = -1;
300 goto EXIT;
301 }
302 gpt_header = (uint8_t*)malloc(blk_size);
303 if (!gpt_header) {
304 fprintf(stderr, "Failed to allocate memory to hold GPT block\n");
305 r = -1;
306 goto EXIT;
307 }
308 gpt2_header_offset = lseek64(fd, 0, SEEK_END) - blk_size;
309 if (gpt2_header_offset < 0) {
310 fprintf(stderr, "Getting secondary GPT header offset failed: %s\n",
311 strerror(errno));
312 r = -1;
313 goto EXIT;
314 }
315
316 /* Read primary GPT header from block dev */
317 r = blk_rw(fd, 0, blk_size, gpt_header, blk_size);
318
319 if (r) {
320 fprintf(stderr, "Failed to read primary GPT header from blk dev\n");
321 goto EXIT;
322 }
323 pentries_start_offset =
324 GET_8_BYTES(gpt_header + PENTRIES_OFFSET) * blk_size;
325 pentry_size = GET_4_BYTES(gpt_header + PENTRY_SIZE_OFFSET);
326 pentries_array_size =
327 GET_4_BYTES(gpt_header + PARTITION_COUNT_OFFSET) * pentry_size;
328
329 pentries = (uint8_t *) calloc(1, pentries_array_size);
330 if (pentries == NULL) {
331 fprintf(stderr,
332 "Failed to alloc memory for GPT partition entries array\n");
333 r = -1;
334 goto EXIT;
335 }
336 /* Read primary GPT partititon entries array from block dev */
337 r = blk_rw(fd, 0, pentries_start_offset, pentries, pentries_array_size);
338 if (r)
339 goto EXIT;
340
341 crc = sparse_crc32(0, pentries, pentries_array_size);
342 if (GET_4_BYTES(gpt_header + PARTITION_CRC_OFFSET) != crc) {
343 fprintf(stderr, "Primary GPT partition entries array CRC invalid\n");
344 r = -1;
345 goto EXIT;
346 }
347
348 /* Read secondary GPT header from block dev */
349 r = blk_rw(fd, 0, gpt2_header_offset, gpt_header, blk_size);
350 if (r)
351 goto EXIT;
352
353 gpt_header_size = GET_4_BYTES(gpt_header + HEADER_SIZE_OFFSET);
354 pentries_start_offset =
355 GET_8_BYTES(gpt_header + PENTRIES_OFFSET) * blk_size;
356
357 if (boot == BACKUP_BOOT) {
358 r = gpt_boot_chain_swap(pentries, pentries + pentries_array_size,
359 pentry_size);
360 if (r)
361 goto EXIT;
362 }
363
364 crc = sparse_crc32(0, pentries, pentries_array_size);
365 PUT_4_BYTES(gpt_header + PARTITION_CRC_OFFSET, crc);
366
367 /* header CRC is calculated with this field cleared */
368 PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, 0);
369 crc = sparse_crc32(0, gpt_header, gpt_header_size);
370 PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, crc);
371
372 /* Write the modified GPT header back to block dev */
373 r = blk_rw(fd, 1, gpt2_header_offset, gpt_header, blk_size);
374 if (!r)
375 /* Write the modified GPT partititon entries array back to block dev */
376 r = blk_rw(fd, 1, pentries_start_offset, pentries,
377 pentries_array_size);
378
379EXIT:
380 if(gpt_header)
381 free(gpt_header);
382 if (pentries)
383 free(pentries);
384 return r;
385}
386
387/**
388 * ==========================================================================
389 *
390 * \brief Checks GPT state (header signature and CRC)
391 *
392 * \param [in] fd block dev file descriptor
393 * \param [in] gpt GPT header to be checked
394 * \param [out] state GPT header state
395 *
396 * \return 0 on success
397 *
398 * ==========================================================================
399 */
400static int gpt_get_state(int fd, enum gpt_instance gpt, enum gpt_state *state)
401{
402 int64_t gpt_header_offset;
403 uint32_t gpt_header_size;
404 uint8_t *gpt_header = NULL;
405 uint32_t crc;
406 uint32_t blk_size = 0;
407
408 *state = GPT_OK;
409
410 if (ioctl(fd, BLKSSZGET, &blk_size) != 0) {
411 fprintf(stderr, "Failed to get GPT device block size: %s\n",
412 strerror(errno));
413 goto error;
414 }
415 gpt_header = (uint8_t*)malloc(blk_size);
416 if (!gpt_header) {
417 fprintf(stderr, "gpt_get_state:Failed to alloc memory for header\n");
418 goto error;
419 }
420 if (gpt == PRIMARY_GPT)
421 gpt_header_offset = blk_size;
422 else {
423 gpt_header_offset = lseek64(fd, 0, SEEK_END) - blk_size;
424 if (gpt_header_offset < 0) {
425 fprintf(stderr, "gpt_get_state:Seek to end of GPT part fail\n");
426 goto error;
427 }
428 }
429
430 if (blk_rw(fd, 0, gpt_header_offset, gpt_header, blk_size)) {
431 fprintf(stderr, "gpt_get_state: blk_rw failed\n");
432 goto error;
433 }
434 if (memcmp(gpt_header, GPT_SIGNATURE, sizeof(GPT_SIGNATURE)))
435 *state = GPT_BAD_SIGNATURE;
436 gpt_header_size = GET_4_BYTES(gpt_header + HEADER_SIZE_OFFSET);
437
438 crc = GET_4_BYTES(gpt_header + HEADER_CRC_OFFSET);
439 /* header CRC is calculated with this field cleared */
440 PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, 0);
441 if (sparse_crc32(0, gpt_header, gpt_header_size) != crc)
442 *state = GPT_BAD_CRC;
443 free(gpt_header);
444 return 0;
445error:
446 if (gpt_header)
447 free(gpt_header);
448 return -1;
449}
450
451
452
453/**
454 * ==========================================================================
455 *
456 * \brief Sets GPT header state (used to corrupt and fix GPT signature)
457 *
458 * \param [in] fd block dev file descriptor
459 * \param [in] gpt GPT header to be checked
460 * \param [in] state GPT header state to set (GPT_OK or GPT_BAD_SIGNATURE)
461 *
462 * \return 0 on success
463 *
464 * ==========================================================================
465 */
466static int gpt_set_state(int fd, enum gpt_instance gpt, enum gpt_state state)
467{
468 int64_t gpt_header_offset;
469 uint32_t gpt_header_size;
470 uint8_t *gpt_header = NULL;
471 uint32_t crc;
472 uint32_t blk_size = 0;
473
474 if (ioctl(fd, BLKSSZGET, &blk_size) != 0) {
475 fprintf(stderr, "Failed to get GPT device block size: %s\n",
476 strerror(errno));
477 goto error;
478 }
479 gpt_header = (uint8_t*)malloc(blk_size);
480 if (!gpt_header) {
481 fprintf(stderr, "Failed to alloc memory for gpt header\n");
482 goto error;
483 }
484 if (gpt == PRIMARY_GPT)
485 gpt_header_offset = blk_size;
486 else {
487 gpt_header_offset = lseek64(fd, 0, SEEK_END) - blk_size;
488 if (gpt_header_offset < 0) {
489 fprintf(stderr, "Failed to seek to end of GPT device\n");
490 goto error;
491 }
492 }
493 if (blk_rw(fd, 0, gpt_header_offset, gpt_header, blk_size)) {
494 fprintf(stderr, "Failed to r/w gpt header\n");
495 goto error;
496 }
497 if (state == GPT_OK)
498 memcpy(gpt_header, GPT_SIGNATURE, sizeof(GPT_SIGNATURE));
499 else if (state == GPT_BAD_SIGNATURE)
500 *gpt_header = 0;
501 else {
502 fprintf(stderr, "gpt_set_state: Invalid state\n");
503 goto error;
504 }
505
506 gpt_header_size = GET_4_BYTES(gpt_header + HEADER_SIZE_OFFSET);
507
508 /* header CRC is calculated with this field cleared */
509 PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, 0);
510 crc = sparse_crc32(0, gpt_header, gpt_header_size);
511 PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, crc);
512
513 if (blk_rw(fd, 1, gpt_header_offset, gpt_header, blk_size)) {
514 fprintf(stderr, "gpt_set_state: blk write failed\n");
515 goto error;
516 }
517 return 0;
518error:
519 if(gpt_header)
520 free(gpt_header);
521 return -1;
522}
523
524int get_scsi_node_from_bootdevice(const char *bootdev_path,
525 char *sg_node_path,
526 size_t buf_size)
527{
528 char sg_dir_path[PATH_MAX] = {0};
529 char real_path[PATH_MAX] = {0};
530 DIR *scsi_dir = NULL;
531 struct dirent *de;
532 int node_found = 0;
533 if (!bootdev_path || !sg_node_path) {
534 fprintf(stderr, "%s : invalid argument\n",
535 __func__);
536 goto error;
537 }
538 if (readlink(bootdev_path, real_path, sizeof(real_path) - 1) < 0) {
539 fprintf(stderr, "failed to resolve link for %s(%s)\n",
540 bootdev_path,
541 strerror(errno));
542 goto error;
543 }
544 if(strlen(real_path) < PATH_TRUNCATE_LOC + 1){
545 fprintf(stderr, "Unrecognized path :%s:\n",
546 real_path);
547 goto error;
548 }
549 //For the safe side in case there are additional partitions on
550 //the XBL lun we truncate the name.
551 real_path[PATH_TRUNCATE_LOC] = '\0';
552 if(strlen(real_path) < LUN_NAME_START_LOC + 1){
553 fprintf(stderr, "Unrecognized truncated path :%s:\n",
554 real_path);
555 goto error;
556 }
557 //This will give us /dev/block/sdb/device/scsi_generic
558 //which contains a file sgY whose name gives us the path
559 //to /dev/sgY which we return
560 snprintf(sg_dir_path, sizeof(sg_dir_path) - 1,
561 "/sys/block/%s/device/scsi_generic",
562 &real_path[LUN_NAME_START_LOC]);
563 scsi_dir = opendir(sg_dir_path);
564 if (!scsi_dir) {
565 fprintf(stderr, "%s : Failed to open %s(%s)\n",
566 __func__,
567 sg_dir_path,
568 strerror(errno));
569 goto error;
570 }
571 while((de = readdir(scsi_dir))) {
572 if (de->d_name[0] == '.')
573 continue;
574 else if (!strncmp(de->d_name, "sg", 2)) {
575 snprintf(sg_node_path,
576 buf_size -1,
577 "/dev/%s",
578 de->d_name);
579 fprintf(stderr, "%s:scsi generic node is :%s:\n",
580 __func__,
581 sg_node_path);
582 node_found = 1;
583 break;
584 }
585 }
586 if(!node_found) {
587 fprintf(stderr,"%s: Unable to locate scsi generic node\n",
588 __func__);
589 goto error;
590 }
591 closedir(scsi_dir);
592 return 0;
593error:
594 if (scsi_dir)
595 closedir(scsi_dir);
596 return -1;
597}
598
599int set_boot_lun(char *sg_dev, uint8_t boot_lun_id)
600{
601 int fd = -1;
602 int rc;
603 struct ufs_ioctl_query_data *data = NULL;
604 size_t ioctl_data_size = sizeof(struct ufs_ioctl_query_data) + UFS_ATTR_DATA_SIZE;
605
606 data = (struct ufs_ioctl_query_data*)malloc(ioctl_data_size);
607 if (!data) {
608 fprintf(stderr, "%s: Failed to alloc query data struct\n",
609 __func__);
610 goto error;
611 }
612 memset(data, 0, ioctl_data_size);
613 data->opcode = UPIU_QUERY_OPCODE_WRITE_ATTR;
614 data->idn = QUERY_ATTR_IDN_BOOT_LU_EN;
615 data->buf_size = UFS_ATTR_DATA_SIZE;
616 data->buffer[0] = boot_lun_id;
617 fd = open(sg_dev, O_RDWR);
618 if (fd < 0) {
619 fprintf(stderr, "%s: Failed to open %s(%s)\n",
620 __func__,
621 sg_dev,
622 strerror(errno));
623 goto error;
624 }
625 rc = ioctl(fd, UFS_IOCTL_QUERY, data);
626 if (rc) {
627 fprintf(stderr, "%s: UFS query ioctl failed(%s)\n",
628 __func__,
629 strerror(errno));
630 goto error;
631 }
632 close(fd);
633 free(data);
634 return 0;
635error:
636 if (fd >= 0)
637 close(fd);
638 if (data)
639 free(data);
640 return -1;
641}
642
643//Swtich betwieen using either the primary or the backup
644//boot LUN for boot. This is required since UFS boot partitions
645//cannot have a backup GPT which is what we use for failsafe
646//updates of the other 'critical' partitions. This function will
647//not be invoked for emmc targets and on UFS targets is only required
648//to be invoked for XBL.
649//
650//The algorithm to do this is as follows:
651//- Find the real block device(eg: /dev/block/sdb) that corresponds
652// to the /dev/block/bootdevice/by-name/xbl(bak) symlink
653//
654//- Once we have the block device 'node' name(sdb in the above example)
655// use this node to to locate the scsi generic device that represents
656// it by checking the file /sys/block/sdb/device/scsi_generic/sgY
657//
658//- Once we locate sgY we call the query ioctl on /dev/sgy to switch
659//the boot lun to either LUNA or LUNB
660int gpt_utils_set_xbl_boot_partition(enum boot_chain chain)
661{
662 struct stat st;
663 ///sys/block/sdX/device/scsi_generic/
664 char sg_dev_node[PATH_MAX] = {0};
665 uint8_t boot_lun_id = 0;
666 const char *boot_dev = NULL;
667
668 if (chain == BACKUP_BOOT) {
669 boot_lun_id = BOOT_LUN_B_ID;
670 if (!stat(XBL_BACKUP, &st))
671 boot_dev = XBL_BACKUP;
672 else if (!stat(XBL_AB_SECONDARY, &st))
673 boot_dev = XBL_AB_SECONDARY;
674 else {
675 fprintf(stderr, "%s: Failed to locate secondary xbl\n",
676 __func__);
677 goto error;
678 }
679 } else if (chain == NORMAL_BOOT) {
680 boot_lun_id = BOOT_LUN_A_ID;
681 if (!stat(XBL_PRIMARY, &st))
682 boot_dev = XBL_PRIMARY;
683 else if (!stat(XBL_AB_PRIMARY, &st))
684 boot_dev = XBL_AB_PRIMARY;
685 else {
686 fprintf(stderr, "%s: Failed to locate primary xbl\n",
687 __func__);
688 goto error;
689 }
690 } else {
691 fprintf(stderr, "%s: Invalid boot chain id\n", __func__);
692 goto error;
693 }
694 //We need either both xbl and xblbak or both xbl_a and xbl_b to exist at
695 //the same time. If not the current configuration is invalid.
696 if((stat(XBL_PRIMARY, &st) ||
697 stat(XBL_BACKUP, &st)) &&
698 (stat(XBL_AB_PRIMARY, &st) ||
699 stat(XBL_AB_SECONDARY, &st))) {
700 fprintf(stderr, "%s:primary/secondary XBL prt not found(%s)\n",
701 __func__,
702 strerror(errno));
703 goto error;
704 }
705 fprintf(stderr, "%s: setting %s lun as boot lun\n",
706 __func__,
707 boot_dev);
708 if (get_scsi_node_from_bootdevice(boot_dev,
709 sg_dev_node,
710 sizeof(sg_dev_node))) {
711 fprintf(stderr, "%s: Failed to get scsi node path for xblbak\n",
712 __func__);
713 goto error;
714 }
715 if (set_boot_lun(sg_dev_node, boot_lun_id)) {
716 fprintf(stderr, "%s: Failed to set xblbak as boot partition\n",
717 __func__);
718 goto error;
719 }
720 return 0;
721error:
722 return -1;
723}
724
725int gpt_utils_is_ufs_device()
726{
727 char bootdevice[PROPERTY_VALUE_MAX] = {0};
728 property_get("ro.boot.bootdevice", bootdevice, "N/A");
729 if (strlen(bootdevice) < strlen(".ufshc") + 1)
730 return 0;
731 return (!strncmp(&bootdevice[strlen(bootdevice) - strlen(".ufshc")],
732 ".ufshc",
733 sizeof(".ufshc")));
734}
735//dev_path is the path to the block device that contains the GPT image that
736//needs to be updated. This would be the device which holds one or more critical
737//boot partitions and their backups. In the case of EMMC this function would
738//be invoked only once on /dev/block/mmcblk1 since it holds the GPT image
739//containing all the partitions For UFS devices it could potentially be
740//invoked multiple times, once for each LUN containing critical image(s) and
741//their backups
742int prepare_partitions(enum boot_update_stage stage, const char *dev_path)
743{
744 int r = 0;
745 int fd = -1;
746 int is_ufs = gpt_utils_is_ufs_device();
747 enum gpt_state gpt_prim, gpt_second;
748 enum boot_update_stage internal_stage;
749 struct stat xbl_partition_stat;
750 struct stat ufs_dir_stat;
751
752 if (!dev_path) {
753 fprintf(stderr, "%s: Invalid dev_path\n",
754 __func__);
755 r = -1;
756 goto EXIT;
757 }
758 fd = open(dev_path, O_RDWR);
759 if (fd < 0) {
760 fprintf(stderr, "%s: Opening '%s' failed: %s\n",
761 __func__,
762 BLK_DEV_FILE,
763 strerror(errno));
764 r = -1;
765 goto EXIT;
766 }
767 r = gpt_get_state(fd, PRIMARY_GPT, &gpt_prim) ||
768 gpt_get_state(fd, SECONDARY_GPT, &gpt_second);
769 if (r) {
770 fprintf(stderr, "%s: Getting GPT headers state failed\n",
771 __func__);
772 goto EXIT;
773 }
774
775 /* These 2 combinations are unexpected and unacceptable */
776 if (gpt_prim == GPT_BAD_CRC || gpt_second == GPT_BAD_CRC) {
777 fprintf(stderr, "%s: GPT headers CRC corruption detected, aborting\n",
778 __func__);
779 r = -1;
780 goto EXIT;
781 }
782 if (gpt_prim == GPT_BAD_SIGNATURE && gpt_second == GPT_BAD_SIGNATURE) {
783 fprintf(stderr, "%s: Both GPT headers corrupted, aborting\n",
784 __func__);
785 r = -1;
786 goto EXIT;
787 }
788
789 /* Check internal update stage according GPT headers' state */
790 if (gpt_prim == GPT_OK && gpt_second == GPT_OK)
791 internal_stage = UPDATE_MAIN;
792 else if (gpt_prim == GPT_BAD_SIGNATURE)
793 internal_stage = UPDATE_BACKUP;
794 else if (gpt_second == GPT_BAD_SIGNATURE)
795 internal_stage = UPDATE_FINALIZE;
796 else {
797 fprintf(stderr, "%s: Abnormal GPTs state: primary (%d), secondary (%d), "
798 "aborting\n", __func__, gpt_prim, gpt_second);
799 r = -1;
800 goto EXIT;
801 }
802
803 /* Stage already set - ready for update, exitting */
804 if ((int) stage == (int) internal_stage - 1)
805 goto EXIT;
806 /* Unexpected stage given */
807 if (stage != internal_stage) {
808 r = -1;
809 goto EXIT;
810 }
811
812 switch (stage) {
813 case UPDATE_MAIN:
814 if (is_ufs) {
815 if(stat(XBL_PRIMARY, &xbl_partition_stat)||
816 stat(XBL_BACKUP, &xbl_partition_stat)){
817 //Non fatal error. Just means this target does not
818 //use XBL but relies on sbl whose update is handled
819 //by the normal methods.
820 fprintf(stderr, "%s: xbl part not found(%s).Assuming sbl in use\n",
821 __func__,
822 strerror(errno));
823 } else {
824 //Switch the boot lun so that backup boot LUN is used
825 r = gpt_utils_set_xbl_boot_partition(BACKUP_BOOT);
826 if(r){
827 fprintf(stderr, "%s: Failed to set xbl backup partition as boot\n",
828 __func__);
829 goto EXIT;
830 }
831 }
832 }
833 //Fix up the backup GPT table so that it actually points to
834 //the backup copy of the boot critical images
835 fprintf(stderr, "%s: Preparing for primary partition update\n",
836 __func__);
837 r = gpt2_set_boot_chain(fd, BACKUP_BOOT);
838 if (r) {
839 if (r < 0)
840 fprintf(stderr,
841 "%s: Setting secondary GPT to backup boot failed\n",
842 __func__);
843 /* No backup partitions - do not corrupt GPT, do not flag error */
844 else
845 r = 0;
846 goto EXIT;
847 }
848 //corrupt the primary GPT so that the backup(which now points to
849 //the backup boot partitions is used)
850 r = gpt_set_state(fd, PRIMARY_GPT, GPT_BAD_SIGNATURE);
851 if (r) {
852 fprintf(stderr, "%s: Corrupting primary GPT header failed\n",
853 __func__);
854 goto EXIT;
855 }
856 break;
857 case UPDATE_BACKUP:
858 if (is_ufs) {
859 if(stat(XBL_PRIMARY, &xbl_partition_stat)||
860 stat(XBL_BACKUP, &xbl_partition_stat)){
861 //Non fatal error. Just means this target does not
862 //use XBL but relies on sbl whose update is handled
863 //by the normal methods.
864 fprintf(stderr, "%s: xbl part not found(%s).Assuming sbl in use\n",
865 __func__,
866 strerror(errno));
867 } else {
868 //Switch the boot lun so that backup boot LUN is used
869 r = gpt_utils_set_xbl_boot_partition(NORMAL_BOOT);
870 if(r) {
871 fprintf(stderr, "%s: Failed to set xbl backup partition as boot\n",
872 __func__);
873 goto EXIT;
874 }
875 }
876 }
877 //Fix the primary GPT header so that is used
878 fprintf(stderr, "%s: Preparing for backup partition update\n",
879 __func__);
880 r = gpt_set_state(fd, PRIMARY_GPT, GPT_OK);
881 if (r) {
882 fprintf(stderr, "%s: Fixing primary GPT header failed\n",
883 __func__);
884 goto EXIT;
885 }
886 //Corrupt the scondary GPT header
887 r = gpt_set_state(fd, SECONDARY_GPT, GPT_BAD_SIGNATURE);
888 if (r) {
889 fprintf(stderr, "%s: Corrupting secondary GPT header failed\n",
890 __func__);
891 goto EXIT;
892 }
893 break;
894 case UPDATE_FINALIZE:
895 //Undo the changes we had made in the UPDATE_MAIN stage so that the
896 //primary/backup GPT headers once again point to the same set of
897 //partitions
898 fprintf(stderr, "%s: Finalizing partitions\n",
899 __func__);
900 r = gpt2_set_boot_chain(fd, NORMAL_BOOT);
901 if (r < 0) {
902 fprintf(stderr, "%s: Setting secondary GPT to normal boot failed\n",
903 __func__);
904 goto EXIT;
905 }
906
907 r = gpt_set_state(fd, SECONDARY_GPT, GPT_OK);
908 if (r) {
909 fprintf(stderr, "%s: Fixing secondary GPT header failed\n",
910 __func__);
911 goto EXIT;
912 }
913 break;
914 default:;
915 }
916
917EXIT:
918 if (fd >= 0) {
919 fsync(fd);
920 close(fd);
921 }
922 return r;
923}
924
925int add_lun_to_update_list(char *lun_path, struct update_data *dat)
926{
927 uint32_t i = 0;
928 struct stat st;
929 if (!lun_path || !dat){
930 fprintf(stderr, "%s: Invalid data",
931 __func__);
932 return -1;
933 }
934 if (stat(lun_path, &st)) {
935 fprintf(stderr, "%s: Unable to access %s. Skipping adding to list",
936 __func__,
937 lun_path);
938 return -1;
939 }
940 if (dat->num_valid_entries == 0) {
941 fprintf(stderr, "%s: Copying %s into lun_list[%d]\n",
942 __func__,
943 lun_path,
944 i);
945 strlcpy(dat->lun_list[0], lun_path,
946 PATH_MAX * sizeof(char));
947 dat->num_valid_entries = 1;
948 } else {
949 for (i = 0; (i < dat->num_valid_entries) &&
950 (dat->num_valid_entries < MAX_LUNS - 1); i++) {
951 //Check if the current LUN is not already part
952 //of the lun list
953 if (!strncmp(lun_path,dat->lun_list[i],
954 strlen(dat->lun_list[i]))) {
955 //LUN already in list..Return
956 return 0;
957 }
958 }
959 fprintf(stderr, "%s: Copying %s into lun_list[%d]\n",
960 __func__,
961 lun_path,
962 dat->num_valid_entries);
963 //Add LUN path lun list
964 strlcpy(dat->lun_list[dat->num_valid_entries], lun_path,
965 PATH_MAX * sizeof(char));
966 dat->num_valid_entries++;
967 }
968 return 0;
969}
970
971int prepare_boot_update(enum boot_update_stage stage)
972{
973 int r, fd;
974 int is_ufs = gpt_utils_is_ufs_device();
975 struct stat ufs_dir_stat;
976 struct update_data data;
977 int rcode = 0;
978 uint32_t i = 0;
979 int is_error = 0;
980 const char ptn_swap_list[][MAX_GPT_NAME_SIZE] = { PTN_SWAP_LIST };
981 //Holds /dev/block/bootdevice/by-name/*bak entry
982 char buf[PATH_MAX] = {0};
983 //Holds the resolved path of the symlink stored in buf
984 char real_path[PATH_MAX] = {0};
985
986 if (!is_ufs) {
987 //emmc device. Just pass in path to mmcblk0
988 return prepare_partitions(stage, BLK_DEV_FILE);
989 } else {
990 //Now we need to find the list of LUNs over
991 //which the boot critical images are spread
992 //and set them up for failsafe updates.To do
993 //this we find out where the symlinks for the
994 //each of the paths under
995 ///dev/block/bootdevice/by-name/PTN_SWAP_LIST
996 //actually point to.
997 fprintf(stderr, "%s: Running on a UFS device\n",
998 __func__);
999 memset(&data, '\0', sizeof(struct update_data));
1000 for (i=0; i < ARRAY_SIZE(ptn_swap_list); i++) {
1001 //XBL on UFS does not follow the convention
1002 //of being loaded based on well known GUID'S.
1003 //We take care of switching the UFS boot LUN
1004 //explicitly later on.
1005 if (!strncmp(ptn_swap_list[i],
1006 PTN_XBL,
1007 strlen(PTN_XBL)))
1008 continue;
1009 snprintf(buf, sizeof(buf),
1010 "%s/%sbak",
1011 BOOT_DEV_DIR,
1012 ptn_swap_list[i]);
1013 if (stat(buf, &ufs_dir_stat)) {
1014 continue;
1015 }
1016 if (readlink(buf, real_path, sizeof(real_path) - 1) < 0)
1017 {
1018 fprintf(stderr, "%s: readlink error. Skipping %s",
1019 __func__,
1020 strerror(errno));
1021 } else {
1022 if(strlen(real_path) < PATH_TRUNCATE_LOC + 1){
1023 fprintf(stderr, "Unknown path.Skipping :%s:\n",
1024 real_path);
1025 } else {
1026 real_path[PATH_TRUNCATE_LOC] = '\0';
1027 add_lun_to_update_list(real_path, &data);
1028 }
1029 }
1030 memset(buf, '\0', sizeof(buf));
1031 memset(real_path, '\0', sizeof(real_path));
1032 }
1033 for (i=0; i < data.num_valid_entries; i++) {
1034 fprintf(stderr, "%s: Preparing %s for update stage %d\n",
1035 __func__,
1036 data.lun_list[i],
1037 stage);
1038 rcode = prepare_partitions(stage, data.lun_list[i]);
1039 if (rcode != 0)
1040 {
1041 fprintf(stderr, "%s: Failed to prepare %s.Continuing..\n",
1042 __func__,
1043 data.lun_list[i]);
1044 is_error = 1;
1045 }
1046 }
1047 }
1048 if (is_error)
1049 return -1;
1050 return 0;
1051}
1052
1053//Given a parttion name(eg: rpm) get the path to the block device that
1054//represents the GPT disk the partition resides on. In the case of emmc it
1055//would be the default emmc dev(/dev/block/mmcblk0). In the case of UFS we look
1056//through the /dev/block/bootdevice/by-name/ tree for partname, and resolve
1057//the path to the LUN from there.
1058static int get_dev_path_from_partition_name(const char *partname,
1059 char *buf,
1060 size_t buflen)
1061{
1062 struct stat st;
1063 char path[PATH_MAX] = {0};
1064 if (!partname || !buf || buflen < ((PATH_TRUNCATE_LOC) + 1)) {
1065 ALOGE("%s: Invalid argument", __func__);
1066 goto error;
1067 }
1068 if (gpt_utils_is_ufs_device()) {
1069 //Need to find the lun that holds partition partname
1070 snprintf(path, sizeof(path),
1071 "%s/%s",
1072 BOOT_DEV_DIR,
1073 partname);
1074 if (stat(path, &st)) {
1075 goto error;
1076 }
1077 if (readlink(path, buf, buflen) < 0)
1078 {
1079 goto error;
1080 } else {
1081 buf[PATH_TRUNCATE_LOC] = '\0';
1082 }
1083 } else {
1084 snprintf(buf, buflen, BLK_DEV_FILE);
1085 }
1086 return 0;
1087
1088error:
1089 return -1;
1090}
1091
1092int gpt_utils_get_partition_map(vector<string>& ptn_list,
1093 map<string, vector<string>>& partition_map) {
1094 char devpath[PATH_MAX] = {'\0'};
1095 map<string, vector<string>>::iterator it;
1096 if (ptn_list.size() < 1) {
1097 fprintf(stderr, "%s: Invalid ptn list\n", __func__);
1098 goto error;
1099 }
1100 //Go through the passed in list
1101 for (uint32_t i = 0; i < ptn_list.size(); i++)
1102 {
1103 //Key in the map is the path to the device that holds the
1104 //partition
1105 if (get_dev_path_from_partition_name(ptn_list[i].c_str(),
1106 devpath,
1107 sizeof(devpath))) {
1108 //Not necessarily an error. The partition may just
1109 //not be present.
1110 continue;
1111 }
1112 string path = devpath;
1113 it = partition_map.find(path);
1114 if (it != partition_map.end()) {
1115 it->second.push_back(ptn_list[i]);
1116 } else {
1117 vector<string> str_vec;
1118 str_vec.push_back( ptn_list[i]);
1119 partition_map.insert(pair<string, vector<string>>
1120 (path, str_vec));
1121 }
1122 memset(devpath, '\0', sizeof(devpath));
1123 }
1124 return 0;
1125error:
1126 return -1;
1127}
1128
1129//Get the block size of the disk represented by decsriptor fd
1130static uint32_t gpt_get_block_size(int fd)
1131{
1132 uint32_t block_size = 0;
1133 if (fd < 0) {
1134 ALOGE("%s: invalid descriptor",
1135 __func__);
1136 goto error;
1137 }
1138 if (ioctl(fd, BLKSSZGET, &block_size) != 0) {
1139 ALOGE("%s: Failed to get GPT dev block size : %s",
1140 __func__,
1141 strerror(errno));
1142 goto error;
1143 }
1144 return block_size;
1145error:
1146 return 0;
1147}
1148
1149//Write the GPT header present in the passed in buffer back to the
1150//disk represented by fd
1151static int gpt_set_header(uint8_t *gpt_header, int fd,
1152 enum gpt_instance instance)
1153{
1154 uint32_t block_size = 0;
1155 off64_t gpt_header_offset = 0;
1156 if (!gpt_header || fd < 0) {
1157 ALOGE("%s: Invalid arguments",
1158 __func__);
1159 goto error;
1160 }
1161 block_size = gpt_get_block_size(fd);
1162 if (block_size == 0) {
1163 ALOGE("%s: Failed to get block size", __func__);
1164 goto error;
1165 }
1166 if (instance == PRIMARY_GPT)
1167 gpt_header_offset = block_size;
1168 else
1169 gpt_header_offset = lseek64(fd, 0, SEEK_END) - block_size;
1170 if (gpt_header_offset <= 0) {
1171 ALOGE("%s: Failed to get gpt header offset",__func__);
1172 goto error;
1173 }
1174 if (blk_rw(fd, 1, gpt_header_offset, gpt_header, block_size)) {
1175 ALOGE("%s: Failed to write back GPT header", __func__);
1176 goto error;
1177 }
1178 return 0;
1179error:
1180 return -1;
1181}
1182
1183//Read out the GPT header for the disk that contains the partition partname
1184static uint8_t* gpt_get_header(const char *partname, enum gpt_instance instance)
1185{
1186 uint8_t* hdr = NULL;
1187 char devpath[PATH_MAX] = {0};
1188 int64_t hdr_offset = 0;
1189 uint32_t block_size = 0;
1190 int fd = -1;
1191 if (!partname) {
1192 ALOGE("%s: Invalid partition name", __func__);
1193 goto error;
1194 }
1195 if (get_dev_path_from_partition_name(partname, devpath, sizeof(devpath))
1196 != 0) {
1197 ALOGE("%s: Failed to resolve path for %s",
1198 __func__,
1199 partname);
1200 goto error;
1201 }
1202 fd = open(devpath, O_RDWR);
1203 if (fd < 0) {
1204 ALOGE("%s: Failed to open %s : %s",
1205 __func__,
1206 devpath,
1207 strerror(errno));
1208 goto error;
1209 }
1210 block_size = gpt_get_block_size(fd);
1211 if (block_size == 0)
1212 {
1213 ALOGE("%s: Failed to get gpt block size for %s",
1214 __func__,
1215 partname);
1216 goto error;
1217 }
1218
1219 hdr = (uint8_t*)malloc(block_size);
1220 if (!hdr) {
1221 ALOGE("%s: Failed to allocate memory for gpt header",
1222 __func__);
1223 }
1224 if (instance == PRIMARY_GPT)
1225 hdr_offset = block_size;
1226 else {
1227 hdr_offset = lseek64(fd, 0, SEEK_END) - block_size;
1228 }
1229 if (hdr_offset < 0) {
1230 ALOGE("%s: Failed to get gpt header offset",
1231 __func__);
1232 goto error;
1233 }
1234 if (blk_rw(fd, 0, hdr_offset, hdr, block_size)) {
1235 ALOGE("%s: Failed to read GPT header from device",
1236 __func__);
1237 goto error;
1238 }
1239 close(fd);
1240 return hdr;
1241error:
1242 if (fd >= 0)
1243 close(fd);
1244 if (hdr)
1245 free(hdr);
1246 return NULL;
1247}
1248
1249//Returns the partition entry array based on the
1250//passed in buffer which contains the gpt header.
1251//The fd here is the descriptor for the 'disk' which
1252//holds the partition
1253static uint8_t* gpt_get_pentry_arr(uint8_t *hdr, int fd)
1254{
1255 uint64_t pentries_start = 0;
1256 uint32_t pentry_size = 0;
1257 uint32_t block_size = 0;
1258 uint32_t pentries_arr_size = 0;
1259 uint8_t *pentry_arr = NULL;
1260 int rc = 0;
1261 if (!hdr) {
1262 ALOGE("%s: Invalid header", __func__);
1263 goto error;
1264 }
1265 if (fd < 0) {
1266 ALOGE("%s: Invalid fd", __func__);
1267 goto error;
1268 }
1269 block_size = gpt_get_block_size(fd);
1270 if (!block_size) {
1271 ALOGE("%s: Failed to get gpt block size for",
1272 __func__);
1273 goto error;
1274 }
1275 pentries_start = GET_8_BYTES(hdr + PENTRIES_OFFSET) * block_size;
1276 pentry_size = GET_4_BYTES(hdr + PENTRY_SIZE_OFFSET);
1277 pentries_arr_size =
1278 GET_4_BYTES(hdr + PARTITION_COUNT_OFFSET) * pentry_size;
1279 pentry_arr = (uint8_t*)calloc(1, pentries_arr_size);
1280 if (!pentry_arr) {
1281 ALOGE("%s: Failed to allocate memory for partition array",
1282 __func__);
1283 goto error;
1284 }
1285 rc = blk_rw(fd, 0,
1286 pentries_start,
1287 pentry_arr,
1288 pentries_arr_size);
1289 if (rc) {
1290 ALOGE("%s: Failed to read partition entry array",
1291 __func__);
1292 goto error;
1293 }
1294 return pentry_arr;
1295error:
1296 if (pentry_arr)
1297 free(pentry_arr);
1298 return NULL;
1299}
1300
1301static int gpt_set_pentry_arr(uint8_t *hdr, int fd, uint8_t* arr)
1302{
1303 uint32_t block_size = 0;
1304 uint64_t pentries_start = 0;
1305 uint32_t pentry_size = 0;
1306 uint32_t pentries_arr_size = 0;
1307 int rc = 0;
1308 if (!hdr || fd < 0 || !arr) {
1309 ALOGE("%s: Invalid argument", __func__);
1310 goto error;
1311 }
1312 block_size = gpt_get_block_size(fd);
1313 if (!block_size) {
1314 ALOGE("%s: Failed to get gpt block size for",
1315 __func__);
1316 goto error;
1317 }
1318 pentries_start = GET_8_BYTES(hdr + PENTRIES_OFFSET) * block_size;
1319 pentry_size = GET_4_BYTES(hdr + PENTRY_SIZE_OFFSET);
1320 pentries_arr_size =
1321 GET_4_BYTES(hdr + PARTITION_COUNT_OFFSET) * pentry_size;
1322 rc = blk_rw(fd, 1,
1323 pentries_start,
1324 arr,
1325 pentries_arr_size);
1326 if (rc) {
1327 ALOGE("%s: Failed to read partition entry array",
1328 __func__);
1329 goto error;
1330 }
1331 return 0;
1332error:
1333 return -1;
1334}
1335
1336
1337
1338//Allocate a handle used by calls to the "gpt_disk" api's
1339struct gpt_disk * gpt_disk_alloc()
1340{
1341 struct gpt_disk *disk;
1342 disk = (struct gpt_disk *)malloc(sizeof(struct gpt_disk));
1343 if (!disk) {
1344 ALOGE("%s: Failed to allocate memory", __func__);
1345 goto end;
1346 }
1347 memset(disk, 0, sizeof(struct gpt_disk));
1348end:
1349 return disk;
1350}
1351
1352//Free previously allocated/initialized handle
1353void gpt_disk_free(struct gpt_disk *disk)
1354{
1355 if (!disk)
1356 return;
1357 if (disk->hdr)
1358 free(disk->hdr);
1359 if (disk->hdr_bak)
1360 free(disk->hdr_bak);
1361 if (disk->pentry_arr)
1362 free(disk->pentry_arr);
1363 if (disk->pentry_arr_bak)
1364 free(disk->pentry_arr_bak);
1365 free(disk);
1366 return;
1367}
1368
1369//fills up the passed in gpt_disk struct with information about the
1370//disk represented by path dev. Returns 0 on success and -1 on error.
1371int gpt_disk_get_disk_info(const char *dev, struct gpt_disk *dsk)
1372{
1373 struct gpt_disk *disk = NULL;
1374 int fd = -1;
1375 uint32_t gpt_header_size = 0;
1376
1377 if (!dsk || !dev) {
1378 ALOGE("%s: Invalid arguments", __func__);
1379 goto error;
1380 }
1381 disk = dsk;
1382 disk->hdr = gpt_get_header(dev, PRIMARY_GPT);
1383 if (!disk->hdr) {
1384 ALOGE("%s: Failed to get primary header", __func__);
1385 goto error;
1386 }
1387 gpt_header_size = GET_4_BYTES(disk->hdr + HEADER_SIZE_OFFSET);
1388 disk->hdr_crc = sparse_crc32(0, disk->hdr, gpt_header_size);
1389 disk->hdr_bak = gpt_get_header(dev, SECONDARY_GPT);
1390 if (!disk->hdr_bak) {
1391 ALOGE("%s: Failed to get backup header", __func__);
1392 goto error;
1393 }
1394 disk->hdr_bak_crc = sparse_crc32(0, disk->hdr_bak, gpt_header_size);
1395
1396 //Descriptor for the block device. We will use this for further
1397 //modifications to the partition table
1398 if (get_dev_path_from_partition_name(dev,
1399 disk->devpath,
1400 sizeof(disk->devpath)) != 0) {
1401 ALOGE("%s: Failed to resolve path for %s",
1402 __func__,
1403 dev);
1404 goto error;
1405 }
1406 fd = open(disk->devpath, O_RDWR);
1407 if (fd < 0) {
1408 ALOGE("%s: Failed to open %s: %s",
1409 __func__,
1410 disk->devpath,
1411 strerror(errno));
1412 goto error;
1413 }
1414 disk->pentry_arr = gpt_get_pentry_arr(disk->hdr, fd);
1415 if (!disk->pentry_arr) {
1416 ALOGE("%s: Failed to obtain partition entry array",
1417 __func__);
1418 goto error;
1419 }
1420 disk->pentry_arr_bak = gpt_get_pentry_arr(disk->hdr_bak, fd);
1421 if (!disk->pentry_arr_bak) {
1422 ALOGE("%s: Failed to obtain backup partition entry array",
1423 __func__);
1424 goto error;
1425 }
1426 disk->pentry_size = GET_4_BYTES(disk->hdr + PENTRY_SIZE_OFFSET);
1427 disk->pentry_arr_size =
1428 GET_4_BYTES(disk->hdr + PARTITION_COUNT_OFFSET) *
1429 disk->pentry_size;
1430 disk->pentry_arr_crc = GET_4_BYTES(disk->hdr + PARTITION_CRC_OFFSET);
1431 disk->pentry_arr_bak_crc = GET_4_BYTES(disk->hdr_bak +
1432 PARTITION_CRC_OFFSET);
1433 disk->block_size = gpt_get_block_size(fd);
1434 close(fd);
1435 disk->is_initialized = GPT_DISK_INIT_MAGIC;
1436 return 0;
1437error:
1438 if (fd >= 0)
1439 close(fd);
1440 return -1;
1441}
1442
1443//Get pointer to partition entry from a allocated gpt_disk structure
1444uint8_t* gpt_disk_get_pentry(struct gpt_disk *disk,
1445 const char *partname,
1446 enum gpt_instance instance)
1447{
1448 uint8_t *ptn_arr = NULL;
1449 if (!disk || !partname || disk->is_initialized != GPT_DISK_INIT_MAGIC) {
1450 ALOGE("%s: Invalid argument",__func__);
1451 goto error;
1452 }
1453 ptn_arr = (instance == PRIMARY_GPT) ?
1454 disk->pentry_arr : disk->pentry_arr_bak;
1455 return (gpt_pentry_seek(partname, ptn_arr,
1456 ptn_arr + disk->pentry_arr_size ,
1457 disk->pentry_size));
1458error:
1459 return NULL;
1460}
1461
1462//Update CRC values for the various components of the gpt_disk
1463//structure. This function should be called after any of the fields
1464//have been updated before the structure contents are written back to
1465//disk.
1466int gpt_disk_update_crc(struct gpt_disk *disk)
1467{
1468 uint32_t gpt_header_size = 0;
1469 if (!disk || (disk->is_initialized != GPT_DISK_INIT_MAGIC)) {
1470 ALOGE("%s: invalid argument", __func__);
1471 goto error;
1472 }
1473 //Recalculate the CRC of the primary partiton array
1474 disk->pentry_arr_crc = sparse_crc32(0,
1475 disk->pentry_arr,
1476 disk->pentry_arr_size);
1477 //Recalculate the CRC of the backup partition array
1478 disk->pentry_arr_bak_crc = sparse_crc32(0,
1479 disk->pentry_arr_bak,
1480 disk->pentry_arr_size);
1481 //Update the partition CRC value in the primary GPT header
1482 PUT_4_BYTES(disk->hdr + PARTITION_CRC_OFFSET, disk->pentry_arr_crc);
1483 //Update the partition CRC value in the backup GPT header
1484 PUT_4_BYTES(disk->hdr_bak + PARTITION_CRC_OFFSET,
1485 disk->pentry_arr_bak_crc);
1486 //Update the CRC value of the primary header
1487 gpt_header_size = GET_4_BYTES(disk->hdr + HEADER_SIZE_OFFSET);
1488 //Header CRC is calculated with its own CRC field set to 0
1489 PUT_4_BYTES(disk->hdr + HEADER_CRC_OFFSET, 0);
1490 PUT_4_BYTES(disk->hdr_bak + HEADER_CRC_OFFSET, 0);
1491 disk->hdr_crc = sparse_crc32(0, disk->hdr, gpt_header_size);
1492 disk->hdr_bak_crc = sparse_crc32(0, disk->hdr_bak, gpt_header_size);
1493 PUT_4_BYTES(disk->hdr + HEADER_CRC_OFFSET, disk->hdr_crc);
1494 PUT_4_BYTES(disk->hdr_bak + HEADER_CRC_OFFSET, disk->hdr_bak_crc);
1495 return 0;
1496error:
1497 return -1;
1498}
1499
1500//Write the contents of struct gpt_disk back to the actual disk
1501int gpt_disk_commit(struct gpt_disk *disk)
1502{
1503 int fd = -1;
1504 if (!disk || (disk->is_initialized != GPT_DISK_INIT_MAGIC)){
1505 ALOGE("%s: Invalid args", __func__);
1506 goto error;
1507 }
1508 fd = open(disk->devpath, O_RDWR);
1509 if (fd < 0) {
1510 ALOGE("%s: Failed to open %s: %s",
1511 __func__,
1512 disk->devpath,
1513 strerror(errno));
1514 goto error;
1515 }
1516 //Write the primary header
1517 if(gpt_set_header(disk->hdr, fd, PRIMARY_GPT) != 0) {
1518 ALOGE("%s: Failed to update primary GPT header",
1519 __func__);
1520 goto error;
1521 }
1522 //Write back the primary partition array
1523 if (gpt_set_pentry_arr(disk->hdr, fd, disk->pentry_arr)) {
1524 ALOGE("%s: Failed to write primary GPT partition arr",
1525 __func__);
1526 goto error;
1527 }
1528 //Write back the secondary header
1529 if(gpt_set_header(disk->hdr_bak, fd, SECONDARY_GPT) != 0) {
1530 ALOGE("%s: Failed to update secondary GPT header",
1531 __func__);
1532 goto error;
1533 }
1534 //Write back the secondary partition array
1535 if (gpt_set_pentry_arr(disk->hdr_bak, fd, disk->pentry_arr_bak)) {
1536 ALOGE("%s: Failed to write secondary GPT partition arr",
1537 __func__);
1538 goto error;
1539 }
1540 close(fd);
1541 return 0;
1542error:
1543 if (fd >= 0)
1544 close(fd);
1545 return -1;
1546}