1 /*
2  * Copyright (c) 2016-2019 Espressif Systems (Shanghai) PTE LTD & Cesanta Software Limited
3  * All rights reserved
4  *
5  * This file is part of the esptool.py binary flasher stub.
6  *
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU General Public License as published by the Free Software
9  * Foundation; either version 2 of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
17  * Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 #include "soc_support.h"
20 #include "stub_write_flash.h"
21 #include "stub_flasher.h"
22 #include "rom_functions.h"
23 #include "miniz.h"
24 
25 /* local flashing state
26 
27    This is wrapped in a structure because gcc 4.8
28    generates significantly more code for ESP32
29    if they are static variables (literal pool, I think!)
30 */
31 static struct {
32   /* set by flash_begin, cleared by flash_end */
33   bool in_flash_mode;
34   /* offset of next SPI write */
35   uint32_t next_write;
36   /* sector number for next erase */
37   int next_erase_sector;
38   /* number of output bytes remaining to write */
39   uint32_t remaining;
40   /* number of sectors remaining to erase */
41   int remaining_erase_sector;
42   /* last error generated by a data packet */
43   esp_command_error last_error;
44 
45   /* inflator state for deflate write */
46   tinfl_decompressor inflator;
47   /* number of compressed bytes remaining to read */
48   uint32_t remaining_compressed;
49 } fs;
50 
51 /* SPI status bits */
52 static const uint32_t STATUS_WIP_BIT = (1 << 0);
53 #if ESP32_OR_LATER
54 static const uint32_t STATUS_QIE_BIT = (1 << 9);  /* Quad Enable */
55 #endif
56 
is_in_flash_mode(void)57 bool is_in_flash_mode(void)
58 {
59   return fs.in_flash_mode;
60 }
61 
get_flash_error(void)62 esp_command_error get_flash_error(void)
63 {
64   return fs.last_error;
65 }
66 
67 /* Wait for the SPI state machine to be ready,
68    ie no command in progress in the internal host.
69 */
spi_wait_ready(void)70 inline static void spi_wait_ready(void)
71 {
72   /* Wait for SPI state machine ready */
73   while((READ_REG(SPI_EXT2_REG) & SPI_ST))
74     { }
75 #if ESP32_OR_LATER
76   while(READ_REG(SPI0_EXT2_REG) & SPI_ST)
77   { }
78 #endif
79 }
80 
81 /* Returns true if the spiflash is ready for its next write
82    operation.
83 
84    Doesn't block, except for the SPI state machine to finish
85    any previous SPI host operation.
86 */
spiflash_is_ready(void)87 static bool spiflash_is_ready(void)
88 {
89   spi_wait_ready();
90   WRITE_REG(SPI_RD_STATUS_REG, 0);
91   /* Issue read status command */
92   WRITE_REG(SPI_CMD_REG, SPI_FLASH_RDSR);
93   while(READ_REG(SPI_CMD_REG) != 0)
94     { }
95   uint32_t status_value = READ_REG(SPI_RD_STATUS_REG);
96   return (status_value & STATUS_WIP_BIT) == 0;
97 }
98 
spi_write_enable(void)99 static void spi_write_enable(void)
100 {
101   while(!spiflash_is_ready())
102     { }
103   WRITE_REG(SPI_CMD_REG, SPI_FLASH_WREN);
104   while(READ_REG(SPI_CMD_REG) != 0)
105     { }
106 }
107 
108 #if ESP32_OR_LATER
109 #if ESP32C3 || ESP32C6 ||ESP8684
110 static esp_rom_spiflash_chip_t *flashchip = (esp_rom_spiflash_chip_t *)0x3fcdfff4;
111 #elif ESP32H2
112 static esp_rom_spiflash_chip_t *flashchip = (esp_rom_spiflash_chip_t *)0x3fcdfff0;
113 #else
114 static esp_rom_spiflash_chip_t *flashchip = (esp_rom_spiflash_chip_t *)0x3ffae270;
115 #endif
116 
117 /* Stub version of SPIUnlock() that replaces version in ROM.
118 
119    This works around a bug where SPIUnlock sometimes reads the wrong
120    high status byte (RDSR2 result) and then copies it back to the
121    flash status, causing lock bit CMP or Status Register Protect ` to
122    become set.
123  */
SPIUnlock(void)124 SpiFlashOpResult SPIUnlock(void)
125 {
126   uint32_t status;
127 
128   spi_wait_ready(); /* ROM SPI_read_status_high() doesn't wait for this */
129 #if ESP32S2_OR_LATER
130   if (SPI_read_status_high(flashchip, &status) != SPI_FLASH_RESULT_OK) {
131     return SPI_FLASH_RESULT_ERR;
132   }
133 #else
134   if (SPI_read_status_high(&status) != SPI_FLASH_RESULT_OK) {
135     return SPI_FLASH_RESULT_ERR;
136   }
137 #endif
138 
139   /* Clear all bits except QIE, if it is set.
140      (This is different from ROM SPIUnlock, which keeps all bits as-is.)
141    */
142   status &= STATUS_QIE_BIT;
143 
144   spi_write_enable();
145 
146   REG_SET_MASK(SPI_CTRL_REG, SPI_WRSR_2B);
147   if (SPI_write_status(flashchip, status) != SPI_FLASH_RESULT_OK) {
148     return SPI_FLASH_RESULT_ERR;
149   }
150 
151   return SPI_FLASH_RESULT_OK;
152 }
153 #endif
154 
155 #if defined(ESP32S3)
page_program_internal(int spi_num,SpiFlashRdMode mode,uint32_t spi_addr,uint8_t * addr_source,uint32_t byte_length)156 esp_rom_spiflash_result_t page_program_internal(int spi_num, SpiFlashRdMode mode, uint32_t spi_addr, uint8_t* addr_source, uint32_t byte_length)
157 {
158     uint32_t  temp_addr;
159     int32_t  temp_bl;
160     esp_rom_opiflash_wait_idle(spi_num, SPI_FLASH_FASTRD_MODE);
161     temp_addr = spi_addr;
162     temp_bl = byte_length;
163     uint32_t temp_len = 0;
164 
165     uint16_t cmd = 0;
166     uint8_t cmd_len = 8;
167     int dummy = 0;
168     switch (mode) {
169         case SPI_FLASH_OOUT_MODE:
170             cmd = ROM_FLASH_CMD_PP4B_OOUT_GD;
171             break;
172         case SPI_FLASH_OIO_STR_MODE:
173             cmd = ROM_FLASH_CMD_PP4B_OIOSTR_GD;
174             break;
175         default:
176             mode = SPI_FLASH_FASTRD_MODE;
177         case SPI_FLASH_SLOWRD_MODE:
178         case SPI_FLASH_FASTRD_MODE:
179             cmd = ROM_FLASH_CMD_PP4B_GD;
180             break;
181     }
182 
183     while (temp_bl > 0 ) {
184         opi_flash_wren(spi_num, SPI_FLASH_FASTRD_MODE);
185         temp_len =  (temp_bl >= 32) ? 32 : temp_bl;   //32 = write_sub_len
186         esp_rom_opiflash_exec_cmd(spi_num, mode,
187                             cmd, cmd_len,
188                             temp_addr, 32,
189                             dummy,
190                             addr_source, 8 * temp_len,
191                             NULL, 0,
192                             ESP_ROM_OPIFLASH_SEL_CS0,
193                             true);
194         esp_rom_opiflash_wait_idle(spi_num, SPI_FLASH_FASTRD_MODE);
195         addr_source += temp_len;
196         temp_addr += temp_len;
197         temp_bl -= temp_len;
198     }
199     return ESP_ROM_SPIFLASH_RESULT_OK;
200 }
201 #endif // ESP32S3
202 
203 #if defined(ESP32S3)
SPIWrite4B(int spi_num,SpiFlashRdMode mode,uint32_t target,uint8_t * src_addr,int32_t len)204 esp_rom_spiflash_result_t SPIWrite4B(int spi_num, SpiFlashRdMode mode, uint32_t target, uint8_t *src_addr, int32_t len)
205 {
206     uint32_t  page_size = 256;
207     uint32_t  pgm_len, pgm_num;
208     uint8_t    i;
209 
210     esp_rom_opiflash_wait_idle(spi_num, SPI_FLASH_FASTRD_MODE);
211     pgm_len = page_size - (target % page_size);
212     if (len < pgm_len) {
213         page_program_internal(spi_num, mode, target, src_addr, len);
214     } else {
215         page_program_internal(spi_num, mode, target, src_addr, pgm_len);
216         //whole page program
217         pgm_num = (len - pgm_len) / page_size;
218         for (i = 0; i < pgm_num; i++) {
219             page_program_internal(spi_num, mode, target + pgm_len, (src_addr + pgm_len), page_size);
220             pgm_len += page_size;
221         }
222         //remain parts to program
223         page_program_internal(spi_num, mode, target + pgm_len, (src_addr + pgm_len), len - pgm_len);
224     }
225     esp_rom_opiflash_wait_idle(spi_num, SPI_FLASH_FASTRD_MODE);
226     return  ESP_ROM_SPIFLASH_RESULT_OK;
227 }
228 #endif // ESP32S3
229 
handle_flash_begin(uint32_t total_size,uint32_t offset)230 esp_command_error handle_flash_begin(uint32_t total_size, uint32_t offset) {
231   fs.in_flash_mode = true;
232   fs.next_write = offset;
233   fs.next_erase_sector = offset / FLASH_SECTOR_SIZE;
234   fs.remaining = total_size;
235   fs.remaining_erase_sector = ((offset % FLASH_SECTOR_SIZE) + total_size + FLASH_SECTOR_SIZE - 1) / FLASH_SECTOR_SIZE;
236   fs.last_error = ESP_OK;
237 
238   if (SPIUnlock() != 0) {
239     return ESP_FAILED_SPI_UNLOCK;
240   }
241 
242   return ESP_OK;
243 }
244 
handle_flash_deflated_begin(uint32_t uncompressed_size,uint32_t compressed_size,uint32_t offset)245 esp_command_error handle_flash_deflated_begin(uint32_t uncompressed_size, uint32_t compressed_size, uint32_t offset) {
246   esp_command_error err = handle_flash_begin(uncompressed_size, offset);
247   tinfl_init(&fs.inflator);
248   fs.remaining_compressed = compressed_size;
249   return err;
250 }
251 
252 /* Erase the next sector or block (depending if we're at a block boundary).
253 
254    Updates fs.next_erase_sector & fs.remaining_erase_sector on success.
255 
256    If nothing left to erase, returns immediately.
257 
258    Returns immediately if SPI flash not yet ready for a write operation.
259 
260    Does not wait for the erase to complete - the next SPI operation
261    should check if a write operation is currently in progress.
262  */
start_next_erase(void)263 static void start_next_erase(void)
264 {
265   bool block_erase = false;
266 
267   if(fs.remaining_erase_sector == 0)
268     return; /* nothing left to erase */
269   if(!spiflash_is_ready())
270     return; /* don't wait for flash to be ready, caller will call again if needed */
271 
272   if(fs.remaining_erase_sector >= SECTORS_PER_BLOCK
273      && fs.next_erase_sector % SECTORS_PER_BLOCK == 0) {
274     /* perform a 64KB block erase if we have space for it */
275     block_erase = true;
276   }
277 
278   spi_write_enable();
279   spi_wait_ready();
280   uint32_t addr = fs.next_erase_sector * FLASH_SECTOR_SIZE;
281     if (addr > 0x00ffffff) {
282       #if defined(ESP32S3)
283         if (block_erase)
284           esp_rom_opiflash_erase_block_64k(1, fs.next_erase_sector / SECTORS_PER_BLOCK, SPI_FLASH_FASTRD_MODE);
285         else
286           esp_rom_opiflash_erase_sector(1, fs.next_erase_sector, SPI_FLASH_FASTRD_MODE);
287       #endif // ESP32S3
288     }
289     else {
290       uint32_t command = block_erase ? SPI_FLASH_BE : SPI_FLASH_SE; /* block erase, 64KB : sector erase, 4KB */
291       WRITE_REG(SPI_ADDR_REG, addr & 0xffffff);
292       WRITE_REG(SPI_CMD_REG, command);
293       while(READ_REG(SPI_CMD_REG) != 0) { }
294     }
295   uint32_t sectors_to_erase = block_erase ? SECTORS_PER_BLOCK : 1;
296   fs.remaining_erase_sector -= sectors_to_erase;
297   fs.next_erase_sector += sectors_to_erase;
298 }
299 
300 /* Write data to flash (either direct for non-compressed upload, or
301    freshly decompressed.) Erases as it goes.
302 
303    Updates fs.remaining_erase_sector, fs.next_write, and fs.remaining
304 */
handle_flash_data(void * data_buf,uint32_t length)305 void handle_flash_data(void *data_buf, uint32_t length) {
306   int last_sector;
307   uint8_t res = 0;
308 
309   if (length > fs.remaining) {
310       /* Trim the final block, as it may have padding beyond
311          the length we are writing */
312       length = fs.remaining;
313   }
314 
315   if (length == 0) {
316       return;
317   }
318 
319   /* what sector is this write going to end in?
320      make sure we've erased at least that far.
321   */
322   last_sector = (fs.next_write + length) / FLASH_SECTOR_SIZE;
323   while(fs.remaining_erase_sector > 0 && fs.next_erase_sector <= last_sector) {
324     start_next_erase();
325   }
326   while(!spiflash_is_ready())
327     {}
328 
329   /* do the actual write */
330   #if defined(ESP32S3)
331     if (fs.next_write + length > 0x00ffffff)
332       res = SPIWrite4B(1, SPI_FLASH_FASTRD_MODE, fs.next_write, data_buf, length);
333     else
334       res = SPIWrite(fs.next_write, data_buf, length);
335   #else
336     res = SPIWrite(fs.next_write, data_buf, length);
337   #endif // ESP32S3
338   if (res != 0)
339     fs.last_error = ESP_FAILED_SPI_OP;
340   fs.next_write += length;
341   fs.remaining -= length;
342 }
343 
344 #if !ESP8266
345 /* Write encrypted data to flash (either direct for non-compressed upload, or
346    freshly decompressed.) Erases as it goes.
347 
348    Updates fs.remaining_erase_sector, fs.next_write, and fs.remaining
349 */
handle_flash_encrypt_data(void * data_buf,uint32_t length)350 void handle_flash_encrypt_data(void *data_buf, uint32_t length) {
351   int last_sector;
352   int res;
353 
354 #if ESP32S2_OR_LATER
355   SPI_Write_Encrypt_Enable();
356 #endif
357 
358   if (length > fs.remaining) {
359       /* Trim the final block, as it may have padding beyond
360          the length we are writing */
361       length = fs.remaining;
362   }
363 
364   if (length == 0) {
365       return;
366   }
367 
368   /* what sector is this write going to end in?
369      make sure we've erased at least that far.
370   */
371   last_sector = (fs.next_write + length) / FLASH_SECTOR_SIZE;
372   while(fs.remaining_erase_sector > 0 && fs.next_erase_sector <= last_sector) {
373     start_next_erase();
374   }
375   while(!spiflash_is_ready())
376     {}
377 
378   /* do the actual write */
379 #if ESP32
380   res = esp_rom_spiflash_write_encrypted(fs.next_write, data_buf, length);
381 #else
382   res = SPI_Encrypt_Write(fs.next_write, data_buf, length);
383 #endif
384 
385   if (res) {
386     fs.last_error = ESP_FAILED_SPI_OP;
387   }
388   fs.next_write += length;
389   fs.remaining -= length;
390 
391 #if ESP32S2_OR_LATER
392   SPI_Write_Encrypt_Disable();
393 #endif
394 }
395 
396 #endif // !ESP8266
397 
handle_flash_deflated_data(void * data_buf,uint32_t length)398 void handle_flash_deflated_data(void *data_buf, uint32_t length) {
399   static uint8_t out_buf[32768];
400   static uint8_t *next_out = out_buf;
401   int status = TINFL_STATUS_NEEDS_MORE_INPUT;
402 
403   while(length > 0 && fs.remaining > 0 && status > TINFL_STATUS_DONE) {
404     size_t in_bytes = length; /* input remaining */
405     size_t out_bytes = out_buf + sizeof(out_buf) - next_out; /* output space remaining */
406     int flags = TINFL_FLAG_PARSE_ZLIB_HEADER;
407     if(fs.remaining_compressed > length) {
408       flags |= TINFL_FLAG_HAS_MORE_INPUT;
409     }
410 
411     /* start an opportunistic erase: decompressing takes time, so might as
412        well be running a SPI erase in the background. */
413     start_next_erase();
414 
415     status = tinfl_decompress(&fs.inflator, data_buf, &in_bytes,
416                      out_buf, next_out, &out_bytes,
417                      flags);
418 
419     fs.remaining_compressed -= in_bytes;
420     length -= in_bytes;
421     data_buf += in_bytes;
422 
423     next_out += out_bytes;
424     size_t bytes_in_out_buf = next_out - out_buf;
425     if (status == TINFL_STATUS_DONE || bytes_in_out_buf == sizeof(out_buf)) {
426       // Output buffer full, or done
427       handle_flash_data(out_buf, bytes_in_out_buf);
428       next_out = out_buf;
429     }
430   } // while
431 
432   if (status < TINFL_STATUS_DONE) {
433     /* error won't get sent back to esptool.py until next block is sent */
434     fs.last_error = ESP_INFLATE_ERROR;
435   }
436 
437   if (status == TINFL_STATUS_DONE && fs.remaining > 0) {
438     fs.last_error = ESP_NOT_ENOUGH_DATA;
439   }
440   if (status != TINFL_STATUS_DONE && fs.remaining == 0) {
441     fs.last_error = ESP_TOO_MUCH_DATA;
442   }
443 }
444 
handle_flash_end(void)445 esp_command_error handle_flash_end(void)
446 {
447   if (!fs.in_flash_mode) {
448     return ESP_NOT_IN_FLASH_MODE;
449   }
450 
451   if (fs.remaining > 0) {
452     return ESP_NOT_ENOUGH_DATA;
453   }
454 
455   fs.in_flash_mode = false;
456   return fs.last_error;
457 }
458