/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
/*
 * Copyright (c) 2020 MediaTek Inc.
 */
#ifndef _MTK_TV_DRM_COMMON_H_
#define _MTK_TV_DRM_COMMON_H_

#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/component.h>
#include <drm/mtk_tv_drm.h>
#include <drm/drm_print.h>
#include <linux/videodev2.h>
#include <linux/slab.h>
#include <linux/dma-buf.h>
#include <uapi/linux/metadata_utility/m_render.h>
#include <uapi/linux/metadata_utility/m_pq.h>

#include "mtk_iommu_dtv_api.h"
#include "metadata_utility.h"
#include "mtk_tv_drm_crtc.h"


/* define */
#define SYS_DEVICE_SIZE (65535)

#define ALIGN_UPTO_X(w, x)      (div_u64(((uint64_t)(w) + (x - 1)), x) * x)
#define ALIGN_DOWNTO_X(w, x)    (div_u64((uint64_t)w, x) * x)

#define MASK_8BITS  (0xFF)
#define MASK_10BITS (0x3FF)
#define MAX_8BITS   (0xFF)
#define MAX_10BITS  (0x3FF)

#define DIGIT_8   (8)
#define DIGIT_10  (10)

#define INTERPOLATE(src_max, src_min, src_val, dst_max, dst_min) ({		\
	uint64_t src_base = (src_max)-(src_min);				\
	uint64_t dst_base = (dst_max)-(dst_min);				\
	uint64_t src_diff = (src_val)-(src_min);				\
	uint64_t dst_val = (src_diff * dst_base / src_base) + (dst_min);	\
	dst_val; })

/* memory alloc */
#define MALLOC(size)	({ uint32_t __sz = size; \
			((__sz >= PAGE_SIZE) ? vmalloc(__sz) : kmalloc(__sz, GFP_KERNEL)); })

#define ZALLOC(size)	({ uint32_t __sz = size; \
			((__sz >= PAGE_SIZE) ? vzalloc(__sz) : kzalloc(__sz, GFP_KERNEL)); })

#define FREE(ptr)	kvfree(ptr) // kvfree include @is_vmalloc_addr inside.

/* enum */
enum mtk_render_common_metatag {
	RENDER_METATAG_FRAME_INFO = 0,
	RENDER_METATAG_SVP_INFO,
	RENDER_METATAG_FRAMESYNC_INFO,
	RENDER_METATAG_IDR_CTRL_INFO,
	RENDER_METATAG_DV_OUTPUT_FRAME_INFO,
	RENDER_METATAG_PQDD_DISPLAY_INFO,
	RENDER_METATAG_PQDD_OUTPUT_FRAME_INFO,
	RENDER_METATAG_PQU_DISPLAY_INFO,
	RENDER_METATAG_META_PQ_OUTPUT_RENDER_INFO_TAG,
	RENDER_METATAG_MAX,
};

enum mtk_render_common_chip_series {
	CHIP_SERIES_MAIN_TS = 1,
	CHIP_SERIES_LEGACY,
	CHIP_SERIES_MAX,
};

/* function*/
int mtk_render_common_read_metadata(struct dma_buf *meta_db,
	enum mtk_render_common_metatag meta_tag, void *meta_content);
int mtk_render_common_write_metadata(struct dma_buf *meta_db,
	enum mtk_render_common_metatag meta_tag, void *meta_content);
int mtk_render_common_delete_metadata(struct dma_buf *meta_db,
	enum mtk_render_common_metatag meta_tag);
int mtk_render_common_set_stub_mode(struct mtk_tv_drm_crtc *crtc,
	struct drm_mtk_tv_common_stub *stubInfo);
int mtk_render_common_parser_cmd_int(const char *cmd,
	char *key, uint64_t *val);
void *mtk_render_common_ioremap(uint64_t phy, uint64_t size);
void mtk_render_common_iounmap(void *addr);
size_t mtk_render_common_pa2va(uint64_t phy_addr, uint32_t len, bool *remap);

#endif
