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 #ifndef MCUBOOT_SINGLE_APPLICATION_SLOT
30     case 1: return FLASH_AREA_IMAGE_SECONDARY(image_index);
31 #endif
32 #if MCUBOOT_SWAP_USING_SCRATCH
33     case 2: return FLASH_AREA_IMAGE_SCRATCH;
34 #endif
35     }
36     return 255;
37 }
38 
flash_area_id_to_multi_image_slot(int image_index,int area_id)39 int flash_area_id_to_multi_image_slot(int image_index, int area_id)
40 {
41     if (area_id == FLASH_AREA_IMAGE_PRIMARY(image_index)) {
42         return 0;
43     }
44 #ifndef MCUBOOT_SINGLE_APPLICATION_SLOT
45     if (area_id == FLASH_AREA_IMAGE_SECONDARY(image_index)) {
46         return 1;
47     }
48 #endif
49     return 255;
50 }
51 
flash_area_sector_from_off(off_t off,struct flash_sector * sector)52 int flash_area_sector_from_off(off_t off, struct flash_sector *sector)
53 {
54     const struct flash_area *fa;
55     const struct hal_flash *hf;
56     uint32_t start;
57     uint32_t size;
58     int rc;
59     int i;
60 
61     rc = flash_area_open(FLASH_AREA_IMAGE_0, &fa);
62     if (rc != 0) {
63         return -1;
64     }
65 
66     rc = -1;
67     hf = hal_bsp_flash_dev(fa->fa_device_id);
68     for (i = 0; i < hf->hf_sector_cnt; i++) {
69         hf->hf_itf->hff_sector_info(hf, i, &start, &size);
70         if (start < fa->fa_off) {
71             continue;
72         }
73         if (off >= start - fa->fa_off && off <= (start - fa->fa_off) + size) {
74             sector->fs_off = start - fa->fa_off;
75             sector->fs_size = size;
76             rc = 0;
77             break;
78         }
79     }
80 
81     flash_area_close(fa);
82     return rc;
83 }
84