/*
 * Copyright (C) 2020-2021 Aloysius Indrayanto
 *
 * This file is part of the eCxx library, see LICENSE file for the license details.
 */

/*
 * ----------------------------------------------------------------------------------
 * The code in this file is copied (with a slight modifications) from:
 *     core_esp8266_features.cpp
 * ----------------------------------------------------------------------------------
 * Copyright (C) 2019 Mike Nix. All rights reserved.
 *
 * This file is part of the esp8266 core for Arduino environment.
 *
 * This library is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation; either version 2.1 of the License, or (at your option) any later
 * version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with this library; if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 * ----------------------------------------------------------------------------------
 */


#include "CoreSys.h"


namespace eCxx {

namespace NodeMCU {


// Preloads flash data into the flash cache
//
// # If f is nullptr, preloads instructions starting at the address it was called from;
//   otherwise preloads flash at the given address.
// # All preloads are word aligned.
//
extern void precache(void* f, eCxx::uint32_t bytes)
{
    // Size of a cache page in bytes; only needs to read one word per page (i.e. 1 word in 8) for this to work
    #define CACHE_PAGE_SIZE 32

    const eCxx::uint32_t lines = (bytes / CACHE_PAGE_SIZE) + 2;

    eCxx::uint32_t a0;
    __asm__ __volatile__ (
        "mov.n %0, a0 \n\t"
        : "=r"(a0)
    );

    volatile eCxx::uint32_t* p = reinterpret_cast<eCxx::uint32_t*>(
                                     ( f ? reinterpret_cast<eCxx::uint32_t>(f) : a0 ) & ~0x03
                                 );

    eCxx::uint32_t x;
    for( eCxx::uint32_t i = 0; i < lines; ++i, p += CACHE_PAGE_SIZE / sizeof(eCxx::uint32_t) ) x = *p;
    eCxx::ignoreUnused(x);
}


} // namespace NodeMCU

} // namespace eCxx
