/**
 * \file
 *
 * \brief Flash Controller Driver
 *
 * - Compiler:           IAR EWAVR32 and GNU GCC for AVR32
 * - Supported devices:  All devices with a FLASHC module
 * - AppNote:
 *
 * \author               Atmel Corporation: http://www.atmel.com \n
 *                       Support and FAQ: http://support.atmel.no/
 *
 * \todo This driver currently only supports changing the number of wait
 * states. We should add support for flash programming at some point.
 *
 * \page License
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. The name of Atmel may not be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
 * 4. This software may only be redistributed and used in connection with an
 * Atmel AVR product.
 *
 * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */
#include <bitops.h>
#include <interrupt.h>
#include <io.h>
#include <chip/memory-map.h>
#include <flash/flashc.h>

void flashc_adjust_wait_state(unsigned long new_hclk_rate)
{
	unsigned long	iflags;
	uint32_t	fcr;

	iflags = cpu_irq_save();

	fcr = mmio_read32((void *)FLASHC_BASE);

	/* FIXME: Max rate taken from UC3A0 data sheet */
	if (new_hclk_rate > 33000000) {
		/* Set one wait state for flash access */
		fcr |= 1 << 6;
	} else {
		/* No wait state necessary */
		fcr &= ~(1 << 6);
	}

	mmio_write32((void *)FLASHC_BASE, fcr);
	mmio_read32((void *)FLASHC_BASE);

	cpu_irq_restore(iflags);
}

void flashc_write_gp_fuse(unsigned int bit_nr)
{
	uint32_t	fcmd;

	assert(bit_nr < 64);

	fcmd = 0xa5 << 24 | bit_nr << 8 | 7;
	mmio_write32((void *)(FLASHC_BASE + 4), fcmd);
}

void flashc_erase_gp_fuse(unsigned int bit_nr)
{
	uint32_t	fcmd;

	assert(bit_nr < 64);

	fcmd = 0xa5 << 24 | bit_nr << 8 | 8;
	mmio_write32((void *)(FLASHC_BASE + 4), fcmd);
}
