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/platform/soc/1d84000.ufshc/by-name/xbl"
69 #define XBL_BACKUP          "/dev/block/platform/soc/1d84000.ufshc/by-name/xblbak"
70 #define XBL_AB_PRIMARY      "/dev/block/platform/soc/1d84000.ufshc/by-name/xbl_a"
71 #define XBL_AB_SECONDARY    "/dev/block/platform/soc/1d84000.ufshc/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  */
blk_rw(int fd,int rw,int64_t offset,uint8_t * buf,unsigned len)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         if (rw) {
165             r = fsync(fd);
166             if (r < 0)
167                 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
168         } else {
169             r = 0;
170         }
171     }
172 
173     return r;
174 }
175 
176 
177 
178 /**
179  *  ==========================================================================
180  *
181  *  \brief  Search within GPT for partition entry with the given name
182  *  or it's backup twin (name-bak).
183  *
184  *  \param [in] ptn_name        Partition name to seek
185  *  \param [in] pentries_start  Partition entries array start pointer
186  *  \param [in] pentries_end    Partition entries array end pointer
187  *  \param [in] pentry_size     Single partition entry size [bytes]
188  *
189  *  \return  First partition entry pointer that matches the name or NULL
190  *
191  *  ==========================================================================
192  */
gpt_pentry_seek(const char * ptn_name,const uint8_t * pentries_start,const uint8_t * pentries_end,uint32_t pentry_size)193 static uint8_t *gpt_pentry_seek(const char *ptn_name,
194                                 const uint8_t *pentries_start,
195                                 const uint8_t *pentries_end,
196                                 uint32_t pentry_size)
197 {
198     char *pentry_name;
199     unsigned len = strlen(ptn_name);
200 
201     for (pentry_name = (char *) (pentries_start + PARTITION_NAME_OFFSET);
202          pentry_name < (char *) pentries_end; pentry_name += pentry_size) {
203         char name8[MAX_GPT_NAME_SIZE / 2];
204         unsigned i;
205 
206         /* Partition names in GPT are UTF-16 - ignoring UTF-16 2nd byte */
207         for (i = 0; i < sizeof(name8); i++)
208             name8[i] = pentry_name[i * 2];
209         if (!strncmp(ptn_name, name8, len))
210             if (name8[len] == 0 || !strcmp(&name8[len], BAK_PTN_NAME_EXT))
211                 return (uint8_t *) (pentry_name - PARTITION_NAME_OFFSET);
212     }
213 
214     return NULL;
215 }
216 
217 
218 
219 /**
220  *  ==========================================================================
221  *
222  *  \brief  Swaps boot chain in GPT partition entries array
223  *
224  *  \param [in] pentries_start  Partition entries array start
225  *  \param [in] pentries_end    Partition entries array end
226  *  \param [in] pentry_size     Single partition entry size
227  *
228  *  \return  0 on success, 1 if no backup partitions found
229  *
230  *  ==========================================================================
231  */
gpt_boot_chain_swap(const uint8_t * pentries_start,const uint8_t * pentries_end,uint32_t pentry_size)232 static int gpt_boot_chain_swap(const uint8_t *pentries_start,
233                                 const uint8_t *pentries_end,
234                                 uint32_t pentry_size)
235 {
236     const char ptn_swap_list[][MAX_GPT_NAME_SIZE] = { PTN_SWAP_LIST };
237 
238     int backup_not_found = 1;
239     unsigned i;
240 
241     for (i = 0; i < ARRAY_SIZE(ptn_swap_list); i++) {
242         uint8_t *ptn_entry;
243         uint8_t *ptn_bak_entry;
244         uint8_t ptn_swap[PTN_ENTRY_SIZE];
245         //Skip the xbl partition on UFS devices. That is handled
246         //seperately.
247         if (gpt_utils_is_ufs_device() && !strncmp(ptn_swap_list[i],
248                                 PTN_XBL,
249                                 strlen(PTN_XBL)))
250             continue;
251 
252         ptn_entry = gpt_pentry_seek(ptn_swap_list[i], pentries_start,
253                         pentries_end, pentry_size);
254         if (ptn_entry == NULL)
255             continue;
256 
257         ptn_bak_entry = gpt_pentry_seek(ptn_swap_list[i],
258                         ptn_entry + pentry_size, pentries_end, pentry_size);
259         if (ptn_bak_entry == NULL) {
260             fprintf(stderr, "'%s' partition not backup - skip safe update\n",
261                     ptn_swap_list[i]);
262             continue;
263         }
264 
265         /* swap primary <-> backup partition entries */
266         memcpy(ptn_swap, ptn_entry, PTN_ENTRY_SIZE);
267         memcpy(ptn_entry, ptn_bak_entry, PTN_ENTRY_SIZE);
268         memcpy(ptn_bak_entry, ptn_swap, PTN_ENTRY_SIZE);
269         backup_not_found = 0;
270     }
271 
272     return backup_not_found;
273 }
274 
275 
276 
277 /**
278  *  ==========================================================================
279  *
280  *  \brief  Sets secondary GPT boot chain
281  *
282  *  \param [in] fd    block dev file descriptor
283  *  \param [in] boot  Boot chain to switch to
284  *
285  *  \return  0 on success
286  *
287  *  ==========================================================================
288  */
gpt2_set_boot_chain(int fd,enum boot_chain boot)289 static int gpt2_set_boot_chain(int fd, enum boot_chain boot)
290 {
291     int64_t  gpt2_header_offset;
292     uint64_t pentries_start_offset;
293     uint32_t gpt_header_size;
294     uint32_t pentry_size;
295     uint32_t pentries_array_size;
296 
297     uint8_t *gpt_header = NULL;
298     uint8_t  *pentries = NULL;
299     uint32_t crc;
300     uint32_t blk_size = 0;
301     int r;
302 
303     if (ioctl(fd, BLKSSZGET, &blk_size) != 0) {
304             fprintf(stderr, "Failed to get GPT device block size: %s\n",
305                             strerror(errno));
306             r = -1;
307             goto EXIT;
308     }
309     gpt_header = (uint8_t*)malloc(blk_size);
310     if (!gpt_header) {
311             fprintf(stderr, "Failed to allocate memory to hold GPT block\n");
312             r = -1;
313             goto EXIT;
314     }
315     gpt2_header_offset = lseek64(fd, 0, SEEK_END) - blk_size;
316     if (gpt2_header_offset < 0) {
317         fprintf(stderr, "Getting secondary GPT header offset failed: %s\n",
318                 strerror(errno));
319         r = -1;
320         goto EXIT;
321     }
322 
323     /* Read primary GPT header from block dev */
324     r = blk_rw(fd, 0, blk_size, gpt_header, blk_size);
325 
326     if (r) {
327             fprintf(stderr, "Failed to read primary GPT header from blk dev\n");
328             goto EXIT;
329     }
330     pentries_start_offset =
331         GET_8_BYTES(gpt_header + PENTRIES_OFFSET) * blk_size;
332     pentry_size = GET_4_BYTES(gpt_header + PENTRY_SIZE_OFFSET);
333     pentries_array_size =
334         GET_4_BYTES(gpt_header + PARTITION_COUNT_OFFSET) * pentry_size;
335 
336     pentries = (uint8_t *) calloc(1, pentries_array_size);
337     if (pentries == NULL) {
338         fprintf(stderr,
339                     "Failed to alloc memory for GPT partition entries array\n");
340         r = -1;
341         goto EXIT;
342     }
343     /* Read primary GPT partititon entries array from block dev */
344     r = blk_rw(fd, 0, pentries_start_offset, pentries, pentries_array_size);
345     if (r)
346         goto EXIT;
347 
348     crc = crc32(0, pentries, pentries_array_size);
349     if (GET_4_BYTES(gpt_header + PARTITION_CRC_OFFSET) != crc) {
350         fprintf(stderr, "Primary GPT partition entries array CRC invalid\n");
351         r = -1;
352         goto EXIT;
353     }
354 
355     /* Read secondary GPT header from block dev */
356     r = blk_rw(fd, 0, gpt2_header_offset, gpt_header, blk_size);
357     if (r)
358         goto EXIT;
359 
360     gpt_header_size = GET_4_BYTES(gpt_header + HEADER_SIZE_OFFSET);
361     pentries_start_offset =
362         GET_8_BYTES(gpt_header + PENTRIES_OFFSET) * blk_size;
363 
364     if (boot == BACKUP_BOOT) {
365         r = gpt_boot_chain_swap(pentries, pentries + pentries_array_size,
366                                 pentry_size);
367         if (r)
368             goto EXIT;
369     }
370 
371     crc = crc32(0, pentries, pentries_array_size);
372     PUT_4_BYTES(gpt_header + PARTITION_CRC_OFFSET, crc);
373 
374     /* header CRC is calculated with this field cleared */
375     PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, 0);
376     crc = crc32(0, gpt_header, gpt_header_size);
377     PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, crc);
378 
379     /* Write the modified GPT header back to block dev */
380     r = blk_rw(fd, 1, gpt2_header_offset, gpt_header, blk_size);
381     if (!r)
382         /* Write the modified GPT partititon entries array back to block dev */
383         r = blk_rw(fd, 1, pentries_start_offset, pentries,
384                     pentries_array_size);
385 
386 EXIT:
387     if(gpt_header)
388             free(gpt_header);
389     if (pentries)
390             free(pentries);
391     return r;
392 }
393 
394 /**
395  *  ==========================================================================
396  *
397  *  \brief  Checks GPT state (header signature and CRC)
398  *
399  *  \param [in] fd      block dev file descriptor
400  *  \param [in] gpt     GPT header to be checked
401  *  \param [out] state  GPT header state
402  *
403  *  \return  0 on success
404  *
405  *  ==========================================================================
406  */
gpt_get_state(int fd,enum gpt_instance gpt,enum gpt_state * state)407 static int gpt_get_state(int fd, enum gpt_instance gpt, enum gpt_state *state)
408 {
409     int64_t gpt_header_offset;
410     uint32_t gpt_header_size;
411     uint8_t  *gpt_header = NULL;
412     uint32_t crc;
413     uint32_t blk_size = 0;
414 
415     *state = GPT_OK;
416 
417     if (ioctl(fd, BLKSSZGET, &blk_size) != 0) {
418             fprintf(stderr, "Failed to get GPT device block size: %s\n",
419                             strerror(errno));
420             goto error;
421     }
422     gpt_header = (uint8_t*)malloc(blk_size);
423     if (!gpt_header) {
424             fprintf(stderr, "gpt_get_state:Failed to alloc memory for header\n");
425             goto error;
426     }
427     if (gpt == PRIMARY_GPT)
428         gpt_header_offset = blk_size;
429     else {
430         gpt_header_offset = lseek64(fd, 0, SEEK_END) - blk_size;
431         if (gpt_header_offset < 0) {
432             fprintf(stderr, "gpt_get_state:Seek to end of GPT part fail\n");
433             goto error;
434         }
435     }
436 
437     if (blk_rw(fd, 0, gpt_header_offset, gpt_header, blk_size)) {
438         fprintf(stderr, "gpt_get_state: blk_rw failed\n");
439         goto error;
440     }
441     if (memcmp(gpt_header, GPT_SIGNATURE, sizeof(GPT_SIGNATURE)))
442         *state = GPT_BAD_SIGNATURE;
443     gpt_header_size = GET_4_BYTES(gpt_header + HEADER_SIZE_OFFSET);
444 
445     crc = GET_4_BYTES(gpt_header + HEADER_CRC_OFFSET);
446     /* header CRC is calculated with this field cleared */
447     PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, 0);
448     if (crc32(0, gpt_header, gpt_header_size) != crc)
449         *state = GPT_BAD_CRC;
450     free(gpt_header);
451     return 0;
452 error:
453     if (gpt_header)
454             free(gpt_header);
455     return -1;
456 }
457 
458 
459 
460 /**
461  *  ==========================================================================
462  *
463  *  \brief  Sets GPT header state (used to corrupt and fix GPT signature)
464  *
465  *  \param [in] fd     block dev file descriptor
466  *  \param [in] gpt    GPT header to be checked
467  *  \param [in] state  GPT header state to set (GPT_OK or GPT_BAD_SIGNATURE)
468  *
469  *  \return  0 on success
470  *
471  *  ==========================================================================
472  */
gpt_set_state(int fd,enum gpt_instance gpt,enum gpt_state state)473 static int gpt_set_state(int fd, enum gpt_instance gpt, enum gpt_state state)
474 {
475     int64_t gpt_header_offset;
476     uint32_t gpt_header_size;
477     uint8_t  *gpt_header = NULL;
478     uint32_t crc;
479     uint32_t blk_size = 0;
480 
481     if (ioctl(fd, BLKSSZGET, &blk_size) != 0) {
482             fprintf(stderr, "Failed to get GPT device block size: %s\n",
483                             strerror(errno));
484             goto error;
485     }
486     gpt_header = (uint8_t*)malloc(blk_size);
487     if (!gpt_header) {
488             fprintf(stderr, "Failed to alloc memory for gpt header\n");
489             goto error;
490     }
491     if (gpt == PRIMARY_GPT)
492         gpt_header_offset = blk_size;
493     else {
494         gpt_header_offset = lseek64(fd, 0, SEEK_END) - blk_size;
495         if (gpt_header_offset < 0) {
496             fprintf(stderr, "Failed to seek to end of GPT device\n");
497             goto error;
498         }
499     }
500     if (blk_rw(fd, 0, gpt_header_offset, gpt_header, blk_size)) {
501         fprintf(stderr, "Failed to r/w gpt header\n");
502         goto error;
503     }
504     if (state == GPT_OK)
505         memcpy(gpt_header, GPT_SIGNATURE, sizeof(GPT_SIGNATURE));
506     else if (state == GPT_BAD_SIGNATURE)
507         *gpt_header = 0;
508     else {
509         fprintf(stderr, "gpt_set_state: Invalid state\n");
510         goto error;
511     }
512 
513     gpt_header_size = GET_4_BYTES(gpt_header + HEADER_SIZE_OFFSET);
514 
515     /* header CRC is calculated with this field cleared */
516     PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, 0);
517     crc = crc32(0, gpt_header, gpt_header_size);
518     PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, crc);
519 
520     if (blk_rw(fd, 1, gpt_header_offset, gpt_header, blk_size)) {
521         fprintf(stderr, "gpt_set_state: blk write failed\n");
522         goto error;
523     }
524     return 0;
525 error:
526     if(gpt_header)
527            free(gpt_header);
528     return -1;
529 }
530 
get_scsi_node_from_bootdevice(const char * bootdev_path,char * sg_node_path,size_t buf_size)531 int get_scsi_node_from_bootdevice(const char *bootdev_path,
532                 char *sg_node_path,
533                 size_t buf_size)
534 {
535         char sg_dir_path[PATH_MAX] = {0};
536         char real_path[PATH_MAX] = {0};
537         DIR *scsi_dir = NULL;
538         struct dirent *de;
539         int node_found = 0;
540         if (!bootdev_path || !sg_node_path) {
541                 fprintf(stderr, "%s : invalid argument\n",
542                                  __func__);
543                 goto error;
544         }
545         if (readlink(bootdev_path, real_path, sizeof(real_path) - 1) < 0) {
546                         fprintf(stderr, "failed to resolve link for %s(%s)\n",
547                                         bootdev_path,
548                                         strerror(errno));
549                         goto error;
550         }
551         if(strlen(real_path) < PATH_TRUNCATE_LOC + 1){
552             fprintf(stderr, "Unrecognized path :%s:\n",
553                            real_path);
554             goto error;
555         }
556         //For the safe side in case there are additional partitions on
557         //the XBL lun we truncate the name.
558         real_path[PATH_TRUNCATE_LOC] = '\0';
559         if(strlen(real_path) < LUN_NAME_START_LOC + 1){
560             fprintf(stderr, "Unrecognized truncated path :%s:\n",
561                            real_path);
562             goto error;
563         }
564         //This will give us /dev/block/sdb/device/scsi_generic
565         //which contains a file sgY whose name gives us the path
566         //to /dev/sgY which we return
567         snprintf(sg_dir_path, sizeof(sg_dir_path) - 1,
568                         "/sys/block/%s/device/scsi_generic",
569                         &real_path[LUN_NAME_START_LOC]);
570         scsi_dir = opendir(sg_dir_path);
571         if (!scsi_dir) {
572                 fprintf(stderr, "%s : Failed to open %s(%s)\n",
573                                 __func__,
574                                 sg_dir_path,
575                                 strerror(errno));
576                 goto error;
577         }
578         while((de = readdir(scsi_dir))) {
579                 if (de->d_name[0] == '.')
580                         continue;
581                 else if (!strncmp(de->d_name, "sg", 2)) {
582                           snprintf(sg_node_path,
583                                         buf_size -1,
584                                         "/dev/%s",
585                                         de->d_name);
586                           fprintf(stderr, "%s:scsi generic node is :%s:\n",
587                                           __func__,
588                                           sg_node_path);
589                           node_found = 1;
590                           break;
591                 }
592         }
593         if(!node_found) {
594                 fprintf(stderr,"%s: Unable to locate scsi generic node\n",
595                                __func__);
596                 goto error;
597         }
598         closedir(scsi_dir);
599         return 0;
600 error:
601         if (scsi_dir)
602                 closedir(scsi_dir);
603         return -1;
604 }
605 
set_boot_lun(char * sg_dev,uint8_t boot_lun_id)606 int set_boot_lun(char *sg_dev, uint8_t boot_lun_id)
607 {
608         int fd = -1;
609         int rc;
610         struct ufs_ioctl_query_data *data = NULL;
611         size_t ioctl_data_size = sizeof(struct ufs_ioctl_query_data) + UFS_ATTR_DATA_SIZE;
612 
613         data = (struct ufs_ioctl_query_data*)malloc(ioctl_data_size);
614         if (!data) {
615                 fprintf(stderr, "%s: Failed to alloc query data struct\n",
616                                 __func__);
617                 goto error;
618         }
619         memset(data, 0, ioctl_data_size);
620         data->opcode = UPIU_QUERY_OPCODE_WRITE_ATTR;
621         data->idn = QUERY_ATTR_IDN_BOOT_LU_EN;
622         data->buf_size = UFS_ATTR_DATA_SIZE;
623         data->buffer[0] = boot_lun_id;
624         fd = open(sg_dev, O_RDWR);
625         if (fd < 0) {
626                 fprintf(stderr, "%s: Failed to open %s(%s)\n",
627                                 __func__,
628                                 sg_dev,
629                                 strerror(errno));
630                 goto error;
631         }
632         rc = ioctl(fd, UFS_IOCTL_QUERY, data);
633         if (rc) {
634                 fprintf(stderr, "%s: UFS query ioctl failed(%s)\n",
635                                 __func__,
636                                 strerror(errno));
637                 goto error;
638         }
639         close(fd);
640         free(data);
641         return 0;
642 error:
643         if (fd >= 0)
644                 close(fd);
645         if (data)
646                 free(data);
647         return -1;
648 }
649 
650 //Switch between using either the primary or the backup
651 //boot LUN for boot. This is required since UFS boot partitions
652 //cannot have a backup GPT which is what we use for failsafe
653 //updates of the other 'critical' partitions. This function will
654 //not be invoked for emmc targets and on UFS targets is only required
655 //to be invoked for XBL.
656 //
657 //The algorithm to do this is as follows:
658 //- Find the real block device(eg: /dev/block/sdb) that corresponds
659 //  to the /dev/block/bootdevice/by-name/xbl(bak) symlink
660 //
661 //- Once we have the block device 'node' name(sdb in the above example)
662 //  use this node to to locate the scsi generic device that represents
663 //  it by checking the file /sys/block/sdb/device/scsi_generic/sgY
664 //
665 //- Once we locate sgY we call the query ioctl on /dev/sgy to switch
666 //the boot lun to either LUNA or LUNB
gpt_utils_set_xbl_boot_partition(enum boot_chain chain)667 int gpt_utils_set_xbl_boot_partition(enum boot_chain chain)
668 {
669         struct stat st;
670         ///sys/block/sdX/device/scsi_generic/
671         char sg_dev_node[PATH_MAX] = {0};
672         uint8_t boot_lun_id = 0;
673         const char *boot_dev = NULL;
674 
675         if (chain == BACKUP_BOOT) {
676                 boot_lun_id = BOOT_LUN_B_ID;
677                 if (!stat(XBL_BACKUP, &st))
678                         boot_dev = XBL_BACKUP;
679                 else if (!stat(XBL_AB_SECONDARY, &st))
680                         boot_dev = XBL_AB_SECONDARY;
681                 else {
682                         fprintf(stderr, "%s: Failed to locate secondary xbl\n",
683                                         __func__);
684                         goto error;
685                 }
686         } else if (chain == NORMAL_BOOT) {
687                 boot_lun_id = BOOT_LUN_A_ID;
688                 if (!stat(XBL_PRIMARY, &st))
689                         boot_dev = XBL_PRIMARY;
690                 else if (!stat(XBL_AB_PRIMARY, &st))
691                         boot_dev = XBL_AB_PRIMARY;
692                 else {
693                         fprintf(stderr, "%s: Failed to locate primary xbl\n",
694                                         __func__);
695                         goto error;
696                 }
697         } else {
698                 fprintf(stderr, "%s: Invalid boot chain id\n", __func__);
699                 goto error;
700         }
701         //We need either both xbl and xblbak or both xbl_a and xbl_b to exist at
702         //the same time. If not the current configuration is invalid.
703         if((stat(XBL_PRIMARY, &st) ||
704                                 stat(XBL_BACKUP, &st)) &&
705                         (stat(XBL_AB_PRIMARY, &st) ||
706                          stat(XBL_AB_SECONDARY, &st))) {
707                 fprintf(stderr, "%s:primary/secondary XBL prt not found(%s)\n",
708                                 __func__,
709                                 strerror(errno));
710                 goto error;
711         }
712         fprintf(stderr, "%s: setting %s lun as boot lun\n",
713                         __func__,
714                         boot_dev);
715         if (get_scsi_node_from_bootdevice(boot_dev,
716                                 sg_dev_node,
717                                 sizeof(sg_dev_node))) {
718                 fprintf(stderr, "%s: Failed to get scsi node path for xblbak\n",
719                                 __func__);
720                 goto error;
721         }
722         if (set_boot_lun(sg_dev_node, boot_lun_id)) {
723                 fprintf(stderr, "%s: Failed to set xblbak as boot partition\n",
724                                 __func__);
725                 goto error;
726         }
727         return 0;
728 error:
729         return -1;
730 }
731 
gpt_utils_is_ufs_device()732 int gpt_utils_is_ufs_device()
733 {
734     char bootdevice[PROPERTY_VALUE_MAX] = {0};
735     property_get("ro.boot.bootdevice", bootdevice, "N/A");
736     if (strlen(bootdevice) < strlen(".ufshc") + 1)
737         return 0;
738     return (!strncmp(&bootdevice[strlen(bootdevice) - strlen(".ufshc")],
739                             ".ufshc",
740                             sizeof(".ufshc")));
741 }
742 //dev_path is the path to the block device that contains the GPT image that
743 //needs to be updated. This would be the device which holds one or more critical
744 //boot partitions and their backups. In the case of EMMC this function would
745 //be invoked only once on /dev/block/mmcblk1 since it holds the GPT image
746 //containing all the partitions For UFS devices it could potentially be
747 //invoked multiple times, once for each LUN containing critical image(s) and
748 //their backups
prepare_partitions(enum boot_update_stage stage,const char * dev_path)749 int prepare_partitions(enum boot_update_stage stage, const char *dev_path)
750 {
751     int r = 0;
752     int fd = -1;
753     int is_ufs = gpt_utils_is_ufs_device();
754     enum gpt_state gpt_prim, gpt_second;
755     enum boot_update_stage internal_stage;
756     struct stat xbl_partition_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 
add_lun_to_update_list(char * lun_path,struct update_data * dat)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 
prepare_boot_update(enum boot_update_stage stage)977 int prepare_boot_update(enum boot_update_stage stage)
978 {
979         int is_ufs = gpt_utils_is_ufs_device();
980         struct stat ufs_dir_stat;
981         struct update_data data;
982         int rcode = 0;
983         uint32_t i = 0;
984         int is_error = 0;
985         const char ptn_swap_list[][MAX_GPT_NAME_SIZE] = { PTN_SWAP_LIST };
986         //Holds /dev/block/bootdevice/by-name/*bak entry
987         char buf[PATH_MAX] = {0};
988         //Holds the resolved path of the symlink stored in buf
989         char real_path[PATH_MAX] = {0};
990 
991         if (!is_ufs) {
992                 //emmc device. Just pass in path to mmcblk0
993                 return prepare_partitions(stage, BLK_DEV_FILE);
994         } else {
995                 //Now we need to find the list of LUNs over
996                 //which the boot critical images are spread
997                 //and set them up for failsafe updates.To do
998                 //this we find out where the symlinks for the
999                 //each of the paths under
1000                 ///dev/block/bootdevice/by-name/PTN_SWAP_LIST
1001                 //actually point to.
1002                 fprintf(stderr, "%s: Running on a UFS device\n",
1003                                 __func__);
1004                 memset(&data, '\0', sizeof(struct update_data));
1005                 for (i=0; i < ARRAY_SIZE(ptn_swap_list); i++) {
1006                         //XBL on UFS does not follow the convention
1007                         //of being loaded based on well known GUID'S.
1008                         //We take care of switching the UFS boot LUN
1009                         //explicitly later on.
1010                         if (!strncmp(ptn_swap_list[i],
1011                                                 PTN_XBL,
1012                                                 strlen(PTN_XBL)))
1013                                 continue;
1014                         snprintf(buf, sizeof(buf),
1015                                         "%s/%sbak",
1016                                         BOOT_DEV_DIR,
1017                                         ptn_swap_list[i]);
1018                         if (stat(buf, &ufs_dir_stat)) {
1019                                 continue;
1020                         }
1021                         if (readlink(buf, real_path, sizeof(real_path) - 1) < 0)
1022                         {
1023                                 fprintf(stderr, "%s: readlink error. Skipping %s",
1024                                                 __func__,
1025                                                 strerror(errno));
1026                         } else {
1027                               if(strlen(real_path) < PATH_TRUNCATE_LOC + 1){
1028                                     fprintf(stderr, "Unknown path.Skipping :%s:\n",
1029                                                 real_path);
1030                                 } else {
1031                                     real_path[PATH_TRUNCATE_LOC] = '\0';
1032                                     add_lun_to_update_list(real_path, &data);
1033                                 }
1034                         }
1035                         memset(buf, '\0', sizeof(buf));
1036                         memset(real_path, '\0', sizeof(real_path));
1037                 }
1038                 for (i=0; i < data.num_valid_entries; i++) {
1039                         fprintf(stderr, "%s: Preparing %s for update stage %d\n",
1040                                         __func__,
1041                                         data.lun_list[i],
1042                                         stage);
1043                         rcode = prepare_partitions(stage, data.lun_list[i]);
1044                         if (rcode != 0)
1045                         {
1046                                 fprintf(stderr, "%s: Failed to prepare %s.Continuing..\n",
1047                                                 __func__,
1048                                                 data.lun_list[i]);
1049                                 is_error = 1;
1050                         }
1051                 }
1052         }
1053         if (is_error)
1054                 return -1;
1055         return 0;
1056 }
1057 
1058 //Given a parttion name(eg: rpm) get the path to the block device that
1059 //represents the GPT disk the partition resides on. In the case of emmc it
1060 //would be the default emmc dev(/dev/block/mmcblk0). In the case of UFS we look
1061 //through the /dev/block/bootdevice/by-name/ tree for partname, and resolve
1062 //the path to the LUN from there.
get_dev_path_from_partition_name(const char * partname,char * buf,size_t buflen)1063 static int get_dev_path_from_partition_name(const char *partname,
1064                 char *buf,
1065                 size_t buflen)
1066 {
1067         struct stat st;
1068         char path[PATH_MAX] = {0};
1069         if (!partname || !buf || buflen < ((PATH_TRUNCATE_LOC) + 1)) {
1070                 ALOGE("%s: Invalid argument", __func__);
1071                 goto error;
1072         }
1073         if (gpt_utils_is_ufs_device()) {
1074                 //Need to find the lun that holds partition partname
1075                 snprintf(path, sizeof(path),
1076                                 "%s/%s",
1077                                 BOOT_DEV_DIR,
1078                                 partname);
1079                 if (stat(path, &st)) {
1080                         goto error;
1081                 }
1082                 if (readlink(path, buf, buflen) < 0)
1083                 {
1084                         goto error;
1085                 } else {
1086                         buf[PATH_TRUNCATE_LOC] = '\0';
1087                 }
1088         } else {
1089                 snprintf(buf, buflen, "/dev/block/mmcblk0");
1090         }
1091         return 0;
1092 
1093 error:
1094         return -1;
1095 }
1096 
gpt_utils_get_partition_map(vector<string> & ptn_list,map<string,vector<string>> & partition_map)1097 int gpt_utils_get_partition_map(vector<string>& ptn_list,
1098                 map<string, vector<string>>& partition_map) {
1099         char devpath[PATH_MAX] = {'\0'};
1100         map<string, vector<string>>::iterator it;
1101         if (ptn_list.size() < 1) {
1102                 fprintf(stderr, "%s: Invalid ptn list\n", __func__);
1103                 return -1;
1104         }
1105         //Go through the passed in list
1106         for (uint32_t i = 0; i < ptn_list.size(); i++)
1107         {
1108                 //Key in the map is the path to the device that holds the
1109                 //partition
1110                 if (get_dev_path_from_partition_name(ptn_list[i].c_str(),
1111                                 devpath,
1112                                 sizeof(devpath))) {
1113                         //Not necessarily an error. The partition may just
1114                         //not be present.
1115                         continue;
1116                 }
1117                 string path = devpath;
1118                 it = partition_map.find(path);
1119                 if (it != partition_map.end()) {
1120                         it->second.push_back(ptn_list[i]);
1121                 } else {
1122                         vector<string> str_vec;
1123                         str_vec.push_back( ptn_list[i]);
1124                         partition_map.insert(pair<string, vector<string>>
1125                                         (path, str_vec));
1126                 }
1127                 memset(devpath, '\0', sizeof(devpath));
1128         }
1129         return 0;
1130 }
1131 
1132 //Get the block size of the disk represented by decsriptor fd
gpt_get_block_size(int fd)1133 static uint32_t gpt_get_block_size(int fd)
1134 {
1135         uint32_t block_size = 0;
1136         if (fd < 0) {
1137                 ALOGE("%s: invalid descriptor",
1138                                 __func__);
1139                 goto error;
1140         }
1141         if (ioctl(fd, BLKSSZGET, &block_size) != 0) {
1142                 ALOGE("%s: Failed to get GPT dev block size : %s",
1143                                 __func__,
1144                                 strerror(errno));
1145                 goto error;
1146         }
1147         return block_size;
1148 error:
1149         return 0;
1150 }
1151 
1152 //Write the GPT header present in the passed in buffer back to the
1153 //disk represented by fd
gpt_set_header(uint8_t * gpt_header,int fd,enum gpt_instance instance)1154 static int gpt_set_header(uint8_t *gpt_header, int fd,
1155                 enum gpt_instance instance)
1156 {
1157         uint32_t block_size = 0;
1158         off_t gpt_header_offset = 0;
1159         if (!gpt_header || fd < 0) {
1160                 ALOGE("%s: Invalid arguments",
1161                                 __func__);
1162                 goto error;
1163         }
1164         block_size = gpt_get_block_size(fd);
1165         ALOGI("%s: Block size is : %d", __func__, block_size);
1166         if (block_size == 0) {
1167                 ALOGE("%s: Failed to get block size", __func__);
1168                 goto error;
1169         }
1170         if (instance == PRIMARY_GPT)
1171                 gpt_header_offset = block_size;
1172         else
1173                 gpt_header_offset = lseek64(fd, 0, SEEK_END) - block_size;
1174         if (gpt_header_offset <= 0) {
1175                 ALOGE("%s: Failed to get gpt header offset",__func__);
1176                 goto error;
1177         }
1178         ALOGI("%s: Writing back header to offset %ld", __func__,
1179                 gpt_header_offset);
1180         if (blk_rw(fd, 1, gpt_header_offset, gpt_header, block_size)) {
1181                 ALOGE("%s: Failed to write back GPT header", __func__);
1182                 goto error;
1183         }
1184         return 0;
1185 error:
1186         return -1;
1187 }
1188 
1189 //Read out the GPT header for the disk that contains the partition partname
gpt_get_header(const char * partname,enum gpt_instance instance)1190 static uint8_t* gpt_get_header(const char *partname, enum gpt_instance instance)
1191 {
1192         uint8_t* hdr = NULL;
1193         char devpath[PATH_MAX] = {0};
1194         int64_t hdr_offset = 0;
1195         uint32_t block_size = 0;
1196         int fd = -1;
1197         if (!partname) {
1198                 ALOGE("%s: Invalid partition name", __func__);
1199                 goto error;
1200         }
1201         if (get_dev_path_from_partition_name(partname, devpath, sizeof(devpath))
1202                         != 0) {
1203                 ALOGE("%s: Failed to resolve path for %s",
1204                                 __func__,
1205                                 partname);
1206                 goto error;
1207         }
1208         fd = open(devpath, O_RDWR);
1209         if (fd < 0) {
1210                 ALOGE("%s: Failed to open %s : %s",
1211                                 __func__,
1212                                 devpath,
1213                                 strerror(errno));
1214                 goto error;
1215         }
1216         block_size = gpt_get_block_size(fd);
1217         if (block_size == 0)
1218         {
1219                 ALOGE("%s: Failed to get gpt block size for %s",
1220                                 __func__,
1221                                 partname);
1222                 goto error;
1223         }
1224 
1225         hdr = (uint8_t*)malloc(block_size);
1226         if (!hdr) {
1227                 ALOGE("%s: Failed to allocate memory for gpt header",
1228                                 __func__);
1229         }
1230         if (instance == PRIMARY_GPT)
1231                 hdr_offset = block_size;
1232         else {
1233                 hdr_offset = lseek64(fd, 0, SEEK_END) - block_size;
1234         }
1235         if (hdr_offset < 0) {
1236                 ALOGE("%s: Failed to get gpt header offset",
1237                                 __func__);
1238                 goto error;
1239         }
1240         if (blk_rw(fd, 0, hdr_offset, hdr, block_size)) {
1241                 ALOGE("%s: Failed to read GPT header from device",
1242                                 __func__);
1243                 goto error;
1244         }
1245         close(fd);
1246         return hdr;
1247 error:
1248         if (fd >= 0)
1249                 close(fd);
1250         if (hdr)
1251                 free(hdr);
1252         return NULL;
1253 }
1254 
1255 //Returns the partition entry array based on the
1256 //passed in buffer which contains the gpt header.
1257 //The fd here is the descriptor for the 'disk' which
1258 //holds the partition
gpt_get_pentry_arr(uint8_t * hdr,int fd)1259 static uint8_t* gpt_get_pentry_arr(uint8_t *hdr, int fd)
1260 {
1261         uint64_t pentries_start = 0;
1262         uint32_t pentry_size = 0;
1263         uint32_t block_size = 0;
1264         uint32_t pentries_arr_size = 0;
1265         uint8_t *pentry_arr = NULL;
1266         int rc = 0;
1267         if (!hdr) {
1268                 ALOGE("%s: Invalid header", __func__);
1269                 goto error;
1270         }
1271         if (fd < 0) {
1272                 ALOGE("%s: Invalid fd", __func__);
1273                 goto error;
1274         }
1275         block_size = gpt_get_block_size(fd);
1276         if (!block_size) {
1277                 ALOGE("%s: Failed to get gpt block size for",
1278                                 __func__);
1279                 goto error;
1280         }
1281         pentries_start = GET_8_BYTES(hdr + PENTRIES_OFFSET) * block_size;
1282         pentry_size = GET_4_BYTES(hdr + PENTRY_SIZE_OFFSET);
1283         pentries_arr_size =
1284                 GET_4_BYTES(hdr + PARTITION_COUNT_OFFSET) * pentry_size;
1285         pentry_arr = (uint8_t*)calloc(1, pentries_arr_size);
1286         if (!pentry_arr) {
1287                 ALOGE("%s: Failed to allocate memory for partition array",
1288                                 __func__);
1289                 goto error;
1290         }
1291         rc = blk_rw(fd, 0,
1292                         pentries_start,
1293                         pentry_arr,
1294                         pentries_arr_size);
1295         if (rc) {
1296                 ALOGE("%s: Failed to read partition entry array",
1297                                 __func__);
1298                 goto error;
1299         }
1300         return pentry_arr;
1301 error:
1302         if (pentry_arr)
1303                 free(pentry_arr);
1304         return NULL;
1305 }
1306 
gpt_set_pentry_arr(uint8_t * hdr,int fd,uint8_t * arr)1307 static int gpt_set_pentry_arr(uint8_t *hdr, int fd, uint8_t* arr)
1308 {
1309         uint32_t block_size = 0;
1310         uint64_t pentries_start = 0;
1311         uint32_t pentry_size = 0;
1312         uint32_t pentries_arr_size = 0;
1313         int rc = 0;
1314         if (!hdr || fd < 0 || !arr) {
1315                 ALOGE("%s: Invalid argument", __func__);
1316                 goto error;
1317         }
1318         block_size = gpt_get_block_size(fd);
1319         if (!block_size) {
1320                 ALOGE("%s: Failed to get gpt block size for",
1321                                 __func__);
1322                 goto error;
1323         }
1324         ALOGI("%s : Block size is %d", __func__, block_size);
1325         pentries_start = GET_8_BYTES(hdr + PENTRIES_OFFSET) * block_size;
1326         pentry_size = GET_4_BYTES(hdr + PENTRY_SIZE_OFFSET);
1327         pentries_arr_size =
1328                 GET_4_BYTES(hdr + PARTITION_COUNT_OFFSET) * pentry_size;
1329         ALOGI("%s: Writing partition entry array of size %d to offset %" PRIu64,
1330                         __func__,
1331                         pentries_arr_size,
1332                         pentries_start);
1333         rc = blk_rw(fd, 1,
1334                         pentries_start,
1335                         arr,
1336                         pentries_arr_size);
1337         if (rc) {
1338                 ALOGE("%s: Failed to read partition entry array",
1339                                 __func__);
1340                 goto error;
1341         }
1342         return 0;
1343 error:
1344         return -1;
1345 }
1346 
1347 
1348 
1349 //Allocate a handle used by calls to the "gpt_disk" api's
gpt_disk_alloc()1350 struct gpt_disk * gpt_disk_alloc()
1351 {
1352         struct gpt_disk *disk;
1353         disk = (struct gpt_disk *)malloc(sizeof(struct gpt_disk));
1354         if (!disk) {
1355                 ALOGE("%s: Failed to allocate memory", __func__);
1356                 goto end;
1357         }
1358         memset(disk, 0, sizeof(struct gpt_disk));
1359 end:
1360         return disk;
1361 }
1362 
1363 //Free previously allocated/initialized handle
gpt_disk_free(struct gpt_disk * disk)1364 void gpt_disk_free(struct gpt_disk *disk)
1365 {
1366         if (!disk)
1367                 return;
1368         if (disk->hdr)
1369                 free(disk->hdr);
1370         if (disk->hdr_bak)
1371                 free(disk->hdr_bak);
1372         if (disk->pentry_arr)
1373                 free(disk->pentry_arr);
1374         if (disk->pentry_arr_bak)
1375                 free(disk->pentry_arr_bak);
1376         free(disk);
1377         return;
1378 }
1379 
1380 //fills up the passed in gpt_disk struct with information about the
1381 //disk represented by path dev. Returns 0 on success and -1 on error.
gpt_disk_get_disk_info(const char * dev,struct gpt_disk * dsk)1382 int gpt_disk_get_disk_info(const char *dev, struct gpt_disk *dsk)
1383 {
1384         struct gpt_disk *disk = NULL;
1385         int fd = -1;
1386         uint32_t gpt_header_size = 0;
1387 
1388         if (!dsk || !dev) {
1389                 ALOGE("%s: Invalid arguments", __func__);
1390                 goto error;
1391         }
1392         disk = dsk;
1393         disk->hdr = gpt_get_header(dev, PRIMARY_GPT);
1394         if (!disk->hdr) {
1395                 ALOGE("%s: Failed to get primary header", __func__);
1396                 goto error;
1397         }
1398         gpt_header_size = GET_4_BYTES(disk->hdr + HEADER_SIZE_OFFSET);
1399         disk->hdr_crc = crc32(0, disk->hdr, gpt_header_size);
1400         disk->hdr_bak = gpt_get_header(dev, PRIMARY_GPT);
1401         if (!disk->hdr_bak) {
1402                 ALOGE("%s: Failed to get backup header", __func__);
1403                 goto error;
1404         }
1405         disk->hdr_bak_crc = crc32(0, disk->hdr_bak, gpt_header_size);
1406 
1407         //Descriptor for the block device. We will use this for further
1408         //modifications to the partition table
1409         if (get_dev_path_from_partition_name(dev,
1410                                 disk->devpath,
1411                                 sizeof(disk->devpath)) != 0) {
1412                 ALOGE("%s: Failed to resolve path for %s",
1413                                 __func__,
1414                                 dev);
1415                 goto error;
1416         }
1417         fd = open(disk->devpath, O_RDWR);
1418         if (fd < 0) {
1419                 ALOGE("%s: Failed to open %s: %s",
1420                                 __func__,
1421                                 disk->devpath,
1422                                 strerror(errno));
1423                 goto error;
1424         }
1425         disk->pentry_arr = gpt_get_pentry_arr(disk->hdr, fd);
1426         if (!disk->pentry_arr) {
1427                 ALOGE("%s: Failed to obtain partition entry array",
1428                                 __func__);
1429                 goto error;
1430         }
1431         disk->pentry_arr_bak = gpt_get_pentry_arr(disk->hdr_bak, fd);
1432         if (!disk->pentry_arr_bak) {
1433                 ALOGE("%s: Failed to obtain backup partition entry array",
1434                                 __func__);
1435                 goto error;
1436         }
1437         disk->pentry_size = GET_4_BYTES(disk->hdr + PENTRY_SIZE_OFFSET);
1438         disk->pentry_arr_size =
1439                 GET_4_BYTES(disk->hdr + PARTITION_COUNT_OFFSET) *
1440                 disk->pentry_size;
1441         disk->pentry_arr_crc = GET_4_BYTES(disk->hdr + PARTITION_CRC_OFFSET);
1442         disk->pentry_arr_bak_crc = GET_4_BYTES(disk->hdr_bak +
1443                         PARTITION_CRC_OFFSET);
1444         disk->block_size = gpt_get_block_size(fd);
1445         close(fd);
1446         disk->is_initialized = GPT_DISK_INIT_MAGIC;
1447         return 0;
1448 error:
1449         if (fd >= 0)
1450                 close(fd);
1451         return -1;
1452 }
1453 
1454 //Get pointer to partition entry from a allocated gpt_disk structure
gpt_disk_get_pentry(struct gpt_disk * disk,const char * partname,enum gpt_instance instance)1455 uint8_t* gpt_disk_get_pentry(struct gpt_disk *disk,
1456                 const char *partname,
1457                 enum gpt_instance instance)
1458 {
1459         uint8_t *ptn_arr = NULL;
1460         if (!disk || !partname || disk->is_initialized != GPT_DISK_INIT_MAGIC) {
1461                 ALOGE("%s: Invalid argument",__func__);
1462                 goto error;
1463         }
1464         ptn_arr = (instance == PRIMARY_GPT) ?
1465                 disk->pentry_arr : disk->pentry_arr_bak;
1466         return (gpt_pentry_seek(partname, ptn_arr,
1467                         ptn_arr + disk->pentry_arr_size ,
1468                         disk->pentry_size));
1469 error:
1470         return NULL;
1471 }
1472 
1473 //Update CRC values for the various components of the gpt_disk
1474 //structure. This function should be called after any of the fields
1475 //have been updated before the structure contents are written back to
1476 //disk.
gpt_disk_update_crc(struct gpt_disk * disk)1477 int gpt_disk_update_crc(struct gpt_disk *disk)
1478 {
1479         uint32_t gpt_header_size = 0;
1480         if (!disk || (disk->is_initialized != GPT_DISK_INIT_MAGIC)) {
1481                 ALOGE("%s: invalid argument", __func__);
1482                 goto error;
1483         }
1484         //Recalculate the CRC of the primary partiton array
1485         disk->pentry_arr_crc = crc32(0,
1486                         disk->pentry_arr,
1487                         disk->pentry_arr_size);
1488         //Recalculate the CRC of the backup partition array
1489         disk->pentry_arr_bak_crc = crc32(0,
1490                         disk->pentry_arr_bak,
1491                         disk->pentry_arr_size);
1492         //Update the partition CRC value in the primary GPT header
1493         PUT_4_BYTES(disk->hdr + PARTITION_CRC_OFFSET, disk->pentry_arr_crc);
1494         //Update the partition CRC value in the backup GPT header
1495         PUT_4_BYTES(disk->hdr_bak + PARTITION_CRC_OFFSET,
1496                         disk->pentry_arr_bak_crc);
1497         //Update the CRC value of the primary header
1498         gpt_header_size = GET_4_BYTES(disk->hdr + HEADER_SIZE_OFFSET);
1499         //Header CRC is calculated with its own CRC field set to 0
1500         PUT_4_BYTES(disk->hdr + HEADER_CRC_OFFSET, 0);
1501         PUT_4_BYTES(disk->hdr_bak + HEADER_CRC_OFFSET, 0);
1502         disk->hdr_crc = crc32(0, disk->hdr, gpt_header_size);
1503         disk->hdr_bak_crc = crc32(0, disk->hdr_bak, gpt_header_size);
1504         PUT_4_BYTES(disk->hdr + HEADER_CRC_OFFSET, disk->hdr_crc);
1505         PUT_4_BYTES(disk->hdr_bak + HEADER_CRC_OFFSET, disk->hdr_bak_crc);
1506         return 0;
1507 error:
1508         return -1;
1509 }
1510 
1511 //Write the contents of struct gpt_disk back to the actual disk
gpt_disk_commit(struct gpt_disk * disk)1512 int gpt_disk_commit(struct gpt_disk *disk)
1513 {
1514         int fd = -1;
1515         if (!disk || (disk->is_initialized != GPT_DISK_INIT_MAGIC)){
1516                 ALOGE("%s: Invalid args", __func__);
1517                 goto error;
1518         }
1519         fd = open(disk->devpath, O_RDWR);
1520         if (fd < 0) {
1521                 ALOGE("%s: Failed to open %s: %s",
1522                                 __func__,
1523                                 disk->devpath,
1524                                 strerror(errno));
1525                 goto error;
1526         }
1527         ALOGI("%s: Writing back primary GPT header", __func__);
1528         //Write the primary header
1529         if(gpt_set_header(disk->hdr, fd, PRIMARY_GPT) != 0) {
1530                 ALOGE("%s: Failed to update primary GPT header",
1531                                 __func__);
1532                 goto error;
1533         }
1534         ALOGI("%s: Writing back primary partition array", __func__);
1535         //Write back the primary partition array
1536         if (gpt_set_pentry_arr(disk->hdr, fd, disk->pentry_arr)) {
1537                 ALOGE("%s: Failed to write primary GPT partition arr",
1538                                 __func__);
1539                 goto error;
1540         }
1541         close(fd);
1542         return 0;
1543 error:
1544         if (fd >= 0)
1545                 close(fd);
1546         return -1;
1547 }
1548