1 /*
2 * SPDX-FileCopyrightText: 2016 Cesanta Software Limited
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 *
6 * SPDX-FileContributor: 2016-2022 Espressif Systems (Shanghai) CO LTD
7 */
8
9 /*
10 * Main flasher stub logic
11 *
12 * This stub uses the same SLIP framing and basic command/response structure
13 * as the in-ROM flasher program, but with some enhanced
14 * functions and also standardizes the flasher features between different chips.
15 *
16 * Actual command handlers are implemented in stub_commands.c
17 */
18 #include <stdlib.h>
19 #include "stub_flasher.h"
20 #include "rom_functions.h"
21 #include "slip.h"
22 #include "stub_commands.h"
23 #include "stub_write_flash.h"
24 #include "stub_io.h"
25 #include "soc_support.h"
26
27 /* Buffers for reading from UART. Data is read double-buffered, so
28 we can read into one buffer while handling data from the other one
29 (used for flashing throughput.) */
30 typedef struct {
31 uint8_t buf_a[MAX_WRITE_BLOCK+64];
32 uint8_t buf_b[MAX_WRITE_BLOCK+64];
33 volatile uint8_t *reading_buf; /* Pointer to buf_a, or buf_b - which are we reading_buf? */
34 uint16_t read; /* how many bytes have we read in the frame */
35 slip_state_t state;
36 esp_command_req_t *command; /* Pointer to buf_a or buf_b as latest command received */
37 } uart_buf_t;
38 static volatile uart_buf_t ub;
39
40 /* esptool protocol "checksum" is XOR of 0xef and each byte of
41 data payload. */
calculate_checksum(uint8_t * buf,int length)42 static uint8_t calculate_checksum(uint8_t *buf, int length)
43 {
44 uint8_t res = 0xef;
45 for(int i = 0; i < length; i++) {
46 res ^= buf[i];
47 }
48 return res;
49 }
50
51 #if USE_MAX_CPU_FREQ
can_use_max_cpu_freq()52 static bool can_use_max_cpu_freq()
53 {
54 /* Check if any of available USB modes are being used. */
55 #if WITH_USB_OTG && !WITH_USB_JTAG_SERIAL
56 return stub_uses_usb_otg();
57 #elif !WITH_USB_OTG && WITH_USB_JTAG_SERIAL
58 return stub_uses_usb_jtag_serial();
59 #elif WITH_USB_OTG && WITH_USB_JTAG_SERIAL
60 return stub_uses_usb_otg() || stub_uses_usb_jtag_serial();
61 #else
62 return false;
63 #endif
64 }
65
66 #if ESP32C6 || ESP32H2 || ESP32C5BETA3
67 static uint32_t pcr_sysclk_conf_reg = 0;
68 #else
69 static uint32_t cpu_per_conf_reg = 0;
70 static uint32_t sysclk_conf_reg = 0;
71 #endif
72
set_max_cpu_freq()73 static void set_max_cpu_freq()
74 {
75 if (can_use_max_cpu_freq())
76 {
77 /* Set CPU frequency to max. This also increases SPI speed. */
78 #if ESP32C6 || ESP32H2 || ESP32C5BETA3
79 pcr_sysclk_conf_reg = READ_REG(PCR_SYSCLK_CONF_REG);
80 WRITE_REG(PCR_SYSCLK_CONF_REG, (pcr_sysclk_conf_reg & ~PCR_SOC_CLK_SEL_M) | (PCR_SOC_CLK_MAX << PCR_SOC_CLK_SEL_S));
81 #else
82 cpu_per_conf_reg = READ_REG(SYSTEM_CPU_PER_CONF_REG);
83 sysclk_conf_reg = READ_REG(SYSTEM_SYSCLK_CONF_REG);
84 WRITE_REG(SYSTEM_SYSCLK_CONF_REG, (sysclk_conf_reg & ~SYSTEM_SOC_CLK_SEL_M) | (SYSTEM_SOC_CLK_MAX << SYSTEM_SOC_CLK_SEL_S));
85 ets_delay_us(100); /* Leave some time for the change to settle, needed for ESP32-S3 */
86 WRITE_REG(SYSTEM_CPU_PER_CONF_REG, (cpu_per_conf_reg & ~SYSTEM_CPUPERIOD_SEL_M) | (SYSTEM_CPUPERIOD_MAX << SYSTEM_CPUPERIOD_SEL_S));
87 #endif
88 }
89 }
90
reset_cpu_freq()91 static void reset_cpu_freq()
92 {
93 /* Restore saved sysclk_conf and cpu_per_conf registers.
94 Use only if set_max_cpu_freq() has been called. */
95 #if ESP32C6 || ESP32H2 || ESP32C5BETA3
96 if (can_use_max_cpu_freq() && pcr_sysclk_conf_reg != 0)
97 {
98 WRITE_REG(PCR_SYSCLK_CONF_REG, (READ_REG(PCR_SYSCLK_CONF_REG) & ~PCR_SOC_CLK_SEL_M) | (pcr_sysclk_conf_reg & PCR_SOC_CLK_SEL_M));
99 }
100 #else
101 if (can_use_max_cpu_freq() && sysclk_conf_reg != 0 && cpu_per_conf_reg != 0)
102 {
103 WRITE_REG(SYSTEM_CPU_PER_CONF_REG, (READ_REG(SYSTEM_CPU_PER_CONF_REG) & ~SYSTEM_CPUPERIOD_SEL_M) | (cpu_per_conf_reg & SYSTEM_CPUPERIOD_SEL_M));
104 WRITE_REG(SYSTEM_SYSCLK_CONF_REG, (READ_REG(SYSTEM_SYSCLK_CONF_REG) & ~SYSTEM_SOC_CLK_SEL_M) | (sysclk_conf_reg & SYSTEM_SOC_CLK_SEL_M));
105 }
106 #endif
107 }
108 #endif // USE_MAX_CPU_FREQ
109
110 #if WITH_USB_JTAG_SERIAL
disable_watchdogs()111 static void disable_watchdogs()
112 {
113 if (stub_uses_usb_jtag_serial())
114 {
115 WRITE_REG(RTC_CNTL_WDTWPROTECT_REG, RTC_CNTL_WDT_WKEY); // Disable write protection
116 WRITE_REG(RTC_CNTL_WDTCONFIG0_REG, 0x0); // Disable RTC watchdog
117 WRITE_REG(RTC_CNTL_WDTWPROTECT_REG, 0x0); // Re-enable write protection
118
119 WRITE_REG(RTC_CNTL_SWD_WPROTECT_REG, RTC_CNTL_SWD_WKEY); // Disable write protection
120 REG_SET_MASK(RTC_CNTL_SWD_CONF_REG, RTC_CNTL_SWD_AUTO_FEED_EN); // Autofeed super watchdog
121 WRITE_REG(RTC_CNTL_SWD_WPROTECT_REG, 0x0); // Re-enable write protection
122 }
123 }
124 #endif // WITH_USB_JTAG_SERIAL
125
126 #if ESP32S3 && !ESP32S3BETA2
127 bool large_flash_mode = false;
128
flash_larger_than_16mb()129 bool flash_larger_than_16mb()
130 {
131 uint32_t flash_id;
132 esp_rom_opiflash_exec_cmd(1, SPI_FLASH_FASTRD_MODE,
133 CMD_RDID, 8,
134 0, 0,
135 0,
136 NULL, 0,
137 (uint8_t *)&flash_id, 24,
138 ESP_ROM_OPIFLASH_SEL_CS0,
139 false);
140
141 uint8_t flid_lowbyte = (flash_id >> 16) & 0xFF;
142 return ((flid_lowbyte >= 0x19 && flid_lowbyte < 0x30) || (flid_lowbyte >= 0x39)); // See DETECTED_FLASH_SIZES in esptool
143 }
144 #endif // ESP32S3
145
stub_handle_rx_byte(char byte)146 static void stub_handle_rx_byte(char byte)
147 {
148 int16_t r = SLIP_recv_byte(byte, (slip_state_t *)&ub.state);
149 if (r >= 0) {
150 ub.reading_buf[ub.read++] = (uint8_t) r;
151 if (ub.read == MAX_WRITE_BLOCK+64) {
152 /* shouldn't happen unless there are data errors */
153 r = SLIP_FINISHED_FRAME;
154 }
155 }
156 if (r == SLIP_FINISHED_FRAME) {
157 /* end of frame, set 'command'
158 to be processed by main thread */
159 if(ub.reading_buf == ub.buf_a) {
160 ub.command = (esp_command_req_t *)ub.buf_a;
161 ub.reading_buf = ub.buf_b;
162 } else {
163 ub.command = (esp_command_req_t *)ub.buf_b;
164 ub.reading_buf = ub.buf_a;
165 }
166 ub.read = 0;
167 }
168 }
169
verify_data_len(esp_command_req_t * command,uint8_t len)170 static esp_command_error verify_data_len(esp_command_req_t *command, uint8_t len)
171 {
172 return (command->data_len == len) ? ESP_OK : ESP_BAD_DATA_LEN;
173 }
174
cmd_loop()175 void cmd_loop() {
176 while(1) {
177 /* Wait for a command */
178 while(ub.command == NULL) {
179 stub_io_idle_hook();
180 }
181 esp_command_req_t *command = ub.command;
182 ub.command = NULL;
183 /* provide easy access for 32-bit data words */
184 uint32_t *data_words = (uint32_t *)command->data_buf;
185
186 /* Send command response header */
187 esp_command_response_t resp = {
188 .resp = 1,
189 .op_ret = command->op,
190 .len_ret = 2, /* esptool.py checks this length */
191 .value = 0,
192 };
193
194 /* Some commands need to set resp.len_ret or resp.value before it is sent back */
195 switch(command->op) {
196 case ESP_READ_REG:
197 if (command->data_len == 4) {
198 resp.value = READ_REG(data_words[0]);
199 }
200 break;
201 case ESP_FLASH_VERIFY_MD5:
202 resp.len_ret = 16 + 2; /* Will sent 16 bytes of data with MD5 value */
203 break;
204 #if ESP32S2_OR_LATER
205 case ESP_GET_SECURITY_INFO:
206 resp.len_ret = SECURITY_INFO_BYTES; /* Buffer size varies */
207 break;
208 #endif // ESP32S2_OR_LATER
209 default:
210 break;
211 }
212
213 /* Send the command response */
214 SLIP_send_frame_delimiter();
215 SLIP_send_frame_data_buf(&resp, sizeof(esp_command_response_t));
216
217 if(command->data_len > MAX_WRITE_BLOCK+16) {
218 SLIP_send_frame_data(ESP_BAD_DATA_LEN);
219 SLIP_send_frame_data(0xEE);
220 SLIP_send_frame_delimiter();
221 continue;
222 }
223
224 /* ... ESP_FLASH_VERIFY_MD5 and ESP_GET_SECURITY_INFO will insert
225 * in-frame response data between here and when we send the
226 * status bytes at the end of the frame */
227
228 esp_command_error error = ESP_CMD_NOT_IMPLEMENTED;
229 int status = 0;
230
231 /* First stage of command processing - before sending error/status */
232 switch (command->op) {
233 case ESP_SYNC:
234 /* Bootloader responds to the SYNC request with eight identical SYNC responses. Stub flasher should react
235 * the same way so SYNC could be possible with the flasher stub as well. This helps in cases when the chip
236 * cannot be reset and the flasher stub keeps running. */
237 error = verify_data_len(command, 36);
238
239 if (error == ESP_OK) {
240 /* resp.value remains 0 which esptool.py can use to detect the flasher stub */
241 resp.value = 0;
242 for (int i = 0; i < 7; ++i) {
243 SLIP_send_frame_data(error);
244 SLIP_send_frame_data(status);
245 SLIP_send_frame_delimiter(); /* end the previous frame */
246
247 SLIP_send_frame_delimiter(); /* start new frame */
248 SLIP_send_frame_data_buf(&resp, sizeof(esp_command_response_t));
249 }
250 /* The last frame is ended outside of the "switch case" at the same place regular one-response frames are
251 * ended. */
252 }
253 break;
254 #if ESP32S2_OR_LATER
255 case ESP_GET_SECURITY_INFO:
256 error = verify_data_len(command, 0) || handle_get_security_info();
257 break;
258 #endif // ESP32S2_OR_LATER
259 case ESP_ERASE_FLASH:
260 error = verify_data_len(command, 0) || SPIEraseChip();
261 break;
262 case ESP_ERASE_REGION:
263 /* Params for ERASE_REGION are addr, len */
264 error = verify_data_len(command, 8) || handle_flash_erase(data_words[0], data_words[1]);
265 break;
266 case ESP_SET_BAUD:
267 /* ESP_SET_BAUD sends two args, new and old baud rates */
268 error = verify_data_len(command, 8);
269 /* actual baud setting happens after we send the reply */
270 break;
271 case ESP_READ_FLASH:
272 error = verify_data_len(command, 16);
273 /* actual data is sent after we send the reply */
274 break;
275 case ESP_FLASH_VERIFY_MD5:
276 /* unsure why the MD5 command has 4 params but we only pass 2 of them,
277 but this is in ESP32 ROM so we can't mess with it.
278 */
279 error = verify_data_len(command, 16) || handle_flash_get_md5sum(data_words[0], data_words[1]);
280 break;
281 case ESP_FLASH_BEGIN:
282 /* parameters (interpreted differently to ROM flasher):
283 0 - erase_size (used as total size to write)
284 1 - num_blocks (ignored)
285 2 - block_size (should be MAX_WRITE_BLOCK, relies on num_blocks * block_size >= erase_size)
286 3 - offset (used as-is)
287 */
288 if (command->data_len == 16 && data_words[2] > MAX_WRITE_BLOCK) {
289 error = ESP_BAD_BLOCKSIZE;
290 } else {
291 error = verify_data_len(command, 16) || handle_flash_begin(data_words[0], data_words[3]);
292 }
293 break;
294 case ESP_FLASH_DEFLATED_BEGIN:
295 /* parameters:
296 0 - uncompressed size
297 1 - num_blocks (based on compressed size)
298 2 - block_size (should be MAX_WRITE_BLOCK, total bytes over serial = num_blocks * block_size)
299 3 - offset (used as-is)
300 */
301 if (command->data_len == 16 && data_words[2] > MAX_WRITE_BLOCK) {
302 error = ESP_BAD_BLOCKSIZE;
303 } else {
304 error = verify_data_len(command, 16) || handle_flash_deflated_begin(data_words[0], data_words[1] * data_words[2], data_words[3]);
305 }
306 break;
307 case ESP_FLASH_DATA:
308 case ESP_FLASH_DEFLATED_DATA:
309 #if !ESP8266
310 case ESP_FLASH_ENCRYPT_DATA:
311 #endif
312
313 /* ACK DATA commands immediately, then process them a few lines down,
314 allowing next command to buffer */
315 if(is_in_flash_mode()) {
316 error = get_flash_error();
317 int payload_len = command->data_len - 16;
318 if (data_words[0] != payload_len) {
319 /* First byte of data payload header is length (repeated) as a word */
320 error = ESP_BAD_DATA_LEN;
321 }
322 uint8_t data_checksum = calculate_checksum(command->data_buf + 16, payload_len);
323 if (data_checksum != command->checksum) {
324 error = ESP_BAD_DATA_CHECKSUM;
325 }
326 }
327 else {
328 error = ESP_NOT_IN_FLASH_MODE;
329 }
330 break;
331 case ESP_FLASH_END:
332 case ESP_FLASH_DEFLATED_END:
333 error = handle_flash_end();
334 break;
335 case ESP_SPI_SET_PARAMS:
336 /* data params: fl_id, total_size, block_size, sector_Size, page_size, status_mask */
337 error = verify_data_len(command, 24) || handle_spi_set_params(data_words, &status);
338 break;
339 case ESP_SPI_ATTACH:
340 /* parameter is 'hspi mode' (0, 1 or a pin mask for ESP32. Ignored on ESP8266.) */
341 error = verify_data_len(command, 4) || handle_spi_attach(data_words[0]);
342 break;
343 case ESP_WRITE_REG:
344 /* The write_reg command can pass multiple write operations in a sequence */
345 if (command->data_len % sizeof(write_reg_args_t) != 0) {
346 error = ESP_BAD_DATA_LEN;
347 } else {
348 error = handle_write_reg((const write_reg_args_t *)data_words, command->data_len/sizeof(write_reg_args_t));
349 }
350 break;
351 case ESP_READ_REG:
352 /* actual READ_REG operation happens higher up */
353 error = verify_data_len(command, 4);
354 break;
355 case ESP_MEM_BEGIN:
356 error = verify_data_len(command, 16) || handle_mem_begin(data_words[0], data_words[3]);
357 break;
358 case ESP_MEM_DATA:
359 error = handle_mem_data(command->data_buf + 16, command->data_len - 16);
360 break;
361 case ESP_MEM_END:
362 error = verify_data_len(command, 8) || handle_mem_finish();
363 break;
364 case ESP_RUN_USER_CODE:
365 /* Returning from here will run user code, ie standard boot process
366
367 This command does not send a response.
368 */
369 return;
370 }
371
372 SLIP_send_frame_data(error);
373 SLIP_send_frame_data(status);
374 SLIP_send_frame_delimiter();
375
376 /* Some commands need to do things after after sending this response */
377 if (error == ESP_OK) {
378 switch(command->op) {
379 case ESP_SET_BAUD:
380 stub_io_set_baudrate(data_words[1], data_words[0]);
381 break;
382 case ESP_READ_FLASH:
383 /* args are: offset, length, block_size, max_in_flight */
384 handle_flash_read(data_words[0], data_words[1], data_words[2],
385 data_words[3]);
386 break;
387 case ESP_FLASH_DATA:
388 /* drop into flashing mode, discard 16 byte payload header */
389 handle_flash_data(command->data_buf + 16, command->data_len - 16);
390 break;
391 #if !ESP8266
392 case ESP_FLASH_ENCRYPT_DATA:
393 /* write encrypted data */
394 handle_flash_encrypt_data(command->data_buf + 16, command->data_len -16);
395 break;
396 #endif
397 case ESP_FLASH_DEFLATED_DATA:
398 handle_flash_deflated_data(command->data_buf + 16, command->data_len - 16);
399 break;
400 case ESP_FLASH_DEFLATED_END:
401 case ESP_FLASH_END:
402 /* passing 0 as parameter for ESP_FLASH_END means reboot now */
403 if (data_words[0] == 0) {
404 /* Flush the FLASH_END response before rebooting */
405 stub_tx_flush();
406 ets_delay_us(10000);
407 #if USE_MAX_CPU_FREQ
408 reset_cpu_freq();
409 #endif // USE_MAX_CPU_FREQ
410 software_reset();
411 }
412 break;
413 case ESP_MEM_END:
414 if (data_words[1] != 0) {
415 void (*entrypoint_fn)(void) = (void (*))data_words[1];
416 /* Make sure the command response has been flushed out
417 of the UART before we run the new code */
418 stub_tx_flush();
419 ets_delay_us(1000);
420 /* this is a little different from the ROM loader,
421 which exits the loader routine and _then_ calls this
422 function. But for our purposes so far, having a bit of
423 extra stuff on the stack doesn't really matter.
424 */
425 #if USE_MAX_CPU_FREQ
426 reset_cpu_freq();
427 #endif // USE_MAX_CPU_FREQ
428 entrypoint_fn();
429 }
430 break;
431 }
432 }
433 }
434 }
435
436
437 extern uint32_t _bss_start;
438 extern uint32_t _bss_end;
439
440 void __attribute__((used)) stub_main();
441
442
443 #ifdef ESP8266
444 __asm__ (
445 ".global stub_main_8266\n"
446 ".literal_position\n"
447 ".align 4\n"
448 "stub_main_8266:\n"
449 /* ESP8266 wrapper for "stub_main()" manipulates the return address in
450 * a0, so 'return' from here runs user code.
451 *
452 * After setting a0, we jump directly to stub_main_inner() which is a
453 * normal C function
454 *
455 * Adapted from similar approach used by Cesanta Software for ESP8266
456 * flasher stub.
457 *
458 */
459 "movi a0, 0x400010a8;"
460 "j stub_main;");
461 #endif
462
463 /* This function is called from stub_main, with return address
464 reset to point to user code. */
stub_main()465 void stub_main()
466 {
467 const uint32_t greeting = 0x4941484f; /* OHAI */
468
469 /* This points to stub_main now, clear for next boot. */
470 ets_set_user_start(0);
471
472 /* Increase CPU frequency and flashing speed if supported. */
473 #if USE_MAX_CPU_FREQ
474 set_max_cpu_freq();
475 #endif // USE_MAX_CPU_FREQ
476
477 /* Disable all watchdogs to prevent the chip from resetting during longer operations. */
478 #if WITH_USB_JTAG_SERIAL
479 disable_watchdogs();
480 #endif // WITH_USB_JTAG_SERIAL
481
482 /* Zero the bss region. */
483 for(uint32_t *p = &_bss_start; p < &_bss_end; p++) {
484 *p = 0;
485 }
486
487 /* Send the OHAI greeting, stub will be reported as running. */
488 SLIP_send(&greeting, 4);
489
490 /* Configure the interrupts for receiving data from esptool on the host. */
491 ub.reading_buf = ub.buf_a;
492 stub_io_init(&stub_handle_rx_byte);
493
494 /* Configure default SPI flash functionality.
495 Can be overridden later by esptool.py. */
496 #ifdef ESP8266
497 SelectSpiFunction();
498 spi_flash_attach();
499 #else
500 #if SUPPORT_CONFIG_SPI
501 uint32_t spiconfig = ets_efuse_get_spiconfig();
502 #else
503 uint32_t spiconfig = 0;
504 #endif // SUPPORT_CONFIG_SPI
505 uint32_t strapping = READ_REG(GPIO_STRAP_REG);
506 /* If GPIO1 (U0TXD) is pulled low and no other boot mode is
507 set in efuse, assume HSPI flash mode (same as normal boot)
508 */
509 if (spiconfig == 0 && (strapping & 0x1c) == 0x08) {
510 spiconfig = 1; /* HSPI flash mode */
511 }
512 spi_flash_attach(spiconfig, 0);
513 #endif // ESP8266
514
515 /* Initialize the OPI flash driver if supported. */
516 #if ESP32S3 && !ESP32S3BETA2
517 large_flash_mode = ets_efuse_flash_octal_mode() || flash_larger_than_16mb();
518
519 // Initialize OPI flash driver only when flash is detected octal or quad larger than 16MB.
520 // Otherwise, we don't need to initialize such a driver
521 if (large_flash_mode) {
522 static const esp_rom_opiflash_def_t flash_driver = OPIFLASH_DRIVER();
523 esp_rom_opiflash_legacy_driver_init(&flash_driver);
524 esp_rom_opiflash_wait_idle();
525 }
526 #endif //ESP32S3 && !ESP32S3BETA2
527 SPIParamCfg(0, FLASH_MAX_SIZE, FLASH_BLOCK_SIZE, FLASH_SECTOR_SIZE,
528 FLASH_PAGE_SIZE, FLASH_STATUS_MASK);
529
530 /* Configurations are done, now run the loop to receive and handle commands. */
531 cmd_loop();
532
533 /* If cmd_loop returns, it's due to ESP_RUN_USER_CODE command. */
534 /* Decrease CPU frequency back to the saved value before the stub flasher returns. */
535 #if USE_MAX_CPU_FREQ
536 reset_cpu_freq();
537 #endif // USE_MAX_CPU_FREQ
538
539 return;
540 }
541