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         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  */
gpt_pentry_seek(const char * ptn_name,const uint8_t * pentries_start,const uint8_t * pentries_end,uint32_t pentry_size)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  */
gpt_boot_chain_swap(const uint8_t * pentries_start,const uint8_t * pentries_end,uint32_t pentry_size)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  */
gpt2_set_boot_chain(int fd,enum boot_chain boot)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  */
gpt_get_state(int fd,enum gpt_instance gpt,enum gpt_state * state)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  */
gpt_set_state(int fd,enum gpt_instance gpt,enum gpt_state state)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 
get_scsi_node_from_bootdevice(const char * bootdev_path,char * sg_node_path,size_t buf_size)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 
set_boot_lun(char * sg_dev,uint8_t boot_lun_id)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
gpt_utils_set_xbl_boot_partition(enum boot_chain chain)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 
gpt_utils_is_ufs_device()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
prepare_partitions(enum boot_update_stage stage,const char * dev_path)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 
751     if (!dev_path) {
752         fprintf(stderr, "%s: Invalid dev_path\n",
753                         __func__);
754         r = -1;
755         goto EXIT;
756     }
757     fd = open(dev_path, O_RDWR);
758     if (fd < 0) {
759         fprintf(stderr, "%s: Opening '%s' failed: %s\n",
760                         __func__,
761                        BLK_DEV_FILE,
762                        strerror(errno));
763         r = -1;
764         goto EXIT;
765     }
766     r = gpt_get_state(fd, PRIMARY_GPT, &gpt_prim) ||
767         gpt_get_state(fd, SECONDARY_GPT, &gpt_second);
768     if (r) {
769         fprintf(stderr, "%s: Getting GPT headers state failed\n",
770                         __func__);
771         goto EXIT;
772     }
773 
774     /* These 2 combinations are unexpected and unacceptable */
775     if (gpt_prim == GPT_BAD_CRC || gpt_second == GPT_BAD_CRC) {
776         fprintf(stderr, "%s: GPT headers CRC corruption detected, aborting\n",
777                         __func__);
778         r = -1;
779         goto EXIT;
780     }
781     if (gpt_prim == GPT_BAD_SIGNATURE && gpt_second == GPT_BAD_SIGNATURE) {
782         fprintf(stderr, "%s: Both GPT headers corrupted, aborting\n",
783                         __func__);
784         r = -1;
785         goto EXIT;
786     }
787 
788     /* Check internal update stage according GPT headers' state */
789     if (gpt_prim == GPT_OK && gpt_second == GPT_OK)
790         internal_stage = UPDATE_MAIN;
791     else if (gpt_prim == GPT_BAD_SIGNATURE)
792         internal_stage = UPDATE_BACKUP;
793     else if (gpt_second == GPT_BAD_SIGNATURE)
794         internal_stage = UPDATE_FINALIZE;
795     else {
796         fprintf(stderr, "%s: Abnormal GPTs state: primary (%d), secondary (%d), "
797                 "aborting\n", __func__, gpt_prim, gpt_second);
798         r = -1;
799         goto EXIT;
800     }
801 
802     /* Stage already set - ready for update, exitting */
803     if ((int) stage == (int) internal_stage - 1)
804         goto EXIT;
805     /* Unexpected stage given */
806     if (stage != internal_stage) {
807         r = -1;
808         goto EXIT;
809     }
810 
811     switch (stage) {
812     case UPDATE_MAIN:
813             if (is_ufs) {
814                 if(stat(XBL_PRIMARY, &xbl_partition_stat)||
815                                 stat(XBL_BACKUP, &xbl_partition_stat)){
816                         //Non fatal error. Just means this target does not
817                         //use XBL but relies on sbl whose update is handled
818                         //by the normal methods.
819                         fprintf(stderr, "%s: xbl part not found(%s).Assuming sbl in use\n",
820                                         __func__,
821                                         strerror(errno));
822                 } else {
823                         //Switch the boot lun so that backup boot LUN is used
824                         r = gpt_utils_set_xbl_boot_partition(BACKUP_BOOT);
825                         if(r){
826                                 fprintf(stderr, "%s: Failed to set xbl backup partition as boot\n",
827                                                 __func__);
828                                 goto EXIT;
829                         }
830                 }
831         }
832         //Fix up the backup GPT table so that it actually points to
833         //the backup copy of the boot critical images
834         fprintf(stderr, "%s: Preparing for primary partition update\n",
835                         __func__);
836         r = gpt2_set_boot_chain(fd, BACKUP_BOOT);
837         if (r) {
838             if (r < 0)
839                 fprintf(stderr,
840                                 "%s: Setting secondary GPT to backup boot failed\n",
841                                 __func__);
842             /* No backup partitions - do not corrupt GPT, do not flag error */
843             else
844                 r = 0;
845             goto EXIT;
846         }
847         //corrupt the primary GPT so that the backup(which now points to
848         //the backup boot partitions is used)
849         r = gpt_set_state(fd, PRIMARY_GPT, GPT_BAD_SIGNATURE);
850         if (r) {
851             fprintf(stderr, "%s: Corrupting primary GPT header failed\n",
852                             __func__);
853             goto EXIT;
854         }
855         break;
856     case UPDATE_BACKUP:
857         if (is_ufs) {
858                 if(stat(XBL_PRIMARY, &xbl_partition_stat)||
859                                 stat(XBL_BACKUP, &xbl_partition_stat)){
860                         //Non fatal error. Just means this target does not
861                         //use XBL but relies on sbl whose update is handled
862                         //by the normal methods.
863                         fprintf(stderr, "%s: xbl part not found(%s).Assuming sbl in use\n",
864                                         __func__,
865                                         strerror(errno));
866                 } else {
867                         //Switch the boot lun so that backup boot LUN is used
868                         r = gpt_utils_set_xbl_boot_partition(NORMAL_BOOT);
869                         if(r) {
870                                 fprintf(stderr, "%s: Failed to set xbl backup partition as boot\n",
871                                                 __func__);
872                                 goto EXIT;
873                         }
874                 }
875         }
876         //Fix the primary GPT header so that is used
877         fprintf(stderr, "%s: Preparing for backup partition update\n",
878                         __func__);
879         r = gpt_set_state(fd, PRIMARY_GPT, GPT_OK);
880         if (r) {
881             fprintf(stderr, "%s: Fixing primary GPT header failed\n",
882                              __func__);
883             goto EXIT;
884         }
885         //Corrupt the scondary GPT header
886         r = gpt_set_state(fd, SECONDARY_GPT, GPT_BAD_SIGNATURE);
887         if (r) {
888             fprintf(stderr, "%s: Corrupting secondary GPT header failed\n",
889                             __func__);
890             goto EXIT;
891         }
892         break;
893     case UPDATE_FINALIZE:
894         //Undo the changes we had made in the UPDATE_MAIN stage so that the
895         //primary/backup GPT headers once again point to the same set of
896         //partitions
897         fprintf(stderr, "%s: Finalizing partitions\n",
898                         __func__);
899         r = gpt2_set_boot_chain(fd, NORMAL_BOOT);
900         if (r < 0) {
901             fprintf(stderr, "%s: Setting secondary GPT to normal boot failed\n",
902                             __func__);
903             goto EXIT;
904         }
905 
906         r = gpt_set_state(fd, SECONDARY_GPT, GPT_OK);
907         if (r) {
908             fprintf(stderr, "%s: Fixing secondary GPT header failed\n",
909                             __func__);
910             goto EXIT;
911         }
912         break;
913     default:;
914     }
915 
916 EXIT:
917     if (fd >= 0) {
918        fsync(fd);
919        close(fd);
920     }
921     return r;
922 }
923 
add_lun_to_update_list(char * lun_path,struct update_data * dat)924 int add_lun_to_update_list(char *lun_path, struct update_data *dat)
925 {
926         uint32_t i = 0;
927         struct stat st;
928         if (!lun_path || !dat){
929                 fprintf(stderr, "%s: Invalid data",
930                                 __func__);
931                 return -1;
932         }
933         if (stat(lun_path, &st)) {
934                 fprintf(stderr, "%s: Unable to access %s. Skipping adding to list",
935                                 __func__,
936                                 lun_path);
937                 return -1;
938         }
939         if (dat->num_valid_entries == 0) {
940                 fprintf(stderr, "%s: Copying %s into lun_list[%d]\n",
941                                 __func__,
942                                 lun_path,
943                                 i);
944                 strlcpy(dat->lun_list[0], lun_path,
945                                 PATH_MAX * sizeof(char));
946                 dat->num_valid_entries = 1;
947         } else {
948                 for (i = 0; (i < dat->num_valid_entries) &&
949                                 (dat->num_valid_entries < MAX_LUNS - 1); i++) {
950                         //Check if the current LUN is not already part
951                         //of the lun list
952                         if (!strncmp(lun_path,dat->lun_list[i],
953                                                 strlen(dat->lun_list[i]))) {
954                                 //LUN already in list..Return
955                                 return 0;
956                         }
957                 }
958                 fprintf(stderr, "%s: Copying %s into lun_list[%d]\n",
959                                 __func__,
960                                 lun_path,
961                                 dat->num_valid_entries);
962                 //Add LUN path lun list
963                 strlcpy(dat->lun_list[dat->num_valid_entries], lun_path,
964                                 PATH_MAX * sizeof(char));
965                 dat->num_valid_entries++;
966         }
967         return 0;
968 }
969 
prepare_boot_update(enum boot_update_stage stage)970 int prepare_boot_update(enum boot_update_stage stage)
971 {
972         int is_ufs = gpt_utils_is_ufs_device();
973         struct stat ufs_dir_stat;
974         struct update_data data;
975         int rcode = 0;
976         uint32_t i = 0;
977         int is_error = 0;
978         const char ptn_swap_list[][MAX_GPT_NAME_SIZE] = { PTN_SWAP_LIST };
979         //Holds /dev/block/bootdevice/by-name/*bak entry
980         char buf[PATH_MAX] = {0};
981         //Holds the resolved path of the symlink stored in buf
982         char real_path[PATH_MAX] = {0};
983 
984         if (!is_ufs) {
985                 //emmc device. Just pass in path to mmcblk0
986                 return prepare_partitions(stage, BLK_DEV_FILE);
987         } else {
988                 //Now we need to find the list of LUNs over
989                 //which the boot critical images are spread
990                 //and set them up for failsafe updates.To do
991                 //this we find out where the symlinks for the
992                 //each of the paths under
993                 ///dev/block/bootdevice/by-name/PTN_SWAP_LIST
994                 //actually point to.
995                 fprintf(stderr, "%s: Running on a UFS device\n",
996                                 __func__);
997                 memset(&data, '\0', sizeof(struct update_data));
998                 for (i=0; i < ARRAY_SIZE(ptn_swap_list); i++) {
999                         //XBL on UFS does not follow the convention
1000                         //of being loaded based on well known GUID'S.
1001                         //We take care of switching the UFS boot LUN
1002                         //explicitly later on.
1003                         if (!strncmp(ptn_swap_list[i],
1004                                                 PTN_XBL,
1005                                                 strlen(PTN_XBL)))
1006                                 continue;
1007                         snprintf(buf, sizeof(buf),
1008                                         "%s/%sbak",
1009                                         BOOT_DEV_DIR,
1010                                         ptn_swap_list[i]);
1011                         if (stat(buf, &ufs_dir_stat)) {
1012                                 continue;
1013                         }
1014                         if (readlink(buf, real_path, sizeof(real_path) - 1) < 0)
1015                         {
1016                                 fprintf(stderr, "%s: readlink error. Skipping %s",
1017                                                 __func__,
1018                                                 strerror(errno));
1019                         } else {
1020                               if(strlen(real_path) < PATH_TRUNCATE_LOC + 1){
1021                                     fprintf(stderr, "Unknown path.Skipping :%s:\n",
1022                                                 real_path);
1023                                 } else {
1024                                     real_path[PATH_TRUNCATE_LOC] = '\0';
1025                                     add_lun_to_update_list(real_path, &data);
1026                                 }
1027                         }
1028                         memset(buf, '\0', sizeof(buf));
1029                         memset(real_path, '\0', sizeof(real_path));
1030                 }
1031                 for (i=0; i < data.num_valid_entries; i++) {
1032                         fprintf(stderr, "%s: Preparing %s for update stage %d\n",
1033                                         __func__,
1034                                         data.lun_list[i],
1035                                         stage);
1036                         rcode = prepare_partitions(stage, data.lun_list[i]);
1037                         if (rcode != 0)
1038                         {
1039                                 fprintf(stderr, "%s: Failed to prepare %s.Continuing..\n",
1040                                                 __func__,
1041                                                 data.lun_list[i]);
1042                                 is_error = 1;
1043                         }
1044                 }
1045         }
1046         if (is_error)
1047                 return -1;
1048         return 0;
1049 }
1050 
1051 //Given a parttion name(eg: rpm) get the path to the block device that
1052 //represents the GPT disk the partition resides on. In the case of emmc it
1053 //would be the default emmc dev(/dev/block/mmcblk0). In the case of UFS we look
1054 //through the /dev/block/bootdevice/by-name/ tree for partname, and resolve
1055 //the path to the LUN from there.
get_dev_path_from_partition_name(const char * partname,char * buf,size_t buflen)1056 static int get_dev_path_from_partition_name(const char *partname,
1057                 char *buf,
1058                 size_t buflen)
1059 {
1060         struct stat st;
1061         char path[PATH_MAX] = {0};
1062         if (!partname || !buf || buflen < ((PATH_TRUNCATE_LOC) + 1)) {
1063                 ALOGE("%s: Invalid argument", __func__);
1064                 goto error;
1065         }
1066         if (gpt_utils_is_ufs_device()) {
1067                 //Need to find the lun that holds partition partname
1068                 snprintf(path, sizeof(path),
1069                                 "%s/%s",
1070                                 BOOT_DEV_DIR,
1071                                 partname);
1072                 if (stat(path, &st)) {
1073                         goto error;
1074                 }
1075                 if (readlink(path, buf, buflen) < 0)
1076                 {
1077                         goto error;
1078                 } else {
1079                         buf[PATH_TRUNCATE_LOC] = '\0';
1080                 }
1081         } else {
1082                 snprintf(buf, buflen, "/dev/block/mmcblk0");
1083         }
1084         return 0;
1085 
1086 error:
1087         return -1;
1088 }
1089 
gpt_utils_get_partition_map(vector<string> & ptn_list,map<string,vector<string>> & partition_map)1090 int gpt_utils_get_partition_map(vector<string>& ptn_list,
1091                 map<string, vector<string>>& partition_map) {
1092         char devpath[PATH_MAX] = {'\0'};
1093         map<string, vector<string>>::iterator it;
1094         if (ptn_list.size() < 1) {
1095                 fprintf(stderr, "%s: Invalid ptn list\n", __func__);
1096                 return -1;
1097         }
1098         //Go through the passed in list
1099         for (uint32_t i = 0; i < ptn_list.size(); i++)
1100         {
1101                 //Key in the map is the path to the device that holds the
1102                 //partition
1103                 if (get_dev_path_from_partition_name(ptn_list[i].c_str(),
1104                                 devpath,
1105                                 sizeof(devpath))) {
1106                         //Not necessarily an error. The partition may just
1107                         //not be present.
1108                         continue;
1109                 }
1110                 string path = devpath;
1111                 it = partition_map.find(path);
1112                 if (it != partition_map.end()) {
1113                         it->second.push_back(ptn_list[i]);
1114                 } else {
1115                         vector<string> str_vec;
1116                         str_vec.push_back( ptn_list[i]);
1117                         partition_map.insert(pair<string, vector<string>>
1118                                         (path, str_vec));
1119                 }
1120                 memset(devpath, '\0', sizeof(devpath));
1121         }
1122         return 0;
1123 }
1124 
1125 //Get the block size of the disk represented by decsriptor fd
gpt_get_block_size(int fd)1126 static uint32_t gpt_get_block_size(int fd)
1127 {
1128         uint32_t block_size = 0;
1129         if (fd < 0) {
1130                 ALOGE("%s: invalid descriptor",
1131                                 __func__);
1132                 goto error;
1133         }
1134         if (ioctl(fd, BLKSSZGET, &block_size) != 0) {
1135                 ALOGE("%s: Failed to get GPT dev block size : %s",
1136                                 __func__,
1137                                 strerror(errno));
1138                 goto error;
1139         }
1140         return block_size;
1141 error:
1142         return 0;
1143 }
1144 
1145 //Write the GPT header present in the passed in buffer back to the
1146 //disk represented by fd
gpt_set_header(uint8_t * gpt_header,int fd,enum gpt_instance instance)1147 static int gpt_set_header(uint8_t *gpt_header, int fd,
1148                 enum gpt_instance instance)
1149 {
1150         uint32_t block_size = 0;
1151         off_t gpt_header_offset = 0;
1152         if (!gpt_header || fd < 0) {
1153                 ALOGE("%s: Invalid arguments",
1154                                 __func__);
1155                 goto error;
1156         }
1157         block_size = gpt_get_block_size(fd);
1158         ALOGI("%s: Block size is : %d", __func__, block_size);
1159         if (block_size == 0) {
1160                 ALOGE("%s: Failed to get block size", __func__);
1161                 goto error;
1162         }
1163         if (instance == PRIMARY_GPT)
1164                 gpt_header_offset = block_size;
1165         else
1166                 gpt_header_offset = lseek64(fd, 0, SEEK_END) - block_size;
1167         if (gpt_header_offset <= 0) {
1168                 ALOGE("%s: Failed to get gpt header offset",__func__);
1169                 goto error;
1170         }
1171         ALOGI("%s: Writing back header to offset %ld", __func__,
1172                 gpt_header_offset);
1173         if (blk_rw(fd, 1, gpt_header_offset, gpt_header, block_size)) {
1174                 ALOGE("%s: Failed to write back GPT header", __func__);
1175                 goto error;
1176         }
1177         return 0;
1178 error:
1179         return -1;
1180 }
1181 
1182 //Read out the GPT header for the disk that contains the partition partname
gpt_get_header(const char * partname,enum gpt_instance instance)1183 static uint8_t* gpt_get_header(const char *partname, enum gpt_instance instance)
1184 {
1185         uint8_t* hdr = NULL;
1186         char devpath[PATH_MAX] = {0};
1187         int64_t hdr_offset = 0;
1188         uint32_t block_size = 0;
1189         int fd = -1;
1190         if (!partname) {
1191                 ALOGE("%s: Invalid partition name", __func__);
1192                 goto error;
1193         }
1194         if (get_dev_path_from_partition_name(partname, devpath, sizeof(devpath))
1195                         != 0) {
1196                 ALOGE("%s: Failed to resolve path for %s",
1197                                 __func__,
1198                                 partname);
1199                 goto error;
1200         }
1201         fd = open(devpath, O_RDWR);
1202         if (fd < 0) {
1203                 ALOGE("%s: Failed to open %s : %s",
1204                                 __func__,
1205                                 devpath,
1206                                 strerror(errno));
1207                 goto error;
1208         }
1209         block_size = gpt_get_block_size(fd);
1210         if (block_size == 0)
1211         {
1212                 ALOGE("%s: Failed to get gpt block size for %s",
1213                                 __func__,
1214                                 partname);
1215                 goto error;
1216         }
1217 
1218         hdr = (uint8_t*)malloc(block_size);
1219         if (!hdr) {
1220                 ALOGE("%s: Failed to allocate memory for gpt header",
1221                                 __func__);
1222         }
1223         if (instance == PRIMARY_GPT)
1224                 hdr_offset = block_size;
1225         else {
1226                 hdr_offset = lseek64(fd, 0, SEEK_END) - block_size;
1227         }
1228         if (hdr_offset < 0) {
1229                 ALOGE("%s: Failed to get gpt header offset",
1230                                 __func__);
1231                 goto error;
1232         }
1233         if (blk_rw(fd, 0, hdr_offset, hdr, block_size)) {
1234                 ALOGE("%s: Failed to read GPT header from device",
1235                                 __func__);
1236                 goto error;
1237         }
1238         close(fd);
1239         return hdr;
1240 error:
1241         if (fd >= 0)
1242                 close(fd);
1243         if (hdr)
1244                 free(hdr);
1245         return NULL;
1246 }
1247 
1248 //Returns the partition entry array based on the
1249 //passed in buffer which contains the gpt header.
1250 //The fd here is the descriptor for the 'disk' which
1251 //holds the partition
gpt_get_pentry_arr(uint8_t * hdr,int fd)1252 static uint8_t* gpt_get_pentry_arr(uint8_t *hdr, int fd)
1253 {
1254         uint64_t pentries_start = 0;
1255         uint32_t pentry_size = 0;
1256         uint32_t block_size = 0;
1257         uint32_t pentries_arr_size = 0;
1258         uint8_t *pentry_arr = NULL;
1259         int rc = 0;
1260         if (!hdr) {
1261                 ALOGE("%s: Invalid header", __func__);
1262                 goto error;
1263         }
1264         if (fd < 0) {
1265                 ALOGE("%s: Invalid fd", __func__);
1266                 goto error;
1267         }
1268         block_size = gpt_get_block_size(fd);
1269         if (!block_size) {
1270                 ALOGE("%s: Failed to get gpt block size for",
1271                                 __func__);
1272                 goto error;
1273         }
1274         pentries_start = GET_8_BYTES(hdr + PENTRIES_OFFSET) * block_size;
1275         pentry_size = GET_4_BYTES(hdr + PENTRY_SIZE_OFFSET);
1276         pentries_arr_size =
1277                 GET_4_BYTES(hdr + PARTITION_COUNT_OFFSET) * pentry_size;
1278         pentry_arr = (uint8_t*)calloc(1, pentries_arr_size);
1279         if (!pentry_arr) {
1280                 ALOGE("%s: Failed to allocate memory for partition array",
1281                                 __func__);
1282                 goto error;
1283         }
1284         rc = blk_rw(fd, 0,
1285                         pentries_start,
1286                         pentry_arr,
1287                         pentries_arr_size);
1288         if (rc) {
1289                 ALOGE("%s: Failed to read partition entry array",
1290                                 __func__);
1291                 goto error;
1292         }
1293         return pentry_arr;
1294 error:
1295         if (pentry_arr)
1296                 free(pentry_arr);
1297         return NULL;
1298 }
1299 
gpt_set_pentry_arr(uint8_t * hdr,int fd,uint8_t * arr)1300 static int gpt_set_pentry_arr(uint8_t *hdr, int fd, uint8_t* arr)
1301 {
1302         uint32_t block_size = 0;
1303         uint64_t pentries_start = 0;
1304         uint32_t pentry_size = 0;
1305         uint32_t pentries_arr_size = 0;
1306         int rc = 0;
1307         if (!hdr || fd < 0 || !arr) {
1308                 ALOGE("%s: Invalid argument", __func__);
1309                 goto error;
1310         }
1311         block_size = gpt_get_block_size(fd);
1312         if (!block_size) {
1313                 ALOGE("%s: Failed to get gpt block size for",
1314                                 __func__);
1315                 goto error;
1316         }
1317         ALOGI("%s : Block size is %d", __func__, block_size);
1318         pentries_start = GET_8_BYTES(hdr + PENTRIES_OFFSET) * block_size;
1319         pentry_size = GET_4_BYTES(hdr + PENTRY_SIZE_OFFSET);
1320         pentries_arr_size =
1321                 GET_4_BYTES(hdr + PARTITION_COUNT_OFFSET) * pentry_size;
1322         ALOGI("%s: Writing partition entry array of size %d to offset %" PRIu64,
1323                         __func__,
1324                         pentries_arr_size,
1325                         pentries_start);
1326         rc = blk_rw(fd, 1,
1327                         pentries_start,
1328                         arr,
1329                         pentries_arr_size);
1330         if (rc) {
1331                 ALOGE("%s: Failed to read partition entry array",
1332                                 __func__);
1333                 goto error;
1334         }
1335         return 0;
1336 error:
1337         return -1;
1338 }
1339 
1340 
1341 
1342 //Allocate a handle used by calls to the "gpt_disk" api's
gpt_disk_alloc()1343 struct gpt_disk * gpt_disk_alloc()
1344 {
1345         struct gpt_disk *disk;
1346         disk = (struct gpt_disk *)malloc(sizeof(struct gpt_disk));
1347         if (!disk) {
1348                 ALOGE("%s: Failed to allocate memory", __func__);
1349                 goto end;
1350         }
1351         memset(disk, 0, sizeof(struct gpt_disk));
1352 end:
1353         return disk;
1354 }
1355 
1356 //Free previously allocated/initialized handle
gpt_disk_free(struct gpt_disk * disk)1357 void gpt_disk_free(struct gpt_disk *disk)
1358 {
1359         if (!disk)
1360                 return;
1361         if (disk->hdr)
1362                 free(disk->hdr);
1363         if (disk->hdr_bak)
1364                 free(disk->hdr_bak);
1365         if (disk->pentry_arr)
1366                 free(disk->pentry_arr);
1367         if (disk->pentry_arr_bak)
1368                 free(disk->pentry_arr_bak);
1369         free(disk);
1370         return;
1371 }
1372 
1373 //fills up the passed in gpt_disk struct with information about the
1374 //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)1375 int gpt_disk_get_disk_info(const char *dev, struct gpt_disk *dsk)
1376 {
1377         struct gpt_disk *disk = NULL;
1378         int fd = -1;
1379         uint32_t gpt_header_size = 0;
1380 
1381         if (!dsk || !dev) {
1382                 ALOGE("%s: Invalid arguments", __func__);
1383                 goto error;
1384         }
1385         disk = dsk;
1386         disk->hdr = gpt_get_header(dev, PRIMARY_GPT);
1387         if (!disk->hdr) {
1388                 ALOGE("%s: Failed to get primary header", __func__);
1389                 goto error;
1390         }
1391         gpt_header_size = GET_4_BYTES(disk->hdr + HEADER_SIZE_OFFSET);
1392         disk->hdr_crc = crc32(0, disk->hdr, gpt_header_size);
1393         disk->hdr_bak = gpt_get_header(dev, PRIMARY_GPT);
1394         if (!disk->hdr_bak) {
1395                 ALOGE("%s: Failed to get backup header", __func__);
1396                 goto error;
1397         }
1398         disk->hdr_bak_crc = crc32(0, disk->hdr_bak, gpt_header_size);
1399 
1400         //Descriptor for the block device. We will use this for further
1401         //modifications to the partition table
1402         if (get_dev_path_from_partition_name(dev,
1403                                 disk->devpath,
1404                                 sizeof(disk->devpath)) != 0) {
1405                 ALOGE("%s: Failed to resolve path for %s",
1406                                 __func__,
1407                                 dev);
1408                 goto error;
1409         }
1410         fd = open(disk->devpath, O_RDWR);
1411         if (fd < 0) {
1412                 ALOGE("%s: Failed to open %s: %s",
1413                                 __func__,
1414                                 disk->devpath,
1415                                 strerror(errno));
1416                 goto error;
1417         }
1418         disk->pentry_arr = gpt_get_pentry_arr(disk->hdr, fd);
1419         if (!disk->pentry_arr) {
1420                 ALOGE("%s: Failed to obtain partition entry array",
1421                                 __func__);
1422                 goto error;
1423         }
1424         disk->pentry_arr_bak = gpt_get_pentry_arr(disk->hdr_bak, fd);
1425         if (!disk->pentry_arr_bak) {
1426                 ALOGE("%s: Failed to obtain backup partition entry array",
1427                                 __func__);
1428                 goto error;
1429         }
1430         disk->pentry_size = GET_4_BYTES(disk->hdr + PENTRY_SIZE_OFFSET);
1431         disk->pentry_arr_size =
1432                 GET_4_BYTES(disk->hdr + PARTITION_COUNT_OFFSET) *
1433                 disk->pentry_size;
1434         disk->pentry_arr_crc = GET_4_BYTES(disk->hdr + PARTITION_CRC_OFFSET);
1435         disk->pentry_arr_bak_crc = GET_4_BYTES(disk->hdr_bak +
1436                         PARTITION_CRC_OFFSET);
1437         disk->block_size = gpt_get_block_size(fd);
1438         close(fd);
1439         disk->is_initialized = GPT_DISK_INIT_MAGIC;
1440         return 0;
1441 error:
1442         if (fd >= 0)
1443                 close(fd);
1444         return -1;
1445 }
1446 
1447 //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)1448 uint8_t* gpt_disk_get_pentry(struct gpt_disk *disk,
1449                 const char *partname,
1450                 enum gpt_instance instance)
1451 {
1452         uint8_t *ptn_arr = NULL;
1453         if (!disk || !partname || disk->is_initialized != GPT_DISK_INIT_MAGIC) {
1454                 ALOGE("%s: Invalid argument",__func__);
1455                 goto error;
1456         }
1457         ptn_arr = (instance == PRIMARY_GPT) ?
1458                 disk->pentry_arr : disk->pentry_arr_bak;
1459         return (gpt_pentry_seek(partname, ptn_arr,
1460                         ptn_arr + disk->pentry_arr_size ,
1461                         disk->pentry_size));
1462 error:
1463         return NULL;
1464 }
1465 
1466 //Update CRC values for the various components of the gpt_disk
1467 //structure. This function should be called after any of the fields
1468 //have been updated before the structure contents are written back to
1469 //disk.
gpt_disk_update_crc(struct gpt_disk * disk)1470 int gpt_disk_update_crc(struct gpt_disk *disk)
1471 {
1472         uint32_t gpt_header_size = 0;
1473         if (!disk || (disk->is_initialized != GPT_DISK_INIT_MAGIC)) {
1474                 ALOGE("%s: invalid argument", __func__);
1475                 goto error;
1476         }
1477         //Recalculate the CRC of the primary partiton array
1478         disk->pentry_arr_crc = crc32(0,
1479                         disk->pentry_arr,
1480                         disk->pentry_arr_size);
1481         //Recalculate the CRC of the backup partition array
1482         disk->pentry_arr_bak_crc = crc32(0,
1483                         disk->pentry_arr_bak,
1484                         disk->pentry_arr_size);
1485         //Update the partition CRC value in the primary GPT header
1486         PUT_4_BYTES(disk->hdr + PARTITION_CRC_OFFSET, disk->pentry_arr_crc);
1487         //Update the partition CRC value in the backup GPT header
1488         PUT_4_BYTES(disk->hdr_bak + PARTITION_CRC_OFFSET,
1489                         disk->pentry_arr_bak_crc);
1490         //Update the CRC value of the primary header
1491         gpt_header_size = GET_4_BYTES(disk->hdr + HEADER_SIZE_OFFSET);
1492         //Header CRC is calculated with its own CRC field set to 0
1493         PUT_4_BYTES(disk->hdr + HEADER_CRC_OFFSET, 0);
1494         PUT_4_BYTES(disk->hdr_bak + HEADER_CRC_OFFSET, 0);
1495         disk->hdr_crc = crc32(0, disk->hdr, gpt_header_size);
1496         disk->hdr_bak_crc = crc32(0, disk->hdr_bak, gpt_header_size);
1497         PUT_4_BYTES(disk->hdr + HEADER_CRC_OFFSET, disk->hdr_crc);
1498         PUT_4_BYTES(disk->hdr_bak + HEADER_CRC_OFFSET, disk->hdr_bak_crc);
1499         return 0;
1500 error:
1501         return -1;
1502 }
1503 
1504 //Write the contents of struct gpt_disk back to the actual disk
gpt_disk_commit(struct gpt_disk * disk)1505 int gpt_disk_commit(struct gpt_disk *disk)
1506 {
1507         int fd = -1;
1508         if (!disk || (disk->is_initialized != GPT_DISK_INIT_MAGIC)){
1509                 ALOGE("%s: Invalid args", __func__);
1510                 goto error;
1511         }
1512         fd = open(disk->devpath, O_RDWR);
1513         if (fd < 0) {
1514                 ALOGE("%s: Failed to open %s: %s",
1515                                 __func__,
1516                                 disk->devpath,
1517                                 strerror(errno));
1518                 goto error;
1519         }
1520         ALOGI("%s: Writing back primary GPT header", __func__);
1521         //Write the primary header
1522         if(gpt_set_header(disk->hdr, fd, PRIMARY_GPT) != 0) {
1523                 ALOGE("%s: Failed to update primary GPT header",
1524                                 __func__);
1525                 goto error;
1526         }
1527         ALOGI("%s: Writing back primary partition array", __func__);
1528         //Write back the primary partition array
1529         if (gpt_set_pentry_arr(disk->hdr, fd, disk->pentry_arr)) {
1530                 ALOGE("%s: Failed to write primary GPT partition arr",
1531                                 __func__);
1532                 goto error;
1533         }
1534         close(fd);
1535         return 0;
1536 error:
1537         if (fd >= 0)
1538                 close(fd);
1539         return -1;
1540 }
1541