1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements.  See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership.  The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License.  You may obtain a copy of the License at
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied.  See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #include <flash_map/flash_map.h>
21 #include <flash_map_backend/flash_map_backend.h>
22 #include <hal/hal_bsp.h>
23 #include <hal/hal_flash_int.h>
24 
flash_area_id_from_multi_image_slot(int image_index,int slot)25 int flash_area_id_from_multi_image_slot(int image_index, int slot)
26 {
27     switch (slot) {
28     case 0: return FLASH_AREA_IMAGE_PRIMARY(image_index);
29     case 1: return FLASH_AREA_IMAGE_SECONDARY(image_index);
30 #if MCUBOOT_SWAP_USING_SCRATCH
31     case 2: return FLASH_AREA_IMAGE_SCRATCH;
32 #endif
33     }
34     return 255;
35 }
36 
flash_area_id_to_multi_image_slot(int image_index,int area_id)37 int flash_area_id_to_multi_image_slot(int image_index, int area_id)
38 {
39     if (area_id == FLASH_AREA_IMAGE_PRIMARY(image_index)) {
40         return 0;
41     }
42     if (area_id == FLASH_AREA_IMAGE_SECONDARY(image_index)) {
43         return 1;
44     }
45     return 255;
46 }
47 
flash_area_sector_from_off(off_t off,struct flash_sector * sector)48 int flash_area_sector_from_off(off_t off, struct flash_sector *sector)
49 {
50     const struct flash_area *fa;
51     const struct hal_flash *hf;
52     uint32_t start;
53     uint32_t size;
54     int rc;
55     int i;
56 
57     rc = flash_area_open(FLASH_AREA_IMAGE_0, &fa);
58     if (rc != 0) {
59         return -1;
60     }
61 
62     rc = -1;
63     hf = hal_bsp_flash_dev(fa->fa_device_id);
64     for (i = 0; i < hf->hf_sector_cnt; i++) {
65         hf->hf_itf->hff_sector_info(hf, i, &start, &size);
66         if (start < fa->fa_off) {
67             continue;
68         }
69         if (off >= start - fa->fa_off && off <= (start - fa->fa_off) + size) {
70             sector->fs_off = start - fa->fa_off;
71             sector->fs_size = size;
72             rc = 0;
73             break;
74         }
75     }
76 
77     flash_area_close(fa);
78     return rc;
79 }
80