1 // Copyright 2020 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 <stdio.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #include "sdkconfig.h"
19 #include "esp_attr.h"
20 #include "esp_err.h"
21 #include "esp_log.h"
22 #include "esp32s2/clk.h"
23 #include "esp32s2/ulp.h"
24 #include "esp32s2/ulp_riscv.h"
25 #include "soc/soc.h"
26 #include "soc/rtc.h"
27 #include "soc/rtc_cntl_reg.h"
28 #include "soc/sens_reg.h"
29 #include "ulp_private.h"
30 #include "esp_rom_sys.h"
31
ulp_riscv_run(void)32 esp_err_t ulp_riscv_run(void)
33 {
34 /* Reset COCPU when power on. */
35 SET_PERI_REG_MASK(RTC_CNTL_COCPU_CTRL_REG, RTC_CNTL_COCPU_SHUT_RESET_EN);
36 esp_rom_delay_us(20);
37 CLEAR_PERI_REG_MASK(RTC_CNTL_COCPU_CTRL_REG, RTC_CNTL_COCPU_SHUT_RESET_EN);
38
39 /* The coprocessor cpu trap signal doesnt have a stable reset value,
40 force ULP-RISC-V clock on to stop RTC_COCPU_TRAP_TRIG_EN from waking the CPU*/
41 SET_PERI_REG_MASK(RTC_CNTL_COCPU_CTRL_REG, RTC_CNTL_COCPU_CLK_FO);
42
43 /* Disable ULP timer */
44 CLEAR_PERI_REG_MASK(RTC_CNTL_ULP_CP_TIMER_REG, RTC_CNTL_ULP_CP_SLP_TIMER_EN);
45 /* wait for at least 1 RTC_SLOW_CLK cycle */
46 esp_rom_delay_us(20);
47 /* Select RISC-V as the ULP_TIMER trigger target. */
48 CLEAR_PERI_REG_MASK(RTC_CNTL_COCPU_CTRL_REG, RTC_CNTL_COCPU_SEL);
49
50 /* Select ULP-RISC-V to send the DONE signal. */
51 SET_PERI_REG_MASK(RTC_CNTL_COCPU_CTRL_REG, RTC_CNTL_COCPU_DONE_FORCE);
52
53 /* start ULP_TIMER */
54 CLEAR_PERI_REG_MASK(RTC_CNTL_ULP_CP_CTRL_REG, RTC_CNTL_ULP_CP_FORCE_START_TOP);
55 SET_PERI_REG_MASK(RTC_CNTL_ULP_CP_TIMER_REG, RTC_CNTL_ULP_CP_SLP_TIMER_EN);
56
57 return ESP_OK;
58 }
59
ulp_riscv_load_binary(const uint8_t * program_binary,size_t program_size_bytes)60 esp_err_t ulp_riscv_load_binary(const uint8_t* program_binary, size_t program_size_bytes)
61 {
62 if (program_binary == NULL) {
63 return ESP_ERR_INVALID_ARG;
64 }
65 if (program_size_bytes > ULP_RESERVE_MEM) {
66 return ESP_ERR_INVALID_SIZE;
67 }
68
69 uint8_t* base = (uint8_t*) RTC_SLOW_MEM;
70
71 //Start by clearing memory reserved with zeros, this will also will initialize the bss:
72 memset(base, 0, ULP_RESERVE_MEM);
73 memcpy(base, program_binary, program_size_bytes);
74
75 return ESP_OK;
76 }
77