/* 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.
 *
 *****************************************************************************/



#include <linux/module.h>
#include <linux/param.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/thread_info.h>
#include <linux/version.h>
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,26)
#include <linux/semaphore.h>
#else
#include <asm/semaphore.h>
#endif
#include "x_assert.h"
#include "x_os.h"


#define INVALID_OWNER ((struct thread_info *)(NULL))


typedef struct os_sema_light
{
    SEMA_TYPE_T e_type;
    struct semaphore sem;
    struct thread_info *owner;
    INT16 i2_selfcount;
} OS_SEMA_LIGHT_T;


INT32 x_sema_create (HANDLE_T*    ph_sema_hdl,
                     SEMA_TYPE_T  e_type,
                     UINT32       ui4_init_value)
{
    OS_SEMA_LIGHT_T *pt_sema;

    /* check arguments */
    if ((ph_sema_hdl == NULL) ||
        ((e_type != X_SEMA_TYPE_BINARY) && (e_type != X_SEMA_TYPE_MUTEX) &&
         (e_type != X_SEMA_TYPE_COUNTING)))
    {
        return OSR_INV_ARG;
    }

    if (((e_type == X_SEMA_TYPE_BINARY) || (e_type == X_SEMA_TYPE_MUTEX)) &&
         (ui4_init_value != X_SEMA_STATE_LOCK) &&
         (ui4_init_value != X_SEMA_STATE_UNLOCK))
    {
        return OSR_INV_ARG;
    }

    if ((e_type == X_SEMA_TYPE_COUNTING) &&
        (((INT32) ui4_init_value) < ((INT32) X_SEMA_STATE_LOCK)))
    {
        return OSR_INV_ARG;
    }

    pt_sema = kcalloc(1, sizeof(OS_SEMA_LIGHT_T), GFP_KERNEL);
    if (pt_sema == NULL)
    {
        return OSR_NO_RESOURCE;
    }
    //FILL_CALLER(pt_sema);

    pt_sema->e_type = e_type;
    pt_sema->owner = INVALID_OWNER;
    sema_init(&pt_sema->sem, ui4_init_value);

    if (e_type == X_SEMA_TYPE_MUTEX)
    {
        if (ui4_init_value == X_SEMA_STATE_LOCK)
        {
            pt_sema->owner = current_thread_info();
            pt_sema->i2_selfcount++;
        }
        else
        {
            pt_sema->owner = INVALID_OWNER;
            pt_sema->i2_selfcount = 0;
        }
    }

    *ph_sema_hdl = (HANDLE_T)(pt_sema);
    return OSR_OK;
}


INT32 x_sema_delete (HANDLE_T  h_sema_hdl)
{
    OS_SEMA_LIGHT_T *pt_sema = (OS_SEMA_LIGHT_T *)(h_sema_hdl);

    kfree(pt_sema);
    return OSR_OK;
}


INT32 x_sema_lock (HANDLE_T       h_sema_hdl,
                   SEMA_OPTION_T  e_option)
{
    OS_SEMA_LIGHT_T *pt_sema = (OS_SEMA_LIGHT_T *)(h_sema_hdl);

    if (e_option != X_SEMA_OPTION_WAIT && e_option != X_SEMA_OPTION_NOWAIT)
    {
        return OSR_INV_ARG;
    }

    if (pt_sema->e_type == X_SEMA_TYPE_MUTEX)
    {
        if (pt_sema->owner != current_thread_info())
        {
            if (e_option == X_SEMA_OPTION_NOWAIT)
            {
                if (down_trylock(&pt_sema->sem) != 0)
                {
                    return OSR_WOULD_BLOCK;
                }
            }
            else
            {
                down(&pt_sema->sem);
            }
            pt_sema->owner = current_thread_info();
        }
        pt_sema->i2_selfcount++;
        return OSR_OK;
    }
    else
    {
        if (e_option == X_SEMA_OPTION_NOWAIT)
        {
            if (down_trylock(&pt_sema->sem) != 0)
            {
                return OSR_WOULD_BLOCK;
            }
        }
        else
        {
            down(&pt_sema->sem);
        }
        pt_sema->owner = current_thread_info();

        return OSR_OK;
    }
}


INT32 x_sema_lock_timeout (HANDLE_T  h_sema_hdl,
                           UINT32    ui4_time)
{
    static const int quantum_ms = 1000 / HZ;
    OS_SEMA_LIGHT_T *pt_sema = (OS_SEMA_LIGHT_T *)(h_sema_hdl);
    int ret;

    if (ui4_time == 0)
    {
        INT32 i4 = x_sema_lock(h_sema_hdl, X_SEMA_OPTION_NOWAIT);
        return i4 != OSR_WOULD_BLOCK ? i4 : OSR_TIMEOUT;
    }

    if (pt_sema->e_type == X_SEMA_TYPE_MUTEX)
    {
        if (pt_sema->owner != current_thread_info())
        {
            ret = down_timeout(&pt_sema->sem, ui4_time / quantum_ms);
            if (ret != 0)
            {
                goto err;
            }
            pt_sema->owner = current_thread_info();
        }
        pt_sema->i2_selfcount++;
        return OSR_OK;
    }
    else
    {
        ret = down_timeout(&pt_sema->sem, ui4_time / quantum_ms);
        if (ret != 0)
        {
            goto err;
        }
        pt_sema->owner = current_thread_info();

        return OSR_OK;
    }

err:
    switch (ret)
    {
    case -ETIME:
        return OSR_TIMEOUT;

    default:
        return OSR_FAIL;
    }
}


INT32 x_sema_unlock (HANDLE_T  h_sema_hdl)
{
    OS_SEMA_LIGHT_T *pt_sema = (OS_SEMA_LIGHT_T *)(h_sema_hdl);

    if (pt_sema->e_type == X_SEMA_TYPE_MUTEX)
    {
        if (pt_sema->owner != current_thread_info())
        {
            return OSR_FAIL;
        }
        pt_sema->i2_selfcount--;
        if (pt_sema->i2_selfcount != 0)
        {
            return OSR_OK;
        }
        pt_sema->owner = INVALID_OWNER;

        up(&pt_sema->sem);
        return OSR_OK;
    }
    else
    {
        if (pt_sema->e_type == X_SEMA_TYPE_BINARY)
        {
            if (down_trylock(&pt_sema->sem))
            {
                // The trylock failed, we already got the lock. Don't need to do anything here.
            }
        }
        pt_sema->owner = INVALID_OWNER;
        up(&pt_sema->sem);
        return OSR_OK;
    }
}


INT32 os_sema_init (VOID)
{
    return OSR_OK;
}


INT32 os_cli_show_sema_all (INT32        i4_argc,
                            const CHAR   **pps_argv)
{
    return OSR_OK;
}


