1 // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <stdint.h>
16 #include <stdbool.h>
17 #include <stddef.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <assert.h>
22 #include <freertos/FreeRTOS.h>
23 #include <freertos/task.h>
24
25 #include "esp_err.h"
26 #include "esp_partition.h"
27 #include "esp_spi_flash.h"
28 #include "esp_image_format.h"
29 #include "esp_secure_boot.h"
30 #include "esp_flash_encrypt.h"
31 #include "esp_spi_flash.h"
32 #include "sdkconfig.h"
33
34 #include "esp_ota_ops.h"
35 #include "sys/queue.h"
36 #include "esp_log.h"
37 #include "esp_flash_partitions.h"
38 #include "bootloader_common.h"
39 #include "sys/param.h"
40 #include "esp_system.h"
41 #include "esp_efuse.h"
42 #include "esp_attr.h"
43
44 #define SUB_TYPE_ID(i) (i & 0x0F)
45
46 /* Partial_data is word aligned so no reallocation is necessary for encrypted flash write */
47 typedef struct ota_ops_entry_ {
48 uint32_t handle;
49 const esp_partition_t *part;
50 bool need_erase;
51 uint32_t wrote_size;
52 uint8_t partial_bytes;
53 WORD_ALIGNED_ATTR uint8_t partial_data[16];
54 LIST_ENTRY(ota_ops_entry_) entries;
55 } ota_ops_entry_t;
56
57 static LIST_HEAD(ota_ops_entries_head, ota_ops_entry_) s_ota_ops_entries_head =
58 LIST_HEAD_INITIALIZER(s_ota_ops_entries_head);
59
60 static uint32_t s_ota_ops_last_handle = 0;
61
62 const static char *TAG = "esp_ota_ops";
63
64 /* Return true if this is an OTA app partition */
is_ota_partition(const esp_partition_t * p)65 static bool is_ota_partition(const esp_partition_t *p)
66 {
67 return (p != NULL
68 && p->type == ESP_PARTITION_TYPE_APP
69 && p->subtype >= ESP_PARTITION_SUBTYPE_APP_OTA_0
70 && p->subtype < ESP_PARTITION_SUBTYPE_APP_OTA_MAX);
71 }
72
73 // Read otadata partition and fill array from two otadata structures.
74 // Also return pointer to otadata info partition.
read_otadata(esp_ota_select_entry_t * two_otadata)75 static const esp_partition_t *read_otadata(esp_ota_select_entry_t *two_otadata)
76 {
77 const esp_partition_t *otadata_partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_OTA, NULL);
78
79 if (otadata_partition == NULL) {
80 ESP_LOGE(TAG, "not found otadata");
81 return NULL;
82 }
83
84 spi_flash_mmap_handle_t ota_data_map;
85 const void *result = NULL;
86 esp_err_t err = esp_partition_mmap(otadata_partition, 0, otadata_partition->size, SPI_FLASH_MMAP_DATA, &result, &ota_data_map);
87 if (err != ESP_OK) {
88 ESP_LOGE(TAG, "mmap otadata filed. Err=0x%8x", err);
89 return NULL;
90 } else {
91 memcpy(&two_otadata[0], result, sizeof(esp_ota_select_entry_t));
92 memcpy(&two_otadata[1], result + SPI_FLASH_SEC_SIZE, sizeof(esp_ota_select_entry_t));
93 spi_flash_munmap(ota_data_map);
94 }
95 return otadata_partition;
96 }
97
image_validate(const esp_partition_t * partition,esp_image_load_mode_t load_mode)98 static esp_err_t image_validate(const esp_partition_t *partition, esp_image_load_mode_t load_mode)
99 {
100 esp_image_metadata_t data;
101 const esp_partition_pos_t part_pos = {
102 .offset = partition->address,
103 .size = partition->size,
104 };
105
106 if (esp_image_verify(load_mode, &part_pos, &data) != ESP_OK) {
107 return ESP_ERR_OTA_VALIDATE_FAILED;
108 }
109
110 return ESP_OK;
111 }
112
set_new_state_otadata(void)113 static esp_ota_img_states_t set_new_state_otadata(void)
114 {
115 #ifdef CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
116 ESP_LOGD(TAG, "Monitoring the first boot of the app is enabled.");
117 return ESP_OTA_IMG_NEW;
118 #else
119 return ESP_OTA_IMG_UNDEFINED;
120 #endif
121 }
122
esp_ota_begin(const esp_partition_t * partition,size_t image_size,esp_ota_handle_t * out_handle)123 esp_err_t esp_ota_begin(const esp_partition_t *partition, size_t image_size, esp_ota_handle_t *out_handle)
124 {
125 ota_ops_entry_t *new_entry;
126 esp_err_t ret = ESP_OK;
127
128 if ((partition == NULL) || (out_handle == NULL)) {
129 return ESP_ERR_INVALID_ARG;
130 }
131
132 partition = esp_partition_verify(partition);
133 if (partition == NULL) {
134 return ESP_ERR_NOT_FOUND;
135 }
136
137 if (!is_ota_partition(partition)) {
138 return ESP_ERR_INVALID_ARG;
139 }
140
141 const esp_partition_t* running_partition = esp_ota_get_running_partition();
142 if (partition == running_partition) {
143 return ESP_ERR_OTA_PARTITION_CONFLICT;
144 }
145
146 #ifdef CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
147 esp_ota_img_states_t ota_state_running_part;
148 if (esp_ota_get_state_partition(running_partition, &ota_state_running_part) == ESP_OK) {
149 if (ota_state_running_part == ESP_OTA_IMG_PENDING_VERIFY) {
150 ESP_LOGE(TAG, "Running app has not confirmed state (ESP_OTA_IMG_PENDING_VERIFY)");
151 return ESP_ERR_OTA_ROLLBACK_INVALID_STATE;
152 }
153 }
154 #endif
155
156 if (image_size != OTA_WITH_SEQUENTIAL_WRITES) {
157 // If input image size is 0 or OTA_SIZE_UNKNOWN, erase entire partition
158 if ((image_size == 0) || (image_size == OTA_SIZE_UNKNOWN)) {
159 ret = esp_partition_erase_range(partition, 0, partition->size);
160 } else {
161 const int aligned_erase_size = (image_size + SPI_FLASH_SEC_SIZE - 1) & ~(SPI_FLASH_SEC_SIZE - 1);
162 ret = esp_partition_erase_range(partition, 0, aligned_erase_size);
163 }
164 if (ret != ESP_OK) {
165 return ret;
166 }
167 }
168
169 new_entry = (ota_ops_entry_t *) calloc(sizeof(ota_ops_entry_t), 1);
170 if (new_entry == NULL) {
171 return ESP_ERR_NO_MEM;
172 }
173
174 LIST_INSERT_HEAD(&s_ota_ops_entries_head, new_entry, entries);
175
176 new_entry->part = partition;
177 new_entry->handle = ++s_ota_ops_last_handle;
178 new_entry->need_erase = (image_size == OTA_WITH_SEQUENTIAL_WRITES);
179 *out_handle = new_entry->handle;
180 return ESP_OK;
181 }
182
esp_ota_write(esp_ota_handle_t handle,const void * data,size_t size)183 esp_err_t esp_ota_write(esp_ota_handle_t handle, const void *data, size_t size)
184 {
185 const uint8_t *data_bytes = (const uint8_t *)data;
186 esp_err_t ret;
187 ota_ops_entry_t *it;
188
189 if (data == NULL) {
190 ESP_LOGE(TAG, "write data is invalid");
191 return ESP_ERR_INVALID_ARG;
192 }
193
194 // find ota handle in linked list
195 for (it = LIST_FIRST(&s_ota_ops_entries_head); it != NULL; it = LIST_NEXT(it, entries)) {
196 if (it->handle == handle) {
197 if (it->need_erase) {
198 // must erase the partition before writing to it
199 uint32_t first_sector = it->wrote_size / SPI_FLASH_SEC_SIZE;
200 uint32_t last_sector = (it->wrote_size + size) / SPI_FLASH_SEC_SIZE;
201
202 ret = ESP_OK;
203 if ((it->wrote_size % SPI_FLASH_SEC_SIZE) == 0) {
204 ret = esp_partition_erase_range(it->part, it->wrote_size, ((last_sector - first_sector) + 1) * SPI_FLASH_SEC_SIZE);
205 } else if (first_sector != last_sector) {
206 ret = esp_partition_erase_range(it->part, (first_sector + 1) * SPI_FLASH_SEC_SIZE, (last_sector - first_sector) * SPI_FLASH_SEC_SIZE);
207 }
208 if (ret != ESP_OK) {
209 return ret;
210 }
211 }
212
213 if (it->wrote_size == 0 && it->partial_bytes == 0 && size > 0 && data_bytes[0] != ESP_IMAGE_HEADER_MAGIC) {
214 ESP_LOGE(TAG, "OTA image has invalid magic byte (expected 0xE9, saw 0x%02x)", data_bytes[0]);
215 return ESP_ERR_OTA_VALIDATE_FAILED;
216 }
217
218 if (esp_flash_encryption_enabled()) {
219 /* Can only write 16 byte blocks to flash, so need to cache anything else */
220 size_t copy_len;
221
222 /* check if we have partially written data from earlier */
223 if (it->partial_bytes != 0) {
224 copy_len = MIN(16 - it->partial_bytes, size);
225 memcpy(it->partial_data + it->partial_bytes, data_bytes, copy_len);
226 it->partial_bytes += copy_len;
227 if (it->partial_bytes != 16) {
228 return ESP_OK; /* nothing to write yet, just filling buffer */
229 }
230 /* write 16 byte to partition */
231 ret = esp_partition_write(it->part, it->wrote_size, it->partial_data, 16);
232 if (ret != ESP_OK) {
233 return ret;
234 }
235 it->partial_bytes = 0;
236 memset(it->partial_data, 0xFF, 16);
237 it->wrote_size += 16;
238 data_bytes += copy_len;
239 size -= copy_len;
240 }
241
242 /* check if we need to save trailing data that we're about to write */
243 it->partial_bytes = size % 16;
244 if (it->partial_bytes != 0) {
245 size -= it->partial_bytes;
246 memcpy(it->partial_data, data_bytes + size, it->partial_bytes);
247 }
248 }
249
250 ret = esp_partition_write(it->part, it->wrote_size, data_bytes, size);
251 if(ret == ESP_OK){
252 it->wrote_size += size;
253 }
254 return ret;
255 }
256 }
257
258 //if go to here ,means don't find the handle
259 ESP_LOGE(TAG,"not found the handle");
260 return ESP_ERR_INVALID_ARG;
261 }
262
esp_ota_write_with_offset(esp_ota_handle_t handle,const void * data,size_t size,uint32_t offset)263 esp_err_t esp_ota_write_with_offset(esp_ota_handle_t handle, const void *data, size_t size, uint32_t offset)
264 {
265 const uint8_t *data_bytes = (const uint8_t *)data;
266 esp_err_t ret;
267 ota_ops_entry_t *it;
268
269 if (data == NULL) {
270 ESP_LOGE(TAG, "write data is invalid");
271 return ESP_ERR_INVALID_ARG;
272 }
273
274 // find ota handle in linked list
275 for (it = LIST_FIRST(&s_ota_ops_entries_head); it != NULL; it = LIST_NEXT(it, entries)) {
276 if (it->handle == handle) {
277 // must erase the partition before writing to it
278 assert(it->need_erase == 0 && "must erase the partition before writing to it");
279
280 /* esp_ota_write_with_offset is used to write data in non contiguous manner.
281 * Hence, unaligned data(less than 16 bytes) cannot be cached if flash encryption is enabled.
282 */
283 if (esp_flash_encryption_enabled() && (size % 16)) {
284 ESP_LOGE(TAG, "Size should be 16byte aligned for flash encryption case");
285 return ESP_ERR_INVALID_ARG;
286 }
287 ret = esp_partition_write(it->part, offset, data_bytes, size);
288 if (ret == ESP_OK) {
289 it->wrote_size += size;
290 }
291 return ret;
292 }
293 }
294
295 // OTA handle is not found in linked list
296 ESP_LOGE(TAG,"OTA handle not found");
297 return ESP_ERR_INVALID_ARG;
298 }
299
get_ota_ops_entry(esp_ota_handle_t handle)300 static ota_ops_entry_t *get_ota_ops_entry(esp_ota_handle_t handle)
301 {
302 ota_ops_entry_t *it = NULL;
303 for (it = LIST_FIRST(&s_ota_ops_entries_head); it != NULL; it = LIST_NEXT(it, entries)) {
304 if (it->handle == handle) {
305 break;
306 }
307 }
308 return it;
309 }
310
esp_ota_abort(esp_ota_handle_t handle)311 esp_err_t esp_ota_abort(esp_ota_handle_t handle)
312 {
313 ota_ops_entry_t *it = get_ota_ops_entry(handle);
314
315 if (it == NULL) {
316 return ESP_ERR_NOT_FOUND;
317 }
318 LIST_REMOVE(it, entries);
319 free(it);
320 return ESP_OK;
321 }
322
esp_ota_end(esp_ota_handle_t handle)323 esp_err_t esp_ota_end(esp_ota_handle_t handle)
324 {
325 ota_ops_entry_t *it = get_ota_ops_entry(handle);
326 esp_err_t ret = ESP_OK;
327
328 if (it == NULL) {
329 return ESP_ERR_NOT_FOUND;
330 }
331
332 /* 'it' holds the ota_ops_entry_t for 'handle' */
333
334 // esp_ota_end() is only valid if some data was written to this handle
335 if (it->wrote_size == 0) {
336 ret = ESP_ERR_INVALID_ARG;
337 goto cleanup;
338 }
339
340 if (it->partial_bytes > 0) {
341 /* Write out last 16 bytes, if necessary */
342 ret = esp_partition_write(it->part, it->wrote_size, it->partial_data, 16);
343 if (ret != ESP_OK) {
344 ret = ESP_ERR_INVALID_STATE;
345 goto cleanup;
346 }
347 it->wrote_size += 16;
348 it->partial_bytes = 0;
349 }
350
351 esp_image_metadata_t data;
352 const esp_partition_pos_t part_pos = {
353 .offset = it->part->address,
354 .size = it->part->size,
355 };
356
357 if (esp_image_verify(ESP_IMAGE_VERIFY, &part_pos, &data) != ESP_OK) {
358 ret = ESP_ERR_OTA_VALIDATE_FAILED;
359 goto cleanup;
360 }
361
362 cleanup:
363 LIST_REMOVE(it, entries);
364 free(it);
365 return ret;
366 }
367
rewrite_ota_seq(esp_ota_select_entry_t * two_otadata,uint32_t seq,uint8_t sec_id,const esp_partition_t * ota_data_partition)368 static esp_err_t rewrite_ota_seq(esp_ota_select_entry_t *two_otadata, uint32_t seq, uint8_t sec_id, const esp_partition_t *ota_data_partition)
369 {
370 if (two_otadata == NULL || sec_id > 1) {
371 return ESP_ERR_INVALID_ARG;
372 }
373
374 two_otadata[sec_id].ota_seq = seq;
375 two_otadata[sec_id].crc = bootloader_common_ota_select_crc(&two_otadata[sec_id]);
376 esp_err_t ret = esp_partition_erase_range(ota_data_partition, sec_id * SPI_FLASH_SEC_SIZE, SPI_FLASH_SEC_SIZE);
377 if (ret != ESP_OK) {
378 return ret;
379 } else {
380 return esp_partition_write(ota_data_partition, SPI_FLASH_SEC_SIZE * sec_id, &two_otadata[sec_id], sizeof(esp_ota_select_entry_t));
381 }
382 }
383
get_ota_partition_count(void)384 static uint8_t get_ota_partition_count(void)
385 {
386 uint16_t ota_app_count = 0;
387 while (esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_app_count, NULL) != NULL) {
388 assert(ota_app_count < 16 && "must erase the partition before writing to it");
389 ota_app_count++;
390 }
391 return ota_app_count;
392 }
393
esp_rewrite_ota_data(esp_partition_subtype_t subtype)394 static esp_err_t esp_rewrite_ota_data(esp_partition_subtype_t subtype)
395 {
396 esp_ota_select_entry_t otadata[2];
397 const esp_partition_t *otadata_partition = read_otadata(otadata);
398 if (otadata_partition == NULL) {
399 return ESP_ERR_NOT_FOUND;
400 }
401
402 uint8_t ota_app_count = get_ota_partition_count();
403 if (SUB_TYPE_ID(subtype) >= ota_app_count) {
404 return ESP_ERR_INVALID_ARG;
405 }
406
407 //esp32_idf use two sector for store information about which partition is running
408 //it defined the two sector as ota data partition,two structure esp_ota_select_entry_t is saved in the two sector
409 //named data in first sector as otadata[0], second sector data as otadata[1]
410 //e.g.
411 //if otadata[0].ota_seq == otadata[1].ota_seq == 0xFFFFFFFF,means ota info partition is in init status
412 //so it will boot factory application(if there is),if there's no factory application,it will boot ota[0] application
413 //if otadata[0].ota_seq != 0 and otadata[1].ota_seq != 0,it will choose a max seq ,and get value of max_seq%max_ota_app_number
414 //and boot a subtype (mask 0x0F) value is (max_seq - 1)%max_ota_app_number,so if want switch to run ota[x],can use next formulas.
415 //for example, if otadata[0].ota_seq = 4, otadata[1].ota_seq = 5, and there are 8 ota application,
416 //current running is (5-1)%8 = 4,running ota[4],so if we want to switch to run ota[7],
417 //we should add otadata[0].ota_seq (is 4) to 4 ,(8-1)%8=7,then it will boot ota[7]
418 //if A=(B - C)%D
419 //then B=(A + C)%D + D*n ,n= (0,1,2...)
420 //so current ota app sub type id is x , dest bin subtype is y,total ota app count is n
421 //seq will add (x + n*1 + 1 - seq)%n
422
423 int active_otadata = bootloader_common_get_active_otadata(otadata);
424 if (active_otadata != -1) {
425 uint32_t seq = otadata[active_otadata].ota_seq;
426 uint32_t i = 0;
427 while (seq > (SUB_TYPE_ID(subtype) + 1) % ota_app_count + i * ota_app_count) {
428 i++;
429 }
430 int next_otadata = (~active_otadata)&1; // if 0 -> will be next 1. and if 1 -> will be next 0.
431 otadata[next_otadata].ota_state = set_new_state_otadata();
432 return rewrite_ota_seq(otadata, (SUB_TYPE_ID(subtype) + 1) % ota_app_count + i * ota_app_count, next_otadata, otadata_partition);
433 } else {
434 /* Both OTA slots are invalid, probably because unformatted... */
435 int next_otadata = 0;
436 otadata[next_otadata].ota_state = set_new_state_otadata();
437 return rewrite_ota_seq(otadata, SUB_TYPE_ID(subtype) + 1, next_otadata, otadata_partition);
438 }
439 }
440
esp_ota_set_boot_partition(const esp_partition_t * partition)441 esp_err_t esp_ota_set_boot_partition(const esp_partition_t *partition)
442 {
443 if (partition == NULL) {
444 return ESP_ERR_INVALID_ARG;
445 }
446
447 if (image_validate(partition, ESP_IMAGE_VERIFY) != ESP_OK) {
448 return ESP_ERR_OTA_VALIDATE_FAILED;
449 }
450
451 // if set boot partition to factory bin ,just format ota info partition
452 if (partition->type == ESP_PARTITION_TYPE_APP) {
453 if (partition->subtype == ESP_PARTITION_SUBTYPE_APP_FACTORY) {
454 const esp_partition_t *find_partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_OTA, NULL);
455 if (find_partition != NULL) {
456 return esp_partition_erase_range(find_partition, 0, find_partition->size);
457 } else {
458 return ESP_ERR_NOT_FOUND;
459 }
460 } else {
461 #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
462 esp_app_desc_t partition_app_desc;
463 esp_err_t err = esp_ota_get_partition_description(partition, &partition_app_desc);
464 if (err != ESP_OK) {
465 return err;
466 }
467
468 if (esp_efuse_check_secure_version(partition_app_desc.secure_version) == false) {
469 ESP_LOGE(TAG, "This a new partition can not be booted due to a secure version is lower than stored in efuse. Partition will be erased.");
470 esp_err_t err = esp_partition_erase_range(partition, 0, partition->size);
471 if (err != ESP_OK) {
472 return err;
473 }
474 return ESP_ERR_OTA_SMALL_SEC_VER;
475 }
476 #endif
477 return esp_rewrite_ota_data(partition->subtype);
478 }
479 } else {
480 return ESP_ERR_INVALID_ARG;
481 }
482 }
483
find_default_boot_partition(void)484 static const esp_partition_t *find_default_boot_partition(void)
485 {
486 // This logic matches the logic of bootloader get_selected_boot_partition() & load_boot_image().
487
488 // Default to factory if present
489 const esp_partition_t *result = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_FACTORY, NULL);
490 if (result != NULL) {
491 return result;
492 }
493
494 // Try first OTA slot if no factory partition
495 for (esp_partition_subtype_t s = ESP_PARTITION_SUBTYPE_APP_OTA_MIN; s != ESP_PARTITION_SUBTYPE_APP_OTA_MAX; s++) {
496 result = esp_partition_find_first(ESP_PARTITION_TYPE_APP, s, NULL);
497 if (result != NULL) {
498 return result;
499 }
500 }
501
502 // Test app slot if present
503 result = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_TEST, NULL);
504 if (result != NULL) {
505 return result;
506 }
507
508 ESP_LOGE(TAG, "invalid partition table, no app partitions");
509 return NULL;
510 }
511
esp_ota_get_boot_partition(void)512 const esp_partition_t *esp_ota_get_boot_partition(void)
513 {
514 esp_ota_select_entry_t otadata[2];
515 const esp_partition_t *otadata_partition = read_otadata(otadata);
516 if (otadata_partition == NULL) {
517 return NULL;
518 }
519
520 int ota_app_count = get_ota_partition_count();
521 ESP_LOGD(TAG, "found ota app max = %d", ota_app_count);
522
523 if ((bootloader_common_ota_select_invalid(&otadata[0]) &&
524 bootloader_common_ota_select_invalid(&otadata[1])) ||
525 ota_app_count == 0) {
526 ESP_LOGD(TAG, "finding factory app...");
527 return find_default_boot_partition();
528 } else {
529 int active_otadata = bootloader_common_get_active_otadata(otadata);
530 if (active_otadata != -1) {
531 int ota_slot = (otadata[active_otadata].ota_seq - 1) % ota_app_count; // Actual OTA partition selection
532 ESP_LOGD(TAG, "finding ota_%d app...", ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_slot);
533 return esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_slot, NULL);
534 } else {
535 ESP_LOGE(TAG, "ota data invalid, no current app. Assuming factory");
536 return find_default_boot_partition();
537 }
538 }
539 }
540
541
esp_ota_get_running_partition(void)542 const esp_partition_t* esp_ota_get_running_partition(void)
543 {
544 static const esp_partition_t *curr_partition = NULL;
545
546 /*
547 * Currently running partition is unlikely to change across reset cycle,
548 * so it can be cached here, and avoid lookup on every flash write operation.
549 */
550 if (curr_partition != NULL) {
551 return curr_partition;
552 }
553
554 /* Find the flash address of this exact function. By definition that is part
555 of the currently running firmware. Then find the enclosing partition. */
556 size_t phys_offs = spi_flash_cache2phys(esp_ota_get_running_partition);
557
558 assert (phys_offs != SPI_FLASH_CACHE2PHYS_FAIL); /* indicates cache2phys lookup is buggy */
559
560 esp_partition_iterator_t it = esp_partition_find(ESP_PARTITION_TYPE_APP,
561 ESP_PARTITION_SUBTYPE_ANY,
562 NULL);
563 assert(it != NULL); /* has to be at least one app partition */
564
565 while (it != NULL) {
566 const esp_partition_t *p = esp_partition_get(it);
567 if (p->address <= phys_offs && p->address + p->size > phys_offs) {
568 esp_partition_iterator_release(it);
569 curr_partition = p;
570 return p;
571 }
572 it = esp_partition_next(it);
573 }
574
575 abort(); /* Partition table is invalid or corrupt */
576 }
577
578
esp_ota_get_next_update_partition(const esp_partition_t * start_from)579 const esp_partition_t* esp_ota_get_next_update_partition(const esp_partition_t *start_from)
580 {
581 const esp_partition_t *default_ota = NULL;
582 bool next_is_result = false;
583 if (start_from == NULL) {
584 start_from = esp_ota_get_running_partition();
585 } else {
586 start_from = esp_partition_verify(start_from);
587 }
588 assert (start_from != NULL);
589 /* at this point, 'start_from' points to actual partition table data in flash */
590
591
592 /* Two possibilities: either we want the OTA partition immediately after the current running OTA partition, or we
593 want the first OTA partition in the table (for the case when the last OTA partition is the running partition, or
594 if the current running partition is not OTA.)
595
596 This loop iterates subtypes instead of using esp_partition_find, so we
597 get all OTA partitions in a known order (low slot to high slot).
598 */
599
600 for (esp_partition_subtype_t t = ESP_PARTITION_SUBTYPE_APP_OTA_0;
601 t != ESP_PARTITION_SUBTYPE_APP_OTA_MAX;
602 t++) {
603 const esp_partition_t *p = esp_partition_find_first(ESP_PARTITION_TYPE_APP, t, NULL);
604 if (p == NULL) {
605 continue;
606 }
607
608 if (default_ota == NULL) {
609 /* Default to first OTA partition we find,
610 will be used if nothing else matches */
611 default_ota = p;
612 }
613
614 if (p == start_from) {
615 /* Next OTA partition is the one to use */
616 next_is_result = true;
617 }
618 else if (next_is_result) {
619 return p;
620 }
621 }
622
623 return default_ota;
624
625 }
626
esp_ota_get_partition_description(const esp_partition_t * partition,esp_app_desc_t * app_desc)627 esp_err_t esp_ota_get_partition_description(const esp_partition_t *partition, esp_app_desc_t *app_desc)
628 {
629 if (partition == NULL || app_desc == NULL) {
630 return ESP_ERR_INVALID_ARG;
631 }
632
633 if(partition->type != ESP_PARTITION_TYPE_APP) {
634 return ESP_ERR_NOT_SUPPORTED;
635 }
636
637 esp_err_t err = esp_partition_read(partition, sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t), app_desc, sizeof(esp_app_desc_t));
638 if (err != ESP_OK) {
639 return err;
640 }
641
642 if (app_desc->magic_word != ESP_APP_DESC_MAGIC_WORD) {
643 return ESP_ERR_NOT_FOUND;
644 }
645
646 return ESP_OK;
647 }
648
649 #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
esp_ota_set_anti_rollback(void)650 static esp_err_t esp_ota_set_anti_rollback(void) {
651 const esp_app_desc_t *app_desc = esp_ota_get_app_description();
652 return esp_efuse_update_secure_version(app_desc->secure_version);
653 }
654 #endif
655
656 // Checks applications on the slots which can be booted in case of rollback.
657 // Returns true if the slots have at least one app (except the running app).
esp_ota_check_rollback_is_possible(void)658 bool esp_ota_check_rollback_is_possible(void)
659 {
660 esp_ota_select_entry_t otadata[2];
661 if (read_otadata(otadata) == NULL) {
662 return false;
663 }
664
665 int ota_app_count = get_ota_partition_count();
666 if (ota_app_count == 0) {
667 return false;
668 }
669
670 bool valid_otadata[2];
671 valid_otadata[0] = bootloader_common_ota_select_valid(&otadata[0]);
672 valid_otadata[1] = bootloader_common_ota_select_valid(&otadata[1]);
673
674 int active_ota = bootloader_common_select_otadata(otadata, valid_otadata, true);
675 if (active_ota == -1) {
676 return false;
677 }
678 int last_active_ota = (~active_ota)&1;
679
680 const esp_partition_t *partition = NULL;
681 #ifndef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
682 if (valid_otadata[last_active_ota] == false) {
683 partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_FACTORY, NULL);
684 if (partition != NULL) {
685 if(image_validate(partition, ESP_IMAGE_VERIFY_SILENT) == ESP_OK) {
686 return true;
687 }
688 }
689 }
690 #endif
691
692 if (valid_otadata[last_active_ota] == true) {
693 int slot = (otadata[last_active_ota].ota_seq - 1) % ota_app_count;
694 partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_MIN + slot, NULL);
695 if (partition != NULL) {
696 if(image_validate(partition, ESP_IMAGE_VERIFY_SILENT) == ESP_OK) {
697 #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
698 esp_app_desc_t app_desc;
699 if (esp_ota_get_partition_description(partition, &app_desc) == ESP_OK &&
700 esp_efuse_check_secure_version(app_desc.secure_version) == true) {
701 return true;
702 }
703 #else
704 return true;
705 #endif
706 }
707 }
708 }
709 return false;
710 }
711
712 // if valid == false - will done rollback with reboot. After reboot will boot previous OTA[x] or Factory partition.
713 // if valid == true - it confirm that current OTA[x] is workable. Reboot will not happen.
esp_ota_current_ota_is_workable(bool valid)714 static esp_err_t esp_ota_current_ota_is_workable(bool valid)
715 {
716 esp_ota_select_entry_t otadata[2];
717 const esp_partition_t *otadata_partition = read_otadata(otadata);
718 if (otadata_partition == NULL) {
719 return ESP_ERR_NOT_FOUND;
720 }
721
722 int active_otadata = bootloader_common_get_active_otadata(otadata);
723 if (active_otadata != -1 && get_ota_partition_count() != 0) {
724 if (valid == true && otadata[active_otadata].ota_state != ESP_OTA_IMG_VALID) {
725 otadata[active_otadata].ota_state = ESP_OTA_IMG_VALID;
726 ESP_LOGD(TAG, "OTA[current] partition is marked as VALID");
727 esp_err_t err = rewrite_ota_seq(otadata, otadata[active_otadata].ota_seq, active_otadata, otadata_partition);
728 #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
729 if (err == ESP_OK) {
730 return esp_ota_set_anti_rollback();
731 }
732 #endif
733 return err;
734 } else if (valid == false) {
735 if (esp_ota_check_rollback_is_possible() == false) {
736 ESP_LOGE(TAG, "Rollback is not possible, do not have any suitable apps in slots");
737 return ESP_ERR_OTA_ROLLBACK_FAILED;
738 }
739 ESP_LOGD(TAG, "OTA[current] partition is marked as INVALID");
740 otadata[active_otadata].ota_state = ESP_OTA_IMG_INVALID;
741 esp_err_t err = rewrite_ota_seq(otadata, otadata[active_otadata].ota_seq, active_otadata, otadata_partition);
742 if (err != ESP_OK) {
743 return err;
744 }
745 ESP_LOGI(TAG, "Rollback to previously worked partition. Restart.");
746 esp_restart();
747 }
748 } else {
749 ESP_LOGE(TAG, "Running firmware is factory");
750 return ESP_FAIL;
751 }
752 return ESP_OK;
753 }
754
esp_ota_mark_app_valid_cancel_rollback(void)755 esp_err_t esp_ota_mark_app_valid_cancel_rollback(void)
756 {
757 return esp_ota_current_ota_is_workable(true);
758 }
759
esp_ota_mark_app_invalid_rollback_and_reboot(void)760 esp_err_t esp_ota_mark_app_invalid_rollback_and_reboot(void)
761 {
762 return esp_ota_current_ota_is_workable(false);
763 }
764
check_invalid_otadata(const esp_ota_select_entry_t * s)765 static bool check_invalid_otadata (const esp_ota_select_entry_t *s) {
766 return s->ota_seq != UINT32_MAX &&
767 s->crc == bootloader_common_ota_select_crc(s) &&
768 (s->ota_state == ESP_OTA_IMG_INVALID ||
769 s->ota_state == ESP_OTA_IMG_ABORTED);
770 }
771
get_last_invalid_otadata(const esp_ota_select_entry_t * two_otadata)772 static int get_last_invalid_otadata(const esp_ota_select_entry_t *two_otadata)
773 {
774
775 bool invalid_otadata[2];
776 invalid_otadata[0] = check_invalid_otadata(&two_otadata[0]);
777 invalid_otadata[1] = check_invalid_otadata(&two_otadata[1]);
778 int num_invalid_otadata = bootloader_common_select_otadata(two_otadata, invalid_otadata, false);
779 ESP_LOGD(TAG, "Invalid otadata[%d]", num_invalid_otadata);
780 return num_invalid_otadata;
781 }
782
esp_ota_get_last_invalid_partition(void)783 const esp_partition_t* esp_ota_get_last_invalid_partition(void)
784 {
785 esp_ota_select_entry_t otadata[2];
786 if (read_otadata(otadata) == NULL) {
787 return NULL;
788 }
789
790 int invalid_otadata = get_last_invalid_otadata(otadata);
791
792 int ota_app_count = get_ota_partition_count();
793 if (invalid_otadata != -1 && ota_app_count != 0) {
794 int ota_slot = (otadata[invalid_otadata].ota_seq - 1) % ota_app_count;
795 ESP_LOGD(TAG, "Find invalid ota_%d app", ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_slot);
796
797 const esp_partition_t* invalid_partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_slot, NULL);
798 if (invalid_partition != NULL) {
799 if (image_validate(invalid_partition, ESP_IMAGE_VERIFY_SILENT) != ESP_OK) {
800 ESP_LOGD(TAG, "Last invalid partition has corrupted app");
801 return NULL;
802 }
803 }
804 return invalid_partition;
805 }
806 return NULL;
807 }
808
esp_ota_get_state_partition(const esp_partition_t * partition,esp_ota_img_states_t * ota_state)809 esp_err_t esp_ota_get_state_partition(const esp_partition_t *partition, esp_ota_img_states_t *ota_state)
810 {
811 if (partition == NULL || ota_state == NULL) {
812 return ESP_ERR_INVALID_ARG;
813 }
814
815 if (!is_ota_partition(partition)) {
816 return ESP_ERR_NOT_SUPPORTED;
817 }
818
819 esp_ota_select_entry_t otadata[2];
820 int ota_app_count = get_ota_partition_count();
821 if (read_otadata(otadata) == NULL || ota_app_count == 0) {
822 return ESP_ERR_NOT_FOUND;
823 }
824
825 int req_ota_slot = partition->subtype - ESP_PARTITION_SUBTYPE_APP_OTA_MIN;
826 bool not_found = true;
827 for (int i = 0; i < 2; ++i) {
828 int ota_slot = (otadata[i].ota_seq - 1) % ota_app_count;
829 if (ota_slot == req_ota_slot && otadata[i].crc == bootloader_common_ota_select_crc(&otadata[i])) {
830 *ota_state = otadata[i].ota_state;
831 not_found = false;
832 break;
833 }
834 }
835
836 if (not_found) {
837 return ESP_ERR_NOT_FOUND;
838 }
839
840 return ESP_OK;
841 }
842
esp_ota_erase_last_boot_app_partition(void)843 esp_err_t esp_ota_erase_last_boot_app_partition(void)
844 {
845 esp_ota_select_entry_t otadata[2];
846 const esp_partition_t* ota_data_partition = read_otadata(otadata);
847 if (ota_data_partition == NULL) {
848 return ESP_FAIL;
849 }
850
851 int active_otadata = bootloader_common_get_active_otadata(otadata);
852 int ota_app_count = get_ota_partition_count();
853 if (active_otadata == -1 || ota_app_count == 0) {
854 return ESP_FAIL;
855 }
856
857 int inactive_otadata = (~active_otadata)&1;
858 if (otadata[inactive_otadata].ota_seq == UINT32_MAX || otadata[inactive_otadata].crc != bootloader_common_ota_select_crc(&otadata[inactive_otadata])) {
859 return ESP_FAIL;
860 }
861
862 int ota_slot = (otadata[inactive_otadata].ota_seq - 1) % ota_app_count; // Actual OTA partition selection
863 ESP_LOGD(TAG, "finding last_boot_app_partition ota_%d app...", ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_slot);
864
865 const esp_partition_t* last_boot_app_partition_from_otadata = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_slot, NULL);
866 if (last_boot_app_partition_from_otadata == NULL) {
867 return ESP_FAIL;
868 }
869
870 const esp_partition_t* running_partition = esp_ota_get_running_partition();
871 if (running_partition == NULL || last_boot_app_partition_from_otadata == running_partition) {
872 return ESP_FAIL;
873 }
874
875 esp_err_t err = esp_partition_erase_range(last_boot_app_partition_from_otadata, 0, last_boot_app_partition_from_otadata->size);
876 if (err != ESP_OK) {
877 return err;
878 }
879
880 int sec_id = inactive_otadata;
881 err = esp_partition_erase_range(ota_data_partition, sec_id * SPI_FLASH_SEC_SIZE, SPI_FLASH_SEC_SIZE);
882 if (err != ESP_OK) {
883 return err;
884 }
885
886 return ESP_OK;
887 }
888
889 #if SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS > 1 && CONFIG_SECURE_BOOT_V2_ENABLED
esp_ota_revoke_secure_boot_public_key(esp_ota_secure_boot_public_key_index_t index)890 esp_err_t esp_ota_revoke_secure_boot_public_key(esp_ota_secure_boot_public_key_index_t index) {
891
892 if (!esp_secure_boot_enabled()) {
893 ESP_LOGE(TAG, "Secure boot v2 has not been enabled.");
894 return ESP_FAIL;
895 }
896
897 if (index != SECURE_BOOT_PUBLIC_KEY_INDEX_0 &&
898 index != SECURE_BOOT_PUBLIC_KEY_INDEX_1 &&
899 index != SECURE_BOOT_PUBLIC_KEY_INDEX_2) {
900 ESP_LOGE(TAG, "Invalid Index found for public key revocation %d.", index);
901 return ESP_ERR_INVALID_ARG;
902 }
903
904 ets_secure_boot_revoke_public_key_digest(index);
905 ESP_LOGI(TAG, "Revoked signature block %d.", index);
906 return ESP_OK;
907 }
908 #endif
909