blob: 89aa55f9d1e1f14511dcc8307780eda2d2424b76 [file] [log] [blame]
micky387e96abca2019-06-11 02:35:20 +02001/*
2 * Copyright (c) 2013,2016, The Linux Foundation. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above
10 * copyright notice, this list of conditions and the following
11 * disclaimer in the documentation and/or other materials provided
12 * with the distribution.
13 * * Neither the name of The Linux Foundation nor the names of its
14 * contributors may be used to endorse or promote products derived
15 * from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
21 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
26 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
27 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30#define _LARGEFILE64_SOURCE /* enable lseek64() */
31
32/******************************************************************************
33 * INCLUDE SECTION
34 ******************************************************************************/
35#include <stdio.h>
36#include <fcntl.h>
37#include <string.h>
38#include <errno.h>
39#include <inttypes.h>
40#include <sys/stat.h>
41#include <sys/ioctl.h>
42#include <scsi/ufs/ioctl.h>
43#include <scsi/ufs/ufs.h>
44#include <unistd.h>
45#include <linux/fs.h>
46#include <limits.h>
47#include <dirent.h>
48#include <linux/kernel.h>
49#include <asm/byteorder.h>
50#include <map>
51#include <vector>
52#include <string>
53#define LOG_TAG "gpt-utils"
54#include <log/log.h>
55#include <cutils/properties.h>
56#include "gpt-utils.h"
micky387e96abca2019-06-11 02:35:20 +020057#include <endian.h>
Logan Chienc4ab4942017-05-17 15:36:58 +080058#include <zlib.h>
micky387e96abca2019-06-11 02:35:20 +020059
60
61/******************************************************************************
62 * DEFINE SECTION
63 ******************************************************************************/
64#define BLK_DEV_FILE "/dev/block/mmcblk0"
65/* list the names of the backed-up partitions to be swapped */
66/* extension used for the backup partitions - tzbak, abootbak, etc. */
67#define BAK_PTN_NAME_EXT "bak"
68#define XBL_PRIMARY "/dev/block/bootdevice/by-name/xbl"
69#define XBL_BACKUP "/dev/block/bootdevice/by-name/xblbak"
70#define XBL_AB_PRIMARY "/dev/block/bootdevice/by-name/xbl_a"
71#define XBL_AB_SECONDARY "/dev/block/bootdevice/by-name/xbl_b"
72/* GPT defines */
73#define MAX_LUNS 26
74//Size of the buffer that needs to be passed to the UFS ioctl
75#define UFS_ATTR_DATA_SIZE 32
76//This will allow us to get the root lun path from the path to the partition.
77//i.e: from /dev/block/sdaXXX get /dev/block/sda. The assumption here is that
78//the boot critical luns lie between sda to sdz which is acceptable because
79//only user added external disks,etc would lie beyond that limit which do not
80//contain partitions that interest us here.
81#define PATH_TRUNCATE_LOC (sizeof("/dev/block/sda") - 1)
82
83//From /dev/block/sda get just sda
84#define LUN_NAME_START_LOC (sizeof("/dev/block/") - 1)
85#define BOOT_LUN_A_ID 1
86#define BOOT_LUN_B_ID 2
87/******************************************************************************
88 * MACROS
89 ******************************************************************************/
90
91
92#define GET_4_BYTES(ptr) ((uint32_t) *((uint8_t *)(ptr)) | \
93 ((uint32_t) *((uint8_t *)(ptr) + 1) << 8) | \
94 ((uint32_t) *((uint8_t *)(ptr) + 2) << 16) | \
95 ((uint32_t) *((uint8_t *)(ptr) + 3) << 24))
96
97#define GET_8_BYTES(ptr) ((uint64_t) *((uint8_t *)(ptr)) | \
98 ((uint64_t) *((uint8_t *)(ptr) + 1) << 8) | \
99 ((uint64_t) *((uint8_t *)(ptr) + 2) << 16) | \
100 ((uint64_t) *((uint8_t *)(ptr) + 3) << 24) | \
101 ((uint64_t) *((uint8_t *)(ptr) + 4) << 32) | \
102 ((uint64_t) *((uint8_t *)(ptr) + 5) << 40) | \
103 ((uint64_t) *((uint8_t *)(ptr) + 6) << 48) | \
104 ((uint64_t) *((uint8_t *)(ptr) + 7) << 56))
105
106#define PUT_4_BYTES(ptr, y) *((uint8_t *)(ptr)) = (y) & 0xff; \
107 *((uint8_t *)(ptr) + 1) = ((y) >> 8) & 0xff; \
108 *((uint8_t *)(ptr) + 2) = ((y) >> 16) & 0xff; \
109 *((uint8_t *)(ptr) + 3) = ((y) >> 24) & 0xff;
110
111/******************************************************************************
112 * TYPES
113 ******************************************************************************/
114using namespace std;
115enum gpt_state {
116 GPT_OK = 0,
117 GPT_BAD_SIGNATURE,
118 GPT_BAD_CRC
119};
120//List of LUN's containing boot critical images.
121//Required in the case of UFS devices
122struct update_data {
123 char lun_list[MAX_LUNS][PATH_MAX];
124 uint32_t num_valid_entries;
125};
126
127/******************************************************************************
128 * FUNCTIONS
129 ******************************************************************************/
130/**
131 * ==========================================================================
132 *
133 * \brief Read/Write len bytes from/to block dev
134 *
135 * \param [in] fd block dev file descriptor (returned from open)
136 * \param [in] rw RW flag: 0 - read, != 0 - write
137 * \param [in] offset block dev offset [bytes] - RW start position
138 * \param [in] buf Pointer to the buffer containing the data
139 * \param [in] len RW size in bytes. Buf must be at least that big
140 *
141 * \return 0 on success
142 *
143 * ==========================================================================
144 */
145static int blk_rw(int fd, int rw, int64_t offset, uint8_t *buf, unsigned len)
146{
147 int r;
148
149 if (lseek64(fd, offset, SEEK_SET) < 0) {
150 fprintf(stderr, "block dev lseek64 %" PRId64 " failed: %s\n", offset,
151 strerror(errno));
152 return -1;
153 }
154
155 if (rw)
156 r = write(fd, buf, len);
157 else
158 r = read(fd, buf, len);
159
160 if (r < 0)
161 fprintf(stderr, "block dev %s failed: %s\n", rw ? "write" : "read",
162 strerror(errno));
163 else
164 r = 0;
165
166 return r;
167}
168
169
170
171/**
172 * ==========================================================================
173 *
174 * \brief Search within GPT for partition entry with the given name
175 * or it's backup twin (name-bak).
176 *
177 * \param [in] ptn_name Partition name to seek
178 * \param [in] pentries_start Partition entries array start pointer
179 * \param [in] pentries_end Partition entries array end pointer
180 * \param [in] pentry_size Single partition entry size [bytes]
181 *
182 * \return First partition entry pointer that matches the name or NULL
183 *
184 * ==========================================================================
185 */
186static uint8_t *gpt_pentry_seek(const char *ptn_name,
187 const uint8_t *pentries_start,
188 const uint8_t *pentries_end,
189 uint32_t pentry_size)
190{
191 char *pentry_name;
192 unsigned len = strlen(ptn_name);
193
194 for (pentry_name = (char *) (pentries_start + PARTITION_NAME_OFFSET);
195 pentry_name < (char *) pentries_end; pentry_name += pentry_size) {
196 char name8[MAX_GPT_NAME_SIZE] = {0}; // initialize with null
197 unsigned i;
198
199 /* Partition names in GPT are UTF-16 - ignoring UTF-16 2nd byte */
200 for (i = 0; i < sizeof(name8) / 2; i++)
201 name8[i] = pentry_name[i * 2];
202 if (!strncmp(ptn_name, name8, len))
203 if (name8[len] == 0 || !strcmp(&name8[len], BAK_PTN_NAME_EXT))
204 return (uint8_t *) (pentry_name - PARTITION_NAME_OFFSET);
205 }
206
207 return NULL;
208}
209
210
211
212/**
213 * ==========================================================================
214 *
215 * \brief Swaps boot chain in GPT partition entries array
216 *
217 * \param [in] pentries_start Partition entries array start
218 * \param [in] pentries_end Partition entries array end
219 * \param [in] pentry_size Single partition entry size
220 *
221 * \return 0 on success, 1 if no backup partitions found
222 *
223 * ==========================================================================
224 */
225static int gpt_boot_chain_swap(const uint8_t *pentries_start,
226 const uint8_t *pentries_end,
227 uint32_t pentry_size)
228{
229 const char ptn_swap_list[][MAX_GPT_NAME_SIZE] = { PTN_SWAP_LIST };
230
231 int backup_not_found = 1;
232 unsigned i;
233
234 for (i = 0; i < ARRAY_SIZE(ptn_swap_list); i++) {
235 uint8_t *ptn_entry;
236 uint8_t *ptn_bak_entry;
237 uint8_t ptn_swap[PTN_ENTRY_SIZE];
238 //Skip the xbl partition on UFS devices. That is handled
239 //seperately.
240 if (gpt_utils_is_ufs_device() && !strncmp(ptn_swap_list[i],
241 PTN_XBL,
242 strlen(PTN_XBL)))
243 continue;
244
245 ptn_entry = gpt_pentry_seek(ptn_swap_list[i], pentries_start,
246 pentries_end, pentry_size);
247 if (ptn_entry == NULL)
248 continue;
249
250 ptn_bak_entry = gpt_pentry_seek(ptn_swap_list[i],
251 ptn_entry + pentry_size, pentries_end, pentry_size);
252 if (ptn_bak_entry == NULL) {
253 fprintf(stderr, "'%s' partition not backup - skip safe update\n",
254 ptn_swap_list[i]);
255 continue;
256 }
257
258 /* swap primary <-> backup partition entries */
259 memcpy(ptn_swap, ptn_entry, PTN_ENTRY_SIZE);
260 memcpy(ptn_entry, ptn_bak_entry, PTN_ENTRY_SIZE);
261 memcpy(ptn_bak_entry, ptn_swap, PTN_ENTRY_SIZE);
262 backup_not_found = 0;
263 }
264
265 return backup_not_found;
266}
267
268
269
270/**
271 * ==========================================================================
272 *
273 * \brief Sets secondary GPT boot chain
274 *
275 * \param [in] fd block dev file descriptor
276 * \param [in] boot Boot chain to switch to
277 *
278 * \return 0 on success
279 *
280 * ==========================================================================
281 */
282static int gpt2_set_boot_chain(int fd, enum boot_chain boot)
283{
284 int64_t gpt2_header_offset;
285 uint64_t pentries_start_offset;
286 uint32_t gpt_header_size;
287 uint32_t pentry_size;
288 uint32_t pentries_array_size;
289
290 uint8_t *gpt_header = NULL;
291 uint8_t *pentries = NULL;
292 uint32_t crc;
293 uint32_t blk_size = 0;
294 int r;
295
296 if (ioctl(fd, BLKSSZGET, &blk_size) != 0) {
297 fprintf(stderr, "Failed to get GPT device block size: %s\n",
298 strerror(errno));
299 r = -1;
300 goto EXIT;
301 }
302 gpt_header = (uint8_t*)malloc(blk_size);
303 if (!gpt_header) {
304 fprintf(stderr, "Failed to allocate memory to hold GPT block\n");
305 r = -1;
306 goto EXIT;
307 }
308 gpt2_header_offset = lseek64(fd, 0, SEEK_END) - blk_size;
309 if (gpt2_header_offset < 0) {
310 fprintf(stderr, "Getting secondary GPT header offset failed: %s\n",
311 strerror(errno));
312 r = -1;
313 goto EXIT;
314 }
315
316 /* Read primary GPT header from block dev */
317 r = blk_rw(fd, 0, blk_size, gpt_header, blk_size);
318
319 if (r) {
320 fprintf(stderr, "Failed to read primary GPT header from blk dev\n");
321 goto EXIT;
322 }
323 pentries_start_offset =
324 GET_8_BYTES(gpt_header + PENTRIES_OFFSET) * blk_size;
325 pentry_size = GET_4_BYTES(gpt_header + PENTRY_SIZE_OFFSET);
326 pentries_array_size =
327 GET_4_BYTES(gpt_header + PARTITION_COUNT_OFFSET) * pentry_size;
328
329 pentries = (uint8_t *) calloc(1, pentries_array_size);
330 if (pentries == NULL) {
331 fprintf(stderr,
332 "Failed to alloc memory for GPT partition entries array\n");
333 r = -1;
334 goto EXIT;
335 }
336 /* Read primary GPT partititon entries array from block dev */
337 r = blk_rw(fd, 0, pentries_start_offset, pentries, pentries_array_size);
338 if (r)
339 goto EXIT;
340
Logan Chienc4ab4942017-05-17 15:36:58 +0800341 crc = crc32(0, pentries, pentries_array_size);
micky387e96abca2019-06-11 02:35:20 +0200342 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
Logan Chienc4ab4942017-05-17 15:36:58 +0800364 crc = crc32(0, pentries, pentries_array_size);
micky387e96abca2019-06-11 02:35:20 +0200365 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);
Logan Chienc4ab4942017-05-17 15:36:58 +0800369 crc = crc32(0, gpt_header, gpt_header_size);
micky387e96abca2019-06-11 02:35:20 +0200370 PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, crc);
371
372 /* Write the modified GPT header back to block dev */
373 r = blk_rw(fd, 1, gpt2_header_offset, gpt_header, blk_size);
374 if (!r)
375 /* Write the modified GPT partititon entries array back to block dev */
376 r = blk_rw(fd, 1, pentries_start_offset, pentries,
377 pentries_array_size);
378
379EXIT:
380 if(gpt_header)
381 free(gpt_header);
382 if (pentries)
383 free(pentries);
384 return r;
385}
386
387/**
388 * ==========================================================================
389 *
390 * \brief Checks GPT state (header signature and CRC)
391 *
392 * \param [in] fd block dev file descriptor
393 * \param [in] gpt GPT header to be checked
394 * \param [out] state GPT header state
395 *
396 * \return 0 on success
397 *
398 * ==========================================================================
399 */
400static int gpt_get_state(int fd, enum gpt_instance gpt, enum gpt_state *state)
401{
402 int64_t gpt_header_offset;
403 uint32_t gpt_header_size;
404 uint8_t *gpt_header = NULL;
405 uint32_t crc;
406 uint32_t blk_size = 0;
407
408 *state = GPT_OK;
409
410 if (ioctl(fd, BLKSSZGET, &blk_size) != 0) {
411 fprintf(stderr, "Failed to get GPT device block size: %s\n",
412 strerror(errno));
413 goto error;
414 }
415 gpt_header = (uint8_t*)malloc(blk_size);
416 if (!gpt_header) {
417 fprintf(stderr, "gpt_get_state:Failed to alloc memory for header\n");
418 goto error;
419 }
420 if (gpt == PRIMARY_GPT)
421 gpt_header_offset = blk_size;
422 else {
423 gpt_header_offset = lseek64(fd, 0, SEEK_END) - blk_size;
424 if (gpt_header_offset < 0) {
425 fprintf(stderr, "gpt_get_state:Seek to end of GPT part fail\n");
426 goto error;
427 }
428 }
429
430 if (blk_rw(fd, 0, gpt_header_offset, gpt_header, blk_size)) {
431 fprintf(stderr, "gpt_get_state: blk_rw failed\n");
432 goto error;
433 }
434 if (memcmp(gpt_header, GPT_SIGNATURE, sizeof(GPT_SIGNATURE)))
435 *state = GPT_BAD_SIGNATURE;
436 gpt_header_size = GET_4_BYTES(gpt_header + HEADER_SIZE_OFFSET);
437
438 crc = GET_4_BYTES(gpt_header + HEADER_CRC_OFFSET);
439 /* header CRC is calculated with this field cleared */
440 PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, 0);
Logan Chienc4ab4942017-05-17 15:36:58 +0800441 if (crc32(0, gpt_header, gpt_header_size) != crc)
micky387e96abca2019-06-11 02:35:20 +0200442 *state = GPT_BAD_CRC;
443 free(gpt_header);
444 return 0;
445error:
446 if (gpt_header)
447 free(gpt_header);
448 return -1;
449}
450
451
452
453/**
454 * ==========================================================================
455 *
456 * \brief Sets GPT header state (used to corrupt and fix GPT signature)
457 *
458 * \param [in] fd block dev file descriptor
459 * \param [in] gpt GPT header to be checked
460 * \param [in] state GPT header state to set (GPT_OK or GPT_BAD_SIGNATURE)
461 *
462 * \return 0 on success
463 *
464 * ==========================================================================
465 */
466static int gpt_set_state(int fd, enum gpt_instance gpt, enum gpt_state state)
467{
468 int64_t gpt_header_offset;
469 uint32_t gpt_header_size;
470 uint8_t *gpt_header = NULL;
471 uint32_t crc;
472 uint32_t blk_size = 0;
473
474 if (ioctl(fd, BLKSSZGET, &blk_size) != 0) {
475 fprintf(stderr, "Failed to get GPT device block size: %s\n",
476 strerror(errno));
477 goto error;
478 }
479 gpt_header = (uint8_t*)malloc(blk_size);
480 if (!gpt_header) {
481 fprintf(stderr, "Failed to alloc memory for gpt header\n");
482 goto error;
483 }
484 if (gpt == PRIMARY_GPT)
485 gpt_header_offset = blk_size;
486 else {
487 gpt_header_offset = lseek64(fd, 0, SEEK_END) - blk_size;
488 if (gpt_header_offset < 0) {
489 fprintf(stderr, "Failed to seek to end of GPT device\n");
490 goto error;
491 }
492 }
493 if (blk_rw(fd, 0, gpt_header_offset, gpt_header, blk_size)) {
494 fprintf(stderr, "Failed to r/w gpt header\n");
495 goto error;
496 }
497 if (state == GPT_OK)
498 memcpy(gpt_header, GPT_SIGNATURE, sizeof(GPT_SIGNATURE));
499 else if (state == GPT_BAD_SIGNATURE)
500 *gpt_header = 0;
501 else {
502 fprintf(stderr, "gpt_set_state: Invalid state\n");
503 goto error;
504 }
505
506 gpt_header_size = GET_4_BYTES(gpt_header + HEADER_SIZE_OFFSET);
507
508 /* header CRC is calculated with this field cleared */
509 PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, 0);
Logan Chienc4ab4942017-05-17 15:36:58 +0800510 crc = crc32(0, gpt_header, gpt_header_size);
micky387e96abca2019-06-11 02:35:20 +0200511 PUT_4_BYTES(gpt_header + HEADER_CRC_OFFSET, crc);
512
513 if (blk_rw(fd, 1, gpt_header_offset, gpt_header, blk_size)) {
514 fprintf(stderr, "gpt_set_state: blk write failed\n");
515 goto error;
516 }
517 return 0;
518error:
519 if(gpt_header)
520 free(gpt_header);
521 return -1;
522}
523
524int get_scsi_node_from_bootdevice(const char *bootdev_path,
525 char *sg_node_path,
526 size_t buf_size)
527{
528 char sg_dir_path[PATH_MAX] = {0};
529 char real_path[PATH_MAX] = {0};
530 DIR *scsi_dir = NULL;
531 struct dirent *de;
532 int node_found = 0;
533 if (!bootdev_path || !sg_node_path) {
534 fprintf(stderr, "%s : invalid argument\n",
535 __func__);
536 goto error;
537 }
538 if (readlink(bootdev_path, real_path, sizeof(real_path) - 1) < 0) {
539 fprintf(stderr, "failed to resolve link for %s(%s)\n",
540 bootdev_path,
541 strerror(errno));
542 goto error;
543 }
544 if(strlen(real_path) < PATH_TRUNCATE_LOC + 1){
545 fprintf(stderr, "Unrecognized path :%s:\n",
546 real_path);
547 goto error;
548 }
549 //For the safe side in case there are additional partitions on
550 //the XBL lun we truncate the name.
551 real_path[PATH_TRUNCATE_LOC] = '\0';
552 if(strlen(real_path) < LUN_NAME_START_LOC + 1){
553 fprintf(stderr, "Unrecognized truncated path :%s:\n",
554 real_path);
555 goto error;
556 }
557 //This will give us /dev/block/sdb/device/scsi_generic
558 //which contains a file sgY whose name gives us the path
559 //to /dev/sgY which we return
560 snprintf(sg_dir_path, sizeof(sg_dir_path) - 1,
561 "/sys/block/%s/device/scsi_generic",
562 &real_path[LUN_NAME_START_LOC]);
563 scsi_dir = opendir(sg_dir_path);
564 if (!scsi_dir) {
565 fprintf(stderr, "%s : Failed to open %s(%s)\n",
566 __func__,
567 sg_dir_path,
568 strerror(errno));
569 goto error;
570 }
571 while((de = readdir(scsi_dir))) {
572 if (de->d_name[0] == '.')
573 continue;
574 else if (!strncmp(de->d_name, "sg", 2)) {
575 snprintf(sg_node_path,
576 buf_size -1,
577 "/dev/%s",
578 de->d_name);
579 fprintf(stderr, "%s:scsi generic node is :%s:\n",
580 __func__,
581 sg_node_path);
582 node_found = 1;
583 break;
584 }
585 }
586 if(!node_found) {
587 fprintf(stderr,"%s: Unable to locate scsi generic node\n",
588 __func__);
589 goto error;
590 }
591 closedir(scsi_dir);
592 return 0;
593error:
594 if (scsi_dir)
595 closedir(scsi_dir);
596 return -1;
597}
598
599int set_boot_lun(char *sg_dev, uint8_t boot_lun_id)
600{
601 int fd = -1;
602 int rc;
603 struct ufs_ioctl_query_data *data = NULL;
604 size_t ioctl_data_size = sizeof(struct ufs_ioctl_query_data) + UFS_ATTR_DATA_SIZE;
605
606 data = (struct ufs_ioctl_query_data*)malloc(ioctl_data_size);
607 if (!data) {
608 fprintf(stderr, "%s: Failed to alloc query data struct\n",
609 __func__);
610 goto error;
611 }
612 memset(data, 0, ioctl_data_size);
613 data->opcode = UPIU_QUERY_OPCODE_WRITE_ATTR;
614 data->idn = QUERY_ATTR_IDN_BOOT_LU_EN;
615 data->buf_size = UFS_ATTR_DATA_SIZE;
616 data->buffer[0] = boot_lun_id;
617 fd = open(sg_dev, O_RDWR);
618 if (fd < 0) {
619 fprintf(stderr, "%s: Failed to open %s(%s)\n",
620 __func__,
621 sg_dev,
622 strerror(errno));
623 goto error;
624 }
625 rc = ioctl(fd, UFS_IOCTL_QUERY, data);
626 if (rc) {
627 fprintf(stderr, "%s: UFS query ioctl failed(%s)\n",
628 __func__,
629 strerror(errno));
630 goto error;
631 }
632 close(fd);
633 free(data);
634 return 0;
635error:
636 if (fd >= 0)
637 close(fd);
638 if (data)
639 free(data);
640 return -1;
641}
642
643//Swtich betwieen using either the primary or the backup
644//boot LUN for boot. This is required since UFS boot partitions
645//cannot have a backup GPT which is what we use for failsafe
646//updates of the other 'critical' partitions. This function will
647//not be invoked for emmc targets and on UFS targets is only required
648//to be invoked for XBL.
649//
650//The algorithm to do this is as follows:
651//- Find the real block device(eg: /dev/block/sdb) that corresponds
652// to the /dev/block/bootdevice/by-name/xbl(bak) symlink
653//
654//- Once we have the block device 'node' name(sdb in the above example)
655// use this node to to locate the scsi generic device that represents
656// it by checking the file /sys/block/sdb/device/scsi_generic/sgY
657//
658//- Once we locate sgY we call the query ioctl on /dev/sgy to switch
659//the boot lun to either LUNA or LUNB
660int gpt_utils_set_xbl_boot_partition(enum boot_chain chain)
661{
662 struct stat st;
663 ///sys/block/sdX/device/scsi_generic/
664 char sg_dev_node[PATH_MAX] = {0};
665 uint8_t boot_lun_id = 0;
666 const char *boot_dev = NULL;
667
668 if (chain == BACKUP_BOOT) {
669 boot_lun_id = BOOT_LUN_B_ID;
670 if (!stat(XBL_BACKUP, &st))
671 boot_dev = XBL_BACKUP;
672 else if (!stat(XBL_AB_SECONDARY, &st))
673 boot_dev = XBL_AB_SECONDARY;
674 else {
675 fprintf(stderr, "%s: Failed to locate secondary xbl\n",
676 __func__);
677 goto error;
678 }
679 } else if (chain == NORMAL_BOOT) {
680 boot_lun_id = BOOT_LUN_A_ID;
681 if (!stat(XBL_PRIMARY, &st))
682 boot_dev = XBL_PRIMARY;
683 else if (!stat(XBL_AB_PRIMARY, &st))
684 boot_dev = XBL_AB_PRIMARY;
685 else {
686 fprintf(stderr, "%s: Failed to locate primary xbl\n",
687 __func__);
688 goto error;
689 }
690 } else {
691 fprintf(stderr, "%s: Invalid boot chain id\n", __func__);
692 goto error;
693 }
694 //We need either both xbl and xblbak or both xbl_a and xbl_b to exist at
695 //the same time. If not the current configuration is invalid.
696 if((stat(XBL_PRIMARY, &st) ||
697 stat(XBL_BACKUP, &st)) &&
698 (stat(XBL_AB_PRIMARY, &st) ||
699 stat(XBL_AB_SECONDARY, &st))) {
700 fprintf(stderr, "%s:primary/secondary XBL prt not found(%s)\n",
701 __func__,
702 strerror(errno));
703 goto error;
704 }
705 fprintf(stderr, "%s: setting %s lun as boot lun\n",
706 __func__,
707 boot_dev);
708 if (get_scsi_node_from_bootdevice(boot_dev,
709 sg_dev_node,
710 sizeof(sg_dev_node))) {
711 fprintf(stderr, "%s: Failed to get scsi node path for xblbak\n",
712 __func__);
713 goto error;
714 }
715 if (set_boot_lun(sg_dev_node, boot_lun_id)) {
716 fprintf(stderr, "%s: Failed to set xblbak as boot partition\n",
717 __func__);
718 goto error;
719 }
720 return 0;
721error:
722 return -1;
723}
724
725int gpt_utils_is_ufs_device()
726{
727 char bootdevice[PROPERTY_VALUE_MAX] = {0};
728 property_get("ro.boot.bootdevice", bootdevice, "N/A");
729 if (strlen(bootdevice) < strlen(".ufshc") + 1)
730 return 0;
731 return (!strncmp(&bootdevice[strlen(bootdevice) - strlen(".ufshc")],
732 ".ufshc",
733 sizeof(".ufshc")));
734}
735//dev_path is the path to the block device that contains the GPT image that
736//needs to be updated. This would be the device which holds one or more critical
737//boot partitions and their backups. In the case of EMMC this function would
738//be invoked only once on /dev/block/mmcblk1 since it holds the GPT image
739//containing all the partitions For UFS devices it could potentially be
740//invoked multiple times, once for each LUN containing critical image(s) and
741//their backups
742int prepare_partitions(enum boot_update_stage stage, const char *dev_path)
743{
744 int r = 0;
745 int fd = -1;
746 int is_ufs = gpt_utils_is_ufs_device();
747 enum gpt_state gpt_prim, gpt_second;
748 enum boot_update_stage internal_stage;
749 struct stat xbl_partition_stat;
micky387e96abca2019-06-11 02:35:20 +0200750
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
916EXIT:
917 if (fd >= 0) {
918 fsync(fd);
919 close(fd);
920 }
921 return r;
922}
923
924int 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
970int prepare_boot_update(enum boot_update_stage stage)
971{
micky387e96abca2019-06-11 02:35:20 +0200972 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.
1056static 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, BLK_DEV_FILE);
1083 }
1084 return 0;
1085
1086error:
1087 return -1;
1088}
1089
1090int 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 goto error;
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;
1123error:
1124 return -1;
1125}
1126
1127//Get the block size of the disk represented by decsriptor fd
1128static uint32_t gpt_get_block_size(int fd)
1129{
1130 uint32_t block_size = 0;
1131 if (fd < 0) {
1132 ALOGE("%s: invalid descriptor",
1133 __func__);
1134 goto error;
1135 }
1136 if (ioctl(fd, BLKSSZGET, &block_size) != 0) {
1137 ALOGE("%s: Failed to get GPT dev block size : %s",
1138 __func__,
1139 strerror(errno));
1140 goto error;
1141 }
1142 return block_size;
1143error:
1144 return 0;
1145}
1146
1147//Write the GPT header present in the passed in buffer back to the
1148//disk represented by fd
1149static int gpt_set_header(uint8_t *gpt_header, int fd,
1150 enum gpt_instance instance)
1151{
1152 uint32_t block_size = 0;
1153 off64_t gpt_header_offset = 0;
1154 if (!gpt_header || fd < 0) {
1155 ALOGE("%s: Invalid arguments",
1156 __func__);
1157 goto error;
1158 }
1159 block_size = gpt_get_block_size(fd);
1160 if (block_size == 0) {
1161 ALOGE("%s: Failed to get block size", __func__);
1162 goto error;
1163 }
1164 if (instance == PRIMARY_GPT)
1165 gpt_header_offset = block_size;
1166 else
1167 gpt_header_offset = lseek64(fd, 0, SEEK_END) - block_size;
1168 if (gpt_header_offset <= 0) {
1169 ALOGE("%s: Failed to get gpt header offset",__func__);
1170 goto error;
1171 }
1172 if (blk_rw(fd, 1, gpt_header_offset, gpt_header, block_size)) {
1173 ALOGE("%s: Failed to write back GPT header", __func__);
1174 goto error;
1175 }
1176 return 0;
1177error:
1178 return -1;
1179}
1180
1181//Read out the GPT header for the disk that contains the partition partname
1182static uint8_t* gpt_get_header(const char *partname, enum gpt_instance instance)
1183{
1184 uint8_t* hdr = NULL;
1185 char devpath[PATH_MAX] = {0};
1186 int64_t hdr_offset = 0;
1187 uint32_t block_size = 0;
1188 int fd = -1;
1189 if (!partname) {
1190 ALOGE("%s: Invalid partition name", __func__);
1191 goto error;
1192 }
1193 if (get_dev_path_from_partition_name(partname, devpath, sizeof(devpath))
1194 != 0) {
1195 ALOGE("%s: Failed to resolve path for %s",
1196 __func__,
1197 partname);
1198 goto error;
1199 }
1200 fd = open(devpath, O_RDWR);
1201 if (fd < 0) {
1202 ALOGE("%s: Failed to open %s : %s",
1203 __func__,
1204 devpath,
1205 strerror(errno));
1206 goto error;
1207 }
1208 block_size = gpt_get_block_size(fd);
1209 if (block_size == 0)
1210 {
1211 ALOGE("%s: Failed to get gpt block size for %s",
1212 __func__,
1213 partname);
1214 goto error;
1215 }
1216
1217 hdr = (uint8_t*)malloc(block_size);
1218 if (!hdr) {
1219 ALOGE("%s: Failed to allocate memory for gpt header",
1220 __func__);
1221 }
1222 if (instance == PRIMARY_GPT)
1223 hdr_offset = block_size;
1224 else {
1225 hdr_offset = lseek64(fd, 0, SEEK_END) - block_size;
1226 }
1227 if (hdr_offset < 0) {
1228 ALOGE("%s: Failed to get gpt header offset",
1229 __func__);
1230 goto error;
1231 }
1232 if (blk_rw(fd, 0, hdr_offset, hdr, block_size)) {
1233 ALOGE("%s: Failed to read GPT header from device",
1234 __func__);
1235 goto error;
1236 }
1237 close(fd);
1238 return hdr;
1239error:
1240 if (fd >= 0)
1241 close(fd);
1242 if (hdr)
1243 free(hdr);
1244 return NULL;
1245}
1246
1247//Returns the partition entry array based on the
1248//passed in buffer which contains the gpt header.
1249//The fd here is the descriptor for the 'disk' which
1250//holds the partition
1251static uint8_t* gpt_get_pentry_arr(uint8_t *hdr, int fd)
1252{
1253 uint64_t pentries_start = 0;
1254 uint32_t pentry_size = 0;
1255 uint32_t block_size = 0;
1256 uint32_t pentries_arr_size = 0;
1257 uint8_t *pentry_arr = NULL;
1258 int rc = 0;
1259 if (!hdr) {
1260 ALOGE("%s: Invalid header", __func__);
1261 goto error;
1262 }
1263 if (fd < 0) {
1264 ALOGE("%s: Invalid fd", __func__);
1265 goto error;
1266 }
1267 block_size = gpt_get_block_size(fd);
1268 if (!block_size) {
1269 ALOGE("%s: Failed to get gpt block size for",
1270 __func__);
1271 goto error;
1272 }
1273 pentries_start = GET_8_BYTES(hdr + PENTRIES_OFFSET) * block_size;
1274 pentry_size = GET_4_BYTES(hdr + PENTRY_SIZE_OFFSET);
1275 pentries_arr_size =
1276 GET_4_BYTES(hdr + PARTITION_COUNT_OFFSET) * pentry_size;
1277 pentry_arr = (uint8_t*)calloc(1, pentries_arr_size);
1278 if (!pentry_arr) {
1279 ALOGE("%s: Failed to allocate memory for partition array",
1280 __func__);
1281 goto error;
1282 }
1283 rc = blk_rw(fd, 0,
1284 pentries_start,
1285 pentry_arr,
1286 pentries_arr_size);
1287 if (rc) {
1288 ALOGE("%s: Failed to read partition entry array",
1289 __func__);
1290 goto error;
1291 }
1292 return pentry_arr;
1293error:
1294 if (pentry_arr)
1295 free(pentry_arr);
1296 return NULL;
1297}
1298
1299static int gpt_set_pentry_arr(uint8_t *hdr, int fd, uint8_t* arr)
1300{
1301 uint32_t block_size = 0;
1302 uint64_t pentries_start = 0;
1303 uint32_t pentry_size = 0;
1304 uint32_t pentries_arr_size = 0;
1305 int rc = 0;
1306 if (!hdr || fd < 0 || !arr) {
1307 ALOGE("%s: Invalid argument", __func__);
1308 goto error;
1309 }
1310 block_size = gpt_get_block_size(fd);
1311 if (!block_size) {
1312 ALOGE("%s: Failed to get gpt block size for",
1313 __func__);
1314 goto error;
1315 }
1316 pentries_start = GET_8_BYTES(hdr + PENTRIES_OFFSET) * block_size;
1317 pentry_size = GET_4_BYTES(hdr + PENTRY_SIZE_OFFSET);
1318 pentries_arr_size =
1319 GET_4_BYTES(hdr + PARTITION_COUNT_OFFSET) * pentry_size;
1320 rc = blk_rw(fd, 1,
1321 pentries_start,
1322 arr,
1323 pentries_arr_size);
1324 if (rc) {
1325 ALOGE("%s: Failed to read partition entry array",
1326 __func__);
1327 goto error;
1328 }
1329 return 0;
1330error:
1331 return -1;
1332}
1333
1334
1335
1336//Allocate a handle used by calls to the "gpt_disk" api's
1337struct gpt_disk * gpt_disk_alloc()
1338{
1339 struct gpt_disk *disk;
1340 disk = (struct gpt_disk *)malloc(sizeof(struct gpt_disk));
1341 if (!disk) {
1342 ALOGE("%s: Failed to allocate memory", __func__);
1343 goto end;
1344 }
1345 memset(disk, 0, sizeof(struct gpt_disk));
1346end:
1347 return disk;
1348}
1349
1350//Free previously allocated/initialized handle
1351void gpt_disk_free(struct gpt_disk *disk)
1352{
1353 if (!disk)
1354 return;
1355 if (disk->hdr)
1356 free(disk->hdr);
1357 if (disk->hdr_bak)
1358 free(disk->hdr_bak);
1359 if (disk->pentry_arr)
1360 free(disk->pentry_arr);
1361 if (disk->pentry_arr_bak)
1362 free(disk->pentry_arr_bak);
1363 free(disk);
1364 return;
1365}
1366
1367//fills up the passed in gpt_disk struct with information about the
1368//disk represented by path dev. Returns 0 on success and -1 on error.
1369int gpt_disk_get_disk_info(const char *dev, struct gpt_disk *dsk)
1370{
1371 struct gpt_disk *disk = NULL;
1372 int fd = -1;
1373 uint32_t gpt_header_size = 0;
1374
1375 if (!dsk || !dev) {
1376 ALOGE("%s: Invalid arguments", __func__);
1377 goto error;
1378 }
1379 disk = dsk;
1380 disk->hdr = gpt_get_header(dev, PRIMARY_GPT);
1381 if (!disk->hdr) {
1382 ALOGE("%s: Failed to get primary header", __func__);
1383 goto error;
1384 }
1385 gpt_header_size = GET_4_BYTES(disk->hdr + HEADER_SIZE_OFFSET);
Logan Chienc4ab4942017-05-17 15:36:58 +08001386 disk->hdr_crc = crc32(0, disk->hdr, gpt_header_size);
micky387e96abca2019-06-11 02:35:20 +02001387 disk->hdr_bak = gpt_get_header(dev, SECONDARY_GPT);
1388 if (!disk->hdr_bak) {
1389 ALOGE("%s: Failed to get backup header", __func__);
1390 goto error;
1391 }
Logan Chienc4ab4942017-05-17 15:36:58 +08001392 disk->hdr_bak_crc = crc32(0, disk->hdr_bak, gpt_header_size);
micky387e96abca2019-06-11 02:35:20 +02001393
1394 //Descriptor for the block device. We will use this for further
1395 //modifications to the partition table
1396 if (get_dev_path_from_partition_name(dev,
1397 disk->devpath,
1398 sizeof(disk->devpath)) != 0) {
1399 ALOGE("%s: Failed to resolve path for %s",
1400 __func__,
1401 dev);
1402 goto error;
1403 }
1404 fd = open(disk->devpath, O_RDWR);
1405 if (fd < 0) {
1406 ALOGE("%s: Failed to open %s: %s",
1407 __func__,
1408 disk->devpath,
1409 strerror(errno));
1410 goto error;
1411 }
1412 disk->pentry_arr = gpt_get_pentry_arr(disk->hdr, fd);
1413 if (!disk->pentry_arr) {
1414 ALOGE("%s: Failed to obtain partition entry array",
1415 __func__);
1416 goto error;
1417 }
1418 disk->pentry_arr_bak = gpt_get_pentry_arr(disk->hdr_bak, fd);
1419 if (!disk->pentry_arr_bak) {
1420 ALOGE("%s: Failed to obtain backup partition entry array",
1421 __func__);
1422 goto error;
1423 }
1424 disk->pentry_size = GET_4_BYTES(disk->hdr + PENTRY_SIZE_OFFSET);
1425 disk->pentry_arr_size =
1426 GET_4_BYTES(disk->hdr + PARTITION_COUNT_OFFSET) *
1427 disk->pentry_size;
1428 disk->pentry_arr_crc = GET_4_BYTES(disk->hdr + PARTITION_CRC_OFFSET);
1429 disk->pentry_arr_bak_crc = GET_4_BYTES(disk->hdr_bak +
1430 PARTITION_CRC_OFFSET);
1431 disk->block_size = gpt_get_block_size(fd);
1432 close(fd);
1433 disk->is_initialized = GPT_DISK_INIT_MAGIC;
1434 return 0;
1435error:
1436 if (fd >= 0)
1437 close(fd);
1438 return -1;
1439}
1440
1441//Get pointer to partition entry from a allocated gpt_disk structure
1442uint8_t* gpt_disk_get_pentry(struct gpt_disk *disk,
1443 const char *partname,
1444 enum gpt_instance instance)
1445{
1446 uint8_t *ptn_arr = NULL;
1447 if (!disk || !partname || disk->is_initialized != GPT_DISK_INIT_MAGIC) {
1448 ALOGE("%s: Invalid argument",__func__);
1449 goto error;
1450 }
1451 ptn_arr = (instance == PRIMARY_GPT) ?
1452 disk->pentry_arr : disk->pentry_arr_bak;
1453 return (gpt_pentry_seek(partname, ptn_arr,
1454 ptn_arr + disk->pentry_arr_size ,
1455 disk->pentry_size));
1456error:
1457 return NULL;
1458}
1459
1460//Update CRC values for the various components of the gpt_disk
1461//structure. This function should be called after any of the fields
1462//have been updated before the structure contents are written back to
1463//disk.
1464int gpt_disk_update_crc(struct gpt_disk *disk)
1465{
1466 uint32_t gpt_header_size = 0;
1467 if (!disk || (disk->is_initialized != GPT_DISK_INIT_MAGIC)) {
1468 ALOGE("%s: invalid argument", __func__);
1469 goto error;
1470 }
1471 //Recalculate the CRC of the primary partiton array
Logan Chienc4ab4942017-05-17 15:36:58 +08001472 disk->pentry_arr_crc = crc32(0,
micky387e96abca2019-06-11 02:35:20 +02001473 disk->pentry_arr,
1474 disk->pentry_arr_size);
1475 //Recalculate the CRC of the backup partition array
Logan Chienc4ab4942017-05-17 15:36:58 +08001476 disk->pentry_arr_bak_crc = crc32(0,
micky387e96abca2019-06-11 02:35:20 +02001477 disk->pentry_arr_bak,
1478 disk->pentry_arr_size);
1479 //Update the partition CRC value in the primary GPT header
1480 PUT_4_BYTES(disk->hdr + PARTITION_CRC_OFFSET, disk->pentry_arr_crc);
1481 //Update the partition CRC value in the backup GPT header
1482 PUT_4_BYTES(disk->hdr_bak + PARTITION_CRC_OFFSET,
1483 disk->pentry_arr_bak_crc);
1484 //Update the CRC value of the primary header
1485 gpt_header_size = GET_4_BYTES(disk->hdr + HEADER_SIZE_OFFSET);
1486 //Header CRC is calculated with its own CRC field set to 0
1487 PUT_4_BYTES(disk->hdr + HEADER_CRC_OFFSET, 0);
1488 PUT_4_BYTES(disk->hdr_bak + HEADER_CRC_OFFSET, 0);
Logan Chienc4ab4942017-05-17 15:36:58 +08001489 disk->hdr_crc = crc32(0, disk->hdr, gpt_header_size);
1490 disk->hdr_bak_crc = crc32(0, disk->hdr_bak, gpt_header_size);
micky387e96abca2019-06-11 02:35:20 +02001491 PUT_4_BYTES(disk->hdr + HEADER_CRC_OFFSET, disk->hdr_crc);
1492 PUT_4_BYTES(disk->hdr_bak + HEADER_CRC_OFFSET, disk->hdr_bak_crc);
1493 return 0;
1494error:
1495 return -1;
1496}
1497
1498//Write the contents of struct gpt_disk back to the actual disk
1499int gpt_disk_commit(struct gpt_disk *disk)
1500{
1501 int fd = -1;
1502 if (!disk || (disk->is_initialized != GPT_DISK_INIT_MAGIC)){
1503 ALOGE("%s: Invalid args", __func__);
1504 goto error;
1505 }
1506 fd = open(disk->devpath, O_RDWR);
1507 if (fd < 0) {
1508 ALOGE("%s: Failed to open %s: %s",
1509 __func__,
1510 disk->devpath,
1511 strerror(errno));
1512 goto error;
1513 }
1514 //Write the primary header
1515 if(gpt_set_header(disk->hdr, fd, PRIMARY_GPT) != 0) {
1516 ALOGE("%s: Failed to update primary GPT header",
1517 __func__);
1518 goto error;
1519 }
1520 //Write back the primary partition array
1521 if (gpt_set_pentry_arr(disk->hdr, fd, disk->pentry_arr)) {
1522 ALOGE("%s: Failed to write primary GPT partition arr",
1523 __func__);
1524 goto error;
1525 }
1526 //Write back the secondary header
1527 if(gpt_set_header(disk->hdr_bak, fd, SECONDARY_GPT) != 0) {
1528 ALOGE("%s: Failed to update secondary GPT header",
1529 __func__);
1530 goto error;
1531 }
1532 //Write back the secondary partition array
1533 if (gpt_set_pentry_arr(disk->hdr_bak, fd, disk->pentry_arr_bak)) {
1534 ALOGE("%s: Failed to write secondary GPT partition arr",
1535 __func__);
1536 goto error;
1537 }
1538 close(fd);
1539 return 0;
1540error:
1541 if (fd >= 0)
1542 close(fd);
1543 return -1;
1544}