/*
* @file hv_drv_UsbPortingOsLinuxApi.h
* @brief Header file of usb adapting to os about linux api.
*
* @author HiView SoC Software Team
* @version 1.0.0
* @date 2022-06-15
*/

#ifndef __HV_DRV_USB_PORTING_OS_LINUX_API_H
#define __HV_DRV_USB_PORTING_OS_LINUX_API_H

#include "hv_drv_UsbPortingTypes.h"
#include "portmacro.h"
#include "FreeRTOS.h"
#include "semphr.h"

#include "hv_comm_Timer.h"
#include "hv_comm_Assert.h"

typedef struct {
    int counter;
} atomic_t;

INLINE void atomic_inc(volatile atomic_t *v) {
    v->counter += 1;
}

INLINE void atomic_dec(volatile atomic_t *v) {
    if (v->counter == 0)
        return;

    v->counter -= 1;
}

INLINE void atomic_set(volatile atomic_t *v, int count) {
    v->counter = (count > 0 ? count : 0);
}

#define atomic_read(v)  ((v)->counter)

typedef void (*timer_fn_t) (unsigned long);

struct timer_list {
    u32 timer_id;
    timer_fn_t func;
    unsigned long data;
    unsigned period;
    u8  periodic:1;
    u8  active:1;
};

typedef struct _completion completion;
struct _completion {
    volatile boolean completed;
    volatile boolean isr_caller;
    SemaphoreHandle_t  semaphore;
};

INLINE void init_completion(completion *done) {
    done->semaphore = USB_SEMA_INIT(1, 0);
    done->completed = 0;
}

INLINE boolean wait_for_completion_timeout(completion *done, int timeout) {
    boolean ret = 0;

    if (USB_SEMA_TAKE(done->semaphore, 0xffffffffUL) == pdHV_TRUE) {
        ret = 0;
    } else {
        ret = 1;
    }
    return ret;
}

INLINE boolean completion_done(completion *done) {
    return done->completed;
}

INLINE void completion_complete(completion *done) {
    BaseType_t pxHigherPriorityTaskWoken = pdHV_TRUE;
    USB_SEMA_GIVE_FROM_ISR(done->semaphore, &pxHigherPriorityTaskWoken);
}

INLINE void destroy_complete(completion *done) {
    USB_SEMA_FINI(done->semaphore);
}


#endif
