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