Home | History | Annotate | Download | only in gpt-utils
      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 #include <endian.h>
     58 #include <zlib.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  ******************************************************************************/
    114 using namespace std;
    115 enum 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
    122 struct 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  */
    145 static 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 %" PRIi64 " 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  */
    186 static 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 / 2];
    197         unsigned i;
    198 
    199         /* Partition names in GPT are UTF-16 - ignoring UTF-16 2nd byte */
    200         for (i = 0; i < sizeof(name8); 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  */
    225 static 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  */
    282 static 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 = 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 = 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 = 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 
    379 EXIT:
    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  */
    400 static 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 (crc32(0, gpt_header, gpt_header_size) != crc)
    442         *state = GPT_BAD_CRC;
    443     free(gpt_header);
    444     return 0;
    445 error:
    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  */
    466 static 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 = 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;
    518 error:
    519     if(gpt_header)
    520            free(gpt_header);
    521     return -1;
    522 }
    523 
    524 int 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;
    593 error:
    594         if (scsi_dir)
    595                 closedir(scsi_dir);
    596         return -1;
    597 }
    598 
    599 int 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;
    635 error:
    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
    660 int 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;
    721 error:
    722         return -1;
    723 }
    724 
    725 int 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
    742 int 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 
    917 EXIT:
    918     if (fd >= 0) {
    919        fsync(fd);
    920        close(fd);
    921     }
    922     return r;
    923 }
    924 
    925 int 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 
    971 int 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/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.
   1058 static 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, "/dev/mmcblk0");
   1085         }
   1086         return 0;
   1087 
   1088 error:
   1089         return -1;
   1090 }
   1091 
   1092 int 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                 return -1;
   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;
   1125 }
   1126 
   1127 //Get the block size of the disk represented by decsriptor fd
   1128 static uint32_t gpt_get_block_size(int fd)
   1129 {
   1130         uint32_t block_size = 0;
   1131         if (fd < 0) {
   1132                 ALOGE("%s: invalid descriptor",
   1133                                 __func__);
   1134                 goto error;
   1135         }
   1136         if (ioctl(fd, BLKSSZGET, &block_size) != 0) {
   1137                 ALOGE("%s: Failed to get GPT dev block size : %s",
   1138                                 __func__,
   1139                                 strerror(errno));
   1140                 goto error;
   1141         }
   1142         return block_size;
   1143 error:
   1144         return 0;
   1145 }
   1146 
   1147 //Write the GPT header present in the passed in buffer back to the
   1148 //disk represented by fd
   1149 static int gpt_set_header(uint8_t *gpt_header, int fd,
   1150                 enum gpt_instance instance)
   1151 {
   1152         uint32_t block_size = 0;
   1153         off_t gpt_header_offset = 0;
   1154         if (!gpt_header || fd < 0) {
   1155                 ALOGE("%s: Invalid arguments",
   1156                                 __func__);
   1157                 goto error;
   1158         }
   1159         block_size = gpt_get_block_size(fd);
   1160         ALOGI("%s: Block size is : %d", __func__, block_size);
   1161         if (block_size == 0) {
   1162                 ALOGE("%s: Failed to get block size", __func__);
   1163                 goto error;
   1164         }
   1165         if (instance == PRIMARY_GPT)
   1166                 gpt_header_offset = block_size;
   1167         else
   1168                 gpt_header_offset = lseek64(fd, 0, SEEK_END) - block_size;
   1169         if (gpt_header_offset <= 0) {
   1170                 ALOGE("%s: Failed to get gpt header offset",__func__);
   1171                 goto error;
   1172         }
   1173         ALOGI("%s: Writing back header to offset %ld", __func__,
   1174                 gpt_header_offset);
   1175         if (blk_rw(fd, 1, gpt_header_offset, gpt_header, block_size)) {
   1176                 ALOGE("%s: Failed to write back GPT header", __func__);
   1177                 goto error;
   1178         }
   1179         return 0;
   1180 error:
   1181         return -1;
   1182 }
   1183 
   1184 //Read out the GPT header for the disk that contains the partition partname
   1185 static uint8_t* gpt_get_header(const char *partname, enum gpt_instance instance)
   1186 {
   1187         uint8_t* hdr = NULL;
   1188         char devpath[PATH_MAX] = {0};
   1189         int64_t hdr_offset = 0;
   1190         uint32_t block_size = 0;
   1191         int fd = -1;
   1192         if (!partname) {
   1193                 ALOGE("%s: Invalid partition name", __func__);
   1194                 goto error;
   1195         }
   1196         if (get_dev_path_from_partition_name(partname, devpath, sizeof(devpath))
   1197                         != 0) {
   1198                 ALOGE("%s: Failed to resolve path for %s",
   1199                                 __func__,
   1200                                 partname);
   1201                 goto error;
   1202         }
   1203         fd = open(devpath, O_RDWR);
   1204         if (fd < 0) {
   1205                 ALOGE("%s: Failed to open %s : %s",
   1206                                 __func__,
   1207                                 devpath,
   1208                                 strerror(errno));
   1209                 goto error;
   1210         }
   1211         block_size = gpt_get_block_size(fd);
   1212         if (block_size == 0)
   1213         {
   1214                 ALOGE("%s: Failed to get gpt block size for %s",
   1215                                 __func__,
   1216                                 partname);
   1217                 goto error;
   1218         }
   1219 
   1220         hdr = (uint8_t*)malloc(block_size);
   1221         if (!hdr) {
   1222                 ALOGE("%s: Failed to allocate memory for gpt header",
   1223                                 __func__);
   1224         }
   1225         if (instance == PRIMARY_GPT)
   1226                 hdr_offset = block_size;
   1227         else {
   1228                 hdr_offset = lseek64(fd, 0, SEEK_END) - block_size;
   1229         }
   1230         if (hdr_offset < 0) {
   1231                 ALOGE("%s: Failed to get gpt header offset",
   1232                                 __func__);
   1233                 goto error;
   1234         }
   1235         if (blk_rw(fd, 0, hdr_offset, hdr, block_size)) {
   1236                 ALOGE("%s: Failed to read GPT header from device",
   1237                                 __func__);
   1238                 goto error;
   1239         }
   1240         close(fd);
   1241         return hdr;
   1242 error:
   1243         if (fd >= 0)
   1244                 close(fd);
   1245         if (hdr)
   1246                 free(hdr);
   1247         return NULL;
   1248 }
   1249 
   1250 //Returns the partition entry array based on the
   1251 //passed in buffer which contains the gpt header.
   1252 //The fd here is the descriptor for the 'disk' which
   1253 //holds the partition
   1254 static uint8_t* gpt_get_pentry_arr(uint8_t *hdr, int fd)
   1255 {
   1256         uint64_t pentries_start = 0;
   1257         uint32_t pentry_size = 0;
   1258         uint32_t block_size = 0;
   1259         uint32_t pentries_arr_size = 0;
   1260         uint8_t *pentry_arr = NULL;
   1261         int rc = 0;
   1262         if (!hdr) {
   1263                 ALOGE("%s: Invalid header", __func__);
   1264                 goto error;
   1265         }
   1266         if (fd < 0) {
   1267                 ALOGE("%s: Invalid fd", __func__);
   1268                 goto error;
   1269         }
   1270         block_size = gpt_get_block_size(fd);
   1271         if (!block_size) {
   1272                 ALOGE("%s: Failed to get gpt block size for",
   1273                                 __func__);
   1274                 goto error;
   1275         }
   1276         pentries_start = GET_8_BYTES(hdr + PENTRIES_OFFSET) * block_size;
   1277         pentry_size = GET_4_BYTES(hdr + PENTRY_SIZE_OFFSET);
   1278         pentries_arr_size =
   1279                 GET_4_BYTES(hdr + PARTITION_COUNT_OFFSET) * pentry_size;
   1280         pentry_arr = (uint8_t*)calloc(1, pentries_arr_size);
   1281         if (!pentry_arr) {
   1282                 ALOGE("%s: Failed to allocate memory for partition array",
   1283                                 __func__);
   1284                 goto error;
   1285         }
   1286         rc = blk_rw(fd, 0,
   1287                         pentries_start,
   1288                         pentry_arr,
   1289                         pentries_arr_size);
   1290         if (rc) {
   1291                 ALOGE("%s: Failed to read partition entry array",
   1292                                 __func__);
   1293                 goto error;
   1294         }
   1295         return pentry_arr;
   1296 error:
   1297         if (pentry_arr)
   1298                 free(pentry_arr);
   1299         return NULL;
   1300 }
   1301 
   1302 static int gpt_set_pentry_arr(uint8_t *hdr, int fd, uint8_t* arr)
   1303 {
   1304         uint32_t block_size = 0;
   1305         uint64_t pentries_start = 0;
   1306         uint32_t pentry_size = 0;
   1307         uint32_t pentries_arr_size = 0;
   1308         int rc = 0;
   1309         if (!hdr || fd < 0 || !arr) {
   1310                 ALOGE("%s: Invalid argument", __func__);
   1311                 goto error;
   1312         }
   1313         block_size = gpt_get_block_size(fd);
   1314         if (!block_size) {
   1315                 ALOGE("%s: Failed to get gpt block size for",
   1316                                 __func__);
   1317                 goto error;
   1318         }
   1319         ALOGI("%s : Block size is %d", __func__, block_size);
   1320         pentries_start = GET_8_BYTES(hdr + PENTRIES_OFFSET) * block_size;
   1321         pentry_size = GET_4_BYTES(hdr + PENTRY_SIZE_OFFSET);
   1322         pentries_arr_size =
   1323                 GET_4_BYTES(hdr + PARTITION_COUNT_OFFSET) * pentry_size;
   1324         ALOGI("%s: Writing partition entry array of size %d to offset %" PRIu64,
   1325                         __func__,
   1326                         pentries_arr_size,
   1327                         pentries_start);
   1328         rc = blk_rw(fd, 1,
   1329                         pentries_start,
   1330                         arr,
   1331                         pentries_arr_size);
   1332         if (rc) {
   1333                 ALOGE("%s: Failed to read partition entry array",
   1334                                 __func__);
   1335                 goto error;
   1336         }
   1337         return 0;
   1338 error:
   1339         return -1;
   1340 }
   1341 
   1342 
   1343 
   1344 //Allocate a handle used by calls to the "gpt_disk" api's
   1345 struct gpt_disk * gpt_disk_alloc()
   1346 {
   1347         struct gpt_disk *disk;
   1348         disk = (struct gpt_disk *)malloc(sizeof(struct gpt_disk));
   1349         if (!disk) {
   1350                 ALOGE("%s: Failed to allocate memory", __func__);
   1351                 goto end;
   1352         }
   1353         memset(disk, 0, sizeof(struct gpt_disk));
   1354 end:
   1355         return disk;
   1356 }
   1357 
   1358 //Free previously allocated/initialized handle
   1359 void gpt_disk_free(struct gpt_disk *disk)
   1360 {
   1361         if (!disk)
   1362                 return;
   1363         if (disk->hdr)
   1364                 free(disk->hdr);
   1365         if (disk->hdr_bak)
   1366                 free(disk->hdr_bak);
   1367         if (disk->pentry_arr)
   1368                 free(disk->pentry_arr);
   1369         if (disk->pentry_arr_bak)
   1370                 free(disk->pentry_arr_bak);
   1371         free(disk);
   1372         return;
   1373 }
   1374 
   1375 //fills up the passed in gpt_disk struct with information about the
   1376 //disk represented by path dev. Returns 0 on success and -1 on error.
   1377 int gpt_disk_get_disk_info(const char *dev, struct gpt_disk *dsk)
   1378 {
   1379         struct gpt_disk *disk = NULL;
   1380         int fd = -1;
   1381         uint32_t gpt_header_size = 0;
   1382 
   1383         if (!dsk || !dev) {
   1384                 ALOGE("%s: Invalid arguments", __func__);
   1385                 goto error;
   1386         }
   1387         disk = dsk;
   1388         disk->hdr = gpt_get_header(dev, PRIMARY_GPT);
   1389         if (!disk->hdr) {
   1390                 ALOGE("%s: Failed to get primary header", __func__);
   1391                 goto error;
   1392         }
   1393         gpt_header_size = GET_4_BYTES(disk->hdr + HEADER_SIZE_OFFSET);
   1394         disk->hdr_crc = crc32(0, disk->hdr, gpt_header_size);
   1395         disk->hdr_bak = gpt_get_header(dev, PRIMARY_GPT);
   1396         if (!disk->hdr_bak) {
   1397                 ALOGE("%s: Failed to get backup header", __func__);
   1398                 goto error;
   1399         }
   1400         disk->hdr_bak_crc = crc32(0, disk->hdr_bak, gpt_header_size);
   1401 
   1402         //Descriptor for the block device. We will use this for further
   1403         //modifications to the partition table
   1404         if (get_dev_path_from_partition_name(dev,
   1405                                 disk->devpath,
   1406                                 sizeof(disk->devpath)) != 0) {
   1407                 ALOGE("%s: Failed to resolve path for %s",
   1408                                 __func__,
   1409                                 dev);
   1410                 goto error;
   1411         }
   1412         fd = open(disk->devpath, O_RDWR);
   1413         if (fd < 0) {
   1414                 ALOGE("%s: Failed to open %s: %s",
   1415                                 __func__,
   1416                                 disk->devpath,
   1417                                 strerror(errno));
   1418                 goto error;
   1419         }
   1420         disk->pentry_arr = gpt_get_pentry_arr(disk->hdr, fd);
   1421         if (!disk->pentry_arr) {
   1422                 ALOGE("%s: Failed to obtain partition entry array",
   1423                                 __func__);
   1424                 goto error;
   1425         }
   1426         disk->pentry_arr_bak = gpt_get_pentry_arr(disk->hdr_bak, fd);
   1427         if (!disk->pentry_arr_bak) {
   1428                 ALOGE("%s: Failed to obtain backup partition entry array",
   1429                                 __func__);
   1430                 goto error;
   1431         }
   1432         disk->pentry_size = GET_4_BYTES(disk->hdr + PENTRY_SIZE_OFFSET);
   1433         disk->pentry_arr_size =
   1434                 GET_4_BYTES(disk->hdr + PARTITION_COUNT_OFFSET) *
   1435                 disk->pentry_size;
   1436         disk->pentry_arr_crc = GET_4_BYTES(disk->hdr + PARTITION_CRC_OFFSET);
   1437         disk->pentry_arr_bak_crc = GET_4_BYTES(disk->hdr_bak +
   1438                         PARTITION_CRC_OFFSET);
   1439         disk->block_size = gpt_get_block_size(fd);
   1440         close(fd);
   1441         disk->is_initialized = GPT_DISK_INIT_MAGIC;
   1442         return 0;
   1443 error:
   1444         if (fd >= 0)
   1445                 close(fd);
   1446         return -1;
   1447 }
   1448 
   1449 //Get pointer to partition entry from a allocated gpt_disk structure
   1450 uint8_t* gpt_disk_get_pentry(struct gpt_disk *disk,
   1451                 const char *partname,
   1452                 enum gpt_instance instance)
   1453 {
   1454         uint8_t *ptn_arr = NULL;
   1455         if (!disk || !partname || disk->is_initialized != GPT_DISK_INIT_MAGIC) {
   1456                 ALOGE("%s: Invalid argument",__func__);
   1457                 goto error;
   1458         }
   1459         ptn_arr = (instance == PRIMARY_GPT) ?
   1460                 disk->pentry_arr : disk->pentry_arr_bak;
   1461         return (gpt_pentry_seek(partname, ptn_arr,
   1462                         ptn_arr + disk->pentry_arr_size ,
   1463                         disk->pentry_size));
   1464 error:
   1465         return NULL;
   1466 }
   1467 
   1468 //Update CRC values for the various components of the gpt_disk
   1469 //structure. This function should be called after any of the fields
   1470 //have been updated before the structure contents are written back to
   1471 //disk.
   1472 int gpt_disk_update_crc(struct gpt_disk *disk)
   1473 {
   1474         uint32_t gpt_header_size = 0;
   1475         if (!disk || (disk->is_initialized != GPT_DISK_INIT_MAGIC)) {
   1476                 ALOGE("%s: invalid argument", __func__);
   1477                 goto error;
   1478         }
   1479         //Recalculate the CRC of the primary partiton array
   1480         disk->pentry_arr_crc = crc32(0,
   1481                         disk->pentry_arr,
   1482                         disk->pentry_arr_size);
   1483         //Recalculate the CRC of the backup partition array
   1484         disk->pentry_arr_bak_crc = crc32(0,
   1485                         disk->pentry_arr_bak,
   1486                         disk->pentry_arr_size);
   1487         //Update the partition CRC value in the primary GPT header
   1488         PUT_4_BYTES(disk->hdr + PARTITION_CRC_OFFSET, disk->pentry_arr_crc);
   1489         //Update the partition CRC value in the backup GPT header
   1490         PUT_4_BYTES(disk->hdr_bak + PARTITION_CRC_OFFSET,
   1491                         disk->pentry_arr_bak_crc);
   1492         //Update the CRC value of the primary header
   1493         gpt_header_size = GET_4_BYTES(disk->hdr + HEADER_SIZE_OFFSET);
   1494         //Header CRC is calculated with its own CRC field set to 0
   1495         PUT_4_BYTES(disk->hdr + HEADER_CRC_OFFSET, 0);
   1496         PUT_4_BYTES(disk->hdr_bak + HEADER_CRC_OFFSET, 0);
   1497         disk->hdr_crc = crc32(0, disk->hdr, gpt_header_size);
   1498         disk->hdr_bak_crc = crc32(0, disk->hdr_bak, gpt_header_size);
   1499         PUT_4_BYTES(disk->hdr + HEADER_CRC_OFFSET, disk->hdr_crc);
   1500         PUT_4_BYTES(disk->hdr_bak + HEADER_CRC_OFFSET, disk->hdr_bak_crc);
   1501         return 0;
   1502 error:
   1503         return -1;
   1504 }
   1505 
   1506 //Write the contents of struct gpt_disk back to the actual disk
   1507 int gpt_disk_commit(struct gpt_disk *disk)
   1508 {
   1509         int fd = -1;
   1510         if (!disk || (disk->is_initialized != GPT_DISK_INIT_MAGIC)){
   1511                 ALOGE("%s: Invalid args", __func__);
   1512                 goto error;
   1513         }
   1514         fd = open(disk->devpath, O_RDWR);
   1515         if (fd < 0) {
   1516                 ALOGE("%s: Failed to open %s: %s",
   1517                                 __func__,
   1518                                 disk->devpath,
   1519                                 strerror(errno));
   1520                 goto error;
   1521         }
   1522         ALOGI("%s: Writing back primary GPT header", __func__);
   1523         //Write the primary header
   1524         if(gpt_set_header(disk->hdr, fd, PRIMARY_GPT) != 0) {
   1525                 ALOGE("%s: Failed to update primary GPT header",
   1526                                 __func__);
   1527                 goto error;
   1528         }
   1529         ALOGI("%s: Writing back primary partition array", __func__);
   1530         //Write back the primary partition array
   1531         if (gpt_set_pentry_arr(disk->hdr, fd, disk->pentry_arr)) {
   1532                 ALOGE("%s: Failed to write primary GPT partition arr",
   1533                                 __func__);
   1534                 goto error;
   1535         }
   1536         close(fd);
   1537         return 0;
   1538 error:
   1539         if (fd >= 0)
   1540                 close(fd);
   1541         return -1;
   1542 }
   1543