#include <linux/module.h>
#include <linux/mm.h>
#include <linux/refcount.h>
#include <linux/scatterlist.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/platform_device.h>
#include <linux/list.h>

#include <media/v4l2-device.h>
#include <media/v4l2-ctrls.h>
#include <media/videobuf2-v4l2.h>
#include <media/videobuf2-memops.h>
#include <media/videobuf2-dma-sg.h>

#include "mtk_pq.h"

static struct list_head in_dma_node;
static struct list_head out_dma_node;
bool dma_buf_cus = true;

struct mtk_pq_dma_node {
	int counter; //Buf bind count
	struct dma_buf *dbuf;
	struct mtk_pq_dma_sg_buf *buf;
	struct list_head list;
};

struct mtk_pq_dma_sg_buf {
	struct device			*dev;
	void				*vaddr;
	struct page			**pages;
	struct frame_vector		*vec;
	int				offset;
	enum dma_data_direction		dma_dir;
	struct sg_table			sg_table;
	/*
	 * This will point to sg_table when used with the MMAP or USERPTR
	 * memory model, and to the dma_buf sglist when used with the
	 * DMABUF memory model.
	 */
	struct sg_table			*dma_sgt;
	size_t				size;
	unsigned int			num_pages;
	refcount_t			refcount;
	struct vb2_vmarea_handler	handler;

	struct dma_buf_attachment	*db_attach;

	struct vb2_buffer		*vb;
	int				attach_cnt; //Buf attach count
};

static void mtk_pq_dma_sg_put(void *buf_priv);

static int vb2_dma_sg_alloc_compacted(struct mtk_pq_dma_sg_buf *buf,
		gfp_t gfp_flags)
{
	unsigned int last_page = 0;
	unsigned long size = buf->size;

	while (size > 0) {
		struct page *pages;
		int order;
		int i;

		order = get_order(size);
		/* Don't over allocate*/
		if ((PAGE_SIZE << order) > size)
			order--;

		pages = NULL;
		while (!pages) {
			pages = alloc_pages(GFP_KERNEL | __GFP_ZERO |
					__GFP_NOWARN | gfp_flags, order);
			if (pages)
				break;

			if (order == 0) {
				while (last_page--)
					__free_page(buf->pages[last_page]);
				return -ENOMEM;
			}
			order--;
		}

		split_page(pages, order);
		for (i = 0; i < (1 << order); i++)
			buf->pages[last_page++] = &pages[i];

		size -= PAGE_SIZE << order;
	}

	return 0;
}

static int _mtk_pq_dma_sg_delete_dma_node(struct mtk_pq_dma_node *node)
{
	struct mtk_pq_dma_sg_buf *buf = NULL;
	struct sg_table *sgt = NULL;

	if (IS_ERR_OR_NULL(node)) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "Input invalid node.\n");
		return -EINVAL;
	}

	/* unmap */
	buf = node->buf;
	sgt = buf->dma_sgt;

	if (WARN_ON(!buf->db_attach)) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR,
				"trying to unpin a not attached buffer\n");
		return -EINVAL;
	}

	if (WARN_ON(!sgt)) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR,
				"dmabuf buffer is already unpinned\n");
		return -EINVAL;
	}

	if (buf->vaddr) {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 17, 0)
		struct iosys_map map = IOSYS_MAP_INIT_VADDR(buf->vaddr);
#else
		struct dma_buf_map map = DMA_BUF_MAP_INIT_VADDR(buf->vaddr);
#endif

		dma_buf_vunmap(buf->db_attach->dmabuf, &map);
		buf->vaddr = NULL;
	}

	dma_buf_unmap_attachment(buf->db_attach, sgt, buf->dma_dir);
	buf->dma_sgt = NULL;

	/* detach */
	dma_buf_detach(buf->db_attach->dmabuf, buf->db_attach);
	buf->db_attach = NULL;
	kfree(node->buf);
	node->buf = NULL;

	dma_buf_put(node->dbuf);

	list_del(&node->list);
	kfree(node);

	return 0;
}

static void *mtk_pq_dma_sg_alloc(struct vb2_buffer *vb, struct device *dev,
			      unsigned long size)
{
	struct mtk_pq_dma_sg_buf *buf;
	struct sg_table *sgt;
	int ret;
	int num_pages;

	if (WARN_ON(!dev) || WARN_ON(!size))
		return ERR_PTR(-EINVAL);

	buf = kzalloc(sizeof(*buf), GFP_KERNEL);
	if (!buf)
		return ERR_PTR(-ENOMEM);

	buf->vaddr = NULL;
	buf->dma_dir = vb->vb2_queue->dma_dir;
	buf->offset = 0;
	buf->size = size;
	/* size is already page aligned */
	buf->num_pages = size >> PAGE_SHIFT;
	buf->dma_sgt = &buf->sg_table;

	/*
	 * NOTE: dma-sg allocates memory using the page allocator directly, so
	 * there is no memory consistency guarantee, hence dma-sg ignores DMA
	 * attributes passed from the upper layer.
	 */
	buf->pages = kvmalloc_array(buf->num_pages, sizeof(struct page *),
				    GFP_KERNEL | __GFP_ZERO);
	if (!buf->pages)
		goto fail_pages_array_alloc;

	ret = vb2_dma_sg_alloc_compacted(buf, vb->vb2_queue->gfp_flags);
	if (ret)
		goto fail_pages_alloc;

	ret = sg_alloc_table_from_pages(buf->dma_sgt, buf->pages,
			buf->num_pages, 0, size, GFP_KERNEL);
	if (ret)
		goto fail_table_alloc;

	/* Prevent the device from being released while the buffer is used */
	buf->dev = get_device(dev);

	sgt = &buf->sg_table;
	/*
	 * No need to sync to the device, this will happen later when the
	 * prepare() memop is called.
	 */
	if (dma_map_sgtable(buf->dev, sgt, buf->dma_dir,
			    DMA_ATTR_SKIP_CPU_SYNC))
		goto fail_map;

	buf->handler.refcount = &buf->refcount;
	buf->handler.put = mtk_pq_dma_sg_put;
	buf->handler.arg = buf;
	buf->vb = vb;

	refcount_set(&buf->refcount, 1);

	return buf;

fail_map:
	put_device(buf->dev);
	sg_free_table(buf->dma_sgt);
fail_table_alloc:
	num_pages = buf->num_pages;
	while (num_pages--)
		__free_page(buf->pages[num_pages]);
fail_pages_alloc:
	kvfree(buf->pages);
fail_pages_array_alloc:
	kfree(buf);
	return ERR_PTR(-ENOMEM);
}

static void mtk_pq_dma_sg_put(void *buf_priv)
{
	struct mtk_pq_dma_sg_buf *buf = NULL;
	struct sg_table *sgt = NULL;
	int i;

	if (IS_ERR_OR_NULL(buf_priv)) {
		pr_err("No memory to map\n");
		return;
	}
	buf = (struct mtk_pq_dma_sg_buf *)buf_priv;

	i = buf->num_pages;
	sgt = &buf->sg_table;

	if (refcount_dec_and_test(&buf->refcount)) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_DBG, "Freeing buffer of %d pages\n", buf->num_pages);
		dma_unmap_sgtable(buf->dev, sgt, buf->dma_dir,
				  DMA_ATTR_SKIP_CPU_SYNC);
		if (buf->vaddr)
			vm_unmap_ram(buf->vaddr, buf->num_pages);
		sg_free_table(buf->dma_sgt);
		while (--i >= 0)
			__free_page(buf->pages[i]);
		kvfree(buf->pages);
		put_device(buf->dev);
		kfree(buf);
	}
}

static void mtk_pq_dma_sg_prepare(void *buf_priv)
{
	struct mtk_pq_dma_sg_buf *buf = NULL;
	struct sg_table *sgt = NULL;

	if (IS_ERR_OR_NULL(buf_priv)) {
		pr_err("No memory to map\n");
		return;
	}
	buf = (struct mtk_pq_dma_sg_buf *)buf_priv;

	if (IS_ERR_OR_NULL(buf->dma_sgt)) {
		pr_err("buf->dma_sgt is invalid pointer\n");
		return;
	}
	sgt = buf->dma_sgt;

	if (IS_ERR_OR_NULL(buf->dev)) {
		pr_err("buf->dev is invalid pointer\n");
		return;
	}

	dma_sync_sgtable_for_device(buf->dev, sgt, buf->dma_dir);
}

static void mtk_pq_dma_sg_finish(void *buf_priv)
{
	struct mtk_pq_dma_sg_buf *buf = NULL;
	struct sg_table *sgt = NULL;

	if (IS_ERR_OR_NULL(buf_priv)) {
		pr_err("No memory to map\n");
		return;
	}
	buf = (struct mtk_pq_dma_sg_buf *)buf_priv;

	if (IS_ERR_OR_NULL(buf->dma_sgt)) {
		pr_err("buf->dma_sgt is invalid pointer\n");
		return;
	}
	sgt = buf->dma_sgt;

	if (IS_ERR_OR_NULL(buf->dev)) {
		pr_err("buf->dev is invalid pointer\n");
		return;
	}

	dma_sync_sgtable_for_cpu(buf->dev, sgt, buf->dma_dir);
}

static void *mtk_pq_dma_sg_get_userptr(struct vb2_buffer *vb, struct device *dev,
				    unsigned long vaddr, unsigned long size)
{
	struct mtk_pq_dma_sg_buf *buf;
	struct sg_table *sgt;
	struct frame_vector *vec;

	if (WARN_ON(!dev))
		return ERR_PTR(-EINVAL);

	buf = kzalloc(sizeof(*buf), GFP_KERNEL);
	if (!buf)
		return ERR_PTR(-ENOMEM);

	buf->vaddr = NULL;
	buf->dev = dev;
	buf->dma_dir = vb->vb2_queue->dma_dir;
	buf->offset = vaddr & ~PAGE_MASK;
	buf->size = size;
	buf->dma_sgt = &buf->sg_table;
	buf->vb = vb;
#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 6, 0)
	vec = vb2_create_framevec(vaddr, size);
#else
	vec = vb2_create_framevec(vaddr, size,
				buf->dma_dir == DMA_FROM_DEVICE ||
				buf->dma_dir == DMA_BIDIRECTIONAL);
#endif
	if (IS_ERR(vec))
		goto userptr_fail_pfnvec;
	buf->vec = vec;

	buf->pages = frame_vector_pages(vec);
	if (IS_ERR(buf->pages))
		goto userptr_fail_sgtable;
	buf->num_pages = frame_vector_count(vec);

	if (sg_alloc_table_from_pages(buf->dma_sgt, buf->pages,
			buf->num_pages, buf->offset, size, 0))
		goto userptr_fail_sgtable;

	sgt = &buf->sg_table;
	/*
	 * No need to sync to the device, this will happen later when the
	 * prepare() memop is called.
	 */
	if (dma_map_sgtable(buf->dev, sgt, buf->dma_dir,
			    DMA_ATTR_SKIP_CPU_SYNC))
		goto userptr_fail_map;

	return buf;

userptr_fail_map:
	sg_free_table(&buf->sg_table);
userptr_fail_sgtable:
	vb2_destroy_framevec(vec);
userptr_fail_pfnvec:
	kfree(buf);
	return ERR_PTR(-ENOMEM);
}

/*
 * @put_userptr: inform the allocator that a USERPTR buffer will no longer
 *		 be used
 */
static void mtk_pq_dma_sg_put_userptr(void *buf_priv)
{
	struct mtk_pq_dma_sg_buf *buf = NULL;
	struct sg_table *sgt = NULL;
	int i = 0;

	if (IS_ERR_OR_NULL(buf_priv)) {
		pr_err("No memory to map\n");
		return;
	}
	buf = (struct mtk_pq_dma_sg_buf *)buf_priv;

	sgt = &buf->sg_table;
	i = buf->num_pages;

	STI_PQ_LOG(STI_PQ_LOG_LEVEL_DBG, "Releasing userspace buffer of %d pages\n",
	       buf->num_pages);
	dma_unmap_sgtable(buf->dev, sgt, buf->dma_dir, DMA_ATTR_SKIP_CPU_SYNC);
	if (buf->vaddr)
		vm_unmap_ram(buf->vaddr, buf->num_pages);
	sg_free_table(buf->dma_sgt);
	if (buf->dma_dir == DMA_FROM_DEVICE ||
	    buf->dma_dir == DMA_BIDIRECTIONAL)
		while (--i >= 0)
			set_page_dirty_lock(buf->pages[i]);
	vb2_destroy_framevec(buf->vec);
	kfree(buf);
}

static void *mtk_pq_dma_sg_vaddr(struct vb2_buffer *vb, void *buf_priv)
{
	struct mtk_pq_dma_sg_buf *buf = NULL;
	int ret;

	if (IS_ERR_OR_NULL(buf_priv)) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "No memory to map\n");
		return NULL;
	}
	buf = (struct mtk_pq_dma_sg_buf *)buf_priv;

	if (!buf->vaddr) {
		if (!IS_ERR_OR_NULL(buf->db_attach)
				&& !IS_ERR_OR_NULL(buf->db_attach->dmabuf)) {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 17, 0)
			struct iosys_map map = IOSYS_MAP_INIT_VADDR(buf->vaddr);
#else
			struct dma_buf_map map = DMA_BUF_MAP_INIT_VADDR(buf->vaddr);
#endif
			ret = dma_buf_vmap(buf->db_attach->dmabuf, &map);
			buf->vaddr = ret ? NULL : map.vaddr;
		} else {
			if (!IS_ERR_OR_NULL(buf->pages)) {
				buf->vaddr = vm_map_ram(buf->pages,
					buf->num_pages, -1);
			}
		}
	}

	/* add offset in case userptr is not page-aligned */
	return buf->vaddr ? buf->vaddr + buf->offset : NULL;
}

static unsigned int mtk_pq_dma_sg_num_users(void *buf_priv)
{
	struct mtk_pq_dma_sg_buf *buf = NULL;

	if (IS_ERR_OR_NULL(buf_priv)) {
		pr_err("No memory to map\n");
		return -EINVAL;
	}
	buf = (struct mtk_pq_dma_sg_buf *)buf_priv;

	return refcount_read(&buf->refcount);
}

static int mtk_pq_dma_sg_mmap(void *buf_priv, struct vm_area_struct *vma)
{
	struct mtk_pq_dma_sg_buf *buf = NULL;
	int err;

	if (IS_ERR_OR_NULL(buf_priv)) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "No memory to map\n");
		return -EINVAL;
	}
	buf = (struct mtk_pq_dma_sg_buf *)buf_priv;

	err = vm_map_pages(vma, buf->pages, buf->num_pages);
	if (err) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "Remapping memory, error: %d\n", err);
		return err;
	}

	/*
	 * Use common vm_area operations to track buffer refcount.
	 */
	vma->vm_private_data	= &buf->handler;
	vma->vm_ops		= &vb2_common_vm_ops;

	vma->vm_ops->open(vma);

	return 0;
}

/*********************************************/
/*       callbacks for DMABUF buffers        */
/*********************************************/

static int mtk_pq_dma_sg_map_dmabuf(void *mem_priv)
{
	struct mtk_pq_dma_sg_buf *buf = NULL;
	struct sg_table *sgt;

	if (IS_ERR_OR_NULL(mem_priv)) {
		pr_err("No memory to map\n");
		return -EINVAL;
	}
	buf = (struct mtk_pq_dma_sg_buf *)mem_priv;

	if (dma_buf_cus == true)
		return 0;

	if (WARN_ON(!buf->db_attach)) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "trying to pin a non attached buffer\n");
		return -EINVAL;
	}

	if (WARN_ON(buf->dma_sgt)) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "dmabuf buffer is already pinned\n");
		return 0;
	}

	/* get the associated scatterlist for this buffer */
	sgt = dma_buf_map_attachment(buf->db_attach, buf->dma_dir);
	if (IS_ERR(sgt)) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "Error getting dmabuf scatterlist\n");
		return -EINVAL;
	}

	buf->dma_sgt = sgt;
	buf->vaddr = NULL;

	return 0;
}

static void mtk_pq_dma_sg_unmap_dmabuf(void *mem_priv)
{
	struct mtk_pq_dma_sg_buf *buf = NULL;
	struct sg_table *sgt;

	if (IS_ERR_OR_NULL(mem_priv)) {
		pr_err("No memory to map\n");
		return;
	}
	buf = (struct mtk_pq_dma_sg_buf *)mem_priv;

	if (dma_buf_cus == true)
		return;

	if (WARN_ON(!buf->db_attach)) {
		pr_err("trying to unpin a not attached buffer\n");
		return;
	}

	sgt = buf->dma_sgt;
	if (WARN_ON(!sgt)) {
		pr_err("dmabuf buffer is already unpinned\n");
		return;
	}

	if (buf->vaddr) {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 17, 0)
		struct iosys_map map = IOSYS_MAP_INIT_VADDR(buf->vaddr);
#else
		struct dma_buf_map map = DMA_BUF_MAP_INIT_VADDR(buf->vaddr);
#endif
		dma_buf_vunmap(buf->db_attach->dmabuf, &map);
		buf->vaddr = NULL;
	}
	dma_buf_unmap_attachment(buf->db_attach, sgt, buf->dma_dir);

	buf->dma_sgt = NULL;
}

static void mtk_pq_dma_sg_detach_dmabuf(void *mem_priv)
{
	struct mtk_pq_dma_sg_buf *buf = NULL;

	if (IS_ERR_OR_NULL(mem_priv)) {
		pr_err("No memory to map\n");
		return;
	}
	buf = (struct mtk_pq_dma_sg_buf *)mem_priv;

	if (dma_buf_cus == true) {
		int ret = 0;
		struct mtk_pq_platform_device *pdev = NULL;
		struct list_head *np, *n, *dma_list;
		struct mutex *dma_mutex = NULL;
		struct mtk_pq_dma_node *node = NULL;

		if (IS_ERR_OR_NULL(buf->dev)) {
			STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "Invalid pointer buf->dev.\n");
			return;
		}
		pdev = dev_get_drvdata(buf->dev);
		if (pdev == NULL) {
			STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "device is not available\n");
			return;
		}

		buf->attach_cnt--;

		if (buf->dma_dir == DMA_TO_DEVICE) {
			dma_list = &in_dma_node;
			dma_mutex = &pdev->mutex_in_dma_list;
		} else {
			dma_list = &out_dma_node;
			dma_mutex = &pdev->mutex_out_dma_list;
		}

		mutex_lock(dma_mutex);
		list_for_each_safe(np, n, dma_list) {
			node = list_entry(np, struct mtk_pq_dma_node, list);
			if (node && ((uint64_t)node->buf == (uint64_t)buf)) {
				if ((node->counter <= 0) && (buf->attach_cnt <= 0)) {
					STI_PQ_LOG(STI_PQ_LOG_LEVEL_DMA,
						"%s dbuf= %llx\n",
						"Detach unbinded buffer, delete node now!",
						(unsigned long long)node->dbuf);
					ret = _mtk_pq_dma_sg_delete_dma_node(node);
					if (ret) {
						STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR,
							"delete dma node failed, ret=%d\n", ret);
						mutex_unlock(dma_mutex);
						return;
					}
				}
				break;
			}
		}

		mutex_unlock(dma_mutex);
		return;
	}

	/* if vb2 works correctly you should never detach mapped buffer */
	if (WARN_ON(buf->dma_sgt))
		mtk_pq_dma_sg_unmap_dmabuf(buf);

	/* detach this attachment */
	dma_buf_detach(buf->db_attach->dmabuf, buf->db_attach);
	kfree(buf);
}

static void *mtk_pq_dma_sg_attach_dmabuf(struct vb2_buffer *vb, struct device *dev,
				      struct dma_buf *dbuf, unsigned long size)
{
	struct mtk_pq_dma_sg_buf *buf;
	struct mtk_pq_dma_node *node;
	struct dma_buf_attachment *dba;
	struct list_head *np, *n, *dma_list;
	struct mtk_pq_platform_device *pdev = NULL;
	struct mutex *dma_mutex = NULL;
	void *ret = NULL;

	if (WARN_ON(!dev))
		return ERR_PTR(-EINVAL);

	if (dbuf->size < size)
		return ERR_PTR(-EFAULT);

	if (dma_buf_cus == true) {
		pdev = dev_get_drvdata(dev);

		if (pdev == NULL) {
			STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "device is not available\n");
			return ERR_PTR(-EINVAL);
		}

		if (vb->vb2_queue->dma_dir == DMA_TO_DEVICE) {
			dma_list = &in_dma_node;
			dma_mutex = &pdev->mutex_in_dma_list;
		} else {
			dma_list = &out_dma_node;
			dma_mutex = &pdev->mutex_out_dma_list;
		}

		STI_PQ_LOG(STI_PQ_LOG_LEVEL_DMA, "search dbuf = %llx\n", (unsigned long long)dbuf);

		mutex_lock(dma_mutex);
		list_for_each_safe(np, n, dma_list) {
			node = list_entry(np, struct mtk_pq_dma_node, list);
			if (node && ((uint64_t)node->dbuf == (uint64_t)dbuf)) {
				mutex_unlock(dma_mutex);
				node->buf->attach_cnt++;
				return (void *)node->buf;
			}
		}
		mutex_unlock(dma_mutex);

		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "buffer has not binded yet\n");
		ret = ERR_PTR(-EFAULT);
	} else {
		buf = kzalloc(sizeof(*buf), GFP_KERNEL);
		if (!buf)
			return ERR_PTR(-ENOMEM);

		buf->dev = dev;
		/* create attachment for the dmabuf with the user device */
		dba = dma_buf_attach(dbuf, buf->dev);
		if (IS_ERR(dba)) {
			pr_err("failed to attach dmabuf\n");
			kfree(buf);
			return dba;
		}

		buf->dma_dir = vb->vb2_queue->dma_dir;
		buf->size = size;
		buf->db_attach = dba;
		buf->vb = vb;

		ret = buf;
	}

	return ret;
}

static void *mtk_pq_dma_sg_cookie(struct vb2_buffer *vb, void *buf_priv)
{
	struct mtk_pq_dma_sg_buf *buf = NULL;

	if (IS_ERR_OR_NULL(buf_priv)) {
		pr_err("No memory to map\n");
		return NULL;
	}
	buf = (struct mtk_pq_dma_sg_buf *)buf_priv;

	if (IS_ERR_OR_NULL(buf->dma_sgt)) {
		pr_err("No memory to map\n");
		return NULL;
	}
	return buf->dma_sgt;
}

const struct vb2_mem_ops mtk_pq_dma_sg_memops = {
	.alloc		= mtk_pq_dma_sg_alloc,
	.put		= mtk_pq_dma_sg_put,
	.get_userptr	= mtk_pq_dma_sg_get_userptr,
	.put_userptr	= mtk_pq_dma_sg_put_userptr,
	.prepare	= mtk_pq_dma_sg_prepare,
	.finish		= mtk_pq_dma_sg_finish,
	.vaddr		= mtk_pq_dma_sg_vaddr,
	.mmap		= mtk_pq_dma_sg_mmap,
	.num_users	= mtk_pq_dma_sg_num_users,
	//.get_dmabuf	= mtk_pq_dma_sg_get_dmabuf, //pqdd doesn't support expdma
	.map_dmabuf	= mtk_pq_dma_sg_map_dmabuf,
	.unmap_dmabuf	= mtk_pq_dma_sg_unmap_dmabuf,
	.attach_dmabuf	= mtk_pq_dma_sg_attach_dmabuf,
	.detach_dmabuf	= mtk_pq_dma_sg_detach_dmabuf,
	.cookie		= mtk_pq_dma_sg_cookie,
};

int mtk_pq_dma_list_init(struct mtk_pq_platform_device *pdev)
{
	if (pdev == NULL) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "pdev is NULL\n");
		return -EINVAL;
	}

	INIT_LIST_HEAD(&in_dma_node);
	INIT_LIST_HEAD(&out_dma_node);

	mutex_init(&pdev->mutex_in_dma_list);
	mutex_init(&pdev->mutex_out_dma_list);

	return 0;
}

int mtk_pq_dma_bind(struct mtk_pq_platform_device *pdev, int type, int fd)
{
	struct list_head *np, *n, *dma_list;
	struct dma_buf *dbuf, *tmp_dbuf;
	struct mtk_pq_dma_sg_buf *buf;
	struct mtk_pq_dma_node *node;
	struct dma_buf_attachment *dba;
	struct sg_table *sgt;
	enum dma_data_direction dma_dir;
	struct mutex *dma_mutex;
	bool find = false;

	if (pdev == NULL) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "pdev is NULL\n");
		return -EINVAL;
	}

	if (dma_buf_cus == false)
		return 0;

	if (V4L2_TYPE_IS_OUTPUT(type)) {
		dma_dir = DMA_TO_DEVICE;
		dma_list = &in_dma_node;
		dma_mutex = &pdev->mutex_in_dma_list;
	} else {
		dma_dir = DMA_FROM_DEVICE;
		dma_list = &out_dma_node;
		dma_mutex = &pdev->mutex_out_dma_list;
	}

	tmp_dbuf = dma_buf_get(fd);
	if (IS_ERR_OR_NULL(tmp_dbuf)) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "Invalid dmabuf fd : %d\n", fd);
		return -EINVAL;
	}

	mutex_lock(dma_mutex);

	list_for_each_safe(np, n, dma_list) {
		node = list_entry(np, struct mtk_pq_dma_node, list);
		if (node && node->dbuf == tmp_dbuf) {
			find = true;
			node->counter += 1;
			break;
		}
	}

	if (find == false) {
		dbuf = dma_buf_get(fd);

		node = kzalloc(sizeof(*node), GFP_KERNEL);
		if (!node) {
			mutex_unlock(dma_mutex);
			dma_buf_put(tmp_dbuf);
			dma_buf_put(dbuf);
			return -ENOMEM;
		}

		buf = kzalloc(sizeof(*buf), GFP_KERNEL);
		if (!buf) {
			kfree(node);
			mutex_unlock(dma_mutex);
			dma_buf_put(tmp_dbuf);
			dma_buf_put(dbuf);
			return -ENOMEM;
		}

		memset(node, 0, sizeof(*node));
		memset(buf, 0, sizeof(*buf));

		buf->dev = pdev->dev;
		/* create attachment for the dmabuf with the user device */
		dba = dma_buf_attach(dbuf, buf->dev);
		if (IS_ERR(dba)) {
			STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "failed to attach dmabuf\n");
			kfree(buf);
			kfree(node);
			mutex_unlock(dma_mutex);
			dma_buf_put(tmp_dbuf);
			dma_buf_put(dbuf);
			return -EINVAL;
		}

		/* get the associated scatterlist for this buffer */
		sgt = dma_buf_map_attachment(dba, dma_dir);
		if (IS_ERR(sgt)) {
			STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "Error getting dmabuf scatterlist\n");
			kfree(buf);
			kfree(node);
			mutex_unlock(dma_mutex);
			dma_buf_put(tmp_dbuf);
			dma_buf_put(dbuf);
			return -EINVAL;
		}

		buf->dma_dir = dma_dir;
		buf->size = dbuf->size;
		buf->db_attach = dba;
		buf->dma_sgt = sgt;
		buf->vaddr = NULL;
		buf->attach_cnt = 0;

		node->dbuf = dbuf;
		node->buf = buf;
		node->counter = 1;

		list_add_tail(&node->list, dma_list);
	}

	mutex_unlock(dma_mutex);

	STI_PQ_LOG(STI_PQ_LOG_LEVEL_DMA, "type = %d, fd = %d, dbuf = %llx, counter = %d\n",
			type, fd, (unsigned long long)tmp_dbuf, node->counter);

	dma_buf_put(tmp_dbuf);

	return 0;
}

int mtk_pq_dma_unbind(struct mtk_pq_platform_device *pdev, int type, int fd)
{
	int ret = 0;
	struct list_head *np, *n, *dma_list;
	struct mtk_pq_dma_node *node = NULL;
	struct dma_buf *tmp_dbuf = NULL;
	struct mutex *dma_mutex = NULL;

	if (pdev == NULL) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "pq_dev is NULL\n");
		return -EINVAL;
	}

	if (dma_buf_cus == false)
		return 0;

	if (V4L2_TYPE_IS_OUTPUT(type)) {
		dma_list = &in_dma_node;
		dma_mutex = &pdev->mutex_in_dma_list;
	} else {
		dma_list = &out_dma_node;
		dma_mutex = &pdev->mutex_out_dma_list;
	}

	tmp_dbuf = dma_buf_get(fd);
	if (IS_ERR_OR_NULL(tmp_dbuf)) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "Type = %d, Invalid fd : %d\n", type, fd);
		return -EINVAL;
	}

	STI_PQ_LOG(STI_PQ_LOG_LEVEL_DMA,
			"unbind type = %d, fd = %d, dbuf = %llx\n",
			type, fd, (unsigned long long)tmp_dbuf);

	mutex_lock(dma_mutex);
	list_for_each_safe(np, n, dma_list) {
		node = list_entry(np, struct mtk_pq_dma_node, list);
		if (node && (node->dbuf == tmp_dbuf)) {
			STI_PQ_LOG(STI_PQ_LOG_LEVEL_DMA,
				"unbind type = %d, fd = %d, dbuf = %llx, counter = %d\n",
				type, fd, (unsigned long long)tmp_dbuf, node->counter);

			node->counter -= 1;
			if (node->counter <= 0) {
				/* If buffer not detached yet, will delete node while detach.*/
				if (node->buf->attach_cnt > 0) {
					STI_PQ_LOG(STI_PQ_LOG_LEVEL_DMA,
						"%s attach_cnt=%u\n",
						"Buffer not detached yet, delete node later.",
						node->buf->attach_cnt);
					break;
				}

				ret = _mtk_pq_dma_sg_delete_dma_node(node);
				if (ret) {
					STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR,
						"_mtk_pq_dma_sg_delete_dma_node failed, ret=%d\n",
						ret);
					mutex_unlock(dma_mutex);
					dma_buf_put(tmp_dbuf);
					return ret;
				}
			}
			break;
		}
	}
	mutex_unlock(dma_mutex);

	dma_buf_put(tmp_dbuf);

	return 0;
}

void mtk_pq_dma_sg_set_dbg(bool val)
{
	dma_buf_cus = val;
}

bool mtk_pq_dma_sg_get_dbg(void)
{
	return dma_buf_cus;
}

void mtk_pq_dma_list_print(struct mtk_pq_platform_device *pdev)
{
	struct list_head *np, *n;
	struct mtk_pq_dma_node *node;

	if (pdev == NULL) {
		STI_PQ_LOG(STI_PQ_LOG_LEVEL_ERROR, "device is not available\n");
		return;
	}

	mutex_lock(&pdev->mutex_in_dma_list);

	if (list_empty(&in_dma_node))
		pr_err("Input dmabuf list is empty\n");

	list_for_each_safe(np, n, &in_dma_node) {
		node = list_entry(np, struct mtk_pq_dma_node, list);
		if (node)
			pr_err("Input dma buf = %llx, counter = %d\n",
					(unsigned long long)node->dbuf, node->counter);
	}

	mutex_unlock(&pdev->mutex_in_dma_list);

	mutex_lock(&pdev->mutex_out_dma_list);

	if (list_empty(&out_dma_node))
		pr_err("Output dmabuf list is empty\n");

	list_for_each_safe(np, n, &out_dma_node) {
		node = list_entry(np, struct mtk_pq_dma_node, list);
		if (node)
			pr_err("Output dma buf = %llx, counter = %d\n",
					(unsigned long long)node->dbuf, node->counter);
	}

	mutex_unlock(&pdev->mutex_out_dma_list);
}
