/* SPDX-License-Identifier: LGPL-2.1-only OR BSD-3-Clause */
/******************************************************************************
 *
 * This file is provided under a dual license.  When you use or
 * distribute this software, you may choose to be licensed under
 * version 2.1 of the GNU Lesser General Public License
 * ("LGPLv2.1 License") or BSD License.
 *
 * LGPLv2.1 License
 *
 * Copyright(C) 2019 MediaTek Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2.1 of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This program 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 https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html for more
 * details.
 *
 * BSD LICENSE
 *
 * Copyright(C) 2019 MediaTek Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * 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.
 *  * Neither the name of the copyright holder nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS 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.
 *
 *****************************************************************************/

/*-----------------------------------------------------------------------------
 *
 * $Author: dtvbm11 $
 * $Date: 2015/11/10 $
 * $RCSfile: dmx_if.c,v $
 * $Revision: #1 $
 *
 *---------------------------------------------------------------------------*/

/** @file dmx_if.c
 *  Demux driver - public interface
 */

//-----------------------------------------------------------------------------
// Include files
//-----------------------------------------------------------------------------
#include "dmx.h"
#include "dmx_drm_drvif.h"
#include "dmx_drm_if.h"
#include "x_assert.h"
#include "dmx_debug.h"

//-----------------------------------------------------------------------------
// Configurations
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
// Constant definitions
//-----------------------------------------------------------------------------
// Uboot use this file, define below to avoid compilation error
#ifdef FUNC_ENTRY
#undef FUNC_ENTRY
#define FUNC_ENTRY
#endif
#ifdef FUNC_EXIT
#undef FUNC_EXIT
#define FUNC_EXIT
#endif

//-----------------------------------------------------------------------------
// Type definitions
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
// Macro definitions
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
// Static variables
//-----------------------------------------------------------------------------
/// API semaphore
#ifndef CC_MTK_LOADER
static HANDLE_T _hApiSem = NULL_HANDLE;
#endif

//-----------------------------------------------------------------------------
// Static functions
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
/** Enter demux API critical section
 *
 *  @retval void
 */
//-----------------------------------------------------------------------------
static void _ApiLock(void)
{
#ifndef CC_MTK_LOADER
    static BOOL _fgInit = FALSE;

    if (!_fgInit)
    {
        VERIFY(x_sema_create(&_hApiSem, X_SEMA_TYPE_MUTEX, X_SEMA_STATE_UNLOCK) == OSR_OK);
        _fgInit = TRUE;
    }

    VERIFY(x_sema_lock(_hApiSem, X_SEMA_OPTION_WAIT) == OSR_OK);
#endif
}


//-----------------------------------------------------------------------------
/** Leave demux API critical section
 *
 *  @retval void
 */
//-----------------------------------------------------------------------------
static void _ApiUnlock(void)
{
#ifndef CC_MTK_LOADER
    VERIFY(x_sema_unlock(_hApiSem) == OSR_OK);
#endif
}

//-----------------------------------------------------------------------------
// Inter-file functions
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
// Public functions
//-----------------------------------------------------------------------------

BOOL DMX_NAND_AES_INIT(UINT8 *pu1Key, UINT16 u2KeyLen)
{
    BOOL fgRet;

    FUNC_ENTRY;

    _ApiLock();
    fgRet = _DMX_NAND_AES_INIT(pu1Key, u2KeyLen);
    _ApiUnlock();

    FUNC_EXIT;

    return fgRet;
}

BOOL DMX_NAND_AES_Encryption(UINT32 u4InBufStart, UINT32 u4OutBufStart, UINT32 u4BufSize)
{
    BOOL fgRet;

    FUNC_ENTRY;

    _ApiLock();
    fgRet = _DMX_NAND_AES_Encryption(u4InBufStart, u4OutBufStart, u4BufSize);
    _ApiUnlock();

    FUNC_EXIT;

    return fgRet;
}

BOOL DMX_NAND_AES_Decryption(UINT32 u4InBufStart, UINT32 u4OutBufStart, UINT32 u4BufSize)
{
    BOOL fgRet;

    FUNC_ENTRY;

    _ApiLock();
    fgRet = _DMX_NAND_AES_Decryption(u4InBufStart, u4OutBufStart, u4BufSize) ;
    _ApiUnlock();

    FUNC_EXIT;

    return fgRet;
}

BOOL DMX_SHA1_Manytimes(BOOL fgFirstPacket, BOOL fgLastPacket, UINT32 *u4BufStart,
									UINT32 u4BufSize, UINT8 *u1HashValue, UINT32 *u4HashValueSize)
{
    BOOL fgRet;

    FUNC_ENTRY;

    _ApiLock();
    fgRet = _DMX_SHA1_Manytimes(fgFirstPacket, fgLastPacket, u4BufStart, u4BufSize, u1HashValue, u4HashValueSize);
    _ApiUnlock();

    FUNC_EXIT;

    return fgRet;
}

BOOL DMX_SHA1_Onece(UINT32 *u4BufStart, UINT32 u4BufSize, UINT8 *u1HashValue, UINT32 *u4HashValueSize)
{
    BOOL fgRet;

    FUNC_ENTRY;

    _ApiLock();
    fgRet = _DMX_SHA1_Onece(u4BufStart, u4BufSize, u1HashValue, u4HashValueSize);
    _ApiUnlock();

    FUNC_EXIT;

    return fgRet;
}


BOOL DMX_Encrypt_Snapshot(UINT8 *u1HashValueIn, UINT32 u4HashValueSize, UINT8 *u1HashValueOut,
									UINT8 *u1AeskeyAddr, UINT32 *u4AeskeySize)
{
    BOOL fgRet;

    FUNC_ENTRY;

    _ApiLock();
    fgRet = _DMX_Encrypt_Snapshot(u1HashValueIn, u4HashValueSize, u1HashValueOut, u1AeskeyAddr, u4AeskeySize);
    _ApiUnlock();

    FUNC_EXIT;

    return fgRet;
}

BOOL DMX_Decrypt_Snapshot(UINT8 *u1HashValue_Encrypt, UINT32 u4HashValueSize, UINT8 *u1HashValue_Clear,
									UINT8 *u1AeskeyAddr, UINT32 u4AeskeySize)

{
    BOOL fgRet;

    FUNC_ENTRY;

    _ApiLock();
    fgRet = _DMX_Decrypt_Snapshot(u1HashValue_Encrypt, u4HashValueSize, u1HashValue_Clear, u1AeskeyAddr, u4AeskeySize);
    _ApiUnlock();

    FUNC_EXIT;

    return fgRet;
}

#ifndef CC_MTK_LOADER
#if 0
extern void readMMCblock(u32* buffer, u32 offset, u32 size);
extern void writeMMCblock(u8* buffer, u32 offset, u32 size);
#else
void readMMCblock(UINT32* buffer, UINT32 offset, UINT32 size) {}
void writeMMCblock(UINT8* buffer, UINT32 offset, UINT32 size) {}
#endif

int sign_snapshot(const char* blkdev, int size, unsigned int snapoffset)
{
    UINT8 u1HashValue[32], u1HashValueOut[32];
    UINT32 u4HashValueSize;
    UINT8 u1AesKey[16];
    UINT32 u4AesKeySize;
    UINT8* buffer;
    UINT32 bufsize=4096;
    UINT32 i;
    UINT32 u4Offset=0;
    UINT32 u4MidEnd;

    UINT32 u4ImageSize;

    x_memset(u1HashValueOut, 0x0, 32);
    x_memset(u1AesKey, 0x0, 16);

    u4ImageSize = size;
    LOG(0,"image size: 0x%x\n", u4ImageSize);
    u4MidEnd = u4Offset + u4ImageSize - bufsize;

    buffer = x_mem_alloc(bufsize);
    if(NULL == buffer)
    {
        LOG(0, "%s allocate buffer fail\n", __FUNCTION__);
        return -1;
    }
    LOG(0,"buffer address: 0x%x\n", buffer);

    // begin
    ASSERT((bufsize & (0x40-1)) == 0);
    readMMCblock((UINT32*)buffer, u4Offset, bufsize);
    DMX_SHA1_Manytimes(TRUE, FALSE, (UINT32*)buffer, bufsize, u1HashValue , &u4HashValueSize);
    u4Offset += bufsize;

    // middle
    while (u4Offset < u4MidEnd)
    {
        ASSERT((bufsize & (0x40-1)) == 0);
        readMMCblock((UINT32*)buffer, u4Offset, bufsize);
        DMX_SHA1_Manytimes(FALSE, FALSE, (UINT32*)buffer, bufsize, u1HashValue , &u4HashValueSize);
        u4Offset += bufsize;
        LOG(0,".");
    }

    // end
    ASSERT((bufsize & (0x40-1)) == 0);
    readMMCblock((UINT32*)buffer, u4Offset, bufsize);
    DMX_SHA1_Manytimes(FALSE, TRUE, (UINT32*)buffer, bufsize, u1HashValue , &u4HashValueSize);
    //u4Offset += bufsize;

    ASSERT(u4HashValueSize==20 || u4HashValueSize==32);

    //output result: u1HashValue[32], u4HashValueSize
    LOG(0,"(yjdbg) u4HashValueSize: %d\n", u4HashValueSize);
    for (i=0; i<u4HashValueSize; i++)
    {
        LOG(0,"%02x ", u1HashValue[i]);
    }
    LOG(0,"\n");

    DMX_Encrypt_Snapshot(u1HashValue, u4HashValueSize, u1HashValueOut, u1AesKey, &u4AesKeySize);
    LOG(0,"(yjdbg) u4AesKeySize: %d\n", u4AesKeySize);
    for (i=0; i<u4AesKeySize; i++)
    {
        LOG(0,"%02x ", u1AesKey[i]);
    }

#if 0 // verification
    cmpresult = DMX_Decrypt_Snapshot(u1HashValueOut, u4HashValueSize, u1HashValue, u1AesKey, u4AesKeySize);
    printf("1st cmpresult: %x\n", cmpresult);

    u1HashValue[0] = 0x12;
    cmpresult = DMX_Decrypt_Snapshot(u1HashValueOut, u4HashValueSize, u1HashValue, u1AesKey, u4AesKeySize);
    printf("2nd cmpresult: %x\n", cmpresult);
#endif

    x_memset(buffer, 0, bufsize);
    x_memcpy(buffer, u1AesKey, u4AesKeySize);
    x_memcpy(buffer+u4AesKeySize, u1HashValueOut, u4HashValueSize);

    writeMMCblock(buffer, snapoffset, bufsize);

    x_mem_free(buffer);

    return 0;
}
#endif
