O real significado (ou a real intenção) do define ICACHE_FLASH_ATTR no SDK da Espressif

Boa noite pessoal!

Nesse pequeno projeto que estou desenvolvendo, como já disse no post anterior, estou utilizando o SDK nativo da Espressif para C/C++. Analisando algumas partes do SDK, vira e mexe me deparo com o define ICACHE_FLASH_ATTR e sempre me pergunto "o que é isso?".

Pesquisando sobre o assunto, encontrei um post no fórum da Espressif onde o usuário @eriksl explicou bem o funcionamento e o porquê de se usar esse define.




Vou colocar abaixo o texto dele na íntegra para aqueles que também estiverem com dúvidas quanto à isso (e para termos essa informação pulverizada pela web, já que a própria Espressif não inclui nada disso em sua documentação oficial).

It has been explained here and there, but never explicitly, so I'll take the shot on doing it simple & good (one time).

The esp8266 has 32k (maybe 64k, that's not completely clear) of IRAM. That means RAM for instructions, code. This is different from the ~80k of DRAM (which means data ram, not dynamic ram, it's all dynamic ram, the iram too). One cannot be use for the other and v.v.

Programs are stored in the flash memory and due to the fast interface (SPI-quad) instructions can be fetched and executed "in place", in other words, without copying them to ram first. In some occasions you cannot execute your code from SPI flash memory directly, mostly because it needs to be maximum fast or because it handles the flash memory itself (e.g. writing to it). In that case, you can have some code, 32k in total, have copied from the flash at startup, to the IRAM. This code will run from IRAM, not from FLASH.

The forementioned #define, which has an ugly, completely wrong name, if applied to a function, takes care that the function is output to the .irom0_text section, which tells the linker to put the function in FLASH memory segment. The default is to output to .text segment which will put the function into the IRAM segment.

A lot of the SDK-code, which you must link to your firmware to have it working, also output their code to the IRAM segment. So there is actually not a lot left, from the 32k for your own application, about 2k, maybe 3k. So use it very sparingly. Also many functions if not all, from libc, are placed into the IRAM segment. So it is very easy to run out of IRAM space. Even though you may have 512k or even 4m of FLASH memory (depening on the chip used). I had to reimplement some functions from libc in my own code, simply because they take up too much space in IRAM.

So always, unless impossible, add this #define to all of your functions.

I think that should cover most of it.
A thread que originou o post do @eriksl pode ser encontrada aqui.

É isso! Espero que ajude.

Até a próxima!

Comentários

Postagens mais visitadas