/**
 * @file binf_util.c
 * @author Shinichiro Nakamura
 * @brief BlueTank ACB-BF592 Application Sample Codes.
 */

/*
 * ===============================================================
 * BlueTank
 * ===============================================================
 * Copyright (c) 2012-2013 Shinichiro Nakamura
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 * ===============================================================
 */

#include <builtins.h>
#include <cdefBF592-A.h>
#include "bfin_util.h"

void bfin_util_usleep(const uint32_t usec)
{
    uint32_t start;
    uint32_t now;
    uint32_t stop = usec * (1000 / 2.5);
    /* 1 cycle = 2.5ns */

    asm("%0 = CYCLES;" : "=d"(start));
    while (1) {
        asm volatile("%0 = CYCLES;" : "=d"(now));
        if ((now - start) >= stop) {
            break;
        }
    }
}

/* Visual DSP++のregister_handler関数実装 */
void bfin_util_register_handler(interrupt_kind kind, ex_handler_fn_gcc fn)
{
    uint32_t l_mask;

    if ((ik_emulation > kind) || (kind > ik_ivg15)) {
      return;
    }

    *((ex_handler_fn_gcc*)&(((uint32_t*)EVT0)[(int32_t)kind])) = fn;
    l_mask  = cli();
    l_mask |= 1u << (int32_t)kind;
    sti(l_mask);
}

